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


Scala Duration类代码示例

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


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

示例1: getDelay

//设置package包名称以及导入依赖的类
package com.box.castle.core.committer.manager

import com.box.castle.core.common.{BoundedQueue, ReadSample}
import com.box.castle.core.config.BatchSizeManagerConfig
import org.joda.time.Duration
import org.slf4s.Logging



  def getDelay(committerActorId: String): Duration = {

    if (samples.size > 1) {
      // We need atleast 2 samples to figure out the rate of data generation and hence the delay
      val dataRead: Double = samples.last.bytesRead - samples.front.bytesRead
      val elapsedTime: Double = samples.last.timestamp - samples.front.timestamp
      val rate: Double = dataRead / elapsedTime
      val delay = (bufferSize * batchSizeManagerConfig.targetBatchSizePercent) / rate

      // The discount factor reduces delay based on how many consecutive full buffers we have seen.
      val discount = Math.pow(batchSizeManagerConfig.discountFactor, consecutiveFullBuffers)
      val computedDelay = Math.min(batchSizeManagerConfig.maxWaitTime.getMillis, (delay * discount).toLong)

      log.info(s"$committerActorId idling for ${computedDelay / 1000} seconds after calculating a rate of ${"%.3f".format(rate / 1048.576)} MiB/sec with discountFactor of ${"%.3f".format(discount)}")
      new Duration(computedDelay)
    }
    else {
      // Not enough data to compute delay
      Duration.ZERO
    }
  }

  def size: Int = samples.size

  def getLastSample: ReadSample = samples.last

} 
开发者ID:Box-Castle,项目名称:core,代码行数:37,代码来源:BatchSizeManager.scala

示例2: BatchSizeManagerConfig

//设置package包名称以及导入依赖的类
package com.box.castle.core.config

import org.joda.time.Duration
import BatchSizeManagerConfig._

case class BatchSizeManagerConfig(samplingSlots: Int = DefaultSamplingSlots,
                                 samplingInterval: Duration = DefaultSamplingInterval,
                                 maxWaitTime: Duration = DefaultMaxWaitTime,
                                 discountFactor: Double = DefaultDiscountFactor,
                                 fullBufferThresholdCount: Int = DefaultFullBufferThresholdCount,
                                 emptyBufferThresholdCount: Int = DefaultEmptyBufferThresholdCount,
                                 targetBatchSizePercent: Double = DefaultTargetBatchSizePercent) {

  require(samplingSlots > 1, "Sampling Slots should be greater than 1")

  require(discountFactor > 0 && discountFactor < 1, "Discount Factor should range between 0 to 1")

  require(targetBatchSizePercent >= 0 && targetBatchSizePercent <= 1,
    "Target batch size percent must be in the interval [0, 1] inclusive")
}


object BatchSizeManagerConfig {
  val DefaultTargetBatchSizePercent = 0
  val DefaultSamplingSlots = 20
  val DefaultSamplingInterval = new Duration(60000) // 1 minute
  val DefaultMaxWaitTime = new Duration(300000) // 5 minutes
  val DefaultDiscountFactor = 0.8
  val DefaultFullBufferThresholdCount = 3
  val DefaultEmptyBufferThresholdCount = 3
} 
开发者ID:Box-Castle,项目名称:core,代码行数:32,代码来源:BatchSizeManagerConfig.scala

示例3: PointSpec

//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.write

import com.pygmalios.reactiveinflux._
import org.joda.time.{DateTime, DateTimeZone, Duration}

object PointSpec {
  val dateTime1 = new DateTime(1983, 1, 10, 11, 42, 7, 13, DateTimeZone.UTC)
  val time1 = PointTime(dateTime1)
  val point1 = Point(time1, "m1", Map.empty, Map("fk" -> LongFieldValue(-1)))

