text:
package sangria.schema

import language.{existentials, higherKinds, implicitConversions}
import sangria.execution.{FieldTag, SubscriptionField}
import sangria.marshalling.FromInput.{CoercedScalaResult, InputObjectResult}
import sangria.marshalling._
import sangria.{ast, introspection}
import sangria.validation.{ConflictingTypeDefinitionViolation, EnumCoercionViolation, EnumValueCoercionViolation, Violation}
import sangria.introspection._
import sangria.streaming.SubscriptionStreamLike
import sangria.streaming.SubscriptionStreamLike

import scala.annotation.implicitNotFound
import scala.reflect.ClassTag
import sangria.util.tag._

sealed trait Type {
  def namedType: Type with Named = {
    def getNamedType(tpe: Type): Type with Named =
      tpe match {
        case OptionInputType(ofType) ⇒ getNamedType(ofType)
        case OptionType(ofType) ⇒ getNamedType(ofType)
        case ListInputType(ofType) ⇒ getNamedType(ofType)
        case ListType(ofType) ⇒ getNamedType(ofType)
        case n: Named ⇒ n
        case t ⇒ throw new IllegalStateException("Expected named type, but got: " + t)
      }

    getNamedType(this)
  }
}

sealed trait InputType[+T] extends Type {
  lazy val isOptional = this match {
    case _: OptionInputType[_] ⇒ true
    case _ ⇒ false
  }

  lazy val isList = this match {
    case _: ListInputType[_] ⇒ true
    case _ ⇒ false
  }

  lazy val isNamed = !(isOptional && isList)
}

sealed trait OutputType[+T] extends Type

sealed trait LeafType extends Type with Named
sealed trait CompositeType[T] extends Type with Named with OutputType[T]
sealed trait AbstractType extends Type with Named {
  def name: String

  def typeOf[Ctx](value: Any, schema: Schema[Ctx, _]): Option[ObjectType[Ctx, _]] =
    schema.possibleTypes get name flatMap (_.find(_ isInstanceOf value).asInstanceOf[Option[ObjectType[Ctx, _]]])
}

sealed trait NullableType
sealed trait UnmodifiedType

sealed trait Named {
  def name: String
  def description: Option[String]
}

sealed trait HasDeprecation {
  def deprecationReason: Option[String]
}

object Named {
  val NameRegexp = """^[_a-zA-Z][_a-zA-Z0-9]*$""".r

  private[sangria] def doCheckUniqueFields(fields: Seq[Named]): Unit =
    if (fields.map(_.name).toSet.size != fields.size)
      throw new IllegalArgumentException("All fields within a Type should have unique names!")

  private[sangria] def doCheckFieldNames(fields: Seq[Named]): Unit =
    fields.foreach(f ⇒ checkName(f.name))

  def checkObjFields[T <: Seq[Named]](fields: T): T = {
    doCheckUniqueFields(fields)
    doCheckFieldNames(fields)
    fields
  }

  def checkIntFields[T <: Seq[Named]](fields: T): T = {
    doCheckUniqueFields(fields)
    doCheckFieldNames(fields)

    fields
  }

  def checkObjFieldsFn[T <: Seq[Named]](fields: T): () ⇒ T = {
    doCheckUniqueFields(fields)
    doCheckFieldNames(fields)
    () ⇒ fields
  }

  def checkIntFieldsFn[T <: Seq[Named]](fields: T): () ⇒ T = {
    doCheckUniqueFields(fields)
    doCheckFieldNames(fields)

    () ⇒ fields
  }

  def checkObjFields[T <: Seq[Named]](fieldsFn: () ⇒ T): () ⇒ T =
    () ⇒ checkObjFields(fieldsFn())

  def checkIntFields[T <: Seq[Named]](fieldsFn: () ⇒ T): () ⇒ T =
    () ⇒ checkIntFields(fieldsFn())

  def checkName(name: String) = {
    if (!NameRegexp.pattern.matcher(name).matches())
      throw new IllegalArgumentException(s"Name '$name' is not valid GraphQL name! Valid name should satisfy following regex: /$NameRegexp/.")

    name
  }
}

/**
  * Defines a GraphQL scalar value type.
  *
  * `coerceOutput` is allowed to return following scala values:
  *
  *   - String
  *   - Boolean
  *   - Int
  *   - Long
  *   - Float
  *   - Double
  *   - scala.BigInt
  *   - scala.BigDecimal
  *   - sangria.ast.Value (it would be converted to raw scala value before given to a marshalling API)
  *
  * It may also return other values as well as long as underlying marshalling library supports them.
  *
  * You can provide additional meta-information to marshalling API with `scalarInfo`.
  */
case class ScalarType[T](
  name: String,
  description: Option[String] = None,
  coerceUserInput: Any ⇒ Either[Violation, T],
  coerceOutput: (T, Set[MarshallerCapability]) ⇒ Any,
  coerceInput: ast.Value ⇒ Either[Violation, T],
  complexity: Double = 0.0D,
  scalarInfo: Set[ScalarValueInfo] = Set.empty
) extends InputType[T @@ CoercedScalaResult] with OutputType[T] with LeafType with NullableType with UnmodifiedType with Named {
  Named.checkName(name)
}

sealed trait ObjectLikeType[Ctx, Val] extends OutputType[Val] with CompositeType[Val] with NullableType with UnmodifiedType with Named {
  def interfaces: List[InterfaceType[Ctx, _]]

  def fieldsFn: () ⇒ List[Field[Ctx, Val]]

  lazy val ownFields = fieldsFn().toVector

  def removeDuplicates[T, E](list: Vector[T], valueFn: T ⇒ E) =
    list.foldLeft((Vector.empty, Vector.empty): (Vector[E], Vector[T])) {
      case (a @ (visited, acc), e) if visited contains valueFn(e) ⇒ a
      case ((visited, acc), e) ⇒ (visited :+ valueFn(e), acc :+ e)
    }._2

  lazy val allInterfaces: Vector[InterfaceType[Ctx, _]] =
    removeDuplicates(interfaces.toVector.flatMap(i ⇒ i +: i.allInterfaces), (i: InterfaceType[Ctx, _]) ⇒ i.name)

  lazy val fields: Vector[Field[Ctx, _]] = ownFields ++ interfaces.flatMap(i ⇒ i.fields.asInstanceOf[Vector[Field[Ctx, _]]])

  lazy val uniqueFields: Vector[Field[Ctx, _]] = removeDuplicates(fields, (e: Field[Ctx, _]) ⇒ e.name)

  lazy val fieldsByName = fields groupBy (_.name)

  def getField(schema: Schema[_, _], fieldName: String): Vector[Field[Ctx, _]] =
    if (sangria.introspection.MetaFieldNames contains fieldName)
      if (fieldName == SchemaMetaField.name && name == schema.query.name) Vector(SchemaMetaField.asInstanceOf[Field[Ctx, _]])
      else if (fieldName == TypeMetaField.name && name == schema.query.name) Vector(TypeMetaField.asInstanceOf[Field[Ctx, _]])
      else if (fieldName == TypeNameMetaField.name) Vector(TypeNameMetaField.asInstanceOf[Field[Ctx, _]])
      else Vector.empty
    else fieldsByName.getOrElse(fieldName, Vector.empty)
}

case class ObjectType[Ctx, Val: ClassTag] (
  name: String,
  description: Option[String],
  fieldsFn: () ⇒ List[Field[Ctx, Val]],
  interfaces: List[InterfaceType[Ctx, _]],
  instanceCheck: (Any, Class[_], ObjectType[Ctx, Val]) ⇒ Boolean
) extends ObjectLikeType[Ctx, Val] {
  lazy val valClass = implicitly[ClassTag[Val]].runtimeClass

  def withInstanceCheck(fn: (Any, Class[_], ObjectType[Ctx, Val]) ⇒ Boolean) =
    copy(instanceCheck = fn)

  def isInstanceOf(value: Any) = instanceCheck(value, valClass, this)
}

