Example #1
0
 def follow(self):
     global TRACES
     self.enable()
     lastLat, lastLon = None, None
     if not self.inMemory:
         if not os.path.isfile(self.filename):
             f = open(self.filename, 'w')
             f.write("date,latitude,longitude\n")
             f.close()
     while not self.stopFollow:
         lat, lon = self.getCurrentLocation()
         #print "follow current:{0},{1}".format(lat, lon)
         if (lat is not None and lon is not None) and (lastLat != lat
                                                       or lastLon != lon):
             #print "follow modified:{0},{1}".format(lat, lon)
             if not self.inMemory:
                 f = open(self.filename, 'a+')
                 f.write("{0},{1},{2}\n".format(
                     datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
                     lat, lon))
                 f.close()
             else:
                 TRACES.append([
                     datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
                     lat, lon
                 ])
         lastLat, lastLon = lat, lon
         sleep(self.period)
     self.disable()
     jnius.detach(
     )  #For fixing a BUG, see https://github.com/kivy/pyjnius/issues/107
Example #2
0
 def _run_find_brick(self):
     try:
         self.brick = nxt.find_one_brick(debug=True)
     finally:
         # kivy/android will crash here if we don't detach
         print('detaching thread')
         detach()
Example #3
0
 def run(self):
     try:
         jnius.autoclass('java.lang.System').out.println('Hello world')
     except:
         pass
     finally:
         jnius.detach()
Example #4
0
 def on_stop(self):
     if 'ANDROID_DATA' in os.environ:
         import jnius
         jnius.detach()
         self.logger.info("jnius detach")
     self.logger.info("stopped")
     self.stopped_event.set()
 def _run_find_brick(self):
     try:
         self.brick = nxt.find_one_brick(debug=True)
     finally:
         # kivy/android will crash here if we don't detach
         print('detaching thread')
         detach()
Example #6
0
def test2(arg):
    try:
        c=jnius.autoclass("ysoserial.exploit.RMIRegistryExploit")
        c.main(arg)
    except jnius.JavaException as e:
        if e.classname=="java.rmi.ServerException":
            print("have a rmi error")
    finally:
        jnius.detach()
Example #7
0
 def on_stop(self):
     if 'ANDROID_DATA' in os.environ:
         try:
             import jnius
             jnius.detach()
             root_logger.debug("jnius detach")
         except ImportError:
             pass  # Chaquopy detaches automatically.
     root_logger.debug("stopped")
Example #8
0
 def on_stop(self):
     if 'ANDROID_DATA' in os.environ:
         try:
             import jnius
             jnius.detach()
             self.print_error("jnius detach")
         except ImportError:
             pass  # Chaquopy detaches automatically.
     self.print_error("stopped")
Example #9
0
 def start_listening(self, from_thread=False):
     if self.is_stopped:
         try:
             self.nsd_mgr.discoverServices('_http._tcp',
                                           self.NsdManager.PROTOCOL_DNS_SD,
                                           self)
         finally:
             if from_thread:
                 detach()
Example #10
0
 def handler(*args, **kwargs):
     try:
         function(*args, **kwargs)
     except Exception as error:
         print("[AppUpdater]", error)
         import traceback
         traceback.print_exc()
     finally:
         jnius.detach()
Example #11
0
    def run(self, *args: str):

        try:
            jnius_config.add_options(*args)
            log.info("Configured jvm options:%s" % jnius_config.get_options())

            from jnius import autoclass
            DebeziumServer = autoclass('io.debezium.server.Main')
            _dbz = DebeziumServer()
            return _dbz.main()
        finally:
            from jnius import detach
            detach()
Example #12
0
	def loadThumbnails(self):
		while True:
			#self.wid_sem.acquire()
			wid = self.non_thumbnailed.get() #Queue blocks thread until not-empty
			#if the object is a specific finished object,
			#we close the thread so the application can close
			if(wid is self.Finished): 
				print "Ending Thumbnail Thread"
				detach()
				break
			print wid.uri
			wid.makeFileThumbnail()
		detach()
Example #13
0
def hourlyFFMCLawson(
        prevFFMC: float,  # pylint: disable=invalid-name
        currFFMC: float,
        rh: float,
        seconds_into_day: int) -> float:
    """ Ok - great - but what does this even do? """
    import jnius  # pylint: disable=import-outside-toplevel
    try:
        CwfgmFwi = jnius.autoclass('ca.cwfgm.fwi.CwfgmFwi')  # pylint: disable=invalid-name
        return CwfgmFwi.hourlyFFMCLawson(prevFFMC, currFFMC, rh,
                                         seconds_into_day)
    finally:
        jnius.detach()  # pylint: disable=no-member
