def do_translate(self, language=None):
   if self.swapping or not self.applet.nwmon.connected():
     return
   #print "len jobs: %i" % len(self.jobs)
   # the 'language' argument is not used but has to be here!
   self.def_from = translate_from = str(self.language_from.nativeWidget().itemData(self.language_from.nativeWidget().currentIndex()).toString())
   self.def_to = translate_to = str(self.language_to.nativeWidget().itemData(self.language_to.nativeWidget().currentIndex()).toString())
   #self.def_to = translate_to = str(self.language_to.text())
   #self.def_from = translate_from = str(self.language_from.text())
   self.applet.cfg.writeEntry("default_from", translate_from)
   self.applet.cfg.writeEntry("default_to", translate_to)
   self.applet.cfg.writeEntry("default_string", self.text.text())
   self.applet.cfg.sync()
   #print "translate from: " + translate_from + " to: " + translate_to
   langpair='%s|%s' % (translate_from,translate_to)
   params=urlencode( (('v',1.0),
                     ('ie', 'UTF8'),
                     ('q',self.text.text().toUtf8()),
                     ('langpair',langpair),) )
   url=translate_url+params
   #print url
   self.applet.setBusy(True)
   self.invert_button.setEnabled(False)
   job = KIO.get(KUrl(url), KIO.NoReload, KIO.HideProgressInfo)
   self.jobs[job] = {}
   self.jobs[job]['idx'] = 0
   self.jobs[job]['data'] = ""
   #self.jobs[job]['mimetype'] = ""
   job.data.connect(self.job_received)
   #job.mimetype.connect(self.job_mimetype)
   try:
     job.result.connect(self.translation_job_done)
   except:
     debug("missing new-style support for KIO.Job.result")
     QObject.connect(job, SIGNAL("result( KJob *)"), self.translation_job_done)
  def detect_language(self):
    if self.swapping or not self.applet.nwmon.connected():
      return
    params=urlencode( (('v',1.0),
		      ('ie', 'UTF8'),
                      ('q',self.text.text().toUtf8()))
                      )
    url=detect_url+params
    #print url
    self.applet.setBusy(True)
    #self.detect_button.setEnabled(False)
    job = KIO.get(KUrl(url), KIO.NoReload, KIO.HideProgressInfo)
    self.jobs[job] = {}
    self.jobs[job]['idx'] = 0
    self.jobs[job]['data'] = ""
    #self.jobs[job]['mimetype'] = ""
    job.data.connect(self.job_received)
    #job.mimetype.connect(self.job_mimetype)
    try:
      # This should work from KDE SC 4.5
      job.result.connect(self.detect_job_done)
    except AttributeError as (errno, strerror):
      print "I/O error({0}): {1}".format(errno, strerror)
      debug("missing new-style support for KIO.Job.result")
      QObject.connect(job, SIGNAL("result( KJob *)"), self.detect_job_done)
 def setEnabled(self, state):
   debug("setEnabled(%i)" % state)
   self.invert_button.setEnabled(state)
   self.go_button.setEnabled(state)
   self.language_from.setEnabled(state)
   self.language_to.setEnabled(state)
   self.translation_result.setEnabled(state)
   self.text.setEnabled(state)
Ejemplo n.º 4
0
 def netstate_changed(self, connected):
     print "GoogleTranslatorApplet: Network status changed! %i" % connected
     if connected:
         debug("GoogleTranslatorApplet: Connected!")
         self._widget.setEnabled(True)
         self.setBusy(False)
     else:
         self.notifier.notify("waiting-for-network", i18n("Waiting for network connection."))
         self._widget.setEnabled(False)
         debug("GoogleTranslatorApplet: Not connected!")
         self.setBusy(True)
Ejemplo n.º 5
0
def check_lock():
    """
    Check the lock file.

    If there is a lock file, then the daemon is running and this
    instance will quit.
    If there is no lock file, then this instance will be the running
    daemon. In this case the lock file is created.
    """
    if os.path.exists(cfg.LOCK):
        debug('daemon already running; not starting another instance')
        sys.exit()
    # else
    os.system("touch {lock}".format(lock=cfg.LOCK))
Ejemplo n.º 6
0
    def configChanged(self):
        debug("GoogleTranslator: configChanged")
        # TODO:
        #	Clear ComboBoxes
        #	Add languages
        #	Select languages
        #	Translate
        defaultSize =  QVariant(QSize (0,0))
        size = self.cfg.readEntry("size", defaultSize ).toSize()
        if (size != defaultSize) :
            self._widget.setPreferredSize(size.width(), size.height())
        else:
            self._widget.setPreferredSize(400 ,200)

        self.connect(self._widget, SIGNAL("resized()"), self.dialog_resized)
