code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class GDevelopInContainer(ContainerTests, test_games.GDevelopTests): <NEW_LINE> <INDENT> TIMEOUT_START = 20 <NEW_LINE> TIMEOUT_STOP = 10 <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.hosts = {443: ["api.github.com", "github.com"]} <NEW_LINE> self.apt_repo_override_path = os.path.join(self.APT_FAKE_REPO_PATH, 'unity3d') <NEW_LINE> super().setUp() <NEW_LINE> self.installed_path = os.path.join(self.install_base_path, "games", "gdevelop") <NEW_LINE> <DEDENT> def test_install_with_changed_download_page(self): <NEW_LINE> <INDENT> download_page_file_path = os.path.join(get_data_dir(), "server-content", "api.github.com", "repos", "4ian", "GD", "releases", "latest") <NEW_LINE> umake_command = self.command('{} games gdevelop'.format(UMAKE)) <NEW_LINE> self.bad_download_page_test(self.command(self.command_args), download_page_file_path) <NEW_LINE> self.assertFalse(self.launcher_exists_and_is_pinned(self.desktop_filename)) <NEW_LINE> self.assertFalse(self.is_in_path(self.exec_link))
This will test GDevelop inside a container
62599078627d3e7fe0e08836
class BaseXListener(threading.Thread): <NEW_LINE> <INDENT> volume_modifier = None <NEW_LINE> display = None <NEW_LINE> volume = None <NEW_LINE> def __init__(self, notification): <NEW_LINE> <INDENT> super(BaseXListener, self).__init__() <NEW_LINE> self.volume_modifier = VolumeModifierThread(notification) <NEW_LINE> self.volume = notification <NEW_LINE> self.display = display.Display() <NEW_LINE> r = self.display.record_get_version(0, 0) <NEW_LINE> print("RECORD extension version {}.{}".format(r.major_version, r.minor_version)) <NEW_LINE> <DEDENT> def listen(self, device_events=(0, 0)): <NEW_LINE> <INDENT> ctx = self.display.record_create_context( 0, [record.AllClients], [{ 'core_requests': (0, 0), 'core_replies': (0, 0), 'ext_requests': (0, 0, 0, 0), 'ext_replies': (0, 0, 0, 0), 'delivered_events': (0, 0), 'device_events': device_events, 'errors': (0, 0), 'client_started': False, 'client_died': False, }]) <NEW_LINE> self.display.record_enable_context(ctx, self.callback) <NEW_LINE> self.display.record_free_context(ctx) <NEW_LINE> <DEDENT> def callback(self, reply): <NEW_LINE> <INDENT> if reply.category != record.FromServer: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if reply.client_swapped: <NEW_LINE> <INDENT> print("* received swapped protocol data, cowardly ignored") <NEW_LINE> return <NEW_LINE> <DEDENT> if not len(reply.data) or ord(reply.data[0]) < 2: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> data = reply.data <NEW_LINE> while len(data): <NEW_LINE> <INDENT> event, data = rq.EventField(None).parse_binary_value( data, self.display.display, None, None) <NEW_LINE> self.processEvent(event) <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self.volume_modifier.is_alive(): <NEW_LINE> <INDENT> self.volume_modifier.stop()
A generic thread to listen to X events. `processEvent(event)` needs to be overridden by subclases
62599078bf627c535bcb2e7d
class TestConnector(object): <NEW_LINE> <INDENT> @pytest.fixture <NEW_LINE> def connection_params(self) -> dict: <NEW_LINE> <INDENT> return { "host": "localhost", "port": 5672, "vhost": "/", "user": "guest", "passwd": "guest", } <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def connector(self, connection_params: dict) -> Connector: <NEW_LINE> <INDENT> return Connector(**connection_params) <NEW_LINE> <DEDENT> @patch("amqpeek.monitor.BlockingConnection") <NEW_LINE> @patch("amqpeek.monitor.ConnectionParameters") <NEW_LINE> @patch("amqpeek.monitor.PlainCredentials") <NEW_LINE> def test_connection_created( self, plain_credentials: MagicMock, connection_params_mock: MagicMock, blocking_connection_mock: MagicMock, connector: Connector, connection_params: dict, ) -> None: <NEW_LINE> <INDENT> credentials_instance_mock = Mock() <NEW_LINE> plain_credentials.return_value = credentials_instance_mock <NEW_LINE> connection_params_instance_mock = Mock() <NEW_LINE> connection_params_mock.return_value = connection_params_instance_mock <NEW_LINE> connector.connect() <NEW_LINE> plain_credentials.assert_called_once_with( username=connection_params["user"], password=connection_params["passwd"] ) <NEW_LINE> connection_params_mock.assert_called_once_with( host=connection_params["host"], port=connection_params["port"], virtual_host=connection_params["vhost"], credentials=credentials_instance_mock, ) <NEW_LINE> blocking_connection_mock.assert_called_once_with( parameters=connection_params_instance_mock )
Tests for the Connector class.
625990783317a56b869bf21d
class IAdminResource(IResource): <NEW_LINE> <INDENT> pass
A marker interface for a web based administrative resource.
625990787d43ff24874280ec
class CalendarEvent: <NEW_LINE> <INDENT> def __init__(self, kwargs): <NEW_LINE> <INDENT> self.event_data = kwargs <NEW_LINE> <DEDENT> def __turn_to_string__(self): <NEW_LINE> <INDENT> self.event_text = "BEGIN:VEVENT\n" <NEW_LINE> for item, data in self.event_data.items(): <NEW_LINE> <INDENT> item = str(item).replace("_", "-") <NEW_LINE> if item not in ["ORGANIZER", "DTSTART", "DTEND", "ATTENDEE"]: <NEW_LINE> <INDENT> self.event_text += "%s:%s\n" % (item, data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.event_text += "%s;%s\n" % (item, data) <NEW_LINE> <DEDENT> <DEDENT> self.event_text += "END:VEVENT\n" <NEW_LINE> return self.event_text
事件对象
62599078283ffb24f3cf5251
class BaseCliStub(object): <NEW_LINE> <INDENT> def __init__(self, available_pkgs=(), available_groups=()): <NEW_LINE> <INDENT> self._available_pkgs = set(available_pkgs) <NEW_LINE> self._available_groups = set(available_groups) <NEW_LINE> self.installed_groups = set() <NEW_LINE> self.installed_pkgs = set() <NEW_LINE> self.repos = dnf.repodict.RepoDict() <NEW_LINE> <DEDENT> def install_grouplist(self, names): <NEW_LINE> <INDENT> to_install = (set(names) & self._available_groups) - self.installed_groups <NEW_LINE> if not to_install: <NEW_LINE> <INDENT> raise dnf.exceptions.Error('nothing to do') <NEW_LINE> <DEDENT> self.installed_groups.update(to_install) <NEW_LINE> <DEDENT> def install(self, pattern): <NEW_LINE> <INDENT> if pattern not in self._available_pkgs or pattern in self.installed_pkgs: <NEW_LINE> <INDENT> raise dnf.exceptions.MarkingError('no package matched') <NEW_LINE> <DEDENT> self.installed_pkgs.add(pattern) <NEW_LINE> <DEDENT> def read_all_repos(self): <NEW_LINE> <INDENT> self.repos.add(RepoStub('main')) <NEW_LINE> <DEDENT> def read_comps(self): <NEW_LINE> <INDENT> if not self._available_groups: <NEW_LINE> <INDENT> raise dnf.exceptions.CompsError('no group available')
A class mocking `dnf.cli.cli.BaseCli`.
625990783539df3088ecdc47
class GSettingsChangeMerger(BaseChangeMerger): <NEW_LINE> <INDENT> pass
GSettings change merger class
625990784428ac0f6e659edf
class DescribeSubnetsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SubnetIds = None <NEW_LINE> self.Filters = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.SubnetIds = params.get("SubnetIds") <NEW_LINE> if params.get("Filters") is not None: <NEW_LINE> <INDENT> self.Filters = [] <NEW_LINE> for item in params.get("Filters"): <NEW_LINE> <INDENT> obj = Filter() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Filters.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit")
DescribeSubnets request structure.
625990789c8ee82313040e5f
class DBHelper(object): <NEW_LINE> <INDENT> __dbAlia = 'db2 catalog db %s as %s at node %s' <NEW_LINE> __dbNode = 'db2 catalog tcpip node %s remote %s server %s remote_instance %s' <NEW_LINE> __conn2Db = 'db2 connect to %s user %s using %s' <NEW_LINE> __isNodeExist = 'db2 list node directory | grep -i %s' <NEW_LINE> __isAliaExist = 'db2 list database directory | grep -i %s' <NEW_LINE> __uncataDBAlia = 'db2 uncatalog db %s' <NEW_LINE> __uncataNode = 'db2 uncatalog node %s' <NEW_LINE> __connOuterSpaceDb = 'db2 connect to %s user %s using %s' <NEW_LINE> __properDict = ContextInitiator().getProperDict() <NEW_LINE> __sqlFloder = ContextInitiator().getWorkingPath() + "/../sqls/" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(DBHelper, self).__init__() <NEW_LINE> <DEDENT> def getOuterSpaceDbCmd(self, replacements): <NEW_LINE> <INDENT> return self.__connOuterSpaceDb % replacements <NEW_LINE> <DEDENT> def getDbAliaCmd(self, replacements): <NEW_LINE> <INDENT> return self.__dbAlia % replacements <NEW_LINE> <DEDENT> def getDbNodeCmd(self, replacements): <NEW_LINE> <INDENT> return self.__dbNode % replacements <NEW_LINE> <DEDENT> def getConn2DbCmd(self, replacements): <NEW_LINE> <INDENT> return self.__conn2Db % replacements <NEW_LINE> <DEDENT> def isNodeExistCmd(self, replacements): <NEW_LINE> <INDENT> return self.__isNodeExist % replacements <NEW_LINE> <DEDENT> def isAliaExistCmd(self, replacements): <NEW_LINE> <INDENT> return self.__isAliaExist % replacements <NEW_LINE> <DEDENT> def getUncataDBAliaCmd(self, replacements): <NEW_LINE> <INDENT> return self.__uncataDBAlia % replacements <NEW_LINE> <DEDENT> def getUncataNode(self, replacements): <NEW_LINE> <INDENT> return self.__uncataNode % replacements <NEW_LINE> <DEDENT> def dbExecCommand(self, sqlFile, logsPath='', logName=''): <NEW_LINE> <INDENT> sqlPath = self.__sqlFloder <NEW_LINE> var = "db2 -tvf " + sqlPath + "tmp_" + sqlFile <NEW_LINE> if logsPath.strip() and logName.strip(): <NEW_LINE> <INDENT> var = var + " > " + logsPath + logName <NEW_LINE> <DEDENT> return var <NEW_LINE> <DEDENT> def sql2TmpSql(self, sourceSql, sedDiect): <NEW_LINE> <INDENT> sqlPath = self.__sqlFloder <NEW_LINE> command = "cat " + sqlPath + sourceSql <NEW_LINE> for ele in sedDiect: <NEW_LINE> <INDENT> command = command + " | sed 's/${" + ele + "}/" + sedDiect[ele] + "/g'" <NEW_LINE> <DEDENT> command = command + "> " + sqlPath + "tmp_" + sourceSql <NEW_LINE> subprocess.call(command, shell=True)
docstring for IBMdbHelper
6259907856ac1b37e63039ba
class CommonClient: <NEW_LINE> <INDENT> def __init__(self,server,port=5222,debug=['always', 'nodebuilder']): <NEW_LINE> <INDENT> if self.__class__.__name__=='Client': self.Namespace,self.DBG='jabber:client',DBG_CLIENT <NEW_LINE> elif self.__class__.__name__=='Component': self.Namespace,self.DBG=dispatcher.NS_COMPONENT_ACCEPT,DBG_COMPONENT <NEW_LINE> self.defaultNamespace=self.Namespace <NEW_LINE> self.disconnect_handlers=[] <NEW_LINE> self.Server=server <NEW_LINE> self.Port=port <NEW_LINE> if debug and type(debug)!=list: debug=['always', 'nodebuilder'] <NEW_LINE> self._DEBUG=Debug.Debug(debug) <NEW_LINE> self.DEBUG=self._DEBUG.Show <NEW_LINE> self.debug_flags=self._DEBUG.debug_flags <NEW_LINE> self.debug_flags.append(self.DBG) <NEW_LINE> self._owner=self <NEW_LINE> self._registered_name=None <NEW_LINE> self.RegisterDisconnectHandler(self.DisconnectHandler) <NEW_LINE> self.connected='' <NEW_LINE> <DEDENT> def RegisterDisconnectHandler(self,handler): <NEW_LINE> <INDENT> self.disconnect_handlers.append(handler) <NEW_LINE> <DEDENT> def UnregisterDisconnectHandler(self,handler): <NEW_LINE> <INDENT> self.disconnect_handlers.remove(handler) <NEW_LINE> <DEDENT> def disconnected(self): <NEW_LINE> <INDENT> self.connected='' <NEW_LINE> self.DEBUG(self.DBG,'Disconnect detected','stop') <NEW_LINE> self.disconnect_handlers.reverse() <NEW_LINE> for i in self.disconnect_handlers: i() <NEW_LINE> self.disconnect_handlers.reverse() <NEW_LINE> if 'TLS' in self.__dict__: self.TLS.PlugOut() <NEW_LINE> <DEDENT> def DisconnectHandler(self): <NEW_LINE> <INDENT> raise IOError('Disconnected from server.') <NEW_LINE> <DEDENT> def event(self,eventName,args={}): <NEW_LINE> <INDENT> print("Event: ",(eventName,args)) <NEW_LINE> <DEDENT> def isConnected(self): <NEW_LINE> <INDENT> return self.connected <NEW_LINE> <DEDENT> def reconnectAndReauth(self): <NEW_LINE> <INDENT> handlerssave=self.Dispatcher.dumpHandlers() <NEW_LINE> self.Dispatcher.PlugOut() <NEW_LINE> if not self.connect(server=self._Server,proxy=self._Proxy): return <NEW_LINE> if not self.auth(self._User,self._Password,self._Resource): return <NEW_LINE> self.Dispatcher.restoreHandlers(handlerssave) <NEW_LINE> return self.connected <NEW_LINE> <DEDENT> def connect(self,server=None,proxy=None): <NEW_LINE> <INDENT> if not server: server=(self.Server,self.Port) <NEW_LINE> if proxy: connected=transports.HTTPPROXYsocket(proxy,server).PlugIn(self) <NEW_LINE> else: connected=transports.TCPsocket(server).PlugIn(self) <NEW_LINE> if not connected: return <NEW_LINE> self._Server,self._Proxy=server,proxy <NEW_LINE> self.connected='tcp' <NEW_LINE> if self.Connection.getPort()==5223: <NEW_LINE> <INDENT> transports.TLS().PlugIn(self,now=1) <NEW_LINE> self.connected='tls' <NEW_LINE> <DEDENT> dispatcher.Dispatcher().PlugIn(self) <NEW_LINE> while self.Dispatcher.Stream._document_attrs is None: self.Process(1) <NEW_LINE> if 'version' in self.Dispatcher.Stream._document_attrs and self.Dispatcher.Stream._document_attrs['version']=='1.0': <NEW_LINE> <INDENT> while not self.Dispatcher.Stream.features and self.Process(): pass <NEW_LINE> <DEDENT> return self.connected
Base for Client and Component classes.
6259907863b5f9789fe86b16
class GetInjectedWorkflows(DBFormatter): <NEW_LINE> <INDENT> sql = """SELECT DISTINCT name FROM wmbs_workflow WHERE injected = :injected""" <NEW_LINE> def execute(self, injected = False, conn = None, transaction = False): <NEW_LINE> <INDENT> if not injected: <NEW_LINE> <INDENT> binds = {'injected': 0} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> binds = {'injected': 1} <NEW_LINE> <DEDENT> result = self.dbi.processData(self.sql, binds, conn = conn, transaction = transaction) <NEW_LINE> dResult = self.formatDict(result) <NEW_LINE> finalResult = [] <NEW_LINE> for entry in dResult: <NEW_LINE> <INDENT> finalResult.append(entry['name']) <NEW_LINE> <DEDENT> return finalResult
Gets workflows that have been fully injected into WMBS
6259907876e4537e8c3f0f2f
class environment(object): <NEW_LINE> <INDENT> def __init__(self, launchSiteLat, launchSiteLon, launchSiteElev, dateAndTime, inflationTemperature=0.0, UTC_offset=0.0, debugging=False, load_on_init=False): <NEW_LINE> <INDENT> self.inflationTemperature = inflationTemperature <NEW_LINE> self.launchSiteLat = launchSiteLat <NEW_LINE> self.launchSiteLon = launchSiteLon <NEW_LINE> self.launchSiteElev = launchSiteElev <NEW_LINE> self.dateAndTime = dateAndTime <NEW_LINE> self.UTC_offset = UTC_offset <NEW_LINE> self.debugging = debugging <NEW_LINE> self._UTC_time = None <NEW_LINE> self.getMCWindDirection = [] <NEW_LINE> self.getMCWindSpeed = [] <NEW_LINE> self._weatherLoaded = False <NEW_LINE> if debugging: <NEW_LINE> <INDENT> log_lev = logging.DEBUG <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log_lev = logging.WARNING <NEW_LINE> <DEDENT> logger.setLevel(log_lev) <NEW_LINE> <DEDENT> def getTemperature(self, lat, lon, alt, time): <NEW_LINE> <INDENT> raise NotImplementedError( "getTemperature method must be implemented by class {}".format( type(self).__name__)) <NEW_LINE> <DEDENT> def getPressure(self, lat, lon, alt, time): <NEW_LINE> <INDENT> raise NotImplementedError( "getPressure method must be implemented by class {}".format( type(self).__name__)) <NEW_LINE> <DEDENT> def getDensity(self, lat, lon, alt, time): <NEW_LINE> <INDENT> raise NotImplementedError( "getDensity method must be implemented by class {}".format( type(self).__name__)) <NEW_LINE> <DEDENT> def getViscosity(self, lat, lon, alt, time): <NEW_LINE> <INDENT> raise NotImplementedError( "getViscosity method must be implemented by class {}".format( type(self).__name__)) <NEW_LINE> <DEDENT> def getWindSpeed(self, *args): <NEW_LINE> <INDENT> raise NotImplementedError( "getWindSpeed method must be implemented by class {}".format( type(self).__name__)) <NEW_LINE> <DEDENT> def getWindDirection(self, *args): <NEW_LINE> <INDENT> raise NotImplementedError( "getWindDirection method must be implemented by class {}".format( type(self).__name__))
Defines a common interface for the Simulator module. This is a meta class that should not be instantiated directly, and is provided mainly for code reuse and a uniform API for the simulator class, regardless of the environment data used. Parameters ---------- launchSiteLat : float latitude of the launch site [deg] launchSiteLon : float longitude of the launch site [deg] launchSiteElev : float elevation of the launch site above Mean Sea Level [m] dateAndTime : :obj:`datetime.datetime` Date and time of launch inflationTemperature : float the ambient temperature during the balloon inflation [degC] UTC_offset : float the offset in hours between the current time zone and UTC (for example, Florida in winter has a UTC_offset = -5) Attributes ---------- launchSiteLat : float latitude of the launch site [deg] launchSiteLon : float longitude of the launch site [deg] launchSiteElev : float elevation of the launch site above Mean Sea Level [m] dateAndTime : :obj:`datetime.datetime` Date and time of launch UTC_offset : float The offset in hours between the current time zone and UTC. NOTE: If zero, UTC offset is AUTOMATICALLY retrieved using the launch site GPS location Notes ----- The primary base class methods that should be overridden are the 'getter' functions for Temperature, Pressure, WindDirection, WindSpeed, Density, Viscosity See Also -------- astra.global_tools.getUTCOffset
62599078be7bc26dc9252b2d
class ZoneoutCell(ModifierCell): <NEW_LINE> <INDENT> def __init__(self, base_cell, zoneout_outputs=0., zoneout_states=0.): <NEW_LINE> <INDENT> assert not isinstance(base_cell, FusedRNNCell), "FusedRNNCell doesn't support zoneout. " "Please unfuse first." <NEW_LINE> assert not isinstance(base_cell, BidirectionalCell), "BidirectionalCell doesn't support zoneout since it doesn't support step. " "Please add ZoneoutCell to the cells underneath instead." <NEW_LINE> assert not isinstance(base_cell, SequentialRNNCell) or not base_cell._bidirectional, "Bidirectional SequentialRNNCell doesn't support zoneout. " "Please add ZoneoutCell to the cells underneath instead." <NEW_LINE> super(ZoneoutCell, self).__init__(base_cell) <NEW_LINE> self.zoneout_outputs = zoneout_outputs <NEW_LINE> self.zoneout_states = zoneout_states <NEW_LINE> self.prev_output = None <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> super(ZoneoutCell, self).reset() <NEW_LINE> self.prev_output = None <NEW_LINE> <DEDENT> def __call__(self, inputs, states): <NEW_LINE> <INDENT> cell, p_outputs, p_states = self.base_cell, self.zoneout_outputs, self.zoneout_states <NEW_LINE> next_output, next_states = cell(inputs, states) <NEW_LINE> mask = lambda p, like: symbol.Dropout(symbol.ones_like(like), p=p) <NEW_LINE> prev_output = self.prev_output if self.prev_output else symbol.zeros((0, 0)) <NEW_LINE> output = (symbol.where(mask(p_outputs, next_output), next_output, prev_output) if p_outputs != 0. else next_output) <NEW_LINE> states = ([symbol.where(mask(p_states, new_s), new_s, old_s) for new_s, old_s in zip(next_states, states)] if p_states != 0. else next_states) <NEW_LINE> self.prev_output = output <NEW_LINE> return output, states
Apply Zoneout on base cell. Parameters ---------- base_cell : BaseRNNCell Cell on whose states to perform zoneout. zoneout_outputs : float, default 0. Fraction of the output that gets dropped out during training time. zoneout_states : float, default 0. Fraction of the states that gets dropped out during training time.
6259907899fddb7c1ca63aae
class SIPPref: <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> pass
A hidden Window that automatically controls the Software Input Panel according to the control focused in the parent window. It should be instancied after all other controls in the parent window
625990788e7ae83300eeaa3c
class TestSignals(TestCase): <NEW_LINE> <INDENT> def test_thumbnails_are_generated_on_save(self): <NEW_LINE> <INDENT> product = models.Product( name="The Cathedral and the bazaar", price=Decimal("3.00") ) <NEW_LINE> product.save() <NEW_LINE> with open("main/fixtures/the-cathedral-the-bazaar.jpg", "rb") as fi: <NEW_LINE> <INDENT> image = models.ProductImage( product=product, image=ImageFile(fi, name="tctb.jpg") ) <NEW_LINE> with self.assertLogs("main", level="INFO") as cm: <NEW_LINE> <INDENT> image.save() <NEW_LINE> <DEDENT> <DEDENT> self.assertGreaterEqual(len(cm.output), 1) <NEW_LINE> image.refresh_from_db() <NEW_LINE> with open("main/fixtures/the-cathedral-the-bazaar.thumb.jpg", "rb") as fi: <NEW_LINE> <INDENT> expected_content = fi.read() <NEW_LINE> assert image.thumbnail.read() == expected_content <NEW_LINE> <DEDENT> image.thumbnail.delete(save=False) <NEW_LINE> image.image.delete(save=False)
Since I need to make sure everything is WORKING, I'll just using the examples from the book, I might change it later on.
6259907891f36d47f2231b67
class FileBrowseUploadField(CharField): <NEW_LINE> <INDENT> description = "FileBrowseUploadField" <NEW_LINE> __metaclass__ = models.SubfieldBase <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.site = kwargs.pop('site', site) <NEW_LINE> self.directory = kwargs.pop('directory', '') <NEW_LINE> self.extensions = kwargs.pop('extensions', '') <NEW_LINE> self.format = kwargs.pop('format', '') <NEW_LINE> self.upload_to = kwargs.pop('upload_to', '') <NEW_LINE> self.temp_upload_dir = kwargs.pop('temp_upload_dir', '') <NEW_LINE> return super(FileBrowseUploadField, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> if not value or isinstance(value, FileObject): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return FileObject(value, site=self.site) <NEW_LINE> <DEDENT> def get_db_prep_value(self, value, connection, prepared=False): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return value.path <NEW_LINE> <DEDENT> def value_to_string(self, obj): <NEW_LINE> <INDENT> value = self._get_val_from_obj(obj) <NEW_LINE> if not value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return value.path <NEW_LINE> <DEDENT> def formfield(self, **kwargs): <NEW_LINE> <INDENT> attrs = {} <NEW_LINE> attrs["site"] = self.site <NEW_LINE> attrs["directory"] = self.directory <NEW_LINE> attrs["extensions"] = self.extensions <NEW_LINE> attrs["format"] = self.format <NEW_LINE> attrs["upload_to"] = self.upload_to <NEW_LINE> attrs["temp_upload_dir"] = self.temp_upload_dir <NEW_LINE> defaults = { 'form_class': FileBrowseUploadFormField, 'widget': FileBrowseUploadWidget(attrs=attrs), 'site': self.site, 'directory': self.directory, 'extensions': self.extensions, 'format': self.format, 'upload_to': self.upload_to, 'temp_upload_dir': self.temp_upload_dir } <NEW_LINE> return super(FileBrowseUploadField, self).formfield(**defaults)
Model field which renders with an option to browse site.directory as well as upload a file to a temporary folder (you still need to somehow move that temporary file to an actual location when the model is being saved).
62599078baa26c4b54d50c62
class Key(object): <NEW_LINE> <INDENT> def __init__(self, obj, *args): <NEW_LINE> <INDENT> self.obj = obj <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> for field in sort_fields: <NEW_LINE> <INDENT> lhs, rhs = getattr(self.obj, field), getattr(other.obj, field) <NEW_LINE> if lhs == rhs: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> return rhs < lhs if field in descending else lhs < rhs <NEW_LINE> <DEDENT> return False
Complex sort order key
625990787cff6e4e811b73f0
class ModelSelector(object): <NEW_LINE> <INDENT> def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str, n_constant=3, min_n_components=2, max_n_components=10, random_state=14, verbose=False): <NEW_LINE> <INDENT> self.words = all_word_sequences <NEW_LINE> self.hwords = all_word_Xlengths <NEW_LINE> self.sequences = all_word_sequences[this_word] <NEW_LINE> self.X, self.lengths = all_word_Xlengths[this_word] <NEW_LINE> self.n_features = len(self.X[0]) <NEW_LINE> self.this_word = this_word <NEW_LINE> self.n_constant = n_constant <NEW_LINE> self.min_n_components = min_n_components <NEW_LINE> self.max_n_components = max_n_components <NEW_LINE> self.random_state = random_state <NEW_LINE> self.verbose = verbose <NEW_LINE> <DEDENT> def select(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def base_model(self, num_states): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> try: <NEW_LINE> <INDENT> hmm_model = GaussianHMM(n_components=num_states, covariance_type="diag", n_iter=1000, random_state=self.random_state, verbose=False).fit(self.X, self.lengths) <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> print("model created for {} with {} states".format(self.this_word, num_states)) <NEW_LINE> <DEDENT> return hmm_model <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print("failure on {} with {} states".format(self.this_word, num_states)) <NEW_LINE> <DEDENT> return None
base class for model selection (strategy design pattern)
625990785fdd1c0f98e5f92e
class Quotas(extensions.ExtensionDescriptor): <NEW_LINE> <INDENT> name = "Quotas" <NEW_LINE> alias = "os-quota-sets" <NEW_LINE> namespace = "http://docs.openstack.org/compute/ext/quotas-sets/api/v1.1" <NEW_LINE> updated = "2011-08-08T00:00:00+00:00" <NEW_LINE> def get_resources(self): <NEW_LINE> <INDENT> resources = [] <NEW_LINE> res = extensions.ResourceExtension('os-quota-sets', QuotaSetsController(self.ext_mgr), member_actions={'defaults': 'GET'}) <NEW_LINE> resources.append(res) <NEW_LINE> return resources
Quotas management support.
62599078442bda511e95da30
class image2d(recoBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(image2d, self).__init__() <NEW_LINE> self._productName = 'image2d' <NEW_LINE> self._product_id = 0 <NEW_LINE> larcv.load_pyutil() <NEW_LINE> <DEDENT> def drawObjects(self, view_manager, io_manager, meta): <NEW_LINE> <INDENT> image2d_data = io_manager.get_data(self._product_id, str(self._producerName)) <NEW_LINE> for image2d_plane in image2d_data.Image2DArray(): <NEW_LINE> <INDENT> thisView = view_manager.getViewPorts()[image2d_plane.meta().plane()] <NEW_LINE> image_as_ndarray = larcv.as_ndarray(image2d_plane) <NEW_LINE> thisView._item.setImage(image_as_ndarray) <NEW_LINE> <DEDENT> return
docstring for cluster
6259907816aa5153ce401e8b
class Component(): <NEW_LINE> <INDENT> _name = None <NEW_LINE> _age = None <NEW_LINE> def __init__(self, name, age): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._age = age <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def get_age(self): <NEW_LINE> <INDENT> return self._age
This class represents the component that will be decorated with new responsibilities
6259907801c39578d7f1440d
class Scraper(object): <NEW_LINE> <INDENT> NETWORK_NAME = None <NEW_LINE> def __init__(self, credentials): <NEW_LINE> <INDENT> if credentials.ad_network_name != self.NETWORK_NAME: <NEW_LINE> <INDENT> raise RuntimeError("Invalid credentials. Attempting to use %s" "credentials for an %s scraper" % (credentials.network, self.NETWORK_NAME)) <NEW_LINE> <DEDENT> self.username = credentials.username <NEW_LINE> self.password = credentials.password <NEW_LINE> <DEDENT> def get_site_stats(self, start_date): <NEW_LINE> <INDENT> raise NotImplementedError("Subclasses of Scraper must implement this " "method.")
Default Scraper abstract object. All scrapers implement this class and it's methods. They're all weird as fuck with roughly 0 things in common though...
6259907897e22403b383c8b3
class StreamEditor(object): <NEW_LINE> <INDENT> table = [] <NEW_LINE> def __init__(self, filename, options): <NEW_LINE> <INDENT> if not self.table: <NEW_LINE> <INDENT> raise NotImplementedError("StreamEditor.table") <NEW_LINE> <DEDENT> self.changes = 0 <NEW_LINE> self.verbose = options.verbose <NEW_LINE> self.dryrun = options.dryrun <NEW_LINE> self.filename = filename <NEW_LINE> with open(self.filename) as handle: <NEW_LINE> <INDENT> self.lines = [line.rstrip() for line in handle] <NEW_LINE> self.matches = list(reversed(self.match_engine())) <NEW_LINE> <DEDENT> <DEDENT> def transform(self): <NEW_LINE> <INDENT> for i, dict_matches in enumerate(self.matches): <NEW_LINE> <INDENT> self.apply_match(i, dict_matches) <NEW_LINE> <DEDENT> <DEDENT> def apply_match(self, i, dict_matches): <NEW_LINE> <INDENT> raise NotImplementedError("StreamEditor.apply_match") <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> if self.changes: <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> msg = "Saving {o.filename}: {o.changes} changes\n".format(o=self) <NEW_LINE> sys.stderr.write(msg) <NEW_LINE> <DEDENT> with open(self.filename, "w") as handle: <NEW_LINE> <INDENT> handle.write("\n".join(self.lines) + "\n") <NEW_LINE> <DEDENT> self.changes = 0 <NEW_LINE> <DEDENT> <DEDENT> def match_engine(self): <NEW_LINE> <INDENT> return match_engine(self.lines, self.table, self.verbose) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.save() <NEW_LINE> <DEDENT> def copy_range(self, loc): <NEW_LINE> <INDENT> start, end = loc <NEW_LINE> return self.lines[start:end] <NEW_LINE> <DEDENT> def replace_range(self, loc, new_lines): <NEW_LINE> <INDENT> self.lines = replace_range(self.lines, new_lines, loc) <NEW_LINE> self.changes += 1 <NEW_LINE> <DEDENT> def insert_range(self, loc, new_lines): <NEW_LINE> <INDENT> self.lines = insert_range(self.lines, new_lines, loc) <NEW_LINE> self.changes += 1 <NEW_LINE> <DEDENT> def append_range(self, loc, new_lines): <NEW_LINE> <INDENT> self.lines = append_range(self.lines, new_lines, loc) <NEW_LINE> self.changes += 1 <NEW_LINE> <DEDENT> def delete_range(self, loc): <NEW_LINE> <INDENT> self.lines = delete_range(self.lines, loc) <NEW_LINE> self.changes += 1 <NEW_LINE> <DEDENT> def entab(self): <NEW_LINE> <INDENT> self.lines = entab(self.lines) <NEW_LINE> self.changes += 1 <NEW_LINE> <DEDENT> def find_line(self, regex): <NEW_LINE> <INDENT> return find_line(self.lines, regex) <NEW_LINE> <DEDENT> def find_any_line(self, regexes): <NEW_LINE> <INDENT> return find_any_line(self.lines, regexes) <NEW_LINE> <DEDENT> def sort_range(self, loc): <NEW_LINE> <INDENT> self.lines = sort_range(self.lines, loc) <NEW_LINE> self.changes += 1
Abstract class for stream editing
6259907897e22403b383c8b2
class ImproperPrior(Prior): <NEW_LINE> <INDENT> def to_distribution( self, dtype: torch.dtype = torch.float32, device: torch.device = None ): <NEW_LINE> <INDENT> return Improper() <NEW_LINE> <DEDENT> def description(self): <NEW_LINE> <INDENT> return f"Improper(-∞, +∞)"
Improper uniform prior with support over the real line.
62599078bf627c535bcb2e7f
class DummyStrategy(Strategy): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def window_size(self): <NEW_LINE> <INDENT> return 5 <NEW_LINE> <DEDENT> def advice(self, data): <NEW_LINE> <INDENT> cond = np.ceil(np.sum(data)) % 3 <NEW_LINE> if cond == 1: <NEW_LINE> <INDENT> return self.LONG <NEW_LINE> <DEDENT> elif cond == 2: <NEW_LINE> <INDENT> return self.SHORT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.HOLD
Strategy that creates random advice, just to demo how to implement the interface.
6259907821bff66bcd72461a
class TasksTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.factory = RequestFactory() <NEW_LINE> self.user = User.objects.create(username="user2", password="user2", email="[email protected]") <NEW_LINE> self.repository = Repository.objects.create(author=self.user, repo_name="repo2", owner_name=self.user.username, type='L') <NEW_LINE> self.task = Task.objects.create(title="Task Ex", description="This is a example task", status='0%', user=self.user, repository=self.repository) <NEW_LINE> <DEDENT> """Creating new task test""" <NEW_LINE> def test_create_task(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(self.task, Task)) <NEW_LINE> self.assertEqual(self.task.description, "This is a example task") <NEW_LINE> self.assertEqual(self.task.title, "Task Ex") <NEW_LINE> self.assertEqual(self.task.status, "0%") <NEW_LINE> self.assertEqual(self.task.user.username, "user2") <NEW_LINE> <DEDENT> """View test""" <NEW_LINE> def test_tasks_view(self): <NEW_LINE> <INDENT> request = self.factory.get('/' + self.user.username + '/' + self.repository.repo_name + '/tasks') <NEW_LINE> request.user = self.user <NEW_LINE> response = task(request, self.user.username, 'repo2') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> """task form test""" <NEW_LINE> def test_task_form(self): <NEW_LINE> <INDENT> data = {'title': "Task one", 'description': "do this", 'status':'0%', 'user':self.user.id} <NEW_LINE> form = TaskForm(data=data) <NEW_LINE> self.assertTrue(form.is_valid()) <NEW_LINE> data = {'title': "", 'description': "Mr. Slave", 'status':'0%'} <NEW_LINE> form = WikiForm(data=data) <NEW_LINE> self.assertFalse(form.is_valid()) <NEW_LINE> <DEDENT> """User adding task test""" <NEW_LINE> def test_adding_task(self): <NEW_LINE> <INDENT> self.client.force_login(self.user) <NEW_LINE> url = '/' + self.user.username + '/' + self.repository.repo_name + '/tasks/' <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertQuerysetEqual(response.context['tasks'], ['<Task: Task object>']) <NEW_LINE> url = '/' + self.user.username + '/' + self.repository.repo_name + '/task-form/' <NEW_LINE> response = self.client.post(url, {'title': "Task", 'description': "Do this and that.", 'status': "0%", 'user':self.user.id}) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> url = '/' + self.user.username + '/' + self.repository.repo_name + '/tasks/' <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(len(response.context['tasks'].all()), 2) <NEW_LINE> self.client.logout()
Preparing data
62599078f548e778e596cf42
@script_interface_register <NEW_LINE> class EnergyCriterion(_PairCriterion): <NEW_LINE> <INDENT> _so_name = "PairCriteria::EnergyCriterion" <NEW_LINE> _so_creation_policy="LOCAL"
Pair criterion returning true, if the short range energy between the particles is >= the cutoff Be aware that the short range energy contains the short range part of dipolar and electrostatic interactions, but not the long range part. The following parameters can be passed to the constructor, changed via set_params() and retrieved via get_params() cut_off : float energy cut off for the criterion
6259907892d797404e389834
class TestUser(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.new_user = User('Rose','rudim3nt@l') <NEW_LINE> <DEDENT> def test__init__(self): <NEW_LINE> <INDENT> self.assertEqual(self.new_user.username,'Rose') <NEW_LINE> self.assertEqual(self.new_user.password,'rudim3nt@l') <NEW_LINE> <DEDENT> def test_save(self): <NEW_LINE> <INDENT> self.new_user.save_user() <NEW_LINE> self.assertEqual(len(User.users),1)
Test for user class
625990784428ac0f6e659ee1
class SAG13Universe(SimulatedUniverse): <NEW_LINE> <INDENT> def __init__(self, **specs): <NEW_LINE> <INDENT> SimulatedUniverse.__init__(self, **specs) <NEW_LINE> <DEDENT> def gen_physical_properties(self, **specs): <NEW_LINE> <INDENT> PPop = self.PlanetPopulation <NEW_LINE> PPMod = self.PlanetPhysicalModel <NEW_LINE> TL = self.TargetList <NEW_LINE> targetSystems = np.random.poisson(lam=PPop.eta, size=TL.nStars) <NEW_LINE> plan2star = [] <NEW_LINE> for j,n in enumerate(targetSystems): <NEW_LINE> <INDENT> plan2star = np.hstack((plan2star, [j]*n)) <NEW_LINE> <DEDENT> self.plan2star = plan2star.astype(int) <NEW_LINE> self.sInds = np.unique(self.plan2star) <NEW_LINE> self.nPlans = len(self.plan2star) <NEW_LINE> self.I, self.O, self.w = PPop.gen_angles(self.nPlans) <NEW_LINE> self.a, self.e, self.p, self.Rp = PPop.gen_plan_params(self.nPlans) <NEW_LINE> if PPop.scaleOrbits: <NEW_LINE> <INDENT> self.a *= np.sqrt(TL.L[self.plan2star]) <NEW_LINE> <DEDENT> self.gen_M0() <NEW_LINE> self.Mp = PPMod.calc_mass_from_radius(self.Rp)
Simulated Universe module based on SAG13 Planet Population module.
625990782c8b7c6e89bd519c
class Projector: <NEW_LINE> <INDENT> def __init__(self, parent, proj_exprs): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.input_exprs = proj_exprs <NEW_LINE> self.resolved_exprs = [parent._ensure_expr(e) for e in proj_exprs] <NEW_LINE> node = parent.op() <NEW_LINE> self.parent_roots = ( [node] if isinstance(node, ops.Selection) else node.root_tables() ) <NEW_LINE> self.clean_exprs = list(map(windowize_function, self.resolved_exprs)) <NEW_LINE> <DEDENT> def get_result(self): <NEW_LINE> <INDENT> roots = self.parent_roots <NEW_LINE> first_root = roots[0] <NEW_LINE> if len(roots) == 1 and isinstance(first_root, ops.Selection): <NEW_LINE> <INDENT> fused_op = self.try_fusion(first_root) <NEW_LINE> if fused_op is not None: <NEW_LINE> <INDENT> return fused_op <NEW_LINE> <DEDENT> <DEDENT> return ops.Selection(self.parent, self.clean_exprs) <NEW_LINE> <DEDENT> def try_fusion(self, root): <NEW_LINE> <INDENT> assert self.parent.op() == root <NEW_LINE> root_table = root.table <NEW_LINE> roots = root_table.op().root_tables() <NEW_LINE> validator = ExprValidator([root_table]) <NEW_LINE> fused_exprs = [] <NEW_LINE> can_fuse = False <NEW_LINE> clean_exprs = self.clean_exprs <NEW_LINE> if not isinstance(root_table.op(), ops.Join): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resolved = root_table._resolve(self.input_exprs) <NEW_LINE> <DEDENT> except (AttributeError, IbisTypeError): <NEW_LINE> <INDENT> resolved = clean_exprs <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> resolved = clean_exprs <NEW_LINE> <DEDENT> if not resolved: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> root_selections = root.selections <NEW_LINE> parent_op = self.parent.op() <NEW_LINE> for val in resolved: <NEW_LINE> <INDENT> lifted_val = substitute_parents(val, past_projection=False) <NEW_LINE> if isinstance(val, ir.TableExpr) and ( parent_op.compatible_with(val.op()) or len(roots) == 1 and val.op().root_tables()[0] is roots[0] ): <NEW_LINE> <INDENT> can_fuse = True <NEW_LINE> have_root = False <NEW_LINE> for root_sel in root_selections: <NEW_LINE> <INDENT> if root_sel.equals(root_table): <NEW_LINE> <INDENT> fused_exprs.append(root_table) <NEW_LINE> have_root = True <NEW_LINE> continue <NEW_LINE> <DEDENT> fused_exprs.append(root_sel) <NEW_LINE> <DEDENT> if not have_root and not root_selections: <NEW_LINE> <INDENT> fused_exprs = [root_table] + fused_exprs <NEW_LINE> <DEDENT> <DEDENT> elif validator.validate(lifted_val): <NEW_LINE> <INDENT> can_fuse = True <NEW_LINE> fused_exprs.append(lifted_val) <NEW_LINE> <DEDENT> elif not validator.validate(val): <NEW_LINE> <INDENT> can_fuse = False <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fused_exprs.append(val) <NEW_LINE> <DEDENT> <DEDENT> if can_fuse: <NEW_LINE> <INDENT> return ops.Selection( root_table, fused_exprs, predicates=root.predicates, sort_keys=root.sort_keys, ) <NEW_LINE> <DEDENT> return None
Analysis and validation of projection operation, taking advantage of "projection fusion" opportunities where they exist, i.e. combining compatible projections together rather than nesting them. Translation / evaluation later will not attempt to do any further fusion / simplification.
62599078167d2b6e312b826b
class DagHandlerProvider(DependencyProvider): <NEW_LINE> <INDENT> def get_dependency(self, worker_ctx: object) -> DagHandler: <NEW_LINE> <INDENT> return DagHandler()
DependencyProvider for the DagHandler object.
625990787c178a314d78e8c4
class ToolboxError(Exception): <NEW_LINE> <INDENT> __error_code = None <NEW_LINE> __details = None <NEW_LINE> def __init__(self, error_code, details=None): <NEW_LINE> <INDENT> super(ToolboxError, self).__init__() <NEW_LINE> self.__error_code = error_code <NEW_LINE> if details: <NEW_LINE> <INDENT> self.__details = details <NEW_LINE> <DEDENT> <DEDENT> def __get_message(self): <NEW_LINE> <INDENT> return ERROR_MESSAGES[self.__error_code] <NEW_LINE> <DEDENT> def __get_description(self): <NEW_LINE> <INDENT> if self.__details: <NEW_LINE> <INDENT> return self.__details <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__get_message() <NEW_LINE> <DEDENT> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return dict( error=self.__error_code, message=self.__get_message(), description=self.__get_description() ) <NEW_LINE> <DEDENT> def get_status(self): <NEW_LINE> <INDENT> return int(self.__error_code.split('-')[1]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{code}: {message}'.format( code=self.__error_code, message=self.__get_message() )
Basic class for Toolbox internal errors
62599078f9cc0f698b1c5fa5
class BamSetChecker(object): <NEW_LINE> <INDENT> def __init__(self) : <NEW_LINE> <INDENT> self.bamList=[] <NEW_LINE> self.bamLabels=[] <NEW_LINE> <DEDENT> def appendBams(self, inputBamList, inputLabel) : <NEW_LINE> <INDENT> if (inputBamList is None) or (len(inputBamList) == 0) : <NEW_LINE> <INDENT> raise OptParseException("No %s sample BAM/CRAM files specified" % (inputLabel)) <NEW_LINE> <DEDENT> for inputBamFile in inputBamList : <NEW_LINE> <INDENT> self.bamList.append(inputBamFile) <NEW_LINE> self.bamLabels.append(inputLabel) <NEW_LINE> <DEDENT> <DEDENT> def check(self, htsfileBin, referenceFasta) : <NEW_LINE> <INDENT> checkChromSet(htsfileBin, referenceFasta, self.bamList, self.bamLabels, isReferenceLocked=True) <NEW_LINE> bamSet=set() <NEW_LINE> for bamFile in self.bamList : <NEW_LINE> <INDENT> if bamFile in bamSet : <NEW_LINE> <INDENT> raise OptParseException("Repeated input BAM/CRAM file: %s" % (bamFile)) <NEW_LINE> <DEDENT> bamSet.add(bamFile)
check properties of the input bams as an aggregate set for instance, same chrom order, no repeated files, etc...
625990784f6381625f19a185
class JobEventType(basestring): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "job-event-type"
Jobs will trigger history events at certain stages of their life cycle. These events are of the types described herein. Possible values: <ul> <li> "idle" - The job has become idle, <li> "running" - The job has started running, <li> "succeeded" - The job has completed successfully, <li> "failed" - The job has completed with a failure, <li> "paused" - The job has been paused, <li> "stopped" - The job has been stopped, <li> "deleted" - The job has been deleted, <li> "error" - Job Manager experienced an error while processing the job </ul>
6259907826068e7796d4e2f0
class ProxyFetchMonitoringProtocol(monitor.MonitoringProtocol): <NEW_LINE> <INDENT> INTV_CHECK = 10 <NEW_LINE> TIMEOUT_GET = 5 <NEW_LINE> __name__ = 'ProxyFetch' <NEW_LINE> from twisted.internet import defer, error <NEW_LINE> from twisted.web import error as weberror <NEW_LINE> catchList = ( defer.TimeoutError, weberror.Error, error.ConnectError ) <NEW_LINE> def __init__(self, coordinator, server, configuration={}): <NEW_LINE> <INDENT> super(ProxyFetchMonitoringProtocol, self).__init__(coordinator, server, configuration) <NEW_LINE> self.intvCheck = self._getConfigInt('interval', self.INTV_CHECK) <NEW_LINE> self.toGET = self._getConfigInt('timeout', self.TIMEOUT_GET) <NEW_LINE> self.checkCall = None <NEW_LINE> self.checkStartTime = None <NEW_LINE> self.URL = self._getConfigStringList('url') <NEW_LINE> reactor.addSystemEventTrigger('before', 'shutdown', self.stop) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> super(ProxyFetchMonitoringProtocol, self).run() <NEW_LINE> if not self.checkCall or not self.checkCall.active(): <NEW_LINE> <INDENT> self.checkCall = reactor.callLater(self.intvCheck, self.check) <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> super(ProxyFetchMonitoringProtocol, self).stop() <NEW_LINE> if self.checkCall and self.checkCall.active(): <NEW_LINE> <INDENT> self.checkCall.cancel() <NEW_LINE> <DEDENT> <DEDENT> def check(self): <NEW_LINE> <INDENT> import random <NEW_LINE> url = random.choice(self.URL) <NEW_LINE> self.checkStartTime = seconds() <NEW_LINE> self.getProxyPage(url, method='GET', host=self.server.host, port=self.server.port, timeout=self.toGET, followRedirect=False ).addCallbacks(self._fetchSuccessful, self._fetchFailed ).addBoth(self._checkFinished) <NEW_LINE> <DEDENT> def _fetchSuccessful(self, result): <NEW_LINE> <INDENT> self.report('Fetch successful, %.3f s' % (seconds() - self.checkStartTime)) <NEW_LINE> self._resultUp() <NEW_LINE> return result <NEW_LINE> <DEDENT> def _fetchFailed(self, failure): <NEW_LINE> <INDENT> self.report('Fetch failed, %.3f s' % (seconds() - self.checkStartTime)) <NEW_LINE> self._resultDown(failure.getErrorMessage()) <NEW_LINE> failure.trap(*self.catchList) <NEW_LINE> <DEDENT> def _checkFinished(self, result): <NEW_LINE> <INDENT> self.checkStartTime = None <NEW_LINE> if self.active: <NEW_LINE> <INDENT> self.checkCall = reactor.callLater(self.intvCheck, self.check) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def getProxyPage(url, contextFactory=None, host=None, port=None, *args, **kwargs): <NEW_LINE> <INDENT> factory = client.HTTPClientFactory(url, *args, **kwargs) <NEW_LINE> host = host or factory.host <NEW_LINE> port = port or factory.port <NEW_LINE> if factory.scheme == 'https': <NEW_LINE> <INDENT> from twisted.internet import ssl <NEW_LINE> if contextFactory is None: <NEW_LINE> <INDENT> contextFactory = ssl.ClientContextFactory() <NEW_LINE> <DEDENT> reactor.connectSSL(host, port, factory, contextFactory) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reactor.connectTCP(host, port, factory) <NEW_LINE> <DEDENT> return factory.deferred <NEW_LINE> <DEDENT> getProxyPage = staticmethod(getProxyPage)
Monitor that checks server uptime by repeatedly fetching a certain URL
62599078627d3e7fe0e0883b
class CloneProvisionError(Exception): <NEW_LINE> <INDENT> pass
Raised when a repo cannot be provisioned.
62599078f548e778e596cf44
class Keybinding(): <NEW_LINE> <INDENT> def __init__(self,up="z",down="s",left="q",right="d",accept="y",refuse="n"): <NEW_LINE> <INDENT> self.up = up <NEW_LINE> self.down = down <NEW_LINE> self.left = left <NEW_LINE> self.right = right <NEW_LINE> self.accept = accept <NEW_LINE> self.refuse = refuse <NEW_LINE> <DEDENT> def getList(self): <NEW_LINE> <INDENT> return [self.up, self.down, self.left, self.right, self.accept, self.refuse]
Class contatining the keys that have special effects
625990783d592f4c4edbc837
class HeatRateCurve(Curve): <NEW_LINE> <INDENT> def __init__(self, isNetGrossP=False, ThermalGeneratingUnit=None, *args, **kw_args): <NEW_LINE> <INDENT> self.isNetGrossP = isNetGrossP <NEW_LINE> self._ThermalGeneratingUnit = None <NEW_LINE> self.ThermalGeneratingUnit = ThermalGeneratingUnit <NEW_LINE> super(HeatRateCurve, self).__init__(*args, **kw_args) <NEW_LINE> <DEDENT> _attrs = ["isNetGrossP"] <NEW_LINE> _attr_types = {"isNetGrossP": bool} <NEW_LINE> _defaults = {"isNetGrossP": False} <NEW_LINE> _enums = {} <NEW_LINE> _refs = ["ThermalGeneratingUnit"] <NEW_LINE> _many_refs = [] <NEW_LINE> def getThermalGeneratingUnit(self): <NEW_LINE> <INDENT> return self._ThermalGeneratingUnit <NEW_LINE> <DEDENT> def setThermalGeneratingUnit(self, value): <NEW_LINE> <INDENT> if self._ThermalGeneratingUnit is not None: <NEW_LINE> <INDENT> self._ThermalGeneratingUnit._HeatRateCurve = None <NEW_LINE> <DEDENT> self._ThermalGeneratingUnit = value <NEW_LINE> if self._ThermalGeneratingUnit is not None: <NEW_LINE> <INDENT> self._ThermalGeneratingUnit.HeatRateCurve = None <NEW_LINE> self._ThermalGeneratingUnit._HeatRateCurve = self <NEW_LINE> <DEDENT> <DEDENT> ThermalGeneratingUnit = property(getThermalGeneratingUnit, setThermalGeneratingUnit)
Relationship between unit heat rate per active power (Y-axis) and unit output (X-axis). The heat input is from all fuels.
62599078091ae356687065ef
class VocabularySearchRequestArgsSchema(SearchRequestArgsSchema): <NEW_LINE> <INDENT> tags = fields.Str()
Add parameter to parse tags.
6259907892d797404e389835
class FileUnitValidator(UnitValidator): <NEW_LINE> <INDENT> def explain(self, unit, field, kind, message): <NEW_LINE> <INDENT> stock_msg = self._explain_map.get(kind) <NEW_LINE> if message or stock_msg: <NEW_LINE> <INDENT> return message or stock_msg
Validator for the FileUnit class. The sole purpose of this class is to have a custom :meth:`explain()` so that we can skip the 'field' part as nobody is really writing file units and the notion of a field may be confusing.
625990787d43ff24874280ee
class DatasetNeg(Dataset): <NEW_LINE> <INDENT> def __init__(self, cands, n_img_per_load = None, max_memory_MB = 2000, max_n_reuse = 1, **kwargs): <NEW_LINE> <INDENT> Dataset.__init__(self, cands, **kwargs) <NEW_LINE> self.max_memory_MB = max_memory_MB <NEW_LINE> if n_img_per_load is None: <NEW_LINE> <INDENT> self.n_img_per_load = np.round( self.max_memory_MB / (self.img_size_in ** 3 * 4 * 1e3)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.n_img_per_load = n_img_per_load <NEW_LINE> <DEDENT> self.max_n_reuse = max_n_reuse <NEW_LINE> self.curr_n_reuse = 0 <NEW_LINE> self.n_used_aft_load = 0 <NEW_LINE> self.ix_to_load = 0 <NEW_LINE> self.ix_to_read = -1 <NEW_LINE> self._load_next_samples() <NEW_LINE> <DEDENT> def _get_next_sample(self): <NEW_LINE> <INDENT> self.ix_to_read += 1 <NEW_LINE> if self.ix_to_read == self.n_img_per_load: <NEW_LINE> <INDENT> self.ix_to_read = 0 <NEW_LINE> self.n_used_aft_load += 1 <NEW_LINE> if self.n_used_aft_load > self.max_n_reuse: <NEW_LINE> <INDENT> self._load_next_samples() <NEW_LINE> <DEDENT> <DEDENT> return (self.imgs_train_valid[self.ix_to_read,:,:,:,:], self.labels_train_valid[self.ix_to_read]) <NEW_LINE> <DEDENT> def _load_next_samples(self): <NEW_LINE> <INDENT> n_loaded = 0 <NEW_LINE> img_all_size = [self.n_img_per_load] + [self.img_size_in] * 3 + [1] <NEW_LINE> img_all = np.zeros(img_all_size, dtype=np.float32) <NEW_LINE> labels = np.zeros(self.n_img_per_load, dtype=np.float32) <NEW_LINE> while n_loaded < self.n_img_per_load: <NEW_LINE> <INDENT> n_to_load = self.n_img_per_load - n_loaded <NEW_LINE> ixs_to_load = self.ix_train_valid[ np.int32( np.mod(self.ix_to_load + np.arange(n_to_load), self.n_train_valid))] <NEW_LINE> img_all1, labels1, _ = self._load_imgs( self.cands.iloc[ixs_to_load,:]) <NEW_LINE> if img_all1 is None: <NEW_LINE> <INDENT> n_loaded1 = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n_loaded1 = img_all1.shape[0] <NEW_LINE> <DEDENT> if n_loaded1 > 0: <NEW_LINE> <INDENT> self.ix_to_load = np.mod(self.ix_to_load + n_to_load, self.n_train_valid) <NEW_LINE> ix_loaded = n_loaded + np.arange(n_loaded1) <NEW_LINE> img_all[ix_loaded,:,:,:,:] = img_all1 <NEW_LINE> labels[ix_loaded] = labels1 <NEW_LINE> n_loaded += n_loaded1 <NEW_LINE> <DEDENT> <DEDENT> self.n_used_aft_load = 0 <NEW_LINE> self.imgs_train_valid = img_all <NEW_LINE> self.labels_train_valid = labels
Load patches incrementally from the disk after a set number of reuse. Suitable for negative examples which are abundant and does not need to be augemnted. The user doesn't need to invoke a separate command for loading: s/he can keep calling get_train_valid() and the samples will be loaded if necessary.
625990785fdd1c0f98e5f931
class TestNulTerminatedString(_TestValueType): <NEW_LINE> <INDENT> value_type = NulTerminatedString(10) <NEW_LINE> attrs = ( ('max_', 10), ('encoding', 'iso-8859-1'), ('sfmt', '10s'), ) <NEW_LINE> accepts_value = ( ('', ''), ('foo', 'foo'), ('bar' * 3, 'bar' * 3), (u'ìë', u'ìë'), ) <NEW_LINE> rejects_value = ( 'bar' * 3 + 'b', u'ìë' * 5, u'실례@', ) + ( None, False, True, -1, 0, 1, -2.3, 0.1, 4.8, (), ('baz',), [], ['baz',], {}, {'baz': 'quux'}, ) <NEW_LINE> accepts_encode = ( ('', b''), ('foo', b'foo'), ('bar' * 3, b'bar' * 3), (u'ìë', b'\xec\xeb'), (u'ìë' * 4, b'\xec\xeb' * 4), ) <NEW_LINE> rejects_encode = rejects_value <NEW_LINE> accepts_decode = tuple([(_[1], _[0]) for _ in accepts_encode]) + ( (b'\x00', ''), (b'\xec\xeb', u'ìë'), (b'\xec\x8b\xa4\xeb\xa1\x80' + b'\x00' * 30, u'실례'.encode('utf-8').decode('latin-1')), ) <NEW_LINE> rejects_decode = rejects_value + ( b'bar' * 3 + b'b', b'\xec\xeb' * 5, u'실'.encode('utf-8') * 4, )
Test :class:`NulTerminatedString` for default encoding.
62599078dc8b845886d54f6e
class Shapeshift_fee(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.shapeshift_fee_data = Shapeshift_api.get_fees_shapeshift() <NEW_LINE> self.last_update_time = time.time() <NEW_LINE> <DEDENT> def get_shapeshift_fee(self, currency): <NEW_LINE> <INDENT> current_time = time.time() <NEW_LINE> if (current_time - self.last_update_time) > 30*60: <NEW_LINE> <INDENT> fees = Shapeshift_api.get_fees_shapeshift() <NEW_LINE> if fees: <NEW_LINE> <INDENT> self.shapeshift_fee_data = fees <NEW_LINE> <DEDENT> self.last_update_time = current_time <NEW_LINE> <DEDENT> for exchange in self.shapeshift_fee_data: <NEW_LINE> <INDENT> currency_shapeshift = exchange["pair"].split('_')[1] <NEW_LINE> if currency_shapeshift == currency: <NEW_LINE> <INDENT> return exchange["minerFee"]
Class responible for scraping the Shapeshift fee
625990787c178a314d78e8c5
class ConsoleServerPort(models.Model): <NEW_LINE> <INDENT> device = models.ForeignKey('Device', related_name='cs_ports', on_delete=models.CASCADE) <NEW_LINE> name = models.CharField(max_length=30) <NEW_LINE> objects = ConsoleServerPortManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ['device', 'name'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name
A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
62599078d268445f2663a838
class OwnerSchema(StrictKeysSchema): <NEW_LINE> <INDENT> id = fields.Function(lambda x: x)
Schema for owners. Allows us to later introduce more properties for an owner.
625990787047854f46340d6f
class CollisionSystem(System): <NEW_LINE> <INDENT> requirements = [ 'position', 'map_layer', 'layer', 'physics', 'sprite' ] <NEW_LINE> event_handlers = { EntityMoveEvent: ['on_entity_event', 12] } <NEW_LINE> def update(self, entity, event=None): <NEW_LINE> <INDENT> if not entity.components['position'].old: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> entity.components['physics'].collision_core.center = entity.components['sprite'].rect.center <NEW_LINE> entity.components['physics'].collision_core.centerx += entity.components['physics'].collision_core_offset[0] <NEW_LINE> entity.components['physics'].collision_core.centery += entity.components['physics'].collision_core_offset[1] <NEW_LINE> collision_rects = entity.components['layer'].layer.collision_map[:] <NEW_LINE> collision_rects.remove(entity.components['physics'].collision_core) <NEW_LINE> collisions = entity.components['physics'].collision_core.collidelist(collision_rects) <NEW_LINE> if collisions > -1: <NEW_LINE> <INDENT> entity.components['position'].primary_position = entity.components['position'].old <NEW_LINE> entity.components['sprite'].rect.topleft = list(entity.components['position'].primary_position) <NEW_LINE> entity.components['physics'].collision_core.center = entity.components['sprite'].rect.center <NEW_LINE> entity.components['physics'].collision_core.centerx += entity.components['physics'].collision_core_offset[0] <NEW_LINE> entity.components['physics'].collision_core.centery += entity.components['physics'].collision_core_offset[1] <NEW_LINE> collided_rect = collision_rects[collisions] <NEW_LINE> collided_entity_id = collided_rect.entity.id if hasattr(collided_rect, 'entity') else None <NEW_LINE> self.events.dispatch(EntityCollisionEvent(entity.id, collided_rect, collided_entity_id))
Collision system.
62599078be8e80087fbc0a49
class ContactDetails(mincepy.SimpleSavable): <NEW_LINE> <INDENT> TYPE_ID = uuid.UUID('7d2e1cf5-6c75-4b85-9fe3-46c70e680e69') <NEW_LINE> name = mincepy.field() <NEW_LINE> email = mincepy.field() <NEW_LINE> institution = mincepy.field() <NEW_LINE> address = mincepy.field() <NEW_LINE> task = mincepy.field() <NEW_LINE> work_package = mincepy.field() <NEW_LINE> def get_html(self) -> str: <NEW_LINE> <INDENT> lines = ['<p><u>Contact Information</u>'] <NEW_LINE> for field_name in mincepy.fields.get_fields(type(self)).keys(): <NEW_LINE> <INDENT> lines.append(f'{field_name}:\t {getattr(self, field_name)}') <NEW_LINE> <DEDENT> lines.append('</p>') <NEW_LINE> return '<br/>\n'.join(lines)
Database storable class representing a person's contact details
62599078f548e778e596cf45
class IoK8sApiCoreV1WeightedPodAffinityTerm(object): <NEW_LINE> <INDENT> swagger_types = { 'pod_affinity_term': 'IoK8sApiCoreV1PodAffinityTerm', 'weight': 'int' } <NEW_LINE> attribute_map = { 'pod_affinity_term': 'podAffinityTerm', 'weight': 'weight' } <NEW_LINE> def __init__(self, pod_affinity_term=None, weight=None): <NEW_LINE> <INDENT> self._pod_affinity_term = None <NEW_LINE> self._weight = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.pod_affinity_term = pod_affinity_term <NEW_LINE> self.weight = weight <NEW_LINE> <DEDENT> @property <NEW_LINE> def pod_affinity_term(self): <NEW_LINE> <INDENT> return self._pod_affinity_term <NEW_LINE> <DEDENT> @pod_affinity_term.setter <NEW_LINE> def pod_affinity_term(self, pod_affinity_term): <NEW_LINE> <INDENT> if pod_affinity_term is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `pod_affinity_term`, must not be `None`") <NEW_LINE> <DEDENT> self._pod_affinity_term = pod_affinity_term <NEW_LINE> <DEDENT> @property <NEW_LINE> def weight(self): <NEW_LINE> <INDENT> return self._weight <NEW_LINE> <DEDENT> @weight.setter <NEW_LINE> def weight(self, weight): <NEW_LINE> <INDENT> if weight is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `weight`, must not be `None`") <NEW_LINE> <DEDENT> self._weight = weight <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(IoK8sApiCoreV1WeightedPodAffinityTerm, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, IoK8sApiCoreV1WeightedPodAffinityTerm): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259907832920d7e50bc79fc
class QtMdiWindow(QtWidget, ProxyMdiWindow): <NEW_LINE> <INDENT> widget = Typed(QMdiSubWindow) <NEW_LINE> def create_widget(self): <NEW_LINE> <INDENT> widget = QMdiSubWindow() <NEW_LINE> widget.layout().setSizeConstraint(QLayout.SetMinAndMaxSize) <NEW_LINE> self.widget = widget <NEW_LINE> <DEDENT> def init_widget(self): <NEW_LINE> <INDENT> super(QtMdiWindow, self).init_widget() <NEW_LINE> d = self.declaration <NEW_LINE> if d.title: <NEW_LINE> <INDENT> self.set_title(d.title) <NEW_LINE> <DEDENT> if d.icon: <NEW_LINE> <INDENT> self.set_icon(d.icon) <NEW_LINE> <DEDENT> <DEDENT> def init_layout(self): <NEW_LINE> <INDENT> super(QtMdiWindow, self).init_layout() <NEW_LINE> self._set_window_widget(self.mdi_widget()) <NEW_LINE> <DEDENT> def mdi_widget(self): <NEW_LINE> <INDENT> w = self.declaration.mdi_widget() <NEW_LINE> if w: <NEW_LINE> <INDENT> return w.proxy.widget <NEW_LINE> <DEDENT> <DEDENT> def child_added(self, child): <NEW_LINE> <INDENT> super(QtMdiWindow, self).child_added(child) <NEW_LINE> if isinstance(child, QtWidget): <NEW_LINE> <INDENT> self._set_window_widget(self.mdi_widget()) <NEW_LINE> <DEDENT> <DEDENT> def child_removed(self, child): <NEW_LINE> <INDENT> super(QtMdiWindow, self).child_added(child) <NEW_LINE> if isinstance(child, QtWidget): <NEW_LINE> <INDENT> self._set_window_widget(self.mdi_widget()) <NEW_LINE> <DEDENT> <DEDENT> def set_icon(self, icon): <NEW_LINE> <INDENT> if icon: <NEW_LINE> <INDENT> qicon = get_cached_qicon(icon) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> qicon = QIcon() <NEW_LINE> <DEDENT> self.widget.setWindowIcon(qicon) <NEW_LINE> <DEDENT> def set_title(self, title): <NEW_LINE> <INDENT> self.widget.setWindowTitle(title) <NEW_LINE> <DEDENT> def _set_window_widget(self, mdi_widget): <NEW_LINE> <INDENT> widget = self.widget <NEW_LINE> widget.setWidget(None) <NEW_LINE> if mdi_widget is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mdi_widget.setParent(None) <NEW_LINE> widget.setWidget(mdi_widget) <NEW_LINE> mdi_widget.lower()
A Qt implementation of an Enaml ProxyMdiWindow.
6259907897e22403b383c8b7
class MockAppDaemon: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> from appdaemontestframework.appdaemon_mock.scheduler import MockScheduler <NEW_LINE> self.tz = pytz.timezone('UTC') <NEW_LINE> self.sched = MockScheduler(self)
Implementation of appdaemon's internal AppDaemon class suitable for testing
62599078aad79263cf43016e
class Document(object): <NEW_LINE> <INDENT> def __init__(self, content, document_date=None, document_id=None): <NEW_LINE> <INDENT> if document_id is None: <NEW_LINE> <INDENT> document_id = uuid.uuid4() <NEW_LINE> <DEDENT> self.document_id = document_id <NEW_LINE> self.document_date = document_date <NEW_LINE> self.content = content <NEW_LINE> <DEDENT> @property <NEW_LINE> def content(self): <NEW_LINE> <INDENT> return self._content <NEW_LINE> <DEDENT> @content.setter <NEW_LINE> def content(self, value): <NEW_LINE> <INDENT> if type(value) != dict: <NEW_LINE> <INDENT> log.error("Erro no atributo content. Ele deve receber umtipo dict mas recebeu %s", type(value)) <NEW_LINE> raise TypeError <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._content = value
Documento a ser sicnronizado nas várias bases de dados
6259907821bff66bcd72461e
class Metadata(graphene.ObjectType): <NEW_LINE> <INDENT> hash = graphene.String() <NEW_LINE> origin_id = LingvodocID() <NEW_LINE> blobs = graphene.List(LingvodocID) <NEW_LINE> merged_by = LingvodocID() <NEW_LINE> data_type = graphene.String() <NEW_LINE> blob_description = graphene.String() <NEW_LINE> merge = graphene.Field(MergeMetadata) <NEW_LINE> original_filename = graphene.String() <NEW_LINE> location = ObjectVal() <NEW_LINE> client_id = graphene.Int() <NEW_LINE> row_id = graphene.Int() <NEW_LINE> merged_to = LingvodocID() <NEW_LINE> is_protected = graphene.Boolean() <NEW_LINE> previous_objects = graphene.List(LingvodocID) <NEW_LINE> younger_siblings = graphene.List(LingvodocID) <NEW_LINE> starling_fields = graphene.List(graphene.String) <NEW_LINE> participant = graphene.List(LingvodocID) <NEW_LINE> link_perspective_id = LingvodocID() <NEW_LINE> tag_list = graphene.List(graphene.String) <NEW_LINE> authors = graphene.List(graphene.String) <NEW_LINE> years = graphene.List(graphene.String) <NEW_LINE> kind = graphene.String() <NEW_LINE> speakersAmount = graphene.String() <NEW_LINE> humanSettlement = graphene.List(graphene.String) <NEW_LINE> transcription_rules = graphene.String() <NEW_LINE> admins = graphene.List(graphene.Int) <NEW_LINE> informant = graphene.String() <NEW_LINE> interrogator = graphene.List(graphene.String) <NEW_LINE> processing = graphene.List(graphene.String) <NEW_LINE> typeOfDiscourse = graphene.String() <NEW_LINE> typeOfSpeech = graphene.String() <NEW_LINE> speechGenre = graphene.String() <NEW_LINE> theThemeOfTheText = graphene.String() <NEW_LINE> license = graphene.String()
graphene object that have all metadata attributes if new attributes of metadata are added, then this class has to be updated
62599078460517430c432d34
class ProxyProtocolHttpsConnection(ProxyProtocolHttpConnection): <NEW_LINE> <INDENT> SSL_CIPHERS = "HIGH:!ADH" <NEW_LINE> SSL_PROTOCOL = ssl.PROTOCOL_TLSv1 <NEW_LINE> def __init__(self, host, port=None, key_file=None, cert_file=None, ca_certs=None, validate=True, proxied_src='localhost', proxied_dst='localhost', proxied_src_port=None, proxied_dst_port=None): <NEW_LINE> <INDENT> ProxyProtocolHttpConnection.__init__(self, host, port, proxied_src, proxied_dst, proxied_src_port, proxied_dst_port) <NEW_LINE> if key_file and not os.access(key_file , os.R_OK): <NEW_LINE> <INDENT> raise IOError('SSL Private Key file "%s" is not readable' % (key_file)) <NEW_LINE> <DEDENT> if cert_file and not os.access(cert_file , os.R_OK): <NEW_LINE> <INDENT> raise IOError('SSL Private Key file "%s" is not readable' % (cert_file)) <NEW_LINE> <DEDENT> if ca_certs and validate and not os.access(ca_certs , os.R_OK): <NEW_LINE> <INDENT> raise IOError('Certificate Authority ca_certs file "%s" is not' ' readable, cannot validate SSL certificates.' % (ca_certs)) <NEW_LINE> <DEDENT> self.keyfile = key_file <NEW_LINE> self.certfile = cert_file <NEW_LINE> self.ca_certs = ca_certs <NEW_LINE> self.validate = validate <NEW_LINE> <DEDENT> def _validate(self, serverName): <NEW_LINE> <INDENT> peercert = self.sock.getpeercert() <NEW_LINE> if 'subject' not in peercert: <NEW_LINE> <INDENT> raise ssl.SSLError('No SSL certificate found from %s:%s' % (self.host, self.port)) <NEW_LINE> <DEDENT> for field in peercert['subject']: <NEW_LINE> <INDENT> if not isinstance(field, tuple): continue <NEW_LINE> if len(field[0]) < 2: continue <NEW_LINE> if field[0] != 'commonName': continue <NEW_LINE> commonName = field[1] <NEW_LINE> if commonName == serverName: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> raise ssl.SSLError('SSL Certificate Error: hostname \'%s\' doens\'t match \'%s\'' % (commonName, serverName)) <NEW_LINE> <DEDENT> raise ssl.SSLError('SSL Certificate Error: could not validate certificate from %s' % self.host) <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) <NEW_LINE> if self._tunnel_host: <NEW_LINE> <INDENT> self._tunnel() <NEW_LINE> server_name = self._tunnel_host <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> server_name = self.host <NEW_LINE> <DEDENT> self.sock.sendall(self._proxyProtocolHeader()) <NEW_LINE> if self.validate: <NEW_LINE> <INDENT> cert_required = ssl.CERT_REQUIRED if self.ca_certs else ssl.CERT_OPTIONAL <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cert_required = ssl.CERT_NONE <NEW_LINE> <DEDENT> self.sock = ssl.wrap_socket(self.sock, keyfile=self.keyfile, certfile=self.certfile, cert_reqs=cert_required, ca_certs=self.ca_certs, ssl_version=self.SSL_PROTOCOL, do_handshake_on_connect=True, ciphers=self.SSL_CIPHERS) <NEW_LINE> if self.validate: <NEW_LINE> <INDENT> self._validate(server_name)
A secure HTTP communicator (via SSL) which supports proxy protocol
625990785fdd1c0f98e5f933
class IMailchimpSettings(Interface): <NEW_LINE> <INDENT> api_key = schema.TextLine( title=_(u"MailChimp API Key"), description=_(u"help_api_key", default=u"Enter in your MailChimp key here (.e.g. " + "'8b785dcabe4b5aa24ef84201ea7dcded-us4'). Log into " + "mailchimp.com, go to account -> extras -> API Keys & " + "Authorized Apps and copy the API Key to this field."), default=u"", required=True) <NEW_LINE> debug = schema.Bool( title=_(u"Debug MailChimp"), description=_(u"help_debug", default=u""), required=True, default=False) <NEW_LINE> ssl = schema.Bool( title=_(u"SSL"), description=_(u"help_ssl", default=u""), required=True, default=True) <NEW_LINE> cache_sec = schema.Int( title=_(u"Cache Sec"), description=_(u"help_cache_sec", default=u""), required=True, default=500) <NEW_LINE> available_fields = schema.Choice( title=_(u"Available fields"), description=_(u"help_available_fields", default=u""), vocabulary=available_fields, required=False) <NEW_LINE> lists_email_type = schema.TextLine( title=_(u"lists_email_type"), description=_(u"help_lists_email_type", default=u""), required=True, default=u'html',) <NEW_LINE> lists_double_optin = schema.Bool( title=_(u"lists_double_optin"), description=_(u"help_lists_double_optin", default=u""), required=True, default=True) <NEW_LINE> lists_update_existing = schema.Bool( title=_(u"lists_update_existing"), description=_(u"help_lists_update_existing", default=u""), required=True, default=False) <NEW_LINE> lists_replace_interests = schema.Bool( title=_(u"lists_replace_interests"), description=_(u"help_lists_replace_interests", default=u""), required=True, default=True) <NEW_LINE> @invariant <NEW_LINE> def valid_api_key(obj): <NEW_LINE> <INDENT> registry = getUtility(IRegistry) <NEW_LINE> mailchimp_settings = registry.forInterface(IMailchimpSettings) <NEW_LINE> if len(mailchimp_settings.api_key) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mailchimp = PostMonkey(mailchimp_settings.api_key) <NEW_LINE> try: <NEW_LINE> <INDENT> return mailchimp.ping() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise Invalid(u"Your MailChimp API key is not valid. Please go " + "to mailchimp.com and check your API key.")
Global mailchimp settings. This describes records stored in the configuration registry and obtainable via plone.registry.
625990784527f215b58eb67b
class TestGegl(unittest.TestCase): <NEW_LINE> <INDENT> def test_100_init(self): <NEW_LINE> <INDENT> Gegl.init(None); <NEW_LINE> <DEDENT> def test_200_config_defaults(self): <NEW_LINE> <INDENT> gegl_config = Gegl.config() <NEW_LINE> self.assertEqual(gegl_config.props.quality, 1.0) <NEW_LINE> <DEDENT> def test_300_exit(self): <NEW_LINE> <INDENT> Gegl.exit()
Tests the Gegl global functions, initialization and configuration handling.
62599078283ffb24f3cf5257
class BaseMixer(object): <NEW_LINE> <INDENT> amplification_factor = settings.MIXER_MAX_VOLUME / 100.0 <NEW_LINE> @property <NEW_LINE> def volume(self): <NEW_LINE> <INDENT> volume = self.get_volume() <NEW_LINE> if volume is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return int(volume / self.amplification_factor) <NEW_LINE> <DEDENT> @volume.setter <NEW_LINE> def volume(self, volume): <NEW_LINE> <INDENT> volume = int(int(volume) * self.amplification_factor) <NEW_LINE> if volume < 0: <NEW_LINE> <INDENT> volume = 0 <NEW_LINE> <DEDENT> elif volume > 100: <NEW_LINE> <INDENT> volume = 100 <NEW_LINE> <DEDENT> self.set_volume(volume) <NEW_LINE> self._trigger_volume_changed() <NEW_LINE> <DEDENT> def get_volume(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_volume(self, volume): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _trigger_volume_changed(self): <NEW_LINE> <INDENT> logger.debug(u'Triggering volume changed event') <NEW_LINE> listeners.BackendListener.send('volume_changed')
**Settings:** - :attr:`mopidy.settings.MIXER_MAX_VOLUME`
62599078167d2b6e312b826d
class SequenceBatch(object): <NEW_LINE> <INDENT> def __init__( self, sequences, original_idxs=None, pad_idx=None, left_aligned=True ): <NEW_LINE> <INDENT> if len(sequences) == 0: <NEW_LINE> <INDENT> raise ValueError("Can't batch 0 sequences together") <NEW_LINE> <DEDENT> if not isinstance(sequences[0], Iterable): <NEW_LINE> <INDENT> sequences = [sequences] <NEW_LINE> <DEDENT> self.original_idxs = _default_value(original_idxs, [0]*len(sequences)) <NEW_LINE> self.lengths = [len(seq) for seq in sequences] <NEW_LINE> self.pad_idx = _default_value(pad_idx, 0) <NEW_LINE> self.left_aligned = left_aligned <NEW_LINE> self.unpadded_sequences = sequences <NEW_LINE> self.sequences = self.collate(sequences) <NEW_LINE> self.max_length = self.sequences.shape[0] <NEW_LINE> self.batch_size = self.sequences.shape[1] <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return SequenceBatch( self.unpadded_sequences[index], self.original_idxs[index], self.pad_idx, self.left_aligned, ) <NEW_LINE> <DEDENT> def get_mask(self, base_val=1, mask_val=0): <NEW_LINE> <INDENT> mask = seq_mask( self.max_length, self.lengths, base_val=base_val, mask_val=mask_val, left_aligned=self.left_aligned ) <NEW_LINE> return mask <NEW_LINE> <DEDENT> def collate(self, sequences): <NEW_LINE> <INDENT> max_len = max(self.lengths) <NEW_LINE> batch_array = np.full( (max_len, len(sequences)), self.pad_idx, dtype=int ) <NEW_LINE> for batch_idx, sequence in enumerate(sequences): <NEW_LINE> <INDENT> if self.left_aligned: <NEW_LINE> <INDENT> batch_array[:self.lengths[batch_idx], batch_idx] = sequence <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> batch_array[-self.lengths[batch_idx]:, batch_idx] = sequence <NEW_LINE> <DEDENT> <DEDENT> return batch_array
Batched sequence object with padding This wraps a list of integer sequences into a nice array padded to the longest sequence. The batch dimension (number of sequences) is the last dimension. By default the sequences are padded to the right which means that they are aligned to the left (they all start at index 0) Args: sequences (list): List of list of integers original_idxs (list): This list should point to the original position of each sequence in the data (before shuffling/reordering). This is useful when you want to access information that has been discarded during preprocessing (eg original sentence before numberizing and ``<unk>`` ing in MT). pad_idx (int): Default index for padding left_aligned (bool, optional): Align to the left (all sequences start at the same position).
625990785fcc89381b266e35
class SpeciesSearchForm(SearchForm): <NEW_LINE> <INDENT> q = None <NEW_LINE> querystring = forms.CharField(required=False, widget=forms.widgets.TextInput(attrs={ "placeholder": "name:Bass OR category:Plants" }), label="Search") <NEW_LINE> sort_by = forms.ChoiceField(choices=[ ("name", "Name"), ("scientific_name", "Scientific Name"), ("severity", "Severity"), ("category", "Category"), ("is_confidential", "Confidential"), ], required=False) <NEW_LINE> order = forms.ChoiceField(choices=[ ("ascending", "Ascending"), ("descending", "Descending"), ], required=False, initial="ascending", widget=forms.widgets.RadioSelect) <NEW_LINE> def __init__(self, *args, user, **kwargs): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> super().__init__(*args, index=SpeciesIndex, **kwargs) <NEW_LINE> <DEDENT> def search(self): <NEW_LINE> <INDENT> results = super().search() <NEW_LINE> if self.cleaned_data.get("querystring"): <NEW_LINE> <INDENT> query = results.query( "query_string", query=self.cleaned_data.get("querystring", ""), lenient=True, ) <NEW_LINE> if not self.is_valid_query(query): <NEW_LINE> <INDENT> results = results.query( "simple_query_string", query=self.cleaned_data.get("querystring", ""), lenient=True, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results = query <NEW_LINE> <DEDENT> <DEDENT> sort_by = self.cleaned_data.get("sort_by") <NEW_LINE> order = self.cleaned_data.get("order") <NEW_LINE> if sort_by: <NEW_LINE> <INDENT> if order == "descending": <NEW_LINE> <INDENT> sort_by = "-" + sort_by <NEW_LINE> <DEDENT> results = results.sort(sort_by) <NEW_LINE> <DEDENT> return results
This form handles searching for a species in the species list view.
62599078379a373c97d9a9d9
class MicrositeAwareSettings(object): <NEW_LINE> <INDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if isinstance(microsite.get_value(name), dict): <NEW_LINE> <INDENT> return microsite.get_dict(name, getattr(base_settings, name, None)) <NEW_LINE> <DEDENT> return microsite.get_value(name, getattr(base_settings, name)) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return getattr(base_settings, name)
This class is a proxy object of the settings object from django. It will try to get a value from the microsite and default to the django settings
625990788e7ae83300eeaa42
class HotspotPage(ubuntuuitoolkit.UbuntuUIToolkitCustomProxyObjectBase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def validate_dbus_object(cls, path, state): <NEW_LINE> <INDENT> name = introspection.get_classname_from_path(path) <NEW_LINE> if name == b'ItemPage': <NEW_LINE> <INDENT> if state['objectName'][1] == 'hotspotPage': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def _switch(self): <NEW_LINE> <INDENT> return self.wait_select_single( ubuntuuitoolkit.CheckBox, objectName='hotspotSwitch') <NEW_LINE> <DEDENT> @autopilot.logging.log_action(logger.debug) <NEW_LINE> def enable_hotspot(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._switch.check(timeout=2) <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> prompt = self.get_root_instance().wait_select_single( objectName='enableWifiDialog') <NEW_LINE> <DEDENT> except StateNotFoundError: <NEW_LINE> <INDENT> prompt = None <NEW_LINE> <DEDENT> if prompt: <NEW_LINE> <INDENT> prompt.confirm_enable() <NEW_LINE> prompt.wait_until_destroyed(timeout=5) <NEW_LINE> <DEDENT> <DEDENT> @autopilot.logging.log_action(logger.debug) <NEW_LINE> def disable_hotspot(self): <NEW_LINE> <INDENT> self._switch.uncheck() <NEW_LINE> <DEDENT> @autopilot.logging.log_action(logger.debug) <NEW_LINE> def setup_hotspot(self, config): <NEW_LINE> <INDENT> obj = self.select_single(objectName='hotspotSetupButton') <NEW_LINE> self.pointing_device.click_object(obj) <NEW_LINE> setup = self.get_root_instance().wait_select_single( objectName='hotspotSetup') <NEW_LINE> if config: <NEW_LINE> <INDENT> if 'ssid' in config: <NEW_LINE> <INDENT> setup.set_ssid(config['ssid']) <NEW_LINE> <DEDENT> if 'auth' in config: <NEW_LINE> <INDENT> setup.set_auth(config['auth']) <NEW_LINE> <DEDENT> if 'password' in config: <NEW_LINE> <INDENT> setup.set_password(config['password']) <NEW_LINE> <DEDENT> <DEDENT> utils.dismiss_osk() <NEW_LINE> setup.enable() <NEW_LINE> if setup: <NEW_LINE> <INDENT> setup.wait_until_destroyed() <NEW_LINE> <DEDENT> <DEDENT> @autopilot.logging.log_action(logger.debug) <NEW_LINE> def get_hotspot_status(self): <NEW_LINE> <INDENT> return self._switch.checked <NEW_LINE> <DEDENT> @autopilot.logging.log_action(logger.debug) <NEW_LINE> def get_hotspot_possible(self): <NEW_LINE> <INDENT> return self._switch.enabled
Autopilot helper for Hotspot page.
62599078e1aae11d1e7cf4eb
class Entry(): <NEW_LINE> <INDENT> def __init__(self, level, heading, tags=None, content=None, starter_char=None): <NEW_LINE> <INDENT> if starter_char: <NEW_LINE> <INDENT> self.starter_char = starter_char <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.starter_char = "*" <NEW_LINE> <DEDENT> self.level = self.starter_char * int(level) <NEW_LINE> self.heading = heading <NEW_LINE> if tags: <NEW_LINE> <INDENT> _tag_list = [":{0}:".format(tag) for tag in tags] <NEW_LINE> self.tags = "".join(_tag_list) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tags = "" <NEW_LINE> <DEDENT> self.content = content <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> header = self.level + " " + self.heading + " " + self.tags <NEW_LINE> if self.content: <NEW_LINE> <INDENT> entry = header + "\n" + self.content <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entry = header <NEW_LINE> <DEDENT> return entry
Describes an individual TODO item for use in agendas and TODO lists
625990787047854f46340d71
class DistributionPieViz(NVD3Viz): <NEW_LINE> <INDENT> viz_type = "pie" <NEW_LINE> verbose_name = _("Distribution - NVD3 - Pie Chart") <NEW_LINE> is_timeseries = False <NEW_LINE> fieldsets = ({ 'label': None, 'fields': ( 'metrics', 'groupby', 'limit', 'pie_label_type', ('donut', 'show_legend'), 'labels_outside', ) },) <NEW_LINE> def query_obj(self): <NEW_LINE> <INDENT> d = super(DistributionPieViz, self).query_obj() <NEW_LINE> d['is_timeseries'] = False <NEW_LINE> return d <NEW_LINE> <DEDENT> def get_df(self, query_obj=None): <NEW_LINE> <INDENT> df = super(DistributionPieViz, self).get_df(query_obj) <NEW_LINE> df = df.pivot_table( index=self.groupby, values=[self.metrics[0]]) <NEW_LINE> df.sort_values(by=self.metrics[0], ascending=False, inplace=True) <NEW_LINE> return df <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> df = self.get_df() <NEW_LINE> df = df.reset_index() <NEW_LINE> df.columns = ['x', 'y'] <NEW_LINE> return df.to_dict(orient="records")
Annoy visualization snobs with this controversial pie chart
6259907844b2445a339b7639
class SimpleVirus(object): <NEW_LINE> <INDENT> def __init__(self, maxBirthProb, clearProb): <NEW_LINE> <INDENT> self.maxBirthProb = maxBirthProb <NEW_LINE> self.clearProb = clearProb <NEW_LINE> <DEDENT> def getMaxBirthProb(self): <NEW_LINE> <INDENT> return self.maxBirthProb <NEW_LINE> <DEDENT> def getClearProb(self): <NEW_LINE> <INDENT> return self.clearProb <NEW_LINE> <DEDENT> def doesClear(self): <NEW_LINE> <INDENT> clearance_decision = random.random() <NEW_LINE> if clearance_decision <= self.clearProb: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def reproduce(self, popDensity): <NEW_LINE> <INDENT> reproduction_outcome = random.random() <NEW_LINE> if reproduction_outcome <= self.maxBirthProb * (1 - popDensity): <NEW_LINE> <INDENT> offspring = SimpleVirus(self.maxBirthProb, self.clearProb) <NEW_LINE> return offspring <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NoChildException
Representation of a simple virus (does not model drug effects/resistance).
625990785fc7496912d48f45
class Book: <NEW_LINE> <INDENT> def __init__(self, title: str, author: str, bid: str = None, **kwargs: Any): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.author = author <NEW_LINE> self.bid = bid if bid is not None else str(uuid4()) <NEW_LINE> self.is_lent = False <NEW_LINE> self.current_user = None <NEW_LINE> self.return_date = None <NEW_LINE> self.__dict__.update(kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self.title} by {self.author}' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"Book(<'{self.title}', '{self.author}', '{self.bid}'>)" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, book_dict: dict, bid: str = None) -> 'Book': <NEW_LINE> <INDENT> _book = cls(book_dict['title'], book_dict['author'], bid) <NEW_LINE> for key, value in book_dict.items(): <NEW_LINE> <INDENT> if key in ['title', 'author']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if key == 'return_date': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _book.return_date = datetime.strptime(value, '%Y%m%d') <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> _book.return_date = None <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> _book.__dict__.update({key: value}) <NEW_LINE> <DEDENT> return _book <NEW_LINE> <DEDENT> @property <NEW_LINE> def days_until_return(self) -> Optional[timedelta]: <NEW_LINE> <INDENT> if self.is_lent: <NEW_LINE> <INDENT> return self.return_date - datetime.today() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def to_dict(self) -> dict: <NEW_LINE> <INDENT> book_dict = {} <NEW_LINE> for key, value in self.__dict__.items(): <NEW_LINE> <INDENT> if key == 'bid': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if key == 'return_date': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return_date = value.strftime('%Y%m%d') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return_date = None <NEW_LINE> <DEDENT> book_dict.update({key: return_date}) <NEW_LINE> continue <NEW_LINE> <DEDENT> book_dict.update({key: value}) <NEW_LINE> <DEDENT> return book_dict
Stores data and manages books
62599078097d151d1a2c2a2d
class Function: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def forward(context, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError("The forward method should be implemented.") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def backward(context, *output_grads): <NEW_LINE> <INDENT> raise NotImplementedError("The backward method should be implemented.") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def apply(cls, *args, **kwargs): <NEW_LINE> <INDENT> assert all([isinstance(arg, Tensor) for arg in args]), "All positional args to a " "Function must be Tensors" <NEW_LINE> requires_grad = any([tensor.requires_grad for tensor in args]) <NEW_LINE> context = Context(cls, parents=(args)) <NEW_LINE> args = [tensor.data for tensor in args] <NEW_LINE> result = cls.forward(context, *args, **kwargs) <NEW_LINE> if not grads_enabled: <NEW_LINE> <INDENT> requires_grad = False <NEW_LINE> <DEDENT> if not requires_grad: <NEW_LINE> <INDENT> context = None <NEW_LINE> <DEDENT> return Tensor(result, requires_grad=requires_grad, context=context) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def apply_backward(cls, context, *args, **kwargs): <NEW_LINE> <INDENT> result = cls.backward(context, *args, **kwargs) <NEW_LINE> if not isinstance(result, (list, tuple)): <NEW_LINE> <INDENT> result = (result, ) <NEW_LINE> <DEDENT> return result
Interface for custom functions to be added to a computational graph. Any custom functions should subclass Function and implement two mandatory static methods: forward and backward. The function should be called by using the apply method, which will return the resulting Tensor of the operation with its corresponding information to track the operations that created that Tensor if any of the Tensors that were used as arguments on the function have requires_grad=True.
6259907801c39578d7f14410
class AliasMixin(models.AbstractModel): <NEW_LINE> <INDENT> _name = 'mail.alias.mixin' <NEW_LINE> _inherits = {'mail.alias': 'alias_id'} <NEW_LINE> alias_id = fields.Many2one('mail.alias', string='Alias', ondelete="restrict", required=True) <NEW_LINE> def get_alias_model_name(self, vals): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_alias_values(self): <NEW_LINE> <INDENT> return {'alias_parent_thread_id': self.id} <NEW_LINE> <DEDENT> @api.model <NEW_LINE> def create(self, vals): <NEW_LINE> <INDENT> record = super(AliasMixin, self.with_context( alias_model_name=self.get_alias_model_name(vals), alias_parent_model_name=self._name, )).create(vals) <NEW_LINE> record.alias_id.sudo().write(record.get_alias_values()) <NEW_LINE> return record <NEW_LINE> <DEDENT> @api.multi <NEW_LINE> def unlink(self): <NEW_LINE> <INDENT> aliases = self.mapped('alias_id') <NEW_LINE> res = super(AliasMixin, self).unlink() <NEW_LINE> aliases.unlink() <NEW_LINE> return res <NEW_LINE> <DEDENT> @api.model_cr_context <NEW_LINE> def _init_column(self, name): <NEW_LINE> <INDENT> super(AliasMixin, self)._init_column(name) <NEW_LINE> if name != 'alias_id': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> alias_ctx = { 'alias_model_name': self.get_alias_model_name({}), 'alias_parent_model_name': self._name, } <NEW_LINE> alias_model = self.env['mail.alias'].sudo().with_context(alias_ctx).browse([]) <NEW_LINE> child_ctx = { 'active_test': False, 'prefetch_fields': False, } <NEW_LINE> child_model = self.sudo().with_context(child_ctx).browse([]) <NEW_LINE> for record in child_model.search([('alias_id', '=', False)]): <NEW_LINE> <INDENT> alias = alias_model.create(record.get_alias_values()) <NEW_LINE> record.with_context({'mail_notrack': True}).alias_id = alias <NEW_LINE> _logger.info('Mail alias created for %s %s (id %s)', record._name, record.display_name, record.id)
A mixin for models that inherits mail.alias. This mixin initializes the alias_id column in database, and manages the expected one-to-one relation between your model and mail aliases.
62599078442bda511e95da33
class BetterLogger(werkzeug.serving.BaseRequestHandler): <NEW_LINE> <INDENT> _user_state = None <NEW_LINE> app = ppc.app() <NEW_LINE> @app.teardown_request <NEW_LINE> def _teardown(response): <NEW_LINE> <INDENT> user_state = '""' <NEW_LINE> if 'user.biv_id' in flask.session: <NEW_LINE> <INDENT> user_state = 'l' <NEW_LINE> if flask.session['user.is_logged_in']: <NEW_LINE> <INDENT> user_state += 'i' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user_state += 'o' <NEW_LINE> <DEDENT> user_state += '-' + str(flask.session['user.biv_id']) <NEW_LINE> <DEDENT> BetterLogger._user_state = user_state <NEW_LINE> <DEDENT> def log_request(self, code='-', size='-'): <NEW_LINE> <INDENT> self.log('info', '%s "%s" %s %s', BetterLogger._user_state, self.requestline, code, size)
HTTP access logger which includes user_state.
625990787cff6e4e811b73f7
class SimpleDatasetPredictor(DatasetPredictorBase): <NEW_LINE> <INDENT> def __init__(self, config, dataset): <NEW_LINE> <INDENT> super(SimpleDatasetPredictor, self).__init__(config, dataset) <NEW_LINE> self.predictor = OfflinePredictor(config) <NEW_LINE> <DEDENT> def get_result(self): <NEW_LINE> <INDENT> self.dataset.reset_state() <NEW_LINE> try: <NEW_LINE> <INDENT> sz = self.dataset.size() <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> sz = 0 <NEW_LINE> <DEDENT> with get_tqdm(total=sz, disable=(sz==0)) as pbar: <NEW_LINE> <INDENT> for dp in self.dataset.get_data(): <NEW_LINE> <INDENT> res = self.predictor(dp) <NEW_LINE> yield res <NEW_LINE> pbar.update()
Run the predict_config on a given `DataFlow`.
62599078bf627c535bcb2e85
@SingletonDecorator <NEW_LINE> class CallCentre(AbstractCallCentre): <NEW_LINE> <INDENT> def __init__(self, ndirectors, nmanagers, nrespondents): <NEW_LINE> <INDENT> self._employees = {} <NEW_LINE> self._create_call_centre(ndirectors, nmanagers, nrespondents) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self._employees) <NEW_LINE> <DEDENT> def _create_call_centre(self, ndirectors, nmanagers, nrespondents): <NEW_LINE> <INDENT> self._employees.update( { "directors": Employee(navailable=ndirectors) } ) <NEW_LINE> self._employees.update( { 'managers': Employee(navailable=nmanagers) } ) <NEW_LINE> self._employees.update( { 'respondents': Employee(navailable=nrespondents) } ) <NEW_LINE> <DEDENT> def _check_availablity(self, role): <NEW_LINE> <INDENT> return self._employees[role]['available'] <NEW_LINE> <DEDENT> def _mark_busy(self, role): <NEW_LINE> <INDENT> if self._employees[role]['navailable'] > 0: <NEW_LINE> <INDENT> self._employees[role]['navailable'] -= 1 <NEW_LINE> <DEDENT> if self._employees[role]['navailable'] == 0: <NEW_LINE> <INDENT> self._employees[role]['available'] = False <NEW_LINE> <DEDENT> <DEDENT> def dispatch_call(self): <NEW_LINE> <INDENT> if self._check_availablity('respondents'): <NEW_LINE> <INDENT> self._mark_busy('respondents') <NEW_LINE> <DEDENT> elif self._check_availablity('managers'): <NEW_LINE> <INDENT> self._mark_busy('managers') <NEW_LINE> <DEDENT> elif self._check_availablity('directors'): <NEW_LINE> <INDENT> self._mark_busy('directors') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Call centre at full capacity')
Concrete Call Centre
62599078fff4ab517ebcf1ce
class Solution: <NEW_LINE> <INDENT> def twoSum(self, numbers, target): <NEW_LINE> <INDENT> from collections import defaultdict <NEW_LINE> table = defaultdict(int) <NEW_LINE> for i, num in enumerate(numbers): <NEW_LINE> <INDENT> if target - num in table: <NEW_LINE> <INDENT> return sorted([i + 1, table[target - num]]) <NEW_LINE> <DEDENT> table[num] = i + 1
@param numbers : An array of Integer @param target : target = numbers[index1] + numbers[index2] @return : [index1 + 1, index2 + 1] (index1 < index2)
62599078796e427e53850131
class Something(data.Dataset): <NEW_LINE> <INDENT> def __init__(self, root_path, annotation_path, subset, n_samples_for_each_video=1, spatial_transform=None, temporal_transform=None, target_transform=None, sample_duration=16, get_loader=get_default_video_loader): <NEW_LINE> <INDENT> self.data, self.class_names = make_dataset( root_path, annotation_path, subset, n_samples_for_each_video, sample_duration) <NEW_LINE> self.spatial_transform = spatial_transform <NEW_LINE> self.temporal_transform = temporal_transform <NEW_LINE> self.target_transform = target_transform <NEW_LINE> self.loader = get_loader() <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> path = self.data[index]['video'] <NEW_LINE> frame_indices = self.data[index]['frame_indices'] <NEW_LINE> if self.temporal_transform is not None: <NEW_LINE> <INDENT> frame_indices = self.temporal_transform(frame_indices) <NEW_LINE> <DEDENT> clip = self.loader(path, frame_indices) <NEW_LINE> if self.spatial_transform is not None: <NEW_LINE> <INDENT> self.spatial_transform.randomize_parameters() <NEW_LINE> clip = [self.spatial_transform(img) for img in clip] <NEW_LINE> <DEDENT> clip = torch.stack(clip, 0).permute(1, 0, 2, 3) <NEW_LINE> target = self.data[index] <NEW_LINE> if self.target_transform is not None: <NEW_LINE> <INDENT> target = self.target_transform(target) <NEW_LINE> <DEDENT> return clip, target <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.data)
Args: root (string): Root directory path. spatial_transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed version. E.g, ``transforms.RandomCrop`` temporal_transform (callable, optional): A function/transform that takes in a list of frame indices and returns a transformed version target_transform (callable, optional): A function/transform that takes in the target and transforms it. loader (callable, optional): A function to load an video given its path and frame indices. Attributes: classes (list): List of the class names. class_to_idx (dict): Dict with items (class_name, class_index). imgs (list): List of (image path, class_index) tuples
625990784c3428357761bc6f
@dataclass <NEW_LINE> class PedidoConsultaCnpj: <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> name = "PedidoConsultaCNPJ" <NEW_LINE> namespace = "http://www.prefeitura.sp.gov.br/nfe" <NEW_LINE> <DEDENT> cabecalho: Optional["PedidoConsultaCnpj.Cabecalho"] = field( default=None, metadata={ "name": "Cabecalho", "type": "Element", "namespace": "", "required": True, } ) <NEW_LINE> cnpjcontribuinte: Optional[TpCpfcnpj] = field( default=None, metadata={ "name": "CNPJContribuinte", "type": "Element", "namespace": "", "required": True, } ) <NEW_LINE> signature: Optional[Signature] = field( default=None, metadata={ "name": "Signature", "type": "Element", "namespace": "http://www.w3.org/2000/09/xmldsig#", "required": True, } ) <NEW_LINE> @dataclass <NEW_LINE> class Cabecalho: <NEW_LINE> <INDENT> cpfcnpjremetente: Optional[TpCpfcnpj] = field( default=None, metadata={ "name": "CPFCNPJRemetente", "type": "Element", "namespace": "", "required": True, } ) <NEW_LINE> versao: str = field( init=False, default="1", metadata={ "name": "Versao", "type": "Attribute", "required": True, "pattern": r"[0-9]{1,3}", } )
Schema utilizado para PEDIDO de consultas de CNPJ. Este Schema XML é utilizado pelos tomadores e/ou prestadores de serviços consultarem quais Inscrições Municipais (CCM) estão vinculadas a um determinado CNPJ e se estes CCM emitem NFS-e ou não. :ivar cabecalho: Cabeçalho do pedido. :ivar cnpjcontribuinte: Informe o CNPJ do Contribuinte que se deseja consultar. :ivar signature: Assinatura digital do CNPJ tomador/prestador que gerou a mensagem XML.
6259907823849d37ff852a6f
class Command(BaseCommand): <NEW_LINE> <INDENT> help = "Handles rename and delete operations on mailboxes" <NEW_LINE> option_list = BaseCommand.option_list + ( make_option( "--pidfile", default="/tmp/handle_mailbox_operations.pid", help="Path to the file that will contain the PID of this process" ), ) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Command, self).__init__(*args, **kwargs) <NEW_LINE> self.logger = logging.getLogger("modoboa.admin") <NEW_LINE> <DEDENT> def rename_mailbox(self, operation): <NEW_LINE> <INDENT> if not os.path.exists(operation.argument): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> new_mail_home = operation.mailbox.mail_home <NEW_LINE> dirname = os.path.dirname(new_mail_home) <NEW_LINE> if not os.path.exists(dirname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(dirname) <NEW_LINE> <DEDENT> except os.error as e: <NEW_LINE> <INDENT> raise OperationError(str(e)) <NEW_LINE> <DEDENT> <DEDENT> code, output = exec_cmd( "mv %s %s" % (operation.argument, new_mail_home) ) <NEW_LINE> if code: <NEW_LINE> <INDENT> raise OperationError(output) <NEW_LINE> <DEDENT> <DEDENT> def delete_mailbox(self, operation): <NEW_LINE> <INDENT> if not os.path.exists(operation.argument): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> code, output = exec_cmd( "rm -r %s" % operation.argument ) <NEW_LINE> if code: <NEW_LINE> <INDENT> raise OperationError(output) <NEW_LINE> <DEDENT> <DEDENT> def check_pidfile(self, path): <NEW_LINE> <INDENT> if os.path.exists(path): <NEW_LINE> <INDENT> with open(path) as fp: <NEW_LINE> <INDENT> pid = fp.read().strip() <NEW_LINE> <DEDENT> code, output = exec_cmd( "grep handle_mailbox_operations /proc/%s/cmdline" % pid ) <NEW_LINE> if not code: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> with open(path, 'w') as fp: <NEW_LINE> <INDENT> print >> fp, os.getpid() <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> load_admin_settings() <NEW_LINE> if not param_tools.get_global_parameter("handle_mailboxes"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self.check_pidfile(options["pidfile"]): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for ope in MailboxOperation.objects.all(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = getattr(self, "%s_mailbox" % ope.type) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> f(ope) <NEW_LINE> <DEDENT> except (OperationError, InternalError) as e: <NEW_LINE> <INDENT> self.logger.critical("%s failed (reason: %s)", ope, str(e).encode("utf-8")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.info("%s succeed", ope) <NEW_LINE> ope.delete() <NEW_LINE> <DEDENT> <DEDENT> os.unlink(options["pidfile"])
Command definition
62599078dc8b845886d54f72
class Gaussian(RandomVariable): <NEW_LINE> <INDENT> def __init__(self, mu=None, var=None, tau=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.mu = mu <NEW_LINE> if var is not None: <NEW_LINE> <INDENT> self.var = var <NEW_LINE> <DEDENT> elif tau is not None: <NEW_LINE> <INDENT> self.tau = tau <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.var = None <NEW_LINE> self.tau = None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def shape(self): <NEW_LINE> <INDENT> if hasattr(self.mu, "shape"): <NEW_LINE> <INDENT> return self.mu.shape <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _fit(self, X): <NEW_LINE> <INDENT> mu_is_gaussian = isinstance(self.mu, Gaussian) <NEW_LINE> if mu_is_gaussian: <NEW_LINE> <INDENT> self._bayes_mu(X) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ml(X) <NEW_LINE> <DEDENT> <DEDENT> def _ml(self, X): <NEW_LINE> <INDENT> self.mu = np.mean(X, axis=0) <NEW_LINE> self.var = np.var(X, axis=0) <NEW_LINE> <DEDENT> def _bayes_mu(self, X): <NEW_LINE> <INDENT> N = len(X) <NEW_LINE> mu = np.mean(X, 0) <NEW_LINE> tau = self.mu.tau + N * self.tau <NEW_LINE> self.mu = Gaussian(mu=self.mu.mu * self.mu.tau / tau, tau=tau) <NEW_LINE> <DEDENT> def _pdf(self, X): <NEW_LINE> <INDENT> d = X - self.mu <NEW_LINE> return ( np.exp(-0.5 * self.tau * d ** 2) / np.sqrt(2 * np.pi * self.var) ) <NEW_LINE> <DEDENT> def _draw(self, sample_size=1): <NEW_LINE> <INDENT> return np.random.normal( loc=self.mu, scale=np.sqrt(self.var), size=(sample_size,) + self.shape )
The Gaussian distribution p(x|mu, var) = exp{-0.5 * (x - mu)^2 / var} / sqrt(2pi * var)
6259907856ac1b37e63039be
class UndirectedGraphOperadBasis(UndirectedGraphBasis): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._graphs = keydefaultdict(partial(undirected_graph_cache.graphs, has_odd_automorphism=False)) <NEW_LINE> <DEDENT> def graph_to_key(self, graph): <NEW_LINE> <INDENT> g, undo_canonicalize, sign = undirected_graph_cache.canonicalize_graph(graph) <NEW_LINE> v, e = len(g), len(g.edges()) <NEW_LINE> try: <NEW_LINE> <INDENT> index = self._graphs[v,e].index(g) <NEW_LINE> return (v,e,index) + tuple(undo_canonicalize), sign <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return None, 1 <NEW_LINE> <DEDENT> <DEDENT> def key_to_graph(self, key): <NEW_LINE> <INDENT> v, e, index = key[:3] <NEW_LINE> undo_canonicalize = key[3:] <NEW_LINE> try: <NEW_LINE> <INDENT> G = self._graphs[v,e][index] <NEW_LINE> g = G.relabeled(undo_canonicalize) <NEW_LINE> sign = g.canonicalize_edges() <NEW_LINE> return g, sign <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return None, 1 <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Basis consisting of labeled undirected graphs with no automorphisms that induce an odd permutation on edges' <NEW_LINE> <DEDENT> def graph_properties(self): <NEW_LINE> <INDENT> return {'has_odd_automorphism' : False}
Basis consisting of labeled undirected graphs with no automorphisms that induce an odd permutation on edges
625990785fcc89381b266e36
class Owl( GenericXml ): <NEW_LINE> <INDENT> edam_format = "format_3262" <NEW_LINE> file_ext = "owl" <NEW_LINE> def set_peek( self, dataset, is_multi_byte=False ): <NEW_LINE> <INDENT> if not dataset.dataset.purged: <NEW_LINE> <INDENT> dataset.peek = data.get_file_peek( dataset.file_name, is_multi_byte=is_multi_byte ) <NEW_LINE> dataset.blurb = "Web Ontology Language OWL" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dataset.peek = 'file does not exist' <NEW_LINE> dataset.blurb = 'file purged from disc' <NEW_LINE> <DEDENT> <DEDENT> def sniff( self, filename ): <NEW_LINE> <INDENT> owl_marker = re.compile(r'\<owl:') <NEW_LINE> with open( filename ) as handle: <NEW_LINE> <INDENT> first_lines = handle.readlines(200) <NEW_LINE> for line in first_lines: <NEW_LINE> <INDENT> if owl_marker.search( line ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False
Web Ontology Language OWL format description http://www.w3.org/TR/owl-ref/
625990785fdd1c0f98e5f936
class SeleniumMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> if ("webdriver" in request.meta and request.meta["webdriver"] == "do_use"): <NEW_LINE> <INDENT> log("Selenium requesting {}".format(request.url)) <NEW_LINE> try: <NEW_LINE> <INDENT> spider.driver.get(request.url) <NEW_LINE> <DEDENT> except TimeoutException as we: <NEW_LINE> <INDENT> log("Web driver: timeout at {}".format(request.url), logging.ERROR) <NEW_LINE> <DEDENT> return HtmlResponse(spider.driver.current_url, body=spider.driver.page_source, encoding="utf-8", request=request)
Uses Selenium for the items having the key in their meta set
6259907844b2445a339b763a
class MediaForm(forms.ModelForm): <NEW_LINE> <INDENT> is_private = forms.NullBooleanField(widget=forms.CheckboxInput(), label=_(u"Private")) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Media <NEW_LINE> fields = ('caption', 'private_media', 'tags',)
Form to add a media object
62599078d486a94d0ba2d970
class UploadNodesInfo(GenericRolesHook): <NEW_LINE> <INDENT> identity = 'upload_nodes_info' <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> q_nodes = objects.Cluster.get_nodes_not_for_deletion(self.cluster) <NEW_LINE> nodes = set(q_nodes.filter_by(status=consts.NODE_STATUSES.ready)) <NEW_LINE> nodes.update(self.nodes) <NEW_LINE> uids = [n.uid for n in nodes] <NEW_LINE> serialized_nodes = self._serialize_nodes(nodes) <NEW_LINE> data = yaml.safe_dump({ 'nodes': serialized_nodes, }) <NEW_LINE> path = self.task['parameters']['path'] <NEW_LINE> yield templates.make_upload_task(uids, path=path, data=data) <NEW_LINE> <DEDENT> def _serialize_nodes(self, nodes): <NEW_LINE> <INDENT> serializer = deployment_serializers.get_serializer_for_cluster( self.cluster) <NEW_LINE> net_serializer = serializer.get_net_provider_serializer(self.cluster) <NEW_LINE> serialized_nodes = serializer.node_list(nodes) <NEW_LINE> serialized_nodes = net_serializer.update_nodes_net_info( self.cluster, serialized_nodes) <NEW_LINE> return serialized_nodes
Hook that uploads info about all nodes in cluster.
62599078a8370b77170f1d87
class MainApplication(tk.Frame): <NEW_LINE> <INDENT> def __init__(self, root=None, *args, **kwargs): <NEW_LINE> <INDENT> tk.Frame.__init__(self, root) <NEW_LINE> self.root = root <NEW_LINE> self.download_location = "downloads/" <NEW_LINE> self.download_type = tk.IntVar() <NEW_LINE> self.url_label = tk.Label(self.root, text="Entre com a URL do vídeo:") <NEW_LINE> self.url_label.grid(row=0, column=0) <NEW_LINE> self.url_entry = tk.Entry(self.root) <NEW_LINE> self.url_entry.grid(row=1, column=0) <NEW_LINE> self.locate_button = tk.Button(self.root, text="Localizar vídeo", command=self.locate) <NEW_LINE> self.locate_button.grid(row=1, column=1) <NEW_LINE> self.info = tk.Label(self.root) <NEW_LINE> self.info.grid(row=2, column=0) <NEW_LINE> self.type_label = tk.Label(self.root, text="Selecione o tipo:") <NEW_LINE> self.type_label.grid(row=3, column=0) <NEW_LINE> audio = tk.Radiobutton(self.root, text="Áudio", variable=self.download_type, value=0) <NEW_LINE> audio.grid(row=4, column=0) <NEW_LINE> video = tk.Radiobutton(self.root, text="Vídeo", variable=self.download_type, value=1) <NEW_LINE> video.grid(row=5, column=0) <NEW_LINE> self.download_button = tk.Button(self.root, text="Iniciar download", state="disabled", command=self.download) <NEW_LINE> self.download_button.grid(row=6, column=0) <NEW_LINE> self.author = tk.Label(self.root, text="By TheGuilherme") <NEW_LINE> self.author.grid(row=7, column=6) <NEW_LINE> <DEDENT> def locate(self): <NEW_LINE> <INDENT> global video_object <NEW_LINE> try: <NEW_LINE> <INDENT> video_object = YouTube(self.url_entry.get()) <NEW_LINE> self.info.configure(text=f"Video title: {video_object.title}", fg="blue") <NEW_LINE> <DEDENT> except RegexMatchError: <NEW_LINE> <INDENT> self.info.configure(text="Error: Incorrect URL!", fg="red") <NEW_LINE> return <NEW_LINE> <DEDENT> self.download_button.configure(state="normal") <NEW_LINE> <DEDENT> def download(self): <NEW_LINE> <INDENT> if self.download_type.get() == 0: <NEW_LINE> <INDENT> video_stream = video_object.streams.filter(only_audio=True).first() <NEW_LINE> <DEDENT> if self.download_type.get() == 1: <NEW_LINE> <INDENT> video_stream = video_object.streams.filter(only_video=True).first() <NEW_LINE> <DEDENT> self.info.configure(text="Baixando...", fg="blue") <NEW_LINE> video_stream.download(self.download_location) <NEW_LINE> self.info.configure(text="Pronto!")
Constructor containing tkinter styles and settings.
6259907897e22403b383c8ba
class ProductTypeSerializer(serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = ProductType <NEW_LINE> fields = ('id', 'label', 'url');
Creates ProductType Serializer @rtwhitfield84
62599078460517430c432d36
class ControlWindow(tkinter.Frame): <NEW_LINE> <INDENT> def __init__(self, parent_win, master): <NEW_LINE> <INDENT> self.root = master <NEW_LINE> self.parent_win = parent_win <NEW_LINE> w = self.root.winfo_screenwidth() <NEW_LINE> h = self.root.winfo_screenheight() * 0.06 <NEW_LINE> x = WIN10PADDING <NEW_LINE> y = self.root.winfo_screenheight() * 0.84 <NEW_LINE> self.root.geometry('%dx%d+%d+%d' % (w, h, x, y)) <NEW_LINE> self.controlVar = tkinter.StringVar() <NEW_LINE> self.switchButton = tkinter.Button(self.root, text="Next Var", command=self.local_switchButtonClick) <NEW_LINE> self.refreshButton = tkinter.Button(self.root, text="Refresh", command=self.local_refreshButtonClick) <NEW_LINE> self.label = tkinter.Label(self.root, textvariable=self.controlVar) <NEW_LINE> self.canvas = tkinter.Canvas(self.root, width=100, height=100) <NEW_LINE> self.imageOnCanvas = self.canvas.create_image(0, 0) <NEW_LINE> self.coordVar = tkinter.StringVar() <NEW_LINE> self.coordLabel = tkinter.Label(self.root, textvariable = self.coordVar) <NEW_LINE> self.leftCoordVar = tkinter.StringVar() <NEW_LINE> self.topCoordVar = tkinter.StringVar() <NEW_LINE> self.rightCoordVar = tkinter.StringVar() <NEW_LINE> self.bottomCoordVar = tkinter.StringVar() <NEW_LINE> self.leftText = tkinter.Entry(self.root, textvariable= self.leftCoordVar) <NEW_LINE> self.topText = tkinter.Entry(self.root, textvariable= self.topCoordVar) <NEW_LINE> self.rightText = tkinter.Entry(self.root, textvariable= self.rightCoordVar) <NEW_LINE> self.bottomText = tkinter.Entry(self.root, textvariable= self.bottomCoordVar) <NEW_LINE> self.moveButton = tkinter.Button(self.root, text="Move", command=self.local_moveButtonClick) <NEW_LINE> self.switchButton.pack(side="left") <NEW_LINE> self.refreshButton.pack(side="left") <NEW_LINE> self.moveButton.pack(side="left") <NEW_LINE> self.label.pack(side="left") <NEW_LINE> self.canvas.pack(side="left") <NEW_LINE> self.coordLabel.pack(side="left") <NEW_LINE> self.leftText.pack(side="left") <NEW_LINE> self.topText.pack(side="left") <NEW_LINE> self.rightText.pack(side="left") <NEW_LINE> self.bottomText.pack(side="left") <NEW_LINE> self.local_setcurrvarvalues(0) <NEW_LINE> <DEDENT> def local_switchButtonClick(self): <NEW_LINE> <INDENT> switchButtonClick(self) <NEW_LINE> <DEDENT> def local_refreshButtonClick(self): <NEW_LINE> <INDENT> refreshButtonClick(self) <NEW_LINE> <DEDENT> def local_setcurrvarvalues(self, ind): <NEW_LINE> <INDENT> setcurrvarvalues(self, self.parent_win, ind) <NEW_LINE> <DEDENT> def local_moveButtonClick(self): <NEW_LINE> <INDENT> if self.rightText.get() == '-': <NEW_LINE> <INDENT> moveButtonClick(self, [int(self.leftText.get()) - 10, int(self.topText.get()) - 10, int(self.leftText.get()) + 10, int(self.topText.get()) + 10], 'adj') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> moveButtonClick(self, [int(self.leftText.get()), int(self.topText.get()), int(self.rightText.get()), int(self.bottomText.get())], 'adj')
Control window to contain variable name and picture preview
625990784527f215b58eb67d
class MyDistribution(Distribution): <NEW_LINE> <INDENT> global_options = Distribution.global_options + [ ('disable-ext', None, 'Disable building extensions.') ] <NEW_LINE> def finalize_options(self): <NEW_LINE> <INDENT> Distribution.finalize_options(self) <NEW_LINE> try: <NEW_LINE> <INDENT> i = self.script_args.index('--disable-ext') <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.disable_ext = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.disable_ext = True <NEW_LINE> self.script_args.pop(i)
This seems to be is the only obvious way to add a global option to distutils. Provide the ability to disable building the extensions for any called command.
6259907855399d3f05627ecd
class Users(APIView): <NEW_LINE> <INDENT> authentication_classes = (SessionAuthentication, BasicAuthentication) <NEW_LINE> permission_classes = (IsAuthenticated, IsAdminUser,) <NEW_LINE> parser_classes = (JSONParser,) <NEW_LINE> def get(self, request, format=None): <NEW_LINE> <INDENT> users = User.objects.all() <NEW_LINE> serializer = UserSerializer(users, many=True) <NEW_LINE> return Response(serializer.data)
List all users.
6259907860cbc95b06365a4a
class EnterpriseCustomerEntitlementViewSet(EnterpriseReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = models.EnterpriseCustomerEntitlement.objects.all() <NEW_LINE> serializer_class = serializers.EnterpriseCustomerEntitlementSerializer <NEW_LINE> USER_ID_FILTER = 'enterprise_customer__enterprise_customer_users__user_id' <NEW_LINE> FIELDS = ( 'enterprise_customer', 'entitlement_id', ) <NEW_LINE> filter_fields = FIELDS <NEW_LINE> ordering_fields = FIELDS
API views for the ``enterprise-customer-entitlements`` API endpoint.
62599078ec188e330fdfa261
class DispatchAgregation(object): <NEW_LINE> <INDENT> def __init__(self, dispatch, moves_by_loc): <NEW_LINE> <INDENT> self.dispatch_id = dispatch <NEW_LINE> self.moves_by_loc = moves_by_loc <NEW_LINE> <DEDENT> @property <NEW_LINE> def picker_id(self): <NEW_LINE> <INDENT> return self.dispatch_id.picker_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def dispatch_name(self): <NEW_LINE> <INDENT> return self.dispatch_id.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def dispatch_notes(self): <NEW_LINE> <INDENT> return self.dispatch_id.notes or u'' <NEW_LINE> <DEDENT> def exists(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.dispatch_id.id) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (self.dispatch_id.id == other.dispatch_id.id) <NEW_LINE> <DEDENT> def iter_locations(self): <NEW_LINE> <INDENT> for locations in self.moves_by_loc: <NEW_LINE> <INDENT> offset = commonprefix(locations).rfind('/') + 1 <NEW_LINE> display_locations = tuple(loc[offset:].strip() for loc in locations) <NEW_LINE> yield display_locations, self._product_quantity(locations) <NEW_LINE> <DEDENT> <DEDENT> def _product_quantity(self, locations): <NEW_LINE> <INDENT> products = {} <NEW_LINE> product_qty = {} <NEW_LINE> carrier = {} <NEW_LINE> moves = self.moves_by_loc[locations] <NEW_LINE> _logger.debug('move ids %s', moves) <NEW_LINE> for move in moves: <NEW_LINE> <INDENT> p_code = move.product_id.default_code <NEW_LINE> products[p_code] = move.product_id <NEW_LINE> carrier[p_code] = move.picking_id.carrier_id and move.picking_id.carrier_id.partner_id.name or '' <NEW_LINE> if p_code not in product_qty: <NEW_LINE> <INDENT> product_qty[p_code] = move.product_qty <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> product_qty[p_code] += move.product_qty <NEW_LINE> <DEDENT> <DEDENT> for p_code in sorted(products): <NEW_LINE> <INDENT> yield products[p_code], product_qty[p_code], carrier[p_code]
group moves from a single dispatch by source and dest locations
6259907876e4537e8c3f0f39
class Item: <NEW_LINE> <INDENT> def __init__ (self, position): <NEW_LINE> <INDENT> self.pos_x = position[0] <NEW_LINE> self.pos_y = position[1] <NEW_LINE> self.visible = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def sprite_position(self): <NEW_LINE> <INDENT> return (self.pos_x * TILE_SIZE, self.pos_y * TILE_SIZE)
Creat an item with position
62599078e1aae11d1e7cf4ed
class SessionToken(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'authn_session_tokens' <NEW_LINE> user_id = db.Column(db.Uuid, db.ForeignKey('users.id'), primary_key=True) <NEW_LINE> token = db.Column(db.UnicodeText, unique=True, index=True, nullable=False) <NEW_LINE> created_at = db.Column(db.DateTime, nullable=False) <NEW_LINE> def __init__( self, user_id: UserID, token: str, created_at: datetime ) -> None: <NEW_LINE> <INDENT> self.user_id = user_id <NEW_LINE> self.token = token <NEW_LINE> self.created_at = created_at
A user's session token.
625990787047854f46340d75
class Scorer(object): <NEW_LINE> <INDENT> def rescore(self, thing, score): <NEW_LINE> <INDENT> raise NotImplementedError("cannot instantiate Abstract Base Class")
Implementations of this interface computes a new 'score' to a object such as an ID of an item or user which a Recommender is considering returning as a top recommendation.
625990781f5feb6acb1645b1
class MySocket: <NEW_LINE> <INDENT> def __init__(self, sock=None,verb=False,timeout=10): <NEW_LINE> <INDENT> self.verb = verb <NEW_LINE> if sock is None: <NEW_LINE> <INDENT> self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sock = sock <NEW_LINE> <DEDENT> self.sock.settimeout(timeout) <NEW_LINE> <DEDENT> def connect(self, host, port): <NEW_LINE> <INDENT> self.sock.connect((host, port)) <NEW_LINE> <DEDENT> def mysend(self, msg): <NEW_LINE> <INDENT> totalsent = 0 <NEW_LINE> while totalsent < MSGLEN: <NEW_LINE> <INDENT> sent = self.sock.send(msg[totalsent:]) <NEW_LINE> if sent == 0: <NEW_LINE> <INDENT> self.sock.send(b'#EOT') <NEW_LINE> if self.verb: <NEW_LINE> <INDENT> print("Socket send: Message finished") <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> totalsent = totalsent + sent <NEW_LINE> time.sleep(0.1) <NEW_LINE> <DEDENT> <DEDENT> def myreceive(self): <NEW_LINE> <INDENT> chunks = [] <NEW_LINE> bytes_recd = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> while bytes_recd < MSGLEN: <NEW_LINE> <INDENT> chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048)) <NEW_LINE> print(chunk) <NEW_LINE> if chunk == b'#EOT': <NEW_LINE> <INDENT> if self.verb: <NEW_LINE> <INDENT> print("Socket receive: Message finished") <NEW_LINE> <DEDENT> return b''.join(chunks) <NEW_LINE> <DEDENT> elif chunk == b'': <NEW_LINE> <INDENT> print("Socket receive: Message broken?") <NEW_LINE> raise RuntimeError("socket connection broken") <NEW_LINE> return b''.join(chunks) <NEW_LINE> <DEDENT> chunks.append(chunk) <NEW_LINE> bytes_recd = bytes_recd + len(chunk) <NEW_LINE> <DEDENT> return b''.join(chunks) <NEW_LINE> <DEDENT> except ConnectionResetError as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> print('Connection reset, returned "None"') <NEW_LINE> return None <NEW_LINE> <DEDENT> except socket.timeout as err: <NEW_LINE> <INDENT> print('Receive timed out: ',err) <NEW_LINE> return None
Socket class The original comment on the example this is base on was: ``demonstration class only - coded for clarity, not efficiency``
625990785fdd1c0f98e5f938
class FileValidationError(Exception): <NEW_LINE> <INDENT> pass
An exception to indicate that a data file has failed validation.
62599078097d151d1a2c2a31
class LocationFields(IntEnum): <NEW_LINE> <INDENT> Location = 0x85
The matching criteria which take a Location, as defined above
62599078442bda511e95da35
class TestScanBlackoutSchedule(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 testScanBlackoutSchedule(self): <NEW_LINE> <INDENT> pass
ScanBlackoutSchedule unit test stubs
6259907897e22403b383c8bd
class TestConfig(BaseConfig): <NEW_LINE> <INDENT> TESTING = True <NEW_LINE> BASE_DIR = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'test.db') <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> WTF_CSRF_ENABLED = False <NEW_LINE> LOGIN_DISABLED = True <NEW_LINE> BCRYPT_LOG_ROUNDS = 4
Configuration for general testing
62599078fff4ab517ebcf1d2
class RigesterForm(forms.ModelForm): <NEW_LINE> <INDENT> password1 = forms.CharField(label='Password', widget=forms.PasswordInput) <NEW_LINE> password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('username', 'email',) <NEW_LINE> <DEDENT> def clean_password2(self): <NEW_LINE> <INDENT> password1 = self.cleaned_data.get("password1") <NEW_LINE> password2 = self.cleaned_data.get("password2") <NEW_LINE> if password1 and password2 and password1 != password2: <NEW_LINE> <INDENT> raise forms.ValidationError("Passwords don't match") <NEW_LINE> <DEDENT> return password2 <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> user = super(RigesterForm, self).save(commit=False) <NEW_LINE> user.set_password(self.cleaned_data["password1"]) <NEW_LINE> if commit: <NEW_LINE> <INDENT> user.save() <NEW_LINE> <DEDENT> return user
A form for creating new users. Includes all the required fields, plus a repeated password.
625990787047854f46340d76
class Detector(six.with_metaclass(ABCMeta, object)): <NEW_LINE> <INDENT> def __init__(self, SE_size_factor=0.15, lam_factor=5, area_factor=0.05, connectivity=4): <NEW_LINE> <INDENT> self.SE_size_factor = SE_size_factor <NEW_LINE> self.lam_factor = lam_factor <NEW_LINE> self.area_factor = area_factor <NEW_LINE> self.connectivity = connectivity <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def detect(self, img): <NEW_LINE> <INDENT> nrows, ncols = img.shape[0], img.shape[1] <NEW_LINE> self.get_SE(nrows * ncols) <NEW_LINE> <DEDENT> def get_SE(self, imgsize): <NEW_LINE> <INDENT> SE_size = int(np.floor(self.SE_size_factor * np.sqrt(imgsize / np.pi))) <NEW_LINE> SE_dim_size = SE_size * 2 - 1 <NEW_LINE> self.SE = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (SE_dim_size, SE_dim_size)) <NEW_LINE> self.lam = self.lam_factor * SE_size <NEW_LINE> return self.SE, self.lam
Abstract class for salient region detectors. Parameters ------ SE_size_factor: float, optional The fraction of the image size that the structuring element should be lam_factor : float, optional The factor of lambda compared to the SE size area_factor: float, optional factor that describes the minimum area of a significent CC connectivity: int What connectivity to use to define CCs
62599078283ffb24f3cf525c
class Primitive: <NEW_LINE> <INDENT> def __init__(self, is_additive, rotation, shape): <NEW_LINE> <INDENT> self.is_additive = is_additive <NEW_LINE> self.rotation = rotation <NEW_LINE> self.shape = shape <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (self.is_additive == other.is_additive and self.rotation == other.rotation and self.shape == other.shape)
A shape with rotation and exposure modifiers.
62599078283ffb24f3cf525d
class NegativeHandler(object): <NEW_LINE> <INDENT> def __init__(self, matcher, actual, *args, **kwargs): <NEW_LINE> <INDENT> self.actual = actual <NEW_LINE> self.matcher = matcher <NEW_LINE> self.args = args <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def resolve(self): <NEW_LINE> <INDENT> if self.matcher.matches(self.actual, *self.args, **self.kwargs): <NEW_LINE> <INDENT> self.handle_failure() <NEW_LINE> <DEDENT> <DEDENT> def handle_failure(self): <NEW_LINE> <INDENT> raise ExpectationNotMetError(self.matcher.failure_message_when_negated)
Used to resolve match of actual against a matcher and propogate a failure if it does.
625990782c8b7c6e89bd51a6
class ErrorMock(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.msg = None <NEW_LINE> <DEDENT> def error(self, msg): <NEW_LINE> <INDENT> self.msg = msg
Error handling
6259907855399d3f05627ecf
class MenuGlyph(Enum,IComparable,IFormattable,IConvertible): <NEW_LINE> <INDENT> def __eq__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __format__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Arrow=None <NEW_LINE> Bullet=None <NEW_LINE> Checkmark=None <NEW_LINE> Max=None <NEW_LINE> Min=None <NEW_LINE> value__=None
Specifies the image to draw when drawing a menu with the System.Windows.Forms.ControlPaint.DrawMenuGlyph(System.Drawing.Graphics,System.Drawing.Rectangle,System.Windows.Forms.MenuGlyph) method. enum MenuGlyph,values: Arrow (0),Bullet (2),Checkmark (1),Max (2),Min (0)
62599078ec188e330fdfa263