• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Charset类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: userPreferencesFileContents

//设置package包名称以及导入依赖的类
package com.github.madoc.create_sbt_project.io

import java.nio.charset.Charset
import java.nio.file.{FileSystem, FileSystems, Files}
import java.util.concurrent.atomic.AtomicReference

import com.github.madoc.create_sbt_project.action.framework.ActionEnvironment
import com.github.madoc.create_sbt_project.io.Write.WriteToAppendable

import scala.io.Source

trait FileSystemSupport extends ActionEnvironment {
  def userPreferencesFileContents:Option[String]
  def writeToStandardOutput:Write
  def writeToErrorOutput:Write
}
object FileSystemSupport {
  val default:FileSystemSupport = new Default(FileSystems getDefault)
  val main:AtomicReference[FileSystemSupport] = new AtomicReference[FileSystemSupport](default)

  class Default(val fs:FileSystem) extends FileSystemSupport {
    def userPreferencesFileContents = {
      val prefsPath = fs getPath userPreferencesFilePath
      if(Files.exists(prefsPath) && Files.isRegularFile(prefsPath) && Files.isReadable(prefsPath)) {
        val source = Source.fromInputStream(Files newInputStream prefsPath, "utf-8")
        try Some(source mkString) finally source.close()
      }
      else None
    }

    val writeToErrorOutput = new WriteToAppendable(systemErr)
    val writeToStandardOutput = new WriteToAppendable(systemOut)
    def fileExists(path:String) = Files exists (fs getPath path)
    def isFileWritable(path:String) = Files isWritable (fs getPath path)
    def isDirectory(path:String) = Files isDirectory (fs getPath path)
    def mkdirs(path:String) = Files createDirectories (fs getPath path)
    def outputToFile[A](contents:A, path:String, charset:Charset)(implicit output:Output[A]) = {
      val writer = Files.newBufferedWriter(fs getPath path, charset)
      try output(contents)(new WriteToAppendable(writer)) finally writer close
    }

    protected def systemErr:Appendable = System err
    protected def systemOut:Appendable = System out
    protected def userHomeDirectory:String = System.getProperty("user.home")
    protected def userPreferencesFilePath:String =
      if(userHomeDirectory endsWith "/") userHomeDirectory + ".create-sbt-project.json"
      else userHomeDirectory + "/.create-sbt-project.json"
  }
} 
开发者ID:Madoc,项目名称:create-sbt-project,代码行数:50,代码来源:FileSystemSupport.scala


示例2: circeEncoder

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

import java.nio.charset.Charset

import cats.data.ValidatedNel
import cats.implicits._
import io.circe._
import io.circe.generic.auto._
import io.circe.parser._
import io.circe.syntax._
import shapeless.Witness

package object circe {

  private val printer = Printer.noSpaces.copy(dropNullKeys = true)

  implicit def circeEncoder[A: Encoder]: content.Encoder[A, Witness.`"application/json"`.T] =
    content.Encoder.of("application/json") {
      (value: A, charset: Charset) => content.Encoder.encodeString(printer.pretty(value.asJson), charset)
    }

  implicit def circeDecoder[A: Decoder]: content.Decoder.Aux[Witness.`"application/json"`.T, A] =
    content.Decoder.of("application/json") {
      response =>
        content.Decoder.decodeString(response).andThen {
          str => (parse(str).toValidated.toValidatedNel: ValidatedNel[Throwable, Json]).andThen {
            json: Json => json.as[A].toValidated.toValidatedNel: ValidatedNel[Throwable, A]
          }
        }
    }

} 
开发者ID:finagle,项目名称:featherbed,代码行数:33,代码来源:package.scala


示例3: SimplisticHandler

//设置package包名称以及导入依赖的类
package com.scalaio.tcp.server

import java.nio.charset.Charset

import akka.actor.{Actor, ActorLogging, Props}
import akka.io.Tcp
import akka.util.ByteString

object SimplisticHandler {
  def props(encoding: Charset) = Props(classOf[SimplisticHandler], encoding)
}

