code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class TestPasswordPostedSmoke(BaseTestPassword): <NEW_LINE> <INDENT> @property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> return self._backend.instance_password() <NEW_LINE> <DEDENT> @test_util.requires_service('http') <NEW_LINE> def test_password_set_posted(self): <NEW_LINE> <INDENT> self.is_password_set(password=self.password) | Test that the password was set and posted to the metadata service
This will attempt a WinRM login on the instance, which will use the
password which was correctly set by the underlying cloud
initialization software. | 6259906e167d2b6e312b81bc |
class BaseSerializer(metaclass=MetaSerializer): <NEW_LINE> <INDENT> @property <NEW_LINE> def fields(self): <NEW_LINE> <INDENT> return getattr(self, self.__class__._fields_storage_key) <NEW_LINE> <DEDENT> def to_representation(self, obj): <NEW_LINE> <INDENT> representation = {} <NEW_LINE> for name, field in self.fields.items(): <NEW_LINE> <INDENT> attribute = self.get_attribute(obj, field.source or name) <NEW_LINE> if attribute is None: <NEW_LINE> <INDENT> representation[name] = [] if field.many else None <NEW_LINE> <DEDENT> elif field.many: <NEW_LINE> <INDENT> representation[name] = [ field.to_representation(item) for item in attribute ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> representation[name] = field.to_representation(attribute) <NEW_LINE> <DEDENT> <DEDENT> return representation <NEW_LINE> <DEDENT> def from_representation(self, representation): <NEW_LINE> <INDENT> object_dict = {} <NEW_LINE> failed = {} <NEW_LINE> for name, field in self.fields.items(): <NEW_LINE> <INDENT> if name not in representation: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> object_dict[field.source or name] = field.from_representation( representation[name] ) <NEW_LINE> <DEDENT> except ValueError as err: <NEW_LINE> <INDENT> failed[name] = str(err) <NEW_LINE> <DEDENT> <DEDENT> if failed: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.validate(object_dict) <NEW_LINE> raise DeserializationError() <NEW_LINE> <DEDENT> except DeserializationError as err: <NEW_LINE> <INDENT> err.failed = failed <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> return object_dict <NEW_LINE> <DEDENT> def validate(self, object_dict, partial=False): <NEW_LINE> <INDENT> sources = { field.source or name if field.source != "*" else name: field for name, field in self.fields.items() } <NEW_LINE> missing = [ name for name, field in sources.items() if all((not partial, name not in object_dict, not field.read_only)) ] <NEW_LINE> forbidden = [ name for name in object_dict if any((name not in sources, sources[name].read_only)) ] <NEW_LINE> invalid = {} <NEW_LINE> for name, value in object_dict.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sources[name].validate(value) <NEW_LINE> <DEDENT> except ValidationError as err: <NEW_LINE> <INDENT> invalid[name] = str(err) <NEW_LINE> <DEDENT> <DEDENT> if any([missing, forbidden, invalid]): <NEW_LINE> <INDENT> raise DeserializationError(missing, forbidden, invalid) <NEW_LINE> <DEDENT> <DEDENT> def get_attribute(self, obj, attr): <NEW_LINE> <INDENT> if attr == '*': <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> if isinstance(obj, Mapping): <NEW_LINE> <INDENT> return obj.get(attr, None) <NEW_LINE> <DEDENT> return getattr(obj, attr, None) <NEW_LINE> <DEDENT> def set_attribute(self, obj, attr, value): <NEW_LINE> <INDENT> if isinstance(obj, MutableMapping): <NEW_LINE> <INDENT> obj[attr] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(obj, attr, value) <NEW_LINE> <DEDENT> <DEDENT> def describe(self): <NEW_LINE> <INDENT> return OrderedDict([ (name, field.describe()) for name, field in self.fields.items() ]) | Base serializer class for describing internal object serialization.
Example:
.. code-block:: python
from graceful.serializers import BaseSerializer
from graceful.fields import RawField, IntField, FloatField
class CatSerializer(BaseSerializer):
species = RawField("non normalized cat species")
age = IntField("cat age in years")
height = FloatField("cat height in cm") | 6259906e3d592f4c4edbc73d |
class KeynoteFormatter(Formatter): <NEW_LINE> <INDENT> def __init__(self, styles): <NEW_LINE> <INDENT> Formatter.__init__(self) <NEW_LINE> def style_name(item): <NEW_LINE> <INDENT> name, style = item <NEW_LINE> if name == 'Paragraph': <NEW_LINE> <INDENT> style = 'SFWPParagraphStyle-%s' % str(style) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> style = 'SFWPCharacterStyle-%s' % str(style) <NEW_LINE> <DEDENT> return (name, style) <NEW_LINE> <DEDENT> self.styles = dict(map(style_name, styles.items())) <NEW_LINE> <DEDENT> def style_for_ttype(self, ttype): <NEW_LINE> <INDENT> parts = str(ttype).split('.') <NEW_LINE> name = '.'.join(parts[1:]) <NEW_LINE> gen_name = parts[1] <NEW_LINE> if name in self.styles: <NEW_LINE> <INDENT> return self.styles[name] <NEW_LINE> <DEDENT> elif gen_name in self.styles: <NEW_LINE> <INDENT> return self.styles[gen_name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def format(self, tokensource, outfile): <NEW_LINE> <INDENT> outfile.write('<sf:p sf:style="%s" sf:list-level="1">' % self.styles['Paragraph']) <NEW_LINE> for ttype, value in tokensource: <NEW_LINE> <INDENT> style = self.style_for_ttype(ttype) <NEW_LINE> text = escape(value).replace('\n', '<sf:lnbr/>') <NEW_LINE> if style: <NEW_LINE> <INDENT> outfile.write('<sf:span sf:style="%s">%s</sf:span>' % (style, text)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> outfile.write(text) <NEW_LINE> <DEDENT> <DEDENT> outfile.write('</sf:p>') | Pygments formatter that outputs XML for Keynote slides. | 6259906e3346ee7daa33828c |
class VertexReplaceError(ArangoRequestError): <NEW_LINE> <INDENT> pass | Failed to replace the vertex. | 6259906e435de62698e9d662 |
class SystemInformation: <NEW_LINE> <INDENT> SECTOR_SYSTEM = 1 <NEW_LINE> SECTOR = 2 <NEW_LINE> SYSTEM = 3 <NEW_LINE> FACTION = 4 <NEW_LINE> def __init__(self, system=VS.getSystemFile()): <NEW_LINE> <INDENT> self.system = system <NEW_LINE> self.faction = VS.GetGalaxyFaction(self.system) <NEW_LINE> <DEDENT> def getInfo(self, inf_type=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> [sec, sys] = self.system.split('/') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> sec = self.system <NEW_LINE> sys = self.system <NEW_LINE> <DEDENT> if not inf_type: <NEW_LINE> <INDENT> return self.system <NEW_LINE> <DEDENT> elif inf_type == self.SECTOR: <NEW_LINE> <INDENT> return sec <NEW_LINE> <DEDENT> elif inf_type == self.SECTOR_SYSTEM: <NEW_LINE> <INDENT> return self.system <NEW_LINE> <DEDENT> elif inf_type == self.SYSTEM: <NEW_LINE> <INDENT> return sys <NEW_LINE> <DEDENT> elif inf_type == self.FACTION: <NEW_LINE> <INDENT> return self.faction <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid information type specified") | A class the provides a query mechanism, for each
instance, that will return the specified system's
faction, name, or parent sector. | 6259906e23849d37ff852912 |
class DdosProtectionPlanListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[DdosProtectionPlan]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["DdosProtectionPlan"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(DdosProtectionPlanListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | A list of DDoS protection plans.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of DDoS protection plans.
:type value: list[~azure.mgmt.network.v2020_11_01.models.DdosProtectionPlan]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str | 6259906ef7d966606f7494ea |
class Game(NamedTuple): <NEW_LINE> <INDENT> teams: Tuple[str, str] <NEW_LINE> match_format: str <NEW_LINE> match_id: int = None <NEW_LINE> stage: str = None <NEW_LINE> start_time: datetime = None <NEW_LINE> game_id: int = None <NEW_LINE> game_number: int = None <NEW_LINE> map_name: str = None <NEW_LINE> score: Tuple[int, int] = None <NEW_LINE> rosters: Tuple[Roster, Roster] = None <NEW_LINE> full_rosters: Tuple[FullRoster, FullRoster] = None <NEW_LINE> @property <NEW_LINE> def drawable(self): <NEW_LINE> <INDENT> return self.map_name in DRAWABLE_MAPS | Describe a single game. | 6259906eb7558d5895464b60 |
class Articles: <NEW_LINE> <INDENT> def __init__(self, author, title, description, url, urlToImage, publishedAt): <NEW_LINE> <INDENT> self.author = author <NEW_LINE> self.title = title <NEW_LINE> self.description = description <NEW_LINE> self.url = url <NEW_LINE> self.urlToImage = urlToImage <NEW_LINE> self.publishedAt = publishedAt | Article class to define article Objects | 6259906ef548e778e596cdea |
class Misty: <NEW_LINE> <INDENT> def __init__( self, ip: str, custom_info: Dict = {}, custom_actions: Dict = {}, custom_data: Dict = {}, rest_protocol: str = "http", websocket_protocol: str = "ws", websocket_endpoint: str = "pubsub", ) -> None: <NEW_LINE> <INDENT> self.ip = ip <NEW_LINE> self.infos = Info(ip, rest_protocol, custom_allowed_infos=custom_info) <NEW_LINE> self.actions = Action( ip, rest_protocol, custom_allowed_actions=custom_actions, custom_allowed_data=custom_data, ) <NEW_LINE> self.event_handler = MistyEventHandler( ip, websocket_protocol, websocket_endpoint ) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "A Misty II robot with IP address %s" % self.ip <NEW_LINE> <DEDENT> def perform_action(self, action_name: str, data: Dict = {}) -> Misty2pyResponse: <NEW_LINE> <INDENT> return self.actions.action_handler(action_name, data) <NEW_LINE> <DEDENT> def get_info(self, info_name: str, params: Dict = {}) -> Misty2pyResponse: <NEW_LINE> <INDENT> return self.infos.get_info(info_name, params) <NEW_LINE> <DEDENT> def event(self, action: str, **kwargs) -> Misty2pyResponse: <NEW_LINE> <INDENT> if action == "subscribe": <NEW_LINE> <INDENT> return self.event_handler.subscribe_event(kwargs) <NEW_LINE> <DEDENT> if action == "get_data": <NEW_LINE> <INDENT> return self.event_handler.get_event_data(kwargs) <NEW_LINE> <DEDENT> if action == "get_log": <NEW_LINE> <INDENT> return self.event_handler.get_event_log(kwargs) <NEW_LINE> <DEDENT> if action == "unsubscribe": <NEW_LINE> <INDENT> return self.event_handler.unsubscribe_event(kwargs) <NEW_LINE> <DEDENT> return Misty2pyResponse( False, error_type=Misty2pyErrorType.COMMAND, error_msg="The event action `%s` is not supported." % action, ) | A class representing a Misty robot.
Attributes:
ip (str): The IP address of this Misty robot.
infos (Info): The object of Info class that belongs to this Misty.
actions (Action): The object of Action class that belongs to this Misty.
events (dict): A dictionary of active event subscriptions (keys being the event name, values the MistyEvent() object). | 6259906e2c8b7c6e89bd5043 |
class ResultDefault(object): <NEW_LINE> <INDENT> def test(self, req_handler): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def act(self, req_handler): <NEW_LINE> <INDENT> raise ServerException("unknown object '{0}'".format(req_handler.path)) | default case | 6259906e99cbb53fe6832744 |
class DocumentLinkInfoViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = DocumentLinkInfo.objects.all() <NEW_LINE> serializer_class = DocumentLinkInfoSerializer | Document DocumentLinkInfo endpoint to `list`, `create`, `retrieve`,
`update` and `destroy` actions for document links | 6259906ea219f33f346c8065 |
class PlotGrid(object): <NEW_LINE> <INDENT> def __init__(self, sizes=(15,5,1)): <NEW_LINE> <INDENT> size = sum(sizes)/2.0 <NEW_LINE> fig = plt.figure(figsize=(size, size)) <NEW_LINE> gridsize = sum(sizes) <NEW_LINE> gs = plt.GridSpec(gridsize, gridsize) <NEW_LINE> js = sizes[1]+sizes[2] <NEW_LINE> ms = sizes[2] <NEW_LINE> ax_joint = fig.add_subplot(gs[js:, :-js]) <NEW_LINE> if sizes[1]>0: <NEW_LINE> <INDENT> ax_marg_x = fig.add_subplot(gs[ms:js, :-js], sharex=ax_joint) <NEW_LINE> ax_marg_y = fig.add_subplot(gs[js:, -js:-ms], sharey=ax_joint) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ax_marg_x = None <NEW_LINE> ax_marg_y = None <NEW_LINE> <DEDENT> if sizes[2]>0: <NEW_LINE> <INDENT> ax_cbar = fig.add_subplot(gs[js:, -ms:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ax_cbar = None <NEW_LINE> <DEDENT> self.fig = fig <NEW_LINE> self.ax_joint = ax_joint <NEW_LINE> self.ax_marg_x = ax_marg_x <NEW_LINE> self.ax_marg_y = ax_marg_y <NEW_LINE> self.ax_cbar = ax_cbar | sns.JointGrid-like grid modified to our desires
Not used yet... | 6259906e4428ac0f6e659d90 |
@register_ensembler("voting") <NEW_LINE> class Voting(BaseEnsembler): <NEW_LINE> <INDENT> def __init__(self, ensemble_size=10, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.ensemble_size = ensemble_size <NEW_LINE> <DEDENT> def fit(self, predictions, label, identifiers, feval, *args, **kwargs): <NEW_LINE> <INDENT> self._re_initialize(identifiers, len(predictions)) <NEW_LINE> if not isinstance(feval, list): <NEW_LINE> <INDENT> feval = [feval] <NEW_LINE> <DEDENT> weights = self._specify_weights(predictions, label, feval) <NEW_LINE> self.model_to_weight = dict(zip(self.identifiers, weights)) <NEW_LINE> VOTE_LOGGER.debug(self.identifiers, weights) <NEW_LINE> training_score = self._eval(predictions, label, feval) <NEW_LINE> return training_score <NEW_LINE> <DEDENT> def ensemble(self, predictions, identifiers, *args, **kwargs): <NEW_LINE> <INDENT> weights = np.zeros([len(predictions)]) <NEW_LINE> for idx, model in enumerate(identifiers): <NEW_LINE> <INDENT> weights[idx] = self.model_to_weight[model] <NEW_LINE> <DEDENT> weights = weights / np.sum(weights) <NEW_LINE> return np.average(predictions, axis=0, weights=weights) <NEW_LINE> <DEDENT> def _specify_weights(self, predictions, label, feval): <NEW_LINE> <INDENT> ensemble_prediction = [] <NEW_LINE> combinations = [] <NEW_LINE> history = [] <NEW_LINE> for i in range(self.ensemble_size): <NEW_LINE> <INDENT> eval_score_full = [] <NEW_LINE> eval_score = np.zeros([self.n_models]) <NEW_LINE> for j, pred in enumerate(predictions): <NEW_LINE> <INDENT> ensemble_prediction.append(pred) <NEW_LINE> pred_mean = np.mean(ensemble_prediction, axis=0) <NEW_LINE> eval_score_full.append( [ fx.evaluate(pred_mean, label) * (1 if fx.is_higher_better else -1) for fx in feval ] ) <NEW_LINE> eval_score[j] = eval_score_full[-1][0] <NEW_LINE> ensemble_prediction.pop() <NEW_LINE> <DEDENT> best_model = np.argmax(eval_score) <NEW_LINE> ensemble_prediction.append(predictions[best_model]) <NEW_LINE> history.append(eval_score_full[best_model]) <NEW_LINE> combinations.append(best_model) <NEW_LINE> <DEDENT> frequency = Counter(combinations).most_common() <NEW_LINE> weights = np.zeros([self.n_models]) <NEW_LINE> for model, freq in frequency: <NEW_LINE> <INDENT> weights[model] = float(freq) <NEW_LINE> <DEDENT> weights = weights / np.sum(weights) <NEW_LINE> return weights <NEW_LINE> <DEDENT> def _re_initialize(self, identifiers, n_models): <NEW_LINE> <INDENT> self.identifiers = identifiers <NEW_LINE> self.n_models = n_models <NEW_LINE> <DEDENT> def _eval(self, predictions, label, feval): <NEW_LINE> <INDENT> pred_ensemble = self.ensemble(predictions, self.identifiers) <NEW_LINE> return [fx.evaluate(pred_ensemble, label) for fx in feval] | An ensembler using the voting method.
Parameters
----------
ensemble_size : int
The number of base models selected by the voter. These selected models can be redundant. Default as 10. | 6259906e66673b3332c31c5a |
class ColumnProperties(proto.Message): <NEW_LINE> <INDENT> class HorizontalAlignment(proto.Enum): <NEW_LINE> <INDENT> HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 <NEW_LINE> LEADING = 1 <NEW_LINE> CENTER = 2 <NEW_LINE> TRAILING = 3 <NEW_LINE> <DEDENT> header = proto.Field(proto.STRING, number=1,) <NEW_LINE> horizontal_alignment = proto.Field( proto.ENUM, number=2, enum="Intent.Message.ColumnProperties.HorizontalAlignment", ) | Column properties for
[TableCard][google.cloud.dialogflow.v2beta1.Intent.Message.TableCard].
Attributes:
header (str):
Required. Column heading.
horizontal_alignment (google.cloud.dialogflow_v2beta1.types.Intent.Message.ColumnProperties.HorizontalAlignment):
Optional. Defines text alignment for all
cells in this column. | 6259906e7d43ff2487428040 |
class STDLogger(object): <NEW_LINE> <INDENT> def __init__(self, log): <NEW_LINE> <INDENT> if log not in SuiteLog.ALL_LOGS: <NEW_LINE> <INDENT> raise Exception('Unknown logger provided "{0}"'.format(log)) <NEW_LINE> <DEDENT> self.log_ = log <NEW_LINE> self.logger = logging.getLogger(log) <NEW_LINE> self.update_time = time() <NEW_LINE> <DEDENT> def log(self, level, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> itask = kwargs.pop("itask") <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> args = ("[%s] -%s" % (itask.identity, args[0]),) + args[1:] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> args = ("[%s] -%s" % (itask, args[0]),) + args[1:] <NEW_LINE> <DEDENT> args = tuple(args) <NEW_LINE> <DEDENT> self.update_time = time() <NEW_LINE> if self.logger.handlers: <NEW_LINE> <INDENT> self.logger.log(level, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = (get_current_time_string() + ' ' + logging._levelNames[level] + ' - ' + str(args[0]),) + tuple(*args[1:]) <NEW_LINE> if self.log_ in [SUITE_OUT, SUITE_LOG]: <NEW_LINE> <INDENT> print(*msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(*msg, file=sys.stderr) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def debug(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> self.log(logging.DEBUG, msg, *args, **kwargs) <NEW_LINE> <DEDENT> def info(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> self.log(logging.INFO, msg, *args, **kwargs) <NEW_LINE> <DEDENT> def warning(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> self.log(logging.WARNING, msg, *args, **kwargs) <NEW_LINE> <DEDENT> def warn(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> self.log(logging.WARNING, msg, *args, **kwargs) <NEW_LINE> <DEDENT> def error(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> self.log(logging.ERROR, msg, *args, **kwargs) <NEW_LINE> <DEDENT> def critical(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> self.log(logging.CRITICAL, msg, *args, **kwargs) <NEW_LINE> <DEDENT> def exception(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> if self.logger.handlers: <NEW_LINE> <INDENT> self.logger.exception(msg, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log(logging.ERROR, msg, *args, **kwargs) | Stand-in for the OUT, ERR loggers which logs messages to the out, err
logs if present otherwise to stdout, stderr.
For use in code which can be run be run within a suite or standalone.
If used with the LOG logger then output will only be printed if suite
logging has been set up. | 6259906e16aa5153ce401d37 |
class EdgeWithZeroProbabilityError(GraphError): <NEW_LINE> <INDENT> def __init__(self, edge): <NEW_LINE> <INDENT> msg = ("The edge '%s' has a probability of 0.0 and isn't of any use " "to the Graph!") % (edge) <NEW_LINE> super().__init__(msg) | Raised if an edge has the probability of 0.0. | 6259906e2ae34c7f260ac946 |
class V1NodeSelectorTerm(object): <NEW_LINE> <INDENT> def __init__(self, match_expressions=None): <NEW_LINE> <INDENT> self.swagger_types = { 'match_expressions': 'list[V1NodeSelectorRequirement]' } <NEW_LINE> self.attribute_map = { 'match_expressions': 'matchExpressions' } <NEW_LINE> self._match_expressions = match_expressions <NEW_LINE> <DEDENT> @property <NEW_LINE> def match_expressions(self): <NEW_LINE> <INDENT> return self._match_expressions <NEW_LINE> <DEDENT> @match_expressions.setter <NEW_LINE> def match_expressions(self, match_expressions): <NEW_LINE> <INDENT> if match_expressions is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `match_expressions`, must not be `None`") <NEW_LINE> <DEDENT> self._match_expressions = match_expressions <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return 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> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259906e97e22403b383c761 |
class HTTPRequestError(RemoteRetrieveError): <NEW_LINE> <INDENT> errno = 4035 <NEW_LINE> format = _('Request failed with status %(status)s: %(reason)s') | **4035** Raised when an HTTP request fails. Includes the response
status in the ``status`` attribute. | 6259906eaad79263cf430013 |
class CourseContentDetail(SecureAPIView): <NEW_LINE> <INDENT> def get(self, request, course_id, content_id): <NEW_LINE> <INDENT> response_data = {} <NEW_LINE> child_descriptor = None <NEW_LINE> base_uri = generate_base_uri(request) <NEW_LINE> response_data['uri'] = base_uri <NEW_LINE> course_descriptor, course_key, course_content = get_course(request, request.user, course_id) <NEW_LINE> if not course_descriptor: <NEW_LINE> <INDENT> return Response({}, status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> if course_id != content_id: <NEW_LINE> <INDENT> if 'include_fields' in request.query_params: <NEW_LINE> <INDENT> child_descriptor, child_key, child_content = get_course_child(request, request.user, course_key, content_id, True) <NEW_LINE> <DEDENT> usage_key = UsageKey.from_string(content_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> usage_key = modulestore().make_course_usage_key(course_key) <NEW_LINE> protocol = 'http' <NEW_LINE> if request.is_secure(): <NEW_LINE> <INDENT> protocol = protocol + 's' <NEW_LINE> <DEDENT> response_data['uri'] = '{}://{}/api/server/courses/{}'.format( protocol, request.get_host(), str(course_key) ) <NEW_LINE> <DEDENT> usage_key = usage_key.replace(course_key=modulestore().fill_in_run(usage_key.course_key)) <NEW_LINE> data_blocks = get_blocks( request, usage_key, depth=1, requested_fields=BLOCK_DATA_FIELDS ) <NEW_LINE> root_block = data_blocks['blocks'][data_blocks['root']] <NEW_LINE> response_data = _make_block_tree( request, data_blocks['blocks'], course_key, course_descriptor, root_block, content_block=child_descriptor ) <NEW_LINE> base_uri_without_qs = generate_base_uri(request, True) <NEW_LINE> resource_uri = '{}/groups'.format(base_uri_without_qs) <NEW_LINE> response_data['resources'] = [] <NEW_LINE> response_data['resources'].append({'uri': resource_uri}) <NEW_LINE> resource_uri = '{}/users'.format(base_uri_without_qs) <NEW_LINE> response_data['resources'].append({'uri': resource_uri}) <NEW_LINE> return Response(response_data, status=status.HTTP_200_OK) | **Use Case**
CourseContentDetail returns a JSON collection for a specified
CourseContent entity. If the specified CourseContent is the Course, the
course representation is returned. You can use the uri values in the
children collection in the JSON response to get details for that content
entity.
CourseContentDetail has an optional type parameter that allows you to
filter the response by content type. The value of the type parameter
matches the category value in the response. Valid values for the type
parameter are:
* chapter
* sequential
* vertical
* html
* problem
* discussion
* video
* [CONFIRM]
**Example Request**
GET /api/courses/{course_id}/content/{content_id}
**Response Values**
* category: The type of content.
* name: The name of the content entity.
* due: The due date.
* uri: The URI of the content entity.
* id: The unique identifier for the course.
* children: Content entities that this conent entity contains.
* resources: A list of URIs to available users and groups:
* Related Users /api/courses/{course_id}/content/{content_id}/users
* Related Groups /api/courses/{course_id}/content/{content_id}/groups | 6259906ea17c0f6771d5d7d8 |
class IPageBreadcrumbsDirective(IContentDirective): <NEW_LINE> <INDENT> name = zope.schema.TextLine( title=u"The name of the content provider.", required=False, default=u'breadcrumbs') <NEW_LINE> permission = Permission( title=u"Permission", description=u"The permission needed to use the view.", required=False, ) <NEW_LINE> crumb_parent = zope.configuration.fields.GlobalObject( title=u"Crumb parent", description=u"Getter of the crumb parent.", required=False, ) <NEW_LINE> follow_crumb = zope.configuration.fields.GlobalObject( title=u"Follow crumb", description=u"The breadcrumb factory.", required=False, ) <NEW_LINE> show_page_title = zope.configuration.fields.Bool( title=u"Show page title", required=False, default=True) | Define breadcrumbs content for a page. | 6259906e097d151d1a2c28ce |
class AdadeltaOptimizer(Optimizer): <NEW_LINE> <INDENT> _avg_squared_grad_acc_str = "_avg_squared_grad" <NEW_LINE> _avg_squared_update_acc_str = "_avg_squared_update" <NEW_LINE> def __init__(self, learning_rate, epsilon=1.0e-6, rho=0.95, **kwargs): <NEW_LINE> <INDENT> if learning_rate is None: <NEW_LINE> <INDENT> raise ValueError("learning_rate is not set.") <NEW_LINE> <DEDENT> if epsilon is None: <NEW_LINE> <INDENT> raise ValueError("epsilon is not set.") <NEW_LINE> <DEDENT> if rho is None: <NEW_LINE> <INDENT> raise ValueError("rho is not set.") <NEW_LINE> <DEDENT> super(AdadeltaOptimizer, self).__init__( learning_rate=learning_rate, **kwargs) <NEW_LINE> self.type = "adadelta" <NEW_LINE> self._epsilon = epsilon <NEW_LINE> self._rho = rho <NEW_LINE> <DEDENT> def _create_accumulators(self, block, parameters): <NEW_LINE> <INDENT> if not isinstance(block, framework.Block): <NEW_LINE> <INDENT> raise TypeError("block is not instance of framework.Block.") <NEW_LINE> <DEDENT> for p in parameters: <NEW_LINE> <INDENT> self._add_accumulator(self._avg_squared_grad_acc_str, p) <NEW_LINE> self._add_accumulator(self._avg_squared_update_acc_str, p) <NEW_LINE> <DEDENT> <DEDENT> def _append_optimize_op(self, block, param_and_grad): <NEW_LINE> <INDENT> if not isinstance(block, framework.Block): <NEW_LINE> <INDENT> raise TypeError("block is not instance of framework.Block.") <NEW_LINE> <DEDENT> avg_squared_grad_acc = self._get_accumulator( self._avg_squared_grad_acc_str, param_and_grad[0]) <NEW_LINE> avg_squared_update_acc = self._get_accumulator( self._avg_squared_update_acc_str, param_and_grad[0]) <NEW_LINE> adadelta_op = block.append_op( type=self.type, inputs={ "Param": param_and_grad[0], "Grad": param_and_grad[1], "AvgSquaredGrad": avg_squared_grad_acc, "AvgSquaredUpdate": avg_squared_update_acc }, outputs={ "ParamOut": param_and_grad[0], "AvgSquaredGradOut": avg_squared_grad_acc, "AvgSquaredUpdateOut": avg_squared_update_acc }, attrs={"epsilon": self._epsilon, "rho": self._rho}) <NEW_LINE> return adadelta_op | **Adadelta Optimizer**
Simple Adadelta optimizer with average squared grad state and
average squared update state.
The details of adadelta please refer to this
`ADADELTA: AN ADAPTIVE LEARNING RATE METHOD
<http://www.matthewzeiler.com/pubs/googleTR2012/googleTR2012.pdf>`_.
.. math::
E(g_t^2) &= \rho * E(g_{t-1}^2) + (1-\rho) * g^2 \\
learning\_rate &= sqrt( ( E(dx_{t-1}^2) + \epsilon ) / ( \
E(g_t^2) + \epsilon ) ) \\
E(dx_t^2) &= \rho * E(dx_{t-1}^2) + (1-\rho) * (-g*learning\_rate)^2
Args:
learning_rate(float): global leraning rate
rho(float): rho in equation
epsilon(float): epsilon in equation
Examples:
.. code-block:: python
optimizer = fluid.optimizer.Adadelta(
learning_rate=0.0003, epsilon=1.0e-6, rho=0.95)
_, params_grads = optimizer.minimize(cost) | 6259906e7d847024c075dc3b |
class InitialTempoFeature(featuresModule.FeatureExtractor): <NEW_LINE> <INDENT> id = 'R30' <NEW_LINE> def __init__(self, dataOrStream=None, *arguments, **keywords): <NEW_LINE> <INDENT> featuresModule.FeatureExtractor.__init__(self, dataOrStream=dataOrStream, *arguments, **keywords) <NEW_LINE> self.name = 'Initial Tempo' <NEW_LINE> self.description = 'Tempo in beats per minute at the start of the recording.' <NEW_LINE> self.isSequential = True <NEW_LINE> self.dimensions = 1 <NEW_LINE> <DEDENT> def _process(self): <NEW_LINE> <INDENT> triples = self.data['metronomeMarkBoundaries'] <NEW_LINE> mm = triples[0][2] <NEW_LINE> self._feature.vector[0] = mm.getQuarterBPM() | >>> from music21 import *
>>> s = corpus.parse('hwv56/movement3-05.md')
>>> fe = features.jSymbolic.InitialTempoFeature(s)
>>> f = fe.extract()
>>> f.vector # a default
[120.0]
>>> s = corpus.parse('hwv56/movement2-09.md') # has a tempos
>>> fe = features.jSymbolic.InitialTempoFeature(s)
>>> f = fe.extract()
>>> f.vector
[46.0] | 6259906ecc0a2c111447c700 |
class PorePressureLineSource(Source): <NEW_LINE> <INDENT> discretized_source_class = meta.DiscretizedPorePressureSource <NEW_LINE> pp = Float.T( default=1.0, help='initial excess pore pressure in [Pa]') <NEW_LINE> length = Float.T( default=0.0, help='length of the line source [m]') <NEW_LINE> azimuth = Float.T( default=0.0, help='azimuth direction, clockwise from north [deg]') <NEW_LINE> dip = Float.T( default=90., help='dip direction, downward from horizontal [deg]') <NEW_LINE> def base_key(self): <NEW_LINE> <INDENT> return Source.base_key(self) + (self.azimuth, self.dip, self.length) <NEW_LINE> <DEDENT> def get_factor(self): <NEW_LINE> <INDENT> return self.pp <NEW_LINE> <DEDENT> def discretize_basesource(self, store, target=None): <NEW_LINE> <INDENT> n = 2 * int(math.ceil(self.length / num.min(store.config.deltas))) + 1 <NEW_LINE> a = num.linspace(-0.5 * self.length, 0.5 * self.length, n) <NEW_LINE> sa = math.sin(self.azimuth * d2r) <NEW_LINE> ca = math.cos(self.azimuth * d2r) <NEW_LINE> sd = math.sin(self.dip * d2r) <NEW_LINE> cd = math.cos(self.dip * d2r) <NEW_LINE> points = num.zeros((n, 3)) <NEW_LINE> points[:, 0] = self.north_shift + a * ca * cd <NEW_LINE> points[:, 1] = self.east_shift + a * sa * cd <NEW_LINE> points[:, 2] = self.depth + a * sd <NEW_LINE> return meta.DiscretizedPorePressureSource( times=util.num_full(n, self.time), lat=self.lat, lon=self.lon, north_shifts=points[:, 0], east_shifts=points[:, 1], depths=points[:, 2], pp=num.ones(n) / n) | Excess pore pressure line source.
The line source is centered at (north_shift, east_shift, depth). | 6259906e91f36d47f2231abe |
class FetchOptions(object): <NEW_LINE> <INDENT> _DEFAULT_CIPHERLIST = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA" <NEW_LINE> def __init__(self, config): <NEW_LINE> <INDENT> self.connectTimeout = config.getint("http", "connect_timeout") <NEW_LINE> self.readTimeout = config.getint("http", "read_timeout") <NEW_LINE> self.redirectDepth = config.getint("http", "redirect_depth") <NEW_LINE> self.userAgent = None <NEW_LINE> self.curlVerbose = False <NEW_LINE> self.sslVersion = pycurl.SSLVERSION_DEFAULT <NEW_LINE> self.useSubprocess = True <NEW_LINE> self.staticCAPath = None <NEW_LINE> self.cipherList = self._DEFAULT_CIPHERLIST <NEW_LINE> if config.has_option("http", "user_agent"): <NEW_LINE> <INDENT> self.userAgent = config.get("http", "user_agent") <NEW_LINE> <DEDENT> if config.has_option("http", "curl_verbose"): <NEW_LINE> <INDENT> self.curlVerbose = config.getboolean("http", "curl_verbose") <NEW_LINE> <DEDENT> if config.has_option("http", "fetch_in_subprocess"): <NEW_LINE> <INDENT> self.useSubprocess = config.getboolean( "http", "fetch_in_subprocess") <NEW_LINE> <DEDENT> if config.has_option("http", "cipherList"): <NEW_LINE> <INDENT> self.cipherList = config.get("http", "cipherList") <NEW_LINE> <DEDENT> if config.has_option("http", "ssl_version"): <NEW_LINE> <INDENT> versionStr = config.get("http", "ssl_version") <NEW_LINE> try: <NEW_LINE> <INDENT> self.sslVersion = getattr(pycurl, 'SSLVERSION_' + versionStr) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError( "SSL version '{}' specified in config is unsupported.".format(versionStr)) <NEW_LINE> <DEDENT> <DEDENT> if config.has_option("http", "static_ca_path"): <NEW_LINE> <INDENT> self.staticCAPath = config.get("http", "static_ca_path") | HTTP fetcher options like timeouts. | 6259906ebe8e80087fbc08ec |
class NotDashboardContextException(Exception): <NEW_LINE> <INDENT> pass | To be raised when a context has no faceted view defined on it. | 6259906ed486a94d0ba2d81e |
class SendTrytesCommand(FilterCommand): <NEW_LINE> <INDENT> command = 'sendTrytes' <NEW_LINE> def get_request_filter(self): <NEW_LINE> <INDENT> return SendTrytesRequestFilter() <NEW_LINE> <DEDENT> def get_response_filter(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _execute(self, request): <NEW_LINE> <INDENT> depth = request['depth'] <NEW_LINE> min_weight_magnitude = request['minWeightMagnitude'] <NEW_LINE> trytes = request['trytes'] <NEW_LINE> reference = request['reference'] <NEW_LINE> gta_response = GetTransactionsToApproveCommand(self.adapter)( depth=depth, reference=reference, ) <NEW_LINE> att_response = AttachToTangleCommand(self.adapter)( branchTransaction = gta_response.get('branchTransaction'), trunkTransaction = gta_response.get('trunkTransaction'), minWeightMagnitude = min_weight_magnitude, trytes = trytes, ) <NEW_LINE> trytes = att_response['trytes'] <NEW_LINE> BroadcastAndStoreCommand(self.adapter)(trytes=trytes) <NEW_LINE> return { 'trytes': trytes, } | Executes `sendTrytes` extended API command.
See :py:meth:`iota.api.IotaApi.send_trytes` for more info. | 6259906e009cb60464d02d95 |
class InvalidKubeHostnameError(CouchDiscGeneralError): <NEW_LINE> <INDENT> _msg = ("The Hostname: {host} doesn't match the signature of a kubernetes" " statefulset hostname.") | Invalid kubernetes hostname
Raised when a host doesn't match the signature of a kubernetes statefulset
hostname.
Provides a `_msg` that includes the host passed in as a kwarg.
Example:
>>> raise InvalidKubeHostnameError(host='google.com')
InvalidKubeHostnameError: The Hostname: google.com doesn't match the
signature of a kubernetes statefulset hostname. | 6259906e7d43ff2487428041 |
class RegisterForm(ModelForm): <NEW_LINE> <INDENT> password = forms.CharField(widget=forms.PasswordInput()) <NEW_LINE> cpassword = forms.CharField(widget=forms.PasswordInput(), label="Confirm password") <NEW_LINE> email = forms.CharField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Patient <NEW_LINE> fields = ['name', 'username', 'date_of_birth', 'contact_information', 'preferred_hospital', 'insurance_id','emergency_contact'] <NEW_LINE> widgets = { 'contact_information': Textarea(attrs={'rows': 5}), 'emergency_contact': Textarea(attrs={'rows': 5}), } <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> for myField in self.fields: <NEW_LINE> <INDENT> self.fields[myField].widget.attrs['class'] = 'form-control' | RegisterForm for a user registering an account
Patients use this while doctors and nurses must be added via a system administrator | 6259906e97e22403b383c763 |
class PageLayout(AbstractPageLayout): <NEW_LINE> <INDENT> orientation = Vertical <NEW_LINE> def updatePagePositions(self): <NEW_LINE> <INDENT> if self.orientation == Vertical: <NEW_LINE> <INDENT> width = max((p.width for p in self), default=0) + self.margin * 2 <NEW_LINE> top = self.margin <NEW_LINE> for page in self: <NEW_LINE> <INDENT> page.x = (width - page.width) / 2 <NEW_LINE> page.y = top <NEW_LINE> top += page.height + self.spacing <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> height = max((p.height for p in self), default=0) + self.margin * 2 <NEW_LINE> left = self.margin <NEW_LINE> for page in self: <NEW_LINE> <INDENT> page.x = left <NEW_LINE> page.y = (height - page.height) / 2 <NEW_LINE> left += page.width + self.spacing | A basic layout that shows pages from right to left or top to bottom.
Additional instance attribute:
`orientation`: Horizontal or Vertical (default) | 6259906e67a9b606de5476d2 |
class Solution: <NEW_LINE> <INDENT> def maxPathSum(self, root): <NEW_LINE> <INDENT> maxRootToAny, maxAnyToAny = self._maxPathSum(root) <NEW_LINE> return maxAnyToAny <NEW_LINE> <DEDENT> def _maxPathSum(self, root): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return (float("-inf"), float("-inf")) <NEW_LINE> <DEDENT> leftRootToAny, leftAnyToAny = self._maxPathSum(root.left) <NEW_LINE> rightRootToAny, rightAnyToAny = self._maxPathSum(root.right) <NEW_LINE> maxRootToAny = max(leftRootToAny + root.val, rightRootToAny + root.val, root.val) <NEW_LINE> maxAnyToAny = max(leftAnyToAny, rightAnyToAny, leftRootToAny + rightRootToAny + root.val, maxRootToAny) <NEW_LINE> return (maxRootToAny, maxAnyToAny) | @param root: The root of binary tree.
@return: An integer | 6259906e76e4537e8c3f0de3 |
class Modified_Resnet50(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_classs=100): <NEW_LINE> <INDENT> super(Modified_Resnet50, self).__init__() <NEW_LINE> model = torchvision.models.resnet50(pretrained=True) <NEW_LINE> self.num_classs = num_classs <NEW_LINE> temp = [] <NEW_LINE> for i, m in enumerate(model.children()): <NEW_LINE> <INDENT> if i <= 8: <NEW_LINE> <INDENT> temp.append(m) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.classifier = nn.Linear(in_features=2048, out_features=num_classs) <NEW_LINE> <DEDENT> <DEDENT> self.features = nn.Sequential(*temp) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.features(x) <NEW_LINE> x = x.view(x.size(0), -1) <NEW_LINE> x = self.classifier(x) <NEW_LINE> return x | docstring for ClassName | 6259906ef9cc0f698b1c5efb |
class Foot_Pound( Unit ): <NEW_LINE> <INDENT> standard= Joule <NEW_LINE> name= "ft.lb." <NEW_LINE> factor= 0.73756215 | Foot-Pound | 6259906e56b00c62f0fb412f |
class ComputeInstancesSetMachineTypeRequest(_messages.Message): <NEW_LINE> <INDENT> instance = _messages.StringField(1, required=True) <NEW_LINE> instancesSetMachineTypeRequest = _messages.MessageField('InstancesSetMachineTypeRequest', 2) <NEW_LINE> project = _messages.StringField(3, required=True) <NEW_LINE> requestId = _messages.StringField(4) <NEW_LINE> zone = _messages.StringField(5, required=True) | A ComputeInstancesSetMachineTypeRequest object.
Fields:
instance: Name of the instance scoping this request.
instancesSetMachineTypeRequest: A InstancesSetMachineTypeRequest resource
to be passed as the request body.
project: Project ID for this request.
requestId: An optional request ID to identify requests. Specify a unique
request ID so that if you must retry your request, the server will know
to ignore the request if it has already been completed. For example,
consider a situation where you make an initial request and then the
request times out. If you make the request again with the same request
ID, the server can check if original operation with the same request ID
was received, and if so, will ignore the second request. This prevents
clients from accidentally creating duplicate commitments.
zone: The name of the zone for this request. | 6259906e7047854f46340c16 |
class ASTNode(object): <NEW_LINE> <INDENT> def __init__(self, parent, value, n_type): <NEW_LINE> <INDENT> self._parent = parent <NEW_LINE> self.value = value <NEW_LINE> self.n_type = n_type <NEW_LINE> self.child_nodes = [] <NEW_LINE> <DEDENT> def add_child(self, node, set_parent=True): <NEW_LINE> <INDENT> if set_parent: <NEW_LINE> <INDENT> node.set_parent_node(self) <NEW_LINE> <DEDENT> self.child_nodes.append(node) <NEW_LINE> <DEDENT> def set_parent_node(self, node): <NEW_LINE> <INDENT> self._parent = node <NEW_LINE> if node != None: <NEW_LINE> <INDENT> node.add_child(self, set_parent=False); <NEW_LINE> <DEDENT> <DEDENT> def get_parent(self, ): <NEW_LINE> <INDENT> return self._parent | A Node in our AST | 6259906e76e4537e8c3f0de4 |
class Action: <NEW_LINE> <INDENT> def __init__(self, type): <NEW_LINE> <INDENT> self._type = type <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._type | This class represents a move in the puzzle. Depending on the state from which
the agent chooses the move - type of the action can be 'r', 'l', 'u', 'd', 't' | 6259906eb7558d5895464b62 |
class StateCompiler(object): <NEW_LINE> <INDENT> def __init__(self, root: str, environment: str = ObjectResolver.DEFAULT_ENV): <NEW_LINE> <INDENT> self._root = root <NEW_LINE> self._environment = environment <NEW_LINE> self._tasks = self._object_tree = None <NEW_LINE> <DEDENT> def _get_state_tasks(self) -> list: <NEW_LINE> <INDENT> tasks = [] <NEW_LINE> for obj_id in self.tree: <NEW_LINE> <INDENT> tasks.append(StateTask(state_task={obj_id: self.tree[obj_id]})) <NEW_LINE> <DEDENT> return tasks <NEW_LINE> <DEDENT> def compile(self, uri: str) -> 'StateCompiler': <NEW_LINE> <INDENT> self._tasks = None <NEW_LINE> self._object_tree = ObjectTree(ObjectResolver(path=self._root, env=self._environment)) <NEW_LINE> self._object_tree.load(uri) <NEW_LINE> return self <NEW_LINE> <DEDENT> @property <NEW_LINE> def tree(self) -> dict: <NEW_LINE> <INDENT> if self._object_tree is None: <NEW_LINE> <INDENT> raise sugar.lib.exceptions.SugarSCException("Nothing compiled yet") <NEW_LINE> <DEDENT> return self._object_tree.tree <NEW_LINE> <DEDENT> @property <NEW_LINE> def tasklist(self) -> typing.Tuple[StateTask]: <NEW_LINE> <INDENT> if self._tasks is None: <NEW_LINE> <INDENT> self._tasks = tuple(self._get_state_tasks()) <NEW_LINE> <DEDENT> return self._tasks <NEW_LINE> <DEDENT> def to_yaml(self) -> str: <NEW_LINE> <INDENT> return (yaml.dump(self.tree, default_flow_style=False) or "").strip() | State Compiler class. | 6259906e92d797404e38978b |
class Shape: <NEW_LINE> <INDENT> def __init__(self, renderer): <NEW_LINE> <INDENT> self.renderer = renderer <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def resize(self, factor): <NEW_LINE> <INDENT> pass | The bridge class | 6259906e2c8b7c6e89bd5046 |
class AbstractPartitionDiagrams(Parent, UniqueRepresentation): <NEW_LINE> <INDENT> Element = AbstractPartitionDiagram <NEW_LINE> def __init__(self, order, category=None): <NEW_LINE> <INDENT> if category is None: <NEW_LINE> <INDENT> category = FiniteEnumeratedSets() <NEW_LINE> <DEDENT> Parent.__init__(self, category=category) <NEW_LINE> self.order = order <NEW_LINE> if order in ZZ: <NEW_LINE> <INDENT> base_set = frozenset(list(range(1,order+1)) + list(range(-order,0))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base_set = frozenset(list(range(1,ZZ(ZZ(1)/ZZ(2) + order)+1)) + list(range(ZZ(-ZZ(1)/ZZ(2) - order),0))) <NEW_LINE> <DEDENT> self._set = base_set <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "{} diagrams of order {}".format(self._name, self.order) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for i in self._diagram_func.__func__(self.order): <NEW_LINE> <INDENT> yield self.element_class(self, i) <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, obj): <NEW_LINE> <INDENT> if not hasattr(obj, '_base_diagram'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj = self._element_constructor_(obj) <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> if obj.base_diagram(): <NEW_LINE> <INDENT> tst = sorted(flatten(obj.base_diagram())) <NEW_LINE> if len(tst) % 2 or tst != list(range(-len(tst)//2,0)) + list(range(1,len(tst)//2+1)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> return self.order == 0 <NEW_LINE> <DEDENT> def _element_constructor_(self, d): <NEW_LINE> <INDENT> return self.element_class(self, d) | This is an abstract base class for partition diagrams.
The primary use of this class is to serve as basis keys for
diagram algebras, but diagrams also have properties in their
own right. Furthermore, this class is meant to be extended to
create more efficient contains methods.
INPUT:
- ``order`` -- integer or integer `+ 1/2`; the order of the diagrams
- ``category`` -- (default: ``FiniteEnumeratedSets()``); the category
All concrete classes should implement attributes
- ``_name`` -- the name of the class
- ``_diagram_func`` -- an iterator function that takes the order
as its only input
EXAMPLES::
sage: import sage.combinat.diagram_algebras as da
sage: pd = da.PartitionDiagrams(2)
sage: pd
Partition diagrams of order 2
sage: pd.an_element() in pd
True
sage: elm = pd([[1,2],[-1,-2]])
sage: elm in pd
True | 6259906e8da39b475be04a4e |
class LaserStimulus(object): <NEW_LINE> <INDENT> id = int() <NEW_LINE> description = str() <NEW_LINE> num_lasers = int() <NEW_LINE> odorvalves = [] <NEW_LINE> flows = [] <NEW_LINE> dillution=int() <NEW_LINE> laserstims = [] <NEW_LINE> within_block_repeats = int() <NEW_LINE> trial_type = str() <NEW_LINE> def __init__(self, odorvalves, flows, id, description, trial_type, **kwds): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.description = description <NEW_LINE> self.flows = [] <NEW_LINE> self.odorvalves = [] <NEW_LINE> self.trial_type = trial_type <NEW_LINE> for ov in odorvalves: <NEW_LINE> <INDENT> self.odorvalves.append(ov) <NEW_LINE> <DEDENT> for flow in flows: <NEW_LINE> <INDENT> self.flows.append(flow) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def __str__(self,indent = ''): <NEW_LINE> <INDENT> return indent+ '\ttrial type: ' +str(self.trial_type) + "\t\todor valves: " + str(self.odorvalves[0]) + "\t\tmfc flows: " + str(self.flows[0]) | Objects representing a stimulus set | 6259906ea219f33f346c8069 |
class RequestHeaderMatchConditionParameters(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'odata_type': {'required': True, 'constant': True}, 'operator': {'required': True}, } <NEW_LINE> _attribute_map = { 'odata_type': {'key': '@odata\\.type', 'type': 'str'}, 'selector': {'key': 'selector', 'type': 'str'}, 'operator': {'key': 'operator', 'type': 'str'}, 'negate_condition': {'key': 'negateCondition', 'type': 'bool'}, 'match_values': {'key': 'matchValues', 'type': '[str]'}, 'transforms': {'key': 'transforms', 'type': '[str]'}, } <NEW_LINE> odata_type = "#Microsoft.Azure.Cdn.Models.DeliveryRuleRequestHeaderConditionParameters" <NEW_LINE> def __init__( self, *, operator: Union[str, "RequestHeaderOperator"], selector: Optional[str] = None, negate_condition: Optional[bool] = None, match_values: Optional[List[str]] = None, transforms: Optional[List[Union[str, "Transform"]]] = None, **kwargs ): <NEW_LINE> <INDENT> super(RequestHeaderMatchConditionParameters, self).__init__(**kwargs) <NEW_LINE> self.selector = selector <NEW_LINE> self.operator = operator <NEW_LINE> self.negate_condition = negate_condition <NEW_LINE> self.match_values = match_values <NEW_LINE> self.transforms = transforms | Defines the parameters for RequestHeader match conditions.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar odata_type: Required. Default value:
"#Microsoft.Azure.Cdn.Models.DeliveryRuleRequestHeaderConditionParameters".
:vartype odata_type: str
:param selector: Name of Header to be matched.
:type selector: str
:param operator: Required. Describes operator to be matched. Possible values include: "Any",
"Equal", "Contains", "BeginsWith", "EndsWith", "LessThan", "LessThanOrEqual", "GreaterThan",
"GreaterThanOrEqual", "RegEx".
:type operator: str or ~azure.mgmt.cdn.models.RequestHeaderOperator
:param negate_condition: Describes if this is negate condition or not.
:type negate_condition: bool
:param match_values: The match value for the condition of the delivery rule.
:type match_values: list[str]
:param transforms: List of transforms.
:type transforms: list[str or ~azure.mgmt.cdn.models.Transform] | 6259906e4f88993c371f1150 |
class Trajectory: <NEW_LINE> <INDENT> def __init__(self, object_id, points=list(), timestamps=list()): <NEW_LINE> <INDENT> self.object_id = object_id <NEW_LINE> self.raw_points = points <NEW_LINE> self.timestamps = timestamps <NEW_LINE> self.length = len(points) <NEW_LINE> <DEDENT> def add_point(self, lat, lon, timestamp): <NEW_LINE> <INDENT> self.raw_points.append((lat,lon)) <NEW_LINE> self.timestamps.append(timestamp) <NEW_LINE> self.length += 1 <NEW_LINE> <DEDENT> def t2string(self): <NEW_LINE> <INDENT> return "Trajectory: " + str(self.object_id) + " " + str(len(self.raw_points)) | Trajectory class
for pre-processing | 6259906e32920d7e50bc78a7 |
class RenderCommentListNode(CommentListNode): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def handle_token(cls, parser, token): <NEW_LINE> <INDENT> tokens = token.contents.split() <NEW_LINE> if tokens[1] != 'for': <NEW_LINE> <INDENT> raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) <NEW_LINE> <DEDENT> extra_kw = {} <NEW_LINE> if tokens[-2] == 'limit': <NEW_LINE> <INDENT> if tokens[-1].isdigit(): <NEW_LINE> <INDENT> extra_kw['limit'] = tokens.pop(-1) <NEW_LINE> tokens.pop(-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise template.TemplateSyntaxError( "When using 'limit' with %r tag, it needs to be followed by a positive integer" % (tokens[0],)) <NEW_LINE> <DEDENT> <DEDENT> if tokens[-1] in ('flat', 'root_only', 'newest', 'admin'): <NEW_LINE> <INDENT> extra_kw[str(tokens.pop())] = True <NEW_LINE> <DEDENT> if len(tokens) == 3: <NEW_LINE> <INDENT> return cls( object_expr=parser.compile_filter(tokens[2]), **extra_kw ) <NEW_LINE> <DEDENT> elif len(tokens) == 4: <NEW_LINE> <INDENT> return cls( ctype=BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr=parser.compile_filter(tokens[3]), **extra_kw ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise template.TemplateSyntaxError("%r tag takes either 2 or 3 arguments" % (tokens[0],)) <NEW_LINE> <DEDENT> <DEDENT> def render(self, context): <NEW_LINE> <INDENT> ctype, object_pk = self.get_target_ctype_pk(context) <NEW_LINE> if object_pk: <NEW_LINE> <INDENT> template_search_list = [ "comments/%s/%s/list.html" % (ctype.app_label, ctype.model), "comments/%s/list.html" % ctype.app_label, "comments/list.html" ] <NEW_LINE> qs = self.get_queryset(context) <NEW_LINE> context = context.flatten() <NEW_LINE> context.update({ "comment_list": self.get_context_value_from_queryset(context, qs), }) <NEW_LINE> return render_to_string(template_search_list, context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' | Render the comments list. | 6259906ea8370b77170f1c28 |
class PreparedStatement(object): <NEW_LINE> <INDENT> column_metadata = None <NEW_LINE> query_id = None <NEW_LINE> query_string = None <NEW_LINE> keyspace = None <NEW_LINE> routing_key_indexes = None <NEW_LINE> consistency_level = None <NEW_LINE> serial_consistency_level = None <NEW_LINE> def __init__(self, column_metadata, query_id, routing_key_indexes, query, keyspace, consistency_level=None, serial_consistency_level=None, fetch_size=None): <NEW_LINE> <INDENT> self.column_metadata = column_metadata <NEW_LINE> self.query_id = query_id <NEW_LINE> self.routing_key_indexes = routing_key_indexes <NEW_LINE> self.query_string = query <NEW_LINE> self.keyspace = keyspace <NEW_LINE> self.consistency_level = consistency_level <NEW_LINE> self.serial_consistency_level = serial_consistency_level <NEW_LINE> self.fetch_size = fetch_size <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_message(cls, query_id, column_metadata, cluster_metadata, query, keyspace): <NEW_LINE> <INDENT> if not column_metadata: <NEW_LINE> <INDENT> return PreparedStatement(column_metadata, query_id, None, query, keyspace) <NEW_LINE> <DEDENT> partition_key_columns = None <NEW_LINE> routing_key_indexes = None <NEW_LINE> ks_name, table_name, _, _ = column_metadata[0] <NEW_LINE> ks_meta = cluster_metadata.keyspaces.get(ks_name) <NEW_LINE> if ks_meta: <NEW_LINE> <INDENT> table_meta = ks_meta.tables.get(table_name) <NEW_LINE> if table_meta: <NEW_LINE> <INDENT> partition_key_columns = table_meta.partition_key <NEW_LINE> statement_indexes = dict((c[2], i) for i, c in enumerate(column_metadata)) <NEW_LINE> try: <NEW_LINE> <INDENT> routing_key_indexes = [statement_indexes[c.name] for c in partition_key_columns] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return PreparedStatement(column_metadata, query_id, routing_key_indexes, query, keyspace) <NEW_LINE> <DEDENT> def bind(self, values): <NEW_LINE> <INDENT> return BoundStatement(self).bind(values) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> consistency = ConsistencyLevel.value_to_name.get(self.consistency_level, 'Not Set') <NEW_LINE> return (u'<PreparedStatement query="%s", consistency=%s>' % (self.query_string, consistency)) <NEW_LINE> <DEDENT> __repr__ = __str__ | A statement that has been prepared against at least one Cassandra node.
Instances of this class should not be created directly, but through
:meth:`.Session.prepare()`.
A :class:`.PreparedStatement` should be prepared only once. Re-preparing a statement
may affect performance (as the operation requires a network roundtrip). | 6259906e3d592f4c4edbc741 |
class Hmp4030: <NEW_LINE> <INDENT> def __init__(self, rm, visaName): <NEW_LINE> <INDENT> self.rm = rm <NEW_LINE> self.visaName = visaName <NEW_LINE> self.handle = None <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.handle = self.rm.get_instrument(self.visaName) <NEW_LINE> self.handle.write('*RST') <NEW_LINE> time.sleep(.5) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print('Hmp4030.open() failed !') <NEW_LINE> raise <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.handle.write('*RST') <NEW_LINE> self.handle.close() <NEW_LINE> self.handle = None <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print('Hmp4030.close() failed !') <NEW_LINE> raise <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def setVoltage(self, channel, voltage): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmd = 'OUT%d' % channel <NEW_LINE> cmd = 'INST ' + cmd + ';' <NEW_LINE> self.handle.write(cmd) <NEW_LINE> cmd = 'VOLT %f;' % voltage <NEW_LINE> self.handle.write(cmd) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print('HMP4030.setVoltage() failed !') <NEW_LINE> raise <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def setCurrent(self, channel, current): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmd = 'OUT%d' % (channel) <NEW_LINE> cmd = 'INST ' + cmd + ';' <NEW_LINE> self.handle.write(cmd) <NEW_LINE> time.sleep(.1) <NEW_LINE> cmd = 'CURR %f;' % (current) <NEW_LINE> time.sleep(.1) <NEW_LINE> self.handle.write(cmd) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print('HMP4030:setCurrent() !') <NEW_LINE> raise <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def enableOutputs(self, mask, state): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for i in range(0, 3): <NEW_LINE> <INDENT> cmd = 'INST ' <NEW_LINE> cmd = cmd + ('OUT%d;' % (i + 1)) <NEW_LINE> self.handle.write(cmd) <NEW_LINE> time.sleep(0.1) <NEW_LINE> cmd = 'OUTP:SEL ' <NEW_LINE> if (mask & 1<<i) != 0: <NEW_LINE> <INDENT> cmd = cmd + '1;' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = cmd + '0;' <NEW_LINE> <DEDENT> self.handle.write(cmd) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> print('HMP4030:setOutput() selection failed !') <NEW_LINE> raise <NEW_LINE> <DEDENT> cmd = 'OUTP:GEN ' <NEW_LINE> if state == True: <NEW_LINE> <INDENT> cmd = cmd + 'ON;' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = cmd + 'OFF;' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.handle.write(cmd) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print('HMP4030.setOutput() set state failed !') <NEW_LINE> raise <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def sendCommand(self, cmd): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.handle.write(cmd) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print('HMP4030:sendCommand() failed !') <NEW_LINE> raise | Class implementing SCPI control of Hameg HMP4030 power source
control via Agilent IO Libraries and VISA interface | 6259906e4428ac0f6e659d94 |
class ClientList(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._data = {} <NEW_LINE> self.lock = Lock("ClientList") <NEW_LINE> self._nextid = 0 <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._data.get(key) <NEW_LINE> <DEDENT> def __delitem__(self, clientid): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> self.remove(clientid) <NEW_LINE> <DEDENT> <DEDENT> def remove(self, clientid): <NEW_LINE> <INDENT> c = self._data[clientid] <NEW_LINE> del self._data[clientid] <NEW_LINE> del self._data[c.ownerid] <NEW_LINE> c.freeze = True <NEW_LINE> <DEDENT> def add(self, arg, principal, security): <NEW_LINE> <INDENT> c = ClientRecord(self._nextid, arg, principal, security=security) <NEW_LINE> if c.ownerid in self._data: <NEW_LINE> <INDENT> raise RuntimeError("ownerid %r already in ClientList" % c.ownerid) <NEW_LINE> <DEDENT> self._nextid += 1 <NEW_LINE> self._data[c.ownerid] = c <NEW_LINE> self._data[c.clientid] = c <NEW_LINE> return c <NEW_LINE> <DEDENT> def wipe(self): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> self._data = {} | Manage mapping of clientids to server data.
Handles the handing out of clientids, the mapping of
client supplied ownerid to server supplied clientid, and
the mapping of either to ClientRecords, where all of the
server's state data related to the client can be accessed. | 6259906e7d43ff2487428042 |
class TemperatureMeasurement(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(TemperatureMeasurement, self).__init__(*args, **kwargs) <NEW_LINE> cls = 'IviDmm' <NEW_LINE> grp = 'TemperatureMeasurement' <NEW_LINE> ivi.add_group_capability(self, cls+grp) <NEW_LINE> self._temperature_transducer_type = '' <NEW_LINE> ivi.add_property(self, 'temperature.transducer_type', self._get_temperature_transducer_type, self._set_temperature_transducer_type) <NEW_LINE> <DEDENT> def _get_temperature_transducer_type(self): <NEW_LINE> <INDENT> return self._temperature_transducer_type <NEW_LINE> <DEDENT> def _set_temperature_transducer_type(self, value): <NEW_LINE> <INDENT> if value not in TemperatureTransducerType: <NEW_LINE> <INDENT> raise ivi.ValueNotSupportedException() <NEW_LINE> <DEDENT> self._temperature_transducer_type = value | Extension IVI methods for DMMs that can take temperature measurements | 6259906e4527f215b58eb5d0 |
class Base32(object): <NEW_LINE> <INDENT> def encode(self, s): <NEW_LINE> <INDENT> return base64.b32encode(s) <NEW_LINE> <DEDENT> def decode(self, s): <NEW_LINE> <INDENT> return base64.b32decode(s) | AUTHORS:
v0.2.0+ --> pydsigner | 6259906e71ff763f4b5e9008 |
class cmd_list(Command): <NEW_LINE> <INDENT> synopsis = "%prog [options]" <NEW_LINE> takes_options = [ Option("-H", "--URL", help="LDB URL for database or target server", type=str, metavar="URL", dest="H"), Option("--full-dn", dest="full_dn", default=False, action='store_true', help="Display DNs including the base DN."), ] <NEW_LINE> takes_optiongroups = { "sambaopts": options.SambaOptions, "credopts": options.CredentialsOptions, "versionopts": options.VersionOptions, } <NEW_LINE> def run(self, sambaopts=None, credopts=None, versionopts=None, H=None, full_dn=False): <NEW_LINE> <INDENT> lp = sambaopts.get_loadparm() <NEW_LINE> creds = credopts.get_credentials(lp, fallback_machine=True) <NEW_LINE> samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) <NEW_LINE> domain_dn = ldb.Dn(samdb, samdb.domain_dn()) <NEW_LINE> res = samdb.search(domain_dn, scope=ldb.SCOPE_SUBTREE, expression="(objectClass=organizationalUnit)", attrs=[]) <NEW_LINE> if (len(res) == 0): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for msg in sorted(res, key=attrgetter('dn')): <NEW_LINE> <INDENT> if not full_dn: <NEW_LINE> <INDENT> msg.dn.remove_base_components(len(domain_dn)) <NEW_LINE> <DEDENT> self.outf.write("%s\n" % str(msg.dn)) | List all organizational units.
Example:
samba-tool ou listobjects
The example shows how an administrator would list all organizational
units. | 6259906efff4ab517ebcf07b |
class KeypressPrompt(Prompt): <NEW_LINE> <INDENT> _ui_data = UIData.title['prompts']['keypress'] <NEW_LINE> _rel_vert_loc = _ui_data['relative vertical location'] <NEW_LINE> _width = _ui_data['width'] <NEW_LINE> _height = _ui_data['height'] <NEW_LINE> _texts = _ui_data['texts'] <NEW_LINE> def __init__(self, text_key): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> text = self._texts[text_key] <NEW_LINE> text_offset = (self._width - len(text)) // 2 <NEW_LINE> curses.curs_set(False) <NEW_LINE> curses.noecho() <NEW_LINE> self._win.addstr(self._vpadding, text_offset, text, curses.A_BOLD) <NEW_LINE> <DEDENT> def get_key(self): <NEW_LINE> <INDENT> curses.noecho() <NEW_LINE> curses.curs_set(False) <NEW_LINE> return self._win.getch() | prompt that asks the user for a single keypress. | 6259906ea8370b77170f1c29 |
@ejit <NEW_LINE> class ArithmeticError(StandardError): <NEW_LINE> <INDENT> pass | Base class for arithmetic errors. | 6259906eaad79263cf430017 |
class UtilsError(STDError): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(UtilsError, self).__init__(*args, **kwargs) | Raised for Uploader exceptions | 6259906e3539df3088ecdafe |
class DBRatings(mysqlpool.MysqlPool): <NEW_LINE> <INDENT> pass | This class contains only methods used by responder on certain queries | 6259906ea17c0f6771d5d7da |
class UserAvatar(db.Model, BaseModel): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> b64string = db.Column(db.String) <NEW_LINE> mimetype = db.Column(db.String(16)) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey("user.id")) <NEW_LINE> @staticmethod <NEW_LINE> def from_raw_image(raw_image: RawImage, user: User): <NEW_LINE> <INDENT> UserAvatar.create( b64string=raw_image.b64string, mimetype=raw_image.mimetype, user=user, ) | Модель аватара пользователя | 6259906e38b623060ffaa484 |
class NotifyOptions(BaseOptions): <NEW_LINE> <INDENT> optParameters = [ ['port', 'p', 8000, 'The port number to listen on.'], ['iface', None, 'localhost', 'The interface to listen on.'], ] | Options global to everything. | 6259906edd821e528d6da5b2 |
class MySqlConnector: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.my_db = Db.connect(**config) <NEW_LINE> self.cursor = self.my_db.cursor() <NEW_LINE> <DEDENT> except Db.Error as err: <NEW_LINE> <INDENT> raise Exception(err) <NEW_LINE> <DEDENT> <DEDENT> def get_db_cursor(self): <NEW_LINE> <INDENT> return self.cursor <NEW_LINE> <DEDENT> def get_db_connect_obj(self): <NEW_LINE> <INDENT> return self.my_db | Class to connect and interact with mysql
| 6259906ecc0a2c111447c702 |
class MachineTypesScopedList(messages.Message): <NEW_LINE> <INDENT> class WarningValue(messages.Message): <NEW_LINE> <INDENT> class CodeValueValuesEnum(messages.Enum): <NEW_LINE> <INDENT> DEPRECATED_RESOURCE_USED = 0 <NEW_LINE> DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 1 <NEW_LINE> INJECTED_KERNELS_DEPRECATED = 2 <NEW_LINE> NEXT_HOP_ADDRESS_NOT_ASSIGNED = 3 <NEW_LINE> NEXT_HOP_CANNOT_IP_FORWARD = 4 <NEW_LINE> NEXT_HOP_INSTANCE_NOT_FOUND = 5 <NEW_LINE> NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 6 <NEW_LINE> NEXT_HOP_NOT_RUNNING = 7 <NEW_LINE> NOT_CRITICAL_ERROR = 8 <NEW_LINE> NO_RESULTS_ON_PAGE = 9 <NEW_LINE> REQUIRED_TOS_AGREEMENT = 10 <NEW_LINE> RESOURCE_NOT_DELETED = 11 <NEW_LINE> SINGLE_INSTANCE_PROPERTY_TEMPLATE = 12 <NEW_LINE> UNREACHABLE = 13 <NEW_LINE> <DEDENT> class DataValueListEntry(messages.Message): <NEW_LINE> <INDENT> key = messages.StringField(1) <NEW_LINE> value = messages.StringField(2) <NEW_LINE> <DEDENT> code = messages.EnumField('CodeValueValuesEnum', 1) <NEW_LINE> data = messages.MessageField('DataValueListEntry', 2, repeated=True) <NEW_LINE> message = messages.StringField(3) <NEW_LINE> <DEDENT> machineTypes = messages.MessageField('MachineType', 1, repeated=True) <NEW_LINE> warning = messages.MessageField('WarningValue', 2) | A MachineTypesScopedList object.
Messages:
WarningValue: [Output Only] An informational warning that appears when the
machine types list is empty.
Fields:
machineTypes: [Output Only] List of machine types contained in this scope.
warning: [Output Only] An informational warning that appears when the
machine types list is empty. | 6259906eaad79263cf430018 |
class IYafowilLayer(IDefaultBrowserLayer): <NEW_LINE> <INDENT> pass | YAFOWIL related browser layer.
| 6259906e92d797404e38978c |
class Redactor(DependencyProvider): <NEW_LINE> <INDENT> def worker_setup(self, worker_ctx): <NEW_LINE> <INDENT> entrypoint = worker_ctx.entrypoint <NEW_LINE> args = worker_ctx.args <NEW_LINE> kwargs = worker_ctx.kwargs <NEW_LINE> redacted.update(get_redacted_args(entrypoint, *args, **kwargs)) | Example DependencyProvider that redacts `sensitive_arguments`
on entrypoints during the worker lifecycle. | 6259906e4f88993c371f1151 |
class StrikeRow(BoxLayout): <NEW_LINE> <INDENT> _row_cache = {} <NEW_LINE> def __init__(self, strike, **kwargs): <NEW_LINE> <INDENT> super().__init__(orientation='horizontal', **kwargs) <NEW_LINE> self.strike = strike <NEW_LINE> self._sub_rows = {} <NEW_LINE> self._widgets_added = False <NEW_LINE> <DEDENT> def append_sub_row( self, record: dict, displayable: dict, bidasks=None, headers=(), table=None, **kwargs, ) -> None: <NEW_LINE> <INDENT> contract_type = record['contract_type'] <NEW_LINE> row = self._row_cache.get((self.strike, contract_type)) <NEW_LINE> if not row: <NEW_LINE> <INDENT> if contract_type == 'call': <NEW_LINE> <INDENT> record = dict(list(reversed(list(record.items())))) <NEW_LINE> <DEDENT> row = Row( record, bidasks=bidasks, headers=headers, table=table, no_cell=_no_display, **kwargs ) <NEW_LINE> self._row_cache[(self.strike, contract_type)] = row <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> row.update(record, displayable) <NEW_LINE> <DEDENT> row.widget = self <NEW_LINE> self._sub_rows[contract_type] = row <NEW_LINE> if self.is_populated() and not self._widgets_added: <NEW_LINE> <INDENT> self.add_widget(self._sub_rows['call']) <NEW_LINE> strike_cell = _strike_cell_cache.setdefault( self.strike, StrikeCell( key=self.strike, text=str(self.strike), size_hint=(1/10., 1), ) ) <NEW_LINE> self.add_widget(strike_cell) <NEW_LINE> self.add_widget(self._sub_rows['put']) <NEW_LINE> self._widgets_added = True <NEW_LINE> <DEDENT> <DEDENT> def is_populated(self): <NEW_LINE> <INDENT> return len(self._sub_rows) == 2 <NEW_LINE> <DEDENT> def has_widgets(self): <NEW_LINE> <INDENT> return self._widgets_added <NEW_LINE> <DEDENT> def update(self, record, displayable): <NEW_LINE> <INDENT> self._sub_rows[record['contract_type']].update( record, displayable) <NEW_LINE> <DEDENT> def get_field(self, key): <NEW_LINE> <INDENT> return int(self.strike) <NEW_LINE> <DEDENT> def rowsitems(self): <NEW_LINE> <INDENT> return self._sub_rows.items() | A 'row' composed of two ``Row``s sandwiching a
``StrikeCell`. | 6259906ebf627c535bcb2d2d |
class header_read_values_test(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.pri = header().default() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> del self.pri <NEW_LINE> <DEDENT> def test_read_values(self): <NEW_LINE> <INDENT> print(self.__class__.__name__) <NEW_LINE> pri = self.pri <NEW_LINE> values = pri.values() <NEW_LINE> self.assertIsInstance(values, list, msg='result of values() not a list') <NEW_LINE> self.assertEqual(len(values), len(pri), msg='values list is wrong length') | Is the list of values in the header read correctly? | 6259906e44b2445a339b7590 |
class PermanentView(View): <NEW_LINE> <INDENT> def __init__(self, uri, name, wrapper=None, session=None): <NEW_LINE> <INDENT> View.__init__(self, uri, wrapper=wrapper, session=session) <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s %r>' % (type(self).__name__, self.name) <NEW_LINE> <DEDENT> def _exec(self, options): <NEW_LINE> <INDENT> if 'keys' in options: <NEW_LINE> <INDENT> options = options.copy() <NEW_LINE> keys = {'keys': options.pop('keys')} <NEW_LINE> _, _, data = self.resource.post_json(body=keys, **self._encode_options(options)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _, _, data = self.resource.get_json(**self._encode_options(options)) <NEW_LINE> <DEDENT> return data | Representation of a permanent view on the server. | 6259906e4527f215b58eb5d1 |
class APITestCase(TestCase): <NEW_LINE> <INDENT> def login(self, username, password): <NEW_LINE> <INDENT> r = self.client.post(path=api_url + "/auth/login", data=json.dumps({'username': username, 'password': password}), content_type="application/json") <NEW_LINE> if 'x-auth-token' in r._headers: <NEW_LINE> <INDENT> self.x_auth_token = r._headers['x-auth-token'][1] <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.x_auth_token = None <NEW_LINE> return False | Subclass of Django's TestCase that includes login() | 6259906e9c8ee82313040db9 |
class DrawActorsAction(Action): <NEW_LINE> <INDENT> def __init__(self, output_service): <NEW_LINE> <INDENT> self.output_service = output_service <NEW_LINE> <DEDENT> def execute(self, cast): <NEW_LINE> <INDENT> self.output_service.clear_screen() <NEW_LINE> if cast["paddle"]: <NEW_LINE> <INDENT> self.output_service.draw_actors(cast["paddle"]) <NEW_LINE> <DEDENT> if cast["brick"]: <NEW_LINE> <INDENT> self.output_service.draw_actors(cast["brick"]) <NEW_LINE> <DEDENT> if cast["ball"]: <NEW_LINE> <INDENT> self.output_service.draw_actors(cast["ball"]) <NEW_LINE> <DEDENT> self.output_service.flush_buffer() | This class will handle the displaying of object on the screen.
| 6259906e7d43ff2487428043 |
@method_decorator(user_passes_test(is_departaments), name="dispatch") <NEW_LINE> class DepartamentTfgDetailView(DetailView): <NEW_LINE> <INDENT> model = Tfgs <NEW_LINE> teamplate_name = "tfgs/tfgs_detail" <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = super().get_queryset().filter( tutor1__userinfos__departaments=self.request.user.userinfos.departaments, draft=False ) <NEW_LINE> queryset = queryset.exclude(announcements=None) <NEW_LINE> return queryset <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context["students"] = Students.objects.filter(tfgs_id=context['tfgs'].id) <NEW_LINE> context["back_url"] = "departament_tfgs_list" <NEW_LINE> context["can_validate"] = True <NEW_LINE> context["validation_url_ok"] = "departament_tfgs_validation_ok" <NEW_LINE> context["validation_url_error"] = "departament_tfgs_validation_error" <NEW_LINE> return context <NEW_LINE> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.GET.get("format") == "pdf": <NEW_LINE> <INDENT> pdf = render_to_pdf("tfgs/tfgs_format_pdf.html", {"tfg": self.get_object()}) <NEW_LINE> return HttpResponse(pdf, content_type="application/pdf") <NEW_LINE> <DEDENT> return super().get(request, *args, **kwargs) | Controlador para mostrar un TFG en detalle.
Atributos:
model(model.Model): Modelo que se va a mostrar en la vista.
template_name(str): Nombre del template donde se va a renderizar la vista. | 6259906e66673b3332c31c60 |
class Flipud(Augmenter): <NEW_LINE> <INDENT> def __init__(self, p=0, name=None, deterministic=False, random_state=None): <NEW_LINE> <INDENT> super(Flipud, self).__init__(name=name, deterministic=deterministic, random_state=random_state) <NEW_LINE> if ia.is_single_number(p): <NEW_LINE> <INDENT> self.p = Binomial(p) <NEW_LINE> <DEDENT> elif isinstance(p, StochasticParameter): <NEW_LINE> <INDENT> self.p = p <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Expected p to be int or float or StochasticParameter, got %s." % (type(p),)) <NEW_LINE> <DEDENT> <DEDENT> def _augment_images(self, images, random_state, parents, hooks): <NEW_LINE> <INDENT> nb_images = len(images) <NEW_LINE> samples = self.p.draw_samples((nb_images,), random_state=random_state) <NEW_LINE> for i in sm.xrange(nb_images): <NEW_LINE> <INDENT> if samples[i] == 1: <NEW_LINE> <INDENT> images[i] = np.flipud(images[i]) <NEW_LINE> <DEDENT> <DEDENT> return images <NEW_LINE> <DEDENT> def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks): <NEW_LINE> <INDENT> nb_images = len(keypoints_on_images) <NEW_LINE> samples = self.p.draw_samples((nb_images,), random_state=random_state) <NEW_LINE> for i, keypoints_on_image in enumerate(keypoints_on_images): <NEW_LINE> <INDENT> if samples[i] == 1: <NEW_LINE> <INDENT> height = keypoints_on_image.shape[0] <NEW_LINE> for keypoint in keypoints_on_image.keypoints: <NEW_LINE> <INDENT> keypoint.y = (height - 1) - keypoint.y <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return keypoints_on_images <NEW_LINE> <DEDENT> def get_parameters(self): <NEW_LINE> <INDENT> return [self.p] | Flip/mirror input images vertically. | 6259906e2ae34c7f260ac94c |
class Plugin(EncoderPlugin): <NEW_LINE> <INDENT> def __init__(self, context): <NEW_LINE> <INDENT> super().__init__('HEX (shell)', "Thomas Engel", ["codecs"], context) <NEW_LINE> <DEDENT> def run(self, text): <NEW_LINE> <INDENT> if text: <NEW_LINE> <INDENT> import codecs <NEW_LINE> output = codecs.encode(text.encode('utf-8', errors='surrogateescape'), 'hex').decode('utf-8', errors='surrogateescape') <NEW_LINE> return "\\x" + "\\x".join([i+j for i, j in zip(output[::2], output[1::2])]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" | Encodes to hex shell code.
Example:
Input:
abcdefghijklmnopqrstuvwxyz
^°!"§$%&/()=?´`<>| ,.-;:_#+'*~
0123456789
Output:
\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e \
\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x0a\x5e \
\xc2\xb0\x21\x22\xc2\xa7\x24\x25\x26\x2f\x28\x29\x3d\x3f \
\xc2\xb4\x60\x3c\x3e\x7c\x20\x2c\x2e\x2d\x3b\x3a\x5f\x23 \
\x2b\x27\x2a\x7e\x0a\x30\x31\x32\x33\x34\x35\x36\x37\x38 \
\x39 | 6259906e56ac1b37e6303914 |
class RegistrationMenu: <NEW_LINE> <INDENT> def __init__(self, phone_number, session_id, user_response): <NEW_LINE> <INDENT> self.session_id = session_id <NEW_LINE> self.user = User.query.filter_by(phone_number=phone_number).first() <NEW_LINE> self.session = SessionLevel.query.filter_by(session_id=self.session_id).first() <NEW_LINE> self.user_response = user_response <NEW_LINE> self.phone_number = phone_number <NEW_LINE> <DEDENT> def get_number(self): <NEW_LINE> <INDENT> new_user = User(phone_number=self.phone_number) <NEW_LINE> db.session.add(new_user) <NEW_LINE> db.session.commit() <NEW_LINE> session = SessionLevel( session_id=self.session_id, phone_number=self.phone_number) <NEW_LINE> session.promote_level(21) <NEW_LINE> db.session.add(session) <NEW_LINE> db.session.commit() <NEW_LINE> menu_text = "CON Please enter your name" <NEW_LINE> return respond(menu_text) <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> if self.user_response: <NEW_LINE> <INDENT> self.user.name =self.user_response <NEW_LINE> self.session.promote_level(22) <NEW_LINE> db.session.add(self.session) <NEW_LINE> db.session.add(self.user) <NEW_LINE> menu_text = "CON Enter your city" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> menu_text = "CON Name not supposed to be empty. Please enter your name \n" <NEW_LINE> <DEDENT> return respond(menu_text) <NEW_LINE> <DEDENT> def get_city(self): <NEW_LINE> <INDENT> if self.user_response: <NEW_LINE> <INDENT> self.user.city = self.user_response <NEW_LINE> self.session.demote_level() <NEW_LINE> db.session.add(self.session) <NEW_LINE> db.session.add(self.user) <NEW_LINE> db.session.commit() <NEW_LINE> menu_text = "END You have been successfully registered. \n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> menu_text = "CON City not supposed to be empty. Please enter your city \n" <NEW_LINE> <DEDENT> return respond(menu_text) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def register_default(): <NEW_LINE> <INDENT> menu_text = "END Apologies something went wrong \n" <NEW_LINE> return respond(menu_text) | Serves registration callbacks | 6259906e67a9b606de5476d4 |
class SBSCommentParser(Parser): <NEW_LINE> <INDENT> def set_com_id(self): <NEW_LINE> <INDENT> self.com_id = self.comment.get("id") <NEW_LINE> <DEDENT> def set_com_type_and_depth(self): <NEW_LINE> <INDENT> com_class = self.comment.get("class") <NEW_LINE> self.node_attr['com_type'] = com_class[0] <NEW_LINE> self.node_attr['com_depth'] = next( int(word[6:]) for word in com_class if word.startswith("depth-")) <NEW_LINE> <DEDENT> def set_comment_and_time(self): <NEW_LINE> <INDENT> self.node_attr['com_content'] = [ item.text for item in self.comment.find( "div", {"class": "comment-content"}).find_all("p")] <NEW_LINE> time_stamp = self.comment.find( "div", {"class": "comment-metadata"}).find("time").get( "datetime") <NEW_LINE> self.node_attr['com_timestamp'] = self.parse_timestamp( time_stamp, "%Y-%m-%dT%H:%M:%S+00:00") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse_fun(comment): <NEW_LINE> <INDENT> return comment.find("cite").text.strip() <NEW_LINE> <DEDENT> def set_author_and_author_url(self): <NEW_LINE> <INDENT> com_author_and_url = self.comment.find( "div", {"class": "comment-author"}).find( "cite", {"class": "fn"}) <NEW_LINE> try: <NEW_LINE> <INDENT> com_author = com_author_and_url.find("a").text <NEW_LINE> self.node_attr['com_author_url'] = com_author_and_url.find( "a").get("href") <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> com_author = com_author_and_url.text <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> logging.debug("Could not resolve author_url for %s", com_author) <NEW_LINE> com_author = "unable to resolve" <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.node_attr['com_author_url'] = None <NEW_LINE> <DEDENT> <DEDENT> self.node_attr['com_author'] = CONVERT[com_author] if com_author in CONVERT else com_author <NEW_LINE> <DEDENT> def set_child_ids(self): <NEW_LINE> <INDENT> self.node_attr['com_children'] = [] | Comment-data for comments on SBS-blog | 6259906e1f037a2d8b9e549c |
class Step: <NEW_LINE> <INDENT> def __init__(self, stepId: int, title=None): <NEW_LINE> <INDENT> self.stepId = stepId <NEW_LINE> self.nexts = dict() <NEW_LINE> self.previouses = dict() <NEW_LINE> self.title = title if title else 'step '+str(stepId) <NEW_LINE> <DEDENT> def getNexts(self): <NEW_LINE> <INDENT> return list(self.nexts.values()) <NEW_LINE> <DEDENT> def getPreviouses(self): <NEW_LINE> <INDENT> return list(self.previouses.values()) <NEW_LINE> <DEDENT> def addNext(self, nextStep): <NEW_LINE> <INDENT> if nextStep.stepId not in self.nexts: <NEW_LINE> <INDENT> self.nexts[nextStep.stepId] = nextStep <NEW_LINE> <DEDENT> if self.stepId not in nextStep.previouses: <NEW_LINE> <INDENT> nextStep.previouses[self.stepId] = self <NEW_LINE> <DEDENT> <DEDENT> def isFirst(self): <NEW_LINE> <INDENT> return not self.previouses <NEW_LINE> <DEDENT> def isLast(self): <NEW_LINE> <INDENT> return not self.nexts | The Step class defines a step in a workflow.
It may be seen as a node in a graph with oriented edges: previous and next steps.
Since a workflow is an oriented graph, step may be defined as first (ie without previous step)
or last (ie wihtout next step) | 6259906e3539df3088ecdb00 |
class ConditionalWrapper(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, estimator, cols=None, na_values=None, col_name=None, drop=True): <NEW_LINE> <INDENT> self.estimator = estimator <NEW_LINE> self.cols = cols <NEW_LINE> self.na_values = na_values <NEW_LINE> self.col_name = col_name <NEW_LINE> self.drop = drop <NEW_LINE> <DEDENT> def find_valid_index(self, X: pd.DataFrame): <NEW_LINE> <INDENT> if self.na_values is None: <NEW_LINE> <INDENT> valid_index = pd.notnull(X).all(axis=1) <NEW_LINE> <DEDENT> elif isinstance(self.na_values, (list, tuple)): <NEW_LINE> <INDENT> from pandas.core.algorithms import isin <NEW_LINE> valid_index = X.apply(lambda x: ~isin(x, self.na_values)).all(axis=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> valid_index = X.apply(lambda x: x != self.na_values).all(axis=1) <NEW_LINE> <DEDENT> return valid_index <NEW_LINE> <DEDENT> def fit(self, X, y=None, **fit_params): <NEW_LINE> <INDENT> if self.cols is None: <NEW_LINE> <INDENT> self.cols = X.columns.tolist() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cols = [c for c in self.cols if c in X.columns] <NEW_LINE> <DEDENT> valid_index = self.find_valid_index(X[self.cols]) <NEW_LINE> y = y[valid_index] if y is not None else y <NEW_LINE> self.estimator.fit(X.loc[valid_index, self.cols], y) <NEW_LINE> return self <NEW_LINE> <DEDENT> def transform(self, X, y=None): <NEW_LINE> <INDENT> x = X.copy() <NEW_LINE> valid_index = self.find_valid_index(X[self.cols]) <NEW_LINE> if hasattr(self.estimator, 'transform'): <NEW_LINE> <INDENT> res = self.estimator.transform(x.loc[valid_index, self.cols]) <NEW_LINE> <DEDENT> elif hasattr(self.estimator, 'fit_transform'): <NEW_LINE> <INDENT> res = self.estimator.fit_transform(x.loc[valid_index, self.cols]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError('Estimator does not have transform or fit_transform method.') <NEW_LINE> <DEDENT> if hasattr(self.estimator, 'n_components'): <NEW_LINE> <INDENT> col_name = [self.col_name + '_' + str(i + 1) for i in range(self.estimator.n_components)] <NEW_LINE> for c in col_name: <NEW_LINE> <INDENT> x[c] = np.nan <NEW_LINE> <DEDENT> x.loc[valid_index, col_name] = res <NEW_LINE> return x.drop(self.cols, axis=1) if self.drop else x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x.loc[valid_index, self.cols] = res <NEW_LINE> return x <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Conditional<' + re.sub(r'\(.*\)', '(cols={})'.format(repr(self.cols)), repr(self.estimator), flags=re.DOTALL) + '>' <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> return getattr(self.estimator, item) | A conditional wrapper that makes a Scikit-Learn transformer only works on part of the data
where X is not missing. | 6259906ee76e3b2f99fda265 |
class StochasticDistributor(AbstractBaseDistributor): <NEW_LINE> <INDENT> def assign_group(self, subjects): <NEW_LINE> <INDENT> pass | Uses law of large numbers principle and random assignment for the treatment groups.
The assignment method for this subclass is stochastic and generally should be used when the law
of large numbers is observable for each group, namely, when there is a large quantity of experimentation
subjects on each group. | 6259906e4a966d76dd5f074d |
class Style: <NEW_LINE> <INDENT> numberRex = re.compile('(\d+)(.*)') <NEW_LINE> def __init__(self, name, family, defaults=None, outlineLevel=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.family = family <NEW_LINE> self.displayName = name <NEW_LINE> self.styleClass = None <NEW_LINE> self.fontSize = None <NEW_LINE> self.fontSizeUnit = None <NEW_LINE> self.outlineLevel = outlineLevel <NEW_LINE> self.styleNameNs = (family == 'table-cell') and 'table' or 'text' <NEW_LINE> self.defaults = defaults <NEW_LINE> self.inheritWorks = family != 'table-cell' <NEW_LINE> <DEDENT> def setFontSize(self, fontSize): <NEW_LINE> <INDENT> rexRes = self.numberRex.search(fontSize) <NEW_LINE> self.fontSize = int(rexRes.group(1)) <NEW_LINE> self.fontSizeUnit = rexRes.group(2) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> res = '<Style %s|family %s' % (self.name, self.family) <NEW_LINE> if self.displayName != None: res += '|displayName "%s"'%self.displayName <NEW_LINE> if self.styleClass != None: res += '|class %s' % self.styleClass <NEW_LINE> if self.fontSize != None: <NEW_LINE> <INDENT> res += '|fontSize %d%s' % (self.fontSize, self.fontSizeUnit) <NEW_LINE> <DEDENT> if self.outlineLevel != None: res += '|level %s' % self.outlineLevel <NEW_LINE> return ('%s>' % res).encode('utf-8') <NEW_LINE> <DEDENT> def getOdfAttributes(self, attrs=None, withName=True, withDefaults=False, exclude=None): <NEW_LINE> <INDENT> res = '' <NEW_LINE> if withName: <NEW_LINE> <INDENT> res = ' %s:style-name="%s"' % (self.styleNameNs, self.name) <NEW_LINE> <DEDENT> if self.outlineLevel != None: <NEW_LINE> <INDENT> res += ' text:outline-level="%d"' % self.outlineLevel <NEW_LINE> <DEDENT> if attrs and ('colspan' in attrs): <NEW_LINE> <INDENT> res += ' table:number-columns-spanned="%s"' % attrs['colspan'] <NEW_LINE> <DEDENT> if attrs and ('rowspan' in attrs): <NEW_LINE> <INDENT> res += ' table:number-rows-spanned="%s"' % attrs['rowspan'] <NEW_LINE> <DEDENT> if withDefaults and self.defaults: <NEW_LINE> <INDENT> for name, value in self.defaults.items(): <NEW_LINE> <INDENT> if exclude and (name in exclude): continue <NEW_LINE> res += ' %s="%s"' % (name, value) <NEW_LINE> <DEDENT> <DEDENT> return res <NEW_LINE> <DEDENT> def getOdfParentAttributes(self, childAttrs=None): <NEW_LINE> <INDENT> if self.inheritWorks: <NEW_LINE> <INDENT> return ' style:parent-style-name="%s"' % self.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.getOdfAttributes(withName=False, withDefaults=True, exclude=childAttrs) | Represents an ODF style. Either parsed from an ODF file or used for
dumping a style into an ODF file. | 6259906e167d2b6e312b81c0 |
class PandasFeatureUnion(FeatureUnion): <NEW_LINE> <INDENT> def merge_dataframes_by_column(self, Xs) -> pd.DataFrame: <NEW_LINE> <INDENT> return pd.concat(Xs, axis="columns", copy=False) <NEW_LINE> <DEDENT> def transform(self, X: pd.DataFrame) -> pd.DataFrame: <NEW_LINE> <INDENT> Xs = Parallel(n_jobs=self.n_jobs)( delayed(_transform_one)(trans, X, None, weight) for name, trans, weight in self._iter()) <NEW_LINE> if not Xs: <NEW_LINE> <INDENT> return np.zeros((X.shape[0], 0)) <NEW_LINE> <DEDENT> if any(sparse.issparse(f) for f in Xs): <NEW_LINE> <INDENT> raise SparseNotAllowedError( "sparse results are not allowed, check transformers") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not all(isinstance(x, pd.DataFrame) for x in Xs): <NEW_LINE> <INDENT> raise TypeError( "one of the results is not a DataFrame, check your transformers" ) <NEW_LINE> <DEDENT> Xs = self.merge_dataframes_by_column(Xs) <NEW_LINE> <DEDENT> return Xs <NEW_LINE> <DEDENT> def fit_transform(self, X: pd.DataFrame, y=None, **fit_params) -> pd.DataFrame: <NEW_LINE> <INDENT> self._validate_transformers() <NEW_LINE> result = Parallel(n_jobs=self.n_jobs)( delayed(_fit_transform_one)(trans, X, y, weight, **fit_params) for name, trans, weight in self._iter()) <NEW_LINE> if not result: <NEW_LINE> <INDENT> return np.zeros((X.shape[0], 0)) <NEW_LINE> <DEDENT> Xs, transformers = zip(*result) <NEW_LINE> self._update_transformer_list(transformers) <NEW_LINE> if any(sparse.issparse(f) for f in Xs): <NEW_LINE> <INDENT> raise SparseNotAllowedError( "sparse results are not allowed, check transformers") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not all(isinstance(x, pd.DataFrame) for x in Xs): <NEW_LINE> <INDENT> raise TypeError( "one of the results is not a DataFrame, check your transformers" ) <NEW_LINE> <DEDENT> Xs = self.merge_dataframes_by_column(Xs) <NEW_LINE> <DEDENT> return Xs | Scikit-learn feature union with support for pandas DataFrames. | 6259906e460517430c432c88 |
@dataclass(frozen=True) <NEW_LINE> class FeatureMatrix: <NEW_LINE> <INDENT> names: List[str] <NEW_LINE> scales: List[float] <NEW_LINE> selections: numpy.ndarray <NEW_LINE> compute_in_2d: numpy.ndarray | Provides OpFeatureSelection compatible interface
Attributes:
names: List of feature ids
scales: List of feature scales
selections: Boolean matrix where rows are feature names and scales are columuns
True value means feature is enabled
compute_in_2d: 1d array for each scale reflecting if feature should be computed in 2D | 6259906ecb5e8a47e493cdb4 |
class Command(BaseCommand): <NEW_LINE> <INDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> collections = BiologicalCollectionRecord.objects.all() <NEW_LINE> for record in collections: <NEW_LINE> <INDENT> print('Update record : %s' % record.original_species_name) <NEW_LINE> update_fish_collection_record(record) | Update Fish Collection Record.
| 6259906e1f5feb6acb164455 |
class Slew(Filter): <NEW_LINE> <INDENT> __documentation_section__ = 'Filter UGens' <NEW_LINE> __slots__ = () <NEW_LINE> _ordered_input_names = ( 'source', 'up', 'dn', ) <NEW_LINE> _valid_calculation_rates = None <NEW_LINE> def __init__( self, calculation_rate=None, dn=1, source=None, up=1, ): <NEW_LINE> <INDENT> Filter.__init__( self, calculation_rate=calculation_rate, dn=dn, source=source, up=up, ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def ar( cls, dn=1, source=None, up=1, ): <NEW_LINE> <INDENT> from supriya.tools import synthdeftools <NEW_LINE> calculation_rate = synthdeftools.CalculationRate.AUDIO <NEW_LINE> ugen = cls._new_expanded( calculation_rate=calculation_rate, dn=dn, source=source, up=up, ) <NEW_LINE> return ugen <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def kr( cls, dn=1, source=None, up=1, ): <NEW_LINE> <INDENT> from supriya.tools import synthdeftools <NEW_LINE> calculation_rate = synthdeftools.CalculationRate.CONTROL <NEW_LINE> ugen = cls._new_expanded( calculation_rate=calculation_rate, dn=dn, source=source, up=up, ) <NEW_LINE> return ugen <NEW_LINE> <DEDENT> @property <NEW_LINE> def dn(self): <NEW_LINE> <INDENT> index = self._ordered_input_names.index('dn') <NEW_LINE> return self._inputs[index] <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> index = self._ordered_input_names.index('source') <NEW_LINE> return self._inputs[index] <NEW_LINE> <DEDENT> @property <NEW_LINE> def up(self): <NEW_LINE> <INDENT> index = self._ordered_input_names.index('up') <NEW_LINE> return self._inputs[index] | A slew rate limiter.
::
>>> source = ugentools.In.ar(bus=0)
>>> slew = ugentools.Slew.ar(
... dn=1,
... source=source,
... up=1,
... )
>>> slew
Slew.ar() | 6259906e3346ee7daa338290 |
class EndPointDetailSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> time_left_before_expiry = serializers.SerializerMethodField() <NEW_LINE> time_after_hitting_url = serializers.SerializerMethodField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = endpoint_models.EndPointDetail <NEW_LINE> fields = ['raw_body', 'headers', 'query_params', 'time_after_hitting_url', 'time_left_before_expiry'] <NEW_LINE> read_only_fields = ['headers', 'query_params', ] <NEW_LINE> <DEDENT> def get_time_left_before_expiry(self, instance): <NEW_LINE> <INDENT> expiry_seconds = endpoint_constants.URL_EXPIRY_TIME_IN_SECONDS - (timezone.now() - instance.url.created_at).total_seconds() <NEW_LINE> return int(expiry_seconds/60) <NEW_LINE> <DEDENT> def get_time_after_hitting_url(self, instance): <NEW_LINE> <INDENT> return int((timezone.now() - instance.created_at).total_seconds()) <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = endpoint_models.Url.objects.get(url=self.context.get('url')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValidationError(detail={'error': 'URL doesnot exist or is expired.'}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> validated_data['url'] = url <NEW_LINE> obj = super().create(validated_data) <NEW_LINE> obj.headers = self.context.get('headers') <NEW_LINE> obj.query_params = self.context.get('query_params') <NEW_LINE> obj.save() <NEW_LINE> url.no_of_hits += 1 <NEW_LINE> url.save(update_fields=['no_of_hits']) <NEW_LINE> return obj | Serializer for EndPointDetail Model | 6259906eb7558d5895464b64 |
class PersistentPineapple(object): <NEW_LINE> <INDENT> settings = {} <NEW_LINE> def __init__(self, path, woc=True, lofc=True): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.woc = woc <NEW_LINE> self.lofc = lofc <NEW_LINE> self._settings_copy = None <NEW_LINE> self._pre_context_woc = None <NEW_LINE> if path and path not in self.settings: <NEW_LINE> <INDENT> self.settings[path] = {} <NEW_LINE> self._load() <NEW_LINE> self.mtime = os.path.getmtime(self.path) <NEW_LINE> <DEDENT> elif path and path in self.settings: <NEW_LINE> <INDENT> self.mtime = os.path.getmtime(self.path) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> <DEDENT> def _lofc(self): <NEW_LINE> <INDENT> if not self.lofc: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mtime = os.path.getmtime(self.path) <NEW_LINE> if self.mtime < mtime: <NEW_LINE> <INDENT> self.mtime = mtime <NEW_LINE> self._load() <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> self._lofc() <NEW_LINE> return self.settings[self.path][key] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.settings[self.path][key] = value <NEW_LINE> if self.woc: <NEW_LINE> <INDENT> self.save() <NEW_LINE> <DEDENT> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del(self.settings[self.path][key]) <NEW_LINE> if self.woc: <NEW_LINE> <INDENT> self.save() <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.settings[self.path]) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._pre_context_woc = self.woc <NEW_LINE> self._settings_copy = copy(self.settings[self.path]) <NEW_LINE> self.woc = False <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.settings[self.path] = copy(self._settings_copy) <NEW_LINE> self.woc = self._pre_context_woc <NEW_LINE> self._settings_copy = None <NEW_LINE> self._pre_context_woc = None <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> self._lofc() <NEW_LINE> return self.settings[self.path][key] <NEW_LINE> <DEDENT> def set(self, key, value): <NEW_LINE> <INDENT> self.settings[self.path][key] = value <NEW_LINE> if self.woc: <NEW_LINE> <INDENT> self.save() <NEW_LINE> <DEDENT> <DEDENT> def _load(self): <NEW_LINE> <INDENT> self.settings[self.path].clear() <NEW_LINE> self.settings[self.path].update(JSON().load(path=self.path)) <NEW_LINE> <DEDENT> def save(self, path=None): <NEW_LINE> <INDENT> if path is None: <NEW_LINE> <INDENT> path = self.path <NEW_LINE> <DEDENT> JSON().store(self.settings[self.path], path) <NEW_LINE> <DEDENT> def reload(self): <NEW_LINE> <INDENT> self._load() | An interface to the project settings. | 6259906e435de62698e9d66a |
class ListCreateAPIMixedPermission(permissions.BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> if request.user.is_authenticated: <NEW_LINE> <INDENT> if request.user.is_staff or is_user_in_groups(request.user, [READ_ONLY_API_GROUP_NAME]): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> elif request.method == 'POST': <NEW_LINE> <INDENT> return request.user.is_authenticated and request.user.is_staff <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Permission class for ListCreate views that want to allow read-only access to some groups and read-write
to others.
GET users must be either (a) staff or (b) in the Limited API group.
POST users must be staff. | 6259906e92d797404e38978d |
class XincaAuthorizationError(XincaError): <NEW_LINE> <INDENT> pass | Credentials have inadequate authorization to perform operation | 6259906ed268445f2663a78f |
class TestViews(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = Client() <NEW_LINE> self.other_client = Client() <NEW_LINE> self.user = get_user_model().objects.create_user( username='test_user', email='[email protected]', password='top_secret' ) <NEW_LINE> self.other_user = get_user_model().objects.create_user( username='other_test_user', email='[email protected]', password='top_secret' ) <NEW_LINE> self.client.login(username='test_user', password='top_secret') <NEW_LINE> self.other_client.login( username='other_test_user', password='top_secret') <NEW_LINE> self.feed = Feed.objects.create( user=self.user, post='A not so long text', likes=0, comments=0) <NEW_LINE> <DEDENT> def test_feed_view(self): <NEW_LINE> <INDENT> request = self.client.get(reverse('feed', args=[self.feed.id])) <NEW_LINE> self.assertEqual(request.status_code, 200) | Includes tests for all the functionality
associated with Views | 6259906ed486a94d0ba2d824 |
class Feature(namedtuple('Feature', 'ls rs lo ro w t n n_ w_')): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '(%s)' % ', '.join(['{}={}'.format(k,v) for k,v in self._asdict().items()]) | Usage
-----
>>> feature = Feature(True, False, False, False, '아이오아이', 'Noun', 5, 5, '아이오아이')
>>> print(feature)
$ (ls=True, rs=False, lo=False, ro=False, w=아이오아이, t=Noun, n=5, n_=5, w_=아이오아이) | 6259906eac7a0e7691f73d4d |
class Button(tk.Button): <NEW_LINE> <INDENT> def __init__(self, master, image, **kwargs): <NEW_LINE> <INDENT> super().__init__(master, **kwargs) <NEW_LINE> self.image = image <NEW_LINE> self['image'] = self.image <NEW_LINE> self['relief'] = tk.FLAT <NEW_LINE> self['overrelief'] = tk.RIDGE | Ribbon Button | 6259906e44b2445a339b7591 |
class CrawlShard(db.Model): <NEW_LINE> <INDENT> crawl = db.Reference(Crawl) <NEW_LINE> feed = db.Reference(Feed) <NEW_LINE> url = db.TextProperty() <NEW_LINE> is_done = db.BooleanProperty(default=False) <NEW_LINE> started = db.DateTimeProperty() <NEW_LINE> finished = db.DateTimeProperty() <NEW_LINE> error = db.TextProperty() <NEW_LINE> parse_errors = db.ListProperty(db.Text) | Single atom of crawl work, which is a URL. | 6259906e9c8ee82313040dba |
class MobBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, c, wide=None, kernel=3): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> wide = 6 * c if wide is None else wide <NEW_LINE> padding = int(math.floor(kernel/2)) <NEW_LINE> self.convs = nn.Sequential( nn.Conv2d(c, wide, kernel_size=1), nn.ReLU6(), nn.Conv2d(wide, wide, kernel_size=kernel, padding=padding, groups=wide), nn.ReLU6(), nn.Conv2d(wide, c, kernel_size=1), nn.BatchNorm2d(c), nn.ReLU6() ) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> return self.convs(x) + x | Inverted residual block (as in mobilenetv2) | 6259906efff4ab517ebcf07f |
class Sequential(Module): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> super(Sequential, self).__init__() <NEW_LINE> if len(args) == 1 and isinstance(args[0], OrderedDict): <NEW_LINE> <INDENT> for key, module in args[0].items(): <NEW_LINE> <INDENT> self.add_module(key, module) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for idx, module in enumerate(args): <NEW_LINE> <INDENT> self.add_module(str(idx), module) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> if not (-len(self) <= idx < len(self)): <NEW_LINE> <INDENT> raise IndexError('index {} is out of range'.format(idx)) <NEW_LINE> <DEDENT> if idx < 0: <NEW_LINE> <INDENT> idx += len(self) <NEW_LINE> <DEDENT> it = iter(self._modules.values()) <NEW_LINE> for i in range(idx): <NEW_LINE> <INDENT> next(it) <NEW_LINE> <DEDENT> return next(it) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._modules) <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> for module in self._modules.values(): <NEW_LINE> <INDENT> input = module(input) <NEW_LINE> <DEDENT> return input | 一个顺序的容器.
模块将按照它们在构造函数中传递的顺序添加到它. 或者, 也可以传入模块的有序字典.
为了更容易理解, 列举小例来说明 ::
# 使用 Sequential 的例子
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
# 与 OrderedDict 一起使用 Sequential 的例子
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1,20,5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20,64,5)),
('relu2', nn.ReLU())
])) | 6259906e71ff763f4b5e900c |
class Branch(BlobVisualData): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.newStreamSeqNum = 0 <NEW_LINE> self.newPredictionSeqNum = 0 <NEW_LINE> self.newPC = 0 <NEW_LINE> self.reason = "NoBranch" <NEW_LINE> self.id = Id() <NEW_LINE> <DEDENT> def from_string(self, string): <NEW_LINE> <INDENT> m = re.match('^(\w+);(\d+)\.(\d+);([0-9a-fA-Fx]+);(.*)$', string) <NEW_LINE> if m is not None: <NEW_LINE> <INDENT> self.reason, newStreamSeqNum, newPredictionSeqNum, newPC, id = m.groups() <NEW_LINE> self.newStreamSeqNum = int(newStreamSeqNum) <NEW_LINE> self.newPredictionSeqNum = int(newPredictionSeqNum) <NEW_LINE> self.newPC = int(newPC, 0) <NEW_LINE> self.id = special_view_decoder(Id)(id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Bad Branch data:", string) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def to_striped_block(self, select): <NEW_LINE> <INDENT> return [colours.number_to_colour(self.newStreamSeqNum), colours.number_to_colour(self.newPredictionSeqNum), colours.number_to_colour(self.newPC)] | Branch data new stream and prediction sequence numbers, a branch
reason and a new PC | 6259906e7c178a314d78e81e |
class TestRequestsConnectorCookie(unittest.TestCase): <NEW_LINE> <INDENT> pass | Test RequestConnector's cookie settings. | 6259906eaad79263cf43001b |
class Authorization(object): <NEW_LINE> <INDENT> def __init__(self, domain, username, password, request_id_prefix = ''): <NEW_LINE> <INDENT> self.domain = domain <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.proto = 'https://' <NEW_LINE> self.verify = True <NEW_LINE> self._request_id_prefix = request_id_prefix <NEW_LINE> self.basic = HTTPBasicAuth(self.username, self.password) <NEW_LINE> <DEDENT> def live_dangerously(self): <NEW_LINE> <INDENT> import requests <NEW_LINE> from requests.packages.urllib3.exceptions import InsecureRequestWarning <NEW_LINE> requests.packages.urllib3.disable_warnings(InsecureRequestWarning) <NEW_LINE> self.verify = False <NEW_LINE> <DEDENT> def request_id_prefix(self): <NEW_LINE> <INDENT> return self._request_id_prefix | Manages basic authorization for accessing the socrata API.
This is passed into the `Socrata` object once, which is the entry
point for all operations.
auth = Authorization(
"data.seattle.gov",
os.environ['SOCRATA_USERNAME'],
os.environ['SOCRATA_PASSWORD']
)
publishing = Socrata(auth) | 6259906ee76e3b2f99fda267 |
class RequestResetEvent(BasicAuditEvent): <NEW_LINE> <INDENT> implements(IAuditEvent) <NEW_LINE> def __init__(self, context, id, d, userInfo, siteInfo, instanceDatum): <NEW_LINE> <INDENT> super(RequestResetEvent, self).__init__(context, id, REQUEST, d, userInfo, userInfo, siteInfo, None, instanceDatum, None, SUBSYSTEM) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> retval = u'%s (%s) requested a password reset on %s (%s). ' u'Used the address <%s>.' % (self.userInfo.name, self.userInfo.id, self.siteInfo.name, self.siteInfo.id, self.instanceDatum) <NEW_LINE> return retval <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> retval = unicode(self).encode('ascii', 'ignore') <NEW_LINE> return retval <NEW_LINE> <DEDENT> @property <NEW_LINE> def xhtml(self): <NEW_LINE> <INDENT> cssClass = u'audit-event gs-profile-password-%s' % self.code <NEW_LINE> retval = u'<span class="%s">Requested password reset ' u'using <code class="email">%s</code>.</span>' % (cssClass, self.instanceDatum) <NEW_LINE> retval = u'%s (%s)' % (retval, munge_date(self.context, self.date)) <NEW_LINE> return retval | An audit-trail event representing a person requesting a
password reset. | 6259906e8a43f66fc4bf39f9 |
class HacsMigration(HacsBase): <NEW_LINE> <INDENT> old = None <NEW_LINE> async def validate(self): <NEW_LINE> <INDENT> self.old = await self.storage.get() <NEW_LINE> if not self.old: <NEW_LINE> <INDENT> await self.update_repositories() <NEW_LINE> <DEDENT> elif "schema" not in self.old["hacs"]: <NEW_LINE> <INDENT> source = "{}/.storage/hacs".format(self.config_dir) <NEW_LINE> destination = "{}.none".format(source) <NEW_LINE> _LOGGER.info("Backing up current file to '%s'", destination) <NEW_LINE> copy2(source, destination) <NEW_LINE> await self.from_none_to_1() <NEW_LINE> await self.update_repositories() <NEW_LINE> <DEDENT> elif self.old["hacs"]["schema"] == "1": <NEW_LINE> <INDENT> source = "{}/.storage/hacs".format(self.config_dir) <NEW_LINE> destination = "{}.1".format(source) <NEW_LINE> _LOGGER.info("Backing up current file to '%s'", destination) <NEW_LINE> copy2(source, destination) <NEW_LINE> await self.from_1_to_2() <NEW_LINE> <DEDENT> elif self.old["hacs"].get("schema") == STORAGE_VERSION: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self.update_repositories() <NEW_LINE> <DEDENT> <DEDENT> async def from_none_to_1(self): <NEW_LINE> <INDENT> _LOGGER.info("Starting migration of HACS data from None to 1.") <NEW_LINE> for item in self.old["elements"]: <NEW_LINE> <INDENT> repodata = self.old["elements"][item] <NEW_LINE> if repodata.get("isinstalled"): <NEW_LINE> <INDENT> _LOGGER.info("Migrating %s", repodata["repo"]) <NEW_LINE> repository, setup_result = await self.register_new_repository( repodata["element_type"], repodata["repo"] ) <NEW_LINE> repository.version_installed = repodata["installed_version"] <NEW_LINE> repository.installed = True <NEW_LINE> self.repositories[repository.repository_id] = repository <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> async def from_1_to_2(self): <NEW_LINE> <INDENT> _LOGGER.info("Starting migration of HACS data from 1 to 2.") <NEW_LINE> for repository in self.repositories: <NEW_LINE> <INDENT> repository = self.repositories[repository] <NEW_LINE> repository.show_beta = False <NEW_LINE> await repository.set_repository_releases() <NEW_LINE> self.repositories[repository.repository_id] = repository <NEW_LINE> <DEDENT> self.data["hacs"]["schema"] = "2" <NEW_LINE> _LOGGER.info("Migration of HACS data from 1 to 2 is complete.") | HACS data migration handler. | 6259906e3346ee7daa338291 |
class FTPRequest(Packet): <NEW_LINE> <INDENT> name = "ftp" <NEW_LINE> fields_desc = [FTPReqField("command", "", "H"), StrField("argument", "", "H")] | class for dissecting the ftp requests
@attention: it inherets Packet class from Scapy library | 6259906e21bff66bcd7244cd |
class ApproveRevisionInLocaleEvent(_RevisionConstructor, _LocaleAndProductFilter, Event): <NEW_LINE> <INDENT> event_type = 'approved wiki in locale' | Event fed to a union when any revision in a certain locale is approved
Not intended to be fired individually | 6259906e7047854f46340c1d |
class House: <NEW_LINE> <INDENT> def __init__(self, house_type, area): <NEW_LINE> <INDENT> self.house_type = house_type <NEW_LINE> self.area = area <NEW_LINE> self.free_area = area <NEW_LINE> self.list_item = [] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "户型:%s, 面积:%.2f, 剩余面积:%.2f, 家具:%s" %( self.house_type, self.area, self.free_area, self.list_item ) <NEW_LINE> <DEDENT> def add_item(self, item): <NEW_LINE> <INDENT> if item.area > self.area: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.free_area -= item.area <NEW_LINE> self.list_item.append(item.name) | 定义一个房子类 | 6259906edd821e528d6da5b4 |
class TestDistroArchSeriesWebservice(TestCaseWithFactory): <NEW_LINE> <INDENT> layer = LaunchpadFunctionalLayer <NEW_LINE> def _makeDistroArchSeries(self): <NEW_LINE> <INDENT> distro = self.factory.makeDistribution() <NEW_LINE> distroseries = self.factory.makeDistroSeries( distribution=distro) <NEW_LINE> self.factory.makeDistroArchSeries( distroseries=distroseries) <NEW_LINE> return distroseries <NEW_LINE> <DEDENT> def test_distroseries_architectures_anonymous(self): <NEW_LINE> <INDENT> distroseries = self._makeDistroArchSeries() <NEW_LINE> endInteraction() <NEW_LINE> launchpad = launchpadlib_for('test', person=None, version='devel') <NEW_LINE> ws_distroseries = ws_object(launchpad, distroseries) <NEW_LINE> self.assertEqual(1, len(ws_distroseries.architectures.entries)) <NEW_LINE> <DEDENT> def test_distroseries_architectures_authenticated(self): <NEW_LINE> <INDENT> distroseries = self._makeDistroArchSeries() <NEW_LINE> accessor = self.factory.makePerson() <NEW_LINE> launchpad = launchpadlib_for('test', accessor.name, version='devel') <NEW_LINE> ws_distroseries = ws_object(launchpad, distroseries) <NEW_LINE> self.assertEqual(1, len(ws_distroseries.architectures.entries)) <NEW_LINE> <DEDENT> def test_setChroot_removeChroot_random_user(self): <NEW_LINE> <INDENT> das = self.factory.makeDistroArchSeries() <NEW_LINE> user = self.factory.makePerson() <NEW_LINE> webservice = launchpadlib_for("testing", user, version='devel') <NEW_LINE> ws_das = ws_object(webservice, das) <NEW_LINE> self.assertRaises( Unauthorized, ws_das.setChroot, data='xyz', sha1sum='0') <NEW_LINE> self.assertRaises(Unauthorized, ws_das.removeChroot) <NEW_LINE> <DEDENT> def test_setChroot_wrong_sha1sum(self): <NEW_LINE> <INDENT> das = self.factory.makeDistroArchSeries() <NEW_LINE> user = das.distroseries.distribution.main_archive.owner <NEW_LINE> webservice = launchpadlib_for("testing", user) <NEW_LINE> ws_das = ws_object(webservice, das) <NEW_LINE> self.assertRaises( BadRequest, ws_das.setChroot, data='zyx', sha1sum='x') <NEW_LINE> <DEDENT> def test_setChroot_removeChroot(self): <NEW_LINE> <INDENT> das = self.factory.makeDistroArchSeries() <NEW_LINE> user = das.distroseries.distribution.main_archive.owner <NEW_LINE> expected_file = 'chroot-%s-%s-%s.tar.bz2' % ( das.distroseries.distribution.name, das.distroseries.name, das.architecturetag) <NEW_LINE> webservice = launchpadlib_for("testing", user) <NEW_LINE> ws_das = ws_object(webservice, das) <NEW_LINE> sha1 = hashlib.sha1('abcxyz').hexdigest() <NEW_LINE> ws_das.setChroot(data='abcxyz', sha1sum=sha1) <NEW_LINE> self.assertTrue(ws_das.chroot_url.endswith(expected_file)) <NEW_LINE> ws_das.removeChroot() <NEW_LINE> self.assertIsNone(ws_das.chroot_url) | Unit Tests for 'DistroArchSeries' Webservice.
| 6259906e2ae34c7f260ac94f |
class NotificationForm(forms.ModelForm): <NEW_LINE> <INDENT> author = forms.ModelChoiceField( label=_("Autor"), queryset=User.objects.all().order_by('username'), widget=forms.Select(), help_text=u'De parte de') <NEW_LINE> destinario = forms.ModelChoiceField( label=_("Destinatario"), queryset=User.objects.all().order_by('username'), help_text=u'Destinado al usuario (Si la opcion "Todos los usuarios" esta activa, esta opción será ignorada)') <NEW_LINE> titulo = forms.CharField( label=_("Titulo"), max_length=255, help_text=u'Titulo de la notificacion') <NEW_LINE> descripcion=forms.CharField( label=_("Descripcion"), widget = forms.Textarea, required=False, help_text=u'Descripcion de la notificación') <NEW_LINE> todos= forms.BooleanField( label=_("Totodos los usuarios"), help_text=u'Seleccionar esta opcion para enviar a todos los usuarios activos del sistema.' ) <NEW_LINE> es_instancea=False <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model= Notification <NEW_LINE> fields = ('author','destinario','level', 'titulo','descripcion','unread','public','timestamp') <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(NotificationForm, self).__init__(*args, **kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> instance=kwargs['instance'] <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> instance=False <NEW_LINE> <DEDENT> if instance: <NEW_LINE> <INDENT> self.es_instancea=True <NEW_LINE> self.fields['descripcion'].initial=instance.description <NEW_LINE> self.fields['titulo'].initial=instance.verb <NEW_LINE> self.fields['author'].initial=instance.actor <NEW_LINE> self.fields['destinario'].initial=instance.recipient <NEW_LINE> self.fields['todos'].widget = forms.HiddenInput() <NEW_LINE> <DEDENT> <DEDENT> def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(NotificationForm, self).clean() <NEW_LINE> if not self.es_instancea: <NEW_LINE> <INDENT> todos = cleaned_data.get("todos") <NEW_LINE> destinario = cleaned_data.get("destinario") <NEW_LINE> if todos: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.errors['destinario'] <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return cleaned_data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if destinario: <NEW_LINE> <INDENT> del self._errors['todos'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> del self._errors['todos'] <NEW_LINE> <DEDENT> return cleaned_data | Formuilario del admin para las notificaciones
Se modifico el __init__ para permitir crear notificaciones para todos los usuarios | 6259906ee5267d203ee6cff0 |
class CreatePhotoView(AddOrEditMixin, CreateView): <NEW_LINE> <INDENT> model = Photo <NEW_LINE> fields = ['albums', 'img_file', 'title', 'description', 'published'] <NEW_LINE> own_queryset_name = 'photos' <NEW_LINE> rel_queryset_name = 'albums' | Create a new Photo to the database. | 6259906e4428ac0f6e659d99 |
class CLIPositionalParameter(CLIParseTreeNode): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> self._quoted = False <NEW_LINE> super(CLIPositionalParameter, self).__init__() <NEW_LINE> logging.debug('CLIPositionalParameter created: value=' + str(value)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @property <NEW_LINE> def quoted(self): <NEW_LINE> <INDENT> return self._quoted <NEW_LINE> <DEDENT> @quoted.setter <NEW_LINE> def quoted(self, quoted): <NEW_LINE> <INDENT> self._quoted = quoted <NEW_LINE> <DEDENT> def set_value(self, value, quoted=False): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> self._quoted = quoted <NEW_LINE> logging.debug('CLIPositionalValue value updated: value=' + str(value) + ', quoted=' + str(quoted)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self._quoted: <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.normalize(self._value) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return common.class_repr(self) | A CLI positional parameter | 6259906e442bda511e95d98b |
@base.vectorize <NEW_LINE> class movc(base.Instruction): <NEW_LINE> <INDENT> __slots__ = ["code"] <NEW_LINE> code = base.opcodes['MOVC'] <NEW_LINE> arg_format = ['cw', 'c'] <NEW_LINE> def execute(self): <NEW_LINE> <INDENT> self.args[0].value = self.args[1].value | Assigns register c_i the value in the register c_j.
This instruction is vectorizable | 6259906e99cbb53fe683274e |
class BakeClient(): <NEW_LINE> <INDENT> def __init__(self, mid): <NEW_LINE> <INDENT> self._client = _pybakeclient.client_init(mid._mid) <NEW_LINE> <DEDENT> def create_provider_handle(self, addr, provider_id): <NEW_LINE> <INDENT> ph = _pybakeclient.provider_handle_create(self._client, addr._hg_addr, provider_id) <NEW_LINE> return BakeProviderHandle(ph) <NEW_LINE> <DEDENT> def shutdown_service(self, addr): <NEW_LINE> <INDENT> _pybakeclient.shutdown_service(self._client, addr._hg_addr) <NEW_LINE> <DEDENT> def finalize(self): <NEW_LINE> <INDENT> _pybakeclient.client_finalize(self._client) | The BakeClient class wraps a bake_client_t structure at C level.
It registers the RPCs necessary to interact with a Bake provider.
It can be used to create provider handles pointing to Bake providers. | 6259906ecc0a2c111447c704 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.