Example #14
0
def SystemIsOnline():
    """
    verifies, if the system has a network connection by system APIs (not by ping)
    returns true, if OS doesn't support it
    """
    try:
        Logger.debug("Checking Android network connectivity")
        Hardware = GetAndroidModule("Hardware")
        bRet = Hardware.checkNetwork()
        detach()
        return bRet
    except Exception as e:
        LogError('SystemIsOnline:', e)
        return True
Example #15
0
 def run(self):
     if self._target is not None:
         try:
             self._return = self._target(*self._args, **self._kwargs)
         except:
             logging.exception("Uncaught exception in thread")
             self._return = -1
         finally:
             # Detach Jnius on Android
             try:
                 import jnius
                 jnius.detach()
             except:
                 pass
Example #16
0
 def loadThumbnails(self):
     while True:
         #self.wid_sem.acquire()
         wid = self.non_thumbnailed.get(
         )  #Queue blocks thread until not-empty
         #if the object is a specific finished object,
         #we close the thread so the application can close
         if (wid is self.Finished):
             print "Ending Thumbnail Thread"
             detach()
             break
         print wid.uri
         wid.makeFileThumbnail()
     detach()
Example #17
0
def OS_SystemIsOnline():
    '''
    verifies, if the system has a network connection by system APIs (not by ping)
    returns true, if OS doesn't support it
    '''
    try:
        if oORCA.uPlatform==u'android':
            Logger.debug("Checking Android network connectivity")
            bRet=Hardware.checkNetwork()
            detach()
            return bRet
        return True
    except Exception as e:
        LogError('OS_SystemIsOnline:',e)
        return True
Example #18
0
 def serve_till(*args):
     import requests.packages.urllib3
     requests.packages.urllib3.disable_warnings()
     try:
         AuthHandler.stop_serving = False
         while not AuthHandler.stop_serving:
             self.server.handle_request()
     except Exception as err:
         print err
     print 'callback....'
     self.callback()
     import jnius
     print 'calling detach....'
     # Setting server to None to avoid binding of server
     # in current thread to port 8080 and hence avoid socket error
     self.server = None
     jnius.detach()
Example #19
0
def bt_rx_thread():
    Logger.info('RC_SVC: ############################## bt_rx_thread started ##############################')
    while service_should_run.is_set():
        try:
            msg = bt_connection.read_line()
            if msg:
                osc.sendMsg(RX_API, [msg, ], port=CLIENT_API_PORT)
        except PortNotOpenException:
            sleep(1.0)
            pass                
        except Exception as e:
            Logger.info('RC_SVC: Exception in rx_message_thread')
            traceback.print_exc()
            osc.sendMsg(CMD_API, ["ERROR", ], port=CLIENT_API_PORT)
            sleep(1.0)
    jnius.detach() #detach the current thread from pyjnius, else hard crash occurs 
    Logger.info('RC_SVC: ############################## bt_rx_thread exited ##############################')
Example #20
0
    def stop_listening(self, block=False, from_thread=False):
        if self.is_stopped:
            # already stopped!
            return

        #TODO: detect Threading automatically
        #if not isinstance(threading.current_thread(), threading.__MainThread):

        # try to stop
        try:
            self.nsd_mgr.stopServiceDiscovery(self)

            if block:
                while self.is_stopped == False:
                    if self.startstop_failed:
                        break
        finally:
            if from_thread:
                detach()
Example #21
0
 def _stream_reader(self, *args):
     stream = ''
     while True:
         if self._stop.is_set():
             jnius.detach()
             return
         if self._connected:
             try:
                 stream = self._recv_stream.readLine()
             except self.IOException as e:
                 raise BTCommunicatorException("{} {}".format(self._lang['messages']['receive_error_IOException'], e.message))
             except jnius.JavaException as e:
                 raise BTCommunicatorException("{} {}".format(self._lang['messages']['receive_error_JavaException'], e.message))
             except:
                 raise BTCommunicatorException("{} {}".format(self._lang['messages']['receive_error_Unknown'], sys.exc_info()[0]))
             try:
                 start = stream.rindex("<") + 1
                 end = stream.rindex(">", start)
                 self._add_response(stream[start:end])
             except ValueError:
                 pass
Example #22
0
    def run(self):
        """
        Main worker.
        """
        #self.sgnBusy.emit(True)

        self.reason_over_ontology()
        detach()

        #self.sgnBusy.emit(False)
        if self.project.inconsistent_ontology is not None:
            if self.project.inconsistent_ontology is True:
                self.sgnOntologyInconsistency.emit()
            else:
                if len(self.project.unsatisfiable_classes) or len(
                        self.project.unsatisfiable_attributes) or len(
                            self.project.unsatisfiable_roles):
                    self.sgnUnsatisfiableEntities.emit()
                else:
                    self.sgnAllOK.emit()

            self.finished.emit()
        else:
            self.sgnError.emit()
