code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class CmdPuiser(Commande): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Commande.__init__(self, "puiser", "draw") <NEW_LINE> self.nom_categorie = "objets" <NEW_LINE> self.schema = "<nom_objet>" <NEW_LINE> self.aide_courte = "puise de l'eau" <NEW_LINE> self.aide_longue = "Cette commande remplit d'eau un conteneur adapté, si vous " "vous trouvez dans une salle avec de l'eau à portée de main " "(rive, salle aquatique, ou contenant une fontaine)." <NEW_LINE> <DEDENT> def ajouter(self): <NEW_LINE> <INDENT> nom_objet = self.noeud.get_masque("nom_objet") <NEW_LINE> nom_objet.proprietes["conteneurs"] = "(personnage.equipement.inventaire, )" <NEW_LINE> nom_objet.proprietes["types"] = "('conteneur de potion', )" <NEW_LINE> <DEDENT> def interpreter(self, personnage, dic_masques): <NEW_LINE> <INDENT> personnage.agir("prendre") <NEW_LINE> conteneur = dic_masques["nom_objet"].objet <NEW_LINE> salle = personnage.salle <NEW_LINE> fontaine = salle.a_detail_flag("fontaine") <NEW_LINE> if not fontaine and salle.terrain.nom not in ("rive", "aquatique", "subaquatique"): <NEW_LINE> <INDENT> personnage << "|err|Il n'y a pas d'eau potable par ici.|ff|" <NEW_LINE> return <NEW_LINE> <DEDENT> if conteneur.potion is not None: <NEW_LINE> <INDENT> personnage << "|err|{} contient déjà du liquide.|ff|".format( conteneur.get_nom()) <NEW_LINE> return <NEW_LINE> <DEDENT> eau = importeur.objet.creer_objet(importeur.objet.prototypes["eau"]) <NEW_LINE> conteneur.potion = eau <NEW_LINE> conteneur.remplir() <NEW_LINE> personnage << "Vous puisez {}.".format( conteneur.get_nom()) <NEW_LINE> personnage.salle.envoyer("{{}} puise {}.".format( conteneur.get_nom()), personnage)
Commande 'puiser'
6259907899cbb53fe6832886
class FunctionalTestCase(ptc.FunctionalTestCase): <NEW_LINE> <INDENT> layer = bbb.plone <NEW_LINE> def afterSetUp(self): <NEW_LINE> <INDENT> self.loginAsPortalOwner() <NEW_LINE> roles = ('Member', 'Contributor') <NEW_LINE> self.portal.portal_membership.addMember('contributor', 'secret', roles, [])
We use this class for functional integration tests that use doctest syntax. Again, we can put basic common utility or setup code in here.
625990785fdd1c0f98e5f91e
class MetaResource(ABCMeta): <NEW_LINE> <INDENT> def __new__(cls, name, bases, body): <NEW_LINE> <INDENT> body['resource'] = name.lower() <NEW_LINE> return super().__new__(cls, name, bases, body)
Metaclass for Crossref Resources. Sets the `resources` attribute with __new__ constructor from class name.
6259907897e22403b383c8a3
class NN(DAGraph, ShowGraph): <NEW_LINE> <INDENT> def __init__(self, leaves, roots, create_connection=True): <NEW_LINE> <INDENT> nodes = self.get_subgraph(leaves, roots) <NEW_LINE> super(NN, self).__init__(nodes) <NEW_LINE> if create_connection: <NEW_LINE> <INDENT> self.create_connections() <NEW_LINE> <DEDENT> <DEDENT> def forward(self, *args, **kwargs): <NEW_LINE> <INDENT> for key, val in kwargs.items(): <NEW_LINE> <INDENT> for inp_layer in self.leaves: <NEW_LINE> <INDENT> if key in inp_layer.interface.keys(): <NEW_LINE> <INDENT> if inp_layer.interface[key] is None: <NEW_LINE> <INDENT> keep_rock_n_rolling(inp_layer, input_=val, name=key) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> outputs = [root.output for root in self.roots] <NEW_LINE> if len(outputs) == 1: <NEW_LINE> <INDENT> outputs = outputs[0] <NEW_LINE> <DEDENT> return outputs <NEW_LINE> <DEDENT> def backward(self): <NEW_LINE> <INDENT> self.back_flow(grad_accumulator) <NEW_LINE> <DEDENT> def optimize(self, lr, algorithm='SGD'): <NEW_LINE> <INDENT> self.for_flow(grad_optimizer, fargs=(lr, 'SGD')) <NEW_LINE> <DEDENT> def zero_grad(self): <NEW_LINE> <INDENT> self.for_flow(zero) <NEW_LINE> <DEDENT> def create_connections(self): <NEW_LINE> <INDENT> self.for_flow(conn)
神经网络 由若干起始节点和若干结束节点组成 ATTRIBUTE nodes : 神经元结点 METHOD forward(*args, **kwargs) : 前向传播 x, parameters --> y backward() : 反向传播 grad_upper_layer --> grad_this_layer, grad_params_this_layer optimize(lr, algorithm="SGD") : 应用相应的优化算法,更新参数的梯度 zero_grad() : 将所有结点的 _grad 清零,默认不清除 local_grad create_connections(): (初始化调用)将网络中所有有关联的节点创建连接
62599078ec188e330fdfa248
class Condition(object): <NEW_LINE> <INDENT> def __init__(self, checks): <NEW_LINE> <INDENT> self.checks = checks <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.checks) <NEW_LINE> <DEDENT> def evaluate(self): <NEW_LINE> <INDENT> all_conditions_met = True <NEW_LINE> for entry in self.checks: <NEW_LINE> <INDENT> component = entry['COMPONENT'] <NEW_LINE> method_name = entry['METHOD'] <NEW_LINE> val = entry['VALUE'] <NEW_LINE> current_condition = component.evaluate_condition(method_name, value=val) <NEW_LINE> all_conditions_met = all_conditions_met and current_condition <NEW_LINE> if not all_conditions_met: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return all_conditions_met <NEW_LINE> <DEDENT> def get_definition(self): <NEW_LINE> <INDENT> def_list = [] <NEW_LINE> for entry in self.checks: <NEW_LINE> <INDENT> cond_def = {'LABEL': entry['COMPONENT_LABEL'], 'METHOD': entry['METHOD'], 'VALUE': entry['VALUE']} <NEW_LINE> def_list.append(cond_def) <NEW_LINE> <DEDENT> return def_list
Keeps track of all of the necessary states of relevant components for its Event
625990782ae34c7f260aca88
class BookGenAddonProperties(bpy.types.PropertyGroup): <NEW_LINE> <INDENT> outline = BookGenShelfOutline() <NEW_LINE> def update_outline_active(self, context): <NEW_LINE> <INDENT> properties = context.scene.BookGenAddonProperties <NEW_LINE> if properties.outline_active and properties.active_shelf != -1: <NEW_LINE> <INDENT> grouping_collection = get_shelf_collection_by_index(context, properties.active_shelf) <NEW_LINE> if not grouping_collection: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> grouping_props = grouping_collection.BookGenGroupingProperties <NEW_LINE> settings = get_settings_by_name(context, grouping_props.settings_name) <NEW_LINE> if grouping_props.grouping_type == 'SHELF': <NEW_LINE> <INDENT> parameters = get_shelf_parameters(context, grouping_props.id, settings) <NEW_LINE> shelf = Shelf( grouping_collection.name, grouping_props.start, grouping_props.end, grouping_props.normal, parameters) <NEW_LINE> shelf.fill() <NEW_LINE> self.outline.enable_outline(*shelf.get_geometry(), context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parameters = get_stack_parameters(context, grouping_props.id, settings) <NEW_LINE> shelf = Stack( grouping_collection.name, grouping_props.origin, grouping_props.forward, grouping_props.normal, grouping_props.height, parameters) <NEW_LINE> shelf.fill() <NEW_LINE> self.outline.enable_outline(*shelf.get_geometry(), context) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.outline.disable_outline() <NEW_LINE> <DEDENT> <DEDENT> auto_rebuild: BoolProperty( name="auto rebuild", description="Automatically rebuild all books if settings are changed", default=True, options=set()) <NEW_LINE> active_shelf: IntProperty(name="Active grouping", update=update_outline_active, options=set()) <NEW_LINE> outline_active: BoolProperty( name="Highlight active", description="Draws an overlay to highlight the active grouping", default=False, update=update_outline_active, options=set()) <NEW_LINE> collection: PointerProperty(type=bpy.types.Collection, name="collection", description="master collection containing all groupings") <NEW_LINE> version: IntVectorProperty(name="version", description="the version of the bookgen add-on", default=(-1, -1, -1))
This store the current state of the bookGen add-on.
6259907855399d3f05627eb5
class User(models.Model): <NEW_LINE> <INDENT> phone = models.CharField(max_length=15, blank=True) <NEW_LINE> email = models.EmailField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = "mrwolfe" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.contact.__unicode__() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.operator.__unicode__() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return self.email
Mr. Wolfe user
625990783539df3088ecdc39
class PurchaseRoad(PurchaseAction): <NEW_LINE> <INDENT> name = "purchase_road" <NEW_LINE> def __init__(self, data): <NEW_LINE> <INDENT> self.__data: Dict[str, object] = data <NEW_LINE> super().__init__(PurchaseRoad.name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self) -> Dict[str, object]: <NEW_LINE> <INDENT> return self.__data <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def fromJson(data: Dict[str, Union[str, dict]]): <NEW_LINE> <INDENT> typeCheck(data, dict) <NEW_LINE> print("Player wants to purchase a road") <NEW_LINE> return PurchaseRoad(data) <NEW_LINE> <DEDENT> def getPurchaseCost(self) -> Dict[Resource, int]: <NEW_LINE> <INDENT> return { Resource.Brick: 1, Resource.Lumber: 1 }
Example js to trigger this class: ws.send(JSON.stringify({'typeName':'action', 'group':'purchase', 'name':'purchase_road'}))
6259907876e4537e8c3f0f21
class InfiniteGenDict: <NEW_LINE> <INDENT> def __init__(self, Gens): <NEW_LINE> <INDENT> self._D = dict(zip([(hasattr(X,'_name') and X._name) or repr(X) for X in Gens],Gens)) <NEW_LINE> <DEDENT> def __cmp__(self,other): <NEW_LINE> <INDENT> if isinstance(other,InfiniteGenDict): <NEW_LINE> <INDENT> return cmp(self._D,other._D) <NEW_LINE> <DEDENT> return -1 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "InfiniteGenDict defined by %s"%repr(self._D.keys()) <NEW_LINE> <DEDENT> def __getitem__(self, k): <NEW_LINE> <INDENT> if not isinstance(k,basestring): <NEW_LINE> <INDENT> raise KeyError("String expected") <NEW_LINE> <DEDENT> L = k.split('_') <NEW_LINE> try: <NEW_LINE> <INDENT> if len(L)==2: <NEW_LINE> <INDENT> return self._D[L[0]][int(L[1])] <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> raise KeyError("%s is not a variable name"%k)
A dictionary-like class that is suitable for usage in ``sage_eval``. The generators of an Infinite Polynomial Ring are not variables. Variables of an Infinite Polynomial Ring are returned by indexing a generator. The purpose of this class is to return a variable of an Infinite Polynomial Ring, given its string representation. EXAMPLES:: sage: R.<a,b> = InfinitePolynomialRing(ZZ) sage: D = R.gens_dict() # indirect doctest sage: D._D [InfiniteGenDict defined by ['a', 'b'], {'1': 1}] sage: D._D[0]['a_15'] a_15 sage: type(_) <class 'sage.rings.polynomial.infinite_polynomial_element.InfinitePolynomial_dense'> sage: sage_eval('3*a_3*b_5-1/2*a_7', D._D[0]) -1/2*a_7 + 3*a_3*b_5
62599078091ae356687065dd
class ImplicitTape(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.tensors = {} <NEW_LINE> self.variables = {} <NEW_LINE> self.gradients = [] <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self is other <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return id(self)
Global object which can watch tensors and wrap them with autograd.
625990788a349b6b43687bfd
class Revision(models.Model): <NEW_LINE> <INDENT> date_created = models.DateTimeField( db_index=True, verbose_name=_("date created"), help_text="The date and time this revision was created.", ) <NEW_LINE> user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_("user"), help_text="The user who created this revision.", ) <NEW_LINE> comment = models.TextField( blank=True, verbose_name=_("comment"), help_text="A text comment on this revision.", ) <NEW_LINE> def get_comment(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> LogEntry = apps.get_model('admin.LogEntry') <NEW_LINE> return LogEntry(change_message=self.comment).get_change_message() <NEW_LINE> <DEDENT> except LookupError: <NEW_LINE> <INDENT> return self.comment <NEW_LINE> <DEDENT> <DEDENT> def revert(self, delete=False): <NEW_LINE> <INDENT> versions_by_db = defaultdict(list) <NEW_LINE> for version in self.version_set.iterator(): <NEW_LINE> <INDENT> versions_by_db[version.db].append(version) <NEW_LINE> <DEDENT> for version_db, versions in versions_by_db.items(): <NEW_LINE> <INDENT> with transaction.atomic(using=version_db): <NEW_LINE> <INDENT> if delete: <NEW_LINE> <INDENT> old_revision = set() <NEW_LINE> for version in versions: <NEW_LINE> <INDENT> model = version._model <NEW_LINE> try: <NEW_LINE> <INDENT> old_revision.add(model._default_manager.using(version.db).get(pk=version.object_id)) <NEW_LINE> <DEDENT> except model.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> current_revision = chain.from_iterable( _follow_relations_recursive(obj) for obj in old_revision ) <NEW_LINE> collector = Collector(using=version_db) <NEW_LINE> new_objs = [item for item in current_revision if item not in old_revision] <NEW_LINE> for model, group in groupby(new_objs, type): <NEW_LINE> <INDENT> collector.collect(list(group)) <NEW_LINE> <DEDENT> collector.delete() <NEW_LINE> <DEDENT> _safe_revert(versions) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ", ".join(force_str(version) for version in self.version_set.all()) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> app_label = "reversion" <NEW_LINE> ordering = ("-pk",)
A group of related serialized versions.
6259907871ff763f4b5e914e
class UsersTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.order = app <NEW_LINE> self.client = self.order.test_client <NEW_LINE> <DEDENT> def test_update_status(self): <NEW_LINE> <INDENT> results = self.client().put('/api/v2/order/2', content_type='application/json', data=json.dumps({"status": "complete"})) <NEW_LINE> self.assertEqual(results.status_code, 200)
Users Test Case
625990787b180e01f3e49d36
class IntAttribute(Attribute): <NEW_LINE> <INDENT> def __init__(self, type_, name, long_value): <NEW_LINE> <INDENT> super(IntAttribute, self).__init__(type_, name) <NEW_LINE> self.long_value = long_value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> str_attriute = 'Name: ' + str(self.name) <NEW_LINE> str_attriute += '\nType: ' + OnepAAAAttributeType.enumval(self.type_) <NEW_LINE> str_attriute += '\nFormat: ULONG' <NEW_LINE> str_attriute += '\nValue: ' + str(self.long_value) <NEW_LINE> return str_attriute
The Attribute class for storing an integer attribute.
62599078e1aae11d1e7cf4e1
class Weakness(Effect): <NEW_LINE> <INDENT> def apply_effect(self): <NEW_LINE> <INDENT> self.stats['strength'] = max(self.stats['strength'] - 2, 1) <NEW_LINE> self.stats['endurance'] = max(self.stats['endurance'] - 2, 1)
. reduces strength, and endurance by 2
625990785166f23b2e244d7a
class Xci: <NEW_LINE> <INDENT> class CartType(enum.IntEnum): <NEW_LINE> <INDENT> GB1 = 0xfA <NEW_LINE> GB2 = 0xf8 <NEW_LINE> GB4 = 0xf0 <NEW_LINE> GB8 = 0xe0 <NEW_LINE> GB16 = 0xe1 <NEW_LINE> GB32 = 0xe2 <NEW_LINE> <DEDENT> def __init__(self, file_or_path: Union[File, str], parse: bool=False): <NEW_LINE> <INDENT> if isinstance(file_or_path, File): <NEW_LINE> <INDENT> file = file_or_path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file = File(file_or_path, "rb") <NEW_LINE> <DEDENT> self.base = fnxbinds.Xci(file.base) <NEW_LINE> self.parsed = False <NEW_LINE> if parse: <NEW_LINE> <INDENT> self.parse() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def valid(self) -> bool: <NEW_LINE> <INDENT> return self.base.is_valid() <NEW_LINE> <DEDENT> def parse(self) -> bool: <NEW_LINE> <INDENT> if not self.valid: <NEW_LINE> <INDENT> raise RuntimeError("Invalid Xci") <NEW_LINE> <DEDENT> if not self.base.parse(): <NEW_LINE> <INDENT> raise RuntimeError("Failed to parse the Xci") <NEW_LINE> <DEDENT> self._partitions = {} <NEW_LINE> for name, part in self.base.get_partitions().items(): <NEW_LINE> <INDENT> self._partitions[name] = Hfs(part) <NEW_LINE> <DEDENT> self.parsed = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def cart_type(self) -> CartType: <NEW_LINE> <INDENT> return Xci.CartType(self.base.get_cart_type()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def get_num_partitions(self): <NEW_LINE> <INDENT> if not self.parsed: <NEW_LINE> <INDENT> self.parse() <NEW_LINE> <DEDENT> return len(self._partitions) <NEW_LINE> <DEDENT> @property <NEW_LINE> def partitions(self): <NEW_LINE> <INDENT> if not self.parsed: <NEW_LINE> <INDENT> self.parse() <NEW_LINE> <DEDENT> return self._partitions <NEW_LINE> <DEDENT> def get_partition(self, name: str) -> Hfs: <NEW_LINE> <INDENT> if not self.parsed: <NEW_LINE> <INDENT> self.parse() <NEW_LINE> <DEDENT> if name not in self._partitions.keys(): <NEW_LINE> <INDENT> raise ValueError("Partition name not found") <NEW_LINE> <DEDENT> return self._partitions[name]
Class representing an Xci
62599078ad47b63b2c5a91f2
class TomlFileUserOptionReader(AbstractUserOptionReader): <NEW_LINE> <INDENT> section_name = "importlinter" <NEW_LINE> potential_config_filenames = ["pyproject.toml"] <NEW_LINE> def _read_config_filename(self, config_filename: str) -> Optional[UserOptions]: <NEW_LINE> <INDENT> if not _HAS_TOML: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> file_contents = settings.FILE_SYSTEM.read(config_filename) <NEW_LINE> data = toml.loads(file_contents) <NEW_LINE> tool_data = data.get("tool", {}) <NEW_LINE> session_options = tool_data.get("importlinter", {}) <NEW_LINE> if not session_options: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> contracts = session_options.pop("contracts", []) <NEW_LINE> self._normalize_booleans(session_options) <NEW_LINE> for contract in contracts: <NEW_LINE> <INDENT> self._normalize_booleans(contract) <NEW_LINE> <DEDENT> return UserOptions(session_options=session_options, contracts_options=contracts) <NEW_LINE> <DEDENT> def _normalize_booleans(self, data: dict) -> None: <NEW_LINE> <INDENT> for key, value in data.items(): <NEW_LINE> <INDENT> if isinstance(value, bool): <NEW_LINE> <INDENT> data[key] = str(value)
Reader that looks for and parses the contents of TOML files.
62599078aad79263cf43015c
class CNNRE(nn.Module): <NEW_LINE> <INDENT> def __init__(self, hidden_size, out_size, voc): <NEW_LINE> <INDENT> super(CNNRE, self).__init__() <NEW_LINE> pe_size = 10 <NEW_LINE> self.word_embedding = torch.nn.Embedding(voc.num_words, hidden_size) <NEW_LINE> self.pos_embedding = torch.nn.Embedding(300 * 2, pe_size) <NEW_LINE> Ci = 1 <NEW_LINE> Co = 8 <NEW_LINE> D = hidden_size + 2 * pe_size <NEW_LINE> self.conv2 = nn.Conv2d(in_channels=Ci, out_channels=Co, kernel_size=(2, D), padding=(1, 0)) <NEW_LINE> self.conv3 = nn.Conv2d(in_channels=Ci, out_channels=Co, kernel_size=(3, D), padding=(1, 0)) <NEW_LINE> self.conv5 = nn.Conv2d(in_channels=Ci, out_channels=Co, kernel_size=(5, D), padding=(2, 0)) <NEW_LINE> self.out = nn.Sequential( nn.Dropout(p=0.5), nn.Linear(Co * 3 + hidden_size, out_size) ) <NEW_LINE> <DEDENT> def conv(self, input, conv_func): <NEW_LINE> <INDENT> x = conv_func(input) <NEW_LINE> x = F.relu(x).squeeze(3) <NEW_LINE> x = F.max_pool1d(x, x.size(2)).squeeze(2) <NEW_LINE> return x <NEW_LINE> <DEDENT> def forward(self, sentences_seq, sentence_lengths, entity1_index, entity2_index, position_to_entity1_batch, position_to_entity2_batch, hidden=None): <NEW_LINE> <INDENT> embedded_sentences = self.word_embedding(sentences_seq.t()) <NEW_LINE> embedded_entity1 = self.word_embedding(entity1_index) <NEW_LINE> embedded_entity2 = self.word_embedding(entity2_index) <NEW_LINE> pe1 = self.pos_embedding(position_to_entity1_batch.t()) <NEW_LINE> pe2 = self.pos_embedding(position_to_entity2_batch.t()) <NEW_LINE> embedded_sentences = torch.cat((embedded_sentences, pe1, pe2), dim=2) <NEW_LINE> embedded_sentences = embedded_sentences.unsqueeze(1) <NEW_LINE> x2 = self.conv(embedded_sentences, self.conv2) <NEW_LINE> x3 = self.conv(embedded_sentences, self.conv3) <NEW_LINE> x5 = self.conv(embedded_sentences, self.conv5) <NEW_LINE> embedded_relation = embedded_entity1 - embedded_entity2 <NEW_LINE> out = self.out(torch.cat((x2, x3, x5, embedded_relation.squeeze(1)), dim=1)) <NEW_LINE> return out
CNN模型 1. 将index转换为embedding 2. 使用3*hidden_size的卷积核进行卷积 3. 进行max pooling 4. 与relation embedding 拼接后喂入全连接 5. 返回out
62599078a8370b77170f1d72
class Colormap(Choice): <NEW_LINE> <INDENT> _icons = {} <NEW_LINE> size = (32, 12) <NEW_LINE> def __init__(self, setn, document, parent): <NEW_LINE> <INDENT> names = sorted(ckeys(document.colormaps)) <NEW_LINE> icons = Colormap._generateIcons(document, names) <NEW_LINE> Choice.__init__(self, setn, True, names, parent, icons=icons) <NEW_LINE> self.setIconSize( qt4.QSize(*self.size) ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _generateIcons(kls, document, names): <NEW_LINE> <INDENT> size = kls.size <NEW_LINE> fakedataset = N.fromfunction(lambda x, y: y, (size[1], size[0])) <NEW_LINE> retn = [] <NEW_LINE> for name in names: <NEW_LINE> <INDENT> val = document.colormaps.get(name, None) <NEW_LINE> if val in kls._icons: <NEW_LINE> <INDENT> icon = kls._icons[val] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if val is None: <NEW_LINE> <INDENT> pixmap = qt4.QPixmap(*size) <NEW_LINE> pixmap.fill(qt4.Qt.transparent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> image = utils.applyColorMap(val, 'linear', fakedataset, 0., size[0]-1., 0) <NEW_LINE> pixmap = qt4.QPixmap.fromImage(image) <NEW_LINE> <DEDENT> icon = qt4.QIcon(pixmap) <NEW_LINE> kls._icons[val] = icon <NEW_LINE> <DEDENT> retn.append(icon) <NEW_LINE> <DEDENT> return retn
Give the user a preview of colormaps. Based on Choice to make life easier
6259907892d797404e38982d
class BountyStage(Enum): <NEW_LINE> <INDENT> Draft = 0 <NEW_LINE> Active = 1 <NEW_LINE> Dead = 2
Python enum class that matches up with the Standard Bounties BountyStage enum. Attributes: Draft (int): Bounty is a draft. Active (int): Bounty is active. Dead (int): Bounty is dead.
625990783539df3088ecdc3b
class TemporalReference(object): <NEW_LINE> <INDENT> begin = None <NEW_LINE> end = None <NEW_LINE> publication = None <NEW_LINE> revision = None <NEW_LINE> creation = None <NEW_LINE> def __init__(self, begin, end, publication, revision, creation): <NEW_LINE> <INDENT> self.begin = begin <NEW_LINE> self.end = end <NEW_LINE> self.publication = publication <NEW_LINE> self.revision = revision <NEW_LINE> self.creation = creation <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return bool(self.begin or self.end or self.publication or self.revision or self.creation)
Element 16
62599078cc0a2c111447c7a3
class LatticeApply(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "retopo.latticeapply" <NEW_LINE> bl_label = "Apply E-Lattice and delete it" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> bpy.ops.object.modifier_apply(apply_as='DATA', modifier="latticeeasytemp") <NEW_LINE> bpy.ops.object.select_pattern(pattern="LatticeEasytTemp", extend=False) <NEW_LINE> bpy.ops.object.delete(use_global=False) <NEW_LINE> return {'FINISHED'}
Apply E-Lattice and delete it
6259907856ac1b37e63039b4
class MemberList(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.b_key = "member-list" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.status = "" <NEW_LINE> self.passive = "" <NEW_LINE> self.connect_success = "" <NEW_LINE> self.member_name = "" <NEW_LINE> self.address = "" <NEW_LINE> self.sync_sequence_number = "" <NEW_LINE> self.connect_fail = "" <NEW_LINE> self.priority = "" <NEW_LINE> self.group_name = "" <NEW_LINE> self.open_out = "" <NEW_LINE> self.learn = "" <NEW_LINE> self.is_master = "" <NEW_LINE> self.open_success = "" <NEW_LINE> self.open_in = "" <NEW_LINE> self.sys_id = "" <NEW_LINE> self.update_in = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value)
This class does not support CRUD Operations please use parent. :param status: {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"} :param passive: {"type": "number", "format": "number"} :param connect_success: {"type": "number", "format": "number"} :param member_name: {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"} :param address: {"type": "string", "format": "ipv4-address"} :param sync_sequence_number: {"type": "number", "format": "number"} :param connect_fail: {"type": "number", "format": "number"} :param priority: {"type": "number", "format": "number"} :param group_name: {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"} :param open_out: {"type": "number", "format": "number"} :param learn: {"type": "number", "format": "number"} :param is_master: {"type": "number", "format": "number"} :param open_success: {"type": "number", "format": "number"} :param open_in: {"type": "number", "format": "number"} :param sys_id: {"type": "number", "format": "number"} :param update_in: {"type": "number", "format": "number"} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
6259907860cbc95b06365a3f
class DatasetSubvolumeObj(Base): <NEW_LINE> <INDENT> __tablename__ = "dataset_subvolumes" <NEW_LINE> subvolume_id =PKColumn(sqlalchemy.Integer) <NEW_LINE> dataset_id = Column( sqlalchemy.Integer, ForeignKey(DatasetObj.dataset_id), doc="The parent dataset of the volume") <NEW_LINE> volume_id=Column( sqlalchemy.Integer, ForeignKey(VolumeObj.volume_id), doc = "The volume encompassed by this subvolume") <NEW_LINE> __table_args__ = ( UniqueConstraint("dataset_id", "volume_id"), ) <NEW_LINE> dataset = relationship(DatasetObj, primaryjoin=dataset_id==DatasetObj.dataset_id) <NEW_LINE> volume = relationship(VolumeObj, primaryjoin=volume_id==VolumeObj.volume_id)
each row is a subvolume within a dataset Note that a dataset subvolume might encompass the entire volume of the dataset.
6259907876e4537e8c3f0f23
class QLearningAgent(ReinforcementAgent): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> self.q_values = util.Counter() <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> if not self.q_values[(state, action)]: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> return self.q_values[(state, action)] <NEW_LINE> <DEDENT> def computeValueFromQValues(self, state): <NEW_LINE> <INDENT> actions = self.getLegalActions(state) <NEW_LINE> if not actions: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> return max([self.getQValue(state, i) for i in actions]) <NEW_LINE> <DEDENT> def computeActionFromQValues(self, state): <NEW_LINE> <INDENT> actions = self.getLegalActions(state) <NEW_LINE> if not actions: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> bests = [i for i in actions if self.getQValue(state, i) == self.getValue(state)] <NEW_LINE> return random.choice(bests) <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> action = None <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> if not legalActions: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if util.flipCoin(self.epsilon): <NEW_LINE> <INDENT> action = random.choice(legalActions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self.getPolicy(state) <NEW_LINE> <DEDENT> return action <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> old_value = self.getQValue(state, action) <NEW_LINE> learned_value = reward + self.discount * self.getValue(nextState) <NEW_LINE> self.q_values[(state, action)] = old_value + self.alpha * (learned_value - old_value) <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromQValues(state) <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.computeValueFromQValues(state)
Q-Learning Agent Functions you should fill in: - computeValueFromQValues - computeActionFromQValues - getQValue - getAction - update Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.discount (discount rate) Functions you should use - self.getLegalActions(state) which returns legal actions for a state
62599078d486a94d0ba2d95c
class InstitutePricing(models.Model): <NEW_LINE> <INDENT> institution = models.OneToOneField(Institution, models.PROTECT, verbose_name=_('Institution')) <NEW_LINE> discount_rate = models.DecimalField(_('Discount rate'), max_digits=6, decimal_places=2, null=True, blank=True) <NEW_LINE> use_alt_pricing = models.BooleanField(_('Alt. Pricing'), default=False, help_text=_('Use alternative price')) <NEW_LINE> open_account = models.BooleanField(_('Open account'), default=False, help_text=_('This institution makes mountly payments')) <NEW_LINE> timestamp = models.DateTimeField(_('Definition date'), editable=False, auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('Institue Pricing') <NEW_LINE> verbose_name_plural = _('Institue Pricings') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s %s" % (self.institution.name, self.discount_rate)
base price discounts per institute
6259907816aa5153ce401e7f
class User(dict): <NEW_LINE> <INDENT> def __init__(self, dict=None): <NEW_LINE> <INDENT> for key in ['username', 'name', 'passphrase', 'email']: <NEW_LINE> <INDENT> self[key] = '' <NEW_LINE> <DEDENT> for key in ['groups']: <NEW_LINE> <INDENT> self[key] = [] <NEW_LINE> <DEDENT> if dict: <NEW_LINE> <INDENT> for key in dict: <NEW_LINE> <INDENT> self[key] = dict[key] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return None
Every user must have keys for a username, name, passphrase (this is a md5 hash of the password), groups, and an email address. They can be blank or None, but the keys must exist.
625990785fdd1c0f98e5f922
class MechMode: <NEW_LINE> <INDENT> def __init__(self, confDict, mechMode_entry): <NEW_LINE> <INDENT> self.name = confDict[mechMode_entry]['name'] <NEW_LINE> self.type = confDict[mechMode_entry]['type'] <NEW_LINE> self.f0 = readentry(confDict,confDict[mechMode_entry]["f0"]) <NEW_LINE> self.Q = readentry(confDict,confDict[mechMode_entry]["Q"]) <NEW_LINE> self.full_scale = readentry(confDict,confDict[mechMode_entry]["full_scale"]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ("\n--MechMode Object--\n" + "name: " + self.name + "\n" + "type: " + self.type + "\n" + "f0: " + str(self.f0) + "\n" + "Q: " + str(self.Q) + "\n" + "full_scale: " + str(self.full_scale) + "\n") <NEW_LINE> <DEDENT> def Get_C_Pointer(self): <NEW_LINE> <INDENT> import accelerator as acc <NEW_LINE> f0 = self.f0['value'] <NEW_LINE> Q = self.Q['value'] <NEW_LINE> k = 1.0 <NEW_LINE> mechMode = acc.MechMode_Allocate_New(f0, Q, k, Tstep_global); <NEW_LINE> self.C_Pointer = mechMode <NEW_LINE> return mechMode
Contains parameters specific to a mechanical mode. Information concerning couplings with electrical modes and Piezos is contained in ElecMode and Piezo objects respectively.
6259907832920d7e50bc79ed
class RoomsList(ListAPIView): <NEW_LINE> <INDENT> queryset = Room.objects.all() <NEW_LINE> serializer_class = RoomSerializer <NEW_LINE> def get(self, *args, **kwargs): <NEW_LINE> <INDENT> get_only_free_rooms = Room.objects.filter(room_status='Free').values() <NEW_LINE> return Response( get_only_free_rooms )
This serializer gives a list of available rooms for booking.
625990781b99ca4002290208
class MissingContainers(Exception): <NEW_LINE> <INDENT> def __init__(self, container_name): <NEW_LINE> <INDENT> self.message = f"No instance of {container_name} is running!" <NEW_LINE> super().__init__(self.message)
Exception raised when not one containers of expected type are running. Inspired from: https://www.programiz.com/python-programming/user-defined-exception :param container_name: Name of container image. message -- explanation of the error
62599078fff4ab517ebcf1bc
@profiler.trace_cls("rpc") <NEW_LINE> class Handler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Handler, self).__init__() <NEW_LINE> <DEDENT> def sign_certificate(self, context, cluster, certificate): <NEW_LINE> <INDENT> LOG.debug("Creating self signed x509 certificate") <NEW_LINE> signed_cert = cert_manager.sign_node_certificate(cluster, certificate.csr, context=context) <NEW_LINE> certificate.pem = signed_cert <NEW_LINE> return certificate <NEW_LINE> <DEDENT> def get_ca_certificate(self, context, cluster): <NEW_LINE> <INDENT> ca_cert = cert_manager.get_cluster_ca_certificate(cluster, context=context) <NEW_LINE> certificate = objects.Certificate.from_object_cluster(cluster) <NEW_LINE> certificate.pem = ca_cert.get_certificate() <NEW_LINE> return certificate <NEW_LINE> <DEDENT> def rotate_ca_certificate(self, context, cluster): <NEW_LINE> <INDENT> cluster_driver = driver.Driver.get_driver_for_cluster(context, cluster) <NEW_LINE> cluster_driver.rotate_ca_certificate(context, cluster)
Magnum CA RPC handler. These are the backend operations. They are executed by the backend service. API calls via AMQP (within the ReST API) trigger the handlers to be called.
62599078a8370b77170f1d73
class SaleOrder(models.Model): <NEW_LINE> <INDENT> _inherit = 'sale.order' <NEW_LINE> commitment_date = fields.Datetime(compute='_compute_commitment_date', string='Commitment Date', store=True, help="Date by which the products are sure to be delivered. This is " "a date that you can promise to the customer, based on the " "Product Lead Times.") <NEW_LINE> requested_date = fields.Datetime('Requested Date', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=False, help="Date by which the customer has requested the items to be " "delivered.\n" "When this Order gets confirmed, the Delivery Order's " "expected date will be computed based on this date and the " "Company's Security Delay.\n" "Leave this field empty if you want the Delivery Order to be " "processed as soon as possible. In that case the expected " "date will be computed using the default method: based on " "the Product Lead Times and the Company's Security Delay.") <NEW_LINE> effective_date = fields.Date(compute='_compute_picking_ids', string='Effective Date', store=True, help="Date on which the first Delivery Order was created.") <NEW_LINE> @api.depends('date_order', 'order_line.customer_lead') <NEW_LINE> def _compute_commitment_date(self): <NEW_LINE> <INDENT> for order in self: <NEW_LINE> <INDENT> dates_list = [] <NEW_LINE> order_datetime = fields.Datetime.from_string(order.date_order) <NEW_LINE> for line in order.order_line.filtered(lambda x: x.state != 'cancel' and not x._is_delivery()): <NEW_LINE> <INDENT> dt = order_datetime + timedelta(days=line.customer_lead or 0.0) <NEW_LINE> dates_list.append(dt) <NEW_LINE> <DEDENT> if dates_list: <NEW_LINE> <INDENT> commit_date = min(dates_list) if order.picking_policy == 'direct' else max(dates_list) <NEW_LINE> order.commitment_date = fields.Datetime.to_string(commit_date) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _compute_picking_ids(self): <NEW_LINE> <INDENT> super(SaleOrder, self)._compute_picking_ids() <NEW_LINE> for order in self: <NEW_LINE> <INDENT> dates_list = [] <NEW_LINE> for pick in order.picking_ids: <NEW_LINE> <INDENT> dates_list.append(fields.Datetime.from_string(pick.date)) <NEW_LINE> <DEDENT> if dates_list: <NEW_LINE> <INDENT> order.effective_date = fields.Datetime.to_string(min(dates_list)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @api.onchange('requested_date') <NEW_LINE> def onchange_requested_date(self): <NEW_LINE> <INDENT> if (self.requested_date and self.commitment_date and self.requested_date < self.commitment_date): <NEW_LINE> <INDENT> return {'warning': { 'title': _('Requested date is too soon!'), 'message': _("The date requested by the customer is " "sooner than the commitment date. You may be " "unable to honor the customer's request.") } }
Add several date fields to Sales Orders, computed or user-entered
6259907892d797404e38982e
class l1MHT: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def make_obj(tree): <NEW_LINE> <INDENT> _pt = getattr(tree, "l1MHT_pt", None) <NEW_LINE> _phi = getattr(tree, "l1MHT_phi", None) <NEW_LINE> return l1MHT(_pt, _phi) <NEW_LINE> <DEDENT> def __init__(self, pt,phi): <NEW_LINE> <INDENT> self.pt = pt <NEW_LINE> self.phi = phi <NEW_LINE> pass
625990788e7ae83300eeaa32
class PredicateRule(object): <NEW_LINE> <INDENT> __slots__ = ("predicate", "message_template") <NEW_LINE> def __init__(self, predicate, message_template=None): <NEW_LINE> <INDENT> self.predicate = predicate <NEW_LINE> self.message_template = message_template or _( "Required to satisfy validation predicate condition." ) <NEW_LINE> <DEDENT> def validate(self, value, name, model, result, gettext): <NEW_LINE> <INDENT> if not self.predicate(model): <NEW_LINE> <INDENT> result.append(gettext(self.message_template)) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True
Fails if predicate return False. Predicate is any callable of the following contract:: def predicate(model): return True
625990782c8b7c6e89bd5190
class ReportItemForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = DailyReportItem <NEW_LINE> exclude = ('daily_report',) <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('label_suffix', '') <NEW_LINE> super(ReportItemForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['self_rating'].widget.attrs={'class': 'self_rating_class form-control'} <NEW_LINE> self.fields['duration_in_hours'].widget.attrs={'class': 'class_duration_in_hours form-control'} <NEW_LINE> self.fields['work_done'].widget.attrs={'class':'form-control', 'cols':20, 'rows':1} <NEW_LINE> self.fields['struggle'].widget.attrs={'class':'form-control', 'cols':20, 'rows':1} <NEW_LINE> self.fields['tags'].widget.attrs={'class':'form-control', 'cols':20, 'rows':1}
Form class for adding ReportItem for a report as ther can be multiple work done by single person. He/she can add as many form entity required.
6259907867a9b606de547778
class CircleMarkerDetectionTask(TaskInterface): <NEW_LINE> <INDENT> zmq_ctx = None <NEW_LINE> capture_source_path = None <NEW_LINE> notify_all = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._process_pipe = None <NEW_LINE> self._progress = 0.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def progress(self): <NEW_LINE> <INDENT> return self._progress <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> super().start() <NEW_LINE> self._process_pipe = zmq_tools.Msg_Pair_Server(self.zmq_ctx) <NEW_LINE> self._request_start_of_detection(self._process_pipe.url) <NEW_LINE> <DEDENT> def _request_start_of_detection(self, pair_url): <NEW_LINE> <INDENT> source_path = self.capture_source_path <NEW_LINE> self.notify_all( { "subject": "circle_detector_process.should_start", "source_path": source_path, "pair_url": pair_url, } ) <NEW_LINE> <DEDENT> def cancel_gracefully(self): <NEW_LINE> <INDENT> super().cancel_gracefully() <NEW_LINE> self._terminate_background_detection() <NEW_LINE> self.on_canceled_or_killed() <NEW_LINE> <DEDENT> def kill(self, grace_period): <NEW_LINE> <INDENT> super().kill(grace_period) <NEW_LINE> self._terminate_background_detection() <NEW_LINE> self.on_canceled_or_killed() <NEW_LINE> <DEDENT> def _terminate_background_detection(self): <NEW_LINE> <INDENT> self._process_pipe.send({"topic": "terminate"}) <NEW_LINE> self._process_pipe.socket.close() <NEW_LINE> self._process_pipe = None <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> super().update() <NEW_LINE> try: <NEW_LINE> <INDENT> self._receive_detections() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.on_exception(e) <NEW_LINE> <DEDENT> <DEDENT> def _receive_detections(self): <NEW_LINE> <INDENT> while self._process_pipe.new_data: <NEW_LINE> <INDENT> topic, msg = self._process_pipe.recv() <NEW_LINE> if topic == "progress": <NEW_LINE> <INDENT> progress_detection_pairs = msg.get("data", []) <NEW_LINE> progress, detections = zip(*progress_detection_pairs) <NEW_LINE> self._progress = progress[-1] / 100.0 <NEW_LINE> detections_without_None_items = (d for d in detections if d) <NEW_LINE> for detection in detections_without_None_items: <NEW_LINE> <INDENT> self._yield_detection(detection) <NEW_LINE> <DEDENT> <DEDENT> elif topic == "finished": <NEW_LINE> <INDENT> self.on_completed(None) <NEW_LINE> return <NEW_LINE> <DEDENT> elif topic == "exception": <NEW_LINE> <INDENT> logger.warning( "Calibration marker detection raised exception:\n{}".format( msg["reason"] ) ) <NEW_LINE> logger.info("Marker detection was interrupted") <NEW_LINE> logger.debug("Reason: {}".format(msg.get("reason", "n/a"))) <NEW_LINE> self.on_canceled_or_killed() <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _yield_detection(self, detection): <NEW_LINE> <INDENT> screen_pos = tuple(detection["screen_pos"]) <NEW_LINE> frame_index = detection["index"] <NEW_LINE> timestamp = detection["timestamp"] <NEW_LINE> reference_location = model.ReferenceLocation(screen_pos, frame_index, timestamp) <NEW_LINE> self.on_yield(reference_location)
The actual marker detection is in launchabeles.marker_detector because OpenCV needs a new and clean process and does not work with forked processes. This task requests the start of the launchable via a notification and retrieves results from the background. It does _not_ run in background itself, but does its work in the update() method that is executed in the main process.
62599078a05bb46b3848bdfd
class ConsultRecord(models.Model): <NEW_LINE> <INDENT> customer = models.ForeignKey('Customer', verbose_name="所咨询客户",on_delete=models.CASCADE) <NEW_LINE> note = models.TextField(verbose_name="跟进内容...") <NEW_LINE> status = models.CharField("跟进状态", max_length=8, choices=seek_status_choices, help_text="选择客户此时的状态") <NEW_LINE> consultant = models.ForeignKey("UserProfile", verbose_name="跟进人", related_name='records',on_delete=models.CASCADE) <NEW_LINE> date = models.DateTimeField("跟进日期", auto_now_add=True) <NEW_LINE> delete_status = models.BooleanField(verbose_name='删除状态', default=False)
跟进记录表
62599078627d3e7fe0e0882e
class TestMultiomeSummary(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.wd = tempfile.mkdtemp(suffix='TestMultiomeSummary') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if REMOVE_TEST_OUTPUTS: <NEW_LINE> <INDENT> shutil.rmtree(self.wd) <NEW_LINE> <DEDENT> <DEDENT> def test_atac_summary_multiome_arc_1_0_0(self): <NEW_LINE> <INDENT> summary_csv = os.path.join(self.wd,"summary.csv") <NEW_LINE> with open(summary_csv,'wt') as fp: <NEW_LINE> <INDENT> fp.write(MULTIOME_SUMMARY) <NEW_LINE> <DEDENT> s = MultiomeSummary(summary_csv) <NEW_LINE> self.assertEqual(s.estimated_number_of_cells,744) <NEW_LINE> self.assertEqual( s.atac_median_high_quality_fragments_per_cell,8079) <NEW_LINE> self.assertEqual(s.gex_median_genes_per_cell,1490) <NEW_LINE> <DEDENT> def test_atac_summary_multiome_arc_2_0_0(self): <NEW_LINE> <INDENT> summary_csv = os.path.join(self.wd,"summary.csv") <NEW_LINE> with open(summary_csv,'wt') as fp: <NEW_LINE> <INDENT> fp.write(MULTIOME_SUMMARY_2_0_0) <NEW_LINE> <DEDENT> s = MultiomeSummary(summary_csv) <NEW_LINE> self.assertEqual(s.estimated_number_of_cells,785) <NEW_LINE> self.assertEqual( s.atac_median_high_quality_fragments_per_cell,9.0) <NEW_LINE> self.assertEqual(s.gex_median_genes_per_cell,15.0)
Tests for the 'MultiomeSummary' class
62599078a8370b77170f1d74
class AddItemImageView(RESTDispatch): <NEW_LINE> <INDENT> @user_auth_required <NEW_LINE> @admin_auth_required <NEW_LINE> def POST(self, request, item_id): <NEW_LINE> <INDENT> item = Item.objects.get(pk=item_id) <NEW_LINE> if "image" not in request.FILES: <NEW_LINE> <INDENT> raise RESTException("No image", 400) <NEW_LINE> <DEDENT> args = { "upload_application": request.META.get( "SS_OAUTH_CONSUMER_NAME", "" ), "upload_user": request.META.get("SS_OAUTH_USER", ""), "description": request.POST.get("description", ""), "display_index": request.POST.get("display_index"), "image": request.FILES["image"], } <NEW_LINE> if args["display_index"] is None: <NEW_LINE> <INDENT> indices = [img.display_index for img in item.itemimage_set.all()] <NEW_LINE> if indices: <NEW_LINE> <INDENT> args["display_index"] = max(indices) + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args["display_index"] = 0 <NEW_LINE> <DEDENT> <DEDENT> image = item.itemimage_set.create(**args) <NEW_LINE> item.spot.save() <NEW_LINE> response = HttpResponse(status=201) <NEW_LINE> response["Location"] = image.rest_url() <NEW_LINE> return response
Saves a ItemImage for a particular Item on POST to /api/v1/item/<item id>/image.
62599078adb09d7d5dc0bf10
class CifcodcheckParser(CiffilterParser): <NEW_LINE> <INDENT> def _check_calc_compatibility(self,calc): <NEW_LINE> <INDENT> from aiida.common.exceptions import ParsingError <NEW_LINE> if not isinstance(calc,CifcodcheckCalculation): <NEW_LINE> <INDENT> raise ParsingError("Input calc must be a CifcodcheckCalculation") <NEW_LINE> <DEDENT> <DEDENT> def _get_output_nodes(self, output_path, error_path): <NEW_LINE> <INDENT> import re <NEW_LINE> messages = [] <NEW_LINE> if output_path is not None: <NEW_LINE> <INDENT> with open(output_path) as f: <NEW_LINE> <INDENT> content = f.readlines() <NEW_LINE> <DEDENT> lines = [x.strip('\n') for x in content] <NEW_LINE> if re.search( ' OK$', lines[0] ) is not None: <NEW_LINE> <INDENT> lines.pop(0) <NEW_LINE> <DEDENT> messages.extend(lines) <NEW_LINE> <DEDENT> if error_path is not None: <NEW_LINE> <INDENT> with open(error_path) as f: <NEW_LINE> <INDENT> content = f.readlines() <NEW_LINE> <DEDENT> lines = [x.strip('\n') for x in content] <NEW_LINE> messages.extend(lines) <NEW_LINE> <DEDENT> output_nodes = [] <NEW_LINE> output_nodes.append(('messages', ParameterData(dict={'output_messages': messages}))) <NEW_LINE> return output_nodes
Specific parser for the output of cif_cod_check script.
6259907871ff763f4b5e9152
@final <NEW_LINE> @dataclass(frozen=True, slots=True) <NEW_LINE> class GetOrganizations(object): <NEW_LINE> <INDENT> _brreg_base_url: str <NEW_LINE> _get: Callable <NEW_LINE> _entities = 'enheter/' <NEW_LINE> _sub_entities = 'underenheter/' <NEW_LINE> _log = logging.getLogger('api.brreg.GetOrganizations') <NEW_LINE> def __call__( self, search_criteria: dict, timeout: int = 20, ) -> ResultE[list]: <NEW_LINE> <INDENT> return flow( self._get( self._brreg_base_url + self._entities, url_params=search_criteria, timeout=timeout, ), alt(tap(self._log.warning)), bind(self._get_json), ) <NEW_LINE> <DEDENT> @safe <NEW_LINE> def _get_json(self, response: requests.Response) -> list: <NEW_LINE> <INDENT> return response.json()
Get a list of organizations with the given criteria.
6259907897e22403b383c8a8
class radialBasisFunctions(object): <NEW_LINE> <INDENT> def __init__(self, stateSpace, meanList, varianceList): <NEW_LINE> <INDENT> self.stateSpace=self.stateSpaceGen(stateSpace) <NEW_LINE> self.meanList=meanList <NEW_LINE> self.varianceList=varianceList <NEW_LINE> <DEDENT> def stateSpaceGen(self,stateSpace): <NEW_LINE> <INDENT> return np.identity(len(stateSpace)) <NEW_LINE> <DEDENT> def phiGen(self): <NEW_LINE> <INDENT> Phi=[[0 for x in range(len(self.meanList))] for y in range(len(self.stateSpace))] <NEW_LINE> for i in range(len(self.stateSpace)): <NEW_LINE> <INDENT> Phi[i]=self.getBasis(self.stateSpace[i]) <NEW_LINE> <DEDENT> Phi=np.reshape(Phi, (len(self.stateSpace),len(self.meanList))) <NEW_LINE> return Phi <NEW_LINE> <DEDENT> def getBasis(self,s): <NEW_LINE> <INDENT> basisVec=np.zeros(len(self.meanList)) <NEW_LINE> for i in range(len(self.meanList)): <NEW_LINE> <INDENT> basisVec[i]=self.gaussianBasis(s,self.meanList[i],self.varianceList[i]) <NEW_LINE> <DEDENT> return basisVec <NEW_LINE> <DEDENT> def gaussianBasis(self, s, mean, variance): <NEW_LINE> <INDENT> return math.exp((-np.linalg.norm(s-mean)**2)/(2*(variance**2)))
classdocs
6259907866673b3332c31da5
class ParcelProtectionQuoteRequestShipmentInfoParcelInfo(object): <NEW_LINE> <INDENT> openapi_types = { 'commodity_list': 'list[ParcelProtectionQuoteRequestShipmentInfoParcelInfoCommodityList]' } <NEW_LINE> attribute_map = { 'commodity_list': 'commodityList' } <NEW_LINE> def __init__(self, commodity_list=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._commodity_list = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.commodity_list = commodity_list <NEW_LINE> <DEDENT> @property <NEW_LINE> def commodity_list(self): <NEW_LINE> <INDENT> return self._commodity_list <NEW_LINE> <DEDENT> @commodity_list.setter <NEW_LINE> def commodity_list(self, commodity_list): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and commodity_list is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `commodity_list`, must not be `None`") <NEW_LINE> <DEDENT> self._commodity_list = commodity_list <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_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, ParcelProtectionQuoteRequestShipmentInfoParcelInfo): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ParcelProtectionQuoteRequestShipmentInfoParcelInfo): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
6259907899cbb53fe683288c
class EditCommentHandler(BlogHandler): <NEW_LINE> <INDENT> @post_exists <NEW_LINE> def post(self, post_id, post): <NEW_LINE> <INDENT> if not self.user: <NEW_LINE> <INDENT> return self.redirect("/signin") <NEW_LINE> <DEDENT> comment_data = self.request.get("comment") <NEW_LINE> comment_id = self.request.get("comment-id") <NEW_LINE> if comment_data and comment_id and self.user: <NEW_LINE> <INDENT> key = db.Key.from_path("PostComment", int( comment_id), parent=blog_key()) <NEW_LINE> comment = db.get(key) <NEW_LINE> if comment and comment.author == self.user.name: <NEW_LINE> <INDENT> comment.comment = comment_data <NEW_LINE> comment.put() <NEW_LINE> <DEDENT> <DEDENT> return self.redirect("/postdetail/%s" % str(post.key().id()))
Edit comment to post request handler If we receive request for a post that doesn't exist we would return 404
6259907801c39578d7f14408
class OWindow(Obit.OWindow): <NEW_LINE> <INDENT> def __init__(self) : <NEW_LINE> <INDENT> super(OWindow, self).__init__() <NEW_LINE> Obit.CreateOWindow (self.this) <NEW_LINE> <DEDENT> def __del__(self, DeleteOWindow=_Obit.DeleteOWindow): <NEW_LINE> <INDENT> if _Obit!=None: <NEW_LINE> <INDENT> DeleteOWindow(self.this) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self,name,value): <NEW_LINE> <INDENT> if name == "me" : <NEW_LINE> <INDENT> Obit.OWindow_Set_me(self.this,value) <NEW_LINE> return <NEW_LINE> <DEDENT> self.__dict__[name] = value <NEW_LINE> <DEDENT> def __getattr__(self,name): <NEW_LINE> <INDENT> if name == "me" : <NEW_LINE> <INDENT> return Obit.OWindow_Get_me(self.this) <NEW_LINE> <DEDENT> raise AttributeError(str(name)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<C OWindow instance>"
Python Obit Image descriptor class This contains information about the Tables associated with an image or dataset Image Members with python interfaces: List - (virtual) Python list of table names and numbers
62599078e1aae11d1e7cf4e3
class RedirectMiddleware(BaseRedirectMiddleware): <NEW_LINE> <INDENT> def process_response(self, request, response, spider): <NEW_LINE> <INDENT> if (request.meta.get('dont_redirect', False) or response.status in getattr(spider, 'handle_httpstatus_list', []) or response.status in request.meta.get('handle_httpstatus_list', []) or request.meta.get('handle_httpstatus_all', False)): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> allowed_status = (301, 302, 303, 307) <NEW_LINE> if 'Location' not in response.headers or response.status not in allowed_status: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> location = safe_url_string(response.headers['location']) <NEW_LINE> redirected_url = urljoin(request.url, location) <NEW_LINE> if response.status in (301, 307) or request.method == 'HEAD': <NEW_LINE> <INDENT> redirected = request.replace(url=redirected_url) <NEW_LINE> return self._redirect(redirected, request, spider, response.status) <NEW_LINE> <DEDENT> redirected = self._redirect_request_using_get(request, redirected_url) <NEW_LINE> return self._redirect(redirected, request, spider, response.status)
Handle redirection of requests based on response status and meta-refresh html tag
6259907856ac1b37e63039b6
class ActiveProductManager(models.Manager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> return super(ActiveProductManager, self).get_query_set().filter(is_active=True)
Manager class to return only those products where each instance is active
62599078460517430c432d2d
class MyThread(Thread): <NEW_LINE> <INDENT> def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None): <NEW_LINE> <INDENT> Thread.__init__(self, group, target, name, args, kwargs) <NEW_LINE> self._return = None <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if self._target is not None: <NEW_LINE> <INDENT> self._return = self._target(*self._args, **self._kwargs) <NEW_LINE> <DEDENT> <DEDENT> def join(self, *args): <NEW_LINE> <INDENT> Thread.join(self, *args) <NEW_LINE> return self._return
defines the threads for multi threaded file search.
6259907867a9b606de547779
class AllSiteSearch(View): <NEW_LINE> <INDENT> pass
分apps 展示内容 提供连接
625990782ae34c7f260aca8e
class AuthAuditRemote(RemoteModel): <NEW_LINE> <INDENT> properties = ("id", "datasource_id", "date_time", "client_ip", "operation", "created_at", "updated_at", "record_id", "message", "field_changes", "user_name", "event_type", "DeviceID", )
The user audit log information defined within NetMRI. | ``id:`` The internal NetMRI identifier of this user audit log information. | ``attribute type:`` number | ``datasource_id:`` The internal NetMRI identifier for the collector NetMRI that collected this data record. | ``attribute type:`` number | ``date_time:`` The date and time this record was collected or calculated. | ``attribute type:`` datetime | ``client_ip:`` The IP address of the client defined within NetMRI. | ``attribute type:`` string | ``operation:`` The operation done is defined in NetMRI. | ``attribute type:`` string | ``created_at:`` The date and time the record was initially created in NetMRI. | ``attribute type:`` datetime | ``updated_at:`` The date and time the record was last modified in NetMRI. | ``attribute type:`` datetime | ``record_id:`` The internal NetMRI identifier of the record. | ``attribute type:`` number | ``message:`` The audit log entry is defined as a message within NetMRI. | ``attribute type:`` string | ``field_changes:`` It describes the audit field changes in NetMRI. | ``attribute type:`` string | ``user_name:`` The username portion of the User Audit Log. | ``attribute type:`` string | ``event_type:`` The type of events occurs in the User Audit section. | ``attribute type:`` string | ``DeviceID:`` The internal NetMRI identifier for the device from which audit log information entry was collected. | ``attribute type:`` number
625990784c3428357761bc60
class ApiKeys(handler_utils.AdminOnlyHandler): <NEW_LINE> <INDENT> @xsrf_utils.RequireToken <NEW_LINE> @handler_utils.RequirePermission(constants.PERMISSIONS.CHANGE_SETTINGS) <NEW_LINE> def post(self, key_name): <NEW_LINE> <INDENT> value = self.request.get('value', None) <NEW_LINE> if value is None: <NEW_LINE> <INDENT> self.abort(httplib.BAD_REQUEST, explanation='No value provided') <NEW_LINE> <DEDENT> if key_name == 'virustotal': <NEW_LINE> <INDENT> singleton.VirusTotalApiAuth.SetInstance(api_key=value) <NEW_LINE> <DEDENT> elif key_name == 'bit9': <NEW_LINE> <INDENT> singleton.Bit9ApiAuth.SetInstance(api_key=value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.abort(httplib.BAD_REQUEST, explanation='Invalid key name')
Set/update the value of an API key.
62599078be7bc26dc9252b29
class Logout(View): <NEW_LINE> <INDENT> @method_decorator(login_required) <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> logout(request) <NEW_LINE> return redirect('top:index')
ログアウト処理を行うクラス
6259907863b5f9789fe86b0e
class PolicyType( str, MultiValueEnum ): <NEW_LINE> <INDENT> OAUTH_AUTHORIZATION_POLICY = "OAUTH_AUTHORIZATION_POLICY", "oauth_authorization_policy" <NEW_LINE> OKTA_SIGN_ON = "OKTA_SIGN_ON", "okta_sign_on" <NEW_LINE> PASSWORD = "PASSWORD", "password" <NEW_LINE> IDP_DISCOVERY = "IDP_DISCOVERY", "idp_discovery" <NEW_LINE> PROFILE_ENROLLMENT = "PROFILE_ENROLLMENT", "profile_enrollment" <NEW_LINE> ACCESS_POLICY = "ACCESS_POLICY", "access_policy"
An enumeration class for PolicyType.
625990787047854f46340d63
class MathModf(MathFunctionBase): <NEW_LINE> <INDENT> pass
modf(x) Return the fractional and integer parts of x. Both results carry the sign of x and are floats.
62599078796e427e53850123
class LogFile(object): <NEW_LINE> <INDENT> def __init__(self, name, append=False, developer=False, flush=True): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.append = append <NEW_LINE> self.developer = developer <NEW_LINE> self.flush = flush <NEW_LINE> self.file = None <NEW_LINE> self.softspace = 0 <NEW_LINE> self.newlines = None <NEW_LINE> self.raw_write = False <NEW_LINE> if renpy.ios: <NEW_LINE> <INDENT> self.file = real_stdout <NEW_LINE> <DEDENT> <DEDENT> def open(self): <NEW_LINE> <INDENT> if self.file: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.file is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if renpy.macapp: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.developer and not renpy.config.developer: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not renpy.config.log_enable: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> base = os.environ.get("RENPY_LOG_BASE", renpy.config.logdir or renpy.config.basedir) <NEW_LINE> fn = os.path.join(base, self.name + ".txt") <NEW_LINE> altfn = os.path.join(tempfile.gettempdir(), "renpy-" + self.name + ".txt") <NEW_LINE> if renpy.android: <NEW_LINE> <INDENT> print("Logging to", fn) <NEW_LINE> <DEDENT> if self.append: <NEW_LINE> <INDENT> mode = "a" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mode = "w" <NEW_LINE> <DEDENT> if renpy.config.log_to_stdout: <NEW_LINE> <INDENT> self.file = real_stdout <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.file = codecs.open(fn, mode, "utf-8") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.file = codecs.open(altfn, mode, "utf-8") <NEW_LINE> <DEDENT> <DEDENT> if self.append: <NEW_LINE> <INDENT> self.write('') <NEW_LINE> self.write('=' * 78) <NEW_LINE> self.write('') <NEW_LINE> <DEDENT> self.write("%s", time.ctime()) <NEW_LINE> try: <NEW_LINE> <INDENT> self.write("%s", platform.platform()) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.write("Unknown platform.") <NEW_LINE> <DEDENT> self.write("%s", renpy.version) <NEW_LINE> self.write("%s %s", renpy.config.name, renpy.config.version) <NEW_LINE> self.write("") <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.file = False <NEW_LINE> traceback.print_exc(file=real_stderr) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def write(self, s, *args): <NEW_LINE> <INDENT> if self.open(): <NEW_LINE> <INDENT> if not self.raw_write: <NEW_LINE> <INDENT> s = s % args <NEW_LINE> s += "\n" <NEW_LINE> <DEDENT> if not isinstance(s, unicode): <NEW_LINE> <INDENT> s = s.decode("latin-1") <NEW_LINE> <DEDENT> s = s.replace("\n", "\r\n") <NEW_LINE> self.file.write(s) <NEW_LINE> if self.flush: <NEW_LINE> <INDENT> self.file.flush() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def exception(self): <NEW_LINE> <INDENT> self.raw_write = True <NEW_LINE> traceback.print_exc(None, self) <NEW_LINE> self.raw_write = False
This manages one of our logfiles.
625990783539df3088ecdc41
class VersionedDependency(object): <NEW_LINE> <INDENT> def __init__(self, name, version=None, min_version=None, max_version=None): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> if version is not None: <NEW_LINE> <INDENT> self._min_version = version <NEW_LINE> self._max_version = version <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._min_version = min_version <NEW_LINE> self._max_version = max_version <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def min_version(self): <NEW_LINE> <INDENT> return self._min_version <NEW_LINE> <DEDENT> @min_version.setter <NEW_LINE> def min_version(self, min_version): <NEW_LINE> <INDENT> self._min_version = min_version <NEW_LINE> <DEDENT> def has_min_version(self): <NEW_LINE> <INDENT> return self._min_version != None <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_version(self): <NEW_LINE> <INDENT> return self._max_version <NEW_LINE> <DEDENT> @max_version.setter <NEW_LINE> def max_version(self, max_version): <NEW_LINE> <INDENT> self._max_version = max_version <NEW_LINE> <DEDENT> def has_max_version(self): <NEW_LINE> <INDENT> return self._max_version != None <NEW_LINE> <DEDENT> def has_versions(self): <NEW_LINE> <INDENT> return (self.has_min_version()) or (self.has_max_version())
DependencyVersion specifies the versions
625990782c8b7c6e89bd5194
class UrlPackage: <NEW_LINE> <INDENT> def __init__(self, url): <NEW_LINE> <INDENT> if ':' in url: <NEW_LINE> <INDENT> self.url = url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.url = posixpath.join('git+git://github.com', url) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def installAs(self): <NEW_LINE> <INDENT> return self.url <NEW_LINE> <DEDENT> def forRequirements(self, versions): <NEW_LINE> <INDENT> return self.url
Represents a package specified as a Url
625990782c8b7c6e89bd5193
class UpdateNotificationReadView(APIView): <NEW_LINE> <INDENT> authentication_classes = (authentication.TokenAuthentication,) <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> parser_classes = (JSONParser,) <NEW_LINE> lookup_url_kwarg = "user_id" <NEW_LINE> def get(self, request, user_id): <NEW_LINE> <INDENT> response = {} <NEW_LINE> try: <NEW_LINE> <INDENT> user_object = Users.objects(user_id=user_id).only('is_unread_notification').first() <NEW_LINE> response_dict = {} <NEW_LINE> response_dict['is_unread_notification'] = user_object.is_unread_notification <NEW_LINE> response['code'] = NOTIFICATIONS_GET_READ_STATUS_SUCCESS_CODE <NEW_LINE> response['message'] = NOTIFICATIONS_GET_READ_STATUS_SUCCESS_MESSAGE <NEW_LINE> response['data'] = response_dict <NEW_LINE> return Response(response, status= status.HTTP_200_OK) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> response['code'] = NOTIFICATIONS_GET_READ_STATUS_INVALID_USERID_CODE <NEW_LINE> response['message'] = NOTIFICATIONS_GET_READ_STATUS_INVALID_USERID_MESSAGE <NEW_LINE> response['data'] = None <NEW_LINE> return Response(response, status= status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> def post(self, request, user_id): <NEW_LINE> <INDENT> response = {} <NEW_LINE> try: <NEW_LINE> <INDENT> user_object = Users.objects.get(user_id=user_id) <NEW_LINE> user_object.update(is_unread_notification=False) <NEW_LINE> response['code'] = NOTIFICATIONS_UPDATE_READ_STATUS_SUCCESS_CODE <NEW_LINE> response['message'] = NOTIFICATIONS_UPDATE_READ_STATUS_SUCCESS_MESSAGE <NEW_LINE> response['data'] = None <NEW_LINE> return Response(response, status= status.HTTP_200_OK) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> response['code'] = NOTIFICATIONS_UPDATE_READ_STATUS_INVALID_USERID_CODE <NEW_LINE> response['message'] = NOTIFICATIONS_UPDATE_READ_STATUS_INVALID_USERID_MESSAGE <NEW_LINE> response['data'] = None <NEW_LINE> return Response(response, status= status.HTTP_400_BAD_REQUEST)
Change read notification variable of a user
625990784a966d76dd5f0895
class GovernmentPosting(CreateView): <NEW_LINE> <INDENT> model = Job <NEW_LINE> form_class = JobForm <NEW_LINE> template_name = 'main/government_list.html' <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> job = form.save(commit=False) <NEW_LINE> job.user = self.request.user <NEW_LINE> job.category = 'Government' <NEW_LINE> job.city = form.cleaned_data['city'].capitalize() <NEW_LINE> job.save() <NEW_LINE> return super().form_valid(form) <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> return reverse('home')
Allow users to post government jobs
6259907899fddb7c1ca63aab
class near_pivot_args(object): <NEW_LINE> <INDENT> def __init__(self, device_uuid=None, access_token=None,): <NEW_LINE> <INDENT> self.device_uuid = device_uuid <NEW_LINE> self.access_token = access_token <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.device_uuid = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.access_token = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('near_pivot_args') <NEW_LINE> if self.device_uuid is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('device_uuid', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.device_uuid.encode('utf-8') if sys.version_info[0] == 2 else self.device_uuid) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.access_token is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('access_token', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.access_token.encode('utf-8') if sys.version_info[0] == 2 else self.access_token) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - device_uuid - access_token
62599078a05bb46b3848bdff
class UnsafeArchive(ArchiveException): <NEW_LINE> <INDENT> pass
Error raised when passed file contains paths that would be extracted outside of the target directory.
62599078aad79263cf430163
class VolumeAPIContext(InternalEndpointContext): <NEW_LINE> <INDENT> def __init__(self, pkg): <NEW_LINE> <INDENT> super(VolumeAPIContext, self).__init__() <NEW_LINE> self._ctxt = None <NEW_LINE> if not pkg: <NEW_LINE> <INDENT> raise ValueError('package name must be provided in order to ' 'determine current OpenStack version.') <NEW_LINE> <DEDENT> self.pkg = pkg <NEW_LINE> <DEDENT> @property <NEW_LINE> def ctxt(self): <NEW_LINE> <INDENT> if self._ctxt is not None: <NEW_LINE> <INDENT> return self._ctxt <NEW_LINE> <DEDENT> self._ctxt = self._determine_ctxt() <NEW_LINE> return self._ctxt <NEW_LINE> <DEDENT> def _determine_ctxt(self): <NEW_LINE> <INDENT> rel = os_release(self.pkg, base='icehouse') <NEW_LINE> version = '2' <NEW_LINE> if CompareOpenStackReleases(rel) >= 'pike': <NEW_LINE> <INDENT> version = '3' <NEW_LINE> <DEDENT> service_type = 'volumev{version}'.format(version=version) <NEW_LINE> service_name = 'cinderv{version}'.format(version=version) <NEW_LINE> endpoint_type = 'publicURL' <NEW_LINE> if config('use-internal-endpoints'): <NEW_LINE> <INDENT> endpoint_type = 'internalURL' <NEW_LINE> <DEDENT> catalog_info = '{type}:{name}:{endpoint}'.format( type=service_type, name=service_name, endpoint=endpoint_type) <NEW_LINE> return { 'volume_api_version': version, 'volume_catalog_info': catalog_info, } <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self.ctxt
Volume API context. This context provides information regarding the volume endpoint to use when communicating between services. It determines which version of the API is appropriate for use. This value will be determined in the resulting context dictionary returned from calling the VolumeAPIContext object. Information provided by this context is as follows: volume_api_version: the volume api version to use, currently 'v2' or 'v3' volume_catalog_info: the information to use for a cinder client configuration that consumes API endpoints from the keystone catalog. This is defined as the type:name:endpoint_type string.
6259907897e22403b383c8ad
class bolacha(httplib2): <NEW_LINE> <INDENT> cls = 'Bolacha'
Wrapper for bolacha.
6259907856b00c62f0fb427d
class SeedHypervisorHostUpgrade(KayobeAnsibleMixin, VaultMixin, Command): <NEW_LINE> <INDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> self.app.LOG.debug("Upgrading seed hypervisor host services") <NEW_LINE> playbooks = _build_playbook_list("kayobe-target-venv") <NEW_LINE> self.run_kayobe_playbooks(parsed_args, playbooks, limit="seed-hypervisor")
Upgrade the seed hypervisor host services. Performs the changes necessary to make the host services suitable for the configured OpenStack release.
625990785166f23b2e244d82
class UpdateMessagePoll(TLObject): <NEW_LINE> <INDENT> __slots__: List[str] = ["poll_id", "results", "poll"] <NEW_LINE> ID = 0xaca1657b <NEW_LINE> QUALNAME = "types.UpdateMessagePoll" <NEW_LINE> def __init__(self, *, poll_id: int, results: "raw.base.PollResults", poll: "raw.base.Poll" = None) -> None: <NEW_LINE> <INDENT> self.poll_id = poll_id <NEW_LINE> self.results = results <NEW_LINE> self.poll = poll <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data: BytesIO, *args: Any) -> "UpdateMessagePoll": <NEW_LINE> <INDENT> flags = Int.read(data) <NEW_LINE> poll_id = Long.read(data) <NEW_LINE> poll = TLObject.read(data) if flags & (1 << 0) else None <NEW_LINE> results = TLObject.read(data) <NEW_LINE> return UpdateMessagePoll(poll_id=poll_id, results=results, poll=poll) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> data = BytesIO() <NEW_LINE> data.write(Int(self.ID, False)) <NEW_LINE> flags = 0 <NEW_LINE> flags |= (1 << 0) if self.poll is not None else 0 <NEW_LINE> data.write(Int(flags)) <NEW_LINE> data.write(Long(self.poll_id)) <NEW_LINE> if self.poll is not None: <NEW_LINE> <INDENT> data.write(self.poll.write()) <NEW_LINE> <DEDENT> data.write(self.results.write()) <NEW_LINE> return data.getvalue()
This object is a constructor of the base type :obj:`~pyrogram.raw.base.Update`. Details: - Layer: ``122`` - ID: ``0xaca1657b`` Parameters: poll_id: ``int`` ``64-bit`` results: :obj:`PollResults <pyrogram.raw.base.PollResults>` poll (optional): :obj:`Poll <pyrogram.raw.base.Poll>`
625990787047854f46340d65
@python_2_unicode_compatible <NEW_LINE> class Trip(Base): <NEW_LINE> <INDENT> route = models.ForeignKey('Route', related_name="trips") <NEW_LINE> service = models.ForeignKey('Service', null=True, blank=True) <NEW_LINE> trip_id = models.CharField( max_length=255, db_index=True, help_text="Unique identifier for a trip.") <NEW_LINE> headsign = models.CharField( max_length=255, blank=True, help_text="Destination identification for passengers.") <NEW_LINE> short_name = models.CharField( max_length=63, blank=True, help_text="Short name used in schedules and signboards.") <NEW_LINE> direction = models.CharField( max_length=1, blank=True, choices=(('0', '0'), ('1', '1')), help_text="Direction for bi-directional routes.") <NEW_LINE> block = models.ForeignKey( 'Block', null=True, blank=True, help_text="Block of sequential trips that this trip belongs to.") <NEW_LINE> shape = models.ForeignKey( 'Shape', null=True, blank=True, help_text="Shape used for this trip") <NEW_LINE> geometry = models.LineStringField( null=True, blank=True, help_text='Geometry cache of Shape or Stops') <NEW_LINE> wheelchair_accessible = models.CharField( max_length=1, blank=True, choices=( ('0', 'No information'), ('1', 'Some wheelchair accommodation'), ('2', 'No wheelchair accommodation')), help_text='Are there accommodations for riders with wheelchair?') <NEW_LINE> bikes_allowed = models.CharField( max_length=1, blank=True, choices=( ('0', 'No information'), ('1', 'Some bicycle accommodation'), ('2', 'No bicycles allowed')), help_text='Are bicycles allowed?') <NEW_LINE> extra_data = JSONField(default={}, blank=True, null=True) <NEW_LINE> def update_geometry(self, update_parent=True): <NEW_LINE> <INDENT> original = self.geometry <NEW_LINE> if self.shape: <NEW_LINE> <INDENT> self.geometry = self.shape.geometry <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stoptimes = self.stoptime_set.order_by('stop_sequence') <NEW_LINE> if stoptimes.count() > 1: <NEW_LINE> <INDENT> self.geometry = LineString( [st.stop.point.coords for st in stoptimes]) <NEW_LINE> <DEDENT> <DEDENT> if self.geometry != original: <NEW_LINE> <INDENT> self.save() <NEW_LINE> if update_parent: <NEW_LINE> <INDENT> self.route.update_geometry() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s-%s" % (self.route, self.trip_id) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'trip' <NEW_LINE> app_label = 'multigtfs' <NEW_LINE> <DEDENT> _column_map = ( ('route_id', 'route__route_id'), ('service_id', 'service__service_id'), ('trip_id', 'trip_id'), ('trip_headsign', 'headsign'), ('trip_short_name', 'short_name'), ('direction_id', 'direction'), ('block_id', 'block__block_id'), ('shape_id', 'shape__shape_id'), ('wheelchair_accessible', 'wheelchair_accessible'), ('bikes_allowed', 'bikes_allowed'), ) <NEW_LINE> _filename = 'trips.txt' <NEW_LINE> _rel_to_feed = 'route__feed' <NEW_LINE> _unique_fields = ('trip_id',)
A trip along a route This implements trips.txt in the GTFS feed
62599078a8370b77170f1d79
class AiAnalysisTaskTagResult(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Status = None <NEW_LINE> self.ErrCodeExt = None <NEW_LINE> self.ErrCode = None <NEW_LINE> self.Message = None <NEW_LINE> self.Input = None <NEW_LINE> self.Output = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Status = params.get("Status") <NEW_LINE> self.ErrCodeExt = params.get("ErrCodeExt") <NEW_LINE> self.ErrCode = params.get("ErrCode") <NEW_LINE> self.Message = params.get("Message") <NEW_LINE> if params.get("Input") is not None: <NEW_LINE> <INDENT> self.Input = AiAnalysisTaskTagInput() <NEW_LINE> self.Input._deserialize(params.get("Input")) <NEW_LINE> <DEDENT> if params.get("Output") is not None: <NEW_LINE> <INDENT> self.Output = AiAnalysisTaskTagOutput() <NEW_LINE> self.Output._deserialize(params.get("Output"))
智能标签结果类型
62599078097d151d1a2c2a21
class Link(Interface): <NEW_LINE> <INDENT> switch = models.ForeignKey(Switch, related_name="links", null=False, editable=False) <NEW_LINE> next_link = models.ForeignKey('self', null=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = (('switch', 'next_link')) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> super(Link, self).clean() <NEW_LINE> if self.switch is self.next_link.switch: <NEW_LINE> <INDENT> raise ValidationError(_('cannot link with same switch')) <NEW_LINE> <DEDENT> if self.switch.host_id != self.next_link.switch.host_id: <NEW_LINE> <INDENT> raise ValidationError(_('cannot link with other host switch'))
{ "uuid": integer, "name": string, "number": integer, "switch": reference, "next_link": reference, }
625990783317a56b869bf21b
class Assets(systemservices.Assets): <NEW_LINE> <INDENT> def getContentItem(self, avatar, storeSession, id, version): <NEW_LINE> <INDENT> d = storeSession.getItemById(id) <NEW_LINE> return d
Generic serve up a poop item
625990784a966d76dd5f0896
class QueryInfo(object): <NEW_LINE> <INDENT> def __init__(self, entry=None, op=None, *args, **kwargs): <NEW_LINE> <INDENT> self.entry = [] if entry is None else entry <NEW_LINE> self.op = op <NEW_LINE> self.args = args <NEW_LINE> self.kwargs = kwargs
Used to pass query info from client to server
625990784f88993c371f11f7
@deprecated_class(deprecated_date="2022-08-23") <NEW_LINE> @dataclass <NEW_LINE> class Inspection(DataClassJsonMixin): <NEW_LINE> <INDENT> project_id: str <NEW_LINE> task_id: str <NEW_LINE> input_data_id: str <NEW_LINE> inspection_id: str <NEW_LINE> phase: TaskPhase <NEW_LINE> phase_stage: int <NEW_LINE> commenter_account_id: str <NEW_LINE> annotation_id: Optional[str] <NEW_LINE> label_id: Optional[str] <NEW_LINE> data: InspectionData <NEW_LINE> parent_inspection_id: Optional[str] <NEW_LINE> phrases: Optional[List[str]] <NEW_LINE> comment: str <NEW_LINE> status: InspectionStatus <NEW_LINE> created_datetime: str <NEW_LINE> updated_datetime: Optional[str]
検査コメント .. deprecated:: 2022-08-23以降に廃止する予定です。
625990784a966d76dd5f0897
class GoogleTranslation(MachineTranslation): <NEW_LINE> <INDENT> name = 'Google Translate' <NEW_LINE> max_score = 90 <NEW_LINE> language_map = { 'he': 'iw', 'jv': 'jw', 'nb': 'no', } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(GoogleTranslation, self).__init__() <NEW_LINE> if settings.MT_GOOGLE_KEY is None: <NEW_LINE> <INDENT> raise MissingConfiguration( 'Google Translate requires API key' ) <NEW_LINE> <DEDENT> <DEDENT> def convert_language(self, language): <NEW_LINE> <INDENT> return super(GoogleTranslation, self).convert_language( language.replace('_', '-').split('@')[0] ) <NEW_LINE> <DEDENT> def download_languages(self): <NEW_LINE> <INDENT> response = self.json_req( GOOGLE_API_ROOT + 'languages', key=settings.MT_GOOGLE_KEY ) <NEW_LINE> if 'error' in response: <NEW_LINE> <INDENT> raise MachineTranslationError(response['error']['message']) <NEW_LINE> <DEDENT> return [d['language'] for d in response['data']['languages']] <NEW_LINE> <DEDENT> def download_translations(self, source, language, text, unit, request): <NEW_LINE> <INDENT> response = self.json_req( GOOGLE_API_ROOT, key=settings.MT_GOOGLE_KEY, q=text, source=source, target=language, format='text', ) <NEW_LINE> if 'error' in response: <NEW_LINE> <INDENT> raise MachineTranslationError(response['error']['message']) <NEW_LINE> <DEDENT> translation = response['data']['translations'][0]['translatedText'] <NEW_LINE> return [(translation, self.max_score, self.name, text)]
Google Translate API v2 machine translation support.
625990782ae34c7f260aca92
class Tag: <NEW_LINE> <INDENT> __slots__ = ["_interpreter", "_abi", "_platform", "_hash"] <NEW_LINE> def __init__(self, interpreter: str, abi: str, platform: str) -> None: <NEW_LINE> <INDENT> self._interpreter = interpreter.lower() <NEW_LINE> self._abi = abi.lower() <NEW_LINE> self._platform = platform.lower() <NEW_LINE> self._hash = hash((self._interpreter, self._abi, self._platform)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def interpreter(self) -> str: <NEW_LINE> <INDENT> return self._interpreter <NEW_LINE> <DEDENT> @property <NEW_LINE> def abi(self) -> str: <NEW_LINE> <INDENT> return self._abi <NEW_LINE> <DEDENT> @property <NEW_LINE> def platform(self) -> str: <NEW_LINE> <INDENT> return self._platform <NEW_LINE> <DEDENT> def __eq__(self, other: object) -> bool: <NEW_LINE> <INDENT> if not isinstance(other, Tag): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return ( (self.platform == other.platform) and (self.abi == other.abi) and (self.interpreter == other.interpreter) ) <NEW_LINE> <DEDENT> def __hash__(self) -> int: <NEW_LINE> <INDENT> return self._hash <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return f"{self._interpreter}-{self._abi}-{self._platform}" <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "<{self} @ {self_id}>".format(self=self, self_id=id(self))
A representation of the tag triple for a wheel. Instances are considered immutable and thus are hashable. Equality checking is also supported.
625990784527f215b58eb676
class Distribution(object): <NEW_LINE> <INDENT> def __init__(self, df: "DataFrame({Index: 'States', Columns: ['Prob', 'Pct_Move', 'Relative_Price']}") -> 'Distribution object': <NEW_LINE> <INDENT> self.distribution_df = df <NEW_LINE> <DEDENT> @property <NEW_LINE> def mean_move(self): <NEW_LINE> <INDENT> return math.sqrt(sum([state.Prob*state.Pct_Move**2 for state in self.distribution_df.itertuples()])) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> i = 1 <NEW_LINE> new_states = [] <NEW_LINE> new_probs = [] <NEW_LINE> new_pct_moves = [] <NEW_LINE> new_relative_prices = [] <NEW_LINE> for self_state in self.distribution_df.itertuples(): <NEW_LINE> <INDENT> for other_state in other.distribution_df.itertuples(): <NEW_LINE> <INDENT> index = i <NEW_LINE> new_prob = self_state.Prob*other_state.Prob <NEW_LINE> new_relative_price = self_state.Relative_Price*other_state.Relative_Price <NEW_LINE> new_pct_move = new_relative_price - 1 <NEW_LINE> new_states.append(i) <NEW_LINE> new_probs.append(new_prob) <NEW_LINE> new_relative_prices.append(new_relative_price) <NEW_LINE> new_pct_moves.append(new_pct_move) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> new_distribution_info = {'State': new_states, 'Prob': new_probs, 'Pct_Move': new_pct_moves, 'Relative_Price': new_relative_prices} <NEW_LINE> new_distribution_df = pd.DataFrame(new_distribution_info) <NEW_LINE> new_distribution_df.set_index('State', inplace=True) <NEW_LINE> new_distribution_df = new_distribution_df.loc[:, ['Prob', 'Pct_Move', 'Relative_Price']] <NEW_LINE> return Distribution(new_distribution_df)
DataFrame({Index: 'States', Columns: ['Prob', 'Pct_Move', 'Price'] }) -> 'Distribution() object'
62599078a8370b77170f1d7a
class ValidatorAll(CompoundValidator): <NEW_LINE> <INDENT> def validate(self, option_dict: TypeOptionMap) -> ReportItemList: <NEW_LINE> <INDENT> report_list = [] <NEW_LINE> for validator in self._validator_list: <NEW_LINE> <INDENT> report_list.extend(validator.validate(option_dict)) <NEW_LINE> <DEDENT> return report_list
Run all validators and return all their reports
625990785fc7496912d48f40
class UserInterface(BaseHoleInterface): <NEW_LINE> <INDENT> def __init__(self, requester, ordered_kwargs): <NEW_LINE> <INDENT> if requester is None: <NEW_LINE> <INDENT> requester = self <NEW_LINE> <DEDENT> super().__init__(requester, ordered_kwargs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def get(cls, **kwargs): <NEW_LINE> <INDENT> requester = cls._get_root_user() <NEW_LINE> with await cls.get_client(requester) as client: <NEW_LINE> <INDENT> user_dict = await client.user_get(**kwargs) <NEW_LINE> <DEDENT> user = cls(requester, user_dict) <NEW_LINE> return user <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_root_user(cls): <NEW_LINE> <INDENT> root_id = cls.settings.ROOT_USER_ID <NEW_LINE> return cls(None, {'id': root_id}) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def authenticate(cls, username_or_email, password): <NEW_LINE> <INDENT> kw = {'username_or_email': username_or_email, 'password': password} <NEW_LINE> with await cls.get_client(None) as client: <NEW_LINE> <INDENT> user_dict = await client.user_authenticate(**kw) <NEW_LINE> <DEDENT> user = cls(None, user_dict) <NEW_LINE> return user <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def change_password(cls, requester, old_password, new_password): <NEW_LINE> <INDENT> kw = {'username_or_email': requester.email, 'old_password': old_password, 'new_password': new_password} <NEW_LINE> with await cls.get_client(requester) as client: <NEW_LINE> <INDENT> await client.user_change_password(**kw) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def request_password_reset(cls, email, reset_link): <NEW_LINE> <INDENT> subject = 'Reset password requested' <NEW_LINE> message = "Follow the link {} to reset your password.".format( reset_link) <NEW_LINE> requester = cls._get_root_user() <NEW_LINE> kw = {'email': email, 'subject': subject, 'message': message} <NEW_LINE> with await cls.get_client(requester) as client: <NEW_LINE> <INDENT> await client.user_send_reset_password_email(**kw) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def change_password_with_token(cls, token, password): <NEW_LINE> <INDENT> kw = {'token': token, 'password': password} <NEW_LINE> requester = cls._get_root_user() <NEW_LINE> with await cls.get_client(requester) as client: <NEW_LINE> <INDENT> await client.user_change_password_with_token(**kw) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def add(cls, email, username, password, allowed_actions): <NEW_LINE> <INDENT> requester = cls._get_root_user() <NEW_LINE> kw = {'username': username, 'email': email, 'password': password, 'allowed_actions': allowed_actions} <NEW_LINE> with await cls.get_client(requester) as client: <NEW_LINE> <INDENT> user_dict = await client.user_add(**kw) <NEW_LINE> <DEDENT> user = cls(None, user_dict) <NEW_LINE> return user <NEW_LINE> <DEDENT> async def delete(self): <NEW_LINE> <INDENT> kw = {'id': str(self.id)} <NEW_LINE> with await type(self).get_client(self.requester) as client: <NEW_LINE> <INDENT> resp = await client.user_remove(**kw) <NEW_LINE> <DEDENT> return resp <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> async def exists(cls, **kwargs): <NEW_LINE> <INDENT> requester = cls._get_root_user() <NEW_LINE> with await cls.get_client(requester) as client: <NEW_LINE> <INDENT> exists = await client.user_exists(**kwargs) <NEW_LINE> <DEDENT> return exists
A user created in the master
6259907832920d7e50bc79f4
class Solution: <NEW_LINE> <INDENT> @timeit <NEW_LINE> def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: <NEW_LINE> <INDENT> from collections import defaultdict <NEW_LINE> graph = defaultdict(list) <NEW_LINE> for a,b in connections: <NEW_LINE> <INDENT> graph[a].append(b) <NEW_LINE> graph[b].append(a) <NEW_LINE> <DEDENT> dfn, low = [-1] * n, [-1] * n <NEW_LINE> res = [] <NEW_LINE> timestamp = 0 <NEW_LINE> def tarjan(u, parent): <NEW_LINE> <INDENT> nonlocal timestamp <NEW_LINE> timestamp += 1 <NEW_LINE> dfn[u] = low[u] = timestamp <NEW_LINE> for v in graph[u]: <NEW_LINE> <INDENT> if dfn[v] < 0: <NEW_LINE> <INDENT> tarjan(v, u) <NEW_LINE> low[u] = min(low[u], low[v]) <NEW_LINE> <DEDENT> elif v != parent: <NEW_LINE> <INDENT> low[u] = min(low[u], dfn[v]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> tarjan(0, 0) <NEW_LINE> print(dfn) <NEW_LINE> print(low) <NEW_LINE> vis = [0] * n <NEW_LINE> def dfs(u): <NEW_LINE> <INDENT> if vis[u]: return <NEW_LINE> vis[u] = 1 <NEW_LINE> for v in graph[u]: <NEW_LINE> <INDENT> if dfn[u] < low[v]: res.append([u, v]) <NEW_LINE> dfs(v) <NEW_LINE> <DEDENT> <DEDENT> dfs(0) <NEW_LINE> return res
[1192. 查找集群内的「关键连接」](https://leetcode-cn.com/problems/critical-connections-in-a-network)
62599078a05bb46b3848be00
class DiscountPricingUpdate(object): <NEW_LINE> <INDENT> swagger_types = { 'discount_percentage': 'float' } <NEW_LINE> attribute_map = { 'discount_percentage': 'discountPercentage' } <NEW_LINE> def __init__(self, discount_percentage=None): <NEW_LINE> <INDENT> self._discount_percentage = None <NEW_LINE> self.discriminator = None <NEW_LINE> if discount_percentage is not None: <NEW_LINE> <INDENT> self.discount_percentage = discount_percentage <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def discount_percentage(self): <NEW_LINE> <INDENT> return self._discount_percentage <NEW_LINE> <DEDENT> @discount_percentage.setter <NEW_LINE> def discount_percentage(self, discount_percentage): <NEW_LINE> <INDENT> self._discount_percentage = discount_percentage <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, DiscountPricingUpdate): <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.
62599078379a373c97d9a9cf
class NapView(View): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def as_view(cls, **initkwargs): <NEW_LINE> <INDENT> return except_response(super().as_view(**initkwargs))
Base view for Nap CBV. Catches any http exceptions raised, and returns them instead.
6259907866673b3332c31dab
class ScanEntropy(strelka.Scanner): <NEW_LINE> <INDENT> def scan(self, data, file, options, expire_at): <NEW_LINE> <INDENT> self.event['entropy'] = entropy.shannon_entropy(data)
Calculates entropy of files.
625990787b180e01f3e49d3b
class Ownership(object): <NEW_LINE> <INDENT> def create(self, pixmap): <NEW_LINE> <INDENT> self.mask = pixmap.selectionMask().getInitializedCopy(value=3) <NEW_LINE> <DEDENT> def isOwned(self, pixelelID): <NEW_LINE> <INDENT> maskValue = self.mask[pixelelID.coord] <NEW_LINE> isOwned = maskValue != 3 <NEW_LINE> selfOwned = maskValue == pixelelID.pixelelIndex <NEW_LINE> return isOwned, selfOwned <NEW_LINE> <DEDENT> def possess(self, pixelelID): <NEW_LINE> <INDENT> self.mask[pixelelID.coord] = pixelelID.pixelelIndex
PixMapMask that knows the channel that owns a Pixel Value of mask byte is 3 if unowned, else the index of owning channel in range [0,2]
6259907832920d7e50bc79f5
class UserEvent(Request): <NEW_LINE> <INDENT> deserialized_types = { 'object_type': 'str', 'request_id': 'str', 'timestamp': 'datetime', 'locale': 'str', 'token': 'str', 'arguments': 'list[object]', 'source': 'object', 'components': 'object' } <NEW_LINE> attribute_map = { 'object_type': 'type', 'request_id': 'requestId', 'timestamp': 'timestamp', 'locale': 'locale', 'token': 'token', 'arguments': 'arguments', 'source': 'source', 'components': 'components' } <NEW_LINE> def __init__(self, request_id=None, timestamp=None, locale=None, token=None, arguments=None, source=None, components=None): <NEW_LINE> <INDENT> self.__discriminator_value = "Alexa.Presentation.APL.UserEvent" <NEW_LINE> self.object_type = self.__discriminator_value <NEW_LINE> super(UserEvent, self).__init__(object_type=self.__discriminator_value, request_id=request_id, timestamp=timestamp, locale=locale) <NEW_LINE> self.token = token <NEW_LINE> self.arguments = arguments <NEW_LINE> self.source = source <NEW_LINE> self.components = components <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_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 if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.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[0], item[1].value) if isinstance(item[1], Enum) 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, UserEvent): <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
:param request_id: Represents the unique identifier for the specific request. :type request_id: (optional) str :param timestamp: Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service. :type timestamp: (optional) datetime :param locale: A string indicating the user’s locale. For example: en-US. This value is only provided with certain request types. :type locale: (optional) str :param token: A unique token for the active presentation. :type token: (optional) str :param arguments: The array of argument data to pass to Alexa. :type arguments: (optional) list[object] :param source: Meta-information about what caused the event to be generated. :type source: (optional) object :param components: Components associated with the request. :type components: (optional) object
62599078a8370b77170f1d7b
class MeasureS18(MeasureActiveReactive): <NEW_LINE> <INDENT> @property <NEW_LINE> def values(self): <NEW_LINE> <INDENT> values = {} <NEW_LINE> try: <NEW_LINE> <INDENT> get = self.objectified.get <NEW_LINE> values.update({ 'order_datetime': self._get_timestamp('Fh'), 'orden': get_integer_value(get('Orden')), }) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self._warnings.append('ERROR: Thrown exception: {}'.format(e)) <NEW_LINE> return [] <NEW_LINE> <DEDENT> return [values]
Class for a set of measures of report S18.
62599078aad79263cf430166
class Scheduler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.runnable_tasks = deque() <NEW_LINE> self.completed_task_results = {} <NEW_LINE> self.failed_task_results = {} <NEW_LINE> <DEDENT> def add(self, routine): <NEW_LINE> <INDENT> task = Task(routine) <NEW_LINE> self.runnable_tasks.append(task) <NEW_LINE> return task.id <NEW_LINE> <DEDENT> def run_to_completion(self): <NEW_LINE> <INDENT> while len(self.runnable_tasks) != 0: <NEW_LINE> <INDENT> task = self.runnable_tasks.popleft() <NEW_LINE> print("Running task {}, ".format(task.id), end='') <NEW_LINE> try: <NEW_LINE> <INDENT> yielded = next(task.routine) <NEW_LINE> <DEDENT> except StopIteration as stopped: <NEW_LINE> <INDENT> print("search completed with result: {!r}".format(stopped.value)) <NEW_LINE> self.completed_task_results[task.id] = stopped.value <NEW_LINE> <DEDENT> except Exception as some_exception: <NEW_LINE> <INDENT> print('search failed with exception: {}'.format(some_exception)) <NEW_LINE> self.failed_task_results[task.id] = some_exception <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert yielded == 'Searching...' <NEW_LINE> print(yielded) <NEW_LINE> self.runnable_tasks.append(task)
`Scheduler()` is just a fancy queue.
62599078f548e778e596cf3e
class ChunkSizeTooBigError(Error): <NEW_LINE> <INDENT> pass
Raised when chunk header has what appears to be an invalid size.
625990784a966d76dd5f0898
class TwoLayerNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=3 * 32 * 32, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.weight_scale=weight_scale <NEW_LINE> self.input_dim = input_dim <NEW_LINE> self.hidden_dim = hidden_dim <NEW_LINE> self.num_classes = num_classes <NEW_LINE> self.params['W1'] = np.random.normal(0, self.weight_scale, (self.input_dim, hidden_dim)) <NEW_LINE> self.params['b1'] = np.zeros((hidden_dim,)) <NEW_LINE> self.params['W2'] = np.random.normal(0, self.weight_scale, (self.hidden_dim, self.num_classes)) <NEW_LINE> self.params['b2'] = np.zeros((self.num_classes,)) <NEW_LINE> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> hidden_inputs_affine, cache1 = affine_forward(X, self.params['W1'], self.params['b1']) <NEW_LINE> hidden_inputs_relu, cache2 = relu_forward(hidden_inputs_affine) <NEW_LINE> output, cache3 = affine_forward(hidden_inputs_relu, self.params['W2'], self.params['b2']) <NEW_LINE> scores = output <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> loss, dy_hat = softmax_loss(scores, y) <NEW_LINE> loss+= 0.5*self.reg * ((np.linalg.norm(self.params['W1']) **2) + (np.linalg.norm(self.params['W2']) **2)) <NEW_LINE> dx3, grads['W2'], grads['b2'] = affine_backward(dy_hat, cache3) <NEW_LINE> dx2 = relu_backward(dx3, cache2) <NEW_LINE> dx1, grads['W1'], grads['b1'] = affine_backward(dx2, cache1) <NEW_LINE> grads['W1']+= self.reg * self.params['W1'] <NEW_LINE> grads['W2']+= self.reg * self.params['W2'] <NEW_LINE> return loss, grads
A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. Note that this class does not implement gradient descent; instead, it will interact with a separate Solver object that is responsible for running optimization. The learnable parameters of the model are stored in the dictionary self.params that maps parameter names to numpy arrays.
625990783539df3088ecdc45
class QueryBuilder(object): <NEW_LINE> <INDENT> def __init__(self, q_type='solr', tokenizer=None): <NEW_LINE> <INDENT> self.q_type = q_type <NEW_LINE> if not tokenizer: <NEW_LINE> <INDENT> tokenizer_class = DEFAULTS['tokenizer'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tokenizer_class = tokenizers.get_class(tokenizer) <NEW_LINE> <DEDENT> self.tokenizer = tokenizer_class() <NEW_LINE> <DEDENT> def _ngram_tokenize(self, query, ngram=2): <NEW_LINE> <INDENT> tokens = self.tokenizer.tokenize(query.lower()) <NEW_LINE> ngrams = tokens.ngrams(n=ngram, uncased=True, filter_fn=utils.filter_ngram) <NEW_LINE> return ngrams <NEW_LINE> <DEDENT> def build(self, query): <NEW_LINE> <INDENT> if self.q_type == 'api_docs': <NEW_LINE> <INDENT> ngrams = self._ngram_tokenize(query) <NEW_LINE> query = ' OR '.join(['"{}"'.format(t) for t in ngrams]) <NEW_LINE> return query <NEW_LINE> <DEDENT> elif self.q_type == 'solr': <NEW_LINE> <INDENT> return self.solr_build_q(query) <NEW_LINE> <DEDENT> elif self.q_type == 'galago': <NEW_LINE> <INDENT> return self.galago_build_q(query) <NEW_LINE> <DEDENT> <DEDENT> def build_batch(self, queries): <NEW_LINE> <INDENT> if self.q_type == 'galago': <NEW_LINE> <INDENT> return self.galago_build_queries(queries) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> <DEDENT> def solr_build_q(self, query): <NEW_LINE> <INDENT> ngrams = self._ngram_tokenize(query) <NEW_LINE> query = ' '.join(['"{}"'.format(t) for t in ngrams]) <NEW_LINE> mm = MetamapExt() <NEW_LINE> meshHeadings = mm.get_mesh_names(query) <NEW_LINE> q_mesh = ' '.join(['meshHeading:"{}"'.format(mh) for mh in meshHeadings]) <NEW_LINE> query += ' ' + q_mesh <NEW_LINE> query += ' -id:(AACR* OR ASCO*)' <NEW_LINE> return query
given query string (e.g. question body), build an expanded query string with respect to the retrieval types (e.g. solr or bioasq data services)
625990782c8b7c6e89bd5197
class VectorStrategy(object): <NEW_LINE> <INDENT> __metaclass__ = SingletonMeta <NEW_LINE> def is_correct_type(self, w_obj): <NEW_LINE> <INDENT> raise NotImplementedError("abstract base class") <NEW_LINE> <DEDENT> def immutable(self, w_vector): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def ref(self, w_vector, i, check=True): <NEW_LINE> <INDENT> if check: <NEW_LINE> <INDENT> self.indexcheck(w_vector, i) <NEW_LINE> <DEDENT> return self._ref(w_vector, i) <NEW_LINE> <DEDENT> def set(self, w_vector, i, w_val, check=True): <NEW_LINE> <INDENT> if check: <NEW_LINE> <INDENT> self.indexcheck(w_vector, i) <NEW_LINE> <DEDENT> if not self.is_correct_type(w_val): <NEW_LINE> <INDENT> self.dehomogenize(w_vector) <NEW_LINE> w_vector.unsafe_set(i, w_val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._set(w_vector, i, w_val) <NEW_LINE> <DEDENT> <DEDENT> def indexcheck(self, w_vector, i): <NEW_LINE> <INDENT> assert 0 <= i < w_vector.length() <NEW_LINE> <DEDENT> def _ref(self, w_vector, i): <NEW_LINE> <INDENT> raise NotImplementedError("abstract base class") <NEW_LINE> <DEDENT> def _set(self, w_vector, i, w_val): <NEW_LINE> <INDENT> raise NotImplementedError("abstract base class") <NEW_LINE> <DEDENT> def ref_all(self, w_vector): <NEW_LINE> <INDENT> raise NotImplementedError("abstract base class") <NEW_LINE> <DEDENT> def create_storage_for_element(self, element, times): <NEW_LINE> <INDENT> raise NotImplementedError("abstract base class") <NEW_LINE> <DEDENT> def create_storage_for_elements(self, elements): <NEW_LINE> <INDENT> raise NotImplementedError("abstract base class") <NEW_LINE> <DEDENT> def dehomogenize(self, w_vector): <NEW_LINE> <INDENT> w_vector.change_strategy(ObjectVectorStrategy.singleton)
works for any W_VectorSuper that has get/set_strategy, get/set_storage
625990784428ac0f6e659edd
class TestSWGOHGG(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> server_address = ('127.0.0.1', 0) <NEW_LINE> httpd = HTTPServer(server_address, BaseHTTPRequestHandler) <NEW_LINE> port = httpd.server_port <NEW_LINE> httpd.server_close() <NEW_LINE> url = 'http://127.0.0.1:{}/swgohgg_guild.html'.format(port) <NEW_LINE> self.swgohgg_class = SWGOHGG <NEW_LINE> self.swgohgg_class.swgoh_guild_url = url <NEW_LINE> self.process = subprocess.Popen(['python', 'mock_server.py', '-port', str(port)]) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.process.kill() <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> test_swgohgg = self.swgohgg_class() <NEW_LINE> self.assertEqual(len(test_swgohgg.guild_response_soup.text), 5059) <NEW_LINE> self.assertEqual( test_swgohgg.guild_response_soup.find('strong').text, 'Note' ) <NEW_LINE> <DEDENT> def test_get_guild_gp(self): <NEW_LINE> <INDENT> test_swgohgg = self.swgohgg_class() <NEW_LINE> guild_gp = test_swgohgg.get_guild_gp() <NEW_LINE> self.assertEqual(len(guild_gp), 48) <NEW_LINE> self.assertIn('Krovikan', guild_gp)
Tests for SWGOHGG class
625990789c8ee82313040e5e
class CustomFilter(RFPDupeFilter): <NEW_LINE> <INDENT> def __getid(self, url): <NEW_LINE> <INDENT> if 'searchterm' in url: <NEW_LINE> <INDENT> url_list = url.split("=") <NEW_LINE> url_list = filter(None, url_list) <NEW_LINE> mm = url_list[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url_list = url.split("/") <NEW_LINE> url_list = filter(None, url_list) <NEW_LINE> mm = url_list[-1] <NEW_LINE> <DEDENT> return mm <NEW_LINE> <DEDENT> def request_seen(self, request): <NEW_LINE> <INDENT> fp = self.__getid(request.url) <NEW_LINE> if fp in self.fingerprints: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> self.fingerprints.add(fp) <NEW_LINE> if self.file: <NEW_LINE> <INDENT> self.file.write(fp + os.linesep)
A dupe filter that considers specific ids in the url
625990782ae34c7f260aca94
class TestElementwisePow(APIBase): <NEW_LINE> <INDENT> def hook(self): <NEW_LINE> <INDENT> self.types = [np.float32] <NEW_LINE> self.debug = False <NEW_LINE> self.enable_backward = False
test
625990784527f215b58eb677
class TestFivePhaseRecipeController(BaseTestCase): <NEW_LINE> <INDENT> def test_recipe_five_phase_gridbased_post(self): <NEW_LINE> <INDENT> recipe = FivePhaselGridBasedSchema() <NEW_LINE> response = self.client.open( '/api/recipe/five_phase/gridbased', method='POST', data=json.dumps(recipe), content_type='application/json') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) <NEW_LINE> <DEDENT> def test_recipe_five_phase_gridbased_uuid_put(self): <NEW_LINE> <INDENT> recipe = FivePhaselGridBasedSchema() <NEW_LINE> response = self.client.open( '/api/recipe/five_phase/gridbased/{uuid}'.format(uuid='uuid_example'), method='PUT', data=json.dumps(recipe), content_type='application/json') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8'))
FivePhaseRecipeController integration test stubs
625990784a966d76dd5f0899
class LabelEntry(): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def CreateFrame(parent, type_dict, entry_width=60): <NEW_LINE> <INDENT> zframe = Frame(parent) <NEW_LINE> return LabelEntry.AddFields(zframe, type_dict, entry_width=entry_width) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def CreateLframe(parent, type_dict, title="Fill-out Form", entry_width=60): <NEW_LINE> <INDENT> zframe = LabelFrame(parent, text=title) <NEW_LINE> return LabelEntry.AddFields(zframe, type_dict, entry_width=entry_width) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def AddFields(zframe, type_dict, entry_width=60, row_start=0, readonly=False): <NEW_LINE> <INDENT> for ss, key in enumerate(type_dict, row_start): <NEW_LINE> <INDENT> Label(zframe, text=key + ": ").grid(column=0, row=ss) <NEW_LINE> if readonly: <NEW_LINE> <INDENT> Entry(zframe, width=entry_width, textvariable=type_dict[key], state='readonly').grid(column=1, row=ss) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Entry(zframe, width=entry_width, textvariable=type_dict[key]).grid(column=1, row=ss) <NEW_LINE> <DEDENT> <DEDENT> return zframe
Create a Tkinter native-type, data-entry display. Returns an unpacked frame sporting a grid layout of your dictionary-defined fields. Tags are field names, entries are rvalues for same. (Using Tkinter's smart-variables for the later.)
62599078aad79263cf430167
class ResidualBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num, use_cuda=False): <NEW_LINE> <INDENT> super(ResidualBlock, self).__init__() <NEW_LINE> if use_cuda: <NEW_LINE> <INDENT> self.c1 = nn.Conv2d(num, num, kernel_size=3, stride=1, padding=1).cuda(device_id=0) <NEW_LINE> self.c2 = nn.Conv2d(num, num, kernel_size=3, stride=1, padding=1).cuda(device_id=0) <NEW_LINE> self.b1 = nn.BatchNorm2d(num).cuda(device_id=0) <NEW_LINE> self.b2 = nn.BatchNorm2d(num).cuda(device_id=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.c1 = nn.Conv2d(num, num, kernel_size=3, stride=1, padding=1) <NEW_LINE> self.c2 = nn.Conv2d(num, num, kernel_size=3, stride=1, padding=1) <NEW_LINE> self.b1 = nn.BatchNorm2d(num) <NEW_LINE> self.b2 = nn.BatchNorm2d(num) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> h = F.relu(self.b1(self.c1(x))) <NEW_LINE> h = self.b2(self.c2(h)) <NEW_LINE> return h + x
Residual blocks as implemented in [1]
6259907856b00c62f0fb4281
class Rates( Base ): <NEW_LINE> <INDENT> __tablename__ = 't_region_city_rates' <NEW_LINE> max_weight = Column( Integer ) <NEW_LINE> city_id = Column( Integer, primary_key=True ) <NEW_LINE> cost = Column( Float )
Стоимость доставки в ДПД регионы
62599078d486a94d0ba2d966
class VersionPlugin(plugin.APRSDRegexCommandPluginBase): <NEW_LINE> <INDENT> command_regex = "^[vV]" <NEW_LINE> command_name = "version" <NEW_LINE> short_description = "What is the APRSD Version" <NEW_LINE> email_sent_dict = {} <NEW_LINE> @trace.trace <NEW_LINE> def process(self, packet): <NEW_LINE> <INDENT> LOG.info("Version COMMAND") <NEW_LINE> stats_obj = stats.APRSDStats() <NEW_LINE> s = stats_obj.stats() <NEW_LINE> return "APRSD ver:{} uptime:{}".format( aprsd.__version__, s["aprsd"]["uptime"], )
Version of APRSD Plugin.
625990787d847024c075dd8a
class KlDivergence( Error ): <NEW_LINE> <INDENT> def __init__( self ): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def f( self, target, predicted ): <NEW_LINE> <INDENT> if isinstance( predicted, Dual ): <NEW_LINE> <INDENT> target = type(predicted)( target, 0, predicted.n_ ) <NEW_LINE> return target * ( target / predicted ).where( target <= 0, 1 ).log() <NEW_LINE> <DEDENT> return target * np.log( np.where( target > 0, target / predicted, 1 ) ) <NEW_LINE> <DEDENT> def df( self, target, predicted ): <NEW_LINE> <INDENT> return -( target / predicted )
Kullback-Liebler
6259907816aa5153ce401e89
class Viewer(): <NEW_LINE> <INDENT> _activity = None <NEW_LINE> _process = None <NEW_LINE> _ui = None <NEW_LINE> def __init__(self,activity): <NEW_LINE> <INDENT> self._activity = activity <NEW_LINE> self._process = ViewerProcess() <NEW_LINE> self._ui = ViewerUI(self._activity, self._process) <NEW_LINE> <DEDENT> def loadUI(self): <NEW_LINE> <INDENT> self._ui.loadUI() <NEW_LINE> <DEDENT> def showStatus(self): <NEW_LINE> <INDENT> self._ui.showStatus()
Viewer component for Classroom Kit Activity
62599078442bda511e95da2f
class Dependency: <NEW_LINE> <INDENT> def __init__(self, collapseDependencies=False, filterRegex=".*", positiveFilter=True): <NEW_LINE> <INDENT> self.dependencies = dict([]) <NEW_LINE> self.collapseDependencies = collapseDependencies <NEW_LINE> self.filterRegex = filterRegex <NEW_LINE> self.positiveFilter = positiveFilter <NEW_LINE> <DEDENT> def _filterDeps(self): <NEW_LINE> <INDENT> filteredDependencies = dict([]) <NEW_LINE> for package, dependency in self.dependencies.items(): <NEW_LINE> <INDENT> if re.match(self.filterRegex, package): <NEW_LINE> <INDENT> if self.positiveFilter: <NEW_LINE> <INDENT> filteredDependencies[package] = dependency <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not self.positiveFilter: <NEW_LINE> <INDENT> filteredDependencies[package] = dependency <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.dependencies = filteredDependencies <NEW_LINE> <DEDENT> def _add(self, rawDependencyString): <NEW_LINE> <INDENT> dependency = re.sub("\s*([<>=]+)\s*", "\\1", rawDependencyString) <NEW_LINE> dependency = re.sub("\s*,\s*", "\n", dependency) <NEW_LINE> dependency = re.sub("\s+", "\n", dependency) <NEW_LINE> dependency = re.sub("([<>=]+)", " \\1", dependency) <NEW_LINE> for dependency in dependency.split("\n"): <NEW_LINE> <INDENT> if len(dependency.strip()) != 0: <NEW_LINE> <INDENT> if re.search(" ", dependency): <NEW_LINE> <INDENT> (package, versionSpec) = dependency.split(" ") <NEW_LINE> dependency = re.sub("\s*([<>=]+\s*)", " \\1 ", dependency) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> package = dependency <NEW_LINE> <DEDENT> if (package in self.dependencies) and not self.collapseDependencies: <NEW_LINE> <INDENT> if self.dependencies[package] != dependency: <NEW_LINE> <INDENT> self.dependencies[package] = self.dependencies[package] + ", " + dependency <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.dependencies[package] = dependency <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def add(self, rawDependencies): <NEW_LINE> <INDENT> if isinstance(rawDependencies, ListType): <NEW_LINE> <INDENT> for item in rawDependencies: <NEW_LINE> <INDENT> self._add(item) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._add(rawDependencies) <NEW_LINE> <DEDENT> self._filterDeps() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ", ".join(self.dependencies.values())
Consumes raw formatted RPM dependencies. Either accumulates them or collapses them so the first/gerneral ones get overwritten by the later/specific ones
6259907897e22403b383c8b1
class SimplePngFileField(factory.LazyAttribute): <NEW_LINE> <INDENT> def __init__(self, method=None, *args, **kwargs): <NEW_LINE> <INDENT> if not method: <NEW_LINE> <INDENT> def png_file(a): <NEW_LINE> <INDENT> return File(simple_png()) <NEW_LINE> <DEDENT> method = png_file <NEW_LINE> <DEDENT> super(SimplePngFileField, self).__init__(method, *args, **kwargs)
A factory file field class that creates an image in memory. Suitable for using as a FileField or ImageField. class ATestFactory(factory.Factory): file = SimplePngFileField()
6259907801c39578d7f1440c
class DBTextMsg(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = u'回复管理(文字消息)' <NEW_LINE> verbose_name_plural = u'回复管理(文字消息)' <NEW_LINE> <DEDENT> name = models.CharField(blank=True, max_length=50, verbose_name=u"消息名字", help_text=u"可以为空,仅用来标识消息") <NEW_LINE> content = models.TextField(blank=False, verbose_name=u"消息内容") <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s %s' % (self.id, self.name)
msg in database
62599078be8e80087fbc0a43