blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
1798f721134caaa620aed4222d4bc6e6bcbba240
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03361/s539561485.py
cffb41867b3225ac6cfe3db9ef25c838fe9f165b
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
767
py
h, w = map(int, input().split()) hw = [list(input()) for _ in range(h)] num = 0 for i in range(h): num+=hw[i].count('#') def check(i, j): if not (0<=i<h and 0<=j<w): return False if hw[i][j] == '#': return True return False checked = set() for i in range(h): for j in range(w): if hw[i][j] == '#': if (i,j) in checked: continue exist = False for di,dj in [(1,0),(-1,0),(0,1),(0,-1)]: ci = i + di cj = j + dj if check(ci, cj): checked.add((ci,cj)) exist = True if exist: checked.add((i,j)) if num == len(checked): print('Yes') else: print('No')
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
b83bc46a7ce13e8a89b50545d2e4e45a4a8d2635
c19ca6779f247572ac46c6f95327af2374135600
/backtrack/leetcode 77 Combinations.py
2030b16ee431a3126d4e022b4aead30741cb7b78
[]
no_license
clhchtcjj/Algorithm
aae9c90d945030707791d9a98d1312e4c07705f8
aec68ce90a9fbceaeb855efc2c83c047acbd53b5
refs/heads/master
2021-01-25T14:24:08.037204
2018-06-11T14:31:38
2018-06-11T14:31:38
123,695,313
5
0
null
null
null
null
UTF-8
Python
false
false
940
py
__author__ = 'CLH' ''' 给定n,k,返回元素个数为k的,由1-n不重复数字组成的组合 ''' # class Solution(object): # def __init__(self): # self.ans = [] # self.total_ans = [] # # def backtrack(self, k, index,n): # if len(self.ans) == k: # self.total_ans.append(list(self.ans)) # else: # for i in range(index+1,n+1): # self.ans.append(i) # self.backtrack(k,i,n) # self.ans.pop() # # def combine(self, n, k): # """ # :type n: int # :type k: int # :rtype: List[List[int]] # """ # self.backtrack(k,0,n) # return self.total_ans # 调包解法 from itertools import combinations class Solution: def combine(self, n, k): return list(combinations(range(1, n+1), k)) if __name__ == "__main__": S = Solution() print(S.combine(4,2))
[ "15720622991@163.com" ]
15720622991@163.com
0c0ae078428e10bafa110ea617e4801beef79c17
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/sdssj_090252.46+321316.0/sdB_SDSSJ_090252.46+321316.0_lc.py
8c033cb236f2b50b487fd3284242254acdd7cd55
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
372
py
from gPhoton.gAperture import gAperture def main(): gAperture(band="NUV", skypos=[135.718583,32.221111], stepsz=30., csvfile="/data2/fleming/GPHOTON_OUTPU/LIGHTCURVES/sdBs/sdB_SDSSJ_090252.46+321316.0 /sdB_SDSSJ_090252.46+321316.0_lc.csv", maxgap=1000., overwrite=True, radius=0.00555556, annulus=[0.005972227,0.0103888972], verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
0ade96035ba97bf0b5dd42bb08eb838289aeb28a
ff413ecba8eb6a3f8afc225bd1339abac453202c
/project/flask_dashboard/app/home/views/product.py
f1541489c44f10c06033dd649b090456f735a0e7
[ "MIT" ]
permissive
Artvell/bot
561b614fde5d19335736ac390e35814afd6b6180
0b85a5efc4c302f522bf23a23fbbbc8a9efc7008
refs/heads/main
2023-08-10T17:10:21.500433
2021-09-11T12:54:32
2021-09-11T12:54:32
405,372,665
0
0
null
null
null
null
UTF-8
Python
false
false
3,914
py
from flask import Blueprint,render_template, redirect, url_for, request, jsonify from flask_login import login_required, current_user from jinja2 import TemplateNotFound from models import Post, Category, Subcategory from flask_dashboard.app.home.forms import ProductForm from flask_peewee.utils import PaginatedQuery product = Blueprint("app_product",__name__) @product.route("/products/") @product.route("/products/<int:x>/") @product.route("/product/<int:product>/") @login_required def products(**kwargs): #try: index = int(kwargs.get("x",5)) product_id = kwargs.get("product","!") if product_id != "!": products = Post.select().where(Post.id == product_id).order_by(Post.id.desc()) else: products = Post.select().order_by(Post.id.desc()) pagination = PaginatedQuery(products,index) result = pagination.get_list() all_count = products.count() return render_template( "products.html", elements=result, index=index, page_count = int(all_count/index) + 1 if all_count % index > 0 else int(all_count/index), segment="products", form=ProductForm(), pagination = pagination ) """except TemplateNotFound: return render_template('page-404.html'), 404 except Exception as e: print(e) return render_template('page-500.html'), 500""" @product.route("/product/subcateg/",methods = ['POST']) @login_required def subcateg(): categ_id = request.json.get("categ_id") data = [[sub.id,sub.subcategory] for sub in Subcategory.select().where(Subcategory.category==categ_id)] return jsonify(data),200 @product.route("/product/delete/",methods = ['POST']) @login_required def delete_order(): product_id = request.form.get("product_id") try: product = Post.get_or_none(Post.id == product_id) if product is not None: product.delete_instance() return "Ok" else: return "No" except TemplateNotFound: return render_template('page-404.html'), 404 except Exception as e: print(e) return render_template('page-500.html'), 500 @product.route("/get_product/", methods = ["GET"]) @login_required def get_product(): name = request.args.get("term","!") products = Post.select(Post.id, Post.name, Post.links).where(Post.name.contains(name)) data = [{"value":p.id,"label":p.name,"icon":p.links[0],"cost":p.cost} for p in products] #data = [p.name for p in products] return jsonify(data),200 @product.route("/product/change/", methods = ['POST']) @login_required def change_product(): #order_id = request.form.get("order_id") post_id = request.form["product_id"] name = request.form["name"] telegraph = request.form["telegraph"] cost = request.form["cost"] is_available = True if request.form.get("is_available",False) == "y" else False is_visible = True if request.form.get("is_visible",False) == "y" else False category = request.form.get("category", None) subcategory = request.form.get("subcategory", None) links = request.form.getlist("links[]") text = request.form.get("text"," ") print("@@ ",links) form = ProductForm() try: product = Post.get_or_none(Post.id == post_id) if product is not None: product.name = name product.telegraph = telegraph product.links = links product.category = category product.subcategory = subcategory product.cost = cost product.is_available = is_available product.is_visible = is_visible product.save() return "Ok" else: return "No" except TemplateNotFound: return render_template('page-404.html'), 404 except Exception as e: print(e) return render_template('page-500.html'), 500
[ "artem.karimov.98@gmail.com" ]
artem.karimov.98@gmail.com
d3506d448432d2d84eae16a530cfd3cf6213adde
380e69be8a329ca4cec838b32b29ac5ec94d9c75
/idea/migrations/0001_initial.py
598f3221d5953b60c856efeda4f4b36ec5587d2f
[]
no_license
jiss02/Bosswar
95fcc8baa3f5dceee777b18f76736d1397431e5a
ab31b6515d88959e4ca745b2bda0a1e20806dc57
refs/heads/master
2022-12-12T00:58:07.500693
2020-02-19T16:05:02
2020-02-19T16:05:02
201,433,007
0
1
null
2022-12-08T05:59:50
2019-08-09T09:09:35
CSS
UTF-8
Python
false
false
1,018
py
# Generated by Django 2.2.3 on 2019-07-19 21:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Idea', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('content', models.TextField()), ('created_at', models.DateTimeField()), ], ), migrations.CreateModel( name='Ideacomment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('comment', models.CharField(max_length=800)), ('idea', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='idea.Idea')), ], ), ]
[ "olo5112olo@naver.com" ]
olo5112olo@naver.com
02dff88aed87044355925dfee09776bb57935d31
033da72a51c76e5510a06be93229a547a538cf28
/Data Engineer with Python Track/08. Introduction to Bash Scripting/Chapter/01. From Command-Line to Bash Script/01-Extracting scores with shell.py
6e3cbc3b7819f7c7a6dbbc55e9533c3b87454923
[]
no_license
ikhwan1366/Datacamp
d5dcd40c1bfeb04248977014260936b1fb1d3065
7738614eaebec446842d89177ae2bc30ab0f2551
refs/heads/master
2023-03-06T13:41:06.522721
2021-02-17T22:41:54
2021-02-17T22:41:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
475
py
''' Extracting scores with shell There is a file in either the start_dir/first_dir, start_dir/second_dir or start_dir/third_dir directory called soccer_scores.csv. It has columns Year,Winner,Winner Goals for outcomes of a soccer league. cd into the correct directory and use cat and grep to find who was the winner in 1959. You could also just ls from the top directory if you like! Instructions 50 XP Possible Answers - Winner - Dunav - Botev Answer : Dunav '''
[ "surel.chandrapratama@gmail.com" ]
surel.chandrapratama@gmail.com
b985ed9cfcf34ff3768b1dee8800bf80f08aedeb
f411cbd68ef0fcc578d931149e0aa1f216efa878
/app/settings.py
403f7361e1be00c18559158d9b5d2dcb9ad17da7
[]
no_license
MarkBorodin/simple_app_template_with_authorization
616e2de687941effd3a7650f83fea581d642c9e9
ba68da72f9bcec393c0d9bbcb00fb17fa4412c1c
refs/heads/master
2023-06-05T12:11:50.437442
2021-06-18T09:55:00
2021-06-18T09:55:00
378,106,750
0
0
null
null
null
null
UTF-8
Python
false
false
3,103
py
import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=!r#ce#%!kc9a#bm9n6sre^_y6)d+v+_re&&^2udspy^#_sg*^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'accounts', 'app' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ AUTH_USER_MODEL = 'accounts.User' STATIC_URL = '/static/' # STATIC_ROOT = '/var/www/<app_name>/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] CRISPY_TEMPLATE_PACK = 'bootstrap4' MEDIA_URL = 'media/' # MEDIA_ROOT = '/var/www/<app_name>/media/'
[ "rens2588@gmail.com" ]
rens2588@gmail.com
f824dd9af38faa203274a3ba0de3f286a2dcef28
25e7d840203e705c6a68aed079cc9844954b9536
/.github/scripts/label_utils.py
d3c19f5b7aad69ed28c992ba9d1412e1ce763cc5
[ "BSD-2-Clause", "LicenseRef-scancode-secret-labs-2011", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
yf225/pytorch
874892cd9d0f7bb748e469cfca23a3f503ea4265
39590d06c563d830d02b9f94611ab01f07133c97
refs/heads/main
2023-07-24T06:17:16.324006
2023-04-24T18:22:54
2023-04-24T18:22:59
113,096,813
1
3
NOASSERTION
2023-08-29T18:46:16
2017-12-04T21:25:08
Python
UTF-8
Python
false
false
3,909
py
"""GitHub Label Utilities.""" import json from functools import lru_cache from typing import Any, List, Tuple, TYPE_CHECKING, Union from urllib.request import Request, urlopen from github_utils import gh_fetch_url, GitHubComment # TODO: this is a temp workaround to avoid circular dependencies, # and should be removed once GitHubPR is refactored out of trymerge script. if TYPE_CHECKING: from trymerge import GitHubPR BOT_AUTHORS = ["github-actions", "pytorchmergebot", "pytorch-bot"] LABEL_ERR_MSG_TITLE = "This PR needs a label" LABEL_ERR_MSG = f"""# {LABEL_ERR_MSG_TITLE} If your changes are user facing and intended to be a part of release notes, please use a label starting with `release notes:`. If not, please add the `topic: not user facing` label. To add a label, you can comment to pytorchbot, for example `@pytorchbot label "topic: not user facing"` For more information, see https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work. """ # Modified from https://github.com/pytorch/pytorch/blob/b00206d4737d1f1e7a442c9f8a1cadccd272a386/torch/hub.py#L129 def _read_url(url: Request) -> Tuple[Any, Any]: with urlopen(url) as r: return r.headers, r.read().decode(r.headers.get_content_charset("utf-8")) def request_for_labels(url: str) -> Tuple[Any, Any]: headers = {"Accept": "application/vnd.github.v3+json"} return _read_url(Request(url, headers=headers)) def update_labels(labels: List[str], info: str) -> None: labels_json = json.loads(info) labels.extend([x["name"] for x in labels_json]) def get_last_page_num_from_header(header: Any) -> int: # Link info looks like: <https://api.github.com/repositories/65600975/labels?per_page=100&page=2>; # rel="next", <https://api.github.com/repositories/65600975/labels?per_page=100&page=3>; rel="last" link_info = header["link"] prefix = "&page=" suffix = ">;" return int( link_info[link_info.rindex(prefix) + len(prefix) : link_info.rindex(suffix)] ) @lru_cache() def gh_get_labels(org: str, repo: str) -> List[str]: prefix = f"https://api.github.com/repos/{org}/{repo}/labels?per_page=100" header, info = request_for_labels(prefix + "&page=1") labels: List[str] = [] update_labels(labels, info) last_page = get_last_page_num_from_header(header) assert ( last_page > 0 ), "Error reading header info to determine total number of pages of labels" for page_number in range(2, last_page + 1): # skip page 1 _, info = request_for_labels(prefix + f"&page={page_number}") update_labels(labels, info) return labels def gh_add_labels( org: str, repo: str, pr_num: int, labels: Union[str, List[str]] ) -> None: gh_fetch_url( url=f"https://api.github.com/repos/{org}/{repo}/issues/{pr_num}/labels", data={"labels": labels}, ) def gh_remove_label(org: str, repo: str, pr_num: int, label: str) -> None: gh_fetch_url( url=f"https://api.github.com/repos/{org}/{repo}/issues/{pr_num}/labels/{label}", method="DELETE", ) def get_release_notes_labels(org: str, repo: str) -> List[str]: return [ label for label in gh_get_labels(org, repo) if label.lstrip().startswith("release notes:") ] def has_required_labels(pr: "GitHubPR") -> bool: pr_labels = pr.get_labels() # Check if PR is not user facing is_not_user_facing_pr = any( label.strip() == "topic: not user facing" for label in pr_labels ) return is_not_user_facing_pr or any( label.strip() in get_release_notes_labels(pr.org, pr.project) for label in pr_labels ) def is_label_err_comment(comment: GitHubComment) -> bool: return ( comment.body_text.lstrip(" #").startswith(LABEL_ERR_MSG_TITLE) and comment.author_login in BOT_AUTHORS )
[ "pytorchmergebot@users.noreply.github.com" ]
pytorchmergebot@users.noreply.github.com
57f6ff95bf0065b31262d44915450203789297d3
f058cd1ec57b2e24430605883387b1c34391a2e3
/simple.py
f4c823207733b242b34b41c137fa21843dbcccd8
[]
no_license
Danny-Dasilva/Blender_Mediapipe
9a2966f38e3e6a9aea503eed1bdcc0e4e2ebc502
80cbd45e721bc12759d26c317f3a57b6176e1af5
refs/heads/main
2023-04-21T09:49:47.200918
2021-05-15T01:03:40
2021-05-15T01:03:40
365,960,178
5
0
null
null
null
null
UTF-8
Python
false
false
4,216
py
############################################################################### ### Simple demo with at least 2 cameras for triangulation ### Input : Live videos of face / hand / body ### : Calibrated camera intrinsics and extrinsics ### Output: 2D/3D (triangulated) display of hand, body keypoint/joint ### Usage : python 07_triangulate.py -m body --use_panoptic_dataset ############################################################################### import cv2 import sys import time import argparse import numpy as np import open3d as o3d from multicam.utils_display import DisplayHand, DisplayBody, DisplayHolistic from multicam.utils_mediapipe import MediaPipeHand, MediaPipeBody, MediaPipeHolistic # User select mode parser = argparse.ArgumentParser() parser.add_argument('--use_panoptic_dataset', action='store_true') parser.add_argument('-m', '--mode', default='body', help='Select mode: hand / body / holistic') args = parser.parse_args() mode = args.mode # Define list of camera index # cam_idx = [4,10] # Note: Hardcoded for my setup # Read from .mp4 file if args.use_panoptic_dataset: pass # Test with 2 views cam_idx = ['./data/front.mp4', './data/side2.mp4'] # # Test with n views # num_views = 5 # Note: Maximum 31 hd cameras but processing time will be extremely slow # cam_idx = [] # for i in range(num_views): # cam_idx.append( # '../data/171204_pose1_sample/hdVideos/hd_00_'+str(i).zfill(2)+'.mp4') # Start video capture cap = [cv2.VideoCapture(cam_idx[i]) for i in range(len(cam_idx))] # Define list of other variable img = [None for i in range(len(cam_idx))] # Store image pipe = [None for i in range(len(cam_idx))] # MediaPipe class disp = [None for i in range(len(cam_idx))] # Display class param = [None for i in range(len(cam_idx))] # Store pose parameter prev_time = [time.time() for i in range(len(cam_idx))] # Open3D visualization vis = o3d.visualization.Visualizer() vis.create_window(width=640, height=480) vis.get_render_option().point_size = 5.0 # Load mediapipe and display class if mode=='hand': for i in range(len(cam_idx)): pipe[i] = MediaPipeHand(static_image_mode=False, max_num_hands=1) disp[i] = DisplayHand(draw3d=True, max_num_hands=1, vis=vis) elif mode=='body': for i in range(len(cam_idx)): pipe[i] = MediaPipeBody(static_image_mode=False, model_complexity=1) disp[i] = DisplayBody(draw3d=True, vis=vis) elif mode=='holistic': for i in range(len(cam_idx)): pipe[i] = MediaPipeHolistic(static_image_mode=False, model_complexity=1) disp[i] = DisplayHolistic(draw3d=True, vis=vis) else: print('Undefined mode only the following modes are available: \n hand / body / holistic') sys.exit() while True: # Loop through video capture for i, c in enumerate(cap): if not c.isOpened(): break ret, img[i] = c.read() if not ret: break # Preprocess image if necessary # img[i] = cv2.flip(img[i], 1) # Flip image for 3rd person view # To improve performance, optionally mark image as not writeable to pass by reference img[i].flags.writeable = False # Feedforward to extract keypoint param[i] = pipe[i].forward(img[i]) img[i].flags.writeable = True # Compute FPS curr_time = time.time() fps = 1/(curr_time-prev_time[i]) if mode=='body': param[i]['fps'] = fps elif mode=='hand': param[i][0]['fps'] = fps elif mode=='holistic': for p in param[i]: p['fps'] = fps prev_time[i] = curr_time for i in range(len(cam_idx)): # Display 2D keypoint img[i] = disp[i].draw2d(img[i].copy(), param[i]) img[i] = cv2.resize(img[i], None, fx=0.5, fy=0.5) cv2.imshow('img'+str(i), img[i]) # Display 3D disp[i].draw3d(param[i]) vis.update_geometry(None) vis.poll_events() vis.update_renderer() key = cv2.waitKey(1) if key==27: break # vis.run() # Keep 3D display for visualization for p, c in zip(pipe, cap): p.pipe.close() c.release()
[ "yahchayildasilva@gmail.com" ]
yahchayildasilva@gmail.com
cfe496afee791a2454716d5249119d032461b1b3
745197407e81606718c4cdbedb6a81b5e8edf50b
/tests/texttest/TestSelf/ChangeTestResults/GUI/SaveFailsNoPermission/testcustomize.py
22ff04e0d5418b1d77d52a0f5901276c9822ebfe
[]
no_license
dineshkummarc/texttest-3.22
5b986c4f6cc11fd553dab173c7f2e90590e7fcf0
85c3d3627082cdc5860d9a8468687acb499a7293
refs/heads/master
2021-01-23T20:44:35.653866
2012-06-25T07:52:13
2012-06-25T07:52:13
4,779,248
1
0
null
null
null
null
UTF-8
Python
false
false
231
py
import os origRemove = os.remove def myremove(file): if file.startswith(os.getenv("TEXTTEST_HOME")): raise OSError, "Permission denied: '" + file + "'" else: origRemove(file) os.remove = myremove
[ "dineshkummarc@gmail.com" ]
dineshkummarc@gmail.com
53d9612d4f7af3b8dbf0a3413ba5ef9d765d3906
dd74f0c5a83962362cdac6fa072fc734f2e3a15c
/manage.py
72c118206eb2cebf9f8ed0f21c7146109b022d06
[ "LicenseRef-scancode-other-permissive" ]
permissive
willyowi/pitch-perfect
06c01ebd7f655e812e57a8107b2c910a690a1664
86e6098040324034579f94b32aab013d162c4338
refs/heads/master
2022-09-22T22:39:27.289062
2019-08-07T10:08:23
2019-08-07T10:08:23
200,611,221
0
0
null
2022-09-16T18:08:12
2019-08-05T08:07:12
HTML
UTF-8
Python
false
false
510
py
from app import create_app, db from app.models import User,Pitch,Comment from flask_script import Manager,Server from flask_migrate import Migrate, MigrateCommand # Creating app instance app = create_app('development') manager = Manager(app) migrate = Migrate(app,db) manager.add_command('server',Server) manager.add_command('db',MigrateCommand) @manager.shell def make_shell_context(): return dict(app = app,db = db,User = User) if __name__ == '__main__': app.secret_key = 'wise' manager.run()
[ "wilsonowino1@gmail.com" ]
wilsonowino1@gmail.com
df37f014ee34791e66da1c0d867889ba7c8729e9
2ea06cfee552026d764fac2899135a4632de4b9f
/hyyjbg/hyyjbg/spiders/dfcfw.py
cdd577da5200a6dcc071130a019a31f347e5ee54
[]
no_license
gasbarroni8/crawler-scrapy
fa173c5c270d12d0d8b888484084fb25ef94cca9
dbf0aebea68213ceda60f44194c4a4e8710d5674
refs/heads/master
2020-11-27T04:26:55.131890
2019-12-20T16:47:24
2019-12-20T16:47:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,160
py
# -*- coding: utf-8 -*- import scrapy import logging from hyyjbg.items import hyyjbgItem class DfcfwSpider(scrapy.Spider): name = 'dfcfw' custom_settings = { 'DOWNLOADER_MIDDLEWARES': { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, }, 'SPIDER_MIDDLEWARES': { 'scrapy_splash.SplashDeduplicateArgsMiddleware': 100, }, 'ITEM_PIPELINES': { 'utils.pipelines.MysqlTwistedPipeline.MysqlTwistedPipeline': 64, 'utils.pipelines.DuplicatesPipeline.DuplicatesPipeline': 100, }, 'DUPEFILTER_CLASS': 'scrapy_splash.SplashAwareDupeFilter', # 'HTTPCACHE_STORAGE': 'scrapy_splash.SplashAwareFSCacheStorage', 'SPLASH_URL': "http://47.106.239.73:8050/"} def __init__(self, pagenum=None, *args, **kwargs): super().__init__(*args, **kwargs) self.add_pagenum = pagenum def start_requests(self): try: contents = [ { 'topic': 'dfcfw', # 东方财富网 'url': 'http://trust.eastmoney.com/news/czjzl_1.html' } ] for content in contents: yield scrapy.Request(content['url'], callback=self.parse_page, cb_kwargs=content, dont_filter=True) except Exception as e: logging.error(self.name + ": " + e.__str__()) logging.exception(e) def parse_page(self, response, **kwargs): page_count = int(self.parse_pagenum(response, kwargs)) try: for pagenum in range(page_count): url = kwargs['url'] url = url.replace('1.html', str(pagenum + 1) + '.html') yield scrapy.Request(url, callback=self.parse, cb_kwargs=kwargs, dont_filter=True) except Exception as e: logging.error(self.name + ": " + e.__str__()) logging.exception(e) def parse_pagenum(self, response, kwargs): try: # 在解析页码的方法中判断是否增量爬取并设定爬取列表页数,如果运行 # 脚本时没有传入参数pagenum指定爬取前几页列表页,则全量爬取 if not self.add_pagenum: return int(response.css('#pagerNoDiv > a:nth-last-child(2)::text').extract_first()) return self.add_pagenum except Exception as e: logging.error(self.name + ": " + e.__str__()) logging.exception(e) def parse(self, response, **kwargs): for href in response.css('#newsListContent .image a::attr(href)').extract(): try: url = response.urljoin(href) yield scrapy.Request(url, callback=self.parse_item, cb_kwargs={'url': url}, dont_filter=True) except Exception as e: logging.error(self.name + ": " + e.__str__()) logging.exception(e) def parse_item(self, response, **kwargs): try: item = hyyjbgItem() item['title'] = response.css('h1::text').extract_first() item['date'] = response.css('.time::text').extract_first() item['resource'] = response.css('.data-source::attr(data-source)').extract_first() item['content'] = response.css('#ContentBody').extract_first() item['website'] = '东方财富网' item['link'] = kwargs['url'] item['spider_name'] = 'dfcfw' item['txt'] = ''.join(response.css('#ContentBody *::text').extract()) item['module_name'] = '信托融资一行业基本报告-东方财富网' print( "===========================>crawled one item" + response.request.url) except Exception as e: logging.error( self.name + " in parse_item: url=" + response.request.url + ", exception=" + e.__str__()) logging.exception(e) yield item
[ "sn_baby@qq.com" ]
sn_baby@qq.com
6f2dcda94c9cae184ac5bec1a2acfa115f757c9a
0102bd51696f6973fc9a8ff56e604be86058d595
/api/photo.py
2e838c2698651e72d247d7c0844dc7d73fa80117
[]
no_license
weaming/unsplash-http-api
549e75e0aee8f4d05d3aef399d117b3c8ab7a2e8
7c5dc0001568999ecc398fd885e952d5fbf77be6
refs/heads/master
2022-08-28T14:18:41.289593
2019-07-17T08:22:39
2019-07-17T08:22:39
145,960,268
1
0
null
2022-08-06T05:22:33
2018-08-24T07:49:27
Python
UTF-8
Python
false
false
2,220
py
import logging from sanic import response from .unsplash_api import api from .to_json import obj_to_dict from .helpers import http_get allowed_order_type = ["latest", "oldest", "popular"] async def random_pohoto(req, count=10, username=None, query=None): """ :param count: The number of photos to return. (Default: 1; max: 30) """ res = api.photo.random(count=count, username=username, query=query) return {"data": obj_to_dict(res)} async def random_photo_html(req, webp=False): res = obj_to_dict(api.photo.random(count=1))[0] if webp: url = res["urls"]["regular"] # webp binary = await http_get(url.replace("fm=jpg", "fm=webp")) return response.raw(binary, content_type="image/webp") url = res["urls"]["raw"] try: location = res["location"] if isinstance(location, dict): location = location["title"] except KeyError as e: logging.warning(str(e)) logging.warning(res) location = "unknown location" html = ( '<body style="margin: 0; display: inline-block;">' '<img src="{url}" alt="{location}" title="{location}" ' 'style="max-width: 100vw; max-height: 100vh; margin: 0 auto;">' "</body>" ) return response.html(html.format(url=url, location=location)) async def all_photo(req, page=1, per_page=10, order_by="latest"): if order_by not in allowed_order_type: return {"reason": "allowed order_by values {}".format(allowed_order_type)}, 400 res = api.photo.all(page=page, per_page=per_page, order_by=order_by) return {"data": obj_to_dict(res)} async def curated_photo(req, page=1, per_page=10, order_by="latest"): if order_by not in allowed_order_type: return {"reason": "allowed order_by values {}".format(allowed_order_type)}, 400 res = api.photo.curated(page=page, per_page=per_page, order_by=order_by) return {"data": obj_to_dict(res)} async def get_photo(req, id): res = api.photo.get(id) return {"data": obj_to_dict(res)} async def search_photo(req, query, page=1, per_page=10): res = api.search.photos(query, page=page, per_page=per_page) return {"data": obj_to_dict(res)}
[ "garden.yuen@gmail.com" ]
garden.yuen@gmail.com
dae34ee6e5649ebad6f60d94eb13d06caf41b74b
8f7615603d4d923fd2cda41a2105b85b596ab4c5
/leetcode/medium/96-Unique_BST.py
0c6377ae22e035dbc9ff9d6e1caf36b8c7778abb
[ "MIT" ]
permissive
shubhamoli/solutions
e7ec922047c16cfdc10070aa5b884a278b12d8c5
5a24fdeb6e5f43b821ef0510fe3b343ddda18f22
refs/heads/master
2021-01-05T04:13:35.302613
2020-06-27T18:28:18
2020-06-27T18:28:18
240,875,585
1
0
null
null
null
null
UTF-8
Python
false
false
660
py
""" Leetcode #96 """ # Similar to find nth catalan number class Solution: def numTrees(self, n: int) -> int: memo = {} self.count = 0 def uniqueTrees(n): if n < 1: return 1 if n in memo: return memo[n] self.count += sum([uniqueTrees(i - 1) * uniqueTrees(n - i) for i in range(1 , n + 1)]) memo[n] = self.count return self.count return uniqueTrees(n) if __name__ == "__main__": solution = Solution() assert solution.numTrees(1) == 1 assert solution.numTrees(2) == 2 assert solution.numTrees(3) == 5
[ "oli.shubham@gmail.com" ]
oli.shubham@gmail.com
7d46cb100cce3a9df30fa08ddad9e3d30ccdfb38
2f0cb310e2ec8fb176ee240aa964a7eef5ed23b4
/giico/quality_control_and_material_testing/doctype/thermal_conductivity_lab/thermal_conductivity_lab.py
8e7d65be8da81f630ed66ba8ad91d07088675845
[ "MIT" ]
permissive
thispl/giico
b96cf6b707f361275f8723d15f8ea1f95f908c9c
14c5631639ab56a586a7962be9871d722c20e205
refs/heads/master
2021-06-18T03:56:02.928303
2021-04-27T06:42:59
2021-04-27T06:42:59
200,183,753
0
0
null
null
null
null
UTF-8
Python
false
false
265
py
# -*- coding: utf-8 -*- # Copyright (c) 2021, VHRS and contributors # For license information, please see license.txt from __future__ import unicode_literals # import frappe from frappe.model.document import Document class ThermalConductivityLAB(Document): pass
[ "hereabdulla@gmail.com" ]
hereabdulla@gmail.com
fa8451a11fbe51270103c2e55055358b12574729
934235f70a390a3ba0d7b464cddd10872f31cda3
/rango/server/.history/tango_with_django/rango/views_20210104191049.py
0fade486e9c7c4ee1d87fba1070ad41793556128
[]
no_license
deji100/Projects
6919041ba23e77a5c74e5ab7692bfcee38ececcb
17e64d954d1d7805be57ec5d8d4344e4944889e6
refs/heads/master
2023-04-30T05:25:03.143303
2021-05-20T15:00:43
2021-05-20T15:00:43
338,844,691
0
0
null
null
null
null
UTF-8
Python
false
false
3,517
py
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from rango.forms import CategoryForm, PageForm from django.urls import reverse from .models import Category, Page, User from django.db import IntegrityError from django.contrib.auth import authenticate, login, logout # Create your views here. def index(request): request.session.set_test_session categories = Category.objects.order_by('-likes')[:4] pages = Page.objects.order_by('-views')[:5] context = {'cat': categories, 'pages': pages} return render(request, 'rango/index.html', context) def category(request, category_name): category = Category.objects.get(name=category_name) pages = Page.objects.filter(category=category) context = {'category': category, 'pages': pages} return render(request, 'rango/category.html', context) def page(request, page_name): page = Page.objects.get(title=page_name) context = {'page': page} return render(request, 'rango/page.html', context) def add(request): if request.method == 'POST': form = CategoryForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('rango:index')) else: return render(request, 'rango/add_category.html', {'form': form}) else: form = CategoryForm() return render(request, 'rango/add_category.html', {'form': form}) def addpage(request, cat_name): category = Category.objects.get(name=cat_name) if request.method == 'POST': title = request.POST['title'] url = request.POST['url'] url = 'https://' + url Page.objects.create(category=category, title=title, url=url) return HttpResponseRedirect(reverse('rango:category', args=(category.name,))) else: return render(request, 'rango/add_page.html', {'cat': category}) def about(request): return HttpResponse("I'm cool") def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] # url = request.POST['url'] # profile_pic = request.POST['profile_pic'] password = request.POST['password'] confirmation = request.POST['confirmation'] if password == confirmation: try: user = User.objects.create_user(username=username, email=email, password=password) user.save() return HttpResponseRedirect(reverse('rango:login')) except IntegrityError: return render(request, 'rango/register.html', {'integrityerror': 'Sorry, username already exist.'}) else: return render(request, 'rango/register.html', {'passworderror': "Password doesn't match."}) else: return render(request, 'rango/register.html') def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse('rango:index')) else: return render(request, 'rango/login.html', {'loginerror': "Invalid username and/or password."}) else: return render(request, 'rango/login.html') def logout_view(request): logout(request) return HttpResponseRedirect(reverse('rango:index'))
[ "68882568+deji100@users.noreply.github.com" ]
68882568+deji100@users.noreply.github.com
3416dc37dc3591b6b17cd7ed333d6222c60420fc
44ea7a1057963cde7a2ac5a6fee1a089a096fb68
/tests/test_discovery.py
40218a1ea84bf6d5c3797e05eff270274ddddab2
[ "MIT" ]
permissive
YAtOff/lansync
3d0d9a41a00b6cc3d94fcbcd71fca8d849b1481d
750588f3b1db87287b518cb29523980e778edfef
refs/heads/master
2023-05-13T11:42:54.006428
2020-01-27T09:41:05
2020-01-27T09:41:05
224,862,668
0
0
MIT
2023-05-01T21:17:44
2019-11-29T13:47:59
Python
UTF-8
Python
false
false
1,560
py
from datetime import datetime from faker import Faker, providers from lansync.discovery import DiscoveryMessage, PeerRegistry, Peer fake = Faker() fake.add_provider(providers.internet) fake.add_provider(providers.misc) fake.add_provider(providers.date_time) def create_peer_params(): return ( fake.md5(), fake.hostname(), fake.ipv4(), fake.pyint(min_value=1024, max_value=65535) ) def test_discovery_message_handling(): registry = PeerRegistry() device_id, namespace, ip, port = create_peer_params() registry.handle_discovery_message( ip, DiscoveryMessage(device_id=device_id, namespace=namespace, port=port) ) assert device_id in registry.peers[namespace] def test_peer_choose(): registry = PeerRegistry() device_id, namespace, ip, port = create_peer_params() registry.handle_discovery_message( ip, DiscoveryMessage(device_id=device_id, namespace=namespace, port=port) ) peer = registry.choose(namespace) assert peer.device_id == device_id registry.peers[namespace][device_id].timestamp = datetime.min assert registry.choose(namespace) is None def test_peer_iteration(): registry = PeerRegistry() namespace = fake.hostname() peer_params = [create_peer_params() for _ in range(5)] for device_id, _, ip, port in peer_params: registry.handle_discovery_message( ip, DiscoveryMessage(device_id=device_id, namespace=namespace, port=port) ) assert len(list(registry.iter_peers(namespace))) == 5
[ "yavor.atov@gmail.com" ]
yavor.atov@gmail.com
7c8ebf0251c336d4f3265a35edf0b95326670407
2dce33fc951195cf9fb21f8c26926358b8f7fb87
/Sharing/views.py
f5e5897b17e043712ba015c861fe4855777fe91e
[]
no_license
hanifsarwary/Travelling-Companion
5531c35b4d4f503b83ab2f427cc6fd5543ae4e2c
b79b048ccdf6327b15090519dd1028344f4d39a2
refs/heads/master
2022-05-04T20:47:14.065334
2019-06-01T10:06:49
2019-06-01T10:06:49
179,090,935
0
0
null
2022-04-22T21:03:54
2019-04-02T14:04:12
Python
UTF-8
Python
false
false
1,187
py
from django.shortcuts import render from rest_framework.generics import * # Create your views here. from .serializer import * class CreateLuggageView(ListCreateAPIView): serializer_class = LuggageSerializer queryset = LuggageSharing.objects.all() class GetAllLuggageView(ListAPIView): serializer_class = LuggageSerializer def get_queryset(self): return LuggageSharing.objects.filter(active=True) class GetOneLuggageView(RetrieveAPIView): lookup_field = 'pk' serializer_class = LuggageSerializer def get_queryset(self): return LuggageSharing.objects.filter(pk=self.kwargs['pk']) class UpdateLuggageView(RetrieveUpdateAPIView): serializer_class = LuggageSerializer lookup_field = 'pk' class CreateCarView(CreateAPIView): serializer_class = CarSerializer queryset = CarSharing.objects.all() class GetAllCarView(RetrieveAPIView): serializer_class = CarSerializer queryset = CarSharing.objects.filter(active=True) class GetOneCarView(RetrieveAPIView): serializer_class = CarSerializer lookup_field = 'pk' def get_queryset(self): return CarSharing.objects.filter(pk=self.kwargs['pk'])
[ "mianhanif13@gmail.com" ]
mianhanif13@gmail.com
41ccba0bac47fc1a2880eccf4cd69dcf9867580d
c42a085521cec895fac0021eb1638d6f077eadf7
/PYTHON_FUNDAMENTALS_May_August_2020/Exam_Preparation_29_07_20_Python_Fundamentals/02. Registration.py
30888da99efa5b5a9e2aafbbc8a56bc9b8c8d6ed
[]
no_license
vasil-panoff/Python_Fundamentals_SoftUni_May_2020
f645ce85efa6db047b52a8b63d411d2e5bd5bd9a
daf1a27ff1a4684d51cf875ee0a4c0706a1a4404
refs/heads/main
2023-01-06T22:20:30.151249
2020-11-03T22:56:24
2020-11-03T22:56:24
309,818,123
0
0
null
null
null
null
UTF-8
Python
false
false
486
py
import re username_pattern = r'U\$([A-Z][a-z]{2,})U\$' password_pattern = r'P@\$([a-z]{5,}\d+)P@\$' regex = fr'{username_pattern}{password_pattern}' n = int(input()) total_count = 0 for i in range(n): registration = input() match = re.match(regex, registration) if match is None: print("Invalid username or password") continue total_count += 1 print(f'Username: {match[1]}, Password: {match[2]}') print(f'Successful registrations: {total_count}')
[ "vasil.panov@gmail.com" ]
vasil.panov@gmail.com
b6ef00ae2eebd8c444b26cbe6dda215cb3a4043c
2f36ee70b1224c5700eb9fd4d5b6d568a1c9fe9f
/dec.py
7c8d7795bfc91e4682d4d875ad613b7bff00ef42
[ "MIT" ]
permissive
laurelkeys/intimo
d70b4621f49937127c8ea9a72ff23495ba151a1e
f5c8200e52e4aeb9c04b4988a61dbc66c04f8255
refs/heads/master
2020-09-03T21:42:12.142312
2019-11-24T21:39:44
2019-11-24T21:39:44
219,578,931
0
0
MIT
2019-11-24T21:37:47
2019-11-04T19:22:15
Python
UTF-8
Python
false
false
3,735
py
import os, sys import argparse import warnings import cv2 import numpy as np import sounddevice as sd from scipy.io import wavfile from codec import decode from converter import convert def get_parser(): parser = argparse.ArgumentParser( description="Retrieve WAV audio data from an image bit plane.") parser.add_argument("enc_img_path", type=str, help="File name (with path) of a PNG image with audio encoded") parser.add_argument("--n_of_channels", "-ch", type=int, choices=[1, 2], default=1, help="Number of audio channels (1=mono, 2=stereo) (defaults to %(default)d)") parser.add_argument("--sample_rate", "-sr", type=int, choices=[8000, 44100], default=8000, help="Sample rate of audio recording (defaults to %(default)dHz)") parser.add_argument("--bit_plane", "-b", type=int, choices=range(0, 8), default=5, help="Bit plane in which to hide the captured audio (defaults to %(default)d)") parser.add_argument("--output_folder", "-o", type=str, default=".", help="Output folder to store the decoded audio (defaults to '%(default)s/')") parser.add_argument("--info_in_fname", "-iifn", action="store_true", help="Get the number of channels, sample rate, and bit plane from the image file name " "(other arguments will be ignored)") parser.add_argument("--playback", action="store_true", help="Play the decoded audio as well") parser.add_argument("--verbose", "-v", action="store_true", help="Increase verbosity") return parser ############################################################################### def main(args): enc_img = cv2.imread(args.enc_img_path) if args.info_in_fname: # "channels_samplerate_bitplane_YYYYmmdd-HHMMSS" fname, _ = os.path.splitext(os.path.basename(args.enc_img_path)) try: ch, sr, b, *_ = fname.split('_') args.n_of_channels = int(ch) args.sample_rate = int(sr) args.bit_plane = int(b) if args.verbose: print("Info taken from file name:") print(" - channels:", args.n_of_channels) print(" - samplerate:", args.sample_rate) print(" - bitplane:", args.bit_plane) except: print("When using --info_in_fname, the expected file name must be in the format: " "'channels_samplerate_bitplane_YYYYmmdd-HHMMSS.png'") exit() decoded_audio = decode(enc_img, args.bit_plane) assert decoded_audio.dtype == np.uint8 decoded_audio = convert(decoded_audio, to='int16') if args.n_of_channels == 2: warnings.warn("\nWarning: stereo audio isn't currently supported") # TODO convert decoded_audio to a 2D array if it's stereo fname, _ = os.path.splitext(os.path.basename(args.enc_img_path)) fname = os.path.join(args.output_folder, fname + "-decoded") wavfile.write(filename=fname + ".wav", rate=args.sample_rate, data=decoded_audio) if args.verbose: print(f"\nSaved audio to '{fname}.wav'") if args.playback: if args.verbose: print(f"\nPlaying (~{decoded_audio.size // args.sample_rate}s) audio..", end='') sd.play(decoded_audio, args.sample_rate) sd.wait() # wait until it is done playing if args.verbose: print(". done.") ############################################################################### if __name__ == '__main__': args = get_parser().parse_args() main(args)
[ "tiagoloureirochaves@gmail.com" ]
tiagoloureirochaves@gmail.com
705a6e762c4b0a8c8ffcf7d70018b1b1cca90cc3
d5f4b09c38cef1ae6ea22c70bd13316661fa1fcb
/Workspace/TestTxt.py
2da291715b852521b603af99913a1607f0b41aa1
[ "MIT" ]
permissive
ExtensiveAutomation/extensiveautomation-appclient
fa4ec42c762c0941c104b679374113b9eac8d0a0
66f65dd6e4a48909120f63239f630147c733df3f
refs/heads/master
2023-08-31T00:04:03.766489
2023-08-18T08:30:01
2023-08-18T08:30:01
168,972,301
2
1
null
null
null
null
UTF-8
Python
false
false
7,706
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # ------------------------------------------------------------------- # Copyright (c) 2010-2020 Denis Machard # This file is part of the extensive automation project # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA # ------------------------------------------------------------------- """ Test txt module """ import sys import base64 # unicode = str with python3 if sys.version_info > (3,): unicode = str from PyQt5.QtWidgets import (QVBoxLayout, QApplication) from Libs import QtHelper, Logger try: from PythonEditor import PyEditor from PythonEditor import EditorWidget except ImportError: # python3 support from .PythonEditor import PyEditor from .PythonEditor import EditorWidget try: import Document except ImportError: # python3 support from . import Document import UserClientInterface as UCI TYPE = 'txt' class WTestTxt(Document.WDocument): """ Test txt widget """ TEST_TXT_EDITOR = 0 def __init__(self, parent = None, path = None, filename = None, extension = None, nonameId = None, remoteFile=True, repoDest=None, project=0, isLocked=False): """ Constructs WScript widget @param parent: @type parent: @param path: @type path: @param filename: @type filename: @param extension: @type extension: @param nonameId: @type nonameId: """ Document.WDocument.__init__(self, parent, path, filename, extension, nonameId, remoteFile, repoDest, project, isLocked) self.srcEditor = None self.createWidgets() self.createConnections() def createWidgets (self): """ QtWidgets creation _______________________ | | | PyEditor | |_______________________| |________QSplitter______| | | | PyEditor | |_______________________| """ self.srcWidget = EditorWidget( editorId=self.TEST_TXT_EDITOR, title="Txt Definition:", parent=self, activePyLexer=False ) self.srcEditor = self.srcWidget.editor layout = QVBoxLayout() layout.addWidget(self.srcWidget) layout.setContentsMargins(2,0,0,0) self.setLayout(layout) def createConnections (self): """ QtSignals connection """ self.srcEditor.FocusChanged.connect( self.focusChanged ) self.srcEditor.cursorPositionChanged.connect(self.onCursorPositionChanged) self.srcEditor.textChanged.connect(self.setModify) self.srcEditor.textChanged.connect(self.updateTotalLines) def viewer(self): """ return the document viewer """ return self.parent def setWrappingMode(self, wrap): """ Set wrap mode """ self.srcEditor.setWrappingMode(wrap=wrap) def updateTotalLines(self): """ On total lines changed """ self.viewer().TotalLinesChanged.emit( self.editor().lines() ) def editor(self): """ Return the editor """ return self.srcEditor def setDefaultCursorPosition(self): """ Set the default cursor position """ self.srcEditor.setFocus() self.srcEditor.setCursorPosition(0,0) def onCursorPositionChanged (self , ln, col): """ Emit signal from parent to update the position of the cursor @param ln: line index @type ln: Integer @param col: column index @type col: Integer """ self.viewer().CursorPositionChanged.emit( ln, col ) def setFolding (self, fold): """ Active or deactivate the code folding @param fold: @type fold: boolean """ if fold: self.srcEditor.activeFolding(fold) else: self.srcEditor.activeFolding(fold) def setLinesNumbering (self, visible): """ Active or deactivate the lines numbering @param visible: @type visible: boolean """ if visible: self.srcEditor.setMarginLineNumbers(1, visible) self.srcEditor.onLinesChanged() else: self.srcEditor.setMarginLineNumbers(1, visible) self.srcEditor.setMarginWidth(1, 0) def setWhitespaceVisible (self, visible): """ Active or deactivate the whitespace visibility @param visible: @type visible: boolean """ if visible: self.srcEditor.setWhitespaceVisible(visible) else: self.srcEditor.setWhitespaceVisible(visible) def setIndentationGuidesVisible (self, visible): """ Active or deactivate indentation guides visibility @param visible: @type visible: boolean """ if visible: self.srcEditor.setIndentationGuidesVisible(visible) else: self.srcEditor.setIndentationGuidesVisible(visible) def currentEditor (self): """ Returns the editor that has the focus @return: Focus editor @rtype: PyEditor """ weditor = QApplication.focusWidget() if isinstance(weditor, PyEditor): if weditor.editorId == self.TEST_TXT_EDITOR: return self.srcEditor else: return self.srcEditor def focusChanged (self): """ Called when focus on editors Emit the signal "focusChanged" """ weditor = QApplication.focusWidget() if isinstance(weditor, PyEditor): if weditor.editorId == self.TEST_TXT_EDITOR: self.viewer().findWidget.setEditor( editor = self.srcEditor) self.viewer().FocusChanged.emit(self) def defaultLoad (self): """ Load default empty script """ self.srcEditor.setText( "" ) self.srcEditor.setFocus() self.setReadOnly( readOnly=False ) def load (self, content=None): """ Open file """ self.srcEditor.setText( content.decode("utf-8") ) self.srcEditor.setFocus() self.setReadOnly( readOnly=False ) return True def getraw_encoded(self): """ Returns raw data encoded """ encoded = "" try: raw = unicode(self.srcEditor.text()).encode('utf-8') encoded = base64.b64encode( raw ) if sys.version_info > (3,): encoded = encoded.decode("utf-8") except Exception as e: self.error( "unable to encode: %s" % e ) return encoded
[ "d.machard@gmail.com" ]
d.machard@gmail.com
0e7b38386ab690b9218ba8a713e93c88f1be4acf
6ab31b5f3a5f26d4d534abc4b197fe469a68e8e5
/katas/kyu_7/sorted_yes_no_how.py
42671da2fe9a26ca20c19645cb1f6d79ec5555f4
[ "MIT" ]
permissive
mveselov/CodeWars
e4259194bfa018299906f42cd02b8ef4e5ab6caa
1eafd1247d60955a5dfb63e4882e8ce86019f43a
refs/heads/master
2021-06-09T04:17:10.053324
2017-01-08T06:36:17
2017-01-08T06:36:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
230
py
def is_sorted_and_how(nums): a_or_d = {'a': 'ascending', 'd': 'descending'} diffs = {'d' if b - a < 0 else 'a' for a, b in zip(nums, nums[1:])} return 'yes, {}'.format(a_or_d[diffs.pop()]) if len(diffs) == 1 else 'no'
[ "the-zebulan@users.noreply.github.com" ]
the-zebulan@users.noreply.github.com
7b3b80fb2fc11b92f63feacf8246e4800fda39ae
e78ce85bac254f720e021f5f0ad172189da3ab77
/banco_de_dados/migrations/0002_exame_alt_anatomia.py
6b51029e3f25268d8689fa4b2950356fd1de1666
[]
no_license
lldenisll/backend_papaiz
4d1a0a0b427e708551d57381591614b9c8bf9c55
71f1eceafadbaf120f8ef9c87741fa8e431d192a
refs/heads/master
2023-07-29T10:28:09.634047
2021-09-10T13:01:50
2021-09-10T13:01:50
405,077,417
0
0
null
null
null
null
UTF-8
Python
false
false
490
py
# Generated by Django 3.2.5 on 2021-08-11 17:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('banco_de_dados', '0001_initial'), ] operations = [ migrations.CreateModel( name='Exame_alt_anatomia', fields=[ ('id_exame', models.IntegerField(primary_key=True, serialize=False)), ('id_alteracao', models.IntegerField()), ], ), ]
[ "namorado@TFGcos-MacBook-Pro.local" ]
namorado@TFGcos-MacBook-Pro.local
a7ae83cdc676a6fee62b948a17dfcb27194dca8a
32809f6f425bf5665fc19de2bc929bacc3eeb469
/src/1297-Maximum-Number-of-Occurrences-of-a-Substring/1297.py
aee0221f3b7df218ccd20e3d5a2801d51b640b42
[]
no_license
luliyucoordinate/Leetcode
9f6bf01f79aa680e2dff11e73e4d10993467f113
bcc04d49969654cb44f79218a7ef2fd5c1e5449a
refs/heads/master
2023-05-25T04:58:45.046772
2023-05-24T11:57:20
2023-05-24T11:57:20
132,753,892
1,575
569
null
2023-05-24T11:57:22
2018-05-09T12:30:59
C++
UTF-8
Python
false
false
312
py
class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: cnt = collections.Counter([s[i:i + minSize] for i in range(len(s) - minSize + 1)]) for k, v in cnt.most_common(): if len(set(k)) <= maxLetters: return v return 0
[ "luliyucoordinate@outlook.com" ]
luliyucoordinate@outlook.com
fb96fd36ffe7f093778aed80d23b8f51c8119a10
d8d6cb5563a71de354072096a5cabfa7a3748dda
/packages/vaex-arrow/vaex_arrow/convert.py
333d0a7568453cc83f62f5c5093a03bdbc52b769
[ "MIT" ]
permissive
tpoterba/vaex
f061ad443a1c8ed3f1c90e7206be316f87ab12df
a24e9c4cedc19753e8c7bacede9de37dfcee3c81
refs/heads/master
2020-04-11T08:42:52.703154
2018-12-13T10:03:13
2018-12-13T10:03:13
161,653,094
0
0
MIT
2018-12-13T14:48:19
2018-12-13T14:48:19
null
UTF-8
Python
false
false
2,682
py
import pyarrow import numpy as np def arrow_array_from_numpy_array(array): dtype = array.dtype mask = None if np.ma.isMaskedArray(array): mask = array.mask if dtype.kind == 'S': type = pyarrow.binary(dtype.itemsize) arrow_array = pyarrow.array(array, type, mask=mask) else: if dtype.isnative: arrow_array = pyarrow.array(array, mask=mask) else: # TODO: we copy here, but I guess we should not... or give some warning arrow_array = pyarrow.array(array.astype(dtype.newbyteorder('=')), mask=mask) return arrow_array def numpy_array_from_arrow_array(arrow_array): arrow_type = arrow_array.type buffers = arrow_array.buffers() assert len(buffers) == 2 bitmap_buffer = buffers[0] data_buffer = buffers[1] if isinstance(arrow_type, type(pyarrow.binary(1))): # todo, is there a better way to typecheck? # mimics python/pyarrow/array.pxi::Array::to_numpy buffers = arrow_array.buffers() assert len(buffers) == 2 dtype = "S" + str(arrow_type.byte_width) # arrow seems to do padding, check if it is all ok expected_length = arrow_type.byte_width * len(arrow_array) actual_length = len(buffers[-1]) if actual_length < expected_length: raise ValueError('buffer is smaller (%d) than expected (%d)' % (actual_length, expected_length)) array = np.frombuffer(buffers[-1], dtype, len(arrow_array))# TODO: deal with offset ? [arrow_array.offset:arrow_array.offset + len(arrow_array)] else: dtype = arrow_array.type.to_pandas_dtype() array = np.frombuffer(data_buffer, dtype, len(arrow_array)) if bitmap_buffer is not None: # arrow uses a bitmap https://github.com/apache/arrow/blob/master/format/Layout.md bitmap = np.frombuffer(bitmap_buffer, np.uint8, len(bitmap_buffer)) # we do have to change the ordering of the bits mask = 1-np.unpackbits(bitmap).reshape((len(bitmap),8))[:,::-1].reshape(-1)[:len(arrow_array)] array = np.ma.MaskedArray(array, mask=mask) return array def arrow_table_from_vaex_df(ds, column_names=None, selection=None, strings=True, virtual=False): """Implementation of Dataset.to_arrow_table""" names = [] arrays = [] for name, array in ds.to_items(column_names=column_names, selection=selection, strings=strings, virtual=virtual): names.append(name) arrays.append(arrow_array_from_numpy_array(array)) return pyarrow.Table.from_arrays(arrays, names) def vaex_df_from_arrow_table(table): from .dataset import DatasetArrow return DatasetArrow(table=table)
[ "maartenbreddels@gmail.com" ]
maartenbreddels@gmail.com
ea5bf03da06892d8e97f87a9e30552535d42d37a
6baeb1bcf18a442faa53a73000aa7cbfccffb0ce
/newv/Lib/site-packages/django/template/response.py
d06017c5209e7af0e21dbcc836d94a145bc4129d
[]
no_license
bipinmilan/HouseRental
22502b2c796f083751f10a7b1724e2566343fbc6
c047d0d20ad4255edcc493b3ae9d75d7819d73b6
refs/heads/master
2022-12-09T05:43:17.588485
2019-12-04T06:43:36
2019-12-04T06:43:36
225,795,647
0
0
null
2022-12-08T05:24:44
2019-12-04T06:28:27
Python
UTF-8
Python
false
false
5,425
py
from django.http import HttpResponse from .loader import get_template, select_template class ContentNotRenderedError(Exception): pass class SimpleTemplateResponse(HttpResponse): rendering_attrs = ['template_name', 'context_data', '_post_render_callbacks'] def __init__(self, template, context=None, content_type=None, status=None, charset=None, using=None): # It would seem obvious to call these next two members 'template' and # 'context', but those names are reserved as part of the test Client # api. To avoid the name collision, we use different names. self.template_name = template self.context_data = context self.using = using self._post_render_callbacks = [] # _request stores the current request object in subclasses that know # about requests, like TemplateResponse. It's defined in the base class # to minimize code duplication. # It's called self._request because self.request gets overwritten by # django.test.client.Client. Unlike template_name and context_data, # _request should not be considered part of the public api. self._request = None # content argument doesn't make sense here because it will be replaced # with rendered template so we always pass empty string in order to # prevent errors and provide shorter signature. super().__init__('', content_type, status, charset=charset) # _is_rendered tracks whether the template and context has been baked # into a final response. # Super __init__ doesn't know any better than to set self.content to # the empty string we just gave it, which wrongly sets _is_rendered # True, so we initialize it to False after the call to super __init__. self._is_rendered = False def __getstate__(self): """ Raise an exception if trying to pickle an unrendered response. Pickle only rendered data, not the data used to construct the response. """ obj_dict = self.__dict__.copy() if not self._is_rendered: raise ContentNotRenderedError('The response content must be ' 'rendered before it can be pickled.') for attr in self.rendering_attrs: if attr in obj_dict: del obj_dict[attr] return obj_dict def resolve_template(self, template): """Accept a template object, path-to-template, or list of paths.""" if isinstance(template, (list, tuple)): return select_template(template, using=self.using) elif isinstance(template, str): return get_template(template, using=self.using) else: return template def resolve_context(self, context): return context @property def rendered_content(self): """Return the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. """ template = self.resolve_template(self.template_name) context = self.resolve_context(self.context_data) content = template.render(context, self._request) return content def add_post_render_callback(self, callback): """Add a new post-rendering callback. If the response has already been rendered, invoke the callback immediately. """ if self._is_rendered: callback(self) else: self._post_render_callbacks.append(callback) def render(self): """Render (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Return the baked response instance. """ retval = self if not self._is_rendered: self.content = self.rendered_content for post_callback in self._post_render_callbacks: newretval = post_callback(retval) if newretval is not None: retval = newretval return retval @property def is_rendered(self): return self._is_rendered def __iter__(self): if not self._is_rendered: raise ContentNotRenderedError( 'The response content must be rendered before it can be iterated over.' ) return super().__iter__() @property def content(self): if not self._is_rendered: raise ContentNotRenderedError( 'The response content must be rendered before it can be accessed.' ) return super().content @content.setter def content(self, value): """Set the content for the response.""" HttpResponse.content.fset(self, value) self._is_rendered = True class TemplateResponse(SimpleTemplateResponse): rendering_attrs = SimpleTemplateResponse.rendering_attrs + ['_request'] def __init__(self, request, template, context=None, content_type=None, status=None, charset=None, using=None): super().__init__(template, context, content_type, status, charset, using) self._request = request
[ "bipinseo62@gmail.com" ]
bipinseo62@gmail.com
638577ab2dbc394a7aacba4ef64f0e646d9b26e6
00c6ded41b84008489a126a36657a8dc773626a5
/.history/Sizing_Method/Aerodynamics/Aerodynamics_20210714153638.py
9d8de4e6619d3956f350d237612b12fe713a8aee
[]
no_license
12libao/DEA
85f5f4274edf72c7f030a356bae9c499e3afc2ed
1c6f8109bbc18c4451a50eacad9b4dedd29682bd
refs/heads/master
2023-06-17T02:10:40.184423
2021-07-16T19:05:18
2021-07-16T19:05:18
346,111,158
0
0
null
null
null
null
UTF-8
Python
false
false
6,839
py
# author: Bao Li # # Georgia Institute of Technology # """Reference: 1: (2.3.1) Mattingly, Jack D., William H. Heiser, and David T. Pratt. Aircraft engine design. American Institute of Aeronautics and Astronautics, 2002. 2. Wedderspoon, J. R. "The high lift development of the A320 aircraft." International Congress of the Aeronautical Sciences, Paper. Vol. 2. No. 2. 1986. """ import numpy as np import Sizing_Method.Aerodynamics.MachNmuber as Ma import Sizing_Method.Other.US_Standard_Atmosphere_1976 as atm class aerodynamics_without_pd: """this is the class to generate aerodynamics model without dp based on Mattingly Equ 2.9 and section 2.3.1 1. SI Units 2. All assumptions, data, tables, and figures are based on large cargo and passenger aircraft, where we use A320neo as the baseline. """ def __init__(self, altitude, velocity, AR=10.3): """ :input h (m): altitude v (m/s): velocity AR: wing aspect ratio, normally between 7 and 10 :output K1: 2nd Order Coefficient for Cd K2: 1st Order Coefficient for Cd CD_0: drag coefficient at zero lift """ self.v = velocity self.h = altitude h = 2.43 # height of winglets b = 35.8 self.AR = AR * (1 + 1.9 * h / b) # equation 9-88, If the wing has winglets the aspect ratio should be corrected # Mach number based on different altitude # The Mach number is between 0 to 0.82 self.a = Ma.mach(self.h, self.v).mach_number() if self.a > 0.82: print("The Mach number is larger than 0.82, something going wrong!") self.CL_min = 0.1 # Assume constant: for most large cargo and passenger, 0.1 < Cl_min < 0.3 self.CD_min = 0.02 # Assume constant: From Mattingly Figure 2.9 e = 0.75 # wing planform efficiency factor is between 0.75 and 0.85, no more than 1 self.K_apo1 = 1 / (np.pi * self.AR * e) # self.K_apo1 = 1 / (np.pi * self.AR * e) # # K_apo2 is between 0.001 to 0.03 for most large cargo and passenger aircraft # Increase with Mach number increase. Thus, assume they have linear relationship K_apo2_max = 0.028 K_apo2_min = 0.001 a_max = 0.82 a_min = 0.001 slop = (K_apo2_max - K_apo2_min) / (a_max - a_min) # is the viscous drag due to lift (skin friction and pressure drag) self.K_apo2 = K_apo2_max - ((a_max - self.a) * slop) # K_apo2 = 0.03*self.a**0.5 # K_apo2 = 0.015*np.log(self.a)+0.03 # K_apo2 = 0.0345*self.a**0.25-0.005 def K1(self): """2nd Order Coefficient for Cd""" return self.K_apo1 + self.K_apo2 def K2(self): """1st Order Coefficient for Cd""" return -2 * self.K_apo2 * self.CL_min def CD_0(self): """drag coefficient at zero lift""" return self.CD_min + self.K_apo2 * self.CL_min ** 2 class aerodynamics_with_pd: """Estimation of ΔCL and ΔCD""" def __init__(self, altitude, velocity, Hp, n, W_S, P_W=90, sweep_angle=25.0, S=124.0, b=35.8, delta_b=0.5, delta_Dp=0.1, xp=0.5, beta=0.5, AOA_p=0.0, Cf=0.009): """ delta_b = 0.64 :param Hp: P_motor/P_total :param n: number of motor :param P_W: :param W_S: :param S: wing area :param b: wingspan :param delta_b: :param delta_Dp: :param xp: :param beta: slipstream correction factor:0-1 :param CL: lift coefficient :param AOA_p: propeller angle of attack :param Cf: skin friction coefficient :output: 1. ΔCD_0: zero lift drag coefficient changes because of the population distribution 2. ΔCL: lift coefficient changes because of the population distribution """ self.h = altitude self.v = velocity self.n = n self.s = S self.delta_y1 = delta_b self.delta_y2 = delta_Dp self.beta = beta self.sp = sweep_angle * np.pi / 180 self.aoa_p = AOA_p self.cf = Cf self.ar = b ** 2 / self.s # aspect ratio # the diameter of the propulsion, reference 1: Equation 21 dp = self.delta_y1 * b / (self.n * (1 + self.delta_y2)) # defining a parameter that indicates how much propulsion-disk # area is needed per unit of aircraft weight # reference 1: Equation 22 dp2w = self.delta_y1 ** 2 / (self.n * (1 + self.delta_y2)) ** 2 * self.ar / W_S self.rho = atm.atmosphere(geometric_altitude=self.h).density() self.t_w = P_W / self.v # thrust coefficient Tc of the DP propulsion # reference 1: Equation 24 tc = 1 / self.n * Hp * self.t_w / (self.rho * self.v ** 2 * dp2w) # Actuator disk theory shows that there is a maximum theoretical propulsive efficiency # for a given thrust coefficient ndp_isolated = 0.76 tc_max = np.pi / 8 * ((2 / ndp_isolated - 1) ** 2 - 1) if tc >= tc_max: tc = tc_max # axial induction factor at the propeller disk (ap) as a # function of the propeller thrust coefficient, from the actuator disk theory: # reference 1: Equation 25 ap = 0.5 * ((1 + 8 / np.pi * tc) ** 0.5 - 1) # the contraction ratio of the slipstream at the wing # leading edge (Rw/RP) can be expressed as # reference 1: Equation 26 rw_rp = ((1 + ap) / ( 1 + ap * (1 + 2 * xp / dp) / ((2 * xp / dp) ** 2 + 1) ** 0.5)) ** 0.5 # from conservation of mass in incompressible flow: axial induction factor self.aw = (ap + 1) / rw_rp ** 2 - 1 self.m = Ma.mach(self.h, self.v).mach_number() # Mach number def delta_lift_coefficient(self, CL): """estimate the lift coefficient changes because of pd""" aoa_w = (CL / (2 * np.pi * self.ar)) * (2 + ( self.ar ** 2 * (1 - self.m ** 2) * (1 + (np.tan(self.sp)) ** 2 / (1 - self.m ** 2)) + 4) ** 0.5) delta_cl = 2 * np.pi * ((np.sin(aoa_w) - self.aw * self.beta * np.sin(self.aoa_p - aoa_w)) * ((self.aw * self.beta) ** 2 + 2 * self.aw * self.beta * np.cos(self.aoa_p) + 1) ** 0.5 - np.sin(aoa_w)) delta_cl = delta_cl * self.delta_y1 return delta_cl def delta_CD_0(self): """estimate the zero lift drag coefficient changes because of the population distribution""" delta_cd0 = self.delta_y1 * self.aw ** 2 * self.cf return delta_cd0
[ "libao@gatech.edu" ]
libao@gatech.edu
62b7554daa56c6497a148072ef4e2ba0e2acb777
56b4d00870af18752b4414495b08e2ec3adf3ae4
/tests/clims/models/test_substance_visualize.py
00928f5bc205cc98eb747892cc05a823427582ae
[ "BSD-2-Clause" ]
permissive
commonlims/commonlims
26c3f937eaa18e6935c5d3fcec823053ab7fefd9
36a02ed244c7b59ee1f2523e64e4749e404ab0f7
refs/heads/develop
2021-07-01T17:20:46.586630
2021-02-02T08:53:22
2021-02-02T08:53:22
185,200,241
4
1
NOASSERTION
2021-02-02T08:53:23
2019-05-06T13:16:37
Python
UTF-8
Python
false
false
1,206
py
from __future__ import absolute_import from tests.clims.models.test_substance import SubstanceTestCase class TestSubstance(SubstanceTestCase): def setUp(self): self.has_context() def test_can_render_substance_graph(self): sample1 = self.create_gemstone() # sample1.v1 original_id = sample1.id assert (sample1.id, sample1.version) == (original_id, 1) # sample1.v1 aliquot1 = sample1.create_child() # aliquot1.v1 (from sample1.v1) aliquot1_id = aliquot1.id assert (aliquot1.id, aliquot1.version) == (aliquot1_id, 1) # aliquot1.v1 sample1.color = 'red' sample1.save() assert (sample1.id, sample1.version) == (original_id, 2) # sample1.v2 sample1.color = 'blue' sample1.save() assert (sample1.id, sample1.version) == (original_id, 3) # sample1.v3 aliquot2 = sample1.create_child() assert aliquot2.version == 1 assert len(aliquot2.parents) == 1 assert (aliquot2.parents[0].id, aliquot2.parents[0].version) == (original_id, 3) ancestry = sample1.to_ancestry() # returns everything with the same origins (i.e. sample1) ancestry.to_svg()
[ "costeinar@gmail.com" ]
costeinar@gmail.com
d29fc2511d456085db14c97843725d23a1057313
b2c0517a0421c32f6782d76e4df842875d6ffce5
/Algorithms/Tree/637. Average of Levels in Binary Tree.py
dc59a5deed5812ed84ce07c82b0f4ad35cf9ec86
[]
no_license
SuYuxi/yuxi
e875b1536dc4b363194d0bef7f9a5aecb5d6199a
45ad23a47592172101072a80a90de17772491e04
refs/heads/master
2022-10-04T21:29:42.017462
2022-09-30T04:00:48
2022-09-30T04:00:48
66,703,247
1
0
null
null
null
null
UTF-8
Python
false
false
597
py
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): res = list() if(not root): return res stack = list() stack.append(root) while(stack): temp = list() Sum = 0 count = 0 while(stack): node = stack.pop() Sum += node.val count += 1 if(node.left): temp.append(node.left) if(node.right): temp.append(node.right) stack = temp res.append(Sum / count) return res
[ "soration2099@gmail.com" ]
soration2099@gmail.com
a9c01d49f035fa98e11a770a4c38558c0ae757c1
2023cc7a0680af1758c0f667a1eae215c58a806b
/list_comprehension/list_comprehensions_test.py
b9355a9769baaa091f774f56ede82ba9443da35c
[]
no_license
EmpowerSecurityAcademy/master_repo
cc157be6441755903cbd7694e321c44a22d342aa
a2b189fe480e02fc9e83dcbbd3a6c84d480cf2b7
refs/heads/master
2021-05-01T12:30:05.921207
2016-08-31T22:56:13
2016-08-31T22:56:13
66,875,719
0
0
null
null
null
null
UTF-8
Python
false
false
555
py
import unittest from list_comprehensions import * class TestNumbers(unittest.TestCase): def test_even_numbers(self): result = even_numbers([1, 2, 4, 5, 7, 8]) self.assertEqual(result, [2, 4, 8]) # def test_start_with_a(self): # result = start_with_a(["apple", "orange", "carrot"]) # self.assertEqual(result, ["apple"]) # def test_multiply_by_11_numbers_divisable_by_three(self): # result = multiply_by_11_numbers_divisable_by_three([1, 2, 4, 9, 7, 12]) # self.assertEqual(result, [99, 132]) if __name__ == '__main__': unittest.main()
[ "sheltowt@gmail.com" ]
sheltowt@gmail.com
a554c517ba038a44869c29b36c0359276d048910
16b389c8dcace7f7d010c1fcf57ae0b3f10f88d3
/docs/jnpr_healthbot_swagger/test/test_rule_schema_byoi_plugin_parameters.py
26cd3b883961f232096d84c0eb6c999897aa28b2
[ "Apache-2.0" ]
permissive
Juniper/healthbot-py-client
e4e376b074920d745f68f19e9309ede0a4173064
0390dc5d194df19c5845b73cb1d6a54441a263bc
refs/heads/master
2023-08-22T03:48:10.506847
2022-02-16T12:21:04
2022-02-16T12:21:04
210,760,509
10
5
Apache-2.0
2022-05-25T05:48:55
2019-09-25T05:12:35
Python
UTF-8
Python
false
false
1,046
py
# coding: utf-8 """ Healthbot APIs API interface for Healthbot application # noqa: E501 OpenAPI spec version: 1.0.0 Contact: healthbot-hackers@juniper.net Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_client from swagger_client.models.rule_schema_byoi_plugin_parameters import RuleSchemaByoiPluginParameters # noqa: E501 from swagger_client.rest import ApiException class TestRuleSchemaByoiPluginParameters(unittest.TestCase): """RuleSchemaByoiPluginParameters unit test stubs""" def setUp(self): pass def tearDown(self): pass def testRuleSchemaByoiPluginParameters(self): """Test RuleSchemaByoiPluginParameters""" # FIXME: construct object with mandatory attributes with example values # model = swagger_client.models.rule_schema_byoi_plugin_parameters.RuleSchemaByoiPluginParameters() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "nitinkr@juniper.net" ]
nitinkr@juniper.net
f221c808e80e79fbf7f47d9405fc2c19189e9814
dec703232249a5b4b3c8c3ecac5e369cb9ed3b3e
/project/urls.py
85a74567a92a4c7002a7a193a16f76e85509f87c
[]
no_license
mmasterenko/ricod
4ab8a8bfd84095ee31021ca660b7d37a64f52d91
8b98a4393906ad1533266aa3d5c974916e49e0cc
refs/heads/master
2021-01-12T08:57:08.807616
2016-09-04T07:09:22
2016-09-04T07:09:22
76,731,374
0
0
null
null
null
null
UTF-8
Python
false
false
826
py
"""project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from ricod import views urlpatterns = [ url(r'^ricodadmin/', include(admin.site.urls)), url(r'^$', views.home, name='home'), url(r'^catalog/', views.catalog, name='catalog'), ]
[ "mmasterenko@gmail.com" ]
mmasterenko@gmail.com
c5dba810e00817877a884148ffdbb50430204751
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/6CGomPbu3dK536PH2_19.py
2e493421cb511fa5ca0f2bec4664db39a3154aeb
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
556
py
""" Create a function that takes in a list and returns a list of the accumulating sum. ### Examples accumulating_list([1, 2, 3, 4]) ➞ [1, 3, 6, 10] # [1, 3, 6, 10] can be written as [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4] accumulating_list([1, 5, 7]) ➞ [1, 6, 13] accumulating_list([1, 0, 1, 0, 1]) ➞ [1, 1, 2, 2, 3] accumulating_list([]) ➞ [] ### Notes An empty list input `[]` should return an empty list `[]`. """ def accumulating_list(lst): return [sum(lst[:(i + 1)]) for i in range(0, len(lst), 1)]
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
7f311b4afa86c8ca906e108d6d07a2e08cb12f38
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2214/60627/300861.py
243f233a14661085464368b8fe5f50eb1b4e3ef2
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
234
py
a = input()[:-1].split('+') b = input()[:-1].split('+') print(a,b) a[0] = int(a[0]) a[1] = int(a[1]) b[0] = int(b[0]) b[1] = int(b[1]) x = a[0]*b[0] + a[1]*b[1] y = a[1]*b[0] + a[0]*b[1] print(a,b) print(str(x) + '+' + str(y) + 'i')
[ "1069583789@qq.com" ]
1069583789@qq.com
20960e289520fe9cc0888be07971cf62745d8cf5
0c6024603ec197e66b759d006c7e8c8ddd8c6a27
/tests/test_docker.py
fdaf5c2d3eb7d325503b0b9c81285ccb2f92e636
[ "Apache-2.0" ]
permissive
cloudmesh/docker-url-provider
31f374b19b260564283d5771f319a7ebdf743598
95703378962e6a3aef027c11a5a94401b3f14776
refs/heads/main
2023-01-19T09:24:33.393770
2014-12-24T05:32:16
2014-12-24T05:32:16
25,997,814
0
0
null
null
null
null
UTF-8
Python
false
false
408
py
""" run with nosetests -v --nocapture """ from __future__ import print_function from cloudmesh_common.util import HEADING from cloudmesh_common.logger import LOGGER, LOGGING_ON, LOGGING_OFF log = LOGGER(__file__) class Test: def setup(self): pass def tearDown(self): pass def test_01_sample(self): HEADING() a = 1 b = 2 assert (a + b == 3)
[ "laszewski@gmail.com" ]
laszewski@gmail.com
4ba2261f15df0084b6779fbded58e3a84937c7f5
e9bb31bf22eb1edcd890d3117dc3b1e5fa929644
/keras.3-3.0.py
e6e50017a7cc32ac975fcdffe3866373903c3c3e
[]
no_license
paulcwlin/tf.keras-test
c6de79ca3ed49997269510ec85619974f583ed82
9914d4e67d1c0dbe5065676c3e25a8afd710f93b
refs/heads/main
2023-04-29T13:42:38.065355
2021-05-21T02:10:44
2021-05-21T02:10:44
369,390,372
0
0
null
null
null
null
UTF-8
Python
false
false
372
py
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten cnn = Sequential() cnn.add(Conv2D(filters=8, kernel_size=[3,3], padding='same', input_shape=[100,100,1])) cnn.add(MaxPooling2D(pool_size=[2,2], strides=2)) cnn.add(Flatten()) cnn.summary()
[ "bauroad@gmail.com" ]
bauroad@gmail.com
01905e300f6adc6e85e2b45520152fcab72bb167
4a27c69443bbbc44b8a826e059fcbb0ae38e0b09
/src/apps/plant/api/serializers.py
adcf8b3b25e6ac48d37473cac21743f61b8aff69
[]
no_license
amir-khakshour/3meg
3b102e694fb9e07221e106ada4e51083ef97738f
9573797c252480dca266d320ea2e97372c2c2b7a
refs/heads/master
2022-12-11T12:54:15.340521
2020-02-19T09:21:16
2020-02-19T09:21:16
240,120,884
0
0
null
2022-12-08T03:36:48
2020-02-12T21:39:46
Python
UTF-8
Python
false
false
927
py
from django.conf import settings from rest_framework import serializers from ..models import DataPoint, Plant class PlantSerializer(serializers.ModelSerializer): class Meta: model = Plant fields = '__all__' class DataPointSerializer(serializers.ModelSerializer): date_created = serializers.DateTimeField(read_only=True) class Meta: model = DataPoint fields = '__all__' class DataPointUpdateSerializer(serializers.Serializer): after = serializers.DateField(format=settings.DATAPOINT_DATE_FILTER_FORMAT, input_formats=[settings.DATAPOINT_DATE_FILTER_FORMAT, 'iso-8601'], required=True) before = serializers.DateField(format=settings.DATAPOINT_DATE_FILTER_FORMAT, input_formats=[settings.DATAPOINT_DATE_FILTER_FORMAT, 'iso-8601'], required=True) class Meta: fields = ('after', 'before',)
[ "khakshour.amir@gmail.com" ]
khakshour.amir@gmail.com
466bcae133a79639ffac7ea43c69d6dddece5cc3
1764780f3bd3cc23b537cb5c59efa08725495c73
/pjt-back/accounts/migrations/0001_initial.py
de77de9945891d66010ccf66f5cde05117a07fbd
[]
no_license
GaYoung87/GEEG
c048c420a266ed621d66bcd74070953f7e56e12d
6e31d86e8165e611d16f21cb0ac10ae8c2081f5b
refs/heads/master
2020-09-15T05:46:13.464753
2019-11-29T06:31:35
2019-11-29T06:31:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,758
py
# Generated by Django 2.2.7 on 2019-11-28 06:48 import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('age', models.IntegerField(null=True)), ('birthday', models.DateField(default='1993-06-16')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), ]
[ "gyyoon4u@naver.com" ]
gyyoon4u@naver.com
904d4ab48a948edeb19066e5b38eef81900b58bc
78d23de227a4c9f2ee6eb422e379b913c06dfcb8
/LeetCode/963.py
505d68a6549dbbab3bb2fa8d985f20898927548e
[]
no_license
siddharthcurious/Pythonic3-Feel
df145293a3f1a7627d08c4bedd7e22dfed9892c0
898b402b7a65073d58c280589342fc8c156a5cb1
refs/heads/master
2020-03-25T05:07:42.372477
2019-09-12T06:26:45
2019-09-12T06:26:45
143,430,534
1
0
null
null
null
null
UTF-8
Python
false
false
1,558
py
from itertools import combinations class Solution(object): def findArea(self, points): x1, y1 = points[0] x2, y2 = points[1] x3, y3 = points[2] x4, y4 = points[3] a = (x1*y2 - x2*y1) + (x2*y3 - x3*y2) + (x3*y4 - x4*y3) + (x4*y1-y4*x1) print(a) if a < 0: a = -1 * a return a def sqr(self, num): return num * num def isRectangle(self, points): x1, y1 = points[0] x2, y2 = points[1] x3, y3 = points[2] x4, y4 = points[3] cx = (x1 + x2 + x3 + x4)/4 cy = (y1 + y2 + y3 + y4)/4 dd1 = self.sqr(cx - x1) + self.sqr(cy - y1) dd2 = self.sqr(cx - x2) + self.sqr(cy - y2) dd3 = self.sqr(cx - x3) + self.sqr(cy - y3) dd4 = self.sqr(cx - x4) + self.sqr(cy - y4) return dd1 == dd2 and dd1 == dd3 and dd1 == dd4 def minAreaFreeRect(self, points): """ :type points: List[List[int]] :rtype: float """ min_area = float("inf") points_combs = combinations(points, 4) for p in points_combs: r = self.isRectangle(p) if r == True: a = self.findArea(p) if min_area > a: min_area = a return min_area if __name__ == "__main__": s = Solution() points = [[1,2],[2,1],[1,0],[0,1], [2,3]] points = [[0,1],[2,1],[1,1],[1,0],[2,0]] points = [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]] r = s.minAreaFreeRect(points) print(r)
[ "sandhyalalkumar@gmail.com" ]
sandhyalalkumar@gmail.com
375e9fa42abf66b0ce774aa92bfab88473ddbff4
21963071945c7bb54a7f126da536da3c2ff40cbe
/Lesson05/binaryTree.py
8d9b632d330ef46fba9f1bbe6d99dd55096c4eb4
[]
no_license
SaretMagnoslove/Data_structures_and_Algorithms_python-Udacity
f05770c112b91206b798305da3dd5f3e2a93a7d9
640c30bd39645bbddad10ac50823434ab82b4354
refs/heads/master
2020-03-21T08:03:41.210949
2018-06-29T17:43:42
2018-06-29T17:43:42
138,317,271
0
0
null
null
null
null
UTF-8
Python
false
false
1,585
py
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self, root): self.root = Node(root) def search(self, find_val): """Return True if the value is in the tree, return False otherwise.""" return self.preorder_search(self.root, find_val) def print_tree(self): """Print out all tree nodes as they are visited in a pre-order traversal.""" return self.preorder_print(self.root, '')[:-1] def preorder_search(self, start, find_val): """Helper method - use this to create a recursive search solution.""" if start: return True if start.value == find_val else self.preorder_search(start.left, find_val) or self.preorder_search(start.right, find_val) return False def preorder_print(self, start, traversal): """Helper method - use this to create a recursive print solution.""" if start: traversal += str(start.value) + '-' traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right,traversal) return traversal # Set up tree tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) # Test search # Should be True print (tree.search(4)) # Should be False print (tree.search(6)) # Test print_tree # Should be 1-2-4-5-3 print( tree.print_tree())
[ "magnoslove@gmail.com" ]
magnoslove@gmail.com
1f89fc3c868206f312b83b1732337ece61d67b5a
8813b9e9894ead566efc0ea192a88cd6546ae29e
/ninjag/tk/ioTK/save_text.py
26cae83c4e3b3846fb06a20ec983e3eb86400daf
[ "MIT" ]
permissive
yuhangwang/ninjag-python
1638f396711533c2b540dee2d70240fa25009c86
b42b447260eebdd6909246a5f7bb4098bfa3c0e1
refs/heads/master
2021-01-12T04:04:13.395305
2017-02-20T19:12:52
2017-02-20T19:12:52
77,489,214
0
1
null
null
null
null
UTF-8
Python
false
false
261
py
def save_text(f_out, *text): """Save text to file Args: f_out (str): output file name text (str): variable number of strings of file content """ with open(f_out, 'w') as OUT: OUT.write("\n".join(text) + "\n")
[ "stevenaura@live.com" ]
stevenaura@live.com
c780f7566c732bdec5336ac8598da93c5a0a1b5b
87bae60470bbe5316d7da8bc4a8709e33b40e2b5
/setup.py
e5bd575e22fb71ebd994629da6b018f29618bf9b
[]
no_license
saxix/django-whatsnew
c11f0d5fa87e5e1c5c7648e8162bd39c64e69302
68b33e5e2599a858e00eda53e1c13a503e1b3856
refs/heads/develop
2021-01-19T12:39:41.876635
2015-01-28T16:18:29
2015-01-28T16:18:29
18,416,313
0
2
null
2015-01-28T16:18:30
2014-04-03T20:00:33
Python
UTF-8
Python
false
false
689
py
#!/usr/bin/env python from setuptools import setup, find_packages dirname = 'whatsnew' app = __import__(dirname) setup( name=app.NAME, version=app.get_version(), url='https://github.com/saxix/django-whatsnew', description="Simple application to manage `what's new` screen.", author='sax', author_email='sax@os4d.org', license='BSD', packages=find_packages('.'), include_package_data=True, platforms=['linux'], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers' ] )
[ "s.apostolico@gmail.com" ]
s.apostolico@gmail.com
8fd2b111a6bb6157ab8fc2e2c901b7dcf47cbf51
ad129f7fc03f10ef2b4734fa2c2b9cb9367c84fa
/Aula 15 - BREAK/Exe070.py
574b69c6195435654ca96c47aef7bde33477767d
[]
no_license
LucasDatilioCarderelli/Exercises_CursoemVideo
c6dc287d7c08a0349867a17185474744513dbaac
67c2d572a4817a52dababbca80513e4b977de670
refs/heads/master
2022-03-31T20:20:52.827370
2020-01-27T13:15:19
2020-01-27T13:15:19
236,491,751
0
0
null
null
null
null
UTF-8
Python
false
false
776
py
# Exe070 - Digite o nome e valor de varios produtos e tenha: # O total da compra, quantos produtos acima de R$1.000,00 e qual o menor produto. cont = contn = soma = menor = 0 menorn = ' ' print(f'{"LOJINHA":-^40}') while True: nome = str(input('Nome: ')) preço = float(input('Preço: R$').strip()) soma += preço contn += 1 if contn == 1 or preço < menor: menor = preço menorn = nome if preço >= 1000: cont += 1 parada = ' ' while parada not in 'SN': parada = str(input('Mais 1 produto [S/N]?: ').strip().upper()[0]) if parada == 'N': break print(f'Total: R${soma:.2f}') print(f'Acima de R$1.000,00: {cont}') print(f'O menor produto custou R${menor} ({menorn}).') print(f'{"VOLTE SEMPRE":-^40}')
[ "noreply@github.com" ]
LucasDatilioCarderelli.noreply@github.com
a8e051e4166dba43f6cc50ba51c3b0cf0686feb4
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/HLTrigger/Configuration/python/HLT_75e33/modules/hltDiEG3023IsoCaloIdHcalIsoL1SeededFilter_cfi.py
aabfec4938f1f470ccd88a2dc9ca5286f84e2174
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
Python
false
false
1,303
py
import FWCore.ParameterSet.Config as cms hltDiEG3023IsoCaloIdHcalIsoL1SeededFilter = cms.EDFilter("HLTEgammaGenericQuadraticEtaFilter", absEtaLowEdges = cms.vdouble(0.0, 0.8, 1.479, 2.0), candTag = cms.InputTag("hltDiEG3023IsoCaloIdHgcalIsoL1SeededFilter"), doRhoCorrection = cms.bool(False), effectiveAreas = cms.vdouble(0.2, 0.2, 0.4, 0.5), energyLowEdges = cms.vdouble(0.0), etaBoundaryEB12 = cms.double(0.8), etaBoundaryEE12 = cms.double(2.0), l1EGCand = cms.InputTag("hltEgammaCandidatesL1Seeded"), lessThan = cms.bool(True), ncandcut = cms.int32(2), rhoMax = cms.double(99999999.0), rhoScale = cms.double(1.0), rhoTag = cms.InputTag("hltFixedGridRhoFastjetAllCaloForEGamma"), saveTags = cms.bool(True), thrOverE2EB1 = cms.vdouble(0.0), thrOverE2EB2 = cms.vdouble(0.0), thrOverE2EE1 = cms.vdouble(0.0), thrOverE2EE2 = cms.vdouble(0.0), thrOverEEB1 = cms.vdouble(0.02), thrOverEEB2 = cms.vdouble(0.02), thrOverEEE1 = cms.vdouble(0.02), thrOverEEE2 = cms.vdouble(0.02), thrRegularEB1 = cms.vdouble(22), thrRegularEB2 = cms.vdouble(22), thrRegularEE1 = cms.vdouble(22), thrRegularEE2 = cms.vdouble(22), useEt = cms.bool(True), varTag = cms.InputTag("hltEgammaHcalPFClusterIsoL1Seeded") )
[ "Thiago.Tomei@cern.ch" ]
Thiago.Tomei@cern.ch
8e47efee6b734ae3afc39185eb157680455e8b0f
def78b4f5764e77a12c2ba01cbeb0d41ec7dbc2b
/tests/test_wsgi_interface.py
98e4b3cf3e98f1d65eaf7c2d03d770d939990d2d
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
aelol/falcon
e7e789cb92c75146eea4a1c627fdda278655594b
14a9c056542a7e4a99663ee0fe298c81c27a8cdd
refs/heads/master
2021-01-20T01:13:29.044522
2017-04-21T21:49:30
2017-04-21T21:49:30
89,238,339
2
0
null
2017-04-24T12:36:37
2017-04-24T12:36:37
null
UTF-8
Python
false
false
1,478
py
import re import sys import falcon import falcon.testing as testing class TestWSGIInterface(object): def test_srmock(self): mock = testing.StartResponseMock() mock(falcon.HTTP_200, ()) assert mock.status == falcon.HTTP_200 assert mock.exc_info is None mock = testing.StartResponseMock() exc_info = sys.exc_info() mock(falcon.HTTP_200, (), exc_info) assert mock.exc_info == exc_info def test_pep3333(self): api = falcon.API() mock = testing.StartResponseMock() # Simulate a web request (normally done though a WSGI server) response = api(testing.create_environ(), mock) # Verify that the response is iterable assert _is_iterable(response) # Make sure start_response was passed a valid status string assert mock.call_count == 1 assert isinstance(mock.status, str) assert re.match('^\d+[a-zA-Z\s]+$', mock.status) # Verify headers is a list of tuples, each containing a pair of strings assert isinstance(mock.headers, list) if len(mock.headers) != 0: header = mock.headers[0] assert isinstance(header, tuple) assert len(header) == 2 assert isinstance(header[0], str) assert isinstance(header[1], str) def _is_iterable(thing): try: for i in thing: break return True except: return False
[ "john.vrbanac@linux.com" ]
john.vrbanac@linux.com
a21f4e0d8bc75227d7a7e081134be283a036133b
4766d241bbc736e070f79a6ae6a919a8b8bb442d
/20200215Python-China/0392. Is Subsequence.py
772e0d436bb37843470e51a166049300a942b2c3
[]
no_license
yangzongwu/leetcode
f7a747668b0b5606050e8a8778cc25902dd9509b
01f2edd79a1e922bfefecad69e5f2e1ff3a479e5
refs/heads/master
2021-07-08T06:45:16.218954
2020-07-18T10:20:24
2020-07-18T10:20:24
165,957,437
10
8
null
null
null
null
UTF-8
Python
false
false
1,204
py
'''Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not). Example 1: s = "abc", t = "ahbgdc" Return true. Example 2: s = "axc", t = "ahbgdc" Return false. Follow up: If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code? Credits: Special thanks to @pbrother for adding this problem and creating all test cases. ''' class Solution: def isSubsequence(self, s: str, t: str) -> bool: k_s=0 k_t=0 while k_s<len(s): while k_t<len(t) and s[k_s]!=t[k_t]: k_t+=1 if k_t==len(t): return False k_s+=1 k_t+=1 return True
[ "noreply@github.com" ]
yangzongwu.noreply@github.com
125a74be48b8ad0a0ee346339d421c491c8a8abb
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/leap/6b4d8efbe16141d1b280e11117525144.py
57e2f3eea9084a568523dbd855b76d0242f6a9e3
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
262
py
# # Skeleton file for the Python "Leap" exercise. # def is_leap_year(year): year = int(year) cond_1 = (year % 4 == 0) and (year % 100 == 0) and (year % 400 == 0) cond_2 = (year % 4 == 0) and (not year % 100 == 0 ) return cond_1 or cond_2
[ "rrc@berkeley.edu" ]
rrc@berkeley.edu
81ecc501d76374282b768dd904e912cc7b87eda4
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_34/782.py
314631cc964f6be8ced98e9b41079f0b36341c92
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,031
py
#! /usr/bin/python import os import sys import glob from math import sqrt if len(sys.argv) != 2: print 'USAGE: q1.py input.in' sys.exit() fIn = open(sys.argv[1], 'r') param = fIn.readline().split() L = int(param[0]) D = int(param[1]) N = int(param[2]) #print str(L)+str(D)+str(N) dict = [] for i in range(D): dict.append(fIn.readline()[:-1]) #print dict tokens = ['' for i in range(L)] #print len(tokens) for i in range(N): line = fIn.readline()[:-1] pos = 0 for j in range(L): m = line[pos] if m != '(' and m != ')': tokens[j] = m pos = pos + 1 if m == '(': while(1): pos = pos + 1 m = line[pos] if m == ')': pos = pos + 1 break tokens[j] += m j = j + 1 # print tokens count = 0 for j in range(D): tag = 1 word = dict[j] # print word for pos in range(L): if tokens[pos].count(word[pos]) == 0: tag = 0 # print 'NOT' break if tag == 1: count = count + 1 print 'Case #'+str(i+1)+': '+str(count) tokens = ['' for i in range(L)] # print '\n'
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
c91e3350c5dd6e4d67b9b480a11112fe1ec6d399
190f56bb215311c293e2c07e40be3d7cc3a5e189
/addresses/migrations/0012_auto_20201005_2323.py
3535fdcd5265d806be49d98d077cb8380602e716
[]
no_license
Omsinha017/Ecommerce
457dec1c5dcc313d4fae6dff0b1d7c7f43874655
d4e57576eef18626d458f0c06b186d0b8a6bc753
refs/heads/master
2023-06-21T11:21:46.495736
2021-07-24T09:09:16
2021-07-24T09:09:16
305,804,444
1
0
null
null
null
null
UTF-8
Python
false
false
454
py
# Generated by Django 3.1 on 2020-10-05 17:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('addresses', '0011_auto_20201005_2317'), ] operations = [ migrations.AlterField( model_name='address', name='address_type', field=models.CharField(choices=[('shipping', 'Shipping'), ('billing', 'Billing')], max_length=120), ), ]
[ "omsinha017@gmail.com" ]
omsinha017@gmail.com
05d56ee57fb8108d00d0c956207892d6f5fd29ce
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/409/usersdata/317/79303/submittedfiles/av1_programa1.py
3f2948ad76a641790398b54e2d495c53608bdaf4
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
164
py
# ENTRADA n = int(input('ditige o número')) if (n/2)%0: print=int(input('o numero é par') else: print=int(input('o numero é impar') print('----FIM----')
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
4b7bc8f4343f81177c562ce45bd65b4be418f47f
c2758f58b29917e5f00cdf19389a0f55b2975eae
/examples/analysis_md2.py
d720cbf028ecc04f0d1914b4b2ce5424d136a8a5
[]
no_license
rdemaria/pyoptics
4cf0b59e3524996de84c38a98a1444509246e9d4
6679a7589c751285757b8166c76aeaa1359742da
refs/heads/master
2023-07-08T19:55:50.364373
2023-06-30T09:50:12
2023-06-30T09:50:12
25,566,323
6
11
null
2023-06-14T12:31:15
2014-10-22T06:47:52
Python
UTF-8
Python
false
false
1,538
py
t_start='2011-05-07 10:00:00.000' t_end='2011-05-07 20:00:00.000' data=cernlogdb.dbget('RPTE.UA23.RB.A12:I_MEAS',t1=t_start,t2=t_end,conf='ldb.conf') data1=cernlogdb.dbget(bctdc,t1=t_start,t2=t_end,conf='ldb.conf') data2=cernlogdb.dbget(bctfr,t1=t_start,t2=t_end,conf='ldb.conf') data3=cernlogdb.dbget(rffreq,t1=t_start,t2=t_end,conf='ldb.conf') bpmb1_fns=sorted(glob('data_ats_md2/fill_data/*/BPM/Beam1@Turn@*.sdds.gz')) bpmb2_fns=sorted(glob('data_ats_md2/fill_data/*/BPM/Beam2@Turn@*.sdds.gz')) bpmb1_t= cernlogdb.t2num([ bpmdata_date(fn) for fn in bpmb1_fns]) bpmb2_t= cernlogdb.t2num([ bpmdata_date(fn) for fn in bpmb2_fns]) vn=data['datavars'][0] t,v=data[0] t=cernlogdb.t2num(t) plot_date(t,v,'k',label=vn) ylim(0,8000) twinx() cernlogdb.plot_data(data2) ylim(0,2e10) twinx() cernlogdb.plot_data(data3) ylim(0,2e10) ax=gca() [ axvline(t,color='c') for t in bpmb1_t ] [ axvline(t,color='y') for t in bpmb2_t ] run harmonic_fit.py run __init__.py m.__class__=LHCBPM bpmb1_fns=sorted(glob('data_ats_md2/fill_data/*/BPM/Beam1@Turn@*.sdds.gz')) bpmb2_fns=sorted(glob('data_ats_md2/fill_data/*/BPM/Beam2@Turn@*.sdds.gz')) m=LHCBPM(bpmb1_fns[-7]) m.mk_fitlsq() t1=optics.open('twiss_lhcb1.tfs') t2=optics.open('twiss_lhcb2.tfs') m.mk_spos(t1) goodx=(~m.badxy) & m.xidx goody=(~m.badxy) & m.yidx sum((m.tune*m.res)[goodx])/sum(m.res[goodx]) sum((m.tune*m.res)[goody])/sum(m.res[goody]) u,s,v=svd(m.data[~m.badxy]) u,s,v=svd(m.data[goodx]) f=linspace(0,0.5,2250/2+1) figure();plot(f,abs(rfft(v[:,:5],axis=0)))
[ "riccardodemaria@gmail.com" ]
riccardodemaria@gmail.com
66a874aeab5071d8d192da698ca71a914f216eed
1a642f40e88f05075c64da1256901d1b796f33fd
/06. Dictionaries/person.py
34b14cd3b24a14714daa6f94de222abd56a7eb41
[]
no_license
Mart1nDimtrov/Python-Crash-Course
357ca4a015929b455395807dfeb260191342e360
326fdedc96e3d3e2ae9597349b54dd9e31a8fb4f
refs/heads/master
2021-01-26T07:07:53.844047
2020-09-27T20:59:17
2020-09-27T20:59:17
243,358,761
0
0
null
null
null
null
UTF-8
Python
false
false
544
py
#6-1. Person: Use a dictionary to store information about a person you know. #Store their first name, last name, age, and the city in which they live. You #should have keys such as first_name, last_name, age, and city. Print each #piece of information stored in your dictionary. person = { 'first_name':'stoyan', 'last_name':'filipov', 'age':25, 'city':'Varna', } print(f'First name: {person["first_name"].title()}.') print(f'Last name: {person["last_name"].title()}.') print(f'Age: {person["age"]}.') print(f'City: {person["city"]}.')
[ "giggly@abv.bg" ]
giggly@abv.bg
1a14569986273f76fc063f439ab0fb87663f2adf
47aa27752421393451ebed3389b5f3a52a57577c
/src/Lib/test/test_json/test_recursion.py
72bccd31ccd7ec23fed0c9ab2c62a5c435638ec7
[ "MIT" ]
permissive
NUS-ALSET/ace-react-redux-brython
e66db31046a6a3cd621e981977ed0ca9a8dddba9
d009490263c5716a145d9691cd59bfcd5aff837a
refs/heads/master
2021-08-08T08:59:27.632017
2017-11-10T01:34:18
2017-11-10T01:34:18
110,187,226
1
1
null
null
null
null
UTF-8
Python
false
false
3,106
py
from test.test_json import PyTest, CTest class JSONTestObject: pass class TestRecursion: def test_listrecursion(self): x = [] x.append(x) try: self.dumps(x) except ValueError: pass else: self.fail("didn't raise ValueError on list recursion") x = [] y = [x] x.append(y) try: self.dumps(x) except ValueError: pass else: self.fail("didn't raise ValueError on alternating list recursion") y = [] x = [y, y] # ensure that the marker is cleared self.dumps(x) def test_dictrecursion(self): x = {} x["test"] = x try: self.dumps(x) except ValueError: pass else: self.fail("didn't raise ValueError on dict recursion") x = {} y = {"a": x, "b": x} # ensure that the marker is cleared self.dumps(x) def test_defaultrecursion(self): class RecursiveJSONEncoder(self.json.JSONEncoder): recurse = False def default(self, o): if o is JSONTestObject: if self.recurse: return [JSONTestObject] else: return 'JSONTestObject' return pyjson.JSONEncoder.default(o) enc = RecursiveJSONEncoder() self.assertEqual(enc.encode(JSONTestObject), '"JSONTestObject"') enc.recurse = True try: enc.encode(JSONTestObject) except ValueError: pass else: self.fail("didn't raise ValueError on default recursion") def test_highly_nested_objects_decoding(self): # test that loading highly-nested objects doesn't segfault when C # accelerations are used. See #12017 with self.assertRaises(RuntimeError): self.loads('{"a":' * 100000 + '1' + '}' * 100000) with self.assertRaises(RuntimeError): self.loads('{"a":' * 100000 + '[1]' + '}' * 100000) with self.assertRaises(RuntimeError): self.loads('[' * 100000 + '1' + ']' * 100000) def test_highly_nested_objects_encoding(self): # See #12051 l, d = [], {} for x in range(100000): l, d = [l], {'k':d} with self.assertRaises(RuntimeError): self.dumps(l) with self.assertRaises(RuntimeError): self.dumps(d) def test_endless_recursion(self): # See #12051 class EndlessJSONEncoder(self.json.JSONEncoder): def default(self, o): """If check_circular is False, this will keep adding another list.""" return [o] with self.assertRaises(RuntimeError): EndlessJSONEncoder(check_circular=False).encode(5j) class TestPyRecursion(TestRecursion, PyTest): pass class TestCRecursion(TestRecursion, CTest): pass
[ "chrisboesch@nus.edu.sg" ]
chrisboesch@nus.edu.sg
7061e0aabffe58d1301cd83d5b44595f4f605b73
2aa21b0d818397d5299bee411aa4df9058c6369e
/atcoder/abc130_c.py
f2db33e09de9a6f10eda0fc8a7f7dcdd7fe5cdca
[]
no_license
YuheiNakasaka/leetcode
ef4a0c04c44c9e9a727773b7d4a1bed0cbc17cba
9109f35a20b5a36e1bd611dbe5ad56ad724e0c96
refs/heads/master
2020-05-16T08:04:34.523056
2020-04-21T00:55:33
2020-04-21T00:55:33
182,897,555
0
0
null
null
null
null
UTF-8
Python
false
false
138
py
W, H, x, y = list(map(int, input().split())) square = (W * H) / 2 cnt = '0' if x + x == W and y + y == H: cnt = '1' print(square, cnt)
[ "yuhei.nakasaka@gmail.com" ]
yuhei.nakasaka@gmail.com
41b8308911f0359ad34e366f655fdeeddf5b3ed0
cca5ceb42b09e567d79fcb46f298757c1ff04447
/Async/Async_4.py
cdf82e563fb9572cf18c1dc4350d6062eba95012
[]
no_license
NishantGhanate/PythonScripts
92933237720e624a0f672729743a98557bea79d6
60b92984d21394002c0d3920bc448c698e0402ca
refs/heads/master
2022-12-13T11:56:14.442286
2022-11-18T14:26:33
2022-11-18T14:26:33
132,910,530
25
15
null
2022-12-09T09:03:58
2018-05-10T14:18:33
Python
UTF-8
Python
false
false
377
py
import asyncio import time class A: async def fucn_1(self): await asyncio.sleep(3) print('hello') async def fucn_2(self): await asyncio.sleep(1) print('yellow') a = A() loop = asyncio.get_event_loop() task1 = loop.create_task(a.fucn_1()) task2 = loop.create_task(a.fucn_2()) loop.run_until_complete(asyncio.gather(task1, task2))
[ "nishant7.ng@gmail.com" ]
nishant7.ng@gmail.com
a0a448f4f413e67c688e869495f5dd1e476d5794
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03623/s414511746.py
255735db787058e6f8122bb55e8033b5d199aa1e
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
170
py
def solve(): x, a, b = map(int, input().split()) if abs(x-a) > abs(x-b): print('B') else: print('A') if __name__ == "__main__": solve()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
ac5a3b92fd58d9f527030ff4fcb8246f03858bc0
ce8d151a075931f2af5c4e2bcc5498fda9dbd1b1
/foundation/organisation/migrations/0015_remove_networkgroup_position.py
41256b78b311cff20d00d3ef0f23cf7082ef1a98
[ "MIT" ]
permissive
okfn/website
d089dfad786b11813c2cad6912cb40e4d277b6e8
1055300216619c30cb06d58e51d78f739beb6483
refs/heads/develop
2023-08-30T23:43:11.515725
2023-08-29T07:41:06
2023-08-29T07:41:06
15,168,170
83
110
MIT
2023-09-13T04:52:25
2013-12-13T16:20:09
Python
UTF-8
Python
false
false
407
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-08-24 10:37 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('organisation', '0014_auto_20200824_1033'), ] operations = [ migrations.RemoveField( model_name='networkgroup', name='position', ), ]
[ "chris.shaw480@gmail.com" ]
chris.shaw480@gmail.com
40147c0abe5fcae15c46d9e2ca12cbd6e7d09e8e
841b8d707cf42dbb26089c89c83fd3238f7f56cf
/root_numpy/_graph.py
66e59f7497e70a264117e98aedd252c74946b253
[ "BSD-3-Clause" ]
permissive
ndawe/root_numpy
d6682976e78acacd25b331ecd9958a270d0eb9eb
34625988547e8a462cc8e10cba6459e9fa2fa65e
refs/heads/master
2020-04-05T04:37:47.389235
2017-10-23T03:20:18
2017-10-23T03:20:18
6,723,352
1
0
null
2012-12-16T05:49:48
2012-11-16T15:13:52
C++
UTF-8
Python
false
false
1,369
py
import numpy as np from . import _librootnumpy __all__ = [ 'fill_graph', ] def fill_graph(graph, array): """Fill a ROOT graph with a NumPy array. Parameters ---------- hist : a ROOT TGraph or TGraph2D The ROOT graph to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the graph with. The number of columns must match the dimensionality of the graph. """ import ROOT array = np.asarray(array, dtype=np.double) if isinstance(graph, ROOT.TGraph): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 2: raise ValueError( "length of the second dimension must equal " "the dimension of the graph") return _librootnumpy.fill_g1( ROOT.AsCObject(graph), array) elif isinstance(graph, ROOT.TGraph2D): if array.ndim != 2: raise ValueError("array must be 2-dimensional") if array.shape[1] != 3: raise ValueError( "length of the second dimension must equal " "the dimension of the graph") return _librootnumpy.fill_g2( ROOT.AsCObject(graph), array) else: raise TypeError( "hist must be an instance of ROOT.TGraph or ROOT.TGraph2D")
[ "noel.dawe@gmail.com" ]
noel.dawe@gmail.com
225faa5c992ef25e33ee5472cd08d2040d303a31
6733716dcdcacfcc739ae5c4af976db81ead852b
/ROOT/Project/functions/rootTree_rootHist/just_test/test4_auto.py
9611e7290189a404df65fa6a16ef108b1c744053
[]
no_license
StudyGroupPKU/fruit_team
45202a058d59057081670db97b9229ee720fa77e
9f9f673f5ce22ce6d25736871f3d7a5bd232c29d
refs/heads/master
2021-01-24T08:15:37.909327
2018-05-11T08:53:06
2018-05-11T08:53:06
122,975,404
0
5
null
2018-04-05T02:37:14
2018-02-26T13:41:24
Python
UTF-8
Python
false
false
4,051
py
IBin = -2.0 FBin = 2.0 NBins = 100 from ROOT import TFile, TH1F, TH1D, TTree import numpy filename = "/Users/leejunho/Desktop/git/python3Env/group_study/fruit_team/ROOT/Project/root_generator/tree/root2_tree.root" f = TFile(filename,"READ") outfile = TFile("outfile_please_modify_correspondingly_test4.root","RECREATE") if(filename[0]=="/"): filename = filename else: filename = os.getcwd() + "/" + filename # get the path included filename loca=len(filename) for i in range (1,len(filename)+1): # find the "/" location if(filename[-i] == "/"): loca = i-1 break FILENAME = filename.replace(filename[:-loca],"") # this is the shorten input filename, excluded path print(FILENAME) ############################################## Getting Name list and Dictionary DirTreeBranchNameList = {} SetBranchNameList = set() dirlist = f.GetListOfKeys() #dirlist.Print(); #print(dirlist.GetSize()) ITER = dirlist.MakeIterator() key = ITER.Next() #key.Print(); print(key.GetName()) while key: BranchNameList = [] tree = key.ReadObj() # print(tree.GetName()) branchlist = tree.GetListOfBranches() if(branchlist.IsEmpty()): continue ITER_b = branchlist.MakeIterator() key_b = ITER_b.Next() while key_b: BranchNameList.append(key_b.GetName()) SetBranchNameList.add(key_b.GetName()) # print(key_b.GetName()) key_b = ITER_b.Next() DirTreeBranchNameList[tree.GetName()] = BranchNameList key = ITER.Next() #print(DirTreeBranchNameList) # seperate branch of each tree #print(SetBranchNameList) # take advantage of no double element in set, define branch variables ############################################################# ################## prepare for SetBranchAddress for each tree. variables definiton for branch ########### DirNumpyArray_branch = {} for NumpyArray in SetBranchNameList: ## prepare for SetBranchAddress for each tree. variables definiton for branch # print(NumpyArray); print(type(NumpyArray)) a = numpy.array([0],'d') DirNumpyArray_branch[NumpyArray] = a #print(type(DirNumpyArray_branch.values()[1][0])) #print(DirNumpyArray_branch) ############################################################# ##########Need to get into tree again, for each tree, do SetBranchAddress(), Setting histograms for each branch!!! ## below :: dirlist = f.GetListOfKeys() ITER = dirlist.MakeIterator() key = ITER.Next() DirhistList = {} ##### histolist for each tree while key: histList = [] NamehistList = [] tree = key.ReadObj() for i in range(len(DirNumpyArray_branch)): tree.SetBranchAddress(DirNumpyArray_branch.keys()[i],DirNumpyArray_branch.values()[i]) #### SetBranchAddress of every branch for each tree branchlist = tree.GetListOfBranches() if(branchlist.IsEmpty()): continue ITER_b = branchlist.MakeIterator() key_b = ITER_b.Next() while key_b: ENTRY = tree.GetEntries() Namehist = FILENAME.replace(".root","") + "_" + tree.GetName() + "_" + key_b.GetName()+"_hist" NamehistList.append(Namehist) hist = TH1D(Namehist, Namehist, NBins, IBin, FBin) histList.append(hist) KEY_B = key_b.GetName() key_b = ITER_b.Next() for i in range(ENTRY): tree.GetEntry(i) for j in range(len(histList)): # histList[j].Fill(DirNumpyArray_branch.values()[j][0]) for k in range(len(histList)): if DirNumpyArray_branch.keys()[j] in histList[k].GetName(): histList[k].Fill(DirNumpyArray_branch.values()[j][0]) else : continue for i in range(len(histList)): histList[i].Write() # print("\n") DirhistList[tree.GetName()] = histList key = ITER.Next() #print(DirhistList) #print(DirNumpyArray_branch) ################################################################ outfile.Close()
[ "skyblue1293@naver.com" ]
skyblue1293@naver.com
d184e3a98bf8510e166e21b881fec6aa57d581ef
f5f4a0e2dcdcc5ee89bd86480d52390878fe612b
/utils/gap_configs/python/ips/interco/router.py
1b682cfc9733009a15860010d5c5c4490097348c
[ "Apache-2.0" ]
permissive
MIT-AI-Accelerator/gap_sdk
0751735b2b7d5a47be234e010eb9f72ebe8f81ef
6d255c70883cf157d76d006b2dbf55bc6974b21f
refs/heads/master
2023-09-05T21:23:00.379129
2021-11-03T18:37:37
2021-11-03T18:37:37
400,571,213
1
0
null
null
null
null
UTF-8
Python
false
false
1,669
py
# # Copyright (C) 2020 GreenWaves Technologies # # 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 gsystree as st class Router(st.Component): def __init__(self, parent, name, latency=0, bandwidth=4, remove_offset=0, config=None): super(Router, self).__init__(parent, name) self.add_property('mappings', {}) self.add_property('vp_component', 'interco.router_impl') self.add_property('latency', latency) self.add_property('bandwidth', bandwidth) self.add_property('remove_offset', remove_offset) if config is not None: self.add_properties(config) def add_mapping(self, name, base=None, size=None, remove_offset=None, add_offset=None, id=None): mapping = {} if base is not None: mapping['base'] = base if size is not None: mapping['size'] = size if remove_offset is not None: mapping['remove_offset'] = remove_offset if add_offset is not None: mapping['add_offset'] = add_offset if id is not None: mapping['id'] = id self.get_property('mappings')[name] = mapping
[ "yao.zhang@greenwaves-technologies.com" ]
yao.zhang@greenwaves-technologies.com
81adc41f2d08345806384aa1c2e0de279ea5afdf
b12e93c2dde41cc43d30fdd9ffbda968abb8e40e
/HearthStone/HearthStone/ext/card_compiler.py
f96e6a058a02c87bb2bb8155ab21d306050a5ab4
[ "MIT" ]
permissive
wkhunter/MiniGames
ec16a22dfc31e7a910466ffe65a3b4961e653724
910fddce17795c51c3e6a232bd98744865f984dc
refs/heads/master
2021-04-30T23:39:18.958443
2017-01-18T12:42:56
2017-01-18T12:42:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,795
py
#! /usr/bin/python # -*- encoding: utf-8 -*- """A simple compiler of card definition language, using PLY. Example: Minion 侏儒发明家 { # Define a new minion {% id = 0, name = '侏儒发明家', type = 0, CAH = [4, 2, 4], klass = 0 %} bc { d 1 } dr { d 1 } } """ import re from types import new_class from collections import namedtuple from ply.lex import lex from ply.yacc import yacc from ..game_entities.card import Minion, Spell, Weapon __author__ = 'fyabc' ######### # Lexer # ######### # Reserved words. ReservedWords = { 'Minion': ('CARD_TYPE', Minion), 'Spell': ('CARD_TYPE', Spell), 'Weapon': ('CARD_TYPE', Weapon), 'bc': ('SKILL', 'battle_cry'), 'battle_cry': ('SKILL', None), 'dr': ('SKILL', 'death_rattle'), 'death_rattle': ('SKILL', None), 'play': ('SKILL', None), 'def': ('DEF', None), } # Token list. tokens = ['DICT', 'LINE_CODE', 'NUM', 'ID', 'CARD_TYPE', 'SKILL', 'DEF'] # Literals list. literals = ['{', '}', '(', ')'] # Ignored characters. t_ignore = ' \t\r\n' # Token specifications (as Regex). # Token processing functions. def t_DICT(t): r"""\{%.*?%}""" t.value = eval('dict({})'.format(t.value[2:-2])) return t def t_LINE_CODE(t): r"""\$.*?\n""" t.value = t.value[1:].strip() return t def t_NUM(t): r"""\d+""" t.value = int(t.value) return t def t_ID(t): # r"""[a-zA-Z_][a-zA-Z_0-9]*""" r"""[^\W0-9]\w*""" token = ReservedWords.get(t.value, ('ID', None)) t.type = token[0] if token[1] is not None: t.value = token[1] return t def t_COMMENT(t): r"""\#.*""" pass # Error handler. def t_error(t): print('Bad character: {!r}'.format(t.value[0])) t.lexer.skip(1) # Build the lexer lexer = lex(reflags=re.UNICODE) ########## # Parser # ########## Action = namedtuple('Action', ['type', 'value']) def p_card(p): """card : CARD_TYPE ID '{' card_contents '}' | CARD_TYPE '{' card_contents '}' """ if len(p) == 5: cls_name = '' cls_dict = p[3] else: cls_name = p[2] cls_dict = p[4] p[0] = new_class(cls_name, (p[1],), {}, lambda ns: ns.update(cls_dict)) def p_card_contents(p): """card_contents : empty | card_contents content_entry """ if len(p) == 2: p[0] = {} else: p[0] = p[1] k, v = p[2] p[0][k] = v def p_content_entry(p): """content_entry : data_definition | skill_definition | func_definition """ p[0] = p[1] def p_data_definition(p): """data_definition : DICT""" p[0] = '_data', p[1] def p_func_definition(p): """func_definition : DEF ID '(' ')' '{' statements '}'""" exec('''\ def __func_do_not_override_this_name(self): {} pass '''.format('\n '.join(s.value for s in p[6])), {}, get_skill_locals()) p[0] = p[2], get_skill_locals().pop('__func_do_not_override_this_name') def p_statements(p): """statements : empty | statements statement """ if len(p) == 2: p[0] = [] else: p[0] = p[1] p[0].append(p[2]) def p_statement(p): """statement : LINE_CODE""" p[0] = Action('statement', p[1]) def p_skill_definition(p): """skill_definition : SKILL '{' actions '}'""" # Parse skills. if p[1] == 'battle_cry': skill_name = 'run_battle_cry' args_string = 'self, player_id, index' elif p[1] == 'death_rattle': skill_name = 'run_death_rattle' args_string = 'self, player_id, index' elif p[1] == 'play': skill_name = 'play' args_string = 'self, player_id, target' else: skill_name = p[1] args_string = 'self' result_statements = [] for action in p[3]: if action.type == 'statement': result_statements.append(action.value) else: # todo: add more actions pass exec('''\ def __skill_do_not_override_this_name({}): {} pass '''.format(args_string, '\n '.join(result_statements)), {}, get_skill_locals()) p[0] = skill_name, get_skill_locals().pop('__skill_do_not_override_this_name') def p_actions(p): """actions : empty | actions action """ if len(p) == 2: p[0] = [] else: p[0] = p[1] p[0].append(p[2]) def p_action(p): """action : statement""" p[0] = p[1] def p_empty(p): """empty :""" pass # Error rule for syntax errors def p_error(p): print("Syntax error in input {}!".format(p)) _default_locals = None def get_skill_locals(): global _default_locals if _default_locals is None: from HearthStone.ext import Minion, Spell, Weapon, set_description from HearthStone.ext.card_creator import m_blank, w_blank, m_summon from HearthStone.ext.card_creator import validator_minion, validator_enemy_minion from HearthStone.ext.card_creator import action_damage, action_destroy from HearthStone.ext import DrawCard, AddCardToHand from HearthStone.ext import Damage, SpellDamage, RestoreHealth, GetArmor from HearthStone.ext import RandomTargetDamage from HearthStone.ext import GameHandler, DeskHandler, FreezeOnDamage from HearthStone.ext import AddMinionToDesk from HearthStone.ext import TurnBegin from HearthStone.ext import MinionDeath from HearthStone.ext import constants from HearthStone.utils.debug_utils import verbose _default_locals = locals() return _default_locals # Build the parser parser = yacc() parse_card = parser.parse __all__ = [ 'lexer', 'parser', 'parse_card', ]
[ "fyabc@mail.ustc.edu.cn" ]
fyabc@mail.ustc.edu.cn
e7144c5ff44d0c156034aa78713708d4b8e205c2
aeeb89d02db3e617fc118605f5464fbfa6ba0d2a
/comp.py
2008ceba9b3de5e917142d1e88560354e219f930
[]
no_license
nadhiyap/begin
477f837e9ec3f06b9a2151c233dcf6281cf416c5
8d5b8b8ffe7e728b5191912b22737945df625c75
refs/heads/master
2021-04-18T22:07:07.674250
2018-04-15T07:37:19
2018-04-15T07:37:19
126,681,009
0
1
null
null
null
null
UTF-8
Python
false
false
158
py
n=int(input("enter the num")) b=1 for i in range(2,n): if n%i==0 and n!=2: b=0 if b==0: print("yes") else: print("no")
[ "noreply@github.com" ]
nadhiyap.noreply@github.com
11fc96ab7fc8484473a073ad362d9bb2a834d499
fc049ef8172ed2f63147612d89b4125fe865441c
/scrape/common.py
4ba416818b8fa9bf4233e789a9a5ed9f8be6436c
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
resistbot/people
a13b5f934cd6f498b349550f8978268648fb509b
a337c4b4d86bbb7b1911c0ec4cac0010c092867a
refs/heads/main
2023-02-22T11:37:23.600635
2021-01-16T22:38:32
2021-01-16T22:38:32
320,011,736
2
0
CC0-1.0
2020-12-09T16:16:44
2020-12-09T16:16:43
null
UTF-8
Python
false
false
3,409
py
import re import uuid from collections import OrderedDict from utils import get_jurisdiction_id, reformat_phone_number def clean_spaces(text): return re.sub(r"\s+", " ", text).strip() PARTIES = { "d": "Democratic", "r": "Republican", "dem": "Democratic", "rep": "Republican", "democrat": "Democratic", "republican": "Republican", } class ContactDetail: def __init__(self, note): self.note = note self.voice = None self.fax = None self.address = None def to_dict(self): d = {} for key in ("voice", "fax", "address"): val = getattr(self, key) if val: if key in ("voice", "fax"): val = reformat_phone_number(val) d[key] = val if d: d["note"] = self.note return d class Person: def __init__( self, name, *, state, party, district, chamber, image=None, email=None, given_name=None, family_name=None, suffix=None, ): self.name = clean_spaces(name) self.party = party self.district = str(district) self.chamber = chamber self.state = state self.given_name = given_name self.family_name = family_name self.suffix = suffix self.image = image self.email = email self.links = [] self.sources = [] self.capitol_office = ContactDetail("Capitol Office") self.district_office = ContactDetail("District Office") self.ids = {} self.extras = {} def to_dict(self): party = PARTIES.get(self.party.lower(), self.party) d = OrderedDict( { "id": f"ocd-person/{uuid.uuid4()}", "name": str(self.name), "party": [{"name": party}], "roles": [ { "district": self.district, "type": self.chamber, "jurisdiction": get_jurisdiction_id(self.state), } ], "links": self.links, "sources": self.sources, } ) if self.given_name: d["given_name"] = str(self.given_name) if self.family_name: d["family_name"] = str(self.family_name) if self.suffix: d["suffix"] = str(self.suffix) if self.image: d["image"] = str(self.image) if self.email: d["email"] = str(self.email) if self.ids: d["ids"] = self.ids if self.extras: d["extras"] = self.extras # contact details d["contact_details"] = [] if self.district_office.to_dict(): d["contact_details"].append(self.district_office.to_dict()) if self.capitol_office.to_dict(): d["contact_details"].append(self.capitol_office.to_dict()) return d def add_link(self, url, note=None): if note: self.links.append({"url": url, "note": note}) else: self.links.append({"url": url}) def add_source(self, url, note=None): if note: self.sources.append({"url": url, "note": note}) else: self.sources.append({"url": url})
[ "dev@jamesturk.net" ]
dev@jamesturk.net
d92a0924366fbeb47f4ab4a24bc9d72fd62f997a
13a6b6bc9327fa6128fb0c4687e0fbc2eb80fa5f
/poo_herencia.py
74ea9e372367bd4838e621418dbd4dd4f3f37855
[]
no_license
jkaalexkei/poo_python
1df5d06f30ab5199b0c8c529cfc3faf5b8d97a61
1be51074c6eb7818770c34ef4c09cae36f1fa0f9
refs/heads/master
2023-05-06T22:52:21.577667
2021-05-27T20:43:47
2021-05-27T20:43:47
370,861,909
0
0
null
null
null
null
UTF-8
Python
false
false
998
py
#LA HERENCIA: # Consiste en la reutilizacion de codigo en caso de crear objetos similares #caracteristicas en comun de los objetos #comportamientos en comun de los objetos #clase padre o superclase agrupa caracteristicas y comportamientos en comun class Vehiculos(): def __init__(self,marca,modelo): self.marca = marca self.modelo = modelo self.enmarcha = False self.acelera = False self.frena = False def arrancar(self): self.enmarcha = True def acelerar(self): self.acelera = True def frenar(self): self.frena = True def estado(self): print("marca: ", self.marca, "\n Modelo: ",self.modelo,"\n En Marcha: ", self.enmarcha, "\n Acelerando: ",self.acelera,"\n Frenando: ", self.frena) class Moto(Vehiculos):#Esta es la manera de heredar. Nombre de la clase y entre parentesis el nombre de la clase que va ha heredar pass miMoto = Moto("Honda","CBR") miMoto.estado()
[ "jkaalexkei@gmail.com" ]
jkaalexkei@gmail.com
c352f3ffcc5682a0ea7ce13f0b7df3c947e19472
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/eMRXLJLpaSTxZvsKN_20.py
492ac2498c5298a0703a9eaded759d7c74284e3b
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
585
py
def is_ladder_safe(ladder): index, spacing, counter, new_array = 0, [], 0, [] for i in ladder: if len(i) < 5: return False x = list(i) hashes = 0 for i in x: if i == "#": hashes +=1 spacing.append(hashes) for i in spacing: if i != spacing[0] and i != spacing[1]: return False if i == spacing[0] and index != 0: counter += 1 if i == spacing[1] and index != 1: new_array.append(counter) counter = 0 index +=1 for i in new_array: if i != new_array[0] or i > 2: return False return True
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
e4ca77f6d1e62a1fc5f27e605bacdd2ab5979bcd
60715c9ea4c66d861708531def532814eab781fd
/python-programming-workshop/pythondatastructures/console/print.py
acf395827d9e1beb9f219f3f5c828e7e7c2a5473
[]
no_license
bala4rtraining/python_programming
6ce64d035ef04486f5dc9572cb0975dd322fcb3e
99a5e6cf38448f5a01b310d5f7fa95493139b631
refs/heads/master
2023-09-03T00:10:26.272124
2021-11-01T08:20:52
2021-11-01T08:20:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
197
py
#Python program that uses print statement # Print a string literal. print("Hello") # Print two arguments. print("Hello", "there") # Print the value of a string variable. a = "Python" print(a)
[ "karthikkannan@gmail.com" ]
karthikkannan@gmail.com
21df4008c8aa3af325373649228fad8b24379e2f
c80f780b62c76a8a59100721ee5beb1333bc787d
/migrations/0002_tvprogram.py
826743db7d0c8788e369a76630469eff007b6cb2
[ "BSD-3-Clause" ]
permissive
alexisbellido/demo-app
73c5391287038102114dcc5a29399ae5cb31bc84
5f855a0fa7813ad830f420dc0e3f3a3d338cdb22
refs/heads/master
2020-04-16T03:58:19.869373
2019-01-12T00:52:43
2019-01-12T00:52:43
165,251,317
0
0
null
null
null
null
UTF-8
Python
false
false
606
py
# Generated by Django 2.1.5 on 2019-01-11 16:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('demo', '0001_initial'), ] operations = [ migrations.CreateModel( name='TVProgram', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('start_time', models.TimeField()), ('end_time', models.TimeField()), ], ), ]
[ "alexis@ventanazul.com" ]
alexis@ventanazul.com
6a8da79d9928bf4ded71044ae06701d5ce3ada3d
d6cf604d393a22fc5e071a0d045a4fadcaf128a6
/ABC/183/183_E.py
b8a7fda6b2a115a4e139f632014b51c19d30bfb9
[]
no_license
shikixyx/AtCoder
bb400dfafd3745c95720b9009881e07bf6b3c2b6
7e402fa82a96bc69ce04b9b7884cb9a9069568c7
refs/heads/master
2021-08-03T21:06:45.224547
2021-07-24T11:58:02
2021-07-24T11:58:02
229,020,968
0
0
null
null
null
null
UTF-8
Python
false
false
1,688
py
import sys sys.setrecursionlimit(10 ** 7) read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines MOD = 10 ** 9 + 7 def main(): H, W = map(int, input().split()) S = [list(input()) for _ in range(H)] T = [[[0, 0, 0, 0] for _ in range(W)] for _ in range(H)] T[0][0][0] = 1 T[0][0][1] = 1 T[0][0][2] = 1 T[0][0][3] = 1 for r in range(H): for c in range(W): if r == 0 and c == 0: continue if S[r][c] == "#": continue # 持ってきて足す # 1: 縦 # 2: 横 # 3: 斜め cnt = 0 # 上 if 0 <= (r - 1): cnt += T[r - 1][c][1] cnt %= MOD # 左 if 0 <= (c - 1): cnt += T[r][c - 1][2] cnt %= MOD # 左上 if 0 <= (r - 1) and 0 <= (c - 1): cnt += T[r - 1][c - 1][3] cnt %= MOD T[r][c][0] = cnt T[r][c][1] = cnt T[r][c][2] = cnt T[r][c][3] = cnt # 更新 # 上 if 0 <= (r - 1): T[r][c][1] += T[r - 1][c][1] # 左 if 0 <= (c - 1): T[r][c][2] += T[r][c - 1][2] # 左上 if 0 <= (r - 1) and 0 <= (c - 1): T[r][c][3] += T[r - 1][c - 1][3] T[r][c][1] %= MOD T[r][c][2] %= MOD T[r][c][3] %= MOD ans = T[H - 1][W - 1][0] % MOD print(ans) return if __name__ == "__main__": main()
[ "shiki.49.313@gmail.com" ]
shiki.49.313@gmail.com
2a21c9269596e7383db3bf89612249d1c740c959
776f52fd8e7c8504373d234b1f453ebfbb252ad9
/tests/test_lightcurve.py
794bd09d0af3fb2b2ea6a4aeee65a0a7912cf0d6
[ "GPL-3.0-only", "MIT" ]
permissive
jpdeleon/chronos
ae2481f504ef5e7b91d06ad73ba7e7bd7ede6fa6
330ab380040944689145a47ab060ee041491d54e
refs/heads/master
2023-02-05T07:35:38.883328
2023-01-31T09:50:13
2023-01-31T09:50:13
236,907,132
7
2
MIT
2020-06-26T02:12:25
2020-01-29T05:05:42
Jupyter Notebook
UTF-8
Python
false
false
2,710
py
# -*- coding: utf-8 -*- """ test methods of lightcurve module """ import pytest import lightkurve as lk import pandas as pd # from matplotlib.figure import Figure from matplotlib.axes import Axes from chronos import Tess, ShortCadence, LongCadence TOIID = 837 TICID = 460205581 SECTOR = 10 CUTOUT_SIZE = (15, 15) QUALITY_BITMASK = "default" def test_tess_methods(): t = Tess(toiid=TOIID) ax = t.plot_pdc_sap_comparison() assert isinstance(ax, Axes) lcs = t.get_lightcurves() assert isinstance(lcs, lk.LightCurve) def test_sc_pipeline(): sc = ShortCadence( ticid=TICID, sap_mask="pipeline", quality_bitmask=QUALITY_BITMASK ) _ = sc.get_lc() assert isinstance(sc.lc_pdcsap, lk.LightCurve) assert isinstance(sc.lc_sap, lk.LightCurve) def test_sc_square(): sc = ShortCadence( ticid=TICID, sap_mask="square", aper_radius=1, threshold_sigma=5, percentile=95, quality_bitmask=QUALITY_BITMASK, ) _ = sc.make_custom_lc() assert isinstance(sc.lc_custom, lk.LightCurve) # assert sc.sap_mask == "square" def test_sc_round(): sc = ShortCadence( ticid=TICID, sap_mask="round", aper_radius=1, quality_bitmask=QUALITY_BITMASK, ) _ = sc.make_custom_lc() assert isinstance(sc.lc_custom, lk.LightCurve) # assert sc.sap_mask == "round" def test_sc_threshold(): sc = ShortCadence( ticid=TICID, sap_mask="threshold", threshold_sigma=5, quality_bitmask=QUALITY_BITMASK, ) _ = sc.make_custom_lc() assert isinstance(sc.lc_custom, lk.LightCurve) # assert sc.sap_mask == "threshold" def test_sc_percentile(): sc = ShortCadence( ticid=TICID, sap_mask="percentile", percentile=90, quality_bitmask=QUALITY_BITMASK, ) _ = sc.make_custom_lc() assert isinstance(sc.lc_custom, lk.LightCurve) # assert sc.sap_mask == "percentile" def test_lc(): lc = LongCadence( ticid=TICID, sap_mask="square", aper_radius=1, cutout_size=CUTOUT_SIZE, quality_bitmask=QUALITY_BITMASK, ) _ = lc.make_custom_lc() assert isinstance(lc.lc_custom, lk.LightCurve) @pytest.mark.skip def test_sc_triceratops(): sc = ShortCadence(ticid=TICID, calc_fpp=True) df = sc.get_NEB_depths() # df = sc.get_fpp(flat=flat, plot=False) assert sc.triceratops is not None assert isinstance(df, pd.DataFrame) @pytest.mark.skip def test_lc_triceratops(): lc = LongCadence(ticid=TICID, calc_fpp=True) # df = sc.get_NEB_depths() # df = sc.get_fpp(flat=flat, plot=False) assert lc.triceratops is not None
[ "jpdeleon.bsap@gmail.com" ]
jpdeleon.bsap@gmail.com
aefd0927cb89585b4ba4e7058ed6d5f417ad28ba
9d90b664ebbd11a57ee6156c528081551b98055b
/wsgi/local_data/brython_programs/string_and_in1.py
8152f92fcc9ddaa939f87d1c34a58f2639fc7a70
[]
no_license
2014cdag21/c21
d4f85f91ba446feb6669a39903dda38c21e8b868
faf4b354f7d1d4abec79c683d7d02055c6bab489
refs/heads/master
2020-06-03T17:54:16.144118
2014-06-20T09:29:02
2014-06-20T09:29:02
19,724,479
0
1
null
null
null
null
UTF-8
Python
false
false
1,021
py
print(3 in [1, 2, 3]) print("3" in [1, 2, 3]) print("3" in [1, 2, "3"]) VOWELS = ['a', 'e', 'i', 'o', 'u'] def is_a_vowel(c): # check if c is a vowel lowercase_c = c.lower() if lowercase_c in VOWELS: # Return (BOOLEAN!) True if c is a vowel return True else: # c must not be a vowel; return (BOOLEAN!) False return False def only_vowels(phrase): # Takes a phrase, and returns a string of all the vowels # Initalize an empty string to hold all of the vowels vowel_string = '' for letter in phrase: # check if each letter is a vowel if is_a_vowel(letter): # If it's a vowel, we append the letter to the vowel string vowel_string = vowel_string + letter # if not a vowel, we don't care about it- so do nothing! return vowel_string # Code after a "return" doesn't print print("A line of code after the return!") print(only_vowels("Takes a phrase, and returns a string of all the vowels"))
[ "chiamingyen@gmail.com" ]
chiamingyen@gmail.com
371e15298db1711c8e04520f405b43a1b83d271f
b972faf032590c9722dc240c45fc60157d5a1bee
/1.py
39ce810ba84b1a8edf3516f6fd5ba14add3290e2
[]
no_license
kih1024/codingStudy
3a91b628bc301d1777d954595e93bf1f9246aca3
3e8a6fe86d3861613a85d3e75991f4bc7cd1e716
refs/heads/master
2022-12-09T04:58:55.264433
2020-09-22T07:29:44
2020-09-22T07:29:44
269,874,529
0
0
null
null
null
null
UTF-8
Python
false
false
612
py
def solution(inputString): answer = -1 arr = [False] * 4 count = [0] * 4 figure = [("(", ")"), ("{", "}"), ("[", "]"), ("<", ">")] for i in range(len(inputString)): for j in range(len(figure)): if inputString[i] == figure[j][0]: arr[j] = True break if inputString[i] == figure[j][1] and arr[j] == True: count[j] += 1 arr[j] = False break for i in arr: if i == True: return -1 answer = sum(count) return answer ans = solution(">_<") print(ans)
[ "rladlsgh654@naver.com" ]
rladlsgh654@naver.com
75b691bc34a70cb9c0af18d31d51db0d33f27155
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5751500831719424_1/Python/phire/1.py
2394b63ef96ce2f57ad745fc11ff7cc9c0530fec
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
1,244
py
#!/usr/bin/python2 # -*- coding: utf-8 -*- import sys import os def compress(s): r = [] c = '' count = 0 for x in s + " ": if x == c: count += 1 else: if count: r.append((c, count)) c = x count = 1 return r def test(arr, x): r = 0 for y in arr: r += abs(y - x) return r def match(arr): avg = float(sum(arr)) / len(arr) avg = int(avg) - 1 avg = max(1, avg) return min(test(arr, avg), test(arr, avg+1), test(arr, avg+2), test(arr, avg+3)) def main(): T = int(sys.stdin.readline()) for t in xrange(1, T+1): N = int(sys.stdin.readline()) a = [] for i in xrange(N): a.append(compress(sys.stdin.readline().strip())) signature = [x[0] for x in a[0]] good = True for r in a: if [x[0] for x in r] != signature: print "Case #" + str(t) + ": Fegla Won" good = False break if not good: continue ret = sum(match([x[i][1] for x in a]) for i in xrange(len(signature))) print "Case #" + str(t) + ": " + str(ret) if __name__ == '__main__': main()
[ "eewestman@gmail.com" ]
eewestman@gmail.com
230890be29b4a007df5076f82d5dff5baaac23ec
d3c673dcb339570eee580f2029d179e5c9dd2535
/venv/bin/pilconvert.py
a76f7dfb1c2173c16cf0168bd9db8b838f308478
[ "MIT" ]
permissive
zubeir-Abubakar/zgram
0304e9a21d4a7976d211a1f6692d7bb1bf5fba2b
33ed713f758ba86642ce8cb3b68a835bf07c29b5
refs/heads/master
2020-06-25T18:56:07.770251
2020-03-24T07:51:31
2020-03-24T07:51:31
199,394,542
1
0
MIT
2020-03-24T07:51:32
2019-07-29T06:44:57
Python
UTF-8
Python
false
false
2,394
py
#!/Users/saadiaomar/Documents/zgram/venv/bin/python3.6 # # The Python Imaging Library. # $Id$ # # convert image files # # History: # 0.1 96-04-20 fl Created # 0.2 96-10-04 fl Use draft mode when converting images # 0.3 96-12-30 fl Optimize output (PNG, JPEG) # 0.4 97-01-18 fl Made optimize an option (PNG, JPEG) # 0.5 98-12-30 fl Fixed -f option (from Anthony Baxter) # from __future__ import print_function import getopt import string import sys from PIL import Image def usage(): print("PIL Convert 0.5/1998-12-30 -- convert image files") print("Usage: pilconvert [option] infile outfile") print() print("Options:") print() print(" -c <format> convert to format (default is given by extension)") print() print(" -g convert to greyscale") print(" -p convert to palette image (using standard palette)") print(" -r convert to rgb") print() print(" -o optimize output (trade speed for size)") print(" -q <value> set compression quality (0-100, JPEG only)") print() print(" -f list supported file formats") sys.exit(1) if len(sys.argv) == 1: usage() try: opt, argv = getopt.getopt(sys.argv[1:], "c:dfgopq:r") except getopt.error as v: print(v) sys.exit(1) output_format = None convert = None options = {} for o, a in opt: if o == "-f": Image.init() id = sorted(Image.ID) print("Supported formats (* indicates output format):") for i in id: if i in Image.SAVE: print(i+"*", end=' ') else: print(i, end=' ') sys.exit(1) elif o == "-c": output_format = a if o == "-g": convert = "L" elif o == "-p": convert = "P" elif o == "-r": convert = "RGB" elif o == "-o": options["optimize"] = 1 elif o == "-q": options["quality"] = string.atoi(a) if len(argv) != 2: usage() try: im = Image.open(argv[0]) if convert and im.mode != convert: im.draft(convert, im.size) im = im.convert(convert) if output_format: im.save(argv[1], output_format, **options) else: im.save(argv[1], **options) except: print("cannot convert image", end=' ') print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))
[ "zubkayare@gmail.com" ]
zubkayare@gmail.com
3fc0d2ac19f0f38ceac5d69162a3f2264facf48a
8f5ce9cb41649cfcfe4026200c3ec48630cec7fa
/Interview/DSA/Strings/string_permutation.py
7bfd73a3b18fe04f1a829ffb7464afc5b43e1098
[]
no_license
karbekk/Python_Data_Structures
2d44ca0e12355b9b587eefa8a6beeba0ffcf3407
87e0ece2893d19ee92f6e72194cab6dcb4a3c4e7
refs/heads/master
2020-03-28T07:32:41.649465
2019-08-08T03:37:09
2019-08-08T03:37:09
147,908,721
0
0
null
2018-09-08T06:40:50
2018-09-08T06:40:50
null
UTF-8
Python
false
false
534
py
# def permute1(start, rest): # res = [] # if len(rest) <= 1: # res += [start + rest, rest + start] # else: # for i, c in enumerate(rest): # s = rest[:i] + rest[i+1:] # for perm in permute1(c, s): # res += [start + perm] # return res def permute2(s): res = [] if len(s) == 1: res = [s] else: for i, c in enumerate(s): for perm in permute2(s[:i] + s[i+1:]): res += perm return res print permute2('ab')
[ "kartikshrikanthegde@gmail.com" ]
kartikshrikanthegde@gmail.com
871c0c6dadbd1a53cd22800b987b3bebc634cb07
84263fd1391de079c5447359f1a7cd1abfb47126
/pythonprog/file_error.py
d221c20dd7b401b5b5f0bd1a8204da7831fea511
[]
no_license
Shilpa-T/Python
b19259b1be17182b1a9f86a42c0dd8134e749304
280fc16e9c7c0f38b33c59381457fcbbd42b8ae3
refs/heads/master
2020-04-19T00:13:38.706605
2019-01-27T18:57:52
2019-01-27T18:57:52
167,841,475
0
0
null
null
null
null
UTF-8
Python
false
false
267
py
""" file error when processing a file """ def printfile(name): try: open_file = open(name) except IOError: print "I canr find file",name else: for line in open_file: print line printfile(raw_input('enter file name'))
[ "shilpindu@gmail.com" ]
shilpindu@gmail.com
b44b3746f25797f37789e6aa68d7f851c31294f2
26f78ba56388765f2fe2dc8fa23ddea097209ec5
/Leetcode/二叉搜索树/124二叉树中的最大路径和.py
1b5552f812083ca1dbedefc848c2aa4e370f02c4
[]
no_license
johnkle/FunProgramming
3ef2ff32a1a378e1c780138ec9bab630c9ba83c7
a60e0d17a1e9f0bc1959d7a95737fc4a0362d735
refs/heads/master
2023-07-18T16:05:56.493458
2021-09-08T19:01:19
2021-09-08T19:01:19
402,861,226
0
0
null
null
null
null
UTF-8
Python
false
false
1,068
py
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int: self.res = float('-inf') #计算node的最大贡献值,并计算以node为根的最大路径和 def helper(node): if not node: return 0 leftGain = max(helper(node.left),0) rightGain = max(helper(node.right),0) path = node.val + leftGain + rightGain self.res = max(self.res,path) return node.val+max(leftGain,rightGain) helper(root) return self.res class Solution2: def maxPathSum(self, root): res = [] def dfs(node): if not node: return 0 leftgain = max(dfs(node.left),0) rightgain = max(dfs(node.right),0) res.append(node.val+leftgain+rightgain) return node.val + max(leftgain,rightgain) dfs(root) return max(res)
[ "605991742@qq.com" ]
605991742@qq.com
0ab6b8e2ed471f92d7c1b8b6dd7a90eca1c1cc92
9055b8f8b1ca2e357473179a5ff551f69541bd34
/Pandas/VISUALIZATION/2. bar.py
724ba66ecf640e22130e0f309412b788a6b2bc6e
[]
no_license
YanlinWang128/PyhonStudy
879c72cbdc1f467a7b4721561692e2deb6a665e9
6b9de9afcfa7ba0b4c55025ddcf87664b170c6e7
refs/heads/master
2020-03-30T18:42:11.520471
2018-11-09T08:38:29
2018-11-09T08:38:29
151,511,393
2
0
null
null
null
null
UTF-8
Python
false
false
402
py
# @Time : 2018/11/6 9:52 # @Author : Yanlin Wang # @Email : wangyl_a@163.com # @File : 2. bar.py from time import clock import pandas as pd import numpy as np import matplotlib.pyplot as plt start = clock() df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) df2.plot.bar() df2.plot.bar(stacked=True) plt.show() end = clock() print('time: {:.8f}s'.format(end - start))
[ "wangyl_a@163.com" ]
wangyl_a@163.com
0563cfeb4ab8f4e39101eaf8fb8c0873253a877e
51575eeda79a6e12c8839046721168e5cc5b6774
/experiments/classification/run_classification.py
cd3dd6ff195b4a873ad6fc3a305673ccec6afceb
[]
no_license
rfeinman/GNS-Modeling
59ad26efea4045c7dae98e98263d1193d53052b8
2c6b3400bfbb30f8f117042722fbcca2a8e9cb98
refs/heads/master
2023-06-08T21:22:27.914054
2021-07-08T14:17:56
2021-07-08T14:17:56
274,778,209
22
7
null
null
null
null
UTF-8
Python
false
false
2,108
py
import os import argparse import pickle import submitit from get_base_parses import get_base_parses from optimize_parses import optimize_parses from refit_parses_multi import refit_parses_multi def array_step(executor, func, jobs, inputs, errors): filt = lambda y : not errors[y] # submit jobs with executor.batch(): for x in filter(filt, inputs): jobs[x] = executor.submit(func, x) # wait for completion for x in filter(filt, inputs): try: jobs[x].result() except Exception as err: errors[x] = err return jobs, errors def save_errors(errors): with open("./logs/errors.pkl", "wb") as f: pickle.dump(errors, f) def main(args): if not os.path.exists('./results'): os.mkdir('./results') run_IDs = list(range(20)) errors = {r:None for r in run_IDs} jobs = {r:None for r in run_IDs} # initialize job executor executor = submitit.AutoExecutor(folder="./logs") executor.update_parameters( nodes=1, tasks_per_node=1, cpus_per_task=3, slurm_mem='20GB', slurm_gres='gpu:1', slurm_time='8:00:00', slurm_job_name='osc', slurm_array_parallelism=20 ) # execute 3-step process sequentially print('step 1: parsing') fn = lambda r : get_base_parses(r, reverse=args.reverse) jobs, errors = array_step(executor, fn, jobs, run_IDs, errors) save_errors(errors) print('step 2: optimization') fn = lambda r : optimize_parses(r, reverse=args.reverse) jobs, errors = array_step(executor, fn, jobs, run_IDs, errors) save_errors(errors) print('step 3: re-fitting') executor.update_parameters(slurm_time='48:00:00') # more compute time needed for this step fn = lambda r : refit_parses_multi(r, reverse=args.reverse) jobs, errors = array_step(executor, fn, jobs, run_IDs, errors) save_errors(errors) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--reverse', action='store_true') args = parser.parse_args() main(args)
[ "rfeinman16@gmail.com" ]
rfeinman16@gmail.com
88a23680fff66f1933d8f7c3cb647302f881af78
e736f413ce7a287c2d0d084c051a637b52b4bb8a
/tools/testing/python/hybrid_encrypt_cli.py
ab507b8a19fc2fbb43e6418bf9865c891ea27bad
[ "Apache-2.0" ]
permissive
anaghvj/tink
b9e7041307ce250ee9a8bfbcd0df10401718bc24
50150573bd1d6f05e818cc3706cfba3fe9ed490a
refs/heads/master
2022-06-17T10:11:19.413016
2020-04-30T23:04:57
2020-04-30T23:05:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,409
py
# 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. """A command-line utility for testing HybridEncrypt-primitives. It requires 4 arguments: keyset-file: name of the file with the keyset to be used for encrypting plaintext-file: name of the file that contains plaintext to be encrypted contextinfo-file: name of the file that contains contextinfo used for encryption output-file: name of the output file for the resulting encryptedtext """ from __future__ import absolute_import from __future__ import division # Placeholder for import for type annotations from __future__ import print_function # Special imports from absl import app from absl import flags from absl import logging import tink from tink import cleartext_keyset_handle from tink import hybrid FLAGS = flags.FLAGS def read_keyset(keyset_filename): """Load a keyset from a file. Args: keyset_filename: A path to a keyset file Returns: A KeysetHandle of the file's keyset Raises: TinkError: if the file is not valid IOError: if the file does not exist """ with open(keyset_filename, 'rb') as keyset_file: text = keyset_file.read() keyset = cleartext_keyset_handle.read(tink.BinaryKeysetReader(text)) return keyset def main(argv): if len(argv) != 5: raise app.UsageError( 'Expected 4 arguments, got %d.\n' 'Usage: %s keyset-file plaintext-file contextinfo-file output-file' % (len(argv) - 1, argv[0])) keyset_filename = argv[1] plaintext_filename = argv[2] contextinfo_filename = argv[3] output_filename = argv[4] logging.info( 'Using keyset from file %s to HybridEncrypt file %s using context ' 'info %s\n.The resulting output will be written to file %s', keyset_filename, plaintext_filename, contextinfo_filename, output_filename) # Initialise Tink try: hybrid.register() except tink.TinkError as e: logging.error('Error initialising Tink: %s', e) return 1 # Read the keyset into keyset_handle try: keyset_handle = read_keyset(keyset_filename) except tink.TinkError as e: logging.error('Error reading key: %s', e) return 1 # Get the primitive try: cipher = keyset_handle.primitive(hybrid.HybridEncrypt) except tink.TinkError as e: logging.error('Error creating primitive: %s', e) return 1 # Read the input files with open(plaintext_filename, 'rb') as plaintext_file: plaintext_data = plaintext_file.read() with open(contextinfo_filename, 'rb') as contextinfo_file: contextinfo_data = contextinfo_file.read() try: output_data = cipher.encrypt(plaintext_data, contextinfo_data) except tink.TinkError as e: logging.error('Error encrypting the input: %s', e) with open(output_filename, 'wb') as output_file: output_file.write(output_data) logging.info('All done.') if __name__ == '__main__': app.run(main)
[ "copybara-worker@google.com" ]
copybara-worker@google.com
4ded37c8c6cba07ee5ecc42d4954c609e42e7dbe
16c41ed01feddb99a0f6e34e7b4ef5f5d83a2848
/fb_post/views/reactions_to_post/tests/snapshots/snap_test_case_01.py
fb19d3e1492d1d6289233e88483d3eee290f9aaa
[]
no_license
karthik018/fb_post_learning
d6d9363aefd152886b4a466179c407135878dd25
bc45c937006c35e7ac09cf038e35f3a40f9c8cf8
refs/heads/master
2022-04-28T08:18:11.852236
2019-07-30T04:19:49
2019-07-30T04:19:49
197,510,185
0
0
null
2022-04-22T21:59:07
2019-07-18T04:14:35
Python
UTF-8
Python
false
false
1,086
py
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['TestCase01ReactionsToPostAPITestCase::test_case status'] = 200 snapshots['TestCase01ReactionsToPostAPITestCase::test_case body'] = { 'reactions': [ { 'profile_pic': '', 'reaction': 'LIKE', 'userid': 1, 'username': 'user1' }, { 'profile_pic': '', 'reaction': 'LIKE', 'userid': 3, 'username': 'user3' } ] } snapshots['TestCase01ReactionsToPostAPITestCase::test_case header_params'] = { 'content-language': [ 'Content-Language', 'en' ], 'content-length': [ '149', 'Content-Length' ], 'content-type': [ 'Content-Type', 'application/json' ], 'vary': [ 'Accept-Language, Origin, Cookie', 'Vary' ], 'x-frame-options': [ 'SAMEORIGIN', 'X-Frame-Options' ] }
[ "thinkcreative01karthik@gmail.com" ]
thinkcreative01karthik@gmail.com
cb7b7cdc8f0c56a1752b15e8b2c877d8149cd557
31b3ac7cc2f0cf43a4979e53d43002a9c5fb2038
/student attendence record1.py
0e932d0ad4fd5f0b398b54391dff536610e2a32e
[]
no_license
shreyansh-tyagi/leetcode-problem
ed31ada9608a1526efce6178b4fe3ee18da98902
f8679a7b639f874a52cf9081b84e7c7abff1d100
refs/heads/master
2023-08-26T13:50:27.769753
2021-10-29T17:39:41
2021-10-29T17:39:41
378,711,844
4
1
null
null
null
null
UTF-8
Python
false
false
1,076
py
''' You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. The student is eligible for an attendance award if they meet both of the following criteria: The student was absent ('A') for strictly fewer than 2 days total. The student was never late ('L') for 3 or more consecutive days. Return true if the student is eligible for an attendance award, or false otherwise. Example 1: Input: s = "PPALLP" Output: true Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days. Example 2: Input: s = "PPALLL" Output: false Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. Constraints: 1 <= s.length <= 1000 s[i] is either 'A', 'L', or 'P'. ''' class Solution: def checkRecord(self, s: str) -> bool: return not(s.count('A')>=2 or s.count('LLL')>0)
[ "sunnytyagi886@gmail.com" ]
sunnytyagi886@gmail.com
481c79a58047713cf46ebefb97f59c98252341c6
ee6fc02e8392ff780a4f0d1a5789776e4d0b6a29
/code/practice/abc/abc067/c.py
d99b0f3ace785fe8942c0c3286d0397a845e0657
[]
no_license
mollinaca/ac
e99bb5d5c07159b3ef98cd7067424fa2751c0256
2f40dd4333c2b39573b75b45b06ad52cf36d75c3
refs/heads/master
2020-12-22T11:02:13.269855
2020-09-18T01:02:29
2020-09-18T01:02:29
236,757,685
0
0
null
null
null
null
UTF-8
Python
false
false
220
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- N = int(input()) a = list(map(int,input().split())) total = sum(a) ans = float('inf') x = 0 for i in range(N-1): x += a[i] ans = min(abs(total-2*x),ans) print (ans)
[ "github@mail.watarinohibi.tokyo" ]
github@mail.watarinohibi.tokyo
535eb8c77ca7155e6ad95784ac8ecceb6a0f0798
95863ef4e8dfcce24dc7e565950728ba4e95d702
/7510_고급수학.py
8ff04a52d3aff48263a3f7671e0ee0c8a039dd83
[]
no_license
choijaehyeokk/BAEKJOON
ee007cd1f06724872fb2359930b26f32a0d646da
1fa57407a2d981ddd851c135e81c9861afa2dd81
refs/heads/master
2023-05-18T01:59:00.753233
2021-06-12T15:50:12
2021-06-12T15:50:12
329,467,059
0
0
null
null
null
null
UTF-8
Python
false
false
357
py
import sys, math test_case = int(sys.stdin.readline().rstrip()) for i in range(test_case): numbers = sorted(list(map(int, sys.stdin.readline().split()))) if numbers[2] == math.sqrt(pow(numbers[0],2) + pow(numbers[1],2)): print('Scenario #{0}:\nyes'.format(i+1)) else: print('Scenario #{0}:\nno'.format(i+1)) if i != test_case-1: print('')
[ "enlqn1010@gmail.com" ]
enlqn1010@gmail.com
fee3248f8aaf9dcb88181e2bab42d4549d71b8f1
5504f5488f9b2a07c600b556f6a14cb6f08c9b12
/recursion.py
71d1c26e17e3e2945f0f46e7c391fa6df06c3e25
[]
no_license
tt-n-walters/saturday-python
4087028e24ff1c3e80b705b5a49c381f02bc1d84
2ad53feb45b5a0e21b927bce25d52c8d2c679793
refs/heads/master
2020-12-26T21:46:18.240026
2020-04-18T17:40:23
2020-04-18T17:40:23
237,655,096
0
0
null
null
null
null
UTF-8
Python
false
false
552
py
from json import dumps moves = [] def move(origin, destination): # print("Moving disk from {} to {}".format(origin, destination)) moves.append([origin, destination]) def hanoi(num_of_disks, origin, temporary, destination): if num_of_disks == 0: pass else: hanoi(num_of_disks - 1, origin, destination, temporary) move(origin, destination) hanoi(num_of_disks - 1, temporary, origin, destination) hanoi(20, 0, 1, 2) print(len(moves)) with open("moves.json", "w") as file: file.write(dumps(moves))
[ "nico.walters@techtalents.es" ]
nico.walters@techtalents.es
18fb98673882c07988251ea832ca145505d88fab
53818da6c5a172fe8241465dcbbd34fba382820d
/PythonProgram/chapter_08/8-13.py
7be5c6f769b32133352770e2e829a2d8b1551e2b
[]
no_license
Lethons/PythonExercises
f4fec3bcbfea4c1d8bc29dfed5b770b6241ad93b
81d588ffecf543ec9de8c1209c7b26c3d6a423b3
refs/heads/master
2021-04-15T11:36:08.991028
2018-07-07T09:20:40
2018-07-07T09:20:40
126,686,044
0
0
null
null
null
null
UTF-8
Python
false
false
317
py
def build_profile(first, last, **user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('lethons', 'jiang', county='China', city='wuhu') print(user_profile)
[ "lethons@163.com" ]
lethons@163.com
4d1c6700d7a06ef2289c860c73dcb0131b8d2bce
46a62c499faaa64fe3cce2356c8b229e9c4c9c49
/taobao-sdk-python-standard/top/api/rest/TraderateListAddRequest.py
e953ad2c46b9045655a3494289e86978fe0d1523
[]
no_license
xjwangliang/learning-python
4ed40ff741051b28774585ef476ed59963eee579
da74bd7e466cd67565416b28429ed4c42e6a298f
refs/heads/master
2021-01-01T15:41:22.572679
2015-04-27T14:09:50
2015-04-27T14:09:50
5,881,815
0
0
null
null
null
null
UTF-8
Python
false
false
371
py
''' Created by auto_sdk on 2012-09-23 16:46:13 ''' from top.api.base import RestApi class TraderateListAddRequest(RestApi): def __init__(self,domain,port): RestApi.__init__(self,domain, port) self.anony = None self.content = None self.result = None self.role = None self.tid = None def getapiname(self): return 'taobao.traderate.list.add'
[ "shigushuyuan@gmail.com" ]
shigushuyuan@gmail.com
5cd97dcf42249f45f58866521562fd46459ffa15
e0045eec29aab56212c00f9293a21eb3b4b9fe53
/purchase/models/res_config_settings.py
fdb001621637fe5fcce1f7f621580d11a93ca173
[]
no_license
tamam001/ALWAFI_P1
a3a9268081b9befc668a5f51c29ce5119434cc21
402ea8687c607fbcb5ba762c2020ebc4ee98e705
refs/heads/master
2020-05-18T08:16:50.583264
2019-04-30T14:43:46
2019-04-30T14:43:46
184,268,686
0
0
null
null
null
null
UTF-8
Python
false
false
2,718
py
# -*- coding: utf-8 -*- # Part of ALWAFI. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' lock_confirmed_po = fields.Boolean("Lock Confirmed Orders", default=lambda self: self.env.user.company_id.po_lock == 'lock') po_lock = fields.Selection(related='company_id.po_lock', string="Purchase Order Modification *", readonly=False) po_order_approval = fields.Boolean("Purchase Order Approval", default=lambda self: self.env.user.company_id.po_double_validation == 'two_step') po_double_validation = fields.Selection(related='company_id.po_double_validation', string="Levels of Approvals *", readonly=False) po_double_validation_amount = fields.Monetary(related='company_id.po_double_validation_amount', string="Minimum Amount", currency_field='company_currency_id', readonly=False) company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string="Company Currency", readonly=True, help='Utility field to express amount currency') default_purchase_method = fields.Selection([ ('purchase', 'Ordered quantities'), ('receive', 'Delivered quantities'), ], string="Bill Control", default_model="product.template", help="This default value is applied to any new product created. " "This can be changed in the product detail form.", default="receive") group_warning_purchase = fields.Boolean("Purchase Warnings", implied_group='purchase.group_warning_purchase') group_manage_vendor_price = fields.Boolean("Vendor Pricelists", implied_group="purchase.group_manage_vendor_price") module_account_3way_match = fields.Boolean("3-way matching: purchases, receptions and bills") module_purchase_requisition = fields.Boolean("Purchase Agreements") po_lead = fields.Float(related='company_id.po_lead', readonly=False) use_po_lead = fields.Boolean( string="Security Lead Time for Purchase", oldname='default_new_po_lead', config_parameter='purchase.use_po_lead', help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.") @api.onchange('use_po_lead') def _onchange_use_po_lead(self): if not self.use_po_lead: self.po_lead = 0.0 def set_values(self): super(ResConfigSettings, self).set_values() self.po_lock = 'lock' if self.lock_confirmed_po else 'edit' self.po_double_validation = 'two_step' if self.po_order_approval else 'one_step'
[ "50145400+gilbertp7@users.noreply.github.com" ]
50145400+gilbertp7@users.noreply.github.com
fb7a9f1737d29effabc4820243aaec5e5ab2d8d2
323f58ecefddd602431eeb285b60ac81316b774a
/aioreactive/operators/pipe.py
55e16feeb7bc68f8ac14fa5e8e23066505346f21
[ "MIT" ]
permissive
tr11/aioreactive
aa9798ee5c2f98c0f5301111732e72093232ab8e
6219f9a0761f69fa1765129b990762affdf661c8
refs/heads/master
2021-01-25T13:58:51.892021
2018-03-02T22:01:23
2018-03-02T22:01:23
123,635,129
0
0
MIT
2018-03-02T21:56:46
2018-03-02T21:56:46
null
UTF-8
Python
false
false
249
py
from typing import Callable from aioreactive.core import AsyncObservable def pipe(source: AsyncObservable, *args: Callable[[AsyncObservable], AsyncObservable]) -> AsyncObservable: for op in args: source = op(source) return source
[ "dag@brattli.net" ]
dag@brattli.net
819501b2dc2d02295834d523fa81eb7da09526f6
9fd3e5f04baf33cdb913fb34d544c35d94d9d397
/tests/unit_tests/cx_core/integration/state_test.py
06c2c574c92d4f17a057320664a5f9f8f3d9a8f2
[ "MIT" ]
permissive
xaviml/controllerx
dfa56b7005af8212d074544eca8542d8d665b9e0
387e130b8489282bf3abb5e847ef16dfe88615c7
refs/heads/main
2023-09-01T11:19:25.754886
2023-04-18T16:13:13
2023-04-18T16:13:13
222,056,780
280
83
MIT
2023-07-17T11:37:12
2019-11-16T06:23:03
Python
UTF-8
Python
false
false
1,329
py
from typing import Optional import pytest from appdaemon.plugins.hass.hassapi import Hass from cx_core.controller import Controller from cx_core.integration.state import StateIntegration from pytest_mock.plugin import MockerFixture @pytest.mark.parametrize("attribute", ["sensor", "entity_id", None]) async def test_listen_changes( fake_controller: Controller, mocker: MockerFixture, attribute: Optional[str] ) -> None: kwargs = {} if attribute is not None: kwargs["attribute"] = attribute controller_id = "controller_id" state_event_mock = mocker.patch.object(Hass, "listen_state") state_integration = StateIntegration(fake_controller, kwargs) await state_integration.listen_changes(controller_id) state_event_mock.assert_called_once_with( fake_controller, state_integration.state_callback, controller_id, attribute=attribute, ) async def test_callback( fake_controller: Controller, mocker: MockerFixture, ) -> None: handle_action_patch = mocker.patch.object(fake_controller, "handle_action") state_integration = StateIntegration(fake_controller, {}) await state_integration.state_callback("test", None, "old_state", "new_state", {}) handle_action_patch.assert_called_once_with("new_state", previous_state="old_state")
[ "xaviml.93@gmail.com" ]
xaviml.93@gmail.com
89bd43e6ff9c99d7fc9f7dbcff19a209e1dcfe51
926621c29eb55046f9f59750db09bdb24ed3078e
/lib/googlecloudsdk/api_lib/compute/iam_base_classes.py
b7e49a6ddc6b2c345b3642ce1a29bd27f31dea8e
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
bopopescu/SDK
525d9b29fb2e901aa79697c9dcdf5ddd852859ab
e6d9aaee2456f706d1d86e8ec2a41d146e33550d
refs/heads/master
2022-11-22T18:24:13.464605
2016-05-18T16:53:30
2016-05-18T16:53:30
282,322,505
0
0
NOASSERTION
2020-07-24T21:52:25
2020-07-24T21:52:24
null
UTF-8
Python
false
false
7,876
py
# Copyright 2014 Google Inc. 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. """Internal base classes for abstracting away common logic.""" import abc from googlecloudsdk.api_lib.compute import base_classes from googlecloudsdk.api_lib.compute import request_helper from googlecloudsdk.api_lib.compute import utils from googlecloudsdk.command_lib.compute import flags from googlecloudsdk.core.iam import iam_util # TODO(user): Investigate sharing more code with BaseDescriber command. class BaseGetIamPolicy(base_classes.BaseCommand): """Base class for getting the Iam Policy for a resource.""" __metaclass__ = abc.ABCMeta @staticmethod def Args(parser, resource=None, list_command_path=None): BaseGetIamPolicy.AddArgs(parser, resource, list_command_path) @staticmethod def AddArgs(parser, resource=None, list_command_path=None): """Add required flags for set Iam policy.""" parser.add_argument( 'name', metavar='NAME', completion_resource=resource, list_command_path=list_command_path, help='The resources whose IAM policy to fetch.') @property def method(self): return 'GetIamPolicy' def ScopeRequest(self, ref, request): """Adds a zone or region to the request object if necessary.""" def SetResourceName(self, ref, request): """Adds a the name of the resource to the request object.""" resource_name = self.service.GetMethodConfig(self.method).ordered_params[-1] setattr(request, resource_name, ref.Name()) @abc.abstractmethod def CreateReference(self, args): pass def Run(self, args): ref = self.CreateReference(args) request_class = self.service.GetRequestType(self.method) request = request_class(project=self.project) self.ScopeRequest(ref, request) self.SetResourceName(ref, request) get_policy_request = (self.service, self.method, request) errors = [] objects = request_helper.MakeRequests( requests=[get_policy_request], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None) # Converting the objects genrator to a list triggers the # logic that actually populates the errors list. resources = list(objects) if errors: utils.RaiseToolException( errors, error_message='Could not fetch resource:') # TODO(user): determine how this output should look when empty. # GetIamPolicy always returns either an error or a valid policy. # If no policy has been set it returns a valid empty policy (just an etag.) # It is not possible to have multiple policies for one resource. return resources[0] def GetIamPolicyHelp(resource_name): return { 'brief': 'Get the IAM Policy for a Google Compute Engine {0}.'.format( resource_name), 'DESCRIPTION': """\ *{{command}}* displays the Iam Policy associated with a Google Compute Engine {0} in a project. """.format(resource_name)} class ZonalGetIamPolicy(BaseGetIamPolicy): """Base class for zonal iam_get_policy commands.""" @staticmethod def Args(parser, resource=None, command=None): BaseGetIamPolicy.AddArgs(parser, resource, command) flags.AddZoneFlag( parser, resource_type='resource', operation_type='fetch') def CreateReference(self, args): return self.CreateZonalReference(args.name, args.zone) def ScopeRequest(self, ref, request): request.zone = ref.zone class GlobalGetIamPolicy(BaseGetIamPolicy): """Base class for global iam_get_policy commands.""" def CreateReference(self, args): return self.CreateGlobalReference(args.name) class BaseSetIamPolicy(base_classes.BaseCommand): """Base class for setting the Iam Policy for a resource.""" __metaclass__ = abc.ABCMeta @staticmethod def Args(parser, resource=None, list_command_path=None): BaseSetIamPolicy.AddArgs(parser, resource, list_command_path) @staticmethod def AddArgs(parser, resource=None, list_command_path=None): """Add required flags for set Iam policy.""" parser.add_argument( 'name', metavar='NAME', completion_resource=resource, list_command_path=list_command_path, help='The resources whose IAM policy to set.') policy_file = parser.add_argument( 'policy_file', metavar='POLICY_FILE', help='Path to a local JSON formatted file contining a valid policy.') policy_file.detailed_help = """\ Path to a local JSON formatted file containing a valid policy. """ # TODO(user): fill in detailed help. @property def method(self): return 'SetIamPolicy' def ScopeRequest(self, ref, request): """Adds a zone or region to the request object if necessary.""" def SetResourceName(self, ref, request): """Adds a the name of the resource to the request object.""" resource_name = self.service.GetMethodConfig(self.method).ordered_params[-1] setattr(request, resource_name, ref.Name()) @abc.abstractmethod def CreateReference(self, args): pass def Run(self, args): policy = iam_util.ParseJsonPolicyFile( args.policy_file, self.messages.Policy) ref = self.CreateReference(args) request_class = self.service.GetRequestType(self.method) request = request_class(project=self.project) self.ScopeRequest(ref, request) self.SetResourceName(ref, request) request.policy = policy set_policy_request = (self.service, self.method, request) errors = [] objects = request_helper.MakeRequests( requests=[set_policy_request], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None) # Converting the objects genrator to a list triggers the # logic that actually populates the errors list. resources = list(objects) if errors: utils.RaiseToolException( errors, error_message='Could not fetch resource:') # TODO(user): determine how this output should look when empty. # SetIamPolicy always returns either an error or the newly set policy. # If the policy was just set to the empty policy it returns a valid empty # policy (just an etag.) # It is not possible to have multiple policies for one resource. return resources[0] def SetIamPolicyHelp(resource_name): return { 'brief': 'Set the IAM Policy for a Google Compute Engine {0}.'.format( resource_name), 'DESCRIPTION': """\ *{{command}}* sets the Iam Policy associated with a Google Compute Engine {0} in a project. """.format(resource_name)} class ZonalSetIamPolicy(BaseSetIamPolicy): """Base class for zonal iam_get_policy commands.""" @staticmethod def Args(parser, resource=None, command=None): BaseSetIamPolicy.AddArgs(parser, resource, command) flags.AddZoneFlag( parser, resource_type='resource', operation_type='fetch') def CreateReference(self, args): return self.CreateZonalReference(args.name, args.zone) def ScopeRequest(self, ref, request): request.zone = ref.zone class GlobalSetIamPolicy(BaseSetIamPolicy): """Base class for global iam_get_policy commands.""" def CreateReference(self, args): return self.CreateGlobalReference(args.name)
[ "richarddewalhalla@gmail.com" ]
richarddewalhalla@gmail.com
7d948050caa7731a5f9087f1a5117cfa2f185d2d
179d753991d2578750dc058f1b963f80eab787c8
/deeppavlov/dataset_readers/faq_reader.py
826fb4088302a5a406eee9f8c0b5d852d5247b17
[ "Apache-2.0", "Python-2.0" ]
permissive
yoptar/DeepPavlov
89ebd280db22e732bc942490e316d0588baf3803
3e7c8821db6d63b3aaac9abdfd8a478104371cb9
refs/heads/master
2020-04-07T12:54:56.279903
2019-01-09T09:23:44
2019-01-09T09:23:44
158,386,034
1
0
Apache-2.0
2019-01-09T08:03:45
2018-11-20T12:26:53
Python
UTF-8
Python
false
false
2,021
py
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT # # 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, softwaredata # 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 typing import Dict from pandas import read_csv from deeppavlov.core.data.dataset_reader import DatasetReader from deeppavlov.core.common.registry import register @register('faq_reader') class FaqDatasetReader(DatasetReader): """Reader for FAQ dataset""" def read(self, data_path: str = None, data_url: str = None, x_col_name: str = 'x', y_col_name: str = 'y') -> Dict: """ Read FAQ dataset from specified csv file or remote url Parameters: data_path: path to csv file of FAQ data_url: url to csv file of FAQ x_col_name: name of Question column in csv file y_col_name: name of Answer column in csv file Returns: A dictionary containing training, validation and test parts of the dataset obtainable via ``train``, ``valid`` and ``test`` keys. """ if data_url is not None: data = read_csv(data_url) elif data_path is not None: data = read_csv(data_path) else: raise ValueError("Please specify data_path or data_url parameter") x = data[x_col_name] y = data[y_col_name] train_xy_tuples = [(x[i].strip(), y[i].strip()) for i in range(len(x))] dataset = dict() dataset["train"] = train_xy_tuples dataset["valid"] = [] dataset["test"] = [] return dataset
[ "seliverstov.a@gmail.com" ]
seliverstov.a@gmail.com
19c2262d2a16a689f5af5323727a094140599163
000a4b227d970cdc6c8db192f4437698cb782721
/python/helpers/typeshed/stubs/psutil/psutil/_psbsd.pyi
6a4df8e9afc90de47c4ec9f2dae8b0a9e9a27ef9
[ "Apache-2.0", "MIT" ]
permissive
trinhanhngoc/intellij-community
2eb2f66a2a3a9456e7a0c5e7be1eaba03c38815d
1d4a962cfda308a73e0a7ef75186aaa4b15d1e17
refs/heads/master
2022-11-03T21:50:47.859675
2022-10-19T16:39:57
2022-10-19T23:25:35
205,765,945
1
0
Apache-2.0
2019-09-02T02:55:15
2019-09-02T02:55:15
null
UTF-8
Python
false
false
3,616
pyi
from contextlib import AbstractContextManager from typing import Any, NamedTuple from ._common import ( FREEBSD as FREEBSD, NETBSD as NETBSD, OPENBSD as OPENBSD, AccessDenied as AccessDenied, NoSuchProcess as NoSuchProcess, ZombieProcess as ZombieProcess, conn_tmap as conn_tmap, conn_to_ntuple as conn_to_ntuple, memoize as memoize, usage_percent as usage_percent, ) __extra__all__: Any PROC_STATUSES: Any TCP_STATUSES: Any PAGESIZE: Any AF_LINK: Any HAS_PER_CPU_TIMES: Any HAS_PROC_NUM_THREADS: Any HAS_PROC_OPEN_FILES: Any HAS_PROC_NUM_FDS: Any kinfo_proc_map: Any class svmem(NamedTuple): total: Any available: Any percent: Any used: Any free: Any active: Any inactive: Any buffers: Any cached: Any shared: Any wired: Any class scputimes(NamedTuple): user: Any nice: Any system: Any idle: Any irq: Any class pmem(NamedTuple): rss: Any vms: Any text: Any data: Any stack: Any pfullmem = pmem class pcputimes(NamedTuple): user: Any system: Any children_user: Any children_system: Any class pmmap_grouped(NamedTuple): path: Any rss: Any private: Any ref_count: Any shadow_count: Any class pmmap_ext(NamedTuple): addr: Any perms: Any path: Any rss: Any private: Any ref_count: Any shadow_count: Any class sdiskio(NamedTuple): read_count: Any write_count: Any read_bytes: Any write_bytes: Any read_time: Any write_time: Any busy_time: Any def virtual_memory(): ... def swap_memory(): ... def cpu_times(): ... def per_cpu_times(): ... def cpu_count_logical(): ... def cpu_count_physical(): ... def cpu_stats(): ... def disk_partitions(all: bool = ...): ... disk_usage: Any disk_io_counters: Any net_io_counters: Any net_if_addrs: Any def net_if_stats(): ... def net_connections(kind): ... def sensors_battery(): ... def sensors_temperatures(): ... def cpu_freq(): ... def boot_time(): ... def users(): ... def pids(): ... def pid_exists(pid): ... def is_zombie(pid): ... def wrap_exceptions(fun): ... def wrap_exceptions_procfs(inst) -> AbstractContextManager[None]: ... class Process: pid: Any def __init__(self, pid) -> None: ... def oneshot(self): ... def oneshot_enter(self) -> None: ... def oneshot_exit(self) -> None: ... def name(self): ... def exe(self): ... def cmdline(self): ... def environ(self): ... def terminal(self): ... def ppid(self): ... def uids(self): ... def gids(self): ... def cpu_times(self): ... def cpu_num(self): ... def memory_info(self): ... memory_full_info: Any def create_time(self): ... def num_threads(self): ... def num_ctx_switches(self): ... def threads(self): ... def connections(self, kind: str = ...): ... def wait(self, timeout: Any | None = ...): ... def nice_get(self): ... def nice_set(self, value): ... def status(self): ... def io_counters(self): ... def cwd(self): ... class nt_mmap_grouped(NamedTuple): path: Any rss: Any private: Any ref_count: Any shadow_count: Any class nt_mmap_ext(NamedTuple): addr: Any perms: Any path: Any rss: Any private: Any ref_count: Any shadow_count: Any def open_files(self): ... def num_fds(self): ... def cpu_affinity_get(self): ... def cpu_affinity_set(self, cpus) -> None: ... def memory_maps(self): ... def rlimit(self, resource, limits: Any | None = ...): ...
[ "intellij-monorepo-bot-no-reply@jetbrains.com" ]
intellij-monorepo-bot-no-reply@jetbrains.com
532452741987cd2de3241c15dc9dca0f6317a145
2cce44d102fc03cdfae7edbf81011c0f9fbbf92a
/_unittests/ut_notebooks/test_LONG_2A_notebook_1.py
3ece67c44bed8494b39381c71d83d2270845ffa5
[ "MIT" ]
permissive
AlexisEidelman/ensae_teaching_cs
ddbbccd0f732563d34ca6b6c2e389a8805dc60df
421d183c1fe6b5c3af9a5acedf1e3ad8f15b02d2
refs/heads/master
2021-01-20T08:29:33.182139
2017-08-03T15:06:49
2017-08-03T15:06:49
90,151,574
0
0
null
2017-05-03T13:23:37
2017-05-03T13:23:36
null
UTF-8
Python
false
false
2,080
py
""" @brief test log(time=170s) notebook test """ import sys import os import unittest try: import src except ImportError: path = os.path.normpath( os.path.abspath( os.path.join( os.path.split(__file__)[0], "..", ".."))) if path not in sys.path: sys.path.append(path) import src try: import pyquickhelper as skip_ except ImportError: path = os.path.normpath( os.path.abspath( os.path.join( os.path.split(__file__)[0], "..", "..", "..", "pyquickhelper", "src"))) if path not in sys.path: sys.path.append(path) import pyquickhelper as skip_ from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, add_missing_development_version class TestNotebookRunner2a_1 (unittest.TestCase): def setUp(self): fLOG("add missing dependencies", OutputPrint=__name__ == "__main__") add_missing_development_version( ["pyensae", "pymyinstall", "pymmails", "jyquickhelper"], __file__) def test_notebook_runner(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") from src.ensae_teaching_cs.automation.notebook_test_helper import ls_notebooks, execute_notebooks from src.ensae_teaching_cs.automation.notebook_test_helper import unittest_raise_exception_notebook, clean_function_1a temp = get_temp_folder(__file__, "temp_notebook2a_1") keepnote = ls_notebooks("td2a") assert len(keepnote) > 0 for k in keepnote: if "_1" in k: fLOG("*********", k) res = execute_notebooks( temp, keepnote, lambda i, n: "_1" in n, clean_function=clean_function_1a, fLOG=fLOG) unittest_raise_exception_notebook(res, fLOG) if __name__ == "__main__": unittest.main()
[ "xavier.dupre@ensae.fr" ]
xavier.dupre@ensae.fr
804d16fb294af1e2167aa7cbfe225cbea1e4a12b
8ecd899a8558ad0a644ecefa28faf93e0710f6fb
/ABC073/ABC073_C.py
d47da98fa19e5b10d9df3438b09a9f9619022de0
[]
no_license
yut-inoue/AtCoder_ABC
b93885547049788d452e86b442a4a9f5ee191b0e
3d2c4b2b2f8871c75f86040ad07ccd7736ad3dbe
refs/heads/master
2021-07-03T09:09:20.478613
2021-02-21T13:20:31
2021-02-21T13:20:31
227,140,718
0
0
null
null
null
null
UTF-8
Python
false
false
166
py
n=int(input()) dic={} for i in range(n): v=int(input()) dic[v]=dic.get(v,0)+1 count=0 for k in dic.keys(): if dic[k]%2!=0: count+=1 print(count)
[ "yinoue.1996787@gmail.com" ]
yinoue.1996787@gmail.com
67cc58df811c8468e0e57e2bfa9176ab97cede56
c5a7003de780b3b92f4dff39d5b9d8364bdd28a8
/HW5/python/q4.py
e9bd110e454a44955f8d3bc41d2cc414271c3393
[ "ICU" ]
permissive
rainmiku/16720-19Spring-Homework
961bb00e1ba46de7acc9884ec61c32389d5a6f4a
9ebc8e178bd2cca85ada52f0cb8ea5f22b47d57e
refs/heads/master
2020-06-18T15:29:02.340995
2019-04-22T03:57:41
2019-04-22T03:57:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,145
py
import numpy as np import skimage import skimage.measure import skimage.color import skimage.restoration import skimage.filters import skimage.morphology import skimage.segmentation # takes a color image # returns a list of bounding boxes and black_and_white image def findLetters(image): bboxes = [] bw = None # insert processing in here # one idea estimate noise -> denoise -> greyscale -> threshold -> morphology -> label -> skip small boxes # this can be 10 to 15 lines of code using skimage functions denoise_image = skimage.restoration.denoise_bilateral(image, multichannel = True) greyscale_image = skimage.color.rgb2gray(image) threshold = skimage.filters.threshold_otsu(greyscale_image) bw = greyscale_image < threshold bw = skimage.morphology.closing(bw, skimage.morphology.square(5)) label_image = skimage.morphology.label(bw, connectivity = 2) props = skimage.measure.regionprops(label_image) mean_size = sum([prop.area for prop in props]) / len(props) bboxes = [prop.bbox for prop in props if prop.area > mean_size / 3] bw = (~bw).astype(np.float) return bboxes, bw
[ "liuzihua0911@gmail.com" ]
liuzihua0911@gmail.com
677777ac7e27e0ebebf55cb1e8df3142b5de111f
f5dd918e0b98bfb72def6c6fc5d903d07f56a6ab
/3/task3.2_.py
cfaaa983b3a837f0f7d3d176ae0e56e287041a21
[]
no_license
kuzovkov/python_labs
c0c250a6a514202d798ee4176321279b87f1c318
503c01024461629f18ad9846b5ed9f57a7f74980
refs/heads/master
2021-01-11T03:41:17.510860
2016-10-19T21:17:02
2016-10-19T21:17:02
71,400,114
0
0
null
null
null
null
WINDOWS-1251
Python
false
false
1,455
py
#Кузовков Александр Владимирович import time import random n1=range(10000) n2=range(12000) list1=[] for i in n1: list1.append(random.randrange(1,50,1)) list2=[] for i in n2: list2.append(random.randrange(1,50,1)) cor1=tuple(list1) cor2=tuple(list2) #1 print "1 -for" #print list1 #print list2 start=time.clock() for item2 in list2: flag=False for item1 in list1: if item1==item2: flag=True if flag ==False: list1.append(item2) end=time.clock() #print list1 print 'Time: %s'%(end-start) #2 print "2 - in" list1=list(cor1) #print list1 #print list2 start=time.clock() for item2 in list2: if item2 not in list1: list1.append(item2) end=time.clock() #print list1 print 'Time: %s'%(end-start) #3 print "3 - dict" list1=list(cor1) #print list1 #print list2 d1=dict(zip(list1,range(len(list1)))) start=time.clock() for item2 in list2: if not d1.has_key(item2): list1.append(item2) end=time.clock() #print list1 print 'Time: %s'%(end-start) #4 print "4 - set" list1=list(cor1) #print list1 #print list2 set1=set(list1) start=time.clock() for item2 in list2: if item2 not in set1: list1.append(item2) end=time.clock() #print list1 print 'Time: %s'%(end-start)
[ "you@example.com" ]
you@example.com
28275d76fc7068091da1f1482abe349efcc37d25
fa7c302f7df6b1773b27de3b742d551bd54aa4e2
/test/test_full_project.py
e13c489a7f2a9a9010537ebe73affc9fb3c1d668
[]
no_license
cons3rt/cons3rt-python-sdk
d01b3b174c295491130fba0d76d046b16492e9f7
f0bcb295735ac55bbe47448fcbd95d2c7beb3ec0
refs/heads/master
2021-11-04T02:31:54.485541
2021-10-26T19:28:57
2021-10-26T19:28:57
241,673,562
0
0
null
null
null
null
UTF-8
Python
false
false
855
py
# coding: utf-8 """ CONS3RT Web API A CONS3RT ReSTful API # noqa: E501 The version of the OpenAPI document: 1.0.0 Contact: apiteam@swagger.io Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import openapi_client from openapi_client.models.full_project import FullProject # noqa: E501 from openapi_client.rest import ApiException class TestFullProject(unittest.TestCase): """FullProject unit test stubs""" def setUp(self): pass def tearDown(self): pass def testFullProject(self): """Test FullProject""" # FIXME: construct object with mandatory attributes with example values # model = openapi_client.models.full_project.FullProject() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "shaun.tarves@jackpinetech.com" ]
shaun.tarves@jackpinetech.com
cccda1d3bd2bf6bddebd293ef21833236a18e6eb
28c80b58099d467e1f54f798e91cd8d495de4a1c
/Hunter_1_1.py
1f9ef72e245d2449592068b4ad01b9570b5a296f
[]
no_license
Raagini539/programs
a01a17bcf5bec2ae5717beb877f1f7f55d6520f2
62767573a21ffd8e8d697eca42685e6fc2a96e0a
refs/heads/master
2020-04-15T22:12:05.095611
2019-06-12T13:33:43
2019-06-12T13:33:43
165,063,410
0
1
null
null
null
null
UTF-8
Python
false
false
314
py
#raagini n=int(input()) n1=list(map(int,input().split())) b=[] l=[0]*10 for i in range(0,len(n1)): l[n1[i]]+=1 a=max(l) for i in range(0,len(l)): if a==l[i]: b.append(i) if b==n1: print("unique") else: for i in range(0,len(b)): if i==len(b)-1: print(b[i]) else: print(b[i],end=' ')
[ "noreply@github.com" ]
Raagini539.noreply@github.com
f316f1b6031ef6cf0a93f051abf8f7a09d1dc624
4823d075d43af119dd65d7031f7611b269d8fab1
/servo_example.py
26e91c918e6761ffbdd05f41f1991eff78d6f518
[]
no_license
mpdevilleres/quadcopter
0588039659ca4b1c9b282ee1d02f044709608712
8c91e722b08be6f85a6ef6d5f2a7d58ed4cef828
refs/heads/master
2021-01-10T06:11:46.903986
2015-12-02T14:19:07
2015-12-02T14:19:07
47,264,603
0
0
null
null
null
null
UTF-8
Python
false
false
1,074
py
#!/usr/bin/python from pcA9685 import PWM import time # =========================================================================== # Example Code # =========================================================================== # Initialise the PWM device using the default address pwm = PWM(0x40) # Note if you'd like more debug output you can instead run: #pwm = PWM(0x40, debug=True) servoMin = 150 # Min pulse length out of 4096 servoMax = 600 # Max pulse length out of 4096 def setServoPulse(channel, pulse): pulseLength = 1000000 # 1,000,000 us per second pulseLength /= 60 # 60 Hz print "%d us per period" % pulseLength pulseLength /= 4096 # 12 bits of resolution print "%d us per bit" % pulseLength pulse *= 1000 pulse /= pulseLength pwm.setPWM(channel, 0, pulse) pwm.setPWMFreq(60) # Set frequency to 60 Hz while (True): # Change speed of continuous servo on channel O pwm.setPWM(0, 0, servoMin) time.sleep(1) pwm.setPWM(0, 0, servoMax) time.sleep(1)
[ "mpdevilleres@gmail.com" ]
mpdevilleres@gmail.com
251789d10b58bdaddd1fa7f2b3837d547323ace7
6879a8596df6f302c63966a2d27f6b4d11cc9b29
/abc/problems070/062/a.py
385a7ee280b6c28a6aea6253a7839fbc1054c3aa
[]
no_license
wkwkgg/atcoder
41b1e02b88bf7a8291b709306e54cb56cb93e52a
28a7d4084a4100236510c05a88e50aa0403ac7cd
refs/heads/master
2020-07-26T03:47:19.460049
2020-03-01T18:29:57
2020-03-01T18:29:57
208,523,188
0
0
null
null
null
null
UTF-8
Python
false
false
170
py
x, y = map(int, input().split()) A = [1,3,5,7,8,10,12] B = [4,6,9,11] ans = "No" if x in A and y in A: ans = "Yes" elif x in B and y in B: ans = "Yes" print(ans)
[ "yujin@komachi.live" ]
yujin@komachi.live