def http_get(self, url): '''Return java.lang.String JSON Input: java.lang.String URL ''' start_timer = System.currentTimeMillis() try: url = URL(url) urlconnect = url.openConnection() br = BufferedReader( InputStreamReader( urlconnect.getInputStream(), "UTF-8" ) ) s = br.readLine() br.close() except MalformedURLException() as ex: cumulus_logger.error(str(ex)) MessageBox.showError(str(ex), "Exception") raise except IOException as ex: cumulus_logger.error(str(ex)) MessageBox.showError(str(ex), "Exception") raise end_timer = System.currentTimeMillis() cumulus_logger.debug( "HTTP GET (milliseconds): {}".format( (end_timer - start_timer) ) ) return s
def processHttpMessage(self, toolFlag, messageIsRequest, requestResponse): if self.isRunning: if self.toolFilter == 0 or self.toolFilter == toolFlag: messageInfo = self._helpers.analyzeRequest(requestResponse) url = messageInfo.getUrl() requestBody = requestResponse.getRequest( )[messageInfo.getBodyOffset():].tostring() if not is_query(requestBody): return # exit early qobj = json.loads(requestBody) queryBody = "" operationName = "" if 'query' in qobj: queryBody = qobj['query'] if 'operationName' in qobj: operationName = qobj['operationName'] if messageIsRequest: self.reqResMap.put(url, System.currentTimeMillis()) elif self.reqResMap.containsKey(url): time = System.currentTimeMillis() - self.reqResMap.get(url) self.reqResMap.remove(url) # create a new log entry with the message details synchronize.apply_synchronized( self.panel.getLogTableModel().getLogArray(), self.syncProcessHttpMessage, (toolFlag, requestResponse, time, queryBody, operationName))
def canMeJoin(self, player, clanid, pledgeType): clan = ClanTable.getInstance().getClan(clanid) if not clan: return False if clan.getCharPenaltyExpiryTime() > System.currentTimeMillis(): player.sendPacket(SystemMessageId.YOU_MUST_WAIT_BEFORE_ACCEPTING_A_NEW_MEMBER) return False if player.getClanId() != 0: sm = SystemMessage.getSystemMessage(SystemMessageId.S1_WORKING_WITH_ANOTHER_CLAN) sm.addString(player.getName()) player.sendPacket(sm) return False if player.getClanJoinExpiryTime() > System.currentTimeMillis(): sm = SystemMessage.getSystemMessage(SystemMessageId.C1_MUST_WAIT_BEFORE_JOINING_ANOTHER_CLAN) sm.addString(player.getName()) player.sendPacket(sm) return False if player.getLevel() > 40 or player.getClassId().level() >= 2: if pledgeType == -1: sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DOESNOT_MEET_REQUIREMENTS_TO_JOIN_ACADEMY) sm.addString(player.getName()) player.sendPacket(sm) player.sendPacket(SystemMessageId.ACADEMY_REQUIREMENTS) return False if clan.getSubPledgeMembersCount(pledgeType) >= clan.getMaxNrOfMembers(pledgeType): if pledgeType == 0: sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CLAN_IS_FULL) sm.addString(clan.getName()) player.sendPacket(sm) else: player.sendPacket(SystemMessageId.SUBCLAN_IS_FULL) return False return True
def ig_ref_search_2file(filename, line, col, toplevelpath, destinationfile): sf = SourceFile(File(filename)) tlp = ToplevelPath(toplevelpath) location = SourceLocation(sf, line, col) start = System.currentTimeMillis() res = SourceLocation2IG.findNearestItem(location, tlp, project) if res == None: printf('No IG item found at %s:%s,%s', filename, line, col) return item = res.getFirst() if item == None: printf('Failed to find nearest IG Item') return path = res.getSecond() rs = IGReferencesSearch(project) if isinstance(item, IGOperationObject): item = item.getObject() result = rs.search(item, path, True, True, False, False) time = System.currentTimeMillis() - start out = PrintStream(File(destinationfile)) printf('Found %s references of %s in %s ms.', result.countRefs(), item, time) out.printf('Found %s references of %s in %s ms:\n', result.countRefs(), item, time) result.dump(0, out)
def __init__(self, id, name, descr): JQuest.__init__(self, id, name, descr) castleOwner = CastleManager.getInstance().getCastleById(8).getOwnerId() siegeDate = CastleManager.getInstance().getCastleById( 8).getSiegeDate().getTimeInMillis() benomTeleporterSpawn = (siegeDate - System.currentTimeMillis()) - 86400000 benomRaidRoomSpawn = (siegeDate - System.currentTimeMillis()) - 86400000 benomRaidSiegeSpawn = (siegeDate - System.currentTimeMillis()) if benomTeleporterSpawn < 0: benomTeleporterSpawn = 1 if benomRaidSiegeSpawn < 0: benomRaidSiegeSpawn = 1 self.BenomWalkRouteStep = 0 self.BenomIsSpawned = 0 if castleOwner > 0: if benomTeleporterSpawn >= 1: self.startQuestTimer("BenomTeleSpawn", benomTeleporterSpawn, None, None) if (siegeDate - System.currentTimeMillis()) > 0: self.startQuestTimer("BenomRaidRoomSpawn", benomRaidRoomSpawn, None, None) self.startQuestTimer("BenomRaidSiegeSpawn", benomRaidSiegeSpawn, None, None) self.Benom = Benom
def __init__(self, pos, speed, direction): AIBase.__init__(self, "thrownshit") self.pos = pos self.speed = speed self.direction = direction self.a = System.currentTimeMillis() self.b = System.currentTimeMillis()
def merge_dss(src_dss, dest_dss): ''' Return list containing FQPN of DSS files Input: java.nio.file.Path src_path java.lang.String dest_path Merge all grid paths in the source dss file into the destination dss file ''' start_timer = System.currentTimeMillis() dss7 = HecDSSUtilities() dss6 = HecDSSUtilities() merged_paths = list() # Process the DSS file if Files.exists(src_dss): # try: dss6path = src_dss.toString().replace("dss7", "dss6") dss7.setDSSFileName(src_dss.toString()) dss7.convertVersion(dss6path) dss6.setDSSFileName(dss6path) dss6.copyFile(dest_dss) dss7.copyFile(dest_dss) dss7.close() dss6.close() if dest_dss not in merged_paths: merged_paths.append(dest_dss) end_timer = System.currentTimeMillis() cumulus_logger.debug( "Merging DSS records (milliseconds): {}".format( (end_timer - start_timer) ) ) return merged_paths
def backupSWUtilizationConfig(Framework): # keep remote ini files BASEDIR = AgentPlatformParameters.getAgentConfigurationPath(Framework) localDiscusgeFile = File.createTempFile( "discusge" + str(System.currentTimeMillis()) + Framework.getTriggerCIData('id'), ".ini") remoteDiscusgeFile = BASEDIR + "discusge.ini" if InventoryUtils.copyRemoteFileToLocal( Framework, remoteDiscusgeFile, localDiscusgeFile.getCanonicalPath(), 0, 1): Framework.setProperty("local_discusge_temp_file", localDiscusgeFile.getCanonicalPath()) else: Framework.reportWarning( "backup discusge.ini file in remote server failed, upgrade agent will use default configuration." ) localPluginFile = File.createTempFile( "plugin" + str(System.currentTimeMillis()) + Framework.getTriggerCIData('id'), ".ini") remotePluginFile = BASEDIR + "plugin.ini" if InventoryUtils.copyRemoteFileToLocal(Framework, remotePluginFile, localPluginFile.getCanonicalPath(), 0, 1): Framework.setProperty("local_plugin_temp_file", localPluginFile.getCanonicalPath()) else: Framework.reportWarning( "backup discusge.ini file in remote server failed, upgrade agent will use default configuration." ) Framework.setStepExecutionStatus(WorkflowStepStatus.SUCCESS)
def mp2scf(molecule, basisSet): from java.text import DecimalFormat from java.lang import System from org.meta.math.qm import * print("Starting computation for " + repr(molecule) + " at " + repr(basisSet) + " basis") t1 = System.currentTimeMillis() bfs = BasisFunctions(molecule, basisSet) t2 = System.currentTimeMillis() print("Number of basis functions : " + repr(bfs.getBasisFunctions().size())) print("Time till setting up basis : " + repr(t2-t1) + " ms") oneEI = OneElectronIntegrals(bfs, molecule) t2 = System.currentTimeMillis() print("Time till 1EI evaluation : " + repr(t2-t1) + " ms") twoEI = TwoElectronIntegrals(bfs) t2 = System.currentTimeMillis() print("Time till 2EI evaluation : " + repr(t2-t1) + " ms") scfm = SCFMethodFactory.getInstance().getSCFMethod(molecule, oneEI, twoEI, SCFType.MOLLER_PLESSET) scfm.scf() print("Final Energy : " + repr(scfm.getEnergy())) return scfm.getEnergy()
def onAdvEvent (self,event,npc,player): objId=0 if event == "baium_unlock" : self.isBaiumLocked = False self.deleteGlobalQuestVar("unlockDatetime") self.addSpawn(STONE_BAIUM,115213,16623,10080,41740,False,0) elif event == "baium_wakeup" and npc: if npc.getNpcId() == LIVE_BAIUM : npc.broadcastPacket(SocialAction(npc.getObjectId(),1)) npc.broadcastPacket(Earthquake(npc.getX(), npc.getY(), npc.getZ(),40,5)) # once Baium is awaken, no more people may enter until he dies, the server reboots, or # 30 pass with no attacks made against Baium. self.isBaiumLocked = True # start monitoring baium's inactivity self.lastAttackVsBaiumTime = System.currentTimeMillis() self.startQuestTimer("baium_despawn", 60000, npc, None) # TODO: the person who woke baium up should be knocked across the room, onto a wall, and # lose massive amounts of HP. # despawn the live baium after 30 minutes of inactivity elif event == "baium_despawn" and npc: if (npc.getNpcId() == LIVE_BAIUM) and (self.lastAttackVsBaiumTime + 1800000 < System.currentTimeMillis()) : npc.deleteMe() # despawn the live-baium self.addSpawn(STONE_BAIUM,115213,16623,10080,41740,False,0) # spawn stone-baium self.deleteGlobalQuestVar("unlockDatetime") # make sure that all locks are deleted from the DB self.isBaiumAwake = False # mark that Baium is not awake any more self.isBaiumLocked = False # unlock the entrance self.playersInside = [] else : # if baium's inactivity is still younger than 30 minutes, just re-add the timer self.startQuestTimer("baium_despawn", 60000, npc, None) return
def rightGB(self): '''Compute a right Groebner base. ''' t = System.currentTimeMillis(); G = ModSolvableGroebnerBaseAbstract().rightGB(self.mset); t = System.currentTimeMillis() - t; print "executed module rightGB in %s ms" % t; return SolvableSubModule(self.module,"",G.list);
def first_click_item_11996(player): uses_left = player.toolUses if (System.currentTimeMillis() - player.buryDelay > 1200): player.buryDelay = System.currentTimeMillis(); if uses_left <= 0: player.getPA().sendMessage("<col=bc0000>You don't have any charges remaining. Ask Michael and you might get some more...") else: HandleHolidayTool(player)
def isRightGB(self): '''Test if this is a right Groebner base. ''' t = System.currentTimeMillis(); b = ModSolvableGroebnerBaseAbstract().isRightGB(self.mset); t = System.currentTimeMillis() - t; print "module isRightGB executed in %s ms" % t; return b;
def retrieveScannerStatus(Framework, success=1): client = Framework.getConnectedClient() options = LockUtils.getClientOptionsMap(client) completionCode = options.get( InventoryUtils.AGENT_OPTION_DISCOVERY_SCAN_EXITCODE) status = options.get(InventoryUtils.AGENT_OPTION_DISCOVERY_SCAN_STATUS) # just put the information into Framework to avoid duplicate log Framework.setProperty( "scanner_state_process_id", options.get(InventoryUtils.AGENT_OPTION_DISCOVERY_SCAN_PID)) Framework.setProperty( "scanner_status_exit_code", options.get(InventoryUtils.AGENT_OPTION_DISCOVERY_SCAN_EXITCODE)) Framework.setProperty( "scanner_status_scanner_stage", options.get(InventoryUtils.AGENT_OPTION_DISCOVERY_SCAN_STAGE)) Framework.setProperty("scanner_status_retrieve_status", str(success)) Framework.setProperty("scanner_status_retrieve_date", Date()) # record Scanner status here recordScannerStatus(Framework, success) completion = "" if (completionCode is not None) and len(completionCode): completion = InventoryUtils.SCANNER_EXIT_CODE_MAPPING.get( str(completionCode)) if (str(completionCode) != '0' and str(completionCode) != '11' and str(completionCode) != '10' and str(completionCode) != '7'): # If the scanner exits with fatal failure, download the scanner log file before the entire workflow exits DownloadScanFile.downloadScanLogFile(Framework) Framework.setStepExecutionStatus(WorkflowStepStatus.FATAL_FAILURE) Framework.reportError( inventoryerrorcodes.INVENTORY_DISCOVERY_SCANNER_STATUS_FAILED, [completion, status]) return 0 elif str(completionCode) != '0': Framework.reportWarning(completion) else: pid = options.get(InventoryUtils.AGENT_OPTION_DISCOVERY_SCAN_PID) if not pid: startTime = Framework.getProperty( "START_TIME_OF_SCANNER_STATUS_CHECKING") if not startTime: Framework.setProperty("START_TIME_OF_SCANNER_STATUS_CHECKING", System.currentTimeMillis()) else: startTime = long(startTime) now = System.currentTimeMillis() if (now - startTime) > maxWaitingTimeForScannerStartUp: Framework.setStepExecutionStatus( WorkflowStepStatus.FATAL_FAILURE) Framework.reportError( "Scanner can't be executed. Check if the scanner can run on the target host." ) return 0 return 1
def rightGB(self): '''Compute a right Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); G = SolvableGroebnerBaseSeq().rightGB(F); t = System.currentTimeMillis() - t; print "executed rightGB in %s ms" % t; return SolvableIdeal(self.ring,"",G);
def regularGB(self): '''Compute a Groebner base over a regular ring. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); G = RGroebnerBasePseudoSeq(self.ring.ring.coFac).GB(F); t = System.currentTimeMillis() - t; print "sequential regular GB executed in %s ms" % t; return ParamIdeal(self.ring,None,G);
def isRegularGB(self): '''Test if this is Groebner base over a regular ring. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); b = RGroebnerBasePseudoSeq(self.ring.ring.coFac).isGB(F); t = System.currentTimeMillis() - t; print "isRegularGB executed in %s ms" % t; return b;
def isCGB(self): '''Test if this is a comprehensive Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); b = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).isGB(F); t = System.currentTimeMillis() - t; print "isCGB executed in %s ms" % t; return b;
def isCGBsystem(self): '''Test if this is a comprehensive Groebner system. ''' s = self.pset; S = self.gbsys; t = System.currentTimeMillis(); b = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).isGBsys(S); t = System.currentTimeMillis() - t; print "isCGBsystem executed in %s ms" % t; return b;
def __init__(self, pos): AIBase.__init__(self, "happysheep") self.pos = pos self.dest = pos self.direction = Point(0, 0) self.lt = System.currentTimeMillis() self.ct = System.currentTimeMillis() self.speed = 1 self.positions = [] self.directions = []
def CGBsystem(self): '''Compute a comprehensive Groebner system. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); S = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).GBsys(F); t = System.currentTimeMillis() - t; print "sequential comprehensive system executed in %s ms" % t; return ParamIdeal(self.ring,None,F,S);
def dump(query): print "JDO->", query start = System.currentTimeMillis(); sqlquery = sqlbuilder.makeQuery(query) generic_stm = GenericSQLGenerator().createSQLStatement(sqlquery) print "Time:", (System.currentTimeMillis() - start) oracle_stm = OracleSQLGenerator().createSQLStatement(sqlquery) print "SQL1->", sqlquery print "SQL2->", generic_stm.getSQL() print
def isRightGB(self): '''Test if this is a right Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); b = SolvableGroebnerBaseSeq().isRightGB(F); t = System.currentTimeMillis() - t; print "isRightGB executed in %s ms" % t; return b;
def ig_ref_search(filename, line, col, toplevelpath): sf = SourceFile(File(filename)) location = SourceLocation(sf, line, col) start = System.currentTimeMillis() if not toplevelpath: nearest = SourceLocation2AST.findNearestASTNode( location, True, project) if not nearest: printf('No AST item found at %s:%s,%s', filename, line, col) return declaration = ASTDeclarationSearch.search(nearest, project) if not declaration: printf('Failed to find declaration of %s', nearest) return result = ASTReferencesSearch.search(declaration, True, True, project) item = nearest else: tlp = ToplevelPath(toplevelpath) res = SourceLocation2IG.findNearestItem(location, tlp, project) if not res: printf('No IG item found at %s:%s,%s', filename, line, col) return item = res.getFirst() if not item: printf('No IG item found at %s:%s,%s', filename, line, col) return path = res.getSecond() rs = IGReferencesSearch(project) if isinstance(item, IGOperationObject): item = item.getObject() result = rs.search(item, path, True, True, False, False) time = System.currentTimeMillis() - start if not result or result.countRefs() == 0: print('Search returned no result.') else: printf('Found %s references of %s in %s ms:', result.countRefs(), item, time) result.dump(0, sys.stdout)
def runScanner(Framework): client = Framework.getConnectedClient() scannersConfigFile = Framework.getConfigFile( CollectorsConstants.SCANNERSBYPLATFORM_FILE_NAME) platform = Framework.getProperty(InventoryUtils.STATE_PROPERTY_PLATFORM) architecture = Framework.getProperty( InventoryUtils.STATE_PROPERTY_ARCHITECTURE) logger.debug('Platform:', platform, ' architecture ', architecture) scannerPlatformConfig = scannersConfigFile.getPlatformConfiguration( platform, architecture) BASEDIR = Framework.getProperty( InventoryUtils.STATE_PROPERTY_RESOLVED_BASEDIR) lockValue = Framework.getProperty(LockUtils.ScannerNodeLock) client_options = LockUtils.getClientOptionsMap(client) logger.debug('Settings agent options') options = HashMap() options.put(InventoryUtils.AGENT_OPTION_DISCOVERY_SCANFILENAME, '') options.put(LockUtils.ScannerNodeLock, lockValue) options.put(InventoryUtils.STATE_PROPERTY_EXECUTION_STARTED, str(System.currentTimeMillis())) logger.debug('Agent option ', InventoryUtils.AGENT_OPTION_DISCOVERY_SCANFILENAME, ':', '') logger.debug('Agent option ', LockUtils.ScannerNodeLock, ':', lockValue) logger.debug('Agent option ', InventoryUtils.STATE_PROPERTY_EXECUTION_STARTED, ':', str(System.currentTimeMillis())) filterOptionsByBlackList( client_options) #filter the options of client by black list client_options.putAll(options) client.setOptionsMap(client_options, 1) shell = shellutils.ShellUtils(client, skip_set_session_locale=True) shell.execCmd('cd ' + BASEDIR) runScannerCommand = scannerPlatformConfig.getRunScannerCommand() logger.debug('Launching scanner on remote machine') commandLine = runScannerCommand.getCommand() commandLine = updateCmdWithLogLevel(commandLine, Framework) commandLine = updateCmdForDeltaScanning(commandLine, Framework) commandLine = InventoryUtils.handleBaseDirPath(Framework, commandLine) commandLine = updateWithPrePostScriptCmd(Framework, commandLine) logger.debug('Scanner execution command:', commandLine) shell.execCmd(commandLine) logger.debug('Scanner Launched on remote machine') Framework.setStepExecutionStatus(WorkflowStepStatus.SUCCESS)
def __init__(self, pos, poses): AIBase.__init__(self, "evilsheep") self.pos = pos self.dest = pos self.direction = Point(0, 0) self.lt = System.currentTimeMillis() self.ct = System.currentTimeMillis() self.speed = 1 self.positions = poses self.cdest = 0 self.lastHit = System.currentTimeMillis()
def NF(self,reducer): '''Compute a normal form of this ideal with respect to reducer. ''' s = self.pset; F = s.list; G = reducer.list; t = System.currentTimeMillis(); N = ReductionSeq().normalform(G,F); t = System.currentTimeMillis() - t; print "sequential NF executed in %s ms" % t; return Ideal(self.ring,"",N);
def ig_ref_search(filename, line, col, toplevelpath): sf = SourceFile(File(filename)) location = SourceLocation(sf, line, col) start = System.currentTimeMillis() if not toplevelpath: nearest = SourceLocation2AST.findNearestASTNode(location, True, project) if not nearest: printf('No AST item found at %s:%s,%s', filename, line, col) return declaration = ASTDeclarationSearch.search(nearest, project) if not declaration: printf('Failed to find declaration of %s', nearest) return result = ASTReferencesSearch.search(declaration, True, True, project) item = nearest else: tlp = ToplevelPath(toplevelpath) res = SourceLocation2IG.findNearestItem(location, tlp, project) if not res: printf('No IG item found at %s:%s,%s', filename, line, col) return item = res.getFirst() if not item: printf('No IG item found at %s:%s,%s', filename, line, col) return path = res.getSecond() rs = IGReferencesSearch(project) if isinstance(item, IGOperationObject): item = item.getObject() result = rs.search(item, path, True, True, False, False) time = System.currentTimeMillis() - start if not result or result.countRefs() == 0: print('Search returned no result.') else: printf('Found %s references of %s in %s ms:', result.countRefs(), item, time) result.dump(0, sys.stdout)
def parTwosidedGB(self,th): '''Compute a two-sided Groebner base in parallel. ''' s = self.pset; F = s.list; bbpar = SolvableGroebnerBaseParallel(th); t = System.currentTimeMillis(); G = bbpar.twosidedGB(F); t = System.currentTimeMillis() - t; bbpar.terminate(); print "parallel %s twosidedGB executed in %s ms" % (th, t); return Ideal(self.ring,"",G);
def CGB(self): '''Compute a comprehensive Groebner base. ''' s = self.pset; F = s.list; t = System.currentTimeMillis(); if self.gbsys == None: self.gbsys = ComprehensiveGroebnerBaseSeq(self.ring.ring.coFac).GBsys(F); G = self.gbsys.getCGB(); t = System.currentTimeMillis() - t; print "sequential comprehensive executed in %s ms" % t; return ParamIdeal(self.ring,"",G,self.gbsys);
def parOldGB(self,th): '''Compute in parallel a Groebner base. ''' s = self.pset; F = s.list; bbpar = GroebnerBaseParallel(th); t = System.currentTimeMillis(); G = bbpar.GB(F); t = System.currentTimeMillis() - t; bbpar.terminate(); print "parallel-old %s executed in %s ms" % (th, t); return Ideal(self.ring,"",G);
def squarefreeFactors(self): '''Compute squarefree factors of first polynomial. ''' s = self.pset; F = s.list; p = F[0]; # only first polynomial t = System.currentTimeMillis(); f = GreatestCommonDivisorSubres().squarefreeFactors(p); t = System.currentTimeMillis() - t; #print "squarefee part %s " % f; #S = ArrayList(); #S.add(f); print "squarefee factors executed in %s ms" % t; return f;
def mmEnergy(molecule): from org.meta.math.mm import * from java.lang import System print("Starting MM Energy for " + repr(molecule)) mm = MMEnergyMethodFactory.getInstance().getMMEnergyMethod(molecule) t1 = System.currentTimeMillis() energy = mm.getEnergy() t2 = System.currentTimeMillis() print("Energy = " + repr(energy) + " a.u.") print("Total Time : " + repr(t2-t1) + " ms") return energy
def test_init_method_with_classifier(self, get_examples, get_classifier_with_init_method, test_examples, nr_of_examples_to_test_list, only_count_based_init=False): print("number of training examples", "random init score before training", "count based init score before training", "random init score after training", "count based init score after training", "random init training time", "count based init training time") for nr_of_training_examples in nr_of_examples_to_test_list: training_exampels = get_examples(nr_of_training_examples) if not only_count_based_init: random_init_classifer = get_classifier_with_init_method(training_exampels, SpecializedHMM.InitMethod.random) count_based_init_classifer = get_classifier_with_init_method(training_exampels, SpecializedHMM.InitMethod.count_based) #Before training if not only_count_based_init: random_score_before_training = random_init_classifer.test(test_examples) else: random_score_before_training = None count_score_before_training = count_based_init_classifer.test(test_examples) #Train start_time = System.currentTimeMillis() if not only_count_based_init: random_init_classifer.train(training_exampels) random_init_training_time = System.currentTimeMillis() - start_time start_time = System.currentTimeMillis() count_based_init_classifer.train(training_exampels) count_based_init_training_time = System.currentTimeMillis() - start_time #After training if not only_count_based_init: random_score_after_training = random_init_classifer.test(test_examples) else: random_score_after_training = None count_score_after_training = count_based_init_classifer.test(test_examples) print(nr_of_training_examples, random_score_before_training, count_score_before_training, random_score_after_training, count_score_after_training, random_init_training_time, count_based_init_training_time)
def onKill(self,npc,player,isPet): npcId = npc.getNpcId() if npcId == BUMPALUMP : respawnMinDelay = 43200000 * int(Config.RAID_MIN_RESPAWN_MULTIPLIER) respawnMaxDelay = 129600000 * int(Config.RAID_MAX_RESPAWN_MULTIPLIER) respawn_delay = Rnd.get(respawnMinDelay,respawnMaxDelay) self.saveGlobalQuestVar("625_respawn", str(System.currentTimeMillis()+respawn_delay)) self.startQuestTimer("spawn_npc", respawn_delay, None, None) self.cancelQuestTimer("Icicle Emperor Bumbalump has despawned",npc,None) party = player.getParty() if party : PartyQuestMembers = [] for player1 in party.getPartyMembers().toArray() : st1 = player1.getQuestState(qn) if st1 : if st1.getState() == State.STARTED and (st1.getInt("cond") == 1 or st1.getInt("cond") == 2) : PartyQuestMembers.append(st1) if len(PartyQuestMembers) == 0 : return st = PartyQuestMembers[Rnd.get(len(PartyQuestMembers))] if st.getQuestItemsCount(FOOD) > 0 : st.takeItems(FOOD,1) st.giveItems(MEAT,1) st.set("cond","3") st.playSound("ItemSound.quest_middle") else : st = player.getQuestState(qn) if not st : return if st.getState() == State.STARTED and (st.getInt("cond") == 1 or st.getInt("cond") == 2) : if st.getQuestItemsCount(FOOD) > 0 : st.takeItems(FOOD,1) st.giveItems(MEAT,1) st.set("cond","3") st.playSound("ItemSound.quest_middle") return
def onKill(self,npc,player,isPet): npcId = npc.getNpcId() if npcId == DAIMON : respawnMinDelay = 43200000 * int(Config.RAID_MIN_RESPAWN_MULTIPLIER) respawnMaxDelay = 129600000 * int(Config.RAID_MAX_RESPAWN_MULTIPLIER) respawn_delay = Rnd.get(respawnMinDelay,respawnMaxDelay) self.saveGlobalQuestVar("604_respawn", str(System.currentTimeMillis()+respawn_delay)) self.startQuestTimer("spawn_npc", respawn_delay, None, None) self.cancelQuestTimer("Daimon the White-Eyed has despawned",npc,None) party = player.getParty() if party : PartyQuestMembers = [] for player1 in party.getPartyMembers().toArray() : st1 = player1.getQuestState(qn) if st1 and Util.checkIfInRange(Config.ALT_PARTY_RANGE, player, player1, True) : if st1.getState() == STARTED and (st1.getInt("cond") == 1 or st1.getInt("cond") == 2) : PartyQuestMembers.append(st1) if len(PartyQuestMembers) == 0 : return st = PartyQuestMembers[Rnd.get(len(PartyQuestMembers))] if st.getQuestItemsCount(S_SUMMON) > 0 : st.takeItems(S_SUMMON,1) st.giveItems(ESSENCE,1) st.set("cond","3") st.playSound("ItemSound.quest_middle") else : st = player.getQuestState(qn) if not st : return if st.getState() == STARTED and (st.getInt("cond") == 1 or st.getInt("cond") == 2) : if st.getQuestItemsCount(S_SUMMON) > 0 : st.takeItems(S_SUMMON,1) st.giveItems(ESSENCE,1) st.set("cond","3") st.playSound("ItemSound.quest_middle") return
def __init__(self, entity, attribute, valueBytes, valueType=None, userReference=None, timestamp=None, sequence=None, operation=None): self.entity = entity self.attribute = attribute self.valueBytes = valueBytes # content type, typically "mime:text/plain" or "pointrel:text/utf-8" [the second is the default if not specified] if valueType == None: self.valueType = DefaultValueType else: self.valueType = valueType self.position = -1 if userReference == None: userReference = "anonymous" if timestamp == None: timestamp = Timestamp(System.currentTimeMillis()) self.userReference = userReference # Java timestamp reference: a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. self.timestamp = timestamp if sequence == None: self.sequence = "0" else: self.sequence = sequence self.previous = None self.deleted = False self.previousWithSameEntity = None if operation == None: # only option allowed currently operation = '+' self.operation = operation self.identifierString = self.makeIdentifierString()
def setValues(self, statement): statement.setLong(1, System.currentTimeMillis()) statement.setString(2, self.srcAddr) statement.setString(3, self.dstAddr) statement.setInt(4, self.srcPort) statement.setInt(5, self.dstPort) statement.setString(6, self.hostid)
def addFollower(self, username, follower): """addFollower username follower""" following_fn = "following:" + follower with Transaction() as fs: yield fs.begin() content = (yield fs.read(following_fn)) if content is None: yield Op.FollowerChangeResult.FAILURE content = Utility.byteArrayToString(content) for line in lines(content): followed_user, timestamp = line.split("\t") if followed_user == username: yield Op.FollowerChangeResult.ALREADY_EXISTS line = "%s\t%d\n" % (username, System.currentTimeMillis()) if not (yield fs.append(following_fn, Utility.stringToByteArray(line))): yield Op.FollowerChangeResult.FAILURE if not (yield fs.commit()): yield Op.FollowerChangeResult.FAILURE yield Op.FollowerChangeResult.SUCCESS
def checkCondition(player,KamaInfo): currentTime = System.currentTimeMillis()/1000 party = player.getParty() if not party: player.sendPacket(SystemMessage(SystemMessageId.NOT_IN_PARTY_CANT_ENTER)) return False # Check size of the party, max 6 for entering Kamaloka Hall of Abyss, 9 for Labyrinth if party and party.getMemberCount() > KamaInfo[5]: player.sendPacket(SystemMessage(SystemMessageId.PARTY_EXCEEDED_THE_LIMIT_CANT_ENTER)) return False for partyMember in party.getPartyMembers().toArray(): if partyMember.getLevel() < KamaInfo[3] or partyMember.getLevel() > KamaInfo[4]: sm = SystemMessage(SystemMessageId.C1_LEVEL_REQUIREMENT_NOT_SUFFICIENT) sm.addPcName(partyMember) player.sendPacket(sm) partyMember.sendPacket(sm) return False st = partyMember.getQuestState(qn) if st: LastEntry = st.getInt("LastEntry") if currentTime < LastEntry + KamaInfo[1]: sm = SystemMessage(SystemMessageId.NO_RE_ENTER_TIME_FOR_C1) sm.addPcName(partyMember) player.sendPacket(sm) partyMember.sendPacket(sm) return False return True