当前位置: 首页>>代码示例>>Scala>>正文


Scala Logger类代码示例

本文整理汇总了Scala中com.typesafe.scalalogging.Logger的典型用法代码示例。如果您正苦于以下问题:Scala Logger类的具体用法?Scala Logger怎么用?Scala Logger使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Logger类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: Population

//设置package包名称以及导入依赖的类
package it.codingjam.lagioconda.population

import com.typesafe.scalalogging.{LazyLogging, Logger}

import scala.util.Random

case class Population(generation: Int, individuals: List[Individual], hillClimbedGene: Int, lastResults: List[Double])
    extends LazyLogging {

  override lazy val logger = Logger(classOf[Population])

  def bestIndividual: Individual = individuals.head

  def randomIndividual: Individual = individuals(Random.nextInt(individuals.size))

  def randomNotElite: Individual = individuals(Population.EliteCount + Random.nextInt(Population.Size - Population.EliteCount))

  def randomElite: Individual = individuals(Random.nextInt(Population.EliteCount))

  def randomPositionAndIndividual: (Int, Individual) = {
    val pos = Random.nextInt(individuals.size)
    (pos, individuals(pos))
  }

  def randomIndividualInRange(position: Int) = {

    def normalizedPosition(i: Int) = {
      if (i < 0) 0
      else if (i > individuals.size - 1) individuals.size - 1
      else i
    }

    val range = 12
    val pos = position - (range / 2) + Random.nextInt(range)
    individuals(normalizedPosition(pos))
  }

  def randomIndividualByWeight: Individual = {
    val total = (individuals.size * (individuals.size + 1)) / 2
    var r = Random.nextInt(total)
    var x = individuals.size
    while (r > 0) {
      r = r - x
      x = x - 1
    }
    val position = individuals.size - x - 1
    individuals(if (position >= 0) position else 0)
  }

}

object Population {

  val Size = 16
  val EliteCount = 4
  val MaxRotate = 500

} 
开发者ID:coding-jam,项目名称:lagioconda,代码行数:59,代码来源:Population.scala

示例2: Utils

//设置package包名称以及导入依赖的类
package com.hxm.earlgrey.jobs

import com.typesafe.scalalogging.Logger



private[earlgrey] object Utils{
  val logger= Logger("Utils")

  def tryWithSafeFinally[T](block: => T)(finallyBlock: => Unit): T = {
    var originalThrowable: Throwable = null
    try {
      block
    } catch {
      case t: Throwable =>
        // Purposefully not using NonFatal, because even fatal exceptions
        // we don't want to have our finallyBlock suppress
        originalThrowable = t
        throw originalThrowable
    } finally {
      try {
        finallyBlock
      } catch {
        case t: Throwable =>
          if (originalThrowable != null) {
            originalThrowable.addSuppressed(t)
            logger.warn(s"Suppressing exception in finally: " + t.getMessage, t)
            throw originalThrowable
          } else {
            throw t
          }
      }
    }
  }

} 
开发者ID:PatrickHuang888,项目名称:Earlgrey,代码行数:37,代码来源:Utils.scala

示例3: ManchesterSyntaxOWLAxiomsDataSetBuilder

//设置package包名称以及导入依赖的类
package net.sansa_stack.owl.flink.dataset

import com.typesafe.scalalogging.Logger
import net.sansa_stack.owl.common.parsing.ManchesterSyntaxParsing
import org.apache.flink.api.scala.ExecutionEnvironment
import org.semanticweb.owlapi.io.OWLParserException
import org.semanticweb.owlapi.model.{OWLAxiom, OWLRuntimeException}


object ManchesterSyntaxOWLAxiomsDataSetBuilder extends ManchesterSyntaxParsing {
  private val logger = Logger(this.getClass)

