Esempio n. 1
0
    def helpext(name):
        try:
            mod = extensions.find(name)
            doc = gettext(mod.__doc__) or _('no help text available')
        except KeyError:
            mod = None
            doc = extensions.disabledext(name)
            if not doc:
                raise error.UnknownCommand(name)

        if '\n' not in doc:
            head, tail = doc, ""
        else:
            head, tail = doc.split('\n', 1)
        rst = [_('%s extension - %s\n\n') % (name.split('.')[-1], head)]
        if tail:
            rst.extend(tail.splitlines(True))
            rst.append('\n')

        if not ui.verbose:
            omitted = _('(some details hidden, use --verbose'
                         ' to show complete help)')
            indicateomitted(rst, omitted)

        if mod:
            try:
                ct = mod.cmdtable
            except AttributeError:
                ct = {}
            modcmds = set([c.split('|', 1)[0] for c in ct])
            rst.extend(helplist(modcmds.__contains__))
        else:
            rst.append(_('(use "hg help extensions" for information on enabling'
                       ' extensions)\n'))
        return rst
Esempio n. 2
0
def _smtp(ui):
    '''build an smtp connection and return a function to send mail'''
    local_hostname = ui.config('smtp', 'local_hostname')
    s = smtplib.SMTP(local_hostname=local_hostname)
    mailhost = ui.config('smtp', 'host')
    if not mailhost:
        raise util.Abort(_('no [smtp]host in hgrc - cannot send mail'))
    mailport = int(ui.config('smtp', 'port', 25))
    ui.note(_('sending mail: smtp host %s, port %s\n') %
            (mailhost, mailport))
    s.connect(host=mailhost, port=mailport)
    if ui.configbool('smtp', 'tls'):
        if not hasattr(socket, 'ssl'):
            raise util.Abort(_("can't use TLS: Python SSL support "
                               "not installed"))
        ui.note(_('(using tls)\n'))
        s.ehlo()
        s.starttls()
        s.ehlo()
    username = ui.config('smtp', 'username')
    password = ui.config('smtp', 'password')
    if username and not password:
        password = ui.getpass()
    if username and password:
        ui.note(_('(authenticating to mail server as %s)\n') %
                  (username))
        try:
            s.login(username, password)
        except smtplib.SMTPException, inst:
            raise util.Abort(inst)
Esempio n. 3
0
 def extract(self, lr):
     line = lr.readline()
     self.hunk.append(line)
     while line and not line.startswith('literal '):
         line = lr.readline()
         self.hunk.append(line)
     if not line:
         raise PatchError(_('could not extract binary patch'))
     size = int(line[8:].rstrip())
     dec = []
     line = lr.readline()
     self.hunk.append(line)
     while len(line) > 1:
         l = line[0]
         if l <= 'Z' and l >= 'A':
             l = ord(l) - ord('A') + 1
         else:
             l = ord(l) - ord('a') + 27
         dec.append(base85.b85decode(line[1:-1])[:l])
         line = lr.readline()
         self.hunk.append(line)
     text = zlib.decompress(''.join(dec))
     if len(text) != size:
         raise PatchError(_('binary patch is %d bytes, not %d') %
                          len(text), size)
     self.text = text
Esempio n. 4
0
def _verifycert(cert, hostname):
    '''Verify that cert (in socket.getpeercert() format) matches hostname.
    CRLs is not handled.

    Returns error message if any problems are found and None on success.
    '''
    if not cert:
        return _('no certificate received')
    dnsname = hostname.lower()
    def matchdnsname(certname):
        return (certname == dnsname or
                '.' in dnsname and certname == '*.' + dnsname.split('.', 1)[1])

    san = cert.get('subjectAltName', [])
    if san:
        certnames = [value.lower() for key, value in san if key == 'DNS']
        for name in certnames:
            if matchdnsname(name):
                return None
        return _('certificate is for %s') % ', '.join(certnames)

    # subject is only checked when subjectAltName is empty
    for s in cert.get('subject', []):
        key, value = s[0]
        if key == 'commonName':
            try:
                # 'subject' entries are unicode
                certname = value.lower().encode('ascii')
            except UnicodeEncodeError:
                return _('IDN in certificate not supported')
            if matchdnsname(certname):
                return None
            return _('certificate is for %s') % certname
    return _('no commonName or subjectAltName found in certificate')
Esempio n. 5
0
def _exthook(ui, repo, name, cmd, args, throw):
    ui.note(_("running hook %s: %s\n") % (name, cmd))

    starttime = time.time()
    env = {}
    for k, v in args.iteritems():
        if callable(v):
            v = v()
        if isinstance(v, dict):
            # make the dictionary element order stable across Python
            # implementations
            v = ('{' +
                 ', '.join('%r: %r' % i for i in sorted(v.iteritems())) +
                 '}')
        env['HG_' + k.upper()] = v

    if repo:
        cwd = repo.root
    else:
        cwd = os.getcwd()
    if 'HG_URL' in env and env['HG_URL'].startswith('remote:http'):
        r = util.system(cmd, environ=env, cwd=cwd, out=ui)
    else:
        r = util.system(cmd, environ=env, cwd=cwd, out=ui.fout)

    duration = time.time() - starttime
    ui.log('exthook', 'exthook-%s: %s finished in %0.2f seconds\n',
           name, cmd, duration)
    if r:
        desc, r = util.explainexit(r)
        if throw:
            raise error.HookAbort(_('%s hook %s') % (name, desc))
        ui.warn(_('warning: %s hook %s\n') % (name, desc))
    return r
Esempio n. 6
0
    def __fill_text_view(self):
        text_buffer = self.__text_view.get_buffer()
        self.__create_tags(text_buffer)

        iter = text_buffer.get_iter_at_offset(0)
        text_buffer.insert_with_tags_by_name(iter, "\n ",
                                             "left_margin_16")
        text_buffer.insert_pixbuf(iter,
                self.__load_icon(self.__engine_desc.get_icon()))
        text_buffer.insert_with_tags_by_name(iter,
                "\n%s\n" % self.__engine_desc.get_longname(),
                "heading", "left_margin_16")
        text_buffer.insert_with_tags_by_name(iter,
                _("Language: %s\n") % IBus.get_language_name(self.__engine_desc.get_language()),
                "small", "bold", "left_margin_16")
        text_buffer.insert_with_tags_by_name(iter,
                _("Keyboard layout: %s\n") % self.__engine_desc.get_layout(),
                "small", "bold", "left_margin_16")
        text_buffer.insert_with_tags_by_name(iter,
                _("Author: %s\n") % self.__engine_desc.get_author(),
                "small", "bold", "left_margin_16")
        text_buffer.insert_with_tags_by_name(iter,
                _("Description:\n"), "small", "bold", "left_margin_16")
        text_buffer.insert_with_tags_by_name(iter,
                self.__engine_desc.get_description(),
                "wrap_text", "left_margin_32")
Esempio n. 7
0
def patch(patchname, ui, strip=1, cwd=None, files={}, eolmode='strict'):
    """Apply <patchname> to the working directory.

    'eolmode' specifies how end of lines should be handled. It can be:
    - 'strict': inputs are read in binary mode, EOLs are preserved
    - 'crlf': EOLs are ignored when patching and reset to CRLF
    - 'lf': EOLs are ignored when patching and reset to LF
    - None: get it from user settings, default to 'strict'
    'eolmode' is ignored when using an external patcher program.

    Returns whether patch was applied with fuzz factor.
    """
    patcher = ui.config('ui', 'patch')
    args = []
    try:
        if patcher:
            return externalpatch(patcher, args, patchname, ui, strip, cwd,
                                 files)
        else:
            try:
                return internalpatch(patchname, ui, strip, cwd, files, eolmode)
            except NoHunks:
                patcher = util.find_exe('gpatch') or util.find_exe('patch') or 'patch'
                ui.debug(_('no valid hunks found; trying with %r instead\n') %
                         patcher)
                if util.needbinarypatch():
                    args.append('--binary')
                return externalpatch(patcher, args, patchname, ui, strip, cwd,
                                     files)
    except PatchError, err:
        s = str(err)
        if s:
            raise util.Abort(s)
        else:
            raise util.Abort(_('patch failed to apply'))
Esempio n. 8
0
File: api.py Progetto: bebound/Pixiv
    def check_expired(self):
        url = 'https://public-api.secure.pixiv.net/v1/ios_magazine_banner.json'
        print(_('Checking session'), end="", flush=True)

        valid = False
        try:
            r = self._request_pixiv('GET', url)

            if r.status_code in [200, 301, 302]:
                try:
                    respond = json.loads(r.text)
                    print(respond)
                    valid = respond['status'] == 'success'
                except Exception as e:
                    print(e)
                    valid = False
                finally:
                    pass
        except Exception as e:
            print(e)
        if valid:
            print(_(' [VALID]'))
        else:
            print(_(' [EXPIRED]'))
            self.access_token = None
        return valid
