code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class TestCommunicatorDelegate(ProcessControllerDelegate): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def launch_mode(self): <NEW_LINE> <INDENT> return self.LAUNCH_MODE_CHILD <NEW_LINE> <DEDENT> def process_filedescriptors(self): <NEW_LINE> <INDENT> return (None, subprocess.PIPE, subprocess.PIPE) <NEW_LINE> <DEDENT> def communicate(self, process): <NEW_LINE> <INDENT> if process.stdout is None: <NEW_LINE> <INDENT> return super(TestCommunicatorDelegate, self).communicate(process) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> err_lines = process.stderr.readlines() <NEW_LINE> assert not err_lines <NEW_LINE> lines = process.stdout.readlines() <NEW_LINE> assert len(lines) == 1 <NEW_LINE> tmpfile = Path(lines[0].decode().strip()) <NEW_LINE> tmpfile.remove() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> res = super(TestCommunicatorDelegate, self).communicate(process) <NEW_LINE> <DEDENT> assert res.returncode == 0, "There should have been no error" <NEW_LINE> return res | Communicate with a process and see how that works | 62598feafbf16365ca79485b |
class SherpaRomeo(utopia.document.Annotator, utopia.document.Visualiser): <NEW_LINE> <INDENT> apiKey = 'TGb5fUBjk9Q' <NEW_LINE> def on_ready_event(self, document): <NEW_LINE> <INDENT> issn = utopia.tools.utils.metadata(document, 'publication-issn') <NEW_LINE> doi = utopia.tools.utils.metadata(document, 'identifiers[doi]') <NEW_LINE> if issn is not None: <NEW_LINE> <INDENT> params = { 'versions': 'all', 'issn': issn, 'ak': self.apiKey } <NEW_LINE> url = 'http://www.sherpa.ac.uk/romeo/api29.php?' + urllib.urlencode(params) <NEW_LINE> srResponse = urllib2.urlopen(url, timeout=8) <NEW_LINE> srData = srResponse.read() <NEW_LINE> root = etree.fromstring(srData) <NEW_LINE> colour = root.find('publishers/publisher/romeocolour') <NEW_LINE> if colour is not None: <NEW_LINE> <INDENT> a = spineapi.Annotation() <NEW_LINE> a['concept'] = 'SherpaRomeo' <NEW_LINE> a['property:doi'] = doi <NEW_LINE> a['property:name'] = 'Sherpa/RoMEO' <NEW_LINE> a['property:sourceDatabase'] = 'sherparomeo' <NEW_LINE> a['property:sourceDescription'] = '<p><a href="http://www.sherpa.ac.uk/romeo/">SHERPA/RoMEO</a> provides information about publisher copyright policies for this article.</p>' <NEW_LINE> a['property:description'] = "Archiving status is '" +colour.text+ "'." <NEW_LINE> explanation = {} <NEW_LINE> explanation['green'] = "the author can archive pre-print <em>and</em> post-print or publisher's version/PDF" <NEW_LINE> explanation['blue'] = "the author can archive post-print (i.e. final draft post-refereeing) or publisher's version/PDF" <NEW_LINE> explanation['yellow'] = "the author can archive pre-print (i.e. pre-refereeing)" <NEW_LINE> explanation['white'] = "archiving of this article not formally supported" <NEW_LINE> journalTitle = root.find('journals/journal/jtitle') <NEW_LINE> publisherName = root.find('publishers/publisher/name') <NEW_LINE> publisherURL = root.find('publishers/publisher/homeurl') <NEW_LINE> xhtml = "<p>" <NEW_LINE> xhtml = xhtml + 'This '+ journalTitle.text + ' article, published by <a href="' + publisherURL.text +'">' + publisherName.text + '</a>, is classified as being <a href="http://www.sherpa.ac.uk/romeo/definitions.php">RoMEO ' + colour.text + '</a>. ' <NEW_LINE> xhtml = xhtml + 'This means that ' + explanation[colour.text] + '.</p>' <NEW_LINE> xhtml = xhtml + '<p>Other <a href="http://www.sherpa.ac.uk/romeo/issn/%s/">details and conditions</a> apply.</p>' % issn <NEW_LINE> a['property:xhtml'] = xhtml <NEW_LINE> document.addAnnotation(a) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def visualisable(self, a): <NEW_LINE> <INDENT> return a.get('concept') == 'SherpaRomeo' and 'property:doi' in a <NEW_LINE> <DEDENT> def visualise(self, a): <NEW_LINE> <INDENT> return a.get('property:xhtml') | Generate Sherpa Romeo information | 62598feaad47b63b2c5a7fe8 |
class MariaDBMigratorBase(MigratorBase): <NEW_LINE> <INDENT> def execute_if_authorized(default: Any = None): <NEW_LINE> <INDENT> def inner_metdhod(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.authorized: <NEW_LINE> <INDENT> return func(self, *args, **kwargs) <NEW_LINE> <DEDENT> return self if default is None else default <NEW_LINE> <DEDENT> return wrapper <NEW_LINE> <DEDENT> return inner_metdhod <NEW_LINE> <DEDENT> def does_table_exists(self, name: str) -> bool: <NEW_LINE> <INDENT> statement = ( "SELECT COUNT(*) " "FROM information_schema.tables " "WHERE table_schema = :database_name " "AND table_name = :table_name " ) <NEW_LINE> result = self.db_session.execute( statement, { "database_name": PyFunceble.cli.factory.DBSession.credential.name, "table_name": name, }, ).fetchone() <NEW_LINE> return result["COUNT(*)"] == 1 <NEW_LINE> <DEDENT> def get_rows( self, statement: str, limit: int = 20 ) -> Generator[Tuple[str, int], dict, None]: <NEW_LINE> <INDENT> statement += f" LIMIT {limit}" <NEW_LINE> while True: <NEW_LINE> <INDENT> db_result = list(self.db_session.execute(statement).fetchall()) <NEW_LINE> if not db_result: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> for result in db_result: <NEW_LINE> <INDENT> yield dict(result) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def authorized(self) -> bool: <NEW_LINE> <INDENT> return PyFunceble.cli.facility.CredentialLoader.is_already_loaded() <NEW_LINE> <DEDENT> @execute_if_authorized(None) <NEW_LINE> def migrate(self) -> "MariaDBMigratorBase": <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @execute_if_authorized(None) <NEW_LINE> def start(self) -> "MariaDBMigratorBase": <NEW_LINE> <INDENT> PyFunceble.facility.Logger.info("Started migration.") <NEW_LINE> self.migrate() <NEW_LINE> PyFunceble.facility.Logger.info("Finished migration.") <NEW_LINE> return self | Provides the base of all our mariadb migration. | 62598fea4c3428357761aa43 |
class ModelExclude(ModelSQL): <NEW_LINE> <INDENT> __name__ = 'test.modelsql.exclude' <NEW_LINE> value = fields.Integer("Value") <NEW_LINE> condition = fields.Boolean("Condition") <NEW_LINE> @classmethod <NEW_LINE> def default_condition(cls): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __setup__(cls): <NEW_LINE> <INDENT> super(ModelExclude, cls).__setup__() <NEW_LINE> t = cls.__table__() <NEW_LINE> cls._sql_constraints = [ ('exclude', Exclude(t, (t.value, Equal), where=t.condition == Literal(True)), "Value must be unique."), ] | ModelSQL with exclude constraint | 62598fea627d3e7fe0e07641 |
@dataclass <NEW_LINE> class GradientClipping(LearnerCallback): <NEW_LINE> <INDENT> clip:float <NEW_LINE> def on_backward_end(self, **kwargs): <NEW_LINE> <INDENT> if self.clip: nn.utils.clip_grad_norm_(self.learn.model.parameters(), self.clip) | To do gradient clipping during training. | 62598feaad47b63b2c5a7fea |
class _Message(object): <NEW_LINE> <INDENT> def __init__(self, msg_id, msg_str, long_msg, default): <NEW_LINE> <INDENT> self.msg_id = msg_id <NEW_LINE> self.msg_str = msg_str <NEW_LINE> if long_msg: <NEW_LINE> <INDENT> self.long_msg = textwrap.dedent(long_msg) <NEW_LINE> self.long_msg = self.long_msg.strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.long_msg = None <NEW_LINE> <DEDENT> self.default = default <NEW_LINE> <DEDENT> @property <NEW_LINE> def msg(self): <NEW_LINE> <INDENT> return "%s: %s" % (self.msg_id, self.msg_str) | An individual pkgcheck message.
This should be accessed via the MESSAGES dict keyed by msg_id,
e.g.
from pkgcheck.messages import MESSAGES
print(MESSAGES['E123'].msg)
:param msg_id: The unique message id (E...)
:param msg_str: The short message string, as displayed in program
output
:param long_msg: A longer more involved message, designed for
documentation | 62598fea091ae356687053b7 |
class PublicTagsApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> <DEDENT> def test_login_required(self): <NEW_LINE> <INDENT> res = self.client.get(TAGS_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | Test the publicly available tags API. | 62598fea187af65679d29fc4 |
class RadicalizationTest(LabyrinthTestCase): <NEW_LINE> <INDENT> def test_cell_placement_removes_cadre(self): <NEW_LINE> <INDENT> mock_randomizer = mock(Randomizer()) <NEW_LINE> app = Labyrinth(1, 1, self.set_up_test_scenario, randomizer=mock_randomizer) <NEW_LINE> country_name = "Iraq" <NEW_LINE> when(mock_randomizer).pick_one(app.map.keys()).thenReturn(country_name) <NEW_LINE> country = app.map[country_name] <NEW_LINE> country.cadre = 1 <NEW_LINE> sleepers_before = country.sleeperCells <NEW_LINE> app.handleRadicalization(1) <NEW_LINE> sleepers_after = country.sleeperCells <NEW_LINE> self.assertEqual(sleepers_after, sleepers_before + 1, "Radicalization should place a sleeper") <NEW_LINE> self.assertEqual(country.cadre, 0, "Cell placement should have removed the cadre") | Test Radicalization | 62598fea26238365f5fad2fd |
class BaseScaffoldFilterRule(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def filter(self, child, parents): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> @abstractmethod <NEW_LINE> def name(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __call__(self, child, parents): <NEW_LINE> <INDENT> return self.filter(child, parents) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<{_cls} at {address}>'.format( _cls=self.__class__.__name__, address=hex(id(self)) ) | Abstract base class for defining rules for scaffold prioritization.
Scaffold filter rules should subclass this base class.
All base rules should implement the ``name`` property and the
``filter`` function. | 62598feac4546d3d9def7654 |
class StatusTrigger(Trigger): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(StatusTrigger, self).__init__() <NEW_LINE> self.cmd_attrs = {} <NEW_LINE> <DEDENT> def get_title(self): <NEW_LINE> <INDENT> return "StatusTrigger" <NEW_LINE> <DEDENT> def check(self, sobject): <NEW_LINE> <INDENT> if not isinstance(sobject, Task): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if sobject.get_value('status') == 'Review' and sobject.get_process()=='rendering': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def execute(self): <NEW_LINE> <INDENT> class_name = self.get_command().__class__.__name__ <NEW_LINE> cmd_sobj = CommandSObj.get_by_class_name(class_name) <NEW_LINE> if class_name != 'SimpleStatusCmd': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not cmd_sobj: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> command = self.get_command() <NEW_LINE> sobjects = command.get_sobjects() <NEW_LINE> if not sobjects: <NEW_LINE> <INDENT> msg = "Command '%s' has no sobjects. Triggers cannot be called" % class_name <NEW_LINE> Environment.add_warning("Command has no sobjects", msg) <NEW_LINE> <DEDENT> for sobject in sobjects: <NEW_LINE> <INDENT> self.handle_sobject(sobject, command) <NEW_LINE> <DEDENT> <DEDENT> def handle_sobject(self, sobject, command): <NEW_LINE> <INDENT> if not self.check(sobject): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> parent = sobject.get_parent() <NEW_LINE> print("Check finished") <NEW_LINE> tasks = Task.get_by_sobject(parent, 'compositing') <NEW_LINE> task_ids = [] <NEW_LINE> for task in tasks: <NEW_LINE> <INDENT> if task.get_value('status') != 'Pending': <NEW_LINE> <INDENT> task.set_value('status','Pending') <NEW_LINE> task.commit() <NEW_LINE> task_ids.append(task.get_id()) <NEW_LINE> <DEDENT> <DEDENT> print("Changed task status to [Pending] for task id %s'" %str(task_ids)) <NEW_LINE> <DEDENT> def handle_done(self): <NEW_LINE> <INDENT> pass | A trigger for changing the compositing task status to Pending when
the rendering task status is set to Review | 62598fea4c3428357761aa49 |
class PiersonMoskowitz(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def significant_wave_height(cls, wind_speed): <NEW_LINE> <INDENT> return (wind_speed ** 2.0) * 0.22 / g <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def peak_wave_period(cls, wind_speed): <NEW_LINE> <INDENT> return wind_speed * 3.0 / 4.0 | Pierson-Moskowitz spectrum for fully developed, wind induced,
surface waves.
This relates significant wave height to U_10 (m/s), which is the
wind speed at 10m elevation. | 62598fea627d3e7fe0e07649 |
class ProxyMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> request.meta["proxy"] = PROXYSERVER <NEW_LINE> request.headers["Proxy-Authorization"] = PROXYAUTH <NEW_LINE> request.headers["Cache-Control"] = "no-cache" | 阿布云代理中间件 | 62598feaab23a570cc2d513e |
class LiteralStructType(BaseStructType): <NEW_LINE> <INDENT> null = 'zeroinitializer' <NEW_LINE> def __init__(self, elems, packed=False): <NEW_LINE> <INDENT> self.elements = tuple(elems) <NEW_LINE> self.packed = packed <NEW_LINE> <DEDENT> def _to_string(self): <NEW_LINE> <INDENT> return self.structure_repr() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, LiteralStructType): <NEW_LINE> <INDENT> return self.elements == other.elements <NEW_LINE> <DEDENT> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(LiteralStructType) | The type of "literal" structs, i.e. structs with a literally-defined
type (by contrast with IdentifiedStructType). | 62598fea627d3e7fe0e0764f |
@pytest.mark.draft <NEW_LINE> @pytest.mark.components <NEW_LINE> @pytest.allure.story('Broadcasts') <NEW_LINE> @pytest.allure.feature('GET') <NEW_LINE> class Test_PFE_Components(object): <NEW_LINE> <INDENT> @pytest.allure.link('https://jira.qumu.com/browse/TC-42299') <NEW_LINE> @pytest.mark.Broadcasts <NEW_LINE> @pytest.mark.GET <NEW_LINE> def test_TC_42299_GET_Broadcasts_Diff_Config(self, context): <NEW_LINE> <INDENT> with pytest.allure.step("""Verify that User is unable to View the Broadcast corresponding to the other Configuration, using token with "Provision" permission within the token expiration time."""): <NEW_LINE> <INDENT> check( context.cl.Broadcasts.getEntity( id='GETid_broadcast_testdata_POST') ) <NEW_LINE> <DEDENT> with pytest.allure.step("""Verify that User is unable to View the Broadcast corresponding to the other Configuration, using token with "Provision" permission within the token expiration time."""): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> client, response = check( context.cl.Broadcasts.getEntity( id='GETid_broadcast_testdata_POST'), quiet=True, returnResponse=True ) <NEW_LINE> <DEDENT> except (HTTPBadRequest, HTTPForbidden) as e: <NEW_LINE> <INDENT> get_error_message(e) | expect.any( should.start_with('may not be empty'), should.start_with('Invalid page parameter specified'), should.contain('Invalid Authorization Token') ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( "Expected error message, got {} status code instead.".format( response.status_code)) | PFE Broadcasts test cases. | 62598fea187af65679d29fcb |
class OrbiterRocketGroupRemove(Operator): <NEW_LINE> <INDENT> bl_idname = "orbiter.rocket_group_remove" <NEW_LINE> bl_label = "Remove Rocket Group" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> orbiter = context.scene.orbiter <NEW_LINE> orbiter.rocket_groups.remove(orbiter.rocket_groups_active_index) <NEW_LINE> orbiter.rocket_groups_active_index = max(orbiter.rocket_groups_active_index - 1, 0) <NEW_LINE> return {'FINISHED'} | Remove a rocket group | 62598fea187af65679d29fcc |
class WPL(ActorCritic): <NEW_LINE> <INDENT> def _loss(self, is_terminal, state, next_state, action, next_action, reward, cum_return, final_reward): <NEW_LINE> <INDENT> grad_est = cum_return - state[:, :, 1].gather(index=action.unsqueeze(1), dim=1).view(-1) <NEW_LINE> grad_projected = torch.where(grad_est < 0, 1. + grad_est, 2. - grad_est) <NEW_LINE> prob_taken = state[:, :, 0].gather(index=action.unsqueeze(1), dim=1).view(-1) <NEW_LINE> prob_target = (prob_taken * grad_projected).detach() <NEW_LINE> act_loss = F.mse_loss(prob_taken, prob_target, reduction='none') <NEW_LINE> ret_loss = F.mse_loss(state[:, :, 1].gather(index=action.unsqueeze(1), dim=1).view(-1), cum_return.detach(), reduction='none').view(-1) <NEW_LINE> return act_loss + ret_loss <NEW_LINE> <DEDENT> def _forward(self, xs, agent): <NEW_LINE> <INDENT> policy = self._policy[agent](xs) <NEW_LINE> policy = (policy.transpose(0, 1) - policy.min(dim=1)[0]).transpose(0, 1) + 1e-6 <NEW_LINE> values = self._qvalue_mem[agent](xs) <NEW_LINE> distribution = torch.distributions.Categorical(probs=policy) <NEW_LINE> if self.training: <NEW_LINE> <INDENT> actions = distribution.sample() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> actions = distribution.logits.max(dim=1)[1] <NEW_LINE> <DEDENT> state = torch.stack([distribution.logits, values], 2) <NEW_LINE> return xs, actions, self._eval_stochastic_are_exp(actions, state), state | Weighted Policy Learner (WPL) Multi-Agent Reinforcement Learning based decision making. | 62598fea4c3428357761aa5a |
class ScopedSymbol(object): <NEW_LINE> <INDENT> def __init__(self, name, enclosing_scope): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.scope = None <NEW_LINE> self.enclosing_scope = enclosing_scope <NEW_LINE> <DEDENT> def define(self, symbol): <NEW_LINE> <INDENT> self.get_members()[symbol.name] = symbol <NEW_LINE> symbol.scope = self <NEW_LINE> <DEDENT> def resolve(self, name): <NEW_LINE> <INDENT> symbol = self.get_members()[name] <NEW_LINE> if symbol is not None: <NEW_LINE> <INDENT> return symbol <NEW_LINE> <DEDENT> if self.get_parent_scope(): <NEW_LINE> <INDENT> return self.get_parent_scope().resolve(name) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_members(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def resolve_member(self, name): <NEW_LINE> <INDENT> return self.fields[name] <NEW_LINE> <DEDENT> def get_parent_scope(self): <NEW_LINE> <INDENT> return self.enclosing_scope | Base class for symbols | 62598feaad47b63b2c5a8000 |
class Vertex: <NEW_LINE> <INDENT> def __init__(self, point_2): <NEW_LINE> <INDENT> self.x = point_2.x() <NEW_LINE> self.y = point_2.y() <NEW_LINE> self.hedgelist = [] <NEW_LINE> <DEDENT> def sortincident(self): <NEW_LINE> <INDENT> self.hedgelist.sort(hsort, reverse=True) | Minimal implementation of a vertex of a 2D dcel | 62598feaab23a570cc2d5145 |
class MetricDescription(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.metric_name = None <NEW_LINE> self.description = None <NEW_LINE> self.extra_fields = None <NEW_LINE> self.unit = None <NEW_LINE> self.cumulative = False <NEW_LINE> self.category = None | Simple object to hold fields describing a monitor's metric. | 62598feb187af65679d29fd0 |
class KeystoneToken(Authenticator): <NEW_LINE> <INDENT> def __init__(self, app, url=None): <NEW_LINE> <INDENT> super(KeystoneToken, self).__init__(app) <NEW_LINE> self.url = url <NEW_LINE> <DEDENT> def authenticate(self, environ, start_response): <NEW_LINE> <INDENT> token = environ.get('HTTP_X_AUTH_TOKEN') <NEW_LINE> if not token: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> headers = {'Content-Type': 'application/json'} <NEW_LINE> body = {'auth': {'identity': {}}} <NEW_LINE> ident = body['auth']['identity'] <NEW_LINE> ident['methods'] = ['token'] <NEW_LINE> ident['token'] = {'id': token} <NEW_LINE> try: <NEW_LINE> <INDENT> response = requests.post( self.url, data=json.dumps(body), headers=headers) <NEW_LINE> <DEDENT> except requests.exceptions.BaseHTTPError as error: <NEW_LINE> <INDENT> self.logger.error( 'Could not reach %s. Denying access. %s: %s', self.url, type(error), error) <NEW_LINE> return False <NEW_LINE> <DEDENT> subject_token_name = 'X-Subject-Token' <NEW_LINE> if subject_token_name in response.headers: <NEW_LINE> <INDENT> token = response.headers[subject_token_name] <NEW_LINE> start_response('200 OK', [ ('content-type', 'application/json'), (subject_token_name, token)]) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False | Auth implementation using token method against OpenStack Keystone | 62598febab23a570cc2d5146 |
class Invalid(Exception): <NEW_LINE> <INDENT> max_err = 1 <NEW_LINE> err_count = 0 <NEW_LINE> def __init__(self, err_code, *args): <NEW_LINE> <INDENT> super(Invalid, self).__init__(err_code) <NEW_LINE> err_msg = err_dict[err_code].format(*args) <NEW_LINE> err_msg = err_msg.replace("{", "{{").replace("}", "}}") <NEW_LINE> self.message = "Error on {} of {}: " + err_msg | Exception that triggers upon invalid data. | 62598feb26238365f5fad316 |
class TestUserCreationForm: <NEW_LINE> <INDENT> def test_clean_username(self) -> None: <NEW_LINE> <INDENT> proto_user = UserFactory.build() <NEW_LINE> form = UserCreationForm( { "username": proto_user.username, "password1": proto_user._password, "password2": proto_user._password, } ) <NEW_LINE> assert form.is_valid() <NEW_LINE> assert form.clean_username() == proto_user.username <NEW_LINE> form.save() <NEW_LINE> form = UserCreationForm( { "username": proto_user.username, "password1": proto_user._password, "password2": proto_user._password, } ) <NEW_LINE> assert not form.is_valid() <NEW_LINE> assert len(form.errors) == 1 <NEW_LINE> assert "username" in form.errors | Test the user creation form. | 62598febab23a570cc2d5147 |
class ListContainerPost(ContainerPost): <NEW_LINE> <INDENT> def __init__( self, name: str, tags: Optional[str] = None, description: Optional[str] = None, extra_fields: Optional[Sequence] = [], can_store_containers: bool = True, can_store_samples: bool = True, location: TargetLocation = TopLevelTargetLocation(), ): <NEW_LINE> <INDENT> super().__init__( name, tags, description, extra_fields, can_store_containers, can_store_samples, location, ) <NEW_LINE> self.data["cType"] = "LIST" | Define a new ListContainer to create | 62598feb4c3428357761aa62 |
class Config(CacheConfig): <NEW_LINE> <INDENT> DEBUG = True <NEW_LINE> TESTING = False <NEW_LINE> SECRET_KEY = "i_don't_want_my_cookies_expiring_while_developing" <NEW_LINE> SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/blacklist.db' <NEW_LINE> REDIS_URL = 'redis://127.0.0.1/0' <NEW_LINE> CELERY_BROKER_URL = 'redis://127.0.0.1/0' <NEW_LINE> CELERY_RESULT_BACKEND = 'redis://127.0.0.1/0' <NEW_LINE> SOCKET_IO_MESSAGE_QUEUE = 'redis://127.0.0.1/0' <NEW_LINE> CACHE_REDIS_URL = 'redis://127.0.0.1/0' <NEW_LINE> PORT = 5000 <NEW_LINE> HOST = '0.0.0.0' | Default Flask configuration inherited by all environments. Use this for development environments. | 62598feb187af65679d29fd2 |
class ConstrainedGameObject(GameObject): <NEW_LINE> <INDENT> def __init__(self, command_queue): <NEW_LINE> <INDENT> self.is_configured = False <NEW_LINE> self.is_started = False <NEW_LINE> self.is_solved = False <NEW_LINE> self.is_static = False <NEW_LINE> self.command_queue = command_queue <NEW_LINE> GameObject.__init__(self) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> assert self.is_configured, "Object started before configuring." <NEW_LINE> assert not self.is_started, "Object already started." <NEW_LINE> self.is_started = True <NEW_LINE> self.accept_notification(None) <NEW_LINE> <DEDENT> def accept_notification(self, cookie): <NEW_LINE> <INDENT> if self.is_static: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.is_started: <NEW_LINE> <INDENT> self.command_queue.push(self.apply_constraints, cookie, 50) <NEW_LINE> <DEDENT> <DEDENT> def apply_constraints(self, cookie): <NEW_LINE> <INDENT> assert self.is_started <NEW_LINE> if not self.is_static: <NEW_LINE> <INDENT> self._apply_dynamic_constraints(cookie) <NEW_LINE> <DEDENT> <DEDENT> def _apply_dynamic_constraints(self, cookie): <NEW_LINE> <INDENT> raise NotImplementedError() | A ConstrainedGameObject has a set of constraints that it tries to solve
by examining neighbouring objects.
States:
(Non-Existent)
Initialised,
Accept subscribe requests but do not call neighbours.
Can be "configured" (especially with neighbours) in this period
Started,
All neighbours are configured.
Solved,
Static
The difference between Solved and Static is Solved objects may continue
to convey the flow of information, but are resolved sufficiently that
the puzzle solution isn't dependent on them any more. | 62598febc4546d3d9def7661 |
class SensorComponent: <NEW_LINE> <INDENT> def __init__(self, name, sensor,range,length=1000): <NEW_LINE> <INDENT> self.plot_widget = pg.PlotWidget( axisItems={'bottom': TimeAxisItem(orientation='bottom')}) <NEW_LINE> self.pw = self.plot_widget <NEW_LINE> self.pw.addLegend() <NEW_LINE> self.x = ComponentAxis('x', self.pw, 'r', length) <NEW_LINE> self.y = ComponentAxis('y', self.pw, 'g', length) <NEW_LINE> self.z = ComponentAxis('z', self.pw, 'b', length) <NEW_LINE> self.m = ComponentAxis('m', self.pw, 'y', length) <NEW_LINE> self.axes = [self.x, self.y, self.z, self.m] <NEW_LINE> self.pw.setTitle(name + ' ' + sensor) <NEW_LINE> self.pw.setYRange(-range, range, padding=0) <NEW_LINE> self.pw.enableAutoRange(ViewBox.XAxis) <NEW_LINE> self.pw.enableAutoRange(ViewBox.YAxis) <NEW_LINE> <DEDENT> def update(self,xaxis): <NEW_LINE> <INDENT> for axis in self.axes: <NEW_LINE> <INDENT> axis.update(xaxis) <NEW_LINE> <DEDENT> <DEDENT> def append_data(self, data, destructive=True): <NEW_LINE> <INDENT> self.x.add_data(data[0], destructive) <NEW_LINE> self.y.add_data(data[1], destructive) <NEW_LINE> self.z.add_data(data[2], destructive) <NEW_LINE> self.m.add_data((data[0]**2+data[1]**2+data[2]**2)**0.5, destructive) | Refers to an individual graph: ie the representation of the
accelerometer, gyroscope, magnetometer or other component of a
sensor. | 62598feb4c3428357761aa63 |
class LoanInterestRate(InterestRateFee): <NEW_LINE> <INDENT> swagger_types = { 'applications': 'list[ApplicationRate]', 'minimum_rate': 'str', 'maximum_rate': 'str' } <NEW_LINE> if hasattr(InterestRateFee, "swagger_types"): <NEW_LINE> <INDENT> swagger_types.update(InterestRateFee.swagger_types) <NEW_LINE> <DEDENT> attribute_map = { 'applications': 'applications', 'minimum_rate': 'minimumRate', 'maximum_rate': 'maximumRate' } <NEW_LINE> if hasattr(InterestRateFee, "attribute_map"): <NEW_LINE> <INDENT> attribute_map.update(InterestRateFee.attribute_map) <NEW_LINE> <DEDENT> def __init__(self, applications=None, minimum_rate=None, maximum_rate=None, *args, **kwargs): <NEW_LINE> <INDENT> self._applications = None <NEW_LINE> self._minimum_rate = None <NEW_LINE> self._maximum_rate = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.applications = applications <NEW_LINE> self.minimum_rate = minimum_rate <NEW_LINE> self.maximum_rate = maximum_rate <NEW_LINE> InterestRateFee.__init__(self, *args, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def applications(self): <NEW_LINE> <INDENT> return self._applications <NEW_LINE> <DEDENT> @applications.setter <NEW_LINE> def applications(self, applications): <NEW_LINE> <INDENT> if applications is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `applications`, must not be `None`") <NEW_LINE> <DEDENT> self._applications = applications <NEW_LINE> <DEDENT> @property <NEW_LINE> def minimum_rate(self): <NEW_LINE> <INDENT> return self._minimum_rate <NEW_LINE> <DEDENT> @minimum_rate.setter <NEW_LINE> def minimum_rate(self, minimum_rate): <NEW_LINE> <INDENT> if minimum_rate is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `minimum_rate`, must not be `None`") <NEW_LINE> <DEDENT> self._minimum_rate = minimum_rate <NEW_LINE> <DEDENT> @property <NEW_LINE> def maximum_rate(self): <NEW_LINE> <INDENT> return self._maximum_rate <NEW_LINE> <DEDENT> @maximum_rate.setter <NEW_LINE> def maximum_rate(self, maximum_rate): <NEW_LINE> <INDENT> if maximum_rate is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `maximum_rate`, must not be `None`") <NEW_LINE> <DEDENT> self._maximum_rate = maximum_rate <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(LoanInterestRate, 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, LoanInterestRate): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598febad47b63b2c5a800c |
class IndexColumnSchema(schema.InformationSchema): <NEW_LINE> <INDENT> __table__ = 'information_schema.index_columns' <NEW_LINE> table_catalog = typing.cast(str, field.Field(field.String, primary_key=True)) <NEW_LINE> table_schema = typing.cast(str, field.Field(field.String, primary_key=True)) <NEW_LINE> table_name = typing.cast(str, field.Field(field.String, primary_key=True)) <NEW_LINE> index_name = typing.cast(str, field.Field(field.String, primary_key=True)) <NEW_LINE> column_name = typing.cast(str, field.Field(field.String, primary_key=True)) <NEW_LINE> ordinal_position = typing.cast(Optional[int], field.Field(field.Integer, nullable=True)) <NEW_LINE> column_ordering = typing.cast(Optional[str], field.Field(field.String, nullable=True)) <NEW_LINE> is_nullable = typing.cast(str, field.Field(field.String)) <NEW_LINE> spanner_type = typing.cast(str, field.Field(field.String)) | Model for interacting with Spanner index column schema table. | 62598feb4c3428357761aa67 |
class frame_type(enum.IntEnum): <NEW_LINE> <INDENT> DATA = 0 <NEW_LINE> HEADERS = 0x01 <NEW_LINE> PRIORITY = 0x02 <NEW_LINE> RST_STREAM = 0x03 <NEW_LINE> SETTINGS = 0x04 <NEW_LINE> PUSH_PROMISE = 0x05 <NEW_LINE> PING = 0x06 <NEW_LINE> GOAWAY = 0x07 <NEW_LINE> WINDOW_UPDATE = 0x08 <NEW_LINE> CONTINUATION = 0x09 <NEW_LINE> ALTSVC = 0x0a | The frame types in HTTP/2 specification. | 62598febc4546d3d9def7665 |
class MFT_INDEX_ENTRY_HEADER(INDEX_ENTRY_HEADER): <NEW_LINE> <INDENT> def __init__(self, buf, offset, parent): <NEW_LINE> <INDENT> super(MFT_INDEX_ENTRY_HEADER, self).__init__(buf, offset, parent) <NEW_LINE> self.declare_field("qword", "mft_reference", 0x0) | Index used by the MFT for INDX attributes. | 62598febc4546d3d9def7669 |
class ReferenceDelegate(object): <NEW_LINE> <INDENT> def __init__(self, name, dataType, plural): <NEW_LINE> <INDENT> self.name = name + "_BackReference" <NEW_LINE> self.dataType = dataType <NEW_LINE> self.plural = plural <NEW_LINE> self.values = None <NEW_LINE> self.maxOccurs = 9999 <NEW_LINE> self.minOccurs = 0 <NEW_LINE> <DEDENT> def getValues(self): <NEW_LINE> <INDENT> return self.values <NEW_LINE> <DEDENT> def getMaxOccurs(self): <NEW_LINE> <INDENT> return self.maxOccurs <NEW_LINE> <DEDENT> def getMinOccurs(self): <NEW_LINE> <INDENT> return self.minOccurs <NEW_LINE> <DEDENT> def getType(self): <NEW_LINE> <INDENT> return self.dataType <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def isComplex(self): <NEW_LINE> <INDENT> return True | A "virtual" property delegate to be used with "reference"
OMEModelProperty instances. This delegate conforms loosely to the same
interface as a delegate coming from generateDS (ie. an "attribute" or
an "element"). | 62598feb4c3428357761aa71 |
class ConditionsTest(cros_test_lib.MockTestCase): <NEW_LINE> <INDENT> def testConditionsMet(self): <NEW_LINE> <INDENT> stat = stats.Stats( username='chrome-bot@chromium.org', host='build42-m2.golo.chromium.org') <NEW_LINE> self.assertTrue(stats.StatsUploader._UploadConditionsMet(stat)) <NEW_LINE> <DEDENT> def testConditionsMet2(self): <NEW_LINE> <INDENT> stat = stats.Stats( username='monkey@google.com', host='typewriter.mtv.corp.google.com') <NEW_LINE> self.assertTrue(stats.StatsUploader._UploadConditionsMet(stat)) <NEW_LINE> <DEDENT> def testConditionsNotMet(self): <NEW_LINE> <INDENT> stat = stats.Stats( username='monkey@home.com', host='typewriter.mtv.corp.google.com') <NEW_LINE> self.assertFalse(stats.StatsUploader._UploadConditionsMet(stat)) <NEW_LINE> <DEDENT> def testConditionsNotMet2(self): <NEW_LINE> <INDENT> stat = stats.Stats( username='monkey@google.com', host='typewriter.noname.com') <NEW_LINE> self.assertFalse(stats.StatsUploader._UploadConditionsMet(stat)) | Test UploadConditionsMet. | 62598feb4c3428357761aa75 |
class TestUserInputs(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> logging.basicConfig(level=logging.FATAL) <NEW_LINE> self.tmp_dir = tempfile.mkdtemp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(self.tmp_dir) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def test_main_missing_debpkgname(): <NEW_LINE> <INDENT> assert err.INVALID_INPUT == gcg.entrypoint.main([ 'xyz', '-O', 'deb']) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def test_main_missing_debdistro(): <NEW_LINE> <INDENT> assert err.INVALID_INPUT == gcg.entrypoint.main([ 'xyz', '-O', 'deb', '-n', 'pkgname']) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def test_main_repo_invalid_path(): <NEW_LINE> <INDENT> assert err.REPO_PATH_INVALID == gcg.entrypoint.main([ 'xyz', '-p', '/doesNot3xist', '-O', 'rpm']) <NEW_LINE> <DEDENT> def test_main_path_is_not_repo(self): <NEW_LINE> <INDENT> assert err.REPO_PATH_NOT_REPO == gcg.entrypoint.main([ 'xyz', '-p', self.tmp_dir, '-O', 'rpm']) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @patch('git.Repo') <NEW_LINE> def test_main_ref_inv_upper_limit(mock_git_repo): <NEW_LINE> <INDENT> mock_git_repo().commit.side_effect = git.BadName('Bang') <NEW_LINE> assert err.INVALID_VCS_LIMITS == gcg.entrypoint.main([ 'xyz', '--until', 'NonExistantTag', '-O', 'rpm']) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @patch('git.Repo') <NEW_LINE> def test_main_sha_inv_upper_limit(mock_git_repo): <NEW_LINE> <INDENT> mock_git_repo().commit.side_effect = ValueError('Boom') <NEW_LINE> assert err.INVALID_VCS_LIMITS == gcg.entrypoint.main([ 'xyz', '--until', 'a1a2a2a3a4a5a6a', '-O', 'rpm']) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @patch('git.Repo') <NEW_LINE> def test_main_ref_inv_low_limit(mock_git_repo): <NEW_LINE> <INDENT> mock_git_repo().commit.side_effect = git.BadName('Bang') <NEW_LINE> assert err.INVALID_VCS_LIMITS == gcg.entrypoint.main([ 'xyz', '--since', 'NonExistantTag', '-O', 'rpm']) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @patch('git.Repo') <NEW_LINE> def test_main_sha_inv_low_limit(mock_git_repo): <NEW_LINE> <INDENT> mock_git_repo().commit.side_effect = ValueError('Boom') <NEW_LINE> assert err.INVALID_VCS_LIMITS == gcg.entrypoint.main([ 'xyz', '--since', 'a1a2a2a3a4a5a6a', '-O', 'rpm']) | Unit test suite for invalid user inputs | 62598feb3cc13d1c6d465f1f |
class SysPathAwareMixin(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(SysPathAwareMixin, self).setUp() <NEW_LINE> setup_with_context_manager(self, saved_sys_path()) | A test case mixin that isolates changes to sys.path. | 62598feb26238365f5fad32b |
class SquaredGroupHonesty(GroupHonesty): <NEW_LINE> <INDENT> def measure_one(self, signaller): <NEW_LINE> <INDENT> r = signaller.do_signal(self.signal) <NEW_LINE> signaller.signal_log.pop() <NEW_LINE> signaller.rounds -= 1 <NEW_LINE> signaller.signal_matches[r] -= 1 <NEW_LINE> try: <NEW_LINE> <INDENT> signaller.signal_memory.pop(hash(signaller), None) <NEW_LINE> signaller.shareable = None <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return (r - signaller.player_type)**2 | Return the average squared distance of everybody's choice of signal
if they were to signal right now, from their own type. | 62598feb091ae356687053e8 |
class casting_operator_t(member_calldef_t, operator_t): <NEW_LINE> <INDENT> def __init__(self, *args, **keywords): <NEW_LINE> <INDENT> member_calldef_t.__init__(self, *args, **keywords) <NEW_LINE> operator_t.__init__(self, *args, **keywords) | describes casting operator declaration | 62598feb627d3e7fe0e07672 |
class GoProblem19(base_go_problem.GoProblem): <NEW_LINE> <INDENT> @property <NEW_LINE> def board_size(self): <NEW_LINE> <INDENT> return 19 <NEW_LINE> <DEDENT> def dataset_filename(self): <NEW_LINE> <INDENT> fn = "go_problem_19" <NEW_LINE> if self.use_kgs_data and self.use_gogod_data: <NEW_LINE> <INDENT> fn += "_multi" <NEW_LINE> <DEDENT> elif self.use_kgs_data: <NEW_LINE> <INDENT> fn += "_kgs" <NEW_LINE> <DEDENT> elif self.use_gogod_data: <NEW_LINE> <INDENT> fn += "_gogod" <NEW_LINE> <DEDENT> return fn <NEW_LINE> <DEDENT> @property <NEW_LINE> def train_shards(self): <NEW_LINE> <INDENT> return 8 <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_small(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def generate_dataset(self, tmp_dir, unzip=True): <NEW_LINE> <INDENT> random.seed(230) <NEW_LINE> data = { "train": [], "dev": [], "test": [] } <NEW_LINE> if self.use_gogod_data: <NEW_LINE> <INDENT> data_gogod = self.get_gogod_dataset(tmp_dir, unzip) <NEW_LINE> for k in data: <NEW_LINE> <INDENT> data[k] += data_gogod[k] <NEW_LINE> <DEDENT> <DEDENT> if self.board_size == 19: <NEW_LINE> <INDENT> data_kgs = self.get_kgs_dataset(tmp_dir, unzip) <NEW_LINE> for k in data: <NEW_LINE> <INDENT> data[k] += data_kgs[k] <NEW_LINE> <DEDENT> <DEDENT> return data | Go Problem for 19x19 go games. | 62598feb3cc13d1c6d465f25 |
class OpNZTsetcolletionorigin(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.nzt_setcollectionorigin" <NEW_LINE> bl_label = "set collection origin" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> if bpy.context.selected_objects==[]: <NEW_LINE> <INDENT> bpy.context.object.users_collection[0].instance_offset=bpy.context.scene.cursor.location <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bpy.context.object.users_collection[0].instance_offset=bpy.context.object.location <NEW_LINE> <DEDENT> return {'FINISHED'} | set active object's collection offset to location of object pivot | 62598febad47b63b2c5a8022 |
class GHSLUrban(GlobalImageDatasource): <NEW_LINE> <INDENT> def build_img_coll(self, year=None, separate=False, use_closest_image=False): <NEW_LINE> <INDENT> if year is not None: <NEW_LINE> <INDENT> if not isinstance(year, int): <NEW_LINE> <INDENT> raise ValueError('Expected year to be integral. Got: {}'.format(type(year))) <NEW_LINE> <DEDENT> self.start_date = str(year) + '-1-1' <NEW_LINE> self.end_date = str(year) + '-12-31' <NEW_LINE> <DEDENT> self.urban = ee.ImageCollection('JRC/GHSL/P2016/SMOD_POP_GLOBE_V1') <NEW_LINE> if use_closest_image: <NEW_LINE> <INDENT> center_date = get_center_date(self.start_date, self.end_date) <NEW_LINE> self.urban = ee.ImageCollection(get_closest_to_date(self.urban, center_date)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.urban = self.urban.filterDate(self.start_date, self.end_date) <NEW_LINE> <DEDENT> if separate: <NEW_LINE> <INDENT> self.urban = self.urban.map(self.separate_urban_bands) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.urban = self.urban.map(self.rename_GHLS_Urban) <NEW_LINE> <DEDENT> self.urban = self.urban.sort('system:time_start') <NEW_LINE> <DEDENT> def get_img_coll(self): <NEW_LINE> <INDENT> return self.urban <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def rename_GHLS_Urban(scene): <NEW_LINE> <INDENT> band_names = ["SMOD"] <NEW_LINE> return scene.select(list(range(len(band_names))), band_names) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def separate_urban_bands(scene): <NEW_LINE> <INDENT> smod = scene.select([0]) <NEW_LINE> inhabited = smod.eq(0).select([0], ["INHABITED"]) <NEW_LINE> rural = smod.eq(1).select([0], ["RUR"]) <NEW_LINE> low_denisty = smod.eq(2).select([0], ["LDC"]) <NEW_LINE> high_denisty = smod.eq(3).select([0], ["HDC"]) <NEW_LINE> split_bands = scene.addBands([inhabited, rural, low_denisty, high_denisty]) <NEW_LINE> split_bands = split_bands.select(list(range(1, 5))) <NEW_LINE> return split_bands <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_band_names(separate=False): <NEW_LINE> <INDENT> if separate: <NEW_LINE> <INDENT> return ["INHABITED", "RUR", "LDC", "HDC"] <NEW_LINE> <DEDENT> return ['SMOD'] | Image Properties
SMOD Degree of urbanization (See table below).
Value Color Description
0 000000 Inhabited areas
1 448564 RUR (rural grid cells)
2 70daa4 LDC (low density clusters)
3 ffffff HDC (high density clusters)
If separate is set to True, the resulting images have separate bands
for each value above. Each pixel has a value of 1 iff the corresponding pixel in the
original band matches the new band's corresponding value.
If separate, band names are ["INHABITED", "RUR", "LDC", "HDC"] | 62598feb4c3428357761aa7e |
class Game(Resource): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> args = parser.parse_args() <NEW_LINE> if 'board_id' not in args or 'bitboard' not in args: <NEW_LINE> <INDENT> return {'message': 'Required POST fields missing'} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> board_id = int(args['board_id']) <NEW_LINE> if len(models.boards) > board_id: <NEW_LINE> <INDENT> models.boards[board_id] = args['bitboard'] <NEW_LINE> return models.boards[board_id] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return {'message': "Board doesn't exist"} <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return {'message': 'Board should be an integer'} <NEW_LINE> <DEDENT> <DEDENT> def model_list(self): <NEW_LINE> <INDENT> return models.games_list | You can also post a new boards state after a move has been completed.
:return: JSON representing the boards state for each players | 62598feb627d3e7fe0e07678 |
class AudioList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> model_obj = models.MediaFileUpload.objects.filter(is_label=False) <NEW_LINE> serializer = serializers.MediaFileUploadSerializer(model_obj, many=True) <NEW_LINE> data_dict={} <NEW_LINE> for i in serializer.data[0]: <NEW_LINE> <INDENT> if i=='media_file': <NEW_LINE> <INDENT> data_dict[i]=settings.BASE_URL+serializer.data[0][i] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data_dict[i] = serializer.data[0][i] <NEW_LINE> <DEDENT> <DEDENT> return Response(data_dict) | List all snippets, or create a new snippet. | 62598fec3cc13d1c6d465f27 |
class ProjectCommand(ObjectCommand): <NEW_LINE> <INDENT> def get_object(self, blank: bool = False): <NEW_LINE> <INDENT> obj = super().get_object(blank=blank) <NEW_LINE> if not isinstance(obj, wlc.Project): <NEW_LINE> <INDENT> raise CommandError("Not supported") <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Wrapper to allow only project objects. | 62598fecad47b63b2c5a8024 |
class LecturerAdmin(utils.ModelAdmin): <NEW_LINE> <INDENT> list_display = ( 'id', 'human', ) <NEW_LINE> search_fields = ( 'id', 'human__first_name', 'human__last_name', 'human__old_last_name', ) <NEW_LINE> inlines = ( LecturerParticipationInlineAdmin, ) | Administration for lecturer.
| 62598fec4c3428357761aa82 |
class MicroscanConfiguration: <NEW_LINE> <INDENT> _K_CODE_PATTERN = re.compile(b'<(K\d+)(.*)>') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.load_defaults() <NEW_LINE> <DEDENT> def load_defaults(self): <NEW_LINE> <INDENT> for k_code, serializer in REGISTRY.items(): <NEW_LINE> <INDENT> prop_name = self._clsname_to_propname(serializer.__name__) <NEW_LINE> setattr(self, prop_name, serializer()) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_config_strings(cls, list_of_strings, defaults=False): <NEW_LINE> <INDENT> instance = cls() <NEW_LINE> if defaults: <NEW_LINE> <INDENT> instance.load_defaults() <NEW_LINE> <DEDENT> for line in list_of_strings: <NEW_LINE> <INDENT> match = cls._K_CODE_PATTERN.match(line) <NEW_LINE> try: <NEW_LINE> <INDENT> k_code = match.group(1) <NEW_LINE> <DEDENT> except (IndexError, AttributeError): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> serializer = REGISTRY[k_code] <NEW_LINE> prop_name = instance._clsname_to_propname(serializer.__name__) <NEW_LINE> setattr( instance, prop_name, serializer.from_config_string(line)) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> logger.info( 'Cannot find serializer class for K-code %s$' % k_code) <NEW_LINE> <DEDENT> <DEDENT> return instance <NEW_LINE> <DEDENT> def _clsname_to_propname(self, clsname): <NEW_LINE> <INDENT> return re.sub(r'([a-z])([A-Z])', r'\1_\2', clsname).lower() <NEW_LINE> <DEDENT> def to_config_string(self, separator=b''): <NEW_LINE> <INDENT> props = [ getattr(self, self._clsname_to_propname(prop.__name__), None) for prop in REGISTRY.values() ] <NEW_LINE> return separator.join([ prop.to_config_string() for prop in props if prop]) | Container for configuration settings for a barcode reader device
Calling the constructor will initialize a configuration object with all
available configuration settings, each set to the default value as
specified by the device documentation.
Use MicroscanConfiguration.from_config_strings() to create a configuration
object from data recorded from a device in response to the `<K?>` command
(or any other source of configuration data in string format). | 62598fec627d3e7fe0e0767c |
class C_spectrum_CAM_RGB(C_spectrum_CAM): <NEW_LINE> <INDENT> mdict_updateRule = { 'R' : {'direction' : [ 'G', 'R' ], 'amount' : 9}, 'G' : {'direction' : [ 'B', 'G' ], 'amount' : 9}, 'B' : {'direction' : [ 'R', 'B' ], 'amount' : 9} } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.mstr_obj = 'C_spectrum_CAM_RGB'; <NEW_LINE> self.ml_keys = [ 'R', 'G', 'B'] <NEW_LINE> if not len(args): args = self.ml_keys <NEW_LINE> C_spectrum_CAM.__init__(self, *args) <NEW_LINE> self.__name__ = 'C_spectrum_CAM_RGB'; <NEW_LINE> self.m_maxQuanta = 99 <NEW_LINE> for key in kwargs: <NEW_LINE> <INDENT> if key == "maxQuanta": <NEW_LINE> <INDENT> self.m_maxQuanta = kwargs[key] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def updateRule_changeAmount(self, af_amount, *args): <NEW_LINE> <INDENT> keysToUpdate = self.ml_keys <NEW_LINE> if len(args): keysToUpdate = args[0] <NEW_LINE> for key in keysToUpdate: <NEW_LINE> <INDENT> C_spectrum_CAM_RGB.mdict_updateRule[key]['amount'] = af_amount <NEW_LINE> <DEDENT> <DEDENT> def spectrum_init(self, value, *args): <NEW_LINE> <INDENT> a_init = np.ones( len(self.ml_keys) ) * self.m_maxQuanta/3 <NEW_LINE> if len(args): <NEW_LINE> <INDENT> v_l = args[0] <NEW_LINE> pcount = 0 <NEW_LINE> for partition in v_l: <NEW_LINE> <INDENT> b_hits = partition[0] == value <NEW_LINE> b_hit = b_hits.sum() <NEW_LINE> if b_hit: <NEW_LINE> <INDENT> a_init = np.zeros( len(self.ml_keys) ) <NEW_LINE> a_init[pcount] = self.m_maxQuanta <NEW_LINE> <DEDENT> pcount += 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if value > 0 and value <= self.m_maxQuanta/3: <NEW_LINE> <INDENT> a_init = np.array( (1, 0, 0) ) * self.m_maxQuanta <NEW_LINE> <DEDENT> if value > self.m_maxQuanta/3 and value <= 2*self.m_maxQuanta/3: <NEW_LINE> <INDENT> a_init = np.array( (0, 1, 0) ) * self.m_maxQuanta <NEW_LINE> <DEDENT> if value > 2*self.m_maxQuanta/3: <NEW_LINE> <INDENT> a_init = np.array( (0, 0, 1) ) * self.m_maxQuanta <NEW_LINE> <DEDENT> <DEDENT> self.arr_set(a_init) <NEW_LINE> <DEDENT> def nextStateDelta_determine(self, adict_neighbors): <NEW_LINE> <INDENT> if not adict_neighbors: return None, None <NEW_LINE> l_dominant = self.max_harmonics() <NEW_LINE> if len(l_dominant) > 1: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> dominant = l_dominant[0] <NEW_LINE> neighbor = random.choice(list(adict_neighbors.keys())) <NEW_LINE> dict_target = { neighbor : C_spectrum_CAM_RGB.mdict_updateRule[dominant] } <NEW_LINE> return None, dict_target <NEW_LINE> <DEDENT> def nextState_process(self, adict_rule): <NEW_LINE> <INDENT> l_direction = adict_rule['direction'] <NEW_LINE> amount = adict_rule['amount'] <NEW_LINE> return self.component_shift(l_direction, amount) | The Cellular Automata Machine (CAM) RGB class, subclassed
from a C_spectrum(_CAM) object. | 62598fec26238365f5fad338 |
class ArLog: <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, ArLog, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, ArLog, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> StdOut = _AriaPy.ArLog_StdOut <NEW_LINE> StdErr = _AriaPy.ArLog_StdErr <NEW_LINE> File = _AriaPy.ArLog_File <NEW_LINE> Colbert = _AriaPy.ArLog_Colbert <NEW_LINE> NoLog = _AriaPy.ArLog_NoLog <NEW_LINE> Terse = _AriaPy.ArLog_Terse <NEW_LINE> Normal = _AriaPy.ArLog_Normal <NEW_LINE> Verbose = _AriaPy.ArLog_Verbose <NEW_LINE> __swig_getmethods__["log"] = lambda x: _AriaPy.ArLog_log <NEW_LINE> __swig_getmethods__["init"] = lambda x: _AriaPy.ArLog_init <NEW_LINE> __swig_getmethods__["close"] = lambda x: _AriaPy.ArLog_close <NEW_LINE> __swig_setmethods__["colbertPrint"] = _AriaPy.ArLog_colbertPrint_set <NEW_LINE> __swig_getmethods__["colbertPrint"] = _AriaPy.ArLog_colbertPrint_get <NEW_LINE> __swig_getmethods__["addToConfig"] = lambda x: _AriaPy.ArLog_addToConfig <NEW_LINE> __swig_getmethods__["aramInit"] = lambda x: _AriaPy.ArLog_aramInit <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> this = _AriaPy.new_ArLog() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _AriaPy.delete_ArLog <NEW_LINE> __del__ = lambda self : None; | Proxy of C++ ArLog class | 62598fecad47b63b2c5a8027 |
@bacpypes_debugging <NEW_LINE> class String(_Struct): <NEW_LINE> <INDENT> def __init__(self, registerLength=6): <NEW_LINE> <INDENT> if _debug: String._debug("__init__ %r", registerLength) <NEW_LINE> self.registerLength = registerLength <NEW_LINE> <DEDENT> def pack(self, value): <NEW_LINE> <INDENT> if _debug: String._debug("pack %r", value) <NEW_LINE> raise NotImplementedError("packing strings is not implemeted") <NEW_LINE> <DEDENT> def unpack(self, registers): <NEW_LINE> <INDENT> if _debug: String._debug("unpack %r", registers) <NEW_LINE> octets = [] <NEW_LINE> for reg in registers: <NEW_LINE> <INDENT> octets.append(reg >> 8) <NEW_LINE> octets.append(reg & 0xFF) <NEW_LINE> <DEDENT> value = ''.join(chr(c) for c in octets) <NEW_LINE> value = value[:value.find('\x00')] <NEW_LINE> return value | This class packs and unpacks a list of registers as a null terminated string. | 62598fec091ae356687053f4 |
class PythonParser(BaseParser): <NEW_LINE> <INDENT> def __init__(self, socket_read_size): <NEW_LINE> <INDENT> self.socket_read_size = socket_read_size <NEW_LINE> self.encoder = None <NEW_LINE> self._sock = None <NEW_LINE> self._buffer = None <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.on_disconnect() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def on_connect(self, connection): <NEW_LINE> <INDENT> self._sock = connection._sock <NEW_LINE> self._buffer = SocketBuffer(self._sock, self.socket_read_size) <NEW_LINE> self.encoder = connection.encoder <NEW_LINE> <DEDENT> def on_disconnect(self): <NEW_LINE> <INDENT> if self._buffer is not None: <NEW_LINE> <INDENT> self._buffer.close() <NEW_LINE> self._buffer = None <NEW_LINE> <DEDENT> self.encoder = None <NEW_LINE> <DEDENT> def can_read(self): <NEW_LINE> <INDENT> return self._buffer and bool(self._buffer.length) <NEW_LINE> <DEDENT> def read_response(self): <NEW_LINE> <INDENT> response = self._buffer.readline() <NEW_LINE> if not response: <NEW_LINE> <INDENT> raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR) <NEW_LINE> <DEDENT> byte, response = byte_to_chr(response[0]), response[1:] <NEW_LINE> if byte not in ('-', '+', ':', '$', '*'): <NEW_LINE> <INDENT> raise InvalidResponse("Protocol Error: %s, %s" % (str(byte), str(response))) <NEW_LINE> <DEDENT> if byte == '-': <NEW_LINE> <INDENT> response = nativestr(response) <NEW_LINE> error = self.parse_error(response) <NEW_LINE> if isinstance(error, ConnectionError): <NEW_LINE> <INDENT> raise error <NEW_LINE> <DEDENT> return error <NEW_LINE> <DEDENT> elif byte == '+': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif byte == ':': <NEW_LINE> <INDENT> response = long(response) <NEW_LINE> <DEDENT> elif byte == '$': <NEW_LINE> <INDENT> length = int(response) <NEW_LINE> if length == -1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> response = self._buffer.read(length) <NEW_LINE> <DEDENT> elif byte == '*': <NEW_LINE> <INDENT> length = int(response) <NEW_LINE> if length == -1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> response = [self.read_response() for i in xrange(length)] <NEW_LINE> <DEDENT> if isinstance(response, bytes): <NEW_LINE> <INDENT> response = self.encoder.decode(response) <NEW_LINE> <DEDENT> return response | Plain Python parsing class | 62598fecc4546d3d9def7672 |
class Negation: <NEW_LINE> <INDENT> __metaclass__ = SlotExpressionFunctor <NEW_LINE> def __init__(self, *lPredicats): <NEW_LINE> <INDENT> self.__lPredicats = lPredicats <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return negation(*self.__lPredicats) | ![] bnf primitive as a functor | 62598fec4c3428357761aa84 |
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE) <NEW_LINE> class SplitTestBase(ModuleStoreTestCase): <NEW_LINE> <INDENT> __test__ = False <NEW_LINE> COURSE_NUMBER = 'split-test-base' <NEW_LINE> ICON_CLASSES = None <NEW_LINE> TOOLTIPS = None <NEW_LINE> HIDDEN_CONTENT = None <NEW_LINE> VISIBLE_CONTENT = None <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.partition = UserPartition( 0, 'first_partition', 'First Partition', [ Group(0, 'alpha'), Group(1, 'beta') ] ) <NEW_LINE> self.course = CourseFactory.create( number=self.COURSE_NUMBER, user_partitions=[self.partition] ) <NEW_LINE> self.chapter = ItemFactory.create( parent_location=self.course.location, category="chapter", display_name="test chapter", ) <NEW_LINE> self.sequential = ItemFactory.create( parent_location=self.chapter.location, category="sequential", display_name="Split Test Tests", ) <NEW_LINE> self.student = UserFactory.create() <NEW_LINE> CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id) <NEW_LINE> self.client.login(username=self.student.username, password='test') <NEW_LINE> <DEDENT> def _video(self, parent, group): <NEW_LINE> <INDENT> return ItemFactory.create( parent_location=parent.location, category="video", display_name="Group {} Sees This Video".format(group), ) <NEW_LINE> <DEDENT> def _problem(self, parent, group): <NEW_LINE> <INDENT> return ItemFactory.create( parent_location=parent.location, category="problem", display_name="Group {} Sees This Problem".format(group), data="<h1>No Problem Defined Yet!</h1>", ) <NEW_LINE> <DEDENT> def _html(self, parent, group): <NEW_LINE> <INDENT> return ItemFactory.create( parent_location=parent.location, category="html", display_name="Group {} Sees This HTML".format(group), data="Some HTML for group {}".format(group), ) <NEW_LINE> <DEDENT> def test_split_test_0(self): <NEW_LINE> <INDENT> self._check_split_test(0) <NEW_LINE> <DEDENT> def test_split_test_1(self): <NEW_LINE> <INDENT> self._check_split_test(1) <NEW_LINE> <DEDENT> def _check_split_test(self, user_tag): <NEW_LINE> <INDENT> UserCourseTagFactory( user=self.student, course_id=self.course.id, key='xblock.partition_service.partition_{0}'.format(self.partition.id), value=str(user_tag) ) <NEW_LINE> resp = self.client.get(reverse( 'courseware_section', kwargs={'course_id': self.course.id.to_deprecated_string(), 'chapter': self.chapter.url_name, 'section': self.sequential.url_name} )) <NEW_LINE> content = resp.content <NEW_LINE> self.assertIn('<a class="{} inactive progress-0"'.format(self.ICON_CLASSES[user_tag]), content) <NEW_LINE> for tooltip in self.TOOLTIPS[user_tag]: <NEW_LINE> <INDENT> self.assertIn(tooltip, content) <NEW_LINE> <DEDENT> for hidden in self.HIDDEN_CONTENT[user_tag]: <NEW_LINE> <INDENT> self.assertNotIn(hidden, content) <NEW_LINE> <DEDENT> for visible in self.VISIBLE_CONTENT[user_tag]: <NEW_LINE> <INDENT> self.assertIn(visible, content) | Sets up a basic course and user for split test testing.
Also provides tests of rendered HTML for two user_tag conditions, 0 and 1. | 62598fec627d3e7fe0e0767e |
class About(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> template_values = make_template_values(self.request) <NEW_LINE> template_values['page_title'] = '{} - {}'.format( DEFAULT_PAGE_TITLE, 'About') <NEW_LINE> template = JINJA_ENVIRONMENT.get_template('about.html') <NEW_LINE> self.response.write(template.render(template_values)) | About page handler. | 62598fec3cc13d1c6d465f2c |
class EnzymeComparison(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 test_basic_isochizomers(self): <NEW_LINE> <INDENT> assert Acc65I.isoschizomers() == [Asp718I, KpnI] <NEW_LINE> assert Acc65I.elucidate() == 'G^GTAC_C' <NEW_LINE> assert Asp718I.elucidate() == 'G^GTAC_C' <NEW_LINE> assert KpnI.elucidate() == 'G_GTAC^C' <NEW_LINE> <DEDENT> def test_comparisons(self): <NEW_LINE> <INDENT> assert Acc65I == Acc65I <NEW_LINE> assert Acc65I != KpnI <NEW_LINE> assert not(Acc65I == Asp718I) <NEW_LINE> assert not(Acc65I != Asp718I) <NEW_LINE> assert Acc65I != EcoRI <NEW_LINE> assert Acc65I >> KpnI <NEW_LINE> assert not(Acc65I >> Asp718I) <NEW_LINE> assert Acc65I % Asp718I <NEW_LINE> assert Acc65I % Acc65I <NEW_LINE> assert not(Acc65I % KpnI) | Tests for comparing various enzymes.
| 62598fecad47b63b2c5a8029 |
class Slot: <NEW_LINE> <INDENT> def __init__(self, concurrency, delay, randomize_delay): <NEW_LINE> <INDENT> self.concurrency = concurrency <NEW_LINE> self.delay = delay <NEW_LINE> self.randomize_delay = randomize_delay <NEW_LINE> self.active = set() <NEW_LINE> self.queue = deque() <NEW_LINE> self.transferring = set() <NEW_LINE> self.lastseen = 0 <NEW_LINE> self.latercall = None <NEW_LINE> <DEDENT> def free_transfer_slots(self): <NEW_LINE> <INDENT> return self.concurrency - len(self.transferring) <NEW_LINE> <DEDENT> def download_delay(self): <NEW_LINE> <INDENT> if self.randomize_delay: <NEW_LINE> <INDENT> return random.uniform(0.5 * self.delay, 1.5 * self.delay) <NEW_LINE> <DEDENT> return self.delay <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.latercall and self.latercall.active(): <NEW_LINE> <INDENT> self.latercall.cancel() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> cls_name = self.__class__.__name__ <NEW_LINE> return "%s(concurrency=%r, delay=%0.2f, randomize_delay=%r)" % ( cls_name, self.concurrency, self.delay, self.randomize_delay) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ( "<downloader.Slot concurrency=%r delay=%0.2f randomize_delay=%r " "len(active)=%d len(queue)=%d len(transferring)=%d lastseen=%s>" % ( self.concurrency, self.delay, self.randomize_delay, len(self.active), len(self.queue), len(self.transferring), datetime.fromtimestamp(self.lastseen).isoformat() ) ) | Downloader slot | 62598fecab23a570cc2d5159 |
class RegionSummaryOverviewItem(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RegionId = None <NEW_LINE> self.RegionName = None <NEW_LINE> self.RealTotalCost = None <NEW_LINE> self.RealTotalCostRatio = None <NEW_LINE> self.CashPayAmount = None <NEW_LINE> self.IncentivePayAmount = None <NEW_LINE> self.VoucherPayAmount = None <NEW_LINE> self.BillMonth = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RegionId = params.get("RegionId") <NEW_LINE> self.RegionName = params.get("RegionName") <NEW_LINE> self.RealTotalCost = params.get("RealTotalCost") <NEW_LINE> self.RealTotalCostRatio = params.get("RealTotalCostRatio") <NEW_LINE> self.CashPayAmount = params.get("CashPayAmount") <NEW_LINE> self.IncentivePayAmount = params.get("IncentivePayAmount") <NEW_LINE> self.VoucherPayAmount = params.get("VoucherPayAmount") <NEW_LINE> self.BillMonth = params.get("BillMonth") | 按地域汇总消费详情
| 62598fec3cc13d1c6d465f2e |
class AlphaEqResult: <NEW_LINE> <INDENT> def __init__(self, res, sub=None): <NEW_LINE> <INDENT> self.res = res <NEW_LINE> self.sub = sub <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> if index < 0 or index > 1: <NEW_LINE> <INDENT> raise IndexError('index {} is out of bounds'.format(index)) <NEW_LINE> <DEDENT> elif index == 0: <NEW_LINE> <INDENT> return self.res <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.sub <NEW_LINE> <DEDENT> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return self.res <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'AlphaEqResult({!r}, {!r})'.format(self.res, self.sub) | Much like a ``namedtuple``, but with better booleanness. | 62598fec26238365f5fad33e |
class ProjectDeleteViewTestCase(TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpTestData(cls): <NEW_LINE> <INDENT> UserModel.objects.create_user(username='Tester', password='test_password') <NEW_LINE> for _ in range(3): <NEW_LINE> <INDENT> ProjectFactory() <NEW_LINE> <DEDENT> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.client.login(username='Tester', password='test_password') <NEW_LINE> self.project = Project.objects.last() <NEW_LINE> <DEDENT> def test_project_confirm_delete(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('project:delete', kwargs={'pk': self.project.pk})) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertTemplateUsed(response, 'projects/project_confirm_delete.html') <NEW_LINE> self.assertEqual(response.context['project'], self.project) <NEW_LINE> <DEDENT> def test_project_delete(self): <NEW_LINE> <INDENT> response = self.client.post(reverse('project:delete', kwargs={'pk': self.project.pk})) <NEW_LINE> self.assertEqual(Project.objects.count(), 2) <NEW_LINE> self.assertRedirects(response, reverse('project:list'), 302) | Testing the project delete view. | 62598fec627d3e7fe0e07684 |
class HasVarianceCol(Params): <NEW_LINE> <INDENT> varianceCol = Param(Params._dummy(), "varianceCol", "column name for the biased sample variance of prediction.", typeConverter=TypeConverters.toString) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(HasVarianceCol, self).__init__() <NEW_LINE> <DEDENT> def setVarianceCol(self, value): <NEW_LINE> <INDENT> self._set(varianceCol=value) <NEW_LINE> return self <NEW_LINE> <DEDENT> def getVarianceCol(self): <NEW_LINE> <INDENT> return self.getOrDefault(self.varianceCol) | Mixin for param varianceCol: column name for the biased sample variance of prediction. | 62598fec3cc13d1c6d465f32 |
class PyscesSMTP: <NEW_LINE> <INDENT> __smtp_active = 0 <NEW_LINE> def __init__(self, fromadd, server): <NEW_LINE> <INDENT> self.server = server <NEW_LINE> try: <NEW_LINE> <INDENT> self.userstr = getuser() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.userstr = 'PySCeS ' <NEW_LINE> <DEDENT> self.msgintro = '' <NEW_LINE> self.fromhead = self.userstr + ' <' + fromadd + '>' <NEW_LINE> self.signature = ( 3 * '\n' + '---\nSent using PySCeS 0.2.2 (http://pysces.sourceforge.net/)\n ' ) <NEW_LINE> <DEDENT> def GenericMail(self, toadd, msgtxt, subj='PySCeS generated email'): <NEW_LINE> <INDENT> assert type(msgtxt) == str, '\nMessage text must be a string' <NEW_LINE> assert self.__smtp_active, 'SMTP Server not active\n' <NEW_LINE> msgtxt = self.msgintro + msgtxt <NEW_LINE> msgtxt += self.signature <NEW_LINE> outer = MIMEText(msgtxt) <NEW_LINE> outer['Subject'] = subj <NEW_LINE> outer['To'] = toadd <NEW_LINE> outer['From'] = self.fromhead <NEW_LINE> outer['Date'] = email.Utils.formatdate(localtime='true') <NEW_LINE> outer.epilogue = ' ' <NEW_LINE> if self.CheckGo(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__SMTPserver.sendmail(self.fromhead, toadd, outer.as_string()) <NEW_LINE> <DEDENT> except SMTPServerDisconnected as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> self.SMTPOpen() <NEW_LINE> self.__SMTPserver.sendmail(self.fromhead, toadd, outer.as_string()) <NEW_LINE> <DEDENT> sleep(0.2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('\nEmail send aborted') <NEW_LINE> <DEDENT> <DEDENT> def CheckGo(self): <NEW_LINE> <INDENT> GO = 1 <NEW_LINE> while GO: <NEW_LINE> <INDENT> resp = input('\nDo you want to continue (yes/no): ') <NEW_LINE> if resp.lower() == 'yes': <NEW_LINE> <INDENT> print('OK.') <NEW_LINE> GO = 0 <NEW_LINE> return 1 <NEW_LINE> <DEDENT> elif resp.lower() == 'no': <NEW_LINE> <INDENT> print('Skipped.') <NEW_LINE> GO = 0 <NEW_LINE> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('\nyes to continue, no to exit') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def SMTPOpen(self): <NEW_LINE> <INDENT> self.__SMTPserver = smtplib.SMTP(self.server) <NEW_LINE> self.__smtp_active = 1 <NEW_LINE> print('\nSMTP server connection opened\n') <NEW_LINE> <DEDENT> def SMTPClose(self): <NEW_LINE> <INDENT> self.__SMTPserver.close() <NEW_LINE> self.__smtp_active = 0 <NEW_LINE> print('\nSMTP server connection closed\n') | A purely experimental class that extends PySCeS with SMTP mailer capabilities. Initialise with
sender address and local mail server name. | 62598fec26238365f5fad340 |
class AlphaSenderList(ListResource): <NEW_LINE> <INDENT> def __init__(self, version, service_sid): <NEW_LINE> <INDENT> super(AlphaSenderList, self).__init__(version) <NEW_LINE> self._solution = { 'service_sid': service_sid, } <NEW_LINE> self._uri = '/Services/{service_sid}/AlphaSenders'.format(**self._solution) <NEW_LINE> <DEDENT> def create(self, alpha_sender): <NEW_LINE> <INDENT> data = values.of({ 'AlphaSender': alpha_sender, }) <NEW_LINE> payload = self._version.create( 'POST', self._uri, data=data, ) <NEW_LINE> return AlphaSenderInstance( self._version, payload, service_sid=self._solution['service_sid'], ) <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 AlphaSenderPage(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 AlphaSenderPage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def get(self, sid): <NEW_LINE> <INDENT> return AlphaSenderContext( self._version, service_sid=self._solution['service_sid'], sid=sid, ) <NEW_LINE> <DEDENT> def __call__(self, sid): <NEW_LINE> <INDENT> return AlphaSenderContext( self._version, service_sid=self._solution['service_sid'], sid=sid, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Messaging.V1.AlphaSenderList>' | PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. | 62598fecad47b63b2c5a802f |
class NestedDict(dict): <NEW_LINE> <INDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> return self.get(key) <NEW_LINE> <DEDENT> return self.setdefault(key, NestedDict()) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> new_dict = {} <NEW_LINE> for key, val in self.items(): <NEW_LINE> <INDENT> if isinstance(val, NestedDict): <NEW_LINE> <INDENT> new_dict[key] = val.to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_dict[key] = val <NEW_LINE> <DEDENT> <DEDENT> return new_dict | This helps with accessing a heavily nested dictionary. Access to keys
which don't exist will result in a new, empty dictionary | 62598fecab23a570cc2d515c |
class PyTautulliApiResponse(PyTautulliApiBaseModel): <NEW_LINE> <INDENT> data: dict[str, Any] | list[ dict[str, Any] ] | PyTautulliApiActivity | PyTautulliApiSession | list[ PyTautulliApiUser ] | None = None <NEW_LINE> message: str | None = None <NEW_LINE> result: APIResult | None = None <NEW_LINE> def _generate_data(self, data: dict[str, Any] | list[dict[str, Any]]) -> None: <NEW_LINE> <INDENT> if self._datatype is None: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> if self._datatype._responsetype == APIResponseType.LIST: <NEW_LINE> <INDENT> return [self._datatype(item, self._datatype) for item in data] <NEW_LINE> <DEDENT> return self._datatype(data, self._datatype) | API response model for PyTautulli Api. | 62598fec4c3428357761aa8e |
class Meta: <NEW_LINE> <INDENT> ordering = ("platform", "name") <NEW_LINE> unique_together = ("name", "platform") | Meta information for ConfigRemove model. | 62598fec26238365f5fad343 |
class TFServingServer(object): <NEW_LINE> <INDENT> def __init__(self, port, model_name, model_path, per_process_gpu_memory_fraction=0.0): <NEW_LINE> <INDENT> self.port = port <NEW_LINE> self.server = None <NEW_LINE> self.running = False <NEW_LINE> self.model_path = model_path <NEW_LINE> self.model_name = model_name <NEW_LINE> self.gpu_mem = per_process_gpu_memory_fraction <NEW_LINE> <DEDENT> def is_running(self): <NEW_LINE> <INDENT> return self.running <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if not self.running: <NEW_LINE> <INDENT> print("Serving Server is launching ... ") <NEW_LINE> self.server = subprocess.Popen(UNIX_COMMAND.format( self.port, self.model_name, self.model_path, self.gpu_mem), stdin=subprocess.PIPE, shell=True) <NEW_LINE> print("Serving Server is started at PID %s\n" % self.server.pid) <NEW_LINE> self.running = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Serving Server has been activated already..\n") <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self.running: <NEW_LINE> <INDENT> self.running = True <NEW_LINE> self._turn_off_server() <NEW_LINE> print("Serving Server is off now\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Serving Server is not activated yet..\n") <NEW_LINE> <DEDENT> <DEDENT> def _turn_off_server(self): <NEW_LINE> <INDENT> ps_command = subprocess.Popen( "kill -9 $(lsof -t -i:%d -sTCP:LISTEN)" % self.port, shell=True, stdout=subprocess.PIPE) <NEW_LINE> ps_output = ps_command.stdout.read() <NEW_LINE> for pid_str in ps_output.split("\n")[:-1]: <NEW_LINE> <INDENT> os.kill(int(pid_str), signal.SIGINT) <NEW_LINE> <DEDENT> self.server.terminate() | Manage TF Serving Server for inference.
This object will manage turning on/off server | 62598fec187af65679d29fe9 |
class ModelCreateObject(Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(ModelCreateObject, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) | Object model for creating a new entity extractor.
:param name: Name of the new entity extractor.
:type name: str | 62598fec4c3428357761aa90 |
class OpenkimModels(CMakePackage): <NEW_LINE> <INDENT> homepage = "https://openkim.org/" <NEW_LINE> url = "https://s3.openkim.org/archives/collection/openkim-models-2021-01-28.txz" <NEW_LINE> maintainers = ['ellio167'] <NEW_LINE> extends('kim-api') <NEW_LINE> depends_on('kim-api@2.2.1:', when='@2021-01-28:') <NEW_LINE> depends_on('kim-api@2.1.0:', when='@2019-07-25:') <NEW_LINE> depends_on('kim-api@:2.0.2', when='@:2019-03-29') <NEW_LINE> version( '2021-01-28', sha256='8824adee02ae4583bd378cc81140fbb49515c5965708ee98d856d122d48dd95f') <NEW_LINE> version( '2019-07-25', sha256='50338084ece92ec0fb13b0bbdf357b5d7450e26068ba501f23c315f814befc26') <NEW_LINE> version( '2019-03-29', sha256='053dda2023fe4bb6d7c1d66530c758c4e633bbf1f1be17b6b075b276fe8874f6') <NEW_LINE> def cmake_args(self): <NEW_LINE> <INDENT> args = [] <NEW_LINE> args.append(('-DKIM_API_MODEL_DRIVER_INSTALL_PREFIX={0}' + '/lib/kim-api/model-drivers').format(prefix)) <NEW_LINE> if self.spec.satisfies('@2019-07-25:'): <NEW_LINE> <INDENT> args.append(('-DKIM_API_PORTABLE_MODEL_INSTALL_PREFIX={0}' + '/lib/kim-api/portable-models').format(prefix)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args.append(('-DKIM_API_MODEL_INSTALL_PREFIX={0}' + '/lib/kim-api/models').format(prefix)) <NEW_LINE> <DEDENT> args.append(('-DKIM_API_SIMULATOR_MODEL_INSTALL_PREFIX={0}' + '/lib/kim-api/simulator-models').format(prefix)) <NEW_LINE> return args | OpenKIM is an online framework for making molecular simulations
reliable, reproducible, and portable. Computer implementations of
inter-atomic models are archived in OpenKIM, verified for coding
integrity, and tested by computing their predictions for a variety
of material properties. Models conforming to the KIM application
programming interface (API) work seamlessly with major simulation
codes that have adopted the KIM API standard.
This package provides all models archived at openkim.org that are
compatible with the kim-api package. | 62598fecab23a570cc2d515f |
class GetElementByStyle(FilterBase): <NEW_LINE> <INDENT> __kind__ = 'element-by-style' <NEW_LINE> __supported_subfilters__ = { 'style': 'HTML style attribute value to filter for (required)', } <NEW_LINE> __default_subfilter__ = 'style' <NEW_LINE> def filter(self, data, subfilter): <NEW_LINE> <INDENT> if 'style' not in subfilter: <NEW_LINE> <INDENT> raise ValueError('Need an element style for filtering') <NEW_LINE> <DEDENT> element_by_style = ElementsBy(FilterBy.ATTRIBUTE, 'style', subfilter['style']) <NEW_LINE> element_by_style.feed(data) <NEW_LINE> return element_by_style.get_html() | Get all HTML elements by style | 62598fec3cc13d1c6d465f3a |
class Convert(object): <NEW_LINE> <INDENT> PATTERN = re.compile(r'inputfile([0-9]+)\.png') <NEW_LINE> def __init__(self, pdf_path): <NEW_LINE> <INDENT> filename = os.path.basename(pdf_path) <NEW_LINE> LOGGER.info('PDF filename=%s' % filename) <NEW_LINE> cache_directory = 'cache/%s' % (filename[:-4]) <NEW_LINE> if not os.path.exists(cache_directory): <NEW_LINE> <INDENT> os.makedirs(cache_directory) <NEW_LINE> LOGGER.info('Created cache directory: %s' % cache_directory) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOGGER.info('Existing cache directory: %s' % cache_directory) <NEW_LINE> <DEDENT> pdf_cached_path = '%s/inputfile.pdf' % (cache_directory) <NEW_LINE> shutil.copyfile(pdf_path, pdf_cached_path) <NEW_LINE> self.workdir = cache_directory <NEW_LINE> self.pdf = pdf_cached_path <NEW_LINE> self.images = [] <NEW_LINE> self._convert() <NEW_LINE> <DEDENT> def _convert(self,): <NEW_LINE> <INDENT> img = self.pdf.replace('.pdf', '.png') <NEW_LINE> LOGGER.info('Converting PDF=[%s] to image=[%s]' % (self.pdf, img)) <NEW_LINE> conversion = sp.Popen( ['convert', self.pdf, img], close_fds=True) <NEW_LINE> conversion.wait() <NEW_LINE> LOGGER.info('Done converting PDF to PNG') <NEW_LINE> contents = os.listdir(self.workdir) <NEW_LINE> if len(contents) == 2: <NEW_LINE> <INDENT> self.images.append({ 'path': '%s/%s' % (self.workdir, 'inputfile.png'), 'page_number': 1 }) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for fn in contents: <NEW_LINE> <INDENT> LOGGER.info(fn) <NEW_LINE> if '.png' in fn: <NEW_LINE> <INDENT> self.images.append({ 'path': '%s/%s' % (self.workdir, fn), 'page_number': Convert.PATTERN.search(fn).group(1) }) | Converts PDF to PNGs, one PNG per page.
Cached in a directory called 'cache'. | 62598fec26238365f5fad347 |
class DigitalCartes(Digital): <NEW_LINE> <INDENT> def __init__(self, left, right): <NEW_LINE> <INDENT> self.left = left <NEW_LINE> self.right = right <NEW_LINE> <DEDENT> def base(self): <NEW_LINE> <INDENT> return self.left.base() * self.right.base() <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> rightbase = self.right.base() <NEW_LINE> res = [] <NEW_LINE> flatprepend(res, self.right[key % rightbase]) <NEW_LINE> flatprepend(res, self.left[key // rightbase]) <NEW_LINE> return res | A digital place with dynamic cartesian multiplication of digits.
>>> dsq = DigitalCartes(Digital('01234'), Digital('abcdef'))
>>> dsq.base()
30
>>> dsq[0]
['0', 'a']
>>> dsq[29]
['4', 'f']
>>> dsq[31]
... #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
IndexError: | 62598fecab23a570cc2d5160 |
class ExperienceViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = ExperienceSerializer <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return Experience.objects.filter(person__id=self.request.user.id).all() <NEW_LINE> <DEDENT> def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> request.data["person"] = request.user <NEW_LINE> result = super().create(request, *args, **kwargs) <NEW_LINE> update_users_profile_percentage(request.user, "experiences") <NEW_LINE> return result <NEW_LINE> <DEDENT> def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> if user.user_type == User.PERSON: <NEW_LINE> <INDENT> user = user.person <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user = user.company <NEW_LINE> <DEDENT> instance = self.get_object() <NEW_LINE> serializer = self.get_serializer(instance, data=request.data, partial=True) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> serializer.save() <NEW_LINE> return Response(serializer.data) | Experience CRUD operations. | 62598fec26238365f5fad349 |
class delete_follow_result(object): <NEW_LINE> <INDENT> def __init__(self, e1=None, e2=None,): <NEW_LINE> <INDENT> self.e1 = e1 <NEW_LINE> self.e2 = e2 <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e1 = TFollowNotFoundException() <NEW_LINE> self.e1.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e2 = TFollowNotAuthorizedException() <NEW_LINE> self.e2.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('delete_follow_result') <NEW_LINE> if self.e1 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e1', TType.STRUCT, 1) <NEW_LINE> self.e1.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e2 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e2', TType.STRUCT, 2) <NEW_LINE> self.e2.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- e1
- e2 | 62598fec627d3e7fe0e07692 |
class Masking(MaskedLayer): <NEW_LINE> <INDENT> def __init__(self, mask_value=0., **kwargs): <NEW_LINE> <INDENT> super(Masking, self).__init__(**kwargs) <NEW_LINE> self.mask_value = mask_value <NEW_LINE> self.input = T.tensor3() <NEW_LINE> <DEDENT> def get_output_mask(self, train=False): <NEW_LINE> <INDENT> X = self.get_input(train) <NEW_LINE> return T.any(T.ones_like(X) * (1. - T.eq(X, self.mask_value)), axis=-1) <NEW_LINE> <DEDENT> def get_output(self, train=False): <NEW_LINE> <INDENT> X = self.get_input(train) <NEW_LINE> return X * T.shape_padright(T.any((1. - T.eq(X, self.mask_value)), axis=-1)) <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = {"name": self.__class__.__name__, "mask_value": self.mask_value} <NEW_LINE> base_config = super(Masking, self).get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items())) | Mask an input sequence by using a mask value to identify padding.
This layer copies the input to the output layer with identified padding
replaced with 0s and creates an output mask in the process.
At each timestep, if the values all equal `mask_value`,
then the corresponding mask value for the timestep is 0 (skipped),
otherwise it is 1. | 62598fecad47b63b2c5a803d |
class ProfileTestCase(ModoTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpTestData(cls): <NEW_LINE> <INDENT> super(ProfileTestCase, cls).setUpTestData() <NEW_LINE> cls.account = factories.UserFactory( username="user@test.com", groups=('SimpleUsers',) ) <NEW_LINE> <DEDENT> def test_update_password(self): <NEW_LINE> <INDENT> self.ajax_post(reverse("core:user_profile"), {"language": "en", "oldpassword": "password", "newpassword": "12345Toi", "confirmation": "12345Toi"}) <NEW_LINE> self.client.logout() <NEW_LINE> self.assertEqual( self.client.login(username="admin", password="12345Toi"), True ) <NEW_LINE> self.assertEqual( self.client.login(username="user@test.com", password="toto"), True ) <NEW_LINE> self.ajax_post( reverse("core:user_profile"), {"oldpassword": "toto", "newpassword": "tutu", "confirmation": "tutu"}, status=400 ) <NEW_LINE> self.ajax_post( reverse("core:user_profile"), {"language": "en", "oldpassword": "toto", "newpassword": "Toto1234", "confirmation": "Toto1234"} ) <NEW_LINE> self.client.logout() <NEW_LINE> self.assertTrue( self.client.login(username="user@test.com", password="Toto1234") ) | Profile related tests. | 62598fec3cc13d1c6d465f40 |
class SELoginEntry(SuccessEntry): <NEW_LINE> <INDENT> selinuxuser = models.CharField(max_length=128) <NEW_LINE> current_selinuxuser = models.CharField(max_length=128, null=True) <NEW_LINE> ENTRY_TYPE = r"SELogin" | SELinux login | 62598fec26238365f5fad34f |
class VMImageHtmlParser(HTMLParser): <NEW_LINE> <INDENT> def __init__(self, pattern): <NEW_LINE> <INDENT> HTMLParser.__init__(self) <NEW_LINE> self.items = [] <NEW_LINE> self.pattern = pattern <NEW_LINE> <DEDENT> def handle_starttag(self, tag, attrs): <NEW_LINE> <INDENT> if tag != 'a': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for attr in attrs: <NEW_LINE> <INDENT> if attr[0] == 'href' and re.match(self.pattern, attr[1]): <NEW_LINE> <INDENT> match = attr[1].strip('/') <NEW_LINE> if match not in self.items: <NEW_LINE> <INDENT> self.items.append(match) | Custom HTML parser to extract the href items that match
a given pattern | 62598fecc4546d3d9def767e |
class W_PromotableClosure(W_Procedure): <NEW_LINE> <INDENT> _attrs_ = _immutable_fields_ = ["closure", "arity"] <NEW_LINE> def __init__(self, caselam, toplevel_env): <NEW_LINE> <INDENT> envs = [toplevel_env] * len(caselam.lams) <NEW_LINE> self.closure = W_Closure._make(envs, caselam, toplevel_env) <NEW_LINE> self.arity = caselam._arity <NEW_LINE> <DEDENT> def enable_jitting(self): <NEW_LINE> <INDENT> self.closure.enable_jitting() <NEW_LINE> <DEDENT> def call(self, args, env, cont): <NEW_LINE> <INDENT> jit.promote(self) <NEW_LINE> return self.closure.call(args, env, cont) <NEW_LINE> <DEDENT> def call_with_extra_info(self, args, env, cont, calling_app): <NEW_LINE> <INDENT> jit.promote(self) <NEW_LINE> return self.closure.call_with_extra_info(args, env, cont, calling_app) <NEW_LINE> <DEDENT> def get_arity(self, promote=False): <NEW_LINE> <INDENT> if promote: <NEW_LINE> <INDENT> self = jit.promote(self) <NEW_LINE> <DEDENT> return self.arity <NEW_LINE> <DEDENT> def tostring(self): <NEW_LINE> <INDENT> return self.closure.tostring() | A W_Closure that is promotable, ie that is cached in some place and
unlikely to change. | 62598fecab23a570cc2d5164 |
class Account: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.id = 0 <NEW_LINE> self.type = AccountType.INVALID <NEW_LINE> self.state = AccountState.INVALID <NEW_LINE> self.subtype = "" <NEW_LINE> <DEDENT> def print_object(self, format_data=""): <NEW_LINE> <INDENT> from huobi.utils.print_mix_object import PrintBasic <NEW_LINE> PrintBasic.print_basic(self.id, format_data + "ID") <NEW_LINE> PrintBasic.print_basic(self.type, format_data + "Account Type") <NEW_LINE> PrintBasic.print_basic(self.state, format_data + "Account State") <NEW_LINE> PrintBasic.print_basic(self.subtype, format_data + "Subtype") | The account information for spot account, margin account etc.
:member
id: The unique account id.
account_type: The type of this account, possible value: spot, margin, otc, point.
account_state: The account state, possible value: working, lock.
balances: The balance list of the specified currency. The content is Balance class | 62598fecad47b63b2c5a8041 |
class ArrayBackend(_BackendBase): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> def process(self, query): <NEW_LINE> <INDENT> response = super(ArrayBackend, self).process(query) <NEW_LINE> data = list(self.data) <NEW_LINE> response['iTotalRecords'] = len(data) <NEW_LINE> if query.sSearch: <NEW_LINE> <INDENT> if query.bRegex: <NEW_LINE> <INDENT> raise NotImplementedError("Searching with regular expresions is not implemented") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = [row for row in data if any((query.sSearch in unicode(cell) for cell in row))] <NEW_LINE> <DEDENT> <DEDENT> response['iTotalDisplayRecords'] = len(data) <NEW_LINE> for column_index, order in reversed(query.sorting_columns): <NEW_LINE> <INDENT> data.sort(key=lambda row: row[column_index], reverse=order == 'desc') <NEW_LINE> <DEDENT> data = data[query.iDisplayStart:query.iDisplayStart + query.iDisplayLength] <NEW_LINE> response['aaData'] = data <NEW_LINE> return response | Array backend to data tables
Stores all data in a plain python list. All filtering is handled in the
running process. It is suitable for very small data sets only but has the
advantage of being unrelated to any databases. | 62598fecab23a570cc2d5165 |
class EnvironmentGroupsListView(TemplateView): <NEW_LINE> <INDENT> template_name = "environment/groups.html" <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> if "name" in self.request.GET: <NEW_LINE> <INDENT> env_groups = TCMSEnvGroup.objects.filter(name__icontains=self.request.GET["name"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env_groups = TCMSEnvGroup.objects.all() <NEW_LINE> <DEDENT> qs = ( TCMSEnvGroupPropertyMap.objects.filter(group__in=env_groups) .values("group__pk", "property__name") .order_by("group__pk", "property__name") .iterator() ) <NEW_LINE> properties = {key: list(value) for key, value in groupby(qs, itemgetter("group__pk"))} <NEW_LINE> env_group_ct = ContentType.objects.get_for_model(TCMSEnvGroup) <NEW_LINE> qs = ( TCMSLogModel.objects.filter(content_type=env_group_ct, object_pk__in=env_groups) .only( "object_pk", "who__username", "date", "field", "original_value", "new_value", ) .order_by("object_pk") ) <NEW_LINE> logs = {int(key): list(value) for key, value in groupby(qs, attrgetter("object_pk"))} <NEW_LINE> env_groups = ( env_groups.select_related("modified_by", "manager") .order_by("is_active", "name") .iterator() ) <NEW_LINE> context.update( { "environments": QuerySetIterationProxy( env_groups, properties=properties, another_logs=logs ), "module": "env", } ) <NEW_LINE> return context | The environment groups index page | 62598fec627d3e7fe0e07698 |
class FreePCBfile (object): <NEW_LINE> <INDENT> def __init__ (self, f): <NEW_LINE> <INDENT> self.File = [i.rstrip () for i in f.readlines ()] <NEW_LINE> self.File.reverse () <NEW_LINE> self.Lineno = 1 <NEW_LINE> <DEDENT> def get_string (self, allow_blank): <NEW_LINE> <INDENT> while self.File and not self.File[-1].strip (): <NEW_LINE> <INDENT> self.File.pop () <NEW_LINE> self.Lineno += 1 <NEW_LINE> <DEDENT> assert len (self.File) <NEW_LINE> self.Lineno += 1 <NEW_LINE> key, delim, value = self.File.pop ().partition (":") <NEW_LINE> key = key.strip () <NEW_LINE> value = value.strip () <NEW_LINE> if value.startswith ('"') and value.endswith ('"'): <NEW_LINE> <INDENT> value, throwaway = parse_string (value) <NEW_LINE> <DEDENT> if not value: <NEW_LINE> <INDENT> raise Exception ("Line %d: expected value" % (self.Lineno - 1)) <NEW_LINE> <DEDENT> return key, value <NEW_LINE> <DEDENT> def indent_level (self): <NEW_LINE> <INDENT> line = self.File[-1] <NEW_LINE> i = 0 <NEW_LINE> halfindents = 0 <NEW_LINE> while i < len (line): <NEW_LINE> <INDENT> if line[i] == '\t': <NEW_LINE> <INDENT> halfindents += 2 <NEW_LINE> <DEDENT> elif line[i] == ' ': <NEW_LINE> <INDENT> halfindents += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> return halfindents // 2 <NEW_LINE> <DEDENT> def at_end (self): <NEW_LINE> <INDENT> while self.File and not self.File[-1].strip (): <NEW_LINE> <INDENT> self.File.pop () <NEW_LINE> self.Lineno += 1 <NEW_LINE> <DEDENT> return not self.File <NEW_LINE> <DEDENT> def peek_key (self): <NEW_LINE> <INDENT> assert len (self.File) <NEW_LINE> key, delim, value = self.File[-1].partition (":") <NEW_LINE> return key.strip () | This just wraps a FreePCB text file, reading it out in pieces. | 62598fed627d3e7fe0e0769c |
class SampleInput(unittest.TestCase): <NEW_LINE> <INDENT> def test_sample_input(self): <NEW_LINE> <INDENT> inputs = [] <NEW_LINE> inputs.append('dog ogday') <NEW_LINE> inputs.append('cat atcay') <NEW_LINE> inputs.append('pig igpay') <NEW_LINE> inputs.append('froot ootfray') <NEW_LINE> inputs.append('loops oopslay') <NEW_LINE> inputs.append('') <NEW_LINE> inputs.append('atcay') <NEW_LINE> inputs.append('ittenkay') <NEW_LINE> inputs.append('oopslay') <NEW_LINE> inputs = '\n'.join(inputs) + '\n' <NEW_LINE> outputs = [] <NEW_LINE> outputs.append('cat') <NEW_LINE> outputs.append('eh') <NEW_LINE> outputs.append('loops') <NEW_LINE> outputs = '\n'.join(outputs) + '\n' <NEW_LINE> with patch('sys.stdin', io.StringIO(inputs)) as stdin, patch('sys.stdout', new_callable=io.StringIO) as stdout: <NEW_LINE> <INDENT> k_babelfish.main() <NEW_LINE> self.assertEqual(stdout.getvalue(), outputs) <NEW_LINE> self.assertEqual(stdin.read(), '') | Problem statement sample inputs and outputs | 62598fed627d3e7fe0e0769e |
class Tag(View): <NEW_LINE> <INDENT> def init(self, conf, env, template='main.html', items_per_page=10, pagination='/tag/:name/:num/'): <NEW_LINE> <INDENT> self.template = template <NEW_LINE> self.items_per_page = items_per_page <NEW_LINE> self.pagination = pagination <NEW_LINE> self.filters.append('relative') <NEW_LINE> <DEDENT> def populate_tags(self, request): <NEW_LINE> <INDENT> tags = fetch(request['entrylist'] + request['translations']) <NEW_LINE> self.tags = dict([(safeslug(k), v) for k, v in tags.iteritems()]) <NEW_LINE> return tags <NEW_LINE> <DEDENT> def context(self, conf, env, request): <NEW_LINE> <INDENT> class Link: <NEW_LINE> <INDENT> def __init__(self, title, href): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.href = href if href.endswith('/') else href + '/' <NEW_LINE> <DEDENT> <DEDENT> def tagify(tags): <NEW_LINE> <INDENT> href = lambda t: expand(self.path, {'name': safeslug(t)}) <NEW_LINE> return [Link(t, href(t)) for t in tags] <NEW_LINE> <DEDENT> tags = self.populate_tags(request) <NEW_LINE> env.engine.register('tagify', tagify) <NEW_LINE> env.tag_cloud = Tagcloud(tags, conf['tag_cloud_steps'], conf['tag_cloud_max_items'], conf['tag_cloud_start_index'], conf['tag_cloud_shuffle']) <NEW_LINE> return env <NEW_LINE> <DEDENT> def generate(self, conf, env, data): <NEW_LINE> <INDENT> ipp = self.items_per_page <NEW_LINE> tt = env.engine.fromfile(self.template) <NEW_LINE> for tag in self.tags: <NEW_LINE> <INDENT> route = expand(self.path, {'name': tag}).rstrip('/') <NEW_LINE> entrylist = [entry for entry in self.tags[tag]] <NEW_LINE> paginator = paginate(entrylist, ipp, route, conf['default_orphans']) <NEW_LINE> for (next, curr, prev), entries, modified in paginator: <NEW_LINE> <INDENT> next = None if next is None else link(u'Next', expand(self.path, {'name': tag}).rstrip('/')) if next == 1 else link(u'Next', expand(self.pagination, {'name': tag, 'num': next})) <NEW_LINE> curr = link(curr, expand(self.path, {'name': tag})) if curr == 1 else link(expand(self.pagination, {'num': curr, 'name': tag})) <NEW_LINE> prev = None if prev is None else link(u'Previous', expand(self.pagination, {'name': tag, 'num': prev})) <NEW_LINE> path = joinurl(conf['output_dir'], curr) <NEW_LINE> if isfile(path) and not (modified or tt.modified or env.modified or conf.modified): <NEW_LINE> <INDENT> event.skip('tag', path) <NEW_LINE> continue <NEW_LINE> <DEDENT> html = tt.render(conf=conf, env=union(env, entrylist=entries, type='tag', prev=prev, curr=curr, next=next, tag=tag, items_per_page=ipp, num_entries=len(entrylist), route=route)) <NEW_LINE> yield html, path | Same behaviour like Index except ``route`` that defaults to */tag/:name/* and
``pagination`` that defaults to */tag/:name/:num/* where :name is the current
tag identifier.
To create a tag cloud head over to :doc:`conf.py`. | 62598fed091ae35668705415 |
class NeighbourScheduler(NearestTransferCPUSelector, NoAdvanceTransmissionScheduler, BaseScheduler): <NEW_LINE> <INDENT> pass | Schedules DAG by neighbour appointment (no advance transmits) | 62598fed091ae35668705417 |
class JEvent(object): <NEW_LINE> <INDENT> def __init__(self, evt_type, number, value): <NEW_LINE> <INDENT> self.type = evt_type <NEW_LINE> self.number = number <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "JEvent(type={}, number={}, value={})".format( self.type, self.number, self.value) | Joystick event class. Encapsulate single joystick event. | 62598fed4c3428357761aaa8 |
class Bug35CModel(models.Model): <NEW_LINE> <INDENT> age = models.PositiveIntegerField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True | Ensure that multiple Postive Integer columns across tables don't
create duplicate constraint names when using inheritence.
The test for Bug35 is just the creation of the tables; there are no
other explicit tests. | 62598fed26238365f5fad35d |
class LayerNorm(nn.Module): <NEW_LINE> <INDENT> def __init__( self, input_size=None, input_shape=None, eps=1e-05, elementwise_affine=True, ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.eps = eps <NEW_LINE> self.elementwise_affine = elementwise_affine <NEW_LINE> if input_shape is not None: <NEW_LINE> <INDENT> input_size = input_shape[2:] <NEW_LINE> <DEDENT> self.norm = torch.nn.LayerNorm( input_size, eps=self.eps, elementwise_affine=self.elementwise_affine, ) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> return self.norm(x) | Applies layer normalization to the input tensor.
Arguments
---------
input_shape : tuple
The expected shape of the input.
eps : float
This value is added to std deviation estimation to improve the numerical
stability.
elementwise_affine : bool
If True, this module has learnable per-element affine parameters
initialized to ones (for weights) and zeros (for biases).
Example
-------
>>> input = torch.randn(100, 101, 128)
>>> norm = LayerNorm(input_shape=input.shape)
>>> output = norm(input)
>>> output.shape
torch.Size([100, 101, 128]) | 62598fedc4546d3d9def7685 |
class Actor: <NEW_LINE> <INDENT> x: int <NEW_LINE> y: int <NEW_LINE> _is_stop: bool <NEW_LINE> _is_push: bool <NEW_LINE> image: pygame.Surface <NEW_LINE> def __init__(self, x: int, y: int) -> None: <NEW_LINE> <INDENT> self.x, self.y = x, y <NEW_LINE> self._is_stop = False <NEW_LINE> self._is_push = False <NEW_LINE> self.image = pygame.Surface((TILESIZE, TILESIZE)) <NEW_LINE> <DEDENT> def is_stop(self) -> bool: <NEW_LINE> <INDENT> return self._is_stop <NEW_LINE> <DEDENT> def is_push(self) -> bool: <NEW_LINE> <INDENT> return self._is_push <NEW_LINE> <DEDENT> def copy(self) -> 'Actor': <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def move(self, game_: 'Game', dx: int, dy: int) -> bool: <NEW_LINE> <INDENT> curr_x=self.x+dx <NEW_LINE> curr_y=self.y+dy <NEW_LINE> if (curr_x > 25 or curr_y > 18): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if (curr_x < 0 or curr_y < 0): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> actor_in_line=[] <NEW_LINE> temp_x=curr_x <NEW_LINE> temp_y=curr_y <NEW_LINE> temp_actor=game_.get_actor(temp_x,temp_y) <NEW_LINE> if(temp_actor!=None): <NEW_LINE> <INDENT> print(temp_actor._is_push) <NEW_LINE> <DEDENT> while(temp_actor!=None and temp_actor._is_push): <NEW_LINE> <INDENT> actor_in_line.append(game_.get_actor(temp_x,temp_y)) <NEW_LINE> temp_x+=dx <NEW_LINE> temp_y+=dy <NEW_LINE> temp_actor = game_.get_actor(temp_x, temp_y) <NEW_LINE> print("while loop") <NEW_LINE> <DEDENT> if (temp_actor == None): <NEW_LINE> <INDENT> for temp_actor_in_line in actor_in_line: <NEW_LINE> <INDENT> actor_current_x = temp_actor_in_line.x + dx <NEW_LINE> actor_current_y = temp_actor_in_line.y + dy <NEW_LINE> rect_other_actor = pygame.Rect(actor_current_x * TILESIZE, actor_current_y * TILESIZE, TILESIZE, TILESIZE) <NEW_LINE> game_.screen.blit(temp_actor_in_line.image, rect_other_actor) <NEW_LINE> temp_actor_in_line.x = actor_current_x <NEW_LINE> temp_actor_in_line.y = actor_current_y <NEW_LINE> <DEDENT> <DEDENT> if(temp_actor!=None and temp_actor._is_push==False): <NEW_LINE> <INDENT> rect = pygame.Rect(curr_x * TILESIZE, curr_y * TILESIZE, TILESIZE, TILESIZE) <NEW_LINE> game_.screen.blit(self.image, rect) <NEW_LINE> self.x = curr_x <NEW_LINE> self.y = curr_y <NEW_LINE> <DEDENT> rect = pygame.Rect(curr_x * TILESIZE, curr_y * TILESIZE, TILESIZE, TILESIZE) <NEW_LINE> game_.screen.blit(self.image, rect) <NEW_LINE> self.x=curr_x <NEW_LINE> self.y=curr_y <NEW_LINE> return True | A class that represents all the actors in the game. This class includes any
attributes/methods that are common between the actors
=== Public Attributes ===
x:
x coordinate of this actor's location on the stage
y:
y coordinate of this actor's location on the stage
image:
the image of the actor
=== Private Attributes ===
_is_stop:
Flag to keep track of whether this object cannot be moved through
_is_push:
Flag to keep track of whether this object is pushable
Representation Invariant: x,y must be greater or equal to 0 | 62598fedc4546d3d9def7686 |
class PIR(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, pirpin, nomovementforseconds): <NEW_LINE> <INDENT> self.__pin = pirpin <NEW_LINE> self.__delay = nomovementforseconds <NEW_LINE> GPIO.setup(self.__pin, GPIO.IN) <NEW_LINE> self.__hasbeenmovement = True <NEW_LINE> super(PIR, self).__init__() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> t = time() <NEW_LINE> while True: <NEW_LINE> <INDENT> while GPIO.input(self.__pin) == 0: <NEW_LINE> <INDENT> if (time() - t) >= self.__delay: <NEW_LINE> <INDENT> self.__hasbeenmovement = False <NEW_LINE> <DEDENT> sleep(0.1) <NEW_LINE> <DEDENT> self.__hasbeenmovement = True <NEW_LINE> t = time() <NEW_LINE> sleep(0.1) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def hasbeenmovement(self): <NEW_LINE> <INDENT> return self.__hasbeenmovement | Detects whether there has been movement around the clock, and turns the matrix off if there has not been any | 62598fed091ae3566870541d |
class Tags(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=64) | Text tags used only with KModel instances | 62598fed187af65679d29ff9 |
class GoogleVisionAPISafeSearchExtractor(GoogleVisionAPIExtractor): <NEW_LINE> <INDENT> request_type = 'SAFE_SEARCH_DETECTION' <NEW_LINE> response_object = 'safeSearchAnnotation' <NEW_LINE> def _parse_annotations(self, annotation): <NEW_LINE> <INDENT> return annotation.keys(), annotation.values() | Extracts safe search detection using the Google Cloud Vision API. | 62598fed3cc13d1c6d465f56 |
class CustomStorageBase(ICustomStorage): <NEW_LINE> <INDENT> def registerCallbacks(self, properties): <NEW_LINE> <INDENT> callbacks = CustomStorageCallbacks( ctypes.c_void_p(), self.create, self.destroy, self.flush, self.loadByteArray, self.storeByteArray, self.deleteByteArray) <NEW_LINE> properties.custom_storage_callbacks_size = ctypes.sizeof(callbacks) <NEW_LINE> self.callbacks = callbacks <NEW_LINE> properties.custom_storage_callbacks = ctypes.cast(ctypes.pointer(callbacks), ctypes.c_void_p) <NEW_LINE> <DEDENT> def create(self, context, returnError): <NEW_LINE> <INDENT> returnError.contents.value = self.IllegalStateError <NEW_LINE> raise NotImplementedError("You must override this method.") <NEW_LINE> <DEDENT> def destroy(self, context, returnError): <NEW_LINE> <INDENT> returnError.contents.value = self.IllegalStateError <NEW_LINE> raise NotImplementedError("You must override this method.") <NEW_LINE> <DEDENT> def loadByteArray(self, context, page, resultLen, resultData, returnError): <NEW_LINE> <INDENT> returnError.contents.value = self.IllegalStateError <NEW_LINE> raise NotImplementedError("You must override this method.") <NEW_LINE> <DEDENT> def storeByteArray(self, context, page, len, data, returnError): <NEW_LINE> <INDENT> returnError.contents.value = self.IllegalStateError <NEW_LINE> raise NotImplementedError("You must override this method.") <NEW_LINE> <DEDENT> def deleteByteArray(self, context, page, returnError): <NEW_LINE> <INDENT> returnError.contents.value = self.IllegalStateError <NEW_LINE> raise NotImplementedError("You must override this method.") <NEW_LINE> <DEDENT> def flush(self, context, returnError): <NEW_LINE> <INDENT> returnError.contents.value = self.IllegalStateError <NEW_LINE> raise NotImplementedError("You must override this method.") | Derive from this class to create your own storage manager with access
to the raw C buffers. | 62598fedc4546d3d9def7688 |
class TwoByteChunk( object ): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.otherParameters = [ 0, 0] <NEW_LINE> <DEDENT> def serialize(self, outputStream): <NEW_LINE> <INDENT> for idx in range(0, 2): <NEW_LINE> <INDENT> outputStream.write_byte( self.otherParameters[ idx ] ); <NEW_LINE> <DEDENT> <DEDENT> def parse(self, inputStream): <NEW_LINE> <INDENT> self.otherParameters = [0]*2 <NEW_LINE> for idx in range(0, 2): <NEW_LINE> <INDENT> val = inputStream.read_byte() <NEW_LINE> self.otherParameters[ idx ] = val | 16 bit piece of data | 62598fed3cc13d1c6d465f58 |
class HealthcareProjectsLocationsDatasetsOperationsListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> name = _messages.StringField(2, required=True) <NEW_LINE> pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) <NEW_LINE> pageToken = _messages.StringField(4) | A HealthcareProjectsLocationsDatasetsOperationsListRequest object.
Fields:
filter: The standard list filter.
name: The name of the operation's parent resource.
pageSize: The standard list page size.
pageToken: The standard list page token. | 62598fed3cc13d1c6d465f5a |
class add_measure_group_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'str_addr', None, None, ), (2, TType.I32, 'interval', None, None, ), ) <NEW_LINE> def __init__(self, str_addr=None, interval=None,): <NEW_LINE> <INDENT> self.str_addr = str_addr <NEW_LINE> self.interval = interval <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.str_addr = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.interval = iprot.readI32(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('add_measure_group_args') <NEW_LINE> if self.str_addr is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('str_addr', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.str_addr) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.interval is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('interval', TType.I32, 2) <NEW_LINE> oprot.writeI32(self.interval) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- str_addr
- interval | 62598fed4c3428357761aab4 |
class PCFG(CFG): <NEW_LINE> <INDENT> EPSILON = 0.01 <NEW_LINE> def __init__(self, start, productions, calculate_leftcorners=True): <NEW_LINE> <INDENT> CFG.__init__(self, start, productions, calculate_leftcorners) <NEW_LINE> probs = {} <NEW_LINE> for production in productions: <NEW_LINE> <INDENT> probs[production.lhs()] = (probs.get(production.lhs(), 0) + production.prob()) <NEW_LINE> <DEDENT> for (lhs, p) in probs.items(): <NEW_LINE> <INDENT> if not ((1-PCFG.EPSILON) < p < (1+PCFG.EPSILON)): <NEW_LINE> <INDENT> raise ValueError("Productions for %r do not sum to 1" % lhs) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def fromstring(cls, input, encoding=None): <NEW_LINE> <INDENT> start, productions = read_grammar(input, standard_nonterm_parser, probabilistic=True, encoding=encoding) <NEW_LINE> return PCFG(start, productions) | A probabilistic context-free grammar. A PCFG consists of a
start state and a set of productions with probabilities. The set of
terminals and nonterminals is implicitly specified by the productions.
PCFG productions use the ``ProbabilisticProduction`` class.
``PCFGs`` impose the constraint that the set of productions with
any given left-hand-side must have probabilities that sum to 1
(allowing for a small margin of error).
If you need efficient key-based access to productions, you can use
a subclass to implement it.
:type EPSILON: float
:cvar EPSILON: The acceptable margin of error for checking that
productions with a given left-hand side have probabilities
that sum to 1. | 62598fed187af65679d29ffd |
class JsAPIOrderPay(UnifiedOrderPay): <NEW_LINE> <INDENT> def __init__(self, wechat_config): <NEW_LINE> <INDENT> super(JsAPIOrderPay, self).__init__(wechat_config) <NEW_LINE> self.trade_type = 'JSAPI' <NEW_LINE> <DEDENT> def post(self, body, out_trade_no, total_fee, spbill_create_ip, notify_url, open_id, url): <NEW_LINE> <INDENT> print("starting to post...") <NEW_LINE> unified_order = super(JsAPIOrderPay, self)._post(body, out_trade_no, total_fee, spbill_create_ip, notify_url, open_id=open_id) <NEW_LINE> print("post done!") <NEW_LINE> nonce_str = random_str(length=32) <NEW_LINE> time_stamp = time.time() <NEW_LINE> pay_params = {'appId': self.app_id, 'timeStamp': '%d' % time_stamp, 'nonceStr': nonce_str, 'package': 'prepay_id=%s' % unified_order.get('prepay_id'), 'signType': 'MD5'} <NEW_LINE> print("starting to sign url") <NEW_LINE> pay_params['paySign'] = sign_url( pay_params, self.api_key, key_name='key', upper_case=True) <NEW_LINE> print("sgin done!") <NEW_LINE> unified_order.update({'pay_params': pay_params, 'config_params': self.get_js_config_params(url, nonce_str, time_stamp)}) <NEW_LINE> return unified_order | H5页面的js调用类 | 62598fedad47b63b2c5a805d |
class Describe_SortRowsByDerivedColumnHelper: <NEW_LINE> <INDENT> def it_derives_the_sort_column_idx_from_the_order_spec_to_help( self, _columns_dimension_prop_, dimension_, _order_spec_prop_, order_spec_ ): <NEW_LINE> <INDENT> _columns_dimension_prop_.return_value = dimension_ <NEW_LINE> dimension_.element_ids = (1, 2, 3, 4, 5) <NEW_LINE> dimension_.translate_element_id.return_value = 3 <NEW_LINE> _order_spec_prop_.return_value = order_spec_ <NEW_LINE> order_spec_.insertion_id = "c" <NEW_LINE> order_helper = _SortRowsByDerivedColumnHelper(None, None) <NEW_LINE> column_idx = order_helper._column_idx <NEW_LINE> dimension_.translate_element_id.assert_called_once_with("c") <NEW_LINE> assert column_idx == 2 <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def _columns_dimension_prop_(self, request): <NEW_LINE> <INDENT> return property_mock(request, _SortRowsByBaseColumnHelper, "_columns_dimension") <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def dimension_(self, request): <NEW_LINE> <INDENT> return instance_mock(request, Dimension) <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def order_spec_(self, request): <NEW_LINE> <INDENT> return instance_mock(request, _OrderSpec) <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def _order_spec_prop_(self, request): <NEW_LINE> <INDENT> return property_mock(request, _SortRowsByBaseColumnHelper, "_order_spec") | Unit test suite for `cr.cube.matrix.assembler._SortRowsByDerivedColumnHelper`. | 62598fedc4546d3d9def768d |
class ProfileSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> owner = serializers.ReadOnlyField(source='owner.username') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Profile <NEW_LINE> fields = ('owner', 'first_name', 'last_name', 'email', 'date_created', 'date_modified' ) <NEW_LINE> read_only_fields = ('date_created', 'date_modified') | Serializer to map the Model instance into JSON format. | 62598fed4c3428357761aaba |
class TestFilename(unittest.TestCase): <NEW_LINE> <INDENT> def test_ordinary(self): <NEW_LINE> <INDENT> date = datetime(2016, 11, 12) <NEW_LINE> seq = 36 <NEW_LINE> name = star_barcode.barcode_filename(date, seq) <NEW_LINE> self.assertEqual( name, 'Barcode_2016-W45-6_36.pdf' ) <NEW_LINE> <DEDENT> def test_wrong_sequence(self): <NEW_LINE> <INDENT> date = datetime(2016, 11, 12) <NEW_LINE> seq = 31 <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> star_barcode.barcode_filename(date, seq) <NEW_LINE> <DEDENT> <DEDENT> def test_year_boundary(self): <NEW_LINE> <INDENT> date = datetime(2017, 1, 1) <NEW_LINE> seq = 27 <NEW_LINE> name = star_barcode.barcode_filename(date, seq) <NEW_LINE> self.assertEqual( name, 'Barcode_2016-W52-7_27.pdf' ) <NEW_LINE> <DEDENT> def test_price_code_0(self): <NEW_LINE> <INDENT> start_date = datetime(2016, 11, 13) <NEW_LINE> for x in range(1, 7): <NEW_LINE> <INDENT> with self.subTest(x=x): <NEW_LINE> <INDENT> date = start_date + timedelta(x) <NEW_LINE> result = star_barcode.barcode_filename(date, x) <NEW_LINE> self.assertEqual( result.split('.')[0][-2:], f'{x:02}' ) | Test barcode_filename function for naming barcode
barcode_filename should take a datetime object and an int,
representing the sequence number of the edition, and
produce a string as so:
Barcode_%G-W%V-%u_SS.pdf
Where %G is the ISO year number, %V the ISO week number,
and %u the ISO weekday number. SS is the sequence int. | 62598fed187af65679d2a000 |
class Review(models.Model): <NEW_LINE> <INDENT> author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='review author', related_name='review_author') <NEW_LINE> thesis = models.ForeignKey(Thesis, on_delete=models.CASCADE, verbose_name='reviewed thesis', related_name='reviewed_thesis') <NEW_LINE> @property <NEW_LINE> def finished(self): <NEW_LINE> <INDENT> return True if self.file.name else False <NEW_LINE> <DEDENT> finished_date = models.DateTimeField('finished date', null=True, blank=True, default=None) <NEW_LINE> @property <NEW_LINE> def deadline(self): <NEW_LINE> <INDENT> return self.thesis.finished_date.date() + timedelta(weeks=2) <NEW_LINE> <DEDENT> def get_file_path(self, filename): <NEW_LINE> <INDENT> file_ext = filename.split('.')[-1] <NEW_LINE> return os.path.join(settings.MEDIA_ROOT, 'theses/thesis_{0}/review.{1}'.format(self.thesis.id, file_ext)) <NEW_LINE> <DEDENT> file = models.FileField(upload_to=get_file_path, verbose_name='review file', null=True, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.get_review_name() <NEW_LINE> <DEDENT> def get_review_name(self): <NEW_LINE> <INDENT> review_name = 'Review #{} by {} of {}'.format(self.id, self.author, self.thesis.get_thesis_name) <NEW_LINE> return review_name.strip() | Review class represents the Review table in the database. It contains following attributes:
author, thesis, finished, finished_date
which can be used to access database regardless of the language it uses
Methods:
deadline(), get_file_path(filename), __str__(), get_review_name() | 62598fed627d3e7fe0e076b6 |
class Insert(StandardInsert): <NEW_LINE> <INDENT> stringify_dialect = "mysql" <NEW_LINE> inherit_cache = False <NEW_LINE> @property <NEW_LINE> def inserted(self): <NEW_LINE> <INDENT> return self.inserted_alias.columns <NEW_LINE> <DEDENT> @util.memoized_property <NEW_LINE> def inserted_alias(self): <NEW_LINE> <INDENT> return alias(self.table, name="inserted") <NEW_LINE> <DEDENT> @_generative <NEW_LINE> @_exclusive_against( "_post_values_clause", msgs={ "_post_values_clause": "This Insert construct already " "has an ON DUPLICATE KEY clause present" }, ) <NEW_LINE> def on_duplicate_key_update(self, *args, **kw): <NEW_LINE> <INDENT> if args and kw: <NEW_LINE> <INDENT> raise exc.ArgumentError( "Can't pass kwargs and positional arguments simultaneously" ) <NEW_LINE> <DEDENT> if args: <NEW_LINE> <INDENT> if len(args) > 1: <NEW_LINE> <INDENT> raise exc.ArgumentError( "Only a single dictionary or list of tuples " "is accepted positionally." ) <NEW_LINE> <DEDENT> values = args[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> values = kw <NEW_LINE> <DEDENT> inserted_alias = getattr(self, "inserted_alias", None) <NEW_LINE> self._post_values_clause = OnDuplicateClause(inserted_alias, values) | MySQL-specific implementation of INSERT.
Adds methods for MySQL-specific syntaxes such as ON DUPLICATE KEY UPDATE.
The :class:`~.mysql.Insert` object is created using the
:func:`sqlalchemy.dialects.mysql.insert` function.
.. versionadded:: 1.2 | 62598fedc4546d3d9def768f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.