  def build(env: ExecutionEnvironment, filePath: String): OWLAxiomsDataSet = {
    val res =
      ManchesterSyntaxOWLExpressionsDataSetBuilder.buildAndGetPrefixes(env, filePath)

    val expressionsDataSet = res._1
    val prefixes = res._2

    val defaultPrefix = prefixes.getOrElse(ManchesterSyntaxParsing._empty,
      ManchesterSyntaxParsing.dummyURI)

    import org.apache.flink.api.scala._
    expressionsDataSet.filter(!_.startsWith("Annotations")).flatMap(frame => {
      try makeAxioms(frame, defaultPrefix)
      catch {
        case exception: OWLParserException => {
          val msg = exception.getMessage
          logger.warn("Parser error for frame\n" + frame + "\n\n" + msg)
          //          exception.printStackTrace()
          Set.empty[OWLAxiom]
        }
        case exception: OWLRuntimeException => {
          val msg = exception.getMessage
          logger.warn("Parser error for frame\n" + frame + "\n\n" + msg)
          exception.printStackTrace()
          Set.empty[OWLAxiom]
        }
      }
    }).filter(_ != null)
  }
} 
开发者ID:SANSA-Stack,项目名称:SANSA-OWL,代码行数:43,代码来源:ManchesterSyntaxOWLAxiomsDataSetBuilder.scala

示例4: ManchesterSyntaxOWLAxiomsRDDBuilder

//设置package包名称以及导入依赖的类
package net.sansa_stack.owl.spark.rdd

import com.typesafe.scalalogging.Logger
import net.sansa_stack.owl.common.parsing.ManchesterSyntaxParsing
import org.apache.spark.SparkContext
import org.semanticweb.owlapi.io.OWLParserException
import org.semanticweb.owlapi.model.{OWLAxiom, OWLRuntimeException}


object ManchesterSyntaxOWLAxiomsRDDBuilder extends ManchesterSyntaxParsing {
  private val logger = Logger(this.getClass)

  def build(sc: SparkContext, filePath: String): OWLAxiomsRDD = {
    val res = ManchesterSyntaxOWLExpressionsRDDBuilder.buildAndGetPrefixes(sc, filePath)

    val expressionsRDD: OWLExpressionsRDD = res._1
    val prefixes: Map[String, String] = res._2

    val defaultPrefix = prefixes.getOrElse(ManchesterSyntaxParsing._empty,
      ManchesterSyntaxParsing.dummyURI)

    expressionsRDD.filter(!_.startsWith("Annotations")).flatMap(frame => {
      try makeAxioms(frame, defaultPrefix)
      catch {
        case exception: OWLParserException => {
          val msg = exception.getMessage
          logger.warn("Parser error for frame\n" + frame + "\n\n" + msg)
//          exception.printStackTrace()
          Set.empty[OWLAxiom]
        }
        case exception: OWLRuntimeException => {
          val msg = exception.getMessage
          logger.warn("Parser error for frame\n" + frame + "\n\n" + msg)
          exception.printStackTrace()
          Set.empty[OWLAxiom]
        }
      }
    })
  }
} 
开发者ID:SANSA-Stack,项目名称:SANSA-OWL,代码行数:41,代码来源:ManchesterSyntaxOWLAxiomsRDDBuilder.scala

示例5: FunctionalSyntaxOWLAxiomsRDDBuilder

//设置package包名称以及导入依赖的类
package net.sansa_stack.owl.spark.rdd

import com.typesafe.scalalogging.Logger
import net.sansa_stack.owl.common.parsing.FunctionalSyntaxParsing
import org.apache.spark.SparkContext
import org.semanticweb.owlapi.io.OWLParserException


object FunctionalSyntaxOWLAxiomsRDDBuilder extends FunctionalSyntaxParsing {
  private val logger = Logger(this.getClass)

  def build(sc: SparkContext, filePath: String): OWLAxiomsRDD = {
    build(sc, FunctionalSyntaxOWLExpressionsRDDBuilder.build(sc, filePath))
  }

  // FIXME: It has to be ensured that expressionsRDD is in functional syntax
  def build(sc: SparkContext, expressionsRDD: OWLExpressionsRDD): OWLAxiomsRDD = {
    expressionsRDD.map(expression => {
      try makeAxiom(expression)
      catch {
        case exception: OWLParserException => {
          logger.warn("Parser error for line " + expression + ": " + exception.getMessage)
          null
        }
      }
    }).filter(_ != null)
  }
} 
开发者ID:SANSA-Stack,项目名称:SANSA-OWL,代码行数:29,代码来源:FunctionalSyntaxOWLAxiomsRDDBuilder.scala

示例6: ManchesterSyntaxOWLAxiomsDatasetBuilder

//设置package包名称以及导入依赖的类
package net.sansa_stack.owl.spark.dataset

