blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ffefe6ceb59eafedcd642ab41b9ad8076c236eb2 | fb46d031cf9e3135f6541b5ef0a4d3d58814236a | /django_blog/settings.py | 9d57fb3c0929ff5cee9eaf6a37c61b5aad429a15 | [] | no_license | SomePythonCode/django_blog | 3fc3b97a2febded04f43db8d31672039040ed428 | e9c6cfd1b735f28aeff389e2e3662571039293eb | refs/heads/master | 2020-06-04T19:22:02.964894 | 2019-06-16T07:59:41 | 2019-06-16T07:59:41 | 192,161,778 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,178 | py | """
Django settings for django_blog project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'b3bknz#8l@)v8y1q2)nd!seeo6bhc$vmi3v3=o*y!kbp6=jpt('
# 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',
'blog',
]
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 = 'django_blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'django_blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/
LANGUAGE_CODE = 'ru-ru'
TIME_ZONE = 'Asia/Krasnoyarsk'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
| [
"some_python_code@list.ru"
] | some_python_code@list.ru |
68cbd79a2e427805337cd0a75ec46e41e0885431 | d48a8150eeb659909475cf7fa724fe9abae091d9 | /test/test_perf.py | 757c1358cf3534e7d8685ce0811127ba6e8614d6 | [
"Apache-2.0"
] | permissive | zxch3n/priority_memory | aebccca857f90592cdcbe63b771dc1ab65e7bfc2 | 85c146732b37791f2d2961a1beddf5d3cea1c7ac | refs/heads/master | 2020-04-07T23:17:57.615376 | 2019-10-17T07:17:02 | 2019-10-17T07:17:02 | 158,806,615 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 938 | py | import numpy as np
import random
import time
from priority_memory import FastPriorReplayBuffer
def create_data(size=100000):
dat = np.arange(0, size)
p = [random.random() for _ in range(size)]
s = sum(p)
p = [_p / s for _p in p]
return dat, p
def test_np_sample():
size = 100000
n_iter = 100
batch_size = 320
dat, p = create_data(size)
start = time.time()
for i in range(n_iter):
np.random.choice(dat, batch_size, True, p)
np_used = time.time() - start
print(f'numpy.random.choice used {np_used}s')
buff = FastPriorReplayBuffer(buffer_size=size)
for _d, _p in zip(dat, p):
buff.append((_d,), _p)
start = time.time()
for i in range(n_iter):
buff.sample_with_weights(32)
buff_used = time.time() - start
print(f'priority_memory.FastPriorReplayBuffer used {buff_used}s')
assert np_used / 10 > buff_used
assert buff_used < 0.1
| [
"remch183@outlook.com"
] | remch183@outlook.com |
17ed0aa43187da97a738f2ea8e17c75edbe6facd | ae42a1dd35b46ef5554802edd01720bc5e17ad5a | /dvc/stage/monitor.py | 409eb533c027bdac2a138577f626d36f9fe28a78 | [
"Apache-2.0"
] | permissive | jankrepl/dvc | e1e1f4cda359315b36de809a8aceef253dbd52d6 | e0d90cdda1347dcfd142d90f407675d7c9f2f1ec | refs/heads/master | 2023-04-08T04:30:34.656723 | 2021-04-23T02:59:15 | 2021-04-23T02:59:15 | 360,839,184 | 5 | 0 | Apache-2.0 | 2021-04-23T09:57:13 | 2021-04-23T09:57:12 | null | UTF-8 | Python | false | false | 4,067 | py | import functools
import logging
import os
import subprocess
import threading
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, List
from dvc.repo.live import create_summary
from dvc.stage.decorators import relock_repo
from dvc.stage.exceptions import StageCmdFailedError
if TYPE_CHECKING:
from dvc.output import BaseOutput
from dvc.stage import Stage
logger = logging.getLogger(__name__)
class CheckpointKilledError(StageCmdFailedError):
pass
class LiveKilledError(StageCmdFailedError):
pass
@dataclass
class MonitorTask:
stage: "Stage"
execute: Callable
proc: subprocess.Popen
done: threading.Event = threading.Event()
killed: threading.Event = threading.Event()
@property
def name(self) -> str:
raise NotImplementedError
@property
def SIGNAL_FILE(self) -> str:
raise NotImplementedError
@property
def error_cls(self) -> type:
raise NotImplementedError
@property
def signal_path(self) -> str:
return os.path.join(self.stage.repo.tmp_dir, self.SIGNAL_FILE)
def after_run(self):
pass
class CheckpointTask(MonitorTask):
name = "checkpoint"
SIGNAL_FILE = "DVC_CHECKPOINT"
error_cls = CheckpointKilledError
def __init__(
self, stage: "Stage", callback_func: Callable, proc: subprocess.Popen
):
super().__init__(
stage,
functools.partial(
CheckpointTask._run_callback, stage, callback_func
),
proc,
)
@staticmethod
@relock_repo
def _run_callback(stage, callback_func):
stage.save(allow_missing=True)
stage.commit(allow_missing=True)
logger.debug("Running checkpoint callback for stage '%s'", stage)
callback_func()
class LiveTask(MonitorTask):
name = "live"
SIGNAL_FILE = "DVC_LIVE"
error_cls = LiveKilledError
def __init__(
self, stage: "Stage", out: "BaseOutput", proc: subprocess.Popen
):
super().__init__(stage, functools.partial(create_summary, out), proc)
def after_run(self):
# make sure summary is prepared for all the data
self.execute()
class Monitor:
AWAIT: float = 1.0
def __init__(self, tasks: List[MonitorTask]):
self.done = threading.Event()
self.tasks = tasks
self.monitor_thread = threading.Thread(
target=Monitor._loop, args=(self.tasks, self.done,),
)
def __enter__(self):
self.monitor_thread.start()
def __exit__(self, exc_type, exc_val, exc_tb):
self.done.set()
self.monitor_thread.join()
for t in self.tasks:
t.after_run()
@staticmethod
def kill(proc):
if os.name == "nt":
return Monitor._kill_nt(proc)
proc.terminate()
proc.wait()
@staticmethod
def _kill_nt(proc):
# windows stages are spawned with shell=True, proc is the shell process
# and not the actual stage process - we have to kill the entire tree
subprocess.call(["taskkill", "/F", "/T", "/PID", str(proc.pid)])
@staticmethod
def _loop(tasks: List[MonitorTask], done: threading.Event):
while True:
for task in tasks:
if os.path.exists(task.signal_path):
try:
task.execute()
except Exception: # pylint: disable=broad-except
logger.exception(
"Error running '%s' task, '%s' will be aborted",
task.name,
task.stage,
)
Monitor.kill(task.proc)
task.killed.set()
finally:
logger.debug(
"Removing signal file for '%s' task", task.name
)
os.remove(task.signal_path)
if done.wait(Monitor.AWAIT):
return
| [
"noreply@github.com"
] | jankrepl.noreply@github.com |
d4a25e44cc45a285b59b4bf76c8e49a8679a13f3 | 96dc42fc8be89e718db9bea158ab341071320efc | /setup.py | d72a29d60e0ab7aae54bf1cb910a0f32bb6e668a | [
"MIT"
] | permissive | verifiedpixel/pytineye | ce3e110d9635d0b6704f2aad7131bc717f8b307a | bb4676fe0e43281c1b9e51f944f74d1319588c3c | refs/heads/master | 2020-12-25T22:37:15.601951 | 2015-07-21T14:22:54 | 2015-07-21T14:22:54 | 39,281,306 | 0 | 0 | null | 2015-07-18T00:42:26 | 2015-07-18T00:42:25 | JavaScript | UTF-8 | Python | false | false | 777 | py | from setuptools import setup, find_packages
import sys, os
version = '1.0'
setup(name='pytineye',
version=version,
description="Python client for the TinEye Commercial API.",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='reverse image search',
author='Id\xc3\xa9e Inc.',
author_email='support@tineye.com',
url='https://api.tineye.com/',
license='MIT License',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'pycrypto', 'simplejson', 'urllib3'
],
entry_points="""
# -*- Entry points: -*-
""",
)
| [
"support@tineye.com"
] | support@tineye.com |
98ecdbfc8fd401271a92625f86f3b760770d1b20 | 5066d38ad1a808fb6e849780f259c29e58495af0 | /ville.py | dc13449cdfb6980690cda49e09caa4ac2a19f1a4 | [] | no_license | Khopa/pyglet-taxi | 301b1075f695727f6b598fe9dd08b6e08455433f | 6d94ec9ff2c53a24089cd7f008d8a7bf8bfb8b72 | refs/heads/master | 2016-08-12T19:24:27.208530 | 2016-02-07T13:59:01 | 2016-02-07T13:59:01 | 51,248,853 | 1 | 0 | null | null | null | null | ISO-8859-1 | Python | false | false | 8,884 | py | # -*- coding: cp1252 -*-
import pyglet
from pyglet.gl import *
from config import *
import random
from pieton import *
from client import *
import charge_ville
import time
import primitives as prims
import display_list as disp
ville = charge_ville.MATRICE_VILLE
class Ville:
"""
Classe pour representer la Ville
(Au moyen d'une matrice de Bloc)
"""
def __init__(self, game):
"""
Constructeur
"""
self.parent = game
self.destination_possible = []
self.matrice = []
for i,ligne in enumerate(ville):
self.matrice.append([])
for j,tile in enumerate(ligne):
if tile == 12: # repertorie les destinations possibles
self.destination_possible.append([i,j])
self.matrice[i].append(Bloc(i,j, tile, self))
def draw(self, cam_pos = None):
"""
Fonction d'affichage
"""
#temps_affichage = time.time()
# Optimisation de type Frustum Culling, on n'affiche que ce qui est a 'DISTANCE_VUE' de la camera
range_min_i = int(cam_pos[0]) - DISTANCE_VUE
if range_min_i < 0 : range_min_i = 0
range_min_j = int(cam_pos[1]) - DISTANCE_VUE
if range_min_j < 0 : range_min_j = 0
range_max_i = int(cam_pos[0]) + DISTANCE_VUE
if range_max_i > len(self.matrice) + 1 : range_max_i = len(self.matrice) + 1
range_max_j = int(cam_pos[1]) + DISTANCE_VUE
if range_max_j > len(self.matrice[0]) : range_max_j = len(self.matrice) + 1
for i in range(range_min_i, range_max_i):
for j in range(range_min_j, range_max_j):
try:
self.matrice[i][j].draw(cam_pos)
except IndexError:
pass
self.gerer_pietons(cam_pos)
#print float(temps_affichage) - float(time.time())
def gerer_pietons(self, cam_pos):
"""
--> I - les pietons situé dans les blocs distants de DISTANCE_GESTION_PIETON sont supprimés
--> II - les blocs situe à DISTANCE_GESTION_PIETON-1 bloc de distance genere des pietons aléatoirement
"""
# I
range_i_max = int(cam_pos[0]) + DISTANCE_GESTION_PIETON
range_i_min = int(cam_pos[0]) - DISTANCE_GESTION_PIETON
range_j_max = int(cam_pos[1]) + DISTANCE_GESTION_PIETON
range_j_min = int(cam_pos[1]) - DISTANCE_GESTION_PIETON
# Cas ligne i
for i in range(range_i_min, range_i_max):
for j in [range_j_max, range_j_min]:
try:
self.matrice[i][j].supprimerPietons()
except:
pass
# Cas ligne j
for j in range(range_j_min+1, range_j_max-1):
for i in [range_i_max, range_i_min]:
try:
self.matrice[i][j].supprimerPietons()
except:
pass
# II
range_i_max = int(cam_pos[0]) + DISTANCE_GESTION_PIETON -1
range_i_min = int(cam_pos[0]) - DISTANCE_GESTION_PIETON +1
range_j_max = int(cam_pos[1]) + DISTANCE_GESTION_PIETON -1
range_j_min = int(cam_pos[1]) - DISTANCE_GESTION_PIETON +1
# Cas ligne i
for i in range(range_i_min, range_i_max):
for j in [range_j_max, range_j_min]:
try:
self.matrice[i][j].genererPietons()
except IndexError:
pass
# Cas ligne j
for j in range(range_j_min+1, range_j_max-1):
for i in [range_i_max, range_i_min]:
try:
self.matrice[i][j].genererPietons()
except IndexError:
pass
def getMatrice(self):
"""
Accesseur de la matrice
"""
return self.matrice
class Bloc:
"""
Un Bloc peut être un morceau de route ou un batiment, en fonction de la valeur text
Un Bloc est un element de la matrice de Ville
"""
def __init__(self, i, j, text, ville):
"""
Constructeur
"""
self.parent = ville
self.listePieton = []
self.pietonGenere = False
self.i = i
self.j = j
hauteur = random.randint(2, 15)
if text == 1:
self.mur = True
self.RANDOM_ID = random.choice([disp.ID_IMMEUBLE, disp.ID_IMMEUBLE2, disp.ID_IMMEUBLE3, disp.ID_IMMEUBLE4])
elif text in [8,9,11]:
self.mur = True
else: self.mur = False
self.p0 = (i*TAILLE_BLOC,0,j*TAILLE_BLOC)
self.p1 = (i*TAILLE_BLOC+TAILLE_BLOC,0,j*TAILLE_BLOC)
self.p2 = (i*TAILLE_BLOC+TAILLE_BLOC,0,j*TAILLE_BLOC+TAILLE_BLOC)
self.position_centrale = [self.p0[0]+TAILLE_BLOC/2,0,self.p0[2]+TAILLE_BLOC/2]
self.texture = text
self.d_fleche = 0
self.sens_fleche = 0
def supprimerPietons(self):
self.listePieton = []
self.pietonGenere = False
def genererPietons(self):
if self.texture in [2,3] and not(self.pietonGenere): # dans les parcs et les places
nb_pieton = random.randint(0, MAX_PIETON)
for i in range(nb_pieton):
pos = [(random.randint(self.p0[0], self.p1[0])), 0, random.randint(self.p0[2], self.p2[2])]
if random.randint(0,10) == 5 and not(self.parent.parent.vehicule.transporte_un_client):
self.listePieton.append(Client(self.parent.parent, pos))
else:
self.listePieton.append(Pieton(self.parent.parent, pos))
self.pietonGenere = True
def draw(self, cam_pos):
"""
Fonction d'affichage
"""
if self.texture == 0:
disp.afficher_bloc(disp.ID_DESSIN_ROUTEZ, self.i, self.j)
elif self.texture == 1:
disp.afficher_bloc(disp.ID_PAVE, self.i, self.j)
# Gestion du cas ou la camera est dans le mur, alors, on l'affiche pas
if int(self.p0[0]/TAILLE_BLOC) == int(cam_pos[0]) and int(self.p0[2]/TAILLE_BLOC) == int(cam_pos[1]):
pass
else:
disp.afficher_bloc(self.RANDOM_ID, self.i, self.j)
elif self.texture == 2:
disp.afficher_bloc(disp.ID_PAVE, self.i, self.j)
elif self.texture == 3:
disp.afficher_bloc(disp.ID_PARC, self.i, self.j)
# Cette ligne ne peut etre stockee dans la display list, car l'affichage de l'arbre est dynamique (depend de l'angle de la camera)
prims.afficherRectangle(position = self.position_centrale,\
dimensions = TAILLE_ARBRE, angleY = self.parent.parent.vehicule.angle,
texture = TEXTURE_ARBRE)
elif self.texture == 4:
disp.afficher_bloc(disp.ID_PASSAGE, self.i, self.j)
elif self.texture == 5:
disp.afficher_bloc(disp.ID_DESSIN_ROUTEX, self.i, self.j)
elif self.texture == 6:
disp.afficher_bloc(disp.ID_DESSIN_ROUTES, self.i, self.j)
elif self.texture == 7:
disp.afficher_bloc(disp.ID_PARC, self.i, self.j)
elif self.texture == 8:
disp.afficher_bloc(disp.ID_HAIE, self.i, self.j)
elif self.texture == 9:
if int(self.p0[0]/TAILLE_BLOC) == int(cam_pos[0]) and int(self.p0[2]/TAILLE_BLOC) == int(cam_pos[1]):
pass
else:
disp.afficher_bloc(disp.ID_FALAISE, self.i, self.j)
elif self.texture == 10:
disp.afficher_bloc(disp.ID_DESSIN_ROUTES, self.i, self.j)
disp.afficher_bloc(disp.ID_TUNNEL, self.i, self.j)
elif self.texture == 11:
disp.afficher_bloc(disp.ID_MAISON, self.i, self.j)
elif self.texture == 12:
disp.afficher_bloc(disp.ID_PAVE, self.i, self.j)
if self.parent.parent.vehicule.destination_client == [self.i, self.j]:
prims.afficherRectangle(position = [self.position_centrale[0],self.d_fleche, self.position_centrale[2]],\
dimensions = TAILLE_ARBRE, angleY = self.parent.parent.vehicule.angle,
texture = FLECHE2)
if self.sens_fleche == 0:
self.d_fleche += 0.1
if self.d_fleche >= 1: self.sens_fleche = 1
else:
self.d_fleche -= 0.1
if self.d_fleche <= 0: self.sens_fleche = 0
for p in self.listePieton:
p.actualiser()
p.afficher()
| [
"clemguip@gmail.com"
] | clemguip@gmail.com |
fac5fe79bcaf507426aacb29775c1000b97f4c2a | e0f7a86b4b9f137223ae543c402cb32ae05c844c | /fire_project/catkin_ws/src/bb2_pkg/src/bb2_pkg/round_move_2.py | f0504f153c1b4541e69b4904ed4b620f0dd985f0 | [] | no_license | Hoon-it/R.O.S-project | f0334dee1dcb48af0614e0dacb1c02cf98f3ffd2 | 90b0187f40a32480ebb0f3bf075da381c3e19102 | refs/heads/main | 2023-08-06T01:45:12.995435 | 2021-09-15T02:56:37 | 2021-09-15T02:56:37 | 406,399,807 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,535 | py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import rospy
from geometry_msgs.msg import Twist
from bb2_pkg.MoveBB2_2 import MoveBB2
from bebop_msgs.msg import Ardrone3PilotingStateAttitudeChanged
'''
순찰모드 움직임 조절
'''
class RotateByAtti:
def __init__(self):
rospy.Subscriber('/bebop/states/ardrone3/PilotingState/AttitudeChanged', Ardrone3PilotingStateAttitudeChanged, self.get_atti)
self.atti_now = 0.0
def get_atti(self, msg):
self.atti_now = msg.yaw
def roundgo(self):
if not rospy.is_shutdown():
tw = Twist()
bb2 = MoveBB2()
print('순회 비행을 시작합니다.')
rospy.sleep(1)
#비밥의 실측결과 약 3m 높이에서 45도 각도로 카메라를 꺾었을 때 좌우 5.5m, 위아래 2m 정도의 범위를 촬영할 수 있었다. 따라서 좌우 이동은 5m 정도, 상하 이동은 3m 정도를 단위로 하여 움직여야 하겠다.
xjump = 0.5
yjump = 0.8
for i in range(5):
if i%2 == 0:
bb2.move_x(xjump, 0.01) # 초회 직진 코드 (직진 거리, 오차 허용값)
bb2.move_y(yjump, 0.01) # 2회차 직진
else:
bb2.move_x(-xjump, 0.01) # 초회 직진 코드 (직진 거리, 오차 허용값)
bb2.move_y(-yjump, 0.01) # 2회차 직진
xjump = xjump + xjump
yjump = yjump + yjump
bb2.stopping()
rospy.sleep(5)
print("순회 비행을 마쳤습니다.")
else:
exit()
| [
"noreply@github.com"
] | Hoon-it.noreply@github.com |
f3a72281b988ed19aa40e3091d6fc039eaed42ae | a528bc1896034a935fb56d306fb24e38a8af723a | /Module14/02_session/main.py | 219ce7c43ccf81a6719c9e7c8029f1b554d6d7a0 | [] | no_license | ivanovs85/python_basic | 6155054616812baa99ea511a19e750b0354ec5a9 | a077728050309a539adf5d30c5990d25320d0b4e | refs/heads/master | 2023-03-26T01:41:32.514642 | 2021-03-29T07:12:10 | 2021-03-29T07:12:10 | 351,993,012 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 459 | py | print("Введите первую точку")
x1 = float(input('X: '))
y1 = float(input('Y: '))
print("\nВведите вторую точку")
x2 = float(input('X: '))
y2 = float(input('Y: '))
x_diff = x1 - x2
y_diff = y1 - y2
print("Уравнение прямой, проходящей через эти точки:")
if x_diff == 0:
print('x =', x1, '+ 0 * y')
else:
k = y_diff / x_diff
b = y2 - k * x2
print("y = ", k, " * x + ", b)
| [
"ivanovs85@mail.ru"
] | ivanovs85@mail.ru |
80b399adcb8f004da5a60aa8896f04fb9a8055b9 | 10f45454e4f52146a20f88b18a61db8e1bb4d277 | /train.py | 897654d329a7244beaf6afe38737fdce79bcbf9f | [] | no_license | aamna2401/MSDS20018_Project_DLSpring2021 | 35cdf372b653492cfaafb752fbce32baaa55ec80 | decae21a81a55598426456136c5466fdae290f30 | refs/heads/main | 2023-07-02T10:18:56.077339 | 2021-08-09T11:28:06 | 2021-08-09T11:28:06 | 391,696,853 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,355 | py |
import os
import torch
import numpy as np
from tensorboardX import SummaryWriter
from dataloader.datagen import CustomDataLoader
from utils.evaluation import evaluate
import torch.backends.cudnn as cudnn
from configurations.train_config import cfg
from utils.image import Compose, ToTensor, RandomHorizontalFlip
from utils.ploting import plot_loss_and_lr, plot_map
from utils.training import train_one_epoch, write_tb, create_model
import argparse
def get_device(cuda=True):
cuda = cuda and torch.cuda.is_available()
print("PyTorch version: {}".format(torch.__version__))
if cuda:
print("CUDA version: {}\n".format(torch.version.cuda))
seed = np.random.randint(1, 10000)
print("Random Seed: ", seed)
np.random.seed(seed)
torch.manual_seed(seed)
if cuda:
torch.cuda.manual_seed(seed)
cudnn.benchmark = True
device = torch.device("cuda:0" if cuda else "cpu")
# device = torch.device('cpu')
print('Device: ', device)
return device
def main(model_save_dir):
# checkpoints path
cfg.model_save_dir = model_save_dir
device = get_device(cuda=True)
print("Using {} device training.".format(device.type))
if not os.path.exists(cfg.model_save_dir):
os.makedirs(cfg.model_save_dir)
# tensorboard writer
writer = SummaryWriter(os.path.join(cfg.model_save_dir, 'epoch_log'))
data_transform = {
"train": Compose([ToTensor(), RandomHorizontalFlip(cfg.train_horizon_flip_prob)]),
"val": Compose([ToTensor()])
}
if not os.path.exists(cfg.data_root_dir):
raise FileNotFoundError("dataset root dir not exist!")
# load train data set
train_data_set = CustomDataLoader(cfg.data_root_dir, 'train', data_transform["train"])
batch_size = cfg.batch_size
nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8])
print('Using {} dataloader workers'.format(nw))
train_data_loader = torch.utils.data.DataLoader(train_data_set,
batch_size=batch_size,
shuffle=True,
num_workers=nw,
collate_fn=train_data_set.collate_fn)
# load validation data set
val_data_set = CustomDataLoader(cfg.data_root_dir, 'val', data_transform["val"])
val_data_set_loader = torch.utils.data.DataLoader(val_data_set,
batch_size=batch_size,
shuffle=False,
num_workers=nw,
collate_fn=train_data_set.collate_fn)
# create model num_classes equal background + 80 classes
model = create_model(num_classes=cfg.num_class)
model.to(device)
# define optimizer
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=cfg.lr,
momentum=cfg.momentum, weight_decay=cfg.weight_decay)
# learning rate scheduler
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer,
step_size=cfg.lr_dec_step_size,
gamma=cfg.lr_gamma)
# train from pretrained weights
if cfg.resume != "":
checkpoint = torch.load(cfg.resume)
model.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])
cfg.start_epoch = checkpoint['epoch'] + 1
print("the training process from epoch{}...".format(cfg.start_epoch))
train_loss = []
learning_rate = []
train_mAP_list = []
val_mAP = []
best_mAP = 0
for epoch in range(cfg.start_epoch, cfg.num_epochs):
loss_dict, total_loss = train_one_epoch(model, optimizer, train_data_loader,
device, epoch, train_loss=train_loss, train_lr=learning_rate,
print_freq=1, warmup=False)
lr_scheduler.step()
print("------>Starting training data valid")
_, train_mAP = evaluate(model, train_data_loader, device=device, mAP_list=train_mAP_list)
print("------>Starting validation data valid")
_, mAP = evaluate(model, val_data_set_loader, device=device, mAP_list=val_mAP)
print('training mAp is {}'.format(train_mAP))
print('validation mAp is {}'.format(mAP))
print('best mAp is {}'.format(best_mAP))
board_info = {'lr': optimizer.param_groups[0]['lr'],
'train_mAP': train_mAP,
'val_mAP': mAP}
for k, v in loss_dict.items():
board_info[k] = v.item()
board_info['total loss'] = total_loss.item()
write_tb(writer, epoch, board_info)
if mAP > best_mAP:
best_mAP = mAP
# save weights
save_files = {
'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'lr_scheduler': lr_scheduler.state_dict(),
'epoch': epoch}
model_save_dir = cfg.model_save_dir
if not os.path.exists(model_save_dir):
os.makedirs(model_save_dir)
torch.save(save_files,
os.path.join(model_save_dir, "{}-model-{}-mAp-{}.pth".format(cfg.backbone, epoch, mAP)))
writer.close()
# plot loss and lr curve
if len(train_loss) != 0 and len(learning_rate) != 0:
plot_loss_and_lr(train_loss, learning_rate, cfg.model_save_dir)
# plot mAP curve
if len(val_mAP) != 0:
plot_map(val_mAP, cfg.model_save_dir)
if __name__ == "__main__":
# parser
parser = argparse.ArgumentParser(description='Faster R-CNN')
parser.add_argument("--model_save_dir", type=str, default="checkpoint",
help="path to directory where checkpoints will be stored.")
args = parser.parse_args()
print('Dump Path: ', args.model_save_dir)
version = torch.version.__version__[:5]
print('torch version is {}'.format(version))
main(args.model_save_dir)
| [
"aamnakhan2401@gmail.com"
] | aamnakhan2401@gmail.com |
4b287952beac2cadefbb2669620d99cd237315f7 | c553e412ab1e74893b6ac51c0758d0bc99ae5358 | /Backup/picam_cali_12042054.py | e57b0693078e5edd27fff1200e1d0840901538f8 | [] | no_license | gaeSeung1/jansen2 | fcde060c34c4a52aaf63dfaad5f37c5fae44c402 | 7506dd6eeb38d0a584e65a07dbefe05fd0ce2772 | refs/heads/master | 2023-02-05T19:06:08.767499 | 2020-12-22T12:52:30 | 2020-12-22T12:52:30 | 316,783,463 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,472 | py | PORT = 6000
host = 'gaeseung.local'
#host = 'localhost'
# 0 : main, 1 : main+streaming
switch = 0
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import numpy as np
import ar_markers
from Time import Time
import threading
from queue import Queue
from http.client import HTTPConnection
import RPi.GPIO as GPIO
from decision import *
#motor init
GPIO.setmode(GPIO.BCM)
motor11=23
motor12=24
motor21=27
motor22=17
pwm1=25
pwm2=22
GPIO.setup(motor11,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(motor12,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(motor21,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(motor22,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(pwm1,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(pwm2,GPIO.OUT,initial=GPIO.LOW)
p1=GPIO.PWM(pwm1,100)
p2=GPIO.PWM(pwm2,100)
p1.start(0)
p2.start(0)
# ultrasonic init
GPIO_TRIGGER = 14
GPIO_ECHO = 15
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO,GPIO.IN)
GPIO.output(GPIO_TRIGGER, False)
#motor action init
MOTOR_SPEEDS = {
"q": (0, 1), "w": (1, 1), "e": (1, 0),
"a": (-1, 1), "s": (0, 0), "d": (1, -1),
"z": (0, -1), "x": (-1, -1), "c": (-1, 0),
}
# Information of picam calibration
DIM=(320, 240)
K=np.array([[132.13704662178574, 0.0, 166.0686598959872], [0.0, 133.16643727381444, 123.27563566060049], [0.0, 0.0, 1.0]])
D=np.array([[-0.07388057626177186], [0.037920859225125836], [-0.030619490583373123], [0.006819370459857302]])
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (320, 240)
#flip
camera.vflip = True
camera.hflip = True
#shutterspeed
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=camera.resolution)
# allow the camera to warmup
time.sleep(0.1)
def captured(img):
cv2.imwrite(time.strftime('%m%d%H%M%S')+'.jpg', img)
def cascade(img):
face_cascade = cv2.CascadeClassifier('./cascade.xml')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
objs = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in objs:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
return objs
def undistort(img):
map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, DIM, cv2.CV_16SC2)
img = cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
return img
def UploadNumpy(img):
# socket HTTPConnection
conn = HTTPConnection(f"{host}:{PORT}")
result, img = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), 90])
if not result:
raise Exception('Image encode error')
conn.request('POST', '/', img.tobytes(), {
"X-Client2Server" : "123"
})
res = conn.getresponse()
def motor(action, m):
if action == 's':
direction = 'stop'
speed = 0
elif action == 'q':
direction = 'left'
speed = 50
elif action == 'e':
direction = 'right'
speed = 50
elif action == 'a':
direction = 'spin left'
speed = 70
elif action == 'd':
direction = 'spin right'
speed = 70
elif action == 'w':
direction = 'forward'
speed = 50
elif action == 'x':
direction = 'backward'
speed = 40
pw1 = min(speed * MOTOR_SPEEDS[action][0], 100)
pw2 = min(speed * MOTOR_SPEEDS[action][1], 100)
if pw1>0:
GPIO.output(motor11,GPIO.HIGH)
GPIO.output(motor12,GPIO.LOW)
elif pw1<0:
GPIO.output(motor11,GPIO.LOW)
GPIO.output(motor12,GPIO.HIGH)
else:
GPIO.output(motor11,GPIO.LOW)
GPIO.output(motor12,GPIO.LOW)
if pw2>0:
GPIO.output(motor21,GPIO.HIGH)
GPIO.output(motor22,GPIO.LOW)
elif pw2<0:
GPIO.output(motor21,GPIO.LOW)
GPIO.output(motor22,GPIO.HIGH)
else:
GPIO.output(motor21,GPIO.LOW)
GPIO.output(motor22,GPIO.LOW)
p1.ChangeDutyCycle(abs(pw1))
p2.ChangeDutyCycle(abs(pw2))
#print(pw1,pw2)
return direction
def ultrasonic():
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
timeOut = start
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
if time.time()-timeOut > 0.012:
return -1
while GPIO.input(GPIO_ECHO)==1:
if time.time()-start > 0.012:
return -1
stop = time.time()
elapsed = stop-start
distance = (elapsed * 34300)/2
return distance
def main(q):
#for capture every second
checktimeBefore = int(time.strftime('%S'))
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
image = frame.array
#undistort
undistorted_image = undistort(image)
#--------------motor control--------------
#decision (action, round(m,4), forward, left_line, right_line, center, direction)
masked_image=select_white(undistorted_image,160)
result=set_path3(masked_image)
#line marker
line_left = []
line_right = []
for j in range(result[2]):
#left
left_coord = (result[5]+1-result[4][j], 239-j)
line_left.append(left_coord)
undistorted_image = cv2.line(undistorted_image, left_coord, left_coord,(0,255,0), 4)
#right
right_coord = (+result[5]+1+result[3][j], 239-j)
line_right.append(right_coord)
undistorted_image = cv2.line(undistorted_image, right_coord, right_coord,(0,255,0), 4)
#slope
try:
undistorted_image = cv2.line(undistorted_image, result[6][0], result[6][1],(0,0,255), 4)
except:
pass
#straight
if result[0] == 'w' and line_left != [] and line_right != []:
straight_factor = 30
if line_left[0][0] > straight_factor:
result_direction = 'e'
elif line_right[0][0] < 320-straight_factor:
result_direction = 'q'
else:
result_direction = result[0]
print(line_left[0][0])
print(line_right[0][0])
else:
result_direction = result[0]
#motor ON!
direction = motor(result_direction, result[1])
#----------------------------
#ultrasonic
ultra = ultrasonic()
if ultra > 0 and ultra < 12:
#print('stop')
direction = motor('s',0)
print(ultra)
#cascade
# cas = len(cascade(undistorted_image))
# if cas != 0:
# direction = motor('s')
#AR marker
markers = ar_markers.detect_markers(undistorted_image)
for marker in markers:
if marker.id == 114:
direction = motor('q',result[1])
elif marker.id == 922:
direction = motor('e',result[1])
elif marker.id == 2537:
direction = motor('s',0)
marker.highlite_marker(undistorted_image)
#----------------------------
#putText
try:
#slope
cv2.putText(undistorted_image,'m = '+str(result[1]), (10,20),cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 1)
#direction
cv2.putText(undistorted_image, direction, (10,40),cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 1)
except:
pass
#----------------------------
# show the frame
cv2.imshow("Frame", undistorted_image)
key = cv2.waitKey(1) & 0xFF
rawCapture.truncate(0)
#Threading
if switch == 1:
evt = threading.Event()
qdata = undistorted_image
q.put((qdata, evt))
# q : break, tap : capture
if key == ord("q"):
break
elif key == ord("\t"):
captured(undistorted_image)
def streaming(q):
while True:
qdata, evt = q.get()
UploadNumpy(qdata)
evt.set()
q.task_done()
if __name__ == "__main__":
q = Queue()
thread_one = threading.Thread(target=main, args=(q,))
thread_two = threading.Thread(target=streaming, args=(q,))
thread_two.daemon = True
thread_one.start()
if switch == 1:
thread_two.start()
q.join()
| [
"job5284@naver.com"
] | job5284@naver.com |
8005bce0876984cdabe37494ddb0f6fb34b778a6 | 13221b03de6a112acf095362dc6f8330268e5e0f | /week1/py/test02.py~ | 4d32070115c3d9ab0b7923cb9f56ff592f3bc3d9 | [] | no_license | daguniko/nlp100 | 0f47f5be1525584281cfaa1aae398da9cbae4c12 | 9f31f37a4faf160178a2fb16458b34671ca4851a | refs/heads/master | 2020-12-24T14:56:32.966406 | 2015-02-02T09:34:38 | 2015-02-02T09:34:38 | 30,180,477 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 323 | #! /usr/bin/python
# -*-coding:utf-8-*-
#(2) タブ1文字につきスペース1文字に置換したもの.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ.
import sys
#! /bin/sh
f = open(u'../data/address.txt').readlines()
for line in f:
print line.expandtabs(1)
| [
"dasi_nikorasu@yahoo.co.jp"
] | dasi_nikorasu@yahoo.co.jp | |
749ffb65bc195c4b6665504919384f99aef6c288 | 1475e0769c7f9c0c4ede19f7686ed8ef219e763d | /03-front-e-back/04-front-e-back-com-delete-via-rest-js-e-python/back-end/config.py | ad3508b13bb706d07d56325eb3e70af75d87cd96 | [] | no_license | hvescovi/programar2020 | ea73efd6438239e77b70633935d0b4a32e5dcdf6 | eab13efd4329505d4354c86de55a305f42461832 | refs/heads/master | 2023-05-15T01:17:20.773602 | 2023-05-04T00:14:04 | 2023-05-04T00:14:04 | 239,891,090 | 3 | 10 | null | 2023-05-04T00:14:49 | 2020-02-12T00:07:26 | Java | UTF-8 | Python | false | false | 534 | py | # importações
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import os
from flask_cors import CORS # permitir back receber json do front
# flask
app = Flask(__name__)
CORS(app) # aplicar o cross domain
# sqlalchemy com sqlite
path = os.path.dirname(os.path.abspath(__file__)) # sugestao do Kaue
arquivobd = os.path.join(path, 'pessoas.db')
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///"+arquivobd
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # remover warnings
db = SQLAlchemy(app)
| [
"hvescovi@gmail.com"
] | hvescovi@gmail.com |
b40f6a025d6b36aaf79432fb1f9cef087cb3f1ce | 8c25c2b9028ff4441d60e27f339d9deb3bb0a121 | /config.py | c65f1978a00a7071a00cacbdcc69842ccc55d59f | [] | no_license | Abott1222/playerlist-generator | f01533cb4cb6d62ae501193b24a168a1a3af0d93 | ca153ab13d071811e8e4354265fe09078cc2cff9 | refs/heads/master | 2022-08-31T11:09:29.907399 | 2020-05-30T00:13:51 | 2020-05-30T00:13:51 | 264,851,743 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 339 | py | import os
SECRET_KEY = os.urandom(32)
# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))
# Enable debug mode.
DEBUG = True
# Connect to the database
# TODO IMPLEMENT DATABASE URL
SQLALCHEMY_DATABASE_URI = 'postgres://alexanderbott@localhost:5432/fyyur'
SQLALCHEMY_TRACK_MODIFICATIONS = False | [
"alexanderbott@MacBook-Pro.local"
] | alexanderbott@MacBook-Pro.local |
c5d68ec1c074501759d2718d706d67f96e5c5e76 | 6685645ec5f2a5b14106535f0537058b60576ebe | /polls/views.py | a2a076fac0abcaae467252409429b54bc4b15629 | [] | no_license | katmutua/rapidpro-smartmin | 3925026849bc5a9596c3ecdff4acc7850fd4b779 | 3f2cccce6926ab28c4bee6c532c2655949bcb55c | refs/heads/master | 2021-01-15T09:15:29.039955 | 2015-08-09T13:17:07 | 2015-08-09T13:17:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 620 | py | from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([p.question_text for p in latest_question_list])
return HttpResponse(output)
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
| [
"jkm.mutua@gmail.com"
] | jkm.mutua@gmail.com |
cdc34bae78d5e489d64543df34eba6b0d6084b0a | 32b523154768eca53699a6cbd003eea7eade46cf | /fabfile.py | 07dd4d9ffad5d024e02858b3543acf5ebc781f60 | [] | no_license | amillergis/WorldCup | fb02198185b0b443efcc07742e3192f6cf9cd2ea | 01ffb7029f1039d71a39476d854121f4675abbeb | refs/heads/master | 2016-09-05T22:26:53.626493 | 2014-06-18T16:28:51 | 2014-06-18T16:28:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | true | false | 440 | py | from fabric.api import local,lcd
def prepare_deployment(branch_name):
local('python manage.py test worldcuppool')
local('git add -p && git commit')
local('git checkout master && git merge ' + branch_name)
def deploy():
with lcd('path/to/my/prod/area/'):
local('git pull /my/path/to/dev/area/')
local('python manage.py migrate worldcuppool')
local('python manage.py test worldcuppool')
local('/my/command/to/restart/webserver') | [
"amiller@millergis.com"
] | amiller@millergis.com |
75afd17e3e069e356eb793613cec54a09dbeb20c | bc5f2aadf602c0de46d0ea68924bf16e421735c4 | /src/authorization/api/parsers/parser_user_info.py | 9231f97eebc68fcfc0f6163dd899aff95eddb120 | [] | no_license | alexeyIvankov/imh_backend | 28d66e4123586013d4e2bbb2005b696f48f7a6c8 | 7cc245bf9ee7f1eefe73a78408d47f7fee8950c3 | refs/heads/master | 2020-06-18T18:41:24.232608 | 2019-07-11T14:23:25 | 2019-07-11T14:23:25 | 196,404,942 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,459 | py |
class ParserUserInfo:
def __init__(self, json):
self.json = json
def try_get_value(self, dict, key):
if dict is None:
return None
try:
value = dict[key]
except KeyError:
value = None
return value
def is_authorization(self):
return self.try_get_value(self.json, 'AuthorizationSuccess')
def get_name_person(self):
info = self.try_get_value(self.json, 'Info')
return self.try_get_value(info, 'ФИО')
def get_person_position_title(self):
info = self.try_get_value(self.json, 'Info')
positions = self.try_get_value(info, 'Должности')
return positions['JobTitle']
def get_person_position_sub_title(self):
info = self.try_get_value(self.json, 'Info')
positions = self.try_get_value(info, 'Должности')
return positions['OrganizationUnit']
def get_person_position_date_receipt(self):
info = self.try_get_value(self.json, 'Info')
positions = self.try_get_value(info, 'Должности')
return positions['DateOfReceipt']
def get_organisation_name(self):
info = self.try_get_value(self.json, 'Info')
positions = self.try_get_value(info, 'Должности')
return positions['Organization']
def get_organization_comment(self):
return self.try_get_value(self.json, 'AuthorizationComment')
| [
"alexey.ivankov@biz-tek.ru"
] | alexey.ivankov@biz-tek.ru |
435edafd02e1ac46f3a5040e3d051a2fc2a206c4 | 275b9c008e4fdb412550da35be85c135c2a37c26 | /pythonthread/process/get_pid.py | d0bce9d18ccf8daa75168fe80d016f6fb4963e53 | [] | no_license | fjpiao/pyclass | cc3c12ca6c0a8b1244219a00ed86fd76699fed9b | 52f73758e762df6841bf001488c2a6e5b3723ca1 | refs/heads/master | 2020-04-27T16:37:50.042169 | 2019-04-11T02:22:12 | 2019-04-11T02:22:12 | 174,488,588 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 249 | py | import os
from time import sleep
pid=os.fork()
if pid<0:
print('error')
elif pid==0:
print('child PID:',os.getpid())
print('get parent pid:',os.getppid())
else:
print('parent PID:',os.getpid())
print('get child pid:',pid)
| [
"fjpiao@126.com"
] | fjpiao@126.com |
e79dd0c02f070b7cc92288b3aa949aa3eba871d5 | d4c2a93e9993500520c5e3e9661deac1fb34e7fd | /CP/D11/Reverse Nodes in k-Group.py | 5302722f5906c6e5c495f85f66eed627a8b5187a | [] | no_license | natnaelabay/comptetive-programming | 3236a0a9b870434a3c9e0627cb82cae7dbc27165 | bc4a67d934167a0bd325e201594819f35ee134ee | refs/heads/master | 2020-11-24T15:16:46.662591 | 2020-08-13T20:39:08 | 2020-08-13T20:39:08 | 228,211,723 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,028 | py | # Natnael Abay
# se.natnael.abay@gmail.com
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
h = head
t = head
leader = trailer = None
while t:
for i in range(k - 1):
if not t:
break
t = t.next
if not t:
break
trailer = t.next
pre = leader
cur = h
#pre, cur = leader, h
while cur != trailer:
tmp = cur.next
cur.next = pre
pre, cur = cur, tmp
if leader:
leader.next = pre
else:
head = pre
leader = h
leader.next = trailer
h = t = trailer
return head
| [
"noreply@github.com"
] | natnaelabay.noreply@github.com |
a40fa3fabeaa09e2c3db291237b8fdf4ba9f4fd4 | 0ad269d44de9ab91dfbe2cdc480fa351d85c97cb | /Python/names.py | 471399920c0f9770151a4819246ecccb39ebe14a | [] | no_license | AuburnFord/kattis | 27b30f58d6993eacae9fcfaef62e5898194f21fe | 05110802dd2cff8c81bca339b6099cc85b073019 | refs/heads/master | 2022-02-05T07:22:04.953551 | 2022-01-30T07:13:04 | 2022-01-30T07:13:04 | 170,073,219 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 307 | py | def main():
name = input()
length = len(name)
best = 100
i = 0
while i < length:
newname = name+name[0:i][::-1]
diff = i
for x in range(len(newname)//2):
if newname[x] != newname[len(newname)-1-x]:
diff += 1
best = min(best,diff)
i+=1
print(best)
if __name__ == "__main__":
main()
| [
"auburnford@gmail.com"
] | auburnford@gmail.com |
ddf1c5a2d22f4c90d7518cbc7eb906bbaf0e9620 | 84f08365af6d2d91264d54232c1cb9c6c5ca0085 | /oob.py | b20498c431b55ac9166d7ef5607080515d43601e | [] | no_license | Birdocalypse/oob | 519383f250864cb7086287be949f1e2406a49ae1 | 4085c206ea3faca1263882a2b25b4fb39ae477a5 | refs/heads/main | 2023-02-18T09:32:06.844408 | 2021-01-17T20:58:06 | 2021-01-17T20:58:06 | 330,485,026 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 185 | py | while true:
x = input().lower()
output = ""
for char in x:
if char in ['a','e','i','o','u']:
char = 'oob'
output += char
print(output) | [
"noreply@github.com"
] | Birdocalypse.noreply@github.com |
e455d35d2e2d5fadab82c3884a1c5ba2381ac2bf | d90bbfe021c176d25ff9f726908eff5a5165902a | /feldman_cousins.py | 739ee6618651802c3ee2a73e316168fc40e0b08b | [] | no_license | jenkijoe/feldman-cousins | 35d4be0ca5fa8c6a17aecb3e007b782e1851e2e1 | 32895ce7b68b9ccc6c7b5fd667db1e9ce5e10f70 | refs/heads/master | 2021-01-10T09:01:52.548589 | 2016-04-06T20:56:06 | 2016-04-06T20:56:06 | 55,640,105 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,190 | py | import numpy as np
import matplotlib.pyplot as plt
import math as math
def _likelihood_ratio_gaussian(x, mu):
if (x < 0):
return math.exp(x * mu - mu * mu/2)
else:
return math.exp(-1 * (x - mu)*(x-mu) / 2)
def _likelihood_ratio_poisson(lmda, n):
if (n <= 0):
return math.exp(-lmda)
else:
return (lmda**n) * math.exp(-lmda) / math.factorial(n)
def feldman_cousins_gaussian(mu_min, mu_max, step_size, sigma, trials=1000000 , confidence_limit=0.9):
"""
Calculate Feldman Cousins confidence intervals for toy gaussian bound by mu > 0
Args:
mu_min -- lower limit for mu parameter scan
max_max -- upper limit for mu parameter scan
step_size -- step_size for mu parameter scan
sigma -- standard deviation for random number gaussian distribution
trials -- number of Monte-Carlo trials (default: 1000000)
confidence_limit -- required confidence limit in the range [0, 1.0) (default: 0.9 for 90% CL)
Returns:
numpy array representation for mu confidence belt: [0] = mu, [1] is lower confidence limit, [2] is upper confidence limit
"""
#initialise arrays
mu_values = np.arange(mu_min + step_size, mu_max, step_size)
results = np.zeros([3, mu_values.shape[0]], dtype=float)
index = 0
for mu in mu_values:
x_values = np.random.normal(mu, sigma, trials)
likelihood_ratios = map(_likelihood_ratio_gaussian, x_values, np.ones(trials) * mu)
# sort them by r
idx = np.argsort(likelihood_ratios, 0)[::-1]
sorted_r = [likelihood_ratios[i] for i in idx]
sorted_x = [x_values[i] for i in idx]
# produce list of indices
cut_off = int(math.floor(confidence_limit * trials))
accepted = sorted_x[0:cut_off]
#get min and max x values from the set of remaining x values
results[0][index] = mu
results[1][index] = min(accepted)
results[2][index] = max(accepted)
index = index+1
return results
def feldman_cousins_poisson(mu_min, mu_max, step_size, n_background, trials=1000000, confidence_limit=0.9):
n_max = int(mu_max)
mu_values = np.arange(mu_min, mu_max, step_size)
n_values = np.arange(n_max)
mu_best = np.array(map(max, np.zeros(n_max), n_values-n_background))
results = np.zeros([3,mu_values.shape[0]], dtype=float) # [0] = mu, [1] is lower confidence limit, [2] is upper confidence limit
index = 0
for mu in mu_values:
#calculate probability for each n
prob_values = np.array(map(_likelihood_ratio_poisson, np.ones(n_max)*(mu+n_background), n_values))
prob_best = np.array(map(_likelihood_ratio_poisson, mu_best+n_background, n_values))
likelihood_ratios = np.divide(prob_values, prob_best)
#sort the likelihood ratios
idx = np.argsort(likelihood_ratios, 0)[::-1]
sorted_n = [n_values[i] for i in idx]
sorted_p = [prob_values[i] for i in idx]
sum_p = 0.0
cut_off = 0
for p in sorted_p:
sum_p = sum_p + p
cut_off = cut_off + 1
if (sum_p > confidence_limit):
break
accepted = sorted_n[0:cut_off]
results[0][index] = mu
results[1][index] = min(accepted)
results[2][index] = max(accepted)
index = index + 1
return results
def _plot(results, x_limits, y_limits, axis_names):
plt.plot(results[1], results[0])
plt.plot(results[2], results[0])
plt.xlim(x_limits)
plt.ylim(y_limits)
plt.xlabel(axis_names[0])
plt.ylabel(axis_names[1])
plt.show()
def main():
# Example 1: toy gaussian bound by mu > 0
results_poisson = feldman_cousins_poisson(0.0, 30.0, 0.001, 3.0, 1000000, 0.9)
#_plot(results_poisson, (0.0, 15.0), (0.0, 15.0), ("Measured n", "Measured mu"))
# Example 2: toy poisson with background count of 3.0
results_gaussian = feldman_cousins_gaussian(0.0, 6.0, 0.05, 1.0, 1000000, 0.9)
#_plot(results_gaussian, (-4.0, 6.0), (0.0, 6.0), ("Measured x", "Mean mu"))
if __name__ == '__main__':
main()
| [
"jj9854@my.bristol.ac.uk"
] | jj9854@my.bristol.ac.uk |
1e4d8f144546bb2e1eeb8157dd23da79dbb06467 | 897cb969990a5ae319547fd572a262d58a1e33a8 | /JEC_Plotter/python/utilities/plot/flavor_fractions.py | a1986ca608672c79d5104191d741376aa0415eaf | [] | no_license | KIT-CMS/Excalibur | cc5a028bf6ad29a636536c3dfc0ebdc0eacfbbb7 | 8c27e2fdd7b7d5a0439f6e63be2299b16f5291c0 | refs/heads/master | 2023-07-24T05:28:08.156998 | 2023-07-17T15:29:15 | 2023-07-17T15:29:15 | 29,307,758 | 1 | 5 | null | 2023-05-24T11:41:22 | 2015-01-15T16:59:28 | Python | UTF-8 | Python | false | false | 8,593 | py | from copy import deepcopy
from ...core import (
PlotHistograms1D,
PlotHistograms1DFractions,
PlotHistograms2D,
CutSet
)
__all__ = ["plot_flavors", "plot_flavor_fractions"]
_flavor_fraction_cuts_parton_matching = dict(
u={
'cut': CutSet(name='u',
weights=["abs(matchedgenparton1flavour)==2"],
labels=[]),
'label': r"u",
'color': 'pink'
},
d={
'cut': CutSet(name='d',
weights=["abs(matchedgenparton1flavour)==1"],
labels=[]),
'label': r"d",
'color': 'darkred'
},
ud={
'cut': CutSet(name='ud',
weights=["(abs(matchedgenparton1flavour)==2||abs(matchedgenparton1flavour)==1)"],
labels=[]),
'label': r"ud",
'color': 'red'
},
s={
'cut': CutSet(name='s',
weights=["abs(matchedgenparton1flavour)==3"],
labels=[]),
'label': r"s",
'color': 'green'
},
c={
'cut': CutSet(name='c',
weights=["abs(matchedgenparton1flavour)==4"],
labels=[]),
'label': r"c",
'color': 'violet'
},
b={
'cut': CutSet(name='b',
weights=["abs(matchedgenparton1flavour)==5"],
labels=[]),
'label': r"b",
'color': 'cornflowerblue'
},
g={
'cut': CutSet(name='g',
weights=["abs(matchedgenparton1flavour)==21"],
labels=[]),
'label': r"g",
'color': 'orange'
},
undef={
'cut': CutSet(name='undef',
weights=["abs(matchedgenparton1flavour)>900"],
labels=[]),
'label': r"undef",
'color': 'lightgray'
},
)
_flavor_fraction_cuts_miniAOD = dict(
u={
'cut': CutSet(name='u',
weights=["abs(jet1flavor)==2"],
labels=[]),
'label': r"u",
'color': 'pink'
},
d={
'cut': CutSet(name='d',
weights=["abs(jet1flavor)==1"],
labels=[]),
'label': r"d",
'color': 'darkred'
},
ud={
'cut': CutSet(name='ud',
weights=["(abs(jet1flavor)==2||abs(jet1flavor)==1)"],
labels=[]),
'label': r"ud",
'color': 'red'
},
s={
'cut': CutSet(name='s',
weights=["abs(jet1flavor)==3"],
labels=[]),
'label': r"s",
'color': 'green'
},
c={
'cut': CutSet(name='c',
weights=["abs(jet1flavor)==4"],
labels=[]),
'label': r"c",
'color': 'violet'
},
b={
'cut': CutSet(name='b',
weights=["abs(jet1flavor)==5"],
labels=[]),
'label': r"b",
'color': 'cornflowerblue'
},
g={
'cut': CutSet(name='g',
weights=["abs(jet1flavor)==21"],
labels=[]),
'label': r"g",
'color': 'orange'
},
undef={
'cut': CutSet(name='undef',
weights=["abs(jet1flavor)==0"],
labels=[]),
'label': r"undef",
'color': 'lightgray'
},
)
def _get_flavor_cuts_colors_labels(flavors, flavor_definition="miniAOD"):
"""return flavor cuts for a particular flavor definition"""
if flavor_definition == 'miniAOD':
_flavor_fraction_cuts = _flavor_fraction_cuts_miniAOD
elif flavor_definition == 'parton matching':
_flavor_fraction_cuts = _flavor_fraction_cuts_parton_matching
else:
print ("ERROR: Unknown flavor definition '{}': "
"expected one of {}".format(flavor_definition,
set(['miniAOD', 'parton matching'])))
_unknown_flavors = (set(flavors) - set(_flavor_fraction_cuts.keys()))
if _unknown_flavors:
raise ValueError(
"Unknown flavors: {}! Available: {}".format(
_unknown_flavors, set(_flavor_fraction_cuts.keys())
)
)
_cuts = []
_colors = []
_labels = []
for _flavor in flavors:
_ac = _flavor_fraction_cuts[_flavor]
_cuts.append(_ac['cut'])
_colors.append(_ac['color'])
_labels.append(_ac['label'])
return _cuts, _colors, _labels
def plot_flavors(sample,
jec_correction_string,
quantities_or_quantity_pairs,
selection_cuts,
www_folder_label,
flavors_to_include=('ud', 's', 'c', 'b', 'g', 'undef'),
flavor_definition='miniAOD',
force_n_bins=None,
stacked=False,
y_log=False):
"""Plot contributions from various jet flavors."""
_cuts, _colors, _labels = _get_flavor_cuts_colors_labels(flavors_to_include, flavor_definition=flavor_definition)
_qs = []
_qpairs = []
for _q_or_qp in quantities_or_quantity_pairs:
if isinstance(_q_or_qp, tuple) or isinstance(_q_or_qp, tuple):
assert len(_q_or_qp) == 2
_qpairs.append(_q_or_qp)
else:
_qs.append(_q_or_qp)
# color each histogram by flavor
_samples = []
for _color, _label in zip(_colors, _labels):
_samples.append(deepcopy(sample))
_samples[-1]['source_label'] = _label
_samples[-1]['color'] = _color
_ph = None
if _qs:
_ph = PlotHistograms1D(
basename="flavors_{}".format(www_folder_label),
# there is one subplot per sample and cut in each plot
samples=_samples,
jec_correction_string=jec_correction_string,
additional_cuts=_cuts,
# each quantity cut generates a different plot
quantities=_qs,
# each selection cut generates a new plot
selection_cuts=selection_cuts,
stacked=stacked,
)
if force_n_bins is not None:
for _plot in _ph._plots:
_plot._basic_dict['x_bins'] = ",".join([str(force_n_bins)] + _plot._basic_dict['x_bins'].split(",")[1:])
_ph_log = deepcopy(_ph)
if y_log:
for _plot in _ph_log._plots:
_plot._basic_dict['y_log'] = True
_ph2 = None
if _qpairs:
_ph2 = PlotProfiles(
basename="flavors_{}".format(www_folder_label),
# there is one subplot per sample and cut in each plot
samples=_samples,
jec_correction_string=jec_correction_string,
additional_cuts=_cuts,
# each quantity cut generates a different plot
quantity_pairs=_qpairs,
# each selection cut generates a new plot
selection_cuts=selection_cuts,
# show_ratio_to_first=True,
)
for _plot2D in _ph2._plots:
if _plot2D._qy in ('jet1pt_over_jet1ptraw',):
_plot2D._basic_dict['lines'] = ['1.0'] # guide to the eye
if _ph is not None:
_ph.make_plots()
if _ph2 is not None:
_ph2.make_plots()
def plot_flavor_fractions(
sample,
jec_correction_string,
quantities,
selection_cuts,
www_folder_label,
flavors_to_include=('ud', 's', 'c', 'b', 'g', 'undef'),
flavor_definition='miniAOD',
force_n_bins=None):
"""Plot flavor composition as a fraction of total. Always stacked."""
_cuts, _colors, _labels = _get_flavor_cuts_colors_labels(flavors_to_include, flavor_definition=flavor_definition)
_ph = PlotHistograms1DFractions(
basename="flavor_fractions_{}".format(www_folder_label),
# there is one subplot per sample and cut in each plot
jec_correction_string=jec_correction_string,
reference_cut_set=None,
sample=sample,
fraction_cut_sets=_cuts,
fraction_colors=_colors,
fraction_labels=_labels,
# each quantity cut generates a different plot
quantities=quantities,
# each selection cut generates a new plot
selection_cuts=selection_cuts,
y_label="Fraction of Total Events"
)
for _plot in _ph._plots:
if force_n_bins is not None:
_plot._basic_dict['x_bins'] = ",".join([str(force_n_bins)] + _plot._basic_dict['x_bins'].split(",")[1:])
return _ph
| [
"daniel.savoiu@cern.ch"
] | daniel.savoiu@cern.ch |
26c7bede7b32cc57126fb18313b9b1f81c0a67c2 | 76ee9edf77b04cf1fbf14e1d92eda6a6c4a203b2 | /My_Temperature_History.py | 3309dedd1bd422f895a870905653016bf20382e3 | [] | no_license | navaliira/MySamsara | 89ea09f66ccbab7610541315c5601666ffb722d4 | 9285ac3800d74a167f79d183c483da51eb31ae03 | refs/heads/master | 2020-06-08T14:19:46.026110 | 2019-06-22T16:11:10 | 2019-06-22T16:11:10 | 193,243,034 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,643 | py | import json
import requests
import matplotlib.pyplot as plt
from datetime import datetime
"""
Input parameters; e.g. API Token, groupId, baseUrl, etc.
"""
access_token = '8lRABQGYyah8lpcvB2r1uGk4FYkkUN'
groupId = 33959
baseUrl = 'https://api.samsara.com/v1'
sensorId_Door = 212014918372977
sensorId_Environment = 212014918414714
fill_missing = "withNull"
#Required Time Span
##############################
# From 17 June 2019, 00:00:00
startMs = 1560729600000
# To 20 June 2019, 00:00:00
endMs = 1560988800000
#With Increments
stepMs = 14400000
#Required Result Field
##############################
series = [{"widgetId": sensorId_Environment, "field": "ambientTemperature"}]
"""
Response Codes Descriptions
"""
def responseCodes(response):
"""
This function performs error handling for the API calls.
"""
if response.status_code >= 200 and response.status_code < 299:
#Do nothing, API call was successful
pass
elif response.status_code == 400:
print(response.text)
raise ValueError('Bad Request: Please make sure the request follows the format specified in the documentation.')
elif response.status_code == 401:
print(response.text)
raise ValueError('Invalid Token: Could not authenticate successfully')
elif response.status_code == 404:
print(response.text)
raise ValueError('Page not found: API Endpoint is invalid')
else:
print(response.text)
raise ValueError('Request was not successful')
"""
Extracting the temperature history from the Environment sensor within specific times
"""
def getSensorsHistory(access_token,groupId):
sensorsHistoryUrl = '/sensors/history'
parameters = {"access_token":access_token}
requestBodyTemperature = {
"endMs": endMs,
"fillMissing": fill_missing,
"groupId": groupId,
"series": [
{
"field": "ambientTemperature",
"widgetId": sensorId_Environment
}
],
"startMs": startMs,
"stepMs": stepMs
}
response = requests.get(baseUrl+sensorsHistoryUrl,params=parameters,json=requestBodyTemperature)
responseCodes(response)
return response.json()['results']
##Saving Result
Result = getSensorsHistory(access_token,groupId)
"""
Plotting Result in real time format
"""
x_timeMs = [i['timeMs'] for i in Result if 'timeMs' in i]
x_realTime = [datetime.utcfromtimestamp(j/1000).strftime('%m/%d %H:%M:%S') for j in x_timeMs]
y_temperature = [i['series'][0]/1000 for i in Result if 'series' in i]
plt.plot(x_realTime, y_temperature)
plt.xticks(x_realTime, rotation='vertical')
plt.title("Temperature History")
plt.xlabel("Date & Time")
plt.ylabel("Temperature (°C)")
plt.grid(color='g', linestyle='-', linewidth=0.1)
plt.show()
| [
"noreply@github.com"
] | navaliira.noreply@github.com |
8a5ac91e927609161b9bdd379ef27e2f3e48ac55 | b7fb131079182a3c2bca8d6d646980bf44503bab | /gigasecond/gigasecond.py | ac90ffc51b93c689b2e0970b9acc5a9d3018ae40 | [] | no_license | Akhilhari/Exercism_task | 4bf50ea463318ee1267489c14c8f2b096566043a | 906a89053d8b2c44b7ee7c86ff018f78cd61eecc | refs/heads/main | 2023-07-16T09:04:08.907653 | 2021-09-10T00:25:54 | 2021-09-10T00:25:54 | 403,230,310 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 96 | py | from datetime import timedelta
def add(datetime):
return datetime + timedelta(seconds=10**9) | [
"akhilbkv@gmail.com"
] | akhilbkv@gmail.com |
07aca1da752ad1919d55d27db4dd894621e07219 | 0bdcc6ce3d4d7669680e103f119564bef74205b7 | /src/weighted-directed-graph.py | 6e51d9ca22383d5ff78380574dfa7d9c304f6471 | [] | no_license | kmgowda/ds-programs-python | c4c71404b4a4c40f6f06c10135ec8155be2fd698 | 3b45f27fdee436aaf45b672648e1f185ee4c3644 | refs/heads/master | 2021-10-25T17:09:05.215789 | 2021-10-16T11:02:16 | 2021-10-16T11:02:16 | 185,553,127 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,093 | py | import random
import networkx as nx
import matplotlib.pyplot as plt
from multiprocessing import Process, Queue
def generate_graph(V, E):
G = nx.DiGraph()
for i in range(V):
G.add_node("V"+str(i+1))
nodes=G.nodes()
for i in range(E):
edge = random.sample(nodes,2)
if G.has_edge(edge[1], edge[0]):
wd = G.get_edge_data(edge[1], edge[0])
w = wd['weight']
else:
w = random.randint(1, 10)
G.add_edge(edge[0], edge[1], weight=w)
return G
def create_adjaceny_list(G):
N = nx.number_of_nodes(G)
adlist = list()
for i in range(N):
adlist.append(list())
adlist[i] = list()
edgeslist = G.edges()
for edge in edgeslist:
index= int(edge[0][1:])-1
dest = int(edge[1][1:])-1
if dest not in adlist[index]:
adlist[index].append(dest)
return adlist
def convert_adjlist_adjmat(adlist, N):
mat = list()
for i in range(N):
mat.append(list())
mat[i]=[0]*N
for i in range(len(adlist)):
for v in adlist[i]:
mat[i][v] = 1
# The below one is for undirected graph
#mat[v][i] = 1
return mat
def print_node_edges(G):
print("Nodes of graph: ")
print(G.nodes())
print("Edges of graph: ")
print(G.edges())
def print_weight_graph(G, edges, title,q):
print("print_graph")
ncolor = ['b']*G.number_of_nodes()
gedges = G.edges()
ecolor = ['k']*len(gedges)
widthlt =[0.5]*len(gedges)
if edges:
for tmp in edges:
val = int(tmp[0][1:])-1
ncolor[val] = 'r'
val = int(tmp[1][1:])-1
ncolor[val] = 'r'
i = 0
for ed in gedges:
for tmp in edges:
if ed == tmp:
ecolor[i]='g'
widthlt[i]=1.5
i+=1
elabels = nx.get_edge_attributes(G,'weight')
layout = nx.circular_layout(G)
nx.draw_networkx(G, pos=layout, with_labels=True, node_color=ncolor, edge_color = ecolor, alpha = 0.5, width=widthlt, arrows=True)
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=elabels)
q.put(None)
plt.title(title)
plt.axis('off')
plt.show()
def show_graph(G, edges, title, q):
p = Process(target=print_weight_graph, args=(G,edges,title, q))
p.start()
q.get()
return p
def shortest_path(G, src, dst):
adlist = create_adjaceny_list(G)
N = G.number_of_nodes()
mat = convert_adjlist_adjmat(adlist, N)
prev = [-1]*N
st = list()
st.append(src)
prev[src]= src
while len(st):
node = st.pop(0)
if node == dst:
break
for i in range(N):
if mat[node][i] and prev[i] == -1:
st.append(i)
prev[i]=node
edges = list()
i = dst
while prev[i] != -1 and prev[i] != src:
edges.append(("V"+str(prev[i]+1), "V"+str(i+1)))
i = prev[i]
if prev[i] == -1:
return None
else:
edges.append(("V"+str(src+1), "V"+str(i+1)))
return edges
if __name__=="__main__":
print("Python program draw the weighted directed graph")
V = int(input("How many nodes/ Vertices?"))
E = int(input("How many edges?"))
G = generate_graph(V,E)
print_node_edges(G)
q = Queue()
p1= show_graph(G, None, "Generated graph", q)
# src = int(input("Enter the source node number (Example : V1 as 1)"))
# dst = int(input("Enter the destination node number (Example : V1 as 1)"))
print("Waiting for the plot to close")
p1.join()
# edges = shortest_path(G, src-1, dst-1)
# print("The edges of the shortest path are as follows")
# for i in range(len(edges)-1, -1, -1):
# print(edges[i], end=" ")
# print()
# p2 = show_graph(G, edges, "Shortest path", q)
# print("waiting for plot close")
# p2.join()
print("Its done KMG!") | [
"keshava.munegowda@dell.com"
] | keshava.munegowda@dell.com |
26395959715c830a502fc738e8042169f5a4f4d2 | 2d3e13a2da45ae49b79c2023fcc0ccddb025963f | /pythonCosas/Curso-Phyton-Basico/04_list.py | a390742d0f31d6bc6c23ed8df9eacfbf1c759037 | [] | no_license | Bardo1/Python-Ejercicios | 67611d86328d676c90b7d67f44edd89411fbcf4b | 50a514f7f4414120d143c57a6f72ef0720de5038 | refs/heads/master | 2020-12-01T23:54:16.572499 | 2019-12-30T14:57:02 | 2019-12-30T14:57:02 | 230,820,515 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 571 | py | demolist = ["list",True,34,3.56,[3,3,1]]
colors = ['red','green','blue']
numbers_list = list((1,2,3,4))
print (type(numbers_list))
r = list(range(1,1000))
print(r)
print(len(demolist))
print(colors[-2]) #<-- indice negativo
print(dir(colors))
# con append agregamos un elemento
colors.append('violet')
colors.extend(['purple','orange'])
print(colors)
# colors.extend('pink','black')
# con insert es posible usar índices negativos
colors.insert(-1,'silver')
colors.sort(reverse=True)
colors.append('red')
print('----------------')
print(colors.count('red'))
| [
"walterrmz1@gmail.com"
] | walterrmz1@gmail.com |
19be2c31c8780a3eb5dc1e961f4169d16796c730 | af1f72ae61b844a03140f3546ffc56ba47fb60df | /tests/aat/api/v1/client/models/packet_generator_learning_result_ipv6.py | d65f878a44224415efcc722874239d15942ac9d4 | [
"Apache-2.0"
] | permissive | Spirent/openperf | 23dac28e2e2e1279de5dc44f98f5b6fbced41a71 | d89da082e00bec781d0c251f72736602a4af9b18 | refs/heads/master | 2023-08-31T23:33:38.177916 | 2023-08-22T03:23:25 | 2023-08-22T07:13:15 | 143,898,378 | 23 | 16 | Apache-2.0 | 2023-08-22T07:13:16 | 2018-08-07T16:13:07 | C++ | UTF-8 | Python | false | false | 5,230 | py | # coding: utf-8
"""
OpenPerf API
REST API interface for OpenPerf # noqa: E501
OpenAPI spec version: 1
Contact: support@spirent.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PacketGeneratorLearningResultIpv6(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'ip_address': 'str',
'next_hop_address': 'str',
'mac_address': 'str'
}
attribute_map = {
'ip_address': 'ip_address',
'next_hop_address': 'next_hop_address',
'mac_address': 'mac_address'
}
def __init__(self, ip_address=None, next_hop_address=None, mac_address=None): # noqa: E501
"""PacketGeneratorLearningResultIpv6 - a model defined in Swagger""" # noqa: E501
self._ip_address = None
self._next_hop_address = None
self._mac_address = None
self.discriminator = None
self.ip_address = ip_address
if next_hop_address is not None:
self.next_hop_address = next_hop_address
if mac_address is not None:
self.mac_address = mac_address
@property
def ip_address(self):
"""Gets the ip_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
IPv6 destination address. # noqa: E501
:return: The ip_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
:rtype: str
"""
return self._ip_address
@ip_address.setter
def ip_address(self, ip_address):
"""Sets the ip_address of this PacketGeneratorLearningResultIpv6.
IPv6 destination address. # noqa: E501
:param ip_address: The ip_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
:type: str
"""
self._ip_address = ip_address
@property
def next_hop_address(self):
"""Gets the next_hop_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
IPv6 next hop address. # noqa: E501
:return: The next_hop_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
:rtype: str
"""
return self._next_hop_address
@next_hop_address.setter
def next_hop_address(self, next_hop_address):
"""Sets the next_hop_address of this PacketGeneratorLearningResultIpv6.
IPv6 next hop address. # noqa: E501
:param next_hop_address: The next_hop_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
:type: str
"""
self._next_hop_address = next_hop_address
@property
def mac_address(self):
"""Gets the mac_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
MAC address of next hop IPv6 address. # noqa: E501
:return: The mac_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
:rtype: str
"""
return self._mac_address
@mac_address.setter
def mac_address(self, mac_address):
"""Sets the mac_address of this PacketGeneratorLearningResultIpv6.
MAC address of next hop IPv6 address. # noqa: E501
:param mac_address: The mac_address of this PacketGeneratorLearningResultIpv6. # noqa: E501
:type: str
"""
self._mac_address = mac_address
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(PacketGeneratorLearningResultIpv6, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PacketGeneratorLearningResultIpv6):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"daniel.morton@spirent.com"
] | daniel.morton@spirent.com |
7f0d6448cc2f278badf68242c95dd3f6470bfccb | db692c460b043f04e4141c8ab3b9be05f3da195e | /azure-devops/azext_devops/dev/pipelines/pipeline_create.py | afe13fdbc5dd46accda35f599fb39a8abf4b8eb9 | [
"MIT"
] | permissive | squassina/azure-devops-cli-extension | 58a0d1074b29e1c3317fa87709b1357511fa5460 | dcb5603f671b51a778c01d5c4a063a13d0fd06f9 | refs/heads/master | 2020-06-23T17:55:43.486866 | 2019-07-29T07:45:28 | 2019-07-29T07:45:28 | 198,704,488 | 0 | 0 | MIT | 2019-07-24T20:20:30 | 2019-07-24T20:20:29 | null | UTF-8 | Python | false | false | 24,711 | py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import tempfile
import os
from knack.log import get_logger
from knack.util import CLIError
from knack.prompting import prompt
from azext_devops.dev.common.services import (get_new_pipeline_client, get_new_cix_client, get_git_client,
resolve_instance_and_project, resolve_instance_project_and_repo)
from azext_devops.dev.common.uri import uri_parse
from azext_devops.dev.common.utils import open_file, delete_dir
from azext_devops.dev.common.git import get_remote_url, get_current_branch_name
from azext_devops.dev.common.arguments import should_detect
from azext_devops.dev.common.prompting import (prompt_user_friendly_choice_list,
verify_is_a_tty_or_raise_error,
prompt_not_empty)
from azext_devops.dev.pipelines.pipeline_create_helpers.github_api_helper import (
push_files_github, get_github_repos_api_url, Files)
from azext_devops.dev.pipelines.pipeline_create_helpers.pipelines_resource_provider import (
get_azure_rm_service_connection, get_azure_rm_service_connection_id, get_github_service_endpoint,
get_kubernetes_environment_resource, get_container_registry_service_connection, get_webapp_from_list_selection)
from azext_devops.dev.pipelines.pipeline_create_helpers.azure_repos_helper import push_files_to_azure_repo
from azext_devops.devops_sdk.v5_1.build.models import Build, BuildDefinition, BuildRepository, AgentPoolQueue
from .build_definition import get_definition_id_from_name
logger = get_logger(__name__)
# pylint: disable=too-few-public-methods
class YmlOptions:
def __init__(self, name, id, content, description='Custom yaml', params=None, path=None, assets=None): # pylint: disable=redefined-builtin
self.name = name
self.id = id
self.description = description
self.content = content
self.path = path
self.params = params
self.assets = assets
_GITHUB_REPO_TYPE = 'github'
_AZURE_GIT_REPO_TYPE = 'tfsgit'
def pipeline_create(name, description=None, repository=None, branch=None, yml_path=None, repository_type=None,
service_connection=None, organization=None, project=None, detect=None, queue_id=None):
""" (PREVIEW) Create a new Azure Pipeline (YAML based)
:param name: Name of the new pipeline
:type name: str
:param description: Description for the new pipeline
:type description: str
:param repository: Repository for which the pipeline needs to be configured.
Can be clone url of the git repository or name of the repository for a Azure Repos
or Owner/RepoName in case of GitHub repository.
If omitted it will be auto-detected from the remote url of local git repository.
If name is mentioned instead of url, --repository-type argument is also required.
:type repository: str
:param branch: Branch name for which the pipeline will be configured. If omitted, it will be auto-detected
from local repository
:type branch: str
:param yml_path: Path of the pipelines yaml file in the repo (if yaml is already present in the repo).
:type yml_path: str
:param repository_type: Type of repository. If omitted, it will be auto-detected from remote url
of local repository. 'tfsgit' for Azure Repos, 'github' for GitHub repository.
:type repository_type: str
:param service_connection: Id of the Service connection created for the repository for GitHub repository.
Use command az devops service-endpoint -h for creating/listing service_connections. Not required for Azure Repos.
:type service_connection: str
:param queue_id: Id of the queue in the available agent pools. Will be auto detected if not specified.
:type queue_id: str
"""
repository_name = None
if repository:
organization, project = resolve_instance_and_project(
detect=detect, organization=organization, project=project)
else:
organization, project, repository_name = resolve_instance_project_and_repo(
detect=detect, organization=organization, project=project)
# resolve repository if local repo for azure repo
if repository_name:
repository = repository_name
repository_type = _AZURE_GIT_REPO_TYPE
# resolve repository from local repo for github repo
if not repository:
repository = _get_repository_url_from_local_repo(detect=detect)
if not repository:
raise CLIError('The following arguments are required: --repository.')
if not repository_type:
repository_type = try_get_repository_type(repository)
if not repository_type:
raise CLIError('The following arguments are required: --repository-type. '
'Check command help for valid values.')
if not branch and should_detect(detect):
branch = get_current_branch_name()
if not branch:
raise CLIError('The following arguments are required: --branch.')
# repository, repository-type, branch should be set by now
if not repository_name and is_valid_url(repository):
repository_name = _get_repo_name_from_repo_url(repository)
else:
repository_name = repository
# Validate name availability so user does not face name conflicts after going through the whole process
if not validate_name_is_available(name, organization, project):
raise CLIError('Pipeline with name {name} already exists.'.format(name=name))
# Parse repository information according to repository type
repo_id = None
api_url = None
repository_url = None
if repository_type.lower() == _GITHUB_REPO_TYPE:
repo_id = repository_name
repository_url = 'https://github.com/' + repository_name
api_url = get_github_repos_api_url(repository_name)
if repository_type.lower() == _AZURE_GIT_REPO_TYPE:
repo_id = _get_repository_id_from_name(organization, project, repository_name)
if not service_connection and repository_type != _AZURE_GIT_REPO_TYPE:
service_connection = get_github_service_endpoint(organization, project)
new_cix_client = get_new_cix_client(organization=organization)
# No yml path => find or recommend yml scenario
queue_branch = branch
if not yml_path:
yml_path, queue_branch = _create_and_get_yml_path(new_cix_client, repository_type, repo_id,
repository_name, branch, service_connection, project,
organization)
if not queue_id:
queue_id = _get_agent_queue_by_heuristic(organization=organization, project=project)
if queue_id is None:
logger.warning('Cannot find a hosted pool queue in the project. Provide a --queue-id in command params.')
# Create build definition
definition = _create_pipeline_build_object(name, description, repo_id, repository_name, repository_url, api_url,
branch, service_connection, repository_type, yml_path, queue_id)
client = get_new_pipeline_client(organization)
created_definition = client.create_definition(definition=definition, project=project)
logger.warning('Successfully created a pipeline with Name: %s, Id: %s.',
created_definition.name, created_definition.id)
return client.queue_build(
build=Build(definition=created_definition, source_branch=queue_branch), project=project)
def pipeline_update(name=None, id=None, description=None, new_name=None, # pylint: disable=redefined-builtin
branch=None, yml_path=None, queue_id=None, organization=None, project=None, detect=None):
""" (PREVIEW) Update a pipeline
:param name: Name of the pipeline to update.
:type name: str
:param id: Id of the pipeline to update.
:type id: str
:param new_name: New updated name of the pipeline.
:type new_name: str
:param description: Description to be updated for the pipeline.
:type description: str
:param branch: Branch name for which the pipeline will be configured.
:type branch: str
:param yml_path: Path of the pipelines yaml file in the repo.
:type yml_path: str
:param queue_id: Queue id of the agent pool where the pipeline needs to run.
:type queue_id: int
"""
# pylint: disable=too-many-branches
organization, project = resolve_instance_and_project(
detect=detect, organization=organization, project=project)
pipeline_client = get_new_pipeline_client(organization=organization)
if id is None:
if name is not None:
id = get_definition_id_from_name(name, pipeline_client, project)
else:
raise CLIError("Either --id or --name argument must be supplied for this command.")
definition = pipeline_client.get_definition(definition_id=id, project=project)
if new_name:
definition.name = new_name
if description:
definition.description = description
if branch:
definition.repository.default_branch = branch
if queue_id:
definition.queue = AgentPoolQueue()
definition.queue.id = queue_id
if yml_path:
definition.process = _create_process_object(yml_path)
return pipeline_client.update_definition(project=project, definition_id=id, definition=definition)
def validate_name_is_available(name, organization, project):
client = get_new_pipeline_client(organization=organization)
definition_references = client.get_definitions(project=project, name=name)
if not definition_references:
return True
return False
def _get_repository_url_from_local_repo(detect):
if should_detect(detect):
return get_remote_url(is_github_url_candidate)
return None
def is_github_url_candidate(url):
if url is None:
return False
components = uri_parse(url.lower())
if components.netloc == 'github.com':
return True
return False
def is_valid_url(url):
if ('github.com' in url or 'visualstudio.com' in url or 'dev.azure.com' in url):
return True
return False
def _get_repo_name_from_repo_url(repository_url):
"""
Should be called with a valid github or azure repo url
returns owner/reponame for github repos, repo_name for azure repo type
"""
repo_type = try_get_repository_type(repository_url)
if repo_type == _GITHUB_REPO_TYPE:
parsed_url = uri_parse(repository_url)
logger.debug('Parsing GitHub url: %s', parsed_url)
if parsed_url.scheme == 'https' and parsed_url.netloc == 'github.com':
logger.debug('Parsing path in the url to find repo id.')
stripped_path = parsed_url.path.strip('/')
if stripped_path.endswith('.git'):
stripped_path = stripped_path[:-4]
return stripped_path
if repo_type == _AZURE_GIT_REPO_TYPE:
parsed_list = repository_url.split('/')
index = 0
for item in parsed_list:
if ('visualstudio.com' in item or 'dev.azure.com' in item) and len(parsed_list) > index + 4:
return parsed_list[index + 4]
index = index + 1
raise CLIError('Could not parse repository url.')
def _create_repo_properties_object(service_endpoint, branch, api_url):
return {
"connectedServiceId": service_endpoint,
"defaultBranch": branch,
"apiUrl": api_url
}
def _create_process_object(yaml_path):
return {
"yamlFilename": yaml_path,
"type": 2
}
def try_get_repository_type(url):
if 'https://github.com' in url:
return _GITHUB_REPO_TYPE
if 'dev.azure.com' in url or '.visualstudio.com' in url:
return _AZURE_GIT_REPO_TYPE
return None
def _create_and_get_yml_path(cix_client, repository_type, repo_id, repo_name, branch, # pylint: disable=too-many-locals, too-many-statements
service_endpoint, project, organization):
logger.debug('No yaml file was given. Trying to find the yaml file in the repo.')
queue_branch = branch
default_yml_exists = False
yml_names = []
yml_options = []
configurations = cix_client.get_configurations(
project=project, repository_type=repository_type,
repository_id=repo_id, branch=branch, service_connection_id=service_endpoint)
for configuration in configurations:
if configuration.path.strip('/') == 'azure-pipelines.yml':
default_yml_exists = True
logger.debug('The repo has a yaml pipeline definition. Path: %s', configuration.path)
custom_name = 'Existing yaml (path={})'.format(configuration.path)
yml_names.append(custom_name)
yml_options.append(YmlOptions(name=custom_name, content=configuration.content, id='customid',
path=configuration.path))
recommendations = cix_client.get_template_recommendations(
project=project, repository_type=repository_type,
repository_id=repo_id, branch=branch, service_connection_id=service_endpoint)
logger.debug('List of recommended templates..')
# sort recommendations
from operator import attrgetter
recommendations = sorted(recommendations, key=attrgetter('recommended_weight'), reverse=True)
for recommendation in recommendations:
yml_names.append(recommendation.name)
yml_options.append(YmlOptions(name=recommendation.name, content=recommendation.content,
id=recommendation.id, description=recommendation.description,
params=recommendation.parameters, assets=recommendation.assets))
temp_filename = None
files = []
yml_selection_index = 0
proceed_selection = 1
while proceed_selection == 1:
proceed_selection = 0
# Clear files since user can change the template now
del files[:]
yml_selection_index = prompt_user_friendly_choice_list("Which template do you want to use for this pipeline?",
yml_names)
if yml_options[yml_selection_index].params:
yml_options[yml_selection_index].content, yml_options[yml_selection_index].assets = _handle_yml_props(
params_required=yml_options[yml_selection_index].params,
template_id=yml_options[yml_selection_index].id,
cix_client=cix_client, repo_name=repo_name, organization=organization, project=project)
temp_dir = tempfile.mkdtemp(prefix='AzurePipelines_')
temp_filename = os.path.join(temp_dir, 'azure-pipelines.yml')
f = open(temp_filename, mode='w')
f.write(yml_options[yml_selection_index].content)
f.close()
assets = yml_options[yml_selection_index].assets
if assets:
for asset in assets:
files.append(Files(asset.destination_path, asset.content))
view_choice = prompt_user_friendly_choice_list(
'Do you want to view/edit the template yaml before proceeding?',
['Continue with generated yaml', 'View or edit the yaml'])
if view_choice == 1:
open_file(temp_filename)
proceed_selection = prompt_user_friendly_choice_list(
'Do you want to proceed creating a pipeline?',
['Proceed with this yaml', 'Choose another template'])
# Read updated data from the file
f = open(temp_filename, mode='r')
content = f.read()
f.close()
delete_dir(temp_dir)
checkin_path = 'azure-pipelines.yml'
if default_yml_exists and not yml_options[yml_selection_index].path: # We need yml path from user
logger.warning('A yaml file azure-pipelines.yml already exists in the repository root.')
checkin_path = prompt_not_empty(
msg='Enter a yaml file path to checkin the new pipeline yaml in the repository? ',
help_string='e.g. /new_azure-pipeline.yml to add in the root folder.')
print('')
files.append(Files(checkin_path, content))
print('Files to be added to your repository ({numfiles})'.format(numfiles=len(files)))
count_file = 1
for file in files:
print('{index}) {file}'.format(index=count_file, file=file.path))
count_file = count_file + 1
print('')
if default_yml_exists and checkin_path.strip('/') == 'azure-pipelines.yml':
print('Edits on the existing yaml can be done in the code repository.')
else:
queue_branch = push_files_to_repository(organization, project, repo_name, branch, files, repository_type)
return checkin_path, queue_branch
def push_files_to_repository(organization, project, repo_name, branch, files, repository_type):
commit_strategy_choice_list = ['Commit directly to the {branch} branch.'.format(branch=branch),
'Create a new branch for this commit and start a pull request.']
commit_choice = prompt_user_friendly_choice_list("How do you want to commit the files to the repository?",
commit_strategy_choice_list)
commit_direct_to_branch = commit_choice == 0
if repository_type == _GITHUB_REPO_TYPE:
return push_files_github(files, repo_name, branch, commit_direct_to_branch)
if repository_type == _AZURE_GIT_REPO_TYPE:
return push_files_to_azure_repo(files, repo_name, branch, commit_direct_to_branch, organization, project)
raise CLIError('File push failed: Repository type not supported.')
def _get_pipelines_trigger(repo_type):
if repo_type.lower() == _GITHUB_REPO_TYPE:
return [{"settingsSourceType": 2, "triggerType": 2},
{"forks": {"enabled": "true", "allowSecrets": "false"},
"settingsSourceType": 2, "triggerType": "pullRequest"}]
return [{"settingsSourceType": 2, "triggerType": 2}]
def _handle_yml_props(params_required, template_id, cix_client, repo_name, organization, project):
logger.warning('The template requires a few inputs. We will help you fill them out')
params_to_render = {}
for param in params_required:
param_name_for_user = param.name
# override with more user friendly name if available
if param.display_name:
param_name_for_user = param.display_name
logger.debug('Looking for param %s in props', param.name)
prop_found = False
if param.default_value:
prop_found = True
user_input_val = prompt(msg='Enter a value for {param_name} [Press Enter for default: {param_default}]:'
.format(param_name=param_name_for_user, param_default=param.default_value))
print('')
if user_input_val:
params_to_render[param.name] = user_input_val
else:
params_to_render[param.name] = param.default_value
elif _is_intelligent_handling_enabled_for_prop_type(prop_name=param.name, prop_type=param.type):
logger.debug('This property is handled intelligently (Name: %s) (Type: %s)', param.name, param.type)
fetched_value = fetch_yaml_prop_intelligently(param.name, param.type, organization, project, repo_name)
if fetched_value is not None:
logger.debug('Auto filling param %s with value %s', param.name, fetched_value)
params_to_render[param.name] = fetched_value
prop_found = True
if not prop_found:
input_value = _prompt_for_prop_input(param_name_for_user, param.type)
params_to_render[param.name] = input_value
prop_found = True
rendered_template = cix_client.render_template(template_id=template_id,
template_parameters={'tokens': params_to_render})
return rendered_template.content, rendered_template.assets
def fetch_yaml_prop_intelligently(prop_name, prop_type, organization, project, repo_name):
if prop_type.lower() == 'endpoint:azurerm':
return get_azure_rm_service_connection(organization, project)
if prop_type.lower() == 'connectedservice:azurerm':
return get_azure_rm_service_connection_id(organization, project)
if prop_type.lower() == 'environmentresource:kubernetes':
return get_kubernetes_environment_resource(organization, project, repo_name)
if prop_type.lower() == 'endpoint:containerregistry':
return get_container_registry_service_connection(organization, project)
if prop_name.lower() == 'webappname':
return get_webapp_from_list_selection()
return None
def _is_intelligent_handling_enabled_for_prop_type(prop_name, prop_type):
SMART_HANDLING_FOR_PROP_TYPES = ['connectedservice:azurerm',
'endpoint:azurerm',
'environmentresource:kubernetes',
'endpoint:containerregistry']
SMART_HANDLING_FOR_PROP_NAMES = ['webappname']
if prop_type.lower() in SMART_HANDLING_FOR_PROP_TYPES:
return True
if prop_name.lower() in SMART_HANDLING_FOR_PROP_NAMES:
return True
return False
def _prompt_for_prop_input(prop_name, prop_type):
verify_is_a_tty_or_raise_error('The template requires a few inputs. These cannot be provided as in command '
'arguments. It can only be input interatively.')
val = prompt(msg='Please enter a value for {prop_name}: '.format(prop_name=prop_name),
help_string='Value of type {prop_type} is required.'.format(prop_type=prop_type))
print('')
return val
def _create_pipeline_build_object(name, description, repo_id, repo_name, repository_url, api_url, branch,
service_endpoint, repository_type, yml_path, queue_id):
definition = BuildDefinition()
definition.name = name
if description:
definition.description = description
# Set build repo
definition.repository = BuildRepository()
if repo_id:
definition.repository.id = repo_id
if repo_name:
definition.repository.name = repo_name
if repository_url:
definition.repository.url = repository_url
if branch:
definition.repository.default_branch = branch
if service_endpoint:
definition.repository.properties = _create_repo_properties_object(service_endpoint, branch, api_url)
# Hack to avoid the case sensitive GitHub type for service hooks.
if repository_type.lower() == _GITHUB_REPO_TYPE:
definition.repository.type = 'GitHub'
else:
definition.repository.type = repository_type
# Set build process
definition.process = _create_process_object(yml_path)
# set agent queue
definition.queue = AgentPoolQueue()
definition.triggers = _get_pipelines_trigger(repository_type)
if queue_id:
definition.queue.id = queue_id
return definition
def _get_repository_id_from_name(organization, project, repository):
git_client = get_git_client(organization)
repository = git_client.get_repository(project=project, repository_id=repository)
return repository.id
def _get_agent_queue_by_heuristic(organization, project):
"""
Tries to detect a queue in the agent pool in a project
Returns id of Hosted Ubuntu 16.04, first hosted pool queue, first queue in that order
None if no queues are returned
"""
from azext_devops.dev.common.services import get_new_task_agent_client
choosen_queue = None
agent_client = get_new_task_agent_client(organization=organization)
queues = agent_client.get_agent_queues(project=project)
if queues:
choosen_queue = queues[0]
found_first_hosted_pool_queue = False
for queue in queues:
if queue.name == 'Hosted Ubuntu 1604':
choosen_queue = queue
break
if not found_first_hosted_pool_queue and queue.pool.is_hosted:
choosen_queue = queue
found_first_hosted_pool_queue = True
logger.debug('Auto detecting agent pool. Queue: %s, Pool: %s', choosen_queue.name, choosen_queue.pool.name)
return choosen_queue.id
return None
| [
"noreply@github.com"
] | squassina.noreply@github.com |
2344843e62438a5a51b96e6c841d292ac76c7fd0 | f9422bf3fca085dceb7f5108d3958435aa665c83 | /EP1/main.py | 99362906dadefd040dc8f3f843f32ed255a983c9 | [] | no_license | zalcademy/course_101 | d7d67ae0439a2d3603f6419e5b74266faa4494cf | ba75084b2d2a1fe24e435248ae1b6de07486eeae | refs/heads/master | 2023-05-07T12:45:37.567176 | 2021-05-24T06:06:41 | 2021-05-24T06:06:41 | 369,218,975 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,236 | py | import math
from lib.greetings import sayHello
import time
import datetime
# Hello World Project:
# name = input()
# print("Hello " + name)
# Variables:
a = 25 # int
print(a)
b = 3.14 # float
c = "Zalcademy" # String
d = True # Boolean
e = False # Boolean
presentUsers = 31
presentUsers = presentUsers - 1
print(presentUsers)
f = b + a
print(f)
g = [1, 5, 8, 10, "zal", 45, "zal"]
print(g[4])
g.append("Bahman")
g.remove(10)
print(g)
print(g.count("zal"))
h = "bahman" in g
print(h)
i = [5, 2, 8, 10, 45, 123456]
i.sort()
print(i)
g.extend(i)
print("-----------------")
print(i)
print(g)
print(len(g))
g[12] = 45654654
print(1)
k = (1, 2, 3)
print(k)
# k[2] = 654456
l = set()
l.add(1)
l.add(2)
l.add(3)
l.add(2)
print(l)
l2 = set([1, 2, 3, 4, 4, 4, 4])
print(l2)
d1 = {"bahman": "09388309605", "Shakiba": "21546884684"}
d1["bahman"] = None
print(d1["bahman"])
print(type(d1))
print(type(l2))
a2 = int("15")
print(type(a2))
# Assignment operators:
# =, =+, =-, =/, =*
#
# Arithmetic Operators:
# +, -, /, *
#
# Logical operators:
# >, <, >=, <=, ==, and, not
# True and True
# True and False
# True or True
# True or False
# False or False
print((5 == 5 and not 5 < 10))
x = 0
x += 1
x += 1
x += 4
x += 1
if x < 5:
print("Allow the next person to enter")
elif x < 10 and x >= 5:
print("Capacity is half full")
else:
print("Full capacity")
print("Program finished")
counter = 0
while counter < 4:
print(counter)
counter += 1
print("-------------------")
for item in g:
print(item * 2)
for item in range(10):
if item == 2:
continue
if item == 6:
break
print(item)
def greeting(name, lastname):
print("Hello " + name + " " + lastname)
return name + " " + lastname
res = greeting("Bahman", "shadmehr")
greeting("Shakiba", "Lotf mohammadi")
print(res)
def customSum(a, b):
a *= 2
b *= 2
return a + b
res = customSum(2, 2)
print(res)
print(math.ceil(3.97))
sayHello()
for i in range(5):
time.sleep(0.5)
print(i)
print(time.time())
print(datetime.datetime.now())
print(datetime.date.today())
classes = {
"1": False,
"2": False,
"10": False,
}
userOption = input()
toReserveClass = input()
classId = input()
| [
"bshadmehr76@gmail.com"
] | bshadmehr76@gmail.com |
2eea0463164ddf4460a11b7f06e6574b4aaef4af | 473ea65bb69368e16d02840ce86a9ed3e8bf2dfc | /tornado_ws/config/__init__.py | 58c74108db15cb6a9bb46c0f60048677c370bb5d | [] | no_license | Lin-SiYu/tornado-ws-project-structure | e9c79df63d3d2738447b74f296376cd19c1dcd32 | 0ea63f60e2b30c491e3a8f59a5ee4596664db357 | refs/heads/master | 2023-08-17T17:02:38.721633 | 2020-03-30T07:37:03 | 2020-03-30T07:37:03 | 196,150,069 | 0 | 0 | null | 2023-08-14T22:06:12 | 2019-07-10T06:59:23 | Python | UTF-8 | Python | false | false | 469 | py | from tornado_ws.config import settings_default, settings_person
class Settings():
def __init__(self):
# 集成全局默认配置
self.__setAttr(settings_default)
# 自定义配置(覆盖相同默认配置)
self.__setAttr(settings_person)
def __setAttr(self, conf):
for key in dir(conf):
if key.isupper():
v = getattr(conf, key)
setattr(self, key, v)
setting = Settings()
| [
"214893130@qq.com"
] | 214893130@qq.com |
45bc20530d16439a48bc5d512ec34f4fd5e41670 | f13e7a2568db9ec0b63aa0e89e7976d6ed6511b6 | /conduction.py | 6f3a22f0a2f7222b54a0bc92555d737c87ca5cf8 | [] | no_license | nobody48sheldor/convection | c5d4c1138ad4043ff1301f5c6c49bc342686bd5a | e72f5ddd99ba56defa550817da62776919f93e49 | refs/heads/main | 2023-05-31T22:06:37.861195 | 2021-06-11T14:11:09 | 2021-06-11T14:11:09 | 369,207,448 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,473 | py | import matplotlib.pyplot as plt
import numpy as np
from math import *
from functools import cache
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
from matplotlib import style
style.use('dark_background')
n = int(input("n = "))
T = int(input("T = "))
tmax = float(input("tmax = "))
D = float(input("D = "))
theta = float(input("theta = "))
x = np.linspace(-10, 10, n)
y = np.linspace(-10, 10, n)
X, Y = np.meshgrid(x, y)
t = np.linspace(0, tmax, T)
dx = x[1]-x[0]
dy = y[1]-y[0]
dt = t[1]-t[0]
def psi_0(x, y):
T = theta*((np.exp(-0.2*(x-2)**2)+np.exp(-0.2*(x+2)**2)) * np.exp(-0.1*y**2))
return(T)
Temperature_ = []
def tempertature():
Temp = []
Yj = []
Xw = []
Temp.append(np.array(psi_0(X, Y)))
i = 1
while i < T:
j = 0
Yj = []
while j < n-2:
w = 0
Xw = []
while w < n-2:
if i > 10:
if ((Temp[i-1][j][w] - Temp[i-10][j][w])/dt) > theta*5000/T:
xw = Temp[i-9][j][w]
else:
xw = Temp[i-1][j][w] + ((D*(((Temp[i-1][j][w+2]- 2*Temp[i-1][j][w+1] + Temp[i-1][j][w])/(dx*dx)) + ((Temp[i-1][j+2][w] - 2*Temp[i-1][j+1][w] + Temp[i-1][j][w])/(dy*dy)))) * dt)
else:
xw = Temp[i-1][j][w] + ((D*(((Temp[i-1][j][w+2]- 2*Temp[i-1][j][w+1] + Temp[i-1][j][w])/(dx*dx)) + ((Temp[i-1][j+2][w] - 2*Temp[i-1][j+1][w] + Temp[i-1][j][w])/(dy*dy)))) * dt)
Xw.append(xw)
if x[w] == x[0]:
if y[j] == y[0]:
Temperature_.append(xw)
w = w + 1
Xw.append(xw)
Xw.append(xw)
Yj.append(Xw)
j = j + 1
Yj.append(Xw)
Yj.append(Xw)
Yja = np.array(Yj)
Temp.append(Yja)
i = i + 1
print(i, "/", T)
return(Temp)
Temp = tempertature()
plt.imshow(psi_0(X, Y))
plt.show()
Temperature_.append(Temperature_[T-2])
plt.plot(t, Temperature_)
plt.show()
input("//")
plt.ion()
fig = plt.figure()
ax1 = plt.subplot(projection = '3d')
i = 0
while i < T:
ax1.clear()
ax1.plot_surface(X, Y, Temp[i], cmap = cm.plasma, linewidth=0, alpha = 1, antialiased=True)
ax1.axes.set_xlim3d(left=-10, right=10)
ax1.axes.set_ylim3d(bottom=-10, top=10)
ax1.axes.set_zlim3d(bottom=0, top= theta + theta/20)
ax1.set_title(i)
plt.pause(0.0001)
i = i + 1
| [
"lolmyizi@gmail.com"
] | lolmyizi@gmail.com |
2a4cde8862da66e69e30f44c095c08b78d1f0411 | 1af87952c5ce64b18a1dd7c4bc275656bb6e2c71 | /spikebit/__init__.py | d57ee93e15ee8b5b35c5214ae354ca59b353425b | [
"MIT"
] | permissive | NRC-Lund/spikebit | 276b152ff530ffdcb65423d41290255302442e97 | b086bb78b7a0da224e4f8db2b83582f121d51cd6 | refs/heads/master | 2021-03-22T01:03:15.929124 | 2018-01-30T22:19:48 | 2018-01-30T22:19:48 | 98,477,027 | 6 | 0 | null | null | null | null | UTF-8 | Python | false | false | 72 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: bengt
"""
| [
"bengt@ljungquistinfo"
] | bengt@ljungquistinfo |
d1eac20d6ecb9450cba8f91e1a7e1d4e1e5741a0 | a8933adda6b90ca158096009165bf27b74a2733d | /auroracallback/index.py | 8e612d31c3268553e12c1b19be4ad251306e88d6 | [] | no_license | knighton/aurora-callback | 6c40db9c271b782ca8c14119b8937e3656980a36 | 26efc9069fcd5d48ae55bca3b06e3adf3927164e | refs/heads/master | 2020-12-18T11:53:16.516590 | 2020-01-21T15:05:41 | 2020-01-21T15:05:41 | 235,369,780 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 465 | py | _INDEX = """
<!DOCTYPE HTML>
<head>
<style type="text/css">
html, body, #image {
width: 100%;
height: 100%;
}
body {
background: radial-gradient(
circle at center,
#000 0%,
#002 50%,
#004 65%,
#408 75%,
#824 85%,
#f40 90%,
#fb0 95%,
white 100%
);
}
</style>
</head>
<body>
<img id="image" src="/aurora.png"></img>
</body>
</html>
"""
def get_index():
return _INDEX
| [
"iamknighton@gmail.com"
] | iamknighton@gmail.com |
1cc72afb9b268e15db943f18c80ff81a0263b625 | f829c0afd889a80ad31c6f9202ce5d72ea8e2b05 | /PPO2/ppo2_carracing_custom.py | aacc64bf0b55be36f15806b8a83c254e4b1bfb68 | [] | no_license | HDLuis13/carracing | 267895a66d27232c95891fa7e006eaeef1f43b49 | 6fc13beb9f1a9153253222c54fcf365ce2a8cc02 | refs/heads/master | 2020-06-11T21:32:50.467898 | 2019-07-26T18:18:50 | 2019-07-26T18:18:50 | 194,088,703 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,324 | py | from CarRacing_custom_wrapper import RacingGym
from stable_baselines.common.policies import CnnPolicy
from stable_baselines import PPO2
from stable_baselines.common.vec_env.dummy_vec_env import DummyVecEnv
env = RacingGym(render=False, skip_actions=1, num_frames=4, vae=False)
env = DummyVecEnv([lambda: env])
model = PPO2(CnnPolicy, env=env, verbose=2, tensorboard_log='./t_log/', n_steps=1024)
timesteps = 100000
for i in range(5):
timesteps_total = timesteps*(i+1)
model.learn(total_timesteps=timesteps, tb_log_name="ppo2_custom_noskip_4frames_{}_steps2048".format(timesteps_total), reset_num_timesteps=False)
model.save("./t_log/ppo2_custom_noskip_4frames_{}".format(timesteps_total))
# # Enjoy trained agent
# env = RacingGym(render=True)
# env = DummyVecEnv([lambda: env])
# model = PPO2.load("./t_log/ppo2_custom_350000", env=env, verbose=2, tensorboard_log='./t_log/')
# timesteps = 50000
# for i in range(3):
# timesteps_total = timesteps*(i+1)+350000
# model.learn(total_timesteps=timesteps, tb_log_name="ppo2_custom_{}".format(timesteps_total), reset_num_timesteps=False,)
# model.save("./t_log/ppo2_custom_{}".format(timesteps_total))
#
# obs = env.reset()
#
# while True:
# action, _states = model.predict(obs)
# obs, rewards, dones, info = env.step(action)
# env.close()
| [
"Ib1sP4FZI!"
] | Ib1sP4FZI! |
533bfb1d261afc66bc066454d6815f32e5bd3610 | 03e38bdb6c7d2ce2cb9ebc9796ecdc7d72023ebb | /build/catkin_generated/generate_cached_setup.py | 465c246ce8083b081202f651b85720ee08bad361 | [] | no_license | igorrecioh/ROS | 56497dd700c88bb1ae067659a2902762e084c4d7 | 9d1e324d5c92cb2d9f88d19f5a4f18950ad1a715 | refs/heads/master | 2021-04-28T18:21:04.695248 | 2018-05-15T19:52:48 | 2018-05-15T19:52:48 | 121,870,555 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,297 | py | # -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/kinetic/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, os.path.join('/opt/ros/kinetic/share/catkin/cmake', '..', 'python'))
try:
from catkin.environment_cache import generate_environment_script
except ImportError:
# search for catkin package in all workspaces and prepend to path
for workspace in "/home/igor/catkin_ws/devel;/opt/ros/kinetic".split(';'):
python_path = os.path.join(workspace, 'lib/python2.7/dist-packages')
if os.path.isdir(os.path.join(python_path, 'catkin')):
sys.path.insert(0, python_path)
break
from catkin.environment_cache import generate_environment_script
code = generate_environment_script('/home/igor/catkin_ws/devel/env.sh')
output_filename = '/home/igor/catkin_ws/build/catkin_generated/setup_cached.sh'
with open(output_filename, 'w') as f:
#print('Generate script for cached setup "%s"' % output_filename)
f.write('\n'.join(code))
mode = os.stat(output_filename).st_mode
os.chmod(output_filename, mode | stat.S_IXUSR)
| [
"igor.recio.h@gmail.com"
] | igor.recio.h@gmail.com |
eed3838ed135ccf97025f3c12079ae9021fdf4f9 | 12720c10cd48d1b950470ea3028b125e0950f4b6 | /code/colored_tree.py | 0a6b0c5e67b968ff931efd9a6cb098ec5768140a | [] | no_license | abpauwel/Memoire2020 | a1cfba9e364f1fe289f11012fb7060e8859adfbb | 1c005ed1f22834d7e78a88158e4c16ffa5e1a5cb | refs/heads/master | 2021-01-02T06:07:49.989719 | 2020-02-03T20:07:59 | 2020-02-03T20:07:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,279 | py | import pickle
from sklearn import tree
from Machine_learning import *
import pydotplus
#https://gist.github.com/sawansaurabh/3748a083ffdec38aacb8f43660a5f654
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.metrics import balanced_accuracy_score, make_scorer
BCR = make_scorer(balanced_accuracy_score)
from Machine_learning import worktbl, tbl, matching
worktbl = worktbl.drop(['patientnumber', 'date', 'surgery_date', 'patient_id'], axis=1)
results= pd.DataFrame(columns=["Exercise", "Type_of_algorithm", "Bcr_train", "Bcr_test",'best_feature'])
images = 'from_metaparam'
for exo in matching:
if images == 'from_metaparam':
clf2 = pickle.load(open("modeltoexport\\modelfor_"+str(exo)+".sav", 'rb'))
else :
clf2 = tree.DecisionTreeClassifier(max_depth=3, class_weight='balanced')
x_train, x_test, Y_train, Y_test = train_test_split(worktbl,
tbl[exo].notnull().astype(int).to_frame(),
test_size=0.2, random_state=42)
clf2 = clf2.fit(x_train, Y_train)
predi = clf2.predict(x_test)
bcr_test = balanced_accuracy_score(Y_test, predi)
predi = clf2.predict(x_train)
bcr_train = balanced_accuracy_score(Y_train, predi)
# Get the most important feature
importances = clf2.feature_importances_
# ([-3:] because you need to take the last 20 elements of the array since argsort sorts in ascending order)
best_feature = list(worktbl.columns[np.flip(np.argsort(importances)[-5:])])
results = results.append({"Exercise": exo.split('_')[0],
"Type_of_algorithm": tree.DecisionTreeClassifier(max_depth=3,
class_weight='balanced'),
"Bcr_test": bcr_test, "Bcr_train": bcr_train, 'best_feature': best_feature},
ignore_index=True)
# Create DOT data
dot_data = tree.export_graphviz(clf2,impurity=False, out_file=None,
feature_names=list(worktbl.columns),
class_names=matching[1],filled=True,
rounded=True,
special_characters=True)
# Draw graph
graph = pydotplus.graph_from_dot_data(dot_data)
# Show graph
nodes = graph.get_node_list()
for node in nodes:
if node.get_label():
if node.get_label().split("samples = ")[0]=='<':
if node.get_label().split('class = ')[1].split('>')[0] =='1':
node.set_fillcolor('red')
else:
node.set_fillcolor('green')
else:
node.set_fillcolor('white')
graph.write_png('C:\\Users\cocol\Desktop\memoire\Jéjé_work\\tree_per_exo_dislays\\tree_for'+str(exo)+'.png')
#graph.write_png('C:\\Users\cocol\Desktop\memoire\Jéjé_work\pres\\fourth pres\Diff_bcr_len3\\' + str(exo) + '.png')
#results.to_csv('C:\\Users\cocol\Desktop\memoire\Jéjé_work\\tree_per_exo_dislays\\len1\\results.csv') | [
"cocoloulouj@hotmail.com"
] | cocoloulouj@hotmail.com |
4c93feebd2feaf7fa2ce7f0387adf4b97ef3af37 | efc45d380b627e6fe782c52b0b2efb49bc49515f | /belajar_context/models/__init__.py | e7f6848d5584d10722c2aa5f917ff05ae8626eec | [] | no_license | alirodhi123/odoo-project | 10f72a54548568cbaf89d26859bd46231fbf84be | 106a80b96650c6d7b74761f3b78ca93c11684c3a | refs/heads/master | 2021-07-05T01:07:28.555325 | 2020-09-11T07:05:24 | 2020-09-11T07:05:24 | 163,510,852 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 96 | py | # -*- coding: utf-8 -*-
from . import models
from . import new_object
from . import res_partner | [
"alirodhi123@gmail.com"
] | alirodhi123@gmail.com |
06240216f9210c8e6d145968274d7682c2efaa25 | 5364927a0f594958ef226cd8b42120e96a970beb | /detectors/countauditor.py | 2ba6d830b4429d9f01dfd0aa9dab54dc2415fc0b | [] | no_license | psf/bpo-tracker-cpython | 883dd13f557179ee2f16e38d4f38e53c7f257a4a | 1a94f0977ca025d2baf45ef712ef87f394a59b25 | refs/heads/master | 2023-06-11T23:59:46.300683 | 2023-04-25T12:18:00 | 2023-04-25T12:18:00 | 276,213,165 | 24 | 10 | null | 2023-04-11T14:16:30 | 2020-06-30T21:32:40 | Python | UTF-8 | Python | false | false | 507 | py |
def count_nosy_msg(db, cl, nodeid, newvalues):
''' Update the counts of messages and nosy users on issue edit'''
if 'nosy' in newvalues:
newvalues['nosy_count'] = len(set(newvalues['nosy']))
if 'messages' in newvalues:
newvalues['message_count'] = len(set(newvalues['messages']))
def init(db):
# Should run after the creator and auto-assignee are added
db.issue.audit('create', count_nosy_msg, priority=120)
db.issue.audit('set', count_nosy_msg, priority=120)
| [
"devnull@localhost"
] | devnull@localhost |
00678ab8ff79facecf814370e31c6cd5fe27add6 | 55c250525bd7198ac905b1f2f86d16a44f73e03a | /Python/Flask/Book_evaluator/venv/Lib/encodings/latin_1.py | dc74012c5ec50ada8637c3b65596d11567dc8a16 | [] | no_license | NateWeiler/Resources | 213d18ba86f7cc9d845741b8571b9e2c2c6be916 | bd4a8a82a3e83a381c97d19e5df42cbababfc66c | refs/heads/master | 2023-09-03T17:50:31.937137 | 2023-08-28T23:50:57 | 2023-08-28T23:50:57 | 267,368,545 | 2 | 1 | null | 2022-09-08T15:20:18 | 2020-05-27T16:18:17 | null | UTF-8 | Python | false | false | 129 | py | version https://git-lfs.github.com/spec/v1
oid sha256:b75503e532a27c636477396c855209ff5f3036536d2a4bede0a576c89382b60c
size 1264
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
c78838148274677208d44a9c154ead76fb9dad18 | 05e38f2c1e87590be334dcd9ea6d93e30e34485a | /Week2/5.Displaying Rooms/main.py | 5a6f25b600e20f4cbebcc2cf90542f26eba3724d | [] | no_license | umair-AT-git/OOP-Python | a85899e3ed34ad88f0250cced25e9ba228c352f7 | 5a6802ca3ee9f69af34e950e2bd511ad2610520f | refs/heads/master | 2021-05-25T18:35:31.857177 | 2020-04-09T14:33:00 | 2020-04-09T14:33:00 | 253,871,827 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 614 | py | from room import Room
#instatntiating (creating) an object
kitchen = Room("Kitchen")
#finding out what we learnt up to now
kitchen.set_description("A dank and dirty room buzzing with flies.")
# kitchen.get_description()
kitchen.describe()
dining_hall = Room("Dining_hall")
dining_hall.set_description("Where gosts have their meals")
ballroom = Room("Ballroom")
ballroom.set_description("Where zombies have their parties")
kitchen.link_room(dining_hall, "south")
dining_hall.link_room(kitchen, "north")
dining_hall.link_room(ballroom, "west")
ballroom.link_room(dining_hall, "east")
dining_hall.get_details() | [
"umairisnow@gmail.com"
] | umairisnow@gmail.com |
20b0302f205c194e320b854752d875c8029c0f25 | cf6a4e6a0c114867f8fd830738a0ecffca3ee4b5 | /proyecto1/proceso.py | 4ed97d007207c50e520d5d765dc5494fcf790217 | [] | no_license | 201602458/Proyecto1S1_201602458 | dd2c4efb205f56a7aa649906b2f6b0ed03eda2bf | 185ad5b00ecad595923ad182c08cc1143d5e1797 | refs/heads/master | 2023-03-19T00:00:24.902074 | 2021-03-09T04:06:21 | 2021-03-09T04:06:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,320 | py | import carga
import re
import dato
class Proceso:
lista = []
lista2=[]
var=""
cadena=""
nombre=""
def __init__ (self):
self.archivo = carga.Carga_archivo.contenido
def verificar(self):
#try:
if (self.archivo.isspace() or len(self.archivo) <= 1):
print("Error de archivo")
else:
print("Ejecutandose...")
self.separar()
#except:
#print("Error de procesamiento")
def separar(self):
# try:
print("Creando matriz")
self.lista = re.split('<|>|=|'+chr(32)+'|'+chr(9)+'|'+chr(34)+'|\n|""',self.archivo)
conta=0
for i in range(0, len(self.lista)):
#con el matriz
if self.lista[i]=="nombre":
nombre=self.lista[i+2]
Proceso.nombre=nombre
conta=conta+1
if self.lista[i]=="n":
n=int(self.lista[i+1])
if self.lista[i]=="m":
m=int(self.lista[i+1])
self.var = dato.matriz_dato(n,m,nombre)
self.var.crear(n,m)
#var.recorrer()
if self.lista[i]=="x":
x=self.lista[i+1]
if self.lista[i]=="y":
y=self.lista[i+1]
if self.lista[i] == "/dato":
datos=self.lista[i-1]
self.var.reemplazo(x,y,datos)
self.var.sumatoria()
self.var.graficar()
def sumatoria(self, m_n, m_b):
print("Realizando sumatoria")
c1=0
c2=c1+1
i=len(m_b)-1
j=len(m_b)-1
while c1 <= i:
#print(i)
while c2 <= j:
#print(m_n)
# print(j)
if m_b[c1]==m_b[c2]:
m_n[c1]=self.sum(m_n[c1],m_n[c2])
#print(self.sum(m_n[i],m_n[j]))
m_n.pop(c2)
m_b.pop(c2)
j=len(m_b)-1
i=len(m_b)-1
c2=c2+1
c1=c1+1
c2=c1+1
#print(m_n)
self.texto(m_n)
def sum(self, m_1, m_2):
#total=0
cadena=""
l1 = re.split("-",m_1)
l2 = re.split("-",m_2)
for i in range(0, len(l1)-1):
total=int(l1[i])+int(l2[i])
cadena=cadena+str(total)+"-"
#print(cadena)
return cadena
def buscar(self, nombre):
self.var.buscar(nombre)
self.nombre=nombre
def texto(self, m_n):
Proceso.cadena='<matriz nombre="'+Proceso.nombre+'_Salida">\n'
#print(m_n)
for i in range(0, len(m_n)):
l1 = re.split("-",m_n[i])
for j in range(0, len(l1)-1):
Proceso.cadena=Proceso.cadena+'<dato x='+str(i+1)+' y='+str(j+1)+'>'+str(l1[j])+'</dato>\n'
Proceso.cadena=Proceso.cadena+'</matriz>'
#print(self.cadena)
def salida(self, ruta):
file=open(ruta,"w")
file.write(Proceso.cadena)
file.close()
| [
"30847541+201602458@users.noreply.github.com"
] | 30847541+201602458@users.noreply.github.com |
d9ed45e757f36c4737c4f53b459548e973a94c38 | 042b3e6553dbd61b204bdbad25e05aaeba79dde8 | /tests/ope/test_fqe.py | 2a871634bfc6235fdfc70ba63e851fba1934a267 | [
"MIT"
] | permissive | jkbjh/d3rlpy | 822e51e1c5b4ef37795aa2be089ff5a7ff18af07 | 43f0ba7e420aba077d85c897a38207f0b3ca6d17 | refs/heads/master | 2023-03-20T06:36:55.424681 | 2021-03-17T14:17:40 | 2021-03-17T14:17:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,859 | py | import pytest
import numpy as np
from unittest.mock import Mock
from d3rlpy.ope.fqe import FQE, DiscreteFQE
from d3rlpy.algos import DDPG, DQN
from tests.base_test import base_tester
from tests.algos.algo_test import algo_update_tester
from tests.algos.algo_test import DummyImpl
def ope_tester(ope, observation_shape, action_size=2):
# dummy impl object
impl = DummyImpl(observation_shape, action_size)
base_tester(ope, impl, observation_shape, action_size)
ope._algo.impl = impl
ope.impl = impl
# check save policy
impl.save_policy = Mock()
ope.save_policy("policy.pt", False)
impl.save_policy.assert_called_with("policy.pt", False)
# check predict
x = np.random.random((2, 3)).tolist()
ref_y = np.random.random((2, action_size)).tolist()
impl.predict_best_action = Mock(return_value=ref_y)
y = ope.predict(x)
assert y == ref_y
impl.predict_best_action.assert_called_with(x)
# check predict_value
action = np.random.random((2, action_size)).tolist()
ref_value = np.random.random((2, 3)).tolist()
impl.predict_value = Mock(return_value=ref_value)
value = ope.predict_value(x, action)
assert value == ref_value
impl.predict_value.assert_called_with(x, action, False)
# check sample_action
impl.sample_action = Mock(return_value=ref_y)
try:
y = ope.sample_action(x)
assert y == ref_y
impl.sample_action.assert_called_with(x)
except NotImplementedError:
pass
ope.impl = None
ope._algo.impl = None
@pytest.mark.parametrize("observation_shape", [(100,), (4, 84, 84)])
@pytest.mark.parametrize("action_size", [2])
@pytest.mark.parametrize("q_func_factory", ["mean", "qr", "iqn", "fqf"])
@pytest.mark.parametrize("scaler", [None, "min_max"])
@pytest.mark.parametrize("action_scaler", [None, "min_max"])
def test_fqe(
observation_shape, action_size, q_func_factory, scaler, action_scaler
):
algo = DDPG()
fqe = FQE(
algo=algo,
scaler=scaler,
action_scaler=action_scaler,
q_func_factory=q_func_factory,
)
ope_tester(fqe, observation_shape)
algo.create_impl(observation_shape, action_size)
algo_update_tester(fqe, observation_shape, action_size, discrete=False)
@pytest.mark.parametrize("observation_shape", [(100,), (4, 84, 84)])
@pytest.mark.parametrize("action_size", [2])
@pytest.mark.parametrize("q_func_factory", ["mean", "qr", "iqn", "fqf"])
@pytest.mark.parametrize("scaler", [None, "standard"])
def test_discrete_fqe(observation_shape, action_size, q_func_factory, scaler):
algo = DQN()
fqe = DiscreteFQE(algo=algo, scaler=scaler, q_func_factory=q_func_factory)
ope_tester(fqe, observation_shape)
algo.create_impl(observation_shape, action_size)
algo_update_tester(fqe, observation_shape, action_size, discrete=True)
| [
"takuma.seno@gmail.com"
] | takuma.seno@gmail.com |
1f45f423f9b9c7a6771aa411b46fc92b4c8473ea | c4520d8327124e78a892ef5a75a38669f8cd7d92 | /venv/bin/pip3.6 | 5de7730cde95e1872365e26e4f9afc03673e919d | [] | no_license | arsh9806/GW2019PA1 | 81d62d3d33cfe3bd9e23aff909dd529b91c17035 | c3d12aed77d2810117ce741c48208edc2b6a1f34 | refs/heads/master | 2020-05-31T09:18:13.112929 | 2019-06-04T06:51:12 | 2019-06-04T06:51:12 | 190,209,074 | 2 | 0 | null | 2019-06-04T13:38:46 | 2019-06-04T13:38:46 | null | UTF-8 | Python | false | false | 412 | 6 | #!/Users/ishantkumar/PycharmProjects/GW2019PA1/venv/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==9.0.1','console_scripts','pip3.6'
__requires__ = 'pip==9.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==9.0.1', 'console_scripts', 'pip3.6')()
)
| [
"er.ishant@gmail.com"
] | er.ishant@gmail.com |
00abcd21aed51c4a1ac7470901e912bd24aedc08 | 470bd9cfcbf6f300f1d632f8d0b732aec8432456 | /surveys.py | 5375c1014054929a5a85a291f18aeb4ee86251dc | [] | no_license | hvanlear/flask-survey | 7788609d44ceb3a5243395d7c32f0544b28630bc | 05fd35b248aef4031fe1cbc9ceac9e6602fe4973 | refs/heads/master | 2023-03-24T01:32:49.223643 | 2020-07-12T14:24:51 | 2020-07-12T14:24:51 | 279,079,302 | 0 | 0 | null | 2021-03-20T04:39:57 | 2020-07-12T14:17:21 | Python | UTF-8 | Python | false | false | 1,809 | py | class Question:
"""Question on a questionnaire."""
def __init__(self, question, choices=None, allow_text=False):
"""Create question (assume Yes/No for choices."""
if not choices:
choices = ["Yes", "No"]
self.question = question
self.choices = choices
self.allow_text = allow_text
class Survey:
"""Questionnaire."""
def __init__(self, title, instructions, questions):
"""Create questionnaire."""
self.title = title
self.instructions = instructions
self.questions = questions
satisfaction_survey = Survey(
"Customer Satisfaction Survey",
"Please fill out a survey about your experience with us.",
[
Question("Have you shopped here before?"),
Question("Did someone else shop with you today?"),
Question("On average, how much do you spend a month on frisbees?",
["Less than $10,000", "$10,000 or more"]),
Question("Are you likely to shop here again?"),
])
personality_quiz = Survey(
"Rithm Personality Test",
"Learn more about yourself with our personality quiz!",
[
Question("Do you ever dream about code?"),
Question("Do you ever have nightmares about code?"),
Question("Do you prefer porcupines or hedgehogs?",
["Porcupines", "Hedgehogs"]),
Question("Which is the worst function name, and why?",
["do_stuff()", "run_me()", "wtf()"],
allow_text=True),
]
)
surveys = {
"satisfaction": satisfaction_survey,
"personality": personality_quiz,
}
# In [13]: satisfaction_survey.questions[2].choices
# Out[13]: ['Less than $10,000', '$10,000 or more'] | [
"hvanlear@gmail.com"
] | hvanlear@gmail.com |
05a8f71fc5e7b421ee098845806cc55f6460df06 | 9e204a5b1c5ff4ea3b115ff0559b5af803ab4d15 | /086 Scramble String.py | 24fb5940b4e91bad75604cd71f6ca376a0c51d99 | [
"MIT"
] | permissive | Aminaba123/LeetCode | 178ed1be0733cc7390f30e676eb47cc7f900c5b2 | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | refs/heads/master | 2020-04-20T10:40:00.424279 | 2019-01-31T08:13:58 | 2019-01-31T08:13:58 | 168,795,374 | 1 | 0 | MIT | 2019-02-02T04:50:31 | 2019-02-02T04:50:30 | null | UTF-8 | Python | false | false | 2,347 | py | """
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great":
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
We say that "rgeat" is a scrambled string of "great".
Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".
rgtae
/ \
rg tae
/ \ / \
r g ta e
/ \
t a
We say that "rgtae" is a scrambled string of "great".
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
"""
__author__ = 'Danyang'
class Solution:
def isScramble(self, s1, s2):
"""
dfs
partition and compare
Compare two trees constructed from the two strings respectively. Two trees are scramble of the other iff A's
left/right subtree is the scramble of B's left/right subtree or A's left/right subtree is the scramble of B's
right/left subtree.
.....|... vs. .....|... or
...|..... vs. .....|...
:param s1:
:param s2:
:return: boolean
"""
if len(s1)!=len(s2):
return False
chars = [0 for _ in xrange(26)]
for char in s1:
chars[ord(char)-ord('a')] += 1
for char in s2:
chars[ord(char)-ord('a')] -= 1
# if filter(lambda x: x!=0, chars):
# return False
for val in chars:
if val!=0:
return False
if len(s1)==1:
return True
for i in xrange(1, len(s1)):
if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]) or \
self.isScramble(s1[:i], s2[-i:]) and self.isScramble(s1[i:], s2[:len(s2)-i]):
return True
return False
if __name__=="__main__":
assert Solution().isScramble("abc", "bca")==True
| [
"zhangdanyangg@gmail.com"
] | zhangdanyangg@gmail.com |
c37b5e7c091393c55c01af84e23f3f883de3ea13 | 7ae9081aff882476ad0caa687ca41796e2035f85 | /planout/apps/accounts/migrations/0005_auto_20150301_1811.py | 176b7b2a6ed4e66694227f5ede41151cde8c9ee6 | [] | no_license | siolag161/planout | eb6b8720dfe0334d379c1040d607bb459a8e695a | f967db9636618906345132d006c2f9a597025a0f | refs/heads/master | 2020-04-14T13:17:26.011810 | 2015-03-21T11:53:48 | 2015-03-21T11:53:48 | 32,376,449 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 842 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
import core.fields
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_basicuser_description'),
]
operations = [
migrations.AddField(
model_name='basicuser',
name='modified',
field=core.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False),
preserve_default=True,
),
migrations.AlterField(
model_name='basicuser',
name='date_joined',
field=core.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='date joined', editable=False),
preserve_default=True,
),
]
| [
"thanh.phan@outlook.com"
] | thanh.phan@outlook.com |
908dfc27dc87c8d51d9505ac7c81c7bc87bf3365 | d4ea02450749cb8db5d8d557a4c2616308b06a45 | /students/Craig_Morton/lesson02/Grid_Exercise.py | 0f252ebf8f61bafc0bf5bb26bf4742c54c471952 | [] | no_license | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | 75421a5bdd6233379443fc310da866ebfcd049fe | e298b1151dab639659d8dfa56f47bcb43dd3438f | refs/heads/master | 2021-06-16T15:41:07.312247 | 2019-07-17T16:02:47 | 2019-07-17T16:02:47 | 115,212,391 | 13 | 160 | null | 2019-11-13T16:07:35 | 2017-12-23T17:52:41 | Python | UTF-8 | Python | false | false | 1,708 | py | # ------------------------------------------------- #
# Title: Lesson 2, pt 1/3, Grid Printer Exercise
# Dev: Craig Morton
# Date: 8/13/2018
# Change Log: CraigM, 8/13/2018, Grid Printer Exercise
# ------------------------------------------------ #
# Variables
plus = "+ "
minus = "- "
pipe = "| "
space = " "
# Grid Part One: Simple grid
def print_grid_one():
"""Prints grid without parameter"""
size = 4
print(plus + minus * size + plus + minus * size + plus)
for y in range(1, size + 1):
print(pipe + space * size + pipe + space * size + pipe)
print(plus + minus * size + plus + minus * size + plus)
for y in range(1, size + 1):
print(pipe + space * size + pipe + space * size + pipe)
print(plus + minus * size + plus + minus * size + plus)
# Grid Part Two: Grid with one parameter
def print_grid_two(size):
"""Prints grid with one parameter"""
print(plus + minus * size + plus + minus * size + plus)
for y in range(1, size + 1):
print(pipe + space * size + pipe + space * size + pipe)
print(plus + minus * size + plus + minus * size + plus)
for y in range(1, size + 1):
print(pipe + space * size + pipe + space * size + pipe)
print(plus + minus * size + plus + minus * size + plus)
# Grid Part Three: Grid with two parameters
def print_grid_three(size1, size2):
"""Prints grid with two parameters"""
row = plus + minus * size2
column = pipe + space * size2
for y in range(0, size1):
print(row * size1 + plus)
for x in range(0, size2):
print(column * size1 + pipe)
print(row * size1 + plus)
print_grid_one()
print_grid_two(10)
print_grid_three(25, 2)
| [
"cmorton11@gmail.com"
] | cmorton11@gmail.com |
118f50c99b8c2573dae735c4dfefb1a4ba180572 | cb9de312679d09fb6fae53d0b724c3d91ac561f3 | /Array_Pasta2/Array_Pasta/wsgi.py | 67f5a31deb2dd99ae544c83aff6e0216f8d4273e | [] | no_license | csc322projectgroup/project | 77232f1de85f5c26b5a8775707bac73cf28b2442 | 6fc31484bcfbf261598a7dbc7444bc31e8ddd950 | refs/heads/main | 2023-01-24T00:59:06.942385 | 2020-12-12T15:05:37 | 2020-12-12T15:05:37 | 304,429,471 | 2 | 1 | null | 2020-12-08T18:38:05 | 2020-10-15T19:33:37 | HTML | UTF-8 | Python | false | false | 399 | py | """
WSGI config for Array_Pasta project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Array_Pasta.settings')
application = get_wsgi_application()
| [
"andresjm30@gmail.com"
] | andresjm30@gmail.com |
0ceccfc0f20161b467e5f633c3340f79cb489e0b | 48e124e97cc776feb0ad6d17b9ef1dfa24e2e474 | /sdk/python/pulumi_azure_native/kubernetesconfiguration/v20210301/source_control_configuration.py | dde54f5999b02095632c8983dd8935df94af9835 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | bpkgoud/pulumi-azure-native | 0817502630062efbc35134410c4a784b61a4736d | a3215fe1b87fba69294f248017b1591767c2b96c | refs/heads/master | 2023-08-29T22:39:49.984212 | 2021-11-15T12:43:41 | 2021-11-15T12:43:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 28,142 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['SourceControlConfigurationArgs', 'SourceControlConfiguration']
@pulumi.input_type
class SourceControlConfigurationArgs:
def __init__(__self__, *,
cluster_name: pulumi.Input[str],
cluster_resource_name: pulumi.Input[str],
cluster_rp: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
configuration_protected_settings: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
enable_helm_operator: Optional[pulumi.Input[bool]] = None,
helm_operator_properties: Optional[pulumi.Input['HelmOperatorPropertiesArgs']] = None,
operator_instance_name: Optional[pulumi.Input[str]] = None,
operator_namespace: Optional[pulumi.Input[str]] = None,
operator_params: Optional[pulumi.Input[str]] = None,
operator_scope: Optional[pulumi.Input[Union[str, 'OperatorScopeType']]] = None,
operator_type: Optional[pulumi.Input[Union[str, 'OperatorType']]] = None,
repository_url: Optional[pulumi.Input[str]] = None,
source_control_configuration_name: Optional[pulumi.Input[str]] = None,
ssh_known_hosts_contents: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a SourceControlConfiguration resource.
:param pulumi.Input[str] cluster_name: The name of the kubernetes cluster.
:param pulumi.Input[str] cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).
:param pulumi.Input[str] cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] configuration_protected_settings: Name-value pairs of protected configuration settings for the configuration
:param pulumi.Input[bool] enable_helm_operator: Option to enable Helm Operator for this git configuration.
:param pulumi.Input['HelmOperatorPropertiesArgs'] helm_operator_properties: Properties for Helm operator.
:param pulumi.Input[str] operator_instance_name: Instance name of the operator - identifying the specific configuration.
:param pulumi.Input[str] operator_namespace: The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.
:param pulumi.Input[str] operator_params: Any Parameters for the Operator instance in string format.
:param pulumi.Input[Union[str, 'OperatorScopeType']] operator_scope: Scope at which the operator will be installed.
:param pulumi.Input[Union[str, 'OperatorType']] operator_type: Type of the operator
:param pulumi.Input[str] repository_url: Url of the SourceControl Repository.
:param pulumi.Input[str] source_control_configuration_name: Name of the Source Control Configuration.
:param pulumi.Input[str] ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances
"""
pulumi.set(__self__, "cluster_name", cluster_name)
pulumi.set(__self__, "cluster_resource_name", cluster_resource_name)
pulumi.set(__self__, "cluster_rp", cluster_rp)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if configuration_protected_settings is not None:
pulumi.set(__self__, "configuration_protected_settings", configuration_protected_settings)
if enable_helm_operator is not None:
pulumi.set(__self__, "enable_helm_operator", enable_helm_operator)
if helm_operator_properties is not None:
pulumi.set(__self__, "helm_operator_properties", helm_operator_properties)
if operator_instance_name is not None:
pulumi.set(__self__, "operator_instance_name", operator_instance_name)
if operator_namespace is None:
operator_namespace = 'default'
if operator_namespace is not None:
pulumi.set(__self__, "operator_namespace", operator_namespace)
if operator_params is not None:
pulumi.set(__self__, "operator_params", operator_params)
if operator_scope is not None:
pulumi.set(__self__, "operator_scope", operator_scope)
if operator_type is not None:
pulumi.set(__self__, "operator_type", operator_type)
if repository_url is not None:
pulumi.set(__self__, "repository_url", repository_url)
if source_control_configuration_name is not None:
pulumi.set(__self__, "source_control_configuration_name", source_control_configuration_name)
if ssh_known_hosts_contents is not None:
pulumi.set(__self__, "ssh_known_hosts_contents", ssh_known_hosts_contents)
@property
@pulumi.getter(name="clusterName")
def cluster_name(self) -> pulumi.Input[str]:
"""
The name of the kubernetes cluster.
"""
return pulumi.get(self, "cluster_name")
@cluster_name.setter
def cluster_name(self, value: pulumi.Input[str]):
pulumi.set(self, "cluster_name", value)
@property
@pulumi.getter(name="clusterResourceName")
def cluster_resource_name(self) -> pulumi.Input[str]:
"""
The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).
"""
return pulumi.get(self, "cluster_resource_name")
@cluster_resource_name.setter
def cluster_resource_name(self, value: pulumi.Input[str]):
pulumi.set(self, "cluster_resource_name", value)
@property
@pulumi.getter(name="clusterRp")
def cluster_rp(self) -> pulumi.Input[str]:
"""
The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).
"""
return pulumi.get(self, "cluster_rp")
@cluster_rp.setter
def cluster_rp(self, value: pulumi.Input[str]):
pulumi.set(self, "cluster_rp", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="configurationProtectedSettings")
def configuration_protected_settings(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
Name-value pairs of protected configuration settings for the configuration
"""
return pulumi.get(self, "configuration_protected_settings")
@configuration_protected_settings.setter
def configuration_protected_settings(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "configuration_protected_settings", value)
@property
@pulumi.getter(name="enableHelmOperator")
def enable_helm_operator(self) -> Optional[pulumi.Input[bool]]:
"""
Option to enable Helm Operator for this git configuration.
"""
return pulumi.get(self, "enable_helm_operator")
@enable_helm_operator.setter
def enable_helm_operator(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable_helm_operator", value)
@property
@pulumi.getter(name="helmOperatorProperties")
def helm_operator_properties(self) -> Optional[pulumi.Input['HelmOperatorPropertiesArgs']]:
"""
Properties for Helm operator.
"""
return pulumi.get(self, "helm_operator_properties")
@helm_operator_properties.setter
def helm_operator_properties(self, value: Optional[pulumi.Input['HelmOperatorPropertiesArgs']]):
pulumi.set(self, "helm_operator_properties", value)
@property
@pulumi.getter(name="operatorInstanceName")
def operator_instance_name(self) -> Optional[pulumi.Input[str]]:
"""
Instance name of the operator - identifying the specific configuration.
"""
return pulumi.get(self, "operator_instance_name")
@operator_instance_name.setter
def operator_instance_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "operator_instance_name", value)
@property
@pulumi.getter(name="operatorNamespace")
def operator_namespace(self) -> Optional[pulumi.Input[str]]:
"""
The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.
"""
return pulumi.get(self, "operator_namespace")
@operator_namespace.setter
def operator_namespace(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "operator_namespace", value)
@property
@pulumi.getter(name="operatorParams")
def operator_params(self) -> Optional[pulumi.Input[str]]:
"""
Any Parameters for the Operator instance in string format.
"""
return pulumi.get(self, "operator_params")
@operator_params.setter
def operator_params(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "operator_params", value)
@property
@pulumi.getter(name="operatorScope")
def operator_scope(self) -> Optional[pulumi.Input[Union[str, 'OperatorScopeType']]]:
"""
Scope at which the operator will be installed.
"""
return pulumi.get(self, "operator_scope")
@operator_scope.setter
def operator_scope(self, value: Optional[pulumi.Input[Union[str, 'OperatorScopeType']]]):
pulumi.set(self, "operator_scope", value)
@property
@pulumi.getter(name="operatorType")
def operator_type(self) -> Optional[pulumi.Input[Union[str, 'OperatorType']]]:
"""
Type of the operator
"""
return pulumi.get(self, "operator_type")
@operator_type.setter
def operator_type(self, value: Optional[pulumi.Input[Union[str, 'OperatorType']]]):
pulumi.set(self, "operator_type", value)
@property
@pulumi.getter(name="repositoryUrl")
def repository_url(self) -> Optional[pulumi.Input[str]]:
"""
Url of the SourceControl Repository.
"""
return pulumi.get(self, "repository_url")
@repository_url.setter
def repository_url(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "repository_url", value)
@property
@pulumi.getter(name="sourceControlConfigurationName")
def source_control_configuration_name(self) -> Optional[pulumi.Input[str]]:
"""
Name of the Source Control Configuration.
"""
return pulumi.get(self, "source_control_configuration_name")
@source_control_configuration_name.setter
def source_control_configuration_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "source_control_configuration_name", value)
@property
@pulumi.getter(name="sshKnownHostsContents")
def ssh_known_hosts_contents(self) -> Optional[pulumi.Input[str]]:
"""
Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances
"""
return pulumi.get(self, "ssh_known_hosts_contents")
@ssh_known_hosts_contents.setter
def ssh_known_hosts_contents(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "ssh_known_hosts_contents", value)
class SourceControlConfiguration(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
cluster_name: Optional[pulumi.Input[str]] = None,
cluster_resource_name: Optional[pulumi.Input[str]] = None,
cluster_rp: Optional[pulumi.Input[str]] = None,
configuration_protected_settings: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
enable_helm_operator: Optional[pulumi.Input[bool]] = None,
helm_operator_properties: Optional[pulumi.Input[pulumi.InputType['HelmOperatorPropertiesArgs']]] = None,
operator_instance_name: Optional[pulumi.Input[str]] = None,
operator_namespace: Optional[pulumi.Input[str]] = None,
operator_params: Optional[pulumi.Input[str]] = None,
operator_scope: Optional[pulumi.Input[Union[str, 'OperatorScopeType']]] = None,
operator_type: Optional[pulumi.Input[Union[str, 'OperatorType']]] = None,
repository_url: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
source_control_configuration_name: Optional[pulumi.Input[str]] = None,
ssh_known_hosts_contents: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
The SourceControl Configuration object returned in Get & Put response.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] cluster_name: The name of the kubernetes cluster.
:param pulumi.Input[str] cluster_resource_name: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).
:param pulumi.Input[str] cluster_rp: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] configuration_protected_settings: Name-value pairs of protected configuration settings for the configuration
:param pulumi.Input[bool] enable_helm_operator: Option to enable Helm Operator for this git configuration.
:param pulumi.Input[pulumi.InputType['HelmOperatorPropertiesArgs']] helm_operator_properties: Properties for Helm operator.
:param pulumi.Input[str] operator_instance_name: Instance name of the operator - identifying the specific configuration.
:param pulumi.Input[str] operator_namespace: The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.
:param pulumi.Input[str] operator_params: Any Parameters for the Operator instance in string format.
:param pulumi.Input[Union[str, 'OperatorScopeType']] operator_scope: Scope at which the operator will be installed.
:param pulumi.Input[Union[str, 'OperatorType']] operator_type: Type of the operator
:param pulumi.Input[str] repository_url: Url of the SourceControl Repository.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[str] source_control_configuration_name: Name of the Source Control Configuration.
:param pulumi.Input[str] ssh_known_hosts_contents: Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: SourceControlConfigurationArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
The SourceControl Configuration object returned in Get & Put response.
:param str resource_name: The name of the resource.
:param SourceControlConfigurationArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(SourceControlConfigurationArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
cluster_name: Optional[pulumi.Input[str]] = None,
cluster_resource_name: Optional[pulumi.Input[str]] = None,
cluster_rp: Optional[pulumi.Input[str]] = None,
configuration_protected_settings: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
enable_helm_operator: Optional[pulumi.Input[bool]] = None,
helm_operator_properties: Optional[pulumi.Input[pulumi.InputType['HelmOperatorPropertiesArgs']]] = None,
operator_instance_name: Optional[pulumi.Input[str]] = None,
operator_namespace: Optional[pulumi.Input[str]] = None,
operator_params: Optional[pulumi.Input[str]] = None,
operator_scope: Optional[pulumi.Input[Union[str, 'OperatorScopeType']]] = None,
operator_type: Optional[pulumi.Input[Union[str, 'OperatorType']]] = None,
repository_url: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
source_control_configuration_name: Optional[pulumi.Input[str]] = None,
ssh_known_hosts_contents: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = SourceControlConfigurationArgs.__new__(SourceControlConfigurationArgs)
if cluster_name is None and not opts.urn:
raise TypeError("Missing required property 'cluster_name'")
__props__.__dict__["cluster_name"] = cluster_name
if cluster_resource_name is None and not opts.urn:
raise TypeError("Missing required property 'cluster_resource_name'")
__props__.__dict__["cluster_resource_name"] = cluster_resource_name
if cluster_rp is None and not opts.urn:
raise TypeError("Missing required property 'cluster_rp'")
__props__.__dict__["cluster_rp"] = cluster_rp
__props__.__dict__["configuration_protected_settings"] = configuration_protected_settings
__props__.__dict__["enable_helm_operator"] = enable_helm_operator
__props__.__dict__["helm_operator_properties"] = helm_operator_properties
__props__.__dict__["operator_instance_name"] = operator_instance_name
if operator_namespace is None:
operator_namespace = 'default'
__props__.__dict__["operator_namespace"] = operator_namespace
__props__.__dict__["operator_params"] = operator_params
__props__.__dict__["operator_scope"] = operator_scope
__props__.__dict__["operator_type"] = operator_type
__props__.__dict__["repository_url"] = repository_url
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["source_control_configuration_name"] = source_control_configuration_name
__props__.__dict__["ssh_known_hosts_contents"] = ssh_known_hosts_contents
__props__.__dict__["compliance_status"] = None
__props__.__dict__["name"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["repository_public_key"] = None
__props__.__dict__["system_data"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-native:kubernetesconfiguration:SourceControlConfiguration"), pulumi.Alias(type_="azure-native:kubernetesconfiguration/v20191101preview:SourceControlConfiguration"), pulumi.Alias(type_="azure-native:kubernetesconfiguration/v20200701preview:SourceControlConfiguration"), pulumi.Alias(type_="azure-native:kubernetesconfiguration/v20201001preview:SourceControlConfiguration"), pulumi.Alias(type_="azure-native:kubernetesconfiguration/v20210501preview:SourceControlConfiguration"), pulumi.Alias(type_="azure-native:kubernetesconfiguration/v20211101preview:SourceControlConfiguration")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(SourceControlConfiguration, __self__).__init__(
'azure-native:kubernetesconfiguration/v20210301:SourceControlConfiguration',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'SourceControlConfiguration':
"""
Get an existing SourceControlConfiguration resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = SourceControlConfigurationArgs.__new__(SourceControlConfigurationArgs)
__props__.__dict__["compliance_status"] = None
__props__.__dict__["configuration_protected_settings"] = None
__props__.__dict__["enable_helm_operator"] = None
__props__.__dict__["helm_operator_properties"] = None
__props__.__dict__["name"] = None
__props__.__dict__["operator_instance_name"] = None
__props__.__dict__["operator_namespace"] = None
__props__.__dict__["operator_params"] = None
__props__.__dict__["operator_scope"] = None
__props__.__dict__["operator_type"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["repository_public_key"] = None
__props__.__dict__["repository_url"] = None
__props__.__dict__["ssh_known_hosts_contents"] = None
__props__.__dict__["system_data"] = None
__props__.__dict__["type"] = None
return SourceControlConfiguration(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="complianceStatus")
def compliance_status(self) -> pulumi.Output['outputs.ComplianceStatusResponse']:
"""
Compliance Status of the Configuration
"""
return pulumi.get(self, "compliance_status")
@property
@pulumi.getter(name="configurationProtectedSettings")
def configuration_protected_settings(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Name-value pairs of protected configuration settings for the configuration
"""
return pulumi.get(self, "configuration_protected_settings")
@property
@pulumi.getter(name="enableHelmOperator")
def enable_helm_operator(self) -> pulumi.Output[Optional[bool]]:
"""
Option to enable Helm Operator for this git configuration.
"""
return pulumi.get(self, "enable_helm_operator")
@property
@pulumi.getter(name="helmOperatorProperties")
def helm_operator_properties(self) -> pulumi.Output[Optional['outputs.HelmOperatorPropertiesResponse']]:
"""
Properties for Helm operator.
"""
return pulumi.get(self, "helm_operator_properties")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
The name of the resource
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="operatorInstanceName")
def operator_instance_name(self) -> pulumi.Output[Optional[str]]:
"""
Instance name of the operator - identifying the specific configuration.
"""
return pulumi.get(self, "operator_instance_name")
@property
@pulumi.getter(name="operatorNamespace")
def operator_namespace(self) -> pulumi.Output[Optional[str]]:
"""
The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.
"""
return pulumi.get(self, "operator_namespace")
@property
@pulumi.getter(name="operatorParams")
def operator_params(self) -> pulumi.Output[Optional[str]]:
"""
Any Parameters for the Operator instance in string format.
"""
return pulumi.get(self, "operator_params")
@property
@pulumi.getter(name="operatorScope")
def operator_scope(self) -> pulumi.Output[Optional[str]]:
"""
Scope at which the operator will be installed.
"""
return pulumi.get(self, "operator_scope")
@property
@pulumi.getter(name="operatorType")
def operator_type(self) -> pulumi.Output[Optional[str]]:
"""
Type of the operator
"""
return pulumi.get(self, "operator_type")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
"""
The provisioning state of the resource provider.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="repositoryPublicKey")
def repository_public_key(self) -> pulumi.Output[str]:
"""
Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user).
"""
return pulumi.get(self, "repository_public_key")
@property
@pulumi.getter(name="repositoryUrl")
def repository_url(self) -> pulumi.Output[Optional[str]]:
"""
Url of the SourceControl Repository.
"""
return pulumi.get(self, "repository_url")
@property
@pulumi.getter(name="sshKnownHostsContents")
def ssh_known_hosts_contents(self) -> pulumi.Output[Optional[str]]:
"""
Base64-encoded known_hosts contents containing public SSH keys required to access private Git instances
"""
return pulumi.get(self, "ssh_known_hosts_contents")
@property
@pulumi.getter(name="systemData")
def system_data(self) -> pulumi.Output['outputs.SystemDataResponse']:
"""
Top level metadata https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-contracts.md#system-metadata-for-all-azure-resources
"""
return pulumi.get(self, "system_data")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
"""
return pulumi.get(self, "type")
| [
"noreply@github.com"
] | bpkgoud.noreply@github.com |
8354a72b23d29710df17f8b2298c4dae1fdaa8fe | 59599bb9485aa3d5043bcbdc3dde535c0ea8e362 | /tests/index/test_signup.py | b3377b73156c542fb7ab56f855056f92556366e8 | [] | no_license | UsmanAbbasi1/AutomationPracticeSolution | 19331ddaa1308c09910b181ab3412697abd32d0c | 1fe782c5deb437f6a4916c942652233faae6771e | refs/heads/master | 2022-04-15T04:55:13.690859 | 2020-03-29T15:14:05 | 2020-03-29T15:14:05 | 250,558,106 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 685 | py | from pages.index.index_page import IndexPage
from tests.base_test import BaseTest
class TestSignup(BaseTest):
def setUp(self):
super().setUp()
self.index_page = IndexPage(self.driver)
self.driver.get(self.index_page.base_url)
def test_signup_successfully(self):
self.index_page.click_login_link()
# Make sure to give new email_address every time when signing up
self.index_page.click_create_account_and_enter_email_address('testuser+123@gmail.com')
self.index_page.fill_sign_up_form()
self.assertIsNotNone(self.index_page.sign_out_button)
self.assertIsNotNone(self.index_page.customer_account_button)
| [
"usman.abasi@hotmail.com"
] | usman.abasi@hotmail.com |
feeb66ab18cc3610d802384e13ea3b8f06daf4ad | a6bc38613f35c23c62772a5a6edbebbf39410c29 | /source/XCat_Models/K_Correction_Models/pyfits/column.py | 2586ca5f80bf2d70a7b84071e30bac9f4b2536d9 | [] | no_license | afarahi/XMAPGEN | 6d99efd7da74f101544590215b56d5d83882b379 | 51ac980294a782717a4a758a302609433aaaf7a8 | refs/heads/master | 2020-12-24T20:52:26.931429 | 2016-05-17T16:24:20 | 2016-05-17T16:24:20 | 58,937,514 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 72,240 | py | import copy
import operator
import re
import sys
import warnings
import weakref
import numpy as np
from numpy import char as chararray
from .extern.six import iteritems, string_types
from .extern.six.moves import reduce
from .card import Card
from .util import (lazyproperty, pairwise, _is_int, _convert_array,
encode_ascii, indent, isiterable, cmp)
from .verify import VerifyError, VerifyWarning
__all__ = ['Column', 'ColDefs', 'Delayed']
# mapping from TFORM data type to numpy data type (code)
# L: Logical (Boolean)
# B: Unsigned Byte
# I: 16-bit Integer
# J: 32-bit Integer
# K: 64-bit Integer
# E: Single-precision Floating Point
# D: Double-precision Floating Point
# C: Single-precision Complex
# M: Double-precision Complex
# A: Character
FITS2NUMPY = {'L': 'i1', 'B': 'u1', 'I': 'i2', 'J': 'i4', 'K': 'i8', 'E': 'f4',
'D': 'f8', 'C': 'c8', 'M': 'c16', 'A': 'a'}
# the inverse dictionary of the above
NUMPY2FITS = dict([(val, key) for key, val in iteritems(FITS2NUMPY)])
# Normally booleans are represented as ints in pyfits, but if passed in a numpy
# boolean array, that should be supported
NUMPY2FITS['b1'] = 'L'
# Add unsigned types, which will be stored as signed ints with a TZERO card.
NUMPY2FITS['u2'] = 'I'
NUMPY2FITS['u4'] = 'J'
NUMPY2FITS['u8'] = 'K'
# This is the order in which values are converted to FITS types
# Note that only double precision floating point/complex are supported
FORMATORDER = ['L', 'B', 'I', 'J', 'K', 'D', 'M', 'A']
# mapping from ASCII table TFORM data type to numpy data type
# A: Character
# I: Integer (32-bit)
# J: Integer (64-bit; non-standard)
# F: Float (32-bit; fixed decimal notation)
# E: Float (32-bit; exponential notation)
# D: Float (64-bit; exponential notation, always 64-bit by convention)
ASCII2NUMPY = {'A': 'a', 'I': 'i4', 'J': 'i8', 'F': 'f4', 'E': 'f4',
'D': 'f8'}
# Maps FITS ASCII column format codes to the appropriate Python string
# formatting codes for that type.
ASCII2STR = {'A': 's', 'I': 'd', 'J': 'd', 'F': 'f', 'E': 'E', 'D': 'E'}
# For each ASCII table format code, provides a default width (and decimal
# precision) for when one isn't given explicity in the column format
ASCII_DEFAULT_WIDTHS= {'A': (1, 0), 'I': (10, 0), 'J': (15, 0),
'E': (15, 7), 'F': (16, 7), 'D': (25, 17)}
# lists of column/field definition common names and keyword names, make
# sure to preserve the one-to-one correspondence when updating the list(s).
# Use lists, instead of dictionaries so the names can be displayed in a
# preferred order.
KEYWORD_NAMES = ['TTYPE', 'TFORM', 'TUNIT', 'TNULL', 'TSCAL', 'TZERO',
'TDISP', 'TBCOL', 'TDIM']
KEYWORD_ATTRIBUTES = ['name', 'format', 'unit', 'null', 'bscale', 'bzero',
'disp', 'start', 'dim']
"""This is a list of the attributes that can be set on `Column` objects."""
# TFORMn regular expression
TFORMAT_RE = re.compile(r'(?P<repeat>^[0-9]*)(?P<format>[LXBIJKAEDCMPQ])'
r'(?P<option>[!-~]*)', re.I)
# TFORMn for ASCII tables; two different versions depending on whether
# the format is floating-point or not; allows empty values for width
# in which case defaults are used
TFORMAT_ASCII_RE = re.compile(r'(?:(?P<format>[AIJ])(?P<width>[0-9]+)?)|'
r'(?:(?P<formatf>[FED])'
r'(?:(?P<widthf>[0-9]+)\.'
r'(?P<precision>[0-9]+))?)')
# table definition keyword regular expression
TDEF_RE = re.compile(r'(?P<label>^T[A-Z]*)(?P<num>[1-9][0-9 ]*$)')
# table dimension keyword regular expression (fairly flexible with whitespace)
TDIM_RE = re.compile(r'\(\s*(?P<dims>(?:\d+,\s*)+\s*\d+)\s*\)\s*')
ASCIITNULL = 0 # value for ASCII table cell with value = TNULL
# this can be reset by user.
# The default placeholder to use for NULL values in ASCII tables when
# converting from binary to ASCII tables
DEFAULT_ASCII_TNULL = '---'
class Delayed(object):
"""Delayed file-reading data."""
def __init__(self, hdu=None, field=None):
self.hdu = weakref.proxy(hdu)
self.field = field
def __getitem__(self, key):
# This forces the data for the HDU to be read, which will replace
# the corresponding Delayed objects in the Tables Columns to be
# transformed into ndarrays. It will also return the value of the
# requested data element.
return self.hdu.data[key][self.field]
class _BaseColumnFormat(str):
"""
Base class for binary table column formats (just called _ColumnFormat)
and ASCII table column formats (_AsciiColumnFormat).
"""
def __eq__(self, other):
if not other:
return False
if isinstance(other, str):
if not isinstance(other, self.__class__):
try:
other = self.__class__(other)
except ValueError:
return False
else:
return False
return self.canonical == other.canonical
def __hash__(self):
return hash(self.canonical)
@classmethod
def from_column_format(cls, format):
"""Creates a column format object from another column format object
regardless of their type.
That is, this can convert a _ColumnFormat to an _AsciiColumnFormat
or vice versa at least in cases where a direct translation is possible.
"""
return cls.from_recformat(format.recformat)
class _ColumnFormat(_BaseColumnFormat):
"""
Represents a FITS binary table column format.
This is an enhancement over using a normal string for the format, since the
repeat count, format code, and option are available as separate attributes,
and smart comparison is used. For example 1J == J.
"""
def __new__(cls, format):
self = super(_ColumnFormat, cls).__new__(cls, format)
self.repeat, self.format, self.option = _parse_tformat(format)
self.format = self.format.upper()
if self.format in ('P', 'Q'):
# TODO: There should be a generic factory that returns either
# _FormatP or _FormatQ as appropriate for a given TFORMn
if self.format == 'P':
recformat = _FormatP.from_tform(format)
else:
recformat = _FormatQ.from_tform(format)
# Format of variable length arrays
self.p_format = recformat.format
else:
self.p_format = None
return self
@classmethod
def from_recformat(cls, recformat):
"""Creates a column format from a Numpy record dtype format."""
return cls(_convert_format(recformat, reverse=True))
@lazyproperty
def recformat(self):
"""Returns the equivalent Numpy record format string."""
return _convert_format(self)
@lazyproperty
def canonical(self):
"""
Returns a 'canonical' string representation of this format.
This is in the proper form of rTa where T is the single character data
type code, a is the optional part, and r is the repeat. If repeat == 1
(the default) it is left out of this representation.
"""
if self.repeat == 1:
repeat = ''
else:
repeat = str(self.repeat)
return '%s%s%s' % (repeat, self.format, self.option)
class _AsciiColumnFormat(_BaseColumnFormat):
"""Similar to _ColumnFormat but specifically for columns in ASCII tables.
The formats of ASCII table columns and binary table columns are inherently
incompatible in FITS. They don't support the same ranges and types of
values, and even reuse format codes in subtly different ways. For example
the format code 'Iw' in ASCII columns refers to any integer whose string
representation is at most w characters wide, so 'I' can represent
effectively any integer that will fit in a FITS columns. Whereas for
binary tables 'I' very explicitly refers to a 16-bit signed integer.
Conversions between the two column formats can be performed using the
``to/from_binary`` methods on this class, or the ``to/from_ascii``
methods on the `_ColumnFormat` class. But again, not all conversions are
possible and may result in a `ValueError`.
"""
def __new__(cls, format, strict=False):
self = super(_AsciiColumnFormat, cls).__new__(cls, format)
self.format, self.width, self.precision = \
_parse_ascii_tformat(format, strict)
# This is to support handling logical (boolean) data from binary tables
# in an ASCII table
self._pseudo_logical = False
return self
@classmethod
def from_column_format(cls, format):
inst = cls.from_recformat(format.recformat)
# Hack
if format.format == 'L':
inst._pseudo_logical = True
return inst
@classmethod
def from_recformat(cls, recformat):
"""Creates a column format from a Numpy record dtype format."""
return cls(_convert_ascii_format(recformat, reverse=True))
@lazyproperty
def recformat(self):
"""Returns the equivalent Numpy record format string."""
return _convert_ascii_format(self)
@lazyproperty
def canonical(self):
"""
Returns a 'canonical' string representation of this format.
This is in the proper form of Tw.d where T is the single character data
type code, w is the width in characters for this field, and d is the
number of digits after the decimal place (for format codes 'E', 'F',
and 'D' only).
"""
if self.format in ('E', 'F', 'D'):
return '%s%s.%s' % (self.format, self.width, self.precision)
return '%s%s' % (self.format, self.width)
class _FormatX(str):
"""For X format in binary tables."""
def __new__(cls, repeat=1):
nbytes = ((repeat - 1) // 8) + 1
# use an array, even if it is only ONE u1 (i.e. use tuple always)
obj = super(_FormatX, cls).__new__(cls, repr((nbytes,)) + 'u1')
obj.repeat = repeat
return obj
@property
def tform(self):
return '%sX' % self.repeat
# TODO: Table column formats need to be verified upon first reading the file;
# as it is, an invalid P format will raise a VerifyError from some deep,
# unexpected place
class _FormatP(str):
"""For P format in variable length table."""
# As far as I can tell from my reading of the FITS standard, a type code is
# *required* for P and Q formats; there is no default
_format_re_template = (r'(?P<repeat>\d+)?%s(?P<dtype>[LXBIJKAEDCM])'
'(?:\((?P<max>\d*)\))?')
_format_code = 'P'
_format_re = re.compile(_format_re_template % _format_code)
_descriptor_format = '2i4'
def __new__(cls, dtype, repeat=None, max=None):
obj = super(_FormatP, cls).__new__(cls, cls._descriptor_format)
obj.format = NUMPY2FITS[dtype]
obj.dtype = dtype
obj.repeat = repeat
obj.max = max
return obj
@classmethod
def from_tform(cls, format):
m = cls._format_re.match(format)
if not m or m.group('dtype') not in FITS2NUMPY:
raise VerifyError('Invalid column format: %s' % format)
repeat = m.group('repeat')
array_dtype = m.group('dtype')
max = m.group('max')
if not max:
max = None
return cls(FITS2NUMPY[array_dtype], repeat=repeat, max=max)
@property
def tform(self):
repeat = '' if self.repeat is None else self.repeat
max = '' if self.max is None else self.max
return '%s%s%s(%s)' % (repeat, self._format_code, self.format, max)
class _FormatQ(_FormatP):
"""Carries type description of the Q format for variable length arrays.
The Q format is like the P format but uses 64-bit integers in the array
descriptors, allowing for heaps stored beyond 2GB into a file.
"""
_format_code = 'Q'
_format_re = re.compile(_FormatP._format_re_template % _format_code)
_descriptor_format = '2i8'
class Column(object):
"""
Class which contains the definition of one column, e.g. ``ttype``,
``tform``, etc. and the array containing values for the column.
"""
def __init__(self, name=None, format=None, unit=None, null=None,
bscale=None, bzero=None, disp=None, start=None, dim=None,
array=None, ascii=None):
"""
Construct a `Column` by specifying attributes. All attributes
except `format` can be optional.
Parameters
----------
name : str, optional
column name, corresponding to ``TTYPE`` keyword
format : str, optional
column format, corresponding to ``TFORM`` keyword
unit : str, optional
column unit, corresponding to ``TUNIT`` keyword
null : str, optional
null value, corresponding to ``TNULL`` keyword
bscale : int-like, optional
bscale value, corresponding to ``TSCAL`` keyword
bzero : int-like, optional
bzero value, corresponding to ``TZERO`` keyword
disp : str, optional
display format, corresponding to ``TDISP`` keyword
start : int, optional
column starting position (ASCII table only), corresponding
to ``TBCOL`` keyword
dim : str, optional
column dimension corresponding to ``TDIM`` keyword
array : iterable, optional
a `list`, `numpy.ndarray` (or other iterable that can be used to
initialize an ndarray) providing intial data for this column.
The array will be automatically converted, if possible, to the data
format of the column. In the case were non-trivial ``bscale``
and/or ``bzero`` arguments are given, the values in the array must
be the *physical* values--that is, the values of column as if the
scaling has already been applied (the array stored on the column
object will then be converted back to its storage values).
ascii : bool, optional
set `True` if this describes a column for an ASCII table; this
may be required to disambiguate the column format
"""
if format is None:
raise ValueError('Must specify format to construct Column.')
# any of the input argument (except array) can be a Card or just
# a number/string
kwargs = {'ascii': ascii}
for attr in KEYWORD_ATTRIBUTES:
value = locals()[attr] # get the argument's value
if isinstance(value, Card):
value = value.value
kwargs[attr] = value
valid_kwargs, invalid_kwargs = self._verify_keywords(**kwargs)
if invalid_kwargs:
msg = ['The following keyword arguments to Column were invalid:']
for val in invalid_kwargs.values():
msg.append(indent(val[1]))
raise VerifyError('\n'.join(msg))
for attr in KEYWORD_ATTRIBUTES:
setattr(self, attr, valid_kwargs.get(attr))
# TODO: For PyFITS 3.3 try to eliminate the following two special cases
# for recformat and dim:
# This is not actually stored as an attribute on columns for some
# reason
recformat = valid_kwargs['recformat']
# The 'dim' keyword's original value is stored in self.dim, while
# *only* the tuple form is stored in self._dims.
self._dims = self.dim
self.dim = dim
# Zero-length formats are legal in the FITS format, but since they
# are not supported by numpy we mark columns that use them as
# "phantom" columns, that are not considered when reading the data
# as a record array.
if self.format[0] == '0' or \
(self.format[-1] == '0' and self.format[-2].isalpha()):
self._phantom = True
else:
self._phantom = False
# Awful hack to use for now to keep track of whether the column holds
# pseudo-unsigned int data
self._pseudo_unsigned_ints = False
# if the column data is not ndarray, make it to be one, i.e.
# input arrays can be just list or tuple, not required to be ndarray
# does not include Object array because there is no guarantee
# the elements in the object array are consistent.
if not isinstance(array,
(np.ndarray, chararray.chararray, Delayed)):
try: # try to convert to a ndarray first
if array is not None:
array = np.array(array)
except:
try: # then try to convert it to a strings array
itemsize = int(recformat[1:])
array = chararray.array(array, itemsize=itemsize)
except ValueError:
# then try variable length array
# Note: This includes _FormatQ by inheritance
if isinstance(recformat, _FormatP):
array = _VLF(array, dtype=recformat.dtype)
else:
raise ValueError('Data is inconsistent with the '
'format `%s`.' % format)
array = self._convert_to_valid_data_type(array)
# We have required (through documentation) that arrays passed in to
# this constructor are already in their physical values, so we make
# note of that here
if isinstance(array, np.ndarray):
self._physical_values = True
else:
self._physical_values = False
self.array = array
def __repr__(self):
text = ''
for attr in KEYWORD_ATTRIBUTES:
value = getattr(self, attr)
if value is not None:
text += attr + ' = ' + repr(value) + '; '
return text[:-2]
def __eq__(self, other):
"""
Two columns are equal if their name and format are the same. Other
attributes aren't taken into account at this time.
"""
# According to the FITS standard column names must be case-insensitive
a = (self.name.lower(), self.format)
b = (other.name.lower(), other.format)
return a == b
def __hash__(self):
"""
Like __eq__, the hash of a column should be based on the unique column
name and format, and be case-insensitive with respect to the column
name.
"""
return hash((self.name.lower(), self.format))
@lazyproperty
def dtype(self):
return np.dtype(_convert_format(self.format))
def copy(self):
"""
Return a copy of this `Column`.
"""
tmp = Column(format='I') # just use a throw-away format
tmp.__dict__ = self.__dict__.copy()
return tmp
@staticmethod
def _convert_format(format, cls):
"""The format argument to this class's initializer may come in many
forms. This uses the given column format class ``cls`` to convert
to a format of that type.
TODO: There should be an abc base class for column format classes
"""
# Short circuit in case we're already a _BaseColumnFormat--there is at
# least one case in which this can happen
if isinstance(format, _BaseColumnFormat):
return format, format.recformat
if format in NUMPY2FITS:
try:
# legit recarray format?
recformat = format
format = cls.from_recformat(format)
except VerifyError:
pass
try:
# legit FITS format?
format = cls(format)
recformat = format.recformat
except VerifyError:
raise VerifyError('Illegal format `%s`.' % format)
return format, recformat
@classmethod
def _verify_keywords(cls, name=None, format=None, unit=None, null=None,
bscale=None, bzero=None, disp=None, start=None,
dim=None, ascii=None):
"""
Given the keyword arguments used to initialize a Column, specifically
those that typically read from a FITS header (so excluding array),
verify that each keyword has a valid value.
Returns a 2-tuple of dicts. The first maps valid keywords to their
values. The second maps invalid keywords to a 2-tuple of their value,
and a message explaining why they were found invalid.
"""
valid = {}
invalid = {}
format, recformat = cls._determine_formats(format, start, dim, ascii)
valid.update(format=format, recformat=recformat)
# Currently we don't have any validation for name, unit, bscale, or
# bzero so include those by default
# TODO: Add validation for these keywords, obviously
for k, v in [('name', name), ('unit', unit), ('bscale', bscale),
('bzero', bzero)]:
if v is not None and v != '':
valid[k] = v
# Validate null option
# Note: Enough code exists that thinks empty strings are sensible
# inputs for these options that we need to treat '' as None
if null is not None and null != '':
msg = None
if isinstance(format, _AsciiColumnFormat):
null = str(null)
if len(null) > format.width:
msg = (
"ASCII table null option (TNULLn) is longer than "
"the column's character width and will be truncated "
"(got %r)." % null)
else:
if not _is_int(null):
# Make this an exception instead of a warning, since any
# non-int value is meaningless
msg = (
'Column null option (TNULLn) must be an integer for '
'binary table columns (got %r). The invalid value '
'will be ignored for the purpose of formatting '
'the data in this column.' % null)
tnull_formats = ('B', 'I', 'J', 'K')
if not (format.format in tnull_formats or
(format.format in ('P', 'Q') and
format.p_format in tnull_formats)):
# TODO: We should also check that TNULLn's integer value
# is in the range allowed by the column's format
msg = (
'Column null option (TNULLn) is invalid for binary '
'table columns of type %r (got %r). The invalid '
'value will be ignored for the purpose of formatting '
'the data in this column.' % (format, null))
if msg is None:
valid['null'] = null
else:
invalid['null'] = (null, msg)
# Validate the disp option
# TODO: Add full parsing and validation of TDISPn keywords
if disp is not None and disp != '':
msg = None
if not isinstance(disp, string_types):
msg = (
'Column disp option (TDISPn) must be a string (got %r).'
'The invalid value will be ignored for the purpose of '
'formatting the data in this column.' % disp)
if (isinstance(format, _AsciiColumnFormat) and
disp[0].upper() == 'L'):
# disp is at least one character long and has the 'L' format
# which is not recognized for ASCII tables
msg = (
"Column disp option (TDISPn) may not use the 'L' format "
"with ASCII table columns. The invalid value will be "
"ignored for the purpose of formatting the data in this "
"column.")
if msg is None:
valid['disp'] = disp
else:
invalid['disp'] = (disp, msg)
# Validate the start option
if start is not None and start != '':
msg = None
if not isinstance(format, _AsciiColumnFormat):
# The 'start' option only applies to ASCII columns
msg = (
'Column start option (TBCOLn) is not allowed for binary '
'table columns (got %r). The invalid keyword will be '
'ignored for the purpose of formatting the data in this '
'column.'% start)
try:
start = int(start)
except (TypeError, ValueError):
pass
if not _is_int(start) and start < 1:
msg = (
'Column start option (TBCOLn) must be a positive integer '
'(got %r). The invalid value will be ignored for the '
'purpose of formatting the data in this column.' % start)
if msg is None:
valid['start'] = start
else:
invalid['start'] = (start, msg)
# Process TDIMn options
# ASCII table columns can't have a TDIMn keyword associated with it;
# for now we just issue a warning and ignore it.
# TODO: This should be checked by the FITS verification code
if dim is not None and dim != '':
msg = None
dims_tuple = tuple()
# NOTE: If valid, the dim keyword's value in the the valid dict is
# a tuple, not the original string; if invalid just the original
# string is returned
if isinstance(format, _AsciiColumnFormat):
msg = (
'Column dim option (TDIMn) is not allowed for ASCII table '
'columns (got %r). The invalid keyword will be ignored '
'for the purpose of formatting this column.' % dim)
elif isinstance(dim, string_types):
dims_tuple = _parse_tdim(dim)
elif isinstance(dim, tuple):
dims_tuple = dim
else:
msg = (
"`dim` argument must be a string containing a valid value "
"for the TDIMn header keyword associated with this column, "
"or a tuple containing the C-order dimensions for the "
"column. The invalid value will be ignored for the purpose "
"of formatting this column.")
if dims_tuple:
if reduce(operator.mul, dims_tuple) > format.repeat:
msg = (
"The repeat count of the column format %r for column %r "
"is fewer than the number of elements per the TDIM "
"argument %r. The invalid TDIMn value will be ignored "
"for the purpose of formatting this column." %
(name, format, dim))
if msg is None:
valid['dim'] = dims_tuple
else:
invalid['dim'] = (dim, msg)
return valid, invalid
@classmethod
def _determine_formats(cls, format, start, dim, ascii):
"""
Given a format string and whether or not the Column is for an
ASCII table (ascii=None means unspecified, but lean toward binary table
where ambiguous) create an appropriate _BaseColumnFormat instance for
the column's format, and determine the appropriate recarray format.
The values of the start and dim keyword arguments are also useful, as
the former is only valid for ASCII tables and the latter only for
BINARY tables.
"""
# If the given format string is unabiguously a Numpy dtype or one of
# the Numpy record format type specifiers supported by PyFITS then that
# should take priority--otherwise assume it is a FITS format
if isinstance(format, np.dtype):
format, _, _ = _dtype_to_recformat(format)
# check format
if ascii is None and not isinstance(format, _BaseColumnFormat):
# We're just give a string which could be either a Numpy format
# code, or a format for a binary column array *or* a format for an
# ASCII column array--there may be many ambiguities here. Try our
# best to guess what the user intended.
format, recformat = cls._guess_format(format, start, dim)
elif not ascii and not isinstance(format, _BaseColumnFormat):
format, recformat = cls._convert_format(format, _ColumnFormat)
elif ascii and not isinstance(format, _AsciiColumnFormat):
format, recformat = cls._convert_format(format,
_AsciiColumnFormat)
else:
# The format is already acceptable and unambiguous
recformat = format.recformat
return format, recformat
@classmethod
def _guess_format(cls, format, start, dim):
if start and dim:
# This is impossible; this can't be a valid FITS column
raise ValueError(
'Columns cannot have both a start (TCOLn) and dim '
'(TDIMn) option, since the former is only applies to '
'ASCII tables, and the latter is only valid for binary '
'tables.')
elif start:
# Only ASCII table columns can have a 'start' option
guess_format = _AsciiColumnFormat
elif dim:
# Only binary tables can have a dim option
guess_format = _ColumnFormat
else:
# If the format is *technically* a valid binary column format
# (i.e. it has a valid format code followed by arbitrary
# "optional" codes), but it is also strictly a valid ASCII
# table format, then assume an ASCII table column was being
# requested (the more likely case, after all).
try:
format = _AsciiColumnFormat(format, strict=True)
except VerifyError:
pass
# A safe guess which reflects the existing behavior of previous
# PyFITS versions
guess_format = _ColumnFormat
try:
format, recformat = cls._convert_format(format, guess_format)
except VerifyError:
# For whatever reason our guess was wrong (for example if we got
# just 'F' that's not a valid binary format, but it an ASCII format
# code albeit with the width/precision ommitted
guess_format = (_AsciiColumnFormat
if guess_format is _ColumnFormat
else _ColumnFormat)
# If this fails too we're out of options--it is truly an invalid
# format, or at least not supported
format, recformat = cls._convert_format(format, guess_format)
return format, recformat
def _convert_to_valid_data_type(self, array):
# Convert the format to a type we understand
if isinstance(array, Delayed):
return array
elif array is None:
return array
else:
format = self.format
dims = self._dims
if 'P' in format or 'Q' in format:
return array
elif 'A' in format:
if array.dtype.char in 'SU':
if dims:
# The 'last' dimension (first in the order given
# in the TDIMn keyword itself) is the number of
# characters in each string
fsize = dims[-1]
else:
fsize = np.dtype(format.recformat).itemsize
return chararray.array(array, itemsize=fsize)
else:
return _convert_array(array, np.dtype(format.recformat))
elif 'L' in format:
# boolean needs to be scaled back to storage values ('T', 'F')
if array.dtype == np.dtype('bool'):
return np.where(array == False, ord('F'), ord('T'))
else:
return np.where(array == 0, ord('F'), ord('T'))
elif 'X' in format:
return _convert_array(array, np.dtype('uint8'))
else:
# Preserve byte order of the original array for now; see #77
# TODO: For some reason we drop the format repeat here; need
# to investigate why that was and if it's something we can
# avoid doing...
new_format = _convert_format(format.format)
numpy_format = array.dtype.byteorder + new_format
# Handle arrays passed in as unsigned ints as pseudo-unsigned
# int arrays; blatantly tacked in here for now--we need columns
# to have explicit knowledge of whether they treated as
# pseudo-unsigned
bzeros = {2: np.uint16(2**15), 4: np.uint32(2**31),
8: np.uint64(2**63)}
if (array.dtype.kind == 'u' and
array.dtype.itemsize in bzeros and
self.bscale in (1, None, '') and
self.bzero == bzeros[array.dtype.itemsize]):
# Basically the array is uint, has scale == 1.0, and the
# bzero is the appropriate value for a pseudo-unsigned
# integer of the input dtype, then go ahead and assume that
# uint is assumed
numpy_format = numpy_format.replace('i', 'u')
self._pseudo_unsigned_ints = True
return _convert_array(array, np.dtype(numpy_format))
class ColDefs(object):
"""
Column definitions class.
It has attributes corresponding to the `Column` attributes
(e.g. `ColDefs` has the attribute `~ColDefs.names` while `Column`
has `~Column.name`). Each attribute in `ColDefs` is a list of
corresponding attribute values from all `Column` objects.
"""
_padding_byte = '\x00'
_col_format_cls = _ColumnFormat
def __new__(cls, input, tbtype=None, ascii=False):
if tbtype is not None:
warnings.warn(
'The ``tbtype`` argument to `ColDefs` is deprecated as of '
'PyFITS 3.3; instead the appropriate table type should be '
'inferred from the formats of the supplied columns. Use the '
'``ascii=True`` argument to ensure that ASCII table columns '
'are used.')
else:
tbtype = 'BinTableHDU' # The old default
# Backards-compat support
# TODO: Remove once the tbtype argument is removed entirely
if tbtype == 'BinTableHDU':
klass = cls
elif tbtype == 'TableHDU':
klass = _AsciiColDefs
else:
raise ValueError('Invalid table type: %s.' % tbtype)
if (hasattr(input, '_columns_type') and
issubclass(input._columns_type, ColDefs)):
klass = input._columns_type
elif (hasattr(input, '_col_format_cls') and
issubclass(input._col_format_cls, _AsciiColumnFormat)):
klass = _AsciiColDefs
if ascii: # force ASCII if this has been explicitly requested
klass = _AsciiColDefs
return object.__new__(klass)
def __init__(self, input, tbtype=None, ascii=False):
"""
Parameters
----------
input : sequence of `Column`, `ColDefs`, other
An existing table HDU, an existing `ColDefs`, or any multi-field
Numpy array or `numpy.recarray`.
**(Deprecated)** tbtype : str, optional
which table HDU, ``"BinTableHDU"`` (default) or
``"TableHDU"`` (text table).
Now ColDefs for a normal (binary) table by default, but converted
automatically to ASCII table ColDefs in the appropriate contexts
(namely, when creating an ASCII table).
ascii : bool
"""
from pyfits.hdu.table import _TableBaseHDU
from pyfits.fitsrec import FITS_rec
if isinstance(input, ColDefs):
self._init_from_coldefs(input)
elif (isinstance(input, FITS_rec) and hasattr(input, '_coldefs') and
input._coldefs):
# If given a FITS_rec object we can directly copy its columns, but
# only if its columns have already been defined, otherwise this
# will loop back in on itself and blow up
self._init_from_coldefs(input._coldefs)
elif isinstance(input, np.ndarray) and input.dtype.fields is not None:
# Construct columns from the fields of a record array
self._init_from_array(input)
elif isiterable(input):
# if the input is a list of Columns
self._init_from_sequence(input)
elif isinstance(input, _TableBaseHDU):
# Construct columns from fields in an HDU header
self._init_from_table(input)
else:
raise TypeError('Input to ColDefs must be a table HDU, a list '
'of Columns, or a record/field array.')
def _init_from_coldefs(self, coldefs):
"""Initialize from an existing ColDefs object (just copy the
columns and convert their formats if necessary).
"""
self.columns = [self._copy_column(col) for col in coldefs]
def _init_from_sequence(self, columns):
for idx, col in enumerate(columns):
if not isinstance(col, Column):
raise TypeError(
'Element %d in the ColDefs input is not a Column.' % idx)
self._init_from_coldefs(columns)
def _init_from_array(self, array):
self.columns = []
for idx in range(len(array.dtype)):
cname = array.dtype.names[idx]
ftype = array.dtype.fields[cname][0]
format = self._col_format_cls.from_recformat(ftype)
# Determine the appropriate dimensions for items in the column
# (typically just 1D)
dim = array.dtype[idx].shape[::-1]
if dim and (len(dim) > 1 or 'A' in format):
if 'A' in format:
# n x m string arrays must include the max string
# length in their dimensions (e.g. l x n x m)
dim = (array.dtype[idx].base.itemsize,) + dim
dim = repr(dim).replace(' ', '')
else:
dim = None
# Check for unsigned ints.
bzero = None
if 'I' in format and ftype == np.dtype('uint16'):
bzero = np.uint16(2**15)
elif 'J' in format and ftype == np.dtype('uint32'):
bzero = np.uint32(2**31)
elif 'K' in format and ftype == np.dtype('uint64'):
bzero = np.uint64(2**63)
c = Column(name=cname, format=format,
array=array.view(np.ndarray)[cname], bzero=bzero,
dim=dim)
self.columns.append(c)
def _init_from_table(self, table):
hdr = table._header
nfields = hdr['TFIELDS']
self._width = hdr['NAXIS1']
self._shape = hdr['NAXIS2']
# go through header keywords to pick out column definition keywords
# definition dictionaries for each field
col_keywords = [{} for i in range(nfields)]
for keyword, value in iteritems(hdr):
key = TDEF_RE.match(keyword)
try:
keyword = key.group('label')
except:
continue # skip if there is no match
if keyword in KEYWORD_NAMES:
col = int(key.group('num'))
if col <= nfields and col > 0:
idx = KEYWORD_NAMES.index(keyword)
attr = KEYWORD_ATTRIBUTES[idx]
if attr == 'format':
# Go ahead and convert the format value to the
# appropriate ColumnFormat container now
value = self._col_format_cls(value)
col_keywords[col - 1][attr] = value
# Verify the column keywords and display any warnings if necessary;
# we only want to pass on the valid keywords
for idx, kwargs in enumerate(col_keywords):
valid_kwargs, invalid_kwargs = Column._verify_keywords(**kwargs)
for val in invalid_kwargs.values():
warnings.warn(
'Invalid keyword for column %d: %s' % (idx + 1, val[1]),
VerifyWarning)
# Special cases for recformat and dim
# TODO: Try to eliminate the need for these special cases
del valid_kwargs['recformat']
if 'dim' in valid_kwargs:
valid_kwargs['dim'] = kwargs['dim']
col_keywords[idx] = valid_kwargs
# data reading will be delayed
for col in range(nfields):
col_keywords[col]['array'] = Delayed(table, col)
# now build the columns
self.columns = [Column(**attrs) for attrs in col_keywords]
self._listener = weakref.proxy(table)
def __copy__(self):
return self.__class__(self)
def __deepcopy__(self, memo):
return self.__class__([copy.deepcopy(c, memo) for c in self.columns])
def _copy_column(self, column):
"""Utility function used currently only by _init_from_coldefs
to help convert columns from binary format to ASCII format or vice
versa if necessary (otherwise performs a straight copy).
"""
if isinstance(column.format, self._col_format_cls):
# This column has a FITS format compatible with this column
# definitions class (that is ascii or binary)
return column.copy()
new_column = column.copy()
# Try to use the Numpy recformat as the equivalency between the
# two formats; if that conversion can't be made then these
# columns can't be transferred
# TODO: Catch exceptions here and raise an explicit error about
# column format conversion
new_column.format = self._col_format_cls.from_column_format(
column.format)
# Handle a few special cases of column format options that are not
# compatible between ASCII an binary tables
# TODO: This is sort of hacked in right now; we really neet
# separate classes for ASCII and Binary table Columns, and they
# should handle formatting issues like these
if not isinstance(new_column.format, _AsciiColumnFormat):
# the column is a binary table column...
new_column.start = None
if new_column.null is not None:
# We can't just "guess" a value to represent null
# values in the new column, so just disable this for
# now; users may modify it later
new_column.null = None
else:
# the column is an ASCII table column...
if new_column.null is not None:
new_column.null = DEFAULT_ASCII_TNULL
if (new_column.disp is not None and
new_column.disp.upper().startswith('L')):
# ASCII columns may not use the logical data display format;
# for now just drop the TDISPn option for this column as we
# don't have a systematic conversion of boolean data to ASCII
# tables yet
new_column.disp = None
return new_column
def __getattr__(self, name):
"""
Automatically returns the values for the given keyword attribute for
all `Column`s in this list.
Implements for example self.units, self.formats, etc.
"""
cname = name[:-1]
if cname in KEYWORD_ATTRIBUTES and name[-1] == 's':
attr = []
for col in self:
val = getattr(col, cname)
if val is not None:
attr.append(val)
else:
attr.append('')
return attr
raise AttributeError(name)
@lazyproperty
def dtype(self):
recformats = [f for idx, f in enumerate(self._recformats)
if not self[idx]._phantom]
formats = ','.join(recformats)
names = [n for idx, n in enumerate(self.names)
if not self[idx]._phantom]
return np.rec.format_parser(formats, names, None).dtype
@lazyproperty
def _arrays(self):
return [col.array for col in self.columns]
@lazyproperty
def _recformats(self):
return [fmt.recformat for fmt in self.formats]
@lazyproperty
def _dims(self):
"""Returns the values of the TDIMn keywords parsed into tuples."""
return [col._dims for col in self.columns]
def __getitem__(self, key):
x = self.columns[key]
if _is_int(key):
return x
else:
return ColDefs(x)
def __len__(self):
return len(self.columns)
def __repr__(self):
rep = 'ColDefs('
if hasattr(self, 'columns') and self.columns:
# The hasattr check is mostly just useful in debugging sessions
# where self.columns may not be defined yet
rep += '\n '
rep += '\n '.join([repr(c) for c in self.columns])
rep += '\n'
rep += ')'
return rep
def __add__(self, other, option='left'):
if isinstance(other, Column):
b = [other]
elif isinstance(other, ColDefs):
b = list(other.columns)
else:
raise TypeError('Wrong type of input.')
if option == 'left':
tmp = list(self.columns) + b
else:
tmp = b + list(self.columns)
return ColDefs(tmp)
def __radd__(self, other):
return self.__add__(other, 'right')
def __sub__(self, other):
if not isinstance(other, (list, tuple)):
other = [other]
_other = [_get_index(self.names, key) for key in other]
indx = range(len(self))
for x in _other:
indx.remove(x)
tmp = [self[i] for i in indx]
return ColDefs(tmp)
def _update_listener(self):
if hasattr(self, '_listener'):
try:
if self._listener._data_loaded:
del self._listener.data
self._listener.columns = self
except ReferenceError:
del self._listener
def add_col(self, column):
"""
Append one `Column` to the column definition.
.. warning::
*New in pyfits 2.3*: This function appends the new column
to the `ColDefs` object in place. Prior to pyfits 2.3,
this function returned a new `ColDefs` with the new column
at the end.
"""
assert isinstance(column, Column)
for cname in KEYWORD_ATTRIBUTES:
attr = getattr(self, cname + 's')
attr.append(getattr(column, cname))
self._arrays.append(column.array)
# Obliterate caches of certain things
del self.dtype
del self._recformats
del self._dims
self.columns.append(column)
# If this ColDefs is being tracked by a Table, inform the
# table that its data is now invalid.
self._update_listener()
return self
def del_col(self, col_name):
"""
Delete (the definition of) one `Column`.
col_name : str or int
The column's name or index
"""
indx = _get_index(self.names, col_name)
for cname in KEYWORD_ATTRIBUTES:
attr = getattr(self, cname + 's')
del attr[indx]
del self._arrays[indx]
# Obliterate caches of certain things
del self.dtype
del self._recformats
del self._dims
del self.columns[indx]
# If this ColDefs is being tracked by a Table, inform the
# table that its data is now invalid.
self._update_listener()
return self
def change_attrib(self, col_name, attrib, new_value):
"""
Change an attribute (in the ``KEYWORD_ATTRIBUTES`` list) of a `Column`.
Parameters
----------
col_name : str or int
The column name or index to change
attrib : str
The attribute name
value : object
The new value for the attribute
"""
indx = _get_index(self.names, col_name)
getattr(self, attrib + 's')[indx] = new_value
# If this ColDefs is being tracked by a Table, inform the
# table that its data is now invalid.
self._update_listener()
def change_name(self, col_name, new_name):
"""
Change a `Column`'s name.
Parameters
----------
col_name : str
The current name of the column
new_name : str
The new name of the column
"""
if new_name != col_name and new_name in self.names:
raise ValueError('New name %s already exists.' % new_name)
else:
self.change_attrib(col_name, 'name', new_name)
# If this ColDefs is being tracked by a Table, inform the
# table that its data is now invalid.
self._update_listener()
def change_unit(self, col_name, new_unit):
"""
Change a `Column`'s unit.
Parameters
----------
col_name : str or int
The column name or index
new_unit : str
The new unit for the column
"""
self.change_attrib(col_name, 'unit', new_unit)
# If this ColDefs is being tracked by a Table, inform the
# table that its data is now invalid.
self._update_listener()
def info(self, attrib='all', output=None):
"""
Get attribute(s) information of the column definition.
Parameters
----------
attrib : str
Can be one or more of the attributes listed in
``pyfits.column.KEYWORD_ATTRIBUTES``. The default is ``"all"``
which will print out all attributes. It forgives plurals and
blanks. If there are two or more attribute names, they must be
separated by comma(s).
output : file, optional
File-like object to output to. Outputs to stdout by default.
If `False`, returns the attributes as a `dict` instead.
Notes
-----
This function doesn't return anything by default; it just prints to
stdout.
"""
if output is None:
output = sys.stdout
if attrib.strip().lower() in ['all', '']:
lst = KEYWORD_ATTRIBUTES
else:
lst = attrib.split(',')
for idx in range(len(lst)):
lst[idx] = lst[idx].strip().lower()
if lst[idx][-1] == 's':
lst[idx] = list[idx][:-1]
ret = {}
for attr in lst:
if output:
if attr not in KEYWORD_ATTRIBUTES:
output.write("'%s' is not an attribute of the column "
"definitions.\n" % attr)
continue
output.write("%s:\n" % attr)
output.write(' %s\n' % getattr(self, attr + 's'))
else:
ret[attr] = getattr(self, attr + 's')
if not output:
return ret
class _AsciiColDefs(ColDefs):
"""ColDefs implementation for ASCII tables."""
_padding_byte = ' '
_col_format_cls = _AsciiColumnFormat
def __init__(self, input, tbtype=None, ascii=True):
super(_AsciiColDefs, self).__init__(input)
# if the format of an ASCII column has no width, add one
if not isinstance(input, _AsciiColDefs):
self._update_field_metrics()
else:
for idx, s in enumerate(input.starts):
self.columns[idx].start = s
self._spans = input.spans
self._width = input._width
@lazyproperty
def dtype(self):
_itemsize = self.spans[-1] + self.starts[-1] - 1
dtype = {}
for j in range(len(self)):
data_type = 'S' + str(self.spans[j])
dtype[self.names[j]] = (data_type, self.starts[j] - 1)
return np.dtype(dtype)
@property
def spans(self):
"""A list of the widths of each field in the table."""
return self._spans
@lazyproperty
def _recformats(self):
if len(self) == 1:
widths = []
else:
widths = [y - x for x, y in pairwise(self.starts)]
# Widths is the width of each field *including* any space between
# fields; this is so that we can map the fields to string records in a
# Numpy recarray
widths.append(self._width - self.starts[-1] + 1)
return ['a' + str(w) for w in widths]
def add_col(self, column):
super(_AsciiColDefs, self).add_col(column)
self._update_field_metrics()
def del_col(self, col_name):
super(_AsciiColDefs, self).del_col(col_name)
self._update_field_metrics()
def _update_field_metrics(self):
"""
Updates the list of the start columns, the list of the widths of each
field, and the total width of each record in the table.
"""
spans = [0] * len(self.columns)
end_col = 0 # Refers to the ASCII text column, not the table col
for idx, col in enumerate(self.columns):
width = col.format.width
# Update the start columns and column span widths taking into
# account the case that the starting column of a field may not
# be the column immediately after the previous field
if not col.start:
col.start = end_col + 1
end_col = col.start + width - 1
spans[idx] = width
self._spans = spans
self._width = end_col
class _VLF(np.ndarray):
"""Variable length field object."""
def __new__(cls, input, dtype='a'):
"""
Parameters
----------
input
a sequence of variable-sized elements.
"""
if dtype == 'a':
try:
# this handles ['abc'] and [['a','b','c']]
# equally, beautiful!
input = [chararray.array(x, itemsize=1) for x in input]
except:
raise ValueError('Inconsistent input data array: %s' % input)
a = np.array(input, dtype=np.object)
self = np.ndarray.__new__(cls, shape=(len(input),), buffer=a,
dtype=np.object)
self.max = 0
self.element_dtype = dtype
return self
def __array_finalize__(self, obj):
if obj is None:
return
self.max = obj.max
self.element_dtype = obj.element_dtype
def __setitem__(self, key, value):
"""
To make sure the new item has consistent data type to avoid
misalignment.
"""
if isinstance(value, np.ndarray) and value.dtype == self.dtype:
pass
elif isinstance(value, chararray.chararray) and value.itemsize == 1:
pass
elif self.element_dtype == 'a':
value = chararray.array(value, itemsize=1)
else:
value = np.array(value, dtype=self.element_dtype)
np.ndarray.__setitem__(self, key, value)
self.max = max(self.max, len(value))
def _get_index(names, key):
"""
Get the index of the `key` in the `names` list.
The `key` can be an integer or string. If integer, it is the index
in the list. If string,
a. Field (column) names are case sensitive: you can have two
different columns called 'abc' and 'ABC' respectively.
b. When you *refer* to a field (presumably with the field
method), it will try to match the exact name first, so in
the example in (a), field('abc') will get the first field,
and field('ABC') will get the second field.
If there is no exact name matched, it will try to match the
name with case insensitivity. So, in the last example,
field('Abc') will cause an exception since there is no unique
mapping. If there is a field named "XYZ" and no other field
name is a case variant of "XYZ", then field('xyz'),
field('Xyz'), etc. will get this field.
"""
if _is_int(key):
indx = int(key)
elif isinstance(key, string_types):
# try to find exact match first
try:
indx = names.index(key.rstrip())
except ValueError:
# try to match case-insentively,
_key = key.lower().rstrip()
names = [n.lower().rstrip() for n in names]
count = names.count(_key) # occurrence of _key in names
if count == 1:
indx = names.index(_key)
elif count == 0:
raise KeyError("Key '%s' does not exist." % key)
else: # multiple match
raise KeyError("Ambiguous key name '%s'." % key)
else:
raise KeyError("Illegal key '%s'." % repr(key))
return indx
def _unwrapx(input, output, repeat):
"""
Unwrap the X format column into a Boolean array.
Parameters
----------
input
input ``Uint8`` array of shape (`s`, `nbytes`)
output
output Boolean array of shape (`s`, `repeat`)
repeat
number of bits
"""
pow2 = np.array([128, 64, 32, 16, 8, 4, 2, 1], dtype='uint8')
nbytes = ((repeat - 1) // 8) + 1
for i in range(nbytes):
_min = i * 8
_max = min((i + 1) * 8, repeat)
for j in range(_min, _max):
output[..., j] = np.bitwise_and(input[..., i], pow2[j - i * 8])
def _wrapx(input, output, repeat):
"""
Wrap the X format column Boolean array into an ``UInt8`` array.
Parameters
----------
input
input Boolean array of shape (`s`, `repeat`)
output
output ``Uint8`` array of shape (`s`, `nbytes`)
repeat
number of bits
"""
output[...] = 0 # reset the output
nbytes = ((repeat - 1) // 8) + 1
unused = nbytes * 8 - repeat
for i in range(nbytes):
_min = i * 8
_max = min((i + 1) * 8, repeat)
for j in range(_min, _max):
if j != _min:
np.left_shift(output[..., i], 1, output[..., i])
np.add(output[..., i], input[..., j], output[..., i])
# shift the unused bits
np.left_shift(output[..., i], unused, output[..., i])
def _makep(array, descr_output, format, nrows=None):
"""
Construct the P (or Q) format column array, both the data descriptors and
the data. It returns the output "data" array of data type `dtype`.
The descriptor location will have a zero offset for all columns
after this call. The final offset will be calculated when the file
is written.
Parameters
----------
array
input object array
descr_output
output "descriptor" array of data type int32 (for P format arrays) or
int64 (for Q format arrays)--must be nrows long in its first dimension
format
the _FormatP object representing the format of the variable array
nrows : int, optional
number of rows to create in the column; defaults to the number of rows
in the input array
"""
# TODO: A great deal of this is redundant with FITS_rec._convert_p; see if
# we can merge the two somehow.
_offset = 0
if not nrows:
nrows = len(array)
n = min(len(array), nrows)
data_output = _VLF([None] * nrows, dtype=format.dtype)
if format.dtype == 'a':
_nbytes = 1
else:
_nbytes = np.array([], dtype=format.dtype).itemsize
for idx in range(nrows):
if idx < len(array):
rowval = array[idx]
else:
if format.dtype == 'a':
rowval = ' ' * data_output.max
else:
rowval = [0] * data_output.max
if format.dtype == 'a':
data_output[idx] = chararray.array(encode_ascii(rowval),
itemsize=1)
else:
data_output[idx] = np.array(rowval, dtype=format.dtype)
descr_output[idx, 0] = len(data_output[idx])
descr_output[idx, 1] = _offset
_offset += len(data_output[idx]) * _nbytes
return data_output
def _parse_tformat(tform):
"""Parse ``TFORMn`` keyword for a binary table into a
``(repeat, format, option)`` tuple.
"""
try:
(repeat, format, option) = TFORMAT_RE.match(tform.strip()).groups()
except:
# TODO: Maybe catch this error use a default type (bytes, maybe?) for
# unrecognized column types. As long as we can determine the correct
# byte width somehow..
raise VerifyError('Format %r is not recognized.' % tform)
if repeat == '':
repeat = 1
else:
repeat = int(repeat)
return (repeat, format.upper(), option)
def _parse_ascii_tformat(tform, strict=False):
"""Parse the ``TFORMn`` keywords for ASCII tables into a
``(format, width, precision)`` tuple (the latter is zero unless
width is one of 'E', 'F', or 'D').
"""
match = TFORMAT_ASCII_RE.match(tform.strip())
if not match:
raise VerifyError('Format %r is not recognized.' % tform)
# Be flexible on case
format = match.group('format')
if format is None:
# Floating point format
format = match.group('formatf').upper()
width = match.group('widthf')
precision = match.group('precision')
if width is None or precision is None:
if strict:
raise VerifyError('Format %r is not unambiguously an ASCII '
'table format.')
else:
width = 0 if width is None else width
precision = 1 if precision is None else precision
else:
format = format.upper()
width = match.group('width')
if width is None:
if strict:
raise VerifyError('Format %r is not unambiguously an ASCII '
'table format.')
else:
# Just use a default width of 0 if unspecified
width = 0
precision = 0
def convert_int(val):
msg = ('Format %r is not valid--field width and decimal precision '
'must be positive integers.')
try:
val = int(val)
except (ValueError, TypeError):
raise VerifyError(msg % tform)
if val <= 0:
raise VerifyError(msg % tform)
return val
if width and precision:
# This should only be the case for floating-point formats
width, precision = convert_int(width), convert_int(precision)
elif width:
# Just for integer/string formats; ignore precision
width = convert_int(width)
else:
# For any format, if width was unspecified use the set defaults
width, precision = ASCII_DEFAULT_WIDTHS[format]
if precision >= width:
raise VerifyError("Format %r not valid--the number of decimal digits "
"must be less than the format's total width %s." &
(tform, width))
return format, width, precision
def _parse_tdim(tdim):
"""Parse the ``TDIM`` value into a tuple (may return an empty tuple if
the value ``TDIM`` value is empty or invalid).
"""
m = tdim and TDIM_RE.match(tdim)
if m:
dims = m.group('dims')
return tuple(int(d.strip()) for d in dims.split(','))[::-1]
# Ignore any dim values that don't specify a multidimensional column
return tuple()
def _scalar_to_format(value):
"""
Given a scalar value or string, returns the minimum FITS column format
that can represent that value. 'minimum' is defined by the order given in
FORMATORDER.
"""
# TODO: Numpy 1.6 and up has a min_scalar_type() function that can handle
# this; in the meantime we have to use our own implementation (which for
# now is pretty naive)
# First, if value is a string, try to convert to the appropriate scalar
# value
for type_ in (int, float, complex):
try:
value = type_(value)
break
except ValueError:
continue
if isinstance(value, int) and value in (0, 1):
# Could be a boolean
return 'L'
elif isinstance(value, int):
for char in ('B', 'I', 'J', 'K'):
type_ = np.dtype(FITS2NUMPY[char]).type
if type_(value) == value:
return char
elif isinstance(value, float):
# For now just assume double precision
return 'D'
elif isinstance(value, complex):
return 'M'
else:
return 'A' + str(len(value))
def _cmp_recformats(f1, f2):
"""
Compares two numpy recformats using the ordering given by FORMATORDER.
"""
if f1[0] == 'a' and f2[0] == 'a':
return cmp(int(f1[1:]), int(f2[1:]))
else:
f1, f2 = NUMPY2FITS[f1], NUMPY2FITS[f2]
return cmp(FORMATORDER.index(f1), FORMATORDER.index(f2))
def _convert_fits2record(format):
"""
Convert FITS format spec to record format spec.
"""
repeat, dtype, option = _parse_tformat(format)
if dtype in FITS2NUMPY:
if dtype == 'A':
output_format = FITS2NUMPY[dtype] + str(repeat)
# to accomodate both the ASCII table and binary table column
# format spec, i.e. A7 in ASCII table is the same as 7A in
# binary table, so both will produce 'a7'.
# Technically the FITS standard does not allow this but it's a very
# common mistake
if format.lstrip()[0] == 'A' and option != '':
# make sure option is integer
output_format = FITS2NUMPY[dtype] + str(int(option))
else:
repeat_str = ''
if repeat != 1:
repeat_str = str(repeat)
output_format = repeat_str + FITS2NUMPY[dtype]
elif dtype == 'X':
output_format = _FormatX(repeat)
elif dtype == 'P':
output_format = _FormatP.from_tform(format)
elif dtype == 'Q':
output_format = _FormatQ.from_tform(format)
elif dtype == 'F':
output_format = 'f8'
else:
raise ValueError('Illegal format %s.' % format)
return output_format
def _convert_record2fits(format):
"""
Convert record format spec to FITS format spec.
"""
recformat, kind, dtype = _dtype_to_recformat(format)
shape = dtype.shape
option = str(dtype.base.itemsize)
ndims = len(shape)
repeat = 1
if ndims > 0:
nel = np.array(shape, dtype='i8').prod()
if nel > 1:
repeat = nel
if kind == 'a':
# This is a kludge that will place string arrays into a
# single field, so at least we won't lose data. Need to
# use a TDIM keyword to fix this, declaring as (slength,
# dim1, dim2, ...) as mwrfits does
ntot = int(repeat) * int(option)
output_format = str(ntot) + 'A'
elif recformat in NUMPY2FITS: # record format
if repeat != 1:
repeat = str(repeat)
else:
repeat = ''
output_format = repeat + NUMPY2FITS[recformat]
else:
raise ValueError('Illegal format %s.' % format)
return output_format
def _dtype_to_recformat(dtype):
"""
Utility function for converting a dtype object or string that instantiates
a dtype (e.g. 'float32') into one of the two character Numpy format codes
that have been traditionally used by PyFITS.
In particular, use of 'a' to refer to character data is long since
deprecated in Numpy, but PyFITS remains heavily invested in its use
(something to try to get away from sooner rather than later).
"""
if not isinstance(dtype, np.dtype):
dtype = np.dtype(dtype)
kind = dtype.base.kind
itemsize = dtype.base.itemsize
recformat = kind + str(itemsize)
if kind in ('U', 'S'):
recformat = kind = 'a'
return recformat, kind, dtype
def _convert_format(format, reverse=False):
"""
Convert FITS format spec to record format spec. Do the opposite if
reverse=True.
"""
if reverse:
return _convert_record2fits(format)
else:
return _convert_fits2record(format)
def _convert_ascii_format(format, reverse=False):
"""Convert ASCII table format spec to record format spec."""
if reverse:
recformat, kind, dtype = _dtype_to_recformat(format)
itemsize = dtype.itemsize
if kind == 'a':
return 'A' + str(itemsize)
elif NUMPY2FITS.get(recformat) == 'L':
# Special case for logical/boolean types--for ASCII tables we
# represent these as single character columns containing 'T' or 'F'
# (a la the storage format for Logical columns in binary tables)
return 'A1'
elif kind == 'i':
# Use for the width the maximum required to represent integers
# of that byte size plus 1 for signs, but use a minumum of the
# default width (to keep with existing behavior)
width = 1 + len(str(2 ** (itemsize * 8)))
width = max(width, ASCII_DEFAULT_WIDTHS['I'][0])
return 'I' + str(width)
elif kind == 'f':
# This is tricky, but go ahead and use D if float-64, and E
# if float-32 with their default widths
if itemsize >= 8:
format = 'D'
else:
format = 'E'
width = '.'.join(str(w) for w in ASCII_DEFAULT_WIDTHS[format])
return format + width
# TODO: There may be reasonable ways to represent other Numpy types so
# let's see what other possibilities there are besides just 'a', 'i',
# and 'f'. If it doesn't have a reasonable ASCII representation then
# raise an exception
else:
format, width, precision = _parse_ascii_tformat(format)
# This gives a sensible "default" dtype for a given ASCII
# format code
recformat = ASCII2NUMPY[format]
# The following logic is taken from CFITSIO:
# For integers, if the width <= 4 we can safely use 16-bit ints for all
# values [for the non-standard J format code just always force 64-bit]
if format == 'I' and width <= 4:
recformat = 'i2'
elif format == 'F' and width > 7:
# 32-bit floats (the default) may not be accurate enough to support
# all values that can fit in this field, so upgrade to 64-bit
recformat = 'f8'
elif format == 'E' and precision > 6:
# Again upgrade to a 64-bit int if we require greater decimal
# precision
recformat = 'f8'
elif format == 'A':
recformat += str(width)
return recformat
| [
"aryaf@flux-login3.arc-ts.umich.edu"
] | aryaf@flux-login3.arc-ts.umich.edu |
caf2ca6c9632803d38917b45e7115aa97852f286 | 3a6cf9e46633128374b775e5d41691cff7f78146 | /keras-frcnn/keras_frcnn/alexnet3.py | 12c4bd19fa6f2105ac797428bc17cdff9613068a | [
"Apache-2.0"
] | permissive | Alliance-DENG/LungNodulesDetection | 63980f7984f475b95f4bec20493f80053fcb4f78 | 6008859ca3414d10f70c53b46a6f95e41f281ddd | refs/heads/master | 2020-03-27T10:27:44.202947 | 2018-09-10T08:52:26 | 2018-09-10T08:52:26 | 146,421,646 | 7 | 3 | null | null | null | null | UTF-8 | Python | false | false | 4,567 | py | # -*- coding: utf-8 -*-
"""
Alexnet model for FasterRCNN, requiring 3 channels input.
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import warnings
from keras.models import Model
from keras.layers import Flatten, Dense, Input, Conv2D, MaxPooling2D, Dropout
from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, TimeDistributed
from keras.engine.topology import get_source_inputs
from keras.utils import layer_utils
from keras.utils.data_utils import get_file
from keras import backend as K
from keras_frcnn.RoiPoolingConv import RoiPoolingConv
from keras.layers.normalization import BatchNormalization
def get_weight_path():
if K.image_dim_ordering() == 'th':
print('pretrained weights not available for VGG with theano backend')
return
else:
return 'vgg16_weights_tf_dim_ordering_tf_kernels.h5'
def get_img_output_length(width, height):
def get_output_length(input_length):
return input_length//16
return get_output_length(width), get_output_length(height)
def nn_base(input_tensor=None, trainable=False):
# Determine proper input shape
if K.image_dim_ordering() == 'th':
input_shape = (3, None, None)
else:
#input_shape = (None, None, 1)
input_shape = (None, None, 3)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
if K.image_dim_ordering() == 'tf':
bn_axis = 3
else:
bn_axis = 1
# pretrained alexnet
# use the same kernel_initializer as sina if you use the same data normalization
x = Conv2D(96, (11, 11), strides=(4,4), activation='relu', padding='same', name='conv2d_1', kernel_initializer='glorot_normal')(img_input)
x = MaxPooling2D((2, 2), strides=(2, 2), padding='same', name='max_pooling2d_1')(x)
x = BatchNormalization()(x)
x = Conv2D(256, (11, 11), strides = (1,1), activation='relu', padding='same', name='conv2d_2', kernel_initializer='glorot_normal')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='max_pooling2d_2')(x)
x = BatchNormalization()(x)
x = Conv2D(384, (3, 3), activation='relu', padding='same', name='conv2d_3', kernel_initializer='glorot_normal')(x)
x = Conv2D(384, (3, 3), activation='relu', padding='same', name='conv2d_4', kernel_initializer='glorot_normal')(x)
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='conv2d_5', kernel_initializer='glorot_normal')(x)
return x
def rpn(base_layers, num_anchors):
x = Conv2D(512, (3, 3), padding='same', activation='relu', kernel_initializer='normal', name='rpn_conv1')(base_layers)
x_class = Conv2D(num_anchors, (1, 1), activation='sigmoid', kernel_initializer='uniform', name='rpn_out_class')(x)
x_regr = Conv2D(num_anchors * 4, (1, 1), activation='linear', kernel_initializer='zero', name='rpn_out_regress')(x)
return [x_class, x_regr, base_layers]
# modify here for different initializer
def classifier(base_layers, input_rois, num_rois, nb_classes = 21, trainable=False):
# compile times on theano tend to be very high, so we use smaller ROI pooling regions to workaround
if K.backend() == 'tensorflow':
pooling_regions = 7
input_shape = (num_rois,7,7,512)
elif K.backend() == 'theano':
pooling_regions = 7
input_shape = (num_rois,512,7,7)
out_roi_pool = RoiPoolingConv(pooling_regions, num_rois)([base_layers, input_rois])
out = TimeDistributed(Flatten(name='flatten'))(out_roi_pool)
#out = TimeDistributed(Dense(4096, activation='relu', name='fc1'))(out)
out = TimeDistributed(Dense(4096, activation='relu', name='fc1', kernel_initializer='glorot_normal'))(out)
out = TimeDistributed(Dropout(0.5))(out)
#out = TimeDistributed(Dense(4096, activation='relu', name='fc2'))(out)
out = TimeDistributed(Dense(4096, activation='relu', name='fc2', kernel_initializer='glorot_normal'))(out)
out = TimeDistributed(Dropout(0.5))(out)
out_class = TimeDistributed(Dense(nb_classes, activation='softmax', kernel_initializer='zero'), name='dense_class_{}'.format(nb_classes))(out)
# note: no regression target for bg class
out_regr = TimeDistributed(Dense(4 * (nb_classes-1), activation='linear', kernel_initializer='zero'), name='dense_regress_{}'.format(nb_classes))(out)
return [out_class, out_regr]
| [
"alliance.deng@gmail.com"
] | alliance.deng@gmail.com |
deec298358d4449942d8f95f300d77c1da85a33b | 1a3d6caf89e5b51a33627458ae7c0bbb00efdc1d | /src/gluonts/torch/model/deep_npts/__init__.py | e664774be4903e7274f0dcb979a150dd03d6169c | [
"Apache-2.0"
] | permissive | zoolhasson/gluon-ts | e9ff8e4ead4d040d9f8fa8e9db5f07473cb396ed | 3dfc0af66b68e3971032a6bd0f75cd216988acd6 | refs/heads/master | 2023-01-25T01:52:57.126499 | 2023-01-13T17:50:38 | 2023-01-13T17:50:38 | 241,743,126 | 0 | 1 | Apache-2.0 | 2020-08-06T16:53:11 | 2020-02-19T22:45:54 | Python | UTF-8 | Python | false | false | 911 | py | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file 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 ._estimator import DeepNPTSEstimator
from ._network import (
DeepNPTSNetwork,
DeepNPTSMultiStepPredictor,
DeepNPTSNetworkDiscrete,
DeepNPTSNetworkSmooth,
)
__all__ = [
"DeepNPTSEstimator",
"DeepNPTSNetwork",
"DeepNPTSMultiStepPredictor",
"DeepNPTSNetworkDiscrete",
"DeepNPTSNetworkSmooth",
]
| [
"noreply@github.com"
] | zoolhasson.noreply@github.com |
41e3d1124209000af26ece6babd818361fcce763 | 03931b56387d9103002fe2ec7157faf86cabab0d | /lib/python2.7/posixpath.py | cc89aa2fcad0d515fa275985e0af4cb58f25a61c | [
"MIT"
] | permissive | yovasx2/mac-screen-auto-locker-by-face | 5d8864c74553c3097fbbc5c72c683012afa6e747 | b3853a3dda54b0b7458cef0b78c7217313653970 | refs/heads/master | 2022-12-11T08:34:32.607349 | 2018-06-08T20:28:47 | 2018-06-08T20:29:26 | 136,656,591 | 4 | 0 | MIT | 2022-12-08T02:09:26 | 2018-06-08T19:06:50 | Python | UTF-8 | Python | false | false | 83 | py | /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py | [
"delirable@gmail.com"
] | delirable@gmail.com |
a9ae66c0130c44d3d165a792cc4462e3280e0b5d | e64f33d37b19423cf82ecaf1291f0b887d1ed0c3 | /myenv/bin/django-admin.py | 871df9a4f4beaa6e697c2d425c56099db85fd7df | [] | no_license | vesuarezRZ/my-first-blog | 3de73887755bbb3cdde26a671cfc72802f224d40 | 8065da8805fc3d582262b9266c1bf73a7c0a4538 | refs/heads/master | 2020-03-25T21:59:55.873214 | 2018-08-16T18:56:56 | 2018-08-16T18:56:56 | 144,200,172 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 145 | py | #!/home/vesrz/django/myenv/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| [
"vesuarezz@gmail.com"
] | vesuarezz@gmail.com |
6aa2a79c4fdcfed72066bc8cb5c95b814b12e02c | 7dce2f4754775f4f1bcebbddd5508d062f8a6a90 | /AceVision/old/QRDetect/__init__.py | a322c45d6ef3bee19236a828d814c30cd541c38f | [
"MIT"
] | permissive | lyj911111/OpenCV_Project | 67d6bb35c90b7a8d40c20c4de3715b49d882ade7 | 9acbfbf666188b6ebb7f2ec4500bb3ab3d2994b9 | refs/heads/master | 2022-12-07T19:10:01.193459 | 2020-09-17T12:48:13 | 2020-09-17T12:48:13 | 161,764,211 | 0 | 0 | MIT | 2022-11-22T03:31:47 | 2018-12-14T09:45:43 | Python | UTF-8 | Python | false | false | 22 | py | __all__ = ['QRDetect'] | [
"lyj911111@naver.com"
] | lyj911111@naver.com |
c054a60cb42cea6481dbbb66c9606e23453f7a40 | f4322ddee013f20a49b34891213b420c67569a1b | /zabbix_sendmail_v2.7.py | 3fe5e9e3374d377c20f5f39fb714bdfa720be064 | [
"MIT"
] | permissive | WZQ1397/zabbix | 304c129e3ed089f2727084f767f4073498a7b27a | d175a01d5aefb7015181a059ad28840132398d79 | refs/heads/master | 2021-01-19T11:25:53.531050 | 2018-11-07T01:29:07 | 2018-11-07T01:29:07 | 82,243,139 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,971 | py | #!/usr/bin/python2.7
#coding:utf-8
#Mail
smtp_server ='smtp.qq.com'
smtp_port = 25
smtp_user ='wzqsergeant@vip.qq.com'
smtp_pass ='1234567890'
def send_mail(mail_to,subject,content):
msg = MIMEText(content,_subtype='plain', _charset='utf-8')
msg['Subject'] = unicode(subject,'UTF-8')
msg['From'] = smtp_user
msg['to'] = mail_to
global sendstatus
global senderr
try:
if smtp_port == 465:
smtp = smtplib.SMTP_SSL()
else:
smtp = smtplib.SMTP()
smtp.connect(smtp_server,smtp_port)
smtp.login(smtp_user,smtp_pass)
smtp.sendmail(smtp_user,mail_to,msg.as_string())
smtp.close()
print 'send ok'
sendstatus = True
except Exception,e:
senderr=str(e)
print senderr
sendstatus = False
def logwrite(sendstatus,mail_to,content):
logpath='/var/log/zabbix/alert'
if not sendstatus:
content = senderr
if not os.path.isdir(logpath):
os.makedirs(logpath)
t=datetime.datetime.now()
daytime=t.strftime('%Y-%m-%d')
daylogfile=logpath+'/'+str(daytime)+'.log'
logging.basicConfig(filename=daylogfile,level=logging.DEBUG)
os.system('chown zabbix.zabbix {0}'.format(daylogfile))
logging.info('*'*130)
logging.debug(str(t)+' mail send to {0},content is :\n {1}'.format(mail_to,content))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Send mail to user for zabbix alerting')
parser.add_argument('mail_to',action="store", help='The address of the E-mail that send to user ')
parser.add_argument('subject',action="store", help='The subject of the E-mail')
parser.add_argument('content',action="store", help='The content of the E-mail')
args = parser.parse_args()
mail_to=args.mail_to
subject=args.subject
content=args.content
send_mail(mail_to,subject,content)
logwrite(sendstatus,mail_to,content) | [
"noreply@github.com"
] | WZQ1397.noreply@github.com |
982ae1e57326f4b22e8f6243880cd0ef770d6424 | 98ed3a3b97b5e523a09936d5528b7d346c62b59b | /Backend_COD_/player.py | cdd9b74132ca84e884c4b38c8661b06f80f8d5f3 | [] | no_license | Larissa-D-Gomes/CursoPython | 231a726667aaae7d89258f872e42cdd595c3bf41 | dae2944d923c97a2de86c809a372791cf7064187 | refs/heads/master | 2022-12-03T14:10:59.902947 | 2020-08-03T17:30:29 | 2020-08-03T17:30:29 | 279,365,719 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 555 | py | """Classe para salvar dados de jogador"""
class Player:
def __init__(self, gamertag, password):
self.gamertag = gamertag
self.password = password
self.total_wins = 0
self.favorite_loadout = None
self.loudout = []
def __str__(self):
return (f'Gamertag: {self.gamertag}\n'
f'Senha: {self.password}\n'
f'Total da vitorias: {self.total_wins}\n'
f'Loadout favorito: {self.favorite_loadout}\n'
f'Loudouts: {self.loudout}\n') | [
"larissadgomes2001@gmail.com"
] | larissadgomes2001@gmail.com |
32ed9575258f7991c5a3e8769bf12f728676802c | dcc193058602f3cdd5ad9ab1cf8ae24d5ffbae28 | /king_phisher/job.py | ede8906855f3f766dab2c8194a79a268602183ea | [
"BSD-3-Clause"
] | permissive | udibott/king-phisher | 0ce6dd7636476fcd7c4e2d16fee58a6f910390cb | a61998daa70d07db6da9c23bac54032c5561c20e | refs/heads/master | 2021-01-16T00:31:34.477399 | 2015-02-19T21:12:28 | 2015-02-19T21:12:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,103 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/job.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the project nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import datetime
import logging
import threading
import time
import uuid
__version__ = '0.1'
__all__ = ['JobManager', 'JobRequestDelete']
def normalize_job_id(job_id):
"""
Convert a value to a job id.
:param job_id: Value to convert.
:type job_id: int, str
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not isinstance(job_id, uuid.UUID):
job_id = uuid.UUID(job_id)
return job_id
class JobRequestDelete(object):
"""
An instance of this class can be returned by a job callback to request
that the job be deleted and not executed again.
"""
pass
class JobRun(threading.Thread):
def __init__(self, callback, args):
super(JobRun, self).__init__()
self.daemon = False
self.callback = callback
self.callback_args = args
self.request_delete = False
self.exception = None
self.reaped = False
def run(self):
try:
result = self.callback(*self.callback_args)
if isinstance(result, JobRequestDelete):
self.request_delete = True
except Exception as error:
self.exception = error
return
# Job Dictionary Details:
# last_run: datetime.datetime
# run_every: datetime.timedelta
# job: None or JobRun instance
# callback: function
# parameters: list of parameters to be passed to the callback function
# enabled: boolean if false do not run the job
# tolerate_exceptions: boolean if true this job will run again after a failure
# run_count: number of times the job has been ran
# expiration: number of times to run a job, datetime.timedelta instance or None
class JobManager(object):
"""
This class provides a threaded job manager for periodically executing
arbitrary functions in an asynchronous fashion.
"""
def __init__(self, use_utc=True):
"""
:param bool use_utc: Whether or not to use UTC time internally.
"""
self._thread = threading.Thread(target=self._run)
self._thread.daemon = True
self._jobs = {}
self._thread_running = threading.Event()
self._thread_shutdown = threading.Event()
self._thread_shutdown.set()
self._job_lock = threading.RLock()
self.use_utc = use_utc
self.logger = logging.getLogger(self.__class__.__name__)
def _job_execute(self, job_id):
self._job_lock.acquire()
job_desc = self._jobs[job_id]
job_desc['last_run'] = self.now()
job_desc['run_count'] += 1
self.logger.debug('executing job with id: ' + str(job_id) + ' and callback function: ' + job_desc['callback'].__name__)
job_desc['job'] = JobRun(job_desc['callback'], job_desc['parameters'])
job_desc['job'].start()
self._job_lock.release()
def _run(self):
self.logger.info('the job manager has been started')
self._thread_running.set()
self._thread_shutdown.clear()
self._job_lock.acquire()
while self._thread_running.is_set():
self._job_lock.release()
time.sleep(1)
self._job_lock.acquire()
if not self._thread_running.is_set():
break
# reap jobs
jobs_for_removal = set()
for job_id, job_desc in self._jobs.items():
job_obj = job_desc['job']
if job_obj.is_alive() or job_obj.reaped:
continue
if job_obj.exception != None:
if job_desc['tolerate_exceptions'] == False:
self.logger.error('job ' + str(job_id) + ' encountered an error and is not set to tolerate exceptions')
jobs_for_removal.add(job_id)
else:
self.logger.warning('job ' + str(job_id) + ' encountered exception: ' + job_obj.exception.__class__.__name__)
if isinstance(job_desc['expiration'], int):
if job_desc['expiration'] <= 0:
jobs_for_removal.add(job_id)
else:
job_desc['expiration'] -= 1
elif isinstance(job_desc['expiration'], datetime.datetime):
if self.now_is_after(job_desc['expiration']):
jobs_for_removal.add(job_id)
if job_obj.request_delete:
jobs_for_removal.add(job_id)
job_obj.reaped = True
for job_id in jobs_for_removal:
self.job_delete(job_id)
# sow jobs
for job_id, job_desc in self._jobs.items():
if job_desc['last_run'] != None and self.now_is_before(job_desc['last_run'] + job_desc['run_every']):
continue
if job_desc['job'].is_alive():
continue
if not job_desc['job'].reaped:
continue
if not job_desc['enabled']:
continue
self._job_execute(job_id)
self._job_lock.release()
self._thread_shutdown.set()
def now(self):
"""
Return a :py:class:`datetime.datetime` instance representing the current time.
:rtype: :py:class:`datetime.datetime`
"""
if self.use_utc:
return datetime.datetime.utcnow()
else:
return datetime.datetime.now()
def now_is_after(self, dt):
"""
Check whether the datetime instance described in dt is after the
current time.
:param dt: Value to compare.
:type dt: :py:class:`datetime.datetime`
:rtype: bool
"""
return bool(dt <= self.now())
def now_is_before(self, dt):
"""
Check whether the datetime instance described in dt is before the
current time.
:param dt: Value to compare.
:type dt: :py:class:`datetime.datetime`
:rtype: bool
"""
return bool(dt >= self.now())
def start(self):
"""
Start the JobManager thread.
"""
if self._thread_running.is_set():
raise RuntimeError('the JobManager has already been started')
return self._thread.start()
def stop(self):
"""
Stop the JobManager thread.
"""
self.logger.debug('stopping the job manager')
self._thread_running.clear()
self._thread_shutdown.wait()
self._job_lock.acquire()
self.logger.debug('waiting on ' + str(len(self._jobs)) + ' job threads')
for job_desc in self._jobs.values():
if job_desc['job'] == None:
continue
if not job_desc['job'].is_alive():
continue
job_desc['job'].join()
self._thread.join()
self._job_lock.release()
self.logger.info('the job manager has been stopped')
return
def job_run(self, callback, parameters=None):
"""
Add a job and run it once immediately.
:param function callback: The function to run asynchronously.
:param parameters: The parameters to be provided to the callback.
:type parameters: list, tuple
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not self._thread_running.is_set():
raise RuntimeError('the JobManager is not running')
parameters = (parameters or ())
if not isinstance(parameters, (list, tuple)):
parameters = (parameters,)
job_desc = {}
job_desc['job'] = JobRun(callback, parameters)
job_desc['last_run'] = None
job_desc['run_every'] = datetime.timedelta(0, 1)
job_desc['callback'] = callback
job_desc['parameters'] = parameters
job_desc['enabled'] = True
job_desc['tolerate_exceptions'] = False
job_desc['run_count'] = 0
job_desc['expiration'] = 0
job_id = uuid.uuid4()
self.logger.info('adding new job with id: ' + str(job_id) + ' and callback function: ' + callback.__name__)
with self._job_lock:
self._jobs[job_id] = job_desc
self._job_execute(job_id)
return job_id
def job_add(self, callback, parameters=None, hours=0, minutes=0, seconds=0, tolerate_exceptions=True, expiration=None):
"""
Add a job to the job manager.
:param function callback: The function to run asynchronously.
:param parameters: The parameters to be provided to the callback.
:type parameters: list, tuple
:param int hours: Number of hours to sleep between running the callback.
:param int minutes: Number of minutes to sleep between running the callback.
:param int seconds: Number of seconds to sleep between running the callback.
:param bool tolerate_execptions: Whether to continue running a job after it has thrown an exception.
:param expiration: When to expire and remove the job. If an integer
is provided, the job will be executed that many times. If a
datetime or timedelta instance is provided, then the job will
be removed after the specified time.
:type expiration: int, :py:class:`datetime.timedelta`, :py:class:`datetime.datetime`
:return: The job id.
:rtype: :py:class:`uuid.UUID`
"""
if not self._thread_running.is_set():
raise RuntimeError('the JobManager is not running')
parameters = (parameters or ())
if not isinstance(parameters, (list, tuple)):
parameters = (parameters,)
job_desc = {}
job_desc['job'] = JobRun(callback, parameters)
job_desc['last_run'] = None
job_desc['run_every'] = datetime.timedelta(0, ((hours * 60 * 60) + (minutes * 60) + seconds))
job_desc['callback'] = callback
job_desc['parameters'] = parameters
job_desc['enabled'] = True
job_desc['tolerate_exceptions'] = tolerate_exceptions
job_desc['run_count'] = 0
if isinstance(expiration, int):
job_desc['expiration'] = expiration
elif isinstance(expiration, datetime.timedelta):
job_desc['expiration'] = self.now() + expiration
elif isinstance(expiration, datetime.datetime):
job_desc['expiration'] = expiration
else:
job_desc['expiration'] = None
job_id = uuid.uuid4()
self.logger.info('adding new job with id: ' + str(job_id) + ' and callback function: ' + callback.__name__)
with self._job_lock:
self._jobs[job_id] = job_desc
return job_id
def job_count(self):
"""
Return the number of jobs.
:return: The number of jobs.
:rtype: int
"""
return len(self._jobs)
def job_count_enabled(self):
"""
Return the number of enabled jobs.
:return: The number of jobs that are enabled.
:rtype: int
"""
enabled = 0
for job_desc in self._jobs.values():
if job_desc['enabled']:
enabled += 1
return enabled
def job_enable(self, job_id):
"""
Enable a job.
:param job_id: Job identifier to enable.
:type job_id: :py:class:`uuid.UUID`
"""
job_id = normalize_job_id(job_id)
with self._job_lock:
job_desc = self._jobs[job_id]
job_desc['enabled'] = True
def job_disable(self, job_id):
"""
Disable a job. Disabled jobs will not be executed.
:param job_id: Job identifier to disable.
:type job_id: :py:class:`uuid.UUID`
"""
job_id = normalize_job_id(job_id)
with self._job_lock:
job_desc = self._jobs[job_id]
job_desc['enabled'] = False
def job_delete(self, job_id, wait=True):
"""
Delete a job.
:param job_id: Job identifier to delete.
:type job_id: :py:class:`uuid.UUID`
:param bool wait: If the job is currently running, wait for it to complete before deleting it.
"""
job_id = normalize_job_id(job_id)
self.logger.info('deleting job with id: ' + str(job_id) + ' and callback function: ' + self._jobs[job_id]['callback'].__name__)
job_desc = self._jobs[job_id]
with self._job_lock:
job_desc['enabled'] = False
if wait and self.job_is_running(job_id):
job_desc['job'].join()
del self._jobs[job_id]
def job_exists(self, job_id):
"""
Check if a job identifier exists.
:param job_id: Job identifier to check.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
return job_id in self._jobs
def job_is_enabled(self, job_id):
"""
Check if a job is enabled.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
job_desc = self._jobs[job_id]
return job_desc['enabled']
def job_is_running(self, job_id):
"""
Check if a job is currently running. False is returned if the job does
not exist.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
if not job_id in self._jobs:
return False
job_desc = self._jobs[job_id]
if job_desc['job']:
return job_desc['job'].is_alive()
return False
| [
"zeroSteiner@gmail.com"
] | zeroSteiner@gmail.com |
22107023e30937e45e791d14cc3a5295aa775000 | f404932e7664293efb28f0070503140b9ecf937a | /Fundamentals/session6/Homework/bt3.py | f049b3c0c958f29677e73bea22e7b976cacbfc53 | [] | no_license | datphamjp2903/phamthanhdat-fundamental-c4e14 | b0db43c705930cccb1cd2a4fd41eeb2d30dcd68a | 4f8c9f6c827256b43a1eac821b5e959192e3b8d0 | refs/heads/master | 2021-05-06T18:05:09.045439 | 2018-01-25T13:30:27 | 2018-01-25T13:30:27 | 111,947,329 | 0 | 1 | null | 2018-01-14T05:30:17 | 2017-11-24T18:46:13 | Python | UTF-8 | Python | false | false | 117 | py | from turtle import *
def draw_square(l, c):
color(c)
for i in range(4):
forward(l)
left(90)
| [
"ptd2903@gmail.com"
] | ptd2903@gmail.com |
19f671faabb62762adaf1a72ed902ca619542c09 | a0f488c48c614b02d5d7b5c48bd72fac432c695b | /utilities.py | 5af23bf039aa3474eab1ce6ab4d57c8273dcd454 | [] | no_license | Wallidantas/Redes-RSF | 5733d4ef149dfce58fe9a178ed5bebe74aac9597 | 220e0c454bf620555780ce2643659e08f4fb87fe | refs/heads/master | 2020-07-29T02:40:05.144485 | 2019-09-19T19:47:48 | 2019-09-19T19:47:48 | 209,636,221 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 202 | py | import math as math
#Função retorna se um host alcança outro
def inRange(centerX, centerY, radius, x, y):
dist = math.sqrt((centerX - x) ** 2 + (centerY - y) ** 2)
return dist <= radius | [
"noreply@github.com"
] | Wallidantas.noreply@github.com |
a845fcc445e101abc749a3b48a3616c6322101d5 | 3c67c0f477c509cebd0b970b0f96a0c2871a9b5c | /MENU/apps.py | 99758377b84d4a4ae96ef7d344a2cb5274fcc20d | [] | no_license | beriya/COFFEEHOUSE | bb27e4eecd844c63cb74606a296bc4981c2b2a56 | 1ecddfb13df6dc53ab6523b990c5fa3e059b1932 | refs/heads/master | 2022-04-18T11:37:05.720008 | 2020-02-06T14:28:43 | 2020-02-06T14:28:43 | 223,134,458 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 88 | py | from django.apps import AppConfig
class MENUConfig(AppConfig):
name = 'MENU'
| [
"noreply@github.com"
] | beriya.noreply@github.com |
36ae8a39c510bf86409ca7c9ef6636a56718e680 | 86c5df404f99b995e64916666e49c04ab9fb8111 | /memo_for_you/tests/conftest.py | ddfef7ac9842698120775b57f302b4d29687b756 | [] | no_license | MC-Mary/organizer | 676e408d6ec7924c9c55d796543351f8d97d4aa5 | 0c02d9eb578e1185c78fe21bce759c7ea00e982b | refs/heads/main | 2023-04-15T22:01:34.263231 | 2021-04-24T17:30:01 | 2021-04-24T17:30:01 | 347,887,412 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,534 | py | import pytest
from django.contrib.auth.models import User
from django.test import Client
from memo_for_you.models import Vaccine, Person, Vaccination, ChildDevelopment, Diet
@pytest.fixture
def client():
"""Create object client in tests database."""
c = Client()
return c
@pytest.fixture
def users():
"""Create 10 objects of users in test database."""
users = []
for x in range(10):
u = User.objects.create(username=str(x))
users.append(u)
return users
@pytest.fixture
def vaccine():
"""Create 10 objects of vaccine in test database."""
vaccine_list = []
for x in range(10):
v = Vaccine.objects.create(name_of_vaccine=str(x), description='brak opisu',
recommended_age='dziecko', type='1')
vaccine_list.append(v)
return vaccine_list
@pytest.fixture
def person():
"""Create 10 objects of person in test database."""
person_list = []
for x in range(10):
p = Person.objects.create(first_name=str(x), second_name=str(x), date_of_birth='2020-03-03',
gender='1')
person_list.append(p)
return person_list
@pytest.fixture
def vaccination(vaccine, person):
"""Create 9 objects of vaccination in test database."""
vaccination_list = []
for x in range(9):
vc = Vaccination.objects.create(vaccine_id=vaccine[x], person_id=person[x],
date_of_vaccination='2020-03-03', additional='dodatkowe informacje')
vaccination_list.append(vc)
return vaccination_list
@pytest.fixture
def child_development(person):
"""Create 10 objects of child development in test database."""
count = 1
child_development_list = []
for p in person:
chd = ChildDevelopment.objects.create(person=p, date_of_entry='2020-03-20', weight='1',
height='2', head_circuit='3', additional_information=count)
count += 1
child_development_list.append(chd)
return child_development_list
@pytest.fixture
def diet():
"""Create 10 objects of diet in test database."""
diet_list = []
for x in range(10):
d = Diet.objects.create(age_of_child=x, nature_feeding=str(x), artificial_feeding='No')
diet_list.append(d)
return diet_list
@pytest.fixture(autouse=True)
def _use_static_files_storage(settings):
settings.STATICFILES_STORAGE = (
"django.contrib.staticfiles.storage.StaticFilesStorage"
)
| [
"maria.czekanska@gmail.com"
] | maria.czekanska@gmail.com |
c2d19183a63b345b7cb99d2ffe76bd9e9f890c66 | ed99dabe950130d4448b21bb0be8189dcf23ebb0 | /player_database/wsgi.py | 741e65c1225691f97a4b4275fb5e8db64e823a00 | [] | no_license | el-burrito1/player_database | 792feffdbfca51497bfac4a3e7e318b77236a576 | 1ff4bd301d4122306c2e0e06e2ef694dc280c2f4 | refs/heads/master | 2021-08-31T10:05:53.942160 | 2017-12-21T01:22:04 | 2017-12-21T01:22:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 408 | py | """
WSGI config for player_database project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "player_database.settings")
application = get_wsgi_application()
| [
"spencer.spiegel@gmail.com"
] | spencer.spiegel@gmail.com |
f2e2fe9f5840dd452768f7b73f5566b7ae7dbee5 | 49e83a1d76c49181bbe1ecd61879a1552470fbcb | /roomater/constants.py | 48ee21e2210be361c08a7c6a273015522bc574a0 | [] | no_license | jsmoxon/Roomater | 7c1483ec296af2e9da8368c211a55eb8e44c129e | 7284c84295fa39b060a48d0d0c1590f5d960fd96 | refs/heads/master | 2021-01-02T08:51:40.864469 | 2014-04-28T16:23:14 | 2014-04-28T16:23:14 | 3,475,140 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 378 | py | DOMAIN = 'localhost:8000'
ADMIN_UN = 'jackmoxon'
ADMIN_UE = ''
ADMIN_PW = 'jm'
DB_ENGINE = 'sqlite3' # mysql
DB_USER = ''
DB_PASSWORD = ''
DB_HOST = ''
DB_PORT = 3306
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'remindr.email@gmail.com'
EMAIL_HOST_PASSWORD = 'remindremail'
EMAIL_USE_TLS = True
| [
"jsmoxon@gmail.com"
] | jsmoxon@gmail.com |
9f827b5cd072b3c5a7b8abb08cbeb1c57976822f | b3ac12dfbb8fa74500b406a0907337011d4aac72 | /goldcoin/cmds/units.py | f39f52b9ed6ece8e4515e68efda51a35c69354ac | [
"Apache-2.0"
] | permissive | chia-os/goldcoin-blockchain | ab62add5396b7734c11d3c37c41776994489d5e7 | 5c294688dbbe995ae1d4422803f6fcf3e1cc6077 | refs/heads/main | 2023-08-11T23:58:53.617051 | 2021-09-12T15:33:26 | 2021-09-12T15:33:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 330 | py | from typing import Dict
# The rest of the codebase uses mojos everywhere.
# Only use these units for user facing interfaces.
units: Dict[str, int] = {
"goldcoin": 10 ** 12, # 1 goldcoin (ozt) is 1,000,000,000,000 mojo (1 trillion)
"mojo:": 1,
"colouredcoin": 10 ** 3, # 1 coloured coin is 1000 colouredcoin mojos
}
| [
"faurepierre78@yahoo.com"
] | faurepierre78@yahoo.com |
605166acc000057f4f8e1a72739b30cd9d77d644 | 17fe4529fd2772b7d046f039bde140768634d028 | /misc/samples/unittest_sample_fixture.py | ec183aa51203926248509bf02996e096d24dc86e | [] | no_license | namesuqi/tapir | b9c21f30bf781eec314f0ae4f57c232f167e4734 | a5d4e9bb45d8cbf7e41d42d9006b43b753f3ecf1 | refs/heads/master | 2020-03-07T04:16:45.213561 | 2018-03-29T08:34:46 | 2018-03-29T08:34:46 | 127,261,810 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,112 | py | # coding=utf-8
# author: zengyuetian
import unittest
def setUpModule():
print("setUpModule >>>")
def tearDownModule():
print("tearDownModule >>>")
class Test1(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("setUpClass for Test1 >>")
@classmethod
def tearDownClass(cls):
print("tearDownClass for Test1 >>")
def setUp(self):
print("setUp for Test1 >")
def tearDown(self):
print("tearDown for Test1 >")
def testCase1(self):
print("testCase1 for Test1")
def testCase2(self):
print("testCase2 for Test1")
class Test2(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("setUpClass for Test2 >>")
@classmethod
def tearDownClass(cls):
print("tearDownClass for Test2 >>")
def setUp(self):
print("setUp for Test2 >")
def tearDown(self):
print("tearDown for Test2 >")
def testCase1(self):
print("testCase1 for Test2")
def testCase2(self):
print("testCase2 for Test2")
if __name__ == "__main__":
unittest.main() | [
"suqi_name@163.com"
] | suqi_name@163.com |
bf07b530312a61ca1d011754de565c5df001fab5 | 400adf647fa45d27fe02fb889edd0ac1dd6901db | /locallibrary/wsgi.py | 5205e97e0c3c4a52b122260d9da07ede42c707b8 | [] | no_license | ChrisClaude/locallibrary | e83f53b1c35f4773c86af7c6cafec022ac27cc3e | 322bded7cefca9916b5aa4b50e548912414e8eb6 | refs/heads/master | 2023-02-05T13:30:12.356551 | 2020-12-31T14:50:26 | 2020-12-31T14:50:26 | 318,599,513 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 827 | py | """
WSGI config for locallibrary project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
# If WEBSITE_HOSTNAME is defined as an environment variable, then we're running
# on Azure App Service and should use the production settings in production.py.
# TODO: Remember to uncomment the following line to make the setting file dynamic, depending on prod or dev environments
# settings_module = 'locallibrary.production' if 'WEBSITE_HOSTNAME' in os.environ else 'locallibrary.settings'
settings_module = 'locallibrary.settings'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_module)
application = get_wsgi_application()
| [
"christ.tchambila@gmail.com"
] | christ.tchambila@gmail.com |
a07aedca0c6055b5312c6b582de6cbac7893c5b5 | db7c0f21e4248581bcfe39d285901054a0b79739 | /BinarySearch.py | 228aa62991b76dc9e78b290ed27130e752f5302a | [] | no_license | ESantosSilv/Sorting_algorithms | db9bb3f0aaa0f8739566ea867f03b61fb7756a18 | bff3c3afc1976da44d0c609a4d9ffeeca0a1d0f5 | refs/heads/master | 2021-08-23T07:23:10.650310 | 2017-12-04T03:49:27 | 2017-12-04T03:49:27 | 112,985,967 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 879 | py |
# Returns index of x in arr if present, else -1
def binarySearch (arr, l, r, x):
# Check base case
if r >= l:
mid = l + (r - l)/2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
# Else the element can only be present in right subarray
else:
return binarySearch(arr, mid+1, r, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print "Element is present at index %d" % result
else:
print "Element is not present in array"
| [
"noreply@github.com"
] | ESantosSilv.noreply@github.com |
79d06d973f4350530acd4a498fc14d7d9edb3e00 | 124b35ccbae76ba33b9044071a056b9109752283 | /Understanding_Concepts/viz/IntegratedGradientsTF/integrated_gradients_tf.py | d6198201ac70bf6560adfe7d8e5fd6aa4984b345 | [] | no_license | anilmaddu/Daily-Neural-Network-Practice-2 | 94bc78fe4a5a429f5ba911bae5f231f3d8246f61 | 748de55c1a17eae9f65d7ea08d6b2b3fc156b212 | refs/heads/master | 2023-03-08T22:04:45.535964 | 2019-03-15T23:10:35 | 2019-03-15T23:10:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,654 | py | #################################################################
# Implementation of Integrated Gradients function in Tensorflow #
# Naozumi Hiranuma (hiranumn@cs.washington.edu) #
#################################################################
import tensorflow as tf
import numpy as np
# INPUT: tensor of samples to explain
# OUTPUT: interpolated: linearly interpolated samples between input samples and references.
# stepsize: stepsizes between samples and references
# reference: a placeholder tensor for optionally specifying reference values.
def linear_inpterpolation(sample, num_steps=50):
# Constrtuct reference values if not available.
reference = tf.placeholder_with_default(tf.zeros_like(sample), shape=sample.get_shape())
# Expand sample and reference
sample_ = tf.stack([sample for _ in range(num_steps)])
reference_ = tf.stack([reference for _ in range(num_steps)])
# Get difference between sample and reference
dif = sample_ - reference_
stepsize = tf.divide(dif, num_steps)
# Get multipliers
multiplier = tf.divide(tf.stack([tf.ones_like(sample)*i for i in range(num_steps)]), num_steps)
interploated_dif = tf.multiply(dif, multiplier)
# Get parameters for reshaping
_shape = [-1] + [int(s) for s in sample.get_shape()[1:]]
perm = [1, 0]+[i for i in range(2,len(sample_.get_shape()))]
# Reshape
interploated = tf.reshape(reference_ + interploated_dif, shape=_shape)
stepsize = tf.reshape(stepsize, shape=_shape)
return interploated, stepsize, reference
# INPUT: samples: linearly interpolated samples between input samples and references. output of linear_interpolation()
# stepsizse: output of linear_interpolation()
# _output: output tensor to be explained. It needs to be connected to samples.
# OUTPUT: explanations: A list of tensors with explanation values.
def build_ig(samples, stepsizes, _output, num_steps=50):
grads = tf.gradients(ys=_output, xs=samples)
flag = False
if not isinstance(samples, list):
samples = [samples]
stepsizes = [stepsizes]
flag=True
# Estimate riemann sum
output = []
for i in range(len(samples)):
s = stepsizes[i]
g = grads[i]
riemann = tf.multiply(s, g)
riemann = tf.reshape(riemann, shape=[num_steps,-1]+[int(s) for s in s.get_shape()[1:]])
explanation = tf.reduce_sum(riemann, axis=0)
output.append(explanation)
# Return the values.
if flag:
return output[0]
else:
return output
# -- end code -- | [
"jae.duk.seo@ryerson.ca"
] | jae.duk.seo@ryerson.ca |
95e4c2ce847b67bf0f5a24fa2290dbe1ac99f9ba | a565367e785c7e72dfb6a003a55cdf2a70f8d563 | /skynet/custom_logger.py | ad8ab1590c01e47e746a5ce307f7d5aaa9e0c0b6 | [] | no_license | bsterrett/ye_olde_skynet | 2dd330b2864e1bb7bd02e9c3f07929f8e7612864 | 43ab187a9bca4c56d6005a46725c56f39949fceb | refs/heads/master | 2021-07-16T22:40:42.193820 | 2017-10-24T01:27:37 | 2017-10-24T01:27:37 | 105,616,515 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,312 | py | import logging
import sys
from os.path import abspath
GLOBAL_LOG_PATH = abspath('logs/global.log')
DEFAULT_CUSTOM_LOG_PATH = abspath('logs/custom_logger.log')
def getLogger(log_name='', log_level=logging.DEBUG):
if len(log_name.strip()) > 0:
logger = logging.getLogger(log_name.strip())
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
else:
logger = logging.getLogger()
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
stdout_stream_handler = logging.StreamHandler(sys.stdout)
stdout_stream_handler.setLevel(log_level)
stdout_stream_handler.setFormatter(formatter)
logger.addHandler(stdout_stream_handler)
file_handler = logging.FileHandler(filename=GLOBAL_LOG_PATH, mode='w')
file_handler.setLevel(log_level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
if len(log_name.strip()) == 0:
custom_log_path = DEFAULT_CUSTOM_LOG_PATH
else:
custom_log_path = abspath(f"logs/{log_name}.log")
file_handler = logging.FileHandler(filename=custom_log_path, mode='w')
file_handler.setLevel(log_level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(log_level)
return logger
| [
"bs11868@gmail.com"
] | bs11868@gmail.com |
2d47584cc285e651a8922bba2e32fc4444a70c09 | b75e0783531680d90c88dd07d6d2f5399eb31a8f | /wwp/PlazaXMLGenerator.py | d2092b0e41ff6a801f3d806b0039d8b520b95f84 | [] | no_license | jacquesCedric/WiiUScripts | 3df11554bfceca72d69ed76f5508017c177de9ca | f0e602dd49d68e997ef35a3275efdc3a4806879d | refs/heads/master | 2021-06-08T14:25:08.392544 | 2021-05-24T22:05:14 | 2021-05-24T22:05:14 | 183,830,827 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,550 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Jacob Gold"
__copyright__ = "Copyright 2021, Jacob Gold"
__credits__ = ["Jacob Gold"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Jacob Gold"
__status__ = "Prototype"
"""
Generating 1stNUP.xml files for use with Nintendo Wii U's Wara Wara Plaza
"""
from lxml import etree
import collections
import random
messages = []
ids = []
communityid = 4294967295 #this is random, but they need to be unique for each topic
# Process all the data we've been collating from discord
def grabContent():
m_common = []
raw_messages = []
# First we process messages
with open("text/msg.txt") as f:
for line in f:
raw_messages.append(line.strip())
for i in list(chunks(raw_messages, 10)):
messages.append(i)
# Then votes
with open("text/vote.txt") as f:
split = f.read().split()
counts = collections.Counter(split)
m_common = counts.most_common(10)
# Lets refine those votes and get some details
for tup in m_common:
ids.append(detailsFromID(tup[0]))
def generateBase():
root = etree.Element('result')
version = subElementWithText(root, 'version', "1")
has_error = subElementWithText(root, 'has_error', "0")
request_name = subElementWithText(root, 'request_name', "topics")
expire = subElementWithText(root, 'expire', "2100-01-01 10:00:00")
# the meat
topics = etree.SubElement(root, 'topics')
for x in range(0,len(ids)):
icon = ""
t = ids[x]
s = t.split(';')
with open("images/data/" + s[0]) as i:
icon = i.read()
t1 = generateTopic(icon, s[0], 4294967295 + x, s[1], messages[x])
topics.append(t1)
return root
def generateTopic(icon, titleID, commID, name, msgs):
topic = etree.Element('topic')
iconfield = subElementWithText(topic, 'icon', icon)
titleid = subElementWithText(topic, 'title_id', str(titleID))
communityid = subElementWithText(topic, 'community_id', str(commID))
isrecommended = subElementWithText(topic, 'is_recommended', "0")
namefield = subElementWithText(topic, 'name', name)
participantcount = subElementWithText(topic, 'participant_count', "0")
# Add people
people = etree.SubElement(topic, "people")
for message in msgs:
person = generatePerson(titleID, message, commID)
people.append(person)
# End add people
empathyCount = subElementWithText(topic, "empathy_count", "0")
hasShopPage = subElementWithText(topic, "has_shop_page", "0")
modifiedAt = subElementWithText(topic, "modified_at", "2019-04-23 06:35:47")
position = subElementWithText(topic, "position", "2")
return topic
def generatePerson(titleID, message, communityid):
s = message.split(';;')
person = etree.Element('person')
posts = generateTextPost(titleID, s[1], s[2], s[0], communityid)
person.append(posts)
return person
def generateTextPost(titleID, text, author, time, communityid):
posts = etree.Element('posts')
post = etree.SubElement(posts, 'post')
body = subElementWithText(post, 'body', text)
communityid = subElementWithText(post, 'community_id', str(communityid))
countryid = subElementWithText(post, 'country_id', "110")
createdat = subElementWithText(post, 'created_at', str(time))
feelingid = subElementWithText(post, 'feeling_id', "1")
postid = subElementWithText(post, 'id', "AYMHAAADAAADV44piZWWdw")
autopost = subElementWithText(post, 'is_autopost', "0")
commprivate = subElementWithText(post, 'is_community_private_autopost', "0")
spoiler = subElementWithText(post, 'is_spoiler', "0")
jumpy = subElementWithText(post, 'is_app_jumpable', "0")
empathy =subElementWithText(post, 'empathy_count', "5")
lang = subElementWithText(post, 'language_id', "1")
mii = subElementWithText(post, 'mii', randomMii())
face = subElementWithText(post, 'mii_face_url', "")
number = subElementWithText(post, 'number', "0")
pid = subElementWithText(post, 'pid', "")
platf = subElementWithText(post, 'platform_id', "1")
region = subElementWithText(post, 'region_id', "4")
reply = subElementWithText(post, 'reply_count', "0")
screen = subElementWithText(post, 'screen_name', author)
titleid = subElementWithText(post, 'title_id', str(titleID))
return posts
def generateImagePost(image):
print("not implemented yet")
# Helper functions
# Grab details using a titleID
def detailsFromID(titleID):
with open("text/titleinfo.txt") as f:
for line in f:
if line[8:16] == titleID[8:16]:
return line.strip()
return 0
# Syntactic sugar for etree stuff
def subElementWithText(root, tag, content):
node = etree.SubElement(root, tag)
node.text = content
return node
# Grab a random mii, needs to be refined
def randomMii():
with open("text/miiArray.txt") as f:
line = next(f)
for num, aline in enumerate(f, 2):
if random.randrange(num):
continue
line = aline
return line
# Divide list into n equal-ish groups
def chunks(seq, size):
return (seq[i::size] for i in range(size))
# Main script
def main():
grabContent()
base = generateBase()
tree = etree.ElementTree(base)
with open('1stNUP.xml', 'wb') as f:
f.write(etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding='UTF-8'))
if __name__ == "__main__":
main()
| [
"12831497+jacquesCedric@users.noreply.github.com"
] | 12831497+jacquesCedric@users.noreply.github.com |
e5f8dd86564f6f2ac9a03aeef761b298c102eb92 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /gH3QMvF3czMDjENkk_9.py | 19552a338cba87d2d304d1d2bbfb9850243e1af0 | [] | 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 | 838 | py | """
Create a function that takes a list and string. The function should remove the
letters in the string from the list, and return the list.
### Examples
remove_letters(["s", "t", "r", "i", "n", "g", "w"], "string") ➞ ["w"]
remove_letters(["b", "b", "l", "l", "g", "n", "o", "a", "w"], "balloon") ➞ ["b", "g", "w"]
remove_letters(["d", "b", "t", "e", "a", "i"], "edabit") ➞ []
### Notes
* If number of times a letter appears in the list is greater than the number of times the letter appears in the string, the extra letters should be left behind (see example #2).
* If all the letters in the list are used in the string, the function should return an empty list (see example #3).
"""
def remove_letters(letters, word):
l = letters
for i in word:
if i in l:
l.remove(i)
return l
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
4728042cbeb6201f811568fdf61bb553ebc3dfae | bd19334c4698932a708afce4bcc208c7d9a3616b | /Q41.py | 8f99ea1ed698ca838b80d8808108f180dd96c636 | [] | no_license | Timothy-py/100-PythonChallenges | b9607cfc5fd27992321d6638a046f2f335f6e05d | f64a1b923a555268f4db38af04dcd354885aa231 | refs/heads/master | 2023-05-31T09:48:31.130970 | 2023-05-23T22:45:04 | 2023-05-23T22:45:04 | 208,028,848 | 2 | 1 | null | 2023-05-23T22:39:06 | 2019-09-12T10:50:43 | Python | UTF-8 | Python | false | false | 82 | py | # Pleas raise a RuntimeError exception.
raise RuntimeError("something is fishy")
| [
"adeyeyetimothy33@gmail.com"
] | adeyeyetimothy33@gmail.com |
9447ef8bb9b49c3575225d440cc3c8b9677ea6b2 | 9190ed3377273fae3278979e0208f94680209f31 | /Pandas_Seaborn_Scikit.py | 27b9b4d8ee58a20833ab93784444c8da6053ecca | [] | no_license | IamYourAlpha/Python-for-machine-learning- | 6015c077ce7ae72fdebfb8b972de6b850e6b7713 | 7764ee84ec0aa756fa842a34e601f614a86e01a6 | refs/heads/master | 2021-05-08T02:15:30.915233 | 2017-11-01T17:09:34 | 2017-11-01T17:09:34 | 107,994,335 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 672 | py | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LinearRegression
# read the data
data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
#sns.pairplot(data, x_vars=['TV', 'radio', 'newspaper'], y_vars='sales', size=7, aspect=0.7, kind='reg')
#plt.show()
feature_cols = ['TV', 'radio', 'newspaper']
x = data[feature_cols]
y = data['sales']
x_train, y_train, x_test, y_test = train_test_split(x, y, random_state = 1)
print x_train
print y_train
linReg = LinearRegression()
linReg.fit(data['TV'], data['sales'])
print linReg
| [
"intisarcs@gmail.com"
] | intisarcs@gmail.com |
4d219c26200be5b7c917f798f9bf654400bbeb23 | 22967e0d24a7fd4d27e0384cd693c7277798abb1 | /ReactDjx/settings.py | 7edff52979bdcf3a83ac1b9dbdbc04067cfc4273 | [] | no_license | AntonioAMPY/Conexion-Django-R1 | eb1441ec424b9d57c091afdfbc9c261762be75a2 | 4c50ad768a79f0356567ee69e88b1f3b18df1a20 | refs/heads/master | 2022-07-04T01:35:06.092167 | 2020-05-15T04:38:37 | 2020-05-15T04:38:37 | 264,096,600 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,257 | py | """
Django settings for ReactDjx project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gc7c4v$(@_6@ie=w8+0e@_of1yq6wnb5wb17g0n7fze&h*4ad_'
# 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',
'ReactDjxApp'
]
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 = 'ReactDjx.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,'../frontrdjx/build'),
],
'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 = 'ReactDjx.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/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.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'../frontrdjx/build/static')
] | [
"antoniozkt@gmail.com"
] | antoniozkt@gmail.com |
26f18c303e12dd1ea296568f3185d5b1df7582fe | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/pa3/sample/op_cmp_int-106.py | 89011902bfe43fdb6bd7bee90efed2d33564d626 | [] | no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 186 | py | x:int = 42
y:int = 7
print(x == y)
print(x != y)
print(x < y)
print(x <= y)
print(x > y)
print(x >= y)
$Var(x == x)
print(x != x)
print(x < x)
print(x <= x)
print(x > x)
print(x >= x)
| [
"647530+Virtlink@users.noreply.github.com"
] | 647530+Virtlink@users.noreply.github.com |
cc9411b7251704073d70f510559e49b20473e415 | 4e30d990963870478ed248567e432795f519e1cc | /tests/models/validators/v3_1_patch_1/jsd_df4fb303a3e5661ba12058f18b225af.py | f31472450dc722d87e16a1a2c2c919e92e4c5463 | [
"MIT"
] | permissive | CiscoISE/ciscoisesdk | 84074a57bf1042a735e3fc6eb7876555150d2b51 | f468c54998ec1ad85435ea28988922f0573bfee8 | refs/heads/main | 2023-09-04T23:56:32.232035 | 2023-08-25T17:31:49 | 2023-08-25T17:31:49 | 365,359,531 | 48 | 9 | MIT | 2023-08-25T17:31:51 | 2021-05-07T21:43:52 | Python | UTF-8 | Python | false | false | 8,158 | py | # -*- coding: utf-8 -*-
"""Identity Services Engine getNetworkAccessConditions data model.
Copyright (c) 2021 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import json
from builtins import *
import fastjsonschema
from ciscoisesdk.exceptions import MalformedRequest
class JSONSchemaValidatorDf4Fb303A3E5661Ba12058F18B225Af(object):
"""getNetworkAccessConditions request schema definition."""
def __init__(self):
super(JSONSchemaValidatorDf4Fb303A3E5661Ba12058F18B225Af, self).__init__()
self._validator = fastjsonschema.compile(json.loads(
'''{
"$schema": "http://json-schema.org/draft-04/schema#",
"properties": {
"response": {
"items": {
"properties": {
"attributeName": {
"type": "string"
},
"attributeValue": {
"type": "string"
},
"children": {
"items": {
"properties": {
"conditionType": {
"enum": [
"ConditionAndBlock",
"ConditionAttributes",
"ConditionOrBlock",
"ConditionReference",
"LibraryConditionAndBlock",
"LibraryConditionAttributes",
"LibraryConditionOrBlock",
"TimeAndDateCondition"
],
"type": "string"
},
"isNegate": {
"type": "boolean"
},
"link": {
"properties": {
"href": {
"type": "string"
},
"rel": {
"enum": [
"next",
"previous",
"self",
"status"
],
"type": "string"
},
"type": {
"type": "string"
}
},
"type": "object"
}
},
"type": "object"
},
"type": "array"
},
"conditionType": {
"enum": [
"ConditionAndBlock",
"ConditionAttributes",
"ConditionOrBlock",
"ConditionReference",
"LibraryConditionAndBlock",
"LibraryConditionAttributes",
"LibraryConditionOrBlock",
"TimeAndDateCondition"
],
"type": "string"
},
"datesRange": {
"properties": {
"endDate": {
"type": "string"
},
"startDate": {
"type": "string"
}
},
"type": "object"
},
"datesRangeException": {
"properties": {
"endDate": {
"type": "string"
},
"startDate": {
"type": "string"
}
},
"type": "object"
},
"description":
{
"type": "string"
},
"dictionaryName": {
"type": "string"
},
"dictionaryValue": {
"type": "string"
},
"hoursRange": {
"properties": {
"endTime": {
"type": "string"
},
"startTime": {
"type": "string"
}
},
"type": "object"
},
"hoursRangeException": {
"properties": {
"endTime": {
"type": "string"
},
"startTime": {
"type": "string"
}
},
"type": "object"
},
"id": {
"type": "string"
},
"isNegate": {
"type": "boolean"
},
"link": {
"properties": {
"href": {
"type": "string"
},
"rel": {
"enum": [
"next",
"previous",
"self",
"status"
],
"type": "string"
},
"type": {
"type": "string"
}
},
"type": "object"
},
"name": {
"type": "string"
},
"operator": {
"enum": [
"contains",
"endsWith",
"equals",
"greaterOrEquals",
"greaterThan",
"in",
"ipEquals",
"ipGreaterThan",
"ipLessThan",
"ipNotEquals",
"lessOrEquals",
"lessThan",
"matches",
"notContains",
"notEndsWith",
"notEquals",
"notIn",
"notStartsWith",
"startsWith"
],
"type": "string"
},
"weekDays": {
"items": {
"enum": [
"Friday",
"Monday",
"Saturday",
"Sunday",
"Thursday",
"Tuesday",
"Wednesday"
],
"type": "string"
},
"type": "array"
},
"weekDaysException": {
"items": {
"enum": [
"Friday",
"Monday",
"Saturday",
"Sunday",
"Thursday",
"Tuesday",
"Wednesday"
],
"type": "string"
},
"type": "array"
}
},
"type": "object"
},
"type": "array"
},
"version": {
"type": "string"
}
},
"required": [
"response",
"version"
],
"type": "object"
}'''.replace("\n" + ' ' * 16, '')
))
def validate(self, request):
try:
self._validator(request)
except fastjsonschema.exceptions.JsonSchemaException as e:
raise MalformedRequest(
'{} is invalid. Reason: {}'.format(request, e.message)
)
| [
"bvargas@altus.cr"
] | bvargas@altus.cr |
472738571aaa55cbb527139e35663f60fb49a5e3 | 12c26007fdb77e855eaec44cc4cc09ba2807f0ef | /open_elections/dolt/states/ct.py | 555133cab62259ea180a50578571f8636fd6239e | [] | no_license | openelections/open-elections-tools | 73daa17ba685284e2003e89c4ab1239babf0e131 | 606be58f11f95613ee8c91501c828d51c56d235f | refs/heads/master | 2022-11-30T01:57:51.212785 | 2020-08-06T21:05:53 | 2020-08-06T21:05:53 | 285,266,558 | 1 | 1 | null | 2020-08-05T11:20:31 | 2020-08-05T11:20:30 | null | UTF-8 | Python | false | false | 738 | py | from open_elections.tools import StateDataFormat, get_coerce_to_integer
import pandas as pd
def fix_vote_counts(df: pd.DataFrame) -> pd.DataFrame:
if 'total' in df.columns:
return df.rename(columns={'total': 'votes'})
else:
breakout_cols = [col for col in ['poll', 'edr', 'abs'] if col in df.columns]
if breakout_cols:
temp = df.copy()
for col in breakout_cols:
if col in temp.columns:
temp[col] = temp[col].apply(get_coerce_to_integer([' - ']))
return temp.assign(votes=df[breakout_cols].sum(axis=1))
else:
return df
national_precinct_dataformat = StateDataFormat(
df_transformers=[fix_vote_counts]
)
| [
"oscar@liquidata.co"
] | oscar@liquidata.co |
9c7b63a6d2fe01845a5f9866a4b4465e0425a73d | 989a03da2ed7169f8e3040227c4b7322f3d43b18 | /test/request.py | 58bfbd031af54465f1626f0dcb79ee534db20a90 | [] | no_license | wp931120/Seach_engine | 7e89c80d664716a968ec08533fd82855de71f9f8 | 13e3301431bf318786b538e5a9bae191c440a63e | refs/heads/master | 2021-12-29T08:09:24.621218 | 2020-02-25T05:18:34 | 2020-02-25T05:18:34 | 242,909,950 | 9 | 1 | null | 2020-02-25T04:33:59 | 2020-02-25T04:31:24 | JavaScript | UTF-8 | Python | false | false | 178 | py | import requests
import json
if __name__ == "__main__":
url = "http://localhost:5000/search"
d = {'data': '债券'}
r = requests.post(url, data=d)
print (r.text) | [
"matt.wang@gaodun.com"
] | matt.wang@gaodun.com |
28535fada1c73a8789a1fe68a5f659bd489e23fc | 8cafbd82a14835d5bc39e7121bc50c5a7416e36c | /5/5.py | 5e33d80426de140b8f8af2a5d700cd2c11037944 | [] | no_license | bo-chen/advent2020 | 25e01c0d60499eb903ce796abbab0ea38c887fc0 | 9fc279ea5b52f2d213eede89468713ce0a2d010d | refs/heads/master | 2023-02-03T01:27:38.943380 | 2020-12-25T05:20:49 | 2020-12-25T05:20:49 | 317,435,673 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 858 | py | import sys
import os
import re
ma = 0
mi = 10000
nums = {}
with open("./input.txt") as fp:
for line in fp:
l = list(line.strip())
rt = l[0:7]
ct = l[7:10]
row = 0
for rl in rt:
row = row << 1
if rl == "F":
row += 0
elif rl == "B":
row += 1
else:
print("BAD")
col = 0
for cl in ct:
col = col << 1
if cl == "L":
col += 0
elif cl == "R":
col += 1
else:
print("BAD2")
id = (row * 8 + col)
if id > ma:
ma = id
if id < mi:
mi = id
nums[id] = 1
for id in range(mi, ma):
if id not in nums.keys():
print(id)
print(mi)
print(ma)
# print()
| [
"bo@liftoff.io"
] | bo@liftoff.io |
df9e1ed2fbda2454efd1784b026e5a2e8aa25d2a | 66d339399671f9520e88d79b7118b6670f6a40a2 | /CheckWeb/Checkapp/apps.py | 4ee45b7130ebc5a7e7d5ea707111249ce199c855 | [
"MIT"
] | permissive | Tarpelite/OJ_research | 038ba1b3a5d8add01642cddd45b59722144ac110 | 5c23591a50e755dac800dfaedb561290ce35fc5b | refs/heads/master | 2020-06-07T10:52:17.059468 | 2019-06-21T10:47:56 | 2019-06-21T10:47:56 | 193,003,111 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 91 | py | from django.apps import AppConfig
class CheckappConfig(AppConfig):
name = 'Checkapp'
| [
"tarpelite_chan@foxmail.com"
] | tarpelite_chan@foxmail.com |
75fcd97a128d5644a6466ec27ccb43ccbde3e28c | dfac96ad523300aba94e608b37ee1485c7be0d53 | /sallybrowse/sallybrowse.py | 569bd6eb4db149470b985e9d766d316e8ccb58c0 | [
"MIT"
] | permissive | XiuyuanLu/browse | ff07a9d5316fdcbfd5ad259be85d5ebd30120d99 | ee5ca57e54fe492d5b109b7cae87d1c8a45dbe25 | refs/heads/master | 2023-04-07T21:24:10.538331 | 2021-04-14T06:43:34 | 2021-04-14T06:43:34 | 295,688,060 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 76 | py | #!/usr/bin/env python3
from sallybrowse import app
app.run(debug = True)
| [
"simon@simonallen.org"
] | simon@simonallen.org |
6076c919a7fc64e1832cdfff14fd936313f6f605 | 3fd7adb56bf78d2a5c71a216d0ac8bc53485b034 | /tensorflow_data/position_ctrl_action5r3_rel/conf.py | 968527a0c3070d794fdb27d5931531bfada19c90 | [] | no_license | anair13/lsdc | 6d1675e493f183f467cab0bfe9b79a4f70231e4e | 7760636bea24ca0231b4f99e3b5e8290c89b9ff5 | refs/heads/master | 2021-01-19T08:02:15.613362 | 2017-05-12T17:13:54 | 2017-05-12T17:13:54 | 87,596,344 | 0 | 0 | null | 2017-04-08T00:18:55 | 2017-04-08T00:18:55 | null | UTF-8 | Python | false | false | 1,872 | py | import os
current_dir = os.path.dirname(os.path.realpath(__file__))
# tf record data location:
DATA_DIR = '/'.join(str.split(current_dir, '/')[:-2]) + '/pushing_data/position_control_a5r3rel/train'
# local output directory
OUT_DIR = current_dir + '/modeldata'
from video_prediction.prediction_model_downsized_lesslayer import construct_model
configuration = {
'experiment_name': 'position_rel',
'data_dir': DATA_DIR, # 'directory containing data.' ,
'output_dir': OUT_DIR, #'directory for model checkpoints.' ,
'current_dir': current_dir, #'directory for writing summary.' ,
'num_iterations': 50000, #'number of training iterations.' ,
'pretrained_model': '', # 'filepath of a pretrained model to resume training from.' ,
'sequence_length': 15, # 'sequence length, including context frames.' ,
'skip_frame': 1, # 'use ever i-th frame to increase prediction horizon' ,
'context_frames': 2, # of frames before predictions.' ,
'use_state': 1, #'Whether or not to give the state+action to the model' ,
'model': 'DNA', #'model architecture to use - CDNA, DNA, or STP' ,
'num_masks': 1, # 'number of masks, usually 1 for DNA, 10 for CDNA, STN.' ,
'schedsamp_k': 900.0, # 'The k hyperparameter for scheduled sampling -1 for no scheduled sampling.' ,
'train_val_split': 0.95, #'The percentage of files to use for the training set vs. the validation set.' ,
'batch_size': 32, #'batch size for training' ,
'learning_rate': 0.001, #'the base learning rate of the generator' ,
'visualize': '', #'load model from which to generate visualizations
'downsize': construct_model, #'create downsized model'
'file_visual': '', # datafile used for making visualizations
'penal_last_only': False # penalize only the last state, to get sharper predictions
}
| [
"frederik.ebert@mytum.de"
] | frederik.ebert@mytum.de |
c09c0a48761b306938e8821c8710afe993aabce5 | 7d4fa66bea9d1526b60ff441498cf1958815e476 | /scripts/microdata_extract.py | d47a2f3d15583789656634cd099f8836674586e8 | [] | no_license | automatist/lgm-video-archive | 5bee1f4cf1a403d85dd8acf2221eb327d9cfcce9 | 83ee820101f8873c7372e5b3a51e374a69133ec2 | refs/heads/master | 2021-01-18T21:58:57.800994 | 2016-04-10T15:34:18 | 2016-04-10T15:34:18 | 38,053,112 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,055 | py | from __future__ import print_function
import microdata, json, sys, re
from argparse import ArgumentParser
p = ArgumentParser("")
p.add_argument("--add", action="append", default=[], help="add default value pairs, ex. --add city=Brussels year=2000")
p.add_argument("--output", default="-", help="output, default: - for stdout")
p.add_argument("input", nargs="*", default=[], help="input")
args = p.parse_args()
def parse_value(v):
v = v.strip()
if re.search(r"^\d*\.\d+$", v):
return float(v)
elif re.search(r"^\d+$", v):
return int(v)
else:
return v
defaults = {}
if args.add != None:
for p in args.add:
n, v = p.split("=", 1)
defaults[n] = parse_value(v)
# print (defaults)
# sys.exit()
if args.output == "-":
out = sys.stdout
else:
out = open(args.output, "w")
data = {}
data['items'] = items = []
for i in args.input:
with open(i) as f:
for item in microdata.get_items(f):
for n, v in defaults.items():
item.set(n, v)
items.append(item.json_dict())
print(json.dumps(data, indent=2), file=out)
| [
"mm@automatist.org"
] | mm@automatist.org |
75ccc26a4c4472390ed15c91ff1250d21f8742ba | 9bb521d515a2401b69df797efed11b04e04401a7 | /tests/runtests-herd.py | 6b8ab527d581912293ea513b8d1152d11ea11811 | [
"BSD-3-Clause"
] | permissive | risent/django-redis | be512f1bf6c51b8e238e2fa8b1eec5073c03916e | 46bfd076c197846035e3f31348748d464ace74d0 | refs/heads/master | 2021-01-14T14:10:59.664982 | 2015-06-11T20:15:28 | 2015-06-11T20:15:28 | 37,450,021 | 0 | 0 | null | 2015-06-15T07:25:20 | 2015-06-15T07:25:20 | null | UTF-8 | Python | false | false | 311 | py | # -*- coding: utf-8 -*-
import os, sys
sys.path.insert(0, '..')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_sqlite_herd")
if __name__ == "__main__":
from django.core.management import execute_from_command_line
args = sys.argv
args.insert(1, "test")
execute_from_command_line(args)
| [
"niwi@niwi.be"
] | niwi@niwi.be |
83e39951b992f2e1fe92e289d2a30efc38a66df9 | 3e17606da0f946a2a5f9f0d2949b1a08c015252b | /Paiza_Prac/SkillChallenge/C-Rank/C-25_Faxの用紙回収/C-25_FaxPaper.py | 57d975c2a65639c9a084120a60f9756f45f53391 | [] | no_license | nao-j3ster-koha/Py3_Practice | 03a5ba57acdb4df964fcfc6b15afdd2f0d833ef1 | 4f64ddc022449060a67f7b0273c65d8f1ff8c680 | refs/heads/master | 2021-10-09T11:04:03.047530 | 2018-10-16T09:15:59 | 2018-10-16T09:15:59 | 103,068,457 | 0 | 0 | null | 2018-10-16T08:47:04 | 2017-09-10T23:12:42 | Python | UTF-8 | Python | false | false | 784 | py | cap = int(input())
n = int(input())
rndCount = 0
hrNum = 0
hrPaperCount = 0
for i in range(n):
tmpList = list(map(int, input().split()))
if i == 0:
hrNum = tmpList[0]
hrPaperCount = tmpList[2]
elif i != n-1:
if hrNum == tmpList[0]:
hrPaperCount += tmpList[2]
elif hrNum != tmpList[0]:
hrNum = tmpList[0]
if int(hrPaperCount % cap) == 0:
rndCount += int(hrPaperCount / cap )
else: rndCount += int(hrPaperCount / cap ) + 1
hrPaperCount = tmpList[2]
elif i == n-1:
hrPaperCount += tmpList[2]
if int(hrPaperCount % cap) == 0:
rndCount += int(hrPaperCount / cap )
else: rndCount += int(hrPaperCount / cap ) + 1
print(rndCount) | [
"sdvr.nao@gmail.com"
] | sdvr.nao@gmail.com |
c582e93c8975075d04eab49820c53057c7244b5c | 9656b84f4c0616f38eff3b11c0111a7d1d3545e9 | /3/prestejLabele.py | f7e5da02b6e7d5349147f408ffb40b4008ef1ed0 | [] | no_license | majcn/dataMining | 641fa05c2bf59a5deb24a0f7b9a2e6dd2a4716b6 | 70d3200491f9ea19d4ddb6f1f35a3c7e8c2f4e1f | refs/heads/master | 2021-01-25T03:54:37.018773 | 2012-05-21T03:55:25 | 2012-05-21T03:55:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 630 | py | from collections import Counter
f = open("minidata/trainingLabels.csv")
a = []
for line in f:
a.append([int(v) for v in line.strip().split(",")])
#cc = Counter([i for i in a])
cc = Counter()
for i in a:
cc.update(i)
ccc = [i[0] for i in cc.most_common(25)]
c = Counter([len(i) for i in a])
f = open("tt.txt")
fout = file("tt.txt.reduced", "w")
a = []
for line in f:
temp = [i for i in [int(v) for v in line.strip().split(" ")] if i in ccc]
for i in temp:
fout.write(str(i)+" ")
if temp == []:
fout.write("40")
fout.write("\n")
fout.close()
#mostCommon = [i[0] for i in dd.most_common(4)] | [
"majcn.m@gmail.com"
] | majcn.m@gmail.com |
a269e979f86ce8957e94c878e791703c14d8db6c | ffe662f49fc2fa985b044947211c9653cb5de789 | /campaignManager/campaignManager/invitations/migrations/0003_invitation_email.py | 992afcd4fa1ddc8919b45f7d75455f6e3db16273 | [
"MIT"
] | permissive | didymus13/kangaroo-black | c7d33e614e3be20b7c63deab11a62dbfc8daee87 | 6fc3a66b43ff734975e4dc2054334bf63ddea7c6 | refs/heads/master | 2016-09-05T15:27:26.231683 | 2014-12-19T16:21:04 | 2014-12-19T16:21:04 | 21,215,024 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 481 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('invitations', '0002_remove_invitation_email'),
]
operations = [
migrations.AddField(
model_name='invitation',
name='email',
field=models.EmailField(default='example@example.com', max_length=254),
preserve_default=False,
),
]
| [
"didymus1313@gmail.com"
] | didymus1313@gmail.com |
b5e0ecb12d1a08d474b999ffd8cb4e5b4519bddb | 6ab0b754395a3db3fda0c9c223a29bbe0220a63d | /salsafuego/accessories_DELETE/urls.py | 1e1b0f7e34eb3d95b87578462b2913dbb068bb70 | [] | no_license | SalsaFuego/coeus | c221fee5bff3ac7fe9669ff6f1352a07091f3168 | 9782b0cf6f5d539011201527b0b1305a8c0001e4 | refs/heads/master | 2020-04-24T21:24:34.938989 | 2019-03-10T19:47:32 | 2019-03-10T19:47:32 | 172,276,626 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 121 | py | from django.urls import path
from . import views
urlpatterns = [
path("", views.accessories, name="accessories")
]
| [
"nwc@nicchappell.com"
] | nwc@nicchappell.com |
d1f27aa225ffe360f4a6845866b0b75f29f289c6 | 23ce59384de2187560c0ebe4c8ac4ac2367efceb | /stringmethods.py | e0df005dda3d64344bd575e96fa41eec3838208f | [] | no_license | hitu8595/learn-python | 3b0ea1c7492aeaff1359813cf5c904fddb3eedfe | fc9e4883ea3301f644a9266b3fe54336e2834132 | refs/heads/master | 2023-02-15T16:06:01.081481 | 2021-01-11T22:33:53 | 2021-01-11T22:33:53 | 282,061,463 | 0 | 0 | null | 2021-01-11T22:33:55 | 2020-07-23T21:43:05 | Python | UTF-8 | Python | false | false | 262 | py | ourString = "This is our string"
lengthofstring = len(ourString)
print(lengthofstring)
print(ourString.upper())
print(ourString.lower())
print(ourString.title())
email_Introduction = "Hello My Name is {} {}"
print(email_Introduction.format("Hitu", "Patel")) | [
"patelhitasvi@gmail.com"
] | patelhitasvi@gmail.com |
067232b530e3cf95e693a8150641b7ad869e65cc | 1e7b7f6d4266844ac46d737188c1b664fe222f64 | /scraper.py | d66da9707ea3e2da22aa82a6b6b4eb75f175ad5e | [] | no_license | christopherekfeldt/Webscraper | bb80580d241ef271fb42b22584bcf49d5f958d21 | 2c833f05a4385281280a4b9eae5109e3ff6b549d | refs/heads/master | 2021-08-07T01:33:48.114751 | 2020-10-07T10:39:22 | 2020-10-07T10:39:22 | 224,911,566 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,379 | py | import requests
from bs4 import BeautifulSoup
import smtplib
import json
with open("config.json") as config:
data = json.load(config)
URL = 'https://www.pricerunner.se/pl/226-4474441/Golf/Callaway-Rogue-Fairway-Wood-priser'
headers = {"User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}
def check_price():
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
title = soup.find("div", class_="_3ua0LznGtn").get_text()
price = soup.find("meta", itemprop="lowPrice")
price = price["content"] if price else None
price = int(price)
print(title)
print(price)
if (price < 1500):
send_mail()
def send_mail():
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(data.get('server').get('username'), data.get('server').get('password'))
subject = "The price fell down!"
body = "Check the pricerunner link https://www.pricerunner.se/pl/226-4474441/Golf/Callaway-Rogue-Fairway-Wood-priser"
msg = f"Subject: {subject}\n\n{body}"
server.sendmail(
data.get('server').get('username'),
data.get('mail').get('sendTo'),
msg
)
print('Hey email has been sent!')
server.quit()
check_price() | [
"christopher.ekfeldt@hotmail.se"
] | christopher.ekfeldt@hotmail.se |
e6334dd94446aa0f73c3d66450b56a70fece539b | a8c718892a7179ca292730e46b6dbc91a6b63ec1 | /shost/wsgi.py | 437a0a924f5ea2645aa23cd1abc8a061d28688e3 | [
"MIT"
] | permissive | lvercellih/shost | a90df181de22bb4847a2f8876eeaf495bf1a0d8f | 52316f24801e2cc3ad8f23115f50bf6148250a42 | refs/heads/master | 2020-05-23T20:39:14.228905 | 2017-03-13T05:42:26 | 2017-03-13T05:42:26 | 84,787,944 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 388 | py | """
WSGI config for shost project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shost.settings")
application = get_wsgi_application()
| [
"lvercellih@gmail.com"
] | lvercellih@gmail.com |
98a5ba2fce68657fdaed702892ee3ed449bf727e | 3e862ce90e7f17c1f1c586aad20bda6c4fc6cbd4 | /home/management/commands/load_initial_data.py | 19443015cfb4110723cc564ebfbfb35c06d46937 | [] | no_license | crowdbotics-users/kailashacrowdboticscom-kai-638 | 621fc891f449a843e0334f4443462f78d1a1d5b6 | e3753824bbd240c64eeadde9671438cc77a8dc0b | refs/heads/master | 2020-04-09T19:42:14.674638 | 2018-12-05T17:00:39 | 2018-12-05T17:00:39 | 160,551,011 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 757 | py |
from django.core.management import BaseCommand
from home.models import CustomText, HomePage
def load_initial_data():
homepage_body = """
<h1 class="display-4 text-center">image-to-text-converter-211</h1>
<p class="lead">
This is the sample application created and deployed from the crowdbotics slack app. You can
view list of packages selected for this application below
</p>"""
customtext_title = 'image-to-text-converter-211'
CustomText.objects.create(title=customtext_title)
HomePage.objects.create(body=homepage_body)
class Command(BaseCommand):
can_import_settings = True
help = 'Load initial data to db'
def handle(self, *args, **options):
load_initial_data()
| [
"sp.gharti@gmail.com"
] | sp.gharti@gmail.com |
758428739d1ef1eff5a3bcbd62a1b50be3fbe2e7 | 88476edf60d8f52c84804e2af748802989aa442a | /face_recognizer.py | 00c84b730e3305b08b3441cf7161a16c05f43619 | [] | no_license | AyuJ01/Face_Detection | 5002f62e7ace7055376c15990a8c54658e9896ca | f416688d43549bc928e8e84f5a5dbe7c2e88fe0b | refs/heads/master | 2020-03-22T10:15:23.743129 | 2018-07-11T07:13:35 | 2018-07-11T07:13:35 | 139,891,499 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,890 | py | #!/usr/bin/python
# Import the required modules
import cv2, os
import numpy as np
from PIL import Image
# For face detection we will use the Haar Cascade provided by OpenCV.
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
# For face recognition we will the the LBPH Face Recognizer
recognizer = cv2.face.LBPHFaceRecognizer_create()
def get_images_and_labels(path):
# Append all the absolute image paths in a list image_paths
# We will not read the image with the .sad extension in the training set
# Rather, we will use them to test our accuracy of the training
image_paths = [os.path.join(path, f) for f in os.listdir(path) if not f.endswith('.sad')]
# images will contains face images
images = []
# labels will contains the label that is assigned to the image
labels = []
for image_path in image_paths:
# Read the image and convert to grayscale
image_pil = Image.open(image_path).convert('L')
# Convert the image format into numpy array
image = np.array(image_pil, 'uint8')
# Get the label of the image
nbr = int(os.path.split(image_path)[1].split(".")[0].replace("subject", ""))
# Detect the face in the image
faces = faceCascade.detectMultiScale(image)
# If face is detected, append the face to images and the label to labels
for (x, y, w, h) in faces:
images.append(image[y: y + h, x: x + w])
labels.append(nbr)
cv2.imshow("Adding faces to traning set...", image[y: y + h, x: x + w])
cv2.waitKey(50)
# return the images list and labels list
return images, labels
# Path to the Yale Dataset
path = 'D:/python/face detection/'
# Call the get_images_and_labels function and get the face images and the
# corresponding labels
images, labels = get_images_and_labels(path)
cv2.destroyAllWindows()
# Perform the tranining
recognizer.train(images, np.array(labels))
# Append the images with the extension .sad into image_paths
image_paths = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.sad')]
for image_path in image_paths:
predict_image_pil = Image.open(image_path).convert('L')
predict_image = np.array(predict_image_pil, 'uint8')
faces = faceCascade.detectMultiScale(predict_image)
for (x, y, w, h) in faces:
nbr_predicted, conf = recognizer.predict(predict_image[y: y + h, x: x + w])
nbr_actual = int(os.path.split(image_path)[1].split(".")[0].replace("subject", ""))
if nbr_actual == nbr_predicted:
print ("{} is Correctly Recognized with confidence {}".format(nbr_actual, conf))
else:
print("{} is Incorrect Recognized as {}".format(nbr_actual, nbr_predicted))
cv2.imshow("Recognizing Face", predict_image[y: y + h, x: x + w])
cv2.waitKey(1000)
| [
"ayushijain625@gmail.com"
] | ayushijain625@gmail.com |
e65f38a6c5f66311a1dbc829dbc02f65e1a11c3f | c45ce94c1e2b75534c3612414018426c923d7c23 | /PKUTreeMaker/test/analysis.py | c872bab7237a66aaff4c2e74b345e2f10b878164 | [] | no_license | zhaoru/zhaoru1 | 40dc25016325daccd027c2f93aae19d81dc40fe1 | 0bf48679f44252773703feab2127881386d42070 | refs/heads/master | 2021-01-10T01:46:04.963993 | 2015-10-19T14:24:12 | 2015-10-19T14:24:12 | 44,540,172 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,987 | py | import FWCore.ParameterSet.Config as cms
process = cms.Process( "TEST" )
process.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(True))
#****************************************************************************************************#
process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff')
process.GlobalTag.globaltag = 'PHYS14_25_V2::All'
process.load("VAJets.PKUCommon.goodMuons_cff")
process.load("VAJets.PKUCommon.goodElectrons_cff")
process.load("VAJets.PKUCommon.goodJets_cff")
process.load("VAJets.PKUCommon.goodPhotons_cff")
process.load("VAJets.PKUCommon.leptonicW_cff")
# Updates
process.goodMuons.src = "slimmedMuons"
process.goodElectrons.src = "slimmedElectrons"
process.goodAK4Jets.src = "slimmedJets"
process.goodPhotons.src = "slimmedPhotons"
process.Wtoenu.MET = "slimmedMETs"
process.Wtomunu.MET = "slimmedMETs"
process.goodOfflinePrimaryVertex = cms.EDFilter("VertexSelector",
src = cms.InputTag("offlineSlimmedPrimaryVertices"),
cut = cms.string("chi2!=0 && ndof >= 4.0 && abs(z) <= 24.0 && abs(position.Rho) <= 2.0"),
filter = cms.bool(True)
)
WBOSONCUT = "pt > 0.0"
process.leptonicVSelector = cms.EDFilter("CandViewSelector",
src = cms.InputTag("leptonicV"),
cut = cms.string( WBOSONCUT ),
filter = cms.bool(True)
)
process.leptonicVFilter = cms.EDFilter("CandViewCountFilter",
src = cms.InputTag("leptonicV"),
minNumber = cms.uint32(1),
filter = cms.bool(True)
)
process.leptonSequence = cms.Sequence(process.muSequence +
process.eleSequence +
process.leptonicVSequence +
process.leptonicVSelector +
process.leptonicVFilter )
#begin------------JEC on the fly--------
#Method 1
process.load("VAJets.PKUJets.redoPatJets_cff")
#process.goodAK4Jets.src = cms.InputTag("selectedPatJetsAK4")
process.jetSequence = cms.Sequence(process.redoPatJets+process.NJetsSequence)
#Mehod 2
jecLevelsAK4chs = [
'PHYS14_25_V2_All_L1FastJet_AK4PFchs.txt',
'PHYS14_25_V2_All_L2Relative_AK4PFchs.txt',
'PHYS14_25_V2_All_L3Absolute_AK4PFchs.txt'
]
#end------------JEC on the fly--------
#updates 2
# process.goodOfflinePrimaryVertex.filter = False
#process.Wtomunu.cut = ''
#process.Wtoenu.cut = ''
#rocess.leptonicVSelector.filter = False
# process.leptonicVSelector.cut = ''
#process.leptonicVFilter.minNumber = 0
print "++++++++++ CUTS ++++++++++\n"
print "Leptonic V cut = "+str(process.leptonicVSelector.cut)
print "\n++++++++++++++++++++++++++"
process.treeDumper = cms.EDAnalyzer("PKUTreeMaker",
originalNEvents = cms.int32(1),
crossSectionPb = cms.double(1),
targetLumiInvPb = cms.double(1.0),
PKUChannel = cms.string("VW_CHANNEL"),
isGen = cms.bool(False),
ak4jetsSrc = cms.string("cleanAK4Jets"),
jets = cms.string("cleanAK4Jets"),
rho = cms.string("fixedGridRhoFastjetAll"),
jecAK4chsPayloadNames = cms.vstring( jecLevelsAK4chs ),
photonSrc = cms.string("goodPhotons"),
leptonicVSrc = cms.string("leptonicV"),
metSrc = cms.string("slimmedMETs"),
reclusteredmets = cms.string("patMETs"),
pfmets = cms.string("pfMet"),
electronIDs = cms.InputTag("heepElectronID-HEEPV50-CSA14-25ns")
)
process.analysis = cms.Path(
process.goodOfflinePrimaryVertex +
process.leptonSequence +
process.photonSequence +
process.jetSequence +
process.treeDumper)
### Source
process.load("VAJets.PKUCommon.data.RSGravitonToWW_kMpl01_M_1000_Tune4C_13TeV_pythia8")
process.source.fileNames = ["/store/user/qili/WWA/Q-Test-v3/150318_075359/0000/JME-Phys14DR-00001_MINIAOD_99.root","/store/user/qili/WWA/Q-Test-v3/150318_075359/0000/JME-Phys14DR-00001_MINIAOD_98.root","/store/user/qili/WWA/Q-Test-v3/150318_075359/0000/JME-Phys14DR-00001_MINIAOD_97.root","/store/user/qili/WWA/Q-Test-v3/150318_075359/0000/JME-Phys14DR-00001_MINIAOD_96.root"]
process.maxEvents.input = -1
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 500
process.MessageLogger.cerr.FwkReport.limit = 99999999999999
process.TFileService = cms.Service("TFileService",
# fileName = cms.string("treePKU_TT_xwh_7.root")
fileName = cms.string("treePKU.root")
# fileName = cms.string("treePKU_MWp_3000_bb_xwh_3_noGen_cuts_1.root")
# fileName = cms.string("treePKU_MWp_4000_bb_xwh.root")
# fileName = cms.string("WJetsToLNu_13TeV-madgraph-pythia8-tauola_all.root")
# fileName = cms.string("JME-Fall13-00001_py8_AN_type2_allcuts_DIYJOB.root")
# fileName = cms.string("treePKU.root")
)
| [
"ruby15965@163.com"
] | ruby15965@163.com |
d56111c362c9cf1702cc112ba471c6544e07742c | ad8caa3519d28beb98a288a50b23c55c9c18f23e | /game_stats.py | fea1badb7b545cc34ae906074590edc735ce0439 | [] | no_license | babylone007/2D-Alien-game | 081bec293185d707a9cb445a283938757166b42e | 61c556f6b440e5fa070ae488f883753a832a6113 | refs/heads/master | 2020-03-25T07:15:51.074679 | 2018-08-31T16:28:42 | 2018-08-31T16:28:42 | 143,550,968 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 546 | py | class GameStats():
"""Track statistics for the game."""
def __init__(self, ai_settings):
"""Initialize statistics."""
self.ai_settings = ai_settings
self.rest_stats()
# Start game in an inactive state.
self.game_active = False
# High score (shouldn't be restarted)
self.high_score = 0
def rest_stats(self):
"""Initialize statistics that can change during the game."""
self.ships_left = self.ai_settings.ship_limit
self.score = 0
self.level = 1
| [
"babyloneroot"
] | babyloneroot |
f0b18d2f6eaec2e83043cf0eb170fb5fb55d6059 | 92b94dd700866a2c089146a4c9b45af7719a284e | /1_diabetes/clustering_kMeans/kMeansInitCentroids.py | 1b3f2a99223b395ce80323e412e69de227fb7b88 | [] | no_license | hzitoun/applying-machine-learning | 1b11932766e9a2f7d885fb991a7f3348e077631b | 36e59f07ecf3ebcb6e1948364af291b180d55438 | refs/heads/master | 2020-03-14T14:08:58.579066 | 2018-05-02T20:14:45 | 2018-05-02T20:14:45 | 131,647,628 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 487 | py | import numpy as np
def kmeans_init_centroids(X, K):
"""This function initializes K centroids that are to be
used in K-Means on the dataset X
centroids = kmeans_init_centroids(X, K) returns K initial centroids to be
used with the K-Means on the dataset X
"""
# Randomly reorder the indices of examples
randidx = np.random.permutation(X.shape[0])
# Take the first K examples as centroids
centroids = X[randidx[0:K], :]
return centroids
| [
"zitoun.hamed@gmail.com"
] | zitoun.hamed@gmail.com |
bc898e40424cb1cafb5b4b23ba444477869ae983 | 5c1531b47fb4dc4d7e5998d44f7200bf1786b12b | /__UNSORTED/130_surrounded_regions/surrounded_regions_TLE.py | 3c923ea0a7709fbedcb124df62b7253ab7f96642 | [] | no_license | Web-Dev-Collaborative/Leetcode-JS-PY-MD | d1f560051aad1896a80eccdd4b4fbb389e7033e3 | 675b94fa5da8d40f0ea79efe6d3ef1393221425f | refs/heads/master | 2023-09-01T22:30:32.313793 | 2021-10-26T02:17:03 | 2021-10-26T02:17:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,019 | py | class Solution:
# @param {character[][]} board
# @return {void} Do not return anything, modify board in-place instead.
def solve(self, board):
if not board:
return
lx = len(board)
ly = len(board[0])
for x in range(lx):
for y in range(ly):
if board[x][y] == "O":
self.area = []
if self.explore(board, x, y):
for xx, yy in self.area:
board[xx][yy] = "X"
def explore(self, board, x, y):
if board[x][y] != "O":
return True
if x == 0 or x == len(board) - 1 or y == 0 or y == len(board[0]) - 1:
return False
if (x, y) in self.area:
return True
self.area.append((x, y))
return (
self.explore(board, x, y + 1)
and self.explore(board, x + 1, y)
and self.explore(board, x - 1, y)
and self.explore(board, x, y - 1)
)
| [
"bryan.guner@gmail.com"
] | bryan.guner@gmail.com |
2ed6e071ac5e6c37ca1bb30e65fe15deb843f041 | 51d2b00b31c26f20279b0b85ca561d55ebd24382 | /Days11/plus.py | 6feb596514e390e53c0da5eef3679e55ad4b5add | [] | no_license | NightDriveraa/Python-100-Days | 8fdb9a2ad9efa63af90c13d518aeaa90ebdf3bfc | 244c6b064be198084cf453f9cddb39db0d0b0662 | refs/heads/master | 2021-05-24T09:25:56.321594 | 2020-06-23T04:11:03 | 2020-06-23T04:11:03 | 253,494,845 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 322 | py | print('Enter two number')
while(True):
try:
num1 = input('first_number: ')
number1 = int(num1)
num2 = input('second_number: ')
number2 = int(num2)
except ValueError:
print('请输入数字')
continue
else:
answer = number1 + number2
print(answer) | [
"ws1224285879@gmail.com"
] | ws1224285879@gmail.com |
5509048765f720d9a22d2656ad5c3afc76f2e75a | f64e75f0e201828a41e29eb5924c6dcf7551c7e4 | /load_data.py | fc9f8cf76af84899ef04b750f5dac348866d6a3b | [] | no_license | rchopinw/models | 30f6dd2ad6af8bec7f2b67e2e8acd95ce9d8a30c | 76f85f4fe251fc5da5b1b8b8323f1bef39183677 | refs/heads/main | 2023-08-29T01:05:05.018228 | 2021-11-02T02:09:34 | 2021-11-02T02:09:34 | 423,677,874 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,201 | py | import numpy as np
import pandas as pd
from collections import Counter, deque
from itertools import chain, product
import heapq
from io import StringIO
# using with statement to open a file
# open function:
# r: open for reading (default)
# w: open for writing, truncating the file first
# a: open for writing, appending to the end of the file if it exists
# b: open in binary mode
# t: text mode
# +: open for updating, both reading and writing
file_path = 'try.txt'
content = []
with open(file_path, ) as fp:
lines = fp.readlines()
for line in lines:
content.append(line)
# using numpy to open a file
np.loadtxt('try.txt',
delimiter=',',
dtype={'names': ('gender', 'age', 'weight'),
'formats': ('S1', 'i4', 'f4')})
# using pandas
data = pd.read_csv('https://www4.stat.ncsu.edu/~boos/var.select/diabetes.tab.txt', sep='\t')
df = pd.DataFrame([[10, 30, 40], [], [15, 8, 12],
[15, 14, 1, 8], [7, 8], [5, 4, 1]],
columns=['Apple', 'Orange', 'Banana', 'Pear'],
index=['Basket1', 'Basket2', 'Basket3', 'Basket4',
'Basket5', 'Basket6'])
print(df.unstack(level=-1)) | [
"noreply@github.com"
] | rchopinw.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.