  val time2 = time1.plus(Duration.millis(3))
  val point2 = Point(time2, "m2", Map("tk1" -> "tv1", "tk2" -> "tv2"),
    Map(
      "fk" -> BooleanFieldValue(true),
      "fk2" -> BigDecimalFieldValue(1),
      "fk3" -> StringFieldValue("abcXYZ")
    ))
} 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:19,代码来源:PointSpec.scala

示例4: FutureExecutorStats

//设置package包名称以及导入依赖的类
package justinb99.futureexecutor

import org.joda.time.Duration
import org.joda.time.format.PeriodFormat


case class FutureExecutorStats(numberOfQueuedFutures: Int,
                               numberOfExecutingFutures: Int,
                               executionTimeMillis: Long,
                               numberOfCompletedFutures: Int,
                               numberOfFailedFutures: Int)
{
  val executionTime: String = FormattedDuration(executionTimeMillis)

  val averageExecutionTimeMillis = executionTimeMillis / numberOfCompletedFutures.toLong
  val averageExecutionTime: String = FormattedDuration(averageExecutionTimeMillis)

  //TODO: convert this to use json4s
  override def toString: String = {
    s"""|{
        |  "numberOfQueuedFutures": $numberOfQueuedFutures,
        |  "numberOfExecutingFutures": $numberOfExecutingFutures,
        |  "executionTimeMillis": $executionTimeMillis,
        |  "numberOfCompletedFutures": $numberOfCompletedFutures,
        |  "numberOfFailedFutures": $numberOfFailedFutures,
        |  "executionTime": "$executionTime",
        |  "averageExecutionTimeMillis": $averageExecutionTimeMillis,
        |  "averageExecutionTime": "$averageExecutionTime"
        |}""".stripMargin
  }
}

object FormattedDuration {

  def apply(millis: Long): String = {
    PeriodFormat.getDefault.print(new Duration(millis).toPeriod())
  }

} 
开发者ID:justinb99,项目名称:futureexecutor,代码行数:40,代码来源:FutureExecutorStats.scala

示例5: OauthCode

//设置package包名称以及导入依赖的类
package models


import org.joda.time.{DateTime, Duration}
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, OWrites, Reads}

import scala.util.Random



case class OauthCode(code : String, user: User, client : OauthClient) {
  val created = new DateTime(new java.util.Date())

  // currently codes are valid for one day
  def isExpired : Boolean = created.plus(new Duration(24L*60L*60L*1000L)).isBeforeNow
}

object OauthCode {
  def apply(user: User, client: OauthClient) : OauthCode = OauthCode(Random.alphanumeric.take(100).mkString, user, client)
//  implicit val oauthCodeJsonFormat = Json.format[OauthCode]
  implicit val profileWrites : OWrites[OauthCode] = (
    (JsPath \ "code").write[String] and
      (JsPath \ "user").write[User] and
      (JsPath \ "client").write[OauthClient]
    )(unlift(OauthCode.unapply))
  implicit val profileReads : Reads[OauthCode] = (
    (JsPath \ "code").read[String] and
      (JsPath \ "user").read[User] and
      (JsPath \ "client").read[OauthClient]
    )((code, user, client) => OauthCode(code, user, client))
} 
开发者ID:Viva-con-Agua,项目名称:drops,代码行数:33,代码来源:OauthCode.scala

示例6: Application

//设置package包名称以及导入依赖的类
package controllers

import org.joda.time.{Duration, DateTime}
import play.api.cache.Cached
import play.api.mvc._

import play.api.Play.current

object Application extends Controller {
  val dateFormat = play.api.http.dateFormat

  case class WithCacheControl(action: EssentialAction) extends EssentialAction {
    def apply(request: RequestHeader) = {
      implicit val executionContext = play.api.libs.concurrent.Execution.defaultContext
      action(request).map { result =>
        result.header.headers.get(EXPIRES).map(dateFormat.parseDateTime) match {
          case None => result
          case Some(expires) =>
            val now = DateTime.now()
            val maxAge = new Duration(now, expires).getStandardSeconds + 1
            result.withHeaders(
              (CACHE_CONTROL, s"max-age=$maxAge")
            )
        }
      }
    }
  }

