code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
class _PipeWriter(_UnicodeWriter, asyncio.BaseProtocol): <NEW_LINE> <INDENT> def __init__(self, process, datatype, encoding): <NEW_LINE> <INDENT> super().__init__(encoding) <NEW_LINE> self._process = process <NEW_LINE> self._datatype = datatype <NEW_LINE> self._transport = None <NEW_LINE> <DEDENT> def connection_made(self, transport): <NEW_LINE> <INDENT> self._transport = transport <NEW_LINE> <DEDENT> def pause_writing(self): <NEW_LINE> <INDENT> self._process.pause_feeding(self._datatype) <NEW_LINE> <DEDENT> def resume_writing(self): <NEW_LINE> <INDENT> self._process.resume_feeding(self._datatype) <NEW_LINE> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> self._transport.write(self.encode(data)) <NEW_LINE> <DEDENT> def write_eof(self): <NEW_LINE> <INDENT> self._transport.write_eof() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._transport.close()
|
Forward data to a pipe
|
62599029d164cc6175821f2e
|
class NDDataRead(registry.UnifiedReadWrite): <NEW_LINE> <INDENT> def __init__(self, instance, cls): <NEW_LINE> <INDENT> super().__init__(instance, cls, 'read') <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> return registry.read(self._cls, *args, **kwargs)
|
Read and parse gridded N-dimensional data and return as an NDData-derived
object.
This function provides the NDDataBase interface to the astropy unified I/O
layer. This allows easily reading a file in the supported data formats,
for example::
>>> from astropy.nddata import CCDData
>>> dat = CCDData.read('image.fits')
Get help on the available readers for ``CCDData`` using the``help()`` method::
>>> CCDData.read.help() # Get help reading CCDData and list supported formats
>>> CCDData.read.help('fits') # Get detailed help on CCDData FITS reader
>>> CCDData.read.list_formats() # Print list of available formats
See also:
- http://docs.astropy.org/en/stable/nddata
- http://docs.astropy.org/en/stable/io/unified.html
Parameters
----------
*args : tuple, optional
Positional arguments passed through to data reader. If supplied the
first argument is the input filename.
format : str, optional
File format specifier.
**kwargs : dict, optional
Keyword arguments passed through to data reader.
Returns
-------
out : `NDData` subclass
NDData-basd object corresponding to file contents
Notes
-----
|
62599029d99f1b3c44d06659
|
class ConnectionError(NetError): <NEW_LINE> <INDENT> pass
|
Failed to connect to the server.
|
62599029507cdc57c63a5d5e
|
class MalformedStatement(MigrateError): <NEW_LINE> <INDENT> pass
|
Incorrect statement exception
|
62599029d18da76e235b7929
|
class DeviceSpace(ColorSpace): <NEW_LINE> <INDENT> def __init__(self, family, default): <NEW_LINE> <INDENT> super(DeviceSpace, self).__init__(family, len(default), default) <NEW_LINE> if family.name == 'DeviceGray': <NEW_LINE> <INDENT> self.as_rgb = lambda value: value * 3 <NEW_LINE> <DEDENT> elif family.name == 'DeviceRGB': <NEW_LINE> <INDENT> self.as_rgb = lambda value: value <NEW_LINE> <DEDENT> elif family.name == 'DeviceCMYK': <NEW_LINE> <INDENT> self.as_rgb = lambda value: self.cmyk_to_rgb(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid device family name: %s", family.name) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def cmyk_to_rgb(cmyk_value): <NEW_LINE> <INDENT> cyan, magenta, yellow, black = cmyk_value <NEW_LINE> return ( 1.0 - min(1, cyan + black), 1.0 - min(1, magenta + black), 1.0 - min(1, yellow + black) )
|
One of the 3 device spaces (DeviceGray, DeviceRGB, DeviceCMYK).
|
625990298e05c05ec3f6f637
|
class Syllables(Base): <NEW_LINE> <INDENT> __tablename__ = 'syllables' <NEW_LINE> word = Column(String(255), nullable= False,primary_key= True) <NEW_LINE> syllable = Column(String(255), nullable= False) <NEW_LINE> mysql_charset='utf8mb4'
|
This Class Contains all of the users
|
625990298a349b6b436871f0
|
class AutodetectionError(RuntimeError): <NEW_LINE> <INDENT> pass
|
Raised when autodetecting the environment fails.
|
62599029ac7a0e7691f734a0
|
class Diffusion(AdvectionDiffusion): <NEW_LINE> <INDENT> def __init__(self, K=None, diffusion_axis=None, use_banded_solver=False, **kwargs): <NEW_LINE> <INDENT> super(Diffusion, self).__init__(K=K, U=0., diffusion_axis=diffusion_axis, use_banded_solver=use_banded_solver, **kwargs)
|
1D diffusion only, with advection set to zero.
Otherwise identical to the parent class AdvectionDiffusion.
|
625990299b70327d1c57fd3a
|
class BaseRunner(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.quiet = False <NEW_LINE> self.force = False <NEW_LINE> self.suppress_errors = False <NEW_LINE> self.suppress_warnings = False <NEW_LINE> self.quiet = False <NEW_LINE> self._print_lock = threading.RLock() <NEW_LINE> <DEDENT> def print_message(self, msg): <NEW_LINE> <INDENT> if self.quiet: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._print(msg) <NEW_LINE> <DEDENT> def print_warning(self, msg): <NEW_LINE> <INDENT> if self.suppress_warnings: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> msg = colors.format('<red>WARNING</red>: %s', msg) <NEW_LINE> self._print(msg, to_stderr=True) <NEW_LINE> <DEDENT> def print_error(self, msg): <NEW_LINE> <INDENT> if self.suppress_errors: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> msg = colors.format('<red>ERROR</red>: %s', msg) <NEW_LINE> self._print(msg, to_stderr=True) <NEW_LINE> <DEDENT> def print_json(self, data): <NEW_LINE> <INDENT> self.print_message(json.dumps(data, sort_keys=True, indent=2)) <NEW_LINE> <DEDENT> def _print(self, msg, to_stderr=False): <NEW_LINE> <INDENT> target = sys.stderr if to_stderr else sys.stdout <NEW_LINE> with self._print_lock: <NEW_LINE> <INDENT> target.write(msg + '\n') <NEW_LINE> <DEDENT> <DEDENT> def confirm(self, message, default=False): <NEW_LINE> <INDENT> if self.force: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> yes = 'Y' if default else 'y' <NEW_LINE> no = 'n' if default else 'N' <NEW_LINE> result = raw_input('%s [%s/%s]: ' % (message, yes, no)) <NEW_LINE> return result.lower() == yes
|
Base class for runners.
|
62599029a8ecb033258721d5
|
class SimContext(InstanceContext): <NEW_LINE> <INDENT> def __init__(self, version, sid): <NEW_LINE> <INDENT> super(SimContext, self).__init__(version) <NEW_LINE> self._solution = {'sid': sid, } <NEW_LINE> self._uri = '/Sims/{sid}'.format(**self._solution) <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> payload = self._version.fetch(method='GET', uri=self._uri, ) <NEW_LINE> return SimInstance(self._version, payload, sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> def update(self, unique_name=values.unset, status=values.unset, fleet=values.unset, callback_url=values.unset, callback_method=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'UniqueName': unique_name, 'Status': status, 'Fleet': fleet, 'CallbackUrl': callback_url, 'CallbackMethod': callback_method, }) <NEW_LINE> payload = self._version.update(method='POST', uri=self._uri, data=data, ) <NEW_LINE> return SimInstance(self._version, payload, sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Supersim.V1.SimContext {}>'.format(context)
|
PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com.
|
6259902915baa72349462f50
|
class AbstractRouter(AbstractSoftware): <NEW_LINE> <INDENT> pass
|
Базовый класс для всего маршрутизирующего ПО.
|
6259902930c21e258be997c4
|
class OSMWay: <NEW_LINE> <INDENT> def __init__(self, id): <NEW_LINE> <INDENT> if not isinstance(id, int): <NEW_LINE> <INDENT> raise NameError('In class OSMWay: constructor: id must be an integer') <NEW_LINE> <DEDENT> self.id = id <NEW_LINE> self.node_ids = [] <NEW_LINE> self.line_type = None <NEW_LINE> <DEDENT> def add_node_id(self, id): <NEW_LINE> <INDENT> if not isinstance(id, int): <NEW_LINE> <INDENT> raise NameError('In class OSMWay: add_node_id: id must be an integer') <NEW_LINE> <DEDENT> self.node_ids.append( id ) <NEW_LINE> <DEDENT> def set_line_type(self, line_type): <NEW_LINE> <INDENT> if not isinstance(line_type, str): <NEW_LINE> <INDENT> raise NameError('In class OSMWay: set_line_type: line_type must be a string') <NEW_LINE> <DEDENT> self.line_type = line_type
|
This class is the OSM Way container
|
625990293eb6a72ae038b61e
|
class EDTestCasePluginExecuteControlGridScreeningv1_0_integrationError(EDTestCasePluginExecuteControlGridScreeningv1_0): <NEW_LINE> <INDENT> def __init__(self, _edStringTestName=None): <NEW_LINE> <INDENT> EDTestCasePluginExecuteControlGridScreeningv1_0.__init__(self, "EDTestCasePluginExecuteControlGridScreeningv1_0_integrationError") <NEW_LINE> self.setConfigurationFile(self.getRefConfigFile()) <NEW_LINE> self.setDataInputFile(os.path.join(self.getPluginTestsDataHome(), "XSDataInputGridScreening_integrationError.xml")) <NEW_LINE> self.setNoExpectedWarningMessages(0) <NEW_LINE> self.setNoExpectedErrorMessages(1) <NEW_LINE> <DEDENT> def preProcess(self): <NEW_LINE> <INDENT> EDTestCasePluginExecuteControlGridScreeningv1_0.preProcess(self) <NEW_LINE> self.loadTestImage([ "integrationError_2_001.img" ]) <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> self.addTestMethod(self.testExecute)
|
Test of characterisation error messages.
|
625990291f5feb6acb163ba9
|
class YPatternManager(PatternManager): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> script_name = os.path.splitext(__file__)[0] <NEW_LINE> path = os.path.abspath('./') <NEW_LINE> super(YPatternManager, self).__init__(pattern_dict=yaml_file_to_dict(script_name, path))
|
Yaml version of pattern manager.
|
625990290a366e3fb87dd9a0
|
class ServiceItem(object): <NEW_LINE> <INDENT> def __init__(self, host, port, ttl=30, payload=""): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.ttl = ttl <NEW_LINE> self.payload = payload <NEW_LINE> self.probe = ORIGIN_DEFAULT_PROBE <NEW_LINE> <DEDENT> @property <NEW_LINE> def url_root(self): <NEW_LINE> <INDENT> return "http://%s:%s" % (self.host, self.port)
|
service definition
|
6259902921a7993f00c66f36
|
class RegistrationViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): <NEW_LINE> <INDENT> queryset = Registration.objects.all() <NEW_LINE> serializer_class = RegistrationSerializer <NEW_LINE> permission_classes = (DRYPermissions,)
|
API endpoints to create and list registrations.
list:
### Example response
[
{
"id": 3,
"email": "charles.dumont@example.net",
"first_name": "Charles",
"last_name": "Dumont",
"submitted": "2018-05-05T14:15:10.998206+02:00",
}
]
create:
This endpoint allows to create a registration for a student.
In fact, it does three things:
1. Create a user for the student
2. Create the registration
3. Create a student profile and link it to the user and the registration.
|
6259902930c21e258be997c5
|
class MaxFn(beam.CombineFn): <NEW_LINE> <INDENT> def create_accumulator(self): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> def add_input(self, current_min, x): <NEW_LINE> <INDENT> return max(current_min, x) <NEW_LINE> <DEDENT> def merge_accumulators(self, accumulators): <NEW_LINE> <INDENT> return max(accumulators) <NEW_LINE> <DEDENT> def extract_output(self, x): <NEW_LINE> <INDENT> return x
|
A CombineFn to find the max of the input PCollection.
|
625990298a349b6b436871f2
|
class LimeSpecParsingError(ParsingError): <NEW_LINE> <INDENT> pass
|
Raised if there is a semantic error in the lime specification.
|
6259902926238365f5fadb0b
|
class NavBar(Menu): <NEW_LINE> <INDENT> def __init__(self, master_frame): <NEW_LINE> <INDENT> super().__init__(master_frame.root) <NEW_LINE> self.parent = master_frame.root <NEW_LINE> self.master = master_frame <NEW_LINE> self.file_menu = None <NEW_LINE> self.create_tab("File", self.file_menu, self.get_file_menu_data()) <NEW_LINE> master_frame.root.config(menu=self) <NEW_LINE> <DEDENT> def create_tab(self, name, menu, options, tearoff=0): <NEW_LINE> <INDENT> menu = Menu(self, tearoff=tearoff) <NEW_LINE> for label, command in options: <NEW_LINE> <INDENT> menu.add_command(label=label, command=command) <NEW_LINE> <DEDENT> self.add_cascade(label=name, menu=menu) <NEW_LINE> <DEDENT> def get_file_menu_data(self): <NEW_LINE> <INDENT> return ( ('Open', self.master.open_file), ('Save', self.master.save_existing_file), ('Save as', self.master.save_new_file), ('Exit', self.close), ) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.parent.quit()
|
This Widget controls the nav bar options and selection
|
62599029e76e3b2f99fd99c6
|
class NetworkConfigurationDiagnosticResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'profile': {'key': 'profile', 'type': 'NetworkConfigurationDiagnosticProfile'}, 'network_security_group_result': {'key': 'networkSecurityGroupResult', 'type': 'NetworkSecurityGroupResult'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(NetworkConfigurationDiagnosticResult, self).__init__(**kwargs) <NEW_LINE> self.profile = kwargs.get('profile', None) <NEW_LINE> self.network_security_group_result = kwargs.get('network_security_group_result', None)
|
Network configuration diagnostic result corresponded to provided traffic query.
:param profile: Network configuration diagnostic profile.
:type profile: ~azure.mgmt.network.v2019_09_01.models.NetworkConfigurationDiagnosticProfile
:param network_security_group_result: Network security group result.
:type network_security_group_result:
~azure.mgmt.network.v2019_09_01.models.NetworkSecurityGroupResult
|
6259902921bff66bcd723c1d
|
class ISIView(HistogramView): <NEW_LINE> <INDENT> x_min = 0 <NEW_LINE> x_max = .05 <NEW_LINE> n_bins = int(x_max / .001) <NEW_LINE> alias_char = 'isi' <NEW_LINE> bin_unit = 'ms' <NEW_LINE> default_shortcuts = { 'change_window_size': 'ctrl+wheel', } <NEW_LINE> default_snippets = { 'set_n_bins': '%sn' % alias_char, 'set_bin_size (%s)' % bin_unit: '%sb' % alias_char, 'set_x_min (%s)' % bin_unit: '%smin' % alias_char, 'set_x_max (%s)' % bin_unit: '%smax' % alias_char, }
|
Histogram view showing the interspike intervals.
|
62599029287bf620b6272bab
|
class EDTestCasePluginExecuteControlCharacterisationv1_2_iceRings(EDTestCasePluginExecuteControlCharacterisationv1_2): <NEW_LINE> <INDENT> def __init__(self, _edStringTestName=None): <NEW_LINE> <INDENT> EDTestCasePluginExecuteControlCharacterisationv1_2.__init__(self, "EDTestCasePluginExecuteControlCharacterisationv1_2_iceRings") <NEW_LINE> self.setConfigurationFile(self.getRefConfigFile()) <NEW_LINE> self.setDataInputFile(os.path.join(self.getPluginTestsDataHome(), "XSDataInputCharacterisation_iceRings.xml")) <NEW_LINE> self.setNoExpectedWarningMessages(2) <NEW_LINE> <DEDENT> def preProcess(self): <NEW_LINE> <INDENT> EDTestCasePluginExecuteControlCharacterisationv1_2.preProcess(self) <NEW_LINE> self.loadTestImage([ "iceRings_1_001.img" ]) <NEW_LINE> <DEDENT> def testExecute(self): <NEW_LINE> <INDENT> EDTestCasePluginExecuteControlCharacterisationv1_2.testExecute(self) <NEW_LINE> edPlugin = self.getPlugin() <NEW_LINE> strStatusMessage = None <NEW_LINE> if edPlugin.hasDataOutput("statusMessage"): <NEW_LINE> <INDENT> strStatusMessage = edPlugin.getDataOutput("statusMessage")[0].getValue() <NEW_LINE> <DEDENT> EDAssert.equal(True, strStatusMessage.find("ring") != -1, "Status message contains 'ring'") <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> self.addTestMethod(self.testExecute)
|
Test of characterisation error messages.
|
62599029bf627c535bcb2472
|
class DictAverageMeter(Meter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.average_meters = defaultdict(AverageMeter) <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.average_meters.clear() <NEW_LINE> <DEDENT> def update(self, val: Dict[str, Union[float, Tensor]]): <NEW_LINE> <INDENT> for k, v in val.items(): <NEW_LINE> <INDENT> self.average_meters[k].update(v) <NEW_LINE> <DEDENT> <DEDENT> def sync(self): <NEW_LINE> <INDENT> for v in self.average_meters.values(): <NEW_LINE> <INDENT> v.sync() <NEW_LINE> <DEDENT> <DEDENT> def accumulate(self): <NEW_LINE> <INDENT> for v in self.average_meters.values(): <NEW_LINE> <INDENT> v.accumulate() <NEW_LINE> <DEDENT> <DEDENT> def value(self): <NEW_LINE> <INDENT> avg_dict = dict() <NEW_LINE> for k, meter in self.average_meters.items(): <NEW_LINE> <INDENT> avg_dict[k] = meter.value() <NEW_LINE> <DEDENT> return avg_dict
|
Computes and stores the average and current value (Dict[str, Union[float, Tensor]])
|
625990298e05c05ec3f6f639
|
class BootstrapResult(object): <NEW_LINE> <INDENT> def __init__(self, empf, shape): <NEW_LINE> <INDENT> self.empf = empf <NEW_LINE> self.point = empf[0] <NEW_LINE> self.shape = shape <NEW_LINE> <DEDENT> def std(self): <NEW_LINE> <INDENT> return self._format(np.std(self.empf, axis=0)) <NEW_LINE> <DEDENT> def mean(self): <NEW_LINE> <INDENT> return self._format(np.mean(self.empf, axis=0)) <NEW_LINE> <DEDENT> def median(self): <NEW_LINE> <INDENT> return self._format(np.median(self.empf, axis=0)) <NEW_LINE> <DEDENT> def get_point(self): <NEW_LINE> <INDENT> return self._format(self.point) <NEW_LINE> <DEDENT> def get_empf(self): <NEW_LINE> <INDENT> return self.empf.reshape((-1,) + self.shape) <NEW_LINE> <DEDENT> def _format(self, stat): <NEW_LINE> <INDENT> return stat.reshape(self.shape) <NEW_LINE> <DEDENT> def pvalue(self, twosided=True, null=0, **kwargs): <NEW_LINE> <INDENT> size = self.point.size <NEW_LINE> tail = np.resize(np.array(kwargs.get('tail', 'right')), size) <NEW_LINE> method = kwargs.get('method', 'shift') <NEW_LINE> mtp = kwargs.get('mtp', None) <NEW_LINE> null = np.resize(np.array(null), size) <NEW_LINE> if not isinstance(null[0], (int,float,np.float,np.int)): <NEW_LINE> <INDENT> raise ValueError('null should be int or float, received {}' .format(type(null[0]))) <NEW_LINE> <DEDENT> if not set(tail.flat).issubset(set(['left','right'])): <NEW_LINE> <INDENT> raise ValueError('all entries in tail must be "left" or "right"') <NEW_LINE> <DEDENT> if method not in ['shift', 'normal']: <NEW_LINE> <INDENT> raise ValueError('method must be either "shift" or "normal"') <NEW_LINE> <DEDENT> if mtp is not None: <NEW_LINE> <INDENT> if mtp not in ['stepdown']: <NEW_LINE> <INDENT> raise ValueError('mtp must be None or "stepdown"') <NEW_LINE> <DEDENT> <DEDENT> nulldist = self.empf - self.empf.mean(axis=0, keepdims=True) + null <NEW_LINE> if (mtp is None) or (self.shape == ()): <NEW_LINE> <INDENT> return self._format(single_pvalue(nulldist, self.point, twosided, tail, method)) <NEW_LINE> <DEDENT> elif mtp == 'stepdown': <NEW_LINE> <INDENT> return self._format(stepdown_pvalue(nulldist, self.point, twosided, tail, method))
|
class for bootstrap sample inference
Parameters
----------
empf : array-like
empirical bootstrap parameter distribution
|
625990298a349b6b436871f4
|
class ModItemForm(MyForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Item <NEW_LINE> exclude = ['Usuario', 'Fase', 'Fecha', 'Estado', 'Version', 'Campos', 'Tipo', 'condicion']
|
Formulario para la creacion de items
Hereda de forms.ModelForm y utiliza la clase Group para
agregar ciertos campos a la hora de la creacion/modificacion/eliminacion
|
62599029d164cc6175821f33
|
class VBCAR_train(TrainEngine): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> super(VBCAR_train, self).__init__(self.config) <NEW_LINE> <DEDENT> def load_dataset(self): <NEW_LINE> <INDENT> split_data = load_split_dataset(self.config) <NEW_LINE> self.data = GroceryData(split_dataset=split_data, config=self.config) <NEW_LINE> self.config["model"]["n_users"] = self.data.n_users <NEW_LINE> self.config["model"]["n_items"] = self.data.n_items <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> self.load_dataset() <NEW_LINE> self.train_data = self.data.sample_triple() <NEW_LINE> self.config["model"]["alpha_step"] = (1 - self.config["model"]["alpha"]) / ( self.config["model"]["max_epoch"] ) <NEW_LINE> self.config["user_fea"] = self.data.user_feature <NEW_LINE> self.config["item_fea"] = self.data.item_feature <NEW_LINE> self.engine = VBCAREngine(self.config) <NEW_LINE> self.engine.data = self.data <NEW_LINE> assert hasattr(self, "engine"), "Please specify the exact model engine !" <NEW_LINE> self.monitor = Monitor( log_dir=self.config["system"]["run_dir"], delay=1, gpu_id=self.gpu_id ) <NEW_LINE> print("Start training... ") <NEW_LINE> epoch_bar = tqdm(range(self.config["model"]["max_epoch"]), file=sys.stdout) <NEW_LINE> self.max_n_update = self.config["model"]["max_n_update"] <NEW_LINE> for epoch in epoch_bar: <NEW_LINE> <INDENT> print(f"Epoch {epoch} starts !") <NEW_LINE> print("-" * 80) <NEW_LINE> if epoch > 0 and self.eval_engine.n_no_update == 0: <NEW_LINE> <INDENT> self.engine.save_checkpoint( model_dir=os.path.join( self.config["system"]["model_save_dir"], "model.cpk" ) ) <NEW_LINE> <DEDENT> if self.eval_engine.n_no_update >= self.max_n_update: <NEW_LINE> <INDENT> print( "Early stop criterion triggered, no performance update for {:} times".format( self.max_n_update ) ) <NEW_LINE> break <NEW_LINE> <DEDENT> data_loader = DataLoader( torch.LongTensor(self.train_data.to_numpy()).to(self.engine.device), batch_size=self.config["model"]["batch_size"], shuffle=True, drop_last=True, ) <NEW_LINE> self.engine.train_an_epoch(data_loader, epoch_id=epoch) <NEW_LINE> self.eval_engine.train_eval( self.data.valid[0], self.data.test[0], self.engine.model, epoch ) <NEW_LINE> self.engine.model.alpha = min( self.config["model"]["alpha"] + math.exp(epoch - self.config["model"]["max_epoch"] + 20), 1, ) <NEW_LINE> lr = self.config["model"]["lr"] * (0.5 ** (epoch // 10)) <NEW_LINE> for param_group in self.engine.optimizer.param_groups: <NEW_LINE> <INDENT> param_group["lr"] = lr <NEW_LINE> <DEDENT> <DEDENT> self.config["run_time"] = self.monitor.stop() <NEW_LINE> return self.eval_engine.best_valid_performance
|
An instance class from the TrainEngine base class.
|
6259902963f4b57ef0086550
|
class Session(requests.Session): <NEW_LINE> <INDENT> def __init__(self, timeout=30, max_retries=1): <NEW_LINE> <INDENT> requests.Session.__init__(self) <NEW_LINE> self.timeout = timeout <NEW_LINE> self.stream = True <NEW_LINE> self.adapters=[] <NEW_LINE> self.domain_delay = {} <NEW_LINE> self.headers.update({'User-Agent': 'FlexGet/%s (www.flexget.com)' % version}) <NEW_LINE> <DEDENT> def add_cookiejar(self, cookiejar): <NEW_LINE> <INDENT> for cookie in cookiejar: <NEW_LINE> <INDENT> self.cookies.set_cookie(cookie) <NEW_LINE> <DEDENT> <DEDENT> def set_domain_delay(self, domain, delay): <NEW_LINE> <INDENT> self.domain_delay[domain] = {'delay': parse_timedelta(delay)} <NEW_LINE> <DEDENT> def request(self, method, url, *args, **kwargs): <NEW_LINE> <INDENT> if is_unresponsive(url): <NEW_LINE> <INDENT> raise requests.Timeout('Requests to this site have timed out recently. Waiting before trying again.') <NEW_LINE> <DEDENT> wait_for_domain(url, self.domain_delay) <NEW_LINE> kwargs.setdefault('timeout', self.timeout) <NEW_LINE> raise_status = kwargs.pop('raise_status', True) <NEW_LINE> if not any(url.startswith(adapter) for adapter in self.adapters): <NEW_LINE> <INDENT> return _wrap_urlopen(url, timeout=kwargs['timeout']) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = requests.Session.request(self, method, url, *args, **kwargs) <NEW_LINE> <DEDENT> except (requests.Timeout, requests.ConnectionError): <NEW_LINE> <INDENT> set_unresponsive(url) <NEW_LINE> raise <NEW_LINE> <DEDENT> if raise_status: <NEW_LINE> <INDENT> result.raise_for_status() <NEW_LINE> <DEDENT> return result
|
Subclass of requests Session class which defines some of our own defaults, records unresponsive sites,
and raises errors by default.
|
625990291d351010ab8f4ad2
|
class Tag(object): <NEW_LINE> <INDENT> __slots__ = ('tagname', 'contents', '_context', '_html_dangle', '_always_paired') <NEW_LINE> def __init__(self, tagname, context, dangle, paired): <NEW_LINE> <INDENT> self.tagname = tagname <NEW_LINE> self._context = context <NEW_LINE> self._html_dangle = dangle <NEW_LINE> self._always_paired = paired <NEW_LINE> self.contents = None <NEW_LINE> <DEDENT> def open(self, bind=None, **attributes): <NEW_LINE> <INDENT> if self not in self._context._tags[self.tagname]: <NEW_LINE> <INDENT> self._context._tags[self.tagname].append(self) <NEW_LINE> <DEDENT> return self._markup(self._open(bind, attributes) + u'>') <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._context._tags[self.tagname].remove(self) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return self._markup(self._close()) <NEW_LINE> <DEDENT> def _open(self, bind, kwargs): <NEW_LINE> <INDENT> contents = kwargs.pop('contents', None) <NEW_LINE> attributes = _transform_keys(kwargs) <NEW_LINE> tagname = self.tagname <NEW_LINE> new_contents = transform( tagname, attributes, contents, self._context, bind) <NEW_LINE> if not new_contents: <NEW_LINE> <INDENT> new_contents = u'' <NEW_LINE> <DEDENT> elif hasattr(new_contents, '__html__'): <NEW_LINE> <INDENT> new_contents = _unpack(new_contents) <NEW_LINE> <DEDENT> self.contents = self._markup(new_contents) <NEW_LINE> if self._context[u'ordered_attributes']: <NEW_LINE> <INDENT> pairs = sorted(attributes.items(), key=_attribute_sort_key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pairs = iteritems(attributes) <NEW_LINE> <DEDENT> guts = u' '.join(u'%s="%s"' % (k, _attribute_escape(v)) for k, v in pairs) <NEW_LINE> if guts: <NEW_LINE> <INDENT> return u'<' + tagname + u' ' + guts <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return u'<' + tagname <NEW_LINE> <DEDENT> <DEDENT> def _close(self): <NEW_LINE> <INDENT> return u'</' + self.tagname + u'>' <NEW_LINE> <DEDENT> def _markup(self, string): <NEW_LINE> <INDENT> return self._context[u'markup_wrapper'](string) <NEW_LINE> <DEDENT> def __call__(self, bind=None, **attributes): <NEW_LINE> <INDENT> header = self._open(bind, attributes) <NEW_LINE> contents = self.contents <NEW_LINE> if not contents: <NEW_LINE> <INDENT> if not self._always_paired: <NEW_LINE> <INDENT> if self._context.xml: <NEW_LINE> <INDENT> return self._markup(header + u' />') <NEW_LINE> <DEDENT> elif self._html_dangle: <NEW_LINE> <INDENT> return self._markup(header + u'>') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if hasattr(contents, '__html__'): <NEW_LINE> <INDENT> contents = _unpack(contents) <NEW_LINE> <DEDENT> return self._markup(header + u'>' + contents + self._close()) <NEW_LINE> <DEDENT> def __html__(self): <NEW_LINE> <INDENT> return self()
|
A printable markup tag.
Tags are generated by :class:`Generator` and are usually called
immediately, returning a fully formed markup string::
print(generator.textarea(contents="hello!"))
For more fine-tuned control over your markup, you may instead choose to
use the :meth:`open` and :meth:`close` methods of the tag::
print(generator.textarea.open())
print("hello!")
print(generator.textarea.close())
|
625990299b70327d1c57fd3e
|
class _QtWindow(QtGui.QWidget): <NEW_LINE> <INDENT> def __init__(self, parent, enable_window): <NEW_LINE> <INDENT> super(_QtWindow, self).__init__(parent) <NEW_LINE> self.handler = _QtWindowHandler(self, enable_window) <NEW_LINE> <DEDENT> def closeEvent(self, event): <NEW_LINE> <INDENT> self.handler.closeEvent(event) <NEW_LINE> return super(_QtWindow, self).closeEvent(event) <NEW_LINE> <DEDENT> def paintEvent(self, event): <NEW_LINE> <INDENT> self.handler.paintEvent(event) <NEW_LINE> <DEDENT> def resizeEvent(self, event): <NEW_LINE> <INDENT> self.handler.resizeEvent(event) <NEW_LINE> <DEDENT> def keyPressEvent(self, event): <NEW_LINE> <INDENT> self.handler.keyPressEvent(event) <NEW_LINE> <DEDENT> def keyReleaseEvent(self, event): <NEW_LINE> <INDENT> self.handler.keyReleaseEvent(event) <NEW_LINE> <DEDENT> def enterEvent(self, event): <NEW_LINE> <INDENT> self.handler.enterEvent(event) <NEW_LINE> <DEDENT> def leaveEvent(self, event): <NEW_LINE> <INDENT> self.handler.leaveEvent(event) <NEW_LINE> <DEDENT> def mouseDoubleClickEvent(self, event): <NEW_LINE> <INDENT> self.handler.mouseDoubleClickEvent(event) <NEW_LINE> <DEDENT> def mouseMoveEvent(self, event): <NEW_LINE> <INDENT> self.handler.mouseMoveEvent(event) <NEW_LINE> <DEDENT> def mousePressEvent(self, event): <NEW_LINE> <INDENT> self.handler.mousePressEvent(event) <NEW_LINE> <DEDENT> def mouseReleaseEvent(self, event): <NEW_LINE> <INDENT> self.handler.mouseReleaseEvent(event) <NEW_LINE> <DEDENT> def wheelEvent(self, event): <NEW_LINE> <INDENT> self.handler.wheelEvent(event) <NEW_LINE> <DEDENT> def dragEnterEvent(self, event): <NEW_LINE> <INDENT> self.handler.dragEnterEvent(event) <NEW_LINE> <DEDENT> def dragLeaveEvent(self, event): <NEW_LINE> <INDENT> self.handler.dragLeaveEvent(event) <NEW_LINE> <DEDENT> def dragMoveEvent(self, event): <NEW_LINE> <INDENT> self.handler.dragMoveEvent(event) <NEW_LINE> <DEDENT> def dropEvent(self, event): <NEW_LINE> <INDENT> self.handler.dropEvent(event) <NEW_LINE> <DEDENT> def sizeHint(self): <NEW_LINE> <INDENT> qt_size_hint = super(_QtWindow, self).sizeHint() <NEW_LINE> return self.handler.sizeHint(qt_size_hint)
|
The Qt widget that implements the enable control.
|
62599029a8ecb033258721d9
|
class DeviceWidget(tk.Toplevel): <NEW_LINE> <INDENT> def __init__(self, device, timeout=1500): <NEW_LINE> <INDENT> tk.Toplevel.__init__(self, padx=6, pady=6) <NEW_LINE> self.title(device.__class__.__name__) <NEW_LINE> self.grid() <NEW_LINE> self.queues = {} <NEW_LINE> self.values = {} <NEW_LINE> self.timeout = timeout <NEW_LINE> grid_opts = {'padx': 3, 'pady': 3} <NEW_LINE> for i, param in enumerate(device): <NEW_LINE> <INDENT> name_label = tk.Label(self, text=param.name) <NEW_LINE> name_label.grid(row=i, column=0, **grid_opts) <NEW_LINE> if param.is_readable(): <NEW_LINE> <INDENT> value = tk.DoubleVar() <NEW_LINE> value.set(param.get().result()) <NEW_LINE> state = tk.NORMAL if param.is_writable() else 'readonly' <NEW_LINE> entry = tk.Entry(self, textvariable=value, state=state) <NEW_LINE> entry.grid(row=i, column=1, **grid_opts) <NEW_LINE> self.queues[param] = Queue.Queue() <NEW_LINE> self.values[param] = value <NEW_LINE> dispatcher.subscribe(param, 'changed', self._update_value) <NEW_LINE> self.after(self.timeout, self._poll, param) <NEW_LINE> <DEDENT> if param.unit: <NEW_LINE> <INDENT> unit_name = param.unit.dimensionality.string <NEW_LINE> unit_label = tk.Label(self, text=unit_name) <NEW_LINE> unit_label.grid(row=i, column=2, **grid_opts) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _update_value(self, param): <NEW_LINE> <INDENT> self.queues[param].put(param.get().result()) <NEW_LINE> <DEDENT> def _poll(self, param): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self.queues[param].get(False) <NEW_LINE> self.values[param].set(result) <NEW_LINE> <DEDENT> except Queue.Empty: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.after(self.timeout, self._poll, param)
|
Wrap a device in a top level Tk widget.
*device* must be an object derived from :class:`.Device`. *timeout*
specifies how much time in milliseconds passes between to parameter
queries.
|
625990291d351010ab8f4ad3
|
class BasicOrganizationSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> url = serializers.HyperlinkedIdentityField(view_name='organization-detail') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Organization <NEW_LINE> fields = ('url', 'id', 'name', 'created', 'display_name') <NEW_LINE> read_only = ('url', 'id', 'created',)
|
Serializer for Basic Organization fields
|
62599029ec188e330fdf9851
|
class Word: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._word = None <NEW_LINE> self._doc = None <NEW_LINE> self._paragraphs = 0 <NEW_LINE> <DEDENT> def _add_paragraph(self): <NEW_LINE> <INDENT> if self._paragraphs > 0: <NEW_LINE> <INDENT> self._doc.Paragraphs.Add() <NEW_LINE> <DEDENT> self._paragraphs = self._doc.Paragraphs.Count <NEW_LINE> return self._doc.Paragraphs(self._paragraphs) <NEW_LINE> <DEDENT> def addPageBreak(self): <NEW_LINE> <INDENT> paragraph = self._add_paragraph() <NEW_LINE> paragraph.Range.InsertBreak() <NEW_LINE> <DEDENT> def textParagraph(self, text, size=None, bold=None): <NEW_LINE> <INDENT> paragraph = self._add_paragraph() <NEW_LINE> if size: <NEW_LINE> <INDENT> paragraph.Range.Font.Size = size <NEW_LINE> <DEDENT> if bold or bold == False: <NEW_LINE> <INDENT> paragraph.Range.Font.Bold = bold <NEW_LINE> <DEDENT> paragraph.Range.InsertAfter(text) <NEW_LINE> <DEDENT> def pasteImage(self): <NEW_LINE> <INDENT> paragraph = self._add_paragraph() <NEW_LINE> paragraph.Range.Paste() <NEW_LINE> <DEDENT> def save(self, filename=None, close=False): <NEW_LINE> <INDENT> if filename: <NEW_LINE> <INDENT> self._doc.SaveAs(filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._doc.Save() <NEW_LINE> <DEDENT> if close: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._doc.Close() <NEW_LINE> self._doc = None <NEW_LINE> if self._word.Documents.Count == 0: <NEW_LINE> <INDENT> self._word.Quit() <NEW_LINE> self._word = None <NEW_LINE> <DEDENT> <DEDENT> def open_document(self, document): <NEW_LINE> <INDENT> self._word = Dispatch("Word.Application") <NEW_LINE> self._word.Visible = True <NEW_LINE> self._word.Documents.Open(document) <NEW_LINE> self._doc = self._word.Documents(1) <NEW_LINE> self._paragraphs = 0 <NEW_LINE> <DEDENT> def new_document(self): <NEW_LINE> <INDENT> self._word = Dispatch("Word.Application") <NEW_LINE> self._word.Visible = True <NEW_LINE> self._word.Documents.Add() <NEW_LINE> self._doc = self._word.Documents(1) <NEW_LINE> self._paragraphs = 0
|
Microsoft Word Document helper
|
625990295e10d32532ce40e2
|
class StructFile(object): <NEW_LINE> <INDENT> def __init__(self, path: str): <NEW_LINE> <INDENT> self._impl = StructFileImpl(path) <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> self._impl.load() <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> self._impl.flush() <NEW_LINE> <DEDENT> def add_address(self, name: str, data: Union[int, Tuple[str, int], Tuple[Address, List[int]]]): <NEW_LINE> <INDENT> self._impl.add_address(name, data) <NEW_LINE> <DEDENT> def remove_address(self, name: str): <NEW_LINE> <INDENT> self._impl.remove_address(name) <NEW_LINE> <DEDENT> def update_code(self, code_definitions: List[Tuple[str, Code]]): <NEW_LINE> <INDENT> self._impl.update_code(code_definitions) <NEW_LINE> <DEDENT> def update_offsets(self, offsets: List[Tuple[str, Union[int, List[int]]]]): <NEW_LINE> <INDENT> self._impl.update_offsets(offsets)
|
Class that is used to read/modify/update pygamehack Addresses, Structs and Code defined in a file
|
62599029925a0f43d25e9005
|
class WorkShop(Donor): <NEW_LINE> <INDENT> objects = {} <NEW_LINE> def build_it(self, name='default'): <NEW_LINE> <INDENT> ride = self.objects.get(name) <NEW_LINE> style = Styles(ride.get_style()) <NEW_LINE> return '%s %s' % (style(), ride.get_model())
|
Reproduces interface.
|
62599029e76e3b2f99fd99ca
|
class IncludeGraphics(LatexFigure): <NEW_LINE> <INDENT> def __init__(self, fname, label, caption, fig=None, position="", star=False, options='width=\columnwidth', margin=False): <NEW_LINE> <INDENT> if fig is None: <NEW_LINE> <INDENT> from matplotlib.pyplot import gcf <NEW_LINE> fig = gcf() <NEW_LINE> <DEDENT> self.label = label <NEW_LINE> self.caption = caption <NEW_LINE> self.fig = fig <NEW_LINE> self.position = position <NEW_LINE> self.options = options <NEW_LINE> self.star = star <NEW_LINE> self.margin = margin <NEW_LINE> self.filename = fname <NEW_LINE> self.data = self._get_data() <NEW_LINE> <DEDENT> def _get_data(self): <NEW_LINE> <INDENT> extension = self.filename.split('.')[-1].lower() <NEW_LINE> if extension == 'svg': <NEW_LINE> <INDENT> return SVG(filename=self.filename) <NEW_LINE> <DEDENT> elif extension == 'pdf': <NEW_LINE> <INDENT> return IFrame("mftex/pgm.pdf#view=fit", 600, 400) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Image(filename=self.filename) <NEW_LINE> <DEDENT> <DEDENT> def _repr_html_(self): <NEW_LINE> <INDENT> return markdown2html('> **Figure (<a name="fig:{label:s}">{label:s}</a>)**: {caption:s}'.format( label=self.label, caption=self.caption)) + '\n' + self.data._repr_html_()
|
A LaTeX IPython DisplayObject Figure
`label` is mandatory, since it also sets the filename. It will
have ``fig:`` preprended to it.
`fig` is optional - the current figure (via ``gcf``) will be used
if it is not set.
`position` is either the float placement specifier or the subfigure
vertical position.
If `subfigure` is set to true, a subfigure with width `width` will
be created.
The figure is saved (via ``savefig``) as a PDF file in the current
directory.
Displaying the object produces LaTeX (only) to embed the figure.
A little hacky, but since this is meant for use in the notebook
it is assumed that the figure is going to be displayed automatically
in HTML independently.
|
6259902a21bff66bcd723c21
|
class Cat(object): <NEW_LINE> <INDENT> def __init__(self, name, legs=4, owner="john"): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.legs = legs <NEW_LINE> self.owner = owner <NEW_LINE> self.word = "meow" <NEW_LINE> <DEDENT> def talk(self): <NEW_LINE> <INDENT> s = "{}, my name is {}. i have {} legs and belong to {}.".format( self.word , self.name , self.legs , self.owner ) <NEW_LINE> return s
|
Create a general Cat object. Requires a name and optional count of legs
and owner name.
|
6259902abe8e80087fbc0037
|
class SoundException(Exception): <NEW_LINE> <INDENT> pass
|
Raised for invalid sound file names or unknown sound types.
|
6259902ad164cc6175821f36
|
class TestBogusFilter(object): <NEW_LINE> <INDENT> pass
|
Class that doesn't inherit from BaseHostFilter
|
6259902aec188e330fdf9853
|
class OrderedDictWithIndex(OrderedDict): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._key_to_pos = {} <NEW_LINE> self._pos_to_key = {} <NEW_LINE> <DEDENT> def _recalc_index(self): <NEW_LINE> <INDENT> self._key_to_pos = {key: pos for (pos, key) in enumerate(self.keys())} <NEW_LINE> self._pos_to_key = {pos: key for (pos, key) in enumerate(self.keys())} <NEW_LINE> <DEDENT> def pos_from_key(self, key): <NEW_LINE> <INDENT> return self._key_to_pos[key] <NEW_LINE> <DEDENT> def value_from_pos(self, pos): <NEW_LINE> <INDENT> key = self._pos_to_key[pos] <NEW_LINE> return self[key] <NEW_LINE> <DEDENT> def popitem(self, *args, **kwargs): <NEW_LINE> <INDENT> ret = super().popitem(*args, **kwargs) <NEW_LINE> self._recalc_index() <NEW_LINE> return ret <NEW_LINE> <DEDENT> def move_to_end(self, *args, **kwargs): <NEW_LINE> <INDENT> ret = super().move_to_end(*args, **kwargs) <NEW_LINE> self._recalc_index() <NEW_LINE> return ret <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> ret = super().clear() <NEW_LINE> self._recalc_index() <NEW_LINE> return ret <NEW_LINE> <DEDENT> def pop(self, *args, **kwargs): <NEW_LINE> <INDENT> ret = super().pop(*args, **kwargs) <NEW_LINE> self._recalc_index() <NEW_LINE> return ret <NEW_LINE> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> ret = super().update(*args, **kwargs) <NEW_LINE> self._recalc_index() <NEW_LINE> return ret <NEW_LINE> <DEDENT> def __delitem__(self, *args, **kwargs): <NEW_LINE> <INDENT> ret = super().__delitem__(*args, **kwargs) <NEW_LINE> self._recalc_index() <NEW_LINE> return ret <NEW_LINE> <DEDENT> def __setitem__(self, key, *args, **kwargs): <NEW_LINE> <INDENT> is_new_key = key not in self <NEW_LINE> ret = super().__setitem__(key, *args, **kwargs) <NEW_LINE> if is_new_key: <NEW_LINE> <INDENT> pos = len(self) - 1 <NEW_LINE> self._key_to_pos[key] = pos <NEW_LINE> self._pos_to_key[pos] = key <NEW_LINE> <DEDENT> return ret
|
An OrderedDict that keeps track of the positions of keys.
Note: very inefficient to modify contents, except to add new items.
|
6259902a21a7993f00c66f3c
|
class DeviotChangeBuildFolderCommand(WindowCommand): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> deviot.folder_explorer(key='build_folder', callback=save_setting)
|
Adds extra libraries folder path from the settings
|
6259902a66673b3332c313ae
|
class CompilerError(Exception): <NEW_LINE> <INDENT> def __init__(self, descrip, range=None, warning=False): <NEW_LINE> <INDENT> self.descrip = descrip <NEW_LINE> self.range = range <NEW_LINE> self.warning = warning <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> error_color = "\x1B[31m" <NEW_LINE> warn_color = "\x1B[33m" <NEW_LINE> reset_color = "\x1B[0m" <NEW_LINE> bold_color = "\033[1m" <NEW_LINE> color_code = warn_color if self.warning else error_color <NEW_LINE> issue_type = "warning" if self.warning else "error" <NEW_LINE> if self.range: <NEW_LINE> <INDENT> indicator = warn_color <NEW_LINE> indicator += " " * (self.range.start.col - 1) <NEW_LINE> if (self.range.start.line == self.range.end.line and self.range.start.file == self.range.end.file): <NEW_LINE> <INDENT> if self.range.end.col == self.range.start.col: <NEW_LINE> <INDENT> indicator += "^" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indicator += "-" * (self.range.end.col - self.range.start.col + 1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> indicator += "-" * (len(self.range.start.full_line) - self.range.start.col + 1) <NEW_LINE> <DEDENT> indicator += reset_color <NEW_LINE> return (f"{bold_color}{self.range.start.file}:" f"{self.range.start.line}:{self.range.start.col}: " f"{color_code}{issue_type}:{reset_color} {self.descrip}\n" f" {self.range.start.full_line}\n" f" {indicator}") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (f"{bold_color}shivyc: {color_code}{issue_type}:" f"{reset_color} {self.descrip}") <NEW_LINE> <DEDENT> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if not self.range: <NEW_LINE> <INDENT> return bool(other.range) <NEW_LINE> <DEDENT> if self.range.start.file != other.range.start.file: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> this_tuple = self.range.start.line, self.range.start.col <NEW_LINE> other_tuple = other.range.start.line, other.range.start.col <NEW_LINE> return this_tuple < other_tuple
|
Class representing compile-time errors.
message (str) - User-friendly explanation of the error. Should
begin with a lowercase letter.
file_name (str) - File name in which the error occurred.
line_number (int) - Line number on which the error occurred
|
6259902a8a349b6b436871f8
|
class RollFinder(with_metaclass(ABCMeta, object)): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def _active_contract(self, oc, front, back, dt): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _get_active_contract_at_offset(self, root_symbol, dt, offset): <NEW_LINE> <INDENT> oc = self.asset_finder.get_ordered_contracts(root_symbol) <NEW_LINE> session = self.trading_calendar.minute_to_session_label(dt) <NEW_LINE> front = oc.contract_before_auto_close(session.value) <NEW_LINE> back = oc.contract_at_offset(front, 1, dt.value) <NEW_LINE> if back is None: <NEW_LINE> <INDENT> return front <NEW_LINE> <DEDENT> primary = self._active_contract(oc, front, back, session) <NEW_LINE> return oc.contract_at_offset(primary, offset, session.value) <NEW_LINE> <DEDENT> def get_contract_center(self, root_symbol, dt, offset): <NEW_LINE> <INDENT> return self._get_active_contract_at_offset(root_symbol, dt, offset) <NEW_LINE> <DEDENT> def get_rolls(self, root_symbol, start, end, offset): <NEW_LINE> <INDENT> oc = self.asset_finder.get_ordered_contracts(root_symbol) <NEW_LINE> front = self._get_active_contract_at_offset(root_symbol, end, 0) <NEW_LINE> back = oc.contract_at_offset(front, 1, end.value) <NEW_LINE> if back is not None: <NEW_LINE> <INDENT> end_session = self.trading_calendar.minute_to_session_label(end) <NEW_LINE> first = self._active_contract(oc, front, back, end_session) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> first = front <NEW_LINE> <DEDENT> first_contract = oc.sid_to_contract[first] <NEW_LINE> rolls = [((first_contract >> offset).contract.sid, None)] <NEW_LINE> tc = self.trading_calendar <NEW_LINE> sessions = tc.sessions_in_range(tc.minute_to_session_label(start), tc.minute_to_session_label(end)) <NEW_LINE> freq = sessions.freq <NEW_LINE> if first == front: <NEW_LINE> <INDENT> curr = first_contract << 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> curr = first_contract << 2 <NEW_LINE> <DEDENT> session = sessions[-1] <NEW_LINE> while session > start and curr is not None: <NEW_LINE> <INDENT> front = curr.contract.sid <NEW_LINE> back = rolls[0][0] <NEW_LINE> prev_c = curr.prev <NEW_LINE> while session > start: <NEW_LINE> <INDENT> prev = session - freq <NEW_LINE> if prev_c is not None: <NEW_LINE> <INDENT> if prev < prev_c.contract.auto_close_date: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if back != self._active_contract(oc, front, back, prev): <NEW_LINE> <INDENT> rolls.insert(0, ((curr >> offset).contract.sid, session)) <NEW_LINE> break <NEW_LINE> <DEDENT> session = prev <NEW_LINE> <DEDENT> curr = curr.prev <NEW_LINE> if curr is not None: <NEW_LINE> <INDENT> session = min(session, curr.contract.auto_close_date + freq) <NEW_LINE> <DEDENT> <DEDENT> return rolls
|
Abstract base class for calculating when futures contracts are the active
contract.
|
6259902a26238365f5fadb11
|
class Simulator: <NEW_LINE> <INDENT> ROUND_DIGITS = 0 <NEW_LINE> RADIUS_CM = 7 <NEW_LINE> TACHO_COUNT_CM_FACTOR = 20 <NEW_LINE> POSITION_FACTOR = 3.328125 <NEW_LINE> def __init__(self, x=0, y=0, r=15, angle=0): <NEW_LINE> <INDENT> self.__x = x <NEW_LINE> self.__y = y <NEW_LINE> self.__r = r <NEW_LINE> self.__angle = angle <NEW_LINE> self.__start_x = self.__x <NEW_LINE> self.__start_y = self.__y <NEW_LINE> self.__start_angle = self.__angle <NEW_LINE> self.__left_distance = 0 <NEW_LINE> self.__right_distance = 0 <NEW_LINE> <DEDENT> @common.check_int <NEW_LINE> @common.max(MAX_DIST) <NEW_LINE> @common.min(MIN_DIST) <NEW_LINE> def forward(self, distance): <NEW_LINE> <INDENT> x = math.cos(math.radians(self.__angle)) * distance / self.POSITION_FACTOR <NEW_LINE> y = math.sin(math.radians(self.__angle)) * distance / self.POSITION_FACTOR <NEW_LINE> self.__x += x <NEW_LINE> self.__y += y <NEW_LINE> self.__left_distance += distance <NEW_LINE> self.__right_distance += distance <NEW_LINE> <DEDENT> @common.check_int <NEW_LINE> @common.max(MAX_DIST) <NEW_LINE> @common.min(MIN_DIST) <NEW_LINE> def backward(self, distance): <NEW_LINE> <INDENT> x = math.cos(math.radians(self.__angle)) * distance / self.POSITION_FACTOR <NEW_LINE> y = math.sin(math.radians(self.__angle)) * distance / self.POSITION_FACTOR <NEW_LINE> self.__x -= x <NEW_LINE> self.__y -= y <NEW_LINE> self.__left_distance -= distance <NEW_LINE> self.__right_distance -= distance <NEW_LINE> <DEDENT> @common.check_int <NEW_LINE> @common.max(MAX_ANGLE) <NEW_LINE> @common.min(MIN_ANGLE) <NEW_LINE> def right(self, angle): <NEW_LINE> <INDENT> self.__angle -= angle <NEW_LINE> distance = self.calc_distance_with_angle(angle) <NEW_LINE> self.__right_distance -= distance <NEW_LINE> self.__left_distance += distance <NEW_LINE> <DEDENT> @common.check_int <NEW_LINE> @common.max(MAX_ANGLE) <NEW_LINE> @common.min(MIN_ANGLE) <NEW_LINE> def left(self, angle): <NEW_LINE> <INDENT> self.__angle += angle <NEW_LINE> distance = self.calc_distance_with_angle(angle) <NEW_LINE> self.__right_distance += distance <NEW_LINE> self.__left_distance -= distance <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.__x = self.__start_x <NEW_LINE> self.__y = self.__start_y <NEW_LINE> self.__angle = self.__start_angle <NEW_LINE> self.__right_distance = 0 <NEW_LINE> self.__left_distance = 0 <NEW_LINE> <DEDENT> def angle(self): <NEW_LINE> <INDENT> return self.__angle <NEW_LINE> <DEDENT> def position(self): <NEW_LINE> <INDENT> return int(round(self.__x, self.ROUND_DIGITS)), int(round(self.__y, self.ROUND_DIGITS)), self.__r <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def state(self): <NEW_LINE> <INDENT> out = { 'right_motor': self.__right_distance, 'left_motor': self.__left_distance, 'angle': self.angle() * -1 } <NEW_LINE> return out <NEW_LINE> <DEDENT> def calc_distance_with_angle(self, angle): <NEW_LINE> <INDENT> return round(2 * self.RADIUS_CM * math.pi * angle / 360 * self.TACHO_COUNT_CM_FACTOR) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "x: %s, y: %s, angle: %s" % (self.__x, self.__y, self.__angle)
|
Simulator for the robot and positional system.
|
6259902a1d351010ab8f4ad6
|
class Episode( collections.namedtuple( 'Episode', 'support_images, query_images, ' 'support_labels, query_labels, support_class_ids, query_class_ids')): <NEW_LINE> <INDENT> @property <NEW_LINE> def unique_class_ids(self): <NEW_LINE> <INDENT> return compute_unique_class_ids( tf.concat((self.support_class_ids, self.query_class_ids), -1)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def support_shots(self): <NEW_LINE> <INDENT> return compute_shot(self.way, self.support_labels) <NEW_LINE> <DEDENT> @property <NEW_LINE> def query_shots(self): <NEW_LINE> <INDENT> return compute_shot(self.way, self.query_labels) <NEW_LINE> <DEDENT> @property <NEW_LINE> def way(self): <NEW_LINE> <INDENT> return tf.size(self.unique_labels) <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_labels(self): <NEW_LINE> <INDENT> return tf.unique(tf.concat((self.support_labels, self.query_labels), -1))[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def labels(self): <NEW_LINE> <INDENT> return self.query_labels <NEW_LINE> <DEDENT> @property <NEW_LINE> def onehot_labels(self): <NEW_LINE> <INDENT> return self.onehot_query_labels <NEW_LINE> <DEDENT> @property <NEW_LINE> def onehot_support_labels(self): <NEW_LINE> <INDENT> return tf.one_hot(self.support_labels, self.way) <NEW_LINE> <DEDENT> @property <NEW_LINE> def onehot_query_labels(self): <NEW_LINE> <INDENT> return tf.one_hot(self.query_labels, self.way)
|
Wraps an episode's data and facilitates creation of feed dict.
Args:
support_images: A Tensor of images for fitting an episodic model.
query_images: A Tensor of images for evaluating an episodic model.
support_labels: A 1D Tensor, the matching support labels (numbers between
0 and K-1, with K the number of classes involved in the episode).
query_labels: A 1D Tensor, the matching query labels (numbers between 0
and K-1, with K the number of classes involved in the episode).
support_class_ids: A 1D Tensor, the matching support class ids (numbers
between 0 and N-1, with N the number of classes in the full dataset).
query_class_ids: A 1D Tensor, the matching query class ids (numbers
between 0 and N-1, with N the number of classes in the full dataset).
|
6259902a6e29344779b0160f
|
class SelezarPotrait(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, Start_X, Start_Y): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.image, self.rect = load_image('SelezarPotrait2.png', 'Idle') <NEW_LINE> self.image.set_colorkey((63,72,204)) <NEW_LINE> scale = 0.7 <NEW_LINE> w,h = self.image.get_size() <NEW_LINE> self.image = pygame.transform.scale(self.image, (int(w*scale), int(h*scale))) <NEW_LINE> self.Current_X_position = Start_X <NEW_LINE> self.Current_Y_position = Start_Y <NEW_LINE> screen = pygame.display.get_surface() <NEW_LINE> self.area = screen.get_rect() <NEW_LINE> self.rect.center = self.Current_X_position, self.Current_Y_position <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> return None
|
generates a potrait of Selezar
|
6259902abe8e80087fbc0039
|
class World: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.objects_list = [] <NEW_LINE> <DEDENT> def getJSON(self): <NEW_LINE> <INDENT> return json.dumps(self, default=lambda o: o.__dict__) <NEW_LINE> <DEDENT> def getDict(self): <NEW_LINE> <INDENT> return json.loads(self.toJSON())
|
This class stores a list of objects detected by the robot. This list is
refreshed everytime the simulation is updated (everytime the robot receives
information about the world)
|
6259902a1d351010ab8f4ad7
|
class COCOAnnotationTransform(object): <NEW_LINE> <INDENT> def __init__(self, label_file): <NEW_LINE> <INDENT> super(COCOAnnotationTransform, self).__init__() <NEW_LINE> self.label_map = self._labelmap(label_file) <NEW_LINE> <DEDENT> def _labelmap(self, label_file): <NEW_LINE> <INDENT> label_map = {} <NEW_LINE> labels = open(label_file, 'r') <NEW_LINE> for line in labels: <NEW_LINE> <INDENT> ids = line.split(',') <NEW_LINE> label_map[int(ids[0])] = int(ids[1]) <NEW_LINE> <DEDENT> return label_map <NEW_LINE> <DEDENT> def __call__(self, target): <NEW_LINE> <INDENT> labels = [] <NEW_LINE> bboxes = [] <NEW_LINE> for obj in target: <NEW_LINE> <INDENT> if 'bbox' in obj: <NEW_LINE> <INDENT> if obj['category_id'] not in self.label_map.keys(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> bbox = obj['bbox'] <NEW_LINE> bbox[2] += bbox[0] <NEW_LINE> bbox[3] += bbox[1] <NEW_LINE> label_idx = self.label_map[obj['category_id']] <NEW_LINE> bboxes += [bbox] <NEW_LINE> labels += [label_idx] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("no bbox problem!") <NEW_LINE> <DEDENT> <DEDENT> if len(bboxes) == 0: <NEW_LINE> <INDENT> print(target) <NEW_LINE> raise ValueError("Targets is empty") <NEW_LINE> <DEDENT> bboxes = torch.FloatTensor(bboxes) <NEW_LINE> labels = torch.LongTensor(labels) <NEW_LINE> return bboxes, labels
|
Transforms a COCO annotation into a Tensor of bbox coords and label index
Initilized with a dictionary lookup of classnames to indexes
|
6259902ad164cc6175821f38
|
class ErrorReportEvent(ObjectEvent): <NEW_LINE> <INDENT> implements(IErrorReportEvent)
|
A new error report has been created.
|
6259902a711fe17d825e147a
|
class Runner(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Runner, self).__init__() <NEW_LINE> self.radius = settings.PLAYER_RADIUS <NEW_LINE> r = self.radius <NEW_LINE> self.image = pygame.Surface((r*2, r*2), pygame.SRCALPHA) <NEW_LINE> pygame.draw.circle(self.image, colors.RED, (r, r), r, 0) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.image = self.image.convert_alpha() <NEW_LINE> self._acc = settings.PLAYER_MAXSPEED*settings.PLAYER_DRAG <NEW_LINE> self._drag = settings.PLAYER_DRAG <NEW_LINE> self._pos = (30.0, 100.0) <NEW_LINE> self._vel = (0.0, 0.0) <NEW_LINE> self._set_rect_pos() <NEW_LINE> <DEDENT> def set_direction(self, up, down, left, right): <NEW_LINE> <INDENT> if up and not down: <NEW_LINE> <INDENT> y = -1 <NEW_LINE> <DEDENT> elif down and not up: <NEW_LINE> <INDENT> y = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y = 0 <NEW_LINE> <DEDENT> if left and not right: <NEW_LINE> <INDENT> x = -1 <NEW_LINE> <DEDENT> elif right and not left: <NEW_LINE> <INDENT> x = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = 0 <NEW_LINE> <DEDENT> if y==1 and x!=0: <NEW_LINE> <INDENT> y = ROOT2 <NEW_LINE> <DEDENT> if y==-1 and x!=0: <NEW_LINE> <INDENT> y = -ROOT2 <NEW_LINE> <DEDENT> if x==1 and y!=0: <NEW_LINE> <INDENT> x = ROOT2 <NEW_LINE> <DEDENT> if x==-1 and y!=0: <NEW_LINE> <INDENT> x = -ROOT2 <NEW_LINE> <DEDENT> self._dir = (x,y) <NEW_LINE> <DEDENT> def move(self, timestep, mediator): <NEW_LINE> <INDENT> dx = ((1.0-timestep*self._drag)*self._vel[0] + timestep*self._acc*self._dir[0]) <NEW_LINE> dy = ((1.0-timestep*self._drag)*self._vel[1] + timestep*self._acc*self._dir[1]) <NEW_LINE> self._vel = (dx, dy) <NEW_LINE> old_pos = self._pos <NEW_LINE> self._pos = (old_pos[0]+self._vel[0]*timestep, old_pos[1]+self._vel[1]*timestep) <NEW_LINE> self._set_rect_pos() <NEW_LINE> if mediator.approve_move(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._vel = (-dx*0.5, -dy*0.5) <NEW_LINE> self._pos = (old_pos[0], old_pos[1]) <NEW_LINE> self._set_rect_pos() <NEW_LINE> <DEDENT> <DEDENT> def _set_rect_pos(self): <NEW_LINE> <INDENT> self.rect.center = (int(self._pos[0]-self.radius), int(self._pos[1]+self.radius))
|
Runner's Sprite
|
6259902a21a7993f00c66f3e
|
class Console(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.timer = None <NEW_LINE> self.__callback = None <NEW_LINE> self.encoding = sys.getfilesystemencoding() <NEW_LINE> self.last_return_code = None <NEW_LINE> self.logger = logging.getLogger(self.__class__.__name__) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self.timer: <NEW_LINE> <INDENT> self.timer.cancel() <NEW_LINE> <DEDENT> <DEDENT> def __process_lines(self, lines): <NEW_LINE> <INDENT> return [line.decode('utf-8').rstrip() for line in lines] <NEW_LINE> <DEDENT> def get_last_return_code(self): <NEW_LINE> <INDENT> return self.last_return_code <NEW_LINE> <DEDENT> def command(self, command, timeout=2.0): <NEW_LINE> <INDENT> self.logger.trace('Launch command "%s"' % command) <NEW_LINE> result = { 'returncode': 0, 'error': False, 'killed': False, 'stdout': [], 'stderr': [] } <NEW_LINE> if timeout is None or timeout <= 0.0: <NEW_LINE> <INDENT> raise Exception('Timeout is mandatory and must be greater than 0') <NEW_LINE> <DEDENT> proc = subprocess.Popen( command, shell=True, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, preexec_fn=os.setsid ) <NEW_LINE> pid = proc.pid <NEW_LINE> done = False <NEW_LINE> start = time.time() <NEW_LINE> killed = False <NEW_LINE> return_code = None <NEW_LINE> while not done: <NEW_LINE> <INDENT> (stdout, stderr) = proc.communicate() <NEW_LINE> if stdout: <NEW_LINE> <INDENT> result['stdout'] += self.__process_lines(stdout.split(b'\n')) <NEW_LINE> <DEDENT> if stderr: <NEW_LINE> <INDENT> result['stderr'] += self.__process_lines(stderr.split(b'\n')) <NEW_LINE> <DEDENT> proc.poll() <NEW_LINE> if proc.returncode is not None: <NEW_LINE> <INDENT> self.logger.trace('Command terminated with returncode %s' % proc.returncode) <NEW_LINE> return_code = proc.returncode <NEW_LINE> self.last_return_code = return_code <NEW_LINE> done = True <NEW_LINE> break <NEW_LINE> <DEDENT> if time.time() > (start + timeout): <NEW_LINE> <INDENT> pgid = os.getpgid(pid) <NEW_LINE> self.logger.debug('Timeout over, kill command for PID=%s PGID=%s' % (pid, pgid)) <NEW_LINE> try: <NEW_LINE> <INDENT> if ON_POSIX: <NEW_LINE> <INDENT> os.killpg(pgid, signal.SIGKILL) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> proc.kill() <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> killed = True <NEW_LINE> break <NEW_LINE> <DEDENT> time.sleep(0.125) <NEW_LINE> <DEDENT> result['returncode'] = return_code <NEW_LINE> if not killed: <NEW_LINE> <INDENT> result['error'] = len(result['stderr']) > 0 <NEW_LINE> <DEDENT> self.logger.trace('Result: %s' % result) <NEW_LINE> try: <NEW_LINE> <INDENT> proc.stdout.close() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> proc.stderr.close() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if self.__callback: <NEW_LINE> <INDENT> self.__callback(result) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def command_delayed(self, command, delay, timeout=2.0, callback=None): <NEW_LINE> <INDENT> self.__callback = callback <NEW_LINE> self.timer = Timer(delay, self.command, [command, timeout]) <NEW_LINE> self.timer.daemon = True <NEW_LINE> self.timer.name = 'commanddelayed' <NEW_LINE> self.timer.start()
|
Helper class to execute command lines.
You can execute command right now using command method or after a certain amount of time using command_delayed
|
6259902a66673b3332c313b0
|
class ModelEma: <NEW_LINE> <INDENT> def __init__(self, model, decay=0.9999, device='', resume=''): <NEW_LINE> <INDENT> self.ema = deepcopy(model) <NEW_LINE> self.ema.eval() <NEW_LINE> self.decay = decay <NEW_LINE> self.device = device <NEW_LINE> if device: <NEW_LINE> <INDENT> self.ema.to(device=device) <NEW_LINE> <DEDENT> self.ema_has_module = hasattr(self.ema, 'module') <NEW_LINE> if resume: <NEW_LINE> <INDENT> self._load_checkpoint(resume) <NEW_LINE> <DEDENT> for p in self.ema.parameters(): <NEW_LINE> <INDENT> p.requires_grad_(False) <NEW_LINE> <DEDENT> <DEDENT> def _load_checkpoint(self, checkpoint_path): <NEW_LINE> <INDENT> checkpoint = torch.load(checkpoint_path, map_location='cpu') <NEW_LINE> assert isinstance(checkpoint, dict) <NEW_LINE> if 'state_dict_ema' in checkpoint: <NEW_LINE> <INDENT> new_state_dict = OrderedDict() <NEW_LINE> for k, v in checkpoint['state_dict_ema'].items(): <NEW_LINE> <INDENT> if self.ema_has_module: <NEW_LINE> <INDENT> name = 'module.' + k if not k.startswith('module') else k <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = k <NEW_LINE> <DEDENT> new_state_dict[name] = v <NEW_LINE> <DEDENT> self.ema.load_state_dict(new_state_dict) <NEW_LINE> _logger.info("Loaded state_dict_ema") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _logger.warning("Failed to find state_dict_ema, starting from loaded model weights") <NEW_LINE> <DEDENT> <DEDENT> def update(self, model): <NEW_LINE> <INDENT> needs_module = hasattr(model, 'module') and not self.ema_has_module <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> msd = model.state_dict() <NEW_LINE> for k, ema_v in self.ema.state_dict().items(): <NEW_LINE> <INDENT> if needs_module: <NEW_LINE> <INDENT> k = 'module.' + k <NEW_LINE> <DEDENT> model_v = msd[k].detach() <NEW_LINE> if self.device: <NEW_LINE> <INDENT> model_v = model_v.to(device=self.device) <NEW_LINE> <DEDENT> ema_v.copy_(ema_v * self.decay + (1. - self.decay) * model_v)
|
Model Exponential Moving Average
Keep a moving average of everything in the model state_dict (parameters and buffers).
This is intended to allow functionality like
https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
A smoothed version of the weights is necessary for some training schemes to perform well.
E.g. Google's hyper-params for training MNASNet, MobileNet-V3, EfficientNet, etc that use
RMSprop with a short 2.4-3 epoch decay period and slow LR decay rate of .96-.99 requires EMA
smoothing of weights to match results. Pay attention to the decay constant you are using
relative to your update count per epoch.
To keep EMA from using GPU resources, set device='cpu'. This will save a bit of memory but
disable validation of the EMA weights. Validation will have to be done manually in a separate
process, or after the training stops converging.
This class is sensitive where it is initialized in the sequence of model init,
GPU assignment and distributed training wrappers.
I've tested with the sequence in my own train.py for torch.DataParallel, apex.DDP, and single-GPU.
|
6259902a5e10d32532ce40e4
|
class OpenFromJSON(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def insert_config(self,**kwargs): <NEW_LINE> <INDENT> file_to_write=kwargs['path'] <NEW_LINE> kwargs.__delitem__('path') <NEW_LINE> out_file = open(file_to_write,"w") <NEW_LINE> json.dump(kwargs , out_file , indent=4) <NEW_LINE> out_file.close() <NEW_LINE> <DEDENT> def get_config(self,**kwargs): <NEW_LINE> <INDENT> path = kwargs['path'] <NEW_LINE> kwargs.__delitem__('path') <NEW_LINE> in_file = open(path,"r") <NEW_LINE> kwargs = json.load(in_file) <NEW_LINE> in_file.close() <NEW_LINE> return kwargs
|
OpenFromJson is a class, which imports cobfiguration from JSON format.
|
6259902a8e05c05ec3f6f63c
|
class MarscoinTestNet(Marscoin): <NEW_LINE> <INDENT> name = 'test-marscoin' <NEW_LINE> seeds = ("dnsseed.marscoin.ru", "testnet-seed.marscointools.com") <NEW_LINE> port = 18338 <NEW_LINE> message_start = b'\xfc\xc1\xb7\xdc' <NEW_LINE> base58_prefixes = { 'PUBKEY_ADDR': 111, 'SCRIPT_ADDR': 196, 'SECRET_KEY': 239 }
|
Class with all the necessary Diamond testing network information based on
https://github.com/marscoin/marscoin/blob/master-0.2/src/net.cpp
(date of access: 02/16/2018)
|
6259902a15baa72349462f59
|
class EnumerateUsers(actions.ActionPlugin): <NEW_LINE> <INDENT> out_rdfvalues = [rdf_client.User, rdf_client.KnowledgeBaseUser] <NEW_LINE> def ParseWtmp(self): <NEW_LINE> <INDENT> users = {} <NEW_LINE> wtmp_struct_size = UtmpStruct.GetSize() <NEW_LINE> for filename in sorted(os.listdir("/var/log")): <NEW_LINE> <INDENT> if filename.startswith("wtmp"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> wtmp = open(os.path.join("/var/log", filename), "rb").read() <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for offset in xrange(0, len(wtmp), wtmp_struct_size): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> record = UtmpStruct(wtmp[offset:offset + wtmp_struct_size]) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if record.ut_type != 7: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if users[record.ut_user] < record.tv_sec: <NEW_LINE> <INDENT> users[record.ut_user] = record.tv_sec <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> users[record.ut_user] = record.tv_sec <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return users <NEW_LINE> <DEDENT> def Run(self, unused_args): <NEW_LINE> <INDENT> users = self.ParseWtmp() <NEW_LINE> for user, last_login in users.iteritems(): <NEW_LINE> <INDENT> username = user.split("\x00", 1)[0] <NEW_LINE> if username: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pwdict = pwd.getpwnam(username) <NEW_LINE> homedir = pwdict[5] <NEW_LINE> full_name = pwdict[4] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> homedir = "" <NEW_LINE> full_name = "" <NEW_LINE> <DEDENT> if last_login < 0: <NEW_LINE> <INDENT> last_login = 0 <NEW_LINE> <DEDENT> self.SendReply( rdf_client.User( username=utils.SmartUnicode(username), homedir=utils.SmartUnicode(homedir), full_name=utils.SmartUnicode(full_name), last_logon=last_login * 1000000))
|
Enumerates all the users on this system.
While wtmp can be collected and parsed server-side using artifacts, we keep
this client action to avoid collecting every wtmp on every interrogate, and to
allow for the metadata (homedir) expansion to occur on the client, where we
have access to LDAP.
|
6259902ad99f1b3c44d06665
|
class AttrList: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self._init_pointer(pango.pango_attr_list_new()) <NEW_LINE> <DEDENT> def _init_pointer(self, pointer: ffi.CData): <NEW_LINE> <INDENT> self._pointer = ffi.gc(pointer, pango.pango_attr_list_unref) <NEW_LINE> <DEDENT> def get_pointer(self) -> ffi.CData: <NEW_LINE> <INDENT> return self._pointer <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_pointer(cls, pointer: ffi.CData) -> "AttrList": <NEW_LINE> <INDENT> if pointer == ffi.NULL: <NEW_LINE> <INDENT> raise ValueError("Null pointer") <NEW_LINE> <DEDENT> self = object.__new__(cls) <NEW_LINE> self._pointer = pointer <NEW_LINE> return self <NEW_LINE> <DEDENT> def _ref(self) -> None: <NEW_LINE> <INDENT> self._pointer = pango.pango_attr_list_ref(self._pointer) <NEW_LINE> <DEDENT> def _unref(self) -> None: <NEW_LINE> <INDENT> pango.pango_attr_list_unref(self._pointer) <NEW_LINE> <DEDENT> def copy(self) -> "AttrList": <NEW_LINE> <INDENT> return AttrList.from_pointer(pango.pango_attr_list_copy(self._pointer)) <NEW_LINE> <DEDENT> def __copy__(self) -> "AttrList": <NEW_LINE> <INDENT> return self.copy() <NEW_LINE> <DEDENT> def __deepcopy__(self, memo) -> "AttrList": <NEW_LINE> <INDENT> return self.copy() <NEW_LINE> <DEDENT> def insert(self, attr: Attribute) -> None: <NEW_LINE> <INDENT> assert isinstance(attr, Attribute), "attr isn't a Attribute" <NEW_LINE> self._ref() <NEW_LINE> pango.pango_attr_list_insert(self._pointer, attr.get_pointer()) <NEW_LINE> <DEDENT> def insert_before(self, attr: Attribute) -> None: <NEW_LINE> <INDENT> assert isinstance(attr, Attribute), "attr isn't a Attribute" <NEW_LINE> self._ref() <NEW_LINE> pango.pango_attr_list_insert_before(self._pointer, attr.get_pointer()) <NEW_LINE> <DEDENT> def change(self, attr: Attribute) -> None: <NEW_LINE> <INDENT> assert isinstance(attr, Attribute), "attr isn't a Attribute" <NEW_LINE> self._ref() <NEW_LINE> pango.pango_attr_list_change(self._pointer, attr.get_pointer()) <NEW_LINE> <DEDENT> def splice(self, attr_list: "AttrList", pos: int, length: int): <NEW_LINE> <INDENT> assert isinstance(attr_list, AttrList), "attr_list isn't a AttrList" <NEW_LINE> assert isinstance(pos, int), "pos isn't a int" <NEW_LINE> assert isinstance(length, int), "length isn't a int" <NEW_LINE> length = ffi.cast("gint", length) <NEW_LINE> pos = ffi.cast("gint", pos) <NEW_LINE> pango.pango_attr_list_splice( self._pointer, attr_list._pointer, pos, length, ) <NEW_LINE> <DEDENT> def __eq__(self, other: "AttrList") -> bool: <NEW_LINE> <INDENT> if isinstance(other, AttrList): <NEW_LINE> <INDENT> return bool( pango.pango_attr_list_equal( self.get_pointer(), other.get_pointer(), ) ) <NEW_LINE> <DEDENT> raise NotImplementedError
|
The :class:`AttrList` represents a list of attributes(:class:`Attribute`)
that apply to a section of text. The attributes are, in general, allowed
to overlap in an arbitrary fashion, however, if the attributes are
manipulated only through :func:`AttrList.change()`, the overlap between
properties will meet stricter criteria.
In general, you should not use a single :class:`AttrList` for more than
one paragraph of text due to internal structures.
|
6259902a21a7993f00c66f40
|
class PyFilter(object): <NEW_LINE> <INDENT> def __init__(self, callable): <NEW_LINE> <INDENT> self.callable = callable <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<pyfilter '{}'>".format(self.callable.func_name) <NEW_LINE> <DEDENT> def __moyafilter__(self, context, app, value, params): <NEW_LINE> <INDENT> return self.callable(value)
|
A Python defined Moya filter.
|
6259902a23e79379d538d4ce
|
class FileSetsByRegexp: <NEW_LINE> <INDENT> def __init__(self, id_regexp_s, id_group = 0): <NEW_LINE> <INDENT> self.id_regexp = re.compile( id_regexp_s) <NEW_LINE> self.id_regexp_s = id_regexp_s <NEW_LINE> self.id_group = id_group <NEW_LINE> <DEDENT> def extract_id(self, name): <NEW_LINE> <INDENT> ret = None <NEW_LINE> s = self.id_regexp.search(name) <NEW_LINE> if s: <NEW_LINE> <INDENT> groups = s.groups() <NEW_LINE> if groups: <NEW_LINE> <INDENT> ret = groups[self.id_group] <NEW_LINE> <DEDENT> <DEDENT> return ret <NEW_LINE> <DEDENT> def group_by(self, list_of_names): <NEW_LINE> <INDENT> groups = {} <NEW_LINE> for name in list_of_names: <NEW_LINE> <INDENT> id = self.extract_id(name) <NEW_LINE> if id: <NEW_LINE> <INDENT> if groups.has_key(id): <NEW_LINE> <INDENT> groups[id].append(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> groups[id] = [name] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("Ignoring name '%s" % (name,)) <NEW_LINE> <DEDENT> <DEDENT> return groups
|
Groups a list of filenames by an id extracted from the filename.
|
6259902a9b70327d1c57fd46
|
class MaxPoolLayer(object): <NEW_LINE> <INDENT> def __init__(self, filter_width=2, filter_height=2, stride=2): <NEW_LINE> <INDENT> self.type = 'pool' <NEW_LINE> self.filter_height, self.filter_width = filter_height, filter_width <NEW_LINE> self.stride = stride <NEW_LINE> self.indices = list() <NEW_LINE> <DEDENT> def pool_function(self, x, type='reshape'): <NEW_LINE> <INDENT> if type == 'reshape': <NEW_LINE> <INDENT> return x.max(axis=2).max(axis=3) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x.max(), x.argmax()
|
Pooling layer that performs the max pooling action, typically used after a ConvolutedLayer
|
6259902abe8e80087fbc003d
|
class ModoboaException(Exception): <NEW_LINE> <INDENT> http_code = None <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if "http_code" in kwargs: <NEW_LINE> <INDENT> self.http_code = kwargs["http_code"] <NEW_LINE> del kwargs["http_code"] <NEW_LINE> <DEDENT> super(ModoboaException, self).__init__(*args, **kwargs)
|
Base class for Modoboa custom exceptions.
|
6259902a287bf620b6272bb5
|
class WordCloudFields(object): <NEW_LINE> <INDENT> num_inputs = Integer( display_name="Inputs", help="Number of text boxes available for students to input words/sentences.", scope=Scope.settings, default=5, values={"min": 1} ) <NEW_LINE> num_top_words = Integer( display_name="Maximum Words", help="Maximum number of words to be displayed in generated word cloud.", scope=Scope.settings, default=250, values={"min": 1} ) <NEW_LINE> display_student_percents = Boolean( display_name="Show Percents", help="Statistics are shown for entered words near that word.", scope=Scope.settings, default=True ) <NEW_LINE> submitted = Boolean( help="Whether this student has posted words to the cloud.", scope=Scope.user_state, default=False ) <NEW_LINE> student_words = List( help="Student answer.", scope=Scope.user_state, default=[] ) <NEW_LINE> all_words = Dict( help="All possible words from all students.", scope=Scope.content ) <NEW_LINE> top_words = Dict( help="Top num_top_words words for word cloud.", scope=Scope.content )
|
XFields for word cloud.
|
6259902a1f5feb6acb163bb5
|
class ValueLessThanFilterSpecification(CriterionFilterSpecification): <NEW_LINE> <INDENT> operator = LESS_THAN
|
Concrete value less than specification
|
6259902a30c21e258be997d0
|
class TestAdapterHugeMemoryRequired(ABCAdapter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> ABCAdapter.__init__(self) <NEW_LINE> <DEDENT> def get_input_tree(self): <NEW_LINE> <INDENT> return [{'name': 'test', 'type': 'int', 'default': '0'}] <NEW_LINE> <DEDENT> def get_output(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def get_required_memory_size(self, **kwargs): <NEW_LINE> <INDENT> return 999999999999999 <NEW_LINE> <DEDENT> def get_required_disk_size(self, **kwargs): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def launch(self, test): <NEW_LINE> <INDENT> str(test)
|
Adapter used for testing launch when a lot of memory is required.
|
6259902aec188e330fdf9858
|
@ns.route('/', endpoint='datasets') <NEW_LINE> class DatasetListAPI(API): <NEW_LINE> <INDENT> @api.doc('list_datasets') <NEW_LINE> @api.expect(search_parser) <NEW_LINE> @api.marshal_with(dataset_page_fields) <NEW_LINE> def get(self): <NEW_LINE> <INDENT> search_parser.parse_args() <NEW_LINE> return search.query(Dataset, **multi_to_dict(request.args)) <NEW_LINE> <DEDENT> @api.secure <NEW_LINE> @api.doc('create_dataset', responses={400: 'Validation error'}) <NEW_LINE> @api.expect(dataset_fields) <NEW_LINE> @api.marshal_with(dataset_fields) <NEW_LINE> def post(self): <NEW_LINE> <INDENT> form = api.validate(DatasetForm) <NEW_LINE> dataset = form.save() <NEW_LINE> return dataset, 201
|
Datasets collection endpoint
|
6259902ad6c5a102081e30eb
|
class LDAPExceptionTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_exception_with_dn(self): <NEW_LINE> <INDENT> dn = distinguishedname.DistinguishedName(stringValue='dc=example,dc=org') <NEW_LINE> exception = ldaperrors.LDAPNoSuchObject(dn) <NEW_LINE> self.assertEqual(exception.toWire(), b'noSuchObject: dc=example,dc=org') <NEW_LINE> <DEDENT> def test_exception_with_message(self): <NEW_LINE> <INDENT> exception = ldaperrors.LDAPProtocolError('Error message') <NEW_LINE> self.assertEqual(exception.toWire(), b'protocolError: Error message') <NEW_LINE> <DEDENT> def test_empty_exception(self): <NEW_LINE> <INDENT> exception = ldaperrors.LDAPCompareFalse() <NEW_LINE> self.assertEqual(exception.toWire(), b'compareFalse') <NEW_LINE> <DEDENT> def test_unnamed_exception(self): <NEW_LINE> <INDENT> exception = UnnamedException() <NEW_LINE> self.assertEqual(exception.toWire(), b'Unknown LDAP error UnnamedException()') <NEW_LINE> <DEDENT> def test_unknown_exception_with_message(self): <NEW_LINE> <INDENT> exception = ldaperrors.LDAPUnknownError(56, 'Error message') <NEW_LINE> self.assertEqual(exception.toWire(), b'unknownError(56): Error message') <NEW_LINE> <DEDENT> def test_unknown_empty_exception(self): <NEW_LINE> <INDENT> exception = ldaperrors.LDAPUnknownError(57) <NEW_LINE> self.assertEqual(exception.toWire(), b'unknownError(57)')
|
Getting bytes representations of LDAP exceptions
|
6259902a21a7993f00c66f42
|
class NotAWebIDException(RejectedClaimException): <NEW_LINE> <INDENT> pass
|
The given URI is not a WebID (no profile
document has been found)
Code: noWebId
|
6259902a26238365f5fadb17
|
@typic.slotted <NEW_LINE> @dataclasses.dataclass(unsafe_hash=True, order=True) <NEW_LINE> class Action: <NEW_LINE> <INDENT> type: ClassVar[NodeType] = NodeType.ACTION <NEW_LINE> action: str <NEW_LINE> persona: NodeID <NEW_LINE> scene: NodeID <NEW_LINE> index: int <NEW_LINE> @typic.cached_property <NEW_LINE> def id(self) -> NodeID: <NEW_LINE> <INDENT> return NodeID(f"{self.scene}-{self.persona}-{self.type.lower()}-{self.index}") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_node(cls, node: "GenericNode") -> "Action": <NEW_LINE> <INDENT> if not node.parent or not node.scene: <NEW_LINE> <INDENT> raise ValueError(f"Can't build {cls.__name__!r} from node: {node}") <NEW_LINE> <DEDENT> return cls( action=node.match_text, persona=node.parent, scene=node.scene, index=node.index, )
|
A representation of a stage direction related to a specific character.
|
6259902a50485f2cf55dbf46
|
class SBFloat32(BaseStructField): <NEW_LINE> <INDENT> PACK_FORMAT = UNPACK_FORMAT = b">f"
|
Unsigned Big Endian 32-bit float field
|
6259902ae76e3b2f99fd99d2
|
class TestApiAddUserResponse(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 testApiAddUserResponse(self): <NEW_LINE> <INDENT> pass
|
ApiAddUserResponse unit test stubs
|
6259902aa4f1c619b294f5ba
|
class Snoozer: <NEW_LINE> <INDENT> def __init__(self, seconds, maximum=None, watch_fds=None): <NEW_LINE> <INDENT> self._lock = threading.Lock() <NEW_LINE> self.seconds = seconds <NEW_LINE> self.maximum = max(maximum or 0, seconds) <NEW_LINE> self.watch_fds = watch_fds or [] <NEW_LINE> self._snoozeq = Queue() <NEW_LINE> self._earliest = 0 <NEW_LINE> self._latest = 0 <NEW_LINE> self._wake_reason = _WOKE_UNKNOWN <NEW_LINE> <DEDENT> def __lt__(s, o): return s._deadlines() < o._deadlines() <NEW_LINE> def __le__(s, o): return s._deadlines() <= o._deadlines() <NEW_LINE> def __gt__(s, o): return s._deadlines() > o._deadlines() <NEW_LINE> def __ge__(s, o): return s._deadlines() >= o._deadlines() <NEW_LINE> def _deadlines(self): <NEW_LINE> <INDENT> return (self._latest, self._earliest) <NEW_LINE> <DEDENT> def _ready(self, now=None): <NEW_LINE> <INDENT> return (self._earliest <= (now if (now is not None) else time.time())) <NEW_LINE> <DEDENT> def reason(self, rcode, details): <NEW_LINE> <INDENT> if rcode >= self._wake_reason[0]: <NEW_LINE> <INDENT> self._wake_reason = (rcode, details) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def wake(self, *exception_and_args): <NEW_LINE> <INDENT> throw = exception_and_args[0] if exception_and_args else None <NEW_LINE> targs = exception_and_args[1:] or None <NEW_LINE> with _conductor_lock: <NEW_LINE> <INDENT> if _conductor is not None: <NEW_LINE> <INDENT> _conductor.remove(self) <NEW_LINE> <DEDENT> <DEDENT> self.reason(*_WOKE_OTHER)._snoozeq.put((throw, targs)) <NEW_LINE> <DEDENT> def snooze(self): <NEW_LINE> <INDENT> global _conductor_lock, _conductor <NEW_LINE> if self._lock.locked(): <NEW_LINE> <INDENT> raise IOError("Snoozer is already in use!") <NEW_LINE> <DEDENT> with self._lock: <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> if self.maximum < 0.5: <NEW_LINE> <INDENT> with _conductor_lock: <NEW_LINE> <INDENT> if _conductor is not None and _conductor._ready(now): <NEW_LINE> <INDENT> _conductor._wake_up() <NEW_LINE> <DEDENT> <DEDENT> time.sleep(self.maximum) <NEW_LINE> return _WOKE_NORMAL <NEW_LINE> <DEDENT> with _conductor_lock: <NEW_LINE> <INDENT> if _conductor is None: <NEW_LINE> <INDENT> _conductor = _SnoozeBot() <NEW_LINE> _conductor.start() <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> while not self._snoozeq.empty(): <NEW_LINE> <INDENT> self._snoozeq.get(False) <NEW_LINE> <DEDENT> self._wake_reason = _WOKE_UNKNOWN <NEW_LINE> self._earliest = now + self.seconds <NEW_LINE> self._latest = now + self.maximum <NEW_LINE> exc, targs = ( _conductor.snooze(self)._snoozeq.get(True, self.maximum)) <NEW_LINE> if exc is not None: <NEW_LINE> <INDENT> raise(exc(*(targs or []))) <NEW_LINE> <DEDENT> return self._wake_reason <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> return _WOKE_NORMAL
|
This is a reusable Snooze schedule, which also provides a wake()
function so other parts of an app can wake a snoozing thread.
|
6259902abe8e80087fbc003f
|
class VariableOffsetWindowIndexer(BaseIndexer): <NEW_LINE> <INDENT> def __init__( self, index_array: np.ndarray | None = None, window_size: int = 0, index=None, offset=None, **kwargs, ): <NEW_LINE> <INDENT> super().__init__(index_array, window_size, **kwargs) <NEW_LINE> self.index = index <NEW_LINE> self.offset = offset <NEW_LINE> <DEDENT> @Appender(get_window_bounds_doc) <NEW_LINE> def get_window_bounds( self, num_values: int = 0, min_periods: int | None = None, center: bool | None = None, closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: <NEW_LINE> <INDENT> if step is not None: <NEW_LINE> <INDENT> raise NotImplementedError("step not implemented for variable offset window") <NEW_LINE> <DEDENT> if num_values <= 0: <NEW_LINE> <INDENT> return np.empty(0, dtype="int64"), np.empty(0, dtype="int64") <NEW_LINE> <DEDENT> if closed is None: <NEW_LINE> <INDENT> closed = "right" if self.index is not None else "both" <NEW_LINE> <DEDENT> right_closed = closed in ["right", "both"] <NEW_LINE> left_closed = closed in ["left", "both"] <NEW_LINE> if self.index[num_values - 1] < self.index[0]: <NEW_LINE> <INDENT> index_growth_sign = -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index_growth_sign = 1 <NEW_LINE> <DEDENT> start = np.empty(num_values, dtype="int64") <NEW_LINE> start.fill(-1) <NEW_LINE> end = np.empty(num_values, dtype="int64") <NEW_LINE> end.fill(-1) <NEW_LINE> start[0] = 0 <NEW_LINE> if right_closed: <NEW_LINE> <INDENT> end[0] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> end[0] = 0 <NEW_LINE> <DEDENT> for i in range(1, num_values): <NEW_LINE> <INDENT> end_bound = self.index[i] <NEW_LINE> start_bound = self.index[i] - index_growth_sign * self.offset <NEW_LINE> if left_closed: <NEW_LINE> <INDENT> start_bound -= Nano(1) <NEW_LINE> <DEDENT> start[i] = i <NEW_LINE> for j in range(start[i - 1], i): <NEW_LINE> <INDENT> if (self.index[j] - start_bound) * index_growth_sign > timedelta(0): <NEW_LINE> <INDENT> start[i] = j <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if (self.index[end[i - 1]] - end_bound) * index_growth_sign <= timedelta(0): <NEW_LINE> <INDENT> end[i] = i + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> end[i] = end[i - 1] <NEW_LINE> <DEDENT> if not right_closed: <NEW_LINE> <INDENT> end[i] -= 1 <NEW_LINE> <DEDENT> <DEDENT> return start, end
|
Calculate window boundaries based on a non-fixed offset such as a BusinessDay.
|
6259902a21bff66bcd723c29
|
class Response(ResponseBase): <NEW_LINE> <INDENT> def __init__(self, result=None, message=None, *args, **kwargs): <NEW_LINE> <INDENT> self.result = result <NEW_LINE> self.message = message <NEW_LINE> super(Response, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__dict__.__str__()
|
Response object for the Transaction::approve API
:param bool result: Result of the API call
:param str message: message related to the API call
|
6259902a91af0d3eaad3adef
|
class CelebDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, csv_path, img_path, img_ext, transform=None): <NEW_LINE> <INDENT> tmp_df = pd.read_csv(csv_path) <NEW_LINE> assert tmp_df['Image_Name'].apply(lambda x: os.path.isfile(img_path + x + img_ext)).all(), "Some images referenced in the CSV file were not found" <NEW_LINE> self.mlb = MultiLabelBinarizer() <NEW_LINE> self.img_path = img_path <NEW_LINE> self.img_ext = img_ext <NEW_LINE> self.transform = transform <NEW_LINE> self.X_train = tmp_df['Image_Name'] <NEW_LINE> self.y_train = self.mlb.fit_transform(tmp_df['Gender'].str.split()).astype(np.float32) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> img = cv2.imread(self.img_path + self.X_train[index] + self.img_ext) <NEW_LINE> img = cv2.resize(img, (256,256)) <NEW_LINE> img = img - np.array([104,117,123]) <NEW_LINE> img = img.transpose(2, 0, 1) <NEW_LINE> img = torch.from_numpy(img).float() <NEW_LINE> label = torch.from_numpy(self.y_train[index]) <NEW_LINE> return img, label <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.X_train.index)
|
Dataset wrapping images and target labels
Arguments:
A CSV file path
Path to image folder
Extension of images
PIL transforms
|
6259902a1f5feb6acb163bb7
|
class ComponentTest(ContainerBase): <NEW_LINE> <INDENT> shard = 22 <NEW_LINE> def setUp(self, is_staff=True): <NEW_LINE> <INDENT> super(ComponentTest, self).setUp(is_staff=is_staff) <NEW_LINE> self.advanced_settings = AdvancedSettingsPage( self.browser, self.course_info['org'], self.course_info['number'], self.course_info['run'] ) <NEW_LINE> <DEDENT> def populate_course_fixture(self, course_fixture): <NEW_LINE> <INDENT> course_fixture.add_advanced_settings( {u"advanced_modules": {"value": ["split_test"]}} ) <NEW_LINE> course_fixture.add_children( XBlockFixtureDesc('chapter', 'Test Section').add_children( XBlockFixtureDesc('sequential', 'Test Subsection').add_children( XBlockFixtureDesc('vertical', 'Test Unit') ) ) ) <NEW_LINE> <DEDENT> def test_add_html_component(self): <NEW_LINE> <INDENT> components = ['Text', 'Announcement', 'Zooming Image Tool', 'Raw HTML'] <NEW_LINE> self.go_to_unit_page() <NEW_LINE> container_page = ContainerPage(self.browser, None) <NEW_LINE> add_components(container_page, 'html', components) <NEW_LINE> problems = [x_block.name for x_block in container_page.xblocks[1:]] <NEW_LINE> self.assertEqual(problems, components) <NEW_LINE> <DEDENT> def test_add_latex_html_component(self): <NEW_LINE> <INDENT> component = 'E-text Written in LaTeX' <NEW_LINE> self.advanced_settings.visit() <NEW_LINE> self.advanced_settings.set('Enable LaTeX Compiler', 'True') <NEW_LINE> self.go_to_unit_page() <NEW_LINE> container_page = ContainerPage(self.browser, None) <NEW_LINE> add_component(container_page, 'html', component, is_advanced_problem=False) <NEW_LINE> problem = container_page.xblocks[1] <NEW_LINE> self.assertEqual(problem.name, component) <NEW_LINE> <DEDENT> def test_common_problem_component(self): <NEW_LINE> <INDENT> components = ['Blank Common Problem', 'Checkboxes', 'Dropdown', 'Multiple Choice', 'Numerical Input', 'Text Input'] <NEW_LINE> self.go_to_unit_page() <NEW_LINE> container_page = ContainerPage(self.browser, None) <NEW_LINE> add_components(container_page, 'problem', components) <NEW_LINE> problems = [x_block.name for x_block in container_page.xblocks[1:]] <NEW_LINE> self.assertEqual(problems, components)
|
Test class to add different components.
(Not the advanced components)
|
6259902ad6c5a102081e30ed
|
class MaxFuncCallReference(FuncCallReference): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> super(MaxFuncCallReference, self).__init__(True, max, *args) <NEW_LINE> <DEDENT> def __safe_repr__(self): <NEW_LINE> <INDENT> return "max_ref({0})".format(self._args_repr())
|
Holds a reference to max(*args) function call.
|
6259902ac432627299fa3fba
|
class EthereumPeer(): <NEW_LINE> <INDENT> def __init__(self, nodes): <NEW_LINE> <INDENT> self.nodes = nodes <NEW_LINE> self.id = 1 <NEW_LINE> self.port = 8545 <NEW_LINE> <DEDENT> def __payload(self, method, params): <NEW_LINE> <INDENT> return json.dumps({ "jsonrpc": "2.0", "method": method, "params": params, "id": self.id }) <NEW_LINE> <DEDENT> def encodes(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> encodes = [] <NEW_LINE> payload = self.__payload("admin_nodeInfo", []) <NEW_LINE> for host in self.nodes['nodes']: <NEW_LINE> <INDENT> url = "http://{}:{}".format(host, self.port) <NEW_LINE> response = requests.post(url, data=payload) <NEW_LINE> encodes.append(response.json()['result']['enode'].replace('[::]', host)) <NEW_LINE> <DEDENT> return encodes <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> <DEDENT> def connectivity(self, encodes): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = "http://{}:{}".format(self.nodes['master'], self.port) <NEW_LINE> for ec in encodes: <NEW_LINE> <INDENT> payload = self.__payload("admin_addPeer", [ec]) <NEW_LINE> response = requests.post(url, data=payload) <NEW_LINE> print(response.json()) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e)
|
Add the ethereum nodes peer.
|
6259902a56b00c62f0fb3887
|
class ElementParser(Element, metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> super().__init__(self.key, value) <NEW_LINE> <DEDENT> @property <NEW_LINE> @classmethod <NEW_LINE> @abstractmethod <NEW_LINE> def key(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}({})'.format(self.name, bytes(self.value))
|
Construct a Element Parser base class.
Element Parsers are used to enforce the convention that all Element Parsers
already know the key of the element they are constructing.
Element Parser is a helper class that simplifies known element definition
and makes a layer of abstraction for functionality that all known elements
can share. The parsing interfaces are cleaner and require less coding as
their definitions (subclasses of Element Parser) do not need to call init
on super with class key and instance value.
|
6259902a925a0f43d25e900f
|
class ServerCheck: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.required_header = [] <NEW_LINE> self.legit_server = [ "br1", "eun1", "euw1", "jp1", "kr", "la1", "la2", "na1", "oc1", "tr1", "ru", "americas", "asia", "europe", ] <NEW_LINE> self.logging = logging.getLogger("ServerCheck") <NEW_LINE> self.logging.propagate = False <NEW_LINE> level = logging.INFO <NEW_LINE> if settings.DEBUG: <NEW_LINE> <INDENT> level = logging.DEBUG <NEW_LINE> <DEDENT> self.logging.setLevel(level) <NEW_LINE> handler = logging.StreamHandler() <NEW_LINE> handler.setLevel(level) <NEW_LINE> handler.setFormatter(logging.Formatter("%(asctime)s [ServerCheck] %(message)s")) <NEW_LINE> self.logging.addHandler(handler) <NEW_LINE> self.logging.info("Initiated middleware.") <NEW_LINE> <DEDENT> @middleware <NEW_LINE> async def middleware(self, request, handler): <NEW_LINE> <INDENT> server = request.rel_url.__str__().split("http://")[1].split(".")[0] <NEW_LINE> if server not in self.legit_server: <NEW_LINE> <INDENT> self.logging.info("Illegal Server.") <NEW_LINE> raise HTTPException <NEW_LINE> <DEDENT> return await handler(request)
|
Middleware that makes sure the request is aimed at the proper server.
|
6259902a73bcbd0ca4bcb259
|
class NetworkInterfaceIPConfigurationListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[NetworkInterfaceIPConfiguration]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(NetworkInterfaceIPConfigurationListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = None
|
Response for list ip configurations API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of ip configurations.
:type value: list[~azure.mgmt.network.v2018_02_01.models.NetworkInterfaceIPConfiguration]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
|
6259902aa4f1c619b294f5bc
|
class MidiMaker: <NEW_LINE> <INDENT> def __init__(self, output_directory, melody): <NEW_LINE> <INDENT> self.output_directory = output_directory <NEW_LINE> self.melody = melody <NEW_LINE> self.file_handler = FileHandler() <NEW_LINE> self.track = 0 <NEW_LINE> self.channel = 0 <NEW_LINE> self.time = 0 <NEW_LINE> self.tempo = 120 <NEW_LINE> self.volume = 127 <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> midi_file = MIDIFile(numTracks=1) <NEW_LINE> midi_file.addTempo(self.track, self.time, self.tempo) <NEW_LINE> current_time = 0 <NEW_LINE> for note_unit in self.melody: <NEW_LINE> <INDENT> for note in note_unit: <NEW_LINE> <INDENT> midi_file.addNote(self.track, self.channel, note[0], current_time, note[1], self.volume) <NEW_LINE> current_time += note[1] <NEW_LINE> <DEDENT> <DEDENT> file_name_with_path = os.path.join(self.output_directory, self.file_handler.list_to_filename(melody_list=self.melody)) <NEW_LINE> with open(file_name_with_path, "wb") as output_file: <NEW_LINE> <INDENT> midi_file.writeFile(output_file) <NEW_LINE> <DEDENT> return file_name_with_path
|
Transforms NoteUnits into midi notes that can be output.
|
6259902a6e29344779b01617
|
class Meta(object): <NEW_LINE> <INDENT> db_table = "zd_snapshot_tree"
|
表配置信息
|
6259902a21bff66bcd723c2b
|
class CompilerArgs(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.import_directories = None <NEW_LINE> self.input_file = None <NEW_LINE> self.output_source = None <NEW_LINE> self.output_header = None <NEW_LINE> self.output_base_dir = None <NEW_LINE> self.output_suffix = None <NEW_LINE> self.write_dependencies = False
|
Set of compiler arguments.
|
6259902a1d351010ab8f4adf
|
class baseparser: <NEW_LINE> <INDENT> def parse_file(self, source): <NEW_LINE> <INDENT> raise NotImplementedError("parse_file: You should have implemented this method!") <NEW_LINE> <DEDENT> def parse_string(self, source): <NEW_LINE> <INDENT> raise NotImplementedError("parse_string: You should have implemented this method!")
|
Parser interface.
|
6259902a1f5feb6acb163bb9
|
class RedirectAdminMiddleware(MiddlewareMixin): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> path = request.path_info.lstrip('/') <NEW_LINE> if request.user.is_superuser: <NEW_LINE> <INDENT> if not compile(settings.SUPERUSER_DASHBOARD).match(path): <NEW_LINE> <INDENT> return HttpResponseRedirect(settings.SUPERUSER_DASHBOARD) <NEW_LINE> <DEDENT> <DEDENT> elif compile(settings.SUPERUSER_DASHBOARD).match(path): <NEW_LINE> <INDENT> return HttpResponseRedirect(settings.INDEX_URL)
|
Middleware class that re-redirects a superuser to the superuser site
|
6259902a0a366e3fb87dd9b0
|
class Feed(twc.Widget): <NEW_LINE> <INDENT> url = None <NEW_LINE> template = 'mako:moksha.feeds.widgets.templates.feed_home' <NEW_LINE> title = twc.Variable("The title of this feed") <NEW_LINE> link = twc.Variable("The url to the site that this feed is for") <NEW_LINE> entries = twc.Variable("A list of feed entries", default=[]) <NEW_LINE> limit = twc.Param("A limit on the number of entries", default=None) <NEW_LINE> @classmethod <NEW_LINE> def iterentries(cls, limit=None): <NEW_LINE> <INDENT> if not hasattr(cls, 'id'): <NEW_LINE> <INDENT> cls.id = str(uuid.uuid4()) <NEW_LINE> <DEDENT> id = cls.id <NEW_LINE> url = cls.url <NEW_LINE> if not cls.url: <NEW_LINE> <INDENT> raise ValueError("Feed must be supplied with a url.") <NEW_LINE> <DEDENT> global feed_cache, feed_storage <NEW_LINE> if not feed_cache: <NEW_LINE> <INDENT> feed_storage = Shove('sqlite:///feeds.db', compress=True) <NEW_LINE> feed_cache = Cache(feed_storage) <NEW_LINE> <DEDENT> feed = feed_cache.fetch(url) <NEW_LINE> if not (200 <= feed.get('status', 200) < 400): <NEW_LINE> <INDENT> log.warning('Got %s status from %s: %s' % ( feed['status'], url, feed.headers.get('status'))) <NEW_LINE> cls.title = feed.headers.get('status') <NEW_LINE> cls.link = feed.feed.get('link') <NEW_LINE> return <NEW_LINE> <DEDENT> cls.link = feed.feed.get('link') <NEW_LINE> try: <NEW_LINE> <INDENT> cls.title = feed.feed.title <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> cls.title = 'Unable to parse feed' <NEW_LINE> return <NEW_LINE> <DEDENT> for i, entry in enumerate(feed.get('entries', [])): <NEW_LINE> <INDENT> entry['uid'] = '%s_%d' % (id, i) <NEW_LINE> entry['link'] = entry.get('link') <NEW_LINE> if i == limit: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> yield entry <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_entries(cls, url=None): <NEW_LINE> <INDENT> if url: <NEW_LINE> <INDENT> cls.url = url <NEW_LINE> <DEDENT> return [entry for entry in cls.iterentries()] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def num_entries(cls): <NEW_LINE> <INDENT> return len(cls.get_entries()) <NEW_LINE> <DEDENT> def prepare(self): <NEW_LINE> <INDENT> super(Feed, self).prepare() <NEW_LINE> for entry in type(self).iterentries(limit=self.limit): <NEW_LINE> <INDENT> self.entries.append(entry) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def close(cls): <NEW_LINE> <INDENT> global feed_storage <NEW_LINE> try: <NEW_LINE> <INDENT> feed_storage.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass
|
The Moksha Feed object.
A Feed is initialized with an id and a url, and automatically handles the
fetching, parsing, and caching of the data.
|
6259902a15baa72349462f61
|
class inidserfinf(inididestud): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = u'13.7 Relación urbano - regionales' <NEW_LINE> verbose_name_plural = u'13.7 Relaciones urbano - regionales' <NEW_LINE> proxy = True
|
Socioeconómico y Cultural
Relaciones funcionales urbano - regionales
Información General
|
6259902a1d351010ab8f4ae0
|
class PVE_Mission(CombatLog): <NEW_LINE> <INDENT> __slots__ = CombatLog.__slots__ <NEW_LINE> matcher = re.compile("^PVE_Mission:\s'(?P<mission>[^']+)'.\s(?P<message>.*)")
|
- mission: contains the mission id.
- message: contains the pve mission message, like starting rounds, waves, etc.
|
6259902a9b70327d1c57fd4c
|
class EcoByZipInputSet(InputSet): <NEW_LINE> <INDENT> def set_APICredentials(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'APICredentials', value) <NEW_LINE> <DEDENT> def set_Limit(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Limit', value) <NEW_LINE> <DEDENT> def set_Zip(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Zip', value)
|
An InputSet with methods appropriate for specifying the inputs to the EcoByZip
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
|
6259902a6fece00bbaccc97c
|
class Fun(Tipo): <NEW_LINE> <INDENT> def __init__(self, domain, range): <NEW_LINE> <INDENT> self.tipo = "Fun" <NEW_LINE> self.domain = domain <NEW_LINE> self.range = range <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s --> %s" % (self.domain, self.range) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if (isinstance(other, Fun)): <NEW_LINE> <INDENT> return self.domain == other.domain and self.range == other.range <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) <NEW_LINE> <DEDENT> def unify(self, t): <NEW_LINE> <INDENT> if (isinstance(t, Fun)): <NEW_LINE> <INDENT> s_domain = self.domain.unify(t.domain) <NEW_LINE> s_range = self.range.unify(t.range).compose(s_domain) <NEW_LINE> try: <NEW_LINE> <INDENT> s_self = self.domain.unify(self.range) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> s_self = Sustitucion() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> s_t = t.domain.unify(t.range) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> s_t = Sustitucion() <NEW_LINE> <DEDENT> return s_range.compose(s_domain.compose(s_t.compose(s_self.compose(s_range)))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return t.unify(self)
|
T1 --> T2
|
6259902ad6c5a102081e30f1
|
class ErrorsMessages: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.message = "error" <NEW_LINE> self.invalid_post = "json post invalid according to the contract" <NEW_LINE> self.integrity_error = "Fields doesn't corresponds to database" <NEW_LINE> self.json_keys = "The json post's keys are invalid according the contract" <NEW_LINE> self.json_types = "The json post value's types are invalid according the contract" <NEW_LINE> <DEDENT> def not_found(self, name): <NEW_LINE> <INDENT> return "{} not found".format(name)
|
Error messages control
|
6259902aec188e330fdf985e
|
class CatmxvcloamloopbkstatusEnum(Enum): <NEW_LINE> <INDENT> disabled = 1 <NEW_LINE> sent = 2 <NEW_LINE> received = 3 <NEW_LINE> failed = 4 <NEW_LINE> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xe._meta import _ATM_MIB as meta <NEW_LINE> return meta._meta_table['AtmMib.Atmvcltable.Atmvclentry.CatmxvcloamloopbkstatusEnum']
|
CatmxvcloamloopbkstatusEnum
Indicates OAM loopback status of the VC.
disabled(1) \-\- No OAMs on this VC.
sent(2) \-\- OAM sent, waiting for echo.
received(3) \-\- OAM received from target.
failed(4) \-\- Last OAM did not return.
.. data:: disabled = 1
.. data:: sent = 2
.. data:: received = 3
.. data:: failed = 4
|
6259902a925a0f43d25e9013
|
class Append(Set): <NEW_LINE> <INDENT> def expression(self, token: Any): <NEW_LINE> <INDENT> if self.if_not_exists: <NEW_LINE> <INDENT> return f"{ref(token)} = if_not_exists({ref(token)}b, list_append({ref(token)}, {val(token)}))" <NEW_LINE> <DEDENT> return f"{ref(token)} = list_append({ref(token)}, {val(token)})"
|
Adds items to the end of a list
|
6259902a507cdc57c63a5d74
|
class Deploy(models.Model): <NEW_LINE> <INDENT> project = models.ForeignKey(verbose_name='项目', to='Project') <NEW_LINE> version = models.CharField(verbose_name='版本', max_length=32) <NEW_LINE> uid = models.CharField(verbose_name='上线文件包名称', max_length=32, null=True, blank=True) <NEW_LINE> status_choice = ( (1, '未获取'), (2, '待发布'), (3, '已发布'), (4, '已回滚'), ) <NEW_LINE> status = models.IntegerField(verbose_name='状态', choices=status_choice, default=1) <NEW_LINE> script = models.ForeignKey(verbose_name='script', to='Script', null=True, blank=True)
|
部署任务表
例如:
1 0.11
2 1.10
1 0.12
|
6259902a66673b3332c313bc
|
class BasicDisplayWidget(QWidget): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.display_image = None <NEW_LINE> self.display_width = 0 <NEW_LINE> self.display_height = 0 <NEW_LINE> return <NEW_LINE> <DEDENT> def paintEvent(self, e): <NEW_LINE> <INDENT> painter = QPainter(self) <NEW_LINE> if self.display_image is None: <NEW_LINE> <INDENT> painter.setPen(Qt.black) <NEW_LINE> painter.setFont(QFont("Arial", 30)) <NEW_LINE> painter.drawText(e.rect(), Qt.AlignCenter, "Identity Finder") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> window_rect = self.rect() <NEW_LINE> image_rect = QRect(0, 0, self.display_width, self.display_height) <NEW_LINE> ratio_of_image = image_rect.width() / image_rect.height() <NEW_LINE> ratio_of_window = window_rect.width() / window_rect.height() <NEW_LINE> if ratio_of_image > ratio_of_window: <NEW_LINE> <INDENT> window_rect.setHeight(window_rect.width()/ratio_of_image) <NEW_LINE> delta = (self.rect().height()-window_rect.height())*0.5 <NEW_LINE> window_rect.setY(delta) <NEW_LINE> window_rect.setHeight(window_rect.height()+delta) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> window_rect.setWidth(window_rect.height()*ratio_of_image) <NEW_LINE> delta = (self.rect().width()-window_rect.width())*0.5 <NEW_LINE> window_rect.setX(delta) <NEW_LINE> window_rect.setWidth(window_rect.width()+delta) <NEW_LINE> <DEDENT> painter.drawImage(window_rect, self.display_image, image_rect) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def setDisplayCvImage(self, img_cv): <NEW_LINE> <INDENT> if img_cv is None: <NEW_LINE> <INDENT> self.display_image = None <NEW_LINE> return <NEW_LINE> <DEDENT> self.setDisplayQImage(apw_comm.img_cv2qt(img_cv)) <NEW_LINE> return <NEW_LINE> <DEDENT> def setDisplayQImage(self, img_qt): <NEW_LINE> <INDENT> if img_qt is None: <NEW_LINE> <INDENT> self.display_image = None <NEW_LINE> return <NEW_LINE> <DEDENT> self.display_image = img_qt <NEW_LINE> self.display_width = img_qt.width() <NEW_LINE> self.display_height = img_qt.height() <NEW_LINE> self.update() <NEW_LINE> return
|
用于显示图像的 Widget 控件
|
6259902abf627c535bcb2484
|
class Eagle(object): <NEW_LINE> <INDENT> def __init__(self, user, password, ipaddress): <NEW_LINE> <INDENT> self._user = user <NEW_LINE> self._password = password <NEW_LINE> self._ipaddress = ipaddress <NEW_LINE> self._base_url = "http://{ip}/cgi-bin/cgi_manager".format(ip=ipaddress) <NEW_LINE> <DEDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return object.__getattribute__(self, name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return partial(self._execute_command, command=name) <NEW_LINE> <DEDENT> <DEDENT> def _execute_command(self, command, **options): <NEW_LINE> <INDENT> xml_command = self._build_command(command, **options) <NEW_LINE> response = self._send_request(xml_command) <NEW_LINE> data = self._parse_response(response.text, command) <NEW_LINE> return data <NEW_LINE> <DEDENT> def _build_command(self, command_name, **options): <NEW_LINE> <INDENT> command = ET.Element('Command') <NEW_LINE> options.update({"Name":command_name}) <NEW_LINE> for key, value in options.iteritems(): <NEW_LINE> <INDENT> option = ET.SubElement(command, key) <NEW_LINE> option.text = value <NEW_LINE> <DEDENT> return ET.tostring(command) <NEW_LINE> <DEDENT> def _send_request(self, xml_command): <NEW_LINE> <INDENT> print(xml_command) <NEW_LINE> response = requests.post(self._base_url, auth=(self._user, self._password), data=xml_command) <NEW_LINE> return response <NEW_LINE> <DEDENT> def _parse_response(self, response_data, command): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> raw_data = json.loads(response_data) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> msg = "invalid query parameters for '%s'. (Probably you are " + "missing a parameter like 'MacId')." <NEW_LINE> msg = msg % command <NEW_LINE> raise EagleException(msg) <NEW_LINE> <DEDENT> parsed_data = defaultdict(list) <NEW_LINE> keys_to_sort = set() <NEW_LINE> for key, value in raw_data.iteritems(): <NEW_LINE> <INDENT> if "[" in key: <NEW_LINE> <INDENT> real_key, index = key.split("[") <NEW_LINE> index = int(index.replace("]", "")) <NEW_LINE> parsed_data[real_key].append([index, value]) <NEW_LINE> keys_to_sort.add(real_key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parsed_data[key] = value <NEW_LINE> <DEDENT> <DEDENT> for key in keys_to_sort: <NEW_LINE> <INDENT> sorted_values = sorted(parsed_data[key], key=lambda x: x[0]) <NEW_LINE> sorted_values = [sv[1] for sv in sorted_values] <NEW_LINE> parsed_data[key] = sorted_values <NEW_LINE> <DEDENT> Response = namedtuple("Response", parsed_data.keys()) <NEW_LINE> data = Response(**parsed_data) <NEW_LINE> return data
|
as per: http://rainforestautomation.com/wp-content/uploads/2015/07/EAGLE_REST_API-1.1.pdf
|
6259902a26238365f5fadb1f
|
class EventListener(EventListenerBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(EventListener, self).__init__() <NEW_LINE> self._listener_thread = None <NEW_LINE> <DEDENT> def listen(self, ip_address): <NEW_LINE> <INDENT> address = (ip_address, self.requested_port_number) <NEW_LINE> self._listener_thread = EventServerThread(address) <NEW_LINE> self._listener_thread.daemon = True <NEW_LINE> self._listener_thread.start() <NEW_LINE> return self.requested_port_number <NEW_LINE> <DEDENT> def stop_listening(self, address): <NEW_LINE> <INDENT> self._listener_thread.stop() <NEW_LINE> try: <NEW_LINE> <INDENT> urlopen( 'http://%s:%s/' % (address[0], address[1])) <NEW_LINE> <DEDENT> except URLError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._listener_thread.join(1) <NEW_LINE> if self._listener_thread.isAlive(): <NEW_LINE> <INDENT> log.warning('Event Listener did not shutdown gracefully.')
|
The Event Listener.
Runs an http server in a thread which is an endpoint for ``NOTIFY``
requests from Sonos devices. Inherits from
`soco.events_base.EventListenerBase`.
|
6259902a1d351010ab8f4ae4
|
class ImportWizardView(SessionWizardView): <NEW_LINE> <INDENT> form_list = [('basics', ProjectBasicsForm), ('extra', ProjectExtraForm), ('advanced', ProjectAdvancedForm)] <NEW_LINE> condition_dict = {'extra': lambda self: self.is_advanced(), 'advanced': lambda self: self.is_advanced()} <NEW_LINE> def get_form_kwargs(self, step): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> kwargs['user'] = self.request.user <NEW_LINE> if step == 'basics': <NEW_LINE> <INDENT> kwargs['show_advanced'] = True <NEW_LINE> <DEDENT> if step == 'extra': <NEW_LINE> <INDENT> extra_form = self.get_form_from_step('basics') <NEW_LINE> project = extra_form.save(commit=False) <NEW_LINE> kwargs['instance'] = project <NEW_LINE> <DEDENT> if step == 'advanced': <NEW_LINE> <INDENT> adv_form = self.get_form_from_step('extra') <NEW_LINE> project = adv_form.save(commit=False) <NEW_LINE> kwargs['instance'] = project <NEW_LINE> <DEDENT> return kwargs <NEW_LINE> <DEDENT> def get_form_from_step(self, step): <NEW_LINE> <INDENT> form = self.form_list[step]( data=self.get_cleaned_data_for_step(step), **self.get_form_kwargs(step) ) <NEW_LINE> form.full_clean() <NEW_LINE> return form <NEW_LINE> <DEDENT> def get_template_names(self): <NEW_LINE> <INDENT> return 'projects/import_{0}.html'.format(self.steps.current, 'base') <NEW_LINE> <DEDENT> def done(self, form_list, **kwargs): <NEW_LINE> <INDENT> basics_form = form_list[0] <NEW_LINE> project = basics_form.save() <NEW_LINE> for form in form_list[1:]: <NEW_LINE> <INDENT> for (field, value) in form.cleaned_data.items(): <NEW_LINE> <INDENT> setattr(project, field, value) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> basic_only = True <NEW_LINE> <DEDENT> project.save() <NEW_LINE> project_import.send(sender=project, request=self.request) <NEW_LINE> trigger_build(project, basic=basic_only) <NEW_LINE> return HttpResponseRedirect(reverse('projects_detail', args=[project.slug])) <NEW_LINE> <DEDENT> def is_advanced(self): <NEW_LINE> <INDENT> data = self.get_cleaned_data_for_step('basics') or {} <NEW_LINE> return data.get('advanced', True)
|
Project import wizard
|
6259902ad10714528d69ee73
|
class SimpleOperationalTxSpec(BaseOperationalTxSpec): <NEW_LINE> <INDENT> def __init__(self, model, asset): <NEW_LINE> <INDENT> super(SimpleOperationalTxSpec, self).__init__() <NEW_LINE> self.model = model <NEW_LINE> self.targets = [] <NEW_LINE> self.asset = asset <NEW_LINE> <DEDENT> def add_target(self, color_target): <NEW_LINE> <INDENT> if not isinstance(color_target, ColorTarget): <NEW_LINE> <INDENT> raise InvalidTargetError("Target is not an instance of ColorTarget") <NEW_LINE> <DEDENT> self.targets.append(color_target) <NEW_LINE> <DEDENT> def get_targets(self): <NEW_LINE> <INDENT> return self.targets <NEW_LINE> <DEDENT> def get_change_addr(self, color_def): <NEW_LINE> <INDENT> color_id = color_def.color_id <NEW_LINE> wam = self.model.get_address_manager() <NEW_LINE> color_set = None <NEW_LINE> if color_def == UNCOLORED_MARKER: <NEW_LINE> <INDENT> color_set = ColorSet.from_color_ids(self.model.get_color_map(), [0]) <NEW_LINE> <DEDENT> elif self.asset.get_color_set().has_color_id(color_id): <NEW_LINE> <INDENT> color_set = self.asset.get_color_set() <NEW_LINE> <DEDENT> if color_set is None: <NEW_LINE> <INDENT> raise InvalidColorIdError('wrong color id') <NEW_LINE> <DEDENT> aw = wam.get_change_address(color_set) <NEW_LINE> return aw.get_address() <NEW_LINE> <DEDENT> def select_coins(self, colorvalue, use_fee_estimator=None): <NEW_LINE> <INDENT> self._validate_select_coins_parameters(colorvalue, use_fee_estimator) <NEW_LINE> def required_sum_fn(selection): <NEW_LINE> <INDENT> if use_fee_estimator: <NEW_LINE> <INDENT> return colorvalue + use_fee_estimator.estimate_required_fee( extra_txins=len(selection)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return colorvalue <NEW_LINE> <DEDENT> <DEDENT> required_sum_0 = required_sum_fn([]) <NEW_LINE> if required_sum_0.get_value() == 0: <NEW_LINE> <INDENT> return [], required_sum_0 <NEW_LINE> <DEDENT> colordef = colorvalue.get_colordef() <NEW_LINE> color_id = colordef.get_color_id() <NEW_LINE> cq = self.model.make_coin_query({"color_id_set": set([color_id])}) <NEW_LINE> utxo_list = cq.get_result() <NEW_LINE> return self._select_enough_coins(colordef, utxo_list, required_sum_fn)
|
Subclass of OperationalTxSpec which uses wallet model.
Represents a transaction that's ready to be composed
and then signed. The parent is an abstract class.
|
6259902a63f4b57ef0086559
|
class RestResponse(TypedDict): <NEW_LINE> <INDENT> json: dict <NEW_LINE> status_code: int
|
Used to define the dict types in a strict way.
|
6259902ad164cc6175821f46
|
class Aspect: <NEW_LINE> <INDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> method = super().__getattribute__(name) <NEW_LINE> if name[:2] == '__': <NEW_LINE> <INDENT> return method <NEW_LINE> <DEDENT> if not isinstance(method, Callable): <NEW_LINE> <INDENT> return method <NEW_LINE> <DEDENT> if isinstance(method, JoinPoint): <NEW_LINE> <INDENT> return method <NEW_LINE> <DEDENT> info = ObjectInfo(self) <NEW_LINE> joinpoint = JoinPoint( aspect=info.name, module=info.module_name, path=info.module_path, method=name, ) <NEW_LINE> joinpoint._method = method <NEW_LINE> setattr(self, name, joinpoint) <NEW_LINE> return joinpoint
|
Patcher for classes.
Place it as first parent for new class for patching.
|
6259902aa8ecb033258721eb
|
class AddSubmodule(standard.Dialog): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> super(AddSubmodule, self).__init__(parent=parent) <NEW_LINE> hint = N_('git://git.example.com/repo.git') <NEW_LINE> tooltip = N_('Submodule URL (can be relative, ex: ../repo.git)') <NEW_LINE> self.url_text = text.HintedDefaultLineEdit(hint, tooltip=tooltip, parent=self) <NEW_LINE> hint = N_('path/to/submodule') <NEW_LINE> tooltip = N_('Submodule path within the current repository (optional)') <NEW_LINE> self.path_text = text.HintedDefaultLineEdit(hint, tooltip=tooltip, parent=self) <NEW_LINE> hint = N_('Branch name') <NEW_LINE> tooltip = N_('Submodule branch to track (optional)') <NEW_LINE> self.branch_text = text.HintedDefaultLineEdit( hint, tooltip=tooltip, parent=self ) <NEW_LINE> self.depth_spinbox = standard.SpinBox( mini=0, maxi=compat.maxint, value=0, parent=self ) <NEW_LINE> self.depth_spinbox.setToolTip( N_( 'Create a shallow clone with history truncated to the ' 'specified number of revisions. 0 performs a full clone.' ) ) <NEW_LINE> hint = N_('Reference URL') <NEW_LINE> tooltip = N_('Reference repository to use when cloning (optional)') <NEW_LINE> self.reference_text = text.HintedDefaultLineEdit( hint, tooltip=tooltip, parent=self ) <NEW_LINE> self.add_button = qtutils.ok_button(N_('Add Submodule'), enabled=False) <NEW_LINE> self.close_button = qtutils.close_button() <NEW_LINE> self.form_layout = qtutils.form( defs.no_margin, defs.button_spacing, (N_('URL'), self.url_text), (N_('Path'), self.path_text), (N_('Branch'), self.branch_text), (N_('Depth'), self.depth_spinbox), (N_('Reference Repository'), self.reference_text), ) <NEW_LINE> self.button_layout = qtutils.hbox( defs.no_margin, defs.button_spacing, qtutils.STRETCH, self.add_button, self.close_button, ) <NEW_LINE> self.main_layout = qtutils.vbox( defs.large_margin, defs.spacing, self.form_layout, self.button_layout ) <NEW_LINE> self.setLayout(self.main_layout) <NEW_LINE> self.init_size(parent=qtutils.active_window()) <NEW_LINE> self.url_text.textChanged.connect(lambda x: self._update_widgets()) <NEW_LINE> qtutils.connect_button(self.add_button, self.accept) <NEW_LINE> qtutils.connect_button(self.close_button, self.close) <NEW_LINE> <DEDENT> def _update_widgets(self): <NEW_LINE> <INDENT> value = self.url_text.value() <NEW_LINE> self.add_button.setEnabled(bool(value)) <NEW_LINE> <DEDENT> def get(self, context): <NEW_LINE> <INDENT> return cmds.SubmoduleAdd( context, self.url_text.value(), self.path_text.value(), self.branch_text.value(), self.depth_spinbox.value(), self.reference_text.value(), )
|
Add a new submodule
|
6259902a30c21e258be997da
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.