init

Here are the examples of how to init in python. These are taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

98109 Examples 7

    def __init__(self, vendorDir, aospDir, bospDir, mergedDir):
        '''
        Constructor
        '''
        self.mVSLib = LibUtils.getSmaliLib(vendorDir)
        self.mASLib = LibUtils.getSmaliLib(aospDir)
        self.mBSLib = LibUtils.getSmaliLib(bospDir)
        self.mMSLib = LibUtils.getSmaliLib(mergedDir)

    def __init(self):
        winsz = fcntl.ioctl(self.fd, termios.TIOCGWINSZ, "        ")
        rows, cols, xpixel, ypixel = struct.unpack('HHHH', winsz)
        self.rows = rows
        self.cols = cols
        self.old = termios.tcgetattr(self.fd)

        def __init(self):
            Script.__init__(self,
                            name="Mammal Super Tree",
                            shortname='mammsupertree',
                            retriever_minimum_version='2.0.dev',
                            version='1.0')

    def __init(self, world, name, image_string="Inn"):
        GameEntity.__init__(self, world, name, "Buildings/"+image_string)

        self.image_funcs = ImageFuncs(32, 32, pygame.image.load("Images/Buildings/TotalImage.png"))
        self.tile_x, self.tile_y = pos
        self.cost = 100
        get_images(name)
        
        self.can_drop_food = False
        self.can_drop_wood = False

  def __init(self):
    self.checkBoxHideCross.setEnabled(False)
    self.__populateTypeMapGUI()
    self.__populateButtonBox()
    self.__registerObjJS()
    self.lbStatusRead.setVisible( False )
    self.__setConnections()
    # Proxy
    proxy = getProxy()
    if not proxy is None:
      self.__manager = QNetworkAccessManager()
      self.__manager.setProxy(proxy)
      self.webViewMap.page().setNetworkAccessManager(self.__manager)

    self.__timerMapReady = QTimer()
    self.__timerMapReady.setSingleShot(True)
    self.__timerMapReady.setInterval(20)
    self.__timerMapReady.timeout.connect(self.__checkMapReady)

	def __init__(self, fileOrPath, ttFont, progress=None, quiet=None):
		if fileOrPath == '-':
			fileOrPath = sys.stdin
		if not hasattr(fileOrPath, "read"):
			self.file = open(fileOrPath, "rb")
			self._closeStream = True
		else:
			# assume readable file object
			self.file = fileOrPath
			self._closeStream = False
		self.ttFont = ttFont
		self.progress = progress
		if quiet is not None:
			from fontTools.misc.loggingTools import deprecateArgument
			deprecateArgument("quiet", "configure logging instead")
			self.quiet = quiet
		self.root = None
		self.contentStack = []
		self.stackSize = 0

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})

        self.parser = Parser()
        self.parser.set_delim("[ \t]+")
        self.parser.set_new_delim("\t")
        self.parser.set_comment("#")
        self.base_parser_name = self.parser.__class__.__name__
        pass

    def __init__(self):
        # To control operation entries
        self.order = None

        # Create SMA on 2nd data
        sma = btind.MovAv.SMA(self.data, period=self.p.period)
        # Create a CrossOver Signal from close an moving average
        self.signal = btind.CrossOver(self.data.close, sma)

        # To alternate amongst different tradeids
        if self.p.mtrade:
            self.tradeid = itertools.cycle([0, 1, 2])
        else:
            self.tradeid = itertools.cycle([0])

    def __init(self):
        self.testrepo = TESTREPO
        self.testuser = TESTUSER
        (self.connectors, self._defaults) = get_login_info()
        for env in get_environments():
            # remove user
            users = self.connectors[env].get('/users/')
            for user in users:
                if user['login'] == self.testuser:
                    self.connectors[env].delete('/users/%s/' % self.testuser)
                    # remove repo
                    self.connectors[env].delete('/repositories/%s/' % self.testrepo)

        super(TestJuicerAdmin, self).__init__()

    def __init__(self, *args, **keys):
        bot.ServiceBot.__init__(self, *args, **keys)

        self._rooms = taskfarm.TaskFarm(self._handle_room, grace_period=0.0)
        self._srcs = {}
        self._ready = idiokit.Event()
        self._stats = {}

    def __init__(self, accounts=None, timeout=None, spec=None):
        if accounts is None:
            accounts = {}
        self.accounts = dict(((host, int(port)), account)
                             for (host, port), account in accounts.items())
        if spec is None:
            spec = pyzor.digest.digest_spec
        self.spec = spec
        if timeout is not None:
            self.timeout = timeout
        self.log = logging.getLogger("pyzor")

    def __init(self, rpm_package):

        for path in [self.prefix, self.SOURCES_dir, self.SPECS_dir,
                     self.BUILD_dir, self.BUILDROOT_dir, self.RPMS_dir,
                     self.src_dir, self.results_dir, self.log_dir]:
            utils.system('rm -rf ' + path)
            os.mkdir(path)

        utils.system('rpm -ivh %s' % rpm_package)

    def __init__ (self, parent):
        HtmlRender.__init__ (self, parent)

        self.render = wx.lib.iewin.IEHtmlWindow (self)
        self.render.silent = 1

        # Подпишемся на события IE
        self.render.AddEventSink(self)

        self.canOpenUrl = False                # Можно ли открывать ссылки

        self.__layout()

        self.Bind (wx.EVT_MENU, self.__onCopyFromHtml, id = wx.ID_COPY)
        self.Bind (wx.EVT_MENU, self.__onCopyFromHtml, id = wx.ID_CUT)

    def __init__(self, description):
        import ipywidgets as ipy
        import traitlets
        try:
            self.progress_bar = ipy.FloatProgress(0, min=0, max=100, description=description)
        except traitlets.TraitError:
            self.progress_bar = None

    def __init__(self, irc):
        self.__parent = super(Ctcp, self)
        self.__parent.__init__(irc)
        self.ignores = ircutils.IrcDict()
        self.floods = ircutils.FloodQueue(conf.supybot.abuse.flood.interval())
        conf.supybot.abuse.flood.interval.addCallback(self.setFloodQueueTimeout)

