code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class DateField(DateTimeField): <NEW_LINE> <INDENT> def to_python(self): <NEW_LINE> <INDENT> if self.data is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(self.data, datetime.date): <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> return parse(self.data).date() | Field to represent a :mod:`datetime.date` | 62598fb992d797404e388c14 |
class Fixed: <NEW_LINE> <INDENT> can_take = False | Cannot be taken or moved.
| 62598fb999fddb7c1ca62e9c |
class Game: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.players = [] <NEW_LINE> self.battles = [] <NEW_LINE> <DEDENT> def get_player(self, username): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return next( p for p in self.players if p.username == username) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> <DEDENT> def add_player(self, player): <NEW_LINE> <INDENT> self.players.append(player) <NEW_LINE> <DEDENT> def player_in_battle(self, username): <NEW_LINE> <INDENT> if self.get_battle_by_username(username): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def get_players_by_world(self, world_id): <NEW_LINE> <INDENT> return [p for p in self.players if p.world_id == world_id] <NEW_LINE> <DEDENT> def get_battle_by_username(self, username): <NEW_LINE> <INDENT> combatant_id = self.get_player(username).combatant_id <NEW_LINE> for battle in self.battles: <NEW_LINE> <INDENT> if battle.has_combatant(combatant_id): <NEW_LINE> <INDENT> return battle <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def del_battle_by_username(self, username): <NEW_LINE> <INDENT> combatant_id = self.get_player(username).combatant_id <NEW_LINE> self.battles = [b for b in self.battles if not b.has_combatant(combatant_id)] <NEW_LINE> <DEDENT> async def create_battle(self, username, ws, player, ai): <NEW_LINE> <INDENT> if self.player_in_battle(username): <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> battle = Battle([player], [ai]) <NEW_LINE> self.battles.append(battle) <NEW_LINE> c_id = player.combatant_id <NEW_LINE> await Util.send_battle_start(ws, c_id.side) <NEW_LINE> await Util.send_battle_status(ws, battle, c_id.side) <NEW_LINE> await Util.send_move_request(ws, c_id.combatant_uuid) | The Game class keeps track of players and WebSockets. | 62598fb9bf627c535bcb1606 |
class AccountInvoices(osv.Model): <NEW_LINE> <INDENT> _inherit = 'account.invoice' <NEW_LINE> def print_invoice(self, cr, user, ids, context={}): <NEW_LINE> <INDENT> return {'type': 'ir.action.report.xml', 'report_name': 'account.invoice'} | account_invoices
| 62598fb97047854f4633f539 |
class ConstantDependencyDistancePass(microprobe.passes.Pass): <NEW_LINE> <INDENT> def __init__(self, dep): <NEW_LINE> <INDENT> super(ConstantDependencyDistancePass, self).__init__() <NEW_LINE> self._dep = dep <NEW_LINE> <DEDENT> def __call__(self, building_block, dummy_target): <NEW_LINE> <INDENT> for bbl in building_block.cfg.bbls: <NEW_LINE> <INDENT> for instr in bbl.instrs: <NEW_LINE> <INDENT> instr.set_dependency_distance(self._dep) <NEW_LINE> <DEDENT> <DEDENT> return [] | ConstantDependencyDistancePass pass.
| 62598fb98e7ae83300ee9202 |
class FlaskPlugin(BasePlugin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.converter_mapping = dict(DEFAULT_CONVERTER_MAPPING) <NEW_LINE> self.openapi_version = None <NEW_LINE> <DEDENT> def init_spec(self, spec): <NEW_LINE> <INDENT> super().init_spec(spec) <NEW_LINE> self.openapi_version = spec.openapi_version <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def flaskpath2openapi(path): <NEW_LINE> <INDENT> return RE_URL.sub(r'{\1}', path) <NEW_LINE> <DEDENT> def register_converter(self, converter, conv_type, conv_format=None): <NEW_LINE> <INDENT> self.converter_mapping[converter] = (conv_type, conv_format) <NEW_LINE> <DEDENT> def rule_to_params(self, rule): <NEW_LINE> <INDENT> params = [] <NEW_LINE> for argument in [a for a in rule.arguments if a not in rule.defaults]: <NEW_LINE> <INDENT> param = { 'in': 'path', 'name': argument, 'required': True, } <NEW_LINE> type_, format_ = self.converter_mapping.get( type(rule._converters[argument]), DEFAULT_TYPE) <NEW_LINE> schema = {'type': type_} <NEW_LINE> if format_ is not None: <NEW_LINE> <INDENT> schema['format'] = format_ <NEW_LINE> <DEDENT> if self.openapi_version.major < 3: <NEW_LINE> <INDENT> param.update(schema) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> param['schema'] = schema <NEW_LINE> <DEDENT> params.append(param) <NEW_LINE> <DEDENT> return params <NEW_LINE> <DEDENT> def path_helper(self, rule, operations, parameters, **kwargs): <NEW_LINE> <INDENT> for path_p in self.rule_to_params(rule): <NEW_LINE> <INDENT> p_doc = next( ( p for p in parameters if ( isinstance(p, Mapping) and p['in'] == 'path' and p['name'] == path_p['name'] ) ), None ) <NEW_LINE> if p_doc is not None: <NEW_LINE> <INDENT> p_doc.update({**path_p, **p_doc}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parameters.append(path_p) <NEW_LINE> <DEDENT> <DEDENT> return self.flaskpath2openapi(rule.rule) | Plugin to create OpenAPI paths from Flask rules | 62598fb9dc8b845886d5371c |
class SensorMap(SensorMapMixin, _EelFigure): <NEW_LINE> <INDENT> def __init__(self, sensors, labels='name', proj='default', mark=None, frame=.05, *args, **kwargs): <NEW_LINE> <INDENT> sensors = as_sensor(sensors) <NEW_LINE> if sensors.sysname: <NEW_LINE> <INDENT> ftitle = 'SensorMap: %s' % sensors.sysname <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ftitle = 'SensorMap' <NEW_LINE> <DEDENT> _EelFigure.__init__(self, ftitle, 1, 7, 1, False, *args, **kwargs) <NEW_LINE> self.axes = self._axes[0] <NEW_LINE> self._sensors = sensors <NEW_LINE> self._proj = proj <NEW_LINE> self._marker_handles = [] <NEW_LINE> self._connectivity = None <NEW_LINE> self._markers = _ax_map2d(self.axes, sensors, proj=proj) <NEW_LINE> SensorMapMixin.__init__(self, [self._markers.sensors]) <NEW_LINE> if labels: <NEW_LINE> <INDENT> self.set_label_text(labels) <NEW_LINE> <DEDENT> if mark is not None: <NEW_LINE> <INDENT> self.mark_sensors(mark) <NEW_LINE> <DEDENT> self._show() <NEW_LINE> <DEDENT> def mark_sensors(self, mark, kwargs=dict(marker='o', color='r', ms=5, markeredgewidth=.9, ls='', )): <NEW_LINE> <INDENT> h = _plt_map2d(self.axes, self._sensors, self._proj, mark=mark, kwargs=kwargs) <NEW_LINE> self._marker_handles.append(h) <NEW_LINE> self.canvas.draw() <NEW_LINE> <DEDENT> def remove_markers(self): <NEW_LINE> <INDENT> while len(self._marker_handles) > 0: <NEW_LINE> <INDENT> h = self._marker_handles.pop(0) <NEW_LINE> h.remove() <NEW_LINE> <DEDENT> self.canvas.draw() <NEW_LINE> <DEDENT> def show_connectivity(self, show=True): <NEW_LINE> <INDENT> if not show: <NEW_LINE> <INDENT> self._markers.connectivity.show(None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if show is True: <NEW_LINE> <INDENT> conn = self._sensors.connectivity() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> conn = self._sensors.connectivity(show) <NEW_LINE> <DEDENT> self._markers.connectivity.show(conn) <NEW_LINE> <DEDENT> self.draw() | Plot sensor positions in 2 dimensions
Parameters
----------
sensors : NDVar | Sensor
sensor-net object or object containing sensor-net
labels : None | 'index' | 'name' | 'fullname'
Content of the labels. For 'name', any prefix common to all names
is removed; with 'fullname', the full name is shown.
proj:
Transform to apply to 3 dimensional sensor coordinates for plotting
locations in a plane
mark : None | list of int
List of sensor indices to mark.
frame : scalar
Size of the empty space around sensors in axes.
title : None | string
Figure title. | 62598fb9627d3e7fe0e07015 |
class CouplingLayer(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_inputs, num_hidden=64): <NEW_LINE> <INDENT> super(CouplingLayer, self).__init__() <NEW_LINE> self.num_inputs = num_inputs <NEW_LINE> self.main = nn.Sequential( nn.Linear(num_inputs // 2, num_hidden), nn.ReLU(), nn.Linear(num_hidden, num_hidden), nn.ReLU(), nn.Linear(num_hidden, 2 * (self.num_inputs - num_inputs // 2))) <NEW_LINE> def init(m): <NEW_LINE> <INDENT> if isinstance(m, nn.Linear): <NEW_LINE> <INDENT> m.bias.data.fill_(0) <NEW_LINE> nn.init.orthogonal_(m.weight.data) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def forward(self, inputs, cond_inputs=None, mode='direct'): <NEW_LINE> <INDENT> if mode == 'direct': <NEW_LINE> <INDENT> x_a, x_b = inputs.chunk(2, dim=-1) <NEW_LINE> log_s, t = self.main(x_b).chunk(2, dim=-1) <NEW_LINE> s = torch.exp(log_s) <NEW_LINE> y_a = x_a * s + t <NEW_LINE> y_b = x_b <NEW_LINE> return torch.cat([y_a, y_b], dim=-1), log_s.sum(-1, keepdim=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y_a, y_b = inputs.chunk(2, dim=-1) <NEW_LINE> log_s, t = self.main(y_b).chunk(2, dim=-1) <NEW_LINE> s = torch.exp(-log_s) <NEW_LINE> x_a = (y_a - t) * s <NEW_LINE> x_b = y_b <NEW_LINE> return torch.cat([x_a, x_b], dim=-1), -log_s.sum(-1, keepdim=True) | An implementation of a coupling layer
from RealNVP (https://arxiv.org/abs/1605.08803). | 62598fb9a219f33f346c6969 |
class CertificateError(ValueError): <NEW_LINE> <INDENT> pass | Raised on certificate errors. | 62598fb9be383301e0253960 |
class Entry(object): <NEW_LINE> <INDENT> def __init__(self, _id, names, emails, grades, genders, ec_list, ec_dict, clublist, ix): <NEW_LINE> <INDENT> self._id = _id <NEW_LINE> self.names=names <NEW_LINE> self.emails=emails <NEW_LINE> self.grades=grades <NEW_LINE> self.genders=genders <NEW_LINE> self.ec_list = ec_list <NEW_LINE> self.ec_dict = ec_dict <NEW_LINE> self.clublist = clublist <NEW_LINE> self.clubIX=ix <NEW_LINE> <DEDENT> def add_to_group(self, name, email, grade, gender, stud_ecs): <NEW_LINE> <INDENT> self.names.append(name) <NEW_LINE> self.emails.append(email) <NEW_LINE> self.grades[grade]+=1 <NEW_LINE> self.genders[gender]+=1 <NEW_LINE> for e in stud_ecs: <NEW_LINE> <INDENT> if e in self.ec_dict: <NEW_LINE> <INDENT> self.ec_dict[e]+=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ec_dict[e]=1 <NEW_LINE> self.ec_list.append(e) | A class that turns participants into objects | 62598fb95fc7496912d4832d |
class AsyncAwaker(GanetiBaseAsyncoreDispatcher): <NEW_LINE> <INDENT> def __init__(self, signal_fn=None): <NEW_LINE> <INDENT> GanetiBaseAsyncoreDispatcher.__init__(self) <NEW_LINE> assert signal_fn is None or callable(signal_fn) <NEW_LINE> (self.in_socket, self.out_socket) = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) <NEW_LINE> self.in_socket.setblocking(0) <NEW_LINE> self.in_socket.shutdown(socket.SHUT_WR) <NEW_LINE> self.out_socket.shutdown(socket.SHUT_RD) <NEW_LINE> self.set_socket(self.in_socket) <NEW_LINE> self.need_signal = True <NEW_LINE> self.signal_fn = signal_fn <NEW_LINE> self.connected = True <NEW_LINE> <DEDENT> def handle_read(self): <NEW_LINE> <INDENT> utils.IgnoreSignals(self.recv, 4096) <NEW_LINE> if self.signal_fn: <NEW_LINE> <INDENT> self.signal_fn() <NEW_LINE> <DEDENT> self.need_signal = True <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> asyncore.dispatcher.close(self) <NEW_LINE> self.out_socket.close() <NEW_LINE> <DEDENT> def signal(self): <NEW_LINE> <INDENT> if self.need_signal: <NEW_LINE> <INDENT> self.need_signal = False <NEW_LINE> self.out_socket.send(b"\x00") | A way to notify the asyncore loop that something is going on.
If an asyncore daemon is multithreaded when a thread tries to push some data
to a socket, the main loop handling asynchronous requests might be sleeping
waiting on a select(). To avoid this it can create an instance of the
AsyncAwaker, which other threads can use to wake it up. | 62598fb9a8370b77170f0543 |
class TestBug666(unittest.TestCase): <NEW_LINE> <INDENT> def testIt(self): <NEW_LINE> <INDENT> if not py3k.IS_PY3K: <NEW_LINE> <INDENT> ba = QByteArray('1234567890') <NEW_LINE> self.assertEqual(ba[2:4], '34') <NEW_LINE> self.assertEqual(ba[:4], '1234') <NEW_LINE> self.assertEqual(ba[4:], '567890') <NEW_LINE> self.assertEqual(len(ba[4:1]), 0) | QByteArray does not support slices | 62598fb9ad47b63b2c5a79b7 |
class NetdevSimDev: <NEW_LINE> <INDENT> def __init__(self, port_count=1): <NEW_LINE> <INDENT> addr = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open("/sys/bus/netdevsim/new_device", "w") as f: <NEW_LINE> <INDENT> f.write("%u %u" % (addr, port_count)) <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.errno == errno.ENOSPC: <NEW_LINE> <INDENT> addr += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> raise e <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> self.addr = addr <NEW_LINE> self.wait_for_netdevs(port_count) <NEW_LINE> ret, out = cmd("udevadm settle", fail=False) <NEW_LINE> if ret: <NEW_LINE> <INDENT> raise Exception("udevadm settle failed") <NEW_LINE> <DEDENT> ifnames = self.get_ifnames() <NEW_LINE> devs.append(self) <NEW_LINE> self.dfs_dir = "/sys/kernel/debug/netdevsim/netdevsim%u/" % addr <NEW_LINE> self.nsims = [] <NEW_LINE> for port_index in range(port_count): <NEW_LINE> <INDENT> self.nsims.append(NetdevSim(self, port_index, ifnames[port_index])) <NEW_LINE> <DEDENT> <DEDENT> def get_ifnames(self): <NEW_LINE> <INDENT> ifnames = [] <NEW_LINE> listdir = os.listdir("/sys/bus/netdevsim/devices/netdevsim%u/net/" % self.addr) <NEW_LINE> for ifname in listdir: <NEW_LINE> <INDENT> ifnames.append(ifname) <NEW_LINE> <DEDENT> ifnames.sort() <NEW_LINE> return ifnames <NEW_LINE> <DEDENT> def wait_for_netdevs(self, port_count): <NEW_LINE> <INDENT> timeout = 5 <NEW_LINE> timeout_start = time.time() <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ifnames = self.get_ifnames() <NEW_LINE> <DEDENT> except FileNotFoundError as e: <NEW_LINE> <INDENT> ifnames = [] <NEW_LINE> <DEDENT> if len(ifnames) == port_count: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if time.time() < timeout_start + timeout: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> raise Exception("netdevices did not appear within timeout") <NEW_LINE> <DEDENT> <DEDENT> def dfs_num_bound_progs(self): <NEW_LINE> <INDENT> path = os.path.join(self.dfs_dir, "bpf_bound_progs") <NEW_LINE> _, progs = cmd('ls %s' % (path)) <NEW_LINE> return len(progs.split()) <NEW_LINE> <DEDENT> def dfs_get_bound_progs(self, expected): <NEW_LINE> <INDENT> progs = DebugfsDir(os.path.join(self.dfs_dir, "bpf_bound_progs")) <NEW_LINE> if expected is not None: <NEW_LINE> <INDENT> if len(progs) != expected: <NEW_LINE> <INDENT> fail(True, "%d BPF programs bound, expected %d" % (len(progs), expected)) <NEW_LINE> <DEDENT> <DEDENT> return progs <NEW_LINE> <DEDENT> def remove(self): <NEW_LINE> <INDENT> with open("/sys/bus/netdevsim/del_device", "w") as f: <NEW_LINE> <INDENT> f.write("%u" % self.addr) <NEW_LINE> <DEDENT> devs.remove(self) <NEW_LINE> <DEDENT> def remove_nsim(self, nsim): <NEW_LINE> <INDENT> self.nsims.remove(nsim) <NEW_LINE> with open("/sys/bus/netdevsim/devices/netdevsim%u/del_port" % self.addr ,"w") as f: <NEW_LINE> <INDENT> f.write("%u" % nsim.port_index) | Class for netdevsim bus device and its attributes. | 62598fb9aad79263cf42e938 |
class IdentityClientMeta(type): <NEW_LINE> <INDENT> _transport_registry = OrderedDict() <NEW_LINE> _transport_registry['grpc'] = IdentityGrpcTransport <NEW_LINE> def get_transport_class(cls, label: str = None, ) -> Type[IdentityTransport]: <NEW_LINE> <INDENT> if label: <NEW_LINE> <INDENT> return cls._transport_registry[label] <NEW_LINE> <DEDENT> return next(iter(cls._transport_registry.values())) | Metaclass for the Identity client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects. | 62598fb93d592f4c4edbb022 |
class SignUpForm(UserCreationForm): <NEW_LINE> <INDENT> email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') <NEW_LINE> first_name = forms.CharField(label='First name', max_length=100) <NEW_LINE> last_name = forms.CharField(label='Last name', max_length=100) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> user = super(SignUpForm, self).save(commit=False) <NEW_LINE> user.first_name = self.cleaned_data["first_name"] <NEW_LINE> user.last_name = self.cleaned_data["last_name"] <NEW_LINE> if commit: <NEW_LINE> <INDENT> user.save() <NEW_LINE> <DEDENT> return user | Class for signup form. | 62598fb932920d7e50bc61b2 |
class CodegenPanic(VyperInternalException): <NEW_LINE> <INDENT> pass | Invalid code generated during codegen phase | 62598fb9236d856c2adc94f2 |
class EYFSDetailsForm(ChildminderForms): <NEW_LINE> <INDENT> field_label_classes = 'form-label-bold' <NEW_LINE> error_summary_template_name = 'standard-error-summary.html' <NEW_LINE> auto_replace_widgets = True <NEW_LINE> eyfs_course_name = forms.CharField(label='Title of training course', error_messages={'required': 'Please enter the title of the course'}) <NEW_LINE> eyfs_course_date = CustomSplitDateField(label='Date you completed course', help_text='For example, 31 03 2016', error_messages={'required': 'Please enter the full date, including the day, month and year'}, min_value=1900) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.application_id_local = kwargs.pop('id') <NEW_LINE> super(EYFSDetailsForm, self).__init__(*args, **kwargs) <NEW_LINE> full_stop_stripper(self) <NEW_LINE> if ChildcareTraining.objects.filter(application_id=self.application_id_local).count() > 0: <NEW_LINE> <INDENT> eyfs_record = ChildcareTraining.objects.get(application_id=self.application_id_local) <NEW_LINE> self.fields['eyfs_course_name'].initial = eyfs_record.eyfs_course_name <NEW_LINE> course_day, course_month, course_year = date_formatter(eyfs_record.eyfs_course_date_day, eyfs_record.eyfs_course_date_month, eyfs_record.eyfs_course_date_year) <NEW_LINE> self.fields['eyfs_course_date'].initial = [course_day, course_month, course_year] <NEW_LINE> self.pk = eyfs_record.eyfs_id <NEW_LINE> self.field_list = ['eyfs_course_name','eyfs_course_date'] <NEW_LINE> <DEDENT> <DEDENT> def clean_eyfs_course_name(self): <NEW_LINE> <INDENT> course_name = self.cleaned_data['eyfs_course_name'] <NEW_LINE> if len(course_name) > 50: <NEW_LINE> <INDENT> raise forms.ValidationError('The title of the course must be under 50 characters long') <NEW_LINE> <DEDENT> return course_name <NEW_LINE> <DEDENT> def clean_eyfs_course_date(self): <NEW_LINE> <INDENT> course_date_day = self.cleaned_data['eyfs_course_date'].day <NEW_LINE> course_date_month = self.cleaned_data['eyfs_course_date'].month <NEW_LINE> course_date_year = self.cleaned_data['eyfs_course_date'].year <NEW_LINE> course_date = date(course_date_year, course_date_month, course_date_day) <NEW_LINE> return course_date | GOV.UK form for the Early Years details: details page | 62598fb95166f23b2e243541 |
class ToolsStatusVersionListRow_Locators_Base(object): <NEW_LINE> <INDENT> locators = { 'base' : "css=tr", 'version' : "css=td:nth-of-type(1)", 'released' : "css=td:nth-of-type(2)", 'subversion' : "css=td:nth-of-type(3)", 'published' : "css=td:nth-of-type(4) span", 'edit' : "css=td:nth-of-type(5) .action-link a", } | locators for ToolsStatusVersionListRow object | 62598fb9ff9c53063f51a7b2 |
class CommunicationIdentityAccessToken(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'token': {'required': True}, 'expires_on': {'required': True}, } <NEW_LINE> _attribute_map = { 'token': {'key': 'token', 'type': 'str'}, 'expires_on': {'key': 'expiresOn', 'type': 'iso-8601'}, } <NEW_LINE> def __init__( self, *, token: str, expires_on: datetime.datetime, **kwargs ): <NEW_LINE> <INDENT> super(CommunicationIdentityAccessToken, self).__init__(**kwargs) <NEW_LINE> self.token = token <NEW_LINE> self.expires_on = expires_on | An access token.
All required parameters must be populated in order to send to Azure.
:ivar token: Required. The access token issued for the identity.
:vartype token: str
:ivar expires_on: Required. The expiry time of the token.
:vartype expires_on: ~datetime.datetime | 62598fb9f548e778e596b70a |
class OzonePressure(Ozone): <NEW_LINE> <INDENT> def __call__(self, **kwargs): <NEW_LINE> <INDENT> return | Ozone fixed with pressure, no adjustment needed. | 62598fb9cc0a2c111447b171 |
class GoalStmt(Visitable): <NEW_LINE> <INDENT> def __init__(self, formula): <NEW_LINE> <INDENT> self._visitorName = 'visit_goal_stmt' <NEW_LINE> self.formula = formula | This class represents the AST node for a pddl problem goal condition. | 62598fb9283ffb24f3cf39e8 |
class TestDeAT(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.factory = Faker('de_AT') <NEW_LINE> <DEDENT> def test_city(self): <NEW_LINE> <INDENT> city = self.factory.city() <NEW_LINE> assert isinstance(city, string_types) <NEW_LINE> assert city in DeAtProvider.cities <NEW_LINE> <DEDENT> def test_state(self): <NEW_LINE> <INDENT> state = self.factory.state() <NEW_LINE> assert isinstance(state, string_types) <NEW_LINE> assert state in DeAtProvider.states <NEW_LINE> <DEDENT> def test_street_suffix_short(self): <NEW_LINE> <INDENT> street_suffix_short = self.factory.street_suffix_short() <NEW_LINE> assert isinstance(street_suffix_short, string_types) <NEW_LINE> assert street_suffix_short in DeAtProvider.street_suffixes_short <NEW_LINE> <DEDENT> def test_street_suffix_long(self): <NEW_LINE> <INDENT> street_suffix_long = self.factory.street_suffix_long() <NEW_LINE> assert isinstance(street_suffix_long, string_types) <NEW_LINE> assert street_suffix_long in DeAtProvider.street_suffixes_long <NEW_LINE> <DEDENT> def test_country(self): <NEW_LINE> <INDENT> country = self.factory.country() <NEW_LINE> assert isinstance(country, string_types) <NEW_LINE> assert country in DeAtProvider.countries <NEW_LINE> <DEDENT> def test_postcode(self): <NEW_LINE> <INDENT> postcode = self.factory.postcode() <NEW_LINE> assert re.match(r"\d{4}", postcode) <NEW_LINE> <DEDENT> def test_city_with_postcode(self): <NEW_LINE> <INDENT> city_with_postcode = self.factory.city_with_postcode() <NEW_LINE> assert isinstance(city_with_postcode, string_types) | Tests in addresses in the de_AT locale | 62598fb991f36d47f2230f5c |
class IiChipAssays(Interface): <NEW_LINE> <INDENT> pass | Marker interface for navigation-root folder
| 62598fb963b5f9789fe852d3 |
class SessionIndex(SamlBase): <NEW_LINE> <INDENT> c_tag = 'SessionIndex' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_value_type = {'base': 'string'} <NEW_LINE> c_children = SamlBase.c_children.copy() <NEW_LINE> c_attributes = SamlBase.c_attributes.copy() <NEW_LINE> c_child_order = SamlBase.c_child_order[:] <NEW_LINE> c_cardinality = SamlBase.c_cardinality.copy() | The urn:oasis:names:tc:SAML:2.0:protocol:SessionIndex element | 62598fb956b00c62f0fb2a1f |
class RouteError(Exception): <NEW_LINE> <INDENT> pass | Error when the remote planner service can't
process the input data and produce routes | 62598fb94527f215b58ea03a |
@inherit_doc <NEW_LINE> class JavaModel(Model, JavaTransformer): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__(self, java_model): <NEW_LINE> <INDENT> super(JavaModel, self).__init__() <NEW_LINE> self._java_obj = java_model <NEW_LINE> self.uid = java_model.uid() <NEW_LINE> <DEDENT> def copy(self, extra=None): <NEW_LINE> <INDENT> if extra is None: <NEW_LINE> <INDENT> extra = dict() <NEW_LINE> <DEDENT> that = super(JavaModel, self).copy(extra) <NEW_LINE> that._java_obj = self._java_obj.copy(self._empty_java_param_map()) <NEW_LINE> that._transfer_params_to_java() <NEW_LINE> return that <NEW_LINE> <DEDENT> def _call_java(self, name, *args): <NEW_LINE> <INDENT> m = getattr(self._java_obj, name) <NEW_LINE> sc = SparkContext._active_spark_context <NEW_LINE> java_args = [_py2java(sc, arg) for arg in args] <NEW_LINE> return _java2py(sc, m(*java_args)) | Base class for :py:class:`Model`s that wrap Java/Scala
implementations. Subclasses should inherit this class before
param mix-ins, because this sets the UID from the Java model. | 62598fb9aad79263cf42e939 |
class QQAuthUserSerializer(serializers.Serializer): <NEW_LINE> <INDENT> access_token = serializers.CharField(label='操作凭证') <NEW_LINE> mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$') <NEW_LINE> password = serializers.CharField(label='密码', max_length=20, min_length=8) <NEW_LINE> sms_code = serializers.CharField(label='短信验证码') <NEW_LINE> def validate(self, attrs): <NEW_LINE> <INDENT> access_token = attrs.get('access_token') <NEW_LINE> openid = check_save_user_token(access_token) <NEW_LINE> if not openid: <NEW_LINE> <INDENT> raise serializers.ValidationError('openid无效') <NEW_LINE> <DEDENT> attrs['access_token'] = openid <NEW_LINE> redis_conn = get_redis_connection('verify_codes') <NEW_LINE> mobile = attrs.get('mobile') <NEW_LINE> real_sms_code = redis_conn.get('sms_%s' % mobile) <NEW_LINE> sms_code = attrs.get('sms_code') <NEW_LINE> if real_sms_code.decode() != sms_code: <NEW_LINE> <INDENT> raise serializers.ValidationError('验证码错误') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(mobile=mobile) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not user.check_password(attrs.get('password')): <NEW_LINE> <INDENT> raise serializers.ValidationError('已存在用户,但密码不正确') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attrs['user'] = user <NEW_LINE> <DEDENT> <DEDENT> return attrs <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> user = validated_data.get('user') <NEW_LINE> if not user: <NEW_LINE> <INDENT> user = User( username=validated_data.get('mobile'), password=validated_data.get('password'), mobile=validated_data.get('mobile') ) <NEW_LINE> user.set_password(validated_data.get('password')) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> QQAuthUser.objects.create( user=user, openid=validated_data.get('access_token') ) <NEW_LINE> return user | 绑定用户的序列化器 | 62598fb9498bea3a75a57c88 |
class IdData(): <NEW_LINE> <INDENT> def __init__(self, id_folder, distance_treshold): <NEW_LINE> <INDENT> print('Loading embeddings: ') <NEW_LINE> self.distance_treshold = distance_treshold <NEW_LINE> self.id_folder = id_folder <NEW_LINE> self.embeddings = np.load(self.id_folder + '/' + 'embeddings.npy') <NEW_LINE> self.id_names = list(np.load(self.id_folder + '/' + 'labels_strings.npy')) <NEW_LINE> <DEDENT> def find_matching_ids(self, embs): <NEW_LINE> <INDENT> matching_ids = [] <NEW_LINE> matching_distances = [] <NEW_LINE> distance_matrix = pairwise_distances(embs, self.embeddings) <NEW_LINE> for distance_row in distance_matrix: <NEW_LINE> <INDENT> min_index = np.argmin(distance_row) <NEW_LINE> if distance_row[min_index] < self.distance_treshold: <NEW_LINE> <INDENT> matching_ids.append(self.id_names[min_index]) <NEW_LINE> matching_distances.append(distance_row[min_index]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> matching_ids.append(None) <NEW_LINE> matching_distances.append(None) <NEW_LINE> <DEDENT> <DEDENT> return matching_ids, matching_distances | Keeps track of known identities and calculates id matches | 62598fb9e5267d203ee6ba64 |
class Automaton(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def __init__(self, obj=None, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def validate_self(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _validate_input_yield(self, input_str): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _validate_input_return(self, input_str): <NEW_LINE> <INDENT> validation_generator = self._validate_input_yield(input_str) <NEW_LINE> for config in validation_generator: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return config <NEW_LINE> <DEDENT> def validate_input_ntm_final(self, input_str,final ,step = False): <NEW_LINE> <INDENT> if step: <NEW_LINE> <INDENT> return self._validate_input_yield_final(input_str,final) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def validate_input(self, input_str, step=False): <NEW_LINE> <INDENT> if step: <NEW_LINE> <INDENT> return self._validate_input_yield(input_str) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._validate_input_return(input_str) <NEW_LINE> <DEDENT> <DEDENT> def validate_input1(self, input_str, step=False): <NEW_LINE> <INDENT> if step: <NEW_LINE> <INDENT> return self._validate_input_yield1(input_str) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._validate_input_return1(input_str) <NEW_LINE> <DEDENT> <DEDENT> def _validate_input_return1(self, input_str): <NEW_LINE> <INDENT> validation_generator = self._validate_input_yield1(input_str) <NEW_LINE> for config in validation_generator: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return config <NEW_LINE> <DEDENT> def _validate_initial_state(self): <NEW_LINE> <INDENT> if self.initial_state not in self.states: <NEW_LINE> <INDENT> raise exceptions.InvalidStateError( '{} nie je platný počiatočný stav, nenachádza sa v množine stavov'.format(self.initial_state)) <NEW_LINE> <DEDENT> <DEDENT> def _validate_initial_state_transitions(self): <NEW_LINE> <INDENT> if self.initial_state not in self.transitions: <NEW_LINE> <INDENT> raise exceptions.MissingStateError( 'Počiatočný stav {} nemá definovaný prechod v prechodovej funkcii'.format( self.initial_state)) <NEW_LINE> <DEDENT> <DEDENT> def _validate_final_states(self): <NEW_LINE> <INDENT> final = {self.final_states} <NEW_LINE> invalid_states = final - self.states <NEW_LINE> if invalid_states: <NEW_LINE> <INDENT> raise exceptions.InvalidStateError( 'Akceptujúci stav ({}) nie je platný, nenachádza sa v množine stavov'.format( ', '.join(invalid_states))) <NEW_LINE> <DEDENT> <DEDENT> def _validate_reject_state(self): <NEW_LINE> <INDENT> reject = {self.reject_state} <NEW_LINE> invalid_states = reject - self.states <NEW_LINE> if invalid_states: <NEW_LINE> <INDENT> raise exceptions.InvalidStateError( 'Zamietajúci stav ({}) nie je platný, nenachádza sa v množine stavov'.format( ', '.join(invalid_states))) <NEW_LINE> <DEDENT> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return self.__class__(self) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ | An abstract base class for all Turing machines. | 62598fb9fff4ab517ebcd948 |
class OBJECT_OT_FeatureShow(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "show.feature" <NEW_LINE> bl_label = "Show previously set feature edges" <NEW_LINE> whichLevel = IntProperty() <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> obj = context.active_object <NEW_LINE> scn = context.scene <NEW_LINE> bpy.ops.object.mode_set(mode='EDIT') <NEW_LINE> bpy.ops.mesh.select_all(action='DESELECT') <NEW_LINE> bpy.ops.object.mode_set(mode='OBJECT') <NEW_LINE> bpy.ops.wm.context_set_value(data_path="tool_settings.mesh_select_mode", value="(False,True,False)") <NEW_LINE> for e in obj.data.edges: <NEW_LINE> <INDENT> e.select = False <NEW_LINE> if e.use_edge_sharp and round(100*e.bevel_weight) == self.whichLevel: <NEW_LINE> <INDENT> e.select = True <NEW_LINE> <DEDENT> <DEDENT> bpy.ops.object.mode_set(mode='EDIT') <NEW_LINE> scn.featLevel = self.whichLevel <NEW_LINE> return {'FINISHED'} | Show previously set feature edges | 62598fb9627d3e7fe0e07017 |
class BorderCommand(Command): <NEW_LINE> <INDENT> BORDER_BEFORE = 0 <NEW_LINE> BORDER_AFTER = 1 <NEW_LINE> position = BORDER_BEFORE <NEW_LINE> def applyBorders(self, cells, location=None): <NEW_LINE> <INDENT> a = self.attributes <NEW_LINE> if a and 'span' in list(a.keys()): <NEW_LINE> <INDENT> try: start, end = a['span'] <NEW_LINE> except TypeError: start = end = a['span'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start = -sys.maxsize <NEW_LINE> end = sys.maxsize <NEW_LINE> <DEDENT> if location is None: <NEW_LINE> <INDENT> location = self.locations[self.position] <NEW_LINE> <DEDENT> colnum = 1 <NEW_LINE> for cell in cells: <NEW_LINE> <INDENT> if colnum < start or colnum > end: <NEW_LINE> <INDENT> colnum += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> cell.style['border-%s-style' % location] = 'solid' <NEW_LINE> cell.style['border-%s-color' % location] = 'black' <NEW_LINE> cell.style['border-%s-width' % location] = '1px' <NEW_LINE> if cell.attributes: <NEW_LINE> <INDENT> colnum += cell.attributes.get('colspan', 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> colnum += 1 | Base class for border commands | 62598fb9ec188e330fdf89f6 |
class GlanceImages(utils.GlanceScenario, nova_utils.NovaScenario): <NEW_LINE> <INDENT> RESOURCE_NAME_PREFIX = "rally_image_" <NEW_LINE> RESOURCE_NAME_LENGTH = 16 <NEW_LINE> @validation.required_services(consts.Service.GLANCE) <NEW_LINE> @validation.required_openstack(users=True) <NEW_LINE> @base.scenario(context={"cleanup": ["glance"]}) <NEW_LINE> def create_and_list_image(self, container_format, image_location, disk_format, **kwargs): <NEW_LINE> <INDENT> self._create_image(container_format, image_location, disk_format, **kwargs) <NEW_LINE> self._list_images() <NEW_LINE> <DEDENT> @validation.required_services(consts.Service.GLANCE) <NEW_LINE> @validation.required_openstack(users=True) <NEW_LINE> @base.scenario(context={"cleanup": ["glance"]}) <NEW_LINE> def list_images(self): <NEW_LINE> <INDENT> self._list_images() <NEW_LINE> <DEDENT> @validation.required_services(consts.Service.GLANCE) <NEW_LINE> @validation.required_openstack(users=True) <NEW_LINE> @base.scenario(context={"cleanup": ["glance"]}) <NEW_LINE> def create_and_delete_image(self, container_format, image_location, disk_format, **kwargs): <NEW_LINE> <INDENT> image = self._create_image(container_format, image_location, disk_format, **kwargs) <NEW_LINE> self._delete_image(image) <NEW_LINE> <DEDENT> @types.set(flavor=types.FlavorResourceType) <NEW_LINE> @validation.flavor_exists("flavor") <NEW_LINE> @validation.required_services(consts.Service.GLANCE, consts.Service.NOVA) <NEW_LINE> @validation.required_openstack(users=True) <NEW_LINE> @base.scenario(context={"cleanup": ["glance", "nova"]}) <NEW_LINE> def create_image_and_boot_instances(self, container_format, image_location, disk_format, flavor, number_instances, **kwargs): <NEW_LINE> <INDENT> image = self._create_image(container_format, image_location, disk_format) <NEW_LINE> image_id = image.id <NEW_LINE> server_name = self._generate_random_name(prefix="rally_novaserver_") <NEW_LINE> self._boot_servers(server_name, image_id, flavor, number_instances, **kwargs) | Benchmark scenarios for Glance images. | 62598fb9a05bb46b3848a9d1 |
class Loader: <NEW_LINE> <INDENT> from ..primitives import uri <NEW_LINE> from .exceptions import LoadingError <NEW_LINE> @classmethod <NEW_LINE> def loadShelves(cls, executive, protocol, uri, scheme, context, **kwds): <NEW_LINE> <INDENT> linker = executive.linker <NEW_LINE> candidates = cls.locateShelves(executive=executive, protocol=protocol, scheme=scheme, context=context, **kwds) <NEW_LINE> for candidate in candidates: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shelf = linker.shelves[candidate.uri] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> linker.shelves[candidate.uri] = cls.shelf(uri=candidate) <NEW_LINE> try: <NEW_LINE> <INDENT> shelf = cls.load(executive=executive, uri=candidate) <NEW_LINE> <DEDENT> except cls.LoadingError as error: <NEW_LINE> <INDENT> del linker.shelves[candidate.uri] <NEW_LINE> continue <NEW_LINE> <DEDENT> linker.shelves[candidate.uri] = shelf <NEW_LINE> <DEDENT> yield shelf <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def locateShelves(cls, executive, protocol, scheme, context, symbol, cfgpath=None, **kwds): <NEW_LINE> <INDENT> contexts = list( context[:pos] for pos in reversed(range(1, len(context)+1))) <NEW_LINE> for candidate in contexts: <NEW_LINE> <INDENT> yield cls.assemble(candidate) <NEW_LINE> <DEDENT> app = executive.dashboard.pyre_application <NEW_LINE> prefixes = list(app.searchpath) if app else [] <NEW_LINE> flavors = [] <NEW_LINE> if protocol: <NEW_LINE> <INDENT> for package, *flavor in protocol.pyre_resolutionContext(): <NEW_LINE> <INDENT> if package not in prefixes: <NEW_LINE> <INDENT> prefixes.append(package) <NEW_LINE> <DEDENT> for known in flavors: <NEW_LINE> <INDENT> for new, old in zip(flavor, known): <NEW_LINE> <INDENT> if new != old: break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(known) >= len(flavor): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> flavors.append(flavor) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> cfgpath = [[]] + (list([path] for path in cfgpath) if cfgpath else []) <NEW_LINE> prefixes = [[]] + (list([prefix] for prefix in prefixes) if prefixes else []) <NEW_LINE> flavors = flavors if flavors else [[]] <NEW_LINE> candidates = [] <NEW_LINE> combine = (cfgpath, prefixes, flavors, contexts) <NEW_LINE> for path, prefix, flavor, user in itertools.product(*combine): <NEW_LINE> <INDENT> for pos in reversed(range(len(flavor)+1)): <NEW_LINE> <INDENT> front = flavor[:pos] <NEW_LINE> candidate = cls.assemble(path + prefix + front + user) <NEW_LINE> yield candidate <NEW_LINE> candidates.append(candidate) <NEW_LINE> for spliced in reversed(flavor[pos:]): <NEW_LINE> <INDENT> candidate = cls.assemble(path + prefix + front + [spliced]) <NEW_LINE> yield candidate <NEW_LINE> candidates.append(candidate) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def register(cls, index): <NEW_LINE> <INDENT> index.update((scheme, cls) for scheme in cls.schemes) <NEW_LINE> return <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def prime(cls, linker): <NEW_LINE> <INDENT> return | Base class for strategies that build component descriptors from persistent stores | 62598fb9a8370b77170f0544 |
class QLinear(nn.Linear): <NEW_LINE> <INDENT> def __init__(self, in_features, out_features, bias=True, num_bits=8, num_bits_weight=8, num_bits_grad=8, biprecision=True): <NEW_LINE> <INDENT> super(QLinear, self).__init__(in_features, out_features, bias) <NEW_LINE> self.num_bits = num_bits <NEW_LINE> self.num_bits_weight = num_bits_weight or num_bits <NEW_LINE> self.num_bits_grad = num_bits_grad <NEW_LINE> self.biprecision = biprecision <NEW_LINE> self.quantize_input = QuantMeasure(self.num_bits) <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> qinput = self.quantize_input(input) <NEW_LINE> weight_qparams = calculate_qparams( self.weight, num_bits=self.num_bits_weight, flatten_dims=(1, -1), reduce_dim=None) <NEW_LINE> qweight = quantize(self.weight, qparams=weight_qparams) <NEW_LINE> if self.bias is not None: <NEW_LINE> <INDENT> qbias = quantize( self.bias, num_bits=self.num_bits_weight + self.num_bits, flatten_dims=(0, -1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> qbias = None <NEW_LINE> <DEDENT> if not self.biprecision or self.num_bits_grad is None: <NEW_LINE> <INDENT> output = F.linear(qinput, qweight, qbias) <NEW_LINE> if self.num_bits_grad is not None: <NEW_LINE> <INDENT> output = quantize_grad( output, num_bits=self.num_bits_grad) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> output = linear_biprec(qinput, qweight, qbias, self.num_bits_grad) <NEW_LINE> <DEDENT> return output | docstring for QConv2d. | 62598fb967a9b606de546137 |
class UserAssistantsList(object): <NEW_LINE> <INDENT> swagger_types = { 'assistants': 'list[UsersuserIdassistantsAssistants]' } <NEW_LINE> attribute_map = { 'assistants': 'assistants' } <NEW_LINE> def __init__(self, assistants=None): <NEW_LINE> <INDENT> self._assistants = None <NEW_LINE> self.discriminator = None <NEW_LINE> if assistants is not None: <NEW_LINE> <INDENT> self.assistants = assistants <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def assistants(self): <NEW_LINE> <INDENT> return self._assistants <NEW_LINE> <DEDENT> @assistants.setter <NEW_LINE> def assistants(self, assistants): <NEW_LINE> <INDENT> self._assistants = assistants <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(UserAssistantsList, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UserAssistantsList): <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. | 62598fb926068e7796d4cabf |
class Interaction(object): <NEW_LINE> <INDENT> INTERACT_SCRIPT = 'interact.scm' <NEW_LINE> def __init__(self, query): <NEW_LINE> <INDENT> self.query = query <NEW_LINE> self.proc = None <NEW_LINE> self.state = None <NEW_LINE> self.good_path = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.proc = Popen(['scheme', '--script', self.INTERACT_SCRIPT], stdin=PIPE, stdout=PIPE) <NEW_LINE> self._send(self.query) <NEW_LINE> self._read_state() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> self.proc.stdin.close() <NEW_LINE> <DEDENT> def _read(self): <NEW_LINE> <INDENT> txt = self.proc.stdout.readline().rstrip().decode('utf-8') <NEW_LINE> if not txt: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return lisp.parse(txt) <NEW_LINE> <DEDENT> def _send(self, datum): <NEW_LINE> <INDENT> self.proc.stdin.write((lisp.unparse(datum) + '\n').encode('utf-8')) <NEW_LINE> self.proc.stdin.flush() <NEW_LINE> <DEDENT> def _good_path(self): <NEW_LINE> <INDENT> if self.state is None: <NEW_LINE> <INDENT> self.good_path = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._send('good-path') <NEW_LINE> self.good_path = self._read() <NEW_LINE> <DEDENT> <DEDENT> def _read_state(self): <NEW_LINE> <INDENT> self.state = self._read() <NEW_LINE> self._good_path() <NEW_LINE> <DEDENT> def follow_path(self, path): <NEW_LINE> <INDENT> self._send(path) <NEW_LINE> feedback = self._read() <NEW_LINE> self._read_state() <NEW_LINE> return feedback <NEW_LINE> <DEDENT> def steps_remaining(self): <NEW_LINE> <INDENT> self._send('steps-remaining') <NEW_LINE> return self._read() <NEW_LINE> <DEDENT> def jump_to_steps_remaining(self, n): <NEW_LINE> <INDENT> self._send(['jump-to-steps-remaining', n]) <NEW_LINE> self._read_state() | Interaction object that communicates with scheme to solve a
miniKaren Programming by Example query. Should use with
with Interaction(query) as env:
...
See example_interaction_gt() for example usage. | 62598fb93346ee7daa3376fb |
class SoOrthoSliceDetail(coin.SoDetail): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def getTypeId(self): <NEW_LINE> <INDENT> return _simvoleon.SoOrthoSliceDetail_getTypeId(self) <NEW_LINE> <DEDENT> def getClassTypeId(): <NEW_LINE> <INDENT> return _simvoleon.SoOrthoSliceDetail_getClassTypeId() <NEW_LINE> <DEDENT> getClassTypeId = staticmethod(getClassTypeId) <NEW_LINE> def cleanupClass(): <NEW_LINE> <INDENT> return _simvoleon.SoOrthoSliceDetail_cleanupClass() <NEW_LINE> <DEDENT> cleanupClass = staticmethod(cleanupClass) <NEW_LINE> def initClass(): <NEW_LINE> <INDENT> return _simvoleon.SoOrthoSliceDetail_initClass() <NEW_LINE> <DEDENT> initClass = staticmethod(initClass) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> this = _simvoleon.new_SoOrthoSliceDetail() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _simvoleon.delete_SoOrthoSliceDetail <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def copy(self): <NEW_LINE> <INDENT> return _simvoleon.SoOrthoSliceDetail_copy(self) <NEW_LINE> <DEDENT> def getValueObjectPos(self): <NEW_LINE> <INDENT> return _simvoleon.SoOrthoSliceDetail_getValueObjectPos(self) <NEW_LINE> <DEDENT> def getValueDataPos(self): <NEW_LINE> <INDENT> return _simvoleon.SoOrthoSliceDetail_getValueDataPos(self) <NEW_LINE> <DEDENT> def getValue(self): <NEW_LINE> <INDENT> return _simvoleon.SoOrthoSliceDetail_getValue(self) | Proxy of C++ SoOrthoSliceDetail class | 62598fb932920d7e50bc61b4 |
class Event(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Event, self).__init__() <NEW_LINE> self.title = "Example Event 2015" <NEW_LINE> self.streets = Street(), Street(), Street() <NEW_LINE> self.closed_periods = [(datetime.datetime.utcnow() - datetime.timedelta(hours=random.randint(24, 36)), datetime.datetime.utcnow() - datetime.timedelta(hours=random.randint(-5, 25)))] <NEW_LINE> self.contact_name, self.contact_email = random.choice(example_people) <NEW_LINE> self.contact_phone = "+1 407-555-1823" <NEW_LINE> self.see_also_web = "http://parade.example.com/orlando/2016" <NEW_LINE> self.timeline = None <NEW_LINE> <DEDENT> def details_as_flowable(self): <NEW_LINE> <INDENT> return Paragraph(self.title + ", Contact: " + self.contact_name + "<" + self.contact_email + ">,\nclosed: " + ",\n".join(str(s) for s in self.streets), plain_para_style) <NEW_LINE> <DEDENT> def summary_as_flowable(self): <NEW_LINE> <INDENT> return ListItem(Paragraph(self.title, plain_para_style), list_item_style) <NEW_LINE> <DEDENT> def set_timeline(self, timeline): <NEW_LINE> <INDENT> self.timeline = timeline <NEW_LINE> <DEDENT> def timeline_as_flowable(self): <NEW_LINE> <INDENT> return self.timeline | A collection of streets, and a range of time, and a name. | 62598fb9f548e778e596b70c |
class Player(pygame.sprite.DirtySprite): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Player, self).__init__() <NEW_LINE> self.width = 10 <NEW_LINE> self.height = 25 <NEW_LINE> self.speed = 5.5 <NEW_LINE> self.color = 'white' <NEW_LINE> self.pos = pygame.Vector2(GAME.screen_width // 2, GAME.screen_width // 2) <NEW_LINE> self.image = pygame.Surface((self.width, self.height)) <NEW_LINE> self.image.set_colorkey('black') <NEW_LINE> self.image.fill(self.color) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.center = (self.rect.x + self.width, self.rect.y + self.height) <NEW_LINE> self.mask = pygame.mask.from_surface(self.image) <NEW_LINE> GAME.dirty_group_top.add(self) <NEW_LINE> <DEDENT> def update(self, move): <NEW_LINE> <INDENT> normalize_vector(move) <NEW_LINE> move *= self.speed <NEW_LINE> self.pos += move <NEW_LINE> if 1 > self.pos[0] + move[0]: <NEW_LINE> <INDENT> self.pos[0] = 1 <NEW_LINE> <DEDENT> if self.pos[0] > (GAME.screen_width - self.width): <NEW_LINE> <INDENT> self.pos[0] = (GAME.screen_width - self.width) - 1 <NEW_LINE> <DEDENT> if 1 > self.pos[1]: <NEW_LINE> <INDENT> self.pos[1] = 1 <NEW_LINE> <DEDENT> if self.pos[1] > (GAME.screen_height - self.height): <NEW_LINE> <INDENT> self.pos[1] = (GAME.screen_height - self.height) - 1 <NEW_LINE> <DEDENT> self.rect.x, self.rect.y = self.pos <NEW_LINE> self.center = (self.rect.x + self.width / 2, self.rect.y + self.height / 2) <NEW_LINE> self.dirty = 1 | User controlled object. Movement is based on arrow-key presses and limited to the screen dimensions. | 62598fb9283ffb24f3cf39ea |
class ContractGroup(BaseModel): <NEW_LINE> <INDENT> name = models.CharField(max_length=255, unique=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name | Contract group model. | 62598fb991f36d47f2230f5d |
class HuaweiK4605(HuaweiWCDMADevicePlugin): <NEW_LINE> <INDENT> name = "Huawei K4605" <NEW_LINE> version = "0.1" <NEW_LINE> author = u"Andrew Bird" <NEW_LINE> custom = HuaweiK4605Customizer() <NEW_LINE> __remote_name__ = "K4605" <NEW_LINE> __properties__ = { 'ID_VENDOR_ID': [0x12d1], 'ID_MODEL_ID': [0x14c6], } <NEW_LINE> conntype = consts.WADER_CONNTYPE_USB | :class:`~core.plugin.DevicePlugin` for Huawei's Vodafone K4605 | 62598fb963b5f9789fe852d4 |
class ProgressBarReader(progressbar.ProgressBar): <NEW_LINE> <INDENT> def __init__(self, iterable, widgets, max_value=None): <NEW_LINE> <INDENT> super(ProgressBarReader, self).__init__( widgets=widgets, max_value=max_value or progressbar.UnknownLength) <NEW_LINE> self._iterable = iterable <NEW_LINE> self.done = False <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = next(self._iterable) <NEW_LINE> if self.start_time is None: <NEW_LINE> <INDENT> self.start() <NEW_LINE> <DEDENT> self.update(self.value + value[0]["size"]) <NEW_LINE> return value <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> self.close() <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self.done: <NEW_LINE> <INDENT> self.finish() <NEW_LINE> self.done = True <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._iterable.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass | Extension of ProgressBar that supports starting and stopping the
BatchReader. | 62598fb94c3428357761a422 |
class TestLinkedQueue(object): <NEW_LINE> <INDENT> def test_linkedqueue_ctor(self): <NEW_LINE> <INDENT> queue = LinkedQueue() <NEW_LINE> assert_equal(0, len(queue)) <NEW_LINE> <DEDENT> @raises(EmptyError) <NEW_LINE> def test_emptylinkedqueue_front(self): <NEW_LINE> <INDENT> queue = LinkedQueue() <NEW_LINE> val = queue.front() <NEW_LINE> <DEDENT> @raises(EmptyError) <NEW_LINE> def test_emptylinkedqueue_dequeue(self): <NEW_LINE> <INDENT> queue = LinkedQueue() <NEW_LINE> val = queue.dequeue() <NEW_LINE> <DEDENT> def test_linkedqueue_enqueue(self): <NEW_LINE> <INDENT> queue = LinkedQueue() <NEW_LINE> for i in range(100): <NEW_LINE> <INDENT> queue.enqueue(i + 1) <NEW_LINE> assert_equal(1, queue.front()) <NEW_LINE> <DEDENT> assert_equal(100, len(queue)) <NEW_LINE> <DEDENT> def test_linkedqueue_dequeue(self): <NEW_LINE> <INDENT> queue = LinkedQueue() <NEW_LINE> for i in range(100): <NEW_LINE> <INDENT> queue.enqueue(i + 1) <NEW_LINE> <DEDENT> for i in range(100): <NEW_LINE> <INDENT> assert_equal(i + 1, queue.dequeue()) <NEW_LINE> assert_equal(99 - i, len(queue)) <NEW_LINE> <DEDENT> assert_equal(0, len(queue)) <NEW_LINE> <DEDENT> def test_linkedqueue_front(self): <NEW_LINE> <INDENT> queue = LinkedQueue() <NEW_LINE> for i in range(100): <NEW_LINE> <INDENT> queue.enqueue(i + 1) <NEW_LINE> <DEDENT> for i in range(100): <NEW_LINE> <INDENT> assert_equal(i + 1, queue.front()) <NEW_LINE> queue.dequeue() | Test class for the queue implementation | 62598fb9167d2b6e312b70dc |
class AsyncQequeSchedulerContainer(BaseSchedulerContainer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.url_queue = asyncio.Queue() <NEW_LINE> <DEDENT> async def push(self, request: Request): <NEW_LINE> <INDENT> await self.url_queue.put(request) <NEW_LINE> <DEDENT> async def pop(self) -> Optional[Request]: <NEW_LINE> <INDENT> res = await self.url_queue.get() <NEW_LINE> self.url_queue.task_done() <NEW_LINE> return res <NEW_LINE> <DEDENT> def size(self) -> int: <NEW_LINE> <INDENT> return self.url_queue.qsize() | deque 保存request | 62598fb910dbd63aa1c70d20 |
class Cash(Payment): <NEW_LINE> <INDENT> def __init__(self, id,amount): <NEW_LINE> <INDENT> super().__init__(id,amount) | cash class | 62598fb9e1aae11d1e7ce8d8 |
class Flatten(nn.Module): <NEW_LINE> <INDENT> def __init__(self, dims_in): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.size = dims_in[0] <NEW_LINE> <DEDENT> def forward(self, x, rev=False): <NEW_LINE> <INDENT> if not rev: <NEW_LINE> <INDENT> return [x[0].view(x[0].shape[0], -1)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [x[0].view(x[0].shape[0], *self.size)] <NEW_LINE> <DEDENT> <DEDENT> def jacobian(self, x, rev=False): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def output_dims(self, input_dims): <NEW_LINE> <INDENT> return [(int(np.prod(input_dims[0])),)] | Flattens N-D tensors into 1-D tensors. | 62598fb9656771135c4897d5 |
class RandomVocabulary(VocabularyBase): <NEW_LINE> <INDENT> CHOICES = ( ('consider', 'Deem to be'), ('minute', 'Infinitely or immeasurably small'), ('evident', 'Clearly revealed to the mind or the senses or judgment'), ('commit', 'Perform an act, usually with a negative connotation'), ('issue', 'Some situation or event that is thought about'), ('establish', 'Set up or found'), ) <NEW_LINE> def get_word_and_hint(self): <NEW_LINE> <INDENT> return random.choice(self.CHOICES) | Vocabulary example.
Choose random word from choices. | 62598fb97d43ff24874274b7 |
class rule_004(Rule): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Rule.__init__(self, 'loop_statement', '004', oToken, lAnchorTokens, oStartToken, oEndToken) <NEW_LINE> self.subphase = 3 | This rule checks the semicolon is on the same line as the **end loop** keyword.
**Violation**
.. code-block:: vhdl
end loop
;
end loop LOOP_LABEL
;
**Fix**
.. code-block:: vhdl
end loop;
end loop LOOP_LABEL; | 62598fb92c8b7c6e89bd392d |
class Filter: <NEW_LINE> <INDENT> def __init__(self, *functions): <NEW_LINE> <INDENT> self.functions = functions <NEW_LINE> <DEDENT> def apply(self, data): <NEW_LINE> <INDENT> return [item for item in data if all(i(item) for i in self.functions)] | Helper filter class. Accepts a list of single-argument
functions that return True if object in list conforms to some criteria | 62598fb9be383301e0253964 |
class SpiderMain(object): <NEW_LINE> <INDENT> def __init__(self,url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> <DEDENT> def _sleep(self): <NEW_LINE> <INDENT> time.sleep(random.randint(2,5)) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> driver = webdriver.Chrome() <NEW_LINE> driver.get(self.url) <NEW_LINE> driver.implicitly_wait(30) <NEW_LINE> self._sleep() <NEW_LINE> driver.find_element_by_id('upquery').send_keys(u'保险') <NEW_LINE> driver.find_element_by_class_name('swz2').click() <NEW_LINE> driver.implicitly_wait(30) <NEW_LINE> self.parser(driver) <NEW_LINE> while 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.ID,'sogou_next')))[0].click() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> driver.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.parser(driver) <NEW_LINE> <DEDENT> <DEDENT> driver.close() <NEW_LINE> <DEDENT> def parser(self,driver): <NEW_LINE> <INDENT> itemslist = driver.find_elements_by_xpath('//div[@class="news-box"]/ul[@class="news-list2"]//li') <NEW_LINE> print(itemslist) <NEW_LINE> for i in itemslist: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> wechatid = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.TAG_NAME, "label"))).text <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> wechatid = None <NEW_LINE> <DEDENT> i.find_element_by_tag_name('a').click() <NEW_LINE> windows = driver.window_handles <NEW_LINE> driver.switch_to_window(windows[-1]) <NEW_LINE> url = driver.current_url <NEW_LINE> try: <NEW_LINE> <INDENT> wechatname = WebDriverWait(driver,10).until( EC.presence_of_all_elements_located((By.CLASS_NAME,'tit')) ).text <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> wechatname = None <NEW_LINE> <DEDENT> url_news = driver.find_elements_by_xpath('//div[@class="weui_msg_card_bd"]//h4') <NEW_LINE> for i in range(len(url_news)): <NEW_LINE> <INDENT> time.sleep(5) <NEW_LINE> url_news = driver.find_elements_by_xpath('//div[@class="weui_msg_card_bd"]//h4') <NEW_LINE> url_news[i].click() <NEW_LINE> title = driver.find_element_by_class_name('rich_media_title').text <NEW_LINE> content = driver.find_element_by_class_name('rich_media_content').get_attribute('innerHTML') <NEW_LINE> driver.back() <NEW_LINE> print(wechatname,wechatid,url,title,content) <NEW_LINE> time.sleep(2) <NEW_LINE> <DEDENT> driver.close() <NEW_LINE> driver.switch_to_window(windows[0]) | 搜狗微信号内容爬取 | 62598fb98a43f66fc4bf22e2 |
class ListBase(Structure): <NEW_LINE> <INDENT> _fields_ = [ ('first', c_void_p), ('last', c_void_p) ] | source/blender/makesdna/DNA_listBase.h: 59 | 62598fb91f5feb6acb162d87 |
class HandlerTest(gr_testutil.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(HandlerTest, self).setUp() <NEW_LINE> self.handler = util.Handler(self.request, self.response) <NEW_LINE> FakeBase.clear() <NEW_LINE> util.now_fn = lambda: NOW <NEW_LINE> policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1) <NEW_LINE> self.testbed.init_datastore_v3_stub(consistency_policy=policy) <NEW_LINE> util.BLACKLIST.add('fa.ke') <NEW_LINE> <DEDENT> def expect_requests_get(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('headers', {}).update(util.USER_AGENT_HEADER) <NEW_LINE> if 'stream' not in kwargs: <NEW_LINE> <INDENT> kwargs['stream'] = True <NEW_LINE> <DEDENT> elif kwargs['stream'] == None: <NEW_LINE> <INDENT> del kwargs['stream'] <NEW_LINE> <DEDENT> return super(HandlerTest, self).expect_requests_get(*args, **kwargs) <NEW_LINE> <DEDENT> def expect_webmention_requests_get(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('headers', {}).update(util.USER_AGENT_HEADER) <NEW_LINE> return super(HandlerTest, self).expect_requests_get(*args, **kwargs) <NEW_LINE> <DEDENT> def expect_requests_post(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('headers', {}).update(util.USER_AGENT_HEADER) <NEW_LINE> return super(HandlerTest, self).expect_requests_post(*args, **kwargs) <NEW_LINE> <DEDENT> def expect_requests_head(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('headers', {}).update(util.USER_AGENT_HEADER) <NEW_LINE> return super(HandlerTest, self).expect_requests_head(*args, **kwargs) | Base test class.
| 62598fb93539df3088ecc415 |
class QueenAnt(ScubaThrower): <NEW_LINE> <INDENT> name = 'Queen' <NEW_LINE> food_cost = 7 <NEW_LINE> True_queen = 1 <NEW_LINE> powered_ants = [] <NEW_LINE> implemented = True <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> if QueenAnt.True_queen: <NEW_LINE> <INDENT> QueenAnt.True_queen = 0 <NEW_LINE> self.true = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.true = False <NEW_LINE> <DEDENT> Ant.__init__(self) <NEW_LINE> <DEDENT> def action(self, colony): <NEW_LINE> <INDENT> if not self.true: <NEW_LINE> <INDENT> self.reduce_armor(self.armor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ThrowerAnt.action(self, colony) <NEW_LINE> current_place = self.place.exit <NEW_LINE> while current_place: <NEW_LINE> <INDENT> if current_place.ant: <NEW_LINE> <INDENT> if current_place.ant not in self.powered_ants: <NEW_LINE> <INDENT> self.powered_ants.append(current_place.ant) <NEW_LINE> current_place.ant.damage = current_place.ant.damage * 2 <NEW_LINE> <DEDENT> if current_place.ant.container and current_place.ant.ant: <NEW_LINE> <INDENT> if current_place.ant.ant not in self.powered_ants: <NEW_LINE> <INDENT> self.powered_ants.append(current_place.ant.ant) <NEW_LINE> current_place.ant.ant.damage = current_place.ant.ant.damage * 2 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> current_place = current_place.exit <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def reduce_armor(self, amount): <NEW_LINE> <INDENT> Insect.reduce_armor(self, amount) <NEW_LINE> if self.true: <NEW_LINE> <INDENT> bees_win() | The Queen of the colony. The game is over if a bee enters her place. | 62598fb971ff763f4b5e78e0 |
class LiveStreamAiReviewImagePoliticalResult(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.StartPtsTime = None <NEW_LINE> self.EndPtsTime = None <NEW_LINE> self.Confidence = None <NEW_LINE> self.Suggestion = None <NEW_LINE> self.Label = None <NEW_LINE> self.Name = None <NEW_LINE> self.AreaCoordSet = None <NEW_LINE> self.Url = None <NEW_LINE> self.PicUrlExpireTime = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.StartPtsTime = params.get("StartPtsTime") <NEW_LINE> self.EndPtsTime = params.get("EndPtsTime") <NEW_LINE> self.Confidence = params.get("Confidence") <NEW_LINE> self.Suggestion = params.get("Suggestion") <NEW_LINE> self.Label = params.get("Label") <NEW_LINE> self.Name = params.get("Name") <NEW_LINE> self.AreaCoordSet = params.get("AreaCoordSet") <NEW_LINE> self.Url = params.get("Url") <NEW_LINE> self.PicUrlExpireTime = params.get("PicUrlExpireTime") | 直播 AI 内容审核图片鉴政结果
| 62598fb9091ae35668704d89 |
class PubKey(bytes): <NEW_LINE> <INDENT> def __new__(cls, buf, eckey=None): <NEW_LINE> <INDENT> self = super(PubKey, cls).__new__(cls, buf) <NEW_LINE> if eckey is None: <NEW_LINE> <INDENT> eckey = ECKey() <NEW_LINE> <DEDENT> eckey.pub = buf <NEW_LINE> self.eckey = eckey <NEW_LINE> return self <NEW_LINE> <DEDENT> def verify_compact(self, h, sig): <NEW_LINE> <INDENT> return self.eckey.verify_compact(h, sig) <NEW_LINE> <DEDENT> def verify(self, h, sig): <NEW_LINE> <INDENT> return self.eckey.verify(h, sig) | Public key | 62598fb94f6381625f199576 |
class Vector: <NEW_LINE> <INDENT> def __init__(self, d): <NEW_LINE> <INDENT> self._coords = [0]*d <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._coords) <NEW_LINE> <DEDENT> def __getitem__(self, j): <NEW_LINE> <INDENT> return self._coords[j] <NEW_LINE> <DEDENT> def __setitem__(self, j, val): <NEW_LINE> <INDENT> self._coords[j] = val <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> if len(self)!=len(other): <NEW_LINE> <INDENT> raise ValueError('Dimensions must agree.') <NEW_LINE> <DEDENT> result = Vector(len(self)) <NEW_LINE> for j in range(len(self)): <NEW_LINE> <INDENT> result[j] = self[j] + other[j] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._coords == other._coords <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<' + str(self._coords)[1:-1] + '>' | Represents a vector in a multidimensional space | 62598fb9a8370b77170f0547 |
class TestVoiceprintCtcdasrResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testVoiceprintCtcdasrResponse(self): <NEW_LINE> <INDENT> pass | VoiceprintCtcdasrResponse unit test stubs | 62598fb9ad47b63b2c5a79bb |
class ReconfigDetectionSQLQueryCommand(base.SQLCommand): <NEW_LINE> <INDENT> query = "SELECT * FROM gp_dist_random('gp_id')" <NEW_LINE> def __init__(self, conn): <NEW_LINE> <INDENT> base.SQLCommand.__init__(self, "Reconfig detection sql query") <NEW_LINE> self.cancel_conn = conn <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> dbconn.execSQL(self.cancel_conn, self.query) | A distributed query that will cause the system to detect
the reconfiguration of the system | 62598fb9aad79263cf42e93c |
class PrmFeu(Parametre): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Parametre.__init__(self, "feu", "fire") <NEW_LINE> self.aide_courte = "fait détonner le canon" <NEW_LINE> self.aide_longue = "Cette commande permet de faire détonner un canon " "présent dans la salle où vous vous trouvez. Celui-ci doit " "avoir été chargé en projectile (%canon% %canon:charger%) " "et poudre (%canon% %canon:poudre%). La quantité de poudre, " "sa puissance, le poids du projectile et d'autres facteurs " "déterminent la course du boulet." <NEW_LINE> <DEDENT> def interpreter(self, personnage, dic_masques): <NEW_LINE> <INDENT> salle = personnage.salle <NEW_LINE> personnage.agir("manip_canon") <NEW_LINE> canon = None <NEW_LINE> if hasattr(salle, "navire"): <NEW_LINE> <INDENT> for element in salle.elements: <NEW_LINE> <INDENT> if element.nom_type == "canon": <NEW_LINE> <INDENT> canon = element <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if canon is None: <NEW_LINE> <INDENT> personnage << "|err|Aucun canon ne se trouve ici.|ff|" <NEW_LINE> return <NEW_LINE> <DEDENT> if canon.onces == 0: <NEW_LINE> <INDENT> personnage << "|err|Ce canon n'est pas chargé en poudre.|ff|" <NEW_LINE> return <NEW_LINE> <DEDENT> if canon.projectile is None: <NEW_LINE> <INDENT> personnage << "|err|Ce canon ne contient pas de projectile.|ff|" <NEW_LINE> return <NEW_LINE> <DEDENT> canon.tirer(auteur=personnage) | Commande 'canon feu'.
| 62598fb923849d37ff85121b |
class AutoRestBoolTestService(object): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self._client = ServiceClient(None, config) <NEW_LINE> client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} <NEW_LINE> self._serialize = Serializer() <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> self.config = config <NEW_LINE> self.bool_model = BoolModel( self._client, self.config, self._serialize, self._deserialize) | Test Infrastructure for AutoRest
:param config: Configuration for client.
:type config: AutoRestBoolTestServiceConfiguration
:ivar bool_model: BoolModel operations
:vartype bool_model: .operations.BoolModel | 62598fb9d7e4931a7ef3c1fe |
class Limepy(LiteratureReferencesMixIn): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> LiteratureReferencesMixIn.__init__(self) <NEW_LINE> kwargs["M"] = 1 <NEW_LINE> kwargs["G"] = 1 <NEW_LINE> kwargs["rv"] = 1 <NEW_LINE> self.model = limepy(*args, **kwargs) <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> @property <NEW_LINE> def result(self): <NEW_LINE> <INDENT> stars = sample(self.model, **self.kwargs) <NEW_LINE> self.sample = stars <NEW_LINE> p = Particles(stars.N) <NEW_LINE> p.mass = stars.m | nbody_system.mass <NEW_LINE> p.x = stars.x | nbody_system.length <NEW_LINE> p.y = stars.y | nbody_system.length <NEW_LINE> p.z = stars.z | nbody_system.length <NEW_LINE> p.vx = stars.vx | nbody_system.length / nbody_system.time <NEW_LINE> p.vy = stars.vy | nbody_system.length / nbody_system.time <NEW_LINE> p.vz = stars.vz | nbody_system.length / nbody_system.time <NEW_LINE> return p | LIMEPY : Lowered Isothermal Model Explorer in PYthon
for help:
print help(limepy.limepy)
print help(limepy.sample)
Relevant references:
.. [#] Gieles & Zocchi 2015, MNRAS, 454,576 | 62598fb93617ad0b5ee062af |
class TotalVatAmount(Vat): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_vat(cls, vat): <NEW_LINE> <INDENT> return cls( value=vat.value, currency=vat.currency, rate=vat.rate, ) <NEW_LINE> <DEDENT> def to_xml(self, factory): <NEW_LINE> <INDENT> metadata = factory.resolver.find('ns0:totalVatAmount') <NEW_LINE> element = Element("totalVatAmount", ns=metadata.namespace()) <NEW_LINE> element.setText(str(int(self.value * 100))) <NEW_LINE> element.set('rate', self.rate) <NEW_LINE> element.set('currency', self.currency) <NEW_LINE> return element | A variation of the Vat for the totalVatAmount array. | 62598fb9009cb60464d0168c |
class ContextNotConfigured(Error): <NEW_LINE> <INDENT> pass | Thrown if use not configured context | 62598fb99f2886367281892d |
class LmdbEventStore(object): <NEW_LINE> <INDENT> def __init__(self, env): <NEW_LINE> <INDENT> self._env = env <NEW_LINE> self._event_history = self._env.open_db('event-history') | LMDB backed event store. | 62598fb9be383301e0253966 |
class QValues(Utilities): <NEW_LINE> <INDENT> @autocastable <NEW_LINE> def get_q_value(self, observation: D.T_agent[D.T_observation], action: D.T_agent[D.T_concurrency[D.T_event]]) -> D.T_value: <NEW_LINE> <INDENT> return self._get_q_value(observation, action) <NEW_LINE> <DEDENT> def _get_q_value(self, observation: D.T_agent[D.T_observation], action: D.T_agent[D.T_concurrency[D.T_event]]) -> D.T_value: <NEW_LINE> <INDENT> raise NotImplementedError | A solver must inherit this class if it can provide the Q function (i.e. action-value function). | 62598fb95fdd1c0f98e5e0f9 |
class PersonNew(object): <NEW_LINE> <INDENT> age = 3 <NEW_LINE> height = 170 <NEW_LINE> def __init__(self, name, age=18): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age | docstring for PersonNew | 62598fb9091ae35668704d8b |
class Sheet(PeriodicModel, TimeStampedModel, UUIDModel, ClassMethodMixin): <NEW_LINE> <INDENT> objects = SheetManager() <NEW_LINE> entity = models.ForeignKey( Entity, related_name='%(class)ss' ) <NEW_LINE> template = models.ForeignKey( BudgetTemplate, related_name='%(class)ss' ) <NEW_LINE> description = models.TextField( _('Budget description'), db_index=True, blank=True, help_text=_('Descriptive text for this %(class)s') ) <NEW_LINE> referencesources = generic.GenericRelation( ReferenceSource ) <NEW_LINE> auxsources = generic.GenericRelation( AuxSource ) <NEW_LINE> @property <NEW_LINE> def total(self): <NEW_LINE> <INDENT> tmp = [item.amount for item in self.items.all()] <NEW_LINE> value = sum(tmp) <NEW_LINE> return value <NEW_LINE> <DEDENT> @property <NEW_LINE> def item_count(self): <NEW_LINE> <INDENT> value = self.items.all().count() <NEW_LINE> return value <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> value = unicode(self.period) + ' ' + self.get_class_name() + ' for ' + self.entity.name <NEW_LINE> return value <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = ['entity'] | An abstract class for common Budget and Actual data | 62598fb9f548e778e596b70f |
class Order: <NEW_LINE> <INDENT> def __init__(self,order_id,price,timestamp,ordertype): <NEW_LINE> <INDENT> self.price = price <NEW_LINE> self.timestamp = TimeCal(timestamp) <NEW_LINE> self.orderid = order_id <NEW_LINE> self.ordertype = ordertype <NEW_LINE> <DEDENT> def order_time_relative(self): <NEW_LINE> <INDENT> return self.timestamp.relativetime() | 委托订单 | 62598fb932920d7e50bc61b8 |
class Example(OObject): <NEW_LINE> <INDENT> def __init__( self, summary: Optional[str] = None, description: Optional[str] = None, value: Optional[Any] = None, external_value: Optional[str] = None, ): <NEW_LINE> <INDENT> _assert_type(summary, (str,), "summary", self.__class__) <NEW_LINE> _assert_type(description, (str,), "description", self.__class__) <NEW_LINE> _assert_type(external_value, (str,), "external_value", self.__class__) <NEW_LINE> assert not (value and external_value) <NEW_LINE> self.summary = summary <NEW_LINE> self.description = description <NEW_LINE> self.value = value <NEW_LINE> self.external_value = external_value | In the `spec <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#example-object>`_ there is
no top-line description, but there is supplemental doc.
In all cases, the example value is expected to be compatible with the type schema of its associated value. Tooling
implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible. | 62598fb95fcc89381b266201 |
class EventCreateView(LoginRequiredMixin, HelpMixin, CreateView): <NEW_LINE> <INDENT> model = Event <NEW_LINE> form_class = EventCreateForm <NEW_LINE> def get_success_url(self): <NEW_LINE> <INDENT> messages.add_message(self.request, messages.SUCCESS, self.object.MESSAGES['create']) <NEW_LINE> return super().get_success_url() <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> form.instance.owner = self.request.user <NEW_LINE> form.instance.organization = self.request.user.organization <NEW_LINE> return super().form_valid(form) | СОЗДАНИЕ МЕРОПРИЯТИЙ | 62598fb923849d37ff85121d |
class Mapper(object): <NEW_LINE> <INDENT> def __init__(self,arch,bytes,base,entry,context): <NEW_LINE> <INDENT> raise NotImplementedError('Override __init__() in a child class') <NEW_LINE> <DEDENT> def gen_mapping(self): <NEW_LINE> <INDENT> raise NotImplementedError('Override gen_mapping() in a child class') <NEW_LINE> <DEDENT> def gen_newcode(self): <NEW_LINE> <INDENT> raise NotImplementedError('Override gen_newcode() in a child class') | A mapper maps old addresses to new addresses and old
instructions to new instructions.
This is a generic Mapper object. All mappers
used by this system should inherit from this parent
object and provide implementations for all functions listed. | 62598fb9236d856c2adc94f5 |
class FieldConverter(models.AbstractModel): <NEW_LINE> <INDENT> _name = 'ir.qweb.field' <NEW_LINE> @api.model <NEW_LINE> def attributes(self, record, field_name, options, values=None): <NEW_LINE> <INDENT> data = OrderedDict() <NEW_LINE> field = record._fields[field_name] <NEW_LINE> if not options['inherit_branding'] and not options['translate']: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> data['data-oe-model'] = record._name <NEW_LINE> data['data-oe-id'] = record.id <NEW_LINE> data['data-oe-field'] = field.name <NEW_LINE> data['data-oe-type'] = options.get('type') <NEW_LINE> data['data-oe-expression'] = options.get('expression') <NEW_LINE> if field.readonly: <NEW_LINE> <INDENT> data['data-oe-readonly'] = 1 <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> @api.model <NEW_LINE> def value_to_html(self, value, options): <NEW_LINE> <INDENT> return html_escape(pycompat.to_text(value), options) <NEW_LINE> <DEDENT> @api.model <NEW_LINE> def record_to_html(self, record, field_name, options): <NEW_LINE> <INDENT> if not record: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> value = record[field_name] <NEW_LINE> return False if value is False else record.env[self._name].value_to_html(value, options=options) <NEW_LINE> <DEDENT> @api.model <NEW_LINE> def user_lang(self): <NEW_LINE> <INDENT> lang_code = self._context.get('lang') or 'en_US' <NEW_LINE> return self.env['res.lang']._lang_get(lang_code) | Used to convert a t-field specification into an output HTML field.
:meth:`~.to_html` is the entry point of this conversion from QWeb, it:
* converts the record value to html using :meth:`~.record_to_html`
* generates the metadata attributes (``data-oe-``) to set on the root
result node
* generates the root result node itself through :meth:`~.render_element` | 62598fb9851cf427c66b8420 |
class DebuggerRubyPage(ConfigurationPageBase, Ui_DebuggerRubyPage): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(DebuggerRubyPage, self).__init__() <NEW_LINE> self.setupUi(self) <NEW_LINE> self.setObjectName("DebuggerRubyPage") <NEW_LINE> self.rubyInterpreterButton.setIcon(UI.PixmapCache.getIcon("open.png")) <NEW_LINE> self.rubyInterpreterCompleter = E5FileCompleter( self.rubyInterpreterEdit) <NEW_LINE> self.rubyInterpreterEdit.setText( Preferences.getDebugger("RubyInterpreter")) <NEW_LINE> self.rbRedirectCheckBox.setChecked( Preferences.getDebugger("RubyRedirect")) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> Preferences.setDebugger( "RubyInterpreter", self.rubyInterpreterEdit.text()) <NEW_LINE> Preferences.setDebugger( "RubyRedirect", self.rbRedirectCheckBox.isChecked()) <NEW_LINE> <DEDENT> @pyqtSlot() <NEW_LINE> def on_rubyInterpreterButton_clicked(self): <NEW_LINE> <INDENT> file = E5FileDialog.getOpenFileName( self, self.tr("Select Ruby interpreter for Debug Client"), self.rubyInterpreterEdit.text()) <NEW_LINE> if file: <NEW_LINE> <INDENT> self.rubyInterpreterEdit.setText( Utilities.toNativeSeparators(file)) | Class implementing the Debugger Ruby configuration page. | 62598fb9be7bc26dc9251f11 |
class RestoreTest(CBBackupRestoreBase): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> super(RestoreTest, self).run() <NEW_LINE> self.cbbackup(wrapper=self.test_config.test_case.use_backup_wrapper) <NEW_LINE> self.flush_buckets() <NEW_LINE> start = time() <NEW_LINE> self.run_cbrestore_with_stats( wrapper=self.test_config.test_case.use_backup_wrapper) <NEW_LINE> t = int(time() - start) <NEW_LINE> logger.info('restore completed in %s sec' % t) <NEW_LINE> if self.test_config.stats_settings.enabled: <NEW_LINE> <INDENT> self.reporter.post_to_sf(t) | After typical workload we backup all nodes then restore
and measure time it takes to perform restore. | 62598fb991f36d47f2230f5f |
@implementer(_IEllipticCurveExchangeKexAlgorithm) <NEW_LINE> class _ECDH384(object): <NEW_LINE> <INDENT> preference = 4 <NEW_LINE> hashProcessor = sha384 | Elliptic Curve Key Exchange with SHA-384 as HASH. Defined in
RFC 5656. | 62598fb963d6d428bbee291a |
class ZDT4(ZDTBaseProblem): <NEW_LINE> <INDENT> def __init__(self, num_variables=10, phenome_preprocessor=None, **kwargs): <NEW_LINE> <INDENT> f2 = ZDT_f2(ZDT1to4_f1, self.g, self.h) <NEW_LINE> self.min_bounds = [-5.0] * num_variables <NEW_LINE> self.min_bounds[0] = 0.0 <NEW_LINE> self.max_bounds = [5.0] * num_variables <NEW_LINE> self.max_bounds[0] = 1.0 <NEW_LINE> bounds = (self.min_bounds, self.max_bounds) <NEW_LINE> preprocessor = BoundConstraintsChecker(bounds, phenome_preprocessor) <NEW_LINE> ZDTBaseProblem.__init__(self, [ZDT1to4_f1, f2], num_objectives=2, phenome_preprocessor=preprocessor, **kwargs) <NEW_LINE> self.is_deterministic = True <NEW_LINE> self.do_maximize = False <NEW_LINE> self.num_variables = num_variables <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def h(f1_value, g_value): <NEW_LINE> <INDENT> return 1.0 - math.sqrt(f1_value / g_value) <NEW_LINE> <DEDENT> def g(self, phenome): <NEW_LINE> <INDENT> n = len(phenome) <NEW_LINE> assert n == self.num_variables <NEW_LINE> temp_sum = 0.0 <NEW_LINE> four_pi = 4 * math.pi <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> x = phenome[i] <NEW_LINE> temp_sum += x ** 2 - 10.0 * math.cos(four_pi * x) <NEW_LINE> <DEDENT> return 1.0 + 10.0 * (n - 1) + temp_sum | The ZDT4 problem. | 62598fb9283ffb24f3cf39ee |
class ArrayExpNode(VarExpNode): <NEW_LINE> <INDENT> def __init__(self, kind, line_number, name, expression, next_node = None): <NEW_LINE> <INDENT> VarExpNode.__init__(self, kind, line_number, name, next_node) <NEW_LINE> self.expression = expression <NEW_LINE> self.declaration = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string = '{} id = {}{}\nIndex Expression:\n{}{}{}'.format( self.base_string, self.name, ' type = {}'.format(self.type_string) if self.type_string is not None else '', indent(self.expression), '\nDeclaration:\n'+indent(dec_info(self.declaration))+'\n' if self.declaration is not None else '', str_if_not_none(self.next_node) ) <NEW_LINE> return string | Represents an array indexing expression, e.g. arr[x+1]. | 62598fb997e22403b383b071 |
class StructureType(Type): <NEW_LINE> <INDENT> def __init__(self, structure_type): <NEW_LINE> <INDENT> self.structure_type = structure_type <NEW_LINE> return <NEW_LINE> <DEDENT> def GetSExp(self): <NEW_LINE> <INDENT> li = [] <NEW_LINE> li.append('structure-of') <NEW_LINE> li.append(self.structure_type) <NEW_LINE> return li | Represents a Structure type. | 62598fb9aad79263cf42e93f |
class MediaStorage(S3BotoStorage): <NEW_LINE> <INDENT> location = settings.MEDIAFILES_LOCATION | Change the Media Storage. | 62598fb910dbd63aa1c70d24 |
class UnsupportedOSVersionError(XylemError): <NEW_LINE> <INDENT> pass | Version of OS is unsupported.
Overriding a specific version is not supported. Version-order can
not be computed for specific version. | 62598fb97d43ff24874274b9 |
class Schueler(object): <NEW_LINE> <INDENT> def setData( self, nachname, vorname, klasse, nutzername, passwort, uid ): <NEW_LINE> <INDENT> self.data = {"nachname" : nachname, "vorname": vorname, "klasse" : klasse, "nutzername" : nutzername, "passwort" : passwort, "uid" : uid } <NEW_LINE> <DEDENT> def debugInfo(self): <NEW_LINE> <INDENT> return "Schueler: %s %s aus der \t %s." % (self.data["vorname"], self.data["nachname"], self.data["klasse"]) <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return "%s %s" % ( self.data["vorname"], self.data["nachname"] ) <NEW_LINE> <DEDENT> def hatDatensatz(self, suche): <NEW_LINE> <INDENT> for item in self.data.itervalues(): <NEW_LINE> <INDENT> if item.contains(suche): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def toolTipString(self): <NEW_LINE> <INDENT> return "<html><body><b>Name:</b> %s %s<br /> <b>Nutzername:</b> \t%s<br /><b>Passwort:</b>\t%s</body></html>" % (self.data["vorname"], self.data["nachname"], self.data["nutzername"], self.data["passwort"] ) | Basisklasse für das Programm. Alle Infos eines Schülers
sind hier gespeichert. über debugInfo() erhält man einen kurzen
Überblick über den Schüler | 62598fb97cff6e4e811b5b8c |
class DraggableMixIn(ItemMixInBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._draggable = False <NEW_LINE> <DEDENT> def isDraggable(self): <NEW_LINE> <INDENT> return self._draggable <NEW_LINE> <DEDENT> def _setDraggable(self, draggable): <NEW_LINE> <INDENT> self._draggable = bool(draggable) <NEW_LINE> <DEDENT> def drag(self, from_, to): <NEW_LINE> <INDENT> raise NotImplementedError("Must be implemented in subclass") | Mix-in class for draggable items | 62598fb98a43f66fc4bf22e6 |
class EmailAuthBackend(ModelBackend): <NEW_LINE> <INDENT> def authenticate(self, request, **kwargs): <NEW_LINE> <INDENT> email = kwargs.get('email') <NEW_LINE> password = kwargs.get('password') <NEW_LINE> email = email.strip() if email else email <NEW_LINE> if email: <NEW_LINE> <INDENT> for user in User.objects.filter(email=email, is_active=True): <NEW_LINE> <INDENT> if user.check_password(password): <NEW_LINE> <INDENT> InvalidatedUser.objects.filter(user=user).update(password_changed=True) <NEW_LINE> return user <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None | Email Authentication Backend: make possible to use email rather than username for user authentication | 62598fb9f9cc0f698b1c5383 |
class WeakValueDictionary(weakref.WeakValueDictionary): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> weakref.WeakValueDictionary.__init__(self, *args, **kwargs) <NEW_LINE> remove_base = self._remove <NEW_LINE> def remove(*args): <NEW_LINE> <INDENT> if safe_equal is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if TLS is None: <NEW_LINE> <INDENT> return remove_base(*args) <NEW_LINE> <DEDENT> nested_hash_level = TLS.nested_hash_level <NEW_LINE> try: <NEW_LINE> <INDENT> TLS.nested_hash_level = 0 <NEW_LINE> remove_base(*args) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> TLS.nested_hash_level = nested_hash_level <NEW_LINE> <DEDENT> <DEDENT> self._remove = remove | A subclass of weakref.WeakValueDictionary
which resets the 'nested_hash_level' when keys are being deleted. | 62598fb9a8370b77170f054a |
class OutboundEventSocket(EventSocket): <NEW_LINE> <INDENT> def __init__(self, socket, address, filter="ALL", connect_timeout=60, eventjson=True, pool_size=5000, trace=False): <NEW_LINE> <INDENT> EventSocket.__init__(self, filter, eventjson, pool_size, trace=trace) <NEW_LINE> self.transport = OutboundTransport(socket, address, connect_timeout) <NEW_LINE> self._uuid = None <NEW_LINE> self._channel = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.trace("run now") <NEW_LINE> self.run() <NEW_LINE> self.trace("run done") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.trace("disconnect now") <NEW_LINE> self.disconnect() <NEW_LINE> self.trace("disconnect done") <NEW_LINE> <DEDENT> <DEDENT> def connect(self): <NEW_LINE> <INDENT> super(OutboundEventSocket, self).connect() <NEW_LINE> self.start_event_handler() <NEW_LINE> timer = Timeout(self.transport.get_connect_timeout()) <NEW_LINE> timer.start() <NEW_LINE> try: <NEW_LINE> <INDENT> connect_response = self._protocol_send("connect") <NEW_LINE> if not connect_response.is_success(): <NEW_LINE> <INDENT> raise ConnectError("Error while connecting") <NEW_LINE> <DEDENT> if connect_response.get_reply_text() == "+OK WatchDog": <NEW_LINE> <INDENT> raise WatchDog() <NEW_LINE> <DEDENT> <DEDENT> except Timeout: <NEW_LINE> <INDENT> raise ConnectError("Timeout connecting") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> timer.cancel() <NEW_LINE> <DEDENT> self._channel = connect_response <NEW_LINE> self._uuid = connect_response.get_header("Unique-ID") <NEW_LINE> self.connected = True <NEW_LINE> if self._filter: <NEW_LINE> <INDENT> if self._is_eventjson: <NEW_LINE> <INDENT> self.trace("using eventjson") <NEW_LINE> filter_response = self.eventjson(self._filter) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.trace("using eventplain") <NEW_LINE> filter_response = self.eventplain(self._filter) <NEW_LINE> <DEDENT> if not filter_response.is_success(): <NEW_LINE> <INDENT> raise ConnectError("Event filter failure") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_channel(self): <NEW_LINE> <INDENT> return self._channel <NEW_LINE> <DEDENT> def get_channel_unique_id(self): <NEW_LINE> <INDENT> return self._uuid <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> pass | FreeSWITCH Outbound Event Socket.
A new instance of this class is created for every call/ session from FreeSWITCH. | 62598fb967a9b606de54613d |
class Class(object): <NEW_LINE> <INDENT> _name = "" <NEW_LINE> _conditional_probabilities = {} <NEW_LINE> _prior_probability = 0.0 <NEW_LINE> def __init__(self, name, prior_probability, conditional_probabilities = None): <NEW_LINE> <INDENT> if conditional_probabilities is None: <NEW_LINE> <INDENT> conditional_probabilities = {} <NEW_LINE> <DEDENT> self._name = name <NEW_LINE> self._conditional_probabilities = conditional_probabilities <NEW_LINE> self._prior_probability = prior_probability <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def conditional_probabilites(self): <NEW_LINE> <INDENT> return self._conditional_probabilities <NEW_LINE> <DEDENT> def conditional_probability(self, word): <NEW_LINE> <INDENT> probability = 0 <NEW_LINE> if word in self._conditional_probabilities: <NEW_LINE> <INDENT> probability = self._conditional_probabilities[word] <NEW_LINE> <DEDENT> return probability <NEW_LINE> <DEDENT> @property <NEW_LINE> def prior_probability(self): <NEW_LINE> <INDENT> return self._prior_probability | Represents a class, has information about the prior probability of the class and maps words to
the conditional probability that they occur in a document of this class.
The prior_probability property contains the prior probability of the class, use the
conditional_probability(word) method to retrieve the probability for the given word or the
conditional_probabilities property to retrieve a dictionary mapping words to probability. | 62598fb9097d151d1a2c119e |
class AmbiguousRepr(object): <NEW_LINE> <INDENT> __repr__ = lambda self: Missing | Uninferable return value | 62598fb93d592f4c4edbb02a |
class TextToken(Token): <NEW_LINE> <INDENT> defaultStyle = 'fore:#000' | Anything that is not a string or comment. | 62598fb9099cdd3c63675498 |
class FetchLoveProduct(APIView): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> res = Product.objects.filter().order_by('-lovenum')[:5] <NEW_LINE> ret = ProductModelSerializer(res, many=True).data <NEW_LINE> mes = {} <NEW_LINE> mes['code'] = 200 <NEW_LINE> mes['list'] = ret <NEW_LINE> return Response(mes) | 首页 人气推荐 | 62598fb966656f66f7d5a55e |
class RHSubContributionREST(RHManageSubContributionBase): <NEW_LINE> <INDENT> def _process_DELETE(self): <NEW_LINE> <INDENT> delete_subcontribution(self.subcontrib) <NEW_LINE> flash(_("Subcontribution '{}' deleted successfully").format(self.subcontrib.title), 'success') <NEW_LINE> return jsonify_data(html=_render_subcontribution_list(self.contrib)) | REST endpoint for management of a single subcontribution. | 62598fb9f548e778e596b712 |
class LogAnalyticsOperationResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'properties': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'properties': {'key': 'properties', 'type': 'LogAnalyticsOutput'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(LogAnalyticsOperationResult, self).__init__(**kwargs) <NEW_LINE> self.properties = None | LogAnalytics operation status response.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar properties: LogAnalyticsOutput.
:vartype properties: ~azure.mgmt.compute.v2020_06_01.models.LogAnalyticsOutput | 62598fb9bf627c535bcb1610 |
class Font(object): <NEW_LINE> <INDENT> texture_width = 256 <NEW_LINE> texture_height = 256 <NEW_LINE> texture_internalformat = GL_ALPHA <NEW_LINE> ascent = 0 <NEW_LINE> descent = 0 <NEW_LINE> glyph_renderer_class = GlyphRenderer <NEW_LINE> texture_class = GlyphTextureAtlas <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.textures = [] <NEW_LINE> self.glyphs = {} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add_font_data(cls, data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def have_font(cls, name): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def create_glyph(self, image): <NEW_LINE> <INDENT> glyph = None <NEW_LINE> self._adapt_texture_size(image) <NEW_LINE> for texture in self.textures: <NEW_LINE> <INDENT> glyph = texture.fit(image) <NEW_LINE> if glyph: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if not glyph: <NEW_LINE> <INDENT> texture = self.texture_class.create_for_size(GL_TEXTURE_2D, self.texture_width, self.texture_height, self.texture_internalformat) <NEW_LINE> self.textures.insert(0, texture) <NEW_LINE> glyph = texture.fit(image) <NEW_LINE> <DEDENT> return glyph <NEW_LINE> <DEDENT> def _adapt_texture_size(self, image): <NEW_LINE> <INDENT> if image.width > self.texture_width or image.height > self.texture_height: <NEW_LINE> <INDENT> largest_dimension = max(image.width, image.height) <NEW_LINE> self.texture_height = self.texture_width = largest_dimension * 4 <NEW_LINE> <DEDENT> <DEDENT> def get_glyphs(self, text): <NEW_LINE> <INDENT> glyph_renderer = None <NEW_LINE> glyphs = [] <NEW_LINE> for c in get_grapheme_clusters(str(text)): <NEW_LINE> <INDENT> if c == '\t': <NEW_LINE> <INDENT> c = ' ' <NEW_LINE> <DEDENT> if c not in self.glyphs: <NEW_LINE> <INDENT> if not glyph_renderer: <NEW_LINE> <INDENT> glyph_renderer = self.glyph_renderer_class(self) <NEW_LINE> <DEDENT> self.glyphs[c] = glyph_renderer.render(c) <NEW_LINE> <DEDENT> glyphs.append(self.glyphs[c]) <NEW_LINE> <DEDENT> return glyphs <NEW_LINE> <DEDENT> def get_glyphs_for_width(self, text, width): <NEW_LINE> <INDENT> glyph_renderer = None <NEW_LINE> glyph_buffer = [] <NEW_LINE> glyphs = [] <NEW_LINE> for c in text: <NEW_LINE> <INDENT> if c == '\n': <NEW_LINE> <INDENT> glyphs += glyph_buffer <NEW_LINE> break <NEW_LINE> <DEDENT> if c not in self.glyphs: <NEW_LINE> <INDENT> if not glyph_renderer: <NEW_LINE> <INDENT> glyph_renderer = self.glyph_renderer_class(self) <NEW_LINE> <DEDENT> self.glyphs[c] = glyph_renderer.render(c) <NEW_LINE> <DEDENT> glyph = self.glyphs[c] <NEW_LINE> glyph_buffer.append(glyph) <NEW_LINE> width -= glyph.advance <NEW_LINE> if width <= 0 and len(glyphs) > 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if c in '\u0020\u200b': <NEW_LINE> <INDENT> glyphs += glyph_buffer <NEW_LINE> glyph_buffer = [] <NEW_LINE> <DEDENT> <DEDENT> if len(glyphs) == 0: <NEW_LINE> <INDENT> glyphs = glyph_buffer <NEW_LINE> <DEDENT> return glyphs | Abstract font class able to produce glyphs.
To construct a font, use `pyglet.font.load`, which will instantiate the
platform-specific font class.
Internally, this class is used by the platform classes to manage the set
of textures into which glyphs are written.
:Ivariables:
`ascent` : int
Maximum ascent above the baseline, in pixels.
`descent` : int
Maximum descent below the baseline, in pixels. Usually negative. | 62598fb991f36d47f2230f60 |
class CommonMetricPrinter(EventWriter): <NEW_LINE> <INDENT> def __init__(self, max_iter): <NEW_LINE> <INDENT> self.logger = logging.getLogger(__name__) <NEW_LINE> self._max_iter = max_iter <NEW_LINE> self._last_write = None <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> storage = get_event_storage() <NEW_LINE> iteration = storage.iter <NEW_LINE> try: <NEW_LINE> <INDENT> data_time = storage.history("data_time").avg(20) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> data_time = None <NEW_LINE> <DEDENT> eta_string = None <NEW_LINE> try: <NEW_LINE> <INDENT> iter_time = storage.history("time").global_avg() <NEW_LINE> eta_seconds = storage.history("time").median(1000) * (self._max_iter - iteration) <NEW_LINE> eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> iter_time = None <NEW_LINE> if self._last_write is not None: <NEW_LINE> <INDENT> estimate_iter_time = (time.perf_counter() - self._last_write[1]) / ( iteration - self._last_write[0] ) <NEW_LINE> eta_seconds = estimate_iter_time * (self._max_iter - iteration) <NEW_LINE> eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) <NEW_LINE> <DEDENT> self._last_write = (iteration, time.perf_counter()) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> lr = "{:.6f}".format(storage.history("lr").latest()) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> lr = "N/A" <NEW_LINE> <DEDENT> if torch.cuda.is_available(): <NEW_LINE> <INDENT> max_mem_mb = torch.cuda.max_memory_allocated() / 1024.0 / 1024.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> max_mem_mb = None <NEW_LINE> <DEDENT> losses = " ".join( [ "{}: {:.3f}".format(k, v.median(20)) for k, v in storage.histories().items() if "loss" in k ] ) <NEW_LINE> other_metrics = " ".join( [ "{}: {:.3f}".format(k, v.median(20)) for k, v in storage.histories().items() if "loss" not in k and k not in ["data_time", "time", "lr"] and "/" not in k ] ) <NEW_LINE> self.logger.info( ("eta: {eta} iter: {iter}/{max_iter} {losses} {other_metrics} " "{data_time} lr: {lr} {memory}").format( eta=eta_string, iter=iteration + 1, max_iter=self._max_iter, losses=losses, other_metrics=other_metrics, data_time="data_time: {:.4f}".format(data_time) if data_time is not None else "", lr=lr, memory="max_mem: {:.0f}M".format(max_mem_mb) if max_mem_mb is not None else "", ) ) | Print **common** metrics to the terminal, including
iteration time, ETA, memory, all losses, and the learning rate.
To print something different, please implement a similar printer by yourself. | 62598fb9d7e4931a7ef3c202 |
class ModuleStoreNoSettings(unittest.TestCase): <NEW_LINE> <INDENT> HOST = MONGO_HOST <NEW_LINE> PORT = MONGO_PORT_NUM <NEW_LINE> DB = 'test_mongo_%s' % uuid4().hex[:5] <NEW_LINE> COLLECTION = 'modulestore' <NEW_LINE> FS_ROOT = DATA_DIR <NEW_LINE> DEFAULT_CLASS = 'modulestore.tests.test_xml_importer.StubXBlock' <NEW_LINE> RENDER_TEMPLATE = lambda t_n, d, ctx=None, nsp='main': '' <NEW_LINE> modulestore_options = { 'default_class': DEFAULT_CLASS, 'fs_root': DATA_DIR, 'render_template': RENDER_TEMPLATE, } <NEW_LINE> DOC_STORE_CONFIG = { 'host': HOST, 'port': PORT, 'db': DB, 'collection': COLLECTION, } <NEW_LINE> MODULESTORE = { 'ENGINE': 'modulestore.mongo.DraftMongoModuleStore', 'DOC_STORE_CONFIG': DOC_STORE_CONFIG, 'OPTIONS': modulestore_options } <NEW_LINE> modulestore = None <NEW_LINE> def cleanup_modulestore(self): <NEW_LINE> <INDENT> if self.modulestore: <NEW_LINE> <INDENT> self.modulestore._drop_database() <NEW_LINE> <DEDENT> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.addCleanup(self.cleanup_modulestore) <NEW_LINE> super(ModuleStoreNoSettings, self).setUp() | A mixin to create a mongo modulestore that avoids settings | 62598fb999cbb53fe6831045 |
class UncheckedKey(KaitaiStruct): <NEW_LINE> <INDENT> def __init__(self, _io, _parent=None, _root=None): <NEW_LINE> <INDENT> self._io = _io <NEW_LINE> self._parent = _parent <NEW_LINE> self._root = _root if _root else self <NEW_LINE> self._read() <NEW_LINE> <DEDENT> def _read(self): <NEW_LINE> <INDENT> self.previous = self._io.read_bytes(32) <NEW_LINE> self.hash = self._io.read_bytes(32) | Key of the unchecked table. | 62598fb91b99ca400228f5e7 |
class PubSubQueue(asyncio.Queue): <NEW_LINE> <INDENT> def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> super().__init__(*args, **kwds) <NEW_LINE> self._exc = None <NEW_LINE> self._closed = False <NEW_LINE> <DEDENT> def close(self, exc=None): <NEW_LINE> <INDENT> self._exc = exc <NEW_LINE> self._closed = True <NEW_LINE> while self._getters: <NEW_LINE> <INDENT> getter = self._getters.popleft() <NEW_LINE> if not getter.done(): <NEW_LINE> <INDENT> if exc: <NEW_LINE> <INDENT> getter.set_exception(exc) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> getter.set_result(None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> async def get(self): <NEW_LINE> <INDENT> while self.empty(): <NEW_LINE> <INDENT> if self._closed: <NEW_LINE> <INDENT> if self._exc: <NEW_LINE> <INDENT> raise QueueClosedError from self._exc <NEW_LINE> <DEDENT> raise QueueClosedError <NEW_LINE> <DEDENT> getter = self._loop.create_future() <NEW_LINE> self._getters.append(getter) <NEW_LINE> try: <NEW_LINE> <INDENT> await getter <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> getter.cancel() <NEW_LINE> try: <NEW_LINE> <INDENT> self._getters.remove(getter) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if not self.empty() and not getter.cancelled(): <NEW_LINE> <INDENT> self._wakeup_next(self._getters) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> <DEDENT> return self.get_nowait() <NEW_LINE> <DEDENT> def _put(self, *args, **kwds): <NEW_LINE> <INDENT> if self._closed: <NEW_LINE> <INDENT> raise QueueClosedError <NEW_LINE> <DEDENT> return super()._put(*args, **kwds) <NEW_LINE> <DEDENT> def __aiter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> async def __anext__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.qsize(): <NEW_LINE> <INDENT> return self.get_nowait() <NEW_LINE> <DEDENT> return await self.get() <NEW_LINE> <DEDENT> except QueueClosedError: <NEW_LINE> <INDENT> raise self._exc or StopAsyncIteration | Queue class to hold incomming messages. | 62598fb99c8ee8231304022a |
class CRAM2FASTQ(ConvBase): <NEW_LINE> <INDENT> _default_method = "samtools" <NEW_LINE> _threading = True <NEW_LINE> def __init__(self, infile, outfile, *args, **kargs): <NEW_LINE> <INDENT> super(CRAM2FASTQ, self).__init__(infile, outfile, *args, **kargs) <NEW_LINE> <DEDENT> @requires("samtools") <NEW_LINE> def _method_samtools(self, *args, **kwargs): <NEW_LINE> <INDENT> cmd = "samtools fastq {} > {}".format(self.infile, self.outfile) <NEW_LINE> self.execute(cmd) <NEW_LINE> p = subprocess.Popen("samtools view -c -f 1 {}".format( self.infile).split(),stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) <NEW_LINE> isPaired = p.communicate()[0].strip() <NEW_LINE> ext = os.path.splitext(self.outfile)[1] <NEW_LINE> output_ext = get_extension(self.outfile, remove_compression=True) <NEW_LINE> if ext in [".gz",".bz2",".dsrc"]: <NEW_LINE> <INDENT> outbasename = os.path.splitext(self.outfile)[0].split(".",1)[0] <NEW_LINE> if ext == ".gz": <NEW_LINE> <INDENT> compresscmd = "gzip -f" <NEW_LINE> <DEDENT> elif ext == ".bz2": <NEW_LINE> <INDENT> compresscmd = "pbzip2 -f" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> compresscmd = "dsrc c" <NEW_LINE> <DEDENT> if isPaired == "0": <NEW_LINE> <INDENT> cmd = "samtools fastq -@ {} {} > {}.{}".format(self.threads, self.infile, outbasename, output_ext) <NEW_LINE> self.execute(cmd) <NEW_LINE> if ext == ".dsrc": <NEW_LINE> <INDENT> cmd = "{} {}.{} {}.{}.dsrc".format(compresscmd, outbasename, output_ext, outbasename, output_ext) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = "{} {}.{}".format(compresscmd, outbasename, output_ext) <NEW_LINE> <DEDENT> self.execute(cmd) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = "samtools fastq -@ {} -1 {}_1.{} -2 {}_2.{} -n {} ".format( self.threads, outbasename, output_ext, outbasename, output_ext, self.infile) <NEW_LINE> self.execute(cmd) <NEW_LINE> if ext == ".dsrc": <NEW_LINE> <INDENT> cmd = "{} {}_1.{} {}_1.{}.dsrc".format(compresscmd, outbasename, output_ext, outbasename, output_ext) <NEW_LINE> self.execute(cmd) <NEW_LINE> cmd = "{} {}_2.{} {}_2.{}.dsrc".format(compresscmd, outbasename, output_ext, outbasename, output_ext) <NEW_LINE> self.execute(cmd) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = "{} {}_1.{}".format(compresscmd, outbasename, output_ext) <NEW_LINE> self.execute(cmd) <NEW_LINE> cmd = "{} {}_2.{}".format(compresscmd, outbasename, output_ext) <NEW_LINE> self.execute(cmd) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> outbasename = os.path.splitext(self.outfile)[0] <NEW_LINE> if isPaired == "0": <NEW_LINE> <INDENT> cmd = "samtools fastq -@ {} {} > {}".format(self.threads, self.infile, self.outfile) <NEW_LINE> self.execute(cmd) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = "samtools fastq -@ {} -1 {}_1.{} -2 {}_2.{} -n {} ".format(self.threads, outbasename, output_ext, outbasename, output_ext, self.infile) <NEW_LINE> self.execute(cmd) | Convert :term:`CRAM` file to :term:`FASTQ` file
Methods available are based on samtools [SAMTOOLS]_. | 62598fb94c3428357761a427 |
class KittiOdometryDataset(dataset.DatasetMixin): <NEW_LINE> <INDENT> def __init__(self, data_dir=None, seq_len=3, split='train'): <NEW_LINE> <INDENT> with open(os.path.join(data_dir, "{}.txt".format(split)), 'r') as f: <NEW_LINE> <INDENT> dir_indexes = f.read().split('\n') <NEW_LINE> <DEDENT> if not dir_indexes[-1]: <NEW_LINE> <INDENT> dir_indexes = dir_indexes[:-1] <NEW_LINE> <DEDENT> self.dir_pathes = [os.path.join(data_dir, index) for index in dir_indexes] <NEW_LINE> self.seq_len = seq_len <NEW_LINE> self.samples = self.crawl_folders() <NEW_LINE> print('{} num sample'.format(split), len(self.samples)) <NEW_LINE> <DEDENT> def crawl_folders(self): <NEW_LINE> <INDENT> sequence_set = [] <NEW_LINE> demi_len = (self.seq_len - 1)//2 <NEW_LINE> for dir_path in self.dir_pathes: <NEW_LINE> <INDENT> calib_path = os.path.join(dir_path, 'cam.txt') <NEW_LINE> intrinsics = np.genfromtxt(calib_path, delimiter=',') <NEW_LINE> intrinsics = intrinsics.astype(np.float32).reshape((3, 3)) <NEW_LINE> imgs = glob.glob(os.path.join(dir_path, '*.jpg')) <NEW_LINE> imgs.sort() <NEW_LINE> if len(imgs) < self.seq_len: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for i in range(demi_len, len(imgs)-demi_len): <NEW_LINE> <INDENT> sample = {'intrinsics': intrinsics, 'tgt': imgs[i], 'ref_imgs': []} <NEW_LINE> for j in range(-demi_len, demi_len + 1): <NEW_LINE> <INDENT> if j != 0: <NEW_LINE> <INDENT> sample['ref_imgs'].append(imgs[i+j]) <NEW_LINE> <DEDENT> <DEDENT> sequence_set.append(sample) <NEW_LINE> <DEDENT> <DEDENT> random.shuffle(sequence_set) <NEW_LINE> return sequence_set <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.samples) <NEW_LINE> <DEDENT> def save_img(self, tgt_img, ref_imgs): <NEW_LINE> <INDENT> import cv2 <NEW_LINE> cv2.imwrite('tgt.png', tgt_img.transpose(1, 2, 0).astype('i')) <NEW_LINE> cv2.imwrite('src1.png', ref_imgs[0].transpose(1, 2, 0).astype('i')) <NEW_LINE> cv2.imwrite('src2.png', ref_imgs[1].transpose(1, 2, 0).astype('i')) <NEW_LINE> <DEDENT> def get_example(self, i): <NEW_LINE> <INDENT> sample = self.samples[i] <NEW_LINE> tgt_img = load_as_float_norm(sample['tgt']) <NEW_LINE> ref_imgs = [load_as_float_norm(ref_img) for ref_img in sample['ref_imgs']] <NEW_LINE> intrinsics = np.copy(sample['intrinsics']) <NEW_LINE> return tgt_img, ref_imgs, intrinsics, np.linalg.inv(intrinsics) | Dataset class for a task on `Kitti Raw Dataset`_.
Args:
data_dir (string): Path to the dataset directory. The directory should
contain at least three directories, :obj:`training`, `testing`
and `ImageSets`.
split ({'train', 'val'}): Select from dataset splits used in
KiTTi Raw Dataset. | 62598fb93346ee7daa3376fe |
class Refreshable(RedditContentObject): <NEW_LINE> <INDENT> def refresh(self): <NEW_LINE> <INDENT> unique = self.reddit_session._unique_count <NEW_LINE> self.reddit_session._unique_count += 1 <NEW_LINE> if isinstance(self, Redditor): <NEW_LINE> <INDENT> other = Redditor(self.reddit_session, self._case_name, fetch=True, uniq=unique) <NEW_LINE> <DEDENT> elif isinstance(self, Comment): <NEW_LINE> <INDENT> sub = Submission.from_url(self.reddit_session, self.permalink, params={'uniq': unique}) <NEW_LINE> other = sub.comments[0] <NEW_LINE> <DEDENT> elif isinstance(self, Multireddit): <NEW_LINE> <INDENT> other = Multireddit(self.reddit_session, author=self._author, name=self.name, uniq=unique, fetch=True) <NEW_LINE> <DEDENT> elif isinstance(self, Submission): <NEW_LINE> <INDENT> params = self._params.copy() <NEW_LINE> params['uniq'] = unique <NEW_LINE> other = Submission.from_url(self.reddit_session, self.permalink, comment_sort=self._comment_sort, params=params) <NEW_LINE> <DEDENT> elif isinstance(self, Subreddit): <NEW_LINE> <INDENT> other = Subreddit(self.reddit_session, self._case_name, fetch=True, uniq=unique) <NEW_LINE> <DEDENT> elif isinstance(self, WikiPage): <NEW_LINE> <INDENT> other = WikiPage(self.reddit_session, six.text_type(self.subreddit), self.page, fetch=True, uniq=unique) <NEW_LINE> <DEDENT> self.__dict__ = other.__dict__ <NEW_LINE> return self | Interface for objects that can be refreshed. | 62598fb910dbd63aa1c70d26 |
class Life: <NEW_LINE> <INDENT> def __init__(self, ROWS, COLUMNS): <NEW_LINE> <INDENT> self.ROWS = ROWS <NEW_LINE> self.COLUMNS = COLUMNS <NEW_LINE> self.grid = np.zeros((self.COLUMNS, self.ROWS)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.grid) <NEW_LINE> <DEDENT> def nextGeneration(self): <NEW_LINE> <INDENT> newGrid = np.zeros((self.COLUMNS, self.ROWS)) <NEW_LINE> nextGenerationCalculation(self.grid, newGrid) <NEW_LINE> self.grid = newGrid <NEW_LINE> <DEDENT> def randomize(self): <NEW_LINE> <INDENT> self.grid = np.random.randint(0,2,(self.COLUMNS, self.ROWS)) | The game of life | 62598fbaec188e330fdf89fe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.