code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class TestOFPQueueStatsReply(unittest.TestCase): <NEW_LINE> <INDENT> class Datapath(object): <NEW_LINE> <INDENT> ofproto = ofproto <NEW_LINE> ofproto_parser = ofproto_v1_0_parser <NEW_LINE> <DEDENT> c = OFPQueueStatsReply(Datapath) <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_parser(self): <NEW_LINE> <INDENT> version = {'buf': '\x01', 'val': ofproto.OFP_VERSION} <NEW_LINE> msg_type = {'buf': '\x11', 'val': ofproto.OFPT_STATS_REPLY} <NEW_LINE> msg_len_val = ofproto.OFP_STATS_MSG_SIZE + ofproto.OFP_QUEUE_STATS_SIZE <NEW_LINE> msg_len = {'buf': '\x00\x2c', 'val': msg_len_val} <NEW_LINE> xid = {'buf': '\x19\xfc\x28\x6c', 'val': 435955820} <NEW_LINE> buf = version['buf'] + msg_type['buf'] + msg_len['buf'] + xid['buf'] <NEW_LINE> type_ = {'buf': '\x00\x05', 'val': ofproto.OFPST_QUEUE} <NEW_LINE> flags = {'buf': '\x3b\x2b', 'val': 15147} <NEW_LINE> buf += type_['buf'] + flags['buf'] <NEW_LINE> port_no = {'buf': '\xe7\x6b', 'val': 59243} <NEW_LINE> zfill = '\x00' * 2 <NEW_LINE> queue_id = {'buf': '\x2a\xa8\x7f\x32', 'val': 715685682} <NEW_LINE> tx_bytes = {'buf': '\x77\xe1\xd5\x63\x18\xae\x63\xaa', 'val': 8638420181865882538} <NEW_LINE> tx_packets = {'buf': '\x27\xa4\x41\xd7\xd4\x53\x9e\x42', 'val': 2856480458895760962} <NEW_LINE> tx_errors = {'buf': '\x57\x32\x08\x2f\x88\x32\x40\x6b', 'val': 6283093430376743019} <NEW_LINE> buf += port_no['buf'] + zfill + queue_id['buf'] + tx_bytes['buf'] + tx_packets['buf'] + tx_errors['buf'] <NEW_LINE> res = OFPQueueStatsReply.parser(object, version['val'], msg_type['val'], msg_len['val'], xid['val'], buf) <NEW_LINE> eq_(version['val'], res.version) <NEW_LINE> eq_(msg_type['val'], res.msg_type) <NEW_LINE> eq_(msg_len['val'], res.msg_len) <NEW_LINE> eq_(xid['val'], res.xid) <NEW_LINE> eq_(type_['val'], res.type) <NEW_LINE> eq_(flags['val'], res.flags) <NEW_LINE> body = res.body[0] <NEW_LINE> eq_(port_no['val'], body.port_no) <NEW_LINE> eq_(queue_id['val'], body.queue_id) <NEW_LINE> eq_(tx_bytes['val'], body.tx_bytes) <NEW_LINE> eq_(tx_packets['val'], body.tx_packets) <NEW_LINE> eq_(tx_errors['val'], body.tx_errors) <NEW_LINE> <DEDENT> def test_serialize(self): <NEW_LINE> <INDENT> pass | Test case for ofproto_v1_0_parser.OFPQueueStatsReply
| 62598fb5f548e778e596b680 |
class ID(DBFormatter): <NEW_LINE> <INDENT> def execute(self, groupname, conn = None, trans = False): <NEW_LINE> <INDENT> self.sql = "SELECT group_id FROM reqmgr_group " <NEW_LINE> self.sql += "WHERE group_name=:groupname" <NEW_LINE> binds = {"groupname": groupname} <NEW_LINE> result = self.dbi.processData(self.sql, binds, conn = conn, transaction = trans) <NEW_LINE> output = self.format(result) <NEW_LINE> if len(output) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return output[0][0] | _ID_
Get a group ID from the group name | 62598fb5796e427e5384e871 |
class Value(object): <NEW_LINE> <INDENT> multiple = False <NEW_LINE> late_binding = False <NEW_LINE> environ_required = False <NEW_LINE> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> value = self.default <NEW_LINE> if not hasattr(self, '_value') and self.environ_name: <NEW_LINE> <INDENT> self.setup(self.environ_name) <NEW_LINE> <DEDENT> if hasattr(self, '_value'): <NEW_LINE> <INDENT> value = self._value <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> instance = object.__new__(cls) <NEW_LINE> if 'late_binding' in kwargs: <NEW_LINE> <INDENT> instance.late_binding = kwargs.get('late_binding') <NEW_LINE> <DEDENT> if not instance.late_binding: <NEW_LINE> <INDENT> instance.__init__(*args, **kwargs) <NEW_LINE> if ((instance.environ and instance.environ_name) or (not instance.environ and instance.default)): <NEW_LINE> <INDENT> instance = instance.setup(instance.environ_name) <NEW_LINE> <DEDENT> <DEDENT> return instance <NEW_LINE> <DEDENT> def __init__(self, default=None, environ=True, environ_name=None, environ_prefix='DJANGO', environ_required=False, *args, **kwargs): <NEW_LINE> <INDENT> if isinstance(default, Value) and default.default is not None: <NEW_LINE> <INDENT> self.default = copy.copy(default.default) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.default = default <NEW_LINE> <DEDENT> self.environ = environ <NEW_LINE> if environ_prefix and environ_prefix.endswith('_'): <NEW_LINE> <INDENT> environ_prefix = environ_prefix[:-1] <NEW_LINE> <DEDENT> self.environ_prefix = environ_prefix <NEW_LINE> self.environ_name = environ_name <NEW_LINE> self.environ_required = environ_required <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self.value) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.value == other <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return bool(self.value) <NEW_LINE> <DEDENT> __nonzero__ = __bool__ <NEW_LINE> def full_environ_name(self, name): <NEW_LINE> <INDENT> if self.environ_name: <NEW_LINE> <INDENT> environ_name = self.environ_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> environ_name = name.upper() <NEW_LINE> <DEDENT> if self.environ_prefix: <NEW_LINE> <INDENT> environ_name = '{0}_{1}'.format(self.environ_prefix, environ_name) <NEW_LINE> <DEDENT> return environ_name <NEW_LINE> <DEDENT> def setup(self, name): <NEW_LINE> <INDENT> value = self.default <NEW_LINE> if self.environ: <NEW_LINE> <INDENT> full_environ_name = self.full_environ_name(name) <NEW_LINE> if full_environ_name in os.environ: <NEW_LINE> <INDENT> value = self.to_python(os.environ[full_environ_name]) <NEW_LINE> <DEDENT> elif self.environ_required: <NEW_LINE> <INDENT> raise ValueError('Value {0!r} is required to be set as the ' 'environment variable {1!r}' .format(name, full_environ_name)) <NEW_LINE> <DEDENT> <DEDENT> self.value = value <NEW_LINE> return value <NEW_LINE> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> return value | A single settings value that is able to interpret env variables
and implements a simple validation scheme. | 62598fb597e22403b383afe2 |
class TrafficControllerRFC2544(TrafficController, IResults): <NEW_LINE> <INDENT> def __init__(self, traffic_gen_class): <NEW_LINE> <INDENT> super(TrafficControllerRFC2544, self).__init__(traffic_gen_class) <NEW_LINE> self._type = 'rfc2544' <NEW_LINE> self._tests = int(settings.getValue('TRAFFICGEN_RFC2544_TESTS')) <NEW_LINE> <DEDENT> def send_traffic(self, traffic): <NEW_LINE> <INDENT> if not self.traffic_required(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._logger.debug('send_traffic with ' + str(self._traffic_gen_class)) <NEW_LINE> self._type = traffic['traffic_type'] <NEW_LINE> for packet_size in self._packet_sizes: <NEW_LINE> <INDENT> if 'l2' in traffic: <NEW_LINE> <INDENT> traffic['l2'] = dict(traffic['l2'], **{'framesize': packet_size}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> traffic['l2'] = {'framesize': packet_size} <NEW_LINE> <DEDENT> if traffic['traffic_type'] == 'rfc2544_back2back': <NEW_LINE> <INDENT> result = self._traffic_gen_class.send_rfc2544_back2back( traffic, tests=self._tests, duration=self._duration, lossrate=self._lossrate) <NEW_LINE> <DEDENT> elif traffic['traffic_type'] == 'rfc2544_continuous': <NEW_LINE> <INDENT> result = self._traffic_gen_class.send_cont_traffic( traffic, duration=self._duration) <NEW_LINE> <DEDENT> elif traffic['traffic_type'] == 'rfc2544_throughput': <NEW_LINE> <INDENT> result = self._traffic_gen_class.send_rfc2544_throughput( traffic, tests=self._tests, duration=self._duration, lossrate=self._lossrate) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError("Unsupported traffic type {} was " "detected".format(traffic['traffic_type'])) <NEW_LINE> <DEDENT> result = self._append_results(result, packet_size) <NEW_LINE> self._results.append(result) <NEW_LINE> <DEDENT> <DEDENT> def send_traffic_async(self, traffic, function): <NEW_LINE> <INDENT> if not self.traffic_required(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._logger.debug('send_traffic_async with ' + str(self._traffic_gen_class)) <NEW_LINE> self._type = traffic['traffic_type'] <NEW_LINE> for packet_size in self._packet_sizes: <NEW_LINE> <INDENT> traffic['l2'] = {'framesize': packet_size} <NEW_LINE> self._traffic_gen_class.start_rfc2544_throughput( traffic, tests=self._tests, duration=self._duration) <NEW_LINE> self._traffic_started = True <NEW_LINE> if len(function['args']) > 0: <NEW_LINE> <INDENT> function['function'](function['args']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> function['function']() <NEW_LINE> <DEDENT> result = self._traffic_gen_class.wait_rfc2544_throughput() <NEW_LINE> result = self._append_results(result, packet_size) <NEW_LINE> self._results.append(result) | Traffic controller for RFC2544 traffic
Used to setup and control a traffic generator for an RFC2544 deployment
traffic scenario. | 62598fb5460517430c4320cb |
class NlmconfiglogoperstatusEnum(Enum): <NEW_LINE> <INDENT> disabled = 1 <NEW_LINE> operational = 2 <NEW_LINE> noFilter = 3 <NEW_LINE> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xe._meta import _NOTIFICATION_LOG_MIB as meta <NEW_LINE> return meta._meta_table['NotificationLogMib.Nlmconfiglogtable.Nlmconfiglogentry.NlmconfiglogoperstatusEnum'] | NlmconfiglogoperstatusEnum
The operational status of this log\:
disabled administratively disabled
operational administratively enabled and working
noFilter administratively enabled but either
nlmConfigLogFilterName is zero length
or does not name an existing entry in
snmpNotifyFilterTable
.. data:: disabled = 1
.. data:: operational = 2
.. data:: noFilter = 3 | 62598fb5cc0a2c111447b0f0 |
class WellConnectionPort(Enum): <NEW_LINE> <INDENT> Top = "port" <NEW_LINE> LeftAnnulus = "left_annulus_port" <NEW_LINE> RightAnnulus = "right_annulus_port" | Available ports for connecting to a Well node. | 62598fb599fddb7c1ca62e59 |
class ParseError(AuthenticatorError): <NEW_LINE> <INDENT> pass | Exception raised on parse error. | 62598fb526068e7796d4ca34 |
class RegistroY800(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', 'Y800'), Campo(2, 'ARQ_RTF'), Campo(3, 'IND_FIM_RTF'), ] | Outras Informações | 62598fb53539df3088ecc38a |
class BounceSearchResponse(object): <NEW_LINE> <INDENT> def __init__(self, total_count=None, bounces=None): <NEW_LINE> <INDENT> self.swagger_types = { 'total_count': 'int', 'bounces': 'list[BounceInfoResponse]' } <NEW_LINE> self.attribute_map = { 'total_count': 'TotalCount', 'bounces': 'Bounces' } <NEW_LINE> self._total_count = None <NEW_LINE> self._bounces = None <NEW_LINE> if total_count is not None: <NEW_LINE> <INDENT> self.total_count = total_count <NEW_LINE> <DEDENT> if bounces is not None: <NEW_LINE> <INDENT> self.bounces = bounces <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def total_count(self): <NEW_LINE> <INDENT> return self._total_count <NEW_LINE> <DEDENT> @total_count.setter <NEW_LINE> def total_count(self, total_count): <NEW_LINE> <INDENT> self._total_count = total_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def bounces(self): <NEW_LINE> <INDENT> return self._bounces <NEW_LINE> <DEDENT> @bounces.setter <NEW_LINE> def bounces(self, bounces): <NEW_LINE> <INDENT> self._bounces = bounces <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, BounceSearchResponse): <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. | 62598fb5851cf427c66b8394 |
class NetworkConfiguration(ConfigurationObject): <NEW_LINE> <INDENT> driver = CP(default='bridge') <NEW_LINE> driver_options = CP(dict) <NEW_LINE> internal = CP(default=False, input_func=bool_if_set) <NEW_LINE> create_options = CP(dict) <NEW_LINE> DOCSTRINGS = { 'driver': "The network driver name.", 'driver_options': "Custom options to the driver.", 'internal': "Whether the network is internal.", 'create_options': "Additional keyword arguments to creating the network.", } | Configuration class for networks. | 62598fb54c3428357761a398 |
class EightRoomSensor(EightSleepUserEntity): <NEW_LINE> <INDENT> def __init__(self, name, eight, sensor, units): <NEW_LINE> <INDENT> super().__init__(eight) <NEW_LINE> self._sensor = sensor <NEW_LINE> self._mapped_name = NAME_MAP.get(self._sensor, self._sensor) <NEW_LINE> self._name = '{} {}'.format(name, self._mapped_name) <NEW_LINE> self._state = None <NEW_LINE> self._attr = None <NEW_LINE> self._units = units <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> _LOGGER.debug("Updating Room sensor: %s", self._sensor) <NEW_LINE> temp = self._eight.room_temperature() <NEW_LINE> try: <NEW_LINE> <INDENT> if self._units == 'si': <NEW_LINE> <INDENT> self._state = round(temp, 2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._state = round((temp*1.8)+32, 2) <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self._state = None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> if self._units == 'si': <NEW_LINE> <INDENT> return '°C' <NEW_LINE> <DEDENT> return '°F' <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return 'mdi:thermometer' | Representation of an eight sleep room sensor. | 62598fb5be8e80087fbbf145 |
class Solution: <NEW_LINE> <INDENT> def mergeSortedArray(self, A, m, B, n): <NEW_LINE> <INDENT> last, i, j = m + n - 1, m - 1, n - 1 <NEW_LINE> while i >= 0 and j >= 0: <NEW_LINE> <INDENT> if A[i] > B[j]: <NEW_LINE> <INDENT> A[last] = A[i] <NEW_LINE> last, i = last - 1, i - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> A[last] = B[j] <NEW_LINE> last, j = last - 1, j - 1 <NEW_LINE> <DEDENT> <DEDENT> while j >= 0: <NEW_LINE> <INDENT> A[last] = B[j] <NEW_LINE> last, j = last - 1, j - 1 | @param A: sorted integer array A which has m elements,
but size of A is m+n
@param B: sorted integer array B which has n elements
@return: void | 62598fb55fdd1c0f98e5e06c |
class UniqueTermManager(TermManagerBase): <NEW_LINE> <INDENT> def __init__(self, max_terminals=None, **kwargs): <NEW_LINE> <INDENT> super(UniqueTermManager, self).__init__(**kwargs) <NEW_LINE> self.max_terminals = max_terminals <NEW_LINE> <DEDENT> def get_terminal(self, term_name=None): <NEW_LINE> <INDENT> if self.max_terminals and len(self.terminals) >= self.max_terminals: <NEW_LINE> <INDENT> raise MaxTerminalsReached(self.max_terminals) <NEW_LINE> <DEDENT> term = self._new_terminal() <NEW_LINE> term.start_reading(self._pty_read_callback) <NEW_LINE> return term <NEW_LINE> <DEDENT> def client_disconnected(self, websocket): <NEW_LINE> <INDENT> self.log.info("Websocket closed, sending SIGHUP to terminal.") <NEW_LINE> if websocket.terminal: <NEW_LINE> <INDENT> websocket.terminal.kill(signal.SIGHUP) | Give each websocket a unique terminal to use. | 62598fb53d592f4c4edbaf9f |
class ElmOracleListener(sublime_plugin.EventListener): <NEW_LINE> <INDENT> def on_selection_modified_async(self, view): <NEW_LINE> <INDENT> sel = view.sel()[0] <NEW_LINE> region = join_qualified(view.word(sel), view) <NEW_LINE> scope = view.scope_name(region.b) <NEW_LINE> if scope.find('source.elm') != -1: <NEW_LINE> <INDENT> view.run_command('elm_show_type') <NEW_LINE> <DEDENT> <DEDENT> def on_activated_async(self, view): <NEW_LINE> <INDENT> view_load(view) <NEW_LINE> <DEDENT> def on_post_save_async(self, view): <NEW_LINE> <INDENT> view_load(view) <NEW_LINE> <DEDENT> def on_query_completions(self, view, prefix, locations): <NEW_LINE> <INDENT> word = get_word_under_cursor(view) <NEW_LINE> return get_matching_names(view.file_name(), word) | An event listener to load and search through data from elm oracle. | 62598fb567a9b606de5460ae |
class ExternalRedundancyFailureTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_external_redundancy_failure(self): <NEW_LINE> <INDENT> external_redundancy_failure_obj = ExternalRedundancyFailure() <NEW_LINE> self.assertNotEqual(external_redundancy_failure_obj, None) | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fb59c8ee823130401e2 |
class ConfigurationError(BaseException): <NEW_LINE> <INDENT> pass | missing or incorrect codevalidator configuration | 62598fb5d486a94d0ba2c0b0 |
class LevelShowHandler(BaseHandler): <NEW_LINE> <INDENT> @tornado.web.authenticated <NEW_LINE> def get(self, id): <NEW_LINE> <INDENT> if self.group != '1': <NEW_LINE> <INDENT> self.render("404.html", username=self.username, group=self.group) <NEW_LINE> <DEDENT> level_info = get_level_info_by_id(self.session, id) <NEW_LINE> if level_info is None: <NEW_LINE> <INDENT> self.render("404.html", username=self.username, group=self.group) <NEW_LINE> <DEDENT> self.render( "admin/level_detail.html", username=self.username, group=self.group, type_name=self.type_name, level_info=level_info ) | Show the detail information of some level. | 62598fb5009cb60464d01601 |
class CsvOutputter: <NEW_LINE> <INDENT> def __init__(self, filename, header_vars): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.attributes = [''] * len(header_vars) <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> self.fref.write(','.join(self.attributes) + "\n") <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> self.fref = open(self.filename, 'w') <NEW_LINE> <DEDENT> def write_header(self, header_vars): <NEW_LINE> <INDENT> with open(self.filename, 'w') as fp: <NEW_LINE> <INDENT> fp.write(','.join(header_vars) + "\n") <NEW_LINE> <DEDENT> <DEDENT> def append(self): <NEW_LINE> <INDENT> self.fref = open(self.filename, 'a') <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.fref.close() | Class that wraps some of the code that must be used in order to provide triggers that writes into a csv file during parsing. | 62598fb58a349b6b4368631b |
class image: <NEW_LINE> <INDENT> class encode: <NEW_LINE> <INDENT> def img_base64(byte_string): <NEW_LINE> <INDENT> output = str(base64.b64encode(byte_string))[2:-1] <NEW_LINE> output = f'["data:image/png;base64,{output}"]' <NEW_LINE> return output <NEW_LINE> <DEDENT> <DEDENT> class process: <NEW_LINE> <INDENT> def json(query: str, top_k: int, endpoint: str) -> list: <NEW_LINE> <INDENT> data = ( '{"top_k":' + str(top_k) + ', "mode": "search", "data":' + query + "}" ) <NEW_LINE> response = requests.post(endpoint, headers=headers, data=data) <NEW_LINE> content = response.json()["search"]["docs"] <NEW_LINE> results = [] <NEW_LINE> for doc in content: <NEW_LINE> <INDENT> matches = doc["matches"] <NEW_LINE> for match in matches: <NEW_LINE> <INDENT> results.append(match["uri"]) <NEW_LINE> <DEDENT> <DEDENT> return results <NEW_LINE> <DEDENT> <DEDENT> class render: <NEW_LINE> <INDENT> def html(results: list) -> str: <NEW_LINE> <INDENT> output = "" <NEW_LINE> for doc in results: <NEW_LINE> <INDENT> html = f'<img src="{doc}">' <NEW_LINE> output += html <NEW_LINE> <DEDENT> return output | Jina image search | 62598fb5d486a94d0ba2c0b1 |
class GoogleCloudVideointelligenceV1beta1AnnotateVideoRequest(_messages.Message): <NEW_LINE> <INDENT> class FeaturesValueListEntryValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> FEATURE_UNSPECIFIED = 0 <NEW_LINE> LABEL_DETECTION = 1 <NEW_LINE> SHOT_CHANGE_DETECTION = 2 <NEW_LINE> <DEDENT> features = _messages.EnumField('FeaturesValueListEntryValuesEnum', 1, repeated=True) <NEW_LINE> inputContent = _messages.StringField(2) <NEW_LINE> inputUri = _messages.StringField(3) <NEW_LINE> locationId = _messages.StringField(4) <NEW_LINE> outputUri = _messages.StringField(5) <NEW_LINE> videoContext = _messages.MessageField('GoogleCloudVideointelligenceV1beta1VideoContext', 6) | Video annotation request.
Enums:
FeaturesValueListEntryValuesEnum:
Fields:
features: Requested video annotation features.
inputContent: The video data bytes. Encoding: base64. If unset, the input
video(s) should be specified via `input_uri`. If set, `input_uri` should
be unset.
inputUri: Input video location. Currently, only [Google Cloud
Storage](https://cloud.google.com/storage/) URIs are supported, which
must be specified in the following format: `gs://bucket-id/object-id`
(other URI formats return google.rpc.Code.INVALID_ARGUMENT). For more
information, see [Request URIs](/storage/docs/reference-uris). A video
URI may include wildcards in `object-id`, and thus identify multiple
videos. Supported wildcards: '*' to match 0 or more characters; '?' to
match 1 character. If unset, the input video should be embedded in the
request as `input_content`. If set, `input_content` should be unset.
locationId: Optional cloud region where annotation should take place.
Supported cloud regions: `us-east1`, `us-west1`, `europe-west1`, `asia-
east1`. If no region is specified, a region will be determined based on
video file location.
outputUri: Optional location where the output (in JSON format) should be
stored. Currently, only [Google Cloud
Storage](https://cloud.google.com/storage/) URIs are supported, which
must be specified in the following format: `gs://bucket-id/object-id`
(other URI formats return google.rpc.Code.INVALID_ARGUMENT). For more
information, see [Request URIs](/storage/docs/reference-uris).
videoContext: Additional video context and/or feature-specific parameters. | 62598fb5adb09d7d5dc0a66c |
class Group: <NEW_LINE> <INDENT> def __init__(self, host): <NEW_LINE> <INDENT> self.people = {host.name: host} <NEW_LINE> self.recipes = {} <NEW_LINE> self.phase = "voting" <NEW_LINE> self.group_id = None <NEW_LINE> <DEDENT> def add_person(self, person_id): <NEW_LINE> <INDENT> if person_id in self.people: <NEW_LINE> <INDENT> raise Exception("Person already exists!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_person = Person(person_id) <NEW_LINE> self.people[person_id] = new_person <NEW_LINE> <DEDENT> <DEDENT> def delete_person(self, person_id): <NEW_LINE> <INDENT> assert person_id in self.people <NEW_LINE> del self.people[person_id] <NEW_LINE> <DEDENT> def get_person(self, person_id): <NEW_LINE> <INDENT> assert person_id in self.people <NEW_LINE> return self.people[person_id] <NEW_LINE> <DEDENT> def add_recipe(self, recipe_name): <NEW_LINE> <INDENT> assert self.phase == "voting" <NEW_LINE> new_recipe = Recipe(recipe_name) <NEW_LINE> self.recipes[recipe_name] = new_recipe <NEW_LINE> <DEDENT> def get_recipe(self, recipe_name): <NEW_LINE> <INDENT> assert recipe_name in self.recipes <NEW_LINE> return self.recipes[recipe_name] <NEW_LINE> <DEDENT> def process_vote(self, member, recipe): <NEW_LINE> <INDENT> assert member in self.members and recipe in self.recipes <NEW_LINE> curr_member = self.members[member] <NEW_LINE> curr_recipe = self.recipes[recipe] <NEW_LINE> curr_recipe.process_vote(member) <NEW_LINE> <DEDENT> def select_recipe(self): <NEW_LINE> <INDENT> selected_recipe = max(self.recipes, key=lambda x: x.number_votes()) <NEW_LINE> self.selected_recipe = selected_recipe <NEW_LINE> self.phase = "waiting_confirmations" <NEW_LINE> self.notify_people() <NEW_LINE> <DEDENT> def process_confirmations(self): <NEW_LINE> <INDENT> self.phase = "confirmed" <NEW_LINE> self.notify_people() <NEW_LINE> <DEDENT> def request_payments(self, message, recipe, amount): <NEW_LINE> <INDENT> host_name = recipe.host.name <NEW_LINE> payment_link = recipe.payment_link <NEW_LINE> recipe_name = recipe.name <NEW_LINE> request_message = "{} requests {} for {}, pay at {}".format(host_name, amount, recipe_name, payment_link) <NEW_LINE> self.notify_people(request_message, criteria) <NEW_LINE> <DEDENT> def notify_people(self, message, criteria): <NEW_LINE> <INDENT> selected_people = [person for person in self.people if criteria(person)] <NEW_LINE> for person in selected_people: <NEW_LINE> <INDENT> person.notify(message) <NEW_LINE> <DEDENT> <DEDENT> def notify_all_members(self, message): <NEW_LINE> <INDENT> for person in self.people: <NEW_LINE> <INDENT> person.notify(message) | Main group class, handles
calls between different
objects. | 62598fb54f6381625f199530 |
class ConfigMerger(object): <NEW_LINE> <INDENT> def __init__(self, resolver=defaultMergeResolve): <NEW_LINE> <INDENT> self.resolver = resolver <NEW_LINE> <DEDENT> def merge(self, merged, mergee): <NEW_LINE> <INDENT> self.mergeMapping(merged, mergee) <NEW_LINE> <DEDENT> def mergeMapping(self, map1, map2): <NEW_LINE> <INDENT> keys = list(map1.keys()) <NEW_LINE> for key in list(map2.keys()): <NEW_LINE> <INDENT> if key not in keys: <NEW_LINE> <INDENT> map1[key] = map2[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj1 = map1[key] <NEW_LINE> obj2 = map2[key] <NEW_LINE> decision = self.resolver(map1, map2, key) <NEW_LINE> if decision == "merge": <NEW_LINE> <INDENT> self.mergeMapping(obj1, obj2) <NEW_LINE> <DEDENT> elif decision == "append": <NEW_LINE> <INDENT> self.mergeSequence(obj1, obj2) <NEW_LINE> <DEDENT> elif decision == "overwrite": <NEW_LINE> <INDENT> map1[key] = obj2 <NEW_LINE> <DEDENT> elif decision == "mismatch": <NEW_LINE> <INDENT> self.handleMismatch(obj1, obj2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = "unable to merge: don't know how to implement %r" <NEW_LINE> raise ValueError(msg % decision) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def mergeSequence(self, seq1, seq2): <NEW_LINE> <INDENT> data1 = object.__getattribute__(seq1, 'data') <NEW_LINE> data2 = object.__getattribute__(seq2, 'data') <NEW_LINE> for obj in data2: <NEW_LINE> <INDENT> data1.append(obj) <NEW_LINE> <DEDENT> comment1 = object.__getattribute__(seq1, 'comments') <NEW_LINE> comment2 = object.__getattribute__(seq2, 'comments') <NEW_LINE> for obj in comment2: <NEW_LINE> <INDENT> comment1.append(obj) <NEW_LINE> <DEDENT> <DEDENT> def handleMismatch(self, obj1, obj2): <NEW_LINE> <INDENT> raise ConfigError("unable to merge %r with %r" % (obj1, obj2)) | This class is used for merging two configurations. If a key exists in the
merge operand but not the merge target, then the entry is copied from the
merge operand to the merge target. If a key exists in both configurations,
then a resolver (a callable) is called to decide how to handle the
conflict. | 62598fb526068e7796d4ca36 |
class TestSameSymbol(unittest.TestCase): <NEW_LINE> <INDENT> def test_signs(self): <NEW_LINE> <INDENT> self.assertNotEqual(same_symbol_check("$", "£"), ("$", "£")) <NEW_LINE> <DEDENT> def test_three_letters(self): <NEW_LINE> <INDENT> self.assertEqual(same_symbol_check("EUR", "AUD"), ("EUR", "AUD")) | Test for currencies with same symbol. Input needed. | 62598fb51f5feb6acb162cfe |
class RedisCache(RedisBackend, BaseCache): <NEW_LINE> <INDENT> def __init__(self, serializer=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.serializer = serializer or JsonSerializer() <NEW_LINE> <DEDENT> def _build_key(self, key, namespace=None): <NEW_LINE> <INDENT> if namespace is not None: <NEW_LINE> <INDENT> return "{}{}{}".format(namespace, ":" if namespace else "", key) <NEW_LINE> <DEDENT> if self.namespace is not None: <NEW_LINE> <INDENT> return "{}{}{}".format(self.namespace, ":" if self.namespace else "", key) <NEW_LINE> <DEDENT> return key <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "RedisCache ({}:{})".format(self.endpoint, self.port) | Redis cache implementation with the following components as defaults:
- serializer: :class:`aiocache.serializers.JsonSerializer`
- plugins: []
Config options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`.
:param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes.
:param namespace: string to use as default prefix for the key used in all operations of
the backend. Default is None.
:param timeout: int or float in seconds specifying maximum timeout for the operations to last.
By default its 5.
:param endpoint: str with the endpoint to connect to. Default is "127.0.0.1".
:param port: int with the port to connect to. Default is 6379.
:param db: int indicating database to use. Default is 0.
:param password: str indicating password to use. Default is None.
:param pool_min_size: int minimum pool size for the redis connections pool. Default is 1
:param pool_max_size: int maximum pool size for the redis connections pool. Default is 10
:param create_connection_timeout: int timeout for the creation of connection,
only for aioredis>=1. Default is None | 62598fb510dbd63aa1c70c96 |
class TestPositionalsActionAppend(ParserTestCase): <NEW_LINE> <INDENT> parser_signature = Sig(add_config=False, add_debug=False) <NEW_LINE> argument_signatures = [ Sig('spam', action='append'), Sig('spam', action='append', nargs=2), ] <NEW_LINE> failures = ['', '--foo', 'a', 'a b', 'a b c d'] <NEW_LINE> successes = [ ('a b c', NS(spam=['a', ['b', 'c']])), ] | Test the 'append' action | 62598fb55fc7496912d482eb |
class SoftmaxRegressor(Classifier): <NEW_LINE> <INDENT> def _fit(self, X, t, max_iter=100, learning_rate=0.1): <NEW_LINE> <INDENT> self.n_classes = np.max(t) + 1 <NEW_LINE> T = np.eye(self.n_classes)[t] <NEW_LINE> W = np.zeros((np.size(X, 1), self.n_classes)) <NEW_LINE> for _ in range(max_iter): <NEW_LINE> <INDENT> W_prev = np.copy(W) <NEW_LINE> y = self._softmax(X @ W) <NEW_LINE> grad = X.T @ (y - T) <NEW_LINE> W -= learning_rate * grad <NEW_LINE> if np.allclose(W, W_prev): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> self.W = W <NEW_LINE> <DEDENT> def _softmax(self, a): <NEW_LINE> <INDENT> a_max = np.max(a, axis=-1, keepdims=True) <NEW_LINE> exp_a = np.exp(a - a_max) <NEW_LINE> return exp_a / np.sum(exp_a, axis=-1, keepdims=True) <NEW_LINE> <DEDENT> def _proba(self, X): <NEW_LINE> <INDENT> y = self._softmax(X @ self.W) <NEW_LINE> return y <NEW_LINE> <DEDENT> def _classify(self, X): <NEW_LINE> <INDENT> proba = self._proba(X) <NEW_LINE> label = np.argmax(proba, axis=-1) <NEW_LINE> return label | Softmax regression model
aka multinomial logistic regression,
multiclass logistic regression, or maximum entropy classifier.
y = softmax(X @ W)
t ~ Categorical(t|y) | 62598fb5ec188e330fdf8970 |
class ResultIterator(): <NEW_LINE> <INDENT> def __init__(self, query, interface, results='substanzas', amount=10, start=None, reverse=False): <NEW_LINE> <INDENT> self.query = query <NEW_LINE> self.amount = amount <NEW_LINE> self.start = start <NEW_LINE> self.interface = interface <NEW_LINE> self.results = results <NEW_LINE> self.reverse = reverse <NEW_LINE> self._stop = False <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> return self.next() <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self._stop: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> self.query[self.interface]['rsm']['before'] = self.reverse <NEW_LINE> self.query['id'] = self.query.stream.new_id() <NEW_LINE> self.query[self.interface]['rsm']['max'] = str(self.amount) <NEW_LINE> if self.start and self.reverse: <NEW_LINE> <INDENT> self.query[self.interface]['rsm']['before'] = self.start <NEW_LINE> <DEDENT> elif self.start: <NEW_LINE> <INDENT> self.query[self.interface]['rsm']['after'] = self.start <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> r = self.query.send(block=True) <NEW_LINE> if not r[self.interface]['rsm']['first'] and not r[self.interface]['rsm']['last']: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> if r[self.interface]['rsm']['count'] and r[self.interface]['rsm']['first_index']: <NEW_LINE> <INDENT> count = int(r[self.interface]['rsm']['count']) <NEW_LINE> first = int(r[self.interface]['rsm']['first_index']) <NEW_LINE> num_items = len(r[self.interface][self.results]) <NEW_LINE> if first + num_items == count: <NEW_LINE> <INDENT> self._stop = True <NEW_LINE> <DEDENT> <DEDENT> if self.reverse: <NEW_LINE> <INDENT> self.start = r[self.interface]['rsm']['first'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.start = r[self.interface]['rsm']['last'] <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> except XMPPError: <NEW_LINE> <INDENT> raise StopIteration | An iterator for Result Set Managment | 62598fb5b7558d589546370d |
class Category(Base): <NEW_LINE> <INDENT> __tablename__ = 'category' <NEW_LINE> name = Column(String(80), nullable=False) <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> @property <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> return { 'name': self.name, 'id': self.id } | A category class mapping to our category table
Args:
Base: the parent class doing the mapping by sqlalchemy | 62598fb57d847024c075c49c |
class Test_vxlan(unittest.TestCase): <NEW_LINE> <INDENT> vni = 0x123456 <NEW_LINE> buf = ( b'\x08\x00\x00\x00' b'\x12\x34\x56\x00' b'test_payload' ) <NEW_LINE> pkt = vxlan.vxlan(vni) <NEW_LINE> jsondict = { 'vxlan': { 'vni': vni } } <NEW_LINE> def test_init(self): <NEW_LINE> <INDENT> eq_(self.vni, self.pkt.vni) <NEW_LINE> <DEDENT> def test_parser(self): <NEW_LINE> <INDENT> parsed_pkt, next_proto_cls, rest_buf = vxlan.vxlan.parser(self.buf) <NEW_LINE> eq_(self.vni, parsed_pkt.vni) <NEW_LINE> eq_(ethernet.ethernet, next_proto_cls) <NEW_LINE> eq_(b'test_payload', rest_buf) <NEW_LINE> <DEDENT> @raises(AssertionError) <NEW_LINE> def test_invalid_flags(self): <NEW_LINE> <INDENT> invalid_flags_bug = ( b'\x00\x00\x00\x00' b'\x12\x34\x56\x00' ) <NEW_LINE> vxlan.vxlan.parser(invalid_flags_bug) <NEW_LINE> <DEDENT> def test_serialize(self): <NEW_LINE> <INDENT> serialized_buf = self.pkt.serialize(payload=None, prev=None) <NEW_LINE> eq_(self.buf[:vxlan.vxlan._MIN_LEN], serialized_buf) <NEW_LINE> <DEDENT> def test_from_jsondict(self): <NEW_LINE> <INDENT> pkt_from_json = vxlan.vxlan.from_jsondict( self.jsondict[vxlan.vxlan.__name__]) <NEW_LINE> eq_(self.vni, pkt_from_json.vni) <NEW_LINE> <DEDENT> def test_to_jsondict(self): <NEW_LINE> <INDENT> jsondict_from_pkt = self.pkt.to_jsondict() <NEW_LINE> eq_(self.jsondict, jsondict_from_pkt) <NEW_LINE> <DEDENT> def test_vni_from_bin(self): <NEW_LINE> <INDENT> vni = vxlan.vni_from_bin(b'\x12\x34\x56') <NEW_LINE> eq_(self.vni, vni) <NEW_LINE> <DEDENT> def test_vni_to_bin(self): <NEW_LINE> <INDENT> eq_(b'\x12\x34\x56', vxlan.vni_to_bin(self.vni)) | Test case for VXLAN (RFC 7348) header encoder/decoder class. | 62598fb523849d37ff851193 |
class QuestObject_(QuestObject, _ComparisonMixin): <NEW_LINE> <INDENT> pass | A QuestObject that implements the == and != operators.
| 62598fb5f9cc0f698b1c533c |
class IRhaptosSwordContentSelectionLens(Interface): <NEW_LINE> <INDENT> pass | Mark a lense as an object that can accept an atom entry POST.
| 62598fb54c3428357761a39a |
class ParameterError(DKIMException): <NEW_LINE> <INDENT> pass | Input parameter error. | 62598fb5097d151d1a2c1110 |
class _ComputeInstancesRepository( repository_mixins.AggregatedListQueryMixin, repository_mixins.ListQueryMixin, _base_repository.GCPRepository): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(_ComputeInstancesRepository, self).__init__( component='instances', **kwargs) <NEW_LINE> <DEDENT> def list(self, resource, zone, **kwargs): <NEW_LINE> <INDENT> kwargs['zone'] = zone <NEW_LINE> return repository_mixins.ListQueryMixin.list(self, resource, **kwargs) | Implementation of Compute Instances repository. | 62598fb5f548e778e596b684 |
class StudentInsertView(LoginRequiredMixin, PermissionMixin, ObjectRedirectView): <NEW_LINE> <INDENT> template_name = 'students/users.html' <NEW_LINE> permissions_required = [ 'change_own_discipline' ] <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> discipline = get_object_or_404( Discipline, slug=self.kwargs.get('slug', '') ) <NEW_LINE> return discipline <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> discipline = self.get_object() <NEW_LINE> success_url = reverse_lazy( 'disciplines:users', kwargs={'slug': discipline.slug} ) <NEW_LINE> return success_url <NEW_LINE> <DEDENT> def action(self, request, *args, **kwargs): <NEW_LINE> <INDENT> user = get_object_or_404( User, pk=self.kwargs.get('pk', '') ) <NEW_LINE> discipline = self.get_object() <NEW_LINE> if user.is_teacher: <NEW_LINE> <INDENT> success = self.insert_monitor(user, discipline) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> success = self.insert_student(user, discipline) <NEW_LINE> <DEDENT> if success: <NEW_LINE> <INDENT> messages.success( self.request, _("{0} was inserted in the discipline: {1}" .format(user.get_short_name(), discipline.title)) ) <NEW_LINE> <DEDENT> return redirect(self.get_success_url()) <NEW_LINE> <DEDENT> def insert_monitor(self, user, discipline): <NEW_LINE> <INDENT> if discipline.monitors.count() >= discipline.monitors_limit: <NEW_LINE> <INDENT> messages.error( self.request, _("There are no more vacancies to monitor") ) <NEW_LINE> return False <NEW_LINE> <DEDENT> if user == discipline.teacher: <NEW_LINE> <INDENT> messages.error( self.request, _("You can't get into your own discipline.") ) <NEW_LINE> return False <NEW_LINE> <DEDENT> discipline.monitors.add(user) <NEW_LINE> return True <NEW_LINE> <DEDENT> def insert_student(self, user, discipline): <NEW_LINE> <INDENT> if discipline.students.count() >= discipline.students_limit: <NEW_LINE> <INDENT> if not discipline.is_closed: <NEW_LINE> <INDENT> discipline.is_closed = True <NEW_LINE> discipline.save() <NEW_LINE> <DEDENT> messages.error( self.request, _("Crowded discipline.") ) <NEW_LINE> return False <NEW_LINE> <DEDENT> discipline.students.add(user) <NEW_LINE> return True | Insert a student or monitor inside discipline by teacher. | 62598fb57c178a314d78d57e |
class RuntimeStore(Singleton): <NEW_LINE> <INDENT> database_path = "" <NEW_LINE> database_file = None <NEW_LINE> last_etag = None <NEW_LINE> data_dir = "" <NEW_LINE> home_data_dir = "" <NEW_LINE> storage = None <NEW_LINE> conf = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import defs <NEW_LINE> self.data_dir = os.path.join(defs.DATA_DIR, "hamster-time-tracker") <NEW_LINE> self.version = defs.VERSION <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> module_dir = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> self.data_dir = os.path.join(module_dir, '..', '..', 'data') <NEW_LINE> self.version = "uninstalled" <NEW_LINE> <DEDENT> self.data_dir = os.path.realpath(self.data_dir) <NEW_LINE> self.storage = Storage() <NEW_LINE> self.home_data_dir = os.path.realpath(os.path.join(xdg_data_home, "hamster-time-tracker")) <NEW_LINE> <DEDENT> @property <NEW_LINE> def art_dir(self): <NEW_LINE> <INDENT> return os.path.join(self.data_dir, "art") | Handles one-shot configuration that is not stored between sessions | 62598fb59c8ee823130401e3 |
class HttpFacadeTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_base(self): <NEW_LINE> <INDENT> http_facade = HttpFacade("tst") <NEW_LINE> self.assertEquals("tst", http_facade.url) <NEW_LINE> self.assertEquals("tst", http_facade.url_to.domain) <NEW_LINE> http_facade = HttpFacade("www.uol.com.br") <NEW_LINE> self.assertEquals("www.uol.com.br", http_facade.url_to.domain) <NEW_LINE> <DEDENT> def test_headers_queries(self): <NEW_LINE> <INDENT> http_facade = HttpFacade("tst") <NEW_LINE> http_facade.header("tst", "tst").header("tst", "tst2") <NEW_LINE> self.assertEquals({"tst": "tst2"}, http_facade.headers) <NEW_LINE> http_facade.query("tst", "tst").query("tst", "tst2") <NEW_LINE> self.assertEquals({"tst": ["tst", "tst2"]}, http_facade.queries) <NEW_LINE> <DEDENT> def test_params(self): <NEW_LINE> <INDENT> http_facade = HttpFacade("tst") <NEW_LINE> http_facade.param("tst", "tst").param("tst", "tst2") <NEW_LINE> self.assertEquals({"tst": ["tst", "tst2"]}, http_facade.form_params) <NEW_LINE> <DEDENT> def test_user_no_http(self): <NEW_LINE> <INDENT> http_facade = HttpFacade("luan.xyz") <NEW_LINE> http_facade.user("danilo", "xptopass") <NEW_LINE> self.assertEquals("danilo:xptopass@luan.xyz", http_facade.url) <NEW_LINE> self.assertTrue("Authentication" in http_facade.headers.keys()) <NEW_LINE> <DEDENT> def test_user_http(self): <NEW_LINE> <INDENT> http_facade = HttpFacade("https://luan.xyz") <NEW_LINE> http_facade.user("danilo", "xptopass") <NEW_LINE> self.assertEquals("https://danilo:xptopass@luan.xyz", http_facade.url) <NEW_LINE> self.assertTrue("Authentication" in http_facade.headers.keys()) <NEW_LINE> <DEDENT> def test_user_to(self): <NEW_LINE> <INDENT> http_facade = HttpFacade("https://regex101.com:8080/blablabla/blebleble?bli=blo&blu=hgfhgf") <NEW_LINE> self.assertEquals("regex101.com", http_facade.url_to.domain) <NEW_LINE> self.assertEquals("http", http_facade.protocol('http').url_to.protocol) | Http Facade Class Tests | 62598fb58a43f66fc4bf225a |
class NearestNeighbourResampler(ImageResampler): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(NearestNeighbourResampler, self).__init__(order=0) | Set to nearest neighbourhood resampling | 62598fb5cc0a2c111447b0f4 |
class WriterToMongoDB(): <NEW_LINE> <INDENT> def __init__(self, logger=None): <NEW_LINE> <INDENT> if logger is None: <NEW_LINE> <INDENT> logger = logging.getLogger() <NEW_LINE> <DEDENT> self.logger = logger <NEW_LINE> self.ctx = zmq.Context() <NEW_LINE> self.sock = self.ctx.socket(zmq.SUB) <NEW_LINE> self.sock.connect("tcp://127.0.0.1:1234") <NEW_LINE> self.sock.subscribe("") <NEW_LINE> connect('muonic', host='localhost', port=27017, username="root", password="muonic", authentication_source='admin') <NEW_LINE> <DEDENT> def DBWriter(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> msg = self.sock.recv_string() <NEW_LINE> obj = jsonpickle.decode(msg) <NEW_LINE> record = RecordAdapter.get(obj) <NEW_LINE> record.save() <NEW_LINE> <DEDENT> <DEDENT> def runDaemon(self): <NEW_LINE> <INDENT> writerTask = threading.Thread(target=self.DBWriter).start() | Writes incoming data to the MongoDB for storage | 62598fb57d43ff2487427473 |
class VRPQuelle: <NEW_LINE> <INDENT> def __init__(self, js_quelle, parent_name): <NEW_LINE> <INDENT> self.name = parent_name <NEW_LINE> self.pfad = js_quelle['pfad'] <NEW_LINE> self.qml = None <NEW_LINE> self.statistik = False <NEW_LINE> self.attribut = None <NEW_LINE> self.filter = None <NEW_LINE> self.text = None <NEW_LINE> if 'name' in js_quelle: <NEW_LINE> <INDENT> if not js_quelle['name'].isspace() and not js_quelle['name'] == '': <NEW_LINE> <INDENT> self.name = js_quelle['name'] <NEW_LINE> <DEDENT> <DEDENT> if 'qml' in js_quelle: <NEW_LINE> <INDENT> if not js_quelle['qml'].isspace() and not js_quelle['qml'] == '': <NEW_LINE> <INDENT> self.qml = js_quelle['qml'] <NEW_LINE> <DEDENT> <DEDENT> if 'statistik' in js_quelle: <NEW_LINE> <INDENT> self.statistik = js_quelle['statistik'] <NEW_LINE> <DEDENT> if 'attribut' in js_quelle: <NEW_LINE> <INDENT> if not js_quelle['attribut'].isspace() and not js_quelle['attribut'] == '': <NEW_LINE> <INDENT> self.attribut = js_quelle['attribut'] <NEW_LINE> <DEDENT> <DEDENT> if 'filter' in js_quelle: <NEW_LINE> <INDENT> if not js_quelle['filter'].isspace() and not js_quelle['filter'] == '': <NEW_LINE> <INDENT> self.filter = js_quelle['filter'] <NEW_LINE> <DEDENT> <DEDENT> if 'text' in js_quelle: <NEW_LINE> <INDENT> self.text = {} <NEW_LINE> for txt in js_quelle['text']: <NEW_LINE> <INDENT> self.text[txt] = js_quelle['text'][txt] | Data source | 62598fb5283ffb24f3cf396e |
class CrossEntropyWithSoftmax(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def fun(y_hat, y): <NEW_LINE> <INDENT> yr_hot = CrossEntropyWithSoftmax.softmax(y_hat) * y <NEW_LINE> return np.average(- np.log(np.sum(yr_hot, 1))) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def diff(y_hat, y): <NEW_LINE> <INDENT> return y_hat - y <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def softmax(y_hat): <NEW_LINE> <INDENT> e_x = np.exp(y_hat - np.max(y_hat, 0)) <NEW_LINE> return e_x / e_x.sum(0) | 带softmax的交叉熵损失函数 | 62598fb57b180e01f3e490c1 |
class Dog: <NEW_LINE> <INDENT> def __init__(self, name, age): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def sit(self): <NEW_LINE> <INDENT> print(f"{self.name} is now sitting.") <NEW_LINE> <DEDENT> def roll_over(self): <NEW_LINE> <INDENT> print(f"{self.name} rolled over!") | A simple attempt to model a dog | 62598fb59f288636728188a5 |
class ValidateChangeAddressForm(FormValidationAction): <NEW_LINE> <INDENT> def name(self) -> Text: <NEW_LINE> <INDENT> return "validate_change_address_form" <NEW_LINE> <DEDENT> async def validate_address_state( self, slot_value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any] ) -> Dict[Text, Any]: <NEW_LINE> <INDENT> if isinstance(slot_value, list): <NEW_LINE> <INDENT> slot_value = slot_value[-1] <NEW_LINE> <DEDENT> if slot_value.upper() not in US_STATES: <NEW_LINE> <INDENT> dispatcher.utter_message(f"{slot_value} is invalid. Please provide a valid state.") <NEW_LINE> return {"address_state": None} <NEW_LINE> <DEDENT> return {"address_state": slot_value} | Validates the user has filled out the change of address form correctly. | 62598fb5bd1bec0571e15133 |
class XGenCreator(avalon.maya.Creator): <NEW_LINE> <INDENT> label = "XGen" <NEW_LINE> family = "reveries.xgen" <NEW_LINE> icon = "paw" <NEW_LINE> defaults = [ "legacy", "interactive", ] <NEW_LINE> def process(self): <NEW_LINE> <INDENT> variant = None <NEW_LINE> for var in self.defaults: <NEW_LINE> <INDENT> prefix = "xgen" + var <NEW_LINE> if self.data["subset"].lower().startswith(prefix): <NEW_LINE> <INDENT> variant = var <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if variant is None: <NEW_LINE> <INDENT> msg = error__invalid_name.format(self.data["subset"], ", ".join(self.defaults)) <NEW_LINE> message_box_error("Invalid Subset Name", msg) <NEW_LINE> raise RuntimeError(msg) <NEW_LINE> <DEDENT> self.data["XGenType"] = variant <NEW_LINE> if variant == "legacy": <NEW_LINE> <INDENT> self.data["step"] = [ legacy.SHAPING, legacy.BAKED, legacy.WIRED, ] <NEW_LINE> <DEDENT> instance = super(XGenCreator, self).process() <NEW_LINE> cmds.setAttr(instance + ".XGenType", lock=True) <NEW_LINE> return put_instance_icon(instance) | Maya XGen Legacy or Interactive Grooming | 62598fb5d7e4931a7ef3c176 |
class EnhancedTextField(JTextField): <NEW_LINE> <INDENT> def __init__(self, text, columns): <NEW_LINE> <INDENT> JTextField.__init__(self, text, columns) <NEW_LINE> self.focusGained=lambda e: e.getSource().selectAll() <NEW_LINE> self.focusLost=lambda e: e.getSource().select(0,0) | A JTextField that selects and unselects the text according to the focus | 62598fb526068e7796d4ca38 |
class RureForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model=rure_master <NEW_LINE> exclude =('rure_id', 'rure_name') | ルアーフォーム | 62598fb5aad79263cf42e8b6 |
class FunctionMixin(PyobjMixin): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> if inspect.ismethod(self.obj): <NEW_LINE> <INDENT> name = 'setup_method' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = 'setup_function' <NEW_LINE> <DEDENT> if isinstance(self.parent, Instance): <NEW_LINE> <INDENT> obj = self.parent.newinstance() <NEW_LINE> self.obj = self._getobj() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj = self.parent.obj <NEW_LINE> <DEDENT> setup_func_or_method = getattr(obj, name, None) <NEW_LINE> if setup_func_or_method is not None: <NEW_LINE> <INDENT> setup_func_or_method(self.obj) <NEW_LINE> <DEDENT> <DEDENT> def teardown(self): <NEW_LINE> <INDENT> if inspect.ismethod(self.obj): <NEW_LINE> <INDENT> name = 'teardown_method' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = 'teardown_function' <NEW_LINE> <DEDENT> obj = self.parent.obj <NEW_LINE> teardown_func_or_meth = getattr(obj, name, None) <NEW_LINE> if teardown_func_or_meth is not None: <NEW_LINE> <INDENT> teardown_func_or_meth(self.obj) <NEW_LINE> <DEDENT> <DEDENT> def _prunetraceback(self, traceback): <NEW_LINE> <INDENT> if hasattr(self, '_obj') and not self.config.option.fulltrace: <NEW_LINE> <INDENT> code = py.code.Code(self.obj) <NEW_LINE> path, firstlineno = code.path, code.firstlineno <NEW_LINE> ntraceback = traceback.cut(path=path, firstlineno=firstlineno) <NEW_LINE> if ntraceback == traceback: <NEW_LINE> <INDENT> ntraceback = ntraceback.cut(path=path) <NEW_LINE> if ntraceback == traceback: <NEW_LINE> <INDENT> ntraceback = ntraceback.cut(excludepath=py._pydir) <NEW_LINE> <DEDENT> <DEDENT> traceback = ntraceback.filter() <NEW_LINE> <DEDENT> return traceback <NEW_LINE> <DEDENT> def repr_failure(self, excinfo, outerr=None): <NEW_LINE> <INDENT> assert outerr is None, "XXX outerr usage is deprecated" <NEW_LINE> return self._repr_failure_py(excinfo) <NEW_LINE> <DEDENT> shortfailurerepr = "F" | mixin for the code common to Function and Generator.
| 62598fb523849d37ff851195 |
class ResourceNotFoundError(Fault): <NEW_LINE> <INDENT> def __init__(self, fault_object, fault_string="Requested resource %r not found"): <NEW_LINE> <INDENT> Fault.__init__(self, 'Client.ResourceNotFound', fault_string % fault_object) | Raised when requested resource is not found. | 62598fb5be383301e02538dd |
class TestEquiv_basic_APIError(HttpEquivalenceTest, HttpTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> HttpTest.setUp(self) <NEW_LINE> @rest.rest_call('GET', '/some_error', Schema({})) <NEW_LINE> def some_error(): <NEW_LINE> <INDENT> self.api_call() <NEW_LINE> <DEDENT> <DEDENT> def api_call(self): <NEW_LINE> <INDENT> raise rest.APIError("Basic test of the APIError code.") <NEW_LINE> <DEDENT> def request(self): <NEW_LINE> <INDENT> return self.client.get('/v0/some_error') | Basic test to make sure the APIError handling code is excercised. | 62598fb563b5f9789fe8524e |
class WorkflowTrigger(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Type = None <NEW_LINE> self.CosFileUploadTrigger = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Type = params.get("Type") <NEW_LINE> if params.get("CosFileUploadTrigger") is not None: <NEW_LINE> <INDENT> self.CosFileUploadTrigger = CosFileUploadTrigger() <NEW_LINE> self.CosFileUploadTrigger._deserialize(params.get("CosFileUploadTrigger")) | Input rule. If an uploaded video hits the rule, the workflow will be triggered.
| 62598fb55fcc89381b2661bd |
class LimitedSpeedNHLIntegrator(MultipleTimeScaleIntegrator): <NEW_LINE> <INDENT> def __init__(self, stepSize, loops, temperature, timeScale, frictionConstant, **kwargs): <NEW_LINE> <INDENT> L = kwargs.pop('L', 1) <NEW_LINE> move = propagators.LimitedSpeedNHLPropagator(temperature, timeScale, frictionConstant, L, 'move') <NEW_LINE> boost = propagators.LimitedSpeedNHLPropagator(temperature, timeScale, frictionConstant, L, 'boost') <NEW_LINE> bath = propagators.LimitedSpeedNHLPropagator(temperature, timeScale, frictionConstant, L, 'bath') <NEW_LINE> super().__init__(stepSize, loops, move, boost, bath, **kwargs) <NEW_LINE> self.addComputePerDof('v', 'sqrt(LkT/m)*tanh(p)') <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> kT = self.getGlobalVariableByName('kT') <NEW_LINE> Q_eta = self.getGlobalVariableByName('Q_eta') <NEW_LINE> sigma = math.sqrt(kT/Q_eta) <NEW_LINE> v_eta = self.getPerDofVariableByName('v_eta') <NEW_LINE> for i in range(len(v_eta)): <NEW_LINE> <INDENT> v_eta[i] = sigma*self._normalVec() <NEW_LINE> <DEDENT> self.setPerDofVariableByName('v_eta', v_eta) <NEW_LINE> p = self.getPerDofVariableByName('p') <NEW_LINE> for i in range(len(v_eta)): <NEW_LINE> <INDENT> p[i] = self._normalVec() <NEW_LINE> <DEDENT> self.setPerDofVariableByName('p', p) | Parameters
----------
stepSize : unit.Quantity
The largest time step for numerically integrating the system of equations.
loops : list(int)
See description in :class:`MultipleTimeScaleIntegrator`.
temperature : unit.Quantity
The temperature to which the configurational sampling should correspond.
frictionConstant : unit.Quantity
The friction constant :math:`\gamma` present in the stochastic equation of motion for
per-DOF thermostat variable :math:`v_2`.
**kwargs : keyword arguments
The same keyword arguments of class :class:`MultipleTimeScaleIntegrator` apply here. | 62598fb532920d7e50bc6136 |
class BladeConfig(object): <NEW_LINE> <INDENT> def __init__(self, current_source_dir): <NEW_LINE> <INDENT> self.current_source_dir = current_source_dir <NEW_LINE> self.configs = { 'cc_test_config' : { 'dynamic_link' : False, 'heap_check' : '', 'gperftools_lib' : '#tcmalloc', 'gperftools_debug_lib' : '#tcmalloc_debug', 'gtest_lib' : 'thirdparty/gtest:gtest', 'gtest_main_lib' : 'thirdparty/gtest:gtest_main' }, 'distcc_config' : { 'enabled' : False }, 'link_config' : { 'link_on_tmp' : False, 'enable_dccc' : False }, 'java_config' : { 'source_version' : '', 'target_version' : '' }, 'protoc_config' : { 'protoc' : '/usr/local/bin/protoc', 'protobuf_lib': 'thirdparty/protobuf:protobuf', 'protobuf_path' : 'thirdparty', 'protobuf_include_path' : '/usr/local/include/google', 'protobuf_php_path' : 'thirdparty/Protobuf-PHP/library', 'protoc_php_plugin' : 'thirdparty/Protobuf-PHP/protoc-gen-php.php', }, 'cc_config' : { 'extra_incs' : 'thirdparty' } } <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bladerc_file = os.path.expanduser("~/.bladerc") <NEW_LINE> if os.path.exists(bladerc_file): <NEW_LINE> <INDENT> execfile(bladerc_file) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> error_exit("Parse error in config file bladerc, exit...\n%s" % traceback.format_exc()) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> execfile(os.path.join(self.current_source_dir, 'BLADE_ROOT')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> error_exit("Parse error in config file BLADE_ROOT, exit...\n%s" % traceback.format_exc()) <NEW_LINE> <DEDENT> <DEDENT> def update_config(self, section_name, user_configs): <NEW_LINE> <INDENT> configs = self.configs.get(section_name, {}) <NEW_LINE> if configs: <NEW_LINE> <INDENT> configs.update(user_configs) <NEW_LINE> <DEDENT> <DEDENT> def get_config(self, section_name): <NEW_LINE> <INDENT> return self.configs.get(section_name, {}) | BladeConfig. A configuration parser class. | 62598fb5498bea3a75a57c03 |
class linear_interpolated_rv_2D(object): <NEW_LINE> <INDENT> def __init__(self, x, y, distribution): <NEW_LINE> <INDENT> self._x = x[:,0] <NEW_LINE> self._y = y[0,:] <NEW_LINE> area_under_curve = trapz(trapz(distribution, axis=1), axis=0) <NEW_LINE> self._pdf = distribution / area_under_curve <NEW_LINE> self._ycdf = cumtrapz(self._pdf, axis=1, initial=0) <NEW_LINE> self._ypdf = self._pdf / self._ycdf[:,-1][:,newaxis] <NEW_LINE> self._ycdf /= self._ycdf[:,-1][:,newaxis] <NEW_LINE> self._xpdf = trapz(self._pdf, axis=1) <NEW_LINE> self._xcdf = cumtrapz(self._xpdf, axis=0, initial=0) <NEW_LINE> <DEDENT> def rvs(self, samples=1): <NEW_LINE> <INDENT> x_uniform = random_sample(samples) <NEW_LINE> ix = self._xcdf.searchsorted(x_uniform) <NEW_LINE> dx = ((-self._xpdf[ix-1] + np.sqrt(self._xpdf[ix-1]**2 + 2 * (self._xpdf[ix] - self._xpdf[ix-1]) * (x_uniform - self._xcdf[ix-1]))) / (self._xpdf[ix] - self._xpdf[ix-1])) <NEW_LINE> x = self._x[ix-1] + dx * (self._x[ix] - self._x[ix-1]) <NEW_LINE> interp_cdf = (self._ycdf[ix-1,:] * (1.0 - dx[:,newaxis]) + dx[:,newaxis] * (self._ycdf[ix,:])) <NEW_LINE> interp_pdf = (self._ypdf[ix-1,:] * (1.0 - dx[:,newaxis]) + dx[:,newaxis] * (self._ypdf[ix,:])) <NEW_LINE> y_uniform = random_sample(samples) <NEW_LINE> jy = np.empty(y_uniform.shape, dtype=int) <NEW_LINE> for j, sample in enumerate(y_uniform): <NEW_LINE> <INDENT> jy[j] = interp_cdf[j,:].searchsorted(sample) <NEW_LINE> <DEDENT> iy = np.arange(0,samples) <NEW_LINE> dy = ((-interp_pdf[iy,jy-1] + np.sqrt(interp_pdf[iy,jy-1]**2 + 2 * (interp_pdf[iy,jy] - interp_pdf[iy,jy-1]) * (y_uniform - interp_cdf[iy,jy-1]))) / (interp_pdf[iy,jy] - interp_pdf[iy,jy-1])) <NEW_LINE> y = self._y[jy-1] + dy * (self._y[jy] - self._y[jy-1]) <NEW_LINE> return x, y | Contrtuct a 2D distribution assuming linear interpolation from discrete
data. | 62598fb566656f66f7d5a4d3 |
class SpkirAbjCsppInstrumentDataParticle(DataParticle): <NEW_LINE> <INDENT> def _build_parsed_values(self): <NEW_LINE> <INDENT> results = [] <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.PROFILER_TIMESTAMP, self.raw_data.group(DataMatchesGroupNumber.PROFILER_TIMESTAMP), numpy.float)) <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.PRESSURE, self.raw_data.group(DataMatchesGroupNumber.PRESSURE), float)) <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.SUSPECT_TIMESTAMP, self.raw_data.group(DataMatchesGroupNumber.SUSPECT_TIMESTAMP), encode_y_or_n)) <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.TIMER, self.raw_data.group(DataMatchesGroupNumber.TIMER), numpy.float)) <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.SAMPLE_DELAY, self.raw_data.group(DataMatchesGroupNumber.SAMPLE_DELAY), int)) <NEW_LINE> channel_array = [int(self.raw_data.group(DataMatchesGroupNumber.CHANNEL_1)), int(self.raw_data.group(DataMatchesGroupNumber.CHANNEL_2)), int(self.raw_data.group(DataMatchesGroupNumber.CHANNEL_3)), int(self.raw_data.group(DataMatchesGroupNumber.CHANNEL_4)), int(self.raw_data.group(DataMatchesGroupNumber.CHANNEL_5)), int(self.raw_data.group(DataMatchesGroupNumber.CHANNEL_6)), int(self.raw_data.group(DataMatchesGroupNumber.CHANNEL_7))] <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.CHANNEL_ARRAY, channel_array, list)) <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.VIN_SENSE, self.raw_data.group(DataMatchesGroupNumber.VIN), int)) <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.VA_SENSE, self.raw_data.group(DataMatchesGroupNumber.VA), int)) <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.INTERNAL_TEMPERATURE, self.raw_data.group(DataMatchesGroupNumber.VA), int)) <NEW_LINE> results.append(self._encode_value(SpkirAbjCsppParserDataParticleKey.FRAME_COUNTER, self.raw_data.group(DataMatchesGroupNumber.FRAME_COUNTER), int)) <NEW_LINE> internal_timestamp_unix = numpy.float(self.raw_data.group( DataMatchesGroupNumber.PROFILER_TIMESTAMP)) <NEW_LINE> self.set_internal_timestamp(unix_time=internal_timestamp_unix) <NEW_LINE> return results | Base Class for building a spkir_abj_cspp instrument data particle | 62598fb556ac1b37e63022cd |
class OrderedDict(Dict): <NEW_LINE> <INDENT> pass | An (ordered) dictionary of objects | 62598fb597e22403b383afe8 |
class UpdateProductRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ProductId = None <NEW_LINE> self.Name = None <NEW_LINE> self.Description = None <NEW_LINE> self.DataTemplate = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ProductId = params.get("ProductId") <NEW_LINE> self.Name = params.get("Name") <NEW_LINE> self.Description = params.get("Description") <NEW_LINE> self.DataTemplate = params.get("DataTemplate") | UpdateProduct请求参数结构体
| 62598fb57c178a314d78d580 |
class MainnetDAOValidatorVM(HomesteadVM): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def validate_header(cls, header: BlockHeader, previous_header: BlockHeader, check_seal: bool=True) -> None: <NEW_LINE> <INDENT> super().validate_header(header, previous_header, check_seal) <NEW_LINE> dao_fork_at = cls.get_dao_fork_block_number() <NEW_LINE> extra_data_block_nums = range(dao_fork_at, dao_fork_at + 10) <NEW_LINE> if header.block_number in extra_data_block_nums: <NEW_LINE> <INDENT> if cls.support_dao_fork and header.extra_data != DAO_FORK_MAINNET_EXTRA_DATA: <NEW_LINE> <INDENT> raise ValidationError( "Block {!r} must have extra data {} not {} when supporting DAO fork".format( header, encode_hex(DAO_FORK_MAINNET_EXTRA_DATA), encode_hex(header.extra_data), ) ) <NEW_LINE> <DEDENT> elif not cls.support_dao_fork and header.extra_data == DAO_FORK_MAINNET_EXTRA_DATA: <NEW_LINE> <INDENT> raise ValidationError( "Block {!r} must not have extra data {} when declining the DAO fork".format( header, encode_hex(DAO_FORK_MAINNET_EXTRA_DATA), ) ) | Only on mainnet, TheDAO fork is accompanied by special extra data. Validate those headers | 62598fb5a79ad1619776a14f |
class PDAConfiguration(collections.namedtuple( 'PDAConfiguration', ['state', 'remaining_input', 'stack'] )): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return '\n{}(\'{}\', \'{}\', {})'.format( self.__class__.__name__, self.state, self.remaining_input, self.stack ) | A configuration is a triple of current state, remaining input and stack.
It represents the complete runtime state of a PDA.
It is hashable and immutable. | 62598fb57cff6e4e811b5b02 |
class OneClassSVM(BaseLibSVM): <NEW_LINE> <INDENT> def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, nu=0.5, shrinking=True, cache_size=200, verbose=False, max_iter=-1, random_state=None): <NEW_LINE> <INDENT> super(OneClassSVM, self).__init__( 'one_class', kernel, degree, gamma, coef0, tol, 0., nu, 0., shrinking, False, cache_size, None, verbose, max_iter, random_state) <NEW_LINE> <DEDENT> def fit(self, X, sample_weight=None, **params): <NEW_LINE> <INDENT> super(OneClassSVM, self).fit(X, [], sample_weight=sample_weight, **params) <NEW_LINE> return self | Unsupervised Outliers Detection.
Estimate the support of a high-dimensional distribution.
The implementation is based on libsvm.
Parameters
----------
kernel : string, optional (default='rbf')
Specifies the kernel type to be used in the algorithm.
It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or
a callable.
If none is given, 'rbf' will be used. If a callable is given it is
used to precompute the kernel matrix.
nu : float, optional
An upper bound on the fraction of training
errors and a lower bound of the fraction of support
vectors. Should be in the interval (0, 1]. By default 0.5
will be taken.
degree : int, optional
Degree of kernel function. Significant only in poly, rbf, sigmoid.
gamma : float, optional (default=0.0)
kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features
will be taken.
coef0 : float, optional
Independent term in kernel function. It is only significant in
poly/sigmoid.
tol : float, optional
Tolerance for stopping criterion.
shrinking: boolean, optional
Whether to use the shrinking heuristic.
cache_size : float, optional
Specify the size of the kernel cache (in MB)
verbose : bool, default: False
Enable verbose output. Note that this setting takes advantage of a
per-process runtime setting in libsvm that, if enabled, may not work
properly in a multithreaded context.
max_iter : int, optional (default=-1)
Hard limit on iterations within solver, or -1 for no limit.
random_state : int seed, RandomState instance, or None (default)
The seed of the pseudo random number generator to use when
shuffling the data for probability estimation.
Attributes
----------
`support_` : array-like, shape = [n_SV]
Index of support vectors.
`support_vectors_` : array-like, shape = [nSV, n_features]
Support vectors.
`dual_coef_` : array, shape = [n_classes-1, n_SV]
Coefficient of the support vector in the decision function.
`coef_` : array, shape = [n_classes-1, n_features]
Weights asigned to the features (coefficients in the primal
problem). This is only available in the case of linear kernel.
`coef_` is readonly property derived from `dual_coef_` and
`support_vectors_`
`intercept_` : array, shape = [n_classes-1]
Constants in decision function. | 62598fb557b8e32f5250818e |
class AddonPremium(amo.models.ModelBase): <NEW_LINE> <INDENT> addon = models.OneToOneField('addons.Addon') <NEW_LINE> price = models.ForeignKey(Price, blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'addons_premium' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'Premium %s: %s' % (self.addon, self.price) <NEW_LINE> <DEDENT> def has_price(self): <NEW_LINE> <INDENT> return self.price is not None and bool(self.price.price) <NEW_LINE> <DEDENT> def get_price(self, currency=None): <NEW_LINE> <INDENT> return self.price.get_price(currency=currency) <NEW_LINE> <DEDENT> def get_price_locale(self, currency=None): <NEW_LINE> <INDENT> return self.price.get_price_locale(currency=currency) <NEW_LINE> <DEDENT> def is_complete(self): <NEW_LINE> <INDENT> return bool(self.addon and self.price and self.addon.paypal_id and self.addon.support_email) <NEW_LINE> <DEDENT> def supported_currencies(self): <NEW_LINE> <INDENT> return self.price.currencies() | Additions to the Addon model that only apply to Premium add-ons. | 62598fb57047854f4633f4be |
class TransporterParser(object): <NEW_LINE> <INDENT> line_pattern = re.compile(r"(\S*)(?:\s*([\d\.]*))?(?:\s*co\((\S*)\))?") <NEW_LINE> name_pattern = re.compile(r"[^_]*_([^_]*)_") <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.clear() <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.transporters = [] <NEW_LINE> <DEDENT> def parse(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> line_no = 0 <NEW_LINE> with open(filename) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> line_no += 1 <NEW_LINE> line = line.strip() <NEW_LINE> if line == "" or line[0] == "#": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> m = self.line_pattern.match(line) <NEW_LINE> transname = m.group(1) <NEW_LINE> transfac = m.group(2) <NEW_LINE> if transfac == "": <NEW_LINE> <INDENT> transfac = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> transfac = float(transfac) <NEW_LINE> <DEDENT> cotrans = m.group(3) <NEW_LINE> self.transporters.append((transname, transfac, cotrans)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("Illegal float value %s in line %u of transporter " "file." % (transfac, line_no)) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise SyntaxError("Syntax error in line %u of transporter file." % line_no) <NEW_LINE> <DEDENT> return self.transporters <NEW_LINE> <DEDENT> def split_by_type(self, l=None): <NEW_LINE> <INDENT> if l is None: <NEW_LINE> <INDENT> l = self.transporters <NEW_LINE> <DEDENT> dict_of_types = {} <NEW_LINE> list_of_lists = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for entry in l: <NEW_LINE> <INDENT> m = self.name_pattern.match(entry[0]) <NEW_LINE> typ = m.group(1) <NEW_LINE> if typ not in dict_of_types: <NEW_LINE> <INDENT> dict_of_types[typ] = len(list_of_lists) <NEW_LINE> list_of_lists.append([(typ,)+entry]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> list_of_lists[dict_of_types[typ]].append((typ,)+entry) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise SyntaxError("Malformed transporter name: %s (cannot identify " "typ)" % entry[0]) <NEW_LINE> <DEDENT> return list_of_lists | Parser for transporter files.
It reads lines of the format
<name> [<factor>] [co(<name>)]
into a list. Lines beginning with a # sign are ignored | 62598fb53346ee7daa3376b9 |
class BaseHandlerI18NTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.options = {} <NEW_LINE> mock_request = Mock() <NEW_LINE> mock_request.options = self.options <NEW_LINE> mock_request.environ = {"route_args": {}} <NEW_LINE> self.handler = handler_factory(BaseHandler, mock_request) <NEW_LINE> assert isinstance(self.handler, BaseHandler) <NEW_LINE> <DEDENT> def test_locale(self): <NEW_LINE> <INDENT> self.handler.route_args["locale"] = "en" <NEW_LINE> assert "en" == self.handler.locale <NEW_LINE> <DEDENT> def test_no_locale(self): <NEW_LINE> <INDENT> assert "" == self.handler.locale <NEW_LINE> <DEDENT> def test_translations(self): <NEW_LINE> <INDENT> translations_manager = {"en": "en-trans", "uk": "uk-trans"} <NEW_LINE> self.handler.route_args["locale"] = "uk" <NEW_LINE> self.options["translations_manager"] = translations_manager <NEW_LINE> assert "uk-trans" == self.handler.translations <NEW_LINE> <DEDENT> def test_translation(self): <NEW_LINE> <INDENT> assert null_translations == self.handler.translation <NEW_LINE> <DEDENT> def test_gettext(self): <NEW_LINE> <INDENT> assert "x" == self.handler.gettext("x") <NEW_LINE> <DEDENT> def test_gettext2(self): <NEW_LINE> <INDENT> assert "x" == self.handler._("x") | Test the ``BaseHandler`` i18n. | 62598fb510dbd63aa1c70c9a |
class TestCoprsWorkerCreate(Base): <NEW_LINE> <INDENT> expected_title = "copr.worker.create" <NEW_LINE> expected_subti = "a new worker was created" <NEW_LINE> expected_packages = set([]) <NEW_LINE> expected_usernames = set([]) <NEW_LINE> expected_objects = set([ 'coprs/worker.create', ]) <NEW_LINE> msg = { u'username': u'copr', u'i': 1, u'timestamp': 1383956077.2320001, u'msg_id': u'2013-675e7b1e-9b7f-4d11-be2f-2b3845817d60', u'topic': u'org.fedoraproject.prod.copr.worker.create', u'msg': { u'what': u'creating worker: 172.16.3.3', u'ip': u'172.16.3.3', }, } | `Copr <https://fedorahosted.org/copr/>`_ publishes these messages
when a new worker is spun up. | 62598fb5ec188e330fdf8974 |
class VerificationCodeModifyPassword(FactoryBase): <NEW_LINE> <INDENT> title = '吃货商城用户密码修改提醒' <NEW_LINE> content = '亲爱的【吃货商城】用户,您正在为您的账户修改密码,您的修改密码的短信验证码为%(code)s,' '有效期10分钟,如非本人操作,请勿理睬!' <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> return self.factory(serializer.validated_data, func_list=self.FUNC_LIST_EXIST, template_code=TEMPLATES_CODE_REGISTER) | 手机验证 | 62598fb5aad79263cf42e8b8 |
class DownloaderActor(pykka.gevent.GeventActor): <NEW_LINE> <INDENT> def __init__(self, librarian): <NEW_LINE> <INDENT> super(DownloaderActor, self).__init__() <NEW_LINE> self.librarian = librarian <NEW_LINE> <DEDENT> def download_song(self, song): <NEW_LINE> <INDENT> base_filepath = self.librarian.get_base_filepath(song) <NEW_LINE> output_template = base_filepath + ".%(ext)s" <NEW_LINE> logger.info("attempting to download %s from %s to %s", song, song.video_watch_url, base_filepath) <NEW_LINE> try: <NEW_LINE> <INDENT> self._download_video(song.video_watch_url, output_template) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logger.exception("download of %s from %s failed", song, song.video_watch_url) <NEW_LINE> self.librarian.notify_download_failed(song) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.info("download of %s completed", song) <NEW_LINE> self.librarian.notify_download_completed(song) <NEW_LINE> <DEDENT> <DEDENT> def download_other_video(self, video): <NEW_LINE> <INDENT> base_dir = self.librarian.get_others_dir() <NEW_LINE> logger.info("attempting to download other video %s to %s", video, base_dir) <NEW_LINE> output_template = path.join(base_dir, "%(title)s-%(id)s.%(ext)s") <NEW_LINE> self._download_video(video['videoURL'], output_template) <NEW_LINE> <DEDENT> def _download_video(self, video_watch_url, output_template): <NEW_LINE> <INDENT> command = ['youtube-dl', '-o', output_template, '--no-progress', '--no-mtime', '-c', video_watch_url] <NEW_LINE> popen = gevent.subprocess.Popen(command) <NEW_LINE> self.subprocess = popen <NEW_LINE> resultcode = popen.wait() <NEW_LINE> self.subprocess = None <NEW_LINE> if resultcode != 0: <NEW_LINE> <INDENT> raise Exception("subcommand %s returned non-zero exit code %s", command, resultcode) | Given a URL where a music video can be watched, downloads the video file.
This implementation uses the rather excellent YoutubeDL. | 62598fb55fc7496912d482ed |
class ApiError(Exception): <NEW_LINE> <INDENT> def __init__(self, error, data='', message=''): <NEW_LINE> <INDENT> super(ApiError, self).__init__(message) <NEW_LINE> self.error = error <NEW_LINE> self.data = data <NEW_LINE> self.message = message | the base ApiError which contains error(required), data(optional) and message(optional) | 62598fb5b7558d5895463711 |
class UbuntuOneLauncherUnity(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.entry = Unity.LauncherEntry.get_for_desktop_id(U1_DOTDESKTOP) <NEW_LINE> <DEDENT> def show_progressbar(self): <NEW_LINE> <INDENT> self.entry.set_property('progress_visible', True) <NEW_LINE> <DEDENT> def hide_progressbar(self): <NEW_LINE> <INDENT> self.entry.set_property('progress_visible', False) <NEW_LINE> <DEDENT> def set_progress(self, value): <NEW_LINE> <INDENT> self.entry.set_property('progress', value) <NEW_LINE> <DEDENT> def set_urgent(self, value=True): <NEW_LINE> <INDENT> self.entry.set_property('urgent', value) <NEW_LINE> <DEDENT> def set_count(self, value): <NEW_LINE> <INDENT> self.entry.set_property('count', value) <NEW_LINE> <DEDENT> def show_count(self): <NEW_LINE> <INDENT> self.entry.set_property('count_visible', True) <NEW_LINE> <DEDENT> def hide_count(self): <NEW_LINE> <INDENT> self.entry.set_property('count_visible', False) | The Magicicada launcher icon. | 62598fb53539df3088ecc390 |
class CalendarViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Calendar.objects.all() <NEW_LINE> serializer_class = CalendarSerializer | API endpoint that allows calendars to be viewed or edited. | 62598fb523849d37ff851197 |
class Preorder: <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def _leq(self, set1, set2): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def compare(self, set1, set2): <NEW_LINE> <INDENT> if set1 == set2: <NEW_LINE> <INDENT> return OrderResult.EQUAL <NEW_LINE> <DEDENT> if self._leq(set1, set2): <NEW_LINE> <INDENT> if self._leq(set2, set1): <NEW_LINE> <INDENT> return OrderResult.EQUIVALENT <NEW_LINE> <DEDENT> return OrderResult.LEQ <NEW_LINE> <DEDENT> if self._leq(set2, set1): <NEW_LINE> <INDENT> return OrderResult.GEQ <NEW_LINE> <DEDENT> return OrderResult.INCOMPARABLE | Represents an abstract preorder | 62598fb5f9cc0f698b1c533e |
class MockRenewer(RenewingAuthorizer): <NEW_LINE> <INDENT> def __init__(self, token_data, **kwargs): <NEW_LINE> <INDENT> self.token_data = token_data <NEW_LINE> self.token_response = mock.Mock() <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def _get_token_response(self): <NEW_LINE> <INDENT> return self.token_response <NEW_LINE> <DEDENT> def _extract_token_data(self, res): <NEW_LINE> <INDENT> return self.token_data | Class that implements RenewingAuthorizer so that _get_token_response and
_extract_token_data can return known values for testing | 62598fb5627d3e7fe0e06f94 |
class CashOnDeliveryLineBuilder(Component): <NEW_LINE> <INDENT> _name = 'ecommerce.order.line.builder.cod' <NEW_LINE> _inherit = 'ecommerce.order.line.builder' <NEW_LINE> _usage = 'order.line.builder.cod' <NEW_LINE> def __init__(self, work_context): <NEW_LINE> <INDENT> super(CashOnDeliveryLineBuilder, self).__init__(work_context) <NEW_LINE> self.product_ref = ('connector_ecommerce', 'product_product_cash_on_delivery') <NEW_LINE> self.sequence = 995 | Return values for a Cash on Delivery line | 62598fb55fdd1c0f98e5e072 |
class AddCourseDetailsModel(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_course_page_title(): <NEW_LINE> <INDENT> return page_identifier['identifier'].get('web_page_title') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_fullname_field_xpath(): <NEW_LINE> <INDENT> return fields['full_name'].get('xpath') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_short_name_field_xpath(): <NEW_LINE> <INDENT> return fields['short_name'].get('xpath') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_course_category_field_xpath(): <NEW_LINE> <INDENT> return fields['course_category'].get('xpath') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_course_id_field_xpath(): <NEW_LINE> <INDENT> return fields['course_id'].get('xpath') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_synopsis_field_xpath(): <NEW_LINE> <INDENT> return fields['summary'].get('xpath') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_course_completion_tracking_field_xpath(): <NEW_LINE> <INDENT> return {'caret': fields['completion_tracking']['caret'].get('xpath'), 'dropdown_menu': fields['completion_tracking']['dropdown_menu'].get('xpath') } <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_save_and_continue_xpath_btn(): <NEW_LINE> <INDENT> return btns['save_and_continue_btn'].get('xpath') | Allows the framework to add the details of the course to the input fields.
This done using the classes public methods. | 62598fb55166f23b2e2434c0 |
class CredentialManager: <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getcredentials(self, host, login=None): <NEW_LINE> <INDENT> return self.badcredentials(host, login) <NEW_LINE> <DEDENT> def badcredentials(self, host, login=None): <NEW_LINE> <INDENT> print("What credential should I use to connect to", host,"?") <NEW_LINE> inputlogin = getinput("".join(("Login", "" if not login else " [default: %s]" % login, ": "))) or login <NEW_LINE> password = getpass.getpass("Password: ") <NEW_LINE> return (inputlogin, password) <NEW_LINE> <DEDENT> def knownhosts(self): <NEW_LINE> <INDENT> return [] | Base class for a PasswordManager, that always asks | 62598fb59c8ee823130401e5 |
class PQ(object): <NEW_LINE> <INDENT> def __init__(self, capacity): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def N(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def isEmpty(self): <NEW_LINE> <INDENT> return self.N == 0 <NEW_LINE> <DEDENT> def insert(self, x): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def top(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def delTop(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _less(self, i, j): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _exch(self, i, j): <NEW_LINE> <INDENT> raise NotImplementedError() | abstract class of PQ | 62598fb5460517430c4320cf |
class AirBrushTool(DataTool): <NEW_LINE> <INDENT> only2d = False <NEW_LINE> def __init__(self, parent, plot): <NEW_LINE> <INDENT> super().__init__(parent, plot) <NEW_LINE> self.__timer = QTimer(self, interval=50) <NEW_LINE> self.__timer.timeout.connect(self.__timout) <NEW_LINE> self.__count = itertools.count() <NEW_LINE> self.__pos = None <NEW_LINE> <DEDENT> def mousePressEvent(self, event): <NEW_LINE> <INDENT> if event.button() == Qt.LeftButton: <NEW_LINE> <INDENT> self.editingStarted.emit() <NEW_LINE> self.__pos = self.mapToPlot(event.pos()) <NEW_LINE> self.__timer.start() <NEW_LINE> return True <NEW_LINE> <DEDENT> return super().mousePressEvent(event) <NEW_LINE> <DEDENT> def mouseMoveEvent(self, event): <NEW_LINE> <INDENT> if event.buttons() & Qt.LeftButton: <NEW_LINE> <INDENT> self.__pos = self.mapToPlot(event.pos()) <NEW_LINE> return True <NEW_LINE> <DEDENT> return super().mouseMoveEvent(event) <NEW_LINE> <DEDENT> def mouseReleaseEvent(self, event): <NEW_LINE> <INDENT> if event.button() == Qt.LeftButton: <NEW_LINE> <INDENT> self.__timer.stop() <NEW_LINE> self.editingFinished.emit() <NEW_LINE> return True <NEW_LINE> <DEDENT> return super().mouseReleaseEvent(event) <NEW_LINE> <DEDENT> def __timout(self): <NEW_LINE> <INDENT> self.issueCommand.emit( AirBrush(self.__pos, None, None, next(self.__count)) ) | Add points with an 'air brush'. | 62598fb5d486a94d0ba2c0b6 |
class EntryList(Resource): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> parser = reqparse.RequestParser() <NEW_LINE> parser.add_argument( 'title', type=str, required=True, help='Entry title required please!') <NEW_LINE> parser.add_argument( 'notes', type=str, required=True, ) <NEW_LINE> args = parser.parse_args() <NEW_LINE> title = args['title'] <NEW_LINE> notes = args['notes'] <NEW_LINE> entry = Entry(title, notes) <NEW_LINE> if len(title.strip()) < 5: <NEW_LINE> <INDENT> return make_response(jsonify( {'message': 'Please enter a valid entry title.'}), 400) <NEW_LINE> <DEDENT> resp = entry.create_entry() <NEW_LINE> if not resp['status']: <NEW_LINE> <INDENT> return make_response(jsonify({ "message": resp['message'] }), 400) <NEW_LINE> <DEDENT> return make_response(jsonify({ "message": resp['message'] }), 201) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> entries = [] <NEW_LINE> for entry in ENTRIES: <NEW_LINE> <INDENT> entry_data = { "id": entry.id, "title": entry.title, "notes": entry.notes, "date_created": entry.date_created } <NEW_LINE> entries.append(entry_data) <NEW_LINE> <DEDENT> return make_response(jsonify({"Entries": entries}), 200) | Handles operations on an Entry | 62598fb5377c676e912f6de1 |
class Native (Decl, DeclRepoId): <NEW_LINE> <INDENT> def __init__(self, file, line, mainFile, pragmas, comments, identifier, scopedName, repoId): <NEW_LINE> <INDENT> Decl.__init__(self, file, line, mainFile, pragmas, comments) <NEW_LINE> DeclRepoId.__init__(self, identifier, scopedName, repoId) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Native(%s)" % "::".join(self.scopedName()) <NEW_LINE> <DEDENT> def accept(self, visitor): visitor.visitNative(self) | Native declaration (Decl, DeclRepoId)
Native should not be used in normal IDL.
No non-inherited functions. | 62598fb5d486a94d0ba2c0b7 |
class Scheduler(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def valid_cookie(cycle=settings.CYCLE): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> print ('Cookies检测进程开始') <NEW_LINE> try: <NEW_LINE> <INDENT> for website, cls in settings.TESTER_MAP.items(): <NEW_LINE> <INDENT> tester = eval(cls+'(website="' + website + '")') <NEW_LINE> tester.run() <NEW_LINE> print ('Cookie 检测完成') <NEW_LINE> del tester <NEW_LINE> time.sleep(cycle) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print (e.args) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def generate_cookie(cycle=settings.CYCLE): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> print ('Cookie 生成开始') <NEW_LINE> try: <NEW_LINE> <INDENT> for website, cls in settings.GERERATOR_MAP.items(): <NEW_LINE> <INDENT> generator = eval(cls+'(website="'+website+'")') <NEW_LINE> generator.run() <NEW_LINE> generator.close() <NEW_LINE> time.sleep(cycle) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print (e.args) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def api(): <NEW_LINE> <INDENT> print ('API start') <NEW_LINE> app.run(host=settings.API_HOST, port=settings.API_PORT) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if settings.API_PROCESS: <NEW_LINE> <INDENT> api_process = Process(target=Scheduler.api) <NEW_LINE> api_process.start() <NEW_LINE> <DEDENT> if settings.GENERATOR_PROCESS: <NEW_LINE> <INDENT> generator_process = Process(target=Scheduler.generate_cookie) <NEW_LINE> generator_process.start() <NEW_LINE> <DEDENT> if settings.VALID_PROCESS: <NEW_LINE> <INDENT> valid_process = Process(target=Scheduler.valid_cookie) <NEW_LINE> valid_process.start() | 调度策略 | 62598fb5cc0a2c111447b0f8 |
class RegionalQuotaCapability(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'region_name': {'key': 'regionName', 'type': 'str'}, 'cores_used': {'key': 'coresUsed', 'type': 'long'}, 'cores_available': {'key': 'coresAvailable', 'type': 'long'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(RegionalQuotaCapability, self).__init__(**kwargs) <NEW_LINE> self.region_name = kwargs.get('region_name', None) <NEW_LINE> self.cores_used = kwargs.get('cores_used', None) <NEW_LINE> self.cores_available = kwargs.get('cores_available', None) | The regional quota capacity.
:param region_name: The region name.
:type region_name: str
:param cores_used: The number of cores used in the region.
:type cores_used: long
:param cores_available: The number of cores available in the region.
:type cores_available: long | 62598fb599fddb7c1ca62e5d |
class TreeBuilder(object): <NEW_LINE> <INDENT> def __init__(self, object_store): <NEW_LINE> <INDENT> self.object_store = object_store <NEW_LINE> self.items = {} <NEW_LINE> <DEDENT> def __setitem__(self, lookup_key, value): <NEW_LINE> <INDENT> self.items[lookup_key] = value <NEW_LINE> <DEDENT> def _make_subtree(self, items): <NEW_LINE> <INDENT> if len(items) == 0: <NEW_LINE> <INDENT> raise ValueError("No items to put.") <NEW_LINE> <DEDENT> if len(items) == 1: <NEW_LINE> <INDENT> (key, serialized_obj), = items <NEW_LINE> value_hash = self.object_store.hash_object(serialized_obj) <NEW_LINE> leaf = TreeLeaf(lookup_key=key, payload_hash=value_hash) <NEW_LINE> return [leaf] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> middle = len(items) // 2 <NEW_LINE> pivot_prefix, pivot_obj = items[middle] <NEW_LINE> left_partition = items[:middle] <NEW_LINE> right_partition = items[middle:] <NEW_LINE> left_subtree_nodes = self._make_subtree(left_partition) <NEW_LINE> right_subtree_nodes = self._make_subtree(right_partition) <NEW_LINE> left_hash = None <NEW_LINE> right_hash = None <NEW_LINE> left_hash = self.object_store.hash_object( encode(left_subtree_nodes[0])) <NEW_LINE> right_hash = self.object_store.hash_object( encode(right_subtree_nodes[0])) <NEW_LINE> pivot_node = TreeNode(pivot_prefix=pivot_prefix, left_hash=left_hash, right_hash=right_hash) <NEW_LINE> return [pivot_node] + left_subtree_nodes + right_subtree_nodes <NEW_LINE> <DEDENT> <DEDENT> def commit(self): <NEW_LINE> <INDENT> items = sorted(self.items.items(), key=lambda t: t[0]) <NEW_LINE> nodes = self._make_subtree(items) <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> serialized_node = encode(node) <NEW_LINE> self.object_store.add(serialized_node) <NEW_LINE> <DEDENT> for serialized_obj in self.items.values(): <NEW_LINE> <INDENT> self.object_store.add(serialized_obj) <NEW_LINE> <DEDENT> root_node = nodes[0] <NEW_LINE> root = self.object_store.hash_object(encode(root_node)) <NEW_LINE> return Tree(self.object_store, root) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('TreeBuilder(' 'object_store={self.object_store}, ' 'items={self.items})').format( self=self) | Builder for a key-value Merkle tree.
:param object_store: Object store
You can add items using a dict-like interface:
>>> from .store import Sha256DictStore
>>> store = Sha256DictStore()
>>> builder = TreeBuilder(store)
>>> builder['foo'] = b'bar'
>>> builder['baz'] = b'zez'
>>> tree = builder.commit()
>>> 'foo' in tree
True | 62598fb5167d2b6e312b7058 |
class PayMilitary(Effect): <NEW_LINE> <INDENT> def __init__(self, arg): <NEW_LINE> <INDENT> super(PayMilitary, self).__init__() | Player may place non-Alien military as non-military with -1 cost
One of a few effects that may be broken apart into more general
effects for clarity's sake | 62598fb54527f215b58e9fbb |
class Thesaurus(models.Model): <NEW_LINE> <INDENT> id = models.AutoField( null=False, blank=False, unique=True, primary_key=True) <NEW_LINE> identifier = models.CharField( max_length=255, null=False, blank=False, unique=True) <NEW_LINE> title = models.CharField(max_length=255, null=False, blank=False) <NEW_LINE> date = models.CharField(max_length=20, default='') <NEW_LINE> description = models.TextField(max_length=255, default='') <NEW_LINE> slug = models.CharField(max_length=64, default='') <NEW_LINE> about = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> card_min = models.IntegerField(default=0) <NEW_LINE> card_max = models.IntegerField(default=-1) <NEW_LINE> facet = models.BooleanField(default=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{0}".format(self.identifier) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ("identifier",) <NEW_LINE> verbose_name_plural = 'Thesauri' | Loadable thesaurus containing keywords in different languages | 62598fb510dbd63aa1c70c9c |
class LongTermRetentionPolicy(RetentionPolicy): <NEW_LINE> <INDENT> _validation = { 'retention_policy_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'retention_policy_type': {'key': 'retentionPolicyType', 'type': 'str'}, 'daily_schedule': {'key': 'dailySchedule', 'type': 'DailyRetentionSchedule'}, 'weekly_schedule': {'key': 'weeklySchedule', 'type': 'WeeklyRetentionSchedule'}, 'monthly_schedule': {'key': 'monthlySchedule', 'type': 'MonthlyRetentionSchedule'}, 'yearly_schedule': {'key': 'yearlySchedule', 'type': 'YearlyRetentionSchedule'}, } <NEW_LINE> def __init__( self, *, daily_schedule: Optional["DailyRetentionSchedule"] = None, weekly_schedule: Optional["WeeklyRetentionSchedule"] = None, monthly_schedule: Optional["MonthlyRetentionSchedule"] = None, yearly_schedule: Optional["YearlyRetentionSchedule"] = None, **kwargs ): <NEW_LINE> <INDENT> super(LongTermRetentionPolicy, self).__init__(**kwargs) <NEW_LINE> self.retention_policy_type = 'LongTermRetentionPolicy' <NEW_LINE> self.daily_schedule = daily_schedule <NEW_LINE> self.weekly_schedule = weekly_schedule <NEW_LINE> self.monthly_schedule = monthly_schedule <NEW_LINE> self.yearly_schedule = yearly_schedule | Long term retention policy.
All required parameters must be populated in order to send to Azure.
:ivar retention_policy_type: Required. This property will be used as the discriminator for
deciding the specific types in the polymorphic chain of types.Constant filled by server.
:vartype retention_policy_type: str
:ivar daily_schedule: Daily retention schedule of the protection policy.
:vartype daily_schedule:
~azure.mgmt.recoveryservicesbackup.activestamp.models.DailyRetentionSchedule
:ivar weekly_schedule: Weekly retention schedule of the protection policy.
:vartype weekly_schedule:
~azure.mgmt.recoveryservicesbackup.activestamp.models.WeeklyRetentionSchedule
:ivar monthly_schedule: Monthly retention schedule of the protection policy.
:vartype monthly_schedule:
~azure.mgmt.recoveryservicesbackup.activestamp.models.MonthlyRetentionSchedule
:ivar yearly_schedule: Yearly retention schedule of the protection policy.
:vartype yearly_schedule:
~azure.mgmt.recoveryservicesbackup.activestamp.models.YearlyRetentionSchedule | 62598fb5a17c0f6771d5c31b |
class OrderWidget(QWidget): <NEW_LINE> <INDENT> def __init__(self,connection): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.connection = connection <NEW_LINE> self.product_model = self.connection.current_products() <NEW_LINE> self.order_details = None <NEW_LINE> self.product_table = QTableView() <NEW_LINE> self.product_table.setModel(self.product_model) <NEW_LINE> self.product_table.setSelectionBehavior(1) <NEW_LINE> self.order_item_table = QTableView() <NEW_LINE> self.add_product_button = QPushButton("Add Product") <NEW_LINE> self.remove_product_button = QPushButton("Remove Product") <NEW_LINE> self.order_button_layout = QVBoxLayout() <NEW_LINE> self.order_button_layout.addWidget(self.add_product_button) <NEW_LINE> self.order_button_layout.addWidget(self.remove_product_button) <NEW_LINE> self.layout = QHBoxLayout() <NEW_LINE> self.layout.addWidget(self.order_item_table) <NEW_LINE> self.layout.addLayout(self.order_button_layout) <NEW_LINE> self.layout.addWidget(self.product_table) <NEW_LINE> self.total_layout = QVBoxLayout() <NEW_LINE> self.total_label = QLabel() <NEW_LINE> self.total_layout.addLayout(self.layout) <NEW_LINE> self.total_layout.addWidget(self.total_label) <NEW_LINE> self.setLayout(self.total_layout) <NEW_LINE> self.disable_selection() <NEW_LINE> self.add_product_button.clicked.connect(self.add_product) <NEW_LINE> self.remove_product_button.clicked.connect(self.remove_product) <NEW_LINE> <DEDENT> def add_product(self): <NEW_LINE> <INDENT> selected_indexes = self.product_table.selectedIndexes() <NEW_LINE> product_index = self.product_table.model().data(selected_indexes[0]) <NEW_LINE> self.connection.add_product_to_order_with_details(self.order_details,product_index) <NEW_LINE> self.order_item_table.model().select() <NEW_LINE> self.calculate_total() <NEW_LINE> <DEDENT> def remove_product(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def disable_selection(self): <NEW_LINE> <INDENT> self.product_table.setDisabled(True) <NEW_LINE> self.add_product_button.setDisabled(True) <NEW_LINE> self.remove_product_button.setDisabled(True) <NEW_LINE> <DEDENT> def enable_selection(self): <NEW_LINE> <INDENT> self.product_table.setEnabled(True) <NEW_LINE> self.add_product_button.setEnabled(True) <NEW_LINE> self.remove_product_button.setEnabled(True) <NEW_LINE> self.order_model = self.connection.current_order_items(self.order_details) <NEW_LINE> self.order_item_table.setModel(self.order_model) <NEW_LINE> self.order_item_table.hideColumn(0) <NEW_LINE> self.order_item_table.hideColumn(1) <NEW_LINE> self.order_model.dataChanged.connect(self.calculate_total) <NEW_LINE> <DEDENT> def calculate_total(self): <NEW_LINE> <INDENT> total = self.connection.current_order_total(self.order_details) <NEW_LINE> self.total_label.setText("Total Cost: £{0:.2f}".format(total)) | provides a widget that enables you to create an order full of products | 62598fb5dc8b845886d5369d |
class UseDatabase: <NEW_LINE> <INDENT> def __init__(self, config: dict) -> None: <NEW_LINE> <INDENT> self.configuration = config <NEW_LINE> <DEDENT> """Настройка подключение к базе""" <NEW_LINE> def __enter__(self) -> 'cursor': <NEW_LINE> <INDENT> self.conn = mysql.connector.connect(**self.configuration) <NEW_LINE> self.cursor = self.conn.cursor() <NEW_LINE> return self.cursor <NEW_LINE> <DEDENT> """Заверщающий код""" <NEW_LINE> def __exit__(self, exc_type, exc_val, exc_tb) -> None: <NEW_LINE> <INDENT> self.conn.commit() <NEW_LINE> self.cursor.close() <NEW_LINE> self.conn.close() | Инициализация конфиг файла | 62598fb53539df3088ecc392 |
class DateTime(Date): <NEW_LINE> <INDENT> _represents = datetime <NEW_LINE> format = '%Y-%m-%dT%H:%M:%S' <NEW_LINE> @classmethod <NEW_LINE> def default_offset(cls): <NEW_LINE> <INDENT> return -mktime(datetime(1970, 1, 1).timetuple()) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_offset(cls, value): <NEW_LINE> <INDENT> if value[-1] == 'Z': <NEW_LINE> <INDENT> return value[:-1], 0 <NEW_LINE> <DEDENT> tz = tz_re.search(value) <NEW_LINE> if not tz: <NEW_LINE> <INDENT> return value, 0 <NEW_LINE> <DEDENT> return ( tz_re.sub('', value), (tz.group(2) == '+' and 1 or -1) * (int(tz.group(3)) * 60 + int(tz.group(4))) * 60 ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_tzinfo(cls, offset): <NEW_LINE> <INDENT> class TempTzInfo(tzinfo): <NEW_LINE> <INDENT> def utcoffset(self, dt): <NEW_LINE> <INDENT> return timedelta(seconds=offset) <NEW_LINE> <DEDENT> def dst(self, dt): <NEW_LINE> <INDENT> return timedelta(0) <NEW_LINE> <DEDENT> <DEDENT> return TempTzInfo() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _validate(cls, value): <NEW_LINE> <INDENT> value, offset = cls.get_offset(value) <NEW_LINE> tz = cls.get_tzinfo(offset) <NEW_LINE> try: <NEW_LINE> <INDENT> return cls._parse(value).replace(tzinfo=tz) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> mo = re.search('\\.\d+$', value) <NEW_LINE> if not mo: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> ms = mo.group(0) <NEW_LINE> value = value.replace(ms, '') <NEW_LINE> return cls._parse(value, cls.format). replace(tzinfo=tz, microsecond=int(ms[1:].ljust(6, '0'))) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def serialize(cls, value): <NEW_LINE> <INDENT> if value.tzinfo: <NEW_LINE> <INDENT> delta = value.utcoffset() + value.dst() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> delta = timedelta(seconds=cls.default_offset()) <NEW_LINE> <DEDENT> value = value.replace(tzinfo=cls.get_tzinfo(0)) - delta <NEW_LINE> ms = '' <NEW_LINE> if value.microsecond: <NEW_LINE> <INDENT> ms = '.' + str(value.microsecond).rjust(6, '0') <NEW_LINE> <DEDENT> return super(DateTime, cls).serialize(value) + ms + 'Z' | Represents datetime values, simplified form is ``datetime``, default
``none_value`` is ``None``. | 62598fb563b5f9789fe85252 |
class APIQueryErrorException(): <NEW_LINE> <INDENT> def __init__(self, code, message): <NEW_LINE> <INDENT> self.code = code <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "%s (Error Code: %s)" % (self.message, self.code) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__unicode__() | This is an error returned by the EVE API. See the URL at the top of
this module for how to get an up to date list. | 62598fb5baa26c4b54d4f39e |
class RoutineAddr : <NEW_LINE> <INDENT> def __init__(self, addr) : <NEW_LINE> <INDENT> self.addr = addr <NEW_LINE> <DEDENT> def __repr__(self) : <NEW_LINE> <INDENT> return "RoutineAddr(0x%x)" % self.addr | for showing pointers to methods. | 62598fb521bff66bcd722d4e |
class VerificationIPFlowResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'access': {'key': 'access', 'type': 'str'}, 'rule_name': {'key': 'ruleName', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(VerificationIPFlowResult, self).__init__(**kwargs) <NEW_LINE> self.access = kwargs.get('access', None) <NEW_LINE> self.rule_name = kwargs.get('rule_name', None) | Results of IP flow verification on the target resource.
:param access: Indicates whether the traffic is allowed or denied. Possible values include:
"Allow", "Deny".
:type access: str or ~azure.mgmt.network.v2019_04_01.models.Access
:param rule_name: Name of the rule. If input is not matched against any security rule, it is
not displayed.
:type rule_name: str | 62598fb5498bea3a75a57c07 |
class _HashedCategoricalColumn( _CategoricalColumn, collections.namedtuple('_HashedCategoricalColumn', ['key', 'hash_bucket_size', 'dtype'])): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.key <NEW_LINE> <DEDENT> @property <NEW_LINE> def _parse_example_spec(self): <NEW_LINE> <INDENT> return {self.key: parsing_ops.VarLenFeature(self.dtype)} <NEW_LINE> <DEDENT> def _transform_feature(self, inputs): <NEW_LINE> <INDENT> input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) <NEW_LINE> if not isinstance(input_tensor, sparse_tensor_lib.SparseTensor): <NEW_LINE> <INDENT> raise ValueError('SparseColumn input must be a SparseTensor.') <NEW_LINE> <DEDENT> fc_utils.assert_string_or_int( input_tensor.dtype, prefix='column_name: {} input_tensor'.format(self.key)) <NEW_LINE> if self.dtype.is_integer != input_tensor.dtype.is_integer: <NEW_LINE> <INDENT> raise ValueError( 'Column dtype and SparseTensors dtype must be compatible. ' 'key: {}, column dtype: {}, tensor dtype: {}'.format( self.key, self.dtype, input_tensor.dtype)) <NEW_LINE> <DEDENT> if self.dtype == dtypes.string: <NEW_LINE> <INDENT> sparse_values = input_tensor.values <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sparse_values = string_ops.as_string(input_tensor.values) <NEW_LINE> <DEDENT> sparse_id_values = string_ops.string_to_hash_bucket_fast( sparse_values, self.hash_bucket_size, name='lookup') <NEW_LINE> return sparse_tensor_lib.SparseTensor( input_tensor.indices, sparse_id_values, input_tensor.dense_shape) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _num_buckets(self): <NEW_LINE> <INDENT> return self.hash_bucket_size <NEW_LINE> <DEDENT> def _get_sparse_tensors(self, inputs, weight_collections=None, trainable=None): <NEW_LINE> <INDENT> return _CategoricalColumn.IdWeightPair(inputs.get(self), None) | see `categorical_column_with_hash_bucket`. | 62598fb52c8b7c6e89bd38ab |
class Shape(Circle): <NEW_LINE> <INDENT> def render2(self) : <NEW_LINE> <INDENT> glCallList(self.z+1) <NEW_LINE> <DEDENT> def render(self) : <NEW_LINE> <INDENT> rad = 8 <NEW_LINE> inner = 6 <NEW_LINE> glNewList(self.z+1, GL_COMPILE) <NEW_LINE> glPushMatrix() <NEW_LINE> glTranslatef(self.x, self.y, -self.z) <NEW_LINE> glColor4f (self.color[0], self.color[1],self.color[2], self.color[3]) <NEW_LINE> gluDisk(engine.q, 0, self.width/2, 50, 1) <NEW_LINE> glPushMatrix() <NEW_LINE> glColor4f (0.2, 0.5, 0.2, 0.7) <NEW_LINE> glTranslatef(-self.radius, 0, 0) <NEW_LINE> gluDisk(engine.q, inner, rad, 20, 1) <NEW_LINE> glTranslatef(self.radius, -self.radius, 0) <NEW_LINE> gluDisk(engine.q, inner, rad, 20, 1) <NEW_LINE> glTranslatef(self.radius, self.radius, 0) <NEW_LINE> gluDisk(engine.q, inner, rad, 20, 1) <NEW_LINE> glTranslatef(-self.radius, self.radius, 0) <NEW_LINE> gluDisk(engine.q, inner, rad, 20, 1) <NEW_LINE> glPopMatrix() <NEW_LINE> glPopMatrix() <NEW_LINE> glEndList() <NEW_LINE> self.render = self.render2 | compiles a list and calls it from render. this should be far more eficient but shape remains static
| 62598fb5cc0a2c111447b0f9 |
class OrderMapUtils: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def order_map_to_dataframe(cls, order_map): <NEW_LINE> <INDENT> index = cls.build_order_map_index(order_map) <NEW_LINE> dk = list(order_map.keys())[0]; <NEW_LINE> pk = list(order_map[dk].keys())[0] <NEW_LINE> colnames = order_map[dk][pk][0].__dict__.keys() <NEW_LINE> order_map_list = cls.order_map_list(order_map) <NEW_LINE> return pd.DataFrame(order_map_list, index=index, columns=colnames) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def dataframe_to_order_map(cls, df, order_event_cls): <NEW_LINE> <INDENT> order_map = {} <NEW_LINE> idx_dict = df.to_dict(orient='index') <NEW_LINE> for key, val in idx_dict.items(): <NEW_LINE> <INDENT> idx_split = key.split(",") <NEW_LINE> dk = idx_split[0] <NEW_LINE> pk = int(idx_split[1]) <NEW_LINE> if dk not in order_map: <NEW_LINE> <INDENT> order_map[dk] = dict() <NEW_LINE> <DEDENT> if pk not in order_map[dk]: <NEW_LINE> <INDENT> order_map[dk][pk] = list() <NEW_LINE> <DEDENT> order_map[dk][pk].append(val) <NEW_LINE> <DEDENT> return order_map <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def order_events_to_dataframe(cls, event_list): <NEW_LINE> <INDENT> colnames = event_list[0].__dict__.keys() <NEW_LINE> order_events = list() <NEW_LINE> for i in range(len(event_list)): <NEW_LINE> <INDENT> order_events.append([getattr(event_list[i], j) for j in colnames]) <NEW_LINE> <DEDENT> return pd.DataFrame(order_events, columns=colnames) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def order_map_list(cls, order_map): <NEW_LINE> <INDENT> order_map_list = list() <NEW_LINE> colnames = cls._order_map_colnames(order_map) <NEW_LINE> date_keys = order_map.keys() <NEW_LINE> for dk in date_keys: <NEW_LINE> <INDENT> primkeys = order_map[dk].keys() <NEW_LINE> for pk in primkeys: <NEW_LINE> <INDENT> for i in range(len(order_map[dk][pk])): <NEW_LINE> <INDENT> order_map_list.append( [getattr(order_map[dk][pk][i], j) for j in colnames]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return order_map_list <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def build_order_map_index(cls, order_map): <NEW_LINE> <INDENT> order_map_index = list() <NEW_LINE> date_keys = order_map.keys() <NEW_LINE> for dk in date_keys: <NEW_LINE> <INDENT> primkeys = order_map[dk].keys() <NEW_LINE> for pk in primkeys: <NEW_LINE> <INDENT> for i in range(len(order_map[dk][pk])): <NEW_LINE> <INDENT> order_event = order_map[dk][pk][i] <NEW_LINE> event_id = getattr(order_event, 'event_id') <NEW_LINE> order_map_index.append("%s,%d,%d" % (dk, pk, event_id)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return order_map_index <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _order_map_colnames(cls, order_map): <NEW_LINE> <INDENT> dk = list(order_map.keys())[0]; <NEW_LINE> pk = list(order_map[dk].keys())[0] <NEW_LINE> return order_map[dk][pk][0].__dict__.keys() | Utilities for order map | 62598fb571ff763f4b5e785b |
class Component(type): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> def __new__(cls, name, bases, dct): <NEW_LINE> <INDENT> component_class = super().__new__(cls, name, bases, dct) <NEW_LINE> component_class.component_id = cls.count <NEW_LINE> cls.count += 1 <NEW_LINE> return component_class | A generic component class | 62598fb556ac1b37e63022d1 |
class TrackSetHandler(PickleableMethodCaller): <NEW_LINE> <INDENT> def __init__(self, force: bool = False, gain_type: str = "auto", dry_run: bool = False, verbose: bool = False) -> None: <NEW_LINE> <INDENT> super(TrackSetHandler, self).__init__( "do_gain", force = force, gain_type = gain_type, verbose = verbose, dry_run = dry_run, ) <NEW_LINE> <DEDENT> def __call__(self, track_set: RGTrackSet) -> RGTrackSet: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super(TrackSetHandler, self).__call__(track_set) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logger.error("Failed to analyze %s. Skipping this track set. The exception was:\n\n%s\n", track_set.track_set_key_string(), traceback.format_exc()) <NEW_LINE> <DEDENT> return track_set | Pickleable callable for multiprocessing.Pool.imap | 62598fb55166f23b2e2434c2 |
class BadgeCategory(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=250, unique=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_user_value(self, user): <NEW_LINE> <INDENT> from sport.models import SportSession <NEW_LINE> sessions = SportSession.objects.filter(day__week__user=user) <NEW_LINE> if self.name == 'distance': <NEW_LINE> <INDENT> agg = sessions.aggregate(total=models.Sum('distance')) <NEW_LINE> return agg['total'] <NEW_LINE> <DEDENT> if self.name == 'denivele': <NEW_LINE> <INDENT> agg = sessions.aggregate(total=models.Sum('elevation_gain')) <NEW_LINE> return agg['total'] <NEW_LINE> <DEDENT> if self.name == 'time': <NEW_LINE> <INDENT> agg = sessions.aggregate(total=models.Sum('time')) <NEW_LINE> nb = agg['total'] <NEW_LINE> return nb and nb.days or 0 <NEW_LINE> <DEDENT> if self.name == 'age': <NEW_LINE> <INDENT> diff = timezone.now() - user.date_joined <NEW_LINE> return diff.days / 365 <NEW_LINE> <DEDENT> if self.name == 'trainer': <NEW_LINE> <INDENT> from club.models import ClubMembership <NEW_LINE> return ClubMembership.objects.filter(trainers=user).count() <NEW_LINE> <DEDENT> return 0.0 <NEW_LINE> <DEDENT> def find_badges(self, user, save=False): <NEW_LINE> <INDENT> val = self.get_user_value(user) <NEW_LINE> if not val: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> badges = self.badges.filter(value__lte=val) <NEW_LINE> added_badges = [] <NEW_LINE> if save: <NEW_LINE> <INDENT> for b in badges: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> BadgeUser.objects.create(user=user, badge=b) <NEW_LINE> added_badges.append(b) <NEW_LINE> <DEDENT> except IntegrityError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return badges, added_badges | Group badges by categories | 62598fb544b2445a339b69e6 |
class ParagraphNode(HeadingNode): <NEW_LINE> <INDENT> def __init__(self, io, options, argument): <NEW_LINE> <INDENT> super().__init__(io, 'paragraph', options, argument) <NEW_LINE> <DEDENT> def get_command(self): <NEW_LINE> <INDENT> return 'paragraph' <NEW_LINE> <DEDENT> def is_block_command(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def number(self, numbers): <NEW_LINE> <INDENT> Node.number(self, numbers) <NEW_LINE> <DEDENT> def is_inline_command(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def set_toc_id(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def prune_whitespace(self): <NEW_LINE> <INDENT> first = self.child_nodes[0] <NEW_LINE> last = self.child_nodes[-1] <NEW_LINE> for node_id in self.child_nodes: <NEW_LINE> <INDENT> node = in_scope(node_id) <NEW_LINE> if isinstance(node, TextNode): <NEW_LINE> <INDENT> if node.id == first: <NEW_LINE> <INDENT> node.prune_whitespace(leading=True) <NEW_LINE> <DEDENT> if node.id == last: <NEW_LINE> <INDENT> node.prune_whitespace(trailing=True) <NEW_LINE> <DEDENT> if node.id != last and node.id != first: <NEW_LINE> <INDENT> node.prune_whitespace() <NEW_LINE> <DEDENT> <DEDENT> out_scope(node) | SDoc2 node for paragraphs. | 62598fb59c8ee823130401e6 |
class testcase_98_kernel_parameter(Testcase): <NEW_LINE> <INDENT> tags = [] <NEW_LINE> stages = ['stage0'] <NEW_LINE> def test(self, connection, params): <NEW_LINE> <INDENT> prod = params['product'].upper() <NEW_LINE> ver = params['version'] <NEW_LINE> if 'kernelparams' in params: <NEW_LINE> <INDENT> self.get_return_value(connection, 'sed -i \'s,\\(kernel .*$\\),\\1 %s,\' /boot/grub/grub.conf' % params['kernelparams']) <NEW_LINE> self.get_return_value(connection, 'nohup sleep 1s && nohup reboot &') <NEW_LINE> time.sleep(30) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log.append({'result': 'skip', 'comment': 'no kernelparam was provided'}) <NEW_LINE> <DEDENT> return self.log | Add specific kernel parameters | 62598fb5d486a94d0ba2c0b8 |
class Parser(object): <NEW_LINE> <INDENT> ChunkClasses = () <NEW_LINE> Timeout = 60 <NEW_LINE> def __init__(self, fp, total_length=None): <NEW_LINE> <INDENT> if isinstance(fp, FilePtr): <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fp = FilePtr(fp, total_length) <NEW_LINE> <DEDENT> self.chunks = [] <NEW_LINE> self._timeout_timer = None <NEW_LINE> self.is_timeout = False <NEW_LINE> self.is_debug = False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_file_length(fp): <NEW_LINE> <INDENT> return os.fstat(fp.fileno()).st_size <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> self._set_timeout() <NEW_LINE> while self.fp.tell() < self.fp.total_length: <NEW_LINE> <INDENT> for chunk_cls in self.__class__.ChunkClasses: <NEW_LINE> <INDENT> if chunk_cls.matches(self.fp): <NEW_LINE> <INDENT> chunk = chunk_cls(self.fp, self) <NEW_LINE> chunk.populate() <NEW_LINE> self.chunks.append(chunk) <NEW_LINE> if self.is_debug: <NEW_LINE> <INDENT> print(chunk) <NEW_LINE> print('Now at', hex(self.fp.tell())) <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> <DEDENT> if self.is_timeout: <NEW_LINE> <INDENT> raise ParseTimeoutException() <NEW_LINE> <DEDENT> <DEDENT> self._timeout_timer.cancel() <NEW_LINE> <DEDENT> def _set_timeout(self): <NEW_LINE> <INDENT> def handler(): <NEW_LINE> <INDENT> self.is_timeout = True <NEW_LINE> <DEDENT> self._timeout_timer = threading.Timer(self.__class__.Timeout, handler) <NEW_LINE> self._timeout_timer.start() <NEW_LINE> <DEDENT> def enable_debug(self): <NEW_LINE> <INDENT> self.is_debug = True <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.fp.close() | Parse chunks from file or streaming.
- In file mode, :attr:`total_length` can be left None and will be read from
file system.
- In streaming mode, you **must** provide :attr:`total_length` to specify the
end of the stream.
:param fp: File object to be read from.
:param total_length: Total length of the source.
:throws ParseTimeoutException: Timeout. Default is 60s. | 62598fb5460517430c4320d0 |
class SiteConfigurationHistoryAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('site', 'enabled', 'created', 'modified') <NEW_LINE> search_fields = ('site__domain', 'values', 'created', 'modified') <NEW_LINE> ordering = ['-created'] <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> model = SiteConfigurationHistory <NEW_LINE> <DEDENT> def has_add_permission(self, request): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def has_delete_permission(self, request, obj=None): <NEW_LINE> <INDENT> return False | Admin interface for the SiteConfigurationHistory object. | 62598fb5377c676e912f6de2 |
@dataclasses.dataclass(slots=True) <NEW_LINE> class RewriteRestFilledCommand(Command): <NEW_LINE> <INDENT> spelling: Spelling = Spelling() <NEW_LINE> def __post_init__(self): <NEW_LINE> <INDENT> Command.__post_init__(self) <NEW_LINE> assert isinstance(self.spelling, Spelling) <NEW_LINE> <DEDENT> def __call__(self, voice, *, tag: abjad.Tag = abjad.Tag()) -> None: <NEW_LINE> <INDENT> selection = voice <NEW_LINE> if self.selector is not None: <NEW_LINE> <INDENT> selection = self.selector(selection) <NEW_LINE> <DEDENT> if self.spelling is not None: <NEW_LINE> <INDENT> increase_monotonic = self.spelling.increase_monotonic <NEW_LINE> forbidden_note_duration = self.spelling.forbidden_note_duration <NEW_LINE> forbidden_rest_duration = self.spelling.forbidden_rest_duration <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> increase_monotonic = None <NEW_LINE> forbidden_note_duration = None <NEW_LINE> forbidden_rest_duration = None <NEW_LINE> <DEDENT> maker = abjad.LeafMaker( increase_monotonic=increase_monotonic, forbidden_note_duration=forbidden_note_duration, forbidden_rest_duration=forbidden_rest_duration, tag=tag, ) <NEW_LINE> for tuplet in abjad.select.tuplets(selection): <NEW_LINE> <INDENT> if not tuplet.rest_filled(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> duration = abjad.get.duration(tuplet) <NEW_LINE> rests = maker([None], [duration]) <NEW_LINE> abjad.mutate.replace(tuplet[:], rests) <NEW_LINE> tuplet.multiplier = abjad.Multiplier(1) | Rewrite rest-filled command. | 62598fb57cff6e4e811b5b06 |
class OrderItemForm(models.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = OrderItemModel <NEW_LINE> exclude = () <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if 'instance' in kwargs: <NEW_LINE> <INDENT> kwargs.setdefault('initial', {}) <NEW_LINE> deliver_quantity = kwargs['instance'].quantity - self.get_delivered(kwargs['instance']) <NEW_LINE> kwargs['initial'].update(deliver_quantity=deliver_quantity) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> deliver_quantity = None <NEW_LINE> <DEDENT> super(OrderItemForm, self).__init__(*args, **kwargs) <NEW_LINE> if deliver_quantity == 0: <NEW_LINE> <INDENT> self['deliver_quantity'].field.widget.attrs.update(readonly='readonly') <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_delivered(cls, instance): <NEW_LINE> <INDENT> aggr = instance.deliveryitem_set.aggregate(delivered=Sum('quantity')) <NEW_LINE> return aggr['delivered'] or 0 <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(OrderItemForm, self).clean() <NEW_LINE> if cleaned_data.get('deliver_quantity') is not None: <NEW_LINE> <INDENT> if cleaned_data['deliver_quantity'] < 0: <NEW_LINE> <INDENT> raise ValidationError(_("Only a positive number of items can be delivered"), code='invalid') <NEW_LINE> <DEDENT> if cleaned_data['deliver_quantity'] > self.instance.quantity - self.get_delivered(self.instance): <NEW_LINE> <INDENT> raise ValidationError(_("The number of items to deliver exceeds the ordered quantity"), code='invalid') <NEW_LINE> <DEDENT> <DEDENT> return cleaned_data <NEW_LINE> <DEDENT> def has_changed(self): <NEW_LINE> <INDENT> return True | This form handles an ordered item, but adds a number field to modify the number of
items to deliver. | 62598fb5009cb60464d01609 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.