object ObjectType {
  def apply[Ctx, Val: ClassTag](name: String, fields: List[Field[Ctx, Val]]): ObjectType[Ctx, Val] =
    ObjectType(Named.checkName(name), None, fieldsFn = Named.checkObjFieldsFn(fields), Nil, instanceCheck = defaultInstanceCheck)
  def apply[Ctx, Val: ClassTag](name: String, description: String, fields: List[Field[Ctx, Val]]): ObjectType[Ctx, Val] =
    ObjectType(Named.checkName(name), Some(description), fieldsFn = Named.checkObjFieldsFn(fields), Nil, instanceCheck = defaultInstanceCheck)
  def apply[Ctx, Val: ClassTag](name: String, interfaces: List[PossibleInterface[Ctx, Val]], fields: List[Field[Ctx, Val]]): ObjectType[Ctx, Val] =
    ObjectType(Named.checkName(name), None, fieldsFn = Named.checkObjFieldsFn(fields), interfaces map (_.interfaceType), instanceCheck = defaultInstanceCheck)
  def apply[Ctx, Val: ClassTag](name: String, description: String, interfaces: List[PossibleInterface[Ctx, Val]], fields: List[Field[Ctx, Val]]): ObjectType[Ctx, Val] =
    ObjectType(Named.checkName(name), Some(description), fieldsFn = Named.checkObjFieldsFn(fields), interfaces map (_.interfaceType), instanceCheck = defaultInstanceCheck)

  def apply[Ctx, Val: ClassTag](name: String, fieldsFn: () ⇒ List[Field[Ctx, Val]]): ObjectType[Ctx, Val] =
    ObjectType(Named.checkName(name), None, Named.checkObjFields(fieldsFn), Nil, instanceCheck = defaultInstanceCheck)
  def apply[Ctx, Val: ClassTag](name: String, description: String, fieldsFn: () ⇒ List[Field[Ctx, Val]]): ObjectType[Ctx, Val] =
    ObjectType(Named.checkName(name), Some(description), Named.checkObjFields(fieldsFn), Nil, instanceCheck = defaultInstanceCheck)
  def apply[Ctx, Val: ClassTag](name: String, interfaces: List[PossibleInterface[Ctx, Val]], fieldsFn: () ⇒ List[Field[Ctx, Val]]): ObjectType[Ctx, Val] =
    ObjectType(Named.checkName(name), None, Named.checkObjFields(fieldsFn), interfaces map (_.interfaceType), instanceCheck = defaultInstanceCheck)
  def apply[Ctx, Val: ClassTag](name: String, description: String, interfaces: List[PossibleInterface[Ctx, Val]], fieldsFn: () ⇒ List[Field[Ctx, Val]]): ObjectType[Ctx, Val] =
    ObjectType(Named.checkName(name), Some(description), Named.checkObjFields(fieldsFn), interfaces map (_.interfaceType), instanceCheck = defaultInstanceCheck)

  def createFromMacro[Ctx, Val: ClassTag](name: String, description: Option[String], interfaces: List[InterfaceType[Ctx, _]], fieldsFn: () ⇒ List[Field[Ctx, Val]]) =
    ObjectType(Named.checkName(name), description, Named.checkObjFields(fieldsFn), interfaces, instanceCheck = defaultInstanceCheck)

  implicit def acceptUnitCtx[Ctx, Val](objectType: ObjectType[Unit, Val]): ObjectType[Ctx, Val] =
    objectType.asInstanceOf[ObjectType[Ctx, Val]]

  def defaultInstanceCheck[Ctx, Val]: (Any, Class[_], ObjectType[Ctx, Val]) ⇒ Boolean =
    (value, valClass, tpe) ⇒ valClass.isAssignableFrom(value.getClass)
}

case class InterfaceType[Ctx, Val](
  name: String,
  description: Option[String] = None,
  fieldsFn: () ⇒ List[Field[Ctx, Val]],
  interfaces: List[InterfaceType[Ctx, _]],
  manualPossibleTypes: () ⇒ List[ObjectType[_, _]]
) extends ObjectLikeType[Ctx, Val] with AbstractType {
  def withPossibleTypes(possible: PossibleObject[Ctx, Val]*) = copy(manualPossibleTypes = () ⇒ possible.toList map (_.objectType))
  def withPossibleTypes(possible: () ⇒ List[PossibleObject[Ctx, Val]]) = copy(manualPossibleTypes = () ⇒ possible() map (_.objectType))
}

object InterfaceType {
  val emptyPossibleTypes: () ⇒ List[ObjectType[_, _]] = () ⇒ Nil

  def apply[Ctx, Val](name: String, fields: List[Field[Ctx, Val]]): InterfaceType[Ctx, Val] =
    InterfaceType(Named.checkName(name), None, fieldsFn = Named.checkIntFieldsFn(fields), Nil, emptyPossibleTypes)
  def apply[Ctx, Val](name: String, description: String, fields: List[Field[Ctx, Val]]): InterfaceType[Ctx, Val] =
    InterfaceType(Named.checkName(name), Some(description), fieldsFn = Named.checkIntFieldsFn(fields), Nil, emptyPossibleTypes)
  def apply[Ctx, Val](name: String, fields: List[Field[Ctx, Val]], interfaces: List[PossibleInterface[Ctx, Val]]): InterfaceType[Ctx, Val] =
    InterfaceType(Named.checkName(name), None, fieldsFn = Named.checkIntFieldsFn(fields), interfaces map (_.interfaceType), emptyPossibleTypes)
  def apply[Ctx, Val](name: String, description: String, fields: List[Field[Ctx, Val]], interfaces: List[PossibleInterface[Ctx, Val]]): InterfaceType[Ctx, Val] =
    InterfaceType(Named.checkName(name), Some(description), fieldsFn = Named.checkIntFieldsFn(fields), interfaces map (_.interfaceType), emptyPossibleTypes)

  def apply[Ctx, Val](name: String, fieldsFn: () ⇒ List[Field[Ctx, Val]]): InterfaceType[Ctx, Val] =
    InterfaceType(Named.checkName(name), None, Named.checkIntFields(fieldsFn), Nil, emptyPossibleTypes)
  def apply[Ctx, Val](name: String, description: String, fieldsFn: () ⇒ List[Field[Ctx, Val]]): InterfaceType[Ctx, Val] =
    InterfaceType(Named.checkName(name), Some(description), Named.checkIntFields(fieldsFn), Nil, emptyPossibleTypes)
  def apply[Ctx, Val](name: String, fieldsFn: () ⇒ List[Field[Ctx, Val]], interfaces: List[PossibleInterface[Ctx, Val]]): InterfaceType[Ctx, Val] =
    InterfaceType(Named.checkName(name), None, Named.checkIntFields(fieldsFn), interfaces map (_.interfaceType), emptyPossibleTypes)
  def apply[Ctx, Val](name: String, description: String, fieldsFn: () ⇒ List[Field[Ctx, Val]], interfaces: List[PossibleInterface[Ctx, Val]]): InterfaceType[Ctx, Val] =
    InterfaceType(Named.checkName(name), Some(description), Named.checkIntFields(fieldsFn), interfaces map (_.interfaceType), emptyPossibleTypes)
}

case class PossibleInterface[Ctx, Concrete](interfaceType: InterfaceType[Ctx, _])

object PossibleInterface extends PossibleInterfaceLowPrioImplicits {
  implicit def apply[Ctx, Abstract, Concrete](interface: InterfaceType[Ctx, Abstract])(implicit ev: PossibleType[Abstract, Concrete]): PossibleInterface[Ctx, Concrete] =
    PossibleInterface[Ctx, Concrete](interface)
}

trait PossibleInterfaceLowPrioImplicits {
  implicit def applyUnit[Ctx, Abstract, Concrete](interface: InterfaceType[Ctx, Abstract])(implicit ev: PossibleType[Abstract, Concrete]): PossibleInterface[Unit, Concrete] =
    PossibleInterface[Unit, Concrete](interface.asInstanceOf[InterfaceType[Unit, Abstract]])
}

case class PossibleObject[Ctx, Abstract](objectType: ObjectType[Ctx, _])

object PossibleObject {
  implicit def apply[Ctx, Abstract, Concrete](obj: ObjectType[Ctx, Concrete])(implicit ev: PossibleType[Abstract, Concrete]): PossibleObject[Ctx, Abstract] =
    PossibleObject[Ctx, Abstract](obj)

  implicit def applyUnit[Ctx, Abstract, Concrete](obj: ObjectType[Unit, Concrete])(implicit ev: PossibleType[Abstract, Concrete]): PossibleObject[Ctx, Abstract] =
    PossibleObject[Ctx, Abstract](obj.asInstanceOf[ObjectType[Ctx, Concrete]])
}

trait PossibleType[AbstrType, ConcreteType]

object PossibleType {
  private object SingletonPossibleType extends PossibleType[AnyRef, AnyRef]

  def create[AbstrType, ConcreteType] = SingletonPossibleType.asInstanceOf[PossibleType[AbstrType, ConcreteType]]

  implicit def InheritanceBasedPossibleType[Abstract, Concrete](implicit ev: Concrete <:< Abstract): PossibleType[Abstract, Concrete] =
    create[Abstract, Concrete]
}

case class UnionType[Ctx](
  name: String,
  description: Option[String] = None,
  types: List[ObjectType[Ctx, _]]) extends OutputType[Any] with CompositeType[Any] with AbstractType with NullableType with UnmodifiedType

case class Field[Ctx, Val](
    name: String,
    fieldType: OutputType[_],
    description: Option[String],
    arguments: List[Argument[_]],
    resolve: Context[Ctx, Val] ⇒ Action[Ctx, _],
    deprecationReason: Option[String],
    tags: List[FieldTag],
    complexity: Option[(Ctx, Args, Double) ⇒ Double],
    manualPossibleTypes: () ⇒ List[ObjectType[_, _]]) extends Named with HasArguments with HasDeprecation {
  def withPossibleTypes(possible: PossibleObject[Ctx, Val]*) = copy(manualPossibleTypes = () ⇒ possible.toList map (_.objectType))
  def withPossibleTypes(possible: () ⇒ List[PossibleObject[Ctx, Val]]) = copy(manualPossibleTypes = () ⇒ possible() map (_.objectType))
}

object Field {
  def apply[Ctx, Val, Res, Out](
      name: String,
      fieldType: OutputType[Out],
      description: Option[String] = None,
      arguments: List[Argument[_]] = Nil,
      resolve: Context[Ctx, Val] ⇒ Action[Ctx, Res],
      possibleTypes: ⇒ List[PossibleObject[_, _]] = Nil,
      tags: List[FieldTag] = Nil,
      complexity: Option[(Ctx, Args, Double) ⇒ Double] = None,
      deprecationReason: Option[String] = None)(implicit ev: ValidOutType[Res, Out]) =
    Field[Ctx, Val](Named.checkName(name), fieldType, description, arguments, resolve, deprecationReason, tags, complexity, () ⇒ possibleTypes map (_.objectType))

  def subs[Ctx, Val, StreamSource, Res, Out](
    name: String,
    fieldType: OutputType[Out],
    description: Option[String] = None,
    arguments: List[Argument[_]] = Nil,
    resolve: Context[Ctx, Val] ⇒ StreamSource,
    possibleTypes: ⇒ List[PossibleObject[_, _]] = Nil,
    tags: List[FieldTag] = Nil,
    complexity: Option[(Ctx, Args, Double) ⇒ Double] = None,
    deprecationReason: Option[String] = None
  )(implicit stream: SubscriptionStreamLike[StreamSource, Action, Ctx, Res, Out]) = {
    val s = stream.subscriptionStream

    Field[Ctx, Val](
      Named.checkName(name),
      fieldType,
      description,
      arguments,
      ctx ⇒ SubscriptionValue[Ctx, StreamSource, stream.StreamSource](resolve(ctx), s),
      deprecationReason,
      SubscriptionField[stream.StreamSource](s) +: tags,
      complexity,
      () ⇒ possibleTypes map (_.objectType))
  }
}

@implicitNotFound(msg = "${Res} is invalid type for the resulting GraphQL type ${Out}.")
trait ValidOutType[-Res, +Out]

object ValidOutType {
  private val valid = new ValidOutType[Any, Any] {}

  implicit def validSubclass[Res, Out](implicit ev: Res <:< Out) = valid.asInstanceOf[ValidOutType[Res, Out]]
  implicit def validNothing[Out] = valid.asInstanceOf[ValidOutType[Nothing, Out]]
  implicit def validOption[Res, Out](implicit ev: Res <:< Out) = valid.asInstanceOf[ValidOutType[Res, Option[Out]]]
}

trait InputValue[T] {
  def name: String
  def inputValueType: InputType[_]
  def description: Option[String]
  def defaultValue: Option[(_, ToInput[_, _])]
}

case class Argument[T](
    name: String,
    argumentType: InputType[_],
    description: Option[String],
    defaultValue: Option[(_, ToInput[_, _])],
    fromInput: FromInput[_]) extends InputValue[T] with Named {

  if (!argumentType.isInstanceOf[OptionInputType[_]] && defaultValue.isDefined)
    throw new IllegalArgumentException(s"Argument '$name' is has NotNull type and defines a default value, which is not allowed! You need to either make this argument nullable or remove the default value.")

  def inputValueType = argumentType
}

object Argument {
  def apply[T, Default](
      name: String,
      argumentType: InputType[T],
      description: String,
      defaultValue: Default)(implicit toInput: ToInput[Default, _], fromInput: FromInput[T], res: ArgumentType[T]): Argument[res.Res] =
    Argument(Named.checkName(name), argumentType, Some(description), Some(defaultValue → toInput), fromInput)

  def apply[T, Default](
      name: String,
      argumentType: InputType[T],
      defaultValue: Default)(implicit toInput: ToInput[Default, _], fromInput: FromInput[T], res: ArgumentType[T]): Argument[res.Res] =
    Argument(Named.checkName(name), argumentType, None, Some(defaultValue → toInput), fromInput)

  def apply[T](
      name: String,
      argumentType: InputType[T],
      description: String)(implicit fromInput: FromInput[T], res: WithoutInputTypeTags[T]): Argument[res.Res] =
    Argument(Named.checkName(name), argumentType, Some(description), None, fromInput)

  def apply[T](
      name: String,
      argumentType: InputType[T])(implicit fromInput: FromInput[T], res: WithoutInputTypeTags[T]): Argument[res.Res] =
    Argument(Named.checkName(name), argumentType, None, None, fromInput)

  def createWithoutDefault[T](
      name: String,
      argumentType: InputType[T],
      description: Option[String])(implicit fromInput: FromInput[T], res: ArgumentType[T]): Argument[res.Res] =
    Argument(Named.checkName(name), argumentType, description, None, fromInput)

  def createWithDefault[T, Default](
      name: String,
      argumentType: InputType[T],
      description: Option[String],
      defaultValue: Default)(implicit toInput: ToInput[Default, _], fromInput: FromInput[T], res: ArgumentType[T]): Argument[res.Res] =
    Argument(Named.checkName(name), argumentType, description, Some(defaultValue → toInput), fromInput)
}

trait WithoutInputTypeTags[T] {
  type Res
}

object WithoutInputTypeTags extends WithoutInputTypeTagsLowPrio {
  implicit def coercedArgTpe[T] = new WithoutInputTypeTags[T @@ CoercedScalaResult] {
    type Res = T
  }

  implicit def coercedOptArgTpe[T] = new WithoutInputTypeTags[Option[T @@ CoercedScalaResult]] {
    type Res = Option[T]
  }

  implicit def coercedSeqOptArgTpe[T] = new WithoutInputTypeTags[Seq[Option[T @@ CoercedScalaResult]]] {
    type Res = Seq[Option[T]]
  }

  implicit def coercedOptSeqArgTpe[T] = new WithoutInputTypeTags[Option[Seq[T @@ CoercedScalaResult]]] {
    type Res = Option[Seq[T]]
  }

  implicit def coercedOptSeqOptArgTpe[T] = new WithoutInputTypeTags[Option[Seq[Option[T @@ CoercedScalaResult]]]] {
    type Res = Option[Seq[Option[T]]]
  }

  implicit def ioArgTpe[T] = new WithoutInputTypeTags[T @@ InputObjectResult] {
    type Res = T
  }

  implicit def ioOptArgTpe[T] = new WithoutInputTypeTags[Option[T @@ InputObjectResult]] {
    type Res = Option[T]
  }

  implicit def ioSeqOptArgTpe[T] = new WithoutInputTypeTags[Seq[Option[T @@ InputObjectResult]]] {
    type Res = Seq[Option[T]]
  }

  implicit def ioOptSeqArgTpe[T] = new WithoutInputTypeTags[Option[Seq[T @@ InputObjectResult]]] {
    type Res = Option[Seq[T]]
  }

  implicit def ioOptSeqOptArgTpe[T] = new WithoutInputTypeTags[Option[Seq[Option[T @@ InputObjectResult]]]] {
    type Res = Option[Seq[Option[T]]]
  }
}

trait WithoutInputTypeTagsLowPrio {
  implicit def defaultArgTpe[T] = new WithoutInputTypeTags[T] {
    type Res = T
  }
}

trait ArgumentType[T] {
  type Res
}

object ArgumentType extends ArgumentTypeLowPrio {
  implicit def coercedArgTpe[T] = new ArgumentType[T @@ CoercedScalaResult] {
    type Res = T
  }

