hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
11 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
251
max_stars_repo_name
stringlengths
4
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
251
max_issues_repo_name
stringlengths
4
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
251
max_forks_repo_name
stringlengths
4
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.05M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.04M
alphanum_fraction
float64
0
1
86bcd2890d4f11513d628469a8efe8d1af2d7195
65
py
Python
src/cicd_sim/artifact/__init__.py
Software-Natives-OSS/cicd_sim
19452a5b06a6c6d99322c9b6777c501025e954f1
[ "MIT" ]
null
null
null
src/cicd_sim/artifact/__init__.py
Software-Natives-OSS/cicd_sim
19452a5b06a6c6d99322c9b6777c501025e954f1
[ "MIT" ]
8
2020-03-12T05:51:56.000Z
2020-03-15T17:31:12.000Z
src/cicd_sim/artifact/__init__.py
Software-Natives-OSS/cicd_sim
19452a5b06a6c6d99322c9b6777c501025e954f1
[ "MIT" ]
null
null
null
from . artifactory import Artifactory __all__ = ['Artifactory']
16.25
37
0.769231
86bd70e7874de4b570ed32325f28d65eaa058486
4,544
py
Python
mandoline/line_segment3d.py
Spiritdude/mandoline-py
702cd1f9264c7d5d814600ff919406387fd86185
[ "BSD-2-Clause" ]
5
2021-09-16T10:41:44.000Z
2021-11-04T14:45:24.000Z
mandoline/line_segment3d.py
Spiritdude/mandoline-py
702cd1f9264c7d5d814600ff919406387fd86185
[ "BSD-2-Clause" ]
null
null
null
mandoline/line_segment3d.py
Spiritdude/mandoline-py
702cd1f9264c7d5d814600ff919406387fd86185
[ "BSD-2-Clause" ]
null
null
null
# vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap
28.223602
79
0.53015
86bd7ed417f64120a297b91ba487086bf72ccb3f
2,328
py
Python
cacheable/adapter/PeeweeAdapter.py
d1hotpep/cacheable
9ea97d6504965179f8fe495b67e466c068719445
[ "MIT" ]
null
null
null
cacheable/adapter/PeeweeAdapter.py
d1hotpep/cacheable
9ea97d6504965179f8fe495b67e466c068719445
[ "MIT" ]
null
null
null
cacheable/adapter/PeeweeAdapter.py
d1hotpep/cacheable
9ea97d6504965179f8fe495b67e466c068719445
[ "MIT" ]
null
null
null
import peewee import playhouse.kv from time import time from . import CacheableAdapter
24.25
72
0.537371
86bf8dc5885e11ca632362fcec2e79f7e5e74050
6,006
py
Python
mmgen/models/architectures/arcface/helpers.py
plutoyuxie/mmgeneration
0a7f5d16c970de1766ebf049d7a0264fe506504b
[ "Apache-2.0" ]
null
null
null
mmgen/models/architectures/arcface/helpers.py
plutoyuxie/mmgeneration
0a7f5d16c970de1766ebf049d7a0264fe506504b
[ "Apache-2.0" ]
null
null
null
mmgen/models/architectures/arcface/helpers.py
plutoyuxie/mmgeneration
0a7f5d16c970de1766ebf049d7a0264fe506504b
[ "Apache-2.0" ]
null
null
null
from collections import namedtuple import torch from torch.nn import (AdaptiveAvgPool2d, BatchNorm2d, Conv2d, MaxPool2d, Module, PReLU, ReLU, Sequential, Sigmoid) # yapf: disable """ ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) # isort:skip # noqa """ # yapf: enable def l2_norm(input, axis=1): """l2 normalization. Args: input (torch.Tensor): The input tensor. axis (int, optional): Specifies which axis of input to calculate the norm across. Defaults to 1. Returns: Tensor: Tensor after L2 normalization per-instance. """ norm = torch.norm(input, 2, axis, True) output = torch.div(input, norm) return output def get_block(in_channel, depth, num_units, stride=2): """Get a single block config. Args: in_channel (int): Input channels. depth (int): Output channels. num_units (int): Number of unit modules. stride (int, optional): Conv2d stride. Defaults to 2. Returns: list: A list of unit modules' config. """ return [Bottleneck(in_channel, depth, stride) ] + [Bottleneck(depth, depth, 1) for i in range(num_units - 1)] def get_blocks(num_layers): """Get block configs of backbone. Args: num_layers (int): Number of ConvBlock layers in backbone. Raises: ValueError: `num_layers` must be one of [50, 100, 152]. Returns: list: A list of block configs. """ if num_layers == 50: blocks = [ get_block(in_channel=64, depth=64, num_units=3), get_block(in_channel=64, depth=128, num_units=4), get_block(in_channel=128, depth=256, num_units=14), get_block(in_channel=256, depth=512, num_units=3) ] elif num_layers == 100: blocks = [ get_block(in_channel=64, depth=64, num_units=3), get_block(in_channel=64, depth=128, num_units=13), get_block(in_channel=128, depth=256, num_units=30), get_block(in_channel=256, depth=512, num_units=3) ] elif num_layers == 152: blocks = [ get_block(in_channel=64, depth=64, num_units=3), get_block(in_channel=64, depth=128, num_units=8), get_block(in_channel=128, depth=256, num_units=36), get_block(in_channel=256, depth=512, num_units=3) ] else: raise ValueError( 'Invalid number of layers: {}. Must be one of [50, 100, 152]'. format(num_layers)) return blocks
30.180905
106
0.585914
86bfaf5a13f46371cddc52c365f2b99eb199e27e
1,694
py
Python
createplaylist.py
mahi0601/SpotifyPlaylist
55e30bb4c13f291693b892d6eeccc70b4a769805
[ "MIT" ]
47
2020-09-21T11:35:10.000Z
2022-01-17T21:25:39.000Z
createplaylist.py
mahi0601/SpotifyPlaylist
55e30bb4c13f291693b892d6eeccc70b4a769805
[ "MIT" ]
2
2021-03-31T17:02:24.000Z
2021-07-30T08:17:37.000Z
createplaylist.py
mahi0601/SpotifyPlaylist
55e30bb4c13f291693b892d6eeccc70b4a769805
[ "MIT" ]
24
2020-09-21T16:45:38.000Z
2022-03-02T10:50:47.000Z
import os from spotifyclient import SpotifyClient if __name__ == "__main__": main()
42.35
118
0.725502
86c0f5e44bffc70a506881987c3f56e4e3ef7cdd
30,797
py
Python
tests/contrib/flask/test_request.py
thieman/dd-trace-py
1e87c9bdf7769032982349c4ccc0e1c2e6866a16
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
tests/contrib/flask/test_request.py
thieman/dd-trace-py
1e87c9bdf7769032982349c4ccc0e1c2e6866a16
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
tests/contrib/flask/test_request.py
thieman/dd-trace-py
1e87c9bdf7769032982349c4ccc0e1c2e6866a16
[ "Apache-2.0", "BSD-3-Clause" ]
1
2021-02-11T10:20:14.000Z
2021-02-11T10:20:14.000Z
# -*- coding: utf-8 -*- from ddtrace.compat import PY2 from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY from ddtrace.contrib.flask.patch import flask_version from ddtrace.ext import http from ddtrace.propagation.http import HTTP_HEADER_TRACE_ID, HTTP_HEADER_PARENT_ID from flask import abort from . import BaseFlaskTestCase from ...utils import assert_span_http_status_code base_exception_name = 'builtins.Exception' if PY2: base_exception_name = 'exceptions.Exception'
39.892487
117
0.618437
86c23c7616ed380cf3c80ae082afe689a1c8e0b9
7,318
py
Python
ConvDR/data/preprocess_cast19.py
blazejdolicki/CHEDAR
e4819775e7f6ffa2d6f1ad798ee262f01370b236
[ "MIT" ]
1
2021-11-10T13:39:16.000Z
2021-11-10T13:39:16.000Z
ConvDR/data/preprocess_cast19.py
blazejdolicki/CHEDAR
e4819775e7f6ffa2d6f1ad798ee262f01370b236
[ "MIT" ]
null
null
null
ConvDR/data/preprocess_cast19.py
blazejdolicki/CHEDAR
e4819775e7f6ffa2d6f1ad798ee262f01370b236
[ "MIT" ]
null
null
null
import argparse from trec_car import read_data from tqdm import tqdm import pickle import os import json import copy from utils.util import NUM_FOLD def parse_sim_file(filename): """ Reads the deduplicated documents file and stores the duplicate passage ids into a dictionary """ sim_dict = {} lines = open(filename).readlines() for line in lines: data = line.strip().split(':') if len(data[1]) > 0: sim_docs = data[-1].split(',') for docs in sim_docs: sim_dict[docs] = 1 return sim_dict if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--car_cbor", type=str) parser.add_argument("--msmarco_collection", type=str) parser.add_argument("--duplicate_file", type=str) parser.add_argument("--cast_dir", type=str) parser.add_argument("--out_data_dir", type=str) parser.add_argument("--out_collection_dir", type=str) args = parser.parse_args() # INPUT sim_file = args.duplicate_file cast_topics_raw_file = os.path.join(args.cast_dir, "evaluation_topics_v1.0.json") cast_topics_manual_file = os.path.join( args.cast_dir, "evaluation_topics_annotated_resolved_v1.0.tsv") cast_qrels_file = os.path.join(args.cast_dir, "2019qrels.txt") # OUTPUT out_topics_file = os.path.join(args.out_data_dir, "eval_topics.jsonl") out_raw_queries_file = os.path.join(args.out_data_dir, "queries.raw.tsv") out_manual_queries_file = os.path.join(args.out_data_dir, "queries.manual.tsv") out_qrels_file = os.path.join(args.out_data_dir, "qrels.tsv") car_id_to_idx_file = os.path.join(args.out_collection_dir, "car_id_to_idx.pickle") car_idx_to_id_file = os.path.join(args.out_collection_dir, "car_idx_to_id.pickle") out_collection_file = os.path.join(args.out_collection_dir, "collection.tsv") # 1. Combine TREC-CAR & MS MARCO, remove duplicate passages, assign new ids car_id_to_idx = {} car_idx_to_id = [] if os.path.exists(out_collection_file) and os.path.exists( car_id_to_idx_file) and os.path.exists(car_idx_to_id_file): print("Preprocessed collection found. Loading car_id_to_idx...") with open(car_id_to_idx_file, "rb") as f: car_id_to_idx = pickle.load(f) else: sim_dict = parse_sim_file(sim_file) car_base_id = 10000000 i = 0 with open(out_collection_file, "w", encoding="utf-8") as f: #FIX change 'a' to 'w' in normal run print("Processing TREC-CAR...") for para in tqdm( read_data.iter_paragraphs(open(args.car_cbor, 'rb'))): car_id = "CAR_" + para.para_id text = para.get_text() text = text.replace("\t", " ").replace("\n", " ").replace("\r", " ") idx = car_base_id + i car_id_to_idx[ car_id] = idx # e.g. CAR_76a4a716d4b1b01995c6663ee16e94b4ca35fdd3 -> 10000044 car_idx_to_id.append(car_id) f.write("{}\t{}\n".format(idx, text)) i += 1 print("Processing MS MARCO...") removed = 0 with open(args.msmarco_collection, "r") as m: for line in tqdm(m): marco_id, text = line.strip().split("\t") if ("MARCO_" + marco_id) in sim_dict: removed += 1 continue f.write("{}\t{}\n".format(marco_id, text)) print("Removed " + str(removed) + " passages") print("Dumping id mappings to {} and {}...".format(car_id_to_idx_file, car_idx_to_id_file)) with open(car_id_to_idx_file, "wb") as f: pickle.dump(car_id_to_idx, f) with open(car_idx_to_id_file, "wb") as f: pickle.dump(car_idx_to_id, f) # 2. Process queries print("Processing CAsT utterances...") with open(cast_topics_raw_file, "r") as fin: raw_data = json.load(fin) with open(cast_topics_manual_file, "r") as fin: annonated_lines = fin.readlines() out_raw_queries = open(out_raw_queries_file, "w") out_manual_queries = open(out_manual_queries_file, "w") all_annonated = {} for line in annonated_lines: splitted = line.split('\t') out_manual_queries.write(line) topic_query = splitted[0] query = splitted[1].strip() topic_id = topic_query.split('_')[0] query_id = topic_query.split('_')[1] if topic_id not in all_annonated: all_annonated[topic_id] = {} all_annonated[topic_id][query_id] = query out_manual_queries.close() topic_number_dict = {} data = [] for group in raw_data: topic_number, description, turn, title = str( group['number']), group.get('description', ''), group['turn'], group.get( 'title', '') queries = [] for query in turn: query_number, raw_utterance = str( query['number']), query['raw_utterance'] queries.append(raw_utterance) record = {} record['topic_number'] = topic_number record['query_number'] = query_number record['description'] = description record['title'] = title record['input'] = copy.deepcopy(queries) record['target'] = all_annonated[topic_number][query_number] out_raw_queries.write("{}_{}\t{}\n".format(topic_number, query_number, raw_utterance)) if not topic_number in topic_number_dict: topic_number_dict[topic_number] = len(topic_number_dict) data.append(record) out_raw_queries.close() with open(out_topics_file, 'w') as fout: for item in data: json_str = json.dumps(item) fout.write(json_str + '\n') # Split eval data into K-fold topic_per_fold = len(topic_number_dict) // NUM_FOLD for i in range(NUM_FOLD): with open(out_topics_file + "." + str(i), 'w') as fout: for item in data: idx = topic_number_dict[item['topic_number']] if idx // topic_per_fold == i: json_str = json.dumps(item) fout.write(json_str + '\n') # 3. Process and convert qrels print("Processing qrels...") with open(cast_qrels_file, "r") as oq, open(out_qrels_file, "w") as nq: for line in oq: qid, _, pid, rel = line.strip().split() if pid.startswith("CAR_"): assert car_id_to_idx[pid] != -1 pid = car_id_to_idx[pid] elif pid.startswith("MARCO_"): pid = int(pid[6:]) else: continue nq.write(qid + "\t0\t" + str(pid) + "\t" + rel + "\n") print("End")
39.556757
104
0.562859
86c253258ad8f50c39a576db2e17ac13da5ea1c7
15,207
py
Python
coord_convert/geojson_utils.py
brandonxiang/example-pyQGIS
a61d0321d223d0b82e44bb809521965858fde857
[ "MIT" ]
3
2017-02-23T08:35:30.000Z
2018-12-11T05:50:54.000Z
coord_convert/geojson_utils.py
brandonxiang/example-pyQGIS
a61d0321d223d0b82e44bb809521965858fde857
[ "MIT" ]
null
null
null
coord_convert/geojson_utils.py
brandonxiang/example-pyQGIS
a61d0321d223d0b82e44bb809521965858fde857
[ "MIT" ]
2
2019-10-22T02:16:50.000Z
2020-09-28T11:37:48.000Z
__doc__ = 'github: https://github.com/brandonxiang/geojson-python-utils' import math from coordTransform_utils import wgs84togcj02 from coordTransform_utils import gcj02tobd09 def linestrings_intersect(line1, line2): """ To valid whether linestrings from geojson are intersected with each other. reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js Keyword arguments: line1 -- first line geojson object line2 -- second line geojson object if(line1 intersects with other) return intersect point array else empty array """ intersects = [] for i in range(0, len(line1['coordinates']) - 1): for j in range(0, len(line2['coordinates']) - 1): a1_x = line1['coordinates'][i][1] a1_y = line1['coordinates'][i][0] a2_x = line1['coordinates'][i + 1][1] a2_y = line1['coordinates'][i + 1][0] b1_x = line2['coordinates'][j][1] b1_y = line2['coordinates'][j][0] b2_x = line2['coordinates'][j + 1][1] b2_y = line2['coordinates'][j + 1][0] ua_t = (b2_x - b1_x) * (a1_y - b1_y) - \ (b2_y - b1_y) * (a1_x - b1_x) ub_t = (a2_x - a1_x) * (a1_y - b1_y) - \ (a2_y - a1_y) * (a1_x - b1_x) u_b = (b2_y - b1_y) * (a2_x - a1_x) - (b2_x - b1_x) * (a2_y - a1_y) if not u_b == 0: u_a = ua_t / u_b u_b = ub_t / u_b if 0 <= u_a and u_a <= 1 and 0 <= u_b and u_b <= 1: intersects.append({'type': 'Point', 'coordinates': [ a1_x + u_a * (a2_x - a1_x), a1_y + u_a * (a2_y - a1_y)]}) # if len(intersects) == 0: # intersects = False return intersects def _bbox_around_polycoords(coords): """ bounding box """ x_all = [] y_all = [] for first in coords[0]: x_all.append(first[1]) y_all.append(first[0]) return [min(x_all), min(y_all), max(x_all), max(y_all)] def _point_in_bbox(point, bounds): """ valid whether the point is inside the bounding box """ return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] > bounds[2] or point['coordinates'][0] < bounds[1] or point['coordinates'][0] > bounds[3]) def _pnpoly(x, y, coords): """ the algorithm to judge whether the point is located in polygon reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation """ vert = [[0, 0]] for coord in coords: for node in coord: vert.append(node) vert.append(coord[0]) vert.append([0, 0]) inside = False i = 0 j = len(vert) - 1 while i < len(vert): if ((vert[i][0] > y) != (vert[j][0] > y)) and (x < (vert[j][1] - vert[i][1]) * (y - vert[i][0]) / (vert[j][0] - vert[i][0]) + vert[i][1]): inside = not inside j = i i += 1 return inside def point_in_polygon(point, poly): """ valid whether the point is located in a polygon Keyword arguments: point -- point geojson object poly -- polygon geojson object if(point inside poly) return true else false """ coords = [poly['coordinates']] if poly[ 'type'] == 'Polygon' else poly['coordinates'] return _point_in_polygon(point, coords) def point_in_multipolygon(point, multipoly): """ valid whether the point is located in a mulitpolygon (donut polygon is not supported) Keyword arguments: point -- point geojson object multipoly -- multipolygon geojson object if(point inside multipoly) return true else false """ coords_array = [multipoly['coordinates']] if multipoly[ 'type'] == "MultiPolygon" else multipoly['coordinates'] for coords in coords_array: if _point_in_polygon(point, coords): return True return False def number2radius(number): """ convert degree into radius Keyword arguments: number -- degree return radius """ return number * math.pi / 180 def number2degree(number): """ convert radius into degree Keyword arguments: number -- radius return degree """ return number * 180 / math.pi def draw_circle(radius_in_meters, center_point, steps=15): """ get a circle shape polygon based on centerPoint and radius Keyword arguments: point1 -- point one geojson object point2 -- point two geojson object if(point inside multipoly) return true else false """ steps = steps if steps > 15 else 15 center = [center_point['coordinates'][1], center_point['coordinates'][0]] dist = (radius_in_meters / 1000) / 6371 # convert meters to radiant rad_center = [number2radius(center[0]), number2radius(center[1])] # 15 sided circle poly = [] for step in range(0, steps): brng = 2 * math.pi * step / steps lat = math.asin(math.sin(rad_center[0]) * math.cos(dist) + math.cos(rad_center[0]) * math.sin(dist) * math.cos(brng)) lng = rad_center[1] + math.atan2(math.sin(brng) * math.sin(dist) * math.cos(rad_center[0]), math.cos(dist) - math.sin(rad_center[0]) * math.sin(lat)) poly.append([number2degree(lng), number2degree(lat)]) return {"type": "Polygon", "coordinates": [poly]} def rectangle_centroid(rectangle): """ get the centroid of the rectangle Keyword arguments: rectangle -- polygon geojson object return centroid """ bbox = rectangle['coordinates'][0] xmin = bbox[0][0] ymin = bbox[0][1] xmax = bbox[2][0] ymax = bbox[2][1] xwidth = xmax - xmin ywidth = ymax - ymin return {'type': 'Point', 'coordinates': [xmin + xwidth / 2, ymin + ywidth / 2]} def point_distance(point1, point2): """ calculate the distance between two point on the sphere like google map reference http://www.movable-type.co.uk/scripts/latlong.html Keyword arguments: point1 -- point one geojson object point2 -- point two geojson object if(point inside multipoly) return true else false """ lon1 = point1['coordinates'][0] lat1 = point1['coordinates'][1] lon2 = point2['coordinates'][0] lat2 = point2['coordinates'][1] deg_lat = number2radius(lat2 - lat1) deg_lon = number2radius(lon2 - lon1) a = math.pow(math.sin(deg_lat / 2), 2) + math.cos(number2radius(lat1)) * \ math.cos(number2radius(lat2)) * math.pow(math.sin(deg_lon / 2), 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return (6371 * c) * 1000 def geometry_within_radius(geometry, center, radius): """ To valid whether point or linestring or polygon is inside a radius around a center Keyword arguments: geometry -- point/linstring/polygon geojson object center -- point geojson object radius -- radius if(geometry inside radius) return true else false """ if geometry['type'] == 'Point': return point_distance(geometry, center) <= radius elif geometry['type'] == 'LineString' or geometry['type'] == 'Polygon': point = {} # it's enough to check the exterior ring of the Polygon coordinates = geometry['coordinates'][0] if geometry['type'] == 'Polygon' else geometry['coordinates'] for coordinate in coordinates: point['coordinates'] = coordinate if point_distance(point, center) > radius: return False return True def area(poly): """ calculate the area of polygon Keyword arguments: poly -- polygon geojson object return polygon area """ poly_area = 0 # TODO: polygon holes at coordinates[1] points = poly['coordinates'][0] j = len(points) - 1 count = len(points) for i in range(0, count): p1_x = points[i][1] p1_y = points[i][0] p2_x = points[j][1] p2_y = points[j][0] poly_area += p1_x * p2_y poly_area -= p1_y * p2_x j = i poly_area /= 2 return poly_area def centroid(poly): """ get the centroid of polygon adapted from http://paulbourke.net/geometry/polyarea/javascript.txt Keyword arguments: poly -- polygon geojson object return polygon centroid """ f_total = 0 x_total = 0 y_total = 0 # TODO: polygon holes at coordinates[1] points = poly['coordinates'][0] j = len(points) - 1 count = len(points) for i in range(0, count): p1_x = points[i][1] p1_y = points[i][0] p2_x = points[j][1] p2_y = points[j][0] f_total = p1_x * p2_y - p2_x * p1_y x_total += (p1_x + p2_x) * f_total y_total += (p1_y + p2_y) * f_total j = i six_area = area(poly) * 6 return {'type': 'Point', 'coordinates': [y_total / six_area, x_total / six_area]} def destination_point(point, brng, dist): """ Calculate a destination Point base on a base point and a distance Keyword arguments: pt -- polygon geojson object brng -- an angle in degrees dist -- distance in Kilometer between destination and base point return destination point object """ dist = float(dist) / 6371 # convert dist to angular distance in radians brng = number2radius(brng) lon1 = number2radius(point['coordinates'][0]) lat1 = number2radius(point['coordinates'][1]) lat2 = math.asin(math.sin(lat1) * math.cos(dist) + math.cos(lat1) * math.sin(dist) * math.cos(brng)) lon2 = lon1 + math.atan2(math.sin(brng) * math.sin(dist) * math.cos(lat1), math.cos(dist) - math.sin(lat1) * math.sin(lat2)) lon2 = (lon2 + 3 * math.pi) % (2 * math.pi) - math.pi # normalise to -180 degree +180 degree return {'type': 'Point', 'coordinates': [number2degree(lon2), number2degree(lat2)]} def simplify(source, kink=20): """ source[] array of geojson points kink in metres, kinks above this depth kept kink depth is the height of the triangle abc where a-b and b-c are two consecutive line segments """ source_coord = map(lambda o: {"lng": o.coordinates[0], "lat": o.coordinates[1]}, source) # count, n_stack, n_dest, start, end, i, sig; # dev_sqr, max_dev_sqr, band_sqr; # x12, y12, d12, x13, y13, d13, x23, y23, d23; F = (math.pi / 180.0) * 0.5 index = [] # aray of indexes of source points to include in the reduced line sig_start = [] # indices of start & end of working section sig_end = [] # check for simple cases count = len(source_coord) if count < 3: return source_coord # one or two points # more complex case. initialize stack band_sqr = kink * 360.0 / (2.0 * math.pi * 6378137.0) # Now in degrees band_sqr *= band_sqr n_dest = 0 sig_start[0] = 0 sig_end[0] = count - 1 n_stack = 1 # while the stack is not empty while n_stack > 0: # ... pop the top-most entries off the stacks start = sig_start[n_stack - 1] end = sig_end[n_stack - 1] n_stack -= 1 if (end - start) > 1: #any intermediate points ? # ... yes, so find most deviant intermediate point to either side of line joining start & end points x12 = source[end]["lng"] - source[start]["lng"] y12 = source[end]["lat"] - source[start]["lat"] if math.fabs(x12) > 180.0: x12 = 360.0 - math.fabs(x12) x12 *= math.cos(F * (source[end]["lat"] + source[start]["lat"])) # use avg lat to reduce lng d12 = (x12 * x12) + (y12 * y12) i = start + 1 sig = start max_dev_sqr = -1.0 while i < end: x13 = source[i]["lng"] - source[start]["lng"] y13 = source[i]["lat"] - source[start]["lat"] if math.fabs(x13) > 180.0: x13 = 360.0 - math.fabs(x13) x13 *= math.cos(F * (source[i]["lat"] + source[start]["lat"])) d13 = (x13 * x13) + (y13 * y13) x23 = source[i]["lng"] - source[end]["lng"] y23 = source[i]["lat"] - source[end]["lat"] if math.fabs(x23) > 180.0: x23 = 360.0 - math.fabs(x23) x23 *= math.cos(F * (source[i]["lat"] + source[end]["lat"])) d23 = (x23 * x23) + (y23 * y23) if d13 >= (d12 + d23): dev_sqr = d23 elif d23 >= (d12 + d13): dev_sqr = d13 else: dev_sqr = (x13 * y12 - y13 * x12) * (x13 * y12 - y13 * x12) / d12 # solve triangle if dev_sqr > max_dev_sqr: sig = i max_dev_sqr = dev_sqr i += 1 if max_dev_sqr < band_sqr: # is there a sig. intermediate point ? #... no, so transfer current start point index[n_dest] = start n_dest += 1 else: # ... yes, so push two sub-sections on stack for further processing n_stack += 1 sig_start[n_stack - 1] = sig sig_end[n_stack - 1] = end n_stack += 1 sig_start[n_stack - 1] = start sig_end[n_stack - 1] = sig else: # ... no intermediate points, so transfer current start point index[n_dest] = start n_dest += 1 # transfer last point index[n_dest] = count - 1 n_dest += 1 # make return array r = [] for i in range(0, n_dest): r.append(source_coord[index[i]]) return map(lambda o: {"type": "Point","coordinates": [o.lng, o.lat]}, r) def wgs2gcj(geometry): """ convert wgs84 to gcj referencing by https://github.com/wandergis/coordTransform_py """ # TODO: point linestring point if geometry['type'] == 'MultiLineString': coordinates = geometry['coordinates'] for lines in coordinates: for line in lines: line[0], line[1] = wgs84togcj02(line[0], line[1]) return geometry def gcj2bd(geometry): """ convert gcj to bd referencing by https://github.com/wandergis/coordTransform_py """ # TODO: point linestring point if geometry['type'] == 'MultiLineString': coordinates = geometry['coordinates'] for lines in coordinates: for line in lines: line[0], line[1] = gcj02tobd09(line[0], line[1]) return geometry
31.290123
125
0.572105
86c29a98e5b655839d8db00b70a6a8da9b1ef8d8
388
py
Python
config.py
Rinku92/Mini_Project3
eab11ce3743fddda2ccc158367a37d4522ba1e39
[ "MIT" ]
null
null
null
config.py
Rinku92/Mini_Project3
eab11ce3743fddda2ccc158367a37d4522ba1e39
[ "MIT" ]
null
null
null
config.py
Rinku92/Mini_Project3
eab11ce3743fddda2ccc158367a37d4522ba1e39
[ "MIT" ]
null
null
null
import os ''' user = os.environ['POSTGRES_USER'] password = os.environ['POSTGRES_PASSWORD'] host = os.environ['POSTGRES_HOST'] database = os.environ['POSTGRES_DB'] port = os.environ['POSTGRES_PORT'] ''' user = 'test' password = 'password' host = 'localhost' database = 'example' port = '5432' DATABASE_CONNECTION_URI = f'postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}'
24.25
93
0.716495
86c368ef733994c7aa8778c60fbe8e4bdf94dac9
347
py
Python
10_days_of_statistics_8_1.py
sercangul/HackerRank
e6d7056babe03baafee8d7f1cacdca7c28b72ded
[ "Apache-2.0" ]
null
null
null
10_days_of_statistics_8_1.py
sercangul/HackerRank
e6d7056babe03baafee8d7f1cacdca7c28b72ded
[ "Apache-2.0" ]
null
null
null
10_days_of_statistics_8_1.py
sercangul/HackerRank
e6d7056babe03baafee8d7f1cacdca7c28b72ded
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 3 19:26:47 2019 @author: sercangul """ n = 5 xy = [map(int, input().split()) for _ in range(n)] sx, sy, sx2, sxy = map(sum, zip(*[(x, y, x**2, x * y) for x, y in xy])) b = (n * sxy - sx * sy) / (n * sx2 - sx**2) a = (sy / n) - b * (sx / n) print('{:.3f}'.format(a + b * 80))
24.785714
71
0.501441
86c4016c71680c25695f7a5d4e332b95ab4759b0
450
py
Python
rlutils/gym/envs/reset_obs/hopper.py
vermouth1992/rl-util
4c06ab8f5c96a44e58f88cf30146bcb837057112
[ "Apache-2.0" ]
null
null
null
rlutils/gym/envs/reset_obs/hopper.py
vermouth1992/rl-util
4c06ab8f5c96a44e58f88cf30146bcb837057112
[ "Apache-2.0" ]
null
null
null
rlutils/gym/envs/reset_obs/hopper.py
vermouth1992/rl-util
4c06ab8f5c96a44e58f88cf30146bcb837057112
[ "Apache-2.0" ]
null
null
null
import gym.envs.mujoco.hopper as hopper import numpy as np
25
40
0.591111
86c445a03cb1fedcfaa9af4175640a3d81afd9b9
8,505
py
Python
reco_utils/recommender/deeprec/io/iterator.py
yutian-zhao/recommenders
17b9c1280a79019dd91f50b3a7e66f25cb5004b1
[ "MIT" ]
null
null
null
reco_utils/recommender/deeprec/io/iterator.py
yutian-zhao/recommenders
17b9c1280a79019dd91f50b3a7e66f25cb5004b1
[ "MIT" ]
null
null
null
reco_utils/recommender/deeprec/io/iterator.py
yutian-zhao/recommenders
17b9c1280a79019dd91f50b3a7e66f25cb5004b1
[ "MIT" ]
null
null
null
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import numpy as np # import tensorflow as tf import abc # class FFMTextIterator(BaseIterator): # """Data loader for FFM format based models, such as xDeepFM. # Iterator will not load the whole data into memory. Instead, it loads data into memory # per mini-batch, so that large files can be used as input data. # """ # def __init__(self, hparams, graph, col_spliter=" ", ID_spliter="%"): # """Initialize an iterator. Create necessary placeholders for the model. # Args: # hparams (obj): Global hyper-parameters. Some key settings such as #_feature and #_field are there. # graph (obj): the running graph. All created placeholder will be added to this graph. # col_spliter (str): column splitter in one line. # ID_spliter (str): ID splitter in one line. # """ # self.feature_cnt = hparams.FEATURE_COUNT # self.field_cnt = hparams.FIELD_COUNT # self.col_spliter = col_spliter # self.ID_spliter = ID_spliter # self.batch_size = hparams.batch_size # self.graph = graph # with self.graph.as_default(): # self.labels = tf.placeholder(tf.float32, [None, 1], name="label") # self.fm_feat_indices = tf.placeholder( # tf.int64, [None, 2], name="fm_feat_indices" # ) # self.fm_feat_values = tf.placeholder( # tf.float32, [None], name="fm_feat_values" # ) # self.fm_feat_shape = tf.placeholder(tf.int64, [None], name="fm_feat_shape") # self.dnn_feat_indices = tf.placeholder( # tf.int64, [None, 2], name="dnn_feat_indices" # ) # self.dnn_feat_values = tf.placeholder( # tf.int64, [None], name="dnn_feat_values" # ) # self.dnn_feat_weights = tf.placeholder( # tf.float32, [None], name="dnn_feat_weights" # ) # self.dnn_feat_shape = tf.placeholder( # tf.int64, [None], name="dnn_feat_shape" # ) # def parser_one_line(self, line): # """Parse one string line into feature values. # Args: # line (str): a string indicating one instance # Returns: # list: Parsed results,including label, features and impression_id # """ # impression_id = 0 # words = line.strip().split(self.ID_spliter) # if len(words) == 2: # impression_id = words[1].strip() # cols = words[0].strip().split(self.col_spliter) # label = float(cols[0]) # features = [] # for word in cols[1:]: # if not word.strip(): # continue # tokens = word.split(":") # features.append([int(tokens[0]) - 1, int(tokens[1]) - 1, float(tokens[2])]) # return label, features, impression_id # def load_data_from_file(self, infile): # """Read and parse data from a file. # Args: # infile (str): text input file. Each line in this file is an instance. # Returns: # obj: An iterator that will yields parsed results, in the format of graph feed_dict. # """ # label_list = [] # features_list = [] # impression_id_list = [] # cnt = 0 # with tf.gfile.GFile(infile, "r") as rd: # for line in rd: # label, features, impression_id = self.parser_one_line(line) # features_list.append(features) # label_list.append(label) # impression_id_list.append(impression_id) # cnt += 1 # if cnt == self.batch_size: # res = self._convert_data(label_list, features_list) # yield self.gen_feed_dict(res), impression_id_list, self.batch_size # label_list = [] # features_list = [] # impression_id_list = [] # cnt = 0 # if cnt > 0: # res = self._convert_data(label_list, features_list) # yield self.gen_feed_dict(res), impression_id_list, cnt # def _convert_data(self, labels, features): # """Convert data into numpy arrays that are good for further operation. # Args: # labels (list): a list of ground-truth labels. # features (list): a 3-dimensional list, carrying a list (batch_size) of feature array, # where each feature array is a list of [field_idx, feature_idx, feature_value] tuple. # Returns: # dict: A dictionary, contains multiple numpy arrays that are convenient for further operation. # """ # dim = self.feature_cnt # FIELD_COUNT = self.field_cnt # instance_cnt = len(labels) # fm_feat_indices = [] # fm_feat_values = [] # fm_feat_shape = [instance_cnt, dim] # dnn_feat_indices = [] # dnn_feat_values = [] # dnn_feat_weights = [] # dnn_feat_shape = [instance_cnt * FIELD_COUNT, -1] # for i in range(instance_cnt): # m = len(features[i]) # dnn_feat_dic = {} # for j in range(m): # fm_feat_indices.append([i, features[i][j][1]]) # fm_feat_values.append(features[i][j][2]) # if features[i][j][0] not in dnn_feat_dic: # dnn_feat_dic[features[i][j][0]] = 0 # else: # dnn_feat_dic[features[i][j][0]] += 1 # dnn_feat_indices.append( # [ # i * FIELD_COUNT + features[i][j][0], # dnn_feat_dic[features[i][j][0]], # ] # ) # dnn_feat_values.append(features[i][j][1]) # dnn_feat_weights.append(features[i][j][2]) # if dnn_feat_shape[1] < dnn_feat_dic[features[i][j][0]]: # dnn_feat_shape[1] = dnn_feat_dic[features[i][j][0]] # dnn_feat_shape[1] += 1 # sorted_index = sorted( # range(len(dnn_feat_indices)), # key=lambda k: (dnn_feat_indices[k][0], dnn_feat_indices[k][1]), # ) # res = {} # res["fm_feat_indices"] = np.asarray(fm_feat_indices, dtype=np.int64) # res["fm_feat_values"] = np.asarray(fm_feat_values, dtype=np.float32) # res["fm_feat_shape"] = np.asarray(fm_feat_shape, dtype=np.int64) # res["labels"] = np.asarray([[label] for label in labels], dtype=np.float32) # res["dnn_feat_indices"] = np.asarray(dnn_feat_indices, dtype=np.int64)[ # sorted_index # ] # res["dnn_feat_values"] = np.asarray(dnn_feat_values, dtype=np.int64)[ # sorted_index # ] # res["dnn_feat_weights"] = np.asarray(dnn_feat_weights, dtype=np.float32)[ # sorted_index # ] # res["dnn_feat_shape"] = np.asarray(dnn_feat_shape, dtype=np.int64) # return res # def gen_feed_dict(self, data_dict): # """Construct a dictionary that maps graph elements to values. # Args: # data_dict (dict): a dictionary that maps string name to numpy arrays. # Returns: # dict: a dictionary that maps graph elements to numpy arrays. # """ # feed_dict = { # self.labels: data_dict["labels"], # self.fm_feat_indices: data_dict["fm_feat_indices"], # self.fm_feat_values: data_dict["fm_feat_values"], # self.fm_feat_shape: data_dict["fm_feat_shape"], # self.dnn_feat_indices: data_dict["dnn_feat_indices"], # self.dnn_feat_values: data_dict["dnn_feat_values"], # self.dnn_feat_weights: data_dict["dnn_feat_weights"], # self.dnn_feat_shape: data_dict["dnn_feat_shape"], # } # return feed_dict
38.310811
112
0.55485
86c692ea321aa5d6632c79b6a92f458cad0e5a70
2,723
py
Python
ncm/api.py
SDhuangao/netease-cloud-music-dl
4a970504e1fec0a9848f3920b392aa507d6b3879
[ "MIT" ]
null
null
null
ncm/api.py
SDhuangao/netease-cloud-music-dl
4a970504e1fec0a9848f3920b392aa507d6b3879
[ "MIT" ]
null
null
null
ncm/api.py
SDhuangao/netease-cloud-music-dl
4a970504e1fec0a9848f3920b392aa507d6b3879
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import requests from ncm.encrypt import encrypted_request from ncm.constants import headers from ncm.constants import song_download_url from ncm.constants import get_song_url from ncm.constants import get_album_url from ncm.constants import get_artist_url from ncm.constants import get_playlist_url
27.505051
84
0.589791
86c7301877ec46ff5d214d67d7d24373229e91aa
15,337
py
Python
book/trees/binary_search_tree.py
Web-Dev-Collaborative/algos
d280581d74ded382094283d931a202eb55fd8369
[ "CC0-1.0" ]
153
2015-12-24T00:32:23.000Z
2022-02-24T06:00:29.000Z
book/trees/binary_search_tree.py
Web-Dev-Collaborative/algos
d280581d74ded382094283d931a202eb55fd8369
[ "CC0-1.0" ]
78
2015-11-17T11:46:15.000Z
2021-06-28T18:37:58.000Z
book/trees/binary_search_tree.py
rhivent/algo-books-python
c4fa29616ca9a8a15ba40fa12d21fd8f35096d40
[ "CC0-1.0" ]
66
2015-11-02T03:38:02.000Z
2022-03-05T17:36:26.000Z
# -*- coding: utf-8 -*- """ The `TreeNode` class provides many helper functions that make the work done in the `BinarySearchTree` class methods much easier. The constructor for a `TreeNode`, along with these helper functions, is shown below. As you can see, many of these helper functions help to classify a node according to its own position as a child, (left or right) and the kind of children the node has. The `TreeNode` class will also explicitly keep track of the parent as an attribute of each node. You will see why this is important when we discuss the implementation for the `del` operator. One of the more interesting methods of `TreeNode` provides an interface to simply iterate over all the keys in the tree in order. You already know how to traverse a binary tree in order, using the `inorder` traversal algorithm. However, because we want our iterator to operate lazily, in this case we use the `yield` keyword to define our `__iter__` method as a Python generator. Pay close attention to the `__iter__` implementation as at first glance you might think that the code is not recursive: in fact, because `__iter__` overrides the `for x in` operation for iteration, it really is recursive! Our full implementation of `TreeNode` is provided below. It includes three further methods `find_successor`, `find_min` and `splice_out` which you can ignore for now as we will return to them later when discussing deletion. """
37.775862
78
0.684684
86c7d4acbb62e0447380b9c4c68ef07bbf5ead1b
28,677
py
Python
fire/core.py
adamruth/python-fire
6912ccd56f50e0f4bb30a0725d95858ef29f3bde
[ "Apache-2.0" ]
1
2020-02-05T04:43:03.000Z
2020-02-05T04:43:03.000Z
fire/core.py
chesnjak/python-fire
72604f40314008e562ba47936dcc183b51166b72
[ "Apache-2.0" ]
null
null
null
fire/core.py
chesnjak/python-fire
72604f40314008e562ba47936dcc183b51166b72
[ "Apache-2.0" ]
1
2020-07-15T22:58:25.000Z
2020-07-15T22:58:25.000Z
# Copyright (C) 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Python Fire is a library for creating CLIs from absolutely any Python object. You can call Fire on any Python object: functions, classes, modules, objects, dictionaries, lists, tuples, etc. They all work! Python Fire turns any Python object into a command line interface. Simply call the Fire function as your main method to create a CLI. When using Fire to build a CLI, your main method includes a call to Fire. Eg: def main(argv): fire.Fire(Component) A Fire CLI command is run by consuming the arguments in the command in order to access a member of current component, call the current component (if it's a function), or instantiate the current component (if it's a class). The target component begins as Component, and at each operation the component becomes the result of the preceding operation. For example "command fn arg1 arg2" might access the "fn" property of the initial target component, and then call that function with arguments 'arg1' and 'arg2'. Additional examples are available in the examples directory. Fire Flags, common to all Fire CLIs, must go after a separating "--". For example, to get help for a command you might run: `command -- --help`. The available flags for all Fire CLIs are: -v --verbose: Include private members in help and usage information. -h --help: Provide help and usage information for the command. -i --interactive: Drop into a Python REPL after running the command. --completion: Write the Bash completion script for the tool to stdout. --separator SEPARATOR: Use SEPARATOR in place of the default separator, '-'. --trace: Get the Fire Trace for the command. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import json import os import pipes import shlex import sys import types from fire import completion from fire import decorators from fire import helputils from fire import inspectutils from fire import interact from fire import parser from fire import trace import six def Fire(component=None, command=None, name=None): """This function, Fire, is the main entrypoint for Python Fire. Executes a command either from the `command` argument or from sys.argv by recursively traversing the target object `component`'s members consuming arguments, evaluating functions, and instantiating classes as it goes. When building a CLI with Fire, your main method should call this function. Args: component: The initial target component. command: Optional. If supplied, this is the command executed. If not supplied, then the command is taken from sys.argv instead. This can be a string or a list of strings; a list of strings is preferred. name: Optional. The name of the command as entered at the command line. Used in interactive mode and for generating the completion script. Returns: The result of executing the Fire command. Execution begins with the initial target component. The component is updated by using the command arguments to either access a member of the current component, call the current component (if it's a function), or instantiate the current component (if it's a class). When all arguments are consumed and there's no function left to call or class left to instantiate, the resulting current component is the final result. Raises: ValueError: If the command argument is supplied, but not a string or a sequence of arguments. FireExit: When Fire encounters a FireError, Fire will raise a FireExit with code 2. When used with the help or trace flags, Fire will raise a FireExit with code 0 if successful. """ name = name or os.path.basename(sys.argv[0]) # Get args as a list. if isinstance(command, six.string_types): args = shlex.split(command) elif isinstance(command, (list, tuple)): args = command elif command is None: # Use the command line args by default if no command is specified. args = sys.argv[1:] else: raise ValueError('The command argument must be a string or a sequence of ' 'arguments.') # Determine the calling context. caller = inspect.stack()[1] caller_frame = caller[0] caller_globals = caller_frame.f_globals caller_locals = caller_frame.f_locals context = {} context.update(caller_globals) context.update(caller_locals) component_trace = _Fire(component, args, context, name) if component_trace.HasError(): for help_flag in ['-h', '--help']: if help_flag in component_trace.elements[-1].args: command = '{cmd} -- --help'.format(cmd=component_trace.GetCommand()) print(('WARNING: The proper way to show help is {cmd}.\n' 'Showing help anyway.\n').format(cmd=pipes.quote(command)), file=sys.stderr) print('Fire trace:\n{trace}\n'.format(trace=component_trace), file=sys.stderr) result = component_trace.GetResult() print( helputils.HelpString(result, component_trace, component_trace.verbose), file=sys.stderr) raise FireExit(2, component_trace) elif component_trace.show_trace and component_trace.show_help: print('Fire trace:\n{trace}\n'.format(trace=component_trace), file=sys.stderr) result = component_trace.GetResult() print( helputils.HelpString(result, component_trace, component_trace.verbose), file=sys.stderr) raise FireExit(0, component_trace) elif component_trace.show_trace: print('Fire trace:\n{trace}'.format(trace=component_trace), file=sys.stderr) raise FireExit(0, component_trace) elif component_trace.show_help: result = component_trace.GetResult() print( helputils.HelpString(result, component_trace, component_trace.verbose), file=sys.stderr) raise FireExit(0, component_trace) else: _PrintResult(component_trace, verbose=component_trace.verbose) result = component_trace.GetResult() return result def CompletionScript(name, component): """Returns the text of the Bash completion script for a Fire CLI.""" return completion.Script(name, component) def _PrintResult(component_trace, verbose=False): """Prints the result of the Fire call to stdout in a human readable way.""" # TODO: Design human readable deserializable serialization method # and move serialization to it's own module. result = component_trace.GetResult() if isinstance(result, (list, set, types.GeneratorType)): for i in result: print(_OneLineResult(i)) elif inspect.isgeneratorfunction(result): raise NotImplementedError elif isinstance(result, dict): print(_DictAsString(result, verbose)) elif isinstance(result, tuple): print(_OneLineResult(result)) elif isinstance(result, (bool, six.string_types, six.integer_types, float, complex)): print(result) elif result is not None: print(helputils.HelpString(result, component_trace, verbose)) def _DictAsString(result, verbose=False): """Returns a dict as a string. Args: result: The dict to convert to a string verbose: Whether to include 'hidden' members, those keys starting with _. Returns: A string representing the dict """ result = {key: value for key, value in result.items() if _ComponentVisible(key, verbose)} if not result: return '{}' longest_key = max(len(str(key)) for key in result.keys()) format_string = '{{key:{padding}s}} {{value}}'.format(padding=longest_key + 1) lines = [] for key, value in result.items(): line = format_string.format(key=str(key) + ':', value=_OneLineResult(value)) lines.append(line) return '\n'.join(lines) def _ComponentVisible(component, verbose=False): """Returns whether a component should be visible in the output.""" return ( verbose or not isinstance(component, six.string_types) or not component.startswith('_')) def _OneLineResult(result): """Returns result serialized to a single line string.""" # TODO: Ensure line is fewer than eg 120 characters. if isinstance(result, six.string_types): return str(result).replace('\n', ' ') try: # Don't force conversion to ascii. return json.dumps(result, ensure_ascii=False) except (TypeError, ValueError): return str(result).replace('\n', ' ') def _Fire(component, args, context, name=None): """Execute a Fire command on a target component using the args supplied. Arguments that come after a final isolated '--' are treated as Flags, eg for interactive mode or completion script generation. Other arguments are consumed by the execution of the Fire command, eg in the traversal of the members of the component, or in calling a function or instantiating a class found during the traversal. The steps performed by this method are: 1. Parse any Flag args (the args after the final --) 2. Start with component as the current component. 2a. If the current component is a class, instantiate it using args from args. 2b. If the current component is a routine, call it using args from args. 2c. Otherwise access a member from component using an arg from args. 2d. Repeat 2a-2c until no args remain. 3a. Embed into ipython REPL if interactive mode is selected. 3b. Generate a completion script if that flag is provided. In step 2, arguments will only ever be consumed up to a separator; a single step will never consume arguments from both sides of a separator. The separator defaults to a hyphen (-), and can be overwritten with the --separator Fire argument. Args: component: The target component for Fire. args: A list of args to consume in Firing on the component, usually from the command line. context: A dict with the local and global variables available at the call to Fire. name: Optional. The name of the command. Used in interactive mode and in the tab completion script. Returns: FireTrace of components starting with component, tracing Fire's execution path as it consumes args. Raises: ValueError: If there are arguments that cannot be consumed. ValueError: If --completion is specified but no name available. """ args, flag_args = parser.SeparateFlagArgs(args) argparser = parser.CreateParser() parsed_flag_args, unused_args = argparser.parse_known_args(flag_args) verbose = parsed_flag_args.verbose interactive = parsed_flag_args.interactive separator = parsed_flag_args.separator show_completion = parsed_flag_args.completion show_help = parsed_flag_args.help show_trace = parsed_flag_args.trace # component can be a module, class, routine, object, etc. if component is None: component = context initial_component = component component_trace = trace.FireTrace( initial_component=initial_component, name=name, separator=separator, verbose=verbose, show_help=show_help, show_trace=show_trace) instance = None remaining_args = args while True: last_component = component initial_args = remaining_args if not remaining_args and (show_help or interactive or show_trace or show_completion): # Don't initialize the final class or call the final function unless # there's a separator after it, and instead process the current component. break saved_args = [] used_separator = False if separator in remaining_args: # For the current component, only use arguments up to the separator. separator_index = remaining_args.index(separator) saved_args = remaining_args[separator_index + 1:] remaining_args = remaining_args[:separator_index] used_separator = True assert separator not in remaining_args if inspect.isclass(component) or inspect.isroutine(component): # The component is a class or a routine; we'll try to initialize it or # call it. isclass = inspect.isclass(component) try: target = component.__name__ filename, lineno = inspectutils.GetFileAndLine(component) component, consumed_args, remaining_args, capacity = _CallCallable( component, remaining_args) # Update the trace. if isclass: component_trace.AddInstantiatedClass( component, target, consumed_args, filename, lineno, capacity) else: component_trace.AddCalledRoutine( component, target, consumed_args, filename, lineno, capacity) except FireError as error: component_trace.AddError(error, initial_args) return component_trace if last_component is initial_component: # If the initial component is a class, keep an instance for use with -i. instance = component elif isinstance(component, (list, tuple)) and remaining_args: # The component is a tuple or list; we'll try to access a member. arg = remaining_args[0] try: index = int(arg) component = component[index] except (ValueError, IndexError): error = FireError( 'Unable to index into component with argument:', arg) component_trace.AddError(error, initial_args) return component_trace remaining_args = remaining_args[1:] filename = None lineno = None component_trace.AddAccessedProperty( component, index, [arg], filename, lineno) elif isinstance(component, dict) and remaining_args: # The component is a dict; we'll try to access a member. target = remaining_args[0] if target in component: component = component[target] elif target.replace('-', '_') in component: component = component[target.replace('-', '_')] else: # The target isn't present in the dict as a string, but maybe it is as # another type. # TODO: Consider alternatives for accessing non-string keys. found_target = False for key, value in component.items(): if target == str(key): component = value found_target = True break if not found_target: error = FireError( 'Cannot find target in dict:', target, component) component_trace.AddError(error, initial_args) return component_trace remaining_args = remaining_args[1:] filename = None lineno = None component_trace.AddAccessedProperty( component, target, [target], filename, lineno) elif remaining_args: # We'll try to access a member of the component. try: target = remaining_args[0] component, consumed_args, remaining_args = _GetMember( component, remaining_args) filename, lineno = inspectutils.GetFileAndLine(component) component_trace.AddAccessedProperty( component, target, consumed_args, filename, lineno) except FireError as error: component_trace.AddError(error, initial_args) return component_trace if used_separator: # Add back in the arguments from after the separator. if remaining_args: remaining_args = remaining_args + [separator] + saved_args elif (inspect.isclass(last_component) or inspect.isroutine(last_component)): remaining_args = saved_args component_trace.AddSeparator() elif component is not last_component: remaining_args = [separator] + saved_args else: # It was an unnecessary separator. remaining_args = saved_args if component is last_component and remaining_args == initial_args: # We're making no progress. break if remaining_args: component_trace.AddError( FireError('Could not consume arguments:', remaining_args), initial_args) return component_trace if show_completion: if name is None: raise ValueError('Cannot make completion script without command name') script = CompletionScript(name, initial_component) component_trace.AddCompletionScript(script) if interactive: variables = context.copy() if name is not None: variables[name] = initial_component variables['component'] = initial_component variables['result'] = component variables['trace'] = component_trace if instance is not None: variables['self'] = instance interact.Embed(variables, verbose) component_trace.AddInteractiveMode() return component_trace def _GetMember(component, args): """Returns a subcomponent of component by consuming an arg from args. Given a starting component and args, this function gets a member from that component, consuming one arg in the process. Args: component: The component from which to get a member. args: Args from which to consume in the search for the next component. Returns: component: The component that was found by consuming an arg. consumed_args: The args that were consumed by getting this member. remaining_args: The remaining args that haven't been consumed yet. Raises: FireError: If we cannot consume an argument to get a member. """ members = dict(inspect.getmembers(component)) arg = args[0] arg_names = [ arg, arg.replace('-', '_'), # treat '-' as '_'. ] for arg_name in arg_names: if arg_name in members: return members[arg_name], [arg], args[1:] raise FireError('Could not consume arg:', arg) def _CallCallable(fn, args): """Calls the function fn by consuming args from args. Args: fn: The function to call or class to instantiate. args: Args from which to consume for calling the function. Returns: component: The object that is the result of the function call. consumed_args: The args that were consumed for the function call. remaining_args: The remaining args that haven't been consumed yet. capacity: Whether the call could have taken additional args. """ parse = _MakeParseFn(fn) (varargs, kwargs), consumed_args, remaining_args, capacity = parse(args) result = fn(*varargs, **kwargs) return result, consumed_args, remaining_args, capacity def _MakeParseFn(fn): """Creates a parse function for fn. Args: fn: The function or class to create the parse function for. Returns: A parse function for fn. The parse function accepts a list of arguments and returns (varargs, kwargs), remaining_args. The original function fn can then be called with fn(*varargs, **kwargs). The remaining_args are the leftover args from the arguments to the parse function. """ fn_spec = inspectutils.GetFullArgSpec(fn) all_args = fn_spec.args + fn_spec.kwonlyargs metadata = decorators.GetMetadata(fn) # Note: num_required_args is the number of positional arguments without # default values. All of these arguments are required. num_required_args = len(fn_spec.args) - len(fn_spec.defaults) required_kwonly = set(fn_spec.kwonlyargs) - set(fn_spec.kwonlydefaults) def _ParseFn(args): """Parses the list of `args` into (varargs, kwargs), remaining_args.""" kwargs, remaining_kwargs, remaining_args = _ParseKeywordArgs( args, all_args, fn_spec.varkw) # Note: _ParseArgs modifies kwargs. parsed_args, kwargs, remaining_args, capacity = _ParseArgs( fn_spec.args, fn_spec.defaults, num_required_args, kwargs, remaining_args, metadata) if fn_spec.varargs or fn_spec.varkw: # If we're allowed *varargs or **kwargs, there's always capacity. capacity = True extra_kw = set(kwargs) - set(fn_spec.kwonlyargs) if fn_spec.varkw is None and extra_kw: raise FireError('Unexpected kwargs present:', extra_kw) missing_kwonly = set(required_kwonly) - set(kwargs) if missing_kwonly: raise FireError('Missing required flags:', missing_kwonly) # If we accept *varargs, then use all remaining arguments for *varargs. if fn_spec.varargs is not None: varargs, remaining_args = remaining_args, [] else: varargs = [] for index, value in enumerate(varargs): varargs[index] = _ParseValue(value, None, None, metadata) varargs = parsed_args + varargs remaining_args += remaining_kwargs consumed_args = args[:len(args) - len(remaining_args)] return (varargs, kwargs), consumed_args, remaining_args, capacity return _ParseFn def _ParseArgs(fn_args, fn_defaults, num_required_args, kwargs, remaining_args, metadata): """Parses the positional and named arguments from the available supplied args. Modifies kwargs, removing args as they are used. Args: fn_args: A list of argument names that the target function accepts, including positional and named arguments, but not the varargs or kwargs names. fn_defaults: A list of the default values in the function argspec. num_required_args: The number of required arguments from the function's argspec. This is the number of arguments without a default value. kwargs: Dict with named command line arguments and their values. remaining_args: The remaining command line arguments, which may still be used as positional arguments. metadata: Metadata about the function, typically from Fire decorators. Returns: parsed_args: A list of values to be used as positional arguments for calling the target function. kwargs: The input dict kwargs modified with the used kwargs removed. remaining_args: A list of the supplied args that have not been used yet. capacity: Whether the call could have taken args in place of defaults. Raises: FireError: if additional positional arguments are expected, but none are available. """ accepts_positional_args = metadata.get(decorators.ACCEPTS_POSITIONAL_ARGS) capacity = False # If we see a default get used, we'll set capacity to True # Select unnamed args. parsed_args = [] for index, arg in enumerate(fn_args): value = kwargs.pop(arg, None) if value is not None: # A value is specified at the command line. value = _ParseValue(value, index, arg, metadata) parsed_args.append(value) else: # No value has been explicitly specified. if remaining_args and accepts_positional_args: # Use a positional arg. value = remaining_args.pop(0) value = _ParseValue(value, index, arg, metadata) parsed_args.append(value) elif index < num_required_args: raise FireError( 'The function received no value for the required argument:', arg) else: # We're past the args for which there's no default value. # There's a default value for this arg. capacity = True default_index = index - num_required_args # index into the defaults. parsed_args.append(fn_defaults[default_index]) for key, value in kwargs.items(): kwargs[key] = _ParseValue(value, None, key, metadata) return parsed_args, kwargs, remaining_args, capacity def _ParseKeywordArgs(args, fn_args, fn_keywords): """Parses the supplied arguments for keyword arguments. Given a list of arguments, finds occurences of --name value, and uses 'name' as the keyword and 'value' as the value. Constructs and returns a dictionary of these keyword arguments, and returns a list of the remaining arguments. Only if fn_keywords is None, this only finds argument names used by the function, specified through fn_args. This returns the values of the args as strings. They are later processed by _ParseArgs, which converts them to the appropriate type. Args: args: A list of arguments fn_args: A list of argument names that the target function accepts, including positional and named arguments, but not the varargs or kwargs names. fn_keywords: The argument name for **kwargs, or None if **kwargs not used Returns: kwargs: A dictionary mapping keywords to values. remaining_kwargs: A list of the unused kwargs from the original args. remaining_args: A list of the unused arguments from the original args. """ kwargs = {} remaining_kwargs = [] remaining_args = [] if not args: return kwargs, remaining_kwargs, remaining_args skip_argument = False for index, argument in enumerate(args): if skip_argument: skip_argument = False continue arg_consumed = False if argument.startswith('--'): # This is a named argument; get its value from this arg or the next. got_argument = False keyword = argument[2:] contains_equals = '=' in keyword is_bool_syntax = ( not contains_equals and (index + 1 == len(args) or args[index + 1].startswith('--'))) if contains_equals: keyword, value = keyword.split('=', 1) got_argument = True elif is_bool_syntax: # Since there's no next arg or the next arg is a Flag, we consider # this flag to be a boolean. got_argument = True if keyword in fn_args: value = 'True' elif keyword.startswith('no'): keyword = keyword[2:] value = 'False' else: value = 'True' else: if index + 1 < len(args): value = args[index + 1] got_argument = True keyword = keyword.replace('-', '_') # In order for us to consume the argument as a keyword arg, we either: # Need to be explicitly expecting the keyword, or we need to be # accepting **kwargs. if got_argument: skip_argument = not contains_equals and not is_bool_syntax arg_consumed = True if keyword in fn_args or fn_keywords: kwargs[keyword] = value else: remaining_kwargs.append(argument) if skip_argument: remaining_kwargs.append(args[index + 1]) if not arg_consumed: # The argument was not consumed, so it is still a remaining argument. remaining_args.append(argument) return kwargs, remaining_kwargs, remaining_args def _ParseValue(value, index, arg, metadata): """Parses value, a string, into the appropriate type. The function used to parse value is determined by the remaining arguments. Args: value: The string value to be parsed, typically a command line argument. index: The index of the value in the function's argspec. arg: The name of the argument the value is being parsed for. metadata: Metadata about the function, typically from Fire decorators. Returns: value, parsed into the appropriate type for calling a function. """ parse_fn = parser.DefaultParseValue # We check to see if any parse function from the fn metadata applies here. parse_fns = metadata.get(decorators.FIRE_PARSE_FNS) if parse_fns: default = parse_fns['default'] positional = parse_fns['positional'] named = parse_fns['named'] if index is not None and 0 <= index < len(positional): parse_fn = positional[index] elif arg in named: parse_fn = named[arg] elif default is not None: parse_fn = default return parse_fn(value)
36.577806
80
0.706873
86c845d512d008bf07b10c93c9a059cfaa7474a0
1,668
py
Python
app.py
AmirValeev/auto-ml-classifier
e803fe92d1ec71e87509845ea61ecc46b363bae6
[ "Apache-2.0" ]
null
null
null
app.py
AmirValeev/auto-ml-classifier
e803fe92d1ec71e87509845ea61ecc46b363bae6
[ "Apache-2.0" ]
null
null
null
app.py
AmirValeev/auto-ml-classifier
e803fe92d1ec71e87509845ea61ecc46b363bae6
[ "Apache-2.0" ]
null
null
null
import os, ast import pandas as pd from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder from sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline import pickle if __name__ == "__main__": main()
33.36
126
0.668465
86c8b4810cb292d6be03cbb1ee7d68143bb6929f
512
py
Python
util/headers.py
giuseppe/quay
a1b7e4b51974edfe86f66788621011eef2667e6a
[ "Apache-2.0" ]
2,027
2019-11-12T18:05:48.000Z
2022-03-31T22:25:04.000Z
util/headers.py
giuseppe/quay
a1b7e4b51974edfe86f66788621011eef2667e6a
[ "Apache-2.0" ]
496
2019-11-12T18:13:37.000Z
2022-03-31T10:43:45.000Z
util/headers.py
giuseppe/quay
a1b7e4b51974edfe86f66788621011eef2667e6a
[ "Apache-2.0" ]
249
2019-11-12T18:02:27.000Z
2022-03-22T12:19:19.000Z
import base64 def parse_basic_auth(header_value): """ Attempts to parse the given header value as a Base64-encoded Basic auth header. """ if not header_value: return None parts = header_value.split(" ") if len(parts) != 2 or parts[0].lower() != "basic": return None try: basic_parts = base64.b64decode(parts[1]).split(":", 1) if len(basic_parts) != 2: return None return basic_parts except ValueError: return None
21.333333
83
0.599609
86c9f566a6eb8b7449c2eceeae4f2a4b402b56f5
3,115
py
Python
indico/core/signals/event/core.py
tobiashuste/indico
c1e6ec0c8c84745988e38c9b1768142a6feb9e0e
[ "MIT" ]
null
null
null
indico/core/signals/event/core.py
tobiashuste/indico
c1e6ec0c8c84745988e38c9b1768142a6feb9e0e
[ "MIT" ]
null
null
null
indico/core/signals/event/core.py
tobiashuste/indico
c1e6ec0c8c84745988e38c9b1768142a6feb9e0e
[ "MIT" ]
null
null
null
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.core.signals.event import _signals sidemenu = _signals.signal('sidemenu', """ Expected to return ``MenuEntryData`` objects to be added to the event side menu. A single entry can be returned directly, multiple entries must be yielded. """) deleted = _signals.signal('deleted', """ Called when an event is deleted. The *sender* is the event object. The `user` kwarg contains the user performing the deletion if available. """) updated = _signals.signal('updated', """ Called when basic data of an event is updated. The *sender* is the event. A dict of changes is passed in the `changes` kwarg, with ``(old, new)`` tuples for each change. Note than the `person_links` change may happen with `old` and `new` being the same lists for technical reasons. If the key is present, it should be assumed that something changed (usually the order or some data on the person link). """) cloned = _signals.signal('cloned', """ Called when an event is cloned. The *sender* is the `Event` object of the old event, the new event is passed in the `new_event` kwarg. """) type_changed = _signals.signal('type-changed', """ Called when the type of an event is changed. The `sender` is the event, the old type is passed in the `old_type` kwarg. """) moved = _signals.signal('moved', """ Called when an event is moved to a different category. The `sender` is the event, the old category is in the `old_parent` kwarg. """) created = _signals.signal('created', """ Called when a new event is created. The `sender` is the new Event. """) session_updated = _signals.signal('session-updated', """ Called when a session is updated. The *sender* is the session. """) session_deleted = _signals.signal('session-deleted', """ Called when a session is deleted. The *sender* is the session. """) session_block_deleted = _signals.signal('session-block-deleted', """ Called when a session block is deleted. The *sender* is the session block. This signal is called before the ``db.session.delete()`` on the block is executed. """) timetable_buttons = _signals.signal('timetable-buttons', """ Expected to return a list of tuples ('button_name', 'js-call-class'). Called when building the timetable view. """) get_log_renderers = _signals.signal('get-log-renderers', """ Expected to return `EventLogRenderer` classes. """) get_feature_definitions = _signals.signal('get-feature-definitions', """ Expected to return `EventFeature` subclasses. """) metadata_postprocess = _signals.signal('metadata-postprocess', """ Called right after a dict-like representation of an event is created, so that plugins can add their own fields. The *sender* is a string parameter specifying the source of the metadata. The *event* kwarg contains the event object. The metadata is passed in the `data` kwarg. The signal should return a dict that will be used to update the original representation (fields to add or override). """)
35.804598
81
0.741252
86ca3287dbcbbef744a382d06122c372e95e738d
3,294
py
Python
cinder/tests/unit/volume/drivers/emc/scaleio/test_delete_volume.py
aarunsai81/netapp
8f0f7bf9be7f4d9fb9c3846bfc639c90a05f86ba
[ "Apache-2.0" ]
11
2015-08-25T13:11:18.000Z
2020-10-15T11:29:20.000Z
cinder/tests/unit/volume/drivers/emc/scaleio/test_delete_volume.py
aarunsai81/netapp
8f0f7bf9be7f4d9fb9c3846bfc639c90a05f86ba
[ "Apache-2.0" ]
5
2018-01-25T11:31:56.000Z
2019-05-06T23:13:35.000Z
cinder/tests/unit/volume/drivers/emc/scaleio/test_delete_volume.py
aarunsai81/netapp
8f0f7bf9be7f4d9fb9c3846bfc639c90a05f86ba
[ "Apache-2.0" ]
11
2015-02-20T18:48:24.000Z
2021-01-30T20:26:18.000Z
# Copyright (c) 2013 - 2015 EMC Corporation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from six.moves import urllib from cinder import context from cinder import exception from cinder.tests.unit import fake_constants as fake from cinder.tests.unit import fake_volume from cinder.tests.unit.volume.drivers.emc import scaleio from cinder.tests.unit.volume.drivers.emc.scaleio import mocks
39.686747
78
0.610808
86ca3cb4e460e6fa964047e9d8e3d1c032b0dafb
1,233
py
Python
example-package/transportation_tutorials/__init__.py
chrisc20042001/python-for-transportation-modeling
677129daa390fcaa6e5cde45960e27d9bd6ca4bf
[ "BSD-3-Clause" ]
null
null
null
example-package/transportation_tutorials/__init__.py
chrisc20042001/python-for-transportation-modeling
677129daa390fcaa6e5cde45960e27d9bd6ca4bf
[ "BSD-3-Clause" ]
null
null
null
example-package/transportation_tutorials/__init__.py
chrisc20042001/python-for-transportation-modeling
677129daa390fcaa6e5cde45960e27d9bd6ca4bf
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- __version__ = '1.0.2' import os import appdirs import osmnx as ox import joblib import requests from .files import load_vars, save_vars, cached, inflate_tar, download_zipfile from .data import data, list_data, problematic from .tools.view_code import show_file from . import mapping cache_dir = None memory = None def set_cache_dir(location=None, compress=True, verbose=0, **kwargs): """ Set up a cache directory for use with the tutorials. Parameter --------- cache_dir : Path-like or False, optional A path for the cache files. Set to False to disable caching. """ global memory, cache_dir if location is None: location = appdirs.user_cache_dir('transportation_tutorials') if location is False: location = None memory = joblib.Memory(location, compress=compress, verbose=verbose, **kwargs) make_cache = ( (ox, 'gdf_from_place'), (ox, 'graph_from_bbox'), (requests, 'get'), (requests, 'post'), ) for module, func_name in make_cache: try: func = getattr(module, f"_{func_name}_orig") except AttributeError: func = getattr(module, func_name) setattr(module, f"_{func_name}_orig", func) setattr(module, func_name, memory.cache(func)) set_cache_dir()
20.55
79
0.721006
86ca8c2e422d5ab12a80680e14af6535e5befd05
2,146
py
Python
common/common.py
czajowaty/curry-bot
91bfbd884342a02c6defd057d27d5b1fcd78cb21
[ "MIT" ]
3
2019-10-09T23:17:55.000Z
2022-02-01T17:34:27.000Z
common/common.py
czajowaty/curry-bot
91bfbd884342a02c6defd057d27d5b1fcd78cb21
[ "MIT" ]
19
2019-10-09T20:42:05.000Z
2022-02-01T08:22:25.000Z
common/common.py
czajowaty/curry-bot
91bfbd884342a02c6defd057d27d5b1fcd78cb21
[ "MIT" ]
6
2020-08-09T20:17:13.000Z
2022-01-27T23:59:28.000Z
from requests.models import PreparedRequest
32.029851
152
0.56384
86cbceec04afe24550cbee582258380f822dc77d
5,265
py
Python
hendrix/test/test_ux.py
anthonyalmarza/hendrix
eebd2a2183cc18ec2267d96a53a70d41b1630ce6
[ "MIT" ]
null
null
null
hendrix/test/test_ux.py
anthonyalmarza/hendrix
eebd2a2183cc18ec2267d96a53a70d41b1630ce6
[ "MIT" ]
null
null
null
hendrix/test/test_ux.py
anthonyalmarza/hendrix
eebd2a2183cc18ec2267d96a53a70d41b1630ce6
[ "MIT" ]
null
null
null
import os import sys from . import HendrixTestCase, TEST_SETTINGS from hendrix.contrib import SettingsError from hendrix.options import options as hx_options from hendrix import ux from mock import patch
35.816327
77
0.637607
86cc1ac4bd0be7cfc736232b574de4d27f85e0ca
6,656
py
Python
discord/types/interactions.py
Voxel-Fox-Ltd/Novus
3e254115daf1c09455b26dc7819b73fbf5ee56e5
[ "MIT" ]
61
2021-08-30T05:30:31.000Z
2022-03-24T11:24:38.000Z
discord/types/interactions.py
Voxel-Fox-Ltd/Novus
3e254115daf1c09455b26dc7819b73fbf5ee56e5
[ "MIT" ]
30
2021-08-31T10:16:42.000Z
2022-03-09T22:53:15.000Z
discord/types/interactions.py
Voxel-Fox-Ltd/Novus
3e254115daf1c09455b26dc7819b73fbf5ee56e5
[ "MIT" ]
15
2021-09-02T09:40:58.000Z
2022-02-25T12:19:02.000Z
""" The MIT License (MIT) Copyright (c) 2015-2021 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import annotations from typing import Optional, TYPE_CHECKING, Dict, TypedDict, Union, List, Literal from .snowflake import Snowflake from .components import Component, SelectOption from .embed import Embed from .channel import ChannelType, Channel from .member import Member from .role import Role from .user import User if TYPE_CHECKING: from .message import AllowedMentions, Message ApplicationCommandType = Literal[1, 2, 3] ApplicationCommandOptionType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ApplicationCommandPermissionType = Literal[1, 2] InteractionType = Literal[1, 2, 3] ApplicationCommandInteractionDataOption = Union[ _ApplicationCommandInteractionDataOptionString, _ApplicationCommandInteractionDataOptionInteger, _ApplicationCommandInteractionDataOptionSubcommand, _ApplicationCommandInteractionDataOptionBoolean, _ApplicationCommandInteractionDataOptionSnowflake, _ApplicationCommandInteractionDataOptionNumber, ] InteractionResponseType = Literal[1, 4, 5, 6, 7]
27.618257
99
0.790415
86cc747c2e5f0caead634114a98e5f4a747d16ea
15,163
py
Python
local/local_sign.py
EVAyo/chaoxing_auto_sign
7ae91a5e9aa4d15f57a5419ff3f5a455e151930a
[ "MIT" ]
null
null
null
local/local_sign.py
EVAyo/chaoxing_auto_sign
7ae91a5e9aa4d15f57a5419ff3f5a455e151930a
[ "MIT" ]
null
null
null
local/local_sign.py
EVAyo/chaoxing_auto_sign
7ae91a5e9aa4d15f57a5419ff3f5a455e151930a
[ "MIT" ]
null
null
null
# -*- coding: utf8 -*- import os import re import time import json import random import asyncio from typing import Optional, List, Dict from aiohttp import ClientSession from aiohttp.cookiejar import SimpleCookie from lxml import etree from bs4 import BeautifulSoup from config import * from message import server_chan_send def save_cookies(self, cookies: dict): """cookies""" with open(COOKIES_FILE_PATH, "r") as f: data = json.load(f) data[self.username] = cookies with open(COOKIES_FILE_PATH, 'w') as f2: json.dump(data, f2) def check_activeid(self, activeid): """activeid""" activeid += self.username if "activeid.json" not in os.listdir(ACTIVEID_PATH): with open(ACTIVEID_FILE_PATH, 'w+') as f: f.write("{}") with open(ACTIVEID_FILE_PATH, 'r') as f: try: # data = json.load(f) if data[activeid]: return True except BaseException: # activeid return False def save_activeid(self, activeid): """activeid""" activeid += self.username if "activeid.json" not in os.listdir(ACTIVEID_PATH): with open(ACTIVEID_FILE_PATH, 'w+') as f: f.write("{}") with open(ACTIVEID_FILE_PATH, 'r') as f: data = json.load(f) with open(ACTIVEID_FILE_PATH, 'w') as f2: data[activeid] = True json.dump(data, f2)
33.770601
149
0.485722
86ccfd65a1bb34c39113feed67502cda22587b34
4,240
py
Python
build/scripts-3.6/fit_background_model.py
stahlberggroup/umierrorcorrect
8ceabe30a87811dad467d04eb5a08d0213065946
[ "MIT" ]
null
null
null
build/scripts-3.6/fit_background_model.py
stahlberggroup/umierrorcorrect
8ceabe30a87811dad467d04eb5a08d0213065946
[ "MIT" ]
null
null
null
build/scripts-3.6/fit_background_model.py
stahlberggroup/umierrorcorrect
8ceabe30a87811dad467d04eb5a08d0213065946
[ "MIT" ]
1
2022-01-12T13:51:59.000Z
2022-01-12T13:51:59.000Z
#!python import numpy as np from numpy import inf from numpy import nan from scipy.optimize import fmin from scipy.stats import beta from scipy.special import beta as B from scipy.special import comb import argparse import sys def parseArgs(): '''Function for parsing arguments''' parser = argparse.ArgumentParser(description="Pipeline for analyzing barcoded amplicon \ sequencing data with Unique molecular \ identifiers (UMI)") parser.add_argument('-cons', '--cons_file', dest='cons_file', help='Path to cons file, for fitting parameters of the bgmodel') parser.add_argument('-nonbgposfile', '--non-background-positions', dest='nonbgposfile', help='Path to file with non-background positions') parser.add_argument('-out', '--out_file',dest='out_file',help="name of output file, default = %(default)s]",default="bgmodel.params") parser.add_argument('-f','--fsize',dest='fsize', help='Family size cutoff (consensus cutoff) for variant calling. [default = %(default)s]', default=3) args = parser.parse_args(sys.argv[1:]) return(args) if __name__=='__main__': args=parseArgs() run_fit_bgmodel(args)
35.932203
154
0.566274
86cdf766574c9c743ff631f5d4070feb9f763d2a
7,654
py
Python
caffe2/python/operator_test/partition_ops_test.py
KevinKecc/caffe2
a2b6c6e2f0686358a84277df65e9489fb7d9ddb2
[ "Apache-2.0" ]
585
2015-08-10T02:48:52.000Z
2021-12-01T08:46:59.000Z
caffe2/python/operator_test/partition_ops_test.py
mingzhe09088/caffe2
8f41717c46d214aaf62b53e5b3b9b308b5b8db91
[ "Apache-2.0" ]
27
2018-04-14T06:44:22.000Z
2018-08-01T18:02:39.000Z
caffe2/python/operator_test/partition_ops_test.py
mingzhe09088/caffe2
8f41717c46d214aaf62b53e5b3b9b308b5b8db91
[ "Apache-2.0" ]
183
2015-08-10T02:49:04.000Z
2021-12-01T08:47:13.000Z
# Copyright (c) 2016-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core, workspace from caffe2.python.test_util import TestCase, rand_array if __name__ == "__main__": import unittest unittest.main()
38.852792
80
0.468774
86ce2b47e96edc2e4a65e6684b182564c236c3d3
11,195
py
Python
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_fib_common_cfg.py
Maikor/ydk-py
b86c4a7c570ae3b2c5557d098420446df5de4929
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_fib_common_cfg.py
Maikor/ydk-py
b86c4a7c570ae3b2c5557d098420446df5de4929
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_fib_common_cfg.py
Maikor/ydk-py
b86c4a7c570ae3b2c5557d098420446df5de4929
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
""" Cisco_IOS_XR_fib_common_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR fib\-common package configuration. This module contains definitions for the following management objects\: fib\: CEF configuration Copyright (c) 2013\-2018 by Cisco Systems, Inc. All rights reserved. """ from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.filters import YFilter from ydk.errors import YError, YModelError from ydk.errors.error_handler import handle_type_error as _handle_type_error
34.875389
184
0.609915
86ce2bcecdfa6edd6bc5db700d444829470b263a
2,888
py
Python
action/combo.py
dl-stuff/dl9
1cbe98afc53a1de9d413797fb130946acc4b6ba4
[ "MIT" ]
null
null
null
action/combo.py
dl-stuff/dl9
1cbe98afc53a1de9d413797fb130946acc4b6ba4
[ "MIT" ]
null
null
null
action/combo.py
dl-stuff/dl9
1cbe98afc53a1de9d413797fb130946acc4b6ba4
[ "MIT" ]
null
null
null
"""Series of actions that form a combo chain""" from __future__ import annotations from typing import Optional, Sequence, TYPE_CHECKING from action import Action from core.utility import Array from core.constants import PlayerForm, SimActKind, MomentType from core.database import FromDB if TYPE_CHECKING: from entity.player import Player
42.470588
138
0.649584
86ce3c0225876fe3453133a9a0965f8f30c17a84
5,447
py
Python
flask_unchained/bundles/session/config.py
achiang/flask-unchained
12788a6e618904a25ff2b571eb05ff1dc8f1840f
[ "MIT" ]
null
null
null
flask_unchained/bundles/session/config.py
achiang/flask-unchained
12788a6e618904a25ff2b571eb05ff1dc8f1840f
[ "MIT" ]
null
null
null
flask_unchained/bundles/session/config.py
achiang/flask-unchained
12788a6e618904a25ff2b571eb05ff1dc8f1840f
[ "MIT" ]
null
null
null
import os from datetime import timedelta from flask_unchained import BundleConfig try: from flask_unchained.bundles.sqlalchemy import db except ImportError: db = None
27.371859
111
0.668258
86ce9b178e942f833e8db993afdcf0aface18b4a
3,845
py
Python
sktime/forecasting/base/adapters/_statsmodels.py
tombh/sktime
53df0b9ed9d1fd800539165c414cc5611bcc56b3
[ "BSD-3-Clause" ]
1
2020-06-02T22:24:44.000Z
2020-06-02T22:24:44.000Z
sktime/forecasting/base/adapters/_statsmodels.py
abhishek-parashar/sktime
1dfce6b41c2acdb576acfc04b09d11bf115c92d1
[ "BSD-3-Clause" ]
1
2020-11-20T13:51:20.000Z
2020-11-20T13:51:20.000Z
sktime/forecasting/base/adapters/_statsmodels.py
abhishek-parashar/sktime
1dfce6b41c2acdb576acfc04b09d11bf115c92d1
[ "BSD-3-Clause" ]
3
2020-10-18T04:54:30.000Z
2021-02-15T18:04:18.000Z
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- __author__ = ["Markus Lning"] __all__ = ["_StatsModelsAdapter"] import numpy as np import pandas as pd from sktime.forecasting.base._base import DEFAULT_ALPHA from sktime.forecasting.base._sktime import _OptionalForecastingHorizonMixin from sktime.forecasting.base._sktime import _SktimeForecaster
32.310924
79
0.628349
86cf3a0a9a0e45685f04435a33dcecfd088782c9
12,924
py
Python
melodic/lib/python2.7/dist-packages/gazebo_msgs/srv/_GetLinkProperties.py
Dieptranivsr/Ros_Diep
d790e75e6f5da916701b11a2fdf3e03b6a47086b
[ "MIT" ]
null
null
null
melodic/lib/python2.7/dist-packages/gazebo_msgs/srv/_GetLinkProperties.py
Dieptranivsr/Ros_Diep
d790e75e6f5da916701b11a2fdf3e03b6a47086b
[ "MIT" ]
1
2021-07-08T10:26:06.000Z
2021-07-08T10:31:11.000Z
melodic/lib/python2.7/dist-packages/gazebo_msgs/srv/_GetLinkProperties.py
Dieptranivsr/Ros_Diep
d790e75e6f5da916701b11a2fdf3e03b6a47086b
[ "MIT" ]
null
null
null
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from gazebo_msgs/GetLinkPropertiesRequest.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct _struct_I = genpy.struct_I # This Python file uses the following encoding: utf-8 """autogenerated by genpy from gazebo_msgs/GetLinkPropertiesResponse.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geometry_msgs.msg _struct_I = genpy.struct_I _struct_7dB7dB = None
37.031519
284
0.638502
86cfbb57e1ec13e6ae0711449af6c95612ae3139
2,268
py
Python
jupytext/kernels.py
st--/jupytext
f8e8352859cc22e17b11154d0770fd946c4a430a
[ "MIT" ]
5,378
2018-09-01T22:03:43.000Z
2022-03-31T06:51:42.000Z
jupytext/kernels.py
st--/jupytext
f8e8352859cc22e17b11154d0770fd946c4a430a
[ "MIT" ]
812
2018-08-31T08:26:13.000Z
2022-03-30T18:12:11.000Z
jupytext/kernels.py
st--/jupytext
f8e8352859cc22e17b11154d0770fd946c4a430a
[ "MIT" ]
380
2018-09-02T01:40:07.000Z
2022-03-25T13:57:23.000Z
"""Find kernel specifications for a given language""" import os import sys from .languages import same_language from .reraise import reraise try: # I prefer not to take a dependency on jupyter_client from jupyter_client.kernelspec import find_kernel_specs, get_kernel_spec except ImportError as err: find_kernel_specs = reraise(err) get_kernel_spec = reraise(err) def set_kernelspec_from_language(notebook): """Set the kernel specification based on the 'main_language' metadata""" language = notebook.metadata.get("jupytext", {}).get("main_language") if "kernelspec" not in notebook.metadata and language: try: kernelspec = kernelspec_from_language(language) except ValueError: return notebook.metadata["kernelspec"] = kernelspec notebook.metadata.get("jupytext", {}).pop("main_language") def kernelspec_from_language(language): """Return the python kernel that matches the current env, or the first kernel that matches the given language""" if language == "python": # Return the kernel that matches the current Python executable for name in find_kernel_specs(): kernel_specs = get_kernel_spec(name) cmd = kernel_specs.argv[0] if ( kernel_specs.language == "python" and os.path.isfile(cmd) and os.path.samefile(cmd, sys.executable) ): return { "name": name, "language": language, "display_name": kernel_specs.display_name, } raise ValueError( "No kernel found that matches the current python executable {}\n".format( sys.executable ) + "Install one with 'python -m ipykernel install --name kernel_name [--user]'" ) for name in find_kernel_specs(): kernel_specs = get_kernel_spec(name) if same_language(kernel_specs.language, language): return { "name": name, "language": language, "display_name": kernel_specs.display_name, } raise ValueError("No kernel found for the language {}".format(language))
36
116
0.622575
86d025f02ce51457ef476e760c051f7660045f69
5,333
py
Python
scipy/sparse/_matrix_io.py
dhruv9vats/scipy
48e1dd7e604df3ae57d104b407c5b7a2a6a3247d
[ "BSD-3-Clause" ]
1
2021-08-16T09:32:42.000Z
2021-08-16T09:32:42.000Z
scipy/sparse/_matrix_io.py
dhruv9vats/scipy
48e1dd7e604df3ae57d104b407c5b7a2a6a3247d
[ "BSD-3-Clause" ]
44
2019-06-27T15:56:14.000Z
2022-03-15T22:21:10.000Z
scipy/sparse/_matrix_io.py
dhruv9vats/scipy
48e1dd7e604df3ae57d104b407c5b7a2a6a3247d
[ "BSD-3-Clause" ]
4
2020-06-13T10:32:25.000Z
2021-12-03T15:48:16.000Z
import numpy as np import scipy.sparse __all__ = ['save_npz', 'load_npz'] # Make loading safe vs. malicious input PICKLE_KWARGS = dict(allow_pickle=False) def save_npz(file, matrix, compressed=True): """ Save a sparse matrix to a file using ``.npz`` format. Parameters ---------- file : str or file-like object Either the file name (string) or an open file (file-like object) where the data will be saved. If file is a string, the ``.npz`` extension will be appended to the file name if it is not already there. matrix: spmatrix (format: ``csc``, ``csr``, ``bsr``, ``dia`` or coo``) The sparse matrix to save. compressed : bool, optional Allow compressing the file. Default: True See Also -------- scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format. numpy.savez: Save several arrays into a ``.npz`` archive. numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive. Examples -------- Store sparse matrix to disk, and load it again: >>> import scipy.sparse >>> sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]])) >>> sparse_matrix <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in Compressed Sparse Column format> >>> sparse_matrix.todense() matrix([[0, 0, 3], [4, 0, 0]], dtype=int64) >>> scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) >>> sparse_matrix = scipy.sparse.load_npz('/tmp/sparse_matrix.npz') >>> sparse_matrix <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in Compressed Sparse Column format> >>> sparse_matrix.todense() matrix([[0, 0, 3], [4, 0, 0]], dtype=int64) """ arrays_dict = {} if matrix.format in ('csc', 'csr', 'bsr'): arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr) elif matrix.format == 'dia': arrays_dict.update(offsets=matrix.offsets) elif matrix.format == 'coo': arrays_dict.update(row=matrix.row, col=matrix.col) else: raise NotImplementedError('Save is not implemented for sparse matrix of format {}.'.format(matrix.format)) arrays_dict.update( format=matrix.format.encode('ascii'), shape=matrix.shape, data=matrix.data ) if compressed: np.savez_compressed(file, **arrays_dict) else: np.savez(file, **arrays_dict) def load_npz(file): """ Load a sparse matrix from a file using ``.npz`` format. Parameters ---------- file : str or file-like object Either the file name (string) or an open file (file-like object) where the data will be loaded. Returns ------- result : csc_matrix, csr_matrix, bsr_matrix, dia_matrix or coo_matrix A sparse matrix containing the loaded data. Raises ------ OSError If the input file does not exist or cannot be read. See Also -------- scipy.sparse.save_npz: Save a sparse matrix to a file using ``.npz`` format. numpy.load: Load several arrays from a ``.npz`` archive. Examples -------- Store sparse matrix to disk, and load it again: >>> import scipy.sparse >>> sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]])) >>> sparse_matrix <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in Compressed Sparse Column format> >>> sparse_matrix.todense() matrix([[0, 0, 3], [4, 0, 0]], dtype=int64) >>> scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) >>> sparse_matrix = scipy.sparse.load_npz('/tmp/sparse_matrix.npz') >>> sparse_matrix <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in Compressed Sparse Column format> >>> sparse_matrix.todense() matrix([[0, 0, 3], [4, 0, 0]], dtype=int64) """ with np.load(file, **PICKLE_KWARGS) as loaded: try: matrix_format = loaded['format'] except KeyError as e: raise ValueError('The file {} does not contain a sparse matrix.'.format(file)) from e matrix_format = matrix_format.item() if not isinstance(matrix_format, str): # Play safe with Python 2 vs 3 backward compatibility; # files saved with SciPy < 1.0.0 may contain unicode or bytes. matrix_format = matrix_format.decode('ascii') try: cls = getattr(scipy.sparse, '{}_matrix'.format(matrix_format)) except AttributeError as e: raise ValueError('Unknown matrix format "{}"'.format(matrix_format)) from e if matrix_format in ('csc', 'csr', 'bsr'): return cls((loaded['data'], loaded['indices'], loaded['indptr']), shape=loaded['shape']) elif matrix_format == 'dia': return cls((loaded['data'], loaded['offsets']), shape=loaded['shape']) elif matrix_format == 'coo': return cls((loaded['data'], (loaded['row'], loaded['col'])), shape=loaded['shape']) else: raise NotImplementedError('Load is not implemented for ' 'sparse matrix of format {}.'.format(matrix_format))
35.553333
114
0.615976
86d07b07d670dc9caa0bd92708721764a364d527
1,423
py
Python
src/simulator/services/resources/atlas.py
ed741/PathBench
50fe138eb1f824f49fe1a862705e435a1c3ec3ae
[ "BSD-3-Clause" ]
46
2020-12-25T04:09:15.000Z
2022-03-25T12:32:42.000Z
src/simulator/services/resources/atlas.py
ed741/PathBench
50fe138eb1f824f49fe1a862705e435a1c3ec3ae
[ "BSD-3-Clause" ]
36
2020-12-21T16:10:02.000Z
2022-01-03T01:42:01.000Z
src/simulator/services/resources/atlas.py
judicaelclair/PathBenchURO
101e67674efdfa8e27e1cf7787dac9fdf99552fe
[ "BSD-3-Clause" ]
11
2021-01-06T23:34:12.000Z
2022-03-21T17:21:47.000Z
from typing import Dict, List from simulator.services.resources.directory import Directory from simulator.services.services import Services
29.040816
97
0.579761
86d18fa6bf233db205e6db3a19952144dd79aa36
1,427
py
Python
ingestion/src/metadata/great_expectations/builders/table/row_count_to_equal.py
ulixius9/OpenMetadata
f121698d968717f0932f685ef2a512c2a4d92438
[ "Apache-2.0" ]
null
null
null
ingestion/src/metadata/great_expectations/builders/table/row_count_to_equal.py
ulixius9/OpenMetadata
f121698d968717f0932f685ef2a512c2a4d92438
[ "Apache-2.0" ]
null
null
null
ingestion/src/metadata/great_expectations/builders/table/row_count_to_equal.py
ulixius9/OpenMetadata
f121698d968717f0932f685ef2a512c2a4d92438
[ "Apache-2.0" ]
null
null
null
# Copyright 2022 Collate # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TestCase builder """ from metadata.generated.schema.api.tests.createTableTest import CreateTableTestRequest from metadata.generated.schema.tests.table import tableRowCountToEqual from metadata.generated.schema.tests.tableTest import TableTestType from metadata.great_expectations.builders.table.base_table_test_builders import ( BaseTableTestBuilder, )
41.970588
86
0.756833
86d22671738e4b0cf43566c5aeec7cd2a5f04193
6,899
py
Python
tensorflow/bbox/jrieke-tf-parse-v2/jrieke_tf_dataset.py
gustavovaliati/obj-det-experiments
e81774a18b34c22d971ad15d7ac6eb8663ac6f22
[ "Apache-2.0" ]
null
null
null
tensorflow/bbox/jrieke-tf-parse-v2/jrieke_tf_dataset.py
gustavovaliati/obj-det-experiments
e81774a18b34c22d971ad15d7ac6eb8663ac6f22
[ "Apache-2.0" ]
null
null
null
tensorflow/bbox/jrieke-tf-parse-v2/jrieke_tf_dataset.py
gustavovaliati/obj-det-experiments
e81774a18b34c22d971ad15d7ac6eb8663ac6f22
[ "Apache-2.0" ]
null
null
null
''' This code is based on https://github.com/jrieke/shape-detection/ ''' import matplotlib.pyplot as plt import matplotlib import numpy as np import tensorflow as tf import datetime
40.582353
142
0.59052
86d39cbeb38ed832359d8101e1462aeccc15eee8
1,400
py
Python
src/knownnodes.py
skeevey/PyBitmessage
196d688b138393d1d540df3322844dfe7e7c02ba
[ "MIT" ]
1
2018-04-25T08:08:47.000Z
2018-04-25T08:08:47.000Z
src/knownnodes.py
skeevey/PyBitmessage
196d688b138393d1d540df3322844dfe7e7c02ba
[ "MIT" ]
null
null
null
src/knownnodes.py
skeevey/PyBitmessage
196d688b138393d1d540df3322844dfe7e7c02ba
[ "MIT" ]
1
2018-04-25T08:08:48.000Z
2018-04-25T08:08:48.000Z
import pickle import threading from bmconfigparser import BMConfigParser import state knownNodesLock = threading.Lock() knownNodes = {} knownNodesTrimAmount = 2000
30.434783
120
0.648571
86d3d194e9e0137871f97d1ad57cf24e9f4a90e3
1,672
py
Python
chroma_agent/action_plugins/manage_node.py
whamcloud/iml-agent
fecb2468fd6edc822f3ab37ced444d98d8725730
[ "MIT" ]
1
2020-04-22T16:43:09.000Z
2020-04-22T16:43:09.000Z
chroma_agent/action_plugins/manage_node.py
AlexTalker/iml-agent
5ebcfe96be670912d9a9b7fbb23431af0d54f768
[ "MIT" ]
53
2018-07-07T18:17:50.000Z
2021-03-19T23:15:28.000Z
chroma_agent/action_plugins/manage_node.py
AlexTalker/iml-agent
5ebcfe96be670912d9a9b7fbb23431af0d54f768
[ "MIT" ]
6
2018-06-18T08:51:38.000Z
2019-10-24T12:16:42.000Z
# Copyright (c) 2018 DDN. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. import os from chroma_agent.lib.shell import AgentShell from chroma_agent.log import console_log from chroma_agent.device_plugins.action_runner import CallbackAfterResponse from chroma_agent.lib.pacemaker import PacemakerConfig ACTIONS = [reboot_server, shutdown_server, fail_node, stonith]
27.866667
75
0.703947
86d45952adaab5e1d25729182d1ca80f64803a29
8,103
py
Python
census_data_downloader/core/tables.py
ian-r-rose/census-data-downloader
f8ac9d773e6d3f52be87bf916a2e32249391f966
[ "MIT" ]
null
null
null
census_data_downloader/core/tables.py
ian-r-rose/census-data-downloader
f8ac9d773e6d3f52be87bf916a2e32249391f966
[ "MIT" ]
null
null
null
census_data_downloader/core/tables.py
ian-r-rose/census-data-downloader
f8ac9d773e6d3f52be87bf916a2e32249391f966
[ "MIT" ]
null
null
null
#! /usr/bin/env python # -*- coding: utf-8 -* """ A base class that governs how to download and process tables from a Census API table. """ import os import logging import pathlib from . import geotypes from . import decorators logger = logging.getLogger(__name__)
28.038062
96
0.60817
86d61d512c3c9d47b1f63fe91873604a549e077d
5,422
py
Python
sgf2ebook.py
loujine/sgf2ebook
13c87056646cc6c06485b129221ab2028e67ef95
[ "MIT" ]
null
null
null
sgf2ebook.py
loujine/sgf2ebook
13c87056646cc6c06485b129221ab2028e67ef95
[ "MIT" ]
null
null
null
sgf2ebook.py
loujine/sgf2ebook
13c87056646cc6c06485b129221ab2028e67ef95
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import argparse import os from pathlib import Path import shutil import subprocess import sys from tempfile import TemporaryDirectory from uuid import uuid4 from zipfile import ZipFile import jinja2 import sente # type: ignore __version__ = (1, 0, 0) SGF_RENDER_EXECUTABLE = './sgf-render' TEMPLATEDIR = Path(__file__, '..', 'epub_template').resolve() if __name__ == "__main__": parser = argparse.ArgumentParser( description='') parser.add_argument('--input-path', '-i', help='Input files or directory') parser.add_argument('--output-path', '-o', help='Output directory') args = parser.parse_args() path = Path(args.input_path) outpath = Path(args.output_path) if not path.exists(): print(f'Input path {path} not found') sys.exit(1) if path.is_file(): main(path, outpath) if path.is_dir(): for filepath in sorted(path.rglob('*.sgf')): main(filepath, outpath.joinpath(filepath.parent.relative_to(path)))
34.75641
142
0.574511
86d75a7478a79891b6baf0f18c7802c22b104725
918
py
Python
dandeliondiary/household/urls.py
amberdiehl/dandeliondiary_project
e9bace5bd7980def6ca763840ab5b38f1e05cd3d
[ "FSFAP" ]
null
null
null
dandeliondiary/household/urls.py
amberdiehl/dandeliondiary_project
e9bace5bd7980def6ca763840ab5b38f1e05cd3d
[ "FSFAP" ]
6
2020-04-29T23:54:15.000Z
2022-03-11T23:25:24.000Z
dandeliondiary/household/urls.py
amberdiehl/dandeliondiary_project
e9bace5bd7980def6ca763840ab5b38f1e05cd3d
[ "FSFAP" ]
null
null
null
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^settings$', views.household_dashboard, name='household_dashboard'), url(r'^myinfo$', views.my_info, name='my_info'), url(r'^profile$', views.household_profile, name='maintain_household'), url(r'^members$', views.household_members, name='maintain_members'), url(r'^vehicles$', views.household_vehicles, name='maintain_vehicles'), url(r'^ajax/models-by-make/(?P<make_id>\d+)/$', views.ajax_models_by_make), url(r'^ajax/makes-by-type/(?P<type_id>\d+)/$', views.ajax_makes_by_type), url(r'^ajax/add-make/(?P<type_key>\d+)/(?P<make>[\w ]{1,50})/$', views.ajax_add_make), url(r'^ajax/add-model/(?P<make_key>\d+)/(?P<model>[\w -]{1,128})/$', views.ajax_add_model), url(r'^ajax/delete-invite/$', views.ajax_delete_invite), url(r'^ajax/change-member-status/$', views.ajax_change_member_status), ]
54
95
0.683007
86d75f7e9a302f49289d9be8498b550dc47650fa
79,634
py
Python
private/templates/NYC/config.py
devinbalkind/eden
d5a684eae537432eb2c7d954132484a4714ca8fb
[ "MIT" ]
null
null
null
private/templates/NYC/config.py
devinbalkind/eden
d5a684eae537432eb2c7d954132484a4714ca8fb
[ "MIT" ]
null
null
null
private/templates/NYC/config.py
devinbalkind/eden
d5a684eae537432eb2c7d954132484a4714ca8fb
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- try: # Python 2.7 from collections import OrderedDict except: # Python 2.6 from gluon.contrib.simplejson.ordered_dict import OrderedDict from gluon import current from gluon.html import A, URL from gluon.storage import Storage from s3 import s3_fullname T = current.T settings = current.deployment_settings """ Template settings for NYC Prepared """ # Pre-Populate settings.base.prepopulate = ("NYC",) settings.base.system_name = T("NYC Prepared") settings.base.system_name_short = T("NYC Prepared") # Theme (folder to use for views/layout.html) settings.base.theme = "NYC" settings.ui.formstyle_row = "bootstrap" settings.ui.formstyle = "bootstrap" settings.ui.filter_formstyle = "table_inline" settings.msg.parser = "NYC" # Uncomment to Hide the language toolbar settings.L10n.display_toolbar = False # Default timezone for users settings.L10n.utc_offset = "UTC -0500" # Uncomment these to use US-style dates in English settings.L10n.date_format = "%m-%d-%Y" # Start week on Sunday settings.L10n.firstDOW = 0 # Number formats (defaults to ISO 31-0) # Decimal separator for numbers (defaults to ,) settings.L10n.decimal_separator = "." # Thousands separator for numbers (defaults to space) settings.L10n.thousands_separator = "," # Default Country Code for telephone numbers settings.L10n.default_country_code = 1 # Enable this to change the label for 'Mobile Phone' settings.ui.label_mobile_phone = "Cell Phone" # Enable this to change the label for 'Postcode' settings.ui.label_postcode = "ZIP Code" # Uncomment to disable responsive behavior of datatables # - Disabled until tested settings.ui.datatables_responsive = False # PDF to Letter settings.base.paper_size = T("Letter") # Restrict the Location Selector to just certain countries # NB This can also be over-ridden for specific contexts later # e.g. Activities filtered to those of parent Project settings.gis.countries = ("US",) settings.fin.currencies = { "USD" : T("United States Dollars"), } settings.L10n.languages = OrderedDict([ ("en", "English"), ("es", "Espaol"), ]) # Authentication settings # These settings should be changed _after_ the 1st (admin) user is # registered in order to secure the deployment # Should users be allowed to register themselves? settings.security.self_registration = "index" # Do new users need to verify their email address? settings.auth.registration_requires_verification = True # Do new users need to be approved by an administrator prior to being able to login? settings.auth.registration_requires_approval = True # Always notify the approver of a new (verified) user, even if the user is automatically approved #settings.auth.always_notify_approver = False # Uncomment this to request the Mobile Phone when a user registers settings.auth.registration_requests_mobile_phone = True # Uncomment this to request the Organisation when a user registers settings.auth.registration_requests_organisation = True # Uncomment this to request the Site when a user registers #settings.auth.registration_requests_site = True # Roles that newly-registered users get automatically #settings.auth.registration_roles = { 0: ["comms_dispatch"]} #settings.auth.registration_link_user_to = {"staff":T("Staff"), # #"volunteer":T("Volunteer") # } settings.auth.registration_link_user_to_default = "staff" settings.security.policy = 5 # Controller, Function & Table ACLs # Enable this to have Open links in IFrames open a full page in a new tab settings.ui.iframe_opens_full = True settings.ui.label_attachments = "Media" settings.ui.update_label = "Edit" # Uncomment to disable checking that LatLons are within boundaries of their parent #settings.gis.check_within_parent_boundaries = False # GeoNames username settings.gis.geonames_username = "eden_nyc" # Uncomment to show created_by/modified_by using Names not Emails settings.ui.auth_user_represent = "name" # Record Approval settings.auth.record_approval = True settings.auth.record_approval_required_for = ("org_organisation",) # ----------------------------------------------------------------------------- # Audit settings.security.audit_write = audit_write # ----------------------------------------------------------------------------- # CMS # Uncomment to use Bookmarks in Newsfeed settings.cms.bookmarks = True # Uncomment to use have Filter form in Newsfeed be open by default settings.cms.filter_open = True # Uncomment to adjust filters in Newsfeed when clicking on locations instead of opening the profile page settings.cms.location_click_filters = True # Uncomment to use organisation_id instead of created_by in Newsfeed settings.cms.organisation = "post_organisation.organisation_id" # Uncomment to use org_group_id in Newsfeed settings.cms.organisation_group = "post_organisation_group.group_id" # Uncomment to use person_id instead of created_by in Newsfeed settings.cms.person = "person_id" # Uncomment to use Rich Text editor in Newsfeed settings.cms.richtext = True # Uncomment to show Links in Newsfeed settings.cms.show_links = True # Uncomment to show Tags in Newsfeed settings.cms.show_tags = True # Uncomment to show post Titles in Newsfeed settings.cms.show_titles = True # ----------------------------------------------------------------------------- # Inventory Management # Uncomment to customise the label for Facilities in Inventory Management settings.inv.facility_label = "Facility" # Uncomment if you need a simpler (but less accountable) process for managing stock levels #settings.inv.direct_stock_edits = True # Uncomment to call Stock Adjustments, 'Stock Counts' settings.inv.stock_count = True # Uncomment to not track pack values settings.inv.track_pack_values = False settings.inv.send_show_org = False # Types common to both Send and Receive settings.inv.shipment_types = { 1: T("Other Warehouse") } settings.inv.send_types = { #21: T("Distribution") } settings.inv.send_type_default = 1 settings.inv.item_status = { #0: current.messages["NONE"], #1: T("Dump"), #2: T("Sale"), #3: T("Reject"), #4: T("Surplus") } # ----------------------------------------------------------------------------- # Organisations # # Enable the use of Organisation Groups settings.org.groups = "Network" # Make Services Hierarchical settings.org.services_hierarchical = True # Set the label for Sites settings.org.site_label = "Facility" #settings.org.site_label = "Location" # Uncomment to show the date when a Site (Facilities-only for now) was last contacted settings.org.site_last_contacted = True # Enable certain fields just for specific Organisations # empty list => disabled for all (including Admin) #settings.org.dependent_fields = { \ # "pr_person_details.mother_name" : [], # "pr_person_details.father_name" : [], # "pr_person_details.company" : [], # "pr_person_details.affiliations" : [], # "vol_volunteer.active" : [], # "vol_volunteer_cluster.vol_cluster_type_id" : [], # "vol_volunteer_cluster.vol_cluster_id" : [], # "vol_volunteer_cluster.vol_cluster_position_id" : [], # } # Uncomment to use an Autocomplete for Site lookup fields settings.org.site_autocomplete = True # Extra fields to search in Autocompletes & display in Representations settings.org.site_autocomplete_fields = ("organisation_id$name", "location_id$addr_street", ) # Uncomment to hide inv & req tabs from Sites #settings.org.site_inv_req_tabs = True # ----------------------------------------------------------------------------- def facility_marker_fn(record): """ Function to decide which Marker to use for Facilities Map @ToDo: Legend """ db = current.db s3db = current.s3db table = db.org_facility_type ltable = db.org_site_facility_type query = (ltable.site_id == record.site_id) & \ (ltable.facility_type_id == table.id) rows = db(query).select(table.name) types = [row.name for row in rows] # Use Marker in preferential order if "Hub" in types: marker = "warehouse" elif "Medical Clinic" in types: marker = "hospital" elif "Food" in types: marker = "food" elif "Relief Site" in types: marker = "asset" elif "Residential Building" in types: marker = "residence" #elif "Shelter" in types: # marker = "shelter" else: # Unknown marker = "office" if settings.has_module("req"): # Colour code by open/priority requests reqs = record.reqs if reqs == 3: # High marker = "%s_red" % marker elif reqs == 2: # Medium marker = "%s_yellow" % marker elif reqs == 1: # Low marker = "%s_green" % marker mtable = db.gis_marker try: marker = db(mtable.name == marker).select(mtable.image, mtable.height, mtable.width, cache=s3db.cache, limitby=(0, 1) ).first() except: marker = db(mtable.name == "office").select(mtable.image, mtable.height, mtable.width, cache=s3db.cache, limitby=(0, 1) ).first() return marker # ----------------------------------------------------------------------------- def org_facility_onvalidation(form): """ Default the name to the Street Address """ form_vars = form.vars name = form_vars.get("name", None) if name: return address = form_vars.get("address", None) if address: form_vars.name = address else: # We need a default form_vars.name = current.db.org_facility.location_id.represent(form_vars.location_id) # ----------------------------------------------------------------------------- settings.customise_org_facility_controller = customise_org_facility_controller # ----------------------------------------------------------------------------- settings.customise_org_organisation_resource = customise_org_organisation_resource # ----------------------------------------------------------------------------- settings.customise_org_organisation_controller = customise_org_organisation_controller # ----------------------------------------------------------------------------- settings.customise_org_group_controller = customise_org_group_controller # ----------------------------------------------------------------------------- # Persons # Uncomment to hide fields in S3AddPersonWidget settings.pr.request_dob = False settings.pr.request_gender = False # Doesn't yet work (form fails to submit) #settings.pr.select_existing = False settings.pr.show_emergency_contacts = False # ----------------------------------------------------------------------------- # Persons settings.customise_pr_person_controller = customise_pr_person_controller # ----------------------------------------------------------------------------- # Groups def chairperson(row): """ Virtual Field to show the chairperson of a group """ if hasattr(row, "pr_group"): row = row.pr_group try: group_id = row.id except: # not available return current.messages["NONE"] db = current.db mtable = current.s3db.pr_group_membership ptable = db.pr_person query = (mtable.group_id == group_id) & \ (mtable.group_head == True) & \ (mtable.person_id == ptable.id) chair = db(query).select(ptable.first_name, ptable.middle_name, ptable.last_name, ptable.id, limitby=(0, 1)).first() if chair: # Only used in list view so HTML is OK return A(s3_fullname(chair), _href=URL(c="hrm", f="person", args=chair.id)) else: return current.messages["NONE"] # ----------------------------------------------------------------------------- settings.customise_pr_group_controller = customise_pr_group_controller # ----------------------------------------------------------------------------- def customise_pr_group_resource(r, tablename): """ Customise pr_group resource (in group & org_group controllers) - runs after controller customisation - but runs before prep """ s3db = current.s3db table = s3db.pr_group field = table.group_type field.default = 3 # Relief Team, to show up in hrm/group field.readable = field.writable = False table.name.label = T("Name") table.description.label = T("Description") table.meetings.readable = table.meetings.writable = True # Increase size of widget from s3 import s3_comments_widget table.description.widget = s3_comments_widget from gluon import Field table.chairperson = Field.Method("chairperson", chairperson) # Format for filter_widgets & imports s3db.add_components("pr_group", org_group_team = "group_id", ) s3db.configure("pr_group", # Redirect to member list when a new group has been created create_next = URL(c="hrm", f="group", args=["[id]", "group_membership"]), ) settings.customise_pr_group_resource = customise_pr_group_resource # ----------------------------------------------------------------------------- def pr_contact_postprocess(form): """ Import Organisation/Network RSS Feeds """ s3db = current.s3db form_vars = form.vars rss_url = form_vars.rsscontact_i_value_edit_0 or \ form_vars.rsscontact_i_value_edit_none if not rss_url: if form.record: # Update form old_rss = form.record.sub_rsscontact import json data = old_rss = json.loads(old_rss)["data"] if data: # RSS feed is being deleted, so we should disable it old_rss = data[0]["value"]["value"] table = s3db.msg_rss_channel old = current.db(table.url == old_rss).select(table.channel_id, table.enabled, limitby = (0, 1) ).first() if old and old.enabled: s3db.msg_channel_disable("msg_rss_channel", old.channel_id) return else: # Nothing to do :) return # Check if we already have a channel for this Contact db = current.db name = form_vars.name table = s3db.msg_rss_channel name_exists = db(table.name == name).select(table.id, table.channel_id, table.enabled, table.url, limitby = (0, 1) ).first() no_import = current.request.post_vars.get("rss_no_import", None) if name_exists: if name_exists.url == rss_url: # No change to either Contact Name or URL if no_import: if name_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", name_exists.channel_id) return elif name_exists.enabled: # Nothing to do :) return else: # Enable channel (& associated parsers) s3db.msg_channel_enable("msg_rss_channel", name_exists.channel_id) return # Check if we already have a channel for this URL url_exists = db(table.url == rss_url).select(table.id, table.channel_id, table.enabled, limitby = (0, 1) ).first() if url_exists: # We have 2 feeds: 1 for the Contact & 1 for the URL # Disable the old Contact one and link the URL one to this Contact # and ensure active or not as appropriate # Name field is unique so rename old one name_exists.update_record(name="%s (Old)" % name) if name_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", name_exists.channel_id) url_exists.update_record(name=name) if no_import: if url_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", url_exists.channel_id) return elif url_exists.enabled: # Nothing to do :) return else: # Enable channel (& associated parsers) s3db.msg_channel_enable("msg_rss_channel", url_exists.channel_id) return else: # Update the URL name_exists.update_record(url=rss_url) if no_import: if name_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", name_exists.channel_id) return elif name_exists.enabled: # Nothing to do :) return else: # Enable channel (& associated parsers) s3db.msg_channel_enable("msg_rss_channel", name_exists.channel_id) return else: # Check if we already have a channel for this URL url_exists = db(table.url == rss_url).select(table.id, table.channel_id, table.enabled, limitby = (0, 1) ).first() if url_exists: # Either Contact has changed Name or this feed is associated with # another Contact # - update Feed name url_exists.update_record(name=name) if no_import: if url_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", url_exists.channel_id) return elif url_exists.enabled: # Nothing to do :) return else: # Enable channel (& associated parsers) s3db.msg_channel_enable("msg_rss_channel", url_exists.channel_id) return elif no_import: # Nothing to do :) return #else: # # Create a new Feed # pass # Add RSS Channel _id = table.insert(name=name, enabled=True, url=rss_url) record = dict(id=_id) s3db.update_super(table, record) # Enable channel_id = record["channel_id"] s3db.msg_channel_enable("msg_rss_channel", channel_id) # Setup Parser table = s3db.msg_parser _id = table.insert(channel_id=channel_id, function_name="parse_rss", enabled=True) s3db.msg_parser_enable(_id) # Check Now async = current.s3task.async async("msg_poll", args=["msg_rss_channel", channel_id]) async("msg_parse", args=[channel_id, "parse_rss"]) # ----------------------------------------------------------------------------- # Human Resource Management # Uncomment to chage the label for 'Staff' settings.hrm.staff_label = "Contacts" # Uncomment to allow Staff & Volunteers to be registered without an email address settings.hrm.email_required = False # Uncomment to allow Staff & Volunteers to be registered without an Organisation settings.hrm.org_required = False # Uncomment to show the Organisation name in HR represents settings.hrm.show_organisation = True # Uncomment to disable Staff experience settings.hrm.staff_experience = False # Uncomment to disable the use of HR Certificates settings.hrm.use_certificates = False # Uncomment to disable the use of HR Credentials settings.hrm.use_credentials = False # Uncomment to enable the use of HR Education settings.hrm.use_education = False # Uncomment to disable the use of HR Skills #settings.hrm.use_skills = False # Uncomment to disable the use of HR Trainings settings.hrm.use_trainings = False # Uncomment to disable the use of HR Description settings.hrm.use_description = False # Change the label of "Teams" to "Groups" settings.hrm.teams = "Groups" # Custom label for Organisations in HR module #settings.hrm.organisation_label = "National Society / Branch" settings.hrm.organisation_label = "Organization" # ----------------------------------------------------------------------------- settings.customise_hrm_human_resource_controller = customise_hrm_human_resource_controller # ----------------------------------------------------------------------------- def customise_hrm_human_resource_resource(r, tablename): """ Customise hrm_human_resource resource (in facility, human_resource, organisation & person controllers) - runs after controller customisation - but runs before prep """ s3db = current.s3db from s3 import S3SQLCustomForm, S3SQLInlineComponent crud_form = S3SQLCustomForm("person_id", "organisation_id", "site_id", S3SQLInlineComponent( "group_person", label = T("Network"), link = False, fields = [("", "group_id")], multiple = False, ), "job_title_id", "start_date", ) list_fields = ["id", "person_id", "job_title_id", "organisation_id", (T("Network"), "group_person.group_id"), (T("Groups"), "person_id$group_membership.group_id"), "site_id", #"site_contact", (T("Email"), "email.value"), (settings.get_ui_label_mobile_phone(), "phone.value"), ] s3db.configure("hrm_human_resource", crud_form = crud_form, list_fields = list_fields, ) settings.customise_hrm_human_resource_resource = customise_hrm_human_resource_resource # ----------------------------------------------------------------------------- settings.customise_hrm_job_title_controller = customise_hrm_job_title_controller # ----------------------------------------------------------------------------- # Projects # Use codes for projects (called 'blurb' in NYC) settings.project.codes = True # Uncomment this to use settings suitable for detailed Task management settings.project.mode_task = False # Uncomment this to use Activities for projects settings.project.activities = True # Uncomment this to use Milestones in project/task. settings.project.milestones = False # Uncomment this to disable Sectors in projects settings.project.sectors = False # Multiple partner organizations settings.project.multiple_organisations = True settings.customise_project_project_controller = customise_project_project_controller # ----------------------------------------------------------------------------- # Requests Management settings.req.req_type = ["People", "Stock"]#, "Summary"] settings.req.prompt_match = False #settings.req.use_commit = False settings.req.requester_optional = True settings.req.date_writable = False settings.req.item_quantities_writable = True settings.req.skill_quantities_writable = True settings.req.items_ask_purpose = False #settings.req.use_req_number = False # Label for Requester settings.req.requester_label = "Site Contact" # Filter Requester as being from the Site settings.req.requester_from_site = True # Label for Inventory Requests settings.req.type_inv_label = "Supplies" # Uncomment to enable Summary 'Site Needs' tab for Offices/Facilities settings.req.summary = True # ----------------------------------------------------------------------------- def req_req_postprocess(form): """ Runs after crud_form completes - creates a cms_post in the newswire - @ToDo: Send out Tweets """ req_id = form.vars.id db = current.db s3db = current.s3db rtable = s3db.req_req # Read the full record row = db(rtable.id == req_id).select(rtable.type, rtable.site_id, rtable.requester_id, rtable.priority, rtable.date_required, rtable.purpose, rtable.comments, limitby=(0, 1) ).first() # Build Title & Body from the Request details priority = rtable.priority.represent(row.priority) date_required = row.date_required if date_required: date = rtable.date_required.represent(date_required) title = "%(priority)s by %(date)s" % dict(priority=priority, date=date) else: title = priority body = row.comments if row.type == 1: # Items ritable = s3db.req_req_item items = db(ritable.req_id == req_id).select(ritable.item_id, ritable.item_pack_id, ritable.quantity) item_represent = s3db.supply_item_represent pack_represent = s3db.supply_item_pack_represent for item in items: item = "%s %s %s" % (item.quantity, pack_represent(item.item_pack_id), item_represent(item.item_id)) body = "%s\n%s" % (item, body) else: # Skills body = "%s\n%s" % (row.purpose, body) rstable = s3db.req_req_skill skills = db(rstable.req_id == req_id).select(rstable.skill_id, rstable.quantity) skill_represent = s3db.hrm_multi_skill_represent for skill in skills: item = "%s %s" % (skill.quantity, skill_represent(skill.skill_id)) body = "%s\n%s" % (item, body) # Lookup series_id stable = s3db.cms_series try: series_id = db(stable.name == "Request").select(stable.id, cache=s3db.cache, limitby=(0, 1) ).first().id except: # Prepop hasn't been run series_id = None # Location is that of the site otable = s3db.org_site location_id = db(otable.site_id == row.site_id).select(otable.location_id, limitby=(0, 1) ).first().location_id # Create Post ptable = s3db.cms_post _id = ptable.insert(series_id=series_id, title=title, body=body, location_id=location_id, person_id=row.requester_id, ) record = dict(id=_id) s3db.update_super(ptable, record) # Add source link url = "%s%s" % (settings.get_base_public_url(), URL(c="req", f="req", args=req_id)) s3db.doc_document.insert(doc_id=record["doc_id"], url=url, ) # ----------------------------------------------------------------------------- settings.customise_req_req_resource = customise_req_req_resource # ----------------------------------------------------------------------------- # Comment/uncomment modules here to disable/enable them settings.modules = OrderedDict([ # Core modules which shouldn't be disabled ("default", Storage( name_nice = T("Home"), restricted = False, # Use ACLs to control access to this module access = None, # All Users (inc Anonymous) can see this module in the default menu & access the controller module_type = None # This item is not shown in the menu )), ("admin", Storage( name_nice = T("Admin"), #description = "Site Administration", restricted = True, access = "|1|", # Only Administrators can see this module in the default menu & access the controller module_type = None # This item is handled separately for the menu )), ("appadmin", Storage( name_nice = T("Administration"), #description = "Site Administration", restricted = True, module_type = None # No Menu )), ("errors", Storage( name_nice = T("Ticket Viewer"), #description = "Needed for Breadcrumbs", restricted = False, module_type = None # No Menu )), ("sync", Storage( name_nice = T("Synchronization"), #description = "Synchronization", restricted = True, access = "|1|", # Only Administrators can see this module in the default menu & access the controller module_type = None # This item is handled separately for the menu )), # Uncomment to enable internal support requests #("support", Storage( # name_nice = T("Support"), # #description = "Support Requests", # restricted = True, # module_type = None # This item is handled separately for the menu # )), ("gis", Storage( name_nice = T("Map"), #description = "Situation Awareness & Geospatial Analysis", restricted = True, module_type = 9, # 8th item in the menu )), ("pr", Storage( name_nice = T("Person Registry"), #description = "Central point to record details on People", restricted = True, access = "|1|", # Only Administrators can see this module in the default menu (access to controller is possible to all still) module_type = 10 )), ("org", Storage( name_nice = T("Locations"), #description = 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities', restricted = True, module_type = 4 )), # All modules below here should be possible to disable safely ("hrm", Storage( name_nice = T("Contacts"), #description = "Human Resources Management", restricted = True, module_type = 3, )), #("vol", Storage( # name_nice = T("Volunteers"), # #description = "Human Resources Management", # restricted = True, # module_type = 2, # )), ("cms", Storage( name_nice = T("Content Management"), #description = "Content Management System", restricted = True, module_type = 10, )), ("doc", Storage( name_nice = T("Documents"), #description = "A library of digital resources, such as photos, documents and reports", restricted = True, module_type = None, )), ("msg", Storage( name_nice = T("Messaging"), #description = "Sends & Receives Alerts via Email & SMS", restricted = True, # The user-visible functionality of this module isn't normally required. Rather it's main purpose is to be accessed from other modules. module_type = None, )), ("supply", Storage( name_nice = T("Supply Chain Management"), #description = "Used within Inventory Management, Request Management and Asset Management", restricted = True, module_type = None, # Not displayed )), ("inv", Storage( name_nice = T("Inventory"), #description = "Receiving and Sending Items", restricted = True, module_type = 10 )), #("proc", Storage( # name_nice = T("Procurement"), # #description = "Ordering & Purchasing of Goods & Services", # restricted = True, # module_type = 10 # )), ("asset", Storage( name_nice = T("Assets"), #description = "Recording and Assigning Assets", restricted = True, module_type = 10, )), # Vehicle depends on Assets #("vehicle", Storage( # name_nice = T("Vehicles"), # #description = "Manage Vehicles", # restricted = True, # module_type = 10, # )), ("req", Storage( name_nice = T("Requests"), #description = "Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.", restricted = True, module_type = 1, )), ("project", Storage( name_nice = T("Projects"), #description = "Tracking of Projects, Activities and Tasks", restricted = True, module_type = 10 )), ("assess", Storage( name_nice = T("Assessments"), #description = "Rapid Assessments & Flexible Impact Assessments", restricted = True, module_type = 5, )), ("event", Storage( name_nice = T("Events"), #description = "Activate Events (e.g. from Scenario templates) for allocation of appropriate Resources (Human, Assets & Facilities).", restricted = True, module_type = 10, )), ("survey", Storage( name_nice = T("Surveys"), #description = "Create, enter, and manage surveys.", restricted = True, module_type = 5, )), #("cr", Storage( # name_nice = T("Shelters"), # #description = "Tracks the location, capacity and breakdown of victims in Shelters", # restricted = True, # module_type = 10 # )), #("dvr", Storage( # name_nice = T("Disaster Victim Registry"), # #description = "Allow affected individuals & households to register to receive compensation and distributions", # restricted = False, # module_type = 10, # )), #("member", Storage( # name_nice = T("Members"), # #description = "Membership Management System", # restricted = True, # module_type = 10, # )), # @ToDo: Rewrite in a modern style #("budget", Storage( # name_nice = T("Budgeting Module"), # #description = "Allows a Budget to be drawn up", # restricted = True, # module_type = 10 # )), # @ToDo: Port these Assessments to the Survey module #("building", Storage( # name_nice = T("Building Assessments"), # #description = "Building Safety Assessments", # restricted = True, # module_type = 10, # )), ])
39.422772
187
0.470226
86d782fd2d0c71e606843e5d70887529cd2c5a40
106
py
Python
experiments/issue561/v2.py
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
4
2019-04-23T10:41:35.000Z
2019-10-27T05:14:42.000Z
experiments/issue561/v2.py
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
null
null
null
experiments/issue561/v2.py
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
4
2018-01-16T00:00:22.000Z
2019-11-01T23:35:01.000Z
#! /usr/bin/env python # -*- coding: utf-8 -*- from main import main main("issue561-v1", "issue561-v2")
15.142857
34
0.632075
86d8ff6a04670083ea5d1c4de998cdc6916ada2c
4,207
py
Python
q2_qemistree/tests/test_fingerprint.py
tgroth97/q2-qemistree
289c447a6c3a29478bb84212281ef0d7ffc1387a
[ "BSD-2-Clause" ]
null
null
null
q2_qemistree/tests/test_fingerprint.py
tgroth97/q2-qemistree
289c447a6c3a29478bb84212281ef0d7ffc1387a
[ "BSD-2-Clause" ]
null
null
null
q2_qemistree/tests/test_fingerprint.py
tgroth97/q2-qemistree
289c447a6c3a29478bb84212281ef0d7ffc1387a
[ "BSD-2-Clause" ]
null
null
null
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2018, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- from unittest import TestCase, main import qiime2 import os from q2_qemistree import MGFDirFmt, SiriusDirFmt, ZodiacDirFmt, OutputDirs from q2_qemistree import (compute_fragmentation_trees, rerank_molecular_formulas, predict_fingerprints) from q2_qemistree._fingerprint import artifactory if __name__ == '__main__': main()
45.728261
78
0.548134
86d90c0ca6a5dbc266bca705498a4a9e3c8d3aac
721
py
Python
chroma-manager/tests/utils/__init__.py
GarimaVishvakarma/intel-chroma
fdf68ed00b13643c62eb7480754d3216d9295e0b
[ "MIT" ]
null
null
null
chroma-manager/tests/utils/__init__.py
GarimaVishvakarma/intel-chroma
fdf68ed00b13643c62eb7480754d3216d9295e0b
[ "MIT" ]
null
null
null
chroma-manager/tests/utils/__init__.py
GarimaVishvakarma/intel-chroma
fdf68ed00b13643c62eb7480754d3216d9295e0b
[ "MIT" ]
null
null
null
import time import datetime import contextlib
24.033333
74
0.629681
86d90c692c5aa920f75d361edbf2de1c22109ec8
3,518
py
Python
tempo/worker.py
rackerlabs/Tempo
60c2adaf5b592ae171987b999e0b9cc46b80c54e
[ "Apache-2.0" ]
4
2015-04-26T01:46:51.000Z
2020-11-10T13:07:59.000Z
tempo/worker.py
rackerlabs/Tempo
60c2adaf5b592ae171987b999e0b9cc46b80c54e
[ "Apache-2.0" ]
null
null
null
tempo/worker.py
rackerlabs/Tempo
60c2adaf5b592ae171987b999e0b9cc46b80c54e
[ "Apache-2.0" ]
null
null
null
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 Rackspace # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import kombu from tempo import actions from tempo import config from tempo import db from tempo import notifier from tempo import queue as tempo_queue from tempo.openstack.common import cfg from tempo.openstack.common import exception as common_exception CFG = config.CFG logger = logging.getLogger('tempo.worker') worker_opts = [ cfg.BoolOpt('daemonized', default=False, help='Run worker as a daemon'), cfg.StrOpt('publisher_id', default='host', help='Where the notification came from') ] worker_group = cfg.OptGroup(name='worker', title='Worker options') CFG.register_group(worker_group) CFG.register_opts(worker_opts, group=worker_group)
29.563025
77
0.673394
86d979010cd46ef001009b94be4cbd36b5242fa0
24,187
py
Python
bin/basenji_motifs.py
AndyPJiang/basenji
64e43570c8bece156b4ab926608014f489b7965e
[ "Apache-2.0" ]
1
2020-05-22T20:53:37.000Z
2020-05-22T20:53:37.000Z
bin/basenji_motifs.py
AndyPJiang/basenji
64e43570c8bece156b4ab926608014f489b7965e
[ "Apache-2.0" ]
null
null
null
bin/basenji_motifs.py
AndyPJiang/basenji
64e43570c8bece156b4ab926608014f489b7965e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2017 Calico LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========================================================================= from __future__ import print_function from optparse import OptionParser import copy, os, pdb, random, shutil, subprocess, time import h5py import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.stats import spearmanr import seaborn as sns from sklearn import preprocessing import tensorflow as tf import basenji ''' basenji_motifs.py Collect statistics and make plots to explore the first convolution layer of the given model using the given sequences. ''' weblogo_opts = '-X NO -Y NO --errorbars NO --fineprint ""' weblogo_opts += ' -C "#CB2026" A A' weblogo_opts += ' -C "#34459C" C C' weblogo_opts += ' -C "#FBB116" G G' weblogo_opts += ' -C "#0C8040" T T' ################################################################################ # main ################################################################################ def get_motif_proteins(meme_db_file): """ Hash motif_id's to protein names using the MEME DB file """ motif_protein = {} for line in open(meme_db_file): a = line.split() if len(a) > 0 and a[0] == 'MOTIF': if a[2][0] == '(': motif_protein[a[1]] = a[2][1:a[2].find(')')] else: motif_protein[a[1]] = a[2] return motif_protein def info_content(pwm, transpose=False, bg_gc=0.415): """ Compute PWM information content. In the original analysis, I used a bg_gc=0.5. For any future analysis, I ought to switch to the true hg19 value of 0.415. """ pseudoc = 1e-9 if transpose: pwm = np.transpose(pwm) bg_pwm = [1 - bg_gc, bg_gc, bg_gc, 1 - bg_gc] ic = 0 for i in range(pwm.shape[0]): for j in range(4): # ic += 0.5 + pwm[i][j]*np.log2(pseudoc+pwm[i][j]) ic += -bg_pwm[j] * np.log2( bg_pwm[j]) + pwm[i][j] * np.log2(pseudoc + pwm[i][j]) return ic def make_filter_pwm(filter_fasta): """ Make a PWM for this filter from its top hits """ nts = {'A': 0, 'C': 1, 'G': 2, 'T': 3} pwm_counts = [] nsites = 4 # pseudocounts for line in open(filter_fasta): if line[0] != '>': seq = line.rstrip() nsites += 1 if len(pwm_counts) == 0: # initialize with the length for i in range(len(seq)): pwm_counts.append(np.array([1.0] * 4)) # count for i in range(len(seq)): try: pwm_counts[i][nts[seq[i]]] += 1 except KeyError: pwm_counts[i] += np.array([0.25] * 4) # normalize pwm_freqs = [] for i in range(len(pwm_counts)): pwm_freqs.append([pwm_counts[i][j] / float(nsites) for j in range(4)]) return np.array(pwm_freqs), nsites - 4 def meme_add(meme_out, f, filter_pwm, nsites, trim_filters=False): """ Print a filter to the growing MEME file Attrs: meme_out : open file f (int) : filter index # filter_pwm (array) : filter PWM array nsites (int) : number of filter sites """ if not trim_filters: ic_start = 0 ic_end = filter_pwm.shape[0] - 1 else: ic_t = 0.2 # trim PWM of uninformative prefix ic_start = 0 while ic_start < filter_pwm.shape[0] and info_content( filter_pwm[ic_start:ic_start + 1]) < ic_t: ic_start += 1 # trim PWM of uninformative suffix ic_end = filter_pwm.shape[0] - 1 while ic_end >= 0 and info_content(filter_pwm[ic_end:ic_end + 1]) < ic_t: ic_end -= 1 if ic_start < ic_end: print('MOTIF filter%d' % f, file=meme_out) print( 'letter-probability matrix: alength= 4 w= %d nsites= %d' % (ic_end - ic_start + 1, nsites), file=meme_out) for i in range(ic_start, ic_end + 1): print('%.4f %.4f %.4f %.4f' % tuple(filter_pwm[i]), file=meme_out) print('', file=meme_out) def meme_intro(meme_file, seqs): """ Open MEME motif format file and print intro Attrs: meme_file (str) : filename seqs [str] : list of strings for obtaining background freqs Returns: mem_out : open MEME file """ nts = {'A': 0, 'C': 1, 'G': 2, 'T': 3} # count nt_counts = [1] * 4 for i in range(len(seqs)): for nt in seqs[i]: try: nt_counts[nts[nt]] += 1 except KeyError: pass # normalize nt_sum = float(sum(nt_counts)) nt_freqs = [nt_counts[i] / nt_sum for i in range(4)] # open file for writing meme_out = open(meme_file, 'w') # print intro material print('MEME version 4', file=meme_out) print('', file=meme_out) print('ALPHABET= ACGT', file=meme_out) print('', file=meme_out) print('Background letter frequencies:', file=meme_out) print('A %.4f C %.4f G %.4f T %.4f' % tuple(nt_freqs), file=meme_out) print('', file=meme_out) return meme_out def name_filters(num_filters, tomtom_file, meme_db_file): """ Name the filters using Tomtom matches. Attrs: num_filters (int) : total number of filters tomtom_file (str) : filename of Tomtom output table. meme_db_file (str) : filename of MEME db Returns: filter_names [str] : """ # name by number filter_names = ['f%d' % fi for fi in range(num_filters)] # name by protein if tomtom_file is not None and meme_db_file is not None: motif_protein = get_motif_proteins(meme_db_file) # hash motifs and q-value's by filter filter_motifs = {} tt_in = open(tomtom_file) tt_in.readline() for line in tt_in: a = line.split() fi = int(a[0][6:]) motif_id = a[1] qval = float(a[5]) filter_motifs.setdefault(fi, []).append((qval, motif_id)) tt_in.close() # assign filter's best match for fi in filter_motifs: top_motif = sorted(filter_motifs[fi])[0][1] filter_names[fi] += '_%s' % motif_protein[top_motif] return np.array(filter_names) ################################################################################ # plot_target_corr # # Plot a clustered heatmap of correlations between filter activations and # targets. # # Input # filter_outs: # filter_names: # target_names: # out_pdf: ################################################################################ ################################################################################ # plot_filter_seq_heat # # Plot a clustered heatmap of filter activations in # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # plot_filter_seq_heat # # Plot a clustered heatmap of filter activations in sequence segments. # # Mean doesn't work well for the smaller segments for some reason, but taking # the max looks OK. Still, similar motifs don't cluster quite as well as you # might expect. # # Input # filter_outs ################################################################################ ################################################################################ # filter_motif # # Collapse the filter parameter matrix to a single DNA motif. # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # filter_possum # # Write a Possum-style motif # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # plot_filter_heat # # Plot a heatmap of the filter's parameters. # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # plot_filter_logo # # Plot a weblogo of the filter's occurrences # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # plot_score_density # # Plot the score density and print to the stats table. # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # __main__ ################################################################################ if __name__ == '__main__': main() # pdb.runcall(main)
29.282082
99
0.585687
86db53b7a1cf34f8c926e78563b430e45842c3b8
1,337
py
Python
apps/shop/urls.py
Joetib/jshop
810ce5dcf2cf2d23b45536dd0c8806efd3b7fc91
[ "MIT" ]
1
2021-09-29T18:48:00.000Z
2021-09-29T18:48:00.000Z
apps/shop/urls.py
Joetib/jshop
810ce5dcf2cf2d23b45536dd0c8806efd3b7fc91
[ "MIT" ]
null
null
null
apps/shop/urls.py
Joetib/jshop
810ce5dcf2cf2d23b45536dd0c8806efd3b7fc91
[ "MIT" ]
null
null
null
from django.urls import path from . import views app_name = "shop" urlpatterns = [ path('', views.HomePage.as_view(), name="home-page"), path('shop/', views.ProductListView.as_view(), name="product-list"), path('shop/<int:category_pk>/', views.ProductListView.as_view(), name="product-list"), path('shop/products/<int:pk>/', views.ProductDetailView.as_view(), name="product-detail"), path('cart/', views.cart_view, name="cart"), path('cart/add/<int:product_pk>/', views.add_product_to_order, name="add-product-to-cart"), path('cart/add/<int:product_pk>/json/', views.add_product_to_cart_json, name="add-product-to-cart-json"), path('checkout/', views.CheckOut.as_view(), name="checkout"), path('checkout/<int:address_pk>/', views.CheckOut.as_view(), name="checkout"), path('payment/', views.PaymentChoice.as_view(), name="payment-choice"), path('payment/order/<int:pk>/', views.MomoPayment.as_view(), name="momo-payment"), path('payment/momo/<int:pk>/confirm/', views.ConfirmMomoPayment.as_view(), name="confirm-momo-payment"), path('orders/', views.OrderList.as_view(), name="order-list"), path('orders/<int:pk>/', views.OrderDetail.as_view(), name="order-detail"), path('orders/<int:order_id>/items/<int:pk>/', views.OrderItemDetail.as_view(), name="order-item-detail"), ]
58.130435
109
0.691847
86db5b39f7333cdce223e5a0be6e734eb216f5d2
11,028
py
Python
surpyval/parametric/expo_weibull.py
dfm/SurPyval
014fba8f1d4a0f43218a3713ce80a78191ad8be9
[ "MIT" ]
null
null
null
surpyval/parametric/expo_weibull.py
dfm/SurPyval
014fba8f1d4a0f43218a3713ce80a78191ad8be9
[ "MIT" ]
null
null
null
surpyval/parametric/expo_weibull.py
dfm/SurPyval
014fba8f1d4a0f43218a3713ce80a78191ad8be9
[ "MIT" ]
null
null
null
import autograd.numpy as np from scipy.stats import uniform from autograd import jacobian from numpy import euler_gamma from scipy.special import gamma as gamma_func from scipy.special import ndtri as z from scipy import integrate from scipy.optimize import minimize from surpyval import parametric as para from surpyval import nonparametric as nonp from surpyval.parametric.parametric_fitter import ParametricFitter from .fitters.mpp import mpp ExpoWeibull = ExpoWeibull_('ExpoWeibull')
32.151603
228
0.537087
86db8d66e4f0f969e4dab6cb93ed65e00e44883f
3,292
py
Python
tests/test_base_table.py
stjordanis/datar
4e2b5db026ad35918954576badef9951928c0cb1
[ "MIT" ]
110
2021-03-09T04:10:40.000Z
2022-03-13T10:28:20.000Z
tests/test_base_table.py
sthagen/datar
1218a549e2f0547c7b5a824ca6d9adf1bf96ba46
[ "MIT" ]
54
2021-06-20T18:53:44.000Z
2022-03-29T22:13:07.000Z
tests/test_base_table.py
sthagen/datar
1218a549e2f0547c7b5a824ca6d9adf1bf96ba46
[ "MIT" ]
11
2021-06-18T03:03:14.000Z
2022-02-25T11:48:26.000Z
import pytest from datar import stats from datar.base import * from datar import f from datar.datasets import warpbreaks, state_division, state_region, airquality from .conftest import assert_iterable_equal
31.056604
79
0.564702
86dbc8be4491e9aac31a1a68443d62ca3e952415
1,922
py
Python
cqlengine/tests/statements/test_update_statement.py
dokai/cqlengine
a080aff3a73351d37126b14eef606061b445aa37
[ "BSD-3-Clause" ]
null
null
null
cqlengine/tests/statements/test_update_statement.py
dokai/cqlengine
a080aff3a73351d37126b14eef606061b445aa37
[ "BSD-3-Clause" ]
null
null
null
cqlengine/tests/statements/test_update_statement.py
dokai/cqlengine
a080aff3a73351d37126b14eef606061b445aa37
[ "BSD-3-Clause" ]
null
null
null
from unittest import TestCase from cqlengine.statements import UpdateStatement, WhereClause, AssignmentClause from cqlengine.operators import *
44.697674
104
0.648283
86dbf2f275a336e7d12bde00e6cd729b126ef190
1,883
py
Python
packages/facilities/diagnostics/py/custom_checkbox.py
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
2
2021-01-15T13:27:19.000Z
2021-08-04T08:40:52.000Z
packages/facilities/diagnostics/py/custom_checkbox.py
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
null
null
null
packages/facilities/diagnostics/py/custom_checkbox.py
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
5
2018-05-01T10:39:31.000Z
2022-03-25T03:02:35.000Z
# Copyright 2020 Jan Feitsma (Falcons) # SPDX-License-Identifier: Apache-2.0 #!/usr/bin/python import matplotlib.pyplot as plt from matplotlib.patches import Rectangle
33.625
117
0.601699
86dc7d357b174d6a4843f8edef2436d8cf30c367
742
py
Python
generator.py
Axonny/HexagonalHitori
582cb50b751796c30ed273f66c8ac9fa6f3dd089
[ "MIT" ]
null
null
null
generator.py
Axonny/HexagonalHitori
582cb50b751796c30ed273f66c8ac9fa6f3dd089
[ "MIT" ]
null
null
null
generator.py
Axonny/HexagonalHitori
582cb50b751796c30ed273f66c8ac9fa6f3dd089
[ "MIT" ]
null
null
null
from hitori_generator import Generator from argparse import ArgumentParser if __name__ == '__main__': main()
27.481481
120
0.628032
86dd7f5030a8b0c0b8c5d1166bbac51638b7d539
25,946
py
Python
opaflib/xmlast.py
feliam/opaf
f9908c26af1bf28cc29f3d647dcd9f55d631d732
[ "MIT" ]
2
2019-11-23T14:46:35.000Z
2022-01-21T16:09:47.000Z
opaflib/xmlast.py
feliam/opaf
f9908c26af1bf28cc29f3d647dcd9f55d631d732
[ "MIT" ]
null
null
null
opaflib/xmlast.py
feliam/opaf
f9908c26af1bf28cc29f3d647dcd9f55d631d732
[ "MIT" ]
1
2019-09-06T21:04:39.000Z
2019-09-06T21:04:39.000Z
from lxml import etree from opaflib.filters import defilterData #Logging facility import logging,code logger = logging.getLogger("OPAFXML") #leaf #tree #Factory PDF = PDFXMLFactory() def create_leaf(tag, value, **kwargs): return PDF.create_leaf(tag, value,**kwargs) def create_tree(tag, childs, **kwargs): return PDF.create_tree(tag, *childs, **kwargs) if __name__=="__main__": name = create_leaf('name', "Name") string = create_leaf('string', "Felipe") entry = create_tree('entry',[name,string]) dictionary = create_tree('dictionary',[entry]) stream_data = create_leaf('data',"A"*100) stream = create_tree('stream',[dictionary,stream_data]) indirect = create_tree('indirect_object', [stream], obj=(1,0)) array = create_tree('array', [create_leaf('number', i) for i in range(0,10)]) xml=indirect print etree.tostring(xml), xml.value import code code.interact(local=locals())
37.332374
172
0.582248
86dd8cfba25399e11b5e6b0c69e97eec2cc7d779
1,590
py
Python
course-code/imooc-tf-mnist-flask/mnist/module.py
le3t/ko-repo
50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5
[ "Apache-2.0" ]
30
2018-12-06T02:17:45.000Z
2021-04-07T09:03:36.000Z
course-code/imooc-tf-mnist-flask/mnist/module.py
Artister/tutorials-java
50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5
[ "Apache-2.0" ]
3
2019-08-26T13:41:57.000Z
2019-08-26T13:44:21.000Z
course-code/imooc-tf-mnist-flask/mnist/module.py
Artister/tutorials-java
50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5
[ "Apache-2.0" ]
20
2018-12-27T08:31:02.000Z
2020-12-03T08:35:28.000Z
import tensorflow as tf # y=ax+b linear model #
30.576923
72
0.620755
86dfb9b0ac538e587eb0952c661e061a843edff2
1,544
py
Python
src/sol/handle_metaplex.py
terra-dashboard/staketaxcsv
5793105488bf799c61aee64a45f44e9ae8fef397
[ "MIT" ]
140
2021-12-11T23:37:46.000Z
2022-03-29T23:04:36.000Z
src/sol/handle_metaplex.py
terra-dashboard/staketaxcsv
5793105488bf799c61aee64a45f44e9ae8fef397
[ "MIT" ]
80
2021-12-17T15:13:47.000Z
2022-03-31T13:33:53.000Z
src/sol/handle_metaplex.py
terra-dashboard/staketaxcsv
5793105488bf799c61aee64a45f44e9ae8fef397
[ "MIT" ]
52
2021-12-12T00:37:17.000Z
2022-03-29T23:25:09.000Z
from common.make_tx import make_swap_tx from sol.handle_simple import handle_unknown_detect_transfers
34.311111
98
0.709845
86e079c3cae2dd930094e58b47942d7cc71d011d
11,293
py
Python
dcor/independence.py
lemiceterieux/dcor
205682a71463a2c6ab8f5b8b215ec12d44f0b5a6
[ "MIT" ]
null
null
null
dcor/independence.py
lemiceterieux/dcor
205682a71463a2c6ab8f5b8b215ec12d44f0b5a6
[ "MIT" ]
null
null
null
dcor/independence.py
lemiceterieux/dcor
205682a71463a2c6ab8f5b8b215ec12d44f0b5a6
[ "MIT" ]
null
null
null
""" Functions for testing independence of several distributions. The functions in this module provide methods for testing if the samples generated from two random vectors are independent. """ import numpy as np import scipy.stats from . import _dcor_internals, _hypothesis from ._dcor import u_distance_correlation_sqr from ._utils import _random_state_init, _transform_to_2d def distance_covariance_test( x, y, *, num_resamples=0, exponent=1, random_state=None, n_jobs=1, ): """ Test of distance covariance independence. Compute the test of independence based on the distance covariance, for two random vectors. The test is a permutation test where the null hypothesis is that the two random vectors are independent. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. num_resamples: int Number of permutations resamples to take in the permutation test. random_state: {None, int, array_like, numpy.random.RandomState} Random state to generate the permutations. Returns ------- HypothesisTest Results of the hypothesis test. See Also -------- distance_covariance Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1, 0, 0, 1], ... [0, 1, 1, 1], ... [1, 1, 1, 1], ... [1, 1, 0, 1]]) >>> dcor.independence.distance_covariance_test(a, a) HypothesisTest(p_value=1.0, statistic=208.0) >>> dcor.independence.distance_covariance_test(a, b) ... # doctest: +ELLIPSIS HypothesisTest(p_value=1.0, statistic=11.75323056...) >>> dcor.independence.distance_covariance_test(b, b) HypothesisTest(p_value=1.0, statistic=1.3604610...) >>> dcor.independence.distance_covariance_test(a, b, ... num_resamples=5, random_state=0) HypothesisTest(p_value=0.5, statistic=11.7532305...) >>> dcor.independence.distance_covariance_test(a, b, ... num_resamples=5, random_state=13) HypothesisTest(p_value=0.3333333..., statistic=11.7532305...) >>> dcor.independence.distance_covariance_test(a, a, ... num_resamples=7, random_state=0) HypothesisTest(p_value=0.125, statistic=208.0) """ x = _transform_to_2d(x) y = _transform_to_2d(y) _dcor_internals._check_same_n_elements(x, y) random_state = _random_state_init(random_state) # Compute U-centered matrices u_x = _dcor_internals._distance_matrix_generic( x, centering=_dcor_internals.double_centered, exponent=exponent) u_y = _dcor_internals._distance_matrix_generic( y, centering=_dcor_internals.double_centered, exponent=exponent) # Use the dcov statistic return _hypothesis._permutation_test_with_sym_matrix( u_x, statistic_function=statistic_function, num_resamples=num_resamples, random_state=random_state, n_jobs=n_jobs) def partial_distance_covariance_test( x, y, z, *, num_resamples=0, exponent=1, random_state=None, n_jobs=1, ): """ Test of partial distance covariance independence. Compute the test of independence based on the partial distance covariance, for two random vectors conditioned on a third. The test is a permutation test where the null hypothesis is that the first two random vectors are independent given the third one. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. z: array_like Observed random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. num_resamples: int Number of permutations resamples to take in the permutation test. random_state: {None, int, array_like, numpy.random.RandomState} Random state to generate the permutations. Returns ------- HypothesisTest Results of the hypothesis test. See Also -------- partial_distance_covariance Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1, 0, 0, 1], ... [0, 1, 1, 1], ... [1, 1, 1, 1], ... [1, 1, 0, 1]]) >>> c = np.array([[1000, 0, 0, 1000], ... [0, 1000, 1000, 1000], ... [1000, 1000, 1000, 1000], ... [1000, 1000, 0, 1000]]) >>> dcor.independence.partial_distance_covariance_test(a, a, b) ... # doctest: +ELLIPSIS HypothesisTest(p_value=1.0, statistic=142.6664416...) >>> dcor.independence.partial_distance_covariance_test(a, b, c) ... # doctest: +ELLIPSIS HypothesisTest(p_value=1.0, statistic=7.2690070...e-15) >>> dcor.independence.partial_distance_covariance_test(b, b, c) ... # doctest: +ELLIPSIS HypothesisTest(p_value=1.0, statistic=2.2533380...e-30) >>> dcor.independence.partial_distance_covariance_test(a, b, c, ... num_resamples=5, random_state=0) HypothesisTest(p_value=0.1666666..., statistic=7.2690070...e-15) >>> dcor.independence.partial_distance_covariance_test(a, b, c, ... num_resamples=5, random_state=13) HypothesisTest(p_value=0.1666666..., statistic=7.2690070...e-15) >>> dcor.independence.partial_distance_covariance_test(a, c, b, ... num_resamples=7, random_state=0) HypothesisTest(p_value=1.0, statistic=-7.5701764...e-12) """ random_state = _random_state_init(random_state) # Compute U-centered matrices u_x = _dcor_internals._u_distance_matrix(x, exponent=exponent) u_y = _dcor_internals._u_distance_matrix(y, exponent=exponent) u_z = _dcor_internals._u_distance_matrix(z, exponent=exponent) # Compute projections proj = _dcor_internals.u_complementary_projection(u_z) p_xz = proj(u_x) p_yz = proj(u_y) # Use the pdcor statistic return _hypothesis._permutation_test_with_sym_matrix( p_xz, statistic_function=statistic_function, num_resamples=num_resamples, random_state=random_state, n_jobs=n_jobs) def distance_correlation_t_statistic(x, y): """ Transformation of the bias corrected version of distance correlation used in :func:`distance_correlation_t_test`. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar T statistic. See Also -------- distance_correlation_t_test Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1, 0, 0, 1], ... [0, 1, 1, 1], ... [1, 1, 1, 1], ... [1, 1, 0, 1]]) >>> with np.errstate(divide='ignore'): ... dcor.independence.distance_correlation_t_statistic(a, a) inf >>> dcor.independence.distance_correlation_t_statistic(a, b) ... # doctest: +ELLIPSIS -0.4430164... >>> with np.errstate(divide='ignore'): ... dcor.independence.distance_correlation_t_statistic(b, b) inf """ bcdcor = u_distance_correlation_sqr(x, y) n = x.shape[0] v = n * (n - 3) / 2 return np.sqrt(v - 1) * bcdcor / np.sqrt(1 - bcdcor**2) def distance_correlation_t_test(x, y): """ Test of independence for high dimension based on convergence to a Student t distribution. The null hypothesis is that the two random vectors are independent. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- HypothesisTest Results of the hypothesis test. See Also -------- distance_correlation_t_statistic Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1, 0, 0, 1], ... [0, 1, 1, 1], ... [1, 1, 1, 1], ... [1, 1, 0, 1]]) >>> with np.errstate(divide='ignore'): ... dcor.independence.distance_correlation_t_test(a, a) ... # doctest: +ELLIPSIS HypothesisTest(p_value=0.0, statistic=inf) >>> dcor.independence.distance_correlation_t_test(a, b) ... # doctest: +ELLIPSIS HypothesisTest(p_value=0.6327451..., statistic=-0.4430164...) >>> with np.errstate(divide='ignore'): ... dcor.independence.distance_correlation_t_test(b, b) ... # doctest: +ELLIPSIS HypothesisTest(p_value=0.0, statistic=inf) """ t_test = distance_correlation_t_statistic(x, y) n = x.shape[0] v = n * (n - 3) / 2 df = v - 1 p_value = 1 - scipy.stats.t.cdf(t_test, df=df) return _hypothesis.HypothesisTest(p_value=p_value, statistic=t_test)
33.411243
79
0.609493
86e150137bde5dca549d0321cdc857bd542bc500
3,878
py
Python
cinemasci/cis/__init__.py
cinemascience/cinemasc
5b00a0c2e3c886f65cfbf1f59e914fc458d7068b
[ "BSD-3-Clause" ]
null
null
null
cinemasci/cis/__init__.py
cinemascience/cinemasc
5b00a0c2e3c886f65cfbf1f59e914fc458d7068b
[ "BSD-3-Clause" ]
3
2020-04-22T16:26:44.000Z
2020-04-22T16:30:12.000Z
cinemasci/cis/__init__.py
cinemascience/cinemasc
5b00a0c2e3c886f65cfbf1f59e914fc458d7068b
[ "BSD-3-Clause" ]
1
2020-03-06T21:21:19.000Z
2020-03-06T21:21:19.000Z
from . import imageview from . import cisview from . import renderer from . import convert
29.603053
84
0.555183
86e1817f75ca21dff7ecb06d87908e9887be1bfd
2,172
py
Python
applications/spaghetti.py
fos/fos-legacy
db6047668781a0615abcebc7d55a7164f3105047
[ "BSD-3-Clause" ]
2
2016-08-03T10:33:08.000Z
2021-06-23T18:50:14.000Z
applications/spaghetti.py
fos/fos-legacy
db6047668781a0615abcebc7d55a7164f3105047
[ "BSD-3-Clause" ]
null
null
null
applications/spaghetti.py
fos/fos-legacy
db6047668781a0615abcebc7d55a7164f3105047
[ "BSD-3-Clause" ]
null
null
null
import numpy as np import nibabel as nib import os.path as op import pyglet #pyglet.options['debug_gl'] = True #pyglet.options['debug_x11'] = True #pyglet.options['debug_gl_trace'] = True #pyglet.options['debug_texture'] = True #fos modules from fos.actor.axes import Axes from fos import World, Window, WindowManager from labeler import TrackLabeler from fos.actor.slicer import Slicer #dipy modules from dipy.segment.quickbundles import QuickBundles from dipy.io.dpy import Dpy from dipy.io.pickles import load_pickle,save_pickle from dipy.viz.colormap import orient2rgb import copy if __name__ == '__main__': subject = 5 seeds = 1 qb_dist = 30 #load T1 volume registered in MNI space img = nib.load('data/subj_'+("%02d" % subject)+'/MPRAGE_32/T1_flirt_out.nii.gz') data = img.get_data() affine = img.get_affine() #load the tracks registered in MNI space fdpyw = 'data/subj_'+("%02d" % subject)+'/101_32/DTI/tracks_gqi_'+str(seeds)+'M_linear.dpy' dpr = Dpy(fdpyw, 'r') T = dpr.read_tracks() dpr.close() #load initial QuickBundles with threshold 30mm fpkl = 'data/subj_'+("%02d" % subject)+'/101_32/DTI/qb_gqi_'+str(seeds)+'M_linear_'+str(qb_dist)+'.pkl' #qb=QuickBundles(T,30.,12) qb=load_pickle(fpkl) #create the interaction system for tracks tl = TrackLabeler(qb,qb.downsampled_tracks(),vol_shape=data.shape,tracks_alpha=1) #add a interactive slicing/masking tool sl = Slicer(affine,data) #add one way communication between tl and sl tl.slicer=sl #OpenGL coordinate system axes ax = Axes(100) x,y,z=data.shape #add the actors to the world w=World() w.add(tl) w.add(sl) #w.add(ax) #create a window wi = Window(caption="Interactive Spaghetti using Diffusion Imaging in Python (dipy.org) and Free On Shades (fos.me)",\ bgcolor=(0.3,0.3,0.6,1),width=1200,height=800) #attach the world to the window wi.attach(w) #create a manager which can handle multiple windows wm = WindowManager() wm.add(wi) wm.run() print('Everything is running ;-)')
31.941176
122
0.675414
86e1dc1697df65dd8302b1c8457579ff83a8e10d
1,074
py
Python
faceai/gender.py
dlzdy/faceai
4b1e41d4c394c00da51533562b76306d86493f72
[ "MIT" ]
1
2021-05-18T07:31:14.000Z
2021-05-18T07:31:14.000Z
faceai/gender.py
dlzdy/faceai
4b1e41d4c394c00da51533562b76306d86493f72
[ "MIT" ]
null
null
null
faceai/gender.py
dlzdy/faceai
4b1e41d4c394c00da51533562b76306d86493f72
[ "MIT" ]
null
null
null
#coding=utf-8 # import cv2 from keras.models import load_model import numpy as np import chineseText img = cv2.imread("img/gather.png") face_classifier = cv2.CascadeClassifier( "d:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml" ) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_classifier.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=3, minSize=(140, 140)) gender_classifier = load_model( "classifier/gender_models/simple_CNN.81-0.96.hdf5") gender_labels = {0: '', 1: ''} color = (255, 255, 255) for (x, y, w, h) in faces: face = img[(y - 60):(y + h + 60), (x - 30):(x + w + 30)] face = cv2.resize(face, (48, 48)) face = np.expand_dims(face, 0) face = face / 255.0 gender_label_arg = np.argmax(gender_classifier.predict(face)) gender = gender_labels[gender_label_arg] cv2.rectangle(img, (x, y), (x + h, y + w), color, 2) img = chineseText.cv2ImgAddText(img, gender, x + h, y, color, 30) cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows()
30.685714
103
0.691806
86e1dfa0c33f00a823a44b2f6b5cc3f12ae76c76
5,872
py
Python
csm_web/scheduler/tests/utils.py
mudit2103/csm_web
3b7fd9ca7269ad4cb57bf264cf62a620e02d3780
[ "MIT" ]
null
null
null
csm_web/scheduler/tests/utils.py
mudit2103/csm_web
3b7fd9ca7269ad4cb57bf264cf62a620e02d3780
[ "MIT" ]
null
null
null
csm_web/scheduler/tests/utils.py
mudit2103/csm_web
3b7fd9ca7269ad4cb57bf264cf62a620e02d3780
[ "MIT" ]
null
null
null
from django.test import TestCase from os import path from rest_framework import status from rest_framework.test import APIClient import random from scheduler.models import Profile from scheduler.factories import ( CourseFactory, SpacetimeFactory, UserFactory, ProfileFactory, SectionFactory, AttendanceFactory, OverrideFactory, create_attendances_for, ) random.seed(0) COURSE_NAMES = ("CS88", "CS61A", "CS61B", "CS70", "CS61C", "EE16A") ROLE_MAP = Profile.ROLE_MAP BASE_PATH = "/scheduler" # ----- REQUEST UTILITIES ----- # ----- MODEL GENERATION ----- def random_objs(clazz, n=1): """ Generates N instances of the provided class, retrieved from the database. """ src = clazz.objects.all() for _ in range(n): yield random.choice(src) def make_test_courses(): """Creates course objects and persists them to database.""" return [CourseFactory.create(name=name) for name in COURSE_NAMES] def make_test_users(n): """Creates N test users and persists them to database.""" return UserFactory.create_batch(n) def give_role(user, role, course): """ Creates a profile for USER in a given ROLE for the provided COURSE, and saves the profile to database. """ return ProfileFactory.create( user=user, course=course, leader=None, section=None, role=role ) def create_empty_section_for(mentor): """ Creates a section for MENTOR without populated students. """ return SectionFactory.create(course=mentor.course, mentor=mentor) def enroll_user_as_student(user, section): """ Creates a student profile for USER, and assigns them to the given SECTION. Also creates blank attendances as necessary. Returns the created profile. """ student = give_role(user, Profile.STUDENT, section.course) student.section = section student.leader = section.leader create_attendances_for(student) return student def gen_test_data(cls, NUM_USERS=300): """ Adds NUM_USERS users to the database and initializes profiles for them as follows: - 2 coords per course - 4 SMs per coord, each with a section of 3-6 students - 3 JMs per SM, each with a section of 3-6 students """ users = iter(make_test_users(NUM_USERS)) courses = make_test_courses() # for sanity tests, everyone only has one role for now num_courses = len(courses) coords, seniors, juniors, students = [], [], [], [] COORD_COUNT = 2 SM_COUNT = 4 JM_COUNT = 3 try: for c in courses: # coords for i in range(COORD_COUNT): coord = assign(Profile.COORDINATOR, None, c, coords) # SMs for j in range(SM_COUNT): sm = assign(Profile.SENIOR_MENTOR, coord, c, seniors) section = create_empty_section_for(sm) for k in range(random.randint(3, 6)): students.append(enroll_user_as_student(next(users), section)) # JMs for k in range(JM_COUNT): jm = assign(Profile.JUNIOR_MENTOR, sm, c, juniors) for _ in range(random.randint(3, 6)): students.append( enroll_user_as_student(next(users), section) ) except StopIteration: pass cls.users = users cls.courses = courses cls.coords = coords cls.seniors = seniors cls.juniors = juniors cls.students = students
32.804469
88
0.647309
86e1fd3bf7ee00e117356675760b13ae01e5890a
3,282
py
Python
coldtype/beziers.py
tallpauley/coldtype
c1811e1d3713ff9c3c804511d6cd607b1d802065
[ "Apache-2.0" ]
null
null
null
coldtype/beziers.py
tallpauley/coldtype
c1811e1d3713ff9c3c804511d6cd607b1d802065
[ "Apache-2.0" ]
null
null
null
coldtype/beziers.py
tallpauley/coldtype
c1811e1d3713ff9c3c804511d6cd607b1d802065
[ "Apache-2.0" ]
null
null
null
import math from fontTools.pens.recordingPen import RecordingPen, replayRecording from fontTools.misc.bezierTools import calcCubicArcLength, splitCubicAtT from coldtype.geometry import Rect, Point __length_cache = {} __split_cache = {}
31.557692
85
0.482937
86e21cfc54ba4f492a89adb3a5ddc21c8d452d78
3,930
py
Python
p1_navigation/train.py
nick0lay/deep-reinforcement-learning
5af4daca9850b4e12aec5d8b0dad87f1e22a1f98
[ "MIT" ]
null
null
null
p1_navigation/train.py
nick0lay/deep-reinforcement-learning
5af4daca9850b4e12aec5d8b0dad87f1e22a1f98
[ "MIT" ]
null
null
null
p1_navigation/train.py
nick0lay/deep-reinforcement-learning
5af4daca9850b4e12aec5d8b0dad87f1e22a1f98
[ "MIT" ]
null
null
null
""" Project for Udacity Danaodgree in Deep Reinforcement Learning This script train an agent to navigate (and collect bananas!) in a large, square world. A reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana. Thus, the goal of your agent is to collect as many yellow bananas as possible while avoiding blue bananas. The state space has 37 dimensions and contains the agent's velocity, along with ray-based perception of objects around the agent's forward direction. Given this information, the agent has to learn how to best select actions. Four discrete actions are available, corresponding to: 0 - move forward. 1 - move backward. 2 - turn left. 3 - turn right. The task is episodic, and in order to solve the environment, your agent must get an average score of +13 over 100 consecutive episodes. """ from unityagents import UnityEnvironment import numpy as np from collections import deque from dqn_agent import Agent import torch device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") """ Unity environment configuration Mac: "path/to/Banana.app" Windows (x86): "path/to/Banana_Windows_x86/Banana.exe" Windows (x86_64): "path/to/Banana_Windows_x86_64/Banana.exe" Linux (x86): "path/to/Banana_Linux/Banana.x86" Linux (x86_64): "path/to/Banana_Linux/Banana.x86_64" Linux (x86, headless): "path/to/Banana_Linux_NoVis/Banana.x86" Linux (x86_64, headless): "path/to/Banana_Linux_NoVis/Banana.x86_64" """ # start Unity environment env = UnityEnvironment(file_name="Banana.app") # get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name] env_info = env.reset(train_mode=False)[brain_name] action_size = brain.vector_action_space_size state_size = len(env_info.vector_observations[0]) # initialize agent agent = Agent(state_size=state_size, action_size=action_size, seed=0, device=device) def train(n_episodes=2000, eps_start=1.0, eps_end=0.05, eps_decay=0.99): """Deep Q-Learning. Params ====== n_episodes (int): maximum number of training episodes eps_start (float): starting value of epsilon, for epsilon-greedy action selection eps_end (float): minimum value of epsilon eps_decay (float): multiplicative factor (per episode) for decreasing epsilon """ scores = [] # list containing scores from each episode scores_window = deque(maxlen=100) # last 100 scores eps = eps_start # initialize epsilon for i_episode in range(1, n_episodes+1): # reset environment env_info = env.reset(train_mode=True)[brain_name] # get initial state state = env_info.vector_observations[0] # set initial score score = 0 while True: action = agent.act(state, eps) env_info = env.step(action)[brain_name] next_state, reward, done = env_info.vector_observations[0], env_info.rewards[0], env_info.local_done[0] agent.step(state, action, reward, next_state, done) state = next_state score += reward if done: break scores_window.append(score) # save most recent score scores.append(score) # save most recent score eps = max(eps_end, eps_decay*eps) # decrease epsilon print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="") if i_episode % 100 == 0: print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window))) if np.mean(scores_window)>=14: print('\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window))) torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth') break return scores train()
42.717391
279
0.689567
86e5087a507beef54f4930afdd98c56727fc0500
2,869
py
Python
models/model_factory.py
jac99/Egonn
075e00368a1676df741a35f42f6f38497da9d58f
[ "MIT" ]
9
2021-10-31T07:11:58.000Z
2022-03-29T14:06:49.000Z
models/model_factory.py
jac99/Egonn
075e00368a1676df741a35f42f6f38497da9d58f
[ "MIT" ]
null
null
null
models/model_factory.py
jac99/Egonn
075e00368a1676df741a35f42f6f38497da9d58f
[ "MIT" ]
3
2021-11-12T17:42:41.000Z
2022-03-11T00:41:47.000Z
# Warsaw University of Technology from layers.eca_block import ECABasicBlock from models.minkgl import MinkHead, MinkTrunk, MinkGL from models.minkloc import MinkLoc from third_party.minkloc3d.minkloc import MinkLoc3D from misc.utils import ModelParams
36.782051
100
0.694319
86e596ecc94466fc1c8a56bb395c9ae7c14904e6
19,380
py
Python
mdns/Phidget22Python/Phidget22/Phidget.py
rabarar/phidget_docker
ceca56c86d27f291a4300a1257c02096862335ec
[ "MIT" ]
null
null
null
mdns/Phidget22Python/Phidget22/Phidget.py
rabarar/phidget_docker
ceca56c86d27f291a4300a1257c02096862335ec
[ "MIT" ]
null
null
null
mdns/Phidget22Python/Phidget22/Phidget.py
rabarar/phidget_docker
ceca56c86d27f291a4300a1257c02096862335ec
[ "MIT" ]
null
null
null
import sys import ctypes from Phidget22.PhidgetSupport import PhidgetSupport from Phidget22.Async import * from Phidget22.ChannelClass import ChannelClass from Phidget22.ChannelSubclass import ChannelSubclass from Phidget22.DeviceClass import DeviceClass from Phidget22.DeviceID import DeviceID from Phidget22.ErrorEventCode import ErrorEventCode from Phidget22.PhidgetException import PhidgetException ANY_SERIAL_NUMBER = -1 ANY_HUB_PORT = -1 ANY_CHANNEL = -1 ANY_LABEL = None INFINITE_TIMEOUT = 0 DEFAULT_TIMEOUT = 1000
26.083445
113
0.757482
86e649d303431093f68ab23ef3215809292e639b
4,872
py
Python
tests/integration/test_celery.py
crossscreenmedia/scout_apm_python
5cd31bf21f5acd0be0df4f40ec0bd29ec050ec01
[ "MIT" ]
null
null
null
tests/integration/test_celery.py
crossscreenmedia/scout_apm_python
5cd31bf21f5acd0be0df4f40ec0bd29ec050ec01
[ "MIT" ]
null
null
null
tests/integration/test_celery.py
crossscreenmedia/scout_apm_python
5cd31bf21f5acd0be0df4f40ec0bd29ec050ec01
[ "MIT" ]
null
null
null
# coding=utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from contextlib import contextmanager import celery import pytest from celery.signals import setup_logging import scout_apm.celery from scout_apm.api import Config # http://docs.celeryproject.org/en/latest/userguide/testing.html#py-test skip_unless_celery_4_plus = pytest.mark.skipif( celery.VERSION < (4, 0), reason="pytest fixtures added in Celery 4.0" ) def test_hello_eager(tracked_requests): with app_with_scout() as app: result = app.tasks["tests.integration.test_celery.hello"].apply() assert result.result == "Hello World!" assert len(tracked_requests) == 1 tracked_request = tracked_requests[0] assert "task_id" in tracked_request.tags assert tracked_request.tags["is_eager"] is True assert tracked_request.tags["exchange"] == "unknown" assert tracked_request.tags["routing_key"] == "unknown" assert tracked_request.tags["queue"] == "unknown" assert tracked_request.active_spans == [] assert len(tracked_request.complete_spans) == 1 span = tracked_request.complete_spans[0] assert span.operation == "Job/tests.integration.test_celery.hello" def test_no_monitor(tracked_requests): # With an empty config, "monitor" defaults to False. with app_with_scout(config={}) as app: result = app.tasks["tests.integration.test_celery.hello"].apply() assert result.result == "Hello World!" assert tracked_requests == []
34.553191
82
0.70936
86e65c540055ab2f761c3c998b140c5377b7f0c6
10,865
py
Python
molly/apps/places/migrations/0001_initial.py
mollyproject/mollyproject
3247c6bac3f39ce8d275d19aa410b30c6284b8a7
[ "Apache-2.0" ]
7
2015-05-16T13:27:21.000Z
2019-08-06T11:09:24.000Z
molly/apps/places/migrations/0001_initial.py
mollyproject/mollyproject
3247c6bac3f39ce8d275d19aa410b30c6284b8a7
[ "Apache-2.0" ]
null
null
null
molly/apps/places/migrations/0001_initial.py
mollyproject/mollyproject
3247c6bac3f39ce8d275d19aa410b30c6284b8a7
[ "Apache-2.0" ]
4
2015-11-27T13:36:36.000Z
2021-03-09T17:55:53.000Z
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models
60.698324
211
0.620985
86e6c529a13c62833d2d9d91e683f2c9cc85c2b8
16,246
py
Python
sdk/python/pulumi_azure_native/servicebus/v20210601preview/get_subscription.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/servicebus/v20210601preview/get_subscription.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/servicebus/v20210601preview/get_subscription.py
polivbr/pulumi-azure-native
09571f3bf6bdc4f3621aabefd1ba6c0d4ecfb0e7
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs __all__ = [ 'GetSubscriptionResult', 'AwaitableGetSubscriptionResult', 'get_subscription', ] def get_subscription(namespace_name: Optional[str] = None, resource_group_name: Optional[str] = None, subscription_name: Optional[str] = None, topic_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSubscriptionResult: """ Description of subscription resource. :param str namespace_name: The namespace name :param str resource_group_name: Name of the Resource group within the Azure subscription. :param str subscription_name: The subscription name. :param str topic_name: The topic name. """ __args__ = dict() __args__['namespaceName'] = namespace_name __args__['resourceGroupName'] = resource_group_name __args__['subscriptionName'] = subscription_name __args__['topicName'] = topic_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:servicebus/v20210601preview:getSubscription', __args__, opts=opts, typ=GetSubscriptionResult).value return AwaitableGetSubscriptionResult( accessed_at=__ret__.accessed_at, auto_delete_on_idle=__ret__.auto_delete_on_idle, client_affine_properties=__ret__.client_affine_properties, count_details=__ret__.count_details, created_at=__ret__.created_at, dead_lettering_on_filter_evaluation_exceptions=__ret__.dead_lettering_on_filter_evaluation_exceptions, dead_lettering_on_message_expiration=__ret__.dead_lettering_on_message_expiration, default_message_time_to_live=__ret__.default_message_time_to_live, duplicate_detection_history_time_window=__ret__.duplicate_detection_history_time_window, enable_batched_operations=__ret__.enable_batched_operations, forward_dead_lettered_messages_to=__ret__.forward_dead_lettered_messages_to, forward_to=__ret__.forward_to, id=__ret__.id, is_client_affine=__ret__.is_client_affine, lock_duration=__ret__.lock_duration, max_delivery_count=__ret__.max_delivery_count, message_count=__ret__.message_count, name=__ret__.name, requires_session=__ret__.requires_session, status=__ret__.status, system_data=__ret__.system_data, type=__ret__.type, updated_at=__ret__.updated_at)
45.253482
595
0.70048
86e708b4a5fa05856a6c8d0dde3c26f2006621e1
4,340
py
Python
py_cfeve/module/CFAF240400E0-030TN-A1.py
crystalfontz/CFA-EVE-Python-Library
c5aca10b9b6ee109d4df8a9a692dcef083dafc88
[ "Unlicense" ]
1
2021-12-08T00:12:02.000Z
2021-12-08T00:12:02.000Z
py_cfeve/module/CFAF240400E0-030TN-A1.py
crystalfontz/CFA-EVE-Python-Library
c5aca10b9b6ee109d4df8a9a692dcef083dafc88
[ "Unlicense" ]
null
null
null
py_cfeve/module/CFAF240400E0-030TN-A1.py
crystalfontz/CFA-EVE-Python-Library
c5aca10b9b6ee109d4df8a9a692dcef083dafc88
[ "Unlicense" ]
null
null
null
#=========================================================================== # # Crystalfontz Raspberry-Pi Python example library for FTDI / BridgeTek # EVE graphic accelerators. # #--------------------------------------------------------------------------- # # This file is part of the port/adaptation of existing C based EVE libraries # to Python for Crystalfontz EVE based displays. # # 2021-10-20 Mark Williams / Crystalfontz America Inc. # https:#www.crystalfontz.com/products/eve-accelerated-tft-displays.php #--------------------------------------------------------------------------- # # This is free and unencumbered software released into the public domain. # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # For more information, please refer to <http:#unlicense.org/> # #============================================================================ #EVE Device Type EVE_DEVICE = 811 # EVE Clock Speed EVE_CLOCK_SPEED = 60000000 # Touch TOUCH_RESISTIVE = False TOUCH_CAPACITIVE = False TOUCH_GOODIX_CAPACITIVE = False # Define RGB output pins order, determined by PCB layout LCD_SWIZZLE = 2 # Define active edge of PCLK. Observed by scope: # 0: Data is put out coincident with falling edge of the clock. # Rising edge of the clock is in the middle of the data. # 1: Data is put out coincident with rising edge of the clock. # Falling edge of the clock is in the middle of the data. LCD_PCLKPOL = 0 # LCD drive strength: 0=5mA, 1=10mA LCD_DRIVE_10MA = 0 # Spread Spectrum on RGB signals. Probably not a good idea at higher # PCLK frequencies. LCD_PCLK_CSPREAD = 0 #This is not a 24-bit display, so dither LCD_DITHER = 0 # Pixel clock divisor LCD_PCLK = 5 #---------------------------------------------------------------------------- # Frame_Rate = 60Hz / 16.7mS #---------------------------------------------------------------------------- # Horizontal timing # Target 60Hz frame rate, using the largest possible line time in order to # maximize the time that the EVE has to process each line. HPX = 240 # Horizontal Pixel Width HSW = 10 # Horizontal Sync Width HBP = 20 # Horizontal Back Porch HFP = 10 # Horizontal Front Porch HPP = 209 # Horizontal Pixel Padding # FTDI needs at least 1 here # Define the constants needed by the EVE based on the timing # Active width of LCD display LCD_WIDTH = HPX # Start of horizontal sync pulse LCD_HSYNC0 = HFP # End of horizontal sync pulse LCD_HSYNC1 = HFP+HSW # Start of active line LCD_HOFFSET = HFP+HSW+HBP # Total number of clocks per line LCD_HCYCLE = HPX+HFP+HSW+HBP+HPP #---------------------------------------------------------------------------- # Vertical timing VLH = 400 # Vertical Line Height VS = 2 # Vertical Sync (in lines) VBP = 2 # Vertical Back Porch VFP = 4 # Vertical Front Porch VLP = 1 # Vertical Line Padding # FTDI needs at least 1 here # Define the constants needed by the EVE based on the timing # Active height of LCD display LCD_HEIGHT = VLH # Start of vertical sync pulse LCD_VSYNC0 = VFP # End of vertical sync pulse LCD_VSYNC1 = VFP+VS # Start of active screen LCD_VOFFSET = VFP+VS+VBP # Total number of lines per screen LCD_VCYCLE = VLH+VFP+VS+VBP+VLP
38.070175
78
0.645392
86e79f3939b52fb2b048dd2d47804d7ba195c64a
12,893
py
Python
quapy/model_selection.py
OneToolsCollection/HLT-ISTI-QuaPy
6a5c528154c2d6d38d9f3258e667727bf692fc8b
[ "BSD-3-Clause" ]
null
null
null
quapy/model_selection.py
OneToolsCollection/HLT-ISTI-QuaPy
6a5c528154c2d6d38d9f3258e667727bf692fc8b
[ "BSD-3-Clause" ]
null
null
null
quapy/model_selection.py
OneToolsCollection/HLT-ISTI-QuaPy
6a5c528154c2d6d38d9f3258e667727bf692fc8b
[ "BSD-3-Clause" ]
null
null
null
import itertools import signal from copy import deepcopy from typing import Union, Callable import numpy as np import quapy as qp from quapy.data.base import LabelledCollection from quapy.evaluation import artificial_prevalence_prediction, natural_prevalence_prediction, gen_prevalence_prediction from quapy.method.aggregative import BaseQuantifier import inspect from util import _check_sample_size
48.65283
119
0.649732
86e7d2f1d51490654abf153935c59b83db56caad
597
py
Python
flasky.py
ZxShane/slam_hospital
302704b3a188cea07dddfb23595dd75f8d3cd636
[ "Apache-2.0" ]
null
null
null
flasky.py
ZxShane/slam_hospital
302704b3a188cea07dddfb23595dd75f8d3cd636
[ "Apache-2.0" ]
1
2020-11-17T16:47:19.000Z
2021-01-26T10:16:33.000Z
flasky.py
ZxShane/slam_hospital
302704b3a188cea07dddfb23595dd75f8d3cd636
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import os from flask_migrate import Migrate from app import create_app, db from app.models import User, Role, PoseToLocation app = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(app, db) # migrate #
22.111111
75
0.730318
86e7e28fd96ba38477835a4f1f9a0169efabb855
2,841
py
Python
python/day09/smoke_basin.py
aesdeef/advent-of-code-2021
4561bcf12ac03d360f5b28c48ef80134f97613b9
[ "MIT" ]
2
2021-12-03T06:18:27.000Z
2021-12-06T11:28:33.000Z
python/day09/smoke_basin.py
aesdeef/advent-of-code-2021
4561bcf12ac03d360f5b28c48ef80134f97613b9
[ "MIT" ]
null
null
null
python/day09/smoke_basin.py
aesdeef/advent-of-code-2021
4561bcf12ac03d360f5b28c48ef80134f97613b9
[ "MIT" ]
null
null
null
INPUT_FILE = "../../input/09.txt" Point = tuple[int, int] Heightmap = dict[Point, int] Basin = set[Point] def parse_input() -> Heightmap: """ Parses the input and returns a Heightmap """ with open(INPUT_FILE) as f: heights = [[int(x) for x in line.strip()] for line in f] heightmap: Heightmap = dict() for (y, row) in enumerate(heights): for (x, height) in enumerate(row): heightmap[(x, y)] = height return heightmap def get_surrounding_points(heightmap: Heightmap, point: Point) -> set[Point]: """ Returns a set of surrounding points within the heightmap """ x, y = point return { (x - 1, y), (x, y - 1), (x, y + 1), (x + 1, y), } & heightmap.keys() def get_surrounding_heights(heightmap: Heightmap, point: Point) -> set[int]: """ Returns the heights of points surrounding the given point """ surrounding_points = get_surrounding_points(heightmap, point) return {heightmap[point] for point in surrounding_points} def get_low_points(heightmap: Heightmap) -> set[Point]: """ Finds the low points on the heightmap """ low_points: set[Point] = set() for point in heightmap: surrounding_heights = get_surrounding_heights(heightmap, point) if all(heightmap[point] < height for height in surrounding_heights): low_points.add(point) return low_points def solve_part1(heightmap: Heightmap, low_points: set[Point]) -> int: """ Calculates the sum of the risk levels of all low points """ return sum(1 + heightmap[point] for point in low_points) def get_basins(heightmap: Heightmap, low_points: set[Point]) -> list[Basin]: """ Finds all basins on the heightmap """ basins: list[Basin] = [] for low_point in low_points: basin: Basin = set() points_to_consider = {low_point} while points_to_consider: point = points_to_consider.pop() if heightmap[point] == 9: continue surrounding_points = get_surrounding_points(heightmap, point) points_to_consider.update(surrounding_points - basin) basin.add(point) basins.append(basin) return basins def solve_part2(heightmap: Heightmap, low_points: set[Point]) -> int: """ Calculates the product of the sizes of the three largest basins """ basins = get_basins(heightmap, low_points) basin_sizes = sorted((len(basin) for basin in basins), reverse=True) return basin_sizes[0] * basin_sizes[1] * basin_sizes[2] if __name__ == "__main__": heightmap = parse_input() low_points = get_low_points(heightmap) part1 = solve_part1(heightmap, low_points) part2 = solve_part2(heightmap, low_points) print(part1) print(part2)
27.852941
77
0.642027
86e856cc4992e6f53fef41d1cfe0de4271ac6642
1,667
py
Python
playground.py
NHGmaniac/voctoconfig
55a803a5f9bc81b48eaa72ced1fddd402aa7a2e9
[ "MIT" ]
null
null
null
playground.py
NHGmaniac/voctoconfig
55a803a5f9bc81b48eaa72ced1fddd402aa7a2e9
[ "MIT" ]
null
null
null
playground.py
NHGmaniac/voctoconfig
55a803a5f9bc81b48eaa72ced1fddd402aa7a2e9
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import signal import logging import sys from gi.repository import GObject GObject.threads_init() import time from lib.args import Args from lib.loghandler import LogHandler import lib.connection as Connection if __name__ == '__main__': main()
24.514706
67
0.644271
86e873cdab8920252696e3d917e54b578dd9f428
3,220
py
Python
tianshou/utils/logger/tensorboard.py
Aceticia/tianshou
6377dc5006ba1111adac42472447b9de4a021c2d
[ "MIT" ]
4,714
2018-04-16T22:52:05.000Z
2022-03-31T14:14:51.000Z
tianshou/utils/logger/tensorboard.py
Aceticia/tianshou
6377dc5006ba1111adac42472447b9de4a021c2d
[ "MIT" ]
529
2020-03-26T00:58:03.000Z
2022-03-31T01:59:14.000Z
tianshou/utils/logger/tensorboard.py
Aceticia/tianshou
6377dc5006ba1111adac42472447b9de4a021c2d
[ "MIT" ]
798
2018-05-26T23:34:07.000Z
2022-03-30T11:26:19.000Z
import warnings from typing import Any, Callable, Optional, Tuple from tensorboard.backend.event_processing import event_accumulator from torch.utils.tensorboard import SummaryWriter from tianshou.utils.logger.base import LOG_DATA_TYPE, BaseLogger
37.011494
87
0.647205
86e8affd139b8a4dffaf5cdc66c6797adccdf84b
7,326
py
Python
PythonAPI/pythonwrappers/jetfuel/gui/menu.py
InsightGit/JetfuelGameEngine
3ea0bf2fb5e09aadf304b7b5a16882d72336c408
[ "Apache-2.0" ]
4
2018-02-05T03:40:10.000Z
2021-06-18T16:22:13.000Z
PythonAPI/pythonwrappers/jetfuel/gui/menu.py
InsightGit/JetfuelGameEngine
3ea0bf2fb5e09aadf304b7b5a16882d72336c408
[ "Apache-2.0" ]
null
null
null
PythonAPI/pythonwrappers/jetfuel/gui/menu.py
InsightGit/JetfuelGameEngine
3ea0bf2fb5e09aadf304b7b5a16882d72336c408
[ "Apache-2.0" ]
null
null
null
# Jetfuel Game Engine- A SDL-based 2D game-engine # Copyright (C) 2018 InfernoStudios # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ctypes import c_uint from ctypes import c_int from ctypes import c_void_p from ctypes import c_bool from ctypes import c_wchar_p from jetfuel.draw.rectangleinterface import rectangle_interface from jetfuel.draw.image import image
46.367089
81
0.590227
86ea235dbd8e630be7e48c8aa27ae5d388c7bc1d
30,649
py
Python
latent_programmer/decomposition_transformer_attention/train.py
ParikhKadam/google-research
00a282388e389e09ce29109eb050491c96cfab85
[ "Apache-2.0" ]
2
2022-01-21T18:15:34.000Z
2022-01-25T15:21:34.000Z
latent_programmer/decomposition_transformer_attention/train.py
ParikhKadam/google-research
00a282388e389e09ce29109eb050491c96cfab85
[ "Apache-2.0" ]
110
2021-10-01T18:22:38.000Z
2021-12-27T22:08:31.000Z
latent_programmer/decomposition_transformer_attention/train.py
admariner/google-research
7cee4b22b925581d912e8d993625c180da2a5a4f
[ "Apache-2.0" ]
1
2022-02-10T10:43:10.000Z
2022-02-10T10:43:10.000Z
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Train seq-to-seq model on random supervised training tasks.""" # pytype: disable=wrong-arg-count # pytype: disable=attribute-error import collections import functools import json import os import random import sys import time from absl import app from absl import flags from absl import logging from flax import jax_utils from flax import linen as nn from flax import optim from flax.metrics import tensorboard from flax.training import checkpoints from flax.training import common_utils import jax import jax.numpy as jnp import numpy as np import tensorflow.compat.v2 as tf from latent_programmer import decode from latent_programmer import models as base_models from latent_programmer.decomposition_transformer_attention import decomposition_models as models from latent_programmer.decomposition_transformer_attention import input_pipeline from latent_programmer.tasks.robust_fill import dsl from latent_programmer.tasks.robust_fill import tokens as dsl_tokens sys.path.append('../../') gfile = tf.io.gfile FLAGS = flags.FLAGS flags.DEFINE_integer('seed', 0, 'Fixed random seed for training.') flags.DEFINE_float('lr', 1e-3, 'Learning rate.') flags.DEFINE_float('weight_decay', 1e-1, 'Decay factor for AdamW-style weight decay.') flags.DEFINE_integer('embedding_dim', 256, 'Embedding dimension.') flags.DEFINE_integer('hidden_dim', 512, 'Hidden dimension.') flags.DEFINE_integer('num_heads', 4, 'Number of layers.') flags.DEFINE_integer('num_layers', 3, 'Number of Transformer heads.') flags.DEFINE_boolean('slow_decode', True, 'Use slow decoding for prediction?') flags.DEFINE_string('dataset_filepattern', None, 'Filepattern for TFRecord dataset.') flags.DEFINE_integer('per_device_batch_size', 16, 'Number of program tasks in a batch.') flags.DEFINE_integer('num_strings_per_task', 4, 'Number of input/output strings per task.') flags.DEFINE_integer('max_program_length', 100, 'Maximum number of tokens in program.') flags.DEFINE_integer('max_characters', 120, 'Maximum number of characters in input/output strings.') flags.DEFINE_string('save_dir', None, 'Directory to save results to.') flags.DEFINE_integer('num_train_steps', 2000000, 'Number of training steps.') flags.DEFINE_integer('num_eval_steps', 10, 'Number of evaluation steps.') flags.DEFINE_integer('log_freq', 1000, 'Number of steps between training logs.') flags.DEFINE_integer('eval_freq', 2000, 'Number of steps between eval.') flags.DEFINE_integer('predict_freq', 50000, 'Number of steps between prediction (beam search).') flags.DEFINE_integer('checkpoint_freq', 50000, 'Number of steps between checkpoint saves.') flags.DEFINE_integer('finetune_start_step', -1, 'Step the initial checkpoint should start at for ' 'finetuning, or -1 if not finetuning.') flags.DEFINE_bool('restore_checkpoints', True, 'Whether to restore from existing model checkpoints.') flags.DEFINE_string('attention_mask_type', 'bos_full_attention', 'The kind of attention mask to use. Options are: baseline, ' 'bos_to_bos, bos_full_attention') flags.DEFINE_bool('use_relative_attention', True, 'Whether to use relative positonal embeddings.') flags.DEFINE_bool('bos_special_attention', False, 'Whether to use special relative attention computation for ' 'BOS tokens.') _internal = False if not _internal: flags.DEFINE_string('xm_parameters', None, 'String specifying hyperparamter search.') def create_learning_rate_scheduler( base_learning_rate=0.5, factors='constant * linear_warmup * rsqrt_normalized_decay', warmup_steps=16000, decay_factor=0.5, steps_per_decay=50000, steps_per_cycle=100000): """Creates learning rate schedule. Interprets factors in the factors string which can consist of: * constant: interpreted as the constant value, * linear_warmup: interpreted as linear warmup until warmup_steps, * rsqrt_decay: divide by square root of max(step, warmup_steps) * decay_every: Every k steps decay the learning rate by decay_factor. * cosine_decay: Cyclic cosine decay, uses steps_per_cycle parameter. Args: base_learning_rate: float, the starting constant for the lr schedule. factors: a string with factors separated by '*' that defines the schedule. warmup_steps: how many steps to warm up for in the warmup schedule. decay_factor: The amount to decay the learning rate by. steps_per_decay: How often to decay the learning rate. steps_per_cycle: Steps per cycle when using cosine decay. Returns: A function learning_rate(step): float -> {'learning_rate': float}, the step-dependent lr. """ factors = [n.strip() for n in factors.split('*')] def step_fn(step): """Step to learning rate function.""" ret = 1.0 for name in factors: if name == 'constant': ret *= base_learning_rate elif name == 'linear_warmup': ret *= jnp.minimum(1.0, step / warmup_steps) elif name == 'rsqrt_decay': ret /= jnp.sqrt(jnp.maximum(1.0, step - warmup_steps)) elif name == 'rsqrt_normalized_decay': ret *= jnp.sqrt(warmup_steps) ret /= jnp.sqrt(jnp.maximum(step, warmup_steps)) elif name == 'decay_every': ret *= (decay_factor**(step // steps_per_decay)) elif name == 'cosine_decay': progress = jnp.maximum(0.0, (step - warmup_steps) / float(steps_per_cycle)) ret *= jnp.maximum(0.0, 0.5 * (1.0 + jnp.cos(jnp.pi * (progress % 1.0)))) else: raise ValueError('Unknown factor %s.' % name) return jnp.asarray(ret, dtype=jnp.float32) return step_fn def compute_weighted_cross_entropy(logits, targets, weights=None): """Compute weighted cross entropy and entropy for log probs and targets. Args: logits: `[batch, length, num_classes]` float array. targets: categorical targets `[batch, length]` int array. weights: None or array of shape [batch, length, 1] Returns: Tuple of scalar loss and batch normalizing factor. """ if logits.ndim != targets.ndim + 1: raise ValueError('Incorrect shapes. Got shape %s logits and %s targets' % (str(logits.shape), str(targets.shape))) onehot_targets = common_utils.onehot(targets, logits.shape[-1]) loss = -jnp.sum(onehot_targets * nn.log_softmax(logits), axis=-1) normalizing_factor = jnp.prod(jnp.asarray(targets.shape)) if weights is not None: loss = loss * weights normalizing_factor = weights.sum() return loss.sum(), normalizing_factor def compute_weighted_accuracy(logits, targets, weights=None): """Compute weighted accuracy for log probs and targets. Args: logits: `[batch, length, num_classes]` float array. targets: categorical targets `[batch, length]` int array. weights: None or array of shape [batch, length, 1] Returns: Tuple of scalar accuracy and batch normalizing factor. """ if logits.ndim != targets.ndim + 1: raise ValueError('Incorrect shapes. Got shape %s logits and %s targets' % (str(logits.shape), str(targets.shape))) acc = jnp.equal(jnp.argmax(logits, axis=-1), targets) normalizing_factor = jnp.prod(jnp.asarray(targets.shape)) if weights is not None: acc = acc * weights normalizing_factor = weights.sum() return acc.sum(), normalizing_factor def compute_metrics(logits, targets, weights): """Compute summary metrics.""" loss, weight_sum = compute_weighted_cross_entropy(logits, targets, weights) acc, _ = compute_weighted_accuracy(logits, targets, weights) metrics = { 'loss': loss, 'accuracy': acc, 'denominator': weight_sum, } metrics = jax.lax.psum(metrics, 'batch') return metrics # Train / eval / decode step functions. # ----------------------------------------------------------------------------- def train_step(optimizer, inputs, outputs, programs, learning_rate_fn, config, dropout_rng): """Train on batch of program tasks.""" # We handle PRNG splitting inside the top pmap, rather # than handling it outside in the training loop - doing the # latter can add some stalls to the devices. dropout_rng, new_dropout_rng = jax.random.split(dropout_rng) weights = jnp.where(programs > 0, 1, 0).astype(jnp.float32) def loss_fn(params): """Loss function used for training.""" logits = models.DecomposeAttentionTransformer(config).apply( {'params': params}, inputs, outputs, programs, rngs={'dropout': dropout_rng}) loss, weight_sum = compute_weighted_cross_entropy(logits, programs, weights) mean_loss = loss / weight_sum return mean_loss, logits step = optimizer.state.step lr = learning_rate_fn(step) grad_fn = jax.value_and_grad(loss_fn, has_aux=True) (_, logits), grad = grad_fn(optimizer.target) grad = jax.lax.pmean(grad, 'batch') new_optimizer = optimizer.apply_gradient(grad, learning_rate=lr) # Get metrics. metrics = compute_metrics(logits, programs, weights) metrics['learning_rate'] = lr return new_optimizer, metrics, new_dropout_rng def eval_step(params, inputs, outputs, programs, eos_token, config): """Collect metrics for evaluation during training.""" weights = jnp.where( jnp.logical_and(programs > 0, jnp.logical_and(programs != config.base_config.bos_token, programs != eos_token)), 1, 0).astype(jnp.float32) logits = models.DecomposeAttentionTransformer(config).apply( {'params': params}, inputs, outputs, programs) return compute_metrics(logits, programs, weights) def initialize_cache(inputs, outputs, programs, max_decode_len, config): """Initialize a cache for a given input shape and max decode length.""" target_shape = (programs.shape[0], max_decode_len) dtype = config.base_config.dtype initial_variables = models.DecomposeAttentionTransformer(config).init( jax.random.PRNGKey(0), jnp.ones(inputs.shape, dtype), jnp.ones(outputs.shape, dtype), jnp.ones(target_shape, dtype)) return initial_variables['cache'] def predict_step(params, inputs, outputs, cache, beam_size, eos_token, max_decode_len, config, slow_decode=True): """Predict translation with fast decoding beam search on a batch.""" # Prepare transformer fast-decoder call for beam search: for beam search, we # need to set up our decoder model to handle a batch size equal to # batch_size * beam_size, where each batch item's data is expanded in-place # rather than tiled. flat_encoded = decode.flat_batch_beam_expand( models.DecomposeAttentionTransformer(config).apply( {'params': params}, inputs, outputs, method=models.DecomposeAttentionTransformer.encode), beam_size) encoded_padding_mask = jnp.where(outputs > 0, 1, 0).astype(jnp.float32) flat_encoded_padding_mask = decode.flat_batch_beam_expand( encoded_padding_mask, beam_size) if slow_decode: def tokens_ids_to_logits(flat_ids): """Token slice to logits from decoder model.""" # --> [batch * beam, 1, vocab] flat_logits = models.DecomposeAttentionTransformer(config=config).apply( {'params': params}, flat_ids, flat_encoded, flat_encoded_padding_mask, method=models.DecomposeAttentionTransformer.decode) return flat_logits else: def tokens_ids_to_logits(flat_ids, flat_cache): """Token slice to logits from decoder model.""" # --> [batch * beam, 1, vocab] flat_logits, new_vars = models.DecomposeAttentionTransformer( config=config).apply( {'params': params, 'cache': flat_cache}, flat_ids, flat_encoded, flat_encoded_padding_mask, mutable=['cache'], method=models.DecomposeAttentionTransformer.decode) new_flat_cache = new_vars['cache'] # Remove singleton sequence-length dimension: # [batch * beam, 1, vocab] --> [batch * beam, vocab] flat_logits = flat_logits.squeeze(axis=1) return flat_logits, new_flat_cache # Using the above-defined single-step decoder function, run a # beam search over possible sequences given input encoding. beam_seqs, _ = decode.beam_search( inputs, cache, tokens_ids_to_logits, beam_size=beam_size, alpha=0.6, bos_token=config.base_config.bos_token, eos_token=eos_token, max_decode_len=max_decode_len, slow_decode=slow_decode) # Beam search returns [n_batch, n_beam, n_length] with beam dimension # sorted in increasing order of log-probability. return beam_seqs # Util functions for prediction # ----------------------------------------------------------------------------- def pad_examples(x, desired_batch_size): """Expand batch to desired size by repeating last slice.""" batch_pad = desired_batch_size - x.shape[0] tile_dims = [1] * len(x.shape) tile_dims[0] = batch_pad return np.concatenate([x, np.tile(x[-1], tile_dims)], axis=0) def tohost(x): """Collect batches from all devices to host and flatten batch dimensions.""" n_device, n_batch, *remaining_dims = x.shape return x.reshape((n_device * n_batch,) + tuple(remaining_dims)) def per_host_sum_pmap(in_tree): """Execute psum on in_tree's leaves over one device per host.""" host2devices = collections.defaultdict(list) for d in jax.devices(): host2devices[d.host_id].append(d) devices = [host2devices[k][0] for k in host2devices] host_psum = jax.pmap(lambda x: jax.lax.psum(x, 'i'), 'i', devices=devices) return post_pmap(host_psum(pre_pmap(in_tree))) def eval_predicted(predicted, inputs, outputs, parse_beam_fn): """Evaluate predicted program beams.""" best_p, best_score = None, -1 # predicted shape [beam_size, length] for beam in predicted[::-1]: try: p = parse_beam_fn(beam) p_outs = [p(inp) for inp in inputs] score = np.sum([p_out == out for p_out, out in zip(p_outs, outputs)]) if score > best_score: best_p, best_score = p, score except: # pylint: disable=bare-except pass if best_score >= len(inputs): # Found solution. break return best_p, best_score if __name__ == '__main__': app.run(main)
38.263421
96
0.661131
86ebf47f1f35ac5baec5295be6bb6feebf67dc9a
5,412
py
Python
plot/profile_interpolation/plot_profile.py
ziyixi/SeisScripts
a484bc1747eae52b2441f0bfd47ac7e093150f1d
[ "MIT" ]
null
null
null
plot/profile_interpolation/plot_profile.py
ziyixi/SeisScripts
a484bc1747eae52b2441f0bfd47ac7e093150f1d
[ "MIT" ]
null
null
null
plot/profile_interpolation/plot_profile.py
ziyixi/SeisScripts
a484bc1747eae52b2441f0bfd47ac7e093150f1d
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt import numpy as np import pandas as pd import click import numba # def get_value_func(x_mesh, y_mesh, z_mesh, value_mesh): # value_func = RegularGridInterpolator( # (x_mesh, y_mesh, z_mesh), value_mesh, method="nearest") # return value_func def generate_vertical_profile_grids(lon_list, lat_list, dep_list, hnpts, vnpts): lons = np.linspace(lon_list[0], lon_list[1], hnpts) lats = np.linspace(lat_list[0], lat_list[1], hnpts) deps = np.linspace(dep_list[0], dep_list[1], vnpts) return lons, lats, deps if __name__ == "__main__": main()
34.037736
153
0.636179
86ebfc32e5da592e6e4c3fa48a02c7a3cbe0a2ce
367
py
Python
tests/test_heroku.py
edpaget/flask-appconfig
5264719ac9229339070b219a4358a3203ffd05b0
[ "MIT" ]
61
2015-01-28T21:19:11.000Z
2020-12-28T10:12:28.000Z
tests/test_heroku.py
edpaget/flask-appconfig
5264719ac9229339070b219a4358a3203ffd05b0
[ "MIT" ]
3
2016-01-25T00:09:55.000Z
2017-09-25T11:36:19.000Z
tests/test_heroku.py
edpaget/flask-appconfig
5264719ac9229339070b219a4358a3203ffd05b0
[ "MIT" ]
14
2015-07-22T12:58:06.000Z
2021-03-24T02:06:30.000Z
from flask import Flask from flask_appconfig import HerokuConfig
22.9375
71
0.746594
86ec0f9bcbbfb50a7fe60cb1505775e1803a9dd4
396
py
Python
flask/util/logger.py
Dev-Jahn/cms
84ea115bdb865daff83d069502f6f0dd105fc4f0
[ "RSA-MD" ]
null
null
null
flask/util/logger.py
Dev-Jahn/cms
84ea115bdb865daff83d069502f6f0dd105fc4f0
[ "RSA-MD" ]
9
2021-01-05T07:48:28.000Z
2021-05-14T06:38:27.000Z
flask/util/logger.py
Dev-Jahn/cms
84ea115bdb865daff83d069502f6f0dd105fc4f0
[ "RSA-MD" ]
4
2021-01-05T06:46:09.000Z
2021-05-06T01:44:28.000Z
import logging """ Formatter """ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d:%H:%M:%S') """ Set Flask logger """ logger = logging.getLogger('FLASK_LOG') logger.setLevel(logging.DEBUG) stream_log = logging.StreamHandler() stream_log.setFormatter(formatter) logger.addHandler(stream_log) # if disabled # logger.disabled = True
20.842105
114
0.699495
86ecab271dab8a62fddc0d43582d82c9d0efb150
1,592
py
Python
utils/backups/backup_psql.py
Krovatkin/NewsBlur
2a5b52984c9d29c864eb80e9c60c658b1f25f7c5
[ "MIT" ]
null
null
null
utils/backups/backup_psql.py
Krovatkin/NewsBlur
2a5b52984c9d29c864eb80e9c60c658b1f25f7c5
[ "MIT" ]
null
null
null
utils/backups/backup_psql.py
Krovatkin/NewsBlur
2a5b52984c9d29c864eb80e9c60c658b1f25f7c5
[ "MIT" ]
null
null
null
#!/usr/bin/python3 import os import sys import socket CURRENT_DIR = os.path.dirname(__file__) NEWSBLUR_DIR = ''.join([CURRENT_DIR, '/../../']) sys.path.insert(0, NEWSBLUR_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'newsblur_web.settings' import threading import time import boto3 from django.conf import settings BACKUP_DIR = '/srv/newsblur/backup/' s3 = boto3.client('s3', aws_access_key_id=settings.S3_ACCESS_KEY, aws_secret_access_key=settings.S3_SECRET) hostname = socket.gethostname().replace('-','_') s3_object_name = f'backup_{hostname}/backup_{hostname}_{time.strftime("%Y-%m-%d-%H-%M")}.sql' path = os.listdir(BACKUP_DIR)[0] full_path = os.path.join(BACKUP_DIR, path) print('Uploading %s to %s on S3 bucket %s' % (full_path, s3_object_name, settings.S3_BACKUP_BUCKET)) s3.upload_file(full_path, settings.S3_BACKUP_BUCKET, s3_object_name, Callback=ProgressPercentage(full_path)) os.remove(full_path)
34.608696
108
0.682161
86ecdb5499de55821a90a7d456c0a5f3e2bbff3c
22,780
py
Python
onap_tests/scenario/solution.py
Orange-OpenSource/xtesting-onap-tests
ce4237f49089a91c81f5fad552f78fec384fd504
[ "Apache-2.0" ]
null
null
null
onap_tests/scenario/solution.py
Orange-OpenSource/xtesting-onap-tests
ce4237f49089a91c81f5fad552f78fec384fd504
[ "Apache-2.0" ]
null
null
null
onap_tests/scenario/solution.py
Orange-OpenSource/xtesting-onap-tests
ce4237f49089a91c81f5fad552f78fec384fd504
[ "Apache-2.0" ]
2
2018-06-08T15:49:51.000Z
2021-06-22T10:06:30.000Z
#!/usr/bin/python # # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # # pylint: disable=missing-docstring # pylint: disable=duplicate-code import logging import time import onap_tests.components.aai as aai import onap_tests.components.so as so import onap_tests.components.sdnc as sdnc import onap_tests.components.nbi as nbi import onap_tests.utils.stack_checker as sc import onap_tests.utils.utils as onap_utils PROXY = onap_utils.get_config("general.proxy")
42.342007
80
0.554478
86ecf5f6a01c26c5389153d1137d146050eff0e3
3,262
py
Python
tutorials/Controls4Docs/ControlEventsGraph.py
dominic-dev/pyformsd
23e31ceff2943bc0f7286d25dd14450a14b986af
[ "MIT" ]
null
null
null
tutorials/Controls4Docs/ControlEventsGraph.py
dominic-dev/pyformsd
23e31ceff2943bc0f7286d25dd14450a14b986af
[ "MIT" ]
null
null
null
tutorials/Controls4Docs/ControlEventsGraph.py
dominic-dev/pyformsd
23e31ceff2943bc0f7286d25dd14450a14b986af
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Ricardo Ribeiro" __credits__ = ["Ricardo Ribeiro"] __license__ = "MIT" __version__ = "0.0" __maintainer__ = "Ricardo Ribeiro" __email__ = "[email protected]" __status__ = "Development" from __init__ import * import random, time from PyQt4 import QtCore ################################################################################################################## ################################################################################################################## ################################################################################################################## #Execute the application if __name__ == "__main__": pyforms.start_app( SimpleExample )
27.183333
116
0.62477
86ecf632226839fdabd506f9f83e9358864f79de
4,447
py
Python
annotation_gui_gcp/orthophoto_view.py
lioncorpo/sfm.lion-judge-corporation
95fb11bff263c3faab62269cc907eec18b527e22
[ "BSD-2-Clause" ]
1
2019-05-31T13:50:41.000Z
2019-05-31T13:50:41.000Z
annotation_gui_gcp/orthophoto_view.py
Pandinosaurus/OpenSfM
b892ba9fd5e7fd6c7a9e3c81edddca80f71c1cd5
[ "BSD-2-Clause" ]
null
null
null
annotation_gui_gcp/orthophoto_view.py
Pandinosaurus/OpenSfM
b892ba9fd5e7fd6c7a9e3c81edddca80f71c1cd5
[ "BSD-2-Clause" ]
2
2017-03-31T16:54:34.000Z
2018-07-10T11:32:22.000Z
from typing import Tuple import numpy as np import rasterio.warp from opensfm import features from .orthophoto_manager import OrthoPhotoManager from .view import View
35.293651
83
0.613672
86eee025668f1ba4e581d9197ce7264211e57bc7
3,704
py
Python
tempest/tests/lib/services/compute/test_security_group_default_rules_client.py
mail2nsrajesh/tempest
1a3b3dc50b418d3a15839830d7d1ff88c8c76cff
[ "Apache-2.0" ]
254
2015-01-05T19:22:52.000Z
2022-03-29T08:14:54.000Z
tempest/tests/lib/services/compute/test_security_group_default_rules_client.py
mail2nsrajesh/tempest
1a3b3dc50b418d3a15839830d7d1ff88c8c76cff
[ "Apache-2.0" ]
13
2015-03-02T15:53:04.000Z
2022-02-16T02:28:14.000Z
tempest/tests/lib/services/compute/test_security_group_default_rules_client.py
mail2nsrajesh/tempest
1a3b3dc50b418d3a15839830d7d1ff88c8c76cff
[ "Apache-2.0" ]
367
2015-01-07T15:05:39.000Z
2022-03-04T09:50:35.000Z
# Copyright 2015 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib.services.compute import security_group_default_rules_client from tempest.tests.lib import fake_auth_provider from tempest.tests.lib.services import base
41.617978
78
0.704644
86ef419ce9a394c69c1d9d5b8bea2b3d98c02484
29,478
py
Python
pirates/leveleditor/worldData/interior_spanish_npc_b.py
itsyaboyrocket/pirates
6ca1e7d571c670b0d976f65e608235707b5737e3
[ "BSD-3-Clause" ]
3
2021-02-25T06:38:13.000Z
2022-03-22T07:00:15.000Z
pirates/leveleditor/worldData/interior_spanish_npc_b.py
itsyaboyrocket/pirates
6ca1e7d571c670b0d976f65e608235707b5737e3
[ "BSD-3-Clause" ]
null
null
null
pirates/leveleditor/worldData/interior_spanish_npc_b.py
itsyaboyrocket/pirates
6ca1e7d571c670b0d976f65e608235707b5737e3
[ "BSD-3-Clause" ]
1
2021-02-25T06:38:17.000Z
2021-02-25T06:38:17.000Z
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.leveleditor.worldData.interior_spanish_npc_b from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Objects': {'1153420207.67dzlu01': {'Type': 'Building Interior', 'Name': '', 'Instanced': True, 'Objects': {'1165347933.66kmuller': {'Type': 'Log_Stack', 'DisableCollision': True, 'Hpr': VBase3(139.803, 0.0, 0.0), 'Pos': Point3(2.978, 25.796, 0.048), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Log_stack_a'}}, '1166138034.99kmuller': {'Type': 'Log_Stack', 'DisableCollision': True, 'Hpr': VBase3(179.29, 0.0, 0.0), 'Pos': Point3(9.307, 24.592, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Log_stack_b'}}, '1166138092.34kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(-90.005, 0.0, 0.0), 'Pos': Point3(18.672, 15.355, 0.009), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/cabinet_spanish_low'}}, '1166138151.37kmuller': {'Type': 'Pots', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(18.938, 13.997, 2.735), 'Scale': VBase3(1.464, 1.464, 1.464), 'Visual': {'Model': 'models/props/pot_A'}}, '1166138161.79kmuller': {'Type': 'Pots', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(18.511, 15.482, 3.364), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pot_B'}}, '1166138390.93kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-0.303, 0.276, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.75, 0.9300000071525574, 1.0, 1.0), 'Model': 'models/props/table_bar_round'}}, '1166138443.79kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(-134.164, 0.0, 0.0), 'Pos': Point3(4.61, -3.84, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bank'}}, '1166138454.85kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(54.358, 0.0, 0.0), 'Pos': Point3(-6.565, 0.327, 0.038), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bar'}}, '1166138510.96kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(162.38, 0.0, 0.0), 'Pos': Point3(-3.36, -6.982, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bank'}}, '1166138524.92kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(80.452, 0.0, 0.0), 'Pos': Point3(5.079, 5.725, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bar'}}, '1166138537.42kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(25.255, 0.0, 0.0), 'Pos': Point3(-1.381, 6.177, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bank'}}, '1166138621.31kmuller': {'Type': 'Jugs_and_Jars', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(0.672, -2.129, 3.008), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/bottle_green'}}, '1166138646.6kmuller': {'Type': 'Jugs_and_Jars', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-0.184, 1.377, 3.061), 'Scale': VBase3(1.429, 1.429, 1.429), 'Visual': {'Model': 'models/props/waterpitcher'}}, '1166138674.59kmuller': {'Type': 'Baskets', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(1.112, 0.235, 2.971), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/basket'}}, '1166138708.48kmuller': {'Type': 'Food', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(19.066, 23.998, 3.071), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/sausage'}}, '1166138742.6kmuller': {'Type': 'Food', 'DisableCollision': False, 'Hpr': VBase3(0.0, -4.607, 0.0), 'Pos': Point3(12.569, 24.56, 2.688), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/garlicString'}}, '1166138817.45kmuller': {'Type': 'Bucket', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(17.053, 10.72, 0.006), 'Scale': VBase3(0.665, 0.665, 0.665), 'Visual': {'Model': 'models/props/washtub'}}, '1166138973.9kmuller': {'Type': 'Tools', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(18.741, 7.367, 0.02), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/butter_churn'}}, '1166139009.4kmuller': {'Type': 'Tools', 'DisableCollision': False, 'Hpr': VBase3(-2.549, 12.708, -168.558), 'Pos': Point3(-7.195, -29.635, 4.369), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/broom'}}, '1166139125.65kmuller': {'Type': 'Furniture - Fancy', 'DisableCollision': True, 'Hpr': VBase3(179.014, 0.0, 0.0), 'Pos': Point3(-16.599, -28.46, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/cabinet_fancy_tall'}}, '1166139259.49kmuller': {'Type': 'Mortar_Pestle', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(19.246, 16.431, 3.391), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/mortar_pestle_stone'}}, '1166139339.62kmuller': {'Type': 'Prop_Groups', 'DisableCollision': True, 'Hpr': VBase3(57.552, 0.0, 0.0), 'Pos': Point3(15.438, -23.688, 0.048), 'Scale': VBase3(0.879, 0.879, 0.879), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/props/prop_group_G'}}, '1166139450.46kmuller': {'Type': 'Trunks', 'DisableCollision': True, 'Hpr': VBase3(-175.386, 0.0, 0.0), 'Pos': Point3(-11.623, -28.323, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Trunk_rounded_2'}}, '1166139482.6kmuller': {'Type': 'Trunks', 'DisableCollision': False, 'Hpr': VBase3(-100.398, 0.0, 0.0), 'Pos': Point3(17.54, -12.363, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Trunk_square'}}, '1166139534.14kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(88.8, 0.0, 0.0), 'Pos': Point3(-19.032, -8.401, 0.172), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/bench_bank'}}, '1166139664.39kmuller': {'Type': 'Bucket', 'DisableCollision': True, 'Hpr': VBase3(-38.995, 0.0, 0.0), 'Pos': Point3(4.278, 24.282, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/bucket_handles'}}, '1166139726.17kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-56.33, 0.0, 0.0), 'Pos': Point3(20.726, 15.931, 4.923), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/candle_holder'}}, '1166139823.07kmuller': {'Type': 'Pan', 'DisableCollision': False, 'Hpr': VBase3(-45.198, -0.006, 0.006), 'Pos': Point3(21.602, 17.485, 4.688), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pan'}}, '1166139883.79kmuller': {'Type': 'Jugs_and_Jars', 'DisableCollision': False, 'Hpr': VBase3(2.971, 0.0, 0.0), 'Pos': Point3(21.796, 18.912, 4.7), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/largejug_B'}}, '1166140032.53kmuller': {'Type': 'Wall_Hangings', 'DisableCollision': False, 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(-2.651, 29.91, 7.991), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Map_01'}}, '1166143136.15kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(87.919, 0.0, 0.0), 'Pos': Point3(-19.128, 10.233, 7.623), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/lamp_candle'}}, '1166143173.57kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(87.919, 0.0, 0.0), 'Pos': Point3(-19.101, -8.222, 7.695), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/lamp_candle'}}, '1166143204.95kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-90.159, 0.0, 0.0), 'Pos': Point3(18.91, 9.923, 7.471), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/lamp_candle'}}, '1166143219.04kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-90.159, 0.0, 0.0), 'Pos': Point3(19.055, -9.027, 7.695), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/lamp_candle'}}, '1166143244.09kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-0.798, 10.488, 17.608), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chandelier_jail'}}, '1166143275.89kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-0.592, -10.927, 17.594), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chandelier_jail'}}, '1167972216.85kmuller': {'Type': 'Furniture', 'DisableCollision': True, 'Hpr': VBase3(44.958, 0.0, 0.0), 'Pos': Point3(-16.331, 26.168, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/bookshelf_spanish'}}, '1167972409.16kmuller': {'Type': 'Tools', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-19.259, 21.62, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/butter_churn'}}, '1176423441.61dzlu': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '97.7273', 'DropOff': '6.8182', 'FlickRate': 0.5, 'Flickering': False, 'Hpr': VBase3(6.993, -61.677, 8.03), 'Intensity': '0.4242', 'LightType': 'SPOT', 'Pos': Point3(2.574, -18.447, 27.908), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.8700000047683716, 1.0, 1.0, 1.0), 'Model': 'models/props/light_tool_bulb'}}, '1176423539.22dzlu': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '64.3182', 'DropOff': '39.5455', 'FlickRate': 0.5, 'Flickering': False, 'Hpr': VBase3(5.763, -56.906, 6.972), 'Intensity': '0.4848', 'LightType': 'SPOT', 'Pos': Point3(-1.976, 15.649, 24.802), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.8700000047683716, 1.0, 1.0, 1.0), 'Model': 'models/props/light_tool_bulb'}}, '1176423736.28dzlu': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '60.0000', 'DropOff': '0.0000', 'FlickRate': 0.5, 'Flickering': True, 'Hpr': VBase3(0.0, 1.848, 0.0), 'Intensity': '0.5152', 'LightType': 'POINT', 'Pos': Point3(-0.034, -10.675, 13.873), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.95, 0.78, 0.64, 1.0), 'Model': 'models/props/light_tool_bulb'}}, '1176424160.2dzlu': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '60.0000', 'DropOff': '0.0000', 'FlickRate': 0.5, 'Flickering': False, 'Hpr': VBase3(0.0, 1.848, 0.0), 'Intensity': '0.6061', 'LightType': 'POINT', 'Pos': Point3(-0.105, 11.422, 13.384), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.95, 0.78, 0.64, 1.0), 'Model': 'models/props/light_tool_bulb'}}, '1185496415.31kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(4.727, 26.813, -0.119), 'Scale': VBase3(2.057, 1.302, 1.198), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}}, '1185496487.15kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(45.263, 0.0, 0.0), 'Pos': Point3(-15.061, 24.578, -0.449), 'Scale': VBase3(1.603, 1.0, 1.891), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185496538.15kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-15.225, -28.682, -0.316), 'Scale': VBase3(2.053, 0.567, 2.235), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}}, '1185496598.36kmuller': {'Type': 'Barrel', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(8.521, -28.523, 0.0), 'Scale': VBase3(0.77, 0.77, 0.77), 'Visual': {'Color': (0.47999998927116394, 0.44999998807907104, 0.4099999964237213, 1.0), 'Model': 'models/props/barrel_grey'}}, '1185496634.87kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-105.442, 0.0, 0.0), 'Pos': Point3(6.902, -26.349, -0.415), 'Scale': VBase3(0.856, 1.0, 1.451), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185496663.32kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-134.387, 0.0, 0.0), 'Pos': Point3(11.183, -19.168, -0.394), 'Scale': VBase3(0.955, 1.0, 1.0), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185496695.84kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(177.474, 0.0, 0.0), 'Pos': Point3(18.836, -16.153, -1.477), 'Scale': VBase3(0.944, 1.0, 1.196), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1192813036.19akelts': {'Type': 'Effect Node', 'EffectName': 'torch_effect', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(16.066, 27.69, 0.728), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1228171574.52kmuller': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-1.084, 0.0, 0.0), 'Pos': Point3(0.226, -30.04, -0.042), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1228171636.05kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-19.562, -12.628, 9.043), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171658.06kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-19.497, -4.055, 8.9), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171680.97kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-19.522, 13.075, 8.571), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171681.0kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-19.48, 6.987, 8.709), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171718.55kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-23.464, 2.055, 9.623), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1228171851.33kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(19.558, 12.771, 8.257), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171851.36kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(19.6, 6.683, 8.394), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171851.37kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(19.605, -5.139, 8.562), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171851.39kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(19.519, -12.932, 8.729), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171985.95kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(23.294, 2.108, 9.247), 'Scale': VBase3(1.749, 1.749, 1.749), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1228172029.81kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-22.915, 0.0, 0.0), 'Pos': Point3(-14.676, 27.506, 8.319), 'Scale': VBase3(0.745, 0.745, 0.745), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift03_winter08'}}, '1228172067.47kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(97.294, 0.0, 0.0), 'Pos': Point3(17.725, -11.752, 1.974), 'Scale': VBase3(0.877, 0.877, 0.877), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift03_winter08'}}, '1228172094.37kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(20.62, 0.0, 0.0), 'Pos': Point3(17.402, -13.417, 1.908), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift02_winter08'}}, '1228172137.52kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(22.222, 0.0, 0.0), 'Pos': Point3(-14.48, 27.114, 2.476), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift03_winter08'}}, '1228172150.87kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(43.198, 0.0, 0.0), 'Pos': Point3(-15.74, 26.194, 4.277), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift04_winter08'}}, '1257805377.33caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(29.215, 0.0, 0.0), 'Pos': Point3(-17.989, 24.828, 8.291), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift01_winter08'}}, '1257805389.23caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-80.692, 0.0, 0.0), 'Pos': Point3(-16.187, 26.439, 8.319), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift04_winter08'}}, '1257805548.61caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(179.828, 0.0, 0.0), 'Pos': Point3(0.134, -29.849, 16.921), 'Scale': VBase3(1.647, 1.647, 1.647), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoRibbon_winter08'}}, '1257805573.24caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-179.622, 0.0, 0.0), 'Pos': Point3(13.583, -29.761, 16.921), 'Scale': VBase3(1.647, 1.647, 1.647), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoRibbon_winter08'}}, '1257805604.96caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-3.461, -2.873, 38.03), 'Pos': Point3(1.516, -29.874, 17.264), 'Scale': VBase3(3.099, 3.099, 3.099), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}, '1257805629.21caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(178.92, 6.382, 0.0), 'Pos': Point3(-13.08, -29.713, 16.646), 'Scale': VBase3(1.795, 1.795, 1.795), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1257805691.46caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-178.182, 2.38, 35.723), 'Pos': Point3(-1.065, -29.816, 17.292), 'Scale': VBase3(3.099, 3.099, 3.099), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}, '1257805757.37caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(178.92, 6.382, 0.0), 'Pos': Point3(0.206, -29.526, 16.511), 'Scale': VBase3(1.795, 1.795, 1.795), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1257805801.97caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(178.92, 6.382, 0.0), 'Pos': Point3(13.537, -29.768, 16.596), 'Scale': VBase3(1.795, 1.795, 1.795), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1257891327.63caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(40.405, 0.0, 0.0), 'Pos': Point3(-1.49, 0.401, 2.948), 'Scale': VBase3(0.743, 0.743, 0.743), 'VisSize': '', 'Visual': {'Color': (0.6000000238418579, 1.0, 0.800000011920929, 1.0), 'Model': 'models/props/pir_m_prp_hol_decoGift01_winter08'}}, '1257891346.66caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-180.0, -89.326, -179.539), 'Pos': Point3(-2.572, 0.139, 2.984), 'Scale': VBase3(0.929, 0.929, 0.929), 'VisSize': '', 'Visual': {'Color': (0.800000011920929, 0.800000011920929, 1.0, 1.0), 'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}, '1257891403.07caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-2.297, 1.647, 2.948), 'Scale': VBase3(0.515, 0.515, 0.515), 'VisSize': '', 'Visual': {'Color': (0.800000011920929, 0.800000011920929, 1.0, 1.0), 'Model': 'models/props/pir_m_prp_hol_decoGift01_winter08'}}, '1257891450.24caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(180.0, -89.326, 138.895), 'Pos': Point3(-2.13, -0.697, 2.993), 'Scale': VBase3(0.929, 0.929, 0.929), 'VisSize': '', 'Visual': {'Color': (0.800000011920929, 0.800000011920929, 1.0, 1.0), 'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}}, 'Visual': {'Model': 'models/buildings/interior_spanish_npc'}}}, 'Node Links': [], 'Layers': {}, 'ObjectIds': {'1153420207.67dzlu01': '["Objects"]["1153420207.67dzlu01"]', '1165347933.66kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1165347933.66kmuller"]', '1166138034.99kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138034.99kmuller"]', '1166138092.34kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138092.34kmuller"]', '1166138151.37kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138151.37kmuller"]', '1166138161.79kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138161.79kmuller"]', '1166138390.93kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138390.93kmuller"]', '1166138443.79kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138443.79kmuller"]', '1166138454.85kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138454.85kmuller"]', '1166138510.96kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138510.96kmuller"]', '1166138524.92kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138524.92kmuller"]', '1166138537.42kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138537.42kmuller"]', '1166138621.31kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138621.31kmuller"]', '1166138646.6kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138646.6kmuller"]', '1166138674.59kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138674.59kmuller"]', '1166138708.48kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138708.48kmuller"]', '1166138742.6kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138742.6kmuller"]', '1166138817.45kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138817.45kmuller"]', '1166138973.9kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138973.9kmuller"]', '1166139009.4kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139009.4kmuller"]', '1166139125.65kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139125.65kmuller"]', '1166139259.49kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139259.49kmuller"]', '1166139339.62kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139339.62kmuller"]', '1166139450.46kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139450.46kmuller"]', '1166139482.6kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139482.6kmuller"]', '1166139534.14kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139534.14kmuller"]', '1166139664.39kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139664.39kmuller"]', '1166139726.17kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139726.17kmuller"]', '1166139823.07kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139823.07kmuller"]', '1166139883.79kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139883.79kmuller"]', '1166140032.53kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166140032.53kmuller"]', '1166143136.15kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143136.15kmuller"]', '1166143173.57kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143173.57kmuller"]', '1166143204.95kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143204.95kmuller"]', '1166143219.04kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143219.04kmuller"]', '1166143244.09kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143244.09kmuller"]', '1166143275.89kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143275.89kmuller"]', '1167972216.85kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1167972216.85kmuller"]', '1167972409.16kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1167972409.16kmuller"]', '1176423441.61dzlu': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1176423441.61dzlu"]', '1176423539.22dzlu': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1176423539.22dzlu"]', '1176423736.28dzlu': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1176423736.28dzlu"]', '1176424160.2dzlu': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1176424160.2dzlu"]', '1185496415.31kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496415.31kmuller"]', '1185496487.15kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496487.15kmuller"]', '1185496538.15kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496538.15kmuller"]', '1185496598.36kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496598.36kmuller"]', '1185496634.87kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496634.87kmuller"]', '1185496663.32kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496663.32kmuller"]', '1185496695.84kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496695.84kmuller"]', '1192813036.19akelts': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1192813036.19akelts"]', '1228171574.52kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171574.52kmuller"]', '1228171636.05kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171636.05kmuller"]', '1228171658.06kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171658.06kmuller"]', '1228171680.97kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171680.97kmuller"]', '1228171681.0kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171681.0kmuller"]', '1228171718.55kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171718.55kmuller"]', '1228171851.33kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171851.33kmuller"]', '1228171851.36kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171851.36kmuller"]', '1228171851.37kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171851.37kmuller"]', '1228171851.39kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171851.39kmuller"]', '1228171985.95kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171985.95kmuller"]', '1228172029.81kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172029.81kmuller"]', '1228172067.47kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172067.47kmuller"]', '1228172094.37kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172094.37kmuller"]', '1228172137.52kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172137.52kmuller"]', '1228172150.87kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172150.87kmuller"]', '1257805377.33caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805377.33caoconno"]', '1257805389.23caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805389.23caoconno"]', '1257805548.61caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805548.61caoconno"]', '1257805573.24caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805573.24caoconno"]', '1257805604.96caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805604.96caoconno"]', '1257805629.21caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805629.21caoconno"]', '1257805691.46caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805691.46caoconno"]', '1257805757.37caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805757.37caoconno"]', '1257805801.97caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805801.97caoconno"]', '1257891327.63caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257891327.63caoconno"]', '1257891346.66caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257891346.66caoconno"]', '1257891403.07caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257891403.07caoconno"]', '1257891450.24caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257891450.24caoconno"]'}} extraInfo = {'camPos': Point3(0, -14, 0), 'camHpr': VBase3(0, 0, 0), 'focalLength': 0.852765381336, 'skyState': -1, 'fog': 0}
4,211.142857
29,056
0.664631
86ef4e909fe2cea39d77e8fe80f71f1e8cdcd676
1,844
py
Python
main.py
Light-Lens/PassGen
8f4f2ef08299d6243b939d0f08ac75bde3cabf5e
[ "MIT" ]
3
2021-07-19T16:39:06.000Z
2021-11-08T11:53:50.000Z
main.py
Light-Lens/PassGen
8f4f2ef08299d6243b939d0f08ac75bde3cabf5e
[ "MIT" ]
null
null
null
main.py
Light-Lens/PassGen
8f4f2ef08299d6243b939d0f08ac75bde3cabf5e
[ "MIT" ]
null
null
null
# PassGen # These imports will be used for this project. from colorama import Fore, Style from colorama import init import datetime import string import random import sys import os # Initilaze File organizer. os.system('title PassGen') init(autoreset = True) # Create Log Functions. # This will Generate a Strong Password for the User! def Generate(PassLen): JoinChars = [] # Create an Empty List. # Split the List of these String Operations, and Join them to JoinChars List. JoinChars.extend(list(string.ascii_letters)) JoinChars.extend(list(string.digits)) JoinChars.extend(list(string.punctuation)) random.shuffle(JoinChars) # Shuffle the List. # Get the random passoword. return "".join(JoinChars[0:PassLen]) # Code Logic here. LOG.WARN_LOG("Initialized PassGen!") LOG.STATUS_LOG("Generating a Random Password for You.") Password = Generate(random.randint(5, 17)) LOG.INFO_LOG(f"Your Password is: {Password}") with open("Password.log", "a") as File: File.write(f"{Password}\n") if (len(sys.argv) == 1) or (len(sys.argv) > 1 and sys.argv[1].lower() != "-o"): os.system("start Password.log") sys.exit() # Exiting the program successfully.
32.350877
80
0.691432
86ef847c1cba2674adc29aa5bed41c18d23f595a
24,723
py
Python
memos/memos/models/Memo.py
iotexpert/docmgr
735c7bcbaeb73bc44efecffb175f268f2438ac3a
[ "MIT" ]
null
null
null
memos/memos/models/Memo.py
iotexpert/docmgr
735c7bcbaeb73bc44efecffb175f268f2438ac3a
[ "MIT" ]
null
null
null
memos/memos/models/Memo.py
iotexpert/docmgr
735c7bcbaeb73bc44efecffb175f268f2438ac3a
[ "MIT" ]
null
null
null
""" The model file for a Memo """ import re import os import shutil import json from datetime import datetime from flask import current_app from memos import db from memos.models.User import User from memos.models.MemoState import MemoState from memos.models.MemoFile import MemoFile from memos.models.MemoSignature import MemoSignature from memos.models.MemoReference import MemoReference from memos.models.MemoHistory import MemoHistory from memos.models.MemoActivity import MemoActivity from memos.revletter import b10_to_rev, rev_to_b10
39.367834
190
0.582049
86f060997b8a24b2a713e28d30aebb3fc5274d62
1,385
py
Python
course_catalog/etl/conftest.py
mitodl/open-discussions
ab6e9fac70b8a1222a84e78ba778a7a065c20541
[ "BSD-3-Clause" ]
12
2017-09-27T21:23:27.000Z
2020-12-25T04:31:30.000Z
course_catalog/etl/conftest.py
mitodl/open-discussions
ab6e9fac70b8a1222a84e78ba778a7a065c20541
[ "BSD-3-Clause" ]
3,293
2017-06-30T18:16:01.000Z
2022-03-31T18:01:34.000Z
course_catalog/etl/conftest.py
mitodl/open-discussions
ab6e9fac70b8a1222a84e78ba778a7a065c20541
[ "BSD-3-Clause" ]
1
2020-04-13T12:19:57.000Z
2020-04-13T12:19:57.000Z
"""Common ETL test fixtures""" import json import pytest
32.209302
80
0.716245
86f07721893f6c50f28bc8f37736be7b92dba3a5
8,850
py
Python
juliaset/juliaset.py
PageotD/juliaset
7c1f98020eeff291fcf040cfcdf25a89e72f46a9
[ "BSD-3-Clause" ]
null
null
null
juliaset/juliaset.py
PageotD/juliaset
7c1f98020eeff291fcf040cfcdf25a89e72f46a9
[ "BSD-3-Clause" ]
null
null
null
juliaset/juliaset.py
PageotD/juliaset
7c1f98020eeff291fcf040cfcdf25a89e72f46a9
[ "BSD-3-Clause" ]
1
2021-08-09T06:45:43.000Z
2021-08-09T06:45:43.000Z
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import random def julia(**kwargs): """ temp """ # Initialize Julia Set instance juliaInstance = JuliaSet() # If kwargs not empty update the attributes if kwargs is not None: juliaInstance.param(**kwargs) return juliaInstance if __name__ == "__main__": # execute only if run as a script genJuliaSet = JuliaSet() genJuliaSet.param() genJuliaSet.run()
32.417582
89
0.566328
86f0877f437e0d2341e2d9c4fb9323bda9c076fe
1,212
py
Python
eye_detection.py
ShivanS93/VAtest_withOKN
8da76f4c3ff526c9e16268194accfdc6221b0a66
[ "MIT" ]
null
null
null
eye_detection.py
ShivanS93/VAtest_withOKN
8da76f4c3ff526c9e16268194accfdc6221b0a66
[ "MIT" ]
null
null
null
eye_detection.py
ShivanS93/VAtest_withOKN
8da76f4c3ff526c9e16268194accfdc6221b0a66
[ "MIT" ]
null
null
null
#!python3 # eye_detection.py - detect eyes using webcam # tutorial: https://www.roytuts.com/real-time-eye-detection-in-webcam-using-python-3/ import cv2 import math import numpy as np if __name__ == "__main__": main()
24.734694
86
0.575908
86f0c522be62919400b4d5f2f8a78d4b4a38dcb9
399
py
Python
scripts/make_gene_table.py
lmdu/bioinfo
4542b0718410d15f3956c6545d9824a16608e02b
[ "MIT" ]
null
null
null
scripts/make_gene_table.py
lmdu/bioinfo
4542b0718410d15f3956c6545d9824a16608e02b
[ "MIT" ]
null
null
null
scripts/make_gene_table.py
lmdu/bioinfo
4542b0718410d15f3956c6545d9824a16608e02b
[ "MIT" ]
null
null
null
#!/usr/bin/env python descripts = {} with open('macaca_genes.txt') as fh: fh.readline() for line in fh: cols = line.strip('\n').split('\t') if cols[1]: descripts[cols[0]] = cols[1].split('[')[0].strip() else: descripts[cols[0]] = cols[1] with open('gene_info.txt') as fh: for line in fh: cols = line.strip().split('\t') cols.append(descripts[cols[1]]) print "\t".join(cols)
19.95
53
0.611529
86f16e97aa13775a35aa0ced03caeac309db0c51
4,627
py
Python
{{cookiecutter.repo_name}}/src/mix_with_scaper.py
nussl/cookiecutter
5df8512592778ea7155b05e3e4b54676227968b0
[ "MIT" ]
null
null
null
{{cookiecutter.repo_name}}/src/mix_with_scaper.py
nussl/cookiecutter
5df8512592778ea7155b05e3e4b54676227968b0
[ "MIT" ]
null
null
null
{{cookiecutter.repo_name}}/src/mix_with_scaper.py
nussl/cookiecutter
5df8512592778ea7155b05e3e4b54676227968b0
[ "MIT" ]
null
null
null
import gin from scaper import Scaper, generate_from_jams import copy import logging import p_tqdm import nussl import os import numpy as np def make_one_mixture(sc, path_to_file, num_sources, event_parameters, allow_repeated_label): """ Creates a single mixture, incoherent. Instantiates according to the event parameters for each source. """ check = False while not check: for j in range(num_sources): sc.add_event(**event_parameters) sc.generate( path_to_file, path_to_file.replace('.wav', '.jams'), no_audio=False, allow_repeated_label=allow_repeated_label, save_isolated_events=True, ) _reset_event_spec(sc) check = check_mixture(path_to_file)
31.691781
87
0.612708
86f1999802fa178d60effb8dd046d22fbb0dd814
4,643
py
Python
adventure-cards/package/main.py
DaneRosa/adventure-cards
0685feeec8b56627795e685ff4fffad187881e1c
[ "MIT" ]
null
null
null
adventure-cards/package/main.py
DaneRosa/adventure-cards
0685feeec8b56627795e685ff4fffad187881e1c
[ "MIT" ]
null
null
null
adventure-cards/package/main.py
DaneRosa/adventure-cards
0685feeec8b56627795e685ff4fffad187881e1c
[ "MIT" ]
null
null
null
import json
48.873684
92
0.420633
86f19d8269d91051babd1a81669ee8409fe871bc
1,328
py
Python
demo/cnn_predict.py
huynhtnhut97/keras-video-classifier
3ea6a8d671f3bd3cc8eddef64ad75abc2a2d593a
[ "MIT" ]
108
2018-03-01T10:03:22.000Z
2022-03-27T03:00:30.000Z
demo/cnn_predict.py
drsagitn/lstm-video-classifier
3d1bce6773e493bdff5d623883d47ca68d45e890
[ "MIT" ]
18
2020-01-28T22:13:07.000Z
2022-03-11T23:54:10.000Z
demo/cnn_predict.py
drsagitn/lstm-video-classifier
3d1bce6773e493bdff5d623883d47ca68d45e890
[ "MIT" ]
56
2018-03-01T10:03:22.000Z
2022-02-23T08:19:10.000Z
import numpy as np from keras import backend as K import os import sys K.set_image_dim_ordering('tf') if __name__ == '__main__': main()
30.883721
110
0.758283
86f2a90daa96d1b00a32e75d50fd040ca01ed705
172
py
Python
pyconde/context_processors.py
EuroPython/djep
afcccbdda483e5f6962ac97f0dc4c4c5ea67fd21
[ "BSD-3-Clause" ]
5
2015-01-02T14:33:14.000Z
2021-08-03T10:19:07.000Z
pyconde/context_processors.py
EuroPython/djep
afcccbdda483e5f6962ac97f0dc4c4c5ea67fd21
[ "BSD-3-Clause" ]
null
null
null
pyconde/context_processors.py
EuroPython/djep
afcccbdda483e5f6962ac97f0dc4c4c5ea67fd21
[ "BSD-3-Clause" ]
3
2015-08-30T09:45:03.000Z
2017-04-08T12:15:22.000Z
from django.conf import settings
21.5
89
0.732558
86f3b70aa2f3c882bdd1f178d6aa80fab1793aab
5,898
py
Python
pmdarima/preprocessing/endog/boxcox.py
tuomijal/pmdarima
5bf84a2a5c42b81b949bd252ad3d4c6c311343f8
[ "MIT" ]
736
2019-12-02T01:33:31.000Z
2022-03-31T21:45:29.000Z
pmdarima/preprocessing/endog/boxcox.py
tuomijal/pmdarima
5bf84a2a5c42b81b949bd252ad3d4c6c311343f8
[ "MIT" ]
186
2019-12-01T18:01:33.000Z
2022-03-31T18:27:56.000Z
pmdarima/preprocessing/endog/boxcox.py
tuomijal/pmdarima
5bf84a2a5c42b81b949bd252ad3d4c6c311343f8
[ "MIT" ]
126
2019-12-07T04:03:19.000Z
2022-03-31T17:40:14.000Z
# -*- coding: utf-8 -*- from scipy import stats import numpy as np import warnings from ...compat import check_is_fitted, pmdarima as pm_compat from .base import BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer']
33.511364
78
0.598847
86f3e8f2399f57967d9da67546eaf7a9b7b31fb7
2,139
py
Python
backend/src/baserow/api/user/registries.py
ashishdhngr/baserow
b098678d2165eb7c42930ee24dc6753a3cb520c3
[ "MIT" ]
1
2022-01-24T15:12:02.000Z
2022-01-24T15:12:02.000Z
backend/src/baserow/api/user/registries.py
rasata/baserow
c6e1d7842c53f801e1c96b49f1377da2a06afaa9
[ "MIT" ]
null
null
null
backend/src/baserow/api/user/registries.py
rasata/baserow
c6e1d7842c53f801e1c96b49f1377da2a06afaa9
[ "MIT" ]
null
null
null
from baserow.core.registry import Instance, Registry user_data_registry = UserDataRegistry()
28.905405
85
0.633006
86f4958fe557f64425c53fe4dff977306ba95b20
17,197
py
Python
Week 2/code.py
aklsh/EE2703
546b70c9adac4a4de294d83affbb74e480c2f65d
[ "MIT" ]
null
null
null
Week 2/code.py
aklsh/EE2703
546b70c9adac4a4de294d83affbb74e480c2f65d
[ "MIT" ]
null
null
null
Week 2/code.py
aklsh/EE2703
546b70c9adac4a4de294d83affbb74e480c2f65d
[ "MIT" ]
3
2020-07-15T08:02:05.000Z
2021-03-07T06:50:07.000Z
''' ------------------------------------- Assignment 2 - EE2703 (Jan-May 2020) Done by Akilesh Kannan (EE18B122) Created on 18/01/20 Last Modified on 04/02/20 ------------------------------------- ''' # importing necessary libraries import sys import cmath import numpy as np import pandas as pd # To improve readability CIRCUIT_START = ".circuit" CIRCUIT_END = ".end" RESISTOR = "R" CAPACITOR = "C" INDUCTOR = "L" IVS = "V" ICS = "I" VCVS = "E" VCCS = "G" CCVS = "H" CCCS = "F" PI = np.pi # Classes for each circuit component # Convert a number in engineer's format to math def enggToMath(enggNumber): try: return float(enggNumber) except: lenEnggNumber = len(enggNumber) # Kilo if enggNumber[lenEnggNumber-1] == 'k': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e3 # Milli elif enggNumber[lenEnggNumber-1] == 'm': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 # Micro elif enggNumber[lenEnggNumber-1] == 'u': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 # Nano elif enggNumber[lenEnggNumber-1] == 'n': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 # Mega elif enggNumber[lenEnggNumber-1] == 'M': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else: sys.exit("Please check the component values given. Supported engineer units are: M, k, m, u, n\nYou can also enter values in exponential format (eg. 1e3 = 1000).") if __name__ == "__main__": # checking number of command line arguments if len(sys.argv)!=2 : sys.exit("Invalid number of arguments!") else: try: circuitFile = sys.argv[1] circuitFreq = 1e-100 circuitComponents = { RESISTOR: [], CAPACITOR: [], INDUCTOR: [], IVS: [], ICS: [], VCVS: [], VCCS: [], CCVS: [], CCCS: [] } circuitNodes = [] # checking if given netlist file is of correct type if (not circuitFile.endswith(".netlist")): print("Wrong file type!") else: netlistFileLines = [] with open (circuitFile, "r") as f: for line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\n')[0]) # Getting frequency, if any if(line[:3] == '.ac'): circuitFreq = float(line.split()[2]) # Setting Angular Frequency w w = 2*PI*circuitFreq try: # Finding the location of the identifiers identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2] for line in circuitBody: # Extracting the data from the line lineTokens = line.split() # Appending new nodes to a list try: if lineTokens[1] not in circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2] not in circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError: continue # Resistor if lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Capacitor elif lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Inductor elif lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Voltage Source elif lineTokens[0][0] == IVS: if len(lineTokens) == 5: # DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: # AC Source if circuitFreq == 1e-100: sys.exit("Frequency of AC Source not specified!!") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # Current Source elif lineTokens[0][0] == ICS: if len(lineTokens) == 5: # DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: # AC Source if circuitFreq == 1e-100: sys.exit("Frequency of AC Source not specified!!") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # VCVS elif lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # VCCS elif lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # CCVS elif lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # CCCS elif lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # Erroneous Component Name else: sys.exit("Wrong Component Given. ABORT!") try: circuitNodes.remove('GND') circuitNodes = ['GND'] + circuitNodes except: sys.exit("No ground node specified in the circuit!!") # Creating a dictionary with node names and their numbers (to reduce the time taken by later parts of the program) nodeNumbers = {circuitNodes[i]:i for i in range(len(circuitNodes))} numNodes = len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices M and b matrixM = np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB = np.zeros((numNodes+numVS,), np.complex) # GND Equation matrixM[0][0] = 1.0 # Resistor Equations for r in circuitComponents[RESISTOR]: if r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value # Capacitor Equations for c in circuitComponents[CAPACITOR]: if c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value) if c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value) # Inductor Equations for l in circuitComponents[INDUCTOR]: if l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value)) if l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value)) # Voltage Source Equations for i in range(len(circuitComponents[IVS])): # Equation accounting for current through the source if circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 # Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current Source Equations for i in circuitComponents[ICS]: if i.node1 != 'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value if i.node2 != 'GND': matrixB[nodeNumbers[i.node2]] = i.value # VCVS Equations for i in range(len(circuitComponents[VCVS])): # Equation accounting for current through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value # CCVS Equations for i in range(len(circuitComponents[CCVS])): # Equation accounting for current through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value # VCCS Equations for vccs in circuitComponents[VCCS]: if vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations for cccs in circuitComponents[CCCS]: if cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x = np.linalg.solve(matrixM, matrixB) circuitCurrents = [] # Formatting Output Data for v in circuitComponents[IVS]: circuitCurrents.append("current in "+v.name) for v in circuitComponents[VCVS]: circuitCurrents.append("current in "+v.name) for v in circuitComponents[CCVS]: circuitCurrents.append("current in "+v.name) # Printing output in table format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage / Current'])) print("The values given above are AMPLITUDE values and NOT RMS values.") except np.linalg.LinAlgError: sys.exit("Singular Matrix Formed! Please check if you have entered the circuit definition correctly!") except ValueError: sys.exit("Netlist does not abide to given format!") except FileNotFoundError: sys.exit("Given file does not exist!")
53.241486
209
0.51823
86f530cec67d3e933cfc6fd5269d65218a8b2c49
880
py
Python
Lib/Co.py
M507/Guessing-passwords-using-machine-learning
da90cfa30ce2e7a5e08ee528f594fa047ecea75c
[ "Apache-2.0" ]
6
2020-05-18T14:20:23.000Z
2021-04-23T16:31:34.000Z
Lib/Co.py
M507/Guessing-passwords-using-machine-learning
da90cfa30ce2e7a5e08ee528f594fa047ecea75c
[ "Apache-2.0" ]
null
null
null
Lib/Co.py
M507/Guessing-passwords-using-machine-learning
da90cfa30ce2e7a5e08ee528f594fa047ecea75c
[ "Apache-2.0" ]
1
2020-05-18T21:19:52.000Z
2020-05-18T21:19:52.000Z
import subprocess import os.path """ Stylish input() """ """ Execute command locally """ """ Get all subdirectories of a directory. """ """ Rocket science """
20.952381
87
0.619318
86f661785147d1c962908ad8a5f0840e9e70661d
446
py
Python
project3_code/part_0/main.py
rachelbrown347/CS294-26_code
72a20a9ab75345091d2a743b13857d7a88adf9be
[ "MIT" ]
1
2022-03-12T00:55:52.000Z
2022-03-12T00:55:52.000Z
project3_code/part_0/main.py
rachelbrown347/CS294-26_code
72a20a9ab75345091d2a743b13857d7a88adf9be
[ "MIT" ]
null
null
null
project3_code/part_0/main.py
rachelbrown347/CS294-26_code
72a20a9ab75345091d2a743b13857d7a88adf9be
[ "MIT" ]
null
null
null
import numpy as np import matplotlib.pyplot as plt from skimage.exposure import rescale_intensity from unsharp import * # Load file and normalize to 0-1 fname = 'iguana.jpg' im = plt.imread(fname) if im.mean() >= 1: im = im/255. sigma = 5 amplitude = 1.5 imsharp = unsharp_mask(im, sigma, amplitude) imsharp = rescale_intensity(imsharp, in_range=(0, 1), out_range=(0,1)) new_fname = fname[:-4]+'_sharp.jpg' plt.imsave(new_fname, imsharp)
23.473684
70
0.726457