import com.typesafe.scalalogging.Logger
import net.sansa_stack.owl.common.parsing.ManchesterSyntaxParsing
import org.apache.spark.sql.{Encoders, SparkSession}
import org.semanticweb.owlapi.io.OWLParserException
import org.semanticweb.owlapi.model.{OWLAxiom, OWLRuntimeException}


object ManchesterSyntaxOWLAxiomsDatasetBuilder extends ManchesterSyntaxParsing {
  private val logger = Logger(this.getClass)

  def build(spark: SparkSession, filePath: String): OWLAxiomsDataset = {
    val res = ManchesterSyntaxOWLExpressionsDatasetBuilder.buildAndGetDefaultPrefix(spark, filePath)
    val expressionsDataset = res._1
    val defaultPrefix = res._2
    build(expressionsDataset, defaultPrefix)
  }

  // FIXME: It has to be ensured that the expressionsDataset is in functional syntax
  def build(expressionsDataset: OWLExpressionsDataset, defaultPrefix: String): OWLAxiomsDataset = {
    implicit val encoder = Encoders.kryo[OWLAxiom]

    expressionsDataset.filter(!_.startsWith("Annotations")).flatMap(frame => {
      try makeAxioms(frame, defaultPrefix)
      catch {
        case exception: OWLParserException => {
          val msg = exception.getMessage
          logger.warn("Parser error for frame\n" + frame + "\n\n" + msg)
//          exception.printStackTrace()
          Set.empty[OWLAxiom]
        }
        case exception: OWLRuntimeException => {
          val msg = exception.getMessage
          logger.warn("Parser error for frame\n" + frame + "\n\n" + msg)
          exception.printStackTrace()
          Set.empty[OWLAxiom]
        }
      }
    })
  }
} 
开发者ID:SANSA-Stack,项目名称:SANSA-OWL,代码行数:43,代码来源:ManchesterSyntaxOWLAxiomsDatasetBuilder.scala

示例7: GitSourceDownloaderActor

//设置package包名称以及导入依赖的类
package cloud.hw.actors

import akka.actor.{Actor, Props}
import akka.routing.BalancingPool
import cloud.hw.app.ErrorCase
import cloud.hw.util.GitSourceDownloader
import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory


class GitSourceDownloaderActor extends Actor{
  val logger = Logger(LoggerFactory.getLogger(this.getClass))

  def receive = {
    case GitSourceReceiver(metadata) =>
      logger.info("Download git project and send to ElasticsearchAdderActor")
      val GitRepoZip = GitSourceDownloader.fromUrl(metadata("downloadUrl"))
      var unzippedRepo = GitRepoZip.asInstanceOf[GitSourceDownloader].download

      // Creates a balance pool of actors to split up the work.
      val router = context.actorOf(BalancingPool(4).props(Props(new ElasticsearchAdderActor())))

      // Run through all the lines and give each actor 15 entries to insert into
      // Elasticsearch. We used 15 because more than that and we were basically DDOS
      // the Elasticsearch server.
      while(!unzippedRepo.isEmpty) {
        logger.info("Taking 15 entries")
        router ! AddGitProjectToElasticsearch(metadata("projectName"), unzippedRepo.take(15))
        unzippedRepo = unzippedRepo.drop(15)
      }

    // Not a Git repo, then don't do anything.
    case ErrorCase => logger.info("Error with Git repo download")
    case _ => logger.info("Not a vaild message to GitSourceDownloaderActor")
  }
} 
开发者ID:mendozagabe1618,项目名称:openhub-source-search-engine,代码行数:37,代码来源:GitSourceDownloaderActor.scala

示例8: OpenHubMetadataFetcherActor

//设置package包名称以及导入依赖的类
package cloud.hw.actors

import akka.actor.Actor
import cloud.hw.app.ErrorCase
import cloud.hw.util.OpenHubMetadataFetcher
import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory


class OpenHubMetadataFetcherActor extends Actor {
  private val logger = Logger(LoggerFactory.getLogger(this.getClass))

  def receive = {

    // Uses an api key and project id number to fetch an XML that holds the
    // project name, download url, and tags about the project.
    case FetchForKeyID(apiKey, id) =>
      logger.info("Fetch for key id")
      sender() ! OpenHubMetadataFetcher.forKeyId(apiKey, id)

    // Uses a pre-existing url to fetch an XML that holds the
    // project name, download url, and tags about the project.
    case FetchForURL(url) =>
      logger.info("Fetch for key id")
      sender() ! OpenHubMetadataFetcher.forUrl(url)
    case ErrorCase => logger.info("OpenHubMetadataFetcherActor failed to fetch anything.")
  }
} 
开发者ID:mendozagabe1618,项目名称:openhub-source-search-engine,代码行数:29,代码来源:OpenHubMetadataFetcherActor.scala