  val key: (RequestHeader) => String = { case rh => rh.uri }

  val cacheDurationFromExpiresHeader: scala.PartialFunction[ResponseHeader, scala.concurrent.duration.Duration] = {
    case rh => rh.headers.get(EXPIRES).map(dateFormat.parseDateTime) match {
      case None => scala.concurrent.duration.Duration(5, scala.concurrent.duration.SECONDS)
      case Some(expires) =>
        val expiresIn = Math.max(new Duration(DateTime.now(), expires).getStandardSeconds, 1)
        scala.concurrent.duration.Duration(expiresIn, scala.concurrent.duration.SECONDS)
    }
  }

  def index = WithCacheControl { Cached(key, cacheDurationFromExpiresHeader) {
    Action {
      val expires = DateTime.now().plusSeconds(5).toString(dateFormat)
      Ok(views.html.index("Your new application is ready."))
        .withHeaders((EXPIRES, expires))
    }
  }}

} 
开发者ID:jruusu,项目名称:play-scala-2.3-cached-result-headers,代码行数:49,代码来源:Application.scala

示例7: JarInfo

//设置package包名称以及导入依赖的类
package spark.jobserver.io

import com.typesafe.config._
import org.joda.time.{DateTime, Duration}
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

// Uniquely identifies the jar used to run a job
case class JarInfo(appName: String, uploadTime: DateTime)

// Both a response and used to track job progress
// NOTE: if endTime is not None, then the job has finished.
case class JobInfo(jobId: String, contextName: String,
                   jarInfo: JarInfo, classPath: String,
                   startTime: DateTime, endTime: Option[DateTime],
                   error: Option[Throwable]) {
  def jobLengthMillis: Option[Long] = endTime.map { end => new Duration(startTime, end).getMillis() }

  def isRunning: Boolean = !endTime.isDefined
  def isErroredOut: Boolean = endTime.isDefined && error.isDefined
}


  def getLastUploadTime(appName: String): Option[DateTime] =
    Await.result(getApps, 60 seconds).get(appName)
} 
开发者ID:TruenoDB,项目名称:trueno-compute-server,代码行数:27,代码来源:JobDAO.scala

示例8: DefaultModule

//设置package包名称以及导入依赖的类
package modules

import com.galacticfog.gestalt.security.SecurityConfig
import com.galacticfog.gestalt.security.data.domain.{AccountStoreMappingService, DefaultAccountStoreMappingServiceImpl}
import com.google.inject.{AbstractModule, Provides}
import org.joda.time.Duration

import scala.util.Properties.envOrNone
import scala.util.Try

class DefaultModule extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[AccountStoreMappingService]).to(classOf[DefaultAccountStoreMappingServiceImpl])
  }

  @Provides
  def providesSecurityConfig(): SecurityConfig = {

    import SecurityConfig._

    val tokenLifetime = (for {
      envString <- envOrNone("OAUTH_TOKEN_LIFETIME")
      lifetime <- Try { Duration.parse(envString) }.toOption
    } yield lifetime) getOrElse DEFAULT_TOKEN_LIFETIME

    val methodOverrideParameter = envOrNone("METHOD_OVERRIDE_PARAM") getOrElse DEFAULT_METHOD_OVERRIDE_PARAM

    val database = DatabaseConfig(
      host = envOrThrow("DATABASE_HOSTNAME"),
      username = envOrThrow("DATABASE_USERNAME"),
      password = envOrThrow("DATABASE_PASSWORD"),
      dbname = envOrThrow("DATABASE_NAME"),
      port = getEnvOptInt("DATABASE_PORT").getOrElse(5432),
      timeout = getEnvOptInt("DATABASE_TIMEOUT_MS").getOrElse(5000)
    )

    val rateLimiting = AuthAttemptConfig(
      periodInMinutes = getEnvOptInt("OAUTH_RATE_LIMITING_PERIOD") getOrElse AuthAttemptConfig.DEFAULT_RATE_LIMITING_PERIOD_IN_MINUTES,
      attemptsPerPeriod = getEnvOptInt("OAUTH_RATE_LIMITING_AMOUNT") getOrElse AuthAttemptConfig.DEFAULT_MAX_ATTEMPTS_PER_MINUTE
    )

    SecurityConfig(
      tokenLifetime = tokenLifetime,
      methodOverrideParameter = methodOverrideParameter,
      database = database,
      rateLimiting = rateLimiting
    )
  }
} 
开发者ID:GalacticFog,项目名称:gestalt-security,代码行数:50,代码来源:DefaultModule.scala