  implicit def coercedOptArgTpe[T] = new ArgumentType[Option[T @@ CoercedScalaResult]] {
    type Res = T
  }

  implicit def coercedSeqOptArgTpe[T] = new ArgumentType[Seq[Option[T @@ CoercedScalaResult]]] {
    type Res = Seq[Option[T]]
  }

  implicit def coercedOptSeqArgTpe[T] = new ArgumentType[Option[Seq[T @@ CoercedScalaResult]]] {
    type Res = Seq[T]
  }

  implicit def coercedOptSeqOptArgTpe[T] = new ArgumentType[Option[Seq[Option[T @@ CoercedScalaResult]]]] {
    type Res = Seq[Option[T]]
  }

  implicit def ioArgTpe[T] = new ArgumentType[T @@ InputObjectResult] {
    type Res = T
  }

  implicit def ioOptArgTpe[T] = new ArgumentType[Option[T @@ InputObjectResult]] {
    type Res = T
  }

  implicit def ioSeqOptArgTpe[T] = new ArgumentType[Seq[Option[T @@ InputObjectResult]]] {
    type Res = Seq[Option[T]]
  }

  implicit def ioOptSeqArgTpe[T] = new ArgumentType[Option[Seq[T @@ InputObjectResult]]] {
    type Res = Seq[T]
  }

  implicit def ioOptSeqOptArgTpe[T] = new ArgumentType[Option[Seq[Option[T @@ InputObjectResult]]]] {
    type Res = Seq[Option[T]]
  }
}

trait ArgumentTypeLowPrio extends ArgumentTypeLowestPrio {
  implicit def optionArgTpe[T] = new ArgumentType[Option[T]] {
    type Res = T
  }
}

trait ArgumentTypeLowestPrio {
  implicit def defaultArgTpe[T] = new ArgumentType[T] {
    type Res = T
  }
}

case class EnumType[T](
    name: String,
    description: Option[String] = None,
    values: List[EnumValue[T]]) extends InputType[T @@ CoercedScalaResult] with OutputType[T] with LeafType with NullableType with UnmodifiedType with Named {
  Named.checkName(name)

  lazy val byName = values groupBy (_.name) mapValues (_.head)
  lazy val byValue = values groupBy (_.value) mapValues (_.head)

  def coerceUserInput(value: Any): Either[Violation, (T, Boolean)] = value match {
    case name: String ⇒ byName get name map (v ⇒ Right(v.value → v.deprecationReason.isDefined)) getOrElse Left(EnumValueCoercionViolation(name))
    case v if byValue exists (_._1 == v) ⇒ Right(v.asInstanceOf[T] → byValue(v.asInstanceOf[T]).deprecationReason.isDefined)
    case _ ⇒ Left(EnumCoercionViolation)
  }

  def coerceInput(value: ast.Value): Either[Violation, (T, Boolean)] = value match {
    case ast.EnumValue(name, _, _) ⇒ byName get name map (v ⇒ Right(v.value → v.deprecationReason.isDefined)) getOrElse Left(EnumValueCoercionViolation(name))
    case _ ⇒ Left(EnumCoercionViolation)
  }

  def coerceOutput(value: T): String = byValue(value).name
}

case class EnumValue[+T](
  name: String,
  description: Option[String] = None,
  value: T,
  deprecationReason: Option[String] = None) extends Named with HasDeprecation

case class InputObjectType[T](
  name: String,
  description: Option[String] = None,
  fieldsFn: () ⇒ List[InputField[_]]
) extends InputType[T @@ InputObjectResult] with NullableType with UnmodifiedType with Named {
  lazy val fields = fieldsFn()
  lazy val fieldsByName = fields groupBy(_.name) mapValues(_.head)
}

object InputObjectType {
  type DefaultInput = Map[String, Any]

  def apply[T](name: String, fields: List[InputField[_]])(implicit res: InputObjectDefaultResult[T]): InputObjectType[res.Res] =
    InputObjectType(Named.checkName(name), None, fieldsFn = Named.checkIntFieldsFn(fields))
  def apply[T](name: String, description: String, fields: List[InputField[_]])(implicit res: InputObjectDefaultResult[T]): InputObjectType[res.Res] =
    InputObjectType(Named.checkName(name), Some(description), fieldsFn = Named.checkIntFieldsFn(fields))

  def apply[T](name: String, fieldsFn: () ⇒ List[InputField[_]])(implicit res: InputObjectDefaultResult[T]): InputObjectType[res.Res] =
    InputObjectType(Named.checkName(name), None, Named.checkIntFields(fieldsFn))
  def apply[T](name: String, description: String, fieldsFn: () ⇒ List[InputField[_]])(implicit res: InputObjectDefaultResult[T]): InputObjectType[res.Res] =
    InputObjectType(Named.checkName(name), Some(description), Named.checkIntFields(fieldsFn))

  def createFromMacro[T](name: String, description: Option[String] = None, fieldsFn: () ⇒ List[InputField[_]]) =
    InputObjectType[T](Named.checkName(name), description, Named.checkIntFields(fieldsFn))
}

trait InputObjectDefaultResult[T] {
  type Res
}

object InputObjectDefaultResult extends InputObjectDefaultResultLowPrio {
  implicit def nothingResult = new InputObjectDefaultResult[Nothing] {
    override type Res = InputObjectType.DefaultInput
  }
}

trait InputObjectDefaultResultLowPrio {
  implicit def defaultResult[T] = new InputObjectDefaultResult[T] {
    override type Res = T
  }
}

case class InputField[T](
  name: String,
  fieldType: InputType[T],
  description: Option[String],
  defaultValue: Option[(_, ToInput[_, _])]
) extends InputValue[T] with Named {
  if (!fieldType.isInstanceOf[OptionInputType[_]] && defaultValue.isDefined)
    throw new IllegalArgumentException(s"Input field '$name' is has NotNull type and defines a default value, which is not allowed! You need to either make this fields nullable or remove the default value.")

  def inputValueType = fieldType
}

object InputField {
  def apply[T, Default](name: String, fieldType: InputType[T], description: String, defaultValue: Default)(implicit toInput: ToInput[Default, _], res: WithoutInputTypeTags[T]): InputField[res.Res] =
    InputField(name, fieldType, Some(description), Some(defaultValue → toInput)).asInstanceOf[InputField[res.Res]]

  def apply[T, Default](name: String, fieldType: InputType[T], defaultValue: Default)(implicit toInput: ToInput[Default, _], res: WithoutInputTypeTags[T]): InputField[res.Res] =
    InputField(name, fieldType, None, Some(defaultValue → toInput)).asInstanceOf[InputField[res.Res]]

  def apply[T](name: String, fieldType: InputType[T], description: String)(implicit res: WithoutInputTypeTags[T]): InputField[res.Res] =
    InputField(name, fieldType, Some(description), None).asInstanceOf[InputField[res.Res]]

  def apply[T](name: String, fieldType: InputType[T])(implicit res: WithoutInputTypeTags[T]): InputField[res.Res] =
    InputField(name, fieldType, None, None).asInstanceOf[InputField[res.Res]]

  def createFromMacroWithDefault[T, Default](
    name: String, fieldType: InputType[T], description: Option[String], defaultValue: Default
  )(implicit toInput: ToInput[Default, _], res: WithoutInputTypeTags[T]): InputField[res.Res] =
    InputField(name, fieldType, description, Some(defaultValue → toInput)).asInstanceOf[InputField[res.Res]]

  def createFromMacroWithoutDefault[T](name: String, fieldType: InputType[T], description: Option[String])(implicit res: WithoutInputTypeTags[T]): InputField[res.Res] =
    InputField(name, fieldType, description, None).asInstanceOf[InputField[res.Res]]
}

case class ListType[T](ofType: OutputType[T]) extends OutputType[Seq[T]] with NullableType
case class ListInputType[T](ofType: InputType[T]) extends InputType[Seq[T]] with NullableType

case class OptionType[T](ofType: OutputType[T]) extends OutputType[Option[T]]
case class OptionInputType[T] (ofType: InputType[T]) extends InputType[Option[T]]

sealed trait HasArguments {
  def arguments: List[Argument[_]]
}

object DirectiveLocation extends Enumeration {
  // Operations

  val Query = Value
  val Mutation = Value
  val Subscription = Value
  val Field = Value
  val FragmentDefinition = Value
  val FragmentSpread = Value
  val InlineFragment = Value

  // Schema Definitions