class SimplisticHandler(encoding: Charset) extends Actor with ActorLogging {
  import Tcp._

  def receive: Receive = {
    case Received(data) =>
      log.info(s"SimplisticHandler received <${data.length}> bytes")
      sender() ! Write(aResponsePacketFrom(data))

    case PeerClosed =>
      log.info("SimplisticHandler received PeerClosed, stopping.")
      context stop self
  }

  def aResponsePacketFrom(data: ByteString): ByteString = {
    val map = new String(data.toArray, 0, data.length, encoding).flatMap(caesarCypher)
    ByteString(map.getBytes(encoding))
  }

  def caesarCypher(c: Char): scala.collection.mutable.ArrayOps[Char] =
    if (c != '\n' && c != '\r') Character.toChars(c + 3) else Array(c)

} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:35,代码来源:SimplisticHandler.scala


示例4: format

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.csv.scaladsl

import java.nio.charset.{Charset, StandardCharsets}

import akka.NotUsed
import akka.stream.alpakka.csv.{javadsl, CsvFormatter}
import akka.stream.scaladsl.{Flow, Source}
import akka.util.ByteString

import scala.collection.immutable


  def format[T <: immutable.Iterable[String]](
      delimiter: Char = Comma,
      quoteChar: Char = DoubleQuote,
      escapeChar: Char = Backslash,
      endOfLine: String = "\r\n",
      quotingStyle: CsvQuotingStyle = CsvQuotingStyle.Required,
      charset: Charset = StandardCharsets.UTF_8,
      byteOrderMark: Option[ByteString] = None
  ): Flow[T, ByteString, NotUsed] = {
    val formatter =
      new CsvFormatter(delimiter, quoteChar, escapeChar, endOfLine, quotingStyle, charset)
    byteOrderMark.fold {
      Flow[T].map(formatter.toCsv).named("CsvFormatting")
    } { bom =>
      Flow[T].map(formatter.toCsv).named("CsvFormatting").prepend(Source.single(bom))
    }

  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:32,代码来源:CsvFormatting.scala


示例5: CsvToMapStage

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.csv

import java.nio.charset.Charset

import akka.stream.stage.{GraphStage, GraphStageLogic, InHandler, OutHandler}
import akka.stream.{Attributes, FlowShape, Inlet, Outlet}
import akka.util.ByteString

import scala.collection.immutable


private[csv] class CsvToMapStage(columnNames: Option[immutable.Seq[String]], charset: Charset)
    extends GraphStage[FlowShape[immutable.Seq[ByteString], Map[String, ByteString]]] {

  override protected def initialAttributes: Attributes = Attributes.name("CsvToMap")

  private val in = Inlet[immutable.Seq[ByteString]]("CsvToMap.in")
  private val out = Outlet[Map[String, ByteString]]("CsvToMap.out")
  override val shape = FlowShape.of(in, out)

  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
    new GraphStageLogic(shape) with InHandler with OutHandler {
      private var headers = columnNames

      setHandlers(in, out, this)

      override def onPush(): Unit = {
        val elem = grab(in)
        if (headers.isDefined) {
          val map = headers.get.zip(elem).toMap
          push(out, map)
        } else {
          headers = Some(elem.map(_.decodeString(charset)))
          pull(in)
        }
      }

      override def onPull(): Unit = pull(in)
    }
} 
开发者ID:akka,项目名称:alpakka,代码行数:41,代码来源:CsvToMapStage.scala


示例6: PeerId

//设置package包名称以及导入依赖的类
package com.spooky.bittorrent.model

import com.spooky.bittorrent.metainfo.Torrent
import java.nio.ByteBuffer
import java.nio.file.Path
import java.util.BitSet
import com.spooky.bittorrent.Binary
import java.nio.charset.Charset
import scala.annotation.tailrec
import com.spooky.bittorrent.Checksum
import com.spooky.bittorrent.InfoHash

case class PeerId(id: String)
object PeerId {
  val UTF8 = Charset.forName("UTF8")
  def parse(buffer: ByteBuffer): PeerId = {
    val buff = Array.ofDim[Byte](20)
    buffer.get(buff)
    //    val charset = Charset.forName("ASCII")
    PeerId(new String(buff, UTF8).intern())
  }
  def create = PeerId("SPOOKY6-c2b4f6c4h4d9")
}
case class TorrentFileState(have: BitSet) {
  //This is bugged since last piece is generaly not fully utalized
  def getDownloaded(torrent: Torrent): Long = {
      @tailrec
      def rec(bitset: BitSet, index: Int, accumulated: Long, length: Long): Long = {
        if (bitset.size == index) {
          accumulated
        } else rec(bitset, index + 1, if (bitset.get(index)) accumulated + length else accumulated, length)
      }
    rec(have, 0, 0l, torrent.info.pieceLength)
  }
  override def toString: String = {
    "|" + Binary.toBinary(have) + "|"
  }
}
case class TorrentSetup(torrent: Torrent, root: Path)
case class EnrichedTorrentSetup(torrent: Torrent, root: Path, state: TorrentFileState)
case class TorrentStatistics(infoHash: InfoHash, uploaded: Long, downloaded: Long, left: Long, corrupt: Long)
case class TorrentConfiguration(port: Short, numwant: Int)
abstract class AbstractPeer(ip: String, port: Short)
case class Peer(ip: String, port: Short) extends AbstractPeer(ip, port)

//rename to something maybe **Context
case class TorrentRef(info: InfoHash, peerId: PeerId)
object TorrentRef {
  def apply(torrent: Torrent, peerId: PeerId): TorrentRef = TorrentRef(torrent.infoHash, peerId)
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:51,代码来源:model.scala


示例7: Base

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

import java.math.BigInteger
import java.util.concurrent.ThreadLocalRandom
import java.nio.charset.Charset

abstract class Base {
  protected val DH_P = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563"
  protected val DH_G = "02"
  protected val DH_L = 160

  protected val UTF8 = Charset.forName("UTF8");
  protected val KEYA_IV = "keyA".getBytes(UTF8)
  protected val KEYB_IV = "keyB".getBytes(UTF8)
  protected val REQ1_IV = "req1".getBytes(UTF8)
  protected val REQ2_IV = "req2".getBytes(UTF8)
  protected val REQ3_IV = "req3".getBytes(UTF8)
  protected val VC = Array[Byte](0, 0, 0, 0, 0, 0, 0, 0)

  protected val RC4_STREAM_ALG = "RC4";

  protected val DH_P_BI = new BigInteger(DH_P, 16)
  protected val DH_G_BI = new BigInteger(DH_G, 16)

  protected val DH_SIZE_BYTES = DH_P.length() / 2

  protected val CRYPTO_PLAIN: Byte = Plain.id
  protected val CRYPTO_RC4: Byte = RC4.id

  protected val PADDING_MAX = 512

  private def randomPaddingSize: Int = {
    val random = ThreadLocalRandom.current
    Math.abs(random.nextInt % PADDING_MAX)
  }

  protected def randomPadding(): Array[Byte] = {
    val padding = Array.ofDim[Byte](randomPaddingSize)
    val random = ThreadLocalRandom.current
    random.nextBytes(padding)
    padding
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:44,代码来源:Base.scala


示例8: ByteString

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

import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.nio.Buffer
import java.util.Arrays

object ByteString {
  private val UTF8 = Charset.forName("UTF8")
  def apply(str: String): ByteString = {
    val result = str.getBytes(UTF8)
    ByteString(result, result.length)
  }
  def apply(arr: Array[Byte]): ByteString = ByteString(arr, arr.length, 0)
  def apply(bb: ByteBuffer): ByteString = {
    val result = bb.array()
    ByteString(result, result.length)
  }
  def copy(bb: Buffer): ByteString = copy(bb.asInstanceOf[ByteBuffer])
  def copy(bb: ByteBuffer): ByteString = {
    val result = Array.ofDim[Byte](bb.remaining)
    bb.get(result)
    ByteString(result, result.length)
  }
}
case class ByteString(arr: Array[Byte], roof: Int, index: Int = 0) {
  def apply(index: Int): Byte = arr(this.index + index)
  def length: Int = roof - index
  def toArray: Array[Byte] = {
    val result = Array.ofDim[Byte](roof - index)
    System.arraycopy(arr, index, result, 0, result.length)
    result
  }
  def toByteBuffer: ByteBuffer = ByteBuffer.wrap(toArray)
  def take(n: Int): ByteString = {
    ByteString(arr, Math.min(arr.length, index + n))
  }
  def isEmpty: Boolean = roof == index
  def head: Byte = arr(index)

  override def toString:String = {
    s"index: $index roof: $roof | ${Arrays.toString(arr)}"
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:45,代码来源:ByteString.scala


示例9: prepareFiles

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

import java.io.File
import java.nio.charset.Charset
import java.nio.file.{Files, Paths}
import java.util

trait FilePreparator {
  def prepareFiles() {
    if (Paths.get(TestEnv.TMP_FOLDER).toFile.exists() && Paths.get(TestEnv.TMP_FOLDER + TestEnv.TMP_FILE).toFile.exists()) return;
    var res1 = util.Arrays.asList("<testresult name=\"Test 1\" time=\"0\" tests=\"4\" errors = \"0\" skipped=\"0\" failures=\"0\"></testresult>")
    var res2 = util.Arrays.asList("<testresult name=\"Test 2\" time=\"0\" tests=\"4\" errors = \"0\" skipped=\"0\" failures=\"99\"></testresult>")
    Files.createDirectories(Paths.get(TestEnv.TMP_FOLDER));
    Files.write(Paths.get(TestEnv.TMP_FOLDER + TestEnv.TMP_FILE), res1, Charset.forName("UTF-8"))
    Files.write(Paths.get(TestEnv.TMP_FOLDER + "2"+TestEnv.TMP_FILE), res2, Charset.forName("UTF-8"))
  }

  def deleteFiles():Boolean = {
    var dir = new File(TestEnv.TMP_FOLDER)
    dir.listFiles.foreach(_.delete())
    dir.delete()
  }
} 
开发者ID:olka,项目名称:test-reports-agregator,代码行数:24,代码来源:FilePreparator.scala


示例10: ProcessBuilderUtils

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

import java.io.ByteArrayInputStream
import java.nio.charset.{Charset, CodingErrorAction}

import text.StringOption

import scala.collection.mutable.ListBuffer
import scala.io.{Codec, Source}
import scala.sys.process.ProcessBuilder


object ProcessBuilderUtils {
  implicit def processToProcessUtils(repr: ProcessBuilder): ProcessBuilderUtils = {
    new ProcessBuilderUtils(repr)
  }
}

class ProcessBuilderUtils(repr: ProcessBuilder) {
  def lineStream(encoding: Charset,
                 onMalformedInput: CodingErrorAction,
                 onUnmappableCharacter: CodingErrorAction,
                 replacementOpt: StringOption): Iterator[String] = {
    val lines: Iterator[String] = repr.lineStream_!.iterator
    val byteBuffer = ListBuffer.empty[Byte]
    while (lines.hasNext) {
      val line: String = lines.next.trim concat "\n"
      byteBuffer ++= line.getBytes
    }
    implicit val codec = Codec(encoding).
      onMalformedInput(onMalformedInput).
      onUnmappableCharacter(onUnmappableCharacter)
    if (replacementOpt.nonEmpty) {
      codec.decodingReplaceWith(replacementOpt.get)
    }
    Source.fromInputStream(new ByteArrayInputStream(byteBuffer.toArray)).getLines
  }
} 
开发者ID:ynupc,项目名称:scalastringcourseday7,代码行数:39,代码来源:ProcessBuilderUtils.scala


示例11: EachLogExpectationBuilder

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

import java.nio.charset.Charset
import java.nio.charset.StandardCharsets.UTF_8

import akka.util.ByteString
import play.api.mvc.Headers

import scala.concurrent.duration._

final case class EachLogExpectationBuilder(
  methodOpt: Option[HttpMethod], // accept all method if None
  headers: Headers = Headers(),
  bodyOpt: Option[ArrayByte] = None, // body for sequential matcher
  count: Int = 1,
  queue: AccessLogQueue
) {
  def method: String = methodOpt.fold("")(_.value)

  def body(v: String, charset: Charset = UTF_8): EachLogExpectationBuilder =
    copy(bodyOpt = Some(ArrayByte(ByteString(v.getBytes(charset)))))

  def count(v: Int): EachLogExpectationBuilder = copy(count = v)

  def header(key: String, value: String): EachLogExpectationBuilder = copy(headers = headers.add((key, value)))

  
  def apply(timeout: FiniteDuration = 1.second, interval: Int = 100): Unit = {
    new EachLogExecutionContext(this).run(timeout, interval)
  }
} 
开发者ID:xuwei-k,项目名称:httpmock,代码行数:32,代码来源:EachLogExpectationBuilder.scala


示例12: CreateActions

//设置package包名称以及导入依赖的类
package com.github.madoc.create_sbt_project.action

import java.nio.charset.Charset

import com.github.madoc.create_sbt_project.action.framework.{Action, ActionList}
import com.github.madoc.create_sbt_project.io.Output
import com.github.madoc.create_sbt_project.model.RootModel

object CreateActions extends (RootModel?ActionList)
{def apply(rootModel:RootModel):ActionList = new CreateActions(rootModel) actions}
private class CreateActions(rootModel:RootModel) {
  def actions:ActionList =
    `create main directory` >>
    `write build.sbt` >>
    `write .gitignore` >>
    `write build.properties` >>
    `write plugins.sbt`

  private val charset = Charset forName "utf-8"

  private def `create main directory`:Action = CreateDirectory(rootModel projectDirectory)
  private def `write build.sbt`:Action = outputToFile("build.sbt", buildDefinition)
  private def `write .gitignore`:Action = if(gitIgnore nonEmpty) outputToFile(".gitignore", gitIgnore) else ActionList.empty
  private def `write build.properties`:Action =
    if(buildProperties nonEmpty) CreateDirectory(path("project"))>>outputToFile("project/build.properties", buildProperties)
    else ActionList.empty
  private def `write plugins.sbt`:Action =
    if(pluginsDefinition nonEmpty) CreateDirectory(path("project"))>>outputToFile("project/plugins.sbt", pluginsDefinition)
    else ActionList.empty

  private def outputToFile[A](file:String, contents:A)(implicit output:Output[A]):Action =
    OutputToFile(path(file), contents, charset)
  private def path(p:String):String = {
    assert(p nonEmpty)
    rootModel.projectDirectory match {
      case "" ? p
      case endsWithSlash if endsWithSlash endsWith "/" ? endsWithSlash + p
      case doesNotEndWithSlash ? doesNotEndWithSlash + "/" + p
    }
  }

  private def buildDefinition = rootModel buildDefinition
  private def buildProperties = rootModel buildProperties
  private def gitIgnore = rootModel gitIgnore
  private def pluginsDefinition = rootModel pluginsDefinition
} 
开发者ID:Madoc,项目名称:create-sbt-project,代码行数:47,代码来源:CreateActions.scala


示例13: OutputToFile

//设置package包名称以及导入依赖的类
package com.github.madoc.create_sbt_project.action

import java.io.File
import java.nio.charset.Charset

import com.github.madoc.create_sbt_project.action.framework.{Action, ActionEnvironment, ActionResult}
import com.github.madoc.create_sbt_project.action.precondition.PreconditionFailure
import com.github.madoc.create_sbt_project.action.precondition.PreconditionFailure.{DirectoryDoesNotExist, DirectoryNotWritable, FileIsOnDirectoryPath}
import com.github.madoc.create_sbt_project.io.Output

case class OutputToFile[A](path:String, contents:A, charset:Charset)(implicit output:Output[A]) extends Action {
  protected def run(env:ActionEnvironment) = {env outputToFile (contents, path, charset); ActionResult.Success}
  def precondition = {env:ActionEnvironment ?
    val parent = Option(new File(path) getParent) getOrElse "."
    if(!(env fileExists parent)) Seq(DirectoryDoesNotExist(parent))
    else if(!(env isFileWritable parent)) Seq(DirectoryNotWritable(parent))
    else if(!(env isDirectory parent)) Seq(FileIsOnDirectoryPath(parent))
    else Seq()
  }
  def mightDealWith(failure:PreconditionFailure) = false
} 
开发者ID:Madoc,项目名称:create-sbt-project,代码行数:22,代码来源:OutputToFile.scala


示例14: TestFileSystemSupport

//设置package包名称以及导入依赖的类
package com.github.madoc.create_sbt_project.io

import java.nio.charset.Charset
import java.nio.file.Files

import com.google.common.jimfs.{Configuration, Jimfs}

import scala.collection.JavaConversions

class TestFileSystemSupport(workingDirectory:String="/home/user/projectdir", userHome:String="/home/user")
extends FileSystemSupport.Default(Jimfs.newFileSystem(Configuration.unix().toBuilder.setWorkingDirectory(workingDirectory).build())) {
  private var errorOutput = ""
  private var standardOutput = ""
  private val lock = new Object

  locally {mkdirs(workingDirectory)}

  def getErrorOutput:String = lock synchronized errorOutput
  def getStandardOutput:String = lock synchronized standardOutput
  def setUserPreferencesFileContents(contents:String) =
    outputToFile(contents, userPreferencesFilePath, Charset forName "utf-8")(new Output[String] {
      def apply(the:String)(write:Write) = write(the)
    })
  def getFileContents(path:String, charset:Charset=Charset forName "utf-8"):String =
    JavaConversions.asScalaBuffer(Files.readAllLines(fs getPath path, charset)).mkString("\n")

  override protected def userHomeDirectory = userHome
  override protected def systemErr = new Appendable {
    def append(csq:CharSequence) = {lock synchronized {errorOutput += csq.toString}; this}
    def append(csq:CharSequence, start:Int, end:Int) = append(csq subSequence (start, end))
    def append(c:Char) = append(c toString)
  }
  override protected def systemOut = new Appendable {
    def append(csq:CharSequence) = {lock synchronized {standardOutput += csq.toString}; this}
    def append(csq:CharSequence, start:Int, end:Int) = append(csq subSequence (start, end))
    def append(c:Char) = append(c toString)
  }
} 
开发者ID:Madoc,项目名称:create-sbt-project,代码行数:39,代码来源:TestFileSystemSupport.scala


示例15: Launcher

//设置package包名称以及导入依赖的类
import org.slf4j.LoggerFactory
import com.argcv.spark.utils.SparkHelper.sc
import com.argcv.spark.utils.SparkHelper.ss
import org.apache.spark.rdd.RDD

import org.apache.commons.io.IOUtils
import java.net.URL
import java.nio.charset.Charset


object Launcher extends App {
  import ss.implicits._
  //
  lazy val logger = LoggerFactory.getLogger(Launcher.getClass)
  val timeStart = System.currentTimeMillis()

  // Zeppelin creates and injects sc (SparkContext) and sqlContext (HiveContext or SqlContext)
  // So you don't need create them manually

  // load bank data
  val bankText: RDD[String] = sc.parallelize(
    IOUtils.toString(
      new URL("https://s3.amazonaws.com/apache-zeppelin/tutorial/bank/bank.csv"),
      Charset.forName("utf8")).split("\n"))
  val bank = bankText.map(s => s.split(";")).filter(s => s(0) != "\"age\"").map(
    s => Bank(s(0).toInt,
      s(1).replaceAll("\"", ""),
      s(2).replaceAll("\"", ""),
      s(3).replaceAll("\"", ""),
      s(5).replaceAll("\"", "").toInt
    )
  ).toDF()

  case class Bank(age: Integer, job: String, marital: String, education: String, balance: Integer)
  bank.createOrReplaceTempView("bank")

  ss.sql("select age, job from bank where age < 35 order by age desc limit 10").show()


  logger.info(s"finished , all time cost : ${System.currentTimeMillis() - timeStart}")
} 
开发者ID:yuikns,项目名称:my-spark,代码行数:42,代码来源:Launcher.scala


示例16: SmartCompletion

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

import java.nio.charset.Charset

class SmartCompletion {
  // multiline selection
  val i = 1
  val s = "1"
  val c = Charset.defaultCharset()
  val d = 1.1
  //println using `priv`

  // ignore auto import
  //  new Codec()
} 
开发者ID:maximn,项目名称:capitalizing-on-a-great-idea,代码行数:16,代码来源:SmartCompletion.scala


示例17: identityFunc

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

import java.nio.charset.Charset
import com.typesafe.config.Config
import scala.concurrent.duration._
import scala.concurrent.Future
import scala.collection.mutable
import shapeless.HList

package object util {

  private[this] val _identityFunc = (x: Any) ? x
  def identityFunc[T]: T ? T      = _identityFunc.asInstanceOf[T ? T]

  def identityHash(obj: AnyRef): String = Integer.toHexString(System.identityHashCode(obj))

  val dropFunc: Any ? Unit         = _ ? ()
  val dropFunc2: (Any, Any) ? Unit = (_, _) ? ()

  val oneIntFunc: Any ? Int = _ ? 1

  val UTF8: Charset  = Charset.forName("UTF-8")
  val ASCII: Charset = Charset.forName("US-ASCII")

  def isPowerOf2(i: Int): Boolean = Integer.lowestOneBit(i) == i

  def roundUpToPowerOf2(i: Int): Int = 1 << (32 - Integer.numberOfLeadingZeros(i - 1))

  def Runnable(body: ? Unit): Runnable = new Runnable { def run(): Unit = body }

  implicit def richByteArray(array: Array[Byte]): RichByteArray                    = new RichByteArray(array)
  implicit def richConfig[T](config: Config): RichConfig                           = new RichConfig(config)
  implicit def richDuration(duration: Duration): RichDuration                      = new RichDuration(duration)
  implicit def richFiniteDuration(duration: FiniteDuration): RichFiniteDuration    = new RichFiniteDuration(duration)
  implicit def richFuture[T](future: Future[T]): RichFuture[T]                     = new RichFuture(future)
  implicit def richHList[L <: HList](list: L): RichHList[L]                        = new RichHList(list)
  implicit def richInt(int: Int): RichInt                                          = new RichInt(int)
  implicit def richList[T](list: List[T]): RichList[T]                             = new RichList(list)
  implicit def richLong(long: Long): RichLong                                      = new RichLong(long)
  implicit def richArrayBuffer[T](seq: mutable.ArrayBuffer[T]): RichArrayBuffer[T] = new RichArrayBuffer(seq)
  implicit def richRefArray[T <: AnyRef](array: Array[T]): RichRefArray[T]         = new RichRefArray(array)
  implicit def richSeq[T](seq: Seq[T]): RichSeq[T]                                 = new RichSeq(seq)
  implicit def richString(string: String): RichString                              = new RichString(string)
  implicit def richTraversable[T](seq: Traversable[T]): RichTraversable[T]         = new RichTraversable(seq)
} 
开发者ID:sirthias,项目名称:swave,代码行数:46,代码来源:package.scala


示例18: RichBytesStreamOpsText

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

import java.nio.charset.{Charset, CodingErrorAction}
import swave.core.io.Bytes

package object text {

  implicit class RichBytesStreamOpsText[T, S[X] <: StreamOps[X]](val underlying: S[T]) extends AnyVal {

    def decode(charset: Charset,
               onMalformedInput: CodingErrorAction = CodingErrorAction.REPORT,
               onUnmappableCharacter: CodingErrorAction = CodingErrorAction.REPLACE)(
        implicit ev: Bytes[T]): S[T]#Repr[String] =
      underlying.via(Text.decode[T](charset, onMalformedInput, onUnmappableCharacter))

    def utf8Decode(implicit ev: Bytes[T]): S[T]#Repr[String] =
      underlying.via(Text.utf8Decode)
  }

  implicit class RichStringStreamOpsText[S <: StreamOps[String]](val underlying: S) extends AnyVal {

    def encode[T: Bytes](charset: Charset): S#Repr[T] =
      underlying.via(Text.encode(charset))

    def utf8Encode[T: Bytes]: S#Repr[T] =
      underlying.via(Text.utf8Encode)

    def lines: S#Repr[String] =
      underlying.via(Text.lines)
  }
} 
开发者ID:sirthias,项目名称:swave,代码行数:32,代码来源:package.scala


示例19: Main

//设置package包名称以及导入依赖的类
package org.mentha.tools.xsd

import java.io.File
import java.nio.charset.Charset

import org.apache.commons.io.FileUtils
import org.apache.xerces.xs._
import collection.convert.wrapAsScala._


object Main {

  // for example, call it with agrs(0) = 'docs/sample.xsd'
  def main(args: Array[String]): Unit = {

    val source = args(0)
    val namespace = if (args.length > 1) args(1) else null

    val model = XSDParser.loadModel(source)
    val processor = new XSDProcessor()

    val components = model.getComponentsByNamespace(XSConstants.ELEMENT_DECLARATION, namespace)
    components
      .values
      .map { obj => obj.asInstanceOf[XSElementDeclaration] }
      .foreach { obj => processor.process(obj) }

    var nodes: Seq[XSNode] = processor.nodes

    // TODO: filter
    // val nodes = processor.nodes
    //   .filterNot { n => "http://www.w3.org/1998/Math/MathML" == n.obj.getNamespace}

    // and optimize them
    {
      nodes = XSDPostProcessor.clearRestrictAnyType(nodes)
      nodes = XSDPostProcessor.simplifyModelGroups(nodes)
      nodes = XSDPostProcessor.removeModelGroups(nodes)
      nodes = XSDPostProcessor.inlineElementTypes(nodes)
    }

    val graphMl = GraphMLRenderer.render(nodes)

    FileUtils.write(
      new File(source+".graphml"),
      graphMl.toString,
      Charset.forName("UTF-8")
    )
  }

} 
开发者ID:zhuj,项目名称:mentha-xsd-graphml,代码行数:52,代码来源:Main.scala


示例20: CompilerTree

//设置package包名称以及导入依赖的类
package org.ucf.spark.ScalaAST
import scala.tools.nsc._
import io._
import scala.io.Source
import scala.reflect.runtime.{universe =>ru}
import scala.tools.reflect.ToolBox
import com.google.common.io.Files
import java.nio.charset.Charset
import java.io.File
import scala.reflect.internal.util.BatchSourceFile


object CompilerTree extends Global(new Settings()){
  new Run
  def parseToTree(path:String) = {
    val code  = AbstractFile.getFile(path)
    val bfs = new BatchSourceFile(code,code.toCharArray)
    val parser = new syntaxAnalyzer.UnitParser(new CompilationUnit(bfs))
    parser.smartParse()
  }
  def parseToString(path:String) = {
      showRaw(this.parseToTree(path))
  }
  def parseWithMirror(path:String) = {
    val source = Files.toString(new File(path),Charset.forName("UTF-8"))
    val toolBox = ru.runtimeMirror(getClass.getClassLoader).mkToolBox()
    toolBox.parse(source)
  }
  
  def parseWithMirrorTypeCheck(path:String) = {
    val source = Files.toString(new File(path),Charset.forName("UTF-8"))
    val toolBox = ru.runtimeMirror(getClass.getClassLoader).mkToolBox()
    toolBox.typecheck(toolBox.parse(source))
  }
  
  
  
} 
开发者ID:bingrao,项目名称:Scala-AST,代码行数:39,代码来源:CompilerTree.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala FileWriter类代码示例发布时间:2022-05-23
下一篇:
Scala SparkSession类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap