code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class GeoLocatorException(Exception): <NEW_LINE> <INDENT> pass | Basic pysyge GeoLocator exception. | 6259905f498bea3a75a59142 |
class ChannelAttention_MLP(nn.Module): <NEW_LINE> <INDENT> def __init__(self, channel, reduction=16): <NEW_LINE> <INDENT> super(ChannelAttention_MLP, self).__init__() <NEW_LINE> self.input_size=128 <NEW_LINE> self.avg_pool = nn.Sequential( nn.AdaptiveAvgPool2d(1), ) <NEW_LINE> self.max_pool = nn.Sequential( nn.MaxPool2d() ) <NEW_LINE> self.fea_extract = nn.Sequential( nn.Conv2d(channel, channel//reduction, 3,2, padding=2, bias=True), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d( channel//reduction, channel//reduction, 3,2, padding=2, bias=True), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d( channel//reduction, channel, 3,2, padding=2, bias=True), nn.AdaptiveAvgPool2d(1), nn.Sigmoid() ) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> y = self.fea_extract(x) <NEW_LINE> return x * y | each channel's feature means different in rebuilding HR image
so by learning what features are being extracted,which feature matters most can be applied. | 6259905f1f5feb6acb164272 |
class ClearMemberFieldInformationError(ApiRequestFailed): <NEW_LINE> <INDENT> pass | An API call to clear member info from a field did not complete correctly | 6259905f63b5f9789fe867fb |
class Context(object): <NEW_LINE> <INDENT> def __init__(self, dict_=None): <NEW_LINE> <INDENT> dict_ = dict_ or {} <NEW_LINE> self.dicts = [dict_] <NEW_LINE> self.dirty = True <NEW_LINE> self.result = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self.dicts) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for d in self.dicts: <NEW_LINE> <INDENT> yield d <NEW_LINE> <DEDENT> <DEDENT> def push(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> self.dicts = [d] + self.dicts <NEW_LINE> self.dirty = True <NEW_LINE> return d <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if len(self.dicts) == 1: <NEW_LINE> <INDENT> raise ContextPopException <NEW_LINE> <DEDENT> return self.dicts.pop(0) <NEW_LINE> self.dirty = True <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.dicts[0][key] = value <NEW_LINE> self.dirty = True <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> for d in self.dicts: <NEW_LINE> <INDENT> if key in d: <NEW_LINE> <INDENT> return d[key] <NEW_LINE> <DEDENT> <DEDENT> raise KeyError(key) <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del self.dicts[0][key] <NEW_LINE> self.dirty = True <NEW_LINE> <DEDENT> def has_key(self, key): <NEW_LINE> <INDENT> for d in self.dicts: <NEW_LINE> <INDENT> if key in d: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> __contains__ = has_key <NEW_LINE> def get(self, key, otherwise=None): <NEW_LINE> <INDENT> for d in self.dicts: <NEW_LINE> <INDENT> if key in d: <NEW_LINE> <INDENT> return d[key] <NEW_LINE> <DEDENT> <DEDENT> return otherwise <NEW_LINE> <DEDENT> def update(self, other_dict): <NEW_LINE> <INDENT> if not hasattr(other_dict, '__getitem__'): <NEW_LINE> <INDENT> raise TypeError('other_dict must be a mapping (dictionary-like) object.') <NEW_LINE> <DEDENT> self.dicts[0].update(other_dict) <NEW_LINE> self.dirty = True <NEW_LINE> return other_dict <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> if not self.dirty: <NEW_LINE> <INDENT> return self.result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d = {} <NEW_LINE> for i in reversed(self.dicts): <NEW_LINE> <INDENT> d.update(i) <NEW_LINE> <DEDENT> self.result = d <NEW_LINE> self.dirty = False <NEW_LINE> <DEDENT> return d | A stack container for variable context | 6259905f7d43ff2487427f54 |
class CTRexNbar_Test(CTRexNbarBase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CTRexNbar_Test, self).__init__(*args, **kwargs) <NEW_LINE> self.unsupported_modes = ['loopback'] <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> super(CTRexNbar_Test, self).setUp() <NEW_LINE> self.router.clear_cft_counters() <NEW_LINE> self.router.clear_nbar_stats() <NEW_LINE> <DEDENT> def test_nbar_simple(self): <NEW_LINE> <INDENT> deviation_compare_value = 0.03 <NEW_LINE> if not CTRexScenario.router_cfg['no_dut_config']: <NEW_LINE> <INDENT> self.router.configure_basic_interfaces() <NEW_LINE> self.router.config_pbr(mode = "config") <NEW_LINE> self.router.config_nbar_pd() <NEW_LINE> <DEDENT> mult = self.get_benchmark_param('multiplier') <NEW_LINE> core = self.get_benchmark_param('cores') <NEW_LINE> ret = self.trex.start_trex( c = core, m = mult, p = True, nc = True, d = 100, f = 'avl/sfr_delay_10_1g.yaml', l = 1000) <NEW_LINE> trex_res = self.trex.sample_until_finish() <NEW_LINE> print("\nLATEST RESULT OBJECT:") <NEW_LINE> print(trex_res) <NEW_LINE> print("\nLATEST DUMP:") <NEW_LINE> print(trex_res.get_latest_dump()) <NEW_LINE> self.check_general_scenario_results(trex_res, check_latency = False) <NEW_LINE> self.check_CPU_benchmark(trex_res) <NEW_LINE> self.match_classification() <NEW_LINE> <DEDENT> def NBarLong(self): <NEW_LINE> <INDENT> if not CTRexScenario.router_cfg['no_dut_config']: <NEW_LINE> <INDENT> self.router.configure_basic_interfaces() <NEW_LINE> self.router.config_pbr(mode = "config") <NEW_LINE> self.router.config_nbar_pd() <NEW_LINE> <DEDENT> mult = self.get_benchmark_param('multiplier') <NEW_LINE> core = self.get_benchmark_param('cores') <NEW_LINE> ret = self.trex.start_trex( c = core, m = mult, p = True, nc = True, d = 18000, f = 'avl/sfr_delay_10_1g.yaml', l = 1000) <NEW_LINE> trex_res = self.trex.sample_until_finish() <NEW_LINE> print("\nLATEST RESULT OBJECT:") <NEW_LINE> print(trex_res) <NEW_LINE> self.check_general_scenario_results(trex_res, check_latency = False) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> CTRexGeneral_Test.tearDown(self) <NEW_LINE> pass | This class defines the NBAR testcase of the TRex traffic generator | 6259905f8e71fb1e983bd153 |
class TestBuyIncomingNumberRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testBuyIncomingNumberRequest(self): <NEW_LINE> <INDENT> pass | BuyIncomingNumberRequest unit test stubs | 6259905f8e7ae83300eea716 |
class State(object): <NEW_LINE> <INDENT> def __init__(self, opts): <NEW_LINE> <INDENT> self.opts = opts <NEW_LINE> self.player_pos = 0 <NEW_LINE> self.opponent_pos = 0 | Represents the state of a pong game | 6259905f15baa7234946361c |
class PSD_Dataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.data['pulses']) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> pulses = torch.FloatTensor(self.data['pulses'][index]) <NEW_LINE> classes = torch.tensor(self.data['class'][index]) <NEW_LINE> dataset = {'pulses': pulses, 'class': classes} <NEW_LINE> return dataset | A class to convert the input data into torch tensors
and store them in a Dataset object so that it
can be read later by torch's Dataloader function. | 6259905f7cff6e4e811b70ce |
class Login(SeleniumCommand): <NEW_LINE> <INDENT> def __init__(self, device=None, address=None, username=None, password=None, port=None, proto='https', timeout=15, ver=None, *args, **kwargs): <NEW_LINE> <INDENT> super(Login, self).__init__(*args, **kwargs) <NEW_LINE> self.timeout = timeout <NEW_LINE> self.proto = proto <NEW_LINE> self.path = '/ui/login/' <NEW_LINE> if device or not address: <NEW_LINE> <INDENT> self.device = device if isinstance(device, DeviceAccess) else ConfigInterface().get_device(device) <NEW_LINE> self.address = address or self.device.address <NEW_LINE> self.port = port or self.device.ports.get(proto, 443) <NEW_LINE> self.username = username or self.device.get_admin_creds().username <NEW_LINE> self.password = password or self.device.get_admin_creds().password <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.device = device <NEW_LINE> self.address = address <NEW_LINE> self.port = port <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> self.ver = ver <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> b = self.api <NEW_LINE> self.ifc.set_credentials(device=self.device, address=self.address, username=self.username, password=self.password, port=self.port, proto=self.proto) <NEW_LINE> if not self.ver: <NEW_LINE> <INDENT> self.ver = self.ifc.version <NEW_LINE> <DEDENT> LOG.info("Login with [{0}]...".format(self.username)) <NEW_LINE> url = "{0[proto]}://{0[address]}:{0[port]}{0[path]}".format(self.__dict__) <NEW_LINE> b.get(url) <NEW_LINE> b.refresh().wait('username', timeout=self.timeout) <NEW_LINE> e = b.find_element_by_name("username") <NEW_LINE> e.click() <NEW_LINE> e.send_keys(self.username) <NEW_LINE> e = b.find_element_by_id("passwd") <NEW_LINE> e.send_keys(self.password) <NEW_LINE> if self.ver >= 'bigiq 4.1' or self.ver < 'bigiq 4.0' or self.ver >= 'iworkflow 2.0': <NEW_LINE> <INDENT> e.submit().wait('navMenu', timeout=self.timeout) <NEW_LINE> <DEDENT> elif self.ifc.version < 'bigiq 4.1': <NEW_LINE> <INDENT> e.submit().wait('loginDiv', timeout=self.timeout) <NEW_LINE> <DEDENT> b.maximize_window() | Log in command.
@param device: The device.
@type device: str or DeviceAccess instance
@param address: The IP or hostname.
@type address: str
@param username: The username.
@type username: str
@param password: The password.
@type password: str | 6259905fd53ae8145f919aeb |
class Body1(object): <NEW_LINE> <INDENT> swagger_types = { 'file': 'str' } <NEW_LINE> attribute_map = { 'file': 'file' } <NEW_LINE> def __init__(self, file=None): <NEW_LINE> <INDENT> self._file = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.file = file <NEW_LINE> <DEDENT> @property <NEW_LINE> def file(self): <NEW_LINE> <INDENT> return self._file <NEW_LINE> <DEDENT> @file.setter <NEW_LINE> def file(self, file): <NEW_LINE> <INDENT> if file is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `file`, must not be `None`") <NEW_LINE> <DEDENT> self._file = file <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(Body1, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Body1): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259905f8e7ae83300eea717 |
class InvariantIndexable(CallByIndex): <NEW_LINE> <INDENT> __slots__ = [] <NEW_LINE> def __init__(self, v): <NEW_LINE> <INDENT> super().__init__(lambda _: v) | Objects whose indexing always gives the same constant.
This small utility is for cases where we need an indexable object whose
indexing result is actually invariant with respect to the given indices.
For an instance constructed with value ``v``, all indexing of it gives ``v``
back. | 6259905f627d3e7fe0e08514 |
class Tail(Part): <NEW_LINE> <INDENT> def __init__(self, **kwa): <NEW_LINE> <INDENT> super(Tail, self).__init__(**kwa) <NEW_LINE> <DEDENT> def pack(self): <NEW_LINE> <INDENT> self.packed = '' <NEW_LINE> if self.kind == raeting.tailKinds.nada: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return self.packed <NEW_LINE> <DEDENT> def parse(self, rest): <NEW_LINE> <INDENT> self.packed = '' <NEW_LINE> self.kind = self.packet.head.data['tk'] <NEW_LINE> if self.kind not in raeting.TAIL_KIND_NAMES: <NEW_LINE> <INDENT> self.kind = raeting.tailKinds.unknown <NEW_LINE> self.packet.error = "Unrecognizible packet tail." <NEW_LINE> return rest <NEW_LINE> <DEDENT> self.length = self.packet.head.data['tl'] <NEW_LINE> self.packed = rest[:self.length] <NEW_LINE> rest = rest[self.length:] <NEW_LINE> if self.kind == raeting.tailKinds.nada: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return rest | RAET protocol packet tail object
Manages the verification of the body portion of the packet | 6259905f16aa5153ce401b66 |
class GPGKey( Entity, EntityCreateMixin, EntityDeleteMixin, EntityReadMixin, EntitySearchMixin): <NEW_LINE> <INDENT> def __init__(self, server_config=None, **kwargs): <NEW_LINE> <INDENT> self._fields = { 'content': entity_fields.StringField(required=True), 'name': entity_fields.StringField(required=True), 'organization': entity_fields.OneToOneField( Organization, required=True, ), } <NEW_LINE> self._meta = { 'api_path': 'katello/api/v2/gpg_keys', 'server_modes': ('sat'), } <NEW_LINE> super(GPGKey, self).__init__(server_config, **kwargs) | A representation of a GPG Key entity. | 6259905fa8370b77170f1a57 |
class CLILoggingFormatter(ColoredFormatter, object): <NEW_LINE> <INDENT> LOG_COLORS = { 'SPAM': '', 'DEBUG': 'blue', 'VERBOSE': 'cyan', 'INFO': 'green', 'NOTICE': 'yellow', 'WARNING': 'red', 'ERROR': 'fg_white,bg_red', 'CRITICAL': 'purple,bold', } <NEW_LINE> def __init__(self, verbosity=logging.INFO): <NEW_LINE> <INDENT> format_string = "%(log_color)s" <NEW_LINE> datefmt = None <NEW_LINE> format_items = ["%(levelname)-7s"] <NEW_LINE> if verbosity <= logging.DEBUG: <NEW_LINE> <INDENT> format_items.append("%(asctime)s.%(msecs)d") <NEW_LINE> datefmt = "%H:%M:%S" <NEW_LINE> <DEDENT> if verbosity <= logging.INFO: <NEW_LINE> <INDENT> format_items.append("%(module)-15s") <NEW_LINE> <DEDENT> if verbosity <= logging.DEBUG: <NEW_LINE> <INDENT> format_items.append("%(lineno)4d") <NEW_LINE> <DEDENT> if verbosity <= logging.VERBOSE: <NEW_LINE> <INDENT> format_items.append("%(funcName)31s()") <NEW_LINE> <DEDENT> format_string += " : ".join(format_items) <NEW_LINE> format_string += " :%(reset)s %(message)s" <NEW_LINE> super(CLILoggingFormatter, self).__init__(format_string, datefmt=datefmt, reset=False, log_colors=self.LOG_COLORS) | Logging formatter with colorization and variable verbosity.
COT logs are formatted differently (more or less verbosely) depending
on the logging level.
.. seealso:: :class:`logging.Formatter`
Args:
verbosity (int): Logging level as defined by :mod:`logging`.
Examples::
>>> record = logging.LogRecord(
... "COT.doctests", # logger name
... logging.INFO, # message level
... "/fakemodule.py", # file reporting the message
... 22, # line number in file
... "Hello world!", # message text
... None, # %-style args for message
... None, # exception info
... "test_func") # function reporting the message
>>> record.created = 0
>>> record.msecs = 0
>>> CLILoggingFormatter(logging.NOTICE).format(record)
'\x1b[32mINFO :\x1b[0m Hello world!'
>>> CLILoggingFormatter(logging.INFO).format(record) # doctest:+ELLIPSIS
'\x1b[32mINFO : fakemodule ... Hello world!'
>>> CLILoggingFormatter(logging.VERBOSE).format(
... record) # doctest:+ELLIPSIS
'\x1b[32mINFO : fakemodule ... test_func()... Hello world!'
>>> CLILoggingFormatter(logging.DEBUG).format(record) # doctest:+ELLIPSIS
'\x1b[32mINFO ...:00.0 : fakemodule ...22...test_func()...Hello world!' | 6259905f460517430c432b97 |
class AttributeLookupTable(EntityLookupTable): <NEW_LINE> <INDENT> def __init__(self, attribute, entity_manager): <NEW_LINE> <INDENT> field = entity_module.Entity.reflect_attribute(attribute) <NEW_LINE> coerce_fn = field.typedesc.coerce <NEW_LINE> def key_func(entity): <NEW_LINE> <INDENT> return (coerce_fn(entity.get_raw(attribute)), ) <NEW_LINE> <DEDENT> super(AttributeLookupTable, self).__init__(attribute, key_func, entity_manager) | Lookup table by attribute value. | 6259905f7b25080760ed8825 |
class YcmGoToDefinition(YcmSearch): <NEW_LINE> <INDENT> searchType = 'GoToDefinition' | Plugin to find the definition of a symbol | 6259905f7d847024c075da5e |
class ColorPrint: <NEW_LINE> <INDENT> reset = "\x1b[0m" <NEW_LINE> def __init__(self, color=30, bg_color=None, style=None): <NEW_LINE> <INDENT> self.__color = "\x1b[" <NEW_LINE> if style: <NEW_LINE> <INDENT> self.__color += "%d;" % style <NEW_LINE> <DEDENT> if bg_color: <NEW_LINE> <INDENT> self.__color += "%d;" % bg_color <NEW_LINE> <DEDENT> self.__color += "%dm" % color <NEW_LINE> <DEDENT> def to_color(self, str): <NEW_LINE> <INDENT> return "%s%s%s" % (self.__color, str, ColorPrint.reset) <NEW_LINE> <DEDENT> def print_str(self, str): <NEW_LINE> <INDENT> print(self.to_color(str)) | 字体色 | 背景色 | 颜色描述
-------------------------------------------
30 | 40 | 黑色
31 | 41 | 红色
32 | 42 | 绿色
33 | 43 | 黃色
34 | 44 | 蓝色
35 | 45 | 紫红色
36 | 46 | 青蓝色
37 | 47 | 白色
-------------------------------------------
-------------------------------
显示方式 | 效果
-------------------------------
0 | 终端默认设置
1 | 高亮显示
4 | 使用下划线
5 | 闪烁
7 | 反白显示
8 | 不可见
------------------------------- | 6259905f23e79379d538db86 |
class SmallestLastNodeColoring: <NEW_LINE> <INDENT> def __init__(self, graph): <NEW_LINE> <INDENT> if graph.is_directed(): <NEW_LINE> <INDENT> raise ValueError("the graph is directed") <NEW_LINE> <DEDENT> self.graph = graph <NEW_LINE> self.color = dict((node, None) for node in self.graph.iternodes()) <NEW_LINE> for edge in self.graph.iteredges(): <NEW_LINE> <INDENT> if edge.source == edge.target: <NEW_LINE> <INDENT> raise ValueError("a loop detected") <NEW_LINE> <DEDENT> <DEDENT> self._color_list = [False] * self.graph.v() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> n = self.graph.v() <NEW_LINE> degree_dict = dict((node, self.graph.degree(node)) for node in self.graph.iternodes()) <NEW_LINE> order = list() <NEW_LINE> used = set() <NEW_LINE> bucket = list(set() for deg in xrange(n)) <NEW_LINE> for node in self.graph.iternodes(): <NEW_LINE> <INDENT> bucket[self.graph.degree(node)].add(node) <NEW_LINE> <DEDENT> for step in xrange(n): <NEW_LINE> <INDENT> for deg in xrange(n): <NEW_LINE> <INDENT> if bucket[deg]: <NEW_LINE> <INDENT> source = bucket[deg].pop() <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> order.append(source) <NEW_LINE> used.add(source) <NEW_LINE> for target in self.graph.iteradjacent(source): <NEW_LINE> <INDENT> if target in used: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> deg = degree_dict[target] <NEW_LINE> bucket[deg].remove(target) <NEW_LINE> bucket[deg-1].add(target) <NEW_LINE> degree_dict[target] = deg-1 <NEW_LINE> <DEDENT> <DEDENT> for source in reversed(order): <NEW_LINE> <INDENT> self._greedy_color(source) <NEW_LINE> <DEDENT> <DEDENT> def _greedy_color(self, source): <NEW_LINE> <INDENT> for target in self.graph.iteradjacent(source): <NEW_LINE> <INDENT> if self.color[target] is not None: <NEW_LINE> <INDENT> self._color_list[self.color[target]] = True <NEW_LINE> <DEDENT> <DEDENT> for c in xrange(self.graph.v()): <NEW_LINE> <INDENT> if not self._color_list[c]: <NEW_LINE> <INDENT> self.color[source] = c <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> for target in self.graph.iteradjacent(source): <NEW_LINE> <INDENT> if self.color[target] is not None: <NEW_LINE> <INDENT> self._color_list[self.color[target]] = False <NEW_LINE> <DEDENT> <DEDENT> return c | Find a smallest last (SL) node coloring.
Attributes
----------
graph : input undirected graph or multigraph
color : dict with nodes (values are colors)
Notes
-----
Colors are 0, 1, 2, ... | 6259905f32920d7e50bc76d0 |
class ProviderException(Exception): <NEW_LINE> <INDENT> pass | Dropbox redirected to your redirect URI with some unexpected error
identifier and error message.
The recommended action is to log the error, tell the user something went
wrong, and let them try again. | 6259905f3eb6a72ae038bcea |
class PKSampler(Sampler): <NEW_LINE> <INDENT> def __init__(self, groups, p, k): <NEW_LINE> <INDENT> self.p = p <NEW_LINE> self.k = k <NEW_LINE> self.groups = create_groups(groups, self.k) <NEW_LINE> assert len(self.groups) >= p <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for key in self.groups: <NEW_LINE> <INDENT> random.shuffle(self.groups[key]) <NEW_LINE> <DEDENT> group_samples_remaining = {} <NEW_LINE> for key in self.groups: <NEW_LINE> <INDENT> group_samples_remaining[key] = len(self.groups[key]) <NEW_LINE> <DEDENT> while len(group_samples_remaining) > self.p: <NEW_LINE> <INDENT> group_ids = list(group_samples_remaining.keys()) <NEW_LINE> selected_group_idxs = torch.multinomial(torch.ones(len(group_ids)), self.p).tolist() <NEW_LINE> for i in selected_group_idxs: <NEW_LINE> <INDENT> group_id = group_ids[i] <NEW_LINE> group = self.groups[group_id] <NEW_LINE> for _ in range(self.k): <NEW_LINE> <INDENT> sample_idx = len(group) - group_samples_remaining[group_id] <NEW_LINE> yield group[sample_idx] <NEW_LINE> group_samples_remaining[group_id] -= 1 <NEW_LINE> <DEDENT> if group_samples_remaining[group_id] < self.k: <NEW_LINE> <INDENT> group_samples_remaining.pop(group_id) | Randomly samples from a dataset while ensuring that each batch (of size p * k)
includes samples from exactly p labels, with k samples for each label.
Args:
groups (list[int]): List where the ith entry is the group_id/label of the ith sample in the dataset.
p (int): Number of labels/groups to be sampled from in a batch
k (int): Number of samples for each label/group in a batch | 6259905fbe8e80087fbc0710 |
class GatewayRouteListResult(Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[GatewayRoute]'}, } <NEW_LINE> def __init__(self, value=None): <NEW_LINE> <INDENT> super(GatewayRouteListResult, self).__init__() <NEW_LINE> self.value = value | List of virtual network gateway routes.
:param value: List of gateway routes
:type value: list[~azure.mgmt.network.v2017_11_01.models.GatewayRoute] | 6259905f76e4537e8c3f0c17 |
class Patched_CNN(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Patched_CNN, self).__init__() <NEW_LINE> self.model = Sequential() <NEW_LINE> <DEDENT> def load_model(self, filepath='model.h5', custom_objects=None, compile=True): <NEW_LINE> <INDENT> self.model = keras.models.load_model(filepath, custom_objects, compile) <NEW_LINE> <DEDENT> def save_model(self, filepath='model.h5'): <NEW_LINE> <INDENT> self.model.save(filepath) <NEW_LINE> <DEDENT> def build_model(self, channels=3, padding="valid", size=32, **kwargs): <NEW_LINE> <INDENT> self.model.add( Conv2D( 50, activation="relu", kernel_size=(3, 3), input_shape=(size, size, channels), padding=padding )) <NEW_LINE> self.model.add( Conv2D( 50, kernel_size=(3, 3), activation="relu", padding=padding ) ) <NEW_LINE> self.model.add( MaxPooling2D( pool_size=(2, 2), strides=1)) <NEW_LINE> self.model.add( Conv2D( 50, kernel_size=(3, 3), activation="relu", padding=padding ) ) <NEW_LINE> self.model.add( Conv2D( 50, kernel_size=(3, 3), activation="relu", padding=padding ) ) <NEW_LINE> self.model.add( Conv2D( 30, kernel_size=(1, 1), activation="relu", padding=padding ) ) <NEW_LINE> self.model.add( MaxPooling2D( pool_size=(2, 2), strides=1 )) <NEW_LINE> self.model.add( Conv2D( 50, kernel_size=(3, 3), activation="relu", padding=padding ) ) <NEW_LINE> self.model.add( Flatten() ) <NEW_LINE> self.model.add( Dense(size*size, activation="sigmoid") ) <NEW_LINE> self.model.compile( keras.optimizers.RMSprop(0.0001), loss=keras.losses.binary_crossentropy, metrics=["acc", "mae"] ) <NEW_LINE> <DEDENT> def train(self, image_segments, labels, batch_size=32, epochs=10, patience=2, prefix="", **kwargs): <NEW_LINE> <INDENT> self.model.fit( np.array(image_segments), np.array(labels), batch_size, epochs, validation_split=0.20, callbacks=[ EarlyStopping(patience=patience), ModelCheckpoint( "./checkpoints/"+prefix+"model.{epoch:02d}-{val_acc:.2f}.hdf5", monitor="val_acc", verbose=1, save_best_only=True) ] ) <NEW_LINE> return <NEW_LINE> <DEDENT> def test(self, image_segments=None, labels=None): <NEW_LINE> <INDENT> images = open_images("./data/SBU-Test/ShadowImages", None) <NEW_LINE> shadow_masks = open_images("./data/SBU-Test/ShadowMasks", None, True) <NEW_LINE> x = [] <NEW_LINE> y = [] <NEW_LINE> x.extend(images) <NEW_LINE> y.extend(shadow_masks) <NEW_LINE> ret = self.model.evaluate( x=np.array(x), y=np.array(y), batch_size=None, verbose=1, sample_weight=None, steps=None) <NEW_LINE> print("Evaluation loss, accuracy, mean absolute error:", ret) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def predict(self, img): <NEW_LINE> <INDENT> return self.model.predict(img) | Implementation based on the 'Patched CNN' architecture from
http://chenpingyu.org/docs/yago_eccv2016.pdf (page 9).
This implementation differs in that it accepts an arbitrary number of
channels for the input, which is defined when build_model() is called. | 6259905f91f36d47f22319d4 |
class NewPostEvent(InstanceEvent): <NEW_LINE> <INDENT> event_type = 'thread reply' <NEW_LINE> content_type = Thread <NEW_LINE> def __init__(self, reply): <NEW_LINE> <INDENT> super(NewPostEvent, self).__init__(reply.thread) <NEW_LINE> self.reply = reply <NEW_LINE> <DEDENT> def fire(self, **kwargs): <NEW_LINE> <INDENT> return EventUnion(self, NewThreadEvent(self.reply)).fire(**kwargs) <NEW_LINE> <DEDENT> def _mails(self, users_and_watches): <NEW_LINE> <INDENT> c = {'post': self.reply.content, 'author': self.reply.author.username, 'host': Site.objects.get_current().domain, 'thread_title': self.instance.title, 'post_url': self.reply.get_absolute_url()} <NEW_LINE> return emails_with_users_and_watches( _(u'Reply to: %s') % self.reply.thread.title, 'forums/email/new_post.ltxt', c, users_and_watches) | An event which fires when a thread receives a reply
Firing this also notifies watchers of the containing forum. | 6259905f0a50d4780f706904 |
class _Failed(object): <NEW_LINE> <INDENT> def __init__(self, matcher): <NEW_LINE> <INDENT> self._matcher = matcher <NEW_LINE> <DEDENT> def _got_failure(self, deferred, failure): <NEW_LINE> <INDENT> deferred.addErrback(lambda _: None) <NEW_LINE> return self._matcher.match(failure) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _got_success(deferred, success): <NEW_LINE> <INDENT> return Mismatch( _u('Failure result expected on %r, found success ' 'result (%r) instead' % (deferred, success))) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _got_no_result(deferred): <NEW_LINE> <INDENT> return Mismatch( _u('Failure result expected on %r, found no result instead' % (deferred,))) <NEW_LINE> <DEDENT> def match(self, deferred): <NEW_LINE> <INDENT> return on_deferred_result( deferred, on_success=self._got_success, on_failure=self._got_failure, on_no_result=self._got_no_result, ) | Matches a Deferred that has failed. | 6259905fd53ae8145f919aed |
class Company(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> fields = ( 'name', 'status', 'notes', 'doc_url', ) <NEW_LINE> model = models.Company | Company form. | 6259905f56ac1b37e630382c |
class TestDownload(IWebTest): <NEW_LINE> <INDENT> @pytest.fixture <NEW_LINE> def image_well_plate(self): <NEW_LINE> <INDENT> plate = PlateI() <NEW_LINE> plate.name = rstring(self.uuid()) <NEW_LINE> plate = self.update.saveAndReturnObject(plate) <NEW_LINE> well = WellI() <NEW_LINE> well.plate = plate <NEW_LINE> well = self.update.saveAndReturnObject(well) <NEW_LINE> image = self.new_image(name=self.uuid()) <NEW_LINE> ws = WellSampleI() <NEW_LINE> ws.image = image <NEW_LINE> ws.well = well <NEW_LINE> well.addWellSample(ws) <NEW_LINE> ws = self.update.saveAndReturnObject(ws) <NEW_LINE> return plate, well, ws.image <NEW_LINE> <DEDENT> def test_spw_download(self, image_well_plate): <NEW_LINE> <INDENT> plate, well, image = image_well_plate <NEW_LINE> request_url = reverse('archived_files') <NEW_LINE> data = { "image": image.id.val } <NEW_LINE> get(self.django_client, request_url, data, status_code=404) <NEW_LINE> <DEDENT> def test_orphaned_image_direct_download(self): <NEW_LINE> <INDENT> images = self.import_fake_file() <NEW_LINE> image = images[0] <NEW_LINE> request_url = reverse('archived_files', args=[image.id.val]) <NEW_LINE> get(self.django_client, request_url) <NEW_LINE> <DEDENT> def test_orphaned_image_download(self): <NEW_LINE> <INDENT> images = self.import_fake_file() <NEW_LINE> image = images[0] <NEW_LINE> request_url = reverse('archived_files') <NEW_LINE> data = { "image": image.id.val } <NEW_LINE> get(self.django_client, request_url, data) <NEW_LINE> <DEDENT> def test_image_in_dataset_download(self): <NEW_LINE> <INDENT> images = self.import_fake_file() <NEW_LINE> image = images[0] <NEW_LINE> ds = self.make_dataset() <NEW_LINE> self.link(ds, image) <NEW_LINE> request_url = reverse('archived_files') <NEW_LINE> data = { "image": image.id.val } <NEW_LINE> get(self.django_client, request_url, data) <NEW_LINE> <DEDENT> def test_image_in_dataset_in_project_download(self): <NEW_LINE> <INDENT> images = self.import_fake_file() <NEW_LINE> image = images[0] <NEW_LINE> ds = self.make_dataset() <NEW_LINE> pr = self.make_project() <NEW_LINE> self.link(pr, ds) <NEW_LINE> self.link(ds, image) <NEW_LINE> request_url = reverse('archived_files') <NEW_LINE> data = { "image": image.id.val } <NEW_LINE> get(self.django_client, request_url, data) <NEW_LINE> <DEDENT> def test_well_download(self, image_well_plate): <NEW_LINE> <INDENT> plate, well, image = image_well_plate <NEW_LINE> request_url = reverse('archived_files') <NEW_LINE> data = { "well": well.id.val } <NEW_LINE> get(self.django_client, request_url, data, status_code=404) <NEW_LINE> <DEDENT> def test_attachment_download(self): <NEW_LINE> <INDENT> images = self.import_fake_file() <NEW_LINE> image = images[0] <NEW_LINE> fa = self.make_file_annotation() <NEW_LINE> self.link(image, fa) <NEW_LINE> request_url = reverse('download_annotation', args=[fa.id.val]) <NEW_LINE> get(self.django_client, request_url) | Tests to check download is disabled where specified. | 6259905fd486a94d0ba2d653 |
class Basket: <NEW_LINE> <INDENT> def __init__(self, request): <NEW_LINE> <INDENT> self.session = request.session <NEW_LINE> basket = self.session.get("skey") <NEW_LINE> if "skey" not in request.session: <NEW_LINE> <INDENT> basket = self.session["skey"] = {} <NEW_LINE> <DEDENT> self.basket = basket <NEW_LINE> <DEDENT> def add(self, product, qty): <NEW_LINE> <INDENT> product_id = product.id <NEW_LINE> if product_id not in self.basket: <NEW_LINE> <INDENT> self.basket[product_id] = { "price": str(product.price), "qty": int(qty) } <NEW_LINE> <DEDENT> self.session.modified = True <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> product_ids = self.basket.keys() <NEW_LINE> products = Product.products.filter(id__in=product_ids) <NEW_LINE> basket = self.basket.copy() <NEW_LINE> for product in products: <NEW_LINE> <INDENT> basket[str(product.id)]["product"] = product <NEW_LINE> <DEDENT> for item in basket.values(): <NEW_LINE> <INDENT> item["price"] = Decimal(item["price"]) <NEW_LINE> item["total_price"] = item["price"] * item["qty"] <NEW_LINE> yield item <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return sum(item["qty"] for item in self.basket.values()) <NEW_LINE> <DEDENT> def get_total_price(self): <NEW_LINE> <INDENT> return sum(Decimal(item["price"]) * item["qty"] for item in self.basket.values()) | A base Basket class, providing some default behaviors that can be inherited
or overridden as necessary. | 6259905f45492302aabfdb65 |
class ReadView(BreadViewMixin, DetailView): <NEW_LINE> <INDENT> perm_name = "view" <NEW_LINE> template_name_suffix = "_read" <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> data = super(ReadView, self).get_context_data(**kwargs) <NEW_LINE> data["form"] = self.get_form(instance=self.object) <NEW_LINE> return data | The read view makes a form, not because we're going to submit
changes, but just as a handy container for the object's data that
we can iterate over in the template to display it if we don't want
to make a custom template for this model. | 6259905fd7e4931a7ef3d6ca |
class ConnectionLevel: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> READ_ONLY = "ro" <NEW_LINE> UPDATE = "update" <NEW_LINE> ADMIN = "admin" | Connection level. | 6259905f8a43f66fc4bf381a |
class Connector: <NEW_LINE> <INDENT> def read_item(self, from_date=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def read_block(self, size, from_date=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def write(self, items): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def latest_date(self): <NEW_LINE> <INDENT> raise NotImplementedError | Abstract class for reading and writing items.
This class provides methods for reading and writing items from/to a
given data source. | 6259905fadb09d7d5dc0bbf6 |
class Viewable(MetaHasProps): <NEW_LINE> <INDENT> model_class_reverse_map = {} <NEW_LINE> def __new__(cls, class_name, bases, class_dict): <NEW_LINE> <INDENT> if "__view_model__" not in class_dict: <NEW_LINE> <INDENT> class_dict["__view_model__"] = class_name <NEW_LINE> <DEDENT> class_dict["get_class"] = Viewable.get_class <NEW_LINE> newcls = super(Viewable,cls).__new__(cls, class_name, bases, class_dict) <NEW_LINE> entry = class_dict["__view_model__"] <NEW_LINE> if entry in Viewable.model_class_reverse_map: <NEW_LINE> <INDENT> raise Warning("Duplicate __view_model__ declaration of '%s' for " "class %s. Previous definition: %s" % (entry, class_name, Viewable.model_class_reverse_map[entry])) <NEW_LINE> <DEDENT> Viewable.model_class_reverse_map[entry] = newcls <NEW_LINE> return newcls <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _preload_models(cls): <NEW_LINE> <INDENT> from . import objects, widgets <NEW_LINE> from .crossfilter import objects <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_class(cls, view_model_name): <NEW_LINE> <INDENT> cls._preload_models() <NEW_LINE> d = Viewable.model_class_reverse_map <NEW_LINE> if view_model_name in d: <NEW_LINE> <INDENT> return d[view_model_name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("View model name '%s' not found" % view_model_name) | Any plot object (Data Model) which has its own View Model in the
persistence layer.
One thing to keep in mind is that a Viewable should have a single
unique representation in the persistence layer, but it might have
multiple concurrent client-side Views looking at it. Those may
be from different machines altogether. | 6259905f379a373c97d9a6b0 |
@dataclass <NEW_LINE> class CoskewArrays: <NEW_LINE> <INDENT> diagonal: np.ndarray <NEW_LINE> semi_diagonal: np.ndarray <NEW_LINE> off_diagonal: np.ndarray | Object to store measured coskew data. | 6259905f7d43ff2487427f56 |
class scaleH(): <NEW_LINE> <INDENT> def __init__(self,planet,species,state): <NEW_LINE> <INDENT> iplanet = np.where(PPdat['body'] == planet)[0] <NEW_LINE> ispecies = np.where(SPdat['species'] == species)[0] <NEW_LINE> self.g = PPdat['g'][iplanet] <NEW_LINE> self.Rv = SPdat['Rv'][ispecies] <NEW_LINE> iTc = np.where((PIdic[planet]['species'] == species) & (PIdic[planet]['state'] == state)) <NEW_LINE> self.Tc = PIdic[planet]['Tc'][iTc] <NEW_LINE> self.L = SPdat['L0'][ispecies] <NEW_LINE> self.Cp = PPdat['Cp'][iplanet] <NEW_LINE> self.Rs = PPdat['Rstar'][iplanet] <NEW_LINE> <DEDENT> def Hc(self): <NEW_LINE> <INDENT> return round(self.Rv * self.Tc**2 * self.Cp / self.g / self.L , 4) <NEW_LINE> <DEDENT> def H(self): <NEW_LINE> <INDENT> return round(self.Rs * self.Tc / self.g, 4) | Load all paramaters for a certain planet and a particular species that will condense in solid or liquid form, and calculate cloud scale height, Hc, and atm scale height, H | 6259905f9c8ee82313040cd0 |
class Ems: <NEW_LINE> <INDENT> def __init__(self, url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> <DEDENT> def conf_radio(self, emsd): <NEW_LINE> <INDENT> ems_url = self.url <NEW_LINE> api_prefix = "" <NEW_LINE> url = ems_url + api_prefix <NEW_LINE> headers = {"Content-Type": "application/json", "Accept": "application/json"} <NEW_LINE> data = emsd <NEW_LINE> r = None <NEW_LINE> try: <NEW_LINE> <INDENT> r = requests.post(url, json=json.loads(json.dumps(data)), timeout=360, headers=headers) <NEW_LINE> logger.info(r.json()) <NEW_LINE> r.raise_for_status() <NEW_LINE> <DEDENT> except requests.exceptions.HTTPError as errh: <NEW_LINE> <INDENT> logger.exception("Http Error:", errh) <NEW_LINE> <DEDENT> except requests.exceptions.ConnectionError as errc: <NEW_LINE> <INDENT> logger.exception("Error Connecting:", errc) <NEW_LINE> <DEDENT> except requests.exceptions.Timeout as errt: <NEW_LINE> <INDENT> logger.exception("Timeout Error:", errt) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException as err: <NEW_LINE> <INDENT> logger.exception("Error:", err) <NEW_LINE> <DEDENT> <DEDENT> def del_slice(self, emsd): <NEW_LINE> <INDENT> logger.info("Deleting Radio Slice Configuration") | Class implementing the communication API with EMS | 6259905f1f037a2d8b9e53b1 |
class LinearLayer(Layer): <NEW_LINE> <INDENT> def __init__(self, n_in, n_out, seed=0): <NEW_LINE> <INDENT> super(LinearLayer, self).__init__(n_in=n_in, n_out=n_out) <NEW_LINE> np.random.seed(seed) <NEW_LINE> self.weights = np.random.normal(0.0, n_in ** -0.5, (n_in, n_out)) <NEW_LINE> self.dloss_dweights = None <NEW_LINE> <DEDENT> def forward_pass(self): <NEW_LINE> <INDENT> self.output = np.dot(self.input, self.weights) <NEW_LINE> <DEDENT> def backward_pass(self): <NEW_LINE> <INDENT> self.dloss_din = np.dot(self.dloss_dout, self.weights.T) <NEW_LINE> <DEDENT> def calc_param_grads(self): <NEW_LINE> <INDENT> self.dloss_dweights = np.dot(self.input.T, self.dloss_dout) <NEW_LINE> <DEDENT> def update_params(self, learning_rate): <NEW_LINE> <INDENT> self.weights -= self.dloss_dweights * learning_rate | A linear layer for a neural network. | 6259905f0c0af96317c578a5 |
class ShowUsedTextures(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.usedtextures" <NEW_LINE> bl_label = "" <NEW_LINE> isGroup: bpy.props.BoolProperty() <NEW_LINE> Index: bpy.props.IntProperty() <NEW_LINE> LODIndex: bpy.props.IntProperty() <NEW_LINE> BlockIndex: bpy.props.IntProperty() <NEW_LINE> def execute(self,context): <NEW_LINE> <INDENT> if self.isGroup: <NEW_LINE> <INDENT> mat = asset.LODGroups[self.Index].LODList[self.LODIndex].materialBlockList[self.BlockIndex] <NEW_LINE> mat.ui_ShowTextures = not mat.ui_ShowTextures <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mat = asset.LODObjects[self.Index].LODList[self.LODIndex].materialBlockList[self.BlockIndex] <NEW_LINE> mat.ui_ShowTextures = not mat.ui_ShowTextures <NEW_LINE> <DEDENT> return {'FINISHED'} | Show used texture paths for the mesh block | 6259905f8da39b475be04874 |
class Operations(object): <NEW_LINE> <INDENT> models = models <NEW_LINE> def __init__(self, client, config, serializer, deserializer): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self.api_version = "2018-01-01" <NEW_LINE> self.config = config <NEW_LINE> <DEDENT> def list( self, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = self.list.metadata['url'] <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = next_link <NEW_LINE> query_parameters = {} <NEW_LINE> <DEDENT> header_parameters = {} <NEW_LINE> header_parameters['Content-Type'] = 'application/json; charset=utf-8' <NEW_LINE> if self.config.generate_client_request_id: <NEW_LINE> <INDENT> header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) <NEW_LINE> <DEDENT> if custom_headers: <NEW_LINE> <INDENT> header_parameters.update(custom_headers) <NEW_LINE> <DEDENT> if self.config.accept_language is not None: <NEW_LINE> <INDENT> header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') <NEW_LINE> <DEDENT> request = self._client.get(url, query_parameters) <NEW_LINE> response = self._client.send( request, header_parameters, stream=False, **operation_config) <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> exp = CloudError(response) <NEW_LINE> exp.request_id = response.headers.get('x-ms-request-id') <NEW_LINE> raise exp <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> deserialized = models.OperationPaged(internal_paging, self._deserialize.dependencies) <NEW_LINE> if raw: <NEW_LINE> <INDENT> header_dict = {} <NEW_LINE> client_raw_response = models.OperationPaged(internal_paging, self._deserialize.dependencies, header_dict) <NEW_LINE> return client_raw_response <NEW_LINE> <DEDENT> return deserialized <NEW_LINE> <DEDENT> list.metadata = {'url': '/providers/Microsoft.Network/operations'} | Operations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: Client API version. Constant value: "2018-01-01". | 6259905ff548e778e596cc15 |
class Bucketlist(BaseModel): <NEW_LINE> <INDENT> created_by = models.ForeignKey(User) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'BucketList : {}'.format(self.name) | A model of the bucketlist table | 6259905fe76e3b2f99fda08c |
class RTester(RPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/gastonstat/tester" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/tester_0.1.7.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/tester" <NEW_LINE> version('0.1.7', sha256='b9c645119c21c69450f3d366c911ed92ac7c14ef61652fd676a38fb9d420b5f4') <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) | tester allows you to test characteristics of common R objects. | 6259905f01c39578d7f1427b |
class CurveMetrics(BinaryClassificationMetrics): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> super(CurveMetrics, self).__init__(*args) <NEW_LINE> <DEDENT> def _to_list(self, rdd): <NEW_LINE> <INDENT> points = [] <NEW_LINE> for row in rdd.collect(): <NEW_LINE> <INDENT> points += [(float(row._1()), float(row._2()))] <NEW_LINE> <DEDENT> return points <NEW_LINE> <DEDENT> def get_curve(self, method): <NEW_LINE> <INDENT> rdd = getattr(self._java_model, method)().toJavaRDD() <NEW_LINE> return self._to_list(rdd) | Scala version implements .roc() and .pr()
Python: https://spark.apache.org/docs/latest/api/python/_modules/pyspark/mllib/common.html
Scala: https://spark.apache.org/docs/latest/api/java/org/apache/spark/mllib/evaluation/BinaryClassificationMetrics.html
See: https://stackoverflow.com/a/57342431/1646932 | 6259905f2c8b7c6e89bd4e7c |
class ResourcePointer(obj.Pointer): <NEW_LINE> <INDENT> resource_base = 0 <NEW_LINE> def __init__(self, resource_base=None, **kwargs): <NEW_LINE> <INDENT> super(ResourcePointer, self).__init__(**kwargs) <NEW_LINE> self.resource_base = (resource_base or self.obj_context.get("resource_base")) <NEW_LINE> if self.resource_base is None: <NEW_LINE> <INDENT> for parent in self.parents: <NEW_LINE> <INDENT> if isinstance(parent, _IMAGE_NT_HEADERS): <NEW_LINE> <INDENT> for section in parent.Sections: <NEW_LINE> <INDENT> if section.Name.startswith(b".rsrc"): <NEW_LINE> <INDENT> self.resource_base = ( section.VirtualAddress + parent.OptionalHeader.ImageBase) <NEW_LINE> self.obj_context[ 'resource_base'] = self.resource_base <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def v(self, vm=None): <NEW_LINE> <INDENT> resource_pointer = int( super(ResourcePointer, self).v()) & ((1 << 31) - 1) <NEW_LINE> if resource_pointer: <NEW_LINE> <INDENT> resource_pointer += self.resource_base <NEW_LINE> <DEDENT> return resource_pointer | A pointer relative to our resource section. | 6259905fdd821e528d6da4c7 |
class DisplacementOperator(Operator): <NEW_LINE> <INDENT> def __init__(self, par_space, control_points, discr_space, ft_kernel): <NEW_LINE> <INDENT> if par_space.size != discr_space.ndim: <NEW_LINE> <INDENT> raise ValueError('dimensions of product space and image grid space' ' do not match ({} != {})' ''.format(par_space.size, discr_space.ndim)) <NEW_LINE> <DEDENT> self.discr_space = discr_space <NEW_LINE> self.range_space = ProductSpace(self.discr_space, self.discr_space.ndim) <NEW_LINE> super().__init__(par_space, self.range_space, linear=True) <NEW_LINE> self.ft_kernel = ft_kernel <NEW_LINE> if not isinstance(control_points, RectGrid): <NEW_LINE> <INDENT> self._control_pts = np.asarray(control_points) <NEW_LINE> if self._control_pts.shape != (self.num_contr_pts, self.ndim): <NEW_LINE> <INDENT> raise ValueError( 'expected control point array of shape {}, got {}.' ''.format((self.num_contr_pts, self.ndim), self.control_points.shape)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._control_pts = control_points <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def ndim(self): <NEW_LINE> <INDENT> return self.domain.ndim <NEW_LINE> <DEDENT> @property <NEW_LINE> def contr_pts_is_grid(self): <NEW_LINE> <INDENT> return isinstance(self.control_points, RectGrid) <NEW_LINE> <DEDENT> @property <NEW_LINE> def control_points(self): <NEW_LINE> <INDENT> return self._control_pts <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_contr_pts(self): <NEW_LINE> <INDENT> if self.contr_pts_is_grid: <NEW_LINE> <INDENT> return self.control_points.size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return len(self.control_points) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def image_grid(self): <NEW_LINE> <INDENT> return self.discr_space.grid <NEW_LINE> <DEDENT> def displacement_ft(self, alphas): <NEW_LINE> <INDENT> temp_op = vectorial_ft_shape_op(alphas.space[0]) <NEW_LINE> ft_momenta = temp_op(alphas) <NEW_LINE> ft_displacement = self.ft_kernel * ft_momenta <NEW_LINE> return temp_op.inverse(ft_displacement) <NEW_LINE> <DEDENT> def _call(self, alphas): <NEW_LINE> <INDENT> return self.displacement_ft(alphas) <NEW_LINE> <DEDENT> def derivative(self, alphas): <NEW_LINE> <INDENT> deriv_op = DisplacementDerivative( alphas, self.control_points, self.discr_space, self.ft_kernel) <NEW_LINE> return deriv_op | Operator mapping parameters to an inverse displacement.
This operator computes for the momenta::
alpha --> D(alpha)
where
D(alpha) = v.
The vector field ``v`` depends on the deformation parameters
``alpha_j`` as follows::
v(y) = sum_j (K(y, y_j) * alpha_j)
Here, ``K`` is the RKHS kernel matrix and each ``alpha_j`` is an
element of ``R^n``, can be seen as the momenta alpha at control point y_j. | 6259905f56ac1b37e630382d |
class I18NTextWidget(I18NWidget, text.TextWidget): <NEW_LINE> <INDENT> implementsOnly(II18NTextWidget) <NEW_LINE> default_widget = text.TextWidget <NEW_LINE> maxlength = I18NWidgetProperty('maxlength') <NEW_LINE> size = I18NWidgetProperty('size') <NEW_LINE> def updateWidget(self, widget, language): <NEW_LINE> <INDENT> super(I18NTextWidget, self).updateWidget(widget, language) <NEW_LINE> widget.maxlength = widget.field.max_length | I18N text input type implementation. | 6259905f3539df3088ecd929 |
class Piece(object): <NEW_LINE> <INDENT> def __init__(self, image, index): <NEW_LINE> <INDENT> self.image = image[:] <NEW_LINE> self.id = index <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return self.image.__getitem__(index) <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self.image.shape[0] <NEW_LINE> <DEDENT> def shape(self): <NEW_LINE> <INDENT> return self.image.shape | Represents single jigsaw puzzle piece.
Each piece has identifier so it can be
tracked across different individuals
:param image: ndarray representing piece's RGB values
:param index: Unique id withing piece's parent image
Usage::
>>> from gaps.piece import Piece
>>> piece = Piece(image[:28, :28, :], 42) | 6259905fa219f33f346c7e93 |
class FluxFactory(object): <NEW_LINE> <INDENT> latest = "0.26.0" <NEW_LINE> def _iter_flux(): <NEW_LINE> <INDENT> loader = pkgutil.get_loader('maestrowf.interfaces.script._flux') <NEW_LINE> mods = [(name, ispkg) for finder, name, ispkg in pkgutil.iter_modules( loader.load_module('maestrowf.interfaces.script._flux').__path__, loader.load_module( 'maestrowf.interfaces.script._flux').__name__ + "." ) ] <NEW_LINE> cs = [] <NEW_LINE> for name, _ in mods: <NEW_LINE> <INDENT> m = pkgutil.get_loader(name).load_module(name) <NEW_LINE> for n, cls in m.__dict__.items(): <NEW_LINE> <INDENT> if isinstance(cls, type) and issubclass(cls, FluxInterface) and not inspect.isabstract(cls): <NEW_LINE> <INDENT> cs.append(cls) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return cs <NEW_LINE> <DEDENT> factories = { interface.key: interface for interface in _iter_flux() } <NEW_LINE> @classmethod <NEW_LINE> def get_interface(cls, interface_id): <NEW_LINE> <INDENT> if interface_id.lower() not in cls.factories: <NEW_LINE> <INDENT> msg = "Interface '{0}' not found. Specify a supported version " "of Flux or implement a new one mapping to the '{0}'" .format(str(interface_id)) <NEW_LINE> LOGGER.error(msg) <NEW_LINE> raise Exception(msg) <NEW_LINE> <DEDENT> return cls.factories[interface_id] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_valid_interfaces(cls): <NEW_LINE> <INDENT> return cls.factories.keys() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_latest_interface(cls): <NEW_LINE> <INDENT> return cls.factories[cls.latest] | A factory for swapping out Flux's backend interface based on version. | 6259905fa8370b77170f1a5b |
class ValueInSetValidator(object): <NEW_LINE> <INDENT> def __init__(self, valid_values, nullable=False): <NEW_LINE> <INDENT> self.valid_values = valid_values <NEW_LINE> self.nullable = nullable <NEW_LINE> <DEDENT> def __call__(self, value): <NEW_LINE> <INDENT> if self.nullable and not value: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if value not in self.valid_values: <NEW_LINE> <INDENT> raise ValidationError("Invalid value: %s. Expected one of: %s"%(value, ", ".join(map(str, self.valid_values)))) | Validates that a value is within a set of possible values.
The optional 'nullable' flag determines whether or not the value
may also be empty. | 6259905f6e29344779b01cdc |
class ATabController(QTabWidget): <NEW_LINE> <INDENT> def __init__(self, tabSettings, parent=None): <NEW_LINE> <INDENT> super(ATabController, self).__init__(parent) <NEW_LINE> self._configureTabs(tabSettings) <NEW_LINE> self.setTabPosition(QTabWidget.South) <NEW_LINE> <DEDENT> def _configureTabs(self, settings): <NEW_LINE> <INDENT> for tab in settings: <NEW_LINE> <INDENT> self.addTab(tab[0], tab[1]) <NEW_LINE> self.setTabIcon(tab[2], QIcon(tab[3])) <NEW_LINE> <DEDENT> self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) <NEW_LINE> <DEDENT> def _onTabChange(self, idx): <NEW_LINE> <INDENT> if idx == 0: <NEW_LINE> <INDENT> self.parent().setWindowTitle('Python Console') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.parent().setWindowTitle('Output Console') <NEW_LINE> <DEDENT> <DEDENT> def sizeHint(self): <NEW_LINE> <INDENT> screenHeight = QApplication.desktop().screenGeometry().height() <NEW_LINE> return QSize(self.width(), int(screenHeight / 3.5)) | Main representation of a tab widget. Constructor expects
an iterable with 4-tuple items containing (widget, text, idx icon name). | 6259905f435de62698e9d493 |
class ComparisonCondition(Condition): <NEW_LINE> <INDENT> _segment = Segment.WHERE <NEW_LINE> def __init__(self, operator: str, field_or_name: Union[field.Field, str], value: Any): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.operator = operator <NEW_LINE> self.value = value <NEW_LINE> if isinstance(field_or_name, field.Field): <NEW_LINE> <INDENT> self.column = field_or_name.name <NEW_LINE> self.field = field_or_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.column = field_or_name <NEW_LINE> self.field = None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _column_key(self) -> str: <NEW_LINE> <INDENT> return self.key(self.column) <NEW_LINE> <DEDENT> def _params(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> return {self._column_key: self.value} <NEW_LINE> <DEDENT> def segment(self) -> Segment: <NEW_LINE> <INDENT> return Segment.WHERE <NEW_LINE> <DEDENT> def _sql(self) -> str: <NEW_LINE> <INDENT> return '{alias}.{column} {operator} @{column_key}'.format( alias=self.model_class.column_prefix, column=self.column, operator=self.operator, column_key=self._column_key) <NEW_LINE> <DEDENT> def _types(self) -> spanner_v1.Type: <NEW_LINE> <INDENT> return {self._column_key: self.model_class.fields[self.column].grpc_type()} <NEW_LINE> <DEDENT> def _validate(self, model_class: Type[Any]) -> None: <NEW_LINE> <INDENT> if self.column not in model_class.fields: <NEW_LINE> <INDENT> raise error.ValidationError('{} is not a column on {}'.format( self.column, model_class.table)) <NEW_LINE> <DEDENT> if self.field and self.field != model_class.fields[self.column]: <NEW_LINE> <INDENT> raise error.ValidationError('{} does not belong to {}'.format( self.column, model_class.table)) <NEW_LINE> <DEDENT> if self.value is None: <NEW_LINE> <INDENT> raise error.ValidationError('{} does not support NULL'.format( self.__name__)) <NEW_LINE> <DEDENT> model_class.fields[self.column].validate(self.value) | Used to specify a comparison between a column and a value in the WHERE. | 6259905f435de62698e9d494 |
class ShellInjectionTimingCheck(_TimingCheck): <NEW_LINE> <INDENT> key = "shell.timing.sleep" <NEW_LINE> name = "Shell Injection Timing" <NEW_LINE> description = "checks for shell injection by executing delays" <NEW_LINE> example = "; sleep 9 #" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._payloads = [ ('; sleep 9 #', 9.00), ('| sleep 9 #', 9.00), ('&& sleep 9 #', 9.00), ('|| sleep 9 #', 9.00), ("' ; sleep 9 #", 9.00), ("' | sleep 9 #", 9.00), ("' && sleep 9 #", 9.00), ("' || sleep 9 #", 9.00), ('" ; sleep 9 #', 9.00), ('" | sleep 9 #', 9.00), ('" && sleep 9 #', 9.00), ('" || sleep 9 #', 9.00), ('`sleep 9`', 9.00), ('$(sleep 9)', 9.00) ] | Checks for Shell Injection by executing the 'sleep' command. The payload uses shell separators to inject 'sleep',
such as ;, &&, ||,
, and backticks.
| 6259905f7b25080760ed8827 |
class ReverseProxiedConfig(object): <NEW_LINE> <INDENT> def __init__(self, trusted_proxy_headers: List[str] = None, http_host: str = None, remote_addr: str = None, script_name: str = None, server_name: str = None, server_port: int = None, url_scheme: str = None, rewrite_path_info: bool = False) -> None: <NEW_LINE> <INDENT> self.trusted_proxy_headers = [] <NEW_LINE> if trusted_proxy_headers: <NEW_LINE> <INDENT> for x in trusted_proxy_headers: <NEW_LINE> <INDENT> h = x.upper() <NEW_LINE> if h in ReverseProxiedMiddleware.ALL_CANDIDATES: <NEW_LINE> <INDENT> self.trusted_proxy_headers.append(h) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.http_host = http_host <NEW_LINE> self.remote_addr = remote_addr <NEW_LINE> self.script_name = script_name.rstrip("/") if script_name else "" <NEW_LINE> self.server_name = server_name <NEW_LINE> self.server_port = str(server_port) if server_port is not None else "" <NEW_LINE> self.url_scheme = url_scheme.lower() if url_scheme else "" <NEW_LINE> self.rewrite_path_info = rewrite_path_info <NEW_LINE> <DEDENT> def necessary(self) -> bool: <NEW_LINE> <INDENT> return any([ self.trusted_proxy_headers, self.http_host, self.remote_addr, self.script_name, self.server_name, self.server_port, self.url_scheme, self.rewrite_path_info, ]) | Class to hold information about a reverse proxy configuration. | 6259905fd7e4931a7ef3d6cb |
class DevelopmentConfig(Config): <NEW_LINE> <INDENT> DEBUG = True <NEW_LINE> SQLALCHEMY_ECHO = True <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> SERVER_NAME = 'localhost:6286' | Development configurations | 6259905fac7a0e7691f73b71 |
class InvalidUsePartnerOstypeSettingInfo(NetAppObject): <NEW_LINE> <INDENT> _initiator_group_os_type = None <NEW_LINE> @property <NEW_LINE> def initiator_group_os_type(self): <NEW_LINE> <INDENT> return self._initiator_group_os_type <NEW_LINE> <DEDENT> @initiator_group_os_type.setter <NEW_LINE> def initiator_group_os_type(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('initiator_group_os_type', val) <NEW_LINE> <DEDENT> self._initiator_group_os_type = val <NEW_LINE> <DEDENT> _initiator_group_name = None <NEW_LINE> @property <NEW_LINE> def initiator_group_name(self): <NEW_LINE> <INDENT> return self._initiator_group_name <NEW_LINE> <DEDENT> @initiator_group_name.setter <NEW_LINE> def initiator_group_name(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('initiator_group_name', val) <NEW_LINE> <DEDENT> self._initiator_group_name = val <NEW_LINE> <DEDENT> _is_use_partner_enabled = None <NEW_LINE> @property <NEW_LINE> def is_use_partner_enabled(self): <NEW_LINE> <INDENT> return self._is_use_partner_enabled <NEW_LINE> <DEDENT> @is_use_partner_enabled.setter <NEW_LINE> def is_use_partner_enabled(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('is_use_partner_enabled', val) <NEW_LINE> <DEDENT> self._is_use_partner_enabled = val <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "invalid-use-partner-ostype-setting-info" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_desired_attrs(): <NEW_LINE> <INDENT> return [ 'initiator-group-os-type', 'initiator-group-name', 'is-use-partner-enabled', ] <NEW_LINE> <DEDENT> def describe_properties(self): <NEW_LINE> <INDENT> return { 'initiator_group_os_type': { 'class': basestring, 'is_list': False, 'required': 'required' }, 'initiator_group_name': { 'class': basestring, 'is_list': False, 'required': 'required' }, 'is_use_partner_enabled': { 'class': bool, 'is_list': False, 'required': 'required' }, } | Information about an invalid initiator group ostype and
use_partner combination | 6259905f3cc13d1c6d466dcf |
class TestPoFileHeaders(FormatsBaseTestCase): <NEW_LINE> <INDENT> def _load_pot(self): <NEW_LINE> <INDENT> test_file = os.path.join(TEST_FILES_PATH, 'test.pot') <NEW_LINE> self.resource.entities.all().delete() <NEW_LINE> handler = POHandler(test_file) <NEW_LINE> handler.bind_resource(self.resource) <NEW_LINE> handler.set_language(self.resource.source_language) <NEW_LINE> handler.parse_file(is_source=True) <NEW_LINE> handler.save2db(is_source=True) <NEW_LINE> return handler <NEW_LINE> <DEDENT> def test_poheader_team_url(self): <NEW_LINE> <INDENT> self.assertFalse(self.team.mainlist) <NEW_LINE> handler = self._load_pot() <NEW_LINE> handler.set_language(self.language) <NEW_LINE> handler.compile() <NEW_LINE> pofile = handler.compiled_template <NEW_LINE> self.assertTrue("Portuguese (Brazilian)" in pofile) <NEW_LINE> self.assertTrue(self.urls['team'] in pofile) <NEW_LINE> <DEDENT> def test_poheader_team_email(self): <NEW_LINE> <INDENT> self.team.mainlist = "[email protected]" <NEW_LINE> self.team.save() <NEW_LINE> handler = self._load_pot() <NEW_LINE> handler.set_language(self.language) <NEW_LINE> handler.compile() <NEW_LINE> pofile = handler.compiled_template <NEW_LINE> self.assertTrue("Portuguese (Brazilian)" in pofile) <NEW_LINE> self.assertFalse(self.urls['team'] in pofile) <NEW_LINE> self.assertTrue(self.team.mainlist in pofile) | Test PO File library support for PO file headers. | 6259905f498bea3a75a59145 |
class Models(DatasetModels, collections.abc.MutableSequence): <NEW_LINE> <INDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del self._models[self.index(key)] <NEW_LINE> <DEDENT> def __setitem__(self, key, model): <NEW_LINE> <INDENT> from gammapy.modeling.models import FoVBackgroundModel, SkyModel <NEW_LINE> if isinstance(model, (SkyModel, FoVBackgroundModel)): <NEW_LINE> <INDENT> self._models[self.index(key)] = model <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError(f"Invalid type: {model!r}") <NEW_LINE> <DEDENT> <DEDENT> def insert(self, idx, model): <NEW_LINE> <INDENT> if model.name in self.names: <NEW_LINE> <INDENT> raise (ValueError("Model names must be unique")) <NEW_LINE> <DEDENT> self._models.insert(idx, model) | Sky model collection.
Parameters
----------
models : `SkyModel`, list of `SkyModel` or `Models`
Sky models | 6259905f7d847024c075da61 |
@HEADS.register_module <NEW_LINE> class FusedSemanticHead(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_ins, fusion_level, num_convs=4, in_channels=256, conv_out_channels=256, num_classes=183, ignore_label=255, loss_weight=0.2, conv_cfg=None, norm_cfg=None): <NEW_LINE> <INDENT> super(FusedSemanticHead, self).__init__() <NEW_LINE> self.num_ins = num_ins <NEW_LINE> self.fusion_level = fusion_level <NEW_LINE> self.num_convs = num_convs <NEW_LINE> self.in_channels = in_channels <NEW_LINE> self.conv_out_channels = conv_out_channels <NEW_LINE> self.num_classes = num_classes <NEW_LINE> self.ignore_label = ignore_label <NEW_LINE> self.loss_weight = loss_weight <NEW_LINE> self.conv_cfg = conv_cfg <NEW_LINE> self.norm_cfg = norm_cfg <NEW_LINE> self.fp16_enabled = False <NEW_LINE> self.lateral_convs = nn.ModuleList() <NEW_LINE> for i in range(self.num_ins): <NEW_LINE> <INDENT> self.lateral_convs.append( ConvModule( self.in_channels, self.in_channels, 1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, inplace=False)) <NEW_LINE> <DEDENT> self.convs = nn.ModuleList() <NEW_LINE> for i in range(self.num_convs): <NEW_LINE> <INDENT> in_channels = self.in_channels if i == 0 else conv_out_channels <NEW_LINE> self.convs.append( ConvModule( in_channels, conv_out_channels, 3, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg)) <NEW_LINE> <DEDENT> self.conv_embedding = ConvModule( conv_out_channels, conv_out_channels, 1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg) <NEW_LINE> self.conv_logits = nn.Conv2d(conv_out_channels, self.num_classes, 1) <NEW_LINE> self.criterion = nn.CrossEntropyLoss(ignore_index=ignore_label) <NEW_LINE> <DEDENT> def init_weights(self): <NEW_LINE> <INDENT> kaiming_init(self.conv_logits) <NEW_LINE> <DEDENT> @auto_fp16() <NEW_LINE> def forward(self, feats): <NEW_LINE> <INDENT> x = self.lateral_convs[self.fusion_level](feats[self.fusion_level]) <NEW_LINE> fused_size = tuple(x.shape[-2:]) <NEW_LINE> for i, feat in enumerate(feats): <NEW_LINE> <INDENT> if i != self.fusion_level: <NEW_LINE> <INDENT> feat = F.interpolate( feat, size=fused_size, mode='bilinear', align_corners=True) <NEW_LINE> x += self.lateral_convs[i](feat) <NEW_LINE> <DEDENT> <DEDENT> for i in range(self.num_convs): <NEW_LINE> <INDENT> x = self.convs[i](x) <NEW_LINE> <DEDENT> mask_pred = self.conv_logits(x) <NEW_LINE> x = self.conv_embedding(x) <NEW_LINE> return mask_pred, x <NEW_LINE> <DEDENT> @force_fp32(apply_to=('mask_pred', )) <NEW_LINE> def loss(self, mask_pred, labels): <NEW_LINE> <INDENT> labels = labels.squeeze(1).long() <NEW_LINE> loss_semantic_seg = self.criterion(mask_pred, labels) <NEW_LINE> loss_semantic_seg *= self.loss_weight <NEW_LINE> return loss_semantic_seg | Multi-level fused semantic segmentation head.
in_1 -> 1x1 conv ---
|
in_2 -> 1x1 conv -- |
||
in_3 -> 1x1 conv - ||
||| /-> 1x1 conv (mask prediction)
in_4 -> 1x1 conv -----> 3x3 convs (*4)
| \-> 1x1 conv (feature)
in_5 -> 1x1 conv --- | 6259905f7d847024c075da62 |
class Datasets: <NEW_LINE> <INDENT> train: LetterData <NEW_LINE> valid: LetterData <NEW_LINE> test: LetterData | データセット | 6259905f2ae34c7f260ac774 |
class BytesMinHash(BaseMinHash): <NEW_LINE> <INDENT> def __init__(self, shingles): <NEW_LINE> <INDENT> super(BytesMinHash, self).__init__(BytesShingle, shingles) | Documentation can be found in the inherited class BaseMinHash | 6259905f4e4d562566373a95 |
class BeautifulStoneSoup(BeautifulSoup): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['features'] = 'xml' <NEW_LINE> warnings.warn( 'The BeautifulStoneSoup class is deprecated. Instead of using ' 'it, pass features="xml" into the BeautifulSoup constructor.') <NEW_LINE> super(BeautifulStoneSoup, self).__init__(*args, **kwargs) | Deprecated interface to an XML parser. | 6259905f9c8ee82313040cd1 |
class OverlapsBelowLookup(GISLookup): <NEW_LINE> <INDENT> lookup_name = 'overlaps_below' | The 'overlaps_below' operator returns true if A's bounding box overlaps or is below
B's bounding box. | 6259905f1b99ca400229007d |
class ConnectionState(Enum): <NEW_LINE> <INDENT> CONNECTING = 0 <NEW_LINE> OPEN = 1 <NEW_LINE> REMOTE_CLOSING = 2 <NEW_LINE> LOCAL_CLOSING = 3 <NEW_LINE> CLOSED = 4 <NEW_LINE> REJECTING = 5 | RFC 6455, Section 4 - Opening Handshake | 6259905f4f6381625f199fea |
class ProductViewSet(PaginatedViewSetMixin): <NEW_LINE> <INDENT> serializer_class = ProductSerializer <NEW_LINE> filter_class = ProductFilter <NEW_LINE> queryset = Product.objects.all() <NEW_LINE> permission_classes = (AdminWriteOnly, ) | Viewset for Product Details | 6259905f0c0af96317c578a6 |
class EntryRandom(RedirectView): <NEW_LINE> <INDENT> permanent = False <NEW_LINE> def get_redirect_url(self, **kwargs): <NEW_LINE> <INDENT> entry = Entry.published.all().order_by('?')[0] <NEW_LINE> return entry.get_absolute_url() | View for handling a random entry
simply do a redirection after the random selection. | 6259905f3eb6a72ae038bcee |
class TemplateBuilder(object): <NEW_LINE> <INDENT> def __init__(self, package_name, options): <NEW_LINE> <INDENT> self.package_name = package_name <NEW_LINE> self.options = vars(options) <NEW_LINE> self.templates = {} <NEW_LINE> self.directories = set() <NEW_LINE> <DEDENT> def add_template(self, template, target): <NEW_LINE> <INDENT> target = re.sub("\{\{PACKAGE\}\}", self.package_name, target) <NEW_LINE> self.templates[template] = target <NEW_LINE> directory = os.path.dirname(target) <NEW_LINE> self.add_directory(os.path.join(self.package_name, directory)) <NEW_LINE> <DEDENT> def add_directory(self, dir_name): <NEW_LINE> <INDENT> self.directories.add(dir_name) <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> self._build_directories() <NEW_LINE> self._fill_templates() <NEW_LINE> <DEDENT> def _build_directories(self): <NEW_LINE> <INDENT> if os.path.exists(self.package_name): <NEW_LINE> <INDENT> question = "Directory '%s' already exists. " "Do you wish to continue?" % self.package_name <NEW_LINE> if not get_confirmation(question): <NEW_LINE> <INDENT> print("Exiting...") <NEW_LINE> exit(-1) <NEW_LINE> <DEDENT> <DEDENT> for directory in self.directories: <NEW_LINE> <INDENT> if not os.path.exists(directory): <NEW_LINE> <INDENT> os.makedirs(directory) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _fill_templates(self): <NEW_LINE> <INDENT> for template, target in self.templates.iteritems(): <NEW_LINE> <INDENT> self._write_file(template, target, self.options) <NEW_LINE> <DEDENT> <DEDENT> def _write_file(self, template, target, file_opts): <NEW_LINE> <INDENT> filepath = os.path.join(self.package_name, target) <NEW_LINE> f = open(filepath, "w") <NEW_LINE> template = env.get_template(template) <NEW_LINE> f.writelines(template.render(file_opts)) <NEW_LINE> f.close() | A builder that handles the creation of directories for the registed
template files in addition to creating the output files by filling
in the templates with the values from options. | 6259905f8da39b475be04876 |
class DefaultsMixin(object): <NEW_LINE> <INDENT> if settings.DEBUG: <NEW_LINE> <INDENT> authentication_classes = ( authentication.BasicAuthentication, JSONWebTokenAuthentication,) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> authentication_classes = (JSONWebTokenAuthentication,) <NEW_LINE> <DEDENT> permission_classes = ( permissions.IsAuthenticated, ) | Default settings for view authentication, permissions,
filtering and pagination. | 6259905f76e4537e8c3f0c1b |
class JSONstr: <NEW_LINE> <INDENT> __slots__ = ['serialized_json'] <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return self.serialized_json <NEW_LINE> <DEDENT> def __init__(self, serialized_json: str): <NEW_LINE> <INDENT> assert isinstance(serialized_json, str) <NEW_LINE> self.serialized_json = serialized_json | JSONStr is a special type that encapsulates already serialized
json-chunks in json object-trees. `json_dumps` will insert the content
of a JSONStr-object literally, rather than serializing it as other
objects. | 6259905fd6c5a102081e37b2 |
class ServiceHealth(EntityHealth): <NEW_LINE> <INDENT> _attribute_map = { 'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'}, 'health_events': {'key': 'HealthEvents', 'type': '[HealthEvent]'}, 'unhealthy_evaluations': {'key': 'UnhealthyEvaluations', 'type': '[HealthEvaluationWrapper]'}, 'name': {'key': 'Name', 'type': 'str'}, 'partition_health_states': {'key': 'PartitionHealthStates', 'type': '[PartitionHealthState]'}, } <NEW_LINE> def __init__(self, aggregated_health_state=None, health_events=None, unhealthy_evaluations=None, name=None, partition_health_states=None): <NEW_LINE> <INDENT> super(ServiceHealth, self).__init__(aggregated_health_state=aggregated_health_state, health_events=health_events, unhealthy_evaluations=unhealthy_evaluations) <NEW_LINE> self.name = name <NEW_LINE> self.partition_health_states = partition_health_states | Information about the health of a Service Fabric service.
:param aggregated_health_state: The HealthState representing the
aggregated health state of the entity computed by Health Manager.
The health evaluation of the entity reflects all events reported on the
entity and its children (if any).
The aggregation is done by applying the desired health policy.
. Possible values include: 'Invalid', 'Ok', 'Warning', 'Error', 'Unknown'
:type aggregated_health_state: str
:param health_events: The list of health events reported on the entity.
:type health_events: list of :class:`HealthEvent
<azure.servicefabric.models.HealthEvent>`
:param unhealthy_evaluations: The unhealthy evaluations that show why the
current aggregated health state was returned by Health Manager.
:type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper
<azure.servicefabric.models.HealthEvaluationWrapper>`
:param name: The name of the service whose health information is
described by this object.
:type name: str
:param partition_health_states: The list of partition health states
associated with the service.
:type partition_health_states: list of :class:`PartitionHealthState
<azure.servicefabric.models.PartitionHealthState>` | 6259905f097d151d1a2c26fe |
class merge_commits_args(object): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'path', None, None, ), (2, TType.STRING, 'ours', None, None, ), (3, TType.STRING, 'theirs', None, None, ), ) <NEW_LINE> def __init__(self, path=None, ours=None, theirs=None,): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.ours = ours <NEW_LINE> self.theirs = theirs <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.path = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.ours = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 3: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.theirs = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> self.validate() <NEW_LINE> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('merge_commits_args') <NEW_LINE> if self.path is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('path', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.path) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ours is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ours', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.ours) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.theirs is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('theirs', TType.STRING, 3) <NEW_LINE> oprot.writeString(self.theirs) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- path
- ours
- theirs | 6259905f38b623060ffaa397 |
class Slack(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> path = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> with open(path + "/../config", "r") as ymlfile: <NEW_LINE> <INDENT> config = yaml.load(ymlfile) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.slack_url = config['slack']['url'] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def notify_slack(self, message): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = {'text': message} <NEW_LINE> req = requests.post(self.slack_url, data=json.dumps(data)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return | Class for pushing realtime notifications to slack channel. | 6259905f0fa83653e46f6576 |
class SpeedsSensorDaysBefore(FeatureBase): <NEW_LINE> <INDENT> def __init__(self, mode, n_days_before=1): <NEW_LINE> <INDENT> name = 'SpeedsSensorDaysBefore' <NEW_LINE> self.n_days_before = n_days_before <NEW_LINE> super(SpeedsSensorDaysBefore, self).__init__( name=name, mode=mode) <NEW_LINE> <DEDENT> def extract_feature(self): <NEW_LINE> <INDENT> s = None <NEW_LINE> if self.mode == 'local': <NEW_LINE> <INDENT> tr = data.speeds_original('train').drop(['KEY_2'], axis=1) <NEW_LINE> te = data.speed_test_masked().drop(['KEY_2'], axis=1) <NEW_LINE> s = pd.concat([tr, te]) <NEW_LINE> del tr <NEW_LINE> del te <NEW_LINE> <DEDENT> elif self.mode == 'full': <NEW_LINE> <INDENT> tr = data.speeds(mode='full').drop(['KEY_2'], axis=1) <NEW_LINE> te = data.speeds_original('test2').drop(['KEY_2'], axis=1) <NEW_LINE> s = pd.concat([tr, te]) <NEW_LINE> del tr <NEW_LINE> del te <NEW_LINE> <DEDENT> f = s[['KEY', 'DATETIME_UTC', 'KM']].copy() <NEW_LINE> s = s.rename(columns={'DATETIME_UTC': 'DATETIME_UTC_drop'}) <NEW_LINE> for i in tqdm(range(1, self.n_days_before+1)): <NEW_LINE> <INDENT> colname = 'DATETIME_UTC_{}_D'.format(i) <NEW_LINE> f[colname] = f.DATETIME_UTC - pd.Timedelta(days=i) <NEW_LINE> f = pd.merge(f, s, how='left', left_on=['KEY', 'KM', colname], right_on=['KEY', 'KM', 'DATETIME_UTC_drop']) .drop([colname, 'DATETIME_UTC_drop'], axis=1) <NEW_LINE> f = f.rename(columns={'SPEED_AVG': 'SPEED_AVG_{}_DAY_BEFORE'.format(i), 'SPEED_SD': 'SPEED_SD_{}_DAY_BEFORE'.format(i), 'SPEED_MIN': 'SPEED_MIN_{}_DAY_BEFORE'.format(i), 'SPEED_MAX': 'SPEED_MAX_{}_DAY_BEFORE'.format(i), 'N_VEHICLES': 'N_VEHICLES_{}_DAY_BEFORE'.format(i)}) <NEW_LINE> <DEDENT> return f.rename(columns={'DATETIME_UTC': 'DATETIME_UTC_y_0'}) <NEW_LINE> <DEDENT> def join_to(self, df, one_hot=False): <NEW_LINE> <INDENT> f = convert_to_datetime(self.read_feature()) <NEW_LINE> return pd.merge(df, f, how='left') | say for each street the avg speed
| KEY | KM | DATETIME_UTC_y_0 | speed_avg_sensor_day_i_before | speed_sd_sensor_day_i_before | speed_min_sensor_day_i_before | speed_max_sensor_day_i_before | n_vehicles_sensor_day_i_before | 6259905fd486a94d0ba2d657 |
class Timer: <NEW_LINE> <INDENT> def __init__(self, num_runs): <NEW_LINE> <INDENT> self.num_runs = num_runs <NEW_LINE> <DEDENT> def __call__(self, func): <NEW_LINE> <INDENT> def wrap(arg): <NEW_LINE> <INDENT> avg_time = 0 <NEW_LINE> for _ in range(self.num_runs): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> return_value = func(arg) <NEW_LINE> end = time.time() <NEW_LINE> avg_time += (end - start) <NEW_LINE> <DEDENT> avg_time /= self.num_runs <NEW_LINE> print("Выполнение заняло %.9f секунд" % avg_time) <NEW_LINE> return return_value <NEW_LINE> <DEDENT> return wrap | Класс с методом __call__(), являющийся декоратором
для замера времени выполнения функции | 6259905f460517430c432b9a |
class ZNode(NodePathWrapper): <NEW_LINE> <INDENT> def __init__(self,geomnode=None,magnification=1): <NEW_LINE> <INDENT> NodePathWrapper.__init__(self) <NEW_LINE> self.magnification = magnification <NEW_LINE> if geomnode is None: <NEW_LINE> <INDENT> cm = CardMaker('Node created by CardMaker') <NEW_LINE> cm.setFrame(-.3,.3,-.4,.4) <NEW_LINE> self.geomnode = cm.generate() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.geomnode = geomnode <NEW_LINE> <DEDENT> self.geomnodepath = self.attachNewNode(self.geomnode) <NEW_LINE> self.geomnode.setIntoCollideMask(self.geomnode.getIntoCollideMask() | zcanvas.mask) <NEW_LINE> <DEDENT> def set_zoomable(self,b): <NEW_LINE> <INDENT> if b is True: <NEW_LINE> <INDENT> self.np.setPythonTag('zoomable',self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.np.clearPythonTag('zoomable') | A nodepath with an attached geomnode that can be automatically zoomed and
panned to by the viewport (a 'zoomable' node.) | 6259905f99cbb53fe6832571 |
class Stretch(Enum): <NEW_LINE> <INDENT> ULTRA_CONDENSED = pango.PANGO_STRETCH_ULTRA_CONDENSED <NEW_LINE> EXTRA_CONDENSED = pango.PANGO_STRETCH_EXTRA_CONDENSED <NEW_LINE> CONDENSED = pango.PANGO_STRETCH_CONDENSED <NEW_LINE> SEMI_CONDENSED = pango.PANGO_STRETCH_SEMI_CONDENSED <NEW_LINE> NORMAL = pango.PANGO_STRETCH_NORMAL <NEW_LINE> SEMI_EXPANDED = pango.PANGO_STRETCH_SEMI_EXPANDED <NEW_LINE> EXPANDED = pango.PANGO_STRETCH_EXPANDED <NEW_LINE> EXTRA_EXPANDED = pango.PANGO_STRETCH_EXTRA_EXPANDED <NEW_LINE> ULTRA_EXPANDED = pango.PANGO_STRETCH_ULTRA_EXPANDED | An enumeration specifying the width of the font relative to other designs
within a family. | 6259905f009cb60464d02bc6 |
class TagTests(TestCase): <NEW_LINE> <INDENT> fixtures = [ 'tag', ] <NEW_LINE> def test_tag_list(self): <NEW_LINE> <INDENT> client = APIClient() <NEW_LINE> response = client.get('/api/tag/list/') <NEW_LINE> result = json.loads(response.content) <NEW_LINE> objects_count = 23 <NEW_LINE> first_uuid = '4a408eff-7f22-44df-aa48-d3947321d6e8' <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(result.get('count', None), objects_count) <NEW_LINE> self.assertEqual(result.get('results', None)[0]['uuid'], first_uuid) <NEW_LINE> self.assertIn('next', result) <NEW_LINE> self.assertIn('previous', result) <NEW_LINE> <DEDENT> def test_tag_list_filtered_by_name(self): <NEW_LINE> <INDENT> first_obj = Tag.objects.get(pk=2) <NEW_LINE> data = { 'name': first_obj.name[:-1], } <NEW_LINE> client = APIClient() <NEW_LINE> response = client.get('/api/tag/list/', data) <NEW_LINE> result = json.loads(response.content) <NEW_LINE> objects_count = 1 <NEW_LINE> first_uuid = '3a613c48-dcb0-4b76-8362-af3cfce85141' <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(result.get('count', None), objects_count) <NEW_LINE> self.assertEqual(result.get('results', None)[0]['uuid'], first_uuid) <NEW_LINE> self.assertIn('next', result) <NEW_LINE> self.assertIn('previous', result) <NEW_LINE> <DEDENT> def test_tag_ordered_list(self): <NEW_LINE> <INDENT> data = { 'ordering': '-name', } <NEW_LINE> client = APIClient() <NEW_LINE> response = client.get('/api/tag/list/', data) <NEW_LINE> result = json.loads(response.content) <NEW_LINE> objects_count = 23 <NEW_LINE> first_uuid = '40bed8ac-9b0b-4ad3-bc18-afa4b793cb5f' <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(result.get('count', None), objects_count) <NEW_LINE> self.assertEqual(result.get('results', None)[0]['uuid'], first_uuid) <NEW_LINE> self.assertIn('next', result) <NEW_LINE> self.assertIn('previous', result) | Test module for Tag model | 6259905f07f4c71912bb0acc |
class Report(object): <NEW_LINE> <INDENT> def __init__(self, report_id, exception_type, device_id, exception_symbols, os_version): <NEW_LINE> <INDENT> self.report_id = report_id; <NEW_LINE> self.exception_type = exception_type; <NEW_LINE> self.device_id = device_id; <NEW_LINE> self.exception_symbols = exception_symbols; <NEW_LINE> self.os_version = os_version; | Report class used to encapsulate the row data in EXCEL | 6259905fac7a0e7691f73b73 |
class ComplaintsStatistics(Document): <NEW_LINE> <INDENT> meta = { 'db_alias': 'statistics', 'collection': 'complaintsstatistics', 'strict': False, } <NEW_LINE> statsType = IntField(required=True) <NEW_LINE> provinceCode = StringField(default=None) <NEW_LINE> cityCode = StringField(required=True) <NEW_LINE> countyCode = StringField(default=None) <NEW_LINE> dataType = IntField(required=True) <NEW_LINE> repairType = IntField(default=None) <NEW_LINE> vehicleType = IntField(default=None) <NEW_LINE> category = IntField(default=None) <NEW_LINE> serviceScore = FloatField(default=0) <NEW_LINE> priceScore = FloatField(default=0) <NEW_LINE> qualityScore = FloatField(default=0) <NEW_LINE> envirScore = FloatField(default=0) <NEW_LINE> efficiencyScore = FloatField(default=0) <NEW_LINE> allComment = FloatField(default=0) <NEW_LINE> periodStart = DateTimeField(required=True, default=datetime(2000, 1, 1)) <NEW_LINE> periodEnd = DateTimeField(required=True, default=datetime(2000, 1, 1)) <NEW_LINE> commentsNum = IntField(default=None) <NEW_LINE> satisfiedComments = IntField(default=None), <NEW_LINE> satisfiactionRate = FloatField(default=None) | 评价统计 | 6259905ffff4ab517ebceeb6 |
class DefaultExchangeRuleTests(TestBase, StandardExchangeVerifier): <NEW_LINE> <INDENT> @SupportedBrokers(QPID, OPENAMQ) <NEW_LINE> @inlineCallbacks <NEW_LINE> def test_default_exchange(self): <NEW_LINE> <INDENT> yield self.queue_declare(queue="d") <NEW_LINE> yield self.assertPublishConsume(queue="d", routing_key="d") <NEW_LINE> yield self.verify_direct_exchange("") | The server MUST predeclare a direct exchange to act as the default exchange
for content Publish methods and for default queue bindings.
Client checks that the default exchange is active by specifying a queue
binding with no exchange name, and publishing a message with a suitable
routing key but without specifying the exchange name, then ensuring that
the message arrives in the queue correctly. | 6259905f1f5feb6acb16427a |
@dataclass <NEW_LINE> class LeanSendsResponse(LeanScriptStep): <NEW_LINE> <INDENT> message: Dict <NEW_LINE> async def run(self, server: 'MockLeanServerProcess') -> None: <NEW_LINE> <INDENT> print(f"\nLean sends the following response:\n{self.message}") <NEW_LINE> server.send_message(self.message) | Simulate Lean's output behaviour | 6259905fe64d504609df9f16 |
class CbgppeerprevstateEnum(Enum): <NEW_LINE> <INDENT> none = 0 <NEW_LINE> idle = 1 <NEW_LINE> connect = 2 <NEW_LINE> active = 3 <NEW_LINE> opensent = 4 <NEW_LINE> openconfirm = 5 <NEW_LINE> established = 6 <NEW_LINE> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xe._meta import _BGP4_MIB as meta <NEW_LINE> return meta._meta_table['Bgp4Mib.Bgppeertable.Bgppeerentry.CbgppeerprevstateEnum'] | CbgppeerprevstateEnum
The BGP peer connection previous state.
.. data:: none = 0
.. data:: idle = 1
.. data:: connect = 2
.. data:: active = 3
.. data:: opensent = 4
.. data:: openconfirm = 5
.. data:: established = 6 | 6259905f3617ad0b5ee077dd |
class RepositoryViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = Repository.objects.all() <NEW_LINE> serializer_class = RepositorySerializer <NEW_LINE> filter_backends = (filters.SearchFilter, filters.OrderingFilter) <NEW_LINE> search_fields = ('name', 'project', 'url') <NEW_LINE> ordering_fields = ('name', 'project', 'url') | Returns a list of all available repositories in Porchlight.
The `name`, `project`, and `url` fields can all be searched using
`?search=`. For example, `?search=porc` will match Porchlight.
Ordering can be changed based on `name`, `project`, and `url` using
`?ordering=`. For example, `?ordering=name` will order by name,
alphabetically. The ordering can be reversed using `?ordering=-name`. | 6259905fa79ad1619776b605 |
class Mouse(Turtle): <NEW_LINE> <INDENT> def __init__(self, position, heading, fill=green, **style): <NEW_LINE> <INDENT> Turtle.__init__(self, position, heading, fill=fill, **style) <NEW_LINE> self.radius = (self.position - self.origin).length() <NEW_LINE> self.theta = (self.m / self.radius) * 180 / pi <NEW_LINE> self.angle = (self.position - self.origin).direction() <NEW_LINE> <DEDENT> def getnextstate(self): <NEW_LINE> <INDENT> p = (self.position - self.origin).rotate(-self.theta) <NEW_LINE> return p + self.origin, self.heading | docstring for Mouse | 6259905fbe8e80087fbc0716 |
class AddTimeFeatures(MapTransformation): <NEW_LINE> <INDENT> @validated() <NEW_LINE> def __init__( self, start_field: str, target_field: str, output_field: str, time_features: List[TimeFeature], pred_length: int, ) -> None: <NEW_LINE> <INDENT> self.date_features = time_features <NEW_LINE> self.pred_length = pred_length <NEW_LINE> self.start_field = start_field <NEW_LINE> self.target_field = target_field <NEW_LINE> self.output_field = output_field <NEW_LINE> self._min_time_point: pd.Timestamp = None <NEW_LINE> self._max_time_point: pd.Timestamp = None <NEW_LINE> self._full_range_date_features: np.ndarray = None <NEW_LINE> self._date_index: pd.DatetimeIndex = None <NEW_LINE> <DEDENT> def _update_cache(self, start: pd.Timestamp, length: int) -> None: <NEW_LINE> <INDENT> end = shift_timestamp(start, length) <NEW_LINE> if self._min_time_point is not None: <NEW_LINE> <INDENT> if self._min_time_point <= start and end <= self._max_time_point: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> if self._min_time_point is None: <NEW_LINE> <INDENT> self._min_time_point = start <NEW_LINE> self._max_time_point = end <NEW_LINE> <DEDENT> self._min_time_point = min( shift_timestamp(start, -50), self._min_time_point ) <NEW_LINE> self._max_time_point = max( shift_timestamp(end, 50), self._max_time_point ) <NEW_LINE> self.full_date_range = pd.date_range( self._min_time_point, self._max_time_point, freq=start.freq ) <NEW_LINE> self._full_range_date_features = ( np.vstack( [feat(self.full_date_range) for feat in self.date_features] ) if self.date_features else None ) <NEW_LINE> self._date_index = pd.Series( index=self.full_date_range, data=np.arange(len(self.full_date_range)), ) <NEW_LINE> <DEDENT> def map_transform(self, data: DataEntry, is_train: bool) -> DataEntry: <NEW_LINE> <INDENT> start = data[self.start_field] <NEW_LINE> length = target_transformation_length( data[self.target_field], self.pred_length, is_train=is_train ) <NEW_LINE> self._update_cache(start, length) <NEW_LINE> i0 = self._date_index[start] <NEW_LINE> features = ( self._full_range_date_features[..., i0 : i0 + length] if self.date_features else None ) <NEW_LINE> data[self.output_field] = features <NEW_LINE> return data | Adds a set of time features.
If `is_train=True` the feature matrix has the same length as the `target` field.
If `is_train=False` the feature matrix has length len(target) + pred_length
Parameters
----------
start_field
Field with the start time stamp of the time series
target_field
Field with the array containing the time series values
output_field
Field name for result.
time_features
list of time features to use.
pred_length
Prediction length | 6259905f8da39b475be04878 |
class Discovery(): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> self._thread = None <NEW_LINE> self._skills = {} <NEW_LINE> self._log = logging.getLogger('atlas.discovery') <NEW_LINE> self._client = DiscoveryClient(on_discovery=self.process) <NEW_LINE> <DEDENT> def _ping(self): <NEW_LINE> <INDENT> self._log.debug('Sending discovery request!') <NEW_LINE> try: <NEW_LINE> <INDENT> self._client.ping() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self._log.warn('Could not send a ping discovery: %s' % e) <NEW_LINE> <DEDENT> now = datetime.utcnow() <NEW_LINE> for k in list(self._skills.keys()): <NEW_LINE> <INDENT> v = self._skills.get(k) <NEW_LINE> if v.has_timedout(now, self._config.timeout): <NEW_LINE> <INDENT> del self._skills[k] <NEW_LINE> self._log.info('⏳ SKill %s has timed out, removed it' % k) <NEW_LINE> <DEDENT> <DEDENT> self._thread = threading.Timer(self._config.interval, self._ping) <NEW_LINE> self._thread.daemon = True <NEW_LINE> self._thread.start() <NEW_LINE> <DEDENT> def process(self, skill_data, raw=None): <NEW_LINE> <INDENT> self._log.debug('Processing response from %s' % skill_data) <NEW_LINE> name = skill_data.get('name') <NEW_LINE> if name: <NEW_LINE> <INDENT> skill = self._skills.get(name) <NEW_LINE> if skill: <NEW_LINE> <INDENT> self._log.debug('Skill %s already exists, updating' % name) <NEW_LINE> skill.heard_of() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._skills[name] = Skill(**skill_data) <NEW_LINE> self._log.info('🛠️ Added skill %s' % name) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._log.warn('No name defined, skipping the skill') <NEW_LINE> <DEDENT> <DEDENT> def skill_env_for_intent(self, intent): <NEW_LINE> <INDENT> skill = find(self._skills.values(), lambda s: s.intents.get(intent) != None) <NEW_LINE> if skill: <NEW_LINE> <INDENT> return skill.env.keys() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def start(self, broker_config): <NEW_LINE> <INDENT> self._client.start(broker_config) <NEW_LINE> self._ping() <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> if self._thread: <NEW_LINE> <INDENT> self._thread.cancel() <NEW_LINE> <DEDENT> self._client.stop() | Represents the discovery service used to keep track of registered skills.
| 6259905f4a966d76dd5f0584 |
class CompatibilityStrategy: <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> @abstractmethod <NEW_LINE> def check_compatibility(self): <NEW_LINE> <INDENT> raise NotImplementedError | Metaclass defining the compatibility check set of operations | 6259905f38b623060ffaa398 |
class RandomInverseModel(InverseModel): <NEW_LINE> <INDENT> name = 'Rnd' <NEW_LINE> desc = 'Random' <NEW_LINE> def infer_x(self, y_desired): <NEW_LINE> <INDENT> InverseModel.infer_x(y_desired) <NEW_LINE> if self.fmodel.size() == 0: <NEW_LINE> <INDENT> return self._random_x() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> idx = random.randint(0, self.fmodel.size()-1) <NEW_LINE> return self.dataset.get_x(idx) | Random Inverse Model | 6259905f009cb60464d02bc7 |
class TestX265NoSAO(unittest.TestCase): <NEW_LINE> <INDENT> def test_x265_no_sao(self): <NEW_LINE> <INDENT> x265 = X265() <NEW_LINE> self._test_no_sao_normal_values(x265) <NEW_LINE> self._test_no_sao_abormal_values(x265) <NEW_LINE> <DEDENT> def _test_no_sao_normal_values(self, x265): <NEW_LINE> <INDENT> x265.no_sao = True <NEW_LINE> self.assertTrue(x265.no_sao) <NEW_LINE> x265.no_sao = False <NEW_LINE> self.assertFalse(x265.no_sao) <NEW_LINE> <DEDENT> def _test_no_sao_abormal_values(self, x265): <NEW_LINE> <INDENT> x265.no_sao = 1 <NEW_LINE> self.assertTrue(x265.no_sao) <NEW_LINE> x265.no_sao = 10 <NEW_LINE> self.assertTrue(x265.no_sao) <NEW_LINE> x265.no_sao = -1 <NEW_LINE> self.assertTrue(x265.no_sao) <NEW_LINE> x265.no_sao = -10 <NEW_LINE> self.assertTrue(x265.no_sao) <NEW_LINE> x265.no_sao = 'Hello, World!' <NEW_LINE> self.assertTrue(x265.no_sao) <NEW_LINE> x265.no_sao = 0 <NEW_LINE> self.assertFalse(x265.no_sao) <NEW_LINE> x265.no_sao = None <NEW_LINE> self.assertFalse(x265.no_sao) <NEW_LINE> x265.no_sao = '' <NEW_LINE> self.assertFalse(x265.no_sao) | Tests all No SAO option values for the x265 codec. | 6259905f3d592f4c4edbc56d |
class Camera(Structure): <NEW_LINE> <INDENT> _fields_ = [ ("mName", String), ("mPosition", Vector3D), ("mUp", Vector3D), ("mLookAt", Vector3D), ("mHorizontalFOV", c_float), ("mClipPlaneNear", c_float), ("mClipPlaneFar", c_float), ("mAspect", c_float), ] | See 'camera.h' for details. | 6259905fa219f33f346c7e97 |
class dN(): <NEW_LINE> <INDENT> def __init__(self, N): <NEW_LINE> <INDENT> self.N = N <NEW_LINE> <DEDENT> def roll(self): <NEW_LINE> <INDENT> return randint(1, self.N) | classdocs | 6259905f4f88993c371f1067 |
class add_doc(object): <NEW_LINE> <INDENT> def __init__(self, description): <NEW_LINE> <INDENT> self.doc = description <NEW_LINE> <DEDENT> def __call__(self, f): <NEW_LINE> <INDENT> f.__doc__ = self.doc <NEW_LINE> return f | Decorator to add a docstring to a function | 6259905fd7e4931a7ef3d6cd |
class ZMQReader: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> context = zmq.Context() <NEW_LINE> receiver = context.socket(zmq.PULL) <NEW_LINE> self._bind_addr = "tcp://127.0.0.1:{}".format(ZMQ_PULL_PORT) <NEW_LINE> receiver.bind(self._bind_addr) <NEW_LINE> logger.info("Biding ZMQ at {}".format(self._bind_addr)) <NEW_LINE> self.name = MODULE_NAME <NEW_LINE> self.limit_rp = False <NEW_LINE> self.limit_thrust = False <NEW_LINE> self.limit_yaw = False <NEW_LINE> self.data = {"roll": 0.0, "pitch": 0.0, "yaw": 0.0, "thrust": -1.0, "estop": False, "exit": False, "althold": False, "alt1": False, "alt2": False, "pitchNeg": False, "rollNeg": False, "pitchPos": False, "rollPos": False} <NEW_LINE> logger.info("Initialized ZMQ") <NEW_LINE> self._receiver_thread = _PullReader(receiver, self._cmd_callback) <NEW_LINE> self._receiver_thread.start() <NEW_LINE> <DEDENT> def _cmd_callback(self, cmd): <NEW_LINE> <INDENT> for k in list(cmd["ctrl"].keys()): <NEW_LINE> <INDENT> self.data[k] = cmd["ctrl"][k] <NEW_LINE> <DEDENT> <DEDENT> def open(self, device_id): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def read(self, device_id): <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> def close(self, device_id): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def devices(self): <NEW_LINE> <INDENT> return [{"id": 0, "name": "ZMQ@{}".format(self._bind_addr)}] | Used for reading data from input devices using the PyGame API. | 6259905f45492302aabfdb6b |
class Explosion(character.Character, object): <NEW_LINE> <INDENT> def __init__(self, pos, direction, game_map, texture="explosion.png"): <NEW_LINE> <INDENT> super(Explosion, self).__init__(pos, texture) <NEW_LINE> current_cell = self.get_current_cell(game_map) <NEW_LINE> if current_cell.occupied_by: <NEW_LINE> <INDENT> current_cell.occupied_by.stun() <NEW_LINE> <DEDENT> self.get_current_cell(game_map).occupied = True <NEW_LINE> <DEDENT> def update(self, game_map): <NEW_LINE> <INDENT> self.frame_count += 1 <NEW_LINE> if self.frame_count > const.EXPLOSIONTIME: <NEW_LINE> <INDENT> self.get_current_cell(game_map).occupied = False <NEW_LINE> self.kill() <NEW_LINE> <DEDENT> <DEDENT> def move(self, direction, game_map): <NEW_LINE> <INDENT> pass | Includes the explosions on the game. | 6259905fe5267d203ee6cf08 |
class StatsdPlugin(Plugin): <NEW_LINE> <INDENT> targets = [ Plugin.gauge('^statsd\.?(?P<server>[^\.]*)\.(?P<wtt>numStats)'), Plugin.gauge('^stats\.statsd\.?(?P<server>[^\.]*)\.(?P<wtt>processing_time)$'), Plugin.rate('^stats\.statsd\.?(?P<server>[^\.]*)\.(?P<wtt>[^\.]+)$'), Plugin.gauge('^stats\.statsd\.?(?P<server>[^\.]*)\.(?P<wtt>graphiteStats\.calculationtime)$'), Plugin.gauge('^stats\.statsd\.?(?P<server>[^\.]*)\.(?P<wtt>graphiteStats\.flush_[^\.]+)$'), { 'match': 'stats\.statsd\.?(?P<server>[^\.]*)\.(?P<wtt>graphiteStats\.last_[^\.]+)$', 'target_type': 'counter' }, ] <NEW_LINE> def sanitize(self, target): <NEW_LINE> <INDENT> if 'wtt' not in target['tags']: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if target['tags']['wtt'] == 'packets_received': <NEW_LINE> <INDENT> target['tags']['unit'] = 'Pckt/s' <NEW_LINE> target['tags']['direction'] = 'in' <NEW_LINE> <DEDENT> if target['tags']['wtt'] == 'bad_lines_seen': <NEW_LINE> <INDENT> target['tags']['unit'] = 'Metric/s' <NEW_LINE> target['tags']['direction'] = 'in' <NEW_LINE> target['tags']['type'] = 'bad' <NEW_LINE> <DEDENT> if target['tags']['wtt'] == 'numStats': <NEW_LINE> <INDENT> target['tags']['unit'] = 'Metric' <NEW_LINE> target['tags']['direction'] = 'out' <NEW_LINE> <DEDENT> if target['tags']['wtt'] == 'graphiteStats.calculationtime': <NEW_LINE> <INDENT> target['tags']['unit'] = 'ms' <NEW_LINE> target['tags']['type'] = 'calculationtime' <NEW_LINE> <DEDENT> if target['tags']['wtt'] == 'graphiteStats.last_exception': <NEW_LINE> <INDENT> if target['tags']['target_type'] == 'counter': <NEW_LINE> <INDENT> target['tags']['unit'] = 'timestamp' <NEW_LINE> target['tags']['type'] = 'last_exception' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> target['tags']['unit'] = 's' <NEW_LINE> target['tags']['type'] = 'last_exception age' <NEW_LINE> <DEDENT> <DEDENT> if target['tags']['wtt'] == 'graphiteStats.last_flush': <NEW_LINE> <INDENT> if target['tags']['target_type'] == 'counter': <NEW_LINE> <INDENT> target['tags']['unit'] = 'timestamp' <NEW_LINE> target['tags']['type'] = 'last_flush' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> target['tags']['unit'] = 's' <NEW_LINE> target['tags']['type'] = 'last_flush age' <NEW_LINE> <DEDENT> <DEDENT> if target['tags']['wtt'] == 'graphiteStats.flush_length': <NEW_LINE> <INDENT> target['tags']['unit'] = 'B' <NEW_LINE> target['tags']['direction'] = 'out' <NEW_LINE> target['tags']['to'] = 'graphite' <NEW_LINE> <DEDENT> if target['tags']['wtt'] == 'graphiteStats.flush_time': <NEW_LINE> <INDENT> target['tags']['unit'] = 'ms' <NEW_LINE> target['tags']['direction'] = 'out' <NEW_LINE> target['tags']['to'] = 'graphite' <NEW_LINE> <DEDENT> if target['tags']['wtt'] == 'processing_time': <NEW_LINE> <INDENT> target['tags']['unit'] = 'ms' <NEW_LINE> target['tags']['type'] = 'processing' <NEW_LINE> <DEDENT> del target['tags']['wtt'] | 'use this in combination with: derivative(statsd.*.udp_packet_receive_errors)',
assumes that if you use prefixStats, it's of the format statsd.<statsd_server> , adjust as needed. | 6259905fe64d504609df9f17 |
class InstrDataCursor(object): <NEW_LINE> <INDENT> text_template = 'x: %0.2f\ny: %0.2f' <NEW_LINE> x, y = 0.0, 0.0 <NEW_LINE> xoffset, yoffset = -20, 20 <NEW_LINE> text_template = 'x: %0.2f\ny: %0.2f' <NEW_LINE> def __init__(self, ax): <NEW_LINE> <INDENT> self.ax = ax <NEW_LINE> self.positions = [] <NEW_LINE> self.intensities = [] <NEW_LINE> self.annotation = ax.annotate(self.text_template, xy=(self.x, self.y), xytext=(self.xoffset, self.yoffset), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0') ) <NEW_LINE> self.annotation.set_visible(False) <NEW_LINE> <DEDENT> def __call__(self, event): <NEW_LINE> <INDENT> self.event = event <NEW_LINE> self.x, self.y = event.mouseevent.xdata, event.mouseevent.ydata <NEW_LINE> if self.x is not None: <NEW_LINE> <INDENT> self.annotation.xy = self.x, self.y <NEW_LINE> self.positions.append(float(self.x)) <NEW_LINE> self.intensities.append(float(self.y)) <NEW_LINE> self.annotation.set_text(self.text_template % (self.x, self.y)) <NEW_LINE> self.annotation.set_visible(True) <NEW_LINE> event.canvas.draw() <NEW_LINE> <DEDENT> <DEDENT> def getPositions(self): <NEW_LINE> <INDENT> return self.positions <NEW_LINE> <DEDENT> def getIntensities(self): <NEW_LINE> <INDENT> return self.intensities | Allows to click on a displayed plot to determine the instrument curve
stop by closing the window
it returns two arrays: positons and corresponding intensity values | 6259905f3c8af77a43b68a8a |
class DS8KConnectionPool(connectionpool.HTTPSConnectionPool): <NEW_LINE> <INDENT> scheme = 'httpsds8k' <NEW_LINE> ConnectionCls = DS8KHTTPSConnection <NEW_LINE> def urlopen(self, method, url, **kwargs): <NEW_LINE> <INDENT> if url and url.startswith('httpsds8k://'): <NEW_LINE> <INDENT> url = 'https://' + url[12:] <NEW_LINE> <DEDENT> return super(DS8KConnectionPool, self).urlopen(method, url, **kwargs) | Extend the HTTPS Connection Pool to our own Certificate verification. | 6259905f2ae34c7f260ac779 |
class TestDefaults: <NEW_LINE> <INDENT> @pytest.mark.parametrize('config_class', [base(), production(), testing(), development()]) <NEW_LINE> def test_core_defaults(self, config_class, monkeypatch): <NEW_LINE> <INDENT> monkeypatch.setattr(os, "environ", {}) <NEW_LINE> instance = config_class() <NEW_LINE> assert len(instance.SECRET_KEY) > 30 and str(instance.SECRET_KEY) <NEW_LINE> assert instance.SQLALCHEMY_DATABASE_URI == 'sqlite:///:memory:' <NEW_LINE> assert instance.SQLALCHEMY_TRACK_MODIFICATIONS is False <NEW_LINE> <DEDENT> @pytest.mark.parametrize('config_class', [base(), production()]) <NEW_LINE> def test_production_defaults(self, config_class, monkeypatch): <NEW_LINE> <INDENT> monkeypatch.setattr(os, "environ", {}) <NEW_LINE> instance = config_class() <NEW_LINE> assert instance.DEBUG is False <NEW_LINE> assert instance.TESTING is False <NEW_LINE> <DEDENT> def test_test_defaults(self, testing, monkeypatch): <NEW_LINE> <INDENT> monkeypatch.setattr(os, "environ", {}) <NEW_LINE> instance = testing() <NEW_LINE> assert instance.DEBUG is False <NEW_LINE> assert instance.TESTING is True <NEW_LINE> <DEDENT> def test_dev_defaults(self, development, monkeypatch): <NEW_LINE> <INDENT> monkeypatch.setattr(os, "environ", {}) <NEW_LINE> instance = development() <NEW_LINE> assert instance.DEBUG is True <NEW_LINE> assert instance.TESTING is False | Ensure that the config classes set their defaults properly. | 6259905f63b5f9789fe86805 |
class InteractionLJ(Interaction): <NEW_LINE> <INDENT> key = "lj" <NEW_LINE> def __init__(self, epsilon, sigma): <NEW_LINE> <INDENT> self.key = InteractionLJ.key <NEW_LINE> self.type = "Lennard-Jones" <NEW_LINE> self.epsilon = epsilon <NEW_LINE> self.sigma = sigma <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{!s} {!s} {!s}".format(self.key, self.epsilon, self.sigma) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> rep = "key={!r}, type={!r}, epsilon={!r}, sigma={!r}" .format(self.key, self.type, self.epsilon, self.sigma) <NEW_LINE> return "Interaction({!s})".format(rep) <NEW_LINE> <DEDENT> def to_dct(self): <NEW_LINE> <INDENT> dct = OrderedDict() <NEW_LINE> dct.update({"KEY" : self.key}) <NEW_LINE> dct.update({"EPSILON" : self.epsilon}) <NEW_LINE> dct.update({"SIGMA" : self.sigma}) <NEW_LINE> return dct <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, dlstr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name, epsilon, sigma = dlstr.split() <NEW_LINE> if name.lower() != cls.key: <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("Require `lj eps sigma` not {!r}".format(dlstr)) <NEW_LINE> <DEDENT> epsilon = float(epsilon) <NEW_LINE> sigma = float(sigma) <NEW_LINE> return cls(epsilon, sigma) | Standard Lennard Jones potential (bonded or non-bonded)
U(r) = 4 epsilon [ (sigma/r)^12 - (sigma/r)^6 ] | 6259905f0c0af96317c578a8 |
class GenconfigCommand(command.Command): <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> init() <NEW_LINE> <DEDENT> def execute_command(self): <NEW_LINE> <INDENT> print(Back.GREEN + Fore.BLACK + "Scrapple Genconfig") <NEW_LINE> print(Back.RESET + Fore.RESET) <NEW_LINE> directory = os.path.join(scrapple.__path__[0], 'templates', 'configs') <NEW_LINE> with open(os.path.join(directory, self.args['--type'] + '.txt'), 'r') as f: <NEW_LINE> <INDENT> template_content = f.read() <NEW_LINE> <DEDENT> print("\n\nUsing the", self.args['--type'], "template\n\n") <NEW_LINE> template = Template(template_content) <NEW_LINE> settings = { 'projectname': self.args['<projectname>'], 'selector_type': self.args['--selector'], 'url': self.args['<url>'] } <NEW_LINE> rendered = template.render(settings=settings) <NEW_LINE> with open(self.args['<projectname>'] + '.json', 'w') as f: <NEW_LINE> <INDENT> f.write(rendered) <NEW_LINE> <DEDENT> print(Back.WHITE + Fore.RED + self.args['<projectname>'], ".json has been created" + Back.RESET + Fore.RESET, sep="") | Defines the execution of :command: genconfig | 6259905f97e22403b383c59f |
class PhonemeTest(TestCase): <NEW_LINE> <INDENT> def test_get_consonant(self): <NEW_LINE> <INDENT> consonant = instance.get_consonant() <NEW_LINE> self.assertEqual(consonant, 'p') <NEW_LINE> <DEDENT> def test_get_vowel(self): <NEW_LINE> <INDENT> vowel = instance.get_vowel() <NEW_LINE> self.assertEqual(vowel, 'o') <NEW_LINE> <DEDENT> def test_get_consonant_clusters(self): <NEW_LINE> <INDENT> pass | phoneme tests | 6259905f45492302aabfdb6c |
class RandomHorizontalFlip(object): <NEW_LINE> <INDENT> def __call__(self, img, inv, flow): <NEW_LINE> <INDENT> if self.p < 0.5: <NEW_LINE> <INDENT> img = img.transpose(Image.FLIP_LEFT_RIGHT) <NEW_LINE> if inv is True: <NEW_LINE> <INDENT> img = ImageOps.invert(img) <NEW_LINE> <DEDENT> <DEDENT> return img <NEW_LINE> <DEDENT> def randomize_parameters(self): <NEW_LINE> <INDENT> self.p = random.random() | Horizontally flip the given PIL.Image randomly with a probability of 0.5. | 6259905f91f36d47f22319d8 |
class FrameProcessorPipeline(FrameProcessorPool): <NEW_LINE> <INDENT> def __init__(self, processorTypes): <NEW_LINE> <INDENT> FrameProcessorPool.__init__(self) <NEW_LINE> self.processors = [] <NEW_LINE> for processorType in processorTypes: <NEW_LINE> <INDENT> if issubclass(processorType, FrameProcessor): <NEW_LINE> <INDENT> processor = processorType(self) if issubclass(processorType, DependentFrameProcessor) else processorType() <NEW_LINE> self.processors.append(processor) <NEW_LINE> self.logger.debug("Added {0} instance.".format(processor.__class__.__name__)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.warning("Warning: {0} is not a FrameProcessor; will not instantiate.".format(processorType.__name__)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def initialize(self, imageIn, timeNow): <NEW_LINE> <INDENT> for processor in self.processors: <NEW_LINE> <INDENT> processor.initialize(imageIn, timeNow) <NEW_LINE> <DEDENT> <DEDENT> def process(self, imageIn, timeNow): <NEW_LINE> <INDENT> keepRunning = True <NEW_LINE> imageOut = None <NEW_LINE> for processor in self.processors: <NEW_LINE> <INDENT> if processor.active: <NEW_LINE> <INDENT> keepRunning, imageOut = processor.process(imageIn, timeNow) <NEW_LINE> if not keepRunning: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return keepRunning, imageOut <NEW_LINE> <DEDENT> def onKeyPress(self, key, keyChar=None): <NEW_LINE> <INDENT> keepRunning = True <NEW_LINE> for processor in self.processors: <NEW_LINE> <INDENT> if processor.active: <NEW_LINE> <INDENT> keepRunning = processor.onKeyPress(key, keyChar) <NEW_LINE> if not keepRunning: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return keepRunning <NEW_LINE> <DEDENT> def activateProcessors(self, processorTypes=None, active=True): <NEW_LINE> <INDENT> for processor in self.processors: <NEW_LINE> <INDENT> if processorTypes is None or processor.__class__ in processorTypes: <NEW_LINE> <INDENT> processor.active = active <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def deactivateProcessors(self, processorTypes=None): <NEW_LINE> <INDENT> self.activateProcessors(processorTypes, False) <NEW_LINE> <DEDENT> def getProcessorByType(self, processorType): <NEW_LINE> <INDENT> for processor in self.processors: <NEW_LINE> <INDENT> if isinstance(processor, processorType): <NEW_LINE> <INDENT> return processor <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> desc = "[" + ", ".join(("" if processor.active else "~") + processor.__class__.__name__ for processor in self.processors) + "]" <NEW_LINE> return desc | An ordered pipeline of FrameProcessor instances. | 6259905fa17c0f6771d5d6ed |
class dynamicObjs(object): <NEW_LINE> <INDENT> def __init__(self, params): <NEW_LINE> <INDENT> self.dckItems = [] <NEW_LINE> self.actItems = [] <NEW_LINE> <DEDENT> def addNewDock(self, dockUIObj, name, description='', icon=None): <NEW_LINE> <INDENT> dckItem = QtWidgets.QDockWidget(self) <NEW_LINE> dockUIObj.setupUi(dckItem) <NEW_LINE> dckItem.setObjectName(name) <NEW_LINE> self.addDockWidget(QtCore.Qt.DockWidgetArea(1), dckItem) <NEW_LINE> actItem = self.addNewAction(name, description, None, 1, 1) <NEW_LINE> actItem.toggled.connect(dckItem.setVisible) <NEW_LINE> dckItem.visibilityChanged.connect(actItem.setChecked) <NEW_LINE> self.toolsMenu.addAction(actItem) <NEW_LINE> self.dckItems.append(dckItem) <NEW_LINE> self.actItems.append(actItem) <NEW_LINE> <DEDENT> def addNewAction(self, name, description=None, icon=None, checkable=False, checked=False): <NEW_LINE> <INDENT> if(icon): <NEW_LINE> <INDENT> itm = QAction(self.qtIcon.getIcon(icon), name, self, statusTip=description, triggered=self.doActionClicked) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> itm = QAction(name, self, statusTip=description, triggered=self.doActionClicked) <NEW_LINE> <DEDENT> itm.setCheckable(checkable) <NEW_LINE> itm.setChecked(checked) <NEW_LINE> return itm <NEW_LINE> <DEDENT> def doActionClicked(self, *arg): <NEW_LINE> <INDENT> currentActObj = self.sender() <NEW_LINE> currentActName = currentActObj.iconText() <NEW_LINE> if currentActName=='Execute': <NEW_LINE> <INDENT> self.executeCurrentScript() | classdocs | 6259905f4e4d562566373a9a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.