示例9: MsgPack

//设置package包名称以及导入依赖的类
package com.taxis99.amazon.serializers

import java.util.Base64

import com.typesafe.scalalogging.Logger
import msgpack4z.{MsgOutBuffer, _}
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsValue, Json}

object MsgPack extends ISerializer {
  protected val logger: Logger =
    Logger(LoggerFactory.getLogger(getClass.getName))

  protected val jsonVal = Play2Msgpack.jsValueCodec(PlayUnpackOptions.default)
  protected val b64encoder = Base64.getEncoder
  protected val b64decoder = Base64.getDecoder

  
  override def decode(value: String): JsValue = {
    val bytes: Array[Byte] = b64decoder.decode(value)
    val unpacker = MsgInBuffer.apply(bytes)
    val unpacked = jsonVal.unpack(unpacker)
    unpacked.valueOr { e =>
      logger.error("Could not decode message", e)
      new ClassCastException("Could not decode message")
      Json.obj()
    }
  }
} 
开发者ID:99Taxis,项目名称:common-sqs,代码行数:30,代码来源:MsgPack.scala

示例10: HttpSecondariesExecutor

//设置package包名称以及导入依赖的类
package com.uglylabs.httpduplicator

import com.typesafe.scalalogging.Logger
import Utils._
import org.apache.http.util.EntityUtils

class HttpSecondariesExecutor(poolSize: Int, config: ServerConfig) {
	private val log = Logger[HttpSecondariesExecutor]
	
	private val client = createHttpClient(config)
	
	import java.util.concurrent.Executors
	import scala.concurrent._

	implicit private val ec = new ExecutionContext {
		val threadPool = Executors.newFixedThreadPool(poolSize)

		def execute(runnable: Runnable) =
			threadPool.submit(runnable)
		
		def reportFailure(t: Throwable) = 
			log.error("Thread pool error", t)
	}
	
	def enqueue(target: HttpTarget, request: HttpRequest) {
		Future {
			log.debug("Send request to secondary target: {}\n{}", target, formatRequest(request))
			val response = timing(s"Processing time for secondary $target : %dms", log.debug(_)) {
				client.execute(target.toHttpHost, request)
			}
				
			log.debug("Receive response from secondary target: {}\n{}", target, formatResponse(response))
				
			// release connection resources allocated to receive entity content
			EntityUtils.consume(response.getEntity())
		}.onFailure {
			case e => log.error(s"Error serve request to target: $target", e)
		}
	}
} 
开发者ID:lis0x90,项目名称:httpduplicator,代码行数:41,代码来源:HttpSecondariesExecutor.scala

示例11: ServerImpl

//设置package包名称以及导入依赖的类
package com.uglylabs.httpduplicator

import scala.collection.JavaConverters._

import com.typesafe.scalalogging.Logger

import Utils._
import io.undertow.Undertow
import io.undertow.server.HttpHandler
import io.undertow.server.HttpServerExchange
import io.undertow.server.handlers.BlockingHandler
import io.undertow.util.HttpString
import org.apache.http.client.config.RequestConfig

class ServerImpl(val config: ServerConfig) {
	private val log = Logger[ServerImpl]

	private val client = createHttpClient(config)
	private val httpDuplicator = new HttpSecondariesExecutor(config.poolSize, config)

	private val requestHandler = new HttpHandler() {
		override def handleRequest(exchange: HttpServerExchange) {
			log.info("Handle request: {}", exchange)

			val request = new HttpRequest(exchange).withTarget(config.mainTarget)

			config.secondaryTargets.foreach { target =>  
				httpDuplicator.enqueue(target, request.withTarget(target))
			}

			log.debug("Send request to main target: {}\n{}", config.mainTarget, formatRequest(request))
			val response = timing(s"Processing time for primary ${config.mainTarget} : %dms", log.debug(_)) {
				client.execute(config.mainTarget.toHttpHost, request)
			}
			log.debug("Receive response from main target: {}\n{}", config.mainTarget, formatResponse(response))

			// Format response to client
			exchange.setStatusCode(response.getStatusLine.getStatusCode)
			exchange.setReasonPhrase(response.getStatusLine.getReasonPhrase)
			response.getAllHeaders.foreach { header =>
				exchange.getResponseHeaders().add(new HttpString(header.getName), header.getValue)
			}

			if(response.getEntity != null) {
				exchange.getResponseSender.send(response.getEntity.getContent.toByteBuffer)
			}
			exchange.endExchange()
		}
	}
	