Esempio n. 9
0
File: api.py Progetto: bebound/Pixiv
    def _request_pixiv(self, method, url, headers=None, params=None, data=None, retry=3):
        """
        handle all url request

        Args:
            method: str, http method

        """
        pixiv_headers = {
            'Referer': 'http://www.pixiv.net/',
            'User-Agent': self.User_Agent,
            'Content-Type': 'application/x-www-form-urlencoded',
        }
        if self.access_token:
            pixiv_headers.update({'Authorization': 'Bearer {}'.format(self.access_token),
                                  'Cookie': 'PHPSESSID={}'.format(self.session_id)})
        if headers:
            pixiv_headers.update(headers)

        if not self.session:
            self.session = requests.Session()
        try:
            if method == 'GET':
                r = self.session.get(url, headers=pixiv_headers, params=params, timeout=self.timeout)
                r.encoding = 'utf-8'
                return r
            elif method == 'POST':
                return self.session.post(url, headers=pixiv_headers, params=params, data=data, timeout=self.timeout)
            else:
                raise RuntimeError(_('Unknown Method:'), method)
        except Exception as e:
            if retry > 0:
                return self._request_pixiv(method, url, headers, params, data, retry=retry - 1)
            else:
                raise RuntimeError(_('[ERROR] connection failed!'), e)
Esempio n. 10
0
def scan_qr(config):
    global proc
    if not zbar:
        raise BaseException("\n".join([_("Cannot start QR scanner."),_("The zbar package is not available."),_("On Linux, try 'sudo pip install zbar'")]))
    if proc is None:
        device = config.get("video_device", "default")
        if device == 'default':
            device = ''
        _proc = zbar.Processor()
        _proc.init(video_device=device)
        # set global only if init did not raise an exception
        proc = _proc


    proc.visible = True
    while True:
        try:
            proc.process_one()
        except Exception:
            # User closed the preview window
            return ""
        for r in proc.results:
            if str(r.type) != 'QRCODE':
                continue
            # hiding the preview window stops the camera
            proc.visible = False
            return r.data
Esempio n. 11
0
    def _abort(self):
        self.count = 0
        self.usages = 0
        self.file.close()
        self.backupsfile.close()

        if self.onabort is not None:
            self.onabort()

        try:
            if not self.entries and not self.backupentries:
                if self.journal:
                    self.opener.unlink(self.journal)
                if self.backupjournal:
                    self.opener.unlink(self.backupjournal)
                return

            self.report(_("transaction abort!\n"))

            try:
                _playback(self.journal, self.report, self.opener,
                          self.entries, self.backupentries, False)
                self.report(_("rollback completed\n"))
            except Exception:
                self.report(_("rollback failed - please run hg recover\n"))
        finally:
            self.journal = None
Esempio n. 12
0
    def __init__(self, transaction_id, parent):
        super(TransactionWindow, self).__init__()

        self.tx_id = str(transaction_id)
        self.parent = parent

        self.setModal(True)
        self.resize(200,100)
        self.setWindowTitle(_("Transaction successfully sent"))

        self.layout = QGridLayout(self)
        history_label = "%s\n%s" % (_("Your transaction has been sent."), _("Please enter a label for this transaction for future reference."))
        self.layout.addWidget(QLabel(history_label))

        self.label_edit = QLineEdit()
        self.label_edit.setPlaceholderText(_("Transaction label"))
        self.label_edit.setObjectName("label_input")
        self.label_edit.setAttribute(Qt.WA_MacShowFocusRect, 0)
        self.label_edit.setFocusPolicy(Qt.ClickFocus)
        self.layout.addWidget(self.label_edit)

        self.save_button = QPushButton(_("Save"))
        self.layout.addWidget(self.save_button)
        self.save_button.clicked.connect(self.set_label)

        self.exec_()
Esempio n. 13
0
    def unbundle(self, cg, heads, source):
        '''Send cg (a readable file-like object representing the
        changegroup to push, typically a chunkbuffer object) to the
        remote server as a bundle. Return an integer indicating the
        result of the push (see localrepository.addchangegroup()).'''

        if heads != ['force'] and self.capable('unbundlehash'):
            heads = encodelist(['hashed',
                                util.sha1(''.join(sorted(heads))).digest()])
        else:
            heads = encodelist(heads)

        ret, output = self._callpush("unbundle", cg, heads=heads)
        if ret == "":
            raise error.ResponseError(
                _('push failed:'), output)
        try:
            ret = int(ret)
        except ValueError:
            raise error.ResponseError(
                _('push failed (unexpected response):'), ret)

        for l in output.splitlines(True):
            self.ui.status(_('remote: '), l)
        return ret
Esempio n. 14
0
 def discoReceived(self, user, what, node):
     if 'info' == what:
         if node is None:
             ids = [{'category': 'gateway', 'type': 'bitcoin',
                     'name':LIB_DESCRIPTION}]
             return {'ids': ids, 'features': [NS_DISCO_INFO, NS_DISCO_ITEMS, NS_REGISTER, NS_VERSION, NS_GATEWAY, NS_LAST]}
         elif 'users' == node:
             ids = [{'category': 'directory', 'type': 'user', 'name': _(DISCO, 'user_list')}]
             return {'ids': ids, 'features': [NS_DISCO_INFO, NS_DISCO_ITEMS]}
     elif 'items' == what:
         items = []
         if user.isRegistered():
             if node is None:
                 items.append({'jid': user.getLocalJID(), 'name': _(DISCO, 'your_addresses'), 'node': 'addresses'})
         else:
             items.append({'jid': self.jid, 'name': LIB_DESCRIPTION})
         if user.isAdmin():
             if node is None:
                 items.append({'jid': self.jid, 'name': 'Users', 'node': 'users'})
             elif 'users' == node:
                 for jid in UserAccount.getAllMembers():
                     member = UserAccount(JID(jid))
                     name = member.username
                     items.append({'jid': member.getLocalJID(), 'name': name})
         return items
Esempio n. 15
0
def nochangesfound(ui, secretlist=None):
    '''report no changes for push/pull'''
    if secretlist:
        ui.status(_("no changes found (ignored %d secret changesets)\n")
                  % len(secretlist))
    else:
        ui.status(_("no changes found\n"))
Esempio n. 16
0
def _incoming(displaychlist, subreporecurse, ui, repo, source,
        opts, buffered=False):
    """
    Helper for incoming / gincoming.
    displaychlist gets called with
        (remoterepo, incomingchangesetlist, displayer) parameters,
    and is supposed to contain only code that can't be unified.
    """
    source, branches = parseurl(ui.expandpath(source), opts.get('branch'))
    other = peer(repo, opts, source)
    ui.status(_('comparing with %s\n') % util.hidepassword(source))
    revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev'))

    if revs:
        revs = [other.lookup(rev) for rev in revs]
    other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other,
                                revs, opts["bundle"], opts["force"])
    try:
        if not chlist:
            ui.status(_("no changes found\n"))
            return subreporecurse()

        displayer = cmdutil.show_changeset(ui, other, opts, buffered)

        # XXX once graphlog extension makes it into core,
        # should be replaced by a if graph/else
        displaychlist(other, chlist, displayer)

        displayer.close()
    finally:
        cleanupfn()
    subreporecurse()
    return 0 # exit code is zero since we found incoming changes
Esempio n. 17
0
 def __call__(self, path):
     if path in self.audited:
         return
     normpath = os.path.normcase(path)
     parts = splitpath(normpath)
     if (os.path.splitdrive(path)[0]
         or parts[0].lower() in ('.hg', '.hg.', '')
         or os.pardir in parts):
         raise Abort(_("path contains illegal component: %s") % path)
     if '.hg' in path.lower():
         lparts = [p.lower() for p in parts]
         for p in '.hg', '.hg.':
             if p in lparts[1:]:
                 pos = lparts.index(p)
                 base = os.path.join(*parts[:pos])
                 raise Abort(_('path %r is inside repo %r') % (path, base))
     def check(prefix):
         curpath = os.path.join(self.root, prefix)
         try:
             st = os.lstat(curpath)
         except OSError, err:
             # EINVAL can be raised as invalid path syntax under win32.
             # They must be ignored for patterns can be checked too.
             if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
                 raise
         else:
Esempio n. 18
0
    def handle_login(self, login, password, redirect):
        """
        Handle login.
        """
        # check for login credentials
        params = dict()
        logger.info("check credentials for [%s]" % login)
        try:
            username = self.app.userdb.login(login, password)
        except:
            logger.exception("fail to validate user credential.")
            params["warning"] = _("Fail to validate user credential.")
        else:
            if username:
                # Login successful
                cherrypy.session['username'] = username  # @UndefinedVariable
                if not redirect or redirect.startswith("/login/"):
                    redirect = "/"
                # The redirect url was unquoted by cherrypy, quote the
                # url again.
                logger.info("redirect user to %s" % redirect)
                raise cherrypy.HTTPRedirect(redirect)
            else:
                logger.warn("invalid username or password")
                params["warning"] = _("Invalid username or password.")

        return params
Esempio n. 19
0
def addbranchrevs(lrepo, repo, branches, revs):
    hashbranch, branches = branches
    if not hashbranch and not branches:
        return revs or None, revs and revs[0] or None
    revs = revs and list(revs) or []
    if not repo.capable('branchmap'):
        if branches:
            raise util.Abort(_("remote branch lookup not supported"))
        revs.append(hashbranch)
        return revs, revs[0]
    branchmap = repo.branchmap()

    def primary(branch):
        if branch == '.':
            if not lrepo or not lrepo.local():
                raise util.Abort(_("dirstate branch not accessible"))
            branch = lrepo.dirstate.branch()
        if branch in branchmap:
            revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
            return True
        else:
            return False

    for branch in branches:
        if not primary(branch):
            raise error.RepoLookupError(_("unknown branch '%s'") % branch)
    if hashbranch:
        if not primary(hashbranch):
            revs.append(hashbranch)
    return revs, revs[0]