示例9: PerformanceReporting

//设置package包名称以及导入依赖的类
package highperfscala.clientreports.views

import org.joda.time.{Duration, Instant, Interval}

object PerformanceReporting {

  def trend(
    now: () => Instant,
    findOrders: (Interval, Ticker) => List[Order],
    findExecutions: (Interval, Ticker) => List[Execution],
    request: GenerateTradingPerformanceTrend): List[TradingPerformanceTrend] = {
    def periodPnL(
      duration: Duration): Map[Ticker, PeriodPnL] = {
      val currentTime = now()
      val interval = new Interval(currentTime.minus(duration), currentTime)
      (for {
        ticker <- request.tickers
        orders = findOrders(interval, ticker)
        executions = findExecutions(interval, ticker)
        idToExecPrice = executions.groupBy(_.id).mapValues(es =>
          Price.average(es.map(_.price)))
        signedExecutionPrices = for {
          o <- orders
          if o.clientId == request.clientId
          price <- idToExecPrice.get(o.id).map(p => o match {
            case _: BuyOrder => Price(p.value * -1)
            case _: SellOrder => p
          }).toList
        } yield price
        trend = signedExecutionPrices.foldLeft(PnL.zero) {
          case (pnl, p) => PnL(pnl.value + p.value)
        } match {
          case p if p.value >= PnL.zero.value => PeriodPositive
          case _ => PeriodNegative
        }
      } yield ticker -> trend).toMap
    }

    val tickerToLastHour = periodPnL(Duration.standardHours(1)).mapValues {
      case PeriodPositive => LastHourPositive
      case PeriodNegative => LastHourNegative
    }
    val tickerToLastDay = periodPnL(Duration.standardDays(1)).mapValues {
      case PeriodPositive => LastDayPositive
      case PeriodNegative => LastDayNegative
    }
    val tickerToLastSevenDays = periodPnL(Duration.standardDays(7)).mapValues {
      case PeriodPositive => LastSevenDayPositive
      case PeriodNegative => LastSevenDayNegative
    }

    tickerToLastHour.zip(tickerToLastDay).zip(tickerToLastSevenDays).map({
      case (((t, lastHour), (_, lastDay)), (_, lastSevenDays)) =>
        TradingPerformanceTrend(t, lastHour, lastDay, lastSevenDays)
    }).toList
  }
} 
开发者ID:PacktPublishing,项目名称:Scala-High-Performance-Programming,代码行数:58,代码来源:PerformanceReporting.scala

示例10: ViewPerformanceReporting

//设置package包名称以及导入依赖的类
package highperfscala.clientreports.views

import org.joda.time.{Duration, Instant, Interval}

object ViewPerformanceReporting {

