code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Player(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, screen): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.__pikachuleft = pygame.image.load("1pikachu-left.gif") <NEW_LINE> self.__pikachuleft = self.__pikachuleft.convert() <NEW_LINE> self.__pikachuright = pygame.image.load("1pikachu-right.gif") <NEW_LINE> self.__pikachuright = self.__pikachuright.convert() <NEW_LINE> self.image = self.__pikachuleft <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.bottom = 470 <NEW_LINE> self.rect.left = screen.get_width()/2-50 <NEW_LINE> self.__screen = screen <NEW_LINE> self.__dx = 0 <NEW_LINE> self.__dy = 3 <NEW_LINE> <DEDENT> def go_right(self): <NEW_LINE> <INDENT> self.image = self.__pikachuright <NEW_LINE> self.__dx = 10 <NEW_LINE> <DEDENT> def go_left(self): <NEW_LINE> <INDENT> self.image = self.__pikachuleft <NEW_LINE> self.__dx = -10 <NEW_LINE> <DEDENT> def go_up(self): <NEW_LINE> <INDENT> self.__dy = -7 <NEW_LINE> <DEDENT> def go_down(self): <NEW_LINE> <INDENT> self.__dy = 13 <NEW_LINE> <DEDENT> def keep_going_x(self): <NEW_LINE> <INDENT> self.__dx = 0 <NEW_LINE> <DEDENT> def keep_going_y(self): <NEW_LINE> <INDENT> self.__dy = 0 <NEW_LINE> <DEDENT> def gravity(self): <NEW_LINE> <INDENT> self.__dy = 3 <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.rect.left < 0: <NEW_LINE> <INDENT> self.rect.left = 0 <NEW_LINE> <DEDENT> self.rect.right += self.__dx <NEW_LINE> if self.rect.right > self.__screen.get_width(): <NEW_LINE> <INDENT> self.rect.right = 640 <NEW_LINE> <DEDENT> if self.rect.top < 0: <NEW_LINE> <INDENT> self.rect.top = 0 <NEW_LINE> <DEDENT> self.rect.bottom +=self.__dy <NEW_LINE> if self.rect.bottom > self.__screen.get_height(): <NEW_LINE> <INDENT> self.rect.bottom = 480 | This class defines the sprite for Player | 62598f9e9c8ee82313040068 |
class deleteStickerFromSet(TelegramMethodBase): <NEW_LINE> <INDENT> ReturnType = bool <NEW_LINE> def __init__(self, sticker: str): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.sticker = sticker | Use this method to delete a sticker from a set created by the bot. Returns True on success.
:param sticker: (str) File identifier of the sticker | 62598f9e3539df3088ecc0aa |
class IotHubClientConfiguration(AzureConfiguration): <NEW_LINE> <INDENT> def __init__( self, credentials, subscription_id, api_version='2016-02-03', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): <NEW_LINE> <INDENT> if credentials is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credentials' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> if not isinstance(subscription_id, str): <NEW_LINE> <INDENT> raise TypeError("Parameter 'subscription_id' must be str.") <NEW_LINE> <DEDENT> if api_version is not None and not isinstance(api_version, str): <NEW_LINE> <INDENT> raise TypeError("Optional parameter 'api_version' must be str.") <NEW_LINE> <DEDENT> if accept_language is not None and not isinstance(accept_language, str): <NEW_LINE> <INDENT> raise TypeError("Optional parameter 'accept_language' must be str.") <NEW_LINE> <DEDENT> if not base_url: <NEW_LINE> <INDENT> base_url = 'https://management.azure.com' <NEW_LINE> <DEDENT> super(IotHubClientConfiguration, self).__init__(base_url, filepath) <NEW_LINE> self.add_user_agent('iothubclient/{}'.format(VERSION)) <NEW_LINE> self.add_user_agent('Azure-SDK-For-Python') <NEW_LINE> self.credentials = credentials <NEW_LINE> self.subscription_id = subscription_id <NEW_LINE> self.api_version = api_version <NEW_LINE> self.accept_language = accept_language <NEW_LINE> self.long_running_operation_retry_timeout = long_running_operation_retry_timeout <NEW_LINE> self.generate_client_request_id = generate_client_request_id | Configuration for IotHubClient
Note that all parameters used to create this instance are saved as instance
attributes.
:param credentials: Credentials needed for the client to connect to Azure.
:type credentials: :mod:`A msrestazure Credentials
object<msrestazure.azure_active_directory>`
:param subscription_id: The subscription identifier.
:type subscription_id: str
:param api_version: The version of the API.
:type api_version: str
:param accept_language: Gets or sets the preferred language for the
response.
:type accept_language: str
:param long_running_operation_retry_timeout: Gets or sets the retry
timeout in seconds for Long Running Operations. Default value is 30.
:type long_running_operation_retry_timeout: int
:param generate_client_request_id: When set to true a unique
x-ms-client-request-id value is generated and included in each request.
Default is true.
:type generate_client_request_id: bool
:param str base_url: Service URL
:param str filepath: Existing config | 62598f9e379a373c97d98e0a |
class Platforms(object): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> <DEDENT> @property <NEW_LINE> def instances(self): <NEW_LINE> <INDENT> return self._config.config['platforms'] | Platforms define the instances to be tested, and the groups to which the
instances belong.
.. code-block:: yaml
platforms:
- name: instance-1
Multiple instances can be provided.
.. code-block:: yaml
platforms:
- name: instance-1
- name: instance-2
Mapping instances to groups. These groups will be used by the Provisioner_
for orchestration purposes.
.. code-block:: yaml
platforms:
- name: instance-1
groups:
- group1
- group2
Children allow the creation of groups of groups.
.. code-block:: yaml
platforms:
- name: instance-1
groups:
- group1
- group2
children:
- child_group1 | 62598f9e442bda511e95c250 |
class TestAccessLogEntry(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 make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return AccessLogEntry( uuid = '0', status = 56, method = '0', request_uri = '0', time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), request_payload = '0', response_payload = '0' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return AccessLogEntry( uuid = '0', status = 56, method = '0', request_uri = '0', time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), request_payload = '0', response_payload = '0', ) <NEW_LINE> <DEDENT> <DEDENT> def testAccessLogEntry(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | AccessLogEntry unit test stubs | 62598f9ef7d966606f747ddd |
class ListElement: <NEW_LINE> <INDENT> _key = None <NEW_LINE> _next = None <NEW_LINE> _previous = None <NEW_LINE> def __init__(self, key=0): <NEW_LINE> <INDENT> self._key = key <NEW_LINE> <DEDENT> def set_next(self, next_element): <NEW_LINE> <INDENT> self._next = next_element <NEW_LINE> <DEDENT> def get_next(self): <NEW_LINE> <INDENT> return self._next <NEW_LINE> <DEDENT> def set_previous(self, prev): <NEW_LINE> <INDENT> self._previous = prev <NEW_LINE> <DEDENT> def get_previous(self): <NEW_LINE> <INDENT> return self._previous | Class represents elemnt of the list | 62598f9e60cbc95b06364142 |
class Multiplicity (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'Multiplicity') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('c:\\Users\\Omar\\PycharmProjects\\volib\\volib\\resources\\vo-dml.xsd', 808, 2) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __minOccurs = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(None, 'minOccurs'), 'minOccurs', '__httpvolute_googlecode_comdmvo_dmlv0_9_Multiplicity_minOccurs', False, pyxb.utils.utility.Location('c:\\Users\\Omar\\PycharmProjects\\volib\\volib\\resources\\vo-dml.xsd', 818, 6), ) <NEW_LINE> minOccurs = property(__minOccurs.value, __minOccurs.set, None, '\n Lower bound on number of instances/values.\n ') <NEW_LINE> __maxOccurs = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(None, 'maxOccurs'), 'maxOccurs', '__httpvolute_googlecode_comdmvo_dmlv0_9_Multiplicity_maxOccurs', False, pyxb.utils.utility.Location('c:\\Users\\Omar\\PycharmProjects\\volib\\volib\\resources\\vo-dml.xsd', 825, 6), ) <NEW_LINE> maxOccurs = property(__maxOccurs.value, __maxOccurs.set, None, '\n When negative, unbounded.\n ') <NEW_LINE> _ElementMap.update({ __minOccurs.name() : __minOccurs, __maxOccurs.name() : __maxOccurs }) <NEW_LINE> _AttributeMap.update({ }) | Also called "Cardinality". Indicates how many instances of a datatype can/must be associated to a given role.
Unless
Follows model in XSD, i.e. with explicit lower bound and upper bound on number of instances.
maxOccurs must be gte minOccurs, unless it is negative, in which case it corresponds to unbounded. | 62598f9e3eb6a72ae038a437 |
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class StandardEvaluable(runnable.AbstractEvaluable): <NEW_LINE> <INDENT> def __init__(self, use_tf_function=True): <NEW_LINE> <INDENT> self.eval_use_tf_function = use_tf_function <NEW_LINE> self.eval_dataset = None <NEW_LINE> self.eval_loop_fn = None <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def build_eval_dataset(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def evaluate( self, num_steps: Optional[tf.Tensor]) -> Optional[Dict[Text, tf.Tensor]]: <NEW_LINE> <INDENT> if self.eval_dataset is None: <NEW_LINE> <INDENT> self.eval_dataset = self.build_eval_dataset() <NEW_LINE> <DEDENT> if self.eval_loop_fn is None: <NEW_LINE> <INDENT> eval_fn = self.eval_step <NEW_LINE> if self.eval_use_tf_function: <NEW_LINE> <INDENT> eval_fn = tf.function(eval_fn) <NEW_LINE> <DEDENT> self.eval_loop_fn = utils.create_loop_fn(eval_fn) <NEW_LINE> <DEDENT> self.eval_iter = tf.nest.map_structure(iter, self.eval_dataset) <NEW_LINE> self.eval_begin() <NEW_LINE> self.eval_loop_fn(self.eval_iter, num_steps) <NEW_LINE> return self.eval_end() <NEW_LINE> <DEDENT> def eval_begin(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def eval_step(self, iterator): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def eval_end(self) -> Optional[Dict[Text, tf.Tensor]]: <NEW_LINE> <INDENT> pass | Implements the standard functionality of AbstractEvaluable APIs. | 62598f9e66656f66f7d5a1e7 |
class WebAnnotatorLoader(HtmlLoader): <NEW_LINE> <INDENT> def __init__(self, encoding=None, cleaner=None, known_entities=None): <NEW_LINE> <INDENT> self.known_entities = known_entities <NEW_LINE> super(WebAnnotatorLoader, self).__init__(encoding, cleaner) <NEW_LINE> <DEDENT> def loadbytes(self, data): <NEW_LINE> <INDENT> tree = html_document_fromstring(data, encoding=self.encoding) <NEW_LINE> webannotator.apply_wa_title(tree) <NEW_LINE> if self.known_entities: <NEW_LINE> <INDENT> self._prune_tags(tree) <NEW_LINE> <DEDENT> entities = self._get_entities(tree) <NEW_LINE> self._process_entities(entities) <NEW_LINE> return self._cleanup_tree(tree) <NEW_LINE> <DEDENT> def _prune_tags(self, tree): <NEW_LINE> <INDENT> for el in tree.xpath('//span[@wa-type]'): <NEW_LINE> <INDENT> if el.attrib['wa-type'] not in self.known_entities: <NEW_LINE> <INDENT> el.drop_tag() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _get_entities(self, tree): <NEW_LINE> <INDENT> entities = defaultdict(list) <NEW_LINE> for el in tree.xpath('//span[@wa-id]'): <NEW_LINE> <INDENT> entities[el.attrib['wa-id']].append(el) <NEW_LINE> <DEDENT> return dict(entities) <NEW_LINE> <DEDENT> def _process_entities(self, entities): <NEW_LINE> <INDENT> for _id, elems in entities.items(): <NEW_LINE> <INDENT> tp = elems[0].attrib['wa-type'] <NEW_LINE> elems[0].text = ' __START_%s__ %s' % (tp, elems[0].text or '') <NEW_LINE> elems[-1].text = '%s __END_%s__ ' % (elems[-1].text or '', tp) <NEW_LINE> for el in elems: <NEW_LINE> <INDENT> el.drop_tag() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _cleanup_tree(self, tree): <NEW_LINE> <INDENT> for el in tree.xpath('//wa-color'): <NEW_LINE> <INDENT> el.drop_tree() <NEW_LINE> <DEDENT> return self.cleaner.clean_html(tree) | Class for loading HTML annotated using
`WebAnnotator <https://github.com/xtannier/WebAnnotator>`_.
.. note::
Use WebAnnotator's "save format", not "export format". | 62598f9e435de62698e9bbea |
class Cells: <NEW_LINE> <INDENT> def __init__(self, xi, ori, sim): <NEW_LINE> <INDENT> self.xi = xi <NEW_LINE> self.ori = ori <NEW_LINE> self.vel = {} <NEW_LINE> return <NEW_LINE> <DEDENT> def calculate_ORI(self, sim): <NEW_LINE> <INDENT> ndelay = int(sim.nsteps/2.0) <NEW_LINE> delay = np.zeros((ndelay), dtype=np.float64) <NEW_LINE> msd = np.zeros((ndelay), dtype=np.float64) <NEW_LINE> for d in range(1, ndelay): <NEW_LINE> <INDENT> delay[d] = d <NEW_LINE> msd[d] = np.mean((self.ori[d:].T*self.ori[:-d].T).sum(axis=0).T.mean(axis=0)) <NEW_LINE> <DEDENT> return delay, msd <NEW_LINE> <DEDENT> def pdistwithpbc(self, sim, t): <NEW_LINE> <INDENT> xx = self.xi[t,:,0]; yy = self.xi[t,:,1] <NEW_LINE> for (xd,ll) in [(xx,sim.lx),(yy,sim.ly)]: <NEW_LINE> <INDENT> pd = pdist(xd.reshape(xd.shape[0],1)) <NEW_LINE> pd = pd-ll*np.round(pd/ll) <NEW_LINE> try: <NEW_LINE> <INDENT> total+=pd**2 <NEW_LINE> <DEDENT> except(NameError): <NEW_LINE> <INDENT> total=pd**2 <NEW_LINE> <DEDENT> <DEDENT> pd = np.sqrt(total) <NEW_LINE> return pd <NEW_LINE> <DEDENT> def pori(self, sim, t): <NEW_LINE> <INDENT> iu = np.triu_indices(sim.nfils,1) <NEW_LINE> orit = self.ori[t,:] <NEW_LINE> return dotproduct(orit[iu[0]], orit[iu[1]]) <NEW_LINE> <DEDENT> def dispcorr(self, sim, t, lag): <NEW_LINE> <INDENT> iu = np.triu_indices(sim.nfils,1) <NEW_LINE> dx = self.xi[t+lag,:,:] - self.xi[t,:,:] <NEW_LINE> return dotproduct(dx[iu[0]], dx[iu[1]]), sum(dotproduct(dx,dx)) <NEW_LINE> <DEDENT> def displacements(self, sim, lag): <NEW_LINE> <INDENT> dx = self.xi[:-lag, :, :] - self.xi[lag:, :, :] <NEW_LINE> self.vel[lag] = dx <NEW_LINE> <DEDENT> def velocity_projection_not_normalised(self, lag): <NEW_LINE> <INDENT> v = np.array([xx.T for xx in self.vel[lag]]) <NEW_LINE> ori = self.ori[:-lag] <NEW_LINE> return np.sum(v*ori, axis=2) <NEW_LINE> <DEDENT> def velocity_projection_normalised(self, lag): <NEW_LINE> <INDENT> v = np.array([xx.T for xx in self.vel[lag]]) <NEW_LINE> ori = self.ori[:-lag] <NEW_LINE> normed = np.linalg.norm(v, axis=2)[:,:,np.newaxis] <NEW_LINE> vnorm = v/normed <NEW_LINE> return np.sum(vnorm*ori, axis=2) | data structure for storing cell information | 62598f9e24f1403a926857ad |
class ConfigApp(Config): <NEW_LINE> <INDENT> def __init__(self, app_id: str, app_key: str, ambiente: str = PRODUCAO): <NEW_LINE> <INDENT> super().__init__(ambiente) <NEW_LINE> self.app_key = app_key <NEW_LINE> self.app_id = app_id <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> app_key_omitida = '*' * len(self.app_key) <NEW_LINE> return f'ConfigApp(app_id={self.app_id!r}, app_key={app_key_omitida!r})' <NEW_LINE> <DEDENT> def query_string(self) -> str: <NEW_LINE> <INDENT> return f'appID={self.app_id}&appKey={self.app_key}' | Classe que representa uma configuração por app_id e app_key | 62598f9efff4ab517ebcd5e3 |
class League(object): <NEW_LINE> <INDENT> def __init__(self, match_class=Match, teams=[]): <NEW_LINE> <INDENT> self._raw_teams = teams <NEW_LINE> self._wrap_teams() <NEW_LINE> self._round = 0 <NEW_LINE> self._match_class = match_class <NEW_LINE> <DEDENT> @property <NEW_LINE> def round(self): <NEW_LINE> <INDENT> return self._round <NEW_LINE> <DEDENT> def _wrap_teams(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _merge_stats(self, match): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def play_round(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def play_season(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> self.play_round() <NEW_LINE> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return self._teams[0] <NEW_LINE> <DEDENT> <DEDENT> def print_standings(self): <NEW_LINE> <INDENT> raise NotImplementedError | A generic league-style competition. | 62598f9e4e4d56256637221a |
class Lightpath(object): <NEW_LINE> <INDENT> _ids = count(0) <NEW_LINE> def __init__(self, route: List[int], wavelength: int): <NEW_LINE> <INDENT> self._id: int = next(self._ids) <NEW_LINE> self._route: List[int] = route <NEW_LINE> self._wavelength: int = wavelength <NEW_LINE> self._holding_time: float = 0.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self) -> int: <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @property <NEW_LINE> def r(self) -> List[int]: <NEW_LINE> <INDENT> return self._route <NEW_LINE> <DEDENT> @property <NEW_LINE> def links(self) -> Iterable[Tuple[int, int]]: <NEW_LINE> <INDENT> iterable = iter(self._route) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> yield next(iterable), next(iterable) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def w(self) -> int: <NEW_LINE> <INDENT> return self._wavelength <NEW_LINE> <DEDENT> @property <NEW_LINE> def holding_time(self) -> float: <NEW_LINE> <INDENT> return self._holding_time <NEW_LINE> <DEDENT> @holding_time.setter <NEW_LINE> def holding_time(self, time: float) -> None: <NEW_LINE> <INDENT> self._holding_time = time <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.r) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s %d' % (self._route, self._wavelength) | Emulates a lightpath composed by a route and a wavelength channel
Lightpath is pretty much a regular path, but must also specify a wavelength
index, since WDM optical networks span multiple wavelength channels over a
single fiber link on the topology.
A Lightpath object also store a holding time parameter, which is set along
the simulation to specify how long the connection may be alive and running
on network links, and therefore taking up space in the traffic matrix,
before it finally terminates and resources are deallocated.
Args:
route: a liste of nodes encoded as integer indices
wavelength: a single number representing the wavelength channel index | 62598f9efbf16365ca793eaf |
class BoardJobPost(TimestampMixin, db.Model): <NEW_LINE> <INDENT> __tablename__ = 'board_jobpost' <NEW_LINE> board_id = db.Column(None, db.ForeignKey('board.id'), primary_key=True) <NEW_LINE> board = db.relationship(Board, backref=db.backref('boardposts', lazy='dynamic', cascade='all, delete-orphan')) <NEW_LINE> jobpost_id = db.Column(None, db.ForeignKey('jobpost.id'), primary_key=True) <NEW_LINE> jobpost = db.relationship(JobPost, backref=db.backref('postboards', lazy='dynamic', order_by='BoardJobPost.created_at', cascade='all, delete-orphan')) <NEW_LINE> pinned = db.Column(db.Boolean, default=False, nullable=False) | Link job posts to boards. | 62598f9e004d5f362081eef8 |
class User(CommonModel, db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> user_id = db.Column(UUID, primary_key=True, default=new_uuid) <NEW_LINE> credentials = db.Column(JSONB, nullable=False) <NEW_LINE> secrets = db.Column(Text) <NEW_LINE> settings = db.Column(JSONB, nullable=False) <NEW_LINE> social = db.Column(JSONB) <NEW_LINE> PUBLIC = (user_id, credentials, settings, social) <NEW_LINE> def __init__(self, credentials, secrets, settings=None, social=None): <NEW_LINE> <INDENT> self.credentials = credentials <NEW_LINE> self.secrets = secrets <NEW_LINE> self.settings = settings or {} <NEW_LINE> self.social = social or {} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def find_by_credentials(cls, credentials, secrets): <NEW_LINE> <INDENT> query = cls.query.filter( text('credentials = :credentials and secrets = :secrets')) <NEW_LINE> query = query.params( credentials=PGJson(credentials), secrets=secrets) <NEW_LINE> return query.order_by(cls.created).first() | Users, many are present in the database. | 62598f9ed268445f26639a7e |
class Swish(nn.Module): <NEW_LINE> <INDENT> def __init__(self, inplace=False): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.inplace = inplace <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> return swish(x, self.inplace) | Swish activation function [1].
References:
[1]: Searching for Activation Functions,
https://arxiv.org/abs/1710.05941 | 62598f9e44b2445a339b6868 |
class UHF(hf.RHF): <NEW_LINE> <INDENT> def __init__(self, scf_method): <NEW_LINE> <INDENT> hf.RHF.__init__(self, scf_method) <NEW_LINE> if scf_method.with_ssss: <NEW_LINE> <INDENT> self.level = 'SSSS' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.level = 'LLLL' <NEW_LINE> <DEDENT> <DEDENT> @pyscf.lib.omnimethod <NEW_LINE> def get_hcore(self, mol=None): <NEW_LINE> <INDENT> if mol is None: <NEW_LINE> <INDENT> mol = self.mol <NEW_LINE> <DEDENT> return get_hcore(mol) <NEW_LINE> <DEDENT> @pyscf.lib.omnimethod <NEW_LINE> def get_ovlp(self, mol=None): <NEW_LINE> <INDENT> if mol is None: <NEW_LINE> <INDENT> mol = self.mol <NEW_LINE> <DEDENT> return get_ovlp(mol) <NEW_LINE> <DEDENT> def _grad_rinv(self, mol, ia): <NEW_LINE> <INDENT> n2c = mol.nao_2c() <NEW_LINE> n4c = n2c * 2 <NEW_LINE> c = mol.light_speed <NEW_LINE> v = numpy.zeros((3,n4c,n4c), numpy.complex) <NEW_LINE> mol.set_rinv_origin_(mol.atom_coord(ia)) <NEW_LINE> vn = mol.atom_charge(ia) * mol.intor('cint1e_iprinv', comp=3) <NEW_LINE> wn = mol.atom_charge(ia) * mol.intor('cint1e_ipsprinvsp', comp=3) <NEW_LINE> v[:,:n2c,:n2c] = vn <NEW_LINE> v[:,n2c:,n2c:] = wn * (.25/c**2) <NEW_LINE> return v <NEW_LINE> <DEDENT> def get_veff(self, mol, dm): <NEW_LINE> <INDENT> return get_coulomb_hf(mol, dm, level=self.level) <NEW_LINE> <DEDENT> def matblock_by_atom(self, mol, atm_id, mat): <NEW_LINE> <INDENT> return matblock_by_atom(mol, atm_id, mat) | Unrestricted Dirac-Hartree-Fock gradients | 62598f9ebaa26c4b54d4f0a4 |
class MatrixSquareRoot(Function): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def forward(ctx, input): <NEW_LINE> <INDENT> m = input.detach().cpu().numpy().astype(np.float_) <NEW_LINE> sqrtm = torch.from_numpy(scipy.linalg.sqrtm(m).real) <NEW_LINE> ctx.save_for_backward(sqrtm) <NEW_LINE> sqrtm = sqrtm.type_as(input) <NEW_LINE> return sqrtm <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def backward(ctx, grad_output): <NEW_LINE> <INDENT> grad_input = None <NEW_LINE> if ctx.needs_input_grad[0]: <NEW_LINE> <INDENT> sqrtm, = ctx.saved_tensors <NEW_LINE> sqrtm = sqrtm.data.numpy().astype(np.float_) <NEW_LINE> gm = grad_output.data.cpu().numpy().astype(np.float_) <NEW_LINE> grad_sqrtm = scipy.linalg.solve_sylvester(sqrtm, sqrtm, gm) <NEW_LINE> grad_input = torch.from_numpy(grad_sqrtm).type_as(grad_output.data) <NEW_LINE> <DEDENT> return Variable(grad_input) | Square root of a positive definite matrix.
Given a positive semi-definite matrix X,
X = X^{1/2}X^{1/2}, compute the gradient: dX^{1/2} by solving the Sylvester equation,
dX = (d(X^{1/2})X^{1/2} + X^{1/2}(dX^{1/2}). | 62598f9e67a9b606de545dbf |
class EntityList(list): <NEW_LINE> <INDENT> def __init__(self, data=[], meta=None): <NEW_LINE> <INDENT> list.__init__(self, data) <NEW_LINE> self._meta = meta | EntityList provides an iterable of API entities along with a _meta
dictionary that contains information about the query results. This could
include result count and pagination details. | 62598f9e67a9b606de545dc0 |
class Windows2008and7(Windows): <NEW_LINE> <INDENT> def __init__(self, tdl, config, auto, output_disk): <NEW_LINE> <INDENT> Windows.__init__(self, tdl, config, output_disk) <NEW_LINE> self.unattendfile = auto <NEW_LINE> if self.unattendfile is None: <NEW_LINE> <INDENT> self.unattendfile = oz.ozutil.generate_full_auto_path("windows-" + self.tdl.update + "-jeos.xml") <NEW_LINE> <DEDENT> <DEDENT> def _generate_new_iso(self): <NEW_LINE> <INDENT> self.log.debug("Generating new ISO") <NEW_LINE> oz.ozutil.subprocess_check_output(["genisoimage", "-b", "cdboot/boot.bin", "-no-emul-boot", "-c", "BOOT.CAT", "-iso-level", "2", "-J", "-l", "-D", "-N", "-joliet-long", "-relaxed-filenames", "-v", "-v", "-V", "Custom", "-udf", "-o", self.output_iso, self.iso_contents]) <NEW_LINE> <DEDENT> def _get_windows_arch(self): <NEW_LINE> <INDENT> arch = "x86" <NEW_LINE> if self.tdl.arch == "x86_64": <NEW_LINE> <INDENT> arch = "amd64" <NEW_LINE> <DEDENT> return arch <NEW_LINE> <DEDENT> def _modify_iso(self): <NEW_LINE> <INDENT> self.log.debug("Modifying ISO") <NEW_LINE> os.mkdir(os.path.join(self.iso_contents, "cdboot")) <NEW_LINE> self._geteltorito(self.orig_iso, os.path.join(self.iso_contents, "cdboot", "boot.bin")) <NEW_LINE> outname = os.path.join(self.iso_contents, "autounattend.xml") <NEW_LINE> if self.unattendfile == oz.ozutil.generate_full_auto_path("windows-" + self.tdl.update + "-jeos.xml"): <NEW_LINE> <INDENT> doc = libxml2.parseFile(self.unattendfile) <NEW_LINE> xp = doc.xpathNewContext() <NEW_LINE> xp.xpathRegisterNs("ms", "urn:schemas-microsoft-com:unattend") <NEW_LINE> for component in xp.xpathEval('/ms:unattend/ms:settings/ms:component'): <NEW_LINE> <INDENT> component.setProp('processorArchitecture', self._get_windows_arch()) <NEW_LINE> <DEDENT> keys = xp.xpathEval('/ms:unattend/ms:settings/ms:component/ms:ProductKey') <NEW_LINE> keys[0].setContent(self.tdl.key) <NEW_LINE> adminpw = xp.xpathEval('/ms:unattend/ms:settings/ms:component/ms:UserAccounts/ms:AdministratorPassword/ms:Value') <NEW_LINE> adminpw[0].setContent(self.rootpw) <NEW_LINE> autologinpw = xp.xpathEval('/ms:unattend/ms:settings/ms:component/ms:AutoLogon/ms:Password/ms:Value') <NEW_LINE> autologinpw[0].setContent(self.rootpw) <NEW_LINE> doc.saveFile(outname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shutil.copy(self.unattendfile, outname) <NEW_LINE> <DEDENT> <DEDENT> def install(self, timeout=None, force=False): <NEW_LINE> <INDENT> internal_timeout = timeout <NEW_LINE> if internal_timeout is None: <NEW_LINE> <INDENT> internal_timeout = 6000 <NEW_LINE> <DEDENT> return self._do_install(internal_timeout, force, 2) | Class for Windows 2008 and 7 installation. | 62598f9e8e7ae83300ee8e96 |
class ScaledDotProductAttention(nn.Module): <NEW_LINE> <INDENT> def __init__(self, temperature, attn_dropout=0.1): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.temperature = temperature <NEW_LINE> self.dropout = nn.Dropout(attn_dropout) <NEW_LINE> <DEDENT> def forward(self, q, k, v, mask=None): <NEW_LINE> <INDENT> attn = torch.matmul(q / self.temperature, k.transpose(2, 3)) <NEW_LINE> if mask is not None: <NEW_LINE> <INDENT> mask = mask.repeat(1, attn.shape[1], 1, 1) <NEW_LINE> attn = attn.masked_fill(mask == True, -1e9) <NEW_LINE> <DEDENT> attn = self.dropout(F.softmax(attn, dim=-1)) <NEW_LINE> output = torch.matmul(attn, v) <NEW_LINE> return output, attn | Scaled Dot-Product Attention | 62598f9e56b00c62f0fb26a6 |
class RangeBenchmark(benchmark_base.DatasetBenchmarkBase): <NEW_LINE> <INDENT> def _benchmark_range(self, num_elements, autotune, benchmark_id): <NEW_LINE> <INDENT> options = dataset_ops.Options() <NEW_LINE> options.experimental_optimization.autotune = autotune <NEW_LINE> dataset = dataset_ops.Dataset.range(num_elements) <NEW_LINE> dataset = dataset.with_options(options) <NEW_LINE> self.run_and_report_benchmark( dataset, num_elements=num_elements, extras={ "model_name": "range.benchmark.%d" % benchmark_id, }, name="modeling_%s" % ("on" if autotune else "off")) <NEW_LINE> <DEDENT> def benchmark_range_with_modeling(self): <NEW_LINE> <INDENT> self._benchmark_range(num_elements=10000000, autotune=True, benchmark_id=1) <NEW_LINE> <DEDENT> def benchmark_range_without_modeling(self): <NEW_LINE> <INDENT> self._benchmark_range(num_elements=50000000, autotune=False, benchmark_id=2) | Benchmarks for `tf.data.Dataset.range()`. | 62598f9ee5267d203ee6b704 |
class GoogleCloudVisionV1p2beta1WebDetectionWebEntity(_messages.Message): <NEW_LINE> <INDENT> description = _messages.StringField(1) <NEW_LINE> entityId = _messages.StringField(2) <NEW_LINE> score = _messages.FloatField(3, variant=_messages.Variant.FLOAT) | Entity deduced from similar images on the Internet.
Fields:
description: Canonical description of the entity, in English.
entityId: Opaque entity ID.
score: Overall relevancy score for the entity. Not normalized and not
comparable across different image queries. | 62598f9e55399d3f05626318 |
class HALLink(AttrDict): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> AttrDict.__init__(self, *args) <NEW_LINE> if 'href' not in self: <NEW_LINE> <INDENT> raise ValueError( "Missing required href field in link: %s" % self) | Just a normal AttrDict, but one that enforces an 'href' field, so errors
get thrown at creation time rather then later when access is attempted | 62598f9e8e71fb1e983bb8ad |
class StringNode(TreeNodeObject): <NEW_LINE> <INDENT> name = Str() <NEW_LINE> label = Str() <NEW_LINE> value = Str() <NEW_LINE> def tno_allows_children(self, node): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def tno_has_children(self, node): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def tno_get_menu(self, _): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def tno_get_icon(self, node, is_expanded): <NEW_LINE> <INDENT> return "@icons:complex_node" <NEW_LINE> <DEDENT> def tno_get_label(self, node): <NEW_LINE> <INDENT> if self.label != "": <NEW_LINE> <INDENT> return self.label <NEW_LINE> <DEDENT> if self.name == "": <NEW_LINE> <INDENT> return self.format_value(self.value) <NEW_LINE> <DEDENT> return "%s: %s" % (self.name, self.format_value(self.value)) <NEW_LINE> <DEDENT> def format_value(self, value): <NEW_LINE> <INDENT> return repr(value) | A tree node for strings | 62598f9ea219f33f346c6611 |
class SeveralLagFeature(Feature): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> data = self.load("data") <NEW_LINE> data = data[["id", "sales", "d"]] <NEW_LINE> def shift_lag_feature(shift: int): <NEW_LINE> <INDENT> data[f"shift_{shift}_rolling_mean_t7"] = data.groupby(["id"])[ "sales" ].transform(lambda x: x.shift(shift).rolling(7).mean()) <NEW_LINE> data[f"shift_{shift}_rolling_mean_t28"] = data.groupby(["id"])[ "sales" ].transform(lambda x: x.shift(shift).rolling(28).mean()) <NEW_LINE> data[f"shift_{shift}_rolling_mean_t56"] = data.groupby(["id"])[ "sales" ].transform(lambda x: x.shift(shift).rolling(56).mean()) <NEW_LINE> <DEDENT> tmp_file = glob.glob("./tmp_feature_*.pkl") <NEW_LINE> if tmp_file: <NEW_LINE> <INDENT> file_name = tmp_file[0] <NEW_LINE> restart = int(file_name.split("_")[-1].split(".")[0]) + 1 <NEW_LINE> print("reload ", file_name) <NEW_LINE> data = pd.read_pickle(file_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> restart = 1 <NEW_LINE> <DEDENT> for i in range(restart, 28): <NEW_LINE> <INDENT> print("day ", i) <NEW_LINE> shift_lag_feature(i) <NEW_LINE> data.to_pickle(f"./tmp_feature_{i}.pkl") <NEW_LINE> if i != 1: <NEW_LINE> <INDENT> os.remove(f"./tmp_feature_{i - 1}.pkl") <NEW_LINE> <DEDENT> <DEDENT> data = data.drop(columns="sales") <NEW_LINE> data = self.set_index(data) <NEW_LINE> self.dump(data) | simple feature from kernel(https://www.kaggle.com/ragnar123/very-fst-model) | 62598f9e91af0d3eaad39c01 |
class WorkerPool(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'instance_names': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'worker_size_id': {'key': 'workerSizeId', 'type': 'int'}, 'compute_mode': {'key': 'computeMode', 'type': 'str'}, 'worker_size': {'key': 'workerSize', 'type': 'str'}, 'worker_count': {'key': 'workerCount', 'type': 'int'}, 'instance_names': {'key': 'instanceNames', 'type': '[str]'}, } <NEW_LINE> def __init__( self, *, worker_size_id: Optional[int] = None, compute_mode: Optional[Union[str, "ComputeModeOptions"]] = None, worker_size: Optional[str] = None, worker_count: Optional[int] = None, **kwargs ): <NEW_LINE> <INDENT> super(WorkerPool, self).__init__(**kwargs) <NEW_LINE> self.worker_size_id = worker_size_id <NEW_LINE> self.compute_mode = compute_mode <NEW_LINE> self.worker_size = worker_size <NEW_LINE> self.worker_count = worker_count <NEW_LINE> self.instance_names = None | Worker pool of an App Service Environment.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar worker_size_id: Worker size ID for referencing this worker pool.
:vartype worker_size_id: int
:ivar compute_mode: Shared or dedicated app hosting. Possible values include: "Shared",
"Dedicated", "Dynamic".
:vartype compute_mode: str or ~azure.mgmt.web.v2019_08_01.models.ComputeModeOptions
:ivar worker_size: VM size of the worker pool instances.
:vartype worker_size: str
:ivar worker_count: Number of instances in the worker pool.
:vartype worker_count: int
:ivar instance_names: Names of all instances in the worker pool (read only).
:vartype instance_names: list[str] | 62598f9e0c0af96317c56179 |
class Float(BaseScalar): <NEW_LINE> <INDENT> type = 'F' <NEW_LINE> typename = 'Float_t' <NEW_LINE> def __new__(cls, default=0., **kwargs): <NEW_LINE> <INDENT> return BaseScalar.__new__(cls, 'f', [Float.convert(default)]) <NEW_LINE> <DEDENT> def __init__(self, default=0., **kwargs): <NEW_LINE> <INDENT> BaseScalar.__init__(self, **kwargs) <NEW_LINE> self.default = Float.convert(default) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def convert(cls, value): <NEW_LINE> <INDENT> return float(value) | This is a variable containing a float | 62598f9e925a0f43d25e7e34 |
class PortMetadata(model_base.BASEV2, HasId): <NEW_LINE> <INDENT> __tablename__ = 'port_metadata' <NEW_LINE> port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete="CASCADE"), nullable=False) <NEW_LINE> data = sa.Column(sa.String(1024)) | Represents a metadata for port on a Neutron v2 network. | 62598f9e85dfad0860cbf970 |
class NodeUnitInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Id = None <NEW_LINE> self.NodeUnitName = None <NEW_LINE> self.NodeList = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Id = params.get("Id") <NEW_LINE> self.NodeUnitName = params.get("NodeUnitName") <NEW_LINE> if params.get("NodeList") is not None: <NEW_LINE> <INDENT> self.NodeList = [] <NEW_LINE> for item in params.get("NodeList"): <NEW_LINE> <INDENT> obj = NodeUnitNodeInfo() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.NodeList.append(obj) <NEW_LINE> <DEDENT> <DEDENT> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | NodeUnit信息
| 62598f9e627d3e7fe0e06ca2 |
class InstallError(JobError): <NEW_LINE> <INDENT> pass | Indicates an installation error which Terminates and fails the job. | 62598f9edd821e528d6d8d2c |
class _DictSearch(object): <NEW_LINE> <INDENT> def __init__(self, basedict): <NEW_LINE> <INDENT> self.basedict = basedict <NEW_LINE> <DEDENT> def __getattr__(self, name, PdfName=PdfName): <NEW_LINE> <INDENT> return self[PdfName(name)] <NEW_LINE> <DEDENT> def __getitem__(self, name, set=set, getattr=getattr, id=id): <NEW_LINE> <INDENT> visited = set() <NEW_LINE> mydict = self.basedict <NEW_LINE> while 1: <NEW_LINE> <INDENT> value = mydict[name] <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> myid = id(mydict) <NEW_LINE> assert myid not in visited <NEW_LINE> visited.add(myid) <NEW_LINE> mydict = mydict.Parent <NEW_LINE> if mydict is None: <NEW_LINE> <INDENT> return | Used to search for inheritable attributes.
| 62598f9e99cbb53fe6830cca |
class SPStack(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.stack = [] <NEW_LINE> <DEDENT> def push(self, lmn): <NEW_LINE> <INDENT> self.stack += [lmn] <NEW_LINE> <DEDENT> def top(self): <NEW_LINE> <INDENT> assert not self.empty(), 'stack empty' <NEW_LINE> return self.stack[-1] <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> lmn = self.top() <NEW_LINE> self.stack = self.stack[:-1] <NEW_LINE> return lmn <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return len(self.stack) <NEW_LINE> <DEDENT> def empty(self): <NEW_LINE> <INDENT> return self.stack == [] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for lmn in self.stack[::-1]: <NEW_LINE> <INDENT> yield lmn | simple LIFO | 62598f9e009cb60464d0131c |
class FeedServiceStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.GetFeed = channel.unary_unary( '/google.ads.googleads.v2.services.FeedService/GetFeed', request_serializer=google_dot_ads_dot_googleads__v2_dot_proto_dot_services_dot_feed__service__pb2.GetFeedRequest.SerializeToString, response_deserializer=google_dot_ads_dot_googleads__v2_dot_proto_dot_resources_dot_feed__pb2.Feed.FromString, ) <NEW_LINE> self.MutateFeeds = channel.unary_unary( '/google.ads.googleads.v2.services.FeedService/MutateFeeds', request_serializer=google_dot_ads_dot_googleads__v2_dot_proto_dot_services_dot_feed__service__pb2.MutateFeedsRequest.SerializeToString, response_deserializer=google_dot_ads_dot_googleads__v2_dot_proto_dot_services_dot_feed__service__pb2.MutateFeedsResponse.FromString, ) | Proto file describing the Feed service.
Service to manage feeds. | 62598f9e8da39b475be02fd7 |
class DataTriageCSV(object): <NEW_LINE> <INDENT> def __init__(self, data_path, n_tests=1): <NEW_LINE> <INDENT> self.data_path = data_path <NEW_LINE> self.n_tests = n_tests <NEW_LINE> self.X, self.y = self._load_dataset_from_path() <NEW_LINE> self.n = len(self.y) <NEW_LINE> self.y_true, self.y_experimental = self._format_target_values(self.y, self.n) <NEW_LINE> self.status = np.zeros((self.n, 1)) <NEW_LINE> self.top_100 = np.argsort(self.y[-1])[-100:] <NEW_LINE> <DEDENT> def _format_target_values(self, y, n): <NEW_LINE> <INDENT> y_true = y <NEW_LINE> y_experimental = np.full((n, self.n_tests), np.nan) <NEW_LINE> return y_true, y_experimental <NEW_LINE> <DEDENT> def _load_dataset_from_path(self): <NEW_LINE> <INDENT> data_set = np.loadtxt(self.data_path, delimiter=",", skiprows=1, dtype='float') <NEW_LINE> if data_set.size <= 0: <NEW_LINE> <INDENT> warnings.warn('Loaded data set was empty') <NEW_LINE> <DEDENT> features, targets = data_set[:, :-self.n_tests], data_set[:, -self.n_tests:] <NEW_LINE> return features, targets | This Parent takes a dataset which is to be assessed by the AMI and then performs the necessary pre-processing
steps on the data set including: loading the data into numpy arrays, formatting the target values into the correct
representation and other values.
Children of this class allow for multiple types of files to be loaded and used depending on user requirements | 62598f9ee76e3b2f99fd882f |
class ObserverInterface(): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> @abc.abstractmethod <NEW_LINE> def update(self, disaster_signal): <NEW_LINE> <INDENT> pass | Interfaces for displays | 62598f9ee5267d203ee6b705 |
class MetsHdr(MetsBase): <NEW_LINE> <INDENT> tag = "metsHdr" <NEW_LINE> contained_children = ["agent", "altRecordID", "metsDocumentID"] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.atts = { "RECORDSTATUS": None, "CREATEDATE": None, "LASTMODDATE": None, "ID": None} <NEW_LINE> super(MetsHdr, self).__init__(**kwargs) | Wrapper for metsHdr element. | 62598f9e2ae34c7f260aaed8 |
class LogOp(Op): <NEW_LINE> <INDENT> def __call__(self, node_A): <NEW_LINE> <INDENT> new_node = Op.__call__(self) <NEW_LINE> new_node.inputs = [node_A] <NEW_LINE> new_node.name = "Log(%s)" % (node_A.name) <NEW_LINE> return new_node <NEW_LINE> <DEDENT> def compute(self, node, input_vals): <NEW_LINE> <INDENT> assert(isinstance(input_vals[0], np.ndarray)) <NEW_LINE> return np.log(input_vals[0]) <NEW_LINE> <DEDENT> def gradient(self, node, output_grad): <NEW_LINE> <INDENT> a = node.inputs[0] <NEW_LINE> return [power_byconst_op(a, -1)*output_grad] | Op that calculate cross entropy. | 62598f9e5f7d997b871f92db |
class str(measure): <NEW_LINE> <INDENT> @property <NEW_LINE> def decl(self): <NEW_LINE> <INDENT> size = self.maxlen <NEW_LINE> return 'TEXT' if size is None else 'VARCHAR({})'.format(size) <NEW_LINE> <DEDENT> def sql(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return "'None'" <NEW_LINE> <DEDENT> return "'{}'".format(value.replace("'", "''")) <NEW_LINE> <DEDENT> def __init__(self, maxlen=None, **kwds): <NEW_LINE> <INDENT> super().__init__(**kwds) <NEW_LINE> self.maxlen = maxlen <NEW_LINE> return | Mixin for strings | 62598f9edd821e528d6d8d2d |
class ReceiptInfo(object): <NEW_LINE> <INDENT> def __init__(self, transaction_number, total, subtotal, tax_edible, tax_non_edible, tax_rate_edible, tax_rate_nonedible, transaction_type): <NEW_LINE> <INDENT> self.transaction_number = transaction_number <NEW_LINE> self.total = total <NEW_LINE> self.subtotal = subtotal <NEW_LINE> self.tax_edible = tax_edible <NEW_LINE> self.tax_non_edible = tax_non_edible <NEW_LINE> self.tax_rate_edible = tax_rate_edible <NEW_LINE> self.tax_rate_non_edible = tax_rate_nonedible <NEW_LINE> self.transaction_type = transaction_type | A struct with all the necessary info for the receipt | 62598f9ee64d504609df92b4 |
class BackgroundRunner: <NEW_LINE> <INDENT> def __init__(self, max_workers=None): <NEW_LINE> <INDENT> if max_workers is None: <NEW_LINE> <INDENT> max_workers = multiprocessing.cpu_count() - 1 <NEW_LINE> <DEDENT> if max_workers == 1: <NEW_LINE> <INDENT> self.executor = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.executor = futures.ProcessPoolExecutor(max_workers) <NEW_LINE> <DEDENT> self.futures = [] <NEW_LINE> <DEDENT> def submit(self, fn, *args, **kwargs): <NEW_LINE> <INDENT> if self.executor: <NEW_LINE> <INDENT> self.futures.append(self.executor.submit(fn, *args, **kwargs)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fn(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def wait(self): <NEW_LINE> <INDENT> if not self.executor: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> futures.wait(self.futures, return_when=futures.FIRST_EXCEPTION) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> for future in self.futures: <NEW_LINE> <INDENT> future.cancel() <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> for future in self.futures: <NEW_LINE> <INDENT> future.cancel() <NEW_LINE> <DEDENT> results = [] <NEW_LINE> error_indices = [] <NEW_LINE> cancelled_indices = [] <NEW_LINE> for i, future in enumerate(self.futures): <NEW_LINE> <INDENT> if future.cancelled(): <NEW_LINE> <INDENT> results.append(futures.CancelledError()) <NEW_LINE> cancelled_indices.append(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exc = future.exception() <NEW_LINE> if exc is not None: <NEW_LINE> <INDENT> results.append(exc) <NEW_LINE> error_indices.append(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results.append(future.result()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.futures = [] <NEW_LINE> was_error = len(error_indices) > 0 or len(cancelled_indices) > 0 <NEW_LINE> return results, was_error, error_indices, cancelled_indices | Class for running jobs in background processes.Use submit() to add jobs,
and then wait() to get the results for each submitted job:
either the return value on successful completion, or an exception object.
Wait() will only wait until the first exception, and after that will
attempt to cancel all pending jobs.
If max_workers is 1, then just run the job in this process. Useful
for debugging, where a proper traceback from a foreground exception
can be helpful. | 62598f9e097d151d1a2c0e20 |
class ShowIpv6MldSsmMapSchema(MetaParser): <NEW_LINE> <INDENT> schema = {'vrf': {Any(): { 'ssm_map': { Any(): { 'source_addr': str, 'group_address': str, 'database': str, 'group_mode_ssm': bool } } }, } } | Schema for:
show ipv6 mld ssm-map <group_address>
show ipv6 mld vrf <vrf> ssm-map <group_address> | 62598f9ed268445f26639a7f |
class CustomShMock(object): <NEW_LINE> <INDENT> def fail_on_pep8(self, arg): <NEW_LINE> <INDENT> if "pep8" in arg: <NEW_LINE> <INDENT> paver.easy.sh("exit 1") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> def fail_on_pylint(self, arg): <NEW_LINE> <INDENT> if "pylint" in arg: <NEW_LINE> <INDENT> paver.easy.sh("exit 1") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return | Diff-quality makes a number of sh calls. None of those calls should be made during tests; however, some
of them need to have certain responses. | 62598f9e63d6d428bbee25aa |
class InvalidObserver(object): <NEW_LINE> <INDENT> def __init__(self, active): <NEW_LINE> <INDENT> self.active = active <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return self.active <NEW_LINE> <DEDENT> __nonzero__ = __bool__ <NEW_LINE> def __call__(self, change): <NEW_LINE> <INDENT> pass | Silly callable which always evaluate to false. | 62598f9e21bff66bcd722a5c |
class TransitionFactory(DjangoModelFactory): <NEW_LINE> <INDENT> FACTORY_FOR = Transition <NEW_LINE> name = 'change-hostname' <NEW_LINE> slug = 'change-hostname' <NEW_LINE> to_status = AssetStatus.in_progress <NEW_LINE> required_report = False | Actions in transition must by added manually in tests | 62598f9e7d847024c075c1c8 |
class Package(object): <NEW_LINE> <INDENT> LIST_SCHEMA = '' <NEW_LINE> HISTORY_SCHEMA = '' <NEW_LINE> def __init__(self, project, name): <NEW_LINE> <INDENT> super(Package, self).__init__() <NEW_LINE> self.project = project <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def get(self, name): <NEW_LINE> <INDENT> return getattr(self, name) <NEW_LINE> <DEDENT> def list(self, **kwargs): <NEW_LINE> <INDENT> request = Osc.get_osc().get_reqobj() <NEW_LINE> path = "/source/%s/%s" % (self.project, self.name) <NEW_LINE> if 'schema' not in kwargs: <NEW_LINE> <INDENT> kwargs['schema'] = Package.LIST_SCHEMA <NEW_LINE> <DEDENT> f = request.get(path, **kwargs) <NEW_LINE> directory = fromstring(f.read(), directory=Directory, entry=File, linkinfo=Linkinfo) <NEW_LINE> directory.set('project', self.project) <NEW_LINE> return directory <NEW_LINE> <DEDENT> def log(self, **kwargs): <NEW_LINE> <INDENT> request = Osc.get_osc().get_reqobj() <NEW_LINE> path = "/source/%s/%s/_history" % (self.project, self.name) <NEW_LINE> if 'schema' not in kwargs: <NEW_LINE> <INDENT> kwargs['schema'] = Package.HISTORY_SCHEMA <NEW_LINE> <DEDENT> f = request.get(path, **kwargs) <NEW_LINE> return fromstring(f.read()) | Class used to access /source/project/package data | 62598f9e6fb2d068a7693d30 |
class FilterByServer(HierarchicalBucketFilter): <NEW_LINE> <INDENT> sweepInterval = None <NEW_LINE> def getBucketKey(self, transport): <NEW_LINE> <INDENT> return transport.getHost()[2] | A bucket filter with a bucket for each service.
| 62598f9e56b00c62f0fb26a8 |
class QuotaEngine(object): <NEW_LINE> <INDENT> def __init__(self, quota_driver_class=None): <NEW_LINE> <INDENT> self._resources = {} <NEW_LINE> if not quota_driver_class: <NEW_LINE> <INDENT> quota_driver_class = CONF.quota_driver <NEW_LINE> <DEDENT> if isinstance(quota_driver_class, basestring): <NEW_LINE> <INDENT> quota_driver_class = importutils.import_object(quota_driver_class, self._resources) <NEW_LINE> <DEDENT> self._driver = quota_driver_class <NEW_LINE> <DEDENT> def __contains__(self, resource): <NEW_LINE> <INDENT> return resource in self._resources <NEW_LINE> <DEDENT> def register_resource(self, resource): <NEW_LINE> <INDENT> self._resources[resource.name] = resource <NEW_LINE> <DEDENT> def register_resources(self, resources): <NEW_LINE> <INDENT> for resource in resources: <NEW_LINE> <INDENT> self.register_resource(resource) <NEW_LINE> <DEDENT> <DEDENT> def get_quota_by_tenant(self, tenant_id, resource): <NEW_LINE> <INDENT> return self._driver.get_quota_by_tenant(tenant_id, resource) <NEW_LINE> <DEDENT> def get_quota_usage(self, quota): <NEW_LINE> <INDENT> return self._driver.get_quota_usage_by_tenant(quota.tenant_id, quota.resource) <NEW_LINE> <DEDENT> def get_defaults(self): <NEW_LINE> <INDENT> return self._driver.get_defaults(self._resources) <NEW_LINE> <DEDENT> def get_all_quotas_by_tenant(self, tenant_id): <NEW_LINE> <INDENT> return self._driver.get_all_quotas_by_tenant(tenant_id, self._resources) <NEW_LINE> <DEDENT> def check_quotas(self, tenant_id, **deltas): <NEW_LINE> <INDENT> self._driver.check_quotas(tenant_id, self._resources, deltas) <NEW_LINE> <DEDENT> def reserve(self, tenant_id, **deltas): <NEW_LINE> <INDENT> reservations = self._driver.reserve(tenant_id, self._resources, deltas) <NEW_LINE> LOG.debug("Created reservations %(reservations)s" % {'reservations': reservations}) <NEW_LINE> return reservations <NEW_LINE> <DEDENT> def commit(self, reservations): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._driver.commit(reservations) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception(_("Failed to commit reservations " "%(reservations)s") % {'reservations': reservations}) <NEW_LINE> <DEDENT> <DEDENT> def rollback(self, reservations): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._driver.rollback(reservations) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception(_("Failed to roll back reservations " "%(reservations)s") % {'reservations': reservations}) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def resources(self): <NEW_LINE> <INDENT> return sorted(self._resources.keys()) | Represent the set of recognized quotas. | 62598f9e99cbb53fe6830ccb |
class SubmapList(metaclass=Metaclass): <NEW_LINE> <INDENT> __slots__ = [ '_header', '_trajectory', ] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> assert all(['_' + key in self.__slots__ for key in kwargs.keys()]), 'Invalid arguments passed to constructor: %r' % kwargs.keys() <NEW_LINE> from std_msgs.msg import Header <NEW_LINE> self.header = kwargs.get('header', Header()) <NEW_LINE> self.trajectory = kwargs.get('trajectory', list()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> typename = self.__class__.__module__.split('.') <NEW_LINE> typename.pop() <NEW_LINE> typename.append(self.__class__.__name__) <NEW_LINE> args = [s[1:] + '=' + repr(getattr(self, s, None)) for s in self.__slots__] <NEW_LINE> return '%s(%s)' % ('.'.join(typename), ', '.join(args)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def header(self): <NEW_LINE> <INDENT> return self._header <NEW_LINE> <DEDENT> @header.setter <NEW_LINE> def header(self, value): <NEW_LINE> <INDENT> from std_msgs.msg import Header <NEW_LINE> assert isinstance(value, Header), "The 'header' field must be a sub message of type 'Header'" <NEW_LINE> self._header = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def trajectory(self): <NEW_LINE> <INDENT> return self._trajectory <NEW_LINE> <DEDENT> @trajectory.setter <NEW_LINE> def trajectory(self, value): <NEW_LINE> <INDENT> from cartographer_ros_msgs.msg import TrajectorySubmapList <NEW_LINE> from collections import Sequence <NEW_LINE> from collections import Set <NEW_LINE> from collections import UserList <NEW_LINE> from collections import UserString <NEW_LINE> assert ((isinstance(value, Sequence) or isinstance(value, Set) or isinstance(value, UserList)) and not isinstance(value, str) and not isinstance(value, UserString) and all([isinstance(v, TrajectorySubmapList) for v in value]) and True), "The 'trajectory' field must be a set or sequence and each value of type 'TrajectorySubmapList'" <NEW_LINE> self._trajectory = value | Message class 'SubmapList'. | 62598f9e30bbd72246469873 |
class DiceBaseBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, channels, in_size): <NEW_LINE> <INDENT> super(DiceBaseBlock, self).__init__() <NEW_LINE> mid_channels = 3 * channels <NEW_LINE> self.convs = Concurrent() <NEW_LINE> self.convs.add_module("ch_conv", conv3x3( in_channels=channels, out_channels=channels, groups=channels)) <NEW_LINE> self.convs.add_module("h_conv", SpatialDiceBranch( sp_size=in_size[0], is_height=True)) <NEW_LINE> self.convs.add_module("w_conv", SpatialDiceBranch( sp_size=in_size[1], is_height=False)) <NEW_LINE> self.norm_activ = NormActivation( in_channels=mid_channels, activation=(lambda: nn.PReLU(num_parameters=mid_channels))) <NEW_LINE> self.shuffle = ChannelShuffle( channels=mid_channels, groups=3) <NEW_LINE> self.squeeze_conv = conv1x1_block( in_channels=mid_channels, out_channels=channels, groups=channels, activation=(lambda: nn.PReLU(num_parameters=channels))) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.convs(x) <NEW_LINE> x = self.norm_activ(x) <NEW_LINE> x = self.shuffle(x) <NEW_LINE> x = self.squeeze_conv(x) <NEW_LINE> return x | Base part of DiCE block (without attention).
Parameters:
----------
channels : int
Number of input/output channels.
in_size : tuple of two ints
Spatial size of the expected input image. | 62598f9e3539df3088ecc0ae |
class Prefs(object): <NEW_LINE> <INDENT> _prefs = {} <NEW_LINE> filename = None <NEW_LINE> autosave = False <NEW_LINE> __borg_state = {} <NEW_LINE> def __init__(self, filename=None): <NEW_LINE> <INDENT> self.__dict__ = self.__borg_state <NEW_LINE> if filename is not None: <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if key in self._prefs: <NEW_LINE> <INDENT> return self._prefs[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self._prefs[key] = value <NEW_LINE> if self.autosave: <NEW_LINE> <INDENT> self.save() <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> if key in self._prefs: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del self._prefs[key] <NEW_LINE> if self.autosave: <NEW_LINE> <INDENT> self.save() <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self._prefs.__iter__() <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self._prefs.keys() <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return self._prefs.items() <NEW_LINE> <DEDENT> def iteritems(self): <NEW_LINE> <INDENT> return six.iteritems(self._prefs) <NEW_LINE> <DEDENT> def save(self, filename=None): <NEW_LINE> <INDENT> if filename is None: <NEW_LINE> <INDENT> filename = self.filename <NEW_LINE> <DEDENT> if filename is not None: <NEW_LINE> <INDENT> fsock = open(filename, 'wb') <NEW_LINE> try: <NEW_LINE> <INDENT> six.moves.cPickle.dump(self._prefs, fsock, 2) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> fsock.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def load(self, filename=None): <NEW_LINE> <INDENT> if filename is None: <NEW_LINE> <INDENT> filename = self.filename <NEW_LINE> <DEDENT> if filename is not None: <NEW_LINE> <INDENT> fsock = open(filename, 'rb') <NEW_LINE> try: <NEW_LINE> <INDENT> self._prefs = six.moves.cPickle.load(fsock) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> fsock.close() | This is a preferences backend object used to:
- Hold the ConfigShell preferences
- Handle persistent storage and retrieval of these preferences
- Share the preferences between the ConfigShell and ConfigNode objects
As it is inherently destined to be shared between objects, this is a Borg. | 62598f9e4a966d76dd5eecda |
class HandleSegFault(GenericCommand): <NEW_LINE> <INDENT> _cmdline_ = "handlesegfault" <NEW_LINE> _syntax_ = "{:s}".format(_cmdline_) <NEW_LINE> @only_if_gdb_running <NEW_LINE> def do_invoke(self, argv): <NEW_LINE> <INDENT> print("segfault pc = {:#x}".format(current_arch.pc)) <NEW_LINE> address = int(gdb.parse_and_eval( '$_siginfo._sifields._sigfault.si_addr')) <NEW_LINE> pc = int(gdb.parse_and_eval('$pc')) <NEW_LINE> print(gdb.parse_and_eval('$_siginfo._sifields._sigfault')) <NEW_LINE> page = (address >> 12) << 12 <NEW_LINE> assert page in __pages__, "Seg Fault on page we never touched: " + hex(page) <NEW_LINE> section = process_lookup_address(address) <NEW_LINE> if not section.is_executable(): <NEW_LINE> <INDENT> assert pc <= address and pc + 15 >= address, "Execution did not occur at PC" <NEW_LINE> rw_to_exec_tracked(page) <NEW_LINE> pc_page = (pc >> 12) << 12 <NEW_LINE> if pc_page != page: <NEW_LINE> <INDENT> assert __pages__[pc_page][0] in ("exec_tracked"), "Instruction that began in an untracked page caused the following page to " + "become tracked causing the later part of the instruction to be overwritten" <NEW_LINE> write_memory(pc, b'\xCC', 1) <NEW_LINE> <DEDENT> <DEDENT> elif section.is_executable(): <NEW_LINE> <INDENT> exec_tracked_to_rw(page) <NEW_LINE> <DEDENT> return | Dummy new command. | 62598f9e07f4c71912baf244 |
class MazeReader: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read_from_file(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename) as input_file: <NEW_LINE> <INDENT> content = input_file.readlines() <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print("Could not open input file: {}".format(e.args)) <NEW_LINE> exit(-1) <NEW_LINE> <DEDENT> maze_board = [] <NEW_LINE> for line_content in content[1:]: <NEW_LINE> <INDENT> line_content = line_content.rstrip('\n') <NEW_LINE> maze_line = [] <NEW_LINE> for block in line_content: <NEW_LINE> <INDENT> maze_line.append(block) <NEW_LINE> <DEDENT> maze_board.append(maze_line) <NEW_LINE> <DEDENT> return maze_board | A class to read mazes from input files into a format the MazeGraph class can parse.
| 62598f9e32920d7e50bc5e4f |
class UpdateAttachment(CreateAttachment, UpdateView): <NEW_LINE> <INDENT> permission_required = 'change_attachment' | Use to edit attachments. | 62598f9e442bda511e95c254 |
class ISRES(Optimizer): <NEW_LINE> <INDENT> ISRES_CONFIGURATION = { 'name': 'ISRES', 'description': 'GN_ISRES Optimizer', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'isres_schema', 'type': 'object', 'properties': { 'max_evals': { 'type': 'integer', 'default': 1000 } }, 'additionalProperties': False }, 'support_level': { 'gradient': Optimizer.SupportLevel.ignored, 'bounds': Optimizer.SupportLevel.supported, 'initial_point': Optimizer.SupportLevel.required }, 'options': ['max_evals'], 'optimizer': ['global'] } <NEW_LINE> def __init__(self, configuration=None): <NEW_LINE> <INDENT> super().__init__(configuration or self.ISRES_CONFIGURATION.copy()) <NEW_LINE> <DEDENT> def init_args(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def optimize(self, num_vars, objective_function, gradient_function=None, variable_bounds=None, initial_point=None): <NEW_LINE> <INDENT> super().optimize(num_vars, objective_function, gradient_function, variable_bounds, initial_point) <NEW_LINE> return minimize(nlopt.GN_ISRES, objective_function, variable_bounds, initial_point, **self._options) | ISRES (Improved Stochastic Ranking Evolution Strategy)
NLopt global optimizer, derivative-free
http://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/#isres-improved-stochastic-ranking-evolution-strategy | 62598f9e3d592f4c4edbacc7 |
class ServerMsgResultDataFixtureEx(ServerMsgResultData): <NEW_LINE> <INDENT> protocol = ServerMsgProtocol.FixtureEx <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._msg = "" <NEW_LINE> self._values = DataFixtureDataValues() <NEW_LINE> self._url = "" <NEW_LINE> <DEDENT> def append(self, data: DataFixtureData): <NEW_LINE> <INDENT> self._values.append(item=data) <NEW_LINE> <DEDENT> def export(self): <NEW_LINE> <INDENT> res_ = super().export() <NEW_LINE> res_["values"] = self._values.export() <NEW_LINE> return res_ | 封装可扩展赛程协议。
ServerMsgResultDataFixtureEx类需要调用下面几个method进行设置
ins.msg = str()
ins.url = "" # 此处url需要根据league_id进行拼接
ins.append(DataFixtureData())
例:
{
"msg": "测试比赛",
"url": "",
"values": [{
"items": [{
"away_name": "",
"away_team_id": 0,
"bg": "",
"fav": 0,
"gms_league_id": 8,
"home_name": "AA",
"home_team_id": 0,
"league_name": "英超",
"match_time": "",
"operation": 0,
"status": 1
}],
"league_name": "英超"
}]
} | 62598f9e236d856c2adc9336 |
class CaseSelectionResource(BaseSelectionResource): <NEW_LINE> <INDENT> case = fields.ForeignKey(CaseResource, "case") <NEW_LINE> productversion = fields.ForeignKey( ProductVersionResource, "productversion") <NEW_LINE> tags = fields.ToManyField(TagResource, "tags", full=True) <NEW_LINE> created_by = fields.ForeignKey( UserResource, "created_by", full=True, null=True, ) <NEW_LINE> modified_by= fields.ForeignKey( UserResource, "modified_by", full=True, null=True, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> queryset = CaseVersion.objects.filter(latest=True).select_related( "case", "productversion", "created_by", ).prefetch_related( "tags", "tags__product", ) <NEW_LINE> list_allowed_methods = ['get'] <NEW_LINE> fields = ["id", "name", "created_by", "modified_on"] <NEW_LINE> filtering = { "productversion": ALL_WITH_RELATIONS, "tags": ALL_WITH_RELATIONS, "case": ALL_WITH_RELATIONS, "created_by": ALL_WITH_RELATIONS, "modified_by": ALL_WITH_RELATIONS, "name": ALL } <NEW_LINE> ordering = ["id", "case", "modified_on", "name"] <NEW_LINE> <DEDENT> def dehydrate(self, bundle): <NEW_LINE> <INDENT> case = bundle.obj.case <NEW_LINE> bundle.data["case_id"] = unicode(case.id) <NEW_LINE> bundle.data["product_id"] = unicode(case.product_id) <NEW_LINE> bundle.data["product"] = {"id": unicode(case.product_id)} <NEW_LINE> bundle.data["priority"] = unicode(case.priority) <NEW_LINE> return bundle | Specialty end-point for an AJAX call in the Suite form multi-select widget
for selecting cases. | 62598f9ebe8e80087fbbee58 |
class StateConfig(configparser.ConfigParser): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._filename = os.path.join(standarddir.data(), 'state') <NEW_LINE> self.read(self._filename, encoding='utf-8') <NEW_LINE> qt_version = qVersion() <NEW_LINE> if 'general' in self: <NEW_LINE> <INDENT> old_qt_version = self['general'].get('qt_version', None) <NEW_LINE> self.qt_version_changed = old_qt_version != qt_version <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.qt_version_changed = False <NEW_LINE> <DEDENT> for sect in ['general', 'geometry', 'inspector']: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.add_section(sect) <NEW_LINE> <DEDENT> except configparser.DuplicateSectionError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> deleted_keys = [ ('general', 'fooled'), ('general', 'backend-warning-shown'), ('general', 'old-qt-warning-shown'), ('geometry', 'inspector'), ] <NEW_LINE> for sect, key in deleted_keys: <NEW_LINE> <INDENT> self[sect].pop(key, None) <NEW_LINE> <DEDENT> self['general']['qt_version'] = qt_version <NEW_LINE> self['general']['version'] = qutebrowser.__version__ <NEW_LINE> <DEDENT> def init_save_manager(self, save_manager: 'savemanager.SaveManager') -> None: <NEW_LINE> <INDENT> save_manager.add_saveable('state-config', self._save) <NEW_LINE> <DEDENT> def _save(self) -> None: <NEW_LINE> <INDENT> with open(self._filename, 'w', encoding='utf-8') as f: <NEW_LINE> <INDENT> self.write(f) | The "state" file saving various application state. | 62598f9edd821e528d6d8d2e |
class TestMediaWikiCommand(unittest.TestCase): <NEW_LINE> <INDENT> def test_backend_class(self): <NEW_LINE> <INDENT> self.assertIs(MediaWikiCommand.BACKEND, MediaWiki) <NEW_LINE> <DEDENT> def test_setup_cmd_parser(self): <NEW_LINE> <INDENT> parser = MediaWikiCommand.setup_cmd_parser() <NEW_LINE> self.assertIsInstance(parser, BackendCommandArgumentParser) <NEW_LINE> args = ['--tag', 'test', '--no-archive', '--from-date', '1970-01-01', MEDIAWIKI_SERVER_URL] <NEW_LINE> parsed_args = parser.parse(*args) <NEW_LINE> self.assertEqual(parsed_args.url, MEDIAWIKI_SERVER_URL) <NEW_LINE> self.assertEqual(parsed_args.tag, 'test') <NEW_LINE> self.assertEqual(parsed_args.no_archive, True) <NEW_LINE> self.assertEqual(parsed_args.from_date, DEFAULT_DATETIME) | Tests for MediaWikiCommand class | 62598f9e009cb60464d0131f |
class svn_location_segment_receiver_t: <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, svn_location_segment_receiver_t, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, svn_location_segment_receiver_t, name) <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def set_parent_pool(self, parent_pool=None): <NEW_LINE> <INDENT> import libsvn.core, weakref <NEW_LINE> self.__dict__["_parent_pool"] = parent_pool or libsvn.core.application_pool; <NEW_LINE> if self.__dict__["_parent_pool"]: <NEW_LINE> <INDENT> self.__dict__["_is_valid"] = weakref.ref( self.__dict__["_parent_pool"]._is_valid) <NEW_LINE> <DEDENT> <DEDENT> def assert_valid(self): <NEW_LINE> <INDENT> if "_is_valid" in self.__dict__: <NEW_LINE> <INDENT> assert self.__dict__["_is_valid"](), "Variable has already been deleted" <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> self.assert_valid() <NEW_LINE> value = _swig_getattr(self, self.__class__, name) <NEW_LINE> members = self.__dict__.get("_members") <NEW_LINE> if members is not None: <NEW_LINE> <INDENT> _copy_metadata_deep(value, members.get(name)) <NEW_LINE> <DEDENT> _assert_valid_deep(value) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> self.assert_valid() <NEW_LINE> self.__dict__.setdefault("_members",{})[name] = value <NEW_LINE> return _swig_setattr(self, self.__class__, name, value) <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> return svn_location_invoke_segment_receiver(self, *args) | Proxy of C svn_location_segment_receiver_t struct | 62598f9e5f7d997b871f92dc |
class CDiscountDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, root, txt_file, num_classes, transform=None, loader=default_loader): <NEW_LINE> <INDENT> self.root = root <NEW_LINE> self.imgs=[] <NEW_LINE> with open(txt_file,'r') as f: <NEW_LINE> <INDENT> for line in f.readlines(): <NEW_LINE> <INDENT> line=line.strip() <NEW_LINE> im_name = line.split(' ')[0] <NEW_LINE> target = int(line.split(' ')[1]) <NEW_LINE> self.imgs.append((im_name,target)) <NEW_LINE> <DEDENT> <DEDENT> self.classes = range(num_classes) <NEW_LINE> self.transform = transform <NEW_LINE> self.loader = loader <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> fname, target = self.imgs[index] <NEW_LINE> path=self.root+'/' +fname <NEW_LINE> img = self.loader(path) <NEW_LINE> if self.transform is not None: <NEW_LINE> <INDENT> img = self.transform(img) <NEW_LINE> <DEDENT> return img, target <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.imgs) | Face Landmarks dataset. | 62598f9e097d151d1a2c0e22 |
class AuditEventSource(fhirelement.FHIRElement): <NEW_LINE> <INDENT> resource_name = "AuditEventSource" <NEW_LINE> def __init__(self, jsondict=None): <NEW_LINE> <INDENT> self.identifier = None <NEW_LINE> self.site = None <NEW_LINE> self.type = None <NEW_LINE> super(AuditEventSource, self).__init__(jsondict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(AuditEventSource, self).elementProperties() <NEW_LINE> js.extend([ ("identifier", "identifier", str, False), ("site", "site", str, False), ("type", "type", coding.Coding, True), ]) <NEW_LINE> return js | Application systems and processes.
| 62598f9e0c0af96317c5617c |
class PresetButton(QPushButton): <NEW_LINE> <INDENT> def __init__(self, radius, fraction): <NEW_LINE> <INDENT> super(PresetButton, self).__init__() <NEW_LINE> self.fraction = 0 <NEW_LINE> self.angle = 0 <NEW_LINE> self.set_fraction(fraction) <NEW_LINE> stroke_w = apply_dpi_scaling(2) <NEW_LINE> self.padding_y = apply_dpi_scaling(3) <NEW_LINE> self.padding_x = apply_dpi_scaling(3) <NEW_LINE> self.pie_rect_size = radius + stroke_w <NEW_LINE> self.rect = QRect(self.padding_x, self.padding_y + stroke_w, self.pie_rect_size, self.pie_rect_size) <NEW_LINE> self.setFixedHeight(radius + 3 * stroke_w + self.padding_y * 2) <NEW_LINE> self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) <NEW_LINE> self.stroke_color = QColor(0, 0, 0) <NEW_LINE> self.stroke_color.setNamedColor('#3A3A3A') <NEW_LINE> self.base_color = QColor(0, 0, 0) <NEW_LINE> self.base_color.setNamedColor('#BDBDBD') <NEW_LINE> self.accent_color = QColor(0, 0, 0) <NEW_LINE> self.accent_color.setNamedColor('#DF6E41') <NEW_LINE> self.dark_color = QColor(0, 0, 0) <NEW_LINE> self.dark_color.setNamedColor('#3A3A3A') <NEW_LINE> <DEDENT> def paintEvent(self, event): <NEW_LINE> <INDENT> super(PresetButton, self).paintEvent(event) <NEW_LINE> painter = QPainter(self) <NEW_LINE> painter.begin(self) <NEW_LINE> painter.setRenderHint(QPainter.Antialiasing) <NEW_LINE> x = (self.geometry().width() - ( self.padding_x * 2 + self.pie_rect_size)) / 2 <NEW_LINE> painter.translate(x, 0) <NEW_LINE> painter.setPen(Qt.NoPen) <NEW_LINE> painter.setBrush(self.dark_color) <NEW_LINE> painter.drawPie(self.rect, (self.angle - 90.0) * -16, (360 - self.angle) * -16) <NEW_LINE> if 0 < abs(self.angle) < 360: <NEW_LINE> <INDENT> painter.setPen(QPen(self.stroke_color, apply_dpi_scaling(1))) <NEW_LINE> <DEDENT> painter.setBrush(self.accent_color) <NEW_LINE> painter.drawPie(self.rect, 90.0 * 16, self.angle * -16) <NEW_LINE> painter.setPen(QPen(self.stroke_color, apply_dpi_scaling(1))) <NEW_LINE> painter.setBrush(Qt.NoBrush) <NEW_LINE> painter.drawEllipse(self.rect) <NEW_LINE> painter.end() <NEW_LINE> <DEDENT> def set_fraction(self, fraction, tooltip=""): <NEW_LINE> <INDENT> self.fraction = fraction <NEW_LINE> self.angle = fraction * 360 <NEW_LINE> self.setToolTip(tooltip) <NEW_LINE> self.update() | Subclass for creating and drawing the fraction buttons | 62598f9e7d847024c075c1ca |
class NOILoginForm(LoginForm): <NEW_LINE> <INDENT> email = StringField(lazy_gettext('Email')) <NEW_LINE> password = PasswordField(lazy_gettext('Password')) <NEW_LINE> remember = BooleanField(lazy_gettext('Remember Me')) <NEW_LINE> submit = SubmitField(lazy_gettext('Log in')) | Localizeable version of Flask-Security's LoginForm | 62598f9e379a373c97d98e0f |
class SetIndex(PdPipelineStage): <NEW_LINE> <INDENT> _DEF_SETIDX_EXC_MSG = "SetIndex stage failed." <NEW_LINE> _DEF_SETIDX_APP_MSG = "Setting indexes..." <NEW_LINE> _SETINDEX_KWARGS = ['drop', 'append', 'verify_integrity'] <NEW_LINE> def __init__(self, keys, **kwargs): <NEW_LINE> <INDENT> common = set(kwargs.keys()).intersection(SetIndex._SETINDEX_KWARGS) <NEW_LINE> self.setindex_kwargs = {key: kwargs.pop(key) for key in common} <NEW_LINE> self.keys = keys <NEW_LINE> if hasattr(keys, '__iter__') and not isinstance(keys, str): <NEW_LINE> <INDENT> _tprec = cond.HasAllColumns(list(keys)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _tprec = cond.HasAllColumns([keys]) <NEW_LINE> <DEDENT> self._tprec = _tprec <NEW_LINE> super_kwargs = { 'exmsg': SetIndex._DEF_SETIDX_EXC_MSG, 'desc': "Set indexes." } <NEW_LINE> super_kwargs.update(**kwargs) <NEW_LINE> super().__init__(**super_kwargs) <NEW_LINE> <DEDENT> def _prec(self, df): <NEW_LINE> <INDENT> return self._tprec(df) <NEW_LINE> <DEDENT> def _transform(self, df, verbose): <NEW_LINE> <INDENT> return df.set_index(keys=self.keys, **self.setindex_kwargs) | A pipeline stage that set existing columns as index.
Supports all parameter supported by pandas.set_index function except for
`inplace`.
Example
-------
>> import pandas as pd; import pdpipe as pdp;
>> df = pd.DataFrame([[1,4],[3, 11]], [1,2], ['a','b'])
>> pdp.SetIndex('a').apply(df)
b
a
1 4
3 11 | 62598f9e8e71fb1e983bb8b0 |
class SSLAdapter(HTTPAdapter): <NEW_LINE> <INDENT> __attrs__ = HTTPAdapter.__attrs__ + ['ssl_version'] <NEW_LINE> def __init__(self, ssl_version=None, **kwargs): <NEW_LINE> <INDENT> self.ssl_version = ssl_version <NEW_LINE> super(SSLAdapter, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def init_poolmanager(self, connections, maxsize, block=False): <NEW_LINE> <INDENT> self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version) | A HTTPS Adapter for Python Requests that allows the choice of the SSL/TLS
version negotiated by Requests. This can be used either to enforce the
choice of high-security TLS versions (where supported), or to work around
misbehaving servers that fail to correctly negotiate the default TLS
version being offered.
Example usage:
>>> import requests
>>> import ssl
>>> from requests_toolbelt import SSLAdapter
>>> s = requests.Session()
>>> s.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1))
You can replace the chosen protocol with any that are available in the
default Python SSL module. All subsequent requests that match the adapter
prefix will use the chosen SSL version instead of the default. | 62598f9e498bea3a75a5791b |
class TransactionCase(BaseCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> TransactionCase.cr = self.cursor() <NEW_LINE> TransactionCase.uid = openerp.SUPERUSER_ID <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.cr.rollback() <NEW_LINE> self.cr.close() | Subclass of BaseCase with a single transaction, rolled-back at the end of
each test (method). | 62598f9e55399d3f0562631c |
class LocalizeStaticMiddleware(object): <NEW_LINE> <INDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> if settings.DEBUG == False: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> if not hasattr(settings, 'LOCALIZE_STATIC'): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> if 'text/html' in response.get('Content-Type', ''): <NEW_LINE> <INDENT> localize_data = settings.LOCALIZE_STATIC <NEW_LINE> soup = BeautifulSoup(response.content, 'lxml') <NEW_LINE> tags_static_css = soup.findAll( 'link', rel='stylesheet', href=re.compile('^http[s]?.*\.css$')) <NEW_LINE> for tag in tags_static_css: <NEW_LINE> <INDENT> url = tag.attrs.get('href') <NEW_LINE> filename = url.split('/')[-1] <NEW_LINE> file_path = os.path.join( settings.BASE_DIR, localize_data.get('app_name'), 'static', localize_data.get('static_css_dir'), filename) <NEW_LINE> if os.path.isfile(file_path): <NEW_LINE> <INDENT> tag.attrs.update( {'href': os.path.join( settings.STATIC_URL, localize_data.get('static_css_dir'), filename) } ) <NEW_LINE> <DEDENT> <DEDENT> tags_static_js = soup.findAll( 'script', src=re.compile('^http[s]?.*\.js$')) <NEW_LINE> for tag in tags_static_js: <NEW_LINE> <INDENT> url = tag.attrs.get('src') <NEW_LINE> filename = url.split('/')[-1] <NEW_LINE> file_path = os.path.join( settings.BASE_DIR, localize_data.get('app_name'), 'static', localize_data.get('static_js_dir'), filename) <NEW_LINE> if os.path.isfile(file_path): <NEW_LINE> <INDENT> tag.attrs.update( {'src': os.path.join( settings.STATIC_URL, localize_data.get('static_js_dir'), filename) } ) <NEW_LINE> <DEDENT> <DEDENT> response.content = soup.prettify(soup.original_encoding) <NEW_LINE> <DEDENT> return response | Process links for static files, replase external links to local links if file exists. | 62598f9ecc0a2c111447ae07 |
class JsonCharacteristicTypeAssignmentReference(object): <NEW_LINE> <INDENT> swagger_types = { 'id': 'str', 'min': 'float', 'max': 'float', 'type': 'JsonResourceType' } <NEW_LINE> attribute_map = { 'id': 'id', 'min': 'min', 'max': 'max', 'type': 'type' } <NEW_LINE> def __init__(self, id=None, min=None, max=None, type=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._min = None <NEW_LINE> self._max = None <NEW_LINE> self._type = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.id = id <NEW_LINE> if min is not None: <NEW_LINE> <INDENT> self.min = min <NEW_LINE> <DEDENT> if max is not None: <NEW_LINE> <INDENT> self.max = max <NEW_LINE> <DEDENT> self.type = type <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `id`, must not be `None`") <NEW_LINE> <DEDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def min(self): <NEW_LINE> <INDENT> return self._min <NEW_LINE> <DEDENT> @min.setter <NEW_LINE> def min(self, min): <NEW_LINE> <INDENT> self._min = min <NEW_LINE> <DEDENT> @property <NEW_LINE> def max(self): <NEW_LINE> <INDENT> return self._max <NEW_LINE> <DEDENT> @max.setter <NEW_LINE> def max(self, max): <NEW_LINE> <INDENT> self._max = max <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @type.setter <NEW_LINE> def type(self, type): <NEW_LINE> <INDENT> if type is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `type`, must not be `None`") <NEW_LINE> <DEDENT> self._type = type <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, JsonCharacteristicTypeAssignmentReference): <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. | 62598f9e8e71fb1e983bb8b1 |
class ServerPackagesRepository(CachedRepository): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def revision(repository_id): <NEW_LINE> <INDENT> from entropy.server.interfaces import Server <NEW_LINE> srv = Server() <NEW_LINE> return srv.local_repository_revision(repository_id) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def remote_revision(repository_id): <NEW_LINE> <INDENT> from entropy.server.interfaces import Server <NEW_LINE> srv = Server() <NEW_LINE> return srv.remote_repository_revision(repository_id) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def update(entropy_client, repository_id, enable_upload, enable_download, force = False): <NEW_LINE> <INDENT> return ServerPackagesRepositoryUpdater(entropy_client, repository_id, enable_upload, enable_download, force = force).update() <NEW_LINE> <DEDENT> def _runConfigurationFilesUpdate(self, actions, files, protect_overwrite = False): <NEW_LINE> <INDENT> return super(ServerPackagesRepository, self)._runConfigurationFilesUpdate( actions, files, protect_overwrite = False) <NEW_LINE> <DEDENT> def handlePackage(self, pkg_data, revision = None, formattedContent = False): <NEW_LINE> <INDENT> pkgatom = entropy.dep.create_package_atom_string( pkg_data['category'], pkg_data['name'], pkg_data['version'], pkg_data['versiontag']) <NEW_LINE> increase_revision = False <NEW_LINE> if revision is None: <NEW_LINE> <INDENT> current_rev = max( pkg_data.get('revision', 0), 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_rev = revision <NEW_LINE> <DEDENT> manual_deps = set() <NEW_LINE> for package_id in self.getPackageIds(pkgatom): <NEW_LINE> <INDENT> if revision is None: <NEW_LINE> <INDENT> pkg_revision = self.retrieveRevision(package_id) <NEW_LINE> if pkg_revision >= current_rev: <NEW_LINE> <INDENT> current_rev = pkg_revision <NEW_LINE> increase_revision = True <NEW_LINE> <DEDENT> <DEDENT> manual_deps |= self.retrieveManualDependencies(package_id, resolve_conditional_deps = False) <NEW_LINE> self.removePackage(package_id) <NEW_LINE> <DEDENT> if increase_revision: <NEW_LINE> <INDENT> current_rev += 1 <NEW_LINE> <DEDENT> removelist = self.getPackagesToRemove( pkg_data['name'], pkg_data['category'], pkg_data['slot'], pkg_data['injected'] ) <NEW_LINE> for r_package_id in removelist: <NEW_LINE> <INDENT> manual_deps |= self.retrieveManualDependencies(r_package_id, resolve_conditional_deps = False) <NEW_LINE> self.removePackage(r_package_id) <NEW_LINE> <DEDENT> m_dep_id = etpConst['dependency_type_ids']['mdepend_id'] <NEW_LINE> for manual_dep in manual_deps: <NEW_LINE> <INDENT> pkg_data['pkg_dependencies'] += ((manual_dep, m_dep_id),) <NEW_LINE> <DEDENT> return self.addPackage(pkg_data, revision = current_rev, formatted_content = formattedContent) <NEW_LINE> <DEDENT> def setReadonly(self, readonly): <NEW_LINE> <INDENT> self._readonly = bool(readonly) <NEW_LINE> <DEDENT> _CONNECTION_POOL = {} <NEW_LINE> _CONNECTION_POOL_MUTEX = threading.RLock() <NEW_LINE> _CURSOR_POOL = {} <NEW_LINE> _CURSOR_POOL_MUTEX = threading.RLock() <NEW_LINE> def _connection_pool(self): <NEW_LINE> <INDENT> return ServerPackagesRepository._CONNECTION_POOL <NEW_LINE> <DEDENT> def _connection_pool_mutex(self): <NEW_LINE> <INDENT> return ServerPackagesRepository._CONNECTION_POOL_MUTEX <NEW_LINE> <DEDENT> def _cursor_pool(self): <NEW_LINE> <INDENT> return ServerPackagesRepository._CURSOR_POOL <NEW_LINE> <DEDENT> def _cursor_pool_mutex(self): <NEW_LINE> <INDENT> return ServerPackagesRepository._CURSOR_POOL_MUTEX | This class represents the installed packages repository and is a direct
subclass of EntropyRepository. | 62598f9e99cbb53fe6830ccd |
class Relationship: <NEW_LINE> <INDENT> def __init__(self, name, _from, to, on): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._from = _from <NEW_LINE> self._to = to <NEW_LINE> self._on = on | Classe que representa um relacionamento entre DataTables
Essa classe tem todas as informações que identificam um relacionamento
entre tabelas. Em qual coluna ele existe, de onde vem e pra onde vai. | 62598f9ef548e778e596b3a7 |
class Catalog(Model): <NEW_LINE> <INDENT> _attribute_map = { 'total_items': {'key': 'total_items', 'type': 'int'}, 'data': {'key': 'data', 'type': '[str]'}, } <NEW_LINE> def __init__(self, total_items=None, data=None): <NEW_LINE> <INDENT> super(Catalog, self).__init__() <NEW_LINE> self.total_items = total_items <NEW_LINE> self.data = data | Catalog.
:param total_items:
:type total_items: int
:param data:
:type data: list[str] | 62598f9e7047854f4633f1dd |
class Car(): <NEW_LINE> <INDENT> def __init__(self,make,model,year): <NEW_LINE> <INDENT> self.make = make <NEW_LINE> self.model = model <NEW_LINE> self.year = year <NEW_LINE> self.odometer_reading = 0 <NEW_LINE> <DEDENT> def fill_gas_tank(self): <NEW_LINE> <INDENT> print('The '+ self.model + 'fuel capacity is 50 litre') <NEW_LINE> <DEDENT> def get_descriptive_name(self): <NEW_LINE> <INDENT> long_name = str(self.year) + ' ' + self.make + ' ' +self.model <NEW_LINE> return long_name <NEW_LINE> <DEDENT> def read_odometer(self): <NEW_LINE> <INDENT> print('Tis car has ' + str(self.odometer_reading) + 'miles on it .') <NEW_LINE> <DEDENT> def update_odometer(self,mileage): <NEW_LINE> <INDENT> if mileage >= self.odometer_reading: <NEW_LINE> <INDENT> self.odometer_reading = mileage <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('You can roll back an odometer!') <NEW_LINE> <DEDENT> <DEDENT> def increment_odometer(self, miles): <NEW_LINE> <INDENT> self.odometer_reading += miles | 一次模拟汽车的简单尝试 | 62598f9e30bbd72246469874 |
class DiscoveryStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.Announce = channel.unary_unary( '/discovery.Discovery/Announce', request_serializer=Announcement.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) <NEW_LINE> self.GetAll = channel.unary_unary( '/discovery.Discovery/GetAll', request_serializer=GetServiceRequest.SerializeToString, response_deserializer=AnnouncementsResponse.FromString, ) <NEW_LINE> self.Get = channel.unary_unary( '/discovery.Discovery/Get', request_serializer=GetRequest.SerializeToString, response_deserializer=Announcement.FromString, ) <NEW_LINE> self.AddMetadata = channel.unary_unary( '/discovery.Discovery/AddMetadata', request_serializer=MetadataRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) <NEW_LINE> self.DeleteMetadata = channel.unary_unary( '/discovery.Discovery/DeleteMetadata', request_serializer=MetadataRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) <NEW_LINE> self.GetByAppID = channel.unary_unary( '/discovery.Discovery/GetByAppID', request_serializer=GetByAppIDRequest.SerializeToString, response_deserializer=Announcement.FromString, ) <NEW_LINE> self.GetByGatewayID = channel.unary_unary( '/discovery.Discovery/GetByGatewayID', request_serializer=GetByGatewayIDRequest.SerializeToString, response_deserializer=Announcement.FromString, ) <NEW_LINE> self.GetByAppEUI = channel.unary_unary( '/discovery.Discovery/GetByAppEUI', request_serializer=GetByAppEUIRequest.SerializeToString, response_deserializer=Announcement.FromString, ) | The Discovery service is used to discover services within The Things Network.
| 62598f9ee1aae11d1e7ce722 |
class Benchmark: <NEW_LINE> <INDENT> def __init__(self, bounds, global_minima, func, **kwargs): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> self._bounds = bounds <NEW_LINE> self._global_minima = global_minima <NEW_LINE> self.kwargs = kwargs <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.func(*args, **kwargs) <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(self.func, attr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dims(self): <NEW_LINE> <INDENT> if hasattr(self, '_dims'): <NEW_LINE> <INDENT> return self._dims <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('For N-dimensional benchmarks the property \'dims\' has to be set.') <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> @dims.setter <NEW_LINE> def dims(self, value): <NEW_LINE> <INDENT> self._dims = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def bounds(self): <NEW_LINE> <INDENT> return [self._bounds] * self.dims if self.is_n_dimensional else self._bounds <NEW_LINE> <DEDENT> @property <NEW_LINE> def global_minima(self): <NEW_LINE> <INDENT> return [[minima for _ in range(self.dims)] for minima in self._global_minima] if self.is_n_dimensional else self._global_minima | Benchmark function wrapper. Enables setting and getting of benchmark
properties while also acting as a function. | 62598f9e9c8ee8231304006b |
class AnkiEmpty(AnkiTest): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> (self.fd, self.name) = tempfile.mkstemp(suffix=".anki2") <NEW_LINE> os.close(self.fd) <NEW_LINE> os.unlink(self.name) <NEW_LINE> super().__init__(Anki(path=self.name)) | Create Anki collection wrapper for an empty collection | 62598f9eac7a0e7691f72306 |
class HubVirtualNetworkConnection(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'}, 'allow_hub_to_remote_vnet_transit': {'key': 'properties.allowHubToRemoteVnetTransit', 'type': 'bool'}, 'allow_remote_vnet_to_use_hub_vnet_gateways': {'key': 'properties.allowRemoteVnetToUseHubVnetGateways', 'type': 'bool'}, 'enable_internet_security': {'key': 'properties.enableInternetSecurity', 'type': 'bool'}, 'routing_configuration': {'key': 'properties.routingConfiguration', 'type': 'RoutingConfiguration'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, remote_virtual_network: Optional["SubResource"] = None, allow_hub_to_remote_vnet_transit: Optional[bool] = None, allow_remote_vnet_to_use_hub_vnet_gateways: Optional[bool] = None, enable_internet_security: Optional[bool] = None, routing_configuration: Optional["RoutingConfiguration"] = None, **kwargs ): <NEW_LINE> <INDENT> super(HubVirtualNetworkConnection, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = None <NEW_LINE> self.remote_virtual_network = remote_virtual_network <NEW_LINE> self.allow_hub_to_remote_vnet_transit = allow_hub_to_remote_vnet_transit <NEW_LINE> self.allow_remote_vnet_to_use_hub_vnet_gateways = allow_remote_vnet_to_use_hub_vnet_gateways <NEW_LINE> self.enable_internet_security = enable_internet_security <NEW_LINE> self.routing_configuration = routing_configuration <NEW_LINE> self.provisioning_state = None | HubVirtualNetworkConnection Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param remote_virtual_network: Reference to the remote virtual network.
:type remote_virtual_network: ~azure.mgmt.network.v2020_11_01.models.SubResource
:param allow_hub_to_remote_vnet_transit: Deprecated: VirtualHub to RemoteVnet transit to
enabled or not.
:type allow_hub_to_remote_vnet_transit: bool
:param allow_remote_vnet_to_use_hub_vnet_gateways: Deprecated: Allow RemoteVnet to use Virtual
Hub's gateways.
:type allow_remote_vnet_to_use_hub_vnet_gateways: bool
:param enable_internet_security: Enable internet security.
:type enable_internet_security: bool
:param routing_configuration: The Routing Configuration indicating the associated and
propagated route tables on this connection.
:type routing_configuration: ~azure.mgmt.network.v2020_11_01.models.RoutingConfiguration
:ivar provisioning_state: The provisioning state of the hub virtual network connection
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2020_11_01.models.ProvisioningState | 62598f9e925a0f43d25e7e38 |
@ComponentFactory("eventadmin-shell-commands-factory") <NEW_LINE> @Requires("_events", pelix.services.SERVICE_EVENT_ADMIN) <NEW_LINE> @Provides(SHELL_COMMAND_SPEC) <NEW_LINE> @Instantiate("eventadmin-shell-commands") <NEW_LINE> class EventAdminCommands(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._events = None <NEW_LINE> <DEDENT> def get_namespace(self): <NEW_LINE> <INDENT> return "event" <NEW_LINE> <DEDENT> def get_methods(self): <NEW_LINE> <INDENT> return [("send", self.send), ("post", self.post)] <NEW_LINE> <DEDENT> def send(self, io_handler, topic, **kwargs): <NEW_LINE> <INDENT> self._events.send(topic, kwargs) <NEW_LINE> <DEDENT> def post(self, io_handler, topic, **kwargs): <NEW_LINE> <INDENT> self._events.post(topic, kwargs) | EventAdmin shell commands | 62598f9e3d592f4c4edbacc9 |
class Port(object): <NEW_LINE> <INDENT> def __init__(self, data_type=MAKE_DATA()): <NEW_LINE> <INDENT> self._data_type = data_type <NEW_LINE> self._pipes = [] <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del self._pipes[key] <NEW_LINE> <DEDENT> def index(self, pipe): <NEW_LINE> <INDENT> return self._pipes.index(pipe) <NEW_LINE> <DEDENT> @property <NEW_LINE> def data_type(self): <NEW_LINE> <INDENT> return self._data_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def pipes(self): <NEW_LINE> <INDENT> return self._pipes <NEW_LINE> <DEDENT> def __iadd__(self, pipe): <NEW_LINE> <INDENT> self._pipes.append(pipe) <NEW_LINE> return self | class to define a connection port in sink or in pump
| 62598f9e6aa9bd52df0d4cc8 |
class StringLabeler(Labeler): <NEW_LINE> <INDENT> def __init__(self, labels=[]): <NEW_LINE> <INDENT> self._labels = [] <NEW_LINE> self.setLabels(labels) <NEW_LINE> <DEDENT> def setLabels(self, labels): <NEW_LINE> <INDENT> if isinstance(labels, list) or isinstance(labels, tuple): <NEW_LINE> <INDENT> self._labels = list(labels) <NEW_LINE> <DEDENT> <DEDENT> def labels(self, locations): <NEW_LINE> <INDENT> locsLength = len(locations) <NEW_LINE> labelsLength = len(self._labels) <NEW_LINE> strings = [] <NEW_LINE> if locsLength == labelsLength: <NEW_LINE> <INDENT> strings.extend(self._labels) <NEW_LINE> <DEDENT> elif locsLength > labelsLength: <NEW_LINE> <INDENT> strings.extend(self._labels) <NEW_LINE> strings.extend([''] * (locsLength - labelsLength)) <NEW_LINE> <DEDENT> elif locsLength < labelsLength: <NEW_LINE> <INDENT> strings.extend(self._labels[:locsLength]) <NEW_LINE> <DEDENT> return map(str, strings) | Labels that are manually specified by the user.
If the user specifies fewer labels than the number of locations that
are requested, then empty strings are added. If there are too many
labels, then the label list is truncated. | 62598f9ea8370b77170f01df |
class Command(BaseCommand): <NEW_LINE> <INDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> new_state, created = State.objects.get_or_create( abbreviation='CA', name='California') <NEW_LINE> placeholder, created = State.objects.get_or_create( abbreviation='N/A', name='N/A') | Populate State model. | 62598f9e8e7ae83300ee8e9b |
class HTMLWriter(object): <NEW_LINE> <INDENT> def __init__(self, build_path, template): <NEW_LINE> <INDENT> self.build_path = build_path <NEW_LINE> self.template = template <NEW_LINE> quiet_mkdir(self.build_path) <NEW_LINE> <DEDENT> def write(self, base, data): <NEW_LINE> <INDENT> path_prefix = '..' <NEW_LINE> quiet_mkdir(os.path.join(self.build_path, base)) <NEW_LINE> if base != 'intro': <NEW_LINE> <INDENT> destination = os.path.join(os.path.join(self.build_path, base, 'index.html')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path_prefix = '.' <NEW_LINE> destination = os.path.join(os.path.join(self.build_path, 'index.html')) <NEW_LINE> <DEDENT> data.update({ 'path_prefix': path_prefix, 'date': now.strftime("%a, %d %b %Y %H:%M") }) <NEW_LINE> with codecs.open(destination, 'w', encoding='utf') as fd: <NEW_LINE> <INDENT> fd.write(self.template.render(data)) | HTML Writer, builds documentation | 62598f9e435de62698e9bbef |
class CoordinateParser(PunchParser): <NEW_LINE> <INDENT> def test(self, line, data): <NEW_LINE> <INDENT> return "symbols" in data and line == " COORDINATES OF SYMMETRY UNIQUE ATOMS (ANGS)\n" <NEW_LINE> <DEDENT> def read(self, line, f, data): <NEW_LINE> <INDENT> f.readline() <NEW_LINE> f.readline() <NEW_LINE> N = len(data["symbols"]) <NEW_LINE> numbers = data.get("numbers") <NEW_LINE> if numbers is None: <NEW_LINE> <INDENT> numbers = np.zeros(N, int) <NEW_LINE> data["numbers"] = numbers <NEW_LINE> <DEDENT> coordinates = data.get("coordinates") <NEW_LINE> if coordinates is None: <NEW_LINE> <INDENT> coordinates = np.zeros((N,3), float) <NEW_LINE> data["coordinates"] = coordinates <NEW_LINE> <DEDENT> for i in range(N): <NEW_LINE> <INDENT> words = f.readline().split() <NEW_LINE> numbers[i] = int(float(words[1])) <NEW_LINE> coordinates[i,0] = float(words[2])*angstrom <NEW_LINE> coordinates[i,1] = float(words[3])*angstrom <NEW_LINE> coordinates[i,2] = float(words[4])*angstrom | Extracts ``numbers`` and ``coordinates`` from the punch file. | 62598f9e8da39b475be02fdb |
class MnistMLP(chainer.Chain): <NEW_LINE> <INDENT> def __init__(self, n_in, n_units, n_out): <NEW_LINE> <INDENT> super(MnistMLP, self).__init__( l1=L.Linear(n_in, n_units), l2=L.Linear(n_units, n_units), l3=L.Linear(n_units, n_out), ) <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> h1 = F.relu(self.l1(x)) <NEW_LINE> h2 = F.relu(self.l2(h1)) <NEW_LINE> return self.l3(h2) | An example of multi-layer perceptron for MNIST dataset.
This is a very simple implementation of an MLP. You can modify this code to
build your own neural net. | 62598f9e24f1403a926857b0 |
class PublishNoticeView(View): <NEW_LINE> <INDENT> def post(self,request): <NEW_LINE> <INDENT> title = request.POST.get('title','') <NEW_LINE> content = request.POST.get('content','') <NEW_LINE> Note =Notice() <NEW_LINE> Note.title = title <NEW_LINE> Note.content = content <NEW_LINE> Note.save() <NEW_LINE> return HttpResponseRedirect('/') | 管理员在首页快速发布通知 | 62598f9e462c4b4f79dbb807 |
class BlogTag(models.Model): <NEW_LINE> <INDENT> objects = BlogTagManager() <NEW_LINE> name = models.CharField(max_length=255, unique=True) <NEW_LINE> slug = models.SlugField(unique=True, max_length=120) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> app_label = 'PyLucidPlugins' <NEW_LINE> ordering = ('name',) | A blog entry tag
TODO: Add a usage counter! So we can easy sort from more to less usages and
building a tag cloud is easier. | 62598f9e10dbd63aa1c709b1 |
class LdapConnectionsCommand(DefaultCommand): <NEW_LINE> <INDENT> IDENTIFIER = "label" <NEW_LINE> DEFAULT_SORT = "label" <NEW_LINE> RESOURCE_IDENTIFIER = "uuid" <NEW_LINE> DEFAULT_TOTAL = "Ldap connection found : %(count)s" <NEW_LINE> MSG_RS_NOT_FOUND = "No Ldap connection could be found." <NEW_LINE> MSG_RS_DELETED = ( "%(position)s/%(count)s: " "The Ldap connection '%(label)s' (%(uuid)s) was deleted. " "(%(time)s s)" ) <NEW_LINE> MSG_RS_CAN_NOT_BE_DELETED = "The Ldap connection '%(label)s' '%(uuid)s' can not be deleted." <NEW_LINE> MSG_RS_CAN_NOT_BE_DELETED_M = "%(count)s Ldap connection(s) can not be deleted." <NEW_LINE> MSG_RS_UPDATED = "The Ldap connection '%(label)s' (%(uuid)s) was successfully updated." <NEW_LINE> MSG_RS_CREATED = ( "The Ldap connection '%(label)s' (%(uuid)s) was " "successfully created. (%(_time)s s)" ) <NEW_LINE> def init_old_language_key(self): <NEW_LINE> <INDENT> self.IDENTIFIER = "identifier" <NEW_LINE> self.DEFAULT_SORT = "identifier" <NEW_LINE> self.RESOURCE_IDENTIFIER = "identifier" <NEW_LINE> self.DEFAULT_TOTAL = "Ldap connection found : %(count)s" <NEW_LINE> self.MSG_RS_NOT_FOUND = "No Ldap connection could be found." <NEW_LINE> self.MSG_RS_DELETED = "The Ldap connection '%(identifier)s' was deleted. (%(time)s s)" <NEW_LINE> self.MSG_RS_DELETED = ( "%(position)s/%(count)s: " "The Ldap connection '%(identifier)s' was deleted. (%(time)s s)" ) <NEW_LINE> self.MSG_RS_CAN_NOT_BE_DELETED = "The Ldap connection '%(identifier)s' can not be deleted." <NEW_LINE> self.MSG_RS_CAN_NOT_BE_DELETED_M = "%(count)s Ldap connection(s) can not be deleted." <NEW_LINE> self.MSG_RS_UPDATED = "The Ldap connection '%(identifier)s' was successfully updated." <NEW_LINE> self.MSG_RS_CREATED = "The Ldap connection '%(identifier)s' was successfully created." <NEW_LINE> <DEDENT> def complete(self, args, prefix): <NEW_LINE> <INDENT> super(LdapConnectionsCommand, self).__call__(args) <NEW_LINE> if self.api_version == 0: <NEW_LINE> <INDENT> self.init_old_language_key() <NEW_LINE> <DEDENT> json_obj = self.ls.ldap_connections.list() <NEW_LINE> return (v.get(self.RESOURCE_IDENTIFIER) for v in json_obj if v.get(self.RESOURCE_IDENTIFIER).startswith(prefix)) | For api >= 1.9 | 62598f9e21a7993f00c65d7f |
class Attribute(object): <NEW_LINE> <INDENT> CREATED = "created" <NEW_LINE> CHANGED = "changed" <NEW_LINE> READ = "read" <NEW_LINE> def __init__(self, operation, name, given_value=None, new_value=None): <NEW_LINE> <INDENT> assert operation in [self.CREATED, self.CHANGED, self.READ] <NEW_LINE> assert isinstance(name, str) <NEW_LINE> self.operation = operation <NEW_LINE> self.name = name <NEW_LINE> self.given_value = given_value <NEW_LINE> self.new_value = new_value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.operation in [self.CREATED, self.READ]: <NEW_LINE> <INDENT> text = "Attribute(operation=%(operation)s, name=%(name)s, value=%(given_value)s)" <NEW_LINE> return text % self.__dict__ <NEW_LINE> <DEDENT> text = "Attribute(operation=%(operation)s, name=%(name)s," + " value=%(given_value)s -> %(new_value)s)" <NEW_LINE> return text % self.__dict__ <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Attribute): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self.name == other.name: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self.given_value == other.given_value: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.new_value == other.new_value <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Attribute): <NEW_LINE> <INDENT> return compare(str(self), str(other)) <NEW_LINE> <DEDENT> diff = compare(self.operation, other.operation) <NEW_LINE> if not diff == 0: <NEW_LINE> <INDENT> return diff <NEW_LINE> <DEDENT> diff = compare(self.name, other.name) <NEW_LINE> if not diff == 0: <NEW_LINE> <INDENT> return diff <NEW_LINE> <DEDENT> diff = compare(self.given_value, other.given_value) <NEW_LINE> if not diff == 0: <NEW_LINE> <INDENT> return diff <NEW_LINE> <DEDENT> return compare(self.new_value, other.new_value) | Represents mock attribute state for create, read and write and the relating values. | 62598f9e44b2445a339b686b |
class Galactic(BaseCoordinateFrame): <NEW_LINE> <INDENT> frame_specific_representation_info = { 'spherical': [RepresentationMapping('lon', 'l'), RepresentationMapping('lat', 'b')], 'cartesian': [RepresentationMapping('x', 'w'), RepresentationMapping('y', 'u'), RepresentationMapping('z', 'v')] } <NEW_LINE> frame_specific_representation_info['unitspherical'] = frame_specific_representation_info['spherical'] <NEW_LINE> default_representation = SphericalRepresentation <NEW_LINE> _ngp_B1950 = FK4NoETerms(ra=192.25*u.degree, dec=27.4*u.degree) <NEW_LINE> _lon0_B1950 = Angle(123, u.degree) <NEW_LINE> _ngp_J2000 = FK5(ra=192.8594812065348*u.degree, dec=27.12825118085622*u.degree) <NEW_LINE> _lon0_J2000 = Angle(122.9319185680026, u.degree) | Galactic Coordinates.
Parameters
----------
representation : `BaseRepresentation` or None
A representation object or None to have no data (or use the other keywords)
l : `Angle`, optional, must be keyword
The Galactic longitude for this object (``b`` must also be given and
``representation`` must be None).
b : `Angle`, optional, must be keyword
The Galactic latitude for this object (``l`` must also be given and
``representation`` must be None).
distance : `~astropy.units.Quantity`, optional, must be keyword
The Distance for this object along the line-of-sight. | 62598f9e1f5feb6acb162a1e |
class IpacHeader(BaseHeader): <NEW_LINE> <INDENT> comment = r'\\' <NEW_LINE> splitter_class = BaseSplitter <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.splitter = self.__class__.splitter_class() <NEW_LINE> self.splitter.process_line = None <NEW_LINE> self.splitter.process_val = None <NEW_LINE> self.splitter.delimiter = '|' <NEW_LINE> <DEDENT> def process_lines(self, lines): <NEW_LINE> <INDENT> delim = self.splitter.delimiter <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if line.startswith(delim) and line.endswith(delim): <NEW_LINE> <INDENT> yield line.strip(delim) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_cols(self, lines): <NEW_LINE> <INDENT> header_lines = self.process_lines(lines) <NEW_LINE> header_vals = [vals for vals in self.splitter(header_lines)] <NEW_LINE> if len(header_vals) == 0: <NEW_LINE> <INDENT> raise ValueError('At least one header line beginning and ending with delimiter required') <NEW_LINE> <DEDENT> elif len(header_vals) > 4: <NEW_LINE> <INDENT> raise ValueError('More than four header lines were found') <NEW_LINE> <DEDENT> cols = [] <NEW_LINE> start = 1 <NEW_LINE> for i, name in enumerate(header_vals[0]): <NEW_LINE> <INDENT> col = Column(name=name.strip(' -'), index=i) <NEW_LINE> col.start = start <NEW_LINE> col.end = start + len(name) <NEW_LINE> if len(header_vals) > 1: <NEW_LINE> <INDENT> col.type = header_vals[1][i].strip(' -') <NEW_LINE> <DEDENT> if len(header_vals) > 2: <NEW_LINE> <INDENT> col.units = header_vals[2][i].strip() <NEW_LINE> <DEDENT> if len(header_vals) > 3: <NEW_LINE> <INDENT> col.null = header_vals[3][i].strip() <NEW_LINE> <DEDENT> start = col.end + 1 <NEW_LINE> cols.append(col) <NEW_LINE> <DEDENT> self.names = [x.name for x in cols] <NEW_LINE> names = set(self.names) <NEW_LINE> if self.include_names is not None: <NEW_LINE> <INDENT> names.intersection_update(self.include_names) <NEW_LINE> <DEDENT> if self.exclude_names is not None: <NEW_LINE> <INDENT> names.difference_update(self.exclude_names) <NEW_LINE> <DEDENT> self.cols = [x for x in cols if x.name in names] <NEW_LINE> for i, col in enumerate(self.cols): <NEW_LINE> <INDENT> col.index = i | IPAC table header | 62598f9e8e7ae83300ee8e9c |
class MongoDbLinkedService(LinkedService): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, 'server': {'required': True}, 'database_name': {'required': True}, } <NEW_LINE> _attribute_map = { 'additional_properties': {'key': '', 'type': '{object}'}, 'connect_via': {'key': 'connectVia', 'type': 'IntegrationRuntimeReference'}, 'description': {'key': 'description', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'server': {'key': 'typeProperties.server', 'type': 'object'}, 'authentication_type': {'key': 'typeProperties.authenticationType', 'type': 'str'}, 'database_name': {'key': 'typeProperties.databaseName', 'type': 'object'}, 'username': {'key': 'typeProperties.username', 'type': 'object'}, 'password': {'key': 'typeProperties.password', 'type': 'SecretBase'}, 'auth_source': {'key': 'typeProperties.authSource', 'type': 'object'}, 'port': {'key': 'typeProperties.port', 'type': 'object'}, 'encrypted_credential': {'key': 'typeProperties.encryptedCredential', 'type': 'object'}, } <NEW_LINE> def __init__(self, server, database_name, additional_properties=None, connect_via=None, description=None, authentication_type=None, username=None, password=None, auth_source=None, port=None, encrypted_credential=None): <NEW_LINE> <INDENT> super(MongoDbLinkedService, self).__init__(additional_properties=additional_properties, connect_via=connect_via, description=description) <NEW_LINE> self.server = server <NEW_LINE> self.authentication_type = authentication_type <NEW_LINE> self.database_name = database_name <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.auth_source = auth_source <NEW_LINE> self.port = port <NEW_LINE> self.encrypted_credential = encrypted_credential <NEW_LINE> self.type = 'MongoDb' | Linked service for MongoDb data source.
:param additional_properties: Unmatched properties from the message are
deserialized this collection
:type additional_properties: dict[str, object]
:param connect_via: The integration runtime reference.
:type connect_via:
~azure.mgmt.datafactory.models.IntegrationRuntimeReference
:param description: Linked service description.
:type description: str
:param type: Constant filled by server.
:type type: str
:param server: The IP address or server name of the MongoDB server. Type:
string (or Expression with resultType string).
:type server: object
:param authentication_type: The authentication type to be used to connect
to the MongoDB database. Possible values include: 'Basic', 'Anonymous'
:type authentication_type: str or
~azure.mgmt.datafactory.models.MongoDbAuthenticationType
:param database_name: The name of the MongoDB database that you want to
access. Type: string (or Expression with resultType string).
:type database_name: object
:param username: Username for authentication. Type: string (or Expression
with resultType string).
:type username: object
:param password: Password for authentication.
:type password: ~azure.mgmt.datafactory.models.SecretBase
:param auth_source: Database to verify the username and password. Type:
string (or Expression with resultType string).
:type auth_source: object
:param port: The TCP port number that the MongoDB server uses to listen
for client connections. The default value is 27017. Type: integer (or
Expression with resultType integer), minimum: 0.
:type port: object
:param encrypted_credential: The encrypted credential used for
authentication. Credentials are encrypted using the integration runtime
credential manager. Type: string (or Expression with resultType string).
:type encrypted_credential: object | 62598f9e656771135c48947f |
class retry_scenario(object): <NEW_LINE> <INDENT> def __init__(self, retries, delay, multiplier, context_string=None): <NEW_LINE> <INDENT> self.retries = retries <NEW_LINE> self.delay = delay <NEW_LINE> self.multiplier = multiplier <NEW_LINE> self.context_string = context_string <NEW_LINE> <DEDENT> def munge_delay(self): <NEW_LINE> <INDENT> if 0 == self.retries: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if self.multiplier == 1.0 or self.retries == 1: <NEW_LINE> <INDENT> time_to_failure = self.delay * self.retries <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time_to_failure = 0 <NEW_LINE> for i in range(0, self.retries): <NEW_LINE> <INDENT> time_to_failure += int(self.delay * pow(self.multiplier, i)) <NEW_LINE> <DEDENT> <DEDENT> return time_to_failure - 0.25 | Stores context information about a test scenario.
See https://docs.irods.org/4.2.4/plugins/composable_resources | 62598f9e0a50d4780f7051d6 |
class TestCreateRecordingParameters(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 testCreateRecordingParameters(self): <NEW_LINE> <INDENT> model = dialmycalls_client.models.create_recording_parameters.CreateRecordingParameters() | CreateRecordingParameters unit test stubs | 62598f9e67a9b606de545dc5 |
class TestXmlNs0ChangeAttributeRequest(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 testXmlNs0ChangeAttributeRequest(self): <NEW_LINE> <INDENT> pass | XmlNs0ChangeAttributeRequest unit test stubs | 62598f9ee5267d203ee6b70a |
class LRDataset(data.Dataset): <NEW_LINE> <INDENT> def __init__(self, opt): <NEW_LINE> <INDENT> super(LRDataset, self).__init__() <NEW_LINE> self.opt = opt <NEW_LINE> self.paths_LR = None <NEW_LINE> self.LR_env = None <NEW_LINE> self.LR_env, self.paths_LR = util.get_image_paths( opt["data_type"], opt["dataroot_LR"] ) <NEW_LINE> assert self.paths_LR, "Error: LR paths are empty." <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> LR_path = None <NEW_LINE> LR_path = self.paths_LR[index] <NEW_LINE> img_LR = util.read_img(self.LR_env, LR_path) <NEW_LINE> H, W, C = img_LR.shape <NEW_LINE> if self.opt["color"]: <NEW_LINE> <INDENT> img_LR = util.channel_convert(C, self.opt["color"], [img_LR])[0] <NEW_LINE> <DEDENT> if img_LR.shape[2] == 3: <NEW_LINE> <INDENT> img_LR = img_LR[:, :, [2, 1, 0]] <NEW_LINE> <DEDENT> img_LR = torch.from_numpy( np.ascontiguousarray(np.transpose(img_LR, (2, 0, 1))) ).float() <NEW_LINE> return {"LR": img_LR, "LR_path": LR_path} <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.paths_LR) | Read LR images only in the test phase. | 62598f9e7b25080760ed72a4 |
class StructType(PointerType): <NEW_LINE> <INDENT> def __init__(self, struct_type_getter, nullable=False): <NEW_LINE> <INDENT> PointerType.__init__(self) <NEW_LINE> self._struct_type_getter = struct_type_getter <NEW_LINE> self._struct_type = None <NEW_LINE> self.nullable = nullable <NEW_LINE> <DEDENT> @property <NEW_LINE> def struct_type(self): <NEW_LINE> <INDENT> if not self._struct_type: <NEW_LINE> <INDENT> self._struct_type = self._struct_type_getter() <NEW_LINE> <DEDENT> return self._struct_type <NEW_LINE> <DEDENT> def Convert(self, value): <NEW_LINE> <INDENT> if value is None or isinstance(value, self.struct_type): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> raise TypeError('%r is not an instance of %r' % (value, self.struct_type)) <NEW_LINE> <DEDENT> def GetDefaultValue(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> return self.struct_type() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def SerializePointer(self, value, data_offset, data, handle_offset): <NEW_LINE> <INDENT> (new_data, new_handles) = value.Serialize(handle_offset) <NEW_LINE> data.extend(new_data) <NEW_LINE> return (data_offset, new_handles) <NEW_LINE> <DEDENT> def DeserializePointer(self, size, nb_elements, data, handles): <NEW_LINE> <INDENT> return self.struct_type.Deserialize(data, handles) | Type object for structs. | 62598f9e3c8af77a43b67e3d |
class Database(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.db_path = notmuch_settings.get('database', 'path') <NEW_LINE> <DEDENT> def do_query(self, query): <NEW_LINE> <INDENT> if hasattr(self, 'query'): <NEW_LINE> <INDENT> if query: <NEW_LINE> <INDENT> query = '(%s) AND (%s)' % (query, self.query) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = self.query <NEW_LINE> <DEDENT> <DEDENT> logging.debug('Executing query %r' % query) <NEW_LINE> db = notmuch.Database(self.db_path) <NEW_LINE> return notmuch.Query(db, query) <NEW_LINE> <DEDENT> def get_messages(self, query, full_thread = False): <NEW_LINE> <INDENT> if not full_thread: <NEW_LINE> <INDENT> for message in self.do_query(query).search_messages(): <NEW_LINE> <INDENT> yield message <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for thread in self.do_query(query).search_threads(): <NEW_LINE> <INDENT> for message in self.walk_thread(thread): <NEW_LINE> <INDENT> yield message <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def mail_bodies_matching(self, *args, **kwargs): <NEW_LINE> <INDENT> query = self.get_messages(*args, **kwargs) <NEW_LINE> for message in query: <NEW_LINE> <INDENT> yield extract_mail_body(message) <NEW_LINE> <DEDENT> <DEDENT> def walk_replies(self, message): <NEW_LINE> <INDENT> yield message <NEW_LINE> replies = message.get_replies() <NEW_LINE> if replies != None: <NEW_LINE> <INDENT> for message in replies: <NEW_LINE> <INDENT> for message in self.walk_replies(message): <NEW_LINE> <INDENT> yield message <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def walk_thread(self, thread): <NEW_LINE> <INDENT> for message in thread.get_toplevel_messages(): <NEW_LINE> <INDENT> for message in self.walk_replies(message): <NEW_LINE> <INDENT> yield message | Convenience wrapper around `notmuch`. | 62598f9e7047854f4633f1e0 |
class StaticGenome(Genome): <NEW_LINE> <INDENT> pass | Realization of Genome.
Basically, a StaticGenome is a python code with quantity of
arguments and attributes. | 62598f9e91af0d3eaad39c07 |
class PathPlot(GraphPlot): <NEW_LINE> <INDENT> def __init__(self, xlist, ylist, path=[], labels=None, **keywords): <NEW_LINE> <INDENT> edges = zip(path,path[1:]) <NEW_LINE> GraphPlot.__init__(self, xlist, ylist, edges, labels, **keywords) | Given a set of vertices and a path through those vertices.
The path is a sequence (list or tuple) specifying the order in which
vertices are visited. | 62598f9e30bbd72246469875 |
@attributes(["going", "coming", "creating", "resizing", "deleting"]) <NEW_LINE> class DatasetChanges(object): <NEW_LINE> <INDENT> pass | The dataset-related changes necessary to change the current state to
the desired state.
:ivar frozenset going: The ``DatasetHandoff``\ s necessary to let
other nodes take over hosting datasets being moved away from a
node. These must be handed off.
:ivar frozenset coming: The ``Dataset``\ s necessary to let this
node take over hosting of any datasets being moved to
this node. These must be acquired.
:ivar frozenset creating: The ``Dataset``\ s necessary to let this
node create any new datasets meant to be hosted on
this node. These must be created.
:ivar frozenset resizing: The ``Dataset``\ s necessary to let this
node resize any existing datasets that are desired somewhere on
the cluster and locally exist with a different maximum_size to the
desired maximum_size. These must be resized.
:ivar frozenset deleting: The ``Dataset``\ s that should be deleted. | 62598f9e85dfad0860cbf973 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.