  val Schema = Value
  val Scalar = Value
  val Object = Value
  val FieldDefinition = Value
  val ArgumentDefinition = Value
  val Interface = Value
  val Union = Value
  val Enum = Value
  val EnumValue = Value
  val InputObject = Value
  val InputFieldDefinition = Value

  def fromString(location: String): DirectiveLocation.Value = location match {
    case "QUERY" ⇒ Query
    case "MUTATION" ⇒ Mutation
    case "SUBSCRIPTION" ⇒ Subscription
    case "FIELD" ⇒ Field
    case "FRAGMENT_DEFINITION" ⇒ FragmentDefinition
    case "FRAGMENT_SPREAD" ⇒ FragmentSpread
    case "INLINE_FRAGMENT" ⇒ InlineFragment

    case "SCHEMA" ⇒ Schema
    case "SCALAR" ⇒ Scalar
    case "OBJECT" ⇒ Object
    case "FIELD_DEFINITION" ⇒ FieldDefinition
    case "ARGUMENT_DEFINITION" ⇒ ArgumentDefinition
    case "INTERFACE" ⇒ Interface
    case "UNION" ⇒ Union
    case "ENUM" ⇒ Enum
    case "ENUM_VALUE" ⇒ EnumValue
    case "INPUT_OBJECT" ⇒ InputObject
    case "INPUT_FIELD_DEFINITION" ⇒ InputFieldDefinition
  }
}

case class Directive(
  name: String,
  description: Option[String] = None,
  arguments: List[Argument[_]] = Nil,
  locations: Set[DirectiveLocation.Value] = Set.empty,
  shouldInclude: DirectiveContext ⇒ Boolean) extends HasArguments with Named

case class Schema[Ctx, Val](
    query: ObjectType[Ctx, Val],
    mutation: Option[ObjectType[Ctx, Val]] = None,
    subscription: Option[ObjectType[Ctx, Val]] = None,
    additionalTypes: List[Type with Named] = Nil,
    directives: List[Directive] = BuiltinDirectives,
    validationRules: List[SchemaValidationRule] = SchemaValidationRule.default) {
  def extend(document: ast.Document, builder: AstSchemaBuilder[Ctx] = AstSchemaBuilder.default[Ctx]): Schema[Ctx, Val] =
    AstSchemaMaterializer.extendSchema(this, document, builder)

  def compare(oldSchema: Schema[_, _]): Vector[SchemaChange] =
    SchemaComparator.compare(oldSchema, this)

  lazy val types: Map[String, (Int, Type with Named)] = {
    def sameType(t1: Type, t2: Type) =
      t1.getClass.getSimpleName == t2.getClass.getSimpleName

    def typeConflict(name: String, t1: Type, t2: Type, parentInfo: String) =
      throw SchemaValidationException(ConflictingTypeDefinitionViolation(
        name, t1.getClass.getSimpleName :: t2.getClass.getSimpleName :: Nil, parentInfo) :: Nil)

    def updated(priority: Int, name: String, tpe: Type with Named, result: Map[String, (Int, Type with Named)], parentInfo: String) =
      result get name match {
        case Some(found) if !sameType(found._2, tpe) ⇒ typeConflict(name, found._2, tpe, parentInfo)
        case Some(_) ⇒ result
        case None ⇒ result.updated(name, priority → tpe)
      }

    def collectTypes(parentInfo: String, priority: Int, tpe: Type, result: Map[String, (Int, Type with Named)]): Map[String, (Int, Type with Named)] = {
      tpe match {
        case null ⇒ throw new IllegalStateException(
          s"A `null` value was provided instead of type for $parentInfo.\n" +
          "This can happen if you have recursive type definition or circular references within your type graph.\n" +
          "Please use no-arg function to provide fields for such types.\n" +
          "You can find more info in the docs: http://sangria-graphql.org/learn/#circular-references-and-recursive-types")
        case t: Named if result contains t.name ⇒
          result get t.name match {
            case Some(found) if !sameType(found._2, t) ⇒ typeConflict(t.name, found._2, t, parentInfo)
            case _ ⇒ result
          }
        case OptionType(ofType) ⇒ collectTypes(parentInfo, priority, ofType, result)
        case OptionInputType(ofType) ⇒ collectTypes(parentInfo, priority, ofType, result)
        case ListType(ofType) ⇒ collectTypes(parentInfo, priority, ofType, result)
        case ListInputType(ofType) ⇒ collectTypes(parentInfo, priority, ofType, result)

        case t @ ScalarType(name, _, _, _, _, _, _) ⇒ updated(priority, name, t, result, parentInfo)
        case t @ EnumType(name, _, _) ⇒ updated(priority, name, t, result, parentInfo)
        case t @ InputObjectType(name, _, _) ⇒
          t.fields.foldLeft(updated(priority, name, t, result, parentInfo)) {
            case (acc, field) ⇒
              collectTypes(s"a field '${field.name}' of '$name' input object type", priority, field.fieldType, acc)
          }
        case t: ObjectLikeType[_, _] ⇒
          val own = t.fields.foldLeft(updated(priority, t.name, t, result, parentInfo)) {
            case (acc, field) ⇒
              val fromArgs = field.arguments.foldLeft(collectTypes(s"a field '${field.name}' of '${t.name}' type", priority, field.fieldType, acc)) {
                case (aacc, arg) ⇒ collectTypes(s"an argument '${arg.name}' defined in field '${field.name}' of '${t.name}' type", priority, arg.argumentType, aacc)
              }

              field.manualPossibleTypes().foldLeft(fromArgs) {
                case (acc, objectType) ⇒ collectTypes(s"a manualPossibleType defined in '${t.name}' type", priority, objectType, acc)
              }
          }

          val withPossible = t match {
            case i: InterfaceType[_, _] ⇒
              i.manualPossibleTypes().foldLeft(own) {
                case (acc, objectType) ⇒ collectTypes(s"a manualPossibleType defined in '${i.name}' type", priority, objectType, acc)
              }
            case _ ⇒ own
          }

          t.interfaces.foldLeft(withPossible) {
            case (acc, interface) ⇒ collectTypes(s"an interface defined in '${t.name}' type", priority, interface, acc)
          }
        case t @ UnionType(name, _, types) ⇒
          types.foldLeft(updated(priority, name, t, result, parentInfo)) {case (acc, tpe) ⇒ collectTypes(s"a '$name' type", priority, tpe, acc)}
      }
    }

    val schemaTypes = collectTypes("a '__Schema' type", 30, introspection.__Schema, Map(BuiltinScalars map (s ⇒ s.name → (40 → s)): _*))
    val queryTypes = collectTypes("a query type", 20, query, schemaTypes)
    val queryTypesWithAdditions = additionalTypes.foldLeft(queryTypes){case (acc, tpe) ⇒ collectTypes("additional type", 10, tpe, acc)}
    val queryAndSubTypes = mutation map (collectTypes("a mutation type", 10, _, queryTypesWithAdditions)) getOrElse queryTypesWithAdditions
    val queryAndSubAndMutTypes = subscription map (collectTypes("a subscription type", 10, _, queryAndSubTypes)) getOrElse queryAndSubTypes

    queryAndSubAndMutTypes
  }

  lazy val typeList: List[Type with Named] = types.values.toList.sortBy(t ⇒ t._1 + t._2.name).map(_._2)
  lazy val availableTypeNames: List[String] = typeList map (_.name)

  lazy val allTypes: Map[String, Type with Named] = types collect {case (name, (_, tpe)) ⇒ name → tpe}
  lazy val inputTypes = types collect {case (name, (_, tpe: InputType[_])) ⇒ name → tpe}
  lazy val outputTypes = types collect {case (name, (_, tpe: OutputType[_])) ⇒ name → tpe}
  lazy val scalarTypes = types collect {case (name, (_, tpe: ScalarType[_])) ⇒ name → tpe}
  lazy val unionTypes: Map[String, UnionType[_]] =
    types.filter(_._2._2.isInstanceOf[UnionType[_]]).mapValues(_._2.asInstanceOf[UnionType[_]])

  lazy val directivesByName = directives groupBy (_.name) mapValues (_.head)

  def getInputType(tpe: ast.Type): Option[InputType[_]] = tpe match {
    case ast.NamedType(name, _) ⇒ inputTypes get name map (OptionInputType(_))
    case ast.NotNullType(ofType, _) ⇒ getInputType(ofType) collect {case OptionInputType(ot) ⇒ ot}
    case ast.ListType(ofType, _) ⇒ getInputType(ofType) map (t ⇒ OptionInputType(ListInputType(t)))
  }

  def getInputType(tpe: IntrospectionTypeRef): Option[InputType[_]] = tpe match {
    case IntrospectionNamedTypeRef(_, name) ⇒ inputTypes get name map (OptionInputType(_))
    case IntrospectionNonNullTypeRef(ofType) ⇒ getInputType(ofType) collect {case OptionInputType(ot) ⇒ ot}
    case IntrospectionListTypeRef(ofType) ⇒ getInputType(ofType) map (t ⇒ OptionInputType(ListInputType(t)))
  }

  def getOutputType(tpe: ast.Type, topLevel: Boolean = false): Option[OutputType[_]] = tpe match {
    case ast.NamedType(name, _) ⇒ outputTypes get name map (ot ⇒ if (topLevel) ot else OptionType(ot))
    case ast.NotNullType(ofType, _) ⇒ getOutputType(ofType) collect {case OptionType(ot) ⇒ ot}
    case ast.ListType(ofType, _) ⇒ getOutputType(ofType) map (ListType(_))
  }

  lazy val directImplementations: Map[String, List[ObjectLikeType[_, _]]] = {
    typeList
      .collect{case objectLike: ObjectLikeType[_, _] ⇒ objectLike}
      .flatMap(objectLike ⇒ objectLike.interfaces map (_.name → objectLike))
      .groupBy(_._1)
      .mapValues(_ map (_._2))
  }

  lazy val implementations: Map[String, List[ObjectType[_, _]]] = {
    def findConcreteTypes(tpe: ObjectLikeType[_, _]): List[ObjectType[_, _]] = tpe match {
      case obj: ObjectType[_, _] ⇒ obj :: Nil
      case interface: InterfaceType[_, _] ⇒ directImplementations(interface.name) flatMap findConcreteTypes
    }

    directImplementations map {
      case (name, directImpls) ⇒ name → directImpls.flatMap(findConcreteTypes).groupBy(_.name).map(_._2.head).toList
    }
  }

  lazy val possibleTypes: Map[String, List[ObjectType[_, _]]] =
    implementations ++ unionTypes.values.map(ut ⇒ ut.name → ut.types)

  def isPossibleType(baseTypeName: String, tpe: ObjectType[_, _]) =
    possibleTypes get baseTypeName exists (_ exists (_.name == tpe.name))

  val validationErrors = validationRules flatMap (_.validate(this))

  if (validationErrors.nonEmpty) throw SchemaValidationException(validationErrors)
}