3
File: socks.py, Project: genpac, View license
uses: socket.SOCK_STREAM
    def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM,
                 proto=0, _sock=None):
        if type not in {socket.SOCK_STREAM, socket.SOCK_DGRAM}:
            msg = "Socket type must be stream or datagram, not {!r}"
            raise ValueError(msg.format(type))

        _BaseSocket.__init__(self, family, type, proto, _sock)
        self._proxyconn = None  # TCP connection to keep UDP relay alive

        if self.default_proxy:
            self.proxy = self.default_proxy
        else:
            self.proxy = (None, None, None, None, None, None)
        self.proxy_sockname = None
        self.proxy_peername = None

  def __init__(self, httpd, pkite, conns):
    self.httpd = httpd
    self.pkite = pkite
    self.conns = conns
    self.modified = False

    self.lock = threading.Lock()
    self.request = None

    # For now, nobody gets ACL_WRITE
    self.auth_tokens = {httpd.secret: self.ACL_READ}

    # Channels are in-memory logs which can be tailed over XML-RPC.
    # Javascript apps can create these for implementing chat etc.
    self.channels = {'LOG': {'access': self.ACL_READ,
                             'tokens': self.auth_tokens,
                             'data': logging.LOG}}

    def __init__(self, options, platform):
        self.options = options
        self.platform = platform
        self.inventorycfg = options['inventory_path']
        self.logger = get_logger(options.get('logfile'), options.get('loglevel'))
        self.cparser = configparser.ConfigParser(allow_no_value=True)
        self.inventory = {'all': {'hosts': []},
                          'kube-master': {'hosts': []},
                          'etcd': {'hosts': []},
                          'kube-node': {'hosts': []},
                          'k8s-cluster:children': {'hosts': [
                              {'hostname': 'kube-node', 'hostvars': []},
                              {'hostname': 'kube-master', 'hostvars': []}
                          ]},
                          }

    def __init__(self, app):
        super().__init__(app)
        self._app = app
        self._stalled_timer = QTimer(self)

        self.error.connect(self.on_error_occured)
        self.mediaChanged.connect(self.on_media_changed)
        self.mediaStatusChanged.connect(self.on_media_status_changed)
        self._stalled_timer.timeout.connect(self._wait_to_seek_back)

        self._music_error_times = 0
        self._retry_latency = 3
        self._music_error_maximum = 3

        self._media_stalled = False

	def __init__(self, frmwk):
		self.frmwk = frmwk

		self.name = 'unknown'
		self.version = 0
		self.author = ['anonymous']
		self.description = 'This module is undocuemented.'
		self.detailed_description = 'This module is undocuemented.'
		self.options = Options(frmwk.directories)
		self.advanced_options = AdvancedOptions(frmwk.directories)

