id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1 value |
|---|---|---|
9711461 | <reponame>zinaukarenku/zkr-platform
# Generated by Django 2.1.1 on 2018-10-11 07:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('questions', '0003_auto_20181011_1044'),
]
operations = [
migrations.AlterField(
model_name='politiciananswer',
name='question',
field=models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='politian_answer', to='questions.Question'),
),
]
| StarcoderdataPython |
1675626 | <filename>bobstack/tests/test_sipmessaging_sipResponse.py
from abstractSIPResponseTestCase import AbstractSIPResponseTestCase
from ..sipmessaging import SIPResponse
class TestSIPResponse(AbstractSIPResponseTestCase):
@property
def status_code(self):
return 100
@property
def reason_phrase(self):
return "Trying"
@property
def sipMessageClassUnderTest(self):
return SIPResponse
def test_parsing(self):
self.run_test_parsing()
def test_rendering_from_list_of_header_fields(self):
self.run_test_rendering_from_list_of_header_fields()
def test_rendering_from_one_big_header_string(self):
self.run_test_rendering_from_one_big_header_string()
# TODO - skipping for now.
# @unittest.skip("temporarily skipping...")
def test_rendering_from_one_big_header_string_with_folding(self):
self.run_test_rendering_from_one_big_header_string_with_folding()
def test_rendering_from_list_of_header_field_strings(self):
self.run_test_rendering_from_list_of_header_field_strings()
def test_rendering_from_list_of_field_names_and_values(self):
self.run_test_rendering_from_list_of_field_names_and_values()
def test_rendering_from_list_of_field_names_and_values_using_property_dict(self):
self.run_test_rendering_from_list_of_field_names_and_values_using_property_dict()
def runAssertionsForSIPMessage(self, a_sip_response):
super(TestSIPResponse, self).runAssertionsForSIPMessage(a_sip_response)
self.assertTrue(a_sip_response.is_known)
self.assertFalse(a_sip_response.is_unknown)
self.assertFalse(a_sip_response.is_ack_request)
self.assertFalse(a_sip_response.is_bye_request)
self.assertFalse(a_sip_response.is_cancel_request)
self.assertFalse(a_sip_response.is_info_request)
self.assertFalse(a_sip_response.is_invite_request)
self.assertFalse(a_sip_response.is_notify_request)
self.assertFalse(a_sip_response.is_notify_request)
self.assertFalse(a_sip_response.is_prack_request)
self.assertFalse(a_sip_response.is_publish_request)
self.assertFalse(a_sip_response.is_message_request)
self.assertFalse(a_sip_response.is_refer_request)
self.assertFalse(a_sip_response.is_register_request)
self.assertFalse(a_sip_response.is_subscribe_request)
self.assertFalse(a_sip_response.is_update_request)
| StarcoderdataPython |
6590875 | <reponame>ptoman/SimpleML<gh_stars>10-100
"""Empty Database
Revision ID: 0680f18b52ca
Revises:
Create Date: 2019-01-22 20:10:03.581025
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
| StarcoderdataPython |
59473 | # foo
# <caret>
pass | StarcoderdataPython |
6665975 | """ Signals used by the app. """
__author__ = "<NAME>"
__date__ = "2018-03-14"
__copyright__ = "Copyright 2019 United Kingdom Research and Innovation"
__license__ = "BSD - see LICENSE file in top-level package directory"
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from uploader.utils.streams import create_data_directory
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_uploader_profile(sender, instance, created, **kwargs):
'''
Called when a Django user is saved
'''
# We are only interested in newly created users
if created:
if not hasattr(settings, 'AUTO_CREATE_DATA_DIR') or settings.AUTO_CREATE_DATA_DIR:
create_data_directory(instance)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def save_user_uploader_profile(sender, instance, **kwargs):
'''
Called when a Django user is saved
'''
if hasattr(instance, 'uploaderprofile'):
instance.uploaderprofile.save()
| StarcoderdataPython |
1801101 | <reponame>take2rohit/monk_v1<filename>monk/tf_keras_1/transforms/transforms.py<gh_stars>100-1000
from monk.tf_keras_1.transforms.imports import *
from monk.system.imports import *
@accepts(dict, [list, float, int], [list, float, int], [list, float, int], [list, float, int], bool, bool, bool, retrieve=bool, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def transform_color_jitter(system_dict, brightness, contrast, saturation, hue, train, val, test, retrieve=False):
'''
Apply Color jittering transformations
Args:
system_dict (dict): System dictionary storing experiment state and set variables
brightness (float): Levels to jitter brightness.
0 - min
1 - max
contrast (float): Levels to jitter contrast.
0 - min
1 - max
saturation (float): Levels to jitter saturation.
0 - min
1 - max
hue (float): Levels to jitter hue.
0 - min
1 - max
train (bool): If True, transform applied to training data
val (bool): If True, transform applied to validation data
test (bool): If True, transform applied to testing/inferencing data
Returns:
dict: updated system dict
'''
tmp = {};
tmp["ColorJitter"] = {};
tmp["ColorJitter"]["brightness"] = brightness;
if(contrast or saturation or hue):
msg = "Unimplemented - contrast, saturation, hue.\n";
ConstraintWarning(msg);
tmp["ColorJitter"]["contrast"] = contrast;
tmp["ColorJitter"]["saturation"] = saturation;
tmp["ColorJitter"]["hue"] = hue;
if(train):
if(not retrieve):
system_dict["dataset"]["transforms"]["train"].append(tmp);
system_dict["local"]["transforms_train"]["brightness_range"] = [max(0, 1-brightness), 1+brightness];
if(val):
if(not retrieve):
system_dict["dataset"]["transforms"]["val"].append(tmp);
system_dict["local"]["transforms_val"]["brightness_range"] = [max(0, 1-brightness), 1+brightness];
if(test):
if(not retrieve):
system_dict["dataset"]["transforms"]["test"].append(tmp);
system_dict["local"]["transforms_test"]["brightness_range"] = [max(0, 1-brightness), 1+brightness];
return system_dict;
@accepts(dict, [list, float, int], [tuple, list, type(None)], [tuple, list, type(None)], [list, float, int, tuple, type(None)],
bool, bool, bool, retrieve=bool, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def transform_random_affine(system_dict, degrees, translate, scale, shear, train, val, test, retrieve=False):
'''
Apply random affine transformations
Args:
system_dict (dict): System dictionary storing experiment state and set variables
degrees (float): Max Rotation range limit for transforms
scale (float, list): Range for randomly scaling
shear (float, list): Range for randomly applying sheer changes
train (bool): If True, transform applied to training data
val (bool): If True, transform applied to validation data
test (bool): If True, transform applied to testing/inferencing data
Returns:
dict: updated system dict
'''
tmp = {};
tmp["RandomAffine"] = {};
tmp["RandomAffine"]["degrees"] = degrees;
tmp["RandomAffine"]["translate"] = translate;
tmp["RandomAffine"]["scale"] = scale;
tmp["RandomAffine"]["shear"] = shear;
if(train):
if(not retrieve):
system_dict["dataset"]["transforms"]["train"].append(tmp);
system_dict["local"]["transforms_train"]["rotation_range"] = degrees;
system_dict["local"]["transforms_train"]["width_shift_range"] = translate;
system_dict["local"]["transforms_train"]["height_shift_range"] = degrees;
system_dict["local"]["transforms_train"]["zoom_range"] = scale;
system_dict["local"]["transforms_train"]["shear_range"] = shear;
if(val):
if(not retrieve):
system_dict["dataset"]["transforms"]["val"].append(tmp);
system_dict["local"]["transforms_val"]["rotation_range"] = degrees;
system_dict["local"]["transforms_val"]["width_shift_range"] = translate;
system_dict["local"]["transforms_val"]["height_shift_range"] = degrees;
system_dict["local"]["transforms_val"]["zoom_range"] = scale;
system_dict["local"]["transforms_val"]["shear_range"] = shear;
if(test):
if(not retrieve):
system_dict["dataset"]["transforms"]["test"].append(tmp);
system_dict["local"]["transforms_test"]["rotation_range"] = degrees;
system_dict["local"]["transforms_test"]["width_shift_range"] = translate;
system_dict["local"]["transforms_test"]["height_shift_range"] = degrees;
system_dict["local"]["transforms_test"]["zoom_range"] = scale;
system_dict["local"]["transforms_test"]["shear_range"] = shear;
return system_dict;
@accepts(dict, float, bool, bool, bool, retrieve=bool, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def transform_random_horizontal_flip(system_dict, probability, train, val, test, retrieve=False):
'''
Apply random horizontal flip transformations
Args:
system_dict (dict): System dictionary storing experiment state and set variables
probability (float): Probability of flipping the input image
train (bool): If True, transform applied to training data
val (bool): If True, transform applied to validation data
test (bool): If True, transform applied to testing/inferencing data
Returns:
dict: updated system dict
'''
tmp = {};
tmp["RandomHorizontalFlip"] = {};
tmp["RandomHorizontalFlip"]["p"] = probability;
if(train):
if(not retrieve):
system_dict["dataset"]["transforms"]["train"].append(tmp);
system_dict["local"]["transforms_train"]["horizontal_flip"] = True;
if(val):
if(not retrieve):
system_dict["dataset"]["transforms"]["val"].append(tmp);
system_dict["local"]["transforms_val"]["horizontal_flip"] = True;
if(test):
if(not retrieve):
system_dict["dataset"]["transforms"]["test"].append(tmp);
system_dict["local"]["transforms_test"]["horizontal_flip"] = True;
return system_dict;
@accepts(dict, float, bool, bool, bool, retrieve=bool, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def transform_random_vertical_flip(system_dict, probability, train, val, test, retrieve=False):
'''
Apply random vertical flip transformations
Args:
system_dict (dict): System dictionary storing experiment state and set variables
probability (float): Probability of flipping the input image
train (bool): If True, transform applied to training data
val (bool): If True, transform applied to validation data
test (bool): If True, transform applied to testing/inferencing data
Returns:
dict: updated system dict
'''
tmp = {};
tmp["RandomVerticalFlip"] = {};
tmp["RandomVerticalFlip"]["p"] = probability;
if(train):
if(not retrieve):
system_dict["dataset"]["transforms"]["train"].append(tmp);
system_dict["local"]["transforms_train"]["horizontal_flip"] = True;
if(val):
if(not retrieve):
system_dict["dataset"]["transforms"]["val"].append(tmp);
system_dict["local"]["transforms_val"]["horizontal_flip"] = True;
if(test):
if(not retrieve):
system_dict["dataset"]["transforms"]["test"].append(tmp);
system_dict["local"]["transforms_test"]["horizontal_flip"] = True;
return system_dict;
@accepts(dict, [float, int, list], bool, bool, bool, retrieve=bool, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def transform_random_rotation(system_dict, degrees, train, val, test, retrieve=False):
'''
Apply random rotation transformations
Args:
system_dict (dict): System dictionary storing experiment state and set variables
degrees (float): Max Rotation range limit for transforms
train (bool): If True, transform applied to training data
val (bool): If True, transform applied to validation data
test (bool): If True, transform applied to testing/inferencing data
Returns:
dict: updated system dict
'''
tmp = {};
tmp["RandomRotation"] = {};
tmp["RandomRotation"]["degrees"] = degrees;
if(train):
if(not retrieve):
system_dict["dataset"]["transforms"]["train"].append(tmp);
system_dict["local"]["transforms_train"]["rotation_range"] = degrees;
if(val):
if(not retrieve):
system_dict["dataset"]["transforms"]["val"].append(tmp);
system_dict["local"]["transforms_val"]["rotation_range"] = degrees;
if(test):
if(not retrieve):
system_dict["dataset"]["transforms"]["test"].append(tmp);
system_dict["local"]["transforms_test"]["rotation_range"] = degrees;
return system_dict;
@accepts(dict, [float, list], bool, bool, bool, retrieve=bool, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def transform_mean_subtraction(system_dict, mean, train, val, test, retrieve=False):
'''
Apply mean subtraction
Args:
system_dict (dict): System dictionary storing experiment state and set variables
mean (float, list): Mean value for subtraction
train (bool): If True, transform applied to training data
val (bool): If True, transform applied to validation data
test (bool): If True, transform applied to testing/inferencing data
Returns:
dict: updated system dict
'''
tmp = {};
tmp["MeanSubtraction"] = {};
tmp["MeanSubtraction"]["mean"] = mean;
system_dict["local"]["mean_subtract"] = True;
if(train):
if(not retrieve):
system_dict["dataset"]["transforms"]["train"].append(tmp);
system_dict["local"]["transforms_train"]["mean"] = np.array(mean)*255;
system_dict["local"]["transforms_train"]["featurewise_center"] = True;
if(val):
if(not retrieve):
system_dict["dataset"]["transforms"]["val"].append(tmp);
system_dict["local"]["transforms_val"]["mean"] = np.array(mean)*255;
system_dict["local"]["transforms_val"]["featurewise_center"] = True;
if(test):
if(not retrieve):
system_dict["dataset"]["transforms"]["test"].append(tmp);
system_dict["local"]["transforms_test"]["mean"] = np.array(mean)*255;
system_dict["local"]["transforms_test"]["featurewise_center"] = True;
return system_dict;
@accepts(dict, [float, list], [float, list], bool, bool, bool, retrieve=bool, post_trace=False)
#@TraceFunction(trace_args=False, trace_rv=False)
def transform_normalize(system_dict, mean, std, train, val, test, retrieve=False):
'''
Apply mean subtraction and standard normalization
Args:
system_dict (dict): System dictionary storing experiment state and set variables
mean (float, list): Mean value for subtraction
std (float, list): Normalization factor
train (bool): If True, transform applied to training data
val (bool): If True, transform applied to validation data
test (bool): If True, transform applied to testing/inferencing data
Returns:
dict: updated system dict
'''
tmp = {};
tmp["Normalize"] = {};
tmp["Normalize"]["mean"] = mean;
tmp["Normalize"]["std"] = std;
system_dict["local"]["normalize"] = True;
input_size = system_dict["dataset"]["params"]["input_size"];
if(train):
if(not retrieve):
system_dict["dataset"]["transforms"]["train"].append(tmp);
system_dict["local"]["transforms_train"]["mean"] = np.array(mean)*255;
system_dict["local"]["transforms_train"]["std"] = np.array(std)*255;
system_dict["local"]["transforms_train"]["featurewise_center"] = True;
system_dict["local"]["transforms_train"]["featurewise_std_normalization"] = True;
if(val):
if(not retrieve):
system_dict["dataset"]["transforms"]["val"].append(tmp);
system_dict["local"]["transforms_val"]["mean"] = np.array(mean)*255;
system_dict["local"]["transforms_val"]["std"] = np.array(std)*255;
system_dict["local"]["transforms_val"]["featurewise_center"] = True;
system_dict["local"]["transforms_val"]["featurewise_std_normalization"] = True;
if(test):
if(not retrieve):
system_dict["dataset"]["transforms"]["test"].append(tmp);
system_dict["local"]["transforms_test"]["mean"] = np.array(mean)*255;
system_dict["local"]["transforms_test"]["std"] = np.array(std)*255;
system_dict["local"]["transforms_test"]["featurewise_center"] = True;
system_dict["local"]["transforms_test"]["featurewise_std_normalization"] = True;
return system_dict; | StarcoderdataPython |
3567838 | <reponame>destenson/ethereum-pyethereum
import os
import ethereum.testutils as testutils
from ethereum.slogging import get_logger
import ethereum.abi as abi
logger = get_logger()
def test_abi_encode_var_sized_array():
abi.encode_abi(['address[]'], [[b'\x00' * 20] * 3])
def test_abi_encode_fixed_size_array():
abi.encode_abi(['uint16[2]'], [[5, 6]])
def test_abi_encode_signed_int():
assert abi.decode_abi(['int8'], abi.encode_abi(['int8'], [1]))[0] == 1
assert abi.decode_abi(['int8'], abi.encode_abi(['int8'], [-1]))[0] == -1
# Will be parametrized fron json fixtures
def test_state(filename, testname, testdata):
testutils.check_abi_test(testutils.fixture_to_bytes(testdata))
def pytest_generate_tests(metafunc):
testutils.generate_test_params('ABITests', metafunc)
| StarcoderdataPython |
11211606 | #!/python3/bin/python3
def do_twice(f,m):
f(m)
f(m)
def print_spam(test):
print(test)
def print_twice(bruce):
print(bruce)
print(bruce)
do_twice(print_spam,'hello')
| StarcoderdataPython |
1815442 | import re
import logging
from osmosis import sh
def dfPercent(location):
output = sh.run(["df", location])
try:
line = " ".join(output.split("\n")[1:])
return int(re.split(r"\s+", line)[4].strip("%"))
except Exception:
logging.exception("Unable to parse DF output:\n%(output)s", dict(output=output))
raise
| StarcoderdataPython |
6615396 | <filename>isbi_model_predict.py
# Imports
import os
import matplotlib.pyplot as plt
import _pickle as cPickle
import numpy as np
import cv2
import time
# Keras Imports
from keras.applications import VGG16
from keras.applications.vgg16 import preprocess_input
from keras.models import Model, load_model
from keras.layers import Input,Conv2D,MaxPooling2D,Conv2DTranspose, multiply, concatenate, Dense, Flatten, Dropout, Lambda
from keras.callbacks import ModelCheckpoint
from keras import losses
from keras import backend as K
# ISBI Model Imports
from code.isbi_model.isbi_model_utilities import create_isbi_model, generate_isbi_predictions
# GLOBAL VARIABLES
# FOLDS
FOLDS = [i for i in range(5)]
# ISBI Model Results Directory
isbi_model_results_dir = 'results/isbi-model'
# ISBI Model Weights Directory
isbi_model_weights_dir = os.path.join(isbi_model_results_dir, 'weights')
# ISBI Model Predictions Directory
isbi_model_predictions_dir = os.path.join(isbi_model_results_dir, 'predictions')
if os.path.isdir(isbi_model_predictions_dir) == False:
os.mkdir(isbi_model_predictions_dir)
# Iterate through folds
for fold in FOLDS:
print('Current fold: {}'.format(fold))
# ISBI Model Weights Path
weights_path = os.path.join(isbi_model_weights_dir, 'isbi_model_trained_Fold_{}.hdf5'.format(fold))
# Data Paths
data_path = 'data/resized'
# X_train path
X_train_path = os.path.join(data_path, 'X_train_221.pickle')
# X_test path
X_test_path = os.path.join(data_path, 'X_test_221.pickle')
# Test indices path
test_indices_path = 'data/train-test-indices/test_indices_list.pickle'
# Start time measurement for the algorithm performance check
startTime = time.time()
# Generate predictions
isbi_preds = generate_isbi_predictions(
X_train_path=X_train_path,
X_test_path=X_test_path,
test_indices_path=test_indices_path,
fold=fold,
isbi_model_weights_path=weights_path
)
# Time measurement
print ('The script took {} seconds for fold {}!'.format(time.time() - startTime, fold))
with open(os.path.join(isbi_model_predictions_dir, 'isbi_preds_w_only_CV_Fold_{}.pickle'.format(fold)), 'wb') as f:
cPickle.dump(isbi_preds, f, -1)
print('ISBI Model Predictions Finished.') | StarcoderdataPython |
223167 | import serial
import sys
import glob
#serialDevice = '/dev/tty.usbmodem12341'
serialDevice = '/dev/ttyUSB0'
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
#print "-----------------"
#print serial_ports()
#print "-----------------"
#ser = serial.Serial(device, baud, timeout=0)
#ser.nonblocking()
#print 'Opened %s, baud %d' % (device, baud)
#ser.write('\r\n!\r\necho off\r\n')
#time.sleep(1)
#serial.flushInput()
def sendCommandsFromUser():
#for baud in (9600, 19200, 38400, 57600):
for baud in (9600,):
print "baud:", baud
#ser = serial.Serial('/dev/tty.usbmodem12341', 19200, timeout=1) # open serial
ser = serial.Serial(serialDevice, baud, timeout=1) # open serial
print(ser.name) # check which port was really used
#print "settings:", ser.getSettingsDict()
ser.nonblocking()
#print "settings:", ser.getSettingsDict()
# loop to collect input
while(True):
s = raw_input()
print "string:", s
ser.write(s + "\r\n") # write a string
#ser.write(s)
ser.flush()
#while ser.in_waiting > 0:
while ser.inWaiting > 0:
print "read:", ser.read()
#print "settings:", ser.getSettingsDict()
ser.close()
def sendCommand():
baud1 = 9600
print "baud:", baud1
#ser = serial.Serial('/dev/tty.usbmodem12341', 19200, timeout=1) # open serial
ser = serial.Serial(serialDevice, baud1, timeout=1) # open serial
print(ser.name) # check which port was really used
#print "settings:", ser.getSettingsDict()
ser.nonblocking()
#print "settings:", ser.getSettingsDict()
# loop to collect input
s = "f"
print "string:", s
ser.write(s + "\r\n") # write a string
#ser.write(s)
ser.flush()
#while ser.in_waiting > 0:
while ser.inWaiting > 0:
#print "settings:", ser.getSettingsDict()
print "read:", ser.read()
ser.close()
sendCommand()
| StarcoderdataPython |
8016390 | import numpy as np
from chairs import sample, sample2, waiting_area
def map_area(data):
return np.array([[np.nan if c == "." else 0 for c in row] for row in data.split("\n")])
def analyze_chairs(m):
"""Iterate through the room & build two lists of indices.
Use a rolling window to search for empty chairs w/ no-one seated nearby
-- add to 'going_to_sit'
Simultainesouly look for filled chairs that ALSO have 4+ neighbors
-- add to 'going_to_leave'
return (arrive_rows, arrive_cols), (leave_rows, leave_cols)
which can be used later to slice into 'm'
"""
arrive_rows, arrive_cols = [], []
leave_rows, leave_cols = [], []
row_dim, col_dim = m.shape
for row, one_row in enumerate(m):
for col, val in enumerate(one_row):
r_min = max(0, row-1)
r_max = min(row_dim, row+2)
c_min = max(0, col-1)
c_max = min(col_dim, col+2)
rolling_window = m[r_min: r_max, c_min: c_max]
# Will someone sit down?
if (val == 0) and (np.nansum(rolling_window) == 0):
arrive_rows.append(row)
arrive_cols.append(col)
# Will this chair vacate? (cutoff @ 5 because of counting self)
if (val == 1) and (np.nansum(rolling_window) >= 5):
leave_rows.append(row)
leave_cols.append(col)
return (arrive_rows, arrive_cols), (leave_rows, leave_cols)
def analyze_sightline(m):
"""Iterate through the room & build two lists of indices.
-- add to 'going_to_sit'
Simultainesouly look for filled chairs that ALSO have 5+ neighbors
-- add to 'going_to_leave'
return (arrive_rows, arrive_cols), (leave_rows, leave_cols)
which can be used later to slice into 'm'
"""
m = np.pad(m, pad_width=2, mode='constant', constant_values=0)
arrive_rows, arrive_cols = [], []
leave_rows, leave_cols = [], []
row_dim, col_dim = m.shape
flipped_m = np.fliplr(m)
for i, one_row in enumerate(m[2:-2]):
for j, val in enumerate(one_row[2:-2]):
if val in [0, 1]:
# Account for the border offset
row, col = i+2, j+2
viewable = count_viewable(row, col, m, flipped_m)
# Will someone sit down?
if (val == 0) and (viewable == 0):
arrive_rows.append(i)
arrive_cols.append(j)
# Will this chair vacate?
if (val == 1) and (viewable >= 5):
leave_rows.append(i)
leave_cols.append(j)
return (arrive_rows, arrive_cols), (leave_rows, leave_cols)
def count_viewable(row, col, m, flipped_m):
"""Before coming in, should pad with a border of 2
This allows np.diagonal() to work.
m = np.pad(m, pad_width=2, mode='constant', constant_values=0)
row, col = row+2, col+2
"""
val = m[row, col]
n_rows, n_cols = m.shape
up = m[:row, col][::-1]
down = m[row+1:, col]
left = m[row, :col][::-1]
right = m[row, col+1:]
d1u = m[:row, :col].diagonal(offset=col-row)[::-1]
d2u = flipped_m[:row, :(n_cols-col)].diagonal(offset=n_cols-col-row-1)[::-1]
d1d = m[row+1:, col+1:].diagonal()
d2d = flipped_m[row+1:, (n_cols-col):].diagonal()
total_seen = 0
for view in [up, down, left, right, d1u, d2u, d1d, d2d]:
view = view[~np.isnan(view)]
total_seen += view[0]
return total_seen
def cycle_once(m, func=analyze_chairs):
"""Analyze a seating map (m) and change it in place.
Return the updated map, and a flag for whether the room is still unstable
"""
going_to_sit, going_to_leave = func(m)
print(f"Arrived {len(going_to_sit[0])} | {len(going_to_leave[0])} Left | Current {int(np.nansum(m))}")
if going_to_sit == going_to_leave:
print("No changes! Exiting . . . ")
return m, False
m[going_to_sit] = 1
m[going_to_leave] = 0
return m, True
def stabalize_room(data, func=analyze_chairs):
"""Parse the raw data, then alternate between filling & vacating
chairs in the waiting room.
When no more changes can occur, exit the cycle & return the total
number of seated visitors.
"""
m, still_in_flux = map_area(data), True
while still_in_flux:
m, still_in_flux = cycle_once(m, func)
return int(np.nansum(m))
def show_room(m):
"""NOT USED: Helper function to visualize using original characters"""
view_map = {np.nan: ".", 0: "L", 1:'#'}
z = np.vectorize(view_map.get)(m)
z = np.vectorize({"None": ".", "L": "L", "#": '#'}.get)(z)
z_printout = "\n".join("".join(row) for row in z)
return z_printout
print(sample)
assert stabalize_room(sample) == 37
assert stabalize_room(sample, analyze_sightline) == 26
if __name__ == "__main__":
print(stabalize_room(waiting_area))
print(stabalize_room(waiting_area, analyze_sightline))
| StarcoderdataPython |
11337508 | <gh_stars>0
from main import Pygame, Element, Image
import time
ballGif = "ball.gif"
def main():
global count
count += 1
if ball.detectCollision(collide) and count >= 300:
pg.remove(collide)
time.sleep(0.5)
print(ball.detectCollision(collide), count)
with Pygame() as pg:
count = 0
ball = Element(image = Image(ballGif), parent = pg, centerPosition = pg.getScreenCenter(), speed = [2, 2])
pg.add(ball)
pygameImage = Image("pygame_tiny.png")
pygameImage.scale(100, 100)
collide = Element(pygameImage, parent = pg, centerPosition = (pg.getScreenWidth()//2, 10), speed = [0, 0])
pg.add(collide)
pg.addKeyboardMovement(element = ball, amount = 2, up = True, down = True, left = True, right = True)
pg.loop(main) | StarcoderdataPython |
6517449 | <reponame>gitter-badger/turbulette
import logging
from ariadne import convert_kwargs_to_snake_case
from tests.app_1.models import Book, Comics
from tests.app_1.pyd_models import CreateBook, CreateComics
from turbulette import mutation, query
from turbulette.apps.auth import get_token_from_user, user_model
from turbulette.apps.auth.pyd_models import BaseUserCreate
from turbulette.errors import ErrorField
from turbulette.validation.decorators import validate
@mutation.field("createUser")
@convert_kwargs_to_snake_case
@validate(BaseUserCreate)
async def resolve_user_create(obj, info, valid_input, **kwargs) -> dict:
user = await user_model.query.where(
user_model.username == valid_input["username"]
).gino.first()
if user:
message = f"User {valid_input['username']} already exists"
# Make sure to call __str__ on BaseError
out = str(ErrorField(message))
logging.info(out)
return ErrorField(message).dict()
new_user = await user_model.create(**valid_input)
auth_token = await get_token_from_user(new_user)
return {
"user": {**new_user.to_dict()},
"token": auth_token,
}
@query.field("books")
async def resolve_books(_, info, **kwargs):
return {
"books": [
{
"title": "<NAME>",
"author": "<NAME>",
"borrowings": 1345,
"price_bought": 15.5,
},
{
"title": "The Lord of the Rings",
"author": "<NAME>",
"borrowings": 2145,
"price_bought": 23.89,
},
]
}
@mutation.field("addBook")
async def add_books(_, __, **kwargs):
return {"success": True}
@mutation.field("borrowBook")
async def borrow_book(_, __, **kwargs):
book = await Book.get(int(kwargs["id"]))
await book.update(borrowings=book.borrowings + 1).apply()
return {"success": True}
@query.field("exclusiveBooks")
async def is_logged(_, __, **kwargs):
return {
"books": [
{"title": "Game Of Thrones", "author": "<NAME>"},
]
}
@query.field("book")
async def resolve_book(_, __, id):
book = await Book.query.where(Book.id == int(id)).gino.first()
return {"book": book.to_dict()}
@mutation.field("createBook")
@convert_kwargs_to_snake_case
@validate(CreateBook)
async def create_book(_, __, valid_input, **kwargs):
book = await Book.create(**valid_input)
return {"book": book.to_dict()}
@mutation.field("updatePassword")
async def update_password(_, __, claims, **kwargs):
await user_model.set_password(claims["sub"], kwargs["password"])
return {"success": True}
@mutation.field("createComic")
@convert_kwargs_to_snake_case
@validate(CreateComics)
async def create_cartoon(_, __, valid_input, **kwargs):
"""Validate input data against multiple models.
This can be useful to add entries in multiple tables linked
with a foreign key
"""
book_input, comics_input = valid_input.pop("book"), valid_input
book = await Book.create(**book_input)
comic = await Comics.create(**comics_input, book=book.id)
return {"comic": {**book.to_dict(), **comic.to_dict()}}
@mutation.field("borrowUnlimitedBooks")
async def borrow_unlimited(_, __, user, **kwargs):
return {"success": True}
@mutation.field("destroyLibrary")
async def destroy_library(_, __, **kwargs):
return {"sucess": True}
@query.field("comics")
async def resolve_comics(_, __, **kwargs):
return {
"comics": [
{"title": "The Blue Lotus", "author": "Hergé", "artist": "Hergé"},
{
"title": "Asterix and Cleopatra",
"author": "<NAME>",
"artist": "<NAME>",
},
]
}
| StarcoderdataPython |
4895555 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import tensorflow as tf
import lib.graphprot_dataloader, lib.rna_utils
from Model.Joint_ada_sampling_model import JointAdaModel
from lib.general_utils import Pool
import multiprocessing as mp
import pandas as pd
tf.logging.set_verbosity(tf.logging.FATAL)
lib.graphprot_dataloader._initialize()
BATCH_SIZE = 128
RBP_LIST = lib.graphprot_dataloader.all_rbps
expr_path_list = os.listdir('output/Joint-ada-sampling-debiased')
expr_name = [dirname.split('-')[-1] for dirname in expr_path_list]
DEVICES = ['/gpu:0', '/gpu:1', '/gpu:0', '/gpu:1', '/gpu:2', '/gpu:3', '/gpu:2', '/gpu:3']
hp = {
'learning_rate': 2e-4,
'dropout_rate': 0.2,
'use_clr': True,
'use_momentum': False,
'use_bn': False,
'units': 32,
'reuse_weights': True, # highly suggested
'layers': 10,
'lstm_ggnn': True,
'probabilistic': True,
'mixing_ratio': 0.05,
'use_ghm': True,
'use_attention': False,
}
def Logger(q):
import time
registered_gpus = {}
while True:
msg = q.get()
print(msg)
if type(msg) is str and msg == 'kill':
break
elif type(msg) is str and msg.startswith('worker'):
process_id = int(msg.split('_')[-1])
if process_id in registered_gpus:
print(process_id, 'found, returning', registered_gpus[process_id])
q.put('master_%d_' % (process_id) + registered_gpus[process_id])
else:
print(process_id, 'not found')
all_registered_devices = list(registered_gpus.values())
from collections import Counter
c1 = Counter(DEVICES)
c2 = Counter(all_registered_devices)
free_devices = list((c1 - c2).elements())
# free_devices = list(set(DEVICES).difference(set(all_registered_devices)))
if len(free_devices) > 0:
print('free device', free_devices[0])
q.put('master_%d_' % (process_id) + free_devices[0])
registered_gpus[process_id] = free_devices[0]
else:
print('no free device!')
print(registered_gpus)
q.put('master_%d_/cpu:0' % (process_id))
else:
q.put(msg)
time.sleep(np.random.rand() * 5)
def plot_one_rbp(rbp):
print('analyzing', rbp)
if rbp not in expr_name:
return
pool = Pool(8)
# original dataset
dataset = lib.graphprot_dataloader.load_clip_seq([rbp], p=pool, load_mat=False, modify_leaks=False, nucleotide_label=True)[0]
expr_path = expr_path_list[expr_name.index(rbp)]
if not os.path.exists(os.path.join('output/Joint-ada-sampling-debiased', expr_path, 'splits.npy')):
print('Warning, fold split file is missing; skipping...')
return
dataset['splits'] = np.load(os.path.join('output/Joint-ada-sampling-debiased', expr_path, 'splits.npy'),
allow_pickle=True)
full_expr_path = os.path.join('output/Joint-ada-sampling-debiased', expr_path)
motif_dir = os.path.join(full_expr_path, 'wholeseq_high_gradient_ranked_motifs_100_4000')
if not os.path.exists(motif_dir):
os.makedirs(motif_dir)
import time
process_id = mp.current_process()._identity[0]
print('sending process id', mp.current_process()._identity[0])
q.put('worker_%d' % (process_id))
while True:
msg = q.get()
if type(msg) is str and msg.startswith('master'):
print('worker %d received' % (process_id), msg, str(int(msg.split('_')[1])))
if int(msg.split('_')[1]) == process_id:
device = msg.split('_')[-1]
print('Process', mp.current_process(), 'received', device)
break
q.put(msg)
time.sleep(np.random.rand() * 2)
fold_idx = 0
fold_output = os.path.join(full_expr_path, 'fold%d' % (fold_idx))
if os.path.exists(fold_output):
model = JointAdaModel(dataset['VOCAB_VEC'].shape[1],
# excluding no bond
dataset['VOCAB_VEC'], device, **hp)
checkpoint_path = tf.train.latest_checkpoint(os.path.join(fold_output, 'checkpoints'))
if checkpoint_path is None:
print('Warning, latest checkpoint of %s is None...' % (fold_output))
return
try:
model.load(checkpoint_path)
except:
print('cannot load back weights; skipping...')
return
_, test_idx = dataset['splits'][0]
test_pred_res = pd.read_csv(os.path.join(full_expr_path, 'fold%d'%(fold_idx), 'predictions.csv'))
test_pred_ranked_idx = np.argsort(np.array(test_pred_res['pred_pos']))[::-1]
# pos_idx = np.where(np.array([np.max(label) for label in dataset['label']]) == 1)[0]
all_data = [dataset['seq'][test_idx][test_pred_ranked_idx],
dataset['segment_size'][test_idx][test_pred_ranked_idx],
dataset['raw_seq'][test_idx][test_pred_ranked_idx]]
print(rbp, 'number of positive examples', len(all_data[0]))
model.rank_extract_motifs(
all_data, save_path=motif_dir, mer_size=10, max_examples=100, p=pool)
model.delete()
pool.close()
pool.join()
else:
print('Warning, %s doesd not exist...' % (fold_output))
if __name__ == "__main__":
manager = mp.Manager()
q = manager.Queue()
pool = Pool(8 + 1)
logger_thread = pool.apply_async(Logger, (q,))
# the first batch
pool.map(plot_one_rbp, ['PTBv1', 'CLIPSEQ_SFRS1', 'PARCLIP_QKI', 'PARCLIP_PUM2',
'ICLIP_TDP43', 'PARCLIP_FUS', 'PARCLIP_TAF15', 'PARCLIP_IGF2BP123'])
# second batch
pool.map(plot_one_rbp, ['CLIPSEQ_AGO2', 'PARCLIP_MOV10_Sievers', 'PARCLIP_AGO1234', 'ZC3H7B_Baltz2012',
'CAPRIN1_Baltz2012', 'C22ORF28_Baltz2012', 'C17ORF85_Baltz2012', 'ALKBH5_Baltz2012'])
# last batch
# pool.map(plot_one_rbp, ['CLIPSEQ_ELAVL1', 'ICLIP_HNRNPC', 'ICLIP_TIA1', 'ICLIP_TIAL1',
# 'PARCLIP_ELAVL1', 'PARCLIP_ELAVL1A', 'PARCLIP_EWSR1', 'PARCLIP_HUR'])
| StarcoderdataPython |
8139404 | # -*- coding: utf-8 -*-
import scrapy
import pdb, datetime
class projectorItem(scrapy.Item):
Brand = scrapy.Field()
Name = scrapy.Field()
Price = scrapy.Field()
Uri = scrapy.Field()
ImageUri = scrapy.Field()
Ratings = scrapy.Field()
CountOfRatings = scrapy.Field()
TimeStamp = scrapy.Field()
class amazonProjectorSpdier(scrapy.Spider):
name = "amazonProjectorSpdier"
allowed_domains = ["amazon.com"]
# start_urls = ( 'http://www.amazon.com/',)
# start_urls = ( 'https://www.amazon.com/gp/search/ref=sr_nr_p_n_feature_seven_br_4?fst=as%3Aoff&rh=n%3A172282%2Cn%3A%21493964%2Cn%3A300334%2Cp_n_feature_browse-bin%3A2358237011%2Cp_n_feature_ten_browse-bin%3A11601827011%2Cp_n_feature_eleven_browse-bin%3A2057590011%2Cp_n_feature_seven_browse-bin%3A11028023011&bbn=300334&ie=UTF8&qid=1478519032&rnid=11028015011',)
start_urls = ( 'https://www.amazon.com/s/ref=sr_nr_p_89_1?fst=as%3Aoff&rh=n%3A172282%2Cn%3A%21493964%2Cn%3A300334%2Cp_n_feature_eleven_browse-bin%3A2057590011%2Cp_n_condition-type%3A2224371011%2Cp_n_feature_ten_browse-bin%3A11601827011%2Cp_89%3AEpson&bbn=300334&sort=review-rank&ie=UTF8&qid=1478541006&rnid=2528832011',)
def parse(self, response):
xpathDict = {}
xpathDict['resultSet'] = "//li[@class='s-result-item celwidget']"
xpathDict['itemBrand'] = ".//div[@class='a-row a-spacing-small']/div/span[@class='a-size-small a-color-secondary'][2]/text()"
xpathDict['itemName'] = ".//h2/text()"
xpathDict['itemUri'] = ".//div[@class='a-row a-spacing-small']/a/@href"
xpathDict['itemImgUri'] = ".//a[@class='a-link-normal a-text-normal']/img/@src"
xpathDict['itemPrice'] = ".//span[contains(@class, 'a-size-base a-color-price')]/text()"
xpathDict['itemRating'] = ".//a/i/span[@class='a-icon-alt']/text()"
xpathDict['itemcntOfRatings'] = ".//div[@class='a-column a-span5 a-span-last']/div[@class='a-row a-spacing-mini']/a[@class='a-size-small a-link-normal a-text-normal']/text()"
itemLst = response.xpath( xpathDict['resultSet'] )
if itemLst:
projectors = projectorItem()
for itemIndex,item in enumerate(itemLst):
print "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print " BEGIN PROCESSING OF ITEM : {0}".format( itemIndex )
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
try:
# Joining all the lists and avoiding the usage of index to avoid "index out of range" error when finding nothing
projectors['Brand'] = ''.join( item.xpath( xpathDict['itemBrand'] ).extract() )
projectors['Name'] = ''.join( item.xpath( xpathDict['itemName'] ).extract() )
projectors['Uri'] = ''.join( item.xpath( xpathDict['itemUri'] ).extract() )
projectors['ImageUri'] = ''.join( item.xpath( xpathDict['itemImgUri'] ).extract() )
findPrice = item.xpath( xpathDict['itemPrice'] ).extract()
# Find price (sometimes does not exists) and picks up new and old offers, so lets pick only the best offer
if len(findPrice) > 0:
findPrice = ''.join ( findPrice[0] )
findPrice = findPrice.replace( '$' , '' )
findPrice = findPrice.replace( ',' , '' )
projectors['Price'] = findPrice
# Split the rating to get the first string, which shows how much the product is rated out of 5 (say 4.5)
findRating = ''.join ( item.xpath( xpathDict['itemRating'] ).extract() )
findRating = findRating.split(' ')[0]
projectors['Ratings'] = findRating
projectors['CountOfRatings'] = ''.join ( item.xpath( xpathDict['itemcntOfRatings'] ).extract() )
projectors['TimeStamp'] = str(datetime.datetime.now())
yield projectors
print "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print " SUCCESSFULLY PROCESSED, STARTING NEXT. "
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
except:
print "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print " ERROR PROCESSING URI : {0}".format( projectors['Uri'] )
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
# pdb.set_trace()
pass | StarcoderdataPython |
232638 | import komand
from .schema import ViewSavedSearchPropertiesInput, ViewSavedSearchPropertiesOutput
# Custom imports below
class ViewSavedSearchProperties(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='view_saved_search_properties',
description='Returns the properties for a saved search',
input=ViewSavedSearchPropertiesInput(),
output=ViewSavedSearchPropertiesOutput())
def run(self, params={}):
saved_search_name = params.get("saved_search_name")
saved_search = self.connection.client.saved_searches[saved_search_name]
properties = saved_search.content
return {"properties": properties}
def test(self):
return {}
| StarcoderdataPython |
170091 | import numpy as np
import warnings
from time import time
import pandas as pd
# SeldonianML imports
from utils import argsweep, experiment, keyboard
from datasets import tutoring_bandit as TutoringSystem
import core.srl_fairness as SRL
import baselines.naive_full as NSRL
# Supress sklearn FutureWarnings for SGD
warnings.simplefilter(action='ignore', category=FutureWarning)
# Imports for baseline algorithms
from baselines.POEM.Skylines import PRMWrapper
from baselines.POEM.DatasetReader import BanditDataset
from contextualbandits.offpolicy import OffsetTree
from sklearn.linear_model import LogisticRegression
########################################
# Helpers for selection SRL models #
########################################
def get_srl_class(bound_ref_return=True, females_only=False, ci_type='ttest'):
if not(ci_type in ['ttest', 'bootstrap']):
raise ValueError('get_srl_class(): Unknown ci_type, "%s".' % ci_type)
if bound_ref_return:
if females_only:
if ci_type == 'ttest':
return SRL.TutoringSystemFemaleSRL
elif ci_type == 'bootstrap':
return SRL.TutoringSystemFemaleBootstrapSRL
else:
if ci_type == 'ttest':
return SRL.TutoringSystemSRL
elif ci_type == 'bootstrap':
return SRL.TutoringSystemBootstrapSRL
else:
if females_only:
if ci_type == 'ttest':
return SRL.TutoringSystemFemaleEmpSRL
elif ci_type == 'bootstrap':
return SRL.TutoringSystemFemaleBootstrapEmpSRL
else:
if ci_type == 'ttest':
return SRL.TutoringSystemEmpSRL
elif ci_type == 'bootstrap':
return SRL.TutoringSystemBootstrapEmpSRL
def get_nsrl_class(bound_ref_return=True, females_only=False, ci_type='ttest'):
if not(ci_type in ['ttest', 'bootstrap']):
raise ValueError('get_srl_class(): Unknown ci_type, "%s".' % ci_type)
if bound_ref_return:
if females_only:
if ci_type == 'ttest':
return NSRL.TutoringSystemFemaleNaiveSRL
elif ci_type == 'bootstrap':
return NSRL.TutoringSystemFemaleBootstrapNaiveSRL
else:
if ci_type == 'ttest':
return NSRL.TutoringSystemNaiveSRL
elif ci_type == 'bootstrap':
return NSRL.TutoringSystemBootstrapNaiveSRL
else:
if females_only:
if ci_type == 'ttest':
return NSRL.TutoringSystemFemaleEmpNaiveSRL
elif ci_type == 'bootstrap':
return NSRL.TutoringSystemFemaleBootstrapEmpNaiveSRL
else:
if ci_type == 'ttest':
return NSRL.TutoringSystemEmpNaiveSRL
elif ci_type == 'bootstrap':
return NSRL.TutoringSystemBootstrapEmpNaiveSRL
########################
# Model Evaluators #
########################
def eval_offset_trees(dataset, mp):
n_actions = dataset.n_actions
t = time()
dataset.enable_R_corrections()
S, A, R, _, P = dataset.training_splits(flatten=True)
new_policy = OffsetTree(base_algorithm=LogisticRegression(solver='lbfgs'), nchoices=dataset.n_actions)
new_policy.fit(X=S, a=A, r=R, p=P)
t_train = time() - t
def predict_proba(S):
S = S[:,0,:]
AP = new_policy.predict(S)
P = np.zeros((len(AP), dataset.n_actions))
for i,a in enumerate(AP):
P[i,a] = 1.0
return P[:,None,:]
# Evaluate using SRL's evaluate method
dataset.disable_R_corrections()
sfp = mp['simulated_female_proportion']
model_params = {
'epsilon_f' : mp['e_f'],
'epsilon_m' : mp['e_m'],
'delta' : mp['d'] }
if not(mp['simulated_female_proportion'] is None):
model_params['male_iw_correction'] = (1-mp['simulated_female_proportion'])/np.mean(dataset._T==0)
model_params['female_iw_correction'] = mp['simulated_female_proportion']/np.mean(dataset._T==1)
min_reward, max_reward = dataset.min_reward, dataset.max_reward
_, _, R, T, _ = dataset.testing_splits(flatten=True)
r_ref_T0 = np.mean(R[T==0])
r_ref_T1 = np.mean(R[T==1])
TutoringSystemSRL = get_srl_class(mp['bound_ref_return'], mp['females_only'], mp['ci_type'])
model = TutoringSystemSRL(min_reward, max_reward, r_ref_T0, r_ref_T1, **model_params)
results = model.evaluate(dataset, probf=predict_proba)
results['train_time'] = t_train
return results
def eval_poem(dataset, mp):
n_actions = dataset.n_actions
# Represent our data in a form compatible with POEM
dataset.enable_R_corrections()
bandit_dataset = BanditDataset(None, verbose=False)
S, A, R, _, P = dataset.testing_splits(flatten=True)
labels = np.zeros((len(A),dataset.n_actions))
for i, a in enumerate(A):
labels[i,a] = 1.0
bandit_dataset.testFeatures = S
bandit_dataset.testLabels = labels
S, A, R, _, P = dataset.training_splits(flatten=True)
labels = np.zeros((len(A),dataset.n_actions))
for i, a in enumerate(A):
labels[i,a] = 1.0
bandit_dataset.trainFeatures = S
bandit_dataset.trainLabels = labels
bandit_dataset.registerSampledData(labels, np.log(P), -R) # POEM expects penalties not rewards
bandit_dataset.createTrainValidateSplit(0.1)
# Train POEM
ss = np.random.random((dataset.n_features, dataset.n_actions))
maj = PRMWrapper(bandit_dataset, n_iter = 1000, tol = 1e-6, minC = 0, maxC = -1, minV = -6, maxV = 0, minClip = 0, maxClip = 0, estimator_type = 'Stochastic', verbose = False, parallel = None, smartStart = ss)
maj.calibrateHyperParams()
t_train = maj.validate()
# Extract the predictor and construct a proba function
def predict_proba(S):
S = S[:,0,:]
V = S.dot(maj.labeler.coef_).astype('float64')
EV = np.exp(V)
return (EV / EV.sum(axis=1)[:,None])[:,None,:]
# Evaluate using SRL's evaluate method
dataset.disable_R_corrections()
model_params = {
'epsilon_f' : mp['e_f'],
'epsilon_m' : mp['e_m'],
'delta' : mp['d'] }
if not(mp['simulated_female_proportion'] is None):
model_params['male_iw_correction'] = (1-mp['simulated_female_proportion'])/np.mean(dataset._T==0)
model_params['female_iw_correction'] = mp['simulated_female_proportion']/np.mean(dataset._T==1)
min_reward, max_reward = dataset.min_reward, dataset.max_reward
_, _, R, T, _ = dataset.testing_splits(flatten=True)
r_ref_T0 = np.mean(R[T==0])
r_ref_T1 = np.mean(R[T==1])
TutoringSystemSRL = get_srl_class(mp['bound_ref_return'], mp['females_only'], mp['ci_type'])
model = TutoringSystemSRL(min_reward, max_reward, r_ref_T0, r_ref_T1, **model_params)
results = model.evaluate(dataset, probf=predict_proba)
results['train_time'] = t_train
return results
def eval_naive(dataset, mp):
n_actions = dataset.n_actions
# Train the model
t = time()
dataset.disable_R_corrections()
model_params = {
'epsilon_f' : mp['e_f'],
'epsilon_m' : mp['e_m'],
'delta' : mp['d'] }
if not(mp['simulated_female_proportion'] is None):
model_params['male_iw_correction'] = (1-mp['simulated_female_proportion'])/np.mean(dataset._T==0)
model_params['female_iw_correction'] = mp['simulated_female_proportion']/np.mean(dataset._T==1)
min_reward, max_reward = dataset.min_reward, dataset.max_reward
_, _, R, T, _ = dataset.testing_splits(flatten=True)
r_ref_T0 = np.mean(R[T==0])
r_ref_T1 = np.mean(R[T==1])
TutoringSystemNaiveSRL = get_nsrl_class(mp['bound_ref_return'], mp['females_only'], mp['ci_type'])
model = TutoringSystemNaiveSRL(min_reward, max_reward, r_ref_T0, r_ref_T1, **model_params)
model.fit(dataset, n_iters=mp['n_iters'], optimizer_name='cmaes')
t_train = time() - t
# Assess the model
results = model.evaluate(dataset, probf=model.get_probf())
results['train_time'] = t_train
return results
def eval_sb(dataset, mp):
n_actions = dataset.n_actions
# Train the model
t = time()
dataset.disable_R_corrections()
model_params = {
'epsilon_f' : mp['e_f'],
'epsilon_m' : mp['e_m'],
'delta' : mp['d'] }
if not(mp['simulated_female_proportion'] is None):
model_params['male_iw_correction'] = (1-mp['simulated_female_proportion'])/np.mean(dataset._T==0)
model_params['female_iw_correction'] = mp['simulated_female_proportion'] /np.mean(dataset._T==1)
min_reward, max_reward = dataset.min_reward, dataset.max_reward
_, _, R, T, _ = dataset.testing_splits(flatten=True)
r_ref_T0 = np.mean(R[T==0])
r_ref_T1 = np.mean(R[T==1])
TutoringSystemSRL = get_srl_class(mp['bound_ref_return'], mp['females_only'], mp['ci_type'])
model = TutoringSystemSRL(min_reward, max_reward, r_ref_T0, r_ref_T1, **model_params)
model.fit(dataset, n_iters=mp['n_iters'], optimizer_name='cmaes')
t_train = time() - t
# Assess the model
results = model.evaluate(dataset)
results['train_time'] = t_train
return results
######################
# Dataset Loader #
######################
def load_dataset(tparams, seed):
dset_args = {
'r_train' : tparams['r_train_v_test'],
'r_candidate' : tparams['r_cand_v_safe'],
'include_T' : tparams['include_T'],
'include_intercept' : not(tparams['omit_intercept']),
'use_pct' : tparams['data_pct'],
'remove_biased_tutorial' : tparams['remove_biased_tutorial'],
'simulated_female_proportion' : tparams['simulated_female_proportion']
}
return TutoringSystem.load(**dset_args)
############
# Main #
############
if __name__ == '__main__':
# Note: This script computes experiments for the cross product of all values given for the
# sweepable arguments.
# Note: Sweepable arguments allow inputs of the form, <start>:<end>:<increment>, which are then
# expanded into ranges via np.arange(<start>, <end>, <increment>).
# Eventually I'll add a nice usage string explaining this.
with argsweep.ArgumentSweeper() as parser:
# Execution parameters
parser.add_argument('--status_delay', type=int, default=30, help='Number of seconds between status updates when running multiple jobs.')
parser.add_argument('base_path', type=str)
parser.add_argument('--n_jobs', type=int, default=4, help='Number of processes to use.')
parser.add_argument('--n_trials', type=int, default=10, help='Number of trials to run.')
# Dataset arguments
parser.add_sweepable_argument('--r_train_v_test', type=float, default=0.4, nargs='*', help='Ratio of data used for training vs testing.')
parser.add_sweepable_argument('--r_cand_v_safe', type=float, default=0.4, nargs='*', help='Ratio of training data used for candidate selection vs safety checking. (SMLA only)')
parser.add_argument('--include_T', action='store_true', help='Whether or not to include type as a predictive feature.')
parser.add_argument('--omit_intercept', action='store_false', help='Whether or not to include an intercept as a predictive feature (included by default).')
parser.add_sweepable_argument('--data_pct', type=float, default=1.0, nargs='*', help='Percentage of the overall size of the dataset to use.')
parser.add_argument('--use_score_text', action='store_true', help='Whether or not to base actions off of the COMPAS score text (default uses the "decile_score" feature).')
parser.add_argument('--rwd_recid', type=float, default=-1.0, help='Reward for instances of recidivism.')
parser.add_argument('--rwd_nonrecid', type=float, default=1.0, help='Reward for instances of non-recidivism.')
parser.add_argument('--simulated_female_proportion', type=float, default=None, help='If specified, rescales the importance weight terms to simulate having the specified proportion of females.')
# Seldonian algorithm parameters
parser.add_argument('--females_only', action='store_true', help='If enabled, only enforce the constraint for females.')
parser.add_argument('--bound_ref_return', action='store_true', help='If enabled, also bound the expected return of the behavior policy.')
parser.add_argument('--ci_type', type=str, default='ttest', help='Choice of confidence interval to use in the Seldonian methods.')
parser.add_argument('--n_iters', type=int, default=10, help='Number of SMLA training iterations.')
parser.add_argument('--remove_biased_tutorial', action='store_true', help='If true, remove the tutorial that is slanted against females (default is to include all data).')
parser.add_sweepable_argument('--e_f', type=float, default=0.00, nargs='*', help='Values for epsilon for the female constraint.')
parser.add_sweepable_argument('--e_m', type=float, default=0.00, nargs='*', help='Values for epsilon for the male constraint (no effect if --females_only).')
parser.add_sweepable_argument('--d', type=float, default=0.05, nargs='*', help='Values for delta.')
args = parser.parse_args()
args_dict = dict(args.__dict__)
# Define the evaluators to be included in the experiment and specify which ones are Seldonian
model_name = get_srl_class(args.bound_ref_return, args.females_only, args.ci_type).__name__
model_evaluators = {
model_name : eval_sb,
'POEM' : eval_poem,
'OffsetTree' : eval_offset_trees,
'Naive' : eval_naive
}
smla_names = [model_name]
# Store task parameters:
tparam_names = ['n_jobs', 'base_path', 'data_pct', 'r_train_v_test', 'r_cand_v_safe', 'include_T', 'omit_intercept', 'use_score_text', 'rwd_recid', 'rwd_nonrecid', 'remove_biased_tutorial', 'simulated_female_proportion']
tparams = {k:args_dict[k] for k in tparam_names}
# Store method parameters:
srl_mparam_names = ['e_f', 'e_m', 'd', 'n_iters', 'ci_type', 'females_only', 'bound_ref_return', 'simulated_female_proportion']
bsln_mparam_names = ['e_f', 'e_m', 'd', 'n_iters', 'ci_type', 'females_only', 'bound_ref_return', 'simulated_female_proportion']
mparams = {}
for name in model_evaluators.keys():
if name in smla_names:
mparams[name] = {k:args_dict[k] for k in srl_mparam_names}
else:
mparams[name] = {k:args_dict[k] for k in bsln_mparam_names}
# Expand the parameter sets into a set of configurations
tparams, mparams = experiment.make_parameters(tparams, mparams, expand=parser._sweep_argnames)
# Create a results file and directory
print()
save_path = experiment.prepare_paths(args.base_path, tparams, mparams, smla_names, root='results', filename=None)
# Run the experiment
print()
experiment.run(args.n_trials, save_path, model_evaluators, load_dataset, tparams, mparams, n_workers=args.n_jobs, seed=None)
| StarcoderdataPython |
11283330 | <gh_stars>1-10
import Tkinter
from scato.scheduler import Scheduler
class DrawArea:
'''Interface:
area = DrawArea(tk_root_element)
# area.compensation_mode = True # for MS Windows
area.bg(color)
area.bd(color)
area.line((x1, y1, x2, y2), width, color)
# if area.compensation_applied:
# print ('Warning: compensation has been applied.\n'
# 'PostScript file would be compensate too.\n'
# 'Redraw image to save it without any distortions.')
area.export_postscript('file.ps')
area.clear()
'''
def __init__(self, root, size):
# compensation mode is a hack arm to compensate
# bug(?) in MS Windows implementation of Tk
self.compensation_mode = False
self.compensation_applied = False
self.root = root
self.size = size
self.lines = []
self.resize_start = 0
self.resize_stop = 0
self.resize_sched = None
self.frame = Tkinter.Frame(
root,
borderwidth=0,
highlightthickness=0,
width=self.size,
height=self.size)
self.frame.pack(fill=Tkinter.BOTH,
expand=Tkinter.TRUE,
anchor=Tkinter.N,
side=Tkinter.TOP)
self.canva = Tkinter.Canvas(
self.frame,
highlightthickness=0,
borderwidth=0,
width=self.size,
height=self.size)
self.canva.create_rectangle(
(0, 0, self.size, self.size),
tags='bg',
width=0,
activewidth=0,
disabledwidth=0)
self.canva.pack()
self.frame.bind('<Configure>', self.ev_resize)
def clean(self):
self.lines = []
self.resize_start = 0
self.resize_stop = 0
self.resize_sched = None
self.compensation_applied = False
self.ll_clean()
self.bg('#999999')
def line(self, p, w, c):
q = p[0], 1-p[1], p[2], 1-p[3]
self.lines.append((q, w, c, self.ll_line(q, w, c)))
def bg(self, c):
self.canva.configure(background=c)
self.canva.itemconfigure('bg', fill=c)
def bd(self, c):
self.frame.configure(background=c)
def export_postscript(self, file):
self.canva.update_idletasks()
return self.canva.postscript(
file=file,
pagewidth='7.5i', # A4 - 8.26x11.69; Letter - 8.50x11.00
pageheight='7.5i',
width=self.size,
height=self.size,
pagex=0,
pagey=0,
pageanchor=Tkinter.N+Tkinter.W,
colormode='color')
def get_box_size(self):
if self.lines:
x1 = 1000000
x2 = -1000000
y1 = 1000000
y2 = -1000000
for (xa, ya, xb, yb), w, t1, t2 in self.lines:
w /= 2
for x, y in (xa, ya), (xb, yb):
x1 = min(x1, x - w)
x2 = max(x2, x + w)
y1 = min(y1, y - w)
y2 = max(y2, y + w)
return (len(self.lines), x1, x2, 1-y2, 1-y1,
self.compensation_applied)
return 0, 0, 0, 0, 0, False
def ev_resize(self, e):
x = min(e.width, e.height)
if x != self.size:
self.compensation_applied = False
self.size = x
self.canva.configure(width=x, height=x)
self.canva.coords('bg', (0, 0, self.size, self.size))
self.resize_start = 0
self.resize_stop = len(self.lines)
if not self.resize_sched is None:
self.resize_sched.cancel()
self.ev_resize_chunk()
def ev_resize_chunk(self):
l = self.resize_start + 500
for i in range(self.resize_start, l):
if i >= self.resize_stop:
break
self.ll_update(self.lines[i])
else:
self.resize_start = l
self.resize_sched = Scheduler(self.root, self.ev_resize_chunk)
return
self.resize_sched = None
def ll_clean(self):
self.canva.delete('line')
def ll_line(self, p, w, c):
if self.compensation_mode:
wd = w * self.size
q = tuple(map(lambda x: self.size * x, p))
l = max(abs(q[0]-q[2]), abs(q[1]-q[3]))
if l < .5 and wd < 1.5:
wd = 1.55
self.compensation_applied = True
return self.canva.create_line(
q,
fill=c,
width=wd,
capstyle='round',
tag='line')
else:
return self.canva.create_line(
tuple(map(lambda x: self.size * x, p)),
fill=c,
width=w * self.size,
capstyle='round',
tag='line')
def ll_update(self, ld):
iid = ld[3]
iw = ld[1] * self.size
# canva.coords can eat only tuple but not list
# Tkinter.__version__ = '$Revision: 50704 $'
ipp = tuple(map(lambda x: self.size * x, ld[0]))
if self.compensation_mode:
l = max(abs(ipp[0]-ipp[2]), abs(ipp[1]-ipp[3]))
if l < .5 and iw < 1.5:
iw = 1.55
self.compensation_applied = True
self.canva.itemconfigure(iid, width=iw)
self.canva.coords(iid, ipp)
if __name__ == '__main__':
# demo
root = Tkinter.Tk()
a = DrawArea(root)
a.bg('#003300')
a.bd('#006600')
a.line((.1, .1, .9, .9), .05, '#33ff33')
root.after(5000, a.clean)
root.after(6000, lambda: a.line((.1, .9, .9, .1), .05, '#33ff33'))
root.mainloop()
| StarcoderdataPython |
8111370 | <gh_stars>1-10
from bs4 import BeautifulSoup
import requests
from requests.api import request
from .models import Marks
from main.anlysis import analysis
hrefa=[]
title=[]
data=[]
dicts={}
fintit=[]
finhref=[]
finscr=[]
def scrapnews(user):
url="https://www.goodnewsnetwork.org/category/news/"
html_doc=requests.get(url).content
soup = BeautifulSoup(html_doc, 'html.parser')
for a in soup.find_all('h3', {'class':'entry-title td-module-title'}):
title.append(a.text)
for b in soup.find_all('a', {'rel':'bookmark'}):
hrefa.append(b['href'])
href=hrefa[0:len(hrefa):2]
url="https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRGx1YlY4U0FtVnVHZ0pKVGlnQVAB?hl=en-IN&gl=IN&ceid=IN%3Aen"
html_doc=requests.get(url).content
soup = BeautifulSoup(html_doc, 'html.parser')
for a in soup.find_all('h3', {'class':'ipQwMb ekueJc RD0gLb'}):
title.append(a.text)
for b in soup.find_all('a', {'class':'DY5T1d'}):
href.append("https://news.google.com/"+b['href'])
scr=analysis(title)
for i in range(len(title)):
dic={scr[i]:[title[i],href[i]]}
dicts.update(dic)
dictss=dicts.items()
fin=sorted(dictss,reverse=True)
for i in range(len(fin)):
scrs,lists=fin[i]
fintit.append(lists[0])
finhref.append(lists[1])
finscr.append(scrs)
scrs=list(map(str,finscr))
for i in range(len(fintit)):
datas=Marks(content=finhref[i],author=user,title=fintit[i],score=finscr[i])
data.append([fintit[i],finscr[i],finhref[i],user,datas.date_modified])
datas.save()
print(fintit)
print(finhref)
print(finscr)
return data
| StarcoderdataPython |
6577430 | <filename>builders/frontend_builder.py<gh_stars>1-10
import tensorflow as tf
from tensorflow.contrib import slim
from frontends import xception
import os
def build_frontend(inputs, frontend, is_training=True, pretrained_dir="models"):
if frontend == 'ResNet50':
with slim.arg_scope(resnet_v2.resnet_arg_scope()):
logits, end_points = resnet_v2.resnet_v2_50(inputs, is_training=is_training, scope='resnet_v2_50')
frontend_scope='resnet_v2_50'
init_fn = slim.assign_from_checkpoint_fn(model_path=os.path.join(pretrained_dir, 'resnet_v2_50.ckpt'), var_list=slim.get_model_variables('resnet_v2_50'), ignore_missing_vars=True)
elif frontend == 'ResNet101':
with slim.arg_scope(resnet_v2.resnet_arg_scope()):
logits, end_points = resnet_v2.resnet_v2_101(inputs, is_training=is_training, scope='resnet_v2_101')
frontend_scope='resnet_v2_101'
init_fn = slim.assign_from_checkpoint_fn(model_path=os.path.join(pretrained_dir, 'resnet_v2_101.ckpt'), var_list=slim.get_model_variables('resnet_v2_101'), ignore_missing_vars=True)
elif frontend == 'xception':
with slim.arg_scope(xception.xception_arg_scope()):
logits, end_points = xception.xception39(inputs, is_training=is_training, scope='xception39')
frontend_scope='xception39'
init_fn = None
else:
raise ValueError("Unsupported fronetnd model '%s'. This function only supports ResNet50, ResNet101, ResNet152, and MobileNetV2, xception" % (frontend))
return logits, end_points, frontend_scope, init_fn | StarcoderdataPython |
1712728 | <gh_stars>10-100
# Copyright (c) 2020 <NAME>
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from google.cloud.bigquery.table import Table as BQTable
from google.cloud.bigquery.table import TimePartitioning
from bq_test_kit.bq_dsl.bq_resources.partitions import TimeField
from bq_test_kit.bq_dsl.bq_resources.partitions.time_partitionning_type import \
TimePartitioningType
def test_default_apply_time_field():
"""TimePartitiongType in TimeField was using BigQuery's API. Closes #3.
"""
table = BQTable("project.dataset.table")
assert table.time_partitioning is None
table = TimeField("f1").apply(table)
assert isinstance(table.time_partitioning, TimePartitioning)
assert table.time_partitioning.field == "f1"
assert table.time_partitioning.type_ == TimePartitioningType.DAY.value
def test_apply_time_field():
table = BQTable("project.dataset.table")
assert table.time_partitioning is None
table = TimeField("f1", type_=TimePartitioningType.DAY).apply(table)
assert isinstance(table.time_partitioning, TimePartitioning)
assert table.time_partitioning.field == "f1"
assert table.time_partitioning.type_ == TimePartitioningType.DAY.value
| StarcoderdataPython |
11216097 | # Created by MechAviv
# ID :: [927020060]
# Hidden Street : Black Mage's Antechamber
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.setSpeakerID(0)
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext("Looks like Freud and Mercedes are already inside. I hope I'm not too late.")
sm.sendDelay(750)
sm.forcedInput(2) | StarcoderdataPython |
85256 | <filename>hospital/admin.py
from django.contrib import admin
# Register your models here.
from hospital.models import Doctor, Patient, Appointment, PatientDischargeDetails
class DoctorAdmin(admin.ModelAdmin):
pass
admin.site.register(Doctor, DoctorAdmin)
class PatientAdmin(admin.ModelAdmin):
pass
admin.site.register(Patient, PatientAdmin)
class AppointmentAdmin(admin.ModelAdmin):
pass
admin.site.register(Appointment, AppointmentAdmin)
class PatientDischargeDetailsAdmin(admin.ModelAdmin):
pass
admin.site.register(PatientDischargeDetails, PatientDischargeDetailsAdmin)
| StarcoderdataPython |
6409150 | <reponame>Sposigor/Caminho_do_Python
from datetime import date
ano = int(input('Ano de nascimento: '))
g = input('Masculino ou Femino [M/F]').strip().upper()
print(f'Quem nasceu em {ano} tem {date.today().year - ano} em {date.today().year}')
if g == 'M':
if date.today().year - ano < 18:
print(f'Falta {(18 - (date.today().year - ano))} anos para o alistamento')
print(f'Seu alistamento será em {(18 - (date.today().year - ano)) + date.today().year}')
else:
print(f'Falta {(40 - (date.today().year - ano))} anos para o exame de prostata')
print(f'A dedada será em {(40 - (date.today().year - ano)) + date.today().year}')
else:
if date.today().year - ano < 18:
print(f'Falta {(18 - (date.today().year - ano))} anos para fazer outras coisas menos alistamento obrigatorio')
print(f'Seu aniversário de 18 anos será em {(18 - (date.today().year - ano)) + date.today().year}')
else:
print(f'Falta {(40 - (date.today().year - ano))} anos para menopausa')
print(f'Próximo desse ano {(40 - (date.today().year - ano)) + date.today().year}') | StarcoderdataPython |
238621 | <gh_stars>0
# Author: <NAME>
# Module: Emerging Technologies
# Date: September, 2017
# Problem Sheet: https://emerging-technologies.github.io/problems/python-fundamentals.html
# create a function to reverse a string
def reverse():
word = input("Enter a string: ") #user enters a string and store it in word
word = word[::-1] # slices and reverses the string
# Reference: https://stackoverflow.com/questions/931092/reverse-a-string-in-python
print(word)
reverse() # call function to run
| StarcoderdataPython |
5150524 | <reponame>wladimir-crypto/TensowFlow-Food
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for recommendation task."""
import os
from absl.testing import parameterized
import tensorflow.compat.v2 as tf
from tensorflow_examples.lite.model_maker.core.data_util import recommendation_dataloader as _dl
from tensorflow_examples.lite.model_maker.core.data_util import recommendation_testutil as _testutil
from tensorflow_examples.lite.model_maker.core.export_format import ExportFormat
from tensorflow_examples.lite.model_maker.core.task import recommendation
class RecommendationTest(parameterized.TestCase, tf.test.TestCase):
def setUp(self):
super().setUp()
_testutil.setup_fake_testdata(self)
self.train_loader = _dl.RecommendationDataLoader.from_movielens(
self.dataset_dir, 'train')
self.test_loader = _dl.RecommendationDataLoader.from_movielens(
self.dataset_dir, 'test')
self.model_spec_options = dict(
context_embedding_dim=16,
label_embedding_dim=16,
item_vocab_size=self.test_loader.max_vocab_id,
hidden_layer_dim_ratios=[1, 1],
)
@parameterized.parameters(
('recommendation_bow'),
('recommendation_cnn'),
('recommendation_rnn'),
)
def test_create(self, model_spec):
model_dir = os.path.join(self.test_tempdir, 'recommendation_create')
model = recommendation.create(
self.train_loader,
model_spec,
self.model_spec_options,
model_dir,
steps_per_epoch=1)
self.assertIsNotNone(model.model)
def test_evaluate(self):
model_dir = os.path.join(self.test_tempdir, 'recommendation_evaluate')
model = recommendation.create(
self.train_loader,
'recommendation_bow',
self.model_spec_options,
model_dir,
steps_per_epoch=1)
history = model.evaluate(self.test_loader)
self.assertIsInstance(history, list)
self.assertTrue(history) # Non-empty list.
def test_export(self):
model_dir = os.path.join(self.test_tempdir, 'recommendation_export')
model = recommendation.create(
self.train_loader,
'recommendation_bow',
self.model_spec_options,
model_dir,
steps_per_epoch=1)
export_format = [ExportFormat.TFLITE, ExportFormat.SAVED_MODEL]
model.export(model_dir, export_format=export_format)
# Expect tflite file.
expected_tflite = os.path.join(model_dir, 'model.tflite')
self.assertTrue(os.path.exists(expected_tflite))
self.assertGreater(os.path.getsize(expected_tflite), 0)
# Expect saved model.
expected_saved_model = os.path.join(model_dir, 'saved_model',
'saved_model.pb')
self.assertTrue(os.path.exists(expected_saved_model))
self.assertGreater(os.path.getsize(expected_saved_model), 0)
# Evaluate tflite model.
self._test_evaluate_tflite(model, expected_tflite)
def _test_evaluate_tflite(self, model, tflite_filepath):
result = model.evaluate_tflite(tflite_filepath, self.test_loader)
self.assertIsInstance(result, dict)
self.assertTrue(result) # Not empty.
if __name__ == '__main__':
tf.test.main()
| StarcoderdataPython |
385284 | <reponame>plaza-project/plaza-toggl-bridge
from sqlalchemy import Column, Integer, String, MetaData, Column, ForeignKey, UniqueConstraint, Table
metadata = MetaData()
TogglUserRegistration = Table(
'TOGGL_USER_REGISTRATION', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('toggl_token', String(256), unique=True),
Column('toggl_user_id', String(256)),
Column('toggl_user_name', String(256)))
PlazaUsers = Table(
'PLAZA_USERS', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('plaza_user_id', String(36), unique=True))
PlazaUsersInToggl = Table(
'PLAZA_USERS_IN_TOGGL', metadata,
Column('plaza_id', Integer, ForeignKey('PLAZA_USERS.id'), primary_key=True),
Column('toggl_id', Integer, ForeignKey('TOGGL_USER_REGISTRATION.id'), primary_key=True),
__table_args__=(UniqueConstraint('plaza_id', 'toggl_id')))
| StarcoderdataPython |
8077268 | <gh_stars>1000+
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class UpdatesOperations(object):
"""UpdatesOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.iot.deviceupdate.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def import_update(
self,
update_to_import, # type: "_models.ImportUpdateInput"
**kwargs # type: Any
):
# type: (...) -> None
"""Import new update version.
:param update_to_import: The update to be imported.
:type update_to_import: ~azure.iot.deviceupdate.models.ImportUpdateInput
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
action = "import"
content_type = kwargs.pop("content_type", "application/json")
# Construct URL
url = self.import_update.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['action'] = self._serialize.query("action", action, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(update_to_import, 'ImportUpdateInput')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
response_headers = {}
response_headers['Location']=self._deserialize('str', response.headers.get('Location'))
response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))
if cls:
return cls(pipeline_response, None, response_headers)
import_update.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates'} # type: ignore
def get_update(
self,
provider, # type: str
name, # type: str
version, # type: str
access_condition=None, # type: Optional["_models.AccessCondition"]
**kwargs # type: Any
):
# type: (...) -> Optional["_models.Update"]
"""Get a specific update version.
:param provider: Update provider.
:type provider: str
:param name: Update name.
:type name: str
:param version: Update version.
:type version: str
:param access_condition: Parameter group.
:type access_condition: ~azure.iot.deviceupdate.models.AccessCondition
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Update, or the result of cls(response)
:rtype: ~azure.iot.deviceupdate.models.Update or None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Update"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
_if_none_match = None
if access_condition is not None:
_if_none_match = access_condition.if_none_match
accept = "application/json"
# Construct URL
url = self.get_update.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
'name': self._serialize.url("name", name, 'str'),
'version': self._serialize.url("version", version, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
if _if_none_match is not None:
header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 304]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Update', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_update.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/providers/{provider}/names/{name}/versions/{version}'} # type: ignore
def delete_update(
self,
provider, # type: str
name, # type: str
version, # type: str
**kwargs # type: Any
):
# type: (...) -> None
"""Delete a specific update version.
:param provider: Update provider.
:type provider: str
:param name: Update name.
:type name: str
:param version: Update version.
:type version: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
# Construct URL
url = self.delete_update.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
'name': self._serialize.url("name", name, 'str'),
'version': self._serialize.url("version", version, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
response_headers = {}
response_headers['Location']=self._deserialize('str', response.headers.get('Location'))
response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))
if cls:
return cls(pipeline_response, None, response_headers)
delete_update.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/providers/{provider}/names/{name}/versions/{version}'} # type: ignore
def get_providers(
self,
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.PageableListOfStrings"]
"""Get a list of all update providers that have been imported to Device Update for IoT Hub.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PageableListOfStrings or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.iot.deviceupdate.models.PageableListOfStrings]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PageableListOfStrings"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.get_providers.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('PageableListOfStrings', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
get_providers.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/providers'} # type: ignore
def get_names(
self,
provider, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.PageableListOfStrings"]
"""Get a list of all update names that match the specified provider.
:param provider: Update provider.
:type provider: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PageableListOfStrings or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.iot.deviceupdate.models.PageableListOfStrings]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PageableListOfStrings"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.get_names.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('PageableListOfStrings', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
get_names.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/providers/{provider}/names'} # type: ignore
def get_versions(
self,
provider, # type: str
name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.PageableListOfStrings"]
"""Get a list of all update versions that match the specified provider and name.
:param provider: Update provider.
:type provider: str
:param name: Update name.
:type name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PageableListOfStrings or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.iot.deviceupdate.models.PageableListOfStrings]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PageableListOfStrings"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.get_versions.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
'name': self._serialize.url("name", name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
'name': self._serialize.url("name", name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('PageableListOfStrings', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
get_versions.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/providers/{provider}/names/{name}/versions'} # type: ignore
def get_files(
self,
provider, # type: str
name, # type: str
version, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.PageableListOfStrings"]
"""Get a list of all update file identifiers for the specified version.
:param provider: Update provider.
:type provider: str
:param name: Update name.
:type name: str
:param version: Update version.
:type version: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PageableListOfStrings or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.iot.deviceupdate.models.PageableListOfStrings]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PageableListOfStrings"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.get_files.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
'name': self._serialize.url("name", name, 'str'),
'version': self._serialize.url("version", version, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
'name': self._serialize.url("name", name, 'str'),
'version': self._serialize.url("version", version, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('PageableListOfStrings', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
get_files.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/providers/{provider}/names/{name}/versions/{version}/files'} # type: ignore
def get_file(
self,
provider, # type: str
name, # type: str
version, # type: str
file_id, # type: str
access_condition=None, # type: Optional["_models.AccessCondition"]
**kwargs # type: Any
):
# type: (...) -> Optional["_models.File"]
"""Get a specific update file from the version.
:param provider: Update provider.
:type provider: str
:param name: Update name.
:type name: str
:param version: Update version.
:type version: str
:param file_id: File identifier.
:type file_id: str
:param access_condition: Parameter group.
:type access_condition: ~azure.iot.deviceupdate.models.AccessCondition
:keyword callable cls: A custom type or function that will be passed the direct response
:return: File, or the result of cls(response)
:rtype: ~azure.iot.deviceupdate.models.File or None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.File"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
_if_none_match = None
if access_condition is not None:
_if_none_match = access_condition.if_none_match
accept = "application/json"
# Construct URL
url = self.get_file.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'provider': self._serialize.url("provider", provider, 'str'),
'name': self._serialize.url("name", name, 'str'),
'version': self._serialize.url("version", version, 'str'),
'fileId': self._serialize.url("file_id", file_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
if _if_none_match is not None:
header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 304]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('File', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_file.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/providers/{provider}/names/{name}/versions/{version}/files/{fileId}'} # type: ignore
def get_operations(
self,
filter=None, # type: Optional[str]
top=None, # type: Optional[int]
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.PageableListOfOperations"]
"""Get a list of all import update operations. Completed operations are kept for 7 days before
auto-deleted. Delete operations are not returned by this API version.
:param filter: Restricts the set of operations returned. Only one specific filter is supported:
"status eq 'NotStarted' or status eq 'Running'".
:type filter: str
:param top: Specifies a non-negative integer n that limits the number of items returned from a
collection. The service returns the number of available items up to but not greater than the
specified value n.
:type top: int
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PageableListOfOperations or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.iot.deviceupdate.models.PageableListOfOperations]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PageableListOfOperations"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.get_operations.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query("top", top, 'int')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('PageableListOfOperations', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
get_operations.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/operations'} # type: ignore
def get_operation(
self,
operation_id, # type: str
access_condition=None, # type: Optional["_models.AccessCondition"]
**kwargs # type: Any
):
# type: (...) -> Optional["_models.Operation"]
"""Retrieve operation status.
:param operation_id: Operation identifier.
:type operation_id: str
:param access_condition: Parameter group.
:type access_condition: ~azure.iot.deviceupdate.models.AccessCondition
:keyword callable cls: A custom type or function that will be passed the direct response
:return: Operation, or the result of cls(response)
:rtype: ~azure.iot.deviceupdate.models.Operation or None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Operation"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
_if_none_match = None
if access_condition is not None:
_if_none_match = access_condition.if_none_match
accept = "application/json"
# Construct URL
url = self.get_operation.metadata['url'] # type: ignore
path_format_arguments = {
'accountEndpoint': self._serialize.url("self._config.account_endpoint", self._config.account_endpoint, 'str', skip_quote=True),
'instanceId': self._serialize.url("self._config.instance_id", self._config.instance_id, 'str', skip_quote=True),
'operationId': self._serialize.url("operation_id", operation_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
if _if_none_match is not None:
header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 304]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
response_headers = {}
deserialized = None
if response.status_code == 200:
response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After'))
deserialized = self._deserialize('Operation', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
get_operation.metadata = {'url': '/deviceupdate/{instanceId}/v2/updates/operations/{operationId}'} # type: ignore
| StarcoderdataPython |
5090835 | <gh_stars>1-10
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Utility to perform policy evaluations for measuring generalization."""
import math
import os
import time
from absl import app
from absl import flags
from absl import logging
import gin
import tensorflow.compat.v2 as tf
from tf_agents.policies import py_tf_eager_policy
from tf_agents.train import actor
from tf_agents.train import triggers
from pse.dm_control import train_eval_flags # pylint:disable=unused-import
from pse.dm_control.utils import env_utils
EVALUATED_STEPS_FILE = 'evaluated_steps.txt'
FLAGS = flags.FLAGS
@gin.configurable(module='drq_agent')
def train_eval(data_dir=None): # pylint: disable=unused-argument
pass
@gin.configurable(module='evaluator')
def evaluate(env_name,
saved_model_dir,
env_load_fn=env_utils.load_dm_env_for_eval,
num_episodes=1,
eval_log_dir=None,
continuous=False,
max_train_step=math.inf,
seconds_between_checkpoint_polls=5,
num_retries=100,
log_measurements=lambda metrics, current_step: None):
"""Evaluates a checkpoint directory.
Checkpoints for the saved model to evaluate are assumed to be at the same
directory level as the saved_model dir. ie:
* saved_model_dir: root_dir/policies/greedy_policy
* checkpoints_dir: root_dir/checkpoints
Args:
env_name: Name of the environment to evaluate in.
saved_model_dir: String path to the saved model directory.
env_load_fn: Function to load the environment specified by env_name.
num_episodes: Number or episodes to evaluate per checkpoint.
eval_log_dir: Optional path to output summaries of the evaluations. If None
a default directory relative to the saved_model_dir will be used.
continuous: If True all the evaluation will keep polling for new
checkpoints.
max_train_step: Maximum train_step to evaluate. Once a train_step greater or
equal to this is evaluated the evaluations will terminate. Should set to
<= train_eval.num_iterations to ensure that eval terminates.
seconds_between_checkpoint_polls: The amount of time in seconds to wait
between polls to see if new checkpoints appear in the continuous setting.
num_retries: Number of retries for reading checkpoints.
log_measurements: Function to log measurements.
Raises:
IOError: on repeated failures to read checkpoints after all the retries.
"""
split = os.path.split(saved_model_dir)
# Remove trailing slash if we have one.
if not split[-1]:
saved_model_dir = split[0]
env = env_load_fn(env_name)
# Load saved model.
saved_model_path = os.path.join(saved_model_dir, 'saved_model.pb')
while continuous and not tf.io.gfile.exists(saved_model_path):
logging.info('Waiting on the first checkpoint to become available at: %s',
saved_model_path)
time.sleep(seconds_between_checkpoint_polls)
for _ in range(num_retries):
try:
policy = py_tf_eager_policy.SavedModelPyTFEagerPolicy(
saved_model_dir, load_specs_from_pbtxt=True)
break
except (tf.errors.OpError, tf.errors.DataLossError, IndexError,
FileNotFoundError):
logging.warning(
'Encountered an error while loading a policy. This can '
'happen when reading a checkpoint before it is fully written. '
'Retrying...')
time.sleep(seconds_between_checkpoint_polls)
else:
logging.error('Failed to load a checkpoint after retrying: %s',
saved_model_dir)
if max_train_step and policy.get_train_step() > max_train_step:
logging.info(
'Policy train_step (%d) > max_train_step (%d). No evaluations performed.',
policy.get_train_step(), max_train_step)
return
# Assume saved_model dir is of the form: root_dir/policies/greedy_policy. This
# requires going up two levels to get the root_dir.
root_dir = os.path.dirname(os.path.dirname(saved_model_dir))
log_dir = eval_log_dir or os.path.join(root_dir, 'eval')
# evaluated_file = os.path.join(log_dir, EVALUATED_STEPS_FILE)
evaluated_checkpoints = set()
train_step = tf.Variable(policy.get_train_step(), dtype=tf.int64)
metrics = actor.eval_metrics(buffer_size=num_episodes)
eval_actor = actor.Actor(
env,
policy,
train_step,
metrics=metrics,
episodes_per_run=num_episodes,
summary_dir=log_dir)
checkpoint_list = _get_checkpoints_to_evaluate(evaluated_checkpoints,
saved_model_dir)
latest_eval_step = policy.get_train_step()
while (checkpoint_list or continuous) and latest_eval_step < max_train_step:
while not checkpoint_list and continuous:
logging.info('Waiting on new checkpoints to become available.')
time.sleep(seconds_between_checkpoint_polls)
checkpoint_list = _get_checkpoints_to_evaluate(evaluated_checkpoints,
saved_model_dir)
checkpoint = checkpoint_list.pop()
for _ in range(num_retries):
try:
policy.update_from_checkpoint(checkpoint)
break
except (tf.errors.OpError, IndexError):
logging.warning(
'Encountered an error while evaluating a checkpoint. This can '
'happen when reading a checkpoint before it is fully written. '
'Retrying...')
time.sleep(seconds_between_checkpoint_polls)
else:
# This seems to happen rarely. Just skip this checkpoint.
logging.error('Failed to evaluate checkpoint after retrying: %s',
checkpoint)
continue
logging.info('Evaluating:\n\tStep:%d\tcheckpoint: %s',
policy.get_train_step(), checkpoint)
eval_actor.train_step.assign(policy.get_train_step())
train_step = policy.get_train_step()
if triggers.ENV_STEP_METADATA_KEY in policy.get_metadata():
env_step = policy.get_metadata()[triggers.ENV_STEP_METADATA_KEY].numpy()
eval_actor.training_env_step = env_step
if latest_eval_step <= train_step:
eval_actor.run_and_log()
latest_eval_step = policy.get_train_step()
else:
logging.info(
'Skipping over train_step %d to avoid logging backwards in time.',
train_step)
evaluated_checkpoints.add(checkpoint)
def _get_checkpoints_to_evaluate(evaluated_checkpoints, saved_model_dir):
"""Get an ordered list of checkpoint directories that have not been evaluated.
Note that the checkpoints are in reversed order here, because we are popping
the checkpoints later.
Args:
evaluated_checkpoints: a set of checkpoint directories that have already
been evaluated.
saved_model_dir: directory where checkpoints are saved. Often
root_dir/policies/greedy_policy.
Returns:
A sorted list of checkpoint directories to be evaluated.
"""
checkpoints_dir = os.path.join(
os.path.dirname(saved_model_dir), 'checkpoints', '*')
checkpoints = tf.io.gfile.glob(checkpoints_dir)
# Sort checkpoints, such that .pop() will return the most recent one.
return sorted(list(set(checkpoints) - evaluated_checkpoints))
def main(_):
logging.set_verbosity(logging.INFO)
logging.info('root_dir is %s', FLAGS.root_dir)
gin.parse_config_files_and_bindings(FLAGS.gin_files, FLAGS.gin_bindings)
if FLAGS.trial_id is not None:
expanded_root_dir = os.path.join(FLAGS.root_dir, FLAGS.env_name,
str(FLAGS.trial_id))
else:
expanded_root_dir = os.path.join(FLAGS.root_dir, FLAGS.env_name)
if FLAGS.seed is not None:
expanded_root_dir = os.path.join(expanded_root_dir, f'seed_{FLAGS.seed}')
saved_model_dir = os.path.join(expanded_root_dir, 'policies', 'greedy_policy')
log_measurements = lambda metrics, current_step: None
evaluate(
env_name=FLAGS.env_name,
saved_model_dir=saved_model_dir,
eval_log_dir=FLAGS.eval_log_dir,
continuous=FLAGS.continuous,
log_measurements=log_measurements)
if __name__ == '__main__':
app.run(main)
| StarcoderdataPython |
278810 | <reponame>bcgov/registries-search<filename>search-api/src/search_api/resources/v1/ops.py
# Copyright © 2022 Province of British Columbia
#
# 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.
"""Endpoints to check and manage the health of the service."""
from flask import current_app, Blueprint
from sqlalchemy import text, exc
from search_api.models import db
bp = Blueprint('OPS', __name__, url_prefix='/ops') # pylint: disable=invalid-name
SQL = text('select 1')
@bp.get('/healthz')
def healthy():
"""Return a JSON object stating the health of the Service and dependencies."""
try:
db.session.execute(SQL)
except exc.SQLAlchemyError as db_exception:
current_app.logger.error('DB connection pool unhealthy:' + repr(db_exception))
return {'message': 'api is down'}, 500
except Exception as default_exception: # noqa: B902; log error
current_app.logger.error('DB connection pool query failed:' + repr(default_exception))
return {'message': 'api is down'}, 500
# made it here, so all checks passed
return {'message': 'api is healthy'}, 200
@bp.get('/readyz')
def ready():
"""Return a JSON object that identifies if the service is setupAnd ready to work."""
return {'message': 'api is ready'}, 200
| StarcoderdataPython |
338604 | from output.models.nist_data.atomic.g_day.schema_instance.nistschema_sv_iv_atomic_g_day_min_inclusive_1_xsd.nistschema_sv_iv_atomic_g_day_min_inclusive_1 import NistschemaSvIvAtomicGDayMinInclusive1
__all__ = [
"NistschemaSvIvAtomicGDayMinInclusive1",
]
| StarcoderdataPython |
114844 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Clione Software
# Copyright (c) 2010-2013 <NAME>
#
# 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.
"""
The calendar module calls a version of Python HTML Calendar and adds some
functions to use django objects with it.
The source code is based on the work of <NAME> <<EMAIL>>
"""
from calendar import LocaleHTMLCalendar
from datetime import date
from itertools import groupby
from django.utils.html import conditional_escape as esc
class EventCalendar(LocaleHTMLCalendar):
"""
Event calendar is a basic calendar made with HTMLCalendar module and
its instance LocaleHTMLCalendar for translation.
:Attributes: LocaleHTMLCalendar
:Methods: formatday, formatmonth, group_by_day, day_cell
"""
# This init is needed for multilanguage, see ticket #86
def __init__(self, events, *args, **kwargs):
self.events = self.group_by_day(events)
super(EventCalendar, self).__init__(*args, **kwargs)
# def __init__(self, events):
# super(EventCalendar, self).__init__()
# self.events = self.group_by_day(events)
def formatday(self, day, weekday):
"""
Format the day cell with the current events for the day.
"""
if day != 0:
cssclass = self.cssclasses[weekday]
if date.today() == date(self.year, self.month, day):
cssclass += ' today'
if day in self.events:
cssclass += ' filled'
body = ['<ul>']
for event in self.events[day]:
body.append('<li>')
body.append('<a href="%s">' % event.get_absolute_url())
body.append(esc(event.title))
body.append('</a></li>')
body.append('<ul>')
return self.day_cell(cssclass, '%d %s' % (day, ''.join(body)))
return self.day_cell(cssclass, day)
return self.day_cell('noday', ' ')
def formatmonth(self, year, month):
"""
Format the current month wuth the events.
"""
# WTF is this!?
self.year, self.month = year, month
return super(EventCalendar, self).formatmonth(self.year, self.month)
def group_by_day(self, events):
"""
Group the returned events into their respective dates.
"""
field = lambda event: event.event_date.day
return dict(
[(day, list(items)) for day, items in groupby(events, field)]
)
def day_cell(self, cssclass, body):
"""
Create the day cell.
"""
return '<td class="%s">%s</td>' % (cssclass, body)
| StarcoderdataPython |
34013 | #!/usr/bin/python3
m1 = int(input("Enter no. of rows : \t"))
n1 = int(input("Enter no. of columns : \t"))
a = []
print("Enter Matrix 1:\n")
for i in range(n1):
row = list(map(int, input().split()))
a.append(row)
print(a)
m2 = int(n1)
print("\n Your Matrix 2 must have",n1,"rows and",m1,"columns \n")
n2 = int(m1)
b = []
for i in range(n2):
row = list(map(int, input().split()))
b.append(row)
print(b)
res = []
res = [ [ 0 for i in range(m2) ] for j in range(n1) ]
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(b)):
res[i][j] += a[i][k] * b[k][j]
print(res) | StarcoderdataPython |
1876369 | <gh_stars>0
'''
Created on 25 Dec 2016
@author: dusted-ipro
Contains callable data structures for all social link types
'''
def allLinks():
'''
All Link Types (Agent <-> Agent, Agent<-->Clan, Clan<-->Clan)
CAUTION: Index Order is used for internal functions!
::returns Dict All types
'''
return {0:'clan', #In same clan
1:'social', #Have interacted socially
2:'family'} #Same family
| StarcoderdataPython |
6573490 | <filename>Puzzles/Easy/DetectivePikaptcha.Ep1.py
import sys
import math
import itertools
CHANGES = [(0,1),(1,0),(0,-1),(-1,0)]
# Read inputs
width, height = (int(i) for i in input().split())
map = [[c for c in input()] for i in range(height)]
def getCase(i, j):
if i < 0 or j < 0 or i >= height or j >= width:
return 0
return 0 if map[i][j] == '#' else 1
for i, j in itertools.product(range(height), range(width)):
if map[i][j] != '#':
map[i][j] = str(sum( [getCase(i+c[0], j+c[1]) for c in CHANGES] ))
for l in map:
print("".join(l)) | StarcoderdataPython |
3313375 | <gh_stars>0
import re
from collections import Counter
def count_words(word_str):
words = Counter(re.findall(r"\b[\w'-]+\b", word_str.lower()))
return dict(words)
| StarcoderdataPython |
9767416 | <reponame>Skydler/skulpt<filename>src/lib/pedal/plugins/check_references.py
# Runner
from pedal.report.imperative import clear_report
import sys
import os
from io import StringIO
from contextlib import redirect_stdout
import unittest
from unittest.mock import patch, mock_open
# Arguments
GRADER_PATH = sys.argv[1]
REFERENCE_SOLUTIONS_DIR = "reference_solutions/"
# Load grader file
with open(GRADER_PATH, 'r') as grader_file:
grader_code = grader_file.read()
# Load Pedal from dev location
PEDAL_DIR = r"C:/Users/acbart/projects/pedal/"
sys.path.insert(0, PEDAL_DIR)
# Load reference solutions
class TestReferenceSolutions(unittest.TestCase):
maxDiff = None
def add_test(class_, name, python_file, expected_output):
def _inner_test(self):
captured_output = StringIO()
with redirect_stdout(captured_output):
# TODO: mock_open will only work if we are not anticipating
# the student or instructor to open files...
with patch('builtins.open', mock_open(read_data=python_file),
create=True):
clear_report()
compile(grader_code, GRADER_PATH, 'exec')
exec(grader_code, globals())
actual_output = captured_output.getvalue()
self.assertEqual(actual_output, expected_output)
setattr(class_, 'test_' + name, _inner_test)
for filename in os.listdir(REFERENCE_SOLUTIONS_DIR):
path = os.path.join(REFERENCE_SOLUTIONS_DIR, filename)
if path.endswith(".py"):
text_path = path[:-2] + "txt"
with open(path, 'r') as python_file:
python = python_file.read()
with open(text_path, 'r') as output_file:
output = output_file.read()
add_test(TestReferenceSolutions, filename[:-3], python, output)
if __name__ == "__main__":
unittest.main()
| StarcoderdataPython |
1816095 | <filename>src/features/fre_to_tpm/viirs/ftt_plume_tracking.py<gh_stars>0
# load in required packages
import glob
import os
from datetime import datetime, timedelta
import logging
import re
import numpy as np
from scipy import ndimage
import cv2
from shapely.geometry import Point, LineString
import src.data.readers.load_hrit as load_hrit
import src.config.filepaths as fp
import src.visualization.ftt_visualiser as vis
import src.features.fre_to_tpm.viirs.ftt_fre as ff
import src.features.fre_to_tpm.viirs.ftt_utils as ut
import src.config.constants as constants
log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(level=logging.INFO, format=log_fmt)
logger = logging.getLogger(__name__)
def get_plume_time(timestamp):
"""
:param plume_fname: the MYD filename for the plume
:return: the plume time stamp
"""
return datetime.strptime(timestamp, 'd%Y%m%d_t%H%M%S')
def find_plume_head(plume_geom_geo, plume_geom_utm, pp, t):
fire_locations_in_plume = ff.fire_locations_for_plume_roi(plume_geom_geo, pp['frp_df'], t)
mean_fire_lon = np.mean([i.x for i in fire_locations_in_plume])
mean_fire_lat = np.mean([i.y for i in fire_locations_in_plume])
# project to utm
mean_fire_utm = ut.reproject_shapely(Point(mean_fire_lon, mean_fire_lat),
plume_geom_utm['utm_resampler_plume'])
return {'head_lon': mean_fire_lon,
'head_lat': mean_fire_lat,
'head': mean_fire_utm}
def find_tail_edge(plume_geom_utm):
# convex hull of plume
x, y = plume_geom_utm['utm_plume_points'].minimum_rotated_rectangle.exterior.xy
# get parallel edges of convex hull
edge_a = LineString([(x[0], y[0]), (x[1], y[1])])
edge_b = LineString([(x[2], y[2]), (x[3], y[3])])
edge_c = LineString([(x[1], y[1]), (x[2], y[2])])
edge_d = LineString([(x[3], y[3]), (x[4], y[4])])
edges = [edge_a, edge_b, edge_c, edge_d]
distances = [plume_geom_utm['utm_plume_tail'].distance(i) for i in edges]
return edges[np.argmin(distances)]
def find_plume_tail(head, plume_geom_utm):
# find tail edge
tail_edge = find_tail_edge(plume_geom_utm)
# using head, project it on to the tail edge to find plume tail for purposes of the code
tail = tail_edge.interpolate(tail_edge.project(head))
tail_lon, tail_lat = plume_geom_utm['utm_resampler_plume'].resample_point_to_geo(tail.y, tail.x)
return {'tail_lon': tail_lon,
'tail_lat': tail_lat,
'tail': tail}
def compute_plume_vector(plume_geom_geo, plume_geom_utm, pp, t):
# first set up the two alternative head and tail combintations
# second cehck if one of the heads is outside of the bounding polygon
# if both inside find the orientation of the rectangle
head_dict = find_plume_head(plume_geom_geo, plume_geom_utm, pp, t)
tail_dict = find_plume_tail(head_dict['head'], plume_geom_utm)
vect = np.array(head_dict['head'].coords) - np.array(tail_dict['tail'].coords)
return head_dict, tail_dict, vect[0]
def compute_flow_window_size(plume_geom_utm):
# convex hull of plume
x, y = plume_geom_utm['utm_plume_points'].minimum_rotated_rectangle.exterior.xy
d1 = np.linalg.norm(np.array([x[1], y[1]]) - np.array([x[0], y[0]]))
d2 = np.linalg.norm(np.array([x[2], y[2]]) - np.array([x[1], y[1]]))
smallest_edge_len = np.min([d1, d2])
return int((smallest_edge_len / constants.utm_grid_size) / 4.0) # 4 determined from experimentation
def spatial_subset(lats_1, lons_1, lats_2, lons_2):
"""
:param lats_1: target lat region
:param lons_1: target lon region
:param lats_2: extended lat region
:param lons_2: extended lon region
:return bounds: bounding box locating l1 in l2
"""
padding = 50 # pixels TODO add to config
min_lat = np.min(lats_1)
max_lat = np.max(lats_1)
min_lon = np.min(lons_1)
max_lon = np.max(lons_1)
coords = np.where((lats_2 >= min_lat) & (lats_2 <= max_lat) &
(lons_2 >= min_lon) & (lons_2 <= max_lon))
min_x = np.min(coords[1]) - padding
max_x = np.max(coords[1]) + padding
min_y = np.min(coords[0]) - padding
max_y = np.max(coords[0]) + padding
if min_x < 0: min_x = 50
if min_y < 0: min_y = 50
# todo implement an appropriate max threshold
return {'max_x': max_x,
'min_x': min_x,
'max_y': max_y,
'min_y': min_y}
def subset_geograpic_data(geostationary_lats, geostationary_lons, bb):
"""
:param geostationary_lats: the lat image
:param geostationary_lons: the lon image
:param bb: the plume bounding box
:return: the lats and lons for the bounding box
"""
geostationary_lats_subset = geostationary_lats[bb['min_y']:bb['max_y'], bb['min_x']:bb['max_x']]
geostationary_lons_subset = geostationary_lons[bb['min_y']:bb['max_y'], bb['min_x']:bb['max_x']]
zoom = 4 # zoom if using 0.5km himawara data (B03) for tracking
geostationary_lats_subset = ndimage.zoom(geostationary_lats_subset, zoom)
geostationary_lons_subset = ndimage.zoom(geostationary_lons_subset, zoom)
bb.update((x, y * zoom) for x, y in bb.items()) # enlarge bounding box by factor of zoom also
return {'geostationary_lats_subset':geostationary_lats_subset,
'geostationary_lons_subset':geostationary_lons_subset}
def find_min_himawari_image_segment(bb):
"""
:param bb: bounding box
:return: the himawari image segment for the given bounding box
"""
# there are ten 2200 pixel segments in himawari 0.5 km data
seg_size = 2200
min_segment = bb['min_y'] / seg_size + 1
return min_segment
def adjust_bb_for_segment(bb, segment):
"""
:param bb: plume bounding box
:param segment: the image segment that contains the bounding box
:return: Nothing, the boudning box coordinates are adjusted inplace
"""
seg_size = 2200
bb['min_y'] -= (segment * seg_size)
bb['max_y'] -= (segment * seg_size)
def get_geostationary_fnames(plume_time, image_segment):
"""
:param plume_time: the time of the MYD observation of the plume
:param image_segment: the Himawari image segment
:return: the geostationary files for the day of and the day before the fire
"""
ym = str(plume_time.year) + str(plume_time.month).zfill(2)
day = str(plume_time.day).zfill(2)
# get all files in the directory using glob with band 3 for main segment
p = os.path.join(fp.path_to_himawari_imagery, ym, day)
fp_1 = glob.glob(p + '/*/*/B03/*S' + str(image_segment).zfill(2) + '*')
# get the day before also
day = str(plume_time.day - 1).zfill(2)
p = os.path.join(fp.path_to_himawari_imagery, ym, day)
fp_2 = glob.glob(p + '/*/*/B03/*S' + str(image_segment).zfill(2) + '*')
files = fp_1 + fp_2
return files
def restrict_geostationary_times(plume_time, geostationary_fnames):
"""
:param plume_time: the plume time
:param geostationary_fnames: the list of geostationary file names
:return: only those goestationary files that were obtained prior to the myd overpass
"""
return [f for f in geostationary_fnames if
datetime.strptime(re.search("[0-9]{8}[_][0-9]{4}", f).group(),
'%Y%m%d_%H%M') <= plume_time]
def sort_geostationary_by_time(geostationary_fnames):
"""
:param geostationary_fnames goestationary filenames
:return: the geostationary filenames in time order
"""
times = [datetime.strptime(re.search("[0-9]{8}[_][0-9]{4}", f).group()
, '%Y%m%d_%H%M') for f in geostationary_fnames]
return [f for _, f in sorted(zip(times, geostationary_fnames))]
def setup_geostationary_files(plume_time, image_segment):
geostationary_fnames = get_geostationary_fnames(plume_time, image_segment)
geostationary_fnames = restrict_geostationary_times(plume_time, geostationary_fnames)
geostationary_fnames = sort_geostationary_by_time(geostationary_fnames)
geostationary_fnames.reverse()
return geostationary_fnames
def extract_observation(f, bb, segment):
# load geostationary files for the segment
rad_segment_1, _ = load_hrit.H8_file_read(os.path.join(fp.path_to_himawari_imagery, f))
# load for the next segment
f_new = f.replace('S' + str(segment).zfill(2), 'S' + str(segment + 1).zfill(2))
rad_segment_2, _ = load_hrit.H8_file_read(os.path.join(fp.path_to_himawari_imagery, f_new))
# concat the himawari files
rad = np.vstack((rad_segment_1, rad_segment_2))
# extract geostationary image subset using adjusted bb and rescale to 8bit
rad_bb = rad[bb['min_y']:bb['max_y'], bb['min_x']:bb['max_x']]
return rad_bb
def load_image(geostationary_fname, bbox, min_geo_segment):
return extract_observation(geostationary_fname, bbox, min_geo_segment)
def reproject_image(im, geo_dict, plume_geom_utm):
return plume_geom_utm['utm_resampler_plume'].resample_image(im, geo_dict['geostationary_lats_subset'],
geo_dict['geostationary_lons_subset'])
def unit_vector(vector):
""" Returns the unit vector of the vector. """
return vector / np.linalg.norm(vector)
def adjust_image_map_coordinates(flow):
"""
The image flow is returned in image coordinate space. The derived vectors
that describe the flow cannot therefore be used as is for calculating the
flow on the map. They need to be adjusted to the map space. As everything
is projected onto a UTM grid this is relatively straightforward, we just need
to invert the y axis (as the image and map coordinate systems are in effect
inverted).
:param flow: the image flow
:return: the adjusted image flow
"""
flow[:,:,1] *= -1
return flow
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
"""
v1 = adjust_image_map_coordinates(v1)
# first norm the vectors
eps = 0.0001
v1 /= np.sqrt(((v1 + eps) ** 2).sum(-1))[..., np.newaxis]
v2 /= np.sqrt(((v2 + eps) ** 2).sum(-1))[..., np.newaxis]
return np.arccos(np.clip(np.dot(v1, v2), -1.0, 1.0))
def extract_plume_flow(plume_geom_geo, plume_geom_utm, f1_subset_reproj, flow,
plume_vector, plume_head, plume_tail,
plume_logging_path, fname, stage_name, plot=True):
plume_mask = plume_geom_geo['plume_mask']
# if plume mask not same shape as himawari subset them
# adjust it to match. Exact overlay doesn't matter as
# we are looking for average plume motion
if plume_mask.shape != f1_subset_reproj.shape:
if plume_mask.size < f1_subset_reproj.size:
ax0_diff = f1_subset_reproj.shape[0] - plume_mask.shape[0]
ax0_pad = (ax0_diff, 0) # padding n_before, n_after. n_after always zero
ax1_diff = f1_subset_reproj.shape[1] - plume_mask.shape[1]
ax1_pad = (ax1_diff, 0)
plume_mask = np.pad(plume_mask, (ax0_pad, ax1_pad), 'edge')
else:
plume_mask = plume_mask[:f1_subset_reproj.shape[0], :f1_subset_reproj.shape[1]]
# mask flow to plume extent
flow *= plume_mask[..., np.newaxis]
# now limit to only vectors in general flow direction
angles = angle_between(flow.copy(), plume_vector)
angular_mask = angles <= constants.angular_limit
flow *= angular_mask[..., np.newaxis]
if plot:
vis.draw_flow(f1_subset_reproj, flow, plume_logging_path, fname, 'unmapped_flow_' + stage_name)
vis.draw_flow_map(f1_subset_reproj, plume_geom_utm['utm_resampler_plume'], plume_geom_utm['utm_plume_points'],
plume_head, plume_tail, flow, plume_logging_path, fname, 'mapped_flow_' + stage_name, step=2) # mask flow to moving points
x, y = flow.T
mask = (x != 0) & (y != 0)
y = y[mask]
x = x[mask]
# take the most most extreme quartile data
if np.abs(y.min()) > y.max():
y_pc = np.percentile(y, 25)
y_mask = y < y_pc
# y_pc_upper = np.percentile(y, 30)
# y_pc_lower = np.percentile(y, 5)
# y = y[(y < y_pc_upper) & (y > y_pc_lower)]
else:
y_pc = np.percentile(y, 75)
y_mask = y > y_pc
# y_pc_upper = np.percentile(y, 95)
# y_pc_lower = np.percentile(y, 70)
# y = y[(y < y_pc_upper) & (y > y_pc_lower)]
if np.abs(x.min()) > x.max():
x_pc = np.percentile(x, 25)
x_mask = x < x_pc
# x_pc_upper = np.percentile(x, 30)
# x_pc_lower = np.percentile(x, 5)
# x = x[(x < x_pc_upper) & (x > x_pc_lower)]
else:
x_pc = np.percentile(x, 75)
x_mask = x > x_pc
# TODO check this masking
y = y[y_mask | x_mask]
x = x[y_mask | x_mask]
# determine plume flow in metres
y = np.mean(y) * constants.utm_grid_size
x = np.mean(x) * constants.utm_grid_size
plume_flow = (x,y)
return plume_flow
def tracker(plume_logging_path, plume_geom_utm, plume_geom_geo, pp, timestamp, p_number):
# get bounding box around smoke plume in geostationary imager coordinates
# and extract the geographic coordinates for the roi, also set up plot stuff
bbox = spatial_subset(plume_geom_geo['plume_lats'], plume_geom_geo['plume_lons'],
pp['geostationary_lats'], pp['geostationary_lons'])
him_geo_dict = subset_geograpic_data(pp['geostationary_lats'], pp['geostationary_lons'], bbox)
him_segment = find_min_himawari_image_segment(bbox)
adjust_bb_for_segment(bbox, him_segment - 1)
plume_time = get_plume_time(timestamp)
geostationary_fnames = setup_geostationary_files(plume_time, him_segment)
# establish plume vector, and the total plume length. If the plume does not
# intersect with the end of the polygon then we do not need to worry about
# limiting the FRP integration times. So just return the min and max geo times
t0 = datetime.strptime(re.search("[0-9]{8}[_][0-9]{4}", geostationary_fnames[0]).group(),
'%Y%m%d_%H%M')
plume_head, plume_tail, plume_vector = compute_plume_vector(plume_geom_geo, plume_geom_utm, pp, t0)
# plume length in metres
plume_length = np.linalg.norm(plume_vector)
# a priori flow determination
flow_images = []
prior_flows = []
current_tracked_plume_distance = 0
for i in xrange(6):
im_subset = load_image(geostationary_fnames[i], bbox, him_segment)
im_subset_reproj = reproject_image(im_subset, him_geo_dict, plume_geom_utm)
flow_images.append(im_subset_reproj)
# if on the first image, continue to load the second
if i == 0:
continue
# As the tracking is from t0 back to source (i.e. bak through time to t-n), we want
# to calulate the flow in reverse, with the previous image being the most recent
# and the next image being the observation prior to the most recent.
flow_win_size = 5
scene_flow = cv2.calcOpticalFlowFarneback(flow_images[i-1], flow_images[i],
flow=None,
pyr_scale=0.5, levels=1,
winsize=flow_win_size, iterations=7,
poly_n=7, poly_sigma=1.5,
flags=cv2.OPTFLOW_FARNEBACK_GAUSSIAN)
# lets do an additional median smoothing here and store flows
#scene_flow = ndimage.filters.median_filter(scene_flow, 2)
prior_flows.append(scene_flow)
plume_flow_x, plume_flow_y = extract_plume_flow(plume_geom_geo, plume_geom_utm, flow_images[i-1], scene_flow,
plume_vector, plume_head, plume_tail,
plume_logging_path, geostationary_fnames[i-1],
'prior_flow_', plot=pp['plot'])
# adust flow for utm
plume_flow_y *= -1
# projected_flow = np.dot(plume_vector, (plume_flow_x, plume_flow_y)) / \
# np.dot(plume_vector, plume_vector) * plume_vector
current_tracked_plume_distance += np.linalg.norm((plume_flow_x, plume_flow_y))
if (((plume_length - current_tracked_plume_distance) < constants.utm_grid_size) |
(current_tracked_plume_distance > plume_length)):
break
# repeat first flow as best estimate
prior_flows.insert(0, prior_flows[0])
current_tracked_plume_distance = 0
velocities = []
post_flows = []
for i in xrange(6): # look at the last hour of data
# again skip first image
if i == 0:
continue
# prev, next, flow, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags
scene_flow = cv2.calcOpticalFlowFarneback(flow_images[i-1], flow_images[i],
flow=prior_flows[i-1],
pyr_scale=0.5, levels=1,
winsize=flow_win_size, iterations=7,
poly_n=7, poly_sigma=1.5,
flags=cv2.OPTFLOW_USE_INITIAL_FLOW + cv2.OPTFLOW_FARNEBACK_GAUSSIAN)
# we should not do this for the second round, as have already applied it in the first. Instead
# just mask to plume and take the mean and sd as the values
plume_flow_x, plume_flow_y = extract_plume_flow(plume_geom_geo, plume_geom_utm, flow_images[i-1], scene_flow,
plume_vector, plume_head, plume_tail,
plume_logging_path, geostationary_fnames[i-1],
'post_flow_', plot=pp['plot'])
# adust flow for utm
plume_flow_y *= -1
# project flow onto principle axis
# projected_flow = np.dot(plume_vector, (plume_flow_x, plume_flow_y)) / \
# np.dot(plume_vector, plume_vector) * plume_vector
# distance_travelled = np.linalg.norm(projected_flow)
post_flows.append((plume_flow_x, plume_flow_y))
distance_travelled = np.linalg.norm((plume_flow_x, plume_flow_y))
current_tracked_plume_distance += distance_travelled
# record the the velocity in the plume direction
velocities.append(distance_travelled / 600) # gives velocity in m/s (600 seconds between images)
print current_tracked_plume_distance
print plume_length
print
if (((plume_length - current_tracked_plume_distance) < constants.utm_grid_size) |
(current_tracked_plume_distance > plume_length)):
break
# get the plume start and stop times
t_start = datetime.strptime(re.search("[0-9]{8}[_][0-9]{4}", geostationary_fnames[0]).group(), '%Y%m%d_%H%M')
#mean_velocity = np.mean(velocity)
#time_for_plume = plume_length / mean_velocity
max_velocity_index = np.argmax(velocities)
max_flow = post_flows[max_velocity_index]
max_velocity = velocities[max_velocity_index]
#print post_flows
#mean_flow = np.mean(post_flows, axis=0)
#mean_velocity = np.mean(velocities)
time_for_plume = plume_length / max_velocity # in seconds
t_stop = t_start - timedelta(seconds=time_for_plume)
# round to nearest 10 minutes
t_stop += timedelta(minutes=5)
t_stop -= timedelta(minutes=t_stop.minute % 10,
seconds=t_stop.second,
microseconds=t_stop.microsecond)
#print 'plume velocity m/s', mean_velocity
print 'plume velocity m/s', max_velocity
print 'time for plume s', time_for_plume
print t_start
print t_stop
print max_flow
if (pp['plot']):
n = int(time_for_plume / 600)
vis.run_plot(max_flow, geostationary_fnames, plume_geom_geo, pp, bbox, him_segment, him_geo_dict, plume_geom_utm,
plume_head, plume_tail, plume_geom_utm['utm_plume_points'], plume_geom_utm['utm_resampler_plume'],
plume_logging_path, n+1)
# return the times
return t_start, t_stop, time_for_plume, plume_length, max_velocity | StarcoderdataPython |
3405480 | <filename>functions/erp-transform-file/func.py<gh_stars>1-10
# Copyright (c) 2021, Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
import logging
import io
import json
import oci.object_storage
from fdk import response
import erp_data_file
def handler(ctx, data: io.BytesIO = None):
logging.info("------------------------------------------------------------------------------")
logging.info("Within erp-transform-file")
logging.info("------------------------------------------------------------------------------")
oci_signer = oci.auth.signers.get_resource_principals_signer()
object_storage_client = oci.object_storage.ObjectStorageClient(config={}, signer=oci_signer)
namespace = object_storage_client.get_namespace().data
# Get Configuration Parameters
cfg = ctx.Config()
try:
param_json_inbound_bucket_name = cfg['json_inbound_bucket_name']
param_zip_inbound_bucket_name = cfg["zip_inbound_bucket_name"]
param_ons_error_topic_ocid = cfg["ons_error_topic_ocid"]
param_ons_info_topic_ocid = cfg["ons_info_topic_ocid"]
except KeyError as ke:
message = f'Mandatory Configuration Parameter {ke} missing, please check all configuration parameters'
return return_fn_error(ctx, response, message)
try:
body = json.loads(data.getvalue())
except json.decoder.JSONDecodeError as ex:
message = send_notification(ons_topic_id=param_ons_error_topic_ocid,
title="JSON Exception",
message="JSON Exception Parsing input data file",
status="ERROR",
additional_details=str(ex)
)
return return_fn_error(ctx, response, message)
if body["eventType"] != "com.oraclecloud.objectstorage.createobject":
message = f'eventType not of com.oraclecloud.objectstorage.createobject aborting'
message = send_notification(ons_topic_id=param_ons_info_topic_ocid,
title="Incorrect Event",
message="Incorrect EventType Received",
status="ERROR",
additional_details=body)
return return_fn_error(ctx, response, message)
json_datafile_name = body['data']['resourceName']
logging.info(f'Data File received = {json_datafile_name}')
# Read datafile from OCI
json_data_file = object_storage_client.get_object(namespace, param_json_inbound_bucket_name, json_datafile_name)
if json_data_file.status != 200:
msg = f'Unable to read Data File [{json_datafile_name} from bucket [{param_json_inbound_bucket_name}'
additional_details = {"jsonDataFilename": json_datafile_name}
message = send_notification(
ons_topic_id=param_ons_info_topic_ocid,
title="Data File Read Error",
message=msg,
status="ERROR",
additional_details=additional_details)
return return_fn_error(ctx, response, message, json.dumps(additional_details))
try:
json_data = json.loads(json_data_file.data.content.decode('UTF8'))
except json.decoder.JSONDecodeError as ex:
additional_details={
"jsonDecodeError": str(ex),
"filename" : json_datafile_name
}
message = send_notification(ons_topic_id=param_ons_error_topic_ocid,
title="JSON Decode Exception",
message="JSON Decode Exception Parsing input data file, please check the file",
status="ERROR",
additional_details=additional_details
)
return return_fn_error(ctx, response, message)
# Write result to /tmp
transformed_data_file = "/tmp/ " + json_datafile_name
erp_data_file.create_erp_invoices_datafiles(json_data, transformed_data_file)
# Write resulting object to json_inbound_bucket_name, no change extension , enroute
with open(transformed_data_file, 'rb') as f:
oci_response = object_storage_client.put_object(namespace, param_zip_inbound_bucket_name,
json_datafile_name.replace('.json', '.zip'), f)
if oci_response.status != 200:
message = f'Error loading file into OCI bucket {json_datafile_name}'
additional_details = {"jsonDataFilename": json_datafile_name}
message = send_notification(
ons_topic_id=param_ons_info_topic_ocid,
title="Data Bucket LoadError",
message="Received error whilst writing file to OCI bucket",
status="ERROR",
additional_details=additional_details)
return return_fn_error(ctx, response, message, json.dumps(additional_details))
# Now delete file as its been processed
if object_storage_client.delete_object(namespace, param_json_inbound_bucket_name, json_datafile_name).status != 204:
message_details = f'Error deleting processed file {json_datafile_name} into OCI bucket '
additional_details = {"jsonDataFilename": json_datafile_name}
message = send_notification(
ons_topic_id=param_ons_error_topic_ocid,
title="Failed to Delete Tranform file",
message=message_details,
status="ERROR",
additional_details=additional_details)
return return_fn_error(ctx, response, message, json.dumps(additional_details))
# Publish Success Message
ons_body = {"message": "ERP Transform of file " + json_datafile_name + " completed",
"filename": json_datafile_name}
additional_details = ""
message = send_notification(
ons_topic_id=param_ons_info_topic_ocid,
title=f'Transform of file {json_datafile_name} Completed ',
message=ons_body,
status="INFO",
additional_details=additional_details)
return response.Response(
ctx, response_data=json.dumps(
{
"message": f'Datafile [{json_datafile_name}] transformed and put into bucket [{param_zip_inbound_bucket_name}]'}),
headers={"Content-Type": "application/json"}
)
def return_fn_error(ctx, fn_response, message, additional_details="None"):
logging.critical(message)
# Return Error
return fn_response.Response(
ctx, response_data=
{
"errorMessage": message,
"additionalDetails": additional_details
},
headers={"Content-Type": "application/json"}
)
#
# Helper functions
#
def publish_ons_notification(topic_id, msg_title, msg_body):
try:
signer = oci.auth.signers.get_resource_principals_signer()
logging.info("Publish notification, topic id" + topic_id)
client = oci.ons.NotificationDataPlaneClient({}, signer=signer)
msg = oci.ons.models.MessageDetails(title=msg_title, body=msg_body)
client.publish_message(topic_id, msg)
except oci.exceptions.ServiceError as serr:
logging.critical(f'Exception sending notification {0} to OCI, is the OCID of the notification correct? {serr}')
except Exception as err:
logging.critical(f'Unknown exception occurred when sending notification, please see log {err}')
def send_notification(ons_topic_id, title, message, status, additional_details) -> object:
message = {"status": status,
"header": title,
"message": message,
"additionalDetails": additional_details}
publish_ons_notification(ons_topic_id, title, str(message))
return message
| StarcoderdataPython |
11216794 | # Operator overloading example
import example
a = example.Complex(2, 3)
b = example.Complex(-5, 10)
print "a =", a
print "b =", b
c = a + b
print "c =", c
print "a*b =", a * b
print "a-c =", a - c
e = example.ComplexCopy(a - c)
print "e =", e
# Big expression
f = ((a + b) * (c + b * e)) + (-a)
print "f =", f
| StarcoderdataPython |
3476124 | <filename>hex_raster_processor/__init__.py<gh_stars>0
# -*- coding: utf-8 -*-
"""Top-level package for Raster Processor."""
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.9'
| StarcoderdataPython |
4876318 | from PyMySQLLock import Locker
def test_get_lock_success(mysql_conn_params, mysql_connectors):
for connector in mysql_connectors:
mysql_conn_params["mysql_lib_connector"] = connector
locker = Locker(**mysql_conn_params)
l = locker.lock("test")
ret = l.acquire(refresh_interval_secs=1)
assert ret
assert l.locked()
# verify the lock returns in get_locks
assert isinstance(locker.get_all_locks(), list)
# verify if lock is obtained by trying to acquire again with same name
l1 = locker.lock("test")
ret1 = l1.acquire(timeout=1)
assert not ret1
assert not l1.locked()
# release the lock now
l.release()
# try again to acquire
ret1 = l1.acquire(timeout=1)
assert ret1
assert l1.locked()
l1.release()
def test_mysql_error(mysql_conn_params):
mysql_conn_params["password"] = "<PASSWORD>" # this will cause an error
try:
locker = Locker(**mysql_conn_params)
l = locker.lock("test")
ret = l.acquire()
except Exception as e:
assert "Could not connect to db" in str(e)
| StarcoderdataPython |
9735160 | <filename>Lib/objc/_BiometricKit.py
"""
Classes from the 'BiometricKit' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
BKErrorHelper = _Class("BKErrorHelper")
BKEnrollPearlProgressInfo = _Class("BKEnrollPearlProgressInfo")
BKFaceDetectStateInfo = _Class("BKFaceDetectStateInfo")
BKSystemProtectedConfiguration = _Class("BKSystemProtectedConfiguration")
BKUserProtectedConfiguration = _Class("BKUserProtectedConfiguration")
BKMatchResultInfo = _Class("BKMatchResultInfo")
BKMatchPearlResultInfo = _Class("BKMatchPearlResultInfo")
BKIdentity = _Class("BKIdentity")
BKOperation = _Class("BKOperation")
BKExtendEnrollTouchIDOperation = _Class("BKExtendEnrollTouchIDOperation")
BKPresenceDetectOperation = _Class("BKPresenceDetectOperation")
BKFaceDetectOperation = _Class("BKFaceDetectOperation")
BKFingerDetectOperation = _Class("BKFingerDetectOperation")
BKMatchOperation = _Class("BKMatchOperation")
BKMatchPearlOperation = _Class("BKMatchPearlOperation")
BKMatchTouchIDOperation = _Class("BKMatchTouchIDOperation")
BKEnrollOperation = _Class("BKEnrollOperation")
BKEnrollPearlOperation = _Class("BKEnrollPearlOperation")
BKEnrollTouchIDOperation = _Class("BKEnrollTouchIDOperation")
BiometricPreferences = _Class("BiometricPreferences")
BiometricSupportTools = _Class("BiometricSupportTools")
BKDevice = _Class("BKDevice")
BKDevicePearl = _Class("BKDevicePearl")
BKDeviceTouchID = _Class("BKDeviceTouchID")
BKMatchEvent = _Class("BKMatchEvent")
BKDeviceManager = _Class("BKDeviceManager")
BKDeviceDescriptor = _Class("BKDeviceDescriptor")
BiometricKitMatchInfo = _Class("BiometricKitMatchInfo")
BiometricKitIdentity = _Class("BiometricKitIdentity")
BiometricKit = _Class("BiometricKit")
BiometricKitStatistics = _Class("BiometricKitStatistics")
BiometricKitTemplateInfo = _Class("BiometricKitTemplateInfo")
BiometricKitXPCClient = _Class("BiometricKitXPCClient")
BiometricKitXPCClientConnection = _Class("BiometricKitXPCClientConnection")
BiometricKitEnrollProgressMergedComponent = _Class(
"BiometricKitEnrollProgressMergedComponent"
)
BiometricKitEnrollProgressCoordinates = _Class("BiometricKitEnrollProgressCoordinates")
BiometricKitEnrollProgressInfo = _Class("BiometricKitEnrollProgressInfo")
| StarcoderdataPython |
11307017 | <gh_stars>100-1000
from clpy.manipulation.join import * # NOQA
| StarcoderdataPython |
5144185 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Let's play a game called "PIG".
+-----------------------------------------------------------+
| There are 2 players: You and the opponent. |
| |
| Players take turns to roll a dice as many times as |
| they wish, adding all roll results to a running total, |
| but if the player rolls a 1 the gained score for the |
| turn will be lost. |
| |
| Who gets to 100 points first wins the game. |
+-----------------------------------------------------------+
"""
import shell
def main():
"""Execute the main program."""
print(__doc__)
shell.Shell().cmdloop()
if __name__ == "__main__":
main()
| StarcoderdataPython |
3473056 | <gh_stars>0
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name' : 'Invoicing',
'version' : '1.1',
'summary': 'Invoices & Payments',
'sequence': 15,
'description': """
Invoicing & Payments
====================
The specific and easy-to-use Invoicing system in Odoo allows you to keep track of your accounting, even when you are not an accountant. It provides an easy way to follow up on your vendors and customers.
You could use this simplified accounting in case you work with an (external) account to keep your books, and you still want to keep track of payments. This module also offers you an easy method of registering payments, without having to encode complete abstracts of account.
""",
'category': 'Accounting/Accounting',
'website': 'https://www.odoo.com/page/billing',
'images' : ['images/accounts.jpeg','images/bank_statement.jpeg','images/cash_register.jpeg','images/chart_of_accounts.jpeg','images/customer_invoice.jpeg','images/journal_entries.jpeg'],
'depends' : ['base_setup', 'product', 'analytic', 'portal', 'digest'],
'data': [
'security/account_security.xml',
'security/ir.model.access.csv',
'data/data_account_type.xml',
'data/account_data.xml',
'data/digest_data.xml',
'views/account_menuitem.xml',
'views/account_payment_view.xml',
'wizard/account_accrual_accounting_view.xml',
'wizard/account_unreconcile_view.xml',
'wizard/account_move_reversal_view.xml',
'views/account_move_views.xml',
'wizard/setup_wizards_view.xml',
'wizard/pos_box.xml',
'views/partner_view.xml',
'views/account_view.xml',
'views/report_statement.xml',
'views/account_report.xml',
'data/mail_template_data.xml',
'wizard/account_validate_move_view.xml',
'views/account_end_fy.xml',
'views/product_view.xml',
'views/account_analytic_view.xml',
'views/account_tip_data.xml',
'views/account.xml',
'views/report_invoice.xml',
'report/account_invoice_report_view.xml',
'views/account_cash_rounding_view.xml',
'wizard/account_report_common_view.xml',
'views/report_journal.xml',
'views/tax_adjustments.xml',
'wizard/wizard_tax_adjustments_view.xml',
'views/res_config_settings_views.xml',
'views/account_journal_dashboard_view.xml',
'views/account_portal_templates.xml',
'views/report_payment_receipt_templates.xml',
'data/payment_receipt_data.xml',
'views/account_onboarding_templates.xml',
'data/service_cron.xml',
'views/account_fiscal_year_view.xml',
'views/account_incoterms_view.xml',
'data/account_incoterms_data.xml',
'views/digest_views.xml',
'wizard/account_invoice_send_views.xml',
'views/account_tax_report_views.xml',
'views/report_statement.xml',
'report/account_hash_integrity_templates.xml'
],
'demo': [
'demo/account_demo.xml',
],
'qweb': [
"static/src/xml/account_reconciliation.xml",
"static/src/xml/account_payment.xml",
"static/src/xml/account_report_backend.xml",
"static/src/xml/bills_tree_upload_views.xml",
'static/src/xml/account_journal_activity.xml',
'static/src/xml/tax_group.xml',
],
'installable': True,
'application': True,
'auto_install': False,
'post_init_hook': '_auto_install_l10n',
}
| StarcoderdataPython |
8067151 | <gh_stars>0
def func(n):
for num in range(2, n):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
print(num)
func(10) | StarcoderdataPython |
3368300 | <filename>greykite/common/time_properties_forecast.py
# BSD 2-CLAUSE LICENSE
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# #ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# original author: <NAME>
"""Functions that extract timeseries properties, with additional
domain logic for forecasting.
"""
import math
from datetime import timedelta
from greykite.common.constants import TIME_COL
from greykite.common.constants import VALUE_COL
from greykite.common.enums import SimpleTimeFrequencyEnum
from greykite.common.enums import TimeEnum
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.time_properties import get_canonical_data
from greykite.common.time_properties import min_gap_in_seconds
def get_default_horizon_from_period(period, num_observations=None):
"""Returns default forecast horizon based on input data period and num_observations
:param period: float
Period of each observation (i.e. average time between observations, in seconds)
:param num_observations: Optional[int]
Number of observations for training
:return: int
default number of periods to forecast
"""
default_from_period = get_simple_time_frequency_from_period(period).value.default_horizon
if num_observations is not None:
default_from_observations = num_observations // 2 # twice as much training data as forecast horizon
return min(default_from_period, default_from_observations) # horizon based on limiting factor
else:
return default_from_period
def get_simple_time_frequency_from_period(period):
"""Returns SimpleTimeFrequencyEnum based on input data period
:param period: float
Period of each observation (i.e. average time between observations, in seconds)
:return: SimpleTimeFrequencyEnum
SimpleTimeFrequencyEnum is used to define default values for horizon, seasonality, etc.
(but original data frequency is not modified)
"""
freq_threshold = [
(SimpleTimeFrequencyEnum.MINUTE, 10.05), # <= 10 minutes is considered minute-level, buffer for abnormalities
(SimpleTimeFrequencyEnum.HOUR, 6.05), # <= 6 hours is considered hourly, buffer for abnormalities
(SimpleTimeFrequencyEnum.DAY, 2.05), # <= 2 days is considered daily, buffer for daylight savings
(SimpleTimeFrequencyEnum.WEEK, 2.05), # <= 2 weeks is considered weekly, buffer for daylight savings
(SimpleTimeFrequencyEnum.MONTH, 2.05), # <= 2 months is considered monthly, buffer for 31-day month
(SimpleTimeFrequencyEnum.YEAR, 1.01), # <= 1 years is considered yearly, buffer for leap year
]
for simple_freq, threshold in freq_threshold:
if period <= simple_freq.value.seconds_per_observation * threshold:
return simple_freq
return SimpleTimeFrequencyEnum.MULTIYEAR
def get_forecast_time_properties(
df,
time_col=TIME_COL,
value_col=VALUE_COL,
freq=None,
date_format=None,
regressor_cols=None,
lagged_regressor_cols=None,
train_end_date=None,
forecast_horizon=None):
"""Returns the number of training points in `df`, the start year, and prediction end year
Parameters
----------
df : `pandas.DataFrame` with columns [``time_col``, ``value_col``]
Univariate timeseries data to forecast
time_col : `str`, default ``TIME_COL`` in constants.py
Name of timestamp column in df
value_col : `str`, default ``VALUE_COL`` in constants.py
Name of value column in df (the values to forecast)
freq : `str` or None, default None
Frequency of input data. Used to generate future dates for prediction.
Frequency strings can have multiples, e.g. '5H'.
See https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases
for a list of frequency aliases.
If None, inferred by pd.infer_freq.
Provide this parameter if ``df`` has missing timepoints.
date_format : `str` or None, default None
strftime format to parse time column, eg ``%m/%d/%Y``.
Note that ``%f`` will parse all the way up to nanoseconds.
If None (recommended), inferred by `pandas.to_datetime`.
regressor_cols : `list` [`str`] or None, optional, default None
A list of regressor columns used in the training and prediction DataFrames.
If None, no regressor columns are used.
Regressor columns that are unavailable in ``df`` are dropped.
lagged_regressor_cols : `list` [`str`] or None, optional, default None
A list of lagged regressor columns used in the training and prediction DataFrames.
If None, no lagged regressor columns are used.
Lagged regressor columns that are unavailable in ``df`` are dropped.
train_end_date : `datetime.datetime`, optional, default None
Last date to use for fitting the model. Forecasts are generated after this date.
If None, it is set to the last date with a non-null value in
``value_col`` of ``df``.
forecast_horizon : `int` or None, default None
Number of periods to forecast into the future. Must be > 0
If None, default is determined from input data frequency
Returns
-------
time_properties : `dict` [`str`, `any`]
Time properties dictionary with keys:
``"period"`` : `int`
Period of each observation (i.e. minimum time between observations, in seconds).
``"simple_freq"`` : `SimpleTimeFrequencyEnum`
``SimpleTimeFrequencyEnum`` member corresponding to data frequency.
``"num_training_points"`` : `int`
Number of observations for training.
``"num_training_days"`` : `int`
Number of days for training.
``"days_per_observation"``: `float`
The time frequency in day units.
``"forecast_horizon"``: `int`
The number of time intervals for which forecast is needed.
``"forecast_horizon_in_timedelta"``: `datetime.timedelta`
The forecast horizon length in timedelta units.
``"forecast_horizon_in_days"``: `float`
The forecast horizon length in day units.
``"start_year"`` : `int`
Start year of the training period.
``"end_year"`` : `int`
End year of the forecast period.
``"origin_for_time_vars"`` : `float`
Continuous time representation of the first date in ``df``.
"""
if regressor_cols is None:
regressor_cols = []
# Defines ``fit_df``, the data available for fitting the model
# and its time column (in `datetime.datetime` format)
canonical_data_dict = get_canonical_data(
df=df,
time_col=time_col,
value_col=value_col,
freq=freq,
date_format=date_format,
train_end_date=train_end_date,
regressor_cols=regressor_cols,
lagged_regressor_cols=lagged_regressor_cols)
fit_df = canonical_data_dict["fit_df"]
# Calculates basic time properties
train_start = fit_df[TIME_COL].min()
start_year = int(train_start.strftime("%Y"))
origin_for_time_vars = get_default_origin_for_time_vars(fit_df, TIME_COL)
period = min_gap_in_seconds(df=fit_df, time_col=TIME_COL)
simple_freq = get_simple_time_frequency_from_period(period)
num_training_points = fit_df.shape[0]
# Calculates number of (fractional) days in the training set
time_delta = fit_df[TIME_COL].max() - train_start
num_training_days = (
time_delta.days
+ (time_delta.seconds + period) / TimeEnum.ONE_DAY_IN_SECONDS.value)
# Calculates forecast horizon (as a number of periods)
if forecast_horizon is None:
# expected to be kept in sync with default value set in ``get_default_time_parameters``
forecast_horizon = get_default_horizon_from_period(
period=period,
num_observations=num_training_points)
days_per_observation = period / TimeEnum.ONE_DAY_IN_SECONDS.value
forecast_horizon_in_days = forecast_horizon * days_per_observation
forecast_horizon_in_timedelta = timedelta(days=forecast_horizon_in_days)
# Calculates forecast end year
train_end = fit_df[TIME_COL].max()
days_to_forecast = math.ceil(forecast_horizon * days_per_observation)
future_end = train_end + timedelta(days=days_to_forecast)
end_year = int(future_end.strftime("%Y"))
return {
"period": period,
"simple_freq": simple_freq,
"num_training_points": num_training_points,
"num_training_days": num_training_days,
"days_per_observation": days_per_observation,
"forecast_horizon": forecast_horizon,
"forecast_horizon_in_timedelta": forecast_horizon_in_timedelta,
"forecast_horizon_in_days": forecast_horizon_in_days,
"start_year": start_year,
"end_year": end_year,
"origin_for_time_vars": origin_for_time_vars
}
| StarcoderdataPython |
1625002 | <filename>sample_AIs/python27.py
# posting to: http://localhost:3000/api/articles/update/:articleid with title, content
# changes title, content
#
# id1: (darwinbot1 P@ssw0rd!! 57d748bc67d0eaf026dff431) <-- this will change with differing mongo instances
import time # for testing, this is not good
import requests # if not installed already, run python -m pip install requests OR pip install requests, whatever you normally do
r = requests.post('http://localhost:80/api/games/search', data={'devkey': "581cef76756322705301183e", 'username': 'darwinbot1'}) # search for new game
json = r.json() # when request comes back, that means you've found a match! (validation if server goes down?)
print(json)
gameID = json['gameID']
playerID = json['playerID']
print(gameID)
print(playerID)
input = ' '
while input != '':
input = raw_input('input move: ')
r = requests.post('http://localhost:80/api/games/submit/' + gameID, data={'playerID': playerID, 'move': input, 'devkey': "581cef76756322705301183e"}); # submit sample move
json = r.json()
print(json) | StarcoderdataPython |
12832604 | <filename>api/File.py
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Turku University (2019) Department of Future Technologies
# Course Virtualization / Website
# Class for Course Virtualization site downloadables
#
# File.py - <NAME> <<EMAIL>>
#
# 2019-12-07 Initial version.
# 2019-12-28 Add prepublish(), JSONFormSchema()
# 2019-12-28 Add publish()
# 2020-08-30 Fix owner check in update()
# 2020-09-23 Add decode_bytemultiple()
#
#
# TODO: remove _* -columns from result sets.
#
import os
import json
import time
import logging
import sqlite3
import flask
from flask import g
from application import app
from .Exception import *
from .DataObject import DataObject
from .OVFData import OVFData
from .Teacher import Teacher
# Pylint doesn't understand app.logger ...so we disable all these warnings
# pylint: disable=maybe-no-member
# Extends api.DataObject
class File(DataObject):
class DefaultDict(dict):
"""Returns for missing key, value for key '*' is returned or raises KeyError if default has not been set."""
def __missing__(self, key):
if key == '*':
raise KeyError("Key not found and default ('*') not set!")
else:
return self['*']
# Translate file.downloadable_to <-> sso.role ACL
# (who can access if file.downloadable_to says...)
# Default value '*' is downloadable to noone.
_downloadable_to2acl = DefaultDict({
'teacher': ['teacher'],
'student': ['student', 'teacher'],
'anyone': ['anonymous', 'student', 'teacher'],
'*': []
})
# Translate current sso.role into a list of file.downloadable_to -values
# (what can I access with my role...)
_role2acl = DefaultDict({
'teacher': ['anyone', 'student', 'teacher'],
'student': ['anyone', 'student'],
'*': ['anyone']
})
# Columns that must not be updated (by client)
_readOnly = ['id', 'name', 'size', 'sha1', 'created']
def __init__(self):
self.cursor = g.db.cursor()
# Init super for table name 'file'
super().__init__(self.cursor, 'file')
def schema(self):
"""Return file -table database schema in JSON.
Possible responses:
500 InternalError - Other processing error
200 OK"""
try:
# Do not send owner data to client
schema = super().schema(['owner'])
# Set readonly columns
for col, attribute in schema.items():
if col in self._readOnly:
attribute['readonly'] = True
except Exception as e:
app.logger.exception("error creating JSON")
raise InternalError(
"schema() error while generating schema JSON", str(e)
) from None
#
# Return schema
#
return (200, {"schema": schema})
def search(
self,
file_type: str = None,
downloadable_to: str = None,
owner: str = None
):
"""Argument 'file_type' as per column file.type, 'role' as column file.downloadable_to, 'owner' as per column file.owner."""
app.logger.debug(
f"search(type='{file_type}', downloadable_to='{downloadable_to}', owner='{owner}')"
)
self.sql = f"SELECT * FROM {self.table_name}"
where = [] # SQL WHERE conditions and bind symbols ('?')
bvars = [] # list of bind variables to match the above
if file_type is not None:
where.append("type = ?")
bvars.append(file_type)
if downloadable_to is not None:
acl = self._role2acl[downloadable_to]
where.append(
f"downloadable_to IN ({','.join(['?'] * len(acl))})"
)
bvars.extend(acl)
if owner is not None:
where.append("owner = ?")
bvars.append(owner)
#
# Create WHERE clause
#
if where:
self.sql += " WHERE " + " AND ".join(where)
app.logger.debug("SQL: " + self.sql)
try:
self.cursor.execute(self.sql, bvars)
except sqlite3.Error as e:
app.logger.exception(
f"'{self.table_name}' -table query failed! ({self.sql})"
)
raise
else:
cursor = self.cursor
data = [dict(zip([key[0] for key in cursor.description], row)) for row in cursor]
finally:
self.cursor.close()
if app.config.get("DEBUG", False):
return (
200,
{
"data" : data,
"query" : {
"sql" : self.sql,
"variables" : bvars
}
}
)
else:
return (200, {"data": data})
def prepublish(self, filepath, owner) -> tuple:
"""Arguments 'filepath' must be an absolute path to the VM image and 'owner' must be an /active/ UID in the 'teacher' table.
Extract information from the file and prepopulate 'file' table row. On success, returns the 'file' table ID value.
Returns:
(200, "{ 'id': <file.id> }")
Exceptions:
404, "Not Found" NotFound()
406, "Not Acceptable" InvalidArgument()
409, "Conflict" Conflict()
500, "Internal Server Error") InternalError()
"""
self.filepath = filepath
self.filedir, self.filename = os.path.split(self.filepath)
_, self.filesuffix = os.path.splitext(self.filename)
# Specified file must exist
if not File.exists(self.filepath):
raise NotFound(f"File '{self.filepath}' does not exist!")
# Check that the teacher is active
if not Teacher(owner).active:
raise InvalidArgument(f"Teacher '{owner}' is not active!")
app.logger.debug("File and owner checks completed!")
# Build a dictionary where keys match 'file' -table column names
# Populate with values either from .OVA or other
#
try:
if self.filesuffix == '.ova':
attributes = File.__ova_attributes(self.filepath)
else:
attributes = File.__img_attributes(self.filepath)
# Cannot be inserted without owner
attributes['owner'] = owner
# File size in bytes
attributes['size'] = os.stat(self.filepath).st_size
except Exception as e:
app.logger.exception("Unexpected error reading file attributes!")
raise InternalError(
"prepublish() error while reading file attributes", str(e)
) from None
app.logger.debug("OVA/IMG attribute collection successful!")
#
# Data collected, insert a row
#
try:
self.sql = f"INSERT INTO file ({','.join(attributes.keys())}) "
self.sql += f"VALUES (:{',:'.join(attributes.keys())})"
self.cursor.execute(self.sql, attributes)
# Get AUTOINCREMENT PK
file_id = self.cursor.lastrowid
self.cursor.connection.commit()
except sqlite3.IntegrityError as e:
self.cursor.connection.rollback()
app.logger.exception("sqlite3.IntegrityError" + self.sql + str(e))
raise Conflict("SQLite3 integrity error", str(e)) from None
except Exception as e:
self.cursor.connection.rollback()
app.logger.exception("Unexpected error while inserting 'file' row!" + str(e))
raise InternalError(
"prepublish() error while inserting", str(e)
) from None
#
# Return with ID
#
if app.config.get("DEBUG", False):
return (
200,
{
"id" : file_id,
"query" : {
"sql" : self.sql,
"variables" : attributes
}
}
)
else:
return (200, {"id": file_id})
# TODO ####################################################################
def publish(self, file_id: int) -> tuple:
"""Moves a file from upload folder to download folder and makes it accessible/downloadable."""
return (200, { "data": "OK" })
# TODO!! ##################################################################
def create(self, request) -> tuple:
"""POST method handler - INSERT new row."""
if not request.json:
raise InvalidArgument("API Request has no JSON payload!")
try:
# Get JSON data as dictionary
data = json.loads(request.json)
except Exception as e:
app.logger.exception("Error getting JSON data")
raise InvalidArgument(
"Argument parsing error",
{'request.json' : request.json, 'exception' : str(e)}
) from None
try:
self.sql = f"INSERT INTO {self.table_name} "
self.sql += f"({','.join(data.keys())}) "
self.sql += f"VALUES (:{',:'.join(data.keys())})"
except Exception as e:
app.logger.exception("Error parsing SQL")
raise InternalError(
"Error parsing SQL",
{'sql': self.sql or '', 'exception' : str(e)}
)
# TO BE COMPLETED!!!! #################################################
def fetch(self, id):
"""Retrieve and return a table row. There are no restrictions for retrieving and viewing file data (but update() and create() methods do require a role)."""
self.sql = f"SELECT * FROM {self.table_name} WHERE id = ?"
try:
# ? bind vars want a list argument
self.cursor.execute(self.sql, [id])
except sqlite3.Error as e:
app.logger.exception(
"psu -table query failed! ({})".format(self.sql)
)
raise
else:
# list of tuples
result = self.cursor.fetchall()
if len(result) < 1:
raise NotFound(
f"File (ID: {id}) not found!",
{ 'sql': self.sql }
)
# Create data dictionary from result
data = dict(zip([c[0] for c in self.cursor.description], result[0]))
finally:
self.cursor.close()
if app.config.get("DEBUG", False):
return (
200,
{
"data" : data,
"query" : {
"sql" : self.sql,
"variables" : {'id': id}
}
}
)
else:
return (200, {"data": data})
def update(self, id, request, owner):
# 2nd argument must be the URI Parameter /api/file/<int:id>.
# Second copy is expected to be found within the request data
# and it has to match with the URI parameter.
"""
PATCH method routine - UPDATE record
Possible results:
404 Not Found raise NotFound()
406 Not Acceptable raise InvalidArgument()
200 OK
{
'id' : <int>
}
"""
app.logger.debug("this.primarykeys: " + str(self.primarykeys))
app.logger.debug("fnc arg id: " + str(id))
if not request.json:
raise InvalidArgument("API Request has no JSON payload!")
else:
data = request.json # json.loads(request.json)
# This is horrible solution - client code should take care of this!
data['id'] = int(data['id'])
app.logger.debug(data)
# Extract POST data into dict
try:
#
# Primary key checking
#
if not data[self.primarykeys[0]]:
raise ValueError(
f"Primary key '{self.primarykeys[0]}' not in dataset!"
)
if not id:
raise ValueError(
f"Primary key value for '{self.primarykeys[0]}' cannot be None!"
)
if data[self.primarykeys[0]] != id:
raise ValueError(
"Primary key '{self.primarykeys[0]}' values do not match! One provided as URI parameter, one included in the data set."
)
#
# Check ownership
#
result = self.cursor.execute(
"SELECT owner FROM file WHERE id = ?",
[id]
).fetchall()
if len(result) != 1:
raise ValueError(
f"File (id: {id}) does not exist!"
)
else:
if result[0][0] != owner:
raise ValueError(
f"User '{owner}' not the owner of file {id}, user '{result[0][0]}' is!"
)
except Exception as e:
app.logger.exception("Prerequisite failure!")
raise InvalidArgument(
"Argument parsing error",
{'request.json' : request.json, 'exception' : str(e)}
) from None
app.logger.debug("Prerequisites OK!")
#
# Handle byte-size variables ('disksize' and 'ram')
# "2 GB" (etc) -> 2147483648 and so on... except when the string makes
# no sense. Then it is used as-is instad.
#
if "ram" in data:
data['ram'] = File.decode_bytemultiple(data['ram'])
if "disksize" in data:
data['disksize'] = File.decode_bytemultiple(data['disksize'])
#
# Generate SQL
#
try:
# columns list, without primary key(s)
cols = [ c for c in data.keys() if c not in self.primarykeys ]
# Remove read-only columns, in case someone injected them
cols = [ c for c in cols if c not in self._readOnly ]
app.logger.debug(f"Columns: {','.join(cols)}")
self.sql = f"UPDATE {self.table_name} SET "
self.sql += ",".join([ c + ' = :' + c for c in cols ])
self.sql += " WHERE "
self.sql += " AND ".join([k + ' = :' + k for k in self.primarykeys])
except Exception as e:
raise InternalError(
"SQL parsing error",
{'sql' : self.sql or '', 'exception' : str(e)}
) from None
app.logger.debug("SQL: " + self.sql)
#
# Execute Statement
#
try:
self.cursor.execute(self.sql, data)
#
# Number of updated rows must be one
#
if self.cursor.rowcount != 1:
nrows = self.cursor.rowcount
g.db.rollback()
if nrows > 1:
raise InternalError(
"Error! Update affected more than one row!",
{'sql': self.sql or '', 'data': data}
)
else:
raise NotFound(
"Entity not found - nothing was updated!",
{'sql': self.sql or '', 'data': data}
)
except sqlite3.Error as e:
# TODO: Check what actually caused the issue
raise InvalidArgument(
"UPDATE failed!",
{'sql': self.sql or '', 'exception': str(e)}
) from None
finally:
g.db.commit()
self.cursor.close()
# Return id
return (200, {'data': {'id' : id}})
def delete(self, vm_id, user_id):
"""Delete file with the given id.
Checks that:
- file exists
- user is the owner of the file
(TODO) users with admin rights should be able to delete others' files
Possible return values:
200: OK (Delete query sent)
403: User is not allowed to delete the file
404: Specified file does not exist
404: Database record not found
500: An exception ocurred (and was logged)"""
#
# Check that the file exists and get filename
#
self.sql = "SELECT name FROM file WHERE id = ?"
try:
result = self.cursor.execute(self.sql,[vm_id]).fetchall()
if len(result) != 1:
app.logger.debug(f"VM with id '{vm_id}' not found")
return (404, { "data": "Not found" })
filename = result[0][0]
app.logger.debug("fetched: " + filename)
folder = app.config.get("DOWNLOAD_FOLDER")
filepath = os.path.join(folder, filename)
if not File.exists(filepath):
app.logger.error(
f"File '{filepath}' does not exist!"
)
return (404, {"data": "File not found"})
except Exception as e:
app.logger.exception(
f"Exception while checking if '{filepath}' exists!"
)
return (500, {"data": "Internal Server Error"})
#
# Check ownership
#
self.sql = "SELECT owner FROM file WHERE id = ?"
try:
result = self.cursor.execute(self.sql, [vm_id]).fetchall()
if len(result) != 1:
app.logger.debug(f"VM with id '{vm_id}' not found")
return (404, { "data": "Not found" })
owner = result[0][0]
app.logger.debug("fetched: " + owner)
if owner != user_id:
app.logger.debug(
f"User '{user_id}' tried to delete '{filename}', owner: '{owner}' (denied)"
)
return (403, { "data": "Forbidden" })
except Exception as e:
app.logger.exception(
f"Exception while checking file '{vm_id}' ownership!"
)
return (500, {"data": "Internal Server Error"})
#
# If all checks have been passed, delete database row and file
#
self.sql = "DELETE FROM file WHERE id = ?"
try:
self.cursor.execute(self.sql, [vm_id])
self.cursor.connection.commit()
# Check that the row has been deleted before deleting file
self.sql = "SELECT name FROM file WHERE id = ?"
result = self.cursor.execute(self.sql,[vm_id]).fetchall()
if len(result) != 0:
app.logger.exception(
f"Exception while trying to delete '{filepath}'"
)
return (500, {"data": "Internal Server Error"})
else:
os.remove(filepath)
except Exception as e:
app.logger.exception(
f"Exception while trying to delete '{filepath}'"
)
return (500, {"data": "Internal Server Error"})
app.logger.debug(f"File '{vm_id}' deleted")
return (200, { "data": "OK" })
def download(self, filename: str, role: str) -> tuple:
"""Checks that the file exists, has a database record and can be downloaded by the specified role.
Possible return values:
200: OK (Download started by Nginx/X-Accel-Redirect)
401: Role not allowed to download the file
404: Specified file does not exist
404: Database record not found
500: An exception ocurred (and was logged)"""
#
# Check that the file exists
#
try:
folder = app.config.get("DOWNLOAD_FOLDER")
filepath = os.path.join(folder, filename)
if not File.exists(filepath):
app.logger.error(
f"File '{filepath}' does not exist!"
)
return "File not found", 404
except Exception as e:
app.logger.exception(
f"Exception while checking if '{filepath}' exists!"
)
return "Internal Server Error", 500
#
# Retrieve information on to whom is it downloadable to
#
self.sql = "SELECT downloadable_to FROM file WHERE name = ?"
try:
self.cursor.execute(self.sql, [filename])
# list of tuples
result = self.cursor.fetchone()
if len(result) < 1:
app.logger.error(
f"No database record for existing file '{filepath}'"
)
return "File Not Found", 404
except Exception as e:
# All other exceptions
app.logger.exception("Error executing a query!")
return "Internal Server Error", 500
#
# Send file
#
# 'X-Accel-Redirect' (header directive) is Nginx feature that is
# intercepted by Nginx and the pointed to by that directive is
# then streamed to the client, freeing Flask thread next request.
#
# More important is the fact that this header allows serving files
# that are not in the request pointed location (URL), letting the
# application code verify access privileges and/or change the
# content (specify a different file in X-Accel-Redirect).
#
try:
# Filepath for X-Accel-Redirect
abs_url_path = os.path.join(
app.config.get("DOWNLOAD_URLPATH"),
filename
)
allowlist = self._downloadable_to2acl[result[0]]
if role in allowlist:
response = flask.Response("")
response.headers['Content-Type'] = ""
response.headers['X-Accel-Redirect'] = abs_url_path
app.logger.debug(
f"Returning response with header X-Accel-Redirect = {response.headers['X-Accel-Redirect']}"
)
return response
else:
app.logger.info(
f"User with role '{role}' attempted to download '{filepath}' that is downloadable to '{allowlist}' (file.downloadable_to: '{result[0]}') (DENIED!)"
)
return "Unauthorized!", 401
except Exception as e:
app.logger.exception(
f"Exception while permission checking role '{role}' (downloadable_to:) '{result[0]}' and/or sending download"
)
return "Internal Server Error", 500
@staticmethod
def decode_bytemultiple(value: str):
mult = {
"KB" : 1024,
"MB" : 1048576,
"GB" : 1073741824,
"TB" : 1099511627776,
"PB" : 2214416418340864
}
try:
# Assume bytes first
return int(value, 10)
except:
for k, v in mult.items():
if value.strip().upper().endswith(k):
try:
return int(float(value[:-2].replace(',', '.')) * v)
#return int(value[:-2], 10) * v
except:
app.logger.debug(f"Unable to convert '{value}'")
return value
# multiple not found, return as-is
return value
@staticmethod
def exists(file: str) -> bool:
"""Accepts path/file or file and tests if it exists (as a file)."""
if os.path.exists(file):
if os.path.isfile(file):
return True
return False
@staticmethod
def __ova_attributes(file: str) -> dict:
# Establish defaults
filedir, filename = os.path.split(file)
attributes = {
'name': filename,
'label': filename,
'size': 0,
'type': 'vm'
}
#
# Extract XML from .OVF -file from inside the .OVA tar-archive
# into variable 'xmlstring'
#
try:
import tarfile
# Extract .OVF - exactly one should exist
with tarfile.open(file, "r") as ova:
for tarinfo in ova.getmembers():
if os.path.splitext(tarinfo.name)[1].lower() == '.ovf':
ovf = tarinfo
break
if not ovf:
raise ValueError(".OVF file not found!!")
xmlstring = ova.extractfile(ovf).read().decode("utf-8")
except Exception as e:
app.logger.exception(f"Error extracting .OVF from '{filename}'")
return attributes
#
# Read OVF XML
#
try:
ovfdata = OVFData(xmlstring, app.logger)
if ovfdata.cpus:
attributes['cores'] = ovfdata.cpus
if ovfdata.ram:
attributes['ram'] = ovfdata.ram
if ovfdata.name:
attributes['label'] = ovfdata.name
if ovfdata.description:
attributes['description'] = ovfdata.description
if ovfdata.disksize:
attributes['disksize'] = ovfdata.disksize
if ovfdata.ostype:
attributes['ostype'] = ovfdata.ostype
except Exception as e:
app.logger.exception("Error reading OVF XML!")
return attributes
@staticmethod
def __img_attributes(file: str) -> dict:
# Images and .ZIP archives (for pendrives)
filedir, filename = os.path.split(file)
# Establish defaults
attributes = {
'name': filename,
'label': filename,
'size': 0,
'type': 'vm'
}
return attributes
# EOF | StarcoderdataPython |
3396099 | #!/usr/bin/env python
# coding: utf-8
# # [Mempersiapkan Library](https://academy.dqlab.id/main/livecode/293/560/2797)
# In[2]:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from kmodes.kmodes import KModes
from kmodes.kprototypes import KPrototypes
import pickle
from pathlib import Path
# # [Membaca Data Pelanggan](https://academy.dqlab.id/main/livecode/293/560/2798)
# In[3]:
# import dataset
df = pd.read_csv ("https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/customer_segments.txt", sep="\t")
# menampilkan data
print(df.head())
# # [Melihat Informasi dari Data](https://academy.dqlab.id/main/livecode/293/560/2799)
# In[4]:
# Menampilkan informasi data
df.info()
# # [Eksplorasi Data Numerik](https://academy.dqlab.id/main/livecode/293/561/2803)
# In[5]:
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white')
plt.clf()
# Fungsi untuk membuat plot
def observasi_num(features):
fig, axs = plt.subplots(2, 2, figsize=(10, 9))
for i, kol in enumerate(features):
sns.boxplot(df[kol], ax = axs[i][0])
sns.distplot(df[kol], ax = axs[i][1])
axs[i][0].set_title('mean = %.2f\n median = %.2f\n std = %.2f'%(df[kol].mean(), df[kol].median(), df[kol].std()))
plt.setp(axs)
plt.tight_layout()
plt.show()
# Memanggil fungsi untuk membuat Plot untuk data numerik
kolom_numerik = ['Umur','NilaiBelanjaSetahun']
observasi_num(kolom_numerik)
# # [Eksplorasi Data Kategorikal](https://academy.dqlab.id/main/livecode/293/561/2804)
# In[7]:
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white')
plt.clf()
# Menyiapkan kolom kategorikal
kolom_kategorikal = ['Jenis Kelamin','Profesi','Tipe Residen']
# Membuat canvas
fig, axs = plt.subplots(3,1,figsize=(7,10))
# Membuat plot untuk setiap kolom kategorikal
for i, kol in enumerate(kolom_kategorikal):
# Membuat Plot
sns.countplot(df[kol], order = df[kol].value_counts().index, ax = axs[i])
axs[i].set_title('\nCount Plot %s\n'%(kol), fontsize=15)
# Memberikan anotasi
for p in axs[i].patches:
axs[i].annotate(format(p.get_height(), '.0f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center',
va = 'center',
xytext = (0, 10),
textcoords = 'offset points')
# Setting Plot
sns.despine(right=True,top = True, left = True)
axs[i].axes.yaxis.set_visible(False)
plt.setp(axs)
plt.tight_layout()
# Tampilkan plot
plt.show()
# # [Standarisasi Kolom Numerik](https://academy.dqlab.id/main/livecode/293/562/2808)
# In[8]:
from sklearn.preprocessing import StandardScaler
kolom_numerik = ['Umur','NilaiBelanjaSetahun']
# Statistik sebelum Standardisasi
print('Statistik Sebelum Standardisasi\n')
print(df[kolom_numerik ].describe().round(1))
# Standardisasi
df_std = StandardScaler().fit_transform(df[kolom_numerik])
# Membuat DataFrame
df_std = pd.DataFrame(data=df_std, index=df.index, columns=df[kolom_numerik].columns)
# Menampilkan contoh isi data dan summary statistic
print('Contoh hasil standardisasi\n')
print(df_std.head())
print('Statistik hasil standardisasi\n')
print(df_std.describe().round(0))
# # [Konversi Kategorikal Data dengan Label Encoder](https://academy.dqlab.id/main/livecode/293/562/2809)
# In[10]:
from sklearn.preprocessing import LabelEncoder
# Inisiasi nama kolom kategorikal
kolom_kategorikal = ['Jenis Kelamin','Profesi','Tipe Residen']
# Membuat salinan data frame
df_encode = df[kolom_kategorikal].copy()
# Melakukan labelEncoder untuk semua kolom kategorikal
for col in kolom_kategorikal:
df_encode[col] = LabelEncoder().fit_transform(df_encode[col])
# Menampilkan data
print(df_encode.head())
# # [Menggabungkan Data untuk Permodelan](https://academy.dqlab.id/main/livecode/293/562/2810)
# In[11]:
# Menggabungkan data frame
df_model = df_encode.merge(df_std, left_index = True, right_index=True, how = 'left')
print(df_model.head())
| StarcoderdataPython |
4945406 | <reponame>karansthr/apistar
import re
from urllib.parse import urljoin
from apistar import validators
from apistar.compat import dict_type
from apistar.document import Document, Field, Link, Section
from apistar.schemas.jsonschema import JSON_SCHEMA, JSONSchema
SCHEMA_REF = validators.Object(
properties={'$ref': validators.String(pattern='^#/definitiions/')}
)
RESPONSE_REF = validators.Object(
properties={'$ref': validators.String(pattern='^#/responses/')}
)
SWAGGER = validators.Object(
def_name='Swagger',
title='Swagger',
properties=[
('swagger', validators.String()),
('info', validators.Ref('Info')),
('paths', validators.Ref('Paths')),
('host', validators.String()),
('basePath', validators.String()),
('schemes', validators.Array(items=validators.String())),
('consumes', validators.Array(items=validators.String())),
('produces', validators.Array(items=validators.String())),
('definitions', validators.Object(additional_properties=validators.Any())),
('parameters', validators.Object(additional_properties=validators.Ref('Parameters'))),
('responses', validators.Object(additional_properties=validators.Ref('Responses'))),
('securityDefinitions', validators.Object(additional_properties=validators.Ref('SecurityScheme'))),
('security', validators.Array(items=validators.Ref('SecurityRequirement'))),
('tags', validators.Array(items=validators.Ref('Tag'))),
('externalDocs', validators.Ref('ExternalDocumentation')),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
required=['swagger', 'info', 'paths'],
definitions={
'Info': validators.Object(
properties=[
('title', validators.String()),
('description', validators.String(format='textarea')),
('termsOfService', validators.String(format='url')),
('contact', validators.Ref('Contact')),
('license', validators.Ref('License')),
('version', validators.String()),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
required=['title', 'version']
),
'Contact': validators.Object(
properties=[
('name', validators.String()),
('url', validators.String(format='url')),
('email', validators.String(format='email')),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
),
'License': validators.Object(
properties=[
('name', validators.String()),
('url', validators.String(format='url')),
],
required=['name'],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
),
'Paths': validators.Object(
pattern_properties=[
('^/', validators.Ref('Path')),
('^x-', validators.Any()),
],
additional_properties=False,
),
'Path': validators.Object(
properties=[
('summary', validators.String()),
('description', validators.String(format='textarea')),
('get', validators.Ref('Operation')),
('put', validators.Ref('Operation')),
('post', validators.Ref('Operation')),
('delete', validators.Ref('Operation')),
('options', validators.Ref('Operation')),
('head', validators.Ref('Operation')),
('patch', validators.Ref('Operation')),
('trace', validators.Ref('Operation')),
('parameters', validators.Array(items=validators.Ref('Parameter'))), # TODO: | ReferenceObject
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
),
'Operation': validators.Object(
properties=[
('tags', validators.Array(items=validators.String())),
('summary', validators.String()),
('description', validators.String(format='textarea')),
('externalDocs', validators.Ref('ExternalDocumentation')),
('operationId', validators.String()),
('consumes', validators.Array(items=validators.String())),
('produces', validators.Array(items=validators.String())),
('parameters', validators.Array(items=validators.Ref('Parameter'))), # TODO: | ReferenceObject
('responses', validators.Ref('Responses')),
('schemes', validators.Array(items=validators.String())),
('deprecated', validators.Boolean()),
('security', validators.Array(validators.Ref('SecurityRequirement'))),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
),
'ExternalDocumentation': validators.Object(
properties=[
('description', validators.String(format='textarea')),
('url', validators.String(format='url')),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
required=['url']
),
'Parameter': validators.Object(
properties=[
('name', validators.String()),
('in', validators.String(enum=['query', 'header', 'path', 'formData', 'body'])),
('description', validators.String(format='textarea')),
('required', validators.Boolean()),
# in: "body"
('schema', JSON_SCHEMA | SCHEMA_REF),
# in: "query"|"header"|"path"|"formData"
('type', validators.String()),
('format', validators.String()),
('allowEmptyValue', validators.Boolean()),
('items', JSON_SCHEMA), # TODO: Should actually be a restricted subset
('collectionFormat', validators.String(enum=['csv', 'ssv', 'tsv', 'pipes', 'multi'])),
('default', validators.Any()),
('maximum', validators.Number()),
('exclusiveMaximum', validators.Boolean()),
('minimum', validators.Number()),
('exclusiveMinimum', validators.Boolean()),
('maxLength', validators.Integer()),
('minLength', validators.Integer()),
('pattern', validators.String()),
('maxItems', validators.Integer()),
('minItems', validators.Integer()),
('uniqueItems', validators.Boolean()),
('enum', validators.Array(items=validators.Any())),
('multipleOf', validators.Integer()),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
required=['name', 'in']
),
'RequestBody': validators.Object(
properties=[
('description', validators.String()),
('content', validators.Object(additional_properties=validators.Ref('MediaType'))),
('required', validators.Boolean()),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
),
'Responses': validators.Object(
properties=[
('default', validators.Ref('Response') | RESPONSE_REF),
],
pattern_properties=[
('^([1-5][0-9][0-9]|[1-5]XX)$', validators.Ref('Response') | RESPONSE_REF),
('^x-', validators.Any()),
],
additional_properties=False,
),
'Response': validators.Object(
properties=[
('description', validators.String()),
('content', validators.Object(additional_properties=validators.Ref('MediaType'))),
('headers', validators.Object(additional_properties=validators.Ref('Header'))),
# TODO: Header | ReferenceObject
# TODO: links
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
),
'MediaType': validators.Object(
properties=[
('schema', JSON_SCHEMA | SCHEMA_REF),
('example', validators.Any()),
# TODO 'examples', 'encoding'
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
),
'Header': validators.Object(
properties=[
('description', validators.String(format='textarea')),
('required', validators.Boolean()),
('deprecated', validators.Boolean()),
('allowEmptyValue', validators.Boolean()),
('style', validators.String()),
('schema', JSON_SCHEMA | SCHEMA_REF),
('example', validators.Any()),
# TODO: Other fields
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False
),
'Tag': validators.Object(
properties=[
('name', validators.String()),
('description', validators.String(format='textarea')),
('externalDocs', validators.Ref('ExternalDocumentation')),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
required=['name']
),
'SecurityRequirement': validators.Object(
additional_properties=validators.Array(items=validators.String()),
),
'SecurityScheme': validators.Object(
properties=[
('type', validators.String(enum=['basic', 'apiKey', 'oauth2'])),
('description', validators.String(format='textarea')),
('name', validators.String()),
('in', validators.String(enum=['query', 'header'])),
('flow', validators.String(enum=['implicit', 'password', 'application', 'accessCode'])),
('authorizationUrl', validators.String(format="url")),
('tokenUrl', validators.String(format="url")),
('scopes', validators.Ref('Scopes')),
],
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=False,
required=['type']
),
'Scopes': validators.Object(
pattern_properties={
'^x-': validators.Any(),
},
additional_properties=validators.String(),
)
}
)
METHODS = [
'get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'
]
def lookup(value, keys, default=None):
for key in keys:
try:
value = value[key]
except (KeyError, IndexError, TypeError):
return default
return value
def _simple_slugify(text):
if text is None:
return None
text = text.lower()
text = re.sub(r'[^a-z0-9]+', '_', text)
text = re.sub(r'[_]+', '_', text)
return text.strip('_')
class Swagger:
def load(self, data):
title = lookup(data, ['info', 'title'])
description = lookup(data, ['info', 'description'])
version = lookup(data, ['info', 'version'])
host = lookup(data, ['host'])
path = lookup(data, ['basePath'], '/')
scheme = lookup(data, ['schemes', 0], 'https')
base_url = None
if host:
base_url = '%s://%s%s' % (scheme, host, path)
schema_definitions = self.get_schema_definitions(data)
content = self.get_content(data, base_url, schema_definitions)
return Document(title=title, description=description, version=version, url=base_url, content=content)
def get_schema_definitions(self, data):
definitions = {}
schemas = lookup(data, ['components', 'schemas'], {})
for key, value in schemas.items():
definitions[key] = JSONSchema().decode_from_data_structure(value)
definitions[key].def_name = key
return definitions
def get_content(self, data, base_url, schema_definitions):
"""
Return all the links in the document, layed out by tag and operationId.
"""
links_by_tag = dict_type()
links = []
for path, path_info in data.get('paths', {}).items():
operations = {
key: path_info[key] for key in path_info
if key in METHODS
}
for operation, operation_info in operations.items():
tag = lookup(operation_info, ['tags', 0])
link = self.get_link(base_url, path, path_info, operation, operation_info, schema_definitions)
if link is None:
continue
if tag is None:
links.append(link)
elif tag not in links_by_tag:
links_by_tag[tag] = [link]
else:
links_by_tag[tag].append(link)
sections = [
Section(name=_simple_slugify(tag), title=tag.title(), content=links)
for tag, links in links_by_tag.items()
]
return links + sections
def get_link(self, base_url, path, path_info, operation, operation_info, schema_definitions):
"""
Return a single link in the document.
"""
name = operation_info.get('operationId')
title = operation_info.get('summary')
description = operation_info.get('description')
if name is None:
name = _simple_slugify(title)
if not name:
return None
# Parameters are taken both from the path info, and from the operation.
parameters = path_info.get('parameters', [])
parameters += operation_info.get('parameters', [])
fields = [
self.get_field(parameter, schema_definitions)
for parameter in parameters
]
default_encoding = None
if any([field.location == 'body' for field in fields]):
default_encoding = 'application/json'
elif any([field.location == 'formData' for field in fields]):
default_encoding = 'application/x-www-form-urlencoded'
form_fields = [field for field in fields if field.location == 'formData']
body_field = Field(
name='body',
location='body',
schema=validators.Object(
properties={
field.name: validators.Any() if field.schema is None else field.schema
for field in form_fields
},
required=[field.name for field in form_fields if field.required]
)
)
fields = [field for field in fields if field.location != 'formData']
fields.append(body_field)
encoding = lookup(operation_info, ['consumes', 0], default_encoding)
return Link(
name=name,
url=urljoin(base_url, path),
method=operation,
title=title,
description=description,
fields=fields,
encoding=encoding
)
def get_field(self, parameter, schema_definitions):
"""
Return a single field in a link.
"""
name = parameter.get('name')
location = parameter.get('in')
description = parameter.get('description')
required = parameter.get('required', False)
schema = parameter.get('schema')
example = parameter.get('example')
if schema is not None:
if '$ref' in schema:
ref = schema['$ref'][len('#/definitions/'):]
schema = schema_definitions.get(ref)
else:
schema = JSONSchema().decode_from_data_structure(schema)
return Field(
name=name,
location=location,
description=description,
required=required,
schema=schema,
example=example
)
| StarcoderdataPython |
6484093 | <filename>authserver/config/__init__.py
from authserver.config.config import AbstractConfiguration, ConfigurationFactory, ConfigurationEnvironmentNotFoundError
| StarcoderdataPython |
8058477 | import os
from zygoat.constants import Projects
from zygoat.components import FileComponent
from . import resources
class Configuration(FileComponent):
filename = "cypress.json"
resource_pkg = resources
base_path = os.path.join(Projects.FRONTEND)
configuration = Configuration()
| StarcoderdataPython |
6549382 | #Python modules
###wrapper for subprocess command
def runsubprocess(args,verbose=False,shell=False,polling=False,printstdout=True,preexec_fn=None):
"""takes a subprocess argument list and runs Popen/communicate or Popen/poll() (if polling=True); if verbose=True, processname (string giving command call) is printed to screen (processname is always printed if a process results in error); errors are handled at multiple levels i.e. subthread error handling; fuction can be used fruitfully (returns stdout)"""
#function setup
import subprocess,sys,signal
try:
import thread
except:
import _thread
def subprocess_setup(): #see: https://github.com/vsbuffalo/devnotes/wiki/Python-and-SIGPIPE
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
if preexec_fn=='sigpipefix':
preexec_fn=subprocess_setup
else:
assert preexec_fn==None,'Error: unrecognised preexec_fn argument %s'%preexec_fn
if shell==True:
processname=args[0]
processname=processname[0].split()
processname=(" ".join(a for a in processname))
else:
processname=(" ".join(a for a in args))
#
if verbose==True:
print('{0} {1}'.format(processname, 'processname'))
try:
if polling==True:
p=subprocess.Popen(args, stdout=subprocess.PIPE,shell=shell,preexec_fn=preexec_fn)
while True:
stdout=p.stdout.readline()
if p.poll() is not None:
break
if stdout: #if stdout not empty...
if printstdout==True:
print('{0}'.format(stdout.decode().strip()))
else:
p=subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=shell,preexec_fn=preexec_fn)
stdout, stderr= p.communicate()
if stdout:
if printstdout==True:
print('{0}'.format(stdout.decode()))
if stderr:
try: #want to output to stderr stream
if (sys.version_info > (3, 0)):
print('{0}'.format(stderr.decode()),file=sys.stderr) #Python3
else:
print>>sys.stderr,stderr #Python2
except: #if above code block fails for some reason, print stderr (to stdout)
print('{0}'.format(stderr.decode()))
if p.returncode==0:
if verbose==True:
print('{0} {1}'.format(processname, 'code has run successfully'))
else:
sys.exit() #triggers except below
except:
print('{0} {1}'.format(processname, '#this pipeline step produced error'))
print('unexpected error; exiting')
sys.exit()
if p.returncode!=0:
print('unexpected error; exiting')
try:
thread.interrupt_main()
except:
_thread.interrupt_main()
else:
if stdout:
return stdout.decode().strip()
###wrapper for splitting input fasta by sample
def splitfastas(infile,fastadir,filepathinfo,seqlengthfile):
"""takes input fastafile from filepath or sys.stdin; splits by sample and writes to outdir; also writes filepathinfo.tsv to record sample, fastafilepath, and blastdbfilepath"""
from Bio import SeqIO
import re,os
from pythonmods import runsubprocess
#first create splitfasta output directory
runsubprocess(['mkdir -p %s'%fastadir],shell=True)
#parse fasta and store in recorddict
recorddict={}
for recordid,recordseq in SeqIO.FastaIO.SimpleFastaParser(infile):
#remove description from fasta id if present
newfastaheader=re.sub(r'(\S+)(?: .*)?',r'\1',recordid)
newfastaheader=newfastaheader.strip()
recordid=newfastaheader
#get sample name (fasta header format should be sample or sample|contig)
sample=re.match(r'^([^\|]*).*',newfastaheader)
sample=sample.group(1)
#write to dict
if sample not in recorddict:
recorddict[sample]=[]
recorddict[sample].append((recordid,recordseq))
infile.close()
#write records to splitfastas directory, split by sample; write seqlengths to seqlengths.tsv
f2=open(filepathinfo,'w')
f3=open(seqlengthfile,'w')
samples=set()
for sample in recorddict.keys():
samples.add(sample)
fastafilepath='%s/%s.fasta'%(fastadir,sample)
blastdbfilepath=os.path.splitext(fastafilepath)[0]
blastdbfilepath='%s_db'%blastdbfilepath
f2.write('%s\t%s\t%s\n'%(sample,fastafilepath,blastdbfilepath))
with open(fastafilepath,'w') as output_handle:
for recordid,recordseq in recorddict[sample]:
f3.write('%s\t%s\n'%(recordid,len(recordseq)))
output_handle.write(">%s\n%s\n" % (recordid, recordseq))
f2.close()
f3.close()
assert len(samples)>0,'Error: no records detected from fasta file provided'
###wrappers for blast commands
def makeBLASTdb(fastafile, databasename, dbtype, parse_seqids=False): #dbtype can be 'nucl' or 'prot'
"""takes fastafile filepath, databasename filepath and dbtype args"""
import subprocess
if parse_seqids==False:
cmdArgs=['makeblastdb', '-dbtype', dbtype, '-in', fastafile, '-out', databasename]
else:
cmdArgs=['makeblastdb', '-dbtype', dbtype, '-in', fastafile, '-out', databasename, '-parse_seqids']
subprocess.call(cmdArgs)
def runblastn(query, database, blastoutput, evalue=str(10), outfmt='custom qcov', task='blastn', num_threads=str(1), max_target_seqs=str(500), max_hsps=False, perc_identity=False, qcov_hsp_perc=False, culling_limit=False, word_size=False): #default evalue is 10; default wordsize is 11 for blastn - just use -tasks parameter which also changes gap settings; default task with no -task parameter set is megablast; N.b use cutstom qcov as standard for blast-based typing and plasmidpipeline, otherwise use outfmt 6 or specify custom outfmt
import subprocess
evalue=str(evalue)
if outfmt=='custom qcov':
outfmt='6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore qcovs qcovhsp qlen slen'
cmdArgs=['blastn', '-query', query, '-db', database, '-out', blastoutput, '-evalue', evalue, '-outfmt', outfmt, '-task', task, '-num_threads', num_threads, '-max_target_seqs', max_target_seqs]
if max_hsps!=False:
cmdArgs.extend(['-max_hsps', max_hsps])
if perc_identity!=False:
cmdArgs.extend(['-perc_identity', perc_identity])
if qcov_hsp_perc!=False:
cmdArgs.extend(['-qcov_hsp_perc', qcov_hsp_perc])
if culling_limit!=False:
cmdArgs.extend(['-culling_limit', culling_limit])
if word_size!=False:
cmdArgs.extend(['-word_size', word_size])
subprocess.call(cmdArgs)
| StarcoderdataPython |
9769694 | # ~ from pytokr import get_tok, get_toks
def make_tokr(f = None):
"make iterator and next functions out of iterable of split strings"
from itertools import chain
def sp(ln):
"to split the strings with a map"
return ln.split()
def the_it():
"so that both, items and item, are called with parentheses"
return it
if f is None:
from sys import stdin as f
it = chain.from_iterable(map(sp, f))
return the_it, it.__next__
items, item = make_tokr()
def collatz_next(n):
'''
Returns number following n in the Collatz sequence
>>> collatz_next(5)
16
>>> collatz_next(16)
8
>>> collatz_next(13)
40
'''
if n % 2 == 1:
return 3 * n + 1
else:
return n//2
for n in items():
c = 0
n = int(n)
while n != 1:
n = collatz_next(n)
c += 1
print(c)
| StarcoderdataPython |
1686518 | <reponame>ngokevin/chili
from cyder.dnsutils.tests.include_forward import *
from cyder.dnsutils.tests.include_reverse import *
from cyder.dnsutils.tests.soa import *
| StarcoderdataPython |
3325103 | <gh_stars>10-100
from django.conf.urls import url
from input_forms import views
urlpatterns = [
url(r"^$", views.index,
name="index"),
url(r"^create$", views.create,
name="create"),
url(r"^update", views.update,
name="update"),
url(r"^search$", views.search,
name="search"),
url(r"^searchAll$", views.search_all,
name="search_all"),
url(r"^searchStandalone$", views.search_standalone,
name="search_standalone"),
url(r"^preview/(?P<input_form_id>[0-9]+)/$", views.preview,
name="preview"),
url(r"^configureTemplate$", views.configure_template_for_endpoint,
name="configure_template_for_endpoint"),
url(r"^configureTemplateForQueue", views.configure_template_for_queue,
name="configure_template_for_queue"),
url(r"^configureTemplateForScreen/(?P<input_form_id>[0-9]+)", views.configure_template_for_screen,
name="configure_template_for_screen"),
url(r"^apply$", views.apply_per_endpoint_template,
name="apply_per_endpoint_template"),
url(r"^applyToQueue", views.apply_template_to_queue,
name="apply_template_to_queue"),
url(r"^applyStandalone$", views.apply_standalone_template,
name="apply_standalone_template"),
url(r"^edit/(?P<input_form_id>[0-9]+)/$", views.edit,
name="edit"),
url(r"^delete/(?P<input_form_id>[0-9]+)/$", views.delete,
name="delete"),
url(r"^(?P<input_form_id>[0-9]+)$", views.detail,
name="details"),
url(r"^export/(?P<input_form_id>[^/]+)$", views.export_form,
name="export_form"),
url(r"^import/$", views.import_form,
name="import_form"),
url(r"^new/(?P<template_id>[0-9]+)$", views.new_from_template,
name="new_from_template"),
url(r"^view_from_template/(?P<template_id>[0-9]+)/$", views.view_from_template,
name="view_from_template"),
url(r"^edit_from_template/(?P<template_id>[0-9]+)/$", views.edit_from_template,
name="edit_from_template"),
url(r"^loadWidgetConfig/$", views.load_widget_config,
name="load_widget_config"),
]
| StarcoderdataPython |
4827848 | import numpy as np
reveal_type(np.Inf) # E: float
reveal_type(np.Infinity) # E: float
reveal_type(np.NAN) # E: float
reveal_type(np.NINF) # E: float
reveal_type(np.NZERO) # E: float
reveal_type(np.NaN) # E: float
reveal_type(np.PINF) # E: float
reveal_type(np.PZERO) # E: float
reveal_type(np.e) # E: float
reveal_type(np.euler_gamma) # E: float
reveal_type(np.inf) # E: float
reveal_type(np.infty) # E: float
reveal_type(np.nan) # E: float
reveal_type(np.pi) # E: float
reveal_type(np.ALLOW_THREADS) # E: int
reveal_type(np.BUFSIZE) # E: int
reveal_type(np.CLIP) # E: int
reveal_type(np.ERR_CALL) # E: int
reveal_type(np.ERR_DEFAULT) # E: int
reveal_type(np.ERR_IGNORE) # E: int
reveal_type(np.ERR_LOG) # E: int
reveal_type(np.ERR_PRINT) # E: int
reveal_type(np.ERR_RAISE) # E: int
reveal_type(np.ERR_WARN) # E: int
reveal_type(np.FLOATING_POINT_SUPPORT) # E: int
reveal_type(np.FPE_DIVIDEBYZERO) # E: int
reveal_type(np.FPE_INVALID) # E: int
reveal_type(np.FPE_OVERFLOW) # E: int
reveal_type(np.FPE_UNDERFLOW) # E: int
reveal_type(np.MAXDIMS) # E: int
reveal_type(np.MAY_SHARE_BOUNDS) # E: int
reveal_type(np.MAY_SHARE_EXACT) # E: int
reveal_type(np.RAISE) # E: int
reveal_type(np.SHIFT_DIVIDEBYZERO) # E: int
reveal_type(np.SHIFT_INVALID) # E: int
reveal_type(np.SHIFT_OVERFLOW) # E: int
reveal_type(np.SHIFT_UNDERFLOW) # E: int
reveal_type(np.UFUNC_BUFSIZE_DEFAULT) # E: int
reveal_type(np.WRAP) # E: int
reveal_type(np.tracemalloc_domain) # E: int
reveal_type(np.little_endian) # E: bool
reveal_type(np.True_) # E: numpy.bool_
reveal_type(np.False_) # E: numpy.bool_
reveal_type(np.UFUNC_PYVALS_NAME) # E: str
reveal_type(np.sctypeDict) # E: dict
reveal_type(np.sctypes) # E: TypedDict
| StarcoderdataPython |
3494326 | <filename>python/bayesian_nn.py
import theano.tensor as T
import theano
import numpy as np
from scipy.spatial.distance import pdist, squareform
import random
import time
'''
Sample code to reproduce our results for the Bayesian neural network example.
Our settings are almost the same as Hernandez-Lobato and Adams (ICML15) https://jmhldotorg.files.wordpress.com/2015/05/pbp-icml2015.pdf
Our implementation is also based on their Python code.
p(y | W, X, \gamma) = \prod_i^N N(y_i | f(x_i; W), \gamma^{-1})
p(W | \lambda) = \prod_i N(w_i | 0, \lambda^{-1})
p(\gamma) = Gamma(\gamma | a0, b0)
p(\lambda) = Gamma(\lambda | a0, b0)
The posterior distribution is as follows:
p(W, \gamma, \lambda) = p(y | W, X, \gamma) p(W | \lambda) p(\gamma) p(\lambda)
To avoid negative values of \gamma and \lambda, we update loggamma and loglambda instead.
Copyright (c) 2016, <NAME> & <NAME>
All rights reserved.
'''
class svgd_bayesnn:
'''
We define a one-hidden-layer-neural-network specifically. We leave extension of deep neural network as our future work.
Input
-- X_train: training dataset, features
-- y_train: training labels
-- batch_size: sub-sampling batch size
-- max_iter: maximum iterations for the training procedure
-- M: number of particles are used to fit the posterior distribution
-- n_hidden: number of hidden units
-- a0, b0: hyper-parameters of Gamma distribution
-- master_stepsize, auto_corr: parameters of adgrad
'''
def __init__(self, X_train, y_train, batch_size = 100, max_iter = 1000, M = 20, n_hidden = 50, a0 = 1, b0 = 0.1, master_stepsize = 1e-3, auto_corr = 0.9):
self.n_hidden = n_hidden
self.d = X_train.shape[1] # number of data, dimension
self.M = M
num_vars = self.d * n_hidden + n_hidden * 2 + 3 # w1: d*n_hidden; b1: n_hidden; w2 = n_hidden; b2 = 1; 2 variances
self.theta = np.zeros([self.M, num_vars]) # particles, will be initialized later
'''
We keep the last 10% (maximum 500) of training data points for model developing
'''
size_dev = min(int(np.round(0.1 * X_train.shape[0])), 500)
X_dev, y_dev = X_train[-size_dev:], y_train[-size_dev:]
X_train, y_train = X_train[:-size_dev], y_train[:-size_dev]
'''
The data sets are normalized so that the input features and the targets have zero mean and unit variance
'''
self.std_X_train = np.std(X_train, 0)
self.std_X_train[ self.std_X_train == 0 ] = 1
self.mean_X_train = np.mean(X_train, 0)
self.mean_y_train = np.mean(y_train)
self.std_y_train = np.std(y_train)
'''
Theano symbolic variables
Define the neural network here
'''
X = T.matrix('X') # Feature matrix
y = T.vector('y') # labels
w_1 = T.matrix('w_1') # weights between input layer and hidden layer
b_1 = T.vector('b_1') # bias vector of hidden layer
w_2 = T.vector('w_2') # weights between hidden layer and output layer
b_2 = T.scalar('b_2') # bias of output
N = T.scalar('N') # number of observations
log_gamma = T.scalar('log_gamma') # variances related parameters
log_lambda = T.scalar('log_lambda')
###
prediction = T.dot(T.nnet.relu(T.dot(X, w_1)+b_1), w_2) + b_2
''' define the log posterior distribution '''
log_lik_data = -0.5 * X.shape[0] * (T.log(2*np.pi) - log_gamma) - (T.exp(log_gamma)/2) * T.sum(T.power(prediction - y, 2))
log_prior_data = (a0 - 1) * log_gamma - b0 * T.exp(log_gamma) + log_gamma
log_prior_w = -0.5 * (num_vars-2) * (T.log(2*np.pi)-log_lambda) - (T.exp(log_lambda)/2)*((w_1**2).sum() + (w_2**2).sum() + (b_1**2).sum() + b_2**2) \
+ (a0-1) * log_lambda - b0 * T.exp(log_lambda) + log_lambda
# sub-sampling mini-batches of data, where (X, y) is the batch data, and N is the number of whole observations
log_posterior = (log_lik_data * N / X.shape[0] + log_prior_data + log_prior_w)
dw_1, db_1, dw_2, db_2, d_log_gamma, d_log_lambda = T.grad(log_posterior, [w_1, b_1, w_2, b_2, log_gamma, log_lambda])
# automatic gradient
logp_gradient = theano.function(
inputs = [X, y, w_1, b_1, w_2, b_2, log_gamma, log_lambda, N],
outputs = [dw_1, db_1, dw_2, db_2, d_log_gamma, d_log_lambda]
)
# prediction function
self.nn_predict = theano.function(inputs = [X, w_1, b_1, w_2, b_2], outputs = prediction)
'''
Training with SVGD
'''
# normalization
X_train, y_train = self.normalization(X_train, y_train)
N0 = X_train.shape[0] # number of observations
''' initializing all particles '''
for i in range(self.M):
w1, b1, w2, b2, loggamma, loglambda = self.init_weights(a0, b0)
# use better initialization for gamma
ridx = np.random.choice(range(X_train.shape[0]), \
np.min([X_train.shape[0], 1000]), replace = False)
y_hat = self.nn_predict(X_train[ridx,:], w1, b1, w2, b2)
loggamma = -np.log(np.mean(np.power(y_hat - y_train[ridx], 2)))
self.theta[i,:] = self.pack_weights(w1, b1, w2, b2, loggamma, loglambda)
grad_theta = np.zeros([self.M, num_vars]) # gradient
# adagrad with momentum
fudge_factor = 1e-6
historical_grad = 0
for iter in range(max_iter):
# sub-sampling
batch = [ i % N0 for i in range(iter * batch_size, (iter + 1) * batch_size) ]
for i in range(self.M):
w1, b1, w2, b2, loggamma, loglambda = self.unpack_weights(self.theta[i,:])
dw1, db1, dw2, db2, dloggamma, dloglambda = logp_gradient(X_train[batch,:], y_train[batch], w1, b1, w2, b2, loggamma, loglambda, N0)
grad_theta[i,:] = self.pack_weights(dw1, db1, dw2, db2, dloggamma, dloglambda)
# calculating the kernel matrix
kxy, dxkxy = self.svgd_kernel(h=-1)
grad_theta = (np.matmul(kxy, grad_theta) + dxkxy) / self.M # \Phi(x)
# adagrad
if iter == 0:
historical_grad = historical_grad + np.multiply(grad_theta, grad_theta)
else:
historical_grad = auto_corr * historical_grad + (1 - auto_corr) * np.multiply(grad_theta, grad_theta)
adj_grad = np.divide(grad_theta, fudge_factor+np.sqrt(historical_grad))
self.theta = self.theta + master_stepsize * adj_grad
'''
Model selection by using a development set
'''
X_dev = self.normalization(X_dev)
for i in range(self.M):
w1, b1, w2, b2, loggamma, loglambda = self.unpack_weights(self.theta[i, :])
pred_y_dev = self.nn_predict(X_dev, w1, b1, w2, b2) * self.std_y_train + self.mean_y_train
# likelihood
def f_log_lik(loggamma): return np.sum( np.log(np.sqrt(np.exp(loggamma)) /np.sqrt(2*np.pi) * np.exp( -1 * (np.power(pred_y_dev - y_dev, 2) / 2) * np.exp(loggamma) )) )
# The higher probability is better
lik1 = f_log_lik(loggamma)
# one heuristic setting
loggamma = -np.log(np.mean(np.power(pred_y_dev - y_dev, 2)))
lik2 = f_log_lik(loggamma)
if lik2 > lik1:
self.theta[i,-2] = loggamma # update loggamma
def normalization(self, X, y = None):
X = (X - np.full(X.shape, self.mean_X_train)) / \
np.full(X.shape, self.std_X_train)
if y is not None:
y = (y - self.mean_y_train) / self.std_y_train
return (X, y)
else:
return X
'''
Initialize all particles
'''
def init_weights(self, a0, b0):
w1 = 1.0 / np.sqrt(self.d + 1) * np.random.randn(self.d, self.n_hidden)
b1 = np.zeros((self.n_hidden,))
w2 = 1.0 / np.sqrt(self.n_hidden + 1) * np.random.randn(self.n_hidden)
b2 = 0.
loggamma = np.log(np.random.gamma(a0, b0))
loglambda = np.log(np.random.gamma(a0, b0))
return (w1, b1, w2, b2, loggamma, loglambda)
'''
Calculate kernel matrix and its gradient: K, \nabla_x k
'''
def svgd_kernel(self, h = -1):
sq_dist = pdist(self.theta)
pairwise_dists = squareform(sq_dist)**2
if h < 0: # if h < 0, using median trick
h = np.median(pairwise_dists)
h = np.sqrt(0.5 * h / np.log(self.theta.shape[0]+1))
# compute the rbf kernel
Kxy = np.exp( -pairwise_dists / h**2 / 2)
dxkxy = -np.matmul(Kxy, self.theta)
sumkxy = np.sum(Kxy, axis=1)
for i in range(self.theta.shape[1]):
dxkxy[:, i] = dxkxy[:,i] + np.multiply(self.theta[:,i],sumkxy)
dxkxy = dxkxy / (h**2)
return (Kxy, dxkxy)
'''
Pack all parameters in our model
'''
def pack_weights(self, w1, b1, w2, b2, loggamma, loglambda):
params = np.concatenate([w1.flatten(), b1, w2, [b2], [loggamma],[loglambda]])
return params
'''
Unpack all parameters in our model
'''
def unpack_weights(self, z):
w = z
w1 = np.reshape(w[:self.d*self.n_hidden], [self.d, self.n_hidden])
b1 = w[self.d*self.n_hidden:(self.d+1)*self.n_hidden]
w = w[(self.d+1)*self.n_hidden:]
w2, b2 = w[:self.n_hidden], w[-3]
# the last two parameters are log variance
loggamma, loglambda= w[-2], w[-1]
return (w1, b1, w2, b2, loggamma, loglambda)
'''
Evaluating testing rmse and log-likelihood, which is the same as in PBP
Input:
-- X_test: unnormalized testing feature set
-- y_test: unnormalized testing labels
'''
def evaluation(self, X_test, y_test):
# normalization
X_test = self.normalization(X_test)
# average over the output
pred_y_test = np.zeros([self.M, len(y_test)])
prob = np.zeros([self.M, len(y_test)])
'''
Since we have M particles, we use a Bayesian view to calculate rmse and log-likelihood
'''
for i in range(self.M):
w1, b1, w2, b2, loggamma, loglambda = self.unpack_weights(self.theta[i, :])
pred_y_test[i, :] = self.nn_predict(X_test, w1, b1, w2, b2) * self.std_y_train + self.mean_y_train
prob[i, :] = np.sqrt(np.exp(loggamma)) /np.sqrt(2*np.pi) * np.exp( -1 * (np.power(pred_y_test[i, :] - y_test, 2) / 2) * np.exp(loggamma) )
pred = np.mean(pred_y_test, axis=0)
# evaluation
svgd_rmse = np.sqrt(np.mean((pred - y_test)**2))
svgd_ll = np.mean(np.log(np.mean(prob, axis = 0)))
return (svgd_rmse, svgd_ll)
if __name__ == '__main__':
print 'Theano', theano.version.version #our implementation is based on theano 0.8.2
np.random.seed(1)
''' load data file '''
data = np.loadtxt('../data/boston_housing')
# Please make sure that the last column is the label and the other columns are features
X_input = data[ :, range(data.shape[ 1 ] - 1) ]
y_input = data[ :, data.shape[ 1 ] - 1 ]
''' build the training and testing data set'''
train_ratio = 0.9 # We create the train and test sets with 90% and 10% of the data
permutation = np.arange(X_input.shape[0])
random.shuffle(permutation)
size_train = int(np.round(X_input.shape[ 0 ] * train_ratio))
index_train = permutation[ 0 : size_train]
index_test = permutation[ size_train : ]
X_train, y_train = X_input[ index_train, : ], y_input[ index_train ]
X_test, y_test = X_input[ index_test, : ], y_input[ index_test ]
start = time.time()
''' Training Bayesian neural network with SVGD '''
batch_size, n_hidden, max_iter = 100, 50, 2000 # max_iter is a trade-off between running time and performance
svgd = svgd_bayesnn(X_train, y_train, batch_size = batch_size, n_hidden = n_hidden, max_iter = max_iter)
svgd_time = time.time() - start
svgd_rmse, svgd_ll = svgd.evaluation(X_test, y_test)
print 'SVGD', svgd_rmse, svgd_ll, svgd_time
| StarcoderdataPython |
8182331 | ## @package onnx
#Module caffe2.python.onnx.onnxifi
"""
ONNXIFI a Caffe2 net
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python._import_c_extension as C
import numpy as np
def onnxifi_caffe2_net(
pred_net,
input_shapes,
max_batch_size=1,
max_seq_size=1,
debug=False,
use_onnx=True,
merge_fp32_inputs_into_fp16=False,
adjust_batch=True,
black_list=None,
weight_names=None):
"""
Transform the caffe2_net by collapsing ONNXIFI-runnable nodes into Onnxifi c2 ops
"""
shape_hints = {}
for k, v in input_shapes.items():
shape_hints[k] = v
pred_net_str = C.onnxifi(pred_net.SerializeToString(),
shape_hints,
black_list if black_list else [],
weight_names if weight_names is not None else [],
max_batch_size,
max_seq_size,
adjust_batch,
debug,
merge_fp32_inputs_into_fp16,
use_onnx)
pred_net_cut = caffe2_pb2.NetDef()
pred_net_cut.ParseFromString(pred_net_str)
return pred_net_cut
| StarcoderdataPython |
11222131 | <gh_stars>1-10
from typing import List
from pdip.data import Entity
from sqlalchemy import Column, String
from sqlalchemy.orm import relationship
from process.domain.base import Base
from process.domain.base.connection.ConnectionTypeBase import ConnectionTypeBase
from process.domain.connection.Connection import Connection
from process.domain.connection.ConnectorType import ConnectorType
class ConnectionType(ConnectionTypeBase, Entity, Base):
__tablename__ = "ConnectionType"
__table_args__ = {"schema": "Connection"}
Name = Column(String(100), index=False, unique=True, nullable=False)
Connectors: List[ConnectorType] = relationship("ConnectorType",
back_populates="ConnectionType")
Connections: List[Connection] = relationship("Connection",
back_populates="ConnectionType")
| StarcoderdataPython |
1618077 | <filename>object_detection.py
# -*- coding: utf-8 -*-
#
# 对象检测
# Author: alex
# Created Time: 2018年11月24日 星期六 10时01分39秒
from imageai.Prediction.Custom import CustomImagePrediction
output_path = '/tmp/'
json_path = '/var/www/tmp/faces/model/json/model_class.json'
model_path = '/var/www/tmp/faces/model/models/model_ex-100_acc-0.250000.h5'
detector = CustomImagePrediction()
detector.setModelTypeAsResNet()
# 载入已训练好的文件
print('Load model...')
detector.setModelPath(model_path)
detector.setJsonPath(json_path)
detector.loadModel(num_objects=3)
print('Load model end!')
def detect(path):
# 将检测后的结果保存为新图片
print('Input File: ', path)
predictions, probabilities = detector.predictImage(path, result_count=5)
for eachPrediction, eachProbability in zip(predictions, probabilities):
print(eachPrediction + " : " + eachProbability)
if __name__ == '__main__':
import sys
detect(sys.argv[1])
| StarcoderdataPython |
11297713 | <reponame>jkosinski/XlinkAnalyzerX<filename>template/cmd.py
# vim: set expandtab shiftwidth=4 softtabstop=4:
def subcommand_function(session, positional_arguments, keyword_arguments):
pass
from chimerax.core.commands import CmdDesc
subcommand_desc = CmdDesc()
# TODO: Add more subcommands here
| StarcoderdataPython |
168531 | <reponame>netor27/codefights-arcade-solutions<gh_stars>0
def extractEachKth(inputArray, k):
return [x for i, x in enumerate(inputArray) if (i + 1) % k != 0]
print(extractEachKth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)) | StarcoderdataPython |
11265169 | <reponame>ehsanik/allenact<gh_stars>0
import glob
import os
from math import ceil
from typing import Dict, Any, List, Optional, Sequence
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from torchvision import models
from constants import ABS_PATH_OF_TOP_LEVEL_DIR
from core.algorithms.onpolicy_sync.losses import PPO
from core.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from core.base_abstractions.experiment_config import ExperimentConfig, MachineParams
from core.base_abstractions.preprocessor import (
ResNetPreprocessor,
SensorPreprocessorGraph,
)
from core.base_abstractions.sensor import SensorSuite
from core.base_abstractions.task import TaskSampler
from plugins.ithor_plugin.ithor_sensors import RGBSensorThor
from plugins.robothor_plugin.robothor_sensors import GPSCompassSensorRoboThor
from plugins.robothor_plugin.robothor_task_samplers import PointNavDatasetTaskSampler
from plugins.robothor_plugin.robothor_tasks import PointNavTask
from projects.pointnav_baselines.models.point_nav_models import (
ResnetTensorPointNavActorCritic,
)
from utils.experiment_utils import (
Builder,
PipelineStage,
TrainingPipeline,
LinearDecay,
evenly_distribute_count_into_bins,
)
class ObjectNavRoboThorRGBPPOExperimentConfig(ExperimentConfig):
"""A Point Navigation experiment configuration in RoboThor."""
# Task Parameters
MAX_STEPS = 500
REWARD_CONFIG = {
"step_penalty": -0.01,
"goal_success_reward": 10.0,
"failed_stop_reward": 0.0,
"shaping_weight": 1.0,
}
# Simulator Parameters
CAMERA_WIDTH = 640
CAMERA_HEIGHT = 480
SCREEN_SIZE = 224
# Training Engine Parameters
ADVANCE_SCENE_ROLLOUT_PERIOD: Optional[int] = None
NUM_PROCESSES = 60
TRAINING_GPUS = list(range(torch.cuda.device_count()))
VALIDATION_GPUS = [torch.cuda.device_count() - 1]
TESTING_GPUS = [torch.cuda.device_count() - 1]
# Dataset Parameters
TRAIN_DATASET_DIR = os.path.join(
ABS_PATH_OF_TOP_LEVEL_DIR, "datasets/ithor-objectnav/train"
)
VAL_DATASET_DIR = os.path.join(
ABS_PATH_OF_TOP_LEVEL_DIR, "datasets/ithor-objectnav/val"
)
SENSORS = [
RGBSensorThor(
height=SCREEN_SIZE,
width=SCREEN_SIZE,
use_resnet_normalization=True,
uuid="rgb_lowres",
),
GPSCompassSensorRoboThor(),
]
PREPROCESSORS = [
Builder(
ResNetPreprocessor,
{
"input_height": SCREEN_SIZE,
"input_width": SCREEN_SIZE,
"output_width": 7,
"output_height": 7,
"output_dims": 512,
"pool": False,
"torchvision_resnet_model": models.resnet18,
"input_uuids": ["rgb_lowres"],
"output_uuid": "rgb_resnet",
},
),
]
OBSERVATIONS = [
"rgb_resnet",
"target_coordinates_ind",
]
ENV_ARGS = dict(
width=CAMERA_WIDTH,
height=CAMERA_HEIGHT,
rotateStepDegrees=30.0,
visibilityDistance=1.0,
gridSize=0.25,
)
@classmethod
def tag(cls):
return "PointNavithorRGBPPO"
@classmethod
def training_pipeline(cls, **kwargs):
ppo_steps = int(250000000)
lr = 3e-4
num_mini_batch = 1
update_repeats = 3
num_steps = 30
save_interval = 5000000
log_interval = 10000
gamma = 0.99
use_gae = True
gae_lambda = 0.95
max_grad_norm = 0.5
return TrainingPipeline(
save_interval=save_interval,
metric_accumulate_interval=log_interval,
optimizer_builder=Builder(optim.Adam, dict(lr=lr)),
num_mini_batch=num_mini_batch,
update_repeats=update_repeats,
max_grad_norm=max_grad_norm,
num_steps=num_steps,
named_losses={"ppo_loss": PPO(**PPOConfig)},
gamma=gamma,
use_gae=use_gae,
gae_lambda=gae_lambda,
advance_scene_rollout_period=cls.ADVANCE_SCENE_ROLLOUT_PERIOD,
pipeline_stages=[
PipelineStage(loss_names=["ppo_loss"], max_stage_steps=ppo_steps)
],
lr_scheduler_builder=Builder(
LambdaLR, {"lr_lambda": LinearDecay(steps=ppo_steps)}
),
)
def machine_params(self, mode="train", **kwargs):
sampler_devices: Sequence[int] = []
if mode == "train":
workers_per_device = 1
gpu_ids = (
[]
if not torch.cuda.is_available()
else self.TRAINING_GPUS * workers_per_device
)
nprocesses = (
1
if not torch.cuda.is_available()
else evenly_distribute_count_into_bins(self.NUM_PROCESSES, len(gpu_ids))
)
sampler_devices = self.TRAINING_GPUS
elif mode == "valid":
nprocesses = 1
gpu_ids = [] if not torch.cuda.is_available() else self.VALIDATION_GPUS
elif mode == "test":
nprocesses = 1
gpu_ids = [] if not torch.cuda.is_available() else self.TESTING_GPUS
else:
raise NotImplementedError("mode must be 'train', 'valid', or 'test'.")
sensor_preprocessor_graph = (
SensorPreprocessorGraph(
source_observation_spaces=SensorSuite(self.SENSORS).observation_spaces,
preprocessors=self.PREPROCESSORS,
)
if mode == "train"
or (
(isinstance(nprocesses, int) and nprocesses > 0)
or (isinstance(nprocesses, Sequence) and sum(nprocesses) > 0)
)
else None
)
return MachineParams(
nprocesses=nprocesses,
devices=gpu_ids,
sampler_devices=sampler_devices
if mode == "train"
else gpu_ids, # ignored with > 1 gpu_ids
sensor_preprocessor_graph=sensor_preprocessor_graph,
)
# Define Model
@classmethod
def create_model(cls, **kwargs) -> nn.Module:
return ResnetTensorPointNavActorCritic(
action_space=gym.spaces.Discrete(len(PointNavTask.class_action_names())),
observation_space=kwargs["sensor_preprocessor_graph"].observation_spaces,
goal_sensor_uuid="target_coordinates_ind",
rgb_resnet_preprocessor_uuid="rgb_resnet",
hidden_size=512,
goal_dims=32,
)
# Define Task Sampler
@classmethod
def make_sampler_fn(cls, **kwargs) -> TaskSampler:
return PointNavDatasetTaskSampler(**kwargs)
# Utility Functions for distributing scenes between GPUs
@staticmethod
def _partition_inds(n: int, num_parts: int):
return np.round(np.linspace(0, n, num_parts + 1, endpoint=True)).astype(
np.int32
)
def _get_sampler_args_for_scene_split(
self,
scenes_dir: str,
process_ind: int,
total_processes: int,
seeds: Optional[List[int]] = None,
deterministic_cudnn: bool = False,
) -> Dict[str, Any]:
path = os.path.join(scenes_dir, "*.json.gz")
scenes = [scene.split("/")[-1].split(".")[0] for scene in glob.glob(path)]
if len(scenes) == 0:
raise RuntimeError(
(
"Could find no scene dataset information in directory {}."
" Are you sure you've downloaded them? "
" If not, see https://allenact.org/installation/download-datasets/ information"
" on how this can be done."
).format(scenes_dir)
)
if total_processes > len(scenes): # oversample some scenes -> bias
if total_processes % len(scenes) != 0:
print(
"Warning: oversampling some of the scenes to feed all processes."
" You can avoid this by setting a number of workers divisible by the number of scenes"
)
scenes = scenes * int(ceil(total_processes / len(scenes)))
scenes = scenes[: total_processes * (len(scenes) // total_processes)]
else:
if len(scenes) % total_processes != 0:
print(
"Warning: oversampling some of the scenes to feed all processes."
" You can avoid this by setting a number of workers divisor of the number of scenes"
)
inds = self._partition_inds(len(scenes), total_processes)
return {
"scenes": scenes[inds[process_ind] : inds[process_ind + 1]],
"max_steps": self.MAX_STEPS,
"sensors": self.SENSORS,
"action_space": gym.spaces.Discrete(len(PointNavTask.class_action_names())),
"seed": seeds[process_ind] if seeds is not None else None,
"deterministic_cudnn": deterministic_cudnn,
"rewards_config": self.REWARD_CONFIG,
}
def train_task_sampler_args(
self,
process_ind: int,
total_processes: int,
devices: Optional[List[int]] = None,
seeds: Optional[List[int]] = None,
deterministic_cudnn: bool = False,
) -> Dict[str, Any]:
res = self._get_sampler_args_for_scene_split(
os.path.join(self.TRAIN_DATASET_DIR, "episodes"),
process_ind,
total_processes,
seeds=seeds,
deterministic_cudnn=deterministic_cudnn,
)
res["scene_directory"] = self.TRAIN_DATASET_DIR
res["loop_dataset"] = True
res["env_args"] = {}
res["env_args"].update(self.ENV_ARGS)
res["env_args"]["x_display"] = (
("0.%d" % devices[process_ind % len(devices)])
if devices is not None and len(devices) > 0
else None
)
res["allow_flipping"] = True
return res
def valid_task_sampler_args(
self,
process_ind: int,
total_processes: int,
devices: Optional[List[int]] = None,
seeds: Optional[List[int]] = None,
deterministic_cudnn: bool = False,
) -> Dict[str, Any]:
res = self._get_sampler_args_for_scene_split(
os.path.join(self.VAL_DATASET_DIR, "episodes"),
process_ind,
total_processes,
seeds=seeds,
deterministic_cudnn=deterministic_cudnn,
)
res["scene_directory"] = self.VAL_DATASET_DIR
res["loop_dataset"] = False
res["env_args"] = {}
res["env_args"].update(self.ENV_ARGS)
res["env_args"]["x_display"] = (
("0.%d" % devices[process_ind % len(devices)])
if devices is not None and len(devices) > 0
else None
)
return res
def test_task_sampler_args(
self,
process_ind: int,
total_processes: int,
devices: Optional[List[int]] = None,
seeds: Optional[List[int]] = None,
deterministic_cudnn: bool = False,
) -> Dict[str, Any]:
res = self._get_sampler_args_for_scene_split(
os.path.join(self.VAL_DATASET_DIR, "episodes"),
process_ind,
total_processes,
seeds=seeds,
deterministic_cudnn=deterministic_cudnn,
)
res["scene_directory"] = self.VAL_DATASET_DIR
res["loop_dataset"] = False
res["env_args"] = {}
res["env_args"].update(self.ENV_ARGS)
return res
| StarcoderdataPython |
1966612 | #! /usr/bin/env python3
import itertools
import sys
def find_clouds(lst: list) -> int:
xs = [int(x[0][0]) for x in lst] + [int(x[1][0]) for x in lst]
max_x = max(xs)
ys = [int(x[0][1]) for x in lst] + [int(x[1][1]) for x in lst]
max_y = max(ys)
sea_map = {}
for x in range(0, max_x + 1):
for y in range(0, max_y + 1):
sea_map[(x, y)] = '.'
for a, b in lst:
x_step = 1 if a[0] < b[0] else -1
y_step = 1 if a[1] < b[1] else -1
if a[0] == b[0]:
fill_value = a[0]
elif a[1] == b[1]:
fill_value = a[1]
else:
fill_value = None
co = itertools.zip_longest(range(a[0], b[0] + x_step, x_step), range(a[1], b[1] + y_step, y_step),
fillvalue=fill_value)
for pair in co:
if sea_map[pair] == '.':
sea_map[pair] = 1
else:
sea_map[pair] += 1
return len(list(filter(lambda v: v != '.' and v > 1, sea_map.values())))
def get_data(path) -> list:
with open(path) as f:
raw = [x.strip().split(' -> ') for x in f.readlines() if x.strip()]
return [[list(map(int, x[0].split(','))), list(map(int, x[1].split(',')))] for x in raw]
if __name__ == '__main__':
if len(sys.argv) == 1:
print('Usage: main.py <filename>')
sys.exit(1)
lines = get_data(sys.argv[1])
r1 = find_clouds(list(filter(lambda x: x[0][0] == x[1][0] or x[0][1] == x[1][1], lines)))
r2 = find_clouds(lines)
print(f'part 1: {r1}')
print(f'part 2: {r2}')
| StarcoderdataPython |
281766 | """
Multiclass-classification by taking the max over a set of one-against-rest
logistic classifiers.
"""
__authors__ = "<NAME>"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["<NAME>"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "<EMAIL>"
import logging
try:
from sklearn.linear_model import LogisticRegression
except ImportError:
LogisticRegression = None
import numpy as np
logger = logging.getLogger(__name__)
class IndependentMulticlassLogistic:
"""
Fits a separate logistic regression classifier for each class, makes
predictions based on the max output: during training, views a one-hot label
vector as a vector of independent binary labels, rather than correctly
modeling them as one-hot like softmax would do.
This is what Jia+Huang used to get state of the art on CIFAR-100
Parameters
----------
C : WRITEME
"""
def __init__(self, C):
self.C = C
def fit(self, X, y):
"""
Fits the model to the given training data.
Parameters
----------
X : ndarray
2D array, each row is one example
y : ndarray
vector of integer class labels
"""
if LogisticRegression is None:
raise RuntimeError("sklearn not available.")
min_y = y.min()
max_y = y.max()
assert min_y == 0
num_classes = max_y + 1
assert num_classes > 1
logistics = []
for c in xrange(num_classes):
logger.info('fitting class {0}'.format(c))
cur_y = (y == c).astype('int32')
logistics.append(LogisticRegression(C = self.C).fit(X,cur_y))
return Classifier(logistics)
class Classifier:
"""
.. todo::
WRITEME
Parameters
----------
logistics : WRITEME
"""
def __init__(self, logistics):
assert len(logistics) > 1
num_classes = len(logistics)
num_features = logistics[0].coef_.shape[1]
self.W = np.zeros((num_features, num_classes))
self.b = np.zeros((num_classes,))
for i in xrange(num_classes):
self.W[:,i] = logistics[i].coef_
self.b[i] = logistics[i].intercept_
def predict(self, X):
"""
.. todo::
WRITEME
"""
return np.argmax(self.b + np.dot(X,self.W), 1)
| StarcoderdataPython |
6508701 | from __future__ import division
from mdp_gen import gen_multi_reward_params, multi_reward_grid_mdp, multiple_grid_mdp, \
write_spudd_model, multiple_bernoulli_mdp, multiple_r_and_d_mdp
from mdp_base import MultipleMDP
from factored_alp import factored_alp, eval_approx_qf
import search
reload(search)
from search import local_search_vi
import h5py, random, time
from sys import stdout
from pdb import pm
import argparse
import IPython as ipy
import time
import numpy as np
import util as u
import subprocess
import lrtdp
n_mdp_vals = [2, 6, 10, 14]
n_gold_loc_vals = [1, 3, 5, 7]
SPUDD_LOC = '/home/dhm/src/spudd-3.6.2/Spudd/bin/linux/Spudd'
SPUDD_FNAME = 'test.mdp'
SPUDD_OUTF = 'data/UAI/comparison_timing.h5'
def compare(outf = SPUDD_OUTF, n_trials=30, mdp_type='grid'):
n_mdps = [2, 3, 4, 5, 6]#, 7, 8, 9, 10, 11, 12, 13, 14]
do_spudd = True
do_singh_cohn = False#True
do_lrtdp_wi = True
do_lrtdp_singh_cohn = True
if mdp_type=='grid':
params = {'n_gold_locs': 3,
'gamma': 0.9,
'dim': 4}
gen_mdp = multiple_grid_mdp
elif mdp_type == 'bernoulli':
params={'sample_bounds': (8, 11),
'prior_weight': 5,
'research_cost': (1, 3),
'gamma': 0.9}
gen_mdp = multiple_bernoulli_mdp
elif mdp_type == 'r_and_d':
params = {'gamma': 0.9}
gen_mdp = multiple_r_and_d_mdp
n_mdps = [2, 5, 10, 20, 30, 50]
outf = h5py.File(outf, 'a')
if 'mdp_type' in outf:
assert str(outf['mdp_type'][()]) == mdp_type
else:
outf['mdp_type'] = mdp_type
for n in n_mdps:
if str(n) in outf:
del outf[str(n)]
print "N:\t{}".format(n)
result_g = outf.create_group(str(n))
result_g['spudd_times'] = -1 * np.ones(n_trials)
result_g['singh_cohn_times'] = -1 * np.ones(n_trials)
result_g['bbvi_times'] = -1 * np.ones(n_trials)
result_g['lrtdp_singh_cohn_times'] = -1 * np.ones(n_trials)
result_g['lrtdp_wi_times'] = -1 * np.ones(n_trials)
result_g['num_expands'] = -1 * np.ones(n_trials)
result_g['singh_cohn_expands'] = -1 * np.ones(n_trials)
result_g['seeds'] = np.zeros((n_trials, n))
result_g['states'] = np.zeros((n_trials, n))
result_g['size'] = str(gen_mdp(
[random.random() for _ in range(n)], **params).num_states)
for i in range(n_trials):
mdp_seeds = [random.random() for _ in range(n)]
result_g['seeds'][i, :] = mdp_seeds
m = gen_mdp(mdp_seeds, **params)
# start_state = random.randint(0, m.num_states)
start_state=0
start_state = u.tuplify(m.index_to_factored_state(start_state))
result_g['states'][i] = start_state
start = time.time()
# try:
wi_frac = m.frontier_alg()
m.build_sparse_transitions()
m.compute_lb_mdp()
search_a, num_expansions, sub_opt = local_search_vi(m, start_state, semi_verbose = True, max_expand=10000)
# except Exception as e:
# print e
# print 'Error encountered in search!'
# sub_opt = 10
# num_expansions = 1000000
time_taken = time.time() - start
result_g['num_expands'][i] = num_expansions
if sub_opt <= 10**-8:
result_g['bbvi_times'][i] = time_taken
print 'BBVI {}'.format(time_taken)
else:
print "BBVI DID NOT CONVERGE"
# print n, num_expansions
if do_spudd:
write_spudd_model(m.component_mdps, SPUDD_FNAME)
start = time.time()
p = subprocess.Popen([SPUDD_LOC, SPUDD_FNAME])
while True:
time.sleep(.01)
res = p.poll()
if res is not None:
break
time_taken = time.time() - start
if time_taken > 1000:
p.terminate()
break
if res is not None and res >= 0:
result_g['spudd_times'][i] = time_taken
print 'SPUDD {}'.format(time_taken)
else:
print 'SPUDD DID NOT CONVERGE'
else:
print 'skipping SPUDD'
outf.flush()
if do_singh_cohn:
start = time.time()
try:
search_a, num_expansions, sub_opt = local_search_vi(m, start_state, semi_verbose = True,
max_expand=10000, use_wi = False,
min_hval_decrease_rate = .1)
except Exception as e:
print e
print 'Error encountered in search!'
sub_opt = 10
num_expansions = 1000000
time_taken = time.time() - start
result_g['singh_cohn_expands'][i] = num_expansions
if sub_opt <= 10**-8:
result_g['singh_cohn_times'][i] = time_taken
print 'SINGH_COHN {}'.format(time_taken)
else:
print "SINGH_COHN DID NOT CONVERGE"
if do_lrtdp_wi:
start = time.time()
converged, best_a = lrtdp.lrtdp(m, start_state, max_iter=10000, use_wi=True, max_t=1000)
time_taken = time.time() - start
if converged:
result_g['lrtdp_wi_times'][i] = time_taken
print "LRTDP_WI {} ".format(time_taken)
else:
print "LRTDP_WI DID NOT CONVERGE"
if do_lrtdp_singh_cohn:
start = time.time()
converged, best_a = lrtdp.lrtdp(m, start_state, max_iter=10000, use_wi=False, max_t=1000)
time_taken = time.time() - start
if converged:
result_g['lrtdp_singh_cohn_times'][i] = time_taken
print "LRTDP_SINGH_COHN {} ".format(time_taken)
else:
print "LRTDP_SINGH_COHN DID NOT CONVERGE"
# if do_lrtdp_h_inf:
# start = time.time()
# converged, best_a = lrtdp.lrtdp(m, start_state, max_iter=10000, use_wi=False)
# time_taken = time.time() - start
# if converged:
# result_g['lrtdp_singh_cohn_times'][i] = time_taken
# print "LRTDP_SINGH_COHN {} ".format(time_taken)
# else:
# print "LRTDP_SINGH_COHN DID NOT CONVERGE"
do_spudd = not np.all(result_g['spudd_times'][:] == -1)
do_singh_cohn = not np.all(result_g['singh_cohn_times'][:] == -1)
do_lrtdp_wi = not np.all(result_g['lrtdp_wi_times'][:] == -1)
do_lrtdp_singh_cohn = not np.all(result_g['lrtdp_singh_cohn_times'][:] == -1)
DEFAULT_MDP_PARAMS = {'n_gold_locs' : 5,
'gamma' : .9,
'dim' : 20}
DEFAULT_NUM_ARMS = 4
def do_single_run(num_trials, mdp = None, verbose=False):
if mdp == None:
mdp = multiple_grid_mdp([random.random() for i in range(DEFAULT_NUM_ARMS)],
**DEFAULT_MDP_PARAMS)
# mdp.build_sparse_transitions()
mdp.frontier_alg()
mdp.compute_lb_mdp()
total_expansions = []
start_states = [mdp.get_rand_state(wc_violations_only=True) for i in range(num_trials)]
print "testing with {:4} states".format(float(mdp.num_states))
for i, s in enumerate(start_states):
print s
start_state = u.tuplify(s)
# try:
search_a, num_expansions, sub_opt = local_search_vi(mdp, start_state,
semi_verbose=verbose,
max_expand=100000)
total_expansions.append(num_expansions)
# except Exception, e:
# print 'Search Failed', e
# total_expansions.append(-1)
print total_expansions
return total_expansions
def proc_data_file(fname):
f = h5py.File(fname, 'r')
time_res = dict([(c, []) for c in exp_conditions[:-1]])
for c in exp_conditions[:-1]:
for t in range(10):
for r in range(40):
time_res[c].append(f[str(c)][str(t)][str(r)]['total_reward'][()])
for c in time_res:
time_res[c] = np.mean(time_res[c])
return time_res
def proc_all_experiment_files():
results = {}
for n_mdp in n_mdp_vals:
for n_gold_locs in n_gold_loc_vals:
fname = 'data/{}-mdps-{}-gold-locs.h5'.format(n_mdp, n_gold_locs)
try:
results[(n_mdp, n_gold_locs)] = proc_data_file(fname)
except:
continue
ipy.embed()
if __name__ == '__main__':
import sys; sys.setrecursionlimit(100000)
parser = argparse.ArgumentParser()
parser.add_argument('mdp_type', type=str)
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--n_trials', type=int, default=10)
# parser.add_argument('exp_file', type=str)
# parser.add_argument('condition', type=str)
args = parser.parse_args()
compare(n_trials=args.n_trials, mdp_type=args.mdp_type)
# num_exp = do_single_run(args.n_trials, verbose = args.verbose)
# print 'num expansions:'
# print num_exp
| StarcoderdataPython |
15162 | import logging
import os
import re
import sublime
# external dependencies (see dependencies.json)
import jsonschema
import yaml # pyyaml
# This plugin generates a hidden syntax file containing rules for additional
# chainloading commands defined by the user. The syntax is stored in the cache
# directory to avoid the possibility of it falling under user version control in
# the usual packages directory
userSyntaxName = 'execline-user-chainload.sublime-syntax'
pkgName = 'execline'
settingsName = 'execline.sublime-settings'
mainSyntaxPath = 'Packages/{}/execline.sublime-syntax'.format(pkgName)
schemaPath = 'Packages/{}/execline.sublime-settings.schema.json'.format(pkgName)
ruleNamespaces = {
'keyword': 'keyword.other',
'function': 'support.function',
}
ruleContexts = {
'argument': {
'generic': 'command-call-common-arg-aside-&pop',
'variable': 'command-call-common-variable-&pop',
'pattern': 'command-call-common-glob-&pop',
},
'block': {
'program': 'block-run-prog',
'arguments': 'block-run-arg',
'trap': 'block-trap',
'multidefine': 'block-multidefine',
},
'options': {
'list': 'command-call-common-opt-list-&pop',
'list-with-args': {
'match': '(?=-[{}])',
'push': 'command-call-common-opt-arg-&pop',
'include': 'command-call-common-opt-list-&pop',
},
},
}
logging.basicConfig()
logger = logging.getLogger(__name__)
# Fully resolve the name of a context in the main syntax file
def _resolve_context(context):
return mainSyntaxPath + '#' + context
# Create a match rule describing a command of a certain type, made of a list of
# elements
def _make_rule(cmd_name, cmd_elements, cmd_type):
try:
namespace = ruleNamespaces[cmd_type]
except KeyError:
logger.warning("Ignoring command of unrecognised type '{}'".format(cmd_type))
return
rule = {}
# Careful to sanitise user input. Only literal command names accepted here
rule['match'] = r'{{chain_pre}}' + re.escape(cmd_name) + r'{{chain_post}}'
rule['scope'] = ' '.join([
'meta.function-call.name.execline',
'{}.user.{}.execline'.format(namespace, cmd_name),
'meta.string.unquoted.execline',
])
contextSeq = []
for elem in cmd_elements:
context = None
# Resolve the element into a name and possible argument
elemType,elemSubtype = elem[0:2]
try:
elemArg = elem[2]
except IndexError:
elemArg = ''
# Look up the context named by this element
try:
contextData = ruleContexts[elemType][elemSubtype]
if isinstance(contextData, str):
contextData = { 'include': contextData }
except KeyError:
logger.warning("Ignoring key '{}' not found in context dictionary".format(elem))
continue
if len(contextData) > 1 and not elemArg:
logger.warning("Ignoring element '{}' with missing data".format(elem))
continue
if len(contextData) == 1:
# context = _resolve_context(contextData['include'])
# Although a basic include could be provided as the target context name
# directly to the 'push' list, this can break if there are a mix of other
# types of contexts being pushed to the stack. A context containing a sole
# include is safe from this
context = [ {'include': _resolve_context(contextData['include'])} ]
elif elemType == 'options':
# Careful to sanitise user input, this must behave as a list of characters
matchPattern = contextData['match'].format( re.escape(elemArg) )
context = [
{'match': matchPattern, 'push': _resolve_context(contextData['push'])},
{'include': _resolve_context(contextData['include'])},
]
if context:
contextSeq.append(context)
# Convert context sequence into context stack
if contextSeq:
rule['push'] = contextSeq
rule['push'].reverse()
return rule
def _validate_settings():
# Read the schema using Sublime Text's builtin JSON parser
try:
schema = sublime.decode_value( sublime.load_resource(schemaPath) )
except Exception as ex:
logger.error("Failed loading schema: {}".format(ex))
return validSets
settings = sublime.load_settings(settingsName)
activeSets = settings.get('user_chainload_active')
if not activeSets:
return []
validSets = []
for setName in activeSets:
if not setName:
sublime.error_message("Error in {}: Set name cannot be the empty string".format(settingsName))
continue
setName = 'user_chainload_set_' + setName
setDict = settings.get(setName)
if setDict == None:
sublime.error_message("Error in {}: Couldn't find expected setting '{}'".format(settingsName, setName))
continue
try:
jsonschema.validate(setDict, schema)
logger.debug("Validation success for {}".format(setName))
validSets.append(setName)
except jsonschema.exceptions.SchemaError as ex:
# A problem in the schema itself for me as the developer to resolve
logger.error("Failed validating schema: {}".format(ex))
break
except jsonschema.exceptions.ValidationError as ex:
# A problem in the settings file for the user to resolve
sublime.error_message("Error in {} in setting '{}': \n{}".format(settingsName, setName, str(ex)))
continue
return validSets if validSets else None
def _write_user_chainload():
# Read settings file and validate
settings = sublime.load_settings(settingsName)
validSets = _validate_settings()
# Prepare output syntax file
cacheDir = os.path.join(sublime.cache_path(), pkgName)
if not os.path.isdir(cacheDir):
os.mkdir(cacheDir)
userSyntaxPath = os.path.join(cacheDir, userSyntaxName)
userSyntaxExists = os.path.isfile(userSyntaxPath)
# Skip writing the syntax if it already exists in a valid form and we don't
# have a valid set of rules for regenerating it
if userSyntaxExists:
if validSets == None:
logger.warning("Not regenerating syntax due to lack of any valid settings")
return
else:
logger.info("Regenerating syntax with sets: {}".format(validSets))
else:
logger.info("Generating syntax with sets: {}".format(validSets))
userSyntax = open(userSyntaxPath, 'w')
# Can't seem to get PyYAML to write a header, so do it manually
header = '\n'.join([
r'%YAML 1.2',
r'# THIS IS AN AUTOMATICALLY GENERATED FILE.',
r'# DO NOT EDIT. CHANGES WILL BE LOST.',
r'---',
'',
])
userSyntax.write(header)
yaml.dump({'hidden': True, 'scope': 'source.shell.execline'}, userSyntax)
# Repeat all the variables from the main syntax file, for convenience
mainDB = yaml.load(sublime.load_resource(mainSyntaxPath),
Loader = yaml.BaseLoader)
yaml.dump({'variables': mainDB['variables']}, userSyntax)
# Create list of rules from the sets of user settings which are currently
# valid
rulesList = []
for rule in [r for s in validSets for r in settings.get(s)]:
# Schema validation guarantees we can trust all the following inputs
# Read a name or list of names
cmdNames = rule['name']
if isinstance(cmdNames, str):
cmdNames = [cmdNames]
# Get type with 'function' being default if not provided
cmdType = rule.get('type', 'function')
cmdElements = []
for elem in rule['elements']:
# Get the sole kv pair, apparently this is most efficient way
key,value = next( iter(elem.items()) )
if key in ruleContexts:
cmdElements.append( (key,value) )
elif 'options_then_' in key:
opts = ''.join( value.get('options_taking_arguments', []) )
if opts:
cmdElements.append( ('options', 'list-with-args', opts) )
else:
cmdElements.append( ('options', 'list') )
then = key.split('_')[-1]
if then == 'end':
# Ignore all further elements
break
else:
# Add the block, etc
cmdElements.append( (then, value[then]) )
for cmdName in cmdNames:
rulesList.append( _make_rule(cmdName, cmdElements, cmdType) )
# Only keep non-empty rules. Sublime doesn't mind if the list of rules ends up
# empty
content = {'contexts': {'main': [r for r in rulesList if r]}}
yaml.dump(content, userSyntax)
def plugin_loaded():
settings = sublime.load_settings(settingsName)
settings.clear_on_change(__name__)
settings.add_on_change(__name__, _write_user_chainload)
if settings.get('user_chainload_debugging'):
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.WARNING)
_write_user_chainload()
| StarcoderdataPython |
11349778 | <filename>No_0993_Cousins in Binary Tree/by_level_order_traversal.py<gh_stars>10-100
'''
Description:
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.
Example 1:
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Note:
The number of nodes in the tree will be between 2 and 100.
Each node has a unique integer value from 1 to 100.
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import namedtuple
# first parameter is parnet node
# second parameter is the level of current node
Entry = namedtuple( 'Entry', 'parent level')
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
# Let general case handle root node
dummy_head = TreeNode(-1)
dummy_head.left = root
traversal_queue = [ (dummy_head, 0) ]
x_info, y_info = None, None
while traversal_queue:
next_level_queue = []
for cur_node, cur_level in traversal_queue:
for child in ( cur_node.left, cur_node.right):
if child:
# update information of parent and level for x and y
if child.val == x:
x_info = Entry( parent = cur_node, level = cur_level+1 )
elif child.val == y:
y_info = Entry( parent = cur_node, level = cur_level+1 )
# update next level traversal queue
next_level_queue.append( (child, cur_level+1) )
traversal_queue = next_level_queue
return (x_info.parent is not y_info.parent) and (x_info.level == y_info.level)
# n : the nubmer of node in binary tree
## Time Complexity: O( n )
#
# The overhead in time is the cost of level-order traversal, which is of O( n ).
## Space Complexity: O( n )
#
# The overhead in space is the storage for traversal queue, which is of O( n ).
from collections import namedtuple
TestEntry = namedtuple('TestEntry', 'root x y')
def test_bench():
root_1 = TreeNode( 1 )
root_1.left = TreeNode( 2 )
root_1.right = TreeNode( 3 )
root_1.left.left = TreeNode( 4 )
x_1, y_1 = 4, 3
# --------------------------------
root_2 = TreeNode( 1 )
root_2.left = TreeNode( 2 )
root_2.right = TreeNode( 3 )
root_2.left.right = TreeNode( 4 )
root_2.right.right = TreeNode( 5 )
x_2, y_2 = 5, 4
# --------------------------------
root_3 = TreeNode( 1 )
root_3.left = TreeNode( 2 )
root_3.right = TreeNode( 3 )
root_3.left.right = TreeNode( 4 )
x_3, y_3 = 2, 3
# --------------------------------
test_data = [
TestEntry( root = root_1, x = x_1, y = y_1 ),
TestEntry( root = root_2, x = x_2, y = y_2 ),
TestEntry( root = root_3, x = x_3, y = y_3 ),
]
# expected output:
'''
False
True
False
'''
for t in test_data:
print( Solution().isCousins( *t ) )
return
if __name__ == '__main__':
test_bench() | StarcoderdataPython |
1867649 | <gh_stars>1-10
import discord
from discord.ext import commands
import youtube_dl
import asyncio
from itertools import cycle
import datetime
from dateutil.relativedelta import relativedelta
import urllib.request
import random
if not discord.opus.is_loaded():
# the 'opus' library here is opus.dll on windows
# or libopus.so on linux in the current directory
# you should replace this with the location the
# opus library is located in and with the proper filename.
# note that on windows this DLL is automatically provided for you
discord.opus.load_opus('opus')
TOKEN = '<KEY>'
ADMIN_ROLE = '547174572731006986', '228677568126124034'
beforeArgs = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"
status = ['Minecraft', 'Roblox', 'Fortnite', 'at the same time...']
jojos = ['https://www.youtube.com/watch?v=tHAGig0Mq6o', 'https://www.youtube.com/watch?v=P-3GOo_nWoc&t=38s',
'https://www.youtube.com/watch?v=ITMjAeWz5hk', 'https://www.youtube.com/watch?v=cPCLFtxpadE',
'https://www.youtube.com/watch?v=NFjE5A4UAJI', 'https://www.youtube.com/watch?v=So54Khf7bB8',
'https://www.youtube.com/watch?v=J69VjA6wUQc',
]
queues, players = {}, {}
#create_ytdl_player(url=self.url, ytdl_options=self.ytdl_format_options, before_options=beforeArgs)
bot = commands.Bot(command_prefix = 'bruh ')
bot.remove_command('help')
def user_is_me(ctx):
return ctx.message.author.id == "2<PASSWORD>"
def check_queue(id):
if queues[id] != []:
player = queues[id].pop(0)
players[id] = player
player.start()
else:
del players[id]
async def change_status():
await bot.wait_until_ready()
msgs = cycle(status)
while not bot.is_closed:
current_status = next(msgs)
await bot.change_presence(game=discord.Game(name=current_status))
await asyncio.sleep(5)
@bot.event
async def on_ready():
print('it seems to be working...')
@bot.event
async def on_message(message):
if 'what\'s' in message.content.lower():
num = random.randint(1,5)
if message.content[7:] == 'ligma' or num == 1:
await bot.send_message(message.channel, message.content[message.content.lower().find('what\'s')+7:] + ' balls\nhttps://i.ytimg.com/vi/ylYqTYJ8vbs/maxresdefault.jpg')
elif message.content[7:] == 'kisma' or num == 2:
await bot.send_message(message.channel, message.content[message.content.lower().find('what\'s')+7:] + ' dick\nhttps://i.ytimg.com/vi/ylYqTYJ8vbs/maxresdefault.jpg')
elif message.content[7:] == 'bofa' or num == 3:
await bot.send_message(message.channel, message.content[message.content.lower().find('what\'s')+7:] + ' deez nuts\nhttps://i.ytimg.com/vi/ylYqTYJ8vbs/maxresdefault.jpg')
elif message.content[7:] == 'candice' or num == 4:
await bot.send_message(message.channel, message.content[message.content.lower().find('what\'s')+7:] + ' dick fit in yo mouth son?\nhttps://i.ytimg.com/vi/ylYqTYJ8vbs/maxresdefault.jpg')
elif message.content[7:] == 'fugma' or num == 5:
await bot.send_message(message.channel, message.content[message.content.lower().find('what\'s')+7:] + ' ass, lil bitch\nhttps://i.ytimg.com/vi/ylYqTYJ8vbs/maxresdefault.jpg')
await bot.process_commands(message)
@bot.command(pass_context=True)
async def help(ctx):
await bot.send_message(ctx.message.author, 'bet')
@bot.command(pass_context=True)
async def cardgame(ctx):
await bot.send_message(ctx.message.author, 'bet')
@bot.command(pass_context=True)
async def clear(ctx, amount=100):
channel = ctx.message.channel
messages = []
async for message in bot.logs_from(channel, limit=int(amount)):
messages.append(message)
await bot.delete_messages(messages)
await bot.say('I\'m still logging all your data lol')
await asyncio.sleep(10)
async for message in bot.logs_from(channel, limit=int(1)):
await bot.delete_messages([message])
@bot.command(pass_context=True)
async def snap(ctx):
channel = ctx.message.channel
messages = []
async for message in bot.logs_from(channel, limit=int(100)):
messages.append(message)
random.shuffle(messages)
await bot.delete_messages(messages[:len(messages)//2])
await bot.say('perfectly balanced\nhttps://media1.tenor.com/images/d89ba4e965cb9144c82348a1c234d425/tenor.gif?itemid=11793362')
@bot.command(pass_context=True)
async def play(ctx, url):
global queue
channel = ctx.message.author.voice.voice_channel
try:
await bot.join_voice_channel(channel)
except:
print('already in voice channel')
server = ctx.message.server
voice_client = bot.voice_client_in(server)
player = await voice_client.create_ytdl_player(url, after=lambda: check_queue(server.id))
if server.id not in players:
players[server.id] = player
player.start()
else:
if server.id in queues:
queues[server.id].append(player)
else:
queues[server.id] = [player]
await bot.say('Queued:\n' + url)
@bot.command(pass_context=True)
async def onjah(ctx):
channel = ctx.message.author.voice.voice_channel
try:
await bot.join_voice_channel(channel)
except:
pass
server = ctx.message.server
voice_client = bot.voice_client_in(server)
if server.id not in players:
player = await voice_client.create_ytdl_player('https://www.youtube.com/watch?v=fGZb5SpRCi0')
players[server.id] = player
player.start()
await bot.say('https://www.pngkey.com/png/detail/486-4869960_xxxtentacion-face-png-xxxtentacion-meme-face.png')
@bot.command(pass_context=True)
async def this(ctx, *args):
check = ''
for word in args:
check += word
if check == 'issosad':
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()
number = random.randint(1, len(words)-1)
if number % 2 == 0:
await bot.say(f'can we hit {number} {words[number]}')
else:
await bot.say(f'can we hit {number} {words[number]} {words[random.randint(1,10000)]}')
@bot.command(pass_context=True)
async def moment(ctx):
channel = ctx.message.author.voice.voice_channel
try:
await bot.join_voice_channel(channel)
except:
pass
server = ctx.message.server
voice_client = bot.voice_client_in(server)
player = await voice_client.create_ytdl_player('https://www.youtube.com/watch?v=2ZIpFytCSVc')
players[server.id] = player
player.start()
@bot.command(pass_context=True)
async def go(ctx, *args):
check = ''
for word in args:
check += word
if check == 'sickomode':
channel = ctx.message.author.voice.voice_channel
try:
await bot.join_voice_channel(channel)
except:
pass
server = ctx.message.server
voice_client = bot.voice_client_in(server)
if server.id not in players:
player = await voice_client.create_ytdl_player('https://www.youtube.com/watch?v=qMc6xlZaxYA')
players[server.id] = player
player.start()
await bot.say('https://media1.giphy.com/media/1oE3Ee4299mmXN8OYb/source.gif')
@bot.command(pass_context=True)
async def jojo(ctx):
channel = ctx.message.author.voice.voice_channel
try:
await bot.join_voice_channel(channel)
except:
pass
server = ctx.message.server
voice_client = bot.voice_client_in(server)
if server.id not in players:
url = jojos[random.randint(0,len(jojos)-1)]
player = await voice_client.create_ytdl_player(url)
players[server.id] = player
player.start()
@bot.command(pass_context=True)
async def finnasmash(ctx):
channel = ctx.message.author.voice.voice_channel
try:
await bot.join_voice_channel(channel)
except:
pass
server = ctx.message.server
voice_client = bot.voice_client_in(server)
if server.id not in players:
player = await voice_client.create_ytdl_player('https://www.youtube.com/watch?v=EhgDibw7vB4')
players[server.id] = player
player.start()
@bot.command(pass_context=True)
async def mutethisbitch(ctx):
pass
@bot.command(pass_context=True)
async def leave(ctx):
global queues
global players
server = ctx.message.server
voice_client = bot.voice_client_in(server)
await voice_client.disconnect()
queues = {}
players = {}
@bot.command(pass_context=True)
async def spam(ctx, *args):
if user_is_me(ctx):
for _ in range(int(args[-1])):
output = ''
for word in args[:-1]:
output += word + ' '
await bot.say(output)
else:
await bot.say('You don\'t have the power, peasant.')
@bot.command(pass_context=True)
async def thatsprettycringe(ctx):
await bot.say('https://i.ytimg.com/vi/ZtFteHYmxuQ/hqdefault.jpg')
@bot.command(pass_context=True)
async def howlong(ctx):
td = relativedelta(datetime.datetime(2020, 12, 11), datetime.datetime.now())
await bot.say(f'<NAME> will be released in {td.years} years, {td.months} months, {td.days} days, {td.hours} hours, {td.minutes} minutes, and {td.seconds} seconds.')
@bot.command(pass_context=True)
async def die(ctx):
if user_is_me(ctx):
await bot.logout()
else:
await bot.say('You cannot kill me, peasant.')
bot.loop.create_task(change_status())
bot.run(TOKEN) | StarcoderdataPython |
3528485 | # -*- coding: utf-8 -*-
import os
import sys
import json
import pkg_resources
from pathlib import Path
import pandas as pd
from findy.utils.log import init_log
sys.setrecursionlimit(1000000)
pd.options.compute.use_bottleneck = True
pd.options.compute.use_numba = False
pd.options.compute.use_numexpr = True
pd.set_option('expand_frame_repr', False)
pd.set_option('mode.chained_assignment', 'raise')
# pd.set_option('display.max_rows', None)
# pd.set_option('display.max_columns', None)
findy_env = {}
findy_config = {}
FINDY_HOME = os.environ.get('FINDY_HOME', os.path.abspath(os.path.join(Path.home(), 'findy-home')))
def init_config(pkg_name: str = None, current_config: dict = None, **kwargs) -> dict:
"""
init config
"""
# create default config.json if not exist
if pkg_name:
config_file = f'{pkg_name}_config.json'
else:
pkg_name = 'findy'
config_file = 'config.json'
config_path = os.path.join(findy_env['findy_home'], config_file)
if not os.path.exists(config_path):
from shutil import copyfile
try:
sample_config = pkg_resources.resource_filename(pkg_name, 'config.json')
if os.path.exists(sample_config):
copyfile(sample_config, config_path)
except Exception as e:
print(f'could not load config.json from package {pkg_name}')
raise e
if os.path.exists(config_path):
with open(config_path) as f:
config_json = json.load(f)
for k in config_json:
current_config[k] = config_json[k]
# set and save the config
for k in kwargs:
current_config[k] = kwargs[k]
with open(config_path, 'w+') as outfile:
json.dump(current_config, outfile)
return current_config
def init_env(findy_home: str, **kwargs) -> dict:
findy_env['findy_home'] = findy_home
# path for storing cache
findy_env['log_path'] = os.path.join(findy_home, 'logs')
os.makedirs(findy_env['log_path'], exist_ok=True)
# path for storing cache
findy_env['cache_path'] = os.path.join(findy_home, 'cache')
os.makedirs(findy_env['cache_path'], exist_ok=True)
# path for storing cache
findy_env['out_path'] = os.path.join(findy_home, 'out')
os.makedirs(findy_env['out_path'], exist_ok=True)
# path for 3th-party source
findy_env['source_path'] = os.path.join(findy_home, 'source')
os.makedirs(findy_env['source_path'], exist_ok=True)
# init config
init_config(current_config=findy_config, **kwargs)
init_log(findy_env['log_path'], debug_mode=findy_config['debug'])
return findy_env
init_env(findy_home=FINDY_HOME)
import findy.database.plugins as findy_plugins
__all__ = ['findy_plugins']
| StarcoderdataPython |
3434272 | """
Maximum density still life in cpmpy.
CSPLib 032: http://www.csplib.org/prob/prob032
'''
Proposed by <NAME>
This problem arises from the Game of Life, invented by <NAME> in the 1960s and
popularized by <NAME> in his Scientific American columns.
Life is played on a squared board, considered to extend to infinity in all directions. Each
square of the board is a cell, which at any time during the game is either alive or dead.
A cell has eight neighbours:
Magic Hexagon
The configuration of live and dead cells at time t leads to a new configuration at time
t+1 according to the rules of the game:
* if a cell has exactly three living neighbours at time t, it is alive at time t+1
* if a cell has exactly two living neighbours at time t it is in the same state at time
t+1 as it was at time t
* otherwise, the cell is dead at time t+1
A stable pattern, or still-life, is not changed by these rules. Hence, every cell that
has exactly three live neighbours is alive, and every cell that has fewer than two or
more than three live neighbours is dead. (An empty board is a still-life, for instance.)
What is the densest possible still-life pattern, i.e. the pattern with the largest
number of live cells, that can be fitted into an n x n section of the board, with all the
rest of the board dead?
(Note that another definition of a still-life requires the pattern to be a single object -
see for instance Mark Niemiec’s Definitions of Life Terms page. On this definition,
the 8 x 8 pattern below is a pseudo still-life.)
'''
This model (or rather my earlier MiniZinc and Comet models)
was inspired by the OPL model by
<NAME>, <NAME>, <NAME>, <NAME>:
'Evaluating ASP and commercial solvers on the CSPLib'
http://www.dis.uniroma1.it/~tmancini/index.php?problemid=032&solver=OPL&spec=BASE&currItem=research.publications.webappendices.csplib2x.problemDetails#listing
(The comments of the constraints etc are from this as well.)
Model created by <NAME>, <EMAIL>
See also my cpmpy page: http://www.hakank.org/cpmpy/
"""
import sys,math
import numpy as np
from cpmpy import *
from cpmpy.solvers import *
from cpmpy_hakank import *
from itertools import combinations
def maximum_density_still_life(size=6,num_procs=1):
grid_size = size+4
# Search space: The set of all possible assignments of 0s (dead) and 1s (live)
# to the cells of the board section. However, to be able to easily express
# constraints on "boundary" cells, we take as search space the set of 0/1
# boards of size n+4 by n+4: the actual stable pattern appears in the sub-board
# defined by ignoring the first/last two rows/columns.
grid = boolvar(shape=(grid_size,grid_size),name="grid")
# Objective function: Maximize the number of live cells in the sub-board defined
# by ignoring the first/last two/ rows/columns.
z = intvar(0,grid_size**2,name="z")
model = Model([z == sum([grid[i,j] for i in range(2,size+1+1) for j in range(2,size+1+1)])])
# C1: Cells in the first/last two rows/columns are all 0 (dead)
for i in range(grid_size):
model += (grid[0,i] == 0)
model += (grid[1,i] == 0)
model += (grid[size+2,i] == 0)
model += (grid[size+3,i] == 0)
model += (grid[i,0] == 0)
model += (grid[i,1] == 0)
model += (grid[i,size+2] == 0)
model += (grid[i,size+3] == 0)
for r in range(1,size+2+1):
for c in range(1,size+2+1):
# C2: Each cell of the board (except those of the first/last row/column)
# that has exactly three live neighbors is alive.
# Together with constraint C1, this implies that cells in the
# second/last-but-one row/column cannot have three live neighbors.
model += (( ( grid[r-1,c-1] + grid[r-1,c] + grid[r-1,c+1] +
grid[r,c-1] + grid[r,c+1] +
grid[r+1,c-1] + grid[r+1,c] + grid[r+1,c+1]
) == 3
).implies(grid[r,c] == 1))
# C3: Each live cell must have 2 or 3 live neighbors (cells of the first/last
# row/column may be ignored by this constraint)
model += ((grid[r,c] == 1).implies(
(2 <=
( grid[r-1,c-1] + grid[r-1,c] + grid[r-1,c+1] +
grid[r,c-1] + grid[r,c+1] +
grid[r+1,c-1] + grid[r+1,c] + grid[r+1,c+1]
))
&
(( grid[r-1,c-1] + grid[r-1,c] + grid[r-1,c+1] +
grid[r,c-1] + grid[r,c+1] +
grid[r+1,c-1] + grid[r+1,c] + grid[r+1,c+1]
) <= 3)
))
# SBSO: Symmetry-breaking by selective ordering
# The assignment is forced to respect an ordering on the values that occur in corner entries
# of the board. In particular:
# - if the NW-corner cell is dead, the SE-corner cell
# must be dead too
# - if the NE-corner cell is dead, the SW-corner cell must be dead too
#
model += (grid[2,2] >= grid[size+1,size+1])
model += (grid[2,size+1] >= grid[size+1,2])
model.maximize(z)
num_solutions = 0
ss = CPM_ortools(model)
ss.ort_solver.parameters.num_search_workers = num_procs # Don't work together with SearchForAllSolutions
ss.ort_solver.parameters.search_branching = ort.PORTFOLIO_SEARCH
# ss.ort_solver.parameters.cp_model_presolve = False
# ss.ort_solver.parameters.linearization_level = 0
# ss.ort_solver.parameters.cp_model_probing_level = 0
if ss.solve():
num_solutions += 1
print("z:",z.value())
print("grid:")
print(grid.value())
print()
print("Num conflicts:", ss.ort_solver.NumConflicts())
print("NumBranches:", ss.ort_solver.NumBranches())
print("WallTime:", ss.ort_solver.WallTime())
print()
print("number of solutions:", num_solutions)
num_procs = 14
for size in range(1,15):
print("\nsize:",size)
maximum_density_still_life(size,num_procs)
| StarcoderdataPython |
11266377 | <gh_stars>0
# Given an integer n, return the number of trailing zeroes in n!.
# Must be logarithmic time complexity.
class Solution:
# @return an integer
def trailingZeroes(self, n):
if n < 5:
return 0
else:
new_num = n // 5
return new_num + self.trailingZeroes(new_num) | StarcoderdataPython |
1984808 | <filename>main.py
from rnn import RNN as Rnn
import numpy as np
from dataset import Dataset
def run_language_model(dataset, max_epochs, hidden_size=100, sequence_length=30, learning_rate=1e-1, sample_every=100):
vocab_size = len(dataset.sorted_chars)
RNN = Rnn(vocab_size, hidden_size, sequence_length, learning_rate) # initialize the recurrent network
current_epoch = 0
batch = 0
#h0 = np.zeros((hidden_size, dataset.batch_size))
h0 = np.zeros((dataset.batch_size, hidden_size))
#TODO
seed = "HAN:\nIs that good or bad?\n\n" #"Lorem ipsum"#
n_sample = 300
average_loss = 0
while current_epoch < max_epochs:
e, x, y = dataset.next_minibatch()
if e:
current_epoch += 1
#h0 = np.zeros((hidden_size, dataset.batch_size))
h0 = np.zeros((dataset.batch_size, hidden_size))
# why do we reset the hidden state here?
# One-hot transform the x and y batches
x_oh, y_oh = dataset.one_hot(x, vocab_size), dataset.one_hot(y, vocab_size)
# Run the recurrent network on the current batch
# Since we are using windows of a short length of characters,
# the step function should return the hidden state at the end
# of the unroll. You should then use that hidden state as the
# input for the next minibatch. In this way, we artificially
# preserve context between batches.
loss, h0 = RNN.step(h0, x_oh, y_oh)
average_loss += loss
if batch % sample_every == 0:
# run sampling (2.2)
print("epoch: %d \t batch: %d/%d \t"%(current_epoch, batch%dataset.num_batches, dataset.num_batches), end="")
print("Average_loss : %f" % (average_loss/(batch*dataset.batch_size)))
print(sample(RNN, seed, n_sample, dataset))
batch += 1
def sample(rnn, seed, n_sample, dataset):
#h0, seed_onehot, samp = np.zeros([rnn.hidden_size, 1]), dataset.one_hot(dataset.encode(seed), rnn.vocab_size), []
h0, seed_onehot, samp = np.zeros([1, rnn.hidden_size]), dataset.one_hot(dataset.encode(seed), rnn.vocab_size), []
# inicijalizirati h0 na vektor nula
# seed string pretvoriti u one-hot reprezentaciju ulaza
for i in range(n_sample):
if i >= len(seed):
h0, _ = rnn.rnn_step_forward(dataset.one_hot(np.array([samp[-1]]), rnn.vocab_size), h0, rnn.U, rnn.W, rnn.b)
else:
h0, _ = rnn.rnn_step_forward(seed_onehot[i].reshape([1, -1]), h0, rnn.U, rnn.W, rnn.b)
samp.append(np.argmax(rnn.output(h0, rnn.V, rnn.c)))
return dataset.decode(samp)#"".join(dataset.decode(samp))
def main():
#TODO
dataset = Dataset(30, 15)
dataset.preprocess("data/selected_conversations.txt")
dataset.create_minibatches()
run_language_model(dataset, 100000, sequence_length=dataset.sequence_length)
if __name__ == '__main__':
main()
| StarcoderdataPython |
324491 | <gh_stars>1-10
'''
Created on Sep 21, 2017
@author: <NAME>
'''
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from Video3_MainWindow_Complex_7_FINAL_UI import Ui_MainWindow
class MainWindow_EXEC():
def __init__(self):
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(MainWindow)
self.update_tree()
MainWindow.show()
sys.exit(app.exec_())
def update_tree(self):
self.print_tree()
self.ui.treeWidget.headerItem().setText(1, 'Header 2')
self.print_tree()
def print_tree(self):
header0 = self.ui.treeWidget.headerItem().text(0)
header1 = self.ui.treeWidget.headerItem().text(1)
print(header0 + '\n' + header1 + '\n')
def update_calendar(self):
pass
def update_progressbar(self):
pass
if __name__ == "__main__":
MainWindow_EXEC()
| StarcoderdataPython |
4860649 | <reponame>alex/effect
"""
A system for helping you separate your IO and state-manipulation code
(hereafter referred to as "effects") from everything else, thus allowing
the majority of your code to be trivially testable and composable (that is,
have the general benefits of purely functional code).
TODO: an effect implementation of ParallelEffects that uses threads?
TODO: an effect implementation of ParallelEffects that is actually serial,
as a fallback?
TODO: integration with other asynchronous libraries like asyncio, trollius,
eventlet
"""
from __future__ import print_function
import sys
import six
from .continuation import trampoline
class Effect(object):
"""
Wrap an object that describes how to perform some effect (called an
"intent"), and allow attaching callbacks to be run when the effect
is complete.
(You're an object-oriented programmer.
You probably want to subclass this.
Don't.)
"""
def __init__(self, intent, callbacks=None):
"""
:param intent: An object that describes an effect to be
performed. Optionally has a perform_effect(dispatcher, box) method.
"""
self.intent = intent
if callbacks is None:
callbacks = []
self.callbacks = callbacks
def on_success(self, callback):
"""
Return a new Effect that will invoke the associated callback when this
Effect completes succesfully.
"""
return self.on(success=callback, error=None)
def on_error(self, callback):
"""
Return a new Effect that will invoke the associated callback when this
Effect fails.
The callback will be invoked with the sys.exc_info() exception tuple
as its only argument. Note that sometimes the third element in the
tuple, the traceback, may sometimes be None.
"""
return self.on(success=None, error=callback)
def after(self, callback):
"""
Return a new Effect that will invoke the associated callback when this
Effect completes, whether successfully or in error.
"""
return self.on(success=callback, error=callback)
def on(self, success, error):
"""
Return a new Effect that will invoke either the success or error
callbacks provided based on whether this Effect completes sucessfully
or in error.
"""
return Effect(self.intent,
callbacks=self.callbacks + [(success, error)])
def __repr__(self):
return "Effect(%r, callbacks=%s)" % (self.intent, self.callbacks)
def dispatch_method(intent, dispatcher):
"""
Call intent.perform_effect with the given dispatcher and box.
Raise NoEffectHandlerError if there's no perform_effect method.
"""
if hasattr(intent, 'perform_effect'):
return intent.perform_effect(dispatcher)
raise NoEffectHandlerError(intent)
def default_dispatcher(intent, box):
"""
This is the default dispatcher used by :func:`perform`.
If the intent has a 'perform_effect' method, invoke it with this
function as an argument. Its result will be passed to the first callback
on the effect.
If the perform_effect method can't be found, raise NoEffectHandlerError.
If you're using Twisted Deferreds, you should look at
:func:`effect.twisted.twisted_dispatcher`.
"""
try:
box.succeed(dispatch_method(intent, default_dispatcher))
except:
box.fail(sys.exc_info())
class _Box(object):
"""
An object into which an effect dispatcher can place a result.
"""
def __init__(self, bouncer, more):
self._bouncer = bouncer
self._more = more
def succeed(self, result):
"""
Indicate that the effect has succeeded, and the result is available.
"""
self._bouncer.bounce(self._more, (False, result))
def fail(self, result):
"""
Indicate that the effect has failed to be met. result must be an
exc_info tuple.
"""
self._bouncer.bounce(self._more, (True, result))
def perform(effect, dispatcher=default_dispatcher):
"""
Perform an effect by invoking the dispatcher, and invoke callbacks
associated with it.
The dispatcher will be passed a "box" argument and the intent. The box
is an object that lets the dispatcher specify the result (optionally
asynchronously). See :func:`_Box.succeed` and :func:`_Box.fail`.
Note that this function does _not_ return the final result of the effect.
You may instead want to use :func:`sync_perform` or
:func:`effect.twisted.perform`.
:returns: None
"""
def _run_callbacks(bouncer, chain, result):
is_error, value = result
if type(value) is Effect:
bouncer.bounce(
_perform,
Effect(value.intent, callbacks=value.callbacks + chain))
return
if not chain:
return
cb = chain[0][is_error]
if cb is not None:
result = guard(cb, value)
chain = chain[1:]
bouncer.bounce(_run_callbacks, chain, result)
def _perform(bouncer, effect):
dispatcher(
effect.intent,
_Box(bouncer,
lambda bouncer, result:
_run_callbacks(bouncer, effect.callbacks, result)))
trampoline(_perform, effect)
def guard(f, *args, **kwargs):
"""
Run a function.
Return (is_error, result), where is_error is a boolean indicating whether
it raised an exception. In that case result will be sys.exc_info().
"""
try:
return (False, f(*args, **kwargs))
except:
return (True, sys.exc_info())
class NoEffectHandlerError(Exception):
"""
No perform_effect method was found on the given intent.
"""
class ParallelEffects(object):
"""
An effect intent that asks for a number of effects to be run in parallel,
and for their results to be gathered up into a sequence.
The default implementation of this effect relies on Twisted's Deferreds.
An alternative implementation can run the child effects in threads, for
example. Of course, the implementation strategy for this effect will need
to cooperate with the effects being parallelized -- there's not much use
running a Deferred-returning effect in a thread.
"""
def __init__(self, effects):
self.effects = effects
def __repr__(self):
return "ParallelEffects(%r)" % (self.effects,)
def parallel(effects):
"""
Given multiple Effects, return one Effect that represents the aggregate of
all of their effects.
The result of the aggregate Effect will be a list of their results, in
the same order as the input to this function.
"""
return Effect(ParallelEffects(list(effects)))
class NotSynchronousError(Exception):
"""Performing an effect did not immediately return a value."""
def sync_perform(effect, dispatcher=default_dispatcher):
"""
Perform an effect, and return its ultimate result. If the final result is
an error, the exception will be raised. This is useful for testing, and
also if you're using blocking effect implementations.
This requires that the effect (and all effects returned from any of its
callbacks) to be synchronous. If this is not the case, NotSynchronousError
will be raised.
"""
successes = []
errors = []
def success(x):
successes.append(x)
def error(x):
errors.append(x)
effect = effect.on(success=success, error=error)
perform(effect, dispatcher=dispatcher)
if successes:
return successes[0]
elif errors:
six.reraise(*errors[0])
else:
raise NotSynchronousError("Performing %r was not synchronous!"
% (effect,))
| StarcoderdataPython |
5199537 | #!/usr/bin/env python
import os
import sys
import yaml
def dir_to_dict(path):
directory = {}
for dirname, dirnames, filenames in os.walk(path):
dn = os.path.basename(dirname)
directory[dn] = []
if dirnames:
for d in dirnames:
directory[dn].append(dir_to_dict(path=os.path.join(path, d)))
for f in filenames:
directory[dn].append(f)
else:
directory[dn] = filenames
return directory
if len(sys.argv) == 1:
p = os.getcwd()
elif len(sys.argv) == 2:
p = os.path.abspath(sys.argv[1])
else:
sys.stderr.write("Unexpected argument {}\n".format(sys.argv[2:]))
try:
with open("{}.yaml".format(os.path.basename(p)), "w") as f:
try:
yaml.dump(dir_to_dict(path=p), f, default_flow_style=False)
print("Dictionary written to {}.yaml".format(os.path.basename(p)))
except Exception as e:
print(e)
except Exception as e:
print(e)
| StarcoderdataPython |
5097696 | """AVM Fritz!Box connectivitiy sensor."""
from collections import defaultdict
import datetime
import logging
try:
from homeassistant.components.binary_sensor import (
ENTITY_ID_FORMAT,
BinarySensorEntity,
)
except ImportError:
from homeassistant.components.binary_sensor import (
ENTITY_ID_FORMAT,
BinarySensorDevice as BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.const import CONF_HOST
from .const import DATA_FRITZ_TOOLS_INSTANCE, DOMAIN
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = datetime.timedelta(seconds=60)
async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up entry."""
_LOGGER.debug("Setting up sensors")
fritzbox_tools = hass.data[DOMAIN][DATA_FRITZ_TOOLS_INSTANCE][entry.data.get(CONF_HOST)]
if "WANIPConn1" in fritzbox_tools.connection.services:
""" We do not support repeaters at the moment """
async_add_entities([FritzBoxConnectivitySensor(fritzbox_tools)], True)
return True
class FritzBoxConnectivitySensor(BinarySensorEntity):
"""Define Fritzbox connectivity class."""
name = "FRITZ!Box Connectivity"
icon = "mdi:router-wireless"
device_class = "connectivity"
def __init__(self, fritzbox_tools):
"""Init Fritzbox connectivity class."""
self.fritzbox_tools = fritzbox_tools
self.entity_id = ENTITY_ID_FORMAT.format(
f"fritzbox_{self.fritzbox_tools.fritzbox_model}_connectivity"
)
self._is_on = True # We assume the fritzbox to be online initially
self._is_available = (
True # set to False if an error happened during toggling the switch
)
self._attributes = defaultdict(str)
super().__init__()
@property
def is_on(self) -> bool:
"""Return status."""
return self._is_on
@property
def unique_id(self):
"""Return unique id."""
return f"{self.fritzbox_tools.unique_id}-{self.entity_id}"
@property
def device_info(self):
"""Return device info."""
return self.fritzbox_tools.device_info
@property
def available(self) -> bool:
"""Return availability."""
return self._is_available
@property
def device_state_attributes(self) -> dict:
"""Return device attributes."""
return self._attributes
def _connection_call_action(self):
return lambda: self.fritzbox_tools.connection.call_action(
"WANCommonInterfaceConfig1", "GetCommonLinkProperties"
)["NewPhysicalLinkStatus"]
async def _async_fetch_update(self):
"""Fetch updates."""
self._is_on = True
try:
if "WANCommonInterfaceConfig1" in self.fritzbox_tools.connection.services:
connection = self._connection_call_action()
is_up = await self.hass.async_add_executor_job(connection)
self._is_on = is_up == "Up"
else:
self._is_on = self.hass.async_add_executor_job(
self.fritzbox_tools.fritzstatus.is_connected
)
self._is_available = True
status = self.fritzbox_tools.fritzstatus
uptime_seconds = await self.hass.async_add_executor_job(
lambda: getattr(status, "uptime")
)
last_reconnect = datetime.datetime.now() - datetime.timedelta(
seconds=uptime_seconds
)
self._attributes["last_reconnect"] = last_reconnect.replace(
microsecond=0
).isoformat()
for attr in [
"modelname",
"external_ip",
"external_ipv6",
]:
self._attributes[attr] = await self.hass.async_add_executor_job(
lambda: getattr(status, attr)
)
except Exception:
_LOGGER.error("Error getting the state from the FRITZ!Box", exc_info=True)
self._is_available = False
async def async_update(self) -> None:
"""Update data."""
_LOGGER.debug("Updating Connectivity sensor...")
await self._async_fetch_update()
| StarcoderdataPython |
1905982 | <filename>transformations2log/__init__.py
from transformations2log.transformations2log import transformations2log
| StarcoderdataPython |
4866237 | def sample_trajectories_train(env, N, m, l, g, build_dics_func):
dicts_in_static = []
dicts_in_dynamic = []
dicts_out_static = []
dicts_out_dynamic = []
state = env.reset()
while (len(dicts_in_static) < N):
for i in range(100):
action = env.action_space.sample()
next_state, _, done, _ = env.step(action)
dict_in_static, dict_in_dynamic = build_dics_func(m, l, g, state, action)
dict_out_static, dict_out_dynamic = build_dics_func(m, l, g, next_state, action)
for key in ["nodes","globals"]:
dict_out_static[key] -= dict_in_static[key]
dict_out_dynamic[key] -= dict_in_dynamic[key]
dicts_in_static.append( dict_in_static )
dicts_in_dynamic.append( dict_in_dynamic )
dicts_out_static.append( dict_out_static )
dicts_out_dynamic.append( dict_out_dynamic )
state = next_state
if done or len(dicts_in_static) == N:
break
return dicts_in_static, dicts_in_dynamic, dicts_out_static, dicts_out_dynamic
def sample_trajectories_test(env, N, m, l, g, build_dics_func):
dicts_in_static = []
dicts_in_dynamic = []
dicts_out_static = []
dicts_out_dynamic = []
state = env.reset()
while (len(dicts_in_static) < N):
for i in range(N):
action = env.action_space.sample()
next_state, _, done, _ = env.step(action)
dict_in_static, dict_in_dynamic = build_dics_func(m, l, g, state, action)
dict_out_static, dict_out_dynamic = build_dics_func(m, l, g, next_state, action)
dicts_in_static.append( dict_in_static )
dicts_in_dynamic.append( dict_in_dynamic )
dicts_out_static.append( dict_out_static )
dicts_out_dynamic.append( dict_out_dynamic )
state = next_state
if done or len(dicts_in_static) == N:
return dicts_in_static, dicts_in_dynamic, dicts_out_static, dicts_out_dynamic
return dicts_in_static, dicts_in_dynamic, dicts_out_static, dicts_out_dynamic
| StarcoderdataPython |
4921821 | from Layers import Layer, EntityLayer
import Things
from Lib import Gen,Vector
import itertools
from random import sample
V=Vector.Vector2
exghosts=[Things.Lazy,Things.Clyde,Things.Crazy]
class Level(object):
backcol=(0,0,0)
scale=1
cpairs=[("Enemies","Players"),("Dots","Players")]
jscores=None
def __init__(self,size,walls=None):
self.size=size*2-Vector.Vector2(1,1)
self.basesize=size
self.objs=set()
self.layers=[Layer(0,"Walls"),EntityLayer(0,"Dots"),EntityLayer(0,"Enemies"),EntityLayer(0,"Players")]
self.ldict = {l.name: l for l in self.layers}
if walls:
self["Walls"].objs=walls
self["Walls"].fix(Vector.zero,self.size,self)
else:
self.regen()
self.rs=self.scale*16+16
def __getitem__(self, item):
return self.ldict[item]
def spawn(self,nobj,pos):
for l in nobj.layers:
self.ldict[l][pos]=nobj
if nobj.updates:
self.objs.add((pos,nobj))
def dest(self,layer,pos):
tobj=self.ldict[layer][pos]
self.dobj(tobj,pos)
def dobj(self,obj,pos):
if obj:
for l in obj.layers:
self.ldict[l].del_obj(pos)
if (pos,obj) in self.objs:
self.objs.remove((pos,obj))
def move(self,obj,pos,d):
if self.solid(pos+d):
return False
for l in obj.layers:
if self.ldict[l][pos+d]:
return False
self.dobj(obj,pos)
self.spawn(obj,pos+d)
obj.moveoff=-d
obj.mprog=self.rs
return True
def render(self,surf):
for l in self.layers:
l.render(surf,Vector.zero,self.size,self)
def update(self,events):
for p,o in set(self.objs):
o.update(p,self,events)
o.mupdate(p,self,events)
for l,ol in self.cpairs:
for p,o in ((q,x) for q,x in self[l].objs.items() if x):
self[ol].collide(self,p,o.rect.move((p*self.rs+o.moveoff).tuple),l,o)
def regen(self):
self["Walls"].reset()
for p,x in Gen.gen_good_maze(self.basesize).iteritems():
if x:
self.spawn(Things.Wall(),p)
for p,o in self["Walls"].objs.iteritems():
o.gen_img(p,self)
self["Walls"].fix(Vector.zero,self.size,self)
def solid(self,pos):
return not pos.within(self.size) or self["Walls"][pos]
def mirrored_pos(self,p):
return {p,V(self.size.x-p.x-1,p.y),V(p.x,self.size.y-p.y-1),V(self.size.x-p.x-1,self.size.y-p.y-1)}
def prepare(self,js):
spos=[]
aspos=[]
for n in range(self.size.y//2):
if not self.solid(V(n,n)):
spos.extend(self.mirrored_pos(V(n,n)))
for n,j in enumerate(js):
self.spawn(Things.Pacman(j),spos[n])
aspos.append(spos[n])
gpos=[]
for n in range(self.size.y//2):
if not self.solid(self.size//2-V(n,n)):
gpos.extend(self.mirrored_pos(self.size//2-V(n,n)))
for n,g in enumerate(self.get_ghosts(max(len(js)-2,0))):
self.spawn(g(),gpos[n])
for p in self.size.iter_locs():
if p not in aspos and not self.solid(p):
self.spawn(Things.Dot(),p)
self.jscores={j:0 for j in js}
def iter_pon(self,name):
for p,o in self.objs:
if o.name==name:
yield p,o
def get_ghosts(self,extra):
return [Things.Blinky,Things.Hood,Things.Pincer,Things.Hazy]+sample(exghosts,extra)
@property
def done(self):
return self.jscores and all(self.jscores.itervalues())
| StarcoderdataPython |
3289541 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
""" A WebIDL parser. """
from ply import lex, yacc
import re
import os
import traceback
# Machinery
def parseInt(literal):
string = literal
sign = 0
base = 0
if string[0] == '-':
sign = -1
string = string[1:]
else:
sign = 1
if string[0] == '0' and len(string) > 1:
if string[1] == 'x' or string[1] == 'X':
base = 16
string = string[2:]
else:
base = 8
string = string[1:]
else:
base = 10
value = int(string, base)
return value * sign
# Magic for creating enums
def M_add_class_attribs(attribs):
def foo(name, bases, dict_):
for v, k in enumerate(attribs):
dict_[k] = v
assert 'length' not in dict_
dict_['length'] = len(attribs)
return type(name, bases, dict_)
return foo
def enum(*names):
class Foo(object):
__metaclass__ = M_add_class_attribs(names)
def __setattr__(self, name, value): # this makes it read-only
raise NotImplementedError
return Foo()
class WebIDLError(Exception):
def __init__(self, message, locations, warning=False):
self.message = message
self.locations = [str(loc) for loc in locations]
self.warning = warning
def __str__(self):
return "%s: %s%s%s" % (self.warning and 'warning' or 'error',
self.message,
", " if len(self.locations) != 0 else "",
"\n".join(self.locations))
class Location(object):
def __init__(self, lexer, lineno, lexpos, filename):
self._line = None
self._lineno = lineno
self._lexpos = lexpos
self._lexdata = lexer.lexdata
self._file = filename if filename else "<unknown>"
def __eq__(self, other):
return self._lexpos == other._lexpos and \
self._file == other._file
def filename(self):
return self._file
def resolve(self):
if self._line:
return
startofline = self._lexdata.rfind('\n', 0, self._lexpos) + 1
endofline = self._lexdata.find('\n', self._lexpos, self._lexpos + 80)
if endofline != -1:
self._line = self._lexdata[startofline:endofline]
else:
self._line = self._lexdata[startofline:]
self._colno = self._lexpos - startofline
# Our line number seems to point to the start of self._lexdata
self._lineno += self._lexdata.count('\n', 0, startofline)
def get(self):
self.resolve()
return "%s line %s:%s" % (self._file, self._lineno, self._colno)
def _pointerline(self):
return " " * self._colno + "^"
def __str__(self):
self.resolve()
return "%s line %s:%s\n%s\n%s" % (self._file, self._lineno, self._colno,
self._line, self._pointerline())
class BuiltinLocation(object):
def __init__(self, text):
self.msg = text + "\n"
def __eq__(self, other):
return isinstance(other, BuiltinLocation) and \
self.msg == other.msg
def filename(self):
return '<builtin>'
def resolve(self):
pass
def get(self):
return self.msg
def __str__(self):
return self.get()
# Data Model
class IDLObject(object):
def __init__(self, location):
self.location = location
self.userData = dict()
def filename(self):
return self.location.filename()
def isInterface(self):
return False
def isEnum(self):
return False
def isCallback(self):
return False
def isType(self):
return False
def isDictionary(self):
return False;
def isUnion(self):
return False
def getUserData(self, key, default):
return self.userData.get(key, default)
def setUserData(self, key, value):
self.userData[key] = value
def addExtendedAttributes(self, attrs):
assert False # Override me!
def handleExtendedAttribute(self, attr):
assert False # Override me!
class IDLScope(IDLObject):
def __init__(self, location, parentScope, identifier):
IDLObject.__init__(self, location)
self.parentScope = parentScope
if identifier:
assert isinstance(identifier, IDLIdentifier)
self._name = identifier
else:
self._name = None
self._dict = {}
def __str__(self):
return self.QName()
def QName(self):
if self._name:
return self._name.QName() + "::"
return "::"
def ensureUnique(self, identifier, object):
"""
Ensure that there is at most one 'identifier' in scope ('self').
Note that object can be None. This occurs if we end up here for an
interface type we haven't seen yet.
"""
assert isinstance(identifier, IDLUnresolvedIdentifier)
assert not object or isinstance(object, IDLObjectWithIdentifier)
assert not object or object.identifier == identifier
if identifier.name in self._dict:
if not object:
return
# ensureUnique twice with the same object is not allowed
assert object != self._dict[identifier.name]
replacement = self.resolveIdentifierConflict(self, identifier,
self._dict[identifier.name],
object)
self._dict[identifier.name] = replacement
return
assert object
self._dict[identifier.name] = object
def resolveIdentifierConflict(self, scope, identifier, originalObject, newObject):
if isinstance(originalObject, IDLExternalInterface) and \
isinstance(newObject, IDLExternalInterface) and \
originalObject.identifier.name == newObject.identifier.name:
return originalObject
# Default to throwing, derived classes can override.
conflictdesc = "\n\t%s at %s\n\t%s at %s" % \
(originalObject, originalObject.location, newObject, newObject.location)
raise WebIDLError(
"Multiple unresolvable definitions of identifier '%s' in scope '%s%s"
% (identifier.name, str(self), conflictdesc), [])
def _lookupIdentifier(self, identifier):
return self._dict[identifier.name]
def lookupIdentifier(self, identifier):
assert isinstance(identifier, IDLIdentifier)
assert identifier.scope == self
return self._lookupIdentifier(identifier)
class IDLIdentifier(IDLObject):
def __init__(self, location, scope, name):
IDLObject.__init__(self, location)
self.name = name
assert isinstance(scope, IDLScope)
self.scope = scope
def __str__(self):
return self.QName()
def QName(self):
return self.scope.QName() + self.name
def __hash__(self):
return self.QName().__hash__()
def __eq__(self, other):
return self.QName() == other.QName()
def object(self):
return self.scope.lookupIdentifier(self)
class IDLUnresolvedIdentifier(IDLObject):
def __init__(self, location, name, allowDoubleUnderscore = False,
allowForbidden = False):
IDLObject.__init__(self, location)
assert len(name) > 0
if name[:2] == "__" and not allowDoubleUnderscore:
raise WebIDLError("Identifiers beginning with __ are reserved",
[location])
if name[0] == '_' and not allowDoubleUnderscore:
name = name[1:]
if name in ["prototype", "constructor", "toString"] and not allowForbidden:
raise WebIDLError("Cannot use reserved identifier '%s'" % (name),
[location])
self.name = name
def __str__(self):
return self.QName()
def QName(self):
return "<unresolved scope>::" + self.name
def resolve(self, scope, object):
assert isinstance(scope, IDLScope)
assert not object or isinstance(object, IDLObjectWithIdentifier)
assert not object or object.identifier == self
scope.ensureUnique(self, object)
identifier = IDLIdentifier(self.location, scope, self.name)
if object:
object.identifier = identifier
return identifier
def finish(self):
assert False # Should replace with a resolved identifier first.
class IDLObjectWithIdentifier(IDLObject):
def __init__(self, location, parentScope, identifier):
IDLObject.__init__(self, location)
assert isinstance(identifier, IDLUnresolvedIdentifier)
self.identifier = identifier
if parentScope:
self.resolve(parentScope)
self.treatNullAs = "Default"
self.treatUndefinedAs = "Default"
def resolve(self, parentScope):
assert isinstance(parentScope, IDLScope)
assert isinstance(self.identifier, IDLUnresolvedIdentifier)
self.identifier.resolve(parentScope, self)
def checkForStringHandlingExtendedAttributes(self, attrs,
isDictionaryMember=False,
isOptional=False):
"""
A helper function to deal with TreatNullAs and TreatUndefinedAs. Returns the list
of attrs it didn't handle itself.
"""
assert isinstance(self, IDLArgument) or isinstance(self, IDLAttribute)
unhandledAttrs = list()
for attr in attrs:
if not attr.hasValue():
unhandledAttrs.append(attr)
continue
identifier = attr.identifier()
value = attr.value()
if identifier == "TreatNullAs":
if not self.type.isString() or self.type.nullable():
raise WebIDLError("[TreatNullAs] is only allowed on "
"arguments or attributes whose type is "
"DOMString",
[self.location])
if isDictionaryMember:
raise WebIDLError("[TreatNullAs] is not allowed for "
"dictionary members", [self.location])
if value != 'EmptyString':
raise WebIDLError("[TreatNullAs] must take the identifier "
"'EmptyString', not '%s'" % value,
[self.location])
self.treatNullAs = value
elif identifier == "TreatUndefinedAs":
if not self.type.isString():
raise WebIDLError("[TreatUndefinedAs] is only allowed on "
"arguments or attributes whose type is "
"DOMString or DOMString?",
[self.location])
if isDictionaryMember:
raise WebIDLError("[TreatUndefinedAs] is not allowed for "
"dictionary members", [self.location])
if value == 'Null':
if not self.type.nullable():
raise WebIDLError("[TreatUndefinedAs=Null] is only "
"allowed on arguments whose type is "
"DOMString?", [self.location])
elif value == 'Missing':
if not isOptional:
raise WebIDLError("[TreatUndefinedAs=Missing] is only "
"allowed on optional arguments",
[self.location])
elif value != 'EmptyString':
raise WebIDLError("[TreatUndefinedAs] must take the "
"identifiers EmptyString or Null or "
"Missing", [self.location])
self.treatUndefinedAs = value
else:
unhandledAttrs.append(attr)
return unhandledAttrs
class IDLObjectWithScope(IDLObjectWithIdentifier, IDLScope):
def __init__(self, location, parentScope, identifier):
assert isinstance(identifier, IDLUnresolvedIdentifier)
IDLObjectWithIdentifier.__init__(self, location, parentScope, identifier)
IDLScope.__init__(self, location, parentScope, self.identifier)
class IDLIdentifierPlaceholder(IDLObjectWithIdentifier):
def __init__(self, location, identifier):
assert isinstance(identifier, IDLUnresolvedIdentifier)
IDLObjectWithIdentifier.__init__(self, location, None, identifier)
def finish(self, scope):
try:
scope._lookupIdentifier(self.identifier)
except:
raise WebIDLError("Unresolved type '%s'." % self.identifier,
[self.location])
obj = self.identifier.resolve(scope, None)
return scope.lookupIdentifier(obj)
class IDLExternalInterface(IDLObjectWithIdentifier):
def __init__(self, location, parentScope, identifier):
assert isinstance(identifier, IDLUnresolvedIdentifier)
assert isinstance(parentScope, IDLScope)
self.parent = None
IDLObjectWithIdentifier.__init__(self, location, parentScope, identifier)
IDLObjectWithIdentifier.resolve(self, parentScope)
def finish(self, scope):
pass
def validate(self):
pass
def isExternal(self):
return True
def isInterface(self):
return True
def isConsequential(self):
return False
def addExtendedAttributes(self, attrs):
assert len(attrs) == 0
def resolve(self, parentScope):
pass
class IDLInterface(IDLObjectWithScope):
def __init__(self, location, parentScope, name, parent, members):
assert isinstance(parentScope, IDLScope)
assert isinstance(name, IDLUnresolvedIdentifier)
assert not parent or isinstance(parent, IDLIdentifierPlaceholder)
self.parent = parent
self._callback = False
self._finished = False
self.members = list(members) # clone the list
self.implementedInterfaces = set()
self._consequential = False
# self.interfacesBasedOnSelf is the set of interfaces that inherit from
# self or have self as a consequential interface, including self itself.
# Used for distinguishability checking.
self.interfacesBasedOnSelf = set([self])
IDLObjectWithScope.__init__(self, location, parentScope, name)
def __str__(self):
return "Interface '%s'" % self.identifier.name
def ctor(self):
identifier = IDLUnresolvedIdentifier(self.location, "constructor",
allowForbidden=True)
try:
return self._lookupIdentifier(identifier)
except:
return None
def resolveIdentifierConflict(self, scope, identifier, originalObject, newObject):
assert isinstance(scope, IDLScope)
assert isinstance(originalObject, IDLInterfaceMember)
assert isinstance(newObject, IDLInterfaceMember)
if originalObject.tag != IDLInterfaceMember.Tags.Method or \
newObject.tag != IDLInterfaceMember.Tags.Method:
# Call the base class method, which will throw
IDLScope.resolveIdentifierConflict(self, identifier, originalObject,
newObject)
assert False # Not reached
retval = originalObject.addOverload(newObject)
# Might be a ctor, which isn't in self.members
if newObject in self.members:
self.members.remove(newObject)
return retval
def finish(self, scope):
if self._finished:
return
self._finished = True
assert not self.parent or isinstance(self.parent, IDLIdentifierPlaceholder)
parent = self.parent.finish(scope) if self.parent else None
if parent and isinstance(parent, IDLExternalInterface):
raise WebIDLError("%s inherits from %s which does not have "
"a definition" %
(self.identifier.name,
self.parent.identifier.name),
[self.location])
assert not parent or isinstance(parent, IDLInterface)
self.parent = parent
assert iter(self.members)
if self.parent:
self.parent.finish(scope)
# Callbacks must not inherit from non-callbacks or inherit from
# anything that has consequential interfaces.
# XXXbz Can non-callbacks inherit from callbacks? Spec issue pending.
# XXXbz Can callbacks have consequential interfaces? Spec issue pending
if self.isCallback():
if not self.parent.isCallback():
raise WebIDLError("Callback interface %s inheriting from "
"non-callback interface %s" %
(self.identifier.name,
self.parent.identifier.name),
[self.location, self.parent.location])
elif self.parent.isCallback():
raise WebIDLError("Non-callback interface %s inheriting from "
"callback interface %s" %
(self.identifier.name,
self.parent.identifier.name),
[self.location, self.parent.location])
for iface in self.implementedInterfaces:
iface.finish(scope)
cycleInGraph = self.findInterfaceLoopPoint(self)
if cycleInGraph:
raise WebIDLError("Interface %s has itself as ancestor or "
"implemented interface" % self.identifier.name,
[self.location, cycleInGraph.location])
if self.isCallback():
# "implements" should have made sure we have no
# consequential interfaces.
assert len(self.getConsequentialInterfaces()) == 0
# And that we're not consequential.
assert not self.isConsequential()
# Now resolve() and finish() our members before importing the
# ones from our implemented interfaces.
# resolve() will modify self.members, so we need to iterate
# over a copy of the member list here.
for member in list(self.members):
member.resolve(self)
for member in self.members:
member.finish(scope)
ctor = self.ctor()
if ctor is not None:
ctor.finish(scope)
# Make a copy of our member list, so things tht implement us
# can get those without all the stuff we implement ourselves
# admixed.
self.originalMembers = list(self.members)
# Import everything from our consequential interfaces into
# self.members. Sort our consequential interfaces by name
# just so we have a consistent order.
for iface in sorted(self.getConsequentialInterfaces(),
cmp=cmp,
key=lambda x: x.identifier.name):
# Flag the interface as being someone's consequential interface
iface.setIsConsequentialInterfaceOf(self)
additionalMembers = iface.originalMembers;
for additionalMember in additionalMembers:
for member in self.members:
if additionalMember.identifier.name == member.identifier.name:
raise WebIDLError(
"Multiple definitions of %s on %s coming from 'implements' statements" %
(member.identifier.name, self),
[additionalMember.location, member.location])
self.members.extend(additionalMembers)
for ancestor in self.getInheritedInterfaces():
ancestor.interfacesBasedOnSelf.add(self)
for ancestorConsequential in ancestor.getConsequentialInterfaces():
ancestorConsequential.interfacesBasedOnSelf.add(self)
# Ensure that there's at most one of each {named,indexed}
# {getter,setter,creator,deleter}.
specialMembersSeen = set()
for member in self.members:
if member.tag != IDLInterfaceMember.Tags.Method:
continue
if member.isGetter():
memberType = "getters"
elif member.isSetter():
memberType = "setters"
elif member.isCreator():
memberType = "creators"
elif member.isDeleter():
memberType = "deleters"
else:
continue
if member.isNamed():
memberType = "named " + memberType
elif member.isIndexed():
memberType = "indexed " + memberType
else:
continue
if memberType in specialMembersSeen:
raise WebIDLError("Multiple " + memberType + " on %s" % (self),
[self.location])
specialMembersSeen.add(memberType)
def validate(self):
for member in self.members:
member.validate()
def isInterface(self):
return True
def isExternal(self):
return False
def setIsConsequentialInterfaceOf(self, other):
self._consequential = True
self.interfacesBasedOnSelf.add(other)
def isConsequential(self):
return self._consequential
def setCallback(self, value):
self._callback = value
def isCallback(self):
return self._callback
def inheritanceDepth(self):
depth = 0
parent = self.parent
while parent:
depth = depth + 1
parent = parent.parent
return depth
def hasConstants(self):
return any(m.isConst() for m in self.members)
def hasInterfaceObject(self):
if self.isCallback():
return self.hasConstants()
return not hasattr(self, "_noInterfaceObject")
def hasInterfacePrototypeObject(self):
return not self.isCallback() and self.getUserData('hasConcreteDescendant', False)
def addExtendedAttributes(self, attrs):
self._extendedAttrDict = {}
for attr in attrs:
identifier = attr.identifier()
# Special cased attrs
if identifier == "TreatNonCallableAsNull":
raise WebIDLError("TreatNonCallableAsNull cannot be specified on interfaces",
[attr.location, self.location])
elif identifier == "NoInterfaceObject":
if not attr.noArguments():
raise WebIDLError("[NoInterfaceObject] must take no arguments",
[attr.location])
if self.ctor():
raise WebIDLError("Constructor and NoInterfaceObject are incompatible",
[self.location])
self._noInterfaceObject = True
elif identifier == "Constructor":
if not self.hasInterfaceObject():
raise WebIDLError("Constructor and NoInterfaceObject are incompatible",
[self.location])
args = attr.args() if attr.hasArgs() else []
retType = IDLWrapperType(self.location, self)
identifier = IDLUnresolvedIdentifier(self.location, "constructor",
allowForbidden=True)
method = IDLMethod(self.location, identifier, retType, args)
# Constructors are always Creators and are always
# assumed to be able to throw (since there's no way to
# indicate otherwise) and never have any other
# extended attributes.
method.addExtendedAttributes(
[IDLExtendedAttribute(self.location, ("Creator",)),
IDLExtendedAttribute(self.location, ("Throws",))])
method.resolve(self)
attrlist = attr.listValue()
self._extendedAttrDict[identifier] = attrlist if len(attrlist) else True
def addImplementedInterface(self, implementedInterface):
assert(isinstance(implementedInterface, IDLInterface))
self.implementedInterfaces.add(implementedInterface)
def getInheritedInterfaces(self):
"""
Returns a list of the interfaces this interface inherits from
(not including this interface itself). The list is in order
from most derived to least derived.
"""
assert(self._finished)
if not self.parent:
return []
parentInterfaces = self.parent.getInheritedInterfaces()
parentInterfaces.insert(0, self.parent)
return parentInterfaces
def getConsequentialInterfaces(self):
assert(self._finished)
# The interfaces we implement directly
consequentialInterfaces = set(self.implementedInterfaces)
# And their inherited interfaces
for iface in self.implementedInterfaces:
consequentialInterfaces |= set(iface.getInheritedInterfaces())
# And now collect up the consequential interfaces of all of those
temp = set()
for iface in consequentialInterfaces:
temp |= iface.getConsequentialInterfaces()
return consequentialInterfaces | temp
def findInterfaceLoopPoint(self, otherInterface):
"""
Finds an interface, amongst our ancestors and consequential interfaces,
that inherits from otherInterface or implements otherInterface
directly. If there is no such interface, returns None.
"""
if self.parent:
if self.parent == otherInterface:
return self
loopPoint = self.parent.findInterfaceLoopPoint(otherInterface)
if loopPoint:
return loopPoint
if otherInterface in self.implementedInterfaces:
return self
for iface in self.implementedInterfaces:
loopPoint = iface.findInterfaceLoopPoint(otherInterface)
if loopPoint:
return loopPoint
return None
def getExtendedAttribute(self, name):
return self._extendedAttrDict.get(name, None)
class IDLDictionary(IDLObjectWithScope):
def __init__(self, location, parentScope, name, parent, members):
assert isinstance(parentScope, IDLScope)
assert isinstance(name, IDLUnresolvedIdentifier)
assert not parent or isinstance(parent, IDLIdentifierPlaceholder)
self.parent = parent
self._finished = False
self.members = list(members)
IDLObjectWithScope.__init__(self, location, parentScope, name)
def __str__(self):
return "Dictionary '%s'" % self.identifier.name
def isDictionary(self):
return True;
def finish(self, scope):
if self._finished:
return
self._finished = True
if self.parent:
assert isinstance(self.parent, IDLIdentifierPlaceholder)
oldParent = self.parent
self.parent = self.parent.finish(scope)
if not isinstance(self.parent, IDLDictionary):
raise WebIDLError("Dictionary %s has parent that is not a dictionary" %
self.identifier.name,
[oldParent.location, self.parent.location])
# Make sure the parent resolves all its members before we start
# looking at them.
self.parent.finish(scope)
for member in self.members:
member.resolve(self)
if not member.isComplete():
member.complete(scope)
assert member.type.isComplete()
# Members of a dictionary are sorted in lexicographic order
self.members.sort(cmp=cmp, key=lambda x: x.identifier.name)
inheritedMembers = []
ancestor = self.parent
while ancestor:
if ancestor == self:
raise WebIDLError("Dictionary %s has itself as an ancestor" %
self.identifier.name,
[self.identifier.location])
inheritedMembers.extend(ancestor.members)
ancestor = ancestor.parent
# Catch name duplication
for inheritedMember in inheritedMembers:
for member in self.members:
if member.identifier.name == inheritedMember.identifier.name:
raise WebIDLError("Dictionary %s has two members with name %s" %
(self.identifier.name, member.identifier.name),
[member.location, inheritedMember.location])
def validate(self):
pass
def addExtendedAttributes(self, attrs):
assert len(attrs) == 0
class IDLEnum(IDLObjectWithIdentifier):
def __init__(self, location, parentScope, name, values):
assert isinstance(parentScope, IDLScope)
assert isinstance(name, IDLUnresolvedIdentifier)
if len(values) != len(set(values)):
raise WebIDLError("Enum %s has multiple identical strings" % name.name,
[location])
IDLObjectWithIdentifier.__init__(self, location, parentScope, name)
self._values = values
def values(self):
return self._values
def finish(self, scope):
pass
def validate(self):
pass
def isEnum(self):
return True
def addExtendedAttributes(self, attrs):
assert len(attrs) == 0
class IDLType(IDLObject):
Tags = enum(
# The integer types
'int8',
'uint8',
'int16',
'uint16',
'int32',
'uint32',
'int64',
'uint64',
# Additional primitive types
'bool',
'float',
'double',
# Other types
'any',
'domstring',
'object',
'date',
'void',
# Funny stuff
'interface',
'dictionary',
'enum',
'callback',
'union'
)
def __init__(self, location, name):
IDLObject.__init__(self, location)
self.name = name
self.builtin = False
def __eq__(self, other):
return other and self.builtin == other.builtin and self.name == other.name
def __ne__(self, other):
return not self == other
def __str__(self):
return str(self.name)
def isType(self):
return True
def nullable(self):
return False
def isPrimitive(self):
return False
def isString(self):
return False
def isVoid(self):
return self.name == "Void"
def isSequence(self):
return False
def isArray(self):
return False
def isArrayBuffer(self):
return False
def isArrayBufferView(self):
return False
def isTypedArray(self):
return False
def isCallbackInterface(self):
return False
def isNonCallbackInterface(self):
return False
def isGeckoInterface(self):
""" Returns a boolean indicating whether this type is an 'interface'
type that is implemented in Gecko. At the moment, this returns
true for all interface types that are not types from the TypedArray
spec."""
return self.isInterface() and not self.isSpiderMonkeyInterface()
def isSpiderMonkeyInterface(self):
""" Returns a boolean indicating whether this type is an 'interface'
type that is implemented in Spidermonkey. At the moment, this
only returns true for the types from the TypedArray spec. """
return self.isInterface() and (self.isArrayBuffer() or \
self.isArrayBufferView() or \
self.isTypedArray())
def isDictionary(self):
return False
def isInterface(self):
return False
def isAny(self):
return self.tag() == IDLType.Tags.any and not self.isSequence()
def isDate(self):
return self.tag() == IDLType.Tags.date
def isObject(self):
return self.tag() == IDLType.Tags.object
def isComplete(self):
return True
def tag(self):
assert False # Override me!
def treatNonCallableAsNull(self):
if not (self.nullable() and self.tag() == IDLType.Tags.callback):
raise WebIDLError("Type %s cannot be TreatNonCallableAsNull" % self,
[self.location])
return hasattr(self, "_treatNonCallableAsNull")
def markTreatNonCallableAsNull(self):
assert not self.treatNonCallableAsNull()
self._treatNonCallableAsNull = True
def addExtendedAttributes(self, attrs):
assert len(attrs) == 0
def resolveType(self, parentScope):
pass
def unroll(self):
return self
def isDistinguishableFrom(self, other):
raise TypeError("Can't tell whether a generic type is or is not "
"distinguishable from other things")
class IDLUnresolvedType(IDLType):
"""
Unresolved types are interface types
"""
def __init__(self, location, name):
IDLType.__init__(self, location, name)
def isComplete(self):
return False
def complete(self, scope):
obj = None
try:
obj = scope._lookupIdentifier(self.name)
except:
raise WebIDLError("Unresolved type '%s'." % self.name,
[self.location])
assert obj
if obj.isType():
# obj itself might not be complete; deal with that.
assert obj != self
if not obj.isComplete():
obj = obj.complete(scope)
return obj
name = self.name.resolve(scope, None)
return IDLWrapperType(self.location, obj)
def isDistinguishableFrom(self, other):
raise TypeError("Can't tell whether an unresolved type is or is not "
"distinguishable from other things")
class IDLNullableType(IDLType):
def __init__(self, location, innerType):
assert not innerType.isVoid()
assert not innerType == BuiltinTypes[IDLBuiltinType.Types.any]
IDLType.__init__(self, location, innerType.name)
self.inner = innerType
self.builtin = False
def __eq__(self, other):
return isinstance(other, IDLNullableType) and self.inner == other.inner
def __str__(self):
return self.inner.__str__() + "OrNull"
def nullable(self):
return True
def isCallback(self):
return self.inner.isCallback()
def isPrimitive(self):
return self.inner.isPrimitive()
def isString(self):
return self.inner.isString()
def isFloat(self):
return self.inner.isFloat()
def isInteger(self):
return self.inner.isInteger()
def isVoid(self):
return False
def isSequence(self):
return self.inner.isSequence()
def isArray(self):
return self.inner.isArray()
def isArrayBuffer(self):
return self.inner.isArrayBuffer()
def isArrayBufferView(self):
return self.inner.isArrayBufferView()
def isTypedArray(self):
return self.inner.isTypedArray()
def isDictionary(self):
return self.inner.isDictionary()
def isInterface(self):
return self.inner.isInterface()
def isCallbackInterface(self):
return self.inner.isCallbackInterface()
def isNonCallbackInterface(self):
return self.inner.isNonCallbackInterface()
def isEnum(self):
return self.inner.isEnum()
def isUnion(self):
return self.inner.isUnion()
def tag(self):
return self.inner.tag()
def resolveType(self, parentScope):
assert isinstance(parentScope, IDLScope)
self.inner.resolveType(parentScope)
def isComplete(self):
return self.inner.isComplete()
def complete(self, scope):
self.inner = self.inner.complete(scope)
if self.inner.nullable():
raise WebIDLError("The inner type of a nullable type must not be "
"a nullable type",
[self.location, self.inner.location])
if self.inner.isUnion():
if self.inner.hasNullableType:
raise WebIDLError("The inner type of a nullable type must not "
"be a union type that itself has a nullable "
"type as a member type", [self.location])
# Check for dictionaries in the union
for memberType in self.inner.flatMemberTypes:
if memberType.isDictionary():
raise WebIDLError("The inner type of a nullable type must "
"not be a union type containing a "
"dictionary type",
[self.location, memberType.location])
if self.inner.isDictionary():
raise WebIDLError("The inner type of a nullable type must not be a "
"dictionary type", [self.location])
self.name = self.inner.name
return self
def unroll(self):
return self.inner.unroll()
def isDistinguishableFrom(self, other):
if (other.nullable() or (other.isUnion() and other.hasNullableType) or
other.isDictionary()):
# Can't tell which type null should become
return False
return self.inner.isDistinguishableFrom(other)
class IDLSequenceType(IDLType):
def __init__(self, location, parameterType):
assert not parameterType.isVoid()
IDLType.__init__(self, location, parameterType.name)
self.inner = parameterType
self.builtin = False
def __eq__(self, other):
return isinstance(other, IDLSequenceType) and self.inner == other.inner
def __str__(self):
return self.inner.__str__() + "Sequence"
def nullable(self):
return False
def isPrimitive(self):
return False;
def isString(self):
return False;
def isVoid(self):
return False
def isSequence(self):
return True
def isArray(self):
return False
def isDictionary(self):
return False
def isInterface(self):
return False
def isEnum(self):
return False
def tag(self):
# XXXkhuey this is probably wrong.
return self.inner.tag()
def resolveType(self, parentScope):
assert isinstance(parentScope, IDLScope)
self.inner.resolveType(parentScope)
def isComplete(self):
return self.inner.isComplete()
def complete(self, scope):
self.inner = self.inner.complete(scope)
self.name = self.inner.name
return self
def unroll(self):
return self.inner.unroll()
def isDistinguishableFrom(self, other):
if other.isUnion():
# Just forward to the union; it'll deal
return other.isDistinguishableFrom(self)
return (other.isPrimitive() or other.isString() or other.isEnum() or
other.isDictionary() or other.isDate() or
other.isNonCallbackInterface())
class IDLUnionType(IDLType):
def __init__(self, location, memberTypes):
IDLType.__init__(self, location, "")
self.memberTypes = memberTypes
self.hasNullableType = False
self.flatMemberTypes = None
self.builtin = False
def __eq__(self, other):
return isinstance(other, IDLUnionType) and self.memberTypes == other.memberTypes
def isVoid(self):
return False
def isUnion(self):
return True
def tag(self):
return IDLType.Tags.union
def resolveType(self, parentScope):
assert isinstance(parentScope, IDLScope)
for t in self.memberTypes:
t.resolveType(parentScope)
def isComplete(self):
return self.flatMemberTypes is not None
def complete(self, scope):
def typeName(type):
if isinstance(type, IDLNullableType):
return typeName(type.inner) + "OrNull"
if isinstance(type, IDLWrapperType):
return typeName(type._identifier.object())
if isinstance(type, IDLObjectWithIdentifier):
return typeName(type.identifier)
if isinstance(type, IDLType) and (type.isArray() or type.isSequence()):
return str(type)
return type.name
for (i, type) in enumerate(self.memberTypes):
if not type.isComplete():
self.memberTypes[i] = type.complete(scope)
self.name = "Or".join(typeName(type) for type in self.memberTypes)
self.flatMemberTypes = list(self.memberTypes)
i = 0
while i < len(self.flatMemberTypes):
if self.flatMemberTypes[i].nullable():
if self.hasNullableType:
raise WebIDLError("Can't have more than one nullable types in a union",
[nullableType.location, self.flatMemberTypes[i].location])
self.hasNullableType = True
nullableType = self.flatMemberTypes[i]
self.flatMemberTypes[i] = self.flatMemberTypes[i].inner
continue
if self.flatMemberTypes[i].isUnion():
self.flatMemberTypes[i:i + 1] = self.flatMemberTypes[i].memberTypes
continue
i += 1
for (i, t) in enumerate(self.flatMemberTypes[:-1]):
for u in self.flatMemberTypes[i + 1:]:
if not t.isDistinguishableFrom(u):
raise WebIDLError("Flat member types of a union should be "
"distinguishable, " + str(t) + " is not "
"distinguishable from " + str(u),
[self.location, t.location, u.location])
return self
def isDistinguishableFrom(self, other):
if self.hasNullableType and other.nullable():
# Can't tell which type null should become
return False
if other.isUnion():
otherTypes = other.unroll().memberTypes
else:
otherTypes = [other]
# For every type in otherTypes, check that it's distinguishable from
# every type in our types
for u in otherTypes:
if any(not t.isDistinguishableFrom(u) for t in self.memberTypes):
return False
return True
class IDLArrayType(IDLType):
def __init__(self, location, parameterType):
assert not parameterType.isVoid()
if parameterType.isSequence():
raise WebIDLError("Array type cannot parameterize over a sequence type",
[location])
if parameterType.isDictionary():
raise WebIDLError("Array type cannot parameterize over a dictionary type",
[location])
IDLType.__init__(self, location, parameterType.name)
self.inner = parameterType
self.builtin = False
def __eq__(self, other):
return isinstance(other, IDLArrayType) and self.inner == other.inner
def __str__(self):
return self.inner.__str__() + "Array"
def nullable(self):
return False
def isPrimitive(self):
return False
def isString(self):
return False
def isVoid(self):
return False
def isSequence(self):
assert not self.inner.isSequence()
return False
def isArray(self):
return True
def isDictionary(self):
assert not self.inner.isDictionary()
return False
def isInterface(self):
return False
def isEnum(self):
return False
def tag(self):
# XXXkhuey this is probably wrong.
return self.inner.tag()
def resolveType(self, parentScope):
assert isinstance(parentScope, IDLScope)
self.inner.resolveType(parentScope)
def isComplete(self):
return self.inner.isComplete()
def complete(self, scope):
self.inner = self.inner.complete(scope)
self.name = self.inner.name
return self
def unroll(self):
return self.inner.unroll()
def isDistinguishableFrom(self, other):
if other.isUnion():
# Just forward to the union; it'll deal
return other.isDistinguishableFrom(self)
return (other.isPrimitive() or other.isString() or other.isEnum() or
other.isDictionary() or other.isDate() or
other.isNonCallbackInterface())
class IDLTypedefType(IDLType, IDLObjectWithIdentifier):
def __init__(self, location, innerType, name):
IDLType.__init__(self, location, innerType.name)
identifier = IDLUnresolvedIdentifier(location, name)
IDLObjectWithIdentifier.__init__(self, location, None, identifier)
self.inner = innerType
self.name = name
self.builtin = False
def __eq__(self, other):
return isinstance(other, IDLTypedefType) and self.inner == other.inner
def __str__(self):
return self.identifier.name
def nullable(self):
return self.inner.nullable()
def isPrimitive(self):
return self.inner.isPrimitive()
def isString(self):
return self.inner.isString()
def isVoid(self):
return self.inner.isVoid()
def isSequence(self):
return self.inner.isSequence()
def isArray(self):
return self.inner.isArray()
def isDictionary(self):
return self.inner.isDictionary()
def isArrayBuffer(self):
return self.inner.isArrayBuffer()
def isArrayBufferView(self):
return self.inner.isArrayBufferView()
def isTypedArray(self):
return self.inner.isTypedArray()
def isInterface(self):
return self.inner.isInterface()
def isCallbackInterface(self):
return self.inner.isCallbackInterface()
def isNonCallbackInterface(self):
return self.inner.isNonCallbackInterface()
def isComplete(self):
return False
def complete(self, parentScope):
if not self.inner.isComplete():
self.inner = self.inner.complete(parentScope)
assert self.inner.isComplete()
return self.inner
def finish(self, parentScope):
# Maybe the IDLObjectWithIdentifier for the typedef should be
# a separate thing from the type? If that happens, we can
# remove some hackery around avoiding isInterface() in
# Configuration.py.
self.complete(parentScope)
def validate(self):
pass
# Do we need a resolveType impl? I don't think it's particularly useful....
def tag(self):
return self.inner.tag()
def unroll(self):
return self.inner.unroll()
def isDistinguishableFrom(self, other):
return self.inner.isDistinguishableFrom(other)
class IDLWrapperType(IDLType):
def __init__(self, location, inner):
IDLType.__init__(self, location, inner.identifier.name)
self.inner = inner
self._identifier = inner.identifier
self.builtin = False
def __eq__(self, other):
return isinstance(other, IDLWrapperType) and \
self._identifier == other._identifier and \
self.builtin == other.builtin
def __str__(self):
return str(self.name) + " (Wrapper)"
def nullable(self):
return False
def isPrimitive(self):
return False
def isString(self):
return False
def isVoid(self):
return False
def isSequence(self):
return False
def isArray(self):
return False
def isDictionary(self):
return isinstance(self.inner, IDLDictionary)
def isInterface(self):
return isinstance(self.inner, IDLInterface) or \
isinstance(self.inner, IDLExternalInterface)
def isCallbackInterface(self):
return self.isInterface() and self.inner.isCallback()
def isNonCallbackInterface(self):
return self.isInterface() and not self.inner.isCallback()
def isEnum(self):
return isinstance(self.inner, IDLEnum)
def resolveType(self, parentScope):
assert isinstance(parentScope, IDLScope)
self.inner.resolve(parentScope)
def isComplete(self):
return True
def tag(self):
if self.isInterface():
return IDLType.Tags.interface
elif self.isEnum():
return IDLType.Tags.enum
elif self.isDictionary():
return IDLType.Tags.dictionary
else:
assert False
def isDistinguishableFrom(self, other):
if other.isUnion():
# Just forward to the union; it'll deal
return other.isDistinguishableFrom(self)
assert self.isInterface() or self.isEnum() or self.isDictionary()
if self.isEnum():
return (other.isInterface() or other.isObject() or
other.isCallback() or other.isDictionary() or
other.isSequence() or other.isArray() or
other.isDate())
if other.isPrimitive() or other.isString() or other.isEnum() or other.isDate():
return True
if self.isDictionary():
return (not other.nullable() and
(other.isNonCallbackInterface() or other.isSequence() or
other.isArray()))
assert self.isInterface()
# XXXbz need to check that the interfaces can't be implemented
# by the same object
if other.isInterface():
if other.isSpiderMonkeyInterface():
# Just let |other| handle things
return other.isDistinguishableFrom(self)
assert self.isGeckoInterface() and other.isGeckoInterface()
if self.inner.isExternal() or other.unroll().inner.isExternal():
return self != other
return (len(self.inner.interfacesBasedOnSelf &
other.unroll().inner.interfacesBasedOnSelf) == 0 and
(self.isNonCallbackInterface() or
other.isNonCallbackInterface()))
if (other.isDictionary() or other.isCallback() or
other.isSequence() or other.isArray()):
return self.isNonCallbackInterface()
# Not much else |other| can be
assert other.isObject()
return False
class IDLBuiltinType(IDLType):
Types = enum(
# The integer types
'byte',
'octet',
'short',
'unsigned_short',
'long',
'unsigned_long',
'long_long',
'unsigned_long_long',
# Additional primitive types
'boolean',
'float',
'double',
# Other types
'any',
'domstring',
'object',
'date',
'void',
# Funny stuff
'ArrayBuffer',
'ArrayBufferView',
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array'
)
TagLookup = {
Types.byte: IDLType.Tags.int8,
Types.octet: IDLType.Tags.uint8,
Types.short: IDLType.Tags.int16,
Types.unsigned_short: IDLType.Tags.uint16,
Types.long: IDLType.Tags.int32,
Types.unsigned_long: IDLType.Tags.uint32,
Types.long_long: IDLType.Tags.int64,
Types.unsigned_long_long: IDLType.Tags.uint64,
Types.boolean: IDLType.Tags.bool,
Types.float: IDLType.Tags.float,
Types.double: IDLType.Tags.double,
Types.any: IDLType.Tags.any,
Types.domstring: IDLType.Tags.domstring,
Types.object: IDLType.Tags.object,
Types.date: IDLType.Tags.date,
Types.void: IDLType.Tags.void,
Types.ArrayBuffer: IDLType.Tags.interface,
Types.ArrayBufferView: IDLType.Tags.interface,
Types.Int8Array: IDLType.Tags.interface,
Types.Uint8Array: IDLType.Tags.interface,
Types.Uint8ClampedArray: IDLType.Tags.interface,
Types.Int16Array: IDLType.Tags.interface,
Types.Uint16Array: IDLType.Tags.interface,
Types.Int32Array: IDLType.Tags.interface,
Types.Uint32Array: IDLType.Tags.interface,
Types.Float32Array: IDLType.Tags.interface,
Types.Float64Array: IDLType.Tags.interface
}
def __init__(self, location, name, type):
IDLType.__init__(self, location, name)
self.builtin = True
self._typeTag = type
def isPrimitive(self):
return self._typeTag <= IDLBuiltinType.Types.double
def isString(self):
return self._typeTag == IDLBuiltinType.Types.domstring
def isInteger(self):
return self._typeTag <= IDLBuiltinType.Types.unsigned_long_long
def isArrayBuffer(self):
return self._typeTag == IDLBuiltinType.Types.ArrayBuffer
def isArrayBufferView(self):
return self._typeTag == IDLBuiltinType.Types.ArrayBufferView
def isTypedArray(self):
return self._typeTag >= IDLBuiltinType.Types.Int8Array and \
self._typeTag <= IDLBuiltinType.Types.Float64Array
def isInterface(self):
# TypedArray things are interface types per the TypedArray spec,
# but we handle them as builtins because SpiderMonkey implements
# all of it internally.
return self.isArrayBuffer() or \
self.isArrayBufferView() or \
self.isTypedArray()
def isNonCallbackInterface(self):
# All the interfaces we can be are non-callback
return self.isInterface()
def isFloat(self):
return self._typeTag == IDLBuiltinType.Types.float or \
self._typeTag == IDLBuiltinType.Types.double
def tag(self):
return IDLBuiltinType.TagLookup[self._typeTag]
def isDistinguishableFrom(self, other):
if other.isUnion():
# Just forward to the union; it'll deal
return other.isDistinguishableFrom(self)
if self.isPrimitive() or self.isString():
return (other.isInterface() or other.isObject() or
other.isCallback() or other.isDictionary() or
other.isSequence() or other.isArray() or
other.isDate())
if self.isAny():
# Can't tell "any" apart from anything
return False
if self.isObject():
return other.isPrimitive() or other.isString() or other.isEnum()
if self.isDate():
return (other.isPrimitive() or other.isString() or other.isEnum() or
other.isInterface() or other.isCallback() or
other.isDictionary() or other.isSequence() or
other.isArray())
if self.isVoid():
return not other.isVoid()
# Not much else we could be!
assert self.isSpiderMonkeyInterface()
# Like interfaces, but we know we're not a callback
return (other.isPrimitive() or other.isString() or other.isEnum() or
other.isCallback() or other.isDictionary() or
other.isSequence() or other.isArray() or other.isDate() or
(other.isInterface() and (
# ArrayBuffer is distinguishable from everything
# that's not an ArrayBuffer or a callback interface
(self.isArrayBuffer() and not other.isArrayBuffer()) or
# ArrayBufferView is distinguishable from everything
# that's not an ArrayBufferView or typed array.
(self.isArrayBufferView() and not other.isArrayBufferView() and
not other.isTypedArray()) or
# Typed arrays are distinguishable from everything
# except ArrayBufferView and the same type of typed
# array
(self.isTypedArray() and not other.isArrayBufferView() and not
(other.isTypedArray() and other.name == self.name)))))
BuiltinTypes = {
IDLBuiltinType.Types.byte:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Byte",
IDLBuiltinType.Types.byte),
IDLBuiltinType.Types.octet:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Octet",
IDLBuiltinType.Types.octet),
IDLBuiltinType.Types.short:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Short",
IDLBuiltinType.Types.short),
IDLBuiltinType.Types.unsigned_short:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "UnsignedShort",
IDLBuiltinType.Types.unsigned_short),
IDLBuiltinType.Types.long:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Long",
IDLBuiltinType.Types.long),
IDLBuiltinType.Types.unsigned_long:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "UnsignedLong",
IDLBuiltinType.Types.unsigned_long),
IDLBuiltinType.Types.long_long:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "LongLong",
IDLBuiltinType.Types.long_long),
IDLBuiltinType.Types.unsigned_long_long:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "UnsignedLongLong",
IDLBuiltinType.Types.unsigned_long_long),
IDLBuiltinType.Types.boolean:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Boolean",
IDLBuiltinType.Types.boolean),
IDLBuiltinType.Types.float:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Float",
IDLBuiltinType.Types.float),
IDLBuiltinType.Types.double:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Double",
IDLBuiltinType.Types.double),
IDLBuiltinType.Types.any:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Any",
IDLBuiltinType.Types.any),
IDLBuiltinType.Types.domstring:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "String",
IDLBuiltinType.Types.domstring),
IDLBuiltinType.Types.object:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Object",
IDLBuiltinType.Types.object),
IDLBuiltinType.Types.date:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Date",
IDLBuiltinType.Types.date),
IDLBuiltinType.Types.void:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Void",
IDLBuiltinType.Types.void),
IDLBuiltinType.Types.ArrayBuffer:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "ArrayBuffer",
IDLBuiltinType.Types.ArrayBuffer),
IDLBuiltinType.Types.ArrayBufferView:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "ArrayBufferView",
IDLBuiltinType.Types.ArrayBufferView),
IDLBuiltinType.Types.Int8Array:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Int8Array",
IDLBuiltinType.Types.Int8Array),
IDLBuiltinType.Types.Uint8Array:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Uint8Array",
IDLBuiltinType.Types.Uint8Array),
IDLBuiltinType.Types.Uint8ClampedArray:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Uint8ClampedArray",
IDLBuiltinType.Types.Uint8ClampedArray),
IDLBuiltinType.Types.Int16Array:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Int16Array",
IDLBuiltinType.Types.Int16Array),
IDLBuiltinType.Types.Uint16Array:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Uint16Array",
IDLBuiltinType.Types.Uint16Array),
IDLBuiltinType.Types.Int32Array:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Int32Array",
IDLBuiltinType.Types.Int32Array),
IDLBuiltinType.Types.Uint32Array:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Uint32Array",
IDLBuiltinType.Types.Uint32Array),
IDLBuiltinType.Types.Float32Array:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Float32Array",
IDLBuiltinType.Types.Float32Array),
IDLBuiltinType.Types.Float64Array:
IDLBuiltinType(BuiltinLocation("<builtin type>"), "Float64Array",
IDLBuiltinType.Types.Float64Array)
}
integerTypeSizes = {
IDLBuiltinType.Types.byte: (-128, 127),
IDLBuiltinType.Types.octet: (0, 255),
IDLBuiltinType.Types.short: (-32768, 32767),
IDLBuiltinType.Types.unsigned_short: (0, 65535),
IDLBuiltinType.Types.long: (-2147483648, 2147483647),
IDLBuiltinType.Types.unsigned_long: (0, 4294967295),
IDLBuiltinType.Types.long_long: (-9223372036854775808,
9223372036854775807),
IDLBuiltinType.Types.unsigned_long_long: (0, 18446744073709551615)
}
def matchIntegerValueToType(value):
for type, extremes in integerTypeSizes.items():
(min, max) = extremes
if value <= max and value >= min:
return BuiltinTypes[type]
return None
class IDLValue(IDLObject):
def __init__(self, location, type, value):
IDLObject.__init__(self, location)
self.type = type
assert isinstance(type, IDLType)
self.value = value
def coerceToType(self, type, location):
if type == self.type:
return self # Nothing to do
# If the type allows null, rerun this matching on the inner type
if type.nullable():
innerValue = self.coerceToType(type.inner, location)
return IDLValue(self.location, type, innerValue.value)
# Else, see if we can coerce to 'type'.
if self.type.isInteger() and type.isInteger():
# We're both integer types. See if we fit.
(min, max) = integerTypeSizes[type._typeTag]
if self.value <= max and self.value >= min:
# Promote
return IDLValue(self.location, type, self.value)
else:
raise WebIDLError("Value %s is out of range for type %s." %
(self.value, type), [location])
elif self.type.isString() and type.isEnum():
# Just keep our string, but make sure it's a valid value for this enum
if self.value not in type.inner.values():
raise WebIDLError("'%s' is not a valid default value for enum %s"
% (self.value, type.inner.identifier.name),
[location, type.inner.location])
return self
else:
raise WebIDLError("Cannot coerce type %s to type %s." %
(self.type, type), [location])
class IDLNullValue(IDLObject):
def __init__(self, location):
IDLObject.__init__(self, location)
self.type = None
self.value = None
def coerceToType(self, type, location):
if (not isinstance(type, IDLNullableType) and
not (type.isUnion() and type.hasNullableType) and
not type.isDictionary() and
not type.isAny()):
raise WebIDLError("Cannot coerce null value to type %s." % type,
[location])
nullValue = IDLNullValue(self.location)
nullValue.type = type
return nullValue
class IDLInterfaceMember(IDLObjectWithIdentifier):
Tags = enum(
'Const',
'Attr',
'Method'
)
def __init__(self, location, identifier, tag):
IDLObjectWithIdentifier.__init__(self, location, None, identifier)
self.tag = tag
self._extendedAttrDict = {}
def isMethod(self):
return self.tag == IDLInterfaceMember.Tags.Method
def isAttr(self):
return self.tag == IDLInterfaceMember.Tags.Attr
def isConst(self):
return self.tag == IDLInterfaceMember.Tags.Const
def addExtendedAttributes(self, attrs):
for attr in attrs:
self.handleExtendedAttribute(attr)
attrlist = attr.listValue()
self._extendedAttrDict[attr.identifier()] = attrlist if len(attrlist) else True
def handleExtendedAttribute(self, attr):
pass
def getExtendedAttribute(self, name):
return self._extendedAttrDict.get(name, None)
class IDLConst(IDLInterfaceMember):
def __init__(self, location, identifier, type, value):
IDLInterfaceMember.__init__(self, location, identifier,
IDLInterfaceMember.Tags.Const)
assert isinstance(type, IDLType)
if type.isDictionary():
raise WebIDLError("A constant cannot be of a dictionary type",
[self.location])
self.type = type
self.value = value
def __str__(self):
return "'%s' const '%s'" % (self.type, self.identifier)
def finish(self, scope):
if not self.type.isComplete():
type = self.type.complete(scope)
if not type.isPrimitive() and not type.isString():
locations = [self.type.location, type.location]
try:
locations.append(type.inner.location)
except:
pass
raise WebIDLError("Incorrect type for constant", locations)
self.type = type
# The value might not match the type
coercedValue = self.value.coerceToType(self.type, self.location)
assert coercedValue
self.value = coercedValue
def validate(self):
pass
class IDLAttribute(IDLInterfaceMember):
def __init__(self, location, identifier, type, readonly, inherit,
static=False):
IDLInterfaceMember.__init__(self, location, identifier,
IDLInterfaceMember.Tags.Attr)
assert isinstance(type, IDLType)
self.type = type
self.readonly = readonly
self.inherit = inherit
self.static = static
self.lenientThis = False
if readonly and inherit:
raise WebIDLError("An attribute cannot be both 'readonly' and 'inherit'",
[self.location])
def isStatic(self):
return self.static
def __str__(self):
return "'%s' attribute '%s'" % (self.type, self.identifier)
def finish(self, scope):
if not self.type.isComplete():
t = self.type.complete(scope)
assert not isinstance(t, IDLUnresolvedType)
assert not isinstance(t, IDLTypedefType)
assert not isinstance(t.name, IDLUnresolvedIdentifier)
self.type = t
if self.type.isDictionary():
raise WebIDLError("An attribute cannot be of a dictionary type",
[self.location])
if self.type.isSequence():
raise WebIDLError("An attribute cannot be of a sequence type",
[self.location])
if self.type.isUnion():
for f in self.type.flatMemberTypes:
if f.isDictionary():
raise WebIDLError("An attribute cannot be of a union "
"type if one of its member types (or "
"one of its member types's member "
"types, and so on) is a dictionary "
"type", [self.location, f.location])
if f.isSequence():
raise WebIDLError("An attribute cannot be of a union "
"type if one of its member types (or "
"one of its member types's member "
"types, and so on) is a sequence "
"type", [self.location, f.location])
def validate(self):
pass
def handleExtendedAttribute(self, attr):
identifier = attr.identifier()
if identifier == "TreatNonCallableAsNull":
self.type.markTreatNonCallableAsNull();
elif identifier == "SetterInfallible" and self.readonly:
raise WebIDLError("Readonly attributes must not be flagged as "
"[SetterInfallible]",
[self.location])
elif identifier == "LenientThis":
if not attr.noArguments():
raise WebIDLError("[LenientThis] must take no arguments",
[attr.location])
if self.isStatic():
raise WebIDLError("[LenientThis] is only allowed on non-static "
"attributes", [attr.location, self.location])
self.lenientThis = True
IDLInterfaceMember.handleExtendedAttribute(self, attr)
def resolve(self, parentScope):
assert isinstance(parentScope, IDLScope)
self.type.resolveType(parentScope)
IDLObjectWithIdentifier.resolve(self, parentScope)
def addExtendedAttributes(self, attrs):
attrs = self.checkForStringHandlingExtendedAttributes(attrs)
IDLInterfaceMember.addExtendedAttributes(self, attrs)
def hasLenientThis(self):
return self.lenientThis
class IDLArgument(IDLObjectWithIdentifier):
def __init__(self, location, identifier, type, optional=False, defaultValue=None, variadic=False, dictionaryMember=False):
IDLObjectWithIdentifier.__init__(self, location, None, identifier)
assert isinstance(type, IDLType)
self.type = type
self.optional = optional
self.defaultValue = defaultValue
self.variadic = variadic
self.dictionaryMember = dictionaryMember
self._isComplete = False
self.enforceRange = False
self.clamp = False
assert not variadic or optional
def addExtendedAttributes(self, attrs):
attrs = self.checkForStringHandlingExtendedAttributes(
attrs,
isDictionaryMember=self.dictionaryMember,
isOptional=self.optional)
for attribute in attrs:
identifier = attribute.identifier()
if identifier == "Clamp":
if not attribute.noArguments():
raise WebIDLError("[Clamp] must take no arguments",
[attribute.location])
if self.enforceRange:
raise WebIDLError("[EnforceRange] and [Clamp] are mutually exclusive",
[self.location]);
self.clamp = True
elif identifier == "EnforceRange":
if not attribute.noArguments():
raise WebIDLError("[EnforceRange] must take no arguments",
[attribute.location])
if self.clamp:
raise WebIDLError("[EnforceRange] and [Clamp] are mutually exclusive",
[self.location]);
self.enforceRange = True
else:
raise WebIDLError("Unhandled extended attribute on an argument",
[attribute.location])
def isComplete(self):
return self._isComplete
def complete(self, scope):
if self._isComplete:
return
self._isComplete = True
if not self.type.isComplete():
type = self.type.complete(scope)
assert not isinstance(type, IDLUnresolvedType)
assert not isinstance(type, IDLTypedefType)
assert not isinstance(type.name, IDLUnresolvedIdentifier)
self.type = type
if self.type.isDictionary() and self.optional and not self.defaultValue:
# Default optional dictionaries to null, for simplicity,
# so the codegen doesn't have to special-case this.
self.defaultValue = IDLNullValue(self.location)
# Now do the coercing thing; this needs to happen after the
# above creation of a default value.
if self.defaultValue:
self.defaultValue = self.defaultValue.coerceToType(self.type,
self.location)
assert self.defaultValue
class IDLCallbackType(IDLType, IDLObjectWithScope):
def __init__(self, location, parentScope, identifier, returnType, arguments):
assert isinstance(returnType, IDLType)
IDLType.__init__(self, location, identifier.name)
self._returnType = returnType
# Clone the list
self._arguments = list(arguments)
IDLObjectWithScope.__init__(self, location, parentScope, identifier)
for (returnType, arguments) in self.signatures():
for argument in arguments:
argument.resolve(self)
def isCallback(self):
return True
def signatures(self):
return [(self._returnType, self._arguments)]
def tag(self):
return IDLType.Tags.callback
def finish(self, scope):
if not self._returnType.isComplete():
type = returnType.complete(scope)
assert not isinstance(type, IDLUnresolvedType)
assert not isinstance(type, IDLTypedefType)
assert not isinstance(type.name, IDLUnresolvedIdentifier)
self._returnType = type
for argument in self._arguments:
if argument.type.isComplete():
continue
type = argument.type.complete(scope)
assert not isinstance(type, IDLUnresolvedType)
assert not isinstance(type, IDLTypedefType)
assert not isinstance(type.name, IDLUnresolvedIdentifier)
argument.type = type
def validate(self):
pass
def isDistinguishableFrom(self, other):
if other.isUnion():
# Just forward to the union; it'll deal
return other.isDistinguishableFrom(self)
return (other.isPrimitive() or other.isString() or other.isEnum() or
other.isNonCallbackInterface() or other.isDate())
class IDLMethodOverload:
"""
A class that represents a single overload of a WebIDL method. This is not
quite the same as an element of the "effective overload set" in the spec,
because separate IDLMethodOverloads are not created based on arguments being
optional. Rather, when multiple methods have the same name, there is an
IDLMethodOverload for each one, all hanging off an IDLMethod representing
the full set of overloads.
"""
def __init__(self, returnType, arguments, location):
self.returnType = returnType
# Clone the list of arguments, just in case
self.arguments = list(arguments)
self.location = location
class IDLMethod(IDLInterfaceMember, IDLScope):
Special = enum(
'None',
'Getter',
'Setter',
'Creator',
'Deleter',
'LegacyCaller',
'Stringifier',
'Static'
)
TypeSuffixModifier = enum(
'None',
'QMark',
'Brackets'
)
NamedOrIndexed = enum(
'Neither',
'Named',
'Indexed'
)
def __init__(self, location, identifier, returnType, arguments,
static=False, getter=False, setter=False, creator=False,
deleter=False, specialType=NamedOrIndexed.Neither,
legacycaller=False, stringifier=False):
# REVIEW: specialType is NamedOrIndexed -- wow, this is messed up.
IDLInterfaceMember.__init__(self, location, identifier,
IDLInterfaceMember.Tags.Method)
self._hasOverloads = False
assert isinstance(returnType, IDLType)
# self._overloads is a list of IDLMethodOverloads
self._overloads = [IDLMethodOverload(returnType, arguments, location)]
assert isinstance(static, bool)
self._static = static
assert isinstance(getter, bool)
self._getter = getter
assert isinstance(setter, bool)
self._setter = setter
assert isinstance(creator, bool)
self._creator = creator
assert isinstance(deleter, bool)
self._deleter = deleter
assert isinstance(legacycaller, bool)
self._legacycaller = legacycaller
assert isinstance(stringifier, bool)
self._stringifier = stringifier
self._specialType = specialType
self.assertSignatureConstraints()
def __str__(self):
return "Method '%s'" % self.identifier
def assertSignatureConstraints(self):
if self._getter or self._deleter:
assert len(self._overloads) == 1
overload = self._overloads[0]
arguments = overload.arguments
assert len(arguments) == 1
assert arguments[0].type == BuiltinTypes[IDLBuiltinType.Types.domstring] or \
arguments[0].type == BuiltinTypes[IDLBuiltinType.Types.unsigned_long]
assert not arguments[0].optional and not arguments[0].variadic
assert not self._getter or not overload.returnType.isVoid()
if self._setter or self._creator:
assert len(self._overloads) == 1
arguments = self._overloads[0].arguments
assert len(arguments) == 2
assert arguments[0].type == BuiltinTypes[IDLBuiltinType.Types.domstring] or \
arguments[0].type == BuiltinTypes[IDLBuiltinType.Types.unsigned_long]
assert not arguments[0].optional and not arguments[0].variadic
assert not arguments[1].optional and not arguments[1].variadic
if self._stringifier:
assert len(self._overloads) == 1
overload = self._overloads[0]
assert len(overload.arguments) == 0
assert overload.returnType == BuiltinTypes[IDLBuiltinType.Types.domstring]
def isStatic(self):
return self._static
def isGetter(self):
return self._getter
def isSetter(self):
return self._setter
def isCreator(self):
return self._creator
def isDeleter(self):
return self._deleter
def isNamed(self):
assert self._specialType == IDLMethod.NamedOrIndexed.Named or \
self._specialType == IDLMethod.NamedOrIndexed.Indexed
return self._specialType == IDLMethod.NamedOrIndexed.Named
def isIndexed(self):
assert self._specialType == IDLMethod.NamedOrIndexed.Named or \
self._specialType == IDLMethod.NamedOrIndexed.Indexed
return self._specialType == IDLMethod.NamedOrIndexed.Indexed
def isLegacycaller(self):
return self._legacycaller
def isStringifier(self):
return self._stringifier
def hasOverloads(self):
return self._hasOverloads
def isIdentifierLess(self):
return self.identifier.name[:2] == "__"
def resolve(self, parentScope):
assert isinstance(parentScope, IDLScope)
IDLObjectWithIdentifier.resolve(self, parentScope)
IDLScope.__init__(self, self.location, parentScope, self.identifier)
for (returnType, arguments) in self.signatures():
for argument in arguments:
argument.resolve(self)
def addOverload(self, method):
assert len(method._overloads) == 1
if self._extendedAttrDict != method ._extendedAttrDict:
raise WebIDLError("Extended attributes differ on different "
"overloads of %s" % method.identifier,
[self.location, method.location])
self._overloads.extend(method._overloads)
self._hasOverloads = True
if self.isStatic() != method.isStatic():
raise WebIDLError("Overloaded identifier %s appears with different values of the 'static' attribute" % method.identifier,
[method.location])
if self.isLegacycaller() != method.isLegacycaller():
raise WebIDLError("Overloaded identifier %s appears with different values of the 'legacycaller' attribute" % method.identifier,
[method.location])
# Can't overload special things!
assert not self.isGetter()
assert not method.isGetter()
assert not self.isSetter()
assert not method.isSetter()
assert not self.isCreator()
assert not method.isCreator()
assert not self.isDeleter()
assert not method.isDeleter()
assert not self.isStringifier()
assert not method.isStringifier()
return self
def signatures(self):
return [(overload.returnType, overload.arguments) for overload in
self._overloads]
def finish(self, scope):
for overload in self._overloads:
inOptionalArguments = False
variadicArgument = None
sawOptionalWithNoDefault = False
arguments = overload.arguments
for (idx, argument) in enumerate(arguments):
if argument.isComplete():
continue
argument.complete(scope)
assert argument.type.isComplete()
if argument.type.isDictionary():
# Dictionaries at the end of the list or followed by
# optional arguments must be optional.
if (not argument.optional and
(idx == len(arguments) - 1 or arguments[idx+1].optional)):
raise WebIDLError("Dictionary argument not followed by "
"a required argument must be "
"optional", [argument.location])
# Only the last argument can be variadic
if variadicArgument:
raise WebIDLError("Variadic argument is not last argument",
[variadicArgument.location])
# Once we see an optional argument, there can't be any non-optional
# arguments.
if inOptionalArguments and not argument.optional:
raise WebIDLError("Non-optional argument after optional "
"arguments",
[argument.location])
# Once we see an argument with no default value, there can
# be no more default values.
if sawOptionalWithNoDefault and argument.defaultValue:
raise WebIDLError("Argument with default value after "
"optional arguments with no default "
"values",
[argument.location])
inOptionalArguments = argument.optional
if argument.variadic:
variadicArgument = argument
sawOptionalWithNoDefault = (argument.optional and
not argument.defaultValue)
returnType = overload.returnType
if returnType.isComplete():
continue
type = returnType.complete(scope)
assert not isinstance(type, IDLUnresolvedType)
assert not isinstance(type, IDLTypedefType)
assert not isinstance(type.name, IDLUnresolvedIdentifier)
overload.returnType = type
# Now compute various information that will be used by the
# WebIDL overload resolution algorithm.
self.maxArgCount = max(len(s[1]) for s in self.signatures())
self.allowedArgCounts = [ i for i in range(self.maxArgCount+1)
if len(self.signaturesForArgCount(i)) != 0 ]
def validate(self):
# Make sure our overloads are properly distinguishable and don't have
# different argument types before the distinguishing args.
for argCount in self.allowedArgCounts:
possibleOverloads = self.overloadsForArgCount(argCount)
if len(possibleOverloads) == 1:
continue
distinguishingIndex = self.distinguishingIndexForArgCount(argCount)
for idx in range(distinguishingIndex):
firstSigType = possibleOverloads[0].arguments[idx].type
for overload in possibleOverloads[1:]:
if overload.arguments[idx].type != firstSigType:
raise WebIDLError(
"Signatures for method '%s' with %d arguments have "
"different types of arguments at index %d, which "
"is before distinguishing index %d" %
(self.identifier.name, argCount, idx,
distinguishingIndex),
[self.location, overload.location])
def overloadsForArgCount(self, argc):
return [overload for overload in self._overloads if
len(overload.arguments) == argc or
(len(overload.arguments) > argc and
overload.arguments[argc].optional)]
def signaturesForArgCount(self, argc):
return [(overload.returnType, overload.arguments) for overload
in self.overloadsForArgCount(argc)]
def locationsForArgCount(self, argc):
return [overload.location for overload in self._overloads if
len(overload.arguments) == argc or
(len(overload.arguments) > argc and
overload.arguments[argc].optional)]
def distinguishingIndexForArgCount(self, argc):
def isValidDistinguishingIndex(idx, signatures):
for (firstSigIndex, (firstRetval, firstArgs)) in enumerate(signatures[:-1]):
for (secondRetval, secondArgs) in signatures[firstSigIndex+1:]:
firstType = firstArgs[idx].type
secondType = secondArgs[idx].type
if not firstType.isDistinguishableFrom(secondType):
return False
return True
signatures = self.signaturesForArgCount(argc)
for idx in range(argc):
if isValidDistinguishingIndex(idx, signatures):
return idx
# No valid distinguishing index. Time to throw
locations = self.locationsForArgCount(argc)
raise WebIDLError("Signatures with %d arguments for method '%s' are not "
"distinguishable" % (argc, self.identifier.name),
locations)
def handleExtendedAttribute(self, attr):
identifier = attr.identifier()
if identifier == "GetterInfallible":
raise WebIDLError("Methods must not be flagged as "
"[GetterInfallible]",
[attr.location, self.location])
if identifier == "SetterInfallible":
raise WebIDLError("Methods must not be flagged as "
"[SetterInfallible]",
[attr.location, self.location])
IDLInterfaceMember.handleExtendedAttribute(self, attr)
class IDLImplementsStatement(IDLObject):
def __init__(self, location, implementor, implementee):
IDLObject.__init__(self, location)
self.implementor = implementor;
self.implementee = implementee
def finish(self, scope):
assert(isinstance(self.implementor, IDLIdentifierPlaceholder))
assert(isinstance(self.implementee, IDLIdentifierPlaceholder))
implementor = self.implementor.finish(scope)
implementee = self.implementee.finish(scope)
# NOTE: we depend on not setting self.implementor and
# self.implementee here to keep track of the original
# locations.
if not isinstance(implementor, IDLInterface):
raise WebIDLError("Left-hand side of 'implements' is not an "
"interface",
[self.implementor.location])
if implementor.isCallback():
raise WebIDLError("Left-hand side of 'implements' is a callback "
"interface",
[self.implementor.location])
if not isinstance(implementee, IDLInterface):
raise WebIDLError("Right-hand side of 'implements' is not an "
"interface",
[self.implementee.location])
if implementee.isCallback():
raise WebIDLError("Right-hand side of 'implements' is a callback "
"interface",
[self.implementee.location])
implementor.addImplementedInterface(implementee)
def validate(self):
pass
def addExtendedAttributes(self, attrs):
assert len(attrs) == 0
class IDLExtendedAttribute(IDLObject):
"""
A class to represent IDL extended attributes so we can give them locations
"""
def __init__(self, location, tuple):
IDLObject.__init__(self, location)
self._tuple = tuple
def identifier(self):
return self._tuple[0]
def noArguments(self):
return len(self._tuple) == 1
def hasValue(self):
return len(self._tuple) == 2 and isinstance(self._tuple[1], str)
def value(self):
assert(self.hasValue())
return self._tuple[1]
def hasArgs(self):
return (len(self._tuple) == 2 and isinstance(self._tuple[1], list) or
len(self._tuple) == 3)
def args(self):
assert(self.hasArgs())
# Our args are our last element
return self._tuple[-1]
def listValue(self):
"""
Backdoor for storing random data in _extendedAttrDict
"""
return list(self._tuple)[1:]
# Parser
class Tokenizer(object):
tokens = [
"INTEGER",
"FLOATLITERAL",
"IDENTIFIER",
"STRING",
"WHITESPACE",
"OTHER"
]
def t_INTEGER(self, t):
r'-?(0([0-7]+|[Xx][0-9A-Fa-f]+)?|[1-9][0-9]*)'
try:
# Can't use int(), because that doesn't handle octal properly.
t.value = parseInt(t.value)
except:
raise WebIDLError("Invalid integer literal",
[Location(lexer=self.lexer,
lineno=self.lexer.lineno,
lexpos=self.lexer.lexpos,
filename=self._filename)])
return t
def t_FLOATLITERAL(self, t):
r'-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)'
assert False
return t
def t_IDENTIFIER(self, t):
r'[A-Z_a-z][0-9A-Z_a-z]*'
t.type = self.keywords.get(t.value, 'IDENTIFIER')
return t
def t_STRING(self, t):
r'"[^"]*"'
t.value = t.value[1:-1]
return t
def t_WHITESPACE(self, t):
r'[\t\n\r ]+|[\t\n\r ]*((//[^\n]*|/\*.*?\*/)[\t\n\r ]*)+'
pass
def t_ELLIPSIS(self, t):
r'\.\.\.'
t.type = self.keywords.get(t.value)
return t
def t_OTHER(self, t):
r'[^\t\n\r 0-9A-Z_a-z]'
t.type = self.keywords.get(t.value, 'OTHER')
return t
keywords = {
"module": "MODULE",
"interface": "INTERFACE",
"partial": "PARTIAL",
"dictionary": "DICTIONARY",
"exception": "EXCEPTION",
"enum": "ENUM",
"callback": "CALLBACK",
"typedef": "TYPEDEF",
"implements": "IMPLEMENTS",
"const": "CONST",
"null": "NULL",
"true": "TRUE",
"false": "FALSE",
"stringifier": "STRINGIFIER",
"attribute": "ATTRIBUTE",
"readonly": "READONLY",
"inherit": "INHERIT",
"static": "STATIC",
"getter": "GETTER",
"setter": "SETTER",
"creator": "CREATOR",
"deleter": "DELETER",
"legacycaller": "LEGACYCALLER",
"optional": "OPTIONAL",
"...": "ELLIPSIS",
"::": "SCOPE",
"Date": "DATE",
"DOMString": "DOMSTRING",
"any": "ANY",
"boolean": "BOOLEAN",
"byte": "BYTE",
"double": "DOUBLE",
"float": "FLOAT",
"long": "LONG",
"object": "OBJECT",
"octet": "OCTET",
"optional": "OPTIONAL",
"sequence": "SEQUENCE",
"short": "SHORT",
"unsigned": "UNSIGNED",
"void": "VOID",
":": "COLON",
";": "SEMICOLON",
"{": "LBRACE",
"}": "RBRACE",
"(": "LPAREN",
")": "RPAREN",
"[": "LBRACKET",
"]": "RBRACKET",
"?": "QUESTIONMARK",
",": "COMMA",
"=": "EQUALS",
"<": "LT",
">": "GT",
"ArrayBuffer": "ARRAYBUFFER",
"or": "OR"
}
tokens.extend(keywords.values())
def t_error(self, t):
raise WebIDLError("Unrecognized Input",
[Location(lexer=self.lexer,
lineno=self.lexer.lineno,
lexpos=self.lexer.lexpos,
filename = self.filename)])
def __init__(self, outputdir, lexer=None):
if lexer:
self.lexer = lexer
else:
self.lexer = lex.lex(object=self,
outputdir=outputdir,
lextab='webidllex',
reflags=re.DOTALL)
class Parser(Tokenizer):
def getLocation(self, p, i):
return Location(self.lexer, p.lineno(i), p.lexpos(i), self._filename)
def globalScope(self):
return self._globalScope
# The p_Foo functions here must match the WebIDL spec's grammar.
# It's acceptable to split things at '|' boundaries.
def p_Definitions(self, p):
"""
Definitions : ExtendedAttributeList Definition Definitions
"""
if p[2]:
p[0] = [p[2]]
p[2].addExtendedAttributes(p[1])
else:
assert not p[1]
p[0] = []
p[0].extend(p[3])
def p_DefinitionsEmpty(self, p):
"""
Definitions :
"""
p[0] = []
def p_Definition(self, p):
"""
Definition : CallbackOrInterface
| PartialInterface
| Dictionary
| Exception
| Enum
| Typedef
| ImplementsStatement
"""
p[0] = p[1]
assert p[1] # We might not have implemented something ...
def p_CallbackOrInterfaceCallback(self, p):
"""
CallbackOrInterface : CALLBACK CallbackRestOrInterface
"""
if p[2].isInterface():
assert isinstance(p[2], IDLInterface)
p[2].setCallback(True)
p[0] = p[2]
def p_CallbackOrInterfaceInterface(self, p):
"""
CallbackOrInterface : Interface
"""
p[0] = p[1]
def p_CallbackRestOrInterface(self, p):
"""
CallbackRestOrInterface : CallbackRest
| Interface
"""
assert p[1]
p[0] = p[1]
def p_Interface(self, p):
"""
Interface : INTERFACE IDENTIFIER Inheritance LBRACE InterfaceMembers RBRACE SEMICOLON
"""
location = self.getLocation(p, 1)
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2])
members = p[5]
p[0] = IDLInterface(location, self.globalScope(), identifier, p[3], members)
def p_InterfaceForwardDecl(self, p):
"""
Interface : INTERFACE IDENTIFIER SEMICOLON
"""
location = self.getLocation(p, 1)
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2])
try:
if self.globalScope()._lookupIdentifier(identifier):
p[0] = self.globalScope()._lookupIdentifier(identifier)
return
except:
pass
p[0] = IDLExternalInterface(location, self.globalScope(), identifier)
def p_PartialInterface(self, p):
"""
PartialInterface : PARTIAL INTERFACE IDENTIFIER LBRACE InterfaceMembers RBRACE SEMICOLON
"""
pass
def p_Inheritance(self, p):
"""
Inheritance : COLON ScopedName
"""
p[0] = IDLIdentifierPlaceholder(self.getLocation(p, 2), p[2])
def p_InheritanceEmpty(self, p):
"""
Inheritance :
"""
pass
def p_InterfaceMembers(self, p):
"""
InterfaceMembers : ExtendedAttributeList InterfaceMember InterfaceMembers
"""
p[0] = [p[2]] if p[2] else []
assert not p[1] or p[2]
p[2].addExtendedAttributes(p[1])
p[0].extend(p[3])
def p_InterfaceMembersEmpty(self, p):
"""
InterfaceMembers :
"""
p[0] = []
def p_InterfaceMember(self, p):
"""
InterfaceMember : Const
| AttributeOrOperation
"""
p[0] = p[1]
def p_Dictionary(self, p):
"""
Dictionary : DICTIONARY IDENTIFIER Inheritance LBRACE DictionaryMembers RBRACE SEMICOLON
"""
location = self.getLocation(p, 1)
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2])
members = p[5]
p[0] = IDLDictionary(location, self.globalScope(), identifier, p[3], members)
def p_DictionaryMembers(self, p):
"""
DictionaryMembers : ExtendedAttributeList DictionaryMember DictionaryMembers
|
"""
if len(p) == 1:
# We're at the end of the list
p[0] = []
return
# Add our extended attributes
p[2].addExtendedAttributes(p[1])
p[0] = [p[2]]
p[0].extend(p[3])
def p_DictionaryMember(self, p):
"""
DictionaryMember : Type IDENTIFIER DefaultValue SEMICOLON
"""
# These quack a lot like optional arguments, so just treat them that way.
t = p[1]
assert isinstance(t, IDLType)
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2])
defaultValue = p[3]
p[0] = IDLArgument(self.getLocation(p, 2), identifier, t, optional=True,
defaultValue=defaultValue, variadic=False,
dictionaryMember=True)
def p_DefaultValue(self, p):
"""
DefaultValue : EQUALS ConstValue
|
"""
if len(p) > 1:
p[0] = p[2]
else:
p[0] = None
def p_Exception(self, p):
"""
Exception : EXCEPTION IDENTIFIER Inheritance LBRACE ExceptionMembers RBRACE SEMICOLON
"""
pass
def p_Enum(self, p):
"""
Enum : ENUM IDENTIFIER LBRACE EnumValueList RBRACE SEMICOLON
"""
location = self.getLocation(p, 1)
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 2), p[2])
values = p[4]
assert values
p[0] = IDLEnum(location, self.globalScope(), identifier, values)
def p_EnumValueList(self, p):
"""
EnumValueList : STRING EnumValues
"""
p[0] = [p[1]]
p[0].extend(p[2])
def p_EnumValues(self, p):
"""
EnumValues : COMMA STRING EnumValues
"""
p[0] = [p[2]]
p[0].extend(p[3])
def p_EnumValuesEmpty(self, p):
"""
EnumValues :
"""
p[0] = []
def p_CallbackRest(self, p):
"""
CallbackRest : IDENTIFIER EQUALS ReturnType LPAREN ArgumentList RPAREN SEMICOLON
"""
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1])
p[0] = IDLCallbackType(self.getLocation(p, 1), self.globalScope(),
identifier, p[3], p[5])
def p_ExceptionMembers(self, p):
"""
ExceptionMembers : ExtendedAttributeList ExceptionMember ExceptionMembers
|
"""
pass
def p_Typedef(self, p):
"""
Typedef : TYPEDEF Type IDENTIFIER SEMICOLON
"""
typedef = IDLTypedefType(self.getLocation(p, 1), p[2], p[3])
typedef.resolve(self.globalScope())
p[0] = typedef
def p_ImplementsStatement(self, p):
"""
ImplementsStatement : ScopedName IMPLEMENTS ScopedName SEMICOLON
"""
assert(p[2] == "implements")
implementor = IDLIdentifierPlaceholder(self.getLocation(p, 1), p[1])
implementee = IDLIdentifierPlaceholder(self.getLocation(p, 3), p[3])
p[0] = IDLImplementsStatement(self.getLocation(p, 1), implementor,
implementee)
def p_Const(self, p):
"""
Const : CONST ConstType IDENTIFIER EQUALS ConstValue SEMICOLON
"""
location = self.getLocation(p, 1)
type = p[2]
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 3), p[3])
value = p[5]
p[0] = IDLConst(location, identifier, type, value)
def p_ConstValueBoolean(self, p):
"""
ConstValue : BooleanLiteral
"""
location = self.getLocation(p, 1)
booleanType = BuiltinTypes[IDLBuiltinType.Types.boolean]
p[0] = IDLValue(location, booleanType, p[1])
def p_ConstValueInteger(self, p):
"""
ConstValue : INTEGER
"""
location = self.getLocation(p, 1)
# We don't know ahead of time what type the integer literal is.
# Determine the smallest type it could possibly fit in and use that.
integerType = matchIntegerValueToType(p[1])
if integerType == None:
raise WebIDLError("Integer literal out of range", [location])
p[0] = IDLValue(location, integerType, p[1])
def p_ConstValueFloat(self, p):
"""
ConstValue : FLOATLITERAL
"""
assert False
pass
def p_ConstValueString(self, p):
"""
ConstValue : STRING
"""
location = self.getLocation(p, 1)
stringType = BuiltinTypes[IDLBuiltinType.Types.domstring]
p[0] = IDLValue(location, stringType, p[1])
def p_ConstValueNull(self, p):
"""
ConstValue : NULL
"""
p[0] = IDLNullValue(self.getLocation(p, 1))
def p_BooleanLiteralTrue(self, p):
"""
BooleanLiteral : TRUE
"""
p[0] = True
def p_BooleanLiteralFalse(self, p):
"""
BooleanLiteral : FALSE
"""
p[0] = False
def p_AttributeOrOperation(self, p):
"""
AttributeOrOperation : Attribute
| Operation
"""
p[0] = p[1]
def p_Attribute(self, p):
"""
Attribute : Inherit ReadOnly ATTRIBUTE Type IDENTIFIER SEMICOLON
"""
location = self.getLocation(p, 3)
inherit = p[1]
readonly = p[2]
t = p[4]
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 5), p[5])
p[0] = IDLAttribute(location, identifier, t, readonly, inherit)
def p_ReadOnly(self, p):
"""
ReadOnly : READONLY
"""
p[0] = True
def p_ReadOnlyEmpty(self, p):
"""
ReadOnly :
"""
p[0] = False
def p_Inherit(self, p):
"""
Inherit : INHERIT
"""
p[0] = True
def p_InheritEmpty(self, p):
"""
Inherit :
"""
p[0] = False
def p_Operation(self, p):
"""
Operation : Qualifiers OperationRest
"""
qualifiers = p[1]
# Disallow duplicates in the qualifier set
if not len(set(qualifiers)) == len(qualifiers):
raise WebIDLError("Duplicate qualifiers are not allowed",
[self.getLocation(p, 1)])
static = True if IDLMethod.Special.Static in p[1] else False
# If static is there that's all that's allowed. This is disallowed
# by the parser, so we can assert here.
assert not static or len(qualifiers) == 1
getter = True if IDLMethod.Special.Getter in p[1] else False
setter = True if IDLMethod.Special.Setter in p[1] else False
creator = True if IDLMethod.Special.Creator in p[1] else False
deleter = True if IDLMethod.Special.Deleter in p[1] else False
legacycaller = True if IDLMethod.Special.LegacyCaller in p[1] else False
stringifier = True if IDLMethod.Special.Stringifier in p[1] else False
if getter or deleter:
if setter or creator:
raise WebIDLError("getter and deleter are incompatible with setter and creator",
[self.getLocation(p, 1)])
(returnType, identifier, arguments) = p[2]
assert isinstance(returnType, IDLType)
specialType = IDLMethod.NamedOrIndexed.Neither
if getter or deleter:
if len(arguments) != 1:
raise WebIDLError("%s has wrong number of arguments" %
("getter" if getter else "deleter"),
[self.getLocation(p, 2)])
argType = arguments[0].type
if argType == BuiltinTypes[IDLBuiltinType.Types.domstring]:
specialType = IDLMethod.NamedOrIndexed.Named
elif argType == BuiltinTypes[IDLBuiltinType.Types.unsigned_long]:
specialType = IDLMethod.NamedOrIndexed.Indexed
else:
raise WebIDLError("%s has wrong argument type (must be DOMString or UnsignedLong)" %
("getter" if getter else "deleter"),
[arguments[0].location])
if arguments[0].optional or arguments[0].variadic:
raise WebIDLError("%s cannot have %s argument" %
("getter" if getter else "deleter",
"optional" if arguments[0].optional else "variadic"),
[arguments[0].location])
if getter:
if returnType.isVoid():
raise WebIDLError("getter cannot have void return type",
[self.getLocation(p, 2)])
if setter or creator:
if len(arguments) != 2:
raise WebIDLError("%s has wrong number of arguments" %
("setter" if setter else "creator"),
[self.getLocation(p, 2)])
argType = arguments[0].type
if argType == BuiltinTypes[IDLBuiltinType.Types.domstring]:
specialType = IDLMethod.NamedOrIndexed.Named
elif argType == BuiltinTypes[IDLBuiltinType.Types.unsigned_long]:
specialType = IDLMethod.NamedOrIndexed.Indexed
else:
raise WebIDLError("%s has wrong argument type (must be DOMString or UnsignedLong)" %
("setter" if setter else "creator"),
[arguments[0].location])
if arguments[0].optional or arguments[0].variadic:
raise WebIDLError("%s cannot have %s argument" %
("setter" if setter else "creator",
"optional" if arguments[0].optional else "variadic"),
[arguments[0].location])
if arguments[1].optional or arguments[1].variadic:
raise WebIDLError("%s cannot have %s argument" %
("setter" if setter else "creator",
"optional" if arguments[1].optional else "variadic"),
[arguments[1].location])
if stringifier:
if len(arguments) != 0:
raise WebIDLError("stringifier has wrong number of arguments",
[self.getLocation(p, 2)])
if not returnType.isString():
raise WebIDLError("stringifier must have string return type",
[self.getLocation(p, 2)])
inOptionalArguments = False
variadicArgument = False
for argument in arguments:
# Only the last argument can be variadic
if variadicArgument:
raise WebIDLError("Only the last argument can be variadic",
[variadicArgument.location])
# Once we see an optional argument, there can't be any non-optional
# arguments.
if inOptionalArguments and not argument.optional:
raise WebIDLError("Cannot have a non-optional argument following an optional argument",
[argument.location])
inOptionalArguments = argument.optional
variadicArgument = argument if argument.variadic else None
# identifier might be None. This is only permitted for special methods.
if not identifier:
if not getter and not setter and not creator and \
not deleter and not legacycaller and not stringifier:
raise WebIDLError("Identifier required for non-special methods",
[self.getLocation(p, 2)])
location = BuiltinLocation("<auto-generated-identifier>")
identifier = IDLUnresolvedIdentifier(location, "__%s%s%s%s%s%s%s" %
("named" if specialType == IDLMethod.NamedOrIndexed.Named else \
"indexed" if specialType == IDLMethod.NamedOrIndexed.Indexed else "",
"getter" if getter else "",
"setter" if setter else "",
"deleter" if deleter else "",
"creator" if creator else "",
"legacycaller" if legacycaller else "",
"stringifier" if stringifier else ""), allowDoubleUnderscore=True)
method = IDLMethod(self.getLocation(p, 2), identifier, returnType, arguments,
static=static, getter=getter, setter=setter, creator=creator,
deleter=deleter, specialType=specialType,
legacycaller=legacycaller, stringifier=stringifier)
p[0] = method
def p_QualifiersStatic(self, p):
"""
Qualifiers : STATIC
"""
p[0] = [IDLMethod.Special.Static]
def p_QualifiersSpecials(self, p):
"""
Qualifiers : Specials
"""
p[0] = p[1]
def p_Specials(self, p):
"""
Specials : Special Specials
"""
p[0] = [p[1]]
p[0].extend(p[2])
def p_SpecialsEmpty(self, p):
"""
Specials :
"""
p[0] = []
def p_SpecialGetter(self, p):
"""
Special : GETTER
"""
p[0] = IDLMethod.Special.Getter
def p_SpecialSetter(self, p):
"""
Special : SETTER
"""
p[0] = IDLMethod.Special.Setter
def p_SpecialCreator(self, p):
"""
Special : CREATOR
"""
p[0] = IDLMethod.Special.Creator
def p_SpecialDeleter(self, p):
"""
Special : DELETER
"""
p[0] = IDLMethod.Special.Deleter
def p_SpecialLegacyCaller(self, p):
"""
Special : LEGACYCALLER
"""
p[0] = IDLMethod.Special.LegacyCaller
def p_SpecialStringifier(self, p):
"""
Special : STRINGIFIER
"""
p[0] = IDLMethod.Special.Stringifier
def p_OperationRest(self, p):
"""
OperationRest : ReturnType OptionalIdentifier LPAREN ArgumentList RPAREN SEMICOLON
"""
p[0] = (p[1], p[2], p[4])
def p_OptionalIdentifier(self, p):
"""
OptionalIdentifier : IDENTIFIER
"""
p[0] = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1])
def p_OptionalIdentifierEmpty(self, p):
"""
OptionalIdentifier :
"""
pass
def p_ArgumentList(self, p):
"""
ArgumentList : Argument Arguments
"""
p[0] = [p[1]] if p[1] else []
p[0].extend(p[2])
def p_ArgumentListEmpty(self, p):
"""
ArgumentList :
"""
p[0] = []
def p_Arguments(self, p):
"""
Arguments : COMMA Argument Arguments
"""
p[0] = [p[2]] if p[2] else []
p[0].extend(p[3])
def p_ArgumentsEmpty(self, p):
"""
Arguments :
"""
p[0] = []
def p_Argument(self, p):
"""
Argument : ExtendedAttributeList Optional Type Ellipsis IDENTIFIER DefaultValue
"""
t = p[3]
assert isinstance(t, IDLType)
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 5), p[5])
optional = p[2]
variadic = p[4]
defaultValue = p[6]
if not optional and defaultValue:
raise WebIDLError("Mandatory arguments can't have a default value.",
[self.getLocation(p, 6)])
if variadic:
if optional:
raise WebIDLError("Variadic arguments should not be marked optional.",
[self.getLocation(p, 2)])
optional = variadic
p[0] = IDLArgument(self.getLocation(p, 5), identifier, t, optional, defaultValue, variadic)
p[0].addExtendedAttributes(p[1])
def p_Optional(self, p):
"""
Optional : OPTIONAL
"""
p[0] = True
def p_OptionalEmpty(self, p):
"""
Optional :
"""
p[0] = False
def p_Ellipsis(self, p):
"""
Ellipsis : ELLIPSIS
"""
p[0] = True
def p_EllipsisEmpty(self, p):
"""
Ellipsis :
"""
p[0] = False
def p_ExceptionMember(self, p):
"""
ExceptionMember : Const
| ExceptionField
"""
pass
def p_ExceptionField(self, p):
"""
ExceptionField : Type IDENTIFIER SEMICOLON
"""
pass
def p_ExtendedAttributeList(self, p):
"""
ExtendedAttributeList : LBRACKET ExtendedAttribute ExtendedAttributes RBRACKET
"""
p[0] = [p[2]]
if p[3]:
p[0].extend(p[3])
def p_ExtendedAttributeListEmpty(self, p):
"""
ExtendedAttributeList :
"""
p[0] = []
def p_ExtendedAttribute(self, p):
"""
ExtendedAttribute : ExtendedAttributeNoArgs
| ExtendedAttributeArgList
| ExtendedAttributeIdent
| ExtendedAttributeNamedArgList
"""
p[0] = IDLExtendedAttribute(self.getLocation(p, 1), p[1])
def p_ExtendedAttributeEmpty(self, p):
"""
ExtendedAttribute :
"""
pass
def p_ExtendedAttributes(self, p):
"""
ExtendedAttributes : COMMA ExtendedAttribute ExtendedAttributes
"""
p[0] = [p[2]] if p[2] else []
p[0].extend(p[3])
def p_ExtendedAttributesEmpty(self, p):
"""
ExtendedAttributes :
"""
p[0] = []
def p_Other(self, p):
"""
Other : INTEGER
| FLOATLITERAL
| IDENTIFIER
| STRING
| OTHER
| ELLIPSIS
| COLON
| SCOPE
| SEMICOLON
| LT
| EQUALS
| GT
| QUESTIONMARK
| DATE
| DOMSTRING
| ANY
| ATTRIBUTE
| BOOLEAN
| BYTE
| LEGACYCALLER
| CONST
| CREATOR
| DELETER
| DOUBLE
| EXCEPTION
| FALSE
| FLOAT
| GETTER
| IMPLEMENTS
| INHERIT
| INTERFACE
| LONG
| MODULE
| NULL
| OBJECT
| OCTET
| OPTIONAL
| SEQUENCE
| SETTER
| SHORT
| STATIC
| STRINGIFIER
| TRUE
| TYPEDEF
| UNSIGNED
| VOID
"""
pass
def p_OtherOrComma(self, p):
"""
OtherOrComma : Other
| COMMA
"""
pass
def p_TypeSingleType(self, p):
"""
Type : SingleType
"""
p[0] = p[1]
def p_TypeUnionType(self, p):
"""
Type : UnionType TypeSuffix
"""
p[0] = self.handleModifiers(p[1], p[2])
def p_SingleTypeNonAnyType(self, p):
"""
SingleType : NonAnyType
"""
p[0] = p[1]
def p_SingleTypeAnyType(self, p):
"""
SingleType : ANY TypeSuffixStartingWithArray
"""
p[0] = self.handleModifiers(BuiltinTypes[IDLBuiltinType.Types.any], p[2])
def p_UnionType(self, p):
"""
UnionType : LPAREN UnionMemberType OR UnionMemberType UnionMemberTypes RPAREN
"""
types = [p[2], p[4]]
types.extend(p[5])
p[0] = IDLUnionType(self.getLocation(p, 1), types)
def p_UnionMemberTypeNonAnyType(self, p):
"""
UnionMemberType : NonAnyType
"""
p[0] = p[1]
def p_UnionMemberTypeArrayOfAny(self, p):
"""
UnionMemberTypeArrayOfAny : ANY LBRACKET RBRACKET
"""
p[0] = IDLArrayType(self.getLocation(p, 2),
BuiltinTypes[IDLBuiltinType.Types.any])
def p_UnionMemberType(self, p):
"""
UnionMemberType : UnionType TypeSuffix
| UnionMemberTypeArrayOfAny TypeSuffix
"""
p[0] = self.handleModifiers(p[1], p[2])
def p_UnionMemberTypes(self, p):
"""
UnionMemberTypes : OR UnionMemberType UnionMemberTypes
"""
p[0] = [p[2]]
p[0].extend(p[3])
def p_UnionMemberTypesEmpty(self, p):
"""
UnionMemberTypes :
"""
p[0] = []
def p_NonAnyType(self, p):
"""
NonAnyType : PrimitiveOrStringType TypeSuffix
| ARRAYBUFFER TypeSuffix
| OBJECT TypeSuffix
"""
if p[1] == "object":
type = BuiltinTypes[IDLBuiltinType.Types.object]
elif p[1] == "ArrayBuffer":
type = BuiltinTypes[IDLBuiltinType.Types.ArrayBuffer]
else:
type = BuiltinTypes[p[1]]
p[0] = self.handleModifiers(type, p[2])
def p_NonAnyTypeSequenceType(self, p):
"""
NonAnyType : SEQUENCE LT Type GT Null
"""
innerType = p[3]
type = IDLSequenceType(self.getLocation(p, 1), innerType)
if p[5]:
type = IDLNullableType(self.getLocation(p, 5), type)
p[0] = type
def p_NonAnyTypeScopedName(self, p):
"""
NonAnyType : ScopedName TypeSuffix
"""
assert isinstance(p[1], IDLUnresolvedIdentifier)
type = None
try:
if self.globalScope()._lookupIdentifier(p[1]):
obj = self.globalScope()._lookupIdentifier(p[1])
if obj.isType():
type = obj
else:
type = IDLWrapperType(self.getLocation(p, 1), p[1])
p[0] = self.handleModifiers(type, p[2])
return
except:
pass
type = IDLUnresolvedType(self.getLocation(p, 1), p[1])
p[0] = self.handleModifiers(type, p[2])
def p_NonAnyTypeDate(self, p):
"""
NonAnyType : DATE TypeSuffix
"""
assert False
pass
def p_ConstType(self, p):
"""
ConstType : PrimitiveOrStringType Null
"""
type = BuiltinTypes[p[1]]
if p[2]:
type = IDLNullableType(self.getLocation(p, 1), type)
p[0] = type
def p_ConstTypeIdentifier(self, p):
"""
ConstType : IDENTIFIER Null
"""
identifier = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1])
type = IDLUnresolvedType(self.getLocation(p, 1), identifier)
if p[2]:
type = IDLNullableType(self.getLocation(p, 1), type)
p[0] = type
def p_PrimitiveOrStringTypeUint(self, p):
"""
PrimitiveOrStringType : UnsignedIntegerType
"""
p[0] = p[1]
def p_PrimitiveOrStringTypeBoolean(self, p):
"""
PrimitiveOrStringType : BOOLEAN
"""
p[0] = IDLBuiltinType.Types.boolean
def p_PrimitiveOrStringTypeByte(self, p):
"""
PrimitiveOrStringType : BYTE
"""
p[0] = IDLBuiltinType.Types.byte
def p_PrimitiveOrStringTypeOctet(self, p):
"""
PrimitiveOrStringType : OCTET
"""
p[0] = IDLBuiltinType.Types.octet
def p_PrimitiveOrStringTypeFloat(self, p):
"""
PrimitiveOrStringType : FLOAT
"""
p[0] = IDLBuiltinType.Types.float
def p_PrimitiveOrStringTypeDouble(self, p):
"""
PrimitiveOrStringType : DOUBLE
"""
p[0] = IDLBuiltinType.Types.double
def p_PrimitiveOrStringTypeDOMString(self, p):
"""
PrimitiveOrStringType : DOMSTRING
"""
p[0] = IDLBuiltinType.Types.domstring
def p_UnsignedIntegerTypeUnsigned(self, p):
"""
UnsignedIntegerType : UNSIGNED IntegerType
"""
p[0] = p[2] + 1 # Adding one to a given signed integer type
# gets you the unsigned type.
def p_UnsignedIntegerType(self, p):
"""
UnsignedIntegerType : IntegerType
"""
p[0] = p[1]
def p_IntegerTypeShort(self, p):
"""
IntegerType : SHORT
"""
p[0] = IDLBuiltinType.Types.short
def p_IntegerTypeLong(self, p):
"""
IntegerType : LONG OptionalLong
"""
if p[2]:
p[0] = IDLBuiltinType.Types.long_long
else:
p[0] = IDLBuiltinType.Types.long
def p_OptionalLong(self, p):
"""
OptionalLong : LONG
"""
p[0] = True
def p_OptionalLongEmpty(self, p):
"""
OptionalLong :
"""
p[0] = False
def p_TypeSuffixBrackets(self, p):
"""
TypeSuffix : LBRACKET RBRACKET TypeSuffix
"""
p[0] = [(IDLMethod.TypeSuffixModifier.Brackets, self.getLocation(p, 1))]
p[0].extend(p[3])
def p_TypeSuffixQMark(self, p):
"""
TypeSuffix : QUESTIONMARK TypeSuffixStartingWithArray
"""
p[0] = [(IDLMethod.TypeSuffixModifier.QMark, self.getLocation(p, 1))]
p[0].extend(p[2])
def p_TypeSuffixEmpty(self, p):
"""
TypeSuffix :
"""
p[0] = []
def p_TypeSuffixStartingWithArray(self, p):
"""
TypeSuffixStartingWithArray : LBRACKET RBRACKET TypeSuffix
"""
p[0] = [(IDLMethod.TypeSuffixModifier.Brackets, self.getLocation(p, 1))]
p[0].extend(p[3])
def p_TypeSuffixStartingWithArrayEmpty(self, p):
"""
TypeSuffixStartingWithArray :
"""
p[0] = []
def p_Null(self, p):
"""
Null : QUESTIONMARK
|
"""
if len(p) > 1:
p[0] = True
else:
p[0] = False
def p_ReturnTypeType(self, p):
"""
ReturnType : Type
"""
p[0] = p[1]
def p_ReturnTypeVoid(self, p):
"""
ReturnType : VOID
"""
p[0] = BuiltinTypes[IDLBuiltinType.Types.void]
def p_ScopedName(self, p):
"""
ScopedName : AbsoluteScopedName
| RelativeScopedName
"""
p[0] = p[1]
def p_AbsoluteScopedName(self, p):
"""
AbsoluteScopedName : SCOPE IDENTIFIER ScopedNameParts
"""
assert False
pass
def p_RelativeScopedName(self, p):
"""
RelativeScopedName : IDENTIFIER ScopedNameParts
"""
assert not p[2] # Not implemented!
p[0] = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1])
def p_ScopedNameParts(self, p):
"""
ScopedNameParts : SCOPE IDENTIFIER ScopedNameParts
"""
assert False
pass
def p_ScopedNamePartsEmpty(self, p):
"""
ScopedNameParts :
"""
p[0] = None
def p_ExtendedAttributeNoArgs(self, p):
"""
ExtendedAttributeNoArgs : IDENTIFIER
"""
p[0] = (p[1],)
def p_ExtendedAttributeArgList(self, p):
"""
ExtendedAttributeArgList : IDENTIFIER LPAREN ArgumentList RPAREN
"""
p[0] = (p[1], p[3])
def p_ExtendedAttributeIdent(self, p):
"""
ExtendedAttributeIdent : IDENTIFIER EQUALS STRING
| IDENTIFIER EQUALS IDENTIFIER
"""
p[0] = (p[1], p[3])
def p_ExtendedAttributeNamedArgList(self, p):
"""
ExtendedAttributeNamedArgList : IDENTIFIER EQUALS IDENTIFIER LPAREN ArgumentList RPAREN
"""
p[0] = (p[1], p[3], p[5])
def p_error(self, p):
if not p:
raise WebIDLError("Syntax Error at end of file. Possibly due to missing semicolon(;), braces(}) or both", [])
else:
raise WebIDLError("invalid syntax", [Location(self.lexer, p.lineno, p.lexpos, self._filename)])
def __init__(self, outputdir='', lexer=None):
Tokenizer.__init__(self, outputdir, lexer)
self.parser = yacc.yacc(module=self,
outputdir=outputdir,
tabmodule='webidlyacc',
errorlog=yacc.NullLogger(),
picklefile='WebIDLGrammar.pkl')
self._globalScope = IDLScope(BuiltinLocation("<Global Scope>"), None, None)
self._installBuiltins(self._globalScope)
self._productions = []
self._filename = "<builtin>"
self.lexer.input(Parser._builtins)
self._filename = None
self.parser.parse(lexer=self.lexer,tracking=True)
def _installBuiltins(self, scope):
assert isinstance(scope, IDLScope)
# xrange omits the last value.
for x in xrange(IDLBuiltinType.Types.ArrayBuffer, IDLBuiltinType.Types.Float64Array + 1):
builtin = BuiltinTypes[x]
name = builtin.name
typedef = IDLTypedefType(BuiltinLocation("<builtin type>"), builtin, name)
typedef.resolve(scope)
@ staticmethod
def handleModifiers(type, modifiers):
for (modifier, modifierLocation) in modifiers:
assert modifier == IDLMethod.TypeSuffixModifier.QMark or \
modifier == IDLMethod.TypeSuffixModifier.Brackets
if modifier == IDLMethod.TypeSuffixModifier.QMark:
type = IDLNullableType(modifierLocation, type)
elif modifier == IDLMethod.TypeSuffixModifier.Brackets:
type = IDLArrayType(modifierLocation, type)
return type
def parse(self, t, filename=None):
self.lexer.input(t)
#for tok in iter(self.lexer.token, None):
# print tok
self._filename = filename
self._productions.extend(self.parser.parse(lexer=self.lexer,tracking=True))
self._filename = None
def finish(self):
# First, finish all the IDLImplementsStatements. In particular, we
# have to make sure we do those before we do the IDLInterfaces.
# XXX khuey hates this bit and wants to nuke it from orbit.
implementsStatements = [ p for p in self._productions if
isinstance(p, IDLImplementsStatement)]
otherStatements = [ p for p in self._productions if
not isinstance(p, IDLImplementsStatement)]
for production in implementsStatements:
production.finish(self.globalScope())
for production in otherStatements:
production.finish(self.globalScope())
# Do any post-finish validation we need to do
for production in self._productions:
production.validate()
# De-duplicate self._productions, without modifying its order.
seen = set()
result = []
for p in self._productions:
if p not in seen:
seen.add(p)
result.append(p)
return result
def reset(self):
return Parser(lexer=self.lexer)
# Builtin IDL defined by WebIDL
_builtins = """
typedef unsigned long long DOMTimeStamp;
"""
def main():
# Parse arguments.
from optparse import OptionParser
usageString = "usage: %prog [options] files"
o = OptionParser(usage=usageString)
o.add_option("--cachedir", dest='cachedir', default=None,
help="Directory in which to cache lex/parse tables.")
o.add_option("--verbose-errors", action='store_true', default=False,
help="When an error happens, display the Python traceback.")
(options, args) = o.parse_args()
if len(args) < 1:
o.error(usageString)
fileList = args
baseDir = os.getcwd()
# Parse the WebIDL.
parser = Parser(options.cachedir)
try:
for filename in fileList:
fullPath = os.path.normpath(os.path.join(baseDir, filename))
f = open(fullPath, 'rb')
lines = f.readlines()
f.close()
print fullPath
parser.parse(''.join(lines), fullPath)
parser.finish()
except WebIDLError, e:
if options.verbose_errors:
traceback.print_exc()
else:
print e
if __name__ == '__main__':
main()
| StarcoderdataPython |
6525070 | <reponame>xinlc/selenium-learning<gh_stars>0
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
from .test_admin_login import TestAdminLogin
import unittest
class TestCategory(unittest.TestCase):
# @classmethod
# def setUpClass(cls) -> None:
# cls.login = TestAdminLogin()
# runner = unittest.TextTestRunner()
# runner.run(cls.login)
def __init__(self, method, login):
unittest.TestCase.__init__(self, method)
# super.__init__(self, method)
self.login = login
# 测试文章分类失败,名称为空
def test_add_category_error(self):
name = ''
parent = 'python'
slug = 'test'
expected = '分类名称不能为空'
# 点击文章
self.login.driver.find_element_by_xpath('//*[@id="sidebar-menu"]/li[4]/a/span[1]').click()
sleep(1)
# 点击分类
self.login.driver.find_element_by_xpath('//*[@id="sidebar-menu"]/li[4]/ul/li[3]/a').click()
sleep(1)
# 输入分类名称
self.login.driver.find_element_by_name('category.title').send_keys(name)
# 选择父分类
parent_category_elem = self.login.driver.find_element_by_name('category.pid')
Select(parent_category_elem).select_by_visible_text(parent)
# 输入slug
self.login.driver.find_element_by_name('category.slug').send_keys(slug)
# 点击添加
self.login.driver.find_element_by_xpath(
'/html/body/div/div/section[2]/div/div[1]/div/form/div[2]/div/div/button').click()
loc = (By.CLASS_NAME, 'toast-message')
WebDriverWait(self.login.driver, 5).until(EC.visibility_of_element_located(loc))
msg = self.login.driver.find_element(*loc).text
assert msg == expected
# 测试文章分类成功
def test_add_category_ok(self):
name = 'test'
parent = 'python'
slug = 'test'
expected = None
# 点击文章
# 上一个测试直接 点击分类
# self.login.driver.find_element_by_xpath('//*[@id="sidebar-menu"]/li[4]/a/span[1]').click()
sleep(1)
# 点击分类
self.login.driver.find_element_by_xpath('//*[@id="sidebar-menu"]/li[4]/ul/li[3]/a').click()
sleep(1)
# 输入分类名称
self.login.driver.find_element_by_name('category.title').clear()
self.login.driver.find_element_by_name('category.title').send_keys(name)
# 选择父分类
parent_category_elem = self.login.driver.find_element_by_name('category.pid')
Select(parent_category_elem).select_by_visible_text(parent)
# 输入slug
self.login.driver.find_element_by_name('category.slug').clear()
self.login.driver.find_element_by_name('category.slug').send_keys(slug)
# 点击添加
self.login.driver.find_element_by_xpath(
'/html/body/div/div/section[2]/div/div[1]/div/form/div[2]/div/div/button').click()
# 没有异常就添加成功,没有提示信息
assert 1 == 1
def runTest(self):
self.test_add_category_error()
self.test_add_category_ok()
# 以下代码 在main中测试
# from testcase.unittest import \
# test_user_register, \
# test_admin_login, \
# test_user_login,\
# test_category,\
# test_article
# import unittest
#
# if __name__ == '__main__':
#
# adminLoginCase = test_admin_login.TestAdminLogin('test_admin_login_code_ok')
# categoryCase = test_category.TestCategory('test_add_category_ok', adminLoginCase)
#
# suite = unittest.TestSuite()
#
# suite.addTest(adminLoginCase)
# suite.addTest(categoryCase)
#
# runner = unittest.TextTestRunner()
# runner.run(suite)
| StarcoderdataPython |
5019549 | from collections import deque
import numpy as np
import matplotlib.pyplot as plt
from .layers import *
from .visualizer import Visualizer
class Model:
"""The Neural Net."""
def __init__(self, inputs, outputs):
self.inputs = inputs
self.outputs = outputs
def compile(self, optimizer, loss, n_classes):
self.optimizer = optimizer
self.loss = loss
self.n_classes = n_classes
self.layers = []
x = self.inputs
while 1:
if not isinstance(x, (Input, Dropout)):
x.init_bias()
x.init_weights()
self.layers.append(x)
if hasattr(x, "next_layer"):
x = x.next_layer
else:
break
assert self.layers[-1] is self.outputs
def fit(self, x, y, batch_size=None, n_epochs=1, val_data=None):
assert len(x) == len(y)
vis = Visualizer(n_epochs)
y_onehot = np.eye(self.n_classes)[y]
if not batch_size:
batch_size = len(x)
for e in range(n_epochs):
print("Epoch {}:".format(e))
loss = self.optimizer.optimize(self, x, y_onehot, batch_size)
accu = self.evaluate(x, y)
print("Loss: {}\tAccu: {}".format(loss, accu), end="\t")
val_loss, val_accu = None, None
if val_data:
x_test, y_test = val_data
y_test_onehot = np.eye(self.n_classes)[y_test]
a_test = self.predict(x_test)
val_loss = self.loss.f(y_test_onehot.T, a_test.T)
for l in range(1, len(self.layers)):
if not self.layers[l].trainable:
continue
val_loss += self.layers[l].regularization()
val_accu = self.evaluate(x_test, y_test)
print("Val_loss: {}\tVal_accu: {}".format(val_loss, val_accu))
print()
vis.update_loss(loss, val_loss)
vis.update_accu(accu, val_accu)
plt.pause(0.05)
plt.show()
def predict(self, x):
self.inputs.forward(x.T)
for l in range(1, len(self.layers)):
self.layers[l].forward(is_training=False)
return self.outputs.activations.T
def evaluate(self, x, y):
predicts = self.predict(x).argmax(axis=-1)
return len(np.where(y == predicts)[0]) / len(y)
| StarcoderdataPython |
4864026 | # @Author: <NAME>@2022
# String/Char Variable Literal Examples
strings = "hello world"
char = "h"
multilineString = """Hello World \
Hello World"""
uniCode = u"\u0048\u0065\u006c\u006c\u006f \u0057\u006f\u0072\u006c\u0064"
rawString = "Hello \n World"
if __name__ == '__main__':
print(strings)
print(char)
print(multilineString)
print(uniCode)
print(rawString)
| StarcoderdataPython |
334800 | <reponame>rbiswas4/utils<gh_stars>0
#!/usr/bin/env python
"""
module to help in plotting.
Functions:
inputExplorer: slider functionality to help in exploring functions
drawxband : drawing shaded regions of specific width around a value,
helpful in ratio/residual plots
settwopanel : returns a figure and axes for two subplots to show the
functional form and differentials of the function with reference
to a fiducial set of values.
"""
import typeutils as tu
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider, Button
__all__ = ['inputExplorer', 'settwopanel', 'threepanel', 'drawxband']
def inputExplorer(f, sliders_properties, wait_for_validation=False):
""" A light GUI to manually explore and tune the outputs of a function.
taken from http://zulko.wordpress.com/2012/08/18/a-gui-for-the-exploration-of-functions-with-python-matplotlib/
args:
f : callable function to return values (for text outputs) or
plot figure. For graphics, it should clear an axes ax
and plot the function with its parameter values on
the figure.
Example: def func(a) :
ax.clear()
ax.plot( x, np.sin(a*x)
fig.canvas.draw()
slider_properties: list of dicts
arguments for Slider: each element of the list should be be a dict with keys "label", "valmax", "valmin" with
string, float, float values respectively. There should
be a dict corresponding to each variable to vary in the
slider.
Example: [{"label":"a", "valmax" :2.0, "valmin":-2.0}]
status:
tested , <NAME>, Tue Apr 29 10:43:07 CDT 2014
example_usage:
>>> x = np.arange(0,10,0.1)
>>> fig, ax = plt.subplots(1)
>>> def func (a , doclear = True) :
>>> if doclear:
>>> ax.clear()
>>> ax.plot( x, np.sin(a*x) )
>>> fig.canvas.draw()
>>> inputExplorer ( func, [{'label':'a', 'valmin' : -1, 'valmax' : 1}])
"""
nVars = len(sliders_properties)
slider_width = 1.0 / nVars
print slider_width
# CREATE THE CANVAS
figure, ax = plt.subplots(1)
figure.canvas.set_window_title("Inputs for '%s'" % (f.func_name))
# choose an appropriate height
width, height = figure.get_size_inches()
height = min(0.5 * nVars, 8)
figure.set_size_inches(width, height, forward=True)
# hide the axis
ax.set_frame_on(False)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# CREATE THE SLIDERS
sliders = []
for i, properties in enumerate(sliders_properties):
ax = plt.axes([0.1, 0.95 - 0.9 * (i + 1) * slider_width,
0.8, 0.8 * slider_width])
sliders.append(Slider(ax=ax, **properties))
# CREATE THE CALLBACK FUNCTIONS
def on_changed(event):
res = f(*(s.val for s in sliders))
if res is not None:
print res
def on_key_press(event):
if event.key is 'enter':
on_changed(event)
figure.canvas.mpl_connect('key_press_event', on_key_press)
# AUTOMATIC UPDATE ?
if not wait_for_validation:
for s in sliders:
s.on_changed(on_changed)
# DISPLAY THE SLIDERS
plt.show()
def drawxband(refval,
xlims=None,
color='gray',
bandwidths=[-0.1, 0.1],
ua=None):
"""
draw a shaded band of color color of certain width around a single
reference value refval
Parameters
----------
refval : float , mandatory
scalar (single) reference value,
Example: refval = 1.0
xlims : list of two floats, optional, defaults to None min and max x
values through which the band will be drawn. if None, these values are
set from the limits of the supplied axessubplot. If axessubplots is not
supplied this will raise an error
color : python color style, optional,defaults to 'gray' color of the band
bandwidths : list of two floats, optional default to [-0.1, 0.1] width of
the band to be shaded.
ua : optional, defaults to None
`~matplotlib.pyplot.axes.subplot` instance on which to, if None,
obtains the current axes
returns:
axes object
example usage:
>>> #To use an existing axes subplot object
>>> drawxband (refval = 60., bandwidths = [-20.,20.], color = 'green', ua = myax0)
>>> #No axes object is available
>>> drawxband (refval = 60., xlims = [4., 8.] , bandwidths = [-20.,20.],color = 'green')
status: Tests in plot_utils main.
tested <NAME>, Fri Apr 18 08:29:54 CDT 2014
"""
if ua is None:
ua = plt.gca()
else:
# plt.sca(ua)
xl, xh = ua.get_xlim()
if xlims is None:
xlims = [xl, xh]
# really started this conditional statement to make it general,
# but have not finished, will always go to the else condition
# in current implementation
if xlims is None:
if not tu.isiterable(refval):
raise ValueError( "To draw band supply either refval as numpy"
"array or xlims over which it should be drawn")
else:
xvals = np.linspace(xlims[0], xlims[1], 2)
# refvals = refval *np.ones(len(xvals)
# plot reference value
ua.axhline(refval, color='k', lw=2.0)
# draw band
ua.fill_between(xvals, refval + bandwidths[0], refval + bandwidths[1],
color=color, alpha=0.25)
return ua
def settwopanel(height_ratios=[1.0, 0.3],
width_ratios=[1., 0.],
padding=None,
setdifflimits=[0.9, 1.1],
setoffset=None,
setgrid=[True, True],
figsize=None):
"""
returns a figure and axes for a main panel and a lower panel for
showing differential information of overplotted quantities in
the top panel.
args :
height_ratios: list of floats, optional defaults to
[1.0, 0.3]
height ratio between the upper and lower panel
width_ratios :list of floats, optional defaults to
[1.0, 0.0]
width ratio between the left and right panel
figsize: figure size
setgrid : List of bools, optional, defaults to [True, True]
whether to set grid on the two panels
returns :
figure object , ax0 (axes for top panel) , and ax1
(axes for lower panel)
usage :
>>> myfig, myax0 , myax1 = settwopanel ( )
>>> myax0.plot( x, y)
>>> myax1.plot(x, x)
>>> myfig.tight_layout()
status :
tested by
<NAME>, Fri Feb 21 00:52:55 CST 2014
"""
import matplotlib.ticker as ticker
majorformatter = ticker.ScalarFormatter(useOffset=False)
if figsize == None:
fig = plt.figure()
else:
fig = plt.figure(figsize=figsize)
gs = gridspec.GridSpec(
2, 1, width_ratios=width_ratios, height_ratios=height_ratios)
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])
if setdifflimits != None:
ax1.set_ylim(setdifflimits)
ax0.set_xticklabels("", visible=False)
ax1.yaxis.set_major_formatter(majorformatter)
if setgrid[0]:
ax0.grid(True)
if setgrid[1]:
ax1.grid(True)
hpad = 0.0
#gridspec.update(hpad = hpad)
return fig, ax0, ax1
if __name__ == "__main__":
x = np.arange(0, 10, 0.1)
y = x * x
fig, ax = plt.subplots(1)
def func(a, doclear=True):
if doclear:
ax.clear()
ax.plot(x, np.sin(a * x))
fig.canvas.draw()
inputExplorer(func, [{'label': 'a', 'valmin': -1, 'valmax': 1}])
myfig, myax0, myax1 = settwopanel()
myax0.plot(x, y)
drawxband(refval=60., bandwidths=[-20., 20.], color='green', ua=myax0)
#myax1.plot(x, x)
myfig.tight_layout()
plt.figure()
plt.plot(x, y)
drawxband(
refval=60., xlims=[4., 8.], bandwidths=[-20., 20.], color='green')
plt.show()
def threepanel():
fig = plt.figure()
gs = gridspec.GridSpec(
3, 1, height_ratios=[0.33, 0.33, 0.33], width_ratios=[1., 0., 0.])
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])
ax2 = plt.subplot(gs[2])
return gs, fig, ax0, ax1, ax2
| StarcoderdataPython |
3374365 | <gh_stars>0
# Generated by Django 3.0.8 on 2020-07-26 05:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('conferences', '0002_auto_20200725_2215'),
('review', '0002_auto_20200725_2215'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name='reviewer',
name='user',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='reviewdecisiontype',
name='allowed_proceedings',
field=models.ManyToManyField(related_name='decision_types', to='conferences.ProceedingType'),
),
migrations.AddField(
model_name='reviewdecisiontype',
name='conference',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='conferences.Conference'),
),
migrations.AddField(
model_name='reviewdecision',
name='decision_type',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='decisions', to='review.ReviewDecisionType'),
),
migrations.AddField(
model_name='reviewdecision',
name='stage',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='decision', to='review.ReviewStage'),
),
migrations.AddField(
model_name='review',
name='reviewer',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to='review.Reviewer'),
),
migrations.AddField(
model_name='review',
name='stage',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='review.ReviewStage'),
),
migrations.AlterUniqueTogether(
name='reviewdecisiontype',
unique_together={('conference', 'decision', 'description')},
),
]
| StarcoderdataPython |
17976 | from pyramid.httpexceptions import HTTPConflict
from h.auth.util import client_authority
from h.presenters import TrustedUserJSONPresenter
from h.schemas import ValidationError
from h.schemas.api.user import CreateUserAPISchema, UpdateUserAPISchema
from h.services.user_unique import DuplicateUserError
from h.views.api.config import api_config
from h.views.api.exceptions import PayloadError
@api_config(
versions=["v1", "v2"],
route_name="api.user_read",
request_method="GET",
link_name="user.read",
description="Fetch a user",
permission="read",
)
def read(context, _request):
"""
Fetch a user.
This API endpoint allows authorized clients (those able to provide a valid
Client ID and Client Secret) to read users in their authority.
"""
return TrustedUserJSONPresenter(context.user).asdict()
@api_config(
versions=["v1", "v2"],
route_name="api.users",
request_method="POST",
link_name="user.create",
description="Create a new user",
permission="create",
)
def create(request):
"""
Create a user.
This API endpoint allows authorised clients (those able to provide a valid
Client ID and Client Secret) to create users in their authority. These
users are created pre-activated, and are unable to log in to the web
service directly.
Note: the authority-enforcement logic herein is, by necessity, strange.
The API accepts an ``authority`` parameter but the only valid value for
the param is the client's verified authority. If the param does not
match the client's authority, ``ValidationError`` is raised.
:raises ValidationError: if ``authority`` param does not match client
authority
:raises HTTPConflict: if user already exists
"""
client_authority_ = client_authority(request)
schema = CreateUserAPISchema()
appstruct = schema.validate(_json_payload(request))
# Enforce authority match
if appstruct["authority"] != client_authority_:
raise ValidationError(
"authority '{auth_param}' does not match client authority".format(
auth_param=appstruct["authority"]
)
)
user_unique_service = request.find_service(name="user_unique")
try:
user_unique_service.ensure_unique(appstruct, authority=client_authority_)
except DuplicateUserError as err:
raise HTTPConflict(str(err)) from err
user_signup_service = request.find_service(name="user_signup")
user = user_signup_service.signup(require_activation=False, **appstruct)
presenter = TrustedUserJSONPresenter(user)
return presenter.asdict()
@api_config(
versions=["v1", "v2"],
route_name="api.user",
request_method="PATCH",
link_name="user.update",
description="Update a user",
permission="update",
)
def update(user, request):
"""
Update a user.
This API endpoint allows authorised clients (those able to provide a valid
Client ID and Client Secret) to update users in their authority.
"""
schema = UpdateUserAPISchema()
appstruct = schema.validate(_json_payload(request))
user_update_service = request.find_service(name="user_update")
user = user_update_service.update(user, **appstruct)
presenter = TrustedUserJSONPresenter(user)
return presenter.asdict()
def _json_payload(request):
try:
return request.json_body
except ValueError as err:
raise PayloadError() from err
| StarcoderdataPython |
9758345 | import os
import platform
import sys
IS_WINDOWS = platform.system() == 'Windows' or os.name == 'nt'
IS_PYTHON2 = sys.version_info.major == 2 or sys.version < '3'
IS_PYTHON35_UP = sys.version >= '3.5'
BASESTRING = basestring if IS_PYTHON2 else str
UNICODE = unicode if IS_PYTHON2 else str
LONG = long if IS_PYTHON2 else int
if IS_PYTHON2:
from dis_sdk_python.com.huaweicloud.dis.sdk.python.models.model_python2 import _BaseModel
else:
from dis_sdk_python.com.huaweicloud.dis.sdk.python.models.model_python3 import _BaseModel
BaseModel = _BaseModel | StarcoderdataPython |
5028509 | <gh_stars>0
import abc
from wdim.util import pack
from wdim.orm import fields
from wdim.orm import exceptions
class StorableMeta(abc.ABCMeta):
STORABLE_CLASSES = {}
def __init__(cls, name, bases, dct):
super().__init__(name, bases, dct)
cls._collection_name = cls.__name__.lower()
cls._fields = {}
for key, value in cls.__dict__.items():
if not isinstance(value, fields.Field):
continue
value._name = key
cls._fields[key] = value
cls._fields = {
key: value
for key, value
in cls.__dict__.items()
if isinstance(value, fields.Field)
}
if cls.__name__ != 'Storable':
assert '_id' in cls._fields, '_id must be specified'
StorableMeta.STORABLE_CLASSES[cls._collection_name] = cls
class _ConnectionAssertion:
def __get__(self, inst, owner):
raise ValueError('connect must be called before interacting with the database')
class Storable(metaclass=StorableMeta):
_DATABASE = _ConnectionAssertion()
@classmethod
def ClassGetter(cls, name):
def getter():
try:
return StorableMeta.STORABLE_CLASSES[name.lower()]
except KeyError:
raise KeyError('Class {} not found'.format(name))
return getter
@classmethod
async def _bootstrap(cls):
for klass in Storable.__subclasses__():
indices = [
pack(key, unique=value.unique, order=1)
for key, value in klass._fields.items()
if value.index
]
if getattr(klass, 'Meta', None) and getattr(klass.Meta, 'indexes', None):
indices.extend(klass.Meta.indexes)
await cls._DATABASE.ensure_index(klass._collection_name, indices)
return True
@classmethod
async def connect(cls, db, bootstrap=True):
cls._DATABASE = db
if bootstrap:
return await cls._bootstrap()
return True
@classmethod
async def create(cls, *, _id=None, **kwargs):
if _id:
inst = cls(_id=_id, **kwargs)
else:
inst = cls(**kwargs)
db_id = await cls._DATABASE.insert(inst)
if _id:
assert _id == db_id, 'Database _id did not match given _id'
cls._fields['_id'].__set__(inst, db_id, override=True)
return inst
@classmethod
async def upsert(cls, *, _id=None, **kwargs):
if _id:
inst = cls(_id=_id, **kwargs)
else:
inst = cls(**kwargs)
db_id = await cls._DATABASE.upsert(inst)
if _id:
assert _id == db_id, 'Database _id did not match given _id'
cls._fields['_id'].__set__(inst, db_id, override=True)
return inst
@classmethod
def from_document(cls, document):
return cls(**document)
@classmethod
async def find_one(cls, query):
doc = await cls._DATABASE.find_one(cls, query)
if not doc:
raise exceptions.NotFound()
return cls.from_document(doc)
@classmethod
async def find(cls, query=None, limit=0, skip=0, sort=None):
return (
cls.from_document(doc)
for doc in
await cls._DATABASE.find(cls, query=query, limit=limit, skip=skip, sort=sort)
)
@classmethod
async def load(cls, _id):
return cls.from_document(await cls._DATABASE.load(cls, _id))
def __init__(self, **kwargs):
assert set(kwargs.keys()).issubset(self._fields.keys()), 'Specified a key that is not in fields'
self._data = {
key: value.parse(kwargs.get(key))
for key, value in self._fields.items()
}
def to_document(self, translator=None):
if translator:
translate = translator.translate_field
else:
translate = lambda field, data: field.to_document(data)
return {
key: translate(field, self._data.get(key))
for key, field in self._fields.items()
}
async def embed(self, translator=None):
if translator:
translate = translator.translate_field
else:
translate = lambda field, data: field.to_document(data)
ret = {}
for key, field in self._fields.items():
if isinstance(field, fields.ForeignField):
foreign = getattr(self, key)
if foreign:
ret[key] = await(await foreign).embed(translator=translator)
continue
ret[key] = translate(field, self._data.get(key))
return ret
| StarcoderdataPython |
15737 | <gh_stars>0
a=''
n=int(input())
while n != 0:
a=str(n%2)+a
n//=2
print(a)
| StarcoderdataPython |
11374648 | <reponame>XanderWander/MasterMind<gh_stars>0
from src.Game import Game
from src.GameData import GameType, Color, Answer, Guess, GameData
from src.View import View, ViewType
from src.Solver import AI, AI_Type
from src.Utils import calc_all_questions, calc_answer | StarcoderdataPython |
5083943 | #!/usr/bin/python
import sys
import argparse
import os
parser = argparse.ArgumentParser(description="Make helper parser")
parser.add_argument("--directory", dest="directory", required=True)
parser.add_argument("--library", dest="library", help="Make a library")
parser.add_argument("--binary", dest="binary", help="Make a binary")
parser.add_argument("--exclude", dest="exclude", help="Exclude file", action="append")
PREFIX=None
LIBRARY=None
BINARY=None
EXCLUDE=[]
def make_o(x):
return os.path.splitext(x)[0] + ".o"
def write_cpp_rule(f, x):
src = "$(%s_SRCDIR)/%s"%(PREFIX, x)
dst = "$(%s_SRCDIR)/%s"%(PREFIX, make_o(x))
f.write("%s: %s\n"%(dst, src))
f.write('\t$(CXX) $(CFLAGS) $(CXXFLAGS) $(INCLUDES) $(' + PREFIX + '_CFLAGS) $(' + PREFIX + '_INCLUDES) -c -o ' + dst + ' ' + src + '\n');
f.write("\n")
def write_asm_rule(f, x):
src = "$(%s_SRCDIR)/%s"%(PREFIX, x)
dst = "$(%s_SRCDIR)/%s"%(PREFIX, make_o(x))
f.write("%s: %s\n"%(dst, src))
f.write('\t$(ASM) $(ASMFLAGS) $(ASM_INCLUDES) $(' + PREFIX + '_ASMFLAGS) $(' + PREFIX + '_ASM_INCLUDES) -o ' + dst + ' ' + src + '\n');
f.write("\n")
def find_sources():
cpp_files = []
asm_files = []
print EXCLUDE
for dir in os.walk("."):
for file in dir[2]:
if not file in EXCLUDE:
if os.path.splitext(file)[1] == '.cpp':
cpp_files.append(os.path.join(dir[0], file))
if os.path.splitext(file)[1] == '.asm':
asm_files.append(os.path.join(dir[0], file))
return [cpp_files, asm_files]
args = parser.parse_args()
if args.library is not None:
PREFIX=args.library.upper()
elif args.binary is not None:
PREFIX=args.binary.upper()
else:
sys.stderr.write("Must provide either library or binary")
sys.exit(1)
if args.exclude is not None:
EXCLUDE = args.exclude
(cpp, asm) = find_sources()
f = open("targets.mk", "w")
f.write("%s_PREFIX=%s\n"%(PREFIX, PREFIX))
f.write("%s_SRCDIR=%s\n"%(PREFIX, args.directory))
f.write("%s_CPP_SRCS=\\\n"%(PREFIX))
for c in cpp:
f.write("\t$(%s_SRCDIR)/%s\\\n"%(PREFIX, c))
f.write("\n")
f.write("%s_OBJS += $(%s_CPP_SRCS:.cpp=.o)\n"%(PREFIX, PREFIX))
f.write("ifeq ($(USE_ASM), Yes)\n");
f.write("%s_ASM_SRCS=\\\n"%(PREFIX))
for c in asm:
f.write("\t$(%s_SRCDIR)/%s\\\n"%(PREFIX, c))
f.write("\n")
f.write("%s_OBJS += $(%s_ASM_SRCS:.asm=.o)\n"%(PREFIX, PREFIX))
f.write("endif\n\n")
f.write("OBJS += $(%s_OBJS)\n"%PREFIX)
for c in cpp:
write_cpp_rule(f, c)
for a in asm:
write_asm_rule(f, a)
if args.library is not None:
f.write("$(LIBPREFIX)%s.$(LIBSUFFIX): $(%s_OBJS)\n"%(args.library, PREFIX));
f.write("\trm -f $(LIBPREFIX)%s.$(LIBSUFFIX)\n"%args.library)
f.write("\tar cr $@ $(%s_OBJS)\n"%PREFIX);
f.write("\n");
f.write("libraries: $(LIBPREFIX)%s.$(LIBSUFFIX)\n"%args.library);
f.write("LIBRARIES += $(LIBPREFIX)%s.$(LIBSUFFIX)\n"%args.library);
if args.binary is not None:
f.write("%s: $(%s_OBJS) $(LIBS) $(%s_LIBS)\n"%(args.binary, PREFIX, PREFIX))
f.write("\t$(CXX) -o $@ $(%s_OBJS) $(%s_LDFLAGS) $(%s_LIBS) $(LDFLAGS) $(LIBS)\n\n"%(PREFIX, PREFIX, PREFIX))
f.write("binaries: %s\n"%args.binary);
f.write("BINARIES += %s\n"%args.binary);
| StarcoderdataPython |
3580588 | from django_jinja import library
from olympia.zadmin.models import get_config as zadmin_get_config
@library.global_function
def get_config(key):
return zadmin_get_config(key)
| StarcoderdataPython |
78052 | import datetime
import os
import sys
import traceback
from os.path import expanduser
from shutil import copyfile
import nose.plugins.base
from jinja2 import Environment, FileSystemLoader
from nose.plugins.base import Plugin
class MarketFeatures(Plugin):
"""
provide summery report of executed tests listed per market feature
"""
name = 'market-features'
def __init__(self):
super(MarketFeatures, self).__init__()
self.results = {"results": []}
self.exceptions = {'exceptions': []}
self.starting_tests = {'timer': []}
self.feature_time = None
self.test_time = None
@staticmethod
def begin():
print("begin")
MarketFeatures._check_report_name_file()
@staticmethod
def _check_report_name_file():
home = expanduser("~")
report_file_name = home + '/.market_features/report_name.dat'
if not os.path.exists(report_file_name):
if not os.path.isdir(home + '/.market_features/'):
os.makedirs(home + '/.market_features/')
file_write = open(report_file_name, 'w+')
file_write.write("")
with open(report_file_name, "r") as saved_file:
generate_report_name = saved_file.read().replace('\n', '')
MarketFeatures.report_file_name = generate_report_name
if not MarketFeatures.report_file_name:
MarketFeatures.report_file_name = "Functional Tests"
def help(self):
return "provide summery report of executed tests listed per market feature"
def startTest(self, test):
address = test.address()
message = test.shortDescription() if test.shortDescription() else str(address[-1]).split('.')[-1]
self.starting_tests['timer'].append(message)
self.feature_time = datetime.datetime.now()
def addError(self, test, err):
end_time = datetime.datetime.now()
if not self.feature_time:
self.feature_time = end_time
report_test_time = end_time - self.feature_time
t = report_test_time
milliseconds = (t.days * 24 * 60 * 60 + t.seconds) * 1000 + t.microseconds / 1000.0
exc_type, exc_value, exc_traceback = sys.exc_info()
t_len = traceback.format_exception(exc_type, exc_value,
exc_traceback).__len__() - 2
exception_msg = "no exception found"
message = "no exception found"
if exc_type :
exception_msg = "{0} {1} {2}".format(str(exc_type.__name__), str(exc_value),
str(traceback.format_exception(exc_type, exc_value,
exc_traceback)[t_len]))
actual = str(traceback.format_exception(exc_type, exc_value,
exc_traceback)[t_len])
actual = actual.split(",", 1)
message = str(actual[0]).split('.')
self.exceptions['exceptions'].append(str(exception_msg))
if isinstance(test, nose.case.Test):
self.report_test("test failed", test, err, round(milliseconds, 2))
else:
self.report_test_exceptions(message, exception_msg, round(milliseconds, 2), 'test error')
def addFailure(self, test, err):
end_time = datetime.datetime.now()
report_test_time = end_time - self.feature_time
t = report_test_time
milliseconds = (t.days * 24 * 60 * 60 + t.seconds) * 1000 + t.microseconds / 1000.0
self.report_test("test failed", test, err, round(milliseconds, 2))
def addSuccess(self, test, error=None):
end_time = datetime.datetime.now()
report_test_time = end_time - self.feature_time
t = report_test_time
milliseconds = (t.days * 24 * 60 * 60 + t.seconds) * 1000 + t.microseconds / 1000.0
self.report_test("test passed", test, error, round(milliseconds, 2))
def finalize(self, result):
self.check_for_any_skipped_tests(result)
now = datetime.datetime.now()
self.results['report_date_time'] = now.strftime("%Y-%m-%d %H:%M")
self.results['report_name'] = self.report_file_name
self.results['total_number_of_market_features'] = self.__get_total_number_of_market_features()
self.results['total_number_of_tests'] = self.__get_total_number_of_tests()
self.results['number_of_passed_market_features'] = self.__get_number_of_passed_market_features()
self.results['number_of_passed_tests'] = self.__get_number_of_passed_tests()
self.results['total_no_of_fail_tests'] = self.__get_number_of_failed_tests()
self.results['total_no_of_skip_tests'] = self.__get_number_of_skipped_tests()
self.results['total_exceptions'] = self.__get_total_number_of_errors()
self.results['exceptions'] = self.exceptions['exceptions']
self.results['time_summary'] = round(self.__get_total_feature_elapsed_time() / 1000, 2)
all_status = check_valid_count(self._get_mixed_status())
for full_results in self.results["results"]:
for status in all_status:
if status:
if full_results['name'] is status[0]:
full_results['status'] = status[1]
report = self.__render_template("market_features.html", self.results)
with open("market_features.html", "w") as output_file:
output_file.write(report)
# copy javascript / css in order to conform to Content-Security-Policy
current_folder = os.path.dirname(os.path.realpath(__file__))
html_scripts = ["style.css", "jquery-3.3.1.min.js", "treeview.js"]
list(map(lambda scriptname : copyfile(current_folder + "/" + scriptname, scriptname), html_scripts))
def check_for_any_skipped_tests(self, result):
self.feature_time = datetime.datetime.now()
end_time = datetime.datetime.now()
report_test_time = end_time - self.feature_time
t = report_test_time
milliseconds = (t.days * 24 * 60 * 60 + t.seconds) * 1000 + t.microseconds / 1000.0
if result.skipped:
for rs in result.skipped:
self.report_test('test skipped', rs[0], err=None, test_time=round(milliseconds, 2), skip=str(rs[1]))
def report_test(self, pre, test, err=None, test_time=None, skip=None):
if not isinstance(test, nose.case.Test):
return
err_msg = "None"
if err:
exc_type, exc_value, exc_traceback = sys.exc_info()
if exc_type :
err_msg = "{0} {1} {2}".format(str(exc_type.__name__), str(exc_value),
str(traceback.format_tb(exc_traceback, 3)[1]))
else:
err_msg = err
if skip:
err_msg = skip
address = test.address()
message = test.shortDescription() if test.shortDescription() else str(address[-1]).split('.')[-1]
market_feature = self.__extract_market_feature(address)
for result in self.results['results']:
if result['name'] == market_feature:
test = {'result': pre, 'name': str(address[1:]), 'message': message, 'err_msg': err_msg,
'test_time': test_time}
result['tests'].append(test)
break
else:
result = {'name': market_feature,
'description': self.__extract_market_feature_description(test),
'status': None, 'tests': [], 'feature_time': None}
test = {'result': pre, 'name': str(address[1:]), 'message': message, 'err_msg': err_msg,
'test_time': test_time}
result['tests'].append(test)
self.results['results'].append(result)
@staticmethod
def __extract_market_feature_description(test):
try:
return sys.modules[sys.modules[test.context.__module__].__package__].__doc__
except KeyError:
return None
@staticmethod
def __extract_market_feature(address):
path = address[0]
snake_case_result = os.path.split(os.path.dirname(os.path.abspath(path)))[1]
split_result = snake_case_result.split('_')
return ' '.join([word.capitalize() for word in split_result])
def __get_total_number_of_market_features(self):
return len(self.results['results'])
def __get_total_number_of_tests(self):
total_number_of_tests = 0
for result in self.results['results']:
total_number_of_tests += len(result['tests'])
return total_number_of_tests
def __get_number_of_passed_market_features(self):
number_of_passed_market_features = 0
for result in self.results['results']:
for test in result['tests']:
if "failed" in test['result']:
result['status'] = 'failed'
break
else:
number_of_passed_market_features += 1
return number_of_passed_market_features
def __get_total_number_of_errors(self):
no_of_tests_with_errors = 0
for result in self.results['results']:
for test in result['tests']:
if "error" in test['result']:
result['status'] = 'error'
no_of_tests_with_errors += 1
return no_of_tests_with_errors
def _get_mixed_status(self):
append_status = []
res_status = []
for result in self.results['results']:
for test in result['tests']:
if "passed" not in test['result']:
res_status.append(test['result'])
res = {'name': result['name'], 'status': res_status}
res_status = []
append_status.append(res)
return append_status
def __get_total_feature_elapsed_time(self):
sum_of_features_update = 0
for result in self.results['results']:
timings = []
for test in result['tests']:
timings.append(test['test_time'])
result['feature_time'] = round(sum(timings) / 1000, 2)
sum_of_features_update += round(sum(timings), 2)
return sum_of_features_update
def __get_number_of_skipped_tests(self):
number_of_skipped_tests = 0
for result in self.results['results']:
for test in result['tests']:
if "skipped" in test['result']:
result['status'] = 'skipped'
number_of_skipped_tests += 1
return number_of_skipped_tests
def __get_number_of_passed_tests(self):
number_of_passed_tests = 0
for result in self.results['results']:
for test in result['tests']:
if "passed" in test['result']:
number_of_passed_tests += 1
return number_of_passed_tests
def __get_number_of_failed_tests(self):
number_of_failed_tests = 0
for result in self.results['results']:
for test in result['tests']:
if "failed" in test['result']:
number_of_failed_tests += 1
return number_of_failed_tests
def __render_template(self, name, data):
env = Environment(loader=FileSystemLoader(name))
env.filters['ignore_empty_elements'] = self.__ignore_empty_elements
templates_path = os.path.dirname(os.path.abspath(__file__))
env = Environment(loader=FileSystemLoader(templates_path))
template = env.get_template(name + ".jinja")
return template.render(data)
def __ignore_empty_elements(self, list):
return [_f for _f in list if _f]
def report_test_exceptions(self, address, err_msg, test_time, error_type=None):
market_feature = self.__extract_market_feature(address)
message = address[0].rsplit('/', 1)[-1]
for result in self.results['results']:
if result['name'] == market_feature:
test = {'result': error_type, 'name': address[0], 'message': message, 'err_msg': err_msg,
'test_time': test_time}
result['tests'].append(test)
break
else:
result = {'name': market_feature,
'status': None, 'tests': [], 'feature_time': None}
test = {'result': error_type, 'name': address[0], 'message': message, 'err_msg': err_msg,
'test_time': test_time}
result['tests'].append(test)
self.results['results'].append(result)
@staticmethod
def check_status(status):
if status.count('test failed') and status.count('test skipped') and status.count('test error') > 0:
return '3 mixed: failed, error and skipped'
if status.count('test failed') and status.count('test skipped') > 0:
return '2 mixed: failed and skipped'
if status.count('test failed') and status.count('test error') > 0:
return '2 mixed: failed and error'
if status.count('test error') and status.count('test skipped') > 0:
return '2 mixed: skipped and error'
def _check_status(status):
if status['status'].count('test failed') and status['status'].count('test skipped') and status['status'].count(
'test error') > 0:
return status['name'], 'failed, error and skipped'
if status['status'].count('test failed') and status['status'].count('test skipped') > 0:
return status['name'], 'failed and skipped'
if status['status'].count('test failed') and status['status'].count('test error') > 0:
return status['name'], 'failed and error'
if status['status'].count('test error') and status['status'].count('test skipped') > 0:
return status['name'], 'skipped and error'
def validate_mix_status_count(x):
return _check_status(x)
def check_valid_count(mixed_status):
return [validate_mix_status_count(x) for x in mixed_status]
| StarcoderdataPython |
307844 | #!/usr/bin/env python
import rospy
import math
import tf
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Pose
from tr5_kinematics.srv import DoInverseKinematics, DoInverseKinematicsResponse
# load private parameters
svc_ik = rospy.get_param("~inv_kin_service", "/do_ik")
# DH Parameters for ROB3/TR5
d1 = 0.275
a2 = 0.200
a3 = 0.130
d5 = 0.130
# receives a pose and returns the matrix entries
def poseToMatrix(pose):
position = []
orientation = []
# translation expressed as a tuple (x,y,z)
position.append(pose.position.x)
position.append(pose.position.y)
position.append(pose.position.z)
# rotation quaternion expressed as a tuple (x,y,z,w)
orientation.append(pose.orientation.x)
orientation.append(pose.orientation.y)
orientation.append(pose.orientation.z)
orientation.append(pose.orientation.w)
# converts a tf into a 4x4 matrix
# |nx sx ax px|
# |ny sy ay py|
# |nz sz az pz|
# | 0 0 0 1|
m = tf.TransformerROS().fromTranslationRotation(position, orientation)
nx = m[0][0]
ny = m[1][0]
nz = m[2][0]
sx = m[0][1]
sy = m[1][1]
sz = m[2][1]
ax = m[0][2]
ay = m[1][2]
az = m[2][2]
px = m[0][3]
py = m[1][3]
pz = m[2][3]
return (nx,ny,nz,sx,sy,sz,ax,ay,az,px,py,pz)
def arctg2(y,x):
return 0 if y==0 and x==0 else math.atan2(y,x)
def sqrt(x):
return 0 if x < 0 else math.sqrt(x)
# callback to handle the inverse kinematics calculations
def doInverseKinematics(srv):
response = JointState()
# converts req_pose into a matrix and get its entries
(nx,ny,nz,sx,sy,sz,ax,ay,az,px,py,pz) = poseToMatrix(srv.req_pose)
theta1 = arctg2(py,px)
theta234 = arctg2(az, ax*math.cos(theta1) + ay*math.sin(theta1))
c_theta3 = (((px*math.cos(theta1) + py*math.sin(theta1) - d5*math.cos(theta234))**2) + ((pz-d1-d5*math.sin(theta234))**2) - a2**2 - a3**2) / (2*a2*a3)
s_theta3 = sqrt(1-c_theta3**2)
theta3 = math.atan(sqrt(1/(c_theta3**2)-1))
theta2 = arctg2(((a2 + a3*math.cos(theta3))*(-d1+pz-d5*math.sin(theta234))),
((a2+a3*math.cos(theta3))*(-d5*math.cos(theta234) + math.cos(theta1)*px + math.sin(theta1)*py) + a3*math.sin(theta3)*(-d1+pz-d5*math.sin(theta234))))
theta4 = theta2 - theta3
theta5 = math.atan((-ny*math.cos(theta1) + nx*math.sin(theta1)) / (-sy*math.cos(theta1) + sx*math.sin(theta1)))
response.header.stamp = rospy.Time.now()
response.name = ['tr5shoulder_pan_joint', 'tr5shoulder_lift_joint', 'tr5elbow_joint', 'tr5wrist_1_joint', 'tr5wrist_2_joint', 'tr5left_finger_joint', 'tr5right_finger_joint']
response.position = [theta1, theta2, theta3, theta4, theta5, 0.0, 0.0]
response.effort = []
response.velocity = []
return DoInverseKinematicsResponse(response)
if __name__ == "__main__":
rospy.init_node('tr5_inverse_kinematics')
# create and advertise the service for inverse kinematics
do_ik = rospy.Service(svc_ik, DoInverseKinematics, doInverseKinematics)
while not rospy.is_shutdown():
rospy.spin()
| StarcoderdataPython |
8091817 | <gh_stars>1-10
from action import Action
from update_dict import UpdateDict
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.