object Schema {
  def isBuiltInType(typeName: String) =
    BuiltinScalarsByName.contains(typeName) || IntrospectionTypesByName.contains(typeName)

  def isBuiltInDirective(directiveName: String) =
    BuiltinDirectivesByName.contains(directiveName)

  def isIntrospectionType(typeName: String) =
    IntrospectionTypesByName.contains(typeName)

  def getBuiltInType(typeName: String): Option[Type with Named] =
    BuiltinScalarsByName.get(typeName) orElse IntrospectionTypesByName.get(typeName)

  /**
    * Build a `Schema` for use by client tools.
    *
    * Given the result of a client running the introspection query, creates and
    * returns a `Schema` instance which can be then used with all sangria
    * tools, but cannot be used to execute a query, as introspection does not
    * represent the "resolver", "parse" or "serialize" functions or any other
    * server-internal mechanisms.
    *
    * @param introspectionResult the result of introspection query
    */
  def buildFromIntrospection[T : InputUnmarshaller](introspectionResult: T) =
    IntrospectionSchemaMaterializer.buildSchema[T](introspectionResult)

  /**
    * Build a `Schema` for use by client tools.
    *
    * Given the result of a client running the introspection query, creates and
    * returns a `Schema` instance which can be then used with all sangria
    * tools, but cannot be used to execute a query, as introspection does not
    * represent the "resolver", "parse" or "serialize" functions or any other
    * server-internal mechanisms.
    *
    * @param introspectionResult the result of introspection query
    */
  def buildFromIntrospection[Ctx, T : InputUnmarshaller](introspectionResult: T, builder: IntrospectionSchemaBuilder[Ctx]) =
    IntrospectionSchemaMaterializer.buildSchema[Ctx, T](introspectionResult, builder)

  def buildFromAst(document: ast.Document) =
    AstSchemaMaterializer.buildSchema(document)

  def buildFromAst[Ctx](document: ast.Document, builder: AstSchemaBuilder[Ctx]) =
    AstSchemaMaterializer.buildSchema[Ctx](document, builder)
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class News {
	/**
	 * Returns single news item with specified id
	 * @param integer $id
	 */
	public static function getNewsItemById($id) {
		$id = intval($id);

		if ($id) {
			$db = Db::getConnection();

			$result = $db->query('SELECT * from news WHERE id='.$id);
			$result->setFetchMode(PDO::FETCH_ASSOC);

			$newsItem = $result->fetch();

			return $newsItem;
		}
	}
	/**
	 * Returns an array of news items
	 */
	public static function getNewsList(){
		$db = Db::getConnection();
		$newsList = array();

		$result = $db->query('SELECT id, title, date, short_content, author_name, preview '
			.'FROM news '
			.'ORDER BY date DESC '
			.'LIMIT 10');

		$i = 0;
		while ($row = $result->fetch()){
			$newsList[$i]['id'] = $row['id'];
			$newsList[$i]['title'] = $row['title'];
			$newsList[$i]['date'] = $row['date'];
			$newsList[$i]['short_content'] = $row['short_content'];
			$newsList[$i]['author_name'] = $row['author_name'];
			$newsList[$i]['preview'] = $row['preview'];
			$i++;
		}

		return $newsList;
	}

	public static function getNewsListAll() {
		$db = Db::getConnection();

		$result = $db->query("SELECT * FROM news ORDER BY id ASC");

		$newsList = array();

		$i = 0;
		while ($row = $result->fetch()) {
			$newsList[$i]['id'] = $row['id'];
			$newsList[$i]['title'] = $row['title'];
			$newsList[$i]['date'] = $row['date'];
			$newsList[$i]['short_content'] = $row['short_content'];
			$newsList[$i]['content'] = $row['content'];
			$newsList[$i]['author_name'] = $row['author_name'];
			$newsList[$i]['type'] = $row['type'];
			$newsList[$i]['preview'] = $row['preview'];
			$i++;
		}

		return $newsList;
	}

	public static function createNews($options)
    {
        // Соединение с БД
        $db = Db::getConnection();
        // Текст запроса к БД
        $sql = 'INSERT INTO news '
                . '(title, date, short_content, content, author_name, type)'
                . 'VALUES (:title, :date, :short_content, :content, :author_name, :type)';
        // Получение и возврат результатов. Используется подготовленный запрос
        $result = $db->prepare($sql);
        $result->bindParam(':title', $options['title'], PDO::PARAM_STR);
        $result->bindParam(':date', $options['date'], PDO::PARAM_STR);
        $result->bindParam(':short_content', $options['short_content'], PDO::PARAM_STR);
        $result->bindParam(':content', $options['content'], PDO::PARAM_STR);
        $result->bindParam(':author_name', $options['author_name'], PDO::PARAM_STR);
        $result->bindParam(':type', $options['type'], PDO::PARAM_STR);

        if ($result->execute()) {
            // Если запрос выполенен успешно, возвращаем id добавленной записи
            return $db->lastInsertId();
        }
        else {
        // Иначе возвращаем 0
        	return 0;
    	}
    }

    public static function deleteNewsById($id) {
        // Соединение с БД
        $db = Db::getConnection();
        // Текст запроса к БД
        $sql = 'DELETE FROM news WHERE id = :id';
        // Получение и возврат результатов. Используется подготовленный запрос
        $result = $db->prepare($sql);
        $result->bindParam(':id', $id, PDO::PARAM_INT);
        return $result->execute();
    }

    public static function getImage($id) {
        // Название изображения-пустышки
        $noImage = 'no-image.jpg';
        // Путь к папке с товарами
        $path = '/upload/images/news/';
        // Путь к изображению товара
        $pathToNewsImage = $path . $id . '.jpg';
        if (file_exists($_SERVER['DOCUMENT_ROOT'].$pathToNewsImage)) {
            // Если изображение для товара существует
            // Возвращаем путь изображения товара
            return $pathToNewsImage;
        }
        // Возвращаем путь изображения-пустышки
        return $path . $noImage;
    }

    public static function updateNewsById($id, $options)
	    {
	        // Соединение с БД
	        $db = Db::getConnection();
	        // Текст запроса к БД
	        $sql = "UPDATE news
	            SET
	                title = :title,
	                date = :date,
	                short_content = :short_content,
	                content = :content,
	                author_name = :author_name,
	                type = :type
	            WHERE id = :id";
	        // Получение и возврат результатов. Используется подготовленный запрос
	        $result = $db->prepare($sql);
	        $result->bindParam(':id', $id, PDO::PARAM_INT);
	        $result->bindParam(':title', $options['title'], PDO::PARAM_STR);
	        $result->bindParam(':date', $options['date'], PDO::PARAM_STR);
	        $result->bindParam(':short_content', $options['short_content'], PDO::PARAM_STR);
	        $result->bindParam(':content', $options['content'], PDO::PARAM_STR);
	        $result->bindParam(':author_name', $options['author_name'], PDO::PARAM_STR);
	        $result->bindParam(':type', $options['type'], PDO::PARAM_STR);
	        return $result->execute();
	    }
}
?>


text:
Q: Performance:1 Trigger on INSERT & UPDATE or 2 triggers with one each on INSERT && UPDATE I have a scenario where i need to Implement triggers for Update and Insert DML Operations.
But,I am in a fix whether to implement Update and Insert in one Trigger or
create 2 triggers for Insert and Delete respectively....
Also,please note that in my case I might need to execute multiple insert commands at one go...
Please suggest me for the better option with regards to performance as CODE OPTIMAZATION is a big issue in my project(i mean my client..!!))..

