code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class AbstractGraph(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @property <NEW_LINE> @abc.abstractmethod <NEW_LINE> def directed(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def add_vertex(self, v: int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def remove_vertex(self, v: int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def add_edge(self, u: int, v: int, weight: int = 1): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def remove_edge(self, u: int, v: int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def neighbours(self, v: int) -> typing.Iterable[WeightedConnection]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def min_weight(self, u: int, v: int): <NEW_LINE> <INDENT> pass | Abstract class representing graph structure.
Consider nodes to be integers, because they could be mapped into any data. | 625990697047854f46340b77 |
class CanonicalizationMethodType (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_MIXED <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'CanonicalizationMethodType') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('C:\\Users\\e-pohe\\Documents\\BigData\\Investment_Banking\\ETL in Banking\\FpML\\confirmation\\xmldsig-core-schema.xsd', 63, 2) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __Algorithm = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'Algorithm'), 'Algorithm', '__httpwww_w3_org200009xmldsig_CanonicalizationMethodType_Algorithm', pyxb.binding.datatypes.anyURI, required=True) <NEW_LINE> __Algorithm._DeclarationLocation = pyxb.utils.utility.Location('C:\\Users\\e-pohe\\Documents\\BigData\\Investment_Banking\\ETL in Banking\\FpML\\confirmation\\xmldsig-core-schema.xsd', 68, 4) <NEW_LINE> __Algorithm._UseLocation = pyxb.utils.utility.Location('C:\\Users\\e-pohe\\Documents\\BigData\\Investment_Banking\\ETL in Banking\\FpML\\confirmation\\xmldsig-core-schema.xsd', 68, 4) <NEW_LINE> Algorithm = property(__Algorithm.value, __Algorithm.set, None, None) <NEW_LINE> _HasWildcardElement = True <NEW_LINE> _ElementMap.update({ }) <NEW_LINE> _AttributeMap.update({ __Algorithm.name() : __Algorithm }) | Complex type {http://www.w3.org/2000/09/xmldsig#}CanonicalizationMethodType with content type MIXED | 625990698e7ae83300eea850 |
class Weapon(object): <NEW_LINE> <INDENT> def attack(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def speed(self): <NEW_LINE> <INDENT> raise NotImplementedError | Weapon common class | 62599069aad79263cf42ff78 |
class Accuracy(EvalMetric): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Accuracy, self).__init__('accuracy') <NEW_LINE> <DEDENT> def update(self, label, pred): <NEW_LINE> <INDENT> pred = pred.asnumpy() <NEW_LINE> label = label.asnumpy().astype('int32') <NEW_LINE> py = numpy.argmax(pred, axis=1) <NEW_LINE> self.sum_metric += numpy.sum(py == label) <NEW_LINE> self.num_inst += label.size | Calculate accuracy | 62599069d6c5a102081e38ea |
class TokenDoesNotExists(Exception): <NEW_LINE> <INDENT> pass | Token does not (yet) exists
| 625990697b180e01f3e49c45 |
class Point(object): <NEW_LINE> <INDENT> def __init__(self, name, coords, classification=None, alpha=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.coords = coords <NEW_LINE> self.classification = classification <NEW_LINE> self.alpha = alpha <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return deepcopy(self) <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> return self.coords[i] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.coords) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return (self.coords == other.coords and self.classification == other.classification and self.alpha == other.alpha) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.classification is None and self.alpha is None: <NEW_LINE> <INDENT> return "Point(%s, %s)" % (str(self.name), str(self.coords)) <NEW_LINE> <DEDENT> return "Point(%s, %s, class=%s, alpha=%s)" % (str(self.name), str(self.coords), str(self.classification), str(self.alpha)) <NEW_LINE> <DEDENT> __repr__ = __str__ | A Point has a name and a list or tuple of coordinates, and optionally a
classification, and/or alpha value. | 62599069460517430c432c36 |
class ComboEntryField(gtk.HBox): <NEW_LINE> <INDENT> def __init__(self, values): <NEW_LINE> <INDENT> gtk.HBox.__init__(self) <NEW_LINE> self.combo = gtk.combo_box_entry_new_text() <NEW_LINE> for value in values: <NEW_LINE> <INDENT> self.combo.append_text(value) <NEW_LINE> <DEDENT> self.pack_start(self.combo) <NEW_LINE> self.combo.show() <NEW_LINE> <DEDENT> def get_state(self): <NEW_LINE> <INDENT> return self.combo.get_child().get_text() <NEW_LINE> <DEDENT> def set_state(self, state): <NEW_LINE> <INDENT> self.combo.get_child().set_text(str(state)) | Select from multiple fixed values, but allow the user to enter text | 625990694428ac0f6e659cf4 |
class SysVarDigitalLabSmith_AV201Position(SysVarDigital): <NEW_LINE> <INDENT> states = ('A', 'closed', 'B') <NEW_LINE> def __init__(self, name, valvesControllerPort, helpLine='', editable=True): <NEW_LINE> <INDENT> SysVarDigital.__init__(self, name, self.states, LabSmithEIB, helpLine=helpLine, editable=editable) <NEW_LINE> self.valvesController = None <NEW_LINE> self.valvesControllerPort = valvesControllerPort <NEW_LINE> <DEDENT> def SetController(self, valvesController): <NEW_LINE> <INDENT> self.valvesController = valvesController <NEW_LINE> self.compName = valvesController.name <NEW_LINE> <DEDENT> def GetFunc(self): <NEW_LINE> <INDENT> state = self.valvesController.getValve(self.valvesControllerPort) <NEW_LINE> return state if state in self.states else None <NEW_LINE> <DEDENT> def SetFunc(self, state): <NEW_LINE> <INDENT> self.valvesController.setValve(self.valvesControllerPort, state) | A LabSmith AV201 valve position | 625990698e7ae83300eea851 |
class Trie: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.root = self.__get_node() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __get_node(): <NEW_LINE> <INDENT> return TrieNode() <NEW_LINE> <DEDENT> def insert(self, word) -> None: <NEW_LINE> <INDENT> current_node = self.root <NEW_LINE> for char in word: <NEW_LINE> <INDENT> child = current_node.children.get(char) <NEW_LINE> if not child: <NEW_LINE> <INDENT> child = self.__get_node() <NEW_LINE> current_node.children[char] = child <NEW_LINE> <DEDENT> current_node = child <NEW_LINE> <DEDENT> current_node.is_end = True <NEW_LINE> <DEDENT> def words_with_prefix(self, prefix: str) -> List[str]: <NEW_LINE> <INDENT> results: List[str] = [] <NEW_LINE> node = self.__get_node_by_prefix(prefix) <NEW_LINE> self.__collect_children(node, prefix, results) <NEW_LINE> return results <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __collect_children( node: Optional[TrieNode], prefix: str, results: List[str] ) -> None: <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if node.is_end: <NEW_LINE> <INDENT> results.append(prefix) <NEW_LINE> <DEDENT> for char, child_node in node.children.items(): <NEW_LINE> <INDENT> Trie.__collect_children(child_node, prefix + char, results) <NEW_LINE> <DEDENT> <DEDENT> def search(self, word) -> bool: <NEW_LINE> <INDENT> node = self.__get_node_by_prefix(word) <NEW_LINE> return node is not None and node.is_end <NEW_LINE> <DEDENT> def __get_node_by_prefix(self, prefix) -> Optional[TrieNode]: <NEW_LINE> <INDENT> current_node = self.root <NEW_LINE> for char in prefix: <NEW_LINE> <INDENT> child = current_node.children.get(char) <NEW_LINE> if not child: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> current_node = child <NEW_LINE> <DEDENT> return current_node | Trie class
Implements 'Trie' tree.
Supported operations are:
- insert: Inserts a word in the Trie
- search: Indicates whether a word exists in the Trie or not
- words_with_prefix: Finds all words that starts by a given prefix | 6259906921bff66bcd724429 |
class RecipeSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> ingredients = serializers.PrimaryKeyRelatedField( many=True, queryset = Ingredient.objects.all() ) <NEW_LINE> tags = serializers.PrimaryKeyRelatedField( many=True, queryset = Tag.objects.all() ) <NEW_LINE> class Meta(): <NEW_LINE> <INDENT> model = Recipe <NEW_LINE> fields = ('id','title','ingredients','tags','time_minutes', 'price','link' ) <NEW_LINE> read_only_fields = ('id',) | serializer for recipe obejct | 62599069adb09d7d5dc0bd2d |
class DescribeCertificatesResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.CertificateSet = None <NEW_LINE> self.TotalCount = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("CertificateSet") is not None: <NEW_LINE> <INDENT> self.CertificateSet = [] <NEW_LINE> for item in params.get("CertificateSet"): <NEW_LINE> <INDENT> obj = Certificate() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.CertificateSet.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> self.RequestId = params.get("RequestId") | DescribeCertificates返回参数结构体
| 6259906976e4537e8c3f0d46 |
class ScaledDotProductAttention(nn.Module): <NEW_LINE> <INDENT> def __init__(self, temperature, attn_dropout=0.1): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.temperature = temperature <NEW_LINE> self.dropout = nn.Dropout(attn_dropout) <NEW_LINE> <DEDENT> def forward(self, q, k, v, mask=None): <NEW_LINE> <INDENT> attn = torch.matmul(q / self.temperature, k.transpose(2, 3)) <NEW_LINE> if mask is not None: <NEW_LINE> <INDENT> attn = attn.masked_fill(mask == 0, -1e9) <NEW_LINE> <DEDENT> attn = self.dropout(F.softmax(attn, dim=-1)) <NEW_LINE> output = torch.matmul(attn, v) <NEW_LINE> return output, attn | 定义基于点积的Attention类.
:param temperature: 表示向量的维度,即v的向量维度
:param attn_dropout: | 625990696e29344779b01e15 |
class UserProfile(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User) <NEW_LINE> member = models.OneToOneField(Member) <NEW_LINE> favorite_videos = models.ManyToManyField( Video, related_name="%(class)s_favorite_set") <NEW_LINE> watch_later_videos = models.ManyToManyField( Video, related_name="%(class)s_watch_later_set") | A model describing a user profile. User profiles attach additional
information to a django User model. Here, a reference to a Member
object is held thus enabling access to a particular Member subclass
directly from the User. | 625990697c178a314d78e7cd |
class CapabilitiesFile(Element, HomogeneousList): <NEW_LINE> <INDENT> def __init__(self, config=None, pos=None, _name='capabilities', **kwargs): <NEW_LINE> <INDENT> Element.__init__(self, config=config, pos=pos, **kwargs) <NEW_LINE> HomogeneousList.__init__(self, vr.Capability) <NEW_LINE> <DEDENT> @xmlelement(name='capability') <NEW_LINE> def capabilities(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> @capabilities.adder <NEW_LINE> def capabilities(self, iterator, tag, data, config, pos): <NEW_LINE> <INDENT> capability = vr.Capability(config, pos, 'capability', **data) <NEW_LINE> capability.parse(iterator, config) <NEW_LINE> self.append(capability) <NEW_LINE> <DEDENT> def parse(self, iterator, config): <NEW_LINE> <INDENT> for start, tag, data, pos in iterator: <NEW_LINE> <INDENT> if start: <NEW_LINE> <INDENT> if tag == "xml": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif tag == "capabilities": <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> vo_raise(E10, config=config, pos=pos) <NEW_LINE> <DEDENT> <DEDENT> super().parse(iterator, config) <NEW_LINE> return self | capabilities element: represents an entire file.
The keyword arguments correspond to setting members of the same
name, documented below. | 62599069462c4b4f79dbd1ca |
class ADT(object): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> self.constr = self.__class__.__name__ <NEW_LINE> self.arg = args if len(args) != 1 else args[0] <NEW_LINE> <DEDENT> def __cmp__(self,other): <NEW_LINE> <INDENT> return self.__dict__.__cmp__(other.__dict__) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> def qstr(x): <NEW_LINE> <INDENT> if isinstance(x, (int,long)): <NEW_LINE> <INDENT> return '0x{0:x}'.format(x) <NEW_LINE> <DEDENT> elif isinstance(x, ADT): <NEW_LINE> <INDENT> return str(x) <NEW_LINE> <DEDENT> elif isinstance(x, tuple): <NEW_LINE> <INDENT> return "(" + ", ".join(qstr(i) for i in x) + ")" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '"{0}"'.format(x) <NEW_LINE> <DEDENT> <DEDENT> def args(): <NEW_LINE> <INDENT> if isinstance(self.arg, tuple): <NEW_LINE> <INDENT> return ", ".join(qstr(x) for x in self.arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return qstr(self.arg) <NEW_LINE> <DEDENT> <DEDENT> return "{0}({1})".format(self.constr, args()) | Algebraic Data Type.
This is a base class for all ADTs. ADT represented by a tuple of arguments,
stored in a val field. Arguments should be instances of ADT class, or numbers,
or strings. Empty set of arguments is permitted.
A one-tuple is automatically untupled, i.e., `Int(12)` has value `12`, not `(12,)`.
For convenience, a name of the constructor is provided in `name` field.
A structural comparison is provided. | 62599069442bda511e95d93a |
class Task(object): <NEW_LINE> <INDENT> def __init__(self,name,session): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> if not hasattr(self,"_description"): <NEW_LINE> <INDENT> self._retrieve_data() <NEW_LINE> <DEDENT> return self._description <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> if not hasattr(self,"_title"): <NEW_LINE> <INDENT> self._retrieve_data() <NEW_LINE> <DEDENT> return self._title <NEW_LINE> <DEDENT> @title.setter <NEW_LINE> def title(self,title): <NEW_LINE> <INDENT> self._title = title <NEW_LINE> <DEDENT> @property <NEW_LINE> def input_description(self): <NEW_LINE> <INDENT> if not hasattr(self,"_input_description"): <NEW_LINE> <INDENT> self._retrieve_data() <NEW_LINE> <DEDENT> return self._input_description <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_description(self): <NEW_LINE> <INDENT> if not hasattr(self,"_output_description"): <NEW_LINE> <INDENT> self._retrieve_data() <NEW_LINE> <DEDENT> return self._output_description <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<Task name={name}>".format(name=self.name) <NEW_LINE> <DEDENT> def _retrieve_data(self): <NEW_LINE> <INDENT> url = PROBLEM_ROOT_URL + "/" + self.name <NEW_LINE> page = self.session.get_soup_from_url(url) <NEW_LINE> problem_data_block = page.find(id="main").find(class_="wiki_text_block") <NEW_LINE> problem_header = problem_data_block.h1 <NEW_LINE> self._title = problem_header.get_text().strip() <NEW_LINE> problem_restriction_row = problem_data_block.table.findAll("tr")[2].findAll("td") <NEW_LINE> self._time_limit = problem_restriction_row[1].get_text().strip() <NEW_LINE> self._memory_limit = problem_restriction_row[3].get_text().strip() <NEW_LINE> input_paragraph = problem_data_block.find("h2",text=re.compile("Date de [iI]n")).next_sibling.next_sibling <NEW_LINE> self._input_description = input_paragraph.get_text().strip() <NEW_LINE> output_paragraph = problem_data_block.find("h2",text=re.compile("Date de [iI]e")).next_sibling.next_sibling <NEW_LINE> self._output_description = output_paragraph.get_text().strip() <NEW_LINE> self._description = "" <NEW_LINE> for paragraph in problem_header.find_next_siblings("p"): <NEW_LINE> <INDENT> if paragraph == input_paragraph: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> maybe_para_header = paragraph.previous_sibling.previous_sibling <NEW_LINE> if maybe_para_header.name == "h2": <NEW_LINE> <INDENT> self._description += "\n" + maybe_para_header.get_text() + "\n\n" <NEW_LINE> <DEDENT> self._description += paragraph.get_text().strip() + "\n" | Contains data for each task.
Task is identified by id/name (the id used by the site to reference the problem)
Data is being loaded lazily so object initialization doesn't infer any cost. | 625990697047854f46340b79 |
class SearchForm(FlaskForm): <NEW_LINE> <INDENT> page = HiddenField('page') <NEW_LINE> search = SearchField( 'search', render_kw={"placeholder": "Ingrese nombre de usuario a buscar"}) <NEW_LINE> active = RadioField('active', coerce=int, choices=[(1, 'Activos'), (0, 'Bloqueados')], default=1) | Clase que se encarga de generar formulario para busqueda de usuarios
para luego realizar validaciones correspondientes, tanto del lado del
servidor como del cliente | 62599069d268445f2663a73f |
class DebugMetricsLogger(MetricsLogger): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(DebugMetricsLogger, self).__init__() <NEW_LINE> <DEDENT> def _format_name(self, *args, **kwargs): <NEW_LINE> <INDENT> pprint.pprint(("_format_name call:", args, kwargs)) <NEW_LINE> <DEDENT> def _gauge(self, *args, **kwargs): <NEW_LINE> <INDENT> pprint.pprint(("_gauge call:", args, kwargs)) <NEW_LINE> <DEDENT> def _counter(self, *args, **kwargs): <NEW_LINE> <INDENT> pprint.pprint(("_counter call:", args, kwargs)) <NEW_LINE> <DEDENT> def _timer(self, *args, **kwargs): <NEW_LINE> <INDENT> pprint.pprint(("_timer call:", args, kwargs)) | MetricsLogger that prints all calls for debugging purposes | 6259906956ac1b37e63038c4 |
class Explosion(Projectile): <NEW_LINE> <INDENT> lifetime: Tuple[int, int] <NEW_LINE> radius: int <NEW_LINE> hull_damage: int <NEW_LINE> energy_damage: int <NEW_LINE> strength: int | A very strange thing to call equipment, whatever way you look at it, yet defined in weapon_equip. | 625990698e7ae83300eea852 |
class Message(models.Model): <NEW_LINE> <INDENT> id = models.CharField(max_length=32, default=_random_uuid, primary_key=True) <NEW_LINE> type = models.CharField(max_length=10, choices=MessageType.choices) <NEW_LINE> sender = models.ForeignKey(Sender, related_name='messages') <NEW_LINE> application = models.ForeignKey(Application, related_name='messages') <NEW_LINE> subject = models.CharField(max_length=100) <NEW_LINE> message = models.TextField() <NEW_LINE> recipients = models.ManyToManyField(Person, through='MessageRecipient') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'from %s' % self.sender.name <NEW_LINE> <DEDENT> __unicode__ = __str__ | a message to one or more people | 6259906991f36d47f2231a71 |
class GroupInvitationSerializer(InvitationSeralizer): <NEW_LINE> <INDENT> group = (serializers .HyperlinkedRelatedField(queryset=Group.objects.all(), view_name='group-detail')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = GroupInvitation <NEW_LINE> fields = ('url', 'accepted', 'inviter', 'invitee', 'created_on', 'group') <NEW_LINE> read_only_fields = ('inviter',) | Serializer for a Group Invitation | 6259906932920d7e50bc780b |
class TaskResource(PandaModelResource): <NEW_LINE> <INDENT> from panda.api.users import UserResource <NEW_LINE> creator = fields.ForeignKey(UserResource, 'creator') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> queryset = TaskStatus.objects.all() <NEW_LINE> resource_name = 'task' <NEW_LINE> allowed_methods = ['get'] <NEW_LINE> filtering = { 'status': ('exact', 'in', ), 'end': ('year', 'month', 'day') } <NEW_LINE> authentication = PandaAuthentication() <NEW_LINE> authorization = DjangoAuthorization() <NEW_LINE> serializer = PandaSerializer() | Simple wrapper around django-celery's task API. | 6259906999cbb53fe68326aa |
class AbsoluteFilenames(Error): <NEW_LINE> <INDENT> pass | Files with absolute path inside archive forbidden
| 62599069009cb60464d02cfd |
class DataProcessor: <NEW_LINE> <INDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_test_examples(self, input_file): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_original_num_labels(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _read_tsv(cls, input_file, quotechar=None): <NEW_LINE> <INDENT> with tf.gfile.Open(input_file, "r") as f: <NEW_LINE> <INDENT> reader = csv.reader(f, delimiter="\t", quotechar=quotechar) <NEW_LINE> lines = [] <NEW_LINE> for line in reader: <NEW_LINE> <INDENT> lines.append(line) <NEW_LINE> <DEDENT> return lines | Base class for data converters for sequence classification data sets. | 62599069f548e778e596cd50 |
class resolve_coreferences_in_tokenized_sentences_args(object): <NEW_LINE> <INDENT> __slots__ = [ 'sentencesWithTokensSeparatedBySpace', ] <NEW_LINE> thrift_spec = ( None, (1, TType.LIST, 'sentencesWithTokensSeparatedBySpace', (TType.STRING,None), None, ), ) <NEW_LINE> def __init__(self, sentencesWithTokensSeparatedBySpace=None,): <NEW_LINE> <INDENT> self.sentencesWithTokensSeparatedBySpace = sentencesWithTokensSeparatedBySpace <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.sentencesWithTokensSeparatedBySpace = [] <NEW_LINE> (_etype80, _size77) = iprot.readListBegin() <NEW_LINE> for _i81 in xrange(_size77): <NEW_LINE> <INDENT> _elem82 = iprot.readString().decode('utf-8') <NEW_LINE> self.sentencesWithTokensSeparatedBySpace.append(_elem82) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('resolve_coreferences_in_tokenized_sentences_args') <NEW_LINE> if self.sentencesWithTokensSeparatedBySpace is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('sentencesWithTokensSeparatedBySpace', TType.LIST, 1) <NEW_LINE> oprot.writeListBegin(TType.STRING, len(self.sentencesWithTokensSeparatedBySpace)) <NEW_LINE> for iter83 in self.sentencesWithTokensSeparatedBySpace: <NEW_LINE> <INDENT> oprot.writeString(iter83.encode('utf-8')) <NEW_LINE> <DEDENT> oprot.writeListEnd() <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, getattr(self, key)) for key in self.__slots__] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for attr in self.__slots__: <NEW_LINE> <INDENT> my_val = getattr(self, attr) <NEW_LINE> other_val = getattr(other, attr) <NEW_LINE> if my_val != other_val: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- sentencesWithTokensSeparatedBySpace | 62599069460517430c432c37 |
class writer(DictWriter): <NEW_LINE> <INDENT> pass | A wrapper for ris.io.DictWriter.
Unlike in the csv module, there is no difference between these classes. | 625990697d847024c075db9e |
@add_wrapper_method <NEW_LINE> class WfSerializationTrans(WfSrSerializationTrans): <NEW_LINE> <INDENT> def __init__( self, assert_sr=None, dtype=DFLT_DTYPE, format=DFLT_FORMAT, subtype=None, endian=None, ): <NEW_LINE> <INDENT> super().__init__(dtype, format, subtype, endian) <NEW_LINE> self.assert_sr = assert_sr <NEW_LINE> <DEDENT> def _obj_of_data(self, data): <NEW_LINE> <INDENT> wf, sr = super()._obj_of_data(data) <NEW_LINE> if self.assert_sr is not None and sr != self.assert_sr: <NEW_LINE> <INDENT> raise SampleRateAssertionError( f'{self.assert_sr} expected but I encountered {sr}' ) <NEW_LINE> <DEDENT> return wf <NEW_LINE> <DEDENT> def _data_of_obj(self, obj): <NEW_LINE> <INDENT> return super()._data_of_obj((obj, self.sr)) | An audio serializatiobn object like WfSrSerializationTrans, but working with waveforms only (sample rate fixed).
See WavSerializationTrans for explanations and doctest examples. | 625990698e71fb1e983bd28b |
class HtmlTagMismatchException(Exception): <NEW_LINE> <INDENT> pass | Pairing of the tags is not done properly | 6259906997e22403b383c6d2 |
class PyTautulliAuthenticationException(PyTautulliException): <NEW_LINE> <INDENT> pass | pytautulli authentication exception. | 6259906967a9b606de547684 |
class CancelActionMiddleware(object): <NEW_LINE> <INDENT> def __init__(self, get_response=None): <NEW_LINE> <INDENT> if get_response is None: <NEW_LINE> <INDENT> get_response = lambda x:x <NEW_LINE> <DEDENT> self.get_response = get_response <NEW_LINE> <DEDENT> def __call__(self, request): <NEW_LINE> <INDENT> return self.get_response(request) <NEW_LINE> <DEDENT> def process_view(self, request, view_func, view_args, view_kwargs): <NEW_LINE> <INDENT> if 'cancel' in get_request_params(request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = getattr(view_func,'CANCEL_MESSAGE') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> msg = 'action canceled' <NEW_LINE> <DEDENT> request.user.message_set.create(message=str(msg)) <NEW_LINE> return HttpResponseRedirect(get_next_url(request)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Django middleware that redirects to the next url
if the request has "cancel" parameter. | 625990695fc7496912d48e4a |
class PyAdam(mx.optimizer.Optimizer): <NEW_LINE> <INDENT> def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8, lazy_update=True, **kwargs): <NEW_LINE> <INDENT> super(PyAdam, self).__init__(learning_rate=learning_rate, **kwargs) <NEW_LINE> self.beta1 = beta1 <NEW_LINE> self.beta2 = beta2 <NEW_LINE> self.epsilon = epsilon <NEW_LINE> self.lazy_update = lazy_update <NEW_LINE> <DEDENT> def create_state(self, index, weight): <NEW_LINE> <INDENT> return (mx.nd.zeros(weight.shape, weight.context, dtype=weight.dtype), mx.nd.zeros(weight.shape, weight.context, dtype=weight.dtype)) <NEW_LINE> <DEDENT> def update(self, index, weight, grad, state): <NEW_LINE> <INDENT> lr = self._get_lr(index) <NEW_LINE> self._update_count(index) <NEW_LINE> t = self._index_update_count[index] <NEW_LINE> mean, variance = state <NEW_LINE> wd = self._get_wd(index) <NEW_LINE> num_rows = weight.shape[0] <NEW_LINE> coef1 = 1. - self.beta1**t <NEW_LINE> coef2 = 1. - self.beta2**t <NEW_LINE> lr *= math.sqrt(coef2)/coef1 <NEW_LINE> for row in range(num_rows): <NEW_LINE> <INDENT> all_zeros = mx.test_utils.almost_equal(grad[row].asnumpy(), np.zeros_like(grad[row].asnumpy())) <NEW_LINE> if all_zeros and self.lazy_update: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> grad[row] = grad[row] * self.rescale_grad + wd * weight[row] <NEW_LINE> if self.clip_gradient is not None: <NEW_LINE> <INDENT> mx.nd.clip(grad[row], -self.clip_gradient, self.clip_gradient, out=grad[row]) <NEW_LINE> <DEDENT> mean[row] *= self.beta1 <NEW_LINE> mean[row] += grad[row] * (1. - self.beta1) <NEW_LINE> variance[row] *= self.beta2 <NEW_LINE> variance[row] += (1 - self.beta2) * mx.nd.square(grad[row], out=grad[row]) <NEW_LINE> weight[row] -= lr*mean[row]/(mx.nd.sqrt(variance[row]) + self.epsilon) | python reference implemenation of adam | 62599069e5267d203ee6cfa0 |
class ReportStatus: <NEW_LINE> <INDENT> def __init__(self, report, jobs): <NEW_LINE> <INDENT> self.__report = report <NEW_LINE> self.__jobs = jobs <NEW_LINE> <DEDENT> @property <NEW_LINE> def slurm_sbatches(self): <NEW_LINE> <INDENT> return bool(self.jobs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def report(self): <NEW_LINE> <INDENT> return self.__report <NEW_LINE> <DEDENT> @property <NEW_LINE> def jobs(self): <NEW_LINE> <INDENT> return self.__jobs <NEW_LINE> <DEDENT> @property <NEW_LINE> def job_ids(self): <NEW_LINE> <INDENT> return [job['id'] for job in self.__job_ids] <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> status = dict(benchmark=self._benchmarks_status(), succeeded=self.succeeded) <NEW_LINE> if self.slurm_sbatches: <NEW_LINE> <INDENT> status.update(sbatch=self.jobs) <NEW_LINE> <DEDENT> return status <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def succeeded(self): <NEW_LINE> <INDENT> ok = all(benchmark['succeeded'] for benchmark in self._benchmarks_status()) <NEW_LINE> ok &= all(job.get('exit_code', True) for job in self.jobs) <NEW_LINE> return ok <NEW_LINE> <DEDENT> def log(self, fmt): <NEW_LINE> <INDENT> if fmt == 'yaml': <NEW_LINE> <INDENT> yaml.dump(self.status, sys.stdout, default_flow_style=False) <NEW_LINE> <DEDENT> elif fmt == 'json': <NEW_LINE> <INDENT> json.dump(self.status, sys.stdout, indent=2) <NEW_LINE> print() <NEW_LINE> <DEDENT> elif fmt == 'log': <NEW_LINE> <INDENT> attrs = self.report.CONTEXT_ATTRS + ['succeeded'] <NEW_LINE> for benchmark in self.status['benchmark']: <NEW_LINE> <INDENT> fields = [field + '=' + str(benchmark[field]) for field in attrs] <NEW_LINE> print('benchmark', *fields) <NEW_LINE> <DEDENT> for job in self.jobs: <NEW_LINE> <INDENT> print('sbatch', *[k + '=' + str(v) for k, v in job.items()]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Unknown format: ' + fmt) <NEW_LINE> <DEDENT> <DEDENT> @listify <NEW_LINE> def _benchmarks_status(self): <NEW_LINE> <INDENT> roots = [] <NEW_LINE> if self.slurm_sbatches: <NEW_LINE> <INDENT> for sbatch in self.report.children.values(): <NEW_LINE> <INDENT> for tag in sbatch.children.values(): <NEW_LINE> <INDENT> assert len(tag.children) <= 1 <NEW_LINE> for root in tag.children.values(): <NEW_LINE> <INDENT> roots.append(root) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> roots.append(self.report) <NEW_LINE> <DEDENT> for root in roots: <NEW_LINE> <INDENT> for path, succeeded in root.collect('command_succeeded', with_path=True): <NEW_LINE> <INDENT> ctx = root.path_context(path) <NEW_LINE> ctx.update(succeeded=succeeded) <NEW_LINE> yield ctx | Build a dictionary reporting benchmarks execution status | 6259906944b2445a339b7542 |
class JSONLogWebFormatter(JSONLogFormatter): <NEW_LINE> <INDENT> def _format_log_object(self, record, request_util): <NEW_LINE> <INDENT> json_log_object = super(JSONLogWebFormatter, self)._format_log_object(record, request_util) <NEW_LINE> if "correlation_id" not in json_log_object: <NEW_LINE> <INDENT> json_log_object.update({ "correlation_id": request_util.get_correlation_id(within_formatter=True), }) <NEW_LINE> <DEDENT> return json_log_object | Formatter for web application log with correlation-id | 6259906999cbb53fe68326ab |
class Meta: <NEW_LINE> <INDENT> model = Career <NEW_LINE> exclude = ['created', 'modified', 'tiles', 'university', 'active'] | Defining serializer meta data. | 62599069baa26c4b54d50a6c |
class TensorDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, data_tensor, target_tensor): <NEW_LINE> <INDENT> assert data_tensor.size(0) == target_tensor.size(0) <NEW_LINE> self.data_tensor = data_tensor <NEW_LINE> self.target_tensor = target_tensor <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return self.data_tensor[index], self.target_tensor[index] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.data_tensor.size(0) | 包装数据和目标张量的数据集.
通过沿着第一个维度索引两个张量来恢复每个样本.
Args:
data_tensor (Tensor): 包含样本数据.
target_tensor (Tensor): 包含样本目标 (标签). | 625990692ae34c7f260ac8ae |
class ShipmentUnassignManualShow(ModelView): <NEW_LINE> <INDENT> __name__ = 'stock.shipment.unassign.manual.show' <NEW_LINE> moves = fields.One2Many( 'stock.shipment.assigned.move', None, "Moves", domain=[('move.id', 'in', Eval('assigned_moves'))], depends=['assigned_moves'], help="The moves to unassign.") <NEW_LINE> assigned_moves = fields.Many2Many( 'stock.move', None, None, "Assigned Moves") | Manually Unassign Shipment | 62599069796e427e5384ff3d |
@httpretty.activate <NEW_LINE> @disable_signal(api, 'thread_deleted') <NEW_LINE> @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True}) <NEW_LINE> class ThreadViewSetDeleteTest(DiscussionAPIViewTestMixin, ModuleStoreTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(ThreadViewSetDeleteTest, self).setUp() <NEW_LINE> self.url = reverse("thread-detail", kwargs={"thread_id": "test_thread"}) <NEW_LINE> self.thread_id = "test_thread" <NEW_LINE> <DEDENT> def test_basic(self): <NEW_LINE> <INDENT> self.register_get_user_response(self.user) <NEW_LINE> cs_thread = make_minimal_cs_thread({ "id": self.thread_id, "course_id": text_type(self.course.id), "username": self.user.username, "user_id": str(self.user.id), }) <NEW_LINE> self.register_get_thread_response(cs_thread) <NEW_LINE> self.register_delete_thread_response(self.thread_id) <NEW_LINE> response = self.client.delete(self.url) <NEW_LINE> self.assertEqual(response.status_code, 204) <NEW_LINE> self.assertEqual(response.content, b"") <NEW_LINE> self.assertEqual( urlparse(httpretty.last_request().path).path, "/api/v1/threads/{}".format(self.thread_id) ) <NEW_LINE> self.assertEqual(httpretty.last_request().method, "DELETE") <NEW_LINE> <DEDENT> def test_delete_nonexistent_thread(self): <NEW_LINE> <INDENT> self.register_get_thread_error_response(self.thread_id, 404) <NEW_LINE> response = self.client.delete(self.url) <NEW_LINE> self.assertEqual(response.status_code, 404) | Tests for ThreadViewSet delete | 62599069a219f33f346c7fce |
class Hero(NPC): <NEW_LINE> <INDENT> bullets_created = 0 <NEW_LINE> bullets = [] <NEW_LINE> shoot_wait = 0 <NEW_LINE> def process(self, doc): <NEW_LINE> <INDENT> shot_used = False <NEW_LINE> for item in doc['cmd_lst']: <NEW_LINE> <INDENT> if item['cmd'] == 'move': <NEW_LINE> <INDENT> x_step = y_step = 0 <NEW_LINE> if item['xd'] == 1: <NEW_LINE> <INDENT> x_step = self.speed <NEW_LINE> <DEDENT> elif item['xd'] == -1: <NEW_LINE> <INDENT> x_step = -self.speed <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x_step = 0 <NEW_LINE> <DEDENT> if item['yd'] == 1: <NEW_LINE> <INDENT> y_step = self.speed <NEW_LINE> <DEDENT> elif item['yd'] == -1: <NEW_LINE> <INDENT> y_step = -self.speed <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y_step = 0 <NEW_LINE> <DEDENT> self.move(x_step, y_step) <NEW_LINE> <DEDENT> elif item['cmd'] == 'shoot' and not shot_used: <NEW_LINE> <INDENT> if self.shoot_wait < 1: <NEW_LINE> <INDENT> self.shoot(item['x'], item['y']) <NEW_LINE> self.shoot_wait = self.reload_delay <NEW_LINE> shot_used = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.shoot_wait -= 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def shoot(self, x_target, y_target): <NEW_LINE> <INDENT> x, y = self.rect.center <NEW_LINE> dt = np.sqrt((x_target - x)**2 + (y_target - y)**2) <NEW_LINE> steps = dt / self.bullet_speed <NEW_LINE> x_step = (x_target - x) / steps <NEW_LINE> y_step = (y_target - y) / steps <NEW_LINE> bullet = HeroBullet(x, y, self.bullet_size, self.bullet_radius, self.screen_width, self.screen_height, self.bullet_speed, num=self.bullets_created, x_step=x_step, y_step=y_step) <NEW_LINE> self.bullets_created += 1 <NEW_LINE> self.bullets.append(bullet) | NPC teached by user | 6259906999cbb53fe68326ac |
class BadDataException(Exception): <NEW_LINE> <INDENT> pass | An exception raised when an argument comes in with improperly formatted or invalid data. | 62599069009cb60464d02cff |
class Messages(TLObject): <NEW_LINE> <INDENT> __slots__: List[str] = ["messages", "chats", "users"] <NEW_LINE> ID = 0x8c718e87 <NEW_LINE> QUALNAME = "types.messages.Messages" <NEW_LINE> def __init__(self, *, messages: List["raw.base.Message"], chats: List["raw.base.Chat"], users: List["raw.base.User"]) -> None: <NEW_LINE> <INDENT> self.messages = messages <NEW_LINE> self.chats = chats <NEW_LINE> self.users = users <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data: BytesIO, *args: Any) -> "Messages": <NEW_LINE> <INDENT> messages = TLObject.read(data) <NEW_LINE> chats = TLObject.read(data) <NEW_LINE> users = TLObject.read(data) <NEW_LINE> return Messages(messages=messages, chats=chats, users=users) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> data = BytesIO() <NEW_LINE> data.write(Int(self.ID, False)) <NEW_LINE> data.write(Vector(self.messages)) <NEW_LINE> data.write(Vector(self.chats)) <NEW_LINE> data.write(Vector(self.users)) <NEW_LINE> return data.getvalue() | This object is a constructor of the base type :obj:`~pyrogram.raw.base.messages.Messages`.
Details:
- Layer: ``122``
- ID: ``0x8c718e87``
Parameters:
messages: List of :obj:`Message <pyrogram.raw.base.Message>`
chats: List of :obj:`Chat <pyrogram.raw.base.Chat>`
users: List of :obj:`User <pyrogram.raw.base.User>`
See Also:
This object can be returned by 11 methods:
.. hlist::
:columns: 2
- :obj:`messages.GetMessages <pyrogram.raw.functions.messages.GetMessages>`
- :obj:`messages.GetHistory <pyrogram.raw.functions.messages.GetHistory>`
- :obj:`messages.Search <pyrogram.raw.functions.messages.Search>`
- :obj:`messages.SearchGlobal <pyrogram.raw.functions.messages.SearchGlobal>`
- :obj:`messages.GetUnreadMentions <pyrogram.raw.functions.messages.GetUnreadMentions>`
- :obj:`messages.GetRecentLocations <pyrogram.raw.functions.messages.GetRecentLocations>`
- :obj:`messages.GetScheduledHistory <pyrogram.raw.functions.messages.GetScheduledHistory>`
- :obj:`messages.GetScheduledMessages <pyrogram.raw.functions.messages.GetScheduledMessages>`
- :obj:`messages.GetReplies <pyrogram.raw.functions.messages.GetReplies>`
- :obj:`channels.GetMessages <pyrogram.raw.functions.channels.GetMessages>`
- :obj:`stats.GetMessagePublicForwards <pyrogram.raw.functions.stats.GetMessagePublicForwards>` | 625990694e4d562566373bcd |
class AT_076: <NEW_LINE> <INDENT> inspire = Summon(CONTROLLER, RandomMurloc()) | Murloc Knight | 62599069f548e778e596cd52 |
@characteristic.with_repr(["logfile"]) <NEW_LINE> class LogfileProgress(Base): <NEW_LINE> <INDENT> __tablename__ = "logfile_progress" <NEW_LINE> source_url = Column(String(100), primary_key=True) <NEW_LINE> current_key = Column(Integer, default=0, nullable=False) | Logfile import progress.
Columns:
source_url: logfile source url
current_key: the key of the next logfile event to import. | 6259906901c39578d7f14318 |
class UserViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> permission_classes = (UserPermissions,) <NEW_LINE> serializer_class = UserSerializer <NEW_LINE> queryset = User.objects.all() | User API view | 6259906916aa5153ce401ca0 |
class MyTcpServerFactory(Factory): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.numProtocols = 1 <NEW_LINE> print("Serveur twisted reception TCP lance\n") <NEW_LINE> <DEDENT> def buildProtocol(self, addr): <NEW_LINE> <INDENT> print("Nombre de protocol dans factory", self.numProtocols) <NEW_LINE> return MyTcpServer(self) | self ici sera self.factory dans les objets MyTcpServer. | 625990695fc7496912d48e4b |
class itkContourSpatialObjectPoint2(itkSpatialObjectPointPython.itkSpatialObjectPoint2): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> _itkContourSpatialObjectPointPython.itkContourSpatialObjectPoint2_swiginit(self,_itkContourSpatialObjectPointPython.new_itkContourSpatialObjectPoint2(*args)) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkContourSpatialObjectPointPython.delete_itkContourSpatialObjectPoint2 <NEW_LINE> def GetPickedPoint(self): <NEW_LINE> <INDENT> return _itkContourSpatialObjectPointPython.itkContourSpatialObjectPoint2_GetPickedPoint(self) <NEW_LINE> <DEDENT> def SetPickedPoint(self, *args): <NEW_LINE> <INDENT> return _itkContourSpatialObjectPointPython.itkContourSpatialObjectPoint2_SetPickedPoint(self, *args) <NEW_LINE> <DEDENT> def GetNormal(self): <NEW_LINE> <INDENT> return _itkContourSpatialObjectPointPython.itkContourSpatialObjectPoint2_GetNormal(self) <NEW_LINE> <DEDENT> def SetNormal(self, *args): <NEW_LINE> <INDENT> return _itkContourSpatialObjectPointPython.itkContourSpatialObjectPoint2_SetNormal(self, *args) | Proxy of C++ itkContourSpatialObjectPoint2 class | 625990692ae34c7f260ac8af |
class TestReplaceDataSource(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(self): <NEW_LINE> <INDENT> with open(os.path.join(os.getcwd(), 'replace_data_source.test.json')) as data_file: <NEW_LINE> <INDENT> self.request = json.load(data_file) <NEW_LINE> <DEDENT> self.temp_folder = tempfile.mkdtemp() <NEW_LINE> self.request['folder'] = self.temp_folder <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(self): <NEW_LINE> <INDENT> shutil.rmtree(self.temp_folder, False) <NEW_LINE> <DEDENT> def test_layer(self): <NEW_LINE> <INDENT> shutil.copy2(os.path.join(os.getcwd(), 'test-data', 'Cities.lyr'), self.temp_folder) <NEW_LINE> lyr_file = os.path.join(self.temp_folder, 'Cities.lyr') <NEW_LINE> self.request['params'][0]['response']['docs'][0]['path'] = lyr_file <NEW_LINE> __import__(self.request['task']) <NEW_LINE> old_workspace = "C:\\GISData\\MDB\\USA.mdb\\cities" <NEW_LINE> new_workspace = os.path.join(os.getcwd(), 'test-data', 'TestData_v10.gdb', 'cities') <NEW_LINE> self.request['params'][2]['value'] = old_workspace <NEW_LINE> self.request['params'][3]['value'] = new_workspace <NEW_LINE> getattr(sys.modules[self.request['task']], "execute")(self.request) <NEW_LINE> dsc = arcpy.Describe(lyr_file) <NEW_LINE> self.assertEquals(dsc.featureclass.catalogpath, os.path.join(os.path.dirname(new_workspace), 'cities')) <NEW_LINE> <DEDENT> def test_layer_backup_exists(self): <NEW_LINE> <INDENT> self.assertTrue(os.path.exists(os.path.join(self.temp_folder, 'Cities.lyr.bak'))) | Test case for Replace Data Source task. | 6259906966673b3332c31bc5 |
class BuildItem(Base): <NEW_LINE> <INDENT> __tablename__ = 'build_item' <NEW_LINE> host_id = Column('host_id', Integer, ForeignKey('host.machine_id', ondelete='CASCADE', name='build_item_host_fk'), nullable=False) <NEW_LINE> service_instance_id = Column(Integer, ForeignKey('service_instance.id', name='build_item_svc_inst_fk'), nullable=False) <NEW_LINE> __table_args__ = (PrimaryKeyConstraint(host_id, service_instance_id), Index('build_item_si_idx', service_instance_id)) | Identifies the service_instance bindings of a machine. | 625990697047854f46340b7d |
class MsiModifiedPlessey(Barcode): <NEW_LINE> <INDENT> codetype = 'msi' <NEW_LINE> aliases = ('msi-plessey', 'msi plessey', 'msi_plessey', 'msiplessey') <NEW_LINE> class _Renderer(LinearCodeRenderer): <NEW_LINE> <INDENT> default_options = dict( LinearCodeRenderer.default_options, height=1, includecheck=False, includecheckintext=False, includetext=False, textyoffset=-7, textsize=10) <NEW_LINE> def _code_bbox(self, codestring): <NEW_LINE> <INDENT> height = self.lookup_option('height') <NEW_LINE> if self.lookup_option('includecheck'): <NEW_LINE> <INDENT> return [0, 0, 3+(len(codestring)+2)*12+4, height*DPI] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [0, 0, 3+(len(codestring))*12+4, height*DPI] <NEW_LINE> <DEDENT> <DEDENT> def _text_bbox(self, codestring): <NEW_LINE> <INDENT> textyoffset = self.lookup_option('textyoffset') <NEW_LINE> textsize = self.lookup_option('textsize') <NEW_LINE> cminx, cminy, cmaxx, cmaxy = self._code_bbox(codestring) <NEW_LINE> return [cminx, textyoffset, cmaxx, textyoffset+textsize] <NEW_LINE> <DEDENT> def build_params(self, codestring): <NEW_LINE> <INDENT> params = super(MsiModifiedPlessey._Renderer, self).build_params(codestring) <NEW_LINE> cbbox = self._code_bbox(codestring) <NEW_LINE> if self.lookup_option('includetext'): <NEW_LINE> <INDENT> tbbox = self._text_bbox(codestring) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tbbox = cbbox <NEW_LINE> <DEDENT> params['bbox'] = "%d %d %d %d" % self._boundingbox(cbbox, tbbox) <NEW_LINE> return params <NEW_LINE> <DEDENT> <DEDENT> renderer = _Renderer | >>> bc = MsiModifiedPlessey()
>>> bc # doctest: +ELLIPSIS
<....MsiModifiedPlessey object at ...>
>>> print(bc.render_ps_code('0123456789')) # doctest: +ELLIPSIS
%!PS-Adobe-2.0
%%Pages: (attend)
%%Creator: Elaphe powered by barcode.ps
%%BoundingBox: 0 0 127 72
%%LanguageLevel: 2
%%EndComments
...
gsave
0 0 moveto
1.000000 1.000000 scale
<30313233343536373839>
<>
/msi /uk.co.terryburton.bwipp findresource exec
grestore
showpage
<BLANKLINE>
>>> bc.render('0123456789', options=dict(includecheck=True, includetext=True), scale=2, margin=1) # doctest: +ELLIPSIS
<PIL.EpsImagePlugin.EpsImageFile ... at ...>
>>> # _.show() | 62599069d268445f2663a741 |
class MediaContainerView(object): <NEW_LINE> <INDENT> def __init__(self, context, request): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.request = request <NEW_LINE> <DEDENT> def media_items(self, media_type=None): <NEW_LINE> <INDENT> provider = IMediaProvider(self.context) <NEW_LINE> provider.media_type = media_type <NEW_LINE> videos = [] <NEW_LINE> for mfile in provider.media_items: <NEW_LINE> <INDENT> videos.append(mfile) <NEW_LINE> <DEDENT> return videos | Media Container View
| 62599069aad79263cf42ff7d |
class WhiteListElement(object): <NEW_LINE> <INDENT> asString = None <NEW_LINE> def __init__(self, elementAsString): <NEW_LINE> <INDENT> self.asString = elementAsString <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.asString <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return u"WhiteListElement(\"{0}\")".format(self.asString) <NEW_LINE> <DEDENT> def test(self, other): <NEW_LINE> <INDENT> return False | A class that represents a domain, IP address range or network segment that has been verified as not being suspicious. | 625990691f5feb6acb1643b5 |
class Httpd(SelectSocket.SelectSocketServer): <NEW_LINE> <INDENT> def __init__(self, iface=None, port=None, root=None): <NEW_LINE> <INDENT> super(Httpd, self).__init__(iface, port) <NEW_LINE> log("HTTP 服务启动, 服务端口:", port) <NEW_LINE> self.path_route = dict() <NEW_LINE> self.root = './www/' if root is None else root <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> super(Httpd, self).start_service() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> super(Httpd, self).stop_service() <NEW_LINE> <DEDENT> def accept(self, fds): <NEW_LINE> <INDENT> peer, address = fds.accept() <NEW_LINE> log("新连接", address) <NEW_LINE> conn = HttpConnection(self, peer, address, self.root) <NEW_LINE> loop = get_select_loop() <NEW_LINE> loop.schedule_read(conn.fds, conn.readable) <NEW_LINE> <DEDENT> def route(self, r_path, process_protocol): <NEW_LINE> <INDENT> r = re.compile(r_path) <NEW_LINE> d = { 'r_path': r, 'protocol': process_protocol } <NEW_LINE> self.path_route[r_path] = d <NEW_LINE> <DEDENT> def route_match(self, method, url, query_string): <NEW_LINE> <INDENT> for _, route in self.path_route.items(): <NEW_LINE> <INDENT> r = route['r_path'] <NEW_LINE> match_result = r.match(url) <NEW_LINE> if match_result in {None, False}: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> return route['protocol'], match_result <NEW_LINE> <DEDENT> return HttpRespons(code=404), None | httpd | 625990692ae34c7f260ac8b0 |
class HaarCascade(): <NEW_LINE> <INDENT> _mCascade = None <NEW_LINE> _mName = None <NEW_LINE> _cache = {} <NEW_LINE> _fhandle = None <NEW_LINE> def __init__(self, fname=None, name=None): <NEW_LINE> <INDENT> if( name is None ): <NEW_LINE> <INDENT> self._mName = fname <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._mName = name <NEW_LINE> <DEDENT> if fname is not None: <NEW_LINE> <INDENT> if os.path.exists(fname): <NEW_LINE> <INDENT> self._fhandle = os.path.abspath(fname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fhandle = os.path.join(LAUNCH_PATH, 'Features','HaarCascades',fname) <NEW_LINE> if (not os.path.exists(self._fhandle)): <NEW_LINE> <INDENT> logger.warning("Could not find Haar Cascade file " + fname) <NEW_LINE> logger.warning("Try running the function img.listHaarFeatures() to see what is available") <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> self._mCascade = cv.Load(self._fhandle) <NEW_LINE> if HaarCascade._cache.has_key(self._fhandle): <NEW_LINE> <INDENT> self._mCascade = HaarCascade._cache[self._fhandle] <NEW_LINE> return <NEW_LINE> <DEDENT> HaarCascade._cache[self._fhandle] = self._mCascade <NEW_LINE> <DEDENT> <DEDENT> def load(self, fname=None, name = None): <NEW_LINE> <INDENT> if( name is None ): <NEW_LINE> <INDENT> self._mName = fname <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._mName = name <NEW_LINE> <DEDENT> if fname is not None: <NEW_LINE> <INDENT> if os.path.exists(fname): <NEW_LINE> <INDENT> self._fhandle = os.path.abspath(fname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fhandle = os.path.join(LAUNCH_PATH, 'Features','HaarCascades',fname) <NEW_LINE> if (not os.path.exists(self._fhandle)): <NEW_LINE> <INDENT> logger.warning("Could not find Haar Cascade file " + fname) <NEW_LINE> logger.warning("Try running the function img.listHaarFeatures() to see what is available") <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> self._mCascade = cv.Load(self._fhandle) <NEW_LINE> if HaarCascade._cache.has_key(self._fhandle): <NEW_LINE> <INDENT> self._mCascade = HaarCascade._cache[fname] <NEW_LINE> return <NEW_LINE> <DEDENT> HaarCascade._cache[self._fhandle] = self._mCascade <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning("No file path mentioned.") <NEW_LINE> <DEDENT> <DEDENT> def getCascade(self): <NEW_LINE> <INDENT> return self._mCascade <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> return self._mName <NEW_LINE> <DEDENT> def setName(self,name): <NEW_LINE> <INDENT> self._mName = name <NEW_LINE> <DEDENT> def getFHandle(self): <NEW_LINE> <INDENT> return self._fhandle | This class wraps HaarCascade files for the findHaarFeatures file.
To use the class provide it with the path to a Haar cascade XML file and
optionally a name. | 62599069d6c5a102081e38f0 |
class Course(object): <NEW_LINE> <INDENT> def __init__(self, client, course_id): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.course_id = unicode(course_id) <NEW_LINE> <DEDENT> def enrollment(self, demographic=None, start_date=None, end_date=None, data_format=DF.JSON): <NEW_LINE> <INDENT> path = 'courses/{0}/enrollment/'.format(self.course_id) <NEW_LINE> if demographic: <NEW_LINE> <INDENT> path += '{0}/'.format(demographic) <NEW_LINE> <DEDENT> params = {} <NEW_LINE> if start_date: <NEW_LINE> <INDENT> params['start_date'] = start_date <NEW_LINE> <DEDENT> if end_date: <NEW_LINE> <INDENT> params['end_date'] = end_date <NEW_LINE> <DEDENT> querystring = urllib.urlencode(params) <NEW_LINE> if querystring: <NEW_LINE> <INDENT> path += '?{0}'.format(querystring) <NEW_LINE> <DEDENT> return self.client.get(path, data_format=data_format) <NEW_LINE> <DEDENT> def activity(self, activity_type=AT.ANY, start_date=None, end_date=None, data_format=DF.JSON): <NEW_LINE> <INDENT> if not activity_type: <NEW_LINE> <INDENT> raise InvalidRequestError('activity_type cannot be None.') <NEW_LINE> <DEDENT> params = { 'activity_type': activity_type } <NEW_LINE> if start_date: <NEW_LINE> <INDENT> params['start_date'] = start_date <NEW_LINE> <DEDENT> if end_date: <NEW_LINE> <INDENT> params['end_date'] = end_date <NEW_LINE> <DEDENT> path = 'courses/{0}/activity/'.format(self.course_id) <NEW_LINE> querystring = urllib.urlencode(params) <NEW_LINE> path += '?{0}'.format(querystring) <NEW_LINE> return self.client.get(path, data_format=data_format) <NEW_LINE> <DEDENT> def recent_activity(self, activity_type=AT.ANY, data_format=DF.JSON): <NEW_LINE> <INDENT> warnings.warn('recent_activity has been deprecated! Use activity instead.', DeprecationWarning) <NEW_LINE> path = 'courses/{0}/recent_activity/?activity_type={1}'.format(self.course_id, activity_type) <NEW_LINE> return self.client.get(path, data_format=data_format) | Course-related analytics. | 625990694a966d76dd5f06bd |
class QueueProcessor(object): <NEW_LINE> <INDENT> def __init__(self, queueName, pollUrl, scoreUrl, apiKey, graders={}, pollTime=10, pollTimeout=30): <NEW_LINE> <INDENT> self.graders = {} <NEW_LINE> for (partNames, grader) in graders.iteritems(): <NEW_LINE> <INDENT> if isinstance(partNames, basestring): <NEW_LINE> <INDENT> self.graders[partNames] = grader <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for partName in partNames: <NEW_LINE> <INDENT> self.graders[partName] = grader <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.pollUrl = pollUrl <NEW_LINE> self.scoreUrl = scoreUrl <NEW_LINE> self.queueName = queueName <NEW_LINE> self.apiKey = apiKey <NEW_LINE> self.pollTime = pollTime <NEW_LINE> self.pollTimeout = pollTimeout <NEW_LINE> self.requestHeaders = { 'x-api-key': self.apiKey } <NEW_LINE> <DEDENT> def pollForever(self): <NEW_LINE> <INDENT> socket.setdefaulttimeout(self.pollTimeout) <NEW_LINE> logging.info("Starting queue processor loop for %s" % (sorted(self.graders.keys()))) <NEW_LINE> while(1): <NEW_LINE> <INDENT> logging.info("Polling %s" % self.pollUrl) <NEW_LINE> data = self.__poll() <NEW_LINE> if not data: <NEW_LINE> <INDENT> logging.error("Http error, sleeping") <NEW_LINE> time.sleep(self.pollTime) <NEW_LINE> continue <NEW_LINE> <DEDENT> data = json.load(data) <NEW_LINE> if 'submission' in data and data['submission']: <NEW_LINE> <INDENT> logging.info("Found a submission!") <NEW_LINE> self.__handleSubmission(QueueSubmission(data['submission'])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.info("No submissions found...") <NEW_LINE> time.sleep(self.pollTime) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __poll(self): <NEW_LINE> <INDENT> values = {'queue' : self.queueName} <NEW_LINE> data = urllib.urlencode(values) <NEW_LINE> req = urllib2.Request(self.pollUrl, data, self.requestHeaders) <NEW_LINE> try: <NEW_LINE> <INDENT> response = urllib2.urlopen(req) <NEW_LINE> return response <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logging.exception("Exception during poll!") <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> def __handleSubmission(self, submission): <NEW_LINE> <INDENT> if submission.partId in self.graders: <NEW_LINE> <INDENT> logging.info("Grading Submission %s" % submission) <NEW_LINE> try: <NEW_LINE> <INDENT> submissionGrade = self.graders[submission.partId](submission) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logging.exception("Unhandled exception while grading!") <NEW_LINE> submissionGrade = SubmissionGrade.errorGrade("Unhandled exception while grading...") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logging.error("No grader for submission %s" % submission) <NEW_LINE> submissionGrade = SubmissionGrade.errorGrade("No graders for part %s" % submission.partId) <NEW_LINE> <DEDENT> self.__submitGrade(submission, submissionGrade) <NEW_LINE> <DEDENT> def __submitGrade(self, submission, submissionGrade): <NEW_LINE> <INDENT> logging.info("Submitting %s to %s" % (submissionGrade, self.scoreUrl)) <NEW_LINE> values = { 'api_state': submission.apiState, 'score': str(submissionGrade.score), 'feedback': submissionGrade.feedback, 'feedback-after-hard-deadline': submissionGrade.hardDeadlineFeedback, 'feedback_after_soft_close_time': submissionGrade.softDeadlineFeedback } <NEW_LINE> try: <NEW_LINE> <INDENT> data = urllib.urlencode(values) <NEW_LINE> req = urllib2.Request(self.scoreUrl, data, self.requestHeaders) <NEW_LINE> response = urllib2.urlopen(req) <NEW_LINE> return response.read() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logging.exception("Unhandled exception while submitting grade!") <NEW_LINE> return None | Polls coursera for solutions, posts the grades. | 6259906991f36d47f2231a73 |
class DecoderRNN(Decoder): <NEW_LINE> <INDENT> def __init__(self, input_size, emb_size, hidden_size, dropout=.3, pad_idx=0): <NEW_LINE> <INDENT> super(DecoderRNN, self).__init__(input_size, emb_size, hidden_size, pad_idx) <NEW_LINE> output_size = input_size <NEW_LINE> self.dropout_layer = nn.Dropout(p=dropout) <NEW_LINE> self.output_layer = nn.Linear(hidden_size + 2 * hidden_size + emb_size, output_size, bias=False) <NEW_LINE> <DEDENT> def _forward_step(self, prev_embed, encoder_hidden, src, src_length, hidden): <NEW_LINE> <INDENT> prev_dec_state = hidden.squeeze().unsqueeze(1) <NEW_LINE> context, _ = self.attention( dec_state=prev_dec_state, enc_state=encoder_hidden, src_length=src_length) <NEW_LINE> rnn_input = torch.cat([prev_embed, context], dim=2) <NEW_LINE> output, hidden = self.rnn(rnn_input, hidden) <NEW_LINE> output = torch.cat([prev_embed, output, context], dim=2) <NEW_LINE> output = torch.log_softmax(self.output_layer(self.dropout_layer(output)), dim=-1) <NEW_LINE> return output, hidden | Decodes a sequence of words given an initial context vector
representing the input sequence and using a Bahdanau (MLP) attention. | 62599069009cb60464d02d01 |
class UserPermissionError(Exception): <NEW_LINE> <INDENT> pass | User has no permission to make this change | 62599069a8370b77170f1b8d |
class gtrend(extract): <NEW_LINE> <INDENT> def __init__(self, keyword:str, start:str, end:str) -> None: <NEW_LINE> <INDENT> self.keyword = keyword <NEW_LINE> super().__init__(start, end) <NEW_LINE> self.connect_API() <NEW_LINE> <DEDENT> def connect_API(self): <NEW_LINE> <INDENT> self.pytrend = TrendReq() <NEW_LINE> <DEDENT> def collect_data(self): <NEW_LINE> <INDENT> self.pytrend.build_payload(kw_list=['{}'.format(self.keyword)]) <NEW_LINE> data = self.pytrend.interest_over_time().reset_index() <NEW_LINE> df = data[['date', '{}'.format(self.keyword)]] <NEW_LINE> df_trend = df.loc[df.index.repeat(7)] <NEW_LINE> df_trend['date'] = pd.to_datetime(df_trend['date']) <NEW_LINE> min_date = df_trend['date'].min() <NEW_LINE> max_date = df_trend['date'].max()+timedelta(days=6) <NEW_LINE> df_trend['GT_date'] = pd.date_range(start=min_date, end=max_date).tolist() <NEW_LINE> sd = datetime.strptime(self.start, "%Y-%m-%d").date() <NEW_LINE> ed = datetime.strptime(self.end, "%Y-%m-%d").date() <NEW_LINE> df_trend = df_trend[(df_trend['GT_date'].dt.date>=sd)&(df_trend['GT_date'].dt.date<=ed)] <NEW_LINE> data_trend = df_trend[['GT_date', '{}'.format(keyword)]] <NEW_LINE> return data_trend | Google trend data extraction.
The class connects to Google trend API for data download
and returns the processed data in DataFrame.
Attributes:
keyword: (str) The word of interest for trend data download.
start: (str) The start date of extracted data.
end: (str) The end date of extracted data. | 62599069379a373c97d9a7e7 |
class Tests(IMP.test.TestCase): <NEW_LINE> <INDENT> def _test_allp(self): <NEW_LINE> <INDENT> m = IMP.Model() <NEW_LINE> ps = [] <NEW_LINE> psr = [] <NEW_LINE> for i in range(0, 50): <NEW_LINE> <INDENT> p = IMP.Particle(m) <NEW_LINE> ps.append(p) <NEW_LINE> if i % 5 == 0: <NEW_LINE> <INDENT> psr.append(p) <NEW_LINE> <DEDENT> <DEDENT> for p in psr: <NEW_LINE> <INDENT> ps.remove(p) <NEW_LINE> <DEDENT> for p0 in lp.get_particles(): <NEW_LINE> <INDENT> for pr in psr: <NEW_LINE> <INDENT> self.assertNotEqual(p0, pr) <NEW_LINE> <DEDENT> <DEDENT> print("bye0") <NEW_LINE> <DEDENT> def test_allp2(self): <NEW_LINE> <INDENT> m = IMP.Model() <NEW_LINE> ps = [] <NEW_LINE> psr = [] <NEW_LINE> for i in range(0, 50): <NEW_LINE> <INDENT> p = IMP.Particle(m) <NEW_LINE> ps.append(p) <NEW_LINE> if i % 5 == 0: <NEW_LINE> <INDENT> psr.append(p) <NEW_LINE> <DEDENT> <DEDENT> for p in psr: <NEW_LINE> <INDENT> ps.remove(p) <NEW_LINE> <DEDENT> for p in psr: <NEW_LINE> <INDENT> m.remove_particle(p.get_index()) <NEW_LINE> <DEDENT> print("bye") | Tests for all pairs pair container | 625990699c8ee82313040d6c |
class BasicView(ElementaryView): <NEW_LINE> <INDENT> isexecutable = False <NEW_LINE> def __init__(self, context, request, parent=None, wizard=None, stepid=None, **kwargs): <NEW_LINE> <INDENT> super(BasicView, self).__init__(context, request, parent, wizard, stepid, **kwargs) <NEW_LINE> self.finished_successfully = True <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> return {} | Basic view | 6259906901c39578d7f14319 |
class EnableJITTracking(PolyJITConfig): <NEW_LINE> <INDENT> def __init__(self, *args, project=None, **kwargs): <NEW_LINE> <INDENT> super(EnableJITTracking, self).__init__( *args, project=project, **kwargs) <NEW_LINE> self.project = project <NEW_LINE> <DEDENT> def __call__(self, binary_command, *args, **kwargs): <NEW_LINE> <INDENT> pjit_args = ["-polli-track"] <NEW_LINE> if self.project is None: <NEW_LINE> <INDENT> LOG.error("Project was not set." " Database activation will be invalid.") <NEW_LINE> <DEDENT> with self.argv(PJIT_ARGS=pjit_args): <NEW_LINE> <INDENT> return self.call_next(binary_command, *args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Enable tracking for PolyJIT" | The run and given extensions store polli's statistics to the database. | 62599069adb09d7d5dc0bd33 |
@api.route('/<string:cveId>') <NEW_LINE> @api.doc(params={'cveId': 'Id of CVE item'}) <NEW_LINE> class CVE(Resource): <NEW_LINE> <INDENT> def __init__(self, Resource): <NEW_LINE> <INDENT> self.api = api <NEW_LINE> <DEDENT> @api.doc(description='Get Cve by cve id. \n\n ' '* `cveId` format: CVE-0000-0000 \n\n' '* [Test query] `cveId`=CVE-2016-1824 \n\n') <NEW_LINE> @api.response(200, 'Success', apiModel.cveModel) <NEW_LINE> @api.response(400, 'Parameter Validation Error', apiModel.paraErrorModel) <NEW_LINE> def get(self, cveId): <NEW_LINE> <INDENT> if not regBox.checkCveId(cveId): <NEW_LINE> <INDENT> return excpHandler.handle_validation_exception('cveId') <NEW_LINE> <DEDENT> with open(fileDir+'/data/cve_result.json') as data_file: <NEW_LINE> <INDENT> result = json.load(data_file) <NEW_LINE> <DEDENT> if len(result) == 0: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return result | CVE with cveId | 6259906921bff66bcd72442f |
class TupelTest(unittest.TestCase): <NEW_LINE> <INDENT> def testCreate(self): <NEW_LINE> <INDENT> a = ('a', 'beh', 1, False, None, 'z') <NEW_LINE> self.assertEqual(6, len(a)) <NEW_LINE> self.assertEqual('a', a[0]) <NEW_LINE> self.assertEqual(0, a[3]) <NEW_LINE> self.assertEqual('z', a[-1]) <NEW_LINE> self.assertEqual(('beh', 1), a[1:3]) <NEW_LINE> self.assertEqual(('z',), a[5:]) <NEW_LINE> self.assertEqual(('a',), a[:1]) <NEW_LINE> self.assertEqual(a, a[:]) <NEW_LINE> b = (1,) <NEW_LINE> b = b + (2,) <NEW_LINE> self.assertEqual((1,2), b) <NEW_LINE> (c1, c2) = b <NEW_LINE> self.assertEqual(1, c1) <NEW_LINE> self.assertEqual(2, c2) <NEW_LINE> <DEDENT> def testSearch(self): <NEW_LINE> <INDENT> a = (1,4,2,3,4) <NEW_LINE> self.assertEqual(2, a.count(4)) <NEW_LINE> self.assertTrue(3 in a) <NEW_LINE> self.assertEqual(2, a.index(2)) <NEW_LINE> <DEDENT> def testListsAsBooleans(self): <NEW_LINE> <INDENT> self.assertTrue((False,)) <NEW_LINE> self.assertFalse(()) <NEW_LINE> <DEDENT> def testConvert(self): <NEW_LINE> <INDENT> a = (1,2,3) <NEW_LINE> t = tuple(a) <NEW_LINE> a2 = list(t) <NEW_LINE> self.assertTrue(isinstance(t, tuple)) <NEW_LINE> self.assertTrue(isinstance(a2, list)) | Tupel sind read-only Listen | 6259906916aa5153ce401ca2 |
class CardsEnoughTurn(PlayerTurn): <NEW_LINE> <INDENT> pass | Карт достаточно. | 62599069435de62698e9d5d4 |
class Material(object): <NEW_LINE> <INDENT> def __init__(self, description, fu, fy, E, poisson_ratio = 0.3): <NEW_LINE> <INDENT> self.description = description <NEW_LINE> self.fu = fu <NEW_LINE> self.fy = fy <NEW_LINE> self.E = E <NEW_LINE> self.poisson_ratio = poisson_ratio <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string = "" <NEW_LINE> string += "Material description: %s\n" % (self.description,) <NEW_LINE> string += "fu = %.1f MPa\n" % (self.fu,) <NEW_LINE> string += "fy = %.1f MPa\n" % (self.fy,) <NEW_LINE> string += "E = %d MPa\n" % (self.E,) <NEW_LINE> string += "PR = %s (Poisson's ratio)\n" % (str(self.poisson_ratio),) <NEW_LINE> return string <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Material at %s>" % (hex(id(self)),) | Class describes steel material properties. | 62599069167d2b6e312b8172 |
class JournalEntryParser(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def entry_to_log_event(entry): <NEW_LINE> <INDENT> time = entry['_SOURCE_REALTIME_TIMESTAMP'].timestamp() <NEW_LINE> hw_id = "" if snowflake.snowflake() is None else snowflake.snowflake() <NEW_LINE> int_map = {'exit_status': entry['EXIT_STATUS']} <NEW_LINE> normal_map = {'unit': entry['UNIT'], 'exit_code': entry["EXIT_CODE"]} <NEW_LINE> return LogEntry(category=SERVICE_EXIT_CATEGORY, time=int(time), hw_id=hw_id, normal_map=normal_map, int_map=int_map) | Utility class for parsing journalctl entries into log events for scribe | 625990697c178a314d78e7d0 |
class Dpad(InputDevice): <NEW_LINE> <INDENT> def __init__(self, name, up, down, left, right): <NEW_LINE> <INDENT> super(Dpad, self).__init__(name) <NEW_LINE> self.last_direction = 1, 0 <NEW_LINE> self.default = 0, 0, 0, 0 <NEW_LINE> self.up = up <NEW_LINE> self.down = down <NEW_LINE> self.left = left <NEW_LINE> self.right = right <NEW_LINE> <DEDENT> @property <NEW_LINE> def buttons(self): <NEW_LINE> <INDENT> return self.up, self.down, self.left, self.right <NEW_LINE> <DEDENT> @property <NEW_LINE> def held(self): <NEW_LINE> <INDENT> return self.get_dominant().held <NEW_LINE> <DEDENT> def get_dominant(self): <NEW_LINE> <INDENT> u, d, l, r = self.buttons <NEW_LINE> dominant = sorted([u, d, l, r], key=lambda b: b.held * -1)[0] <NEW_LINE> return dominant <NEW_LINE> <DEDENT> def check(self): <NEW_LINE> <INDENT> return self.get_dominant().check() <NEW_LINE> <DEDENT> def get_input(self): <NEW_LINE> <INDENT> return tuple([b.get_input() for b in self.buttons]) <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> u, d, l, r = super(Dpad, self).get_value() <NEW_LINE> x, y = 0, 0 <NEW_LINE> x -= int(l) <NEW_LINE> x += int(r) <NEW_LINE> y += int(d) <NEW_LINE> y -= int(u) <NEW_LINE> return x, y <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> for b in self.buttons: <NEW_LINE> <INDENT> b.update() <NEW_LINE> <DEDENT> x, y = self.get_value() <NEW_LINE> if (x, y) != (0, 0): <NEW_LINE> <INDENT> self.last_direction = x, y | A Dpad object represents an input device that can input 8 discrete directions through
a combination of four individual buttons, one for up, down, left, and right. | 62599069ac7a0e7691f73cb0 |
class InstrumentModelImpl(ResourceSimpleImpl): <NEW_LINE> <INDENT> def on_simpl_init(self): <NEW_LINE> <INDENT> self.instrument_agent = InstrumentAgentImpl(self.clients) <NEW_LINE> self.instrument_device = InstrumentDeviceImpl(self.clients) <NEW_LINE> self.policy = ModelPolicy(self.clients) <NEW_LINE> self.add_lce_precondition(LCE.PLAN, self.policy.lce_precondition_plan) <NEW_LINE> self.add_lce_precondition(LCE.DEVELOP, self.policy.lce_precondition_develop) <NEW_LINE> self.add_lce_precondition(LCE.INTEGRATE, self.policy.lce_precondition_integrate) <NEW_LINE> self.add_lce_precondition(LCE.DEPLOY, self.policy.lce_precondition_deploy) <NEW_LINE> self.add_lce_precondition(LCE.RETIRE, self.policy.lce_precondition_retire) <NEW_LINE> <DEDENT> def _primary_object_name(self): <NEW_LINE> <INDENT> return RT.InstrumentModel <NEW_LINE> <DEDENT> def _primary_object_label(self): <NEW_LINE> <INDENT> return "instrument_model" <NEW_LINE> <DEDENT> def lcs_precondition_retired(self, instrument_model_id): <NEW_LINE> <INDENT> if 0 < self.instrument_agent.find_having_model(instrument_model_id): <NEW_LINE> <INDENT> return "Can't retire an instrument_model still associated to instrument agent(s)" <NEW_LINE> <DEDENT> if 0 < self.instrument_device.find_having_model(instrument_model_id): <NEW_LINE> <INDENT> return "Can't retire an instrument_model still associated to instrument_device(s)" <NEW_LINE> <DEDENT> return "" | @brief resource management for InstrumentModel resources | 62599069cb5e8a47e493cd68 |
class Collections(enum.Enum): <NEW_LINE> <INDENT> OPERATIONS = ( 'operations', 'operations/{operationsId}', {}, [u'operationsId'] ) <NEW_LINE> ORGANIZATIONS = ( 'organizations', 'organizations/{organizationsId}', {}, [u'organizationsId'] ) <NEW_LINE> PROJECTS = ( 'projects', 'projects/{projectId}', {}, [u'projectId'] ) <NEW_LINE> def __init__(self, collection_name, path, flat_paths, params): <NEW_LINE> <INDENT> self.collection_name = collection_name <NEW_LINE> self.path = path <NEW_LINE> self.flat_paths = flat_paths <NEW_LINE> self.params = params | Collections for all supported apis. | 625990697047854f46340b7e |
class CheckConfigNoReplace(GenericCheckBase): <NEW_LINE> <INDENT> def __init__(self, base): <NEW_LINE> <INDENT> GenericCheckBase.__init__(self, base) <NEW_LINE> self.url = 'http://fedoraproject.org/wiki/' 'Packaging/Guidelines#Configuration_files' <NEW_LINE> self.text = '%config files are marked noreplace or the reason' ' is justified.' <NEW_LINE> self.automatic = True <NEW_LINE> self.type = 'MUST' <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> rc = self.NA <NEW_LINE> bad_lines = [] <NEW_LINE> extra = None <NEW_LINE> for pkg in self.spec.packages: <NEW_LINE> <INDENT> for line in self.spec.get_files(pkg): <NEW_LINE> <INDENT> if line.startswith('%config'): <NEW_LINE> <INDENT> if not line.startswith('%config(noreplace)'): <NEW_LINE> <INDENT> bad_lines.append(line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rc = self.PASS <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if bad_lines: <NEW_LINE> <INDENT> extra = "No (noreplace) in " + ' '.join(bad_lines) <NEW_LINE> rc = self.PENDING <NEW_LINE> <DEDENT> self.set_passed(rc, extra) | '%config files are marked noreplace or reason justified. | 625990697047854f46340b7f |
class Concat(AtomicFunction): <NEW_LINE> <INDENT> def __init__(self, dim=0, **kwargs): <NEW_LINE> <INDENT> self.__dim = dim <NEW_LINE> super(Concat, self).__init__(Out=1, **kwargs) <NEW_LINE> <DEDENT> def fn(self, *args): <NEW_LINE> <INDENT> return torch.cat(args, dim=self.__dim) | A wrapper around torch.cat | 625990693539df3088ecda69 |
class GroupSerializer(serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> name = serializers.SerializerMethodField('get_group_name') <NEW_LINE> type = serializers.SerializerMethodField('get_group_type') <NEW_LINE> data = serializers.SerializerMethodField('get_group_data') <NEW_LINE> def get_group_name(self, group): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> group_profile = group.groupprofile <NEW_LINE> if group_profile and group_profile.name: <NEW_LINE> <INDENT> return group_profile.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return group.name <NEW_LINE> <DEDENT> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return group.name <NEW_LINE> <DEDENT> <DEDENT> def get_group_type(self, group): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> group_profile = group.groupprofile <NEW_LINE> return group_profile.group_type <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_group_data(self, group): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> group_profile = group.groupprofile <NEW_LINE> if group_profile.data: <NEW_LINE> <INDENT> return json.loads(group_profile.data) <NEW_LINE> <DEDENT> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Group <NEW_LINE> fields = ('id', 'url', 'name', 'type', 'data') | Serializer for model interactions | 625990691f5feb6acb1643b7 |
class LogInForm(wtf.Form): <NEW_LINE> <INDENT> username = wtf.TextField('Username: ',[validators.Required()]) <NEW_LINE> password = wtf.PasswordField('Password: ',[validators.Required()]) | This is the Log In form
.. method:: LogInForm(username, password)
:param username: Username of user
:type username: unicode
:param password: Password of user
:type password: unicode
:rtype: Form instance | 625990695fdd1c0f98e5f74f |
class AppOnboardingRequest(Model): <NEW_LINE> <INDENT> def __init__(self, name: str=None, version: str=None, provider: str=None, checksum: str=None, app_package_path: str=None, user_defined_data: UserDefinedDatadef=None): <NEW_LINE> <INDENT> self.swagger_types = { 'name': str, 'version': str, 'provider': str, 'checksum': str, 'app_package_path': str, 'user_defined_data': UserDefinedDatadef } <NEW_LINE> self.attribute_map = { 'name': 'name', 'version': 'version', 'provider': 'provider', 'checksum': 'checksum', 'app_package_path': 'appPackagePath', 'user_defined_data': 'userDefinedData' } <NEW_LINE> self._name = name <NEW_LINE> self._version = version <NEW_LINE> self._provider = provider <NEW_LINE> self._checksum = checksum <NEW_LINE> self._app_package_path = app_package_path <NEW_LINE> self._user_defined_data = user_defined_data <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'AppOnboardingRequest': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name: str): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `name`, must not be `None`") <NEW_LINE> <DEDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def version(self) -> str: <NEW_LINE> <INDENT> return self._version <NEW_LINE> <DEDENT> @version.setter <NEW_LINE> def version(self, version: str): <NEW_LINE> <INDENT> if version is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `version`, must not be `None`") <NEW_LINE> <DEDENT> self._version = version <NEW_LINE> <DEDENT> @property <NEW_LINE> def provider(self) -> str: <NEW_LINE> <INDENT> return self._provider <NEW_LINE> <DEDENT> @provider.setter <NEW_LINE> def provider(self, provider: str): <NEW_LINE> <INDENT> if provider is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `provider`, must not be `None`") <NEW_LINE> <DEDENT> self._provider = provider <NEW_LINE> <DEDENT> @property <NEW_LINE> def checksum(self) -> str: <NEW_LINE> <INDENT> return self._checksum <NEW_LINE> <DEDENT> @checksum.setter <NEW_LINE> def checksum(self, checksum: str): <NEW_LINE> <INDENT> if checksum is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `checksum`, must not be `None`") <NEW_LINE> <DEDENT> self._checksum = checksum <NEW_LINE> <DEDENT> @property <NEW_LINE> def app_package_path(self) -> str: <NEW_LINE> <INDENT> return self._app_package_path <NEW_LINE> <DEDENT> @app_package_path.setter <NEW_LINE> def app_package_path(self, app_package_path: str): <NEW_LINE> <INDENT> if app_package_path is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `app_package_path`, must not be `None`") <NEW_LINE> <DEDENT> self._app_package_path = app_package_path <NEW_LINE> <DEDENT> @property <NEW_LINE> def user_defined_data(self) -> UserDefinedDatadef: <NEW_LINE> <INDENT> return self._user_defined_data <NEW_LINE> <DEDENT> @user_defined_data.setter <NEW_LINE> def user_defined_data(self, user_defined_data: UserDefinedDatadef): <NEW_LINE> <INDENT> self._user_defined_data = user_defined_data | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 625990698e7ae83300eea858 |
class TestAdd2UsersWithSameUsername(testLib.RestTestCase): <NEW_LINE> <INDENT> def assertResponse(self, respData, count = None, errCode = testLib.RestTestCase.SUCCESS): <NEW_LINE> <INDENT> expected = { 'errCode' : errCode } <NEW_LINE> if count is not None: <NEW_LINE> <INDENT> expected['count'] = count <NEW_LINE> <DEDENT> self.assertDictEqual(expected, respData) <NEW_LINE> <DEDENT> def testAddExists(self): <NEW_LINE> <INDENT> respData = self.makeRequest("/users/add", method="POST", data = { 'user' : 'user1', 'password' : 'password'} ) <NEW_LINE> self.assertResponse(respData, count = 1) <NEW_LINE> respData = self.makeRequest("/users/add", method="POST", data = { 'user' : 'user1', 'password' : 'password'} ) <NEW_LINE> self.assertResponse(respData, errCode = testLib.RestTestCase.ERR_USER_EXISTS) | Tests that adding a duplicate user name fails | 62599069be8e80087fbc0855 |
class NamesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_first_last_name(self): <NEW_LINE> <INDENT> formatted_name = get_formatted_name('sam', 'chia') <NEW_LINE> self.assertEqual(formatted_name, 'Sam Chia') <NEW_LINE> <DEDENT> def test_first_last_middle_name(self): <NEW_LINE> <INDENT> formatted_name = get_formatted_name( 'sam', 'chia', 'eileen') <NEW_LINE> self.assertEqual(formatted_name, 'Sam Eileen Chia') | Tests for 'name_function.py' | 625990692c8b7c6e89bd4fb0 |
class Flake8Isort5(Flake8IsortBase): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> if self.filename is not self.stdin_display_name: <NEW_LINE> <INDENT> file_path = Path(self.filename) <NEW_LINE> isort_config = isort.settings.Config( settings_path=file_path.parent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file_path = None <NEW_LINE> isort_config = isort.settings.Config( settings_path=Path.cwd()) <NEW_LINE> <DEDENT> input_string = ''.join(self.lines) <NEW_LINE> traceback = '' <NEW_LINE> isort_changed = False <NEW_LINE> input_stream = StringIO(input_string) <NEW_LINE> output_stream = StringIO() <NEW_LINE> isort_stdout = StringIO() <NEW_LINE> try: <NEW_LINE> <INDENT> with redirect_stdout(isort_stdout): <NEW_LINE> <INDENT> isort_changed = isort.api.sort_stream( input_stream=input_stream, output_stream=output_stream, config=isort_config, file_path=file_path) <NEW_LINE> <DEDENT> <DEDENT> except isort.exceptions.FileSkipped: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except isort.exceptions.ISortError as e: <NEW_LINE> <INDENT> warnings.warn(e) <NEW_LINE> <DEDENT> if isort_changed: <NEW_LINE> <INDENT> outlines = output_stream.getvalue() <NEW_LINE> diff_delta = "".join(unified_diff( input_string.splitlines(keepends=True), outlines.splitlines(keepends=True), fromfile="{}:before".format(self.filename), tofile="{}:after".format(self.filename))) <NEW_LINE> traceback = (isort_stdout.getvalue() + "\n" + diff_delta) <NEW_LINE> for line_num, message in self.isort_linenum_msg(diff_delta): <NEW_LINE> <INDENT> if self.show_traceback: <NEW_LINE> <INDENT> message += traceback <NEW_LINE> <DEDENT> yield line_num, 0, message, type(self) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def isort_linenum_msg(self, udiff): <NEW_LINE> <INDENT> line_num = 0 <NEW_LINE> additions = [] <NEW_LINE> moves = [] <NEW_LINE> for line in udiff.splitlines(): <NEW_LINE> <INDENT> if line.startswith('@@', 0, 2): <NEW_LINE> <INDENT> line_num = int(line[4:].split(' ')[0].split(',')[0]) <NEW_LINE> continue <NEW_LINE> <DEDENT> elif not line_num: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if line.startswith(' ', 0, 1): <NEW_LINE> <INDENT> line_num += 1 <NEW_LINE> <DEDENT> elif line.startswith('-', 0, 1): <NEW_LINE> <INDENT> if line.strip() == '-': <NEW_LINE> <INDENT> yield line_num, self.isort_blank_unexp <NEW_LINE> line_num += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> moves.append(line[1:]) <NEW_LINE> yield line_num, self.isort_unsorted <NEW_LINE> line_num += 1 <NEW_LINE> <DEDENT> <DEDENT> elif line.startswith('+', 0, 1): <NEW_LINE> <INDENT> if line.strip() == '+': <NEW_LINE> <INDENT> yield line_num, self.isort_blank_req <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> additions.append((line_num, line)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for line_num, line in additions: <NEW_LINE> <INDENT> if not line[1:] in moves: <NEW_LINE> <INDENT> yield line_num, self.isort_add_unexp | class for isort >=5 | 625990690a50d4780f7069a5 |
class MonitoredException(Exception): <NEW_LINE> <INDENT> pass | Thrown when a Handler finds an Exception from a monitored log | 6259906932920d7e50bc7811 |
class Cmd: <NEW_LINE> <INDENT> _index = "setup" <NEW_LINE> def __init__(self, args: dict): <NEW_LINE> <INDENT> self._url = args.config <NEW_LINE> self._args = args.args <NEW_LINE> self._cluster_conf = args.cluster_conf <NEW_LINE> <DEDENT> @property <NEW_LINE> def args(self) -> str: <NEW_LINE> <INDENT> return self._args <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self) -> str: <NEW_LINE> <INDENT> return self._url <NEW_LINE> <DEDENT> @property <NEW_LINE> def cluster_conf(self) -> str: <NEW_LINE> <INDENT> return self._cluster_conf <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def usage(prog: str): <NEW_LINE> <INDENT> sys.stderr.write( f"usage: {prog} [-h] <cmd> --config <url> <args>...\n" f"where:\n" f"cmd post_install, config, init, reset, test\n" f"url Config URL\n") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_command(desc: str, argv: dict): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(desc) <NEW_LINE> subparsers = parser.add_subparsers() <NEW_LINE> cmds = inspect.getmembers(sys.modules[__name__]) <NEW_LINE> cmds = [(x, y) for x, y in cmds if x.endswith("Cmd") and x != "Cmd"] <NEW_LINE> for name, cmd in cmds: <NEW_LINE> <INDENT> cmd.add_args(subparsers, cmd, name) <NEW_LINE> <DEDENT> args = parser.parse_args(argv) <NEW_LINE> return args.command(args) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _add_extended_args(parser): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def add_args(parser: str, cls: str, name: str): <NEW_LINE> <INDENT> parser1 = parser.add_parser(cls.name, help='setup %s' % name) <NEW_LINE> parser1.add_argument('--config', help='Conf Store URL', type=str) <NEW_LINE> parser1.add_argument('--cluster_conf', help='cluster.conf url', type=str, default=CLUSTER_CONF) <NEW_LINE> cls._add_extended_args(parser1) <NEW_LINE> parser1.add_argument('args', nargs='*', default=[], help='args') <NEW_LINE> parser1.set_defaults(command=cls) | Setup Command | 625990694e4d562566373bd1 |
class BuildRequestHandler(SocketServer.StreamRequestHandler): <NEW_LINE> <INDENT> def build(self, repo, subsystem, subcommand): <NEW_LINE> <INDENT> configuration = { "application" : "application" } <NEW_LINE> exception_config = ConfigParser.ConfigParser() <NEW_LINE> exception_config.read("%s/exceptions.ini"%self.server.base_directory) <NEW_LINE> if exception_config.has_section(repo): <NEW_LINE> <INDENT> for config_key in configuration.keys(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> configuration[config_key] = exception_config.get(repo, config_key) <NEW_LINE> <DEDENT> except ConfigParser.NoOptionError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> subsystem_constants = { "wkz" : ["../werkzeug/wkz.exe", configuration["application"]], "svn" : ["svn", ""] } <NEW_LINE> if subsystem not in subsystem_constants: <NEW_LINE> <INDENT> yield "Error: requested subsystem '{}' is not in valid list of subsystems: {}\n".format(subsystem, subsystem_constants.keys()) <NEW_LINE> return <NEW_LINE> <DEDENT> full_application_path = os.path.join( self.server.base_directory, repo, subsystem_constants[subsystem][1] ) <NEW_LINE> try: <NEW_LINE> <INDENT> os.chdir(full_application_path) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> yield "Error: Unable to chdir: %s\n"%e <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> process = subprocess.Popen( [subsystem_constants[subsystem][0], subcommand], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> yield "Error: Could not run executable: {}\n".format(e) <NEW_LINE> return <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> stdout_byte = process.stdout.read(1) <NEW_LINE> if not stdout_byte: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> yield stdout_byte <NEW_LINE> <DEDENT> <DEDENT> def handle(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> key, repo, subsystem, subcommand = self.request.recv(1024).strip().split() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.wfile.write("Incorrect syntax\n") <NEW_LINE> return <NEW_LINE> <DEDENT> if key != self.server.key: <NEW_LINE> <INDENT> self.wfile.write("Incorrect key\n") <NEW_LINE> return <NEW_LINE> <DEDENT> for outputbyte in self.build(repo, subsystem, subcommand): <NEW_LINE> <INDENT> self.wfile.write(outputbyte) | Handles incoming TCP connections and executes a build on the proper
project using Werkzeug. | 625990697d847024c075dba4 |
class WorkItemUpdate(WorkItemTrackingResourceReference): <NEW_LINE> <INDENT> _attribute_map = { 'url': {'key': 'url', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '{WorkItemFieldUpdate}'}, 'id': {'key': 'id', 'type': 'int'}, 'relations': {'key': 'relations', 'type': 'WorkItemRelationUpdates'}, 'rev': {'key': 'rev', 'type': 'int'}, 'revised_by': {'key': 'revisedBy', 'type': 'IdentityReference'}, 'revised_date': {'key': 'revisedDate', 'type': 'iso-8601'}, 'work_item_id': {'key': 'workItemId', 'type': 'int'} } <NEW_LINE> def __init__(self, url=None, fields=None, id=None, relations=None, rev=None, revised_by=None, revised_date=None, work_item_id=None): <NEW_LINE> <INDENT> super(WorkItemUpdate, self).__init__(url=url) <NEW_LINE> self.fields = fields <NEW_LINE> self.id = id <NEW_LINE> self.relations = relations <NEW_LINE> self.rev = rev <NEW_LINE> self.revised_by = revised_by <NEW_LINE> self.revised_date = revised_date <NEW_LINE> self.work_item_id = work_item_id | WorkItemUpdate.
:param url:
:type url: str
:param fields:
:type fields: dict
:param id:
:type id: int
:param relations:
:type relations: :class:`WorkItemRelationUpdates <work-item-tracking.v4_0.models.WorkItemRelationUpdates>`
:param rev:
:type rev: int
:param revised_by:
:type revised_by: :class:`IdentityReference <work-item-tracking.v4_0.models.IdentityReference>`
:param revised_date:
:type revised_date: datetime
:param work_item_id:
:type work_item_id: int | 62599069fff4ab517ebcefe5 |
class Simulator(Container): <NEW_LINE> <INDENT> def simulate(self, basetime=0, ticks=1): <NEW_LINE> <INDENT> t = basetime <NEW_LINE> while t < (basetime + ticks): <NEW_LINE> <INDENT> self.execute(t) <NEW_LINE> t += 1 | A container intended to be the starting point for implementing or
holding gates for interfaces.
Does not act as a gate. | 625990694428ac0f6e659cfd |
class FakePropertyFactory(BaseFake): <NEW_LINE> <INDENT> def __init__(self, organization=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.organization = organization <NEW_LINE> <DEDENT> def get_property(self, organization=None, **kw): <NEW_LINE> <INDENT> property_details = { 'organization': self._get_attr('organization', organization), } <NEW_LINE> property_details.update(kw) <NEW_LINE> return Property.objects.create(**property_details) | Factory Class for producing Property instances. | 6259906921bff66bcd724431 |
class LogProgressThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(LogProgressThread, self).__init__() <NEW_LINE> self.setDaemon(True) <NEW_LINE> self.finished = False <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> global tracker <NEW_LINE> if not globals.dry_run and globals.progress and tracker.has_collected_evidence(): <NEW_LINE> <INDENT> while not self.finished: <NEW_LINE> <INDENT> tracker.log_upload_progress() <NEW_LINE> time.sleep(globals.progress_rate) | Background thread that reports progress to the log,
every --progress-rate seconds | 6259906997e22403b383c6d8 |
class StatusReporter(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._latest_result = None <NEW_LINE> self._last_result = None <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> self._error = None <NEW_LINE> self._done = False <NEW_LINE> <DEDENT> def __call__(self, **kwargs): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> self._latest_result = self._last_result = kwargs.copy() <NEW_LINE> <DEDENT> <DEDENT> def _get_and_clear_status(self): <NEW_LINE> <INDENT> if self._error: <NEW_LINE> <INDENT> raise TuneError("Error running trial: " + str(self._error)) <NEW_LINE> <DEDENT> if self._done and not self._latest_result: <NEW_LINE> <INDENT> if not self._last_result: <NEW_LINE> <INDENT> raise TuneError("Trial finished without reporting result!") <NEW_LINE> <DEDENT> self._last_result.update(done=True) <NEW_LINE> return self._last_result <NEW_LINE> <DEDENT> with self._lock: <NEW_LINE> <INDENT> res = self._latest_result <NEW_LINE> self._latest_result = None <NEW_LINE> return res <NEW_LINE> <DEDENT> <DEDENT> def _stop(self): <NEW_LINE> <INDENT> self._error = "Agent stopped" | Object passed into your main() that you can report status through.
Example:
>>> reporter = StatusReporter()
>>> reporter(timesteps_total=1) | 6259906916aa5153ce401ca4 |
class MpiPool(object): <NEW_LINE> <INDENT> def __init__(self, mapFunction): <NEW_LINE> <INDENT> self.rank = MPI.COMM_WORLD.Get_rank() <NEW_LINE> self.size = MPI.COMM_WORLD.Get_size() <NEW_LINE> self.mapFunction = mapFunction <NEW_LINE> <DEDENT> def map(self, function, sequence): <NEW_LINE> <INDENT> sequence = mpiBCast(sequence) <NEW_LINE> getLogger().debug("Rank: %s, pid: %s MpiPool: starts processing iteration" %(self.rank, os.getpid())) <NEW_LINE> mergedList = mergeList(MPI.COMM_WORLD.allgather( self.mapFunction(function, splitList(sequence,self.size)[self.rank]))) <NEW_LINE> getLogger().debug("Rank: %s, pid: %s MpiPool: done processing iteration"%(self.rank, os.getpid())) <NEW_LINE> return mergedList <NEW_LINE> <DEDENT> def isMaster(self): <NEW_LINE> <INDENT> return (self.rank==0) | Implementation of a mpi based pool. Currently it supports only the map function.
:param mapFunction: the map function to apply on the mpi nodes | 625990693617ad0b5ee0791f |
@configure.adapter( for_=IResource, provides=IRolePermissionManager, trusted=True) <NEW_LINE> class PloneRolePermissionManager(PloneSecurityMap): <NEW_LINE> <INDENT> key = 'roleperm' <NEW_LINE> def grant_permission_to_role(self, permission_id, role_id): <NEW_LINE> <INDENT> PloneSecurityMap.add_cell(self, permission_id, role_id, Allow) <NEW_LINE> <DEDENT> def grant_permission_to_role_no_inherit(self, permission_id, role_id): <NEW_LINE> <INDENT> PloneSecurityMap.add_cell( self, permission_id, role_id, AllowSingle) <NEW_LINE> <DEDENT> def deny_permission_to_role(self, permission_id, role_id): <NEW_LINE> <INDENT> PloneSecurityMap.add_cell(self, permission_id, role_id, Deny) <NEW_LINE> <DEDENT> unset_permission_from_role = PloneSecurityMap.del_cell <NEW_LINE> get_roles_for_permission = PloneSecurityMap.get_row <NEW_LINE> get_permissions_for_role = PloneSecurityMap.get_col <NEW_LINE> get_roles_and_permissions = PloneSecurityMap.get_all_cells <NEW_LINE> def get_setting(self, permission_id, role_id, default=Unset): <NEW_LINE> <INDENT> return PloneSecurityMap.query_cell( self, permission_id, role_id, default) | Provide adapter that manages role permission data in an object attribute
| 625990697d847024c075dba5 |
class PrivateUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = create_user( email='[email protected]', password='testpassword', name='test', ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> <DEDENT> def test_retrive_profile_success(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, { 'name': self.user.name, 'email': self.user.email, }) <NEW_LINE> <DEDENT> def test_pose_me_not_allowed(self): <NEW_LINE> <INDENT> res = self.client.post(ME_URL, {}) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> <DEDENT> def test_update_user_profile(self): <NEW_LINE> <INDENT> payload = {'name': 'new name', 'password': 'newpassword'} <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(self.user.name, payload['name']) <NEW_LINE> self.assertTrue(self.user.check_password(payload['password'])) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) | Test API requests that require authentication | 62599069167d2b6e312b8173 |
class SceneMouseEvent(SceneEvent): <NEW_LINE> <INDENT> def __init__(self, event, canvas, **kwds): <NEW_LINE> <INDENT> self.mouse_event = event <NEW_LINE> super(SceneMouseEvent, self).__init__(type=event.type, canvas=canvas, **kwds) <NEW_LINE> <DEDENT> @property <NEW_LINE> def pos(self): <NEW_LINE> <INDENT> return self.map_from_canvas(self.mouse_event.pos) <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_event(self): <NEW_LINE> <INDENT> if self.mouse_event.last_event is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ev = self.copy() <NEW_LINE> ev.mouse_event = self.mouse_event.last_event <NEW_LINE> return ev <NEW_LINE> <DEDENT> @property <NEW_LINE> def press_event(self): <NEW_LINE> <INDENT> if self.mouse_event.press_event is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ev = self.copy() <NEW_LINE> ev.mouse_event = self.mouse_event.press_event <NEW_LINE> return ev <NEW_LINE> <DEDENT> @property <NEW_LINE> def button(self): <NEW_LINE> <INDENT> return self.mouse_event.button <NEW_LINE> <DEDENT> @property <NEW_LINE> def buttons(self): <NEW_LINE> <INDENT> return self.mouse_event.buttons <NEW_LINE> <DEDENT> @property <NEW_LINE> def delta(self): <NEW_LINE> <INDENT> return self.mouse_event.delta <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> ev = self.__class__(self.mouse_event, self._canvas) <NEW_LINE> ev._stack = self._stack[:] <NEW_LINE> ev._viewbox_stack = self._viewbox_stack[:] <NEW_LINE> return ev | Represents a mouse event that occurred on a SceneCanvas. This event is
delivered to all entities whose mouse interaction area is under the event. | 62599069097d151d1a2c2839 |
class _TempPopup(Frame): <NEW_LINE> <INDENT> def __init__(self, screen, parent, x, y, w, h): <NEW_LINE> <INDENT> self.palette = defaultdict(lambda: parent.frame.palette["focus_field"]) <NEW_LINE> self.palette["selected_field"] = parent.frame.palette["selected_field"] <NEW_LINE> self.palette["selected_focus_field"] = parent.frame.palette["selected_focus_field"] <NEW_LINE> self.palette["invalid"] = parent.frame.palette["invalid"] <NEW_LINE> super(_TempPopup, self).__init__(screen, h, w, x=x, y=y, has_border=True, is_modal=True) <NEW_LINE> self._parent = parent <NEW_LINE> <DEDENT> def process_event(self, event): <NEW_LINE> <INDENT> if event is not None: <NEW_LINE> <INDENT> if isinstance(event, KeyboardEvent): <NEW_LINE> <INDENT> if event.key_code in [Screen.ctrl("M"), Screen.ctrl("J"), ord(" ")]: <NEW_LINE> <INDENT> event = None <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(event, MouseEvent): <NEW_LINE> <INDENT> origin = self._canvas.origin <NEW_LINE> if event.y < origin[1] or event.y >= origin[1] + self._canvas.height: <NEW_LINE> <INDENT> event = None <NEW_LINE> <DEDENT> elif event.x < origin[0] or event.x >= origin[0] + self._canvas.width: <NEW_LINE> <INDENT> event = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if event is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._on_close() <NEW_LINE> self._scene.remove_effect(self) <NEW_LINE> <DEDENT> except InvalidFields: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return super(_TempPopup, self).process_event(event) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _on_close(self): <NEW_LINE> <INDENT> pass | An internal Frame for creating a temporary pop-up for a Widget in another Frame. | 6259906967a9b606de547687 |
class V1Stage(object): <NEW_LINE> <INDENT> openapi_types = { 'uuid': 'str', 'stage': 'V1Stages', 'stage_conditions': 'list[V1StageCondition]' } <NEW_LINE> attribute_map = { 'uuid': 'uuid', 'stage': 'stage', 'stage_conditions': 'stage_conditions' } <NEW_LINE> def __init__(self, uuid=None, stage=None, stage_conditions=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration.get_default_copy() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._uuid = None <NEW_LINE> self._stage = None <NEW_LINE> self._stage_conditions = None <NEW_LINE> self.discriminator = None <NEW_LINE> if uuid is not None: <NEW_LINE> <INDENT> self.uuid = uuid <NEW_LINE> <DEDENT> if stage is not None: <NEW_LINE> <INDENT> self.stage = stage <NEW_LINE> <DEDENT> if stage_conditions is not None: <NEW_LINE> <INDENT> self.stage_conditions = stage_conditions <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def uuid(self): <NEW_LINE> <INDENT> return self._uuid <NEW_LINE> <DEDENT> @uuid.setter <NEW_LINE> def uuid(self, uuid): <NEW_LINE> <INDENT> self._uuid = uuid <NEW_LINE> <DEDENT> @property <NEW_LINE> def stage(self): <NEW_LINE> <INDENT> return self._stage <NEW_LINE> <DEDENT> @stage.setter <NEW_LINE> def stage(self, stage): <NEW_LINE> <INDENT> self._stage = stage <NEW_LINE> <DEDENT> @property <NEW_LINE> def stage_conditions(self): <NEW_LINE> <INDENT> return self._stage_conditions <NEW_LINE> <DEDENT> @stage_conditions.setter <NEW_LINE> def stage_conditions(self, stage_conditions): <NEW_LINE> <INDENT> self._stage_conditions = stage_conditions <NEW_LINE> <DEDENT> def to_dict(self, serialize=False): <NEW_LINE> <INDENT> result = {} <NEW_LINE> def convert(x): <NEW_LINE> <INDENT> if hasattr(x, "to_dict"): <NEW_LINE> <INDENT> args = getfullargspec(x.to_dict).args <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> return x.to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x.to_dict(serialize) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> <DEDENT> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> attr = self.attribute_map.get(attr, attr) if serialize else attr <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: convert(x), value )) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], convert(item[1])), value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = convert(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, V1Stage): <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, V1Stage): <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. | 625990697c178a314d78e7d1 |
class ListDeletedEventRequest(Request): <NEW_LINE> <INDENT> deserialized_types = { 'object_type': 'str', 'request_id': 'str', 'timestamp': 'datetime', 'locale': 'str', 'body': 'ask_sdk_model.services.list_management.list_body.ListBody' } <NEW_LINE> attribute_map = { 'object_type': 'type', 'request_id': 'requestId', 'timestamp': 'timestamp', 'locale': 'locale', 'body': 'body' } <NEW_LINE> def __init__(self, request_id=None, timestamp=None, locale=None, body=None): <NEW_LINE> <INDENT> self.__discriminator_value = "AlexaHouseholdListEvent.ListDeleted" <NEW_LINE> self.object_type = self.__discriminator_value <NEW_LINE> super(ListDeletedEventRequest, self).__init__(object_type=self.__discriminator_value, request_id=request_id, timestamp=timestamp, locale=locale) <NEW_LINE> self.body = body <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, ListDeletedEventRequest): <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.
:type locale: (optional) str
:param body:
:type body: (optional) ask_sdk_model.services.list_management.list_body.ListBody | 625990692ae34c7f260ac8b3 |
class WaitForCompletion(AuthView): <NEW_LINE> <INDENT> def handle(self, request: Request, helper) -> Response: <NEW_LINE> <INDENT> if "continue_setup" in request.POST: <NEW_LINE> <INDENT> return helper.next_step() <NEW_LINE> <DEDENT> return self.respond("sentry_auth_rippling/wait-for-completion.html") | Rippling provides the Metadata URL during initial application setup, before
configuration values have been saved, thus we cannot immediately attempt to
create an identity for the setting up the SSO.
This is simply an extra step to wait for them to complete that. | 62599069ac7a0e7691f73cb2 |
class MandelTileProvider(DynamicTileProvider): <NEW_LINE> <INDENT> def __init__(self, tilecache): <NEW_LINE> <INDENT> DynamicTileProvider.__init__(self, tilecache) <NEW_LINE> <DEDENT> filext = 'png' <NEW_LINE> tilesize = 256 <NEW_LINE> aspect_ratio = 1.0 <NEW_LINE> def _load_dynamic(self, tile_id, outfile): <NEW_LINE> <INDENT> media_id, tilelevel, row, col = tile_id <NEW_LINE> if row < 0 or col < 0 or row > 2**tilelevel - 1 or col > 2**tilelevel - 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> tilesize_units = 4.0 * 2**-tilelevel <NEW_LINE> x = col * tilesize_units <NEW_LINE> y = row * tilesize_units <NEW_LINE> x1 = x - 3.0 <NEW_LINE> y1 = 2.0 - y <NEW_LINE> x2 = x1 + tilesize_units <NEW_LINE> y2 = y1 - tilesize_units <NEW_LINE> fd, tmpfile = tempfile.mkstemp('.pgm') <NEW_LINE> os.close(fd) <NEW_LINE> bbox = "%f,%f:%f,%f" % (x1,y1,x2,y2) <NEW_LINE> size = "%d,%d" % (self.tilesize,self.tilesize) <NEW_LINE> max_iterations = 512 <NEW_LINE> self._logger.debug("calling jrMandel -w %s" % bbox) <NEW_LINE> returncode = subprocess.call(['jrMandel', '-w', bbox, '-s', size, '-i', str(max_iterations), tmpfile]) <NEW_LINE> if returncode != 0: <NEW_LINE> <INDENT> self._logger.error("conversion failed with return code %d", returncode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> converter = MagickConverter(tmpfile, outfile) <NEW_LINE> converter.start() <NEW_LINE> converter.join() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> os.unlink(tmpfile) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.__logger.exception("unable to unlink temporary file " "'%s'" % tmpfile) | MandelTileProvider objects are used for generating tiles of the
Mandelbrot set using jrMandel (<http://freshmeat.net/projects/jrmandel/>).
Constructor: MandelTileProvider(TileCache) | 625990691b99ca400229011b |
class SmallerSetJsonField(serializers.JSONField): <NEW_LINE> <INDENT> def to_representation(self, value): <NEW_LINE> <INDENT> limited_dict = {} <NEW_LINE> if 'profile_image_url_https' in value: <NEW_LINE> <INDENT> limited_dict['profile_image_url'] = value['profile_image_url_https'] <NEW_LINE> <DEDENT> limited_dict['url'] = 'https://twitter.com/' + value.get('screen_name', '') <NEW_LINE> limited_dict['screen_name'] = value.get('screen_name', '') <NEW_LINE> limited_dict['name'] = value.get('name', '') <NEW_LINE> return limited_dict | Class to expose Smaller set of JSON fields. | 6259906971ff763f4b5e8f71 |
class QNetwork(nn.Module): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, seed, fc1_units=64, fc2_units=32): <NEW_LINE> <INDENT> super(QNetwork, self).__init__() <NEW_LINE> self.seed = torch.manual_seed(seed) <NEW_LINE> self.fc1 = nn.Linear(state_size, fc1_units) <NEW_LINE> self.fc2 = nn.Linear(fc1_units, fc2_units) <NEW_LINE> self.fc3 = nn.Linear(fc2_units, action_size) <NEW_LINE> <DEDENT> def forward(self, state): <NEW_LINE> <INDENT> x = F.relu(self.fc1(state)) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> return self.fc3(x) | Actor (Policy) Model. | 62599069d486a94d0ba2d78a |
class SnippetViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Snippet.objects.all() <NEW_LINE> serializer_class = SnippetSerializer <NEW_LINE> permission_classes = ( permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) <NEW_LINE> @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) <NEW_LINE> def highlight(self, request, *args, **kwargs): <NEW_LINE> <INDENT> snippet = self.get_object() <NEW_LINE> return Response(snippet.highlighted) <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(owner=self.request.user) | This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action. | 62599069cb5e8a47e493cd69 |
class DevConfig(Config): <NEW_LINE> <INDENT> SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://gitu_m:sqlpass@localhost/blogger' <NEW_LINE> DEBUG = True | child configuration class for development | 62599069a8370b77170f1b90 |
class Table: <NEW_LINE> <INDENT> def __init__(self, header, body): <NEW_LINE> <INDENT> header_length = len(header) <NEW_LINE> self._check_body_length(body, header_length) <NEW_LINE> self._header = header <NEW_LINE> self._body = body <NEW_LINE> <DEDENT> @property <NEW_LINE> def header(self): <NEW_LINE> <INDENT> return copy(self._header) <NEW_LINE> <DEDENT> @property <NEW_LINE> def body(self): <NEW_LINE> <INDENT> return copy(self._body) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _check_body_length(body, header_length): <NEW_LINE> <INDENT> for index, row in enumerate(body): <NEW_LINE> <INDENT> if len(row) is not header_length: <NEW_LINE> <INDENT> raise ValueError('Row at index ' + str(index) + " is not of the same length as the table header") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _get_column_index(self, column_name): <NEW_LINE> <INDENT> return self._header.index(column_name) <NEW_LINE> <DEDENT> def _parse_column(self, column): <NEW_LINE> <INDENT> if isinstance(column, str): <NEW_LINE> <INDENT> index = self._get_column_index(column) <NEW_LINE> <DEDENT> elif isinstance(column, int): <NEW_LINE> <INDENT> index = column <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('Column has to be a string or an integer value') <NEW_LINE> <DEDENT> return index <NEW_LINE> <DEDENT> def get_row(self, index): <NEW_LINE> <INDENT> return self._body[index] <NEW_LINE> <DEDENT> def get_column(self, column): <NEW_LINE> <INDENT> column_index = self._parse_column(column) <NEW_LINE> column_array = [] <NEW_LINE> for row in self._body: <NEW_LINE> <INDENT> column_array.append(row[column_index]) <NEW_LINE> <DEDENT> return column_array <NEW_LINE> <DEDENT> def get_cell(self, column, row_index): <NEW_LINE> <INDENT> column_index = self._parse_column(column) <NEW_LINE> cell = self._body[row_index][column_index] <NEW_LINE> return cell <NEW_LINE> <DEDENT> def get_row_count(self): <NEW_LINE> <INDENT> table_length = len(self._body) <NEW_LINE> return table_length | Simple implementation of a table. The Table class helps with accessing table structured data. | 625990697047854f46340b80 |
class TestXmlNs0BrowserSearchRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testXmlNs0BrowserSearchRequest(self): <NEW_LINE> <INDENT> pass | XmlNs0BrowserSearchRequest unit test stubs | 62599069f548e778e596cd57 |
class Client(Iface): <NEW_LINE> <INDENT> def __init__(self, iprot, oprot=None): <NEW_LINE> <INDENT> self._iprot = self._oprot = iprot <NEW_LINE> if oprot is not None: <NEW_LINE> <INDENT> self._oprot = oprot <NEW_LINE> <DEDENT> self._seqid = 0 <NEW_LINE> <DEDENT> def is_healthy(self, request): <NEW_LINE> <INDENT> self.send_is_healthy(request) <NEW_LINE> return self.recv_is_healthy() <NEW_LINE> <DEDENT> def send_is_healthy(self, request): <NEW_LINE> <INDENT> self._oprot.writeMessageBegin("is_healthy", TMessageType.CALL, self._seqid) <NEW_LINE> args = is_healthy_args() <NEW_LINE> args.request = request <NEW_LINE> args.write(self._oprot) <NEW_LINE> self._oprot.writeMessageEnd() <NEW_LINE> self._oprot.trans.flush() <NEW_LINE> <DEDENT> def recv_is_healthy(self): <NEW_LINE> <INDENT> iprot = self._iprot <NEW_LINE> (fname, mtype, rseqid) = iprot.readMessageBegin() <NEW_LINE> if mtype == TMessageType.EXCEPTION: <NEW_LINE> <INDENT> x = TApplicationException() <NEW_LINE> x.read(iprot) <NEW_LINE> iprot.readMessageEnd() <NEW_LINE> raise x <NEW_LINE> <DEDENT> result = is_healthy_result() <NEW_LINE> result.read(iprot) <NEW_LINE> iprot.readMessageEnd() <NEW_LINE> if result.success is not None: <NEW_LINE> <INDENT> return result.success <NEW_LINE> <DEDENT> raise TApplicationException( TApplicationException.MISSING_RESULT, "is_healthy failed: unknown result" ) | The base for any baseplate-based service.
Your service should inherit from this one so that common tools can interact
with any expected interfaces. | 6259906926068e7796d4e105 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.