Ejemplo n.º 7
0
    def init(self):
        debug("GoogleTranslatorApplet: init().")
        BasePlasmoid.init(self)

        self._widget = None
        self.setHasConfigurationInterface(False)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)

        self.notifier = Notifier(self)
        self.nwmon = NetworkMonitor()
        if self.nwmon.connected():
          self.setBusy(False)
        else:
            self.notifier.notify("waiting-for-network", i18n("Waiting for network connection."))

        self.nwmon.status_changed.connect(self.netstate_changed)

        # Main widget
        debug("GoogleTranslatorApplet: Creating main widget.")
        self._widget = GoogleTranslator(self)
        self._widget.init()
        self.setGraphicsWidget(self._widget)
        self.setPopupIcon(self.metadata.pluginName())

        self.setGraphicsWidget(self._widget)

        # Tool tip for panel
        self.metadata = self.package().metadata()
        self.tooltipdata = Plasma.ToolTipContent()
        self.tooltipdata.setMainText(self.metadata.name())
        self.tooltipdata.setSubText(self.metadata.description())
        self.tooltipdata.setImage(KIcon(self.metadata.pluginName()))
        Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata)

        # Only register the tooltip in panels
        #if (self.formFactor() != Plasma.Planar):
        if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)):
            print("GoogleTranslatorApplet: In Panel")
            Plasma.ToolTipManager.self().registerWidget(self.applet)
        else:
            Plasma.ToolTipManager.self().unregisterWidget(self.applet)
            print("GoogleTranslatorApplet: Not in Panel")

        self.configChanged()
  def translation_job_done(self, job):
    debug("job_done")
    if self.jobs.has_key(job):
      d = unicode(self.jobs[job]['data'], encoding='utf-8')
      jsdata = simplejson.loads(d)
      if jsdata['responseStatus'] == 200:
        #print unicode(jsdata['responseData']['translatedText'])
        self.translation_result.setText(jsdata['responseData']['translatedText'])
      elif jsdata['responseStatus'] == 400:
        if jsdata['responseDetails'] != None:
	  self.applet.showMessage(KIcon("info"), i18n("Translation error: %s" % jsdata['responseDetails']), Plasma.ButtonOk)
          self.translation_result.setText(jsdata['responseDetails'])
        else:
	  self.applet.showMessage(KIcon("info"), i18n("Unknown translation error!"), Plasma.ButtonOk)
          self.translation_result.setText(i18n("Unknown translation error!"))
      else:
	self.applet.showMessage(KIcon("info"), i18n("Unknown translation error!"), Plasma.ButtonOk)
        self.translation_result.setText(i18n("Unknown translation error!"))
      del self.jobs[job]
      self.applet.setBusy(False)
      self.invert_button.setEnabled(True)
    def __init__(self):
        QtCore.QObject.__init__(self)

        self.is_connected = (Solid.Networking.status() == Solid.Networking.Connected) or (Solid.Networking.status() == Solid.Networking.Unknown) == True
        print "NetworkMonitor: %i" % self.is_connected

        try:
            # Apparently this is only possible from KDE SC 4.4.X
            notifier = Solid.Networking.notifier()
            #notifier.statusChanged.connect(self.netstate_changed)
            notifier.connect(notifier, QtCore.SIGNAL("statusChanged(Solid::Networking::Status)"), self.netstate_changed)
            debug("NetworkMonitor: Connected to network notifier.")
        except AttributeError as e: # (errno, strerror):
            #print "I/O error({0}): {1}".format(errno, strerror)
            debug(e)
            debug("NetworkMonitor: Trouble setting up network monitor")
        except:
            debug("NetworkMonitor: Trouble setting up network monitor")
            print "NetworkMonitor: Unexpected error:", sys.exc_info()[0]

        print "NetworkMonitor: Network is connected:", (Solid.Networking.status() == Solid.Networking.Connected)
        print "NetworkMonitor: Current status:", statusString[Solid.Networking.status()]
Ejemplo n.º 10
0
def main():
    """
    Controller.

    If there is no running daemon, then let's start working.
    Process every task and wait a little bit after each.
    The producer(s) may create lots of small tasks that are
    processed very fast, thus we wait a little bit.
    When all tasks are treated, we quit.
    """
    check_lock()
    debug("="*50)
    debug('start daemon')
    #
    while process():
        sleep(0.05)
    #
    debug('stop daemon')
    remove_lock()
  def detect_job_done(self, job):
    debug("detect_job_done")
    if self.jobs.has_key(job):
      d = unicode(self.jobs[job]['data'], encoding='utf-8')
      #d = QString.fromUtf8(self.jobs[job]['data'])
      #print d
      jsdata = simplejson.loads(d)
      print jsdata
      lang = ""
      if jsdata['responseStatus'] == 200:
        debug(jsdata['responseData']['language'])
        lang = jsdata['responseData']['language']
      elif jsdata['responseStatus'] == 400:
        if jsdata['responseDetails'] != None:
	  self.applet.showMessage(KIcon("info"), i18n("Language detection error: %s" % jsdata['responseDetails']), Plasma.ButtonOk)
          self.translation_result.setText(jsdata['responseDetails'])
        else:
	  self.applet.showMessage(KIcon("info"), i18n("Unknown translation error!"), Plasma.ButtonOk)
          self.translation_result.setText(i18n("Unknown detection error!"))
      else:
        #self.applet.showMessage(QIcon("info"), i18n("Unknown translation error!"), Plasma.MessageButton.ButtonOk(0))
	self.applet.showMessage(KIcon("info"), i18n("Unknown translation error!"), Plasma.ButtonOk)
        self.translation_result.setText(i18n("Unknown detection error!"))
      #self.job_part = "" # to be removed
      del self.jobs[job]
      self.applet.setBusy(False)
      #self.detect_button.setEnabled(True)

      languages = self.get_languages()
      language_names = languages.keys()
      language_names.sort()
      i = 0
      for language_name in language_names:
        language_code = languages[language_name]
        if str(language_code).upper() == lang.upper():
          self.language_from.nativeWidget().setCurrentIndex(i)
          break
        i+=1
      else:
        debug(u"Detected language %s was not found in KDE." % lang)
 def job_info(self, job, info):
   debug("job_info %s: " % str(info))
Ejemplo n.º 13
0
def subtract(x, y):
    """Subtract Function"""
    return x - y


def multiply(x, y):
    """Multiply Function"""
    return x * y


def divide(x, y):
    """Divide Function"""
    return x / y


num_1 = 20
num_2 = 10

add_result = add(num_1, num_2)
mylogging.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))

sub_result = subtract(num_1, num_2)
mylogging.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))

mul_result = multiply(num_1, num_2)
mylogging.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))

div_result = divide(num_1, num_2)
mylogging.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))