A: I would suggest to create a single Trigger as to create a separate trigger for the UPDATE and the INSERT would become maintenance problem. There is no such performance issue regarding the code optimization.
For performance optimization point of view you can check something like IF EXISTS.

redpajama_set_name: RedPajamaStackExchange


NEWARK, NJ –– State Senator and Newark Deputy Mayor Ronald L. Rice and the Vice Chairman of the Newark Commission of Veteran Affairs James Collura will join NJ TRANSIT Executive Director George D. Warrington and veterans at a ceremony to dedicate the old Broadway Street Station on the Newark City Subway (NCS) to veterans and rename the stop Military Park Station.
The newly named station, located on the corner of Raymond Boulevard and Park Place, is across the street from Military Park. The park was designed as a training place for soldiers when the city was planned in 1667.
WHEN: Thursday, November 11, 2004 at 10 a.m.


text:
Home World Middle East News Fadhil Ahmad al-Hayali: ISIS Deputy Leader Killed in US Airstrike in Iraq
Fadhil Ahmad al-Hayali: ISIS Deputy Leader Killed in US Airstrike in Iraq
ISIS deputy leader Fadhil Ahmad al-Hayali has been killed in a US military strike in northern Iraq, the White House announces.
Fadhil Ahmad al-Hayali, also known as Hajji Mutazz, is described by US officials as the second in command of the group.
They said he was killed in an attack on his car in Mosul on August 18, and that his death would damage ISIS operations.
A number of ISIS leaders have been killed by US-led air coalition strikes in both Iraq and Syria in recent months.
Fadhil Ahmad al-Hayali was a primary co-ordinator for moving large amounts of weapons, explosives, vehicles and people between Iraq and Syria, the US National Security Council's Ned Price said in a statement.
In Iraq, Fadhil Ahmad al-Hayali was "instrumental in planning operations over the past two years, including the IS offensive in Mosul in June 2014", Ned Price said.
Photo NY Times
Fadhil Ahmad al-Hayali is described as "the senior deputy" to ISIS leader Abu Bakr al-Baghdadi, who was reportedly seriously injured in another air strike by the US-led coalition in March 2014.
"Hayali's death will adversely impact IS's operations given that his influence spanned IS's finance, media, operations, and logistics," Ned Price added.
A second ISIS member who co-ordinated media, known as Abu Abdullah, was killed in the same air strike as Fadhil Ahmad al-Hayali.
It comes several months after Iraqi defence officials declared another "IS second-in-command", Abdul Rahman Mustafa Mohammed, dead in an air strike in northern Iraq.
Abdul Rahman Mustafa Mohammed, also known as Abu Alaa al-Afari, was killed inside a mosque hit by a strike in Tal Afar in May, they reported.
At the time, there were unconfirmed reports Abu Alaa al-Afari had taken temporary charge of ISIS operations amid reports its leader, Abu Bakr al-Baghdadi had become incapacitated.
In June 2015, the US reported that more than 10,000 IS fighters had been killed since the international coalition began its campaign against the group last summer.
Fadhil Ahmad al-Hayali
isis leader
New York Lawyer Requests Game of Thrones-style Trial by Combat
French Train Attack: Americans Hailed as Heroes for Overpowering Gunman
Roy Siemens
Roy likes politics. Knowledge is power, Roy constantly says, so he spends nearly all day gathering information and writing articles about the latest events around the globe. He likes history and studying about war techniques, this is why he finds writing his articles a piece of cake. Another hobby of his is horse – riding.
Leolah Brown claims Nick Gordon is under investigation for Bobbi Kristina attempted murder in letter to Dr Phil
Bobbi Kristina Brown's aunt Leolah Brown claims Nick Gordon is "under investigation for [Bobbi Kristina] attempted murder" in a new …Read More »
Wade Michael Page identified as Wisconsin Sikh temple gunman
The gunman suspected of shooting six people dead at a Sikh temple in Wisconsin on Sunday has been identified as …Read More »
Felix Baumgartner set to break sound barrier at Red Bull Stratos 2012
Felix Baumgartner will attempt to become the first human to break the sound barrier unaided by a vehicle. The Austrian …Read More »
McDonald's China Opens Outlet in Ex-Taiwan President's Residence
McDonald's China has sparked controversy after the opening of a outlet in the home of former Taiwanese leader Chiang Ching-kuo …Read More »
CeeLo Green will not be performing at BayFest 2014
BayFest music festival in Mobile, Alabama, has canceled CeeLo Green's appearance following his online comments about assault. BayFest CEO Bobby …Read More »

redpajama_set_name: RedPajamaCommonCrawl


text:
Wheels 2014
Current: Best Compact: Volkwagen Golf
Best Compact: Volkwagen Golf
The compact segment is littered with choice but picking a winner was a relatively straight forward decision
By Imran Malik, Features Writer
Source:Stefan Lindeque/ANM
It isn't just about massive SUVs here in the UAE — even though they probably make up the largest percentage of vehicles on our roads. No, there are other cars here too — and no, I don't mean supercars either. You see, sitting in between 458 Italias and Land Cruisers are your everyday cars. Compacts, if you will. Designed to get you from here to there without a fuss and without costing a packet in the process. The budget buyer has to make the right choice and his/her hard-earned dirhams have to be put in the right place. Fortunately, there is plenty of choice and we narrowed it down to three we felt offered the best value for money; the Volkswagen Golf, Toyota Yaris saloon and Kia Cerato.
The Yaris is much loved in these parts and the hatch has been joined by the new body style. But its below-average dynamics and ageing drivetrain (it still comes with a four-speed auto, where rivals offer six-speeds...) means it is dropped from the list rather sharpish.
The battle is now between the Kia Cerato and Mk7 Golf. Good looking, comfortable and great value for money (its 2.0-litre four cylinder makes a healthy 159bhp and it has a very roomy cabin), the Kia is a great option. In a recent wheels comparative test, it beat four of its rivals purely due to the fact that it's so well equipped. But the VW wasn't part of that group test…
Now into its seventh generation and showing no signs of abating, it is all the car you'll ever need. Built to last with exquisite German know-how and engineered to perfection, the Golf has it all: superb ride, roomy cabin, and it's loaded to the hilt.
But we're petrolheads, and the thing that sways it for us is the Golf's chassis. It's properly good fun to drive; an area where its Far Eastern rival doesn't even come close with its soggy dynamics. You'll be hunting highway off-ramps and roundabouts all day in the Golf.
It's lighter than the previous gen yet looks remarkably similar (the boxy shape doesn't really need changing — it's iconic and we all love it). Its 1.4-litre TSI packs 138bhp and 250Nm of torque.
Compared to the other two, this feels like a proper driver's car. The DSG is snappy and the steering is far sharper than either the Kia or Toyota.
The ride quality is also much better, and while the Cerato and Yaris get noisy at highway speeds, the Golf is serene there and beyond. Sure, it's more expensive, but it looks and feels premium. It's a worthy winner.
2018 Volkswagen Golf R review: All the car you'll need
Wolfsburg gives its quintessential hot hatch a mid-cycle update. Does it make the best better?
Jonathan Flender and his 2015 VW Golf R and 2008 Honda S2000
Jonathan loves hot hatches and has owned several in the past. Now he has a fabulous Volkswagen Golf R and one of the best handling sportcars ever built, a Honda S2000. He tells us all about both of his awesome rides
2020 Volkswagen Golf spied
Upcoming eighth-generation hatchback spotted totally undisguised
2002 Volkswagen Golf R32
The precursor to the modern-day VW super hatch is getting rarer than hens' teeth
The making of 2017 wheels Car of the Year
The wheels team is bickering again and there can only be one reason why. yep, it's the 2017 car of the year. with so many different opinions, this is going to be a challenging but exciting ride as we reveal our winners...