	private val server = Undertow.builder()
		.addHttpListener(config.bind.port, config.bind.host)
		.setHandler(new BlockingHandler(requestHandler))
		.build()

	def start() {
		log.info("Start server with config: {}", config)
		server.start()
	}
} 
开发者ID:lis0x90,项目名称:httpduplicator,代码行数:61,代码来源:ServerImpl.scala

示例12: BackendJsonProtocol

//设置package包名称以及导入依赖的类
package org.breakout.connector.backend

import akka.actor.ActorSystem
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.Logger
import org.breakout.connector.HttpConnection._
import org.breakout.connector.backend.BackendRoutes.ADD_PAYMENT
import spray.client.pipelining._
import spray.http._
import spray.httpx.SprayJsonSupport._
import spray.json.{DefaultJsonProtocol, NullOptions}

import scala.concurrent.Future

object BackendJsonProtocol extends DefaultJsonProtocol with NullOptions {
  implicit val backendPaymentFormat = jsonFormat2(BackendPayment)
  implicit val backendInvoiceFormat = jsonFormat2(BackendInvoice)
}

case class BackendRoute(url: String)

object BackendRoutes {

  private val config = ConfigFactory.load()
  private val baseUrl = config.getString("backend.url")

  def ADD_PAYMENT(purposeOfTransferCode: String): BackendRoute =
    BackendRoute(s"$baseUrl/invoice/payment/$purposeOfTransferCode/")
}

object BackendApi {

  private val log = Logger[BackendApi.type]
  private val config = ConfigFactory.load()
  private val authToken = config.getString("backend.authToken")
  private implicit val system = ActorSystem()

  import BackendJsonProtocol._
  import system.dispatcher

  private val backendPipeline = (
    addHeader("X-AUTH-TOKEN", authToken)
      // ~> logReq
      ~> sendReceive
      // ~> logResp
      ~> setContentType(MediaTypes.`application/json`)
    )

  def addPayment(purposeOfTransferCode: String, payment: BackendPayment): Future[BackendInvoice] = {
    log.debug(s"adding Payment $purposeOfTransferCode; $payment")
    val pipeline = backendPipeline ~> unmarshal[BackendInvoice]
    pipeline(Post(ADD_PAYMENT(purposeOfTransferCode).url, payment))
  }

} 
开发者ID:BreakOutEvent,项目名称:breakout-payment,代码行数:56,代码来源:BackendApi.scala

示例13: CheckPaidLogic

//设置package包名称以及导入依赖的类
package org.breakout.logic

import com.typesafe.scalalogging.Logger
import org.breakout.CmdConfig
import org.breakout.connector.backend.{BackendApi, BackendPayment}
import org.breakout.connector.fidor.FidorApi
import org.breakout.util.IntUtils._
import org.breakout.util.StringUtils._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}


object CheckPaidLogic {

  private val log = Logger[CheckPaidLogic.type]

