hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 248 | max_stars_repo_name stringlengths 5 125 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 248 | max_issues_repo_name stringlengths 5 125 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 248 | max_forks_repo_name stringlengths 5 125 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 2.06M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.03M | alphanum_fraction float64 0 1 | count_classes int64 0 1.6M | score_classes float64 0 1 | count_generators int64 0 651k | score_generators float64 0 1 | count_decorators int64 0 990k | score_decorators float64 0 1 | count_async_functions int64 0 235k | score_async_functions float64 0 1 | count_documentation int64 0 1.04M | score_documentation float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2ea7b1e2f8c9260e23fc9fd591de1116fc926068 | 332 | py | Python | gsheetsdb/types.py | tim-werner/gsheets-db-api | 12f2a4fbe1bd5aa36781226759326ce782b08a91 | [
"MIT"
] | 176 | 2018-09-11T12:29:00.000Z | 2022-03-26T19:33:31.000Z | gsheetsdb/types.py | tim-werner/gsheets-db-api | 12f2a4fbe1bd5aa36781226759326ce782b08a91 | [
"MIT"
] | 16 | 2018-09-14T18:11:09.000Z | 2022-03-08T20:17:56.000Z | gsheetsdb/types.py | tim-werner/gsheets-db-api | 12f2a4fbe1bd5aa36781226759326ce782b08a91 | [
"MIT"
] | 14 | 2019-01-10T16:40:25.000Z | 2021-07-27T01:22:58.000Z | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from enum import Enum
class Type(Enum):
STRING = 'string'
NUMBER = 'number'
BOOLEAN = 'boolean'
DATE = 'date'
DATETIME = 'datetime'
TIMEOFDAY = 'timeofday'
| 20.75 | 39 | 0.73494 | 157 | 0.472892 | 0 | 0 | 0 | 0 | 0 | 0 | 52 | 0.156627 |
2ea7de1147d9144369902e2ec0e8782d863ee315 | 1,525 | py | Python | copy_activities.py | atulbhingarde/PythonTwo | 3a43dd0c46959b7aeb6d07c9b26db712e4c14eed | [
"CNRI-Python"
] | null | null | null | copy_activities.py | atulbhingarde/PythonTwo | 3a43dd0c46959b7aeb6d07c9b26db712e4c14eed | [
"CNRI-Python"
] | null | null | null | copy_activities.py | atulbhingarde/PythonTwo | 3a43dd0c46959b7aeb6d07c9b26db712e4c14eed | [
"CNRI-Python"
] | null | null | null | import os
from pathlib import Path
from shutil import copyfile
def stu_activities(rootDir):
# set the rootDir where the search will start
# that is in home dorectory
#rootDir = "Downloads"
# build rootDir from rootDir with the base as home "~"
rootDir = os.path.join(Path.home(),rootDir)
# traverse rootDir and locate the files
####
# when the path has Stu_ in it
####
# store currenet directory and build target directory based on current directory
curDir=os.path.curdir
targetDir=os.path.join(curDir,"target")
print(f'{targetDir}')
if not os.path.exists(targetDir):
os.makedirs(targetDir)
moveOn = True
for dirName, subdirList, fileList in os.walk(rootDir):
if ( "Stu_" in dirName ):
for fname in fileList:
sourceFile = os.path.join(dirName,fname)
targetFile = os.path.join(targetDir,fname)
#print('\t%s' % sourceFile)
#print(f'{targetDir}')
if not os.path.exists(targetFile):
copyfile(sourceFile, targetFile)
else:
print(f'excuse me I can not copy \n source file {sourceFile} as \n target file {targetFile} exists')
moveOn = False
break
else:
if ( not moveOn ):
break
if ( not moveOn ):
break
stu_activities("Downloads")
# test
| 35.465116 | 121 | 0.557377 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 506 | 0.331803 |
2ea7fcfc6b9425bbcc8ff271e419c167ea927769 | 1,122 | py | Python | not_so_weird/oneoff/helper.py | psorus/anogen | 86afc22718aded00bbc05e4582fa0a9b6aa3ab25 | [
"MIT"
] | null | null | null | not_so_weird/oneoff/helper.py | psorus/anogen | 86afc22718aded00bbc05e4582fa0a9b6aa3ab25 | [
"MIT"
] | null | null | null | not_so_weird/oneoff/helper.py | psorus/anogen | 86afc22718aded00bbc05e4582fa0a9b6aa3ab25 | [
"MIT"
] | null | null | null | import matplotlib.pyplot as plt
import numpy as np
def plot(ac):
ac=np.array(ac)
ac=ac.reshape((28,28))
ac=[[int(ac2+0.48) for ac2 in ac1] for ac1 in ac]
plt.imshow(ac)
f=np.load("model.npz",allow_pickle=True)
f2=np.load("model2.npz",allow_pickle=True)
f3=np.load("model3.npz",allow_pickle=True)
f4=np.load("model4.npz",allow_pickle=True)
f5=np.load("model5.npz",allow_pickle=True)
model=f["model"]
print("exp model1")
model2=f2["model"]
print("exp model2")
model3=f3["model"]
print("exp model3")
model4=f4["model"]
print("exp model4")
model5=f5["model"]
print("exp model5")
models=[model,model2,model3,model4,model5]
t=f["t"]
t0=np.mean(t[np.where(t<0.5)])
t1=np.mean(t[np.where(t>0.5)])
def runmodel(inp,model):
x=inp
for l in model:
x=np.dot(x,l)
x=np.maximum(x,0)
x=np.mean(x,axis=-1)
return x
def lossbybool(inp):
"""input either 0 or 1"""
dt=t1-t0
inp/=dt
inp+=t0
ret=(runmodel(inp,models[0])-m7[0])**2
for zw,mea in zip(models[1:],m7):
ret+=(runmodel(inp,models[0])-mea)**2
return ret/len(m7)
m7=[np.mean(runmodel(t,m)) for m in models]
print("done loading")
| 19.016949 | 51 | 0.663993 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 196 | 0.174688 |
2ea85744077900251cd10c8772714c2d58a74dc9 | 2,021 | py | Python | workers/event_checker.py | D00Movenok/ctf-participation-bot | bc922f083c4b16e7f78ce6ba8b2836b82261fd45 | [
"MIT"
] | 8 | 2022-03-05T09:55:31.000Z | 2022-03-10T20:17:54.000Z | workers/event_checker.py | D00Movenok/ctf-participation-bot | bc922f083c4b16e7f78ce6ba8b2836b82261fd45 | [
"MIT"
] | null | null | null | workers/event_checker.py | D00Movenok/ctf-participation-bot | bc922f083c4b16e7f78ce6ba8b2836b82261fd45 | [
"MIT"
] | null | null | null | import logging
import threading
import time
from datetime import datetime, timedelta
from sqlalchemy import column, func, select
from sqlalchemy.orm import SessionTransaction
from actions.discord import Discord
from actions.telegram import Telegram
from common.database import session
from common.models import Event, Voter
from config import config
class EventChecker:
_tg_bot = Telegram()
_discord_bot = Discord()
def start(self):
threading.Thread(target=self.__monitor_cycle).start()
def __monitor_cycle(self):
logging.info('Event checker starting...')
while True:
self.__check()
time.sleep(60)
def __check(self):
logging.debug('Сhecking events for readiness...')
with session.begin() as local_session:
self.__check_ready(local_session)
self.__check_started(local_session)
def __check_ready(self, local_session: SessionTransaction):
subquery = select(Voter.poll_id).\
where(Voter.will_play == True).\
group_by(Voter.poll_id).\
having(func.count(Voter.user_id) >= config['min_will_play'])
query = select(Event).\
where(
Event.start_time <= (datetime.utcnow() + timedelta(days=1)),
column('poll_id').in_(subquery),
Event.done == False,
)
result = local_session.scalars(query)
for event in result:
self._discord_bot.create_event(event)
event.done = True
def __check_started(self, local_session: SessionTransaction):
query = select(Event).\
where(Event.start_time <= datetime.utcnow())
result = local_session.scalars(query)
for event in result:
if event.message_id is not None and event.chat_id is not None and \
event.pinned:
self._tg_bot.unpin_message(event.chat_id, event.message_id)
event.pinned = False
event.done = True
| 33.131148 | 79 | 0.638793 | 1,667 | 0.824431 | 0 | 0 | 0 | 0 | 0 | 0 | 86 | 0.042532 |
2ea94d8d31634c3fa968dde28070a8a994acc38b | 9,148 | py | Python | zigpy_deconz_parser/commands/responses.py | zha-ng/zigpy-deconz-parser | 9182b3578f20a145ccd46b0cfa002613c4cd38db | [
"Apache-2.0"
] | 2 | 2020-02-06T00:00:10.000Z | 2022-02-25T23:47:30.000Z | zigpy_deconz_parser/commands/responses.py | zha-ng/zigpy-deconz-parser | 9182b3578f20a145ccd46b0cfa002613c4cd38db | [
"Apache-2.0"
] | 2 | 2020-04-08T11:57:46.000Z | 2020-05-13T13:32:03.000Z | zigpy_deconz_parser/commands/responses.py | zha-ng/zigpy-deconz-parser | 9182b3578f20a145ccd46b0cfa002613c4cd38db | [
"Apache-2.0"
] | null | null | null | import attr
import binascii
import zigpy.types as t
import zigpy_deconz.types as dt
import zigpy_deconz_parser.types as pt
@attr.s
class Version(pt.Command):
SCHEMA = (t.uint32_t, )
version = attr.ib(factory=SCHEMA[0])
def pretty_print(self, *args):
self.print("Version: 0x{:08x}".format(self.version))
@attr.s
class ReadParameter(pt.Command):
SCHEMA = (t.uint16_t, pt.DeconzParameter, pt.Bytes)
payload_length = attr.ib(factory=SCHEMA[0])
parameter = attr.ib(factory=SCHEMA[1])
value = attr.ib(factory=SCHEMA[2])
def pretty_print(self, *args):
self.print("Payload length: {}".format(self.payload_length))
self.print(str(self.parameter))
self.print("Value: {}".format(binascii.hexlify(self.value)))
@attr.s
class WriteParameter(pt.Command):
SCHEMA = (t.uint16_t, pt.DeconzParameter, )
payload_length = attr.ib(factory=SCHEMA[0])
parameter = attr.ib(factory=SCHEMA[1])
def pretty_print(self, *args):
self.print("Payload length: {}".format(self.payload_length))
self.print(str(self.parameter))
@attr.s
class DeviceState(pt.Command):
SCHEMA = (pt.DeviceState, t.uint8_t, t.Optional(t.uint8_t), )
device_state = attr.ib(factory=SCHEMA[0])
reserved_2 = attr.ib(factory=SCHEMA[1])
reserved_3 = attr.ib(factory=SCHEMA[2])
def pretty_print(self, *args):
self.device_state.pretty_print()
self.print("Reserved: {} Shall be ignored".format(self.reserved_2))
self.print("Reserved: {} Shall be ignored".format(self.reserved_3))
@attr.s
class ChangeNetworkState(pt.Command):
SCHEMA = (pt.NetworkState, )
network_state = attr.ib(factory=SCHEMA[0])
def pretty_print(self, *args):
self.print(str(self.network_state))
@attr.s
class DeviceStateChanged(pt.Command):
SCHEMA = (pt.DeviceState, )
device_state = attr.ib(factory=SCHEMA[0])
def pretty_print(self, *args):
self.device_state.pretty_print()
@attr.s
class ApsDataIndication(pt.Command):
SCHEMA = (t.uint16_t, pt.DeviceState, dt.DeconzAddress, t.uint8_t,
dt.DeconzAddress, t.uint8_t, t.uint16_t, t.uint16_t,
t.LongOctetString, t.uint8_t, t.uint8_t, t.uint8_t, t.uint8_t,
t.uint8_t, t.uint8_t, t.uint8_t, t.int8s, )
payload_length = attr.ib(factory=SCHEMA[0])
device_state = attr.ib(factory=SCHEMA[1])
dst_addr = attr.ib(factory=SCHEMA[2])
dst_ep = attr.ib(factory=SCHEMA[3])
src_addr = attr.ib(factory=SCHEMA[4])
src_ep = attr.ib(factory=SCHEMA[5])
profile = attr.ib(factory=SCHEMA[6])
cluster_id = attr.ib(factory=SCHEMA[7])
asdu = attr.ib(factory=SCHEMA[8])
reserved_1 = attr.ib(factory=SCHEMA[9])
reserved_2 = attr.ib(factory=SCHEMA[10])
lqi = attr.ib(factory=SCHEMA[11])
reserved_3 = attr.ib(factory=SCHEMA[12])
reserved_4 = attr.ib(factory=SCHEMA[13])
reserved_5 = attr.ib(factory=SCHEMA[14])
reserved_6 = attr.ib(factory=SCHEMA[15])
rssi = attr.ib(factory=SCHEMA[16])
def pretty_print(self, *args):
self.print("Payload length: {}".format(self.payload_length))
self.device_state.pretty_print()
if self.profile == 0 and self.dst_ep == 0:
# ZDO
request_id = t.uint8_t.deserialize(self.asdu)[0]
else:
# ZCL
frame_control = self.asdu[0]
if frame_control & 0b0100:
request_id = self.asdu[3]
else:
request_id = self.asdu[1]
headline = "\t\t Request id: [0x{:02x}] ". \
format(request_id).ljust(self._lpad, '<')
print(headline + ' Dst Addr: {}'.format(self.dst_addr))
if self.dst_addr.address_mode in (1, 2, 4):
self.print("Dst address: 0x{:04x}".format(self.dst_addr.address))
self.print("Dst endpoint {}".format(self.dst_ep))
self.print("Src address: {}".format(self.src_addr))
if self.src_addr.address_mode in (1, 2, 4):
self.print("Src address: 0x{:04x}".format(self.src_addr.address))
self.print("Src endpoint: {}".format(self.src_ep))
self.print("Profile id: 0x{:04x}".format(self.profile))
self.print("Cluster id: 0x{:04x}".format(self.cluster_id))
self.print("ASDU: {}".format(binascii.hexlify(self.asdu)))
r = "reserved_1: 0x{:02x} Shall be ignored/Last hop since proto ver 0x0108"
self.print(r.format(self.reserved_1))
r = "reserved_2: 0x{:02x} Shall be ignored/Last hop since proto ver 0x0108"
self.print(r.format(self.reserved_2))
self.print("LQI: {}".format(self.lqi))
self.print("reserved_3: 0x{:02x} Shall be ignored".format(self.reserved_3))
self.print("reserved_4: 0x{:02x} Shall be ignored".format(self.reserved_4))
self.print("reserved_5: 0x{:02x} Shall be ignored".format(self.reserved_5))
self.print("reserved_6: 0x{:02x} Shall be ignored".format(self.reserved_6))
self.print("RSSI: {}".format(self.rssi))
@attr.s
class ApsDataRequest(pt.Command):
_lpad = pt.LPAD
SCHEMA = (
t.uint16_t, # payload length
pt.DeviceState, # Device state
t.uint8_t, # request_id
)
payload_length = attr.ib(factory=SCHEMA[0])
device_state = attr.ib(factory=SCHEMA[1])
request_id = attr.ib(factory=SCHEMA[2])
def pretty_print(self, *args):
self.print("Payload length: {}".format(self.payload_length))
headline = "\t\t Request id: [0x{:02x}] ". \
format(self.request_id).ljust(self._lpad, '<')
print(headline + ' ' + '^^^ Above status ^^^')
self.device_state.pretty_print()
@attr.s
class ApsDataConfirm(pt.Command):
SCHEMA = (
t.uint16_t, # payload length
pt.DeviceState, # Device State
t.uint8_t, # Request ID
dt.DeconzAddressEndpoint, # Destination address
t.uint8_t, # Source endpoint
pt.ConfirmStatus, # Confirm Status
t.uint8_t, # Reserved below
t.uint8_t,
t.uint8_t,
t.uint8_t,
)
payload_length = attr.ib(factory=SCHEMA[0])
device_state = attr.ib(factory=SCHEMA[1])
request_id = attr.ib(factory=SCHEMA[2])
dst_addr = attr.ib(factory=SCHEMA[3])
src_ep = attr.ib(factory=SCHEMA[4])
confirm_status = attr.ib(factory=SCHEMA[5])
reserved_1 = attr.ib(factory=SCHEMA[6])
reserved_2 = attr.ib(factory=SCHEMA[7])
reserved_3 = attr.ib(factory=SCHEMA[8])
reserved_4 = attr.ib(factory=SCHEMA[9])
def pretty_print(self, *args):
self.print("Payload length: {}".format(self.payload_length))
self.device_state.pretty_print()
headline = "\t\t Request id: [0x{:02x}] ". \
format(self.request_id).ljust(self._lpad, '<')
print(headline + ' ' + str(self.dst_addr))
if self.dst_addr.address_mode in (1, 2, 4):
self.print("NWK: 0x{:04x}".format(self.dst_addr.address))
self.print("Src endpoint: {}".format(self.src_ep))
self.print("TX Status: {}".format(str(self.confirm_status)))
r = "reserved_1: 0x{:02x} Shall be ignored"
self.print(r.format(self.reserved_1))
r = "reserved_2: 0x{:02x} Shall be ignored"
self.print(r.format(self.reserved_2))
r = "reserved_3: 0x{:02x} Shall be ignored"
self.print(r.format(self.reserved_3))
r = "reserved_4: 0x{:02x} Shall be ignored"
self.print(r.format(self.reserved_4))
@attr.s
class MacPoll(pt.Command):
SCHEMA = (t.uint16_t, dt.DeconzAddress, t.uint8_t, t.int8s, )
payload_length = attr.ib(factory=SCHEMA[0])
some_address = attr.ib(factory=SCHEMA[1])
lqi = attr.ib(factory=SCHEMA[2])
rssi = attr.ib(factory=SCHEMA[3])
def pretty_print(self, *args):
self.print("Payload length: {}".format(self.payload_length))
self.print("Address: {}".format(self.some_address))
if self.some_address.address_mode in (1, 2, 4):
self.print("Address: 0x{:04x}".format(self.some_address.address))
self.print("LQI: {}".format(self.lqi))
self.print("RSSI: {}".format(self.rssi))
@attr.s
class ZGPDataInd(pt.Command):
SCHEMA = (t.LongOctetString, )
payload = attr.ib(factory=t.LongOctetString)
def pretty_print(self, *args):
self.print('Payload: {}'.format(binascii.hexlify(self.payload)))
@attr.s
class SimpleBeacon(pt.Command):
SCHEMA = (t.uint16_t, t.NWK, t.NWK, t.uint8_t, t.uint8_t, t.uint8_t, )
payload_length = attr.ib(factory=SCHEMA[0])
SrcNWK = attr.ib(factory=SCHEMA[1])
PanId = attr.ib(factory=SCHEMA[2])
channel = attr.ib(factory=SCHEMA[3])
flags = attr.ib(factory=SCHEMA[4])
updateId = attr.ib(factory=SCHEMA[5])
def pretty_print(self, *args):
self.print("Payload length: {}".format(self.payload_length))
self.print("Source NWK: {}".format(self.SrcNWK))
self.print("PAN ID: {}".format(self.PanId))
self.print("Channel: {}".format(self.channel))
self.print("Flags: 0x{:02x}".format(self.flags))
self.print("Update id: 0x{:02x}".format(self.updateId))
| 35.049808 | 83 | 0.636314 | 8,892 | 0.972016 | 0 | 0 | 8,988 | 0.98251 | 0 | 0 | 1,363 | 0.148994 |
2ea9907ebbbf213bac1387472ad831707cedf09e | 2,240 | py | Python | run.py | evgsolntsev/labirinth_screensaver | b41df36d18a9d7d7fcad6c8de89e04c89b0ed704 | [
"MIT"
] | 1 | 2018-09-09T16:50:37.000Z | 2018-09-09T16:50:37.000Z | run.py | evgsolntsev/labirinth_screensaver | b41df36d18a9d7d7fcad6c8de89e04c89b0ed704 | [
"MIT"
] | null | null | null | run.py | evgsolntsev/labirinth_screensaver | b41df36d18a9d7d7fcad6c8de89e04c89b0ed704 | [
"MIT"
] | null | null | null | #!/usr/bin/python3
import math
import os
import random
import sys
import time
from operator import itemgetter
import pygame
from screeninfo import get_monitors
from Xlib import display
from level import Level
DEBUG = "XSCREENSAVER_WINDOW" not in os.environ
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
pygame.init()
def get_geometry(window_id):
drawable = display.Display().create_resource_object(
"window", window_id)
return drawable.get_geometry()
if not DEBUG:
geometry = get_geometry(int(os.getenv("XSCREENSAVER_WINDOW"), 16))
screen_size = (geometry.width, geometry.height)
else:
screen_size = min(
((m.width, m.height) for m in get_monitors()),
key=itemgetter(0))
screen = pygame.display.set_mode(screen_size)
if DEBUG:
geometry = get_geometry(pygame.display.get_wm_info()["window"])
height, width = geometry.width, geometry.height
def get_n():
return random.randint(20, 30)
N = 30 #get_n()
edge = math.ceil(min(height, width) * 9 / 10)
level_coords = (int((height - edge) / 2), int((width - edge) / 2))
score_coords = (int((height - edge) / 2), int((width - edge) / 4))
level = Level(N, edge, edge)
pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', int((width - edge) / 6))
TARGET_SCORE = N ** 2 - 1
WAIT = 5
NEXT = 0
congrats_counter = 0
while True:
screen.fill(BLACK)
if level.score != TARGET_SCORE:
congrats_counter = 0
surface = level.draw()
screen.blit(surface, level_coords)
if level.score == TARGET_SCORE:
if NEXT == 0:
NEXT = time.time() + 5
if NEXT <= time.time():
level = Level(N, edge, edge)
NEXT = 0
continue
text = "Congratulations! Next round in: {0}".format(
int(NEXT - time.time()))
else:
text = "Collected: {0} / {1}.".format(level.score, TARGET_SCORE)
textsurface = myfont.render(text, False, pygame.color.Color("Limegreen"))
screen.blit(textsurface, score_coords)
if DEBUG:
events = pygame.event.get()
for e in events:
if e.type == pygame.KEYDOWN and e.key == pygame.K_RETURN:
sys.exit(0)
pygame.display.update()
time.sleep(0.01)
| 23.829787 | 77 | 0.636607 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 170 | 0.075893 |
2ea9eb3263cf5ab011a34c951f427040e1522b17 | 29,789 | py | Python | q_dic.py | 1ahmedg/quote-script | 852d7bb88d5edc282080a9f86387df67eab270ed | [
"MIT"
] | null | null | null | q_dic.py | 1ahmedg/quote-script | 852d7bb88d5edc282080a9f86387df67eab270ed | [
"MIT"
] | null | null | null | q_dic.py | 1ahmedg/quote-script | 852d7bb88d5edc282080a9f86387df67eab270ed | [
"MIT"
] | null | null | null | # Quotes from: https://www.notion.so/Quotes-by-Naval-Ravikant-3edaf88cfc914b06a98b58b62b6dc222
dic = [\
"Read what you love until you love to read.",\
"True Wisdom Comes From Understanding, Not Memorization.",\
"Meditation is the art of doing nothing. You cannot do meditation. By definition, if you’re doing something, you’re not in meditation. Meditation is a state you’re in when you’re not doing anything – physically, mentally, or consciously. You’re just making no effort. You’re literally being completely still, physically and mentally, inside and out.",\
"You’re actually in deep meditation all the time. It’s just covered up by all the noise and all the thoughts and all the emotional things that are running through you. It’s always there underneath.",\
"Every psychedelic state that people encounter using so-called plant medicines can be arrived at just through pure meditation.",\
"You can meditate 24/7. Meditation is not a sit-down and close your eyes activity. Meditation is basically watching your own thoughts like you would watch anything else in the outside world and saying, ‘Why am I having that thought? Does that serve me anymore? Is this just conditioning from when I was 10 years?’",\
"Most smart people, over time, realize that possessions don’t make them happy.",\
"Anything you wanted in your life – whether it was a car, whether it was a girl, or whether it was money – when you got it, a year later, you were back to zero. Your brain had hedonically adapted to it, and you were looking for the next thing.",\
"If you’re smart, you should be able to figure out how to be happy. Otherwise, you’re not that smart.",\
"Just like fitness can be a choice, health can be a choice, nutrition can be a choice, and working hard and making money can be a choice, happiness can be a choice as well.",\
"Reality is neutral. Reality has no judgments. To a tree, there’s no concept of right or wrong or good or bad. You’re born, you have a whole set of sensory experiences… and then you die. How you choose to interpret that is up to you. And you do have that choice.",\
"In every moment, in everything that happens, you can look on the bright side of something… There are two ways of seeing almost everything.",\
"Desire to me is a contract that you make with yourself to be unhappy until you get what you want.",\
"Pick your one overwhelming desire – it’s okay to suffer over that one. But on all the other desires, let them go so you can be calm and peaceful and relaxed.",\
"Desire is suffering… every desire you have is an axis where you will suffer. So just don’t focus on more than one desire at a time. The universe is rigged in such a way that if you just want one thing, and you focus on that, you’ll get it, but everything else you gotta let go.",\
"In today’s day and age, many people think you get peace by resolving all your external problems, but there are unlimited external problems. The only way to actually get peace on the inside is by giving up the idea of having problems.",\
"To me, peace is happiness at rest, and happiness is peace in motion. You can convert peace to happiness anytime you want.",\
"A clear mind leads to better judgment and better outcomes. A happy, calm, and peaceful person will make better decisions. So if you want to operate at peak performance, you have to learn how to tame your mind.",\
"Look at your own experiences; your bliss from success never lasts, nor does your misery from failure."
"The way to survive in modern society is to be an ascetic; it is to retreat from society."
"You have society in your phone, society in your pocket, society in your ears… It’s socializing you and programming everyone. The only solution is to turn it off.",\
"In a first-world society, success and failure is much more about how you control, manage, and break addictions than it is about going out and doing something.",\
"A lot of what creates unhappiness in modern society is the struggle between what society wants and what the individual wants… Guilt is just society’s voice talking in your head.",\
"You’re better off following your genuine intellectual curiosity than chasing whatever’s hot right now.",\
"Retirement is when you stop sacrificing today for some imaginary tomorrow.",\
"Your real resume is just a cataloging of all your suffering."
"When you do things for their own sake, that’s when you create your best work. That’s when it’s art.",\
"The smaller the company you work for, the happier you’ll be."
"I value freedom above anything else. Freedom to do what I want, freedom from not doing what I don’t want to do, and freedom from my own reactions and emotions…things that may disturb my peace.",\
"I don’t care how rich you are. I don’t care whether you’re a top Wall Street banker. If somebody has to tell you when to be at work, what to wear and how to behave, you’re not a free person. You’re not actually rich.",\
"If you have to wear a tie to work, you’re not really free. If you have to be at your desk at a certain time, you’re not free.",\
"What you do, who you do it with, and how you do it is WAY more important than how hard you work."
"8 hours of input does not equate to the same output for every single person (your output is based on the quality of work you put in)."
"You HAVE to know how to learn anything you want to learn. There should be no book in the library that scares you."
"When you’re reading a book, and you’re not understanding a lot of what it’s saying, and there’s a lot of confusion in your mind about it, that confusion is similar to the burn you get in the gym when you’re working out, except you’re building mental, instead of physical, muscles.",\
"If you’re a perpetual learning machine, you will never be out of options on how to make money.",\
"Today in society, you get rewarded for creative work, for creating something brand new that society didn’t even know that it wanted that it doesn’t yet know how to get, other than through you.",\
"No matter how high your bar is, raise your bar… You can never be working with other people who are great enough. If there’s someone greater out there to work with, you should go work with them.",\
"Worry about working hard only AFTER you’ve picked the right thing to work on and the right people to work with."
"Specific knowledge is the stuff that feels like play to you but looks like work to others. It’s found by pursuing your innate talents, your genuine curiosity, and your passion."
"If you’re not 100% into it, then someone else who is 100% into it will outperform you.",\
"No one can compete with you on being you.",\
"Embrace accountability and take business risks under your own name."
"Busy is the death of productivity.",\
"You have to get bored before you can get creative… You can’t be creative on schedule.",\
"I need 4-5 hours of time by myself every day doing NOTHING. Because if I don’t have that time, I won’t be able to do ANYTHING.",\
"I believe everybody can be wealthy. It’s not a zero-sum game; it’s a positive-sum game.",\
"People who are living far below their means enjoy a freedom that people busy upgrading their lifestyle just can’t fathom."
"All the benefits in life come from compound interest, whether in relationships, life, your career, health, or learning."
"You’re not going to get rich renting out your time. Aim to have a job, career, or profession where your inputs don’t match your output."
"Successful people have a strong action bias."
"Productize yourself."
"Aim to become so good at something, that luck eventually finds you. Over time, it isn’t luck; it’s destiny."
"The 5 most important skills are reading, writing, arithmetic, persuasion, and computer programming."
"The number of iterations drives the learning curve."
"If you’re good with computers, if you’re good at basic math, if you’re good at writing, if you’re good at speaking, and if you like reading, you’re set for life.",\
"Get comfortable with frequent, small failures."
"If you’re willing to bleed a little bit every day, but in exchange, you win big later, you’ll be better off."
"Become the best in the world at what you do. Keep redefining what you do until this is true."
"Reject most advice but remember you have to listen to/read enough of it to know what to reject and what to accept."
"In entrepreneurship, you just have to be right ONCE. The good news is you can take as many shots on goal as you want."
"Know that your physical health, mental health, and your relationships will bring you more peace and happiness than any amount of money ever will."
"It’s good for everybody to realize that at this point in human history, you are basically no longer a citizen of your nation. Wherever you live, whoever you are, you have one foot in the internet. The internet is the real country.",\
"If all of your beliefs line up into one political party, you’re not a clear thinker. If all your beliefs are the same as your neighbors and your friends, you’re not a clear thinker; your beliefs are taken from other people. If you want to be a clear thinker, you cannot pay attention to politics; it will destroy your ability to think.",\
"Fair doesn’t exist in the world. If you’re going to obsess over fair, you’ll never get anywhere in life. You basically just have to do the best you can, with the cards you’re dealt.",\
"Pick three hobbies: One that makes you money, one that makes you fit, and one that keeps you creative.",\
"A lot of wisdom is just realizing the long-term consequences of your actions. The longer-term you’re willing to look, the wiser you’re going to seem to everybody around you.",\
# """llusion #1: The illusion of meaning
# We’re all going to die, and everything will turn to dust – how can anything have meaning?""",\
"IMHO the three big ones in life are wealth, health, and happiness. We pursue them in that order but their importance is in the reverse."
"You can have the mind or you can have the moment.",\
"Ego is false confidence, self-respect is true confidence."
"No one can compete with you on being you. Most of life is a search for who and what needs you the most."
"A rational person can find peace by cultivating indifference to things outside of their control.",\
"Success is the enemy of learning. It can deprive you of the time and the incentive to start over. Beginner’s mind also needs beginner’s time."
"Escape competition through authenticity.",\
"The heart decides, the head rationalizes."
"The fundamental delusion — there is something out there that will make you happy and fulfilled forever.",\
"All the benefits in life come from compound interest — money, relationships, habits — anything of importance.",\
"The compound interest from many quick small iterations is greater than the compound interest from a few slow big iterations. Compound interest operates in most intellectual and social domains."
"Relax. You’ll live longer *and* perform better."
"Twitter is television for intellectuals."
"If you can't decide, the answer is No."
"You don’t get rich by spending your time to save money. You get rich by saving your time to make money."
"Trade money for time, not time for money. You’re going to run out of time first."
"Seek wealth, not money or status. Wealth is having assets that earn while you sleep. Money is how we transfer time and wealth. Status is your place in the social hierarchy."
"Work as hard as you can. Even though who you work with and what you work on are more important than how hard you work.",\
"It is the mark of a charalatan to explain a simple concept in a complex way.",\
"Self-image is the prison. Other people are the guards."
"The greatest superpower is the ability to change yourself."
"We say 'peace of mind', but really what we want is peace from mind."
"A fit body, a calm mind, a house full of love. These things cannot be bought — they must be earned.",\
"Founders run every sprint as if they’re about to lose, but grind out the long race knowing that victory is inevitable."
"It's never been easier to start a company. It's never been harder to build one."
"An early exit for your startup is a mirage in the desert. If you thirst for it, it disappears.",\
"Read what you love until you love to read."
"Wealth creation is an evolutionarily recent positive-sum game. Status is an old zero-sum game. Those attacking wealth creation are often just seeking status."
"The reality is life is a single-player game. You’re born alone. You’re going to die alone. All of your interpretations are alone. All your memories are alone. You’re gone in three generations and nobody cares. Before you showed up, nobody cared. It’s all single-player."
"Become the best in the world at what you do. Keep redefining what you do until this is true."
"In an age of infinite leverage, judgement is the most important skill."
"Leverage is a force multiplier for your judgement."
"Once you’ve truly controlled your own fate, for better or for worse, you’ll never let anyone else tell you what to do."
"You will get rich by giving society what it wants but does not yet know how to get. At scale."
"People who try to look smart by pointing out obvious exceptions actually signal the opposite.",\
"The selfish reason to be ethical is that it attracts the other ethical people in the network.",\
"There are no get rich quick schemes. That’s just someone else getting rich off you.",\
"Specific knowledge is found by pursuing your genuine curiosity and passion rather than whatever is hot right now."
"Better to find a new audience than to write for the audience."
"Learn to sell. Learn to build. If you can do both, you will be unstoppable."
"A taste of freedom can make you unemployable."
"Your closest friends are the ones you can have a relationship with about nothing."
" 'Consensus' is just another way of saying 'average'."
"Morality and ethics automatically emerge when we realize the long term consequences of our actions.",\
"The best jobs are neither decreed nor degreed. They are creative expressions of continuous learners in free markets."
"The skills you really want can’t be taught, but they can be learned."
"Building technology means you don’t have to choose between practicing science, commerce, and art."
"Twitter is a much better resumé than LinkedIn."
"It is the mark of a charlatan to explain a simple concept in a complex way.",\
"Free education is abundant, all over the internet. It’s the desire to learn that’s scarce.",\
"The internet is the best school ever created. The best peers are on the Internet. The best books are on the Internet. The best teachers are on the Internet. The tools for learning are abundant. It’s the desire to learn that’s scarce."
"Teaching is more a way for the teacher to learn than for the student to learn."
"A busy mind accelerates the passage of subjective time."
"All the value in life, including in relationships, comes from compound interest."
"The first rule of handling conflict is don't hang around with people who are constantly engaging in conflict."
"If you want to be successful, surround yourself with people who are more successful than you are, but if you want to be happy, surround yourself with people who are less successful than you are."
"Pick an industry where you can play long term games with long term people."
"The most important trick to be happy is to realize that happiness is a choice that you make and a skill set that you develop. You choose to be happy, and then you work at it. It's just like building muscles."
"Don’t do things that you know are morally wrong. Not because someone is watching, but because you are. Self-esteem is just the reputation that you have with yourself. You’ll always know."
"If you create intersections, you’re going to have collisions."
"The right to debate should not be up for debate."
"Knowledge is discovered by all of us, each adding to the whole. Wisdom is rediscovered by each of us, one at a time."
"My 1 repeated learning in life: 'There Are No Adults' Everyone's making it up as they go along. Figure it out yourself, and do it."
"Making money through an early lucky trade is the worst way to win. The bad habits that it reinforces will lead to a lifetime of losses."
"Forty hour workweeks are a relic of the Industrial Age. Knowledge workers function like athletes — train and sprint, then rest and reassess.",\
"Information is everywhere but its meaning is created by the observer that interprets it. Meaning is relative and there is no objective, over-arching meaning.",\
"If you’re more passionate about founding a business than the business itself, you can fall into a ten year trap. Better to stay emotionally unattached and select the best opportunity that arises. Applies to relationships too.",\
"Smart money is just dumb money that’s been through a crash.",\
"The secret to public speaking is to speak as if you were alone.",\
"Notifications are just alarm clocks that someone else is setting for you."
"The best way, perhaps the only way, to change others is to become an example."
"Sophisticated foods are bittersweet (wine, beer, coffee, chocolate). Addictive relationships are cooperative and competitive. Work becomes flow at the limits of ability. The flavor of life is on the edge.",\
"I think the best way to prepare for the future 20 years is find something you love to do, to have a shot at being one of the best people in the world at it. Build an independent brand around it, with your name."
"Technology is not only the thing that moves the human race forward, but it’s the only thing that ever has. Without technology, we’re just monkeys playing in the dirt.",\
"Success is the enemy of learning. It can deprive you of the time and the incentive to start over. Beginner’s mind also needs beginner’s time.",\
"Don’t debate people in the media when you can debate them in the marketplace.",\
"Twitter is a way to broadcast messages to hundreds of millions of people to find the few dozen that you actually want to talk to."
"A contrarian isn’t one who always objects — that’s a confirmist of a different sort. A contrarian reasons independently, from the ground up, and resists pressure to conform.",\
"The real struggle isn’t proletariat vs bourgeois. It’s between high-status elites and wealthy elites. When their cooperation breaks, revolution.",\
"Branding requires accountability. To build a great personal brand (an eponymous one), you must take on the risk of being publicly wrong.",\
"If you're going to pick 3 cards in the hand you're dealt, take intelligence, drive, and most importantly, emotional self-discipline."
"Before you can lie to another, you must first lie to yourself.",\
"The tools for learning are abundant. It’s the desire to learn that’s scarce.",\
"This is such a short and precious life that it’s really important that you don’t spend it being unhappy.",\
"You make your own luck if you stay at it long enough.",\
"The power to make and break habits and learning how to do that is really important.",\
"Happiness is a choice and a skill and you can dedicate yourself to learning that skill and making that choice.",\
"We’re not really here for that long and we don’t really matter that much. And nothing that we do lasts. So eventually you will fade. Your works will fade. Your children will fade. Your thoughts will fade. This planet will fade. The sun will fade. It will all be gone.",\
"The first rule of handling conflict is don’t hang around people who are constantly engaging in conflict.",\
"The problem happens when we have multiple desires. When we have fuzzy desires. When we want to do ten different things and we’re not clear about which is the one we care about.",\
"People spend too much time doing and not enough time thinking about what they should be doing.",\
"The people who succeed are irrationally passionate about something.",\
"I don’t plan. I’m not a planner. I prefer to live in the moment and be free and to flow and to be happy.",\
"If you see a get rich quick scheme, that’s someone else trying to get rich off of you.",\
"If you try to micromanage yourself all you’re going to do is make yourself miserable.",\
"Social media has degenerated into a deafening cacophony of groups signaling and repeating their shared myths.",\
"If it entertains you now but will bore you someday, it’s a distraction. Keep looking.",\
"If the primary purpose of school was education, the Internet should obsolete it. But school is mainly about credentialing.",\
"Desire is a contract that you make with yourself to be unhappy until you get what you want.",\
"Technology is applied science. Science is the study of nature. Mathematics is the language of nature. Philosophy is the root of mathematics. All tightly interrelated.",\
"Be present above all else.",\
"Who you do business with is just as important as what you choose to do.",\
"If you can’t see yourself working with someone for life, don’t work with them for a day.",\
"Time is the ultimate currency and I should have been more tight fisted with it."
"Impatience is a virtue. Self-discipline is another form of self conflict. Find things that excite you."
"Earn with your mind, not your time.",\
"Humans are basically habit machines… I think learning how to break habits is actually a very important meta skill and can serve you in life almost better than anything else.",\
"The older the problem, the older the solution.",\
"Humans aren’t evolved to worry about everything happening outside of their immediate environment."
"It’s the mark of a charlatan to try and explain simple things in complex ways and it’s the mark of a genius to explain complicated things in simple ways.",\
"The Efficient Markets Hypothesis fails because humans are herd animals, not independent rational actors. Thus the best investors tend to be antisocial and contrarian.",\
"You’re never going to get rich renting out your time.",\
"Lots of literacy in modern society, but not enough numeracy.",\
"Above 'product-market fit', is 'founder-product-market fit'.",\
"Good copy is a poor substitute for good UI. Good marketing is a poor substitute for a good product."
"Software is gnawing on Venture Capital."
"Society has had multiple stores of value, as none is perfectly secure. Gold, oil, dollars, real estate, (some) bonds & equities. Crypto is the first that’s decentralized *and* digital.",\
"Crypto is a bet against the modern macroeconomic dogma, which is passed off as science, but is really a branch of politics — with rulers, winners, and losers.",\
"The overeducated are worse off than the undereducated, having traded common sense for the illusion of knowledge."
"Trade money for time, not time for money. You’re going to run out of time first."
"School, politics, sports, and games train us to compete against others. True rewards - wealth, knowledge, love, fitness, and equanimity - come from ignoring others and improving ourselves."
"If you eat, invest, and think according to what the ‘news’ advocates, you’ll end up nutritionally, financially and morally bankrupt.",\
"If you’re more passionate about founding a business than the business itself, you can fall into a ten year trap. Better to stay emotionally unattached and select the best opportunity that arises."
"Making money through an early lucky trade is the worst way to win. The bad habits that it reinforces will lead to a lifetime of losses."
"Your goal in life is to find out the people who need you the most, to find out the business that needs you the most, to find the project and the art that needs you the most. There is something out there just for you.",\
"Yoga cultivates Peace of Body. Meditation cultivates Peace of Mind."
"Judgement requires experience, but can be built faster by learning foundational skills."
"Tell your friends that you're a happy person. Then you'll be forced to conform to it. You'll have a consistency bias. You have to live up to it. Your friends will expect you to be a happy person."
"Clear thinkers appeal to their own authority.",\
"Think clearly from the ground up. Understand and explain from first principles. Ignore society and politics. Acknowledge what you have. Control your emotions.",\
"Cynicism is easy. Mimicry is easy. Optimistic contrarians are the rarest breed.",\
"If they can train you to do it, then eventually they will train a computer to do it.",\
"A great goal in life would be to not have to be in a given place at a given time... Being accountable for your output rather than your input. I would love to be paid purely for my judgment.",\
"If you’re desensitized to the fact that you’re going to die, consider it a different way. As far as you’re concerned, this world is going to end. Now what?",\
"Following your genuine intellectual curiosity is a better foundation for a career than following whatever is making money right now.",\
"Objectively, the world is improving. To the elites, it’s falling apart as their long-lived institutions are flattened by the Internet.",\
"One of the most damaging and widespread social beliefs is the idea that most adults are incapable of learning new skills.",\
"A personal metric: how much of the day is spent doing things out of obligation rather than out of interest?",\
"Caught in a funk? Use meditation, music, and exercise to reset your mood. Then choose a new path to commit emotional energy for rest of day.",\
"To be honest, speak without identity.",\
"A rational person can find peace by cultivating indifference to things outside of their control.",\
"Politics is sports writ large — pick a side, rally the tribe, exchange stories confirming bias, hurl insults and threats at the other side.",\
"People who live far below their means enjoy a freedom that people busy upgrading their lifestyles can’t fathom.",\
"We feel guilt when we no longer want to associate with old friends and colleagues who haven’t changed. The price, and marker, of growth.",\
"The most important trick to be happy is to realize that happiness is a choice that you make and a skill that you develop. You choose to be happy, and then you work at it. It’s just like building muscles.",\
"Don’t do things that you know are morally wrong. Not because someone is watching, but because you are. Self-esteem is just the reputation that you have with yourself.",\
"Anger is a hot coal that you hold in your hand while waiting to throw it at someone else. (Buddhist saying)",
"All the real benefits of life come from compound interest.",\
"Total honesty at all times. It’s almost always possible to be honest & positive.",\
"Truth is that which has predictive power.",\
"Watch every thought. Always ask, why am I having this thought?",\
"All greatness comes from suffering.",\
"Love is given, not received.",\
"Enlightenment is the space between your thoughts.",\
"Mathematics is the language of nature.",\
"Every moment has to be complete in and of itself.",\
"So I have no time for short-term things: dinners with people I won’t see again, tedious ceremonies to please tedious people, traveling to places that I wouldn’t go to on vacation.",\
"You can change it, you can accept it, or you can leave it. What is not a good option is to sit around wishing you would change it but not changing it, wishing you would leave it but not leaving it, and not accepting it. It’s that struggle, that aversion, that is responsible for most of our misery. The phrase that I use the most to myself in my head is one word: accept.",\
"I don’t have time is just saying it’s not a priority.",\
"Happiness is a state where nothing is missing.",\
"If you don’t love yourself who will?",\
"If being ethical were profitable everybody would do it.",\
"Someone who is using a lot of fancy words and big concepts probably doesn’t know what they’re talking about. The smartest people can explain things to a child; if you can’t do that, you don’t understand the concept.",\
"School, politics, sports, and games train us to compete against others. True rewards — wealth, knowledge, love, fitness, and equanimity — come from ignoring others and improving ourselves.",\
"Signaling virtue is a vice.",\
"Investing favors the dispassionate. Markets efficiently separate emotional investors from their money.",\
"Reality is neutral. Our reactions reflect back and create our world. Judge, and feel separate and lonely. Anger, and lose peace of mind. Cling, and live in anxiety. Fantasize, and miss the present. Desire, and suffer until you have it. Heaven and hell are right here, right now.",\
"Knowledge is a skyscraper. You can take a shortcut with a fragile foundation of memorization, or build slowly upon a steel frame of understanding.",\
"A busy mind accelerates the perceived passage of time. Buy more time by cultivating peace of mind.",\
"Politics is the exercise of power without merit.",\
"Politics and merit are opposite ends of a spectrum. More political organizations are less productive, have less inequality, and top performers opt out. More merit based organizations have higher productivity, more inequality, and higher odds of internal fracture.",\
# "Doctors won’t make you healthy.\nNutritionists won’t make you slim.\nTeachers won’t make you smart.\nGurus won’t make you calm.\nMentors won’t make you rich.\nTrainers won’t make you fit.\nUltimately, you have to take responsibility. Save yourself.",\
"You have to surrender, at least a little bit, to be the best version of yourself possible.",\
] | 61.168378 | 376 | 0.757629 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 29,171 | 0.966055 |
2eaaaf757b2e454dd1e67efcc93720debfd58001 | 9,520 | py | Python | back_end/database/update_db_helpers.py | PrincetonResInDe/course-selection | 7ec447e13ff74bf130c61feb2de65d94fb192efa | [
"MIT"
] | 3 | 2022-01-11T17:39:44.000Z | 2022-02-13T16:31:25.000Z | back_end/database/update_db_helpers.py | PrincetonResInDe/course-selection | 7ec447e13ff74bf130c61feb2de65d94fb192efa | [
"MIT"
] | 5 | 2022-01-12T19:03:05.000Z | 2022-01-31T20:28:00.000Z | back_end/database/update_db_helpers.py | PrincetonResInDe/course-selection | 7ec447e13ff74bf130c61feb2de65d94fb192efa | [
"MIT"
] | null | null | null | import json
from database_utils import DatabaseUtils
from mobileapp import MobileApp
from registrar import RegistrarAPI
import logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s: %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
"""
This file contains helper methods used in update_db_*.py scripts to update term and course data in the database.
"""
# Update course information for one term
# term: term code
# batch: set to True to make batch query to MobileApp
def update_courses_for_one_term(term: str, batch: bool = False) -> None:
db = DatabaseUtils()
if not db.is_valid_term_code(code=term):
logger.error(f"invalid term code {term} provided")
return
# get course data from mobileapp api
try:
logger.info(
f"getting course data for term {term} from mobileapp ({'non-batch' if not batch else 'batch'} query)"
)
if batch:
all_courses = MobileApp().get_all_courses_BATCH(term)
else:
all_courses = MobileApp().get_all_courses_INDIV(term)
except Exception as e:
logger.error(
f"unable to get course data for term {term} from mobileapp with error {e}"
)
return
# NOTE: it may be possible that courses can be deleted, instructors
# removed from a course. only do two clearing operations below
# for current term and if confident that update for all courses
# will not fail.
# db.clear_courses_for_one_term(term)
# db.clear_courses_for_instructor_for_one_term(term)
id_tracker = set() # track seen course ids
up_counter = 0 # count num courses updated
total_counter = 0 # count total courses processed
logger.info(f"started updating courses for term {term}")
for subject in all_courses:
dept = subject["code"]
logger.info(f"processing {'all' if batch else 'some'} courses for {dept}")
for mapp_course in subject["courses"]:
guid = mapp_course["guid"]
course_id = mapp_course["course_id"]
# skip duped courses (only applies for non-batch course queries)
if not batch:
if course_id in id_tracker:
continue
id_tracker.add(course_id)
total_counter += 1
# get course data from registrar's api
try:
logger.info(f"getting data for course {guid} from registrar's api")
# NOTE: this operation slows down the script, but not sure
# if it's worth optimizing because we will switch to OIT's
# student API, where we can pull mobileapp & registrar api's
# data at the same time
reg_course = RegistrarAPI().get_course_data(term, course_id)
except Exception as e:
logger.error(
f"failed to get data for course {guid} from registrar's api with error {e}"
)
continue
# update instructors collection with course guid
if "instructors" in mapp_course:
for instr in mapp_course["instructors"]:
try:
db.add_course_for_instructor(instr, guid)
except Exception as e:
logger.error(
f"failed to add course {guid} for instructor {instr['emplid']} with error {e}"
)
try:
data = {"term": term, "department": dept}
data = parse_course_data(
res=data, mapp_course=mapp_course, reg_course=reg_course
)
# update courses collection with course data
db.update_course_data(guid, data)
up_counter += 1
except Exception as e:
logger.error(
f"failed to parse & update course data for course {guid} with error {e}"
)
logger.info(f"updated data for {up_counter}/{total_counter} courses in term {term}")
# Combines MobileApp and Registrar's API data into one dictionary
# res = resulting dictionary to store data into
# mapp_course = raw data returned by MobileApp
# reg_course = raw data returned by Registrar
def parse_course_data(res: dict, mapp_course: json, reg_course: json) -> dict:
res.update(parse_mobileapp_course_data(mapp_course))
res.update(parse_registrar_course_data(reg_course))
return res
# Parse raw course data returned by MobileApp API
# course = json returned by API
def parse_mobileapp_course_data(course: json) -> dict:
data = {}
data["course_id"] = course.get("course_id", None)
data["guid"] = course.get("guid", None)
data["title"] = course.get("title", None)
data["catalog_number"] = course.get("catalog_number", None)
data["crosslistings"] = course.get("crosslistings", [])
data["classes"] = course.get("classes", [])
if "detail" in course:
details = course["detail"]
data["description"] = details.get("description", None)
data["track"] = details.get("track", None)
return data
# Parse raw course data returned by Registrar's API
# course = json returned by API
# Adapted from Princeton Course's importBasicCourseDetails.js script
# https://github.com/PrincetonUSG/PrincetonCourses/blob/master/importers/importBasicCourseDetails.js#L131
def parse_registrar_course_data(course: json) -> dict:
# Mappings copied from Princeton Course's importBasicCourseDetails.js script
# https://github.com/PrincetonUSG/PrincetonCourses/blob/9fd073f9ad80306afe6646aa7aea9f16586d6a59/importers/importBasicCourseDetails.js#L28-L46
GRADING_LABELS = {
"grading_mid_exam": "Mid term exam",
"grading_paper_mid_exam": "Paper in lieu of mid term",
"grading_final_exam": "Final exam",
"grading_paper_final_exam": "Paper in lieu of final",
"grading_other_exam": "Other exam",
"grading_home_mid_exam": "Take home mid term exam",
"grading_design_projects": "Design project",
"grading_home_final_exam": "Take home final exam",
"grading_prog_assign": "Programming assignments",
"grading_quizzes": "Quizzes",
"grading_lab_reports": "Lab reports",
"grading_papers": "Papers",
"grading_oral_pres": "Oral presentation(s)",
"grading_term_papers": "Term paper(s)",
"grading_precept_part": "Class/precept participation",
"grading_prob_sets": "Problem set(s)",
"grading_other": "Other (see instructor)",
}
# https://github.com/PrincetonUSG/PrincetonCourses/blob/9fd073f9ad80306afe6646aa7aea9f16586d6a59/importers/importBasicCourseDetails.js#L182-L224
GRADING_BASIS_MAPPINGS = {
"FUL": { # Graded A-F, P/D/F, Audit (also the Default)
"pdf": {"required": False, "permitted": True},
"audit": True,
},
"NAU": { # No Audit
"pdf": {"required": False, "permitted": True},
"audit": False,
},
"GRD": { # na, npdf
"pdf": {"required": False, "permitted": False},
"audit": False,
},
"NPD": {"pdf": {"required": False, "permitted": False}, "audit": True}, # npdf
"PDF": { # P/D/F only
"pdf": {"required": True, "permitted": True},
"audit": True,
},
}
data = {}
# parse reading list
data["readings"] = []
reading_list_title_keys = [k for k in course if k.startswith("reading_list_title_")]
for title_k in reading_list_title_keys:
ind = int(title_k.split("reading_list_title_")[1])
author_k = f"reading_list_author_{ind}"
if course[title_k].strip() == "" and course[author_k].strip() == "":
continue
data["readings"].append({"title": course[title_k], "author": course[author_k]})
# parse grading breakdown
data["grading"] = {}
grading_keys = [k for k in course if k.startswith("grading_")]
for k in grading_keys:
if k in GRADING_LABELS and int(course[k]) != 0:
data["grading"][GRADING_LABELS[k]] = int(course[k])
# prase grading basis
if "grading_basis" in course:
grading_basis = course["grading_basis"]
if grading_basis not in GRADING_BASIS_MAPPINGS:
grading_basis = "FUL"
data["pdf"] = GRADING_BASIS_MAPPINGS[grading_basis]["pdf"]
data["audit"] = GRADING_BASIS_MAPPINGS[grading_basis]["audit"]
# parse seating reservations
k = "seat_reservations"
data[k] = []
if "seat_reservation" in course[k]:
data[k] = course[k]["seat_reservation"]
# parse other data
data["other_restrictions"] = course.get("other_restrictions", None)
data["other_information"] = course.get("other_information", None)
data["distribution"] = course.get("distribution_area_short", None)
data["website"] = course.get("web_address", None)
data["assignments"] = course.get("reading_writing_assignment", None)
data["catalog_title"] = None
if "crosslistings" in course:
course_codes = course["crosslistings"].split("/")
for i, code in enumerate(course_codes):
course_codes[i] = code.replace(" ", "")
data["catalog_title"] = " / ".join(course_codes)
return data
if __name__ == "__main__":
update_courses_for_one_term(term="1224", batch=True)
| 39.338843 | 148 | 0.626996 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4,505 | 0.473214 |
2eb1e585fcbec5ec479747784f42d3567bceb246 | 1,294 | py | Python | submission_config.py | ege-k/nlp4nethack | 8b8b45a2f0be09c5233b33a47f421906e9e4b561 | [
"MIT"
] | null | null | null | submission_config.py | ege-k/nlp4nethack | 8b8b45a2f0be09c5233b33a47f421906e9e4b561 | [
"MIT"
] | null | null | null | submission_config.py | ege-k/nlp4nethack | 8b8b45a2f0be09c5233b33a47f421906e9e4b561 | [
"MIT"
] | null | null | null | from agents.custom_agent import CustomAgent
from agents.torchbeast_agent import TorchBeastAgent
from envs.wrappers import addtimelimitwrapper_fn
################################################
# Import your own agent code #
# Set Submision_Agent to your agent #
# Set NUM_PARALLEL_ENVIRONMENTS as needed #
# Set submission_env_make_fn to your wrappers #
# Test with local_evaluation.py #
################################################
class SubmissionConfig:
## Add your own agent class
# AGENT = CustomAgent
AGENT = TorchBeastAgent
## Change the NUM_ENVIRONMENTS as you need
## for example reduce it if your GPU doesn't fit
## Increasing above 32 is not advisable for the Nethack Challenge 2021
NUM_ENVIRONMENTS = 32
## Add a function that creates your nethack env
## Mainly this is to add wrappers
## Add your wrappers to envs/wrappers.py and change the name here
## IMPORTANT: Don't "call" the function, only provide the name
MAKE_ENV_FN = addtimelimitwrapper_fn
class TestEvaluationConfig:
# Change this to locally check a different number of rollouts
# The AIcrowd submission evaluator will not use this
# It is only for your local evaluation
NUM_EPISODES = 512
| 33.179487 | 74 | 0.663833 | 798 | 0.616692 | 0 | 0 | 0 | 0 | 0 | 0 | 902 | 0.697063 |
2eb5fd9ffdbf193e8abf2874479c7b6361639df5 | 1,452 | py | Python | xmem/templates/registry.py | mHaisham/xmem | 87f3ce1b18b629bbc36824cfac5e8f883f9a371a | [
"Apache-2.0"
] | null | null | null | xmem/templates/registry.py | mHaisham/xmem | 87f3ce1b18b629bbc36824cfac5e8f883f9a371a | [
"Apache-2.0"
] | null | null | null | xmem/templates/registry.py | mHaisham/xmem | 87f3ce1b18b629bbc36824cfac5e8f883f9a371a | [
"Apache-2.0"
] | null | null | null | from typing import Union
try:
import winreg
except ImportError:
pass
from ..template import BaseTemplate
from ..exceptions import NotFoundError
class RegistryTemplate(BaseTemplate):
root = winreg.HKEY_CURRENT_USER
def __init__(self, name='xmem'):
"""
:param name: name of your application, will be created in registry
"""
super(RegistryTemplate, self).__init__()
# check if os is supported [Windows]
import platform
if platform.system() != 'Windows':
raise OSError('Unsupported operating system, this template only works on windows')
self.registry_path = f'SOFTWARE\\{name}\\Settings'
def save(self, data: Union[str, bytes], path):
try:
winreg.CreateKey(self.root, self.registry_path)
with winreg.OpenKey(self.root, self.registry_path, 0, winreg.KEY_WRITE) as key:
winreg.SetValueEx(key, str(path), 0, winreg.REG_SZ, data)
return True
except WindowsError:
return False
def load(self, path) -> Union[str, bytes]:
try:
with winreg.OpenKey(self.root, self.registry_path, 0, winreg.KEY_READ) as key:
data, type = winreg.QueryValueEx(key, str(path))
return data
except WindowsError:
path = self.registry_path + f"\\{path}"
raise NotFoundError(f'registry path, {path} does not exist')
| 29.632653 | 94 | 0.626033 | 1,295 | 0.891873 | 0 | 0 | 0 | 0 | 0 | 0 | 287 | 0.197658 |
2eb65dad6e5394cc110d92fd92ceb3c0ad67e792 | 610 | py | Python | RSA/src/primeCheck3.py | BenGH28/Projects | f9e25e39e6afb58203b283c2d0d32d11f1c71124 | [
"MIT"
] | null | null | null | RSA/src/primeCheck3.py | BenGH28/Projects | f9e25e39e6afb58203b283c2d0d32d11f1c71124 | [
"MIT"
] | null | null | null | RSA/src/primeCheck3.py | BenGH28/Projects | f9e25e39e6afb58203b283c2d0d32d11f1c71124 | [
"MIT"
] | null | null | null | from math import sqrt, ceil
def isPrime(x):
"""Primality test.
Param x: int.
Returns True if x is prime, False otherwise.
"""
if x <= 0:
return False
elif x == 2 or x == 3:
return True
else:
for i in range(2, ceil(sqrt(x)) + 1):
if x % i == 0:
return False
return True
if __name__ == "__main__":
strNum = input("Enter number to check if prime (-1 to quit): ")
while strNum != '-1':
num = int(strNum)
print(isPrime(num))
strNum = input("Enter number to check if prime (-1 to quit): ")
| 21.785714 | 71 | 0.52459 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 203 | 0.332787 |
2eb7960ce3140ec7ac3164e707d922756ad1469b | 1,279 | py | Python | text_classifier/utils/analyze_data.py | felixdittrich92/Document_Scanner | 64d482393aa76aa845a30cdf5c86c7705c780450 | [
"MIT"
] | null | null | null | text_classifier/utils/analyze_data.py | felixdittrich92/Document_Scanner | 64d482393aa76aa845a30cdf5c86c7705c780450 | [
"MIT"
] | null | null | null | text_classifier/utils/analyze_data.py | felixdittrich92/Document_Scanner | 64d482393aa76aa845a30cdf5c86c7705c780450 | [
"MIT"
] | 1 | 2021-03-19T14:55:51.000Z | 2021-03-19T14:55:51.000Z | """Script to analyze the Dataframes
"""
import pandas as pd
import matplotlib.pyplot as plt
german_df = pd.read_parquet('/home/felix/Desktop/Document_Scanner/text_classifier/data/german.parquet')
english_df = pd.read_parquet('/home/felix/Desktop/Document_Scanner/text_classifier/data/english.parquet')
german_df.to_csv('/home/felix/Desktop/Document_Scanner/text_classifier/data/german.csv')
english_df.to_csv('/home/felix/Desktop/Document_Scanner/text_classifier/data/english.csv')
german_df = pd.read_csv('/home/felix/Desktop/Document_Scanner/text_classifier/data/german.csv')
english_df = pd.read_csv('/home/felix/Desktop/Document_Scanner/text_classifier/data/english.csv')
print("german data")
print(german_df.info)
print("english data")
print(english_df.info)
fig = german_df[["label", "text"]].groupby("label").count().plot(kind="bar", title="German Data").get_figure()
plt.xlabel("label")
plt.ylabel("text")
plt.tight_layout()
fig.savefig('/home/felix/Desktop/Document_Scanner/text_classifier/data/de_test.pdf')
fig = english_df[["label", "text"]].groupby("label").count().plot(kind="bar", title="English Data").get_figure()
plt.xlabel("label")
plt.ylabel("text")
plt.tight_layout()
fig.savefig('/home/felix/Desktop/Document_Scanner/text_classifier/data/en_test.pdf')
| 42.633333 | 112 | 0.784206 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 742 | 0.580141 |
2ebb42c9684dbe1d66150928c34e62dbd038a141 | 4,742 | py | Python | timeflux_serial/nodes/driver.py | mesca/timeflux_serial | 60d751c7250d06cc82f77906f7ec741bf2ca0a8b | [
"MIT"
] | null | null | null | timeflux_serial/nodes/driver.py | mesca/timeflux_serial | 60d751c7250d06cc82f77906f7ec741bf2ca0a8b | [
"MIT"
] | null | null | null | timeflux_serial/nodes/driver.py | mesca/timeflux_serial | 60d751c7250d06cc82f77906f7ec741bf2ca0a8b | [
"MIT"
] | null | null | null | import serial
import time
import numpy as np
import pandas as pd
from timeflux.core.exceptions import WorkerInterrupt
from timeflux.helpers import clock
from timeflux.core.node import Node
class SerialDevice(Node):
"""A generic serial device driver.
Attributes:
o (Port): Stream from the serial device, provides DataFrame.
Args:
port (string): The serial port.
e.g. ``COM3`` on Windows; ``/dev/tty.tty.SLAB_USBtoUART`` on MacOS;
``/dev/ttyUSB0`` on GNU/Linux.
rate (int): The device rate in Hz.
Possible values: ``1``, ``10``, ``100``, ``1000``. Default: ``1000``.
Example:
.. literalinclude:: /../test/graphs/test.yaml
:language: yaml
Notes:
.. attention::
Make sure to set your graph rate to an high-enough value, otherwise the device
internal buffer may saturate, and data may be lost. A 30Hz graph rate is
recommended for a 1000Hz device rate.
"""
def __init__(self, port, rate=1000):
# Check port
if not port.startswith('/dev/') and not port.startswith('COM'):
raise ValueError(f'Invalid serial port: {port}')
# Check rate
if not isinstance(rate, int):
raise ValueError(f'Invalid rate: {rate}')
self._rate = rate
# Sample size in bytes
self.sample_size = 9
# Connect to device
self.device = self._connect(port)
# try:
# self.device = self.connect(port)
# except Exception as e:
# raise WorkerInterrupt(e)
# Set rate
self._send(f'rate,{rate}')
# Start Acquisition
self._send('start')
# Initialize counters for timestamp indices and continuity checks
self._sample_counter = 65535
self._timestamp = clock.now()
def update(self):
data, indices = self._read()
self.o.set(data, indices, ('SEQ', 'UTIME', 'A0'), {'rate': self._rate})
def _connect(self, port):
device = serial.Serial(port, 115200)
msg = device.readline(); # Wait for 'ready\n'
try:
msg.decode()
except UnicodeDecodeError:
self.logger.error('Unstable state. Please re-plug the device and start again.')
# https://stackoverflow.com/questions/21073086/wait-on-arduino-auto-reset-using-pyserial
# https://forum.arduino.cc/index.php?topic=38981.0
raise WorkerInterrupt()
return device
def _send(self, cmd):
cmd = (cmd + '\n').encode()
self.device.write(cmd)
def _read(self):
"""Read all available data"""
# Check buffer size and limits
buffer_size = self.device.in_waiting
if buffer_size == 1020:
# The OS serial buffer can hold up to 1020 bytes
self.logger.warn('Internal buffer saturated. Increase graph rate or decrease device rate.')
# Compute the maximum number of samples we can get
sample_count = int(buffer_size / self.sample_size)
# Read raw samples from device
now = clock.now()
raw = self.device.read(sample_count * self.sample_size)
# Initialize the output matrix
data = np.full((sample_count, 3), np.nan, np.uint32)
# Parse the raw data
for sample_number in range(sample_count):
# Extract sample
start = sample_number * self.sample_size
stop = start + self.sample_size
sample = raw[start:stop]
# Check (dummy) CRC
crc = sample[8]
if crc != 0:
self.logger.warn('Corrupted sample.')
continue
# Parse sample
data[sample_number, 0] = int.from_bytes(sample[0:2], byteorder='little', signed=False)
data[sample_number, 1] = int.from_bytes(sample[2:6], byteorder='little', signed=False)
data[sample_number, 2] = int.from_bytes(sample[6:8], byteorder='little', signed=False)
# Did we miss any sample?
# Check for discontinuity in the internal sample counter (2 bytes).
sample_counter = data[sample_number, 0]
if sample_counter == self._sample_counter + 1:
pass
elif sample_counter == 0 and self._sample_counter == 65535:
pass
else:
self.logger.warn('Missed sample.')
self._sample_counter = sample_counter
# Compute indices
indices = clock.time_range(self._timestamp, now, len(data))
self._timestamp = now
return data, indices
def terminate(self):
self._send('stop')
self.device.close()
| 30.792208 | 103 | 0.590679 | 4,550 | 0.959511 | 0 | 0 | 0 | 0 | 0 | 0 | 1,891 | 0.398777 |
2ebc95c774511889dc90b69ea08be7978a3d36fc | 2,147 | py | Python | example/infer.py | johnson7788/OpenNRE | dedf56d30b1ba8fa4d7fac2791fb89d6b8af4ba0 | [
"MIT"
] | 5 | 2021-05-20T02:29:34.000Z | 2021-12-21T13:37:39.000Z | example/infer.py | johnson7788/OpenNRE | dedf56d30b1ba8fa4d7fac2791fb89d6b8af4ba0 | [
"MIT"
] | null | null | null | example/infer.py | johnson7788/OpenNRE | dedf56d30b1ba8fa4d7fac2791fb89d6b8af4ba0 | [
"MIT"
] | 4 | 2021-06-09T07:40:52.000Z | 2022-03-11T01:16:08.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021/3/15 10:40 上午
# @File : infer.py
# @Author: johnson
# @Contact : github: johnson7788
# @Desc : 推理模型
import opennre
def infer_wiki80_cnn_softmax():
model = opennre.get_model('wiki80_cnn_softmax')
result = model.infer({
'text': 'He was the son of Máel Dúin mac Máele Fithrich, and grandson of the high king Áed Uaridnach (died 612).',
'h': {'pos': (18, 46)}, 't': {'pos': (78, 91)}})
print(result)
def infer_wiki80_bert_softmax():
"""
有一些错误
:return:
"""
model = opennre.get_model('wiki80_bert_softmax')
result = model.infer({
'text': 'He was the son of Máel Dúin mac Máele Fithrich, and grandson of the high king Áed Uaridnach (died 612).',
'h': {'pos': (18, 46)}, 't': {'pos': (78, 91)}})
print(result)
def infer_wiki80_bertentity_softmax():
model = opennre.get_model('wiki80_bertentity_softmax')
result = model.infer({
'text': 'He was the son of Máel Dúin mac Máele Fithrich, and grandson of the high king Áed Uaridnach (died 612).',
'h': {'pos': (18, 46)}, 't': {'pos': (78, 91)}})
print(result)
def infer_tacred_bertentity_softmax():
model = opennre.get_model('tacred_bertentity_softmax')
result = model.infer({
'text': 'He was the son of Máel Dúin mac Máele Fithrich, and grandson of the high king Áed Uaridnach (died 612).',
'h': {'pos': (18, 46)}, 't': {'pos': (78, 91)}})
print(result)
def infer_tacred_bert_softmax():
model = opennre.get_model('tacred_bert_softmax')
result = model.infer({
'text': 'He was the son of Máel Dúin mac Máele Fithrich, and grandson of the high king Áed Uaridnach (died 612).',
'h': {'pos': (18, 46)}, 't': {'pos': (78, 91)}})
print(result)
if __name__ == '__main__':
infer_wiki80_bert_softmax()
# infer_tacred_bertentity_softmax()
# infer_tacred_bert_softmax() | 38.339286 | 143 | 0.567303 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,058 | 0.483326 |
2ec16ba2dc35438c6e75d67e92a70276533f6439 | 6,938 | py | Python | acme_diags/container/e3sm_diags_container.py | zshaheen/e3sm_diags | 0317d5634b14221052c0984ad0c1a27ca8484e2e | [
"BSD-3-Clause"
] | null | null | null | acme_diags/container/e3sm_diags_container.py | zshaheen/e3sm_diags | 0317d5634b14221052c0984ad0c1a27ca8484e2e | [
"BSD-3-Clause"
] | null | null | null | acme_diags/container/e3sm_diags_container.py | zshaheen/e3sm_diags | 0317d5634b14221052c0984ad0c1a27ca8484e2e | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
"""
A standalone script that prepares a set of input to e3sm_diags
to be ran as a container, and then runs e3sm_diags as a container.
"""
import os
import sys
import importlib
import argparse
import subprocess
# Change these commands if needed.
SHIFTER_COMMAND = 'shifter --volume=$REFERENCE_DATA_PATH:/reference_data_path'
SHIFTER_COMMAND += ' --volume=$TEST_DATA_PATH:/test_data_path --volume=$RESULTS_DIR:/results_dir'
SHIFTER_COMMAND += ' --image=docker:e3sm/e3sm_diags:{}'
# Shifter doesn't use the entrypoint defined in the Dockerfile, so we need to specify what command to use.
SHIFTER_COMMAND += ' -- e3sm_diags'
DOCKER_COMMAND = 'docker run --mount type=bind,source=$REFERENCE_DATA_PATH,target=/reference_data_path'
DOCKER_COMMAND += ' --mount type=bind,source=$TEST_DATA_PATH,target=/test_data_path'
DOCKER_COMMAND += ' --mount type=bind,source=$RESULTS_DIR,target=/results_dir'
# Docker needs the cwd mounted as well, otherwise the input parameter files will not be found.
DOCKER_COMMAND += ' --mount type=bind,source="$(pwd)",target=/e3sm_diags_container_cwd'
DOCKER_COMMAND += ' e3sm/e3sm_diags:{}'
def run_cmd(cmd):
"""
Given a command, run it.
"""
print('Using the command: {}'.format(cmd))
# p = subprocess.Popen(cmd, shell=True)
p = subprocess.Popen(cmd, shell=True).wait()
# This doesn't work: p = subprocess.Popen(cmd.split(), shell=True)
def run_container(args):
e3sm_diags_args = get_user_args_for_e3sm_diags()
# Append the e3sm_diags arguments to the container command.
if args.shifter:
cmd = SHIFTER_COMMAND.format(args.container_version)
cmd += ' ' + ' '.join(e3sm_diags_args)
run_cmd(cmd)
elif args.singularity:
raise RuntimeError('This is not implemented yet! Please understand.')
elif args.docker:
cmd = DOCKER_COMMAND.format(args.container_version)
cmd += ' ' + ' '.join(e3sm_diags_args)
run_cmd(cmd)
else:
msg = 'Invalid container runtime option. Please choose '
msg += 'from "--shifter", "--singularity", or "--docker".'
raise RuntimeError(msg)
def get_parameter_from_file(path, param):
"""
From the Python parameters file located at path,
get the value of the param attribute from it.
"""
if not os.path.exists(path) or not os.path.isfile(path):
raise IOError('The parameter file passed in does not exist.')
path_to_module = os.path.split(path)[0]
module_name = os.path.split(path)[1]
if '.' in module_name:
module_name = module_name.split('.')[0]
sys.path.insert(0, path_to_module)
module = importlib.import_module(module_name)
if not hasattr(module, param):
msg = 'Error: {} was not defined in the command'.format(param)
msg += ' line nor in the Python file.'
raise AttributeError(msg)
else:
return getattr(module, param)
def set_env_vars(args):
"""
From the user's input, set the right environmental
variables to run the container.
"""
# Get the parameters from the command line.
reference_data_path = args.reference_data_path
test_data_path = args.test_data_path
results_dir = args.results_dir
# If they are empty, try to get them from the Python file.
param_file = args.parameters
if not reference_data_path:
reference_data_path = get_parameter_from_file(param_file, 'reference_data_path')
if not test_data_path:
test_data_path = get_parameter_from_file(param_file, 'test_data_path')
if not results_dir:
results_dir = get_parameter_from_file(param_file, 'results_dir')
# Need to make sure paths are valid before actually setting the environmental variables.
if not os.path.exists(reference_data_path):
msg = '{} does not exist.'.format(reference_data_path)
raise IOError(msg)
if not os.path.exists(test_data_path):
msg = '{} does not exist.'.format(test_data_path)
raise IOError(msg)
if not os.path.exists(results_dir):
os.makedirs(results_dir, 0o775)
# Make the paths absolute.
# Docker needs this.
reference_data_path = os.path.abspath(reference_data_path)
test_data_path = os.path.abspath(test_data_path)
results_dir = os.path.abspath(results_dir)
# Then set them as the environmental variables.
os.environ['REFERENCE_DATA_PATH'] = reference_data_path
os.environ['TEST_DATA_PATH'] = test_data_path
os.environ['RESULTS_DIR'] = results_dir
def get_user_args_for_e3sm_diags():
"""
Extract the correct passed in arguments from this script that are needed for e3sm_diags.
"""
params_to_ignore = ['e3sm_diags_container', 'python', 'e3sm_diags_container.py',
'--shifter', '--singularity', '--docker', '--container_version']
e3sm_diags_args = []
i = 0
while i < len(sys.argv):
arg = sys.argv[i]
if arg not in params_to_ignore:
# Commands must be in '' so it works correctly.
e3sm_diags_args.append("'{}'".format(arg))
i += 1
elif arg == '--container_version':
# Skip the 'container_version' arg, as well as the version specified.
# That's why we skip by two.
i += 2
else:
i += 1
return e3sm_diags_args
# For this preprocessing step, these are the only parameters we care about.
parser = argparse.ArgumentParser()
parser.add_argument(
'-p', '--parameters',
dest='parameters',
default='',
help='Path to the user-defined parameter file.',
required=False)
parser.add_argument(
'--reference_data_path',
dest='reference_data_path',
help='Path for the reference data.',
required=False)
parser.add_argument(
'--test_data_path',
dest='test_data_path',
help='Path for the test data.',
required=False)
parser.add_argument(
'--results_dir',
dest='results_dir',
help='Path of where to save the results.',
required=False)
parser.add_argument(
'--container_version',
dest='container_version',
help='Which version of the container to use.',
default='latest',
required=False)
# A separate group of arguments for the container runtimes.
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'--shifter',
dest='shifter',
help='Run the diags in a container using shifter.',
action='store_const',
const=True,
required=False)
group.add_argument(
'--singularity',
dest='singularity',
help='Run the diags in a container using singularity.',
action='store_const',
const=True,
required=False)
group.add_argument(
'--docker',
dest='docker',
help='Run the diags in a container using docker.',
action='store_const',
const=True,
required=False)
args, unknown = parser.parse_known_args()
set_env_vars(args)
run_container(args)
| 34.009804 | 106 | 0.682906 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,160 | 0.455463 |
2ec16cb8adc026001f696ccb5a401d62990e6977 | 15,601 | py | Python | johnhablecode.py | anthonyjclark/MeshroomCLI | 1f1ab5bb758aa7fd804c34e039c1d728723696f2 | [
"CC0-1.0"
] | null | null | null | johnhablecode.py | anthonyjclark/MeshroomCLI | 1f1ab5bb758aa7fd804c34e039c1d728723696f2 | [
"CC0-1.0"
] | null | null | null | johnhablecode.py | anthonyjclark/MeshroomCLI | 1f1ab5bb758aa7fd804c34e039c1d728723696f2 | [
"CC0-1.0"
] | 1 | 2021-03-03T02:34:28.000Z | 2021-03-03T02:34:28.000Z | import sys, os
import shutil
def SilentMkdir(theDir):
try:
os.mkdir(theDir)
except:
pass
return 0
def Run_00_CameraInit(baseDir, binDir, srcImageDir):
# SilentMkdir(baseDir + "/00_CameraInit")
binName = binDir + "\\aliceVision_cameraInit" # .exe"
dstDir = baseDir + "/" # + "/00_CameraInit/"
cmdLine = binName
cmdLine = (
cmdLine
+ ' --defaultFieldOfView 45.0 --verboseLevel info --sensorDatabase "" --allowSingleView 1'
)
cmdLine = cmdLine + ' --imageFolder "' + srcImageDir + '"'
cmdLine = cmdLine + ' --output "' + dstDir + 'cameraInit.sfm"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_01_FeatureExtraction(baseDir, binDir, numImages):
# SilentMkdir(baseDir + "/01_FeatureExtraction")
srcSfm = baseDir + "/00_CameraInit/cameraInit.sfm"
binName = binDir + "\\aliceVision_featureExtraction" # .exe"
dstDir = baseDir + "/01_FeatureExtraction/"
cmdLine = binName
cmdLine = (
cmdLine
+ " --describerTypes sift --forceCpuExtraction True --verboseLevel info --describerPreset normal"
)
cmdLine = cmdLine + " --rangeStart 0 --rangeSize " + str(numImages)
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_02_ImageMatching(baseDir, binDir):
# SilentMkdir(baseDir + "/02_ImageMatching")
srcSfm = baseDir + "/00_CameraInit/cameraInit.sfm"
srcFeatures = baseDir + "/01_FeatureExtraction/"
dstMatches = baseDir + "/02_ImageMatching/imageMatches.txt"
binName = binDir + "\\aliceVision_imageMatching" # .exe"
cmdLine = binName
cmdLine = (
cmdLine + " --minNbImages 200 --tree "
" --maxDescriptors 500 --verboseLevel info --weights "
" --nbMatches 50"
)
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --featuresFolder "' + srcFeatures + '"'
cmdLine = cmdLine + ' --output "' + dstMatches + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_03_FeatureMatching(baseDir, binDir):
# SilentMkdir(baseDir + "/03_FeatureMatching")
srcSfm = baseDir + "/00_CameraInit/cameraInit.sfm"
srcFeatures = baseDir + "/01_FeatureExtraction/"
srcImageMatches = baseDir + "/02_ImageMatching/imageMatches.txt"
dstMatches = baseDir + "/03_FeatureMatching"
binName = binDir + "\\aliceVision_featureMatching" # .exe"
cmdLine = binName
cmdLine = (
cmdLine
+ " --verboseLevel info --describerTypes sift --maxMatches 0 --exportDebugFiles False --savePutativeMatches False --guidedMatching False"
)
cmdLine = (
cmdLine
+ " --geometricEstimator acransac --geometricFilterType fundamental_matrix --maxIteration 2048 --distanceRatio 0.8"
)
cmdLine = cmdLine + " --photometricMatchingMethod ANN_L2"
cmdLine = cmdLine + ' --imagePairsList "' + srcImageMatches + '"'
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --featuresFolders "' + srcFeatures + '"'
cmdLine = cmdLine + ' --output "' + dstMatches + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_04_StructureFromMotion(baseDir, binDir):
# SilentMkdir(baseDir + "/04_StructureFromMotion")
srcSfm = baseDir + "/00_CameraInit/cameraInit.sfm"
srcFeatures = baseDir + "/01_FeatureExtraction/"
srcImageMatches = baseDir + "/02_ImageMatching/imageMatches.txt"
srcMatches = baseDir + "/03_FeatureMatching"
dstDir = baseDir + "/04_StructureFromMotion"
binName = binDir + "\\aliceVision_incrementalSfM" # .exe"
cmdLine = binName
cmdLine = (
cmdLine
+ " --minAngleForLandmark 2.0 --minNumberOfObservationsForTriangulation 2 --maxAngleInitialPair 40.0 --maxNumberOfMatches 0 --localizerEstimator acransac --describerTypes sift --lockScenePreviouslyReconstructed False --localBAGraphDistance 1"
)
# cmdLine = (
# cmdLine + " --initialPairA "
# " --initialPairB "
# " --interFileExtension .ply --useLocalBA True"
# )
cmdLine = cmdLine + " --interFileExtension .ply --useLocalBA True"
cmdLine = (
cmdLine
+ " --minInputTrackLength 2 --useOnlyMatchesFromInputFolder False --verboseLevel info --minAngleForTriangulation 3.0 --maxReprojectionError 4.0 --minAngleInitialPair 5.0"
)
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --featuresFolders "' + srcFeatures + '"'
cmdLine = cmdLine + ' --matchesFolders "' + srcMatches + '"'
cmdLine = cmdLine + ' --outputViewsAndPoses "' + dstDir + '/cameras.sfm"'
cmdLine = cmdLine + ' --extraInfoFolder "' + dstDir + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '/bundle.sfm"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_05_PrepareDenseScene(baseDir, binDir):
# SilentMkdir(baseDir + "/05_PrepareDenseScene")
# srcSfm = baseDir + "/04_StructureFromMotion/cameras.sfm"
srcSfm = baseDir + "/04_StructureFromMotion/bundle.sfm"
dstDir = baseDir + "/05_PrepareDenseScene"
binName = binDir + "\\aliceVision_prepareDenseScene" # .exe"
cmdLine = binName
cmdLine = cmdLine + " --verboseLevel info"
cmdLine = cmdLine + ' --input "' + srcSfm + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_06_CameraConnection(baseDir, binDir):
# SilentMkdir(baseDir + "/06_CameraConnection")
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
# This step kindof breaks the directory structure. Tt creates
# a camsPairsMatrixFromSeeds.bin file in in the same file as mvs.ini
binName = binDir + "\\aliceVision_cameraConnection" # .exe"
cmdLine = binName
cmdLine = cmdLine + " --verboseLevel info"
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_07_DepthMap(baseDir, binDir, numImages, groupSize):
# SilentMkdir(baseDir + "/07_DepthMap")
numGroups = (numImages + (groupSize - 1)) // groupSize
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
binName = binDir + "\\aliceVision_depthMapEstimation" # .exe"
dstDir = baseDir + "/07_DepthMap"
cmdLine = binName
cmdLine = (
cmdLine
+ " --sgmGammaC 5.5 --sgmWSH 4 --refineGammaP 8.0 --refineSigma 15 --refineNSamplesHalf 150 --sgmMaxTCams 10 --refineWSH 3 --downscale 2 --refineMaxTCams 6 --verboseLevel info --refineGammaC 15.5 --sgmGammaP 8.0"
)
cmdLine = (
cmdLine
+ " --refineNiters 100 --refineNDepthsToRefine 31 --refineUseTcOrRcPixSize False"
)
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
for groupIter in range(numGroups):
groupStart = groupSize * groupIter
groupSize = min(groupSize, numImages - groupStart)
print(
"DepthMap Group %d/%d: %d, %d"
% (groupIter, numGroups, groupStart, groupSize)
)
cmd = cmdLine + (" --rangeStart %d --rangeSize %d" % (groupStart, groupSize))
print(cmd)
# os.system(cmd)
# cmd = "aliceVision_depthMapEstimation --sgmGammaC 5.5 --sgmWSH 4 --refineGammaP 8.0 --refineSigma 15 --refineNSamplesHalf 150 --sgmMaxTCams 10 --refineWSH 3 --downscale 2 --refineMaxTCams 6 --verboseLevel info --refineGammaC 15.5 --sgmGammaP 8.0 --ini \"c:/users/geforce/appdata/local/temp/MeshroomCache/PrepareDenseScene/4f0d6d9f9d072ed05337fd7c670811b1daa00e62/mvs.ini\" --refineNiters 100 --refineNDepthsToRefine 31 --refineUseTcOrRcPixSize False --output \"c:/users/geforce/appdata/local/temp/MeshroomCache/DepthMap/18f3bd0a90931bd749b5eda20c8bf9f6dab63af9\" --rangeStart 0 --rangeSize 3"
# cmd = binName + " --sgmGammaC 5.5 --sgmWSH 4 --refineGammaP 8.0 --refineSigma 15 --refineNSamplesHalf 150 --sgmMaxTCams 10 --refineWSH 3 --downscale 2 --refineMaxTCams 6 --verboseLevel info --refineGammaC 15.5 --sgmGammaP 8.0 --ini \"c:/users/geforce/appdata/local/temp/MeshroomCache/PrepareDenseScene/4f0d6d9f9d072ed05337fd7c670811b1daa00e62/mvs.ini\" --refineNiters 100 --refineNDepthsToRefine 31 --refineUseTcOrRcPixSize False --output \"build_files/07_DepthMap/\" --rangeStart 0 --rangeSize 3"
# cmd = binName + " --sgmGammaC 5.5 --sgmWSH 4 --refineGammaP 8.0 --refineSigma 15 --refineNSamplesHalf 150 --sgmMaxTCams 10 --refineWSH 3 --downscale 2 --refineMaxTCams 6 --verboseLevel info --refineGammaC 15.5 --sgmGammaP 8.0 --ini \"" + srcIni + "\" --refineNiters 100 --refineNDepthsToRefine 31 --refineUseTcOrRcPixSize False --output \"build_files/07_DepthMap/\" --rangeStart 0 --rangeSize 3"
# print(cmd)
# os.system(cmd)
return 0
def Run_08_DepthMapFilter(baseDir, binDir):
# SilentMkdir(baseDir + "/08_DepthMapFilter")
binName = binDir + "\\aliceVision_depthMapFiltering" # .exe"
dstDir = baseDir + "/08_DepthMapFilter"
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
srcDepthDir = baseDir + "/07_DepthMap"
cmdLine = binName
cmdLine = cmdLine + " --minNumOfConsistensCamsWithLowSimilarity 4"
cmdLine = (
cmdLine + " --minNumOfConsistensCams 3 --verboseLevel info --pixSizeBall 0"
)
cmdLine = cmdLine + " --pixSizeBallWithLowSimilarity 0 --nNearestCams 10"
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
cmdLine = cmdLine + ' --depthMapFolder "' + srcDepthDir + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_09_Meshing(baseDir, binDir):
# SilentMkdir(baseDir + "/09_Meshing")
binName = binDir + "\\aliceVision_meshing" # .exe"
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
srcDepthFilterDir = baseDir + "/08_DepthMapFilter"
srcDepthMapDir = baseDir + "/07_DepthMap"
dstDir = baseDir + "/09_Meshing"
cmdLine = binName
cmdLine = (
cmdLine
+ " --simGaussianSizeInit 10.0 --maxInputPoints 50000000 --repartition multiResolution"
)
cmdLine = (
cmdLine
+ " --simGaussianSize 10.0 --simFactor 15.0 --voteMarginFactor 4.0 --contributeMarginFactor 2.0 --minStep 2 --pixSizeMarginFinalCoef 4.0 --maxPoints 5000000 --maxPointsPerVoxel 1000000 --angleFactor 15.0 --partitioning singleBlock"
)
cmdLine = (
cmdLine
+ " --minAngleThreshold 1.0 --pixSizeMarginInitCoef 2.0 --refineFuse True --verboseLevel info"
)
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
cmdLine = cmdLine + ' --depthMapFilterFolder "' + srcDepthFilterDir + '"'
cmdLine = cmdLine + ' --depthMapFolder "' + srcDepthMapDir + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '/mesh.obj"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_10_MeshFiltering(baseDir, binDir):
# SilentMkdir(baseDir + "/10_MeshFiltering")
binName = binDir + "\\aliceVision_meshFiltering" # .exe"
srcMesh = baseDir + "/09_Meshing/mesh.obj"
dstMesh = baseDir + "/10_MeshFiltering/mesh.obj"
cmdLine = binName
cmdLine = (
cmdLine
+ " --verboseLevel info --removeLargeTrianglesFactor 60.0 --iterations 5 --keepLargestMeshOnly True"
)
cmdLine = cmdLine + " --lambda 1.0"
cmdLine = cmdLine + ' --input "' + srcMesh + '"'
cmdLine = cmdLine + ' --output "' + dstMesh + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def Run_11_Texturing(baseDir, binDir):
# SilentMkdir(baseDir + "/11_Texturing")
binName = binDir + "\\aliceVision_texturing" # .exe"
srcMesh = baseDir + "/10_MeshFiltering/mesh.obj"
srcRecon = baseDir + "/09_Meshing/denseReconstruction.bin"
srcIni = baseDir + "/05_PrepareDenseScene/mvs.ini"
dstDir = baseDir + "/11_Texturing"
cmdLine = binName
cmdLine = cmdLine + " --textureSide 8192"
cmdLine = cmdLine + " --downscale 2 --verboseLevel info --padding 15"
cmdLine = (
cmdLine
+ " --unwrapMethod Basic --outputTextureFileType png --flipNormals False --fillHoles False"
)
cmdLine = cmdLine + ' --inputDenseReconstruction "' + srcRecon + '"'
cmdLine = cmdLine + ' --inputMesh "' + srcMesh + '"'
cmdLine = cmdLine + ' --ini "' + srcIni + '"'
cmdLine = cmdLine + ' --output "' + dstDir + '"'
print("\n\n", "-" * 20, "\n\n", cmdLine)
# os.system(cmdLine)
return 0
def main():
print("Prepping Scan, v2.")
print(sys.argv)
print(len(sys.argv))
if len(sys.argv) != 6:
print(
"usage: python run_alicevision.py <baseDir> <imgDir> <binDir> <numImages> <runStep>"
)
print("Must pass 6 arguments.")
sys.exit(0)
baseDir = sys.argv[1]
srcImageDir = sys.argv[2]
binDir = sys.argv[3]
numImages = int(sys.argv[4])
runStep = sys.argv[5]
print("Base dir : %s" % baseDir)
print("Image dir : %s" % srcImageDir)
print("Bin dir : %s" % binDir)
print("Num images: %d" % numImages)
print("Step : %s" % runStep)
# SilentMkdir(baseDir)
if runStep == "runall":
Run_00_CameraInit(baseDir, binDir, srcImageDir)
Run_01_FeatureExtraction(baseDir, binDir, numImages)
# Run_02_ImageMatching(baseDir, binDir)
# Run_03_FeatureMatching(baseDir, binDir)
# Run_04_StructureFromMotion(baseDir, binDir)
# Run_05_PrepareDenseScene(baseDir, binDir)
# Run_06_CameraConnection(baseDir, binDir)
# Run_07_DepthMap(baseDir, binDir, numImages, 3)
# Run_08_DepthMapFilter(baseDir, binDir)
# Run_09_Meshing(baseDir, binDir)
# Run_10_MeshFiltering(baseDir, binDir)
# Run_11_Texturing(baseDir, binDir)
elif runStep == "run00":
Run_00_CameraInit(baseDir, binDir, srcImageDir)
elif runStep == "run01":
Run_01_FeatureExtraction(baseDir, binDir, numImages)
elif runStep == "run02":
Run_02_ImageMatching(baseDir, binDir)
elif runStep == "run03":
Run_03_FeatureMatching(baseDir, binDir)
elif runStep == "run04":
Run_04_StructureFromMotion(baseDir, binDir)
elif runStep == "run05":
Run_05_PrepareDenseScene(baseDir, binDir)
elif runStep == "run06":
Run_06_CameraConnection(baseDir, binDir)
elif runStep == "run07":
Run_07_DepthMap(baseDir, binDir, numImages, 3)
elif runStep == "run08":
Run_08_DepthMapFilter(baseDir, binDir)
elif runStep == "run09":
Run_09_Meshing(baseDir, binDir)
elif runStep == "run10":
Run_10_MeshFiltering(baseDir, binDir)
elif runStep == "run11":
Run_11_Texturing(baseDir, binDir)
else:
print("Invalid Step: %s" % runStep)
# print("running")
# Run_00_CameraInit(baseDir,binDir,srcImageDir)
# Run_01_FeatureExtraction(baseDir,binDir,numImages)
# Run_02_ImageMatching(baseDir,binDir)
# Run_03_FeatureMatching(baseDir,binDir)
# Run_04_StructureFromMotion(baseDir,binDir)
# Run_05_PrepareDenseScene(baseDir,binDir)
# Run_06_CameraConnection(baseDir,binDir)
# Run_07_DepthMap(baseDir,binDir,numImages,3)
# Run_08_DepthMapFilter(baseDir,binDir)
# Run_09_Meshing(baseDir,binDir)
# Run_10_MeshFiltering(baseDir,binDir)
# Run_11_Texturing(baseDir,binDir)
return 0
main()
| 35.864368 | 599 | 0.647715 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8,312 | 0.532786 |
2ec17047f3913b1560fc059588ca428be5228730 | 17,448 | py | Python | tests/test_cli.py | lucasace/browser-history | cdd6ce892e1bcc84a2eaf932273ac0454af061a0 | [
"Apache-2.0"
] | null | null | null | tests/test_cli.py | lucasace/browser-history | cdd6ce892e1bcc84a2eaf932273ac0454af061a0 | [
"Apache-2.0"
] | null | null | null | tests/test_cli.py | lucasace/browser-history | cdd6ce892e1bcc84a2eaf932273ac0454af061a0 | [
"Apache-2.0"
] | null | null | null | import csv
import itertools
import json
import tempfile
import re
import pytest
from browser_history.utils import get_browsers
from browser_history.cli import cli, AVAILABLE_BROWSERS
from .utils import ( # noqa: F401
become_linux,
become_mac,
become_windows,
change_homedir,
)
# pylint: disable=redefined-outer-name,unused-argument
CMD_ROOT = "browser-history"
# Options:
VALID_CMD_OPTS = [
(f"--{long_o}", f"-{short_o}")
for long_o, short_o in [
("help", "h"),
("type", "t"),
("browser", "b"),
("format", "f"),
("output", "o"),
]
]
INVALID_CMD_OPTS = [
"--history",
"-a",
"-B",
"-0",
]
# Arguments, where the default arg should be put first for default testing:
VALID_TYPE_ARGS = [
"history",
"bookmarks",
]
INVALID_TYPE_ARGS = ["cookies", "lol", "histories", "bookmark"]
VALID_BROWSER_ARGS = [
"all",
"Chrome",
"Chromium",
"Firefox",
"Safari",
"Edge",
"Opera",
"OperaGX",
"Brave",
]
INVALID_BROWSER_ARGS = ["explorer", "ie", "netscape", "none", "brr"]
VALID_FORMAT_ARGS = [
"infer",
"csv",
"json",
"jsonl",
]
INVALID_FORMAT_ARGS = ["csvv", "txt", "html", "qwerty"]
# (VALID_OUTPUT_ARGS is any existent file, so validity depends on the fs)
GENERAL_INVALID_ARGS = [
"foo",
"0",
]
# Output markers:
HELP_SIGNATURE = (
"usage: browser-history [-h] [-t TYPE] [-b BROWSER] [-f FORMAT] [-o OUTPUT]"
)
HISTORY_HEADER = "Timestamp,URL"
BOOKMARKS_HEADER = "Timestamp,URL,Title,Folder"
CSV_HISTORY_HEADER = HISTORY_HEADER
CSV_BOOKMARKS_HEADER = BOOKMARKS_HEADER
platform_fixture_map = {
"linux": become_linux,
"windows": become_windows,
"mac": become_mac,
}
all_platform_fixtures = tuple("become_" + plat for plat in platform_fixture_map.keys())
@pytest.fixture
def platform(request):
"""Fixture to change platform based on pytest parameter"""
request.getfixturevalue("change_homedir")
return request.getfixturevalue(request.param)
def _get_browser_available_on_system():
"""Find a browser that is supported and installed on the test system."""
for browser in get_browsers():
try: # filter out unsupported browsers
history = browser().fetch_history()
except AssertionError: # anything caught here is unsupported
continue
# Has non-empty history so must be installed as well as supported
if json.loads(history.to_json())["history"]:
# Return string name which corresponds to a VALID_BROWSER_ARGS entry
return browser.name
return # None indicating no browsers available on system
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
def test_no_argument(capsys, platform):
"""Test the root command gives basic output."""
cli([])
captured = capsys.readouterr()
assert CSV_HISTORY_HEADER in captured.out
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
def test_type_argument(capsys, platform):
"""Test arguments for the type option."""
for type_opt in VALID_CMD_OPTS[1]:
for type_arg in VALID_TYPE_ARGS:
cli([type_opt, type_arg])
captured = capsys.readouterr()
if type_arg == "history":
# assuming csv is default
assert captured.out.startswith(CSV_HISTORY_HEADER)
if type_arg == "bookmarks":
assert captured.out.startswith(CSV_BOOKMARKS_HEADER)
@pytest.mark.parametrize("browser_arg", VALID_BROWSER_ARGS)
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
def test_browser_argument(browser_arg, capsys, platform):
"""Test arguments for the browser option."""
for browser_opt in VALID_CMD_OPTS[2]:
try:
cli([browser_opt, browser_arg])
captured = capsys.readouterr()
assert CSV_HISTORY_HEADER in captured.out
except AssertionError as e:
if any(
browser_unavailable_err in e.args[0]
for browser_unavailable_err in (
"browser is not supported",
"browser is not installed",
)
):
# In case the tester does not have access to the browser
# in question, which makes the command fail, but in a way
# that is expected and gives a recognised error message.
pytest.skip(
"Unable to test against {} browser because it is "
"not available locally".format(browser_opt)
)
else: # command fails for another reason i.e. a test failure
pytest.fail(
"{} browser is available but the command to fetch "
"the history from it has failed.".format(browser_opt)
)
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
def test_format_argument(capsys, platform):
"""Tests arguments for the format option."""
# First check format of default:
cli([])
captured = capsys.readouterr()
csv_output = captured.out
# Sniffer determines format, less intensive than reading in csv.reader
# and we don't mind the CSV dialect, so just check call doesn't error
read_csv = csv.Sniffer()
# This gives '_csv.Error: Could not determine delimiter' if not a csv file
read_csv.sniff(csv_output, delimiters=",")
assert read_csv.has_header(
csv_output
), "CSV format missing heading with type followed by column names."
for fmt_opt in VALID_CMD_OPTS[3]:
for fmt_arg in VALID_FORMAT_ARGS:
cli([fmt_opt, fmt_arg])
output = capsys.readouterr().out
if fmt_arg in ("csv", "infer"): # infer gives csv if no file
read_csv.sniff(output, delimiters=",")
assert read_csv.has_header(output)
assert CSV_HISTORY_HEADER in output
elif fmt_arg == "json":
json.loads(output)
elif fmt_arg == "jsonl":
# Newline-delimited json so test each line is valid json
for line in output.splitlines():
json.loads(line)
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
def test_output_argument(capsys, platform):
"""Test arguments for the output option."""
for output_opt in VALID_CMD_OPTS[4]:
with tempfile.TemporaryDirectory() as tmpdir:
cli([output_opt, tmpdir + "out.csv"])
output = capsys.readouterr().out
# Check output was not sent to STDOUT since should go to file
assert HISTORY_HEADER not in output
with open(tmpdir + "out.csv", "rt") as f: # now check the file
assert HISTORY_HEADER in f.read()
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
@pytest.mark.parametrize("browser", AVAILABLE_BROWSERS.split(", "))
def test_argument_combinations(capsys, platform, browser):
"""Test that combinations of optional arguments work properly."""
# Choose some representative combinations. No need to test every one.
indices = (0, 1)
available_browser = _get_browser_available_on_system()
# To test combos of short or long option variants
for index_a, index_b in itertools.product(indices, indices):
if available_browser:
try:
cli(
[
VALID_CMD_OPTS[1][index_a], # type
VALID_TYPE_ARGS[1], # ... is bookmarks,
VALID_CMD_OPTS[2][index_a], # browser
browser, # ... is any usable on system
]
)
except AssertionError as e:
if any(
browser_unavailable_err in e.args[0]
for browser_unavailable_err in (
"browser is not supported",
"browser is not installed",
"Bookmarks are not supported",
)
):
# In case the tester does not have access to the browser
# in question, which makes the command fail, but in a way
# that is expected and gives a recognised error message.
pytest.skip(
"Unable to test against {} browser because it is "
"not available locally".format(browser)
)
else: # command fails for another reason i.e. a test failure
pytest.fail(
"{} browser is available but the command to fetch "
"the history from it has failed.".format(browser)
)
output = capsys.readouterr().out
read_csv = csv.Sniffer()
read_csv.sniff(output, delimiters=",")
assert read_csv.has_header(output)
else: # unlikely but catch just in case can't use any browser
for _ in range(3): # to cover all three assert tests above
pytest.skip("No browsers available to test with")
with tempfile.TemporaryDirectory() as tmpdir:
# This command should write to the given output file:
cli(
[
VALID_CMD_OPTS[3][index_b], # format
VALID_FORMAT_ARGS[2], # ... is json,
VALID_CMD_OPTS[4][index_b], # output
tmpdir + "out.json", # ... is a named file
]
)
with open(tmpdir + "out.json", "rb") as f:
json.loads(f.read().decode("utf-8"))
def test_help_option(capsys):
"""Test the command-line help provided to the user on request."""
for help_opt in VALID_CMD_OPTS[0]:
with pytest.raises(SystemExit) as e:
cli([help_opt])
output = capsys.readouterr()
assert HELP_SIGNATURE in output
assert e.value.code == 0
def test_invalid_options(change_homedir): # noqa: F811
"""Test that invalid options error correctly."""
for bad_opt in INVALID_CMD_OPTS:
with pytest.raises(SystemExit) as e:
cli([bad_opt])
assert e.value.code == 2
def test_invalid_format(change_homedir): # noqa: F811
"""Test that invalid formats error correctly."""
for bad_format in INVALID_FORMAT_ARGS:
with pytest.raises(SystemExit) as e:
cli(["-f", bad_format])
assert e.value.code == 1
def test_invalid_type(change_homedir): # noqa: F811
"""Test that invalid types error correctly."""
for bad_type in INVALID_TYPE_ARGS:
with pytest.raises(SystemExit) as e:
cli(["-t", bad_type])
assert e.value.code == 1
def test_invalid_browser(change_homedir): # noqa: F811
"""Test that invalid browsers error correctly."""
for bad_browser in INVALID_BROWSER_ARGS:
with pytest.raises(SystemExit) as e:
cli(["-b", bad_browser])
assert e.value.code == 1
def test_chrome_linux_profiles(capsys, become_linux, change_homedir): # noqa: F811
"""Test --show-profiles option for Chrome on linux"""
out = None
try:
cli(["--show-profiles", "chrome"])
except SystemExit:
captured = capsys.readouterr()
out = captured.out
assert out.strip() == "Profile"
def test_chromium_linux_profiles(capsys, become_linux, change_homedir): # noqa: F811
"""Test --show-profiles option for Chromium on linux"""
out = None
try:
cli(["--show-profiles", "chromium"])
except SystemExit:
captured = capsys.readouterr()
out = captured.out
# use set to make the comparison order-insensitive
profiles = set(out.strip().split("\n"))
assert profiles == {"Default", "Profile"}
def test_firefox_windows_profiles(capsys, become_windows, change_homedir): # noqa: F811
"""Test --show-profiles option for Firefox on Windows"""
out = None
try:
cli(["--show-profiles", "firefox"])
except SystemExit:
captured = capsys.readouterr()
out = captured.out
assert out.strip() == "Profile 1\nProfile 2"
def test_safari_mac_profiles(caplog, become_mac, change_homedir): # noqa: F811
"""Test --show-profiles option for Safari on Mac
This test checks for failure with a error code 1
"""
try:
cli(["--show-profiles", "safari"])
except SystemExit as e:
assert e.code == 1
assert len(caplog.records) > 0
for record in caplog.records:
assert record.levelname == "CRITICAL"
assert record.message == "Safari browser does not support profiles"
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
def test_show_profiles_all(caplog, platform): # noqa: F811
"""Test --show-profile option with "all" parameter which should fail with
error code 1.
"""
try:
cli(["--show-profiles", "all"])
except SystemExit as e:
assert e.code == 1
assert len(caplog.records) > 0
for record in caplog.records:
assert record.levelname == "CRITICAL"
assert (
record.message == "'all' cannot be used with --show-profiles, "
"please specify a single browser"
)
@pytest.mark.parametrize("browser_arg", INVALID_BROWSER_ARGS)
def test_show_profiles_invalid(caplog, browser_arg): # noqa: F811
"""Test --show-profile option with "all" parameter which should fail with
error code 1.
"""
try:
cli(["--show-profiles", browser_arg])
except SystemExit as e:
assert e.code == 1
assert len(caplog.records) > 0
for record in caplog.records:
assert record.levelname == "ERROR"
assert record.message.endswith(
"browser is unavailable. Check --help for available browsers"
)
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
@pytest.mark.parametrize("profile_arg", ("-p", "--profile"))
def test_profile_all(capsys, platform, profile_arg): # noqa: F811
"""Test -p/--profile option with "all" option on all platforms.
Since the "all" option is not valid, the test checks for exit failure
"""
try:
cli([profile_arg, "all"])
except SystemExit as e:
assert e.code == 2
out, err = capsys.readouterr()
assert out == ""
print(err)
assert err.strip().endswith(
"Cannot use --profile option without specifying"
" a browser or with --browser set to 'all'"
)
@pytest.mark.parametrize("profile_arg", ("-p", "--profile"))
def test_profile_safari(caplog, become_mac, profile_arg): # noqa: F811
"""Test -p/--profile option with Safari on all platforms.
Since Safari does not support profiles, the test checks for failure
"""
try:
cli(["-b", "safari", profile_arg, "some_profile"])
except SystemExit as e:
assert e.code == 1
assert len(caplog.records) > 0
for record in caplog.records:
assert record.levelname == "CRITICAL"
assert record.message == "Safari browser does not support profiles"
@pytest.mark.parametrize("platform", all_platform_fixtures, indirect=True)
@pytest.mark.parametrize("profile_arg", ("-p", "--profile"))
@pytest.mark.parametrize("profile_name", ("nonexistent", "nonexistent2", "some-prof"))
@pytest.mark.parametrize("browser", ("firefox", "chrome"))
def test_profile_nonexistent(
caplog, platform, profile_arg, profile_name, browser
): # noqa: F811
"""Test -p/--profile option with a nonexistent profile"""
try:
cli(["-b", browser, profile_arg, profile_name])
except SystemExit as e:
assert e.code == 1
assert len(caplog.records) > 0
for record in caplog.records:
assert record.levelname == "CRITICAL"
assert re.match(
r"Profile '.*' not found in .* browser or profile does not contain history",
record.message,
)
def test_firefox_windows_profile(capsys, become_windows, change_homedir): # noqa: F811
"""Test -p/--profile for Firefox on Windows"""
cli(["-b", "firefox", "-p", "Profile 2"])
out, err = capsys.readouterr()
assert out.startswith("Timestamp,URL")
assert out.endswith("https://www.reddit.com/\r\n\n")
assert err == ""
def test_firefox_windows_profile_bookmarks(
capsys, become_windows, change_homedir # noqa: F81
):
"""Test -p/--profile for Firefox on Windows, for bookmarks"""
cli(["-b", "firefox", "-p", "Profile 1", "-t", "bookmarks"])
out, err = capsys.readouterr()
assert out.startswith("Timestamp,URL,Title,Folder")
assert err == ""
@pytest.mark.parametrize("type_arg", ("nonexistent", "cookies", "invalid"))
def test_firefox_windows_profile_invalid_type(caplog, type_arg): # noqa: F811
"""Test -p/--profile option with a nonexistent profile"""
try:
cli(["-b", "firefox", "-p", "Profile 1", "-t", type_arg])
except SystemExit as e:
assert e.code == 1
assert len(caplog.records) > 0
for record in caplog.records:
assert record.levelname == "CRITICAL"
assert re.match(
r"Type .* is unavailable. Check --help for available types",
record.message,
)
| 34.965932 | 88 | 0.618524 | 0 | 0 | 0 | 0 | 11,213 | 0.642652 | 0 | 0 | 6,066 | 0.347662 |
2ec1bd4f84d036770ed1c8c4c525dc52df5d3226 | 3,363 | py | Python | lab4FinalFLCD/venv/Lib/site-packages/domain/validate.py | raduceaca1234/Formal-Languages-and-Compiler-Design | 6ced207ad0aa12b9fe5b5090b10bb6dcdd4d2297 | [
"MIT"
] | null | null | null | lab4FinalFLCD/venv/Lib/site-packages/domain/validate.py | raduceaca1234/Formal-Languages-and-Compiler-Design | 6ced207ad0aa12b9fe5b5090b10bb6dcdd4d2297 | [
"MIT"
] | null | null | null | lab4FinalFLCD/venv/Lib/site-packages/domain/validate.py | raduceaca1234/Formal-Languages-and-Compiler-Design | 6ced207ad0aa12b9fe5b5090b10bb6dcdd4d2297 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
def case_insensitive_string(string, available, default=None):
if string is None:
return default
_available = [each.lower() for each in available]
try:
index = _available.index(f"{string}".lower())
except ValueError:
raise ValueError(f"unrecognised input ('{string}') - must be in {available}")
else:
return available[index]
def listing_type(entry):
if entry is None:
return ""
available_listing_types = ["Sale", "Rent", "Share", "Sold", "NewHomes"]
_alt = [each.lower() for each in available_listing_types]
try:
index = _alt.index(str(entry).lower())
except ValueError:
raise ValueError("listing type must be one of: {}".format(
", ".join(available_listing_types)))
else:
return available_listing_types[index]
def property_types(entries):
if entries is None:
return [""]
available_property_types = [
"AcreageSemiRural", "ApartmentUnitFlat", "BlockOfUnits", "CarSpace",
"DevelopmentSite", "Duplex", "Farm", "NewHomeDesigns", "House",
"NewHouseLand", "NewLand", "NewApartments", "Penthouse",
"RetirementVillage", "Rural", "SemiDetached", "SpecialistFarm",
"Studio", "Terrace", "Townhouse", "VacantLand", "Villa"]
_lower_pt = [each.lower() for each in available_property_types]
if isinstance(entries, (str, unicode)):
entries = [entries]
validated_entries = []
for entry in entries:
try:
index = _lower_pt.index(str(entry).lower())
except IndexError:
raise ValueError(
"Unrecognised property type '{}'. Available types: {}".format(
entry, ", ".join(available_property_types)))
validated_entries.append(available_property_types[index])
return validated_entries
def listing_attributes(entries):
if entries is None:
return [""]
available_listing_attributes = ["HasPhotos", "HasPrice", "NotUpForAuction",
"NotUnderContract", "MarkedAsNew"]
_lower_la = [each.lower() for each in available_listing_attributes]
if isinstance(entries, (str, unicode)):
entries = [entries]
validated_entries = []
for entry in entries:
try:
index = _lower_la.index(str(entry).lower())
except IndexError:
raise ValueError(
"Unrecognised listing attribute {}. Available attributes: {}"\
.format(entry, ", ".join(available_listing_attributes)))
validated_entries.append(available_listing_attributes[index])
return validated_entries
def integer_range(entry, default_value=-1):
entry = entry or default_value
# Allow a single value to be given.
if isinstance(entry, int) or entry == default_value:
return (entry, entry)
if len(entry) > 2:
raise ValueError("only lower and upper range can be given, not a list")
return tuple(sorted(entry))
def city(string, **kwargs):
cities = ("Sydney", "Melbourne", "Brisbane", "Adelaide", "Canberra")
return case_insensitive_string(string, cities, **kwargs)
def advertiser_ids(entries):
if entries is None:
return [""]
if isinstance(entries, (str, unicode)):
entries = [entries]
return entries
| 26.273438 | 85 | 0.632174 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 769 | 0.228665 |
2ec35e8658fe8c350dc2c624d8f6bcac6016d398 | 12,527 | py | Python | plugin.video.220ro/default.py | keddyboys/keddy-repo | 5c3420828e19f97222714e0e8518a95d58b3f637 | [
"MIT"
] | 1 | 2019-09-08T05:39:36.000Z | 2019-09-08T05:39:36.000Z | plugin.video.220ro/default.py | keddyboys/keddy-repo | 5c3420828e19f97222714e0e8518a95d58b3f637 | [
"MIT"
] | 1 | 2017-12-03T09:17:31.000Z | 2019-01-13T08:48:40.000Z | plugin.video.220ro/default.py | keddyboys/keddy-repo | 5c3420828e19f97222714e0e8518a95d58b3f637 | [
"MIT"
] | null | null | null | import HTMLParser
import os
import re
import sys
import time
import urllib
import urllib2
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
__addon__ = xbmcaddon.Addon()
__cwd__ = xbmc.translatePath(__addon__.getAddonInfo('path')).decode("utf-8")
__resource__ = xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib')).decode("utf-8")
sys.path.append (__resource__)
settings = xbmcaddon.Addon(id='plugin.video.220ro')
search_thumb = os.path.join(settings.getAddonInfo('path'), 'resources', 'media', 'search.png')
movies_thumb = os.path.join(settings.getAddonInfo('path'), 'resources', 'media', 'movies.png')
next_thumb = os.path.join(settings.getAddonInfo('path'), 'resources', 'media', 'next.png')
def ROOT():
addDir('Video', 'http://www.220.ro/', 23, movies_thumb, 'video')
addDir('Shows', 'http://www.220.ro/', 23, movies_thumb, 'shows')
addDir('Best-Of', 'http://www.220.ro/', 23, movies_thumb, 'best-of')
addDir('Cauta', 'http://www.220.ro/', 3, search_thumb)
def CAUTA_LIST(url):
link = get_search(url)
match = re.compile('<div class=".+?>\n<div.+?\n<a.+?"(.+?)" title="(.+?)" class.+?\n<img src="(.+?)".+?\n.+?\n<span.+?>\n(.+?)\n', re.IGNORECASE | re.MULTILINE).findall(link)
if len(match) > 0:
print match
for legatura, name, img, length in match:
# name = HTMLParser.HTMLParser().unescape( codecs.decode(name, "unicode_escape") ) + " " + length
name = name + " " + length
the_link = legatura
image = img
sxaddLink(name, the_link, image, name, 10)
def CAUTA_VIDEO_LIST(url, meniu):
link = get_search(url)
# f = open( '/storage/.kodi/temp/files.py', 'w' )
# f.write( 'url = ' + repr(url) + '\n' )
# f.close()
if meniu == 'video':
match = re.compile('<div class=".+?>\n<a title="(.+?)" href="(.+?)" class=.+?><img.+?data-src="(.+?)".+?\n<span.+?\n(.+?)\n', re.IGNORECASE | re.MULTILINE).findall(link)
if len(match) > 0:
for name, legatura, img, length in match:
# name = HTMLParser.HTMLParser().unescape( codecs.decode(name, "unicode_escape") ) + " " + length
the_link = legatura
image = img
sxaddLink(name, the_link, image, name, 10, name, length)
elif meniu == 'shows':
match = re.compile('<div class="tabel_show">\n<a href="(.+?)" title="(.+?)".+? data-src="(.+?)".+?\n.+?\n.+?\n.+?\n<p>(.+?)</p>', re.IGNORECASE | re.MULTILINE).findall(link)
if len(match) > 0:
for legatura, name, image, descript in match:
addDir(name, legatura, 5, image, 'sub_shows', descript)
elif meniu == 'sub_shows':
match = re.compile('<div class="left thumbnail">\n<a href="(.+?)" title="(.+?)".+?data-src="(.+?)".+?<span.+?>(.+?)</span>.+?<p>(.+?)</p>', re.IGNORECASE | re.MULTILINE | re.DOTALL).findall(link)
if len(match) > 0:
for legatura, name, image, length, descript in match:
sxaddLink(name, legatura, image, name, 10, descript, length)
elif meniu == 'best-month':
match = re.compile('<div class=".+?>\n<div.+?\n<a.+?"(.+?)" title="(.+?)" class.+?\n<img src="(.+?)".+?\n.+?\n<span.+?>\n(.+?)\n.+?\n.+?\n.+?\n.+?\n<p>(.+?)</p>', re.IGNORECASE | re.MULTILINE).findall(link)
if len(match) > 0:
for legatura, name, image, length, descript in match:
sxaddLink(name, legatura, image, name, 10, descript, length)
match = re.compile('<li><a href=".+?" title="Pagina (\d+)">', re.IGNORECASE).findall(link)
if len(match) > 0:
if meniu == 'best-month':
page_num = re.compile('.+?220.+?\d+/\d+/(\d+)', re.IGNORECASE).findall(url)
nexturl = re.sub('.+?220.+?\d+/\d+/(\d+)', match[0], url)
else:
page_num = re.compile('.+?220.+?(\d+)', re.IGNORECASE).findall(url)
nexturl = re.sub('.+?220.+?(\d+)', match[0], url)
if nexturl.find("/\d+") == -1:
nexturl = url[:-1]
if page_num:
pagen = page_num[0]
pagen = int(pagen)
pagen += 1
nexturl += str(pagen)
else:
nexturl = url + match[0]
addNext('Next', nexturl, 5, next_thumb, meniu)
def CAUTA(url, autoSearch=None):
keyboard = xbmc.Keyboard('')
keyboard.doModal()
if (keyboard.isConfirmed() is False):
return
search_string = keyboard.getText()
if len(search_string) == 0:
return
if autoSearch is None:
autoSearch = ""
CAUTA_LIST(get_search_url(search_string + "" + autoSearch))
def CAUTA_VIDEO(url, gen, autoSearch=None):
CAUTA_VIDEO_LIST(get_search_video_url(gen), meniu=None)
def SXVIDEO_GENERIC_PLAY(sxurl):
progress = xbmcgui.DialogProgress()
progress.create('220.ro', 'Se incarca videoclipul \n')
url = sxurl
src = get_url(urllib.quote(url, safe="%/:=&?~#+!$,;'@()*[]"))
title = ''
# title
match = re.compile('<title>(.+?)<.+?>.?\s*.+?videosrc:\'(.+?)\'.+?og:description.+?"(.+?)".+?<p class="date">(.+?)</p>', re.IGNORECASE | re.DOTALL).findall(src)
title = HTMLParser.HTMLParser().unescape(match[0][0])
title = re.sub('VIDEO.?- ', '', title) + " " + match[0][3]
location = match[0][1]
progress.update(0, "", title, "")
if progress.iscanceled():
return False
listitem = xbmcgui.ListItem(path=location)
listitem.setInfo('video', {'Title': title, 'Plot': match[0][2]})
# xbmcplugin.setResolvedUrl(1, True, listitem)
progress.close()
xbmc.Player().play(item=(location + '|Host=s2.220.t1.ro'), listitem=listitem)
def get_url(url):
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
try:
response = urllib2.urlopen(req)
link = response.read()
response.close()
return link
except:
return False
def get_search_url(keyword, offset=None):
url = 'http://www.220.ro/cauta/' + urllib.quote_plus(keyword) + '/video'
return url
def get_search_video_url(gen, offset=None):
url = 'http://www.220.ro/' + gen + '/'
return url
def get_search(url):
params = {}
req = urllib2.Request(url, urllib.urlencode(params))
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
req.add_header('Content-type', 'application/x-www-form-urlencoded')
try:
response = urllib2.urlopen(req)
link = response.read()
response.close()
return link
except:
return False
def get_params():
param = []
paramstring = sys.argv[2]
if len(paramstring) >= 2:
params = sys.argv[2]
cleanedparams = params.replace('?', '')
if (params[len(params) - 1] == '/'):
params = params[0:len(params) - 2]
pairsofparams = cleanedparams.split('&')
param = {}
for i in range(len(pairsofparams)):
splitparams = {}
splitparams = pairsofparams[i].split('=')
if (len(splitparams)) == 2:
param[splitparams[0]] = splitparams[1]
return param
def sxaddLink(name, url, iconimage, movie_name, mode=4, descript=None, length=None):
ok = True
u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str(mode) + "&name=" + urllib.quote_plus(name)
liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
if descript is not None:
liz.setInfo(type="Video", infoLabels={"Title": movie_name, "Plot": descript})
else:
liz.setInfo(type="Video", infoLabels={"Title": movie_name, "Plot": name})
if length is not None:
liz.setInfo(type="Video", infoLabels={"duration": int(get_sec(length))})
xbmcplugin.setContent(int(sys.argv[1]), 'movies')
ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False)
return ok
def get_sec(time_str):
m, s = time_str.split(':')
return int(m) * 60 + int(s)
def addLink(name, url, iconimage, movie_name):
ok = True
liz = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
liz.setInfo(type="Video", infoLabels={"Title": movie_name})
ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=liz)
return ok
def addNext(name, page, mode, iconimage, meniu=None):
u = sys.argv[0] + "?url=" + urllib.quote_plus(page) + "&mode=" + str(mode) + "&name=" + urllib.quote_plus(name)
if meniu is not None:
u += "&meniu=" + urllib.quote_plus(meniu)
liz = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
liz.setInfo(type="Video", infoLabels={"Title": name})
xbmcplugin.setContent(int(sys.argv[1]), 'movies')
ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
return ok
def addDir(name, url, mode, iconimage, meniu=None, descript=None):
u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str(mode) + "&name=" + urllib.quote_plus(name)
if meniu is not None:
u += "&meniu=" + urllib.quote_plus(meniu)
if descript is not None:
u += "&descriere=" + urllib.quote_plus(descript)
ok = True
liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
liz.setInfo(type="Video", infoLabels={"Genre": name})
if descript is not None:
liz.setInfo(type="Video", infoLabels={"Title": name, "Plot": descript})
else:
liz.setInfo(type="Video", infoLabels={"Title": name})
ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
return ok
def parse_menu(url, meniu):
if url is None:
url = 'http://www.220.ro/'
if meniu == 'video':
url = url + meniu + '/'
link = get_search(url)
match = re.compile('</a>\n<a title="(.+?)" href="(.+?)">', re.IGNORECASE | re.MULTILINE).findall(link)
match.append(['Sexy', 'http://www.220.ro/sexy/'])
elif meniu == 'shows':
match = [('Cele mai tari', 'http://www.220.ro/shows/'), ('Ultimele actualizate', 'http://www.220.ro/shows/ultimele-actualizate/'), ('Alfabetic', 'http://www.220.ro/shows/alfabetic/')]
elif meniu == 'best-of':
now = time.localtime()
# x = (now.tm_year - 2005) * 12 + (now.tm_mon - 5)
x = (now.tm_year - 2005) + 1
# match = [time.localtime(time.mktime((now.tm_year, now.tm_mon - n, 1, 0, 0, 0, 0, 0, 0)))[:1] for n in range(x)]
match = [time.localtime(time.mktime((now.tm_year - n, 12, 0, 0, 0, 0, 0, 0, 0)))[:2] for n in range(x)]
# match=[(), (), (), (), (), (), (), (), (), (), (), ()]
elif meniu == 'best-year':
match = [('Ianuarie', '01'), ('Februarie', '02'), ('Martie', '03'), ('Aprilie', '04'), ('Mai', '05'), ('Iunie', '06'), ('Iulie', '07'), ('August', '08'), ('Septembrie', '09'), ('Octombrie', '10'), ('Noiembrie', '11'), ('Decembrie', '12')]
if len(match) > 0:
print match
if meniu == 'best-of':
for titlu, an in match:
image = "DefaultVideo.png"
year_link = 'http://www.220.ro/best-of/' + str(titlu) + '/'
addDir(str(titlu), year_link, 23, image, 'best-year')
elif meniu == 'best-year':
for titlu, luna in match:
image = "DefaultVideo.png"
month_link = url + str(luna) + '/'
addDir(str(titlu), month_link, 5, image, 'best-month')
else:
for titlu, url in match:
image = "DefaultVideo.png"
addDir(titlu, url, 5, image, meniu, titlu)
xbmcplugin.setContent(int(sys.argv[1]), 'movies')
params = get_params()
url = None
mode = None
meniu = None
try:
url = urllib.unquote_plus(params["url"])
except:
pass
try:
mode = int(params["mode"])
except:
pass
try:
meniu = urllib.unquote_plus(params["meniu"])
except:
pass
# print "Mode: "+str(mode)
# print "URL: "+str(url)
# print "Name: "+str(name)
if mode is None or url is None or len(url) < 1:
ROOT()
elif mode == 1:
CAUTA_VIDEO(url, 'faze-tari')
elif mode == 2:
CAUTA_LIST(url)
elif mode == 3:
CAUTA(url)
elif mode == 5:
CAUTA_VIDEO_LIST(url, meniu)
elif mode == 23:
parse_menu(url, meniu)
elif mode == 10:
SXVIDEO_GENERIC_PLAY(url)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
| 38.192073 | 246 | 0.58346 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,171 | 0.253133 |
2ec52c2ec087b16583f425248434d46a96af0fd5 | 912 | py | Python | tickets/forms.py | connorgannaway/dockmate | 040d44cac896aabc1488f3ed9d59b417e20719d8 | [
"MIT"
] | null | null | null | tickets/forms.py | connorgannaway/dockmate | 040d44cac896aabc1488f3ed9d59b417e20719d8 | [
"MIT"
] | null | null | null | tickets/forms.py | connorgannaway/dockmate | 040d44cac896aabc1488f3ed9d59b417e20719d8 | [
"MIT"
] | null | null | null | from django import forms
from . import widgets
from .models import Ticket, TicketItem
#Creating html forms.
# Each class interacts with a model. Fields for a form are chosen in 'fields'
class TicketForm(forms.ModelForm):
#setting timeDue to have specific formatting
timeDue = forms.DateTimeField(
input_formats=['%Y-%m-%d %H:%M:%S'],
widget=widgets.DateTimeField()
)
class Meta:
model = Ticket
fields = ["customer", "boat", "timeDue"]
class TicketItemForm(forms.ModelForm):
class Meta:
model = TicketItem
fields = ["item", "description"]
class TicketItemCompletionForm(forms.ModelForm):
completed = forms.BooleanField(required=False, label='')
class Meta:
model = TicketItem
fields = ["completed"]
class TicketCompletionForm(forms.ModelForm):
class Meta:
model= Ticket
fields = ['completed'] | 28.5 | 77 | 0.664474 | 719 | 0.788377 | 0 | 0 | 0 | 0 | 0 | 0 | 229 | 0.251096 |
2ec5499aa58ee90bddbc543db1bbb0895014d0e6 | 1,089 | py | Python | conftest.py | Budapest-Quantum-Computing-Group/piquassoboost | fd384be8f59cfd20d62654cf86c89f69d3cf8b8c | [
"Apache-2.0"
] | 4 | 2021-11-29T13:28:19.000Z | 2021-12-21T22:57:09.000Z | conftest.py | Budapest-Quantum-Computing-Group/piquassoboost | fd384be8f59cfd20d62654cf86c89f69d3cf8b8c | [
"Apache-2.0"
] | 11 | 2021-09-24T18:02:26.000Z | 2022-01-27T18:51:47.000Z | conftest.py | Budapest-Quantum-Computing-Group/piquassoboost | fd384be8f59cfd20d62654cf86c89f69d3cf8b8c | [
"Apache-2.0"
] | 1 | 2021-11-13T10:06:52.000Z | 2021-11-13T10:06:52.000Z | #
# Copyright 2021 Budapest Quantum Computing Group
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import pytest
import piquassoboost as pqb
@pytest.fixture(autouse=True)
def _patch(request):
regexp = re.compile(f"{re.escape(str(request.config.rootdir))}\/(.+?)\/(.*)")
result = regexp.search(str(request.fspath))
if result.group(1) == "piquasso-module":
# NOTE: Only override the simulators, when the origin Piquasso Python tests are
# executed. For tests originating in PiquassoBoost, handle everything manually!
pqb.patch()
| 33 | 87 | 0.724518 | 0 | 0 | 0 | 0 | 423 | 0.38843 | 0 | 0 | 825 | 0.757576 |
2ec7a0b5bdeca4cd119b116e98c327c2a10981dd | 799 | py | Python | app/core/tests/test_models.py | Skyprince-gh/recipe-app-api | a4f0ead6ab546b1fea69c32caa3c269898c4086f | [
"MIT"
] | null | null | null | app/core/tests/test_models.py | Skyprince-gh/recipe-app-api | a4f0ead6ab546b1fea69c32caa3c269898c4086f | [
"MIT"
] | null | null | null | app/core/tests/test_models.py | Skyprince-gh/recipe-app-api | a4f0ead6ab546b1fea69c32caa3c269898c4086f | [
"MIT"
] | null | null | null | from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_emamil_successful(self):
"""Test creating a new user with an email is successful"""
email = 'test@test.com'
password = 'testpass123'
user = get_user_model().objects.create_user( #call the create user function from the user model do not import models directly
email=email, #adds email note all these are custom properties since the user model will be changed
password=password #add password note all these are custom properties since the user model will be changed
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password)) #you use the check_password function because passwords are encrypted | 47 | 129 | 0.768461 | 718 | 0.898623 | 0 | 0 | 0 | 0 | 0 | 0 | 406 | 0.508135 |
2ec96efd7987b372b655db0ecf660d386e3c6beb | 6,736 | py | Python | nova/virt/libvirt/storage/dmcrypt.py | bopopescu/nova-token | ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2 | [
"Apache-2.0"
] | null | null | null | nova/virt/libvirt/storage/dmcrypt.py | bopopescu/nova-token | ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2 | [
"Apache-2.0"
] | null | null | null | nova/virt/libvirt/storage/dmcrypt.py | bopopescu/nova-token | ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2 | [
"Apache-2.0"
] | 2 | 2017-07-20T17:31:34.000Z | 2020-07-24T02:42:19.000Z | begin_unit
comment|'# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory'
nl|'\n'
comment|'# All Rights Reserved'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# http://www.apache.org/licenses/LICENSE-2.0'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Unless required by applicable law or agreed to in writing, software'
nl|'\n'
comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT'
nl|'\n'
comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the'
nl|'\n'
comment|'# License for the specific language governing permissions and limitations'
nl|'\n'
comment|'# under the License.'
nl|'\n'
nl|'\n'
name|'import'
name|'os'
newline|'\n'
nl|'\n'
name|'from'
name|'oslo_concurrency'
name|'import'
name|'processutils'
newline|'\n'
name|'from'
name|'oslo_log'
name|'import'
name|'log'
name|'as'
name|'logging'
newline|'\n'
name|'from'
name|'oslo_utils'
name|'import'
name|'excutils'
newline|'\n'
nl|'\n'
name|'from'
name|'nova'
op|'.'
name|'i18n'
name|'import'
name|'_LE'
newline|'\n'
name|'from'
name|'nova'
op|'.'
name|'virt'
op|'.'
name|'libvirt'
name|'import'
name|'utils'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|variable|LOG
name|'LOG'
op|'='
name|'logging'
op|'.'
name|'getLogger'
op|'('
name|'__name__'
op|')'
newline|'\n'
nl|'\n'
DECL|variable|_dmcrypt_suffix
name|'_dmcrypt_suffix'
op|'='
string|"'-dmcrypt'"
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|volume_name
name|'def'
name|'volume_name'
op|'('
name|'base'
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Returns the suffixed dmcrypt volume name.\n\n This is to avoid collisions with similarly named device mapper names for\n LVM volumes\n """'
newline|'\n'
name|'return'
name|'base'
op|'+'
name|'_dmcrypt_suffix'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|is_encrypted
dedent|''
name|'def'
name|'is_encrypted'
op|'('
name|'path'
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Returns true if the path corresponds to an encrypted disk."""'
newline|'\n'
name|'if'
name|'path'
op|'.'
name|'startswith'
op|'('
string|"'/dev/mapper'"
op|')'
op|':'
newline|'\n'
indent|' '
name|'return'
name|'path'
op|'.'
name|'rpartition'
op|'('
string|"'/'"
op|')'
op|'['
number|'2'
op|']'
op|'.'
name|'endswith'
op|'('
name|'_dmcrypt_suffix'
op|')'
newline|'\n'
dedent|''
name|'else'
op|':'
newline|'\n'
indent|' '
name|'return'
name|'False'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|create_volume
dedent|''
dedent|''
name|'def'
name|'create_volume'
op|'('
name|'target'
op|','
name|'device'
op|','
name|'cipher'
op|','
name|'key_size'
op|','
name|'key'
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Sets up a dmcrypt mapping\n\n :param target: device mapper logical device name\n :param device: underlying block device\n :param cipher: encryption cipher string digestible by cryptsetup\n :param key_size: encryption key size\n :param key: encryption key as an array of unsigned bytes\n """'
newline|'\n'
name|'cmd'
op|'='
op|'('
string|"'cryptsetup'"
op|','
nl|'\n'
string|"'create'"
op|','
nl|'\n'
name|'target'
op|','
nl|'\n'
name|'device'
op|','
nl|'\n'
string|"'--cipher='"
op|'+'
name|'cipher'
op|','
nl|'\n'
string|"'--key-size='"
op|'+'
name|'str'
op|'('
name|'key_size'
op|')'
op|','
nl|'\n'
string|"'--key-file=-'"
op|')'
newline|'\n'
name|'key'
op|'='
string|"''"
op|'.'
name|'join'
op|'('
name|'map'
op|'('
name|'lambda'
name|'byte'
op|':'
string|'"%02x"'
op|'%'
name|'byte'
op|','
name|'key'
op|')'
op|')'
newline|'\n'
name|'try'
op|':'
newline|'\n'
indent|' '
name|'utils'
op|'.'
name|'execute'
op|'('
op|'*'
name|'cmd'
op|','
name|'process_input'
op|'='
name|'key'
op|','
name|'run_as_root'
op|'='
name|'True'
op|')'
newline|'\n'
dedent|''
name|'except'
name|'processutils'
op|'.'
name|'ProcessExecutionError'
name|'as'
name|'e'
op|':'
newline|'\n'
indent|' '
name|'with'
name|'excutils'
op|'.'
name|'save_and_reraise_exception'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
name|'LOG'
op|'.'
name|'error'
op|'('
name|'_LE'
op|'('
string|'"Could not start encryption for disk %(device)s: "'
nl|'\n'
string|'"%(exception)s"'
op|')'
op|','
op|'{'
string|"'device'"
op|':'
name|'device'
op|','
string|"'exception'"
op|':'
name|'e'
op|'}'
op|')'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|delete_volume
dedent|''
dedent|''
dedent|''
name|'def'
name|'delete_volume'
op|'('
name|'target'
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Deletes a dmcrypt mapping\n\n :param target: name of the mapped logical device\n """'
newline|'\n'
name|'try'
op|':'
newline|'\n'
indent|' '
name|'utils'
op|'.'
name|'execute'
op|'('
string|"'cryptsetup'"
op|','
string|"'remove'"
op|','
name|'target'
op|','
name|'run_as_root'
op|'='
name|'True'
op|')'
newline|'\n'
dedent|''
name|'except'
name|'processutils'
op|'.'
name|'ProcessExecutionError'
name|'as'
name|'e'
op|':'
newline|'\n'
comment|'# cryptsetup returns 4 when attempting to destroy a non-existent'
nl|'\n'
comment|'# dm-crypt device. It indicates that the device is invalid, which'
nl|'\n'
comment|'# means that the device is invalid (i.e., it has already been'
nl|'\n'
comment|'# destroyed).'
nl|'\n'
indent|' '
name|'if'
name|'e'
op|'.'
name|'exit_code'
op|'=='
number|'4'
op|':'
newline|'\n'
indent|' '
name|'LOG'
op|'.'
name|'debug'
op|'('
string|'"Ignoring exit code 4, volume already destroyed"'
op|')'
newline|'\n'
dedent|''
name|'else'
op|':'
newline|'\n'
indent|' '
name|'with'
name|'excutils'
op|'.'
name|'save_and_reraise_exception'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
name|'LOG'
op|'.'
name|'error'
op|'('
name|'_LE'
op|'('
string|'"Could not disconnect encrypted volume "'
nl|'\n'
string|'"%(volume)s. If dm-crypt device is still active "'
nl|'\n'
string|'"it will have to be destroyed manually for "'
nl|'\n'
string|'"cleanup to succeed."'
op|')'
op|','
op|'{'
string|"'volume'"
op|':'
name|'target'
op|'}'
op|')'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|list_volumes
dedent|''
dedent|''
dedent|''
dedent|''
name|'def'
name|'list_volumes'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
string|'"""Function enumerates encrypted volumes."""'
newline|'\n'
name|'return'
op|'['
name|'dmdev'
name|'for'
name|'dmdev'
name|'in'
name|'os'
op|'.'
name|'listdir'
op|'('
string|"'/dev/mapper'"
op|')'
nl|'\n'
name|'if'
name|'dmdev'
op|'.'
name|'endswith'
op|'('
string|"'-dmcrypt'"
op|')'
op|']'
newline|'\n'
dedent|''
endmarker|''
end_unit
| 15.556582 | 320 | 0.621734 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4,040 | 0.599762 |
2ec9b42a47d378d39bc5d7f55d620025c929fc40 | 1,308 | py | Python | quiz/routing.py | zeroish/grey-matters | a8e235b7412f754be70d057ac46d5ca38171cb54 | [
"MIT"
] | 1 | 2018-05-18T12:02:05.000Z | 2018-05-18T12:02:05.000Z | quiz/routing.py | zeroish/grey-matters | a8e235b7412f754be70d057ac46d5ca38171cb54 | [
"MIT"
] | 44 | 2017-11-10T11:27:45.000Z | 2022-03-08T21:09:03.000Z | quiz/routing.py | zeroish/grey-matters | a8e235b7412f754be70d057ac46d5ca38171cb54 | [
"MIT"
] | 2 | 2019-03-07T21:52:58.000Z | 2020-06-25T10:08:24.000Z | from channels.staticfiles import StaticFilesConsumer
from .consumers import ws_connect, ws_receive, ws_disconnect, new_contestant, start_quiz, submit_answer
from channels import include, route
# Although we could, there is no path matching on these routes; instead we rely
# on the matching from the top-level routing.
websocket_routing = [
# This makes Django serve static files from settings.STATIC_URL, similar
# to django.views.static.serve. This isn't ideal (not exactly production
# quality) but it works for a minimal example.
route('http.request', StaticFilesConsumer()),
# Called when WebSockets connect
route("websocket.connect", ws_connect),
# Called when WebSockets get sent a data frame
route("websocket.receive", ws_receive),
# Called when WebSockets disconnect
route("websocket.disconnect", ws_disconnect),
]
channel_routing = [
# Handling different quiz commands (websocket.receive is decoded and put
# onto this channel) - routed on the "command" attribute of the decoded
# message.
route("quiz.receive", new_contestant, command="^new_contestant$"),
route("quiz.receive", start_quiz, command="^start_quiz$"),
route("quiz.receive", submit_answer, command="^submit_answer$"),
include("quiz.routing.websocket_routing"),
] | 42.193548 | 103 | 0.745413 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 777 | 0.594037 |
2ecc0dd0c98eb13c08cf7df88acd4f1371b2c87f | 2,039 | py | Python | webapp/flow_summary_graphs.py | bfitzy2142/NET4901-SP | 908c13332a5356bd6a59879b8d78af76432b807c | [
"MIT"
] | 3 | 2019-08-04T03:09:02.000Z | 2020-06-08T15:48:36.000Z | webapp/flow_summary_graphs.py | bfitzy2142/NET4901-SP | 908c13332a5356bd6a59879b8d78af76432b807c | [
"MIT"
] | 3 | 2019-09-06T08:30:21.000Z | 2020-06-30T03:24:56.000Z | webapp/flow_summary_graphs.py | bfitzy2142/NET4901-SP-SDLENS | 908c13332a5356bd6a59879b8d78af76432b807c | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
"""
MySql Parser for graphical presentation
"""
import mysql.connector
import datetime
from mysql.connector import Error
from datetime import datetime, timedelta
import json
def pull_flow_graphs(node, time, sql_creds, db):
""" Pulls the RX and TX information from the database
to display for the graphs page.
Arguments:
node [str] -- The node that holds the interface which
is to presented.
time [str] -- Time ranging from 30 minutes to 10 Years
Returns:
dict -- containing arrays of the counter values at
their coresponding timestamp.
"""
data_end = datetime.now()
if time == '1':
data_start = datetime.now() - timedelta(hours=0, minutes=30)
elif time == '2':
data_start = datetime.now() - timedelta(hours=1)
elif time == '3':
data_start = datetime.now() - timedelta(hours=2)
elif time == '4':
data_start = datetime.now() - timedelta(hours=6)
elif time == '5':
data_start = datetime.now() - timedelta(days=1)
else:
data_start = datetime.now() - timedelta(days=3650)
data_end.strftime('%Y-%m-%d %H:%M:%S')
data_start.strftime('%Y-%m-%d %H:%M:%S')
node_st = "openflow" + node
query = (
"SELECT Timestamp, Active_Flows "
f"FROM {node_st}_table0_summary WHERE "
f"Timestamp >= '{data_start}'"
f"AND Timestamp < '{data_end}'"
)
mydb = mysql.connector.connect(
host=sql_creds['host'],
user=sql_creds['user'],
passwd=sql_creds['password'],
database=db
)
cur = mydb.cursor()
cur.execute(query)
response = cur.fetchall()
displayPoints = []
dataPointDict = {}
for dataPoint in response:
# Response == Full sql query response
date = str(dataPoint[0])
flow_count = int(dataPoint[1])
dataPointDict = {"date": date, "flow_count": flow_count}
displayPoints.append(dataPointDict)
return displayPoints
| 29.550725 | 68 | 0.611574 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 741 | 0.363413 |
2ecd9594ca823d5651d395e05b565a78030a392e | 35,203 | py | Python | cardinal_pythonlib/sphinxtools.py | bopopescu/pythonlib | 9c2187d6092ba133342ca3374eb7c86f9d296c30 | [
"Apache-2.0"
] | null | null | null | cardinal_pythonlib/sphinxtools.py | bopopescu/pythonlib | 9c2187d6092ba133342ca3374eb7c86f9d296c30 | [
"Apache-2.0"
] | null | null | null | cardinal_pythonlib/sphinxtools.py | bopopescu/pythonlib | 9c2187d6092ba133342ca3374eb7c86f9d296c30 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# cardinal_pythonlib/sphinxtools.py
"""
===============================================================================
Original code copyright (C) 2009-2020 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
===============================================================================
**Functions to help with Sphinx, in particular the generation of autodoc
files.**
Rationale: if you want Sphinx ``autodoc`` code to appear as "one module per
Sphinx page" (which I normally do), you need one ``.rst`` file per module.
"""
from enum import Enum
from fnmatch import fnmatch
import glob
import logging
from os.path import (
abspath, basename, dirname, exists, expanduser, isdir, isfile, join,
relpath, sep, splitext
)
from typing import Dict, Iterable, List, Union
from cardinal_pythonlib.fileops import mkdir_p, relative_filename_within_dir
from cardinal_pythonlib.logs import BraceStyleAdapter
from cardinal_pythonlib.reprfunc import auto_repr
from pygments.lexer import Lexer
from pygments.lexers import get_lexer_for_filename
from pygments.util import ClassNotFound
log = BraceStyleAdapter(logging.getLogger(__name__))
# =============================================================================
# Constants
# =============================================================================
AUTOGENERATED_COMMENT = ".. THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT."
DEFAULT_INDEX_TITLE = "Automatic documentation of source code"
DEFAULT_SKIP_GLOBS = ["__init__.py"]
EXT_PYTHON = ".py"
EXT_RST = ".rst"
CODE_TYPE_NONE = "none"
class AutodocMethod(Enum):
"""
Enum to specify the method of autodocumenting a file.
"""
BEST = 0
CONTENTS = 1
AUTOMODULE = 2
# =============================================================================
# Helper functions
# =============================================================================
def rst_underline(heading: str, underline_char: str) -> str:
"""
Underlines a heading for RST files.
Args:
heading: text to underline
underline_char: character to use
Returns:
underlined heading, over two lines (without a final terminating
newline)
"""
assert "\n" not in heading
assert len(underline_char) == 1
return heading + "\n" + (underline_char * len(heading))
def fail(msg: str) -> None:
log.critical(msg)
raise RuntimeError(msg)
def write_if_allowed(filename: str,
content: str,
overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes the contents to a file, if permitted.
Args:
filename: filename to write
content: contents to write
overwrite: permit overwrites?
mock: pretend to write, but don't
Raises:
RuntimeError: if file exists but overwriting not permitted
"""
# Check we're allowed
if not overwrite and exists(filename):
fail(f"File exists, not overwriting: {filename!r}")
# Make the directory, if necessary
directory = dirname(filename)
if not mock:
mkdir_p(directory)
# Write the file
log.info("Writing to {!r}", filename)
if mock:
log.warning("Skipping writes as in mock mode")
else:
with open(filename, "wt") as outfile:
outfile.write(content)
# =============================================================================
# FileToAutodocument
# =============================================================================
class FileToAutodocument(object):
"""
Class representing a file to document automatically via Sphinx autodoc.
Example:
.. code-block:: python
import logging
from cardinal_pythonlib.logs import *
from cardinal_pythonlib.sphinxtools import *
main_only_quicksetup_rootlogger(level=logging.DEBUG)
f = FileToAutodocument(
source_filename="~/Documents/code/cardinal_pythonlib/cardinal_pythonlib/sphinxtools.py",
project_root_dir="~/Documents/code/cardinal_pythonlib",
target_rst_filename="~/Documents/code/cardinal_pythonlib/docs/source/autodoc/sphinxtools.rst",
)
print(f)
f.source_extension
f.is_python
f.source_filename_rel_project_root
f.rst_dir
f.source_filename_rel_rst_file
f.rst_filename_rel_project_root
f.rst_filename_rel_autodoc_index(
"~/Documents/code/cardinal_pythonlib/docs/source/autodoc/_index.rst")
f.python_module_name
f.pygments_code_type
print(f.rst_content(prefix=".. Hello!"))
print(f.rst_content(prefix=".. Hello!", method=AutodocMethod.CONTENTS))
f.write_rst(prefix=".. Hello!")
""" # noqa
def __init__(self,
source_filename: str,
project_root_dir: str,
target_rst_filename: str,
method: AutodocMethod = AutodocMethod.BEST,
python_package_root_dir: str = None,
source_rst_title_style_python: bool = True,
pygments_language_override: Dict[str, str] = None) -> None:
"""
Args:
source_filename: source file (e.g. Python, C++, XML file) to
document
project_root_dir: root directory of the whole project
target_rst_filename: filenamd of an RST file to write that will
document the source file
method: instance of :class:`AutodocMethod`; for example, should we
ask Sphinx's ``autodoc`` to read docstrings and build us a
pretty page, or just include the contents with syntax
highlighting?
python_package_root_dir: if your Python modules live in a directory
other than ``project_root_dir``, specify it here
source_rst_title_style_python: if ``True`` and the file is a Python
file and ``method == AutodocMethod.AUTOMODULE``, the heading
used will be in the style of a Python module, ``x.y.z``.
Otherwise, it will be a path (``x/y/z``).
pygments_language_override: if specified, a dictionary mapping
file extensions to Pygments languages (for example: a ``.pro``
file will be autodetected as Prolog, but you might want to
map that to ``none`` for Qt project files).
"""
self.source_filename = abspath(expanduser(source_filename))
self.project_root_dir = abspath(expanduser(project_root_dir))
self.target_rst_filename = abspath(expanduser(target_rst_filename))
self.method = method
self.source_rst_title_style_python = source_rst_title_style_python
self.python_package_root_dir = (
abspath(expanduser(python_package_root_dir))
if python_package_root_dir else self.project_root_dir
)
self.pygments_language_override = pygments_language_override or {} # type: Dict[str, str] # noqa
assert isfile(self.source_filename), (
f"Not a file: source_filename={self.source_filename!r}")
assert isdir(self.project_root_dir), (
f"Not a directory: project_root_dir={self.project_root_dir!r}")
assert relative_filename_within_dir(
filename=self.source_filename,
directory=self.project_root_dir
), (
f"Source file {self.source_filename!r} is not within "
f"project directory {self.project_root_dir!r}"
)
assert relative_filename_within_dir(
filename=self.python_package_root_dir,
directory=self.project_root_dir
), (
f"Python root {self.python_package_root_dir!r} is not within "
f"project directory {self.project_root_dir!r}"
)
assert isinstance(method, AutodocMethod)
def __repr__(self) -> str:
return auto_repr(self)
@property
def source_extension(self) -> str:
"""
Returns the extension of the source filename.
"""
return splitext(self.source_filename)[1]
@property
def is_python(self) -> bool:
"""
Is the source file a Python file?
"""
return self.source_extension == EXT_PYTHON
@property
def source_filename_rel_project_root(self) -> str:
"""
Returns the name of the source filename, relative to the project root.
Used to calculate file titles.
"""
return relpath(self.source_filename, start=self.project_root_dir)
@property
def source_filename_rel_python_root(self) -> str:
"""
Returns the name of the source filename, relative to the Python package
root. Used to calculate the name of Python modules.
"""
return relpath(self.source_filename,
start=self.python_package_root_dir)
@property
def rst_dir(self) -> str:
"""
Returns the directory of the target RST file.
"""
return dirname(self.target_rst_filename)
@property
def source_filename_rel_rst_file(self) -> str:
"""
Returns the source filename as seen from the RST filename that we
will generate. Used for ``.. include::`` commands.
"""
return relpath(self.source_filename, start=self.rst_dir)
@property
def rst_filename_rel_project_root(self) -> str:
"""
Returns the filename of the target RST file, relative to the project
root directory. Used for labelling the RST file itself.
"""
return relpath(self.target_rst_filename, start=self.project_root_dir)
def rst_filename_rel_autodoc_index(self, index_filename: str) -> str:
"""
Returns the filename of the target RST file, relative to a specified
index file. Used to make the index refer to the RST.
"""
index_dir = dirname(abspath(expanduser(index_filename)))
return relpath(self.target_rst_filename, start=index_dir)
@property
def python_module_name(self) -> str:
"""
Returns the name of the Python module that this instance refers to,
in dotted Python module notation, or a blank string if it doesn't.
"""
if not self.is_python:
return ""
filepath = self.source_filename_rel_python_root
dirs_and_base = splitext(filepath)[0]
dir_and_file_parts = dirs_and_base.split(sep)
return ".".join(dir_and_file_parts)
@property
def pygments_language(self) -> str:
"""
Returns the code type annotation for Pygments; e.g. ``python`` for
Python, ``cpp`` for C++, etc.
"""
extension = splitext(self.source_filename)[1]
if extension in self.pygments_language_override:
return self.pygments_language_override[extension]
try:
lexer = get_lexer_for_filename(self.source_filename) # type: Lexer
return lexer.name
except ClassNotFound:
log.warning("Don't know Pygments code type for extension {!r}",
self.source_extension)
return CODE_TYPE_NONE
def rst_content(self,
prefix: str = "",
suffix: str = "",
heading_underline_char: str = "=",
method: AutodocMethod = None) -> str:
"""
Returns the text contents of an RST file that will automatically
document our source file.
Args:
prefix: prefix, e.g. RST copyright comment
suffix: suffix, after the part we're creating
heading_underline_char: RST character to use to underline the
heading
method: optional method to override ``self.method``; see
constructor
Returns:
the RST contents
"""
spacer = " "
# Choose our final method
if method is None:
method = self.method
is_python = self.is_python
if method == AutodocMethod.BEST:
if is_python:
method = AutodocMethod.AUTOMODULE
else:
method = AutodocMethod.CONTENTS
elif method == AutodocMethod.AUTOMODULE:
if not is_python:
method = AutodocMethod.CONTENTS
# Write the instruction
if method == AutodocMethod.AUTOMODULE:
if self.source_rst_title_style_python:
title = self.python_module_name
else:
title = self.source_filename_rel_project_root
instruction = (
f".. automodule:: {self.python_module_name}\n"
f" :members:"
)
elif method == AutodocMethod.CONTENTS:
title = self.source_filename_rel_project_root
# Using ".. include::" with options like ":code: python" doesn't
# work properly; everything comes out as Python.
# Instead, see http://www.sphinx-doc.org/en/1.4.9/markup/code.html;
# we need ".. literalinclude::" with ":language: LANGUAGE".
instruction = (
".. literalinclude:: {filename}\n"
"{spacer}:language: {language}".format(
filename=self.source_filename_rel_rst_file,
spacer=spacer,
language=self.pygments_language
)
)
else:
raise ValueError("Bad method!")
# Create the whole file
content = """
.. {filename}
{AUTOGENERATED_COMMENT}
{prefix}
{underlined_title}
{instruction}
{suffix}
""".format(
filename=self.rst_filename_rel_project_root,
AUTOGENERATED_COMMENT=AUTOGENERATED_COMMENT,
prefix=prefix,
underlined_title=rst_underline(
title, underline_char=heading_underline_char),
instruction=instruction,
suffix=suffix,
).strip() + "\n"
return content
def write_rst(self,
prefix: str = "",
suffix: str = "",
heading_underline_char: str = "=",
method: AutodocMethod = None,
overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes the RST file to our destination RST filename, making any
necessary directories.
Args:
prefix: as for :func:`rst_content`
suffix: as for :func:`rst_content`
heading_underline_char: as for :func:`rst_content`
method: as for :func:`rst_content`
overwrite: overwrite the file if it exists already?
mock: pretend to write, but don't
"""
content = self.rst_content(
prefix=prefix,
suffix=suffix,
heading_underline_char=heading_underline_char,
method=method
)
write_if_allowed(self.target_rst_filename, content,
overwrite=overwrite, mock=mock)
# =============================================================================
# AutodocIndex
# =============================================================================
class AutodocIndex(object):
"""
Class to make an RST file that indexes others.
Example:
.. code-block:: python
import logging
from cardinal_pythonlib.logs import *
from cardinal_pythonlib.sphinxtools import *
main_only_quicksetup_rootlogger(level=logging.INFO)
# Example where one index contains another:
subidx = AutodocIndex(
index_filename="~/Documents/code/cardinal_pythonlib/docs/source/autodoc/_index2.rst",
highest_code_dir="~/Documents/code/cardinal_pythonlib",
project_root_dir="~/Documents/code/cardinal_pythonlib",
autodoc_rst_root_dir="~/Documents/code/cardinal_pythonlib/docs/source/autodoc",
source_filenames_or_globs="~/Documents/code/cardinal_pythonlib/docs/*.py",
)
idx = AutodocIndex(
index_filename="~/Documents/code/cardinal_pythonlib/docs/source/autodoc/_index.rst",
highest_code_dir="~/Documents/code/cardinal_pythonlib",
project_root_dir="~/Documents/code/cardinal_pythonlib",
autodoc_rst_root_dir="~/Documents/code/cardinal_pythonlib/docs/source/autodoc",
source_filenames_or_globs="~/Documents/code/cardinal_pythonlib/cardinal_pythonlib/*.py",
)
idx.add_index(subidx)
print(idx.index_content())
idx.write_index_and_rst_files(overwrite=True, mock=True)
# Example with a flat index:
flatidx = AutodocIndex(
index_filename="~/Documents/code/cardinal_pythonlib/docs/source/autodoc/_index.rst",
highest_code_dir="~/Documents/code/cardinal_pythonlib/cardinal_pythonlib",
project_root_dir="~/Documents/code/cardinal_pythonlib",
autodoc_rst_root_dir="~/Documents/code/cardinal_pythonlib/docs/source/autodoc",
source_filenames_or_globs="~/Documents/code/cardinal_pythonlib/cardinal_pythonlib/*.py",
)
print(flatidx.index_content())
flatidx.write_index_and_rst_files(overwrite=True, mock=True)
""" # noqa
def __init__(self,
index_filename: str,
project_root_dir: str,
autodoc_rst_root_dir: str,
highest_code_dir: str,
python_package_root_dir: str = None,
source_filenames_or_globs: Union[str, Iterable[str]] = None,
index_heading_underline_char: str = "-",
source_rst_heading_underline_char: str = "~",
title: str = DEFAULT_INDEX_TITLE,
introductory_rst: str = "",
recursive: bool = True,
skip_globs: List[str] = None,
toctree_maxdepth: int = 1,
method: AutodocMethod = AutodocMethod.BEST,
rst_prefix: str = "",
rst_suffix: str = "",
source_rst_title_style_python: bool = True,
pygments_language_override: Dict[str, str] = None) -> None:
"""
Args:
index_filename:
filename of the index ``.RST`` (ReStructured Text) file to
create
project_root_dir:
top-level directory for the whole project
autodoc_rst_root_dir:
directory within which all automatically generated ``.RST``
files (each to document a specific source file) will be placed.
A directory hierarchy within this directory will be created,
reflecting the structure of the code relative to
``highest_code_dir`` (q.v.).
highest_code_dir:
the "lowest" directory such that all code is found within it;
the directory structure within ``autodoc_rst_root_dir`` is to
``.RST`` files what the directory structure is of the source
files, relative to ``highest_code_dir``.
python_package_root_dir:
if your Python modules live in a directory other than
``project_root_dir``, specify it here
source_filenames_or_globs:
optional string, or list of strings, each describing a file or
glob-style file specification; these are the source filenames
to create automatic RST` for. If you don't specify them here,
you can use :func:`add_source_files`. To add sub-indexes, use
:func:`add_index` and :func:`add_indexes`.
index_heading_underline_char:
the character used to underline the title in the index file
source_rst_heading_underline_char:
the character used to underline the heading in each of the
source files
title:
title for the index
introductory_rst:
extra RST for the index, which goes between the title and the
table of contents
recursive:
use :func:`glob.glob` in recursive mode?
skip_globs:
list of file names or file specifications to skip; e.g.
``['__init__.py']``
toctree_maxdepth:
``maxdepth`` parameter for the ``toctree`` command generated in
the index file
method:
see :class:`FileToAutodocument`
rst_prefix:
optional RST content (e.g. copyright comment) to put early on
in each of the RST files
rst_suffix:
optional RST content to put late on in each of the RST files
source_rst_title_style_python:
make the individual RST files use titles in the style of Python
modules, ``x.y.z``, rather than path style (``x/y/z``); path
style will be used for non-Python files in any case.
pygments_language_override:
if specified, a dictionary mapping file extensions to Pygments
languages (for example: a ``.pro`` file will be autodetected as
Prolog, but you might want to map that to ``none`` for Qt
project files).
"""
assert index_filename
assert project_root_dir
assert autodoc_rst_root_dir
assert isinstance(toctree_maxdepth, int)
assert isinstance(method, AutodocMethod)
self.index_filename = abspath(expanduser(index_filename))
self.title = title
self.introductory_rst = introductory_rst
self.project_root_dir = abspath(expanduser(project_root_dir))
self.autodoc_rst_root_dir = abspath(expanduser(autodoc_rst_root_dir))
self.highest_code_dir = abspath(expanduser(highest_code_dir))
self.python_package_root_dir = (
abspath(expanduser(python_package_root_dir))
if python_package_root_dir else self.project_root_dir
)
self.index_heading_underline_char = index_heading_underline_char
self.source_rst_heading_underline_char = source_rst_heading_underline_char # noqa
self.recursive = recursive
self.skip_globs = skip_globs if skip_globs is not None else DEFAULT_SKIP_GLOBS # noqa
self.toctree_maxdepth = toctree_maxdepth
self.method = method
self.rst_prefix = rst_prefix
self.rst_suffix = rst_suffix
self.source_rst_title_style_python = source_rst_title_style_python
self.pygments_language_override = pygments_language_override or {} # type: Dict[str, str] # noqa
assert isdir(self.project_root_dir), (
f"Not a directory: project_root_dir={self.project_root_dir!r}")
assert relative_filename_within_dir(
filename=self.index_filename,
directory=self.project_root_dir
), (
f"Index file {self.index_filename!r} is not within "
f"project directory {self.project_root_dir!r}"
)
assert relative_filename_within_dir(
filename=self.highest_code_dir,
directory=self.project_root_dir
), (
f"Highest code directory {self.highest_code_dir!r} is not within "
f"project directory {self.project_root_dir!r}"
)
assert relative_filename_within_dir(
filename=self.autodoc_rst_root_dir,
directory=self.project_root_dir
), (
f"Autodoc RST root directory {self.autodoc_rst_root_dir!r} is not "
f"within project directory {self.project_root_dir!r}"
)
assert isinstance(method, AutodocMethod)
assert isinstance(recursive, bool)
self.files_to_index = [] # type: List[Union[FileToAutodocument, AutodocIndex]] # noqa
if source_filenames_or_globs:
self.add_source_files(source_filenames_or_globs)
def __repr__(self) -> str:
return auto_repr(self)
def add_source_files(
self,
source_filenames_or_globs: Union[str, List[str]],
method: AutodocMethod = None,
recursive: bool = None,
source_rst_title_style_python: bool = None,
pygments_language_override: Dict[str, str] = None) -> None:
"""
Adds source files to the index.
Args:
source_filenames_or_globs: string containing a filename or a
glob, describing the file(s) to be added, or a list of such
strings
method: optional method to override ``self.method``
recursive: use :func:`glob.glob` in recursive mode? (If ``None``,
the default, uses the version from the constructor.)
source_rst_title_style_python: optional to override
``self.source_rst_title_style_python``
pygments_language_override: optional to override
``self.pygments_language_override``
"""
if not source_filenames_or_globs:
return
if method is None:
# Use the default
method = self.method
if recursive is None:
recursive = self.recursive
if source_rst_title_style_python is None:
source_rst_title_style_python = self.source_rst_title_style_python
if pygments_language_override is None:
pygments_language_override = self.pygments_language_override
# Get a sorted list of filenames
final_filenames = self.get_sorted_source_files(
source_filenames_or_globs,
recursive=recursive
)
# Process that sorted list
for source_filename in final_filenames:
self.files_to_index.append(FileToAutodocument(
source_filename=source_filename,
project_root_dir=self.project_root_dir,
python_package_root_dir=self.python_package_root_dir,
target_rst_filename=self.specific_file_rst_filename(
source_filename
),
method=method,
source_rst_title_style_python=source_rst_title_style_python,
pygments_language_override=pygments_language_override,
))
def get_sorted_source_files(
self,
source_filenames_or_globs: Union[str, List[str]],
recursive: bool = True) -> List[str]:
"""
Returns a sorted list of filenames to process, from a filename,
a glob string, or a list of filenames/globs.
Args:
source_filenames_or_globs: filename/glob, or list of them
recursive: use :func:`glob.glob` in recursive mode?
Returns:
sorted list of files to process
"""
if isinstance(source_filenames_or_globs, str):
source_filenames_or_globs = [source_filenames_or_globs]
final_filenames = [] # type: List[str]
for sfg in source_filenames_or_globs:
sfg_expanded = expanduser(sfg)
log.debug("Looking for: {!r}", sfg_expanded)
for filename in glob.glob(sfg_expanded, recursive=recursive):
log.debug("Trying: {!r}", filename)
if self.should_exclude(filename):
log.info("Skipping file {!r}", filename)
continue
final_filenames.append(filename)
final_filenames.sort()
return final_filenames
@staticmethod
def filename_matches_glob(filename: str, globtext: str) -> bool:
"""
The ``glob.glob`` function doesn't do exclusion very well. We don't
want to have to specify root directories for exclusion patterns. We
don't want to have to trawl a massive set of files to find exclusion
files. So let's implement a glob match.
Args:
filename: filename
globtext: glob
Returns:
does the filename match the glob?
See also:
- https://stackoverflow.com/questions/20638040/glob-exclude-pattern
"""
# Quick check on basename-only matching
if fnmatch(filename, globtext):
log.debug("{!r} matches {!r}", filename, globtext)
return True
bname = basename(filename)
if fnmatch(bname, globtext):
log.debug("{!r} matches {!r}", bname, globtext)
return True
# Directory matching: is actually accomplished by the code above!
# Otherwise:
return False
def should_exclude(self, filename) -> bool:
"""
Should we exclude this file from consideration?
"""
for skip_glob in self.skip_globs:
if self.filename_matches_glob(filename, skip_glob):
return True
return False
def add_index(self, index: "AutodocIndex") -> None:
"""
Add a sub-index file to this index.
Args:
index: index file to add, as an instance of :class:`AutodocIndex`
"""
self.files_to_index.append(index)
def add_indexes(self, indexes: List["AutodocIndex"]) -> None:
"""
Adds multiple sub-indexes to this index.
Args:
indexes: list of sub-indexes
"""
for index in indexes:
self.add_index(index)
def specific_file_rst_filename(self, source_filename: str) -> str:
"""
Gets the RST filename corresponding to a source filename.
See the help for the constructor for more details.
Args:
source_filename: source filename within current project
Returns:
RST filename
Note in particular: the way we structure the directories means that we
won't get clashes between files with idential names in two different
directories. However, we must also incorporate the original source
filename, in particular for C++ where ``thing.h`` and ``thing.cpp``
must not generate the same RST filename. So we just add ``.rst``.
"""
highest_code_to_target = relative_filename_within_dir(
source_filename, self.highest_code_dir)
bname = basename(source_filename)
result = join(self.autodoc_rst_root_dir,
dirname(highest_code_to_target),
bname + EXT_RST)
log.debug("Source {!r} -> RST {!r}", source_filename, result)
return result
def write_index_and_rst_files(self, overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes both the individual RST files and the index.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't
"""
for f in self.files_to_index:
if isinstance(f, FileToAutodocument):
f.write_rst(
prefix=self.rst_prefix,
suffix=self.rst_suffix,
heading_underline_char=self.source_rst_heading_underline_char, # noqa
overwrite=overwrite,
mock=mock,
)
elif isinstance(f, AutodocIndex):
f.write_index_and_rst_files(overwrite=overwrite, mock=mock)
else:
fail(f"Unknown thing in files_to_index: {f!r}")
self.write_index(overwrite=overwrite, mock=mock)
@property
def index_filename_rel_project_root(self) -> str:
"""
Returns the name of the index filename, relative to the project root.
Used for labelling the index file.
"""
return relpath(self.index_filename, start=self.project_root_dir)
def index_filename_rel_other_index(self, other: str) -> str:
"""
Returns the filename of this index, relative to the director of another
index. (For inserting a reference to this index into ``other``.)
Args:
other: the other index
Returns:
relative filename of our index
"""
return relpath(self.index_filename, start=dirname(other))
def index_content(self) -> str:
"""
Returns the contents of the index RST file.
"""
# Build the toctree command
index_filename = self.index_filename
spacer = " "
toctree_lines = [
".. toctree::",
spacer + f":maxdepth: {self.toctree_maxdepth}",
""
]
for f in self.files_to_index:
if isinstance(f, FileToAutodocument):
rst_filename = spacer + f.rst_filename_rel_autodoc_index(
index_filename)
elif isinstance(f, AutodocIndex):
rst_filename = (
spacer + f.index_filename_rel_other_index(index_filename)
)
else:
fail(f"Unknown thing in files_to_index: {f!r}")
rst_filename = "" # won't get here; for the type checker
toctree_lines.append(rst_filename)
toctree = "\n".join(toctree_lines)
# Create the whole file
content = """
.. {filename}
{AUTOGENERATED_COMMENT}
{prefix}
{underlined_title}
{introductory_rst}
{toctree}
{suffix}
""".format(
filename=self.index_filename_rel_project_root,
AUTOGENERATED_COMMENT=AUTOGENERATED_COMMENT,
prefix=self.rst_prefix,
underlined_title=rst_underline(
self.title, underline_char=self.index_heading_underline_char),
introductory_rst=self.introductory_rst,
toctree=toctree,
suffix=self.rst_suffix,
).strip() + "\n"
return content
def write_index(self, overwrite: bool = False, mock: bool = False) -> None:
"""
Writes the index file, if permitted.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't
"""
write_if_allowed(self.index_filename, self.index_content(),
overwrite=overwrite, mock=mock)
| 37.81203 | 106 | 0.599068 | 31,020 | 0.881175 | 0 | 0 | 4,189 | 0.118996 | 0 | 0 | 18,392 | 0.522455 |
2ecd9c823bd13321a5aed037237d0b2d3b1ca359 | 481 | py | Python | monsterapi/migrations/0005_monster_name.py | merenor/momeback | 33195c43abd2757a361dfc5cb7e3cf56f6b57402 | [
"MIT"
] | 1 | 2018-11-05T13:08:48.000Z | 2018-11-05T13:08:48.000Z | monsterapi/migrations/0005_monster_name.py | merenor/momeback | 33195c43abd2757a361dfc5cb7e3cf56f6b57402 | [
"MIT"
] | null | null | null | monsterapi/migrations/0005_monster_name.py | merenor/momeback | 33195c43abd2757a361dfc5cb7e3cf56f6b57402 | [
"MIT"
] | null | null | null | # Generated by Django 2.1.3 on 2018-11-08 21:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('monsterapi', '0004_name'),
]
operations = [
migrations.AddField(
model_name='monster',
name='name',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='monsterapi.Name'),
),
]
| 24.05 | 126 | 0.634096 | 355 | 0.738046 | 0 | 0 | 0 | 0 | 0 | 0 | 102 | 0.212058 |
2ecf02de134bbfb63253edf9f0df0a07e83ef05f | 239 | py | Python | src/check_ids.py | lubianat/complex_bot | e0ddabcc0487c52b14fb94950c5a812f0bdb2283 | [
"MIT"
] | 1 | 2021-10-06T00:21:10.000Z | 2021-10-06T00:21:10.000Z | src/check_ids.py | lubianat/complex_bot | e0ddabcc0487c52b14fb94950c5a812f0bdb2283 | [
"MIT"
] | 14 | 2021-01-15T21:51:38.000Z | 2021-11-10T10:08:22.000Z | src/check_ids.py | lubianat/complex_bot | e0ddabcc0487c52b14fb94950c5a812f0bdb2283 | [
"MIT"
] | 1 | 2021-01-18T10:32:56.000Z | 2021-01-18T10:32:56.000Z | import pandas as pd
from wikidataintegrator import wdi_login
import utils
from login import WDPASS, WDUSER
import argparse
import sys
parser = argparse.ArgumentParser()
df = utils.get_complex_portal_species_ids()
print(df.to_markdown()) | 21.727273 | 43 | 0.824268 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2ed00b75cde30c9fb64baa2e01095d04529cd5dc | 2,398 | py | Python | src/sentry/migrations/0028_user_reports.py | pierredup/sentry | 0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80 | [
"BSD-3-Clause"
] | null | null | null | src/sentry/migrations/0028_user_reports.py | pierredup/sentry | 0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80 | [
"BSD-3-Clause"
] | null | null | null | src/sentry/migrations/0028_user_reports.py | pierredup/sentry | 0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.27 on 2020-01-23 19:07
from __future__ import unicode_literals
import logging
from django.db import migrations
from sentry import eventstore
from sentry.utils.query import RangeQuerySetWrapper
from sentry.utils.snuba import (
SnubaError,
QueryOutsideRetentionError,
QueryOutsideGroupActivityError,
)
logger = logging.getLogger(__name__)
def backfill_user_reports(apps, schema_editor):
"""
Processes user reports that are missing event data, and adds the appropriate data
if the event exists in Clickhouse.
"""
UserReport = apps.get_model("sentry", "UserReport")
user_reports = UserReport.objects.filter(group__isnull=True, environment__isnull=True)
for report in RangeQuerySetWrapper(user_reports, step=1000):
try:
event = eventstore.get_event_by_id(report.project_id, report.event_id)
except (SnubaError, QueryOutsideGroupActivityError, QueryOutsideRetentionError) as se:
logger.warn(
"failed to fetch event %s for project %d: %s"
% (report.event_id, report.project_id, se)
)
continue
if event:
report.update(group_id=event.group_id, environment=event.get_environment())
class Migration(migrations.Migration):
# This flag is used to mark that a migration shouldn't be automatically run in
# production. We set this to True for operations that we think are risky and want
# someone from ops to run manually and monitor.
# General advice is that if in doubt, mark your migration as `is_dangerous`.
# Some things you should always mark as dangerous:
# - Adding indexes to large tables. These indexes should be created concurrently,
# unfortunately we can't run migrations outside of a transaction until Django
# 1.10. So until then these should be run manually.
# - Large data migrations. Typically we want these to be run manually by ops so that
# they can be monitored. Since data migrations will now hold a transaction open
# this is even more important.
# - Adding columns to highly active tables, even ones that are NULL.
is_dangerous = True
dependencies = [
("sentry", "0027_exporteddata"),
]
operations = [
migrations.RunPython(backfill_user_reports, migrations.RunPython.noop),
]
| 36.892308 | 94 | 0.708924 | 1,107 | 0.461635 | 0 | 0 | 0 | 0 | 0 | 0 | 1,110 | 0.462886 |
2ed1150755a47f709a199aa35375f61abbfe571c | 190 | py | Python | config.py | sixleaves/fisher | 8f35e840f936e4a4d8450acaae793af3be00a842 | [
"MIT"
] | null | null | null | config.py | sixleaves/fisher | 8f35e840f936e4a4d8450acaae793af3be00a842 | [
"MIT"
] | null | null | null | config.py | sixleaves/fisher | 8f35e840f936e4a4d8450acaae793af3be00a842 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/5/5 12:39 AM
@Author : sweetcs
@Site :
@File : config.py
@Software: PyCharm
"""
DEBUG=True
HOST="0.0.0.0"
PORT=9292 | 14.615385 | 28 | 0.578947 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 160 | 0.842105 |
2ed1c87b80dd4e8779929d2ec1d831bf4040a93d | 45 | py | Python | garbage/buidlInformation.py | mjasnikovs/horus | c342aafc074e163a5a2eaa3564cba3131c6050a0 | [
"MIT"
] | null | null | null | garbage/buidlInformation.py | mjasnikovs/horus | c342aafc074e163a5a2eaa3564cba3131c6050a0 | [
"MIT"
] | null | null | null | garbage/buidlInformation.py | mjasnikovs/horus | c342aafc074e163a5a2eaa3564cba3131c6050a0 | [
"MIT"
] | null | null | null | import cv2
print(cv2.getBuildInformation())
| 11.25 | 32 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2ed3994d0c5b4857eeceb1cfe4c63346bcc38f0c | 26,733 | py | Python | contrib/gitian-build.py | castarco/unit-e | a396aaea29406744e04057aab3a771c7283086e9 | [
"MIT"
] | 36 | 2019-04-17T18:58:51.000Z | 2022-01-18T12:16:27.000Z | contrib/gitian-build.py | Danpetersen448/unit-e | 4ca86fc55a41e0daeb4409de2719a5523b6007c6 | [
"MIT"
] | 109 | 2019-04-17T17:19:45.000Z | 2019-06-19T15:16:37.000Z | contrib/gitian-build.py | Danpetersen448/unit-e | 4ca86fc55a41e0daeb4409de2719a5523b6007c6 | [
"MIT"
] | 16 | 2019-04-17T17:35:42.000Z | 2020-01-09T17:51:05.000Z | #!/usr/bin/env python3
# Copyright (c) 2018-2019 The Bitcoin Core developers
# Copyright (c) 2019 The Unit-e developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://opensource.org/licenses/MIT.
import argparse
import os
import subprocess
import sys
import platform
import tempfile
from pathlib import Path
from contextlib import contextmanager
OSSLSIGNCODE_VER = '1.7.1'
OSSLSIGNCODE_DIR = 'osslsigncode-'+OSSLSIGNCODE_VER
@contextmanager
def cd(destination_dir):
original_dir = os.getcwd()
os.chdir(destination_dir)
try:
yield
finally:
os.chdir(original_dir)
class Installer:
""" Wrapper around native package installer, supports apt-get and brew, only
installs packages which aren't installed yet."""
def __init__(self, backend=None, quiet=False):
if backend != "apt" and backend != "brew":
raise ValueError("Invalid value for backend argument: '%'. Valid values are `apt` and `brew`.")
self.backend = backend
self.updated = False
self.to_install = []
if quiet and self.backend == "apt":
self.flags = ['-qq']
else:
self.flags = []
def backend_command(self, subcommand):
if self.backend == 'apt':
if subcommand == 'ls':
command = ['dpkg', '-s']
else:
command = ['sudo', 'apt-get', subcommand] + self.flags
elif self.backend == 'brew':
command = ['brew', subcommand]
return command
def update(self):
if not self.updated:
self.updated = True
subprocess.check_call(self.backend_command('update'))
def try_to_install(self, *programs):
self.update()
print(self.backend + ': installing', ", ".join(programs))
return subprocess.call(self.backend_command('install') + list(programs)) == 0
def batch_install(self):
if not self.to_install:
print(self.backend + ': nothing to install')
return
if not self.try_to_install(*self.to_install):
print('Could not install packages.', file=sys.stderr)
exit(1)
self.to_install = []
def is_installed(self, program):
return subprocess.call(self.backend_command('ls') + [program], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0
def add_requirements(self, *programs):
for program in programs:
if not self.is_installed(program):
self.to_install.append(program)
def verify_user_specified_osslsigncode(user_spec_path):
if not Path(user_spec_path).is_file():
raise Exception('provided osslsign does not exists: {}'.format(user_spec_path))
try:
if subprocess.call([user_spec_path, '--version'], stderr=subprocess.DEVNULL) != 255:
raise Exception('cannot execute provided osslsigncode: {}'.format(user_spec_path))
except subprocess.CalledProcessError as e:
raise Exception('unexpected exception raised while executing provided osslsigncode: {}'.format(str(e)))
return Path(user_spec_path).resolve()
def find_osslsigncode(user_spec_path):
if user_spec_path:
return verify_user_specified_osslsigncode(user_spec_path)
which_ossl_proc = subprocess.Popen(['which', 'osslsigncode'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
if which_ossl_proc.wait() == 0:
ossl_path = which_ossl_proc.communicate()[0].split()[0].decode()
if subprocess.call([ossl_path, '--version'], stderr=subprocess.DEVNULL) == 255:
return ossl_path
expected_path = Path(OSSLSIGNCODE_DIR, 'osslsigncode')
if expected_path.is_file() and subprocess.call([expected_path, '--version'], stderr=subprocess.DEVNULL) == 255:
return expected_path.resolve()
return None
def install_osslsigner():
subprocess.check_call(['wget', '-N', 'https://downloads.sourceforge.net/project/osslsigncode/osslsigncode/osslsigncode-'+OSSLSIGNCODE_VER+'.tar.gz'])
subprocess.check_call(['wget', '-N', 'https://bitcoincore.org/cfields/osslsigncode-Backports-to-'+OSSLSIGNCODE_VER+'.patch'])
subprocess.check_call(["echo 'a8c4e9cafba922f89de0df1f2152e7be286aba73f78505169bc351a7938dd911 osslsigncode-Backports-to-"+OSSLSIGNCODE_VER+".patch' | sha256sum -c"], shell=True)
subprocess.check_call(["echo 'f9a8cdb38b9c309326764ebc937cba1523a3a751a7ab05df3ecc99d18ae466c9 osslsigncode-"+OSSLSIGNCODE_VER+".tar.gz' | sha256sum -c"], shell=True)
subprocess.check_call(['tar', '-xzf', 'osslsigncode-'+OSSLSIGNCODE_VER+'.tar.gz'])
subprocess.check_call(['patch -p1 < ../osslsigncode-Backports-to-'+OSSLSIGNCODE_VER+'.patch'], shell=True, cwd=OSSLSIGNCODE_DIR)
subprocess.check_call(['./configure', '--without-gsf', '--without-curl', '--disable-dependency-tracking'], cwd=OSSLSIGNCODE_DIR)
subprocess.check_call(['make'], cwd=OSSLSIGNCODE_DIR)
return Path(OSSLSIGNCODE_DIR, 'osslsigncode').resolve()
def install_libssl_dev(apt):
dist_str = platform.dist()
dist_type = dist_str[0]
dist_no = int(dist_str[1].replace('.', ''))
if dist_type == 'Ubuntu' and dist_no < 1800 or dist_type == 'Debian' and dist_no < 900:
apt.add_requirements('libssl-dev')
else:
apt.add_requirements('libssl1.0-dev')
def install_linux_deps(args):
apt = Installer(backend='apt', quiet=args.quiet)
apt.add_requirements('ruby', 'git', 'make')
if args.kvm:
apt.add_requirements('apt-cacher-ng', 'python-vm-builder', 'qemu-kvm', 'qemu-utils')
elif args.docker:
if subprocess.call(['docker', '--version']) != 0:
if not apt.try_to_install('docker.io') and not apt.try_to_install('docker-ce'):
print('Cannot find any way to install docker', file=sys.stderr)
exit(1)
else:
apt.add_requirements('apt-cacher-ng', 'lxc', 'debootstrap')
should_make_ossl = False
if args.codesign and args.windows:
args.osslsigncode_path = find_osslsigncode(args.osslsigncode_path)
if not args.osslsigncode_path:
should_make_ossl = True
apt.add_requirements('tar', 'wget', 'patch', 'autoconf')
install_libssl_dev(apt)
apt.batch_install()
if should_make_ossl:
args.osslsigncode_path = install_osslsigner()
def create_bin_symlink(link, target):
bin_path = Path("bin", link)
if not bin_path.exists():
bin_path.symlink_to(target)
def install_mac_deps(args):
if not args.docker:
print('Mac can only work with docker, re-run with --docker flag.', file=sys.stderr)
exit(1)
if subprocess.call(['docker', '--version']) != 0:
print('Please install docker manually, e.g. with `brew cask install docker`.', file=sys.stderr)
exit(1)
brew = Installer(backend='brew')
brew.add_requirements('ruby', 'coreutils')
brew.batch_install()
create_bin_symlink("date", "/usr/local/bin/gdate")
create_bin_symlink("sha256sum", "/usr/local/bin/gsha256sum")
def install_deps(args):
system_str = platform.system()
if system_str == 'Linux':
install_linux_deps(args)
elif system_str == 'Darwin':
install_mac_deps(args)
else:
print("Unsupported system '%s'." % system_str, file=sys.stderr)
exit(1)
def setup(args):
install_deps(args)
if not Path('unit-e-sigs').is_dir():
subprocess.check_call(['git', 'clone', 'git@github.com:dtr-org/unit-e-sigs.git'])
if not Path('gitian-builder').is_dir():
subprocess.check_call(['git', 'clone', 'https://github.com/devrandom/gitian-builder.git'])
if not Path(args.git_dir).is_dir():
subprocess.check_call(['git', 'clone', args.url, args.git_dir])
make_image_prog = ['bin/make-base-vm', '--suite', 'bionic', '--arch', 'amd64']
if args.docker:
make_image_prog += ['--docker']
elif not args.kvm:
make_image_prog += ['--lxc']
subprocess.check_call(make_image_prog, cwd='gitian-builder')
if args.is_bionic and not args.kvm and not args.docker:
subprocess.check_call(['sudo', 'sed', '-i', 's/lxcbr0/br0/', '/etc/default/lxc-net'])
print('Reboot is required')
exit(0)
def gitian_descriptors(args, platform_str):
return '../work/gitian-descriptors/gitian-' + platform_str + '.yml'
def build(args):
os.makedirs('unit-e-binaries/' + args.version, exist_ok=True)
print('\nBuilding Dependencies\n')
with cd('gitian-builder'):
os.makedirs('inputs', exist_ok=True)
subprocess.check_call(['make', '-C', Path('../', args.git_dir, 'depends'), 'download', 'SOURCES_PATH=' + os.getcwd() + '/cache/common'])
if args.linux:
print('\nCompiling ' + args.version + ' Linux')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'unit-e='+args.commit, '--url', 'unit-e='+args.url, gitian_descriptors(args, 'linux')])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-linux', '--destination', '../unit-e-sigs/', gitian_descriptors(args, 'linux')])
subprocess.check_call('mv build/out/unit-e-*.tar.gz build/out/src/unit-e-*.tar.gz ../unit-e-binaries/'+args.version, shell=True)
if args.windows:
print('\nCompiling ' + args.version + ' Windows')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'unit-e='+args.commit, '--url', 'unit-e='+args.url, gitian_descriptors(args, 'win')])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-win-unsigned', '--destination', '../unit-e-sigs/', gitian_descriptors(args, 'win')])
subprocess.check_call('mv build/out/unit-e-*-win-unsigned.tar.gz inputs/', shell=True)
subprocess.check_call('mv build/out/unit-e-*.zip build/out/unit-e-*.exe ../unit-e-binaries/'+args.version, shell=True)
if args.macos:
print('\nCompiling ' + args.version + ' MacOS')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'unit-e='+args.commit, '--url', 'unit-e='+args.url, gitian_descriptors(args, 'osx')])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-osx-unsigned', '--destination', '../unit-e-sigs/', gitian_descriptors(args, 'osx')])
subprocess.check_call('mv build/out/unit-e-*.tar.gz ../unit-e-binaries/'+args.version, shell=True)
if args.commit_files:
print('\nCommitting '+args.version+' Unsigned Sigs\n')
with cd('unit-e-sigs'):
if args.linux:
subprocess.check_call(['git', 'add', args.version+'-linux/'+args.signer])
if args.windows:
subprocess.check_call(['git', 'add', args.version+'-win-unsigned/'+args.signer])
if args.macos:
subprocess.check_call(['git', 'add', args.version+'-osx-unsigned/'+args.signer])
subprocess.check_call(['git', 'commit', '-m', 'Add '+args.version+' unsigned sigs for '+args.signer])
def get_signatures_path(platform_str, version):
return Path('unit-e-sigs', version + '-detached', 'unit-e-'+platform_str+'-signatures.tar.gz').resolve()
def codesign_windows(osslsign_path, version, win_code_cert_path, win_code_key_path):
gitian_dir = Path('gitian-builder').resolve()
signatures_tarball = get_signatures_path('win', version)
if signatures_tarball.is_file():
print('Signatures already present at:', signatures_tarball, '\nI cowardly refuse to continue', file=sys.stderr)
exit(1)
signatures_tarball.parent.mkdir(exist_ok=True)
print('\nSigning ' + version + ' Windows')
with tempfile.TemporaryDirectory() as build_dir:
subprocess.check_call(['cp', 'inputs/unit-e-' + version + '-win-unsigned.tar.gz', Path(build_dir, 'unit-e-win-unsigned.tar.gz')], cwd=gitian_dir)
subprocess.check_call(['tar', '-xzf', 'unit-e-win-unsigned.tar.gz'], cwd=build_dir)
for fp in Path(build_dir).glob('unsigned/*.exe'):
subprocess.check_call([osslsign_path, 'sign', '-certs', win_code_cert_path, '-in', fp, '-out', str(fp)+'-signed', '-key', win_code_key_path, '-askpass'])
subprocess.check_call([osslsign_path, 'extract-signature', '-pem', '-in', str(fp)+'-signed', '-out', str(fp)+'.pem'])
subprocess.check_call(['tar', '-czf', signatures_tarball, *[path.name for path in Path(build_dir, 'unsigned').glob('*.exe.pem')]], cwd=Path(build_dir, 'unsigned'))
def codesign(args):
if not args.windows:
print('Warning: codesigning requested, but windows not in the --os flag.', file=sys.stderr)
return
codesign_windows(args.osslsigncode_path, args.version, args.win_code_cert_path, args.win_code_key_path)
if args.commit_files:
print('\nCommitting '+args.version+' Detached Sigs\n')
subprocess.check_call(['git', 'add', Path(args.version + '-detached', 'unit-e-win-signatures.tar.gz')], cwd='unit-e-sigs')
subprocess.check_call(['git', 'commit', '-a', '-m', 'Add '+args.version+' detached signatures by '+args.signer], cwd='unit-e-sigs')
def sign(args):
if not args.windows:
print('Warning: signing requested, but windows not in the --os flag.', file=sys.stderr)
return
gitian_dir = Path('gitian-builder').resolve()
subprocess.check_call(['wget', '-N', '-P', 'inputs', 'https://downloads.sourceforge.net/project/osslsigncode/osslsigncode/osslsigncode-'+OSSLSIGNCODE_VER+'.tar.gz'], cwd=gitian_dir)
subprocess.check_call(['wget', '-N', '-P', 'inputs', 'https://bitcoincore.org/cfields/osslsigncode-Backports-to-'+OSSLSIGNCODE_VER+'.patch'], cwd=gitian_dir)
signatures_tarball = get_signatures_path('win', args.version)
if not signatures_tarball.is_file():
print('Signatures not present at:', signatures_tarball, file=sys.stderr)
exit(1)
print('\nSigning ' + args.version + ' Windows')
subprocess.check_call(['cp', signatures_tarball, 'inputs/unit-e-win-signatures.tar.gz'], cwd=gitian_dir)
subprocess.check_call(['cp', 'inputs/unit-e-' + args.version + '-win-unsigned.tar.gz', 'inputs/unit-e-win-unsigned.tar.gz'], cwd=gitian_dir)
subprocess.check_call(['bin/gbuild', '-i', '--commit', 'signature=master', gitian_descriptors(args, 'win-signer')], cwd=gitian_dir)
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-win-signed', '--destination', '../unit-e-sigs/', gitian_descriptors(args, 'win-signer')], cwd=gitian_dir)
subprocess.check_call('mv build/out/unit-e-*win64-setup.exe ../unit-e-binaries/'+args.version, shell=True, cwd=gitian_dir)
subprocess.check_call('mv build/out/unit-e-*win32-setup.exe ../unit-e-binaries/'+args.version, shell=True, cwd=gitian_dir)
if args.commit_files:
print('\nCommitting '+args.version+' Signed Sigs\n')
subprocess.check_call(['git', 'add', args.version+'-win-signed/'+args.signer], cwd='unit-e-sigs')
subprocess.check_call(['git', 'commit', '-a', '-m', 'Add '+args.version+' signed binary sigs for '+args.signer], cwd='unit-e-sigs')
def verify(args):
""" Verify the builds. Exits with error in case any of the signatures fail to verify and if any of the signatures are missing. """
gitian_builder = Path('gitian-builder')
sigs_path = Path('unit-e-sigs')
builds_were_missing = False
for (sig_path_suffix, descriptor_suffix, build_name) in [
('linux', 'linux', 'Linux'),
('win-unsigned', 'win', 'Windows'),
('osx-unsigned', 'osx', 'MacOS'),
('win-signed', 'win-signer', 'Signed Windows'),
]:
build_sig_dir = args.version + '-' + sig_path_suffix
if Path(sigs_path, build_sig_dir).is_dir():
print('\nVerifying v{} {}\n'.format(args.version, build_name))
descriptor = gitian_descriptors(args, descriptor_suffix)
subprocess.check_call(['bin/gverify', '-v', '-d', '../unit-e-sigs/', '-r', build_sig_dir, descriptor], cwd=gitian_builder)
else:
print('\nSkipping v{} {} as it is not present\n'.format(args.version, build_name))
builds_were_missing = True
if builds_were_missing:
print('Some builds were missing, please refer to previous logs.', file=sys.stderr)
exit(1)
def prepare_git_dir(args):
with cd(args.git_dir):
if args.pull:
subprocess.check_call(['git', 'fetch', args.url, 'refs/pull/'+args.version+'/merge'])
os.chdir('../gitian-builder/inputs/unit-e')
subprocess.check_call(['git', 'fetch', args.url, 'refs/pull/'+args.version+'/merge'])
args.commit = subprocess.check_output(['git', 'show', '-s', '--format=%H', 'FETCH_HEAD'], universal_newlines=True, encoding='utf8').strip()
args.version = 'pull-' + args.version
print(args.commit)
if not args.skip_checkout:
subprocess.check_call(['git', 'fetch'])
subprocess.check_call(['git', 'checkout', args.commit])
# Use only keyword-only arguments as defined in PEP 3102 to avoid accidentally swapping of arguments
def prepare_gitian_descriptors(*, source, target, hosts=None):
descriptor_source_dir = Path(source)
descriptor_dir = Path(target)
if not descriptor_source_dir.is_dir():
raise Exception("Gitian descriptor dir '%s' does not exist" % descriptor_source_dir)
descriptor_dir.mkdir(parents=True, exist_ok=True)
for descriptor_path in descriptor_source_dir.glob("*.yml"):
filename = descriptor_path.relative_to(descriptor_source_dir)
descriptor_in = descriptor_source_dir / filename
descriptor_out = descriptor_dir / filename
with descriptor_out.open("w") as file_out, descriptor_in.open() as file_in:
for line in file_in:
if hosts and line.startswith(' HOSTS='):
file_out.write(' HOSTS="%s"\n' % hosts)
else:
file_out.write(line)
def create_work_dir(work_dir):
work_dir = Path(work_dir)
if Path(work_dir).exists() and not Path(work_dir).is_dir():
raise Exception("Work dir '%s' exists but is not a directory." % work_dir)
if not work_dir.exists():
print("Creating working directory '%s'" % work_dir)
work_dir.mkdir()
return work_dir.resolve()
def main():
parser = argparse.ArgumentParser(usage='%(prog)s [options]')
parser.add_argument('-c', '--commit', action='store_true', dest='commit', help='Indicate that the version argument is for a commit or branch')
parser.add_argument('-p', '--pull', action='store_true', dest='pull', help='Indicate that the version argument is the number of a github repository pull request')
parser.add_argument('-u', '--url', dest='url', default='git@github.com:dtr-org/unit-e.git', help='Specify the URL of the repository. Default is %(default)s')
parser.add_argument('-g', '--git-dir', dest='git_dir', default='unit-e', help='Specify the name of the directory where the unit-e git repo is checked out. This is relative to the working directory (see --work-dir option)')
parser.add_argument('-v', '--verify', action='store_true', dest='verify', help='Verify the Gitian build')
parser.add_argument('-b', '--build', action='store_true', dest='build', help='Do a Gitian build')
parser.add_argument('-C', '--codesign', action='store_true', dest='codesign', help='Make detached signatures for Windows and MacOS')
parser.add_argument('-s', '--sign', action='store_true', dest='sign', help='Make signed binaries for Windows')
parser.add_argument('-B', '--buildsign', action='store_true', dest='buildsign', help='Build both signed and unsigned binaries')
parser.add_argument('-o', '--os', dest='os', default='lwm', help='Specify which Operating Systems the build is for. Default is %(default)s. l for Linux, w for Windows, m for MacOS')
parser.add_argument('-j', '--jobs', dest='jobs', default='2', help='Number of processes to use. Default %(default)s')
parser.add_argument('-m', '--memory', dest='memory', default='2000', help='Memory to allocate in MiB. Default %(default)s')
parser.add_argument('-k', '--kvm', action='store_true', dest='kvm', help='Use KVM instead of LXC')
parser.add_argument('-d', '--docker', action='store_true', dest='docker', help='Use Docker instead of LXC')
parser.add_argument('-S', '--setup', action='store_true', dest='setup', help='Set up the Gitian building environment. Uses LXC. If you want to use KVM, use the --kvm option. Only works on Debian-based systems (Ubuntu, Debian)')
parser.add_argument('-D', '--detach-sign', action='store_true', dest='detach_sign', help='Create the assert file for detached signing. Will not commit anything.')
parser.add_argument('-n', '--no-commit', action='store_false', dest='commit_files', help='Do not commit anything to git')
parser.add_argument('-q', '--quiet', action='store_true', dest='quiet', help='Do not prompt user for confirmations')
parser.add_argument('--osslsign', dest='osslsigncode_path', help='Path to osslsigncode executable.')
parser.add_argument('--win-code-cert', dest='win_code_cert_path', help='Path to code signing certificate.')
parser.add_argument('--win-code-key', dest='win_code_key_path', help='Path to key corresponding to code signing certificate.')
parser.add_argument('--signer', dest='signer', help='GPG signer to sign each build assert file. Required to build, sign or verify')
parser.add_argument('--version', dest='version', help='Version number, commit, or branch to build. If building a commit or branch, the -c option must be specified. Required to build, sign or verify')
parser.add_argument('--skip-checkout', dest='skip_checkout', action='store_true', help='Skip checkout of git repo. Use with care as it might leave you in an inconsistent state.')
parser.add_argument('--hosts', dest='hosts', help='Specify hosts for which is built. See the gitian descriptors for valid values.')
parser.add_argument('-w', '--work-dir', dest='work_dir', help='Working directory where data is checked out and the build takes place. The directory will be created if it does not exist.')
args = parser.parse_args()
if not args.work_dir:
print("Please provide a working directory (--work-dir <path>)", file=sys.stderr)
exit(1)
if args.win_code_cert_path:
args.win_code_cert_path = Path(args.win_code_cert_path).resolve()
if args.win_code_key_path:
args.win_code_key_path = Path(args.win_code_key_path).resolve()
work_dir = create_work_dir(args.work_dir)
with cd(work_dir):
print("Using working directory '%s'" % work_dir)
os.environ["PATH"] = str(Path("bin").resolve()) + ":" + os.environ["PATH"]
args.linux = 'l' in args.os
args.windows = 'w' in args.os
args.macos = 'm' in args.os
args.is_bionic = platform.dist() == ('Ubuntu', '18.04', 'bionic')
if args.buildsign:
args.build = True
args.sign = True
if args.kvm and args.docker:
raise Exception('Error: cannot have both kvm and docker')
args.sign_prog = 'true' if args.detach_sign else 'gpg --detach-sign'
# Set environment variable USE_LXC or USE_DOCKER, let gitian-builder know that we use lxc or docker
if args.docker:
os.environ['USE_DOCKER'] = '1'
os.environ['USE_LXC'] = ''
os.environ['USE_VBOX'] = ''
elif not args.kvm:
os.environ['USE_LXC'] = '1'
os.environ['USE_DOCKER'] = ''
os.environ['USE_VBOX'] = ''
if not 'GITIAN_HOST_IP' in os.environ.keys():
os.environ['GITIAN_HOST_IP'] = '10.0.3.1'
if not 'LXC_GUEST_IP' in os.environ.keys():
os.environ['LXC_GUEST_IP'] = '10.0.3.5'
# Disable for MacOS if no SDK found
if args.macos and not Path('gitian-builder/inputs/MacOSX10.11.sdk.tar.gz').is_file():
print('Cannot build for MacOS, SDK does not exist. Will build for other OSes')
args.macos = False
if args.setup:
setup(args)
if not args.build and not args.sign and not args.verify and not args.codesign:
return
if not args.linux and not args.windows and not args.macos:
raise RuntimeError('No platform specified. Exiting.')
script_name = Path(sys.argv[0]).name
# Signer and version shouldn't be empty
if not args.signer:
print(script_name+': Missing signer.')
print('Try '+script_name+' --help for more information')
exit(1)
if not args.version:
print(script_name+': Missing version.')
print('Try '+script_name+' --help for more information')
exit(1)
# Check that path to osslsigncode executable is known
if args.windows and args.codesign:
if not args.setup:
args.osslsigncode_path = find_osslsigncode(args.osslsigncode_path)
if not args.osslsigncode_path:
print('Cannot find osslsigncode. Please provide it with --osslsign or run --setup to make it.', file=sys.stderr)
exit(1)
if not args.win_code_cert_path or not Path(args.win_code_cert_path).is_file():
print('Please provide code signing certificate path (--win-code-cert)', file=sys.stderr)
exit(1)
if not args.win_code_key_path or not Path(args.win_code_key_path).is_file():
print('Please provide code signing key path (--win-code-key)', file=sys.stderr)
exit(1)
# Add leading 'v' for tags
if args.commit and args.pull:
raise Exception('Cannot have both commit and pull')
args.commit = ('' if args.commit else 'v') + args.version
if args.pull and args.skip_checkout:
raise Exception('Cannot pull and skip-checkout at the same time')
prepare_git_dir(args)
prepare_gitian_descriptors(source=args.git_dir + "/contrib/gitian-descriptors/",
target="work/gitian-descriptors", hosts=args.hosts)
if args.build:
build(args)
if args.codesign:
codesign(args)
if args.sign:
sign(args)
if args.verify:
verify(args)
if __name__ == '__main__':
main()
| 50.061798 | 231 | 0.652714 | 1,932 | 0.07227 | 152 | 0.005686 | 168 | 0.006284 | 0 | 0 | 9,579 | 0.358321 |
2ed51113f6af6104ceef30f404b847887714f4ec | 1,239 | py | Python | src/commands/guild_list.py | HugeBrain16/ZenRPG | 9ed83a2696a359dff573583582b724ca7bb920ae | [
"MIT"
] | null | null | null | src/commands/guild_list.py | HugeBrain16/ZenRPG | 9ed83a2696a359dff573583582b724ca7bb920ae | [
"MIT"
] | null | null | null | src/commands/guild_list.py | HugeBrain16/ZenRPG | 9ed83a2696a359dff573583582b724ca7bb920ae | [
"MIT"
] | null | null | null | import discord
from lib import utils
async def _guild_list(page=1):
try:
page = int(page) - 1
except Exception:
await _guild_list.message.channel.send(
":warning: use number to navigate between pages"
)
return
guilds = utils.get_guilds()
pages = [[]]
for guild in guilds:
if len(pages[len(pages) - 1]) == 10:
pages.append([])
if len(pages[len(pages) - 1]) < 10:
fuser = await _guild_list.client.fetch_user(guild["leader"])
pages[len(pages) - 1].append(
f"{guild['id']}). {guild['name']} [leader {fuser.name}#{fuser.discriminator}] [members {guild['members']}]"
)
if (page + 1) > len(pages) or (page + 1) < 1:
await _guild_list.message.channel.send(f":x: Page {page + 1} did not exists")
return
if len(pages[0]) < 1:
await _guild_list.message.channel.send(f":x: No guilds were created")
return
embed = discord.Embed(title="List of Guilds", color=0xFF00FF)
embed.description = "```\n" + "\n".join(pages[page]) + "\n```"
embed.set_author(name=f"Page {page + 1} of {len(pages)}")
await _guild_list.message.channel.send(embed=embed)
| 29.5 | 123 | 0.577885 | 0 | 0 | 0 | 0 | 0 | 0 | 1,198 | 0.966909 | 297 | 0.239709 |
2ed64ffbfe98feb2efc11a0c58fa360ff20cbac1 | 4,184 | py | Python | redshift-dataapi/iac/app.py | InfrastructureHQ/AWS-CDK-Accelerators | a8a3f61040f4419a6c3485c8f4b8df6204a55940 | [
"Apache-2.0"
] | null | null | null | redshift-dataapi/iac/app.py | InfrastructureHQ/AWS-CDK-Accelerators | a8a3f61040f4419a6c3485c8f4b8df6204a55940 | [
"Apache-2.0"
] | null | null | null | redshift-dataapi/iac/app.py | InfrastructureHQ/AWS-CDK-Accelerators | a8a3f61040f4419a6c3485c8f4b8df6204a55940 | [
"Apache-2.0"
] | null | null | null | #
# Copyright (c) 2021, SteelHead Industry Cloud, Inc. <info@steelheadhq.com>.
# All Rights Reserved. *
# #
# Import Core Modules
# For consistency with other languages, `cdk` is the preferred import name for the CDK's core module.
from aws_cdk import core as cdk
from aws_cdk.core import App, Stack, Tags
import os
# Import CICD Stack
from stacks.cicdstack import CICDStack
# Import Stacks
# from stacks.appflowstack import AppFlowStack
from stacks.apistack import APIStack
from stacks.sharedinfrastack import SharedInfraStack
from stacks.lambdastack import LambdaStack
from stacks.eventbridgestack import EventBridgeStack
from stacks.vpcstack import VPCStack
from stacks.redshiftstack import RedshiftStack
# Import Global & Stack Specific Settings
from settings.globalsettings import GlobalSettings
from settings.apistacksettings import APIStackSettings
globalsettings = GlobalSettings()
apistacksettings = APIStackSettings()
# Stack Environment: Region and Account
AWS_ACCOUNT_ID = globalsettings.AWS_ACCOUNT_ID
AWS_REGION = globalsettings.AWS_REGION
OWNER = globalsettings.OWNER
PRODUCT = globalsettings.PRODUCT
PACKAGE = globalsettings.PACKAGE
STAGE = globalsettings.STAGE
app = cdk.App()
# Stack Environment: Region and Account
ENV = {
"region": AWS_REGION,
"account": AWS_ACCOUNT_ID,
}
# ***************** CICD Stack ******************* #
# CICD Stack
cicd_stack = CICDStack(
app,
"{OWNER}-{PRODUCT}-{PACKAGE}-{STACKNAME}-{STAGE}".format(
OWNER=OWNER,
PRODUCT=PRODUCT,
PACKAGE=PACKAGE,
STACKNAME="CICDStack",
STAGE=STAGE,
),
env=ENV,
)
# Add a tag to all constructs in the Stack
Tags.of(cicd_stack).add("Package", PACKAGE)
# ***************** All Other Stack ******************* #
"""
# Shared Infra Stack
sharedinfra_stack = SharedInfraStack(
app,
"{OWNER}-{PRODUCT}-{PACKAGE}-{STACKNAME}-{STAGE}".format(
OWNER=OWNER,
PRODUCT=PRODUCT,
PACKAGE=PACKAGE,
STACKNAME="SharedInfraStack",
STAGE=STAGE,
),
env=ENV,
)
# Add a tag to all constructs in the Stack
Tags.of(sharedinfra_stack).add("Package", PACKAGE)
# Lambda Stack
lambda_stack = LambdaStack(
app,
"{OWNER}-{PRODUCT}-{PACKAGE}-{STACKNAME}-{STAGE}".format(
OWNER=OWNER,
PRODUCT=PRODUCT,
PACKAGE=PACKAGE,
STACKNAME="LambdaStack",
STAGE=STAGE,
),
env=ENV,
)
# Add a tag to all constructs in the Stack
Tags.of(lambda_stack).add("Package", PACKAGE)
# API Stack
api_stack = APIStack(
app,
"{OWNER}-{PRODUCT}-{PACKAGE}-{STACKNAME}-{STAGE}".format(
OWNER=OWNER, PRODUCT=PRODUCT, PACKAGE=PACKAGE, STACKNAME="APIStack", STAGE=STAGE
),
sharedinfra_stack,
lambda_stack,
env=ENV,
)
# Add a tag to all constructs in the Stack
Tags.of(api_stack).add("Package", PACKAGE)
# EventBridge Stack
eventbridge_stack = EventBridgeStack(
app,
"{OWNER}-{PRODUCT}-{PACKAGE}-{STACKNAME}-{STAGE}".format(
OWNER=OWNER,
PRODUCT=PRODUCT,
PACKAGE=PACKAGE,
STACKNAME="EventBridgeStack",
STAGE=STAGE,
),
sharedinfra_stack,
lambda_stack,
env=ENV,
)
# Add a tag to all constructs in the Stack
Tags.of(eventbridge_stack).add("Package", PACKAGE)
# AppFlow Stack
appflow_stack = AppFlowStack(
app,
"{OWNER}-{PRODUCT}-{PACKAGE}-{STACKNAME}-{STAGE}".format(
OWNER=OWNER,
PRODUCT=PRODUCT,
PACKAGE=PACKAGE,
STACKNAME="AppFlowStack",
STAGE=STAGE,
),
env=ENV,
)
# Add a tag to all constructs in the Stack
Tags.of(appflow_stack).add("Package", PACKAGE)
"""
# vpc_stack = VPCStack(
# app,
# "{OWNER}-{PRODUCT}-{PACKAGE}-{STACKNAME}-{STAGE}".format(
# OWNER=OWNER,
# PRODUCT=PRODUCT,
# PACKAGE=PACKAGE,
# STACKNAME="VPCStack",
# STAGE=STAGE,
# ),
# env=ENV,
# )
# redshift_stack = RedshiftStack(
# app,
# "{OWNER}-{PRODUCT}-{PACKAGE}-{STACKNAME}-{STAGE}".format(
# OWNER=OWNER,
# PRODUCT=PRODUCT,
# PACKAGE=PACKAGE,
# STACKNAME="RedshiftStack",
# STAGE=STAGE,
# ),
# env=ENV,
# )
app.synth()
| 24.757396 | 101 | 0.658461 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,051 | 0.729207 |
2ed6729bedf9bfe75446a749ed9fe190a3fd7ac0 | 2,443 | py | Python | chronosoft8puppeteer/gpio.py | mika1337/chronosoft8-puppeteer | b277664005636e159057998e873271653481ec72 | [
"MIT"
] | null | null | null | chronosoft8puppeteer/gpio.py | mika1337/chronosoft8-puppeteer | b277664005636e159057998e873271653481ec72 | [
"MIT"
] | null | null | null | chronosoft8puppeteer/gpio.py | mika1337/chronosoft8-puppeteer | b277664005636e159057998e873271653481ec72 | [
"MIT"
] | null | null | null | # =============================================================================
# System imports
import logging
import RPi.GPIO as RPiGPIO
# =============================================================================
# Logger setup
logger = logging.getLogger(__name__)
# =============================================================================
# Classes
class GPIO:
IN = 0
OUT = 1
_initialized = False
def __init__(self,name,channel,inout,default_value=0,active_high=True,debug=False):
self._name = name
self._channel = channel
self._inout = inout
self._active_high = active_high
self._debug = debug
logger.debug('Initializing GPIO {:<10} channel={} inout={} default={} active_high={} debug={}'
.format( self._name
, self._channel
, "in" if inout == GPIO.IN else "out"
, default_value
, self._active_high
, self._debug ))
if self._debug == False:
if GPIO._initialized == False:
self._initialize()
rpigpio_inout = RPiGPIO.IN if inout == GPIO.IN else RPiGPIO.OUT
initial_state = None
if inout == GPIO.IN:
RPiGPIO.setup( self._channel
, rpigpio_inout )
else:
initial_state = RPiGPIO.LOW
if (self._active_high == True and default_value == 1) or \
(self._active_high == False and default_value == 0):
initial_state = RPiGPIO.HIGH
RPiGPIO.setup( self._channel
, rpigpio_inout
, initial=initial_state)
def __del__(self):
if self._debug == False:
RPiGPIO.cleanup( self._channel )
def _initialize(self):
logger.debug('Initializing RpiGPIO module')
RPiGPIO.setmode(RPiGPIO.BOARD)
GPIO._initialized = True
def set(self,value):
if self._inout == GPIO.IN:
logger.error('Can\'t set input GPIO {}'.format(self._name))
else:
physical_value = value if self._active_high == True else not value
logger.debug('Setting GPIO {:<10} to {} (logical value)'.format(self._name,1 if value else 0))
if self._debug == False:
RPiGPIO.output( self._channel, physical_value )
| 35.926471 | 106 | 0.494883 | 2,079 | 0.851003 | 0 | 0 | 0 | 0 | 0 | 0 | 464 | 0.18993 |
2ed8168234f69683f90dc66c5e63649460c38d3c | 235 | py | Python | eventos/admin.py | JohnVictor2017/StartTm | 91a6f60ffd36f25f01d75798c5ef83e7dc44d97d | [
"MIT"
] | null | null | null | eventos/admin.py | JohnVictor2017/StartTm | 91a6f60ffd36f25f01d75798c5ef83e7dc44d97d | [
"MIT"
] | null | null | null | eventos/admin.py | JohnVictor2017/StartTm | 91a6f60ffd36f25f01d75798c5ef83e7dc44d97d | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import Evento, EventoCategoria, InscricaoSolicitacao
# Register your models here.
admin.site.register(Evento)
admin.site.register(EventoCategoria)
admin.site.register(InscricaoSolicitacao) | 33.571429 | 65 | 0.846809 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | 0.119149 |
2eda2e9ebcd9d63e306693c5ef3298caf6dec8ba | 4,949 | py | Python | indra/benchmarks/assembly_eval/batch4/rasmodel.py | pupster90/indra | e90b0bc1016fc2d210a9b46fb160b78a7d6a5ab9 | [
"BSD-2-Clause"
] | 2 | 2020-01-14T08:59:10.000Z | 2020-12-18T16:21:38.000Z | indra/benchmarks/assembly_eval/batch4/rasmodel.py | pupster90/indra | e90b0bc1016fc2d210a9b46fb160b78a7d6a5ab9 | [
"BSD-2-Clause"
] | null | null | null | indra/benchmarks/assembly_eval/batch4/rasmodel.py | pupster90/indra | e90b0bc1016fc2d210a9b46fb160b78a7d6a5ab9 | [
"BSD-2-Clause"
] | null | null | null | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.statements import *
from indra.preassembler.grounding_mapper import GroundingMapper, \
default_grounding_map
def get_statements():
statements = []
egf = Agent('EGF')
egfr = Agent('EGFR')
st = Complex([egf, egfr])
statements.append(st)
egfre = Agent('EGFR', bound_conditions=[BoundCondition(egf, True)])
egfre = Agent('EGFR', bound_conditions=[BoundCondition(egf, True)])
st = Complex([egfre, egfre])
statements.append(st)
egfrdimer = Agent('EGFR', bound_conditions=[BoundCondition(egfr, True)])
st = Transphosphorylation(egfrdimer, 'Y')
statements.append(st)
egfrpY = Agent('EGFR', mods=[ModCondition('phosphorylation', 'Y')])
grb2 = Agent('GRB2')
st = Complex([egfrpY, grb2])
statements.append(st)
grb2bound = Agent('GRB2', bound_conditions=[BoundCondition(egfr, True)])
sos1 = Agent('SOS1')
st = Complex([grb2bound, sos1])
statements.append(st)
hras = Agent('HRAS')
kras = Agent('KRAS')
nras = Agent('NRAS')
gdp = Agent('GDP')
for ras in [hras, kras, nras]:
st = Complex([ras, gdp])
statements.append(st)
sos1bound = Agent('SOS1', bound_conditions=[BoundCondition(grb2, True)])
hras_gdp = Agent('HRAS', bound_conditions=[BoundCondition(gdp, True)])
kras_gdp = Agent('KRAS', bound_conditions=[BoundCondition(gdp, True)])
nras_gdp = Agent('NRAS', bound_conditions=[BoundCondition(gdp, True)])
for ras_gdp in [hras_gdp, kras_gdp, nras_gdp]:
st = Complex([sos1bound, ras_gdp])
statements.append(st)
st = ActiveForm(ras_gdp, 'activity', False)
statements.append(st)
hras_bound = Agent('HRAS', bound_conditions=[BoundCondition(sos1, True)])
kras_bound = Agent('KRAS', bound_conditions=[BoundCondition(sos1, True)])
nras_bound = Agent('NRAS', bound_conditions=[BoundCondition(sos1, True)])
sos1bound = Agent('SOS1', bound_conditions=[BoundCondition(grb2, True)])
for ras_bound in [hras_bound, kras_bound, nras_bound]:
st = Complex([sos1bound, ras_bound])
statements.append(st)
gtp = Agent('GTP')
hras_gtp = Agent('HRAS', bound_conditions=[BoundCondition(gtp, True)])
kras_gtp = Agent('KRAS', bound_conditions=[BoundCondition(gtp, True)])
nras_gtp = Agent('NRAS', bound_conditions=[BoundCondition(gtp, True)])
braf = Agent('BRAF')
for ras_gtp in [hras_gtp, kras_gtp, nras_gtp]:
st = Complex([ras_gtp, braf])
statements.append(st)
st = ActiveForm(ras_gtp, 'activity', True)
statements.append(st)
hras_braf = Agent('BRAF', bound_conditions=[BoundCondition(hras, True)])
kras_braf = Agent('BRAF', bound_conditions=[BoundCondition(kras, True)])
nras_braf = Agent('BRAF', bound_conditions=[BoundCondition(nras, True)])
for braf1 in [hras_braf, kras_braf, nras_braf]:
for braf2 in [hras_braf, kras_braf, nras_braf]:
st = Complex([braf1, braf2])
statements.append(st)
braf_bound = Agent('BRAF', bound_conditions=[BoundCondition(braf, True)])
st = Transphosphorylation(braf_bound)
statements.append(st)
braf_phos = Agent('BRAF', mods=[ModCondition('phosphorylation')])
mek1 = Agent('MAP2K1')
mek2 = Agent('MAP2K2')
st = ActiveForm(braf_phos, 'kinase', True)
statements.append(st)
st = Phosphorylation(braf_phos, mek1)
statements.append(st)
st = Phosphorylation(braf_phos, mek2)
statements.append(st)
mek1_phos = Agent('MAP2K1', mods=[ModCondition('phosphorylation')])
mek2_phos = Agent('MAP2K2', mods=[ModCondition('phosphorylation')])
mapk1 = Agent('MAPK1')
mapk3 = Agent('MAPK3')
st = ActiveForm(mek1_phos, 'kinase', True)
statements.append(st)
st = ActiveForm(mek2_phos, 'kinase', True)
statements.append(st)
st = Phosphorylation(braf_phos, mek1)
statements.append(st)
st = Phosphorylation(braf_phos, mek2)
statements.append(st)
for mek in [mek1_phos, mek2_phos]:
for erk in [mapk1, mapk3]:
st = Phosphorylation(mek, erk)
for st in statements:
st.belief = 1
st.evidence.append(Evidence(source_api='assertion'))
# Update the statements with grounding info. To do this, we set the "text"
# field of the db_refs to copy from the agent name, then run the grounding
# mapper
for st in statements:
for ag in st.agent_list():
if ag is None:
continue
else:
ag.db_refs = {'TEXT': ag.name}
# Now load the grounding map and run
gm = GroundingMapper(default_grounding_map)
mapped_stmts = gm.map_agents(statements)
# This shouldn't change anything, but just in case...
renamed_stmts = gm.rename_agents(mapped_stmts)
return renamed_stmts
| 37.210526 | 78 | 0.661144 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 609 | 0.123055 |
2edb2059e18b0c410523e3639bf85166c7f4e887 | 263 | py | Python | gdal/swig/python/scripts/gcps2wld.py | Sokigo-GLS/gdal | 595f74bf60dff89fc5df53f9f4c3e40fc835e909 | [
"MIT"
] | null | null | null | gdal/swig/python/scripts/gcps2wld.py | Sokigo-GLS/gdal | 595f74bf60dff89fc5df53f9f4c3e40fc835e909 | [
"MIT"
] | null | null | null | gdal/swig/python/scripts/gcps2wld.py | Sokigo-GLS/gdal | 595f74bf60dff89fc5df53f9f4c3e40fc835e909 | [
"MIT"
] | null | null | null | import sys
# import osgeo.utils.gcps2wld as a convenience to use as a script
from osgeo.utils.gcps2wld import * # noqa
from osgeo.utils.gcps2wld import main
from osgeo.gdal import deprecation_warn
deprecation_warn('gcps2wld', 'utils')
sys.exit(main(sys.argv))
| 26.3 | 65 | 0.787072 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 88 | 0.334601 |
2edb46e51b23c5cc0a15172f8710ba6f0f6689e9 | 139 | py | Python | sort-characters-by-frequency/sort-characters-by-frequency.py | anomius/Leetcode-dump | 641e44c5cc614b2dc9cd01c34b9dcf12e9d16043 | [
"MIT"
] | null | null | null | sort-characters-by-frequency/sort-characters-by-frequency.py | anomius/Leetcode-dump | 641e44c5cc614b2dc9cd01c34b9dcf12e9d16043 | [
"MIT"
] | null | null | null | sort-characters-by-frequency/sort-characters-by-frequency.py | anomius/Leetcode-dump | 641e44c5cc614b2dc9cd01c34b9dcf12e9d16043 | [
"MIT"
] | null | null | null | class Solution:
def frequencySort(self, s: str) -> str:
return reduce(lambda a, b: a + b[1]*b[0], Counter(s).most_common(), '') | 46.333333 | 79 | 0.604317 | 139 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0.014388 |
2edc0159fa249c0dec93294da274e3a53143a4d1 | 2,138 | py | Python | api_tests/principal_claim_test.py | bhatti/saas_rbac | 8debc56a9610f8fef1a323155eb938bfef4fa034 | [
"MIT"
] | 5 | 2019-12-20T19:52:50.000Z | 2021-08-03T11:03:18.000Z | api_tests/principal_claim_test.py | bhatti/saas_rbac | 8debc56a9610f8fef1a323155eb938bfef4fa034 | [
"MIT"
] | null | null | null | api_tests/principal_claim_test.py | bhatti/saas_rbac | 8debc56a9610f8fef1a323155eb938bfef4fa034 | [
"MIT"
] | 2 | 2020-03-30T17:00:36.000Z | 2021-06-17T05:59:01.000Z | import unittest
import base_test
import json
class PrincipalClaimTest(base_test.BaseTest):
def setUp(self):
super(PrincipalClaimTest, self).setUp()
self._org = self.post('/api/orgs', {"name":"claim_org", "url":"https://myorg.com"})
self._principal = self.post('/api/orgs/%s/principals' % self._org["id"], {"username":"my_principal", "organization_id":self._org["id"]})
self._realm = self.post('/api/realms', {"id":"resource_realm"})
self._license = self.post('/api/orgs/%s/licenses' % self._org["id"], {"name":"my_license", "organization_id":self._org["id"], "effective_at": "2019-01-01T00:00:00", "expired_at": "2030-01-01T00:00:00"})
self._resource = self.post('/api/realms/%s/resources' % self._realm["id"], {"resource_name":"my_resource", "realm_id":self._realm["id"]})
def tearDown(self):
self.delete('/api/realms/%s/resources/%s/claims/%s' % (self._realm["id"], self._resource["id"], self._claim["id"]))
self.delete('/api/orgs/%s/licenses/%s' % (self._org["id"], self._license["id"]))
self.delete('/api/realms/%s/resources/%s' % (self._realm["id"], self._resource["id"]))
self.delete('/api/realms/%s' % self._realm["id"])
self.delete('/api/orgs/%s' % self._org["id"])
self.delete('/api/orgs/%s/principals/%s' % (self._org["id"], self._principal["id"]))
def test_add_remove_claim_to_principal(self):
self._claim = self.post('/api/realms/%s/resources/%s/claims' % (self._realm["id"], self._resource["id"]), {"action":"READ", "realm_id":self._realm["id"]})
self.assertEquals("READ", self._claim["action"])
#
resp = self.put('/api/realms/%s/resources/%s/claims/%s/principals/%s' % (self._realm["id"], self._resource["id"], self._claim["id"], self._principal["id"]), {})
self.assertEquals(1, resp, json.dumps(resp))
resp = self.delete('/api/realms/%s/resources/%s/claims/%s/principals/%s' % (self._realm["id"], self._resource["id"], self._claim["id"], self._principal["id"]))
self.assertEquals(1, resp, json.dumps(resp))
if __name__ == '__main__':
unittest.main()
| 62.882353 | 210 | 0.630028 | 2,043 | 0.955566 | 0 | 0 | 0 | 0 | 0 | 0 | 796 | 0.372311 |
2edf86c413814d5ad4dd994b2501c494657290bc | 510 | py | Python | examples/standalone/simple_case_build.py | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | 1 | 2021-06-10T15:28:51.000Z | 2021-06-10T15:28:51.000Z | examples/standalone/simple_case_build.py | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | null | null | null | examples/standalone/simple_case_build.py | awillats/brian2 | e1107ed0cc4a7d6c69c1e2634b675ba09edfd9fc | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/env python
'''
The most simple case how to use standalone mode with several `run` calls.
'''
from brian2 import *
set_device('cpp_standalone', build_on_run=False)
tau = 10*ms
I = 1 # input current
eqs = '''
dv/dt = (I-v)/tau : 1
'''
G = NeuronGroup(10, eqs, method='exact')
G.v = 'rand()'
mon = StateMonitor(G, 'v', record=True)
run(20*ms)
I = 0
run(80*ms)
# Actually generate/compile/run the code:
device.build()
plt.plot(mon.t/ms, mon.v.T)
plt.gca().set(xlabel='t (ms)', ylabel='v')
plt.show()
| 20.4 | 73 | 0.656863 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 232 | 0.454902 |
2ee031ceef9afeeee26f7964687ce928e931a2a2 | 801 | py | Python | 01-python-fundamentals.py | reysmerwvr/python-playgrounds | 1e039639d96044986ba5cc894a210180cc2b08e0 | [
"MIT"
] | null | null | null | 01-python-fundamentals.py | reysmerwvr/python-playgrounds | 1e039639d96044986ba5cc894a210180cc2b08e0 | [
"MIT"
] | null | null | null | 01-python-fundamentals.py | reysmerwvr/python-playgrounds | 1e039639d96044986ba5cc894a210180cc2b08e0 | [
"MIT"
] | null | null | null | # What should be printing the next snippet of code?
intNum = 10
negativeNum = -5
testString = "Hello "
testList = [1, 2, 3]
print(intNum * 5)
print(intNum - negativeNum)
print(testString + 'World')
print(testString * 2)
print(testString[-1])
print(testString[1:])
print(testList + testList)
# The sum of each three first numbers of each list should be resulted in the last element of each list
matrix = [
[1, 1, 1, 3],
[2, 2, 2, 7],
[3, 3, 3, 9],
[4, 4, 4, 13]
]
matrix[1][-1] = sum(matrix[1][:-1])
matrix[-1][-1] = sum(matrix[-1][:-1])
print(matrix)
# Reverse string str[::-1]
testString = "eoD hnoJ,01"
testString = testString[::-1]
print(testString)
n = 0
while n < 10:
if (n % 2) == 0:
print(n, 'even number')
else:
print(n, 'odd number')
n = n + 1
| 21.078947 | 102 | 0.60799 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 232 | 0.289638 |
2ee1f5707dc3b138efdc660027411aa4640b57d7 | 801 | py | Python | cdchanger/urls.py | mnosinov/cdchanger | 7dc4db3849e135c813d4a46287bdb7cb8b1547d6 | [
"MIT"
] | null | null | null | cdchanger/urls.py | mnosinov/cdchanger | 7dc4db3849e135c813d4a46287bdb7cb8b1547d6 | [
"MIT"
] | null | null | null | cdchanger/urls.py | mnosinov/cdchanger | 7dc4db3849e135c813d4a46287bdb7cb8b1547d6 | [
"MIT"
] | null | null | null | from django.urls import path
from django.views.generic import TemplateView
from .views import CdchangerListView, CdchangerWizard
urlpatterns = [
path('', TemplateView.as_view(template_name='cdchanger/index.html'), name='index'),
path('cdchangers', CdchangerListView.as_view(), name='cdchangers'),
path('cdchangers/', CdchangerListView.as_view(), name='cdchangers'),
path('cdchangers/create', CdchangerWizard.as_view(CdchangerWizard.FORMS), name='cdchanger-create-wizard'),
# TODO
# path('cdchangers/<int:pk>/view', CdchangerDetailView.as_view(), name='cdchanger-detail-view'),
# path('cdchangers/<int:pk>/update', CdchangerUpdateView.as_view(), name='cdchanger-update'),
# path('cdchangers/<int:pk>/delete', CdchangerDeleteView.as_view(), name='cdchanger-delete'),
]
| 50.0625 | 110 | 0.739076 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 412 | 0.514357 |
2ee23bd27e64239ca72b8aa33e58b21e0f9b9dca | 9,255 | py | Python | src/genomic_benchmarks/loc2seq/with_biopython.py | Shirapti-nath/genomic_benchmarks | 293cb55c645aac1cca8fb349a36fa530cf59276a | [
"Apache-2.0"
] | null | null | null | src/genomic_benchmarks/loc2seq/with_biopython.py | Shirapti-nath/genomic_benchmarks | 293cb55c645aac1cca8fb349a36fa530cf59276a | [
"Apache-2.0"
] | null | null | null | src/genomic_benchmarks/loc2seq/with_biopython.py | Shirapti-nath/genomic_benchmarks | 293cb55c645aac1cca8fb349a36fa530cf59276a | [
"Apache-2.0"
] | null | null | null | import pandas as pd
import yaml
import gzip
import re
import urllib
import shutil # for removing and creating folders
from pathlib import Path
from tqdm.autonotebook import tqdm
import warnings
from Bio import SeqIO
from Bio.Seq import Seq
from .cloud_caching import CLOUD_CACHE, download_from_cloud_cache
CACHE_PATH = Path.home() / '.genomic_benchmarks'
REF_CACHE_PATH = CACHE_PATH / 'fasta'
DATASET_DIR_PATH = (Path(__file__).parents[0] / '..' / '..' / '..' / 'datasets').resolve()
def download_dataset(interval_list_dataset, version=None, dest_path=CACHE_PATH, cache_path=REF_CACHE_PATH,
force_download=False, use_cloud_cache=True):
'''
Transform an interval-list genomic dataset into a full-seq genomic dataset.
Parameters:
interval_list_dataset (str or Path): Either a path or a name of dataset included in this package.
version (int): Version of the dataset.
dest_path (str or Path): Folder to store the full-seq dataset.
cache_path (str or Path): Folder to store the downloaded references.
force_download (bool): If True, force downloading of references.
use_cloud_cache (bool): If True, use the cloud cache for downloading a full-seq genomic datasets.
Returns:
seq_dataset_path (Path): Path to the full-seq dataset.
'''
interval_list_dataset = _guess_location(interval_list_dataset)
metadata = _check_dataset_existence(interval_list_dataset, version)
dataset_name = _get_dataset_name(interval_list_dataset)
if version is None:
version = metadata['version']
if use_cloud_cache and ((dataset_name, version) in CLOUD_CACHE):
Path(dest_path).mkdir(parents=True, exist_ok=True) # to be sure "./.genomic_benchmarks" exists
return download_from_cloud_cache((dataset_name, version), Path(dest_path) / dataset_name)
refs = _download_references(metadata, cache_path=cache_path, force=force_download)
fastas = _load_fastas_into_memory(refs, cache_path=cache_path)
_remove_and_create(Path(dest_path) / dataset_name)
_remove_and_create(Path(dest_path) / dataset_name / "train")
_remove_and_create(Path(dest_path) / dataset_name / "test")
for c in metadata['classes']:
for t in ['train', 'test']:
dt_filename = Path(interval_list_dataset) / t / (c + '.csv.gz')
dt = pd.read_csv(dt_filename, compression="gzip")
ref_name = _get_reference_name(metadata['classes'][c]['url'])
dt['seq'] = _fill_seq_column(fastas[ref_name], dt)
folder_filename = Path(dest_path) / dataset_name / t / c
_remove_and_create(folder_filename)
for row in dt.iterrows():
row_filename = folder_filename / (str(row[1]['id']) + '.txt')
row_filename.write_text(row[1]['seq'])
return Path(dest_path) / dataset_name
def _guess_location(dataset_path):
if Path(dataset_path).exists():
return Path(dataset_path)
elif (DATASET_DIR_PATH / str(dataset_path)).exists():
return DATASET_DIR_PATH / str(dataset_path)
else:
raise FileNotFoundError(f'Dataset {dataset_path} not found.')
def _check_dataset_existence(interval_list_dataset, version):
# check that the dataset exists, returns its metadata
path = Path(interval_list_dataset)
if not path.exists():
raise FileNotFoundError(f'Dataset {interval_list_dataset} not found.')
metadata_path = path / 'metadata.yaml'
if not metadata_path.exists():
raise FileNotFoundError(f'Dataset {interval_list_dataset} does not contain `metadata.yaml` file.')
with open(metadata_path, "r") as fr:
metadata = yaml.safe_load(fr)
if version is not None:
if version != metadata['version']:
raise ValueError(f"Dataset version {version} does not match the version in metadata {metadata['version']}.")
else:
warnings.warn(f"No version specified. Using version {metadata['version']}.")
return metadata
def _get_dataset_name(path):
# get the dataset name from the path
return Path(path).stem
def _download_references(metadata, cache_path, force=False):
# download all references from the metadata into cache_path folder
cache_path = Path(cache_path)
if not cache_path.exists():
cache_path.mkdir(parents=True)
refs = {(c['url'], c['type'], c.get('extra_processing')) for c in metadata['classes'].values()}
for ref in refs:
ref_path = cache_path / _get_reference_name(ref[0])
if not ref_path.exists() or force:
_download_url(ref[0], ref_path)
else:
print(f'Reference {ref_path} already exists. Skipping.')
return refs
def _get_reference_name(url):
# get the reference name from the url
### TODO: better naming scheme (e.g. taking the same file from 2 Ensembl releases)
return url.split('/')[-1]
def _download_url(url, dest):
# download a file from url to dest
if Path(dest).exists():
Path(dest).unlink()
print(f"Downloading {url}")
class DownloadProgressBar(tqdm):
# for progress bar
def update_to(self, b=1, bsize=1, tsize=None):
if tsize is not None:
self.total = tsize
self.update(b * bsize - self.n)
with DownloadProgressBar(unit='B', unit_scale=True,
miniters=1, desc=str(dest)) as t:
# TODO: adapt fastdownload code instead of urllib
urllib.request.urlretrieve(url, filename=dest, reporthook=t.update_to)
EXTRA_PREPROCESSING = {
# known extra preprocessing steps
'default': [None, None, lambda x: x],
'ENSEMBL_HUMAN_GENOME': [24, 'MT', lambda x: "chr"+x], # use only chromosomes, not contigs, and add chr prefix
'ENSEMBL_MOUSE_GENOME': [21, 'MT', lambda x: "chr"+x], # use only chromosomes, not contigs, and add chr prefix
'ENSEMBL_HUMAN_TRANSCRIPTOME': [190_000, None, lambda x: re.sub("ENST([0-9]*)[.][0-9]*", "ENST\\1", x)] # remove the version number from the ensembl id
}
def _load_fastas_into_memory(refs, cache_path):
# load all references into memory
fastas = {}
for ref in refs:
ref_path = Path(cache_path) / _get_reference_name(ref[0])
ref_type = ref[1]
ref_extra_preprocessing = ref[2] if ref[2] is not None else "default"
if ref_extra_preprocessing not in EXTRA_PREPROCESSING:
raise ValueError(f"Unknown extra preprocessing: {ref_extra_preprocessing}")
if ref_type == 'fa.gz':
fasta = _fastagz2dict(ref_path, fasta_total=EXTRA_PREPROCESSING[ref_extra_preprocessing][0],
stop_id=EXTRA_PREPROCESSING[ref_extra_preprocessing][1],
region_name_transform=EXTRA_PREPROCESSING[ref_extra_preprocessing][2])
fastas[_get_reference_name(ref[0])] = fasta
else:
raise ValueError(f'Unknown reference type {ref_type}')
return fastas
def _fastagz2dict(fasta_path, fasta_total=None, stop_id=None, region_name_transform=lambda x: x):
# load gzipped fasta into dictionary
fasta = {}
with gzip.open(fasta_path, "rt") as handle:
for record in tqdm(SeqIO.parse(handle, "fasta"), total=fasta_total):
fasta[region_name_transform(record.id)] = str(record.seq)
if stop_id and (record.id == stop_id):
# stop, do not read small contigs
break
return fasta
def _fill_seq_column(fasta, df):
# fill seq column in DataFrame tab
if not all([r in fasta for r in df['region']]):
missing_regions = list({r for r in df['region'] if r not in fasta})
if len(missing_regions) > 5: missing_regions = missing_regions[:6]
raise ValueError('Some regions not found in the reference, e.g. ' + " ".join([str(r) for r in missing_regions]))
output = pd.Series([_rev(fasta[region][start:end], strand) for region, start, end, strand in zip(df['region'], df['start'], df['end'], df['strand'])])
return output
def _rev(seq, strand):
# reverse complement
if strand == '-':
return str(Seq(seq).reverse_complement())
else:
return seq
def _remove_and_create(path):
# cleaning step: remove the folder and then create it again
if path.exists():
shutil.rmtree(path)
path.mkdir(parents=True)
def remove_dataset_from_disk(interval_list_dataset, version=None, dest_path=CACHE_PATH):
'''
Remove the full-seq dataset from the disk.
Parameters:
interval_list_dataset (str or Path): Either a path or a name of dataset included in this package.
version (int): Version of the dataset.
dest_path (str or Path): Folder to store the full-seq dataset.
'''
interval_list_dataset = _guess_location(interval_list_dataset)
metadata = _check_dataset_existence(interval_list_dataset, version)
dataset_name = _get_dataset_name(interval_list_dataset)
path = Path(dest_path) / dataset_name
if path.exists():
shutil.rmtree(path) | 41.877828 | 156 | 0.663857 | 227 | 0.024527 | 0 | 0 | 0 | 0 | 0 | 0 | 2,904 | 0.313776 |
2ee562e1b0d873d6a89174fee384867b26eb8eb9 | 851 | py | Python | main.py | Forcide/ApacheParser | 0f82e8d7d696f1c2e17be4975e6836e435a9ab1a | [
"MIT"
] | null | null | null | main.py | Forcide/ApacheParser | 0f82e8d7d696f1c2e17be4975e6836e435a9ab1a | [
"MIT"
] | null | null | null | main.py | Forcide/ApacheParser | 0f82e8d7d696f1c2e17be4975e6836e435a9ab1a | [
"MIT"
] | null | null | null | from modules import menu, hosts, logMail, status, webpagina, zoekInLog
def main():
""""
Dit is de start file/functie van het programma, hierin worden alle modules geladen en zo nodig uitgevoerd.
Het menu wordt gestart en de keuze wordt verwezen naar een van de modules.
Geimporteerde modules:
- menu
- hosts
- logMail
- status
- webpagina
- zoekInLog
"""
keuze = menu.menu()
if keuze == 1:
logMail.logMail()
elif keuze == 2:
webpagina.bezochteWebpagina()
elif keuze == 3:
hosts.uniekeHosts()
elif keuze == 4:
status.aantalStatus()
elif keuze == 5:
zoekInLog.zoekInLog()
elif keuze == 6:
exit()
hoofdmenu = menu.menuAfsluiten()
if hoofdmenu == 'J':
main()
elif hoofdmenu == 'N':
exit()
main()
| 19.340909 | 110 | 0.589894 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 317 | 0.372503 |
2ee6a54ae75caf325e2b975f0980d27b34405153 | 15,329 | py | Python | Chapter09/cifar_10_revisted_transfer_learning.py | PacktPublishing/Deep-Learning-By-Example | 2755f92fad19c54ee15ad858ca20e8e64f58cc00 | [
"MIT"
] | 27 | 2018-02-28T04:56:07.000Z | 2021-11-08T13:12:44.000Z | Chapter09/cifar_10_revisted_transfer_learning.py | PacktPublishing/Deep-Learning-By-Example | 2755f92fad19c54ee15ad858ca20e8e64f58cc00 | [
"MIT"
] | 1 | 2018-04-10T21:26:45.000Z | 2018-04-10T21:26:45.000Z | Chapter09/cifar_10_revisted_transfer_learning.py | PacktPublishing/Deep-Learning-By-Example | 2755f92fad19c54ee15ad858ca20e8e64f58cc00 | [
"MIT"
] | 16 | 2018-03-07T01:14:14.000Z | 2022-01-12T02:11:27.000Z | import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import time
from datetime import timedelta
import os
# Importing a helper module for the functions of the Inception model.
import inception
import cifar10
from cifar10 import num_classes
from inception import transfer_values_cache
#Importing the color map for plotting each class with different color.
import matplotlib.cm as color_map
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.metrics import confusion_matrix
cifar10.data_path = "data/CIFAR-10/"
cifar10.maybe_download_and_extract()
class_names = cifar10.load_class_names()
print(class_names)
print('Loading the training set...')
training_images, training_cls_integers, trainig_one_hot_labels = cifar10.load_training_data()
print('Loading the test set...')
testing_images, testing_cls_integers, testing_one_hot_labels = cifar10.load_test_data()
print("-Number of images in the training set:\t\t{}".format(len(training_images)))
print("-Number of images in the testing set:\t\t{}".format(len(testing_images)))
def plot_imgs(imgs, true_class, predicted_class=None):
assert len(imgs) == len(true_class)
# Creating a placeholders for 9 subplots
fig, axes = plt.subplots(3, 3)
# Adjustting spacing.
if predicted_class is None:
hspace = 0.3
else:
hspace = 0.6
fig.subplots_adjust(hspace=hspace, wspace=0.3)
for i, ax in enumerate(axes.flat):
# There may be less than 9 images, ensure it doesn't crash.
if i < len(imgs):
# Plot image.
ax.imshow(imgs[i],
interpolation='nearest')
# Get the actual name of the true class from the class_names array
true_class_name = class_names[true_class[i]]
# Showing labels for the predicted and true classes
if predicted_class is None:
xlabel = "True: {0}".format(true_class_name)
else:
# Name of the predicted class.
predicted_class_name = class_names[predicted_class[i]]
xlabel = "True: {0}\nPred: {1}".format(true_class_name, predicted_class_name)
ax.set_xlabel(xlabel)
# Remove ticks from the plot.
ax.set_xticks([])
ax.set_yticks([])
plt.show()
# get the first 9 images in the test set
imgs = testing_images[0:9]
# Get the integer representation of the true class.
true_class = testing_cls_integers[0:9]
# Plotting the images
plot_imgs(imgs=imgs, true_class=true_class)
print('Downloading the pretrained inception v3 model')
inception.maybe_download()
# Loading the inception model so that we can inialized it with the pretrained weights and customize for our model
inception_model = inception.Inception()
file_path_train = os.path.join(cifar10.data_path, 'inception_cifar10_train.pkl')
file_path_test = os.path.join(cifar10.data_path, 'inception_cifar10_test.pkl')
print("Processing Inception transfer-values for the training images of Cifar-10 ...")
# First we need to scale the imgs to fit the Inception model requirements as it requires all pixels to be from 0 to 255,
# while our training examples of the CIFAR-10 pixels are between 0.0 and 1.0
imgs_scaled = training_images * 255.0
# Checking if the transfer-values for our training images are already calculated and loading them, if not calcaulate and save them.
transfer_values_training = transfer_values_cache(cache_path=file_path_train,
images=imgs_scaled,
model=inception_model)
print("Processing Inception transfer-values for the testing images of Cifar-10 ...")
# First we need to scale the imgs to fit the Inception model requirements as it requires all pixels to be from 0 to 255,
# while our training examples of the CIFAR-10 pixels are between 0.0 and 1.0
imgs_scaled = testing_images * 255.0
# Checking if the transfer-values for our training images are already calculated and loading them, if not calcaulate and save them.
transfer_values_testing = transfer_values_cache(cache_path=file_path_test,
images=imgs_scaled,
model=inception_model)
print('Shape of the training set transfer values...')
print(transfer_values_training.shape)
print('Shape of the testing set transfer values...')
print(transfer_values_testing.shape)
def plot_transferValues(ind):
print("Original input image:")
# Plot the image at index ind of the test set.
plt.imshow(testing_images[ind], interpolation='nearest')
plt.show()
print("Transfer values using Inception model:")
# Visualize the transfer values as an image.
transferValues_img = transfer_values_testing[ind]
transferValues_img = transferValues_img.reshape((32, 64))
# Plotting the transfer values image.
plt.imshow(transferValues_img, interpolation='nearest', cmap='Reds')
plt.show()
plot_transferValues(ind=15)
pca_obj = PCA(n_components=2)
subset_transferValues = transfer_values_training[0:3000]
cls_integers = testing_cls_integers[0:3000]
print('Shape of a subset form the transfer values...')
print(subset_transferValues.shape)
reduced_transferValues = pca_obj.fit_transform(subset_transferValues)
print('Shape of the reduced version of the transfer values...')
print(reduced_transferValues.shape)
def plot_reduced_transferValues(transferValues, cls_integers):
# Create a color-map with a different color for each class.
c_map = color_map.rainbow(np.linspace(0.0, 1.0, num_classes))
# Getting the color for each sample.
colors = c_map[cls_integers]
# Getting the x and y values.
x_val = transferValues[:, 0]
y_val = transferValues[:, 1]
# Plot the transfer values in a scatter plot
plt.scatter(x_val, y_val, color=colors)
plt.show()
plot_reduced_transferValues(reduced_transferValues, cls_integers)
pca_obj = PCA(n_components=50)
transferValues_50d = pca_obj.fit_transform(subset_transferValues)
tsne_obj = TSNE(n_components=2)
reduced_transferValues = tsne_obj.fit_transform(transferValues_50d)
print('Shape of the reduced version of the transfer values using t-SNE method...')
print(reduced_transferValues.shape)
plot_reduced_transferValues(reduced_transferValues, cls_integers)
transferValues_arrLength = inception_model.transfer_len
input_values = tf.placeholder(tf.float32, shape=[None, transferValues_arrLength], name='input_values')
y_actual = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_actual')
y_actual_cls = tf.argmax(y_actual, axis=1)
def new_weights(shape):
return tf.Variable(tf.truncated_normal(shape, stddev=0.05))
def new_biases(length):
return tf.Variable(tf.constant(0.05, shape=[length]))
def new_fc_layer(input, # The previous layer.
num_inputs, # Num. inputs from prev. layer.
num_outputs, # Num. outputs.
use_relu=True): # Use Rectified Linear Unit (ReLU)?
# Create new weights and biases.
weights = new_weights(shape=[num_inputs, num_outputs])
biases = new_biases(length=num_outputs)
# Calculate the layer as the matrix multiplication of
# the input and weights, and then add the bias-values.
layer = tf.matmul(input, weights) + biases
# Use ReLU?
if use_relu:
layer = tf.nn.relu(layer)
return layer
# First fully-connected layer.
layer_fc1 = new_fc_layer(input=input_values,
num_inputs=2048,
num_outputs=1024,
use_relu=True)
# Second fully-connected layer.
layer_fc2 = new_fc_layer(input=layer_fc1,
num_inputs=1024,
num_outputs=num_classes,
use_relu=False)
# Predicted class-label.
y_predicted = tf.nn.softmax(layer_fc2)
# Cross-entropy for the classification of each image.
cross_entropy = \
tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2,
labels=y_actual)
# Loss aka. cost-measure.
# This is the scalar value that must be minimized.
loss = tf.reduce_mean(cross_entropy)
step = tf.Variable(initial_value=0,
name='step', trainable=False)
optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(loss, step)
y_predicted_cls = tf.argmax(y_predicted, axis=1)
correct_prediction = tf.equal(y_predicted_cls, y_actual_cls)
model_accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
session = tf.Session()
session.run(tf.global_variables_initializer())
training_batch_size = 32
def select_random_batch():
# Number of images (transfer-values) in the training-set.
num_imgs = len(transfer_values_training)
# Create a random index.
ind = np.random.choice(num_imgs,
size=training_batch_size,
replace=False)
# Use the random index to select random x and y-values.
# We use the transfer-values instead of images as x-values.
x_batch = transfer_values_training[ind]
y_batch = trainig_one_hot_labels[ind]
return x_batch, y_batch
def optimize(num_iterations):
for i in range(num_iterations):
# Selectin a random batch of images for training
# where the transfer values of the images will be stored in input_batch
# and the actual labels of those batch of images will be stored in y_actual_batch
input_batch, y_actual_batch = select_random_batch()
# storing the batch in a dict with the proper names
# such as the input placeholder variables that we define above.
feed_dict = {input_values: input_batch,
y_actual: y_actual_batch}
# Now we call the optimizer of this batch of images
# TensorFlow will automatically feed the values of the dict we created above
# to the model input placeholder variables that we defined above.
i_global, _ = session.run([step, optimizer],
feed_dict=feed_dict)
# print the accuracy every 100 steps.
if (i_global % 100 == 0) or (i == num_iterations - 1):
# Calculate the accuracy on the training-batch.
batch_accuracy = session.run(model_accuracy,
feed_dict=feed_dict)
msg = "Step: {0:>6}, Training Accuracy: {1:>6.1%}"
print(msg.format(i_global, batch_accuracy))
def plot_errors(cls_predicted, cls_correct):
# cls_predicted is an array of the predicted class-number for
# all images in the test-set.
# cls_correct is an array with boolean values to indicate
# whether is the model predicted the correct class or not.
# Negate the boolean array.
incorrect = (cls_correct == False)
# Get the images from the test-set that have been
# incorrectly classified.
incorrectly_classified_images = testing_images[incorrect]
# Get the predicted classes for those images.
cls_predicted = cls_predicted[incorrect]
# Get the true classes for those images.
true_class = testing_cls_integers[incorrect]
n = min(9, len(incorrectly_classified_images))
# Plot the first n images.
plot_imgs(imgs=incorrectly_classified_images[0:n],
true_class=true_class[0:n],
predicted_class=cls_predicted[0:n])
def plot_confusionMatrix(cls_predicted):
# cls_predicted array of all the predicted
# classes numbers in the test.
# Call the confucion matrix of sklearn
cm = confusion_matrix(y_true=testing_cls_integers,
y_pred=cls_predicted)
# Printing the confusion matrix
for i in range(num_classes):
# Append the class-name to each line.
class_name = "({}) {}".format(i, class_names[i])
print(cm[i, :], class_name)
# labeling each column of the confusion matrix with the class number
cls_numbers = [" ({0})".format(i) for i in range(num_classes)]
print("".join(cls_numbers))
# Split the data-set in batches of this size to limit RAM usage.
batch_size = 128
def predict_class(transferValues, labels, cls_true):
# Number of images.
num_imgs = len(transferValues)
# Allocate an array for the predicted classes which
# will be calculated in batches and filled into this array.
cls_predicted = np.zeros(shape=num_imgs, dtype=np.int)
# Now calculate the predicted classes for the batches.
# We will just iterate through all the batches.
# There might be a more clever and Pythonic way of doing this.
# The starting index for the next batch is denoted i.
i = 0
while i < num_imgs:
# The ending index for the next batch is denoted j.
j = min(i + batch_size, num_imgs)
# Create a feed-dict with the images and labels
# between index i and j.
feed_dict = {input_values: transferValues[i:j],
y_actual: labels[i:j]}
# Calculate the predicted class using TensorFlow.
cls_predicted[i:j] = session.run(y_predicted_cls, feed_dict=feed_dict)
# Set the start-index for the next batch to the
# end-index of the current batch.
i = j
# Create a boolean array whether each image is correctly classified.
correct = [a == p for a, p in zip(cls_true, cls_predicted)]
print(type(correct))
return correct, cls_predicted
def predict_class_test():
return predict_class(transferValues = transfer_values_testing,
labels = trainig_one_hot_labels,
cls_true = training_cls_integers)
def classification_accuracy(correct):
# When averaging a boolean array, False means 0 and True means 1.
# So we are calculating: number of True / len(correct) which is
# the same as the classification accuracy.
# Return the classification accuracy
# and the number of correct classifications.
return np.mean(correct), np.sum(correct)
def test_accuracy(show_example_errors=False,
show_confusion_matrix=False):
# For all the images in the test-set,
# calculate the predicted classes and whether they are correct.
correct, cls_pred = predict_class_test()
print(type(correct))
# Classification accuracypredict_class_test and the number of correct classifications.
accuracy, num_correct = classification_accuracy(correct)
# Number of images being classified.
num_images = len(correct)
# Print the accuracy.
msg = "Test set accuracy: {0:.1%} ({1} / {2})"
print(msg.format(accuracy, num_correct, num_images))
# Plot some examples of mis-classifications, if desired.
if show_example_errors:
print("Example errors:")
plot_errors(cls_predicted=cls_pred, cls_correct=correct)
# Plot the confusion matrix, if desired.
if show_confusion_matrix:
print("Confusion Matrix:")
plot_confusionMatrix(cls_predicted=cls_pred)
test_accuracy(show_example_errors=True,
show_confusion_matrix=True)
optimize(num_iterations=1000)
test_accuracy(show_example_errors=True,
show_confusion_matrix=True) | 34.447191 | 131 | 0.694109 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5,839 | 0.380912 |
2ee7379d9c15a586379addc309fdbb786e13adc1 | 2,276 | py | Python | posts/api/views.py | kasper190/SPAforum | 4d26c9d7b62ce84540100ca7f6b1b2aaa4fb57bd | [
"MIT"
] | null | null | null | posts/api/views.py | kasper190/SPAforum | 4d26c9d7b62ce84540100ca7f6b1b2aaa4fb57bd | [
"MIT"
] | null | null | null | posts/api/views.py | kasper190/SPAforum | 4d26c9d7b62ce84540100ca7f6b1b2aaa4fb57bd | [
"MIT"
] | null | null | null | from rest_framework.exceptions import NotFound, PermissionDenied
from rest_framework.generics import (
CreateAPIView,
DestroyAPIView,
RetrieveUpdateAPIView,
)
from .permissions import (
IsAdminOrModeratorOrReadOnly,
IsOwnerOrAdminOrModeratorOrReadOnly,
IsOwnerOrReadOnly,
)
from .serializers import (
NoteSerializer,
NoteCreateUpdateSerializer,
PostCreateSerializer,
PostUpdateSerializer,
PostListSerializer,
)
from posts.models import (
Note,
Post,
)
class NoteCreateAPIView(CreateAPIView):
queryset = Note.objects.all()
serializer_class = NoteCreateUpdateSerializer
def perform_create(self, serializer):
post_id = self.request.data['post']
user_id = self.request.user.id
is_admin = self.request.user.is_staff
if serializer.is_valid(raise_exception=True):
is_moderator = Post.objects.filter(
id = post_id,
thread__subforum__moderators = user_id
).exists()
if not (is_admin or is_moderator):
raise PermissionDenied(detail='You do not have permission to perform this action.')
serializer.save(user=self.request.user)
class NoteUpdateAPIView(RetrieveUpdateAPIView):
queryset = Note.objects.all()
serializer_class = NoteCreateUpdateSerializer
permission_classes = (IsAdminOrModeratorOrReadOnly, IsOwnerOrReadOnly)
def perform_update(self, serializer):
serializer.save(user=self.request.user)
class NoteDeleteAPIView(DestroyAPIView):
queryset = Note.objects.all()
serializer_class = NoteSerializer
permission_classes = (IsAdminOrModeratorOrReadOnly, IsOwnerOrReadOnly)
class PostCreateAPIView(CreateAPIView):
queryset = Post.objects.all()
serializer_class = PostCreateSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class PostUpdateAPIView(RetrieveUpdateAPIView):
queryset = Post.objects.all()
serializer_class = PostUpdateSerializer
permission_classes = (IsOwnerOrAdminOrModeratorOrReadOnly,)
class PostDeleteAPIView(DestroyAPIView):
queryset = Post.objects.all()
serializer_class = PostListSerializer
permission_classes = (IsAdminOrModeratorOrReadOnly,) | 30.346667 | 99 | 0.737258 | 1,755 | 0.77109 | 0 | 0 | 0 | 0 | 0 | 0 | 58 | 0.025483 |
2ee7856345c9fb44d682f93c6f98e331db8127ea | 270 | py | Python | app/questionnaire_state/state_section.py | qateam123/eq | 704757952323647d659c49a71975c56406ff4047 | [
"MIT"
] | null | null | null | app/questionnaire_state/state_section.py | qateam123/eq | 704757952323647d659c49a71975c56406ff4047 | [
"MIT"
] | 8 | 2020-03-24T15:24:18.000Z | 2022-03-02T04:32:56.000Z | app/questionnaire_state/state_section.py | qateam123/eq | 704757952323647d659c49a71975c56406ff4047 | [
"MIT"
] | null | null | null | from app.questionnaire_state.state_item import StateItem
class StateSection(StateItem):
def __init__(self, item_id, schema_item):
super().__init__(item_id=item_id, schema_item=schema_item)
self.questions = []
self.children = self.questions
| 30 | 66 | 0.72963 | 210 | 0.777778 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2ee8096164e1adc4d2f9118ff7c8dcfcb8620047 | 8,046 | py | Python | examples/visualize.py | Jallet/keras-jl-ac-mean | 2bbc1596192fb8c3aefc4a8126482a5283574a59 | [
"MIT"
] | null | null | null | examples/visualize.py | Jallet/keras-jl-ac-mean | 2bbc1596192fb8c3aefc4a8126482a5283574a59 | [
"MIT"
] | null | null | null | examples/visualize.py | Jallet/keras-jl-ac-mean | 2bbc1596192fb8c3aefc4a8126482a5283574a59 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from __future__ import print_function
import sys
sys.path.insert(0, "/home/liangjiang/code/keras-jl-mean/")
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import model_from_json
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import np_utils
from keras.callbacks import EarlyStopping, LearningRateScheduler
from keras.regularizers import l2, activity_l1l2
from keras import backend as K
import argparse
import json
import numpy as np
import matplotlib.pyplot as plt
def argparser():
parser = argparse.ArgumentParser()
parser.add_argument("weight_path", action = 'store',
help = "Path of learned weight")
parser.add_argument("--layer", "-l", action = 'store', type = int, default = 1,
dest = 'layer', help = "Layer to be visualized")
return parser
def random_crop(X_train, size = (3, 3), times = 10):
num_samples = times * X_train.shape[0]
print("num_samples: ", num_samples)
row = X_train.shape[2]
col = X_train.shape[3]
crop_row = size[0]
crop_col = size[1]
random_sample = np.random.randint(0, X_train.shape[0], size = num_samples)
print("random_sample: ", random_sample)
random_col_index = np.random.randint(0, row - crop_row + 1, size = num_samples)
print("random_col_index: ", random_col_index)
random_row_index = np.random.randint(0, col - crop_col, size = num_samples)
print("random_row_index: ", random_row_index)
# cropped_x_cols = cropped_x.shape[2]
# cropped_x_rows = cropped_x.shape[3]
crop_x = np.zeros((num_samples, X_train.shape[1], crop_row, crop_col))
for i in range(num_samples):
crop_x[i, :, :, :] = X_train[random_sample[i], :,
random_row_index[i] : random_row_index[i] + crop_row,
random_col_index[i] : random_col_index[i] + crop_col]
# print("crop_x[0]: ", crop_x[0, :, :, :])
return crop_x
def main():
parser = argparser()
args = parser.parse_args()
weight_path = args.weight_path
layer = args.layer
img_rows, img_cols = 32, 32
# the CIFAR10 images are RGB
img_channels = 3
batch_size = 32
nb_classes = 10
model = Sequential()
print("Making model")
model.add(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(img_channels, img_rows, img_cols),
W_regularizer = l2(l = 0.),
b_regularizer = l2(l = 0.)))
model.add(Activation('relu'))
model.add(Convolution2D(32, 3, 3,
W_regularizer = l2(l = 0.),
b_regularizer = l2(l = 0.)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Dropout(0.25))
model.add(Convolution2D(64, 3, 3, border_mode='same',
W_regularizer = l2(l = 0.),
b_regularizer = l2(l = 0.)))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3,
W_regularizer = l2(l = 0.),
b_regularizer = l2(l = 0.)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, W_regularizer = l2(l = 0.), b_regularizer = l2(l = 0.)))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes, W_regularizer = l2(l = 0.), b_regularizer = l2(l = 0.)))
model.add(Activation('softmax'))
# let's train the model using SGD + momentum (how original).
print("Compiling model")
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy'])
print("Going to visualize layer ", layer)
print(model.layers[layer].get_config())
# load learned weight
print("Loading weight")
model.load_weights(weight_path)
weight = model.layers[0].get_weights()
print("shape of weight: ", weight[0].shape)
# generate function to get output at layer to be visualized
for i in range(len(model.layers)):
print(i)
input = model.layers[0].input
output = model.layers[layer].output
func = K.function([K.learning_phase()] + [input], output)
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
# im = X_train[100, :, :, :]
# im = np.swapaxes(im, 0, 2)
# im = np.swapaxes(im, 0, 1)
# plt.figure(1)
# plt.imshow(im)
# plt.show()
# sys.exit()
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print(X_test.shape[0], 'test samples')
crop_x = X_test
# crop_x = random_crop(X_test, size = (9, 9), times = 10)
print("shape of crop_x: ", crop_x.shape)
im = crop_x[0, :, :, :]
# print("crop_x[0]", im)
im = im * 255
im = im.astype(np.uint8)
# print("im of uint8: ", im)
fig = plt.figure()
# plt.imshow(im)
# plt.show()
# sys.exit()
# get output from layer to be visualized
# print(X_test[50][1])
activation = func([0] + [crop_x])
print("shape of activation: ", activation.shape)
# max_sample_index = np.argmax(activation, axis = 0)
# max_sample_index = max_sample_index.squeeze()
# np.savetxt("max_sample_index", max_sample_index, fmt = "%d")
# print("shape of max_sample_index: ", max_sample_index.shape)
# # print("max_29", activation[:, 29, :, :])
# for i in range(32):
# ax = fig.add_subplot(8, 4, i + 1, frameon=False)
# ax.set_xticks([])
# ax.set_yticks([])
# ax.xaxis.set_ticks_position('none')
# ax.yaxis.set_ticks_position('none')
# im = crop_x[max_sample_index[i], :, :, :]
# im = np.swapaxes(im, 0, 2)
# im = np.swapaxes(im, 1, 0)
# # print("shape of im: ", im.shape)
# im = im * 255
# im = im.astype(np.uint8)
# ax.imshow(im)
# plt.show()
if activation.ndim == 4:
num = activation.shape[0]
print("num: ", num)
col = activation.shape[1]
print("col: ", col)
map_size = activation.shape[2] * activation.shape[3]
print("map_size: ", map_size)
# temp = np.mean(activation, axis = -1)
# matrix_activation = np.mean(temp, axis = -1)
flatten_activation = np.reshape(activation, (num, col * map_size))
print("shape of flatten_activation: ", flatten_activation.shape)
trans_activation = flatten_activation.transpose()
print("shape of trans_activation: ", trans_activation.shape)
reshape_activation = np.reshape(trans_activation, (col, num * map_size))
print("shape of reshape_activation: ", reshape_activation.shape)
matrix_activation = reshape_activation.transpose()
print("shape of matrix_activation: ", matrix_activation.shape)
mean = np.mean(matrix_activation, axis = 0, keepdims = True)
# mean_p = T.printing.Print('mean')(mean)
std = np.std(matrix_activation, axis = 0, keepdims = True)
normalized_output = (matrix_activation - mean) / std
covariance = np.dot(np.transpose(normalized_output), normalized_output) / num / map_size
else:
num = activation.shape[0]
mean = np.mean(activation, axis = 0, keepdims = True)
# mean_p = T.printing.Print('mean')(mean)
std = np.std(activation, axis = 0, keepdims = True)
normalized_output = (activation - mean) / std
covariance = np.dot(np.transpose(normalized_output), normalized_output) / num
np.savetxt("mean", mean, fmt = "%f")
np.savetxt("std", std, fmt = "%f")
np.savetxt("covariance", covariance, fmt = "%f")
if "__main__" == __name__:
main()
| 38.682692 | 97 | 0.616828 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,226 | 0.276659 |
2ee93559b4c44d3a539288935e7f1d8e903dfc6a | 14,221 | py | Python | electrical_simulation/miasole_module_two.py | architecture-building-systems/bipv-tool | 3ae73a541754e5215dfd39ef837d72f4b80ef967 | [
"MIT"
] | 4 | 2019-02-18T14:10:49.000Z | 2021-04-23T09:03:13.000Z | electrical_simulation/miasole_module_two.py | architecture-building-systems/bipv-tool | 3ae73a541754e5215dfd39ef837d72f4b80ef967 | [
"MIT"
] | 1 | 2018-08-16T13:27:15.000Z | 2018-08-16T13:27:16.000Z | electrical_simulation/miasole_module_two.py | architecture-building-systems/bipv-tool | 3ae73a541754e5215dfd39ef837d72f4b80ef967 | [
"MIT"
] | null | null | null | import numpy as np
import pvlib.pvsystem as pvsyst
import interconnection as connect
import matplotlib.pyplot as plt
def calculate_reverse_scaling_factor(voltages, breakdown_voltage, miller_exponent):
"""
:param voltages: numpy array of voltages
:param breakdown_voltage: the minimum voltage before the avelanche breakdown happens
:param miller_exponent: --> google
:return: numpy array of according factors
"""
reverse_scaling_factor = np.reciprocal(1. - np.power((np.absolute(voltages) / -breakdown_voltage), miller_exponent))
return reverse_scaling_factor
def calculate_sub_cell_characteristics(irrad_on_subcells, evaluated_cell_voltages, num_subcells,
reverse_scaling_factor, irrad_temp_lookup_np, t_ambient, irrad_noct, t_noct,
t_a_noct, alpha_short_current, module_params, egap_ev, round_irrad_to_ten):
"""
:param irrad_on_subcells:
:param evaluated_voltages:
:param numcells:
:param irrad_temp_lookup_df:
:param irrad_noct:
:param t_noct:
:param t_a_noct:
:param alpha_short_current:
:param module_params:
:param egap_ev:
:return: subcell_v_values: List of np arrays where a list of v-values is stored for every cell
subcell_i_values,:List of np arrays where a list of v-values is stored for every cell
"""
subcell_i_values = np.empty((len(irrad_on_subcells), len(
evaluated_cell_voltages))) # List of lists where a list of i-values is stored for every subcell
subcell_v_values = np.empty((len(irrad_on_subcells), len(
evaluated_cell_voltages))) # List of lists where a list of v-values is stored for every cell, basically the same as for cells
irrad_on_subcells_np = np.array(irrad_on_subcells) # Take this out of the function
sub_cell_irrad_np = np.rint(irrad_on_subcells_np).astype(int) # Take this out of the function
t_ambient = int(t_ambient) # Take this out of the function
temperature_row = irrad_temp_lookup_np[t_ambient + 25] # +25 because row on is at -25Celsius
for position, irradiance_value in np.ndenumerate(sub_cell_irrad_np):
if round_irrad_to_ten == True:
irradiance_value_lookup=irradiance_value/10
else:
irradiance_value_lookup = irradiance_value
if not (temperature_row[irradiance_value_lookup,0,0] != temperature_row[irradiance_value_lookup,0,0]): # Checks for NaNs
subcell_i_values[position] = temperature_row[irradiance_value_lookup][0] # should collect a numpy array
subcell_v_values[position] = temperature_row[irradiance_value_lookup][1] # should collect a numpy array
else:
if irradiance_value == 0:
irradiance_value = 1
t_cell = float(t_ambient) + float(irradiance_value) / irrad_noct * (t_noct - t_a_noct) # t_cell in deg C
desoto_values = pvsyst.calcparams_desoto(irradiance_value, t_cell, alpha_short_current, module_params,
egap_ev, 0.0001, 1, 1000, 25)
# calcparams_desoto takes the temperature in degrees Celsius!
photocurrent = desoto_values[0] # [A]
sat_current = desoto_values[1] # [A]
series_resistance = desoto_values[2] # [Ohm]
shunt_resistance = desoto_values[3] # [Ohm]
nnsvth = desoto_values[4]
evaluated_module_voltages = evaluated_cell_voltages*56
# Basic assumption here: Module IV-curve can be converted to a cell IV-curve by dividing the module voltage
# by the number of cells further the subcell current is calculated by dividing currents by the number of
# subcells.
evaluated_currents = pvsyst.i_from_v(shunt_resistance, series_resistance, nnsvth,
evaluated_module_voltages, sat_current, photocurrent)
subcell_v_values[position] = evaluated_cell_voltages # Save for later use
# calculate the subcell forward and reverse characteristc
subcell_current = np.multiply(evaluated_currents, reverse_scaling_factor) / num_subcells # Numpy array
subcell_i_values[position] = subcell_current # Save for later use
irrad_temp_lookup_np[t_ambient + 25][irradiance_value_lookup] = [subcell_current, evaluated_cell_voltages]
# plt.plot(subcell_v_values[position],subcell_i_values[position])
# plt.show()
return subcell_i_values, subcell_v_values
def sub_cells_2_cells(subcell_i_values, num_subcells):
"""
:param subcell_i_values: numpy array
:param num_subcells:
:return: cell_i_values, numpy array
simple reshaping can be used, because the subcell v values all have the same basis
"""
cell_i_values = subcell_i_values.reshape((-1, num_subcells, len(subcell_i_values[0]))).sum(axis=1)
return cell_i_values
def cells2substrings(cell_v_values_np, cell_i_values_np, cells_per_substring, number_of_substrings, max_i_module,
min_i_module, interpolation_resolution_submodules):
"""
:param cell_v_values_np: numpy array of cell voltage values [[cell1values][cell2values] etc]
:param cell_i_values_np: numpy array of cell current values [[cell1values][cell2values] etc]
:param cells_per_substring: int, this value represents how many cells are in a substring = number of cells per
bypass diode
:param number_of_substrings: int, here equal to number of bypass diodes
:param max_i_module: this is the maximum expected current in the module. Setting a value close above Isc prevents
having huge unnecessary interpolations when connecting the cells.
:param min_i_module: zero can be used as long as cells are not connected in parallel to other cells
:return: returns numpy dtype object array with i and v values for each substring/submodule
"""
i_connected_np = np.empty(number_of_substrings, dtype=object)
v_connected_np = np.empty(number_of_substrings, dtype=object)
for substring in range(number_of_substrings): # iterate through all the substrings by number
substring_v_values_np = cell_v_values_np[substring * cells_per_substring:(substring + 1) * cells_per_substring]
substring_i_values_np = cell_i_values_np[substring * cells_per_substring:(substring + 1) * cells_per_substring]
i_connected_np[substring], v_connected_np[substring] = connect.series_connect_multiple(substring_i_values_np,
substring_v_values_np,
max_i_module, min_i_module,
interpolation_resolution_submodules)
return i_connected_np, v_connected_np
def bypass_diodes_on_substrings(substring_i_values_np, substring_v_values_np, number_of_substrings,
diode_saturation_current=1.0e-7, n_x_Vt=1.7e-2, numerical_diode_threshold=-1):
"""
:param substring_i_values: numpy array dtype object
:param substring_v_values: numpy array dtype object
:param number_of_substrings: int, here equal to number of bypass diodes
:param diode_saturation_current: float, the saturation current of the modelled diode
:param n_x_Vt: float, thermal voltage multiplied by the diode ideality factor
:param numerical_diode_threshold: this is a value to speed up the calculation by not taking any values into account
below this voltage and thereby not causing any overflow errors.
:return: returns the parallel addition of the bypass diodes and the substring currents
"""
diode_current = np.empty(number_of_substrings, dtype=object) # List of np ndarrays for the current of each diode
for substring in range(number_of_substrings):
# Do diode calculations diode_current = 1.e-7*np.exp(-voltage_selected/1.7e-2) Where from??
# diode_steps = np.empty(len(substring_v_values[substring]))
substring_v_values_np[substring][substring_v_values_np[substring] < numerical_diode_threshold] = numerical_diode_threshold
diode_steps = diode_saturation_current * np.exp(-substring_v_values_np[substring] / n_x_Vt)
diode_current[substring]=diode_steps
for substring in range(number_of_substrings):
substring_i_values_np[substring] = np.add(substring_i_values_np[substring], diode_current[substring])
return substring_i_values_np
def partial_shading(irrad_on_subcells, temperature=25, irrad_temp_lookup_np=None,
breakdown_voltage=-6.10, evaluated_module_voltages=None, simulation_parameters=None,
module_params=None):
"""
This function returns the module IV curve of a module under any partial shading conditions or unequal irradiance.
:param irrad_on_subcells: list, list of all irradiance values on the specific module (for one specific hour) make
sure that the dimensions of this list equals the number of cells or subcells that are
used for the module. E.G number of cells = 56, num_subcells=4 --> list length = 274
:param temperature: float, Ambient temperature value for the given hour
:param irrad_temp_lookup_df:
:param module_df:
:param module_name:
:param numcells:
:param n_bypass_diodes:
:param num_subcells:
:param vmax:
:param v_threshold:
:param breakdown_voltage:
:return:
"""
# Definition of constants, these are defined in hardcode because they are fixed:
t_a_noct = 20 # [a,NOCT]
irrad_noct = 800 # [W/m2]
egap_ev = 1.12 # Band gap energy [eV]
miller_exponent = 3 # This is set
#For now here, change to parameters:
max_i_module = module_params["max_module_current"] # [A]
min_i_module = module_params["min_module_current"] # [A], min value of interpolation in series connect
n_bypass_diodes = module_params["number_of_bypass_diodes"]
numcells = module_params["number_of_cells"]
num_subcells = module_params["number_of_subcells"]
alpha_short_current = module_params['alpha_short_current']
t_noct = module_params['t_noct']
interpolation_resolution_submodules = simulation_parameters["interpolation_resolution_submodules"] # [A]
interpolation_resolution_module = simulation_parameters["interpolation_resolution_module"] # [A]
final_module_iv_resolution = simulation_parameters["final_module_iv_resolution"] # [A] or [V] counts for both dimensions
round_irrad_to_ten = simulation_parameters["round_irradiance_to_ten"]
if n_bypass_diodes > 0:
cells_per_substring = numcells / n_bypass_diodes
else:
cells_per_substring = numcells
if cells_per_substring % 1 != 0:
print "WARNING: Number of bypass diodes or number of cells is wrong."
else:
pass
# Rearrange irrad_on_subcells
irrad_on_subcells = connect.rearrange_shading_pattern_miasole(irrad_on_subcells, num_subcells)
evaluated_cell_voltages = evaluated_module_voltages / numcells # Only divide by the number of cells
reverse_scaling_factor = calculate_reverse_scaling_factor(evaluated_cell_voltages, breakdown_voltage, miller_exponent)
t_ambient = temperature # degC, if measured, use data here
# Calculate sub_cell characteristic
subcell_i_values, subcell_v_values = calculate_sub_cell_characteristics(irrad_on_subcells=irrad_on_subcells,
evaluated_cell_voltages=evaluated_cell_voltages,
num_subcells=num_subcells,
reverse_scaling_factor=reverse_scaling_factor,
irrad_temp_lookup_np=irrad_temp_lookup_np,
t_ambient=t_ambient,
irrad_noct=irrad_noct,
t_noct=t_noct, t_a_noct=t_a_noct,
alpha_short_current=alpha_short_current,
module_params=module_params,
egap_ev=egap_ev,
round_irrad_to_ten=round_irrad_to_ten)
# Calculate cell characteristics
cell_i_values_np = sub_cells_2_cells(subcell_i_values, num_subcells)
cell_v_values_np = np.tile(evaluated_cell_voltages, (numcells, 1))
# Calculate basic substring characteristics
i_connected_np, v_connected_np = cells2substrings(cell_v_values_np, cell_i_values_np, cells_per_substring,
n_bypass_diodes, max_i_module, min_i_module,
interpolation_resolution_submodules)
# add bypass diode to sub_strings
i_connected_np = bypass_diodes_on_substrings(substring_i_values_np=i_connected_np,
substring_v_values_np=v_connected_np,
number_of_substrings=n_bypass_diodes)
# add sub_module voltages:
i_module, v_module = connect.series_connect_multiple(i_connected_np, v_connected_np, max_i_module, min_i_module,
interpolation_resolution_module)
i_module, v_module = connect.clean_curve([i_module, v_module], final_module_iv_resolution)
# print len(v_module)
# plt.plot(v_module, i_module)
# plt.show()
return i_module, v_module, irrad_temp_lookup_np
| 52.283088 | 134 | 0.664932 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5,252 | 0.369313 |
2ee996c7e56c15fda4c16fc6ca5f0fcf36384ef4 | 284 | py | Python | default_settings.py | RobMilinski/Xero-Starter-Branched-Test | c82382e674b34c2336ee164f5a079d6becd1ed46 | [
"MIT"
] | null | null | null | default_settings.py | RobMilinski/Xero-Starter-Branched-Test | c82382e674b34c2336ee164f5a079d6becd1ed46 | [
"MIT"
] | null | null | null | default_settings.py | RobMilinski/Xero-Starter-Branched-Test | c82382e674b34c2336ee164f5a079d6becd1ed46 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import os
from os.path import dirname, join
SECRET_KEY = os.urandom(16)
# configure file based session
SESSION_TYPE = "filesystem"
SESSION_FILE_DIR = join(dirname(__file__), "cache")
# configure flask app for local development
ENV = "development"
| 23.666667 | 52 | 0.714789 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 131 | 0.461268 |
2eea53e1e9eb945c94d4c33420b934da2fc613c6 | 5,610 | py | Python | v0.2/crawl_tool.py | sivanWu0222/GetLinksFromSoBooks | 9f429b5f8b359e4faf25381a7b59f5effd21b5ca | [
"Apache-2.0"
] | 8 | 2019-02-09T05:00:50.000Z | 2020-11-02T11:30:03.000Z | v0.2/crawl_tool.py | sivanWu0222/GetLinksFromSoBooks | 9f429b5f8b359e4faf25381a7b59f5effd21b5ca | [
"Apache-2.0"
] | null | null | null | v0.2/crawl_tool.py | sivanWu0222/GetLinksFromSoBooks | 9f429b5f8b359e4faf25381a7b59f5effd21b5ca | [
"Apache-2.0"
] | null | null | null | import requests
from bs4 import BeautifulSoup
import re
from selenium import webdriver
import model
URL = "https://sobooks.cc"
VERIFY_KEY = '2019777'
def convert_to_beautifulsoup(data):
"""
用于将传过来的data数据包装成BeautifulSoup对象
:param data: 对应网页的html内容数据
:return: 对应data的BeautifulSoup对象
"""
bs = BeautifulSoup(data, "html.parser")
return bs
def url_pattern():
"""
匹配URL的正则表达式
:return:
"""
pattern = '(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?'
pattern = re.compile(pattern)
return pattern
def get_category_link(url):
"""
爬取导航栏各个分类下的URL,并将其添加到一个列表中
:param URL:
:return:
"""
navbar_links = []
data = requests.get(url).text
bs = convert_to_beautifulsoup(data)
navbar_contents = bs.select('.menu-item')
for navbar_content in navbar_contents:
pattern = url_pattern()
navbar_link = pattern.search(str(navbar_content))
navbar_links.append(navbar_link.group())
return navbar_links
def get_url_content(url):
"""
返回url对应网页的内容,用于分析和提取有价值的内容
:param url: 网页地址
:return: url对应的网页html内容
"""
return requests.get(url).text
def get_book_card_content(url, data):
"""
得到每页书籍卡片的内容,从而为获取书籍作者名字和链接提供方便
:param url: 网页的url地址
:param data: url对应的网页内容
:return:
"""
books_perpage = convert_to_beautifulsoup(data).select('h3')
return books_perpage
def get_url_book(url, data):
"""
获得对应页面URL链接存放的每个书籍对应的URL
:param url: 网页的url地址
:param data: url对应的网页内容
:return: 返回该URL所在页面的每个书籍对应的URL组成的列表
"""
book_links = []
# 通过h3标签查找每页书籍
books_perpage = get_book_card_content(url, data)
for book_content in books_perpage:
pattern = url_pattern()
# 获取每本书的链接
book_link = pattern.search(str(book_content))
book_links.append(book_link.group())
return book_links
def has_next_page(url, data):
"""
判断url对应的页面是否有 下一页
:param url: 网页的url地址
:param data: url对应的网页内容
:return: 有下一页 返回下一页对应的URL地址
没有下一页 返回False
"""
bs = BeautifulSoup(data, "html.parser")
next_page = bs.select('.next-page')
if next_page:
url_next_page = url_pattern().search(str(next_page))
return url_next_page.group()
else:
return False
def get_url_books_name(url, data):
"""
判断书籍列表中url对应的页面的书名组成的列表
:param url: 网页的url地址
:param data: url对应的网页内容
:return: 返回url对应网址的书籍名称组成的列表
"""
books_name = []
books_perpage = get_book_card_content(url, data)
for book in books_perpage:
book_name = book.select('a')[0].get('title')
books_name.append(book_name)
return books_name
def get_book_baidu_neturl(url):
"""
获取每个书籍详情页面的百度网盘链接
:param url: 每本书详情页面的URL
:return: 返回每本书的百度网盘链接,如果没有返回 False
"""
data = requests.get(url).text
bs = convert_to_beautifulsoup(data)
for a_links in bs.select('a'):
if a_links.get_text() == '百度网盘':
book_baidu_url = a_links.get('href')
# 提取百度网盘链接的正则表达式
pattern = '(http|ftp|https):\/\/pan\.[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?'
pattern = re.compile(pattern)
book_baidu_url = pattern.search(book_baidu_url).group()
return book_baidu_url
def get_book_baidu_password(url):
"""
获取对应url链接存储的书籍百度网盘的提取密码
:param url: 要获取提取密码的url链接所对应的书籍
:return: 如果存在返回提取密码
否则返回None
"""
# @TODO 1. 尝试使用爬虫的方式获取提交的页面来获得百度网盘提取码
# @TODO 2. 如果不可以的话,就使用selenium模拟浏览器来爬取内容吧
browser = webdriver.Chrome()
browser.get(url)
try:
browser.find_element_by_class_name('euc-y-s')
secret_key = browser.find_element_by_class_name('euc-y-i')
secret_key.send_keys(VERIFY_KEY)
browser.find_element_by_class_name('euc-y-s').click()
except Exception as e:
browser.close()
password = str(browser.find_element_by_class_name('e-secret').text)
if password:
return password[-4:]
else:
return None
def get_book_author(url, data):
"""
获得url对应的书籍列表页面中的作者列表
:param url: 对应书籍列表页面的url
:param data: 对应书籍列表页面的html内容
:return: 返回url对应的作者列表
"""
book_authors = []
bs = convert_to_beautifulsoup(data)
for book_author in bs.select('div > p > a'):
book_authors.append(book_author.text)
return book_authors
def analy_url_page(url):
"""
分析url对应的网址,包括如下几个方面
1. 提取当前url所有书籍的链接
2. 判断当前url是否有下一页,如果有, 继续步骤3
如果没有,继续从新的分类开始爬取,
如果新的分类已经爬取完成,则爬取完成
3. 获取当前页面所有书籍,并依次为每个书籍创建对象(进行初始化,爬取书籍的名称、作者名、书籍详情页、书籍百度网盘地址、书籍百度网盘提取码)
4. 继续步骤2
:param url: 网页的url地址
:return: None
"""
while url:
data = get_url_content(url)
url_links_page = get_url_book(url, data)
url_next_page = has_next_page(url, data)
books_name = get_url_books_name(url, data)
for i in range(len(books_name)):
book_name = books_name[i]
book_author = get_book_author(url, data)[i]
book_info_url = url_links_page[i]
book_baidu_url = get_book_baidu_neturl(url_links_page[i])
book_baidu_password = get_book_baidu_password(url_links_page[i])
book = model.Book(book_name, book_info_url, book_author, book_baidu_url, book_baidu_password)
print(book)
if url_next_page:
url = url_next_page
else:
break
if __name__ == '__main__':
root_url = URL
for url in get_category_link(root_url):
analy_url_page(url) | 26.842105 | 106 | 0.636364 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,287 | 0.474726 |
2eea8d34fe53d8a8743f98b68b96db418c9710d2 | 2,545 | py | Python | test_basic.py | mpeters/movie_rating | 307188ee2908e42bcdc4e98114a7fe9ae264ebeb | [
"MIT"
] | null | null | null | test_basic.py | mpeters/movie_rating | 307188ee2908e42bcdc4e98114a7fe9ae264ebeb | [
"MIT"
] | null | null | null | test_basic.py | mpeters/movie_rating | 307188ee2908e42bcdc4e98114a7fe9ae264ebeb | [
"MIT"
] | null | null | null | import unittest
import subprocess
import re
from os import environ
class MoveRatingTestBasic(unittest.TestCase):
def setUp(self):
if environ.get('OMDB_API_KEY') is None or len(environ.get('OMDB_API_KEY')) < 1:
raise Exception("The OMDB_API_KEY environment variable is not set. Unable to run tests without it")
def test_existing_movie(self):
p = self._movie_rating_cmd("--title 'Guardians of the Galaxy'")
rating = p.stdout.rstrip()
self.assertTrue(re.match(r'^\d\d%$', rating), "Existing movie has a rating ({})".format(p.stdout))
def test_existing_movie_bad_year(self):
p = self._movie_rating_cmd("--title 'Guardians of the Galaxy' --year 1999")
self.assertNotEqual(p.returncode, 0, "Non-zero return code")
self.assertTrue(p.stdout == "", "Bad Year ({}) doesn't have a rating")
error = p.stderr.rstrip()
self.assertEqual("We're sorry, but a movie by that name (Guardians of the Galaxy) in that year (1999) was not found", error, "Correct error for bad year")
def test_typo_movie(self):
p = self._movie_rating_cmd("--title 'Napolean Dynamite'")
self.assertNotEqual(p.returncode, 0, "Non-zero return code")
self.assertTrue(p.stdout == "", "Typo ({}) doesn't have a rating")
error = p.stderr.rstrip()
self.assertEqual("We're sorry, but a movie by that name (Napolean Dynamite) was not found", error, "Correct error for typo movie")
def test_missing_title(self):
p = self._movie_rating_cmd("")
self.assertNotEqual(p.returncode, 0, "Non-zero return code")
self.assertTrue('arguments are required: --title' in p.stderr, "Correct error for missing title")
def test_invalid_year(self):
p = self._movie_rating_cmd("--title Foo --year 200a")
self.assertNotEqual(p.returncode, 0, "Non-zero return code")
self.assertTrue('--year: invalid int value' in p.stderr, "Correct error for invalid year")
def test_invalid_api_key(self):
p = subprocess.run("/usr/src/app/movie_rating.py --api-key foo --title foo", shell=True, capture_output=True, text=True)
self.assertNotEqual(p.returncode, 0, "Non-zero return code")
self.assertTrue("API Key was not valid" in p.stderr, "Correct error for invalid api-key")
def _movie_rating_cmd(self, args):
p = subprocess.run("/usr/src/app/movie_rating.py {}".format(args), shell=True, capture_output=True, text=True)
return p
if __name__ == '__main__':
unittest.main()
| 48.942308 | 162 | 0.674263 | 2,428 | 0.954028 | 0 | 0 | 0 | 0 | 0 | 0 | 988 | 0.388212 |
2eebbacb5df6c83ca0a014890b1d4f2d50ccc8e9 | 228 | py | Python | tools/intogen/runtime/pyenv/lib/python2.7/site-packages/numpy/version.py | globusgenomics/galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
] | 1 | 2021-02-05T13:19:58.000Z | 2021-02-05T13:19:58.000Z | tools/intogen/runtime/pyenv/lib/python2.7/site-packages/numpy/version.py | globusgenomics/galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
] | null | null | null | tools/intogen/runtime/pyenv/lib/python2.7/site-packages/numpy/version.py | globusgenomics/galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
] | null | null | null |
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY
short_version = '1.9.0'
version = '1.9.0'
full_version = '1.9.0'
git_revision = '07601a64cdfeb1c0247bde1294ad6380413cab66'
release = True
if not release:
version = full_version
| 20.727273 | 57 | 0.745614 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 107 | 0.469298 |
2eebfa288fa7ac7e2d9bbee1fae33a9fe39c1ae3 | 620 | py | Python | txter/migrations/0001_initial.py | KanataIZUMIKAWA/TXTer | 6cbf67a229db30452e412883cd55584a204199a7 | [
"MIT"
] | null | null | null | txter/migrations/0001_initial.py | KanataIZUMIKAWA/TXTer | 6cbf67a229db30452e412883cd55584a204199a7 | [
"MIT"
] | null | null | null | txter/migrations/0001_initial.py | KanataIZUMIKAWA/TXTer | 6cbf67a229db30452e412883cd55584a204199a7 | [
"MIT"
] | null | null | null | # Generated by Django 3.1.4 on 2021-01-05 03:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Posts',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user', models.CharField(default='noname', max_length=64)),
('note', models.TextField(default='')),
('read', models.BooleanField(default=False)),
],
),
]
| 25.833333 | 114 | 0.564516 | 527 | 0.85 | 0 | 0 | 0 | 0 | 0 | 0 | 90 | 0.145161 |
2eec6b15a40ea433bc4066f828b5719399dfaf23 | 1,450 | py | Python | bin/util.py | data-lessons/dh-openrefine | 925546279c3dbbb35a76d5a7652a999c634ed7a5 | [
"CC-BY-4.0"
] | 7 | 2016-08-05T15:38:38.000Z | 2021-08-15T09:28:40.000Z | bin/util.py | ucsdlib/library-bash | de433b43aef2983ef1e51a8d61438ab2d5d08e3d | [
"CC-BY-4.0"
] | 4 | 2016-07-28T08:00:12.000Z | 2016-09-16T10:17:36.000Z | bin/util.py | ucsdlib/library-bash | de433b43aef2983ef1e51a8d61438ab2d5d08e3d | [
"CC-BY-4.0"
] | 4 | 2016-07-28T06:51:03.000Z | 2017-09-24T17:17:58.000Z | import sys
class Reporter(object):
'''Collect and report errors.'''
def __init__(self, args):
'''Constructor.'''
super(Reporter, self).__init__()
self.messages = []
def check_field(self, filename, name, values, key, expected):
'''Check that a dictionary has an expected value.'''
if key not in values:
self.add(filename, '{0} does not contain {1}', name, key)
elif values[key] != expected:
self.add(filename, '{0} {1} is {2} not {3}', name, key, values[key], expected)
def check(self, condition, location, fmt, *args):
'''Append error if condition not met.'''
if not condition:
self.add(location, fmt, *args)
def add(self, location, fmt, *args):
'''Append error unilaterally.'''
if type(location) is NoneType:
extra = ''
elif type(location) is str:
extra = 'at {0}'.format(filename)
elif type(location) is tuple:
filename, line_number = location
extra = 'at {0}:{1}'.format(*location)
else:
assert False, 'Unknown location "{0}"/{1}'.format(location, type(location))
self.messages.append(fmt.format(*args) + extra)
def report(self, stream=sys.stdout):
'''Report all messages.'''
if not self.messages:
return
for m in self.messages:
print(m, file=stream)
| 27.884615 | 90 | 0.561379 | 1,437 | 0.991034 | 0 | 0 | 0 | 0 | 0 | 0 | 300 | 0.206897 |
2eee14c3677a7997e3c8aceecca0e08c51854b86 | 10,722 | py | Python | src/graph_io.py | Abdumaleek/infinity-mirror | b493c5602d9e4bcf374b748e9b80e7c85be54a88 | [
"MIT"
] | 5 | 2020-03-13T02:54:03.000Z | 2022-03-18T02:33:12.000Z | src/graph_io.py | Abdumaleek/infinity-mirror | b493c5602d9e4bcf374b748e9b80e7c85be54a88 | [
"MIT"
] | 2 | 2021-11-10T19:47:00.000Z | 2022-02-10T01:24:59.000Z | src/graph_io.py | Abdumaleek/infinity-mirror | b493c5602d9e4bcf374b748e9b80e7c85be54a88 | [
"MIT"
] | 1 | 2021-05-24T21:54:44.000Z | 2021-05-24T21:54:44.000Z | """
Graph i/o helpers
"""
import math
from pathlib import Path
import networkx as nx
import numpy as np
from src.utils import ColorPrint as CP, check_file_exists, print_float
# TODO: add LFR benchmark graphs
class GraphReader:
"""
Class for graph reader
.g /.txt: graph edgelist
.gml, .gexf for Gephi
.mat for adjacency matrix
"""
__slots__ = ['possible_extensions', 'filename', 'path', 'gname', 'graph']
def __init__(self, filename: str, gname: str = '', reindex_nodes: bool = False, first_label: int = 0,
take_lcc: bool = True) -> None:
"""
:param filename: path to input file
:param gname: name of the graph
"""
self.possible_extensions = ['.g', '.gexf', '.gml', '.txt', '.mat']
self.filename = filename
self.path = Path(filename)
assert check_file_exists(self.path), f'Path: "{self.path}" does not exist'
if gname != '':
self.gname = gname
else:
self.gname = self.path.stem
self.graph: nx.Graph = self._read()
self._preprocess(reindex_nodes=reindex_nodes, first_label=first_label, take_lcc=take_lcc)
assert self.graph.name != '', 'Graph name is empty'
return
def _read(self) -> nx.Graph:
"""
Reads the graph based on its extension
returns the largest connected component
:return:
"""
CP.print_blue(f'Reading "{self.gname}" from "{self.path}"')
extension = self.path.suffix
assert extension in self.possible_extensions, f'Invalid extension "{extension}", supported extensions: ' \
f'{self.possible_extensions}'
str_path = str(self.path)
if extension in ('.g', '.txt'):
graph: nx.Graph = nx.read_edgelist(str_path, nodetype=int)
elif extension == '.gml':
graph: nx.Graph = nx.read_gml(str_path)
elif extension == '.gexf':
graph: nx.Graph = nx.read_gexf(str_path)
elif extension == '.mat':
mat = np.loadtxt(fname=str_path, dtype=bool)
graph: nx.Graph = nx.from_numpy_array(mat)
else:
raise (NotImplementedError, f'{extension} not supported')
graph.name = self.gname
return graph
def _preprocess(self, reindex_nodes: bool, first_label: int = 0, take_lcc: bool = True) -> None:
"""
Preprocess the graph - taking the largest connected components, re-index nodes if needed
:return:
"""
CP.print_none('Pre-processing graph....')
CP.print_none(f'Original graph "{self.gname}" n:{self.graph.order():,} '
f'm:{self.graph.size():,} #components: {nx.number_connected_components(self.graph)}')
if take_lcc and nx.number_connected_components(self.graph) > 1:
## Take the LCC
component_sizes = [len(c) for c in sorted(nx.connected_components(self.graph), key=len, reverse=True)]
CP.print_none(f'Taking the largest component out of {len(component_sizes)} components: {component_sizes}')
graph_lcc = nx.Graph(self.graph.subgraph(max(nx.connected_components(self.graph), key=len)))
perc_nodes = graph_lcc.order() / self.graph.order() * 100
perc_edges = graph_lcc.size() / self.graph.size() * 100
CP.print_orange(
f'LCC has {print_float(perc_nodes)}% of nodes and {print_float(perc_edges)}% edges in the original graph')
self.graph = graph_lcc
selfloop_edges = list(nx.selfloop_edges(self.graph))
if len(selfloop_edges) > 0:
CP.print_none(f'Removing {len(selfloop_edges)} self-loops')
self.graph.remove_edges_from(selfloop_edges) # remove self-loops
if reindex_nodes:
# re-index nodes, stores the old label in old_label
self.graph = nx.convert_node_labels_to_integers(self.graph, first_label=first_label,
label_attribute='old_label')
CP.print_none(
f'Re-indexing nodes to start from {first_label}, old labels are stored in node attr "old_label"')
CP.print_none(f'Pre-processed graph "{self.gname}" n:{self.graph.order():,} m:{self.graph.size():,}')
return
def __str__(self) -> str:
return f'<GraphReader object> graph: {self.gname}, path: {str(self.path)} n={self.graph.order():,}, m={self.graph.size()}'
def __repr__(self) -> str:
return str(self)
class SyntheticGraph:
"""
Container for Synthetic graphs
"""
__slots__ = ['kind', 'args', 'g', 'r']
implemented_methods = {'chain': ('n',), 'tree': ('r', 'h'), 'ladder': ('n',), 'circular_ladder': ('n',),
'ring': ('n',), 'clique_ring': ('n', 'k'), 'grid': ('m', 'n'),
'erdos_renyi': ('n', 'p', 'seed'), 'ring_lattice': ('n',), 'BA': ('n', 'm', 'seed'),
'cycle': ('n',)}
def __init__(self, kind, **kwargs):
self.kind = kind
assert kind in SyntheticGraph.implemented_methods, f'Generator {kind} not implemented. Implemented methods: {self.implemented_methods.keys()}'
self.args = kwargs
if 'seed' in SyntheticGraph.implemented_methods[kind] \
and 'seed' not in self.args: # if seed is not specified, set it to None
self.args['seed'] = None
self.g = self._make_graph()
self.r = self.args.get('r', 0) # default r is 0
if self.r != 0:
self._rewire_edges()
def _make_graph(self) -> nx.Graph:
"""
Makes the graph
:return:
"""
assert set(self.implemented_methods[self.kind]).issubset(
set(self.args)), f'Improper args {self.args.keys()}, need: {self.implemented_methods[self.kind]}'
if self.kind == 'chain':
g = nx.path_graph(self.args['n'])
name = f'chain-{g.order()}'
elif self.kind in ('ring', 'cycle'):
g = nx.cycle_graph(self.args['n'])
name = f'ring-{g.order()}'
elif self.kind == 'tree':
g = nx.balanced_tree(self.args['r'], self.args['h'])
name = f"tree-{self.args['r']}-{self.args['h']}"
elif self.kind == 'ladder':
g = nx.ladder_graph(self.args['n'])
name = f'ladder-{g.order() // 2}'
elif self.kind == 'circular_ladder':
g = nx.circular_ladder_graph(self.args['n'])
name = f'circular-ladder-{g.order()}'
elif self.kind == 'clique_ring':
g = nx.ring_of_cliques(self.args['n'], self.args['k'])
name = f"clique-ring-{self.args['n']}-{self.args['k']}"
elif self.kind == 'grid':
g = nx.grid_2d_graph(self.args['m'], self.args['n'])
g = nx.convert_node_labels_to_integers(g, first_label=0) # renumber node labels in grid - default labels are (x,y)
name = f"grid-{self.args['m']}-{self.args['n']}"
elif self.kind == 'erdos_renyi':
seed = self.args['seed']
g = nx.erdos_renyi_graph(n=self.args['n'], p=self.args['p'], seed=seed)
name = f"erdos-renyi-{self.args['n']}-{g.size()}"
if seed is not None:
name += f'-{seed}' # add the seed to the name
elif self.kind == 'ring_lattice':
g = nx.watts_strogatz_graph(n=self.args['n'], k=4, p=0)
name = f"ring-lattice-{g.order()}"
elif self.kind == 'BA':
seed = self.args['seed']
g = nx.barabasi_albert_graph(n=self.args['n'], m=self.args['m'], seed=seed)
name = f"BA-{self.args['n']}-{self.args['m']}"
elif self.kind == 'PLC': # powerlaw cluster graph
p = self.args.get('p', 0.5) # default p is 0.5
seed = self.args['seed']
g = nx.powerlaw_cluster_graph(n=self.args['n'], m=self.args['m'], p=p, seed=seed)
name = f"PLC-{self.args['n']}-{self.args['m']}-{int(p * 100)}"
else:
raise NotImplementedError(f'Improper kind: {self.kind}')
g.name = name
return g
def _rewire_edges(self) -> None:
"""
Re-wires edges randomly
:return:
"""
double_edges_to_rewire = int(math.ceil(self.r * self.g.size())) // 2
CP.print_blue(f'Rewiring {double_edges_to_rewire} edges: {self.g.name}')
nx.connected_double_edge_swap(self.g, nswap=double_edges_to_rewire)
return
class GraphWriter:
"""
Class for writing graphs, expects a networkx graph as input
"""
__slots__ = ['graph', 'path', 'fmt']
def __init__(self, graph: nx.Graph, path: str, fmt: str = '', gname: str = ''):
self.graph: nx.Graph = graph
if self.graph == '':
self.graph.name = gname
assert self.graph.name != '', 'Graph name is empty'
self.path = Path(path)
if fmt == '': # figure out extension from filename
self.fmt = self.path.suffix
else:
self.fmt = fmt
self._write()
def _write(self) -> None:
"""
write the graph into the format
:return:
"""
extension = self.path.suffix
str_path = str(self.path)
if extension in ('.g', '.txt'):
nx.write_edgelist(path=str_path, G=self.graph, data=False)
elif extension == '.gml':
nx.write_gml(path=str_path, G=self.graph)
elif extension == '.gexf':
nx.write_gexf(path=str_path, G=self.graph)
elif extension == '.mat':
mat = nx.to_numpy_matrix(self.graph, dtype=int)
np.savetxt(fname=self.path, X=mat, fmt='%d')
CP.print_blue(f'Wrote {self.graph.name} to {self.path} with n={self.graph.order():,}, m={self.graph.size():,}')
return
def __str__(self) -> str:
return f'<GraphWriter object> graph: {self.graph}, path: {str(self.path)} n={self.graph.order():,}, m={self.graph.size():,}'
def __repr__(self) -> str:
return str(self)
try:
import pyintergraph as pig
except ImportError as e:
print(e)
try:
import igraph as ig
except ImportError as e:
print(e)
def networkx_to_graphtool(nx_G: nx.Graph):
return pig.nx2gt(nx_G)
def graphtool_to_networkx(gt_G):
graph = pig.InterGraph.from_graph_tool(gt_G)
return graph.to_networkX()
def networkx_to_igraph(nx_G: nx.Graph):
graph = pig.InterGraph.from_networkX(nx_G)
return graph.to_igraph()
def igraph_to_networkx(ig_G):
graph = pig.InterGraph.from_igraph(ig_G)
return graph.to_networkX()
| 36.845361 | 150 | 0.571908 | 9,946 | 0.927625 | 0 | 0 | 0 | 0 | 0 | 0 | 3,528 | 0.329043 |
2eee76235b6e429c851cf2af43ca0728c03365df | 1,241 | py | Python | arquivo.py | raphaelss/programagestalt | dabe073bda7d34a16368cdc881e9d1a7150263cc | [
"MIT"
] | null | null | null | arquivo.py | raphaelss/programagestalt | dabe073bda7d34a16368cdc881e9d1a7150263cc | [
"MIT"
] | null | null | null | arquivo.py | raphaelss/programagestalt | dabe073bda7d34a16368cdc881e9d1a7150263cc | [
"MIT"
] | null | null | null | import csv
import re
class Arquivo:
def __init__(self, path):
rp = re.compile("^ *(\d+) +(\d+)\n?$")
self.alturas = []
self.duracoes = []
linecount = 1
with open(path) as f:
for line in f:
match = rp.match(line)
if match:
self.alturas.append(int(match.group(1)))
self.duracoes.append(int(match.group(2)))
else:
print("Erro na linha", linecount, ":", line)
exit()
linecount = linecount + 1
def gerar_altura(self):
return self.alturas
def gerar_duracao(self):
return self.duracoes
class Csv:
def __init__(self, path):
self.alturas = []
self.duracoes = []
with open(path) as f:
for row in csv.reader(f, delimiter=';'):
self.alturas.append(int(row[3]))
self.duracoes.append(round(float(row[1].replace(',','.')) * 60))
def gerar_altura(self):
return self.alturas
def gerar_duracao(self):
return self.duracoes
def abrir(path):
if path.endswith('csv'):
return Csv(path)
else:
return Arquivo(path)
| 26.404255 | 80 | 0.507655 | 1,105 | 0.890411 | 0 | 0 | 0 | 0 | 0 | 0 | 53 | 0.042707 |
2ef007f96300135913374e66f242b4d7ad638d34 | 937 | py | Python | env/Lib/site-packages/OpenGL/GL/ARB/shader_clock.py | 5gconnectedbike/Navio2 | 8c3f2b5d8bbbcea1fc08739945183c12b206712c | [
"BSD-3-Clause"
] | 210 | 2016-04-09T14:26:00.000Z | 2022-03-25T18:36:19.000Z | env/Lib/site-packages/OpenGL/GL/ARB/shader_clock.py | 5gconnectedbike/Navio2 | 8c3f2b5d8bbbcea1fc08739945183c12b206712c | [
"BSD-3-Clause"
] | 72 | 2016-09-04T09:30:19.000Z | 2022-03-27T17:06:53.000Z | env/Lib/site-packages/OpenGL/GL/ARB/shader_clock.py | 5gconnectedbike/Navio2 | 8c3f2b5d8bbbcea1fc08739945183c12b206712c | [
"BSD-3-Clause"
] | 64 | 2016-04-09T14:26:49.000Z | 2022-03-21T11:19:47.000Z | '''OpenGL extension ARB.shader_clock
This module customises the behaviour of the
OpenGL.raw.GL.ARB.shader_clock to provide a more
Python-friendly API
Overview (from the spec)
This extension exposes a 64-bit monotonically incrementing shader
counter which may be used to derive local timing information within
a single shader invocation.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/ARB/shader_clock.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.GL import _types, _glgets
from OpenGL.raw.GL.ARB.shader_clock import *
from OpenGL.raw.GL.ARB.shader_clock import _EXTENSION_NAME
def glInitShaderClockARB():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( _EXTENSION_NAME )
### END AUTOGENERATED SECTION | 32.310345 | 71 | 0.803629 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 565 | 0.602988 |
2ef1c30c2a21d30607beca0e47199956e827e7ca | 234 | py | Python | tuiuiu/tuiuiuadmin/tests/api/utils.py | caputomarcos/tuiuiu.io | d8fb57cf95487e7fe1454b2130ef18acc916da46 | [
"BSD-3-Clause"
] | 3 | 2019-08-08T09:09:35.000Z | 2020-12-15T18:04:17.000Z | tuiuiu/tuiuiuadmin/tests/api/utils.py | caputomarcos/tuiuiu.io | d8fb57cf95487e7fe1454b2130ef18acc916da46 | [
"BSD-3-Clause"
] | null | null | null | tuiuiu/tuiuiuadmin/tests/api/utils.py | caputomarcos/tuiuiu.io | d8fb57cf95487e7fe1454b2130ef18acc916da46 | [
"BSD-3-Clause"
] | 1 | 2017-09-09T20:10:40.000Z | 2017-09-09T20:10:40.000Z | from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from tuiuiu.tests.utils import TuiuiuTestUtils
class AdminAPITestCase(TestCase, TuiuiuTestUtils):
def setUp(self):
self.login()
| 21.272727 | 56 | 0.790598 | 92 | 0.393162 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2ef1fb64ccfc3ef2323962139efae480655479b6 | 1,933 | py | Python | youtube_channel_dl.py | allicebiyon/youtube-channel-dl | 53d06f64fd9a256dd920bc1db093ccd84949c580 | [
"MIT"
] | null | null | null | youtube_channel_dl.py | allicebiyon/youtube-channel-dl | 53d06f64fd9a256dd920bc1db093ccd84949c580 | [
"MIT"
] | null | null | null | youtube_channel_dl.py | allicebiyon/youtube-channel-dl | 53d06f64fd9a256dd920bc1db093ccd84949c580 | [
"MIT"
] | null | null | null | import argparse
import requests
import youtube_dl
from bs4 import BeautifulSoup
from jsonfinder import jsonfinder
from nested_lookup import nested_lookup
parser = argparse.ArgumentParser(description='Download YouTube videos from a channel using youtube-dl.')
parser.add_argument('channelURL', metavar='url', type=str, help='The channel\'s URL')
args = parser.parse_args()
url = args.channelURL
# Check if user input is valid youtube URL
if url.startswith("https://www.youtube.com/channel/") != True:
print("Input is not valid YouTube channel URL.")
exit(0)
# remove "/featured" if it exists
url = url.replace('/featured', '')
# stick "/videos" to input URL
if url.endswith("/videos") != True:
url += "/videos"
# Access le youtube chanel
print("Accessing YouTube channel...\n")
try:
res = requests.get(url)
except requests.exceptions.RequestException as e:
raise SystemExit(e)
# Create BeautifulSoup object from html response
print("Parsing YouTube channel...\n")
soup = BeautifulSoup(res.text, 'html.parser')
# Get the playlist for all videos
scripts = soup.find_all('script')
for script in scripts:
if script.string != None and script.string.find('window["ytInitialData"]') >0:
for _, __, obj in jsonfinder(script.string, json_only=True):
if(len(obj))> 2:
target = nested_lookup('playAllButton', obj)
playlist_id = target[0]['buttonRenderer']['navigationEndpoint']['watchPlaylistEndpoint']['playlistId']
playlist_url = "https://youtube.com/playlist?list="+playlist_id
print("Playlist ID for all videos:")
print(playlist_id,"\n")
print("Playlist URL for youtube-dl:")
print(playlist_url,"\n")
# Call youtube-dl
print("Calling youtube-dl...\n")
# Download all videos
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([playlist_url])
| 28.426471 | 118 | 0.68598 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 773 | 0.399897 |
2ef21a49b80856b019df0f92474580a5a810fe47 | 1,415 | py | Python | Camera_V2.py | Damian-Gsource/ENGI301 | e52b23e76fce576235c80eaca908e665076e4ab6 | [
"MIT"
] | null | null | null | Camera_V2.py | Damian-Gsource/ENGI301 | e52b23e76fce576235c80eaca908e665076e4ab6 | [
"MIT"
] | null | null | null | Camera_V2.py | Damian-Gsource/ENGI301 | e52b23e76fce576235c80eaca908e665076e4ab6 | [
"MIT"
] | null | null | null | import cv2
import numpy as np
# Create a VideoCapture object
cap = cv2.VideoCapture(0)
# Check if camera opened successfully
if (cap.isOpened() == False):
print("Unable to read camera feed")
# Default resolutions of the frame are obtained.The default resolutions are system dependent.
# We convert the resolutions from float to integer.
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
print('frame: width = {0} height = {1}'.format(frame_width,frame_height))
frame_width = 320
frame_height = 240
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
out = cv2.VideoWriter('outpy.mp4',cv2.VideoWriter_fourcc(*'MP4V'), 10, (frame_width,frame_height))
print('Camera Set Up')
try:
while(True):
ret, frame = cap.read()
if ret == True:
# Write the frame into the file 'output.avi'
out.write(frame)
print('Frame Written')
# Display the resulting frame
#cv2.imshow('frame',frame)
# Press Q on keyboard to stop recording
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Break the loop
else:
break
except KeyboardInterrupt:
pass
# When everything done, release the video capture and video write objects
cap.release()
out.release()
# Closes all the frames
#cv2.destroyAllWindows()
| 25.267857 | 98 | 0.691873 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 691 | 0.488339 |
2ef2497a0bb99f58197f6f6252d8254c97895330 | 2,502 | py | Python | train/tf/nlp/trainer/tf.py | charliemorning/mlws | 8e9bad59ca9f5e774cc1ae7fe454ff3b8a8e1784 | [
"MIT"
] | null | null | null | train/tf/nlp/trainer/tf.py | charliemorning/mlws | 8e9bad59ca9f5e774cc1ae7fe454ff3b8a8e1784 | [
"MIT"
] | null | null | null | train/tf/nlp/trainer/tf.py | charliemorning/mlws | 8e9bad59ca9f5e774cc1ae7fe454ff3b8a8e1784 | [
"MIT"
] | null | null | null | from models.torch.trainer import SupervisedNNModelTrainConfig, Trainer
class KerasTrainer(Trainer):
def __init__(
self,
train_config: SupervisedNNModelTrainConfig
):
super(KerasTrainer, self).__init__(train_config)
def fit(self, train_data, eval_data=None, callbacks=None, verbose=2):
super(KerasTrainer, self).fit(train_data=train_data, eval_data=eval_data)
xs_train, ys_train = train_data
self.model.fit(xs_train, ys_train,
batch_size=self.train_config.train_batch_size,
epochs=self.train_config.epoch,
validation_data=eval_data,
callbacks=callbacks,
verbose=verbose)
def evaluate(self, eval_data):
super(KerasTrainer, self).evaluate(eval_data=eval_data)
xs_test, ys_test = eval_data
self.model.evaluate(xs_test, ys_test, self.train_config.eval_batch_size)
def predict(self, xs_test):
return self.model.predict(xs_test)
def load_model(self, model_file_path):
self.model.load_weights(model_file_path)
class TensorFlowEstimatorTrainer(Trainer):
def __init__(self,
train_config: SupervisedNNModelTrainConfig
):
super(TensorFlowEstimatorTrainer, self).__init__()
self.train_config = train_config
def __input_fn_builder(self, xs_test, ys_test=None):
pass
def __model_fn_builder(self):
pass
def fit(self, xs_train, ys_train):
input_fn = self.__input_fn_builder(xs_train, ys_train)
self.estimator.train(input_fn=input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None)
def evaluate(self, xs_valid, ys_valid):
input_fn = self.__input_fn_builder(xs_valid, ys_valid)
self.estimator.evaluate(input_fn=input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None)
def predict(self, xs_test):
input_fn = self.__input_fn_builder(xs_test)
self.estimator.predict(input_fn=input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None)
def load_model(self, model_file_path):
self.estimator.export_saved_model(model_file_path,
# serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None)
| 37.909091 | 113 | 0.643086 | 2,425 | 0.969225 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | 0.011191 |
2ef4a98fba2216863d25c4500c449a51c8172226 | 1,168 | py | Python | Sliding Window/String Anagrams.py | yalyakoob/Algorithmic-Coding-Challenges | ec1fe427e2eb7f00f56850c5911acc3622a03c55 | [
"MIT"
] | null | null | null | Sliding Window/String Anagrams.py | yalyakoob/Algorithmic-Coding-Challenges | ec1fe427e2eb7f00f56850c5911acc3622a03c55 | [
"MIT"
] | null | null | null | Sliding Window/String Anagrams.py | yalyakoob/Algorithmic-Coding-Challenges | ec1fe427e2eb7f00f56850c5911acc3622a03c55 | [
"MIT"
] | null | null | null | """Given a string and a pattern, find all anagrams of the pattern in the given string.
Write a function to return a list of starting indices of the anagrams of the pattern
in the given string."""
"""Example: String="ppqp", Pattern="pq", Output = [1, 2] """
def find_string_anagrams(str1, pattern):
result_indexes = []
window_start, matched = 0, 0
char_frequency = {}
for char in pattern:
if char not in char_frequency:
char_frequency[char] = 0
char_frequency[char] += 1
for window_end in range(len(str1)):
right_char = str1[window_end]
if right_char in char_frequency:
char_frequency[right_char] -= 1
if char_frequency[right_char] == 0:
matched += 1
if matched == len(pattern):
result_indexes.append(window_start)
if window_end >= len(pattern) - 1:
left_char = str1[window_start]
window_start += 1
if left_char in char_frequency:
if char_frequency[left_char] == 0:
matched -= 1
char_frequency[left_char] += 1
return result_indexes
| 35.393939 | 88 | 0.601884 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 264 | 0.226027 |
2ef62c36e89113dd64975e4991597617554ffa18 | 826 | py | Python | ninja/openapi/urls.py | lsaavedr/django-ninja | caa182007368bb0fed85b184fb0583370e9589b4 | [
"MIT"
] | null | null | null | ninja/openapi/urls.py | lsaavedr/django-ninja | caa182007368bb0fed85b184fb0583370e9589b4 | [
"MIT"
] | null | null | null | ninja/openapi/urls.py | lsaavedr/django-ninja | caa182007368bb0fed85b184fb0583370e9589b4 | [
"MIT"
] | null | null | null | from functools import partial
from django.urls import path
from .views import openapi_json, swagger, home
def get_openapi_urls(api: "NinjaAPI"):
result = [path("", partial(home, api=api), name=f"api-root")]
if api.openapi_url:
result.append(
path(
api.openapi_url.lstrip("/"),
partial(openapi_json, api=api),
name="openapi-json",
)
)
assert (
api.openapi_url != api.docs_url
), "Please use different urls for openapi_url and docs_url"
if api.docs_url:
result.append(
path(
api.docs_url.lstrip("/"),
partial(swagger, api=api),
name="openapi-swagger",
)
)
return result
| 25.8125 | 67 | 0.512107 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 116 | 0.140436 |
2ef92842a29485830b7dc96257442537b474a8cf | 1,243 | py | Python | app/backend/queries/mysql.py | sesam-community/autoconnect | 1f0a4630ca77cc3cf5786de0bb4686b05bd0f0bb | [
"Apache-2.0"
] | null | null | null | app/backend/queries/mysql.py | sesam-community/autoconnect | 1f0a4630ca77cc3cf5786de0bb4686b05bd0f0bb | [
"Apache-2.0"
] | null | null | null | app/backend/queries/mysql.py | sesam-community/autoconnect | 1f0a4630ca77cc3cf5786de0bb4686b05bd0f0bb | [
"Apache-2.0"
] | 1 | 2021-02-18T15:15:01.000Z | 2021-02-18T15:15:01.000Z | def table_pkey(table):
query = f"""SELECT KU.table_name as TABLENAME,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
AND KU.table_name='{table}' ORDER BY KU.TABLE_NAME,KU.ORDINAL_POSITION LIMIT 1;"""
return query
def get_fkey_relations(db_name, table):
query = f"""SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '{db_name}'
AND REFERENCED_TABLE_NAME = '{table}';"""
return query
def get_index_info(db_name):
query = f"""SELECT DISTINCT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = '{db_name}';"""
return query
def get_table_columns_for_indexing(table):
query = f"select column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table}';"
return query
def get_table_ref_idx(index_table, table, index_column, column):
sql = f"SELECT * FROM {index_table}, {table} WHERE {index_table}.{index_column} = {table}.{column} LIMIT 500;"
return sql | 47.807692 | 143 | 0.745776 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 887 | 0.713596 |
2efa90e5edb8969c91a038deb579183818e94e09 | 113 | py | Python | apps.py | MrOerni/django_event_signup | 4fa13d64c5cb20599bc1398a8b474ffc6cbdc012 | [
"MIT"
] | null | null | null | apps.py | MrOerni/django_event_signup | 4fa13d64c5cb20599bc1398a8b474ffc6cbdc012 | [
"MIT"
] | null | null | null | apps.py | MrOerni/django_event_signup | 4fa13d64c5cb20599bc1398a8b474ffc6cbdc012 | [
"MIT"
] | null | null | null | from django.apps import AppConfig
class django_event_signupConfig(AppConfig):
name = 'django_event_signup'
| 18.833333 | 43 | 0.80531 | 76 | 0.672566 | 0 | 0 | 0 | 0 | 0 | 0 | 21 | 0.185841 |
2efb047b94d6832acae0ceb75434aca43e199244 | 515 | py | Python | good_spot/places/migrations/0028_fieldtype_is_shown_in_about_place.py | jasmine92122/NightClubBackend | 7f59129b78baaba0e0c25de2b493033b858f1b00 | [
"MIT"
] | null | null | null | good_spot/places/migrations/0028_fieldtype_is_shown_in_about_place.py | jasmine92122/NightClubBackend | 7f59129b78baaba0e0c25de2b493033b858f1b00 | [
"MIT"
] | 5 | 2020-02-12T03:13:11.000Z | 2022-01-13T01:41:14.000Z | good_spot/places/migrations/0028_fieldtype_is_shown_in_about_place.py | jasmine92122/NightClubBackend | 7f59129b78baaba0e0c25de2b493033b858f1b00 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-29 18:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('places', '0027_auto_20171229_1606'),
]
operations = [
migrations.AddField(
model_name='fieldtype',
name='is_shown_in_about_place',
field=models.BooleanField(default=False, verbose_name='Show in About Place section'),
),
]
| 24.52381 | 97 | 0.646602 | 357 | 0.693204 | 0 | 0 | 0 | 0 | 0 | 0 | 169 | 0.328155 |
2efcacbc0077a1fe4130947c761f4105ee9cbf6b | 1,798 | py | Python | mqtt.py | hansehe/graphql-gateway | f2c4b21f1f509ea3c516d8401d69eb0db618045d | [
"MIT"
] | 3 | 2021-03-05T02:27:44.000Z | 2021-11-07T02:11:28.000Z | mqtt.py | hansehe/graphql-gateway | f2c4b21f1f509ea3c516d8401d69eb0db618045d | [
"MIT"
] | 1 | 2021-01-22T12:54:18.000Z | 2021-01-22T14:02:29.000Z | mqtt.py | hansehe/graphql-gateway | f2c4b21f1f509ea3c516d8401d69eb0db618045d | [
"MIT"
] | null | null | null | import paho.mqtt.client as mqtt
import uuid
import time
# Test code to trig the gateway to update with mqtt.
# Requirements:
# - pip install paho-mqtt
stopMqttClient = False
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print('Connected with result code '+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe('graphql-gateway/update')
client.publish('graphql-gateway/update', 'Update gateway')
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
global stopMqttClient
print(msg.topic+': '+str(msg.payload.decode('utf-8')))
stopMqttClient = True
def on_disconnect(client, userdata: object, rc: int):
print('Disconnected with result code '+str(rc))
def get_client():
clientId = f'mqtt-test-{uuid.uuid1()}'
print(clientId)
client = mqtt.Client(client_id=clientId, transport='websockets')
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
host = 'localhost'
port = 15675
client.ws_set_options(path='/ws', headers=None)
client.username_pw_set('amqp', password='amqp')
client.connect(host, port=port, keepalive=3)
return client
client = get_client()
client.loop_start()
print('Waiting until mqtt message is published and received.')
while not stopMqttClient:
time.sleep(0.1)
client.loop_stop(force=True)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
# client.loop_forever() | 29.966667 | 79 | 0.735261 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 831 | 0.46218 |
2efe4b44afb23c91ba071cfabe00b534c6793018 | 11,863 | py | Python | shrun/runner.py | Nextdoor/shrun | bfc30d535e1e8de1b6ea77b74ca12743c86c7344 | [
"BSD-2-Clause"
] | 1 | 2016-10-22T23:57:17.000Z | 2016-10-22T23:57:17.000Z | shrun/runner.py | Nextdoor/shrun | bfc30d535e1e8de1b6ea77b74ca12743c86c7344 | [
"BSD-2-Clause"
] | 2 | 2016-10-05T22:46:36.000Z | 2016-10-23T14:15:37.000Z | shrun/runner.py | Nextdoor/shrun | bfc30d535e1e8de1b6ea77b74ca12743c86c7344 | [
"BSD-2-Clause"
] | 1 | 2017-07-08T17:57:19.000Z | 2017-07-08T17:57:19.000Z | from builtins import str
import collections
import contextlib
import functools
import itertools
import io
import os
import re
import six
import subprocess
import threading
import tempfile
import time
import traceback
import termcolor
from . import command
from . import parser
COLORS = ['yellow', 'blue', 'red', 'green', 'magenta', 'cyan']
IO_ERROR_RETRY_INTERVAL = 0.1
IO_ERROR_RETRY_ATTEMPTS = 100
RunnerResults = collections.namedtuple('RunnerResults', ('failed', 'running', 'interrupt'))
def print_exceptions(f):
""" Exceptions in threads don't show a traceback so this decorator will dump them to stdout """
@functools.wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
termcolor.cprint(traceback.format_exc(), 'red')
print('-' * 20)
raise
return wrapper
# See https://bugs.python.org/issue1167930 for why thread join ignores interrupts
class InterruptibleThread(threading.Thread):
POLL_FREQ = 0.1
def join(self, timeout=None):
start_time = time.time()
while not timeout or time.time() - start_time < timeout:
super(InterruptibleThread, self).join(timeout or self.POLL_FREQ)
if not self.is_alive():
return
return
class Runner(object):
def __init__(self, tmpdir, environment, retry_interval=None, shell='/bin/bash',
output_timeout=None):
self.tmpdir = tmpdir
self._retry_interval = retry_interval
self._shell = shell
self._output_timeout = output_timeout
self._procs_lock = threading.Lock()
self._procs = []
self._output_lock = threading.Lock()
self._colors = collections.OrderedDict((c, 0) for c in COLORS)
self._color_lock = threading.Lock()
self._environment = environment
self._name_counts = {}
self._dead = False
self.threads_lock = threading.Lock()
self.threads = collections.defaultdict(list)
self._results = {}
def kill_all(self):
""" Kills all running threads """
self._dead = True
while True: # Keep killing procs until the threads terminate
with self.threads_lock:
if any(t.isAlive() for t in itertools.chain(*self.threads.values())):
with self._procs_lock:
for proc in self._procs:
proc.kill()
time.sleep(0.1)
else:
return True
@staticmethod
def print_lines(lines, prefix, color, end=''):
for line in lines:
for _ in range(IO_ERROR_RETRY_ATTEMPTS):
try:
termcolor.cprint(prefix + str(line), color, end=end)
except IOError:
time.sleep(IO_ERROR_RETRY_INTERVAL)
else:
break
@property
def env(self):
env = os.environ.copy()
env.update(self._environment)
return env
@property
def output_timeout(self):
return self._output_timeout
def print_command(self, cmd, prefix='', color='white', message='Running'):
with self._output_lock: # Use a lock to keep output lines separate
lines = cmd.split('\n')
message += ': '
if len(lines) > 1:
lines = [message] + lines + ['---']
else:
lines = [message + lines[0]]
self.print_lines(lines, '{}| '.format(prefix), color=color, end='\n')
@contextlib.contextmanager
def using_color(self):
with self._color_lock:
# Pick the oldest color, favoring colors not in use
color = next(
itertools.chain((c for c, count in self._colors.items() if count == 0),
self._colors.items()))
self._colors[color] = self._colors.pop(color) + 1 # Re-add at the end
try:
yield color
finally:
with self._color_lock:
self._colors[color] -= 1
def create_name(self, name, command):
if name:
command_name = name
else:
command_name = re.search('\w+', command).group(0)
if command_name in self._name_counts:
self._name_counts[command_name] += 1
command_name = '{}_{}'.format(command_name, self._name_counts[command_name])
else:
self._name_counts[command_name] = 0
return command_name
def _run(self, command, name, start_time, color, skip=False, timeout=None, ignore_status=False,
background=False, retries=0, interval=None):
if skip:
self.print_command(command.command, message='Skipping')
return True
interval = interval or self._retry_interval
for attempt in range(0, retries + 1):
command_name = self.create_name(name, command.command)
stdout_path = os.path.join(self.tmpdir, '{}_{}.stdout'.format(command_name, attempt))
stderr_path = os.path.join(self.tmpdir, '{}_{}.stderr'.format(command_name, attempt))
with io.open(stdout_path, 'wb') as stdout_writer, \
io.open(stdout_path, 'rb') as stdout_reader, \
io.open(stderr_path, 'wb') as stderr_writer, \
io.open(stderr_path, 'rb') as stderr_reader:
# See http://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true # noqa
proc = subprocess.Popen(command.command, shell=True, executable=self._shell,
stdout=stdout_writer, stderr=stderr_writer, env=self.env)
with self._procs_lock:
self._procs.append(proc)
prefix = name or str(proc.pid)
self.print_command(
command.command,
message=('Retrying ({})'.format(attempt) if attempt > 0 else 'Running'),
prefix=prefix, color=color)
last_output_time = time.time()
def print_output():
with self._output_lock:
out = stdout_reader.readlines()
err = stderr_reader.readlines()
self.print_lines(out, '{}| '.format(prefix), color)
self.print_lines(err, '{}: '.format(prefix), color)
return bool(out or err)
while proc.poll() is None:
saw_output = print_output()
current_time = time.time()
if (timeout is not None and current_time > last_output_time + timeout and
not background):
proc.kill()
termcolor.cprint('{}! OUTPUT TIMEOUT ({:0.1f}s)'.format(prefix, timeout),
color, attrs=['bold'])
elif saw_output:
last_output_time = current_time
time.sleep(0.05)
print_output()
with self._procs_lock:
self._procs.remove(proc)
passed = not bool(proc.returncode)
if passed or self._dead:
break
elif attempt < retries:
termcolor.cprint('{}| Retrying after {}s'.format(prefix, interval), color)
time.sleep(interval)
elapsed_time = time.time() - start_time
if passed:
message = 'Done'
elif self._dead:
message = 'Terminated'
elif ignore_status:
message = 'Failed'
else:
message = 'FAILED'
termcolor.cprint('{}| {}'.format(prefix, message), attrs=(None if passed else ['bold']),
color=color, end='')
termcolor.cprint(" {}({:0.1f}s)".format(
'(ignored) ' if (not passed and ignore_status) else '', elapsed_time), color=color)
return passed
@functools.wraps(_run)
def run(self, *args, **kwargs):
with self.using_color() as color:
return self._run(*args, color=color, **kwargs)
@print_exceptions # Ensure we see thread exceptions
def _run_job(self, job, job_id, **kwargs):
passed = job.run(**kwargs)
self._results[job_id] = passed
def start(self, cmd, job_id, shared_context):
""" Start a job.
Returns:
A tuple: (Job ID, True/False/None = Success/Failure/Background)
"""
self._results[job_id] = None
job = command.Job(command=cmd)
job.synchronous_prepare(shared_context)
thread = InterruptibleThread(
target=self._run_job,
kwargs=dict(runner=self,
job=job,
job_id=job_id,
shared_context=shared_context))
thread.daemon = True # Ensure this thread doesn't outlive the main thread
# Keep track of all running threads
with self.threads_lock:
if job.background:
self.threads['background'].append(thread)
else:
self.threads['normal'].append(thread)
thread.start()
# Wait if command is synchronous
if not (job.background or job.name):
thread.join()
return self._results.get(job_id)
def finish(self):
""" Waits for non-background jobs. """
# Wait for all the non-background threads to complete
for t in self.threads['normal']:
t.join()
def failures(self):
""" Returns failed jobs """
return [id for id, result in six.iteritems(self._results) if result is False]
def running(self):
""" Returns jobs that are still running jobs """
return [id for id, result in six.iteritems(self._results) if result is None]
def run_commands(commands, retry_interval=None, shell='/bin/bash', tmpdir=None, output_timeout=None,
environment={}):
"""
Args:
commands: A list of commands
retry_interval: Time between retries in seconds
shell: Choice of shell
tmpdir: temporary directory to store output logs
output_timeout: Fail command if it takes longer than this number of seconds
environment: Environment variables to use during command run
Returns:
RunnerResults (a tuple):
A list of failed commands.
A list of commands that are still running.
"""
tmpdir = tmpdir or tempfile.gettempdir()
assert type(commands) == list, (
"Expected command list to be a list but got {}".format(type(commands)))
job_runner = Runner(tmpdir=tmpdir, retry_interval=retry_interval, shell=shell,
environment=environment, output_timeout=output_timeout)
shared_context = command.SharedContext()
started_commands = {}
def results(interrupt=False):
return RunnerResults(
failed=[started_commands[id] for id in job_runner.failures()],
running=[started_commands[id] for id in job_runner.running()],
interrupt=interrupt)
job_id_counter = itertools.count()
try:
for cmd in parser.generate_commands(commands):
job_id = next(job_id_counter)
started_commands[job_id] = cmd
result = job_runner.start(cmd, job_id=job_id, shared_context=shared_context)
if result is False:
break
job_runner.finish()
return results()
except KeyboardInterrupt:
return results(interrupt=True)
finally:
job_runner.kill_all()
| 34.08908 | 134 | 0.571441 | 9,111 | 0.768018 | 500 | 0.042148 | 1,655 | 0.139509 | 0 | 0 | 1,898 | 0.159993 |
2efec4d7645754973922248e12f2e9e6fd0b48f4 | 746 | py | Python | demo/examples/radio/application.py | haizzus/FPGA-radio | 7b7811091bafb2865bccb8aef9f4a53f7b43089e | [
"MIT"
] | 53 | 2016-10-15T17:13:19.000Z | 2022-03-27T02:24:50.000Z | demo/examples/radio/application.py | dawsonjon/FPGA-radio | 7b7811091bafb2865bccb8aef9f4a53f7b43089e | [
"MIT"
] | null | null | null | demo/examples/radio/application.py | dawsonjon/FPGA-radio | 7b7811091bafb2865bccb8aef9f4a53f7b43089e | [
"MIT"
] | 10 | 2017-03-17T11:16:01.000Z | 2022-03-30T05:00:05.000Z | from demo.components.server import server
from chips.api.api import *
def application(chip):
eth = Component("application.c")
eth(
chip,
inputs = {
"eth_in" : chip.inputs["input_eth_rx"],
"am_in" : chip.inputs["input_radio_am"],
"fm_in" : chip.inputs["input_radio_fm"],
"rs232_rx":chip.inputs["input_rs232_rx"],
},
outputs = {
"eth_out" : chip.outputs["output_eth_tx"],
"audio_out" : chip.outputs["output_audio"],
"frequency_out" : chip.outputs["output_radio_frequency"],
"samples_out" : chip.outputs["output_radio_average_samples"],
"rs232_tx":chip.outputs["output_rs232_tx"],
},
)
| 32.434783 | 73 | 0.576408 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 267 | 0.357909 |
2eff7f3dafd4df68788f8af91c9f219b3565485e | 227 | py | Python | Xiecheng/__init__.py | scottyyf/MultiWorker | 4abd361c3053140be6453d6e6e30f5c31a189e79 | [
"Apache-2.0"
] | 2 | 2021-12-14T10:46:14.000Z | 2021-12-14T10:47:00.000Z | Xiecheng/__init__.py | scottyyf/MultiWorker | 4abd361c3053140be6453d6e6e30f5c31a189e79 | [
"Apache-2.0"
] | 9 | 2021-12-06T06:16:15.000Z | 2021-12-20T06:39:50.000Z | Xiecheng/__init__.py | scottyyf/MultiWorker | 4abd361c3053140be6453d6e6e30f5c31a189e79 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: __init__.py.py
Author: Scott Yang(Scott)
Email: yangyingfa@skybility.com
Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved.
Description:
"""
| 20.636364 | 79 | 0.709251 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 223 | 0.982379 |
2effa2910ab4cf2ceba74e75f327552e40cb5a00 | 10,926 | py | Python | learning/pytorch/models/rnn_models.py | thomasehuang/Ithemal-Extension | 821a875962a261de003c6da6e2d3e9b49918d68a | [
"MIT"
] | 105 | 2019-08-05T21:27:33.000Z | 2022-02-16T03:35:10.000Z | learning/pytorch/models/rnn_models.py | thomasehuang/Ithemal-Extension | 821a875962a261de003c6da6e2d3e9b49918d68a | [
"MIT"
] | 16 | 2019-08-06T21:12:11.000Z | 2021-03-22T14:09:21.000Z | learning/pytorch/models/rnn_models.py | thomasehuang/Ithemal-Extension | 821a875962a261de003c6da6e2d3e9b49918d68a | [
"MIT"
] | 25 | 2019-08-11T22:41:57.000Z | 2021-11-10T08:02:50.000Z | #this file contains models that I have tried out for different tasks, which are reusable
#plus it has the training framework for those models given data - each model has its own data requirements
import numpy as np
import common_libs.utilities as ut
import random
import torch.nn as nn
import torch.autograd as autograd
import torch.optim as optim
import torch
import math
class ModelAbs(nn.Module):
"""
Abstract model without the forward method.
lstm for processing tokens in sequence and linear layer for output generation
lstm is a uni-directional single layer lstm
num_classes = 1 - for regression
num_classes = n - for classifying into n classes
"""
def __init__(self, hidden_size, embedding_size, num_classes):
super(ModelAbs, self).__init__()
self.hidden_size = hidden_size
self.name = 'should be overridden'
#numpy array with batchsize, embedding_size
self.embedding_size = embedding_size
self.num_classes = num_classes
#lstm - input size, hidden size, num layers
self.lstm_token = nn.LSTM(self.embedding_size, self.hidden_size)
#hidden state for the rnn
self.hidden_token = self.init_hidden()
#linear layer for regression - in_features, out_features
self.linear = nn.Linear(self.hidden_size, self.num_classes)
def init_hidden(self):
return (autograd.Variable(torch.zeros(1, 1, self.hidden_size)),
autograd.Variable(torch.zeros(1, 1, self.hidden_size)))
#this is to set learnable embeddings
def set_learnable_embedding(self, mode, dictsize, seed = None):
self.mode = mode
if mode != 'learnt':
embedding = nn.Embedding(dictsize, self.embedding_size)
if mode == 'none':
print 'learn embeddings form scratch...'
initrange = 0.5 / self.embedding_size
embedding.weight.data.uniform_(-initrange, initrange)
self.final_embeddings = embedding
elif mode == 'seed':
print 'seed by word2vec vectors....'
embedding.weight.data = torch.FloatTensor(seed)
self.final_embeddings = embedding
else:
print 'using learnt word2vec embeddings...'
self.final_embeddings = seed
#remove any references you may have that inhibits garbage collection
def remove_refs(self, item):
return
class ModelSequentialRNN(ModelAbs):
"""
Prediction at every hidden state of the unrolled rnn.
Input - sequence of tokens processed in sequence by the lstm
Output - predictions at the every hidden state
uses lstm and linear setup of ModelAbs
each hidden state is given as a seperate batch to the linear layer
"""
def __init__(self, hidden_size, embedding_size, num_classes, intermediate):
super(ModelSequentialRNN, self).__init__(hidden_size, embedding_size, num_classes)
if intermediate:
self.name = 'sequential RNN intermediate'
else:
self.name = 'sequential RNN'
self.intermediate = intermediate
def forward(self, item):
self.hidden_token = self.init_hidden()
#convert to tensor
if self.mode == 'learnt':
acc_embeds = []
for token in item.x:
acc_embeds.append(self.final_embeddings[token])
embeds = torch.FloatTensor(acc_embeds)
else:
embeds = self.final_embeddings(torch.LongTensor(item.x))
#prepare for lstm - seq len, batch size, embedding size
seq_len = embeds.shape[0]
embeds_for_lstm = embeds.unsqueeze(1)
#lstm outputs
#output, (h_n,c_n)
#output - (seq_len, batch = 1, hidden_size * directions) - h_t for each t final layer only
#h_n - (layers * directions, batch = 1, hidden_size) - h_t for t = seq_len
#c_n - (layers * directions, batch = 1, hidden_size) - c_t for t = seq_len
#lstm inputs
#input, (h_0, c_0)
#input - (seq_len, batch, input_size)
lstm_out, self.hidden_token = self.lstm_token(embeds_for_lstm, self.hidden_token)
if self.intermediate:
#input to linear - seq_len, hidden_size (seq_len is the batch size for the linear layer)
#output - seq_len, num_classes
values = self.linear(lstm_out[:,0,:].squeeze()).squeeze()
else:
#input to linear - hidden_size
#output - num_classes
values = self.linear(self.hidden_token[0].squeeze()).squeeze()
return values
class ModelHierarchicalRNN(ModelAbs):
"""
Prediction at every hidden state of the unrolled rnn for instructions.
Input - sequence of tokens processed in sequence by the lstm but seperated into instructions
Output - predictions at the every hidden state
lstm predicting instruction embedding for sequence of tokens
lstm_ins processes sequence of instruction embeddings
linear layer process hidden states to produce output
"""
def __init__(self, hidden_size, embedding_size, num_classes, intermediate):
super(ModelHierarchicalRNN, self).__init__(hidden_size, embedding_size, num_classes)
self.hidden_ins = self.init_hidden()
self.lstm_ins = nn.LSTM(self.hidden_size, self.hidden_size)
if intermediate:
self.name = 'hierarchical RNN intermediate'
else:
self.name = 'hierarchical RNN'
self.intermediate = intermediate
def copy(self, model):
self.linear = model.linear
self.lstm_token = model.lstm_token
self.lstm_ins = model.lstm_ins
def forward(self, item):
self.hidden_token = self.init_hidden()
self.hidden_ins = self.init_hidden()
ins_embeds = autograd.Variable(torch.zeros(len(item.x),self.embedding_size))
for i, ins in enumerate(item.x):
if self.mode == 'learnt':
acc_embeds = []
for token in ins:
acc_embeds.append(self.final_embeddings[token])
token_embeds = torch.FloatTensor(acc_embeds)
else:
token_embeds = self.final_embeddings(torch.LongTensor(ins))
#token_embeds = torch.FloatTensor(ins)
token_embeds_lstm = token_embeds.unsqueeze(1)
out_token, hidden_token = self.lstm_token(token_embeds_lstm,self.hidden_token)
ins_embeds[i] = hidden_token[0].squeeze()
ins_embeds_lstm = ins_embeds.unsqueeze(1)
out_ins, hidden_ins = self.lstm_ins(ins_embeds_lstm, self.hidden_ins)
if self.intermediate:
values = self.linear(out_ins[:,0,:]).squeeze()
else:
values = self.linear(hidden_ins[0].squeeze()).squeeze()
return values
class ModelHierarchicalRNNRelational(ModelAbs):
def __init__(self, embedding_size, num_classes):
super(ModelHierarchicalRNNRelational, self).__init__(embedding_size, num_classes)
self.hidden_ins = self.init_hidden()
self.lstm_ins = nn.LSTM(self.hidden_size, self.hidden_size)
self.linearg1 = nn.Linear(2 * self.hidden_size, self.hidden_size)
self.linearg2 = nn.Linear(self.hidden_size, self.hidden_size)
def forward(self, item):
self.hidden_token = self.init_hidden()
self.hidden_ins = self.init_hidden()
ins_embeds = autograd.Variable(torch.zeros(len(item.x),self.hidden_size))
for i, ins in enumerate(item.x):
if self.mode == 'learnt':
acc_embeds = []
for token in ins:
acc_embeds.append(self.final_embeddings[token])
token_embeds = torch.FloatTensor(acc_embeds)
else:
token_embeds = self.final_embeddings(torch.LongTensor(ins))
#token_embeds = torch.FloatTensor(ins)
token_embeds_lstm = token_embeds.unsqueeze(1)
out_token, hidden_token = self.lstm_token(token_embeds_lstm,self.hidden_token)
ins_embeds[i] = hidden_token[0].squeeze()
ins_embeds_lstm = ins_embeds.unsqueeze(1)
out_ins, hidden_ins = self.lstm_ins(ins_embeds_lstm, self.hidden_ins)
seq_len = len(item.x)
g_variable = autograd.Variable(torch.zeros(self.hidden_size))
for i in range(seq_len):
for j in range(i,seq_len):
concat = torch.cat((out_ins[i].squeeze(),out_ins[j].squeeze()),0)
g1 = nn.functional.relu(self.linearg1(concat))
g2 = nn.functional.relu(self.linearg2(g1))
g_variable += g2
output = self.linear(g_variable)
return output
class ModelSequentialRNNComplex(nn.Module):
"""
Prediction using the final hidden state of the unrolled rnn.
Input - sequence of tokens processed in sequence by the lstm
Output - the final value to be predicted
we do not derive from ModelAbs, but instead use a bidirectional, multi layer
lstm and a deep MLP with non-linear activation functions to predict the final output
"""
def __init__(self, embedding_size):
super(ModelFinalHidden, self).__init__()
self.name = 'sequential RNN'
self.hidden_size = 256
self.embedding_size = embedding_size
self.layers = 2
self.directions = 1
self.is_bidirectional = (self.directions == 2)
self.lstm_token = torch.nn.LSTM(input_size = self.embedding_size,
hidden_size = self.hidden_size,
num_layers = self.layers,
bidirectional = self.is_bidirectional)
self.linear1 = nn.Linear(self.layers * self. directions * self.hidden_size, self.hidden_size)
self.linear2 = nn.Linear(self.hidden_size,1)
self.hidden_token = self.init_hidden()
def init_hidden(self):
return (autograd.Variable(torch.zeros(self.layers * self.directions, 1, self.hidden_size)),
autograd.Variable(torch.zeros(self.layers * self.directions, 1, self.hidden_size)))
def forward(self, item):
self.hidden_token = self.init_hidden()
#convert to tensor
if self.mode == 'learnt':
acc_embeds = []
for token in item.x:
acc_embeds.append(self.final_embeddings[token])
embeds = torch.FloatTensor(acc_embeds)
else:
embeds = self.final_embeddings(torch.LongTensor(item.x))
#prepare for lstm - seq len, batch size, embedding size
seq_len = embeds.shape[0]
embeds_for_lstm = embeds.unsqueeze(1)
lstm_out, self.hidden_token = self.lstm_token(embeds_for_lstm, self.hidden_token)
f1 = nn.functional.relu(self.linear1(self.hidden_token[0].squeeze().view(-1)))
f2 = self.linear2(f1)
return f2
| 34.358491 | 106 | 0.645158 | 10,538 | 0.964488 | 0 | 0 | 0 | 0 | 0 | 0 | 2,836 | 0.259564 |
2c00b39003b7029e872ee5035a075a953fa079f3 | 9,669 | py | Python | ddsc/config.py | Duke-GCB/DukeDSClient | 7f119a5ee2e674e8deaff1f080caed1953c5cc61 | [
"MIT"
] | 4 | 2020-06-18T12:30:13.000Z | 2020-10-12T21:25:54.000Z | ddsc/config.py | Duke-GCB/DukeDSClient | 7f119a5ee2e674e8deaff1f080caed1953c5cc61 | [
"MIT"
] | 239 | 2016-02-18T14:44:08.000Z | 2022-03-11T14:38:56.000Z | ddsc/config.py | Duke-GCB/DukeDSClient | 7f119a5ee2e674e8deaff1f080caed1953c5cc61 | [
"MIT"
] | 10 | 2016-02-22T15:01:28.000Z | 2022-02-21T22:46:26.000Z | """ Global configuration for the utility based on config files and environment variables."""
import os
import re
import math
import yaml
import multiprocessing
from ddsc.core.util import verify_file_private
from ddsc.exceptions import DDSUserException
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
GLOBAL_CONFIG_FILENAME = '/etc/ddsclient.conf'
LOCAL_CONFIG_FILENAME = '~/.ddsclient'
LOCAL_CONFIG_ENV = 'DDSCLIENT_CONF'
DUKE_DATA_SERVICE_URL = 'https://api.dataservice.duke.edu/api/v1'
D4S2_SERVICE_URL = 'https://datadelivery.genome.duke.edu/api/v1'
MB_TO_BYTES = 1024 * 1024
DDS_DEFAULT_UPLOAD_CHUNKS = 100 * MB_TO_BYTES
DDS_DEFAULT_DOWNLOAD_CHUNK_SIZE = 20 * MB_TO_BYTES
AUTH_ENV_KEY_NAME = 'DUKE_DATA_SERVICE_AUTH'
# when uploading skip .DS_Store, our key file, and ._ (resource fork metadata)
FILE_EXCLUDE_REGEX_DEFAULT = '^\.DS_Store$|^\.ddsclient$|^\.\_'
MAX_DEFAULT_WORKERS = 8
GET_PAGE_SIZE_DEFAULT = 100 # fetch 100 items per page
DEFAULT_FILE_DOWNLOAD_RETRIES = 5
DEFAULT_BACKING_STORAGE = "dds"
def get_user_config_filename():
user_config_filename = os.environ.get(LOCAL_CONFIG_ENV)
if user_config_filename:
return user_config_filename
else:
return LOCAL_CONFIG_FILENAME
def create_config(allow_insecure_config_file=False):
"""
Create config based on /etc/ddsclient.conf and ~/.ddsclient.conf($DDSCLIENT_CONF)
:param allow_insecure_config_file: bool: when true we will not check ~/.ddsclient permissions.
:return: Config with the configuration to use for DDSClient.
"""
config = Config()
config.add_properties(GLOBAL_CONFIG_FILENAME)
user_config_filename = get_user_config_filename()
if user_config_filename == LOCAL_CONFIG_FILENAME and not allow_insecure_config_file:
verify_file_private(user_config_filename)
config.add_properties(user_config_filename)
return config
def default_num_workers():
"""
Return the number of workers to use as default if not specified by a config file.
Returns the number of CPUs or MAX_DEFAULT_WORKERS (whichever is less).
"""
return min(multiprocessing.cpu_count(), MAX_DEFAULT_WORKERS)
class Config(object):
"""
Global configuration object based on config files an environment variables.
"""
URL = 'url' # specifies the dataservice host we are connecting too
USER_KEY = 'user_key' # user key: /api/v1/current_user/api_key
AGENT_KEY = 'agent_key' # software_agent key: /api/v1/software_agents/{id}/api_key
AUTH = 'auth' # Holds actual auth token for connecting to the dataservice
UPLOAD_BYTES_PER_CHUNK = 'upload_bytes_per_chunk' # bytes per chunk we will upload
UPLOAD_WORKERS = 'upload_workers' # how many worker processes used for uploading
DOWNLOAD_WORKERS = 'download_workers' # how many worker processes used for downloading
DOWNLOAD_BYTES_PER_CHUNK = 'download_bytes_per_chunk' # bytes per chunk we will download
DEBUG_MODE = 'debug' # show stack traces
D4S2_URL = 'd4s2_url' # url for use with the D4S2 (share/deliver service)
FILE_EXCLUDE_REGEX = 'file_exclude_regex' # allows customization of which filenames will be uploaded
GET_PAGE_SIZE = 'get_page_size' # page size used for GET pagination requests
STORAGE_PROVIDER_ID = 'storage_provider_id' # setting to override the default storage provider
FILE_DOWNLOAD_RETRIES = 'file_download_retries' # number of times to retry a failed file download
BACKING_STORAGE = 'backing_storage' # backing storage either "dds" or "azure"
def __init__(self):
self.values = {}
def add_properties(self, filename):
"""
Add properties to config based on filename replacing previous values.
:param filename: str path to YAML file to pull top level properties from
"""
filename = os.path.expanduser(filename)
if os.path.exists(filename):
with open(filename, 'r') as yaml_file:
config_data = yaml.safe_load(yaml_file)
if config_data:
self.update_properties(config_data)
else:
raise DDSUserException("Error: Empty config file {}".format(filename))
def update_properties(self, new_values):
"""
Add items in new_values to the internal list replacing existing values.
:param new_values: dict properties to set
"""
self.values = dict(self.values, **new_values)
@property
def url(self):
"""
Specifies the dataservice host we are connecting too.
:return: str url to a dataservice host
"""
return self.values.get(Config.URL, DUKE_DATA_SERVICE_URL)
def get_portal_url_base(self):
"""
Determine root url of the data service from the url specified.
:return: str root url of the data service (eg: https://dataservice.duke.edu)
"""
api_url = urlparse(self.url).hostname
portal_url = re.sub('^api\.', '', api_url)
portal_url = re.sub(r'api', '', portal_url)
return portal_url
@property
def user_key(self):
"""
Contains user key user created from /api/v1/current_user/api_key used to create a login token.
:return: str user key that can be used to create an auth token
"""
return self.values.get(Config.USER_KEY, None)
@property
def agent_key(self):
"""
Contains user agent key created from /api/v1/software_agents/{id}/api_key used to create a login token.
:return: str agent key that can be used to create an auth token
"""
return self.values.get(Config.AGENT_KEY, None)
@property
def auth(self):
"""
Contains the auth token for use with connecting to the dataservice.
:return:
"""
return self.values.get(Config.AUTH, os.environ.get(AUTH_ENV_KEY_NAME, None))
@property
def upload_bytes_per_chunk(self):
"""
Return the bytes per chunk to be sent to external store.
:return: int bytes per upload chunk
"""
value = self.values.get(Config.UPLOAD_BYTES_PER_CHUNK, DDS_DEFAULT_UPLOAD_CHUNKS)
return Config.parse_bytes_str(value)
@property
def upload_workers(self):
"""
Return the number of parallel works to use when uploading a file.
:return: int number of workers. Specify None or 1 to disable parallel uploading
"""
return self.values.get(Config.UPLOAD_WORKERS, default_num_workers())
@property
def download_workers(self):
"""
Return the number of parallel works to use when downloading a file.
:return: int number of workers. Specify None or 1 to disable parallel downloading
"""
default_workers = int(math.ceil(default_num_workers()))
return self.values.get(Config.DOWNLOAD_WORKERS, default_workers)
@property
def download_bytes_per_chunk(self):
return self.values.get(Config.DOWNLOAD_BYTES_PER_CHUNK, DDS_DEFAULT_DOWNLOAD_CHUNK_SIZE)
@property
def debug_mode(self):
"""
Return true if we should show stack traces on error.
:return: boolean True if debugging is enabled
"""
return self.values.get(Config.DEBUG_MODE, False)
@property
def d4s2_url(self):
"""
Returns url for D4S2 service or '' if not setup.
:return: str url
"""
return self.values.get(Config.D4S2_URL, D4S2_SERVICE_URL)
@staticmethod
def parse_bytes_str(value):
"""
Given a value return the integer number of bytes it represents.
Trailing "MB" causes the value multiplied by 1024*1024
:param value:
:return: int number of bytes represented by value.
"""
if type(value) == str:
if "MB" in value:
return int(value.replace("MB", "")) * MB_TO_BYTES
else:
return int(value)
else:
return value
@property
def file_exclude_regex(self):
"""
Returns regex that should be used to filter out filenames.
:return: str: regex that when matches we should exclude a file from uploading.
"""
return self.values.get(Config.FILE_EXCLUDE_REGEX, FILE_EXCLUDE_REGEX_DEFAULT)
@property
def page_size(self):
"""
Returns the page size used to fetch paginated lists from DukeDS.
For DukeDS APIs that fail related to timeouts lowering this value can help.
:return:
"""
return self.values.get(Config.GET_PAGE_SIZE, GET_PAGE_SIZE_DEFAULT)
@property
def storage_provider_id(self):
"""
Returns storage provider id from /api/v1/storage_providers DukeDS API or None to use default.
:return: str: uuid of storage provider
"""
return self.values.get(Config.STORAGE_PROVIDER_ID, None)
@property
def file_download_retries(self):
"""
Returns number of times to retry failed external file downloads
:return: int: number of retries allowed before failure
"""
return self.values.get(Config.FILE_DOWNLOAD_RETRIES, DEFAULT_FILE_DOWNLOAD_RETRIES)
@property
def backing_storage(self):
return self.values.get(Config.BACKING_STORAGE, DEFAULT_BACKING_STORAGE)
| 39.145749 | 114 | 0.664288 | 7,476 | 0.773193 | 0 | 0 | 4,424 | 0.457545 | 0 | 0 | 4,614 | 0.477195 |
2c01d7b503296aad5ad328001d1b93bd84cc4e39 | 12,781 | py | Python | keras_wraper_ensemble.py | asultan123/ADP | 12a0875d84a6d1b660a4657e0276e7a0511487fd | [
"Apache-2.0"
] | null | null | null | keras_wraper_ensemble.py | asultan123/ADP | 12a0875d84a6d1b660a4657e0276e7a0511487fd | [
"Apache-2.0"
] | null | null | null | keras_wraper_ensemble.py | asultan123/ADP | 12a0875d84a6d1b660a4657e0276e7a0511487fd | [
"Apache-2.0"
] | null | null | null | """
Model construction utilities based on keras
"""
import warnings
from distutils.version import LooseVersion
import tensorflow.keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Flatten
# from cleverhans.model import Model, NoSuchLayerError
import tensorflow as tf
from abc import ABCMeta
class NoSuchLayerError(ValueError):
"""Raised when a layer that does not exist is requested."""
class AModel(object):
"""
An abstract interface for model wrappers that exposes model symbols
needed for making an attack. This abstraction removes the dependency on
any specific neural network package (e.g. Keras) from the core
code of CleverHans. It can also simplify exposing the hidden features of a
model when a specific package does not directly expose them.
"""
__metaclass__ = ABCMeta
O_LOGITS, O_PROBS, O_FEATURES = "logits probs features".split()
def __init__(
self, scope=None, nb_classes=None, hparams=None, needs_dummy_fprop=False
):
"""
Constructor.
:param scope: str, the name of model.
:param nb_classes: integer, the number of classes.
:param hparams: dict, hyper-parameters for the model.
:needs_dummy_fprop: bool, if True the model's parameters are not
created until fprop is called.
"""
self.scope = scope or self.__class__.__name__
self.nb_classes = nb_classes
self.hparams = hparams or {}
self.needs_dummy_fprop = needs_dummy_fprop
def __call__(self, *args, **kwargs):
"""
For compatibility with functions used as model definitions (taking
an input tensor and returning the tensor giving the output
of the model on that input).
"""
warnings.warn(
"Model.__call__ is deprecated. "
"The call is ambiguous as to whether the output should "
"be logits or probabilities, and getting the wrong one "
"can cause serious problems. "
"The output actually is probabilities, which are a very "
"dangerous thing to use as part of any interface for "
"cleverhans, because softmax probabilities are prone "
"to gradient masking."
"On or after 2019-04-24, this method will change to raise "
"an exception explaining why Model.__call__ should not be "
"used."
)
return self.get_probs(*args, **kwargs)
def get_logits(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
"""
outputs = self.fprop(x, **kwargs)
if self.O_LOGITS in outputs:
return outputs[self.O_LOGITS]
raise NotImplementedError(
str(type(self)) + "must implement `get_logits`"
" or must define a " + self.O_LOGITS + " output in `fprop`"
)
def get_predicted_class(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
"""
return tf.argmax(self.get_logits(x, **kwargs), axis=1)
def get_probs(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
"""
d = self.fprop(x, **kwargs)
if self.O_PROBS in d:
output = d[self.O_PROBS]
min_prob = tf.reduce_min(output)
max_prob = tf.reduce_max(output)
asserts = [
utils_tf.assert_greater_equal(min_prob, tf.cast(0.0, min_prob.dtype)),
utils_tf.assert_less_equal(max_prob, tf.cast(1.0, min_prob.dtype)),
]
with tf.control_dependencies(asserts):
output = tf.identity(output)
return output
elif self.O_LOGITS in d:
return tf.nn.softmax(logits=d[self.O_LOGITS])
else:
raise ValueError("Cannot find probs or logits.")
def fprop(self, x, **kwargs):
"""
Forward propagation to compute the model outputs.
:param x: A symbolic representation of the network input
:return: A dictionary mapping layer names to the symbolic
representation of their output.
"""
raise NotImplementedError("`fprop` not implemented.")
def get_params(self):
"""
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
"""
if hasattr(self, "params"):
return list(self.params)
# Catch eager execution and assert function overload.
try:
if tf.executing_eagerly():
raise NotImplementedError(
"For Eager execution - get_params " "must be overridden."
)
except AttributeError:
pass
# For graph-based execution
scope_vars = tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES, self.scope + "/"
)
if len(scope_vars) == 0:
self.make_params()
scope_vars = tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES, self.scope + "/"
)
assert len(scope_vars) > 0
# Make sure no parameters have been added or removed
if hasattr(self, "num_params"):
if self.num_params != len(scope_vars):
print("Scope: ", self.scope)
print("Expected " + str(self.num_params) + " variables")
print("Got " + str(len(scope_vars)))
for var in scope_vars:
print("\t" + str(var))
assert False
else:
self.num_params = len(scope_vars)
return scope_vars
def make_params(self):
"""
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_fprop:
if hasattr(self, "_dummy_input"):
return
self._dummy_input = self.make_input_placeholder()
self.fprop(self._dummy_input)
def get_layer_names(self):
"""Return the list of exposed layers for this model."""
raise NotImplementedError
def get_layer(self, x, layer, **kwargs):
"""Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
"""
return self.fprop(x, **kwargs)[layer]
def make_input_placeholder(self):
"""Create and return a placeholder representing an input to the model.
This method should respect context managers (e.g. "with tf.device")
and should not just return a reference to a single pre-created
placeholder.
"""
raise NotImplementedError(
str(type(self)) + " does not implement " "make_input_placeholder"
)
def make_label_placeholder(self):
"""Create and return a placeholder representing class labels.
This method should respect context managers (e.g. "with tf.device")
and should not just return a reference to a single pre-created
placeholder.
"""
raise NotImplementedError(
str(type(self)) + " does not implement " "make_label_placeholder"
)
def __hash__(self):
return hash(id(self))
def __eq__(self, other):
return self is other
class KerasModelWrapper(AModel):
"""
An implementation of `Model` that wraps a Keras model. It
specifically exposes the hidden features of a model by creating new models.
The symbolic graph is reused and so there is little overhead. Splitting
in-place operations can incur an overhead.
"""
def __init__(self, model, num_class=10):
"""
Create a wrapper for a Keras model
:param model: A Keras model
"""
super(KerasModelWrapper, self).__init__()
if model is None:
raise ValueError('model argument must be supplied.')
self.model = model
self.keras_model = None
self.num_classes = num_class
def _get_softmax_name(self):
"""
Looks for the name of the softmax layer.
:return: Softmax layer name
"""
for layer in self.model.layers:
cfg = layer.get_config()
if cfg['name'] == 'average_1':
return layer.name
raise Exception("No softmax layers found")
def _get_logits_name(self):
"""
Looks for the name of the layer producing the logits.
:return: name of layer producing the logits
"""
softmax_name = self._get_softmax_name()
softmax_layer = self.model.get_layer(softmax_name)
if not isinstance(softmax_layer, Activation):
# In this case, the activation is part of another layer
return softmax_name
if hasattr(softmax_layer, 'inbound_nodes'):
warnings.warn(
"Please update your version to keras >= 2.1.3; "
"support for earlier keras versions will be dropped on "
"2018-07-22")
node = softmax_layer.inbound_nodes[0]
else:
node = softmax_layer._inbound_nodes[0]
logits_name = node.inbound_layers[0].name
return logits_name
def get_logits(self, x):
"""
:param x: A symbolic representation of the network input.
:return: A symbolic representation of the logits
"""
# logits_name = self._get_logits_name()
# logits_layer = self.get_layer(x, logits_name)
# # Need to deal with the case where softmax is part of the
# # logits layer
# if logits_name == self._get_softmax_name():
# softmax_logit_layer = self.get_layer(x, logits_name)
# # The final op is the softmax. Return its input
# logits_layer = softmax_logit_layer._op.inputs[0]
prob = self.get_probs(x)
logits = tf.log(prob)
return logits
def get_probs(self, x):
"""
:param x: A symbolic representation of the network input.
:return: A symbolic representation of the probs
"""
return self.model(x)
def get_layer_names(self):
"""
:return: Names of all the layers kept by Keras
"""
layer_names = [x.name for x in self.model.layers]
return layer_names
def fprop(self, x):
"""
Exposes all the layers of the model returned by get_layer_names.
:param x: A symbolic representation of the network input
:return: A dictionary mapping layer names to the symbolic
representation of their output.
"""
from tensorflow.keras.models import Model as KerasModel
if self.keras_model is None:
# Get the input layer
new_input = self.model.get_input_at(0)
# Make a new model that returns each of the layers as output
out_layers = [x_layer.output for x_layer in self.model.layers]
self.keras_model = KerasModel(new_input, out_layers)
# and get the outputs for that model on the input x
outputs = self.keras_model(x)
# Keras only returns a list for outputs of length >= 1, if the model
# is only one layer, wrap a list
if len(self.model.layers) == 1:
outputs = [outputs]
# compute the dict to return
fprop_dict = dict(zip(self.get_layer_names(), outputs))
return fprop_dict
def get_layer(self, x, layer):
"""
Expose the hidden features of a model given a layer name.
:param x: A symbolic representation of the network input
:param layer: The name of the hidden layer to return features at.
:return: A symbolic representation of the hidden features
:raise: NoSuchLayerError if `layer` is not in the model.
"""
# Return the symbolic representation for this layer.
output = self.fprop(x)
try:
requested = output[layer]
except KeyError:
raise NoSuchLayerError()
return requested
| 35.30663 | 86 | 0.617323 | 12,423 | 0.97199 | 0 | 0 | 0 | 0 | 0 | 0 | 6,525 | 0.510523 |
2c0300ca0658c1688971286bba3169afb2699074 | 1,911 | py | Python | controllers/task_handler.py | MuhammadWaleedUsman/PythonTornadoDockerTraefikMySql | 29d7a72c30a96f4eaf9174fdf29fd06fb48e7974 | [
"Apache-2.0"
] | null | null | null | controllers/task_handler.py | MuhammadWaleedUsman/PythonTornadoDockerTraefikMySql | 29d7a72c30a96f4eaf9174fdf29fd06fb48e7974 | [
"Apache-2.0"
] | null | null | null | controllers/task_handler.py | MuhammadWaleedUsman/PythonTornadoDockerTraefikMySql | 29d7a72c30a96f4eaf9174fdf29fd06fb48e7974 | [
"Apache-2.0"
] | null | null | null | from .db_handler import cursor
from tornado import concurrent
import tornado.web
executor = concurrent.futures.ThreadPoolExecutor(8)
def start_task(arg):
print("The Task has started") # Async task
return True
def stop_task(arg):
print("The Task has stopped") # Async task
return True
class HandlerStart(tornado.web.RequestHandler):
def post(self, username):
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
user_names = []
if users:
keys = ("id", "name", "email")
list_of_users = [dict(zip(keys, values)) for values in users]
for user in list_of_users:
user_names.append(user['name'])
if username in set(user_names):
flag = True
else:
flag = False
else:
flag = False
if flag:
executor.submit(start_task, username)
response = "started"
else:
response = "User Doesn't exist"
self.write('request accepted |' + str(username) + ' | ' + str(response))
class HandlerStop(tornado.web.RequestHandler):
def post(self, username):
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
user_names = []
if users:
keys = ("id", "name", "email")
list_of_users = [dict(zip(keys, values)) for values in users]
for user in list_of_users:
user_names.append(user['name'])
if username in set(user_names):
flag = True
else:
flag = False
else:
flag = False
if flag:
executor.submit(stop_task, username)
response = "stopped"
else:
response = "User Doesn't exist"
self.write('request accepted |' + str(username) + ' | ' + str(response))
| 29.4 | 80 | 0.55259 | 1,600 | 0.837258 | 0 | 0 | 0 | 0 | 0 | 0 | 264 | 0.138148 |
2c0432e1308cc8fe3207fb79660271c04e458a71 | 666 | py | Python | Python/WordBreak.py | Jspsun/LEETCodePractice | 9dba8c0441201a188b93e4d39a0a9b7602857a5f | [
"MIT"
] | 3 | 2017-10-14T19:49:28.000Z | 2019-01-12T21:51:11.000Z | Python/WordBreak.py | Jspsun/LEETCodePractice | 9dba8c0441201a188b93e4d39a0a9b7602857a5f | [
"MIT"
] | null | null | null | Python/WordBreak.py | Jspsun/LEETCodePractice | 9dba8c0441201a188b93e4d39a0a9b7602857a5f | [
"MIT"
] | 5 | 2017-02-06T19:10:23.000Z | 2020-12-19T01:58:10.000Z | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [False for i in xrange(len(s)+1)]
dp[0] = True
for i in range(1, len(s)+1):
for w in wordDict:
if len(w)<= i and dp[i-len(w)]:
if s[i-len(w):i]==w:
dp[i] = True
break
return dp[-1]
print Solution().wordBreak("leetcode", ["leet","code"])==True
print Solution().wordBreak("leetcode", ["wowwwww","caode"])==False
print Solution().wordBreak("aaaaaaa", ["aaaa","aa"])==False | 31.714286 | 66 | 0.478979 | 476 | 0.714715 | 0 | 0 | 0 | 0 | 0 | 0 | 158 | 0.237237 |
2c0648d5d20facaf4eda0597999791fd836d5caa | 9,523 | py | Python | apps/mixins/db_admin/datatables_client.py | Eudorajab1/websaw | 7c3a369789d23ac699868fa1eff6c63e3e5c1e36 | [
"MIT"
] | 1 | 2022-03-29T00:12:12.000Z | 2022-03-29T00:12:12.000Z | apps/mixins/db_admin/datatables_client.py | Eudorajab1/websaw | 7c3a369789d23ac699868fa1eff6c63e3e5c1e36 | [
"MIT"
] | null | null | null | apps/mixins/db_admin/datatables_client.py | Eudorajab1/websaw | 7c3a369789d23ac699868fa1eff6c63e3e5c1e36 | [
"MIT"
] | null | null | null | from websaw.core import Fixture
from yatl.helpers import INPUT, H1, A, DIV, SPAN, XML
from .datatables_utils import DtGui
mygui=DtGui()
from pprint import pprint
import json
# ################################################################
# Grid object (replaced SQLFORM.grid) using Datatables
# ################################################################
class Grid(object):
"""
Usage in websaw controller:
def index():
grid = Grid(db.thing, record=1)
return dict(grid=grid)
Arguments:
- ctx current context
- db name we are using as defined in DBRegistry
- table: a DAL table or a list of fields (equivalent to old SQLFORM.factory)
- fields: a list of fields to display
- create: set to False to disable creation of new record
- editable: set to False to disallow editing of recordrsd seletion
- deletable: set to False to disallow deleting of recordrsd seletion
- links: list of addtional links to other tables
- form_name: the optional name for this grid
- serverside: set to False for client side processing
"""
def __init__(self,
ctx = None,
cdb = None,
table = None,
fields=None,
create=True,
editable=True,
deletable=True,
viewable=True,
upload=False,
download=False,
back=None,
links=None,
page_title=None,
formstyle='',
form_name=False,
serverside=True,
show_id=True,
hide=[],
order=['0', 'asc'],
extended_search=False):
self.ctx = ctx
self.cdb = cdb
self.table = table
self.create=create
self.editable=editable
self.deletable=deletable
self.viewable=viewable
self.back=back
self.links=links
self.readonly = False
self.upload=upload
self.download=download
self.page_title=page_title
self.formstyle=formstyle
self.serverside=serverside
self.form_name = form_name or table._tablename
self.hidden = False
self.formkey = None
self.cached_helper = None
self.show_id = show_id
self.hide=hide
self.order=order
self.extended_search=extended_search
self.db = self.ctx.ask(self.cdb)
self.ctx.session['query'] = self.ctx.session.get('query', '')
if self.ctx.session['query'] :
print(self.ctx.session['query'])
else:
self.ctx.session['query'] = ''
if isinstance(table, list):
dbio = False
# mimic a table from a list of fields without calling define_table
form_name = form_name or 'none'
for field in table:
field.tablename = getattr(field,'tablename',form_name)
if isinstance(fields, list):
self.fields=fields
else:
self.fields=table.fields
cal = self.ctx.request.url.split("/")
#print('CAL is ', cal)
scal = cal[4].split("?")
self.app = cal[3]
self.func = scal[0]
def build_headers(self):
#call_header = ctx.request.headers.get('Referer')
headers= ''
db = self.db
hide = self.hide
t = self.table
self.col = ",".join(self.fields)
self.cols=[]
self.hdrs=[]
for f in self.fields:
if f in hide:
continue
if f == 'id':
if self.show_id:
self.cols.append({'data': f})
self.hdrs.append(db[t][f].label)
continue
else:
continue
self.cols.append({'data': f})
self.hdrs.append(db[t][f].label)
self.hdrs.append('Action')
self.cols.append({'data': 'btns'})
headers = self.hdrs
return headers
def get_fields(self):
return self.fields
def form_buttons(self):
btns = []
#a="""
#<button id="btToggleDisplay" class="btn btn-outline-info btn-sm"><i class="fa fa-table" aria-hidden="true"></i>
#<i class="fas fa-arrows-alt-h " aria-hidden="true"></i> <i class="far fa-address-card " aria-hidden="true"></i></button>
#"""
if self.download:
d_button = mygui.get_dt_button('download', self.ctx.URL('index', vars={"caller": self.func, "table" : self.table._tablename}), "Export", 'Export')
btns.append(d_button)
if self.upload:
u_button = mygui.get_dt_button('upload_csv', self.ctx.URL('index', vars={"caller": self.func, "table" : self.table._tablename}), "Import", "Import")
btns.append(u_button)
if self.create:
a_button = mygui.get_dt_button('add', self.ctx.URL('add_rec', vars={"cdb":self.cdb, "caller": self.func, "table" : self.table._tablename}), "Add", 'Add')
btns.append(a_button)
if self.back:
btns.append(self.back)
#btns.append(a)
if not self.page_title:
if not self.table._plural:
b_str='<span class="subtitle"> %s</span>' % self.table
else:
b_str='<span class="subtitle"> %s</span>' % self.table._plural
else:
b_str='<span class="subtitle"> %s</span>' % self.page_title
for b in btns:
b_str += '<span class="is-pulled-right"> %s</span>' % XML(b)
return b_str
def row_buttons(self):
r_btns = []
row_buttons=[]
if self.links:
for l in self.links:
#print('LINK IS', l)
r_btns.append('link')
row_buttons.append({'name': l['name'], 'cdb':self.cdb, 'caller': self.func, 'func':l['func'], 'fk':l['fk'],'id':'id'})
if self.viewable:
r_btns.append('view')
row_buttons.append({"name":"View", 'cdb':self.cdb, "caller": self.func, "func":"view_rec", "id": "id"})
if self.editable:
r_btns.append('edit')
row_buttons.append({"name":"Edit",'cdb':self.cdb,"caller": self.func, "func":"edit_rec", "id": "id"})
if self.deletable:
r_btns.append('delete')
row_buttons.append({"name":"Delete",'cdb':self.cdb,"caller": self.func, "func":"del_rec", "id": "id"})
self.r_buts = ",".join(r_btns)
return row_buttons
def build_j_script(self):
row_buttons = self.row_buttons()
name = self.table
js="""
<script>
$(document).ready(function() {
var table = $('#%s').DataTable( {
"processing": true,
"serverSide": true,
"autoWidth": false,
"scrollX": true,
"ajax": {
"url": "%s",
"data": function ( d ) {
d.table = "%s"
d.cols = "%s"
d.row_buttons = "%s"
d.row_button_list = %s
d.caller = "%s"
d.hide = "%s"
d.cdb = "%s"
},
},
"columns": %s,
"order" : [%s]
});
$('#btToggleDisplay').on('click', function () {
$("#generic thead").toggle()
$("#generic").toggleClass('cards')
if($("#generic").hasClass("cards")){
// Create an array of labels containing all table headers
var labels = [];
$("#generic").find("thead th").each(function() {
labels.push($(this).text());
});
// Add data-label attribute to each cell
$("#generic").find("tbody tr").each(function() {
$(this).find("td").each(function(column) {
$(this).attr("data-label", labels[column]);
});
});
var max = 0;
$("#generic tr").each(function() {
max = Math.max($(this).height(), max);
}).height(max);
} else {
// Remove data-label attribute from each cell
$("#generic").find("td").each(function() {
$(this).removeAttr("data-label");
});
$("#generic tr").each(function(){
$(this).height("auto");
});
}
});
});
</script>""" % (self.table, self.ctx.URL('dt_server'), self.table, self.col, self.r_buts,
row_buttons,self.func, self.hide, self.cdb, self.cols,self.order)
return js
def dt_grid(self):
f_buttons = self.form_buttons()
hdrs = self.build_headers()
hd = ''
for h in hdrs:
hd += '<th>%s</th>' % h
frm = self.build_j_script()
frm += """
<div class="column is-12 is-centered">
%s
</div>
<div class="table-responsive">
<table id=%s class="table is-narrow is-striped is-bordered">
<thead>
<tr>
%s
</tr>
</thead>
</table>
</div>""" % (f_buttons, self.table, hd)
return frm
def __str__(self):
return self.dt_grid()
| 34.132616 | 165 | 0.491967 | 9,157 | 0.961567 | 0 | 0 | 0 | 0 | 0 | 0 | 4,177 | 0.438622 |
2c09a4a2e41ca60c7d6287eab58dfe9fe3c0167c | 680 | py | Python | gatewayconfig/bluetooth/descriptors/utf8_format_descriptor.py | AndriiIevdoshenko/hm-config | f513d72dd8c67c040310d78071d8ac2de418d0d6 | [
"MIT"
] | 7 | 2021-07-09T16:54:39.000Z | 2022-02-18T09:07:54.000Z | gatewayconfig/bluetooth/descriptors/utf8_format_descriptor.py | AndriiIevdoshenko/hm-config | f513d72dd8c67c040310d78071d8ac2de418d0d6 | [
"MIT"
] | 137 | 2021-02-05T21:53:35.000Z | 2022-03-31T23:31:54.000Z | gatewayconfig/bluetooth/descriptors/utf8_format_descriptor.py | AndriiIevdoshenko/hm-config | f513d72dd8c67c040310d78071d8ac2de418d0d6 | [
"MIT"
] | 16 | 2021-02-15T11:25:37.000Z | 2022-01-17T07:53:38.000Z | import dbus
from lib.cputemp.service import Descriptor
import gatewayconfig.constants as constants
class UTF8FormatDescriptor(Descriptor):
def __init__(self, characteristic):
Descriptor.__init__(
self, constants.PRESENTATION_FORMAT_DESCRIPTOR_UUID,
["read"],
characteristic)
def ReadValue(self, options):
value = []
value.append(dbus.Byte(0x19))
value.append(dbus.Byte(0x00))
value.append(dbus.Byte(0x00))
value.append(dbus.Byte(0x00))
value.append(dbus.Byte(0x01))
value.append(dbus.Byte(0x00))
value.append(dbus.Byte(0x00))
return value
| 27.2 | 68 | 0.638235 | 578 | 0.85 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 0.008824 |
2c0a5da432ba3d41420010568b4150514d1d9b8a | 4,340 | py | Python | gurobiSolver.py | kursatbakis/cmpe492project | bb882ac3febada05824e407e7d573a08b4232ee8 | [
"MIT"
] | null | null | null | gurobiSolver.py | kursatbakis/cmpe492project | bb882ac3febada05824e407e7d573a08b4232ee8 | [
"MIT"
] | null | null | null | gurobiSolver.py | kursatbakis/cmpe492project | bb882ac3febada05824e407e7d573a08b4232ee8 | [
"MIT"
] | null | null | null | import gurobipy as gp
from gurobipy import GRB
from scheduler.utils import *
import csv
W = {}
days = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"]
departments = ["CMPE"]
def create_W_matrix():
global W
allAvailableSlots = get_all_available_slots()
for availableSlot in allAvailableSlots:
for slot in availableSlot.slots:
if slot is None:
continue
if availableSlot.instructor in W:
W[availableSlot.instructor].append(TimeSlot(slot))
else:
W[availableSlot.instructor] = [TimeSlot(slot)]
def does_intersect(slot1, slot2):
if slot1.day != slot2.day:
return False
if slot1.slot == slot2.slot:
return True
if slot1.length == 2 and slot1.slot + 1 == slot2.slot:
return True
if slot2.length == 2 and slot2.slot + 1 == slot1.slot:
return True
return False
def solve():
m = gp.Model('Scheduling')
create_W_matrix()
X = m.addVars(allInstructors, allCourses, allSlots, allClassrooms, name="X", vtype=GRB.BINARY)
constr1 = m.addConstrs(
gp.quicksum(X[f, c, s, r] for c in allCourses for r in allClassrooms) <= 1 for f in allInstructors for s in
allSlots)
constr2 = m.addConstrs(
(gp.quicksum(X[f, c, s, r] for f in allInstructors for c in allCourses) <= 1 for s in allSlots for r in
allClassrooms))
constr3 = m.addConstrs((gp.quicksum(
X[f, c, s, r] * c.quota for f in allInstructors for s in allSlots) <= gp.quicksum(
X[f, c, s, r] * r.capacity for f in allInstructors for s in allSlots))
for c in allCourses for r in allClassrooms)
constr4 = m.addConstrs(
gp.quicksum(X[f, c, s, r] for c in allCourses for r in allClassrooms) == 0 for f in allInstructors for s in
allSlots if f.id in W and s not in W[f.id])
constr5 = m.addConstrs(gp.quicksum(
X[f, c, s, r] * s.length for s in allSlots for r in allClassrooms for f in allInstructors) == c.hours for c in
allCourses)
constr6 = m.addConstrs(
gp.quicksum(X[f, c, s, r] for s in allSlots for r in allClassrooms) == 0 for f in allInstructors for c in
allCourses if c.id not in f.courses)
constr7 = m.addConstrs(
gp.quicksum(X[f, c, rs, r] for rs in getRelatedSlots(s) for r in allClassrooms for c in allCourses) <= 1
for f in allInstructors for s in allSlots)
constr8 = m.addConstrs(
gp.quicksum(X[f, c, s, r] for r in allClassrooms for f in allInstructors for s in allSlots if s.day == d) <= 1
for d in days for c in allCourses)
# Dersleri 2 + 1 seklinde ayirabilmek icin.
constr9 = m.addConstrs(
gp.quicksum(X[f, c, s, r] for r in allClassrooms for s in allSlots) <= 2 for f in allInstructors for c in
allCourses
)
constr11 = m.addConstrs(
gp.quicksum(X[f, c, rs, r] for rs in getRelatedSlots(s) for f in allInstructors for c in allCourses) <= 1
for r in allClassrooms for s in allSlots)
# constr10 = m.addConstrs(
# gp.quicksum(X[f, c, ss, r] for c in allCourses if 100 * Class <= c.code < 100 * (Class + 1) and c.department == d for f in allInstructors for r in allClassrooms for ss in allSlots if does_intersect(ss, s)) <= 1 for Class in range(1, 5) for d in departments for s in allSlots
# )
obj = gp.quicksum(
X[f, c, s, r] for f in allInstructors for s in allSlots for c in allCourses for r in allClassrooms)
m.setObjective(obj, GRB.MAXIMIZE)
m.optimize()
solution = m.getAttr('X', X)
for instructor, course, slot, classroom in X.keys():
if solution[instructor, course, slot, classroom] > 0.5:
with open('results/{}.csv'.format(classroom.code), 'a+') as f:
writer = csv.writer(f)
writer.writerow(
[slot.day, slot.slot, slot.length, instructor.full_name, course.department, course.code])
with open('results/{}.csv'.format(instructor.full_name), 'a+') as f:
writer = csv.writer(f)
writer.writerow([slot.day, slot.slot, slot.length, classroom.code, course.department, course.code])
| 42.135922 | 285 | 0.609677 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 467 | 0.107604 |
2c0c6d4c1880f94e8964a089e665e4a8c770f8e9 | 616 | py | Python | app/app/models/task.py | gooocho/fastapi_todo | b88177e651f1c6984a636262a4d686935b67ed6f | [
"MIT"
] | null | null | null | app/app/models/task.py | gooocho/fastapi_todo | b88177e651f1c6984a636262a4d686935b67ed6f | [
"MIT"
] | null | null | null | app/app/models/task.py | gooocho/fastapi_todo | b88177e651f1c6984a636262a4d686935b67ed6f | [
"MIT"
] | null | null | null | from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from app.db.settings import Base
from app.models.assignment import ModelAssignment
class ModelTask(Base):
__tablename__ = "tasks"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)
priority = Column(Integer, index=True)
status = Column(Integer, index=True)
users = relationship(
"ModelUser",
secondary=ModelAssignment.__tablename__,
order_by="ModelUser.id",
back_populates="tasks",
)
| 26.782609 | 54 | 0.709416 | 442 | 0.717532 | 0 | 0 | 0 | 0 | 0 | 0 | 39 | 0.063312 |
2c0cc4e362937d93adf7ebfce043afa65bc46a05 | 1,777 | py | Python | ico_gateway/views.py | dacom-dark-sun/dacom-api | 7efd77bf75cd28771b4a466ff36310d12b634f30 | [
"MIT"
] | null | null | null | ico_gateway/views.py | dacom-dark-sun/dacom-api | 7efd77bf75cd28771b4a466ff36310d12b634f30 | [
"MIT"
] | null | null | null | ico_gateway/views.py | dacom-dark-sun/dacom-api | 7efd77bf75cd28771b4a466ff36310d12b634f30 | [
"MIT"
] | null | null | null | from rest_framework import viewsets, status
from rest_framework.response import Response
from account.models import Account
from wallet.coin_base import coin_base
from wallet.models import Wallet
from ico_gateway.models import IcoWallet, IcoProject
from ico_gateway.serializers import (
IcoProjectSerializer,
IcoWalletSerializer,
CreateIcoWalletSerializer
)
class IcoWalletViewSet(viewsets.ModelViewSet):
queryset = IcoWallet.objects.all()
serializer_class = IcoWalletSerializer
def create(self, request):
slz = CreateIcoWalletSerializer(data=request.data)
slz.is_valid(raise_exception=True)
community = request.community
if IcoWallet.objects.filter(
# Если кошелек для ico уже у юзера есть
wallet__currency=slz.validated_data['currency'],
wallet__owner__name=slz.validated_data['account'],
ico_project__community=community
).exists():
return Response('IcoWallet for %s already exists'
% slz.validated_data['account'],
status.HTTP_400_BAD_REQUEST)
# Предполагается что аккаунт существует
# все новые акки сразу синхронизируются
wallet = Wallet.objects.create(
owner=Account.objects.get(name=slz.validated_data['account']),
currency=slz.validated_data['currency']
)
new_ico_wallet = IcoWallet.objects.create(
wallet=wallet,
ico_project=IcoProject.objects.get(community=request.community),
)
return Response(self.serializer_class(new_ico_wallet).data)
class IcoProjectViewSet(viewsets.ModelViewSet):
queryset = IcoProject.objects.all()
serializer_class = IcoProjectSerializer
| 33.528302 | 76 | 0.694992 | 1,494 | 0.798503 | 0 | 0 | 0 | 0 | 0 | 0 | 291 | 0.155532 |
2c1009ce318ebb350e16fb6f622adf0a9ca64b2c | 2,733 | py | Python | motion/reference_model/los_reference_model/scripts/los_reference_model_node.py | vortexntnu/Manta-AUV | 7966b871c56b0ea9f95bb61a48609a81f4a276d8 | [
"MIT"
] | 25 | 2020-09-20T16:25:05.000Z | 2022-03-05T09:06:36.000Z | motion/reference_model/los_reference_model/scripts/los_reference_model_node.py | vortexntnu/Manta-AUV | 7966b871c56b0ea9f95bb61a48609a81f4a276d8 | [
"MIT"
] | 187 | 2020-09-20T16:02:01.000Z | 2022-03-26T00:14:32.000Z | motion/reference_model/los_reference_model/scripts/los_reference_model_node.py | vortexntnu/Manta-AUV | 7966b871c56b0ea9f95bb61a48609a81f4a276d8 | [
"MIT"
] | 15 | 2020-09-24T20:23:51.000Z | 2022-03-05T09:14:00.000Z | #!/usr/bin/env python
import rospy
import numpy as np
import math
from discrete_tustin import ReferenceModel
from vortex_msgs.msg import GuidanceData
class LOSReferenceModelNode():
"""
This is the ROS wrapper class for the reference model class.
Nodes created:
los_reference_model
Subscribes to:
/guidance/los_data
Publishes to:
/reference_model/los_data
"""
def __init__(self):
# Update rate
self.h = 0.05
self.u = 0.0
# ROS node init
rospy.init_node('rm_los')
# Subscribers
self.guidance_data_sub = rospy.Subscriber('/guidance/los_data', GuidanceData, self.guidanceDataCallback, queue_size=1)
# Publishers
self.rm_los_data_pub = rospy.Publisher('/reference_model/los_data', GuidanceData, queue_size=1)
# RM object
self.reference_model = ReferenceModel(np.array((0, 0)), self.h)
def fixHeadingWrapping(self, u, psi, psi_ref, speed):
"""
The heading angle is obtained by the use of an arctangent
function, which is discontinuous at -pi and pi. This can
be problematic when the heading angle is fed into the
reference model. This function fixes this problem by
wrapping the angles around by 2pi.
"""
e = psi - psi_ref
if e < -math.pi:
psi_ref = psi_ref - 2*math.pi
if e > math.pi:
psi_ref = psi_ref + 2*math.pi
# Reference Model
x_d = self.reference_model.discreteTustinMSD(np.array((speed, psi_ref)))
psi_d = x_d[2]
e = psi - psi_d
if e > math.pi:
psi_d = psi_d - 2*math.pi
self.reference_model = ReferenceModel(np.array((u, psi)), self.h)
x_d = self.reference_model.discreteTustinMSD(np.array((speed, psi_d)))
if e < -math.pi:
psi_d = psi_d + 2*math.pi
self.reference_model = ReferenceModel(np.array((u, psi)), self.h)
x_d = self.reference_model.discreteTustinMSD(np.array((speed, psi_d)))
return x_d
def guidanceDataCallback(self, msg):
"""
Gets topic msg from LOS guidance module, applies discrete Tustin transform,
publishes data from guidance and the calculated data to LOS controller.
"""
# Guidance data sub
u = msg.u
psi = msg.psi
psi_ref = msg.psi_ref
speed = msg.speed
# Reference model calc
"""
Wrapping would have been avoided by using quaternions instead of Euler angles
if you don't care about wrapping, use this instead:
x_d = self.reference_model.discreteTustinMSD(np.array((self.los.speed,psi_d)))
"""
x_d = self.fixHeadingWrapping(u, psi, psi_ref, speed)
# Reference Model data pub
msg.u_d = x_d[0]
msg.u_d_dot = x_d[1]
msg.psi_d = x_d[2]
msg.r_d = x_d[3]
msg.r_d_dot = x_d[4]
self.rm_los_data_pub.publish(msg)
if __name__ == '__main__':
try:
rm_los_node = LOSReferenceModelNode()
rospy.spin()
except rospy.ROSInterruptException:
pass
| 24.621622 | 120 | 0.712404 | 2,443 | 0.893889 | 0 | 0 | 0 | 0 | 0 | 0 | 1,091 | 0.399195 |
2c1069139cd713638cf5bbb933fb4bfc312c6f46 | 2,225 | py | Python | e_fun_calls.py | panamantis/gretnet_api | 7b30e3ca07992c52478de90cca94e18c1a1fa9f3 | [
"MIT"
] | null | null | null | e_fun_calls.py | panamantis/gretnet_api | 7b30e3ca07992c52478de90cca94e18c1a1fa9f3 | [
"MIT"
] | null | null | null | e_fun_calls.py | panamantis/gretnet_api | 7b30e3ca07992c52478de90cca94e18c1a1fa9f3 | [
"MIT"
] | null | null | null | import sys,os
import time
import datetime
import random
import re
import json
import requests
from flask import Flask, jsonify
from flasgger import Swagger # pip install flasgger
from flasgger import swag_from
from flask import request
from api_helper import GretNet_API_Helper
LOCAL_PATH = os.path.abspath(os.path.dirname(__file__))+"/"
sys.path.insert(0,LOCAL_PATH)
sys.path.insert(0,LOCAL_PATH+"../")
#0v1# JC Apr 8, 2021 Base setup
#Helper=GretNet_API_Helper()
## OpenAPI
#
#/crawl_domain
def handle_crawl_domain_request(): #*args,**kwargs):
"""Submit a domain to crawl
---
post:
summary: Handle submit domain to crawl requests
consumes:
- application/json
parameters:
- in: body
name: meta
description: Domain to crawl
schema:
type: object
properties:
url:
type: string
responses:
200:
description: Post accepted and processed.
"""
try:
the_json=request.json
except: the_json={}
if the_json:
Helper.cache_request('crawl_domain',the_json, id='')
try: print (str(request.json))
except: pass
result={}
result['status_code']=200
return jsonify(result)
#TBD: add node or relation, standard search
def dev1():
return
if __name__=='__main__':
branches=['dev1']
for b in branches:
globals()[b]()
"""
"""
"""
"""
| 11.410256 | 60 | 0.412135 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 746 | 0.335281 |
2c1092a7d5dfc15f1ac47f20c842e794dad8aa14 | 13,051 | py | Python | src/ion.py | lksrmp/paw_structure | 560a0a601a90114fd80f98096aa1f0e012121c69 | [
"Apache-2.0"
] | null | null | null | src/ion.py | lksrmp/paw_structure | 560a0a601a90114fd80f98096aa1f0e012121c69 | [
"Apache-2.0"
] | 2 | 2022-03-22T15:27:17.000Z | 2022-03-30T14:16:26.000Z | src/ion.py | lksrmp/paw_structure | 560a0a601a90114fd80f98096aa1f0e012121c69 | [
"Apache-2.0"
] | null | null | null | """
paw_structure.ion
-----------------
Ion complex detection using geometric :ref:`algorithm<Control_ION_algorithm>`.
Main routine is :func:`.ion_find_parallel`.
Dependencies:
:py:mod:`functools`
:py:mod:`miniutils`
:py:mod:`numpy`
:py:mod:`pandas`
:mod:`.neighbor`
:mod:`.utility`
:class:`.Snap`
.. autosummary::
ion_find_parallel
ion_load
ion_save
ion_single
"""
import numpy as np
import pandas as pd
from functools import partial
import miniutils.progress_bar as progress
# MODULES WITHIN PROJECT
from . import neighbor
from . import utility
from .tra import Snap
########################################################################################################################
# FIND ION COMPLEX FOR A SINGLE SNAPSHOT
########################################################################################################################
# INPUT
# class Snap snap snapshot containing all information
# str id1 identifier for atom used as center (e.g. 'MN'); only one allowed to be in snap
# str id2 identifier for atoms as possible first neighbors (e.g. 'O_')
# str id3 identifier for atoms as possible neighbors of first neighbors (e.g. 'H_')
# float cut1 cutoff distance for first neighbor search
# float cut2 cutoff distance for second neighbor search
#####
# OUTPUT
# pandas DataFrame contains the whole complex centered around id1
########################################################################################################################
def ion_single(snap, id1, id2, id3, cut1, cut2):
"""
Find ion complex of a single snapshot of atomic positions.
Args:
snap (:class:`.Snap`): single snapshot containing the atomic information
id1 (str): identifier for atom used as center (e.g. 'MN')
id2 (str): identifier for atoms as possible first neighbors (e.g. 'O\_')
id3 (str): identifier for atoms as possible neighbors of first neighbors (e.g. 'H\_')
cut1 (float): cutoff distance for first neighbor search
cut2 (float): cutoff distance for second neighbor search
Returns:
:class:`.Snap`: snapshot containing an ion complex
Todo:
Implement possibility for more atoms of type id1 or allow selection by name.
"""
# check if only one atom is selected as ion
if len(snap.atoms[snap.atoms['id'] == id1]) != 1:
utility.err('ion_single', 0, [len(snap.atoms[snap.atoms['id'] == id1])])
# check if all three are different species
if id1 == id2 or id2 == id3 or id1 == id3:
utility.err('ion_single', 1, [id1, id2, id3])
# search first neighbors
next1 = neighbor.neighbor_name(snap, id1, id2, cut1)
# extract name lists
id1_list = [atom[0] for atom in next1]
id2_list = [y for x in [atom[1:] for atom in next1] for y in x]
# search second neighbors
next2 = neighbor.neighbor_name(snap, id2, id3, cut2, names=id2_list)
# extract name list
id3_list = [y for x in [atom[1:] for atom in next2] for y in x]
# extract correct atom information
id1_list = snap.atoms.loc[snap.atoms['name'].isin(id1_list)]
id2_list = snap.atoms.loc[snap.atoms['name'].isin(id2_list)]
id3_list = snap.atoms.loc[snap.atoms['name'].isin(id3_list)]
comp = pd.concat([id1_list, id2_list, id3_list])
return Snap(snap.iter, snap.time, snap.cell, None, None, dataframe=comp)
########################################################################################################################
# SAVE INFORMATION FROM ion_find TO FILE <root>.ext FOR LATER ANALYSIS
# TODO: check if snapshots is empty
########################################################################################################################
# INPUT
# str root root name for saving file
# list class Snap snapshots list with information to be saved
# str id1 identifier for atom used as center (e.g. 'MN'); only one allowed to be in snap
# str id2 identifier for atoms as possible first neighbors (e.g. 'O_')
# str id3 identifier for atoms as possible neighbors of first neighbors (e.g. 'H_')
# float cut1 cutoff distance for first neighbor search
# float cut2 cutoff distance for second neighbor search
# str ext (optional) extension for the saved file: name = root + ext
########################################################################################################################
def ion_save(root, snapshots, id1, id2, id3, cut1, cut2, ext='.ion'):
"""
Save results to file :ref:`Output_ion`.
Args:
root (str): root name for saving file
snapshots (list[:class:`.Snap`]): list of snapshots containing an ion complex
id1 (str): identifier for atom used as center (e.g. 'MN')
id2 (str): identifier for atoms as possible first neighbors (e.g. 'O\_')
id3 (str): identifier for atoms as possible neighbors of first neighbors (e.g. 'H\_')
cut1 (float): cutoff distance for first neighbor search
cut2 (float): cutoff distance for second neighbor search
ext (str, optional): default ".ion" - extension for the saved file: name = root + ext
Todo:
Check if snapshots is empty.
"""
# open file
path = root + ext
try:
f = open(path, 'w')
except IOError:
utility.err_file('ion_save', path)
# write header
f.write(utility.write_header())
f.write("ION COMPLEXES\n")
f.write("%-14s%14.8f\n" % ("T1", snapshots[0].time))
f.write("%-14s%14.8f\n" % ("T2", snapshots[-1].time))
f.write("%-14s%14d\n" % ("SNAPSHOTS", len(snapshots)))
f.write("%-14s%14s\n" % ("ID1", id1))
f.write("%-14s%14s\n" % ("ID2", id2))
f.write("%-14s%14s\n" % ("ID3", id3))
f.write("%-14s%14.8f\n" % ("CUT1", cut1))
f.write("%-14s%14.8f\n" % ("CUT2", cut2))
f.write("%-14s\n" % ("UNIT CELL"))
np.savetxt(f, snapshots[0].cell, fmt="%14.8f")
# write structure information
for i in range(len(snapshots)):
f.write("-" * 84 + "\n")
f.write("%-14s%-14.8f%-14s%-14d%-14s%-14d\n" %
("TIME", snapshots[i].time, "ITERATION", snapshots[i].iter, "ATOMS", len(snapshots[i].atoms)))
f.write("%-14s%-14s%-14s%14s%14s%14s\n" % ('NAME', 'ID', 'INDEX', 'X', 'Y', 'Z'))
np.savetxt(f, snapshots[i].atoms, fmt="%-14s%-14s%-14d%14.8f%14.8f%14.8f")
f.close()
return
########################################################################################################################
# LOAD INFORMATION PREVIOUSLY SAVED BY ion_save()
# WARNING: READING IS LINE SENSITIVE! ONLY USE ON UNCHANGED FILES WRITTEN BY ion_save()
########################################################################################################################
# INPUT
# str root root name for the file to be loaded
# str ext (optional) extension for the file to be loaded: name = root + ext
#####
# OUTPUT
# list class Snap snapshots list of all information
########################################################################################################################
def ion_load(root, ext='.ion'):
"""
Load information from the :ref:`Output_ion` file previously created by :func:`.ion_save`.
Args:
root (str): root name for the file to be loaded
ext (str, optional): default ".ion" - extension for the file to be loaded: name = root + ext
Returns:
list[:class:`.Snap`]: list of snapshots containing an ion complex
Note:
Reading is line sensitive. Do not alter the output file before loading.
"""
path = root + ext
try:
f = open(path, 'r')
except IOError:
utility.err_file('ion_load', path)
text = f.readlines() # read text as lines
for i in range(len(text)):
text[i] = text[i].split() # split each line into list with strings as elements
snapshots = [] # storage list
for i in range(len(text)):
if len(text[i]) > 1:
if text[i][0] == 'UNIT':
cell = np.array(text[i+1:i+4], dtype=float) # get unit cell
if text[i][0] == "TIME": # search for trigger of new snapshot
iter = int(text[i][3])
time = float(text[i][1])
n_atoms = int(text[i][5])
test = np.array(text[i + 2:i + 2 + n_atoms])
atoms = {}
atoms['name'] = test[:, 0]
atoms['id'] = test[:, 1]
atoms['index'] = np.array(test[:, 2], dtype=int)
df = pd.DataFrame(data=atoms)
# save information as class Snap
snapshots.append(Snap(iter, time, cell, np.array(test[:, 3:6], dtype=np.float64), df))
return snapshots
########################################################################################################################
# FIND ION COMPLEXES IN MULTIPLE SNAPSHOTS
# WARNING: NOT IN USE BECAUSE NO PARALLEL COMPUTING
########################################################################################################################
# INPUT
# str root root name for saving file
# list class Snap snapshots list with information to be saved
# str id1 identifier for atom used as center (e.g. 'MN'); only one allowed to be in snap
# str id2 identifier for atoms as possible first neighbors (e.g. 'O_')
# str id3 identifier for atoms as possible neighbors of first neighbors (e.g. 'H_')
# float cut1 (optional) cutoff distance for first neighbor search
# float cut2 (optional) cutoff distance for second neighbor search
#####
# OUTPUT
# list class Snap complex list with all ion complexes found
########################################################################################################################
# def ion_find(root, snapshots, id1, id2, id3, cut1=3.0, cut2=1.4):
# complex = []
# # loop through different snapshots
# for snap in snapshots:
# # get complex information
# comp = ion_single(snap, id1, id2, id3, cut1, cut2)
# # append Snap object for data storage
# complex.append(Snap(snap.iter, snap.time, snap.cell, None, None, dataframe=comp))
# # save information to file
# ion_save(root, complex, id1, id2, id3, cut1, cut2)
# return complex
########################################################################################################################
# ROUTINE TO FIND ION COMPLEXES FOR MULTIPLE SNAPSHOTS
# PARALLEL VERSION OF ion_find() WITH PROGRESS BAR IN CONSOLE
########################################################################################################################
# INPUT
# str root root name for saving file
# list class Snap snapshots list with information to be saved
# str id1 identifier for atom used as center (e.g. 'MN'); only one allowed to be in snap
# str id2 identifier for atoms as possible first neighbors (e.g. 'O_')
# str id3 identifier for atoms as possible neighbors of first neighbors (e.g. 'H_')
# float cut1 (optional) cutoff distance for first neighbor search
# float cut2 (optional) cutoff distance for second neighbor search
#####
# OUTPUT
# list class Snap ion_comp list of ion complexes found
########################################################################################################################
def ion_find_parallel(root, snapshots, id1, id2, id3, cut1, cut2):
"""
Find ion complexes for multiple snapshots of atomic configurations.
Args:
root (str): root name of the files
snapshots (list[:class:`.Snap`]): list of snapshots containing the atomic information
id1 (str): identifier for atom used as center (e.g. 'MN')
id2 (str): identifier for atoms as possible first neighbors (e.g. 'O\_')
id3 (str): identifier for atoms as possible neighbors of first neighbors (e.g. 'H\_')
cut1 (float): cutoff distance for first neighbor search
cut2 (float): cutoff distance for second neighbor search
Returns:
list[:class:`.Snap`]: list of snapshots containing an ion complex
Parallelization based on :py:mod:`multiprocessing`.
Note:
Only one atom of type :data:`id1` allowed to be in a snapshot at the moment.
"""
print("ION COMPLEX DETECTION IN PROGRESS")
# set other arguments (necessary for parallel computing)
multi_one = partial(ion_single, id1=id1, id2=id2, id3=id3, cut1=cut1, cut2=cut2)
# run data extraction
ion_comp = progress.parallel_progbar(multi_one, snapshots)
# create output file
ion_save(root, ion_comp, id1, id2, id3, cut1, cut2)
print("ION COMPLEX DETECTION FINISHED")
return ion_comp
| 46.610714 | 120 | 0.539192 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9,751 | 0.747146 |
2c1242ea99a96b6aa8170526e30cefef163adf0c | 720 | py | Python | facilities/migrations/0002_auto_20160406_1835.py | uonafya/mfl_api | 379310b9b56cde084620f1f2dbfe4c6d7c1de47b | [
"MIT"
] | null | null | null | facilities/migrations/0002_auto_20160406_1835.py | uonafya/mfl_api | 379310b9b56cde084620f1f2dbfe4c6d7c1de47b | [
"MIT"
] | null | null | null | facilities/migrations/0002_auto_20160406_1835.py | uonafya/mfl_api | 379310b9b56cde084620f1f2dbfe4c6d7c1de47b | [
"MIT"
] | 4 | 2018-07-26T05:53:06.000Z | 2021-07-17T14:30:09.000Z | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('facilities', '0001_auto_20160328_1426'),
]
operations = [
migrations.AddField(
model_name='facilityunit',
name='license_number',
field=models.CharField(max_length=100, null=True, blank=True),
),
migrations.AlterField(
model_name='facilitytype',
name='sub_division',
field=models.CharField(help_text=b'Parent of the facility type e.g sub-district hospitals are under Hospitals.', max_length=100, null=True, blank=True),
),
]
| 28.8 | 164 | 0.633333 | 611 | 0.848611 | 0 | 0 | 0 | 0 | 0 | 0 | 196 | 0.272222 |
2c146b5c3b1a1974b34c4daff216ed3881890272 | 4,547 | py | Python | pysparkle/frontend/qt.py | macdems/pysparkle | 7d6018e5f2010d6a79fe71bc972bd29c61a113bc | [
"MIT"
] | 1 | 2015-12-19T19:25:15.000Z | 2015-12-19T19:25:15.000Z | pysparkle/frontend/qt.py | macdems/pysparkle | 7d6018e5f2010d6a79fe71bc972bd29c61a113bc | [
"MIT"
] | null | null | null | pysparkle/frontend/qt.py | macdems/pysparkle | 7d6018e5f2010d6a79fe71bc972bd29c61a113bc | [
"MIT"
] | null | null | null | # Copyright (c) 2015-2016 Maciej Dems <maciej.dems@p.lodz.pl>
# See LICENSE file for copyright information.
import sys
if 'PySide6' in sys.modules:
from PySide6.QtWidgets import QMessageBox, QLabel, QTextEdit
_exec_attr = 'exec'
elif 'PyQt6' in sys.modules:
from PyQt6.QtWidgets import QMessageBox, QLabel, QTextEdit
_exec_attr = 'exec'
elif 'PySide2' in sys.modules:
from PySide2.QtWidgets import QMessageBox, QLabel, QTextEdit
_exec_attr = 'exec_'
elif 'PyQt5' in sys.modules:
from PyQt5.QtWidgets import QMessageBox, QLabel, QTextEdit
_exec_attr = 'exec_'
else:
if 'PySide' in sys.modules:
from PySide.QtGui import QMessageBox, QLabel, QTextEdit
elif 'PyQt4' in sys.modules:
from PyQt4.QtGui import QMessageBox, QLabel, QTextEdit
else:
raise ImportError("cannot determine Qt bindings: import desired Qt module first")
_exec_attr = 'exec_'
QMessageBox.ButtonRole.YesRole = QMessageBox.YesRole
QMessageBox.ButtonRole.NoRole = QMessageBox.NoRole
QMessageBox.ButtonRole.RejectRole = QMessageBox.RejectRole
QMessageBox.StandardButton.Ok = QMessageBox.Ok
QMessageBox.StandardButton.Yes = QMessageBox.Yes
QMessageBox.StandardButton.No = QMessageBox.No
def ask_for_autocheck(pysparkle):
dialog = QMessageBox()
dialog.setIcon(QMessageBox.Icon.Question)
dialog.setWindowTitle(dialog.tr("Check for updates automatically?"))
dialog.setText(dialog.tr("Should {} automatically check for updates?").format(pysparkle.appname))
dialog.setInformativeText(dialog.tr("You can always check for updates manually from the menu."))
dialog.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
result = getattr(dialog, _exec_attr)()
return result == QMessageBox.StandardButton.Yes
def update_error(msg=None):
dialog = QMessageBox()
dialog.setIcon(QMessageBox.Icon.Critical)
dialog.setWindowTitle(dialog.tr("Update Error!"))
dialog.setText(dialog.tr("An error occurred in retrieving update information; "
"are you connected to the internet? Please try again later."))
if msg is not None:
dialog.setDetailedText(msg)
dialog.setStandardButtons(QMessageBox.StandardButton.Ok)
getattr(dialog, _exec_attr)()
def no_info(pysparkle):
dialog = QMessageBox()
dialog.setIcon(QMessageBox.Icon.Warning)
dialog.setWindowTitle(dialog.tr("No update information!"))
dialog.setText(dialog.tr("There is no update information for {}.\n\n"
"Maybe the software is not supported for your operating system...")
.format(pysparkle.appname))
dialog.setStandardButtons(QMessageBox.StandardButton.Ok)
getattr(dialog, _exec_attr)()
def no_update(pysparkle):
dialog = QMessageBox()
dialog.setIcon(QMessageBox.Icon.Information)
dialog.setWindowTitle(dialog.tr("You're up to date!"))
dialog.setText(dialog.tr("{} {} is currently the newest version available.")
.format(pysparkle.appname, pysparkle.appver))
dialog.setStandardButtons(QMessageBox.StandardButton.Ok)
getattr(dialog, _exec_attr)()
def update_available(pysparkle, maxitem, items):
dialog = QMessageBox()
dialog.setIcon(QMessageBox.Icon.Information)
dialog.setWindowTitle(dialog.tr("A new version of {} is available!").format(pysparkle.appname))
dialog.setText(dialog.tr("{} {} is now available (you have {}).\n\nWould you like to download it now?")
.format(pysparkle.appname, maxitem['version'], pysparkle.appver))
if any(item['notes'] for item in items):
grid = dialog.layout()
label = QLabel(dialog.tr("Release notes:"))
grid.addWidget(label, grid.rowCount(), 0, 1, grid.columnCount())
notes = QTextEdit()
notes.setText("<br/>\n".join("<h3>{title}</h3>\n{notes}\n".format(**item) for item in items))
notes.setFixedHeight(200)
notes.setReadOnly(True)
grid.addWidget(notes, grid.rowCount(), 0, 1, grid.columnCount())
dialog.updateGeometry()
get_button = dialog.addButton(dialog.tr("Get update"), QMessageBox.ButtonRole.YesRole)
skip_button = dialog.addButton(dialog.tr("Skip this version"), QMessageBox.ButtonRole.NoRole)
later_button = dialog.addButton(dialog.tr("Remind me later"), QMessageBox.ButtonRole.RejectRole)
getattr(dialog, _exec_attr)()
result = dialog.clickedButton()
if result in (get_button, skip_button):
return result == get_button
| 45.47 | 107 | 0.710798 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 947 | 0.208269 |
2c14a991d87c2cf60960166a41fc56bf0090a775 | 11,475 | py | Python | python/3D-rrt/pvtrace/Visualise.py | rapattack88/mcclanahoochie | 6df72553ba954b52e949a6847a213b22f9e90157 | [
"Apache-2.0"
] | 1 | 2020-12-27T21:37:35.000Z | 2020-12-27T21:37:35.000Z | python/3D-rrt/pvtrace/Visualise.py | rapattack88/mcclanahoochie | 6df72553ba954b52e949a6847a213b22f9e90157 | [
"Apache-2.0"
] | null | null | null | python/3D-rrt/pvtrace/Visualise.py | rapattack88/mcclanahoochie | 6df72553ba954b52e949a6847a213b22f9e90157 | [
"Apache-2.0"
] | null | null | null | # pvtrace is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# pvtrace is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
try:
import visual
VISUAL_INSTALLED = True
print "Python module visual is installed..."
except:
print "Python module visual is not installed... telling all Visualiser object to not render."
VISUAL_INSTALLED = False
import numpy as np
import Geometry as geo
import ConstructiveGeometry as csg
import external.transformations as tf
class Visualiser (object):
"""Visualiser a class that converts project geometry objects into vpython objects and draws them. It can be used programmatically: just add objects as they are created and the changes will update in the display."""
VISUALISER_ON = True
if not VISUAL_INSTALLED:
VISUALISER_ON = False
def __init__(self, background=(0,0,0), ambient=1.):
super(Visualiser, self).__init__()
if not Visualiser.VISUALISER_ON:
return
self.display = visual.display(title='PVTrace', x=0, y=0, width=800, height=600, background=background, ambient=ambient)
self.display.exit = False
visual.curve(pos=[(0,0,0), (.2,0,0)], radius=0.001, color=visual.color.red)
visual.curve(pos=[(0,0,0), (0,.2,0)], radius=0.001, color=visual.color.green)
visual.curve(pos=[(0,0,0), (0,0,.2)], radius=0.001, color=visual.color.blue)
visual.label(pos=(.22, 0, 0), text='X', linecolor=visual.color.red)
visual.label(pos=(0, .22, 0), text='Y', linecolor=visual.color.green)
visual.label(pos=(0, 0, .22), text='Z', linecolor=visual.color.blue)
def addBox(self, box, colour=None):
if not Visualiser.VISUALISER_ON:
return
if isinstance(box, geo.Box):
if colour == None:
colour = visual.color.red
org = geo.transform_point(box.origin, box.transform)
ext = geo.transform_point(box.extent, box.transform)
print "Visualiser: box origin=%s, extent=%s" % (str(org), str(ext))
size = np.abs(ext - org)
pos = org + 0.5*size
print "Visualiser: box position=%s, size=%s" % (str(pos), str(size))
angle, direction, point = tf.rotation_from_matrix(box.transform)
print "colour,", colour
if colour == [0,0,0]:
visual.box(pos=pos, size=size, opacity=0.3, material=visual.materials.plastic)
else:
visual.box(pos=pos, size=size, color=geo.norm(colour), opacity=0.5)
def addFinitePlane(self, plane, colour=None, opacity=0.):
if not Visualiser.VISUALISER_ON:
return
if isinstance(plane, geo.FinitePlane):
if colour == None:
colour = visual.color.blue
# visual doesn't support planes, so we draw a very thin box
H = .001
pos = (plane.length/2, plane.width/2, H/2)
pos = geo.transform_point(pos, plane.transform)
size = (plane.length, plane.width, H)
axis = geo.transform_direction((0,0,1), plane.transform)
visual.box(pos=pos, size=size, color=colour, opacity=0)
def addPolygon(self, polygon, colour=None):
if not Visualiser.VISUALISER_ON:
return
if isinstance(polygon, geo.Polygon):
if colour == None:
visual.convex(pos=polygon.pts, color=geo.norm([0.1,0.1,0.1]), material=visual.materials.plastic)
else:
visual.convex(pos=convex.points, color=geo.norm(colour), opacity=0.5)
def addConvex(self, convex, colour=None):
"""docstring for addConvex"""
if not Visualiser.VISUALISER_ON:
return
if isinstance(convex, geo.Convex):
if colour == None:
print "Color is none"
visual.convex(pos=polygon.pts, color=geo.norm([0.1,0.1,0.1]), material=visual.materials.plastic)
else:
import pdb; pdb.set_trace()
print "Colour is", geo.norm(colour)
visual.convex(pos=convex.points, color=geo.norm(colour), material=visual.materials.plastic)
def addRay(self, ray, colour=None):
if not Visualiser.VISUALISER_ON:
return
if isinstance(ray, geo.Ray):
if colour == None:
colour = visual.color.white
pos = ray.position
axis = ray.direction * 5
visual.cylinder(pos=pos, axis=axis, radius=0.0001, color=geo.norm(colour))
def addSmallSphere(self, point, colour=None):
if not Visualiser.VISUALISER_ON:
return
if colour == None:
colour = visual.color.blue
visual.sphere(pos=point, radius=0.00012, color=geo.norm(colour))
#visual.curve(pos=[point], radius=0.0005, color=geo.norm(colour))
def addLine(self, start, stop, colour=None):
if not Visualiser.VISUALISER_ON:
return
if colour == None:
colour = visual.color.white
axis = np.array(stop) - np.array(start)
visual.cylinder(pos=start, axis=axis, radius=0.0001, color=geo.norm(colour))
def addCylinder(self, cylinder, colour=None):
if not Visualiser.VISUALISER_ON:
return
if colour == None:
colour = visual.color.blue
#angle, direction, point = tf.rotation_from_matrix(cylinder.transform)
#axis = direction * cylinder.length
position = geo.transform_point([0,0,0], cylinder.transform)
axis = geo.transform_direction([0,0,1], cylinder.transform)
print cylinder.transform, "Cylinder:transform"
print position, "Cylinder:position"
print axis, "Cylinder:axis"
print colour, "Cylinder:colour"
print cylinder.radius, "Cylinder:radius"
visual.cylinder(pos=position, axis=axis, color=colour, radius=cylinder.radius, opacity=0.5, length = cylinder.length)
def addCSG(self, CSGobj, res,origin,extent,colour=None):
"""
Visualise a CSG structure in a space subset defined by xmin, xmax, ymin, .... with division factor (i.e. ~ resolution) res
"""
#INTone = Box(origin = (-1.,-1.,-0.), extent = (1,1,3))
#INTtwo = Box(origin = (-0.5,-0.5,0), extent = (0.5,0.5,3))
#INTtwo.append_transform(tf.translation_matrix((0,0.5,0)))
#INTtwo.append_transform(tf.rotation_matrix(np.pi/4, (0,0,1)))
#CSGobj = CSGsub(INTone, INTtwo)
#xmin = -1.
#xmax = 1.
#ymin = -1.
#ymax = 1.
#zmin = -1.
#zmax = 3.
#resolution = 0.05
#print "Resolution: ", res
xmin = origin[0]
xmax = extent[0]
ymin = origin[1]
ymax = extent[1]
zmin = origin[2]
zmax = extent[2]
"""
Determine Voxel size from resolution
"""
voxelextent = (res*(xmax-xmin), res*(ymax-ymin), res*(zmax-zmin))
pex = voxelextent
"""
Scan space
"""
x = xmin
y = ymin
z = zmin
print 'Visualisation of ', CSGobj.reference, ' started...'
while x < xmax:
y=ymin
z=zmin
while y < ymax:
z = zmin
while z < zmax:
pt = (x, y, z)
if CSGobj.contains(pt):
origin = (pt[0]-pex[0]/2, pt[1]-pex[1]/2, pt[2]-pex[2]/2)
extent = (pt[0]+pex[0]/2, pt[1]+pex[1]/2, pt[2]+pex[2]/2)
voxel = geo.Box(origin = origin, extent = extent)
self.addCSGvoxel(voxel, colour=colour)
z = z + res*(zmax-zmin)
y = y + res*(ymax-ymin)
x = x + res*(xmax-xmin)
print 'Complete.'
def addCSGvoxel(self, box, colour):
"""
16/03/10: To visualise CSG objects
"""
if colour == None:
colour = visual.color.red
org = box.origin
ext = box.extent
size = np.abs(ext - org)
pos = org + 0.5*size
visual.box(pos=pos, size=size, color=colour, opacity=0.2)
def addPhoton(self, photon):
"""Draws a smallSphere with direction arrow and polariation (if data is avaliable)."""
self.addSmallSphere(photon.position)
visual.arrow(pos=photon.position, axis=photon.direction * 0.0005, shaftwidth=0.0003, color=visual.color.magenta, opacity=0.8)
if photon.polarisation != None:
visual.arrow(pos=photon.position, axis=photon.polarisation * 0.0005, shaftwidth=0.0003, color=visual.color.white, opacity=0.4 )
def addObject(self, obj, colour=None, opacity=0.5, res=0.05, origin=(-0.02,-0.02,0.), extent = (0.02,0.02,1.)):
if not Visualiser.VISUALISER_ON:
return
if isinstance(obj, geo.Box):
self.addBox(obj, colour=colour)
if isinstance(obj, geo.Ray):
self.addRay(obj, colour=colour)
if isinstance(obj, geo.Cylinder):
self.addCylinder(obj, colour=colour)
if isinstance(obj, geo.FinitePlane):
self.addFinitePlane(obj, colour, opacity)
if isinstance(obj, csg.CSGadd) or isinstance (obj, csg.CSGint) or isinstance (obj, csg.CSGsub):
self.addCSG(obj, res, origin, extent, colour)
if isinstance(obj, geo.Polygon):
self.addPolygon(obj, colour=colour)
if isinstance(obj, geo.Convex):
self.addConvex(obj, colour=colour)
if False:
box1 = geo.Box(origin=[0,0,0], extent=[2,2,2])
box2 = geo.Box(origin=[2,2,2], extent=[2.1,4,4])
ray1 = geo.Ray(position=[-1,-1,-1], direction=[1,1,1])
ray2 = geo.Ray(position=[-1,-1,-1], direction=[1,0,0])
vis = Visualiser()
vis.addObject(box1)
import time
time.sleep(1)
vis.addObject(ray1)
time.sleep(1)
vis.addObject(ray2)
time.sleep(1)
vis.addObject(box2)
time.sleep(1)
vis.addLine([0,0,0],[5,4,5])
"""
# TEST TEST TEST
vis = Visualiser()
INTone = geo.Box(origin = (-1.,-1.,-0.), extent = (1,1,3))
INTtwo = geo.Box(origin = (-0.5,-0.5,0), extent = (0.5,0.5,3))
#INTtwo.append_transform(tf.translation_matrix((0,0.5,0)))
INTtwo.append_transform(tf.rotation_matrix(np.pi/4, (0,0,1)))
myobj = csg.CSGsub(INTone, INTtwo)
#vis.addObject(INTone, colour=visual.color.green)
#vis.addObject(INTtwo, colour=visual.color.blue)
vis.addObject(myobj, res=0.05, colour = visual.color.green)
"""
| 38.506711 | 218 | 0.573943 | 9,494 | 0.827364 | 0 | 0 | 0 | 0 | 0 | 0 | 2,711 | 0.236253 |
2c15d80e491037ea14b873717a75a66167a22e80 | 621 | py | Python | dropme/error.py | tivaliy/dropme | 3d760e1da8182cdf62ab2a6f357dea923fca3cd7 | [
"Apache-2.0"
] | null | null | null | dropme/error.py | tivaliy/dropme | 3d760e1da8182cdf62ab2a6f357dea923fca3cd7 | [
"Apache-2.0"
] | null | null | null | dropme/error.py | tivaliy/dropme | 3d760e1da8182cdf62ab2a6f357dea923fca3cd7 | [
"Apache-2.0"
] | null | null | null | #
# Copyright 2017 Vitalii Kulanov
#
class ClientException(Exception):
"""Base Exception for Dropme client
All child classes must be instantiated before raising.
"""
pass
class ConfigNotFoundException(ClientException):
"""
Should be raised if configuration for dropme client is not specified.
"""
pass
class InvalidFileException(ClientException):
"""
Should be raised when some problems while working with file occurred.
"""
pass
class ActionException(ClientException):
"""
Should be raised when some problems occurred while perform any command
"""
| 19.40625 | 74 | 0.702093 | 569 | 0.916264 | 0 | 0 | 0 | 0 | 0 | 0 | 396 | 0.637681 |
2c181e2dad47cea140e8dd9cb71766cc7851ab04 | 83 | py | Python | sage/apps.py | one-two-four-cee-four-one-plus/sage-project | 2192ef60d8d3330586147a8ca93f899ef346ed42 | [
"WTFPL"
] | null | null | null | sage/apps.py | one-two-four-cee-four-one-plus/sage-project | 2192ef60d8d3330586147a8ca93f899ef346ed42 | [
"WTFPL"
] | null | null | null | sage/apps.py | one-two-four-cee-four-one-plus/sage-project | 2192ef60d8d3330586147a8ca93f899ef346ed42 | [
"WTFPL"
] | null | null | null | from django.apps import AppConfig
class SageConfig(AppConfig):
name = 'sage'
| 13.833333 | 33 | 0.73494 | 46 | 0.554217 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 0.072289 |
2c18b6e9e45bd540c1325793507b1f1e6ae3f589 | 11,058 | py | Python | plotting.py | derEitel/explainableMS | f1ba37d5579b3e4b1a4ec8bf38f7385bb71e00a3 | [
"BSD-3-Clause"
] | 7 | 2019-04-21T03:02:31.000Z | 2021-06-10T21:15:03.000Z | plotting.py | derEitel/explainableMS | f1ba37d5579b3e4b1a4ec8bf38f7385bb71e00a3 | [
"BSD-3-Clause"
] | 3 | 2021-03-07T07:01:32.000Z | 2022-02-08T17:15:46.000Z | plotting.py | derEitel/explainableMS | f1ba37d5579b3e4b1a4ec8bf38f7385bb71e00a3 | [
"BSD-3-Clause"
] | 4 | 2019-04-22T07:15:26.000Z | 2021-06-16T05:14:18.000Z | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap
ms_color = [0.12156863, 0.46666667, 0.70588235, 1]
hc_color = [1., 0.49803922, 0.05490196, 1]
SMALL_SIZE = 12
MEDIUM_SIZE = 14
BIGGER_SIZE = 16
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=BIGGER_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
# set serif font
plt.rc('font', family='serif')
def generate_transparanet_cm(base='coolwarm', name="TransCoWa"):
# copy from existing colormap
ncolors = 256
color_array = plt.get_cmap(base)(range(ncolors))
# create parabolic decrease
decr = [-1*(x**2)+1 for x in range(int(ncolors/2))]
# normalize
decr = (decr - np.min(decr))/(np.max(decr - np.min(decr)))
# use inverted parabola as increase
incr = np.copy(decr)[::-1]
alphas = np.concatenate((decr, incr))
# update alpha values
color_array[:,-1] = alphas
# create new colormap and register it
transparent_coolwarm = LinearSegmentedColormap.from_list(name, color_array)
plt.register_cmap(cmap=transparent_coolwarm)
def get_labels_dict(path):
import xmltodict
with open(path) as f:
labels_xml = xmltodict.parse(f.read())['atlas']['data']['label']
labels_dict = {}
for row in labels_xml:
labels_dict[int(row['index'])] = row['name']
return labels_dict
def heatmap_per_region(hm, atlas, positive=True, size_normalize=False, signed=False):
# get heatmap mean per region
# use only positive values
signed_hm = np.copy(hm)
if signed:
if positive:
signed_hm[signed_hm<0] = 0
else:
signed_hm[signed_hm>0] = 0
regional_hm = {}
for lbl_idx in np.unique(atlas):
# skip outside area
if lbl_idx != 0:
atlas_lbl = atlas.copy()
# get region mask for each label
atlas_lbl[lbl_idx!=atlas] = 0
atlas_lbl[lbl_idx==atlas] = 1
# multiply region mask with heatmap
region_intensity = np.mean(atlas_lbl * np.squeeze(signed_hm))
if size_normalize:
region_size = np.sum(atlas_lbl).item()
region_intensity /= region_size
regional_hm[lbl_idx] = region_intensity
return regional_hm
def aggregate_regions(regional_hm, all_areas):
# aggregate atlas regions to previously defined areas
area_hm = {}
for name, (min_idx, max_idx) in all_areas.items():
regions_fit = []
for key in regional_hm.keys():
if key in range(min_idx, max_idx+1):
regions_fit.append(regional_hm[key])
region_mean = np.mean(regions_fit)
area_hm[name] = region_mean
return area_hm
def get_area_relevance(heatmaps, atlas, area_dict, positive=True, size_normalize=True):
keys = []
values = []
for hm in heatmaps:
regional_hm = heatmap_per_region(hm, atlas, positive=positive, size_normalize=size_normalize)
area_hm = aggregate_regions(regional_hm, area_dict)
# sort by values
area_hm_sorted = sorted(area_hm.items(), key=lambda kv: kv[1])
keys_sorted = [row[0] for row in area_hm_sorted]
values_sorted = [row[1] for row in area_hm_sorted]
keys.append(keys_sorted)
values.append(values_sorted)
return keys, values
def translate_keys(keys):
names_list = []
for key_list in keys:
name_list = []
for key in key_list:
name_list.append(short_name_map[key])
names_list.append(name_list)
return names_list
def wrap_as_df(keys, values):
df_ms = pd.DataFrame({"values_ms": values[0]}, keys[0])
df_hc = pd.DataFrame({"values_hc": values[1]}, keys[1])
df = pd.merge(df_ms, df_hc, left_index=True, right_index=True, how='outer')
return df
def reduce_df(df, take=30):
# get order based on relevance sum
abs_order = (np.abs(df["values_hc"]) + np.abs(df["values_ms"])).sort_values().index
most = abs_order[-take:]
short_df = df.loc[most]
order = (short_df["values_hc"] + short_df["values_ms"]).sort_values().index
short_df = df.loc[order]
return short_df
def reduce_two_dfs(df_zero, df_one, take=30):
abs_order = (df_zero.abs().sum() + df_one.abs().sum()).sort_values().index
most = abs_order[-take:]
# columns are keys so use [:, key]
short_df_zero = df_zero.loc[:,most]
short_df_one = df_one.loc[:,most]
order = (short_df_zero.sum() + short_df_one.sum()).sort_values().index
short_df_zero = short_df_zero.reindex(order, axis=1)
short_df_one = short_df_one.reindex(order, axis=1)
return short_df_zero, short_df_one
def plot_key_value_pairs(keys, values, title, loc="center left"):
plt.figure(figsize=(10, 6))
plt.plot(keys[0], values[0], 'o', color=ms_color, label="CDMS")
plt.plot(keys[1], values[1], 'o', color=hc_color, label="HC")
plt.xticks(rotation='vertical')
plt.legend(loc=loc)
plt.title(title)
plt.show()
def plot_dataframe(df, title, loc="center left"):
plt.figure(figsize=(10, 6))
plt.plot(df["values_ms"], 'o', color=ms_color, label="CDMS")
plt.plot(df["values_hc"], 'o', color=hc_color, label="HC")
plt.xticks(rotation='vertical')
plt.legend(loc=loc)
plt.title(title)
plt.show()
# Modified areas from Visualizing evidence for AD paper by
# Boehle et al. Based on Neuromorphometrics atlas from SPM12
# Name: (min, max)
gm_areas= {
"Accumbens": (23, 30),
"Amygdala": (31, 32),
"Brain Stem": (35, 35),
"Caudate": (36, 37),
"Cerebellum": (38, 41),
"Hippocampus": (47, 48),
"Parahippocampal gyrus": (170, 171),
"Pallidum": (55, 56),
"Putamen": (57, 58),
"Thalamus": (59, 60),
"CWM": (44, 45),
"ACG": (100, 101),
"Ant. Insula": (102, 103),
"Post. Insula": (172, 173),
"AOG": (104, 105),
"AG": (106, 107),
"Cuneus": (114, 115),
"Central operculum": (112, 113),
"Frontal operculum": (118, 119),
"Frontal pole": (120, 121),
"Fusiform gyrus": (122, 123),
"Temporal pole": (202, 203),
"TrIFG": (204, 205),
"TTG": (206, 207),
"Entorh. cortex": (116, 117),
"Parietal operculum": (174, 175),
"SPL": (198, 199),
"CSF": (46, 46),
"3rd Ventricle": (4, 4),
"4th Ventricle": (11, 11),
"Lateral Ventricles": (49, 52),
"Diencephalon": (61, 62),
"Vessels": (63, 64),
"Optic Chiasm": (69, 69),
"Vermal Lobules": (71, 73),
"Basal Forebrain": (75, 76),
"Calc": (108, 109),
"GRe": (124, 125),
"IOG": (128, 129),
"ITG": (132, 133),
"LiG": (134, 135),
"LOrG": (136, 137),
"MCgG": (138, 139),
"MFC": (140, 141),
"MFG": (142, 143),
"MOG": (144, 145),
"MOrG": (146, 147),
"MPoG": (148, 149),
"MPrG": (150, 151),
"MSFG": (152, 153),
"MTG": (154, 155),
"OCP": (156, 157),
"OFuG": (160, 161),
"OpIFG": (162, 163),
"OrIFG": (164, 165),
"PCgG": (166, 167),
"PCu": (168, 169),
"PoG": (176, 177),
"POrG": (178, 179),
"PP": (180, 181),
"PrG": (182, 183),
"PT": (184, 185),
"SCA": (186, 187),
"SFG": (190, 191),
"SMC": (192, 193),
"SMG": (194, 195),
"SOG": (196, 197),
"STG": (200, 201),
}
short_name_map = {
'Accumbens': 'Accumbens',
'Amygdala': 'Amygdala',
'Brain Stem': 'Brain Stem',
'Caudate': 'Caudate',
'Cerebellum': 'Cerebellum',
'Hippocampus': 'Hippocampus',
'Parahippocampal gyrus': 'Parahippocampal gyr.',
'Pallidum': 'Pallidum',
'Putamen': 'Putamen',
'Thalamus': 'Thalamus',
'Diencephalon': 'Diencephalon',
'CWM': 'Cerebral white matter',
'ACG': 'Ant. cingulate gyr.',
'Ant. Insula': 'Ant. insula',
'Post. Insula': 'Post. insula',
'AOG': 'Ant. orbital gyr.',
'AG': 'Angular gyr.',
'Cuneus': 'Cuneus',
'Central operculum': 'Central operculum',
'Frontal operculum': 'Frontal operculum',
'Frontal pole': 'Frontal pole',
'Fusiform gyrus': 'Fusiform gyr.',
'Temporal pole': 'Temporal pole',
'TrIFG': 'Triangular part of IFG',
'TTG': 'Trans. temporal gyr.',
'Entorh. cortex': 'Entorhinal area',
'Parietal operculum': 'Parietal operculum',
'SPL': 'Sup. parietal lobule',
'CSF': 'CSF',
'3rd Ventricle': '3rd Ventricle',
'4th Ventricle': '4th Ventricle',
'Lateral Ventricles': 'Inf. Lat. Ventricles',
'Vessels': 'Vessels',
'Optic Chiasm': 'Optic Chiasm',
'Vermal Lobules': 'Cereb. Verm. Lob.',
'Basal Forebrain': 'Basal Forebrain',
'Calc': 'Calcarine cortex',
'GRe': 'Gyrus rectus',
'IOG': 'Inf. occipital gyr.',
'ITG': 'Inf. temporal gyr.',
'LiG': 'Lingual gyr.',
'LOrG': 'Lat. orbital gyr.',
'MCgG': 'Mid. cingulate gyr.',
'MFC': 'Med. frontal cortex',
'MFG': 'Mid. frontal gyr.',
'MOG': 'Mid. occipital gyr.',
'MOrG': 'Med. orbital gyr.',
'MPoG': 'Post. gyr. med. seg.',
'MPrG': 'Pre. gyr. med. seg.',
'MSFG': 'Sup. frontal gyr. med. seg.',
'MTG': 'Mid. temporal gyr.',
'OCP': 'Occipital pole',
'OFuG': 'Occipital fusiform gyr.',
'OpIFG': 'Opercular part of IFG',
'OrIFG': 'Orbital part of IFG',
'PCgG': 'Post. cingulate gyr.',
'PCu': 'Precuneus',
'PoG': 'Postcentral gyr.',
'POrG': 'Post. orbital gyr.',
'PP': 'Planum polare',
'PrG': 'Precentral gyr.',
'PT': 'Planum temporale',
'SCA': 'Subcallosal area',
'SFG': 'Sup. frontal gyr.',
'SMC': 'Supp. motor cortex',
'SMG': 'Supramarginal gyr.',
'SOG': 'Sup. occipital gyr.',
'STG': 'Sup. temporal gyr.'
}
# Aggregated white matter areas from JHU ICBM DTI atlas from FSL
# Name: (min, max)
wm_areas= {
"Middle cerebellar peduncle": (1, 2),
"Corpus callosum": (3, 5),
"Fornix": (6, 6),
"Corticospinal tract": (7, 8),
"Medial lemniscus": (9, 10),
"Inferior cerebellar peduncle": (11, 12),
"Superior cerebellar peduncle": (13, 14),
"Cerebral peduncle": (15, 16),
"Anterior limb of internal capsule": (17, 18),
"Posterior limb of internal capsule": (19, 20),
"Retrolenticular part of internal capsule": (21, 22),
"Anterior corona radiata": (23, 24),
"Superior corona radiata": (25, 26),
"Posterior corona radiata": (27, 28),
"Posterior thalamic radiation": (29, 30),
"Sagittal stratum": (31, 32),
"External capsule": (33, 34),
"Cingulum": (35, 38),
"Superior longitudinal fasciculus": (41, 42),
"Superior fronto-occipital fasciculus": (43, 44),
"Uncinate fasciculus": (45, 46),
"Tapetum": (47, 48),
}
| 32.813056 | 101 | 0.60038 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4,075 | 0.368511 |
2c1972ea227e28510c531045816167ae977f461e | 1,670 | py | Python | setup.py | lucuma/Shake | b54082c9d217059ef02317aa043c3690d2e601d7 | [
"MIT"
] | 4 | 2015-02-15T17:35:12.000Z | 2016-07-21T06:35:12.000Z | setup.py | lucuma/Shake | b54082c9d217059ef02317aa043c3690d2e601d7 | [
"MIT"
] | null | null | null | setup.py | lucuma/Shake | b54082c9d217059ef02317aa043c3690d2e601d7 | [
"MIT"
] | null | null | null | # coding=utf-8
import io
import os
import re
from setuptools import setup, find_packages
def get_path(*args):
return os.path.join(os.path.dirname(__file__), *args)
def read_from(filepath):
with io.open(filepath, 'rt', encoding='utf8') as f:
return f.read()
def get_requirements(filename='requirements.txt'):
data = read_from(get_path(filename))
lines = map(lambda s: s.strip(), data.splitlines())
return [l for l in lines if l and not l.startswith('#')]
data = read_from(get_path('shake', '__init__.py')).encode('utf8')
version = str(re.search(b"__version__\s*=\s*u?'([^']+)'", data).group(1)).strip()
desc = str(re.search(b'"""(.+)"""', data, re.DOTALL).group(1)).strip()
setup(
name='Shake',
version=version,
author='Lucuma labs',
author_email='info@lucumalabs.com',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
url='http://github.com/lucuma/shake',
license='MIT license (see LICENSE)',
description='A lightweight web framework based on Werkzeug and Jinja2 as an alternative to Flask',
long_description=desc,
install_requires=get_requirements(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: PyPy',
]
)
| 30.925926 | 102 | 0.64491 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 687 | 0.411377 |
2c19b4968a0e3a6289484e46f79c0a118894e2f2 | 3,110 | py | Python | meetup2xibo/updater/phrase_mapper.py | jshprentz/meetup2xibo | 236bef01305878943f27d246dac1b21cc78a521b | [
"MIT"
] | 3 | 2019-11-29T04:32:49.000Z | 2020-06-03T01:34:45.000Z | meetup2xibo/updater/phrase_mapper.py | jshprentz/meetup2xibo | 236bef01305878943f27d246dac1b21cc78a521b | [
"MIT"
] | 194 | 2020-06-01T01:42:41.000Z | 2021-08-02T10:25:58.000Z | meetup2xibo/updater/phrase_mapper.py | jshprentz/meetup2xibo | 236bef01305878943f27d246dac1b21cc78a521b | [
"MIT"
] | 1 | 2019-07-31T14:59:05.000Z | 2019-07-31T14:59:05.000Z | """Map phrases to preferred phrases."""
import logging
from collections import namedtuple
PhraseMapping = namedtuple("PhraseMapping", "preferred_phrase phrase_length")
SortableMatch = namedtuple(
"SortableMatch",
"start descending_phrase_length end preferred_phrase")
class PhraseMapper:
"""Rewrites a string, mapping phrases to preferred phrases."""
logger = logging.getLogger("PhraseMapper")
def __init__(self, automaton, phrase_tuples):
"""Initialize with an Aho-Corasick automaton and a list of tuples
containing a phrase and its preferred phrase."""
self.automaton = automaton
self.phrase_tuples = phrase_tuples
def map_phrases(self, text):
"""Return a list of phrases preferred to those found in the text."""
normalized_text = normalize_text(text)
matches = self.automaton.iter(normalized_text)
sortable_matches = [
match_to_sortable_match(match)
for match in matches
if is_valid_match(match, normalized_text)]
sortable_matches.sort()
longest_matches = longest_non_overlapping_matches(sortable_matches)
return [match.preferred_phrase for match in longest_matches]
def setup(self):
"""Setup and return the phrase mapper."""
for phrase, preferred_phrase in self.phrase_tuples:
normalized_phrase = normalize_text(phrase)
phrase_mapping = PhraseMapping(
preferred_phrase,
len(normalized_phrase))
self.automaton.add_word(normalized_phrase, phrase_mapping)
self.automaton.make_automaton()
return self
def normalize_text(text):
"""Normalize a text by converting it to lower case and removing
excess white space."""
return " ".join(text.casefold().split())
def is_valid_match(match, text):
"""True unless the match starts or ends in the middle of a word."""
end, phrase_mapping = match
start = end - phrase_mapping.phrase_length + 1
return (
end + 1 == len(text)
or (not text[end + 1].isalnum())
or (not text[end].isalnum())
) and (
start == 0
or (not text[start].isalnum())
or (not text[start - 1].isalnum())
)
def match_to_sortable_match(match):
"""Return a sortable match given a match tuple. Matches will be sorted by
start position and decending by phrase length."""
end, phrase_mapping = match
return SortableMatch(
start=end - phrase_mapping.phrase_length,
end=end,
descending_phrase_length=-phrase_mapping.phrase_length,
preferred_phrase=phrase_mapping.preferred_phrase)
def longest_non_overlapping_matches(sorted_matches):
"""Return a generator of the longest non-overlapping matches from a sorted
list of matches."""
start = -1
for match in sorted_matches:
if match.start < start:
continue
yield match
start = match.end
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 autoindent
| 33.44086 | 78 | 0.662058 | 1,401 | 0.450482 | 302 | 0.097106 | 0 | 0 | 0 | 0 | 911 | 0.292926 |
2c19cbf8d9bb1b9d43bac56824e10f5d3f24bc92 | 3,092 | py | Python | hw1/deco.py | Tymeade/otus-python | b5ba2ab4f9c91abc97e6417a5600e4de1bcdb95c | [
"MIT"
] | null | null | null | hw1/deco.py | Tymeade/otus-python | b5ba2ab4f9c91abc97e6417a5600e4de1bcdb95c | [
"MIT"
] | null | null | null | hw1/deco.py | Tymeade/otus-python | b5ba2ab4f9c91abc97e6417a5600e4de1bcdb95c | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import update_wrapper, wraps
def disable(func):
"""
Disable a decorator by re-assigning the decorator's name
to this function. For example, to turn off memoization:
>>> memo = disable
"""
return func
def decorator(decorator_func):
"""
Decorate a decorator so that it inherits the docstrings
and stuff from the function it's decorating.
"""
return update_wrapper(decorator_func, 1)
def countcalls(func):
"""Decorator that counts calls made to the function decorated."""
@wraps(func)
def wrapped(*args, **kwargs):
wrapped.calls += 1
return func(*args, **kwargs)
wrapped.calls = 0
return wrapped
def memo(func):
"""
Memoize a function so that it caches all return values for
faster future lookups.
"""
memory = {}
@wraps(func)
def decorated(*args):
if args in memory:
return memory[args]
answer = func(*args)
memory[args] = answer
return answer
return decorated
def n_ary(func):
"""
Given binary function f(x, y), return an n_ary function such
that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x.
"""
@wraps(func)
def wrapped(*args):
if len(args) == 1:
return args[0]
if len(args) == 2:
return func(*args)
return func(args[0], wrapped(*args[1:]))
return wrapped
def trace(ident):
"""Trace calls made to function decorated.
@trace("____")
def fib(n):
....
>>> fib(3)
--> fib(3)
____ --> fib(2)
________ --> fib(1)
________ <-- fib(1) == 1
________ --> fib(0)
________ <-- fib(0) == 1
____ <-- fib(2) == 2
____ --> fib(1)
____ <-- fib(1) == 1
<-- fib(3) == 3
"""
def deco(func):
@wraps(func)
def wrapped(*args, **kwargs):
arguments = [str(a) for a in args] + ["%s=%s" % (key, value) for key, value in kwargs.iteritems()]
argument_string = ",".join(arguments)
func_name = "%s(%s)" % (func.__name__, argument_string)
wrapped.call_level += 1
print ident * wrapped.call_level, "-->", func_name
answer = func(*args, **kwargs)
print ident * wrapped.call_level, "<--", func_name, "==", answer
wrapped.call_level -= 1
return answer
wrapped.call_level = 0
return wrapped
return deco
@memo
@countcalls
@n_ary
def foo(a, b):
return a + b
@countcalls
@memo
@n_ary
def bar(a, b):
return a * b
@countcalls
@trace("####")
@memo
def fib(n):
"""Some doc"""
return 1 if n <= 1 else fib(n-1) + fib(n-2)
def main():
print foo(4, 3)
print foo(4, 3, 2)
print foo(4, 3)
print "foo was called", foo.calls, "times"
print bar(4, 3)
print bar(4, 3, 2)
print bar(4, 3, 2, 1)
print "bar was called", bar.calls, "times"
print fib.__doc__
fib(3)
print fib.calls, 'calls made'
if __name__ == '__main__':
main()
| 20.342105 | 110 | 0.554334 | 0 | 0 | 0 | 0 | 1,270 | 0.410737 | 0 | 0 | 1,094 | 0.353816 |
2c1a614bb487efce19fb64d000b2277fd8703c04 | 13,670 | py | Python | chunair/kicad-footprint-generator-master/scripts/Connector/Connector_Molex/conn_molex_mini-fit-sr_tht_top_dual.py | speedypotato/chuni-lite | c8dda8428723f8c4f99075e7cbaa22a44cbc187d | [
"CC-BY-4.0"
] | 2 | 2022-03-18T23:42:51.000Z | 2022-03-19T15:31:34.000Z | chunair/kicad-footprint-generator-master/scripts/Connector/Connector_Molex/conn_molex_mini-fit-sr_tht_top_dual.py | speedypotato/chuni-lite | c8dda8428723f8c4f99075e7cbaa22a44cbc187d | [
"CC-BY-4.0"
] | null | null | null | chunair/kicad-footprint-generator-master/scripts/Connector/Connector_Molex/conn_molex_mini-fit-sr_tht_top_dual.py | speedypotato/chuni-lite | c8dda8428723f8c4f99075e7cbaa22a44cbc187d | [
"CC-BY-4.0"
] | null | null | null | #!/usr/bin/env python3
'''
kicad-footprint-generator is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
kicad-footprint-generator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with kicad-footprint-generator. If not, see < http://www.gnu.org/licenses/ >.
'''
import sys
import os
#sys.path.append(os.path.join(sys.path[0],"..","..","kicad_mod")) # load kicad_mod path
# export PYTHONPATH="${PYTHONPATH}<path to kicad-footprint-generator directory>"
sys.path.append(os.path.join(sys.path[0], "..", "..", "..")) # load parent path of KicadModTree
from math import sqrt
import argparse
import yaml
from helpers import *
from KicadModTree import *
sys.path.append(os.path.join(sys.path[0], "..", "..", "tools")) # load parent path of tools
from footprint_text_fields import addTextFields
series = "Mini-Fit_Sr"
series_long = 'Mini-Fit Sr. Power Connectors'
manufacturer = 'Molex'
orientation = 'V'
number_of_rows = 2
datasheet = 'http://www.molex.com/pdm_docs/sd/439151404_sd.pdf'
#pins_per_row per row
pins_per_row_range = [3, 4, 5, 6, 7]
#Molex part number
#n = number of circuits per row
part_code = "43915-xx{n:02}"
pitch = 10
drill = 2.8
offset_second_pad = 4.4
pitch_row = offset_second_pad + 8.06
pad_to_pad_clearance = 3
max_annular_ring = 1
min_annular_ring = 0.15
#locating pins
x_loc = 8.43
r_loc = 3.0
pad_size = [offset_second_pad + 0.1, pitch - pad_to_pad_clearance]
if pad_size[1] - drill < 2*min_annular_ring:
pad_size[1] = drill + 2*min_annular_ring
if pad_size[1] - drill > 2*max_annular_ring:
pad_size[1] = drill + 2*max_annular_ring
version_params = {
'with_thermals':{
'description': ', With thermal vias in pads',
'fp_name_suffix': '_ThermalVias',
'thermals': True
},
'only_pads':{
'description': '',
'fp_name_suffix': '',
'thermals': False
}
}
def generate_one_footprint(pins, params, configuration):
pad_silk_off = configuration['silk_pad_clearance'] + configuration['silk_line_width']/2
mpn = part_code.format(n=pins*number_of_rows)
# handle arguments
orientation_str = configuration['orientation_options'][orientation]
footprint_name = configuration['fp_name_format_string'].format(man=manufacturer,
series=series,
mpn=mpn, num_rows=number_of_rows, pins_per_row=pins_per_row, mounting_pad = "",
pitch=pitch, orientation=orientation_str)
footprint_name += params['fp_name_suffix']
kicad_mod = Footprint(footprint_name)
desc_format_str = "Molex {:s}, {:s}{:s}, {:d} Pins per row ({:s}), generated with kicad-footprint-generator"
kicad_mod.setDescription(desc_format_str.format(series_long, mpn, params['description'], pins, datasheet))
kicad_mod.setTags(configuration['keyword_fp_string'].format(series=series,
orientation=orientation_str, man=manufacturer,
entry=configuration['entry_direction'][orientation]))
#calculate fp dimensions
#ref: http://www.molex.com/pdm_docs/sd/439151404_sd.pdf
#A = distance between mounting holes
A = pins * pitch + 1.41
#B = distance between end pin centers
B = (pins - 1) * pitch
#E = length of part
E = pins * pitch + 0.9
#connector width
W = 19.16
#corner positions
y1 = -(E-B)/2
y2 = y1 + E
x1 = -1.15
x2 = x1 + W
TL = 5
TW = 13
body_edge={
'left':x1,
'right':x2,
'bottom':y2,
'top': y1
}
bounding_box = {
'left': -pad_size[0]/2,
'right': pitch_row + offset_second_pad + pad_size[0]/2
}
pad_silk_off = configuration['silk_pad_clearance'] + configuration['silk_line_width']/2
#generate the pads
for row_idx in range(2):
for pad_idx in range(2):
kicad_mod.append(PadArray(
pincount=pins, start=[row_idx*pitch_row + pad_idx*offset_second_pad, 0],
initial=row_idx*pins+1, y_spacing=pitch, size=pad_size, drill=drill,
type=Pad.TYPE_THT, shape=Pad.SHAPE_RECT, layers=Pad.LAYERS_THT,
tht_pad1_shape=Pad.SHAPE_RECT))
#thermal vias
d_small = 0.3
s_small = d_small + 2*min_annular_ring
thermal_to_pad_edge = s_small/2 + 0.15
if params['thermals']:
for yi in range(pins):
for xi in range(number_of_rows):
n = xi*pins + yi + 1
pad_center_x = xi*pitch_row + offset_second_pad/2
pad_center_y = yi*pitch
pad_l = offset_second_pad + pad_size[0]
dy = (pad_size[1] - 2*thermal_to_pad_edge)/2
dx = (pad_l - 2*thermal_to_pad_edge)/4
#draw rectangle on F.Fab layer
# kicad_mod.append(RectLine(
# start=[pad_center_x - pad_l/2, pad_center_y - pad_size[1]/2],
# end=[pad_center_x + pad_l/2, pad_center_y + pad_size[1]/2],
# layer='F.Fab', width=configuration['fab_line_width']))
kicad_mod.append(PadArray(center=[pad_center_x, pad_center_y],
pincount=3, x_spacing=dx*2,
drill=d_small, size=s_small, initial=n, increment=0,
shape=Pad.SHAPE_CIRCLE, type=Pad.TYPE_THT, layers=Pad.LAYERS_THT))
kicad_mod.append(PadArray(center=[pad_center_x, pad_center_y - dy],
pincount=5, x_spacing=dx,
drill=d_small, size=s_small, initial=n, increment=0,
type=Pad.TYPE_THT, shape=Pad.SHAPE_CIRCLE, layers=Pad.LAYERS_THT))
kicad_mod.append(PadArray(center=[pad_center_x, pad_center_y + dy],
pincount=5, x_spacing=dx,
drill=d_small, size=s_small, initial=n, increment=0,
type=Pad.TYPE_THT, shape=Pad.SHAPE_CIRCLE, layers=Pad.LAYERS_THT))
# locating pins
kicad_mod.append(Pad(at=[x_loc, 5], type=Pad.TYPE_NPTH, shape=Pad.SHAPE_CIRCLE,
size=r_loc, drill=r_loc, layers=Pad.LAYERS_NPTH))
kicad_mod.append(Pad(at=[x_loc, B/2-A/2], type=Pad.TYPE_THT, shape=Pad.SHAPE_CIRCLE,
size=r_loc+0.5, drill=r_loc, layers=Pad.LAYERS_THT))
kicad_mod.append(Pad(at=[x_loc, B/2+A/2], type=Pad.TYPE_THT, shape=Pad.SHAPE_CIRCLE,
size=r_loc+0.5, drill=r_loc, layers=Pad.LAYERS_THT))
#mark pin-1 (bottom layer)
kicad_mod.append(RectLine(start=[-pad_size[0]/2, -pad_size[1]/2],
end=[offset_second_pad + pad_size[0]/2,pad_size[1]/2],offset=pad_silk_off,
width=configuration['silk_line_width'], layer='B.SilkS'))
#draw connector outline (basic)
kicad_mod.append(RectLine(start=[x1,y1],end=[x2,y2],
width=configuration['fab_line_width'], layer='F.Fab'))
#connector outline on F.SilkScreen
off = configuration['silk_line_width']
corner = [
{'y': -pad_size[1]/2 - pad_silk_off, 'x': x1-off},
{'y': y1 - off, 'x': x1-off},
{'y': y1 - off, 'x': x_loc-r_loc/2-0.5},
]
# kicad_mod.append(PolygoneLine(polygone=corner,
# width=configuration['silk_line_width'], layer='F.SilkS'))
kicad_mod.append(Line(start=[x_loc-r_loc/2-0.5, y1 - off],
end=[x_loc-TW/2-off, y1 - off],
width=configuration['silk_line_width'], layer='F.SilkS'))
kicad_mod.append(PolygoneLine(polygone=corner,y_mirror=B/2,
width=configuration['silk_line_width'], layer='F.SilkS'))
kicad_mod.append(PolygoneLine(polygone=corner,x_mirror=x_loc,
width=configuration['silk_line_width'], layer='F.SilkS'))
kicad_mod.append(PolygoneLine(polygone=corner,y_mirror=B/2,x_mirror=x_loc,
width=configuration['silk_line_width'], layer='F.SilkS'))
#silk-screen between each pad
for i in range(pins-1):
ya = i * pitch + pad_size[1]/2 + pad_silk_off
yb = (i+1) * pitch - pad_size[1]/2 - pad_silk_off
kicad_mod.append(Line(start=[x1-off, ya],end=[x1-off, yb],
width=configuration['silk_line_width'], layer='F.SilkS'))
kicad_mod.append(Line(start=[x2+off, ya],end=[x2+off, yb],
width=configuration['silk_line_width'], layer='F.SilkS'))
#draw the tabs at each end
def offsetPoly(poly_points, o , center_x, center_y):
new_points = []
for point in poly_points:
new_points.append(
{
'y': point['y'] + (o if point['y'] > center_y else -o),
'x': point['x'] + (o if point['x'] > center_x else -o)
}
)
return new_points
tab = [
{'y': y1,'x': x_loc-TW/2},
{'y': y1-TL,'x': x_loc-TW/2},
{'y': y1-TL,'x': x_loc+TW/2},
{'y': y1,'x': x_loc+TW/2},
]
kicad_mod.append(PolygoneLine(polygone=tab,
width=configuration['fab_line_width'], layer='F.Fab'))
kicad_mod.append(PolygoneLine(polygone=tab, y_mirror=B/2,
width=configuration['fab_line_width'], layer='F.Fab'))
tap_off = offsetPoly(tab, off, x_loc, B/2)
kicad_mod.append(PolygoneLine(polygone=tap_off,
width=configuration['silk_line_width'], layer='F.SilkS'))
kicad_mod.append(PolygoneLine(polygone=tap_off, y_mirror=B/2,
width=configuration['silk_line_width'], layer='F.SilkS'))
bounding_box['top'] = y1 - TL
bounding_box['bottom'] = y2 + TL
#inner-tab
T = 2
tab = [
{'y': y1-off,'x': x_loc-TW/2-off+T},
{'y': y1-off-TL+T,'x': x_loc-TW/2-off+T},
{'y': y1-off-TL+T,'x': x_loc+TW/2+off-T},
{'y': y1-off,'x': x_loc+TW/2+off-T},
]
kicad_mod.append(PolygoneLine(polygone=tab,
width=configuration['silk_line_width'], layer='F.SilkS'))
kicad_mod.append(PolygoneLine(polygone=tab,y_mirror=B/2,
width=configuration['silk_line_width'], layer='F.SilkS'))
#pin-1 marker
x = x1 - 1.5
m = 0.4
pin = [
{'x': x,'y': 0},
{'x': x-2*m,'y': -m},
{'x': x-2*m,'y': +m},
{'x': x,'y': 0},
]
kicad_mod.append(PolygoneLine(polygone=pin,
width=configuration['silk_line_width'], layer='F.SilkS'))
sl=3
pin = [
{'x': body_edge['left'], 'y': -sl/2},
{'x': body_edge['left'] + sl/sqrt(2), 'y': 0},
{'x': body_edge['left'], 'y': sl/2}
]
kicad_mod.append(PolygoneLine(polygone=pin,
width=configuration['fab_line_width'], layer='F.Fab'))
########################### CrtYd #################################
cx1 = roundToBase(bounding_box['left']-configuration['courtyard_offset']['connector'], configuration['courtyard_grid'])
cy1 = roundToBase(bounding_box['top']-configuration['courtyard_offset']['connector'], configuration['courtyard_grid'])
cx2 = roundToBase(bounding_box['right']+configuration['courtyard_offset']['connector'], configuration['courtyard_grid'])
cy2 = roundToBase(bounding_box['bottom'] + configuration['courtyard_offset']['connector'], configuration['courtyard_grid'])
kicad_mod.append(RectLine(
start=[cx1, cy1], end=[cx2, cy2],
layer='F.CrtYd', width=configuration['courtyard_line_width']))
######################### Text Fields ###############################
addTextFields(kicad_mod=kicad_mod, configuration=configuration, body_edges=body_edge,
courtyard={'top':cy1, 'bottom':cy2}, fp_name=footprint_name, text_y_inside_position='bottom')
##################### Output and 3d model ############################
model3d_path_prefix = configuration.get('3d_model_prefix','${KICAD6_3DMODEL_DIR}/')
lib_name = configuration['lib_name_format_string'].format(series=series, man=manufacturer)
model_name = '{model3d_path_prefix:s}{lib_name:s}.3dshapes/{fp_name:s}.wrl'.format(
model3d_path_prefix=model3d_path_prefix, lib_name=lib_name, fp_name=footprint_name)
kicad_mod.append(Model(filename=model_name))
output_dir = '{lib_name:s}.pretty/'.format(lib_name=lib_name)
if not os.path.isdir(output_dir): #returns false if path does not yet exist!! (Does not check path validity)
os.makedirs(output_dir)
filename = '{outdir:s}{fp_name:s}.kicad_mod'.format(outdir=output_dir, fp_name=footprint_name)
file_handler = KicadFileHandler(kicad_mod)
file_handler.writeFile(filename)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='use confing .yaml files to create footprints.')
parser.add_argument('--global_config', type=str, nargs='?', help='the config file defining how the footprint will look like. (KLC)', default='../../tools/global_config_files/config_KLCv3.0.yaml')
parser.add_argument('--series_config', type=str, nargs='?', help='the config file defining series parameters.', default='../conn_config_KLCv3.yaml')
args = parser.parse_args()
with open(args.global_config, 'r') as config_stream:
try:
configuration = yaml.safe_load(config_stream)
except yaml.YAMLError as exc:
print(exc)
with open(args.series_config, 'r') as config_stream:
try:
configuration.update(yaml.safe_load(config_stream))
except yaml.YAMLError as exc:
print(exc)
for version in version_params:
for pins_per_row in pins_per_row_range:
generate_one_footprint(pins_per_row, version_params[version], configuration)
| 38.615819 | 199 | 0.640234 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4,006 | 0.29305 |
2c1a887bbd2d5ae6437d92ebd5ad09e7ede709e9 | 1,048 | py | Python | AprendeAyudando/forum/migrations/0001_initial.py | memoriasIT/AprendeAyudando | 0a32f59d3606075abb99a74ce1983a6171aa34cd | [
"CC0-1.0"
] | 1 | 2021-09-09T09:54:04.000Z | 2021-09-09T09:54:04.000Z | AprendeAyudando/forum/migrations/0001_initial.py | memoriasIT/AprendeAyudando | 0a32f59d3606075abb99a74ce1983a6171aa34cd | [
"CC0-1.0"
] | null | null | null | AprendeAyudando/forum/migrations/0001_initial.py | memoriasIT/AprendeAyudando | 0a32f59d3606075abb99a74ce1983a6171aa34cd | [
"CC0-1.0"
] | null | null | null | # Generated by Django 3.1.3 on 2020-11-28 23:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Forum',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('enrolled_users', models.ManyToManyField(blank=True, related_name='forums', to=settings.AUTH_USER_MODEL)),
('teacher', models.ForeignKey(limit_choices_to={'groups__name': 'Profesor'}, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Foro',
'verbose_name_plural': 'Foros',
},
),
]
| 33.806452 | 179 | 0.622137 | 889 | 0.848282 | 0 | 0 | 0 | 0 | 0 | 0 | 174 | 0.166031 |
2c1b704a0373251585df63bff52ef28aefddc95f | 1,158 | py | Python | utils/utils.py | dtiarks/pg_agents | 321651a9d03c3836541c54bac4861bb576086e42 | [
"MIT"
] | 4 | 2018-05-23T05:46:10.000Z | 2020-05-13T23:20:15.000Z | utils/utils.py | dtiarks/pg_agents | 321651a9d03c3836541c54bac4861bb576086e42 | [
"MIT"
] | 1 | 2018-03-12T01:13:44.000Z | 2018-03-12T01:13:44.000Z | utils/utils.py | dtiarks/pg_agents | 321651a9d03c3836541c54bac4861bb576086e42 | [
"MIT"
] | null | null | null | import numpy as np
def flatten_array_list(a_list):
return np.concatenate([l.ravel() for l in a_list])
def unflatten_array_list(array, shapes):
c = 0
l = []
for s in shapes:
tmp = np.array(array[c:c + np.prod(s)])
reshaped = np.reshape(tmp, s)
c += np.prod(s)
l.append(reshaped)
return l
def cg_solve(Ax_prod, b, x_init):
x = x_init
r = b - Ax_prod(x)
p = r
rsold = np.dot(r, r)
for i in range(20):
Ap = Ax_prod(p)
alpha = rsold / np.dot(p, Ap)
x = x + alpha * p
r = r - alpha * Ap
rsnew = np.dot(r, r)
# print(np.sqrt(rsnew))
if (np.sqrt(rsnew) < 1e-10):
return x
beta = np.true_divide(rsnew, rsold)
p = r + beta * p
rsold = rsnew
return x
# A=[[4.,1.],[1.,3.]]
# b=[1.,2.]
# x_init=[2.,1.]
# Ax_prod=lambda x:np.dot(A,x)
# print(cg_solve(Ax_prod,b,x_init))
# shape_list=[(2,2,1),(3,3),(4,4)]
# array_list=[s[0]*np.ones(s) for s in shape_list]
# flat=flatten_array_list(array_list)
# unflat=unflatten_array_list(flat,shape_list)
# print(array_list)
# print(unflat)
| 17.283582 | 54 | 0.547496 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 337 | 0.291019 |
2c1c0560ca30de9f1d31898b330aaa3130eb4feb | 804 | py | Python | clay/markdown_ext/jinja.py | TuxCoder/Clay | 04f15b4d742b14d09df9049dd91cfa4386cba66e | [
"MIT"
] | null | null | null | clay/markdown_ext/jinja.py | TuxCoder/Clay | 04f15b4d742b14d09df9049dd91cfa4386cba66e | [
"MIT"
] | null | null | null | clay/markdown_ext/jinja.py | TuxCoder/Clay | 04f15b4d742b14d09df9049dd91cfa4386cba66e | [
"MIT"
] | null | null | null | # coding=utf-8
import os
import jinja2
import jinja2.ext
from .render import md_to_jinja
MARKDOWN_EXTENSION = '.md'
class MarkdownExtension(jinja2.ext.Extension):
def preprocess(self, source, name, filename=None):
if name is None or os.path.splitext(name)[1] != MARKDOWN_EXTENSION:
return source
_source, meta = md_to_jinja(source)
self.meta = meta or {}
self.environment.globals.update(meta)
return _source
def _from_string(self, source, globals=None, template_class=None):
env = self.environment
globals = env.make_globals(globals)
cls = template_class or env.template_class
template_name = 'markdown_from_string.md'
return cls.from_code(env, env.compile(source, template_name), globals, None)
| 27.724138 | 84 | 0.689055 | 681 | 0.847015 | 0 | 0 | 0 | 0 | 0 | 0 | 44 | 0.054726 |
2c1c31e1395ffc1971b2b93851e2582898ff12e7 | 1,553 | py | Python | FWCore/Modules/test/emptysource_firstLuminosityBlockForEachRun_cfg.py | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | 1 | 2019-03-09T19:47:49.000Z | 2019-03-09T19:47:49.000Z | FWCore/Modules/test/emptysource_firstLuminosityBlockForEachRun_cfg.py | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | null | null | null | FWCore/Modules/test/emptysource_firstLuminosityBlockForEachRun_cfg.py | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | 1 | 2019-03-19T13:44:54.000Z | 2019-03-19T13:44:54.000Z | # Configuration file for EmptySource
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("FWCore.Framework.test.cmsExceptionsFatal_cff")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(8*5)
)
runToLumi = ((2,1),(10,3),(20,7) )
def findRunForLumi( lumi) :
lastRun = runToLumi[0][0]
for r,l in runToLumi:
if l > lumi:
break
lastRun = r
return lastRun
process.source = cms.Source("EmptySource",
firstLuminosityBlock = cms.untracked.uint32(1),
firstLuminosityBlockForEachRun = cms.untracked.VLuminosityBlockID(*[cms.LuminosityBlockID(x,y) for x,y in runToLumi]),
numberEventsInLuminosityBlock = cms.untracked.uint32(5),
firstTime = cms.untracked.uint64(1000),
timeBetweenEvents = cms.untracked.uint64(10)
)
ids = cms.VEventID()
numberOfEventsInLumi = 0
numberOfEventsPerLumi = process.source.numberEventsInLuminosityBlock.value()
lumi = process.source.firstLuminosityBlock.value()
event=0
oldRun = 2
for i in xrange(process.maxEvents.input.value()):
numberOfEventsInLumi +=1
event += 1
run = findRunForLumi(lumi)
if numberOfEventsInLumi > numberOfEventsPerLumi:
numberOfEventsInLumi=1
lumi += 1
run = findRunForLumi(lumi)
if run != oldRun:
event = 1
oldRun = run
ids.append(cms.EventID(run,lumi,event))
process.check = cms.EDAnalyzer("EventIDChecker", eventSequence = cms.untracked(ids))
process.print1 = cms.OutputModule("AsciiOutputModule")
process.p = cms.EndPath(process.check+process.print1)
| 29.301887 | 122 | 0.728912 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 136 | 0.087572 |
2c1ca54b5401d6fe3df69b6981ac878708992788 | 3,666 | py | Python | fewshot/models/refine_model.py | ashok-arjun/few-shot-ssl-public | f7577d80b7491e0f27234a2e9c0113782365c2e1 | [
"MIT"
] | 497 | 2018-03-02T00:50:53.000Z | 2022-03-22T06:30:59.000Z | fewshot/models/refine_model.py | eleniTriantafillou/few-shot-ssl-public | 3cf522031aa40b4ffb61e4693d0b48fdd5669276 | [
"MIT"
] | 20 | 2018-03-19T06:15:30.000Z | 2021-11-20T07:21:38.000Z | fewshot/models/refine_model.py | eleniTriantafillou/few-shot-ssl-public | 3cf522031aa40b4ffb61e4693d0b48fdd5669276 | [
"MIT"
] | 108 | 2018-03-02T06:56:13.000Z | 2021-12-23T03:40:43.000Z | # Copyright (c) 2018 Mengye Ren, Eleni Triantafillou, Sachin Ravi, Jake Snell,
# Kevin Swersky, Joshua B. Tenenbaum, Hugo Larochelle, Richars S. Zemel.
#
# 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.
# =============================================================================
"""
A few-shot classification model implementation that refines on unlabled
refinement images.
Author: Mengye Ren (mren@cs.toronto.edu)
A single episode is divided into three parts:
1) Labeled reference images (self.x_ref).
2) Unlabeled refinement images (self.x_unlabel).
3) Labeled query images (from validation) (self.x_candidate).
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import tensorflow as tf
from fewshot.models.nnlib import cnn, weight_variable, concat
from fewshot.models.basic_model import BasicModel
from fewshot.utils import logger
log = logger.get()
# Load up the LSTM cell implementation.
if tf.__version__.startswith("0"):
BasicLSTMCell = tf.nn.rnn_cell.BasicLSTMCell
LSTMStateTuple = tf.nn.rnn_cell.LSTMStateTuple
else:
BasicLSTMCell = tf.contrib.rnn.BasicLSTMCell
LSTMStateTuple = tf.contrib.rnn.LSTMStateTuple
class RefineModel(BasicModel):
"""A retrieval model with an additional refinement stage."""
def __init__(self,
config,
nway=1,
nshot=1,
num_unlabel=10,
candidate_size=10,
is_training=True,
dtype=tf.float32):
"""Initiliazer.
Args:
config: Model configuration object.
nway: Int. Number of classes in the reference images.
nshot: Int. Number of labeled reference images.
num_unlabel: Int. Number of unlabeled refinement images.
candidate_size: Int. Number of candidates in the query stage.
is_training: Bool. Whether is in training mode.
dtype: TensorFlow data type.
"""
self._num_unlabel = num_unlabel
self._x_unlabel = tf.placeholder(
dtype, [None, None, config.height, config.width, config.num_channel],
name="x_unlabel")
self._y_unlabel = tf.placeholder(dtype, [None, None], name="y_unlabel")
super(RefineModel, self).__init__(
config,
nway=nway,
nshot=nshot,
num_test=candidate_size,
is_training=is_training,
dtype=dtype)
@property
def x_unlabel(self):
return self._x_unlabel
@property
def y_unlabel(self):
return self._y_unlabel
if __name__ == "__main__":
from fewshot.configs.omniglot_config import OmniglotRefineConfig
model = RefineModel(OmniglotRefineConfig())
| 37.030303 | 80 | 0.707038 | 1,293 | 0.3527 | 0 | 0 | 118 | 0.032188 | 0 | 0 | 2,157 | 0.58838 |