Example #23
0
 def follow(self):
     global TRACES
     self.enable()
     lastLat, lastLon = None, None 
     if self.inMemory==False:
         if os.path.isfile(self.filename) == False:
             f = open(self.filename,'w')
             f.write("date,latitude,longitude\n")
             f.close()
     while self.stopFollow == False:
         lat, lon = self.getCurrentLocation()
         #print "follow current:{0},{1}".format(lat, lon)
         if (lat!=None and lon!=None) and (lastLat!=lat or lastLon!=lon):
             #print "follow modified:{0},{1}".format(lat, lon)
             if self.inMemory==False:
                 f = open(self.filename,'a+')
                 f.write("{0},{1},{2}\n".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), lat, lon))
                 f.close()
             else:
                 TRACES.append([datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), lat, lon])
         lastLat, lastLon = lat, lon
         sleep(self.period)
     self.disable()
     jnius.detach() #For fixing a BUG, see https://github.com/kivy/pyjnius/issues/107
Example #24
0
 def clean_up(self):
     jnius.detach()
Example #25
0
def safe_thread_exit():
    if platform == 'android':
        jnius.detach(
        )  # detach the current thread from pyjnius, else hard crash occurs
Example #26
0
def _detachThread():
    loadLibrary()
    import jnius
    jnius.detach()
Example #27
0
 def _one_row(*args, **kwargs):
     rtr = self._retrieve_one(*args, **kwargs)
     detach()
     return rtr
def safe_thread_exit():
    if platform == "android":
        jnius.detach()  # detach the current thread from pyjnius, else hard crash occurs
Example #29
0
 def on_stop(self):
     if 'ANDROID_DATA' in os.environ:
         import jnius
         jnius.detach()
         self.print_error("jnius detach")
     self.print_error("stopped")
Example #30
0
 def on_stop(self):
     if 'ANDROID_DATA' in os.environ:
         import jnius
         jnius.detach()
         self.logger.info("jnius detach")
     self.logger.info("stopped")
Example #31
0
def detach_thread():
    try:
        jnius.detach()
    except BaseException:
        pass
Example #32
0
 def on_stop(self):
     if 'ANDROID_DATA' in os.environ:
         import jnius
         jnius.detach()
         self.print_error("jnius detach")
     self.print_error("stopped")
Example #33
0
 def jnius_thread_hook(*args, **kwargs):
     try:
         return orig_thread_run(*args, **kwargs)
     finally:
         jnius.detach()
Example #34
0
 def jnius_thread_hook(*args, **kwargs):
     try:
         return orig_thread_run(*args, **kwargs)
     finally:
         jnius.detach()
Example #35
0
def FWICalculateDailyStatisticsCOM(
        longitude: float,  # pylint: disable=invalid-name, too-many-arguments
        latitude: float,
        yesterday_ffmc: float,
        yesterday_dmc: float,
        yesterday_dc: float,
        noon_temp: float,
        noon_rh: float,
        noon_precip: float,
        noon_wind_speed: float,
        calc_hourly: bool,
        hourly_temp: float,
        hourly_rh: float,
        hourly_precip: float,
        hourly_wind_speed: float,
        previous_hourly_ffmc: float,
        use_van_wagner: bool,
        use_lawson_previous_hour: bool,
        time_of_interest: datetime) -> FWICalculations:
    """ Take input parameters to calculate FWI and pass to REDapp java instance of class
    ca.cwfgm.fwi.FWICalculations. Then call FWICalculateDailyStatisticsCOM on instance, and
    copy results into response object.
    """
    # pylint: disable=too-many-locals
    # we have to do a late import, otherwise we get a segmentation fault.
    import jnius  # pylint: disable=import-outside-toplevel
    try:
        Calendar = jnius.autoclass('java.util.Calendar')  # pylint: disable=invalid-name
        TimeZone = jnius.autoclass('java.util.TimeZone')  # pylint: disable=invalid-name
        FWICalculationsClass = jnius.autoclass('ca.cwfgm.fwi.FWICalculations')  # pylint: disable=invalid-name

        fwi = FWICalculationsClass()
        fwi.setLatitude(latitude)
        fwi.setLongitude(longitude)
        fwi.ystrdyFFMC = yesterday_ffmc
        fwi.ystrdyDMC = yesterday_dmc
        fwi.ystrdyDC = yesterday_dc
        fwi.noonTemp = noon_temp
        fwi.noonRH = noon_rh
        fwi.noonPrecip = noon_precip
        fwi.noonWindSpeed = noon_wind_speed
        fwi.calcHourly = calc_hourly
        fwi.hrlyTemp = hourly_temp
        fwi.hrlyRH = hourly_rh
        fwi.hrlyPrecip = hourly_precip
        fwi.hrlyWindSpeed = hourly_wind_speed
        fwi.prvhlyFFMC = previous_hourly_ffmc
        fwi.useVanWagner = use_van_wagner
        fwi.useLawsonPreviousHour = use_lawson_previous_hour

        fwi.m_date = _python_date_to_java_calendar(time_of_interest, Calendar,
                                                   TimeZone)

        fwi.FWICalculateDailyStatisticsCOM()

        copy = FWICalculations()
        for key in dir(copy):
            if '__' not in key:
                if key == 'm_date':
                    copy.m_date = _java_calendar_to_python_date(
                        fwi.m_date, Calendar)
                else:
                    setattr(copy, key, getattr(fwi, key))

        return copy

    finally:
        # Each time you create a native thread in Python and use Pyjnius, any call to Pyjnius
        # methods will force attachment of the native thread to the current JVM. But you must
        # detach it before leaving the thread, and Pyjnius cannot do it for you.
        jnius.detach()  # pylint: disable=no-member