Esempio n. 20
0
    def cam_tab( self ):
        """
        The cam module Preff Tab.

        Arguments:
        - self: The main object pointer.
        """

        frame = gtk.Frame()

        camBox = gtk.VBox( spacing = 6 )

        mapperActive = gtk.CheckButton( _("Show Point Mapper") )
        mapperActive.set_active( self.cfg.getboolean( "gui", "showPointMapper" ) )
        mapperActive.connect( "toggled", self._checkToggled, "gui", "showPointMapper" )

        camBox.pack_start( mapperActive, False, False )

        showCapture = gtk.CheckButton( _("Show Capture") )
        showCapture.set_active( self.cfg.getboolean( "gui", "showCapture" ) )
        showCapture.connect( "toggled", self._checkToggled, "gui", "showCapture" )

        camBox.pack_start( showCapture, False, False )

        camBox.show_all()

        frame.add( camBox )
        frame.show()

        self.noteBook.insert_page(frame, gtk.Label( _("Camera") ) )
Esempio n. 21
0
    def debug_tab( self ):
        """
        The debuging Preff Tab.

        Arguments:
        - self: The main object pointer.
        """


        frame = gtk.Frame()

        debugBox = gtk.VBox( spacing = 6 )

        levelHbox = gtk.HBox( spacing = 4 )

        levellabel = gtk.Label( _("Debugging Level:") )
        levellabel.set_alignment( 0.0, 0.5 )
        levellabel.show()
        levelHbox.pack_start( levellabel, False, False )

        adj = gtk.Adjustment( self.cfg.getint( "main", "debugLevel" ), 10, 50, 10, 1, 0)
        levelSpin = gtk.SpinButton( adj, 0.0, 0 )
        levelSpin.set_wrap( True )
        levelHbox.pack_start( levelSpin, False, False )
        levelSpin.connect( "value-changed", self._spinChanged, "main", "debugLevel" )

        debugBox.pack_start( levelHbox, False, False )

        debugBox.show_all()

        frame.add( debugBox )
        frame.show()

        self.noteBook.insert_page(frame, gtk.Label( _("Debug") ) )
Esempio n. 22
0
	def update(self):
		# Namecheap requires the hostname splitted into a host and domain part.
		host, domain = self.hostname.split(".", 1)

		data = {
			"ip"       : self.get_address("ipv4"),
			"password" : self.password,
			"host"     : host,
			"domain"   : domain
		}

		# Send update to the server.
		response = self.send_request(self.url, data=data)

		# Get the full response message.
		output = response.read()

		# Handle success messages.
		if self.get_xml_tag_value(output, "IP") == self.get_address("ipv4"):
			return

		# Handle error codes.
		errorcode = self.get_xml_tag_value(output, "ResponseNumber")

		if errorcode == "304156":
			raise DDNSAuthenticationError
		elif errorcode == "316153":
			raise DDNSRequestError(_("Domain not found."))
		elif errorcode == "316154":
			raise DDNSRequestError(_("Domain not active."))
		elif errorcode in ("380098", "380099"):
			raise DDNSInternalServerError

		# If we got here, some other update error happened.
		raise DDNSUpdateError
Esempio n. 23
0
	def update(self):
		data = self._prepare_request_data()

		# Send update to the server.
		response = self.send_request(self.url, data=data,
			username=self.username, password=self.password)

		# Get the full response message.
		output = response.read()

		# Handle success messages.
		if output.startswith("good") or output.startswith("nochg"):
			return

		# Handle error codes.
		if output == "badauth":
			raise DDNSAuthenticationError
		elif output == "aduse":
			raise DDNSAbuseError
		elif output == "notfqdn":
			raise DDNSRequestError(_("No valid FQDN was given."))
		elif output == "nohost":
			raise DDNSRequestError(_("Specified host does not exist."))
		elif output == "911":
			raise DDNSInternalServerError
		elif output == "dnserr":
			raise DDNSInternalServerError(_("DNS error encountered."))

		# If we got here, some other update error happened.
		raise DDNSUpdateError(_("Server response: %s") % output)
Esempio n. 24
0
    def find_user_password(self, realm, authuri):
        authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(
            self, realm, authuri)
        user, passwd = authinfo
        if user and passwd:
            self._writedebug(user, passwd)
            return (user, passwd)

        if not user or not passwd:
            res = httpconnectionmod.readauthforuri(self.ui, authuri, user)
            if res:
                group, auth = res
                user, passwd = auth.get('username'), auth.get('password')
                self.ui.debug("using auth.%s.* for authentication\n" % group)
        if not user or not passwd:
            if not self.ui.interactive():
                raise util.Abort(_('http authorization required'))

            self.ui.write(_("http authorization required\n"))
            self.ui.write(_("realm: %s\n") % realm)
            if user:
                self.ui.write(_("user: %s\n") % user)
            else:
                user = self.ui.prompt(_("user:"), default=None)

            if not passwd:
                passwd = self.ui.getpass()

        self.add_password(realm, authuri, user, passwd)
        self._writedebug(user, passwd)
        return (user, passwd)
Esempio n. 25
0
    def find_user_password(self, realm, authuri):
        authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(
            self, realm, authuri)
        user, passwd = authinfo
        if user and passwd:
            self._writedebug(user, passwd)
            return (user, passwd)

        if not user:
            auth = self.readauthtoken(authuri)
            if auth:
                user, passwd = auth.get('username'), auth.get('password')
        if not user or not passwd:
            if not self.ui.interactive():
                raise util.Abort(_('http authorization required'))

            self.ui.write(_("http authorization required\n"))
            self.ui.status(_("realm: %s\n") % realm)
            if user:
                self.ui.status(_("user: %s\n") % user)
            else:
                user = self.ui.prompt(_("user:"), default=None)

            if not passwd:
                passwd = self.ui.getpass()

        self.add_password(realm, authuri, user, passwd)
        self._writedebug(user, passwd)
        return (user, passwd)
Esempio n. 26
0
def remote(repo, subset, x):
    """``remote([id [,path]])``
    Local revision that corresponds to the given identifier in a
    remote repository, if present. Here, the '.' identifier is a
    synonym for the current local branch.
    """

    import hg # avoid start-up nasties
    # i18n: "remote" is a keyword
    l = getargs(x, 0, 2, _("remote takes one, two or no arguments"))

    q = '.'
    if len(l) > 0:
    # i18n: "remote" is a keyword
        q = getstring(l[0], _("remote requires a string id"))
    if q == '.':
        q = repo['.'].branch()

    dest = ''
    if len(l) > 1:
        # i18n: "remote" is a keyword
        dest = getstring(l[1], _("remote requires a repository path"))
    dest = repo.ui.expandpath(dest or 'default')
    dest, branches = hg.parseurl(dest)
    revs, checkout = hg.addbranchrevs(repo, repo, branches, [])
    if revs:
        revs = [repo.lookup(rev) for rev in revs]
    other = hg.peer(repo, {}, dest)
    n = other.lookup(q)
    if n in repo:
        r = repo[n].rev()
        if r in subset:
            return [r]
    return []
