code
stringlengths
5
1M
repo_name
stringlengths
5
109
path
stringlengths
6
208
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1M
/** * Copyright 2015 Devon Miller * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.im package vdom package backend import scala.concurrent.ExecutionContext import scala.concurrent.Future import org.im.vdom._ import vdom._ /** * Render to markup. This is a WIP and the current markup output is not valid. * * TODO: Make the markup correct :-) */ trait MarkupRendererComponent extends RendererComponent { self: Backend => import Utils._ type RenderOutput = String def render(vnode: VNode)(implicit executor: ExecutionContext): IOAction[RenderOutput] = { val ctx = createContext().getEC(executor) vnode match { case v@VirtualText(content) => Action.successful(content) case v@VirtualElementNode(tag, attributes, children, key, namespace) => // find style "attributes", then add val processStyles = Action.lift { createMarkupForStyles(attributes.filter(keepStyles)).map("style=\"" + _ + "\"").getOrElse(" ") } // process remaining attributes val processAttributes = Action.lift { attributes.filter(keepAttributes).map { createMarkupForProperty(_).getOrElse("") }.mkString(" ") } // create tag content val childMarkup = Action.fold(children.map { child => render(child) }, "") { stringAppend } val elHint = DOMElHints.hint(tag) // If omit closing tag, just close tag, don't generate middle content. val middleEnd = elHint.filter(h => !(h.values & Hints.OmitClosingTag).isEmpty).fold { Seq(Action.successful(">"), childMarkup, Action.successful("</" + tag + ">")) } { h => Seq(Action.successful("/>")) } Action.fold(Seq(Action.successful("<" + tag + " "), processStyles, processAttributes) ++ middleEnd, "") { stringAppend } case EmptyNode() => Action.successful("<div></div>") case ThunkNode(f) => render(f()) case x@_ => Action.failed(new VDomException(s"Unknown VNode type $x for $this")) } } } trait MarkupBackend extends Backend with MarkupRendererComponent { type This = MarkupBackend type Context = BasicContext protected[this] def createContext() = new BasicContext {} } object MarkupBackend extends MarkupBackend
nightscape/scala-vdom
shared/src/main/scala/org/im/vdom/backend/MarkupBackend.scala
Scala
apache-2.0
2,867
package com.ncodelab.trackers.bitbucket import java.util.Base64 import java.nio.charset.StandardCharsets object Auth { type Token = String def auth(credentials: Credentials): Token = Base64.getEncoder .encodeToString((credentials.username + ":" + credentials.password) .getBytes(StandardCharsets.UTF_8)) }
ncodelab/trackers-link
src/main/scala/com/ncodelab/trackers/bitbucket/Auth.scala
Scala
lgpl-3.0
329
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.spark.testsuite.deleteTable import org.apache.spark.sql.common.util.QueryTest import org.scalatest.BeforeAndAfterAll /** * test class for testing the create cube DDL. */ class TestDeleteTableNewDDL extends QueryTest with BeforeAndAfterAll { override def beforeAll: Unit = { sql("drop table if exists CaseInsensitiveTable") sql("drop table if exists dropTableTest1") sql("drop table if exists dropTableTest2") sql("drop table if exists dropTableTest4") sql("drop table if exists table1") sql("drop table if exists table2") sql("CREATE TABLE IF NOT EXISTS table1(empno Int, empname Array<String>, designation String, doj Timestamp, " + "workgroupcategory Int, workgroupcategoryname String, deptno Int, deptname String, projectcode Int, " + "projectjoindate Timestamp, projectenddate Timestamp , attendance Int,utilization Int,salary Int )" + " STORED BY 'org.apache.carbondata.format' ") sql("CREATE TABLE IF NOT EXISTS table2(empno Int, empname Array<String>, designation String, doj Timestamp, " + "workgroupcategory Int, workgroupcategoryname String, deptno Int, deptname String, projectcode Int, " + "projectjoindate Timestamp, projectenddate Timestamp , attendance Int,utilization Int,salary Int )" + " STORED BY 'org.apache.carbondata.format' ") } // normal deletion case test("drop table Test with new DDL") { sql("drop table table1") } test("test drop database cascade command") { sql("create database testdb") sql("use testdb") sql("CREATE TABLE IF NOT EXISTS testtable(empno Int, empname string, utilization Int,salary Int)" + " STORED BY 'org.apache.carbondata.format' ") try { sql("drop database testdb") assert(false) } catch { case _ : Exception => } sql("drop database testdb cascade") try { sql("use testdb") assert(false) } catch { case _ : Exception => } sql("use default") } // deletion case with if exists test("drop table if exists Test with new DDL") { sql("drop table if exists table2") } // try to delete after deletion with if exists test("drop table after deletion with if exists with new DDL") { sql("drop table if exists table2") } // try to delete after deletion with out if exists. this should fail test("drop table after deletion with new DDL") { try { sql("drop table table2") fail("failed") // this should not be executed as exception is expected } catch { case _: Exception => // pass the test case as this is expected } } test("drop table using case insensitive table name") { sql("drop table if exists CaseInsensitiveTable") // create table sql( "CREATE table CaseInsensitiveTable (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary int) stored by 'org.apache.carbondata.format'" + "TBLPROPERTIES('DICTIONARY_INCLUDE'='ID, salary')" ) // table should drop wihout any error sql("drop table caseInsensitiveTable") // Now create same table, it should not give any error. sql( "CREATE table CaseInsensitiveTable (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary int) stored by 'org.apache.carbondata.format'" + "TBLPROPERTIES('DICTIONARY_INCLUDE'='ID, salary')" ) } test("drop table using dbName and table name") { // create table sql( "CREATE table default.table3 (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary int) stored by 'org.apache.carbondata.format'" + "TBLPROPERTIES('DICTIONARY_INCLUDE'='ID, salary')" ) // table should drop without any error sql("drop table default.table3") } test("drop table and create table with different data type") { sql("drop table if exists droptabletest1") sql( "CREATE table dropTableTest1 (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary int) stored by 'org.apache.carbondata.format' " ) sql( s"LOAD DATA LOCAL INPATH '$resourcesPath/dataretention1.csv' INTO TABLE dropTableTest1 " + "OPTIONS('DELIMITER' = ',')") sql("drop table dropTableTest1") sql( "CREATE table dropTableTest1 (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary String) stored by 'org.apache.carbondata.format' " ) sql( s"LOAD DATA LOCAL INPATH '$resourcesPath/dataretention1.csv' INTO TABLE dropTableTest1 " + "OPTIONS('DELIMITER' = ',')") } test("drop table and create table with dictionary exclude integer scenario") { sql("drop table if exists dropTableTest2") sql( "CREATE table dropTableTest2 (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary int) stored by 'org.apache.carbondata.format' " + "TBLPROPERTIES('DICTIONARY_INCLUDE'='salary')" ) sql( s"LOAD DATA LOCAL INPATH '$resourcesPath/dataretention1.csv' INTO TABLE dropTableTest2 " + "OPTIONS('DELIMITER' = ',')") sql("drop table dropTableTest2") sql( "CREATE table dropTableTest2 (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary decimal) stored by 'org.apache.carbondata.format' " + "TBLPROPERTIES('DICTIONARY_INCLUDE'='date')" ) sql( s"LOAD DATA LOCAL INPATH '$resourcesPath/dataretention1.csv' INTO TABLE dropTableTest2 " + "OPTIONS('DELIMITER' = ',')") } test("drop table and create table with dictionary exclude string scenario") { try { sql("create database test") sql( "CREATE table test.dropTableTest3 (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary int) stored by 'org.apache.carbondata.format' " + "TBLPROPERTIES('DICTIONARY_INCLUDE'='salary')" ) sql( s"LOAD DATA LOCAL INPATH '$resourcesPath/dataretention1.csv' INTO TABLE test.dropTableTest3 " + "OPTIONS('DELIMITER' = ',')") sql("drop table test.dropTableTest3") sql( "CREATE table test.dropTableTest3 (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary decimal) stored by 'org.apache.carbondata.format' " + "TBLPROPERTIES('DICTIONARY_EXCLUDE'='date')" ) sql( s"LOAD DATA LOCAL INPATH '$resourcesPath/dataretention1.csv' INTO TABLE test.dropTableTest3 " + "OPTIONS('DELIMITER' = ',')") } finally { sql("drop table test.dropTableTest3") sql("drop database test") } } test("drop table and create table with same name but different cols") { sql("drop table if exists dropTableTest4") sql( "CREATE TABLE dropTableTest4 (imei string,age int,task bigint,name string,country string," + "city string,sale int,num double,level decimal(10,3),quest bigint,productdate timestamp," + "enddate timestamp,PointId double,score decimal(10,3))STORED BY 'org.apache.carbondata" + ".format'") sql( s"LOAD DATA INPATH '$resourcesPath/big_int_Decimal.csv' INTO TABLE dropTableTest4 " + "options ('DELIMITER'=',', 'QUOTECHAR'='\\"', 'COMPLEX_DELIMITER_LEVEL_1'='$'," + "'COMPLEX_DELIMITER_LEVEL_2'=':', 'FILEHEADER'= '')") sql("drop table dropTableTest4") sql( "CREATE table dropTableTest4 (ID int, date String, country String, name " + "String," + "phonetype String, serialname String, salary decimal) stored by 'org.apache.carbondata" + ".format' " + "TBLPROPERTIES('DICTIONARY_EXCLUDE'='date')" ) sql( s"LOAD DATA LOCAL INPATH '$resourcesPath/dataretention1.csv' INTO TABLE dropTableTest4 " + "OPTIONS('DELIMITER' = ',')") } override def afterAll: Unit = { sql("drop table if exists CaseInsensitiveTable") sql("drop table if exists dropTableTest1") sql("drop table if exists dropTableTest2") sql("drop table if exists dropTableTest4") sql("drop table if exists table1") sql("drop table if exists table2") } }
ksimar/incubator-carbondata
integration/spark-common-test/src/test/scala/org/apache/carbondata/spark/testsuite/deleteTable/TestDeleteTableNewDDL.scala
Scala
apache-2.0
9,218
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.xforms import org.orbeon.oxf.common.OXFException import org.orbeon.oxf.util.CoreUtils._ import org.orbeon.oxf.util.IndentedLogger import org.orbeon.oxf.util.Logging._ import org.orbeon.oxf.xforms.control.Controls.{BindingUpdater, ControlsIterator} import org.orbeon.oxf.xforms.control.controls.{XFormsRepeatControl, XFormsRepeatIterationControl} import org.orbeon.oxf.xforms.control.{Controls, Focus, XFormsContainerControl, XFormsControl} import org.orbeon.oxf.xforms.event.Dispatch import org.orbeon.oxf.xforms.event.events.XXFormsRefreshDoneEvent import org.orbeon.oxf.xforms.itemset.Itemset import org.orbeon.oxf.xforms.state.ControlState class XFormsControls(val containingDocument: XFormsContainingDocument) { import Private._ implicit val indentedLogger: IndentedLogger = containingDocument.getIndentedLogger("control") // Q: Not "controls"? def isInitialized : Boolean = Private.initialized def isDirtySinceLastRequest : Boolean = Private.dirtySinceLastRequest def isRequireRefresh : Boolean = Private.requireRefresh def isInRefresh : Boolean = Private.inRefresh def markDirtySinceLastRequest(bindingsAffected: Boolean): Unit = { dirtySinceLastRequest = true if (bindingsAffected) currentControlTree.markBindingsDirty() } def requireRefresh(): Unit = { Private.requireRefresh = true markDirtySinceLastRequest(true) } def refreshStart(): Unit = { Private.requireRefresh = false inRefresh = true containingDocument.getRequestStats.refreshes += 1 containingDocument.xpathDependencies.refreshStart() } def refreshDone(): Unit = { inRefresh = false containingDocument.xpathDependencies.refreshDone() } // Create the controls, whether upon initial creation of restoration of the controls. def createControlTree(state: Option[Map[String, ControlState]]): Unit = { assert(! initialized) if (containingDocument.staticState.topLevelPart.hasControls) { // NOTE: We set this first so that the tree is made available during construction to XPath functions // like `index()` or `case()` initialControlTree = new ControlTree currentControlTree = initialControlTree // Set this here so that while `initialize()` runs below, refresh events will find the flag set initialized = true currentControlTree.initialize(containingDocument, state) } else { initialized = true } } // Adjust the controls after sending a response. // This makes sure that we don't keep duplicate control trees. def afterUpdateResponse(): Unit = { assert(initialized) if (containingDocument.staticState.topLevelPart.hasControls) { // Keep only one control tree initialControlTree = currentControlTree // We are now clean markCleanSinceLastRequest() // Need to make sure that `current eq initial` within controls ControlsIterator(containingDocument.controls.getCurrentControlTree) foreach (_.resetLocal()) } } // Create a new repeat iteration for insertion into the current tree of controls. def createRepeatIterationTree( repeatControl : XFormsRepeatControl, iterationIndex : Int // 1..repeat size + 1 ): XFormsRepeatIterationControl = { if ((initialControlTree eq currentControlTree) && containingDocument.isHandleDifferences) throw new OXFException("Cannot call `insertRepeatIteration()` when `initialControlTree eq currentControlTree`") withDebug("controls: adding iteration") { currentControlTree.createRepeatIterationTree(containingDocument, repeatControl, iterationIndex) } } // Get the `ControlTree` computed in the `initialize()` method def getInitialControlTree: ControlTree = initialControlTree // Get the last computed `ControlTree` def getCurrentControlTree: ControlTree = currentControlTree // Clone the current controls tree if: // // 1. it hasn't yet been cloned // 2. we are not during the XForms engine initialization // // The rationale for #2 is that there is no controls comparison needed during initialization. Only during further // client requests do the controls need to be compared. // def cloneInitialStateIfNeeded(): Unit = if ((initialControlTree eq currentControlTree) && containingDocument.isHandleDifferences) withDebug("controls: cloning") { // NOTE: We clone "back", that is the new tree is used as the "initial" tree. This is done so that // if we started working with controls in the initial tree, we can keep using those references safely. initialControlTree = currentControlTree.getBackCopy.asInstanceOf[ControlTree] } // For Java callers // 2018-01-05: 1 usage def getObjectByEffectiveId(effectiveId: String): XFormsControl = findObjectByEffectiveId(effectiveId).orNull def findObjectByEffectiveId(effectiveId: String): Option[XFormsControl] = currentControlTree.findControl(effectiveId) // Get the items for a given control id def getConstantItems(controlPrefixedId: String): Option[Itemset] = constantItems.get(controlPrefixedId) // Set the items for a given control id def setConstantItems(controlPrefixedId: String, itemset: Itemset): Unit = constantItems += controlPrefixedId -> itemset def doRefresh(): Unit = { if (! initialized) { debug("controls: skipping refresh as controls are not initialized") return } if (inRefresh) { // Ignore "nested refresh" // See https://github.com/orbeon/orbeon-forms/issues/1550 debug("controls: attempt to do nested refresh") return } // This method implements the new refresh event algorithm: // http://wiki.orbeon.com/forms/doc/developer-guide/xforms-refresh-events // Don't do anything if there are no children controls if (getCurrentControlTree.children.isEmpty) { debug("controls: not performing refresh because no controls are available") refreshStart() refreshDone() } else { withDebug("controls: performing refresh") { // Notify dependencies refreshStart() // Focused control before updating bindings val focusedBeforeOpt = focusedControlOpt val resultOpt = try { // Update control bindings // NOTE: During this process, ideally, no events are dispatched. However, at this point, the code // can an dispatch, upon removed repeat iterations, xforms-disabled, DOMFocusOut and possibly events // arising from updating the binding of nested XBL controls. // This unfortunately means that side-effects can take place. This should be fixed, maybe by simply // detaching removed iterations first, and then dispatching events after all bindings have been // updated as part of dispatchRefreshEvents() below. This requires that controls are able to kind of // stay alive in detached mode, and then that the index is also available while these events are // dispatched. // `None` if bindings are clean for (updater <- updateControlBindings()) yield updater -> gatherControlsForRefresh } finally { // TODO: Why a `finally` block here? If an exception happened, do we really need to do a `refreshDone()`? // "Actions that directly invoke rebuild, recalculate, revalidate, or refresh always have an immediate // effect, and clear the corresponding flag." refreshDone() } resultOpt foreach { case (updater, controlsEffectiveIds) => // Dispatch events currentControlTree.updateValueControls(controlsEffectiveIds) currentControlTree.dispatchRefreshEvents(controlsEffectiveIds, isInitial = false) // Handle focus changes Focus.updateFocusWithEvents(focusedBeforeOpt, updater.partialFocusRepeat)(containingDocument) // Dispatch to the root control getCurrentControlTree.rootOpt foreach { root => Dispatch.dispatchEvent(new XXFormsRefreshDoneEvent(root)) } } } } } // Do a refresh of a subtree of controls starting at the given container control. // This is used by `xf:switch` and `xxf:dialog` as of 2021-04-14. def doPartialRefresh(containerControl: XFormsContainerControl): Unit = { val focusedBeforeOpt = getFocusedControl // Update bindings starting at the container control val updater = updateSubtreeBindings(containerControl) val controlIds = gatherControlsForRefresh(containerControl) currentControlTree.updateValueControls(controlIds) currentControlTree.dispatchRefreshEvents(controlIds, isInitial = false) Focus.updateFocusWithEvents(focusedBeforeOpt, updater.partialFocusRepeat)(containingDocument) } def getFocusedControl: Option[XFormsControl] = Private.focusedControlOpt def setFocusedControl(focusedControl: Option[XFormsControl]): Unit = Private.focusedControlOpt = focusedControl private object Private { var initialized = false var initialControlTree = new ControlTree var currentControlTree = initialControlTree // Crude flag to indicate that something might have changed since the last request. This caches simples cases where // an incoming change on the document does not cause any change to the data or controls. In that case, the control // trees need not be compared. A general mechanism detecting mutations in the proper places would be better. var dirtySinceLastRequest = false // Whether we currently require a UI refresh var requireRefresh = false // Whether we are currently in a refresh var inRefresh = false var constantItems = Map[String, Itemset]() // Remember which control owns focus if any var focusedControlOpt: Option[XFormsControl] = None def markCleanSinceLastRequest(): Unit = { dirtySinceLastRequest = false currentControlTree.markBindingsClean() } // Update all the control bindings. // // Return `None` if control bindings are not dirty. Otherwise, control bindings are // updated and the `BindingUpdater` is returned. // def updateControlBindings(): Option[BindingUpdater] = { assert(initialized) currentControlTree.bindingsDirty option { // Clone if needed cloneInitialStateIfNeeded() // Visit all controls and update their bindings val updater = withDebug("controls: updating bindings") { Controls.updateBindings(containingDocument) |!> (updater => debugResults(updaterDebugResults(updater))) } // Controls are clean initialControlTree.markBindingsClean() currentControlTree.markBindingsClean() updater } } // Update the bindings of a container control and its descendants. // This is used by `xf:switch` and `xxf:dialog` as of 2021-04-14. def updateSubtreeBindings(containerControl: XFormsContainerControl): BindingUpdater = { cloneInitialStateIfNeeded() withDebug("controls: updating bindings", List("container" -> containerControl.effectiveId)) { Controls.updateBindings(containerControl) |!> (updater => debugResults(updaterDebugResults(updater))) } } private def updaterDebugResults(updater: BindingUpdater) = List( "controls visited" -> updater.visitedCount.toString, "bindings evaluated" -> updater.updatedCount.toString, "bindings optimized" -> updater.optimizedCount.toString ) def gatherControlsForRefresh: List[String] = ControlsIterator(containingDocument.controls.getCurrentControlTree) filter XFormsControl.controlSupportsRefreshEvents map (_.effectiveId) toList def gatherControlsForRefresh(containerControl: XFormsContainerControl): List[String] = ControlsIterator(containerControl, includeSelf = true) filter XFormsControl.controlSupportsRefreshEvents map (_.effectiveId) toList } }
orbeon/orbeon-forms
xforms-runtime/shared/src/main/scala/org/orbeon/oxf/xforms/XFormsControls.scala
Scala
lgpl-2.1
12,939
package com.ovoenergy.orchestration.scheduling object Persistence { sealed trait SetAsOrchestratingResult case class Successful(schedule: Schedule) extends SetAsOrchestratingResult case object AlreadyBeingOrchestrated extends SetAsOrchestratingResult case object Failed extends SetAsOrchestratingResult trait Orchestration { def attemptSetScheduleAsOrchestrating(scheduleId: ScheduleId): SetAsOrchestratingResult def setScheduleAsFailed(scheduleId: ScheduleId, reason: String): Unit def setScheduleAsComplete(scheduleId: ScheduleId): Unit } trait Listing { def listPendingSchedules(): List[Schedule] def listExpiredSchedules(): List[Schedule] } }
ovotech/comms-orchestration
src/main/scala/com/ovoenergy/orchestration/scheduling/Persistence.scala
Scala
mit
715
/** * Copyright (C) 2017-2018 Koddi Inc * See the LICENSE file distributed with this work for additional * information regarding copyright ownership. */ package com.koddi.geocoder import java.net.URLEncoder object Component { val ROUTE = "route" val LOCALITY = "locality" val ADMINISTRATIVE_AREA = "administrative_area" val POSTAL_CODE = "postal_code" val COUNTRY = "country" } sealed abstract class AbstractComponent(key: String, value: String) { private val formattedString = s"${key}:${value}" override def toString(): String = formattedString } case class Component(key: String, value: String) extends AbstractComponent(key, value) /** Serializes to "route=value" */ case class RouteComponent(value: String) extends AbstractComponent(Component.ROUTE, value) /** Serializes to "locality=value" */ case class LocalityComponent(value: String) extends AbstractComponent(Component.LOCALITY, value) /** Serializes to "administrative_area=value" */ case class AdministrativeAreaComponent(value: String) extends AbstractComponent(Component.ADMINISTRATIVE_AREA, value) /** Serializes to "postal_code=value" */ case class PostalCodeComponent(value: String) extends AbstractComponent(Component.POSTAL_CODE, value) /** Serializes to "country=value" */ case class CountryComponent(value: String) extends AbstractComponent(Component.COUNTRY, value) case class Parameters( language: Option[String] = None, region: Option[String] = None, bounds: Option[GeometryBounds] = None, resultType: Option[Seq[String]] = None, locationType: Option[Seq[String]] = None) { def appendToUrlBuilder(builder: StringBuilder) { language match { case Some(value) => appendQueryParameter(builder, Geocoder.API_PARAM_LANGUAGE, value) case None => // default } region match { case Some(value) => appendQueryParameter(builder, Geocoder.API_PARAM_REGION, value) case None => // default } bounds match { case Some(value) => appendQueryParameter(builder, Geocoder.API_PARAM_BOUNDS, value.toString) case None => // default } resultType match { case Some(value) => appendQueryParameter(builder, Geocoder.API_PARAM_RESULT_TYPE, value.mkString("|")) case None => // default } locationType match { case Some(value) => appendQueryParameter(builder, Geocoder.API_PARAM_LOCATION_TYPE, value.mkString("|")) case None => // default } } private def appendQueryParameter(builder: StringBuilder, key: String, value: String) { builder.append("&") builder.append(URLEncoder.encode(key, "UTF-8")) builder.append("=") builder.append(URLEncoder.encode(value, "UTF-8")) } }
mcross1882/geocoder
src/main/scala/com/koddi/geocoder/Component.scala
Scala
mit
2,884
package org.skrushingiv.json import play.api.libs.json.{Format,Reads,Writes,JsValue} /** * `WrappedFormat` provides methods that implement the Format interface by forwarding to * `Reads` and `Writes` instances local to the implementing class. */ trait WrappedFormat[T] extends Format[T] { protected val r: Reads[T] protected val w: Writes[T] def reads(json:JsValue) = r.reads(json) def writes(value:T) = w.writes(value) }
srushingiv/org.skrushingiv
src/main/scala/org/skrushingiv/json/WrappedFormat.scala
Scala
mit
436
package com.socrata.spandex.common.client import java.time.Instant import java.util.concurrent.ArrayBlockingQueue import com.typesafe.scalalogging.slf4j.Logging /** * The ColumnValueCacheWriterThread writes values cached from its provided spandexESClient to Elasticsearch. * * @param spandexESClient The Elasticsearch Client that values will be written to ES from * @param columnValuesCache A reference to the column value cache in spandexESClient * @param flushCacheTimeoutSeconds The maximum amount of time between writes... if we don't have enough Column * Values to justify a flush for flushCacheTimeoutSeconds seconds, we write to * the cache regardless. * @param sleepIntervalMillis The amount of time we sleep at the end of the thread's main loop */ class ColumnValueCacheWriter( val spandexESClient: SpandexElasticSearchClient, val shouldKill : java.util.ArrayList[Boolean], val columnValuesCache: ArrayBlockingQueue[ColumnValue], val flushCacheTimeoutSeconds: Int = 30, // scalastyle:off magic.number val sleepIntervalMillis: Int = 250 // scalastyle:off magic.number ) extends Runnable with Logging { def run: Unit = { logger.info("ColumnValueWriterThread thread initialized") var lastWriteTime = Instant.now() while (shouldKill.isEmpty) { if (columnValuesCache.size > spandexESClient.dataCopyBatchSize) { spandexESClient.flushColumnValueCache(spandexESClient.dataCopyBatchSize) lastWriteTime = Instant.now() } /* If we haven't written anything in 30 seconds, go ahead and flush the cache */ if (lastWriteTime.plusSeconds(flushCacheTimeoutSeconds).isBefore(Instant.now())) { spandexESClient.flushColumnValueCache() lastWriteTime = Instant.now() } Thread.sleep(sleepIntervalMillis) } logger.info("ColumnValueWriterThread shutting down") } }
socrata-platform/spandex
spandex-common/src/main/scala/com/socrata/spandex/common/client/ColumnValueCacheWriter.scala
Scala
apache-2.0
1,968
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.streaming import org.apache.hadoop.fs.Path import org.apache.hadoop.io.{NullWritable, Text} import org.apache.hadoop.mapreduce.TaskAttemptContext import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.execution.datasources.OutputWriter import org.apache.spark.sql.Row import org.apache.carbondata.hadoop.streaming.{CarbonStreamingOutputFormat, CarbonStreamingRecordWriter} class CarbonStreamingOutputWriter ( path: String, context: TaskAttemptContext) extends OutputWriter { private[this] val buffer = new Text() private val recordWriter: CarbonStreamingRecordWriter[NullWritable, Text] = { val outputFormat = new CarbonStreamingOutputFormat[NullWritable, Text] () { override def getDefaultWorkFile(context: TaskAttemptContext, extension: String) : Path = { new Path(path) } /* May need to override def getOutputCommiter(c: TaskAttemptContext): OutputCommitter = { null } */ } outputFormat. getRecordWriter(context).asInstanceOf[CarbonStreamingRecordWriter[NullWritable, Text]] } override def write(row: Row): Unit = { throw new UnsupportedOperationException("call writeInternal") } override protected [sql] def writeInternal(row: InternalRow): Unit = { val utf8string = row.getUTF8String(0) buffer.set(utf8string.getBytes) recordWriter.write(NullWritable.get(), buffer) } def getpath: String = path override def close(): Unit = { recordWriter.close(context) } def flush(): Unit = { recordWriter.flush() } def getPos(): Long = { recordWriter.getOffset() } def commit(finalCommit: Boolean): Unit = { recordWriter.commit(finalCommit) } }
aniketadnaik/carbondataStreamIngest
integration/spark2/src/main/scala/org/apache/spark/sql/streaming/CarbonStreamingOutputWriter.scala
Scala
apache-2.0
2,562
package models import org.jboss.netty.buffer._ import org.joda.time.DateTime import play.api.data._ import play.api.data.Forms._ import play.api.data.format.Formats._ import play.api.data.validation.Constraints._ import reactivemongo.bson._ case class Article( id: Option[BSONObjectID], title: String, content: String, publisher: String, creationDate: Option[DateTime], updateDate: Option[DateTime]) // Turn off your mind, relax, and float downstream // It is not dying... object Article { implicit object ArticleBSONReader extends BSONDocumentReader[Article] { def read(doc: BSONDocument): Article = Article( doc.getAs[BSONObjectID]("_id"), doc.getAs[String]("title").get, doc.getAs[String]("content").get, doc.getAs[String]("publisher").get, doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)), doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value))) } implicit object ArticleBSONWriter extends BSONDocumentWriter[Article] { def write(article: Article): BSONDocument = BSONDocument( "_id" -> article.id.getOrElse(BSONObjectID.generate), "title" -> article.title, "content" -> article.content, "publisher" -> article.publisher, "creationDate" -> article.creationDate.map(date => BSONDateTime(date.getMillis)), "updateDate" -> article.updateDate.map(date => BSONDateTime(date.getMillis))) } val form = Form( mapping( "id" -> optional(of[String] verifying pattern( """[a-fA-F0-9]{24}""".r, "constraint.objectId", "error.objectId")), "title" -> nonEmptyText, "content" -> text, "publisher" -> nonEmptyText, "creationDate" -> optional(of[Long]), "updateDate" -> optional(of[Long])) { (id, title, content, publisher, creationDate, updateDate) => Article( id.map(new BSONObjectID(_)), title, content, publisher, creationDate.map(new DateTime(_)), updateDate.map(new DateTime(_))) } { article => Some( (article.id.map(_.stringify), article.title, article.content, article.publisher, article.creationDate.map(_.getMillis), article.updateDate.map(_.getMillis))) }) }
scalastic/reactivemongo-demo-app
app/models/articles.scala
Scala
apache-2.0
2,360
package powercards.stages import powercards.{ActionCard, Item, Game, Stage, choices } import powercards.Functions.divide object ActionStage extends Stage { def play(game: Game): Stage = { if (game.active.actions > 0) { game.active.chooseOptionalOne(message = "Select an action card to play", items = game.active.hand.map(c => new Item(c.name, c.isInstanceOf[ActionCard]))) match { case choices.optional_one.NonSelectable => game.log("No action card to play. Skip to treasure stage") skip(game) case choices.optional_one.Skip => game.log("Skip to treasure stage") skip(game) case choices.optional_one.One(index) => game.active.actions -= 1 val (card, hand) = divide(game.active.hand, index) game.active.hand = hand game.active.played :+= card game.log(s"Playing $card") card.asInstanceOf[ActionCard].play(game) this } } else { game.log("No action point. Skip to treasure stage") skip(game) } } private def skip(game: Game): Stage = { game.active.actions = 0 TreasureStage } }
whence/powerlife
scala/powercards_oo/src/main/scala/powercards/stages/ActionStage.scala
Scala
mit
1,172
package com.calabs.dss.dataimport import java.util import org.json4s.JsonAST.{JArray, JInt, JString} import org.scalatest.FunSpec import scala.collection.mutable.{Map => MutableMap} import scala.io.Source import scala.util.{Failure, Success} /** * Created by Jordi Aranda * <[email protected]> * 21/11/14 */ class JSONDataResourceSpec extends FunSpec { import Config._ val resourceMapper = DataResourceMapper() describe("A JSON Data Resource extractor"){ it("should correctly extract metrics from a JSON data resource (resourceType=json)"){ val config = jsonResourceConfig.load(getClass.getResource("/json/file/example-file.ok.config").getPath) val mapping = resourceMapper.load(getClass.getResource("/json/file/example-file.ok.map").getPath) (config, mapping) match { case (Success(c), Success(m)) => { // How to test files that are loaded from a path property read from a file? This will be different between machines! // Overwrite data source path by now with one existing relative to resources folder val newConfig = DataResourceConfig(Map[String,Any](("source" -> getClass.getResource("/json/file/example-file.json").getPath), ("resourceType" -> ResourceType.JSON))) val jsonResource = JSONResource(newConfig, DataResourceMapping(m)) val documents = jsonResource.extractDocuments documents match { case Success(docs) => { val (vertices, edges) = (docs._1, docs._2) assert(vertices(0).isVertex) assert(vertices(0).props.get("metric1") == Some(JString("bar"))) assert(vertices(0).props.get("metric2") == Some(JInt(2))) assert(vertices(0).props.get("metric3") == Some(JArray(List(JInt(1),JInt(2),JInt(3))))) } case Failure(e) => fail(s"Some error occured while trying to extract documents from the JSON resource: ${e.getMessage}.") } } case (Failure(c), Success(m)) => { fail(s"Some error occurred while trying to load the JSON resource config file: ${c.getMessage}.") } case (Success(c), Failure(m)) => { fail(s"Some error occurred while trying to load the JSON resource mapping file: ${m.getMessage}.") } case _ => { fail("Neither the JSON resource config file nor the mapping file could be loaded.") } } } it("should correctly extract metrics from a JSON data resource (resourceType=jsonAPI)"){ val config = jsonApiResourceConfig.load(getClass.getResource("/json/api/example-api.ok.config").getPath) val mapping = resourceMapper.load(getClass.getResource("/json/api/example-api.ok.map").getPath) (config, mapping) match { case (Success(c), Success(m)) => { val jsonResource = JSONAPIResource(DataResourceConfig(c), DataResourceMapping(m)) val documents = jsonResource.extractDocuments documents match { case Success(docs) => { val (vertices, edges) = (docs._1, docs._2) assert(vertices(0).isVertex) assert(vertices(0).props.get("login") == Some(JString("jarandaf"))) assert(vertices(0).props.get("url") == Some(JString("https://api.github.com/users/jarandaf"))) assert(vertices(0).props.get("email") == Some(JString("[email protected]"))) } case Failure(e) => fail(s"Some error occurred while trying to extract documents from the JSON resource: ${e.getMessage}.") } } case (Failure(c), Success(m)) => { fail(s"Some error occurred while trying to load the JSON resource config file: ${c.getMessage}.") } case (Success(c), Failure(m)) => { fail(s"Some error occurred while trying to load the JSON resource mapping file: ${m.getMessage}.") } case _ => { fail("Neither the JSON resource config file nor the mapping file could be loaded.") } } } it("should fail when trying to extract metrics from a JSON data resource (resourceType=json) with invalid config or mapping files"){ val config = jsonResourceConfig.load(getClass.getResource("/json/file/example-file.ko.config").getPath) val mapping = resourceMapper.load(getClass.getResource("/json/file/example-file.ko.map").getPath) (config, mapping) match { case (Success(c), Success(m)) => fail("Unexpected correct loading of config/mapping files: they are wrong!") case _ => assert(true) } } it("should fail when trying to extract metrics from a JSON data resource (resourceType=jsonAPI) with invalid config or mapping files"){ val config = jsonApiResourceConfig.load(getClass.getResource("/json/api/example-api.ko.config").getPath) val mapping = resourceMapper.load(getClass.getResource("/json/api/example-api.ko.map").getPath) (config, mapping) match { case (Success(c), Success(m)) => fail("Unexpected correct loading of config/mapping files: they are wrong!") case _ => assert(true) } } } }
CA-Labs/dss-data-import
src/test/scala/com/calabs/dss/dataimport/JSONDataResourceSpec.scala
Scala
mit
5,144
/* * The MIT License * * Copyright (c) 2017 Fulcrum Genomics LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.fulcrumgenomics.basecalling import java.nio.file.Files import com.fulcrumgenomics.illumina.{Sample, SampleSheet} import com.fulcrumgenomics.testing.{ErrorLogLevel, UnitSpec} import com.fulcrumgenomics.util.Io class ExtractBasecallingParamsForPicardTest extends UnitSpec with ErrorLogLevel { private val outputDir = Files.createTempDirectory("ExtractBasecallingParamsTest") "BasecallingParams.bamFileFrom" should "create a path to a BAM file with a single-indexed sample" in { val bam = BasecallingParams.bamFileFrom( output = outputDir, sample = new Sample(sampleOrdinal=0, sampleId="sampleId", sampleName="sampleName", libraryId="libraryId", i7IndexBases=Some("GATTACA")), lane = 1 ) bam.toString shouldBe outputDir.resolve("sampleName.GATTACA.1.bam").toString } "BasecallingParams.unmatchedBamFileFrom" should "create a path to an unmatched BAM" in { val bam = BasecallingParams.unmatchedBamFileFrom(output = outputDir, lane = 1) bam.toString shouldBe outputDir.resolve("unmatched.1.bam").toString } it should "create a path to a BAM file without a library identifier" in { val bam = BasecallingParams.bamFileFrom( output = outputDir, sample = new Sample(sampleOrdinal=0, sampleId="sampleId", sampleName="sampleName", libraryId="libraryId", i7IndexBases=Some("GATTACA"), i5IndexBases=Some("ACATTAG")), lane = 2 ) bam.toString shouldBe outputDir.resolve("sampleName.GATTACAACATTAG.2.bam").toString } private val singleIndexSampleSheet = """[Data],,,,,,,,, |Sample_ID,Sample_Name,Sample_Plate,Sample_Well,R1_Barcode_Bases,R2_Barcode_Bases,I7_Index_ID,index,Sample_Project,Description |20000101-EXPID-1,Sample_Name_1,,,GATTACAG,GATTACAGA,I7_1,GATTACAACGT,Sample_Project_1,Description_1 |20000101-EXPID-2,Sample_Name_2,,,GATTACAG,GATTACAGA,I7_2,GATTACAACGT,Sample_Project_2,Description_2 |20000101-EXPID-3,Sample_Name_3,,,GATTACAG,GATTACAGA,I7_3,GATTACAACGT,Sample_Project_3,Description_3 |20000101-EXPID-4,Sample_Name_4,,,GATTACAG,GATTACAGA,I7_4,GATTACAACGT,Sample_Project_4,Description_4 |20000101-EXPID-5,Sample_Name_5,,,GATTACAG,GATTACAGA,I7_5,GATTACAACGT,Sample_Project_5,Description_5 |20000101-EXPID-6,Sample_Name_6,,,GATTACAG,GATTACAGA,I7_6,GATTACAACGT,Sample_Project_6,Description_6 |20000101-EXPID-7,Sample_Name_7,,,GATTACAG,GATTACAGA,I7_7,GATTACAACGT,Sample_Project_7,Description_7 |20000101-EXPID-8,Sample_Name_8,,,GATTACAG,GATTACAGA,I7_8,GATTACAACGT,Sample_Project_8,Description_8 |20000101-EXPID-9,Sample_Name_9,,,GATTACAG,GATTACAGA,I7_9,GATTACAACGT,Sample_Project_9,Description_9 |20000101-EXPID-10,Sample_Name_10,,,GATTACAG,GATTACAGA,I7_10,GATTACAACGT,Sample_Project_10,Description_10 |20000101-EXPID-11,Sample_Name_11,,,GATTACAG,GATTACAGA,I7_11,GATTACAACGT,Sample_Project_11,Description_11 |20000101-EXPID-12,Sample_Name_12,,,GATTACAG,GATTACAGA,I7_12,GATTACAACGT,Sample_Project_12,Description_12""" .stripMargin.split("\\n").toIndexedSeq private val dualIndexedSampleSheet = """[Data],,,,,,,,, |Sample_ID,Sample_Name,Sample_Plate,Sample_Well,R1_Barcode_Bases,R2_Barcode_Bases,I7_Index_ID,index,I5_Index_ID,index2,Sample_Project,Description |20000101-EXPID-1,Sample_Name_1,,,GATTACAG,GATTACAGA,I7_1,GATTACAACGT,I5_1,GATTACA,Sample_Project_1,Description_1 |20000101-EXPID-2,Sample_Name_2,,,GATTACAG,GATTACAGA,I7_2,GATTACAACGT,I5_2,GATTACA,Sample_Project_2,Description_2 |20000101-EXPID-3,Sample_Name_3,,,GATTACAG,GATTACAGA,I7_3,GATTACAACGT,I5_3,GATTACA,Sample_Project_3,Description_3 |20000101-EXPID-4,Sample_Name_4,,,GATTACAG,GATTACAGA,I7_4,GATTACAACGT,I5_4,GATTACA,Sample_Project_4,Description_4 |20000101-EXPID-5,Sample_Name_5,,,GATTACAG,GATTACAGA,I7_5,GATTACAACGT,I5_5,GATTACA,Sample_Project_5,Description_5 |20000101-EXPID-6,Sample_Name_6,,,GATTACAG,GATTACAGA,I7_6,GATTACAACGT,I5_6,GATTACA,Sample_Project_6,Description_6 |20000101-EXPID-7,Sample_Name_7,,,GATTACAG,GATTACAGA,I7_7,GATTACAACGT,I5_7,GATTACA,Sample_Project_7,Description_7 |20000101-EXPID-8,Sample_Name_8,,,GATTACAG,GATTACAGA,I7_8,GATTACAACGT,I5_8,GATTACA,Sample_Project_8,Description_8 |20000101-EXPID-9,Sample_Name_9,,,GATTACAG,GATTACAGA,I7_9,GATTACAACGT,I5_9,GATTACA,Sample_Project_9,Description_9 |20000101-EXPID-10,Sample_Name_10,,,GATTACAG,GATTACAGA,I7_10,GATTACAACGT,I5_10,GATTACA,Sample_Project_10,Description_10 |20000101-EXPID-11,Sample_Name_11,,,GATTACAG,GATTACAGA,I7_11,GATTACAACGT,I5_11,GATTACA,Sample_Project_11,Description_11 |20000101-EXPID-12,Sample_Name_12,,,GATTACAG,GATTACAGA,I7_12,GATTACAACGT,I5_12,GATTACA,Sample_Project_12,Description_12""" .stripMargin.split("\\n").toIndexedSeq private val dualIndexedSampleSheetNoProjectOrDescription = """[Data],,,,,,,,, |Sample_ID,Sample_Name,Sample_Plate,Sample_Well,R1_Barcode_Bases,R2_Barcode_Bases,I7_Index_ID,index,I5_Index_ID,index2,Sample_Project,Description |20000101-EXPID-1,Sample_Name_1,,,GATTACAG,GATTACAGA,I7_1,GATTACAACGT,I5_1,GATTACA,,""" .stripMargin.split("\\n").toIndexedSeq private val duplicateNamesSampleSheet = """[Data],,,,,,,,, |Sample_ID,Sample_Name,Sample_Plate,Sample_Well,R1_Barcode_Bases,R2_Barcode_Bases,I7_Index_ID,index,Sample_Project,Description |20000101-EXPID-1,Sample_Name_1,,,GATTACAG,GATTACAGA,I7_1,GATTACAACGT,Sample_Project_1,Description_1 |20000101-EXPID-2,Sample_Name_1,,,GATTACAG,GATTACAGA,I7_2,GATTACAACGT,Sample_Project_2,Description_2 |20000101-EXPID-3,Sample_Name_3,,,GATTACAG,GATTACAGA,I7_3,GATTACAACGT,Sample_Project_3,Description_3 |20000101-EXPID-4,Sample_Name_4,,,GATTACAG,GATTACAGA,I7_4,GATTACAACGT,Sample_Project_4,Description_4 |20000101-EXPID-5,Sample_Name_5,,,GATTACAG,GATTACAGA,I7_5,GATTACAACGT,Sample_Project_5,Description_5 |20000101-EXPID-6,Sample_Name_6,,,GATTACAG,GATTACAGA,I7_6,GATTACAACGT,Sample_Project_6,Description_6 |20000101-EXPID-7,Sample_Name_7,,,GATTACAG,GATTACAGA,I7_7,GATTACAACGT,Sample_Project_7,Description_7 |20000101-EXPID-8,Sample_Name_8,,,GATTACAG,GATTACAGA,I7_8,GATTACAACGT,Sample_Project_8,Description_8 |20000101-EXPID-9,Sample_Name_9,,,GATTACAG,GATTACAGA,I7_9,GATTACAACGT,Sample_Project_9,Description_9 |20000101-EXPID-10,Sample_Name_10,,,GATTACAG,GATTACAGA,I7_10,GATTACAACGT,Sample_Project_10,Description_10 |20000101-EXPID-11,Sample_Name_11,,,GATTACAG,GATTACAGA,I7_11,GATTACAACGT,Sample_Project_11,Description_11 |20000101-EXPID-12,Sample_Name_12,,,GATTACAG,GATTACAGA,I7_12,GATTACAACGT,Sample_Project_12,Description_12""" .stripMargin.split("\\n").toIndexedSeq "BasecallingParams.from" should "extract params from a single-index sequencing run" in { val sampleSheet = SampleSheet(singleIndexSampleSheet.iterator, lane=None) val params = BasecallingParams.from(sampleSheet=sampleSheet, lanes=Seq(1), output=outputDir) params should have size 1 val param = params.head param.barcodeFile shouldBe BasecallingParams.barcodeFileFrom(output=outputDir, lane=1) param.libraryParamsFile shouldBe BasecallingParams.libraryParamsFileFrom(output=outputDir, lane=1) param.bams.head shouldBe BasecallingParams.bamFileFrom(output=outputDir, sample=sampleSheet.head, lane=1) // Check the header, first sample, and last line (last sample) val barcodeParams = Io.readLines(param.barcodeFile).toSeq barcodeParams.head shouldBe "barcode_sequence_1\\tbarcode_name\\tlibrary_name" barcodeParams.drop(1).head shouldBe "GATTACAACGT\\tGATTACAACGT\\t20000101-EXPID-1" barcodeParams.last shouldBe "GATTACAACGT\\tGATTACAACGT\\t20000101-EXPID-12" // Check the header, first sample, and last line (unmatched sample) val libraryParams = Io.readLines(param.libraryParamsFile).toSeq libraryParams.head shouldBe "BARCODE_1\\tOUTPUT\\tSAMPLE_ALIAS\\tLIBRARY_NAME\\tDS" libraryParams.drop(1).head shouldBe s"GATTACAACGT\\t${outputDir.resolve("Sample_Name_1.GATTACAACGT.1.bam")}\\tSample_Name_1\\t20000101-EXPID-1\\tDescription_1" libraryParams.last shouldBe s"N\\t${outputDir.resolve("unmatched.1.bam")}\\tunmatched\\tunmatched\\tunmatched" } it should "extract params for multiple lanes from a sequencing run" in { val sampleSheet = SampleSheet(singleIndexSampleSheet.iterator, lane=None) val params = BasecallingParams.from(sampleSheet=sampleSheet, lanes=Seq(1, 2, 4), output=outputDir) params should have size 3 val param = params.last param.barcodeFile shouldBe BasecallingParams.barcodeFileFrom(output=outputDir, lane=4) param.libraryParamsFile shouldBe BasecallingParams.libraryParamsFileFrom(output=outputDir, lane=4) param.bams.head shouldBe BasecallingParams.bamFileFrom(output=outputDir, sample=sampleSheet.head, lane=4) // Check the header, first sample, and last line (last sample) val barcodeParams = Io.readLines(param.barcodeFile).toSeq barcodeParams.head shouldBe "barcode_sequence_1\\tbarcode_name\\tlibrary_name" barcodeParams.drop(1).head shouldBe "GATTACAACGT\\tGATTACAACGT\\t20000101-EXPID-1" barcodeParams.last shouldBe "GATTACAACGT\\tGATTACAACGT\\t20000101-EXPID-12" // Check the header, first sample, and last line (unmatched sample) val libraryParams = Io.readLines(param.libraryParamsFile).toSeq libraryParams.head shouldBe "BARCODE_1\\tOUTPUT\\tSAMPLE_ALIAS\\tLIBRARY_NAME\\tDS" libraryParams.drop(1).head shouldBe s"GATTACAACGT\\t${outputDir.resolve("Sample_Name_1.GATTACAACGT.4.bam")}\\tSample_Name_1\\t20000101-EXPID-1\\tDescription_1" libraryParams.last shouldBe s"N\\t${outputDir.resolve("unmatched.4.bam")}\\tunmatched\\tunmatched\\tunmatched" } it should "extract params from a dual-indexed sequencing run" in { val sampleSheet = SampleSheet(dualIndexedSampleSheet.iterator, lane=None) val params = BasecallingParams.from(sampleSheet=sampleSheet, lanes=Seq(1), output=outputDir) params should have size 1 val param = params.head param.barcodeFile shouldBe BasecallingParams.barcodeFileFrom(output=outputDir, lane=1) param.libraryParamsFile shouldBe BasecallingParams.libraryParamsFileFrom(output=outputDir, lane=1) param.bams.head shouldBe BasecallingParams.bamFileFrom(output=outputDir, sample=sampleSheet.head, lane=1) // Check the header, first sample, and last line (last sample) val barcodeParams = Io.readLines(param.barcodeFile).toSeq barcodeParams.head shouldBe "barcode_sequence_1\\tbarcode_sequence_2\\tbarcode_name\\tlibrary_name" barcodeParams.drop(1).head shouldBe "GATTACAACGT\\tGATTACA\\tGATTACAACGTGATTACA\\t20000101-EXPID-1" barcodeParams.last shouldBe "GATTACAACGT\\tGATTACA\\tGATTACAACGTGATTACA\\t20000101-EXPID-12" // Check the header, first sample, and last line (unmatched sample) val libraryParams = Io.readLines(param.libraryParamsFile).toSeq libraryParams.head shouldBe "BARCODE_1\\tBARCODE_2\\tOUTPUT\\tSAMPLE_ALIAS\\tLIBRARY_NAME\\tDS" libraryParams.drop(1).head shouldBe s"GATTACAACGT\\tGATTACA\\t${outputDir.resolve("Sample_Name_1.GATTACAACGTGATTACA.1.bam")}\\tSample_Name_1\\t20000101-EXPID-1\\tDescription_1" libraryParams.last shouldBe s"N\\tN\\t${outputDir.resolve("unmatched.1.bam")}\\tunmatched\\tunmatched\\tunmatched" } it should "exclude the description if the project and description are not defined on all samples" in { val sampleSheet = SampleSheet(dualIndexedSampleSheetNoProjectOrDescription.iterator, lane=None) val params = BasecallingParams.from(sampleSheet=sampleSheet, lanes=Seq(1), output=outputDir) params should have size 1 val param = params.head param.barcodeFile shouldBe BasecallingParams.barcodeFileFrom(output=outputDir, lane=1) param.libraryParamsFile shouldBe BasecallingParams.libraryParamsFileFrom(output=outputDir, lane=1) param.bams.head shouldBe BasecallingParams.bamFileFrom(output=outputDir, sample=sampleSheet.head, lane=1) // Check the header, first sample, and last line (last sample) val barcodeParams = Io.readLines(param.barcodeFile).toSeq barcodeParams.head shouldBe "barcode_sequence_1\\tbarcode_sequence_2\\tbarcode_name\\tlibrary_name" barcodeParams.drop(1).head shouldBe "GATTACAACGT\\tGATTACA\\tGATTACAACGTGATTACA\\t20000101-EXPID-1" barcodeParams.last shouldBe "GATTACAACGT\\tGATTACA\\tGATTACAACGTGATTACA\\t20000101-EXPID-1" // Check the header, first sample, and last line (unmatched sample) val libraryParams = Io.readLines(param.libraryParamsFile).toSeq libraryParams.head shouldBe "BARCODE_1\\tBARCODE_2\\tOUTPUT\\tSAMPLE_ALIAS\\tLIBRARY_NAME" libraryParams.drop(1).head shouldBe s"GATTACAACGT\\tGATTACA\\t${outputDir.resolve("Sample_Name_1.GATTACAACGTGATTACA.1.bam")}\\tSample_Name_1\\t20000101-EXPID-1" libraryParams.last shouldBe s"N\\tN\\t${outputDir.resolve("unmatched.1.bam")}\\tunmatched\\tunmatched" } "ExtractBasecallingParams" should "run end-to-end" in { val sampleSheet = makeTempFile("SampleSheet", ".csv") Io.writeLines(sampleSheet, dualIndexedSampleSheet.toSeq) new ExtractBasecallingParamsForPicard(input=sampleSheet, output=outputDir, lanes=Seq(1)).execute() val barcodeFile = BasecallingParams.barcodeFileFrom(output=outputDir, lane=1) val libraryParamsFile = BasecallingParams.libraryParamsFileFrom(output=outputDir, lane=1) // Check the header, first sample, and last line (last sample) val barcodeParams = Io.readLines(barcodeFile).toSeq barcodeParams.head shouldBe "barcode_sequence_1\\tbarcode_sequence_2\\tbarcode_name\\tlibrary_name" barcodeParams.drop(1).head shouldBe "GATTACAACGT\\tGATTACA\\tGATTACAACGTGATTACA\\t20000101-EXPID-1" barcodeParams.last shouldBe "GATTACAACGT\\tGATTACA\\tGATTACAACGTGATTACA\\t20000101-EXPID-12" // Check the header, first sample, and last line (unmatched sample) val libraryParams = Io.readLines(libraryParamsFile).toSeq libraryParams.head shouldBe "BARCODE_1\\tBARCODE_2\\tOUTPUT\\tSAMPLE_ALIAS\\tLIBRARY_NAME\\tDS" libraryParams.drop(1).head shouldBe s"GATTACAACGT\\tGATTACA\\t${outputDir.resolve("Sample_Name_1.GATTACAACGTGATTACA.1.bam")}\\tSample_Name_1\\t20000101-EXPID-1\\tDescription_1" libraryParams.last shouldBe s"N\\tN\\t${outputDir.resolve("unmatched.1.bam")}\\tunmatched\\tunmatched\\tunmatched" } }
fulcrumgenomics/fgbio
src/test/scala/com/fulcrumgenomics/basecalling/ExtractBasecallingParamsForPicardTest.scala
Scala
mit
15,395
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fuberlin.wiwiss.silk.plugins.distance.tokenbased import de.fuberlin.wiwiss.silk.runtime.plugin.Plugin import java.util.regex.Pattern import de.fuberlin.wiwiss.silk.linkagerule.similarity.SimpleDistanceMeasure import de.fuberlin.wiwiss.silk.entity.Index import de.fuberlin.wiwiss.silk.plugins.distance.characterbased.{JaroWinklerDistance, JaroDistanceMetric, LevenshteinMetric} /** * <p> * Similarity measure for strings. Strings are split into tokens and a similarity * measure is applied to compare all tokens with each other. The comparison results * are filtered such that no token appears in more than one comparison. The * individual token comparisons are aggregated by a technique similar to * the jaccard set similiarty in the following way: * <p> * * <p> * The sets to be compared are the token sets obtained from each string. * </p> * * <p> * The analogue figure of the set intersection size in the jaccard similarity is the * sum over all similarities, i.e intersectionScore = Sum[over all matches](score) * The analogue figure of the set union size in the jaccard similarity is the sum of * unmatched tokens in both token sets, plus the sum of the similarity score that was NOT attained * for each matched token, i.e. unionScore = |unmatchedA| + |unmatchedB| + Sum[over all matches](score + 2*(1-score)) * The final score is computed as intersectionScore / unionScore * </p> * * <p> * The token weights affect the score computation as follows:<br> * <ul> * <li>Matched tokens:</li> * <ul> * <li>intersectionScore += token1_weight * token2_weight * match_score </li> * <li>unionScore += token1_weight * token2_weight * match_score + (1 - match_score) * (token1_weight^2 + token2_weight^2) </li> * </ul> * <li>Unmatched tokens: unionScore += token_weight^2</li> * </ul> * </p> * * <p> * The parameter useIncrementalIdfWeights allows the user to activate collecting token counts and using them for calculating the * IDF token weight. If this feature is active, the parameters nonStopwordWeight and stopwordWeight are used as upper * bounds for the token weights * </p> * * <p> * The parameter matchThreshold is used to disallow token matches below a certain threshold. * </p> * * <p> * Ordering of tokens in both input strings can also be taken into account. The parameter orderingImpact defines the * impact ordering has on the final score. If orderingImpact > 0.0, the positions of the matched tokens are compared * using kendall's tau, which yields 1 for identical ordering and 0 for reverse ordering. * The final score is computed as score * (1 - orderingImpact * (1 - tau)), which means that the maximum score for * input strings with tokens in exactly reverse order is 1 - orderingImpact * </p> * * <p> * If adjustByTokenLength is set to true, each token weight is multiplied by its length relative to the length of the * longest token in the input string, i.e, token_weight = token_weight * token_length / max_token_length_in_input_string. * <p> * * @author Florian Kleedorfer, Research Studios Austria */ @Plugin( id = "tokenwiseDistance", categories = Array("Tokenbased"), label = "Token-wise Distance", description = "Token-wise string distance using the specified metric" ) case class TokenwiseStringDistance( ignoreCase: Boolean = true, metricName: String = "levenshtein", splitRegex: String = "[\\s\\d\\p{Punct}]+", stopwords: String = "", stopwordWeight: Double = 0.01, nonStopwordWeight: Double = 0.1, useIncrementalIdfWeights:Boolean = false, matchThreshold: Double = 0.0, orderingImpact: Double = 0.0, adjustByTokenLength: Boolean = false ) extends SimpleDistanceMeasure { require(stopwordWeight >= 0.0 && stopwordWeight <= 1.0, "stopwordWeight must be in [0,1]") require(nonStopwordWeight >= 0.0 && nonStopwordWeight <= 1.0, "nonStopwordWeight must be in [0,1]") require(matchThreshold >= 0.0 && matchThreshold <= 1.0, "matchThreshold must be in [0,1]") require(orderingImpact >= 0.0 && orderingImpact <= 1.0, "orderingImpact must be in [0,1]") private val splitPattern = Pattern.compile(splitRegex) private val metric = metricName match { case "levenshtein" => new LevenshteinMetric() case "jaro" => new JaroDistanceMetric() case "jaroWinkler" => new JaroWinklerDistance() case _ => throw new IllegalArgumentException("unknown value '" + metricName +"' for parameter 'metricName', must be one of ['levenshtein', 'jaro', 'jaroWinkler')"); } private val documentFrequencies = scala.collection.mutable.Map[String, Int]() private var documentCount = 0 private val stopwordsSet = stopwords.split("[,\\s]+").map(x => if (ignoreCase) x.toLowerCase else x).toSet /** * Calculates a jaccard-like aggregation of string similarities of tokens. Order of tokens is not taken into account. */ def tokenize(string1: String): Array[String] = { string1.split(splitRegex).map(x => if (ignoreCase) x.toLowerCase else x).filter(_.length > 0).toArray } override def evaluate(string1: String, string2: String, limit : Double) : Double = { var debug = false // generate array of tokens val tokens1 = tokenize(string1) val tokens2 = tokenize(string2) if (debug) println("string1: " + string1 +", words1=" + tokens1.mkString("'","','","'")) if (debug) println("string2: " + string2 +", words2=" + tokens2.mkString("'","','","'")) if (tokens1.isEmpty || tokens2.isEmpty) return 1.0 // store weight for each token in array var weights1 = (for (token <- tokens1) yield getWeight(token)).toArray var weights2 = (for (token <- tokens2) yield getWeight(token)).toArray if (adjustByTokenLength) { weights1 = adjustWeightsByTokenLengths(weights1, tokens1) weights2 = adjustWeightsByTokenLengths(weights2, tokens2) } //evaluate metric for all pairs of tokens and create triple (score, tokenIndex1, tokenIndex2) val scores = for (ind1 <- 0 to tokens1.size - 1; ind2 <- 0 to tokens2.size - 1; score = 1.0 - metric.evaluate(tokens1(ind1), tokens2(ind2), limit) if score >= matchThreshold) yield { (score, ind1, ind2) } //now sort by score val sortedScores= scores.sortBy(t => -t._1) if (debug) println ("sorted scores: " + sortedScores.mkString(",")) // val matchedTokens1 = Array.fill(tokens1.size)(false) val matchedTokens2 = Array.fill(tokens2.size)(false) var matchedCount1 = 0 var matchedCount2 = 0 var lastScore = 1.0 //optimized version of the match calculation: // select best matches, only one match for each token val alignmentScores = for (triple <- sortedScores if matchedCount1 < tokens1.size && matchedCount2 < tokens2.size && lastScore > 0.0 && matchedTokens1(triple._2) == false && matchedTokens2(triple._3) == false) yield { lastScore = triple._1 matchedTokens1(triple._2) = true matchedTokens2(triple._3) = true matchedCount1 += 1 matchedCount2 += 1 triple } ///// original computation of alignmentScores, slightly slower with longer strings (~10-15% for 2 strings with about 25 words) // //now select only the highest score for each word // val alignmentScores = sortedScores.foldLeft[Seq[Triple[Double,Int,Int]]](Seq.empty)((triples, triple) => { // //check if we can add the current triple or not // if (triples.size == 0) { // Seq(triple) // } else if (triples.exists(x => x._2 == triple._2 || x._3 == triple._3)) { // //one of the words in the current comparison has already been selected, so we can't add it to the result // triples // } else { // //none of the words in the current comparison has been matched so far, add it if it has score > 0 // if (triple._1 > 0.0) { // triple +: triples // } else { // triples // } // } // }) if (debug) println("alignmentScores=" + alignmentScores.map(x => (x._1, tokens1(x._2), tokens2(x._3) )).mkString("\n")) //calculate score for each match: weight_of_word1 * weight_of_word2 * score, and sum //in the jaccard-like aggregation this is the 'intersection' of the two token sets var intersectionScore = 0.0 //calculate score not reached for each match: weight_of_word1 * weight_of_word2 * (2 - score)[= 1+(1-score)], and sum //in the jaccard-like aggregation this is the 'union' of the two token sets, where they are matched var unionScoreForMatched = 0.0 for (alignmentScore <- alignmentScores) { val weight1 = weights1(alignmentScore._2) val weight2 = weights2(alignmentScore._3) val tmpIntersectionScore = weight1 * weight2 * alignmentScore._1 //~jaccard intersection intersectionScore += tmpIntersectionScore unionScoreForMatched += tmpIntersectionScore + (math.pow(weight1,2) + math.pow(weight2,2)) * ( 1.0 - alignmentScore._1 ) //~ jaccard union wrt matches } ////// original calculation of intersectionScore and unionScoreForMatched // //calculate score for each match: weight_of_word1 * weight_of_word2 * score, and sum // //in the jaccard-like aggregation this is the 'intersection' of the two token sets // val intersectionScore = alignmentScores.foldLeft[Double](0)((sum,t) => sum + getWeight(words1(t._2)) * getWeight(words2(t._3)) * t._1) //~jaccard intersection // //now, calculate score not reached for each match: weight_of_word1 * weight_of_word2 * (2 - score)[= 1+(1-score)], and sum // //in the jaccard-like aggregation this is the 'union' of the two token sets, where they are matched // val unionScoreForMatched = alignmentScores.foldLeft[Double](0)((sum,t) => sum + getWeight(words1(t._2)) * getWeight(words2(t._3)) * t._1 + (math.pow(getWeight(words1(t._2)),2) + math.pow(getWeight(words2(t._3)),2)) * ( 1.0 - t._1)) //~ jaccard union wrt matches //now calculate a penalty score for the words that weren't matched //in the jaccard-like aggregation, this is the 'union' of the two token sets where they are not matched val unmatchedIndices1 = matchedTokens1.zipWithIndex.filter(!_._1).map(_._2) val unmatchedIndices2 = matchedTokens2.zipWithIndex.filter(!_._1).map(_._2) val unionScoreForUnmatched = unmatchedIndices1.map(x => math.pow(weights1(x),2)).sum + unmatchedIndices2.map(x => math.pow(weights2(x),2)).sum // ~jaccard union wrt unmatched words if (debug) println("matchedTokens1 = " + matchedTokens1.mkString(",")) if (debug) println("unmatchedIndices1 = " + unmatchedIndices1.mkString(",")) ///// original calculation of unionScoreForUnmatched // val unmatchedWords1 = words1.indices.diff(alignmentScores.map[Int,Seq[Int]](x => x._2)).map(words1(_)) // if (debug) println("unmatched1: " + unmatchedWords1.mkString("\n")) // val unmatchedWords2 = words2.indices.diff(alignmentScores.map[Int,Seq[Int]](x => x._3)).map(words2(_)) // if (debug) println("unmatched2: " + unmatchedWords2.mkString("\n")) //val unionScoreForUnmatched = unmatchedWords1.map(x => math.pow(getWeight(x),2)).sum + unmatchedWords2.map(x => math.pow(getWeight(x),2)).sum // ~jaccard union wrt unmatched words if (debug) println("intersectionScore=" + intersectionScore) if (debug) println("unionScoreForMatched=" + unionScoreForMatched) if (debug) println("unionScoreForUnmatched=" + unionScoreForUnmatched) val unionScore = unionScoreForUnmatched + unionScoreForMatched //note: the classic computation of the union score, following the scheme |A| + |B| - |A intersect B| //isn't applicable when tokens have individual weights. The error thus introduced for each token pair would be // sim(t1,t2) * (w(t1) - w(t2))^2 // [w(tx) being the weight of token x, and sim(x,y) the similarity score for tokens x and y] //i.e. the greater the difference between w(t1) and w(t2), and the higher the similiarty, the greater the error //this would be the classic calculation: //val unionScore = weights1.map(math.pow(_,2)).sum + weights2.map(math.pow(_,2)).sum - intersectionScore; if (debug) println("unionScore=" + unionScore) if (debug) println(alignmentScores.mkString("\n")) val score = if (unionScore == 0.0){ 1.0 } else { intersectionScore / unionScore } if (debug) println("score=" + score) if (orderingImpact > 0.0 && alignmentScores.size > 1) { val matchIndices1 = alignmentScores.map(_._2).zipWithIndex.sortBy(x => -x._1).map(_._2) val matchIndices2 = alignmentScores.map(_._3).zipWithIndex.sortBy(x => -x._1).map(_._2) if (debug) println("matchIndices1=" + matchIndices1.mkString(",")) if (debug) println("matchIndices2=" + matchIndices2.mkString(",")) val tau = kendallsTau(matchIndices1, matchIndices2) if (debug) println("tau=" + tau) val scoreWithOrdering = score * (1 - orderingImpact * ( 1 - tau)) if (debug) println("scoreWithOrdering=" + scoreWithOrdering) 1.0 - scoreWithOrdering } else { 1.0 - score } } def adjustWeightsByTokenLengths(weights: Array[Double], tokens: Array[String]): Array[Double] = { val tokenLengths = tokens.map(_.length) val totalLength = tokenLengths.max val relativeLengths = tokenLengths.map(x => x.toDouble / totalLength.toDouble) weights.zip(relativeLengths).map(x => x._1 * x._2) } /** * Returns the weight associated with a token. * TODO: if there were a way to get useful IDF values for all tokens that can be expected, * this method should return the respective IDF value. */ def getWeight(token: String): Double = { val fixedWeight = getFixedWeight(token) if (!useIncrementalIdfWeights) { fixedWeight } else { val docFreq = documentFrequencies.getOrElse(token,0) if (docFreq == 0) { fixedWeight } else { val weight = math.log(documentCount/docFreq.toDouble) math.min(fixedWeight,weight) } } } def getFixedWeight(token: String):Double = { if (stopwordsSet(token)){ stopwordWeight } else { nonStopwordWeight } } /** * Vanilla implementation of kendall's tau with complexity O(n^2) */ def kendallsTau(seq1: Seq[Int], seq2: Seq[Int]): Double = { require(seq1.size == seq2.size, "for calculating kendall's tau, the sequences must be of equal size") if (seq1.size == 1) return 1.0 val arr1 = seq1.toArray val arr2 = seq2.toArray val numerator = (for (i <- 0 to arr1.size -1 ; j <- 0 to i-1) yield { if (math.signum(arr1(i) - arr1(j)) == math.signum(arr2(i) - arr2(j))){ 1.0 } else { 0.0 } }).sum numerator / (0.5 * (arr1.size * (arr1.size -1))) } /** * Very simple indexing function that requires at least one common token in strings for them to * be compared */ override def indexValue(value: String, limit: Double): Index = { val tokens = tokenize(value) if (tokens.isEmpty) { Index.empty } else { if (useIncrementalIdfWeights){ documentCount += 1 for (token <- tokens.distinct) { documentFrequencies.put(token, documentFrequencies.getOrElse(token,0) + 1) } } //Set(tokens.map(_.hashCode % blockCounts.head).toSeq) val tokenIndexes = for (token <- tokens.distinct) yield metric.indexValue(token, limit) tokenIndexes.reduce(_ merge _) } } }
fusepoolP3/p3-silk
silk-core/src/main/scala/de/fuberlin/wiwiss/silk/plugins/distance/tokenbased/TokenwiseStringDistance.scala
Scala
apache-2.0
16,112
package library.x { class X { class Foo implicit val foo = new Foo } } package library { package object x extends X } package app { import library.x._ object App { implicitly[Foo] } }
felixmulder/scala
test/pending/pos/t6225.scala
Scala
bsd-3-clause
200
case class Parser(ctx: Context) extends BasicSupport
dotty-staging/dotty
tests/pos/i10634/AParser.scala
Scala
apache-2.0
54
package org.mitre.jcarafe.util import org.mitre.jcarafe.lexer._ //import org.mitre.jcarafe.tokenizer._ import GenTokerConstants._ import java.io._ object SeparateDocs { def main(args: Array[String]) = { if (args.length == 3) { var cnt = 0 val dir = new File(args(0)) val tg = args(2) val rr = ("<" + tg + " ").r val odirPath = args(1) dir.listFiles foreach { f => if (f.isFile) { val sr = new java.io.FileInputStream(f) var os = new java.io.OutputStreamWriter(new java.io.BufferedOutputStream(new java.io.FileOutputStream(new java.io.File(odirPath + f.getName + ".doc-" + cnt.toString))), "UTF-8") val parser = new GenToker(sr) var c = true while (c) { val t: org.mitre.jcarafe.lexer.Token = parser.getNextToken() t.kind match { case EOF => c = false case TAGSTART => val ss = t.image if (rr.findFirstIn(ss).isDefined) { os.close cnt += 1 os = new java.io.OutputStreamWriter(new java.io.BufferedOutputStream(new java.io.FileOutputStream(new java.io.File(odirPath + f.getName + ".doc-" + cnt.toString))), "UTF-8") } case TAGEND => case _ => os.write(t.image) } } os.close } } } else println("usage: java -cp jcarafe...jar org.mitre.jcarafe.util.StripTags <input file> <output file>") } }
wellner/jcarafe
jcarafe-core/src/main/scala/org/mitre/jcarafe/util/SeparateDocs.scala
Scala
bsd-3-clause
1,569
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.ml.tuning import com.github.fommil.netlib.F2jBLAS import org.apache.spark.Logging import org.apache.spark.annotation.Experimental import org.apache.spark.ml._ import org.apache.spark.ml.evaluation.Evaluator import org.apache.spark.ml.param._ import org.apache.spark.ml.util.Identifiable import org.apache.spark.mllib.util.MLUtils import org.apache.spark.sql.DataFrame import org.apache.spark.sql.types.StructType /** * Params for [[CrossValidator]] and [[CrossValidatorModel]]. */ private[ml] trait CrossValidatorParams extends ValidatorParams { /** * Param for number of folds for cross validation. Must be >= 2. * Param用于交叉验证的折叠数。 必须> = 2 * Default: 3 * @group param */ val numFolds: IntParam = new IntParam(this, "numFolds", "number of folds for cross validation (>= 2)", ParamValidators.gtEq(2)) /** @group getParam */ def getNumFolds: Int = $(numFolds) setDefault(numFolds -> 3) } /** * :: Experimental :: * K-fold cross validation. */ @Experimental class CrossValidator(override val uid: String) extends Estimator[CrossValidatorModel] with CrossValidatorParams with Logging { def this() = this(Identifiable.randomUID("cv")) private val f2jBLAS = new F2jBLAS /** @group setParam */ def setEstimator(value: Estimator[_]): this.type = set(estimator, value) /** @group setParam */ def setEstimatorParamMaps(value: Array[ParamMap]): this.type = set(estimatorParamMaps, value) /** @group setParam */ def setEvaluator(value: Evaluator): this.type = set(evaluator, value) /** @group setParam */ def setNumFolds(value: Int): this.type = set(numFolds, value) override def fit(dataset: DataFrame): CrossValidatorModel = { val schema = dataset.schema transformSchema(schema, logging = true) val sqlCtx = dataset.sqlContext val est = $(estimator) val eval = $(evaluator) val epm = $(estimatorParamMaps) val numModels = epm.length val metrics = new Array[Double](epm.length) val splits = MLUtils.kFold(dataset.rdd, $(numFolds), 0) splits.zipWithIndex.foreach { case ((training, validation), splitIndex) => val trainingDataset = sqlCtx.createDataFrame(training, schema).cache() val validationDataset = sqlCtx.createDataFrame(validation, schema).cache() // multi-model training logDebug(s"Train split $splitIndex with multiple sets of parameters.") val models = est.fit(trainingDataset, epm).asInstanceOf[Seq[Model[_]]] trainingDataset.unpersist() var i = 0 while (i < numModels) { // TODO: duplicate evaluator to take extra params from input val metric = eval.evaluate(models(i).transform(validationDataset, epm(i))) logDebug(s"Got metric $metric for model trained with ${epm(i)}.") metrics(i) += metric i += 1 } validationDataset.unpersist() } f2jBLAS.dscal(numModels, 1.0 / $(numFolds), metrics, 1) logInfo(s"Average cross-validation metrics: ${metrics.toSeq}") val (bestMetric, bestIndex) = if (eval.isLargerBetter) metrics.zipWithIndex.maxBy(_._1) else metrics.zipWithIndex.minBy(_._1) logInfo(s"Best set of parameters:\\n${epm(bestIndex)}") logInfo(s"Best cross-validation metric: $bestMetric.") val bestModel = est.fit(dataset, epm(bestIndex)).asInstanceOf[Model[_]] copyValues(new CrossValidatorModel(uid, bestModel, metrics).setParent(this)) } override def transformSchema(schema: StructType): StructType = { $(estimator).transformSchema(schema) } override def validateParams(): Unit = { super.validateParams() val est = $(estimator) for (paramMap <- $(estimatorParamMaps)) { est.copy(paramMap).validateParams() } } override def copy(extra: ParamMap): CrossValidator = { val copied = defaultCopy(extra).asInstanceOf[CrossValidator] if (copied.isDefined(estimator)) { copied.setEstimator(copied.getEstimator.copy(extra)) } if (copied.isDefined(evaluator)) { copied.setEvaluator(copied.getEvaluator.copy(extra)) } copied } } /** * :: Experimental :: * Model from k-fold cross validation. */ @Experimental class CrossValidatorModel private[ml] ( override val uid: String, val bestModel: Model[_], val avgMetrics: Array[Double]) extends Model[CrossValidatorModel] with CrossValidatorParams { override def validateParams(): Unit = { bestModel.validateParams() } override def transform(dataset: DataFrame): DataFrame = { transformSchema(dataset.schema, logging = true) bestModel.transform(dataset) } override def transformSchema(schema: StructType): StructType = { bestModel.transformSchema(schema) } override def copy(extra: ParamMap): CrossValidatorModel = { val copied = new CrossValidatorModel( uid, bestModel.copy(extra).asInstanceOf[Model[_]], avgMetrics.clone()) copyValues(copied, extra).setParent(parent) } }
tophua/spark1.52
mllib/src/main/scala/org/apache/spark/ml/tuning/CrossValidator.scala
Scala
apache-2.0
5,779
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.scala.migration import java.util import org.apache.flink.api.common.accumulators.IntCounter import org.apache.flink.api.common.functions.RichFlatMapFunction import org.apache.flink.api.common.state._ import org.apache.flink.api.common.typeinfo.{BasicTypeInfo, TypeInformation} import org.apache.flink.api.java.functions.KeySelector import org.apache.flink.api.java.tuple.Tuple2 import org.apache.flink.api.scala.createTypeInformation import org.apache.flink.api.scala.migration.CustomEnum.CustomEnum import org.apache.flink.configuration.Configuration import org.apache.flink.contrib.streaming.state.RocksDBStateBackend import org.apache.flink.runtime.state.memory.MemoryStateBackend import org.apache.flink.runtime.state.{FunctionInitializationContext, FunctionSnapshotContext, StateBackendLoader} import org.apache.flink.streaming.api.TimeCharacteristic import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment import org.apache.flink.streaming.api.functions.co.KeyedBroadcastProcessFunction import org.apache.flink.streaming.api.functions.sink.RichSinkFunction import org.apache.flink.streaming.api.functions.source.SourceFunction import org.apache.flink.streaming.api.watermark.Watermark import org.apache.flink.test.checkpointing.utils.SavepointMigrationTestBase import org.apache.flink.testutils.migration.MigrationVersion import org.apache.flink.util.Collector import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.{Assert, Ignore, Test} import scala.util.{Failure, Try} object StatefulJobWBroadcastStateMigrationITCase { @Parameterized.Parameters(name = "Migrate Savepoint / Backend: {0}") def parameters: util.Collection[(MigrationVersion, String)] = { util.Arrays.asList( (MigrationVersion.v1_5, StateBackendLoader.MEMORY_STATE_BACKEND_NAME), (MigrationVersion.v1_5, StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME), (MigrationVersion.v1_6, StateBackendLoader.MEMORY_STATE_BACKEND_NAME), (MigrationVersion.v1_6, StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME), (MigrationVersion.v1_7, StateBackendLoader.MEMORY_STATE_BACKEND_NAME), (MigrationVersion.v1_7, StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME), (MigrationVersion.v1_8, StateBackendLoader.MEMORY_STATE_BACKEND_NAME), (MigrationVersion.v1_8, StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME), (MigrationVersion.v1_9, StateBackendLoader.MEMORY_STATE_BACKEND_NAME), (MigrationVersion.v1_9, StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME)) } // TODO to generate savepoints for a specific Flink version / backend type, // TODO change these values accordingly, e.g. to generate for 1.3 with RocksDB, // TODO set as (MigrationVersion.v1_3, StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME) // TODO Note: You should generate the savepoint based on the release branch instead of the master. val GENERATE_SAVEPOINT_VER: MigrationVersion = MigrationVersion.v1_9 val GENERATE_SAVEPOINT_BACKEND_TYPE: String = StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME val NUM_ELEMENTS = 4 } /** * ITCase for migration Scala state types across different Flink versions. */ @RunWith(classOf[Parameterized]) class StatefulJobWBroadcastStateMigrationITCase( migrationVersionAndBackend: (MigrationVersion, String)) extends SavepointMigrationTestBase with Serializable { @Test @Ignore def testCreateSavepointWithBroadcastState(): Unit = { val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) StatefulJobWBroadcastStateMigrationITCase.GENERATE_SAVEPOINT_BACKEND_TYPE match { case StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME => env.setStateBackend(new RocksDBStateBackend(new MemoryStateBackend())) case StateBackendLoader.MEMORY_STATE_BACKEND_NAME => env.setStateBackend(new MemoryStateBackend()) case _ => throw new UnsupportedOperationException } lazy val firstBroadcastStateDesc = new MapStateDescriptor[Long, Long]( "broadcast-state-1", BasicTypeInfo.LONG_TYPE_INFO.asInstanceOf[TypeInformation[Long]], BasicTypeInfo.LONG_TYPE_INFO.asInstanceOf[TypeInformation[Long]]) lazy val secondBroadcastStateDesc = new MapStateDescriptor[String, String]( "broadcast-state-2", BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO) env.setStateBackend(new MemoryStateBackend) env.enableCheckpointing(500) env.setParallelism(4) env.setMaxParallelism(4) val stream = env .addSource( new CheckpointedSource(4)).setMaxParallelism(1).uid("checkpointedSource") .keyBy( new KeySelector[(Long, Long), Long] { override def getKey(value: (Long, Long)): Long = value._1 } ) .flatMap(new StatefulFlatMapper) .keyBy( new KeySelector[(Long, Long), Long] { override def getKey(value: (Long, Long)): Long = value._1 } ) val broadcastStream = env .addSource( new CheckpointedSource(4)).setMaxParallelism(1).uid("checkpointedBroadcastSource") .broadcast(firstBroadcastStateDesc, secondBroadcastStateDesc) stream .connect(broadcastStream) .process(new TestBroadcastProcessFunction) .addSink(new AccumulatorCountingSink) executeAndSavepoint( env, s"src/test/resources/stateful-scala-with-broadcast" + s"-udf-migration-itcase-flink" + s"${StatefulJobWBroadcastStateMigrationITCase.GENERATE_SAVEPOINT_VER}" + s"-${StatefulJobWBroadcastStateMigrationITCase.GENERATE_SAVEPOINT_BACKEND_TYPE}-savepoint", new Tuple2( AccumulatorCountingSink.NUM_ELEMENTS_ACCUMULATOR, StatefulJobWBroadcastStateMigrationITCase.NUM_ELEMENTS ) ) } @Test def testRestoreSavepointWithBroadcast(): Unit = { val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) migrationVersionAndBackend._2 match { case StateBackendLoader.ROCKSDB_STATE_BACKEND_NAME => env.setStateBackend(new RocksDBStateBackend(new MemoryStateBackend())) case StateBackendLoader.MEMORY_STATE_BACKEND_NAME => env.setStateBackend(new MemoryStateBackend()) case _ => throw new UnsupportedOperationException } lazy val firstBroadcastStateDesc = new MapStateDescriptor[Long, Long]( "broadcast-state-1", BasicTypeInfo.LONG_TYPE_INFO.asInstanceOf[TypeInformation[Long]], BasicTypeInfo.LONG_TYPE_INFO.asInstanceOf[TypeInformation[Long]]) lazy val secondBroadcastStateDesc = new MapStateDescriptor[String, String]( "broadcast-state-2", BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO) env.setStateBackend(new MemoryStateBackend) env.enableCheckpointing(500) env.setParallelism(4) env.setMaxParallelism(4) val stream = env .addSource( new CheckpointedSource(4)).setMaxParallelism(1).uid("checkpointedSource") .keyBy( new KeySelector[(Long, Long), Long] { override def getKey(value: (Long, Long)): Long = value._1 } ) .flatMap(new StatefulFlatMapper) .keyBy( new KeySelector[(Long, Long), Long] { override def getKey(value: (Long, Long)): Long = value._1 } ) val broadcastStream = env .addSource( new CheckpointedSource(4)).setMaxParallelism(1).uid("checkpointedBroadcastSource") .broadcast(firstBroadcastStateDesc, secondBroadcastStateDesc) val expectedFirstState: Map[Long, Long] = Map(0L -> 0L, 1L -> 1L, 2L -> 2L, 3L -> 3L) val expectedSecondState: Map[String, String] = Map("0" -> "0", "1" -> "1", "2" -> "2", "3" -> "3") stream .connect(broadcastStream) .process(new VerifyingBroadcastProcessFunction(expectedFirstState, expectedSecondState)) .addSink(new AccumulatorCountingSink) restoreAndExecute( env, SavepointMigrationTestBase.getResourceFilename( s"stateful-scala-with-broadcast" + s"-udf-migration-itcase-flink${migrationVersionAndBackend._1}" + s"-${migrationVersionAndBackend._2}-savepoint"), new Tuple2( AccumulatorCountingSink.NUM_ELEMENTS_ACCUMULATOR, StatefulJobWBroadcastStateMigrationITCase.NUM_ELEMENTS) ) } } class TestBroadcastProcessFunction extends KeyedBroadcastProcessFunction [Long, (Long, Long), (Long, Long), (Long, Long)] { lazy val firstBroadcastStateDesc = new MapStateDescriptor[Long, Long]( "broadcast-state-1", BasicTypeInfo.LONG_TYPE_INFO.asInstanceOf[TypeInformation[Long]], BasicTypeInfo.LONG_TYPE_INFO.asInstanceOf[TypeInformation[Long]]) val secondBroadcastStateDesc = new MapStateDescriptor[String, String]( "broadcast-state-2", BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO) @throws[Exception] override def processElement( value: (Long, Long), ctx: KeyedBroadcastProcessFunction [Long, (Long, Long), (Long, Long), (Long, Long)]#ReadOnlyContext, out: Collector[(Long, Long)]): Unit = { out.collect(value) } @throws[Exception] override def processBroadcastElement( value: (Long, Long), ctx: KeyedBroadcastProcessFunction [Long, (Long, Long), (Long, Long), (Long, Long)]#Context, out: Collector[(Long, Long)]): Unit = { ctx.getBroadcastState(firstBroadcastStateDesc).put(value._1, value._2) ctx.getBroadcastState(secondBroadcastStateDesc).put(value._1.toString, value._2.toString) } } @SerialVersionUID(1L) private object CheckpointedSource { var CHECKPOINTED_STRING = "Here be dragons!" } @SerialVersionUID(1L) private class CheckpointedSource(val numElements: Int) extends SourceFunction[(Long, Long)] with CheckpointedFunction { private var isRunning = true private var state: ListState[CustomCaseClass] = _ @throws[Exception] override def run(ctx: SourceFunction.SourceContext[(Long, Long)]) { ctx.emitWatermark(new Watermark(0)) ctx.getCheckpointLock synchronized { var i = 0 while (i < numElements) { ctx.collect(i, i) i += 1 } } // don't emit a final watermark so that we don't trigger the registered event-time // timers while (isRunning) Thread.sleep(20) } def cancel() { isRunning = false } override def initializeState(context: FunctionInitializationContext): Unit = { state = context.getOperatorStateStore.getListState( new ListStateDescriptor[CustomCaseClass]( "sourceState", createTypeInformation[CustomCaseClass])) } override def snapshotState(context: FunctionSnapshotContext): Unit = { state.clear() state.add(CustomCaseClass("Here be dragons!", 123)) } } @SerialVersionUID(1L) private object AccumulatorCountingSink { var NUM_ELEMENTS_ACCUMULATOR = classOf[AccumulatorCountingSink[_]] + "_NUM_ELEMENTS" } @SerialVersionUID(1L) private class AccumulatorCountingSink[T] extends RichSinkFunction[T] { private var count: Int = 0 @throws[Exception] override def open(parameters: Configuration) { super.open(parameters) getRuntimeContext.addAccumulator( AccumulatorCountingSink.NUM_ELEMENTS_ACCUMULATOR, new IntCounter) } @throws[Exception] override def invoke(value: T) { count += 1 getRuntimeContext.getAccumulator( AccumulatorCountingSink.NUM_ELEMENTS_ACCUMULATOR).add(1) } } class StatefulFlatMapper extends RichFlatMapFunction[(Long, Long), (Long, Long)] { private var caseClassState: ValueState[CustomCaseClass] = _ private var caseClassWithNestingState: ValueState[CustomCaseClassWithNesting] = _ private var collectionState: ValueState[List[CustomCaseClass]] = _ private var tryState: ValueState[Try[CustomCaseClass]] = _ private var tryFailureState: ValueState[Try[CustomCaseClass]] = _ private var optionState: ValueState[Option[CustomCaseClass]] = _ private var optionNoneState: ValueState[Option[CustomCaseClass]] = _ private var eitherLeftState: ValueState[Either[CustomCaseClass, String]] = _ private var eitherRightState: ValueState[Either[CustomCaseClass, String]] = _ private var enumOneState: ValueState[CustomEnum] = _ private var enumThreeState: ValueState[CustomEnum] = _ override def open(parameters: Configuration): Unit = { caseClassState = getRuntimeContext.getState( new ValueStateDescriptor[CustomCaseClass]( "caseClassState", createTypeInformation[CustomCaseClass])) caseClassWithNestingState = getRuntimeContext.getState( new ValueStateDescriptor[CustomCaseClassWithNesting]( "caseClassWithNestingState", createTypeInformation[CustomCaseClassWithNesting])) collectionState = getRuntimeContext.getState( new ValueStateDescriptor[List[CustomCaseClass]]( "collectionState", createTypeInformation[List[CustomCaseClass]])) tryState = getRuntimeContext.getState( new ValueStateDescriptor[Try[CustomCaseClass]]( "tryState", createTypeInformation[Try[CustomCaseClass]])) tryFailureState = getRuntimeContext.getState( new ValueStateDescriptor[Try[CustomCaseClass]]( "tryFailureState", createTypeInformation[Try[CustomCaseClass]])) optionState = getRuntimeContext.getState( new ValueStateDescriptor[Option[CustomCaseClass]]( "optionState", createTypeInformation[Option[CustomCaseClass]])) optionNoneState = getRuntimeContext.getState( new ValueStateDescriptor[Option[CustomCaseClass]]( "optionNoneState", createTypeInformation[Option[CustomCaseClass]])) eitherLeftState = getRuntimeContext.getState( new ValueStateDescriptor[Either[CustomCaseClass, String]]( "eitherLeftState", createTypeInformation[Either[CustomCaseClass, String]])) eitherRightState = getRuntimeContext.getState( new ValueStateDescriptor[Either[CustomCaseClass, String]]( "eitherRightState", createTypeInformation[Either[CustomCaseClass, String]])) enumOneState = getRuntimeContext.getState( new ValueStateDescriptor[CustomEnum]( "enumOneState", createTypeInformation[CustomEnum])) enumThreeState = getRuntimeContext.getState( new ValueStateDescriptor[CustomEnum]( "enumThreeState", createTypeInformation[CustomEnum])) } override def flatMap(in: (Long, Long), collector: Collector[(Long, Long)]): Unit = { caseClassState.update(CustomCaseClass(in._1.toString, in._2 * 2)) caseClassWithNestingState.update( CustomCaseClassWithNesting(in._1, CustomCaseClass(in._1.toString, in._2 * 2))) collectionState.update(List(CustomCaseClass(in._1.toString, in._2 * 2))) tryState.update(Try(CustomCaseClass(in._1.toString, in._2 * 5))) tryFailureState.update(Failure(new RuntimeException)) optionState.update(Some(CustomCaseClass(in._1.toString, in._2 * 2))) optionNoneState.update(None) eitherLeftState.update(Left(CustomCaseClass(in._1.toString, in._2 * 2))) eitherRightState.update(Right((in._1 * 3).toString)) enumOneState.update(CustomEnum.ONE) enumOneState.update(CustomEnum.THREE) collector.collect(in) } } class VerifyingBroadcastProcessFunction( firstExpectedBroadcastState: Map[Long, Long], secondExpectedBroadcastState: Map[String, String]) extends KeyedBroadcastProcessFunction [Long, (Long, Long), (Long, Long), (Long, Long)] { lazy val firstBroadcastStateDesc = new MapStateDescriptor[Long, Long]( "broadcast-state-1", BasicTypeInfo.LONG_TYPE_INFO.asInstanceOf[TypeInformation[Long]], BasicTypeInfo.LONG_TYPE_INFO.asInstanceOf[TypeInformation[Long]]) val secondBroadcastStateDesc = new MapStateDescriptor[String, String]( "broadcast-state-2", BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO) @throws[Exception] override def processElement( value: (Long, Long), ctx: KeyedBroadcastProcessFunction [Long, (Long, Long), (Long, Long), (Long, Long)]#ReadOnlyContext, out: Collector[(Long, Long)]): Unit = { var actualFirstState = Map[Long, Long]() import scala.collection.JavaConversions._ for (entry <- ctx.getBroadcastState(firstBroadcastStateDesc).immutableEntries()) { val v = firstExpectedBroadcastState.get(entry.getKey).get Assert.assertEquals(v, entry.getValue) actualFirstState += (entry.getKey -> entry.getValue) } Assert.assertEquals(firstExpectedBroadcastState, actualFirstState) var actualSecondState = Map[String, String]() import scala.collection.JavaConversions._ for (entry <- ctx.getBroadcastState(secondBroadcastStateDesc).immutableEntries()) { val v = secondExpectedBroadcastState.get(entry.getKey).get Assert.assertEquals(v, entry.getValue) actualSecondState += (entry.getKey -> entry.getValue) } Assert.assertEquals(secondExpectedBroadcastState, actualSecondState) out.collect(value) } @throws[Exception] override def processBroadcastElement( value: (Long, Long), ctx: KeyedBroadcastProcessFunction [Long, (Long, Long), (Long, Long), (Long, Long)]#Context, out: Collector[(Long, Long)]): Unit = { // do nothing } }
jinglining/flink
flink-tests/src/test/scala/org/apache/flink/api/scala/migration/StatefulJobWBroadcastStateMigrationITCase.scala
Scala
apache-2.0
18,727
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package kafka.api import java.io.File import java.util.Properties import kafka.server._ import org.apache.kafka.common.security.auth.{KafkaPrincipal, SecurityProtocol} import org.apache.kafka.common.utils.Sanitizer import org.junit.Before class UserClientIdQuotaTest extends BaseQuotaTest { override protected def securityProtocol = SecurityProtocol.SSL override protected lazy val trustStoreFile = Some(File.createTempFile("truststore", ".jks")) override def producerClientId = "QuotasTestProducer-!@#$%^&*()" override def consumerClientId = "QuotasTestConsumer-!@#$%^&*()" @Before override def setUp() { this.serverConfig.setProperty(KafkaConfig.SslClientAuthProp, "required") this.serverConfig.setProperty(KafkaConfig.ProducerQuotaBytesPerSecondDefaultProp, Long.MaxValue.toString) this.serverConfig.setProperty(KafkaConfig.ConsumerQuotaBytesPerSecondDefaultProp, Long.MaxValue.toString) super.setUp() val defaultProps = quotaTestClients.quotaProperties(defaultProducerQuota, defaultConsumerQuota, defaultRequestQuota) adminZkClient.changeUserOrUserClientIdConfig(ConfigEntityName.Default + "/clients/" + ConfigEntityName.Default, defaultProps) quotaTestClients.waitForQuotaUpdate(defaultProducerQuota, defaultConsumerQuota, defaultRequestQuota) } override def createQuotaTestClients(topic: String, leaderNode: KafkaServer): QuotaTestClients = { val producer = createProducer() val consumer = createConsumer() new QuotaTestClients(topic, leaderNode, producerClientId, consumerClientId, producer, consumer) { override def userPrincipal: KafkaPrincipal = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "O=A client,CN=localhost") override def quotaMetricTags(clientId: String): Map[String, String] = { Map("user" -> Sanitizer.sanitize(userPrincipal.getName), "client-id" -> clientId) } override def overrideQuotas(producerQuota: Long, consumerQuota: Long, requestQuota: Double) { val producerProps = new Properties() producerProps.setProperty(DynamicConfig.Client.ProducerByteRateOverrideProp, producerQuota.toString) producerProps.setProperty(DynamicConfig.Client.RequestPercentageOverrideProp, requestQuota.toString) updateQuotaOverride(userPrincipal.getName, producerClientId, producerProps) val consumerProps = new Properties() consumerProps.setProperty(DynamicConfig.Client.ConsumerByteRateOverrideProp, consumerQuota.toString) consumerProps.setProperty(DynamicConfig.Client.RequestPercentageOverrideProp, requestQuota.toString) updateQuotaOverride(userPrincipal.getName, consumerClientId, consumerProps) } override def removeQuotaOverrides() { val emptyProps = new Properties adminZkClient.changeUserOrUserClientIdConfig(Sanitizer.sanitize(userPrincipal.getName) + "/clients/" + Sanitizer.sanitize(producerClientId), emptyProps) adminZkClient.changeUserOrUserClientIdConfig(Sanitizer.sanitize(userPrincipal.getName) + "/clients/" + Sanitizer.sanitize(consumerClientId), emptyProps) } private def updateQuotaOverride(userPrincipal: String, clientId: String, properties: Properties) { adminZkClient.changeUserOrUserClientIdConfig(Sanitizer.sanitize(userPrincipal) + "/clients/" + Sanitizer.sanitize(clientId), properties) } } } }
ollie314/kafka
core/src/test/scala/integration/kafka/api/UserClientIdQuotaTest.scala
Scala
apache-2.0
3,945
package models.customer import models.common._ import play.api.libs.json.Json import models._ import models.AssetSupport.IdType import org.joda.time.DateTime import services.CollectionName case class ContactIn( _id: IdType, createdAt: DateTime, lastModifiedAt: DateTime, active: Boolean, description: String, contactTypeId: IdType, status: String, title: String, firstName: String, lastName: String, phonenumbers: List[PhoneNumber], emails: List[Email] ) extends ContactLike with AssetIn with AssetUpdateBuilder[ContactUpdate] { override def fillup(lastModifiedAt: DateTime) = ContactUpdate( lastModifiedAt, active, description, contactTypeId, status, title, firstName, lastName, phonenumbers, emails) } object ContactIn extends DateFormatSupport { implicit val format = Json.format[ContactIn] implicit val collectionName = new CollectionName[ContactIn] { override def get: String = "contacts" } } case class ContactUpdate(lastModifiedAt: DateTime, active: Boolean, description: String, contactTypeId: IdType, status: String, title: String, firstName: String, lastName: String, phonenumbers: List[PhoneNumber], emails: List[Email]) extends ContactLike with AssetUpdate object ContactUpdate extends DateFormatSupport { implicit val format = Json.format[ContactUpdate] implicit val collectionName = new CollectionName[ContactUpdate] { override def get: String = ContactIn.collectionName.get } } case class ContactCreate(active: Boolean, description: String, contactTypeId: IdType, status: String, title: String, firstName: String, lastName: String, phonenumbers: List[PhoneNumber], emails: List[Email]) extends ContactLike with AssetCreate[ContactIn] { self => override def fillup(b: AssetBase) = { ContactIn( b.id, b.createdAt, b.lastModifiedAt, active, description, contactTypeId, status, title, firstName, lastName, phonenumbers, emails) } } object ContactCreate { implicit val reads = Json.reads[ContactCreate] }
tsechov/shoehorn
app/models/customer/contact.scala
Scala
apache-2.0
2,807
package com.github.johnynek.bazel_deps import java.io.File import java.nio.file.Paths import io.circe.jawn.JawnParser import scala.sys.process.{ BasicIO, Process, ProcessIO } import scala.util.{ Failure, Success, Try } import cats.instances.try_._ object MakeDeps { def apply(g: Command.Generate): Unit = { val content: String = Model.readFile(g.absDepsFile) match { case Success(str) => str case Failure(err) => System.err.println(s"[ERROR]: Failed to read ${g.depsFile}.\\n$err") System.exit(1) sys.error("unreachable") } val parser = if (g.depsFile.endsWith(".json")) new JawnParser else Yaml val model = Decoders.decodeModel(parser, content) match { case Right(m) => m case Left(err) => System.err.println(s"[ERROR]: Failed to parse ${g.depsFile}.\\n$err") System.exit(1) sys.error("unreachable") } val workspacePath = g.shaFilePath val projectRoot = g.repoRoot.toFile val resolverCachePath = model.getOptions.getResolverCache match { case ResolverCache.Local => Paths.get("target/local-repo") case ResolverCache.BazelOutputBase => Try(Process(List("bazel", "info", "output_base"), projectRoot) !!) match { case Success(path) => Paths.get(path.trim, "bazel-deps/local-repo") case Failure(err) => System.err.println(s"[ERROR]: Could not find resolver cache path -- `bazel info output_base` failed.\\n$err") System.exit(1) sys.error("unreachable") } } val deps = model.dependencies val resolver = new Resolver(model.getOptions.getResolvers, resolverCachePath.toAbsolutePath) val graph = resolver.addAll(Graph.empty, deps.roots, model) // This is a defensive check that can be removed as we add more tests deps.roots.foreach { m => require(graph.nodes(m), s"$m") } Normalizer(graph, deps.roots, model.getOptions.getVersionConflictPolicy) match { case None => println("[ERROR] could not normalize versions:") println(graph.nodes.groupBy(_.unversioned) .mapValues { _.map(_.version).toList.sorted } .filter { case (_, s) => s.lengthCompare(1) > 0 } .map { case (u, vs) => s"""${u.asString}: ${vs.mkString(", ")}\\n""" } .mkString("\\n")) System.exit(1) case Some(normalized) => /** * The graph is now normalized, lets get the shas */ val duplicates = graph.nodes .groupBy(_.unversioned) .mapValues(_.map(_.version)) .filter { case (_, set) => set.size > 1 } /** * Make sure all the optional versioned items were found */ val uvNodes = normalized.nodes.map(_.unversioned) deps.unversionedRoots.filterNot { u => uvNodes(u) || model.getReplacements.get(u).isDefined }.toList match { case Nil => () case missing => System.err.println( s"Missing unversioned deps in the normalized graph: ${missing.map(_.asString).mkString(" ")}") System.exit(-1) } def replaced(m: MavenCoordinate): Boolean = model.getReplacements.get(m.unversioned).isDefined val shas = resolver.getShas(normalized.nodes.filterNot(replaced)) // build the workspace def ws = Writer.workspace(normalized, duplicates, shas, model) // build the BUILDs in thirdParty val targets = Writer.targets(normalized, model) match { case Right(t) => t case Left(err) => System.err.println(s"""Could not find explicit exports named by: ${err.mkString(", ")}""") System.exit(-1) sys.error("exited already") } val formatter: Writer.BuildFileFormatter = g.buildifier match { // If buildifier is provided, run it with the unformatted contents on its stdin; it will print the formatted // result on stdout. case Some(buildifierPath) => (p, s) => { val output = new java.lang.StringBuilder() val error = new java.lang.StringBuilder() val processIO = new ProcessIO( os => { os.write(s.getBytes(IO.charset)) os.close() }, BasicIO.processFully(output), BasicIO.processFully(error) ) val exit = Process(List(buildifierPath, "-path", p.asString, "-"), projectRoot).run(processIO).exitValue // Blocks until the process exits. if (exit != 0) { System.err.println(s"buildifier $buildifierPath failed (code $exit) for ${p.asString}:\\n$error") System.exit(-1) sys.error("unreachable") } output.toString } // If no buildifier is provided, pass the contents through directly. case None => (_, s) => s } if (g.checkOnly) { executeCheckOnly(model, projectRoot, IO.path(workspacePath), ws, targets, formatter) } else { executeGenerate(model, projectRoot, IO.path(workspacePath), ws, targets, formatter) } } } private def executeCheckOnly(model: Model, projectRoot: File, workspacePath: IO.Path, workspaceContents: String, targets: List[Target], formatter: Writer.BuildFileFormatter): Unit = { // Build up the IO operations that need to run. val io = for { wsOK <- IO.compare(workspacePath, workspaceContents) wsbOK <- IO.compare(workspacePath.sibling("BUILD"), "") buildsOK <- Writer.compareBuildFiles(model.getOptions.getBuildHeader, targets, formatter) } yield wsOK :: wsbOK :: buildsOK // Here we actually run the whole thing io.foldMap(IO.fileSystemExec(projectRoot)) match { case Failure(err) => System.err.println(err) System.exit(-1) case Success(comparisons) => val mismatchedFiles = comparisons.filter(!_.ok) if (mismatchedFiles.isEmpty) { println(s"all ${comparisons.size} generated files are up-to-date") } else { System.err.println(s"some generated files are not up-to-date:\\n${mismatchedFiles.map(_.path.asString).sorted.mkString("\\n")}") System.exit(2) } } } private def executeGenerate(model: Model, projectRoot: File, workspacePath: IO.Path, workspaceContents: String, targets: List[Target], formatter: Writer.BuildFileFormatter): Unit = { // Build up the IO operations that need to run. Till now, // nothing was written val io = for { _ <- IO.recursiveRmF(IO.Path(model.getOptions.getThirdPartyDirectory.parts)) _ <- IO.mkdirs(workspacePath.parent) _ <- IO.writeUtf8(workspacePath, workspaceContents) _ <- IO.writeUtf8(workspacePath.sibling("BUILD"), "") builds <- Writer.createBuildFiles(model.getOptions.getBuildHeader, targets, formatter) } yield builds // Here we actually run the whole thing io.foldMap(IO.fileSystemExec(projectRoot)) match { case Failure(err) => System.err.println(err) System.exit(-1) case Success(builds) => println(s"wrote ${targets.size} targets in $builds BUILD files") } } }
GinFungYJF/bazel-deps
src/scala/com/github/johnynek/bazel_deps/MakeDeps.scala
Scala
mit
7,276
package fpinscala.errorhandling import scala.{Option => _, Either => _, Left => _, Right => _, _} // hide std library `Option` and `Either`, since we are writing our own in this chapter sealed trait Either[+E,+A] { def map[B](f: A => B): Either[E, B] = this match { case Right(x) => Right(f(x)) case Left(x) => Left(x) } def flatMap[EE >: E, B](f: A => Either[EE, B]): Either[EE, B] = this match { case Right(x) => f(x) case Left(x) => Left(x) } def orElse[EE >: E, B >: A](b: => Either[EE, B]): Either[EE, B] = this match { case Right(x) => this case Left(x) => b } def map2[EE >: E, B, C](b: Either[EE, B])(f: (A, B) => C): Either[EE, C] = { flatMap(x => b.map((y => f(x, y)))) } } case class Left[+E](get: E) extends Either[E,Nothing] case class Right[+A](get: A) extends Either[Nothing,A] object Either { def traverse[E,A,B](es: List[A])(f: A => Either[E, B]): Either[E, List[B]] = es match { case x :: xs => f(x).map2(traverse(xs)(f))(_::_) case Nil => Right(Nil) } def sequence[E,A](es: List[Either[E,A]]): Either[E,List[A]] = traverse(es)(x => x) def mean(xs: IndexedSeq[Double]): Either[String, Double] = if (xs.isEmpty) Left("mean of empty list!") else Right(xs.sum / xs.length) def safeDiv(x: Int, y: Int): Either[Exception, Int] = try Right(x / y) catch { case e: Exception => Left(e) } def Try[A](a: => A): Either[Exception, A] = try Right(a) catch { case e: Exception => Left(e) } }
conor10/fpinscala
exercises/src/main/scala/fpinscala/errorhandling/Either.scala
Scala
mit
1,508
package mesosphere.marathon.upgrade import akka.actor.{ Actor, ActorLogging } import akka.event.EventStream import mesosphere.marathon.SchedulerActions import mesosphere.marathon.core.launchqueue.LaunchQueue import mesosphere.marathon.event.{ HealthStatusChanged, MarathonHealthCheckEvent, MesosStatusUpdateEvent } import mesosphere.marathon.state.AppDefinition import mesosphere.marathon.tasks.TaskTracker import org.apache.mesos.SchedulerDriver import scala.concurrent.duration._ trait StartingBehavior { this: Actor with ActorLogging => import context.dispatcher import mesosphere.marathon.upgrade.StartingBehavior._ def eventBus: EventStream def scaleTo: Int def nrToStart: Int def taskQueue: LaunchQueue def driver: SchedulerDriver def scheduler: SchedulerActions def taskTracker: TaskTracker val app: AppDefinition val Version = app.version.toString var atLeastOnceHealthyTasks = Set.empty[String] var startedRunningTasks = Set.empty[String] val AppId = app.id val withHealthChecks: Boolean = app.healthChecks.nonEmpty def initializeStart(): Unit final override def preStart(): Unit = { if (withHealthChecks) { eventBus.subscribe(self, classOf[MarathonHealthCheckEvent]) } else { eventBus.subscribe(self, classOf[MesosStatusUpdateEvent]) } initializeStart() checkFinished() context.system.scheduler.scheduleOnce(5.seconds, self, Sync) } final def receive: Receive = { val behavior = if (withHealthChecks) checkForHealthy else checkForRunning behavior orElse commonBehavior } final def checkForHealthy: Receive = { case HealthStatusChanged(AppId, taskId, Version, true, _, _) if !atLeastOnceHealthyTasks(taskId) => atLeastOnceHealthyTasks += taskId log.info(s"$taskId is now healthy") checkFinished() } final def checkForRunning: Receive = { case MesosStatusUpdateEvent(_, taskId, "TASK_RUNNING", _, app.`id`, _, _, Version, _, _) if !startedRunningTasks(taskId) => // scalastyle:off line.size.limit startedRunningTasks += taskId log.info(s"New task $taskId now running during app ${app.id.toString} scaling, " + s"${nrToStart - startedRunningTasks.size} more to go") checkFinished() } def commonBehavior: Receive = { case MesosStatusUpdateEvent(_, taskId, StartErrorState(_), _, app.`id`, _, _, Version, _, _) => // scalastyle:off line.size.limit log.warning(s"New task $taskId failed during app ${app.id.toString} scaling, queueing another task") startedRunningTasks -= taskId taskQueue.add(app) case Sync => val actualSize = taskQueue.get(app.id).map(_.totalTaskCount).getOrElse(taskTracker.count(app.id)) val tasksToStartNow = Math.max(scaleTo - actualSize, 0) if (tasksToStartNow > 0) { log.info(s"Reconciling tasks during app ${app.id.toString} scaling: queuing ${tasksToStartNow} new tasks") taskQueue.add(app, tasksToStartNow) } context.system.scheduler.scheduleOnce(5.seconds, self, Sync) } def checkFinished(): Unit = { val started = if (withHealthChecks) atLeastOnceHealthyTasks.size else startedRunningTasks.size if (started == nrToStart) { success() } } def success(): Unit } object StartingBehavior { case object Sync } private object StartErrorState { def unapply(state: String): Option[String] = state match { case "TASK_ERROR" | "TASK_FAILED" | "TASK_KILLED" | "TASK_LOST" => Some(state) case _ => None } }
Kosta-Github/marathon
src/main/scala/mesosphere/marathon/upgrade/StartingBehavior.scala
Scala
apache-2.0
3,533
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package models.businessmatching import jto.validation.forms.UrlFormEncoded import jto.validation._ import play.api.libs.json._ import cats.data.Validated.{Invalid, Valid} import play.api.i18n.Messages sealed trait BusinessType object BusinessType { import jto.validation.forms.Rules._ case object SoleProprietor extends BusinessType case object LimitedCompany extends BusinessType case object Partnership extends BusinessType case object LPrLLP extends BusinessType case object UnincorporatedBody extends BusinessType def errorMessageFor(businessType: BusinessType)(implicit messages: Messages): String = { val common = "error.required.declaration.add.position.for" businessType match { case BusinessType.LimitedCompany => Messages(s"$common.limitedcompany") case BusinessType.SoleProprietor => Messages(s"$common.sole.proprietor") case BusinessType.Partnership => Messages(s"$common.partner.ship") case BusinessType.LPrLLP => Messages(s"$common.lprlpp") case BusinessType.UnincorporatedBody => Messages(s"$common.unicorporated.body") } } implicit val formR: Rule[UrlFormEncoded, BusinessType] = From[UrlFormEncoded] { __ => (__ \\ "businessType").read[String] flatMap { case "01" => Rule(_ => Valid(LimitedCompany)) case "02" => Rule(_ => Valid(SoleProprietor)) case "03" => Rule(_ => Valid(Partnership)) case "04" => Rule(_ => Valid(LPrLLP)) case "05" => Rule(_ => Valid(UnincorporatedBody)) case _ => Rule { _ => Invalid(Seq(Path \\ "businessType" -> Seq(ValidationError("error.invalid")))) } } } implicit val formW: Write[BusinessType, UrlFormEncoded] = Write[BusinessType, UrlFormEncoded] { case LimitedCompany => Map("businessType" -> Seq("01")) case SoleProprietor => Map("businessType" -> Seq("02")) case Partnership => Map("businessType" -> Seq("03")) case LPrLLP => Map("businessType" -> Seq("04")) case UnincorporatedBody => Map("businessType" -> Seq("05")) } implicit val writes = Writes[BusinessType] { case LimitedCompany => JsString("Corporate Body") case SoleProprietor => JsString("Sole Trader") case Partnership => JsString("Partnership") case LPrLLP => JsString("LLP") case UnincorporatedBody => JsString("Unincorporated Body") } implicit val reads = Reads[BusinessType] { case JsString("Corporate Body") => JsSuccess(LimitedCompany) case JsString("Sole Trader") => JsSuccess(SoleProprietor) case JsString("Partnership") => JsSuccess(Partnership) case JsString("LLP") => JsSuccess(LPrLLP) case JsString("Unincorporated Body") => JsSuccess(UnincorporatedBody) case _ => JsError(JsPath -> play.api.libs.json.JsonValidationError("error.invalid")) } }
hmrc/amls-frontend
app/models/businessmatching/BusinessType.scala
Scala
apache-2.0
3,479
package in.tamchow.LinearAlgebra import scala.language.implicitConversions object LinearAlgebra { object Enhancements { implicit class ScalarMatrixInterOp[T](scalar: T)(implicit evidence: Numeric[T]) { def product[B: Numeric](matrix: Matrix[B]): Matrix[Double] = matrix product scalar def *[B: Numeric](matrix: Matrix[B]): Matrix[Double] = product(matrix) def toMatrix: Matrix[T] = Matrix(IndexedSeq(IndexedSeq(scalar))) } def doSafe[A, B](action: => Either[Throwable, A])(onSuccess: A => B): B = action match { case Left(exception) => throw exception case Right(data) => onSuccess(data) } implicit def getSafe[A](action: => Either[Throwable, A]): A = doSafe(action)(identity _) } import Enhancements._ case class Matrix[T](private val data: IndexedSeq[IndexedSeq[T]])(implicit numeric: Numeric[T]) { private lazy val notSquareUndefinedOperationMessage = s"Matrix of $rows rows & $columns columns is not square, %s cannot be defined" import numeric._ lazy val dimensions: (Int, Int) = (data.length, data.headOption.getOrElse(IndexedSeq()).length) lazy val (rows, columns) = dimensions override lazy val toString: String = data.map(_.mkString("[", ", ", "]")) .mkString(s"${getClass.getSimpleName}($rows, $columns) = [", ", ", "]") lazy val toPrintableString: String = data.map(_.mkString("[", ", ", "]")) .mkString("", "\\n", "\\n") private lazy val isValidMatrix: Boolean = rowVectors.tail .map(row => row.length) .forall(rowLength => rowLength == columns) def apply(i: Int, j: Int): T = get(i, j) /** * Accesses an element at (i, j) * * @param i row index, 1 - based * @param j column index, 1 - based * @return the element @ (i, j) */ def get(i: Int, j: Int): Either[IndexOutOfBoundsException, T] = checkBoundsException(data(i - 1)(j - 1))(i, j) /** * Updates an element at (i, j) * * @param i row index, 1 - based * @param j column index, 1 - based * @param value the value to update * @return A matrix with the value @ (i, j) updated to `value` */ def updated(i: Int, j: Int)(value: T): Either[IndexOutOfBoundsException, Matrix[T]] = checkBoundsException(Matrix(data.updated(i, data(i - 1).updated(j - 1, value))))(i, j) def set(i: Int, j: Int)(value: T): Matrix[T] = getSafe(updated(i, j)(value)) lazy val isSquare: Boolean = rows == columns def sum(matrix: Matrix[T]): Either[UnsupportedOperationException, Matrix[T]] = if (matrix.rows == rows || matrix.columns == columns) Right(Matrix( for ((ourRow, theirRow) <- data.zip(matrix.data)) yield { for ((ourElement, theirElement) <- ourRow.zip(theirRow)) yield { theirElement + ourElement } })) else Left(new UnsupportedOperationException( s"Unequal matrix dimensions, cannot add (${matrix.rows} to $rows rows, ${matrix.columns} to $columns columns")) def +(matrix: Matrix[T]): Matrix[T] = sum(matrix) def unary_- = Matrix(data.map(row => row.map(element => -element))) def difference(matrix: Matrix[T]): Either[UnsupportedOperationException, Matrix[T]] = sum(-matrix) def -(matrix: Matrix[T]): Matrix[T] = difference(matrix) /** * Product of a matrix with a scalar. Overloaded with matrix product for convenience * * @param scalar The scalar to multiply this matrix by * @param evidence Implicit parameter containing type which allows numeric operations on `scalar` * @tparam B The type of `scalar` * @return the product of this matrix with the scalar `scalar` * @see [[Matrix.*[B](scalar:B)*]] */ def product[B](scalar: B)(implicit evidence: Numeric[B]): Matrix[Double] = { val scalarAsDouble = scalar.toString.toDouble Matrix(for (row <- rowVectors) yield { row.map(_.toDouble * scalarAsDouble) }) } /** * Operator alias for [[Matrix.product[B](scalar:B)*]] * * @see [[Matrix.product[B](scalar:B)*]] */ def *[B](scalar: B)(implicit evidence: Numeric[B]): Matrix[Double] = product(scalar) def product(matrix: Matrix[T]): Either[IllegalArgumentException, Matrix[T]] = if (this.columns != matrix.rows) Left(new IllegalArgumentException( s"Product is not defined for $rows rows of left matrix not equal to $columns columns of right matrix")) else Right(Matrix(IndexedSeq.tabulate(rows)(row => IndexedSeq.tabulate(matrix.columns)(column => Seq.tabulate(columns)(subIndex => data(row)(subIndex) * matrix.data(subIndex)(column)).sum)))) def *(matrix: Matrix[T]): Matrix[T] = product(matrix) lazy val transpose: Matrix[T] = Matrix(IndexedSeq.tabulate(columns) { row => IndexedSeq.tabulate(rows) { column => data(column)(row) } }) def coFactor(i: Int, j: Int): Either[IndexOutOfBoundsException, Matrix[T]] = checkBoundsException(Matrix( for ((row, rowIndex) <- data.zipWithIndex if rowIndex != (i - 1)) yield { (for ((element, columnIndex) <- row.zipWithIndex if columnIndex != (j - 1)) yield element).toIndexedSeq } ))(i, j) lazy val determinant: Either[UnsupportedOperationException, T] = errorIfNotSquare( getSafe(order) match { case 1 => this (1, 1) case 2 => this (1, 1) * this (2, 2) - this (1, 2) * this (2, 1) case _ => expandAlongTopRow.sum }, "determinant") private def errorIfNotSquare[A](action: => A, operation: String): Either[UnsupportedOperationException, A] = if (isSquare) Right(action) else Left(new UnsupportedOperationException(notSquareUndefinedOperationMessage.format(operation))) lazy val expandAlongTopRow: IndexedSeq[T] = IndexedSeq.tabulate(order) { // Craziness mixing "one" and "1" is to avoid even more "implicit" confusion column => this (1, column + 1) * (if (column % 2 != 0) -one else one) * coFactor(1, column + 1).determinant } lazy val matrixOfMinors: Matrix[T] = Matrix(IndexedSeq.tabulate(rows) { row => IndexedSeq.tabulate(columns) { column => coFactor(row + 1, column + 1).determinant // Won't throw any exceptions! Promise! } }) lazy val inverse: Either[UnsupportedOperationException, Matrix[Double]] = errorIfNotSquare(matrixOfMinors.transpose * (one.toDouble / getSafe(determinant).toDouble), "inverse") lazy val order: Either[UnsupportedOperationException, Int] = if (isSquare) Right(rows) else Left(new UnsupportedOperationException(notSquareUndefinedOperationMessage.format("order"))) lazy val (rowVectors, columnVectors) = (data, transpose.data) private def checkBoundsException[A](stuff: => A)(i: Int, j: Int): Either[IndexOutOfBoundsException, A] = raiseExceptionOnBoundsViolation(i, j) match { case Some(boundsException) => Left(boundsException) case None => Right(stuff) } private def raiseExceptionOnBoundsViolation(i: Int, j: Int): Option[IndexOutOfBoundsException] = if (i <= 0 || j <= 0 || i > rows || j > columns) Some(new IndexOutOfBoundsException( s"($i, $j) are invalid 1-based indices for a matrix of $rows rows and $columns columns")) else None } object Matrix { def nullMatrix(rows: Int, columns: Int): Matrix[Double] = fill(rows, columns)(0.0) def apply(data: String): Either[IllegalArgumentException, Matrix[Double]] = if (data.startsWith("[[[") || data.startsWith("]]]")) Left(new IllegalArgumentException("Tensors of order > 2 not supported")) else if (data.count(_ == '[') != data.count(_ == ']')) Left(new IllegalArgumentException("Unbalanced square brackets")) else Right(Matrix( (if (data.startsWith("[[") && data.endsWith("]]")) data.substring(1, data.length - 1) // trim matrix-delimiting square brackets else data).split("\\\\],?\\\\s+\\\\[") map { // split into rows row => row.filter(character => !(character == '[' || character == ']')) // remove stray delimiters .split(",?\\\\s+") // split into elements .map(_.toDouble).toIndexedSeq })) def createMatrix[T](data: IndexedSeq[IndexedSeq[T]])(implicit numeric: Numeric[T]): Either[IllegalArgumentException, Matrix[T]] = { val matrix = new Matrix(data) if (!matrix.isValidMatrix) Left(new IllegalArgumentException("Matrix may not have jagged rows")) else Right(matrix) } def fromString(data: String): Matrix[Double] = getSafe(Matrix(data)) def identityMatrix(order: Int): Matrix[Double] = tabulate(order, order)((row, column) => if (row == column) 1.0 else 0.0) def tabulate[T: Numeric](numRows: Int, numColumns: Int)(elementFunction: (Int, Int) => T): Matrix[T] = Matrix(IndexedSeq.tabulate(numRows, numColumns)(elementFunction)) def fill[T: Numeric](numRows: Int, numColumns: Int)(element: => T): Matrix[T] = Matrix(IndexedSeq.fill(numRows, numColumns)(element)) } case class Vector(private val components: IndexedSeq[Double]) { private val data: Matrix[Double] = Matrix(IndexedSeq(components)) lazy val dimensions: Int = components.length override lazy val toString: String = s"$getClass(${components.mkString(", ")}" def add(other: Vector): Vector = Vector((data + other.data).rowVectors(0)) def +(other: Vector): Vector = add(other) def subtract(other: Vector): Vector = Vector((data + other.data).rowVectors(0)) def -(other: Vector): Vector = subtract(other) def crossProduct(other: Vector): Vector = Vector(Matrix(IndexedSeq(IndexedSeq.fill(dimensions)(1.0), components, other.components)).expandAlongTopRow) def dotProduct(other: Vector): Double = components.zipAll(other.components, 0.0, 0.0) .map { case (x1, x2) => x1 * x2 } .sum def apply(index: Int): Double = components(index) } object Vector { def nullVector(numComponents: Int): Vector = fill(numComponents)(0.0) def unitVector(numComponents: Int, direction: Int): Vector = Vector(IndexedSeq.tabulate(numComponents)(index => if (index == direction) 1.0 else 0.0)) def tabulate(numComponents: Int)(elementFunction: Int => Double): Vector = Vector(IndexedSeq.tabulate(numComponents)(elementFunction)) def fill(numComponents: Int)(element: => Double): Vector = Vector(IndexedSeq.fill(numComponents)(element)) def apply(components: Double*): Vector = Vector(components.toIndexedSeq) } }
tamchow/ScalaStuff
src/in/tamchow/LinearAlgebra/LinearAlgebra.scala
Scala
bsd-3-clause
12,082
package com.hyenawarrior.OldNorseGrammar.grammar.morphophonology.ProductiveTransforms import com.hyenawarrior.OldNorseGrammar.grammar.Syllable.Length._ import com.hyenawarrior.OldNorseGrammar.grammar.Syllables import com.hyenawarrior.auxiliary.& /** * Created by HyenaWarrior on 2018.03.18.. */ object SieversLaw { /* * Syncope? * rí-kij -> rí-ki * rí-ki -> rí-kij * rík-jum -> rí-ki-jum * * rí-ki * ríkj- */ private val svJ = ".+[^y]j.*".r def restore(str: String): Option[String] = str match { case Syllables(firstSy :: _) & svJ() if firstSy.length == OVERLONG => Some { str.replace("j", "ij") } case Syllables(firstSy :: _) if firstSy.length == LONG && str.endsWith("i") => Some { str.replace("i", "ij") } case _ => None } }
HyenaSoftware/IG-Dictionary
OldNorseGrammarEngine/src/main/scala/com/hyenawarrior/OldNorseGrammar/grammar/morphophonology/ProductiveTransforms/SieversLaw.scala
Scala
lgpl-3.0
817
import java.io.IOException import java.sql.Timestamp import java.text.SimpleDateFormat import java.time.Instant import scala.concurrent.Await import scala.concurrent.ExecutionContextExecutor import scala.concurrent.Future import scala.concurrent.duration._ import java.time.Duration import scala.math._ import akka.actor.ActorSystem import akka.event.Logging import akka.event.LoggingAdapter import akka.http.scaladsl.Http import akka.http.scaladsl.client.RequestBuilding import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.HttpRequest import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.ActorMaterializer import akka.stream.Materializer import akka.stream.scaladsl.Flow import akka.stream.scaladsl.Sink import akka.stream.scaladsl.Source import com.typesafe.config.Config import com.typesafe.config.ConfigFactory import spray.json.DefaultJsonProtocol import slick.backend.DatabasePublisher import akka.http.scaladsl.model.HttpEntity import akka.util.ByteString import akka.http.scaladsl.model.ContentTypes._ import spray.json._ import DefaultJsonProtocol._ trait Protocols2 extends DefaultJsonProtocol { implicit object TimestampFormat extends JsonFormat[Timestamp] { def write(obj: Timestamp) = JsNumber(obj.getTime) def read(json: JsValue) = json match { case JsNumber(time) => new Timestamp(time.toLong) case _ => throw new DeserializationException("Date expected") } } implicit object CapmasCapitalRequestReader extends RootJsonReader[CapmasCapitalRequest] { override def read(json: JsValue): CapmasCapitalRequest = json.asJsObject.getFields("id", "capmasId", "requestDate", "requestStatus", "strategyCode", "localCurr", "localAmt") match { case Seq(JsNumber(id), JsString(capmasId), JsNumber(requestDate), JsString(requestStatus), JsString(strategyCode), JsString(localCurr), JsNumber(localAmt)) => CapmasCapitalRequest(id.toIntExact, capmasId, new Timestamp(requestDate.toLong), requestStatus, strategyCode, localCurr, localAmt) case _ => throw deserializationError(s"CapmasCapitalRequest expected") } } implicit val requestFormat = jsonFormat7(CapmasCapitalRequest.apply) } trait Service2 extends Protocols2 { implicit val system: ActorSystem implicit def executor: ExecutionContextExecutor implicit val materializer: Materializer def config: Config val logger: LoggingAdapter def retrieveData = { Source(AkkaService2.repo.getRequestsStream(AkkaService2.testDt)) } val routes = { logRequestResult("akka-http-microservice") { path("streamTest") { (get) { val jsonRows = retrieveData.map { row => row.toJson.compactPrint } val jsonArray = Source.single("[\\n") ++ jsonRows.map(_ + ",\\n") ++ Source.single("]\\n") complete(HttpEntity.Chunked.fromData(`application/json`, jsonArray.map(ByteString(_)))) } } } } } object AkkaService2 extends App with Service2 { override implicit val system = ActorSystem() override implicit val executor = system.dispatcher override implicit val materializer = ActorMaterializer() override val config = ConfigFactory.load() override val logger = Logging(system, getClass) val sdf = new SimpleDateFormat("yyyy.MM.dd"); val testDt = sdf.parse("2015.01.02") val db_type = System.getenv("unit_test_db_type") val repo = (db_type match { case "oracle" => new OracleCapmasCapitalRequestRepository() case _ => new HsqlCapmasCapitalRequestRepository() }).capmasCapitalRequestRepository Await.ready(repo.create, 10.seconds) val start = Instant.now() Await.ready( repo.insert(Seq.fill(20)(CapmasCapitalRequest(0, "1", new Timestamp(testDt.getTime()), "1", "C-FI", "001", 100))), 100.seconds) val end = Instant.now() println("Records inserted in " + Duration.between(start, end).toMillis()) Http().bindAndHandle(routes, config.getString("http.interface"), config.getInt("http.port")) }
charlesxucheng/akka-http-microservice
src/main/scala/Service2.scala
Scala
mit
4,203
package core import java.util.Properties import java.util.concurrent.atomic.AtomicLong import akka.actor._ import akka.event.Logging import domain.{Place, Tweet, User} import org.apache.kafka.clients.producer.{Callback, KafkaProducer, ProducerConfig, ProducerRecord, RecordMetadata} import scala.concurrent.duration._ import scala.util.Random object RandomTweet { private[this] val serialGen = new AtomicLong() def apply(keywords: String): Tweet = { val id = Random.nextLong() val serial = serialGen.incrementAndGet() val text = s"Hello DCOS Demo $serial, $keywords" val json = s""" |{ | "created_at": "Mon Sep 28 14:59:10 +0000 2015", | "id": $id, | "id_str": "$id", | "text": "$text", | "truncated": false, | "in_reply_to_status_id": null, | "in_reply_to_status_id_str": null, | "in_reply_to_user_id": null, | "in_reply_to_user_id_str": null, | "in_reply_to_screen_name": null, | "user": { | "id": 123, | "id_str": "123", | "name": "DCOSDemoProducer", | "screen_name": "dcosProducer", | "location": "Hamburg, Germany", | "protected": false, | "verified": false, | "followers_count": 580, | "friends_count": 924, | "listed_count": 52, | "favourites_count": 0, | "statuses_count": 13343, | "created_at": "Thu Apr 16 13:17:13 +0000 2015", | "utc_offset": null, | "time_zone": null, | "geo_enabled": false, | "lang": "en", | "contributors_enabled": false, | "is_translator": false, | "following": null, | "follow_request_sent": null, | "notifications": null | }, | "geo": null, | "coordinates": null, | "place": null, | "contributors": null, | "retweet_count": 0, | "favorite_count": 0, | "entities": { | "hashtags": [ | { | "text": "dcos", | "indices": [ | 35, | 41 | ] | } | ], | "trends": [], | "urls": [], | "user_mentions": [], | "symbols": [] | }, | "favorited": false, | "retweeted": false, | "possibly_sensitive": false, | "filter_level": "low", | "lang": "en", | "timestamp_ms": "1443452350630" |} """.stripMargin Tweet( id = id.toString, user = User(id = "fake", lang = "en", followersCount = 0), text = text, place = Some(Place("Germany", "Hamburg")), json = json ) } } class ProducerActor(keywords: String) extends Actor { val log = Logging(context.system, this) val kafkaTopic = sys.env("TWEET_PRODUCER_KAFKA_TOPIC") var producer: KafkaProducer[String, String] = _ override def preStart(): Unit = { val kafkaBrokers = sys.env("TWEET_PRODUCER_KAFKA_BROKERS") val props = new Properties() props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaBrokers) props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer") props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer") producer = new KafkaProducer[String, String](props) } override def postStop(): Unit = { producer.close() } def receive: Receive = { case tweet: Tweet => val record = new ProducerRecord[String, String](kafkaTopic, tweet.json) producer.send(record, new Callback { override def onCompletion(result: RecordMetadata, exception: Exception) { if (exception != null) { log.warning(s"Failed to sent ${tweet.id}: ${tweet.text}", exception) } else { log.info(s"Sent tweet ${tweet.id}: ${tweet.text}") } } }) } }
mesosphere/iot-demo
twitter/src/main/scala/core/ProducerActor.scala
Scala
apache-2.0
4,363
import sbt._ import Keys._ object Build extends Build { lazy val buildSettings = Seq( libraryDependencies ++= Seq( "org.scodec" %% "scodec-core" % "1.7.0", "org.specs2" %% "specs2" % "2.4.15" % "test", "org.scalacheck" %% "scalacheck" % "1.12.2" % "test" ) ) ++ Seq( scalaVersion := "2.11.5", crossScalaVersions := Seq("2.10.4", scalaVersion.value), resolvers += "Scalaz Bintray Repo" at "http://dl.bintray.com/scalaz/releases", scalacOptions ++= ( "-deprecation" :: "-unchecked" :: "-Xlint" :: "-language:existentials" :: "-language:higherKinds" :: "-language:implicitConversions" :: Nil ), scalacOptions ++= { if (scalaVersion.value.startsWith("2.11")) Seq("-Ywarn-unused", "-Ywarn-unused-import") else Nil }, pomExtra := <developers> <developer> <id>filippovitale</id> <name>Filippo Vitale</name> <url>https://github.com/filippovitale</url> </developer> </developers> <scm> <url>[email protected]:filippovitale/pefile.git</url> <connection>scm:git:[email protected]:filippovitale/pefile.git</connection> <tag> {scala.util.Try(sys.process.Process("git rev-parse HEAD").lines_!.head).getOrElse("no-tag")} </tag> </scm> , description := "yet another pe analyser", organization := "com.github.filippovitale", homepage := Some(url("https://github.com/filippovitale/pefile")), licenses := Seq("MIT" -> url("http://www.opensource.org/licenses/mit-license.php")) ) ++ bintray.Plugin.bintraySettings lazy val pefile = Project( id = "pefile", base = file("."), settings = buildSettings ) }
filippovitale/pefile
project/build.scala
Scala
mit
1,790
package edu.cmu.dynet /** The underlying storage for a model parameter. You will never need to construct this yourself, * but can get it back from [[edu.cmu.dynet.ParameterCollection.parametersList()]]. */ class ParameterStorage private[dynet](private[dynet] val storage: internal.ParameterStorage) { def size(): Long = storage.size() def dim: Dim = new Dim(storage.getDim) def values: Tensor = new Tensor(storage.getValues) } class LookupParameterStorage private[dynet](private[dynet] val storage: internal.LookupParameterStorage) { def size(): Long = storage.size() } /** A (learnable) parameter of a model. */ class Parameter private[dynet] (private[dynet] val parameter: internal.Parameter) { //def this(model: ParameterCollection, index: Long) { this(new internal.Parameter(model.model, index)) } def zero(): Unit = parameter.zero() def dim(): Dim = new Dim(parameter.dim) def values(): Tensor = new Tensor(parameter.values) def setUpdated(b: Boolean): Unit = parameter.set_updated(b) def isUpdated(): Boolean = parameter.is_updated() } class LookupParameter private[dynet] (private[dynet] val lookupParameter: internal.LookupParameter) { //def this(model: ParameterCollection, index: Long) { this(new internal.LookupParameter(model.model, index))} def initialize(index: Long, values: FloatVector) = { lookupParameter.initialize(index, values.vector) } def zero(): Unit = lookupParameter.zero() def dim(): Dim = new Dim(lookupParameter.dim) def setUpdated(b: Boolean): Unit = lookupParameter.set_updated(b) def isUpdated(): Boolean = lookupParameter.is_updated() } /** Specifies how to initialize a parameter. Construct a particular initialization using the * various factory methods on the companion object. */ class ParameterInit private[dynet] ( private[dynet] val parameterInit: internal.ParameterInit) { def initializeParams(values: Tensor): Unit = parameterInit.initialize_params(values.tensor) } object ParameterInit { /* Initialize a parameter with random normal values */ def normal(m: Float = 0.0f, v: Float = 1.0f): ParameterInit = new ParameterInit(new internal.ParameterInitNormal(m, v)) /* Initialize a parameter with random uniform [left, right] values */ def uniform(left: Float, right: Float): ParameterInit = new ParameterInit(new internal.ParameterInitUniform(left, right)) /* Initialize a parameter with random uniform [-scale, scale] values */ def uniform(scale: Float): ParameterInit = uniform(-scale, scale) /* Initialize a parameter with the constant value c */ def const(c: Float): ParameterInit = new ParameterInit(new internal.ParameterInitConst(c)) /* Initialize a parameter with the identity matrix */ def identity(): ParameterInit = new ParameterInit(new internal.ParameterInitIdentity()) /* Initialize a parameter using the specified vector of values */ def fromVector(v: FloatVector): ParameterInit = new ParameterInit(new internal.ParameterInitFromVector(v.vector)) /* Initialize a parameter using Glorot initialization */ def glorot(isLookup: Boolean = false): ParameterInit = new ParameterInit(new internal.ParameterInitGlorot(isLookup)) }
xunzhang/dynet
contrib/swig/src/main/scala/edu/cmu/dynet/Parameter.scala
Scala
apache-2.0
3,204
package reasonable.interact import scalaz.~> import scalaz.Scalaz._ import reasonable.Algebra._ import InteractAlgebra._ object Console extends (Interact ~> EitherType) { def apply[A](i: Interact[A]) = i match { case Ask(prompt) => println(prompt) (scala.io.StdIn.readLine).right case Tell(msg) => (println(msg)).right case End => (new Exception("End")).left } }
enpassant/scalaz
src/main/scala/reasonable/interact/Console.scala
Scala
apache-2.0
406
package neuroflow.nets import org.scalatest.FunSuite import neuroflow.core.Activators.Double._ /** * @author bogdanski * @since 22.04.17 */ class ActivatorPerformanceTest extends FunSuite { def withTimer[B](f: => B): Long = { val n1 = System.nanoTime() f val n2 = System.nanoTime() n2 - n1 } test("Benchmark Activator Funcs") { val funcs = Seq(Linear, Square, Sigmoid, Tanh, ReLU, LeakyReLU(0.01), SoftPlus) val bench = funcs.map { f => (f, withTimer(f(1.0)), withTimer(f.derivative(1.0))) } bench.sortBy(_._2).foreach { case (f, value, derivative) => println(s"Function: ${f.symbol}, Evaluation: $value, Derivative: $derivative") } } }
zenecture/neuroflow
core/src/test/scala/ActivatorPerformanceTest.scala
Scala
apache-2.0
708
/* * Copyright (C) 2010-2014 GRNET S.A. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gr.grnet.common import java.io.{File, Closeable} package object io { implicit class CloseAnyway(val io: Closeable) extends AnyVal { def closeAnyway(): Unit = { try io.close() catch { case _: Exception ⇒ } } } implicit class DeleteAnyway(val file: File) extends AnyVal { def deleteAnyway(): Unit = try file.delete() catch { case _: Exception ⇒ } } }
grnet/snf-common-j
src/main/scala/gr/grnet/common/io/package.scala
Scala
gpl-3.0
1,111
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.scalnet.layers.reshaping import org.deeplearning4j.nn.conf.InputPreProcessor import org.scalatest.FunSpec /** * Created by maxpumperla on 19/07/17. */ class Flatten3DTest extends FunSpec { describe("A 3D flatten layer with output dim 20") { val outShape = List(20) val flatten = Flatten3D(outShape) it("should have output shape as input shape") { assert(flatten.inputShape == outShape) } it("should have outputShape as provided") { assert(flatten.outputShape == outShape) } it("should accept a new input shape when provided") { val reshapedFlatten = flatten.reshapeInput(List(10, 2, 10)) assert(reshapedFlatten.inputShape == List(10, 2, 10)) } it("should not compile when input shape is not 3D") { assertThrows[java.lang.IllegalArgumentException] { flatten.compile } } it("should become a DL4J InputPreProcessor when compiled") { val reshapedFlatten = flatten.reshapeInput(List(10, 2, 10)) val compiledFlatten = reshapedFlatten.compile assert(compiledFlatten.isInstanceOf[InputPreProcessor]) } } }
RobAltena/deeplearning4j
scalnet/src/test/scala/org/deeplearning4j/scalnet/layers/reshaping/Flatten3DTest.scala
Scala
apache-2.0
1,921
/* * Copyright 2011-2019 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.spark.runtime.fragment package user import scala.collection.JavaConversions._ import java.lang.{ Iterable => JIterable } import java.util.{ Iterator => JIterator } import com.asakusafw.runtime.core.Result import com.asakusafw.runtime.flow.ListBuffer import com.asakusafw.runtime.model.DataModel abstract class CoGroupOperatorFragment( buffers: IndexedSeq[Buffer[_ <: DataModel[_]]], children: IndexedSeq[Fragment[_]]) extends Fragment[IndexedSeq[Iterator[_]]] { override def doAdd(result: IndexedSeq[Iterator[_]]): Unit = { try { buffers.zip(result).foreach { case (buffer, iter) => def prepare[T <: DataModel[T]]() = { buffer.asInstanceOf[Buffer[T]] .prepare(iter.asInstanceOf[Iterator[T]]) } prepare() } cogroup(buffers.map(_.iterable), children) } finally { buffers.foreach(_.cleanup()) } } def cogroup(inputs: IndexedSeq[JIterable[_]], outputs: IndexedSeq[Result[_]]): Unit override def doReset(): Unit = { children.foreach(_.reset()) } } trait Buffer[T <: DataModel[T]] { def prepare(iter: Iterator[T]): Unit def iterable: JIterable[T] def cleanup(): Unit } abstract class ListLikeBuffer[T <: DataModel[T]](buffer: ListBuffer[T]) extends Buffer[T] { def newDataModel(): T override def prepare(iter: Iterator[T]): Unit = { buffer.begin() iter.foreach { input => if (buffer.isExpandRequired()) { buffer.expand(newDataModel()) } buffer.advance().copyFrom(input.asInstanceOf[T]) } buffer.end() } override def iterable: JIterable[T] = buffer override def cleanup(): Unit = buffer.shrink() } class IterableBuffer[T <: DataModel[T]] extends Buffer[T] { self => private var iter: Iterator[T] = _ def prepare(iter: Iterator[T]): Unit = { this.iter = iter } def iterable: JIterable[T] = new JIterable[T] { private var iter: JIterator[T] = self.iter override def iterator: JIterator[T] = { val result = iter if (result == null) { // scalastyle:ignore throw new IllegalStateException() } iter = null // scalastyle:ignore result } } def cleanup(): Unit = { if (iter != null) { // scalastyle:ignore while (iter.hasNext) { iter.next() } iter = null // scalastyle:ignore } } }
ashigeru/asakusafw-spark
runtime/src/main/scala/com/asakusafw/spark/runtime/fragment/user/CoGroupOperatorFragment.scala
Scala
apache-2.0
3,004
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.ui import java.util.{Date, ServiceLoader} import scala.collection.JavaConverters._ import org.apache.spark.{SecurityManager, SparkConf, SparkContext} import org.apache.spark.internal.Logging import org.apache.spark.scheduler._ import org.apache.spark.status.api.v1.{ApiRootResource, ApplicationAttemptInfo, ApplicationInfo, UIRoot} import org.apache.spark.storage.StorageStatusListener import org.apache.spark.ui.JettyUtils._ import org.apache.spark.ui.env.{EnvironmentListener, EnvironmentTab} import org.apache.spark.ui.exec.{ExecutorsListener, ExecutorsTab} import org.apache.spark.ui.jobs.{JobProgressListener, JobsTab, StagesTab} import org.apache.spark.ui.scope.RDDOperationGraphListener import org.apache.spark.ui.storage.{StorageListener, StorageTab} import org.apache.spark.util.Utils /** * Top level user interface for a Spark application. */ private[spark] class SparkUI private ( val sc: Option[SparkContext], val conf: SparkConf, securityManager: SecurityManager, val environmentListener: EnvironmentListener, val storageStatusListener: StorageStatusListener, val executorsListener: ExecutorsListener, val jobProgressListener: JobProgressListener, val storageListener: StorageListener, val operationGraphListener: RDDOperationGraphListener, var appName: String, val basePath: String, val startTime: Long) extends WebUI(securityManager, securityManager.getSSLOptions("ui"), SparkUI.getUIPort(conf), conf, basePath, "SparkUI") with Logging with UIRoot { val killEnabled = sc.map(_.conf.getBoolean("spark.ui.killEnabled", true)).getOrElse(false) var appId: String = _ /** Initialize all components of the server. */ def initialize() { val jobsTab = new JobsTab(this) attachTab(jobsTab) val stagesTab = new StagesTab(this) attachTab(stagesTab) attachTab(new StorageTab(this)) attachTab(new EnvironmentTab(this)) attachTab(new ExecutorsTab(this)) attachHandler(createStaticHandler(SparkUI.STATIC_RESOURCE_DIR, "/static")) attachHandler(createRedirectHandler("/", "/jobs/", basePath = basePath)) attachHandler(ApiRootResource.getServletHandler(this)) // These should be POST only, but, the YARN AM proxy won't proxy POSTs attachHandler(createRedirectHandler( "/jobs/job/kill", "/jobs/", jobsTab.handleKillRequest, httpMethods = Set("GET", "POST"))) attachHandler(createRedirectHandler( "/stages/stage/kill", "/stages/", stagesTab.handleKillRequest, httpMethods = Set("GET", "POST"))) } initialize() def getSparkUser: String = { environmentListener.systemProperties.toMap.get("user.name").getOrElse("<unknown>") } def getAppName: String = appName def setAppId(id: String): Unit = { appId = id } /** Stop the server behind this web interface. Only valid after bind(). */ override def stop() { super.stop() logInfo("Stopped Spark web UI at %s".format(appUIAddress)) } /** * Return the application UI host:port. This does not include the scheme (http://). */ private[spark] def appUIHostPort = publicHostName + ":" + boundPort private[spark] def appUIAddress = s"http://$appUIHostPort" def getSparkUI(appId: String): Option[SparkUI] = { if (appId == this.appId) Some(this) else None } def getApplicationInfoList: Iterator[ApplicationInfo] = { Iterator(new ApplicationInfo( id = appId, name = appName, coresGranted = None, maxCores = None, coresPerExecutor = None, memoryPerExecutorMB = None, attempts = Seq(new ApplicationAttemptInfo( attemptId = None, startTime = new Date(startTime), endTime = new Date(-1), duration = 0, lastUpdated = new Date(startTime), sparkUser = "", completed = false )) )) } def getApplicationInfo(appId: String): Option[ApplicationInfo] = { getApplicationInfoList.find(_.id == appId) } } private[spark] abstract class SparkUITab(parent: SparkUI, prefix: String) extends WebUITab(parent, prefix) { def appName: String = parent.getAppName } private[spark] object SparkUI { val DEFAULT_PORT = 4040 val STATIC_RESOURCE_DIR = "org/apache/spark/ui/static" val DEFAULT_POOL_NAME = "default" val DEFAULT_RETAINED_STAGES = 1000 val DEFAULT_RETAINED_JOBS = 1000 def getUIPort(conf: SparkConf): Int = { conf.getInt("spark.ui.port", SparkUI.DEFAULT_PORT) } def createLiveUI( sc: SparkContext, conf: SparkConf, listenerBus: SparkListenerBus, jobProgressListener: JobProgressListener, securityManager: SecurityManager, appName: String, startTime: Long): SparkUI = { create(Some(sc), conf, listenerBus, securityManager, appName, jobProgressListener = Some(jobProgressListener), startTime = startTime) } def createHistoryUI( conf: SparkConf, listenerBus: SparkListenerBus, securityManager: SecurityManager, appName: String, basePath: String, startTime: Long): SparkUI = { val sparkUI = create( None, conf, listenerBus, securityManager, appName, basePath, startTime = startTime) val listenerFactories = ServiceLoader.load(classOf[SparkHistoryListenerFactory], Utils.getContextOrSparkClassLoader).asScala listenerFactories.foreach { listenerFactory => val listeners = listenerFactory.createListeners(conf, sparkUI) listeners.foreach(listenerBus.addListener) } sparkUI } /** * Create a new Spark UI. * * @param sc optional SparkContext; this can be None when reconstituting a UI from event logs. * @param jobProgressListener if supplied, this JobProgressListener will be used; otherwise, the * web UI will create and register its own JobProgressListener. */ private def create( sc: Option[SparkContext], conf: SparkConf, listenerBus: SparkListenerBus, securityManager: SecurityManager, appName: String, basePath: String = "", jobProgressListener: Option[JobProgressListener] = None, startTime: Long): SparkUI = { val _jobProgressListener: JobProgressListener = jobProgressListener.getOrElse { val listener = new JobProgressListener(conf) listenerBus.addListener(listener) listener } val environmentListener = new EnvironmentListener val storageStatusListener = new StorageStatusListener(conf) val executorsListener = new ExecutorsListener(storageStatusListener, conf) val storageListener = new StorageListener(storageStatusListener) val operationGraphListener = new RDDOperationGraphListener(conf) listenerBus.addListener(environmentListener) listenerBus.addListener(storageStatusListener) listenerBus.addListener(executorsListener) listenerBus.addListener(storageListener) listenerBus.addListener(operationGraphListener) new SparkUI(sc, conf, securityManager, environmentListener, storageStatusListener, executorsListener, _jobProgressListener, storageListener, operationGraphListener, appName, basePath, startTime) } }
Panos-Bletsos/spark-cost-model-optimizer
core/src/main/scala/org/apache/spark/ui/SparkUI.scala
Scala
apache-2.0
7,951
package controllers import models.Survey import play.api.libs.json._ import play.api.mvc._ object Application extends Controller { def addSurvey = Action(BodyParsers.parse.json) { request => val s = request.body.validate[Survey.Survey] s.fold( errors => { BadRequest(Json.obj("status" -> "OK", "message" -> JsError.toFlatJson(errors))) }, survey => { Survey.addSurvey(survey) Ok(Json.obj("status" -> "OK")) } ) } def getHealthPrediction = Action(BodyParsers.parse.json) { request => val p = request.body.validate[models.SparkEngine.Person] p.fold( errors => BadRequest(Json.obj("status" -> "OK", "message" -> JsError.toFlatJson(errors))), person => { val prediction = models.SparkEngine.getHealthPrediction(models.SparkEngine.Person(person.familySize, person.kids, person.education)) //person(0).toString.toInt, person(1).toString.toInt, person(2).toString.toInt)) //person) Ok(Json.obj("status" -> "OK", "prediction" -> prediction)) } ) } def getWealthPrediction = Action(BodyParsers.parse.json) { request => val p = request.body.validate[models.SparkEngine.Person] p.fold( errors => BadRequest(Json.obj("status" -> "OK", "message" -> JsError.toFlatJson(errors))), person => { val prediction = models.SparkEngine.getWealthPrediction(models.SparkEngine.Person(person.familySize, person.kids, person.education)) Ok(Json.obj("status" -> "OK", "prediction" -> prediction)) } ) } }
geerdink/FortuneTellerApi
app/controllers/Application.scala
Scala
mit
1,559
/* * Copyright 2013 Julian Peeters * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package artisanal.pickle.maker package methods package cls import tags._ import types._ import scala.reflect.internal.pickling._ case class Equals(position: Position, classSym: ClassSym, myPickleBuffer: PickleBuffer, productElement: ProductElement, Boolean: TypeRefTpe_Boolean, Any: TypeRefTpe_Any) { val valSymPosition = position.current ValSym(position, position.current + 1, classSym.position, 2097696L, position.current + 2).write(myPickleBuffer) TermName(position, "equals").write(myPickleBuffer) MethodTpe(position, List(Boolean.position, position.current + 1)).write(myPickleBuffer) ValSym(position, productElement.termNamex1Position, valSymPosition, 2105344L, Any.position).write(myPickleBuffer) }
julianpeeters/artisanal-pickle-maker
src/main/scala/methods/cls/Equals.scala
Scala
apache-2.0
1,322
package mesosphere.mesos import com.google.common.collect.Lists import com.google.protobuf.TextFormat import mesosphere.marathon.state.AppDefinition.VersionInfo.OnlyVersion import mesosphere.marathon.core.task.Task import mesosphere.marathon.state.Container.Docker import mesosphere.marathon.state.Container.Docker.PortMapping import mesosphere.marathon.state.PathId._ import mesosphere.marathon.state.{ AppDefinition, Container, PathId, Timestamp, _ } import mesosphere.marathon.{ MarathonTestHelper, MarathonSpec, Protos } import mesosphere.mesos.protos.{ Resource, TaskID, _ } import org.apache.mesos.Protos.ContainerInfo.DockerInfo import org.apache.mesos.{ Protos => MesosProtos } import org.joda.time.{ DateTime, DateTimeZone } import org.scalatest.Matchers import scala.collection.JavaConverters._ import scala.collection.immutable.Seq class TaskBuilderTest extends MarathonSpec with Matchers { import mesosphere.mesos.protos.Implicits._ test("BuildIfMatches") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = PortDefinitions(8080, 8081) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get assertTaskInfo(taskInfo, taskPorts, offer) assert(!taskInfo.hasLabels) } test("BuildIfMatches with port name and labels") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = Seq( PortDefinition(8080, "tcp", Some("http"), Map("VIP" -> "127.0.0.1:8080")), PortDefinition(8081, "tcp", Some("admin"), Map("VIP" -> "127.0.0.1:8081")) ) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get val discoveryInfo = taskInfo.getDiscovery val discoveryInfoProto = MesosProtos.DiscoveryInfo.newBuilder .setVisibility(MesosProtos.DiscoveryInfo.Visibility.FRAMEWORK) .setName(taskInfo.getName) .setPorts( MesosProtos.Ports.newBuilder .addPorts( MesosProtos.Port.newBuilder.setName("http").setNumber(taskPorts(0)).setProtocol("tcp") .setLabels(MesosProtos.Labels.newBuilder().addLabels( MesosProtos.Label.newBuilder().setKey("VIP").setValue("127.0.0.1:8080") )) ).addPorts( MesosProtos.Port.newBuilder.setName("admin").setNumber(taskPorts(1)).setProtocol("tcp") .setLabels(MesosProtos.Labels.newBuilder().addLabels( MesosProtos.Label.newBuilder().setKey("VIP").setValue("127.0.0.1:8081") )) ) ).build TextFormat.shortDebugString(discoveryInfo) should equal(TextFormat.shortDebugString(discoveryInfoProto)) discoveryInfo should equal(discoveryInfoProto) } test("BuildIfMatches with port name, protocol and labels") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = Seq( PortDefinition(8080, "tcp", Some("http"), Map("VIP" -> "127.0.0.1:8080")), PortDefinition(8081, "udp", Some("admin"), Map("VIP" -> "127.0.0.1:8081")) ) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get val discoveryInfo = taskInfo.getDiscovery val discoveryInfoProto = MesosProtos.DiscoveryInfo.newBuilder .setVisibility(MesosProtos.DiscoveryInfo.Visibility.FRAMEWORK) .setName(taskInfo.getName) .setPorts( MesosProtos.Ports.newBuilder .addPorts( MesosProtos.Port.newBuilder.setName("http").setNumber(taskPorts(0)).setProtocol("tcp") .setLabels(MesosProtos.Labels.newBuilder().addLabels( MesosProtos.Label.newBuilder().setKey("VIP").setValue("127.0.0.1:8080") )) ).addPorts( MesosProtos.Port.newBuilder.setName("admin").setNumber(taskPorts(1)).setProtocol("udp") .setLabels(MesosProtos.Labels.newBuilder().addLabels( MesosProtos.Label.newBuilder().setKey("VIP").setValue("127.0.0.1:8081") )) ) ).build TextFormat.shortDebugString(discoveryInfo) should equal(TextFormat.shortDebugString(discoveryInfoProto)) discoveryInfo should equal(discoveryInfoProto) } test("BuildIfMatches with port mapping with name, protocol and labels") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", container = Some(Container( docker = Some(Docker( network = Some(DockerInfo.Network.BRIDGE), portMappings = Some(Seq( PortMapping( containerPort = 8080, hostPort = 0, servicePort = 9000, protocol = "tcp", name = Some("http"), labels = Map("VIP" -> "127.0.0.1:8080")), PortMapping( containerPort = 8081, hostPort = 0, servicePort = 9001, protocol = "udp", name = Some("admin"), labels = Map("VIP" -> "127.0.0.1:8081")) )) )) ))) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get val discoveryInfo = taskInfo.getDiscovery val discoveryInfoProto = MesosProtos.DiscoveryInfo.newBuilder .setVisibility(MesosProtos.DiscoveryInfo.Visibility.FRAMEWORK) .setName(taskInfo.getName) .setPorts( MesosProtos.Ports.newBuilder .addPorts( MesosProtos.Port.newBuilder.setName("http").setNumber(taskPorts(0)).setProtocol("tcp") .setLabels(MesosProtos.Labels.newBuilder().addLabels( MesosProtos.Label.newBuilder().setKey("VIP").setValue("127.0.0.1:8080") )) ).addPorts( MesosProtos.Port.newBuilder.setName("admin").setNumber(taskPorts(1)).setProtocol("udp") .setLabels(MesosProtos.Labels.newBuilder().addLabels( MesosProtos.Label.newBuilder().setKey("VIP").setValue("127.0.0.1:8081") )) ) ).build TextFormat.shortDebugString(discoveryInfo) should equal(TextFormat.shortDebugString(discoveryInfoProto)) discoveryInfo should equal(discoveryInfoProto) } test("BuildIfMatches works with duplicated resources") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000) .addResources(ScalarResource("cpus", 1)) .addResources(ScalarResource("mem", 128)) .addResources(ScalarResource("disk", 2000)) .build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = PortDefinitions(8080, 8081) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get assertTaskInfo(taskInfo, taskPorts, offer) assert(!taskInfo.hasLabels) } test("build creates task with appropriate resource share") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 2.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = PortDefinitions(8080, 8081) ) ) val Some((taskInfo, _)) = task def resource(name: String): Resource = taskInfo.getResourcesList.asScala.find(_.getName == name).get assert(resource("cpus") == ScalarResource("cpus", 1)) assert(resource("mem") == ScalarResource("mem", 64)) assert(resource("disk") == ScalarResource("disk", 1)) val portsResource: Resource = resource("ports") assert(portsResource.getRanges.getRangeList.asScala.map(range => range.getEnd - range.getBegin + 1).sum == 2) assert(portsResource.getRole == ResourceRole.Unreserved) } // #1583 Do not pass zero disk resource shares to Mesos test("build does set disk resource to zero in TaskInfo") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 2.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), disk = 0.0 ) ) val Some((taskInfo, _)) = task def resourceOpt(name: String) = taskInfo.getResourcesList.asScala.find(_.getName == name) assert(resourceOpt("disk").isEmpty) } test("build creates task with appropriate resource share also preserves role") { val offer = MarathonTestHelper.makeBasicOffer( cpus = 2.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000, role = "marathon" ).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = PortDefinitions(8080, 8081) ), mesosRole = Some("marathon"), acceptedResourceRoles = Some(Set(ResourceRole.Unreserved, "marathon")) ) val Some((taskInfo, _)) = task def resource(name: String): Resource = taskInfo.getResourcesList.asScala.find(_.getName == name).get assert(resource("cpus") == ScalarResource("cpus", 1, "marathon")) assert(resource("mem") == ScalarResource("mem", 64, "marathon")) assert(resource("disk") == ScalarResource("disk", 1, "marathon")) val portsResource: Resource = resource("ports") assert(portsResource.getRanges.getRangeList.asScala.map(range => range.getEnd - range.getBegin + 1).sum == 2) assert(portsResource.getRole == "marathon") } test("build creates task for DOCKER container using named, external [DockerVolume] volumes") { val offer = MarathonTestHelper.makeBasicOffer( cpus = 2.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000 ).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 32.0, executor = "//cmd", portDefinitions = Nil, container = Some(Container( docker = Some(Docker()), // must have this to force docker container serialization `type` = MesosProtos.ContainerInfo.Type.DOCKER, volumes = Seq[Volume]( DockerVolume("/container/path", "namedFoo", MesosProtos.Volume.Mode.RW) ) )) ) ) val Some((taskInfo, _)) = task def resource(name: String): Resource = taskInfo.getResourcesList.asScala.find(_.getName == name).get assert(resource("cpus") == ScalarResource("cpus", 1)) // sanity, we DID match the offer, right? // check protobuf construction, should be a ContainerInfo w/ volumes def vol(name: String): Option[MesosProtos.Volume] = { if (taskInfo.hasContainer) { taskInfo.getContainer.getVolumesList.asScala.find(_.getHostPath == name) } else None } assert(taskInfo.getContainer.getVolumesList.size > 0, "check that container has volumes declared") assert(!taskInfo.getContainer.getDocker.hasVolumeDriver, "docker spec should not define a volume driver") assert(vol("namedFoo").isDefined, s"missing expected volume namedFoo, got instead: ${taskInfo.getContainer.getVolumesList}") } // TODO(jdef) test both dockerhostvol and persistent extvol in the same docker container test("build creates task for DOCKER container using external [DockerVolume] volumes") { val offer = MarathonTestHelper.makeBasicOffer( cpus = 2.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000 ).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 32.0, executor = "//cmd", portDefinitions = Nil, container = Some(Container( `type` = MesosProtos.ContainerInfo.Type.DOCKER, docker = Some(Docker()), // must have this to force docker container serialization volumes = Seq[Volume]( ExternalVolume("/container/path", ExternalVolumeInfo( name = "namedFoo", provider = "dvdi", options = Map[String, String]("dvdi/driver" -> "bar") ), MesosProtos.Volume.Mode.RW), ExternalVolume("/container/path2", ExternalVolumeInfo( name = "namedEdc", provider = "dvdi", options = Map[String, String]("dvdi/driver" -> "ert") ), MesosProtos.Volume.Mode.RO) ) )) ) ) val Some((taskInfo, _)) = task def resource(name: String): Resource = taskInfo.getResourcesList.asScala.find(_.getName == name).get assert(resource("cpus") == ScalarResource("cpus", 1)) // sanity, we DID match the offer, right? // check protobuf construction, should be a ContainerInfo w/ volumes def vol(name: String): Option[MesosProtos.Volume] = { if (taskInfo.hasContainer) { taskInfo.getContainer.getVolumesList.asScala.find(_.getHostPath == name) } else None } assert(taskInfo.getContainer.getVolumesList.size > 0, "check that container has volumes declared") assert(taskInfo.getContainer.getDocker.hasVolumeDriver, "docker spec should define a volume driver") assert(taskInfo.getContainer.getDocker.getVolumeDriver == "ert", "docker spec should choose ert driver") assert(vol("namedFoo").isDefined, s"missing expected volume namedFoo, got instead: ${taskInfo.getContainer.getVolumesList}") assert(vol("namedEdc").isDefined, s"missing expected volume namedFoo, got instead: ${taskInfo.getContainer.getVolumesList}") } test("build creates task for MESOS container using named, external [ExternalVolume] volumes") { val offer = MarathonTestHelper.makeBasicOffer( cpus = 2.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000 ).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 32.0, executor = "/qazwsx", portDefinitions = Nil, container = Some(Container( `type` = MesosProtos.ContainerInfo.Type.MESOS, volumes = Seq[Volume]( ExternalVolume("/container/path", ExternalVolumeInfo( name = "namedFoo", provider = "dvdi", options = Map[String, String]("dvdi/driver" -> "bar") ), MesosProtos.Volume.Mode.RW), ExternalVolume("/container/path2", ExternalVolumeInfo( size = Some(2L), name = "namedEdc", provider = "dvdi", options = Map[String, String]("dvdi/driver" -> "ert") ), MesosProtos.Volume.Mode.RW) ) )) ) ) val Some((taskInfo, _)) = task def resource(name: String): Resource = taskInfo.getResourcesList.asScala.find(_.getName == name).get assert(resource("cpus") == ScalarResource("cpus", 1)) // sanity, we DID match the offer, right? def hasEnv(name: String, value: String): Boolean = taskInfo.getExecutor.getCommand.hasEnvironment && taskInfo.getExecutor.getCommand.getEnvironment.getVariablesList.asScala.find{ ev => ev.getName == name && ev.getValue == value }.isDefined def missingEnv(name: String): Boolean = taskInfo.getExecutor.getCommand.hasEnvironment && taskInfo.getExecutor.getCommand.getEnvironment.getVariablesList.asScala.find{ ev => ev.getName == name }.isEmpty taskInfo.hasContainer should be (false) taskInfo.hasCommand should be (false) taskInfo.getExecutor.hasContainer should be (true) taskInfo.getExecutor.getContainer.hasMesos should be (true) // check protobuf construction, should be a ContainerInfo w/ no volumes, w/ envvar assert(taskInfo.getExecutor.getContainer.getVolumesList.isEmpty, "check that container has no volumes declared") assert(hasEnv("DVDI_VOLUME_NAME", "namedFoo"), s"missing expected command w/ envvar declaring volume namedFoo, got instead: ${taskInfo.getExecutor.getCommand}") assert(hasEnv("DVDI_VOLUME_DRIVER", "bar"), s"missing expected command w/ envvar declaring volume namedFoo, got instead: ${taskInfo.getExecutor.getCommand}") assert(missingEnv("DVDI_VOLUME_OPTS"), s"has unexpected command w/ envvar declaring volume namedFoo, got instead: ${taskInfo.getExecutor.getCommand}") assert(hasEnv("DVDI_VOLUME_NAME1", "namedEdc"), s"missing expected command w/ envvar declaring volume namedEdc, got instead: ${taskInfo.getExecutor.getCommand}") assert(hasEnv("DVDI_VOLUME_DRIVER1", "ert"), s"missing expected command w/ envvar declaring volume namedEdc, got instead: ${taskInfo.getExecutor.getCommand}") assert(hasEnv("DVDI_VOLUME_OPTS1", "size=2"), s"missing expected command w/ envvar declaring volume namedEdc, got instead: ${taskInfo.getExecutor.getCommand}") assert(missingEnv("DVDI_VOLUME_NAME2"), s"has unexpected command w/ envvar declaring volume namedFoo, got instead: ${taskInfo.getExecutor.getCommand}") } test("BuildIfMatchesWithLabels") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val labels = Map("foo" -> "bar", "test" -> "test") val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = PortDefinitions(8080, 8081), labels = labels ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get assertTaskInfo(taskInfo, taskPorts, offer) val expectedLabels = MesosProtos.Labels.newBuilder.addAllLabels( labels.map { case (mKey, mValue) => MesosProtos.Label.newBuilder.setKey(mKey).setValue(mValue).build() }.asJava ).build() assert(taskInfo.hasLabels) assert(taskInfo.getLabels == expectedLabels) } test("BuildIfMatchesWithArgs") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "testApp".toPath, args = Some(Seq("a", "b", "c")), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = PortDefinitions(8080, 8081) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get val rangeResourceOpt = taskInfo.getResourcesList.asScala.find(r => r.getName == Resource.PORTS) val ranges = rangeResourceOpt.fold(Seq.empty[MesosProtos.Value.Range])(_.getRanges.getRangeList.asScala.to[Seq]) val rangePorts = ranges.flatMap(r => r.getBegin to r.getEnd).toSet assert(2 == rangePorts.size) assert(2 == taskPorts.size) assert(taskPorts.toSet == rangePorts.toSet) assert(!taskInfo.hasExecutor) assert(taskInfo.hasCommand) val cmd = taskInfo.getCommand assert(!cmd.getShell) assert(cmd.hasValue) assert(cmd.getArgumentsList.asScala == Seq("a", "b", "c")) for (r <- taskInfo.getResourcesList.asScala) { assert(ResourceRole.Unreserved == r.getRole) } // TODO test for resources etc. } test("BuildIfMatchesWithIpAddress") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "testApp".toPath, args = Some(Seq("a", "b", "c")), cpus = 1.0, mem = 64.0, disk = 1.0, portDefinitions = Nil, ipAddress = Some( IpAddress( groups = Seq("a", "b", "c"), labels = Map( "foo" -> "bar", "baz" -> "buzz" ) ) ) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get taskInfo.hasExecutor should be (false) taskInfo.hasContainer should be (true) val networkInfos = taskInfo.getContainer.getNetworkInfosList.asScala networkInfos.size should be (1) val networkInfoProto = MesosProtos.NetworkInfo.newBuilder .addIpAddresses(MesosProtos.NetworkInfo.IPAddress.getDefaultInstance) .addAllGroups(Seq("a", "b", "c").asJava) .setLabels( MesosProtos.Labels.newBuilder.addAllLabels( Seq( MesosProtos.Label.newBuilder.setKey("foo").setValue("bar").build, MesosProtos.Label.newBuilder.setKey("baz").setValue("buzz").build ).asJava )) .build TextFormat.shortDebugString(networkInfos.head) should equal(TextFormat.shortDebugString(networkInfoProto)) networkInfos.head should equal(networkInfoProto) } test("BuildIfMatchesWithIpAddressAndCustomExecutor") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "testApp".toPath, args = Some(Seq("a", "b", "c")), cpus = 1.0, mem = 64.0, disk = 1.0, executor = "/custom/executor", portDefinitions = Nil, ipAddress = Some( IpAddress( groups = Seq("a", "b", "c"), labels = Map( "foo" -> "bar", "baz" -> "buzz" ) ) ) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get taskInfo.hasContainer should be (false) taskInfo.hasExecutor should be (true) taskInfo.getExecutor.hasContainer should be (true) val networkInfos = taskInfo.getExecutor.getContainer.getNetworkInfosList.asScala networkInfos.size should be (1) val networkInfoProto = MesosProtos.NetworkInfo.newBuilder .addIpAddresses(MesosProtos.NetworkInfo.IPAddress.getDefaultInstance) .addAllGroups(Seq("a", "b", "c").asJava) .setLabels( MesosProtos.Labels.newBuilder.addAllLabels( Seq( MesosProtos.Label.newBuilder.setKey("foo").setValue("bar").build, MesosProtos.Label.newBuilder.setKey("baz").setValue("buzz").build ).asJava )) .build TextFormat.shortDebugString(networkInfos.head) should equal(TextFormat.shortDebugString(networkInfoProto)) networkInfos.head should equal(networkInfoProto) taskInfo.hasDiscovery should be (true) taskInfo.getDiscovery.getName should be (taskInfo.getName) } test("BuildIfMatchesWithIpAddressAndDiscoveryInfo") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, args = Some(Seq("a", "b", "c")), cpus = 1.0, mem = 64.0, disk = 1.0, portDefinitions = Nil, ipAddress = Some( IpAddress( groups = Seq("a", "b", "c"), labels = Map( "foo" -> "bar", "baz" -> "buzz" ), discoveryInfo = DiscoveryInfo( ports = Seq(DiscoveryInfo.Port(name = "http", number = 80, protocol = "tcp")) ) ) ) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get taskInfo.hasExecutor should be (false) taskInfo.hasContainer should be (true) val networkInfos = taskInfo.getContainer.getNetworkInfosList.asScala networkInfos.size should be (1) val networkInfoProto = MesosProtos.NetworkInfo.newBuilder .addIpAddresses(MesosProtos.NetworkInfo.IPAddress.getDefaultInstance) .addAllGroups(Seq("a", "b", "c").asJava) .setLabels( MesosProtos.Labels.newBuilder.addAllLabels( Seq( MesosProtos.Label.newBuilder.setKey("foo").setValue("bar").build, MesosProtos.Label.newBuilder.setKey("baz").setValue("buzz").build ).asJava )) .build TextFormat.shortDebugString(networkInfos.head) should equal(TextFormat.shortDebugString(networkInfoProto)) networkInfos.head should equal(networkInfoProto) taskInfo.hasDiscovery should be (true) val discoveryInfo = taskInfo.getDiscovery val discoveryInfoProto = MesosProtos.DiscoveryInfo.newBuilder .setVisibility(MesosProtos.DiscoveryInfo.Visibility.FRAMEWORK) .setName(taskInfo.getName) .setPorts( MesosProtos.Ports.newBuilder .addPorts( MesosProtos.Port.newBuilder .setName("http") .setNumber(80) .setProtocol("tcp") .build) .build) .build TextFormat.shortDebugString(discoveryInfo) should equal(TextFormat.shortDebugString(discoveryInfoProto)) discoveryInfo should equal(discoveryInfoProto) } test("BuildIfMatchesWithCommandAndExecutor") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000) .addResources(ScalarResource("cpus", 1)) .addResources(ScalarResource("mem", 128)) .addResources(ScalarResource("disk", 2000)) .build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "testApp".toPath, cpus = 1.0, mem = 64.0, disk = 1.0, cmd = Some("foo"), executor = "/custom/executor", portDefinitions = PortDefinitions(8080, 8081) ) ) assert(task.isDefined) val (taskInfo, _) = task.get assert(taskInfo.hasExecutor) assert(!taskInfo.hasCommand) val cmd = taskInfo.getExecutor.getCommand assert(cmd.getShell) assert(cmd.hasValue) assert(cmd.getArgumentsList.asScala.isEmpty) assert(cmd.getValue == "chmod ug+rx '/custom/executor' && exec '/custom/executor' foo") } test("BuildIfMatchesWithArgsAndExecutor") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 1.0, mem = 128.0, disk = 2000.0, beginPort = 31000, endPort = 32000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "testApp".toPath, cpus = 1.0, mem = 64.0, disk = 1.0, args = Some(Seq("a", "b", "c")), executor = "/custom/executor", portDefinitions = PortDefinitions(8080, 8081) ) ) assert(task.isDefined) val (taskInfo, _) = task.get val cmd = taskInfo.getExecutor.getCommand assert(!taskInfo.hasCommand) assert(cmd.getValue == "chmod ug+rx '/custom/executor' && exec '/custom/executor' a b c") } test("BuildIfMatchesWithRole") { val offer = MarathonTestHelper.makeBasicOfferWithRole(cpus = 1.0, mem = 128.0, disk = 1000.0, beginPort = 31000, endPort = 32000, role = "marathon") .addResources(ScalarResource("cpus", 1, ResourceRole.Unreserved)) .addResources(ScalarResource("mem", 128, ResourceRole.Unreserved)) .addResources(ScalarResource("disk", 1000, ResourceRole.Unreserved)) .addResources(ScalarResource("cpus", 2, "marathon")) .addResources(ScalarResource("mem", 256, "marathon")) .addResources(ScalarResource("disk", 2000, "marathon")) .addResources(RangesResource(Resource.PORTS, Seq(protos.Range(33000, 34000)), "marathon")) .build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "testApp".toPath, cpus = 2.0, mem = 200.0, disk = 2.0, executor = "//cmd", portDefinitions = PortDefinitions(8080, 8081) ), mesosRole = Some("marathon"), acceptedResourceRoles = Some(Set("marathon")) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get val ports = taskInfo.getResourcesList.asScala .find(r => r.getName == Resource.PORTS) .map(r => r.getRanges.getRangeList.asScala.flatMap(range => range.getBegin to range.getEnd)) .getOrElse(Seq.empty) assert(ports == taskPorts) for (r <- taskInfo.getResourcesList.asScala) { assert("marathon" == r.getRole) } // TODO test for resources etc. } test("BuildIfMatchesWithRole2") { val offer = MarathonTestHelper.makeBasicOfferWithRole(cpus = 1.0, mem = 128.0, disk = 1000.0, beginPort = 31000, endPort = 32000, role = ResourceRole.Unreserved) .addResources(ScalarResource("cpus", 1, ResourceRole.Unreserved)) .addResources(ScalarResource("mem", 128, ResourceRole.Unreserved)) .addResources(ScalarResource("disk", 1000, ResourceRole.Unreserved)) .addResources(ScalarResource("cpus", 2, "marathon")) .addResources(ScalarResource("mem", 256, "marathon")) .addResources(ScalarResource("disk", 2000, "marathon")) .addResources(RangesResource(Resource.PORTS, Seq(protos.Range(33000, 34000)), "marathon")) .build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "testApp".toPath, cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", portDefinitions = PortDefinitions(8080, 8081) ) ) assert(task.isDefined) val (taskInfo, taskPorts) = task.get val ports = taskInfo.getResourcesList.asScala .find(r => r.getName == Resource.PORTS) .map(r => r.getRanges.getRangeList.asScala.flatMap(range => range.getBegin to range.getEnd)) .getOrElse(Seq.empty) assert(ports == taskPorts) // In this case, the first roles are sufficient so we'll use those first. for (r <- taskInfo.getResourcesList.asScala) { assert(ResourceRole.Unreserved == r.getRole) } // TODO test for resources etc. } test("PortMappingsWithZeroContainerPort") { val offer = MarathonTestHelper.makeBasicOfferWithRole( cpus = 1.0, mem = 128.0, disk = 1000.0, beginPort = 31000, endPort = 31000, role = ResourceRole.Unreserved ) .addResources(RangesResource(Resource.PORTS, Seq(protos.Range(33000, 34000)), "marathon")) .build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "testApp".toPath, cpus = 1.0, mem = 64.0, disk = 1.0, executor = "//cmd", container = Some(Container( docker = Some(Docker( network = Some(DockerInfo.Network.BRIDGE), portMappings = Some(Seq( PortMapping(containerPort = 0, hostPort = 0, servicePort = 9000, protocol = "tcp") )) )) )) ) ) assert(task.isDefined) val (taskInfo, _) = task.get val hostPort = taskInfo.getContainer.getDocker.getPortMappings(0).getHostPort assert(hostPort == 31000) val containerPort = taskInfo.getContainer.getDocker.getPortMappings(0).getContainerPort assert(containerPort == hostPort) } test("BuildIfMatchesWithRackIdConstraint") { val offer = MarathonTestHelper.makeBasicOffer(1.0, 128.0, 31000, 32000) .addAttributes(TextAttribute("rackid", "1")) .build val app = MarathonTestHelper.makeBasicApp().copy( constraints = Set( Protos.Constraint.newBuilder .setField("rackid") .setOperator(Protos.Constraint.Operator.UNIQUE) .build() ) ) val t1 = makeSampleTask(app.id, "rackid", "2") val t2 = makeSampleTask(app.id, "rackid", "3") val s = Set(t1, t2) val builder = new TaskBuilder(app, s => Task.Id(s.toString), MarathonTestHelper.defaultConfig()) val task = builder.buildIfMatches(offer, s) assert(task.isDefined) // TODO test for resources etc. } test("RackAndHostConstraints") { // Test the case where we want tasks to be balanced across racks/AZs // and run only one per machine val app = MarathonTestHelper.makeBasicApp().copy( instances = 10, versionInfo = OnlyVersion(Timestamp(10)), constraints = Set( Protos.Constraint.newBuilder.setField("rackid").setOperator(Protos.Constraint.Operator.GROUP_BY).setValue("3").build, Protos.Constraint.newBuilder.setField("hostname").setOperator(Protos.Constraint.Operator.UNIQUE).build ) ) var runningTasks = Set.empty[Task] val builder = new TaskBuilder(app, s => Task.Id(s.toString), MarathonTestHelper.defaultConfig()) def shouldBuildTask(message: String, offer: Offer) { val Some((taskInfo, ports)) = builder.buildIfMatches(offer, runningTasks) val marathonTask = MarathonTestHelper.makeTaskFromTaskInfo(taskInfo, offer) runningTasks += marathonTask } def shouldNotBuildTask(message: String, offer: Offer) { val tupleOption = builder.buildIfMatches(offer, runningTasks) assert(tupleOption.isEmpty, message) } val offerRack1HostA = MarathonTestHelper.makeBasicOffer() .setHostname("alpha") .addAttributes(TextAttribute("rackid", "1")) .build shouldBuildTask("Should take first offer", offerRack1HostA) val offerRack1HostB = MarathonTestHelper.makeBasicOffer() .setHostname("beta") .addAttributes(TextAttribute("rackid", "1")) .build shouldNotBuildTask("Should not take offer for the same rack", offerRack1HostB) val offerRack2HostC = MarathonTestHelper.makeBasicOffer() .setHostname("gamma") .addAttributes(TextAttribute("rackid", "2")) .build shouldBuildTask("Should take offer for different rack", offerRack2HostC) // Nothing prevents having two hosts with the same name in different racks val offerRack3HostA = MarathonTestHelper.makeBasicOffer() .setHostname("alpha") .addAttributes(TextAttribute("rackid", "3")) .build shouldNotBuildTask("Should not take offer in different rack with non-unique hostname", offerRack3HostA) } test("UniqueHostNameAndClusterAttribute") { val app = MarathonTestHelper.makeBasicApp().copy( instances = 10, constraints = Set( Protos.Constraint.newBuilder.setField("spark").setOperator(Protos.Constraint.Operator.CLUSTER).setValue("enabled").build, Protos.Constraint.newBuilder.setField("hostname").setOperator(Protos.Constraint.Operator.UNIQUE).build ) ) var runningTasks = Set.empty[Task] val builder = new TaskBuilder(app, s => Task.Id(s.toString), MarathonTestHelper.defaultConfig()) def shouldBuildTask(message: String, offer: Offer) { val Some((taskInfo, ports)) = builder.buildIfMatches(offer, runningTasks) val marathonTask = MarathonTestHelper.makeTaskFromTaskInfo(taskInfo, offer) runningTasks += marathonTask } def shouldNotBuildTask(message: String, offer: Offer) { val tupleOption = builder.buildIfMatches(offer, runningTasks) assert(tupleOption.isEmpty, message) } val offerHostA = MarathonTestHelper.makeBasicOffer() .setHostname("alpha") .addAttributes(TextAttribute("spark", "disabled")) .build shouldNotBuildTask("Should not take an offer with spark:disabled", offerHostA) val offerHostB = MarathonTestHelper.makeBasicOffer() .setHostname("beta") .addAttributes(TextAttribute("spark", "enabled")) .build shouldBuildTask("Should take offer with spark:enabled", offerHostB) } test("PortsEnv") { val env = TaskBuilder.portsEnv(Seq(0, 0), Seq(1001, 1002), Seq(None, None)) assert("1001" == env("PORT")) assert("1001" == env("PORT0")) assert("1002" == env("PORT1")) assert(!env.contains("PORT_0")) } test("PortsEnvEmpty") { val env = TaskBuilder.portsEnv(Seq(), Seq(), Seq()) assert(Map.empty == env) } test("PortsNamedEnv") { val env = TaskBuilder.portsEnv(Seq(0, 0), Seq(1001, 1002), Seq(Some("http"), Some("https"))) assert("1001" == env("PORT")) assert("1001" == env("PORT0")) assert("1002" == env("PORT1")) assert("1001" == env("PORT_HTTP")) assert("1002" == env("PORT_HTTPS")) } test("DeclaredPortsEnv") { val env = TaskBuilder.portsEnv(Seq(80, 8080), Seq(1001, 1002), Seq(None, None)) assert("1001" == env("PORT")) assert("1001" == env("PORT0")) assert("1002" == env("PORT1")) assert("1001" == env("PORT_80")) assert("1002" == env("PORT_8080")) } test("DeclaredPortsEnvNamed") { val env = TaskBuilder.portsEnv(Seq(80, 8080, 443), Seq(1001, 1002, 1003), Seq(Some("http"), None, Some("https"))) assert("1001" == env("PORT")) assert("1001" == env("PORT0")) assert("1002" == env("PORT1")) assert("1003" == env("PORT2")) assert("1001" == env("PORT_80")) assert("1002" == env("PORT_8080")) assert("1003" == env("PORT_443")) assert("1001" == env("PORT_HTTP")) assert("1003" == env("PORT_HTTPS")) } test("TaskContextEnv empty when no taskId given") { val version = AppDefinition.VersionInfo.forNewConfig(Timestamp(new DateTime(2015, 2, 3, 12, 30, DateTimeZone.UTC))) val app = AppDefinition( id = PathId("/app"), versionInfo = version ) val env = TaskBuilder.taskContextEnv(app = app, taskId = None) assert(env == Map.empty) } test("TaskContextEnv minimal") { val version = AppDefinition.VersionInfo.forNewConfig(Timestamp(new DateTime(2015, 2, 3, 12, 30, DateTimeZone.UTC))) val app = AppDefinition( id = PathId("/app"), versionInfo = version ) val env = TaskBuilder.taskContextEnv(app = app, taskId = Some(Task.Id("taskId"))) assert( env == Map( "MESOS_TASK_ID" -> "taskId", "MARATHON_APP_ID" -> "/app", "MARATHON_APP_VERSION" -> "2015-02-03T12:30:00.000Z", "MARATHON_APP_RESOURCE_CPUS" -> AppDefinition.DefaultCpus.toString, "MARATHON_APP_RESOURCE_MEM" -> AppDefinition.DefaultMem.toString, "MARATHON_APP_RESOURCE_DISK" -> AppDefinition.DefaultDisk.toString, "MARATHON_APP_LABELS" -> "" ) ) } test("TaskContextEnv all fields") { val version = AppDefinition.VersionInfo.forNewConfig(Timestamp(new DateTime(2015, 2, 3, 12, 30, DateTimeZone.UTC))) val taskId = TaskID("taskId") val app = AppDefinition( id = PathId("/app"), versionInfo = version, container = Some(Container( docker = Some(Docker( image = "myregistry/myimage:version" )) )), cpus = 10.0, mem = 256.0, disk = 128.0, labels = Map( "LABEL1" -> "VALUE1", "LABEL2" -> "VALUE2" ) ) val env = TaskBuilder.taskContextEnv(app = app, Some(Task.Id(taskId))) assert( env == Map( "MESOS_TASK_ID" -> "taskId", "MARATHON_APP_ID" -> "/app", "MARATHON_APP_VERSION" -> "2015-02-03T12:30:00.000Z", "MARATHON_APP_DOCKER_IMAGE" -> "myregistry/myimage:version", "MARATHON_APP_RESOURCE_CPUS" -> "10.0", "MARATHON_APP_RESOURCE_MEM" -> "256.0", "MARATHON_APP_RESOURCE_DISK" -> "128.0", "MARATHON_APP_LABELS" -> "LABEL1 LABEL2", "MARATHON_APP_LABEL_LABEL1" -> "VALUE1", "MARATHON_APP_LABEL_LABEL2" -> "VALUE2" ) ) } test("TaskContextEnv will provide label env safety") { // will exceed max length for sure val longLabel = "longlabel" * TaskBuilder.maxVariableLength var longValue = "longvalue" * TaskBuilder.maxEnvironmentVarLength val app = AppDefinition( labels = Map( "label" -> "VALUE1", "label-with-invalid-chars" -> "VALUE2", "other--label\\\\--\\\\a" -> "VALUE3", longLabel -> "value for long label", "label-long" -> longValue ) ) val env = TaskBuilder.taskContextEnv(app = app, Some(Task.Id("taskId"))) .filterKeys(_.startsWith("MARATHON_APP_LABEL")) assert( env == Map( "MARATHON_APP_LABELS" -> "OTHER_LABEL_A LABEL LABEL_WITH_INVALID_CHARS", "MARATHON_APP_LABEL_LABEL" -> "VALUE1", "MARATHON_APP_LABEL_LABEL_WITH_INVALID_CHARS" -> "VALUE2", "MARATHON_APP_LABEL_OTHER_LABEL_A" -> "VALUE3" ) ) } test("AppContextEnvironment") { val command = TaskBuilder.commandInfo( app = AppDefinition( id = "/test".toPath, portDefinitions = PortDefinitions(8080, 8081), container = Some(Container( docker = Some(Docker( image = "myregistry/myimage:version" )) ) ) ), taskId = Some(Task.Id("task-123")), host = Some("host.mega.corp"), ports = Seq(1000, 1001), envPrefix = None ) val env: Map[String, String] = command.getEnvironment.getVariablesList.asScala.toList.map(v => v.getName -> v.getValue).toMap assert("task-123" == env("MESOS_TASK_ID")) assert("/test" == env("MARATHON_APP_ID")) assert("1970-01-01T00:00:00.000Z" == env("MARATHON_APP_VERSION")) assert("myregistry/myimage:version" == env("MARATHON_APP_DOCKER_IMAGE")) } test("user defined variables override automatic port variables") { // why? // see https://github.com/mesosphere/marathon/issues/905 val command = TaskBuilder.commandInfo( app = AppDefinition( id = "/test".toPath, portDefinitions = PortDefinitions(8080, 8081), env = Map( "PORT" -> "1", "PORTS" -> "ports", "PORT0" -> "1", "PORT1" -> "2", "PORT_8080" -> "port8080", "PORT_8081" -> "port8081" ) ), taskId = Some(Task.Id("task-123")), host = Some("host.mega.corp"), ports = Seq(1000, 1001), envPrefix = None ) val env: Map[String, String] = command.getEnvironment.getVariablesList.asScala.toList.map(v => v.getName -> v.getValue).toMap assert("1" == env("PORT")) assert("ports" == env("PORTS")) assert("1" == env("PORT0")) assert("2" == env("PORT1")) assert("port8080" == env("PORT_8080")) assert("port8081" == env("PORT_8081")) } test("PortsEnvWithOnlyPorts") { val command = TaskBuilder.commandInfo( app = AppDefinition( portDefinitions = PortDefinitions(8080, 8081) ), taskId = Some(Task.Id("task-123")), host = Some("host.mega.corp"), ports = Seq(1000, 1001), envPrefix = None ) val env: Map[String, String] = command.getEnvironment.getVariablesList.asScala.toList.map(v => v.getName -> v.getValue).toMap assert("1000" == env("PORT_8080")) assert("1001" == env("PORT_8081")) } test("PortsEnvWithCustomPrefix") { val command = TaskBuilder.commandInfo( AppDefinition( portDefinitions = PortDefinitions(8080, 8081) ), Some(Task.Id("task-123")), Some("host.mega.corp"), Seq(1000, 1001), Some("CUSTOM_PREFIX_") ) val env: Map[String, String] = command.getEnvironment.getVariablesList.asScala.toList.map(v => v.getName -> v.getValue).toMap assert("1000,1001" == env("CUSTOM_PREFIX_PORTS")) assert("1000" == env("CUSTOM_PREFIX_PORT")) assert("1000" == env("CUSTOM_PREFIX_PORT0")) assert("1000" == env("CUSTOM_PREFIX_PORT_8080")) assert("1001" == env("CUSTOM_PREFIX_PORT1")) assert("1001" == env("CUSTOM_PREFIX_PORT_8081")) assert("host.mega.corp" == env("CUSTOM_PREFIX_HOST")) assert(Seq("HOST", "PORTS", "PORT0", "PORT1").forall(k => !env.contains(k))) assert(Seq("MESOS_TASK_ID", "MARATHON_APP_ID", "MARATHON_APP_VERSION").forall(env.contains)) } test("OnlyWhitelistedUnprefixedVariablesWithCustomPrefix") { val command = TaskBuilder.commandInfo( AppDefinition( portDefinitions = PortDefinitions(8080, 8081) ), Some(Task.Id("task-123")), Some("host.mega.corp"), Seq(1000, 1001), Some("P_") ) val env: Map[String, String] = command.getEnvironment.getVariablesList.asScala.toList.map(v => v.getName -> v.getValue).toMap val nonPrefixedEnvVars = env.filterKeys(!_.startsWith("P_")) val whiteList = Seq("MESOS_TASK_ID", "MARATHON_APP_ID", "MARATHON_APP_VERSION", "MARATHON_APP_RESOURCE_CPUS", "MARATHON_APP_RESOURCE_MEM", "MARATHON_APP_RESOURCE_DISK", "MARATHON_APP_LABELS") assert(nonPrefixedEnvVars.keySet.forall(whiteList.contains)) } test("PortsEnvWithOnlyMappings") { val command = TaskBuilder.commandInfo( app = AppDefinition( container = Some(Container( docker = Some(Docker( network = Some(DockerInfo.Network.BRIDGE), portMappings = Some(Seq( PortMapping(containerPort = 8080, hostPort = 0, servicePort = 9000, protocol = "tcp"), PortMapping(containerPort = 8081, hostPort = 0, servicePort = 9000, protocol = "tcp") )) )) )) ), taskId = Some(Task.Id("task-123")), host = Some("host.mega.corp"), ports = Seq(1000, 1001), envPrefix = None ) val env: Map[String, String] = command.getEnvironment.getVariablesList.asScala.toList.map(v => v.getName -> v.getValue).toMap assert("1000" == env("PORT_8080")) assert("1001" == env("PORT_8081")) } test("PortsEnvWithBothPortsAndMappings") { val command = TaskBuilder.commandInfo( app = AppDefinition( portDefinitions = PortDefinitions(22, 23), container = Some(Container( docker = Some(Docker( network = Some(DockerInfo.Network.BRIDGE), portMappings = Some(Seq( PortMapping(containerPort = 8080, hostPort = 0, servicePort = 9000, protocol = "tcp"), PortMapping(containerPort = 8081, hostPort = 0, servicePort = 9000, protocol = "tcp") )) )) )) ), taskId = Some(Task.Id("task-123")), host = Some("host.mega.corp"), ports = Seq(1000, 1001), envPrefix = None ) val env: Map[String, String] = command.getEnvironment.getVariablesList.asScala.toList.map(v => v.getName -> v.getValue).toMap assert("1000" == env("PORT_8080")) assert("1001" == env("PORT_8081")) assert(!env.contains("PORT_22")) assert(!env.contains("PORT_23")) } test("TaskWillCopyFetchIntoCommand") { val command = TaskBuilder.commandInfo( app = AppDefinition( fetch = Seq( FetchUri(uri = "http://www.example.com", extract = false, cache = true, executable = false), FetchUri(uri = "http://www.example2.com", extract = true, cache = true, executable = true) ) ), taskId = Some(Task.Id("task-123")), host = Some("host.mega.corp"), ports = Seq(1000, 1001), envPrefix = None ) assert(command.getUris(0).getValue.contentEquals("http://www.example.com")) assert(command.getUris(0).getCache) assert(!command.getUris(0).getExtract) assert(!command.getUris(0).getExecutable) assert(command.getUris(1).getValue.contentEquals("http://www.example2.com")) assert(command.getUris(1).getCache) assert(command.getUris(1).getExtract) assert(command.getUris(1).getExecutable) } // #2865 Multiple explicit ports are mixed up in task json test("build with requirePorts preserves the port order") { val offer = MarathonTestHelper.makeBasicOffer(cpus = 2.0, mem = 128.0, disk = 2000.0, beginPort = 25000, endPort = 26000).build val task: Option[(MesosProtos.TaskInfo, Seq[Int])] = buildIfMatches( offer, AppDefinition( id = "/product/frontend".toPath, cmd = Some("foo"), portDefinitions = PortDefinitions(25552, 25551), requirePorts = true ) ) val Some((taskInfo, _)) = task val env: Map[String, String] = taskInfo.getCommand.getEnvironment.getVariablesList.asScala.toList.map(v => v.getName -> v.getValue).toMap assert("25552" == env("PORT0")) assert("25552" == env("PORT_25552")) assert("25551" == env("PORT1")) assert("25551" == env("PORT_25551")) val portsFromTaskInfo = { val asScalaRanges = for { resource <- taskInfo.getResourcesList.asScala if resource.getName == Resource.PORTS range <- resource.getRanges.getRangeList.asScala } yield range.getBegin to range.getEnd asScalaRanges.flatMap(_.iterator).toList } assert(portsFromTaskInfo == Seq(25552, 25551)) } def buildIfMatches( offer: Offer, app: AppDefinition, mesosRole: Option[String] = None, acceptedResourceRoles: Option[Set[String]] = None, envVarsPrefix: Option[String] = None) = { val builder = new TaskBuilder(app, s => Task.Id(s.toString), MarathonTestHelper.defaultConfig( mesosRole = mesosRole, acceptedResourceRoles = acceptedResourceRoles, envVarsPrefix = envVarsPrefix)) builder.buildIfMatches(offer, Iterable.empty) } def makeSampleTask(id: PathId, attr: String, attrVal: String) = { import MarathonTestHelper.Implicits._ MarathonTestHelper .stagedTask(taskId = id.toString) .withAgentInfo(_.copy(attributes = Iterable(TextAttribute(attr, attrVal)))) .withHostPorts(Seq(999)) } private def assertTaskInfo(taskInfo: MesosProtos.TaskInfo, taskPorts: Seq[Int], offer: Offer): Unit = { val portsFromTaskInfo = { val asScalaRanges = for { resource <- taskInfo.getResourcesList.asScala if resource.getName == Resource.PORTS range <- resource.getRanges.getRangeList.asScala } yield range.getBegin to range.getEnd asScalaRanges.flatMap(_.iterator).toSet } assert(portsFromTaskInfo == taskPorts.toSet) // The taskName is the elements of the path, reversed, and joined by dots assert("frontend.product" == taskInfo.getName) assert(!taskInfo.hasExecutor) assert(taskInfo.hasCommand) val cmd = taskInfo.getCommand assert(cmd.getShell) assert(cmd.hasValue) assert(cmd.getArgumentsList.asScala.isEmpty) assert(cmd.getValue == "foo") assert(cmd.hasEnvironment) val envVars = cmd.getEnvironment.getVariablesList.asScala assert(envVars.exists(v => v.getName == "HOST" && v.getValue == offer.getHostname)) assert(envVars.exists(v => v.getName == "PORT0" && v.getValue.nonEmpty)) assert(envVars.exists(v => v.getName == "PORT1" && v.getValue.nonEmpty)) assert(envVars.exists(v => v.getName == "PORT_8080" && v.getValue.nonEmpty)) assert(envVars.exists(v => v.getName == "PORT_8081" && v.getValue.nonEmpty)) val exposesFirstPort = envVars.find(v => v.getName == "PORT0").get.getValue == envVars.find(v => v.getName == "PORT_8080").get.getValue assert(exposesFirstPort) val exposesSecondPort = envVars.find(v => v.getName == "PORT1").get.getValue == envVars.find(v => v.getName == "PORT_8081").get.getValue assert(exposesSecondPort) for (r <- taskInfo.getResourcesList.asScala) { assert(ResourceRole.Unreserved == r.getRole) } assert(taskInfo.hasDiscovery) val discoveryInfo = taskInfo.getDiscovery val discoveryInfoProto = MesosProtos.DiscoveryInfo.newBuilder .setVisibility(MesosProtos.DiscoveryInfo.Visibility.FRAMEWORK) .setName(taskInfo.getName) .setPorts( MesosProtos.Ports.newBuilder .addPorts(MesosProtos.Port.newBuilder.setNumber(taskPorts(0)).setProtocol("tcp")) .addPorts(MesosProtos.Port.newBuilder.setNumber(taskPorts(1)).setProtocol("tcp")) ).build TextFormat.shortDebugString(discoveryInfo) should equal(TextFormat.shortDebugString(discoveryInfoProto)) discoveryInfo should equal(discoveryInfoProto) // TODO test for resources etc. } }
titosand/marathon
src/test/scala/mesosphere/mesos/TaskBuilderTest.scala
Scala
apache-2.0
54,107
import com.thesamet.pb.{MyMap, MyVector} import com.thesamet.proto.e2e.collection_types._ import org.scalatest._ import scala.collection.mutable class CollectionTypesSpec extends FlatSpec with MustMatchers { "lenses" should "compile" in { val cis = CollectionTypesMessage().update(_.repeatedInt32 :++= Seq(11, 9)) val cv = CollectionTypesVector().update(_.repeatedInt32 :++= Seq(11, 9)) val cl = CollectionTypesList().update(_.repeatedInt32 :++= Seq(11, 9)) val cs = CollectionTypesSet().update(_.repeatedInt32 :++= Seq(11, 9)) cis.repeatedInt32 must be (a[collection.immutable.Seq[_]]) cv.repeatedInt32 must be (a[Vector[_]]) cl.repeatedInt32 must be (a[List[_]]) cs.repeatedInt32 must be (a[Set[_]]) } "custom collection" should "work" in { val c = CustomCollection(repeatedInt32 = MyVector(Vector(11, 24, 19))) CustomCollection.parseFrom(c.toByteArray) must be(c) CustomCollection.fromAscii(c.toProtoString) must be(c) CustomCollection.fromJavaProto(CustomCollection.toJavaProto(c)) must be(c) } // See https://github.com/scalapb/ScalaPB/issues/274 "packed sets serialization" should "work" in { val m = CollectionTypesPackedSet(repeatedUint32 = Set(1,2,3,4,5)) CollectionTypesPackedSet.parseFrom(m.toByteArray) must be(m) } "custom maps" should "have expected types" in { val m = CollectionTypesMap() m.mapInt32Bool must be (a[mutable.Map[_, _]]) m.mapInt32Enum must be (a[mutable.Map[_, _]]) m.mymapInt32Bool must be (a[MyMap[_, _]]) } "custom maps" should "serialize and deserialize" in { val m = CollectionTypesMap(mymapInt32Bool = MyMap(Map(3 -> true, 4 -> false))) CollectionTypesMap.parseFrom(m.toByteArray) must be(m) m.mapInt32Bool += (3 -> true) } "custom maps" should "convertible to and from Java" in { val m = CollectionTypesMap(mymapInt32Bool = MyMap(Map(3 -> true, 4 -> false))) CollectionTypesMap.fromJavaProto(CollectionTypesMap.toJavaProto(m)) must be(m) } }
dotty-staging/ScalaPB
e2e/src/test/scala/CollectionTypesSpec.scala
Scala
apache-2.0
2,005
package linguistica.stemmer.porter import org.scalatest._ import org.scalatest.matchers._ import org.scalatest.Assertions._ class PrecomputeSpec extends FunSuite with Logic { import LetterType._ test("test that precompute returns everything right") { assert(Word("TR").letters === List(('T', Consonant), ('R', Consonant))) assert(Word("TREE").letters === List(('T', Consonant), ('R', Consonant), ('E', Vowel), ('E', Vowel))) assert(Word("YEL").letters === List(('Y', Consonant), ('E', Vowel), ('L', Consonant))) assert(Word("HEY").letters === List(('H', Consonant), ('E', Vowel), ('Y', Consonant))) assert(Word("BY").letters === List(('B', Consonant), ('Y', Vowel))) } }
vcherkassky/porter-stemmer
src/test/scala/linguistica/stemmer/porter/PrecomputeSpec.scala
Scala
mit
700
package com.github.jmccrae.yuzu import com.github.jmccrae.yuzu.YuzuSettings._ import com.hp.hpl.jena.rdf.model.{Literal, Model, RDFNode, Resource, Property} import com.hp.hpl.jena.vocabulary._ import java.io.Writer import scala.collection.JavaConversions._ import scala.collection.mutable.{Map => MutableMap} object JsonLDPrettySerializer { sealed trait JsonObj { def write(out : Writer, indent : Int) : Unit override def toString = { val sw = new java.io.StringWriter() write(sw, 0) sw.toString } } object JsonObj { def apply(value : Any) : JsonObj = value match { case o : JsonObj => o case s : String => JsonString(s) case i : Int => JsonInt(i) case d : Double => JsonFloat(d) case s : Seq[_] => JsonList(s.map(JsonObj(_))) case m : Map[_, _] => JsonMap(MutableMap((m.map { case (k, v) => k.toString -> JsonObj(v) }).toSeq:_*)) case m : MutableMap[_, _] => JsonMap(m.map { case (k, v) => k.toString -> JsonObj(v) }) } def apply(vals : (String, Any)*) : JsonMap = JsonMap((vals.map { case (k, v) => k -> JsonObj(v) }):_*) } case class JsonString(value : String) extends JsonObj { def write(out : Writer, indent : Int) { out.write("\\"%s\\"" format (value.replaceAll("\\\\\\\\","\\\\\\\\\\\\\\\\"). replaceAll("\\"", "\\\\\\\\\\""))) } } case class JsonInt(value : Int) extends JsonObj { def write(out : Writer, indent : Int) { out.write(value.toString) } } case class JsonFloat(value : Double) extends JsonObj { def write(out : Writer, index : Int) { out.write(value.toString) } } class JsonMap(val value : MutableMap[String, JsonObj]) extends JsonObj { def write(out : Writer, indent : Int) { out.write("{\\n") val elems = value.toSeq.sortBy(_._1) if(!elems.isEmpty) { val h = elems.head out.write(" " * (indent + 1)) out.write("\\"%s\\": " format h._1) h._2.write(out, indent + 2) for((k, v) <- elems.tail) { out.write(",\\n") out.write(" " * (indent + 1)) out.write("\\"%s\\": " format k) v.write(out, indent + 2) }} out.write("\\n") out.write(" " * indent) out.write("}") } def update(key : String, v : JsonObj) = value.update(key, v) def update(key : String, v : String) = value.update(key, JsonString(v)) def contains(key : String) = value.contains(key) def apply(key : String) = value(key) def remove(key : String) = value.remove(key) def keys = value.keys override def equals(o : Any) = o match { case null => false case jm : JsonMap => value == jm.value case _ => false } } object JsonMap { def apply(value : MutableMap[String, JsonObj]) = new JsonMap(value) def apply(vals : (String, JsonObj)*) = new JsonMap( MutableMap(vals:_*)) } case class JsonList(value : Seq[JsonObj]) extends JsonObj { def write(out : Writer, indent : Int) { out.write("[\\n") if(!value.isEmpty) { val h = value.head out.write(" " * (indent + 1)) h.write(out, indent + 1) for(v <- value.tail) { out.write(",\\n") out.write(" " * (indent + 1)) v.write(out, indent + 1) }} out.write("\\n") out.write(" " * indent) out.write("]") } def :+(elem : JsonObj) = JsonList(value :+ elem) def +:(elem : JsonObj) = JsonList(elem +: value) def apply(i : Int) = value(i) } implicit class GraphPimp(graph : Model) { def listProperties(subj : Resource = null, obj : RDFNode = null) = { (graph.listStatements(subj, Option(obj).map(x => graph.createProperty(x.asResource().getURI())).getOrElse(null), null).map { st => // (stats.filter { st => // (subj == null || st.getSubject() == subj) && // (obj == null || st.getObject() == obj) // } map { st => st.getPredicate() }).toSet } } private def isAlnum(s : String) = s.matches("\\\\w+") private def propType(p : Property, graph : Model) : JsonObj = { if(graph.listObjectsOfProperty(p).forall(_.isResource())) { JsonObj("@id" -> p.getURI(), "@type" -> "@id") } else { JsonString(p.getURI()) }} private def splitURI(value : String, graph : Model) : (Option[String], String) = { if(value.startsWith(BASE_NAME)) { return (None, value.drop(BASE_NAME.length)) } for((qn, uri) <- graph.getNsPrefixMap()) { if(value.startsWith(uri)) { return (Some(qn), value.drop(uri.length)) }} return (None, value) } private def isPrefixUsed(prefix : String, graph : Model) : Boolean = { graph.listStatements().exists { stat => stat.getPredicate().getURI().startsWith(prefix) || (stat.getSubject().isURIResource() && stat.getSubject().asResource().getURI().startsWith(prefix)) || (stat.getObject().isURIResource() && stat.getObject().asResource().getURI().startsWith(prefix)) } } private def extractJsonLDContext(graph : Model, query : String) : (JsonMap, Map[String, String]) = { val context = JsonObj("@base" -> BASE_NAME) for((k, v) <- graph.getNsPrefixMap()) { if(isPrefixUsed(v, graph)) { context(k) = v }} val props = MutableMap[String, String]() for(p <- graph.listProperties()) { val pStr = p.getURI() var shortName = "" if(pStr.contains("#")) { shortName = pStr.drop(pStr.lastIndexOf("#") + 1) } if(!isAlnum(shortName) && pStr.contains("/")) { shortName = pStr.drop(pStr.lastIndexOf("/") + 1) } if(!isAlnum(shortName)) { val (pre, suf) = splitURI(pStr, graph) shortName = suf } var sn = shortName var i = 2 while(context.contains(sn)) { sn = "%s%d" format (shortName, i) i += 1 } if(p == RDF.`type`) { sn = "@type" } else { context(sn) = propType(p, graph) } props(pStr) = sn } (context, props.toMap) } private def addProps(obj : JsonMap, value : Resource, context : JsonMap, graph : Model, query : String, prop2sn : Map[String, String], drb : Set[Resource], stack : List[Resource]) { if(!(stack contains value)) { for(p <- graph.listProperties(value)) { val objs = graph.listObjectsOfProperty(value, p).toList.sortBy(_.toString) val isObj = p == RDF.`type` || context(prop2sn(p.getURI())).isInstanceOf[JsonMap] if(objs.size == 1) { graph.removeAll(value, p, objs(0)) obj(prop2sn(p.getURI())) = jsonLDValue(objs(0), context, graph, query, prop2sn, isObj, drb, value :: stack) } else { for(o <- objs) { graph.removeAll(value, p, o) } obj(prop2sn(p.getURI())) = JsonList((objs.map { o => jsonLDValue(o, context, graph, query, prop2sn, isObj, drb, value :: stack) }).toList) }}}} private def addInverseProps(obj : JsonMap, value : Resource, context : JsonMap, graph : Model, query : String, prop2sn : Map[String, String], drb : Set[Resource], stack : List[Resource]) { if(!(stack contains value)) { for(p <- graph.listProperties()) { val objs = graph.listObjectsOfProperty(value, p).toList.sortBy(_.toString) for(o <- objs) { if(o.isResource()) { obj(prop2sn(p.getURI())) match { case jm : JsonMap => addInverseProps(jm, value, context, graph, query, prop2sn, drb, value :: stack) case _ => // ignore }}}} if(!graph.listProperties(null, value).isEmpty) { val robj = JsonMap() obj("@reverse") = robj for(p <- graph.listProperties(null, value)) { val objs = graph.listSubjectsWithProperty(p, value).toList. sortBy(_.toString).filter { o => o.isResource() //&& !o.asResource().getURI().startsWith(query) } map { o => o.asResource() } if(objs.size == 1) { graph.removeAll(objs(0), p, value) robj(prop2sn(p.getURI())) = jsonLDValue(objs(0), context, graph, query, prop2sn, false, drb, value :: stack) } else if(objs.size > 1) { for(o <- objs) { graph.removeAll(o, p, value) } robj(prop2sn(p.getURI())) = JsonList(objs.map { o => jsonLDValue(o, context, graph, query, prop2sn, false, drb, value :: stack) }) }}}}} private def jsonLDValue(value : Any, context : JsonMap, graph : Model, query : String, prop2sn : Map[String, String], isObj : Boolean, drb : Set[Resource], stack : List[Resource]) : JsonObj = { value match { case list : Seq[_] => if(list.size == 1) { jsonLDValue(list(0), context, graph, query, prop2sn, isObj, drb, stack) } else { JsonList(list.map { v => jsonLDValue(v, context, graph, query, prop2sn, isObj, drb, stack) })} case r : Resource if r.isURIResource() => if(graph.listStatements(r, null, null : RDFNode).isEmpty && isObj) { val (pre, suf) = splitURI(r.getURI(), graph) pre match { case Some(pre) => JsonString("%s:%s" format (pre, suf)) case None => JsonString(suf) }} else { val (pre, suf) = splitURI(r.getURI(), graph) val obj = pre match { case Some(pre) => JsonObj("@id" -> ("%s:%s" format (pre, suf))) case None => JsonObj("@id" -> suf) } addProps(obj, r, context, graph, query, prop2sn, drb, stack) obj } case r : Resource => if(graph.listStatements(r, null, null : RDFNode).isEmpty && isObj) { if(drb.contains(r)) { JsonString("_:" + r.getId().getLabelString()) } else { JsonMap() }} else { val obj = if(drb.contains(r)) { JsonObj("@id" -> ("_:" + r.getId().getLabelString())) } else { JsonMap() } addProps(obj, r, context, graph, query, prop2sn, drb, stack) obj } case l : Literal => if(l.getLanguage() != null && l.getLanguage() != "") { JsonObj("@value" -> l.getLexicalForm(), "@language" -> l.getLanguage()) } else if(l.getDatatype() != null) { val (pre, suf) = splitURI(l.getDatatype().getURI(), graph) pre match { case Some("xsd") if suf == "integer" => JsonInt(l.getInt()) case Some("xsd") if suf == "double" => JsonFloat(l.getDouble()) case Some(pre) => JsonObj("@value" -> l.getLexicalForm(), "@type" -> ("%s:%s" format (pre, suf))) case None => JsonObj("@value" -> l.getLexicalForm(), "@type" -> suf) }} else { return JsonString(l.getLexicalForm()) }}} private def doubleReffedBNodes(graph : Model) : Set[Resource] = { (for { o <- graph.listObjects() if o.isResource() && !o.isURIResource() if graph.listStatements(null, null, o).size > 1 } yield o.asResource()).toSet } def write(out : java.io.Writer, graph : Model, query : String) { val obj = jsonLDfromModel(graph, query) obj.write(out, 0) out.write("\\n") out.flush() } def jsonLDfromModel(graph : Model, query : String) : JsonObj = { val (context, prop2sn) = extractJsonLDContext(graph, query) val theId = if(query.startsWith(BASE_NAME)) { query.drop(BASE_NAME.size) } else { query } var theObj = JsonObj( "@context" -> context, "@id" -> JsonString(theId) ) val elem = graph.createResource(query) val drb = doubleReffedBNodes(graph) addProps(theObj, elem, context, graph, query, prop2sn, drb, Nil) addInverseProps(theObj, elem, context, graph, query, prop2sn, drb, Nil) var rest = graph.listSubjects().toList if(!rest.isEmpty()) { val graphObj = JsonObj( "@context" -> context, "@graph" -> JsonList(Seq(theObj))) theObj.remove("@context") theObj = graphObj while(!rest.isEmpty()) { theObj("@graph") = theObj("@graph").asInstanceOf[JsonList] :+ jsonLDValue(rest.head, context, graph, query, prop2sn, true, drb, Nil) rest = graph.listSubjects().toList }} theObj } }
jmccrae/yuzu
scala/src/main/scala/yuzu/jsonld.scala
Scala
apache-2.0
13,035
package com.websudos.phantom.db import com.websudos.phantom.connectors.ContactPoint import com.websudos.phantom.tables.{Recipes, JsonTable, EnumTable, BasicTable} private object DefaultKeysapce { lazy val local = ContactPoint.local.keySpace("phantom_test") } class TestDatabase extends DatabaseImpl(DefaultKeysapce.local) { object basicTable extends BasicTable with connector.Connector object enumTable extends EnumTable with connector.Connector object jsonTable extends JsonTable with connector.Connector object recipes extends Recipes with connector.Connector }
dan-mi-sun/phantom
phantom-dsl/src/test/scala/com/websudos/phantom/db/TestDatabase.scala
Scala
bsd-2-clause
578
package de.htw.pgerhard.domain.tweets import akka.actor.Status.Failure import akka.actor.{ActorRef, Props} import akka.util.Timeout import de.htw.pgerhard.domain.generic._ import de.htw.pgerhard.domain.tweets.errors.TweetNotFound import de.htw.pgerhard.domain.tweets.events._ import scala.collection.mutable import scala.concurrent.ExecutionContext import scala.reflect.ClassTag class TweetView( val view: ActorRef)( override implicit val ec: ExecutionContext, val timeout: Timeout, val classTag: ClassTag[SimpleTweet]) extends ViewConnector[SimpleTweet] class TweetViewActor extends View { private val tweets = mutable.Map[String, SimpleTweet]() override protected def handleEvent: EventHandler = { case ev: TweetPostedEvent ⇒ tweets(ev.tweetId) = SimpleTweet.fromCreatedEvent(ev) case ev: TweetRepostedEvent ⇒ val tweet = tweets(ev.tweetId) tweets(ev.tweetId) = tweet.copy(repostCount = tweet.repostCount + 1) case ev: TweetRepostDeletedEvent ⇒ val tweet = tweets(ev.tweetId) tweets(ev.tweetId) = tweet.copy(repostCount = tweet.repostCount - 1) case ev: TweetDeletedEvent ⇒ tweets.remove(ev.tweetId) } override protected def receiveClientMessage: Receive = { case msg: GetById ⇒ sender() ! tweets.getOrElse(msg.id, Failure(TweetNotFound(msg.id))) case msg: GetOptById ⇒ sender() ! tweets.get(msg.id) case msg: GetSeqByIds ⇒ sender() ! msg.ids.flatMap(tweets.get) } } object TweetViewActor { def props: Props = Props(new TweetViewActor) } case class SimpleTweet( id: String, authorId: String, body: String, timestamp: Long, likeCount: Int, repostCount: Int) object SimpleTweet { def fromCreatedEvent(ev: TweetPostedEvent): SimpleTweet = SimpleTweet(ev.tweetId, ev.authorId, ev.body, ev.timestamp, 0, 0) }
peter-gerhard/my-twitter-playground
src/main/scala/de/htw/pgerhard/domain/tweets/TweetView.scala
Scala
apache-2.0
1,879
package jp.co.cyberagent.aeromock.server import io.netty.channel.ChannelInitializer import io.netty.channel.socket.SocketChannel import io.netty.handler.codec.http.HttpObjectAggregator import io.netty.handler.codec.http.HttpRequestDecoder import io.netty.handler.codec.http.HttpResponseEncoder import io.netty.handler.codec.protobuf.ProtobufEncoder import io.netty.handler.stream.ChunkedWriteHandler import scaldi.Injector class AeromockServerInitializer(implicit inj: Injector) extends ChannelInitializer[SocketChannel] { override def initChannel(channel: SocketChannel) { channel.pipeline() .addLast(classOf[HttpRequestDecoder].getName, new HttpRequestDecoder) .addLast(classOf[HttpObjectAggregator].getName, new HttpObjectAggregator(65536)) .addLast(classOf[HttpResponseEncoder].getName, new HttpResponseEncoder) .addLast(classOf[ProtobufEncoder].getName, new ProtobufEncoder) .addLast(classOf[ChunkedWriteHandler].getName, new ChunkedWriteHandler) .addLast(classOf[AeromockServerHandler].getName, new AeromockServerHandler(true)) } }
CyberAgent/aeromock
aeromock-server/src/main/scala/jp/co/cyberagent/aeromock/server/AeromockServerInitializer.scala
Scala
mit
1,085
package queries import authes.Role import com.github.nscala_time.time.Imports._ import models.User import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder case class CreateUser(name: String, email: String, password: String) { def user(now: DateTime = DateTime.now()): User = { val encoded = BCryptEncoder(password) User(0L, name, email, Role.NormalUser, encoded, public = false, now) } } object BCryptEncoder { val bcrypt = new BCryptPasswordEncoder(12) def apply(pass: String) = bcrypt.encode(pass) }
ponkotuy/aggregate-exif
app/queries/CreateUser.scala
Scala
apache-2.0
537
import sbt._ import Keys._ import PlayProject._ object ApplicationBuild extends Build { val appName = "play-authenticate-demo" val appVersion = "1.0-SNAPSHOT" val appDependencies = Seq( "be.objectify" %% "deadbolt-java" % "2.1-SNAPSHOT", "com.feth" %% "play-authenticate" % "0.2.5-SNAPSHOT", javaCore, javaJdbc, javaEbean ) val main = play.Project(appName, appVersion, appDependencies).settings( resolvers += Resolver.url("Objectify Play Repository (release)", url("http://schaloner.github.com/releases/"))(Resolver.ivyStylePatterns), resolvers += Resolver.url("Objectify Play Repository (snapshot)", url("http://schaloner.github.com/snapshots/"))(Resolver.ivyStylePatterns), resolvers += Resolver.url("play-easymail (release)", url("http://joscha.github.com/play-easymail/repo/releases/"))(Resolver.ivyStylePatterns), resolvers += Resolver.url("play-easymail (snapshot)", url("http://joscha.github.com/play-easymail/repo/snapshots/"))(Resolver.ivyStylePatterns), resolvers += Resolver.url("play-authenticate (release)", url("http://joscha.github.com/play-authenticate/repo/releases/"))(Resolver.ivyStylePatterns), resolvers += Resolver.url("play-authenticate (snapshot)", url("http://joscha.github.com/play-authenticate/repo/snapshots/"))(Resolver.ivyStylePatterns) ) }
stefanil/play2-prototypen
play-authenticate-demo/project/Build.scala
Scala
apache-2.0
1,385
/*********************************************************************** * Copyright (c) 2013-2017 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.accumulo.audit import java.io.Serializable import java.util.{Map => jMap} import org.locationtech.geomesa.accumulo.data.AccumuloDataStoreParams import org.locationtech.geomesa.utils.audit.AuditProvider import scala.collection.JavaConversions._ class ParamsAuditProvider extends AuditProvider { private var id = "unknown" override def getCurrentUserId: String = id override val getCurrentUserDetails: jMap[AnyRef, AnyRef] = Map.empty[AnyRef, AnyRef] override def configure(params: jMap[String, Serializable]): Unit = { import AccumuloDataStoreParams._ val user = if (ConnectorParam.exists(params)) { ConnectorParam.lookup(params).whoami() } else if (UserParam.exists(params)) { UserParam.lookup(params) } else { null } if (user != null) { id = s"accumulo[$user]" } } }
ronq/geomesa
geomesa-accumulo/geomesa-accumulo-datastore/src/main/scala/org/locationtech/geomesa/accumulo/audit/ParamsAuditProvider.scala
Scala
apache-2.0
1,337
/* * Copyright 2018 Satellite Applications Catapult Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.catapult.sa.tribble.stats import org.junit.Assert._ import org.junit.Test /** * Quick test of the duration formatting in stats. */ class TestStats { val tests = List( (0L, "0S"), (45000L, "45S"), (4500L, "4S 500ms"), (5L, "5ms"), (67000L, "1M 7S"), (70230L, "1M 10S 230ms"), (3606000L, "1H 6S") ) @Test def runTests() : Unit = { tests.zipWithIndex.foreach { t => val result = CurrentStats.formatDuration(t._1._1) assertEquals(s"Wrong result for entry ${t._2}, input ${t._1._1}", t._1._2, result) } } }
SatelliteApplicationsCatapult/tribble
tribble-core/src/test/scala/org/catapult/sa/tribble/stats/TestStats.scala
Scala
apache-2.0
1,237
package org.jetbrains.plugins.scala.testingSupport.scalatest.scala2_11.scalatest2_1_7 import org.jetbrains.plugins.scala.SlowTests import org.jetbrains.plugins.scala.testingSupport.scalatest.finders.FindersApiTest import org.junit.experimental.categories.Category /** * @author Roman.Shein * @since 10.02.2015. */ @Category(Array(classOf[SlowTests])) class Scalatest2_11_2_1_7_FindersApiTest extends Scalatest2_11_2_1_7_Base with FindersApiTest
jastice/intellij-scala
scala/scala-impl/test/org/jetbrains/plugins/scala/testingSupport/scalatest/scala2_11/scalatest2_1_7/Scalatest2_11_2_1_7_FindersApiTest.scala
Scala
apache-2.0
450
// Generated by the Scala Plugin for the Protocol Buffer Compiler. // Do not edit! // // Protofile syntax: PROTO3 package com.google.protobuf.api /** Api is a light-weight descriptor for an API Interface. * * Interfaces are also described as "protocol buffer services" in some contexts, * such as by the "service" keyword in a .proto file, but they are different * from API Services, which represent a concrete implementation of an interface * as opposed to simply a description of methods and bindings. They are also * sometimes simply referred to as "APIs" in other contexts, such as the name of * this message itself. See https://cloud.google.com/apis/design/glossary for * detailed terminology. * * @param name * The fully qualified name of this interface, including package name * followed by the interface's simple name. * @param methods * The methods of this interface, in unspecified order. * @param options * Any metadata attached to the interface. * @param version * A version string for this interface. If specified, must have the form * `major-version.minor-version`, as in `1.10`. If the minor version is * omitted, it defaults to zero. If the entire version field is empty, the * major version is derived from the package name, as outlined below. If the * field is not empty, the version in the package name will be verified to be * consistent with what is provided here. * * The versioning schema uses [semantic * versioning](http://semver.org) where the major version number * indicates a breaking change and the minor version an additive, * non-breaking change. Both version numbers are signals to users * what to expect from different versions, and should be carefully * chosen based on the product plan. * * The major version is also reflected in the package name of the * interface, which must end in `v&lt;major-version&gt;`, as in * `google.feature.v1`. For major versions 0 and 1, the suffix can * be omitted. Zero major versions must only be used for * experimental, non-GA interfaces. * @param sourceContext * Source context for the protocol buffer service represented by this * message. * @param mixins * Included interfaces. See [Mixin][]. * @param syntax * The source syntax of the service. */ @SerialVersionUID(0L) final case class Api( name: _root_.scala.Predef.String = "", methods: _root_.scala.Seq[com.google.protobuf.api.Method] = _root_.scala.Seq.empty, options: _root_.scala.Seq[com.google.protobuf.`type`.OptionProto] = _root_.scala.Seq.empty, version: _root_.scala.Predef.String = "", sourceContext: _root_.scala.Option[com.google.protobuf.source_context.SourceContext] = _root_.scala.None, mixins: _root_.scala.Seq[com.google.protobuf.api.Mixin] = _root_.scala.Seq.empty, syntax: com.google.protobuf.`type`.Syntax = com.google.protobuf.`type`.Syntax.SYNTAX_PROTO2, unknownFields: _root_.scalapb.UnknownFieldSet = _root_.scalapb.UnknownFieldSet.empty ) extends scalapb.GeneratedMessage with scalapb.lenses.Updatable[Api] { @transient private[this] var __serializedSizeMemoized: _root_.scala.Int = 0 private[this] def __computeSerializedSize(): _root_.scala.Int = { var __size = 0 { val __value = name if (!__value.isEmpty) { __size += _root_.com.google.protobuf.CodedOutputStream.computeStringSize(1, __value) } }; methods.foreach { __item => val __value = __item __size += 1 + _root_.com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(__value.serializedSize) + __value.serializedSize } options.foreach { __item => val __value = __item __size += 1 + _root_.com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(__value.serializedSize) + __value.serializedSize } { val __value = version if (!__value.isEmpty) { __size += _root_.com.google.protobuf.CodedOutputStream.computeStringSize(4, __value) } }; if (sourceContext.isDefined) { val __value = sourceContext.get __size += 1 + _root_.com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(__value.serializedSize) + __value.serializedSize }; mixins.foreach { __item => val __value = __item __size += 1 + _root_.com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(__value.serializedSize) + __value.serializedSize } { val __value = syntax.value if (__value != 0) { __size += _root_.com.google.protobuf.CodedOutputStream.computeEnumSize(7, __value) } }; __size += unknownFields.serializedSize __size } override def serializedSize: _root_.scala.Int = { var __size = __serializedSizeMemoized if (__size == 0) { __size = __computeSerializedSize() + 1 __serializedSizeMemoized = __size } __size - 1 } def writeTo(`_output__`: _root_.com.google.protobuf.CodedOutputStream): _root_.scala.Unit = { { val __v = name if (!__v.isEmpty) { _output__.writeString(1, __v) } }; methods.foreach { __v => val __m = __v _output__.writeTag(2, 2) _output__.writeUInt32NoTag(__m.serializedSize) __m.writeTo(_output__) }; options.foreach { __v => val __m = __v _output__.writeTag(3, 2) _output__.writeUInt32NoTag(__m.serializedSize) __m.writeTo(_output__) }; { val __v = version if (!__v.isEmpty) { _output__.writeString(4, __v) } }; sourceContext.foreach { __v => val __m = __v _output__.writeTag(5, 2) _output__.writeUInt32NoTag(__m.serializedSize) __m.writeTo(_output__) }; mixins.foreach { __v => val __m = __v _output__.writeTag(6, 2) _output__.writeUInt32NoTag(__m.serializedSize) __m.writeTo(_output__) }; { val __v = syntax.value if (__v != 0) { _output__.writeEnum(7, __v) } }; unknownFields.writeTo(_output__) } def withName(__v: _root_.scala.Predef.String): Api = copy(name = __v) def clearMethods = copy(methods = _root_.scala.Seq.empty) def addMethods(__vs: com.google.protobuf.api.Method *): Api = addAllMethods(__vs) def addAllMethods(__vs: Iterable[com.google.protobuf.api.Method]): Api = copy(methods = methods ++ __vs) def withMethods(__v: _root_.scala.Seq[com.google.protobuf.api.Method]): Api = copy(methods = __v) def clearOptions = copy(options = _root_.scala.Seq.empty) def addOptions(__vs: com.google.protobuf.`type`.OptionProto *): Api = addAllOptions(__vs) def addAllOptions(__vs: Iterable[com.google.protobuf.`type`.OptionProto]): Api = copy(options = options ++ __vs) def withOptions(__v: _root_.scala.Seq[com.google.protobuf.`type`.OptionProto]): Api = copy(options = __v) def withVersion(__v: _root_.scala.Predef.String): Api = copy(version = __v) def getSourceContext: com.google.protobuf.source_context.SourceContext = sourceContext.getOrElse(com.google.protobuf.source_context.SourceContext.defaultInstance) def clearSourceContext: Api = copy(sourceContext = _root_.scala.None) def withSourceContext(__v: com.google.protobuf.source_context.SourceContext): Api = copy(sourceContext = Option(__v)) def clearMixins = copy(mixins = _root_.scala.Seq.empty) def addMixins(__vs: com.google.protobuf.api.Mixin *): Api = addAllMixins(__vs) def addAllMixins(__vs: Iterable[com.google.protobuf.api.Mixin]): Api = copy(mixins = mixins ++ __vs) def withMixins(__v: _root_.scala.Seq[com.google.protobuf.api.Mixin]): Api = copy(mixins = __v) def withSyntax(__v: com.google.protobuf.`type`.Syntax): Api = copy(syntax = __v) def withUnknownFields(__v: _root_.scalapb.UnknownFieldSet) = copy(unknownFields = __v) def discardUnknownFields = copy(unknownFields = _root_.scalapb.UnknownFieldSet.empty) def getFieldByNumber(__fieldNumber: _root_.scala.Int): _root_.scala.Any = { (__fieldNumber: @_root_.scala.unchecked) match { case 1 => { val __t = name if (__t != "") __t else null } case 2 => methods case 3 => options case 4 => { val __t = version if (__t != "") __t else null } case 5 => sourceContext.orNull case 6 => mixins case 7 => { val __t = syntax.javaValueDescriptor if (__t.getNumber() != 0) __t else null } } } def getField(__field: _root_.scalapb.descriptors.FieldDescriptor): _root_.scalapb.descriptors.PValue = { _root_.scala.Predef.require(__field.containingMessage eq companion.scalaDescriptor) (__field.number: @_root_.scala.unchecked) match { case 1 => _root_.scalapb.descriptors.PString(name) case 2 => _root_.scalapb.descriptors.PRepeated(methods.iterator.map(_.toPMessage).toVector) case 3 => _root_.scalapb.descriptors.PRepeated(options.iterator.map(_.toPMessage).toVector) case 4 => _root_.scalapb.descriptors.PString(version) case 5 => sourceContext.map(_.toPMessage).getOrElse(_root_.scalapb.descriptors.PEmpty) case 6 => _root_.scalapb.descriptors.PRepeated(mixins.iterator.map(_.toPMessage).toVector) case 7 => _root_.scalapb.descriptors.PEnum(syntax.scalaValueDescriptor) } } def toProtoString: _root_.scala.Predef.String = _root_.scalapb.TextFormat.printToUnicodeString(this) def companion: com.google.protobuf.api.Api.type = com.google.protobuf.api.Api // @@protoc_insertion_point(GeneratedMessage[google.protobuf.Api]) } object Api extends scalapb.GeneratedMessageCompanion[com.google.protobuf.api.Api] { implicit def messageCompanion: scalapb.GeneratedMessageCompanion[com.google.protobuf.api.Api] = this def parseFrom(`_input__`: _root_.com.google.protobuf.CodedInputStream): com.google.protobuf.api.Api = { var __name: _root_.scala.Predef.String = "" val __methods: _root_.scala.collection.immutable.VectorBuilder[com.google.protobuf.api.Method] = new _root_.scala.collection.immutable.VectorBuilder[com.google.protobuf.api.Method] val __options: _root_.scala.collection.immutable.VectorBuilder[com.google.protobuf.`type`.OptionProto] = new _root_.scala.collection.immutable.VectorBuilder[com.google.protobuf.`type`.OptionProto] var __version: _root_.scala.Predef.String = "" var __sourceContext: _root_.scala.Option[com.google.protobuf.source_context.SourceContext] = _root_.scala.None val __mixins: _root_.scala.collection.immutable.VectorBuilder[com.google.protobuf.api.Mixin] = new _root_.scala.collection.immutable.VectorBuilder[com.google.protobuf.api.Mixin] var __syntax: com.google.protobuf.`type`.Syntax = com.google.protobuf.`type`.Syntax.SYNTAX_PROTO2 var `_unknownFields__`: _root_.scalapb.UnknownFieldSet.Builder = null var _done__ = false while (!_done__) { val _tag__ = _input__.readTag() _tag__ match { case 0 => _done__ = true case 10 => __name = _input__.readStringRequireUtf8() case 18 => __methods += _root_.scalapb.LiteParser.readMessage[com.google.protobuf.api.Method](_input__) case 26 => __options += _root_.scalapb.LiteParser.readMessage[com.google.protobuf.`type`.OptionProto](_input__) case 34 => __version = _input__.readStringRequireUtf8() case 42 => __sourceContext = Option(__sourceContext.fold(_root_.scalapb.LiteParser.readMessage[com.google.protobuf.source_context.SourceContext](_input__))(_root_.scalapb.LiteParser.readMessage(_input__, _))) case 50 => __mixins += _root_.scalapb.LiteParser.readMessage[com.google.protobuf.api.Mixin](_input__) case 56 => __syntax = com.google.protobuf.`type`.Syntax.fromValue(_input__.readEnum()) case tag => if (_unknownFields__ == null) { _unknownFields__ = new _root_.scalapb.UnknownFieldSet.Builder() } _unknownFields__.parseField(tag, _input__) } } com.google.protobuf.api.Api( name = __name, methods = __methods.result(), options = __options.result(), version = __version, sourceContext = __sourceContext, mixins = __mixins.result(), syntax = __syntax, unknownFields = if (_unknownFields__ == null) _root_.scalapb.UnknownFieldSet.empty else _unknownFields__.result() ) } implicit def messageReads: _root_.scalapb.descriptors.Reads[com.google.protobuf.api.Api] = _root_.scalapb.descriptors.Reads{ case _root_.scalapb.descriptors.PMessage(__fieldsMap) => _root_.scala.Predef.require(__fieldsMap.keys.forall(_.containingMessage eq scalaDescriptor), "FieldDescriptor does not match message type.") com.google.protobuf.api.Api( name = __fieldsMap.get(scalaDescriptor.findFieldByNumber(1).get).map(_.as[_root_.scala.Predef.String]).getOrElse(""), methods = __fieldsMap.get(scalaDescriptor.findFieldByNumber(2).get).map(_.as[_root_.scala.Seq[com.google.protobuf.api.Method]]).getOrElse(_root_.scala.Seq.empty), options = __fieldsMap.get(scalaDescriptor.findFieldByNumber(3).get).map(_.as[_root_.scala.Seq[com.google.protobuf.`type`.OptionProto]]).getOrElse(_root_.scala.Seq.empty), version = __fieldsMap.get(scalaDescriptor.findFieldByNumber(4).get).map(_.as[_root_.scala.Predef.String]).getOrElse(""), sourceContext = __fieldsMap.get(scalaDescriptor.findFieldByNumber(5).get).flatMap(_.as[_root_.scala.Option[com.google.protobuf.source_context.SourceContext]]), mixins = __fieldsMap.get(scalaDescriptor.findFieldByNumber(6).get).map(_.as[_root_.scala.Seq[com.google.protobuf.api.Mixin]]).getOrElse(_root_.scala.Seq.empty), syntax = com.google.protobuf.`type`.Syntax.fromValue(__fieldsMap.get(scalaDescriptor.findFieldByNumber(7).get).map(_.as[_root_.scalapb.descriptors.EnumValueDescriptor]).getOrElse(com.google.protobuf.`type`.Syntax.SYNTAX_PROTO2.scalaValueDescriptor).number) ) case _ => throw new RuntimeException("Expected PMessage") } def javaDescriptor: _root_.com.google.protobuf.Descriptors.Descriptor = ApiProto.javaDescriptor.getMessageTypes().get(0) def scalaDescriptor: _root_.scalapb.descriptors.Descriptor = ApiProto.scalaDescriptor.messages(0) def messageCompanionForFieldNumber(__number: _root_.scala.Int): _root_.scalapb.GeneratedMessageCompanion[_] = { var __out: _root_.scalapb.GeneratedMessageCompanion[_] = null (__number: @_root_.scala.unchecked) match { case 2 => __out = com.google.protobuf.api.Method case 3 => __out = com.google.protobuf.`type`.OptionProto case 5 => __out = com.google.protobuf.source_context.SourceContext case 6 => __out = com.google.protobuf.api.Mixin } __out } lazy val nestedMessagesCompanions: Seq[_root_.scalapb.GeneratedMessageCompanion[_ <: _root_.scalapb.GeneratedMessage]] = Seq.empty def enumCompanionForFieldNumber(__fieldNumber: _root_.scala.Int): _root_.scalapb.GeneratedEnumCompanion[_] = { (__fieldNumber: @_root_.scala.unchecked) match { case 7 => com.google.protobuf.`type`.Syntax } } lazy val defaultInstance = com.google.protobuf.api.Api( name = "", methods = _root_.scala.Seq.empty, options = _root_.scala.Seq.empty, version = "", sourceContext = _root_.scala.None, mixins = _root_.scala.Seq.empty, syntax = com.google.protobuf.`type`.Syntax.SYNTAX_PROTO2 ) implicit class ApiLens[UpperPB](_l: _root_.scalapb.lenses.Lens[UpperPB, com.google.protobuf.api.Api]) extends _root_.scalapb.lenses.ObjectLens[UpperPB, com.google.protobuf.api.Api](_l) { def name: _root_.scalapb.lenses.Lens[UpperPB, _root_.scala.Predef.String] = field(_.name)((c_, f_) => c_.copy(name = f_)) def methods: _root_.scalapb.lenses.Lens[UpperPB, _root_.scala.Seq[com.google.protobuf.api.Method]] = field(_.methods)((c_, f_) => c_.copy(methods = f_)) def options: _root_.scalapb.lenses.Lens[UpperPB, _root_.scala.Seq[com.google.protobuf.`type`.OptionProto]] = field(_.options)((c_, f_) => c_.copy(options = f_)) def version: _root_.scalapb.lenses.Lens[UpperPB, _root_.scala.Predef.String] = field(_.version)((c_, f_) => c_.copy(version = f_)) def sourceContext: _root_.scalapb.lenses.Lens[UpperPB, com.google.protobuf.source_context.SourceContext] = field(_.getSourceContext)((c_, f_) => c_.copy(sourceContext = Option(f_))) def optionalSourceContext: _root_.scalapb.lenses.Lens[UpperPB, _root_.scala.Option[com.google.protobuf.source_context.SourceContext]] = field(_.sourceContext)((c_, f_) => c_.copy(sourceContext = f_)) def mixins: _root_.scalapb.lenses.Lens[UpperPB, _root_.scala.Seq[com.google.protobuf.api.Mixin]] = field(_.mixins)((c_, f_) => c_.copy(mixins = f_)) def syntax: _root_.scalapb.lenses.Lens[UpperPB, com.google.protobuf.`type`.Syntax] = field(_.syntax)((c_, f_) => c_.copy(syntax = f_)) } final val NAME_FIELD_NUMBER = 1 final val METHODS_FIELD_NUMBER = 2 final val OPTIONS_FIELD_NUMBER = 3 final val VERSION_FIELD_NUMBER = 4 final val SOURCE_CONTEXT_FIELD_NUMBER = 5 final val MIXINS_FIELD_NUMBER = 6 final val SYNTAX_FIELD_NUMBER = 7 def of( name: _root_.scala.Predef.String, methods: _root_.scala.Seq[com.google.protobuf.api.Method], options: _root_.scala.Seq[com.google.protobuf.`type`.OptionProto], version: _root_.scala.Predef.String, sourceContext: _root_.scala.Option[com.google.protobuf.source_context.SourceContext], mixins: _root_.scala.Seq[com.google.protobuf.api.Mixin], syntax: com.google.protobuf.`type`.Syntax ): _root_.com.google.protobuf.api.Api = _root_.com.google.protobuf.api.Api( name, methods, options, version, sourceContext, mixins, syntax ) // @@protoc_insertion_point(GeneratedMessageCompanion[google.protobuf.Api]) }
scalapb/ScalaPB
scalapb-runtime/src/main/js-native/com/google/protobuf/api/Api.scala
Scala
apache-2.0
18,143
package scorex.consensus.nxt import com.google.common.primitives.Longs import scorex.account.{Account, PrivateKeyAccount, PublicKeyAccount} import scorex.block.{Block, BlockField} import scorex.consensus.{ConsensusModule, OneGeneratorConsensusModule, PoSConsensusModule, TransactionsOrdering} import scorex.crypto.encode.Base58 import scorex.crypto.hash.FastCryptographicHash._ import scorex.settings.ChainParameters import scorex.transaction._ import scorex.utils.{NTP, ScorexLogging} import scala.concurrent.duration._ import scala.util.Try import scala.util.control.NonFatal class WavesConsensusModule(override val forksConfig: ChainParameters, AvgDelay: Duration) extends PoSConsensusModule[NxtLikeConsensusBlockData] with OneGeneratorConsensusModule with ScorexLogging { import WavesConsensusModule._ implicit val consensusModule: ConsensusModule[NxtLikeConsensusBlockData] = this val version = 2: Byte val MinBlocktimeLimit = normalize(53) val MaxBlocktimeLimit = normalize(67) val BaseTargetGamma = normalize(64) val MaxBaseTarget = Long.MaxValue / avgDelayInSeconds // val InitialBaseTarget = MaxBaseTarget / 2 val InitialBaseTarget = 153722867L // for compatibility reason private def avgDelayInSeconds: Long = AvgDelay.toSeconds private def normalize(value: Long): Double = value * avgDelayInSeconds / (60: Double) override def isValid[TT](block: Block)(implicit transactionModule: TransactionModule[TT]): Boolean = try { val blockTime = block.timestampField.value require((blockTime - NTP.correctedTime()).millis < MaxTimeDrift, s"Block timestamp $blockTime is from future") val history = transactionModule.blockStorage.history if (block.timestampField.value > forksConfig.requireSortedTransactionsAfter) { require(block.transactions.sorted(TransactionsOrdering) == block.transactions, "Transactions must be sorted correctly") } val parentOpt = history.parent(block) require(parentOpt.isDefined || history.height() == 1, s"Can't find parent block with id '${Base58.encode(block.referenceField.value)}' of block " + s"'${Base58.encode(block.uniqueId)}'") val parent = parentOpt.get val parentHeightOpt = history.heightOf(parent.uniqueId) require(parentHeightOpt.isDefined, s"Can't get parent block with id '${Base58.encode(block.referenceField.value)}' height") val parentHeight = parentHeightOpt.get val prevBlockData = consensusBlockData(parent) val blockData = consensusBlockData(block) //check baseTarget val cbt = calcBaseTarget(parent, blockTime) val bbt = blockData.baseTarget require(cbt == bbt, s"Block's basetarget is wrong, calculated: $cbt, block contains: $bbt") val generator = block.signerDataField.value.generator //check generation signature val calcGs = calcGeneratorSignature(prevBlockData, generator) val blockGs = blockData.generationSignature require(calcGs.sameElements(blockGs), s"Block's generation signature is wrong, calculated: ${calcGs.mkString}, block contains: ${blockGs.mkString}") val effectiveBalance = generatingBalance(generator, Some(parentHeight)) if (block.timestampField.value >= forksConfig.minimalGeneratingBalanceAfterTimestamp) { require(effectiveBalance >= MinimalEffictiveBalanceForGenerator, s"Effective balance $effectiveBalance is less that minimal ($MinimalEffictiveBalanceForGenerator)") } //check hit < target calcHit(prevBlockData, generator) < calcTarget(parent, blockTime, effectiveBalance) } catch { case e: IllegalArgumentException => log.error("Error while checking a block", e) false case NonFatal(t) => log.error("Fatal error while checking a block", t) throw t } override def generateNextBlock[TT](account: PrivateKeyAccount) (implicit tm: TransactionModule[TT]): Option[Block] = try { val history = tm.blockStorage.history val lastBlock = history.lastBlock val height = history.heightOf(lastBlock).get val balance = generatingBalance(account, Some(height)) if (balance < MinimalEffictiveBalanceForGenerator) { throw new IllegalStateException(s"Effective balance $balance is less that minimal ($MinimalEffictiveBalanceForGenerator)") } val lastBlockKernelData = consensusBlockData(lastBlock) val lastBlockTime = lastBlock.timestampField.value val currentTime = NTP.correctedTime() val h = calcHit(lastBlockKernelData, account) val t = calcTarget(lastBlock, currentTime, balance) val eta = (currentTime - lastBlockTime) / 1000 log.debug(s"hit: $h, target: $t, generating ${h < t}, eta $eta, " + s"account: $account " + s"account balance: $balance " + s"last block id: ${lastBlock.encodedId}, " + s"height: $height, " + s"last block target: ${lastBlockKernelData.baseTarget}" ) if (h < t) { val btg = calcBaseTarget(lastBlock, currentTime) val gs = calcGeneratorSignature(lastBlockKernelData, account) val consensusData = new NxtLikeConsensusBlockData { override val generationSignature: Array[Byte] = gs override val baseTarget: Long = btg } val unconfirmed = tm.packUnconfirmed(Some(height)) log.debug(s"Build block with ${unconfirmed.asInstanceOf[Seq[Transaction]].size} transactions") log.debug(s"Block time interval is $eta seconds ") Some(Block.buildAndSign(version, currentTime, lastBlock.uniqueId, consensusData, unconfirmed, account)) } else None } catch { case e: UnsupportedOperationException => log.debug(s"DB can't find last block because of unexpected modification") None case e: IllegalStateException => log.debug(s"Failed to generate new block: ${e.getMessage}") None } override def nextBlockGenerationTime(block: Block, account: PublicKeyAccount) (implicit tm: TransactionModule[_]): Option[Long] = { val history = tm.blockStorage.history history.heightOf(block.uniqueId) .map(height => (height, generatingBalance(account, Some(height)))).filter(_._2 > 0) .flatMap { case (height, balance) => val cData = consensusBlockData(block) val hit = calcHit(cData, account) val t = cData.baseTarget val result = Some((hit * 1000) / (BigInt(t) * balance) + block.timestampField.value) .filter(_ > 0).filter(_ < Long.MaxValue) .map(_.toLong) log.debug({ val currentTime = NTP.correctedTime() s"Next block gen time: $result " + s"in ${result.map(t => (t - currentTime) / 1000)} seconds, " + s"hit: $hit, target: $t, " + s"account: $account, account balance: $balance " + s"last block id: ${block.encodedId}, " + s"height: $height" }) result } } private def calcGeneratorSignature(lastBlockData: NxtLikeConsensusBlockData, generator: PublicKeyAccount) = hash(lastBlockData.generationSignature ++ generator.publicKey) private def calcHit(lastBlockData: NxtLikeConsensusBlockData, generator: PublicKeyAccount): BigInt = BigInt(1, calcGeneratorSignature(lastBlockData, generator).take(8).reverse) /** * BaseTarget calculation algorithm fixing the blocktimes. */ private def calcBaseTarget[TT](prevBlock: Block, timestamp: Long) (implicit transactionModule: TransactionModule[TT]): Long = { val history = transactionModule.blockStorage.history val height = history.heightOf(prevBlock).get val prevBaseTarget = consensusBlockData(prevBlock).baseTarget if (height % 2 == 0) { val blocktimeAverage = history.parent(prevBlock, AvgBlockTimeDepth - 1) .map(b => (timestamp - b.timestampField.value) / AvgBlockTimeDepth) .getOrElse(timestamp - prevBlock.timestampField.value) / 1000 val baseTarget = (if (blocktimeAverage > avgDelayInSeconds) { prevBaseTarget * Math.min(blocktimeAverage, MaxBlocktimeLimit) / avgDelayInSeconds } else { prevBaseTarget - prevBaseTarget * BaseTargetGamma * (avgDelayInSeconds - Math.max(blocktimeAverage, MinBlocktimeLimit)) / (avgDelayInSeconds * 100) }).toLong // TODO: think about MinBaseTarget like in Nxt scala.math.min(baseTarget, MaxBaseTarget) } else { prevBaseTarget } } protected def calcTarget(prevBlock: Block, timestamp: Long, balance: Long)(implicit transactionModule: TransactionModule[_]): BigInt = { require(balance >= 0, s"Balance cannot be negative") val prevBlockData = consensusBlockData(prevBlock) val prevBlockTimestamp = prevBlock.timestampField.value val eta = (timestamp - prevBlockTimestamp) / 1000 //in seconds BigInt(prevBlockData.baseTarget) * eta * balance } override def parseBytes(bytes: Array[Byte]): Try[BlockField[NxtLikeConsensusBlockData]] = Try { NxtConsensusBlockField(new NxtLikeConsensusBlockData { override val baseTarget: Long = Longs.fromByteArray(bytes.take(BaseTargetLength)) override val generationSignature: Array[Byte] = bytes.takeRight(GeneratorSignatureLength) }) } override def blockScore(block: Block): BigInt = { val baseTarget = consensusBlockData(block).baseTarget BigInt("18446744073709551616") / baseTarget }.ensuring(_ > 0) override def generators(block: Block): Seq[Account] = Seq(block.signerDataField.value.generator) override def genesisData: BlockField[NxtLikeConsensusBlockData] = NxtConsensusBlockField(new NxtLikeConsensusBlockData { override val baseTarget: Long = InitialBaseTarget override val generationSignature: Array[Byte] = Array.fill(32)(0: Byte) }) override def formBlockData(data: NxtLikeConsensusBlockData): BlockField[NxtLikeConsensusBlockData] = NxtConsensusBlockField(data) override def consensusBlockData(block: Block): NxtLikeConsensusBlockData = block.consensusDataField.value match { case b: NxtLikeConsensusBlockData => b case m => throw new AssertionError(s"Only NxtLikeConsensusBlockData is available, $m given") } } object WavesConsensusModule { val BaseTargetLength = 8 val GeneratorSignatureLength = 32 // 10000 waves val MinimalEffictiveBalanceForGenerator = 1000000000000L val AvgBlockTimeDepth: Int = 3 val MaxTimeDrift = 15.seconds }
B83YPoj/Waves
src/main/scala/scorex/consensus/nxt/WavesConsensusModule.scala
Scala
apache-2.0
10,526
/* * * * Copyright 2015 Skymind,Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package org.dhira.core.util import org.deeplearning4j.berkeley.Pair import org.nd4j.linalg.api.ndarray.INDArray import java.util.ArrayList import java.util.List import java.util.Random object InputSplit { def splitInputs(inputs: INDArray, outcomes: INDArray, train: List[Nothing], test: List[Nothing], split: Double) { val list: List[Nothing] = new ArrayList[E] { var i: Int = 0 while (i < inputs.rows) { { list.add(new Nothing(inputs.getRow(i), outcomes.getRow(i))) } ({ i += 1; i - 1 }) } } splitInputs(list, train, test, split) } def splitInputs(pairs: List[Nothing], train: List[Nothing], test: List[Nothing], split: Double) { val rand: Random = new Random import scala.collection.JavaConversions._ for (pair <- pairs) if (rand.nextDouble <= split) train.add(pair) else test.add(pair) } } class InputSplit { private def this() { this() } }
Mageswaran1989/aja
src/main/scala/org/aja/dhira/src/main/scala/org/dhira/core/util/InputSplit.scala
Scala
apache-2.0
1,633
/* * Copyright (c) <2015-2016>, see CONTRIBUTORS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.usi.inf.l3.sana.guod.phases import ch.usi.inf.l3.sana import sana.tiny.dsl._ import sana.tiny.core._ import sana.tiny.core.Implicits._ import sana.tiny.ast.{Tree, NoTree} import sana.tiny.symbols.Symbol import sana.modulej.Nodes import sana.guod.codegen._ trait InitializersFamilyApi extends TransformationFamily[Tree, Tree] { self => override def default = { case s => s } def components: List[PartialFunction[Tree, Tree]] = generateComponents[Tree, Tree]("Program,PackageDef,ClassDef,Template,CompilationUnit", "InitializerComponent", "inline", "") def inline: Tree => Tree = family } case class InitializersFamily(compiler: CompilerInterface) extends InitializersFamilyApi
amanjpro/languages-a-la-carte
guod/src/main/scala/phases/InitializersFamily.scala
Scala
bsd-3-clause
2,283
package com.alanjz.meerkat.app.menu.view import java.awt.event.{ActionEvent, KeyEvent} import com.alanjz.meerkat.app.menu.MCMenuItem object MCFullScreen extends MCMenuItem("Enter Full Screen", KeyEvent.VK_F, ActionEvent.CTRL_MASK | ActionEvent.META_MASK){ val f = (_ : ActionEvent) => {} }
spacenut/meerkat-chess
src/com/alanjz/meerkat/app/menu/view/MCFullscreen.scala
Scala
gpl-2.0
295
// scalac: -Xfatal-warnings -Xlint:infer-any // trait Foo[-A <: AnyRef, +B <: AnyRef] { def run[U](x: A)(action: B => U): Boolean = ??? def foo = { run(_: A)(_: B => String) } } trait Xs[+A] { { List(1, 2, 3) contains "a" } // only this warns { List(1, 2, 3) contains 1 } { identity(List(1, 2, 3) contains 1) } { List("a") foreach println } } trait Ys[+A] { { 1 to 5 contains 5L } { 1L to 5L contains 5 } { 1L to 5L contains 5d } { 1L to 5L contains 5L } } trait Zs { def f[A](a: A*) = 42 def g[A >: Any](a: A*) = 42 // don't warn def za = f(1, "one") def zu = g(1, "one") } class C1 class C2 trait Cs { val cs = List(new C1) cs.contains[AnyRef](new C2) // doesn't warn cs.contains(new C2) // warns }
martijnhoekstra/scala
test/files/neg/warn-inferred-any.scala
Scala
apache-2.0
744
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package whisk.core.connector import scala.annotation.tailrec import scala.collection.mutable import scala.concurrent.Future import scala.concurrent.blocking import scala.concurrent.duration._ import scala.util.Failure import org.apache.kafka.clients.consumer.CommitFailedException import akka.actor.FSM import akka.pattern.pipe import whisk.common.Logging import whisk.common.TransactionId trait MessageConsumer { /** The maximum number of messages peeked (i.e., max number of messages retrieved during a long poll). */ val maxPeek: Int /** * Gets messages via a long poll. May or may not remove messages * from the message connector. Use commit() to ensure messages are * removed from the connector. * * @param duration for the long poll * @return iterable collection (topic, partition, offset, bytes) */ def peek(duration: Duration): Iterable[(String, Int, Long, Array[Byte])] /** * Commits offsets from last peek operation to ensure they are removed * from the connector. */ def commit(): Unit /** Closes consumer. */ def close(): Unit } object MessageFeed { protected sealed trait FeedState protected[connector] case object Idle extends FeedState protected[connector] case object FillingPipeline extends FeedState protected[connector] case object DrainingPipeline extends FeedState protected sealed trait FeedData private case object NoData extends FeedData /** Indicates the consumer is ready to accept messages from the message bus for processing. */ object Ready /** Steady state message, indicates capacity in downstream process to receive more messages. */ object Processed /** Indicates the fill operation has completed. */ private case class FillCompleted(messages: Seq[(String, Int, Long, Array[Byte])]) } /** * This actor polls the message bus for new messages and dispatches them to the given * handler. The actor tracks the number of messages dispatched and will not dispatch new * messages until some number of them are acknowledged. * * This is used by the invoker to pull messages from the message bus and apply back pressure * when the invoker does not have resources to complete processing messages (i.e., no containers * are available to run new actions). It is also used in the load balancer to consume active * ack messages. * When the invoker releases resources (by reclaiming containers) it will send a message * to this actor which will then attempt to fill the pipeline with new messages. * * The actor tries to fill the pipeline with additional messages while the number * of outstanding requests is below the pipeline fill threshold. */ @throws[IllegalArgumentException] class MessageFeed( description: String, logging: Logging, consumer: MessageConsumer, maximumHandlerCapacity: Int, longPollDuration: FiniteDuration, handler: Array[Byte] => Future[Unit], autoStart: Boolean = true, logHandoff: Boolean = true) extends FSM[MessageFeed.FeedState, MessageFeed.FeedData] { import MessageFeed._ // double-buffer to make up for message bus read overhead val maxPipelineDepth = maximumHandlerCapacity * 2 private val pipelineFillThreshold = maxPipelineDepth - consumer.maxPeek require(consumer.maxPeek <= maxPipelineDepth, "consumer may not yield more messages per peek than permitted by max depth") private val outstandingMessages = mutable.Queue[(String, Int, Long, Array[Byte])]() private var handlerCapacity = maximumHandlerCapacity private implicit val tid = TransactionId.dispatcher logging.info(this, s"handler capacity = $maximumHandlerCapacity, pipeline fill at = $pipelineFillThreshold, pipeline depth = $maxPipelineDepth") when(Idle) { case Event(Ready, _) => fillPipeline() goto(FillingPipeline) case _ => stay } // wait for fill to complete, and keep filling if there is // capacity otherwise wait to drain when(FillingPipeline) { case Event(Processed, _) => updateHandlerCapacity() sendOutstandingMessages() stay case Event(FillCompleted(messages), _) => outstandingMessages.enqueue(messages: _*) sendOutstandingMessages() if (shouldFillQueue()) { fillPipeline() stay } else { goto(DrainingPipeline) } case _ => stay } when(DrainingPipeline) { case Event(Processed, _) => updateHandlerCapacity() sendOutstandingMessages() if (shouldFillQueue()) { fillPipeline() goto(FillingPipeline) } else stay case _ => stay } onTransition { case _ -> Idle => if (autoStart) self ! Ready } startWith(Idle, MessageFeed.NoData) initialize() private implicit val ec = context.system.dispatcher private def fillPipeline(): Unit = { if (outstandingMessages.size <= pipelineFillThreshold) { Future { blocking { // Grab next batch of messages and commit offsets immediately // essentially marking the activation as having satisfied "at most once" // semantics (this is the point at which the activation is considered started). // If the commit fails, then messages peeked are peeked again on the next poll. // While the commit is synchronous and will block until it completes, at steady // state with enough buffering (i.e., maxPipelineDepth > maxPeek), the latency // of the commit should be masked. val records = consumer.peek(longPollDuration) consumer.commit() FillCompleted(records.toSeq) } }.andThen { case Failure(e: CommitFailedException) => logging.error(this, s"failed to commit $description consumer offset: $e") case Failure(e: Throwable) => logging.error(this, s"exception while pulling new $description records: $e") }.recover { case _ => FillCompleted(Seq.empty) }.pipeTo(self) } else { logging.error(this, s"dropping fill request until $description feed is drained") } } /** Send as many messages as possible to the handler. */ @tailrec private def sendOutstandingMessages(): Unit = { val occupancy = outstandingMessages.size if (occupancy > 0 && handlerCapacity > 0) { val (topic, partition, offset, bytes) = outstandingMessages.dequeue() if (logHandoff) logging.info(this, s"processing $topic[$partition][$offset] ($occupancy/$handlerCapacity)") handler(bytes) handlerCapacity -= 1 sendOutstandingMessages() } } private def shouldFillQueue(): Boolean = { val occupancy = outstandingMessages.size if (occupancy <= pipelineFillThreshold) { logging.debug(this, s"$description pipeline has capacity: $occupancy <= $pipelineFillThreshold ($handlerCapacity)") true } else { logging.debug(this, s"$description pipeline must drain: $occupancy > $pipelineFillThreshold") false } } private def updateHandlerCapacity(): Int = { logging.debug(self, s"$description received processed msg, current capacity = $handlerCapacity") if (handlerCapacity < maximumHandlerCapacity) { handlerCapacity += 1 handlerCapacity } else { if (handlerCapacity > maximumHandlerCapacity) logging.error(self, s"$description capacity already at max") maximumHandlerCapacity } } }
prccaraujo/openwhisk
common/scala/src/main/scala/whisk/core/connector/MessageConsumer.scala
Scala
apache-2.0
8,747
package uk.ac.ncl.openlab.intake24.systemsql.admin import java.sql.Connection import anorm.Macro.ColumnNaming import javax.inject.{Inject, Named} import javax.sql.DataSource import anorm._ import org.apache.commons.lang3.StringUtils import org.postgresql.util.PSQLException import uk.ac.ncl.openlab.intake24.api.data.{NewRespondentIds, NewUserProfile} import uk.ac.ncl.openlab.intake24.errors._ import uk.ac.ncl.openlab.intake24.services.systemdb.admin._ import uk.ac.ncl.openlab.intake24.sql.{SqlDataService, SqlResourceLoader} class UserAdminImpl @Inject()(@Named("intake24_system") val dataSource: DataSource) extends UserAdminService with SqlDataService with SqlResourceLoader { private case class RolesForId(userId: Long, roles: Set[String]) private case class SecurePasswordForId(userId: Long, password: SecurePassword) private def updateUserRolesById(roles: Seq[RolesForId])(implicit connection: Connection): Either[RecordNotFound, Unit] = { if (roles.nonEmpty) { SQL("DELETE FROM user_roles WHERE user_id IN ({user_ids})") .on('user_ids -> roles.map(_.userId)) .execute() val params = roles.flatMap { r => r.roles.map { role => Seq[NamedParameter]('user_id -> r.userId, 'role -> role) } } if (!params.isEmpty) { tryWithConstraintCheck("user_roles_user_id_fkey", e => RecordNotFound(new RuntimeException(s"Could not update roles because one of the user records was not found"))) { BatchSql("INSERT INTO user_roles(user_id, role) VALUES ({user_id}, {role})", params.head, params.tail: _*).execute() Right(()) } } else Right(()) } else Right(()) } private case class RolesForAlias(surveyId: String, userName: String, roles: Set[String]) private def updateUserRolesByAlias(roles: Seq[RolesForAlias])(implicit connection: Connection): Either[RecordNotFound, Unit] = { if (roles.nonEmpty) { SQL("DELETE FROM user_roles WHERE user_id IN (SELECT user_id FROM user_survey_aliases WHERE (survey_id, user_name) IN (SELECT unnest(ARRAY[{survey_ids}]), unnest(ARRAY[{user_names}])))") .on('user_names -> roles.map(_.userName), 'survey_ids -> roles.map(_.surveyId)) .execute() val params = roles.flatMap { r => r.roles.map { role => Seq[NamedParameter]('survey_id -> r.surveyId, 'user_name -> r.userName, 'role -> role) } } if (!params.isEmpty) { tryWithConstraintCheck("user_roles_user_id_fkey", e => RecordNotFound(new RuntimeException(s"Could not update roles because one of the user records was not found"))) { BatchSql("INSERT INTO user_roles(user_id, role) SELECT user_id,{role} FROM user_survey_aliases WHERE survey_id={survey_id} AND user_name={user_name}", params.head, params.tail: _*).execute() Right(()) } } Right(()) } else Right(()) } private case class CustomDataForId(userId: Long, customData: Map[String, String]) private def updateCustomDataById(customData: Seq[CustomDataForId])(implicit connection: Connection): Either[UpdateError, Unit] = { if (customData.nonEmpty) { SQL("DELETE FROM user_custom_fields WHERE user_id IN ({user_ids})") .on('user_ids -> customData.map(_.userId)) .execute() val userCustomFieldParams = customData.flatMap { case r => r.customData.map { case (name, value) => Seq[NamedParameter]('user_id -> r.userId, 'name -> name, 'value -> value) } } if (!userCustomFieldParams.isEmpty) tryWithConstraintCheck("user_custom_fields_user_id_fkey", e => RecordNotFound(new RuntimeException(s"Could not update custom user data because one of the user records was not found"))) { BatchSql("INSERT INTO user_custom_fields VALUES (DEFAULT, {user_id}, {name}, {value})", userCustomFieldParams.head, userCustomFieldParams.tail: _*).execute() Right(()) } else Right(()) } else Right(()) } private case class CustomDataForAlias(surveyId: String, userName: String, customData: Map[String, String]) private def updateCustomDataByAlias(customData: Seq[CustomDataForAlias])(implicit connection: Connection): Either[UpdateError, Unit] = { if (customData.nonEmpty) { SQL("DELETE FROM user_custom_fields WHERE user_id IN (SELECT user_id FROM user_survey_aliases WHERE (survey_id, user_name) IN (SELECT unnest(ARRAY[{survey_ids}]), unnest(ARRAY[{user_names}])))") .on('survey_ids -> customData.map(_.surveyId), 'user_names -> customData.map(_.userName)) .execute() val userCustomFieldParams = customData.flatMap { case r => r.customData.map { case (name, value) => Seq[NamedParameter]('survey_id -> r.surveyId, 'user_name -> r.userName, 'name -> name, 'value -> value) } } if (!userCustomFieldParams.isEmpty) tryWithConstraintCheck("user_custom_fields_user_id_fkey", e => RecordNotFound(new RuntimeException(s"Could not update custom user data because one of the user records was not found"))) { BatchSql("INSERT INTO user_custom_fields (user_id, name, value) SELECT user_id, {name}, {value} FROM user_survey_aliases WHERE user_name={user_name} AND survey_id={survey_id}", userCustomFieldParams.head, userCustomFieldParams.tail: _*).execute() Right(()) } else Right(()) } else Right(()) } private case class SecurePasswordForAlias(alias: SurveyUserAlias, password: SecurePassword) private def createOrUpdatePasswordsByAlias(passwords: Seq[SecurePasswordForAlias])(implicit connection: Connection): Either[UnexpectedDatabaseError, Unit] = { if (passwords.nonEmpty) { val params = passwords.map { case p => Seq[NamedParameter]('user_name -> p.alias.userName, 'survey_id -> p.alias.surveyId, 'password_hash -> p.password.hashBase64, 'password_salt -> p.password.saltBase64, 'password_hasher -> p.password.hasher) } BatchSql( """INSERT INTO user_passwords(user_id, password_hash, password_salt, password_hasher) | SELECT user_id,{password_hash},{password_salt},{password_hasher} FROM user_survey_aliases WHERE user_name={user_name} AND survey_id={survey_id} | ON CONFLICT(user_id) DO UPDATE SET password_hash=excluded.password_hash,password_salt=excluded.password_salt,password_hasher=excluded.password_hasher""".stripMargin, params.head, params.tail: _*).execute() Right(()) } else Right(()) } private lazy val createOrUpdateUserByAliasQuery = sqlFromResource("admin/users/create_or_update_user_by_alias.sql") private def fetchNewRespondentIds(aliases: Seq[SurveyUserAlias])(implicit connection: Connection): Either[UnexpectedDatabaseError, Seq[NewRespondentIds]] = { Right(SQL( """with q(survey_id, user_name) as ( | select * | from unnest(ARRAY [{survey_ids}], ARRAY [{user_names}]) |) |select a.user_id, q.survey_id, q.user_name, a.url_auth_token |from q | join user_survey_aliases as a on q.survey_id = a.survey_id and q.user_name = a.user_name;""".stripMargin) .on('survey_ids -> aliases.map(_.surveyId), 'user_names -> aliases.map(_.userName)) .executeQuery() .as(Macro.namedParser[NewRespondentIds](ColumnNaming.SnakeCase).*)) } def createOrUpdateUsersWithAliases(usersWithAliases: Seq[NewUserWithAlias]): Either[DependentUpdateError, Seq[NewRespondentIds]] = tryWithConnection { implicit conn => withTransaction { val userUpsertParams = usersWithAliases.map { u => Seq[NamedParameter]('survey_id -> u.alias.surveyId, 'user_name -> u.alias.userName, 'url_auth_token -> URLAuthTokenUtils.generateToken, 'name -> u.userInfo.name, 'email -> u.userInfo.email, 'phone -> u.userInfo.phone, 'simple_name -> u.userInfo.name.map(StringUtils.stripAccents(_).toLowerCase())) } if (userUpsertParams.nonEmpty) { tryWithConstraintCheck[DependentUpdateError, Seq[NewRespondentIds]]("users_email_unique", e => DuplicateCode(e)) { BatchSql(createOrUpdateUserByAliasQuery, userUpsertParams.head, userUpsertParams.tail: _*).execute() for ( _ <- updateUserRolesByAlias(usersWithAliases.foldLeft(List[RolesForAlias]()) { case (acc, userRecord) => RolesForAlias(userRecord.alias.surveyId, userRecord.alias.userName, userRecord.userInfo.roles) +: acc }).right; _ <- updateCustomDataByAlias(usersWithAliases.foldLeft(List[CustomDataForAlias]()) { case (acc, record) => CustomDataForAlias(record.alias.surveyId, record.alias.userName, record.userInfo.customFields) +: acc }).right; _ <- createOrUpdatePasswordsByAlias(usersWithAliases.map(u => SecurePasswordForAlias(u.alias, u.password))).right; result <- fetchNewRespondentIds(usersWithAliases.map(_.alias)) ) yield result } } else Right(Seq()) } } def createUsersQuery(newUsers: Seq[NewUserProfile])(implicit connection: Connection): Either[CreateError, Seq[Long]] = { if (newUsers.isEmpty) Right(Seq()) else { val userParams = newUsers.map { newUser => Seq[NamedParameter]('simple_name -> newUser.name.map(StringUtils.stripAccents(_).toLowerCase()), 'name -> newUser.name, 'email -> newUser.email, 'phone -> newUser.phone) } tryWithConstraintCheck[CreateError, Seq[Long]]("users_email_unique", e => DuplicateCode(e)) { val batchSql = BatchSql("INSERT INTO users(name,email,phone,simple_name) VALUES ({name},{email},{phone},{simple_name})", userParams.head, userParams.tail: _*) val userIds = AnormUtil.batchKeys(batchSql) val userInfoWithId = newUsers.zip(userIds) (for ( _ <- updateUserRolesById(userInfoWithId.map { case (userInfo, userId) => RolesForId(userId, userInfo.roles) }).right; _ <- updateCustomDataById(userInfoWithId.map { case (userInfo, userId) => CustomDataForId(userId, userInfo.customFields) }).right ) yield userIds).left.map(e => UnexpectedDatabaseError(e.exception)) } } } private def createPasswordsQuery(passwords: Seq[SecurePasswordForId])(implicit connection: Connection): Either[CreateError, Unit] = { if (passwords.isEmpty) Right(()) else { val passwordParams = passwords.map { p => Seq[NamedParameter]('user_id -> p.userId, 'hash -> p.password.hashBase64, 'salt -> p.password.saltBase64, 'hasher -> p.password.hasher) } BatchSql("INSERT INTO user_passwords(user_id, password_hash, password_salt, password_hasher) VALUES({user_id},{hash},{salt},{hasher})", passwordParams.head, passwordParams.tail: _*).execute() Right(()) } } def createUserWithPassword(newUser: NewUserWithPassword): Either[CreateError, Long] = tryWithConnection { implicit conn => for (userId <- createUsersQuery(Seq(newUser.userInfo)).right.map(_.head).right; _ <- createPasswordsQuery(Seq(SecurePasswordForId(userId, newUser.password))).right ) yield userId } def createUsers(newUsers: Seq[NewUserProfile]): Either[CreateError, Seq[Long]] = tryWithConnection { implicit conn => createUsersQuery(newUsers) } def updateUserProfile(userId: Long, update: UserProfileUpdate): Either[UpdateError, Unit] = tryWithConnection { implicit conn => withTransaction { tryWithConstraintCheck[UpdateError, Unit]("users_email_unique", e => DuplicateCode(e)) { val count = SQL("UPDATE users SET name={name},email={email},phone={phone},simple_name={simple_name},email_notifications={email_n},sms_notifications={sms_n} WHERE id={user_id}") .on('user_id -> userId, 'name -> update.name, 'email -> update.email, 'phone -> update.phone, 'email_n -> update.emailNotifications, 'sms_n -> update.smsNotifications, 'simple_name -> update.name.map(StringUtils.stripAccents(_).toLowerCase())).executeUpdate() if (count == 1) { Right(()) } else Left(RecordNotFound(new RuntimeException(s"User $userId does not exist"))) } } } private case class UserInfoRow(id: Long, name: Option[String], email: Option[String], phone: Option[String], email_notifications: Boolean, sms_notifications: Boolean) private object UserProfileRow { val parser = Macro.namedParser[UserInfoRow] } private case class PasswordRow(password_hash: String, password_salt: String, password_hasher: String) private object PasswordRow { val parser = Macro.namedParser[PasswordRow] } def getUserById(userId: Long): Either[LookupError, UserProfile] = tryWithConnection { implicit conn => withTransaction { SQL("SELECT id, name, email, phone, email_notifications, sms_notifications FROM users WHERE id={user_id}") .on('user_id -> userId) .as(UserProfileRow.parser.singleOpt) match { case Some(row) => Right(buildUserRecordsFromRows(Seq(row)).head) case None => Left(RecordNotFound(new RuntimeException(s"User $userId does not exist"))) } } } def getUserByAlias(alias: SurveyUserAlias): Either[LookupError, UserProfile] = tryWithConnection { implicit conn => withTransaction { SQL("SELECT id, name, email, phone, email_notifications, sms_notifications FROM users JOIN user_survey_aliases ON users.id = user_survey_aliases.user_id WHERE survey_id={survey_id} AND user_name={user_name}") .on('survey_id -> alias.surveyId, 'user_name -> alias.userName) .as(UserProfileRow.parser.singleOpt) match { case Some(row) => Right(buildUserRecordsFromRows(Seq(row)).head) case None => Left(RecordNotFound(new RuntimeException(s"User alias ${alias.surveyId}/${alias.userName} does not exist"))) } } } def validateUrlToken(token: String): Either[LookupError, Unit] = tryWithConnection { implicit conn => val valid = SQL("SELECT 1 FROM user_survey_aliases WHERE url_auth_token={token}").on('token -> token).executeQuery().as(SqlParser.long(1).singleOpt).isDefined if (valid) Right(()) else Left(RecordNotFound(new RuntimeException(s"Invalid URL authentication token: $token"))) } def getUserByUrlToken(token: String): Either[LookupError, UserProfile] = tryWithConnection { implicit conn => withTransaction { SQL("SELECT id, name, email, phone, email_notifications, sms_notifications FROM users JOIN user_survey_aliases ON users.id = user_survey_aliases.user_id WHERE user_survey_aliases.url_auth_token={token}") .on('token -> token) .as(UserProfileRow.parser.singleOpt) match { case Some(row) => Right(buildUserRecordsFromRows(Seq(row)).head) case None => Left(RecordNotFound(new RuntimeException(s"User with given URL authentication token not found"))) } } } def getUserByEmail(email: String): Either[LookupError, UserProfile] = tryWithConnection { implicit conn => withTransaction { SQL("SELECT id, name, email, phone, email_notifications, sms_notifications FROM users WHERE lower(email)=lower({email})") .on('email -> email) .as(UserProfileRow.parser.singleOpt) match { case Some(row) => Right(buildUserRecordsFromRows(Seq(row)).head) case None => Left(RecordNotFound(new RuntimeException(s"User with e-mail address <$email> does not exist"))) } } } def deleteUsersById(userIds: Seq[Long]): Either[DeleteError, Unit] = tryWithConnection { implicit conn => tryWithConstraintCheck("survey_submissions_user_id_fkey", e => StillReferenced(new RuntimeException("User cannot be deleted because they have survey submissions", e))) { SQL("DELETE FROM users WHERE id IN({user_ids})").on('user_ids -> userIds).execute() Right(()) } } def deleteUsersByAlias(aliases: Seq[SurveyUserAlias]): Either[DeleteError, Unit] = tryWithConnection { implicit conn => tryWithConstraintCheck("survey_submissions_user_id_fkey", e => StillReferenced(new RuntimeException("User cannot be deleted because they have survey submissions", e))) { val params = aliases.map { a => Seq[NamedParameter]('survey_id -> a.surveyId, 'user_name -> a.userName) } if (params.nonEmpty) { BatchSql("DELETE FROM users WHERE id IN (SELECT user_id FROM user_survey_aliases AS a WHERE a.survey_id={survey_id} AND a.user_name={user_name})", params.head, params.tail: _*).execute() Right(()) } else Right(()) } } def giveAccessToSurvey(userAccessToSurvey: UserAccessToSurvey): Either[UpdateError, Unit] = tryWithConnection { implicit conn => val query = """ |INSERT INTO user_roles (user_id, role) |VALUES ({user_id}, {role}) |ON CONFLICT (user_id, role) DO NOTHING; """.stripMargin SQL(query).on( 'user_id -> userAccessToSurvey.userId, 'role -> userAccessToSurvey.role ).execute() Right(()) } def withdrawAccessToSurvey(userAccessToSurvey: UserAccessToSurvey): Either[UpdateError, Unit] = tryWithConnection { implicit conn => val query = """ |DELETE FROM user_roles |WHERE user_id={user_id} AND role={role}; """.stripMargin SQL(query).on( 'user_id -> userAccessToSurvey.userId, 'role -> userAccessToSurvey.role ).execute() Right(()) } def getUserPasswordById(userId: Long): Either[LookupError, SecurePassword] = tryWithConnection { implicit conn => SQL("SELECT password_hash, password_salt, password_hasher FROM user_passwords WHERE user_id={user_id}") .on('user_id -> userId) .as(PasswordRow.parser.singleOpt) match { case Some(row) => Right(SecurePassword(row.password_hash, row.password_salt, row.password_hasher)) case None => Left(RecordNotFound(new RuntimeException(s"User $userId does not exist"))) } } def getUserPasswordByAlias(alias: SurveyUserAlias): Either[LookupError, SecurePassword] = tryWithConnection { implicit conn => SQL("SELECT password_hash, password_salt, password_hasher FROM user_passwords JOIN user_survey_aliases AS a ON a.user_id=user_passwords.user_id WHERE a.survey_id={survey_id} AND a.user_name={user_name}") .on('survey_id -> alias.surveyId, 'user_name -> alias.userName) .as(PasswordRow.parser.singleOpt) match { case Some(row) => Right(SecurePassword(row.password_hash, row.password_salt, row.password_hasher)) case None => Left(RecordNotFound(new RuntimeException(s"User alias ${alias.surveyId}/${alias.userName} does not exist"))) } } def getUserPasswordByEmail(email: String): Either[LookupError, SecurePassword] = tryWithConnection { implicit conn => SQL("SELECT password_hash, password_salt, password_hasher FROM user_passwords JOIN users ON user_passwords.user_id=users.id WHERE lower(users.email)=lower({email})") .on('email -> email) .as(PasswordRow.parser.singleOpt) match { case Some(row) => Right(SecurePassword(row.password_hash, row.password_salt, row.password_hasher)) case None => Left(RecordNotFound(new RuntimeException(s"User with e-mail addess <$email> does not exist"))) } } def updateUserPassword(userId: Long, update: SecurePassword): Either[UpdateError, Unit] = tryWithConnection { implicit conn => val count = SQL("UPDATE user_passwords SET password_hash={hash},password_salt={salt},password_hasher={hasher} WHERE user_id={user_id}") .on('user_id -> userId, 'hash -> update.hashBase64, 'salt -> update.saltBase64, 'hasher -> update.hasher) .executeUpdate() if (count != 1) Left(RecordNotFound(new RuntimeException(s"Password for $userId does not exist"))) else Right(()) } def updateUserRoles(userId: Long, update: UserRolesUpdate): Either[UpdateError, Unit] = tryWithConnection { implicit conn => withTransaction { updateUserRolesById(Seq(RolesForId(userId, update.roles))) } } private def getUserRoles(userIds: Seq[Long])(implicit connection: java.sql.Connection): Map[Long, Set[String]] = { if (userIds.isEmpty) Map() else SQL("SELECT user_id, role FROM user_roles WHERE user_id IN ({user_ids})") .on('user_ids -> userIds).as((SqlParser.long("user_id") ~ SqlParser.str("role")).*).foldLeft(Map[Long, Set[String]]()) { case (acc, userId ~ role) => acc + (userId -> (acc.getOrElse(userId, Set()) + role)) } } private def getUserCustomData(userIds: Seq[Long])(implicit connection: java.sql.Connection): Map[Long, Map[String, String]] = { if (userIds.isEmpty) Map() else SQL("SELECT user_id, name, value FROM user_custom_fields WHERE user_id IN ({user_ids})") .on('user_ids -> userIds).as((SqlParser.long("user_id") ~ SqlParser.str("name") ~ SqlParser.str("value")).*).foldLeft(Map[Long, Map[String, String]]()) { case (acc, userId ~ name ~ value) => acc + (userId -> (acc.getOrElse(userId, Map()) + (name -> value))) } } def createSurveyUserAliasesQuery(surveyId: String, surveyUserNames: Map[Long, String])(implicit connection: java.sql.Connection): Either[DependentCreateError, Map[Long, String]] = { if (surveyUserNames.isEmpty) Right(Map()) else { val errors = Map[String, PSQLException => DependentCreateError]( "user_aliases_pkey" -> (e => DuplicateCode(e)), "user_aliases_user_id_fkey" -> (e => ParentRecordNotFound(e)), "user_aliases_survey_id_fkey" -> (e => ParentRecordNotFound(e)) ) val authTokens = surveyUserNames.map { case (userId, _) => (userId, URLAuthTokenUtils.generateToken) } val params = surveyUserNames.toSeq.map { case (userId, userName) => Seq[NamedParameter]('user_id -> userId, 'survey_id -> surveyId, 'user_name -> userName, 'auth_token -> authTokens(userId)) } tryWithConstraintsCheck[DependentCreateError, Map[Long, String]](errors) { BatchSql("INSERT INTO user_survey_aliases (user_id, survey_id, user_name, url_auth_token) VALUES ({user_id},{survey_id},{user_name},{auth_token})", params.head, params.tail: _*).execute() Right(authTokens) } } } def getSurveyUserAliases(userIds: Seq[Long], surveyId: String): Either[UnexpectedDatabaseError, Map[Long, SurveyUserAliasData]] = tryWithConnection { implicit connection => if (userIds.isEmpty) Right(Map()) else Right(SQL("SELECT user_id, user_name, url_auth_token FROM user_survey_aliases WHERE user_id IN ({user_ids}) AND survey_id={survey_id}") .on('user_ids -> userIds, 'survey_id -> surveyId) .as((SqlParser.long("user_id") ~ SqlParser.str("user_name") ~ SqlParser.str("url_auth_token")).*).foldLeft(Map[Long, SurveyUserAliasData]()) { case (acc, userId ~ userName ~ authToken) => acc + (userId -> SurveyUserAliasData(userName, authToken)) }) } private def buildUserRecordsFromRows(rows: Seq[UserInfoRow])(implicit connection: java.sql.Connection): Seq[UserProfile] = { val roles = getUserRoles(rows.map(_.id)).withDefaultValue(Set[String]()) val customData = getUserCustomData(rows.map(_.id)).withDefaultValue(Map[String, String]()) rows.map { row => UserProfile(row.id, row.name, row.email, row.phone, row.email_notifications, row.sms_notifications, roles(row.id), customData(row.id)) } } def findUsers(query: String, limit: Int): Either[UnexpectedDatabaseError, Seq[UserProfile]] = tryWithConnection { implicit conn => withTransaction { val rows = SQL("SELECT id,name,email,phone,email_notifications,sms_notifications FROM users WHERE (simple_name LIKE {name_query} OR email LIKE {query}) ORDER BY id LIMIT {limit}") .on('name_query -> ("%" + AnormUtil.escapeLike(StringUtils.stripAccents(query).toLowerCase()) + "%"), 'query -> ("%" + AnormUtil.escapeLike(query) + "%"), 'limit -> limit) .as(UserProfileRow.parser.*) Right(buildUserRecordsFromRows(rows)) } } def listUsersByRole(role: String, offset: Int, limit: Int): Either[UnexpectedDatabaseError, Seq[UserProfile]] = tryWithConnection { implicit conn => withTransaction { val rows = SQL("SELECT id,name,email,phone,email_notifications,sms_notifications FROM users JOIN user_roles ON users.id=user_roles.user_id AND role={role} ORDER BY id OFFSET {offset} LIMIT {limit}") .on('role -> role, 'offset -> offset, 'limit -> limit) .as(UserProfileRow.parser.*) Right(buildUserRecordsFromRows(rows)) } } private case class UserDataRow(name: String, value: String) def getUserCustomData(userId: Long): Either[LookupError, Map[String, String]] = tryWithConnection { implicit conn => withTransaction { val userExists = SQL("SELECT 1 FROM users WHERE id={user_id}").on('user_id -> userId).executeQuery().as(SqlParser.long(1).singleOpt).nonEmpty if (!userExists) Left(RecordNotFound(new RuntimeException(s"User $userId does not exist"))) else { val result = SQL("SELECT name, value FROM user_custom_fields WHERE user_id={user_id}") .on('user_id -> userId) .executeQuery().as(Macro.namedParser[UserDataRow].*).map(row => (row.name, row.value)).toMap Right(result) } } } def updateUserCustomData(userId: Long, data: Map[String, String]): Either[UpdateError, Unit] = tryWithConnection { implicit conn => withTransaction { val userExists = SQL("SELECT 1 FROM users WHERE id={user_id}").on('user_id -> userId).executeQuery().as(SqlParser.long(1).singleOpt).nonEmpty if (!userExists) Left(RecordNotFound(new RuntimeException(s"User $userId does not exist"))) else updateCustomDataById(Seq(CustomDataForId(userId, data))) } } def nextGeneratedUserId(surveyId: String): Either[UnexpectedDatabaseError, Int] = tryWithConnection { implicit conn => Right(SQL("INSERT INTO gen_user_counters VALUES({survey_id}, 0) ON CONFLICT(survey_id) DO UPDATE SET count=gen_user_counters.count+1 RETURNING count") .on('survey_id -> surveyId) .executeQuery() .as(SqlParser.int("count").single)) } override def getAuthTokenByUserId(userId: Long): Either[LookupError, String] = tryWithConnection { implicit conn => SQL("SELECT url_auth_token FROM user_survey_aliases WHERE user_id = {user_id}") .on('user_id -> userId) .as(SqlParser.str("url_auth_token").singleOpt) match { case Some(str) => Right(str) case None => Left(RecordNotFound(new Exception(s"Couldn't find user with user id $userId"))) } } }
digitalinteraction/intake24
SystemDataSQL/src/main/scala/uk/ac/ncl/openlab/intake24/systemsql/admin/UserAdminImpl.scala
Scala
apache-2.0
27,301
/* Copyright 2013 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.summingbird.online import com.twitter.summingbird._ import com.twitter.summingbird.planner._ import com.twitter.summingbird.memory.Memory import scala.collection.mutable.{Map => MMap} import org.scalacheck._ import Gen._ import Arbitrary._ import org.scalacheck.Prop._ object TopologyPlannerLaws extends Properties("Online Dag") { implicit def extractor[T]: TimeExtractor[T] = TimeExtractor(_ => 0L) private type MemoryDag = Dag[Memory] import TestGraphGenerators._ implicit def sink1: Memory#Sink[Int] = sample[Int => Unit] implicit def sink2: Memory#Sink[(Int, Int)] = sample[((Int, Int)) => Unit] implicit def testStore: Memory#Store[Int, Int] = MMap[Int, Int]() implicit val arbSource1: Arbitrary[Producer[Memory, Int]] = Arbitrary(Gen.listOfN(100, Arbitrary.arbitrary[Int]).map{ x: List[Int] => Memory.toSource(x)}) implicit val arbSource2: Arbitrary[KeyedProducer[Memory, Int, Int]] = Arbitrary(Gen.listOfN(100, Arbitrary.arbitrary[(Int, Int)]).map{ x: List[(Int, Int)] => IdentityKeyedProducer(Memory.toSource(x))}) lazy val genGraph : Gen[TailProducer[Memory, _]]= for { tail <- oneOf(summed, written) } yield tail implicit def genDag: Arbitrary[MemoryDag] = Arbitrary(genGraph.map(OnlinePlan(_))) implicit def genProducer: Arbitrary[TailProducer[Memory, _]] = Arbitrary(genGraph) val testFn = { i: Int => List((i -> i)) } def sample[T: Arbitrary]: T = Arbitrary.arbitrary[T].sample.get var dumpNumber = 1 def dumpGraph(dag: MemoryDag) = { import java.io._ import com.twitter.summingbird.viz.VizGraph val writer2 = new PrintWriter(new File("/tmp/failingGraph" + dumpNumber + ".dot")) VizGraph(dag, writer2) writer2.close() dumpNumber = dumpNumber + 1 } def dumpGraph(tail: Producer[Memory, Any]) = { import java.io._ import com.twitter.summingbird.viz.VizGraph val writer2 = new PrintWriter(new File("/tmp/failingProducerGraph" + dumpNumber + ".dot")) VizGraph(tail, writer2) writer2.close() dumpNumber = dumpNumber + 1 } property("Dag Nodes must be unique") = forAll { (dag: MemoryDag) => dag.nodes.size == dag.nodes.toSet.size } property("Must have at least one producer in each MemoryNode") = forAll { (dag: MemoryDag) => dag.nodes.forall{n => n.members.size > 0 } } property("If a Node contains a Summer, all other producers must be NOP's") = forAll { (dag: MemoryDag) => dag.nodes.forall{n => val producersWithoutNOP = n.members.filterNot(Producer.isNoOp(_)) val firstP = producersWithoutNOP.headOption producersWithoutNOP.forall{p => val inError = (p.isInstanceOf[Summer[_, _, _]] && producersWithoutNOP.size != 1) if(inError) dumpGraph(dag) !inError } } } property("The first producer in a online node cannot be a NamedProducer") = forAll { (dag: MemoryDag) => dag.nodes.forall{n => val inError = n.members.last.isInstanceOf[NamedProducer[_, _]] if(inError) dumpGraph(dag) !inError } } property("0 or more merge producers at the start of every online bolts, followed by 1+ non-merge producers and no other merge producers following those.") = forAll { (dag: MemoryDag) => dag.nodes.forall{n => val (_, inError) = n.members.foldLeft((false, false)) { case ((seenMergeProducer, inError), producer) => producer match { case MergedProducer(_, _) => (true, inError) case NamedProducer(_, _) => (seenMergeProducer, inError) case _ => (seenMergeProducer, (inError || seenMergeProducer)) } } if(inError) dumpGraph(dag) !inError } } property("No producer is repeated") = forAll { (dag: MemoryDag) => val numAllProducers = dag.nodes.foldLeft(0){(sum, n) => sum + n.members.size} val allProducersSet = dag.nodes.foldLeft(Set[Producer[Memory, _]]()){(runningSet, n) => runningSet | n.members.toSet} numAllProducers == allProducersSet.size } property("All producers are in a Node") = forAll { (dag: MemoryDag) => val allProducers = Producer.entireGraphOf(dag.tail).toSet + dag.tail val numAllProducersInDag = dag.nodes.foldLeft(0){(sum, n) => sum + n.members.size} allProducers.size == numAllProducersInDag } property("Only sources can have no incoming dependencies") = forAll { (dag: MemoryDag) => dag.nodes.forall{n => val success = n match { case _: SourceNode[_] => true case _ => dag.dependenciesOf(n).size > 0 } if(!success) dumpGraph(dag) success } } property("Sources must have no incoming dependencies, and they must have dependants") = forAll { (dag: MemoryDag) => dag.nodes.forall{n => val success = n match { case _: SourceNode[_] => dag.dependenciesOf(n).size == 0 && dag.dependantsOf(n).size > 0 case _ => true } if(!success) dumpGraph(dag) success } } property("Prior to a summer the Nonde should be a FlatMap Node") = forAll { (dag: MemoryDag) => dag.nodes.forall{n => val firstP = n.members.last val success = firstP match { case Summer(_, _, _) => dag.dependenciesOf(n).size > 0 && dag.dependenciesOf(n).forall {otherN => otherN.isInstanceOf[FlatMapNode[_]] } case _ => true } if(!success) dumpGraph(dag) success } } property("There should be no flatmap producers in the source node") = forAll { (dag: MemoryDag) => dag.nodes.forall{n => val success = n match { case n: SourceNode[_] => n.members.forall{p => !p.isInstanceOf[FlatMappedProducer[_, _, _]]} case _ => true } if(!success) dumpGraph(dag) success } } property("Nodes in the DAG should have unique names") = forAll { (dag: MemoryDag) => val allNames = dag.nodes.toList.map{n => dag.getNodeName(n)} allNames.size == allNames.distinct.size } property("Running through the optimizer should only reduce the number of nodes") = forAll { (tail: TailProducer[Memory, _]) => val (_, stripped) = StripNamedNode(tail) Producer.entireGraphOf(stripped).size <= Producer.entireGraphOf(tail).size } property("The number of non-named nodes should remain constant running with StripNamedNode") = forAll { (tail: TailProducer[Memory, _]) => def countNonNamed(tail: Producer[Memory, _]): Int = { Producer.entireGraphOf(tail).collect { case NamedProducer(_, _) => 0 case _ => 1 }.sum } val (_, stripped) = StripNamedNode(tail) countNonNamed(tail) == countNonNamed(stripped) } }
sengt/summingbird-batch
summingbird-online/src/test/scala/com/twitter/summingbird/online/TopologyPlannerLaws.scala
Scala
apache-2.0
7,292
/* * Copyright (c) 2014 Snowplow Analytics Ltd. * All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache * License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. * * See the Apache License Version 2.0 for the specific language * governing permissions and limitations there under. */ package com.snowplowanalytics.snowplow.storage.kinesis.elasticsearch // Java import java.io.File import java.util.Properties // Config import com.typesafe.config.{Config,ConfigFactory,ConfigException} // Argot import org.clapper.argot.ArgotParser // AWS libs import com.amazonaws.auth.DefaultAWSCredentialsProviderChain // AWS Kinesis Connector libs import com.amazonaws.services.kinesis.connectors.KinesisConnectorConfiguration // Scalaz import scalaz._ import Scalaz._ // json4s import org.json4s._ import org.json4s.jackson.JsonMethods._ import org.json4s.JsonDSL._ // Tracker import com.snowplowanalytics.snowplow.scalatracker.Tracker import com.snowplowanalytics.snowplow.scalatracker.SelfDescribingJson import com.snowplowanalytics.snowplow.scalatracker.emitters.AsyncEmitter // Common Enrich import com.snowplowanalytics.snowplow.enrich.common.outputs.BadRow // This project import sinks._ // Whether the input stream contains enriched events or bad events object StreamType extends Enumeration { type StreamType = Value val Good, Bad = Value } /** * Main entry point for the Elasticsearch sink */ object ElasticsearchSinkApp extends App { val parser = new ArgotParser( programName = generated.Settings.name, compactUsage = true, preUsage = Some("%s: Version %s. Copyright (c) 2015, %s.".format( generated.Settings.name, generated.Settings.version, generated.Settings.organization) ) ) // Mandatory config argument val config = parser.option[Config](List("config"), "filename", "Configuration file.") { (c, opt) => val file = new File(c) if (file.exists) { ConfigFactory.parseFile(file) } else { parser.usage("Configuration file \"%s\" does not exist".format(c)) ConfigFactory.empty() } } parser.parse(args) val resolvedConfig: Config = config.value.getOrElse(throw new RuntimeException("--config argument must be provided")).resolve private val sink = resolvedConfig.getConfig("sink") val streamType = configValue.getString("stream-type") match { case "good" => StreamType.Good case "bad" => StreamType.Bad case _ => throw new RuntimeException("\"stream-type\" must be set to \"good\" or \"bad\"") } val elasticsearch = sink.getConfig("elasticsearch") val documentIndex = elasticsearch.getString("index") val documentType = elasticsearch.getString("type") val tracker = if (sink.hasPath("monitoring.snowplow")) { SnowplowTracking.initializeTracker(sink.getConfig("monitoring.snowplow")).some } else { None } val maxConnectionTime = configValue.getConfig("elasticsearch").getLong("max-timeout") val finalConfig = convertConfig(configValue) val goodSink = configValue.getString("sink.good") match { case "stdout" => Some(new StdouterrSink) case "elasticsearch" => None } val badSink = configValue.getString("sink.bad") match { case "stderr" => new StdouterrSink case "none" => new NullSink case "kinesis" => { val kinesis = configValue.getConfig("kinesis") val kinesisSink = kinesis.getConfig("out") val kinesisSinkName = kinesisSink.getString("stream-name") val kinesisSinkShards = kinesisSink.getInt("shards") val kinesisSinkRegion = kinesis.getString("region") val kinesisSinkEndpoint = s"https://kinesis.${kinesisSinkRegion}.amazonaws.com" new KinesisSink(finalConfig.AWS_CREDENTIALS_PROVIDER, kinesisSinkEndpoint, kinesisSinkName, kinesisSinkShards) } } val executor = configValue.getString("source") match { val executor = sink.getString("source") match { // Read records from Kinesis case "kinesis" => { new ElasticsearchSinkExecutor(streamType, documentIndex, documentType, finalConfig, goodSink, badSink, tracker, maxConnectionTime).success } // Run locally, reading from stdin and sending events to stdout / stderr rather than Elasticsearch / Kinesis // TODO reduce code duplication case "stdin" => new Runnable { val transformer = streamType match { case StreamType.Good => new SnowplowElasticsearchTransformer(documentIndex, documentType) case StreamType.Bad => new BadEventTransformer(documentIndex, documentType) } lazy val elasticsearchSender = new ElasticsearchSender(finalConfig, None, maxConnectionTime) def run = for (ln <- scala.io.Source.stdin.getLines) { val emitterInput = transformer.consumeLine(ln) emitterInput._2.bimap( f => badSink.store(FailureUtils.getBadRow(emitterInput._1, f), None, false), s => goodSink match { case Some(gs) => gs.store(s.getSource, None, true) case None => elasticsearchSender.sendToElasticsearch(List(ln -> s.success)) } ) } }.success case _ => "Source must be set to 'stdin' or 'kinesis'".fail } executor.fold( err => throw new RuntimeException(err), exec => { tracker foreach { t => SnowplowTracking.initializeSnowplowTracking(t) } exec.run() } ) // Return Options from the configuration. object Helper { implicit class RichConfig(val underlying: Config) extends AnyVal { def getOptionalString(path: String): Option[String] = try { Some(underlying.getString(path)) } catch { case e: ConfigException.Missing => None } } } /** * Builds a KinesisConnectorConfiguration from the "connector" field of the configuration HOCON * * @param connector The "connector" field of the configuration HOCON * @return A KinesisConnectorConfiguration */ def convertConfig(connector: Config): (Properties, KinesisConnectorConfiguration) = { import Helper.RichConfig val props = new Properties props.setProperty("documentIndex", documentIndex) props.setProperty("documentType", documentType) val aws = connector.getConfig("aws") val accessKey = aws.getString("access-key") val secretKey = aws.getString("secret-key") val elasticsearch = connector.getConfig("elasticsearch") val elasticsearchEndpoint = elasticsearch.getString("endpoint") val elasticsearchPort = elasticsearch.getString("port") val clusterName = elasticsearch.getOptionalString("cluster-name") props.setProperty("appIdToIndex", elasticsearch.getString("appIdToIndex")) val kinesis = connector.getConfig("kinesis") val kinesisIn = kinesis.getConfig("in") val streamRegion = kinesis.getString("region") val appName = kinesis.getString("app-name") val initialPosition = kinesisIn.getString("initial-position") val streamName = kinesisIn.getString("stream-name") val streamEndpoint = s"https://kinesis.${streamRegion}.amazonaws.com" val buffer = connector.getConfig("buffer") val byteLimit = buffer.getString("byte-limit") val recordLimit = buffer.getString("record-limit") val timeLimit = buffer.getString("time-limit") props.setProperty(KinesisConnectorConfiguration.PROP_ELASTICSEARCH_ENDPOINT, elasticsearchEndpoint) props.setProperty(KinesisConnectorConfiguration.PROP_ELASTICSEARCH_PORT, elasticsearchPort) if (clusterName == None) { props.setProperty(KinesisConnectorConfiguration.PROP_ELASTICSEARCH_IGNORE_CLUSTER_NAME, "true") props.setProperty(KinesisConnectorConfiguration.PROP_ELASTICSEARCH_CLUSTER_NAME, appName) } else { props.setProperty(KinesisConnectorConfiguration.PROP_ELASTICSEARCH_IGNORE_CLUSTER_NAME, "false") props.setProperty(KinesisConnectorConfiguration.PROP_ELASTICSEARCH_CLUSTER_NAME, clusterName.get) } props.setProperty(KinesisConnectorConfiguration.PROP_REGION_NAME, streamRegion) props.setProperty(KinesisConnectorConfiguration.PROP_APP_NAME, appName) props.setProperty(KinesisConnectorConfiguration.PROP_INITIAL_POSITION_IN_STREAM, initialPosition) props.setProperty(KinesisConnectorConfiguration.PROP_KINESIS_INPUT_STREAM, streamName) props.setProperty(KinesisConnectorConfiguration.PROP_KINESIS_ENDPOINT, streamEndpoint) props.setProperty(KinesisConnectorConfiguration.PROP_BUFFER_BYTE_SIZE_LIMIT, byteLimit) props.setProperty(KinesisConnectorConfiguration.PROP_BUFFER_RECORD_COUNT_LIMIT, recordLimit) props.setProperty(KinesisConnectorConfiguration.PROP_BUFFER_MILLISECONDS_LIMIT, timeLimit) props.setProperty(KinesisConnectorConfiguration.PROP_CONNECTOR_DESTINATION, "elasticsearch") props.setProperty(KinesisConnectorConfiguration.PROP_RETRY_LIMIT, "1") (props, new KinesisConnectorConfiguration(props, CredentialsLookup.getCredentialsProvider(accessKey, secretKey))) } }
jramos/snowplow
4-storage/kinesis-elasticsearch-sink/src/main/scala/com.snowplowanalytics.snowplow.storage.kinesis/elasticsearch/ElasticsearchSinkApp.scala
Scala
apache-2.0
9,333
package com.productfoundry.akka.cqrs.process import akka.actor.Props import com.productfoundry.akka.PassivationConfig import com.productfoundry.akka.cqrs.{AggregateEvent, EntityIdResolution, AggregateEventHeaders, AggregateTag} object DummyProcessManager extends ProcessManagerCompanion[DummyProcessManager] { override def idResolution: EntityIdResolution[DummyProcessManager] = new ProcessIdResolution[DummyProcessManager] { override def processIdResolver: ProcessIdResolver = { case event: AggregateEvent => event.id.toString } } def factory() = new ProcessManagerFactory[DummyProcessManager] { override def props(config: PassivationConfig): Props = { Props(new DummyProcessManager(config)) } } } class DummyProcessManager(val passivationConfig: PassivationConfig) extends ProcessManager[Any, Any] { override def receiveEvent(tag: AggregateTag, headers: AggregateEventHeaders): ReceiveEvent = { case event => context.system.eventStream.publish(event) } }
odd/akka-cqrs
core/src/test/scala/com/productfoundry/akka/cqrs/process/DummyProcessManager.scala
Scala
apache-2.0
1,007
/* SimpleApp.scala */ import org.apache.spark.SparkContext import org.apache.spark.SparkContext._ import org.apache.spark.SparkConf object SimpleApp { def main(args: Array[String]) { val conf = new SparkConf().setAppName("SimpleApp") val sc = new SparkContext(conf) //val logFile = "YOUR_SPARK_HOME/README.md" // Should be some file on your system //val conf = new SparkConf().setAppName("Simple Application") //val sc = new SparkContext(conf) //val logData = sc.textFile(logFile, 2).cache() //val numAs = logData.filter(line => line.contains("a")).count() //val numBs = logData.filter(line => line.contains("b")).count() //println("Lines with a: %s, Lines with b: %s".format(numAs, numBs)) HelloWorld.PrintMessage(); } }
HintonBR/scratch
language-experiments/scala/SimpleApp.scala
Scala
mit
767
/* * Ported by Alistair Johnson from * https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/math/Conversion.java * Original license copied below: */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.math import scala.annotation.tailrec import java.util.ScalaOps._ /** Provides {@link BigInteger} base conversions. * * Static library that provides {@link BigInteger} base conversion from/to any * integer represented in a {@link java.lang.String} Object. */ private[math] object Conversion { /** Holds the maximal exponent for each radix. * * Holds the maximal exponent for each radix, so that * radix<sup>digitFitInInt[radix]</sup> fit in an {@code int} (32 bits). */ final val DigitFitInInt = Array( -1, -1, 31, 19, 15, 13, 11, 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5) /** Precomputed maximal powers of radices. * * BigRadices values are precomputed maximal powers of radices (integer * numbers from 2 to 36) that fit into unsigned int (32 bits). bigRadices[0] = * 2 ^ 31, bigRadices[8] = 10 ^ 9, etc. */ final val BigRadices = Array( -2147483648, 1162261467, 1073741824, 1220703125, 362797056, 1977326743, 1073741824, 387420489, 1000000000, 214358881, 429981696, 815730721, 1475789056, 170859375, 268435456, 410338673, 612220032, 893871739, 1280000000, 1801088541, 113379904, 148035889, 191102976, 244140625, 308915776, 387420489, 481890304, 594823321, 729000000, 887503681, 1073741824, 1291467969, 1544804416, 1838265625, 60466176) /** @see BigInteger#toString(int) */ def bigInteger2String(bi: BigInteger, radix: Int): String = { val sign = bi.sign val numberLength = bi.numberLength val digits = bi.digits val radixOutOfBounds = radix < Character.MIN_RADIX || radix > Character.MAX_RADIX if (sign == 0) { "0" } else if (numberLength == 1) { val highDigit = digits(numberLength - 1) var v = highDigit & 0xFFFFFFFFL if (sign < 0) v = -v java.lang.Long.toString(v, radix) } else if (radix == 10 || radixOutOfBounds) { bi.toString } else { var bitsForRadixDigit: Double = 0.0 bitsForRadixDigit = Math.log(radix) / Math.log(2) val addForSign = if (sign < 0) 1 else 0 val biAbsLen = bi.abs().bitLength() val resLenInChars = (biAbsLen / bitsForRadixDigit + addForSign).toInt + 1 var result: String = "" var currentChar = resLenInChars var resDigit: Int = 0 if (radix != 16) { val temp = new Array[Int](numberLength) System.arraycopy(digits, 0, temp, 0, numberLength) var tempLen = numberLength val charsPerInt = DigitFitInInt(radix) val bigRadix = BigRadices(radix - 2) @inline @tailrec def loop(): Unit = { resDigit = Division.divideArrayByInt(temp, temp, tempLen, bigRadix) val previous = currentChar @inline @tailrec def innerLoop(): Unit = { currentChar -= 1 result = Character.forDigit(resDigit % radix, radix).toString + result resDigit /= radix if(resDigit != 0 && currentChar != 0) innerLoop() } innerLoop() val delta = charsPerInt - previous + currentChar var i: Int = 0 while (i < delta && currentChar > 0) { currentChar -= 1 result = "0" + result i += 1 } i = tempLen - 1 while (i > 0 && temp(i) == 0) { i -= 1 } tempLen = i + 1 if (!(tempLen == 1 && temp(0) == 0)) loop() } loop() } else { for (i <- 0 until numberLength) { var j = 0 while (j < 8 && currentChar > 0) { resDigit = digits(i) >> (j << 2) & 0xf currentChar -= 1 result = Integer.toHexString(resDigit) + result j += 1 } } } // strip leading zero's var dropLen = 0 while (result.charAt(dropLen) == '0') dropLen += 1 if (dropLen != 0) result = result.substring(dropLen) if (sign == -1) "-" + result else result } } /** The string representation scaled by zero. * * Builds the correspondent {@code String} representation of {@code val} being * scaled by 0. * * @see BigInteger#toString() * @see BigDecimal#toString() */ def toDecimalScaledString(bi: BigInteger): String = { val sign: Int = bi.sign val numberLength: Int = bi.numberLength val digits: Array[Int] = bi.digits if (sign == 0) { "0" } else if (numberLength == 1) { val absStr = Integer.toUnsignedString(digits(0)) if (sign < 0) "-" + absStr else absStr } else { var result: String = "" val temp = new Array[Int](numberLength) var tempLen = numberLength System.arraycopy(digits, 0, temp, 0, tempLen) do { // Divide the array of digits by 1000000000 and compute the remainder var rem: Int = 0 var i: Int = tempLen - 1 while (i >= 0) { val temp1 = (rem.toLong << 32) + (temp(i) & 0xFFFFFFFFL) val quot = java.lang.Long.divideUnsigned(temp1, 1000000000L).toInt temp(i) = quot rem = (temp1 - quot * 1000000000L).toInt i -= 1 } // Convert the remainder to string, and add it to the result val remStr = rem.toString() val padding = "000000000".substring(remStr.length) result = padding + remStr + result while ((tempLen != 0) && (temp(tempLen - 1) == 0)) tempLen -= 1 } while (tempLen != 0) result = dropLeadingZeros(result) if (sign < 0) "-" + result else result } } private def dropLeadingZeros(s: String): String = { var zeroPrefixLength = 0 val len = s.length while (zeroPrefixLength < len && s.charAt(zeroPrefixLength) == '0') zeroPrefixLength += 1 s.substring(zeroPrefixLength) } /* can process only 32-bit numbers */ def toDecimalScaledString(value: Long, scale: Int): String = { if (value == 0) { scale match { case 0 => "0" case 1 => "0.0" case 2 => "0.00" case 3 => "0.000" case 4 => "0.0000" case 5 => "0.00000" case 6 => "0.000000" case _ => val scaleVal = if (scale == Int.MinValue) "2147483648" else java.lang.Integer.toString(-scale) val result = if (scale < 0) "0E+" else "0E" result + scaleVal } } else { // one 32-bit unsigned value may contains 10 decimal digits // Explanation why 10+1+7: // +1 - one char for sign if needed. // +7 - For "special case 2" (see below) we have 7 free chars for inserting necessary scaled digits. val resLengthInChars = 18 val negNumber = value < 0 var result = "" // Allocated [resLengthInChars+1] characters. // a free latest character may be used for "special case 1" (see below) var currentChar = resLengthInChars var v: Long = if (negNumber) -value else value do { val prev = v v /= 10 currentChar -= 1 result = (prev - v * 10).toInt.toString + result } while (v != 0) val exponent: Long = resLengthInChars - currentChar - scale.toLong - 1 if (scale > 0 && exponent >= -6L) { val index = exponent.toInt + 1 if (index > 0) { // special case 1 result = result.substring(0, index) + "." + result.substring(index) } else { // special case 2 for (j <- 0 until -index) { result = "0" + result } result = "0." + result } } else if (scale != 0) { val exponentStr = if (exponent > 0) "E+" + exponent else "E" + exponent result = if (resLengthInChars - currentChar > 1) result.substring(0, 1) + "." + result.substring(1) + exponentStr else result + exponentStr } if (negNumber) "-" + result else result } } def bigInteger2Double(bi: BigInteger): Double = { if (bi.numberLength < 2 || ((bi.numberLength == 2) && (bi.digits(1) > 0))) { bi.longValue().toDouble } else if (bi.numberLength > 32) { if (bi.sign > 0) Double.PositiveInfinity else Double.NegativeInfinity } else { val bitLen = bi.abs().bitLength() var exponent: Long = bitLen - 1 val delta = bitLen - 54 val lVal = bi.abs().shiftRight(delta).longValue() var mantissa = lVal & 0x1FFFFFFFFFFFFFL if (exponent == 1023 && mantissa == 0X1FFFFFFFFFFFFFL) { if (bi.sign > 0) Double.PositiveInfinity else Double.NegativeInfinity } else if (exponent == 1023 && mantissa == 0x1FFFFFFFFFFFFEL) { if (bi.sign > 0) Double.MaxValue else -Double.MaxValue } else { val droppedBits = BitLevel.nonZeroDroppedBits(delta, bi.digits) if (((mantissa & 1) == 1) && (((mantissa & 2) == 2) || droppedBits)) mantissa += 2 mantissa >>= 1 val resSign = if (bi.sign < 0) 0x8000000000000000L else 0 exponent = ((1023 + exponent) << 52) & 0x7FF0000000000000L val result = resSign | exponent | mantissa java.lang.Double.longBitsToDouble(result) } } } }
scala-js/scala-js
javalib/src/main/scala/java/math/Conversion.scala
Scala
apache-2.0
10,377
/* * Copyright 2016 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.ct.computations.calculations import org.scalatest.{Matchers, WordSpec} import uk.gov.hmrc.ct.CATO20 import uk.gov.hmrc.ct.computations.CP92._ import uk.gov.hmrc.ct.computations._ class MachineryAndPlantCalculatorSpec extends WordSpec with Matchers { "computeBalanceAllowance CP90" should { "calculate Balance Allowance" in new MachineryAndPlantCalculator { computeBalanceAllowance(cpq8 = CPQ8(Some(true)), cp78 = CP78(1), cp666 = CP666(2), cp674 = CP674(3), cp84 = CP84(4), cpAux1 = CPAux1(5), cpAux2 = CPAux2(6), cpAux3 = CPAux3(7), cp673 = CP673(8)) shouldBe CP90(Some(12)) } "calculate Balance Allowance where cpq8 is true and calculation < 0" in new MachineryAndPlantCalculator { computeBalanceAllowance(cpq8 = CPQ8(Some(true)), cp78 = CP78(1), cp666 = CP666(2), cp674 = CP674(3), cp84 = CP84(4), cpAux1 = CPAux1(5), cpAux2 = CPAux2(6), cpAux3 = CPAux3(7), cp673 = CP673(20)) shouldBe CP90(Some(0)) } "calculate Balance Allowance where cpq8 is false" in new MachineryAndPlantCalculator { computeBalanceAllowance(cpq8 = CPQ8(Some(false)), cp78 = CP78(1), cp666 = CP666(2), cp674 = CP674(3), cp84 = CP84(4), cpAux1 = CPAux1(5), cpAux2 = CPAux2(6), cpAux3 = CPAux3(7), cp673 = CP673(8)) shouldBe CP90(None) } } "computeBalancingCharge CP91" should { "calculate CP91 using cpq8 = true, negative balancing charge" in new MachineryAndPlantCalculator { computeBalancingCharge(cpq8 = CPQ8(Some(true)), cp78 = CP78(1), cp666 = CP666(2), cp674 = CP674(7), cp84 = CP84(30), cpAux1 = CPAux1(9), cpAux2 = CPAux2(10), cpAux3 = CPAux3(11), cp667 = CP667(12), cp673 = CP673(8), cp672 = CP672(0), cp82 = CP82(4), cato20 = CATO20(0)) shouldBe CP91(Some(10)) } "calculate CP91 using cpq8 = true, positive balancing charge" in new MachineryAndPlantCalculator { computeBalancingCharge( cpq8 = CPQ8(Some(true)), cp78 = CP78(1), cp666 = CP666(2), cp674 = CP674(7), cp84 = CP84(10), cpAux1 = CPAux1(9), cpAux2 = CPAux2(10), cpAux3 = CPAux3(11), cp667 = CP667(12), cp673 = CP673(8), cp672 = CP672(0), cp82 = CP82(4), cato20 = CATO20(0)) shouldBe CP91(Some(0)) } "calculate CP91 using cpq8 = false, cp672 > val1" in new MachineryAndPlantCalculator { computeBalancingCharge( cpq8 = CPQ8(Some(false)), cp78 = CP78(1), cp666 = CP666(2), cp674 = CP674(7), cp84 = CP84(30), cpAux1 = CPAux1(9), cpAux2 = CPAux2(10), cpAux3 = CPAux3(11), cp667 = CP667(12), cp673 = CP673(8), cp672 = CP672(29), cp82 = CP82(4), cato20 = CATO20(13)) shouldBe CP91(Some(1)) } "calculate CP91 using cpq8 = false, cp672 <= val1" in new MachineryAndPlantCalculator { computeBalancingCharge( cpq8 = CPQ8(Some(false)), cp78 = CP78(1), cp666 = CP666(2), cp674 = CP674(7), cp84 = CP84(30), cpAux1 = CPAux1(9), cpAux2 = CPAux2(10), cpAux3 = CPAux3(11), cp667 = CP667(12), cp673 = CP673(8), cp672 = CP672(28), cp82 = CP82(4), cato20 = CATO20(13)) shouldBe CP91(None) } } "computeTotalAllowances CP186" should { "return zero for all zero values when ceasedTrading is false" in new MachineryAndPlantCalculator { computeTotalAllowancesClaimed(cpq8 = CPQ8(value = Some(false)), cp87 = CP87(0), cp88 = CP88(0), cp89 = CP89(0), cp90 = CP90(None)) shouldBe CP186(Some(0)) } "return Some(10) for totalFirstYearAllowanceClaimed == 10 and 0 for all others when ceasedTrading is false" in new MachineryAndPlantCalculator { computeTotalAllowancesClaimed(cpq8 = CPQ8(value = Some(false)), cp87 = CP87(10), cp88 = CP88(0), cp89 = CP89(0), cp90 = CP90(None)) shouldBe CP186(Some(10)) } "return Some(125) from all but write down allowances entered when ceasedTrading is false" in new MachineryAndPlantCalculator { computeTotalAllowancesClaimed(cpq8 = CPQ8(value = Some(false)), cp87 = CP87(10), cp88 = CP88(115), cp89 = CP89(0), cp90 = CP90(None)) shouldBe CP186(Some(125)) } "return Some(125) from all values entered when ceasedTrading is false" in new MachineryAndPlantCalculator { computeTotalAllowancesClaimed(cpq8 = CPQ8(value = Some(false)), cp87 = CP87(10), cp88 = CP88(100), cp89 = CP89(15), cp90 = CP90(None)) shouldBe CP186(Some(125)) } "return None when ceasedTrading is false and balance allowance is not defined" in new MachineryAndPlantCalculator { computeTotalAllowancesClaimed(cpq8 = CPQ8(value = Some(true)), cp87 = CP87(10), cp88 = CP88(100), cp89 = CP89(15), cp90 = CP90(None)) shouldBe CP186(Some(0)) } "return balanceAllowance when trading ceased is true and balance allowance is defined" in new MachineryAndPlantCalculator {//DONE computeTotalAllowancesClaimed(cpq8 = CPQ8(Some(true)), cp87 = CP87(10), cp88 = CP88(100), cp89 = CP89(15), cp90 = CP90(Some(345))) shouldBe CP186(Some(345)) } "return None when ceasedTrading is not defined" in new MachineryAndPlantCalculator { computeTotalAllowancesClaimed(cpq8 = CPQ8(value = None), cp87 = CP87(10), cp88 = CP88(100), cp89 = CP89(15), cp90 = CP90(None)) shouldBe CP186(None) } } "CP92 - Written Down Value calculation" should { "calculate CP92 using cpq8 = false and CP91 is null, value is -ve" in new MachineryAndPlantCalculator { writtenDownValue( cpq8 = CPQ8(Some(false)), cp78 = CP78(Some(5)), cp82 = CP82(6), cp89 = CP89(7), cp91 = CP91(None), cp672 = CP672(9999), cato20 = CATO20(8), cpAux2 = CPAux2(7)) shouldBe CP92(Some(0)) } "calculate CP92 using cpq8 = false and CP91 is null, value is +ve" in new MachineryAndPlantCalculator { writtenDownValue( cpq8 = CPQ8(Some(false)), cp78 = CP78(Some(5)), cp82 = CP82(6), cp89 = CP89(7), cp91 = CP91(None), cp672 = CP672(0), cato20 = CATO20(8), cpAux2 = CPAux2(7)) shouldBe CP92(Some(19)) } "calculate CP92 using cpq8 = true and CP91 is null, value is +ve" in new MachineryAndPlantCalculator { writtenDownValue( cpq8 = CPQ8(Some(true)), cp78 = CP78(None), cp82 = CP82(None), cp89 = CP89(None), cp91 = CP91(None), cp672 = CP672(None), cato20 = CATO20(0), cpAux2 = CPAux2(0)) shouldBe CP92(Some(0)) } "calculate CP92 using cpq8 = false and CP91 is not null, value is +ve" in new MachineryAndPlantCalculator { writtenDownValue( cpq8 = CPQ8(Some(false)), cp78 = CP78(None), cp82 = CP82(None), cp89 = CP89(None), cp91 = CP91(Some(91)), cp672 = CP672(None), cato20 = CATO20(0), cpAux2 = CPAux2(0)) shouldBe CP92(Some(0)) } } "CATO20 - UnclaimedAIA_FYA calculation" should { "calculate the value correctly" in new MachineryAndPlantCalculator { unclaimedAIAFirstYearAllowance( cp81 = CP81(1), cp83 = CP83(Some(2)), cp87 = CP87(3), cp88 = CP88(Some(4)), cpAux1 = CPAux1(5) ) should be (CATO20(1)) } } }
ahudspith-equalexperts/ct-calculations
src/test/scala/uk/gov/hmrc/ct/computations/calculations/MachineryAndPlantCalculatorSpec.scala
Scala
apache-2.0
10,235
package com.twitter.finagle.exp.mysql import java.util.{Calendar, TimeZone} import java.sql.{Date, Timestamp, Time} import com.twitter.finagle.exp.mysql.transport.{Buffer, BufferReader, BufferWriter} /** * Defines a Value ADT that represents the domain of values * received from a mysql server. */ sealed trait Value case class ByteValue(b: Byte) extends Value case class ShortValue(s: Short) extends Value case class IntValue(i: Int) extends Value case class LongValue(l: Long) extends Value case class FloatValue(f: Float) extends Value case class DoubleValue(d: Double) extends Value case class StringValue(s: String) extends Value case object EmptyValue extends Value case object NullValue extends Value /** * A RawValue contains the raw bytes that represent * a value and enough meta data to decode the * bytes. * * @param typ The mysql type code for this value. * @param charset The charset encoding of the bytes. * @param isBinary Disambiguates between the text and binary protocol. * @param bytes The raw bytes for this value. */ case class RawValue( typ: Short, charset: Short, isBinary: Boolean, bytes: Array[Byte] ) extends Value object TimestampValue { /** * Creates a RawValue from a java.sql.Timestamp */ def apply(ts: Timestamp): Value = { val bytes = new Array[Byte](11) val bw = BufferWriter(bytes) val cal = Calendar.getInstance cal.setTimeInMillis(ts.getTime) bw.writeShort(cal.get(Calendar.YEAR)) bw.writeByte(cal.get(Calendar.MONTH) + 1) // increment 0 indexed month bw.writeByte(cal.get(Calendar.DATE)) bw.writeByte(cal.get(Calendar.HOUR_OF_DAY)) bw.writeByte(cal.get(Calendar.MINUTE)) bw.writeByte(cal.get(Calendar.SECOND)) bw.writeInt(ts.getNanos) RawValue(Type.Timestamp, Charset.Binary, true, bytes) } /** * Value extractor for java.sql.Timestamp * Returns timestamp in UTC, to match what is inserted into database */ def unapply(v: Value): Option[Timestamp] = v match { case RawValue(t, Charset.Binary, false, bytes) if (t == Type.Timestamp || t == Type.DateTime) => val str = new String(bytes, Charset(Charset.Binary)) if (str == Zero.toString) Some(Zero) else { val cal = Calendar.getInstance() val ts = Timestamp.valueOf(str) val offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) val utcTimeStamp = new Timestamp(ts.getTime + offset) Some(utcTimeStamp) } case RawValue(t, Charset.Binary, true, bytes) if (t == Type.Timestamp || t == Type.DateTime) => Some(fromBytes(bytes)) case _ => None } /** * Timestamp object that can appropriately * represent MySQL zero Timestamp. */ private[this] object Zero extends Timestamp(0) { override val getTime = 0L override val toString = "0000-00-00 00:00:00" } /** * Creates a Timestamp from a Mysql binary representation. * We standardize on representing timestamps in UTC. * Invalid DATETIME or TIMESTAMP values are converted to * the “zero” value ('0000-00-00 00:00:00'). * @param An array of bytes representing a TIMESTAMP written in the * MySQL binary protocol. */ private[this] def fromBytes(bytes: Array[Byte]): Timestamp = { if (bytes.isEmpty) { return Zero } var year, month, day, hour, min, sec, nano = 0 val br = BufferReader(bytes) // If the len was not zero, we can strictly // expect year, month, and day to be included. if (br.readable(4)) { year = br.readUnsignedShort() month = br.readUnsignedByte() day = br.readUnsignedByte() } else { return Zero } // if the time-part is 00:00:00, it isn't included. if (br.readable(3)) { hour = br.readUnsignedByte() min = br.readUnsignedByte() sec = br.readUnsignedByte() } // if the sub-seconds are 0, they aren't included. if (br.readable(4)) { nano = br.readInt() } val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")) cal.set(year, month-1, day, hour, min, sec) val ts = new Timestamp(0) ts.setTime(cal.getTimeInMillis) ts.setNanos(nano) ts } } object DateValue { /** * Creates a RawValue from a java.sql.Date */ def apply(date: Date): Value = { val bytes = new Array[Byte](4) val bw = BufferWriter(bytes) val cal = Calendar.getInstance cal.setTimeInMillis(date.getTime) bw.writeShort(cal.get(Calendar.YEAR)) bw.writeByte(cal.get(Calendar.MONTH) + 1) // increment 0 indexed month bw.writeByte(cal.get(Calendar.DATE)) RawValue(Type.Date, Charset.Binary, true, bytes) } /** * Value extractor for java.sql.Date */ def unapply(v: Value): Option[Date] = v match { case RawValue(Type.Date, Charset.Binary, false, bytes) => val str = new String(bytes, Charset(Charset.Binary)) if (str == Zero.toString) Some(Zero) else Some(Date.valueOf(str)) case RawValue(Type.Date, Charset.Binary, true, bytes) => Some(fromBytes(bytes)) case _ => None } /** * Date object that can appropriately * represent MySQL zero Date. */ private[this] object Zero extends Date(0) { override val getTime = 0L override val toString = "0000-00-00" } /** * Creates a DateValue from its MySQL binary representation. * Invalid DATE values are converted to * the “zero” value of the appropriate type * ('0000-00-00' or '0000-00-00 00:00:00'). * @param An array of bytes representing a DATE written in the * MySQL binary protocol. */ private[this] def fromBytes(bytes: Array[Byte]): Date = { if(bytes.isEmpty) { return Zero } var year, month, day = 0 val br = BufferReader(bytes) if (br.readable(4)) { year = br.readUnsignedShort() month = br.readUnsignedByte() day = br.readUnsignedByte() } else { return Zero } val cal = Calendar.getInstance cal.set(year, month-1, day) new Date(cal.getTimeInMillis) } } object BigDecimalValue { def apply(b: BigDecimal): Value = { val str = b.toString.getBytes(Charset(Charset.Binary)) RawValue(Type.NewDecimal, Charset.Binary, true, str) } def unapply(v: Value): Option[BigDecimal] = v match { case RawValue(Type.NewDecimal, Charset.Binary, _, bytes) => Some(BigDecimal(new String(bytes, Charset(Charset.Binary)))) case _ => None } }
JustinTulloss/finagle
finagle-mysql/src/main/scala/com/twitter/finagle/mysql/Value.scala
Scala
apache-2.0
6,455
/* * Copyright 2001-2009 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest.fixture import org.scalatest._ import events.TestFailed class FixtureFeatureSpecSpec extends org.scalatest.Spec with SharedHelpers { describe("A FixtureFeatureSpec") { it("should return the test names in order of registration from testNames") { val a = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("should do that") { fixture => } scenario("should do this") { fixture => } } expect(List("Scenario: should do that", "Scenario: should do this")) { a.testNames.iterator.toList } val b = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} } expect(List[String]()) { b.testNames.iterator.toList } val c = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("should do this") { fixture => } scenario("should do that") { fixture => } } expect(List("Scenario: should do this", "Scenario: should do that")) { c.testNames.iterator.toList } } it("should throw NotAllowedException if a duplicate scenario name registration is attempted") { intercept[DuplicateTestNameException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("test this") { fixture => } scenario("test this") { fixture => } } } intercept[DuplicateTestNameException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("test this") { fixture => } ignore("test this") { fixture => } } } intercept[DuplicateTestNameException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} ignore("test this") { fixture => } ignore("test this") { fixture => } } } intercept[DuplicateTestNameException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} ignore("test this") { fixture => } scenario("test this") { fixture => } } } } it("should pass in the fixture to every test method") { val a = new FixtureFeatureSpec { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest) { test(hello) } scenario("should do this") { fixture => assert(fixture === hello) } scenario("should do that") { fixture => assert(fixture === hello) } } val rep = new EventRecordingReporter a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker()) assert(!rep.eventsReceived.exists(_.isInstanceOf[TestFailed])) } it("should throw NullPointerException if a null test tag is provided") { // scenario intercept[NullPointerException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("hi", null) { fixture => } } } val caught = intercept[NullPointerException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("hi", mytags.SlowAsMolasses, null) { fixture => } } } assert(caught.getMessage === "a test tag was null") intercept[NullPointerException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("hi", mytags.SlowAsMolasses, null, mytags.WeakAsAKitten) { fixture => } } } // ignore intercept[NullPointerException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} ignore("hi", null) { fixture => } } } val caught2 = intercept[NullPointerException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} ignore("hi", mytags.SlowAsMolasses, null) { fixture => } } } assert(caught2.getMessage === "a test tag was null") intercept[NullPointerException] { new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} ignore("hi", mytags.SlowAsMolasses, null, mytags.WeakAsAKitten) { fixture => } } } } it("should return a correct tags map from the tags method") { val a = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} ignore("test this") { fixture => } scenario("test that") { fixture => } } expect(Map("Scenario: test this" -> Set("org.scalatest.Ignore"))) { a.tags } val b = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("test this") { fixture => } ignore("test that") { fixture => } } expect(Map("Scenario: test that" -> Set("org.scalatest.Ignore"))) { b.tags } val c = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} ignore("test this") { fixture => } ignore("test that") { fixture => } } expect(Map("Scenario: test this" -> Set("org.scalatest.Ignore"), "Scenario: test that" -> Set("org.scalatest.Ignore"))) { c.tags } val d = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("test this", mytags.SlowAsMolasses) { fixture => } ignore("test that", mytags.SlowAsMolasses) { fixture => } } expect(Map("Scenario: test this" -> Set("org.scalatest.SlowAsMolasses"), "Scenario: test that" -> Set("org.scalatest.Ignore", "org.scalatest.SlowAsMolasses"))) { d.tags } val e = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} } expect(Map()) { e.tags } val f = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) {} scenario("test this", mytags.SlowAsMolasses, mytags.WeakAsAKitten) { fixture => } scenario("test that", mytags.SlowAsMolasses) { fixture => } } expect(Map("Scenario: test this" -> Set("org.scalatest.SlowAsMolasses", "org.scalatest.WeakAsAKitten"), "Scenario: test that" -> Set("org.scalatest.SlowAsMolasses"))) { f.tags } } class TestWasCalledSuite extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false scenario("this") { fixture => theTestThisCalled = true } scenario("that") { fixture => theTestThatCalled = true } } it("should execute all tests when run is called with testName None") { val b = new TestWasCalledSuite b.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker) assert(b.theTestThisCalled) assert(b.theTestThatCalled) } it("should execute one test when run is called with a defined testName") { val a = new TestWasCalledSuite a.run(Some("Scenario: this"), SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker) assert(a.theTestThisCalled) assert(!a.theTestThatCalled) } it("should report as ignored, and not run, tests marked ignored") { val a = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false scenario("test this") { fixture => theTestThisCalled = true } scenario("test that") { fixture => theTestThatCalled = true } } val repA = new TestIgnoredTrackingReporter a.run(None, repA, new Stopper {}, Filter(), Map(), None, new Tracker) assert(!repA.testIgnoredReceived) assert(a.theTestThisCalled) assert(a.theTestThatCalled) val b = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false ignore("test this") { fixture => theTestThisCalled = true } scenario("test that") { fixture => theTestThatCalled = true } } val repB = new TestIgnoredTrackingReporter b.run(None, repB, new Stopper {}, Filter(), Map(), None, new Tracker) assert(repB.testIgnoredReceived) assert(repB.lastEvent.isDefined) assert(repB.lastEvent.get.testName endsWith "test this") assert(!b.theTestThisCalled) assert(b.theTestThatCalled) val c = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false scenario("test this") { fixture => theTestThisCalled = true } ignore("test that") { fixture => theTestThatCalled = true } } val repC = new TestIgnoredTrackingReporter c.run(None, repC, new Stopper {}, Filter(), Map(), None, new Tracker) assert(repC.testIgnoredReceived) assert(repC.lastEvent.isDefined) assert(repC.lastEvent.get.testName endsWith "test that", repC.lastEvent.get.testName) assert(c.theTestThisCalled) assert(!c.theTestThatCalled) // The order I want is order of appearance in the file. // Will try and implement that tomorrow. Subtypes will be able to change the order. val d = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false ignore("test this") { fixture => theTestThisCalled = true } ignore("test that") { fixture => theTestThatCalled = true } } val repD = new TestIgnoredTrackingReporter d.run(None, repD, new Stopper {}, Filter(), Map(), None, new Tracker) assert(repD.testIgnoredReceived) assert(repD.lastEvent.isDefined) assert(repD.lastEvent.get.testName endsWith "test that") // last because should be in order of appearance assert(!d.theTestThisCalled) assert(!d.theTestThatCalled) } it("should run a test marked as ignored if run is invoked with that testName") { // If I provide a specific testName to run, then it should ignore an Ignore on that test // method and actually invoke it. val e = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false ignore("test this") { fixture => theTestThisCalled = true } scenario("test that") { fixture => theTestThatCalled = true } } val repE = new TestIgnoredTrackingReporter e.run(Some("Scenario: test this"), repE, new Stopper {}, Filter(), Map(), None, new Tracker) assert(!repE.testIgnoredReceived) assert(e.theTestThisCalled) assert(!e.theTestThatCalled) } it("should run only those tests selected by the tags to include and exclude sets") { // Nothing is excluded val a = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false scenario("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true } scenario("test that") { fixture => theTestThatCalled = true } } val repA = new TestIgnoredTrackingReporter a.run(None, repA, new Stopper {}, Filter(), Map(), None, new Tracker) assert(!repA.testIgnoredReceived) assert(a.theTestThisCalled) assert(a.theTestThatCalled) // SlowAsMolasses is included, one test should be excluded val b = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false scenario("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true } scenario("test that") { fixture => theTestThatCalled = true } } val repB = new TestIgnoredTrackingReporter b.run(None, repB, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), Map(), None, new Tracker) assert(!repB.testIgnoredReceived) assert(b.theTestThisCalled) assert(!b.theTestThatCalled) // SlowAsMolasses is included, and both tests should be included val c = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false scenario("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true } scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } } val repC = new TestIgnoredTrackingReporter c.run(None, repB, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), Map(), None, new Tracker) assert(!repC.testIgnoredReceived) assert(c.theTestThisCalled) assert(c.theTestThatCalled) // SlowAsMolasses is included. both tests should be included but one ignored val d = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false ignore("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true } scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } } val repD = new TestIgnoredTrackingReporter d.run(None, repD, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.Ignore")), Map(), None, new Tracker) assert(repD.testIgnoredReceived) assert(!d.theTestThisCalled) assert(d.theTestThatCalled) // SlowAsMolasses included, FastAsLight excluded val e = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false scenario("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } scenario("test the other") { fixture => theTestTheOtherCalled = true } } val repE = new TestIgnoredTrackingReporter e.run(None, repE, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), Map(), None, new Tracker) assert(!repE.testIgnoredReceived) assert(!e.theTestThisCalled) assert(e.theTestThatCalled) assert(!e.theTestTheOtherCalled) // An Ignored test that was both included and excluded should not generate a TestIgnored event val f = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false ignore("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } scenario("test the other") { fixture => theTestTheOtherCalled = true } } val repF = new TestIgnoredTrackingReporter f.run(None, repF, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), Map(), None, new Tracker) assert(!repF.testIgnoredReceived) assert(!f.theTestThisCalled) assert(f.theTestThatCalled) assert(!f.theTestTheOtherCalled) // An Ignored test that was not included should not generate a TestIgnored event val g = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false scenario("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } ignore("test the other") { fixture => theTestTheOtherCalled = true } } val repG = new TestIgnoredTrackingReporter g.run(None, repG, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")), Map(), None, new Tracker) assert(!repG.testIgnoredReceived) assert(!g.theTestThisCalled) assert(g.theTestThatCalled) assert(!g.theTestTheOtherCalled) // No tagsToInclude set, FastAsLight excluded val h = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false scenario("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } scenario("test the other") { fixture => theTestTheOtherCalled = true } } val repH = new TestIgnoredTrackingReporter h.run(None, repH, new Stopper {}, Filter(None, Set("org.scalatest.FastAsLight")), Map(), None, new Tracker) assert(!repH.testIgnoredReceived) assert(!h.theTestThisCalled) assert(h.theTestThatCalled) assert(h.theTestTheOtherCalled) // No tagsToInclude set, SlowAsMolasses excluded val i = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false scenario("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } scenario("test the other") { fixture => theTestTheOtherCalled = true } } val repI = new TestIgnoredTrackingReporter i.run(None, repI, new Stopper {}, Filter(None, Set("org.scalatest.SlowAsMolasses")), Map(), None, new Tracker) assert(!repI.testIgnoredReceived) assert(!i.theTestThisCalled) assert(!i.theTestThatCalled) assert(i.theTestTheOtherCalled) // No tagsToInclude set, SlowAsMolasses excluded, TestIgnored should not be received on excluded ones val j = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false ignore("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } ignore("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } scenario("test the other") { fixture => theTestTheOtherCalled = true } } val repJ = new TestIgnoredTrackingReporter j.run(None, repJ, new Stopper {}, Filter(None, Set("org.scalatest.SlowAsMolasses")), Map(), None, new Tracker) assert(!repI.testIgnoredReceived) assert(!j.theTestThisCalled) assert(!j.theTestThatCalled) assert(j.theTestTheOtherCalled) // Same as previous, except Ignore specifically mentioned in excludes set val k = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false var theTestTheOtherCalled = false ignore("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true } ignore("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true } ignore("test the other") { fixture => theTestTheOtherCalled = true } } val repK = new TestIgnoredTrackingReporter k.run(None, repK, new Stopper {}, Filter(None, Set("org.scalatest.SlowAsMolasses", "org.scalatest.Ignore")), Map(), None, new Tracker) assert(repK.testIgnoredReceived) assert(!k.theTestThisCalled) assert(!k.theTestThatCalled) assert(!k.theTestTheOtherCalled) } it("should return the correct test count from its expectedTestCount method") { val a = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("test this") { fixture => } scenario("test that") { fixture => } } assert(a.expectedTestCount(Filter()) === 2) val b = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } ignore("test this") { fixture => } scenario("test that") { fixture => } } assert(b.expectedTestCount(Filter()) === 1) val c = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("test this", mytags.FastAsLight) { fixture => } scenario("test that") { fixture => } } assert(c.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1) assert(c.expectedTestCount(Filter(None, Set("org.scalatest.FastAsLight"))) === 1) val d = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("test this", mytags.FastAsLight, mytags.SlowAsMolasses) { fixture => } scenario("test that", mytags.SlowAsMolasses) { fixture => } scenario("test the other thing") { fixture => } } assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1) assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) === 1) assert(d.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) === 1) assert(d.expectedTestCount(Filter()) === 3) val e = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("test this", mytags.FastAsLight, mytags.SlowAsMolasses) { fixture => } scenario("test that", mytags.SlowAsMolasses) { fixture => } ignore("test the other thing") { fixture => } } assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1) assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) === 1) assert(e.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) === 0) assert(e.expectedTestCount(Filter()) === 2) val f = new Suites(a, b, c, d, e) assert(f.expectedTestCount(Filter()) === 10) } it("should generate a TestPending message when the test body is (pending)") { val a = new FixtureFeatureSpec { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest) { test(hello) } scenario("should do this") (pending) scenario("should do that") { fixture => assert(fixture === hello) } scenario("should do something else") { fixture => assert(fixture === hello) pending } } val rep = new EventRecordingReporter a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker()) val tp = rep.testPendingEventsReceived assert(tp.size === 2) } it("should generate a test failure if a Throwable, or an Error other than direct Error subtypes " + "known in JDK 1.5, excluding AssertionError") { val a = new FixtureFeatureSpec { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest) { test(hello) } scenario("throws AssertionError") { s => throw new AssertionError } scenario("throws plain old Error") { s => throw new Error } scenario("throws Throwable") { s => throw new Throwable } } val rep = new EventRecordingReporter a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker()) val tf = rep.testFailedEventsReceived assert(tf.size === 3) } it("should propagate out Errors that are direct subtypes of Error in JDK 1.5, other than " + "AssertionError, causing Suites and Runs to abort.") { val a = new FixtureFeatureSpec { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest) { test(hello) } scenario("throws AssertionError") { s => throw new OutOfMemoryError } } intercept[OutOfMemoryError] { a.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker()) } } it("should send InfoProvided events with aboutAPendingTest set to true for info " + "calls made from a test that is pending") { val a = new FixtureFeatureSpec with GivenWhenThen { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest) { test(hello) } scenario("should do something else") { s => given("two integers") when("one is subracted from the other") then("the result is the difference between the two numbers") pending } } val rep = new EventRecordingReporter a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker()) val ip = rep.infoProvidedEventsReceived assert(ip.size === 3) for (event <- ip) { assert(event.aboutAPendingTest.isDefined && event.aboutAPendingTest.get) } } it("should send InfoProvided events with aboutAPendingTest set to false for info " + "calls made from a test that is not pending") { val a = new FixtureFeatureSpec with GivenWhenThen { type FixtureParam = String val hello = "Hello, world!" def withFixture(test: OneArgTest) { test(hello) } scenario("should do something else") { s => given("two integers") when("one is subracted from the other") then("the result is the difference between the two numbers") assert(1 + 1 === 2) } } val rep = new EventRecordingReporter a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker()) val ip = rep.infoProvidedEventsReceived assert(ip.size === 3) for (event <- ip) { assert(event.aboutAPendingTest.isDefined && !event.aboutAPendingTest.get) } } it("should allow both tests that take fixtures and tests that don't") { val a = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("Hello, world!") } var takesNoArgsInvoked = false scenario("take no args") { () => takesNoArgsInvoked = true } var takesAFixtureInvoked = false scenario("takes a fixture") { s => takesAFixtureInvoked = true } } a.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker()) assert(a.testNames.size === 2, a.testNames) assert(a.takesNoArgsInvoked) assert(a.takesAFixtureInvoked) } it("should work with test functions whose inferred result type is not Unit") { val a = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("Hello, world!") } var takesNoArgsInvoked = false scenario("should take no args") { () => takesNoArgsInvoked = true; true } var takesAFixtureInvoked = false scenario("should take a fixture") { s => takesAFixtureInvoked = true; true } } assert(!a.takesNoArgsInvoked) assert(!a.takesAFixtureInvoked) a.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker()) assert(a.testNames.size === 2, a.testNames) assert(a.takesNoArgsInvoked) assert(a.takesAFixtureInvoked) } it("should work with ignored tests whose inferred result type is not Unit") { val a = new FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } var theTestThisCalled = false var theTestThatCalled = false ignore("should test this") { () => theTestThisCalled = true; "hi" } ignore("should test that") { fixture => theTestThatCalled = true; 42 } } assert(!a.theTestThisCalled) assert(!a.theTestThatCalled) val reporter = new EventRecordingReporter a.run(None, reporter, new Stopper {}, Filter(), Map(), None, new Tracker) assert(reporter.testIgnoredEventsReceived.size === 2) assert(!a.theTestThisCalled) assert(!a.theTestThatCalled) } it("should pass a NoArgTest to withFixture for tests that take no fixture") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String var aNoArgTestWasPassed = false var aOneArgTestWasPassed = false override def withFixture(test: NoArgTest) { aNoArgTestWasPassed = true } def withFixture(test: OneArgTest) { aOneArgTestWasPassed = true } scenario("something") { () => assert(1 + 1 === 2) } } val s = new MySpec s.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker()) assert(s.aNoArgTestWasPassed) assert(!s.aOneArgTestWasPassed) } it("should not pass a NoArgTest to withFixture for tests that take a Fixture") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String var aNoArgTestWasPassed = false var aOneArgTestWasPassed = false override def withFixture(test: NoArgTest) { aNoArgTestWasPassed = true } def withFixture(test: OneArgTest) { aOneArgTestWasPassed = true } scenario("something") { fixture => assert(1 + 1 === 2) } } val s = new MySpec s.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker()) assert(!s.aNoArgTestWasPassed) assert(s.aOneArgTestWasPassed) } it("should pass a NoArgTest that invokes the no-arg test when the " + "NoArgTest's no-arg apply method is invoked") { class MySuite extends FixtureFeatureSpec { type FixtureParam = String var theNoArgTestWasInvoked = false def withFixture(test: OneArgTest) { // Shouldn't be called, but just in case don't invoke a OneArgTest } scenario("something") { () => theNoArgTestWasInvoked = true } } val s = new MySuite s.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker()) assert(s.theNoArgTestWasInvoked) } describe("(when a nesting rule has been violated)") { it("should, if they call a feature from within an scenario clause, result in a TestFailedException when running the test") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("should blow up") { fixture => feature("in the wrong place, at the wrong time") { } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "Scenario: should blow up") } it("should, if they call a feature with a nested it from within an it clause, result in a TestFailedException when running the test") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("should blow up") { fixture => feature("in the wrong place, at the wrong time") { scenario("should never run") { fixture => assert(1 === 1) } } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "Scenario: should blow up") } it("should, if they call a nested it from within an it clause, result in a TestFailedException when running the test") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("should blow up") { fixture => scenario("should never run") { fixture => assert(1 === 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "Scenario: should blow up") } it("should, if they call a nested it with tags from within an it clause, result in a TestFailedException when running the test") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("should blow up") { fixture => scenario("should never run", mytags.SlowAsMolasses) { fixture => assert(1 === 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "Scenario: should blow up") } it("should, if they call a feature with a nested ignore from within an it clause, result in a TestFailedException when running the test") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("should blow up") { fixture => feature("in the wrong place, at the wrong time") { ignore("should never run") { fixture => assert(1 === 1) } } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "Scenario: should blow up") } it("should, if they call a nested ignore from within an it clause, result in a TestFailedException when running the test") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("should blow up") { fixture => ignore("should never run") { fixture => assert(1 === 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "Scenario: should blow up") } it("should, if they call a nested ignore with tags from within an it clause, result in a TestFailedException when running the test") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } scenario("should blow up") { fixture => ignore("should never run", mytags.SlowAsMolasses) { fixture => assert(1 === 1) } } } val spec = new MySpec ensureTestFailedEventReceived(spec, "Scenario: should blow up") } it("should, if they call a nested feature from within a feature clause, result in a SuiteAborted event when constructing the FeatureSpec") { class MySpec extends FixtureFeatureSpec { type FixtureParam = String def withFixture(test: OneArgTest) { test("hi") } feature("should blow up") { feature("should never run") { } } } val caught = intercept[NotAllowedException] { new MySpec } assert(caught.getMessage === "Feature clauses cannot be nested.") } } } it("should pass the correct test name in the OneArgTest passed to withFixture") { val a = new FixtureFeatureSpec { type FixtureParam = String var correctTestNameWasPassed = false def withFixture(test: OneArgTest) { correctTestNameWasPassed = test.name == "Scenario: should do something" test("hi") } scenario("should do something") { fixture => } } a.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker()) assert(a.correctTestNameWasPassed) } it("should pass the correct config map in the OneArgTest passed to withFixture") { val a = new FixtureFeatureSpec { type FixtureParam = String var correctConfigMapWasPassed = false def withFixture(test: OneArgTest) { correctConfigMapWasPassed = (test.configMap == Map("hi" -> 7)) test("hi") } scenario("should do something") { fixture => } } a.run(None, SilentReporter, new Stopper {}, Filter(), Map("hi" -> 7), None, new Tracker()) assert(a.correctConfigMapWasPassed) } }
JimCallahan/Graphics
external/scalatest/src/test/scala/org/scalatest/fixture/FixtureFeatureSpecSpec.scala
Scala
apache-2.0
38,836
package eu.unicredit.swagger.dependencies object Language extends Enumeration { val Scala, Java = Value }
unicredit/sbt-swagger-codegen
lib/src/main/scala/eu/unicredit/swagger/dependencies/Language.scala
Scala
apache-2.0
109
package com.fsist.stream.run import collection.mutable import java.util.concurrent.atomic.AtomicLong import com.fsist.stream._ import scala.annotation.tailrec import scala.language.implicitConversions // This file contains a small implementation of a mutable graph. Existing libraries like scala-graph are not performant // enough (at least by default) because they are too general. We need a very fast implementation of mutable, small digraphs // to make stream building fast. /** Wraps each stream component for placement in the graph, and makes sure to compare nodes by identity. * Otherwise StreamComponent case classes that compare equal would be confused. */ case class ComponentId(value: StreamComponent) { override def equals(other: Any): Boolean = (other != null) && other.isInstanceOf[ComponentId] && (value eq other.asInstanceOf[ComponentId].value) override def hashCode(): Int = System.identityHashCode(value) override lazy val toString: String = System.identityHashCode(value).toString } object ComponentId { implicit def make(value: StreamComponent): ComponentId = ComponentId(value) } /** Wraps each Connector when used as a key in a Set or Map. * * Can't use `Node` here because Connector isn't a StreamComponent. */ case class ConnectorId[T](value: Connector[T]) { override def equals(other: Any): Boolean = (other != null) && other.isInstanceOf[ConnectorId[_]] && (value eq other.asInstanceOf[ConnectorId[_]].value) override def hashCode(): Int = System.identityHashCode(value) override lazy val toString: String = System.identityHashCode(value).toString } object ConnectorId { implicit def make[T](value: Connector[T]): ConnectorId[T] = ConnectorId(value) } /** Mutable graph containing the components and connectors in a stream and the connections between them. * This serves as the main part of a FutureStreamBuilder's internal state. */ private[run] class StreamGraph { /** Component nodes mapped to the sink components to which they are connected */ val components = new mutable.HashMap[ComponentId, Option[ComponentId]]() /** Registers a new component */ def register(component: ComponentId): Unit = { components.getOrElseUpdate(component, None) } /** Connect two components together (forms an edge) */ def connect(component: ComponentId, target: ComponentId): Unit = { components.put(component, Some(target)) register(target) } /** Update this graph to also contain all the data from that other graph. */ def mergeFrom(graph: StreamGraph): Unit = { for ((component, sink) <- graph.components) { components.get(component) match { case None => components.put(component, sink) case Some(None) if sink.isDefined => components.update(component, sink) case _ => } } } def connectors(): Set[ConnectorId[_]] = (for (component <- components.keys if component.value.isInstanceOf[ConnectorEdge[_]]) yield ConnectorId(component.value.asInstanceOf[ConnectorEdge[_]].connector)).toSet def isAcyclic(): Boolean = { type Node = Either[ComponentId, ConnectorId[_]] def nextNodes(node: Node): Seq[Node] = node match { case Left(ComponentId(ConnectorInput(connector, _))) => List(Right(connector)) case Left(comp @ ComponentId(other)) if ! other.isInstanceOf[StreamOutput[_, _]] => List(Left(components(comp).get)) case Left(_) => List.empty // StreamOutput node case Right(ConnectorId(connector)) => connector.outputs map (output => Left[ComponentId, ConnectorId[_]](output)) } // See eg https://en.wikipedia.org/wiki/Topological_sorting#Algorithms val visited = new mutable.HashSet[Node]() val marked = new mutable.HashSet[Node]() def visit(node: Node): Boolean = { if (marked.contains(node)) false else { marked.add(node) for (next <- nextNodes(node)) visit(next) visited.add(node) marked.remove(node) true } } components.keys.map(Left.apply).forall { node => visited.contains(node) || visit(node) } } override def toString(): String = { val sb = new mutable.StringBuilder(100) val ids = components.keys.zipWithIndex.toMap sb ++= s"Nodes: ${components.keys.map(ids).mkString(", ")}\\n" sb ++= s"Edges: ${ ((for ((source, Some(sink)) <- components) yield { s"${ids(source)} ~> ${ids(sink)}" }) ++ (for (node <- components.keys if node.value.isInstanceOf[ConnectorInput[_]]; input = node.value.asInstanceOf[ConnectorInput[_]]; output <- input.connector.outputs) yield { val inputComponent = components.keySet.find(_.value eq input).get val outputComponent = components.keySet.find(_.value eq output).get s"${ids(inputComponent)} ~> ${ids(outputComponent)}" })).mkString(", ") }\\n" sb ++= s"Where:\\n" for (node <- components.keys) { sb ++= s"${ids(node)}\\t= ${node.value}\\n" } sb.result() } }
fsist/future-streams
src/main/scala/com/fsist/stream/run/Graph.scala
Scala
apache-2.0
5,029
package com.twitter.finagle.http import com.twitter.util.Duration import java.io.{InputStream, InputStreamReader, OutputStream, OutputStreamWriter, Reader, Writer} import java.util.{Iterator => JIterator} import java.nio.charset.Charset import java.util.{Date, TimeZone} import org.apache.commons.lang.time.FastDateFormat import org.jboss.netty.buffer._ import org.jboss.netty.handler.codec.http.{Cookie, HttpMessage, HttpHeaders, HttpMethod, HttpVersion} import scala.collection.JavaConversions._ import scala.reflect.BeanProperty /** * Rich HttpMessage * * Base class for Request and Response. There are both input and output * methods, though only one set of methods should be used. */ abstract class Message extends HttpMessage { def isRequest: Boolean def isResponse = !isRequest def content: ChannelBuffer = getContent() def content_=(content: ChannelBuffer) { setContent(content) } def version: HttpVersion = getProtocolVersion() def version_=(version: HttpVersion) { setProtocolVersion(version) } lazy val headers = new HeaderMap(this) // Java users: use Netty HttpMessage interface for headers /** Cookies. In a request, this uses the Cookie headers. In a response, it * uses the Set-Cookie headers. */ lazy val cookies = new CookieSet(this) // Java users: use the interface below for cookies /** Get iterator over Cookies */ def getCookies(): JIterator[Cookie] = cookies.iterator /** Add a cookie */ def addCookie(cookie: Cookie) { cookies += cookie } /** Remove a cookie */ def removeCookie(cookie: Cookie) { cookies -= cookie } /** Accept header */ def accept: Seq[String] = Option(getHeader(HttpHeaders.Names.ACCEPT)) match { case Some(s) => s.split(",").map(_.trim).filter(_.nonEmpty) case None => Seq() } /** Set Accept header */ def accept_=(value: String) { setHeader(HttpHeaders.Names.ACCEPT, value) } /** Set Accept header with list of values */ def accept_=(values: Iterable[String]) { accept = values.mkString(", ") } /** Accept header media types (normalized, no parameters) */ def acceptMediaTypes: Seq[String] = accept.map { _.split(";", 2).headOption .map(_.trim.toLowerCase) // media types are case-insensitive .filter(_.nonEmpty) // skip blanks }.flatten /** Allow header */ def allow: Option[String] = Option(getHeader(HttpHeaders.Names.ALLOW)) /** Set Authorization header */ def allow_=(value: String) { setHeader(HttpHeaders.Names.ALLOW, value) } /** Set Authorization header */ def allow_=(values: Iterable[HttpMethod]) { allow = values.mkString(",") } /** Get Authorization header */ def authorization: Option[String] = Option(getHeader(HttpHeaders.Names.AUTHORIZATION)) /** Set Authorization header */ def authorization_=(value: String) { setHeader(HttpHeaders.Names.AUTHORIZATION, value) } /** Get Cache-Control header */ def cacheControl: Option[String] = Option(getHeader(HttpHeaders.Names.CACHE_CONTROL)) /** Set Cache-Control header */ def cacheControl_=(value: String) { setHeader(HttpHeaders.Names.CACHE_CONTROL, value) } /** Set Cache-Control header with a max-age (and must-revalidate). */ def cacheControl_=(maxAge: Duration) { cacheControl = "max-age=" + maxAge.inSeconds.toString + ", must-revalidate" } /** Get Content-Length header. Use length to get the length of actual content. */ def contentLength: Option[Long] = Option(getHeader(HttpHeaders.Names.CONTENT_LENGTH)).map { _.toLong } /** Set Content-Length header. Normally, this is automatically set by the * Codec, but this method allows you to override that. */ def contentLength_=(value: Long) { setHeader(HttpHeaders.Names.CONTENT_LENGTH, value.toString) } /** Get Content-Type header */ def contentType: Option[String] = Option(getHeader(HttpHeaders.Names.CONTENT_TYPE)) /** Set Content-Type header */ def contentType_=(value: String) { setHeader(HttpHeaders.Names.CONTENT_TYPE, value) } /** Set Content-Type header by media-type and charset */ def setContentType(mediaType: String, charset: String) { setHeader(HttpHeaders.Names.CONTENT_TYPE, mediaType + ";charset=" + charset) } /** Set Content-Type header to application/json;charset=utf-8 */ def setContentTypeJson() { setHeader(HttpHeaders.Names.CONTENT_TYPE, Message.ContentTypeJson) } /** Get Expires header */ def expires: Option[String] = Option(getHeader(HttpHeaders.Names.EXPIRES)) /** Set Expires header */ def expires_=(value: String) { setHeader(HttpHeaders.Names.EXPIRES, value) } /** Set Expires header by Date */ def expires_=(value: Date) { expires = Message.httpDateFormat(value) } /** Get Location header */ def location: Option[String] = Option(getHeader(HttpHeaders.Names.LOCATION)) /** Set Location header */ def location_=(value: String) { setHeader(HttpHeaders.Names.LOCATION, value) } /** Get media-type from Content-Type header */ def mediaType: Option[String] = contentType.flatMap { contentType => val beforeSemi = contentType.indexOf(";") match { case -1 => contentType case n => contentType.substring(0, n) } val mediaType = beforeSemi.trim if (mediaType.nonEmpty) Some(mediaType.toLowerCase) else None } /** Set media-type in Content-Type heaer */ def mediaType_=(value: String) { setContentType(value, "utf-8") } /** Get Referer [sic] header */ def referer: Option[String] = Option(getHeader(HttpHeaders.Names.REFERER)) /** Set Referer [sic] header */ def referer_=(value: String) { setHeader(HttpHeaders.Names.REFERER, value) } /** Get Retry-After header */ def retryAfter: Option[String] = Option(getHeader(HttpHeaders.Names.RETRY_AFTER)) /** Set Retry-After header */ def retryAfter_=(value: String) { setHeader(HttpHeaders.Names.RETRY_AFTER, value) } /** Set Retry-After header by seconds */ def retryAfter_=(value: Long) { retryAfter = value.toString } /** Get User-Agent header */ def userAgent: Option[String] = Option(getHeader(HttpHeaders.Names.USER_AGENT)) /** Set User-Agent header */ def userAgent_=(value: String) { setHeader(HttpHeaders.Names.USER_AGENT, value) } /** Get X-Forwarded-For header */ def xForwardedFor: Option[String] = Option(getHeader("X-Forwarded-For")) /** Set X-Forwarded-For header */ def xForwardedFor_=(value: String) { setHeader("X-Forwarded-For", value) } /** Get length of content. */ def length: Int = getContent.readableBytes def getLength(): Int = length /** Get the content as a string. */ def contentString: String = getContent.toString(Charset.forName("UTF-8")) def getContentString(): String = contentString /** Set the content as a string. */ def contentString_=(value: String) { if (value != "") setContent(ChannelBuffers.wrappedBuffer(value.getBytes("UTF-8"))) else setContent(ChannelBuffers.EMPTY_BUFFER) } def setContentString(value: String) { contentString = value } /** * Use content as InputStream. The underlying channel buffer's reader * index is advanced. (Scala interface. Java users can use getInputStream().) */ def withInputStream(f: (InputStream => Unit)) { val inputStream = getInputStream() f(inputStream) // throws inputStream.close() } /** * Get InputStream for content. Caller must close. (Java interface. Scala * users should use withInputStream.) */ def getInputStream(): InputStream = new ChannelBufferInputStream(getContent) /** Use content as Reader. (Scala interface. Java usrs can use getReader().) */ def withReader(f: Reader => Unit) { withInputStream { inputStream => val reader = new InputStreamReader(inputStream) f(reader) } } /** Get Reader for content. (Java interface. Scala users should use withReader.) */ def getReader(): Reader = new InputStreamReader(getInputStream()) /** Append string to content. */ def write(string: String) { write(string.getBytes("UTF-8")) } /** Append bytes to content. */ def write(bytes: Array[Byte]) { getContent match { case buffer: DynamicChannelBuffer => buffer.writeBytes(bytes) case _ => val buffer = ChannelBuffers.wrappedBuffer(bytes) write(buffer) } } /** Append ChannelBuffer to content. */ def write(buffer: ChannelBuffer) { getContent match { case ChannelBuffers.EMPTY_BUFFER => setContent(buffer) case content => setContent(ChannelBuffers.wrappedBuffer(content, buffer)) } } /** * Use content as OutputStream. Content is replaced with stream contents. * (Java users can use this with a Function, or use Netty's ChannelBufferOutputStream * and then call setContent() with the underlying buffer.) */ def withOutputStream(f: (OutputStream => Unit)) { // Use buffer size of 1024. Netty default is 256, which seems too small. // Netty doubles buffers on resize. val outputStream = new ChannelBufferOutputStream(ChannelBuffers.dynamicBuffer(1024)) f(outputStream) // throws outputStream.close() write(outputStream.buffer) } /** Use as a Writer. Content is replaced with writer contents. */ def withWriter(f: (Writer => Unit)) { withOutputStream { outputStream => val writer = new OutputStreamWriter(outputStream) f(writer) writer.close() // withOutputStream will write() } } /** Clear content (set to ""). */ def clearContent() { setContent(ChannelBuffers.EMPTY_BUFFER) } } object Message { @deprecated("Use MediaType.Json") val MediaTypeJson = "application/json" @deprecated("Use MediaType.Javascript") val MediaTypeJavascript = "application/javascript" @deprecated("Use MediaType.WwwForm") val MediaTypeWwwForm = "application/x-www-form-urlencoded" val CharsetUtf8 = "charset=utf-8" val ContentTypeJson = MediaType.Json + ";" + CharsetUtf8 val ContentTypeJavascript = MediaType.Javascript + ";" + CharsetUtf8 val ContentTypeWwwFrom = MediaType.WwwForm + ";" + CharsetUtf8 private val HttpDateFormat = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss", TimeZone.getTimeZone("GMT")) def httpDateFormat(date: Date): String = HttpDateFormat.format(date) + " GMT" }
enachb/finagle_2.9_durgh
finagle-http/src/main/scala/com/twitter/finagle/http/Message.scala
Scala
apache-2.0
10,431
package amphip.stoch //import scalax.file.Path import scalaz._, Scalaz._ import spire.implicits._ import amphip.dsl._ import amphip.base._ //import amphip.sem.mathprog object BigModelSpec extends App /* extends FunSuite */ { val BS = BasicScenario import System.{currentTimeMillis => millis} import StochData._ implicit def LinkedMapShow[K: Show, V: Show]: Show[LinkedMap[K, V]] = Show.shows { map => map.map(_.shows).toString } implicit val StageShow: Show[Stage] = Show.shows(_.name) implicit val BSShow: Show[BasicScenario] = Show.shows(_.name) def lazyStochData(sd: StochData) = new { import amphip.data.ModelData._ import sd._ lazy private[this] val scenariosArr: Array[Array[Scenario]] = { val res = Array.ofDim[Scenario](finalScenarios.size, stages.size) for { (scen, s) <- finalScenarios.zipWithIndex } { cfor(0)(_ < stages.length, _ + 1) { t => res(s)(t) = scen.take(t + 1) } } res } lazy val linkData: collection.SeqView[(List[SimpleData], SimpleData), Seq[_]] = { val offset = separated.fold(1, 0) def samePrefix(s1: Int, s2: Int, t: Int): Boolean = { val s1_ = s1 - 1 val s2_ = s2 - 1 val t_ = t - 1 - offset scenariosArr(s1_)(t_) == scenariosArr(s2_)(t_) } val scenariosSize = finalScenarios.size val stagesSize = stages.size println("before triple iteration") for { s1 <- (1 to scenariosSize).view s2 <- (1 to scenariosSize).view t <- (1 to stagesSize).view } yield { if (s1 < 10 && s2 < 10 && t < 1) println(s"FORCING VIEW linkData: ($s1, $s2, $t)") List[SimpleData](s1, s2, t) -> samePrefix(s1, s2, t).fold[SimpleData](1, 0) } } } def elapsed(label: String, start: Long, end: Long): Unit = { println(s"$label: ${(end - start)} millis") } //test("Eighteen stages") { { println() println("Waiting for user input ...") scala.io.StdIn.readLine() println("Ready.") println() val start = millis val S = set val T = set val prob = param(S) //val link = param(S, S, T) default 0 val ST = set(T) within S * S val p1 = param(S, T) val x1 = xvar(S, T) val obj = minimize(p1 * x1) val base = millis println(S.shows) println(T.shows) println(prob.shows) println(ST.shows) println(p1.shows) println() val numStages = 18 /* 10 stages [info] linkDataFullT: 9420 millis [info] linkDataFullDiagonalT: 10857 millis [info] linkDataOldT: 1474 millis [info] linkDataWithDefaultT: 1458 millis [info] linkDataWithDefaultDiagonalT: 1304 millis [info] dataT: 95137 millis */ // 11 (data) OutOfMemoryError ("-XX:+UseConcMarkSweepGC", "-Xmx8G") println(s"""Creating "big model" for $numStages stages ...""") val stages = (1 to numStages).map(i => Stage(s"s$i")) val (a, b) = (BS("a"), BS("b")) val gen = millis val baseModel = model(obj).stochastic(T, S, prob, ST) .stochDefault(p1, 1.1) .stochStages(stages: _*) val assignStages = millis val finalModel = stages.foldLeft(baseModel) { (model, ti) => model .stochBasicScenarios(ti, a -> 0.4, b -> 0.6) .stochBasicData(p1, ti, a, 1.2) .stochBasicData(p1, ti, b, 1.3) } val assignBS = millis val stochData = finalModel.stochData //val lazySD = lazyStochData(stochData) val stochDataT = millis stochData.balancedTree val balancedTreeT = millis val finalScenarios = stochData.finalScenarios val scenariosT = millis stochData.TData val TDataT = millis stochData.SData val SDataT = millis elapsed("base", start, base) elapsed("gen", base, gen) elapsed("assignStages", gen, assignStages) elapsed("assignBS", assignStages, assignBS) elapsed("stochDataT", assignBS, stochDataT) elapsed("balancedTreeT", stochDataT, balancedTreeT) elapsed("scenariosT", balancedTreeT, scenariosT) elapsed("TDataT", scenariosT, TDataT) elapsed("SDataT", TDataT, SDataT) /*stochData.initPrefixes() val initPrefixesT = millis stochData.linkDataFull val linkDataFullT = millis stochData.linkDataFullDiagonal val linkDataFullDiagonalT = millis stochData.linkDataWithDefault val linkDataWithDefaultT = millis stochData.linkDataWithDefaultDiagonal val linkDataWithDefaultDiagonalT = millis elapsed("initPrefixesT", getSData, initPrefixesT) elapsed("linkDataFullT", initPrefixesT, linkDataFullT) elapsed("linkDataFullDiagonalT", linkDataFullT, linkDataFullDiagonalT) //elapsed("linkDataT (lazy)", getSData, linkDataT) elapsed("linkDataWithDefaultT", linkDataFullDiagonalT, linkDataWithDefaultT) elapsed("linkDataWithDefaultDiagonalT", linkDataWithDefaultT, linkDataWithDefaultDiagonalT) */ val startMatrix = millis stochData.initMatrix() val initMatrixT = millis /*stochData.linkSetData val linkSetDataT = millis*/ //val linkSetDataBounds = stochData.linkSetDataBounds stochData.linkSetDataBounds val linkSetDataBoundsT = millis elapsed("initMatrixT", startMatrix, initMatrixT) //elapsed("linkSetDataT", initMatrixT, linkSetDataT) elapsed("linkSetDataBoundsT", initMatrixT, linkSetDataBoundsT) /*println() println("linkSetDataBounds:") linkSetDataBounds.foreach(x => println(x.shows)) println()*/ val start2 = millis /*stochData.parametersData val parametersDataT = millis*/ stochData.parametersDataBounds val parametersDataBoundsT = millis //elapsed("parametersDataT", start2, parametersDataT) elapsed("parametersDataBoundsT", start2, parametersDataBoundsT) val start3 = millis stochData.finalProbabilities val probabilitiesT = millis val probData = stochData.probabilityData val probabilityDataT = millis /*val probData2 = stochData.probabilityData2 val probabilityData2T = millis*/ elapsed("probabilitiesT", start3, probabilitiesT) elapsed("probabilityDataT", probabilitiesT, probabilityDataT) //elapsed("probabilityData2T", probabilityDataT, probabilityData2T) /*def fixPDataSum(iter: Int): Double = { var pDataSum = probData.sum cfor(1)(_ < iter && pDataSum != 1, _ + 1) { i => pDataSum = probData.map(_ / pDataSum).sum } pDataSum }*/ val start4 = millis val pDataSum = probData.sum//fixPDataSum(1)// probData.sum val probDataSumT = millis /*val pDataSum2 = probData2.qsum val probData2SumT = millis*/ elapsed("probDataSumT", start4, probDataSumT) //elapsed("probData2SumT", probDataSumT, probData2SumT) println() println("probData:") println(probData.take(10).mkString("\\n")) println() println("probData.sum: " + pDataSum) //println("probData2.sum: " + pDataSum2) println() println() /*println("Generating mip model (data) ...") val startData = millis val mip = finalModel.mip val mipT = millis elapsed("mipT", startData, mipT) elapsed("total", start, startData)*/ println("finalScenarios:") println(finalScenarios.take(10).mkString("", "\\n", "\\n")) /*val start5 = millis val data = mip.data val dataSection = mathprog.genData(data) val dataSectionT = millis val mipModel = mip.model val modelSection = mathprog.genModel(mipModel) val modelSectionT = millis val dataPath = Path("src") / "test" / "resources" / "big-model-spec.dat" dataPath.write(dataSection) val writeDataSectionT = millis val modelPath = Path("src") / "test" / "resources" / "big-model-spec.mod" modelPath.write(modelSection) val writeModelSectionT = millis elapsed("dataSectionT", start5, dataSectionT) elapsed("modelSectionT", dataSectionT, modelSectionT) elapsed("writeDataSectionT", dataSectionT, writeDataSectionT) elapsed("writeModelSectionT", writeDataSectionT, writeModelSectionT) println() println(s"dataPath: ${dataPath.path} (${dataPath.size})") println(s"modelPath: ${modelPath.path} (${modelPath.size})")*/ } println("Waiting for user input ...") scala.io.StdIn.readLine() println("Done.") }
gerferra/amphip
core/src/test/scala/amphip/stoch/BigModelSpec.scala
Scala
mpl-2.0
8,409
package com.mesosphere.cosmos.model import com.mesosphere.universe.{ReleaseVersion, PackageDetailsVersion} case class ListVersionsResponse( results: Map[PackageDetailsVersion, ReleaseVersion] )
movicha/cosmos
cosmos-model/src/main/scala/com/mesosphere/cosmos/model/ListVersionsResponse.scala
Scala
apache-2.0
198
/* __ *\\ ** ________ ___ / / ___ __ ____ Scala.js Test Suite ** ** / __/ __// _ | / / / _ | __ / // __/ (c) 2013, LAMP/EPFL ** ** __\\ \\/ /__/ __ |/ /__/ __ |/_// /_\\ \\ http://scala-js.org/ ** ** /____/\\___/_/ |_/____/_/ | |__/ /____/ ** ** |/____/ ** \\* */ package org.scalajs.testsuite.scalalib import scala.language.implicitConversions import scala.reflect._ import org.junit.Test import org.junit.Assert._ class ClassTagTest { @Test def apply_should_get_the_existing_instances_for_predefined_ClassTags(): Unit = { assertSame(ClassTag.Byte, ClassTag(classOf[Byte])) assertSame(ClassTag.Short, ClassTag(classOf[Short])) assertSame(ClassTag.Char, ClassTag(classOf[Char])) assertSame(ClassTag.Int, ClassTag(classOf[Int])) assertSame(ClassTag.Long, ClassTag(classOf[Long])) assertSame(ClassTag.Float, ClassTag(classOf[Float])) assertSame(ClassTag.Double, ClassTag(classOf[Double])) assertSame(ClassTag.Boolean, ClassTag(classOf[Boolean])) if (System.getProperty("scalac.hasBoxedUnitBug") == null) { // Can't run on 2.12.0-M4. assertSame(ClassTag.Unit, ClassTag(classOf[Unit])) } assertSame(ClassTag.Object, ClassTag(classOf[Object])) assertSame(ClassTag.Nothing, ClassTag(classOf[Nothing])) assertSame(ClassTag.Null, ClassTag(classOf[Null])) assertSame(ClassTag.Byte, classTag[Byte]) assertSame(ClassTag.Short, classTag[Short]) assertSame(ClassTag.Char, classTag[Char]) assertSame(ClassTag.Int, classTag[Int]) assertSame(ClassTag.Long, classTag[Long]) assertSame(ClassTag.Float, classTag[Float]) assertSame(ClassTag.Double, classTag[Double]) assertSame(ClassTag.Boolean, classTag[Boolean]) assertSame(ClassTag.Unit, classTag[Unit]) assertSame(ClassTag.Any, classTag[Any]) assertSame(ClassTag.Object, classTag[Object]) assertSame(ClassTag.AnyVal, classTag[AnyVal]) assertSame(ClassTag.AnyRef, classTag[AnyRef]) assertSame(ClassTag.Nothing, classTag[Nothing]) assertSame(ClassTag.Null, classTag[Null]) } @Test def runtimeClass(): Unit = { assertSame(classOf[Byte], ClassTag.Byte.runtimeClass) assertSame(classOf[Short], ClassTag.Short.runtimeClass) assertSame(classOf[Char], ClassTag.Char.runtimeClass) assertSame(classOf[Int], ClassTag.Int.runtimeClass) assertSame(classOf[Long], ClassTag.Long.runtimeClass) assertSame(classOf[Float], ClassTag.Float.runtimeClass) assertSame(classOf[Double], ClassTag.Double.runtimeClass) assertSame(classOf[Boolean], ClassTag.Boolean.runtimeClass) if (System.getProperty("scalac.hasBoxedUnitBug") == null) { // Can't run on 2.12.0-M4. assertSame(classOf[Unit], ClassTag.Unit.runtimeClass) } assertSame(classOf[Any], ClassTag.Any.runtimeClass) assertSame(classOf[Object], ClassTag.Object.runtimeClass) assertSame(classOf[AnyVal], ClassTag.AnyVal.runtimeClass) assertSame(classOf[AnyRef], ClassTag.AnyRef.runtimeClass) assertSame(classOf[Nothing], ClassTag.Nothing.runtimeClass) assertSame(classOf[Null], ClassTag.Null.runtimeClass) assertSame(classOf[String], classTag[String].runtimeClass) assertSame(classOf[Integer], classTag[Integer].runtimeClass) assertSame(classOf[Seq[_]], classTag[Seq[_]].runtimeClass) assertSame(classOf[Array[_]], classTag[Array[_]].runtimeClass) assertSame(classOf[Array[Object]], classTag[Array[Object]].runtimeClass) assertSame(classOf[Array[_ <: AnyRef]], classTag[Array[_ <: AnyRef]].runtimeClass) assertSame(classOf[Array[String]], classTag[Array[String]].runtimeClass) assertSame(classOf[Array[_ <: Seq[_]]], classTag[Array[_ <: Seq[_]]].runtimeClass) assertSame(classOf[Array[Int]], classTag[Array[Int]].runtimeClass) assertSame(classOf[Array[Unit]], classTag[Array[Unit]].runtimeClass) // Weird, those two return Array[s.r.Nothing$] instead of Array[Object] // The same happens on the JVM assertSame(classOf[Array[scala.runtime.Nothing$]], classTag[Array[Nothing]].runtimeClass) assertSame(classOf[Array[scala.runtime.Null$]], classTag[Array[Null]].runtimeClass) assertSame(classOf[String], ClassTag(classOf[String]).runtimeClass) assertSame(classOf[Integer], ClassTag(classOf[Integer]).runtimeClass) assertSame(classOf[Seq[_]], ClassTag(classOf[Seq[_]]).runtimeClass) assertSame(classOf[Array[_]], ClassTag(classOf[Array[_]]).runtimeClass) assertSame(classOf[Array[Object]], ClassTag(classOf[Array[Object]]).runtimeClass) assertSame(classOf[Array[_ <: AnyRef]], ClassTag(classOf[Array[_ <: AnyRef]]).runtimeClass) assertSame(classOf[Array[String]], ClassTag(classOf[Array[String]]).runtimeClass) assertSame(classOf[Array[_ <: Seq[_]]], ClassTag(classOf[Array[_ <: Seq[_]]]).runtimeClass) assertSame(classOf[Array[Int]], ClassTag(classOf[Array[Int]]).runtimeClass) assertSame(classOf[Array[Unit]], ClassTag(classOf[Array[Unit]]).runtimeClass) // These work as expected, though assertSame(classOf[Array[Nothing]], ClassTag(classOf[Array[Nothing]]).runtimeClass) assertSame(classOf[Array[Null]], ClassTag(classOf[Array[Null]]).runtimeClass) } }
japgolly/scala-js
test-suite/shared/src/test/scala/org/scalajs/testsuite/scalalib/ClassTagTest.scala
Scala
bsd-3-clause
5,406
package old import drx.concreteplatform import drx.graph.{Obs, Rx} import org.scalajs.dom import org.scalajs.dom.Element import scalatags.JsDom.TypedTag import scalatags.JsDom.all._ import scalatags.generic.{AttrPair, StylePair} import scala.collection.mutable import scala.scalajs.js /** Created by david on 15.09.17. */ object RxDom { // for some subtypes of Modifier, implicit conversions aproximating // Rx[Modifier] ==> Modifier implicit def tagToMod[X <: Element](sig: Rx[TypedTag[X]]): Modifier = (parent: Element) => { var oldelem: Element = span("{{init}}").render val sinkTag = sig.map(_.render).mkForeach { newelem => replaceChild(parent, oldelem, newelem) oldelem = newelem } addSink(oldelem, sinkTag) parent.appendChild(oldelem) } implicit def styleToMod(sig: Rx[StylePair[Element, _]]): Modifier = (parent: Element) => { val sinkStyle = sig.mkForeach { mod => mod.applyTo(parent) } addSink(parent, sinkStyle) } implicit def attrToMod(sig: Rx[AttrPair[Element, _]]): Modifier = (parent: dom.Element) => { val sinkAttr = sig.mkForeach { mod => // TODO? replace hacky code with unmodifiers (unnapplyto) in scalatags? alt: use scala-dom-types? if (mod.a.name == "value") parent.asInstanceOf[js.Dynamic].value = mod.v.asInstanceOf[String] else if (mod.a.name == "checked") parent.asInstanceOf[js.Dynamic].checked = mod.v.asInstanceOf[Boolean] else if (mod.a.name == "disabled") parent.asInstanceOf[js.Dynamic].disabled = mod.v.asInstanceOf[Boolean] else mod.applyTo(parent) } addSink(parent, sinkAttr) } implicit class RxDMapMap[X](val diffs: Rx[TraversableOnce[(String, Option[X])]]) extends AnyVal { def dmapmap(fun: X => TypedTag[Element]): Modifier = (parent: Element) => { val map = mutable.Map[String, Element]() val sinkDiff = diffs.map { diffmap => diffmap }.mkForeach { diffmap => // val diffmap = diffmapy.map { case (k, optmk) => // k -> optmk.map(mk => fun(mk).render) } diffmap foreach { case (k, optnewelem) => val z = map remove k optnewelem foreach { newelemy => val newelem = fun(newelemy).render map += (k -> newelem) insertChild(parent, newelem) } z foreach (removeChild(parent, _)) } } addSink(parent, sinkDiff) } } def insertChild(parent: dom.Element, elem: dom.Element): Unit = { elem.classList.add("rx-building") parent.appendChild(elem) // if (isRooted(elem)) foreachSink(elem)(_.start()) // TODO originally switch with next line // elem.classList.remove("rx-building") } def replaceChild(parent: dom.Element, oldelem: dom.Element, newelem: dom.Element): Unit = { sinkMap.get(oldelem).getOrElse(Seq()).foreach { sink => // transfer sinks from old to new elem remSink(oldelem, sink) addSink(newelem, sink) } newelem.classList.add("rx-building") // if (isRooted(parent)) { foreachChildSink(oldelem)(_.stop()) // stop unrooted sinks foreachSink(newelem)(_.start()) // start rooted sinks // } parent.appendChild(newelem) // root newelem // TODO or before isRooted? parent.removeChild(oldelem) // root newelem // TODO or before isRooted? // elem.classList.remove("rx-building") } def removeChild(parent: dom.Element, elem: dom.Element): Unit = { parent.removeChild(elem) // if (isRooted(elem)) foreachSink(elem)(_.stop()) // TODO or one line below? } // def attrValue(sig: Rx[Modifier]): Modifier = // (t: dom.Element) => sig.mkObs { mod => // mod.applyTo(t) // } // implicit def styleValue[T: StyleValue](t: dom.Element, a: Style, signal: Signal[T]): Unit = // signal.foreach { value => implicitly[StyleValue[T]].apply(t, a, value) } // def replaceLastChild(parent: dom.Element, newelem: dom.Element): Unit = { // val visible = isRooted(parent) // if (visible) foreachSink(parent)(_.stop()) // parent.replaceChild(newelem, parent.lastChild) // if (visible) foreachSink(parent)(_.start()) // } // for debugging / testing purposes // def checkConsistency(): Unit = { // val a: Set[Observer[_]] = collectAllObs() // val b: Set[Observer[_]] = drx.debug.transitivehullobservers(a) // if (a != b) println("mist: onlydom=" + (a -- b).map(_.id) + " | onlygraph=" + (b -- a).map(_.id)) // } private val DATA_IS_REACTIVE = "data-is-reactive" private val sinkMap = concreteplatform.WeakMap[dom.Node, mutable.Set[Obs[_]]]() private def addSink(it: dom.Element, obs: Obs[_]): Unit = { val sinks = sinkMap.get(it).getOrElse { val tmp = mutable.Set[Obs[_]]() sinkMap.set(it, tmp) it.setAttribute(DATA_IS_REACTIVE, "true") tmp } sinks += obs // dom.console.log(sinkMap) } private def remSink(it: dom.Element, obs: Obs[_]): Unit = { val sinks = sinkMap.get(it).get sinks -= obs if (sinks.isEmpty) it.removeAttribute(DATA_IS_REACTIVE) // dom.console.log(sinkMap) } def collectChildSinks(fc: dom.Element): Set[Obs[_]] = { val list = fc.querySelectorAll("["+DATA_IS_REACTIVE+"]") (for (i <- 0 until list.length; y <- sinkMap.get(list(i)).getOrElse(mutable.Set())) yield y).toSet[Obs[_]] } // platform.platform.collector = () => collectChildSinks(dom.document.body) private def foreachChildSink(fc: dom.Element)(f: Obs[_] => Unit): Unit = collectChildSinks(fc).foreach(f) private def foreachSink(fc: dom.Element)(f: Obs[_] => Unit): Unit = (collectChildSinks(fc) ++ sinkMap.get(fc).getOrElse(mutable.Set())).foreach(f) private def isRooted(node: dom.Node): Boolean = dom.document.body.asInstanceOf[js.Dynamic].contains(node).asInstanceOf[Boolean] }
drcicero/drx
todojs/src/main/scala/old/RxDom.scala
Scala
mit
5,820
package org.company.app.models import com.plasmaconduit.json.codegen.traits.{GenParameterRep, GenReader, GenWriter} case class PhoneNumber(value: String) extends GenReader with GenWriter { override val readerRep = GenParameterRep override val writerRep = GenParameterRep }
Agrosis/jcg
examples/src/main/scala/org/company/app/models/PhoneNumber.scala
Scala
mit
279
package xitrum.handler.inbound import java.util.{Map => JMap, List => JList} import scala.collection.mutable.{ArrayBuffer, Map => MMap} import scala.util.control.NonFatal import io.netty.channel.{ChannelHandler, ChannelHandlerContext, SimpleChannelInboundHandler} import ChannelHandler.Sharable import io.netty.handler.codec.http.QueryStringDecoder import xitrum.{Config, Log} import xitrum.handler.HandlerEnv import xitrum.scope.request.{Params, PathInfo} @Sharable class UriParser extends SimpleChannelInboundHandler[HandlerEnv] { override def channelRead0(ctx: ChannelHandlerContext, env: HandlerEnv) { val request = env.request try { val decoder = new QueryStringDecoder(request.getUri, Config.xitrum.request.charset) val path = decoder.path // Treat "articles" and "articles/" the same val noSlashSuffix = if (path.endsWith("/")) path.substring(0, path.length - 1) else path env.pathInfo = new PathInfo(noSlashSuffix) env.queryParams = jParamsToParams(decoder.parameters) ctx.fireChannelRead(env) } catch { case NonFatal(e) => val msg = "Could not parse query params URI: " + request.getUri Log.warn(msg, e) // https://github.com/xitrum-framework/xitrum/issues/508#issuecomment-72808997 // Do not close channel without responding status code. // Nginx decides that upstream is down if upstream drop connection without responding status code. BadClientSilencer.respond400(ctx.channel, "Could not parse params in URI: " + e.getMessage) } } //---------------------------------------------------------------------------- private def jParamsToParams(params: JMap[String, JList[String]]): Params = { val keySet = params.keySet val it = keySet.iterator val ret = MMap.empty[String, Seq[String]] while (it.hasNext) { val key = it.next() val values = params.get(key) val it2 = values.iterator val ret2 = ArrayBuffer.empty[String] while (it2.hasNext) { val value = it2.next() ret2.append(value) } ret(key) = ret2.toList } ret } }
caiiiycuk/xitrum
src/main/scala/xitrum/handler/inbound/UriParser.scala
Scala
mit
2,188
package com.gjos.scala.swoc package object protocol { type Location = Int type Move = Int type Field = Int type Direction = Int type BoardHash = Int type MoveType = Int type Player = Int type Stone = Int }
Oduig/swoc2014
Greedy/src/main/scala/com/gjos/scala/swoc/protocol/package.scala
Scala
apache-2.0
223
package org.jetbrains.plugins.scala package testingSupport.test import java.io.{File, FileOutputStream, IOException, PrintStream} import com.intellij.diagnostic.logging.LogConfigurationPanel import com.intellij.execution._ import com.intellij.execution.configurations._ import com.intellij.execution.runners.{ExecutionEnvironment, ProgramRunner} import com.intellij.execution.testframework.TestFrameworkRunningModel import com.intellij.execution.testframework.sm.{CompositeTestLocationProvider, SMTestRunnerConnectionUtil} import com.intellij.execution.testframework.sm.runner.SMTRunnerConsoleProperties import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.module.{Module, ModuleManager} import com.intellij.openapi.options.{SettingsEditor, SettingsEditorGroup} import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.{JdkUtil, Sdk} import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.{Computable, Getter, JDOMExternalizer} import com.intellij.psi._ import com.intellij.psi.search.GlobalSearchScope import org.jdom.Element import org.jetbrains.plugins.scala.extensions._ import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil import org.jetbrains.plugins.scala.lang.psi.api.ScPackage import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScModifierListOwner import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScClass, ScObject} import org.jetbrains.plugins.scala.lang.psi.impl.{ScPackageImpl, ScalaPsiManager} import org.jetbrains.plugins.scala.project._ import org.jetbrains.plugins.scala.project.maven.ScalaTestDefaultWorkingDirectoryProvider import org.jetbrains.plugins.scala.testingSupport.ScalaTestingConfiguration import org.jetbrains.plugins.scala.testingSupport.locationProvider.ScalaTestLocationProvider import org.jetbrains.plugins.scala.testingSupport.test.AbstractTestRunConfiguration.PropertiesExtension import org.jetbrains.plugins.scala.testingSupport.test.TestRunConfigurationForm.{SearchForTest, TestKind} import org.jetbrains.plugins.scala.util.ScalaUtil import scala.beans.BeanProperty import scala.collection.JavaConversions._ import scala.collection.mutable import scala.collection.mutable.ArrayBuffer /** * @author Ksenia.Sautina * @since 5/15/12 */ abstract class AbstractTestRunConfiguration(val project: Project, val configurationFactory: ConfigurationFactory, val name: String, private var envs: java.util.Map[String, String] = new mutable.HashMap[String, String](), private var addIntegrationTestsClasspath: Boolean = false) extends ModuleBasedConfiguration[RunConfigurationModule](name, new RunConfigurationModule(project), configurationFactory) with ScalaTestingConfiguration { val SCALA_HOME = "-Dscala.home=" val CLASSPATH = "-Denv.classpath=\"%CLASSPATH%\"" val EMACS = "-Denv.emacs=\"%EMACS%\"" def setupIntegrationTestClassPath() = addIntegrationTestsClasspath = true def getAdditionalTestParams(testName: String): Seq[String] = Seq() def currentConfiguration = AbstractTestRunConfiguration.this def suitePaths: List[String] final def javaSuitePaths = { import scala.collection.JavaConverters._ suitePaths.asJava } def mainClass: String def reporterClass: String def errorMessage: String private var testClassPath = "" private var testPackagePath = "" private var testArgs = "" private var javaOptions = "" private var workingDirectory = "" def getTestClassPath = testClassPath def getTestPackagePath = testPackagePath def getTestArgs = testArgs def getJavaOptions = javaOptions def getWorkingDirectory: String = ExternalizablePath.localPathValue(workingDirectory) def setTestClassPath(s: String) { testClassPath = s } def setTestPackagePath(s: String) { testPackagePath = s } def setTestArgs(s: String) { testArgs = s } def setJavaOptions(s: String) { javaOptions = s } def setWorkingDirectory(s: String) { workingDirectory = ExternalizablePath.urlValue(s) } def initWorkingDir() = if (workingDirectory == null || workingDirectory.trim.isEmpty) setWorkingDirectory(provideDefaultWorkingDir) private def provideDefaultWorkingDir = { val module = getModule ScalaTestDefaultWorkingDirectoryProvider.EP_NAME.getExtensions.find(_.getWorkingDirectory(module) != null) match { case Some(provider) => provider.getWorkingDirectory(module) case _ => Option(getProject.getBaseDir).map(_.getPath).getOrElse("") } } @BeanProperty var searchTest: SearchForTest = SearchForTest.ACCROSS_MODULE_DEPENDENCIES @BeanProperty var testName = "" @BeanProperty var testKind = TestKind.CLASS @BeanProperty var showProgressMessages = true def splitTests = testName.split("\n").filter(!_.isEmpty) private var generatedName: String = "" def setGeneratedName(name: String) { generatedName = name } override def isGeneratedName = getName == null || getName.equals(suggestedName) override def suggestedName = generatedName def apply(configuration: TestRunConfigurationForm) { testKind = configuration.getSelectedKind setTestClassPath(configuration.getTestClassPath) setTestPackagePath(configuration.getTestPackagePath) setSearchTest(configuration.getSearchForTest) setJavaOptions(configuration.getJavaOptions) setTestArgs(configuration.getTestArgs) setModule(configuration.getModule) val workDir = configuration.getWorkingDirectory setWorkingDirectory( if (workDir != null && !workDir.trim.isEmpty) { workDir } else { provideDefaultWorkingDir } ) setTestName(configuration.getTestName) setEnvVariables(configuration.getEnvironmentVariables) setShowProgressMessages(configuration.getShowProgressMessages) } def getClazz(path: String, withDependencies: Boolean): PsiClass = { val classes = ScalaPsiManager.instance(project).getCachedClasses(getScope(withDependencies), path) val objectClasses = classes.filter(_.isInstanceOf[ScObject]) val nonObjectClasses = classes.filter(!_.isInstanceOf[ScObject]) if (nonObjectClasses.nonEmpty) nonObjectClasses(0) else if (objectClasses.nonEmpty) objectClasses(0) else null } def getPackage(path: String): PsiPackage = { ScPackageImpl.findPackage(project, path) } def getScope(withDependencies: Boolean): GlobalSearchScope = { def mScope(module: Module) = { if (withDependencies) GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) else GlobalSearchScope.moduleScope(module) } def unionScope(moduleGuard: Module => Boolean): GlobalSearchScope = { var scope: GlobalSearchScope = if (getModule != null) mScope(getModule) else GlobalSearchScope.EMPTY_SCOPE for (module <- ModuleManager.getInstance(getProject).getModules) { if (moduleGuard(module)) { scope = scope.union(mScope(module)) } } scope } testKind match { case TestKind.ALL_IN_PACKAGE => searchTest match { case SearchForTest.IN_WHOLE_PROJECT => unionScope(_ => true) case SearchForTest.IN_SINGLE_MODULE if getModule != null => mScope(getModule) case SearchForTest.ACCROSS_MODULE_DEPENDENCIES if getModule != null => unionScope(ModuleManager.getInstance(getProject).isModuleDependent(getModule, _)) case _ => unionScope(_ => true) } case _ => if (getModule != null) mScope(getModule) else unionScope(_ => true) } } def expandPath(_path: String): String = { var path = _path path = PathMacroManager.getInstance(project).expandPath(path) if (getModule != null) { path = PathMacroManager.getInstance(getModule).expandPath(path) } path } def getEnvVariables = envs def setEnvVariables(variables: java.util.Map[String, String]) = { envs = variables } def getModule: Module = { getConfigurationModule.getModule } def getValidModules: java.util.List[Module] = getProject.modulesWithScala override def getModules: Array[Module] = { ApplicationManager.getApplication.runReadAction(new Computable[Array[Module]] { @SuppressWarnings(Array("ConstantConditions")) def compute: Array[Module] = { searchTest match { case SearchForTest.ACCROSS_MODULE_DEPENDENCIES if getModule != null => val buffer = new ArrayBuffer[Module]() buffer += getModule for (module <- ModuleManager.getInstance(getProject).getModules) { if (ModuleManager.getInstance(getProject).isModuleDependent(getModule, module)) { buffer += module } } buffer.toArray case SearchForTest.IN_SINGLE_MODULE if getModule != null => Array(getModule) case SearchForTest.IN_WHOLE_PROJECT => ModuleManager.getInstance(getProject).getModules case _ => Array.empty } } }) } private def getSuiteClass = { val suiteClasses = suitePaths.map(suitePath => getClazz(suitePath, withDependencies = true)).filter(_ != null) if (suiteClasses.isEmpty) { throw new RuntimeConfigurationException(errorMessage) } if (suiteClasses.size > 1) { throw new RuntimeConfigurationException("Multiple suite traits detected: " + suiteClasses) } suiteClasses.head } override def checkConfiguration() { super.checkConfiguration() val suiteClass = getSuiteClass testKind match { case TestKind.ALL_IN_PACKAGE => searchTest match { case SearchForTest.IN_WHOLE_PROJECT => case SearchForTest.IN_SINGLE_MODULE | SearchForTest.ACCROSS_MODULE_DEPENDENCIES => if (getModule == null) { throw new RuntimeConfigurationException("Module is not specified") } } val pack = JavaPsiFacade.getInstance(project).findPackage(getTestPackagePath) if (pack == null) { throw new RuntimeConfigurationException("Package doesn't exist") } case TestKind.CLASS | TestKind.TEST_NAME => if (getModule == null) { throw new RuntimeConfigurationException("Module is not specified") } if (getTestClassPath == "") { throw new RuntimeConfigurationException("Test Class is not specified") } val clazz = getClazz(getTestClassPath, withDependencies = false) if (clazz == null || isInvalidSuite(clazz)) { throw new RuntimeConfigurationException("No Suite Class is found for Class %s in module %s".format(getTestClassPath, getModule.getName)) } if (!ScalaPsiUtil.cachedDeepIsInheritor(clazz, suiteClass)) { throw new RuntimeConfigurationException("Class %s is not inheritor of Suite trait".format(getTestClassPath)) } if (testKind == TestKind.TEST_NAME && getTestName == "") { throw new RuntimeConfigurationException("Test Name is not specified") } } JavaRunConfigurationExtensionManager.checkConfigurationIsValid(this) } def getConfigurationEditor: SettingsEditor[_ <: RunConfiguration] = { val group: SettingsEditorGroup[AbstractTestRunConfiguration] = new SettingsEditorGroup group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), new AbstractTestRunConfigurationEditor(project, this)) JavaRunConfigurationExtensionManager.getInstance.appendEditors(this, group) group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel) group } protected[test] def isInvalidSuite(clazz: PsiClass): Boolean = AbstractTestRunConfiguration.isInvalidSuite(clazz) override def getState(executor: Executor, env: ExecutionEnvironment): RunProfileState = { def classNotFoundError() { throw new ExecutionException("Test class not found.") } var clazz: PsiClass = null var suiteClass: PsiClass = null var pack: ScPackage = null try { testKind match { case TestKind.CLASS => clazz = getClazz(getTestClassPath, withDependencies = false) case TestKind.ALL_IN_PACKAGE => pack = ScPackageImpl(getPackage(getTestPackagePath)) case TestKind.TEST_NAME => clazz = getClazz(getTestClassPath, withDependencies = false) if (getTestName == null || getTestName == "") throw new ExecutionException("Test name not found.") } suiteClass = getSuiteClass } catch { case e if clazz == null => classNotFoundError() } if (clazz == null && pack == null) classNotFoundError() if (suiteClass == null) throw new ExecutionException(errorMessage) val classes = new mutable.HashSet[PsiClass] if (clazz != null) { if (ScalaPsiUtil.cachedDeepIsInheritor(clazz, suiteClass)) classes += clazz } else { val scope = getScope(withDependencies = false) def getClasses(pack: ScPackage): Seq[PsiClass] = { val buffer = new ArrayBuffer[PsiClass] buffer ++= pack.getClasses(scope) for (p <- pack.getSubPackages) { buffer ++= getClasses(ScPackageImpl(p)) } buffer.toSeq } for (cl <- getClasses(pack)) { if (!isInvalidSuite(cl) && ScalaPsiUtil.cachedDeepIsInheritor(cl, suiteClass)) classes += cl } } if (classes.isEmpty) throw new ExecutionException("Not found suite class.") val module = getModule if (module == null) throw new ExecutionException("Module is not specified") val state = new JavaCommandLineState(env) with AbstractTestRunConfiguration.TestCommandLinePatcher { val getClasses: Seq[String] = getClassFileNames(classes) protected override def createJavaParameters: JavaParameters = { val params = new JavaParameters() params.setCharset(null) var vmParams = getJavaOptions //expand macros vmParams = PathMacroManager.getInstance(project).expandPath(vmParams) if (module != null) { vmParams = PathMacroManager.getInstance(module).expandPath(vmParams) } params.setEnv(getEnvVariables) //expand environment variables in vmParams for (entry <- params.getEnv.entrySet) { vmParams = StringUtil.replace(vmParams, "$" + entry.getKey + "$", entry.getValue, false) } params.getVMParametersList.addParametersString(vmParams) val wDir = getWorkingDirectory params.setWorkingDirectory(expandPath(wDir)) // params.getVMParametersList.addParametersString("-Xnoagent -Djava.compiler=NONE -Xdebug " + // "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5010") val rtJarPath = ScalaUtil.runnersPath() params.getClassPath.add(rtJarPath) if (addIntegrationTestsClasspath) { //a workaround to add jars for integration tests val integrationTestsPath = ScalaUtil.testingSupportTestPath() params.getClassPath.add(integrationTestsPath) } searchTest match { case SearchForTest.IN_WHOLE_PROJECT => var jdk: Sdk = null for (module <- ModuleManager.getInstance(project).getModules if jdk == null) { jdk = JavaParameters.getModuleJdk(module) } params.configureByProject(project, JavaParameters.JDK_AND_CLASSES_AND_TESTS, jdk) case _ => params.configureByModule(module, JavaParameters.JDK_AND_CLASSES_AND_TESTS, JavaParameters.getModuleJdk(module)) } params.setMainClass(mainClass) if (JdkUtil.useDynamicClasspath(getProject)) { try { val fileWithParams: File = File.createTempFile("abstracttest", ".tmp") val outputStream = new FileOutputStream(fileWithParams) val printer: PrintStream = new PrintStream(outputStream) if (getFailedTests == null) { printer.println("-s") for (cl <- getClasses) { printer.println(cl) } if (testKind == TestKind.TEST_NAME && testName != "") { //this is a "by-name" test for single suite, better fail in a known manner then do something undefined assert(getClasses.size == 1) for (test <- splitTests) { printer.println("-testName") printer.println(test) for (testParam <- getAdditionalTestParams(test)) { params.getVMParametersList.addParametersString(testParam) } } } } else { printer.println("-failedTests") for (failed <- getFailedTests) { printer.println(failed._1) printer.println(failed._2) for (testParam <- getAdditionalTestParams(failed._2)) { params.getVMParametersList.addParametersString(testParam) } } } printer.println("-showProgressMessages") printer.println(showProgressMessages.toString) if (reporterClass != null) { printer.println("-C") printer.println(reporterClass) } val parms: Array[String] = ParametersList.parse(getTestArgs) for (parm <- parms) { printer.println(parm) } printer.close() params.getProgramParametersList.add("@" + fileWithParams.getPath) } catch { case ioException: IOException => throw new ExecutionException("Failed to create dynamic classpath file with command-line args.", ioException) } } else { if (getFailedTests == null) { params.getProgramParametersList.add("-s") for (cl <- getClasses) params.getProgramParametersList.add(cl) if (testKind == TestKind.TEST_NAME && testName != "") { //this is a "by-name" test for single suite, better fail in a known manner then do something undefined assert(getClasses.size == 1) for (test <- splitTests) { params.getProgramParametersList.add("-testName") params.getProgramParametersList.add(test) for (testParam <- getAdditionalTestParams(test)) { params.getVMParametersList.addParametersString(testParam) } } } } else { params.getProgramParametersList.add("-failedTests") for (failed <- getFailedTests) { params.getProgramParametersList.add(failed._1) params.getProgramParametersList.add(failed._2) for (testParam <- getAdditionalTestParams(failed._2)) { params.getVMParametersList.addParametersString(testParam) } } } params.getProgramParametersList.add("-showProgressMessages") params.getProgramParametersList.add(showProgressMessages.toString) if (reporterClass != null) { params.getProgramParametersList.add("-C") params.getProgramParametersList.add(reporterClass) } params.getProgramParametersList.addParametersString(getTestArgs) } for (ext <- Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) { ext.updateJavaParameters(currentConfiguration, params, getRunnerSettings) } params } override def execute(executor: Executor, runner: ProgramRunner[_ <: RunnerSettings]): ExecutionResult = { val processHandler = startProcess val runnerSettings = getRunnerSettings if (getConfiguration == null) setConfiguration(currentConfiguration) val config = getConfiguration JavaRunConfigurationExtensionManager.getInstance. attachExtensionsToProcess(currentConfiguration, processHandler, runnerSettings) val consoleProperties = new SMTRunnerConsoleProperties(currentConfiguration, "Scala", executor) with PropertiesExtension { override def getTestLocator = new ScalaTestLocationProvider def getRunConfigurationBase: RunConfigurationBase = config } consoleProperties.setIdBasedTestTree(true) // console view val consoleView = SMTestRunnerConnectionUtil.createAndAttachConsole("Scala", processHandler, consoleProperties) val res = new DefaultExecutionResult(consoleView, processHandler, createActions(consoleView, processHandler, executor): _*) val rerunFailedTestsAction = new AbstractTestRerunFailedTestsAction(consoleView) rerunFailedTestsAction.init(consoleView.getProperties) rerunFailedTestsAction.setModelProvider(new Getter[TestFrameworkRunningModel] { def get: TestFrameworkRunningModel = { consoleView.asInstanceOf[SMTRunnerConsoleView].getResultsViewer } }) res.setRestartActions(rerunFailedTestsAction) res } } state } protected def getClassFileNames(classes: mutable.HashSet[PsiClass]): Seq[String] = classes.map(_.qualifiedName).toSeq override def writeExternal(element: Element) { super.writeExternal(element) JavaRunConfigurationExtensionManager.getInstance.writeExternal(this, element) writeModule(element) JDOMExternalizer.write(element, "path", getTestClassPath) JDOMExternalizer.write(element, "package", getTestPackagePath) JDOMExternalizer.write(element, "vmparams", getJavaOptions) JDOMExternalizer.write(element, "params", getTestArgs) JDOMExternalizer.write(element, "workingDirectory", workingDirectory) JDOMExternalizer.write(element, "searchForTest", searchTest.toString) JDOMExternalizer.write(element, "testName", testName) JDOMExternalizer.write(element, "testKind", if (testKind != null) testKind.toString else TestKind.CLASS.toString) JDOMExternalizer.write(element, "showProgressMessages", showProgressMessages.toString) JDOMExternalizer.writeMap(element, envs, "envs", "envVar") PathMacroManager.getInstance(getProject).collapsePathsRecursively(element) } override def readExternal(element: Element) { PathMacroManager.getInstance(getProject).expandPaths(element) super.readExternal(element) JavaRunConfigurationExtensionManager.getInstance.readExternal(this, element) readModule(element) testClassPath = JDOMExternalizer.readString(element, "path") testPackagePath = JDOMExternalizer.readString(element, "package") javaOptions = JDOMExternalizer.readString(element, "vmparams") testArgs = JDOMExternalizer.readString(element, "params") workingDirectory = JDOMExternalizer.readString(element, "workingDirectory") JDOMExternalizer.readMap(element, envs, "envs", "envVar") val s = JDOMExternalizer.readString(element, "searchForTest") for (search <- SearchForTest.values()) { if (search.toString == s) searchTest = search } testName = Option(JDOMExternalizer.readString(element, "testName")).getOrElse("") testKind = TestKind.fromString(Option(JDOMExternalizer.readString(element, "testKind")).getOrElse("Class")) showProgressMessages = JDOMExternalizer.readBoolean(element, "showProgressMessages") } } trait SuiteValidityChecker { protected[test] def isInvalidSuite(clazz: PsiClass): Boolean = { val list: PsiModifierList = clazz.getModifierList list != null && list.hasModifierProperty(PsiModifier.ABSTRACT) || lackSuitableConstructor(clazz) } protected[test] def lackSuitableConstructor(clazz: PsiClass): Boolean } object AbstractTestRunConfiguration extends SuiteValidityChecker { private[test] trait TestCommandLinePatcher { private var failedTests: Seq[(String, String)] = null def setFailedTests(failedTests: Seq[(String, String)]) { this.failedTests = Option(failedTests).map(_.distinct).orNull } def getFailedTests = failedTests def getClasses: Seq[String] @BeanProperty var configuration: RunConfigurationBase = null } private[test] trait PropertiesExtension extends SMTRunnerConsoleProperties{ def getRunConfigurationBase: RunConfigurationBase } protected[test] def lackSuitableConstructor(clazz: PsiClass): Boolean = { val constructors = clazz match { case c: ScClass => c.secondaryConstructors.filter(_.isConstructor).toList ::: c.constructor.toList case _ => clazz.getConstructors.toList } for (con <- constructors) { if (con.isConstructor && con.getParameterList.getParametersCount == 0) { con match { case owner: ScModifierListOwner => if (owner.hasModifierProperty(PsiModifier.PUBLIC)) return false case _ => } } } true } }
whorbowicz/intellij-scala
src/org/jetbrains/plugins/scala/testingSupport/test/AbstractTestRunConfiguration.scala
Scala
apache-2.0
25,313
package io.github.binaryfoo.lagotto import org.joda.time.DateTime import scala.collection.mutable /** * Ceremony around a Map. */ case class SimpleLogEntry(private val _fields: mutable.LinkedHashMap[String, String], private val timeFormat: Option[TimeExpr] = None, lines: String, source: SourceRef = null) extends LogEntry { val timestamp: DateTime = { timeFormat.map { case TimeExpr(expr, formatter) => _fields.get(expr) .map(formatter.parseDateTime) .getOrElse(throw new IAmSorryDave(s"Missing 'timestamp' in ${_fields}")) }.orNull } val fields = _fields.withDefaultValue(null) def apply(id: String) = fields(id) override def exportAsSeq: Seq[(String, String)] = _fields.toSeq } object SimpleLogEntry { def apply(lines: String, fields: (String, String)*): SimpleLogEntry = SimpleLogEntry(mutable.LinkedHashMap(fields :_*), lines = lines) def apply(fields: (String, String)*): SimpleLogEntry = SimpleLogEntry(mutable.LinkedHashMap(fields :_*), lines = "") }
binaryfoo/lagotto
src/main/scala/io/github/binaryfoo/lagotto/SimpleLogEntry.scala
Scala
mit
1,008
package examples import language.implicitConversions import scala.concurrent.{ Channel, ExecutionContext, future, Future, promise } import scala.concurrent.util.Duration import scala.util.{ Try, Success, Failure } import java.util.concurrent.{ CountDownLatch, Executors } import java.util.concurrent.atomic._ object computeServer { type Stats = Tuple3[Int,Int,Int] class ComputeServer(n: Int, completer: Try[Stats] => Unit)(implicit ctx: ExecutionContext) { private trait Job { type T def task: T def complete(x: Try[T]): Unit } private val openJobs = new Channel[Job]() private def processor(i: Int) = { printf("processor %d starting\\n", i) // simulate failure in faulty #3 if (i == 3) throw new IllegalStateException("processor %d: Drat!" format i) var good = 0 var bad = 0 while (!isDone) { val job = openJobs.read printf("processor %d read a job\\n", i) val res = Try(job.task) if (res.isSuccess) good += 1 else bad += 1 job complete res } printf("processor %d terminating\\n", i) (i, good, bad) } def submit[A](body: => A): Future[A] = { val p = promise[A]() openJobs.write { new Job { type T = A def task = body def complete(x: Try[A]) = p complete x } } p.future } val done = new AtomicBoolean def isDone = done.get def finish() { done set true val nilJob = new Job { type T = Null def task = null def complete(x: Try[Null]) { } } // unblock readers for (_ <- 1 to n) { openJobs write nilJob } } // You can, too! http://www.manning.com/suereth/ def futured[A,B](f: A => B): A => Future[B] = { in => future(f(in)) } def futureHasArrived(f: Future[Stats]) = f onComplete completer 1 to n map futured(processor) foreach futureHasArrived } @inline implicit class Whiling(val latch: CountDownLatch) extends AnyVal { def awaitAwhile()(implicit d: Duration): Boolean = latch.await(d.length, d.unit) } def main(args: Array[String]) { def usage(msg: String = "scala examples.computeServer <n>"): Nothing = { println(msg) sys.exit(1) } if (args.length > 1) usage() val rt = Runtime.getRuntime import rt.{ availableProcessors => avail } def using(n: Int) = { println(s"Using $n processors"); n } val numProcessors = (Try(args.head.toInt) filter (_ > 0) map (_ min avail) recover { case _: NumberFormatException => usage() case _ => using(4 min avail) }).get implicit val ctx = ExecutionContext fromExecutorService (Executors newFixedThreadPool (numProcessors)) val doneLatch = new CountDownLatch(numProcessors) def completer(e: Try[Stats]) { e match { case Success(s) => println(s"Processor ${s._1} completed ${s._2} jobs with ${s._3} errors") case Failure(t) => println("Processor terminated in error: "+ t.getMessage) } doneLatch.countDown() } val server = new ComputeServer(numProcessors, completer _) val numResults = 3 val resultLatch = new CountDownLatch(numResults) class ResultCounter[A](future: Future[A]) { def onResult[B](body: PartialFunction[Try[A], B])(implicit x: ExecutionContext) = future andThen body andThen { case _ => resultLatch.countDown() } } implicit def countingFuture[A](f: Future[A]): ResultCounter[A] = new ResultCounter[A](f) def dbz = 1/0 val k = server submit dbz k onResult { case Success(v) => println("k returned? "+ v) case Failure(e) => println("k failed! "+ e) } val f = server submit 42 val g = server submit 38 val h = for (x <- f; y <- g) yield { x + y } h onResult { case Success(v) => println(s"Computed $v") } val report: PartialFunction[Try[_], Unit] = { case Success(v) => println(s"Computed $v") case Failure(e) => println(s"Does not compute: $e") } val r = for { x <- server submit 17 y <- server submit { throw new RuntimeException("Simulated failure"); 13 } } yield (x * y) r onResult report implicit val awhile = Duration("1 sec") def windDown() = { server.finish() doneLatch.awaitAwhile() } def shutdown() = { ctx.shutdown() ctx.awaitTermination(awhile.length, awhile.unit) } val done = resultLatch.awaitAwhile() && windDown() && shutdown() assert(done, "Error shutting down.") } }
chenc10/Spark-PAF
build/scala-2.10.5/examples/computeserver.scala
Scala
apache-2.0
4,582
package org.jetbrains.plugins.scala package lang package psi package api package statements import java.util import com.intellij.lang.java.lexer.JavaLexer import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.Key import com.intellij.pom.java.LanguageLevel import com.intellij.psi.PsiReferenceList.Role import com.intellij.psi._ import com.intellij.psi.impl.source.HierarchicalMethodSignatureImpl import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.{MethodSignatureBackedByPsiMethod, PsiModificationTracker} import com.intellij.util.containers.ConcurrentHashMap import org.jetbrains.plugins.scala.caches.CachesUtil import org.jetbrains.plugins.scala.extensions._ import org.jetbrains.plugins.scala.icons.Icons import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes import org.jetbrains.plugins.scala.lang.psi.api.base.ScMethodLike import org.jetbrains.plugins.scala.lang.psi.api.base.types._ import org.jetbrains.plugins.scala.lang.psi.api.expr.ScBlockStatement import org.jetbrains.plugins.scala.lang.psi.api.statements.params._ import org.jetbrains.plugins.scala.lang.psi.api.toplevel._ import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef._ import org.jetbrains.plugins.scala.lang.psi.fake.{FakePsiReferenceList, FakePsiTypeParameterList} import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.synthetic.{JavaIdentifier, ScSyntheticFunction, ScSyntheticTypeParameter, SyntheticClasses} import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.typedef.TypeDefinitionMembers import org.jetbrains.plugins.scala.lang.psi.light.ScFunctionWrapper import org.jetbrains.plugins.scala.lang.psi.light.scala.{ScLightFunctionDeclaration, ScLightFunctionDefinition} import org.jetbrains.plugins.scala.lang.psi.stubs.ScFunctionStub import org.jetbrains.plugins.scala.lang.psi.types.nonvalue._ import org.jetbrains.plugins.scala.lang.psi.types.result.{Failure, Success, TypeResult, TypingContext} import org.jetbrains.plugins.scala.lang.psi.types.{Unit => UnitType, _} import scala.annotation.tailrec import scala.collection.Seq import scala.collection.immutable.Set import scala.collection.mutable.ArrayBuffer /** * @author Alexander Podkhalyuzin */ //some functions are not PsiMethods and are e.g. not visible from java //see ScSyntheticFunction trait ScFun extends ScTypeParametersOwner { def retType: ScType def paramClauses: Seq[Seq[Parameter]] def methodType: ScType = { paramClauses.foldRight[ScType](retType) { (params: Seq[Parameter], tp: ScType) => new ScMethodType(tp, params, false)(getProject, getResolveScope) } } def polymorphicType: ScType = { if (typeParameters.length == 0) methodType else ScTypePolymorphicType(methodType, typeParameters.map(new TypeParameter(_))) } } /** * Represents Scala's internal function definitions and declarations */ trait ScFunction extends ScalaPsiElement with ScMember with ScTypeParametersOwner with ScParameterOwner with ScDocCommentOwner with ScTypedDefinition with ScCommentOwner with ScDeclaredElementsHolder with ScAnnotationsHolder with ScMethodLike with ScBlockStatement { private var synthNavElement: Option[PsiElement] = None var syntheticCaseClass: Option[ScClass] = None var syntheticContainingClass: Option[ScTypeDefinition] = None def setSynthetic(navElement: PsiElement) { synthNavElement = Some(navElement) } def isSyntheticCopy: Boolean = synthNavElement.nonEmpty && name == "copy" def isSyntheticApply: Boolean = synthNavElement.nonEmpty && name == "apply" def isSyntheticUnapply: Boolean = synthNavElement.nonEmpty && name == "unapply" def isSyntheticUnapplySeq: Boolean = synthNavElement.nonEmpty && name == "unapplySeq" def isSynthetic: Boolean = synthNavElement.nonEmpty def getSyntheticNavigationElement: Option[PsiElement] = synthNavElement def hasUnitResultType = { def hasUnitRT(t: ScType): Boolean = t match { case UnitType => true case ScMethodType(result, _, _) => hasUnitRT(result) case _ => false } hasUnitRT(methodType) } def isParameterless = paramClauses.clauses.isEmpty private val probablyRecursive: ThreadLocal[Boolean] = new ThreadLocal[Boolean]() { override def initialValue(): Boolean = false } def isProbablyRecursive = probablyRecursive.get() def setProbablyRecursive(b: Boolean) {probablyRecursive.set(b)} def isEmptyParen = paramClauses.clauses.size == 1 && paramClauses.params.size == 0 def addEmptyParens() { val clause = ScalaPsiElementFactory.createClauseFromText("()", getManager) paramClauses.addClause(clause) } def removeAllClauses() { paramClauses.clauses.headOption.zip(paramClauses.clauses.lastOption).foreach { p => paramClauses.deleteChildRange(p._1, p._2) } } def isNative: Boolean = { hasAnnotation("scala.native") != None } override def hasModifierProperty(name: String): Boolean = { if (name == "abstract") { this match { case _: ScFunctionDeclaration => containingClass match { case t: ScTrait => return true case c: ScClass if c.hasAbstractModifier => return true case _ => } case _ => } } super.hasModifierProperty(name) } /** * This method is important for expected type evaluation. */ def getInheritedReturnType: Option[ScType] = { returnTypeElement match { case Some(_) => returnType.toOption case None => val superReturnType = superMethodAndSubstitutor match { case Some((fun: ScFunction, subst)) => var typeParamSubst = ScSubstitutor.empty fun.typeParameters.zip(typeParameters).foreach { case (oldParam: ScTypeParam, newParam: ScTypeParam) => typeParamSubst = typeParamSubst.bindT((oldParam.name, ScalaPsiUtil.getPsiElementId(oldParam)), new ScTypeParameterType(newParam, subst)) } fun.returnType.toOption.map(typeParamSubst.followed(subst).subst) case Some((fun: ScSyntheticFunction, subst)) => var typeParamSubst = ScSubstitutor.empty fun.typeParameters.zip(typeParameters).foreach { case (oldParam: ScSyntheticTypeParameter, newParam: ScTypeParam) => typeParamSubst = typeParamSubst.bindT((oldParam.name, ScalaPsiUtil.getPsiElementId(oldParam)), new ScTypeParameterType(newParam, subst)) } Some(subst.subst(fun.retType)) case Some((fun: PsiMethod, subst)) => var typeParamSubst = ScSubstitutor.empty fun.getTypeParameters.zip(typeParameters).foreach { case (oldParam: PsiTypeParameter, newParam: ScTypeParam) => typeParamSubst = typeParamSubst.bindT((oldParam.name, ScalaPsiUtil.getPsiElementId(oldParam)), new ScTypeParameterType(newParam, subst)) } Some(typeParamSubst.followed(subst).subst(ScType.create(fun.getReturnType, getProject, getResolveScope))) case _ => None } superReturnType } } override def getTextOffset: Int = nameId.getTextRange.getStartOffset def hasParameterClause: Boolean = { if (effectiveParameterClauses.length != 0) return true superMethod match { case Some(fun: ScFunction) => fun.hasParameterClause case Some(psi: PsiMethod) => true case None => false } } /** * Signature has repeated param, which is not the last one */ def hasMalformedSignature: Boolean = { val clausesIterator = paramClauses.clauses.iterator while (clausesIterator.hasNext) { val clause = clausesIterator.next() val paramsIterator = clause.parameters.iterator while (paramsIterator.hasNext) { val param = paramsIterator.next() if (paramsIterator.hasNext && param.isRepeatedParameter) return true } } false } def definedReturnType: TypeResult[ScType] = { returnTypeElement match { case Some(ret) => ret.getType(TypingContext.empty) case _ if !hasAssign => Success(types.Unit, Some(this)) case _ => superMethod match { case Some(f: ScFunction) => f.definedReturnType case Some(m: PsiMethod) => Success(ScType.create(m.getReturnType, getProject, getResolveScope), Some(this)) case _ => Failure("No defined return type", Some(this)) } } } /** * Returns pure 'function' type as it was defined as a field with functional value */ def methodType(result: Option[ScType]): ScType = { val clauses = effectiveParameterClauses val resultType = result match { case None => returnType.getOrAny case Some(x) => x } if (!hasParameterClause) return resultType val res = if (clauses.length > 0) clauses.foldRight[ScType](resultType){(clause: ScParameterClause, tp: ScType) => new ScMethodType(tp, clause.getSmartParameters, clause.isImplicit)(getProject, getResolveScope) } else new ScMethodType(resultType, Seq.empty, false)(getProject, getResolveScope) res.asInstanceOf[ScMethodType] } /** * Returns internal type with type parameters. */ def polymorphicType(result: Option[ScType] = None): ScType = { if (typeParameters.length == 0) methodType(result) else ScTypePolymorphicType(methodType(result), typeParameters.map(new TypeParameter(_))) } /** * Optional Type Element, denotion function's return type * May be omitted for non-recursive functions */ def returnTypeElement: Option[ScTypeElement] = { this match { case st: ScalaStubBasedElementImpl[_] => val stub = st.getStub if (stub != null) { return stub.asInstanceOf[ScFunctionStub].getReturnTypeElement } case _ => } findChild(classOf[ScTypeElement]) } def returnTypeIsDefined: Boolean = !definedReturnType.isEmpty def hasExplicitType = returnTypeElement.isDefined def removeExplicitType() { val colon = children.find(_.getNode.getElementType == ScalaTokenTypes.tCOLON) (colon, returnTypeElement) match { case (Some(first), Some(last)) => deleteChildRange(first, last) case _ => } } def paramClauses: ScParameters def parameterList: ScParameters = paramClauses // TODO merge def isProcedure = paramClauses.clauses.isEmpty def importantOrderFunction(): Boolean = false def returnType: TypeResult[ScType] = { if (importantOrderFunction()) { val parent = getParent val data = parent.getUserData(ScFunction.calculatedBlockKey) if (data != null) returnTypeInner else { val children = parent match { case stub: ScalaStubBasedElementImpl[_] if stub.getStub != null => import scala.collection.JavaConverters._ stub.getStub.getChildrenStubs.asScala.map(_.getPsi) case _ => parent.getChildren.toSeq } children.foreach { case fun: ScFunction if fun.importantOrderFunction() => ProgressManager.checkCanceled() fun.returnTypeInner case _ => } parent.putUserData(ScFunction.calculatedBlockKey, java.lang.Boolean.TRUE) returnTypeInner } } else returnTypeInner } def returnTypeInner: TypeResult[ScType] def declaredType: TypeResult[ScType] = wrap(returnTypeElement) flatMap (_.getType(TypingContext.empty)) def clauses: Option[ScParameters] = Some(paramClauses) def paramTypes: Seq[ScType] = parameters.map {_.getType(TypingContext.empty).getOrNothing} def effectiveParameterClauses: Seq[ScParameterClause] = { CachesUtil.get(this, CachesUtil.FUNCTION_EFFECTIVE_PARAMETER_CLAUSE_KEY, new CachesUtil.MyProvider(this, (f: ScFunction) => f.paramClauses.clauses ++ f.syntheticParamClause) (PsiModificationTracker.MODIFICATION_COUNT)) } private def syntheticParamClause: Option[ScParameterClause] = { val hasImplicit = clauses.exists(_.clauses.exists(_.isImplicit)) if (isConstructor) { containingClass match { case owner: ScTypeParametersOwner => if (hasImplicit) None else ScalaPsiUtil.syntheticParamClause(owner, paramClauses, classParam = false) case _ => None } } else { if (hasImplicit) None else ScalaPsiUtil.syntheticParamClause(this, paramClauses, classParam = false) } } def declaredElements = Seq(this) /** * Seek parameter with appropriate name in appropriate parameter clause. * @param name parameter name * @param clausePosition = -1, effective clause number, if -1 then parameter in any explicit? clause */ def getParamByName(name: String, clausePosition: Int = -1): Option[ScParameter] = { clausePosition match { case -1 => parameters.find { case param => ScalaPsiUtil.memberNamesEquals(param.name, name) || param.deprecatedName.exists(ScalaPsiUtil.memberNamesEquals(_, name)) } case i if i < 0 || i >= effectiveParameterClauses.length => None case _ => effectiveParameterClauses.apply(clausePosition).effectiveParameters.find { case param => ScalaPsiUtil.memberNamesEquals(param.name, name) || param.deprecatedName.exists(ScalaPsiUtil.memberNamesEquals(_, name)) } } } override def accept(visitor: ScalaElementVisitor) { visitor.visitFunction(this) } def getGetterOrSetterFunction: Option[ScFunction] = { containingClass match { case clazz: ScTemplateDefinition => if (name.endsWith("_=")) { clazz.functions.find(_.name == name.substring(0, name.length - 2)) } else if (!hasParameterClause) { clazz.functions.find(_.name == name + "_=") } else None case _ => None } } def isBridge: Boolean = { //todo: fix algorithm for annotation resolve to not resolve objects (if it's possible) //heuristic algorithm to avoid SOE in MixinNodes.build annotations.exists(annot => { annot.typeElement match { case s: ScSimpleTypeElement => s.reference match { case Some(ref) => ref.refName == "bridge" case _ => false } case _ => false } }) } def getTypeParameters: Array[PsiTypeParameter] = { val params = typeParameters val size = params.length val result = PsiTypeParameter.ARRAY_FACTORY.create(size) var i = 0 while (i < size) { result(i) = params(i).asInstanceOf[PsiTypeParameter] i += 1 } result } def getTypeParameterList = new FakePsiTypeParameterList(getManager, getLanguage, typeParameters.toArray, this) def hasTypeParameters = typeParameters.length > 0 def getParameterList: ScParameters = paramClauses private val functionWrapper: ConcurrentHashMap[(Boolean, Boolean, Option[PsiClass]), (Seq[ScFunctionWrapper], Long)] = new ConcurrentHashMap() private def isJavaVarargs: Boolean = { if (hasAnnotation("scala.annotation.varargs").isDefined) true else { superMethod match { case Some(f: ScFunction) => f.isJavaVarargs case Some(m: PsiMethod) => m.isVarArgs case _ => false } } } /** * @return Empty array, if containing class is null. */ def getFunctionWrappers(isStatic: Boolean, isInterface: Boolean, cClass: Option[PsiClass] = None): Seq[ScFunctionWrapper] = { val curModCount = getManager.getModificationTracker.getOutOfCodeBlockModificationCount val r = functionWrapper.get(isStatic, isInterface, cClass) if (r != null && r._2 == curModCount) { return r._1 } val buffer = new ArrayBuffer[ScFunctionWrapper] if (cClass != None || containingClass != null) { buffer += new ScFunctionWrapper(this, isStatic, isInterface, cClass) for { clause <- clauses first <- clause.clauses.headOption if first.hasRepeatedParam if isJavaVarargs } { buffer += new ScFunctionWrapper(this, isStatic, isInterface, cClass, isJavaVarargs = true) } if (!isConstructor) { for (i <- 0 until this.parameters.length if parameters(i).baseDefaultParam) { buffer += new ScFunctionWrapper(this, isStatic, isInterface, cClass, forDefault = Some(i + 1)) } } } val result: Seq[ScFunctionWrapper] = buffer.toSeq functionWrapper.put((isStatic, isInterface, cClass), (result, curModCount)) result } def parameters: Seq[ScParameter] = paramClauses.params override def getIcon(flags: Int) = Icons.FUNCTION def getReturnType: PsiType = { if (DumbService.getInstance(getProject).isDumb || !SyntheticClasses.get(getProject).isClassesRegistered) { return null //no resolve during dumb mode or while synthetic classes is not registered } CachesUtil.get( this, CachesUtil.PSI_RETURN_TYPE_KEY, new CachesUtil.MyProvider(this, {ic: ScFunction => ic.getReturnTypeImpl}) (PsiModificationTracker.MODIFICATION_COUNT) ) } private def getReturnTypeImpl: PsiType = { val tp = getType(TypingContext.empty).getOrAny tp match { case ScFunctionType(rt, _) => ScType.toPsi(rt, getProject, getResolveScope) case _ => ScType.toPsi(tp, getProject, getResolveScope) } } def superMethods: Seq[PsiMethod] = { val clazz = containingClass if (clazz != null) TypeDefinitionMembers.getSignatures(clazz).forName(ScalaPsiUtil.convertMemberName(name))._1. get(new PhysicalSignature(this, ScSubstitutor.empty)).getOrElse(return Seq.empty).supers. filter(_.info.isInstanceOf[PhysicalSignature]).map {_.info.asInstanceOf[PhysicalSignature].method} else Seq.empty } def superMethod: Option[PsiMethod] = superMethodAndSubstitutor.map(_._1) def superMethodAndSubstitutor: Option[(PsiMethod, ScSubstitutor)] = { val clazz = containingClass if (clazz != null) { val option = TypeDefinitionMembers.getSignatures(clazz).forName(name)._1. fastPhysicalSignatureGet(new PhysicalSignature(this, ScSubstitutor.empty)) if (option == None) return None option.get.primarySuper.filter(_.info.isInstanceOf[PhysicalSignature]). map(node => (node.info.asInstanceOf[PhysicalSignature].method, node.info.substitutor)) } else None } def superSignatures: Seq[Signature] = { val clazz = containingClass val s = new PhysicalSignature(this, ScSubstitutor.empty) if (clazz == null) return Seq(s) val t = TypeDefinitionMembers.getSignatures(clazz).forName(ScalaPsiUtil.convertMemberName(name))._1. fastPhysicalSignatureGet(s) match { case Some(x) => x.supers.map {_.info} case None => Seq[Signature]() } t } def superSignaturesIncludingSelfType: Seq[Signature] = { val clazz = containingClass val s = new PhysicalSignature(this, ScSubstitutor.empty) if (clazz == null) return Seq(s) val withSelf = clazz.selfType != None if (withSelf) { val signs = TypeDefinitionMembers.getSelfTypeSignatures(clazz).forName(ScalaPsiUtil.convertMemberName(name))._1 signs.fastPhysicalSignatureGet(s) match { case Some(x) if x.info.namedElement == this => x.supers.map { _.info } case Some(x) => x.supers.filter {_.info.namedElement != this }.map { _.info } :+ x.info case None => signs.get(s) match { case Some(x) if x.info.namedElement == this => x.supers.map { _.info } case Some(x) => x.supers.filter {_.info.namedElement != this }.map { _.info } :+ x.info case None => Seq.empty } } } else { TypeDefinitionMembers.getSignatures(clazz).forName(ScalaPsiUtil.convertMemberName(name))._1. fastPhysicalSignatureGet(s) match { case Some(x) => x.supers.map { _.info } case None => Seq.empty } } } override def getNameIdentifier: PsiIdentifier = new JavaIdentifier(nameId) def findDeepestSuperMethod: PsiMethod = { val s = superMethods if (s.length == 0) null else s(s.length - 1) } def getReturnTypeElement = null def findSuperMethods(parentClass: PsiClass) = PsiMethod.EMPTY_ARRAY def findSuperMethods(checkAccess: Boolean) = PsiMethod.EMPTY_ARRAY def findSuperMethods = superMethods.toArray // TODO which other xxxSuperMethods can/should be implemented? def findDeepestSuperMethods = PsiMethod.EMPTY_ARRAY def getReturnTypeNoResolve: PsiType = PsiType.VOID def getPom = null def findSuperMethodSignaturesIncludingStatic(checkAccess: Boolean) = new util.ArrayList[MethodSignatureBackedByPsiMethod]() def getSignature(substitutor: PsiSubstitutor) = MethodSignatureBackedByPsiMethod.create(this, substitutor) //todo implement me! def isVarArgs = false def isConstructor = name == "this" def getBody: PsiCodeBlock = null def getThrowsList = new FakePsiReferenceList(getManager, getLanguage, Role.THROWS_LIST) { override def getReferenceElements: Array[PsiJavaCodeReferenceElement] = { getReferencedTypes.map { tp => PsiElementFactory.SERVICE.getInstance(getProject).createReferenceElementByType(tp) } } override def getReferencedTypes: Array[PsiClassType] = { hasAnnotation("scala.throws") match { case Some(annotation) => annotation.constructor.args.map(_.exprs).getOrElse(Seq.empty).flatMap { expr => expr.getType(TypingContext.empty) match { case Success(ScParameterizedType(des, Seq(arg)), _) => ScType.extractClass(des) match { case Some(clazz) if clazz.qualifiedName == "java.lang.Class" => ScType.toPsi(arg, getProject, getResolveScope) match { case c: PsiClassType => Seq(c) case _ => Seq.empty } case _ => Seq.empty } case _ => Seq.empty } }.toArray case _ => PsiClassType.EMPTY_ARRAY } } } def getType(ctx: TypingContext): TypeResult[ScType] = { returnType match { case Success(tp: ScType, _) => var res: TypeResult[ScType] = Success(tp, None) var i = paramClauses.clauses.length - 1 while (i >= 0) { val cl = paramClauses.clauses.apply(i) val paramTypes = cl.parameters.map(_.getType(ctx)) res match { case Success(t: ScType, _) => res = collectFailures(paramTypes, Nothing)(ScFunctionType(t, _)(getProject, getResolveScope)) case _ => } i = i - 1 } res case x => x } } override protected def isSimilarMemberForNavigation(m: ScMember, strictCheck: Boolean) = m match { case f: ScFunction => f.name == name && { if (strictCheck) new PhysicalSignature(this, ScSubstitutor.empty). paramTypesEquiv(new PhysicalSignature(f, ScSubstitutor.empty)) else true } case _ => false } def hasAssign = getNode.getChildren(TokenSet.create(ScalaTokenTypes.tASSIGN)).size > 0 def getHierarchicalMethodSignature: HierarchicalMethodSignature = { new HierarchicalMethodSignatureImpl(getSignature(PsiSubstitutor.EMPTY)) } override def isDeprecated = { hasAnnotation("scala.deprecated") != None || hasAnnotation("java.lang.Deprecated") != None } override def getName = { val res = if (isConstructor && getContainingClass != null) getContainingClass.getName else super.getName if (JavaLexer.isKeyword(res, LanguageLevel.HIGHEST)) "_mth" + res else res } override def setName(name: String): PsiElement = { if (isConstructor) this else super.setName(name) } override def getOriginalElement: PsiElement = { val ccontainingClass = containingClass if (ccontainingClass == null) return this val originalClass: PsiClass = ccontainingClass.getOriginalElement.asInstanceOf[PsiClass] if (ccontainingClass eq originalClass) return this if (!originalClass.isInstanceOf[ScTypeDefinition]) return this val c = originalClass.asInstanceOf[ScTypeDefinition] val membersIterator = c.members.iterator val buf: ArrayBuffer[ScMember] = new ArrayBuffer[ScMember] while (membersIterator.hasNext) { val member = membersIterator.next() if (isSimilarMemberForNavigation(member, strictCheck = false)) buf += member } if (buf.length == 0) this else if (buf.length == 1) buf(0) else { val filter = buf.filter(isSimilarMemberForNavigation(_, strictCheck = true)) if (filter.length == 0) buf(0) else filter(0) } } //Why not to use default value? It's not working in Scala... def getTypeNoImplicits(ctx: TypingContext): TypeResult[ScType] = getTypeNoImplicits(ctx, returnType) def getTypeNoImplicits(ctx: TypingContext, rt: TypeResult[ScType]): TypeResult[ScType] = { collectReverseParamTypesNoImplicits match { case Some(params) => val project = getProject val resolveScope = getResolveScope rt.map(params.foldLeft(_)((res, params) => ScFunctionType(res, params)(project, resolveScope))) case None => Failure("no params", Some(this)) } } @volatile private var collectReverseParamTypesNoImplicitsCache: Option[Seq[Seq[ScType]]] = null @volatile private var collectReverseParamTypesNoImplicitsModCount: Long = 0L def collectReverseParamTypesNoImplicits: Option[Seq[Seq[ScType]]] = { def calc: Option[Seq[Seq[ScType]]] = { var i = paramClauses.clauses.length - 1 val res: ArrayBuffer[Seq[ScType]] = ArrayBuffer.empty while (i >= 0) { val cl = paramClauses.clauses.apply(i) if (!cl.isImplicit) { val paramTypes: Seq[TypeResult[ScType]] = cl.parameters.map(_.getType(TypingContext.empty)) if (paramTypes.exists(_.isEmpty)) return None res += paramTypes.map(_.get) } i = i - 1 } Some(res.toSeq) } val count = getManager.getModificationTracker.getModificationCount var res = collectReverseParamTypesNoImplicitsCache if (res != null && count == collectReverseParamTypesNoImplicitsModCount) return collectReverseParamTypesNoImplicitsCache res = calc collectReverseParamTypesNoImplicitsModCount = count collectReverseParamTypesNoImplicitsCache = res res } } object ScFunction { object Name { val Apply = "apply" val Update = "update" val Unapply = "unapply" val UnapplySeq = "unapplySeq" val Foreach = "foreach" val Map = "map" val FlatMap = "flatMap" val Filter = "filter" val WithFilter = "withFilter" val Unapplies: Set[String] = Set(Unapply, UnapplySeq) val ForComprehensions: Set[String] = Set(Foreach, Map, FlatMap, Filter, WithFilter) val Special: Set[String] = Set(Apply, Update) ++ Unapplies ++ ForComprehensions } /** Is this function sometimes invoked without it's name appearing at the call site? */ def isSpecial(name: String): Boolean = Name.Special(name) private val calculatedBlockKey: Key[java.lang.Boolean] = Key.create("calculated.function.returns.block") @tailrec def getCompoundCopy(pTypes: List[List[ScType]], tParams: List[TypeParameter], rt: ScType, fun: ScFunction): ScFunction = { fun match { case light: ScLightFunctionDeclaration => getCompoundCopy(pTypes, tParams, rt, light.fun) case light: ScLightFunctionDefinition => getCompoundCopy(pTypes, tParams, rt, light.fun) case decl: ScFunctionDeclaration => new ScLightFunctionDeclaration(pTypes, tParams, rt, decl) case definition: ScFunctionDefinition => new ScLightFunctionDefinition(pTypes, tParams, rt, definition) } } }
triggerNZ/intellij-scala
src/org/jetbrains/plugins/scala/lang/psi/api/statements/ScFunction.scala
Scala
apache-2.0
27,807
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package Yosemite.framework.master.ui import akka.actor._ import javax.servlet.http.HttpServletRequest import org.eclipse.jetty.server.{Handler, Server} import scala.concurrent.duration.Duration import Yosemite.{Logging, Utils} import Yosemite.ui.JettyUtils import Yosemite.ui.JettyUtils._ /** * Web UI server for the standalone master. */ private[Yosemite] class MasterWebUI(masterActorRef_ : ActorRef, requestedPort: Int, bDNS: Boolean = true) extends Logging { implicit val timeout = Duration.create( System.getProperty("Yosemite.akka.askTimeout", "10").toLong, "seconds") val port = requestedPort if (bDNS == false) { host = Utils.localIpAddress } val masterActorRef = masterActorRef_ val coflowPage = new CoflowPage(this) val indexPage = new IndexPage(this) val handlers = Array[(String, Handler)]( ("/static", createStaticHandler(MasterWebUI.STATIC_RESOURCE_DIR)), ("/coflow/json", (request: HttpServletRequest) => coflowPage.renderJson(request)), ("/coflow", (request: HttpServletRequest) => coflowPage.render(request)), ("/json", (request: HttpServletRequest) => indexPage.renderJson(request)), ("*", (request: HttpServletRequest) => indexPage.render(request)) ) var host = Utils.localHostName() var server: Option[Server] = None var boundPort: Option[Int] = None def start() { try { val (srv, bPort) = JettyUtils.startJettyServer("0.0.0.0", port, handlers) server = Some(srv) boundPort = Some(bPort) logInfo("Started Master web UI at http://%s:%d".format(host, boundPort.get)) } catch { case e: Exception => logError("Failed to create Master JettyUtils", e) System.exit(1) } } def stop() { server.foreach(_.stop()) } } private[Yosemite] object MasterWebUI { val STATIC_RESOURCE_DIR = "Yosemite/ui/static" }
zhanghan1990/Yosemite
core/src/main/scala/Yosemite/framework/master/ui/MasterWebUI.scala
Scala
apache-2.0
2,654
/* * The MIT License (MIT) * * Copyright (c) 2016 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package algolia.dsl import algolia.AlgoliaDsl._ import algolia.AlgoliaTest import algolia.http._ import algolia.objects.{Acl, ApiKey} import org.json4s.Formats import org.json4s.native.JsonMethods._ import org.json4s.native.Serialization._ import scala.language.postfixOps class ApiKeysTest extends AlgoliaTest { implicit val formats: Formats = org.json4s.DefaultFormats + new AclSerializer describe("global keys") { describe("get a key") { it("should get a key") { get key "keyName" } it("should call the API") { (get key "keyName").build() should be( HttpPayload( GET, List("1", "keys", "keyName"), isSearch = false, requestOptions = None ) ) } } describe("get all keys") { it("should get all keys") { list keys } it("should call the API") { list.keys.build() should be( HttpPayload( GET, List("1", "keys"), isSearch = false, requestOptions = None ) ) } } describe("add a key") { it("should add a key") { add key ApiKey() } it("should call the API") { (add key ApiKey(validity = Some(10))).build() should be( HttpPayload( POST, List("1", "keys"), body = Some("""{"validity":10}"""), isSearch = false, requestOptions = None ) ) } } describe("delete a key") { it("should a key") { delete key "keyName" } it("should call the API") { (delete key "keyName").build() should be( HttpPayload( DELETE, List("1", "keys", "keyName"), isSearch = false, requestOptions = None ) ) } } describe("update key") { it("should update a key") { update key "keyName" `with` ApiKey() } it("should call the API") { (update key "keyName" `with` ApiKey(validity = Some(10))) .build() should be( HttpPayload( PUT, List("1", "keys", "keyName"), body = Some("""{"validity":10}"""), isSearch = false, requestOptions = None ) ) } } } describe("ApiKey serialization/deserialization") { val json = """{ | "acl":[ | "search", | "addObject" | ] |}""".stripMargin it("should deserialize json") { inside(parse(json).extract[ApiKey]) { case a: ApiKey => a.acl should be(Some(Seq(Acl.search, Acl.addObject))) } } it("should serialize json") { val a = ApiKey( acl = Some(Seq(Acl.search, Acl.addObject)) ) writePretty(a) should be(json) } } }
algolia/algoliasearch-client-scala
src/test/scala/algolia/dsl/ApiKeysTest.scala
Scala
mit
4,089
package enigma import org.scalacheck._ import Prop._ object PlugboardSpec extends Properties("plugboard") { val p1 = Plugboard(Alphabet.empty) val p2 = Plugboard(Alphabet.shuffled) val alpha = Gen.choose('A','Z') property("identity plugboard") = forAll(alpha){ (c: Char) => p1.transform(c) == c } property("bijective resolution") = forAll(alpha){ (c: Char) => val a: Char = p2.transform(c) val b: Char = p2.transform(a) b == c } }
timperrett/enigma
src/test/scala/PlugboardSpec.scala
Scala
apache-2.0
465
package com.arcusys.learn.models.request import com.arcusys.learn.liferay.permission.PermissionCredentials import com.arcusys.learn.service.util.{ AntiSamyHelper, Parameter } import org.scalatra.ScalatraBase import scala.util.Try object QuestionRequest extends BaseRequest { val NewCourseId = "newCourseID" val CategoryId = "categoryID" val CategoryIds = "categoryIDs" val Id = "id" val QuestionType = "questionType" val Title = "title" val Text = "text" val ExplanationText = "explanationText" val RightAnswerText = "rightAnswerText" val WrongAnswerText = "wrongAnswerText" val Force = "forceCorrectCount" val Case = "isCaseSensitive" val Answers = "answers" val Index = "index" val ParentId = "parentID" val QuestionIds = "questionIDs" def apply(scalatra: ScalatraBase) = new Model(scalatra) class Model(scalatra: ScalatraBase) extends BaseCollectionFilteredRequestModel(scalatra) { implicit val httpRequest = scalatra.request def action = QuestionActionType.withName(Parameter(Action).required.toUpperCase) def id = Parameter(Id).intRequired def idOption = Parameter(Id).intOption def courseId = Parameter(CourseId).intOption def newCourseId = Parameter(NewCourseId).intOption def questionType = Parameter(QuestionType).intRequired def categoryId = Parameter(CategoryId).intOption def title = AntiSamyHelper.sanitize(Parameter(Title).required) def text = AntiSamyHelper.sanitize(Parameter(Text).withDefault("")) def explanationText = AntiSamyHelper.sanitize(Parameter(ExplanationText).withDefault("")) def rightAnswerText = AntiSamyHelper.sanitize(Parameter(RightAnswerText).withDefault("")) def wrongAnswerText = AntiSamyHelper.sanitize(Parameter(WrongAnswerText).withDefault("")) def forceCorrectCount = Parameter(Force).booleanRequired def isCaseSensitive = Parameter(Case).booleanRequired def answers = Parameter(Answers).withDefault("[]") def parentId = Parameter(ParentId).intOption def index = Parameter(Index).intRequired def categoryIds = Parameter(CategoryIds).multiWithEmpty.map(x => Try(x.toInt).get) def questionIds = Parameter(QuestionIds).multiWithEmpty.map(x => Try(x.toInt).get) } }
icacic/Valamis
learn-portlet/src/main/scala/com/arcusys/learn/models/request/QuestionRequest.scala
Scala
gpl-3.0
2,252
// timber -- Copyright 2012-2021 -- Justin Patterson // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.scalawag.timber.backend.receiver import org.scalawag.timber.api.Entry import org.scalawag.timber.backend.InternalLogger import org.scalawag.timber.backend.receiver.buffering.{ImmediateFlushing, PeriodicFlushing} import org.scalawag.timber.backend.receiver.concurrency.{Locking, Queueing} import sun.misc.{Signal, SignalHandler} import scala.concurrent.duration.FiniteDuration /** Marks a class that is capable of receiving [[Entry entries]] and doing something interesting with them. What * exactly it does is up to the implementation, but common behaviors are writing to a local log file or sending * to a log aggregation service. */ trait Receiver { /** Receives an [[Entry]] for processing. There is no initialization method for receivers, so this method must * handle resource initialization on the first call after construction or after closure. * * @param entry the entry being received by this receiver */ def receive(entry: Entry): Unit /** Tells this receiver to flush any buffered entries that it has received but not yet fully processed. This makes * it possible for this receiver to improve performance by batching I/O work. */ def flush(): Unit /** Closes the receiver. This means that the resources held by this receiver should be released in preparation for * it being decommissioned. This usually happens before system shutdown, but it does not necessarily mean that this * receiver will not receive any more entries. Receviers can be closed simply to release file system or network * resources. * * This method must handle any flushing that is required prior to any resource deallocation. Timber will not * necessarily call `flush()` before `close()`. */ def close(): Unit def flushImmediately: Receiver = ImmediateFlushing(this) def flushAtLeastEvery(duration: FiniteDuration): Receiver = PeriodicFlushing(this, duration) def withLocking: Receiver = Locking(this) def withQueueing: Receiver = Queueing(this) } /** Provides methods for telling timber how to manage your Receivers. */ object Receiver { private[this] var closeOnShutdownReceivers: Set[Receiver] = Set.empty private[this] var shutdownHookInstalled = false /** Registers [[Receiver receivers]] to be closed at system shutdown. This uses the Java runtime's * [[java.lang.Runtime#addShutdownHook addShutdownHook]] which only executes during certain system shutdown * scenarios. * * Calling this method multiple times with the same receiver has no effect beyond calling it once. * * @param receivers a set of receivers to attempt to close on normal system shutdown */ def closeOnShutdown(receivers: Receiver*): Unit = { if (!shutdownHookInstalled) { val runnable = new Runnable { override def run(): Unit = { closeOnShutdownReceivers foreach { er => try { er.close() } catch { // $COVERAGE-OFF$ case ex: Exception => InternalLogger.error(s"failed to close entry receiver ($er) at shutdown: $ex") // $COVERAGE-ON$ } } } } Runtime.getRuntime.addShutdownHook(new Thread(runnable, "Timber-ReceiverManager-ShutdownHook")) } closeOnShutdownReceivers ++= receivers } // TODO: This is non-standard Java. We should maybe protect it with reflection to allow this to run on non-Oracle // TODO: JVMs. Or maybe you just can't use this call except on Oracle JVMs. private[this] var closeOnSignalReceivers: Map[String, Set[Receiver]] = Map.empty /** Registers [[Receiver receivers]] to be closed when the JVM receives a certain signal. This is intended for * integration with tools like [[https://github.com/logrotate/logrotate logrotate]] that are capable of sending * signals during rotation to tell the logging process to close and reopen its log files to prevent the process * from hanging on to an open file handle and therefore continuing to log to a log file that has been rotated out. * * Calling this method multiple times with the same receiver and signal combination has no effect beyond calling * it once with that combination. All receivers passed to calls for the same signal are accumulated and closed * when that signal is received. There is no way to retract the registration. * * @param signal the signal to listen for (I recommend "HUP") * @param receivers the receivers to close when the signal is received */ def closeOnSignal(signal: String, receivers: Receiver*): Unit = { // Ony install the signal handler once. After that, just add the receivers to the set. if (!closeOnSignalReceivers.contains(signal)) { Signal.handle( new Signal(signal), new SignalHandler { override def handle(s: Signal): Unit = { closeOnSignalReceivers(signal) foreach { er => try { er.close() } catch { case ex: Exception => InternalLogger.error(s"failed to close receiver ($er) on signal $signal: $ex") } } } } ) } val newReceiversSet = closeOnSignalReceivers.get(signal).getOrElse(Set.empty) ++ receivers closeOnSignalReceivers += signal -> newReceiversSet } }
scalawag/timber
timber-backend/src/main/scala/org/scalawag/timber/backend/receiver/Receiver.scala
Scala
apache-2.0
6,010
import org.scalatest._ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import rpm4s.data._ class StatSpec extends AnyFlatSpec with Matchers with ScalaCheckPropertyChecks { "Stat" should "be parsed correctly" in { val stat = Stat.fromShort(16877).get stat.tpe shouldBe Stat.FileType.Directory stat.permsString shouldBe "rwxr-xr-x" } "Stat.fromShort" should "not allow invalid values" in { Stat.fromShort(0) shouldBe None } }
lucidd/rpm4s
shared/src/test/scala/StatSpec.scala
Scala
mit
553
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package models.renewal import jto.validation.forms.UrlFormEncoded import jto.validation.{Invalid, Path, Rule, VA, Valid, ValidationError, Write} import models.Country import org.scalatestplus.play.PlaySpec import play.api.libs.json.{JsSuccess, Json} class SendTheLargestAmountsOfMoneySpec extends PlaySpec { "SendTheLargestAmountsOfMoney" must { val rule: Rule[UrlFormEncoded, SendTheLargestAmountsOfMoney] = implicitly val write: Write[SendTheLargestAmountsOfMoney, UrlFormEncoded] = implicitly "roundtrip through json" in { val model: SendTheLargestAmountsOfMoney = SendTheLargestAmountsOfMoney(Seq(Country("United Kingdom", "GB"))) Json.fromJson[SendTheLargestAmountsOfMoney](Json.toJson(model)) mustEqual JsSuccess(model) } "correctly parse the json if country_1 and country_3 fields provided" in { val json = Json.obj("country_1" -> "GB", "country_3" -> "IN") val expected = SendTheLargestAmountsOfMoney(Seq(Country("United Kingdom", "GB"), Country("India", "IN"))) Json.fromJson[SendTheLargestAmountsOfMoney](json) mustEqual JsSuccess(expected) } "roundtrip through forms" in { val model: SendTheLargestAmountsOfMoney = SendTheLargestAmountsOfMoney(Seq(Country("United Kingdom", "GB"))) rule.validate(write.writes(model)) mustEqual Valid(model) } "fail to validate when there are no countries" in { val form: UrlFormEncoded = Map( "largestAmountsOfMoney" -> Seq.empty ) rule.validate(form) mustEqual Invalid( Seq((Path \\ "largestAmountsOfMoney") -> Seq(ValidationError("error.required.renewal.largest.amounts.country"))) ) } "fail to validate when there are more than 3 countries" in { // scalastyle:off magic.number val form: UrlFormEncoded = Map( "largestAmountsOfMoney[]" -> Seq.fill(4)("GB") ) rule.validate(form) mustEqual Invalid( Seq((Path \\ "largestAmountsOfMoney") -> Seq(ValidationError("error.maxLength", 3))) ) } } "SendTheLargestAmountsOfMoney Form Writes" when { "an item is repeated" must { "serialise all items correctly" in { SendTheLargestAmountsOfMoney.formW.writes(SendTheLargestAmountsOfMoney(List( Country("Country2", "BB"), Country("Country1", "AA"), Country("Country1", "AA") ))) must be ( Map( "largestAmountsOfMoney[0]" -> List("BB"), "largestAmountsOfMoney[1]" -> List("AA"), "largestAmountsOfMoney[2]" -> List("AA") ) ) } } } "SendTheLargestAmountsOfMoney Form Reads" when { "all countries are valid" must { "Successfully read from the form" in { SendTheLargestAmountsOfMoney.formR.validate( Map( "largestAmountsOfMoney[0]" -> Seq("GB"), "largestAmountsOfMoney[1]" -> Seq("MK"), "largestAmountsOfMoney[2]" -> Seq("JO") ) ) must be(Valid(SendTheLargestAmountsOfMoney(Seq( Country("United Kingdom", "GB"), Country("Macedonia, the Former Yugoslav Republic of", "MK"), Country("Jordan", "JO") )))) } } "the second country is invalid" must { "fail validation" in { val x: VA[SendTheLargestAmountsOfMoney] = SendTheLargestAmountsOfMoney.formR.validate( Map( "largestAmountsOfMoney[0]" -> Seq("GB"), "largestAmountsOfMoney[1]" -> Seq("hjjkhjkjh"), "largestAmountsOfMoney[2]" -> Seq("MK") ) ) x must be (Invalid(Seq((Path \\ "largestAmountsOfMoney" \\ 1) -> Seq(ValidationError("error.invalid.country"))))) } } } }
hmrc/amls-frontend
test/models/renewal/SendTheLargestAmountsOfMoneySpec.scala
Scala
apache-2.0
4,332
/* * Copyright 2011-2017 Chris de Vreeze * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.cdevreeze.yaidom.core import org.scalatest.funsuite.AnyFunSuite /** * EName test case. * * @author Chris de Vreeze */ class ENameTest extends AnyFunSuite { private val bookstoreNs = "http://bookstore" test("testNoNamespaceName") { val ename = EName(None, "Bookstore") assertResult("Bookstore") { ename.localPart } assertResult(None) { ename.namespaceUriOption } val ename2 = EName("Bookstore") assertResult("Bookstore") { ename2.localPart } assertResult(None) { ename2.namespaceUriOption } assertResult(ename) { ename2 } assertResult(ename.hashCode) { ename2.hashCode } val ename3 = EName.fromUriQualifiedNameString("Q{}Bookstore") assertResult("Bookstore") { ename3.localPart } assertResult(None) { ename3.namespaceUriOption } assertResult(ename) { ename3 } assertResult(ename.hashCode) { ename3.hashCode } assertResult("Q{}Bookstore") { ename3.toUriQualifiedNameString } val ename4 = EName("Bookstore") assertResult("Bookstore") { ename4.localPart } assertResult(None) { ename4.namespaceUriOption } assertResult(ename) { ename4 } assertResult(ename.hashCode) { ename4.hashCode } val ename5 = EName("Bookstore") assertResult("Bookstore") { ename5.localPart } assertResult(None) { ename5.namespaceUriOption } assertResult(ename) { ename5 } assertResult(ename.hashCode) { ename5.hashCode } val ename6 = EName(" Bookstore ") assertResult(ename) { ename6 } intercept[Exception] { EName(null) } intercept[Exception] { EName("").validated } intercept[Exception] { EName.parse("").validated } val enOption = ename match { case en@EName(None, localPart) => Some(en) case _ => None } assertResult(Some(ename)) { enOption } } test("testNameInNamespace") { val ename = EName(bookstoreNs, "Bookstore") assertResult("Bookstore") { ename.localPart } assertResult(Some(bookstoreNs)) { ename.namespaceUriOption } val ename2: EName = EName(bookstoreNs, "Bookstore") assertResult("Bookstore") { ename2.localPart } assertResult(Some(bookstoreNs)) { ename2.namespaceUriOption } assertResult(ename) { ename2 } assertResult(ename.hashCode) { ename2.hashCode } val ename3: EName = EName(Some(bookstoreNs), "Bookstore") assertResult("Bookstore") { ename3.localPart } assertResult(Some(bookstoreNs)) { ename3.namespaceUriOption } assertResult(ename) { ename3 } assertResult(ename.hashCode) { ename3.hashCode } val ename4 = EName(s"{$bookstoreNs}Bookstore") assertResult("Bookstore") { ename4.localPart } assertResult(Some(bookstoreNs)) { ename4.namespaceUriOption } assertResult(ename) { ename4 } assertResult(ename.hashCode) { ename4.hashCode } val ename5 = EName.fromUriQualifiedNameString(s"Q{$bookstoreNs}Bookstore") assertResult("Bookstore") { ename5.localPart } assertResult(Some(bookstoreNs)) { ename5.namespaceUriOption } assertResult(ename) { ename5 } assertResult(ename.hashCode) { ename5.hashCode } assertResult(s"Q{$bookstoreNs}Bookstore") { ename5.toUriQualifiedNameString } val ename6 = EName(s" {$bookstoreNs}Bookstore ") assertResult(ename) { ename6 } intercept[Exception] { EName(null.asInstanceOf[Option[String]], null) } intercept[Exception] { EName(null.asInstanceOf[Option[String]], "b") } intercept[Exception] { EName("a", null) } intercept[Exception] { EName("", "").validated } intercept[Exception] { EName("", "b").validated } intercept[Exception] { EName("a", "").validated } intercept[Exception] { EName.parse("{}").validated } intercept[Exception] { EName.parse("{}x").validated } intercept[Exception] { EName("a", "b:c").validated } intercept[Exception] { EName.parse("a{").validated } intercept[Exception] { EName.parse("}b").validated } intercept[Exception] { EName.parse(s"{$bookstoreNs} Bookstore").validated } val enOption = ename match { case en@EName(Some(ns), localPart) => Some(en) case _ => None } assertResult(Some(ename)) { enOption } } }
dvreeze/yaidom
jvm/src/test/scala/eu/cdevreeze/yaidom/core/ENameTest.scala
Scala
apache-2.0
5,305
package service import util.Directory._ import util.ControlUtil._ import SystemSettingsService._ import javax.servlet.http.HttpServletRequest trait SystemSettingsService { def baseUrl(implicit request: HttpServletRequest): String = loadSystemSettings().baseUrl(request) def saveSystemSettings(settings: SystemSettings): Unit = { defining(new java.util.Properties()){ props => settings.baseUrl.foreach(x => props.setProperty(BaseURL, x.replaceFirst("/\\Z", ""))) settings.information.foreach(x => props.setProperty(Information, x)) props.setProperty(AllowAccountRegistration, settings.allowAccountRegistration.toString) props.setProperty(AllowAnonymousAccess, settings.allowAnonymousAccess.toString) props.setProperty(IsCreateRepoOptionPublic, settings.isCreateRepoOptionPublic.toString) props.setProperty(Gravatar, settings.gravatar.toString) props.setProperty(Notification, settings.notification.toString) props.setProperty(Ssh, settings.ssh.toString) settings.sshPort.foreach(x => props.setProperty(SshPort, x.toString)) if(settings.notification) { settings.smtp.foreach { smtp => props.setProperty(SmtpHost, smtp.host) smtp.port.foreach(x => props.setProperty(SmtpPort, x.toString)) smtp.user.foreach(props.setProperty(SmtpUser, _)) smtp.password.foreach(props.setProperty(SmtpPassword, _)) smtp.ssl.foreach(x => props.setProperty(SmtpSsl, x.toString)) smtp.fromAddress.foreach(props.setProperty(SmtpFromAddress, _)) smtp.fromName.foreach(props.setProperty(SmtpFromName, _)) } } props.setProperty(LdapAuthentication, settings.ldapAuthentication.toString) if(settings.ldapAuthentication){ settings.ldap.map { ldap => props.setProperty(LdapHost, ldap.host) ldap.port.foreach(x => props.setProperty(LdapPort, x.toString)) ldap.bindDN.foreach(x => props.setProperty(LdapBindDN, x)) ldap.bindPassword.foreach(x => props.setProperty(LdapBindPassword, x)) props.setProperty(LdapBaseDN, ldap.baseDN) props.setProperty(LdapUserNameAttribute, ldap.userNameAttribute) ldap.additionalFilterCondition.foreach(x => props.setProperty(LdapAdditionalFilterCondition, x)) ldap.fullNameAttribute.foreach(x => props.setProperty(LdapFullNameAttribute, x)) ldap.mailAttribute.foreach(x => props.setProperty(LdapMailAddressAttribute, x)) ldap.tls.foreach(x => props.setProperty(LdapTls, x.toString)) ldap.ssl.foreach(x => props.setProperty(LdapSsl, x.toString)) ldap.keystore.foreach(x => props.setProperty(LdapKeystore, x)) } } using(new java.io.FileOutputStream(GitBucketConf)){ out => props.store(out, null) } } } def loadSystemSettings(): SystemSettings = { defining(new java.util.Properties()){ props => if(GitBucketConf.exists){ using(new java.io.FileInputStream(GitBucketConf)){ in => props.load(in) } } SystemSettings( getOptionValue[String](props, BaseURL, None).map(x => x.replaceFirst("/\\Z", "")), getOptionValue[String](props, Information, None), getValue(props, AllowAccountRegistration, false), getValue(props, AllowAnonymousAccess, true), getValue(props, IsCreateRepoOptionPublic, true), getValue(props, Gravatar, true), getValue(props, Notification, false), getValue(props, Ssh, false), getOptionValue(props, SshPort, Some(DefaultSshPort)), if(getValue(props, Notification, false)){ Some(Smtp( getValue(props, SmtpHost, ""), getOptionValue(props, SmtpPort, Some(DefaultSmtpPort)), getOptionValue(props, SmtpUser, None), getOptionValue(props, SmtpPassword, None), getOptionValue[Boolean](props, SmtpSsl, None), getOptionValue(props, SmtpFromAddress, None), getOptionValue(props, SmtpFromName, None))) } else { None }, getValue(props, LdapAuthentication, false), if(getValue(props, LdapAuthentication, false)){ Some(Ldap( getValue(props, LdapHost, ""), getOptionValue(props, LdapPort, Some(DefaultLdapPort)), getOptionValue(props, LdapBindDN, None), getOptionValue(props, LdapBindPassword, None), getValue(props, LdapBaseDN, ""), getValue(props, LdapUserNameAttribute, ""), getOptionValue(props, LdapAdditionalFilterCondition, None), getOptionValue(props, LdapFullNameAttribute, None), getOptionValue(props, LdapMailAddressAttribute, None), getOptionValue[Boolean](props, LdapTls, None), getOptionValue[Boolean](props, LdapSsl, None), getOptionValue(props, LdapKeystore, None))) } else { None } ) } } } object SystemSettingsService { import scala.reflect.ClassTag case class SystemSettings( baseUrl: Option[String], information: Option[String], allowAccountRegistration: Boolean, allowAnonymousAccess: Boolean, isCreateRepoOptionPublic: Boolean, gravatar: Boolean, notification: Boolean, ssh: Boolean, sshPort: Option[Int], smtp: Option[Smtp], ldapAuthentication: Boolean, ldap: Option[Ldap]){ def baseUrl(request: HttpServletRequest): String = baseUrl.getOrElse { defining(request.getRequestURL.toString){ url => url.substring(0, url.length - (request.getRequestURI.length - request.getContextPath.length)) } }.stripSuffix("/") } case class Ldap( host: String, port: Option[Int], bindDN: Option[String], bindPassword: Option[String], baseDN: String, userNameAttribute: String, additionalFilterCondition: Option[String], fullNameAttribute: Option[String], mailAttribute: Option[String], tls: Option[Boolean], ssl: Option[Boolean], keystore: Option[String]) case class Smtp( host: String, port: Option[Int], user: Option[String], password: Option[String], ssl: Option[Boolean], fromAddress: Option[String], fromName: Option[String]) val DefaultSshPort = 29418 val DefaultSmtpPort = 25 val DefaultLdapPort = 389 private val BaseURL = "base_url" private val Information = "information" private val AllowAccountRegistration = "allow_account_registration" private val AllowAnonymousAccess = "allow_anonymous_access" private val IsCreateRepoOptionPublic = "is_create_repository_option_public" private val Gravatar = "gravatar" private val Notification = "notification" private val Ssh = "ssh" private val SshPort = "ssh.port" private val SmtpHost = "smtp.host" private val SmtpPort = "smtp.port" private val SmtpUser = "smtp.user" private val SmtpPassword = "smtp.password" private val SmtpSsl = "smtp.ssl" private val SmtpFromAddress = "smtp.from_address" private val SmtpFromName = "smtp.from_name" private val LdapAuthentication = "ldap_authentication" private val LdapHost = "ldap.host" private val LdapPort = "ldap.port" private val LdapBindDN = "ldap.bindDN" private val LdapBindPassword = "ldap.bind_password" private val LdapBaseDN = "ldap.baseDN" private val LdapUserNameAttribute = "ldap.username_attribute" private val LdapAdditionalFilterCondition = "ldap.additional_filter_condition" private val LdapFullNameAttribute = "ldap.fullname_attribute" private val LdapMailAddressAttribute = "ldap.mail_attribute" private val LdapTls = "ldap.tls" private val LdapSsl = "ldap.ssl" private val LdapKeystore = "ldap.keystore" private def getValue[A: ClassTag](props: java.util.Properties, key: String, default: A): A = defining(props.getProperty(key)){ value => if(value == null || value.isEmpty) default else convertType(value).asInstanceOf[A] } private def getOptionValue[A: ClassTag](props: java.util.Properties, key: String, default: Option[A]): Option[A] = defining(props.getProperty(key)){ value => if(value == null || value.isEmpty) default else Some(convertType(value)).asInstanceOf[Option[A]] } private def convertType[A: ClassTag](value: String) = defining(implicitly[ClassTag[A]].runtimeClass){ c => if(c == classOf[Boolean]) value.toBoolean else if(c == classOf[Int]) value.toInt else value } // // TODO temporary flag // val enablePluginSystem = Option(System.getProperty("enable.plugin")).getOrElse("false").toBoolean }
mqshen/gitbucketTest
src/main/scala/service/SystemSettingsService.scala
Scala
apache-2.0
8,643
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql.parsers import com.github.mauricio.async.db.postgresql.messages.backend.{ServerMessage, NoticeMessage} import java.nio.charset.Charset class NoticeParser(charset: Charset) extends InformationParser(charset) { def createMessage(fields: Map[Char, String]): ServerMessage = new NoticeMessage(fields) }
outbrain/postgresql-async
postgresql-async/src/main/scala/com/github/mauricio/async/db/postgresql/parsers/NoticeParser.scala
Scala
apache-2.0
991
package com.productfoundry.akka.cqrs import akka.persistence.PersistentActor import com.productfoundry.akka.GracefulPassivation /** * Defines a domain entity. */ trait Entity extends PersistentActor with GracefulPassivation { final val entityName = context.parent.path.name final val entityId = self.path.name final val _persistenceId = s"$entityName/$entityId" override def persistenceId: String = _persistenceId if (persistenceId != _persistenceId) { throw new AssertionError(s"Persistence id is invalid, is it changed by a trait? Expected: $entityId, actual: $persistenceId") } }
odd/akka-cqrs
core/src/main/scala/com/productfoundry/akka/cqrs/Entity.scala
Scala
apache-2.0
607
package me.laiseca.restcale.util object PathUtils { private val SEGMENT_SEPARATOR = "/" def split(path:String):List[String] = { path.split(SEGMENT_SEPARATOR).filterNot(_.isEmpty).toList } }
xabierlaiseca/restcale
core/src/main/scala/me/laiseca/restcale/util/PathUtils.scala
Scala
apache-2.0
203
package fr.njin.playoauth.rs import play.api.mvc.Results._ import play.api.mvc.Security.AuthenticatedRequest import play.api.mvc._ import scala.concurrent.{ExecutionContext, Future} import fr.njin.playoauth.common.domain._ import scala.language.{implicitConversions, reflectiveCalls} trait Oauth2Resource[TO <: OauthToken, U <: OauthResourceOwner] { /** provided scopes => RequestHeader => Future[Either[Option[User], omit scopes]] */ type UserInfo = Seq[String] => RequestHeader => Future[Either[Option[U], Seq[String]]] /** using example: * {{{ * def tokenRepo: OauthTokenRepository[TO] = ??? * * def userRepo: OauthResourceOwnerRepository[U] = ??? * * val userInfo = toUserInfo(Utils.parseBearer, tokenRepo.find, userRepo.find) * * def someResourceAction = ScopedAction(Seq("some_scope"), userInfo){ request => * Ok("Hello " + request.user) * }} * }}} * * example with token fetch from remote: * {{{ * def userRepo: OauthResourceOwnerRepository[U] = ??? * * //wsApi: WSAPI is @Injected * def tokenFetcher(value: String) = * wsApi.url("http://localhost:9000/oauth2/token") * .withAuth("CLIENT_ID","CLIENT_SECRET", WSAuthScheme.BASIC) * .withQueryString("value" -> value) * .get().map { response => * response.status match { * case Status.OK => Json.fromJson[AuthToken](response.json).asOpt * case _ => None * } * * def userInfo = toUserInfo(Utils.parseBearer, tokenFetcher, userRepo.find) * * def someResourceAction = ScopedAction(Seq("some_scope"), userInfo){ request => * Ok("Hello " + request.user) * }} * }}} */ class ScopedAction(scopes: Seq[String], userInfo: UserInfo, onUnauthorized: RequestHeader => Result, onForbidden: Seq[String] => RequestHeader => Result) extends ActionBuilder[({type R[A] = AuthenticatedRequest[A, U]})#R] { def invokeBlock[A](req: Request[A], block: (AuthenticatedRequest[A, U]) => Future[Result]) = userInfo(scopes)(req).flatMap { either => either.fold( ownerOpt => ownerOpt.fold(Future successful onUnauthorized(req)) { owner => block(new AuthenticatedRequest(owner, req)) }, Future successful onForbidden(_)(req) ) }(this.executionContext) } object ScopedAction { def apply(scopes: Seq[String], userInfo: UserInfo, onUnauthorized: RequestHeader => Result = _ => Unauthorized, onForbidden: Seq[String] => RequestHeader => Result = scopes => _ => Forbidden) = new ScopedAction(scopes, userInfo, onUnauthorized, onForbidden) } def toUserInfo(tokenValue: RequestHeader => Option[String], token: String => Future[Option[TO]], user: String => Future[Option[U]]) (implicit ec: ExecutionContext): UserInfo = scopes => request => tokenValue(request).map(token(_).flatMap( _.filter(!_.hasExpired) match { case None => Future successful Left(None) case Some(tk) => tk.scopes .map(tokenScopes => scopes.filter(tokenScopes.contains)) .filter(_.isEmpty) match { case None => user(tk.ownerId).map(Left(_)) case Some(omitScopes) => Future successful Right(omitScopes) } } )).getOrElse(Future successful Left(None)) }
giabao/play-oauth
play-oauth/src/main/scala/fr/njin/playoauth/rs/Oauth2Resource.scala
Scala
apache-2.0
3,559
package poly.collection.mut import cats.implicits._ import poly.collection._ import poly.collection.factory._ /** * A set backed by a singly-linked list. * @since 0.1.0 * @author Tongfei Chen */ class ListSet[T] private(private val data: ListSeq[T])(implicit val keyEq: Eq[T]) extends KeyMutableSet[T] { override def size = data.len def contains(x: T): Boolean = { var found = false var c = data.dummy.next while (c ne data.dummy) { if (c.data === x) return true c = c.next } false } def clear_!() = data.clear_!() def add_!(x: T) = { if (!contains(x)) data.prepend_!(x) } def remove_!(x: T) = { var p = data.dummy var c = data.dummy.next while (c ne data.dummy) { if (c.data === x) p.next = c.next p = c c = c.next } } def keys: Seq[T] = data } object ListSet extends SetFactory[ListSet, Eq] { def newSetBuilder[K: Eq]: Builder[K, ListSet[K]] = new Builder[K, ListSet[K]] { private[this] val s = new ListSet(ListSeq[K]()) def add(x: K) = s add_! x def result = s } }
ctongfei/poly-collection
core/src/main/scala/poly/collection/mut/ListSet.scala
Scala
mit
1,095
package edu.gemini.horizons.api.osgi import org.osgi.framework.{BundleContext, BundleActivator} class Activator extends BundleActivator { def start(ctx: BundleContext): Unit = { } def stop(ctx: BundleContext): Unit = { } }
arturog8m/ocs
bundle/edu.gemini.horizons.api/src/main/scala/edu/gemini/horizons/api/osgi/Activator.scala
Scala
bsd-3-clause
236
package cromwell.database.slick import cromwell.database.sql.tables.SummaryStatusEntry import scala.concurrent.ExecutionContext trait SummaryStatusSlickDatabase { this: MetadataSlickDatabase => import dataAccess.driver.api._ private[slick] def getSummaryStatusEntryMaximumId(summaryTableName: String, summarizedTableName: String): DBIO[Option[Long]] = { dataAccess. maximumIdForSummaryTableNameSummarizedTableName((summaryTableName, summarizedTableName)). result.headOption } private[slick] def previousOrMaximum(previous: Long, longs: Seq[Long]): Long = (previous +: longs).max private[slick] def upsertSummaryStatusEntryMaximumId(summaryTableName: String, summarizedTableName: String, maximumId: Long)(implicit ec: ExecutionContext): DBIO[Unit] = { if (useSlickUpserts) { for { _ <- dataAccess.summaryStatusEntryIdsAutoInc. insertOrUpdate(SummaryStatusEntry(summaryTableName, summarizedTableName, maximumId)) } yield () } else { for { updateCount <- dataAccess. maximumIdForSummaryTableNameSummarizedTableName((summaryTableName, summarizedTableName)). update(maximumId) _ <- updateCount match { case 0 => dataAccess.summaryStatusEntryIdsAutoInc += SummaryStatusEntry(summaryTableName, summarizedTableName, maximumId) case _ => assertUpdateCount("upsertSummaryStatusEntryMaximumId", updateCount, 1) } } yield () } } }
ohsu-comp-bio/cromwell
database/sql/src/main/scala/cromwell/database/slick/SummaryStatusSlickDatabase.scala
Scala
bsd-3-clause
1,555
package com.github.mdr.mash.completions import com.github.mdr.mash.inference.Type import com.github.mdr.mash.lexer.Token import com.github.mdr.mash.parser.AbstractSyntax._ import com.github.mdr.mash.parser.{ ConcreteSyntax, SourceInfo } import com.github.mdr.mash.utils.{ Region, StringUtils } import scala.PartialFunction._ case class MemberCompletionResult(isMemberExpr: Boolean, completionResultOpt: Option[CompletionResult], prioritiseMembers: Boolean) object MemberCompleter { private val Dummy = "dummy" /** * Find completions for string literals that correspond to members of the given target type. */ def completeStringMember(targetType: Type, prefix: String): Seq[Completion] = MemberFinder.getMembers(targetType) .filter(_.name startsWith prefix) .map(_.asCompletion(isQuoted = true)) def completeIdentifier(text: String, identifier: Token, parser: CompletionParser): MemberCompletionResult = { val expr = parser.parse(text) val memberLikeOpt = findMemberLike(expr, identifier) val completionResultOpt = for { memberLike ← memberLikeOpt target = getTarget(memberLike) members ← getMembers(target) completions = members.filter(_.name startsWith identifier.text).map(_.asCompletion(isQuoted = false)) result ← CompletionResult.of(completions, identifier.region) } yield result val prioritiseMembers = memberLikeOpt.exists { case memberExpr: MemberExpr ⇒ shouldPrioritise(memberExpr) case _ ⇒ false } MemberCompletionResult(memberLikeOpt.isDefined, completionResultOpt, prioritiseMembers) } def completeImmediatelyAfterDot(text: String, dot: Token, pos: Int, parser: CompletionParser): Option[CompletionResult] = for { (expr, identifier) ← insertDummyIdentifierAfterDot(text, dot, parser) memberLikeOpt ← findMemberLike(expr, identifier) target = getTarget(memberLikeOpt) members ← getMembers(target) completions = members.map(_.asCompletion(isQuoted = false)) region = Region(dot.region.posAfter, 0) result ← CompletionResult.of(completions, region) } yield result private def insertDummyIdentifierAfterDot(text: String, dot: Token, parser: CompletionParser): Option[(Expr, Token)] = { val replacedText = StringUtils.replace(text, dot.region, s"${dot.text}$Dummy ") val dummyIdentifierRegion = Region(dot.region.posAfter, Dummy.length) val expr = parser.parse(replacedText) for { sourceInfo ← expr.sourceInfoOpt identifierToken ← sourceInfo.node.tokens.find(t ⇒ t.isIdentifier && t.region == dummyIdentifierRegion) } yield (expr, identifierToken) } private def getTarget(expr: Expr) = expr match { case memberExpr: MemberExpr ⇒ memberExpr.target case importStatement: ImportStatement ⇒ importStatement.expr case _ ⇒ throw new AssertionError(s"Unexpected expression: $expr") } private def getMembers(target: Expr): Option[Seq[MemberInfo]] = target.constantValueOpt.flatMap(MemberFinder.getValueMembers) orElse target.typeOpt.map(MemberFinder.getMembers(_)) private def shouldPrioritise(memberExpr: MemberExpr): Boolean = !spaceBeforeDot(memberExpr) && !cond(memberExpr.target) { case _: Identifier | _: StringLiteral ⇒ true } private def spaceBeforeDot(memberExpr: MemberExpr): Boolean = memberExpr.sourceInfoOpt.exists { sourceInfo ⇒ cond(sourceInfo.node) { case ConcreteSyntax.MemberExpr(before, dot, after) ⇒ dot.offset > 0 && dot.source.charAt(dot.offset - 1).isWhitespace } } private def findMemberLike(expr: Expr, token: Token): Option[Expr] = expr.find { case e@MemberExpr(_, _, _, Some(SourceInfo(_, ConcreteSyntax.MemberExpr(_, _, `token`)))) ⇒ e case e@MemberExpr(_, _, _, Some(SourceInfo(_, ConcreteSyntax.HeadlessMemberExpr(_, `token`)))) ⇒ e case e@ImportStatement(_, _, Some(SourceInfo(_, ConcreteSyntax.ImportStatement(_, _, _, `token`)))) ⇒ e } }
mdr/mash
src/main/scala/com/github/mdr/mash/completions/MemberCompleter.scala
Scala
mit
4,175
package io.vamp.container_driver import io.vamp.common.Config case class DockerPortMapping(containerPort: Int, hostPort: Option[Int], protocol: String = "tcp") object Docker { val network = Config.string("vamp.container-driver.network") } case class Docker(image: String, portMappings: List[DockerPortMapping], parameters: List[DockerParameter], privileged: Boolean = false, network: String) case class DockerParameter(key: String, value: String) case class DockerApp( id: String, container: Option[Docker], instances: Int, cpu: Double, memory: Int, environmentVariables: Map[String, String], command: List[String] = Nil, arguments: List[String] = Nil, labels: Map[String, String] = Map(), constraints: List[List[String]] = Nil )
magneticio/vamp
container_driver/src/main/scala/io/vamp/container_driver/Docker.scala
Scala
apache-2.0
891
package vggames.scala.specs.valvar import vggames.scala.specs.GameSpecification import vggames.scala.code.RestrictedFunction0 import vggames.scala.specs.TestRun class DefineValInt extends GameSpecification[RestrictedFunction0[Int]] { def runSignature = ":Int" def extendsType = "RestrictedFunction0[Int]" override def afterCode = "numero" def challenge = """Defina a constante chamada <code>numero</code> com o valor <code>123</code> """ def run(code : Code, submittedCode : String)(implicit cases : TestRun) = "O seu código" should { """ definir a constante 123 chamada numero """ in { code() must_== 123 } } }
vidageek/games
games/scala/src/main/scala/vggames/scala/specs/valvar/DefineValInt.scala
Scala
gpl-3.0
658