code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Reference: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.number = "" <NEW_LINE> self.authors = "" <NEW_LINE> self.citation = ""
Holds information from a Prodoc citation. Attributes: - number Number of the reference. (string) - authors Names of the authors. - citation Describes the citation.
62599045d99f1b3c44d069e4
class RelayCommand(BaseCommand): <NEW_LINE> <INDENT> daemonizable = True <NEW_LINE> name = 'fedmsg-relay' <NEW_LINE> relay_consumer = RelayConsumer <NEW_LINE> def run(self): <NEW_LINE> <INDENT> moksha_options = dict( zmq_subscribe_endpoints=",".join(list(iterate( self.config['relay_inbound'] ))), zmq_subscribe_method="bind", ) <NEW_LINE> self.config.update(moksha_options) <NEW_LINE> self.config[self.relay_consumer.config_key] = True <NEW_LINE> from moksha.hub import main <NEW_LINE> for publish_endpoint in self.config['endpoints']['relay_outbound']: <NEW_LINE> <INDENT> self.config['zmq_publish_endpoints'] = publish_endpoint <NEW_LINE> try: <NEW_LINE> <INDENT> return main( options=self.config, consumers=[self.relay_consumer], producers=[], framework=False, ) <NEW_LINE> <DEDENT> except zmq.ZMQError: <NEW_LINE> <INDENT> self.log.debug("Failed to bind to %r" % publish_endpoint) <NEW_LINE> <DEDENT> <DEDENT> raise IOError("Failed to bind to any outbound endpoints.")
Relay connections from active loggers to the bus. ``fedmsg-relay`` is a service which binds to two ports, listens for messages on one and emits them on the other. ``fedmsg-logger`` requires that an instance of ``fedmsg-relay`` be running *somewhere* and that it's inbound address be listed in the config as one of the entries in :term:`relay_inbound`. ``fedmsg-relay`` becomes a necessity for integration points that cannot bind consistently to and serve from a port. See :doc:`topology` for the mile-high view. More specifically, ``fedmsg-relay`` is a SUB.bind()->PUB.bind() relay.
62599045d6c5a102081e3460
class S3BucketUploadJob(MashJob): <NEW_LINE> <INDENT> def post_init(self): <NEW_LINE> <INDENT> self.cloud = 'ec2' <NEW_LINE> self._image_size = 0 <NEW_LINE> self._total_bytes_transferred = 0 <NEW_LINE> self._last_percentage_logged = 0 <NEW_LINE> self._percentage_log_step = 20 <NEW_LINE> try: <NEW_LINE> <INDENT> self.account = self.job_config['raw_image_upload_account'] <NEW_LINE> self.location = self.job_config['raw_image_upload_location'] <NEW_LINE> <DEDENT> except KeyError as error: <NEW_LINE> <INDENT> raise MashUploadException( 'S3 bucket upload jobs require a(n) {0} ' 'key in the job doc.'.format( error ) ) <NEW_LINE> <DEDENT> <DEDENT> def _log_progress(self, bytes_transferred): <NEW_LINE> <INDENT> self._total_bytes_transferred += bytes_transferred <NEW_LINE> percent_transferred = (self._total_bytes_transferred * 100) / self._image_size <NEW_LINE> if percent_transferred >= (self._last_percentage_logged + self._percentage_log_step): <NEW_LINE> <INDENT> self._last_percentage_logged = int( percent_transferred - (percent_transferred % self._percentage_log_step) ) <NEW_LINE> self.log_callback.info('Raw image {progress}% uploaded.'.format( progress=str(self._last_percentage_logged) )) <NEW_LINE> <DEDENT> <DEDENT> def run_job(self): <NEW_LINE> <INDENT> self.status = SUCCESS <NEW_LINE> self.log_callback.info('Uploading raw image.') <NEW_LINE> self.request_credentials([self.account]) <NEW_LINE> credentials = self.credentials[self.account] <NEW_LINE> location_args = str.split(self.location, '/', 1) <NEW_LINE> bucket_name = location_args[0] <NEW_LINE> try: <NEW_LINE> <INDENT> bucket_path = location_args[1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> bucket_path = '' <NEW_LINE> <DEDENT> if self.status_msg['cloud_image_name']: <NEW_LINE> <INDENT> suffix = '.'.join(str.split(self.status_msg['image_file'], '.')[-2:]) <NEW_LINE> key_name = '.'.join([self.status_msg['cloud_image_name'], suffix]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key_name = path.basename(self.status_msg['image_file']) <NEW_LINE> <DEDENT> if not bucket_path: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif bucket_path[-1] == '/': <NEW_LINE> <INDENT> key_name = ''.join([bucket_path, key_name]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key_name = bucket_path <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> statinfo = stat(self.status_msg['image_file']) <NEW_LINE> self._image_size = statinfo.st_size <NEW_LINE> client = get_client( 's3', credentials['access_key_id'], credentials['secret_access_key'], None ) <NEW_LINE> client.upload_file( self.status_msg['image_file'], bucket_name, key_name, Callback=self._log_progress ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise MashUploadException( 'Raw upload to S3 bucket failed with: {0}'.format(e) )
Implements raw image upload to Amazon S3 bucket
62599045507cdc57c63a60e2
class TestWriteCCFull(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> cdl_convert.ColorCorrection.members = {} <NEW_LINE> self.cdl = cdl_convert.ColorCorrection("014_xf_seqGrade_v01", '') <NEW_LINE> self.cdl.desc = [ 'CC description 1', 'CC description 2', 'CC description 3', 'CC description 4', 'CC description 5' ] <NEW_LINE> self.cdl.input_desc = 'Input Desc Text' <NEW_LINE> self.cdl.viewing_desc = 'Viewing Desc Text' <NEW_LINE> self.cdl.slope = (1.014, 1.0104, 0.62) <NEW_LINE> self.cdl.offset = (-0.00315, -0.00124, 0.3103) <NEW_LINE> self.cdl.power = (1.0, 0.9983, 1.0) <NEW_LINE> self.cdl.sop_node.desc = [ 'Sop description 1', 'Sop description 2', 'Sop description 3' ] <NEW_LINE> self.cdl.sat = 1.09 <NEW_LINE> self.cdl.sat_node.desc = [ 'Sat description 1', 'Sat description 2' ] <NEW_LINE> self.target_xml_root = enc(CC_FULL_WRITE) <NEW_LINE> self.target_xml = enc('\n'.join(CC_FULL_WRITE.split('\n')[1:])) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> cdl_convert.ColorCorrection.members = {} <NEW_LINE> <DEDENT> def test_root_xml(self): <NEW_LINE> <INDENT> self.assertEqual( self.target_xml_root, self.cdl.xml_root ) <NEW_LINE> <DEDENT> def test_base_xml(self): <NEW_LINE> <INDENT> self.assertEqual( self.target_xml, self.cdl.xml ) <NEW_LINE> <DEDENT> def test_element(self): <NEW_LINE> <INDENT> self.assertEqual( 'ColorCorrection', self.cdl.element.tag ) <NEW_LINE> <DEDENT> def test_write(self): <NEW_LINE> <INDENT> mockOpen = mock.mock_open() <NEW_LINE> self.cdl._files['file_out'] = 'bobs_big_file.cc' <NEW_LINE> with mock.patch(builtins + '.open', mockOpen, create=True): <NEW_LINE> <INDENT> cdl_convert.write_cc(self.cdl) <NEW_LINE> <DEDENT> mockOpen.assert_called_once_with('bobs_big_file.cc', 'wb') <NEW_LINE> mockOpen().write.assert_called_once_with(self.target_xml_root)
Tests full writing of CC XML
6259904515baa723494632d7
class Literal: <NEW_LINE> <INDENT> def __init__(self, lstr): <NEW_LINE> <INDENT> self.lstr = lstr <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.lstr <NEW_LINE> <DEDENT> def escape(self, escape_func): <NEW_LINE> <INDENT> return escape_func(self.lstr) <NEW_LINE> <DEDENT> def for_signature(self): <NEW_LINE> <INDENT> return self.lstr <NEW_LINE> <DEDENT> def is_literal(self): <NEW_LINE> <INDENT> return 1
A wrapper for a string. If you use this object wrapped around a string, then it will be interpreted as literal. When passed to the command interpreter, all special characters will be escaped.
62599046097d151d1a2c23b1
class ComplexArrayVarArray(VarArray): <NEW_LINE> <INDENT> def __init__(self, field, base, arraysize, config={}, pos=None): <NEW_LINE> <INDENT> VarArray.__init__(self, field, base, arraysize, config, pos) <NEW_LINE> <DEDENT> def parse(self, value, config={}, pos=None): <NEW_LINE> <INDENT> if value.strip() == '': <NEW_LINE> <INDENT> return ma.array([]), True <NEW_LINE> <DEDENT> parts = self._splitter(value, config, pos) <NEW_LINE> items = self._base._items <NEW_LINE> parse_parts = self._base.parse_parts <NEW_LINE> if len(parts) % items != 0: <NEW_LINE> <INDENT> vo_raise(E02, (items, len(parts)), config, pos) <NEW_LINE> <DEDENT> result = [] <NEW_LINE> result_mask = [] <NEW_LINE> for i in xrange(0, len(parts), items): <NEW_LINE> <INDENT> value, mask = parse_parts(parts[i:i + items], config, pos) <NEW_LINE> result.append(value) <NEW_LINE> result_mask.append(mask) <NEW_LINE> <DEDENT> return _make_masked_array(result, result_mask), False
Handles an array of variable-length arrays of complex numbers.
6259904682261d6c52730868
class Multiselect(Region): <NEW_LINE> <INDENT> _book_list_arrow_icon_locator = ( By.CSS_SELECTOR, 'i.fa') <NEW_LINE> _book_list_toggle_locator = ( By.CSS_SELECTOR, '[type=button]') <NEW_LINE> _book_title_bar_locator = ( By.CSS_SELECTOR, '.result') <NEW_LINE> @property <NEW_LINE> def books(self) -> List[CompleteYourProfile.Multiselect.Book]: <NEW_LINE> <INDENT> return [self.Book(self, book) for book in self.find_elements(*self._book_title_bar_locator)] <NEW_LINE> <DEDENT> @property <NEW_LINE> def list_is_open(self) -> bool: <NEW_LINE> <INDENT> icon = self.find_element(*self._book_list_arrow_icon_locator) <NEW_LINE> return 'caret-up' in icon.get_attribute('class') <NEW_LINE> <DEDENT> def toggle(self): <NEW_LINE> <INDENT> arrow = self.find_element(*self._book_list_toggle_locator) <NEW_LINE> Utility.click_option(self.driver, element=arrow) <NEW_LINE> sleep(0.25) <NEW_LINE> <DEDENT> class Book(Region): <NEW_LINE> <INDENT> @property <NEW_LINE> def title(self) -> str: <NEW_LINE> <INDENT> return self.root.text <NEW_LINE> <DEDENT> def select(self): <NEW_LINE> <INDENT> Utility.click_option(self.driver, element=self.root)
A book multi-selection widget.
6259904630dc7b76659a0b78
class ABCTopoSwitched( Topo ): <NEW_LINE> <INDENT> def __init__( self ): <NEW_LINE> <INDENT> Topo.__init__( self ) <NEW_LINE> leftHost = self.addHost( 'h1' ) <NEW_LINE> middleHost = self.addHost( 'h2' ) <NEW_LINE> rightHost = self.addHost( 'h3' ) <NEW_LINE> leftSwitch = self.addSwitch( 's1' ) <NEW_LINE> rightSwitch = self.addSwitch( 's2' ) <NEW_LINE> self.addLink( leftHost, leftSwitch ) <NEW_LINE> self.addLink( leftSwitch, middleHost ) <NEW_LINE> self.addLink( middleHost, rightSwitch ) <NEW_LINE> self.addLink( rightSwitch, rightHost )
Simple topology example.
625990463c8af77a43b688e0
class OrderDefault(BaseMixinsModel): <NEW_LINE> <INDENT> __tablename__ = "p_order_default" <NEW_LINE> create_date = Column(DateTime(), default=datetime.now, comment=u"添加时间") <NEW_LINE> num = Column(Integer(), default=0, comment=u"数量") <NEW_LINE> status = Column(Boolean(), default=True, comment=u"True进货,False出货") <NEW_LINE> desc = Column(String(200), comment=u"描述") <NEW_LINE> g_id = Column(Integer(), ForeignKey('p_goods_default.id')) <NEW_LINE> goods = relationship("GoodsDefault", order_by='GoodsDefault.id', backref="OrderDefault") <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return self.desc
物料订单
6259904615baa723494632d8
class PCE: <NEW_LINE> <INDENT> version = None <NEW_LINE> def _get_device(self): <NEW_LINE> <INDENT> device = usb.core.find(idVendor=ID_VENDOR, idProduct=ID_PRODUCT) <NEW_LINE> if device is None: <NEW_LINE> <INDENT> raise DeviceNotFound('FS20 PCE not found.') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> device.get_active_configuration() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> device.set_configuration() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> device.detach_kernel_driver(0) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return device <NEW_LINE> <DEDENT> def get_response(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self._get_device().read(ENDPOINT_READ, 13, timeout=100) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> response = '' <NEW_LINE> <DEDENT> if response[0:2] == array('B', [0x02, 0x0b]): <NEW_LINE> <INDENT> PCE.version = response[12] <NEW_LINE> return Response(response[2:]) <NEW_LINE> <DEDENT> raise DeviceInvalidResponse('Invalid response from device.') <NEW_LINE> <DEDENT> def get_version(self): <NEW_LINE> <INDENT> if PCE.version is None: <NEW_LINE> <INDENT> raise DeviceMissingResponse('Version only available after receiving commands.') <NEW_LINE> <DEDENT> version = str(PCE.version) <NEW_LINE> return 'v%s.%s' % (version[0], version[1]) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.get_response() <NEW_LINE> <DEDENT> except DeviceInvalidResponse: <NEW_LINE> <INDENT> break
Handles I/O of FS20 PCE. Attributes: version: Holds the firmware version of FS20 PCE.
62599046462c4b4f79dbcd45
class CapImage(CapFile): <NEW_LINE> <INDENT> def search_image(self, pattern, sortby=CapFile.SEARCH_RELEVANCE, nsfw=False): <NEW_LINE> <INDENT> return self.search_file(pattern, sortby) <NEW_LINE> <DEDENT> def get_image(self, _id): <NEW_LINE> <INDENT> return self.get_file(_id)
Image file provider
6259904623e79379d538d844
class CustomDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, csv_file, root_dir, transform=None): <NEW_LINE> <INDENT> self.data_frame = pd.read_csv(csv_file) <NEW_LINE> self.root_dir = root_dir <NEW_LINE> self.transform = transform <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.data_frame) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> img_name = os.path.join(self.root_dir, self.data_frame.iloc[idx, 0]) <NEW_LINE> image = io.imread(img_name) <NEW_LINE> label = self.data_frame.iloc[idx, 1:].as_matrix() <NEW_LINE> sample = {'image': image, 'label': label} <NEW_LINE> if self.transform: <NEW_LINE> <INDENT> sample = self.transform(sample) <NEW_LINE> <DEDENT> return sample
Face Landmarks dataset.
6259904607d97122c4217fe7
class Browser: <NEW_LINE> <INDENT> def __init__(self, url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.init() <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> self.session = requests.Session() <NEW_LINE> self.session.proxies = { 'http': PROXY, 'https': PROXY } <NEW_LINE> self.session.verify = False <NEW_LINE> <DEDENT> def get(self, url ,*args, **kwargs): <NEW_LINE> <INDENT> return self.session.get(url=self.url + url, *args, **kwargs) <NEW_LINE> <DEDENT> def post(self, url, *args, **kwargs): <NEW_LINE> <INDENT> return self.session.post(url=self.url + url, *args, **kwargs) <NEW_LINE> <DEDENT> def matches(self, r, regex): <NEW_LINE> <INDENT> return re.findall(regex, r.text)
Wrapper around requests.
62599046be383301e0254b5f
class TranslationCapturer(TokenTranslator): <NEW_LINE> <INDENT> def handle_conversion(self, s, translation): <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> def get_order_preserving_anonymizer(self): <NEW_LINE> <INDENT> generated_translations = dict(self._translations) <NEW_LINE> for k in self._word_map.keys(): <NEW_LINE> <INDENT> del generated_translations[k] <NEW_LINE> <DEDENT> for k in self._keep: <NEW_LINE> <INDENT> del generated_translations[k] <NEW_LINE> <DEDENT> sorted_keys = sorted(generated_translations.keys()) <NEW_LINE> sorted_values = sorted(generated_translations.values()) <NEW_LINE> ordered_translations = dict(zip(sorted_keys, sorted_values)) <NEW_LINE> for k, v in self._word_map.items(): <NEW_LINE> <INDENT> ordered_translations[k] = v <NEW_LINE> <DEDENT> return Anonymizer([], ordered_translations, self._keep, self._strict)
Captures strings that need anonymizing, but doesn't actually anonymize them. Useful when we need the anonymized strings to be in the same dictionary order as the strings they replace: We capture all strings that need anonymizing in one pass, and then anonymize in a second pass.
62599046d53ae8145f9197a6
class SpiralTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> output_filename = os.path.join("Graphics","spiral_test.pdf") <NEW_LINE> self.c = Canvas(output_filename, pagesize=A4) <NEW_LINE> self.x_0, self.y_0 = 0.5 * A4[0], 0.5 * A4[1] <NEW_LINE> <DEDENT> def test_colorlist(self): <NEW_LINE> <INDENT> cs = ColorSpiral(a = 4, b = 0.33, jitter = 0) <NEW_LINE> colours = list(cs.get_colors(8)) <NEW_LINE> cstr = ["(%.2f, %.2f, %.2f)" % (r, g, b) for r, g, b in colours] <NEW_LINE> expected = ['(0.64, 0.74, 0.81)', '(0.68, 0.52, 0.76)', '(0.72, 0.41, 0.55)', '(0.68, 0.39, 0.31)', '(0.63, 0.54, 0.22)', '(0.48, 0.59, 0.13)', '(0.24, 0.54, 0.06)', '(0.01, 0.50, -0.00)'] <NEW_LINE> self.assertEqual(cstr, expected) <NEW_LINE> <DEDENT> def test_colorspiral(self): <NEW_LINE> <INDENT> cs = ColorSpiral(a = 4, b = 0.33, jitter = 0) <NEW_LINE> radius = A4[0] * 0.025 <NEW_LINE> for r, g, b in cs.get_colors(16): <NEW_LINE> <INDENT> self.c.setFillColor((r, g, b)) <NEW_LINE> h, s, v = colorsys.rgb_to_hsv(r, g, b) <NEW_LINE> coords = cmath.rect(s * A4[0] * 0.45, h * 2 * pi) <NEW_LINE> x, y = self.x_0 + coords.real, self.y_0 + coords.imag <NEW_LINE> self.c.ellipse(x - radius, y - radius, x + radius, y + radius, stroke = 0, fill = 1) <NEW_LINE> <DEDENT> self.finish() <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> self.c.save()
Construct and draw ColorSpiral colours placed on HSV spiral.
6259904663b5f9789fe864b3
class MultiElement(CompoundElement, ButtonElementMixin): <NEW_LINE> <INDENT> class ProxiedInterface(CompoundElement.ProxiedInterface): <NEW_LINE> <INDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> found = find_if(lambda x: x is not None, imap(lambda c: getattr(c.proxied_interface, name, None), self.outer.nested_control_elements())) <NEW_LINE> if found is not None: <NEW_LINE> <INDENT> return found <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __init__(self, *controls, **k): <NEW_LINE> <INDENT> super(MultiElement, self).__init__(**k) <NEW_LINE> self.register_control_elements(*map(get_element, controls)) <NEW_LINE> <DEDENT> def send_value(self, value): <NEW_LINE> <INDENT> for control in self.owned_control_elements(): <NEW_LINE> <INDENT> control.send_value(value) <NEW_LINE> <DEDENT> <DEDENT> def set_light(self, value): <NEW_LINE> <INDENT> for control in self.owned_control_elements(): <NEW_LINE> <INDENT> control.set_light(value) <NEW_LINE> <DEDENT> <DEDENT> def on_nested_control_element_value(self, value, control): <NEW_LINE> <INDENT> if not self.is_pressed() or value: <NEW_LINE> <INDENT> self.notify_value(value) <NEW_LINE> <DEDENT> <DEDENT> def is_pressed(self): <NEW_LINE> <INDENT> return find_if(lambda c: getattr(c, 'is_pressed', const(False))(), self.owned_control_elements()) != None <NEW_LINE> <DEDENT> def is_momentary(self): <NEW_LINE> <INDENT> return find_if(lambda c: getattr(c, 'is_momentary', const(False))(), self.nested_control_elements()) != None <NEW_LINE> <DEDENT> def on_nested_control_element_received(self, control): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_nested_control_element_lost(self, control): <NEW_LINE> <INDENT> pass
Makes several elements behave as single one. Useful when it is desired to map several buttons to single one.
62599046287bf620b6272f2f
class NotFoundError(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(NotFoundError, self).__init__(message) <NEW_LINE> self.message = message
Raised when a resource is not found.
62599046e64d504609df9d74
class TeacherListView(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> all_teachers = Teacher.objects.all() <NEW_LINE> sorted_teacher = all_teachers.order_by('-click_nums')[:3] <NEW_LINE> search_keywords = request.GET.get('keywords', '') <NEW_LINE> if search_keywords: <NEW_LINE> <INDENT> all_teachers = all_teachers.filter(Q(name__icontains=search_keywords) | Q(work_company__icontains=search_keywords) | Q(work_position__icontains=search_keywords)) <NEW_LINE> <DEDENT> sort = request.GET.get('sort', '') <NEW_LINE> if sort: <NEW_LINE> <INDENT> if sort == 'hot': <NEW_LINE> <INDENT> all_teachers = all_teachers.order_by('-click_nums') <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> page = request.GET.get('page', 1) <NEW_LINE> <DEDENT> except PageNotAnInteger: <NEW_LINE> <INDENT> page = 1 <NEW_LINE> <DEDENT> p = Paginator(all_teachers, 3, request=request) <NEW_LINE> teachers = p.page(page) <NEW_LINE> return render(request, 'teachers-list.html', { 'all_teachers': teachers, 'sort': sort, 'sorted_teacher': sorted_teacher, })
课程讲师列表页
62599046c432627299fa42a6
class AddressView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> address = Address.objects.get_default_address(user=request.user) <NEW_LINE> return render(request, 'user_center_site.html', {'address': address}) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> receiver = request.POST.get('receiver') <NEW_LINE> addr = request.POST.get('addr') <NEW_LINE> code = request.POST.get('code') <NEW_LINE> phone = request.POST.get('phone') <NEW_LINE> if not all([receiver, addr, phone]): <NEW_LINE> <INDENT> return render(request, 'user_center_site.html', {'errmsg': '数据不完整'}) <NEW_LINE> <DEDENT> if not re.match(r'^1[3|4|5|7|8][0-9]{9}$', phone): <NEW_LINE> <INDENT> return render(request, 'user_center_site.html', {'errmsg': '手机号格式错误'}) <NEW_LINE> <DEDENT> if Address.objects.get_default_address(user=request.user): <NEW_LINE> <INDENT> is_default = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> is_default = True <NEW_LINE> <DEDENT> address = Address.objects.create( user=request.user, receiver=receiver, addr=addr, zip_code=code, phone=phone, is_default=is_default) <NEW_LINE> return redirect(reverse('user:address'))
用户中心-地址页
6259904615baa723494632d9
class Animal: <NEW_LINE> <INDENT> def __init__(self, age): <NEW_LINE> <INDENT> self.age = age <NEW_LINE> self.name = None <NEW_LINE> <DEDENT> def get_age(self): <NEW_LINE> <INDENT> return self.age <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def set_age(self, new_age): <NEW_LINE> <INDENT> self.age = new_age <NEW_LINE> <DEDENT> def set_name(self, new_name=""): <NEW_LINE> <INDENT> self.name = new_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "animal:" + str(self.name) + " : " + str(self.age)
Basic class.
62599046498bea3a75a58e66
class TestVerifySublayouts(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(self): <NEW_LINE> <INDENT> self.working_dir = os.getcwd() <NEW_LINE> demo_files = os.path.join( os.path.dirname(os.path.realpath(__file__)), "demo_files") <NEW_LINE> self.test_dir = os.path.realpath(tempfile.mkdtemp()) <NEW_LINE> os.chdir(self.test_dir) <NEW_LINE> for file in os.listdir(demo_files): <NEW_LINE> <INDENT> shutil.copy(os.path.join(demo_files, file), self.test_dir) <NEW_LINE> <DEDENT> alice = import_rsa_key_from_file("alice") <NEW_LINE> alice_pub = import_rsa_key_from_file("alice.pub") <NEW_LINE> layout_template = Layout.read_from_file("demo.layout.template") <NEW_LINE> sub_layout = copy.deepcopy(layout_template) <NEW_LINE> sub_layout_name = "sub_layout" <NEW_LINE> sub_layout_path = FILENAME_FORMAT.format(step_name=sub_layout_name, keyid=alice_pub["keyid"]) <NEW_LINE> sub_layout.sign(alice) <NEW_LINE> sub_layout.dump(sub_layout_path) <NEW_LINE> self.super_layout = Layout() <NEW_LINE> self.super_layout.keys[alice_pub["keyid"]] = alice_pub <NEW_LINE> sub_layout_step = Step( name=sub_layout_name, pubkeys=[alice_pub["keyid"]] ) <NEW_LINE> self.super_layout.steps.append(sub_layout_step) <NEW_LINE> self.super_layout_links = self.super_layout.import_step_metadata_from_files_as_dict() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(self): <NEW_LINE> <INDENT> os.chdir(self.working_dir) <NEW_LINE> shutil.rmtree(self.test_dir) <NEW_LINE> <DEDENT> def test_verify_demo_as_sublayout(self): <NEW_LINE> <INDENT> verify_sublayouts( self.super_layout, self.super_layout_links)
Tests verifylib.verify_sublayouts(layout, reduced_chain_link_dict). Call with one-step super layout that has a sublayout (demo layout).
6259904607f4c71912bb077a
class build_clib(orig.build_clib): <NEW_LINE> <INDENT> def build_libraries(self, libraries): <NEW_LINE> <INDENT> for (lib_name, build_info) in libraries: <NEW_LINE> <INDENT> sources = build_info.get('sources') <NEW_LINE> if sources is None or not isinstance(sources, (list, tuple)): <NEW_LINE> <INDENT> raise DistutilsSetupError( "in 'libraries' option (library '%s'), " "'sources' must be present and must be " "a list of source filenames" % lib_name) <NEW_LINE> <DEDENT> sources = list(sources) <NEW_LINE> log.info("building '%s' library", lib_name) <NEW_LINE> obj_deps = build_info.get('obj_deps', dict()) <NEW_LINE> if not isinstance(obj_deps, dict): <NEW_LINE> <INDENT> raise DistutilsSetupError( "in 'libraries' option (library '%s'), " "'obj_deps' must be a dictionary of " "type 'source: list'" % lib_name) <NEW_LINE> <DEDENT> dependencies = [] <NEW_LINE> global_deps = obj_deps.get('', list()) <NEW_LINE> if not isinstance(global_deps, (list, tuple)): <NEW_LINE> <INDENT> raise DistutilsSetupError( "in 'libraries' option (library '%s'), " "'obj_deps' must be a dictionary of " "type 'source: list'" % lib_name) <NEW_LINE> <DEDENT> for source in sources: <NEW_LINE> <INDENT> src_deps = [source] <NEW_LINE> src_deps.extend(global_deps) <NEW_LINE> extra_deps = obj_deps.get(source, list()) <NEW_LINE> if not isinstance(extra_deps, (list, tuple)): <NEW_LINE> <INDENT> raise DistutilsSetupError( "in 'libraries' option (library '%s'), " "'obj_deps' must be a dictionary of " "type 'source: list'" % lib_name) <NEW_LINE> <DEDENT> src_deps.extend(extra_deps) <NEW_LINE> dependencies.append(src_deps) <NEW_LINE> <DEDENT> expected_objects = self.compiler.object_filenames( sources, output_dir=self.build_temp, ) <NEW_LINE> if ( newer_pairwise_group(dependencies, expected_objects) != ([], []) ): <NEW_LINE> <INDENT> macros = build_info.get('macros') <NEW_LINE> include_dirs = build_info.get('include_dirs') <NEW_LINE> cflags = build_info.get('cflags') <NEW_LINE> self.compiler.compile( sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, extra_postargs=cflags, debug=self.debug ) <NEW_LINE> <DEDENT> self.compiler.create_static_lib( expected_objects, lib_name, output_dir=self.build_clib, debug=self.debug )
Override the default build_clib behaviour to do the following: 1. Implement a rudimentary timestamp-based dependency system so 'compile()' doesn't run every time. 2. Add more keys to the 'build_info' dictionary: * obj_deps - specify dependencies for each object compiled. this should be a dictionary mapping a key with the source filename to a list of dependencies. Use an empty string for global dependencies. * cflags - specify a list of additional flags to pass to the compiler.
62599046d10714528d69f031
class GoodsDetailView(DetailView): <NEW_LINE> <INDENT> model = Goods <NEW_LINE> template_name = 'goods/goods.html'
Show goods details
6259904623849d37ff852404
class SqueezeTransform(Transform): <NEW_LINE> <INDENT> codomain = constraints.real <NEW_LINE> bijective = True <NEW_LINE> event_dim = 3 <NEW_LINE> volume_preserving = True <NEW_LINE> def __init__(self, factor=2): <NEW_LINE> <INDENT> super().__init__(cache_size=1) <NEW_LINE> self.factor = factor <NEW_LINE> <DEDENT> def _call(self, inputs): <NEW_LINE> <INDENT> if inputs.dim() < 3: <NEW_LINE> <INDENT> raise ValueError(f'Expecting inputs with at least 3 dimensions, got {inputs.shape} - {inputs.dim()}') <NEW_LINE> <DEDENT> *batch_dims, c, h, w = inputs.size() <NEW_LINE> num_batch = len(batch_dims) <NEW_LINE> if h % self.factor != 0 or w % self.factor != 0: <NEW_LINE> <INDENT> raise ValueError('Input image size not compatible with the factor.') <NEW_LINE> <DEDENT> inputs = inputs.view(*batch_dims, c, h // self.factor, self.factor, w // self.factor, self.factor) <NEW_LINE> permute = np.array((0, 2, 4, 1, 3)) + num_batch <NEW_LINE> inputs = inputs.permute(*np.arange(num_batch), *permute).contiguous() <NEW_LINE> inputs = inputs.view(*batch_dims, c * self.factor * self.factor, h // self.factor, w // self.factor) <NEW_LINE> return inputs <NEW_LINE> <DEDENT> def _inverse(self, inputs): <NEW_LINE> <INDENT> if inputs.dim() < 3: <NEW_LINE> <INDENT> raise ValueError(f'Expecting inputs with at least 3 dimensions, got {inputs.shape}') <NEW_LINE> <DEDENT> *batch_dims, c, h, w = inputs.size() <NEW_LINE> num_batch = len(batch_dims) <NEW_LINE> if c < 4 or c % 4 != 0: <NEW_LINE> <INDENT> raise ValueError('Invalid number of channel dimensions.') <NEW_LINE> <DEDENT> inputs = inputs.view(*batch_dims, c // self.factor ** 2, self.factor, self.factor, h, w) <NEW_LINE> permute = np.array((0, 3, 1, 4, 2)) + num_batch <NEW_LINE> inputs = inputs.permute(*np.arange(num_batch), *permute).contiguous() <NEW_LINE> inputs = inputs.view(*batch_dims, c // self.factor ** 2, h * self.factor, w * self.factor) <NEW_LINE> return inputs <NEW_LINE> <DEDENT> def log_abs_det_jacobian(self, x, y): <NEW_LINE> <INDENT> log_abs_det_jacobian = torch.zeros(x.size()[:-3], dtype=x.dtype, layout=x.layout, device=x.device) <NEW_LINE> return log_abs_det_jacobian <NEW_LINE> <DEDENT> def get_output_shape(self, c, h, w): <NEW_LINE> <INDENT> return (c * self.factor * self.factor, h // self.factor, w // self.factor)
A transformation defined for image data that trades spatial dimensions for channel dimensions, i.e. "squeezes" the inputs along the channel dimensions. Implementation adapted from https://github.com/pclucas14/pytorch-glow and https://github.com/chaiyujin/glow-pytorch. Reference: > L. Dinh et al., Density estimation using Real NVP, ICLR 2017.
62599046379a373c97d9a373
class Command(BaseCommand): <NEW_LINE> <INDENT> def add_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument("args", nargs=2) <NEW_LINE> parser.add_argument( "--no-refresh", action="store_false", dest="refresh", default=True, help="Do not refresh Solr after the import", ) <NEW_LINE> <DEDENT> help = ( "Usage: ./manage.py import_folio_mapping <manuscript_id> <mapping_csv_file> [<manuscript2_id> <mapping_csv_file2> ...]" '\n\tNote that csv files must be in the folder "data_dumps/folio_mapping/"' ) <NEW_LINE> def handle(self, *args, **options): <NEW_LINE> <INDENT> if len(args) == 0 or len(args) % 2 == 1: <NEW_LINE> <INDENT> self.stdout.write(self.help) <NEW_LINE> return <NEW_LINE> <DEDENT> manuscripts = [] <NEW_LINE> for index, arg in enumerate(args): <NEW_LINE> <INDENT> if index % 2 == 0: <NEW_LINE> <INDENT> temp_manuscript = {"id": arg} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp_manuscript["file"] = arg <NEW_LINE> manuscripts.append(temp_manuscript) <NEW_LINE> <DEDENT> <DEDENT> for manuscript in manuscripts: <NEW_LINE> <INDENT> manuscript_id = manuscript["id"] <NEW_LINE> input_file = manuscript["file"] <NEW_LINE> try: <NEW_LINE> <INDENT> manuscript = Manuscript.objects.get(id=manuscript_id) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> raise IOError( "Manuscript {0} does not exist".format(manuscript_id) ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> mapping_csv = csv.DictReader( open( "data_dumps/folio_mapping/{0}".format(input_file), "rU" ) ) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> raise IOError( "File data_dumps/folio_mapping/{0} does not exist".format( input_file ) ) <NEW_LINE> <DEDENT> self.stdout.write( "Starting import process for manuscript {0}".format( manuscript_id ) ) <NEW_LINE> for index, row in enumerate(mapping_csv): <NEW_LINE> <INDENT> folio = row["folio"] <NEW_LINE> uri = row["uri"] <NEW_LINE> try: <NEW_LINE> <INDENT> folio_obj = Folio.objects.get( number=folio, manuscript__id=manuscript_id ) <NEW_LINE> <DEDENT> except Folio.DoesNotExist: <NEW_LINE> <INDENT> folio_obj = Folio() <NEW_LINE> folio_obj.number = folio <NEW_LINE> folio_obj.manuscript = manuscript <NEW_LINE> <DEDENT> folio_obj.image_uri = uri <NEW_LINE> folio_obj.save() <NEW_LINE> if index > 0 and index % 50 == 0: <NEW_LINE> <INDENT> self.stdout.write("Imported {0} folios".format(index)) <NEW_LINE> <DEDENT> <DEDENT> self.stdout.write( "All folios of manuscript {0} have been imported".format( manuscript_id ) ) <NEW_LINE> <DEDENT> if options["refresh"]: <NEW_LINE> <INDENT> self.stdout.write("Refreshing Solr chants after folio import") <NEW_LINE> call_command( "refresh_solr", "chants", *[str(man["id"]) for man in manuscripts] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stdout.write( "Import process completed. To refresh Solr," "use './manage.py refresh_solr chants [manuscript_id ...]'" )
Import a folio mapping (CSV file) Save that mapping to both django and Solr (through signals) Usage: See 'help' below
62599046a79ad1619776b3c8
class BaseUp(DefaultChildrenMixin, BaseTitle): <NEW_LINE> <INDENT> main_text = models.CharField(verbose_name=_('Main text'), max_length=1000, blank=True, default='Main Text') <NEW_LINE> main_text_color = HexColorField(blank=True) <NEW_LINE> main_text_is_raw_html = models.BooleanField( verbose_name=_('Is main text raw HTML?'), default=False) <NEW_LINE> main_title_size = models.IntegerField( verbose_name=_('Main Title Size (h1~h6)'), choices=TITLE_SIZE_CHOICES, default=2) <NEW_LINE> main_title_is_raw_html = models.BooleanField( verbose_name=_('Is main title raw HTML?'), default=False) <NEW_LINE> text_align = models.CharField(verbose_name=_('Text alignment'), max_length=32, default='left', choices=TEXT_ALIGN_CHOICES) <NEW_LINE> form = modelform_factory('BaseUpForm', css_style=css_style_form_field, main_text=text_form_field) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def main_title_tag(self): <NEW_LINE> <INDENT> return 'h{}'.format(self.main_title_size)
abstract widget to support 2-Up and 3-Up widget patterns, MSP Member Materials
6259904626238365f5fadea4
class HomematicipLightMeasuring(HomematicipLight): <NEW_LINE> <INDENT> @property <NEW_LINE> def current_power_w(self): <NEW_LINE> <INDENT> return self._device.currentPowerConsumption <NEW_LINE> <DEDENT> @property <NEW_LINE> def today_energy_kwh(self): <NEW_LINE> <INDENT> if self._device.energyCounter is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return round(self._device.energyCounter)
MomematicIP measuring light device.
6259904630c21e258be99b4f
class FieldSchema(object): <NEW_LINE> <INDENT> def __init__(self, name=None, type=None, comment=None,): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = type <NEW_LINE> self.comment = comment <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.name = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.type = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 3: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.comment = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('FieldSchema') <NEW_LINE> if self.name is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('name', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.name) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.type is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('type', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.type) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.comment is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('comment', TType.STRING, 3) <NEW_LINE> oprot.writeString(self.comment) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - name - type - comment
625990463617ad0b5ee07484
class PresentInput(Process): <NEW_LINE> <INDENT> inputs = NdarrayParam(shape=('...',)) <NEW_LINE> presentation_time = NumberParam(low=0, low_open=True) <NEW_LINE> def __init__(self, inputs, presentation_time): <NEW_LINE> <INDENT> self.inputs = inputs <NEW_LINE> self.presentation_time = presentation_time <NEW_LINE> super(PresentInput, self).__init__( default_size_out=self.inputs[0].size) <NEW_LINE> <DEDENT> def make_step(self, size_in, size_out, dt, rng): <NEW_LINE> <INDENT> assert size_in == 0 <NEW_LINE> assert size_out == self.inputs[0].size <NEW_LINE> n = len(self.inputs) <NEW_LINE> inputs = self.inputs.reshape(n, -1) <NEW_LINE> presentation_time = float(self.presentation_time) <NEW_LINE> def step_image_input(t): <NEW_LINE> <INDENT> i = int(t / presentation_time + 1e-7) <NEW_LINE> return inputs[i % n] <NEW_LINE> <DEDENT> return step_image_input
Present a series of inputs, each for the same fixed length of time. Parameters ---------- inputs : array_like Inputs to present, where each row is an input. Rows will be flattened. presentation_time : float Show each input for `presentation_time` seconds.
6259904663b5f9789fe864b5
class OSSM_Hyd_Reader(OSSM_ReaderClass): <NEW_LINE> <INDENT> Type = "OSSM_Hyd" <NEW_LINE> TimeZone = None <NEW_LINE> Fields = { "Discharge": 0, } <NEW_LINE> Units = {} <NEW_LINE> def IsType(self, FileName): <NEW_LINE> <INDENT> return self.CheckHeader(FileName, 3) <NEW_LINE> <DEDENT> def LoadData(self, FileName): <NEW_LINE> <INDENT> infile = open(FileName, 'r', encoding='utf-8') <NEW_LINE> self.Name = infile.readline().strip() <NEW_LINE> line = infile.readline() <NEW_LINE> self.LatLong = tuple( map(float, line.strip().split(',')) ) <NEW_LINE> self.Units["Discharge"] = infile.readline().strip() <NEW_LINE> self.ReadData(infile) <NEW_LINE> self.DataArray = self.DataArray[:, 0:1].copy()
Reader for the OSSM "Hydrology" format -- usually used for river flow data
62599046ec188e330fdf9be5
class UserManager(BaseUserManager): <NEW_LINE> <INDENT> def _create_user(self, username, email, password, is_superuser, **extra_fields): <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> if not username: <NEW_LINE> <INDENT> raise ValueError('The given username must be set') <NEW_LINE> <DEDENT> email = self.normalize_email(email) <NEW_LINE> user = self.model(username=username, email=email, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_user(self, username, email=None, password=None, **extra_fields): <NEW_LINE> <INDENT> return self._create_user(username, email, password, False, **extra_fields) <NEW_LINE> <DEDENT> def create_superuser(self, username, email, password, **extra_fields): <NEW_LINE> <INDENT> return self._create_user(username, email, password, True, **extra_fields) <NEW_LINE> <DEDENT> def get_default_user(self): <NEW_LINE> <INDENT> return super(UserManager, self).get_queryset().get(username='default') <NEW_LINE> <DEDENT> def get_nobody_user(self): <NEW_LINE> <INDENT> return super(UserManager, self).get_queryset().get(username='nobody') <NEW_LINE> <DEDENT> def get_system_user(self): <NEW_LINE> <INDENT> return super(UserManager, self).get_queryset().get(username='system') <NEW_LINE> <DEDENT> def hide_defaults(self): <NEW_LINE> <INDENT> return super(UserManager, self).get_queryset().exclude( username__in=('nobody', 'default', 'system') )
Pootle User manager. This manager hides the 'nobody' and 'default' users for normal queries, since they are special users. Code that needs access to these users should use the methods get_default_user and get_nobody_user.
6259904645492302aabfd820
class SessionDataStore(oauth.OAuthStore): <NEW_LINE> <INDENT> def _get_chrome_app(self, consumer_key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return models.MachineApp.objects.get(consumer_key = consumer_key, app_type='chrome') <NEW_LINE> <DEDENT> except models.MachineApp.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _get_request_token(self, token_str, type=None, pha=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return models.SessionRequestToken.objects.get(token = token_str) <NEW_LINE> <DEDENT> except models.SessionRequestToken.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _get_token(self, token_str, type=None, pha=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return models.SessionToken.objects.get(token = token_str) <NEW_LINE> <DEDENT> except models.SessionToken.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def lookup_consumer(self, consumer_key): <NEW_LINE> <INDENT> return self._get_chrome_app(consumer_key) <NEW_LINE> <DEDENT> def create_request_token(self, consumer, request_token_str, request_token_secret, verifier, oauth_callback): <NEW_LINE> <INDENT> token = models.SessionRequestToken.objects.create(token = request_token_str, secret = request_token_secret) <NEW_LINE> return token <NEW_LINE> <DEDENT> def lookup_request_token(self, consumer, request_token_str): <NEW_LINE> <INDENT> return self._get_request_token(token_str = request_token_str) <NEW_LINE> <DEDENT> def authorize_request_token(self, request_token, user=None): <NEW_LINE> <INDENT> request_token.user = user <NEW_LINE> request_token.authorized_p = True <NEW_LINE> request_token.save() <NEW_LINE> <DEDENT> def mark_request_token_used(self, consumer, request_token): <NEW_LINE> <INDENT> if not request_token.authorized_p: <NEW_LINE> <INDENT> raise oauth.OAuthError("request token not authorized") <NEW_LINE> <DEDENT> request_token.delete() <NEW_LINE> <DEDENT> def create_access_token(self, consumer, request_token, access_token_str, access_token_secret): <NEW_LINE> <INDENT> token = models.SessionToken.objects.create( token = access_token_str, secret = access_token_secret, user = request_token.user) <NEW_LINE> return token <NEW_LINE> <DEDENT> def lookup_access_token(self, consumer, access_token_str): <NEW_LINE> <INDENT> return self._get_token(access_token_str) <NEW_LINE> <DEDENT> def check_and_store_nonce(self, nonce_str): <NEW_LINE> <INDENT> nonce, created = models.Nonce.objects.get_or_create(nonce = nonce_str, oauth_type = self.__class__.__name__) <NEW_LINE> if not created: <NEW_LINE> <INDENT> raise oauth.OAuthError("Nonce already exists")
Layer between Python OAuth and Django database. An oauth-server for in-RAM chrome-app user-specific tokens
62599046baa26c4b54d505f3
class Cpu(models.Model): <NEW_LINE> <INDENT> Asset = models.OneToOneField(Assets, on_delete=models.CASCADE) <NEW_LINE> cpu_model = models.CharField( verbose_name='cpu型号', max_length=128, null=True, blank=True ) <NEW_LINE> cpu_count = models.PositiveSmallIntegerField( verbose_name='cpu数量', default=1 ) <NEW_LINE> cpu_core_count = models.PositiveSmallIntegerField( verbose_name='cpu核心数', default=1 ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '<{0}:{1}>'.format(self.Asset.Asset_Name, self.cpu_model) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'cpu信息'
cpu info
625990468a43f66fc4bf34de
class RecipeViewSet(BaseRecipeAttrViewSet): <NEW_LINE> <INDENT> serializer_class = serializers.RecipeSerializer <NEW_LINE> queryset = Recipe.objects.all()
recipe view set
62599046004d5f362081f98b
class Car: <NEW_LINE> <INDENT> def __init__(self, price_of_car=None, type_of_car=None, time_of_renting=None): <NEW_LINE> <INDENT> self.price = price_of_car <NEW_LINE> self.type = type_of_car <NEW_LINE> self.time = time_of_renting <NEW_LINE> <DEDENT> def car_info(self, type_of_car=None): <NEW_LINE> <INDENT> selection = str(input( "select the car which you want to rent:\n 1. SUV \n 2. Hatchbeck \n 3.sedan ")) <NEW_LINE> if selection == '1': <NEW_LINE> <INDENT> self.type = 'SUV' <NEW_LINE> self.price_info() <NEW_LINE> <DEDENT> elif selection == '2': <NEW_LINE> <INDENT> self.type = 'Hatchbeck' <NEW_LINE> self.price_info() <NEW_LINE> <DEDENT> elif selection == '3': <NEW_LINE> <INDENT> self.type = 'sedan' <NEW_LINE> self.price_info() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("the number you enter is not valid, please enter again.") <NEW_LINE> <DEDENT> <DEDENT> def price_info(self, price_of_car=None): <NEW_LINE> <INDENT> time_of_renting = int( input("How many days do you want to rent your car?")) <NEW_LINE> if time_of_renting <= 7: <NEW_LINE> <INDENT> if self.type == 'SUV': <NEW_LINE> <INDENT> price_of_car = 100 <NEW_LINE> print( "if you choocse ro rent {} car for {} days, the price will be {} pounds per one day!".format(self.type, time_of_renting, price_of_car)) <NEW_LINE> <DEDENT> if self.type == 'Hatchbeck': <NEW_LINE> <INDENT> price_of_car = 30 <NEW_LINE> print( "if you choocse ro rent {} car for {} days, the price will be {} pounds per one day!".format(self.type, time_of_renting, price_of_car)) <NEW_LINE> <DEDENT> if self.type == 'sedan': <NEW_LINE> <INDENT> price_of_car = 50 <NEW_LINE> print( "if you choocse ro rent {} car for {} days, the price will be {} pounds per one day!".format(self.type, time_of_renting, price_of_car)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.type == 'SUV': <NEW_LINE> <INDENT> price_of_car = 90 <NEW_LINE> print( "if you choocse ro rent {} car for {} days, the price will be {} pounds per one day!".format(self.type, time_of_renting, price_of_car)) <NEW_LINE> <DEDENT> if self.type == 'Hatchbeck': <NEW_LINE> <INDENT> price_of_car = 25 <NEW_LINE> print( "if you choocse ro rent {} car for {} days, the price will be {} pounds per one day!".format(self.type, time_of_renting, price_of_car)) <NEW_LINE> <DEDENT> if self.type == 'sedan': <NEW_LINE> <INDENT> price_of_car = 40 <NEW_LINE> print( "if you choocse ro rent {} car for {} days, the price will be {} pounds per one day!".format(self.type, time_of_renting, price_of_car))
This class is created for customers to check the information of car.
62599046097d151d1a2c23b5
class CertificateProfile(VersionedPanObject): <NEW_LINE> <INDENT> ROOT = Root.PANORAMA_VSYS <NEW_LINE> SUFFIX = ENTRY <NEW_LINE> CHILDTYPES = ("device.CertificateProfileCaCertificate",) <NEW_LINE> def _setup(self): <NEW_LINE> <INDENT> self._xpaths.add_profile(value="/certificate-profile") <NEW_LINE> params = [] <NEW_LINE> params.append( VersionedParamPath( "username_field", path="username-field/{username_field}", values=("subject", "subject-alt"), ) ) <NEW_LINE> params.append( VersionedParamPath( "username_field_value", path="username-field/{username_field}", ) ) <NEW_LINE> params.append(VersionedParamPath("domain", path="domain",)) <NEW_LINE> params.append(VersionedParamPath("use_crl", path="use-crl",)) <NEW_LINE> params.append(VersionedParamPath("use_ocsp", path="use-ocsp",)) <NEW_LINE> params.append( VersionedParamPath( "crl_receive_timeout", default=5, vartype="int", path="crl-receive-timeout", ) ) <NEW_LINE> params.append( VersionedParamPath( "ocsp_receive_timeout", default=5, vartype="int", path="ocsp-receive-timeout", ) ) <NEW_LINE> params.append( VersionedParamPath( "certificate_status_timeout", default=5, vartype="int", path="cert-status-timeout", ) ) <NEW_LINE> params.append( VersionedParamPath( "block_unknown_certificate", vartype="yesno", path="block-unknown-cert", ) ) <NEW_LINE> params.append( VersionedParamPath( "block_certificate_timeout", vartype="yesno", path="block-timeout-cert", ) ) <NEW_LINE> params.append( VersionedParamPath("block_unauthenticated_certificate", exclude=True,) ) <NEW_LINE> params[-1].add_profile( "7.1.0", vartype="yesno", path="block-unauthenticated-cert", ) <NEW_LINE> params.append(VersionedParamPath("block_expired_certificate", exclude=True,)) <NEW_LINE> params[-1].add_profile( "8.1.0", vartype="yesno", path="block-expired-cert", ) <NEW_LINE> params.append(VersionedParamPath("ocsp_exclude_nonce", exclude=True,)) <NEW_LINE> params[-1].add_profile( "9.0.0", path="ocsp-exclude-nonce", vartype="yesno", ) <NEW_LINE> self._params = tuple(params)
Certificate profile object. Args: name (str): The name username_field (str): The username field. Valid values are "subject", "subject-alt", or "none". username_field_value (str): The value for the given `username_field`. domain (str): The domain. use_crl (bool): Use CRL. use_ocsp (bool): Use OCSP. crl_receive_timeout (int): CRL receive timeout (sec). ocsp_receive_timeout (int): OCSP receive timeout (sec). certificate_status_timeout (int): Certificate status timeout (sec). block_unknown_certificate (bool): Block session if certificate status is unknown. block_certificate_timeout (bool): Block if a session certificate status can't be retrieved within timeout. block_unauthenticated_certificate (bool): (PAN-OS 7.1) Block session if the certificate was not issued to the authenticating device. block_expired_certificate (bool): (PAN-OS 8.1) Block session if the certificate is expired. ocsp_exclude_nonce (bool): (PAN-OS 9.0) Whether to exclude nonce extension for OCSP requests.
6259904630dc7b76659a0b7c
class NamedEntities(AnnotationLayerWithIDs): <NEW_LINE> <INDENT> element = 'namedEntities' <NEW_LINE> def __init__(self, type): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.type = type <NEW_LINE> <DEDENT> @property <NEW_LINE> def tcf(self): <NEW_LINE> <INDENT> element = super().tcf <NEW_LINE> element.set('type', self.type) <NEW_LINE> return element
The namedEntities annotation layer. It holds a sequence of :class:`NamedEntity` objects.
62599046d53ae8145f9197a9
class ExtendPygments(Pygments): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> self.assert_has_content() <NEW_LINE> try: <NEW_LINE> <INDENT> lexer = get_lexer_by_name(self.arguments[0]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> lexer = TextLexer() <NEW_LINE> <DEDENT> if pys.PYGMENTS_RST_OPTIONS is not None: <NEW_LINE> <INDENT> for k, v in six.iteritems(pys.PYGMENTS_RST_OPTIONS): <NEW_LINE> <INDENT> if k not in self.options: <NEW_LINE> <INDENT> self.options[k] = v <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if ('linenos' in self.options and self.options['linenos'] not in ('table', 'inline')): <NEW_LINE> <INDENT> if self.options['linenos'] == 'none': <NEW_LINE> <INDENT> self.options.pop('linenos') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.options['linenos'] = 'table' <NEW_LINE> <DEDENT> <DEDENT> for flag in ('nowrap', 'nobackground', 'anchorlinenos'): <NEW_LINE> <INDENT> if flag in self.options: <NEW_LINE> <INDENT> self.options[flag] = True <NEW_LINE> <DEDENT> <DEDENT> formatter = HtmlFormatter(noclasses=False, **self.options) <NEW_LINE> parsed = highlight('\n'.join(self.content), lexer, formatter) <NEW_LINE> parsed = parsed.replace( '<div class="highlight"><pre>', ''.join(( '<pre class="highlight">', '<code class="language-%s">' % lexer.name.lower() )) ) <NEW_LINE> parsed = parsed.replace('</pre></div>', '</code></pre>') <NEW_LINE> return [nodes.raw('', parsed, format='html')]
Adapt Pygments comportement to Ace_editor.
625990463c8af77a43b688e2
class NewHostHandler(BaseHandler): <NEW_LINE> <INDENT> async def post(self, *args, **kwargs): <NEW_LINE> <INDENT> host = self.get_argument('host_id') <NEW_LINE> if 'http' in host: <NEW_LINE> <INDENT> host = host.split('http://')[-1] <NEW_LINE> <DEDENT> isrun = await self.ping(url='http://{}:{}'.format(host, self.get_argument('host_port'))) <NEW_LINE> inst = await self.application.objects.create( Host, host=host, name=self.get_argument('host_name'), scrapyd_name=self.get_argument('scrapy_name', ''), scrapyd_password=self.get_argument('scrapy_password', ''), port=self.get_argument('host_port'), create_time=time.time(), is_run=isrun) <NEW_LINE> if inst is None: <NEW_LINE> <INDENT> self.write({"data": False, "msg": "dataBase error!"}, status_code=404) <NEW_LINE> return <NEW_LINE> <DEDENT> self.write({"data": True})
new link scrapyd server
6259904621a7993f00c672b3
class MotorDifferentor: <NEW_LINE> <INDENT> def __init__(self, plforward, plbackward, prforward, prbackward): <NEW_LINE> <INDENT> self.logger = logging.getLogger(__name__) <NEW_LINE> self.logger.info( "MotorDifferentor(lf:%d, lb:%d, rf:%d, rb:%d) created.", plforward, plbackward, prforward, prbackward ) <NEW_LINE> self.motorleft = Motor(plforward, plbackward) <NEW_LINE> self.motorright = Motor(prforward, prbackward) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.logger.info("MotorDifferentor is being deconstructed") <NEW_LINE> self.motorleft = None <NEW_LINE> self.motorright = None <NEW_LINE> <DEDENT> def set_speed(self, v, deltav): <NEW_LINE> <INDENT> self.logger.info( "MotorDifferentor set_speed(%d, %d)=>(left:%d, right:%d)", v, deltav, v+deltav, v-deltav ) <NEW_LINE> if v+deltav>100 or v+deltav<-100 or v-deltav>100 or v-deltav<-100: <NEW_LINE> <INDENT> self.logger.warning("Speed may be cut due to overflow!") <NEW_LINE> <DEDENT> self.motorleft.set_speed(v+deltav) <NEW_LINE> self.motorright.set_speed(v-deltav)
For controlling 2 motor with v+-deltav deltav direction + right - left
62599046d10714528d69f032
class DefinitionListTreeNode(TreeNode): <NEW_LINE> <INDENT> canonical_tag_name = 'dl' <NEW_LINE> alias_tag_names = () <NEW_LINE> render_html_template = '<dl>{inner_html}</dl>\n' <NEW_LINE> def render_html(self, inner_html, **kwargs): <NEW_LINE> <INDENT> return self.render_html_template.format(inner_html=inner_html) <NEW_LINE> <DEDENT> def render_text(self, inner_text, **kwargs): <NEW_LINE> <INDENT> return inner_text
Definitions list tree node class.
6259904607d97122c4217fec
class VirtualNetworkGatewayListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[VirtualNetworkGateway]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["VirtualNetworkGateway"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(VirtualNetworkGatewayListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None
Response for the ListVirtualNetworkGateways API service call. Variables are only populated by the server, and will be ignored when sending a request. :param value: Gets a list of VirtualNetworkGateway resources that exists in a resource group. :type value: list[~azure.mgmt.network.v2018_01_01.models.VirtualNetworkGateway] :ivar next_link: The URL to get the next set of results. :vartype next_link: str
6259904623849d37ff852406
class sorted_merge(object): <NEW_LINE> <INDENT> pass
description of class
6259904626068e7796d4dc91
class IdentityInterface(IOBase): <NEW_LINE> <INDENT> input_spec = DynamicTraitedSpec <NEW_LINE> output_spec = DynamicTraitedSpec <NEW_LINE> def __init__(self, fields=None, **inputs): <NEW_LINE> <INDENT> super(IdentityInterface, self).__init__(**inputs) <NEW_LINE> if fields is None or not fields: <NEW_LINE> <INDENT> raise Exception('Identity Interface fields must be a non-empty list') <NEW_LINE> <DEDENT> self._fields = fields <NEW_LINE> add_traits(self.inputs, fields) <NEW_LINE> <DEDENT> def _add_output_traits(self, base): <NEW_LINE> <INDENT> undefined_traits = {} <NEW_LINE> for key in self._fields: <NEW_LINE> <INDENT> base.add_trait(key, traits.Any) <NEW_LINE> undefined_traits[key] = Undefined <NEW_LINE> <DEDENT> base.trait_set(trait_change_notify=False, **undefined_traits) <NEW_LINE> return base <NEW_LINE> <DEDENT> def _list_outputs(self): <NEW_LINE> <INDENT> outputs = self._outputs().get() <NEW_LINE> for key in self._fields: <NEW_LINE> <INDENT> val = getattr(self.inputs, key) <NEW_LINE> if isdefined(val): <NEW_LINE> <INDENT> outputs[key] = val <NEW_LINE> <DEDENT> <DEDENT> return outputs
Basic interface class generates identity mappings Examples -------- >>> from nipype.interfaces.utility import IdentityInterface >>> ii = IdentityInterface(fields=['a','b']) >>> ii.inputs.a <undefined> >>> ii.inputs.a = 'foo' >>> out = ii._outputs() >>> out.a <undefined> >>> out = ii.run() >>> out.outputs.a 'foo'
625990468da39b475be0453a
class Subscription(six.with_metaclass(abc.ABCMeta)): <NEW_LINE> <INDENT> @enum.unique <NEW_LINE> class Kind(enum.Enum): <NEW_LINE> <INDENT> NONE = 'none' <NEW_LINE> TERMINATION_ONLY = 'termination only' <NEW_LINE> FULL = 'full'
Describes customer code's interest in values from the other side. Attributes: kind: A Kind value describing the overall kind of this value. termination_callback: A callable to be passed the Outcome associated with the operation after it has terminated. Must be non-None if kind is Kind.TERMINATION_ONLY. Must be None otherwise. allowance: A callable behavior that accepts positive integers representing the number of additional payloads allowed to be passed to the other side of the operation. Must be None if kind is Kind.FULL. Must not be None otherwise. operator: An Operator to be passed values from the other side of the operation. Must be non-None if kind is Kind.FULL. Must be None otherwise. protocol_receiver: A ProtocolReceiver to be passed protocol objects as they become available during the operation. Must be non-None if kind is Kind.FULL.
6259904626238365f5fadea6
class GetInfo(object): <NEW_LINE> <INDENT> def get_current_activity(self): <NEW_LINE> <INDENT> cur_act = driver.current_activity <NEW_LINE> return cur_act <NEW_LINE> <DEDENT> def get_device_name(self): <NEW_LINE> <INDENT> b = os.popen('adb devices') <NEW_LINE> device_name = b.readlines()[1].split()[0] <NEW_LINE> return device_name <NEW_LINE> <DEDENT> def get_android_version(self): <NEW_LINE> <INDENT> c = os.popen('adb shell getprop ro.build.version.release') <NEW_LINE> return c.readline() <NEW_LINE> <DEDENT> def get_middle_coordinate(self): <NEW_LINE> <INDENT> list1 = [] <NEW_LINE> x = (driver.get_window_size()['width']) <NEW_LINE> y = (driver.get_window_size()['height']) <NEW_LINE> list1.append(x) <NEW_LINE> list1.append(y) <NEW_LINE> return list1 <NEW_LINE> <DEDENT> def get_time(self, display=0): <NEW_LINE> <INDENT> if display == 0: <NEW_LINE> <INDENT> now = time.strftime('%y%m%d%H%M%S') <NEW_LINE> <DEDENT> elif display == 1: <NEW_LINE> <INDENT> now = time.strftime('%Y.%m.%d_%H:%M:%S') <NEW_LINE> <DEDENT> return now <NEW_LINE> <DEDENT> def get_xml(self): <NEW_LINE> <INDENT> content = driver.page_source <NEW_LINE> return content <NEW_LINE> <DEDENT> def get_desktop_path(self): <NEW_LINE> <INDENT> key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') <NEW_LINE> return winreg.QueryValueEx(key, "Desktop")[0]
信息获取
6259904630c21e258be99b51
class ContentManager(models.Manager, ModeratedQuerySetMixin, SEIndexQuerySetMixin): <NEW_LINE> <INDENT> def post(self, authors, category, title, body, visible=True, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> [kwargs.pop(name, None) for name in ['authors', 'category', 'title', 'body', 'visible']] <NEW_LINE> category_instance = Category.objects.get_by_name(category) <NEW_LINE> content, _ = self.get_or_create(category=category_instance, title=title, body=body, published=visible, **kwargs) <NEW_LINE> authors = make_iterable(authors, list) <NEW_LINE> content.authors.add(*authors) <NEW_LINE> return content <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> print_exc(e) <NEW_LINE> return None
Manager des contenus
6259904696565a6dacd2d92f
class RegisterSkyMap(AdminOperation): <NEW_LINE> <INDENT> def __init__(self, skymap_name: str) -> None: <NEW_LINE> <INDENT> super().__init__(f"skymaps-{skymap_name}") <NEW_LINE> self.skymap_name = skymap_name <NEW_LINE> self.config_uri = f"resource://lsst.gen3_shared_repo_admin/config/skymaps/{skymap_name}.py" <NEW_LINE> <DEDENT> def print_status(self, tool: RepoAdminTool, indent: int) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tool.butler.registry.expandDataId(skymap=self.name) <NEW_LINE> <DEDENT> except LookupError: <NEW_LINE> <INDENT> print(f"{' '*indent}{self.name}: not started") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(f"{' '*indent}{self.name}: done") <NEW_LINE> <DEDENT> <DEDENT> def run(self, tool: RepoAdminTool) -> None: <NEW_LINE> <INDENT> from lsst.pipe.tasks.script.registerSkymap import MakeSkyMapConfig <NEW_LINE> config = MakeSkyMapConfig() <NEW_LINE> config.loadFromStream(ButlerURI(self.config_uri).read().decode()) <NEW_LINE> assert config.name == self.skymap_name <NEW_LINE> tool.log.info("Constructing SkyMap '%s' from configuration.", config.name) <NEW_LINE> skymap = config.skyMap.apply() <NEW_LINE> skymap.logSkyMapInfo(tool.log) <NEW_LINE> tool.log.info("Registering SkyMap '%s' in database.", config.name) <NEW_LINE> if not tool.dry_run: <NEW_LINE> <INDENT> skymap.register(config.name, tool.butler)
A concrete `AdminOperation` that calls `BaseSkyMap.register`, using configuration packaged within `gen3_shared_repo_admin` itself. Parameters ---------- skymap_name : `str` Name for the skymap dimension record; also used as the filename (without extension) for the config file, and the operation name (with a ``skymaps-`` prefix).
62599046b830903b9686ee20
class Describe(base_classes.GlobalRegionalDescriber): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> cli = Describe.GetCLIGenerator() <NEW_LINE> base_classes.GlobalRegionalDescriber.Args(parser, 'forwardingRules', cli, 'compute.forwarding-rules') <NEW_LINE> <DEDENT> @property <NEW_LINE> def global_service(self): <NEW_LINE> <INDENT> return self.compute.globalForwardingRules <NEW_LINE> <DEDENT> @property <NEW_LINE> def regional_service(self): <NEW_LINE> <INDENT> return self.compute.forwardingRules <NEW_LINE> <DEDENT> @property <NEW_LINE> def global_resource_type(self): <NEW_LINE> <INDENT> return 'globalForwardingRules' <NEW_LINE> <DEDENT> @property <NEW_LINE> def regional_resource_type(self): <NEW_LINE> <INDENT> return 'forwardingRules'
Display detailed information about a forwarding rule.
62599046b57a9660fecd2dc8
class GlobalId(BaseGlobalId): <NEW_LINE> <INDENT> pass
An Id which is globally unique
6259904650485f2cf55dc2d3
class ConstantFeeModel(FeeModel, IFeeModel): <NEW_LINE> <INDENT> def GetOrderFee(self, parameters): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self, fee, currency): <NEW_LINE> <INDENT> pass
Provides an order fee model that always returns the same order fee. ConstantFeeModel(fee: Decimal, currency: str)
62599046004d5f362081f98c
class RemoveClothOperator(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "fracture.cloth_remove" <NEW_LINE> bl_label = "Remove Cloth" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> if context.object is None: <NEW_LINE> <INDENT> return {'CANCELLED'} <NEW_LINE> <DEDENT> if has_cloth(self, context): <NEW_LINE> <INDENT> remove_cloth(self, context) <NEW_LINE> return {'FINISHED'} <NEW_LINE> <DEDENT> return {'CANCELLED'}
Removes the Cloth setup from the object
62599046d10714528d69f033
class School(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) <NEW_LINE> slug = models.SlugField(max_length=150, null=True) <NEW_LINE> location = models.CharField(max_length=255, blank=True, null=True) <NEW_LINE> url = models.URLField(max_length=511, blank=True) <NEW_LINE> facebook_id = models.BigIntegerField(blank=True, null=True) <NEW_LINE> usde_id = models.BigIntegerField(blank=True, null=True) <NEW_LINE> file_count = models.IntegerField(default=0) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['-file_count', 'name'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.slug: <NEW_LINE> <INDENT> self.slug = defaultfilters.slugify(self.name) <NEW_LINE> <DEDENT> super(School, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def autocomplete_search_fields(): <NEW_LINE> <INDENT> return ("name__icontains",) <NEW_LINE> <DEDENT> def update_note_count(self): <NEW_LINE> <INDENT> self.file_count = sum([course.file_count for course in self.course_set.all()]) <NEW_LINE> self.save() <NEW_LINE> <DEDENT> def update_related_note_count(self): <NEW_LINE> <INDENT> for course in self.course_set.all(): <NEW_LINE> <INDENT> course.update_note_count() <NEW_LINE> <DEDENT> self.update_note_count()
A grouping that contains many courses
6259904623e79379d538d84a
class DuellingMLP(hk.Module): <NEW_LINE> <INDENT> def __init__( self, num_actions: int, hidden_sizes: Sequence[int], ): <NEW_LINE> <INDENT> super().__init__(name='duelling_q_network') <NEW_LINE> self._value_mlp = hk.nets.MLP([*hidden_sizes, 1]) <NEW_LINE> self._advantage_mlp = hk.nets.MLP([*hidden_sizes, num_actions]) <NEW_LINE> <DEDENT> def __call__(self, inputs: jnp.ndarray) -> jnp.ndarray: <NEW_LINE> <INDENT> value = self._value_mlp(inputs) <NEW_LINE> advantages = self._advantage_mlp(inputs) <NEW_LINE> advantages -= jnp.mean(advantages, axis=-1, keepdims=True) <NEW_LINE> q_values = value + advantages <NEW_LINE> return q_values
A Duelling MLP Q-network.
62599046d53ae8145f9197ac
class CommonBaseTree(tree.Node): <NEW_LINE> <INDENT> AND = 'AND' <NEW_LINE> OR = 'OR' <NEW_LINE> default = AND <NEW_LINE> query = None <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CommonBaseTree, self).__init__(children=list(args) + kwargs.items()) <NEW_LINE> <DEDENT> def _combine(self, other, conn): <NEW_LINE> <INDENT> if not isinstance(other, (BaseTree)): <NEW_LINE> <INDENT> raise TypeError(other) <NEW_LINE> <DEDENT> obj = type(self)() <NEW_LINE> obj.add(self, conn) <NEW_LINE> obj.add(other, conn) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return self._combine(other, self.OR) <NEW_LINE> <DEDENT> def __and__(self, other): <NEW_LINE> <INDENT> return self._combine(other, self.AND) <NEW_LINE> <DEDENT> def __invert__(self): <NEW_LINE> <INDENT> obj = type(self)() <NEW_LINE> obj.add(self, self.AND) <NEW_LINE> obj.negate() <NEW_LINE> return obj <NEW_LINE> <DEDENT> def set_query(self, query): <NEW_LINE> <INDENT> self.query = query <NEW_LINE> return self
Encapsulates filters as objects that can then be combined logically (using & and |).
62599046be383301e0254b65
class TiledObject(TiledElement): <NEW_LINE> <INDENT> def __init__(self, parent, node): <NEW_LINE> <INDENT> TiledElement.__init__(self) <NEW_LINE> self.parent = parent <NEW_LINE> self.id = 0 <NEW_LINE> self.name = None <NEW_LINE> self.type = None <NEW_LINE> self.x = 0 <NEW_LINE> self.y = 0 <NEW_LINE> self.width = 0 <NEW_LINE> self.height = 0 <NEW_LINE> self.rotation = 0 <NEW_LINE> self.gid = 0 <NEW_LINE> self.visible = 1 <NEW_LINE> self.template = None <NEW_LINE> self.parse_xml(node) <NEW_LINE> <DEDENT> @property <NEW_LINE> def image(self): <NEW_LINE> <INDENT> if self.gid: <NEW_LINE> <INDENT> return self.parent.images[self.gid] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def parse_xml(self, node): <NEW_LINE> <INDENT> def read_points(text): <NEW_LINE> <INDENT> return tuple(tuple(map(float, i.split(','))) for i in text.split()) <NEW_LINE> <DEDENT> self._set_properties(node) <NEW_LINE> if self.gid: <NEW_LINE> <INDENT> self.gid = self.parent.register_gid(self.gid) <NEW_LINE> <DEDENT> points = None <NEW_LINE> polygon = node.find('polygon') <NEW_LINE> if polygon is not None: <NEW_LINE> <INDENT> points = read_points(polygon.get('points')) <NEW_LINE> self.closed = True <NEW_LINE> <DEDENT> polyline = node.find('polyline') <NEW_LINE> if polyline is not None: <NEW_LINE> <INDENT> points = read_points(polyline.get('points')) <NEW_LINE> self.closed = False <NEW_LINE> <DEDENT> if points: <NEW_LINE> <INDENT> x1 = x2 = y1 = y2 = 0 <NEW_LINE> for x, y in points: <NEW_LINE> <INDENT> if x < x1: x1 = x <NEW_LINE> if x > x2: x2 = x <NEW_LINE> if y < y1: y1 = y <NEW_LINE> if y > y2: y2 = y <NEW_LINE> <DEDENT> self.width = abs(x1) + abs(x2) <NEW_LINE> self.height = abs(y1) + abs(y2) <NEW_LINE> self.points = tuple( [(i[0] + self.x, i[1] + self.y) for i in points]) <NEW_LINE> <DEDENT> return self
Represents a any Tiled Object Supported types: Box, Ellipse, Tile Object, Polyline, Polygon
62599046b5575c28eb71366f
class TopK(PytorchMetric): <NEW_LINE> <INDENT> def __init__(self, k: int, train: bool = True, evaluate: bool = True): <NEW_LINE> <INDENT> super().__init__(self._compute, f"Top-{k}", train, evaluate) <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def _compute(self, predictions: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> top_k = torch.topk(predictions, self.k, -1).indices <NEW_LINE> return (top_k == targets.unsqueeze(-1)).any(-1).sum() / torch.numel(targets)
TopK metric. A prediction is valid if the true target is in the top k. (Multiclass classification)
6259904626068e7796d4dc93
class Test_SDL_Event(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.ev = SDL_Event() <NEW_LINE> <DEDENT> def test_cannot_subclass(self): <NEW_LINE> <INDENT> self.assertRaises(TypeError, type, 'TestSubclass', (SDL_Event,), {}) <NEW_LINE> <DEDENT> def test_weakref(self): <NEW_LINE> <INDENT> ref = weakref.ref(self.ev) <NEW_LINE> <DEDENT> def test_memview(self): <NEW_LINE> <INDENT> mem = memoryview(self.ev) <NEW_LINE> <DEDENT> def test_memview_obj(self): <NEW_LINE> <INDENT> mem = memoryview(self.ev) <NEW_LINE> self.assertIs(mem.obj, self.ev) <NEW_LINE> <DEDENT> def test_memview_bytes(self): <NEW_LINE> <INDENT> mem = memoryview(self.ev) <NEW_LINE> self.assertTrue(mem.c_contiguous) <NEW_LINE> self.assertTrue(mem.contiguous) <NEW_LINE> self.assertEqual(mem.format, 'B') <NEW_LINE> self.assertEqual(mem.itemsize, 1) <NEW_LINE> self.assertEqual(mem.ndim, 1) <NEW_LINE> self.assertEqual(mem.strides, (1,)) <NEW_LINE> <DEDENT> def test_memview_writable(self): <NEW_LINE> <INDENT> mem = memoryview(self.ev) <NEW_LINE> self.assertFalse(mem.readonly) <NEW_LINE> for i in range(mem.nbytes): <NEW_LINE> <INDENT> mem[i] = 42 <NEW_LINE> <DEDENT> <DEDENT> def test_memview_zeroes(self): <NEW_LINE> <INDENT> mem = memoryview(self.ev) <NEW_LINE> zeroes = bytes(mem.nbytes) <NEW_LINE> self.assertEqual(mem.tobytes(), zeroes) <NEW_LINE> <DEDENT> def test_type_attr_get(self): <NEW_LINE> <INDENT> self.assertIs(type(self.ev.type), int) <NEW_LINE> self.assertEqual(self.ev.type, 0) <NEW_LINE> <DEDENT> def test_type_attr_set(self): <NEW_LINE> <INDENT> setattr(self.ev, 'type', 42) <NEW_LINE> <DEDENT> def test_type_attr_set_no_neg(self): <NEW_LINE> <INDENT> self.assertRaises(OverflowError, setattr, self.ev, 'type', -42) <NEW_LINE> <DEDENT> def test_type_attr_set_no_overflow(self): <NEW_LINE> <INDENT> self.assertRaises(OverflowError, setattr, self.ev, 'type', 0xfffffffff) <NEW_LINE> <DEDENT> def test_type_attr_set_reject_non_int(self): <NEW_LINE> <INDENT> self.assertRaises(TypeError, setattr, self.ev, 'type', 42.0) <NEW_LINE> <DEDENT> def test_motion(self): <NEW_LINE> <INDENT> self.assertIs(type(self.ev.motion), SDL_MouseMotionEvent) <NEW_LINE> <DEDENT> def test_motion_readonly(self): <NEW_LINE> <INDENT> self.assertRaises(AttributeError, setattr, self.ev, 'motion', 42) <NEW_LINE> <DEDENT> def test_motion_same_event(self): <NEW_LINE> <INDENT> self.ev.type = 42 <NEW_LINE> self.assertEqual(self.ev.motion.type, 42)
Tests csdl2.SDL_Event
625990464e696a045264e7c7
class Buy_error(Exception): <NEW_LINE> <INDENT> pass
For shop issues.
62599046b57a9660fecd2dca
class BotoReadFileHandle(object): <NEW_LINE> <INDENT> def __init__(self, scheme, key): <NEW_LINE> <INDENT> self._scheme = scheme <NEW_LINE> self._key = key <NEW_LINE> self._closed = False <NEW_LINE> self._offset = 0 <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._key.close(fast=True) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self._key.close() <NEW_LINE> <DEDENT> self._closed = True <NEW_LINE> <DEDENT> def read(self, size=-1): <NEW_LINE> <INDENT> if self._offset or (size > -1): <NEW_LINE> <INDENT> if self._offset >= self._key.size: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> if size > -1: <NEW_LINE> <INDENT> sizeStr = str(self._offset + size - 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sizeStr = "" <NEW_LINE> <DEDENT> hdrs = {"Range": "bytes=%d-%s" % (self._offset, sizeStr)} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hdrs = {} <NEW_LINE> <DEDENT> buf = self._key.get_contents_as_string(headers=hdrs) <NEW_LINE> self._offset += len(buf) <NEW_LINE> return buf <NEW_LINE> <DEDENT> def seek(self, offset, whence=0): <NEW_LINE> <INDENT> if whence == 0: <NEW_LINE> <INDENT> self._offset = offset <NEW_LINE> <DEDENT> elif whence == 1: <NEW_LINE> <INDENT> self._offset += offset <NEW_LINE> <DEDENT> elif whence == 2: <NEW_LINE> <INDENT> self._offset = self._key.size + offset <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise IOError("Invalid 'whence' argument, must be 0, 1, or 2. See file().seek.") <NEW_LINE> <DEDENT> <DEDENT> def tell(self): <NEW_LINE> <INDENT> return self._offset <NEW_LINE> <DEDENT> @property <NEW_LINE> def closed(self): <NEW_LINE> <INDENT> return self._closed <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._scheme + ":///" + self._key.bucket.name + "/" + self._key.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def mode(self): <NEW_LINE> <INDENT> return "rb"
Read-only file handle-like object exposing a subset of file methods. Returned by BotoFileReader's open() method.
62599046baa26c4b54d505f7
class MotorFrame(wx.Frame): <NEW_LINE> <INDENT> def __init__(self, mx_database, motors, shape, timer=True, *args, **kwargs): <NEW_LINE> <INDENT> wx.Frame.__init__(self, *args, **kwargs) <NEW_LINE> self.mx_database = mx_database <NEW_LINE> self.mx_timer = wx.Timer() <NEW_LINE> self.mx_timer.Bind(wx.EVT_TIMER, self._on_mxtimer) <NEW_LINE> top_sizer = self._create_layout(motors, shape) <NEW_LINE> self.SetSizer(top_sizer) <NEW_LINE> self.Fit() <NEW_LINE> self.Raise() <NEW_LINE> if timer: <NEW_LINE> <INDENT> self.mx_timer.Start(100) <NEW_LINE> <DEDENT> <DEDENT> def _create_layout(self, motors, shape): <NEW_LINE> <INDENT> motor_grid = wx.FlexGridSizer(rows=shape[0], cols=shape[1], vgap=2, hgap=2) <NEW_LINE> for i in range(shape[1]): <NEW_LINE> <INDENT> motor_grid.AddGrowableCol(i) <NEW_LINE> <DEDENT> for motor in motors: <NEW_LINE> <INDENT> motor_panel = MotorPanel(motor, self.mx_database, self) <NEW_LINE> mtr_box_sizer = wx.StaticBoxSizer(wx.StaticBox(self, label='{} Controls'.format(motor))) <NEW_LINE> mtr_box_sizer.Add(motor_panel) <NEW_LINE> motor_grid.Add(mtr_box_sizer) <NEW_LINE> <DEDENT> motor_panel_sizer = wx.BoxSizer(wx.HORIZONTAL) <NEW_LINE> motor_panel_sizer.Add(motor_grid) <NEW_LINE> return motor_panel_sizer <NEW_LINE> <DEDENT> def _on_mxtimer(self, evt): <NEW_LINE> <INDENT> self.mx_database.wait_for_messages(0.01)
A lightweight motor frame designed to hold an arbitrary number of motors in an arbitrary grid pattern.
625990461f5feb6acb163f43
class LightSchema: <NEW_LINE> <INDENT> CONF_STATE_ADDRESS = CONF_STATE_ADDRESS <NEW_LINE> CONF_BRIGHTNESS_ADDRESS = "brightness_address" <NEW_LINE> CONF_BRIGHTNESS_STATE_ADDRESS = "brightness_state_address" <NEW_LINE> CONF_COLOR_ADDRESS = "color_address" <NEW_LINE> CONF_COLOR_STATE_ADDRESS = "color_state_address" <NEW_LINE> CONF_COLOR_TEMP_ADDRESS = "color_temperature_address" <NEW_LINE> CONF_COLOR_TEMP_STATE_ADDRESS = "color_temperature_state_address" <NEW_LINE> CONF_COLOR_TEMP_MODE = "color_temperature_mode" <NEW_LINE> CONF_RGBW_ADDRESS = "rgbw_address" <NEW_LINE> CONF_RGBW_STATE_ADDRESS = "rgbw_state_address" <NEW_LINE> CONF_MIN_KELVIN = "min_kelvin" <NEW_LINE> CONF_MAX_KELVIN = "max_kelvin" <NEW_LINE> DEFAULT_NAME = "KNX Light" <NEW_LINE> DEFAULT_COLOR_TEMP_MODE = "absolute" <NEW_LINE> DEFAULT_MIN_KELVIN = 2700 <NEW_LINE> DEFAULT_MAX_KELVIN = 6000 <NEW_LINE> SCHEMA = vol.Schema( { vol.Required(CONF_ADDRESS): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_STATE_ADDRESS): cv.string, vol.Optional(CONF_BRIGHTNESS_ADDRESS): cv.string, vol.Optional(CONF_BRIGHTNESS_STATE_ADDRESS): cv.string, vol.Optional(CONF_COLOR_ADDRESS): cv.string, vol.Optional(CONF_COLOR_STATE_ADDRESS): cv.string, vol.Optional(CONF_COLOR_TEMP_ADDRESS): cv.string, vol.Optional(CONF_COLOR_TEMP_STATE_ADDRESS): cv.string, vol.Optional( CONF_COLOR_TEMP_MODE, default=DEFAULT_COLOR_TEMP_MODE ): cv.enum(ColorTempModes), vol.Optional(CONF_RGBW_ADDRESS): cv.string, vol.Optional(CONF_RGBW_STATE_ADDRESS): cv.string, vol.Optional(CONF_MIN_KELVIN, default=DEFAULT_MIN_KELVIN): vol.All( vol.Coerce(int), vol.Range(min=1) ), vol.Optional(CONF_MAX_KELVIN, default=DEFAULT_MAX_KELVIN): vol.All( vol.Coerce(int), vol.Range(min=1) ), } )
Voluptuous schema for KNX lights.
6259904682261d6c5273086c
class RequestLog(AbstractRequestLog): <NEW_LINE> <INDENT> category = models.CharField( max_length=100, help_text=_lazy("Used to filter / group logs.") ) <NEW_LINE> label = models.CharField( max_length=100, help_text=_lazy("Used to identify individual logs.") ) <NEW_LINE> objects = RequestLogManager() <NEW_LINE> def __str__(self) -> str: <NEW_LINE> <INDENT> if self.user: <NEW_LINE> <INDENT> return ( f"Logged request by {self.user} to '{self.request_path[:100]}' " f"at {self.timestamp}" ) <NEW_LINE> <DEDENT> return ( f"Logged anonymous request to '{self.request_path[:100]}' " f"at {self.timestamp}" ) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return ( f"<RequestLog id={self.id} user_id={self.user_id} " f"timestamp='self.timestamp'>" )
Concrete implementation of a request log.
62599046d7e4931a7ef3d3c4
class CassetteAgent(object): <NEW_LINE> <INDENT> def __init__(self, agent, cassette_path, preserve_exact_body_bytes=False): <NEW_LINE> <INDENT> self.agent = agent <NEW_LINE> self.recording = True <NEW_LINE> self.cassette_path = cassette_path <NEW_LINE> self.preserve_exact_body_bytes = preserve_exact_body_bytes <NEW_LINE> self.index = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> with open(self.cassette_path) as cassette_file: <NEW_LINE> <INDENT> self.cassette = Cassette.from_dict(json.load(cassette_file)) <NEW_LINE> <DEDENT> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> if e.errno != errno.ENOENT: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> self.cassette = Cassette() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.recording = False <NEW_LINE> <DEDENT> <DEDENT> @inlineCallbacks <NEW_LINE> def request(self, method, uri, headers=None, bodyProducer=None): <NEW_LINE> <INDENT> if not self.recording: <NEW_LINE> <INDENT> response = yield self.replay_request( method, uri, headers, bodyProducer) <NEW_LINE> returnValue(response) <NEW_LINE> <DEDENT> if bodyProducer is not None: <NEW_LINE> <INDENT> bodyProducer = RecordingBodyProducer(bodyProducer) <NEW_LINE> <DEDENT> real_response = yield self.agent.request( method, uri, headers, bodyProducer) <NEW_LINE> response = RecordingResponse(real_response) <NEW_LINE> self.cassette.responses.append(response) <NEW_LINE> returnValue(IsolatingResponse(response)) <NEW_LINE> <DEDENT> def replay_request(self, method, uri, headers=None, bodyProducer=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self.cassette[self.index] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise IOError('no more saved interactions for current {} ' 'request for {}'.format(method, uri)) <NEW_LINE> <DEDENT> self.index += 1 <NEW_LINE> if not (method == response.request.method and uri == response.request.absoluteURI): <NEW_LINE> <INDENT> raise IOError( 'current {} request for {} differs from saved {} ' 'request for {}'.format(method, uri, response.request.method, response.request.absoluteURI)) <NEW_LINE> <DEDENT> return succeed(response) <NEW_LINE> <DEDENT> def save(self, deferred_result=None): <NEW_LINE> <INDENT> if self.recording: <NEW_LINE> <INDENT> with open(self.cassette_path, 'w') as cassette_file: <NEW_LINE> <INDENT> dct = self.cassette.as_dict(self.preserve_exact_body_bytes) <NEW_LINE> json.dump(dct, cassette_file) <NEW_LINE> <DEDENT> <DEDENT> return deferred_result
A Twisted Web `Agent` that reconstructs a `Response` object from a recorded HTTP response in JSON-serialized VCR cassette format, or records a new cassette if none exists.
6259904615baa723494632e0
class CompanyFactory(factory.django.DjangoModelFactory): <NEW_LINE> <INDENT> company_name = factory.Faker("name") <NEW_LINE> fantasy_name = factory.Faker("name") <NEW_LINE> state = uf(n=1)[0] <NEW_LINE> cnpj = cnpj(formatting=True) <NEW_LINE> user_created = factory.SubFactory(UserFactory) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = "companies.Company"
Generates an new Company object for testing purposes.
6259904610dbd63aa1c71f29
class InstanceTypeFilteringTest(test.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(InstanceTypeFilteringTest, self).setUp() <NEW_LINE> self.context = context.get_admin_context() <NEW_LINE> <DEDENT> def assertFilterResults(self, filters, expected): <NEW_LINE> <INDENT> inst_types = objects.FlavorList.get_all( self.context, filters=filters) <NEW_LINE> inst_names = [i.name for i in inst_types] <NEW_LINE> self.assertEqual(inst_names, expected) <NEW_LINE> <DEDENT> def test_no_filters(self): <NEW_LINE> <INDENT> filters = None <NEW_LINE> expected = ['m1.tiny', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge'] <NEW_LINE> self.assertFilterResults(filters, expected) <NEW_LINE> <DEDENT> def test_min_memory_mb_filter(self): <NEW_LINE> <INDENT> filters = dict(min_memory_mb=513) <NEW_LINE> expected = ['m1.small', 'm1.medium', 'm1.large', 'm1.xlarge'] <NEW_LINE> self.assertFilterResults(filters, expected) <NEW_LINE> <DEDENT> def test_min_root_gb_filter(self): <NEW_LINE> <INDENT> filters = dict(min_root_gb=80) <NEW_LINE> expected = ['m1.large', 'm1.xlarge'] <NEW_LINE> self.assertFilterResults(filters, expected) <NEW_LINE> <DEDENT> def test_min_memory_mb_AND_root_gb_filter(self): <NEW_LINE> <INDENT> filters = dict(min_memory_mb=16384, min_root_gb=80) <NEW_LINE> expected = ['m1.xlarge'] <NEW_LINE> self.assertFilterResults(filters, expected)
Test cases for the filter option available for instance_type_get_all.
625990468da39b475be0453e
class CircularBeam(Beam): <NEW_LINE> <INDENT> def __init__(self, studyId, groupName, groupGeomObj, parameters, name = Beam.DEFAULT_NAME, color = None): <NEW_LINE> <INDENT> if color is None: <NEW_LINE> <INDENT> if parameters.has_key("R1"): <NEW_LINE> <INDENT> color = LIGHT_RED <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> color = RED <NEW_LINE> <DEDENT> <DEDENT> Beam.__init__(self, studyId, groupName, groupGeomObj, parameters, name, color) <NEW_LINE> self.R1 = self._getParameter(["R1", "R"]) <NEW_LINE> self.R2 = self._getParameter(["R2", "R"]) <NEW_LINE> self.EP1 = self._getParameter(["EP1", "EP"]) <NEW_LINE> self.EP2 = self._getParameter(["EP2", "EP"]) <NEW_LINE> if self.EP1 is None or self.EP2 is None or self.EP1 == 0 or self.EP2 == 0: <NEW_LINE> <INDENT> self.filling = FULL <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.filling = HOLLOW <NEW_LINE> <DEDENT> logger.debug(repr(self)) <NEW_LINE> self._checkSize(self.R1, MIN_DIM_FOR_EXTRUDED_SHAPE / 2.0, self._getParamUserName("R1")) <NEW_LINE> self._checkSize(self.R2, MIN_DIM_FOR_EXTRUDED_SHAPE / 2.0, self._getParamUserName("R2")) <NEW_LINE> if self.filling == HOLLOW: <NEW_LINE> <INDENT> self._checkSize(self.EP1, MIN_THICKNESS, self._getParamUserName("EP1")) <NEW_LINE> self._checkSize(self.EP2, MIN_THICKNESS, self._getParamUserName("EP2")) <NEW_LINE> self._checkSize(self.R1 - self.EP1, MIN_DIM_FOR_EXTRUDED_SHAPE / 2.0, "%s - %s" % (self._getParamUserName("R1"), self._getParamUserName("EP1"))) <NEW_LINE> self._checkSize(self.R2 - self.EP2, MIN_DIM_FOR_EXTRUDED_SHAPE / 2.0, "%s - %s" % (self._getParamUserName("R2"), self._getParamUserName("EP2"))) <NEW_LINE> <DEDENT> <DEDENT> def _makeSectionWires(self, fPoint, fNormal, lPoint, lNormal): <NEW_LINE> <INDENT> outerCircle1 = self.geom.MakeCircle(fPoint, fNormal, self.R1) <NEW_LINE> outerCircle2 = self.geom.MakeCircle(lPoint, lNormal, self.R2) <NEW_LINE> if self.filling == HOLLOW: <NEW_LINE> <INDENT> innerCircle1 = self.geom.MakeCircle(fPoint, fNormal, self.R1 - self.EP1) <NEW_LINE> innerCircle2 = self.geom.MakeCircle(lPoint, lNormal, self.R2 - self.EP2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> innerCircle1 = None <NEW_LINE> innerCircle2 = None <NEW_LINE> <DEDENT> return (outerCircle1, innerCircle1, outerCircle2, innerCircle2)
This class defines a beam with a circular section. It can be full or hollow, and its radius and thickness can vary from one end of the beam to the other. The valid parameters for circular beams are: * "R1" or "R": radius at the first end of the beam. * "R2" or "R": radius at the other end of the beam. * "EP1" or "EP" (optional): thickness at the first end of the beam. If not specified or equal to 0, the beam is considered full. * "EP2" or "EP" (optional): thickness at the other end of the beam. If not specified or equal to 0, the beam is considered full. See class :class:`StructuralElementPart` for the description of the other parameters.
6259904673bcbd0ca4bcb5db
class SingletonMixin(object): <NEW_LINE> <INDENT> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> lock = None <NEW_LINE> if not hasattr(cls, '_singleton_instances'): <NEW_LINE> <INDENT> lock = threading.Lock() <NEW_LINE> with lock: <NEW_LINE> <INDENT> if not hasattr(cls, '_singleton_instances'): <NEW_LINE> <INDENT> cls._singleton_instances = {} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> key = str(hash(cls)) <NEW_LINE> if key not in cls._singleton_instances: <NEW_LINE> <INDENT> if lock is None: <NEW_LINE> <INDENT> lock = threading.Lock() <NEW_LINE> <DEDENT> with lock: <NEW_LINE> <INDENT> if key not in cls._singleton_instances: <NEW_LINE> <INDENT> cls._singleton_instances[key] = super(SingletonMixin, cls) .__new__(cls, *args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return cls._singleton_instances[key]
Provides a singleton of an object per thread. Usage: class ObjectYouWantSingletoned(SingletonMixin): # implementation instance = ObjectYouWantSingletoned()
62599046b5575c28eb713670
class ConfabFileSystemLoader(FileSystemLoader): <NEW_LINE> <INDENT> def get_source(self, environment, template): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(ConfabFileSystemLoader, self).get_source(environment, template) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for searchpath in self.searchpath: <NEW_LINE> <INDENT> filename = join(searchpath, template) <NEW_LINE> if exists(filename): <NEW_LINE> <INDENT> return "", filename, True <NEW_LINE> <DEDENT> <DEDENT> raise TemplateNotFound(template)
Adds support for binary templates when loading an environment from the file system. Binary config files cannot be loaded as Jinja templates by default, but since confab's model is built around Jinja environments we need to make sure we can still represent them as jinja Templates. Since confab only renders templates from text config files (see :py:meth:`confab.conffiles.Conffile.generate` and :py:meth:`confab.options.should_render`) we can workaround this by returning a dummy template for binary config files with the appropriate metadata. When generating the configuration, confab, instead of rendering the template, will just copy the template file (the binary config file) verbatim to the generated folder.
6259904616aa5153ce40183c
class InputObjectDependencyAttribute(Attribute): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def __new__(self, Type): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Type = property(lambda self: object(), lambda self, v: None, lambda self: None)
InputObjectDependencyAttribute(Type: InputObjectDependency) InputObjectDependencyAttribute(Type: int)
6259904607f4c71912bb0781
class CertificateItem(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'attributes': {'key': 'attributes', 'type': 'CertificateAttributes'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'x509_thumbprint': {'key': 'x5t', 'type': 'base64'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, attributes: Optional["CertificateAttributes"] = None, tags: Optional[Dict[str, str]] = None, x509_thumbprint: Optional[bytes] = None, **kwargs ): <NEW_LINE> <INDENT> super(CertificateItem, self).__init__(**kwargs) <NEW_LINE> self.id = id <NEW_LINE> self.attributes = attributes <NEW_LINE> self.tags = tags <NEW_LINE> self.x509_thumbprint = x509_thumbprint
The certificate item containing certificate metadata. :param id: Certificate identifier. :type id: str :param attributes: The certificate management attributes. :type attributes: ~azure.keyvault.v7_3_preview.models.CertificateAttributes :param tags: A set of tags. Application specific metadata in the form of key-value pairs. :type tags: dict[str, str] :param x509_thumbprint: Thumbprint of the certificate. :type x509_thumbprint: bytes
62599046d99f1b3c44d069ee
class GoodBroyden(QuasiNewton): <NEW_LINE> <INDENT> def update_hessian(self, x_next, x_k): <NEW_LINE> <INDENT> delta_k = x_next - x_k <NEW_LINE> gamma_k = self.gradient(x_next) - self.gradient(x_k) <NEW_LINE> H_km1 = self.inverted_hessian <NEW_LINE> u = H_km1@delta_k <NEW_LINE> nominator = (delta_k - H_km1@delta_k) @ u.T <NEW_LINE> denominator = u.T @ gamma_k <NEW_LINE> H_k = H_km1 + nominator/denominator <NEW_LINE> self.inverted_hessian = H_k
Uses simple Broyden rank-1 update of the Hessian G and applies Sherman-Morisson's formula, see sections 3.15-3.17
6259904629b78933be26aa6a
class HOConv2d(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_shape, out_channel, kernel_size=(3, 2, 2), **kwargs): <NEW_LINE> <INDENT> super(HOConv2d, self).__init__() <NEW_LINE> self.regressor = KernelRegressor(input_shape, out_channel, kernel_size) <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> kernels = self.regressor(input) <NEW_LINE> return conv2d_iwk(input, kernels, **self.kwargs)
Higher order Conv2d, the convolution has no parameters, the kernel are computed by a neural net
6259904623e79379d538d84d
class Kind(object): <NEW_LINE> <INDENT> MAPPING = None <NEW_LINE> SCALAR = None <NEW_LINE> SEQUENCE = None <NEW_LINE> _name = None <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._name
YAML raw object type.
62599046baa26c4b54d505f9
class AffineHypersurface(AlgebraicScheme_subscheme_affine): <NEW_LINE> <INDENT> def __init__(self, poly, ambient=None): <NEW_LINE> <INDENT> if not is_MPolynomial(poly): <NEW_LINE> <INDENT> raise TypeError("Defining polynomial (= %s) must be a multivariate polynomial"%poly) <NEW_LINE> <DEDENT> if ambient is None: <NEW_LINE> <INDENT> R = poly.parent() <NEW_LINE> from sage.schemes.affine.affine_space import AffineSpace <NEW_LINE> ambient = AffineSpace(R.base_ring(), R.ngens()) <NEW_LINE> ambient._coordinate_ring = R <NEW_LINE> <DEDENT> AlgebraicScheme_subscheme_affine.__init__(self, ambient, [poly]) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Affine hypersurface defined by %s in %s"%( self.defining_polynomial(), self.ambient_space()) <NEW_LINE> <DEDENT> def defining_polynomial(self): <NEW_LINE> <INDENT> return self.defining_polynomials()[0]
The affine hypersurface defined by the given polynomial. EXAMPLES:: sage: A.<x, y, z> = AffineSpace(ZZ, 3) sage: AffineHypersurface(x*y-z^3, A) Affine hypersurface defined by -z^3 + x*y in Affine Space of dimension 3 over Integer Ring :: sage: A.<x, y, z> = QQ[] sage: AffineHypersurface(x*y-z^3) Affine hypersurface defined by -z^3 + x*y in Affine Space of dimension 3 over Rational Field
625990461d351010ab8f4e6a
class Database(collections.MutableMapping): <NEW_LINE> <INDENT> def __init__(self, top_source_dir, top_build_dir): <NEW_LINE> <INDENT> self.top_source_dir = top_source_dir <NEW_LINE> self.top_build_dir = top_build_dir <NEW_LINE> self.board = None <NEW_LINE> self.genimage = None <NEW_LINE> self.kernel = None <NEW_LINE> self.uboot = None <NEW_LINE> self.toolchain = None <NEW_LINE> <DEDENT> def use_genimage(self): <NEW_LINE> <INDENT> self.genimage = { 'path': os.path.join(self.top_build_dir, 'genimage_sources'), 'build_dir': os.path.join(self.top_build_dir, 'build_genimage'), 'output_path': os.path.join(self.top_build_dir, 'images'), 'input_path': os.path.join(self.top_build_dir, 'genimage-input'), 'root_path': os.path.join(self.top_build_dir, '.genimage-root'), 'tmp_path': os.path.join(self.top_build_dir, '.genimage-tmp'), 'config': os.path.join(self.top_build_dir, 'genimage.cfg'), } <NEW_LINE> <DEDENT> def set_kernel(self, kernel, kernel_config): <NEW_LINE> <INDENT> self.kernel = kernel <NEW_LINE> self.kernel.config = kernel_config <NEW_LINE> if self.toolchain.local: <NEW_LINE> <INDENT> self.kernel.set_arch(utils.get_arch()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.kernel.toolchain = self.toolchain <NEW_LINE> self.kernel.set_arch(self.toolchain.arch) <NEW_LINE> <DEDENT> <DEDENT> def set_uboot(self, uboot, uboot_config): <NEW_LINE> <INDENT> self.uboot = uboot <NEW_LINE> self.uboot.config = uboot_config <NEW_LINE> if not self.toolchain.local: <NEW_LINE> <INDENT> self.uboot.toolchain = self.toolchain <NEW_LINE> <DEDENT> <DEDENT> def set_toolchain(self, toolchain): <NEW_LINE> <INDENT> self.toolchain = toolchain <NEW_LINE> <DEDENT> def set_xen(self, xen, xen_config): <NEW_LINE> <INDENT> self.xen = xen <NEW_LINE> self.xen.config = xen_config <NEW_LINE> self.xen.host = os.path.basename(self.toolchain.prefix) <NEW_LINE> if not self.toolchain.local: <NEW_LINE> <INDENT> self.xen.toolchain = self.toolchain <NEW_LINE> <DEDENT> <DEDENT> def set_board(self, board): <NEW_LINE> <INDENT> self.board = board <NEW_LINE> self.set_toolchain(board.toolchain) <NEW_LINE> self.use_genimage() <NEW_LINE> self.set_kernel(board.kernel, board.kernel_config) <NEW_LINE> if not board.vm: <NEW_LINE> <INDENT> self.set_uboot(board.uboot, board.uboot_config) <NEW_LINE> <DEDENT> if board.xen: <NEW_LINE> <INDENT> self.set_xen(board.xen, board.xen_config) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, attr): <NEW_LINE> <INDENT> return getattr(self, attr) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(vars(self)) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for item in vars(self).keys(): <NEW_LINE> <INDENT> yield item
The Database class holds the SBXG configuration. It is an aggregation of data models and can be accessed in the same fashion than a dictionary. This allows this class to be passed directly to the jinja templating engine flawlessly.
625990460fa83653e46f622c
class Mod349PartnerRecord(orm.Model): <NEW_LINE> <INDENT> _name = 'l10n.es.aeat.mod349.partner_record' <NEW_LINE> _description = 'AEAT 349 Model - Partner record' <NEW_LINE> _order = 'operation_key asc' <NEW_LINE> def get_record_name(self, cr, uid, ids, field_name, args, context=None): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for rec in self.browse(cr, uid, ids, context=context): <NEW_LINE> <INDENT> result[rec.id] = rec.partner_vat <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def _check_partner_record_line(self, cr, uid, ids, name, args, context=None): <NEW_LINE> <INDENT> res = {} <NEW_LINE> for item in self.browse(cr, uid, ids, context=context): <NEW_LINE> <INDENT> res[item.id] = bool(item.partner_vat and item.country_id and item.total_operation_amount) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def onchange_format_partner_vat(self, cr, uid, ids, partner_vat, country_id, context=None): <NEW_LINE> <INDENT> if country_id: <NEW_LINE> <INDENT> country_obj = self.pool['res.country'] <NEW_LINE> country = country_obj.browse(cr, uid, country_id, context=context) <NEW_LINE> partner_vat = _format_partner_vat(cr, uid, partner_vat=partner_vat, country=country) <NEW_LINE> <DEDENT> return {'value': {'partner_vat': partner_vat}} <NEW_LINE> <DEDENT> _columns = { 'report_id': fields.many2one('l10n.es.aeat.mod349.report', 'AEAT 349 Report ID'), 'name': fields.function(get_record_name, method=True, type="char", size="64", string="Name"), 'partner_id': fields.many2one('res.partner', 'Partner', required=True), 'partner_vat': fields.char('VAT', size=15, select=1), 'country_id': fields.many2one('res.country', 'Country'), 'operation_key': fields.selection(OPERATION_KEYS, 'Operation key', required=True), 'total_operation_amount': fields.float('Total operation amount'), 'partner_record_ok': fields.function( _check_partner_record_line, method=True, string='Partner Record OK', help='Checked if partner record is OK'), 'record_detail_ids': fields.one2many( 'l10n.es.aeat.mod349.partner_record_detail', 'partner_record_id', 'Partner record detail IDS', ondelete='cascade'), }
AEAT 349 Model - Partner record Shows total amount per operation key (grouped) for each partner
6259904607d97122c4217ff1
class TableDoesNotExistException(Exception): <NEW_LINE> <INDENT> pass
Raise this exception when google fusiontables table does not exist.
6259904607d97122c4217ff2
class Algorithm(enum.IntEnum): <NEW_LINE> <INDENT> XCP_ADD_11 = 1 <NEW_LINE> XCP_ADD_12 = 2 <NEW_LINE> XCP_ADD_14 = 3 <NEW_LINE> XCP_ADD_22 = 4 <NEW_LINE> XCP_ADD_24 = 5 <NEW_LINE> XCP_ADD_44 = 6 <NEW_LINE> XCP_CRC_16 = 7 <NEW_LINE> XCP_CRC_16_CITT = 8 <NEW_LINE> XCP_CRC_32 = 9 <NEW_LINE> XCP_USER_DEFINED = 10
Enumerates available checksum algorithms
625990468da39b475be04540
class CategoryLink(pages_models.Page): <NEW_LINE> <INDENT> blog_category = models.ForeignKey(blog_models.BlogCategory) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('Category link') <NEW_LINE> verbose_name_plural = _('Category links') <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> cat_slug = self.blog_category.slug <NEW_LINE> rev_url = reverse('blog_post_list_category', args=(cat_slug,)) <NEW_LINE> return rev_url.strip('/') <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.slug = urlunquote(self.get_absolute_url()) <NEW_LINE> return super(CategoryLink, self).save(*args, **kwargs)
Link to blog category
6259904607f4c71912bb0783
class UnderlayConnectivity(Case): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(UnderlayConnectivity, self).__init__() <NEW_LINE> <DEDENT> def test_connectivity(self, nodes_src, nodes_dst): <NEW_LINE> <INDENT> for src in nodes_src: <NEW_LINE> <INDENT> for dst in nodes_dst: <NEW_LINE> <INDENT> if not src.is_reachable(dst): <NEW_LINE> <INDENT> self.fail_msg.append('Node %s cannot reach %s' % (src.ip, dst.ip)) <NEW_LINE> warn('node %s cannot reach %s' % (src.ip, dst.ip)) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def run_case(self, stack): <NEW_LINE> <INDENT> control_nodes = stack.get_control_nodes() <NEW_LINE> network_nodes = stack.get_network_nodes() <NEW_LINE> compute_nodes = stack.get_computer_nodes() <NEW_LINE> self.result = self.test_connectivity(control_nodes, compute_nodes) and self.test_connectivity(network_nodes, compute_nodes) and self.test_connectivity(control_nodes, network_nodes) <NEW_LINE> super(UnderlayConnectivity, self).run_case(module_name='Underlay ' 'Connectivity')
UnderlayConnectivity : the case to detect underlay connectivity problem.
62599046711fe17d825e1646
class OptionGroup(JsonObject): <NEW_LINE> <INDENT> attributes = {} <NEW_LINE> label_max_length = 75 <NEW_LINE> options_max_length = 100 <NEW_LINE> logger = logging.getLogger(__name__) <NEW_LINE> def __init__( self, *, label: Optional[Union[str, dict, TextObject]] = None, options: Sequence[Union[dict, Option]], **others: dict, ): <NEW_LINE> <INDENT> self._label: Optional[TextObject] = TextObject.parse( label, default_type=PlainTextObject.type ) <NEW_LINE> self.label: Optional[str] = self._label.text if self._label else None <NEW_LINE> self.options = Option.parse_all(options) <NEW_LINE> show_unknown_key_warning(self, others) <NEW_LINE> <DEDENT> @JsonValidator(f"label attribute cannot exceed {label_max_length} characters") <NEW_LINE> def _validate_label_length(self): <NEW_LINE> <INDENT> return self.label is None or len(self.label) <= self.label_max_length <NEW_LINE> <DEDENT> @JsonValidator(f"options attribute cannot exceed {options_max_length} elements") <NEW_LINE> def _validate_options_length(self): <NEW_LINE> <INDENT> return self.options is None or len(self.options) <= self.options_max_length <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse_all( cls, option_groups: Optional[Sequence[Union[dict, "OptionGroup"]]] ) -> Optional[List["OptionGroup"]]: <NEW_LINE> <INDENT> if option_groups is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> option_group_objects = [] <NEW_LINE> for o in option_groups: <NEW_LINE> <INDENT> if isinstance(o, dict): <NEW_LINE> <INDENT> d = copy.copy(o) <NEW_LINE> option_group_objects.append(OptionGroup(**d)) <NEW_LINE> <DEDENT> elif isinstance(o, OptionGroup): <NEW_LINE> <INDENT> option_group_objects.append(o) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cls.logger.warning( f"Unknown option group object detected and skipped ({o})" ) <NEW_LINE> <DEDENT> <DEDENT> return option_group_objects <NEW_LINE> <DEDENT> def to_dict(self, option_type: str = "block") -> dict: <NEW_LINE> <INDENT> self.validate_json() <NEW_LINE> dict_options = [o.to_dict(option_type) for o in self.options] <NEW_LINE> if option_type == "dialog": <NEW_LINE> <INDENT> return { "label": self.label, "options": dict_options, } <NEW_LINE> <DEDENT> elif option_type == "action": <NEW_LINE> <INDENT> return { "text": self.label, "options": dict_options, } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dict_label: dict = self._label.to_dict() <NEW_LINE> return { "label": dict_label, "options": dict_options, }
JSON must be retrieved with an explicit option_type - the Slack API has different required formats in different situations
6259904623e79379d538d84f
class RHChangeEventType(RHManageEventBase): <NEW_LINE> <INDENT> def _process(self): <NEW_LINE> <INDENT> type_ = EventType[request.form['type']] <NEW_LINE> update_event_type(self.event, type_) <NEW_LINE> flash(_('The event type has been changed to {}.').format(type_.title), 'success') <NEW_LINE> return jsonify_data(flash=False, redirect=url_for('.settings', self.event))
Change the type of an event.
6259904676d4e153a661dc1e
class DisplayException(Exception): <NEW_LINE> <INDENT> pass
Base exception for all rich output-related exceptions. EXAMPLES:: sage: from sage.repl.rich_output.display_manager import DisplayException sage: raise DisplayException('foo') Traceback (most recent call last): ... DisplayException: foo
625990468a43f66fc4bf34e6
class Invitacion(BaseModel): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> id_arquero = db.Column(db.Integer, db.ForeignKey('arquero.id'), nullable=False) <NEW_LINE> codigo = db.Column(db.String(10), nullable=False, unique=True) <NEW_LINE> usada = db.Column(db.Boolean, nullable=False, default=False)
Como los arqueros normalmente solo se pueden registrar mediante una invitacion, esto registra a todas las personas a quienes se les envio una invitacion. :param int id: un identificador autogenerado. :param int id_arquero: el identificador del arquero a quien se le envio el email para que se cree una cuenta. :param str codigo: un codigo de la invitacion. Esto es un campo interno para asegurarse de quienes se le hayan enviado una invitacion puedan crear su usuario. :param boolean usada: si es True, entonces la misma ya fue usada y no se la puede usar para crear a otro usuario.
6259904673bcbd0ca4bcb5de
class CeleryMockMixin(): <NEW_LINE> <INDENT> def mock_celery(self): <NEW_LINE> <INDENT> self._celery_patcher = patch('absortium.celery.base.DBTask', new=DBTask) <NEW_LINE> self.mock_dbtask = self._celery_patcher.start() <NEW_LINE> <DEDENT> def unmock_celery(self): <NEW_LINE> <INDENT> self._celery_patcher.stop()
CeleryMockMixin substitute original DBTask in order to close db connections
625990468e71fb1e983bce21
class SignUp(CreateView): <NEW_LINE> <INDENT> model = User <NEW_LINE> template_name = "sign_up.html" <NEW_LINE> form_class = SignUpForm <NEW_LINE> success_url = "/index/"
Страница регистрации
62599046d10714528d69f036
class Revision(object): <NEW_LINE> <INDENT> CACHE_KEY = 'pootle:revision' <NEW_LINE> INITIAL = 0 <NEW_LINE> @classmethod <NEW_LINE> def initialize(cls, force=False): <NEW_LINE> <INDENT> if force: <NEW_LINE> <INDENT> return cls.set(cls.INITIAL) <NEW_LINE> <DEDENT> return cls.add(cls.INITIAL) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get(cls): <NEW_LINE> <INDENT> return cache.get(cls.CACHE_KEY) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def set(cls, value): <NEW_LINE> <INDENT> return cache.set(cls.CACHE_KEY, value) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add(cls, value): <NEW_LINE> <INDENT> return cache.add(cls.CACHE_KEY, value) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def incr(cls): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return cache.incr(cls.CACHE_KEY) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise NoRevision()
Wrapper around the revision counter stored in Redis.
62599046435de62698e9d157
class TextDialog(Dialog): <NEW_LINE> <INDENT> def __init__(self, parent, *args, **kwargs): <NEW_LINE> <INDENT> super(TextDialog, self).__init__(parent, *args, **kwargs) <NEW_LINE> self._validateFunction = None <NEW_LINE> self.setMainWidget(QLineEdit()) <NEW_LINE> self.lineEdit().setFocus() <NEW_LINE> <DEDENT> def lineEdit(self): <NEW_LINE> <INDENT> return self.mainWidget() <NEW_LINE> <DEDENT> def setText(self, text): <NEW_LINE> <INDENT> self.lineEdit().setText(text) <NEW_LINE> <DEDENT> def text(self): <NEW_LINE> <INDENT> return self.lineEdit().text() <NEW_LINE> <DEDENT> def setValidateFunction(self, func): <NEW_LINE> <INDENT> old = self._validateFunction <NEW_LINE> self._validateFunction = func <NEW_LINE> if func: <NEW_LINE> <INDENT> self._validate(self.lineEdit().text()) <NEW_LINE> if not old: <NEW_LINE> <INDENT> self.lineEdit().textChanged.connect(self._validate) <NEW_LINE> <DEDENT> <DEDENT> elif old: <NEW_LINE> <INDENT> self.lineEdit().textChanged.disconnect(self._validate) <NEW_LINE> self.button('ok').setEnabled(True) <NEW_LINE> <DEDENT> <DEDENT> def setValidateRegExp(self, regexp): <NEW_LINE> <INDENT> validator = function = None <NEW_LINE> if regexp is not None: <NEW_LINE> <INDENT> rx = QRegExp(regexp) <NEW_LINE> validator = QRegExpValidator(rx, self.lineEdit()) <NEW_LINE> function = rx.exactMatch <NEW_LINE> <DEDENT> self.lineEdit().setValidator(validator) <NEW_LINE> self.setValidateFunction(function) <NEW_LINE> <DEDENT> def _validate(self, text): <NEW_LINE> <INDENT> self.button('ok').setEnabled(self._validateFunction(text))
A dialog with text string input and validation.
6259904663b5f9789fe864bf
class VectorSchema(object): <NEW_LINE> <INDENT> swagger_types = { 'x': 'float', 'y': 'float', 'z': 'float' } <NEW_LINE> attribute_map = { 'x': 'x', 'y': 'y', 'z': 'z' } <NEW_LINE> def __init__(self, x=None, y=None, z=None): <NEW_LINE> <INDENT> self._x = None <NEW_LINE> self._y = None <NEW_LINE> self._z = None <NEW_LINE> self.discriminator = None <NEW_LINE> if x is not None: <NEW_LINE> <INDENT> self.x = x <NEW_LINE> <DEDENT> if y is not None: <NEW_LINE> <INDENT> self.y = y <NEW_LINE> <DEDENT> if z is not None: <NEW_LINE> <INDENT> self.z = z <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def x(self): <NEW_LINE> <INDENT> return self._x <NEW_LINE> <DEDENT> @x.setter <NEW_LINE> def x(self, x): <NEW_LINE> <INDENT> self._x = x <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> return self._y <NEW_LINE> <DEDENT> @y.setter <NEW_LINE> def y(self, y): <NEW_LINE> <INDENT> self._y = y <NEW_LINE> <DEDENT> @property <NEW_LINE> def z(self): <NEW_LINE> <INDENT> return self._z <NEW_LINE> <DEDENT> @z.setter <NEW_LINE> def z(self, z): <NEW_LINE> <INDENT> self._z = z <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, VectorSchema): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259904694891a1f408ba09f
class Action12(Action): <NEW_LINE> <INDENT> def execute(self, instance): <NEW_LINE> <INDENT> raise NotImplementedError('%s not implemented' % ( self.__class__.__name__))
On Draw Changes->Set X Offset... Parameters: 0: Enter X Offset (EXPRESSION, ExpressionParameter)
625990464e696a045264e7ca
class Hub(object): <NEW_LINE> <INDENT> def __init__(self, ip: str, secret: str, main_light: int, lights: list): <NEW_LINE> <INDENT> self.last_changed = datetime.datetime.now(); <NEW_LINE> self.ip = ip <NEW_LINE> self.secret = secret <NEW_LINE> self.lights_selected = lights <NEW_LINE> self.main_light = main_light
Generic hub class
62599046711fe17d825e1647
class DescribeDailyCallDurationRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(DescribeDailyCallDurationRequest, self).__init__( '/describeDailyCallDuration', 'GET', header, version) <NEW_LINE> self.parameters = parameters
获取近7天通讯时长
6259904615baa723494632e5
class DNSServer(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._check_localhost() <NEW_LINE> self._requests = [] <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> try: <NEW_LINE> <INDENT> self._socket = socket._orig_socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> <DEDENT> self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> self._socket.bind(("", 53)) <NEW_LINE> self._running = False <NEW_LINE> self._initialized = False <NEW_LINE> <DEDENT> def _check_localhost(self): <NEW_LINE> <INDENT> response = b"" <NEW_LINE> try: <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> s.connect(("", 53)) <NEW_LINE> s.send(binascii.unhexlify("6509012000010000000000010377777706676f6f676c6503636f6d00000100010000291000000000000000")) <NEW_LINE> response = s.recv(512) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if response and b"google" in response: <NEW_LINE> <INDENT> raise socket.error("another DNS service already running on '0.0.0.0:53'") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def pop(self, prefix=None, suffix=None): <NEW_LINE> <INDENT> retVal = None <NEW_LINE> if prefix and hasattr(prefix, "encode"): <NEW_LINE> <INDENT> prefix = prefix.encode() <NEW_LINE> <DEDENT> if suffix and hasattr(suffix, "encode"): <NEW_LINE> <INDENT> suffix = suffix.encode() <NEW_LINE> <DEDENT> with self._lock: <NEW_LINE> <INDENT> for _ in self._requests: <NEW_LINE> <INDENT> if prefix is None and suffix is None or re.search(b"%s\\..+\\.%s" % (prefix, suffix), _, re.I): <NEW_LINE> <INDENT> self._requests.remove(_) <NEW_LINE> retVal = _.decode() <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return retVal <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> def _(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._running = True <NEW_LINE> self._initialized = True <NEW_LINE> while True: <NEW_LINE> <INDENT> data, addr = self._socket.recvfrom(1024) <NEW_LINE> _ = DNSQuery(data) <NEW_LINE> self._socket.sendto(_.response("127.0.0.1"), addr) <NEW_LINE> with self._lock: <NEW_LINE> <INDENT> self._requests.append(_._query) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._running = False <NEW_LINE> <DEDENT> <DEDENT> thread = threading.Thread(target=_) <NEW_LINE> thread.daemon = True <NEW_LINE> thread.start()
Used for making fake DNS resolution responses based on received raw request Reference(s): http://code.activestate.com/recipes/491264-mini-fake-dns-server/ https://code.google.com/p/marlon-tools/source/browse/tools/dnsproxy/dnsproxy.py
62599046498bea3a75a58e72
class AddCoords(tf.keras.layers.Layer): <NEW_LINE> <INDENT> def __init__(self, with_r=False): <NEW_LINE> <INDENT> super(AddCoords, self).__init__() <NEW_LINE> self.with_r = with_r <NEW_LINE> <DEDENT> def call(self, input_tensor): <NEW_LINE> <INDENT> batch_size_tensor, x_dim, y_dim = tf.shape(input_tensor)[:3] <NEW_LINE> xx_channel = tf.range(y_dim, dtype=tf.float32) <NEW_LINE> xx_channel = tf.expand_dims(xx_channel, 0) <NEW_LINE> xx_channel = tf.expand_dims(xx_channel, 0) <NEW_LINE> xx_channel = tf.tile(xx_channel, [batch_size_tensor, x_dim, 1]) <NEW_LINE> xx_channel = tf.expand_dims(xx_channel, -1) <NEW_LINE> yy_channel = tf.range(x_dim, dtype=tf.float32) <NEW_LINE> yy_channel = tf.expand_dims(yy_channel, 0) <NEW_LINE> yy_channel = tf.expand_dims(yy_channel, -1) <NEW_LINE> yy_channel = tf.tile(yy_channel, [batch_size_tensor, 1, y_dim]) <NEW_LINE> yy_channel = tf.expand_dims(yy_channel, -1) <NEW_LINE> xx_channel = 2 * xx_channel / (tf.cast(x_dim, dtype=tf.float32) - 1) - 1 <NEW_LINE> yy_channel = 2 * yy_channel / (tf.cast(y_dim, dtype=tf.float32) - 1) - 1 <NEW_LINE> ret = tf.concat([input_tensor, xx_channel, yy_channel], axis=-1) <NEW_LINE> if self.with_r: <NEW_LINE> <INDENT> rr = tf.math.sqrt(tf.square(xx_channel) + tf.square(yy_channel)) <NEW_LINE> ret = tf.concat([ret, rr], axis=-1) <NEW_LINE> <DEDENT> return ret
Add Coord to tensor Alternate implementation, use tf.tile instead of tf.matmul, and x_dim, y_dim is got directly from input_tensor
62599046dc8b845886d5490e
class RootIterator(object): <NEW_LINE> <INDENT> def __init__(self, o): <NEW_LINE> <INDENT> if hasattr(o,'Class') and o.Class().InheritsFrom('TIterator'): <NEW_LINE> <INDENT> self.iter = o <NEW_LINE> <DEDENT> elif hasattr(o,'createIterator'): <NEW_LINE> <INDENT> self.iter = o.createIterator() <NEW_LINE> <DEDENT> elif hasattr(o,'MakeIterator'): <NEW_LINE> <INDENT> self.iter = o.MakeIterator() <NEW_LINE> <DEDENT> elif hasattr(o,'componentIterator'): <NEW_LINE> <INDENT> self.iter = o.componentIterator() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.iter = None <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> n = self.iter.Next() <NEW_LINE> if n is None or not n: <NEW_LINE> <INDENT> raise StopIteration() <NEW_LINE> <DEDENT> return n
A wrapper around the ROOT iterator so that it can be used in python
625990460fa83653e46f6230
class HistogramPlot(StandardStyle): <NEW_LINE> <INDENT> def __init__(self, values): <NEW_LINE> <INDENT> StandardStyle.__init__(self) <NEW_LINE> self.values = values <NEW_LINE> self.parameters["num_bins"] = 30.0 <NEW_LINE> <DEDENT> def plot(self): <NEW_LINE> <INDENT> self.axis.hist(self.values,bins=self.num_bins,edgecolor='none') <NEW_LINE> self.y_label = '#'
This function plots the histogram of list of value lists, coloring each independently. Parameters ---------- values : list List of numpy arrays objects. The top level list corresponds to different sets of values that will be plotted together. Each set will be colored by the color on corresponding postion of the colors parameter. If None all colors will be set to '#848484' (gray). Other parameters ---------------- num_bins : int The with of the bins into which to bin the spikes. colors : list The colors to assign to the different sets of spikes.
6259904645492302aabfd826
class DBStoreWizardHandlerPlugin(FormWizardHandlerPlugin): <NEW_LINE> <INDENT> uid = UID <NEW_LINE> name = _("DB store") <NEW_LINE> allow_multiple = False <NEW_LINE> def run(self, form_wizard_entry, request, form_list, form_wizard, form_element_entries=None): <NEW_LINE> <INDENT> if not form_element_entries: <NEW_LINE> <INDENT> form_element_entries = get_form_element_entries_for_form_wizard_entry( form_wizard_entry ) <NEW_LINE> <DEDENT> field_name_to_label_map, cleaned_data = get_processed_form_wizard_data( form_wizard, form_list, form_element_entries ) <NEW_LINE> for key, value in cleaned_data.items(): <NEW_LINE> <INDENT> if isinstance(value, (datetime.datetime, datetime.date)): <NEW_LINE> <INDENT> cleaned_data[key] = value.isoformat() if hasattr(value, 'isoformat') else value <NEW_LINE> <DEDENT> <DEDENT> saved_form_wizard_data_entry = SavedFormWizardDataEntry( form_wizard_entry=form_wizard_entry, user=request.user if request.user and request.user.pk else None, form_data_headers=json.dumps( field_name_to_label_map, cls=DjangoJSONEncoder ), saved_data=json.dumps(cleaned_data, cls=DjangoJSONEncoder) ) <NEW_LINE> saved_form_wizard_data_entry.save() <NEW_LINE> <DEDENT> def custom_actions(self, form_wizard_entry, request=None): <NEW_LINE> <INDENT> widget = get_form_wizard_handler_plugin_widget( self.uid, request=request, as_instance=True ) <NEW_LINE> if widget: <NEW_LINE> <INDENT> view_entries_icon_class = widget.view_entries_icon_class <NEW_LINE> export_entries_icon_class = widget.export_entries_icon_class <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> view_entries_icon_class = 'glyphicon glyphicon-list' <NEW_LINE> export_entries_icon_class = 'glyphicon glyphicon-export' <NEW_LINE> <DEDENT> return ( ( reverse('fobi.contrib.plugins.form_handlers.db_store.' 'view_saved_form_wizard_data_entries', args=[form_wizard_entry.pk]), _("View entries"), view_entries_icon_class ), ( reverse('fobi.contrib.plugins.form_handlers.db_store.' 'export_saved_form_wizard_data_entries', args=[form_wizard_entry.pk]), _("Export entries"), export_entries_icon_class ), )
DB store form wizard handler plugin. Can be used only once per form.
6259904624f1403a92686277
class Invert(Query): <NEW_LINE> <INDENT> def __init__(self, subquery): <NEW_LINE> <INDENT> self.subquery = subquery <NEW_LINE> <DEDENT> def _execute_query(self, instance): <NEW_LINE> <INDENT> part = self.subquery._execute_query(instance) <NEW_LINE> return QueryResult(self, not part.result, [ part ] ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return u'~ %r' % self.subquery
Implementation of the invert operator
6259904694891a1f408ba0a0
class ExampleNameChooser(NameChooser): <NEW_LINE> <INDENT> def chooseName(self, name, obj): <NEW_LINE> <INDENT> self.checkName(unicode(self.context._count + 1), obj) <NEW_LINE> return unicode(self.context._count + 1)
A name chooser for example objects in the container context.
62599046711fe17d825e1648