text:
Research to improve health equity and outcomes
Return to annual report
Innovating for the future | Research
Each day, our vision of health for a better world is made more tangible through comprehensive investments that are informed by community voices. During the pandemic, our Providence Research Network teams saw opportunities to solve problems by collaborating in new and nimble ways, and by connecting more deeply with community organizations. Innovative work done by the Providence Research Network in 2021 produced vital research findings on the impact of COVID-19 and on health disparities, bringing knowledge and hope to our patients.
Learn more about the Providence Research Network and read its 2021 annual report.
My COVID Diary Study: Citizen scientists track long COVID symptoms
Early in the pandemic, Providence's research team began the My COVID diary study, which continued into 2021 and ultimately engaged about 15,000 participants to understand the impact of COVID-19, especially among those who experienced long and difficult recoveries. The study gathered an immense amount of qualitative data that helped inform other COVID research and reflects a period in which researchers, clinicians and patients were all learning about the virus in real time.
My COVID diary invited participants to be citizen scientists. It was an opportunity to put patients' voices at the center of research. "This journaling-based study seeks to understand the experience of COVID through the voices of those who experienced it firsthand: not just the symptoms, but how it affected their lives," shares Bill Wright, Ph.D., vice president of Innovation and Research at Providence.
Patients who received a positive COVID-19 test were contacted by text message or phone call and invited to participate in My COVID diary via a phone-based application. The study sent out occasional surveys and reminders to participants on the app, encouraging them to log their symptoms.
"We have to do research closer to communities we serve, engage them as partners, not subjects, and understand their health concerns in the context of their own lives." - Bill Wright, Ph.D., vice president, Innovation and Research at Providence.
Dr. Wright also notes that studies such as My COVID Diary allow Providence to translate a large amount of data into clear insights that benefit patients and entire communities. "Beyond the clinical, we can see from this study the effect on people's lives and emotions. We have to do research closer to communities we serve, engage them as partners, not subjects, and understand their health concerns in the context of their own lives," says Wright.
The My COVID diary study complements other important Providence research, such as a study led by the Institute for Systems Biology, published in early 2022 by Cell, to increase our knowledge of the causes, characteristics, and consequences of long COVID.
A collaborative team spanning Providence's clinical analytics team, the Center for Outcomes Research and Education, or CORE, and our health research accelerator continues to work with the data. The team uses coding and artificial intelligence natural language processing technology to help analyze patterns of what was reported.
Learn more about CORE and read the team's 2021 CORE annual report.
Southern California: Research supports Standup to Cancer partnership
Collaborations with other organizations in our communities are as important in research as in our clinical and community service work. In October 2021, we joined forces with Stand Up To Cancer®, SU2C, and Exact Sciences to create and fund a new 'Dream Team' dedicated to reducing colorectal cancer disparities. With more than 50,000 deaths per year, colorectal cancer is the second most common cause of cancer deaths in the U.S. and has a disproportionate impact on medically under-resourced communities, including communities of color.
The SU2C Colorectal Cancer Health Equity Dream Team received financial support from Providence to embark on an innovative and comprehensive partnership, including $2 million for research. Together, leading researchers, patient advocates, community leaders and clinicians share several goals, including increasing colorectal cancer screening in medically underserved communities.
Among communities of color, colorectal cancer incidence and deaths are highest among Black Americans, followed closely by Indigenous Americans/Alaska Natives. Another area of inequity is that people with the lowest socioeconomic status are 40 percent more likely to be diagnosed with colorectal cancer than those with the highest socioeconomic status. During the course of the pandemic, screenings for colorectal cancer have significantly decreased especially among these populations.
One of The Dream Team's leaders is Anton Bilchik, M.D., Ph.D., MBA, FACS, who is based at Providence Saint John's Health Center in Los Angeles. He and others on the leadership team bring a deep understanding of racial and health inequities within communities of color. Providence Saint John's is partnering with our health research accelerator to advance this important project.
Local Community Health Action Teams will work as health promoters and care navigators in their own neighborhoods to increase colorectal cancer screening rates in diverse areas of Los Angeles. CHATs will also be collecting data to feed into research.
Under the leadership of Dr. Bilchik, and supported by community-based research, Providence is deploying a locally-focused campaign to increase colorectal cancer screening rates in demographically diverse areas within Los Angeles County. Essential to the plan are Community Health Action Teams. These teams will be made up of local residents trained and supported to work as health promoters and care navigators in their own neighborhoods. CHATs will also be collecting data to feed into research that will help Providence Saint John's clinicians understand how to strengthen and replicate the impacts of the approach. Our research team is proud to be a collaborator in this important campaign.
Using our scale for good
Successes in research from 2021 emphasized the benefits of creating accelerated processes to launch research quickly. We learned that our best work is done when we collaborate and use the scope and reach of our network to achieve clinically useful results and, most importantly, advance health equity for all. Thanks to these networks and a focus on translational and precision medicine, we're able to conduct and scale research that integrates social and personal influences on health. In this way, we can reach our goal of democratizing findings and creating more paths to advance precision medicine at the bedside.
Return to Providence annual report
Why Providence made a bold carbon-negative pledge.
Providence is leading the movement for energy efficiency in health care by with our carbon-negative pledge.
Providence Research Network findings improve health equity and outcomes.
Innovation at scale: Using virtual technology to reach patients and clinicians
Patient interest in receiving virtual care remained strong in 2021, and Providence responded with investments in existing and new telehealth programs.


NEWTOWN -- Reed Intermediate School's celebration of peace Monday was so large it could be seen from the sky. Literally.
T-shirts, joined together to form a human peace sign and the word "peace" on the school's soccer field.
Shannon Hicks, a volunteer from the Sandy Hook Fire Department, got as high as possible, without being in a plane, at the top of a very tall department ladder, and took pictures of what art teacher Angela Choniski called "a human sculpture."
The schedule for the rest of the day was just as large, as students were taught how to convey peace in other visible ways, and in different languages.
Monday was the United Nations' International Day of Peace, and officially kicked off a yearlong celebration.
Performer John Farrell and Maxwell Kofi Donkor, a native Ghanaian and the director of the African Drum and Dance Ensemble Sankofa, taught the students how to say "hello" and "peace" in nine different languages.
"John Farrell lives the life of peace. He is one of the kindest people I know on Earth," said sixth grade teacher Gael Lynch, one of the four who organized the day's events.
The three other teachers were Maura Drabik, Gina Swanson and Mary Faith Zanghi.
Farrell taught the students his original song, called "The Question," which reflected Principal Sharon Epple's yearlong theme of "celebrate peace all year long: What can you do for peace today?" perfectly.
"What can we do to make peace?" the song's lyrics said. "What can we do, what can we say, we want to help make peace today. We know we can find a way, what can we do to make peace?"
"It's not a one day commitment, it's a lifetime commitment," Farrell explained.
The students, and teachers, were receptive to his ideas about peace, as they enthusiastically sang, played instruments and volunteered to lead the giant assembly.
Over 400 students created peace-sign artwork which formed a wall of peace in the school's lobby.
"It doesn't matter where you come from; it doesn't matter the color of your skin -- (peace) starts within you," Donkor said.
Farrell reminded students that even if there is a language gap, peace can be conveyed.
"Try to be very inviting -- put a smile on your face," he said.
He also encouraged people to be more empathetic, by teaching them an original song, "If I wasn't me, I might be you," that he made into a music video with his daughter Katie, who is overseas in the Peace Corps.
One of the most moving events of the day was when the entire assembly sang a song about peace in English and Zulu while performing the lyrics through sign language.
"Make this yearlong project the most you can," Farrell urged, offering students the ability to connect with other students in Africa through pen pal and interactive relationships.
"I believe we will leave together today with more hope and strength to make the world a better place," he said.
Not only will this day remain in the memory of those who experienced it, but the photos taken provide a visual record for students and others to see -- to be reminded of the day, and school year's message.