  def trend(
    now: () => Instant,
    findOrders: (Interval, Ticker) => List[Order],
    findExecutions: (Interval, Ticker) => List[Execution],
    request: GenerateTradingPerformanceTrend): List[TradingPerformanceTrend] = {

    def periodPnL(
      duration: Duration): Map[Ticker, PeriodPnL] = {
      val currentTime = now()
      val interval = new Interval(currentTime.minus(duration), currentTime)
      (for {
        ticker <- request.tickers
        orders = findOrders(interval, ticker)
        executions = findExecutions(interval, ticker)
        idToExecPrice = executions.groupBy(_.id).mapValues(es =>
          Price.average(es.map(_.price)))
        signedExecutionPrices = for {
          o <- orders.view
          if o.clientId == request.clientId
          price <- idToExecPrice.get(o.id).map(p => o match {
            case _: BuyOrder => Price(p.value * -1)
            case _: SellOrder => p
          }).toList
        } yield price
        trend = signedExecutionPrices.foldLeft(PnL.zero) {
          case (pnl, p) => PnL(pnl.value + p.value)
        } match {
          case p if p.value >= PnL.zero.value => PeriodPositive
          case _ => PeriodNegative
        }
      } yield ticker -> trend).toMap
    }

    val tickerToLastHour = periodPnL(Duration.standardHours(1)).mapValues {
      case PeriodPositive => LastHourPositive
      case PeriodNegative => LastHourNegative
    }
    val tickerToLastDay = periodPnL(Duration.standardDays(1)).mapValues {
      case PeriodPositive => LastDayPositive
      case PeriodNegative => LastDayNegative
    }
    val tickerToLastSevenDays = periodPnL(Duration.standardDays(7)).mapValues {
      case PeriodPositive => LastSevenDayPositive
      case PeriodNegative => LastSevenDayNegative
    }

    tickerToLastHour.zip(tickerToLastDay).zip(tickerToLastSevenDays).map({
      case (((t, lastHour), (_, lastDay)), (_, lastSevenDays)) =>
        TradingPerformanceTrend(t, lastHour, lastDay, lastSevenDays)
    }).toList
  }

} 
开发者ID:PacktPublishing,项目名称:Scala-High-Performance-Programming,代码行数:60,代码来源:ViewPerformanceReporting.scala

示例11: TotalEstimatorSpec

//设置package包名称以及导入依赖的类
package cas.analysis

import java.util.Date

import cas.analysis.estimation._
import cas.analysis.subject.Subject
import cas.analysis.subject.components.{CreationDate, Likability, Virality}
import org.joda.time.{DateTime, Duration, Period}
import org.specs2.mutable.Specification

class TotalEstimatorSpec extends Specification {
  "TotalEstimator" should {
    val estims = new LoyaltyEstimator(LoyaltyConfigs(Map(
      Duration.standardMinutes(2) -> 2.0)
    )) :: Nil
    val estimator = new TotalEstimator(estims)

    "Return error" in {
      "With lack of subject components" in {
        val subj = Subject(List(CreationDate(DateTime.now())))
        val actuality = estimator estimateActuality subj
        println("[TotalEstimator] Left msg (lack of components): " + actuality.left.get)
        actuality.right.getOrElse(-1.0) must beCloseTo(-1.0, 0.001)
      }
    }

    "Return actuality" in {
      "With weight" in {
        val subj = Subject(List(Likability(5.0), Virality(11.0), CreationDate(DateTime.now())))
        val actuality = estimator estimateActuality subj
        actuality.right.getOrElse(-10.0) must beGreaterThanOrEqualTo(0.3)
      }
    }
  }
} 
开发者ID:kell18,项目名称:CAS,代码行数:36,代码来源:TotalEstimatorSpec.scala

示例12: Timer

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

import org.joda.time.Duration
import org.joda.time.format.PeriodFormatterBuilder

class Timer {
  val millis = 0L

  def display:String = {
    val duration = new Duration(millis)
    val formatter = new PeriodFormatterBuilder()
      .printZeroAlways().minimumPrintedDigits(2)
      .appendHours()
      .appendSeparator(":")
      .appendMinutes()
      .appendSeparator(":")
      .appendSeconds()
      .toFormatter
    formatter.print(duration.toPeriod)
  }
} 
开发者ID:pharmpress,项目名称:timer,代码行数:22,代码来源:Timer.scala


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