Esempio n. 27
0
 def add(self, list, prefix=""):
     join = lambda f: os.path.join(prefix, f)
     wlock = self._repo.wlock()
     ui, ds = self._repo.ui, self._repo.dirstate
     try:
         rejected = []
         for f in list:
             scmutil.checkportable(ui, join(f))
             p = self._repo.wjoin(f)
             try:
                 st = os.lstat(p)
             except OSError:
                 ui.warn(_("%s does not exist!\n") % join(f))
                 rejected.append(f)
                 continue
             if st.st_size > 10000000:
                 ui.warn(_("%s: up to %d MB of RAM may be required "
                           "to manage this file\n"
                           "(use 'hg revert %s' to cancel the "
                           "pending addition)\n")
                           % (f, 3 * st.st_size // 1000000, join(f)))
             if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
                 ui.warn(_("%s not added: only files and symlinks "
                           "supported currently\n") % join(f))
                 rejected.append(p)
             elif ds[f] in 'amn':
                 ui.warn(_("%s already tracked!\n") % join(f))
             elif ds[f] == 'r':
                 ds.normallookup(f)
             else:
                 ds.add(f)
         return rejected
     finally:
         wlock.release()
Esempio n. 28
0
	def update(self):
		data = {
			"domain" : self.hostname,
			"ip"     : self.get_address("ipv4"),
		}

		# Send update to the server.
		response = self.send_request(self.url, username=self.username, password=self.password,
			data=data)

		# Get the full response message.
		output = response.read()

		# Handle success messages.
		if output.startswith("ok") or output.startswith("nochange"):
			return

		# Handle error codes.
		if output == "unauth":
			raise DDNSAuthenticationError
		elif output == "abuse":
			raise DDNSAbuseError
		elif output == "blocked":
			raise DDNSBlockedError
		elif output == "nofqdn":
			raise DDNSRequestError(_("No valid FQDN was given."))
		elif output == "nohost":
			raise DDNSRequestError(_("Invalid hostname specified."))
		elif output == "notdyn":
			raise DDNSRequestError(_("Hostname not marked as a dynamic host."))
		elif output == "invalid":
			raise DDNSRequestError(_("Invalid IP address has been sent."))

		# If we got here, some other update error happened.
		raise DDNSUpdateError
Esempio n. 29
0
def _findexactmatches(repo, added, removed):
    '''find renamed files that have no changes

    Takes a list of new filectxs and a list of removed filectxs, and yields
    (before, after) tuples of exact matches.
    '''
    numfiles = len(added) + len(removed)

    # Get hashes of removed files.
    hashes = {}
    for i, fctx in enumerate(removed):
        repo.ui.progress(_('searching for exact renames'), i, total=numfiles)
        h = util.sha1(fctx.data()).digest()
        hashes[h] = fctx

    # For each added file, see if it corresponds to a removed file.
    for i, fctx in enumerate(added):
        repo.ui.progress(_('searching for exact renames'), i + len(removed),
                total=numfiles)
        h = util.sha1(fctx.data()).digest()
        if h in hashes:
            yield (hashes[h], fctx)

    # Done
    repo.ui.progress(_('searching for exact renames'), None)
Esempio n. 30
0
File: main.py Progetto: ahqmhjk/ibus
    def __init__ (self, replace):
        pynotify.init("ibus")
        self.__bus = ibus.Bus()
        self.__bus.connect("disconnected", gtk.main_quit)
        self.__bus.connect("registry-changed", self.__registry_changed_cb)

        match_rule = "type='signal',\
                      sender='org.freedesktop.IBus',\
                      path='/org/freedesktop/IBus'"
        self.__bus.add_match(match_rule)

        self.__panel = panel.Panel(self.__bus)
        flag = ibus.BUS_NAME_FLAG_ALLOW_REPLACEMENT
        if replace:
            flag = flag | ibus.BUS_NAME_FLAG_REPLACE_EXISTING
        self.__bus.request_name(ibus.IBUS_SERVICE_PANEL, flag)
        self.__bus.get_dbusconn().add_signal_receiver(self.__name_acquired_cb,
                                                      signal_name="NameAcquired")
        self.__bus.get_dbusconn().add_signal_receiver(self.__name_lost_cb,
                                                      signal_name="NameLost")
        self.__notify = pynotify.Notification("IBus", \
                            _("Some input methods have been installed, removed or updated. " \
                            "Please restart ibus input platform."), \
                            "ibus")
        self.__notify.set_timeout(10 * 1000)
        self.__notify.add_action("restart", _("Restart Now"), self.__restart_cb, None)
        self.__notify.add_action("ignore", _("Later"), lambda *args: None, None)
Esempio n. 31
0
class Plugin(Plugin_Base):
    '''
        call sequence:
            set vars like hintSignal, hintSignal
            onInit
            onWidget
            onUiInitDone
            onActive
                send
                onReceived
            onDel
    '''
    # vars set by caller
    isConnected = lambda o: False
    send = lambda o, x, y: None  # send(data_bytes=None, file_path=None, callback=lambda ok,msg:None), can call in UI thread directly
    ctrlConn = lambda o, k, v: None  # call ctrl func of connection
    hintSignal = None  # hintSignal.emit(type(error, warning, info), title, msg)
    reloadWindowSignal = None  # reloadWindowSignal.emit(title, msg, callback(close or not)), reload window to load new configs
    configGlobal = {}
    # other vars
    connParent = "main"  # parent id
    connChilds = []  # children ids
    id = "gragh"
    name = _("Gragh")

    enabled = False  # user enabled this plugin
    active = False  # using this plugin

    help = '{}<br><br>{}<br>Python:<br><pre>{}</pre><br>C/C++:<br><pre>{}</pre>'.format(
        _("Double click gragh item to add a gragh widget"),
        _("line chart plot protocol:"), '''
from COMTool.plugin import gragh_protocol
frame = gragh_protocol.plot_pack(name, x, y, header= b'\xAA\xCC\xEE\xBB')
''', '''
void plot_pack(uint8_t *buff, int buff_len,
               uint8_t header[4], char *name,
               double x, double y)
{
    memcpy(buff, header, 4);
    uint8_t len = (uint8_t)strlen(name);
    buff[4] = len;
    memcpy(buff + 5, name, len);
    memcpy(buff + 5 + len, &x, 8);
    memcpy(buff + 5 + len + 8, &y, 8);
    int sum = 0;
    for (int i = 0; i &lt; 4+1+len+8+8; i++)
    {
        sum += buff[i];
    }
    buff[4+1+len+8+8] = (uint8_t)(sum & 0xff);
}
''')

    def __init__(self):
        super().__init__()
        if not self.id:
            raise ValueError(f"var id of Plugin {self} should be set")

    def onInit(self, config):
        '''
            init params, DO NOT take too long time in this func
            @config dict type, just change this var's content,
                               when program exit, this config will be auto save to config file
        '''
        self.config = config
        default = {
            "version": 1,
            "graghWidgets": [
                # {
                #     "id": "plot",
                #     "config": {}
                # }
            ]
        }
        for k in default:
            if not k in self.config:
                self.config[k] = default[k]
        self.widgets = []

    def onDel(self):
        pass

    def onWidgetMain(self, parent):
        '''
            main widget, just return a QWidget object
        '''
        widget = QWidget()
        widget.setProperty("class", "scrollbar2")
        layout = QVBoxLayout(widget)
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        layout.addWidget(scroll)
        widget2 = QWidget()
        scroll.setWidget(widget2)
        self.widgetsLayout = QVBoxLayout()
        widget2.setLayout(self.widgetsLayout)
        widget.resize(600, 400)
        # load gragh widgets
        for item in self.config["graghWidgets"]:
            if not item["id"] in graghWidgets:
                continue
            c = graghWidgets[item["id"]]
            w = c(hintSignal=self.hintSignal,
                  rmCallback=self.rmWidgetFromMain,
                  send=self.sendData,
                  config=item["config"])
            self.widgets.append(w)
            self.widgetsLayout.addWidget(w)
        return widget

    def onWidgetSettings(self, parent):
        '''
            setting widget, just return a QWidget object or None
        '''
        itemList = QListWidget()
        for k, v in graghWidgets.items():
            itemList.addItem(k)
        itemList.setToolTip(_("Double click to add a gragh widget"))
        itemList.setCurrentRow(0)
        itemList.itemDoubleClicked.connect(self.addWidgetToMain)
        return itemList

    def addWidgetToMain(self, item):
        for k, c in graghWidgets.items():
            if k == item.text():
                config = {"id": c.id, "config": {}}
                w = c(hintSignal=self.hintSignal,
                      rmCallback=self.rmWidgetFromMain,
                      send=self.sendData,
                      config=config["config"])
                self.widgets.append(w)
                self.widgetsLayout.addWidget(w)
                self.config["graghWidgets"].append(config)

    def rmWidgetFromMain(self, widget):
        self.widgetsLayout.removeWidget(widget)
        for item in self.config["graghWidgets"]:
            if id(item["config"]) == id(widget.config):
                self.config["graghWidgets"].remove(item)
                break
        widget.deleteLater()
        self.widgets.remove(widget)

    def onWidgetFunctional(self, parent):
        '''
            functional widget, just return a QWidget object or None
        '''
        button = QPushButton(_("Clear count"))
        button.clicked.connect(self.clearCount)
        return button

    def onWidgetStatusBar(self, parent):
        self.statusBar = statusBar(rxTxCount=True)
        return self.statusBar

    def clearCount(self):
        self.statusBar.clear()

    def onReceived(self, data: bytes):
        '''
            call in receive thread, not UI thread
        '''
        self.statusBar.addRx(len(data))
        for w in self.widgets:
            w.onData(data)

    def sendData(self, data: bytes):
        '''
            send data, chidren call send will invoke this function
            if you send data in this plugin, you can directly call self.send
        '''
        self.send(data, callback=self.onSent)

    def onSent(self, ok, msg, length, path):
        if ok:
            self.statusBar.addTx(length)
        else:
            self.hintSignal.emit("error", _("Error"),
                                 _("Send data failed!") + " " + msg)

    def onKeyPressEvent(self, event):
        for w in self.widgets:
            w.onKeyPressEvent(event)

    def onKeyReleaseEvent(self, event):
        for w in self.widgets:
            w.onKeyReleaseEvent(event)

    def onUiInitDone(self):
        '''
            UI init done, you can update your widget here
            this method runs in UI thread, do not block too long
        '''
        pass

    def onActive(self):
        '''
            plugin active
        '''
        pass
Esempio n. 32
0
def _showstats(repo, stats):
    repo.ui.status(
        _("%d files updated, %d files merged, "
          "%d files removed, %d files unresolved\n") % stats)
Esempio n. 33
0
def clone(ui,
          peeropts,
          source,
          dest=None,
          pull=False,
          rev=None,
          update=True,
          stream=False,
          branch=None):
    """Make a copy of an existing repository.

    Create a copy of an existing repository in a new directory.  The
    source and destination are URLs, as passed to the repository
    function.  Returns a pair of repository peers, the source and
    newly created destination.

    The location of the source is added to the new repository's
    .hg/hgrc file, as the default to be used for future pulls and
    pushes.

    If an exception is raised, the partly cloned/updated destination
    repository will be deleted.

    Arguments:

    source: repository object or URL

    dest: URL of destination repository to create (defaults to base
    name of source repository)

    pull: always pull from source repository, even in local case

    stream: stream raw data uncompressed from repository (fast over
    LAN, slow over WAN)

    rev: revision to clone up to (implies pull=True)

    update: update working directory after clone completes, if
    destination is local repository (True means update to default rev,
    anything else is treated as a revision)

    branch: branches to clone
    """

    if isinstance(source, str):
        origsource = ui.expandpath(source)
        source, branch = parseurl(origsource, branch)
        srcpeer = peer(ui, peeropts, source)
    else:
        srcpeer = source.peer()  # in case we were called with a localrepo
        branch = (None, branch or [])
        origsource = source = srcpeer.url()
    rev, checkout = addbranchrevs(srcpeer, srcpeer, branch, rev)

    if dest is None:
        dest = defaultdest(source)
        ui.status(_("destination directory: %s\n") % dest)
    else:
        dest = ui.expandpath(dest)

    dest = util.urllocalpath(dest)
    source = util.urllocalpath(source)

    if not dest:
        raise util.Abort(_("empty destination path is not valid"))
    if os.path.exists(dest):
        if not os.path.isdir(dest):
            raise util.Abort(_("destination '%s' already exists") % dest)
        elif os.listdir(dest):
            raise util.Abort(_("destination '%s' is not empty") % dest)

    srclock = destlock = cleandir = None
    srcrepo = srcpeer.local()
    try:
        abspath = origsource
        if islocal(origsource):
            abspath = os.path.abspath(util.urllocalpath(origsource))

        if islocal(dest):
            cleandir = dest

        copy = False
        if (srcrepo and srcrepo.cancopy() and islocal(dest)
                and not phases.hassecret(srcrepo)):
            copy = not pull and not rev

        if copy:
            try:
                # we use a lock here because if we race with commit, we
                # can end up with extra data in the cloned revlogs that's
                # not pointed to by changesets, thus causing verify to
                # fail
                srclock = srcrepo.lock(wait=False)
            except error.LockError:
                copy = False

        if copy:
            srcrepo.hook('preoutgoing', throw=True, source='clone')
            hgdir = os.path.realpath(os.path.join(dest, ".hg"))
            if not os.path.exists(dest):
                os.mkdir(dest)
            else:
                # only clean up directories we create ourselves
                cleandir = hgdir
            try:
                destpath = hgdir
                util.makedir(destpath, notindexed=True)
            except OSError, inst:
                if inst.errno == errno.EEXIST:
                    cleandir = None
                    raise util.Abort(
                        _("destination '%s' already exists") % dest)
                raise

            destlock = copystore(ui, srcrepo, destpath)

            # Recomputing branch cache might be slow on big repos,
            # so just copy it
            dstcachedir = os.path.join(destpath, 'cache')
            srcbranchcache = srcrepo.sjoin('cache/branch2')
            dstbranchcache = os.path.join(dstcachedir, 'branch2')
            if os.path.exists(srcbranchcache):
                if not os.path.exists(dstcachedir):
                    os.mkdir(dstcachedir)
                util.copyfile(srcbranchcache, dstbranchcache)

            # we need to re-init the repo after manually copying the data
            # into it
            destpeer = peer(srcrepo, peeropts, dest)
            srcrepo.hook('outgoing',
                         source='clone',
                         node=node.hex(node.nullid))
        else:
Esempio n. 34
0
    requirements += 'shared\n'
    util.writefile(os.path.join(roothg, 'requires'), requirements)
    util.writefile(os.path.join(roothg, 'sharedpath'), sharedpath)

    r = repository(ui, root)

    default = srcrepo.ui.config('paths', 'default')
    if default:
        fp = r.opener("hgrc", "w", text=True)
        fp.write("[paths]\n")
        fp.write("default = %s\n" % default)
        fp.close()

    if update:
        r.ui.status(_("updating working directory\n"))
        if update is not True:
            checkout = update
        for test in (checkout, 'default', 'tip'):
            if test is None:
                continue
            try:
                uprev = r.lookup(test)
                break
            except error.RepoLookupError:
                continue
        _update(r, uprev)


def copystore(ui, srcrepo, destpath):
    '''copy files from store of srcrepo in destpath
Esempio n. 35
0
 def __str__(self):
     return _("Incorrect password")
Esempio n. 36
0
def format_time(timestamp):
    date = timestamp_to_datetime(timestamp)
    return date.isoformat(' ')[:-3] if date else _("Unknown")
Esempio n. 37
0
import os, sys, re, json
import platform
import shutil
from collections import defaultdict
from datetime import datetime
from decimal import Decimal
import traceback
import urlparse
import urllib
import threading
from i18n import _

base_units = {'VTC': 8, 'mVTC': 5, 'uVTC': 2}
fee_levels = [
    _('Within 25 blocks'),
    _('Within 10 blocks'),
    _('Within 5 blocks'),
    _('Within 2 blocks'),
    _('In the next block')
]


def normalize_version(v):
    return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")]


class NotEnoughFunds(Exception):
    pass

Esempio n. 38
0
    def prepareMainTemplate(self, request):
        # here will be generated the dictionary for the main template
        ret = getCollapsedMenus()
        ret['configsections'] = getConfigsSections()['sections']
        ret['showname'] = getShowName()['showname']
        ret['customname'] = getCustomName()['customname']
        ret['boxname'] = getBoxName()['boxname']
        if not ret['boxname'] or not ret['customname']:
            ret['boxname'] = getInfo()['brand'] + " " + getInfo()['model']
        ret['box'] = getBoxType()
        ret["remote"] = REMOTE
        if hasattr(eEPGCache, 'FULL_DESCRIPTION_SEARCH'):
            ret['epgsearchcaps'] = True
        else:
            ret['epgsearchcaps'] = False
        extras = [{'key': 'ajax/settings', 'description': _("Settings")}]
        ifaces = iNetwork.getConfiguredAdapters()
        if len(ifaces):
            ip_list = iNetwork.getAdapterAttribute(
                ifaces[0], "ip")  # use only the first configured interface
            if ip_list:
                ip = "%d.%d.%d.%d" % (ip_list[0], ip_list[1], ip_list[2],
                                      ip_list[3])

                if fileExists(
                        resolveFilename(SCOPE_PLUGINS,
                                        "Extensions/LCD4linux/WebSite.pyo")):
                    lcd4linux_key = "lcd4linux/config"
                    if fileExists(
                            resolveFilename(
                                SCOPE_PLUGINS,
                                "Extensions/WebInterface/plugin.pyo")):
                        try:
                            lcd4linux_port = "http://" + ip + ":" + str(
                                config.plugins.Webinterface.http.port.value
                            ) + "/"
                            lcd4linux_key = lcd4linux_port + 'lcd4linux/config'
                        except:  # noqa: E722
                            lcd4linux_key = None
                    if lcd4linux_key:
                        extras.append({
                            'key': lcd4linux_key,
                            'description': _("LCD4Linux Setup"),
                            'nw': '1'
                        })

        oscamwebif, port, oscamconf, variant = self.oscamconfPath()

        # Assume http until we know better ...
        proto = "http"

        # config file exists
        if oscamwebif and oscamconf is not None:
            # oscam defaults to NOT to start the web interface unless a section for it exists, so reset port to None until we find one
            port = None
            data = open(oscamconf, "r").readlines()
            for i in data:
                if "httpport" in i.lower():
                    port = i.split("=")[1].strip()
                    if port[0] == '+':
                        proto = "https"
                        port = port[1:]

        if oscamwebif and port is not None:
            url = "%s://%s:%s" % (proto, request.getRequestHostname(), port)
            if variant == "oscam":
                extras.append({
                    'key': url,
                    'description': _("OSCam Webinterface"),
                    'nw': '1'
                })
            elif variant == "ncam":
                extras.append({
                    'key': url,
                    'description': _("NCam Webinterface"),
                    'nw': '1'
                })

        try:
            from Plugins.Extensions.AutoTimer.AutoTimer import AutoTimer  # noqa: F401
            extras.append({'key': 'ajax/at', 'description': _('AutoTimer')})
        except ImportError:
            pass

        if fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/bqe.tmpl")
        ) or fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/bqe.pyo")):
            extras.append({
                'key': 'ajax/bqe',
                'description': _('BouquetEditor')
            })

        try:
            from Plugins.Extensions.EPGRefresh.EPGRefresh import epgrefresh  # noqa: F401
            extras.append({'key': 'ajax/epgr', 'description': _('EPGRefresh')})
        except ImportError:
            pass

        try:
            # this will currenly only works if NO Webiterface plugin installed
            # TODO: test if webinterface AND openwebif installed
            from Plugins.Extensions.WebInterface.WebChilds.Toplevel import loaded_plugins
            for plugins in loaded_plugins:
                if plugins[0] in [
                        "fancontrol", "iptvplayer", "serienrecorderui"
                ]:
                    try:
                        extras.append({
                            'key': plugins[0],
                            'description': plugins[2],
                            'nw': '2'
                        })
                    except KeyError:
                        pass
        except ImportError:
            pass

        if os.path.exists('/usr/bin/shellinaboxd') and (fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/terminal.tmpl"
                )
        ) or fileExists(
                resolveFilename(
                    SCOPE_PLUGINS,
                    "Extensions/OpenWebif/controllers/views/ajax/terminal.pyo")
        )):
            extras.append({
                'key': 'ajax/terminal',
                'description': _('Terminal')
            })

        ret['extras'] = extras
        theme = 'original'
        if config.OpenWebif.webcache.theme.value:
            theme = config.OpenWebif.webcache.theme.value
        if not os.path.exists(getPublicPath('themes')):
            if not (theme == 'original' or theme == 'clear'):
                theme = 'original'
                config.OpenWebif.webcache.theme.value = theme
                config.OpenWebif.webcache.theme.save()
        ret['theme'] = theme

        moviedb = config.OpenWebif.webcache.moviedb.value if config.OpenWebif.webcache.moviedb.value else 'IMDb'
        config.OpenWebif.webcache.moviedb.value = moviedb
        config.OpenWebif.webcache.moviedb.save()
        ret['moviedb'] = moviedb
        imagedistro = getInfo()['imagedistro']
        ret['vti'] = imagedistro in ("VTi-Team Image") and 1 or 0
        ret['webtv'] = os.path.exists(getPublicPath('webtv'))
        return ret
Esempio n. 39
0
 def changegroupsubset(self, bases, heads, kind):
     self.requirecap('changegroupsubset', _('look up remote changes'))
     bases = encodelist(bases)
     heads = encodelist(heads)
     f = self._callstream("changegroupsubset", bases=bases, heads=heads)
     return changegroupmod.unbundle10(self._decompress(f), 'UN')
Esempio n. 40
0
 def onSent(self, ok, msg, length, path):
     if ok:
         self.statusBar.addTx(length)
     else:
         self.hintSignal.emit("error", _("Error"),
                              _("Send data failed!") + " " + msg)
Esempio n. 41
0
def installParcel(parcel, oldVersion=None):
    blocks    = schema.ns("osaf.framework.blocks", parcel)
    main      = schema.ns("osaf.views.main", parcel)
    # The following trick finds the location of the directory containing
    # this file. This allows us to move the parcel to a new location without
    # editing any code in it.
    certstore = schema.ns(__name__[:__name__.rfind('.')], parcel)
    detail    = schema.ns("osaf.views.detail", parcel)

    certificateCollection = KindCollection.update(
        parcel, 'CertificateStore',
        displayName = _(u"Certificate Store"),
        kind = certstore.Certificate.getKind(parcel.itsView),
        recursive = True)
    
    #setting the preferredClass to MissingClass is a hint to display it in the All View
    UserCollection (certificateCollection).preferredClass = MissingClass

    addCertificateToSidebarEvent = Block.AddToSidebarEvent.update(
        parcel, 'addCertificateToSidebarEvent',
        blockName = 'addCertificateToSidebarEvent',
        item = certificateCollection,
        copyItems = False,
        disambiguateDisplayName = False)

    certMenu = blocks.Menu.update(
        parcel, "CertificateTestMenu",
        blockName = "CertificateTestMenu",
        title = _(u"&Certificates"),
        parentBlock = main.ToolsMenu)

    blocks.MenuItem.update(
        parcel, "CertificateView",
        blockName = "CertificateView",
        title = _(u"&Manage Certificates"),
        event = addCertificateToSidebarEvent,
        eventsForNamedLookup = [addCertificateToSidebarEvent],
        parentBlock = certMenu,
    )


    # Import
  
    importCertificateEvent = ImportCertificateEvent.update(
        parcel, 'importCertificateEvent',
        blockName = 'importCertificateEvent',
        collection = certificateCollection,
        collectionAddEvent = addCertificateToSidebarEvent,
        classParameter = certstore.Certificate)

    blocks.MenuItem.update(
        parcel, "CertificateImport",
        blockName = "CertificateImport",
        title = _(u"&Import Certificate..."),
        event = importCertificateEvent,
        eventsForNamedLookup = [importCertificateEvent],
        parentBlock = certMenu,
    )

    purposeArea = detail.makeArea(parcel, "PurposeArea",
        position = 0.1,
        childBlocks = [
            detail.makeLabel(parcel, _(u'purpose')),
            detail.makeSpacer(parcel, width=8),
            detail.makeEditor(parcel, 'PurposeAttribute',
                viewAttribute=u'purpose',
                stretchFactor=0.0,
                size=SizeType(60, -1)
            )]).install(parcel)
    
    trustArea = detail.makeArea(parcel, "TrustArea",
        position = 0.2,
        childBlocks = [
            detail.makeLabel(parcel, _(u"trust")),
            detail.makeSpacer(parcel, width=8),
            detail.makeEditor(parcel, "TrustAttribute",
                viewAttribute="trust",
                stretchFactor=0.0,
                size=SizeType(60, -1)
        )]).install(parcel)
    
    fingerprintArea = detail.makeArea(parcel, "FingerprintArea",
        position = 0.3,
        childBlocks = [
            detail.makeLabel(parcel, _(u"fingerprint")),
            detail.makeSpacer(parcel, width=8),
            detail.makeEditor(parcel, "FingerprintLabel",
                viewAttribute=u"fingerprint",
                stretchFactor = 0,
                size=SizeType(180, -1)
            )]).install(parcel)
    
    fingerprintAlgArea = detail.makeArea(parcel, "FingerprintAlgArea",
        position = 0.4,
        childBlocks = [
            detail.makeLabel(parcel, _(u"algorithm")),
            detail.makeSpacer(parcel, width=8),
            detail.makeEditor(parcel, "FingerprintAlgLabel",
                viewAttribute=u"fingerprintAlgorithm",
                stretchFactor = 0,
                size=SizeType(60, -1)
            )]).install(parcel)
    
    #XXX [i18n] Rather than getting all as text which cannot be localized,
    #XXX [i18n] make a field for each attribute in the certificate. These
    #XXX [i18n] can be localized easily. There is one blocker: there are a lot
    #XXX [i18n] of fields that should only appear if the cert has that field,
    #XXX [i18n] but there does not seem to be a way to implement that yet.
    asTextEditor = detail.makeEditor(parcel, 'AsTextAttribute',
        position = 0.9, 
        viewAttribute=u'asTextAsString',
        presentationStyle={'lineStyleEnum': 'MultiLine' },
    ).install(parcel)
    
    detail.makeSubtree(parcel, certstore.Certificate, [
        detail.MarkupBar,
        detail.makeSpacer(parcel, height=6, position=0.01).install(parcel),
        purposeArea,
        trustArea,
        fingerprintArea,
        fingerprintAlgArea,
        asTextEditor,
    ])
 def heads(self):
     d = self._call("heads")
     try:
         return decodelist(d[:-1])
     except:
         self._abort(error.ResponseError(_("unexpected response:"), d))
Esempio n. 43
0
 def lock(self, wait=True):
     raise util.Abort(_('cannot lock static-http repository'))
Esempio n. 44
0
from bungeni.models import schema, domain, utils, delegation
from bungeni.models.interfaces import ITranslatable

from zope.schema.interfaces import IVocabularyFactory
from zope.i18n import translate

from i18n import _

import datetime
from bungeni.core.translation import translate_obj
from bungeni.ui.calendar.utils import first_nth_weekday_of_month
from bungeni.ui.calendar.utils import nth_day_of_month
from bungeni.ui.calendar.utils import nth_day_of_week

days = [
    _('day_%d' % index, default=default)
    for (index, default) in enumerate((u"Mon", u"Tue", u"Wed", u"Thu", u"Fri",
                                       u"Sat", u"Sun"))
]


class WeekdaysVocabulary(object):
    interface.implements(IVocabularyFactory)

    def __call__(self, context):
        return vocabulary.SimpleVocabulary([
            vocabulary.SimpleTerm(nth_day_of_week(index), str(index), msg)
            for (index, msg) in enumerate(days)
        ])

Esempio n. 45
0
 def __init__(self, **kwargs):
     super(Int, self).__init__(int, **kwargs)
     self.msg_fmt = _('%s has to be an integer')
Esempio n. 46
0
def instance(ui, path, create):
    if create:
        raise util.Abort(_('cannot create new static-http repository'))
    return statichttprepository(ui, path[7:])
Esempio n. 47
0
 def validate(self, name, title, value):
     if value == "":
         raise ValidationError(_("%s must not be empty") %
                 title)
     return value
Esempio n. 48
0
 def __init__(self, **kwargs):
     super(Float, self).__init__(float, **kwargs)
     self.msg_fmt = _('%s has to be a float value')
Esempio n. 49
0
def handle_stats(relations: areas.Relations,
                 request_uri: str) -> yattag.doc.Doc:
    """Expected request_uri: e.g. /osm/housenumber-stats/hungary/."""
    if request_uri.endswith("/cityprogress"):
        return handle_stats_cityprogress(relations)

    if request_uri.endswith("/invalid-relations"):
        return handle_invalid_refstreets(relations)

    doc = yattag.doc.Doc()
    doc.asis(get_toolbar(relations).getvalue())

    prefix = config.Config.get_uri_prefix()

    # Emit localized strings for JS purposes.
    with doc.tag("div", style="display: none;"):
        string_pairs = [
            ("str-daily-title",
             _("New house numbers, last 2 weeks, as of {}")),
            ("str-daily-x-axis", _("During this day")),
            ("str-daily-y-axis", _("New house numbers")),
            ("str-monthly-title", _("New house numbers, last year, as of {}")),
            ("str-monthly-x-axis", _("During this month")),
            ("str-monthly-y-axis", _("New house numbers")),
            ("str-monthlytotal-title",
             _("All house numbers, last year, as of {}")),
            ("str-monthlytotal-x-axis", _("Latest for this month")),
            ("str-monthlytotal-y-axis", _("All house numbers")),
            ("str-dailytotal-title",
             _("All house numbers, last 2 weeks, as of {}")),
            ("str-dailytotal-x-axis", _("At the start of this day")),
            ("str-dailytotal-y-axis", _("All house numbers")),
            ("str-topusers-title", _("Top house number editors, as of {}")),
            ("str-topusers-x-axis", _("User name")),
            ("str-topusers-y-axis",
             _("Number of house numbers last changed by this user")),
            ("str-topcities-title", _("Top edited cities, as of {}")),
            ("str-topcities-x-axis", _("City name")),
            ("str-topcities-y-axis",
             _("Number of house numbers added in the past 30 days")),
            ("str-topcities-empty", _("(empty)")),
            ("str-topcities-invalid", _("(invalid)")),
            ("str-usertotal-title",
             _("Number of house number editors, as of {}")),
            ("str-usertotal-x-axis", _("All editors")),
            ("str-usertotal-y-axis",
             _("Number of editors, at least one housenumber is last changed by these users"
               )),
            ("str-progress-title", _("Coverage is {1}%, as of {2}")),
            ("str-progress-x-axis", _("Number of house numbers in database")),
            ("str-progress-y-axis", _("Data source")),
        ]
        for key, value in string_pairs:
            kwargs: Dict[str, str] = {}
            kwargs["id"] = key
            kwargs["data-value"] = value
            with doc.tag("div", **kwargs):
                pass

    title_ids = [
        (_("New house numbers"), "daily"),
        (_("All house numbers"), "dailytotal"),
        (_("New house numbers, monthly"), "monthly"),
        (_("All house numbers, monthly"), "monthlytotal"),
        (_("Top house number editors"), "topusers"),
        (_("Top edited cities"), "topcities"),
        (_("All house number editors"), "usertotal"),
        (_("Coverage"), "progress"),
        (_("Per-city coverage"), "cityprogress"),
        (_("Invalid relation settings"), "invalid-relations"),
    ]

    with doc.tag("ul"):
        for title, identifier in title_ids:
            with doc.tag("li"):
                if identifier == "cityprogress":
                    with doc.tag("a",
                                 href=prefix +
                                 "/housenumber-stats/hungary/cityprogress"):
                        doc.text(title)
                    continue
                if identifier == "invalid-relations":
                    with doc.tag(
                            "a",
                            href=prefix +
                            "/housenumber-stats/hungary/invalid-relations"):
                        doc.text(title)
                    continue
                with doc.tag("a", href="#_" + identifier):
                    doc.text(title)

    for title, identifier in title_ids:
        if identifier in ("cityprogress", "invalid-relations"):
            continue
        with doc.tag("h2", id="_" + identifier):
            doc.text(title)
            with doc.tag("div", klass="canvasblock"):
                with doc.tag("canvas", id=identifier):
                    pass

    with doc.tag("h2"):
        doc.text(_("Note"))
    with doc.tag("div"):
        doc.text(
            _("""These statistics are provided purely for interested editors, and are not
intended to reflect quality of work done by any given editor in OSM. If you want to use
them to motivate yourself, that's fine, but keep in mind that a bit of useful work is
more meaningful than a lot of useless work."""))

    doc.asis(get_footer().getvalue())
    return doc
Esempio n. 50
0
 def validate(self, name, title, value):
     if not value in self.item_list:
         raise ValidationError(
             _("%(title)s has to be one of %(items)s") %
             { 'title': title, 'items': ', '.join(self.item_list)})
     return value
Esempio n. 51
0
def get_toolbar(relations: Optional[areas.Relations] = None,
                function: str = "",
                relation_name: str = "",
                relation_osmid: int = 0) -> yattag.doc.Doc:
    """Produces the start of the page. Note that the content depends on the function and the
    relation, but not on the action to keep a balance between too generic and too specific
    content."""
    items: List[yattag.doc.Doc] = []

    if relations and relation_name:
        relation = relations.get_relation(relation_name)
        streets = relation.get_config().should_check_missing_streets()

    doc = yattag.doc.Doc()
    prefix = config.Config.get_uri_prefix()
    with doc.tag("a", href=prefix + "/"):
        doc.text(_("Area list"))
    items.append(doc)

    if relation_name:
        fill_missing_header_items(streets, relation_name, items)

    fill_header_function(function, relation_name, items)

    if relation_name:
        fill_existing_header_items(streets, relation_name, items)

    doc = yattag.doc.Doc()

    # Emit localized strings for JS purposes.
    with doc.tag("div", style="display: none;"):
        string_pairs = [
            ("str-toolbar-overpass-wait", _("Waiting for Overpass...")),
            ("str-toolbar-overpass-error", _("Error from Overpass: "******"str-toolbar-reference-wait", _("Creating from reference...")),
            ("str-toolbar-reference-error", _("Error from reference: ")),
        ]
        for key, value in string_pairs:
            kwargs: Dict[str, str] = {}
            kwargs["id"] = key
            kwargs["data-value"] = value
            with doc.tag("div", **kwargs):
                pass

    with doc.tag("a", href="https://overpass-turbo.eu/"):
        doc.text(_("Overpass turbo"))
    items.append(doc)

    if relation_osmid:
        doc = yattag.doc.Doc()
        with doc.tag("a",
                     href="https://www.openstreetmap.org/relation/" +
                     str(relation_osmid)):
            doc.text(_("Area boundary"))
        items.append(doc)
    else:
        # These are on the main page only.
        doc = yattag.doc.Doc()
        with doc.tag("a", href=prefix + "/housenumber-stats/hungary/"):
            doc.text(_("Statistics"))
        items.append(doc)

        doc = yattag.doc.Doc()
        with doc.tag(
                "a",
                href="https://github.com/vmiklos/osm-gimmisn/tree/master/doc"):
            doc.text(_("Documentation"))
        items.append(doc)

    doc = yattag.doc.Doc()
    with doc.tag("div", id="toolbar"):
        for index, item in enumerate(items):
            if index:
                doc.text(" ¦ ")
            doc.asis(item.getvalue())
    doc.stag("hr")
    return doc
Esempio n. 52
0
def fill_header_function(function: str, relation_name: str,
                         items: List[yattag.doc.Doc]) -> None:
    """Fills items with function-specific links in the header. Returns a title."""
    prefix = config.Config.get_uri_prefix()
    if function == "missing-housenumbers":
        # The OSM data source changes much more frequently than the ref one, so add a dedicated link
        # to update OSM house numbers first.
        doc = yattag.doc.Doc()
        with doc.tag("span", id="trigger-street-housenumbers-update"):
            with doc.tag("a",
                         href=prefix + "/street-housenumbers/" +
                         relation_name + "/update-result"):
                doc.text(_("Update from OSM"))
        items.append(doc)

        doc = yattag.doc.Doc()
        with doc.tag("span", id="trigger-missing-housenumbers-update"):
            with doc.tag("a",
                         href=prefix + "/missing-housenumbers/" +
                         relation_name + "/update-result"):
                doc.text(_("Update from reference"))
        items.append(doc)
    elif function in ("missing-streets", "additional-streets"):
        # The OSM data source changes much more frequently than the ref one, so add a dedicated link
        # to update OSM streets first.
        doc = yattag.doc.Doc()
        with doc.tag("span", id="trigger-streets-update"):
            with doc.tag("a",
                         href=prefix + "/streets/" + relation_name +
                         "/update-result"):
                doc.text(_("Update from OSM"))
        items.append(doc)

        doc = yattag.doc.Doc()
        with doc.tag("span", id="trigger-missing-streets-update"):
            with doc.tag("a",
                         href=prefix + "/missing-streets/" + relation_name +
                         "/update-result"):
                doc.text(_("Update from reference"))
        items.append(doc)
    elif function == "street-housenumbers":
        doc = yattag.doc.Doc()
        with doc.tag("span", id="trigger-street-housenumbers-update"):
            with doc.tag("a",
                         href=prefix + "/street-housenumbers/" +
                         relation_name + "/update-result"):
                doc.text(_("Call Overpass to update"))
        items.append(doc)
        doc = yattag.doc.Doc()
        with doc.tag("a",
                     href=prefix + "/street-housenumbers/" + relation_name +
                     "/view-query"):
            doc.text(_("View query"))
        items.append(doc)
    elif function == "streets":
        doc = yattag.doc.Doc()
        with doc.tag("span", id="trigger-streets-update"):
            with doc.tag("a",
                         href=prefix + "/streets/" + relation_name +
                         "/update-result"):
                doc.text(_("Call Overpass to update"))
        items.append(doc)
        doc = yattag.doc.Doc()
        with doc.tag("a",
                     href=prefix + "/streets/" + relation_name +
                     "/view-query"):
            doc.text(_("View query"))
        items.append(doc)
Esempio n. 53
0
 def choose_hw_device(self):
     title = _('Hardware Keystore')
     # check available plugins
     support = self.plugins.get_hardware_support()
     if not support:
         msg = '\n'.join([
             _('No hardware wallet support found on your system.'),
             _('Please install the relevant libraries (eg python-trezor for Trezor).'
               ),
         ])
         self.confirm_dialog(title=title,
                             message=msg,
                             run_next=lambda x: self.choose_hw_device())
         return
     # scan devices
     devices = []
     devmgr = self.plugins.device_manager
     for name, description, plugin in support:
         try:
             # FIXME: side-effect: unpaired_device_info sets client.handler
             u = devmgr.unpaired_device_infos(None, plugin)
         except:
             devmgr.print_error("error", name)
             continue
         devices += map(lambda x: (name, x), u)
     if not devices:
         msg = ''.join([
             _('No hardware device detected.') + '\n',
             _('To trigger a rescan, press \'Next\'.') + '\n\n',
             _('If your device is not detected on Windows, go to "Settings", "Devices", "Connected devices", and do "Remove device". Then, plug your device again.'
               ) + ' ',
             _('On Linux, you might have to add a new permission to your udev rules.'
               ),
         ])
         self.confirm_dialog(title=title,
                             message=msg,
                             run_next=lambda x: self.choose_hw_device())
         return
     # select device
     self.devices = devices
     choices = []
     for name, info in devices:
         state = _("initialized") if info.initialized else _("wiped")
         label = info.label or _("An unnamed %s") % name
         descr = "%s [%s, %s]" % (label, name, state)
         choices.append(((name, info), descr))
     msg = _('Select a device') + ':'
     self.choice_dialog(title=title,
                        message=msg,
                        choices=choices,
                        run_next=self.on_device)
Esempio n. 54
0
def handle_stats_cityprogress(relations: areas.Relations) -> yattag.doc.Doc:
    """Expected request_uri: e.g. /osm/housenumber-stats/hungary/cityprogress."""
    doc = yattag.doc.Doc()
    doc.asis(get_toolbar(relations).getvalue())

    ref_citycounts: Dict[str, int] = {}
    with open(config.Config.get_reference_citycounts_path(), "r") as stream:
        first = True
        for line in stream.readlines():
            if first:
                first = False
                continue
            cells = line.strip().split('\t')
            if len(cells) < 2:
                continue
            city = cells[0]
            count = int(cells[1])
            ref_citycounts[city] = count
    today = time.strftime("%Y-%m-%d")
    osm_citycounts: Dict[str, int] = {}
    with open(config.Config.get_workdir() + "/stats/" + today + ".citycount",
              "r") as stream:
        for line in stream.readlines():
            cells = line.strip().split('\t')
            if len(cells) < 2:
                continue
            city = cells[0]
            count = int(cells[1])
            osm_citycounts[city] = count
    cities = util.get_in_both(list(ref_citycounts.keys()),
                              list(osm_citycounts.keys()))
    cities.sort(key=locale.strxfrm)
    table = []
    table.append([
        util.html_escape(_("City name")),
        util.html_escape(_("House number coverage")),
        util.html_escape(_("OSM count")),
        util.html_escape(_("Reference count"))
    ])
    for city in cities:
        percent = "100.00"
        if ref_citycounts[city] > 0 and osm_citycounts[city] < ref_citycounts[
                city]:
            percent = "%.2f" % (osm_citycounts[city] / ref_citycounts[city] *
                                100)
        table.append([
            util.html_escape(city),
            util.html_escape(util.format_percent(percent)),
            util.html_escape(str(osm_citycounts[city])),
            util.html_escape(str(ref_citycounts[city]))
        ])
    doc.asis(util.html_table_from_list(table).getvalue())

    with doc.tag("h2"):
        doc.text(_("Note"))
    with doc.tag("div"):
        doc.text(
            _("""These statistics are estimates, not taking house number filters into account.
Only cities with house numbers in OSM are considered."""))

    doc.asis(get_footer().getvalue())
    return doc
Esempio n. 55
0
def explainexit(code):
    """return a 2-tuple (desc, code) describing a subprocess status
    (codes from kill are negative - not os.system/wait encoding)"""
    if code >= 0:
        return _("exited with status %d") % code, code
    return _("killed by signal %d") % -code, -code
Esempio n. 56
0
 def setbranch(self, branch):
     if branch in ['tip', '.', 'null']:
         raise util.Abort(_('the name \'%s\' is reserved') % branch)
     self._branch = encoding.fromlocal(branch)
     self._opener("branch", "w").write(self._branch + '\n')
Esempio n. 57
0
class IBungeniSettings(interface.Interface):
    speakers_office_email = schema.TextLine(
        title=_(u"Speaker's Office Email"),
        default=u"*****@*****.**")
    speakers_office_notification = schema.Bool(
        title=_(u"Speaker's Office Notification"),
        description=_(u"Alert the speaker's office when a document is "
                      "submitted"),
        default=False)
    clerks_office_notification = schema.Bool(
        title=_(u"Clerk's Office Notification"),
        description=_(u"Alert the clerk's office by e-mail when a document is "
                      "submitted"),
        default=False)
    clerks_office_email = schema.TextLine(
        title=_(u"Clerks's Office Email"),
        default=u"*****@*****.**")
    ministries_notification = schema.Bool(
        title=_(u"Ministries Notification"),
        description=_(u"Notify concerned ministries by e-mail when a document "
                      "is submitted"),
        default=False)
    administrators_email = schema.TextLine(title=_(u"Administrator's Email"),
                                           default=u"*****@*****.**")
    question_submission_allowed = schema.Bool(
        title=_(u"Allow Question Submission"), default=True)
    days_to_defer_question = schema.Int(
        title=_(u"Days to Defer Question"),
        description=_(u"number of days after which admissible questions are "
                      "automatically deferred"),
        default=10)
    days_to_notify_ministry_unanswered = schema.Int(
        title=_(u"Days to Notify Ministry of Pending Response"),
        description=_(u"Days after which to notify concerned ministry and  "
                      "clerk's office of questions with pending responses"),
        default=5)
    days_before_question_schedule = schema.Int(
        title=_(u"Days before question scheduled"), default=3)
    days_before_bill_schedule = schema.Int(
        title=_(u"Days before bill scheduled"), default=3)
    max_questions_sitting = schema.Int(
        title=_(u"Maximum Questions Per Sitting"), default=15)
    max_mp_questions_sitting = schema.Int(
        title=_(u"Maximum Questions Per Sitting Per MP"), default=1)
    max_sittings_in_business = schema.Int(
        title=_(u"Number of sittings to include in what's business section"),
        default=5,
        min=1)
    bill_signatories_min = schema.Int(
        title=_(u"Minimum consented signatories for a bill"), default=0)
    bill_signatories_max = schema.Int(
        title=_(u"Maximum consented signatories for a bill"), default=0)
    question_signatories_min = schema.Int(
        title=_(u"Minimum consented signatories for a question"), default=0)
    question_signatories_max = schema.Int(
        title=_(u"Maximum consented signatories for a question"), default=0)
    motion_signatories_min = schema.Int(
        title=_(u"Minimum consented signatories for a motion"), default=0)
    motion_signatories_max = schema.Int(
        title=_(u"Maximum consented signatories for a motion"), default=0)
    agendaitem_signatories_min = schema.Int(
        title=_(u"Minimum consented signatories for an agenda item"),
        default=0)
    agendaitem_signatories_max = schema.Int(
        title=_(u"Maximum consented signatories for an agenda item"),
        default=0)
    tableddocument_signatories_min = schema.Int(
        title=_(u"Minimum consented signatories for a tabled document"),
        default=0)
    tableddocument_signatories_max = schema.Int(
        title=_(u"Maximum consented signatories for a tabled document"),
        default=0)
Esempio n. 58
0
    def choose_keystore(self):
        assert self.wallet_type in ['standard', 'multisig']
        i = len(self.keystores)
        title = _('Add cosigner') + ' (%d of %d)' % (
            i + 1, self.n) if self.wallet_type == 'multisig' else _('Keystore')
        if self.wallet_type == 'standard' or i == 0:
            message = _(
                'Do you want to create a new seed, or to restore a wallet using an existing seed?'
            )
            choices = [
                ('create_seed', _('Create a new seed')),
                ('restore_from_seed', _('I already have a seed')),
                ('restore_from_key', _('Use public or private keys')),
            ]
            if not self.is_kivy:
                choices.append(
                    ('choose_hw_device', _('Use a hardware device')))
        else:
            message = _('Add a cosigner to your multi-sig wallet')
            choices = [
                ('restore_from_key', _('Enter cosigner key')),
                ('restore_from_seed', _('Enter cosigner seed')),
            ]
            if not self.is_kivy:
                choices.append(
                    ('choose_hw_device', _('Cosign with hardware device')))

        self.choice_dialog(title=title,
                           message=message,
                           choices=choices,
                           run_next=self.run)
Esempio n. 59
0
 def channel_description(self):
     return "%s %s" % (self.i18n_context.short_name,
                       _(u"timeline"))
Esempio n. 60
0
class IBungeniUserSettings(interface.Interface):

    # examples
    email_delivery = schema.Bool(title=_(u"Email Notifications Enabled?"),
                                 default=True)