def __init():
    global packb
    global unpackb
    global compatibility
    global _float_size
    global _unpack_dispatch_table

    # Compatibility mode for handling strings/bytes with the old specification
    compatibility = False

    # Auto-detect system float precision
    if sys.float_info.mant_dig == 53:
        _float_size = 64
    else:
        _float_size = 32

    # Map packb and unpackb to the appropriate version
    if sys.version_info[0] == 3:
        packb = _packb3
        unpackb = _unpackb3
    else:
        packb = _packb2
        unpackb = _unpackb2

    # Build a dispatch table for fast lookup of unpacking function

    _unpack_dispatch_table = {}
    # Fix uint
    for code in range(0, 0x7f+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
    # Fix map
    for code in range(0x80, 0x8f+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_map
    # Fix array
    for code in range(0x90, 0x9f+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_array
    # Fix str
    for code in range(0xa0, 0xbf+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_string
    # Nil
    _unpack_dispatch_table[b'\xc0'] = _unpack_nil
    # Reserved
    _unpack_dispatch_table[b'\xc1'] = _unpack_reserved
    # Boolean
    _unpack_dispatch_table[b'\xc2'] = _unpack_boolean
    _unpack_dispatch_table[b'\xc3'] = _unpack_boolean
    # Bin
    for code in range(0xc4, 0xc6+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_binary
    # Ext
    for code in range(0xc7, 0xc9+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_ext
    # Float
    _unpack_dispatch_table[b'\xca'] = _unpack_float
    _unpack_dispatch_table[b'\xcb'] = _unpack_float
    # Uint
    for code in range(0xcc, 0xcf+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
    # Int
    for code in range(0xd0, 0xd3+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
    # Fixext
    for code in range(0xd4, 0xd8+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_ext
    # String
    for code in range(0xd9, 0xdb+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_string
    # Array
    _unpack_dispatch_table[b'\xdc'] = _unpack_array
    _unpack_dispatch_table[b'\xdd'] = _unpack_array
    # Map
    _unpack_dispatch_table[b'\xde'] = _unpack_map
    _unpack_dispatch_table[b'\xdf'] = _unpack_map
    # Negative fixint
    for code in range(0xe0, 0xff+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer

    def __init__(self, config):
        GObject.GObject.__init__(self)
        self.commands = {}

        # Configure Audio Source
        src = config.options.microphone
        if src:
            audio_src = 'alsasrc device="hw:{0},0"'.format(src)
        else:
            audio_src = 'autoaudiosrc'

        # Build Pipeline
        cmd = (
            audio_src +
            ' ! audioconvert' +
            ' ! audioresample' +
            ' ! pocketsphinx lm=' + config.lang_file + ' dict=' +
            config.dic_file +
            ' ! appsink sync=false'
        )
        try:
            self.pipeline = Gst.parse_launch(cmd)
        except Exception as e:
            print(e.message)
            print("You may need to install gstreamer1.0-pocketsphinx")
            raise e

        # Process Results From Pipeline With 'self.result()'
        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect('message::element', self.result)

  def __Init(self):



    self.__connection.execute('PRAGMA synchronous = OFF')


    self.__connection.executescript(_CORE_SCHEMA)
    self.__connection.commit()


    c = self.__connection.execute('SELECT app_id, name_space FROM Namespaces')
    self.__namespaces = set(c.fetchall())


    for app_ns in self.__namespaces:
      prefix = ('%s!%s' % app_ns).replace('"', '""')
      self.__connection.execute(
          'INSERT OR IGNORE INTO ScatteredIdCounters VALUES (?, ?)',
          (prefix, 1))
    self.__connection.commit()

    c = self.__connection.execute(
        'SELECT commit_timestamp FROM CommitTimestamps WHERE prefix = ""')
    row = c.fetchone()
    if row:
      self._commit_timestamp = row[0]



    c = self.__connection.execute('SELECT app_id, indexes FROM Apps')
    for _, index_proto in c.fetchall():
      if not index_proto:
        continue
      indexes = datastore_pb.CompositeIndices(index_proto)
      for index in indexes.index_list():
        self._SideLoadIndex(index)

    def __init(self, parent):
        QLabel.__init__(self, parent)

    def __init__(self, client):
        TaskManagerEventListener.__init__(self)
        self.client = client

0
File: muccore.py, Project: pyxmpp, View license
uses: pyxmpp.jid.JID
    def __init(self,affiliation,role,jid=None,nick=None,actor=None,reason=None):
        """Initialize a `MucItem` object from a set of attributes.

        :Parameters:
            - `affiliation`: affiliation of the user.
            - `role`: role of the user.
            - `jid`: JID of the user.
            - `nick`: nickname of the user.
            - `actor`: actor modyfying the user data.
            - `reason`: reason of change of the user data.
        :Types:
            - `affiliation`: `str`
            - `role`: `str`
            - `jid`: `JID`
            - `nick`: `unicode`
            - `actor`: `JID`
            - `reason`: `unicode`
        """
        if not affiliation:
            affiliation=None
        elif affiliation not in affiliations:
            raise ValueError,"Bad affiliation"
        self.affiliation=affiliation
        if not role:
            role=None
        elif role not in roles:
            raise ValueError,"Bad role"
        self.role=role
        if jid:
            self.jid=JID(jid)
        else:
            self.jid=None
        if actor:
            self.actor=JID(actor)
        else:
            self.actor=None
        self.nick=nick
        self.reason=reason

    def __init__(self):
        JSONProxy.__init__(self, "services/EchoService.py",
                                    ["index"])

    def __init(self):
        """
            Init widget content if needed
        """
        if self.__button is not None:
            return
        self.__stack = Gtk.Stack()
        self.__stack.set_transition_duration(500)
        self.__stack.set_transition_type(Gtk.StackTransitionType.CROSSFADE)
        self.__button = Gtk.Button.new()
        self.__image = Gtk.Image.new()
        self.__button.set_image(self.__image)
        self.__button.set_relief(Gtk.ReliefStyle.NONE)
        self.__button.get_style_context().add_class('menu-button')
        self.__button.get_style_context().add_class('track-menu-button')
        self.__image.set_opacity(0.2)
        self.__button.show()
        self.__button.connect('clicked', self.__on_button_clicked)
        play = Gtk.Image.new_from_icon_name('media-playback-start-symbolic',
                                            Gtk.IconSize.MENU)
        loved = Gtk.Image.new_from_icon_name('emblem-favorite-symbolic',
                                             Gtk.IconSize.MENU)
        self.__stack.add_named(self.__button, 'button')
        self.__stack.add_named(play, 'play')
        self.__stack.add_named(loved, 'loved')
        self.add(self.__stack)
        self.connect('enter-notify-event', self.__on_enter_notify)
        self.connect('leave-notify-event', self.__on_leave_notify)
        self.show_all()

    def __init__(self, short_name, full_name, owners, categories,
                 added_default=None, added_mandatory=None,
                 node_settings_model=None, user_settings_model=None, include_js=None, include_css=None,
                 widget_help=None, views=None, configs=None, models=None,
                 has_hgrid_files=False, get_hgrid_data=None, max_file_size=None, high_max_file_size=None,
                 accept_extensions=True, description='', url=None,
                 node_settings_template=None, user_settings_template=None,
                 **kwargs):

        self.models = models
        self.settings_models = {}

        if node_settings_model:
            node_settings_model.config = self
            self.settings_models['node'] = node_settings_model

        if user_settings_model:
            user_settings_model.config = self
            self.settings_models['user'] = user_settings_model

        self.short_name = short_name
        self.full_name = full_name
        self.description = description
        self.url = url
        self.owners = owners
        self.categories = categories

        self.added_default = added_default or []
        self.added_mandatory = added_mandatory or []
        if set(self.added_mandatory).difference(self.added_default):
            raise ValueError('All mandatory targets must also be defaults.')

        self.include_js = self._include_to_static(include_js or {})
        self.include_css = self._include_to_static(include_css or {})

        self.widget_help = widget_help

        self.views = views or []
        self.configs = configs or []

        self.has_hgrid_files = has_hgrid_files
        # WARNING: get_hgrid_data can return None if the addon is added but has no credentials.
        self.get_hgrid_data = get_hgrid_data  # if has_hgrid_files and not get_hgrid_data rubeus.make_dummy()
        self.max_file_size = max_file_size
        self.high_max_file_size = high_max_file_size
        self.accept_extensions = accept_extensions

        # Provide the path the the user_settings template
        self.user_settings_template = user_settings_template
        if not user_settings_template or not os.path.exists(os.path.dirname(user_settings_template)):
            # Use the default template (ATM for OAuth addons)
            self.user_settings_template = USER_SETTINGS_TEMPLATE_DEFAULT

        # Provide the path the the node_settings template
        self.node_settings_template = node_settings_template
        if not node_settings_template or not os.path.exists(os.path.dirname(node_settings_template)):
            # Use the default template
            self.node_settings_template = NODE_SETTINGS_TEMPLATE_DEFAULT

        # Build template lookup
        template_dirs = list(
            set(
                [
                    path
                    for path in [os.path.dirname(self.user_settings_template), os.path.dirname(self.node_settings_template), settings.TEMPLATES_PATH]
                    if os.path.exists(path)
                ]
            )
        )
        if template_dirs:
            self.template_lookup = TemplateLookup(
                directories=template_dirs,
                default_filters=[
                    'unicode',  # default filter; must set explicitly when overriding
                    'temp_ampersand_fixer',
                    # FIXME: Temporary workaround for data stored in wrong format in DB. Unescape it before it gets re-escaped by Markupsafe. See [#OSF-4432]
                    'h',
                ],
                imports=[
                    'from website.util.sanitize import temp_ampersand_fixer',
                    # FIXME: Temporary workaround for data stored in wrong format in DB. Unescape it before it gets re-escaped by Markupsafe. See [#OSF-4432]
                ]
            )
        else:
            self.template_lookup = None

    def __init__(self, text=None):
        QPushButton.__init__(self, text)

    def __init__(self, name):

        """
        Define the special help messages after instantiating a `click.Command()`.
        """

        click.Command.__init__(self, name)

        util_name = os.path.basename(sys.argv and sys.argv[0] or __file__)

        if os.environ.get('CLICK_PLUGINS_HONESTLY'):  # pragma no cover
            icon = u'\U0001F4A9'
        else:
            icon = u'\u2020'

        self.help = (
            "\nWarning: entry point could not be loaded. Contact "
            "its author for help.\n\n\b\n"
            + traceback.format_exc())
        self.short_help = (
            icon + " Warning: could not load plugin. See `%s %s --help`."
            % (util_name, self.name))

  def __Init(self):



    self.__connection.execute('PRAGMA synchronous = OFF')


    self.__connection.executescript(_CORE_SCHEMA)
    self.__connection.commit()


    c = self.__connection.execute('SELECT app_id, name_space FROM Namespaces')
    self.__namespaces = set(c.fetchall())


    for app_ns in self.__namespaces:
      prefix = ('%s!%s' % app_ns).replace('"', '""')
      self.__connection.execute(
          'INSERT OR IGNORE INTO ScatteredIdCounters VALUES (?, ?)',
          (prefix, 1))
    self.__connection.commit()



    c = self.__connection.execute('SELECT app_id, indexes FROM Apps')
    for _, index_proto in c.fetchall():
      if not index_proto:
        continue
      indexes = datastore_pb.CompositeIndices(index_proto)
      for index in indexes.index_list():
        self._SideLoadIndex(index)

    def __init__(self, master, window, **kw):
        ttk.Frame.__init__(self, master, **kw)
        self.window = window

        self.columnconfigure(1, weight=1)
        self.rowconfigure(1, weight=1)

        self.tree = ttk.Treeview(self,
                                 columns=('name', 'location'),
                                 displaycolumns=('name', 'location'),
                                 height=20,
                                 selectmode='browse',
                                 show='headings')

        self.tree.heading('name', text='name', anchor='w')
        self.tree.column('name', width=200, anchor='w')
        self.tree.heading('location', text='location', anchor='w')
        self.tree.column('location', width=300, anchor='w')

        self.tree.grid(column=0, row=1, columnspan=2, sticky='nwes', pady=(6, 6))

        search_label = ttk.Label(self, text='search: ')
        search_label.grid(column=0, row=0, sticky='w')

        self.search = ttk.Entry(self, exportselection=False, validate='key',
                                validatecommand=(self.register(self._filterPrinters), '%P'))
        self.search.grid(column=1, row=0, sticky='we')

        self.add_button = ttk.Button(self, text='add this printer', command=self._invokeAddDialog)
        self.add_button.grid(column=1, row=2, sticky='e')

        self.search.bind('<Control-BackSpace>', self._clearQuery)
        self.search.bind('<Return>', self._invokeAddDialog)
        self.tree.bind('<Return>', self._invokeAddDialog)
        self.tree.bind('<Double-1>', self._invokeAddDialog)

        self._initPrinters()

    def __init(self, parent):
        QtGui.QLabel.__init__(self, parent)

def __init():
    global pack
    global packb
    global unpack
    global unpackb
    global dump
    global dumps
    global load
    global loads
    global compatibility
    global _float_size
    global _unpack_dispatch_table
    global xrange

    # Compatibility mode for handling strings/bytes with the old specification
    compatibility = False

    # Auto-detect system float precision
    if sys.float_info.mant_dig == 53:
        _float_size = 64
    else:
        _float_size = 32

    # Map packb and unpackb to the appropriate version
    if sys.version_info[0] == 3:
        pack = _pack3
        packb = _packb3
        dump = _pack3
        dumps = _packb3
        unpack = _unpack3
        unpackb = _unpackb3
        load = _unpack3
        loads = _unpackb3
        xrange = range
    else:
        pack = _pack2
        packb = _packb2
        dump = _pack2
        dumps = _packb2
        unpack = _unpack2
        unpackb = _unpackb2
        load = _unpack2
        loads = _unpackb2

    # Build a dispatch table for fast lookup of unpacking function

    _unpack_dispatch_table = {}
    # Fix uint
    for code in range(0, 0x7f+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
    # Fix map
    for code in range(0x80, 0x8f+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_map
    # Fix array
    for code in range(0x90, 0x9f+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_array
    # Fix str
    for code in range(0xa0, 0xbf+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_string
    # Nil
    _unpack_dispatch_table[b'\xc0'] = _unpack_nil
    # Reserved
    _unpack_dispatch_table[b'\xc1'] = _unpack_reserved
    # Boolean
    _unpack_dispatch_table[b'\xc2'] = _unpack_boolean
    _unpack_dispatch_table[b'\xc3'] = _unpack_boolean
    # Bin
    for code in range(0xc4, 0xc6+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_binary
    # Ext
    for code in range(0xc7, 0xc9+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_ext
    # Float
    _unpack_dispatch_table[b'\xca'] = _unpack_float
    _unpack_dispatch_table[b'\xcb'] = _unpack_float
    # Uint
    for code in range(0xcc, 0xcf+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
    # Int
    for code in range(0xd0, 0xd3+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
    # Fixext
    for code in range(0xd4, 0xd8+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_ext
    # String
    for code in range(0xd9, 0xdb+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_string
    # Array
    _unpack_dispatch_table[b'\xdc'] = _unpack_array
    _unpack_dispatch_table[b'\xdd'] = _unpack_array
    # Map
    _unpack_dispatch_table[b'\xde'] = _unpack_map
    _unpack_dispatch_table[b'\xdf'] = _unpack_map
    # Negative fixint
    for code in range(0xe0, 0xff+1):
        _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer

    def __init__(self, **kwargs):
        BaseElement.__init__(self, 'glyphRef')
        self.setKWARGS(**kwargs)

    def __init__(self, window_id, title, slot_count,
                 inv_type=None, persistent_slots=None, eid=None):
        assert not inv_type or inv_type == self.inv_type, \
            'inv_type differs: %s instead of %s' % (inv_type, self.inv_type)
        self.is_storage = slot_count > 0  # same after re-opening window
        if not self.is_storage:  # get number of temporary slots
            window_dict = windows_by_id[inv_type]
            if 'slots' in window_dict:
                slot_count = max(slot['index'] + slot.get('size', 1)
                                 for slot in window_dict['slots'])
        self.window_id = window_id
        self.title = title
        self.eid = eid  # used for horses

        # window slots vary, but always end with main inventory and hotbar
        # create own slots, ...
        self.slots = [Slot(self, slot_nr) for slot_nr in range(slot_count)]
        # ... append persistent slots (main inventory and hotbar)
        if persistent_slots is None:
            for slot_nr in range(constants.INV_SLOTS_PERSISTENT):
                self.slots.append(Slot(self, slot_nr + slot_count))
        else:  # persistent slots have to be moved from other inventory
            moved_slots = persistent_slots[-constants.INV_SLOTS_PERSISTENT:]
            for slot_nr, moved_slot in enumerate(moved_slots):
                moved_slot.move_to_window(self, slot_nr + slot_count)
                self.slots.append(moved_slot)

        # additional info dependent on inventory type,
        # dynamically updated by server
        self.properties = {}

    def __init__(self, user, session=None):
        self.participating_sessions = Session.objects.with_participation(user)
        self.facilitating_sessions = Session.objects.with_facilitator(user)
        self.pending_responses = Session.objects.with_pending_responses(user)
        self.session = session

    def __init(self):
        self.s.clear()
        self.s.setComponentByPosition(0, univ.Null(null))
        self.s.setDefaultComponents()

        def __init(self, parent):
            QLabel.__init__(self, parent)

    def __init__(self, patron, notify_cfg, suffix, ip, ns, ns_ttl):
        labour.BaseLabour.__init__(self, patron)

0
File: ipdns.py, Project: fail2ban, View license
uses: socket.AF_UNSPEC
	def __init(self, ipstr, cidr=CIDR_UNSPEC):
		""" initialize IP object by converting IP address string
			to binary to integer
		"""
		self._family = socket.AF_UNSPEC
		self._addr = 0
		self._plen = 0
		self._maskplen = None
		# always save raw value (normally used if really raw or not valid only):
		self._raw = ipstr
		# if not raw - recognize family, set addr, etc.:
		if cidr != IPAddr.CIDR_RAW:
			for family in [socket.AF_INET, socket.AF_INET6]:
				try:
					binary = socket.inet_pton(family, ipstr)
					self._family = family
					break
				except socket.error:
					continue

			if self._family == socket.AF_INET:
				# convert host to network byte order
				self._addr, = struct.unpack("!L", binary)
				self._plen = 32

				# mask out host portion if prefix length is supplied
				if cidr is not None and cidr >= 0:
					mask = ~(0xFFFFFFFFL >> cidr)
					self._addr &= mask
					self._plen = cidr

			elif self._family == socket.AF_INET6:
				# convert host to network byte order
				hi, lo = struct.unpack("!QQ", binary)
				self._addr = (hi << 64) | lo
				self._plen = 128

				# mask out host portion if prefix length is supplied
				if cidr is not None and cidr >= 0:
					mask = ~(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFL >> cidr)
					self._addr &= mask
					self._plen = cidr

				# if IPv6 address is a IPv4-compatible, make instance a IPv4
				elif self.isInNet(IPAddr.IP6_4COMPAT):
					self._addr = lo & 0xFFFFFFFFL
					self._family = socket.AF_INET
					self._plen = 32
		else:
			self._family = IPAddr.CIDR_RAW

    def __init(self, test=False):
        """
        we use this method to initialize because here it could be, that
        Exceptions are thrown. in __init__() we could not catch them
        see handle_main() to understand

        @param test: used in test_get_all
        """
        self._parser = MemacsArgumentParser(
            prog_version=self.__prog_version,
            prog_version_date=self.__prog_version_date,
            prog_description=self.__prog_description,
            copyright_year=self.__copyright_year,
            copyright_authors=self.__copyright_authors,
            use_config_parser_name=self.__use_config_parser_name)
        # adding additional arguments from our subcass
        self._parser_add_arguments()
        # parse all arguments
        self._parser_parse_args()
        # set logging configuration
        handle_logging(self._args.__dict__,
                       self._args.verbose,
                       self._args.suppressmessages,
                       self._args.outputfile,
                       )

        # for testing purposes it's good to see which args are secified
        logging.debug("args specified:")
        logging.debug(self._args)

        # if an tag is specified as argument take that tag
        if self._args.tag:
            tag = self._args.tag
        else:
            tag = self.__prog_tag

        #
        if self.__use_config_parser_name != "":
            self.__config_parser = ConfigParser()
            self.__config_parser.read(self._args.configfile)
            logging.debug("cfg: %s",
                          self.__config_parser.items(
                                        self.__use_config_parser_name))

        # handling autotagging
        autotag_dict = self.__handle_autotagfile()

        ## collect additional header lines:
        additional_headerlines = False
        if self._args.columns_header:
            additional_headerlines = '#+COLUMNS: ' + self._args.columns_header
        if self._args.custom_header:
            additional_headerlines = self._args.custom_header

        # set up orgoutputwriter
        self._writer = OrgOutputWriter(
            file_name=self._args.outputfile,
            short_description=self.__prog_short_description,
            tag=tag,
            test=test,
            append=self._args.append,
            autotag_dict=autotag_dict,
            number_entries=self._args.number_entries,
            additional_headerlines = additional_headerlines,
            timestamp_delta=self._args.timestamp_delta,
            inactive_timestamps=self._args.inactive_timestamps)

            def __init(self, text):
                QPushButton.__init__(self, text)
                self.setFlat(True)

    def __init(self, *args):
        if self._cue.duration > 0 and not self._active:
            # Cue "status" signals
            self._cue.started.connect(self.start, Connection.QtQueued)
            self._cue.paused.connect(self.stop, Connection.QtQueued)
            self._cue.stopped.connect(self.stop, Connection.QtQueued)
            self._cue.end.connect(self.stop, Connection.QtQueued)
            self._cue.error.connect(self.stop, Connection.QtQueued)

            if self._cue.state == CueState.Running:
                self.start()
            self._active = True
        elif self._cue.duration < 0 and self._active:
            self._cue.started.disconnect(self.start)
            self._cue.paused.disconnect(self.stop)
            self._cue.stopped.disconnect(self.stop)
            self._cue.end.disconnect(self.stop)
            self._cue.error.disconnect(self.stop)

            self.stop()
            self._active = False

    def __init__(self, stream, **kw):
        Parser.__init__(self, stream, **kw)

    def __init__(self, filename, config, list_streams=False, init_stream_list=None):
        """ Init and try to load a stream list, nothing about curses yet """

        global TITLE_STRING

        self.db_was_read = False

        # Open the storage (create it if necessary)
        try:
            db_dir = os.path.dirname(filename)
            if not os.path.exists(db_dir):
                os.makedirs(db_dir)
            f = shelve.open(filename, 'c')
        except Exception:
            raise ShelveError(
                'Database could not be opened, another livestreamer-curses instance might be already running. '
                'Please note that a database created with Python 2.x cannot be used with Python 3.x and vice versa.'
            )

        self.max_id = 0
        if init_stream_list:
            f['streams'] = init_stream_list
            for i, s in enumerate(f['streams']):
                s['id'] = s.get('id') or i
                s['seen'] = s.get('seen') or 0
                s['last_seen'] = s.get('last_seen') or 0
            self.max_id = i
            f.sync()

        # Sort streams by view count
        try:
            self.streams = sorted(f['streams'], key=lambda s:s['seen'], reverse=True)
            for s in self.streams:
                # Max id, needed when adding a new stream
                self.max_id = max(self.max_id, s['id'])
                s['online'] = 2
            if list_streams:
                print(json.dumps(self.streams))
                f.close()
                sys.exit(0)
        except:
            self.streams = []
        self.db_was_read = True
        self.filtered_streams = list(self.streams)
        self.filter = ''
        self.all_streams_offline = None
        self.show_offline_streams = False
        self.config = config

        TITLE_STRING = TITLE_STRING.format(self.config.VERSION)

        self.cmd_list = list(map(shlex.split, self.config.LIVESTREAMER_COMMANDS))
        self.cmd_index = 0
        self.cmd = self.cmd_list[self.cmd_index]

        self.last_autocheck = 0

        self.default_res = self.config.DEFAULT_RESOLUTION

        self.store = f
        self.store.sync()

        self.no_streams = self.streams == []
        self.no_stream_shown = self.no_streams
        self.q = ProcessList(StreamPlayer().play)

        self.livestreamer = livestreamer.Livestreamer()

0
File: multicombo.py, Project: kiwi, View license
uses: gtk.gdk.Pixbuf
    def __init__(self, **kwargs):
        super(MultiCombo, self).__init__()

        # FIXME: gtk.HBox doesn't support kwargs on __init__ on gtk2.
        # Put it there when we migrate to gtk3
        for k, v in kwargs.iteritems():
            self.set_property(k, v)

        self.model = gtk.ListStore(str, object, gtk.gdk.Pixbuf, object)
        self._setup_ui()

        self.popup = _MultiComboPopup(self, self.model)
        self.popup.connect('item-selected', self._on_popup__item_selected)

        self.set_size_request(self.width, -1)

        itr = self.textbuffer.get_end_iter()
        self._row_height = self.textview.get_line_yrange(itr)[1]

        self.connect('notify::width', self._on__notify_width)
        self.connect('notify::scrolling_threshold',
                     self._on__notify_scrolling_threshold)

    def __init(self):
        """
            Init row
        """
        artists = []
        if self.__item.is_track:
            obj = Track(self.__item.id)
            album_id = obj.album_id
        else:
            obj = Album(self.__item.id)
            album_id = obj.id

        if self.__item.id is None:
            if self.__item.is_track:
                self.__name.set_text("♫ " + self.__item.name)
            else:
                self.__name.set_text(self.__item.name)
            artists = self.__item.artists
            surface = Lp().art.get_default_icon('emblem-music-symbolic',
                                                ArtSize.MEDIUM,
                                                self.get_scale_factor())
        else:
            if self.__item.is_track:
                self.__name.set_text("♫ " + Track(self.__item.id).name)
            else:
                self.__name.set_text(Album(self.__item.id).name)
            for artist_id in self.__item.artist_ids:
                artists.append(Lp().artists.get_name(artist_id))
            surface = Lp().art.get_album_artwork(Album(album_id),
                                                 ArtSize.MEDIUM,
                                                 self.get_scale_factor())
        self.__cover.set_from_surface(surface)
        del surface
        self.__artist.set_text(", ".join(artists))

    def __init__(self, *args, **kwargs):
        super(DirectoryHandler, self).__init__(*args, **kwargs)

        if 'filename' not in kwargs:
            raise ValueError('Must pass a filename to DirectoryHandler')
        src_path = kwargs['filename']
        argv = kwargs.get('argv', [])

        main_py = join(src_path, 'main.py')
        main_ipy = join(src_path, 'main.ipynb')
        if exists(main_py) and exists(main_ipy):
            log.warn("Found both 'main.py' and 'main.ipynb' in %s, using 'main.py'" % (src_path))
            main = main_py
        elif exists(main_py):
            main = main_py
        elif exists(main_ipy):
            main = main_ipy
        else:
            raise ValueError("No 'main.py' or 'main.ipynb' in %s" % (src_path))
        self._path = src_path
        self._main = main
        self._main_handler = ScriptHandler(filename=self._main, argv=argv)

        lifecycle = join(src_path, 'server_lifecycle.py')
        if exists(lifecycle):
            self._lifecycle = lifecycle
            self._lifecycle_handler = ServerLifecycleHandler(filename=self._lifecycle, argv=argv)
        else:
            self._lifecycle = None
            self._lifecycle_handler = Handler() # no-op handler

        self._theme = None
        themeyaml = join(src_path, 'theme.yaml')
        if exists(themeyaml):
            from bokeh.themes import Theme
            self._theme = Theme(filename=themeyaml)

        appstatic = join(src_path, 'static')
        if exists(appstatic):
            self._static = appstatic

        self._template = None
        appindex = join(src_path, 'templates', 'index.html')
        if exists(appindex):
            env = Environment(loader=FileSystemLoader(dirname(appindex)))
            self._template = env.get_template('index.html')