code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ChiralTetrahedral(Tetrahedral): <NEW_LINE> <INDENT> index = 2 <NEW_LINE> order = 12 <NEW_LINE> mirrors = 1 <NEW_LINE> def fundamental_domain(self): <NEW_LINE> <INDENT> return self.chiral()
Chiral Tetrahedral symmetry This is the symmetry group used by Escher's 'Sphere with Fish' This group is an interesting one, for having a very large fundamental domain. This makes that the curvature of the sphere plays a large role in how the tiles fit together
62599050a219f33f346c7c97
class EmbeddingLayer(object): <NEW_LINE> <INDENT> def __init__(self, vocabulary_size, embedding_size, hidden_size, float_dtype, name): <NEW_LINE> <INDENT> self.vocabulary_size = vocabulary_size <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.float_dtype = float_dtype <NEW_LINE> self.name = name <NEW_LINE> self.embedding_table = tf.get_variable(name='embedding_table', shape=[vocabulary_size, embedding_size], dtype=float_dtype, initializer=glorot_uniform_initializer(), trainable=True) <NEW_LINE> self.projection_matrix = tf.transpose(self.embedding_table, name='vocab_projection_matrix') <NEW_LINE> <DEDENT> def embed(self, one_hot_inputs): <NEW_LINE> <INDENT> embeddings = tf.nn.embedding_lookup(self.embedding_table, one_hot_inputs) <NEW_LINE> embeddings *= tf.sqrt(tf.cast(self.hidden_size, self.float_dtype)) <NEW_LINE> return embeddings <NEW_LINE> <DEDENT> def project(self, dec_out): <NEW_LINE> <INDENT> projections = matmul_nd(dec_out, self.projection_matrix) <NEW_LINE> return projections <NEW_LINE> <DEDENT> def get_embedding_table(self): <NEW_LINE> <INDENT> return self.embedding_table <NEW_LINE> <DEDENT> def get_projection_matrix(self): <NEW_LINE> <INDENT> return self.projection_matrix <NEW_LINE> <DEDENT> def get_vocab_size(self): <NEW_LINE> <INDENT> return self.vocabulary_size
Looks up embeddings for the specified token sequence in the learned embedding table; allows for easy weight scaling and tying.
62599050d99f1b3c44d06b30
class ITaskTemplateFolderSchema(model.Schema): <NEW_LINE> <INDENT> model.fieldset( u'common', label=_(u'fieldset_common', default=u'Common'), fields=[u'sequence_type', 'text']) <NEW_LINE> directives.order_after(sequence_type='IOpenGeverBase.description') <NEW_LINE> sequence_type = schema.Choice( title=_(u'label_sequence_type', default='Type'), vocabulary=sequence_type_vocabulary, required=True, ) <NEW_LINE> directives.order_after(text='sequence_type') <NEW_LINE> text = schema.Text( title=_(u"label_text", default=u"Text"), description=_('help_tasktemplatefolder_text', default=u'Prefills the comment field of the main task'), required=False, )
Marker Schema for TaskTemplateFolder
62599050d6c5a102081e35b4
class TestLPS(unittest.TestCase): <NEW_LINE> <INDENT> def test_empty_string(self): <NEW_LINE> <INDENT> assert lps("") == 0 <NEW_LINE> <DEDENT> def test_single_char(self): <NEW_LINE> <INDENT> assert lps("a") == 1 <NEW_LINE> assert lps("k") == 1 <NEW_LINE> <DEDENT> def test_two_chars(self): <NEW_LINE> <INDENT> assert lps("aa") == 2 <NEW_LINE> assert lps("ab") == 1 <NEW_LINE> assert lps("gh") == 1 <NEW_LINE> assert lps("56") == 1 <NEW_LINE> assert lps("22") == 2 <NEW_LINE> <DEDENT> def test_substring_palindromes(self): <NEW_LINE> <INDENT> assert lps("nitin") == 5 <NEW_LINE> assert lps("Level") == 3 <NEW_LINE> assert lps("level") == 5 <NEW_LINE> assert lps("eve") == 3 <NEW_LINE> assert lps("titit") == 5 <NEW_LINE> assert lps("dsfsdfsameemas") == 8 <NEW_LINE> <DEDENT> def test_uncontinuous_strings(self): <NEW_LINE> <INDENT> assert lps("kauukaz") == 4 <NEW_LINE> assert lps("agbdba") == 5 <NEW_LINE> assert lps("dkjaklevelsdclevelshdkhdak") == 17
Test cases for lps function
625990508da39b475be0467b
class _basefilecache(scmutil.filecache): <NEW_LINE> <INDENT> def __get__(self, repo, type=None): <NEW_LINE> <INDENT> if repo is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> return super(_basefilecache, self).__get__(repo.unfiltered(), type) <NEW_LINE> <DEDENT> def __set__(self, repo, value): <NEW_LINE> <INDENT> return super(_basefilecache, self).__set__(repo.unfiltered(), value) <NEW_LINE> <DEDENT> def __delete__(self, repo): <NEW_LINE> <INDENT> return super(_basefilecache, self).__delete__(repo.unfiltered())
All filecache usage on repo are done for logic that should be unfiltered
62599050f7d966606f749300
class TableFileHandleResults(ModelNormal): <NEW_LINE> <INDENT> allowed_values = { } <NEW_LINE> validations = { } <NEW_LINE> additional_properties_type = None <NEW_LINE> _nullable = False <NEW_LINE> @cached_property <NEW_LINE> def openapi_types(): <NEW_LINE> <INDENT> lazy_import() <NEW_LINE> return { 'headers': ([SelectColumn],), 'rows': ([FileHandleResults],), 'table_id': (str,), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = { 'headers': 'headers', 'rows': 'rows', 'table_id': 'tableId', } <NEW_LINE> _composed_schemas = {} <NEW_LINE> required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) <NEW_LINE> @convert_js_args_to_python_args <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _check_type = kwargs.pop('_check_type', True) <NEW_LINE> _spec_property_naming = kwargs.pop('_spec_property_naming', False) <NEW_LINE> _path_to_item = kwargs.pop('_path_to_item', ()) <NEW_LINE> _configuration = kwargs.pop('_configuration', None) <NEW_LINE> _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) <NEW_LINE> if args: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> self._data_store = {} <NEW_LINE> self._check_type = _check_type <NEW_LINE> self._spec_property_naming = _spec_property_naming <NEW_LINE> self._path_to_item = _path_to_item <NEW_LINE> self._configuration = _configuration <NEW_LINE> self._visited_composed_classes = _visited_composed_classes + (self.__class__,) <NEW_LINE> for var_name, var_value in kwargs.items(): <NEW_LINE> <INDENT> if var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> setattr(self, var_name, var_value)
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values.
625990508da39b475be0467c
class HeaderMessage(StatusMessage): <NEW_LINE> <INDENT> def __init__(self, message, status=None): <NEW_LINE> <INDENT> horiz_lines = max(len(message) + 10, 80) <NEW_LINE> new_message = ( "{:^{spacing}}\n".format(message, spacing=horiz_lines) + '–' * horiz_lines ) <NEW_LINE> super().__init__(new_message, status)
Extends StatusMessage with a border around the message
62599050b57a9660fecd2f13
class GreedyAgent(AgentBase): <NEW_LINE> <INDENT> def __init__(self, env): <NEW_LINE> <INDENT> self.env = env <NEW_LINE> self.name = "Greedy" <NEW_LINE> <DEDENT> def act(self): <NEW_LINE> <INDENT> flip_num = self.env.num_disks_can_filp(self.env.turn) <NEW_LINE> max_flips_index = np.argwhere(flip_num == flip_num.max()) <NEW_LINE> return max_flips_index[np.random.randint(len(max_flips_index))] <NEW_LINE> <DEDENT> def end_episode(self): <NEW_LINE> <INDENT> pass
Represents a Snake agent that takes a random action at every step.
62599050d7e4931a7ef3d50f
class RecuperationDeadline(Deadline.Deadline): <NEW_LINE> <INDENT> def __init__(self,nom,description,heure): <NEW_LINE> <INDENT> self.nom = nom <NEW_LINE> self.description = description <NEW_LINE> self.mon_deadline = heure
this class was created in order to allow me to create deadline in a different way by retrieving data entered by the user in a file
62599050462c4b4f79dbce96
class SchoolLocationView(ListAPIView): <NEW_LINE> <INDENT> serializer_class = SchoolLocationSerializer <NEW_LINE> filter_class = SchoolLocationFilter <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> region = self.kwargs['region'] <NEW_LINE> return SchoolLocation.objects.filter(region__name=region)
This is a read-only view that represents `SchoolLocation`. get: Returns a list of all available schools in the given region. Provides filters for `district`.
625990503c8af77a43b68989
class AllRoutes(View): <NEW_LINE> <INDENT> model = Schedule <NEW_LINE> form_class = RouteCreation <NEW_LINE> template_name = 'trains_schedule/trains.html' <NEW_LINE> context_object_name = 'schedule_list' <NEW_LINE> def get(self, request, train_id=None): <NEW_LINE> <INDENT> if train_id: <NEW_LINE> <INDENT> train = get_object_or_404(self.model, pk=train_id) <NEW_LINE> context = {'train': train} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context = {'schedule_list': self.model.objects.all().order_by('departure_date')} <NEW_LINE> <DEDENT> return render(request, self.template_name, context) <NEW_LINE> <DEDENT> def post(self, request, train_id): <NEW_LINE> <INDENT> route = get_object_or_404(self.model, pk=train_id) <NEW_LINE> if request.POST['action'] == 'Delete': <NEW_LINE> <INDENT> return self.delete(route) <NEW_LINE> <DEDENT> elif request.POST['action'] == 'Save': <NEW_LINE> <INDENT> form = self.form_class(request.POST, instance=route) <NEW_LINE> if form.has_changed(): <NEW_LINE> <INDENT> if form.is_valid(): <NEW_LINE> <INDENT> route = form.save() <NEW_LINE> return redirect('/schedule/trains/{}'.format(route.id)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return HttpResponse("Error: you enter incorrect value {}".format(form.errors)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return HttpResponse("Error: you hadn't change anything") <NEW_LINE> <DEDENT> <DEDENT> elif request.POST['action'] == 'Change': <NEW_LINE> <INDENT> initial_data = {'departure_city': route.departure_city, 'destination_city': route.destination_city, 'departure_date': route.departure_date.strftime('%Y-%m-%d %H:%M'), 'destination_date': route.destination_date.strftime('%Y-%m-%d %H:%M'), 'train': route.train} <NEW_LINE> form = self.form_class(initial=initial_data) <NEW_LINE> context = {'train': route, 'form': form} <NEW_LINE> return render(request, self.template_name, context) <NEW_LINE> <DEDENT> <DEDENT> def delete(self, route): <NEW_LINE> <INDENT> response = u'Successful delete route {}'.format(route.display_name()) <NEW_LINE> route.delete() <NEW_LINE> return HttpResponse(response)
Класс отвечающий за вывод информации о маршрутах, /schedule/trains/ - все маршруты /schedule/trains/19 - информация по конкретному маршруту Так же обрабатывает запросы на изменение/удаление маршрута
62599050d6c5a102081e35b5
class DataType(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> s_desc = models.CharField(max_length=200, verbose_name='short_description', help_text='A concise description of the file format, for quick orientation') <NEW_LINE> desc = models.CharField(max_length=2000, verbose_name='description', help_text='A complete and accurate description of the file format.') <NEW_LINE> file_extension = models.CharField(max_length=10) <NEW_LINE> is_raw = models.BooleanField(default=False) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
A dimension alteredand the experiment, e.g. time since some event, concnentration of some molecule in medium, etc.
62599050fff4ab517ebcecb4
@implementer(IOpenSSLClientConnectionCreator) <NEW_LINE> class ClientTLSOptions: <NEW_LINE> <INDENT> def __init__(self, hostname: str, ctx: SSL.Context): <NEW_LINE> <INDENT> self._ctx = ctx <NEW_LINE> if isIPAddress(hostname) or isIPv6Address(hostname): <NEW_LINE> <INDENT> self._hostnameBytes = hostname.encode("ascii") <NEW_LINE> self._sendSNI = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._hostnameBytes = _idnaBytes(hostname) <NEW_LINE> self._sendSNI = True <NEW_LINE> <DEDENT> ctx.set_info_callback(_tolerateErrors(self._identityVerifyingInfoCallback)) <NEW_LINE> <DEDENT> def clientConnectionForTLS( self, tlsProtocol: TLSMemoryBIOProtocol ) -> SSL.Connection: <NEW_LINE> <INDENT> context = self._ctx <NEW_LINE> connection = SSL.Connection(context, None) <NEW_LINE> connection.set_app_data(tlsProtocol) <NEW_LINE> return connection <NEW_LINE> <DEDENT> def _identityVerifyingInfoCallback( self, connection: SSL.Connection, where: int, ret: int ) -> None: <NEW_LINE> <INDENT> if where & SSL.SSL_CB_HANDSHAKE_START and self._sendSNI: <NEW_LINE> <INDENT> connection.set_tlsext_host_name(self._hostnameBytes)
Client creator for TLS without certificate identity verification. This is a copy of twisted.internet._sslverify.ClientTLSOptions with the identity verification left out. For documentation, see the twisted documentation.
6259905010dbd63aa1c72075
class TemplateManager(LabfluenceBase): <NEW_LINE> <INDENT> def __init__(self, confighandler, server=None): <NEW_LINE> <INDENT> LabfluenceBase.__init__(self, confighandler, server) <NEW_LINE> self.Cache = dict() <NEW_LINE> confighandler.Singletons['templatemanager'] = self <NEW_LINE> <DEDENT> def get(self, templatetype): <NEW_LINE> <INDENT> return self.getTemplate(templatetype) <NEW_LINE> <DEDENT> def getTemplate(self, templatetype=None): <NEW_LINE> <INDENT> if templatetype is None: <NEW_LINE> <INDENT> templatetype = self.Confighandler.get('wiki_default_newpage_template', 'exp_page') <NEW_LINE> <DEDENT> if templatetype in self.Cache and self.Confighandler.get('wiki_allow_template_caching', False): <NEW_LINE> <INDENT> return self.Cache[templatetype] <NEW_LINE> <DEDENT> template = self.Confighandler.get(templatetype+'_template', None) <NEW_LINE> if template: <NEW_LINE> <INDENT> if self.Confighandler.get('wiki_allow_template_caching', False): <NEW_LINE> <INDENT> self.Cache[templatetype] = template <NEW_LINE> <DEDENT> return template <NEW_LINE> <DEDENT> template_pageids = self.Confighandler.get('wiki_templates_pageIds') <NEW_LINE> if template_pageids: <NEW_LINE> <INDENT> logger.info("template_pageids: %s", template_pageids) <NEW_LINE> templatePageId = template_pageids.get(templatetype, None) <NEW_LINE> logger.info("templatePageId: type=%s, value=%s", type(templatePageId), templatePageId) <NEW_LINE> if not self.Server: <NEW_LINE> <INDENT> logger.info("TemplateManager.getTemplate() > Server is None or not connected, aborting (after having searched locally).") <NEW_LINE> return <NEW_LINE> <DEDENT> if templatePageId: <NEW_LINE> <INDENT> templatestruct = self.Server.getPage(pageId=templatePageId) <NEW_LINE> logger.info("templatestruct: %s", templatestruct) <NEW_LINE> if templatestruct and 'content' in templatestruct: <NEW_LINE> <INDENT> template = templatestruct['content'] <NEW_LINE> if self.Confighandler.get('wiki_allow_template_caching', False): <NEW_LINE> <INDENT> self.Cache[templatetype] = template <NEW_LINE> <DEDENT> return template <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> logger.info("No matching pageId for given template '%s', aborting...", templatetype) <NEW_LINE> return
TemplateManager is responsible for locating templates, either locally or from the wiki server. The templates may be cached (if enabled in config). to improve performance.
625990500fa83653e46f6376
class BeauticianKind(BaseKind): <NEW_LINE> <INDENT> nickName = ndb.StringProperty() <NEW_LINE> compEval = ndb.FloatProperty() <NEW_LINE> pr = ndb.IntegerProperty() <NEW_LINE> totalPoint = ndb.IntegerProperty(default=0) <NEW_LINE> gender = ndb.IntegerProperty() <NEW_LINE> birthday = ndb.DateProperty() <NEW_LINE> licenseFlg = ndb.TextProperty() <NEW_LINE> srhCondPref = ndb.IntegerProperty(repeated=True) <NEW_LINE> srhCondIowestRat = ndb.FloatProperty() <NEW_LINE> licenseKey = ndb.KeyProperty(kind=BeauticianLicenseKind) <NEW_LINE> myGalleryKey = ndb.KeyProperty(repeated=True, kind=BeauticianMyGalleryKind) <NEW_LINE> workGalleryKey = ndb.KeyProperty(repeated=True, kind=BeauticianWorkGalleryKind)
美容師情報
625990507b25080760ed8729
class ArticleDataSource(TemplateDataSource): <NEW_LINE> <INDENT> _BASE = ARTICLES_TEMPLATES
Serves templates for Articles.
62599050a219f33f346c7c99
class TestMozmillAPI(unittest.TestCase): <NEW_LINE> <INDENT> def make_test(self): <NEW_LINE> <INDENT> test = """var test_something = function() {}""" <NEW_LINE> fd, path = tempfile.mkstemp() <NEW_LINE> os.write(fd, test) <NEW_LINE> os.close(fd) <NEW_LINE> return path <NEW_LINE> <DEDENT> def test_runtwice(self): <NEW_LINE> <INDENT> passes = 2 <NEW_LINE> path = self.make_test() <NEW_LINE> m = mozmill.MozMill.create() <NEW_LINE> m.run([dict(path=path)]) <NEW_LINE> results = m.run([dict(path=path)]) <NEW_LINE> self.assertTrue(len(results.passes) == passes)
test mozmill's API
6259905015baa72349463424
class TestFixedAddressApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = ibcsp_ipamsvc.api.fixed_address_api.FixedAddressApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_fixed_address_create(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_fixed_address_delete(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_fixed_address_list(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_fixed_address_read(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_fixed_address_update(self): <NEW_LINE> <INDENT> pass
FixedAddressApi unit test stubs
625990507d847024c075d86c
class PublicViewTest(TestBase): <NEW_LINE> <INDENT> def test_public_front_page_view(self): <NEW_LINE> <INDENT> response = self.testapp.get('/') <NEW_LINE> self.assertEqual(response.status_int, 200) <NEW_LINE> <DEDENT> def test_public_about_page_view(self): <NEW_LINE> <INDENT> for page in ['/about', '/about/?doc=terms', '/about/?doc=privacy']: <NEW_LINE> <INDENT> response = self.testapp.get('/about') <NEW_LINE> self.assertEqual(response.status_int, 200) <NEW_LINE> self.assertIn('About', response.body) <NEW_LINE> <DEDENT> <DEDENT> def test_public_link_google_account_page(self): <NEW_LINE> <INDENT> response = self.testapp.get('/link') <NEW_LINE> self.assertEqual(response.status_int, 200) <NEW_LINE> <DEDENT> def test_public_sandbox_page(self): <NEW_LINE> <INDENT> response = self.testapp.get('/sandbox') <NEW_LINE> self.assertEqual(response.status_int, 200)
test that the public views are implemented and functioning correctly
6259905063b5f9789fe86606
class ProgressBar: <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> self._maxLength = str(args[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._maxLength = None <NEW_LINE> <DEDENT> self._input = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self._maxLength: <NEW_LINE> <INDENT> return self._input + " / " + self._maxLength <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._input <NEW_LINE> <DEDENT> <DEDENT> def update(self, i): <NEW_LINE> <INDENT> self._input = str(i) <NEW_LINE> sys.stdout.write('\r' + self.__str__()) <NEW_LINE> sys.stdout.flush()
a simple progress handler to monitor the status of some process
6259905045492302aabfd96c
class VOIEWithInterviewData(object): <NEW_LINE> <INDENT> _names = { "txverify_interview":'txVerifyInterview', "extract_earnings":'extractEarnings', "extract_deductions":'extractDeductions', "extract_direct_deposit":'extractDirectDeposit' } <NEW_LINE> def __init__(self, txverify_interview=None, extract_earnings=True, extract_deductions=False, extract_direct_deposit=True, additional_properties = {}): <NEW_LINE> <INDENT> self.txverify_interview = txverify_interview <NEW_LINE> self.extract_earnings = extract_earnings <NEW_LINE> self.extract_deductions = extract_deductions <NEW_LINE> self.extract_direct_deposit = extract_direct_deposit <NEW_LINE> self.additional_properties = additional_properties <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dictionary(cls, dictionary): <NEW_LINE> <INDENT> if dictionary is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> txverify_interview = None <NEW_LINE> if dictionary.get('txVerifyInterview') != None: <NEW_LINE> <INDENT> txverify_interview = list() <NEW_LINE> for structure in dictionary.get('txVerifyInterview'): <NEW_LINE> <INDENT> txverify_interview.append(finicityapi.models.txverify_interview.TxverifyInterview.from_dictionary(structure)) <NEW_LINE> <DEDENT> <DEDENT> extract_earnings = dictionary.get("extractEarnings") if dictionary.get("extractEarnings") else True <NEW_LINE> extract_deductions = dictionary.get("extractDeductions") if dictionary.get("extractDeductions") else False <NEW_LINE> extract_direct_deposit = dictionary.get("extractDirectDeposit") if dictionary.get("extractDirectDeposit") else True <NEW_LINE> for key in cls._names.values(): <NEW_LINE> <INDENT> if key in dictionary: <NEW_LINE> <INDENT> del dictionary[key] <NEW_LINE> <DEDENT> <DEDENT> return cls(txverify_interview, extract_earnings, extract_deductions, extract_direct_deposit, dictionary)
Implementation of the 'VOIE With Interview Data' model. TODO: type model description here. Attributes: txverify_interview (list of TxverifyInterview): An array of txVerifyInterview objects. extract_earnings (bool): Field to indicate whether to extract the earnings on all pay statements. This is an optional field. extract_deductions (bool): Field to indicate whether to extract the deductions on all pay statements. This is an optional field. extract_direct_deposit (bool): Field to indicate whether to extract the direct deposits on all pay statements. This is an optional field.
62599050435de62698e9d296
class PublicTransportData(object): <NEW_LINE> <INDENT> def __init__(self, journey): <NEW_LINE> <INDENT> self.start = journey[0] <NEW_LINE> self.destination = journey[1] <NEW_LINE> self.times = {} <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> response = requests.get( _RESOURCE + 'connections?' + 'from=' + self.start + '&' + 'to=' + self.destination + '&' + 'fields[]=connections/from/departureTimestamp/&' + 'fields[]=connections/', timeout=10) <NEW_LINE> connections = response.json()['connections'][:2] <NEW_LINE> try: <NEW_LINE> <INDENT> self.times = [ dt_util.as_local( dt_util.utc_from_timestamp( item['from']['departureTimestamp'])).strftime( TIME_STR_FORMAT) for item in connections ] <NEW_LINE> self.times.append( dt_util.as_local( dt_util.utc_from_timestamp( connections[0]['from']['departureTimestamp'])) - dt_util.as_local(dt_util.utcnow())) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.times = ['n/a']
The Class for handling the data retrieval.
62599050dd821e528d6da373
class CartItem(models.Model): <NEW_LINE> <INDENT> cart_id = models.CharField(max_length=50) <NEW_LINE> date_added = models.DateTimeField(auto_now_add=True) <NEW_LINE> quantity = models.IntegerField(default=1) <NEW_LINE> product = models.ForeignKey('catalog.Product', unique=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'cart_items' <NEW_LINE> ordering = ['date_added'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def total(self): <NEW_LINE> <INDENT> return self.quantity * self.product.price <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.product.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def price(self): <NEW_LINE> <INDENT> return self.product.price <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return self.product.get_absolute_url() <NEW_LINE> <DEDENT> def augment_quantity(self, quantity): <NEW_LINE> <INDENT> self.quantity = self.quantity + int(quantity) <NEW_LINE> self.save()
Model for a cart item.
6259905007d97122c421813d
class Shoter: <NEW_LINE> <INDENT> def __init__(self, width=1280, height=720): <NEW_LINE> <INDENT> options = Options() <NEW_LINE> options.add_argument('--headless') <NEW_LINE> options.add_argument('--disable-dev-shm-usage') <NEW_LINE> driver = 'chromium.chromedriver' <NEW_LINE> path = '/snap/bin/chromium.chromedriver' <NEW_LINE> driver = webdriver.Chrome(driver, options=options) <NEW_LINE> driver.set_window_size(width, height) <NEW_LINE> self.driver = driver <NEW_LINE> <DEDENT> def load_page(self, page, timeout=1): <NEW_LINE> <INDENT> self.driver.get(page) <NEW_LINE> time.sleep(timeout) <NEW_LINE> <DEDENT> def next_slide(self, timeout=1): <NEW_LINE> <INDENT> action = ActionChains(self.driver) <NEW_LINE> action.send_keys(Keys.PAGE_DOWN) <NEW_LINE> action.perform() <NEW_LINE> time.sleep(timeout) <NEW_LINE> <DEDENT> def shot(self, count): <NEW_LINE> <INDENT> if not os.path.exists('out'): <NEW_LINE> <INDENT> os.mkdir('out') <NEW_LINE> <DEDENT> name = 'out/slide-{:02}.png'.format(count) <NEW_LINE> screenshot = self.driver.save_screenshot(name) <NEW_LINE> return screenshot <NEW_LINE> <DEDENT> def get_url(self): <NEW_LINE> <INDENT> return self.driver.current_url <NEW_LINE> <DEDENT> def get_snapshot(self): <NEW_LINE> <INDENT> sections = self.driver.find_elements_by_css_selector('section.present') <NEW_LINE> if not sections: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return sections[-1].get_attribute('innerHTML') <NEW_LINE> <DEDENT> def exit(self): <NEW_LINE> <INDENT> self.driver.quit()
class able to record screenshots from slenium webdriver
6259905099cbb53fe683237e
class SourcePackageCopyrightView(LaunchpadView): <NEW_LINE> <INDENT> page_title = "Copyright" <NEW_LINE> @property <NEW_LINE> def label(self): <NEW_LINE> <INDENT> return smartquote("Copyright for " + self.context.title)
A view to display a source package's copyright information.
6259905076e4537e8c3f0a1f
class ArtifactTagProperties(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'registry_login_server': {'required': True, 'readonly': True}, 'repository_name': {'required': True, 'readonly': True}, 'name': {'required': True, 'readonly': True}, 'digest': {'required': True, 'readonly': True}, 'created_on': {'required': True, 'readonly': True}, 'last_updated_on': {'required': True, 'readonly': True}, } <NEW_LINE> _attribute_map = { 'registry_login_server': {'key': 'registry', 'type': 'str'}, 'repository_name': {'key': 'imageName', 'type': 'str'}, 'name': {'key': 'tag.name', 'type': 'str'}, 'digest': {'key': 'tag.digest', 'type': 'str'}, 'created_on': {'key': 'tag.createdTime', 'type': 'iso-8601'}, 'last_updated_on': {'key': 'tag.lastUpdateTime', 'type': 'iso-8601'}, 'can_delete': {'key': 'tag.changeableAttributes.deleteEnabled', 'type': 'bool'}, 'can_write': {'key': 'tag.changeableAttributes.writeEnabled', 'type': 'bool'}, 'can_list': {'key': 'tag.changeableAttributes.listEnabled', 'type': 'bool'}, 'can_read': {'key': 'tag.changeableAttributes.readEnabled', 'type': 'bool'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ArtifactTagProperties, self).__init__(**kwargs) <NEW_LINE> self.registry_login_server = None <NEW_LINE> self.repository_name = None <NEW_LINE> self.name = None <NEW_LINE> self.digest = None <NEW_LINE> self.created_on = None <NEW_LINE> self.last_updated_on = None <NEW_LINE> self.can_delete = kwargs.get('can_delete', None) <NEW_LINE> self.can_write = kwargs.get('can_write', None) <NEW_LINE> self.can_list = kwargs.get('can_list', None) <NEW_LINE> self.can_read = kwargs.get('can_read', None)
Tag attributes. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar registry_login_server: Required. Registry login server name. This is likely to be similar to {registry-name}.azurecr.io. :vartype registry_login_server: str :ivar repository_name: Required. Image name. :vartype repository_name: str :ivar name: Required. Tag name. :vartype name: str :ivar digest: Required. Tag digest. :vartype digest: str :ivar created_on: Required. Tag created time. :vartype created_on: ~datetime.datetime :ivar last_updated_on: Required. Tag last update time. :vartype last_updated_on: ~datetime.datetime :ivar can_delete: Delete enabled. :vartype can_delete: bool :ivar can_write: Write enabled. :vartype can_write: bool :ivar can_list: List enabled. :vartype can_list: bool :ivar can_read: Read enabled. :vartype can_read: bool
6259905094891a1f408ba141
class CodeBlockProcessor(BlockProcessor): <NEW_LINE> <INDENT> def test(self, parent, block): <NEW_LINE> <INDENT> return block.startswith(' '*self.tab_length) <NEW_LINE> <DEDENT> def run(self, parent, blocks): <NEW_LINE> <INDENT> sibling = self.lastChild(parent) <NEW_LINE> block = blocks.pop(0) <NEW_LINE> theRest = '' <NEW_LINE> if (sibling is not None and sibling.tag == "pre" and len(sibling) and sibling[0].tag == "code"): <NEW_LINE> <INDENT> code = sibling[0] <NEW_LINE> block, theRest = self.detab(block) <NEW_LINE> code.text = util.AtomicString( '%s\n%s\n' % (code.text, block.rstrip()) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pre = util.etree.SubElement(parent, 'pre') <NEW_LINE> code = util.etree.SubElement(pre, 'code') <NEW_LINE> block, theRest = self.detab(block) <NEW_LINE> code.text = util.AtomicString('%s\n' % block.rstrip()) <NEW_LINE> <DEDENT> if theRest: <NEW_LINE> <INDENT> blocks.insert(0, theRest)
Process code blocks.
62599050435de62698e9d297
class PizzaToppin(models.Model): <NEW_LINE> <INDENT> id_pizza = models.ForeignKey(Pizza, on_delete=models.DO_NOTHING, verbose_name="Pizza") <NEW_LINE> id_toppin = models.ForeignKey(Toppin, on_delete=models.DO_NOTHING, verbose_name="Toppin") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '{}'.format(self.id_toppin.nombre_toppin)
Model: PizzaToppin Tabla: PizzaToppin Compone las relaciones de la pizza y los toppins que se le asignan Numero de id_pizza y Numero del id_toppin
6259905023e79379d538d995
class CustomORJSONResponse(ORJSONResponse): <NEW_LINE> <INDENT> def render(self, content: Any) -> bytes: <NEW_LINE> <INDENT> assert orjson is not None, "orjson must be installed to use ORJSONResponse" <NEW_LINE> return orjson.dumps( content, option=orjson.OPT_PASSTHROUGH_DATETIME, default=default )
Custom orjson response with a custom format for datetimes orjson defaults to outputing datetime objects in RFC 3339 format: `1970-01-01T00:00:00+00:00` with this, we simply output the string representation of the python datetime object: `1970-01-01 00:00:00` see: https://github.com/ijl/orjson#opt_passthrough_datetime
6259905016aa5153ce401987
class MathOperation(Expression): <NEW_LINE> <INDENT> __slots__ = 'left', 'operator', 'right' <NEW_LINE> OPERATORS = ('*', '/', '%', '+', '-') <NEW_LINE> func_lookup = {"*": "multiply", "+": "add", "-": "subtract", "%": "modulo", "/": "divide"} <NEW_LINE> min_precedence = NamedSubquery.precedence + 1 <NEW_LINE> max_precedence = min_precedence + 1 <NEW_LINE> full_template = Template('$left $operator $right') <NEW_LINE> negative_template = Template('$operator$right') <NEW_LINE> def __init__(self, left, operator, right): <NEW_LINE> <INDENT> self.left = left <NEW_LINE> self.operator = operator <NEW_LINE> self.right = right <NEW_LINE> <DEDENT> def to_function_call(self): <NEW_LINE> <INDENT> return FunctionCall(self.func_lookup[self.operator], [self.left, self.right]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def precedence(self): <NEW_LINE> <INDENT> if self.operator in "*/%": <NEW_LINE> <INDENT> return self.min_precedence <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.max_precedence <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def template(self): <NEW_LINE> <INDENT> return self.negative_template if self.left == Number(0) else self.full_template
Mathematical operation between two numeric values.
6259905024f1403a9268631a
class DNAPlugin(Plugin): <NEW_LINE> <INDENT> def __init__(self, instance, dn="cn=Distributed Numeric Assignment Plugin,cn=plugins,cn=config"): <NEW_LINE> <INDENT> super(DNAPlugin, self).__init__(instance, dn)
A single instance of Distributed Numeric Assignment plugin entry :param instance: An instance :type instance: lib389.DirSrv :param dn: Entry DN :type dn: str
6259905076d4e153a661dcc5
class Sablon(object): <NEW_LINE> <INDENT> def __init__(self, template): <NEW_LINE> <INDENT> self.template = template <NEW_LINE> self.returncode = None <NEW_LINE> self.stdout = None <NEW_LINE> self.stderr = None <NEW_LINE> self.file_data = None <NEW_LINE> <DEDENT> def process(self, json_data, namedblobfile=None): <NEW_LINE> <INDENT> sablon_url = environ.get('SABLON_URL') <NEW_LINE> if sablon_url: <NEW_LINE> <INDENT> return self.process_using_service( sablon_url, json_data, namedblobfile) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.process_using_executable(json_data, namedblobfile) <NEW_LINE> <DEDENT> <DEDENT> def is_processed_successfully(self): <NEW_LINE> <INDENT> return self.returncode == 0 <NEW_LINE> <DEDENT> def process_using_service(self, url, json_data, namedblobfile): <NEW_LINE> <INDENT> if namedblobfile is None: <NEW_LINE> <INDENT> namedblobfile = self.template.file <NEW_LINE> <DEDENT> template = namedblobfile.open() <NEW_LINE> resp = None <NEW_LINE> try: <NEW_LINE> <INDENT> resp = requests.post( url, files={'context': json_data, 'template': template}, ) <NEW_LINE> resp.raise_for_status() <NEW_LINE> <DEDENT> except requests.exceptions.RequestException: <NEW_LINE> <INDENT> details = resp.content[:200] if resp is not None else '' <NEW_LINE> logger.exception( 'Document creation with sablon failed. %s', details) <NEW_LINE> raise SablonProcessingFailed(details) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.file_data = resp.content <NEW_LINE> self.returncode = 0 <NEW_LINE> return self <NEW_LINE> <DEDENT> <DEDENT> def process_using_executable(self, json_data, namedblobfile): <NEW_LINE> <INDENT> tmpdir_path = tempfile.mkdtemp(prefix='opengever.core.sablon_') <NEW_LINE> output_path = join(tmpdir_path, 'sablon_output.docx') <NEW_LINE> if namedblobfile is None: <NEW_LINE> <INDENT> template_path = self.template.as_file(tmpdir_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> template_path = join(tmpdir_path, namedblobfile.filename) <NEW_LINE> with open(template_path, 'wb') as template_file: <NEW_LINE> <INDENT> template_file.write(namedblobfile.data) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> sablon_path = environ.get('SABLON_BIN', 'sablon') <NEW_LINE> subprocess = Popen( [sablon_path, template_path, output_path], stdin=PIPE, stdout=PIPE, stderr=PIPE) <NEW_LINE> self.stdout, self.stderr = subprocess.communicate(input=json_data) <NEW_LINE> self.returncode = subprocess.returncode <NEW_LINE> if not self.is_processed_successfully(): <NEW_LINE> <INDENT> raise SablonProcessingFailed(self.stderr) <NEW_LINE> <DEDENT> with open(output_path, 'rb') as outfile: <NEW_LINE> <INDENT> self.file_data = outfile.read() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> shutil.rmtree(tmpdir_path) <NEW_LINE> <DEDENT> return self
Integrate word document template processor. See https://github.com/senny/sablon
62599050d99f1b3c44d06b34
class uavcangen(Task.Task): <NEW_LINE> <INDENT> color = 'BLUE' <NEW_LINE> before = 'cxx c' <NEW_LINE> def run(self): <NEW_LINE> <INDENT> python = self.env.get_flat('PYTHON') <NEW_LINE> out = self.env.get_flat('OUTPUT_DIR') <NEW_LINE> src = self.env.get_flat('SRC') <NEW_LINE> dsdlc = self.env.get_flat("DSDL_COMPILER") <NEW_LINE> ret = self.exec_command(['{}'.format(python), '{}'.format(dsdlc), '-O{}'.format(out)] + [x.abspath() for x in self.inputs]) <NEW_LINE> if ret != 0: <NEW_LINE> <INDENT> if ret > 128 or ret < 0: <NEW_LINE> <INDENT> Logs.warn('uavcangen crashed with code: {}'.format(ret)) <NEW_LINE> ret = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Logs.error('uavcangen returned {} error code'.format(ret)) <NEW_LINE> <DEDENT> <DEDENT> return ret <NEW_LINE> <DEDENT> def post_run(self): <NEW_LINE> <INDENT> super(uavcangen, self).post_run() <NEW_LINE> for header in self.generator.output_dir.ant_glob("*.hpp **/*.hpp", remove=False): <NEW_LINE> <INDENT> header.sig = header.cache_sig = self.cache_sig
generate uavcan header files
62599050b57a9660fecd2f16
class SigCertConstraintFlags(Flag): <NEW_LINE> <INDENT> SUBJECT = 1 <NEW_LINE> ISSUER = 2 <NEW_LINE> OID = 4 <NEW_LINE> SUBJECT_DN = 8 <NEW_LINE> RESERVED = 16 <NEW_LINE> KEY_USAGE = 32 <NEW_LINE> URL = 64 <NEW_LINE> UNSUPPORTED = RESERVED | OID
Flags for the ``/Ff`` entry in the certificate seed value dictionary for a dictionary field. These mark which of the constraints are to be strictly enforced, as opposed to optional ones. .. warning:: While this enum records values for all flags, not all corresponding constraint types have been implemented yet.
62599050498bea3a75a58fbb
class PlayerAI(character.Character): <NEW_LINE> <INDENT> movements = {0:UP, 1:DOWN, 2:RIGHT, 3:LEFT} <NEW_LINE> def __init__(self, position, world,sprite, with_animation=True): <NEW_LINE> <INDENT> super().__init__(position,world,sprite, with_animation) <NEW_LINE> tf.reset_default_graph() <NEW_LINE> tf.set_random_seed(42) <NEW_LINE> np.random.seed(42) <NEW_LINE> self.network = DDQNs('online', 15,15,512,100,4) <NEW_LINE> self.sess = tf.Session() <NEW_LINE> saver = tf.train.Saver() <NEW_LINE> saver.restore(self.sess,'../train/saver/posible/93/sampling7BB.ckpt') <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.moving: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> state = self.world.generateState() <NEW_LINE> q_values = self.network.evalActionSess([state],self.sess) <NEW_LINE> action = np.argmax(q_values) <NEW_LINE> self.changeDirection(self.movements[action]) <NEW_LINE> new_position = self.position + self.direction <NEW_LINE> if self.world.canMove(new_position): <NEW_LINE> <INDENT> self.move(new_position) <NEW_LINE> self.world.testCoin() <NEW_LINE> <DEDENT> <DEDENT> def futureDirection(self,direction): <NEW_LINE> <INDENT> return <NEW_LINE> self.future_direction = direction
Class used for the characters of the game
625990508e7ae83300eea52c
class ExcludeState(object): <NEW_LINE> <INDENT> def __init__(self, *states): <NEW_LINE> <INDENT> self.not_allowed_states = states <NEW_LINE> <DEDENT> def __call__(self, window): <NEW_LINE> <INDENT> state = window.state <NEW_LINE> for not_allowed_state in self.not_allowed_states: <NEW_LINE> <INDENT> if not_allowed_state in state: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Return only windows without specified types.
62599050a79ad1619776b509
class Prototype(Vowel.Vowel): <NEW_LINE> <INDENT> def __init__(self, e1, e2, length, name): <NEW_LINE> <INDENT> super(Prototype, self).__init__(e1, e2, length, name) <NEW_LINE> self.carriers = 1 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> f1, f2 = self.to_hz_praat(self.e1, self.e2) <NEW_LINE> f1 = int(f1) <NEW_LINE> f2 = "{:>4}".format(int(f2)) <NEW_LINE> l = int(self.length) <NEW_LINE> s = "({0}, {1}, {2})".format(f1, f2, l) <NEW_LINE> return s <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> e1 = self.e1 <NEW_LINE> e2 = self.e2 <NEW_LINE> repr_s = ", ".join( [ str(e1), str(e2), str(self.length)] ) <NEW_LINE> return '('+repr_s+')' <NEW_LINE> <DEDENT> def to_hz_praat(self, e1, e2): <NEW_LINE> <INDENT> from math import exp <NEW_LINE> d1 = exp ((e1 - 43.0) / 11.17) <NEW_LINE> f1 = (14680*d1 - 312.0) / (1 - d1) <NEW_LINE> d2 = exp ((e2 - 43.0) / 11.17) <NEW_LINE> f2 = (14680*d2 - 312.0) / (1 - d2) <NEW_LINE> return (f1, f2) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> matches = (self.e1 == other.e1 and self.e2 == other.e2 and self.length == other.length) <NEW_LINE> return matches <NEW_LINE> <DEDENT> def update(self, ne1, ne2, nl, c): <NEW_LINE> <INDENT> self.e1 = ne1 <NEW_LINE> self.e2 = ne2 <NEW_LINE> self.length = nl <NEW_LINE> self.carriers = c <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.e1, self.e2, self.length))
Prototype class *Vowel subclass* A Prototype indicates the average f1/f2 position, length of a vowel and the number of carriers (Agents) i.e. the conventional representation of a vowel for some population. Prototypes are formed by collecting Vowels from agents.
62599050287bf620b6273084
class gcPersonView(BrowserView): <NEW_LINE> <INDENT> implements(IgcPersonView) <NEW_LINE> def __init__(self, context, request): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.request = request <NEW_LINE> <DEDENT> @property <NEW_LINE> def portal_catalog(self): <NEW_LINE> <INDENT> return getToolByName(self.context, 'portal_catalog') <NEW_LINE> <DEDENT> @property <NEW_LINE> def portal_membership(self): <NEW_LINE> <INDENT> return getToolByName(self.context, 'portal_membership') <NEW_LINE> <DEDENT> @property <NEW_LINE> def portal(self): <NEW_LINE> <INDENT> return getToolByName(self.context, 'portal_url').getPortalObject() <NEW_LINE> <DEDENT> def getSpamProtectedEmail(self): <NEW_LINE> <INDENT> email = self.context.getEmail() <NEW_LINE> email = email.replace('.', ' [ DOT ] ') <NEW_LINE> email = email.replace('@', ' [ AT ] ') <NEW_LINE> email = email.replace('-', ' [ DASH ] ') <NEW_LINE> email = email.replace('_', ' [ UNDERSCORE ] ') <NEW_LINE> return email <NEW_LINE> <DEDENT> def get_your_contributions(self, type): <NEW_LINE> <INDENT> user = self.portal_membership.getAuthenticatedMember() <NEW_LINE> user_id = user.getId() <NEW_LINE> brains = self.portal_catalog({'portal_type': type, 'getPrimaryAuthor': user_id, 'sort_on':'created', 'sort_order': 'reverse'}) <NEW_LINE> return [i.getObject() for i in brains] <NEW_LINE> <DEDENT> def get_addable_items_list(self): <NEW_LINE> <INDENT> class Workaround: <NEW_LINE> <INDENT> def portal_type(self): <NEW_LINE> <INDENT> return self._portal_type <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def __init__(self, _name, _portal_type): <NEW_LINE> <INDENT> self._name = _name <NEW_LINE> self._portal_type = _portal_type <NEW_LINE> <DEDENT> <DEDENT> all_known = [] <NEW_LINE> all_known.append(Workaround('Conference Paper', 'ConferencePaper')) <NEW_LINE> all_known.append(Workaround('Conference Event', 'ConferenceEvent')) <NEW_LINE> all_known.append(Workaround('Article', 'Article')) <NEW_LINE> return all_known <NEW_LINE> <DEDENT> def get_cfps(self): <NEW_LINE> <INDENT> brains = self.portal_catalog({'portal_type': ['Conference', 'Journal'], 'sort_on':'created', 'sort_order': 'reverse'}) <NEW_LINE> return [i.getObject() for i in brains]
gcPerson browser view
6259905063d6d428bbee3c67
class ReceivingItemView(Viewable): <NEW_LINE> <INDENT> branch = Branch <NEW_LINE> id = ReceivingOrderItem.id <NEW_LINE> order_identifier = ReceivingOrder.identifier <NEW_LINE> purchase_identifier = PurchaseOrder.identifier <NEW_LINE> purchase_item_id = ReceivingOrderItem.purchase_item_id <NEW_LINE> sellable_id = ReceivingOrderItem.sellable_id <NEW_LINE> invoice_number = ReceivingOrder.invoice_number <NEW_LINE> receival_date = ReceivingOrder.receival_date <NEW_LINE> quantity = ReceivingOrderItem.quantity <NEW_LINE> cost = ReceivingOrderItem.cost <NEW_LINE> unit_description = SellableUnit.description <NEW_LINE> supplier_name = Person.name <NEW_LINE> batch_number = Coalesce(StorableBatch.batch_number, u'') <NEW_LINE> batch_date = StorableBatch.create_date <NEW_LINE> tables = [ ReceivingOrderItem, LeftJoin(StorableBatch, StorableBatch.id == ReceivingOrderItem.batch_id), Join(ReceivingOrder, ReceivingOrderItem.receiving_order_id == ReceivingOrder.id), Join(PurchaseReceivingMap, ReceivingOrder.id == PurchaseReceivingMap.receiving_id), LeftJoin(ReceivingInvoice, ReceivingOrder.receiving_invoice_id == ReceivingInvoice.id), Join(PurchaseOrder, PurchaseReceivingMap.purchase_id == PurchaseOrder.id), LeftJoin(Sellable, ReceivingOrderItem.sellable_id == Sellable.id), LeftJoin(SellableUnit, Sellable.unit_id == SellableUnit.id), LeftJoin(Supplier, PurchaseOrder.supplier_id == Supplier.id), LeftJoin(Person, Supplier.person_id == Person.id), Join(Branch, PurchaseOrder.branch_id == Branch.id), ]
Stores information about receiving items. This view is used to query products that are going to be received or was already received and the information related to that process. :cvar id: the id of the receiving item :cvar order_identifier: the identifier of the receiving order :cvar purchase_identifier: the identifier of the purchase order :cvar purchase_item_id: the id of the purchase item :cvar sellable_id: the id of the sellable related to the received item :cvar invoice_number: the invoice number of the receiving order :cvar receival_date: the date when the item was received :cvar quantity: the received quantity :cvar cost: the product cost :cvar unit_description: the product unit description :cvar supplier_name: the product supplier name
62599050e76e3b2f99fd9e9a
class Brew(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> bubble_sensor_gpio = models.SmallIntegerField(blank=True, null=True) <NEW_LINE> start_time = models.DateTimeField(default=timezone.now) <NEW_LINE> finished = models.BooleanField(default=False) <NEW_LINE> def bubbles_in_interval(self, time_from, time_to): <NEW_LINE> <INDENT> if time_from > time_to: <NEW_LINE> <INDENT> return self.bubble_set.filter(time_stamp__gte=time_to, time_stamp__lt=time_from).count() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.bubble_set.filter(time_stamp__gte=time_from, time_stamp__lt=time_to).count() <NEW_LINE> <DEDENT> <DEDENT> def get_min_date(self): <NEW_LINE> <INDENT> return self.bubble_set.aggregate(Min('time_stamp'))['time_stamp__min'] <NEW_LINE> <DEDENT> def get_max_date(self): <NEW_LINE> <INDENT> return self.bubble_set.aggregate(Max('time_stamp'))['time_stamp__max'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
A brew class
62599050d7e4931a7ef3d513
class History(list): <NEW_LINE> <INDENT> def new_epoch(self): <NEW_LINE> <INDENT> self.append({'batches': []}) <NEW_LINE> <DEDENT> def new_batch(self): <NEW_LINE> <INDENT> self[-1]['batches'].append({}) <NEW_LINE> <DEDENT> def record(self, attr, value): <NEW_LINE> <INDENT> msg = "Call new_epoch before recording for the first time." <NEW_LINE> if not self: <NEW_LINE> <INDENT> raise ValueError(msg) <NEW_LINE> <DEDENT> self[-1][attr] = value <NEW_LINE> <DEDENT> def record_batch(self, attr, value): <NEW_LINE> <INDENT> self[-1]['batches'][-1][attr] = value <NEW_LINE> <DEDENT> def to_list(self): <NEW_LINE> <INDENT> return list(self) <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> if isinstance(i, (int, slice)): <NEW_LINE> <INDENT> return super().__getitem__(i) <NEW_LINE> <DEDENT> x = self <NEW_LINE> if isinstance(i, tuple): <NEW_LINE> <INDENT> for part in i: <NEW_LINE> <INDENT> x_dirty = partial_index(x, part) <NEW_LINE> x = filter_missing(x_dirty) <NEW_LINE> if type(x) is _missingno: <NEW_LINE> <INDENT> raise x.e <NEW_LINE> <DEDENT> <DEDENT> return x <NEW_LINE> <DEDENT> raise ValueError("Invalid parameter type passed to index. " "Pass string, int or tuple.")
History contains the information about the training history of a NeuralNet, facilitating some of the more common tasks that are occur during training. When you want to log certain information during training (say, a particular score or the norm of the gradients), you should write them to the net's history object. It is basically a list of dicts for each epoch, that, again, contains a list of dicts for each batch. For convenience, it has enhanced slicing notation and some methods to write new items. To access items from history, you may pass a tuple of up to four items: 1. Slices along the epochs. 2. Selects columns from history epochs, may be a single one or a tuple of column names. 3. Slices along the batches. 4. Selects columns from history batchs, may be a single one or a tuple of column names. You may use a combination of the four items. If you select columns that are not present in all epochs/batches, only those epochs/batches are chosen that contain said columns. If this set is empty, a KeyError is raised. Examples -------- >>> # ACCESSING ITEMS >>> # history of a fitted neural net >>> history = net.history >>> # get current epoch, a dict >>> history[-1] >>> # get train losses from all epochs, a list of floats >>> history[:, 'train_loss'] >>> # get train and valid losses from all epochs, a list of tuples >>> history[:, ('train_loss', 'valid_loss')] >>> # get current batches, a list of dicts >>> history[-1, 'batches'] >>> # get latest batch, a dict >>> history[-1, 'batches', -1] >>> # get train losses from current batch, a list of floats >>> history[-1, 'batches', :, 'train_loss'] >>> # get train and valid losses from current batch, a list of tuples >>> history[-1, 'batches', :, ('train_loss', 'valid_loss')] >>> # WRITING ITEMS >>> # add new epoch row >>> history.new_epoch() >>> # add an entry to current epoch >>> history.record('my-score', 123) >>> # add a batch row to the current epoch >>> history.new_batch() >>> # add an entry to the current batch >>> history.record_batch('my-batch-score', 456) >>> # overwrite entry of current batch >>> history.record_batch('my-batch-score', 789)
62599050dd821e528d6da375
class FakeDBSubjectLock(data_store.DBSubjectLock): <NEW_LINE> <INDENT> def _Acquire(self, lease_time): <NEW_LINE> <INDENT> self.expires = int((time.time() + lease_time) * 1e6) <NEW_LINE> with self.store.lock: <NEW_LINE> <INDENT> expires = self.store.transactions.get(self.subject) <NEW_LINE> if expires and (time.time() * 1e6) < expires: <NEW_LINE> <INDENT> raise data_store.DBSubjectLockError("Subject is locked") <NEW_LINE> <DEDENT> self.store.transactions[self.subject] = self.expires <NEW_LINE> self.locked = True <NEW_LINE> <DEDENT> <DEDENT> def UpdateLease(self, duration): <NEW_LINE> <INDENT> self.expires = int((time.time() + duration) * 1e6) <NEW_LINE> self.store.transactions[self.subject] = self.expires <NEW_LINE> <DEDENT> def Release(self): <NEW_LINE> <INDENT> with self.store.lock: <NEW_LINE> <INDENT> if self.locked: <NEW_LINE> <INDENT> self.store.transactions.pop(self.subject, None) <NEW_LINE> self.locked = False
A fake transaction object for testing.
625990508e71fb1e983bcf60
class RequestRedirect(werkzeug.routing.RequestRedirect): <NEW_LINE> <INDENT> code = 302
Used for redirection from within nested calls. Note: We avoid using 308 to avoid permanent
6259905096565a6dacd2d9d6
class FileSystemResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'items': 'list[FileSystem]' } <NEW_LINE> attribute_map = { 'items': 'items' } <NEW_LINE> required_args = { } <NEW_LINE> def __init__( self, items=None, ): <NEW_LINE> <INDENT> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> if key not in self.attribute_map: <NEW_LINE> <INDENT> raise KeyError("Invalid key `{}` for `FileSystemResponse`".format(key)) <NEW_LINE> <DEDENT> self.__dict__[key] = value <NEW_LINE> <DEDENT> def __getattribute__(self, item): <NEW_LINE> <INDENT> value = object.__getattribute__(self, item) <NEW_LINE> if isinstance(value, Property): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <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> <DEDENT> if issubclass(FileSystemResponse, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = 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, FileSystemResponse): <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
Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition.
6259905010dbd63aa1c72079
class DirectConn: <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self.db = config['Main']['inv_db'] <NEW_LINE> self.dbConn, self.cur = self._connect2db() <NEW_LINE> <DEDENT> def _connect2db(self): <NEW_LINE> <INDENT> logging.debug("Creating Datastore object and cursor") <NEW_LINE> if os.path.isfile(self.db): <NEW_LINE> <INDENT> db_conn = sqlite3.connect(self.db) <NEW_LINE> logging.debug("Datastore object and cursor are created") <NEW_LINE> return db_conn, db_conn.cursor() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False, False <NEW_LINE> <DEDENT> <DEDENT> def rebuild(self): <NEW_LINE> <INDENT> if self.dbConn: <NEW_LINE> <INDENT> self.dbConn.close() <NEW_LINE> os.remove(self.db) <NEW_LINE> <DEDENT> self.dbConn, self.cur = self._connect2db() <NEW_LINE> conn_string = "sqlite:///{db}".format(db=self.db) <NEW_LINE> engine = set_engine(conn_string=conn_string) <NEW_LINE> Base.metadata.create_all(engine) <NEW_LINE> <DEDENT> def res_query(self, query): <NEW_LINE> <INDENT> res_set = [] <NEW_LINE> self.cur.execute(query) <NEW_LINE> field_names = [i[0] for i in self.cur.description] <NEW_LINE> for rec in self.cur: <NEW_LINE> <INDENT> res_dict = {} <NEW_LINE> for cnt in range(len(field_names)): <NEW_LINE> <INDENT> res_dict[field_names[cnt]] = rec[cnt] <NEW_LINE> <DEDENT> res_set.append(res_dict) <NEW_LINE> <DEDENT> return res_set
This class will set up a direct connection to the database. It allows to reset the database, in which case the database will be dropped and recreated, including all tables.
62599050e5267d203ee6cd86
class BaseNNLayer: <NEW_LINE> <INDENT> BATCH_SIZE = 64 <NEW_LINE> @staticmethod <NEW_LINE> def lrelu(x, alpha=0.2): <NEW_LINE> <INDENT> return tf.maximum(alpha*x, x) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def weight_variable(shape, stddev=.1): <NEW_LINE> <INDENT> init = tf.truncated_normal(shape=shape, stddev=stddev) <NEW_LINE> return tf.Variable(init, name="W") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def bias_variable(shape, val=.1): <NEW_LINE> <INDENT> init = tf.constant(val, shape=shape) <NEW_LINE> return tf.Variable(init, name="b")
A basic NN layer containing definitions of general functions
62599050d53ae8145f9198fe
class _CommandLatticePopulateChildren_Array: <NEW_LINE> <INDENT> def GetResources(self): <NEW_LINE> <INDENT> return {'Pixmap' : getIconPath("Lattice2_PopulateChildren_Array.svg"), 'MenuText': QtCore.QT_TRANSLATE_NOOP("Lattice2_PopulateChildren","Populate with Children: Build Array"), 'Accel': "", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Lattice2_PopulateChildren","Populate with Children: Build Array: poplate placements with children so that the first child is not moved. Select a compound, and a placement/array.")} <NEW_LINE> <DEDENT> def Activated(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(FreeCADGui.Selection.getSelection())==0: <NEW_LINE> <INDENT> infoMessage("Populate with Children: Build Array", "Populate with Children: Build Array command. Creates an array from children packed into a compound.\n\n"+ "Please select a compound, and an array of placements. Then invoke the command. It is also allowed to use another array of placements instead of compound.\n\n"+ "Compared to plain 'Populate With Children' command, the placements are treated as being relative to the first placement in the array. As a result, the first child always remains where it was.") <NEW_LINE> return <NEW_LINE> <DEDENT> cmdPopulate_shapes_nonFromTo("First item") <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> msgError(err) <NEW_LINE> <DEDENT> <DEDENT> def IsActive(self): <NEW_LINE> <INDENT> if FreeCAD.ActiveDocument: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Command to create LatticePopulateChildren feature
625990507b25080760ed872b
class OpenvswitchMechanismDriver(mech_agent.SimpleAgentMechanismDriverBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(OpenvswitchMechanismDriver, self).__init__( constants.AGENT_TYPE_OVS, portbindings.VIF_TYPE_OVS, {portbindings.CAP_PORT_FILTER: True, portbindings.OVS_HYBRID_PLUG: True}) <NEW_LINE> <DEDENT> def check_segment_for_agent(self, segment, agent): <NEW_LINE> <INDENT> mappings = agent['configurations'].get('bridge_mappings', {}) <NEW_LINE> tunnel_types = agent['configurations'].get('tunnel_types', []) <NEW_LINE> LOG.debug(_("Checking segment: %(segment)s " "for mappings: %(mappings)s " "with tunnel_types: %(tunnel_types)s"), {'segment': segment, 'mappings': mappings, 'tunnel_types': tunnel_types}) <NEW_LINE> network_type = segment[api.NETWORK_TYPE] <NEW_LINE> if network_type == 'local': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif network_type in tunnel_types: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif network_type in ['flat', 'vlan']: <NEW_LINE> <INDENT> return segment[api.PHYSICAL_NETWORK] in mappings <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Attach to networks using openvswitch L2 agent. The OpenvswitchMechanismDriver integrates the ml2 plugin with the openvswitch L2 agent. Port binding with this driver requires the openvswitch agent to be running on the port's host, and that agent to have connectivity to at least one segment of the port's network.
62599050a219f33f346c7c9d
class CSVDataLine: <NEW_LINE> <INDENT> def __init__(self, name: str, date: str, occurrence: int) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> test_val = int(occurrence) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print("Occurence should be and integer value!") <NEW_LINE> <DEDENT> if len(date) != 13: <NEW_LINE> <INDENT> raise ValueError("Invalid date format YYYY-dd-mm-hh expected!") <NEW_LINE> <DEDENT> self.name = name <NEW_LINE> self.date = date <NEW_LINE> self.occurrence = test_val <NEW_LINE> <DEDENT> def to_csv(self) -> str: <NEW_LINE> <INDENT> return self.name + ";" + str(self.occurrence) + ";" + self.date
Class that specifies the look of data line in processed csv file prepared for database
6259905007d97122c4218140
class Bond(namedtuple("Bond", ["tail", "head"])): <NEW_LINE> <INDENT> def __contains__(self, item): <NEW_LINE> <INDENT> if isinstance(item, BondGraphBase): <NEW_LINE> <INDENT> return self.head[0] is item or self.tail[0] is item <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> c, i = item <NEW_LINE> return any(c == comp and i == idx for comp, idx in self) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False
Stores the connection between two ports. Head and tail are specified to determine orientation Attributes: head: The 'harpoon' end of the power bond and direction of positive $f$ tail: The non-harpoon end, and direction of negative $f$
625990507cff6e4e811b6ed7
class TypeLookup(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.uuid = False <NEW_LINE> self.label = False <NEW_LINE> self.project_uuid = False <NEW_LINE> self.predicate_uuid = False <NEW_LINE> self.predicate_label = False <NEW_LINE> self.content_uuid = False <NEW_LINE> self.content = False <NEW_LINE> self.oc_type = False <NEW_LINE> self.manifest = False <NEW_LINE> self.oc_string = False <NEW_LINE> self.super_classes = False <NEW_LINE> self.show_super_classes = False <NEW_LINE> self.show_predicate_label = False <NEW_LINE> <DEDENT> def get_whole_octype(self, uuid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.manifest = Manifest.objects.get(uuid=uuid) <NEW_LINE> <DEDENT> except Manifest.DoesNotExist: <NEW_LINE> <INDENT> self.manifest = False <NEW_LINE> <DEDENT> if(self.manifest is not False): <NEW_LINE> <INDENT> self.uuid = self.manifest.uuid <NEW_LINE> self.label = self.manifest.label <NEW_LINE> self.project_uuid = self.manifest.project_uuid <NEW_LINE> <DEDENT> self.get_octype_without_manifest(uuid) <NEW_LINE> <DEDENT> def get_octype_without_manifest(self, uuid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.oc_type = OCtype.objects.get(uuid=uuid) <NEW_LINE> <DEDENT> except OCtype.DoesNotExist: <NEW_LINE> <INDENT> self.oc_type = False <NEW_LINE> <DEDENT> if(self.oc_type is not False): <NEW_LINE> <INDENT> self.predicate_uuid = self.oc_type.predicate_uuid <NEW_LINE> self.content_uuid = self.oc_type.content_uuid <NEW_LINE> try: <NEW_LINE> <INDENT> self.oc_string = OCstring.objects.get(uuid=self.content_uuid) <NEW_LINE> <DEDENT> except OCstring.DoesNotExist: <NEW_LINE> <INDENT> self.oc_string = False <NEW_LINE> <DEDENT> if(self.show_predicate_label): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pred_man = Manifest.objects.get(uuid=self.predicate_uuid) <NEW_LINE> self.predicate_label = pred_man.label <NEW_LINE> <DEDENT> except Manifest.DoesNotExist: <NEW_LINE> <INDENT> self.predicate_label = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if(self.oc_string is not False): <NEW_LINE> <INDENT> self.content = self.oc_string.content
Class for helping with derefencing type entities
62599050d6c5a102081e35b9
class Class_Base(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.any_base_class = False <NEW_LINE> <DEDENT> def has_any_base(self): <NEW_LINE> <INDENT> return self.any_base_class
The types of global class variables are kept here.
6259905030dc7b76659a0cca
class TemporaryUserGroup(DeclarativeBase): <NEW_LINE> <INDENT> __tablename__ = "user_group" <NEW_LINE> group_id = Column(Integer, primary_key=True) <NEW_LINE> user_id = Column(Integer, primary_key=True)
temporary sqlalchemy object to help migration
6259905029b78933be26ab10
class PlatformComponent(object): <NEW_LINE> <INDENT> def __init__(self, get_func): <NEW_LINE> <INDENT> self.get_func = get_func <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.instance = self.get_func() <NEW_LINE> return self.instance <NEW_LINE> <DEDENT> def __exit__(self, etype, value, trace): <NEW_LINE> <INDENT> if self.instance is not None: <NEW_LINE> <INDENT> self.instance.destroy()
Context manager to safely handle platform components.
62599050f7d966606f749303
class Assignment(base.Assignment): <NEW_LINE> <INDENT> implements(Iprezencka) <NEW_LINE> users = [] <NEW_LINE> def __init__(self, header="Prezenčka", dateBool=False): <NEW_LINE> <INDENT> self.header = header <NEW_LINE> self.dateBool = dateBool <NEW_LINE> self.users = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return __(self.header) <NEW_LINE> <DEDENT> @property <NEW_LINE> def visitDate(self): <NEW_LINE> <INDENT> return self.dateBool <NEW_LINE> <DEDENT> @property <NEW_LINE> def us(self): <NEW_LINE> <INDENT> return self.users
Portlet assignment. This is what is actually managed through the portlets UI and associated with columns.
6259905023849d37ff85255a
class ARFieldMappingList(Structure): <NEW_LINE> <INDENT> _fields_ = [ ('numItems', c_uint), ('mappingList', POINTER(ARFieldMappingStruct)) ]
"List of 0 or more field mappings (ar.h line 5502).
62599050287bf620b6273086
class VariableValue(Callback): <NEW_LINE> <INDENT> def __init__(self, var_list, period=1, filename=None, precision=2): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.var_list = var_list if isinstance(var_list, list) else [var_list] <NEW_LINE> self.period = period <NEW_LINE> self.precision = precision <NEW_LINE> self.file = sys.stdout if filename is None else open(filename, "w", buffering=1) <NEW_LINE> self.value = None <NEW_LINE> self.epochs_since_last = 0 <NEW_LINE> <DEDENT> def on_train_begin(self): <NEW_LINE> <INDENT> if backend_name == "tensorflow.compat.v1": <NEW_LINE> <INDENT> self.value = self.model.sess.run(self.var_list) <NEW_LINE> <DEDENT> elif backend_name == "tensorflow": <NEW_LINE> <INDENT> self.value = [var.numpy() for var in self.var_list] <NEW_LINE> <DEDENT> elif backend_name == "pytorch": <NEW_LINE> <INDENT> self.value = [var.detach().item() for var in self.var_list] <NEW_LINE> <DEDENT> print( self.model.train_state.epoch, list_to_str(self.value, precision=self.precision), file=self.file, ) <NEW_LINE> self.file.flush() <NEW_LINE> <DEDENT> def on_epoch_end(self): <NEW_LINE> <INDENT> self.epochs_since_last += 1 <NEW_LINE> if self.epochs_since_last >= self.period: <NEW_LINE> <INDENT> self.epochs_since_last = 0 <NEW_LINE> self.on_train_begin() <NEW_LINE> <DEDENT> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self.value
Get the variable values. Args: var_list: A `TensorFlow Variable <https://www.tensorflow.org/api_docs/python/tf/Variable>`_ or a list of TensorFlow Variable. period (int): Interval (number of epochs) between checking values. filename (string): Output the values to the file `filename`. The file is kept open to allow instances to be re-used. If ``None``, output to the screen. precision (int): The precision of variables to display.
6259905063b5f9789fe8660a
class BKTransaction(ATCTContent): <NEW_LINE> <INDENT> schema = BKTransactionSchema <NEW_LINE> __implements__ = (ATCTContent.__implements__) <NEW_LINE> implements(IBKTransaction) <NEW_LINE> meta_type = 'BKTransaction' <NEW_LINE> portal_type = 'BKTransaction' <NEW_LINE> archetype_name = 'BKTransaction' <NEW_LINE> _at_rename_after_creation = True <NEW_LINE> bk_id_prefix = 'tx' <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> def _renameAfterCreation(self, check_auto_id=False): <NEW_LINE> <INDENT> transaction.savepoint(optimistic=True) <NEW_LINE> newId = str(self.getNextUniqueId()) <NEW_LINE> self.log.info('the next value for leocornus bookkeeping sequence: %s', newId) <NEW_LINE> self.setId(self.bk_id_prefix + newId) <NEW_LINE> <DEDENT> security.declarePublic('vocabularyTrxTypes') <NEW_LINE> def vocabularyTrxCategories(self, masterType=None): <NEW_LINE> <INDENT> categories = (masterType == None and self.getCategories(self.transactionType()) or self.getCategories(masterType)) <NEW_LINE> retList = [] <NEW_LINE> for aType in categories: <NEW_LINE> <INDENT> retList.append((aType, aType)) <NEW_LINE> <DEDENT> return DisplayList(retList) <NEW_LINE> <DEDENT> security.declarePublic('transactionTotal') <NEW_LINE> def transactionTotal(self): <NEW_LINE> <INDENT> return self.subtotal() + self.gst() + self.pst() <NEW_LINE> <DEDENT> security.declarePublic('pst') <NEW_LINE> def pst(self): <NEW_LINE> <INDENT> return float(self.getBk_transaction_pst()) <NEW_LINE> <DEDENT> security.declarePublic('gst') <NEW_LINE> def gst(self): <NEW_LINE> <INDENT> return float(self.getBk_transaction_gst()) <NEW_LINE> <DEDENT> security.declarePublic('subtotal') <NEW_LINE> def subtotal(self): <NEW_LINE> <INDENT> return float(self.getBk_transaction_subtotal()) <NEW_LINE> <DEDENT> security.declareProtected(permissions.View, 'transactionDate') <NEW_LINE> def transactionDate(self): <NEW_LINE> <INDENT> txDate = self.getField('bk_transaction_date').get(self) <NEW_LINE> return txDate <NEW_LINE> <DEDENT> security.declareProtected(permissions.View, 'transactionType') <NEW_LINE> def transactionType(self): <NEW_LINE> <INDENT> trxType = self.getField('bk_transaction_type').get(self) <NEW_LINE> return trxType <NEW_LINE> <DEDENT> security.declareProtected(permissions.View, 'transactionCategory') <NEW_LINE> def transactionCategory(self): <NEW_LINE> <INDENT> category = self.getField('bk_transaction_category').get(self) <NEW_LINE> return category
a transaction record.
62599050d53ae8145f9198ff
class Solution: <NEW_LINE> <INDENT> def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: <NEW_LINE> <INDENT> result = [] <NEW_LINE> m = len(matrix) <NEW_LINE> if not m: return result <NEW_LINE> dd = defaultdict(list) <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> n = len(matrix[i]) <NEW_LINE> for j in range(n): <NEW_LINE> <INDENT> dd[i + j].append(matrix[i][j]) <NEW_LINE> <DEDENT> <DEDENT> for k in sorted(dd.keys()): <NEW_LINE> <INDENT> result += dd[k] if k % 2 else dd[k][::-1] <NEW_LINE> <DEDENT> return result
Runtime: 196 ms, faster than 46.02% of Python3 Memory Usage: 17.2 MB, less than 5.05% of Python3
62599050a8ecb033258726af
class GMRES(SolverTag): <NEW_LINE> <INDENT> def vcl_solve_call(self, *args): <NEW_LINE> <INDENT> return _v.iterative_solve(*args) <NEW_LINE> <DEDENT> def __init__(self, tolerance=1e-8, max_iterations=300, krylov_dim=20): <NEW_LINE> <INDENT> self.vcl_tag = _v.gmres_tag(tolerance, max_iterations, krylov_dim) <NEW_LINE> <DEDENT> @property <NEW_LINE> def tolerance(self): <NEW_LINE> <INDENT> return self.vcl_tag.tolerance <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_iterations(self): <NEW_LINE> <INDENT> return self.vcl_tag.max_iterations <NEW_LINE> <DEDENT> @property <NEW_LINE> def krylov_dim(self): <NEW_LINE> <INDENT> return self.vcl_tag.krylov_dim <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_restarts(self): <NEW_LINE> <INDENT> return self.vcl_tag.max_restarts <NEW_LINE> <DEDENT> @property <NEW_LINE> def iters(self): <NEW_LINE> <INDENT> return self.vcl_tag.iters <NEW_LINE> <DEDENT> @property <NEW_LINE> def error(self): <NEW_LINE> <INDENT> return self.vcl_tag.error
Instruct the solver to solve using the GMRES solver. Used for supplying solver parameters.
62599050d486a94d0ba2d461
class Random(Actor): <NEW_LINE> <INDENT> @manage(['lower', 'upper']) <NEW_LINE> def init(self, lower, upper): <NEW_LINE> <INDENT> self.lower = lower <NEW_LINE> self.upper = upper <NEW_LINE> self.setup() <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> self.use('calvinsys.math.rng', shorthand="random") <NEW_LINE> <DEDENT> def did_migrate(self): <NEW_LINE> <INDENT> self.setup() <NEW_LINE> <DEDENT> @condition(action_input=['trigger'], action_output=['integer']) <NEW_LINE> def action(self, trigger): <NEW_LINE> <INDENT> return (self['random'].randrange(self.lower, self.upper), ) <NEW_LINE> <DEDENT> action_priority = (action, ) <NEW_LINE> requires = ['calvinsys.math.rng']
Produce random integer in range [lower ... upper-1] Inputs: trigger : Any token Outputs: integer : Random integer in range [lower ... upper-1]
62599050b830903b9686eec9
class TestAlignmentErrored(TestAlignment): <NEW_LINE> <INDENT> def test_error(self): <NEW_LINE> <INDENT> self.assertEqual(self.aln.error, "Whoops")
Test an Alignment with an error.
625990500fa83653e46f637c
class Search (GeneaProveModel): <NEW_LINE> <INDENT> activity = models.ForeignKey(Activity, null=True, on_delete=models.CASCADE) <NEW_LINE> source = models.ForeignKey( Source, null=True, help_text="The source in which the search was conducted. It could" " be null if this was a general search in a repository for" " instance", on_delete=models.CASCADE) <NEW_LINE> repository = models.ForeignKey(Repository, on_delete=models.CASCADE) <NEW_LINE> searched_for = models.TextField(null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "search"
A specific examination of a source to find information. This is usually linked to a research_objective, through an activity, but not necessarily, if for instance this is an unexpected opportunity
625990506fece00bbaccce58
class BufferTree(gtkextra.Tree): <NEW_LINE> <INDENT> YPAD = 2 <NEW_LINE> XPAD = 2 <NEW_LINE> COLUMNS = [('icon', gtk.gdk.Pixbuf, gtk.CellRendererPixbuf, True, 'pixbuf'), ('name', gobject.TYPE_STRING, gtk.CellRendererText, True, 'markup'), ('file', gobject.TYPE_STRING, None, False, None), ('number', gobject.TYPE_INT, None, False, None)] <NEW_LINE> def populate(self, bufferlist): <NEW_LINE> <INDENT> self.clear() <NEW_LINE> for buf in bufferlist: <NEW_LINE> <INDENT> path = '' <NEW_LINE> if len(buf) > 1: <NEW_LINE> <INDENT> path = '%s' % buf[1] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> nr = int(buf[0]) <NEW_LINE> dirn, name = os.path.split(path) <NEW_LINE> mtype = mimetypes.guess_type(path)[0] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> nr = 0 <NEW_LINE> name, dirn = '' <NEW_LINE> mtype = None <NEW_LINE> <DEDENT> if mtype: <NEW_LINE> <INDENT> mtype = mtype.replace('/','-') <NEW_LINE> im = self.do_get_image(mtype).get_pixbuf() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> im = self.do_get_image('text-plain').get_pixbuf() <NEW_LINE> <DEDENT> markup = self.beautify(name, dirn, path) <NEW_LINE> self.add_item([im, markup, path, nr]) <NEW_LINE> <DEDENT> <DEDENT> def beautify(self, name, dirn, path): <NEW_LINE> <INDENT> if not name: <NEW_LINE> <INDENT> name = 'untitled' <NEW_LINE> <DEDENT> pdir = os.path.split(dirn)[-1] <NEW_LINE> MU = ('<span size="small">' '<span foreground="#0000c0">%s/</span>' '<b>%s</b>' '</span>') <NEW_LINE> dirn = dirn.replace(os.path.expanduser('~'), '~') <NEW_LINE> return MU % (pdir, name) <NEW_LINE> <DEDENT> def set_active(self, buffernumber): <NEW_LINE> <INDENT> for node in self.model: <NEW_LINE> <INDENT> if node[3] == buffernumber: <NEW_LINE> <INDENT> self.view.set_cursor(node.path) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Tree view control for buffer list. The displayed columns are the icon and shortened name. @var YPAD: Increase the default y-padding @var XPAD: Increase the default x-padding @var COLUMNS: The column template
62599050d99f1b3c44d06b38
class Gimmick_Battery(Gimmick): <NEW_LINE> <INDENT> def __init__(self, fobj): <NEW_LINE> <INDENT> self.param_names = ('polarity', 'is_toggle', 'target_id', 'param3', 'param4', 'param5') <NEW_LINE> super(Gimmick_Battery, self).__init__(fobj) <NEW_LINE> self.name = 'Battery'
Gimmick # 22
62599050baa26c4b54d50748
class FlashMessageException(CFMEException): <NEW_LINE> <INDENT> def skip_and_log(self, message="Skipping due to flash message"): <NEW_LINE> <INDENT> logger.error("Flash message error: {}".format(str(self))) <NEW_LINE> pytest.skip("{}: {}".format(message, str(self)))
Raised by functions in :py:mod:`cfme.web_ui.flash`
6259905015baa7234946342a
class Solution: <NEW_LINE> <INDENT> def climbStairs(self, n): <NEW_LINE> <INDENT> if n < 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if n == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if n <= 2: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> prev_prev, prev = 1, 2 <NEW_LINE> result = None <NEW_LINE> for i in xrange(2, n): <NEW_LINE> <INDENT> result = prev + prev_prev <NEW_LINE> prev_prev = prev <NEW_LINE> prev = result <NEW_LINE> <DEDENT> return result
@param n: An integer @return: An integer
62599050009cb60464d029d7
class Team: <NEW_LINE> <INDENT> STATS = {'teamRoster': 0, 'personNames': 1, 'teamScheduleNext': 2, 'teamSchedulePrev': 3, 'teamStats': 4, 'teams': 5} <NEW_LINE> modifiers = {STATS['teamRoster']: 'expand=team.roster', STATS['personNames']: 'expand=person.names', STATS['teamScheduleNext']: 'expand=team.schedule.next', STATS['teamSchedulePrev']: 'expand=team.schedule.previous', STATS['teamStats']: 'expand=team.stats', STATS['teams']: ''} <NEW_LINE> base_url = 'https://statsapi.web.nhl.com/api/v1/' <NEW_LINE> def __init__(self, nhl_id, url=None, content=None): <NEW_LINE> <INDENT> self.url = '' <NEW_LINE> self.name = '' <NEW_LINE> self.content = {} <NEW_LINE> self.nhl_id = nhl_id <NEW_LINE> if url is not None: <NEW_LINE> <INDENT> self.url = url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.nhl_id: <NEW_LINE> <INDENT> self.url = self.base_url + 'teams/{}'.format(self.nhl_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.url = self.base_url + 'teams' <NEW_LINE> <DEDENT> <DEDENT> if content is not None: <NEW_LINE> <INDENT> self.content = content <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.content = get_json_data(self.url) <NEW_LINE> <DEDENT> if self.nhl_id and self.content and 'teams' in self.content: <NEW_LINE> <INDENT> if 'name' in self.content['teams'][0]: <NEW_LINE> <INDENT> self.name = self.content['teams'][0]['name'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_ext_url(self, *modifiers, **kwargs): <NEW_LINE> <INDENT> sep = '?' <NEW_LINE> suffix = '' <NEW_LINE> url = self.url + '/' <NEW_LINE> if kwargs and 'season' in kwargs and kwargs['season']: <NEW_LINE> <INDENT> suffix = '&season={}{}'.format(kwargs['season'], kwargs['season'] + 1) <NEW_LINE> <DEDENT> if isinstance(modifiers, int): <NEW_LINE> <INDENT> return url + sep + self.modifiers[modifiers] + suffix <NEW_LINE> <DEDENT> for elem in modifiers: <NEW_LINE> <INDENT> if isinstance(elem, (int, str, float)): <NEW_LINE> <INDENT> url += sep + self.modifiers[int(elem)] <NEW_LINE> <DEDENT> elif isinstance(elem, dict): <NEW_LINE> <INDENT> for key, value in elem.items(): <NEW_LINE> <INDENT> if isinstance(value, (int, str, float)): <NEW_LINE> <INDENT> url += sep + self.modifiers[key].format(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url += sep + self.modifiers[key].format(*value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> sep = '&' <NEW_LINE> <DEDENT> return url + suffix <NEW_LINE> <DEDENT> def load_ext_url(self, *modifiers, **kwargs): <NEW_LINE> <INDENT> url = self.get_ext_url(*modifiers, **kwargs) <NEW_LINE> self.content = get_json_data(url)
Team class for the nhlapi package
6259905071ff763f4b5e8c47
class TestCartesianToSpherical(unittest.TestCase): <NEW_LINE> <INDENT> def test_cartesian_to_spherical(self): <NEW_LINE> <INDENT> np.testing.assert_almost_equal( cartesian_to_spherical(np.array([3, 1, 6])), np.array([6.78232998, 1.08574654, 0.32175055]), decimal=7) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_spherical(np.array([-1, 9, 16])), np.array([18.38477631, 1.05578119, 1.68145355]), decimal=7) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_spherical(np.array([6.3434, -0.9345, 18.5675])), np.array([19.64342307, 1.23829030, -0.14626640]), decimal=7) <NEW_LINE> <DEDENT> def test_n_dimensional_cartesian_to_spherical(self): <NEW_LINE> <INDENT> vector_i = np.array([3, 1, 6]) <NEW_LINE> vector_o = np.array([6.78232998, 1.08574654, 0.32175055]) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_spherical(vector_i), vector_o, decimal=7) <NEW_LINE> vector_i = np.tile(vector_i, (6, 1)) <NEW_LINE> vector_o = np.tile(vector_o, (6, 1)) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_spherical(vector_i), vector_o, decimal=7) <NEW_LINE> vector_i = np.reshape(vector_i, (2, 3, 3)) <NEW_LINE> vector_o = np.reshape(vector_o, (2, 3, 3)) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_spherical(vector_i), vector_o, decimal=7) <NEW_LINE> <DEDENT> @ignore_numpy_errors <NEW_LINE> def test_nan_cartesian_to_spherical(self): <NEW_LINE> <INDENT> cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] <NEW_LINE> cases = set(permutations(cases * 3, r=3)) <NEW_LINE> for case in cases: <NEW_LINE> <INDENT> vector_i = np.array(case) <NEW_LINE> cartesian_to_spherical(vector_i)
Defines :func:`colour.algebra.coordinates.transformations.cartesian_to_spherical` definition unit tests methods.
6259905076e4537e8c3f0a25
class StockOutTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.se = StockOut(None) <NEW_LINE> self.OP_CODE = self.se.get_opcodes().pop() <NEW_LINE> <DEDENT> def send_args(self, arg_string): <NEW_LINE> <INDENT> return self.se.parse_arguments(self.OP_CODE, arg_string, None) <NEW_LINE> <DEDENT> def test_valid(self): <NEW_LINE> <INDENT> effects, kwargs = self.send_args(" A") <NEW_LINE> self.assertEqual(len(effects), 1) <NEW_LINE> self.assertEqual(effects[0].priority, 'INFO') <NEW_LINE> self.assertEqual(kwargs['stock_out'], 'A') <NEW_LINE> <DEDENT> def test_error_no_arg(self): <NEW_LINE> <INDENT> effects, kwargs = self.send_args(" ") <NEW_LINE> self.assertEqual(len(effects), 1) <NEW_LINE> self.assertEqual(effects[0].priority, 'ERROR') <NEW_LINE> <DEDENT> def test_valid_followed_by_junk(self): <NEW_LINE> <INDENT> effects, kwargs = self.send_args("AW049045") <NEW_LINE> self.assertEqual(len(effects), 1) <NEW_LINE> self.assertEqual(effects[0].priority, 'ERROR') <NEW_LINE> <DEDENT> def test_junk_only(self): <NEW_LINE> <INDENT> effects, kwargs = self.send_args("934><8,.984") <NEW_LINE> self.assertEqual(len(effects), 1) <NEW_LINE> self.assertEqual(effects[0].priority, 'ERROR')
All tests involving a the StockOut app.
62599050fff4ab517ebcecbc
class ScoreRecord(models.Model): <NEW_LINE> <INDENT> student = models.ForeignKey(to='Student', on_delete=models.CASCADE) <NEW_LINE> content = models.TextField(verbose_name='理由') <NEW_LINE> score = models.IntegerField(verbose_name='分值', help_text='违纪扣分,表现优秀加分') <NEW_LINE> user = models.ForeignKey(verbose_name='执行人', to='UserInfo', on_delete=models.CASCADE)
学分记录
625990507cff6e4e811b6edb
class Device(freestyle.FreeStyleHidDevice): <NEW_LINE> <INDENT> def get_meter_info(self): <NEW_LINE> <INDENT> return common.MeterInfo( 'FreeStyle Libre', serial_number=self.get_serial_number(), version_info=( 'Software version: ' + self._get_version(),), native_unit=self.get_glucose_unit()) <NEW_LINE> <DEDENT> def get_serial_number(self): <NEW_LINE> <INDENT> return self._send_text_command(b'$sn?').rstrip('\r\n') <NEW_LINE> <DEDENT> def get_glucose_unit(self): <NEW_LINE> <INDENT> return common.UNIT_MGDL <NEW_LINE> <DEDENT> def get_readings(self): <NEW_LINE> <INDENT> for record in self._get_multirecord(b'$history?'): <NEW_LINE> <INDENT> parsed_record = _parse_record(record, _HISTORY_ENTRY_MAP) <NEW_LINE> if not parsed_record or parsed_record['errors'] != 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield common.Reading( _extract_timestamp(parsed_record), parsed_record['value'], comment='(Sensor)') <NEW_LINE> <DEDENT> for record in self._get_multirecord(b'$arresult?'): <NEW_LINE> <INDENT> reading = _parse_arresult(record) <NEW_LINE> if reading: <NEW_LINE> <INDENT> yield reading
Glucometer driver for FreeStyle Libre devices.
62599050498bea3a75a58fc0
class Clock(Scheduler): <NEW_LINE> <INDENT> pass
Schedules stuff like a Scheduler, and includes time limiting functions WIP
62599050b7558d5895464977
class Output2Excl(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def process(cls, file, total_ent_list, sent_list, entity_relationship): <NEW_LINE> <INDENT> total_et = dict() <NEW_LINE> for entity_list in total_ent_list: <NEW_LINE> <INDENT> et_index = 0 <NEW_LINE> for entity in entity_list: <NEW_LINE> <INDENT> et_id = entity['id'] <NEW_LINE> total_et[et_id] = entity <NEW_LINE> entity['original'] = ''.join(['[', str(et_index), ']', entity['original']]) <NEW_LINE> et_index += 1 <NEW_LINE> <DEDENT> <DEDENT> et_rel = defaultdict(dict) <NEW_LINE> all_et_relship = entity_relationship.get_all_relationship() <NEW_LINE> et_relship = all_et_relship[0] <NEW_LINE> for s_et_rel in et_relship: <NEW_LINE> <INDENT> f_id = s_et_rel['first_id'] <NEW_LINE> s_id = s_et_rel['second_id'] <NEW_LINE> rel_type = s_et_rel['relation'] <NEW_LINE> et_rel[f_id][s_id] = rel_type <NEW_LINE> et_rel[s_id][f_id] = rel_type <NEW_LINE> <DEDENT> sentence_entity_list_obj = zip(total_ent_list, sent_list) <NEW_LINE> Output2Excl.save_result(file, sentence_entity_list_obj, total_et, et_rel) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def save_result(cls, file, sentence_entity_list_obj, total_et_data, rel_data): <NEW_LINE> <INDENT> wbk = xlwt.Workbook() <NEW_LINE> sheet = wbk.add_sheet('sheet 1') <NEW_LINE> cls.write_head(sheet) <NEW_LINE> line_no = 1 <NEW_LINE> for entity_list, sentence_value in sentence_entity_list_obj: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(entity_list): <NEW_LINE> <INDENT> for et in entity_list: <NEW_LINE> <INDENT> tmp_et = EntityStructure() <NEW_LINE> tmp_et.set_value(et) <NEW_LINE> tmp_et.set_rel_value(total_et_data, rel_data) <NEW_LINE> cls.save_rs(sheet, '--', '--', sentence_value, tmp_et, line_no) <NEW_LINE> line_no += 1 <NEW_LINE> <DEDENT> line_no += 1 <NEW_LINE> <DEDENT> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> print('处理字段时出现异常,就诊数据路径'.format()) <NEW_LINE> print(ex.with_traceback()) <NEW_LINE> <DEDENT> <DEDENT> wbk.save(os.path.join(file + '.xls')) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def write_head(cls, sheet): <NEW_LINE> <INDENT> elements = head_line.split('@') <NEW_LINE> for ele_index, ele in enumerate(elements): <NEW_LINE> <INDENT> sheet.write(0, ele_index, ele) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def save_rs(cls, sheet, table_name, column_name, sentence, et, line_no): <NEW_LINE> <INDENT> sheet.write(line_no, 0, sentence) <NEW_LINE> et_value = et.get_rs() <NEW_LINE> et_values = et_value.split('@') <NEW_LINE> for ele_index, ele in enumerate(et_values): <NEW_LINE> <INDENT> sheet.write(line_no, 1 + ele_index, ele)
将依存树解析结果输出到excel进行可视化
62599050d7e4931a7ef3d519
class ContextParserCache(Cache): <NEW_LINE> <INDENT> def get_context_parser(self, parser_module_name): <NEW_LINE> <INDENT> logger.debug("starting") <NEW_LINE> parser_function = self.get(parser_module_name, lambda: load_the_parser(parser_module_name)) <NEW_LINE> logger.debug("done") <NEW_LINE> return parser_function
Get functions from the pypeloader cache.
6259905071ff763f4b5e8c48
class copy_img(object): <NEW_LINE> <INDENT> def __init__(self, xml_dir, img_orginal_dir, img_copy_dir): <NEW_LINE> <INDENT> self.xml_dir = xml_dir <NEW_LINE> self.img_orginal_dir = img_orginal_dir <NEW_LINE> self.img_copy_dir = img_copy_dir <NEW_LINE> <DEDENT> def copy_imgs(self): <NEW_LINE> <INDENT> for file in tqdm(os.listdir(self.xml_dir)): <NEW_LINE> <INDENT> if str(file).endswith("xml"): <NEW_LINE> <INDENT> file = str(file).split(".")[0] <NEW_LINE> try: <NEW_LINE> <INDENT> img_orginal_file = os.path.join(self.img_orginal_dir, file + ".jpg") <NEW_LINE> img_copy_file = os.path.join(self.img_copy_dir, file + ".jpg") <NEW_LINE> shutil.copy(img_orginal_file, img_copy_file) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print(file)
按xml文件中的文件名称,从所有图片中拷贝部分至另一个文件夹
62599050e76e3b2f99fd9ea0
class Squirrel(models.Model): <NEW_LINE> <INDENT> AM, PM = 'AM', 'PM' <NEW_LINE> SHIFT_CHOICES = ((AM, 'AM'), (PM, 'PM')) <NEW_LINE> x = models.FloatField('X', help_text='Geo Latitude') <NEW_LINE> y = models.FloatField('Y', help_text='Geo Longitude') <NEW_LINE> unique_squirrel_id = models.CharField('Unique Squirrel ID', max_length=255, primary_key=True, help_text='Squirrel Identifier') <NEW_LINE> hectare = models.CharField('Hectare', max_length=255, help_text='Park Hectare Identifier') <NEW_LINE> shift = models.CharField('Shift', max_length=2, choices=SHIFT_CHOICES) <NEW_LINE> date = models.DateField('Date') <NEW_LINE> hectare_squirrel_number = models.IntegerField('Hectare Squirrel Number', null=True, blank=True) <NEW_LINE> age = models.CharField('Age', max_length=255, blank=True) <NEW_LINE> primary_fur_color = models.CharField('Primary Fur Color', max_length=255, blank=True) <NEW_LINE> highlight_fur_color = models.CharField('Highlight Fur Color', max_length=255, blank=True) <NEW_LINE> combination_of_primary_and_highlight_color = models.CharField('Combination of Primary and Highlight Color', max_length=255, blank=True) <NEW_LINE> color_notes = models.CharField('Color notes', max_length=255, blank=True) <NEW_LINE> location = models.CharField('Location', max_length=255, blank=True) <NEW_LINE> above_ground_sighter_measurement = models.CharField('Above Ground Sighter Measurement', max_length=255, blank=True) <NEW_LINE> specific_location = models.CharField('Specific Location', max_length=255, blank=True) <NEW_LINE> running = models.BooleanField('Running') <NEW_LINE> chasing = models.BooleanField('Chasing') <NEW_LINE> climbing = models.BooleanField('Climbing') <NEW_LINE> eating = models.BooleanField('Eating') <NEW_LINE> foraging = models.BooleanField('Foraging') <NEW_LINE> other_activities = models.CharField('Other Activities', max_length=255, blank=True) <NEW_LINE> kuks = models.BooleanField('Kuks') <NEW_LINE> quaas = models.BooleanField('Quaas') <NEW_LINE> moans = models.BooleanField('Moans') <NEW_LINE> tail_flags = models.BooleanField('Tail flags') <NEW_LINE> tail_twitches = models.BooleanField('Tail twitches') <NEW_LINE> approaches = models.BooleanField('Approaches') <NEW_LINE> indifferent = models.BooleanField('Indifferent') <NEW_LINE> runs_from = models.BooleanField('Runs from') <NEW_LINE> other_interactions = models.CharField('Other Interactions', max_length=255, blank=True) <NEW_LINE> lat_long = models.CharField('Lat/Long', max_length=255, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f'<ID: {self.unique_squirrel_id}> {self.lat_long}'
Model class for storing sighted squirrel information
625990508e71fb1e983bcf66
class TestList(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testList(self): <NEW_LINE> <INDENT> model = swagger_client.models.list.List()
List unit test stubs
6259905063b5f9789fe8660e
class UnetSkipConnectionBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False, conv=nn.Conv2d, deconv=nn.ConvTranspose2d): <NEW_LINE> <INDENT> super(UnetSkipConnectionBlock, self).__init__() <NEW_LINE> self.outermost = outermost <NEW_LINE> if type(norm_layer) == functools.partial: <NEW_LINE> <INDENT> use_bias = (norm_layer.func == nn.InstanceNorm2d) or ( norm_layer.func == nn.InstanceNorm3d) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> use_bias = (norm_layer == nn.InstanceNorm2d) or ( norm_layer == nn.InstanceNorm3d) <NEW_LINE> <DEDENT> if input_nc is None: <NEW_LINE> <INDENT> input_nc = outer_nc <NEW_LINE> <DEDENT> downconv = conv( input_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) <NEW_LINE> downrelu = nn.LeakyReLU(0.2, True) <NEW_LINE> downnorm = norm_layer(inner_nc) <NEW_LINE> uprelu = nn.ReLU(True) <NEW_LINE> upnorm = norm_layer(outer_nc) <NEW_LINE> if outermost: <NEW_LINE> <INDENT> upconv = deconv( inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1) <NEW_LINE> down = [downconv] <NEW_LINE> up = [uprelu, upconv, nn.Tanh()] <NEW_LINE> model = down + [submodule] + up <NEW_LINE> <DEDENT> elif innermost: <NEW_LINE> <INDENT> upconv = deconv( inner_nc, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) <NEW_LINE> down = [downrelu, downconv] <NEW_LINE> up = [uprelu, upconv, upnorm] <NEW_LINE> model = down + up <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> upconv = deconv( inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) <NEW_LINE> down = [downrelu, downconv, downnorm] <NEW_LINE> up = [uprelu, upconv, upnorm] <NEW_LINE> if use_dropout: <NEW_LINE> <INDENT> model = down + [submodule] + up + [nn.Dropout(0.5)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> model = down + [submodule] + up <NEW_LINE> <DEDENT> <DEDENT> self.model = nn.Sequential(*model) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> if self.outermost: <NEW_LINE> <INDENT> return self.model(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return torch.cat([x, self.model(x)], 1)
Unet Skip Connection built recursively by taking a submodule and generating a downsample and upsample block over it. These blocks are then connected in a short circuit.
6259905094891a1f408ba145
class VariableList(ListResource): <NEW_LINE> <INDENT> def __init__(self, version, service_sid, environment_sid): <NEW_LINE> <INDENT> super(VariableList, self).__init__(version) <NEW_LINE> self._solution = {'service_sid': service_sid, 'environment_sid': environment_sid, } <NEW_LINE> self._uri = '/Services/{service_sid}/Environments/{environment_sid}/Variables'.format(**self._solution) <NEW_LINE> <DEDENT> def stream(self, limit=None, page_size=None): <NEW_LINE> <INDENT> limits = self._version.read_limits(limit, page_size) <NEW_LINE> page = self.page(page_size=limits['page_size'], ) <NEW_LINE> return self._version.stream(page, limits['limit'], limits['page_limit']) <NEW_LINE> <DEDENT> def list(self, limit=None, page_size=None): <NEW_LINE> <INDENT> return list(self.stream(limit=limit, page_size=page_size, )) <NEW_LINE> <DEDENT> def page(self, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) <NEW_LINE> response = self._version.page( 'GET', self._uri, params=params, ) <NEW_LINE> return VariablePage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def get_page(self, target_url): <NEW_LINE> <INDENT> response = self._version.domain.twilio.request( 'GET', target_url, ) <NEW_LINE> return VariablePage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def create(self, key, value): <NEW_LINE> <INDENT> data = values.of({'Key': key, 'Value': value, }) <NEW_LINE> payload = self._version.create( 'POST', self._uri, data=data, ) <NEW_LINE> return VariableInstance( self._version, payload, service_sid=self._solution['service_sid'], environment_sid=self._solution['environment_sid'], ) <NEW_LINE> <DEDENT> def get(self, sid): <NEW_LINE> <INDENT> return VariableContext( self._version, service_sid=self._solution['service_sid'], environment_sid=self._solution['environment_sid'], sid=sid, ) <NEW_LINE> <DEDENT> def __call__(self, sid): <NEW_LINE> <INDENT> return VariableContext( self._version, service_sid=self._solution['service_sid'], environment_sid=self._solution['environment_sid'], sid=sid, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Serverless.V1.VariableList>'
PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
62599050379a373c97d9a4cc
class Keys(NamedTuple): <NEW_LINE> <INDENT> pid: int <NEW_LINE> service: str
Dictionary key tuple.
62599050fff4ab517ebcecbe
class Front(SubredditListingMixin): <NEW_LINE> <INDENT> def __init__(self, reddit: Reddit): <NEW_LINE> <INDENT> super().__init__(reddit, _data=None) <NEW_LINE> self._path = "/" <NEW_LINE> <DEDENT> def best( self, **generator_kwargs: Union[str, int] ) -> Generator[Submission, None, None]: <NEW_LINE> <INDENT> return ListingGenerator( self._reddit, urljoin(self._path, "best"), **generator_kwargs )
Front is a Listing class that represents the front page.
6259905024f1403a9268631e
class ModelView(QWidget, Ui_ModelView): <NEW_LINE> <INDENT> __author__ = "Moritz Wade" <NEW_LINE> __contact__ = "[email protected]" <NEW_LINE> __copyright__ = "Zuse Institute Berlin 2011" <NEW_LINE> def __init__(self, parent, bioParkinController): <NEW_LINE> <INDENT> if not parent or not bioParkinController: <NEW_LINE> <INDENT> logging.debug("ModelView: Can't instantiate without parent and controller.") <NEW_LINE> return <NEW_LINE> <DEDENT> super(ModelView, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self._models = OrderedDict() <NEW_LINE> self._modelIndexes = OrderedDict() <NEW_LINE> self.bioParkinController = bioParkinController <NEW_LINE> self.bioParkinController.activeModelChanged.connect(self.on_activeModelChanged) <NEW_LINE> self.bioParkinController.modelClosed.connect(self.on_modelClosed) <NEW_LINE> self._modelListWidget.currentItemChanged.connect(self.on_currentItemChanged) <NEW_LINE> <DEDENT> def on_activeModelChanged(self, modelController): <NEW_LINE> <INDENT> if not modelController: <NEW_LINE> <INDENT> self._modelListWidget.setCurrentIndex(None) <NEW_LINE> return <NEW_LINE> <DEDENT> filename = QFileInfo(modelController.filename).fileName() <NEW_LINE> if self._modelIndexes.has_key(filename): <NEW_LINE> <INDENT> self._modelListWidget.item(self._modelIndexes[filename]).setSelected(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._modelListWidget.addItem(filename) <NEW_LINE> self._models[filename] = modelController <NEW_LINE> index = self._modelListWidget.count() - 1 <NEW_LINE> self._modelIndexes[filename] = index <NEW_LINE> self._modelListWidget.item(index).setSelected(True) <NEW_LINE> <DEDENT> <DEDENT> def on_modelClosed(self, modelController): <NEW_LINE> <INDENT> if not modelController: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> filename = QFileInfo(modelController.filename).fileName() <NEW_LINE> if self._modelIndexes.has_key(filename): <NEW_LINE> <INDENT> index = self._modelIndexes[filename] <NEW_LINE> item = self._modelListWidget.takeItem(index) <NEW_LINE> del item <NEW_LINE> self._models.pop(filename) <NEW_LINE> self._modelIndexes.pop(filename) <NEW_LINE> if self._modelListWidget.count() > 0: <NEW_LINE> <INDENT> self._modelListWidget.item(0).setSelected(True) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def on_currentItemChanged(self, newItem, previousItem): <NEW_LINE> <INDENT> if newItem: <NEW_LINE> <INDENT> filename = newItem.data(0) <NEW_LINE> if self._models.has_key(filename): <NEW_LINE> <INDENT> modelController = self._models[filename] <NEW_LINE> self.bioParkinController.activeModelChanged.emit(modelController)
Provides a list widget that connects to the main BioPARKIN controller, displays all current models and allows to select any of them. It is hooked up to events of the BioPARKIN controller so it is only loosely coupled and not a necessary part of the UI at all (e.g. the NetworkView can also be used to show and select current models). @since: 2011-05-16
625990506fece00bbaccce5c
class Question(Base): <NEW_LINE> <INDENT> __tablename__ = 'questions' <NEW_LINE> id = Column( Integer, primary_key=True) <NEW_LINE> question_timestamp = Column( DateTime, nullable=False) <NEW_LINE> subject = Column( String, nullable=False) <NEW_LINE> text = Column( String, nullable=False) <NEW_LINE> reply_timestamp = Column( DateTime, nullable=True) <NEW_LINE> ignored = Column( Boolean, nullable=False, default=False) <NEW_LINE> reply_subject = Column( String, nullable=True) <NEW_LINE> reply_text = Column( String, nullable=True) <NEW_LINE> user_id = Column( Integer, ForeignKey(User.id, onupdate="CASCADE", ondelete="CASCADE"), nullable=False, index=True) <NEW_LINE> user = relationship( User, backref=backref('questions', order_by=[question_timestamp, reply_timestamp], cascade="all, delete-orphan", passive_deletes=True))
Class to store a private question from the user to the managers, and its answer.
62599050d99f1b3c44d06b3c
class Select(UnaryOperator): <NEW_LINE> <INDENT> def __init__(self, condition=None, input=None): <NEW_LINE> <INDENT> self.condition = condition <NEW_LINE> UnaryOperator.__init__(self, input) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (UnaryOperator.__eq__(self, other) and self.condition == other.condition) <NEW_LINE> <DEDENT> def num_tuples(self): <NEW_LINE> <INDENT> return int(self.input.num_tuples() * 0.5) <NEW_LINE> <DEDENT> def shortStr(self): <NEW_LINE> <INDENT> if isinstance(self.condition, dict): <NEW_LINE> <INDENT> cond = self.condition["condition"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cond = self.condition <NEW_LINE> <DEDENT> return "%s(%s)" % (self.opname(), cond) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{op}({cond!r}, {inp!r})".format(op=self.opname(), cond=self.condition, inp=self.input) <NEW_LINE> <DEDENT> def copy(self, other): <NEW_LINE> <INDENT> self.condition = other.condition <NEW_LINE> UnaryOperator.copy(self, other) <NEW_LINE> <DEDENT> def scheme(self): <NEW_LINE> <INDENT> return self.input.scheme() <NEW_LINE> <DEDENT> def get_unnamed_condition(self): <NEW_LINE> <INDENT> return expression.ensure_unnamed(self.condition, self.input)
Logical selection operator
6259905007f4c71912bb08d7
class TestKillProcess(unittest.TestCase): <NEW_LINE> <INDENT> def test_kill_process(self): <NEW_LINE> <INDENT> s = Solution() <NEW_LINE> self.assertEqual(sorted([5, 10]), sorted(s.killProcess([1, 3, 10, 5], [3, 0, 5, 3], 5)))
Test q582_kill_process.py
625990500c0af96317c577b1
class SonobuoyStatus: <NEW_LINE> <INDENT> def __init__(self, status_json: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> status = json.loads(status_json) <NEW_LINE> self.status: Status = Status(status["status"]) <NEW_LINE> self.tar_info: str = status["tar-info"] <NEW_LINE> self.plugins: Dict[str, Dict[str, Any]] = {} <NEW_LINE> for plugin in status["plugins"]: <NEW_LINE> <INDENT> self.plugins[plugin["plugin"]] = plugin <NEW_LINE> <DEDENT> <DEDENT> except json.decoder.JSONDecodeError: <NEW_LINE> <INDENT> logger.warning("json decoding of status failed: %s", status_json) <NEW_LINE> self.status = Status.ERROR <NEW_LINE> self.plugins = {} <NEW_LINE> <DEDENT> <DEDENT> def plugin_list(self): <NEW_LINE> <INDENT> return list(self.plugins.keys()) <NEW_LINE> <DEDENT> def plugin(self, plugin: str): <NEW_LINE> <INDENT> return self.plugins[plugin] <NEW_LINE> <DEDENT> def plugin_status(self, plugin: str) -> "Status": <NEW_LINE> <INDENT> status_string = self.plugin(plugin)["status"] <NEW_LINE> return Status(status_string) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> status: List[str] = [] <NEW_LINE> for plugin_id in self.plugin_list(): <NEW_LINE> <INDENT> status.append(f"{plugin_id}:{self.plugin_status(plugin_id)}") <NEW_LINE> <DEDENT> return f"[{']['.join(status)}]"
A status output from the sonobuoy CLI.
625990508da39b475be04687
class Resume(base.Command): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> parsers.AddQueueResourceArg(parser, 'to resume') <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> queues_client = queues.Queues() <NEW_LINE> queue_ref = parsers.ParseQueue(args.queue) <NEW_LINE> queues_client.Resume(queue_ref) <NEW_LINE> log.status.Print('Resumed queue [{}].'.format(queue_ref.Name()))
Request to resume a paused or disabled queue.
62599050507cdc57c63a6241
class Weather: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.temperature = 70.0 <NEW_LINE> self.status = "sunny" <NEW_LINE> <DEDENT> def process_message(self, message): <NEW_LINE> <INDENT> value = message.value() <NEW_LINE> if value: <NEW_LINE> <INDENT> self.temperature = value.get("temperature") <NEW_LINE> self.status = value.get("status")
Defines the Weather model
625990504e696a045264e871
class TestCopyableTraitNames( unittest.TestCase ): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> foo = Foo() <NEW_LINE> self.names = foo.copyable_trait_names() <NEW_LINE> return <NEW_LINE> <DEDENT> def test_events_not_copyable(self): <NEW_LINE> <INDENT> self.failIf( 'e' in self.names ) <NEW_LINE> <DEDENT> def test_delegate_not_copyable(self): <NEW_LINE> <INDENT> self.failIf( 'd' in self.names ) <NEW_LINE> <DEDENT> def test_read_only_property_not_copyable(self): <NEW_LINE> <INDENT> self.failIf( 'p_ro' in self.names ) <NEW_LINE> <DEDENT> def test_any_copyable(self): <NEW_LINE> <INDENT> self.failUnless( 'a' in self.names ) <NEW_LINE> <DEDENT> def test_bool_copyable(self): <NEW_LINE> <INDENT> self.failUnless( 'b' in self.names ) <NEW_LINE> <DEDENT> def test_str_copyable(self): <NEW_LINE> <INDENT> self.failUnless( 's' in self.names ) <NEW_LINE> <DEDENT> def test_instance_copyable(self): <NEW_LINE> <INDENT> self.failUnless( 'i' in self.names ) <NEW_LINE> <DEDENT> def test_property_copyable(self): <NEW_LINE> <INDENT> self.failUnless( 'p' in self.names )
Validate that copyable_trait_names returns the appropraite result.
62599050b57a9660fecd2f1f
class GeneratorIO(BufferedIOBase): <NEW_LINE> <INDENT> def __init__(self, generator, length=None): <NEW_LINE> <INDENT> self._generator = generator <NEW_LINE> self._next_chunk = bytearray() <NEW_LINE> self._length = length <NEW_LINE> <DEDENT> def read(self, num_bytes=None): <NEW_LINE> <INDENT> if self._next_chunk is None: <NEW_LINE> <INDENT> return b'' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if num_bytes is None: <NEW_LINE> <INDENT> rv = self._next_chunk[:] <NEW_LINE> self._next_chunk[:] = next(self._generator) <NEW_LINE> return bytes(rv) <NEW_LINE> <DEDENT> while len(self._next_chunk) < num_bytes: <NEW_LINE> <INDENT> self._next_chunk += next(self._generator) <NEW_LINE> <DEDENT> rv = self._next_chunk[:num_bytes] <NEW_LINE> self._next_chunk[:] = self._next_chunk[num_bytes:] <NEW_LINE> return bytes(rv) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> rv = self._next_chunk[:] <NEW_LINE> self._next_chunk = None <NEW_LINE> return bytes(rv) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> if self._length is not None: <NEW_LINE> <INDENT> return self._length <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise UnsupportedOperation
Wrapper around a generator to act as a file-like object.
62599050e76e3b2f99fd9ea2
class SetupCommand(Command): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(SetupCommand, self).__init__( name='setup', help_short='Setup the build environment.', *args, **kwargs) <NEW_LINE> <DEDENT> def execute(self, args, cwd): <NEW_LINE> <INDENT> print('Setting up the build environment...') <NEW_LINE> print('') <NEW_LINE> print('- git submodule init / update...') <NEW_LINE> shell_call('git submodule init') <NEW_LINE> shell_call('git submodule update') <NEW_LINE> print('') <NEW_LINE> if os.path.exists('/Cygwin.bat'): <NEW_LINE> <INDENT> print('- setting filemode off on cygwin...') <NEW_LINE> shell_call('git config core.filemode false') <NEW_LINE> shell_call('git submodule foreach git config core.filemode false') <NEW_LINE> print('') <NEW_LINE> <DEDENT> if (not os.path.exists('third_party/ninja/ninja') and not os.path.exists('third_party/ninja/ninja.exe')): <NEW_LINE> <INDENT> print('- preparing ninja...') <NEW_LINE> os.chdir('third_party/ninja') <NEW_LINE> extra_args = '' <NEW_LINE> shell_call('python configure.py --bootstrap ' + extra_args) <NEW_LINE> os.chdir(cwd) <NEW_LINE> print('') <NEW_LINE> <DEDENT> print('- Building binutils...') <NEW_LINE> if sys.platform == 'win32': <NEW_LINE> <INDENT> print('WARNING: binutils build not supported yet') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shell_call('third_party/binutils/build.sh') <NEW_LINE> <DEDENT> print('') <NEW_LINE> post_update_deps('debug') <NEW_LINE> post_update_deps('release') <NEW_LINE> print('- running gyp...') <NEW_LINE> run_all_gyps() <NEW_LINE> print('') <NEW_LINE> print('Success!') <NEW_LINE> return 0
'setup' command.
62599050dd821e528d6da37d
class StateMiddleware: <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> state = models.BaseVersionedModel.PUBLISHED <NEW_LINE> if request.user.is_staff: <NEW_LINE> <INDENT> state = request.session.get(SESSION_KEY, models.BaseVersionedModel.DRAFT) <NEW_LINE> <DEDENT> manager.activate(state) <NEW_LINE> <DEDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> manager.deactivate() <NEW_LINE> return response
Middleware that sets state to published unless an active staff user is logged in and has flagged show drafts in their session.
62599050d486a94d0ba2d467
class MongoDB(Database): <NEW_LINE> <INDENT> def __init__(self, mongodburi): <NEW_LINE> <INDENT> self._description = 'mongo' <NEW_LINE> db_name = mongodburi[mongodburi.rfind('/') + 1:] <NEW_LINE> self._mongo = MongoClient(mongodburi)[db_name][COLLECTION] <NEW_LINE> <DEDENT> def __contains__(self, uid): <NEW_LINE> <INDENT> return self._mongo.find_one(uid) is not None <NEW_LINE> <DEDENT> def get(self, uid): <NEW_LINE> <INDENT> entry = self._mongo.find_one(uid) <NEW_LINE> return zlib.decompress(entry['code']) if entry is not None else None <NEW_LINE> <DEDENT> def put(self, code, uid=None): <NEW_LINE> <INDENT> if uid is None: <NEW_LINE> <INDENT> uid = Database.hash_(code) <NEW_LINE> <DEDENT> if uid not in self: <NEW_LINE> <INDENT> self._mongo.insert(Database.make_ds(uid, Binary(zlib.compress(code))), safe=True) <NEW_LINE> <DEDENT> return uid
MongoDB abstraction.
625990503539df3088ecd744
class StudentUpdateView(UpdateView): <NEW_LINE> <INDENT> model = Student <NEW_LINE> template_name = 'students/students_edit.html' <NEW_LINE> form_class = StudentUpdateForm <NEW_LINE> def get_success_url(self): <NEW_LINE> <INDENT> return u'%s?success=1&status_message=Студента було успішно збережено!' % reverse('home') <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.POST.get('cancel_button'): <NEW_LINE> <INDENT> return HttpResponseRedirect( u'%s?success=0&status_message=Редагування студента відмінено!' % reverse('home')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(StudentUpdateView, self).post(request, *args, **kwargs)
Class for editing students
62599050a219f33f346c7ca5
class Channel: <NEW_LINE> <INDENT> def __init__(self, reader, writer): <NEW_LINE> <INDENT> self.reader = reader <NEW_LINE> self.writer = writer <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.writer.close()
encapsulate the (reader, writer) stream pair
62599050baa26c4b54d5074e
class ToolError(Exception): <NEW_LINE> <INDENT> pass
Exception raised for problems during tooling setup
62599050b5575c28eb71371b
class NewGameForm(messages.Message): <NEW_LINE> <INDENT> user_name = messages.StringField(1, required=True) <NEW_LINE> attempts = messages.IntegerField(2, default=6)
Used to create a new game
625990500c0af96317c577b2
class AFDEndpoint(TrackedResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'system_data': {'readonly': True}, 'location': {'required': True}, 'origin_response_timeout_seconds': {'minimum': 16}, 'provisioning_state': {'readonly': True}, 'deployment_status': {'readonly': True}, 'host_name': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'origin_response_timeout_seconds': {'key': 'properties.originResponseTimeoutSeconds', 'type': 'int'}, 'enabled_state': {'key': 'properties.enabledState', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'deployment_status': {'key': 'properties.deploymentStatus', 'type': 'str'}, 'host_name': {'key': 'properties.hostName', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, origin_response_timeout_seconds: Optional[int] = None, enabled_state: Optional[Union[str, "EnabledState"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(AFDEndpoint, self).__init__(location=location, tags=tags, **kwargs) <NEW_LINE> self.origin_response_timeout_seconds = origin_response_timeout_seconds <NEW_LINE> self.enabled_state = enabled_state <NEW_LINE> self.provisioning_state = None <NEW_LINE> self.deployment_status = None <NEW_LINE> self.host_name = None
CDN endpoint is the entity within a CDN profile containing configuration information such as origin, protocol, content caching and delivery behavior. The AzureFrontDoor endpoint uses the URL format :code:`<endpointname>`.azureedge.net. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Resource ID. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar system_data: Read only system data. :vartype system_data: ~azure.mgmt.cdn.models.SystemData :param location: Required. Resource location. :type location: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param origin_response_timeout_seconds: Send and receive timeout on forwarding request to the origin. When timeout is reached, the request fails and returns. :type origin_response_timeout_seconds: int :param enabled_state: Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled'. Possible values include: "Enabled", "Disabled". :type enabled_state: str or ~azure.mgmt.cdn.models.EnabledState :ivar provisioning_state: Provisioning status. Possible values include: "Succeeded", "Failed", "Updating", "Deleting", "Creating". :vartype provisioning_state: str or ~azure.mgmt.cdn.models.AfdProvisioningState :ivar deployment_status: Possible values include: "NotStarted", "InProgress", "Succeeded", "Failed". :vartype deployment_status: str or ~azure.mgmt.cdn.models.DeploymentStatus :ivar host_name: The host name of the endpoint structured as {endpointName}.{DNSZone}, e.g. contoso.azureedge.net. :vartype host_name: str
625990508e7ae83300eea536
class PDAError(AutomatonError): <NEW_LINE> <INDENT> pass
The base class for all PDA-related errors.
62599050009cb60464d029dd