  def doPaidCheck(cmdConfig: CmdConfig) = {
    log.info(s"Start doPaidCheck ${cmdConfig.dryRun.name}")

    FidorApi.getAllTransactions onComplete {
      case Success(transactions) =>
        val withCorrectSubject = transactions.filter(_.subject.hasValidSubject)
        val withoutCorrectSubject = transactions.filter(t => !withCorrectSubject.contains(t))

        log.debug(s"Got ${withCorrectSubject.size} transactions, with correct subject")

        Future.sequence(withCorrectSubject.map { transaction =>
          log.debug(s"received ${transaction.amount.toDecimalAmount}€ with ${transaction.subject.getSubjectCode} as id ${transaction.id} ")

          if (!cmdConfig.dryRun.enabled) {
            BackendApi.addPayment(
              transaction.subject.getSubjectCode,
              BackendPayment(transaction.amount.toDecimalAmount, transaction.id.toLong)
            ) map { invoice =>
              log.info(s"SUCCESS: inserted payment to backend invoice $invoice")
            } recover { case _: Throwable =>
              log.error(s"backend rejected, maybe already inserted: ${transaction.amount.toDecimalAmount}€ as ${transaction.subject} from ${transaction.transaction_type_details.remote_name} (${transaction.transaction_type_details.remote_iban}) on ${transaction.value_date.get}; fidor id: ${transaction.id}")
            }
          } else {
            log.info("Won't insert payments to backend due to dry-running")
            Future.successful()
          }
        }) onComplete { _ =>
          withoutCorrectSubject.foreach { t =>
            log.error(s"subject is not matching for: ${t.amount.toDecimalAmount}€ as ${t.subject} from ${t.transaction_type_details.remote_name.get} (${t.transaction_type_details.remote_iban.get}) on ${t.value_date.get}; fidor id: ${t.id}")
          }
          System.exit(1)
        }

      case Failure(e) => e.printStackTrace()
    }
  }


} 
开发者ID:BreakOutEvent,项目名称:breakout-payment,代码行数:58,代码来源:CheckPaidLogic.scala

示例14: StringUtils

//设置package包名称以及导入依赖的类
package org.breakout.util

import java.security.MessageDigest

import com.typesafe.scalalogging.Logger

object StringUtils {

  private val log = Logger[StringUtils.type]

  implicit class StringImprovements(val string: String) {

    def getSubjectCode: String =
      getSubjectGroups(string) match {
        case Some((code, checksum)) => code + checksum
        case None => throw new Exception(s"No valid SubjectCode found in $string")
      }

    def hasValidSubject: Boolean = {
      getSubjectGroups(string) match {
        case Some((code, checksum)) =>
          log.debug(s"code: $code; checksum: $checksum; subject: $string")

          val expectedChecksum = MessageDigest.getInstance("SHA-256")
            .digest(code.getBytes("UTF-8"))
            .map("%02X".format(_)).mkString
            .substring(0, 2)

          checksum == expectedChecksum
        case _ => false
      }
    }
  }

  private def getSubjectGroups(subject: String): Option[(String, String)] = {
    val pattern = """([A-Z0-9]{4})([A-Z0-9]{2})-""".r

    val matchedString = pattern.findAllIn(subject.toUpperCase())
    matchedString.isEmpty match {
      case true => None
      case false =>
        val matchedGroups = (0 to matchedString.groupCount).map(matchedString.group).toList

        matchedGroups match {
          case _ :: code :: checksum :: _ =>
            Some((code, checksum))
          case _ => None
        }
    }
  }

} 
开发者ID:BreakOutEvent,项目名称:breakout-payment,代码行数:53,代码来源:StringUtils.scala

示例15: CalculateImportance

//设置package包名称以及导入依赖的类
package org.gc.calculation

import com.typesafe.scalalogging.Logger
import org.gc.component.{Component, Network}

import scala.collection.immutable.HashSet


class CalculateImportance(val network: Network) {

  val log = Logger(classOf[CalculateImportance])

  val failureThreshold = 20
  val failureScore = 10
  val pointOfFailureScore = 10

  var subNetwork = new HashSet[Component]

  def updateNetwork(startComponent: Component): Set[Component] = {

    // Update only the subnet
    subNetwork = new HashSet[Component]
    DFS(startComponent)

    val aps = new CalculateAP(network).findArticulationPoints(startComponent)
    for (n <- aps) {
      n.asInstanceOf[Component].isPointOfFailure = true
    }

    for (n <- subNetwork) {
      scoreCalculator(n.asInstanceOf[Component])
    }

    return subNetwork

  }

  private def scoreCalculator(comp: Component) = {
    var finalScore = 0
    if (comp.isPointOfFailure) {
      finalScore += pointOfFailureScore
    }
    if (comp.failureRate >= failureThreshold) {
      finalScore += failureScore
    }
    finalScore += comp.userImportanceRate
    comp.score = finalScore
  }

  private def DFS(v: Component) {

    subNetwork += v

    for (x <- v.adjacentNodes()) {
      if (subNetwork.find(x.equals).isEmpty) {
        DFS(x.asInstanceOf[Component])
      }
    }
  }

} 
开发者ID:JohnnyCosta,项目名称:graphcheck,代码行数:62,代码来源:CalculateImportance.scala


注:本文中的com.typesafe.scalalogging.Logger类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。