Example #36
0
 def thread_check_run(*args, **kwargs):
     try:
         return orig_thread_run(*args, **kwargs)
     finally:
         jnius.detach()
 def releaser_thread(player, duration):
     sleep(duration)
     mPlayer.release()
     detach()
Example #38
0
def FBPCalculateStatisticsCOM(elevation: float, latitude: float,
                              longitude: float, time_of_interest: datetime,
                              fuel_type: str, ffmc: float, dmc: float,
                              dc: float, bui: float, wind_speed: float,
                              wind_direction: float, percentage_conifer: float,
                              percentage_dead_balsam_fir: float,
                              grass_cure: float,
                              crown_base_height: float) -> FBPCalculations:
    """ Uses method FBPCalculateStatisticsCOM on class ca.cwfgm.fbp.FBPCalculations to calculate
    fire behaviour.

    public class FBPCalculations {

        # methods:
        public FBPCalculations() {
        initializeInputValues();
        initializeOutputValues();
        }
        public void FBPCalculateStatisticsCOM()
    }
    """
    # pylint: disable=too-many-locals
    # we have to do a late import, otherwise we get a segmentation fault.
    import jnius  # pylint: disable=import-outside-toplevel
    try:
        Calendar = jnius.autoclass('java.util.Calendar')  # pylint: disable=invalid-name
        TimeZone = jnius.autoclass('java.util.TimeZone')  # pylint: disable=invalid-name
        FBPCalculationsClass = jnius.autoclass('ca.cwfgm.fbp.FBPCalculations')  # pylint: disable=invalid-name

        if percentage_dead_balsam_fir is None:
            percentage_dead_balsam_fir = 0.0
        if grass_cure is None:
            grass_cure = 0.0
        if crown_base_height is None:
            use_crown_base_height = False
            crown_base_height = 0.0
        else:
            use_crown_base_height = True
        if percentage_conifer is None:
            percentage_conifer = 0.0

        fbp = FBPCalculationsClass()
        fbp.elevation = elevation
        fbp.latitude = latitude
        fbp.longitude = longitude
        fbp.ffmc = ffmc
        fbp.dmc = dmc
        fbp.dc = dc
        fbp.useBui = True
        fbp.useBuildup = True
        fbp.bui = bui
        fbp.windSpeed = wind_speed
        fbp.windDirection = wind_direction
        fbp.fuelType = _fbp_fuel_type_map(fuel_type)
        fbp.conifMixedWood = percentage_conifer
        fbp.deadBalsam = percentage_dead_balsam_fir
        fbp.grassCuring = grass_cure
        fbp.crownBase = crown_base_height

        fbp.useSlope = False
        fbp.useCrownBaseHeight = use_crown_base_height

        fbp.m_date = _python_date_to_java_calendar(time_of_interest, Calendar,
                                                   TimeZone)
        fbp.FBPCalculateStatisticsCOM()

        # we copy the java object into a python object, so that we can safely detach from the java VM
        # when we exit this function.
        copy = FBPCalculations()
        for key in dir(copy):
            if '__' not in key:
                if key == 'm_date':
                    copy.m_date = _java_calendar_to_python_date(
                        fbp.m_date, Calendar)
                else:
                    setattr(copy, key, getattr(fbp, key))

        return copy
    finally:
        # Each time you create a native thread in Python and use Pyjnius, any call to Pyjnius
        # methods will force attachment of the native thread to the current JVM. But you must
        # detach it before leaving the thread, and Pyjnius cannot do it for you.
        jnius.detach()  # pylint: disable=no-member
Example #39
0
 def dispose(self):
     """
     Executed whenever the plugin is going to be destroyed.
     """
     detach()