code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class TestSample: <NEW_LINE> <INDENT> def test_sample_dimensions(self, qubit_device_2_wires): <NEW_LINE> <INDENT> qubit_device_2_wires.reset() <NEW_LINE> qubit_device_2_wires.apply([qml.RX(1.5708, wires=[0]), qml.RX(1.5708, wires=[1])]) <NEW_LINE> qubit_device_2_wires.shots = 10 <NEW_LINE> qubit_device_2_wires._wires_measured = {0} <NEW_LINE> qubit_device_2_wires._samples = qubit_device_2_wires.generate_samples() <NEW_LINE> s1 = qubit_device_2_wires.sample(qml.PauliZ(wires=[0])) <NEW_LINE> assert np.array_equal(s1.shape, (10,)) <NEW_LINE> qubit_device_2_wires.reset() <NEW_LINE> qubit_device_2_wires.shots = 12 <NEW_LINE> qubit_device_2_wires._wires_measured = {1} <NEW_LINE> qubit_device_2_wires._samples = qubit_device_2_wires.generate_samples() <NEW_LINE> s2 = qubit_device_2_wires.sample(qml.PauliZ(wires=[1])) <NEW_LINE> assert np.array_equal(s2.shape, (12,)) <NEW_LINE> qubit_device_2_wires.reset() <NEW_LINE> qubit_device_2_wires.shots = 17 <NEW_LINE> qubit_device_2_wires._wires_measured = {0, 1} <NEW_LINE> qubit_device_2_wires._samples = qubit_device_2_wires.generate_samples() <NEW_LINE> s3 = qubit_device_2_wires.sample(qml.PauliX(0) @ qml.PauliZ(1)) <NEW_LINE> assert np.array_equal(s3.shape, (17,)) <NEW_LINE> <DEDENT> def test_sample_values(self, qubit_device_2_wires, tol): <NEW_LINE> <INDENT> qubit_device_2_wires.reset() <NEW_LINE> qubit_device_2_wires.shots = 1000 <NEW_LINE> qubit_device_2_wires.apply([qml.RX(1.5708, wires=[0])]) <NEW_LINE> qubit_device_2_wires._wires_measured = {0} <NEW_LINE> qubit_device_2_wires._samples = qubit_device_2_wires.generate_samples() <NEW_LINE> s1 = qubit_device_2_wires.sample(qml.PauliZ(0)) <NEW_LINE> assert np.allclose(s1**2, 1, atol=tol, rtol=0)
Tests that samples are properly calculated.
62598fed091ae3566870542f
class ParseError(Error): <NEW_LINE> <INDENT> def __init__(self, text, offset): <NEW_LINE> <INDENT> self._text = text <NEW_LINE> self._offset = offset <NEW_LINE> self._line = line(text, offset) <NEW_LINE> self._column = column(text, offset) <NEW_LINE> message = _format_invalid_syntax(text, offset) <NEW_LINE> super(ParseError, self).__init__(message) <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self._text <NEW_LINE> <DEDENT> @property <NEW_LINE> def offset(self): <NEW_LINE> <INDENT> return self._offset <NEW_LINE> <DEDENT> @property <NEW_LINE> def line(self): <NEW_LINE> <INDENT> return self._line <NEW_LINE> <DEDENT> @property <NEW_LINE> def column(self): <NEW_LINE> <INDENT> return self._column
This exception is raised when the parser fails to parse the text.
62598fee3cc13d1c6d465f68
class UpdatableAPISyntheticsResource(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def update_synthetics(cls, id, params=None, **body): <NEW_LINE> <INDENT> if params is None: <NEW_LINE> <INDENT> params = {} <NEW_LINE> <DEDENT> path = "{resource_name}/tests/{resource_id}".format(resource_name=cls._resource_name, resource_id=id) <NEW_LINE> api_version = getattr(cls, "_api_version", None) <NEW_LINE> return APIClient.submit("PUT", path, api_version, body, **params)
Update Synthetics resource
62598feec4546d3d9def7692
class UpdateObserverDict(ObservedDict): <NEW_LINE> <INDENT> def __init__( self, name, observer, initial_dict=None, initial_yaml_string=None, *args, **kwargs, ): <NEW_LINE> <INDENT> self.observer = observer <NEW_LINE> self.name = name <NEW_LINE> check_input_args = [i is None for i in [initial_dict, initial_yaml_string]] <NEW_LINE> if all(check_input_args) or not any(check_input_args): <NEW_LINE> <INDENT> raise ValueError( "must supply one, and only one, of initial_dict or initial_yaml_string" ) <NEW_LINE> <DEDENT> super().__init__(initial_dict, initial_yaml_string, *args, **kwargs) <NEW_LINE> <DEDENT> def notify(self, updated=None): <NEW_LINE> <INDENT> temp_dict = { k: v for k, v in self.items() if (not isinstance(v, dict) and v is not None) or (isinstance(v, dict) and len(v.keys()) > 0) } <NEW_LINE> self.observer.attrs[self.name] = AttrDict(temp_dict).to_yaml()
Dictionary subclass which observes a dictionary and updates an attribute of the model_data xarray dataset with a YAML string of that dictionary. This update takes place whenever a value is updated in the dictionary. Parameters ---------- name : str The model_data attribute key to update. observer : xarray Dataset (e.g. calliope model_data) The Dataset whose attribute dictionary will contain the key `name` and value = a YAML string of the initial_dict. initial_dict : dict, optional, default = None An initial dictionary to copy for observing. One of initial_dict or initial_yaml_string must be defined. initial_yaml_string : str, optional, default = None A YAML string of an initial dictionary to copy for observing. One of initial_dict or initial_yaml_string must be defined. Returns ------- Observed dictionary, which acts as a dictionary in every sense *except* that on changing or adding any key:value pairs in that dictionary, the YAML string stored at `observer.attrs[name]` will be updated to reflect the new Observed dicitonary.
62598fee26238365f5fad37a
class TagDetail(generics.RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> http_method_names = ['get', 'put', 'delete'] <NEW_LINE> queryset = Tag.objects.all() <NEW_LINE> serializer_class = TagSerializer <NEW_LINE> permission_classes = (permissions.IsAuthenticated, IsOwnerOrChris) <NEW_LINE> def retrieve(self, request, *args, **kwargs): <NEW_LINE> <INDENT> response = super(TagDetail, self).retrieve(request, *args, **kwargs) <NEW_LINE> template_data = {"name": "", "color": ""} <NEW_LINE> return services.append_collection_template(response, template_data)
A tag view.
62598feead47b63b2c5a806b
class TankAnt(BodyguardAnt): <NEW_LINE> <INDENT> name = 'Tank' <NEW_LINE> damage = 1 <NEW_LINE> implemented = True <NEW_LINE> food_cost = 6 <NEW_LINE> armor = 2 <NEW_LINE> is_container = True <NEW_LINE> def action(self, colony): <NEW_LINE> <INDENT> if self.contained_ant != None: <NEW_LINE> <INDENT> self.contained_ant.action(colony) <NEW_LINE> <DEDENT> bees_in_the_spot = self.place.bees[:] <NEW_LINE> for bee in bees_in_the_spot: <NEW_LINE> <INDENT> bee.reduce_armor(self.damage)
TankAnt provides both offensive and defensive capabilities.
62598fee4c3428357761aac8
class TipoServicioAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ("nombre", "get_icono",) <NEW_LINE> exclude = ("width", "height",)
Tipo de servicio
62598fee091ae3566870543d
@key_as_value <NEW_LINE> class CONFIG_KEYS(object): <NEW_LINE> <INDENT> SERVER_URI = '' <NEW_LINE> LOGIN_USERNAME = '' <NEW_LINE> LOGIN_PASSWORD = '' <NEW_LINE> PATCH_METEOR_CLIENT = '' <NEW_LINE> RECONNECT_ENABLED = '' <NEW_LINE> HEARTBEAT_ENABLED = '' <NEW_LINE> HEARTBEAT_INTERVAL = '' <NEW_LINE> HEARTBEAT_FUNC = '' <NEW_LINE> BOT_LOG_LEVEL = ''
Class that contains config keys. After decorated by `key_as_value`, the attribute values are set to be the attribute names, i.e. CONFIG_KEYS.SERVER_URI == 'SERVER_URI'. Config values can be overridden by env variables. Config key `SERVER_URI` maps to env variable name `ROCKETCHAT_SERVER_URI`. Use string '0', 'false' or 'no' to mean boolean false in env variable value. The prefix used when mapping config name to env variable name is defined at 5IQNR.
62598fee26238365f5fad382
class AttributeValue(ctypes.Union): <NEW_LINE> <INDENT> _arg_type = ctypes.c_uint64 <NEW_LINE> _fields_ = [ ("uint8", ctypes.c_uint8), ("uint16", ctypes.c_uint16), ("uint32", ctypes.c_uint32), ("uint64", ctypes.c_uint64), ("int8", ctypes.c_int8), ("int16", ctypes.c_int16), ("int32", ctypes.c_int32), ("int64", ctypes.c_int64), ("float32", ctypes.c_float), ("float64", ctypes.c_double), ("stringRef", StringRef), ("attributeRef", AttributeRef), ("locationRef", LocationRef), ("regionRef", RegionRef), ("groupRef", GroupRef), ("metricRef", MetricRef), ("commRef", CommRef), ("parameterRef", ParameterRef), ("rmaWinRef", RmaWinRef), ("sourceCodeLocationRef", SourceCodeLocationRef), ("callingContextRef", CallingContextRef), ("interruptGeneratorRef", InterruptGeneratorRef), ("ioFileRef", IoFileRef), ("ioHandleRef", IoHandleRef), ("_arg_value", ctypes.c_uint64), ]
ctypes does not support unions as (non-pointer) arguments _arg_value / _arg_type is a crude and evil hack to guess the right argument type. This type must be correct in terms of size (maximum of the union) and calling convention (architecture specific, but for AMD64 int usually wins). Whenever used as a direct function argument (also applies to callbacks) this type should be used instead of the union. Otherwise you get undefined behavior.
62598fee3cc13d1c6d465f76
@Singleton <NEW_LINE> class Tools: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.tools = {} <NEW_LINE> self.load_yaml() <NEW_LINE> <DEDENT> def load_yaml(self): <NEW_LINE> <INDENT> yaml_file = None <NEW_LINE> config_file_search = [os.path.join(os.path.abspath(os.sep), "dgenies", "tools.yaml"), "/etc/dgenies/tools.yaml", "/etc/dgenies/tools.yaml.local", os.path.join(str(Path.home()), ".dgenies", "tools.yaml"), os.path.join(str(Path.home()), ".dgenies", "tools.yaml.local")] <NEW_LINE> if os.name == "nt": <NEW_LINE> <INDENT> config_file_search.insert(1, os.path.join(sys.executable, '..', "tools.yaml")) <NEW_LINE> config_file_search.insert(1, os.path.join(sys.executable, '..', "tools.yaml.local")) <NEW_LINE> <DEDENT> app_dir = os.path.dirname(inspect.getfile(self.__class__)) <NEW_LINE> config_file_search.append(os.path.join(app_dir, "tools-dev.yaml")) <NEW_LINE> config_file_search.append(os.path.join(app_dir, "tools-dev.yaml.local")) <NEW_LINE> for my_config_file in reversed(config_file_search): <NEW_LINE> <INDENT> if os.path.exists(my_config_file): <NEW_LINE> <INDENT> yaml_file = my_config_file <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if yaml_file is None: <NEW_LINE> <INDENT> raise FileNotFoundError("ERROR: tools.yaml not found.") <NEW_LINE> <DEDENT> with open(yaml_file, "r") as yml_f: <NEW_LINE> <INDENT> tools_dict = yaml.load(yml_f) <NEW_LINE> tools = {} <NEW_LINE> for name, props in tools_dict.items(): <NEW_LINE> <INDENT> tools[name] = Tool(name=name, **props) <NEW_LINE> <DEDENT> self.tools.update(tools)
Load (from yaml file) and store available alignement tools
62598fee4c3428357761aad0
class DefaultNamed: <NEW_LINE> <INDENT> def __init__(self, package, name=None, *args, **kwargs): <NEW_LINE> <INDENT> name = name or self.default_name <NEW_LINE> super(DefaultNamed, self).__init__(package, name, *args, **kwargs)
Mix-in for Parts that have a default name. Subclasses should include a 'default_name' attribute, which will be used during construction if a name is not explicitly defined.
62598feec4546d3d9def7699
class Parse(luigi.Task): <NEW_LINE> <INDENT> id = luigi.IntParameter() <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> return [Skeleton(), Download(self.id)] <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> with open('./cn_database/config.yaml', 'r') as f: <NEW_LINE> <INDENT> config = yaml.load(f) <NEW_LINE> <DEDENT> return luigi.LocalTarget(config['data_path'] + 'materia/materia_{}.tsv'.format(self.id)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> columns = pickle.load(open('cn_database/skeletons/senado_materia_sql.p', 'rb')) <NEW_LINE> d = {c[0]:"" for c in columns} <NEW_LINE> skeleton = collections.OrderedDict(sorted(d.items(), key=lambda x: x[0])) <NEW_LINE> with self.input()[1].open('rb') as f: <NEW_LINE> <INDENT> xml = f.read() <NEW_LINE> df = self._to_csv(xml, skeleton) <NEW_LINE> <DEDENT> with self.output().open('w') as f: <NEW_LINE> <INDENT> for i, v in enumerate(df.values()): <NEW_LINE> <INDENT> if len(df)-1 == i: <NEW_LINE> <INDENT> print('funcionou') <NEW_LINE> f.write('{}'.format(v)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f.write('{}\t'.format(v)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _to_csv(self, xml, skeleton): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> full_dic = xmltodict.parse(xml)['DetalheMateria']['Materia'] <NEW_LINE> all_keys = pickle.load(open('cn_database/skeletons/senado_materia_keymap.p', 'rb')) <NEW_LINE> df = utils._get_values(full_dic, all_keys, skeleton) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise Exception('EmptyXML') <NEW_LINE> <DEDENT> df['datacaptura'] = datetime.datetime.now() <NEW_LINE> df['numerocaptura'] = int(1) <NEW_LINE> df = utils._strip_all(df) <NEW_LINE> return df
Gets a XML file and parses it to a .tsv file using the skeleton. Raises an error if XML is empty
62598fee091ae35668705443
class DeepLabv3FinalBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, bottleneck_factor=4): <NEW_LINE> <INDENT> super(DeepLabv3FinalBlock, self).__init__() <NEW_LINE> assert (in_channels % bottleneck_factor == 0) <NEW_LINE> mid_channels = in_channels // bottleneck_factor <NEW_LINE> self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels) <NEW_LINE> self.dropout = nn.Dropout(p=0.1, inplace=False) <NEW_LINE> self.conv2 = conv1x1( in_channels=mid_channels, out_channels=out_channels, bias=True) <NEW_LINE> <DEDENT> def forward(self, x, out_size): <NEW_LINE> <INDENT> x = self.conv1(x) <NEW_LINE> x = self.dropout(x) <NEW_LINE> x = self.conv2(x) <NEW_LINE> x = F.interpolate(x, size=out_size, mode="bilinear", align_corners=True) <NEW_LINE> return x
DeepLabv3 final block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bottleneck_factor : int, default 4 Bottleneck factor.
62598fee627d3e7fe0e076cc
class InceptionResnetV2Unet(UnetModel): <NEW_LINE> <INDENT> def __init__(self, config_dict, name=None): <NEW_LINE> <INDENT> super().__init__(config_dict) <NEW_LINE> self.name = 'incepres_unet' if name is None else name <NEW_LINE> <DEDENT> def build_model(self, inp, mode, regularizer=None): <NEW_LINE> <INDENT> net = inp['img'] <NEW_LINE> training = (mode == tf.estimator.ModeKeys.TRAIN) <NEW_LINE> with tf.variable_scope('encode'): <NEW_LINE> <INDENT> ds_layers = encoder.build_inception_resnet_v2(net, l2_weight_decay=self.config_dict['ext']['encoder_l2_decay'], is_training=training) <NEW_LINE> <DEDENT> logits = self.decoder(ds_layers, regularizer=regularizer, training=training) <NEW_LINE> return logits
Unet with Inception Resnet v2 decoder
62598fee26238365f5fad388
class MessageMaker(AbsMessageMaker): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.keyword = '' <NEW_LINE> self.keychannel = 0 <NEW_LINE> self.reply = '' <NEW_LINE> <DEDENT> async def executeFunction(self, message, clinet) -> str: <NEW_LINE> <INDENT> asyncio_result = await self._makeMessage(message) <NEW_LINE> return asyncio_result <NEW_LINE> <DEDENT> async def _makeMessage(self, message) -> str: <NEW_LINE> <INDENT> asyncio_result = await message.channel.send(self.reply) <NEW_LINE> return asyncio_result <NEW_LINE> <DEDENT> def checkTriggers(self, message) -> bool: <NEW_LINE> <INDENT> return self._checkKeyword(message) <NEW_LINE> <DEDENT> def _checkKeyword(self, message) -> bool: <NEW_LINE> <INDENT> if message.content.startswith(self.keyword): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _checkChannelMessageWritten(self, message) -> bool: <NEW_LINE> <INDENT> if message.channel.id == self.keychannel: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
メッセージを作成する基底クラス absMessageMakerから直接いろんなMessageMakerに飛ばないのは オーバーライドさせたかったから。 ness_mado_message_maker.pyを見てもらうとわかるが、 このクラスを継承すれば変数に値を入れるだけでbotが反応するようにしてある。
62598fee627d3e7fe0e076ce
class _Trigger(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def fetch_all(): <NEW_LINE> <INDENT> all_triggers = [] <NEW_LINE> if trigger_body.id is not None: <NEW_LINE> <INDENT> all_triggers.append(trigger_body) <NEW_LINE> <DEDENT> methods_calls.trace += '.fetch_all' <NEW_LINE> return all_triggers <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def delete(trigger_id): <NEW_LINE> <INDENT> trigger_body.id = None <NEW_LINE> methods_calls.trace += '.delete' <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def fetch_by_id(trigger_id): <NEW_LINE> <INDENT> methods_calls.trace += '.fetch_by_id' <NEW_LINE> return trigger_body <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create(**kwargs): <NEW_LINE> <INDENT> methods_calls.trace += '.create' <NEW_LINE> return trigger_body
Mock api methods
62598feead47b63b2c5a807d
class ButtonWidget(object): <NEW_LINE> <INDENT> def __call__(self, field, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('id', field.id) <NEW_LINE> kwargs.setdefault('type', field.button_type) <NEW_LINE> kwargs.setdefault('value', field.value) <NEW_LINE> return HTMLString(u'<button %s>%s</button>' % (html_params(name=field.short_name, **kwargs), escape(unicode(field.text))))
Реализует тег <button>.
62598fee091ae35668705449
class Destroy(Object): <NEW_LINE> <INDENT> ID = "destroy" <NEW_LINE> def __init__(self, extra=None, **kwargs): <NEW_LINE> <INDENT> self.extra = extra <NEW_LINE> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(q: dict, *args) -> "Destroy": <NEW_LINE> <INDENT> return Destroy()
Closes the TDLib instance, destroying all local data without a proper logout. The current user session will remain in the list of all active sessions. All local data will be destroyed. After the destruction completes updateAuthorizationState with authorizationStateClosed will be sent Attributes: ID (:obj:`str`): ``Destroy`` No parameters required. Returns: Ok Raises: :class:`telegram.Error`
62598fee187af65679d2a00f
class UserDefinedType(Column): <NEW_LINE> <INDENT> value_manager = UDTValueManager <NEW_LINE> def __init__(self, user_type, **kwargs): <NEW_LINE> <INDENT> self.user_type = user_type <NEW_LINE> self.db_type = "frozen<{0}>".format(user_type.type_name()) <NEW_LINE> super(UserDefinedType, self).__init__(**kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def sub_types(self): <NEW_LINE> <INDENT> return list(self.user_type._fields.values()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def cql_type(self): <NEW_LINE> <INDENT> return UserType.make_udt_class( keyspace="", udt_name=self.user_type.type_name(), field_names=[c.db_field_name for c in self.user_type._fields.values()], field_types=[c.cql_type for c in self.user_type._fields.values()], )
User Defined Type column http://www.datastax.com/documentation/cql/3.1/cql/cql_using/cqlUseUDT.html These columns are represented by a specialization of :class:`cassandra.cqlengine.usertype.UserType`. Please see :ref:`user_types` for examples and discussion.
62598fee627d3e7fe0e076d4
class GsDiffCommand(WindowCommand, GitCommand): <NEW_LINE> <INDENT> def run(self, **kwargs): <NEW_LINE> <INDENT> sublime.set_timeout_async(lambda: self.run_async(**kwargs), 0) <NEW_LINE> <DEDENT> def run_async(self, in_cached_mode=False, file_path=None, current_file=False, base_commit=None, target_commit=None, disable_stage=False, title=None): <NEW_LINE> <INDENT> repo_path = self.repo_path <NEW_LINE> if current_file: <NEW_LINE> <INDENT> file_path = self.file_path or file_path <NEW_LINE> <DEDENT> view_key = "{0}{1}+{2}".format( in_cached_mode, "-" if base_commit is None else "--" + base_commit, file_path or repo_path ) <NEW_LINE> if view_key in diff_views and diff_views[view_key] in sublime.active_window().views(): <NEW_LINE> <INDENT> diff_view = diff_views[view_key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> diff_view = util.view.get_scratch_view(self, "diff", read_only=True) <NEW_LINE> if not title: <NEW_LINE> <INDENT> title = (DIFF_CACHED_TITLE if in_cached_mode else DIFF_TITLE).format(os.path.basename(repo_path)) <NEW_LINE> <DEDENT> diff_view.set_name(title) <NEW_LINE> diff_view.set_syntax_file("Packages/GitSavvy/syntax/diff.sublime-syntax") <NEW_LINE> diff_view.settings().set("git_savvy.repo_path", repo_path) <NEW_LINE> diff_view.settings().set("git_savvy.file_path", file_path) <NEW_LINE> diff_view.settings().set("git_savvy.diff_view.in_cached_mode", in_cached_mode) <NEW_LINE> diff_view.settings().set("git_savvy.diff_view.ignore_whitespace", False) <NEW_LINE> diff_view.settings().set("git_savvy.diff_view.show_word_diff", False) <NEW_LINE> diff_view.settings().set("git_savvy.diff_view.base_commit", base_commit) <NEW_LINE> diff_view.settings().set("git_savvy.diff_view.target_commit", target_commit) <NEW_LINE> diff_view.settings().set("git_savvy.diff_view.disable_stage", disable_stage) <NEW_LINE> diff_views[view_key] = diff_view <NEW_LINE> <DEDENT> self.window.focus_view(diff_view) <NEW_LINE> diff_view.sel().clear() <NEW_LINE> diff_view.run_command("gs_diff_refresh")
Create a new view to display the difference of `target_commit` against `base_commit`. If `target_commit` is None, compare working directory with `base_commit`. If `in_cached_mode` is set, display a diff of the Git index. Set `disable_stage` to True to disable Ctrl-Enter in the diff view.
62598fee187af65679d2a010
class MessageTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_validate_message(self): <NEW_LINE> <INDENT> payload = {'args': [], 'kwargs': {}} <NEW_LINE> message.KaleMessage._validate_task_payload(payload) <NEW_LINE> <DEDENT> def test_message(self): <NEW_LINE> <INDENT> payload = {'args': [], 'kwargs': {}} <NEW_LINE> kale_msg = message.KaleMessage.create_message( task_class=task.Task, task_id=1, payload=payload, queue=mock.MagicMock(), current_retry_num=None) <NEW_LINE> self.assertIsNotNone(kale_msg)
Test KaleMessage.
62598fee4c3428357761aadc
class ReprFailExample(TerminalRepr): <NEW_LINE> <INDENT> Markup = { '+': dict(green=True), '-': dict(red=True), '?': dict(bold=True), } <NEW_LINE> def __init__(self, filename, lineno, outputfile, message): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.lineno = lineno <NEW_LINE> self.outputfile = outputfile <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def toterminal(self, tw): <NEW_LINE> <INDENT> for line in self.message: <NEW_LINE> <INDENT> markup = ReprFailExample.Markup.get(line[0], {}) <NEW_LINE> tw.line(line, **markup) <NEW_LINE> <DEDENT> tw.line('%s:%d (in %s): Unexpected output' % (self.filename, self.lineno, os.path.relpath(self.outputfile)))
Reports output mismatches in a nice and informative representation.
62598fee3cc13d1c6d465f84
class NumberOfCommonMelodicIntervalsFeature(featuresModule.FeatureExtractor): <NEW_LINE> <INDENT> id = 'M7' <NEW_LINE> def __init__(self, dataOrStream=None, *arguments, **keywords): <NEW_LINE> <INDENT> featuresModule.FeatureExtractor.__init__(self, dataOrStream=dataOrStream, *arguments, **keywords) <NEW_LINE> self.name = 'Number of Common Melodic Intervals' <NEW_LINE> self.description = ('Number of melodic intervals that represent ' + 'at least 9% of all melodic intervals.') <NEW_LINE> self.isSequential = True <NEW_LINE> self.dimensions = 1 <NEW_LINE> <DEDENT> def _process(self): <NEW_LINE> <INDENT> histo = self.data['midiIntervalHistogram'] <NEW_LINE> total = sum(histo) <NEW_LINE> post = 0 <NEW_LINE> for i, count in enumerate(histo): <NEW_LINE> <INDENT> if count / float(total) >= .09: <NEW_LINE> <INDENT> post += 1 <NEW_LINE> <DEDENT> <DEDENT> self._feature.vector[0] = post
Number of melodic intervals that represent at least 9% of all melodic intervals. >>> s = corpus.parse('bwv66.6') >>> fe = features.jSymbolic.NumberOfCommonMelodicIntervalsFeature(s) >>> f = fe.extract() >>> f.vector [3]
62598fefad47b63b2c5a8087
class JobWorkUnitTest(JobTestBase): <NEW_LINE> <INDENT> def notestJobCreatesWorkUnits(self): <NEW_LINE> <INDENT> self.createSingleJobWorkflow() <NEW_LINE> testRunLumi = Run(1, 45) <NEW_LINE> loadByFRL = WorkUnit(taskID=self.testWorkflow.id, fileid=self.testFileA['id'], runLumi=testRunLumi) <NEW_LINE> loadByFRL.load() <NEW_LINE> self.assertEqual(loadByFRL['last_unit_count'], 2) <NEW_LINE> self.assertGreater(loadByFRL['id'], 0) <NEW_LINE> testRunLumi = Run(1, 46) <NEW_LINE> loadByFRL = WorkUnit(taskID=self.testWorkflow.id, fileid=self.testFileB['id'], runLumi=testRunLumi) <NEW_LINE> loadByFRL.load() <NEW_LINE> self.assertEqual(loadByFRL['last_unit_count'], 2) <NEW_LINE> self.assertGreater(loadByFRL['id'], 0) <NEW_LINE> return <NEW_LINE> <DEDENT> def notestCreateDeleteExists(self): <NEW_LINE> <INDENT> testWorkflow = Workflow(spec="spec.xml", owner="Simon", name="wf001", task="Test") <NEW_LINE> testWorkflow.create() <NEW_LINE> testWMBSFileset = Fileset(name="TestFileset") <NEW_LINE> testWMBSFileset.create() <NEW_LINE> testSubscription = Subscription(fileset=testWMBSFileset, workflow=testWorkflow) <NEW_LINE> testSubscription.create() <NEW_LINE> testJobGroup = JobGroup(subscription=testSubscription) <NEW_LINE> testJobGroup.create() <NEW_LINE> testFileA = File(lfn="/this/is/a/lfnA", size=1024, events=10) <NEW_LINE> testFileA.addRun(Run(1, *[45])) <NEW_LINE> testFileB = File(lfn="/this/is/a/lfnB", size=1024, events=10) <NEW_LINE> testFileB.addRun(Run(1, *[46])) <NEW_LINE> testFileA.create() <NEW_LINE> testFileB.create() <NEW_LINE> testJob = Job(name="TestJob", files=[testFileA, testFileB]) <NEW_LINE> testWU1 = WorkUnit(taskID=testWorkflow.id, fileid=testFileA['id'], runLumi=Run(1, *[45])) <NEW_LINE> testWU2 = WorkUnit(taskID=testWorkflow.id, fileid=testFileB['id'], runLumi=Run(1, *[46])) <NEW_LINE> self.assertFalse(testWU1.exists(), "WorkUnit exists before job was created") <NEW_LINE> self.assertFalse(testWU2.exists(), "WorkUnit exists before job was created") <NEW_LINE> testJob.create(group=testJobGroup) <NEW_LINE> self.assertTrue(testWU1.exists(), "WorkUnit does not exist after job was created") <NEW_LINE> self.assertTrue(testWU2.exists(), "WorkUnit does not exist after job was created") <NEW_LINE> testJob.delete() <NEW_LINE> self.assertTrue(testWU1.exists(), "WorkUnit does not exist after job is deleted") <NEW_LINE> self.assertTrue(testWU2.exists(), "WorkUnit does not exist after job is deleted") <NEW_LINE> testWorkflow.delete() <NEW_LINE> self.assertFalse(testWU1.exists(), "WorkUnit exists after workflow is deleted") <NEW_LINE> self.assertFalse(testWU2.exists(), "WorkUnit exists after workflow is deleted") <NEW_LINE> return
Create jobs and test that associated WorkUnits are correct
62598fef3cc13d1c6d465f8a
class OverviewPage(Template.Page): <NEW_LINE> <INDENT> titleElements = [ Nouvelle.tag('img', _class='banner', src='/media/img/banner-70-nb.png', width=329, height=52, alt='CIA.vc: The open source version control informant.'), ] <NEW_LINE> logoElements = [] <NEW_LINE> heading = Template.pageBody[ "This is a brief overview of the information collected recently. ", Nouvelle.tag("a", href="/doc")[ "Learn more about CIA" ], ] <NEW_LINE> def __init__(self, sidebarPath='doc/.default.sidebar'): <NEW_LINE> <INDENT> self.leftColumn = self._loadSidebar(sidebarPath) <NEW_LINE> <DEDENT> def _loadSidebar(self, path): <NEW_LINE> <INDENT> sections = [] <NEW_LINE> for line in open(path): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if not line: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if line[0] == '-': <NEW_LINE> <INDENT> sections.append(Template.StaticSection(line[1:].strip())) <NEW_LINE> continue <NEW_LINE> <DEDENT> pieces = line.split("::", 1) <NEW_LINE> if len(pieces) > 1: <NEW_LINE> <INDENT> title, url = pieces <NEW_LINE> sections[-1].rows.append( Nouvelle.tag('a', href=url.strip())[title.strip()] ) <NEW_LINE> <DEDENT> <DEDENT> return sections <NEW_LINE> <DEDENT> def render_mainColumn(self, context): <NEW_LINE> <INDENT> return [ self.heading, [ Template.SectionGrid( [ ActivitySection("project", "Most active projects today"), ActivitySection("author", "Most active authors today"), ], [ TimestampSection("project", "Newest projects"), TimestampSection("author", "Newest authors"), ], ), ] ]
A web page showing an overview of open source activity, meant to be used as a front page for the CIA web site. We want to act as a jumping-off point for the rest of the site, so this page doesn't include its own sidebar- it will copy the sidebar from a given page.
62598fef627d3e7fe0e076df
class ToTensor(object): <NEW_LINE> <INDENT> def __call__(self, pic): <NEW_LINE> <INDENT> if isinstance(pic, np.ndarray): <NEW_LINE> <INDENT> img = torchTool.from_numpy(pic.transpose((2, 0, 1))) <NEW_LINE> return img.float().div(255) <NEW_LINE> <DEDENT> if accimage is not None and isinstance(pic, accimage.Image): <NEW_LINE> <INDENT> nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) <NEW_LINE> pic.copyto(nppic) <NEW_LINE> return torchTool.from_numpy(nppic) <NEW_LINE> <DEDENT> if pic.mode == 'I': <NEW_LINE> <INDENT> img = torchTool.from_numpy(np.array(pic, np.int32, copy=False)) <NEW_LINE> <DEDENT> elif pic.mode == 'I;16': <NEW_LINE> <INDENT> img = torchTool.from_numpy(np.array(pic, np.int16, copy=False)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> img = torchTool.ByteTensor(torchTool.ByteStorage.from_buffer(pic.tobytes())) <NEW_LINE> <DEDENT> if pic.mode == 'YCbCr': <NEW_LINE> <INDENT> nchannel = 3 <NEW_LINE> <DEDENT> elif pic.mode == 'I;16': <NEW_LINE> <INDENT> nchannel = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nchannel = len(pic.mode) <NEW_LINE> <DEDENT> img = img.view(pic.size[1], pic.size[0], nchannel) <NEW_LINE> img = img.transpose(0, 1).transpose(0, 2).contiguous() <NEW_LINE> if isinstance(img, torchTool.ByteTensor): <NEW_LINE> <INDENT> return img.float().div(255) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return img
Convert a ``PIL.Image`` or ``numpy.ndarray`` to tensor. Converts a PIL.Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].
62598fef26238365f5fad39a
class Error(object): <NEW_LINE> <INDENT> def __init__(self, result=None, code=None, message=None): <NEW_LINE> <INDENT> self.result = result <NEW_LINE> self.code = code <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__dict__.__str__()
This class represents the result of a call to the API. It does not necessarily represent a failed call because this implies the result of the call itself
62598fef4c3428357761aaee
class ArticleUpdateForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Article <NEW_LINE> fields = ('title', 'content',) <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ArticleUpdateForm, self).__init__(*args, **kwargs) <NEW_LINE> self.helper = FormHelper(self) <NEW_LINE> self.helper.form_action = reverse('wiki_edit', kwargs={'pk': kwargs['instance'].id}) <NEW_LINE> self.helper.form_method = 'POST' <NEW_LINE> self.helper.form_class = 'form-horizontal' <NEW_LINE> self.helper.form_id = 'form_update_wiki' <NEW_LINE> self.helper.help_text_inline = True <NEW_LINE> self.helper.html5_required = True <NEW_LINE> self.helper.label_class = 'col-sm-1 control-label' <NEW_LINE> self.helper.field_class = 'col-sm-11' <NEW_LINE> self.helper.layout = Layout( Field('title'), Field('content'), ButtonHolder( Submit('add_button', _(u'Save'), css_class="btn btn-success"), Submit('cancel_button', _(u'Cancel'), css_class="btn btn-primary"), ) )
View ArticleUpdateForm
62598fefc4546d3d9def76a8
class MajorDomo(object): <NEW_LINE> <INDENT> _worker_pool = []
The controller
62598fef627d3e7fe0e076ed
class MainGameEventHandler(EventHandler): <NEW_LINE> <INDENT> def ev_keydown(self, event: tcod.event.KeyDown) -> Optional[ActionOrHandler]: <NEW_LINE> <INDENT> action: Optional[Action] = None <NEW_LINE> key = event.sym <NEW_LINE> modifier = event.mod <NEW_LINE> player: Actor = self.engine.player <NEW_LINE> if key == tcod.event.K_PERIOD and modifier & ( tcod.event.KMOD_LSHIFT | tcod.event.KMOD_RSHIFT ): <NEW_LINE> <INDENT> return actions.TakeStairsAction(player) <NEW_LINE> <DEDENT> if key in MOVE_KEYS: <NEW_LINE> <INDENT> dx, dy = MOVE_KEYS[key] <NEW_LINE> action = BumpAction(player, dx, dy) <NEW_LINE> <DEDENT> elif key in WAIT_KEYS: <NEW_LINE> <INDENT> action = WaitAction(player) <NEW_LINE> <DEDENT> elif key == tcod.event.K_ESCAPE: <NEW_LINE> <INDENT> raise SystemExit() <NEW_LINE> <DEDENT> elif key == tcod.event.K_v: <NEW_LINE> <INDENT> return HistoryViewer(self.engine) <NEW_LINE> <DEDENT> elif key == tcod.event.K_g: <NEW_LINE> <INDENT> action = PickupAction(player) <NEW_LINE> <DEDENT> elif key == tcod.event.K_i: <NEW_LINE> <INDENT> return InventoryActivateHandler(self.engine) <NEW_LINE> <DEDENT> elif key == tcod.event.K_d: <NEW_LINE> <INDENT> return InventoryDropHandler(self.engine) <NEW_LINE> <DEDENT> elif key == tcod.event.K_c: <NEW_LINE> <INDENT> return CharacterScreenEventHandler(self.engine) <NEW_LINE> <DEDENT> elif key == tcod.event.K_SLASH: <NEW_LINE> <INDENT> return LookHandler(self.engine) <NEW_LINE> <DEDENT> return action
Handles events from TCOD.
62598fef091ae35668705467
class catalog_013(models.Model): <NEW_LINE> <INDENT> id = models.IntegerField(primary_key=True) <NEW_LINE> src_word = models.CharField(max_length=50) <NEW_LINE> tar_word = models.CharField(max_length=50) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.src_word + "-->" + self.tar_word
Create a table which contains catalog id and word pair. The number of this catalog table is 013 It contains three columns: id int type catalog id src_word char type the source word which needs to be subsitute tar_word char type the word that is translated from the source word
62598fefc4546d3d9def76ad
class CategoricalDataset(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.codes = collections.OrderedDict( (var, np.unique(data[var])) for var in data ) <NEW_LINE> self.dimensions = [len(code) for code in self.codes.values()] <NEW_LINE> <DEDENT> def to_onehot_flat(self): <NEW_LINE> <INDENT> return torch.cat([to_onehot(self.data[var], code) for var, code in self.codes.items()], 1) <NEW_LINE> <DEDENT> def from_onehot_flat(self, data): <NEW_LINE> <INDENT> categorical_data = pd.DataFrame() <NEW_LINE> index = 0 <NEW_LINE> for var, code in self.codes.items(): <NEW_LINE> <INDENT> var_data = data[:, index:(index+len(code))] <NEW_LINE> categorical_data[var] = from_onehot(var_data, code) <NEW_LINE> index += len(code) <NEW_LINE> <DEDENT> return categorical_data
Class to convert between pandas DataFrame with categorical variables and a torch Tensor with onehot encodings of each variable Parameters ---------- data : pandas.DataFrame
62598fefad47b63b2c5a80a1
class TransferAppDataProcessor(ZipProcessor): <NEW_LINE> <INDENT> zip_pattern = r'\d+_\d+_\d+_TR_Applications\.txt' <NEW_LINE> def transform(self): <NEW_LINE> <INDENT> with open(self.fn, encoding='utf8') as f: <NEW_LINE> <INDENT> data = f.read() <NEW_LINE> <DEDENT> pattern = r'custom_questions_(\d+)_(.+?)(?=[\t\r\n])' <NEW_LINE> replacement = r'\2_\1' <NEW_LINE> with open(self.fn, 'w', encoding='utf8') as f: <NEW_LINE> <INDENT> f.write(re.sub(pattern, replacement, data))
Class for handling Transfer Application Data files.
62598fefc4546d3d9def76af
class NetConvOnly(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.conv1 = nn.Conv2d(1, 32, 3, 1) <NEW_LINE> self.conv2 = nn.Conv2d(32, 64, 3, 1) <NEW_LINE> self.dropout1 = nn.Dropout2d(0.25) <NEW_LINE> self.dropout2 = nn.Dropout2d(0.5) <NEW_LINE> self.conv3 = nn.Conv2d(64, 128, 1, 1) <NEW_LINE> self.conv4 = nn.Conv2d(128, 10, 1, 1) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.conv1(x) <NEW_LINE> x = F.relu(x) <NEW_LINE> x = self.conv2(x) <NEW_LINE> x = F.relu(x) <NEW_LINE> x = F.max_pool2d(x, 2) <NEW_LINE> x = self.dropout1(x) <NEW_LINE> x = self.conv3(x) <NEW_LINE> x = F.relu(x) <NEW_LINE> x = self.dropout2(x) <NEW_LINE> x = self.conv4(x) <NEW_LINE> output = F.avg_pool2d(x, (12, 12), 1) <NEW_LINE> return output
Adapted Lenet model, to be quantized and synthesized. I. e. replaced the fully connected layers with 1x1 convolutions and a final global average pooling.
62598fef627d3e7fe0e076f7
class CheckPoint(Unit): <NEW_LINE> <INDENT> def __init__(self, x, y, entity_id, r, vx, vy): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.entity_id = entity_id <NEW_LINE> self.radius = r <NEW_LINE> self.x_velocity = vx <NEW_LINE> self.y_velocity = vy <NEW_LINE> <DEDENT> def bounce(self, other_unit): <NEW_LINE> <INDENT> pass
A checkpoint
62598fef187af65679d2a021
class AutoScalingBlockDevice(base.Property): <NEW_LINE> <INDENT> def __init__(self, delete_on_termination=None, iops=None, snapshot_id=None, volume_size=None, volume_type=None): <NEW_LINE> <INDENT> super(AutoScalingBlockDevice, self).__init__() <NEW_LINE> self._values = {'DeleteOnTermination': delete_on_termination, 'iops': iops, 'SnapshotId': snapshot_id, 'VolumeSize': volume_size, 'VolumegType': volume_type}
The AutoScaling EBS Block Device type is an embedded property of the AutoScaling Block Device Mapping type.
62598fef4c3428357761aafe
class ContinuumVar(QsoSimVar,SpectralFeatureVar): <NEW_LINE> <INDENT> pass
Base class for variables that define the quasar spectral continuum.
62598fef4c3428357761ab00
class VnsfoVnsfWrongPackageFormat(ExceptionMessage): <NEW_LINE> <INDENT> pass
Wrong vNSFO package format.
62598fef3cc13d1c6d465fa8
class UserState: <NEW_LINE> <INDENT> def __init__(self, scenario_name, step_name, context=None): <NEW_LINE> <INDENT> self.scenario_name = scenario_name <NEW_LINE> self.step_name = step_name <NEW_LINE> self.context = context or dict(step_index='regular', text_index='regular', failure_index='regular')
Состояние пользователя внутри сценария.
62598ff0187af65679d2a023
class Individual(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.rank = None <NEW_LINE> self.crowding_distance = None <NEW_LINE> self.dominated_solutions = set() <NEW_LINE> self.genes = None <NEW_LINE> self.objectives = None <NEW_LINE> self.dominates = None <NEW_LINE> <DEDENT> def set_objectives(self, objectives): <NEW_LINE> <INDENT> self.objectives = objectives
Represents one individual
62598ff04c3428357761ab02
class ReplicaPoolParamsV1Beta1(_messages.Message): <NEW_LINE> <INDENT> autoRestart = _messages.BooleanField(1) <NEW_LINE> baseInstanceName = _messages.StringField(2) <NEW_LINE> canIpForward = _messages.BooleanField(3) <NEW_LINE> description = _messages.StringField(4) <NEW_LINE> disksToAttach = _messages.MessageField('ExistingDisk', 5, repeated=True) <NEW_LINE> disksToCreate = _messages.MessageField('NewDisk', 6, repeated=True) <NEW_LINE> initAction = _messages.StringField(7) <NEW_LINE> machineType = _messages.StringField(8) <NEW_LINE> metadata = _messages.MessageField('Metadata', 9) <NEW_LINE> networkInterfaces = _messages.MessageField('NetworkInterface', 10, repeated=True) <NEW_LINE> onHostMaintenance = _messages.StringField(11) <NEW_LINE> serviceAccounts = _messages.MessageField('ServiceAccount', 12, repeated=True) <NEW_LINE> tags = _messages.MessageField('Tag', 13) <NEW_LINE> zone = _messages.StringField(14)
Configuration information for a ReplicaPools v1beta1 API resource. Directly maps to ReplicaPool InitTemplate. Fields: autoRestart: Whether these replicas should be restarted if they experience a failure. The default value is true. baseInstanceName: The base name for instances within this ReplicaPool. canIpForward: Enables IP Forwarding description: An optional textual description of the resource. disksToAttach: A list of existing Persistent Disk resources to attach to each replica in the pool. Each disk will be attached in read-only mode to every replica. disksToCreate: A list of Disk resources to create and attach to each Replica in the Pool. Currently, you can only define one disk and it must be a root persistent disk. Note that Replica Pool will create a root persistent disk for each replica. initAction: Name of the Action to be run during initialization of a ReplicaPoolModule. machineType: The machine type for this instance. Either a complete URL, or the resource name (e.g. n1-standard-1). metadata: The metadata key/value pairs assigned to this instance. networkInterfaces: A list of network interfaces for the instance. Currently only one interface is supported by Google Compute Engine. onHostMaintenance: A string attribute. serviceAccounts: A list of Service Accounts to enable for this instance. tags: A list of tags to apply to the Google Compute Engine instance to identify resources. zone: The zone for this ReplicaPool.
62598ff026238365f5fad3c0
class CDR_REPORT_COLUMN_NAME(Choice): <NEW_LINE> <INDENT> date = _('start date') <NEW_LINE> call_id = _('call ID') <NEW_LINE> leg = _('leg') <NEW_LINE> caller_id = _('caller ID') <NEW_LINE> phone_no = _('phone no') <NEW_LINE> gateway = _('gateway') <NEW_LINE> duration = _('duration') <NEW_LINE> bill_sec = _('bill sec') <NEW_LINE> disposition = _('disposition') <NEW_LINE> amd_status = _('amd status')
Column Name for the CDR Report
62598ff0187af65679d2a028
@since('3.0.21') <NEW_LINE> class TestSecondaryIndexes(ReplicaSideFiltering): <NEW_LINE> <INDENT> __test__ = True <NEW_LINE> def create_index(self): <NEW_LINE> <INDENT> return True
@jira_ticket CASSANDRA-8272 Tests the consistency of secondary indexes queries when some of the replicas have stale data.
62598ff03cc13d1c6d465fb4
class CertificateMergeParameters(Model): <NEW_LINE> <INDENT> _validation = { 'x509_certificates': {'required': True}, } <NEW_LINE> _attribute_map = { 'x509_certificates': {'key': 'x5c', 'type': '[bytearray]'}, 'certificate_attributes': {'key': 'attributes', 'type': 'CertificateAttributes'}, 'tags': {'key': 'tags', 'type': '{str}'}, } <NEW_LINE> def __init__(self, *, x509_certificates, certificate_attributes=None, tags=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(CertificateMergeParameters, self).__init__(**kwargs) <NEW_LINE> self.x509_certificates = x509_certificates <NEW_LINE> self.certificate_attributes = certificate_attributes <NEW_LINE> self.tags = tags
The certificate merge parameters. All required parameters must be populated in order to send to Azure. :param x509_certificates: Required. The certificate or the certificate chain to merge. :type x509_certificates: list[bytearray] :param certificate_attributes: The attributes of the certificate (optional). :type certificate_attributes: ~azure.keyvault.models.CertificateAttributes :param tags: Application specific metadata in the form of key-value pairs. :type tags: dict[str, str]
62598ff026238365f5fad3c2
class LayerOutput(object): <NEW_LINE> <INDENT> def __init__(self, name, layer_type, parents=None, activation=None, num_filters=None, img_norm_type=None, size=None, outputs=None, reverse=None): <NEW_LINE> <INDENT> assert isinstance(name, basestring) <NEW_LINE> assert isinstance(layer_type, basestring) <NEW_LINE> assert size is not None <NEW_LINE> assert LayerType.is_layer_type(layer_type) <NEW_LINE> self.name = name <NEW_LINE> self.layer_type = layer_type <NEW_LINE> if parents is not None and type(parents) != list: <NEW_LINE> <INDENT> parents = [parents] <NEW_LINE> <DEDENT> self.parents = [] if parents is None else parents <NEW_LINE> self.activation = activation <NEW_LINE> self.num_filters = num_filters <NEW_LINE> self.img_norm_type = img_norm_type <NEW_LINE> self.size = size <NEW_LINE> if outputs is None: <NEW_LINE> <INDENT> outputs = ['default'] <NEW_LINE> <DEDENT> self.outputs = outputs <NEW_LINE> self.reverse = reverse <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> assert False, "this method should not be invoked" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> assert False, "this method should not be invoked"
LayerOutput is output for layer function. It is used internally by several reasons. - Check layer connection make sense. - FC(Softmax) => Cost(MSE Error) is not good for example. - Tracking layer connection. - Pass to layer methods as input. :param name: Layer output name. :type name: basestring :param layer_type: Current Layer Type. One of LayerType enumeration. :type layer_type: basestring :param activation: Layer Activation. :type activation: BaseActivation. :param parents: Layer's parents. :type parents: list|tuple|collections.Sequence
62598ff0c4546d3d9def76b8
@attr.s(auto_attribs=True, init=False) <NEW_LINE> class Datagroup(model.Model): <NEW_LINE> <INDENT> can: Optional[MutableMapping[str, bool]] = None <NEW_LINE> created_at: Optional[int] = None <NEW_LINE> id: Optional[str] = None <NEW_LINE> model_name: Optional[str] = None <NEW_LINE> name: Optional[str] = None <NEW_LINE> stale_before: Optional[int] = None <NEW_LINE> trigger_check_at: Optional[int] = None <NEW_LINE> trigger_error: Optional[str] = None <NEW_LINE> trigger_value: Optional[str] = None <NEW_LINE> triggered_at: Optional[int] = None <NEW_LINE> def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[int] = None, id: Optional[str] = None, model_name: Optional[str] = None, name: Optional[str] = None, stale_before: Optional[int] = None, trigger_check_at: Optional[int] = None, trigger_error: Optional[str] = None, trigger_value: Optional[str] = None, triggered_at: Optional[int] = None ): <NEW_LINE> <INDENT> self.can = can <NEW_LINE> self.created_at = created_at <NEW_LINE> self.id = id <NEW_LINE> self.model_name = model_name <NEW_LINE> self.name = name <NEW_LINE> self.stale_before = stale_before <NEW_LINE> self.trigger_check_at = trigger_check_at <NEW_LINE> self.trigger_error = trigger_error <NEW_LINE> self.trigger_value = trigger_value <NEW_LINE> self.triggered_at = triggered_at
Attributes: can: Operations the current user is able to perform on this object created_at: UNIX timestamp at which this entry was created. id: Unique ID of the datagroup model_name: Name of the model containing the datagroup. Unique when combined with name. name: Name of the datagroup. Unique when combined with model_name. stale_before: UNIX timestamp before which cache entries are considered stale. Cannot be in the future. trigger_check_at: UNIX timestamp at which this entry trigger was last checked. trigger_error: The message returned with the error of the last trigger check. trigger_value: The value of the trigger when last checked. triggered_at: UNIX timestamp at which this entry became triggered. Cannot be in the future.
62598ff0627d3e7fe0e07709
class DiskDict(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.db = get_default_temp_db_instance() <NEW_LINE> self.table_name = rand_alpha(30) <NEW_LINE> columns = [('index_', 'INTEGER'), ('key', 'BLOB'), ('value', 'BLOB')] <NEW_LINE> pks = ['index_'] <NEW_LINE> self.db.create_table(self.table_name, columns, pks) <NEW_LINE> self.db.create_index(self.table_name, ['key']) <NEW_LINE> self.db.commit() <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> self.db.drop_table(self.table_name) <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> pickled_keys = self.db.select('SELECT key FROM %s' % self.table_name) <NEW_LINE> result_list = [] <NEW_LINE> for r in pickled_keys: <NEW_LINE> <INDENT> result_list.append(cPickle.loads(r[0])) <NEW_LINE> <DEDENT> return result_list <NEW_LINE> <DEDENT> def iterkeys(self): <NEW_LINE> <INDENT> pickled_keys = self.db.select('SELECT key FROM %s' % self.table_name) <NEW_LINE> for r in pickled_keys: <NEW_LINE> <INDENT> yield cPickle.loads(r[0]) <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> query = 'SELECT count(*) FROM %s WHERE key=? limit 1' % self.table_name <NEW_LINE> r = self.db.select_one(query, (cPickle.dumps(key),)) <NEW_LINE> return bool(r[0]) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> query = 'UPDATE %s SET value = ? WHERE key=?' % self.table_name <NEW_LINE> self.db.execute(query, (cPickle.dumps(value), cPickle.dumps(key))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = "INSERT INTO %s VALUES (NULL, ?, ?)" % self.table_name <NEW_LINE> self.db.execute(query, (cPickle.dumps(key), cPickle.dumps(value))) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> query = 'SELECT value FROM %s WHERE key=? limit 1' % self.table_name <NEW_LINE> r = self.db.select(query, (cPickle.dumps(key),)) <NEW_LINE> if not r: <NEW_LINE> <INDENT> raise KeyError('%s not in DiskDict.' % key) <NEW_LINE> <DEDENT> return cPickle.loads(r[0][0]) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> query = 'SELECT count(*) FROM %s' % self.table_name <NEW_LINE> r = self.db.select_one(query) <NEW_LINE> return r[0] <NEW_LINE> <DEDENT> def get(self, key, default=-456): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> if default is not -456: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> raise KeyError()
It's a dict that stores items in a sqlite3 database and has the following features: - Dict-like API - Is thread safe - Deletes the table when the instance object is deleted :author: Andres Riancho (andres.riancho@gmail.com)
62598ff0187af65679d2a02a
class TimeoutHTTPConnection(http_client.HTTPConnection): <NEW_LINE> <INDENT> _timeout = None <NEW_LINE> def __init__(self, host, port=None, strict=None, timeout=None): <NEW_LINE> <INDENT> http_client.HTTPConnection.__init__(self, host, port, strict) <NEW_LINE> self._timeout = timeout or TimeoutHTTPConnection._timeout <NEW_LINE> if self._timeout: self._timeout = float(self._timeout) <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> msg = "getaddrinfo returns an empty list" <NEW_LINE> err = socket.error <NEW_LINE> for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): <NEW_LINE> <INDENT> af, socktype, proto, canonname, sa = res <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.sock = socket.socket(af, socktype, proto) <NEW_LINE> if self._timeout: self.sock.settimeout(self._timeout) <NEW_LINE> if self.debuglevel > 0: <NEW_LINE> <INDENT> print("connect: (%s, %s)" % (self.host, self.port)) <NEW_LINE> <DEDENT> self.sock.connect(sa) <NEW_LINE> <DEDENT> except socket.timeout as msg: <NEW_LINE> <INDENT> err = socket.timeout <NEW_LINE> if self.debuglevel > 0: <NEW_LINE> <INDENT> print('connect timeout:', (self.host, self.port)) <NEW_LINE> <DEDENT> self.sock = _clear(self.sock) <NEW_LINE> continue <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> except socket.error as msg: <NEW_LINE> <INDENT> if self.debuglevel > 0: <NEW_LINE> <INDENT> print('general connect fail:', (self.host, self.port)) <NEW_LINE> <DEDENT> self.sock = _clear(self.sock) <NEW_LINE> continue <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> if not self.sock: <NEW_LINE> <INDENT> if err == socket.timeout: <NEW_LINE> <INDENT> raise HTTPConnectionTimeoutError(msg) <NEW_LINE> <DEDENT> raise err(msg)
A timeout control enabled HTTPConnection. Inherit httplib.HTTPConnection class and provide the socket timeout control.
62598ff04c3428357761ab10
class TracerouteSchema(MetaParser): <NEW_LINE> <INDENT> schema = { 'traceroute':{ Any():{ 'hops':{ Any():{ 'paths':{ Any():{ 'address': str, Optional('asn'): int, Optional('name'): str, Optional('probe_msec'): list, Optional('vrf_in_name'): str, Optional('vrf_out_name'): str, Optional('vrf_in_id'): str, Optional('vrf_out_id'): str, Optional('label_info'):{ Optional('label_name'): str, Optional('exp'): int, Optional('MPLS'):{ 'label': str, 'exp': int, }, }, Optional('mru'): int, }, }, Optional('code'): str, } }, Optional('timeout_seconds'): int, Optional('name_of_address'): str, 'address': str, Optional('vrf'): str, Optional('mask'): str, }, }, }
Schema for: * 'traceroute' * 'traceroute mpls traffic-eng tunnel {tunnelid}'
62598ff03cc13d1c6d465fb8
class GH_UndoException(Exception, ISerializable, _Exception): <NEW_LINE> <INDENT> def add_SerializeObjectState(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def remove_SerializeObjectState(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, message, args=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self, *args): <NEW_LINE> <INDENT> pass
GH_UndoException(message: str) GH_UndoException(message: str, *args: Array[object])
62598ff0627d3e7fe0e0770f
class Txt(webpage.WebpageRaw): <NEW_LINE> <INDENT> head = False <NEW_LINE> visited = [] <NEW_LINE> def parse(self, *args, **kwargs): <NEW_LINE> <INDENT> self.links = [y for x in self.html.split('\n') for y in x.split('\r') if validate.url_explicit(y)]
Parses Txt sitemaps.
62598ff0c4546d3d9def76bc
class CourseKeyMalformedErrorMiddleware(BaseProcessErrorMiddleware): <NEW_LINE> <INDENT> @property <NEW_LINE> def error(self): <NEW_LINE> <INDENT> return CourseKeyMalformedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_code(self): <NEW_LINE> <INDENT> return 'course_key_malformed' <NEW_LINE> <DEDENT> @property <NEW_LINE> def status_code(self): <NEW_LINE> <INDENT> return status.HTTP_400_BAD_REQUEST
Raise 400 if course key is malformed.
62598ff0627d3e7fe0e07711
class TestContentTypeSelect(TestCase): <NEW_LINE> <INDENT> def test_filter_choices(self): <NEW_LINE> <INDENT> ctype = ContentType.objects.get_for_model(TestModel) <NEW_LINE> test_choice = (str(ctype.pk), ctype.name) <NEW_LINE> ctype = ContentType.objects.get_for_model(AnotherTestModel) <NEW_LINE> another_choice = (str(ctype.pk), ctype.name) <NEW_LINE> ctype = ContentType.objects.get_for_model(WrongTestModel) <NEW_LINE> wrong_choice = (str(ctype.pk), ctype.name) <NEW_LINE> widget = mock.MagicMock(spec=widgets.ContentTypeSelect) <NEW_LINE> widget.choices = [ ("", "----"), test_choice, another_choice, wrong_choice ] <NEW_LINE> widgets.ContentTypeSelect._filter_choices(widget) <NEW_LINE> self.assertIn(("", "----"), widget.choices) <NEW_LINE> self.assertIn(test_choice, widget.choices) <NEW_LINE> self.assertNotIn(another_choice, widget.choices) <NEW_LINE> self.assertNotIn(wrong_choice, widget.choices) <NEW_LINE> <DEDENT> @mock.patch('django.utils.safestring.mark_safe', return_value='baz') <NEW_LINE> def test_render_with_mark_safe(self, mark_safe): <NEW_LINE> <INDENT> widget = mock.MagicMock(spec=widgets.ContentTypeSelect) <NEW_LINE> widget.js = " %s" <NEW_LINE> with mock.patch.object( utils, 'get_choices_url_pattern', return_value='foo' ) as get_url_pattern, mock.patch.object( Select, 'render', return_value='bar' ) as render: <NEW_LINE> <INDENT> result = widgets.ContentTypeSelect.render(widget, 'name', 'value') <NEW_LINE> get_url_pattern.assert_called_with() <NEW_LINE> render.assert_called_with('name', 'value', None) <NEW_LINE> <DEDENT> mark_safe.assert_called_with('bar foo') <NEW_LINE> self.assertEqual(result, "baz")
Tests for the widget for selecting models in the Image admin
62598ff03cc13d1c6d465fc1
class QPushButton_cRankStocks_clicked(QThread): <NEW_LINE> <INDENT> log_signal = pyqtSignal(str) <NEW_LINE> def __init__(self, date, parent=None): <NEW_LINE> <INDENT> super(QPushButton_cRankStocks_clicked, self).__init__(parent) <NEW_LINE> self.date = date <NEW_LINE> self.header = "RankList" <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.working = False <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> DataList = Fuct_LocalData.RankList_Data(self.date) <NEW_LINE> self.emit(QtCore.SIGNAL("SIGNAL_QPushButton_cRankStocks"), self.header, DataList)
龙虎榜数据
62598ff0ad47b63b2c5a80c1
class Root(TemplateNode): <NEW_LINE> <INDENT> _sources, _targets = None, None <NEW_LINE> @_util.Property <NEW_LINE> def encoder(): <NEW_LINE> <INDENT> def fget(self): <NEW_LINE> <INDENT> return self._udict['encoder'] <NEW_LINE> <DEDENT> return locals() <NEW_LINE> <DEDENT> @_util.Property <NEW_LINE> def decoder(): <NEW_LINE> <INDENT> def fget(self): <NEW_LINE> <INDENT> return self._udict['decoder'] <NEW_LINE> <DEDENT> return locals() <NEW_LINE> <DEDENT> @_util.Property <NEW_LINE> def source_overlay_names(): <NEW_LINE> <INDENT> def fget(self): <NEW_LINE> <INDENT> if self._sources is None: <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> return self._sources.iterkeys() <NEW_LINE> <DEDENT> return locals() <NEW_LINE> <DEDENT> @_util.Property <NEW_LINE> def target_overlay_names(): <NEW_LINE> <INDENT> def fget(self): <NEW_LINE> <INDENT> if self._targets is None: <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> return self._targets.iterkeys() <NEW_LINE> <DEDENT> return locals() <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> super(Root, self).__init__('', (), {}, False) <NEW_LINE> self.endtag = '' <NEW_LINE> self._udict['is_root'] = True <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.to_string(verbose=True) <NEW_LINE> <DEDENT> def to_string(self, verbose=False): <NEW_LINE> <INDENT> if not self._finalized: <NEW_LINE> <INDENT> raise NodeTreeError("Tree was not finalized yet") <NEW_LINE> <DEDENT> return '\n'.join(list( _nodetree.represent(self._udict, bool(verbose)) )) + '\n' <NEW_LINE> <DEDENT> def finalize(self, encoder, decoder): <NEW_LINE> <INDENT> if self._finalized: <NEW_LINE> <INDENT> raise NodeTreeError("Tree was already finalized") <NEW_LINE> <DEDENT> self._sources, self._targets = _finalize.finalize(self._udict, encoder, decoder) <NEW_LINE> self._finalized = True <NEW_LINE> <DEDENT> def overlay(self, other): <NEW_LINE> <INDENT> if not self._finalized: <NEW_LINE> <INDENT> raise NodeTreeError("Tree was not finalized yet.") <NEW_LINE> <DEDENT> if not other._finalized: <NEW_LINE> <INDENT> raise NodeTreeError("Overlay tree was not finalized yet.") <NEW_LINE> <DEDENT> return _nodetree.overlay( self._udict, other._sources, TemplateNode, Root ) <NEW_LINE> <DEDENT> def render(self, model, startnode=None): <NEW_LINE> <INDENT> return _nodetree.render( _nodetree.findnode(self, startnode), model, Node )
Root Node class This class has to be used as the initial root of the tree.
62598ff0091ae3566870548d
class Assign(Internal): <NEW_LINE> <INDENT> def __init__(self, value, dst): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.value = value <NEW_LINE> self.dst = dst <NEW_LINE> <DEDENT> def __call__(self, player): <NEW_LINE> <INDENT> if isinstance(self.dst, str): <NEW_LINE> <INDENT> dst = PYTHON(self.dst, player) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dst = self.dst(player) <NEW_LINE> <DEDENT> player.values[self.value] = dst
Assign(value, dst) => action где: value - имя значения которое будет изменено dst (function) - Функция (lambda), возрат запуска которой будет новым значение для value-name Функция dst обязана принимать один аргумент. Пр. lambda player: player.values["yuri_love"] + 1
62598ff0091ae3566870548f
class RepositoryResource(proto.Message): <NEW_LINE> <INDENT> class AptRepository(proto.Message): <NEW_LINE> <INDENT> class ArchiveType(proto.Enum): <NEW_LINE> <INDENT> ARCHIVE_TYPE_UNSPECIFIED = 0 <NEW_LINE> DEB = 1 <NEW_LINE> DEB_SRC = 2 <NEW_LINE> <DEDENT> archive_type = proto.Field( proto.ENUM, number=1, enum="OSPolicy.Resource.RepositoryResource.AptRepository.ArchiveType", ) <NEW_LINE> uri = proto.Field( proto.STRING, number=2, ) <NEW_LINE> distribution = proto.Field( proto.STRING, number=3, ) <NEW_LINE> components = proto.RepeatedField( proto.STRING, number=4, ) <NEW_LINE> gpg_key = proto.Field( proto.STRING, number=5, ) <NEW_LINE> <DEDENT> class YumRepository(proto.Message): <NEW_LINE> <INDENT> id = proto.Field( proto.STRING, number=1, ) <NEW_LINE> display_name = proto.Field( proto.STRING, number=2, ) <NEW_LINE> base_url = proto.Field( proto.STRING, number=3, ) <NEW_LINE> gpg_keys = proto.RepeatedField( proto.STRING, number=4, ) <NEW_LINE> <DEDENT> class ZypperRepository(proto.Message): <NEW_LINE> <INDENT> id = proto.Field( proto.STRING, number=1, ) <NEW_LINE> display_name = proto.Field( proto.STRING, number=2, ) <NEW_LINE> base_url = proto.Field( proto.STRING, number=3, ) <NEW_LINE> gpg_keys = proto.RepeatedField( proto.STRING, number=4, ) <NEW_LINE> <DEDENT> class GooRepository(proto.Message): <NEW_LINE> <INDENT> name = proto.Field( proto.STRING, number=1, ) <NEW_LINE> url = proto.Field( proto.STRING, number=2, ) <NEW_LINE> <DEDENT> apt = proto.Field( proto.MESSAGE, number=1, oneof="repository", message="OSPolicy.Resource.RepositoryResource.AptRepository", ) <NEW_LINE> yum = proto.Field( proto.MESSAGE, number=2, oneof="repository", message="OSPolicy.Resource.RepositoryResource.YumRepository", ) <NEW_LINE> zypper = proto.Field( proto.MESSAGE, number=3, oneof="repository", message="OSPolicy.Resource.RepositoryResource.ZypperRepository", ) <NEW_LINE> goo = proto.Field( proto.MESSAGE, number=4, oneof="repository", message="OSPolicy.Resource.RepositoryResource.GooRepository", )
A resource that manages a package repository. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. Setting any member of the oneof automatically clears all other members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: apt (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.AptRepository): An Apt Repository. This field is a member of `oneof`_ ``repository``. yum (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.YumRepository): A Yum Repository. This field is a member of `oneof`_ ``repository``. zypper (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.ZypperRepository): A Zypper Repository. This field is a member of `oneof`_ ``repository``. goo (google.cloud.osconfig_v1alpha.types.OSPolicy.Resource.RepositoryResource.GooRepository): A Goo Repository. This field is a member of `oneof`_ ``repository``.
62598ff0c4546d3d9def76c0
class LearningRateSchedulerFixedStep(AdaptiveLearningRateScheduler): <NEW_LINE> <INDENT> def __init__(self, schedule: List[Tuple[float, int]], updates_per_checkpoint: int) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> check_condition(all(num_updates > 0 for (_, num_updates) in schedule), "num_updates for each step should be > 0.") <NEW_LINE> check_condition(all(num_updates % updates_per_checkpoint == 0 for (_, num_updates) in schedule), "num_updates for each step should be divisible by updates_per_checkpoint.") <NEW_LINE> self.schedule = schedule <NEW_LINE> self.current_step = 0 <NEW_LINE> self.current_rate = 0. <NEW_LINE> self.current_step_num_updates = 0 <NEW_LINE> self.current_step_started_at = 0 <NEW_LINE> self.next_step_at = 0 <NEW_LINE> self.latest_t = 0 <NEW_LINE> self._update_rate(self.current_step) <NEW_LINE> <DEDENT> def new_evaluation_result(self, has_improved: bool) -> bool: <NEW_LINE> <INDENT> logger.info("Checkpoint learning rate: %1.2e (%d/%d updates)", self.current_rate, self.latest_t - self.current_step_started_at, self.current_step_num_updates) <NEW_LINE> if self.latest_t >= self.next_step_at: <NEW_LINE> <INDENT> self.current_step += 1 <NEW_LINE> self._update_rate(self.current_step) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _update_rate(self, step: int): <NEW_LINE> <INDENT> if self.current_step < len(self.schedule): <NEW_LINE> <INDENT> self.current_rate, self.current_step_num_updates = self.schedule[step] <NEW_LINE> self.current_step_started_at = self.latest_t <NEW_LINE> self.next_step_at += self.current_step_num_updates <NEW_LINE> logger.info("Changing learning rate to %1.2e for %d updates", self.current_rate, self.current_step_num_updates) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, t: int): <NEW_LINE> <INDENT> self.latest_t = max(t, self.latest_t) <NEW_LINE> return self.current_rate <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse_schedule_str(schedule_str: str) -> List[Tuple[float, int]]: <NEW_LINE> <INDENT> schedule = list() <NEW_LINE> for step in schedule_str.split(","): <NEW_LINE> <INDENT> rate, num_updates = step.split(":") <NEW_LINE> schedule.append((float(rate), int(num_updates))) <NEW_LINE> <DEDENT> return schedule
Use a fixed schedule of learning rate steps: lr_1 for N steps, lr_2 for M steps, etc. :param schedule: List of learning rate step tuples in the form (rate, num_updates). :param updates_per_checkpoint: Updates per checkpoint.
62598ff0627d3e7fe0e07719
class BlacklistToken(DB.Model): <NEW_LINE> <INDENT> __tablename__ = 'blacklist_tokens' <NEW_LINE> id = Column(Integer, primary_key=True, autoincrement=True) <NEW_LINE> token = Column(String(500), unique=True, nullable=False) <NEW_LINE> blacklisted_on = Column(DateTime, nullable=False) <NEW_LINE> def __init__(self, token): <NEW_LINE> <INDENT> self.token = token <NEW_LINE> self.blacklisted_on = datetime.datetime.now() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<id: token: {}'.format(self.token) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def check_blacklist(auth_token): <NEW_LINE> <INDENT> res = BlacklistToken.query.filter_by(token=str(auth_token)).first() <NEW_LINE> if res: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Token Model for storing JWT tokens
62598ff026238365f5fad3d6
class Executable(object): <NEW_LINE> <INDENT> def __init__(self, mod): <NEW_LINE> <INDENT> self.mod = mod <NEW_LINE> self._function_params = {} <NEW_LINE> self._save = self.mod["save"] <NEW_LINE> self._get_lib = self.mod["get_lib"] <NEW_LINE> self._get_bytecode = self.mod["get_bytecode"] <NEW_LINE> self._get_stats = self.mod["get_stats"] <NEW_LINE> self._get_function_arity = self.mod["get_function_arity"] <NEW_LINE> self._get_function_param_name = self.mod["get_function_param_name"] <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> return self._save(), self._get_lib() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def load_exec(bytecode, lib): <NEW_LINE> <INDENT> if isinstance(bytecode, (bytes, str)): <NEW_LINE> <INDENT> code = bytearray(bytecode) <NEW_LINE> <DEDENT> elif not isinstance(bytecode, (bytearray, TVMByteArray)): <NEW_LINE> <INDENT> raise TypeError( "bytecode is expected to be the type of bytearray " + "or TVMByteArray, but received {}".format(type(code)) ) <NEW_LINE> <DEDENT> if lib is not None and not isinstance(lib, tvm.runtime.Module): <NEW_LINE> <INDENT> raise TypeError( "lib is expected to be the type of tvm.runtime.Module" + ", but received {}".format(type(lib)) ) <NEW_LINE> <DEDENT> return Executable(_ffi_api.Load_Executable(bytecode, lib)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def lib(self): <NEW_LINE> <INDENT> return self._get_lib() <NEW_LINE> <DEDENT> @property <NEW_LINE> def stats(self): <NEW_LINE> <INDENT> return self._get_stats() <NEW_LINE> <DEDENT> @property <NEW_LINE> def primitive_ops(self): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> num_primitives = _ffi_api.GetNumOfPrimitives(self.module) <NEW_LINE> for i in range(num_primitives): <NEW_LINE> <INDENT> ret.append(_ffi_api.GetPrimitiveFields(self.module, i)) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> @property <NEW_LINE> def bytecode(self): <NEW_LINE> <INDENT> return self._get_bytecode() <NEW_LINE> <DEDENT> @property <NEW_LINE> def globals(self): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> num_globals = _ffi_api.GetNumOfGlobals(self.module) <NEW_LINE> for i in range(num_globals): <NEW_LINE> <INDENT> ret.append(_ffi_api.GetGlobalFields(self.module, i)) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> @property <NEW_LINE> def module(self): <NEW_LINE> <INDENT> return self.mod <NEW_LINE> <DEDENT> def get_function_params(self, func_name): <NEW_LINE> <INDENT> if func_name in self._function_params: <NEW_LINE> <INDENT> return self._function_params[func_name] <NEW_LINE> <DEDENT> arity = self._get_function_arity(func_name) <NEW_LINE> assert arity >= 0 <NEW_LINE> params = [] <NEW_LINE> for i in range(arity): <NEW_LINE> <INDENT> p = self._get_function_param_name(func_name, i) <NEW_LINE> assert p <NEW_LINE> params.append(p) <NEW_LINE> <DEDENT> self._function_params[func_name] = params <NEW_LINE> return params
Relay VM executable
62598ff0091ae35668705495
@testing_utils.skipUnlessGPU <NEW_LINE> class TestConvai2LanguageModel(unittest.TestCase): <NEW_LINE> <INDENT> def test_languagemodel_f1(self): <NEW_LINE> <INDENT> import projects.convai2.baselines.language_model.eval_f1 as eval_f1 <NEW_LINE> with testing_utils.capture_output() as stdout: <NEW_LINE> <INDENT> report = eval_f1.main() <NEW_LINE> <DEDENT> self.assertEqual(report['f1'], 0.1531, str(stdout))
Checks that the language model produces correct results.
62598ff126238365f5fad3d8
class OSBase: <NEW_LINE> <INDENT> def check_presence(self): <NEW_LINE> <INDENT> raise OSDetectException("check_presence unimplemented") <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> raise OSDetectException("get_name unimplemented") <NEW_LINE> <DEDENT> def get_version(self): <NEW_LINE> <INDENT> raise OSDetectException("get_version unimplemented")
This defines the API used for OS detection within the os_detect module for roslib. All OS specific instantiantions must inherit and override these methods.
62598ff1091ae35668705499
class BotList(messages.Message): <NEW_LINE> <INDENT> cursor = messages.StringField(1) <NEW_LINE> items = messages.MessageField(BotInfo, 2, repeated=True) <NEW_LINE> now = message_types.DateTimeField(3) <NEW_LINE> death_timeout = messages.IntegerField(4)
Wraps a list of BotInfo.
62598ff1627d3e7fe0e07721
class QuestionAnswersEntity(entities.BaseEntity): <NEW_LINE> <INDENT> data = db.TextProperty(indexed=False) <NEW_LINE> @classmethod <NEW_LINE> def safe_key(cls, db_key, transform_fn): <NEW_LINE> <INDENT> return db.Key.from_path(cls.kind(), transform_fn(db_key.id_or_name()))
Student answers to individual questions.
62598ff13cc13d1c6d465fcf
class UrlAuthResultAccepted(TLObject): <NEW_LINE> <INDENT> __slots__ = ["url"] <NEW_LINE> ID = 0x8f8c0e4e <NEW_LINE> QUALNAME = "types.UrlAuthResultAccepted" <NEW_LINE> def __init__(self, *, url: str): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "UrlAuthResultAccepted": <NEW_LINE> <INDENT> url = String.read(b) <NEW_LINE> return UrlAuthResultAccepted(url=url) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> b.write(String(self.url)) <NEW_LINE> return b.getvalue()
Attributes: LAYER: ``112`` Attributes: ID: ``0x8f8c0e4e`` Parameters: url: ``str`` See Also: This object can be returned by :obj:`messages.RequestUrlAuth <pyrogram.api.functions.messages.RequestUrlAuth>` and :obj:`messages.AcceptUrlAuth <pyrogram.api.functions.messages.AcceptUrlAuth>`.
62598ff1ad47b63b2c5a80d5
class Folder(SObject): <NEW_LINE> <INDENT> SEARCH_TYPE = "sthpw/folder" <NEW_LINE> def get_children(my): <NEW_LINE> <INDENT> search = Search(Folder) <NEW_LINE> search.add_filter("parent_id", my.get_id() ) <NEW_LINE> return search.get_sobjects() <NEW_LINE> <DEDENT> def create(my, parent, subdir, sobject): <NEW_LINE> <INDENT> folder = SearchType.create(Folder) <NEW_LINE> if parent: <NEW_LINE> <INDENT> folder.set_value("parent_id", parent.get_id() ) <NEW_LINE> parent_path = parent.get_value("path") <NEW_LINE> path = "%s/%s" % (parent_path,subdir) <NEW_LINE> folder.set_value("path", path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> folder.set_value("path", "/") <NEW_LINE> <DEDENT> folder.set_value("search_type", sobject.get_search_type() ) <NEW_LINE> folder.set_value("search_id", sobject.id() ) <NEW_LINE> folder.commmit() <NEW_LINE> return folder
Defines all of the settings for a given production
62598ff115fb5d323ce7f5cb
class DirectTemplateView(TemplateView): <NEW_LINE> <INDENT> extra_context = None <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(self.__class__, self).get_context_data(**kwargs) <NEW_LINE> if self.extra_context is not None: <NEW_LINE> <INDENT> for key, value in self.extra_context.items(): <NEW_LINE> <INDENT> if callable(value): <NEW_LINE> <INDENT> context[key] = value() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context[key] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return context
Extend Django ``TemplateView`` to accept extra contexts.
62598ff13cc13d1c6d465fd9
class Message(db.Model): <NEW_LINE> <INDENT> __tablename__ = "messages" <NEW_LINE> message_id = db.Column(db.Integer, autoincrement=True, primary_key=True) <NEW_LINE> sess_id = db.Column(db.Integer, db.ForeignKey("messages_sessions.sess_id"), nullable=False) <NEW_LINE> from_user_id = db.Column(db.Integer, db.ForeignKey("users.user_id"), nullable=False) <NEW_LINE> to_user_id = db.Column(db.Integer, db.ForeignKey("users.user_id"), nullable=False) <NEW_LINE> messaged_on = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) <NEW_LINE> message = db.Column(db.String(300)) <NEW_LINE> from_user = db.relationship("User", foreign_keys=[from_user_id], backref=db.backref("messages_sent", order_by=message_id)) <NEW_LINE> to_user = db.relationship("User", foreign_keys=[to_user_id], backref=db.backref("messages_received", order_by=message_id)) <NEW_LINE> mess_sess = db.relationship("MessageSession", backref=db.backref("messages", order_by=message_id)) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<Message message_id={} from_user_id={} to_user_id={}>".format( self.message_id, self.from_user_id, self.to_user_id)
Users exchange messages.
62598ff1187af65679d2a03c
class SellarProblemWithArrays(om.Problem): <NEW_LINE> <INDENT> def __init__(self, model_class=SellarDerivatives, **kwargs): <NEW_LINE> <INDENT> super(SellarProblemWithArrays, self).__init__(model_class(**kwargs)) <NEW_LINE> model = self.model <NEW_LINE> model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0]), indices=np.arange(2, dtype=int)) <NEW_LINE> model.add_design_var('x', lower=0.0, upper=10.0) <NEW_LINE> model.add_objective('obj') <NEW_LINE> model.add_constraint('con1', equals=np.zeros(1)) <NEW_LINE> model.add_constraint('con2', upper=0.0) <NEW_LINE> self.set_solver_print(0)
The Sellar problem with ndarray variable options
62598ff1ad47b63b2c5a80db
class QuickResourceApproveFormView(SuperuserRequiredMixin, ResourceCreateView): <NEW_LINE> <INDENT> def get_initial(self): <NEW_LINE> <INDENT> quick_resource = get_object_or_404(QuickResource, pk=self.kwargs.get('pk')) <NEW_LINE> initial = super().get_initial() <NEW_LINE> initial['owner'] = quick_resource.owner.pk <NEW_LINE> initial['title'] = quick_resource.title <NEW_LINE> initial['link'] = quick_resource.link <NEW_LINE> return initial <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> Resource.objects.filter(slug=self.object.slug).update(active=True) <NEW_LINE> self._notify() <NEW_LINE> QuickResource.objects.get(pk=self.kwargs.get('pk')).delete() <NEW_LINE> return super().get_success_url() <NEW_LINE> <DEDENT> def _notify(self): <NEW_LINE> <INDENT> resource = self.object <NEW_LINE> site = get_current_site(self.request) <NEW_LINE> context = { 'site_name': site.name, 'user_name': resource.owner.username, 'resource_title': resource.title, 'resource_link': get_full_path(self.request, 'resources:details', slug=resource.slug) } <NEW_LINE> subject = 'Se ha publicado el recurso {resource}'.format(resource=resource.title) <NEW_LINE> send_templated_mail( subject=subject, from_email=settings.GROUP_EMAILS['NO-REPLY'], recipients=[resource.owner.email], context=context, template_text='resources/emails/notify_quick_resource_approve.txt' )
Aprobar un recurso rápido. Muestra el form de creación del un nuevo recurso normal pero añade los datos del recurso rápido (obtenidos por el pk del URLConf). El superuser, ya ha tenido que crear manualmente los datos que faltaban al recurso.
62598ff126238365f5fad3ea
class LocationReportMode(object): <NEW_LINE> <INDENT> T0 = TypeValue(0x00,u'定时上报') <NEW_LINE> T1 = TypeValue(0x01,u'定距上报') <NEW_LINE> T2 = TypeValue(0x02,u'拐点上传') <NEW_LINE> T3 = TypeValue(0x03,u'ACC 状态改变上传') <NEW_LINE> T4 = TypeValue(0x04,u'从运动变为静止状态后,补传最后一个定位点') <NEW_LINE> T5 = TypeValue(0x05,u'网络断开重连后,上报之前最后一个有效上传点') <NEW_LINE> T6 = TypeValue(0x06,u'上报模式:星历更新强制上传 GPS 点') <NEW_LINE> T7 = TypeValue(0x07,u'上报模式:按键上传定位点') <NEW_LINE> T8 = TypeValue(0x08,u'上报模式:开机上报位置信息') <NEW_LINE> T9 = TypeValue(0x09,u'上报模式:未使用') <NEW_LINE> Ta = TypeValue(0x0a,u'上报模式:设备静止后上报最后的经纬度,但时间更新') <NEW_LINE> Tb = TypeValue(0x0b,u'WIFI 解析经纬度上传包') <NEW_LINE> Tc = TypeValue(0x0c,u'上报模式:LJDW(立即定位)指令上报') <NEW_LINE> Td = TypeValue(0x0d,u'上报模式:设备静止后上报最后的经纬度') <NEW_LINE> Te = TypeValue(0x0e,u'上报模式:GPSDUP 上传(下静止状态定时上传)') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.value = self.T0
数据点上报类型
62598ff1187af65679d2a03d
class ProducesIVCurve(sciunit.Capability): <NEW_LINE> <INDENT> def produce_iv_curve(self, **run_params): <NEW_LINE> <INDENT> return NotImplementedError("%s not implemented" % inspect.stack()[0][3]) <NEW_LINE> <DEDENT> def produce_iv_curve_ss(self, **run_params): <NEW_LINE> <INDENT> return NotImplementedError("%s not implemented" % inspect.stack()[0][3]) <NEW_LINE> <DEDENT> def produce_iv_curve_peak(self, **run_params): <NEW_LINE> <INDENT> return NotImplementedError("%s not implemented" % inspect.stack()[0][3]) <NEW_LINE> <DEDENT> def plot_iv_curve(self, v, i, *plt_args, **plt_kwargs): <NEW_LINE> <INDENT> return NotImplementedError("%s not implemented" % inspect.stack()[0][3])
The capability to produce a current-voltage plot for a set of voltage steps
62598ff1ad47b63b2c5a80dd
class OfCappedPriorityQueue(CappedPriorityQueue): <NEW_LINE> <INDENT> def push(self, members_with_core): <NEW_LINE> <INDENT> script = self.load_script('of_capped_priority_queue_push') <NEW_LINE> p = self._run_lua_script(script, [self._key], [self._cap] + self._make_members(members_with_core)) <NEW_LINE> return p[0], self._make_return(p[1]) <NEW_LINE> <DEDENT> def push_ne(self, members_with_core): <NEW_LINE> <INDENT> script = self.load_script('of_capped_priority_queue_push_ne') <NEW_LINE> p = self._run_lua_script(script, [self._key], [self._cap] + self._make_members(members_with_core)) <NEW_LINE> return False if p == 'err_ae' else (p[0], self._make_return(p[1])) <NEW_LINE> <DEDENT> def push_ae(self, members_with_core): <NEW_LINE> <INDENT> script = self.load_script('of_capped_priority_queue_push_ae') <NEW_LINE> p = self._run_lua_script(script, [self._key], [self._cap] + self._make_members(members_with_core)) <NEW_LINE> return False if p == 'err_ne' else (p[0], self._make_return(p[1])) <NEW_LINE> <DEDENT> def push_ni(self, member, score): <NEW_LINE> <INDENT> script = self.load_script('of_capped_priority_queue_push_not_in') <NEW_LINE> rs = self._run_lua_script(script, [self._key], [self._cap, score, member]) <NEW_LINE> return (rs[0], self._make_return(rs[1]), bool(rs[2])) if isinstance(rs, list) else rs
Overflow-able Priority Queue. Usage: of_capped_pq = OfCappedPriorityQueue("hello-of-pq", 3)
62598ff13cc13d1c6d465fdd
class AuthenticationExtendedForm(AuthenticationForm): <NEW_LINE> <INDENT> def confirm_login_allowed(self, user: User): <NEW_LINE> <INDENT> if not user.profile.email_is_verified: <NEW_LINE> <INDENT> messages.warning(self.request, _('Place verified you E-Mail address')) <NEW_LINE> <DEDENT> if not user.is_active: <NEW_LINE> <INDENT> raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) <NEW_LINE> <DEDENT> if not user.is_staff and not user.profile.owner.is_active: <NEW_LINE> <INDENT> raise forms.ValidationError( _("Your main user account is inactive. Place contact the main User/Admin."), code='inactive', )
Login check if user and owner is active
62598ff1091ae356687054a9
class ServerLiveMigrateForceAndAbort( integrated_helpers.ProviderUsageBaseTestCase): <NEW_LINE> <INDENT> compute_driver = 'fake.FakeLiveMigrateDriver' <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(ServerLiveMigrateForceAndAbort, self).setUp() <NEW_LINE> self.compute1 = self._start_compute(host='host1') <NEW_LINE> self.compute2 = self._start_compute(host='host2') <NEW_LINE> flavors = self.api.get_flavors() <NEW_LINE> self.flavor1 = flavors[0] <NEW_LINE> <DEDENT> def test_live_migrate_force_complete(self): <NEW_LINE> <INDENT> source_hostname = self.compute1.host <NEW_LINE> dest_hostname = self.compute2.host <NEW_LINE> source_rp_uuid = self._get_provider_uuid_by_host(source_hostname) <NEW_LINE> dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname) <NEW_LINE> server = self._boot_and_check_allocations( self.flavor1, source_hostname) <NEW_LINE> post = { 'os-migrateLive': { 'host': dest_hostname, 'block_migration': True, } } <NEW_LINE> self.api.post_server_action(server['id'], post) <NEW_LINE> migration = self._wait_for_migration_status(server, ['running']) <NEW_LINE> self.api.force_complete_migration(server['id'], migration['id']) <NEW_LINE> self._wait_for_server_parameter(self.api, server, {'OS-EXT-SRV-ATTR:host': dest_hostname, 'status': 'ACTIVE'}) <NEW_LINE> self._run_periodics() <NEW_LINE> self.assertRequestMatchesUsage( {'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0}, source_rp_uuid) <NEW_LINE> self.assertFlavorMatchesUsage(dest_rp_uuid, self.flavor1) <NEW_LINE> self.assertFlavorMatchesAllocation(self.flavor1, server['id'], dest_rp_uuid) <NEW_LINE> self._delete_and_check_allocations(server) <NEW_LINE> <DEDENT> def test_live_migrate_delete(self): <NEW_LINE> <INDENT> source_hostname = self.compute1.host <NEW_LINE> dest_hostname = self.compute2.host <NEW_LINE> source_rp_uuid = self._get_provider_uuid_by_host(source_hostname) <NEW_LINE> dest_rp_uuid = self._get_provider_uuid_by_host(dest_hostname) <NEW_LINE> server = self._boot_and_check_allocations( self.flavor1, source_hostname) <NEW_LINE> post = { 'os-migrateLive': { 'host': dest_hostname, 'block_migration': True, } } <NEW_LINE> self.api.post_server_action(server['id'], post) <NEW_LINE> migration = self._wait_for_migration_status(server, ['running']) <NEW_LINE> self.api.delete_migration(server['id'], migration['id']) <NEW_LINE> self._wait_for_server_parameter(self.api, server, {'OS-EXT-SRV-ATTR:host': source_hostname, 'status': 'ACTIVE'}) <NEW_LINE> self._run_periodics() <NEW_LINE> allocations = self._get_allocations_by_server_uuid(server['id']) <NEW_LINE> self.assertNotIn(dest_rp_uuid, allocations) <NEW_LINE> self.assertFlavorMatchesUsage(source_rp_uuid, self.flavor1) <NEW_LINE> self.assertFlavorMatchesAllocation(self.flavor1, server['id'], source_rp_uuid) <NEW_LINE> self.assertRequestMatchesUsage({'VCPU': 0, 'MEMORY_MB': 0, 'DISK_GB': 0}, dest_rp_uuid) <NEW_LINE> self._delete_and_check_allocations(server)
Test Server live migrations, which delete the migration or force_complete it, and check the allocations after the operations. The test are using fakedriver to handle the force_completion and deletion of live migration.
62598ff115fb5d323ce7f5d3
class CoreBluetoothGattCharacteristic(GattCharacteristic): <NEW_LINE> <INDENT> def __init__(self, characteristic): <NEW_LINE> <INDENT> self._characteristic = characteristic <NEW_LINE> self._value_read = threading.Event() <NEW_LINE> <DEDENT> @property <NEW_LINE> def _device(self): <NEW_LINE> <INDENT> return device_list().get(self._characteristic.service().peripheral()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def uuid(self): <NEW_LINE> <INDENT> return cbuuid_to_uuid(self._characteristic.UUID()) <NEW_LINE> <DEDENT> def read_value(self, timeout_sec=TIMEOUT_SEC): <NEW_LINE> <INDENT> self._value_read.clear() <NEW_LINE> self._device._peripheral.readValueForCharacteristic_(self._characteristic) <NEW_LINE> if not self._value_read.wait(timeout_sec): <NEW_LINE> <INDENT> raise RuntimeError('Exceeded timeout waiting to read characteristic value!') <NEW_LINE> <DEDENT> return self._characteristic.value() <NEW_LINE> <DEDENT> def write_value(self, value, write_type=0): <NEW_LINE> <INDENT> data = NSData.dataWithBytes_length_(value, len(value)) <NEW_LINE> self._device._peripheral.writeValue_forCharacteristic_type_(data, self._characteristic, write_type) <NEW_LINE> <DEDENT> def start_notify(self, on_change): <NEW_LINE> <INDENT> self._device._notify_characteristic(self._characteristic, on_change) <NEW_LINE> self._device._peripheral.setNotifyValue_forCharacteristic_(True, self._characteristic) <NEW_LINE> <DEDENT> def stop_notify(self): <NEW_LINE> <INDENT> self._device._peripheral.setNotifyValue_forCharacteristic_(False, self._characteristic) <NEW_LINE> <DEDENT> def list_descriptors(self): <NEW_LINE> <INDENT> return descriptor_list().get_all(self._characteristic.descriptors())
CoreBluetooth GATT characteristic object.
62598ff1627d3e7fe0e07733
class SigmoidLayer(NeuronLayer): <NEW_LINE> <INDENT> def _forwardImplementation(self, inbuf, outbuf): <NEW_LINE> <INDENT> outbuf[:] = sigmoid(inbuf) <NEW_LINE> <DEDENT> def _backwardImplementation(self, outerr, inerr, outbuf, inbuf): <NEW_LINE> <INDENT> inerr[:] = outbuf * (1 - outbuf) * outerr
Layer implementing the sigmoid squashing function.
62598ff13cc13d1c6d465fe3
class Gag(AweRemPlugin): <NEW_LINE> <INDENT> def activate(self): <NEW_LINE> <INDENT> self.handler = GagHandler(self) <NEW_LINE> self.info = {"title": "9gag", "category": "contextual", "priority": -1} <NEW_LINE> self.procmanager = ProcessesManagerSingleton.get() <NEW_LINE> messagemanager.set_callback("9gag", self.on_messages) <NEW_LINE> <DEDENT> def state_change(self, running): <NEW_LINE> <INDENT> if running: <NEW_LINE> <INDENT> self.info["priority"] = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.info["priority"] = -1 <NEW_LINE> <DEDENT> self.pollmanager.updateNavigationDrawer() <NEW_LINE> <DEDENT> def on_messages(self, messages): <NEW_LINE> <INDENT> for message in messages: <NEW_LINE> <INDENT> if message == "started": <NEW_LINE> <INDENT> self.state_change(True) <NEW_LINE> <DEDENT> elif message == "stopped": <NEW_LINE> <INDENT> self.state_change(False) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getHandler(self): <NEW_LINE> <INDENT> return self.handler <NEW_LINE> <DEDENT> def getInfo(self): <NEW_LINE> <INDENT> return self.info <NEW_LINE> <DEDENT> def getIconPath(self, dpi): <NEW_LINE> <INDENT> return ""
Control a 9gag webpage
62598ff1187af65679d2a041
class GruPrezDialog(ga._AnagDialog): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if not kwargs.has_key('title') and len(args) < 3: <NEW_LINE> <INDENT> kwargs['title'] = FRAME_TITLE <NEW_LINE> <DEDENT> ga._AnagDialog.__init__(self, *args, **kwargs) <NEW_LINE> self.LoadAnagPanel(GruPrezPanel(self, -1))
Dialog Gestione tabella Gruppi prezzi.
62598ff1091ae356687054b1
class KafkaLoggingHandler(logging.Handler): <NEW_LINE> <INDENT> def __init__(self, host, topic, key=None): <NEW_LINE> <INDENT> logging.Handler.__init__(self) <NEW_LINE> self.kafka_topic = topic <NEW_LINE> self.key = key <NEW_LINE> self.producer = KafkaProducer(bootstrap_servers=host) <NEW_LINE> <DEDENT> def emit(self, record): <NEW_LINE> <INDENT> if re.match('kafka', record.name): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> msg = self.format(record).encode('utf-8') <NEW_LINE> if self.key is None: <NEW_LINE> <INDENT> self.producer.send(self.kafka_topic, msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.producer.send(self.kafka_topic, self.key, msg) <NEW_LINE> <DEDENT> <DEDENT> except (KeyboardInterrupt, SystemExit): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.handleError(record) <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.producer.close() <NEW_LINE> logging.Handler.close(self)
Class to provide logging handler How to Use: step1: define the SERVER and TOPIC need to send KAFKA_SERVER = 'kafka:9092' TOPIC = 'kafka_log' step2: instantiate the handler and add into logger logger = logging.getLogger("") kafka_handler = KafkaLoggingHandler(host=KAFKA_SERVER, topic=TOPIC) logger.addHandler(kafka_handler)
62598ff115fb5d323ce7f5db
class Darknet(nn.Module): <NEW_LINE> <INDENT> def __init__(self, config_path, img_size=416): <NEW_LINE> <INDENT> super(Darknet, self).__init__() <NEW_LINE> self.module_defs = parse_model_config(config_path) <NEW_LINE> self.hyperparams, self.module_list = create_modules(self.module_defs) <NEW_LINE> self.yolo_layers = [layer[0] for layer in self.module_list if hasattr(layer[0], "metrics")] <NEW_LINE> self.img_size = img_size <NEW_LINE> self.seen = 0 <NEW_LINE> self.header_info = np.array([0, 0, 0, self.seen, 0], dtype=np.int32) <NEW_LINE> <DEDENT> def forward(self, x, targets=None): <NEW_LINE> <INDENT> img_dim = x.shape[2] <NEW_LINE> loss = 0 <NEW_LINE> layer_outputs, yolo_outputs = [], [] <NEW_LINE> for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)): <NEW_LINE> <INDENT> print(module) <NEW_LINE> if module_def["type"] in ["convolutional", "upsample", "maxpool"]: <NEW_LINE> <INDENT> x = module(x) <NEW_LINE> <DEDENT> elif module_def["type"] == "route": <NEW_LINE> <INDENT> x = torch.cat([layer_outputs[int(layer_i)] for layer_i in module_def["layers"].split(",")], 1) <NEW_LINE> <DEDENT> elif module_def["type"] == "shortcut": <NEW_LINE> <INDENT> layer_i = int(module_def["from"]) <NEW_LINE> x = layer_outputs[-1] + layer_outputs[layer_i] <NEW_LINE> <DEDENT> elif module_def["type"] == "yolo": <NEW_LINE> <INDENT> x, layer_loss = module[0](x, targets, img_dim) <NEW_LINE> loss += layer_loss <NEW_LINE> yolo_outputs.append(x) <NEW_LINE> <DEDENT> layer_outputs.append(x) <NEW_LINE> <DEDENT> yolo_outputs = to_cpu(torch.cat(yolo_outputs, 1)) <NEW_LINE> return yolo_outputs if targets is None else (loss, yolo_outputs)
YOLOv3 object detection model
62598ff14c3428357761ab42
class ALLMusicPraise(models.Model): <NEW_LINE> <INDENT> music = models.ForeignKey(AllSongMusic, blank=True, null=True, on_delete=models.SET_NULL, related_name='allmusic_praise', verbose_name=u'所属歌曲') <NEW_LINE> owner = models.ForeignKey(User, related_name='parise_user', db_index=True, verbose_name=u'赞的人') <NEW_LINE> update_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = u'合唱歌曲点赞管理' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.is_praise
赞过的用户
62598ff2ad47b63b2c5a80eb
class TestUtils(unittest.TestCase): <NEW_LINE> <INDENT> def test_get_title(self): <NEW_LINE> <INDENT> under_test = CMakeWriter.get_comment('text of comment') <NEW_LINE> self.assertEqual( '################################################################################\n' '# text of comment\n' '################################################################################\n', under_test )
This file test methods of utils package
62598ff2187af65679d2a046
class Feature: <NEW_LINE> <INDENT> __slots__ = ('seqid', 'source', 'feature', 'start', 'end', 'score', 'strand', 'phase', 'attrs') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> attr_str = ' '.join('%s "%s";' % (k, v) for (k, v) in self.attrs.iteritems()) <NEW_LINE> fields = [self.seqid, self.source, self.feature, str(self.start + 1), str(self.end), str(self.score), self.strand, self.phase, attr_str] <NEW_LINE> return '\t'.join(fields) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_str(s): <NEW_LINE> <INDENT> fields = s.strip().split('\t') <NEW_LINE> f = GTF.Feature() <NEW_LINE> f.seqid = fields[0] <NEW_LINE> f.source = fields[1] <NEW_LINE> f.feature = fields[2] <NEW_LINE> f.start = int(fields[3])-1 <NEW_LINE> f.end = int(fields[4]) <NEW_LINE> f.score = fields[5] <NEW_LINE> f.strand = fields[6] <NEW_LINE> f.phase = fields[7] <NEW_LINE> attrs = collections.OrderedDict() <NEW_LINE> if fields[8] != GTF.EMPTY_FIELD: <NEW_LINE> <INDENT> attr_strings = fields[8].strip().split(';') <NEW_LINE> for a in attr_strings: <NEW_LINE> <INDENT> if not a.strip(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> a = a.strip().split(' ') <NEW_LINE> k = a[0] <NEW_LINE> v = ' '.join(a[1:]) <NEW_LINE> v = v.strip('"') <NEW_LINE> attrs[k] = v <NEW_LINE> <DEDENT> <DEDENT> f.attrs = attrs <NEW_LINE> return f
GTF Specification (fields are tab-separated) 1. seqname - sequence name (chromosome) 2. source - program that generated this feature. 3. feature - type of feature ("transcript", "exon") 4. start - start pos of feature (1-based) 5. end - end pos of feature (inclusive) 6. score - number between 0 and 1000 7. strand - '+', '-', or '.' for unspecified 8. phase - for coding exons, frame should be a number between 0-2 that represents the reading frame of the first base. If the feature is not a coding exon, the value should be '.'. 9. attributes - optional attributes in the format: key1 "value1"; key2 "value2";
62598ff2091ae356687054bb
class TextFunction(CommandBit): <NEW_LINE> <INDENT> commandmap = FormulaConfig.textfunctions <NEW_LINE> def parsebit(self, pos): <NEW_LINE> <INDENT> self.output = TaggedOutput().settag(self.translated) <NEW_LINE> if not self.factory.detecttype(Bracket, pos): <NEW_LINE> <INDENT> Trace.error('No parameter for ' + unicode(self)) <NEW_LINE> <DEDENT> bracket = Bracket().setfactory(self.factory).parsetext(pos) <NEW_LINE> self.add(bracket) <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> self.type = 'font'
A function where parameters are read as text.
62598ff2ad47b63b2c5a80f1
class PreSimulation(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.pre_simulation" <NEW_LINE> bl_label = "Floating Pre-Simulation" <NEW_LINE> bl_options = {'REGISTER'} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return context.active_object is not None <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> mainPresim(context) <NEW_LINE> return {'FINISHED'}
Execute Pre-Simulation
62598ff215fb5d323ce7f5e5
class ClustExANM(ClustENM): <NEW_LINE> <INDENT> def _buildANM(self, ca): <NEW_LINE> <INDENT> anm = exANM() <NEW_LINE> anm.buildHessian(ca, cutoff=self._cutoff, gamma=self._gamma, R=self._R, Ri=self._Ri, r=self._r, h=self._h, exr=self._exr, gamma_memb=self._gamma_memb, hull=self._hull, lat=self._lat, center=self._centering) <NEW_LINE> return anm <NEW_LINE> <DEDENT> def run(self, **kwargs): <NEW_LINE> <INDENT> depth = kwargs.pop('depth', None) <NEW_LINE> h = depth / 2 if depth is not None else None <NEW_LINE> self._h = kwargs.pop('h', h) <NEW_LINE> self._R = float(kwargs.pop('R', 80.)) <NEW_LINE> self._Ri = float(kwargs.pop('Ri', 0.)) <NEW_LINE> self._r = float(kwargs.pop('r', 3.1)) <NEW_LINE> self._lat = str(kwargs.pop('lat', 'FCC')) <NEW_LINE> self._exr = float(kwargs.pop('exr', 5.)) <NEW_LINE> self._hull = kwargs.pop('hull', True) <NEW_LINE> self._centering = kwargs.pop('center', True) <NEW_LINE> self._turbo = kwargs.pop('turbo', True) <NEW_LINE> self._gamma_memb = kwargs.pop('gamma_memb', 1.) <NEW_LINE> super(ClustExANM, self).run(**kwargs)
Experimental.
62598ff24c3428357761ab4a
class OtherPackage(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> json_data = request.GET.get('data') <NEW_LINE> data = json.loads(json_data) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return JsonError("解析失败") <NEW_LINE> <DEDENT> if data: <NEW_LINE> <INDENT> if data.get("delete_id"): <NEW_LINE> <INDENT> model.GoodPackage.objects.filter(id=data['delete_id']).delete() <NEW_LINE> return JsonSuccess("删除成功") <NEW_LINE> <DEDENT> instance = model.Good.objects.filter(id=data['good_id']).first() <NEW_LINE> if not instance: <NEW_LINE> <INDENT> return JsonError("未知商品") <NEW_LINE> <DEDENT> form = CreateOtherPackageForm(data) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> if valid_package(instance, data): <NEW_LINE> <INDENT> package = form.save(commit=False) <NEW_LINE> package.one_package_id = data['good_id'] <NEW_LINE> package.quantify_id = data['quantify_id'] <NEW_LINE> package.save() <NEW_LINE> ret = {"package_id": package.id} <NEW_LINE> return JsonSuccess("添加成功", data=ret) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return JsonError("包装价格不能低于成本价") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for key in form.errors: <NEW_LINE> <INDENT> return JsonError(form.errors[key][0]) <NEW_LINE> <DEDENT> <DEDENT> return JsonError("提交数据有误")
"添加其他包装
62598ff226238365f5fad400
class UnsafeThreadingError(PipedError): <NEW_LINE> <INDENT> pass
Used when we are using possible dangerous threading without specifying that we really want to.
62598ff2ad47b63b2c5a80f3
class ScanPoliciesManager(v2.ScanPoliciesManager): <NEW_LINE> <INDENT> def __init__( self, exclude_dir_regexes: Iterable[Union[str, regex_class]] = tuple(), exclude_file_regexes: Iterable[Union[str, regex_class]] = tuple(), include_file_regexes: Iterable[Union[str, regex_class]] = tuple(), exclude_all_symlinks: bool = False, exclude_modified_before: Optional[int] = None, exclude_modified_after: Optional[int] = None, exclude_uploaded_before: Optional[int] = None, exclude_uploaded_after: Optional[int] = None, ): <NEW_LINE> <INDENT> if include_file_regexes and not exclude_file_regexes: <NEW_LINE> <INDENT> raise v2_exception.InvalidArgument( 'include_file_regexes', 'cannot be used without exclude_file_regexes at the same time' ) <NEW_LINE> <DEDENT> self._exclude_dir_set = v2.RegexSet(exclude_dir_regexes) <NEW_LINE> self._exclude_file_because_of_dir_set = v2.RegexSet( map(v2.convert_dir_regex_to_dir_prefix_regex, exclude_dir_regexes) ) <NEW_LINE> self._exclude_file_set = v2.RegexSet(exclude_file_regexes) <NEW_LINE> self._include_file_set = v2.RegexSet(include_file_regexes) <NEW_LINE> self.exclude_all_symlinks = exclude_all_symlinks <NEW_LINE> self._include_mod_time_range = v2.IntegerRange( exclude_modified_before, exclude_modified_after ) <NEW_LINE> with v2_exception.check_invalid_argument( 'exclude_uploaded_before,exclude_uploaded_after', '', ValueError ): <NEW_LINE> <INDENT> self._include_upload_time_range = v2.IntegerRange( exclude_uploaded_before, exclude_uploaded_after ) <NEW_LINE> <DEDENT> <DEDENT> def should_exclude_file(self, file_path): <NEW_LINE> <INDENT> if self._exclude_file_because_of_dir_set.matches(file_path): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self._include_file_set.matches(file_path): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._exclude_file_set.matches(file_path) <NEW_LINE> <DEDENT> def should_exclude_file_version(self, file_version): <NEW_LINE> <INDENT> return file_version.mod_time not in self._include_mod_time_range <NEW_LINE> <DEDENT> def should_exclude_directory(self, dir_path): <NEW_LINE> <INDENT> return self._exclude_dir_set.matches(dir_path)
Policy object used when scanning folders for syncing, used to decide which files to include in the list of files to be synced. Code that scans through files should at least use should_exclude_file() to decide whether each file should be included; it will check include/exclude patterns for file names, as well as patterns for excluding directories. Code that scans may optionally use should_exclude_directory() to test whether it can skip a directory completely and not bother listing the files and sub-directories in it.
62598ff2091ae356687054bf
class BayesMonty(BayesBasic): <NEW_LINE> <INDENT> def likelihood(self, inData): <NEW_LINE> <INDENT> lh = np.zeros(len(self.hypotheses)) <NEW_LINE> if len(lh) != 3: <NEW_LINE> <INDENT> sys.exit("Not correct number of hypotheses (3) for Monty Hall problem!") <NEW_LINE> <DEDENT> lh[0] = 1/2 <NEW_LINE> lh[1] = 0 <NEW_LINE> lh[2] = 1 <NEW_LINE> return lh
Likelihood function for Monty Hall problem. Quite unique and unlikely to be used in other applications.
62598ff2c4546d3d9def76d7
class PresetPersistorTestDeprecated(support.ResultTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.base = support.MockBase("main") <NEW_LINE> self.base.read_mock_comps() <NEW_LINE> self.base.init_sack() <NEW_LINE> <DEDENT> def test_group_install(self): <NEW_LINE> <INDENT> prst = self.base.group_persistor <NEW_LINE> grp = self.base.comps.group_by_pattern('Base') <NEW_LINE> p_grp = prst.group('base') <NEW_LINE> self.assertFalse(p_grp.installed) <NEW_LINE> with warnings.catch_warnings(): <NEW_LINE> <INDENT> self.assertEqual(self.base.group_install(grp.id, ('mandatory',)), 2) <NEW_LINE> <DEDENT> inst, removed = self.installed_removed(self.base) <NEW_LINE> self.assertEmpty(inst) <NEW_LINE> self.assertEmpty(removed) <NEW_LINE> self.assertTrue(p_grp.installed) <NEW_LINE> <DEDENT> def test_group_remove(self): <NEW_LINE> <INDENT> prst = self.base.group_persistor <NEW_LINE> grp_ids = prst.groups_by_pattern('somerset') <NEW_LINE> self.assertEqual(grp_ids, set(['somerset'])) <NEW_LINE> grp_id = dnf.util.first(grp_ids) <NEW_LINE> p_grp = prst.group('somerset') <NEW_LINE> with warnings.catch_warnings(): <NEW_LINE> <INDENT> self.assertGreater(self.base.group_remove(grp_id), 0) <NEW_LINE> <DEDENT> inst, removed = self.installed_removed(self.base) <NEW_LINE> self.assertEmpty(inst) <NEW_LINE> self.assertCountEqual([pkg.name for pkg in removed], ('pepper',)) <NEW_LINE> self.assertFalse(p_grp.installed)
Test group operations with some data in the persistor.
62598ff2ad47b63b2c5a80f5
@ddt.ddt <NEW_LINE> class MachPromotionDispatch(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> log.info('******************************** -- 测试开始 -- ********************************************') <NEW_LINE> <DEDENT> @ddt.data(*flow_not_change_Promotion) <NEW_LINE> def test_flow_promotion(self, flow_not_change_Promotion): <NEW_LINE> <INDENT> log.info('准备开始执行:^^^^^ %s ^^^^^ 编号的测试用例' % flow_not_change_Promotion['编号']) <NEW_LINE> self.after_treatment_data = Handle.machaccnt_pay_dispatch_handle(flow_not_change_Promotion) <NEW_LINE> log.info('参数化处理后的测试数据为:--%s' % self.after_treatment_data) <NEW_LINE> self.mach_pay_up_obj = MachPayDispatchUp(self.after_treatment_data, is_promotion=Constants.RESULT.TRUE) <NEW_LINE> log.info('预处理返回的内容 mach_pay_up_obj:: %s' % self.mach_pay_up_obj) <NEW_LINE> amt_info_bef, mch_ant_bef, settled_ant_bef = PreconditionKeepingAccounts.mct_promotion_dispatch_pre( self.mach_pay_up_obj) <NEW_LINE> res, html = RequestBase.send_request(**self.after_treatment_data) <NEW_LINE> log.info('本次请求结果为%s' % html) <NEW_LINE> excepted = json.loads(self.after_treatment_data['excepted_code']) <NEW_LINE> self.amt_info_after, mch_ant_after, settled_ant_aft = PreconditionKeepingAccounts.mct_promotion_dispatch_pre( self.mach_pay_up_obj) <NEW_LINE> log.info('本次数据库查询实际结果返回为 amt_info_after:%s \n mch_ant_after:%s' % (self.amt_info_after, mch_ant_after)) <NEW_LINE> Handle.machaccnt_promotion_dispatch_assert(self, html, excepted, self.mach_pay_up_obj, mch_ant_bef, mch_ant_after, self.amt_info_after, settled_ant_bef, settled_ant_aft) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> ClearingKeepingAccounts.machaccnt_promotion_dispatch_clear(self.amt_info_after, self.mach_pay_up_obj) <NEW_LINE> log.info('********************************测试结束 -- 数据清理完成 --********************************************') <NEW_LINE> log.info('******************************** -- 测试结束 -- ********************************************') <NEW_LINE> log.info('\r\n\r\n\r\n\r\n')
活动记账测试用例: <br> 1>>活动金额记账正常流程测试 test_flow_promotion
62598ff23cc13d1c6d465ff9
class Equals(Criteria): <NEW_LINE> <INDENT> def __init__(self, param1, param2, lookback=1): <NEW_LINE> <INDENT> Criteria.__init__(self) <NEW_LINE> if isinstance(param1, TechnicalIndicator): <NEW_LINE> <INDENT> param1 = param1.value <NEW_LINE> <DEDENT> if isinstance(param2, TechnicalIndicator): <NEW_LINE> <INDENT> param2 = param2.value <NEW_LINE> <DEDENT> self.param1 = param1 <NEW_LINE> self.param2 = param2 <NEW_LINE> self.lookback = lookback <NEW_LINE> self.label = 'Equals_%s_%s_%s' %(param1, param2, lookback) <NEW_LINE> self.num_bars_required = lookback <NEW_LINE> self.logger.info('Initialized - %s' %self) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Equals(param1=%s, param2=%s, lookback=%s)' %(self.param1, self.param2, self.lookback) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.label <NEW_LINE> <DEDENT> def apply(self, data_frame): <NEW_LINE> <INDENT> if len(data_frame) < self.lookback: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if isinstance(self.param2, (int, long, float)): <NEW_LINE> <INDENT> return data_frame[self.param1][-self.lookback] == self.param2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return data_frame[self.param1][-self.lookback] == data_frame[self.param2][-self.lookback]
Criteria used to determine if a technical indicator or symbol OHLCV is currently equal to another technical indicator, symbol OHLCV, or value.
62598ff2091ae356687054c7
class Tags(BasePackageElement): <NEW_LINE> <INDENT> DEFAULT_TAGS = { 'Root': { 'TagColor': 'LightBlue' } } <NEW_LINE> @property <NEW_LINE> def filename(self): <NEW_LINE> <INDENT> return 'XML/Tags.xml' <NEW_LINE> <DEDENT> def _build_etree(self): <NEW_LINE> <INDENT> self._etree = etree.Element( etree.QName(self.XMLNS_IDPKG, 'Tags'), nsmap={'idPkg': self.XMLNS_IDPKG} ) <NEW_LINE> self._etree.set('DOMVersion', self.DOM_VERSION) <NEW_LINE> self._add_xmltags() <NEW_LINE> <DEDENT> def _add_xmltags(self): <NEW_LINE> <INDENT> tags = self.merge_attributes(self.DEFAULT_TAGS, self._attributes) <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> xmltag = etree.SubElement( self._etree, 'XMLTag', attrib={ 'Self': 'XMLTag/{}'.format(tag), 'Name': tag, } ) <NEW_LINE> properties = etree.SubElement( xmltag, 'Properties' ) <NEW_LINE> tagcolor = etree.SubElement( properties, 'TagColor', attrib={ 'type': 'enumeration' } ) <NEW_LINE> tagcolor.text = tags[tag]['TagColor']
As Adobe's idml specification explains: `` The Tags.xml file contains the XML tag de nitions stored in the InDesign document, including unused tags. ``
62598ff2627d3e7fe0e0774f
class SetOversizedDMXBlockAddress(OptionalParameterTestFixture): <NEW_LINE> <INDENT> CATEGORY = TestCategory.ERROR_CONDITIONS <NEW_LINE> PID = 'DMX_BLOCK_ADDRESS' <NEW_LINE> DEPS = [SetDMXBlockAddress] <NEW_LINE> def Test(self): <NEW_LINE> <INDENT> self.AddIfSetSupported(self.NackSetResult(RDMNack.NR_DATA_OUT_OF_RANGE)) <NEW_LINE> data = struct.pack('!H', MAX_DMX_ADDRESS + 1) <NEW_LINE> self.SendRawSet(ROOT_DEVICE, self.pid, data)
Set DMX_BLOCK_ADDRESS to 513.
62598ff2091ae356687054ca
class ActionCreateFormat(DeviceAction): <NEW_LINE> <INDENT> type = ACTION_TYPE_CREATE <NEW_LINE> obj = ACTION_OBJECT_FORMAT <NEW_LINE> def __init__(self, device, format=None): <NEW_LINE> <INDENT> DeviceAction.__init__(self, device) <NEW_LINE> if format: <NEW_LINE> <INDENT> self.origFormat = device.format <NEW_LINE> if self.device.format.exists: <NEW_LINE> <INDENT> self.device.format.teardown() <NEW_LINE> <DEDENT> self.device.format = format <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.origFormat = getFormat(None) <NEW_LINE> <DEDENT> <DEDENT> def execute(self, intf=None): <NEW_LINE> <INDENT> self.device.setup() <NEW_LINE> if isinstance(self.device, PartitionDevice): <NEW_LINE> <INDENT> for flag in partitionFlag.keys(): <NEW_LINE> <INDENT> if flag in [ PARTITION_LBA, self.format.partedFlag ]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.device.unsetFlag(flag) <NEW_LINE> <DEDENT> if self.format.partedFlag is not None: <NEW_LINE> <INDENT> self.device.setFlag(self.format.partedFlag) <NEW_LINE> <DEDENT> if self.format.partedSystem is not None: <NEW_LINE> <INDENT> self.device.partedPartition.system = self.format.partedSystem <NEW_LINE> <DEDENT> self.device.disk.format.commitToDisk() <NEW_LINE> <DEDENT> self.device.format.create(intf=intf, device=self.device.path, options=self.device.formatArgs) <NEW_LINE> udev_settle() <NEW_LINE> self.device.updateSysfsPath() <NEW_LINE> info = udev_get_block_device(self.device.sysfsPath) <NEW_LINE> self.device.format.uuid = udev_device_get_uuid(info) <NEW_LINE> <DEDENT> def cancel(self): <NEW_LINE> <INDENT> self.device.format = self.origFormat <NEW_LINE> <DEDENT> def requires(self, action): <NEW_LINE> <INDENT> return ((self.device.dependsOn(action.device) and not (action.isDestroy and action.isDevice)) or (action.isDevice and (action.isCreate or action.isResize) and self.device.id == action.device.id)) <NEW_LINE> <DEDENT> def obsoletes(self, action): <NEW_LINE> <INDENT> return (self.device.id == action.device.id and self.obj == action.obj and not (action.isDestroy and action.format.exists) and self.id > action.id)
An action representing creation of a new filesystem.
62598ff24c3428357761ab58
class svn_delta_path_driver_cb_func_t: <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, svn_delta_path_driver_cb_func_t, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, svn_delta_path_driver_cb_func_t, name) <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def set_parent_pool(self, parent_pool=None): <NEW_LINE> <INDENT> import libsvn.core, weakref <NEW_LINE> self.__dict__["_parent_pool"] = parent_pool or libsvn.core.application_pool; <NEW_LINE> if self.__dict__["_parent_pool"]: <NEW_LINE> <INDENT> self.__dict__["_is_valid"] = weakref.ref( self.__dict__["_parent_pool"]._is_valid) <NEW_LINE> <DEDENT> <DEDENT> def assert_valid(self): <NEW_LINE> <INDENT> if "_is_valid" in self.__dict__: <NEW_LINE> <INDENT> assert self.__dict__["_is_valid"](), "Variable has already been deleted" <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> self.assert_valid() <NEW_LINE> value = _swig_getattr(self, self.__class__, name) <NEW_LINE> members = self.__dict__.get("_members") <NEW_LINE> if members is not None: <NEW_LINE> <INDENT> _copy_metadata_deep(value, members.get(name)) <NEW_LINE> <DEDENT> _assert_valid_deep(value) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> self.assert_valid() <NEW_LINE> self.__dict__.setdefault("_members",{})[name] = value <NEW_LINE> return _swig_setattr(self, self.__class__, name, value) <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> return svn_delta_invoke_path_driver_cb_func(self, *args)
Proxy of C svn_delta_path_driver_cb_func_t struct
62598ff226238365f5fad40f
@python_2_unicode_compatible <NEW_LINE> class Plan(StripeObject): <NEW_LINE> <INDENT> name = models.CharField(max_length=100, null=False) <NEW_LINE> currency = models.CharField( choices=CURRENCIES, max_length=10, null=False) <NEW_LINE> interval = models.CharField( max_length=10, choices=INTERVALS, verbose_name="Interval type", null=False) <NEW_LINE> interval_count = models.IntegerField( verbose_name="Intervals between charges", default=1, null=True) <NEW_LINE> amount = models.DecimalField(decimal_places=2, max_digits=7, verbose_name="Amount (per period)", null=False) <NEW_LINE> trial_period_days = models.IntegerField(null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create(cls, metadata={}, **kwargs): <NEW_LINE> <INDENT> stripe.Plan.create( id=kwargs['stripe_id'], amount=int(kwargs['amount'] * 100), currency=kwargs['currency'], interval=kwargs['interval'], interval_count=kwargs.get('interval_count', None), name=kwargs['name'], trial_period_days=kwargs.get('trial_period_days'), metadata=metadata) <NEW_LINE> plan = Plan.objects.create( stripe_id=kwargs['stripe_id'], amount=kwargs['amount'], currency=kwargs['currency'], interval=kwargs['interval'], interval_count=kwargs.get('interval_count', None), name=kwargs['name'], trial_period_days=kwargs.get('trial_period_days'), ) <NEW_LINE> return plan <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_or_create(cls, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Plan.objects.get(stripe_id=kwargs['stripe_id']), False <NEW_LINE> <DEDENT> except Plan.DoesNotExist: <NEW_LINE> <INDENT> return cls.create(**kwargs), True <NEW_LINE> <DEDENT> <DEDENT> def update_name(self): <NEW_LINE> <INDENT> p = stripe.Plan.retrieve(self.stripe_id) <NEW_LINE> p.name = self.name <NEW_LINE> p.save() <NEW_LINE> self.save() <NEW_LINE> <DEDENT> @property <NEW_LINE> def stripe_plan(self): <NEW_LINE> <INDENT> return stripe.Plan.retrieve(self.stripe_id)
A Stripe Plan.
62598ff2627d3e7fe0e07757
class BinarySensorEntity(Entity): <NEW_LINE> <INDENT> entity_description: BinarySensorEntityDescription <NEW_LINE> _attr_device_class: BinarySensorDeviceClass | str | None <NEW_LINE> _attr_is_on: bool | None = None <NEW_LINE> _attr_state: None = None <NEW_LINE> @property <NEW_LINE> def device_class(self) -> BinarySensorDeviceClass | str | None: <NEW_LINE> <INDENT> if hasattr(self, "_attr_device_class"): <NEW_LINE> <INDENT> return self._attr_device_class <NEW_LINE> <DEDENT> if hasattr(self, "entity_description"): <NEW_LINE> <INDENT> return self.entity_description.device_class <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self) -> bool | None: <NEW_LINE> <INDENT> return self._attr_is_on <NEW_LINE> <DEDENT> @final <NEW_LINE> @property <NEW_LINE> def state(self) -> StateType: <NEW_LINE> <INDENT> return STATE_ON if self.is_on else STATE_OFF
Represent a binary sensor.
62598ff2091ae356687054d0