text
stringlengths 27
775k
|
---|
package io.github.tonnyl.latticify.data.datasource
import io.github.tonnyl.latticify.data.AuthRevokeWrapper
import io.github.tonnyl.latticify.data.AuthTestWrapper
import io.reactivex.Observable
/**
* Created by lizhaotailang on 10/10/2017.
*/
interface AuthDataSource {
fun revoke(test: Int = 1): Observable<AuthRevokeWrapper>
fun test(): Observable<AuthTestWrapper>
}
|
# Configure Rails Environment
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'test/unit'
require 'mocha'
require 'rails/test_help'
require 'mocha/test_unit'
require 'wicked_pdf'
Rails.backtrace_cleaner.remove_silencers!
if (assets_dir = Rails.root.join('app/assets')) && File.directory?(assets_dir)
# Copy CSS file
destination = assets_dir.join('stylesheets/wicked.css')
source = File.read('test/fixtures/wicked.css')
File.open(destination, 'w') { |f| f.write(source) }
# Copy JS file
destination = assets_dir.join('javascripts/wicked.js')
source = File.read('test/fixtures/wicked.js')
File.open(destination, 'w') { |f| f.write(source) }
end
|
#!/bin/bash -ex
rm -f *.csv
rm -f *.png
|
using Ocuda.Promenade.Models.Entities;
namespace Ocuda.Promenade.Controllers.ViewModels.Shared
{
public class CarouselItemViewModel
{
public CarouselItem Item { get; set; }
public string ReturnUrl { get; set; }
}
}
|
package com.eon.opcuapubsubclient.parser
import java.util.UUID
import com.eon.opcuapubsubclient.UnitSpec
import com.eon.opcuapubsubclient.domain.CommonTypes._ //{GuidIdentifier, NumericFourByteIdentifier, StringIdentifier}
import org.scalatest.BeforeAndAfterAll
import scodec.bits.ByteVector
// TODO: Write additional tests for other types
class NodeIdParserSpec extends UnitSpec with BeforeAndAfterAll {
//val numericNodeIdByteSeq: Array[Byte] = toByteArray("")
//val guidNodeIdByteSeq : Array[Byte] = toByteArray("")
//val opaqueNodeIdByteSeq: Array[Byte] = toByteArray("")
"NodeIdParser # parseTwoByteNodeId" should "parse a 2 byte NodeId successfully" in {
val testData1 = toByteArray("00 72")
val (nodeId1, pos1) = NodeIdParser(ByteVector(testData1))(initParsePosition)
assert(nodeId1.namespaceIndex == 0, s"namespaceIndex should be 0, but we got ${nodeId1.namespaceIndex}")
assert(nodeId1.identifier == NumericTwoByteIdentifier(72))
assert(pos1 == testData1.length)
}
"NodeIdParser # parseFourByteNodeId" should "parse a 4 byte NodeId successfully" in {
val testData1 = toByteArray("1 1 1 0")
val (nodeId1, pos1) = NodeIdParser(ByteVector(testData1))(initParsePosition)
assert(pos1 == testData1.length)
assert(nodeId1.namespaceIndex == 1, s"namespaceIndex should be 1, but we got ${nodeId1.namespaceIndex}")
assert(nodeId1.identifier == NumericFourByteIdentifier(1))
val testData2 = toByteArray("01 05 01 04")
val (nodeId2, pos2) = NodeIdParser(ByteVector(testData2))(initParsePosition)
assert(pos2 == testData2.length)
assert(nodeId2.namespaceIndex == 5, s"namespaceIndex should be 5, but we got ${nodeId2.namespaceIndex}")
assert(nodeId2.identifier == NumericFourByteIdentifier(1025))
}
"NodeIdParser # parseStringNodeId" should "parse a string NodeId successfully" in {
val testData1 = toByteArray("03 01 00 06 00 00 00 72 111 74 230 176 180")
val (nodeId1, pos1) = NodeIdParser(ByteVector(testData1))(initParsePosition)
assert(pos1 == testData1.length)
assert(nodeId1.namespaceIndex == 1, s"namespaceIndex should be 1, but we got ${nodeId1.namespaceIndex}")
assert(nodeId1.identifier == StringIdentifier("HoJ水"))
}
// FIXME: This shit does not yet work now!
ignore
"NodeIdParser # parseGuidNodeId" should "parse a Guid NodeId successfully" in {
val testData1 = toByteArray("04 04 00 91 43 96 72 75 250 230 74 141 18 180 04 220 125 175 63")
val (nodeId1, pos1) = NodeIdParser(ByteVector(testData1))(initParsePosition)
assert(pos1 == testData1.length)
assert(nodeId1.namespaceIndex == 4, s"namespaceIndex should be 4, but we got ${nodeId1.namespaceIndex}")
assert(nodeId1.identifier == GuidIdentifier(UUID.fromString("72962B91-FA75-4AE6-8D28-B404DC7DAF63")))
}
"NodeIdParser # parseByteStringNodeId" should "parse a ByteString / Opaque NodeId successfully" in {
val testData1 = toByteArray("05 03 00 8 0 0 0 43 96 72 75 12 15 74 32")
val (nodeId1, pos1) = NodeIdParser(ByteVector(testData1))(initParsePosition)
assert(pos1 == testData1.length)
assert(nodeId1.namespaceIndex == 3, s"namespaceIndex should be 3, but we got ${nodeId1.namespaceIndex}")
assert(nodeId1.identifier == OpaqueIdentifier(toByteArray("43 96 72 75 12 15 74 32").toVector))
}
"NodeIdParser # parseUnknownNodeId" should "parse into an UnknownNodeIdentifier type" in {
val testData1 = toByteArray("06 03 00")
val (nodeId1, pos1) = NodeIdParser(ByteVector(testData1))(initParsePosition)
assert(pos1 == 0) // ParsePosition will not be incremented!
assert(nodeId1.namespaceIndex == 0, s"namespaceIndex should be 0, but we got ${nodeId1.namespaceIndex}")
assert(nodeId1.identifier == UnknownIdentifier)
}
"NodeIdParser # random 1" should "parse into the appropriate NodeId structure" in {
val testData1 = toByteArray("1 0 76 0 1 0 22 0 0 0 0 0")
val (nodeId1, pos1) = NodeIdParser(ByteVector(testData1))(initParsePosition)
assert(pos1 == 4) // ParsePosition will not be incremented!
assert(nodeId1.namespaceIndex == 0, s"namespaceIndex should be 0, but we got ${nodeId1.namespaceIndex}")
assert(nodeId1.identifier == NumericFourByteIdentifier(76))
}
}
|
13
castelliiYDR418W
castelliiYEL054C 0.3519
mikataeYDR418W 0.5750 0.5796
mikataeYEL054C 0.6095 0.6043 0.5080
kluyveriYDR418W 0.4162 0.3750 0.5658 0.6015
paradoxusYDR418W 0.5642 0.5713 0.2325 0.4203 0.5912
paradoxusYEL054C 0.6004 0.5928 0.4953 0.1009 0.5925 0.3848
kudriavzeviiYDR418W 0.5432 0.5160 0.3875 0.2606 0.5287 0.2605 0.2490
kudriavzeviiYEL054C 0.5844 0.5648 0.4697 0.1589 0.5464 0.3979 0.1468 0.1793
bayanusYDR418W 0.4651 0.4474 0.1859 0.4753 0.4504 0.2124 0.4660 0.3239 0.4372
bayanusYEL054C 0.4591 0.4485 0.3738 0.1589 0.4689 0.2895 0.1464 0.1655 0.1392 0.3126
cerevisiaeYDR418W 0.5788 0.5618 0.4243 0.3021 0.6065 0.2258 0.2482 0.2806 0.3095 0.3601 0.2057
cerevisiaeYEL054C 0.6221 0.6229 0.5320 0.1262 0.6065 0.4275 0.0749 0.2957 0.1989 0.5003 0.1854 0.2475
|
module FirstOrder
using LinearAlgebra
import ..LocalDescent:
search,
LineSearch, StrongBacktracking
struct Termination
max_iter
ϵ_abs
ϵ_rel
ϵ_grad
Termination(;
max_iter = 10_000,
ϵ_abs = eps(),
ϵ_rel = eps(),
ϵ_grad = eps()) =
new(max_iter, ϵ_abs, ϵ_rel, ϵ_grad)
Termination(ϵ;
max_iter = 10_000) =
new(max_iter, ϵ, ϵ, ϵ)
end
mutable struct TerminationConditions
abs
rel
grad
TerminationConditions(term::Termination) =
new((fx, fx_next)->fx - fx_next < term.ϵ_abs,
(fx, fx_next)->fx - fx_next < term.ϵ_abs * abs(fx),
∇fx_next->norm(∇fx_next) < term.ϵ_grad)
end
function descent_until(term::Termination, descent_method, f, ∇f, X, trace)
term_cond = TerminationConditions(term)
for _ = 1:term.max_iter
x = X[:, end]
x_next = descent_method(f, ∇f, x)
if trace
X = hcat(X, x_next)
else
X = x_next
end
fx, fx_next, ∇fx_next = f(x), f(x_next), ∇f(x_next)
if term_cond.abs(fx, fx_next) ||
term_cond.rel(fx, fx_next) ||
term_cond.grad(∇fx_next)
return X
end
end
@warn "descent_until: max number of iterations reached"
X
end
abstract type FirstOrderMethods end
# Maximum Gradient Descent
struct MaximumGradientDescent <: FirstOrderMethods end
function search(::MaximumGradientDescent, f, ∇f, x_0; term = Termination(), trace = false)
descent_until(term, descent_step_maxgd, f, ∇f, x_0, trace)
end
function descent_step_maxgd(f, ∇f, x)
"""
Maximum Gradient Descent
A step of maximum gradient descent produces the value of x(k+1)
where f(x) in the direction of maximum descent is at its local
minimum.
"""
g = ∇f(x)
d = direction_maxgd(g)
search(LineSearch(), f, x, d)
end
function direction_maxgd(g)
-g / norm(g)
end
# Gradient Descent
struct GradientDescent <: FirstOrderMethods
α
GradientDescent(; α = 0.001) = new(α)
end
function search(params::GradientDescent, f, ∇f, x_0; term = Termination(), trace = false)
descent_step = (f, ∇f, x)->descent_step_gd(params.α, f, ∇f, x)
descent_until(term, descent_step, f, ∇f, x_0, trace)
end
function descent_step_gd(α, f, ∇f, x)
"""
Gradient Descent
Algorithm 5.1
A step of a gradient descent algorithm with fixed learning rate α.
"""
g = ∇f(x)
x - α * g
end
# Conjugate Gradient Descent
struct ConjugateGradientDescent <: FirstOrderMethods end
mutable struct CGDProblemState
g
d
CGDProblemState(dim) = new(ones(dim), zeros(dim))
end
function search(params::ConjugateGradientDescent, f, ∇f, x_0; term = Termination(), trace = false)
state = CGDProblemState(size(x_0))
descent_step = (f, ∇f, x)->descent_step_cgd!(state, f, ∇f, x)
descent_until(term, descent_step, f, ∇f, x_0, trace)
end
function descent_step_cgd!(state, f, ∇f, x)
"""
Conjugate Gradient Descent
Algorithm 5.2
https://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient_method
"""
g = ∇f(x)
d = direction_cgd(g, state.g, state.d)
state.g = g
state.d = d
search(StrongBacktracking(), f, ∇f, x, d)
end
function direction_cgd(g, gm1, dm1)
"""
Polak-Ribiere update
Notation:
g is for g(k)
dm1 is for d(k-1)
gm1 indicates g(k-1)
"""
β_PR = (g' * (g - gm1)) / (gm1'gm1)
β = max(β_PR, 0)
-g + β * dm1
end
end # module
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TwilioCallsImporter.Data
{
public class Result
{
public string first_page_uri { get; set; }
public int end { get; set; }
public Call[] calls { get; set; }
public object previous_page_uri { get; set; }
public string uri { get; set; }
public int page_size { get; set; }
public int start { get; set; }
public string next_page_uri { get; set; }
public int page { get; set; }
public class Call
{
public string sid { get; set; }
public string date_created { get; set; }
public string date_updated { get; set; }
public object parent_call_sid { get; set; }
public string account_sid { get; set; }
public string to { get; set; }
public string to_formatted { get; set; }
public string from { get; set; }
public string from_formatted { get; set; }
public object phone_number_sid { get; set; }
public string status { get; set; }
public string start_time { get; set; }
public string end_time { get; set; }
public string duration { get; set; }
public string price { get; set; }
public string price_unit { get; set; }
public string direction { get; set; }
public object answered_by { get; set; }
public object annotation { get; set; }
public string api_version { get; set; }
public object forwarded_from { get; set; }
public object group_sid { get; set; }
public string caller_name { get; set; }
public string uri { get; set; }
public Subresource_Uris subresource_uris { get; set; }
}
public class Subresource_Uris
{
public string notifications { get; set; }
public string recordings { get; set; }
}
}
}
|
import model from './model'
import { verify } from '@lib/jwt'
export default {
Query: {
hashtag: async(_, {}, { authorization }) => {
try {
const branchID = verify(authorization).branchID
console.log(authorization)
const { study_center_branch_hashtag: hashtag } = await model.hashtag(branchID)
return hashtag
}
catch(error) {
throw new Error(error)
}
}
}
}
|
package internal
import (
"github.com/go-gl/gl/v4.6-core/gl"
"github.com/mokiat/lacking/framework/opengl"
)
type Presentation struct {
Program *opengl.Program
}
func (p *Presentation) Delete() {
p.Program.Release()
}
type PostprocessingPresentation struct {
Presentation
FramebufferDraw0Location int32
ExposureLocation int32
}
func NewPostprocessingPresentation(vertexSrc, fragmentSrc string) *PostprocessingPresentation {
program := buildProgram(vertexSrc, fragmentSrc)
return &PostprocessingPresentation{
Presentation: Presentation{
Program: program,
},
FramebufferDraw0Location: program.UniformLocation("fbColor0TextureIn"),
ExposureLocation: program.UniformLocation("exposureIn"),
}
}
type SkyboxPresentation struct {
Presentation
ProjectionMatrixLocation int32
ViewMatrixLocation int32
AlbedoCubeTextureLocation int32
}
func NewSkyboxPresentation(vertexSrc, fragmentSrc string) *SkyboxPresentation {
program := buildProgram(vertexSrc, fragmentSrc)
return &SkyboxPresentation{
Presentation: Presentation{
Program: program,
},
ProjectionMatrixLocation: program.UniformLocation("projectionMatrixIn"),
ViewMatrixLocation: program.UniformLocation("viewMatrixIn"),
AlbedoCubeTextureLocation: program.UniformLocation("albedoCubeTextureIn"),
}
}
type ShadowPresentation struct {
Presentation
}
func NewShadowPresentation(vertexSrc, fragmentSrc string) *ShadowPresentation {
program := buildProgram(vertexSrc, fragmentSrc)
return &ShadowPresentation{
Presentation: Presentation{
Program: program,
},
}
}
type GeometryPresentation struct {
Presentation
ProjectionMatrixLocation int32
ModelMatrixLocation int32
ViewMatrixLocation int32
MetalnessLocation int32
RoughnessLocation int32
AlbedoColorLocation int32
AlbedoTextureLocation int32
}
func NewGeometryPresentation(vertexSrc, fragmentSrc string) *GeometryPresentation {
program := buildProgram(vertexSrc, fragmentSrc)
return &GeometryPresentation{
Presentation: Presentation{
Program: program,
},
ProjectionMatrixLocation: program.UniformLocation("projectionMatrixIn"),
ModelMatrixLocation: program.UniformLocation("modelMatrixIn"),
ViewMatrixLocation: program.UniformLocation("viewMatrixIn"),
MetalnessLocation: program.UniformLocation("metalnessIn"),
RoughnessLocation: program.UniformLocation("roughnessIn"),
AlbedoColorLocation: program.UniformLocation("albedoColorIn"),
AlbedoTextureLocation: program.UniformLocation("albedoTwoDTextureIn"),
}
}
type LightingPresentation struct {
Presentation
FramebufferDraw0Location int32
FramebufferDraw1Location int32
FramebufferDepthLocation int32
ProjectionMatrixLocation int32
CameraMatrixLocation int32
ViewMatrixLocation int32
ReflectionTextureLocation int32
RefractionTextureLocation int32
LightDirection int32
LightIntensity int32
}
func NewLightingPresentation(vertexSrc, fragmentSrc string) *LightingPresentation {
program := buildProgram(vertexSrc, fragmentSrc)
return &LightingPresentation{
Presentation: Presentation{
Program: program,
},
FramebufferDraw0Location: program.UniformLocation("fbColor0TextureIn"),
FramebufferDraw1Location: program.UniformLocation("fbColor1TextureIn"),
FramebufferDepthLocation: program.UniformLocation("fbDepthTextureIn"),
ProjectionMatrixLocation: program.UniformLocation("projectionMatrixIn"),
CameraMatrixLocation: program.UniformLocation("cameraMatrixIn"),
ViewMatrixLocation: program.UniformLocation("viewMatrixIn"),
ReflectionTextureLocation: program.UniformLocation("reflectionTextureIn"),
RefractionTextureLocation: program.UniformLocation("refractionTextureIn"),
LightDirection: program.UniformLocation("lightDirectionIn"),
LightIntensity: program.UniformLocation("lightIntensityIn"),
}
}
func buildProgram(vertSrc, fragSrc string) *opengl.Program {
vertexShader := opengl.NewShader()
vertexShader.Allocate(opengl.ShaderAllocateInfo{
ShaderType: gl.VERTEX_SHADER,
SourceCode: vertSrc,
})
defer func() {
vertexShader.Release()
}()
fragmentShader := opengl.NewShader()
fragmentShader.Allocate(opengl.ShaderAllocateInfo{
ShaderType: gl.FRAGMENT_SHADER,
SourceCode: fragSrc,
})
defer func() {
fragmentShader.Release()
}()
program := opengl.NewProgram()
program.Allocate(opengl.ProgramAllocateInfo{
VertexShader: vertexShader,
FragmentShader: fragmentShader,
})
return program
}
|
import { ActivityInterface } from "~/interfaces/activity.interface"
import { Activity } from "../base/activity.model"
import { GPSLocation } from "../base/gps-location.model"
import { MarketTo } from "../market/market-to.model"
class MarketActivity extends Activity {
constructor (
baseActivityData: ActivityInterface,
private readonly marketTo: MarketTo,
private readonly location: GPSLocation
) {
super(baseActivityData, "Pasarkan")
}
get MarketTo(): MarketTo {
return this.marketTo
}
get Location(): GPSLocation {
return this.location
}
}
export {
MarketActivity
}
|
package scala.meta.internal.metals
import scala.meta.Dialect
import scala.meta.dialects._
import scala.meta.internal.mtags
import scala.meta.internal.semver.SemVer
object ScalaVersions {
def isScala3Milestone(version: String): Boolean =
version.startsWith("3.0.0-M") || version.startsWith("3.0.0-RC")
/**
* Non-Lightbend compilers often use a suffix, such as `-bin-typelevel-4`
*/
def dropVendorSuffix(version: String): String =
version.replaceAll("-bin-.*", "")
private val _isDeprecatedScalaVersion: Set[String] =
BuildInfo.deprecatedScalaVersions.toSet
private val _isSupportedScalaVersion: Set[String] =
BuildInfo.supportedScalaVersions.toSet
def isSupportedScalaVersion(version: String): Boolean =
_isSupportedScalaVersion(dropVendorSuffix(version))
def isDeprecatedScalaVersion(version: String): Boolean =
_isDeprecatedScalaVersion(dropVendorSuffix(version))
def isSupportedScalaBinaryVersion(scalaVersion: String): Boolean =
BuildInfo.supportedScalaBinaryVersions.exists { binaryVersion =>
scalaVersion.startsWith(binaryVersion)
}
def isScala3Version(scalaVersion: String): Boolean =
scalaVersion.startsWith("3.")
def supportedScala3Versions: Set[String] =
BuildInfo.supportedScalaVersions.filter(isScala3Version(_)).toSet
val isLatestScalaVersion: Set[String] =
Set(BuildInfo.scala212, BuildInfo.scala213, BuildInfo.scala3)
def latestBinaryVersionFor(scalaVersion: String): Option[String] = {
val binaryVersion = scalaBinaryVersionFromFullVersion(scalaVersion)
isLatestScalaVersion
.find(latest =>
binaryVersion == scalaBinaryVersionFromFullVersion(latest)
)
}
def recommendedVersion(scalaVersion: String): String = {
latestBinaryVersionFor(scalaVersion).getOrElse {
if (isScala3Version(scalaVersion)) {
BuildInfo.scala3
} else {
BuildInfo.scala212
}
}
}
def isFutureVersion(scalaVersion: String): Boolean = {
latestBinaryVersionFor(scalaVersion)
.map(latest =>
latest != scalaVersion && SemVer
.isLaterVersion(latest, scalaVersion)
)
.getOrElse {
val versions =
if (isScala3Version(scalaVersion))
isLatestScalaVersion.filter(isScala3Version)
else
isLatestScalaVersion.filter(!isScala3Version(_))
versions.forall(ver => SemVer.isLaterVersion(ver, scalaVersion))
}
}
def isCurrentScalaCompilerVersion(version: String): Boolean =
ScalaVersions.dropVendorSuffix(
version
) == mtags.BuildInfo.scalaCompilerVersion
def scalaBinaryVersionFromFullVersion(scalaVersion: String): String = {
if (isScala3Milestone(scalaVersion))
scalaVersion
else
scalaVersion.split('.').take(2).mkString(".")
}
def dialectForScalaVersion(scalaVersion: String): Dialect = {
val scalaBinaryVersion = scalaBinaryVersionFromFullVersion(scalaVersion)
scalaBinaryVersion match {
case "2.11" => Scala211
case "2.12" => Scala212
case "2.13" => Scala213
case version if version.startsWith("3.") => Scala3
case _ => Scala213
}
}
}
|
#!/bin/bash
DOCKER_IMAGE_NAME=apple-availability
docker run \
--name $DOCKER_IMAGE_NAME \
-v `pwd`/app:/app \
-it \
--rm \
--env-file SETTINGS \
$DOCKER_IMAGE_NAME "$@"
|
part of vcl;
typedef void TDataChangeEvent(TObject Sender, TField? Field);
typedef void TDataOperation();
enum TFieldAttribute { HiddenCol, Readonly, Required, Link, UnNamed, Fixed }
typedef TFieldAttributes = Set<TFieldAttribute>;
// Misc DataSet types
enum TFieldType { Unknown, Dynamic, String, Integer,
Boolean, Float, Date, Time, DateTime,
AutoInc, ADT, Array, DataSet, }
String DataTypeToString(TFieldType type)
{
switch(type)
{
case TFieldType.AutoInc: return 'AutoInc';
case TFieldType.Boolean: return 'Boolean';
case TFieldType.Date: return 'Date';
case TFieldType.DateTime: return 'DateTime';
case TFieldType.Dynamic: return 'Dynamic';
case TFieldType.Float: return 'Float';
case TFieldType.Integer: return 'Integer';
case TFieldType.String: return 'String';
case TFieldType.Time: return 'Time';
default: return 'Unknown';
}
}
enum TDataSetState { Inactive, Browse, Edit, Insert, SetKey,
BlockRead,
Opening }
enum TDataEvent { FieldChange, RecordChange, DataSetChange, DataSetScroll, LayoutChange,
UpdateRecord, UpdateState, CheckBrowseMode, PropertyChange, FieldListChange,
FocusControl, ParentScroll, ConnectChange,
DataSetReady } // new
// Exception classes
class EDatabaseError extends TException
{
EDatabaseError(String msg) : super(msg);
EDatabaseError.CreateResFmt(String msg, var args) : super.CreateFmt(msg, args);
}
enum TFieldKind { Data, Calculated, Lookup, InternalCalc, Aggregate }
enum TBookmarkFlag { Current, BOF, EOF, Inserted }
enum TGetMode { Current, Next, Prior }
enum TGetResult { OK, BOF, EOF, Error }
enum TDataAction { Fail, Abort, Retry }
enum TLocateOption { CaseInsensitive, PartialKey }
typedef TLocateOptions = Set<TLocateOption>;
typedef TDataSetNotifyEvent(TDataSet DataSet);
typedef TDataSetErrorEvent(TDataSet DataSet, EDatabaseError E, TDataAction Action);
bool StateInEditModes(TDataSetState State)
{
return
State==TDataSetState.Edit ||
State==TDataSetState.Insert ||
State==TDataSetState.SetKey;
}
void DatabaseError(String Message, [TComponent? Component])
{
if((Component!=null) && (Component.Name.isNotEmpty))
throw EDatabaseError(SysUtils.Format('%s: %s', [Component.Name, Message]));
else
throw EDatabaseError(Message);
}
void DatabaseErrorFmt(String Message, var Args, [TComponent? Component])
{
DatabaseError(SysUtils.Format(Message, Args), Component);
}
class TNamedItem extends TCollectionItem
{
String _name = '';
String
get Name => _name;
set Name(String Value) => SetDisplayName(Value);
String GetDisplayName()
{
return _name;
}
void SetDisplayName(String Value)
{
if((Value != '') && (Value != _name) &&
(Collection is TDefCollection) &&
((Collection as TDefCollection).IndexOf(Value) >= 0))
DatabaseErrorFmt(DBConsts.SDuplicateName, [Value, Collection!.ClassName()]);
_name = Value;
super.SetDisplayName(Value);
}
}
typedef void TDefUpdateMethod();
abstract class TDefCollection extends TOwnedCollection
{
late final TDataSet DataSet;
int _internalUpdateCount = 0;
TUnsafeNotifyEvent? _onUpdate;
TUnsafeNotifyEvent?
get OnUpdate => _onUpdate;
set OnUpdate(TUnsafeNotifyEvent? Value) => _onUpdate = Value;
bool _updated = false;
bool
get Updated => _updated;
set Updated(bool Value) => _updated = Value;
TDefCollection(TPersistent? AOwner, TObjectCreator AClass) : super(AOwner, AClass)
{
_onUpdate = DoUpdate;
}
void Update(TCollectionItem? AItem)
{
if(!DataSet.ComponentState.contains(ComponentStates.Loading))
OnUpdate!(AItem);
}
void DoUpdate(dynamic Sender)
{
if(_internalUpdateCount == 0)
{
Updated = false;
DataSet.DefChanged(this);
}
}
void UpdateDefs(TDefUpdateMethod AMethod)
{
if(Updated)
return;
_internalUpdateCount++;
BeginUpdate();
try
{
AMethod();
}
finally
{
EndUpdate();
_internalUpdateCount--;
}
Updated = true; // Defs are now a mirror of data source
}
int IndexOf(String AName)
{
for(int i = 0; i < Count; i++)
if(((_items[i]) as TNamedItem).Name == AName)
return i;
return -1;
}
TNamedItem? Find(String AName)
{
int i = IndexOf(AName);
if(i < 0)
return null;
return _items[i] as TNamedItem;
}
}
class TFieldDef extends TNamedItem
{
TFieldDefs? _childDefs;
int _precision = 0;
int
get Precision => _precision;
set Precision(int Value)
{
_precision = Value;
Changed(false);
}
int _fieldNo = 0;
int
get FieldNo
{
if(_fieldNo > 0)
return _fieldNo;
return Index + 1;
}
set FieldNo(int Value) => _fieldNo = Value;
int _size = 0;
int
get Size
{
if(HasChildDefs() && (_size == 0))
return _childDefs!.Count;
else
return _size;
}
set Size(int Value)
{
if(HasChildDefs() && (DataType != TFieldType.Array))
return;
_size = Value;
Changed(false);
}
TFieldType _dataType = TFieldType.Unknown;
TFieldType
get DataType => _dataType;
set DataType(TFieldType Value)
{
_dataType = Value;
_precision = 0;
switch(_dataType)
{
case TFieldType.String:
_size = 20;
break;
default:
_size = 0;
break;
}
Changed(false);
}
TFieldAttributes _attributes = TFieldAttributes();
TFieldAttributes
get Attributes => _attributes;
set Attributes(TFieldAttributes Value)
{
_attributes = Value;
Changed(false);
}
bool
get Required => Attributes.contains(TFieldAttribute.Required);
set Required(bool Value)
{
if(Value)
Attributes << TFieldAttribute.Required;
else
Attributes >> TFieldAttribute.Required;
}
bool HasChildDefs()
{
return (_childDefs != null) && (_childDefs!.Count > 0);
}
TField CreateFieldComponent(TDataSet Owner, [ TObjectField? ParentField, String FieldName = '' ])
{
TField Result = Owner.CreateTypeField(DataType);
try
{
Result.Size = Size;
if(FieldName != '')
Result.FieldName = FieldName;
else
Result.FieldName = Name;
Result.Required = Attributes.contains(TFieldAttribute.Required);
Result.ReadOnly = Attributes.contains(TFieldAttribute.Readonly);
if(ParentField == null)
Result.DataSet = (Collection as TFieldDefs).DataSet;
}
catch(E)
{
Result.Destroy();
throw E;
}
return Result;
}
TField CreateField(TDataSet Owner, [ TObjectField? ParentField, String FieldName='', bool CreateChildren = true ])
{
TField Result = CreateFieldComponent(Owner, ParentField, FieldName);
return Result;
}
}
class TFieldDefs extends TDefCollection
{
late final TFieldDef? _parentDef;
late final TItems<TFieldDef> _fields;
TItems<TFieldDef> get Items => _fields;
TFieldDefs(TPersistent AOwner) : super(AOwner, (Sender) => TFieldDef())
{
_fields = TItems<TFieldDef>.from(super.Items);
if(AOwner is TFieldDef)
{
_parentDef = AOwner;
DataSet = (_parentDef!.Collection as TFieldDefs).DataSet;
}
else
{
_parentDef = null;
DataSet = AOwner as TDataSet;
}
}
TFieldDef AddFieldDef()
{
return super.Add() as TFieldDef;
}
void AddEx(String FieldName, TFieldType DataType, [ int Size=0, bool Required=false ])
{
if(FieldName == "")
DatabaseError(DBConsts.SFieldNameMissing, DataSet);
BeginUpdate();
try
{
TFieldDef FieldDef = AddFieldDef();
try
{
// FieldNo is defaulted
FieldDef.Name = FieldName;
FieldDef.DataType = DataType;
FieldDef.Size = Size;
// Precision is defaulted
FieldDef.Required = Required;
}
catch(E)
{
FieldDef.Destroy();
throw E;
}
}
finally
{
EndUpdate();
}
}
TFieldDef Find(String Name)
{
var Result = super.Find(Name) as TFieldDef?;
if(Result == null)
DatabaseErrorFmt(DBConsts.SFieldNotFound, [ Name ], DataSet);
return Result!;
}
void InternalUpdate()
{
DataSet.FieldDefList.Updated = false;
UpdateDefs(DataSet.InitFieldDefs);
}
}
abstract class TFlatList extends TStringList
{
final TDataSet DataSet;
bool _locked = true;
bool
get Locked => _locked;
set Locked(bool Value) => _locked = Value;
bool _updated = false;
bool
get Updated => GetUpdated();
set Updated(bool Value) => _updated=Value;
void UpdateList();
TFlatList(this.DataSet) : super()
{
OnChanging = this._listChanging;
}
TObject? FindItem(String Name, bool MustExist)
{
if(!Updated)
Update();
int i = IndexOf(Name);
if(i > -1)
return GetObject(i);
else
{
if(MustExist)
DatabaseErrorFmt(DBConsts.SFieldNotFound, [ Name ], DataSet);
return null;
}
}
int GetCount()
{
if(!Updated)
Update();
return super.GetCount();
}
bool GetUpdated()
{
return _updated;
}
void _listChanging(TObject Sender)
{
if(Locked)
DatabaseError(RTLConsts.SReadOnlyProperty, DataSet);
}
void Update()
{
if(Updated)
return;
Locked = false;
BeginUpdate();
try
{
Clear();
UpdateList();
_updated = true;
}
finally
{
EndUpdate();
Locked = true;
}
}
}
class TFieldDefList extends TFlatList
{
late final TItems<TFieldDef> FieldDefs;
TFieldDefList(TDataSet ADataSet) : super(ADataSet)
{
FieldDefs = TItems<TFieldDef>(
(ndx)
{
if(!Updated)
Update();
return GetObject(ndx);
},
() => throw UnimplementedError() );
}
TFieldDef? Find(String Name)
{
return FindItem(Name, false) as TFieldDef;
}
TFieldDef? FieldByName(String Name)
{
return FindItem(Name, true) as TFieldDef;
}
void UpdateList()
{
void AddFieldDefs(String ParentName, TFieldDefs FieldDefs)
{
for(int i = 0; i<FieldDefs.Count; i++)
{
TFieldDef FieldDef = FieldDefs.Items[i];
String FieldName = ParentName+FieldDef.Name;
AddObject(FieldName, FieldDef);
}
}
if(DataSet.Active)
DataSet.FieldDefs.InternalUpdate();
AddFieldDefs("", DataSet.FieldDefs);
}
bool GetUpdated()
{
return _updated && DataSet.FieldDefs.Updated;
}
}
class TFieldList extends TFlatList
{
late final TItems<TField> Fields;
TFieldList(TDataSet ADataSet) : super(ADataSet)
{
Fields = TItems<TField>(
(ndx)
{
if(!Updated)
Update();
return Objects[ndx];
},
() => throw UnimplementedError() );
}
void UpdateList()
{
void AddFields(TFields AFields)
{ // Using Fields.FList.Count here to exclude sparse fields
for(var item in AFields._list)
{
AddObject(item.FullName, item);
}
}
AddFields(DataSet.Fields);
}
}
class TFields extends TObject
{
final TDataSet DataSet;
final _list = <TField>[];
late final TItems<TField> Fields;
TFields(this.DataSet) : super()
{
Fields = TItems<TField>(
(int ndx) => _list[ndx],
() => _list.iterator );
}
void Changed()
{
if(!DataSet.ComponentState.contains(ComponentStates.Destroying))
DataSet.DataEvent(TDataEvent.FieldListChange, null);
}
void CheckFieldKind(TFieldKind FieldKind, TField Field)
{
}
void Add(TField Field)
{
CheckFieldKind(Field.FieldKind, Field);
_list.add(Field);
Field._fields = this;
Changed();
}
TField? AddEx(String name, TFieldType type, [ int size = 0 ])
{
if(DataSet.Active)
return null;
TField Result = DataSet.CreateTypeField(type);
if(size > 0)
Result.Size = size;
Result.FieldName = name;
Add(Result);
return Result;
}
void Remove(TField Field)
{
_list.remove(Field);
Field._fields = null;
Changed();
}
void Clear()
{
while(_list.isNotEmpty)
{
TField f = _list.removeLast();
f._dataSet = null;
f.Destroy();
}
Changed();
}
int get Count
{
return _list.length;
}
int IndexOf(TField Field)
{
return _list.indexOf(Field);
}
void CheckFieldName(String FieldName)
{
if(FieldName.isEmpty)
DatabaseError(DBConsts.SFieldNameMissing, DataSet);
if(FindField(FieldName) != null)
DatabaseErrorFmt(DBConsts.SDuplicateFieldName, [FieldName], DataSet);
}
TField? FindField(String FieldName)
{
for(var item in _list)
{
if(item.FieldName == FieldName)
return item;
}
return null;
}
TField? FieldByName(String FieldName)
{
TField? Result = FindField(FieldName);
if(Result == null)
DatabaseErrorFmt(DBConsts.SFieldNotFound, [FieldName], DataSet);
return Result;
}
void SetFieldIndex(TField Field, int Value)
{
int CurIndex = _list.indexOf(Field);
if(CurIndex >= 0)
{
int Count = _list.length;
if(Value < 0) Value = 0;
if(Value >= Count) Value = Count - 1;
if(Value != CurIndex)
{
_list.removeAt(CurIndex);
_list.insert(Value, Field);
Field.PropertyChanged(true);
Changed();
}
}
}
}
class TField extends TComponent
{
String _fieldName = '';
TFields? _fields;
TFieldType _dataType = TFieldType.Unknown;
bool _readOnly = false;
TFieldKind _fieldKind = TFieldKind.Data;
TFieldKind
get FieldKind => _fieldKind;
set FieldKind(TFieldKind Value) => SetFieldKind(Value);
TAlignment _alignment = TAlignment.LeftJustify;
bool _visible = true;
bool _required = false;
int _size = 0;
int _fieldNo = -1;
String _displayLabel="";
String
get DisplayLabel => DisplayName;
set DisplayLabel(String Value)
{
if(Value == _fieldName)
Value = "";
if(_displayLabel == Value)
return;
_displayLabel = Value;
PropertyChanged(true);
}
String get DisplayName =>
_displayLabel.isEmpty? _fieldName : _displayLabel;
String _keyFields = '';
String get KeyFields => _keyFields;
TField? _parentField;
TField? get ParentField => _parentField;
bool
get AsBoolean => GetAsBoolean();
set AsBoolean(bool Value) => SetAsBoolean(Value);
TDateTime
get AsDateTime => GetAsDateTime();
set AsDateTime(TDateTime Value) => SetAsDateTime(Value);
double
get AsFloat => GetAsFloat();
set AsFloat(double Value) => SetAsFloat(Value);
int
get AsInteger => GetAsInteger();
set AsInteger(int Value) => SetAsInteger(Value);
dynamic
get AsNative => GetAsNative();
set AsNative(dynamic Value) => SetAsNative(Value);
String
get AsString => GetAsString();
set AsString(String Value) => SetAsString(Value);
dynamic
get AsVariant => GetAsVariant();
set AsVariant(dynamic Value) => SetAsVariant(Value);
TDataSet? _dataSet;
TDataSet?
get DataSet => _dataSet;
set DataSet(TDataSet? Value) => SetDataSet(Value);
TFieldType
get DataType => _dataType;
set DataType(TFieldType Value) => _dataType = Value;
String get DisplayText
{
return GetText(true);
}
int get FieldNo => GetFieldNo();
String get FullName
{
if((_parentField == null) || (DataSet == null))
return FieldName;
else
return DataSet!.GetFieldFullName(this);
}
int
get Size => GetSize();
set Size(int Value) => SetSize(Value);
String get Text // GetEditText
{
return GetText(false);
}
void set Text(String Value) // SetEditText
{
SetText(Value);
}
String get FieldName => _fieldName;
bool
get ReadOnly => _readOnly;
set ReadOnly(bool Value)
{
if(_readOnly == Value)
return;
_readOnly = Value;
PropertyChanged(true);
}
bool
get Required => _required;
set Required(bool Value) => _required = Value;
bool
get Visible => _visible;
set Visible(bool Value)
{
if(_visible == Value)
return;
_visible = Value;
PropertyChanged(true);
}
TField(TComponent AOwner) : super(AOwner)
{
}
void Destroy()
{
if(_dataSet!=null)
{
DataSet!.Close();
if(_fields != null)
_fields!.Remove(this);
}
super.Destroy();
}
EDatabaseError AccessError(String TypeName)
{
return EDatabaseError.CreateResFmt(DBConsts.SFieldAccessError,
[DisplayName, TypeName]);
}
void AssignValue(dynamic Value)
{
}
void Bind(bool Binding)
{
}
void CheckInactive()
{
_dataSet?.CheckInactive();
}
void Clear()
{
SetData(null);
}
void FocusControl()
{
if((_dataSet != null) && _dataSet!.Active)
_dataSet!.DataEvent(TDataEvent.FocusControl, this);
}
void FreeBuffers()
{
}
bool GetAsBoolean()
{
throw AccessError('Boolean'); // Do not localize
}
TDateTime GetAsDateTime()
{
throw AccessError('DateTime'); // Do not localize
}
double GetAsFloat()
{
throw AccessError('Float'); // Do not localize
}
int GetAsInteger()
{
throw AccessError('Integer'); // Do not localize
}
dynamic GetAsNative()
{
return null;
}
void SetAsNative(dynamic Value)
{
if(Value is bool)
SetAsBoolean(Value);
else
if(Value is String)
SetAsString(Value);
else
if(Value is int)
SetAsInteger(Value);
else
if(Value is TDateTime)
SetAsDateTime(Value);
else
throw AccessError('Native'); // Do not localize
}
String GetAsString()
{
return DisplayText; // new
}
dynamic GetAsVariant()
{
return GetData();
}
String GetClassDesc()
{
return "";
}
dynamic GetData()
{
return DataSet?.GetFieldData(this);
}
int GetFieldNo()
{
return _fieldNo;
}
bool get IsNull => GetIsNull();
bool GetIsNull() => GetData() == null;
void PropertyChanged(bool LayoutAffected)
{
if((_dataSet != null) && _dataSet!.Active)
_dataSet!.DataEvent(LayoutAffected? TDataEvent.LayoutChange : TDataEvent.DataSetChange, null);
}
void SetAsBoolean(bool Value)
{
throw AccessError('Boolean'); // Do not localize
}
void SetAsDateTime(TDateTime Value)
{
throw AccessError('DateTime'); // Do not localize
}
void SetAsFloat(double Value)
{
throw AccessError('Float'); // Do not localize
}
void SetAsInteger(int Value)
{
throw AccessError('Integer'); // Do not localize
}
void SetAsString(String Value)
{
throw AccessError('String'); // Do not localize
}
void SetAsVariant(dynamic Value)
{
if(Value == null)
Clear();
else
{
try
{
SetVarValue(Value);
}
catch(E)
{
}
}
}
TAlignment
get Alignment => _alignment;
set Alignment(TAlignment Value)
{
if(_alignment == Value)
return;
_alignment = Value;
PropertyChanged(false);
}
void SetData(dynamic Value)
{
DataSet!.SetFieldData(this, Value);
}
void SetDataSet(TDataSet? ADataSet)
{
if(ADataSet != _dataSet)
{
// Make sure new and old datasets are closed and fieldname is not a dup.
if(_dataSet != null)
_dataSet!.CheckInactive();
if(ADataSet != null)
{
ADataSet.CheckInactive();
}
// If ParentField is set and part of a different dataset then clear it
if((_parentField != null) && (_parentField!.DataSet != ADataSet))
{
_parentField!._fields!.Remove(this);
_parentField = null;
}
else
if(_dataSet != null)
{
if(FieldKind == TFieldKind.Aggregate)
_dataSet!.AggFields.Remove(this);
else
_dataSet!.Fields.Remove(this);
}
// Add to the new dataset's field list, unless parentfield is still set
if((ADataSet != null) && (_parentField == null))
{
if(FieldKind == TFieldKind.Aggregate)
ADataSet.AggFields.Add(this);
else
ADataSet.Fields.Add(this);
}
_dataSet = ADataSet;
}
}
void SetFieldKind(TFieldKind Value)
{
if(_fieldKind == Value)
return;
_fields?.CheckFieldKind(Value, this);
if((DataSet != null))
{
}
else
{
CheckInactive();
_fieldKind = Value;
}
}
void set FieldName(String Value)
{
CheckInactive;
if((_dataSet != null) && (_fieldName != Value))
_fields!.CheckFieldName(Value);
_fieldName = Value;
if(_dataSet != null)
_dataSet!.Fields.Changed();
}
void SetFieldType(TFieldType Value)
{
}
int get Index
{
if(_parentField != null)
return _parentField!._fields!.IndexOf(this);
if(_dataSet == null)
return -1;
return DataSet!.Fields.IndexOf(this);
}
set Index(int Value)
{
if(_fields != null)
_fields!.SetFieldIndex(this, Value);
}
void CheckTypeSize(int Value)
{
}
void SetSize(int Value)
{
CheckInactive;
CheckTypeSize(Value);
_size = Value;
}
int GetSize()
{
return _size;
}
String GetText(bool DisplayText)
{
return GetAsString();
}
void SetText(String Value)
{
SetAsString(Value);
}
void SetVarValue(dynamic Value)
{
if(Value is bool)
SetAsBoolean(Value);
else
if(Value is int)
SetAsInteger(Value);
else
if(Value is String)
SetAsString(Value);
else
if(Value is TDateTime)
SetAsDateTime(Value);
else
throw AccessError('Variant'); // Do not localize
}
}
class TStringField extends TField
{
String get Value => GetAsString();
void set AsString(String Value) => SetAsString(Value);
TStringField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.String;
if(Size == 0)
Size = 20; // Don't reset descendent settings
}
dynamic GetAsNative() => GetAsString();
String GetAsString()
{
return GetValue();
}
dynamic GetAsVariant()
{
return GetValue();
}
String GetValue()
{
return GetData() ?? '';
}
void SetAsString(String Value)
{
SetData(Value);
}
}
class TDynamicField extends TField
{
TDynamicField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.Dynamic;
}
dynamic GetAsNative() => GetData();
}
class TNumericField extends TField
{
TNumericField(TComponent AOwner) : super(AOwner)
{
Alignment = TAlignment.RightJustify;
}
}
class TIntegerField extends TNumericField
{
int
get Value => GetAsInteger();
set Value(int v) => SetAsInteger(v);
TIntegerField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.Integer;
}
dynamic GetAsNative() => GetAsInteger();
bool GetAsBoolean() =>
GetAsInteger() != 0;
int GetAsInteger()
{
return GetData() ?? 0;
}
String GetAsString()
{
return '${GetData() ?? ''}';
}
dynamic GetAsVariant()
{
return GetData();
}
void SetAdBoolean(bool Value) =>
SetAsInteger(Value? 1 : 0);
void SetAsInteger(int Value)
{
SetData(Value);
}
void SetAsString(String Value)
{
}
}
class TAutoIncField extends TIntegerField
{
TAutoIncField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.AutoInc;
}
}
class TFloatField extends TNumericField
{
double
get Value => GetAsFloat();
set Value(double v) => SetAsFloat(v);
TFloatField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.Float;
}
dynamic GetAsNative() => GetAsFloat();
double GetAsFloat()
{
return GetData() ?? 0;
}
int GetAsInteger()
{
return GetAsFloat().toInt();
}
String GetAsString()
{
return '${ GetData() ?? '' }' ;
}
String GetAsExponential([int? fractionDigits])
{
var res = GetData() as double?;
if(res == null)
return '';
if(res == 0)
return '0';
return res.toStringAsExponential(fractionDigits);
}
dynamic GetAsVariant()
{
return GetData();
}
void SetAsFloat(double Value)
{
SetData(Value);
}
void SetAsInteger(int Value)
{
SetAsFloat(Value.toDouble());
}
}
class TBooleanField extends TField
{
TBooleanField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.Boolean;
}
bool get Value => GetAsBoolean();
void set Value(bool Value) => SetAsBoolean(Value);
bool GetAsBoolean()
{
return GetData() ?? false;
}
String GetAsString()
{
dynamic res = GetData();
if(res == null)
return '';
return res? 'true' : 'false';
}
void SetAsBoolean(bool Value)
{
SetData(Value);
}
dynamic GetAsNative() => GetAsBoolean();
}
class TDateTimeField extends TField
{
String _displayFormat = "";
String get DisplayFormat => _displayFormat;
TDateTimeField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.DateTime;
Alignment = TAlignment.Center; // new
}
TDateTime
get Value => GetAsDateTime();
set Value(TDateTime Value) => SetAsDateTime(Value);
TDateTime GetAsDateTime()
{
return GetData() ?? TDateTime();
}
String GetText(bool DisplayText)
{
TDateTime D = GetAsDateTime();
if(D.Val == 0)
return "";
if(DisplayText)
return SysUtils.DateTimeToString(_displayFormat, D);
switch(DataType)
{
case TFieldType.Date:
return SysUtils.DateTimeToString(SysUtils.ShortDateFormat, D);
case TFieldType.Time:
return SysUtils.DateTimeToString(SysUtils.LongTimeFormat, D);
default:
return SysUtils.DateTimeToString("", D);
}
}
void SetAsDateTime(TDateTime Value)
{
SetData(Value);
}
dynamic GetAsNative() => GetAsDateTime();
}
class TDateField extends TDateTimeField
{
TDateField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.Date;
}
}
class TObjectField extends TField
{
TObjectField(TComponent AOwner) : super(AOwner)
{
}
}
class TDataSetField extends TObjectField
{
TDataSet? _nestedDataSet;
TDataSetField(TComponent AOwner) : super(AOwner)
{
_dataType = TFieldType.DataSet;
}
void Destroy()
{
AssignNestedDataSet(null);
super.Destroy();
}
void AssignNestedDataSet(TDataSet? Value)
{
if(_nestedDataSet!=null)
{
_nestedDataSet!.Close();
_nestedDataSet!._dataSetField = null;
}
if(Value!=null)
{
_fields = Value.Fields;
}
_nestedDataSet = Value;
}
}
class TDataLink extends TPersistent
{
TDataSource? _dataSource;
TDataSource?
get DataSource => _dataSource;
set DataSource(TDataSource? ADataSource)
{
if(_dataSource == ADataSource)
return;
if(_dataSourceFixed)
DatabaseError(DBConsts.SDataSourceChange, _dataSource);
if(_dataSource != null)
_dataSource!.RemoveDataLink(this);
if(ADataSource != null)
ADataSource.AddDataLink(this);
}
TDataLink? _next;
int _bufferCount = 1;
int
get BufferCount => GetBufferCount();
set BufferCount(int Value) => SetBufferCount(Value);
int GetBufferCount() => _bufferCount;
void SetBufferCount(int Value)
{
if(_bufferCount == Value)
return;
_bufferCount = Value;
if(Active)
{
UpdateRange();
DataSet!.UpdateBufferCount();
UpdateRange();
}
}
int _firstRecord = 0;
bool _readOnly = false;
bool
get ReadOnly => _readOnly;
set ReadOnly(bool Value)
{
if(_readOnly == Value)
return;
_readOnly = Value;
UpdateState();
}
bool _active = false;
bool
get Active => _active;
set Active(bool Value)
{
if(_active == Value)
return;
_active = Value;
if(Value)
UpdateRange();
else
_firstRecord = 0;
ActiveChanged();
}
bool _visualControl = false;
bool
get VisualControl => _visualControl;
set VisualControl(bool Value) => _visualControl = Value;
bool _editing = false;
bool
get Editing => _editing;
set Editing(bool Value)
{
if(_editing == Value)
return;
_editing = Value;
EditingChanged();
}
bool _updating =false;
bool _dataSourceFixed=false;
bool
get DataSourceFixed => _dataSourceFixed;
set DataSourceFixed(bool Value) => _dataSourceFixed=Value;
TDataSet? get DataSet
{
return DataSource?.DataSet;
}
TDataLink() : super()
{
}
void Destroy()
{
_active = false;
_editing = false;
_dataSourceFixed = false;
DataSource = null;
super.Destroy();
}
void UpdateRange()
{
int Min = DataSet!._activeRecord - _bufferCount + 1;
if(Min < 0)
Min = 0;
int Max = DataSet!._recordCount - _bufferCount;
if(Max < 0)
Max = 0;
if(Max > DataSet!._activeRecord)
Max = DataSet!._activeRecord;
if(_firstRecord < Min)
_firstRecord = Min;
if(_firstRecord > Max)
_firstRecord = Max;
if((_firstRecord != 0) && (DataSet!._activeRecord - _firstRecord < _bufferCount - 1))
_firstRecord--;
}
void UpdateState()
{
Active = (DataSource != null) && (DataSource!.State != TDataSetState.Inactive);
Editing = (DataSource != null) && (StateInEditModes(DataSource!.State) && !_readOnly);
}
void UpdateRecord()
{
_updating = true;
try
{
UpdateData();
}
finally
{
_updating = false;
}
}
bool Edit()
{
if(!_readOnly && (DataSource != null))
DataSource!.Edit();
return _editing;
}
int
get ActiveRecord => GetActiveRecord();
set ActiveRecord(int Value) => SetActiveRecord(Value);
int GetActiveRecord()
{
if(DataSource!.State == TDataSetState.SetKey)
return 0;
return DataSource!.DataSet!._activeRecord - _firstRecord;
}
void SetActiveRecord(int Value)
{
if(DataSource!.State != TDataSetState.SetKey)
DataSource!.DataSet!._activeRecord = Value + _firstRecord;
}
int get RecordCount => GetRecordCount();
int GetRecordCount()
{
if(DataSource!.State == TDataSetState.SetKey)
return 1;
int Result = DataSource!.DataSet!._recordCount;
if(Result > _bufferCount)
return _bufferCount;
return Result;
}
void DataEvent(TDataEvent Event, dynamic Info)
{
if(Event == TDataEvent.UpdateState)
{
UpdateState();
return;
}
if(_active == false)
return;
switch(Event)
{
case TDataEvent.FieldChange:
case TDataEvent.RecordChange:
if(!_updating)
RecordChanged(Info as TField?);
break;
case TDataEvent.DataSetChange:
case TDataEvent.DataSetScroll:
case TDataEvent.LayoutChange:
int Count = 0;
if(DataSet!.State != TDataSetState.SetKey)
{
int Active = DataSource!.DataSet!._activeRecord;
int First = _firstRecord + Info as int;
int Last = First + _bufferCount - 1;
if(Active > Last)
Count = Active - Last;
else
if(Active < First)
Count = Active - First;
_firstRecord = First + Count;
}
if(Event == TDataEvent.DataSetChange)
DataSetChanged();
else
if(Event == TDataEvent.DataSetScroll)
DataSetScrolled(Count);
else
if(Event == TDataEvent.LayoutChange)
LayoutChanged();
break;
case TDataEvent.UpdateRecord:
UpdateRecord();
break;
case TDataEvent.CheckBrowseMode:
CheckBrowseMode();
break;
case TDataEvent.FocusControl:
FocusControl(Info as TField);
break;
default:
break;
}
}
void ActiveChanged()
{
}
void CheckBrowseMode()
{
}
void DataSetChanged()
{
RecordChanged(null);
}
void DataSetScrolled(int Distance)
{
DataSetChanged();
}
void EditingChanged()
{
}
void FocusControl(TField Field)
{
}
void LayoutChanged()
{
DataSetChanged();
}
void RecordChanged(TField? Field)
{
}
void UpdateData()
{
}
bool get Bof => GetBof();
bool GetBof() => DataSet!.Bof;
bool get Eof => GetEof();
bool GetEof() => DataSet!.Eof;
int MoveBy(int Distance) =>
DataSet!.MoveBy(Distance);
}
class TDataSource extends TComponent
{
TDataSet? _dataSet;
TDataSet?
get DataSet => _dataSet;
set DataSet(TDataSet? ADataSet)
{
if(IsLinkedTo(ADataSet))
DatabaseError(DBConsts.SCircularDataLink, this);
if(_dataSet != null)
_dataSet!.RemoveDataSource(this);
if(ADataSet != null)
ADataSet.AddDataSource(this);
}
final DataLinks = TList();
bool _enabled = true;
bool
get Enabled => _enabled;
set Enabled(bool Value)
{
_enabled = true;
UpdateState();
}
bool _autoEdit = true;
bool
get AutoEdit => _autoEdit;
set AutoEdit(bool Value) => _autoEdit=Value;
TDataSetState _state = TDataSetState.Inactive;
TDataSetState
get State => _state;
set State(TDataSetState Value)
{
if(_state == Value)
return;
TDataSetState PriorState = _state;
_state = Value;
NotifyDataLinks(TDataEvent.UpdateState, 0);
if(!ComponentState.contains(ComponentStates.Destroying))
{
if(_onStateChange != null)
_onStateChange!(this);
if(PriorState == TDataSetState.Inactive)
if(_onDataChange!=null)
_onDataChange!(this, null);
}
}
TNotifyEvent? _onStateChange;
TNotifyEvent?
get OnStateChange => _onStateChange;
set OnStateChange(TNotifyEvent? Value) => _onStateChange=Value;
TDataChangeEvent? _onDataChange;
TDataChangeEvent?
get OnDataChange => _onDataChange;
set OnDataChange(TDataChangeEvent? Value) => _onDataChange=Value;
TNotifyEvent? _onUpdateData;
TNotifyEvent?
get OnUpdateData => _onUpdateData;
set OnUpdateData(TNotifyEvent? Value) => _onUpdateData=Value;
TDataSource(TComponent AOwner) : super(AOwner)
{
}
void Destroy()
{
_onStateChange = null;
DataSet = null;
while(DataLinks.Count > 0)
RemoveDataLink(DataLinks.Last);
DataLinks.Destroy();
super.Destroy();
}
void Edit()
{
if(AutoEdit && (State == TDataSetState.Browse))
DataSet!.Edit();
}
void UpdateState()
{
if(Enabled && (DataSet != null))
State = DataSet!.State;
else
State = TDataSetState.Inactive;
}
bool IsLinkedTo(TDataSet? DataSet)
{
while(DataSet != null)
{
if((DataSet.DataSetField != null) &&
(DataSet.DataSetField!.DataSet!.GetDataSource() == this))
return true;
TDataSource? DataSource = DataSet.GetDataSource();
if(DataSource == null)
break;
if(DataSource == this)
return true;
DataSet = DataSource.DataSet;
}
return false;
}
void AddDataLink(TDataLink DataLink)
{
DataLinks.Add(DataLink);
DataLink._dataSource = this;
if(DataSet != null)
DataSet!.UpdateBufferCount();
DataLink.UpdateState();
}
void RemoveDataLink(TDataLink DataLink)
{
DataLink._dataSource = null;
DataLinks.Remove(DataLink);
DataLink.UpdateState();
if(DataSet != null)
DataSet!.UpdateBufferCount();
}
void NotifyLinkTypes(TDataEvent Event, dynamic Info, bool LinkType)
{
for(int i = DataLinks.Count - 1; i>=0; i--)
{
TDataLink DataLink = DataLinks.Items[i];
if(LinkType == DataLink.VisualControl)
DataLink.DataEvent(Event, Info);
}
}
void NotifyDataLinks(TDataEvent Event, dynamic Info)
{
// Notify non-visual links (i.e. details), before visual controls
NotifyLinkTypes(Event, Info, false);
NotifyLinkTypes(Event, Info, true);
}
void DataEvent(TDataEvent Event, dynamic Info)
{
if(Event == TDataEvent.UpdateState)
UpdateState();
else
if(_state != TDataSetState.Inactive)
{
NotifyDataLinks(Event, Info);
switch(Event)
{
case TDataEvent.FieldChange:
if(_onDataChange!=null)
_onDataChange!(this, Info);
break;
case TDataEvent.RecordChange:
case TDataEvent.DataSetChange:
case TDataEvent.DataSetScroll:
case TDataEvent.LayoutChange:
if(_onDataChange != null)
_onDataChange!(this, null);
break;
case TDataEvent.UpdateRecord:
if(_onUpdateData != null)
_onUpdateData!(this);
break;
default:
break;
}
}
}
}
abstract class TRecordBuf
{
}
abstract class TDataSet extends TComponent
{
late final TFields Fields;
int get FieldCount => Fields.Count;
late final TFields AggFields;
late final TFieldDefs _fieldDefs;
TFieldDefs
get FieldDefs => _fieldDefs;
set FieldDefs(TFieldDefs Value) => FieldDefs.Assign(Value);
late final TFieldDefList FieldDefList;
late final TFieldList FieldList;
final _dataSources = <TDataSource>[];
TDataLink? _firstDataLink;
int _bufferCount = 0;
int _recordCount = 0;
int _activeRecord = 0;
int
get ActiveRecord => _activeRecord;
set ActiveRecord(int value) => _activeRecord = value; // new
int _currentRecord = 0;
int get CurrentRecord => _currentRecord;
final _buffers = <TRecordBuf>[];
int _calcFieldsSize = 0;
int get CalcFieldsSize => _calcFieldsSize;
int _disableCount = 0;
int _blobFieldCount = 0;
int get BlobFieldCount => _blobFieldCount;
int _blockReadSize = 0;
int get BlockReadSize => _blockReadSize;
TDataSetField? _dataSetField;
TDataSetField?
get DataSetField => _dataSetField;
set DataSetField(TDataSetField? Value) => SetDataSetField(Value);
bool _isUniDirectional = false;
bool get IsUniDirectional => _isUniDirectional;
int _fieldNoOfs = 1;
int get FieldNoOfs => _fieldNoOfs;
TDataSetState _state = TDataSetState.Inactive;
TDataSetState get State => _state;
TDataEvent _enableEvent = TDataEvent.LayoutChange; // ???
TDataSetState _disableState = TDataSetState.Inactive;
bool _bof = true;
bool get Bof => _bof;
bool _eof = true;
bool get Eof => _eof;
bool _modified = false;
bool get Modified => _modified;
bool _internalCalcFields = false;
bool get InternalCalcFields => _internalCalcFields;
bool _defaultFields = false;
bool get DefaultFields => _defaultFields;
bool _internalOpenComplete = false;
// Events
TDataSetNotifyEvent? _beforeOpen;
TDataSetNotifyEvent? _afterOpen;
TDataSetNotifyEvent? _beforeClose;
TDataSetNotifyEvent? _afterClose;
TDataSetNotifyEvent? _beforeInsert;
TDataSetNotifyEvent? _afterInsert;
TDataSetNotifyEvent? _beforeEdit;
TDataSetNotifyEvent? _afterEdit;
TDataSetNotifyEvent? _beforePost;
TDataSetNotifyEvent? _afterPost;
TDataSetNotifyEvent? _beforeCancel;
TDataSetNotifyEvent? _afterCancel;
TDataSetNotifyEvent? _beforeDelete;
TDataSetNotifyEvent? _afterDelete;
TDataSetNotifyEvent? _beforeRefresh;
TDataSetNotifyEvent? _afterRefresh;
TDataSetNotifyEvent? _afterScroll;
TDataSetNotifyEvent?
get AfterScroll => _afterScroll;
set AfterScroll(TDataSetNotifyEvent? Value) => _afterScroll= Value;
TDataSetNotifyEvent? _beforeScroll;
TDataSetNotifyEvent?
get BeforeScroll => _beforeScroll;
set BeforeScroll(TDataSetNotifyEvent? Value) => _beforeScroll= Value;
TDataSetNotifyEvent? _onNewRecord;
TDataSetNotifyEvent? _onCalcFields;
TDataSetErrorEvent? _onEditError;
TDataSetErrorEvent? _onPostError;
TDataSetErrorEvent? _onDeleteError;
// abstract methods required for all datasets
TGetResult GetRecord(TRecordBuf? Buffer, TGetMode GetMode, bool DoCheck);
void InternalClose();
// procedure InternalHandleException; virtual; abstract;
void InternalInitFieldDefs();
void InternalOpen();
bool IsCursorOpen();
bool get CanModify => GetCanModify();
TDataSet(TComponent? AOwner) : super(AOwner)
{
_fieldDefs = TFieldDefs(this);
FieldDefList = TFieldDefList(this);
Fields = TFields(this);
FieldList = TFieldList(this);
AggFields = TFields(this);
ClearBuffers();
}
void Destroy()
{
Destroying();
Close();
SetDataSetField(null);
super.Destroy();
}
void SetState(TDataSetState Value)
{
if(_state == Value)
return;
_state = Value;
_modified = false;
DataEvent(TDataEvent.UpdateState, 0);
}
void SetModified(bool Value)
{
_modified = Value;
}
void SetDataSetField(TDataSetField? Value)
{
if(_dataSetField == Value)
return;
if((Value != null) && ((Value.DataSet == this) ||
((Value.DataSet!.GetDataSource() != null) &&
(Value.DataSet!.GetDataSource()!.DataSet == this))))
DatabaseError(DBConsts.SCircularDataLink, this);
if(Active) Close();
_dataSetField?.AssignNestedDataSet(null);
_dataSetField = Value;
if(Value != null)
{
Value.AssignNestedDataSet(this);
if(Value.DataSet!.Active)
Open();
}
}
void SetUniDirectional(bool Value)
{
_isUniDirectional = Value;
}
void Open()
{
Active = true;
}
void Close()
{
Active = false;
}
void CheckBiDirectional()
{
if(IsUniDirectional)
DatabaseError(DBConsts.SDataSetUnidirectional, this);
}
void CheckInactive()
{
if(Active == false)
return;
if(ComponentState.contains(ComponentStates.Updating) && ComponentState.contains(ComponentStates.Designing))
Close();
else
DatabaseError(DBConsts.SDataSetOpen, this);
}
void CheckActive()
{
if(State == TDataSetState.Inactive)
DatabaseError(DBConsts.SDataSetClosed, this);
}
bool get Active => _state != TDataSetState.Inactive && _state != TDataSetState.Opening;
void set Active(bool Value) => SetActive(Value);
void SetActive(bool Value)
{
if(ComponentState.contains(ComponentStates.Reading))
{
}
else
if(Active != Value)
{
if(Value)
{
DoBeforeOpen();
try
{
OpenCursor();
}
finally
{
if(State != TDataSetState.Opening)
OpenCursorComplete();
}
}
else
{
if(!(ComponentState.contains(ComponentStates.Destroying)))
DoBeforeClose();
SetState(TDataSetState.Inactive);
CloseCursor();
if(!(ComponentState.contains(ComponentStates.Destroying)))
DoAfterClose();
}
}
}
void DoInternalOpen()
{
_defaultFields = FieldCount == 0;
InternalOpen();
_internalOpenComplete = true;
UpdateBufferCount();
_bof = true;
}
void OpenCursorComplete()
{
try
{
if(State == TDataSetState.Opening)
DoInternalOpen();
}
finally
{
if(_internalOpenComplete)
{
SetState(TDataSetState.Browse);
DoAfterOpen();
}
else
{
SetState(TDataSetState.Inactive);
CloseCursor();
}
}
}
void OpenCursor([bool InfoQuery = false])
{
if(InfoQuery)
InternalInitFieldDefs();
else
if(State != TDataSetState.Opening)
DoInternalOpen();
}
void CloseCursor()
{
_blockReadSize = 0;
_internalOpenComplete = false;
FreeFieldBuffers();
ClearBuffers();
SetBufListSize(0);
InternalClose();
_bufferCount = 0;
_defaultFields = false;
}
// Field Management
void DefChanged(TObject Sender)
{
}
void InitFieldDefs()
{
if(IsCursorOpen())
InternalInitFieldDefs();
else
try
{
OpenCursor(true);
}
finally
{
CloseCursor();
}
}
String GetFieldFullName(TField Field)
{
String Result = Field.FieldName;
return Result;
}
TField CreateTypeField(TFieldType Type)
{
switch(Type)
{
case TFieldType.AutoInc:
return TAutoIncField(this);
case TFieldType.Boolean:
return TBooleanField(this);
case TFieldType.Dynamic:
return TDynamicField(this);
case TFieldType.Date:
return TDateField(this);
case TFieldType.DateTime:
return TDateTimeField(this);
case TFieldType.Float:
return TFloatField(this);
case TFieldType.Integer:
return TIntegerField(this);
case TFieldType.String:
return TStringField(this);
default:
return TField(this);
}
}
void CreateFields()
{
for(int i = 0; i<FieldDefList.Count; i++)
{
TFieldDef fld = FieldDefList.FieldDefs[i];
if((fld.DataType != TFieldType.Unknown) )
fld.CreateField(this, null, FieldDefList.Strings[i]);
}
}
void DestroyFields()
{
Fields.Clear();
}
void CheckFieldCompatibility(TField Field, TFieldDef FieldDef)
{
}
void BindFields(bool Binding)
{
void DoBindFields(TFields Fields)
{
for(int i = 0; i<Fields.Count; i++)
{
TField WithField = Fields.Fields[i];
if(Binding)
{
{
TFieldDef? FieldDef;
int FieldIndex = FieldDefList.IndexOf(WithField.FullName);
if(FieldIndex != -1)
FieldDef = FieldDefList.FieldDefs[FieldIndex];
else
DatabaseErrorFmt(DBConsts.SFieldNotFound, [WithField.DisplayName], this);
if(WithField.FieldKind == TFieldKind.InternalCalc)
WithField._fieldNo = FieldDef!.FieldNo;
else
WithField._fieldNo = FieldIndex + _fieldNoOfs;
CheckFieldCompatibility(Fields.Fields[i], FieldDef!);
}
WithField.Bind(true);
}
else
{
WithField.Bind(false);
WithField._fieldNo = 0;
}
}
}
_calcFieldsSize = 0;
_blobFieldCount = 0;
_internalCalcFields = false;
DoBindFields(Fields);
}
void FreeFieldBuffers()
{
for(int i = 0; i <Fields.Count; i++)
Fields.Fields[i].FreeBuffers();
}
dynamic ConvertToFieldFormat(TField fld, dynamic Value)
{
switch(fld.DataType)
{
case TFieldType.Dynamic:
return Value;
case TFieldType.Boolean:
if(Value is bool)
return Value;
if(Value is int)
return Value!=0;
break;
case TFieldType.AutoInc:
case TFieldType.Integer:
if(Value is int)
return Value;
if(Value is double)
return Value.truncate();
break;
case TFieldType.Date:
case TFieldType.DateTime:
case TFieldType.Time:
if(Value is TDateTimeBase)
return TDateTime(Value);
if(Value is String)
return TDateTime.parse(Value);
break;
case TFieldType.Float:
if(Value is double)
return Value;
if(Value is int)
return Value.toDouble();
break;
case TFieldType.String:
if(Value is String)
return Value;
break;
default:
break;
}
return null;
}
dynamic GetFieldData(TField fld)
{
dynamic Value = GetFieldValue(fld);
if(Value == null)
return null;
return ConvertToFieldFormat(fld, Value);
}
dynamic GetFieldValue(TField fld)
{
return null;
}
void SetFieldData(TField Field, dynamic Value)
{
}
TField? FieldByName(String FieldName)
{
TField? Result = FindField(FieldName);
if(Result == null)
DatabaseErrorFmt(DBConsts.SFieldNotFound, [FieldName], this);
return Result;
}
TField? FindField(String name)
{
TField? Result = Fields.FindField(name);
return Result;
}
// Datasource/Datalink Interaction
TDataSource? get DataSource => GetDataSource();
TDataSource? GetDataSource()
{
return null;
}
void AddDataSource(TDataSource DataSource)
{
_dataSources.add(DataSource);
DataSource._dataSet = this;
UpdateBufferCount();
DataSource.UpdateState();
}
void RemoveDataSource(TDataSource DataSource)
{
DataSource._dataSet = null;
_dataSources.remove(DataSource);
DataSource.UpdateState();
UpdateBufferCount();
}
void DataEvent(TDataEvent Event, dynamic Info)
{
void NotifyDetails()
{
if(State == TDataSetState.BlockRead)
for(var item in _dataSources)
item.NotifyLinkTypes(Event, Info, false);
}
void CheckNestedBrowseMode()
{
}
switch(Event)
{
case TDataEvent.FieldChange:
break;
case TDataEvent.FieldListChange:
case TDataEvent.LayoutChange:
FieldList.Updated = false;
break;
case TDataEvent.PropertyChange:
FieldDefs.Updated = false;
break;
case TDataEvent.CheckBrowseMode:
CheckNestedBrowseMode();
break;
case TDataEvent.DataSetChange:
case TDataEvent.DataSetScroll:
NotifyDetails();
break;
default:
break;
}
if((_disableCount == 0) && (State != TDataSetState.BlockRead))
{
for(var item in _dataSources)
item.DataEvent(Event, Info);
}
else
if((Event == TDataEvent.UpdateState) && (State == TDataSetState.Inactive) ||
(Event == TDataEvent.LayoutChange))
_enableEvent = TDataEvent.LayoutChange;
}
bool ControlsDisabled()
{
return _disableCount != 0;
}
void DisableControls()
{
if(_disableCount == 0)
{
_disableState = _state;
_enableEvent = TDataEvent.DataSetChange;
}
_disableCount++;
}
void EnableControls()
{
if(_disableCount != 0)
{
_disableCount--;
if(_disableCount == 0)
{
if(_disableState != _state)
DataEvent(TDataEvent.UpdateState, 0);
if((_disableState != TDataSetState.Inactive) && (_state != TDataSetState.Inactive))
DataEvent(_enableEvent, 0);
}
}
}
void UpdateRecord()
{
if(!StateInEditModes(State))
DatabaseError(DBConsts.SNotEditing, this);
DataEvent(TDataEvent.UpdateRecord, 0);
}
// Buffer Management
TRecordBuf AllocRecordBuffer();
void FreeRecordBuffer(TRecordBuf? Buffer)
{
}
void SetBufListSize(int Value)
{
if(_buffers.length == Value)
return;
while(_buffers.length < Value)
_buffers.add(AllocRecordBuffer());
while(_buffers.length > Value)
FreeRecordBuffer(_buffers.removeLast());
}
void SetBufferCount(int Value)
{
void AdjustFirstRecord(int Delta)
{
if(Delta != 0)
{
TDataLink? DataLink = _firstDataLink;
while(DataLink != null)
{
if(DataLink.Active)
DataLink._firstRecord+=Delta;
DataLink = DataLink._next;
}
}
}
if(_bufferCount != Value)
{
if((_bufferCount > Value) && (_recordCount > 0))
{
int Delta = _activeRecord;
TDataLink? DataLink = _firstDataLink;
while(DataLink != null)
{
if(DataLink.Active && (DataLink._firstRecord < Delta))
Delta = DataLink._firstRecord;
DataLink = DataLink._next;
}
for(int i = 0; i<Value; i++)
MoveBuffer(i + Delta, i);
_activeRecord-=Delta;
if(_currentRecord != -1)
_currentRecord-=Delta;
if(_recordCount > Value)
_recordCount = Value;
AdjustFirstRecord(-Delta);
}
SetBufListSize(Value + 1);
_bufferCount = Value;
if(!ComponentState.contains(ComponentStates.Destroying))
{
GetNextRecords();
AdjustFirstRecord(GetPriorRecords());
}
}
}
void UpdateBufferCount()
{
if(IsCursorOpen())
{
int MaxBufferCount = 1;
_firstDataLink = null;
for(int i = _dataSources.length - 1; i>=0; i--)
{
TList WithDataLink = _dataSources[i].DataLinks;
for(int j = WithDataLink.Count - 1; j>=0; j--)
{
TDataLink DataLink = WithDataLink.Items[j];
DataLink._next = _firstDataLink;
_firstDataLink = DataLink;
if(DataLink._bufferCount > MaxBufferCount)
MaxBufferCount = DataLink._bufferCount;
}
}
SetBufferCount(MaxBufferCount);
}
}
void SetCurrentRecord(int Index)
{
if((_currentRecord != Index) || (_dataSetField != null))
{
if((DataSetField != null) && (DataSetField!.DataSet!.State != TDataSetState.Insert))
DataSetField!.DataSet!.UpdateCursorPos();
if(!IsUniDirectional)
{
TRecordBuf Buffer = _buffers[Index];
switch(GetBookmarkFlag(Buffer))
{
case TBookmarkFlag.Current:
case TBookmarkFlag.Inserted:
InternalSetToRecord(Buffer);
break;
case TBookmarkFlag.BOF:
InternalFirst();
break;
case TBookmarkFlag.EOF:
InternalLast();
}
}
_currentRecord = Index;
}
}
TRecordBuf? GetBuffer(int Index)
{
if(Index < _buffers.length)
return _buffers[Index];
return null;
}
bool GetNextRecord()
{
TGetMode GetMode = TGetMode.Next;
if(_recordCount > 0)
{
SetCurrentRecord(_recordCount - 1);
if((State == TDataSetState.Insert) && (_currentRecord == _activeRecord) &&
(GetBookmarkFlag(ActiveBuffer())) == TBookmarkFlag.Current)
GetMode = TGetMode.Current;
}
else
if((DataSetField != null) && (DataSetField!.DataSet!.State != TDataSetState.Insert))
DataSetField!.DataSet!.UpdateCursorPos();
bool Result = (GetRecord(GetBuffer(_recordCount), GetMode, true) == TGetResult.OK);
if(Result)
{
if(_recordCount == 0)
ActivateBuffers();
else
if(_recordCount < _bufferCount)
_recordCount++;
else
MoveBuffer(0, _recordCount);
_currentRecord = _recordCount - 1;
}
else
CursorPosChanged();
return Result;
}
bool GetPriorRecord()
{
CheckBiDirectional();
if(_recordCount > 0)
SetCurrentRecord(0);
bool Result = GetRecord(GetBuffer(_recordCount), TGetMode.Prior, true) == TGetResult.OK;
if(Result)
{
if(_recordCount == 0)
ActivateBuffers();
else
{
MoveBuffer(_recordCount, 0);
if(_recordCount < _bufferCount)
{
_recordCount++;
_activeRecord++;
}
}
_currentRecord = 0;
}
else
CursorPosChanged();
return Result;
}
void Resync( { bool rmExact = false, bool rmCenter = false} )
{
if(!IsUniDirectional)
{
if(rmExact)
{
CursorPosChanged();
if(GetRecord(_buffers[_recordCount], TGetMode.Current, true) != TGetResult.OK)
DatabaseError(DBConsts.SRecordNotFound, this);
}
else
if((GetRecord(_buffers[_recordCount], TGetMode.Current, false) != TGetResult.OK) &&
(GetRecord(_buffers[_recordCount], TGetMode.Next, false) != TGetResult.OK) &&
(GetRecord(_buffers[_recordCount], TGetMode.Prior, false) != TGetResult.OK))
{
ClearBuffers();
DataEvent(TDataEvent.DataSetChange, 0);
return;
}
int Count = rmCenter? ((_bufferCount - 1) / 2).truncate() : _activeRecord;
MoveBuffer(_recordCount, 0);
ActivateBuffers();
try
{
while((Count > 0) && GetPriorRecord())
Count--;
GetNextRecords();
GetPriorRecords();
}
finally
{
DataEvent(TDataEvent.DataSetChange, 0);
}
}
}
void MoveBuffer(int CurIndex, int NewIndex)
{
if(!IsUniDirectional && (CurIndex != NewIndex))
{
TRecordBuf Buffer = _buffers.removeAt(CurIndex);
_buffers.insert(NewIndex, Buffer);
}
}
TRecordBuf ActiveBuffer()
{
return _buffers[_activeRecord];
}
TRecordBuf TempBuffer()
{
return _buffers[_recordCount];
}
void ClearBuffers()
{
_recordCount = 0;
_activeRecord = 0;
_currentRecord = -1;
_bof = true;
_eof = true;
}
void ActivateBuffers()
{
_recordCount = 1;
_activeRecord = 0;
_currentRecord = 0;
_bof = false;
_eof = false;
}
void UpdateCursorPos()
{
if(_recordCount > 0)
SetCurrentRecord(_activeRecord);
}
void CursorPosChanged()
{
_currentRecord = -1;
}
bool GetCurrentRecord(TRecordBuf Buffer)
{
return false;
}
int GetNextRecords()
{
int Result = 0;
while((_recordCount < _bufferCount) && GetNextRecord())
Result++;
return Result;
}
int GetPriorRecords()
{
int Result = 0;
if(!IsUniDirectional)
while((_recordCount < _bufferCount) && GetPriorRecord())
Result++;
return Result;
}
void InitRecord(TRecordBuf Buffer)
{
InternalInitRecord(Buffer);
ClearCalcFields(Buffer);
SetBookmarkFlag(Buffer, TBookmarkFlag.Inserted);
}
bool IsEmpty()
{
return _activeRecord >= _recordCount;
}
void ClearCalcFields(TRecordBuf Buffer)
{
}
// Navigation
void InternalFirst()
{
}
void InternalLast()
{
}
void First()
{
CheckBrowseMode();
DoBeforeScroll();
bool FReopened = false;
if(IsUniDirectional)
{
if(!Bof)
{ // Need to Close and Reopen dataset: (Midas)
Active = false;
Active = true;
}
FReopened = true;
}
else
ClearBuffers();
try
{
InternalFirst();
if(!FReopened)
{
GetNextRecord();
GetNextRecords();
}
}
finally
{
_bof = true;
DataEvent(TDataEvent.DataSetChange, 0);
DoAfterScroll();
}
}
void Last()
{
CheckBiDirectional();
CheckBrowseMode();
DoBeforeScroll();
ClearBuffers();
try
{
InternalLast();
GetPriorRecord();
GetPriorRecords();
}
finally
{
_eof = true;
DataEvent(TDataEvent.DataSetChange, 0);
DoAfterScroll();
}
}
int MoveBy(int Distance)
{
CheckBrowseMode();
int Result = 0;
DoBeforeScroll();
if(((Distance > 0) && !_eof) || ((Distance < 0) && !_bof))
{
_bof = false;
_eof = false;
int OldRecordCount = _recordCount;
int ScrollCount = 0;
try
{
while(Distance > 0)
{
if(_activeRecord < _recordCount - 1)
_activeRecord++;
else
{
int I = _recordCount < _bufferCount? 0 : 1;
if(GetNextRecord())
{
ScrollCount-=I;
if(_activeRecord < _recordCount - 1)
_activeRecord++;
}
else
{
_eof = true;
break;
}
}
Distance--;
Result++;
}
while(Distance < 0)
{
if(_activeRecord > 0)
_activeRecord--;
else
{
int I = _recordCount < _bufferCount? 0 : 1;
if(GetPriorRecord())
{
ScrollCount+=I;
if(_activeRecord > 0)
_activeRecord--;
}
else
{
_bof = true;
break;
}
}
Distance++;
Result--;
}
}
finally
{
if(_recordCount != OldRecordCount)
DataEvent(TDataEvent.DataSetChange, 0);
else
DataEvent(TDataEvent.DataSetScroll, ScrollCount);
DoAfterScroll();
}
}
return Result;
}
void Next()
{
if(BlockReadSize > 0)
BlockReadNext();
else
MoveBy(1);
}
void BlockReadNext()
{
MoveBy(1);
}
void Prior()
{
MoveBy(-1);
}
void Refresh()
{
DoBeforeRefresh();
CheckBrowseMode();
UpdateCursorPos();
try
{
InternalRefresh();
}
finally
{
Resync();
DoAfterRefresh();
}
}
void SetBlockReadSize(int Value)
{
if(Value > 0)
{
CheckActive();
SetState(TDataSetState.BlockRead);
}
else
if(State == TDataSetState.BlockRead)
SetState(TDataSetState.Browse);
_blockReadSize = Value;
}
// Editing
void CheckParentState()
{
if(DataSetField != null)
DataSetField!.DataSet!.Edit();
}
void Edit()
{
if(State!=TDataSetState.Edit && State!=TDataSetState.Insert)
if(_recordCount == 0)
Insert();
else
{
CheckBrowseMode();
CheckCanModify();
DoBeforeEdit();
CheckParentState();
CheckOperation(InternalEdit, _onEditError);
//GetCalcFields(ActiveBuffer);
SetState(TDataSetState.Edit);
DataEvent(TDataEvent.RecordChange, null);
DoAfterEdit();
}
}
void Insert()
{
BeginInsertAppend();
MoveBuffer(_recordCount, _activeRecord);
TRecordBuf Buffer = ActiveBuffer();
InitRecord(Buffer);
if(_recordCount == 0)
SetBookmarkFlag(Buffer, TBookmarkFlag.BOF);
if(_recordCount < _bufferCount)
_recordCount++;
InternalInsert();
EndInsertAppend();
}
void Append()
{
BeginInsertAppend();
ClearBuffers();
TRecordBuf Buffer = _buffers[0];
InitRecord(Buffer);
SetBookmarkFlag(Buffer, TBookmarkFlag.EOF);
_recordCount = 1;
_bof = false;
GetPriorRecords();
InternalInsert();
EndInsertAppend();
}
void Post()
{
UpdateRecord();
if(State==TDataSetState.Edit || State==TDataSetState.Insert)
{
DataEvent(TDataEvent.CheckBrowseMode, 0);
DoBeforePost();
CheckOperation(InternalPost, _onPostError);
FreeFieldBuffers();
SetState(TDataSetState.Browse);
Resync();
DoAfterPost();
}
}
void Cancel()
{
void CancelNestedDataSets()
{
}
if(State == TDataSetState.Edit || State == TDataSetState.Insert)
{
CancelNestedDataSets();
DataEvent(TDataEvent.CheckBrowseMode, 0);
DoBeforeCancel();
bool DoScrollEvents = State == TDataSetState.Insert;
if(DoScrollEvents)
DoBeforeScroll();
UpdateCursorPos();
InternalCancel();
FreeFieldBuffers();
SetState(TDataSetState.Browse);
Resync();
DoAfterCancel();
if(DoScrollEvents)
DoAfterScroll();
}
}
void Delete()
{
CheckActive();
if(State==TDataSetState.Insert || State == TDataSetState.SetKey)
Cancel();
else
{
if(_recordCount == 0)
DatabaseError(DBConsts.SDataSetEmpty, this);
DataEvent(TDataEvent.CheckBrowseMode, 0);
DoBeforeDelete();
DoBeforeScroll();
CheckOperation(InternalDelete, _onDeleteError);
FreeFieldBuffers();
SetState(TDataSetState.Browse);
Resync();
DoAfterDelete();
DoAfterScroll();
}
}
void BeginInsertAppend()
{
CheckBrowseMode();
CheckCanModify();
DoBeforeInsert();
CheckParentState();
DoBeforeScroll();
}
void EndInsertAppend()
{
SetState(TDataSetState.Insert);
try
{
DoOnNewRecord();
}
catch(E)
{
UpdateCursorPos();
FreeFieldBuffers();
SetState(TDataSetState.Browse);
Resync();
throw E;
}
_modified = false;
DataEvent(TDataEvent.DataSetChange, 0);
DoAfterInsert();
DoAfterScroll();
}
void AddRecord(List Values, bool Append)
{
BeginInsertAppend();
if(!Append)
UpdateCursorPos();
DisableControls();
try
{
MoveBuffer(_recordCount, _activeRecord);
try
{
var Buffer = ActiveBuffer();
InitRecord(Buffer);
_state = TDataSetState.Insert;
try
{
DoOnNewRecord();
DoAfterInsert();
SetFields(Values);
DoBeforePost();
InternalAddRecord(Buffer, Append);
}
finally
{
FreeFieldBuffers();
_state = TDataSetState.Browse;
_modified = false;
}
}
catch(E)
{
MoveBuffer(_activeRecord, _recordCount);
throw E;
}
Resync();
DoAfterPost();
}
finally
{
EnableControls();
}
}
void InsertRecord(List Values)
{
AddRecord(Values, false);
}
void AppendRecord(List Values)
{
AddRecord(Values, true);
}
void CheckOperation(TDataOperation Operation, TDataSetErrorEvent? ErrorEvent)
{
bool Done = false;
do
{
try
{
UpdateCursorPos();
Operation();
Done = true;
}
catch(E)
{
print(E);
break; // new
}
} while(!Done);
}
void SetFields(List Values)
{
int i = 0;
for(var item in Values)
Fields.Fields[i++].AssignValue(item);
}
void CheckRequiredFields()
{
for(int i = 0; i<Fields.Count; i++)
{
TField WithField = Fields.Fields[i];
if(WithField.Required && !WithField.ReadOnly && (WithField.FieldKind == TFieldKind.Data) && WithField.IsNull)
{
WithField.FocusControl();
DatabaseErrorFmt(DBConsts.SFieldRequired, [ WithField.DisplayName ]);
}
}
}
// Editing Stubs
void InternalInitRecord(TRecordBuf Buffer)
{
}
void InternalAddRecord(TRecordBuf Buffer, bool Append)
{
}
void InternalDelete()
{
}
void InternalPost()
{
CheckRequiredFields();
}
void InternalCancel()
{
}
void InternalEdit()
{
}
void InternalInsert()
{
}
void InternalRefresh()
{
}
TBookmarkFlag GetBookmarkFlag(TRecordBuf Buffer)
{
return TBookmarkFlag.Current;
}
void SetBookmarkFlag(TRecordBuf Buffer, TBookmarkFlag Value)
{
}
void InternalGotoBookmark(var Bookmark)
{
}
void InternalSetToRecord(TRecordBuf Buffer)
{
}
bool BookmarkValid(var Bookmark)
{
return false;
}
/// Filter / Locate / Find
bool _filtered = false;
bool
get Filtered => _filtered;
set Filtered(bool value) => SetFiltered(value);
void SetFiltered(bool value)
{
if(value == true)
CheckBiDirectional();
_filtered = value;
}
String _filterText = '';
String
get Filter => _filterText;
set Filter(String value) => SetFilterText(value);
void SetFilterText(String value)
{
CheckBiDirectional();
_filterText = value;
}
bool Locate(Map data, TLocateOptions Options)
{
CheckBiDirectional();
return false;
}
// Informational
void CheckBrowseMode()
{
CheckActive();
DataEvent(TDataEvent.CheckBrowseMode, 0);
switch(State)
{
case TDataSetState.Edit:
case TDataSetState.Insert:
UpdateRecord();
if(Modified)
Post();
else
Cancel();
break;
case TDataSetState.SetKey:
Post();
break;
default:
break;
}
}
bool GetCanModify()
{
return true;
}
void CheckCanModify()
{
if(!CanModify)
DatabaseError(DBConsts.SDataSetReadOnly, this);
}
int get RecordCount => GetRecordCount();
int GetRecordCount() => -1;
int get RecNo => GetRecNo();
int GetRecNo() => -1;
void set RecNo(int Value) => SetRecNo(Value);
void SetRecNo(int Value) {
}
bool IsSequenced()
{
return true;
}
// Event Handler Helpers
void DoAfterCancel()
{
if(_afterCancel!= null) _afterCancel!(this);
}
void DoAfterClose()
{
if(_afterClose!=null) _afterClose!(this);
}
void DoAfterDelete()
{
if(_afterDelete!=null) _afterDelete!(this);
}
void DoAfterEdit()
{
if(_afterEdit!=null) _afterEdit!(this);
}
void DoAfterInsert()
{
if(_afterInsert!=null) _afterInsert!(this);
}
void DoAfterOpen()
{
if(_afterOpen!=null) _afterOpen!(this);
if(!IsEmpty()) DoAfterScroll();
}
void DoAfterPost()
{
if(_afterPost!=null) _afterPost!(this);
}
void DoAfterRefresh()
{
if(_afterRefresh!=null) _afterRefresh!(this);
}
void DoAfterScroll()
{
if(_afterScroll!=null) _afterScroll!(this);
}
void DoBeforeCancel()
{
if(_beforeCancel!=null) _beforeCancel!(this);
}
void DoBeforeClose()
{
if(_beforeClose!=null) _beforeClose!(this);
}
void DoBeforeDelete()
{
if(_beforeDelete!=null) _beforeDelete!(this);
}
void DoBeforeEdit()
{
if(_beforeEdit!=null) _beforeEdit!(this);
}
void DoBeforeInsert()
{
if(_beforeInsert!=null) _beforeInsert!(this);
}
void DoBeforeOpen()
{
if(_beforeOpen!=null) _beforeOpen!(this);
}
void DoBeforePost()
{
if(_beforePost!=null) _beforePost!(this);
}
void DoBeforeRefresh()
{
if(_beforeRefresh!=null) _beforeRefresh!(this);
}
void DoBeforeScroll()
{
if(_beforeScroll!=null) _beforeScroll!(this);
}
void DoOnCalcFields()
{
if(_onCalcFields!=null) _onCalcFields!(this);
}
void DoOnNewRecord()
{
if(_onNewRecord!=null) _onNewRecord!(this);
}
dynamic operator [](String name)
{
TField? f = FindField(name);
if(f == null)
return null;
return f.AsNative;
}
void operator []=(String name, dynamic value)
{
TField? f = FindField(name);
if(f != null)
f.AsNative = value;
}
double AsFloat(String name)
{
TField? fld = FindField(name);
if(fld == null)
return 0.0;
return fld.AsFloat;
}
int AsInteger(String name)
{
TField? fld = FindField(name);
if(fld == null)
return 0;
return fld.AsInteger;
}
String AsString(String name)
{
TField? fld = FindField(name);
if(fld == null)
return "";
return fld.AsString;
}
TDateTime AsDateTime(String name)
{
TField? fld = FindField(name);
if(fld == null)
return TDateTime();
return fld.AsDateTime;
}
}
|
node-ldap
=========
OpenLDAP client bindings for Node.js. Requires libraries from
http://www.openldap.org installed.
Contributing
------------
Any and all patches and pull requests are certainly welcome.
Thanks to:
----------
* Petr Běhan
* YANG Xudong
Dependencies
------------
Tested with Node >= v0.4.0
Installation
------------
To build, ensure the OpenLDAP client libraries are installed, and
npm install https://github.com/jeremycx/node-LDAP/tarball/master -g
Connection.open(uri, version)
-----------------------------
Opens a new connection to the LDAP server or servers. Does not make a
connection attept (that is saved until the first command is issued).
Basically, this call will always succeeds, but may throw an error in
the case of improper parameters. Will not return an error unless no
memory is available.
Open Example
------------
var LDAPConnection = require("../LDAP").Connection;
var LDAP = new LDAPConnection();
if (LDAP.open("ldap://server1.domain.com ldap://server2.domain.com", 3) < 0) {
throw new Error("Unable to connect to server");
}
Connection.SimpleBind(dn, password, callback(msgid, err));
-----------------------------------
Authenticates to the server. When the response is ready, or the
timeout occurs, will execute the callback with the error value set.
Connection.Search(base, scope, filter, attrs, function(msgid, err, data))
---------------------------------------------
Searches LDAP within the given base for entries matching the given
filter, and returns all attrs for matching entries. To get all
available attrs, use "*".
Scopes are specified as one of the following integers:
* Connection.BASE = 0;
* Connection.ONELEVEL = 1;
* Connection.SUBTREE = 2;
* Connection.SUBORDINATE = 3;
* Connection.DEFAULT = -1;
If a disconnect or other server error occurs, the backing library will
attempt to reconnect automatically, and if this reconnection fails,
Connection.Open() will return -1.
See also "man 3 ldap" for details.
Search Example
--------------
var LDAPConnection = require("../LDAP").Connection;
var LDAP = new LDAPConnection();
// Open a connection.
LDAP.open("ldap://ldap1.example.com");
LDAP.search("o=company", LDAP.SUBTREE, "(uid=alice)", "*", function(msgid, error, data) {
switch(error) {
case -2:
console.log("Timeout");
break;
case -1:
console.log("Server gone away");
break;
default:
console.log(data[0].uid[0]);
break;
}
});
TODO:
-----
* Document Modify, Add and Rename
* Testing against Microsoft Active Directory is welcomed, as I don't
have a server to test against.
|
package crazy
// Ziggurat implements a generalized ziggurat algorithm for producing random
// values according to any monotone decreasing density, optionally symmetric
// about zero. See http://www.jstatsoft.org/v05/i08/paper.
type Ziggurat struct {
// PDF is the probability density function for the desired distribution.
PDF func(x float64) float64
// Used to generate a value distributed along the tail of the desired
// distribution. The value returned should be positive; if it is used and
// the ziggurat is mirrored, there is a 50% chance of the value being
// negated before being returned.
Tail func(src Source) float64
// If true, one random bit is used to determine the sign of the values
// produced by the ziggurat.
Mirrored bool
// K[i] = floor(2**53 * (x[i-1]/x[i]))
// K[0] = floor(2**53 * r * PDF(r) / v)
K [1024]uint64
// W[i] = x[i] / 2**53
// W[0] = v*PDF(r) / 2**53
W [1024]float64
// F[i] = PDF(x[i])
F [1024]float64
}
// GenNext generates a value distributed according to the ziggurat.
func (z *Ziggurat) GenNext(src Source) float64 {
for {
j := int64(RNG{src}.Uint64())
i := uint16(j >> 54 & 0x3ff)
if z.Mirrored {
j = j << 10 >> 10
} else {
j = j & 0x001fffffffffffff
}
if uint64(j+j>>63^j>>63) < z.K[i] {
return float64(j) * z.W[i]
}
if i != 0 {
x := float64(j) * z.W[i]
if z.F[i]+(Uniform0_1{src}.Next())*(z.F[i-1]-z.F[i]) < z.PDF(x) {
return x
}
} else {
x := z.Tail(src)
if j < 0 {
return -x
}
return x
}
}
}
|
import * as ActionsTypes from '../constants/actions-types'
import * as config from '../constants/config'
import axios from 'axios'
const receiveBeers = beers => ({
type: ActionsTypes.RECEIVE_BEERS,
beers
})
export const getAllBeers = () => dispatch => {
axios.get(config.API_BASE_URL + 'beers')
.then(res => {
if (res.status === 200)
dispatch(receiveBeers(res.data))
else
throw new Error('Server error!')
})
.catch(error => {
console.log('Error: ', error)
})
}
|
#!/bin/sh
set -e
if [ $# -eq 0 ]; then
echo "Usage: $0 <tag>"
echo "Release version required as argument"
exit 1
fi
VERSION="$1"
GIT_COMMIT=$(git rev-list -1 HEAD)
BUILD_DATE=$(date)
export CGO_ENABLED=0
RELEASE_FILE=RELEASE.md
LDFLAGS="-s -w \
-X \"github.com/naggie/dstask.GIT_COMMIT=$GIT_COMMIT\" \
-X \"github.com/naggie/dstask.VERSION=$VERSION\" \
-X \"github.com/naggie/dstask.BUILD_DATE=$BUILD_DATE\"\
"
# get release information
if ! test -f $RELEASE_FILE || head -n 1 $RELEASE_FILE | grep -vq $VERSION; then
# file doesn't exist or is for old version, replace
printf "$VERSION\n\n\n" > $RELEASE_FILE
fi
vim "+ normal G $" $RELEASE_FILE
# build
mkdir -p dist
# UPX is disabled due to 40ms overhead, plus:
# see https://github.com/upx/upx/issues/222 -- UPX produces broken darwin executables.
GOOS=linux GOARCH=arm GOARM=5 go build -o dstask -mod=vendor -ldflags="$LDFLAGS" cmd/dstask/main.go
GOOS=linux GOARCH=arm GOARM=5 go build -o dstask-import -mod=vendor -ldflags="$LDFLAGS" cmd/dstask-import/main.go
# upx -q dstask
mv dstask dist/dstask-linux-arm5
mv dstask-import dist/dstask-import-linux-arm5
GOOS=linux GOARCH=amd64 go build -o dstask -mod=vendor -ldflags="$LDFLAGS" cmd/dstask/main.go
GOOS=linux GOARCH=amd64 go build -o dstask-import -mod=vendor -ldflags="$LDFLAGS" cmd/dstask-import/main.go
# upx -q dstask
mv dstask dist/dstask-linux-amd64
mv dstask-import dist/dstask-import-linux-amd64
GOOS=darwin GOARCH=amd64 go build -o dstask -mod=vendor -ldflags="$LDFLAGS" cmd/dstask/main.go
GOOS=darwin GOARCH=amd64 go build -o dstask-import -mod=vendor -ldflags="$LDFLAGS" cmd/dstask-import/main.go
#upx -q dstask
mv dstask dist/dstask-darwin-amd64
mv dstask-import dist/dstask-import-darwin-amd64
hub release create \
--draft \
-a dist/dstask-linux-arm5#"dstask linux-arm5" \
-a dist/dstask-import-linux-arm5#"dstask linux-arm5" \
-a dist/dstask-linux-amd64#"dstask linux-amd64" \
-a dist/dstask-import-linux-amd64#"dstask linux-amd64" \
-a dist/dstask-darwin-amd64#"dstask darwin-amd64" \
-a dist/dstask-import-darwin-amd64#"dstask darwin-amd64" \
-F $RELEASE_FILE \
$1
|
///////////////////////////////////////////////////////////////////////
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
///////////////////////////////////////////////////////////////////////
package validator
import (
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
log "github.com/sirupsen/logrus"
"github.com/vmware/dispatch/pkg/functions"
)
type schemaValidator struct {
}
// New creates a schema validator
func New() functions.Validator {
return &schemaValidator{}
}
type inputError struct {
Err error `json:"err"`
}
func (err *inputError) Error() string {
return err.Err.Error()
}
func (err *inputError) AsUserErrorObject() interface{} {
return err
}
type outputError struct {
Err error `json:"err"`
}
func (err *outputError) Error() string {
return err.Err.Error()
}
func (err *outputError) AsFunctionErrorObject() interface{} {
return err
}
func (*schemaValidator) GetMiddleware(schemas *functions.Schemas) functions.Middleware {
return func(f functions.Runnable) functions.Runnable {
return func(ctx functions.Context, input interface{}) (interface{}, error) {
if schema, ok := schemas.SchemaIn.(*spec.Schema); ok {
if schema != nil {
if err := validate.AgainstSchema(schema, input, strfmt.Default); err != nil {
return nil, &inputError{err}
}
}
} else {
log.Warnf("Unknown schema impl: %v", schema)
}
output, err := f(ctx, input)
if err != nil {
return nil, err
}
if schema, ok := schemas.SchemaOut.(*spec.Schema); ok {
if schema != nil {
if err := validate.AgainstSchema(schema, output, strfmt.Default); err != nil {
return nil, &outputError{err}
}
}
} else {
log.Warnf("Unknown schema impl: %v", schema)
}
return output, nil
}
}
}
|
struct SelectValues{T}
name::Symbol
values::Vector{T}
split::Bool
filter::Bool
end
SelectValues(name, values, split = false) = SelectValues(name, values, split, true)
struct SelectPredicate{T}
name::Symbol
f::T
split::Bool
filter::Bool
end
SelectPredicate(name, f, split = false) = SelectPredicate(name, f, split, true)
struct Data2Select{T<:AbstractIndexedTable, N1, N2}
table::T
discrete::NTuple{N1, SelectValues}
continuous::NTuple{N2, SelectPredicate}
end
struct SelectedData{T<:AbstractIndexedTable, N}
table::T
splitby::NTuple{N, Symbol}
end
SelectedData(d2s::Data2Select) =
SelectedData(selectdata(d2s.table, d2s.discrete, d2s.continuous), Tuple(i.name for i in d2s.discrete if i.split))
Base.:(==)(a::SelectedData, b::SelectedData) = (a.table == b.table) && (a.splitby == b.splitby)
function selectdata(df, discrete, continuous)
f = function(i)
all(getfield(i, s.name) in s.values for s in discrete if s.filter) &&
all(s.f(getfield(i, s.name)) for s in continuous if s.filter)
end
filter(f, df)
end
|
/*
* Copyright 2016 The BigDL Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intel.analytics.bigdl.nn
import com.intel.analytics.bigdl.nn.abstractnn.TensorCriterion
import com.intel.analytics.bigdl.tensor.{DenseTensorApply, Tensor, TensorFunc6}
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric
import scala.reflect.ClassTag
/**
* This method is same as `mean_absolute_percentage_error` loss in keras.
* It caculates diff = K.abs((y - x) / K.clip(K.abs(y), K.epsilon(), Double.MaxValue))
* and return 100 * K.mean(diff) as outpout
* Here, the x and y can have or not have a batch.
* @param ev$1
* @param ev
* @tparam T The numeric type in the criterion, usually which are [[Float]] or [[Double]]
*/
class MeanAbsolutePercentageCriterion[T: ClassTag]
(implicit ev: TensorNumeric[T]) extends TensorCriterion[T] {
@transient
private var buffer1 : Tensor[T] = null
@transient
private var buffer2 : Tensor[T] = null
private val epsilon: T = ev.fromType(1e-07)
private val maxValue: T = ev.fromType(Double.MaxValue)
private val negativeOne: T = ev.fromType(-1)
override def updateOutput(input: Tensor[T], target : Tensor[T]): T = {
if (buffer1 == null) buffer1 = Tensor[T]()
if (buffer2 == null) buffer2 = Tensor[T]()
buffer1.resizeAs(input).copy(input)
buffer2.resizeAs(target).copy(target)
buffer1.sub(target).abs()
// buffer2 = K.clip(K.abs(y), K.epsilon(), Double.MaxValue)
buffer2.apply1(e => ev.clip(ev.abs(e), epsilon, maxValue))
buffer1.div(buffer2)
output = ev.times(buffer1.mean(), ev.fromType(100.0))
output
}
override def updateGradInput(input: Tensor[T], target: Tensor[T]): Tensor[T] = {
val norm : T = ev.fromType(100.0 / input.nElement())
buffer1.resizeAs(input).copy(input)
gradInput.resizeAs(target).copy(target)
val func = new TensorFunc6[T] {
override def apply(inputBuf: Array[T], inputOffset: Int, targetClipBuf: Array[T],
targetClipOffset: Int, gradInputBuf: Array[T], gradInputOffset: Int): Unit = {
val a = inputBuf(inputOffset)
val b = targetClipBuf(targetClipOffset)
val c = gradInputBuf(gradInputOffset)
if (a == c) {
// x=y, gradInput value = 0
gradInputBuf(gradInputOffset) = ev.zero
} else if (ev.isGreater(a, c)) {
// x > y, gradInput value = 1/K.clip(K.abs(y), K.epsilon(), Double.MaxValue)
gradInputBuf(gradInputOffset) = ev.divide(ev.one, b)
} else {
// x < y, , gradInput value = -1/K.clip(K.abs(y), K.epsilon(), Double.MaxValue)
gradInputBuf(gradInputOffset) = ev.divide(negativeOne, b)
}
}
}
DenseTensorApply.apply3(buffer1, buffer2, gradInput, func)
gradInput.mul(norm)
gradInput
}
override def canEqual(other: Any): Boolean =
other.isInstanceOf[MeanAbsolutePercentageCriterion[T]]
override def equals(other: Any): Boolean = other match {
case that: MeanAbsolutePercentageCriterion[T] =>
super.equals(that) &&
(that canEqual this)
case _ => false
}
override def hashCode(): Int = {
val state = Seq(super.hashCode())
state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
}
}
object MeanAbsolutePercentageCriterion {
def apply[T : ClassTag]()(implicit ev: TensorNumeric[T]): MeanAbsolutePercentageCriterion[T]
= new MeanAbsolutePercentageCriterion[T]()
}
|
"""
Created on Mon Apr 26 10:13:34 2021.
@author: tom
"""
from typing import Tuple, Optional, Dict, TypedDict
import numpy as np
from qiskit_optimization import QuadraticProgram
from utilities.helpers import cplex_varname
class RQuboBoundaries(TypedDict):
"""Boundary dict typing class for RandomQubo instances."""
Q: Tuple[int, int]
c: Tuple[int, int]
class RandomQubo(QuadraticProgram):
"""Random qubo class.
Defines a class with randomly constructed qubos.
It is an optimization problem in which the objective function is quadratic and
no constraints exist.
Problem:
:math:`
\\underset{x}{\\min}\\quad \\frac{1}{2} x^T Q x + c^T x \\
Q \\in \\mathbb{Z}^{n\\times n}, c \\in \\mathbb{Z}^{n} \\
x \\in \\mathbb{F}^{n}\\
`
The random instance is constructed as follows:
Choose random Q and c multiple times to create sparse problems with clear structure.
"""
def __init__(
self,
num_vars: int,
name: str,
multiple: int = 1,
*,
boundaries: Optional[RQuboBoundaries] = None,
):
"""
Create an instance of RandomQubo with specified boundaries.
Args:
num_vars (int): Number of Variables.
name (str): Name of Quadratic Program.
multiple (int, optional): Create mutiple unconnected parts with
num_vars variables each.
boundaries (Optional[dict], optional):
Dictionary with bounds as follows. Defaults to None.
"Q" : Lower and upper bound for objective matrix Q.
"c" : Lower and upper bound for objective vector c.
"""
super().__init__(name)
self._num_vars = num_vars
self._multiple = multiple
if boundaries is not None:
self._populate_random(boundaries)
def _populate_random(self, boundaries):
linear_objective = np.array([])
quadratic_objective = {}
for k in range(self._multiple):
self._add_vars(k)
quadratic_objective.update(self._create_quadratic_data(k, boundaries))
vec_c = self._create_linear_data(boundaries)
linear_objective = np.append(linear_objective, vec_c)
self.minimize(linear=linear_objective, quadratic=quadratic_objective)
def _create_quadratic_data(self, k: int, boundaries: dict) -> Dict[Tuple[str, str], int]:
"""Create random quadratic data Q."""
# pylint: disable=invalid-name
matrix_q_lb, matrix_q_ub = boundaries["Q"]
n = self._num_vars
quadratic = {}
Q = np.random.randint(matrix_q_lb, matrix_q_ub + 1, size=(n, n))
for i in range(n):
for j in range(i, n):
var_i = cplex_varname(k, i)
if i == j:
quadratic[var_i, var_i] = Q[i, i]
else:
var_j = cplex_varname(k, j)
quadratic[var_i, var_j] = Q[i, j] + Q[j, i]
return quadratic
def _create_linear_data(self, boundaries: dict) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Create random linear data A, b and c."""
# pylint: disable=invalid-name
c_lb, c_ub = boundaries["c"]
c = np.random.randint(c_lb, c_ub + 1, size=self._num_vars)
return c
def _add_vars(self, var_k: int):
"""Add variables to CPLEX model."""
for j in range(self._num_vars):
self.binary_var(cplex_varname(var_k, j))
@classmethod
def create_random_qubo(
cls,
name: str,
num_vars: int,
*,
multiple: int = 1,
matrix_q_lb: int = -1,
matrix_q_ub: int = 1,
c_lb: int = -1,
c_ub: int = 1,
) -> "RandomQubo":
"""
Create an instance of RandomQubo with specified and/or default bounds.
Args:
name (str): Name of binary Program..
num_vars (int): Number of Variables.
multiple (int, optional): Create mutiple unconnected parts with
num_vars each. Defaults to 1.
matrix_q_lb (int, optional): Lower bound for objective matrix Q.
Defaults to -1.
matrix_q_ub (int, optional): Upper bound for objective matrix Q.
Defaults to 1.
c_lb (int, optional): Lower bound for objective vector c.
Defaults to -1.
c_ub (int, optional): Upper bound for objective vector c.
Defaults to 1.
Returns:
RandomQubo: An instance of RandomQubo.
"""
boundaries = {"Q": (matrix_q_lb, matrix_q_ub), "c": (c_lb, c_ub)}
return RandomQubo(num_vars, name, multiple, boundaries=boundaries)
|
#!/bin/bash
doxygen
mv html/class_q_*.html .
rm -r html
|
class Post < ApplicationRecord
$categorie = [
[1, 'problema' , 'cogs', '1abc9c'],
[2, 'tutorial', 'graduation-cap', '8e44ad'],
[3, 'sfida', 'cube', 'e74c3c'],
[4, 'hardware', 'hdd-o', '34495e'],
[5, 'off topic', 'coffee', 'd35400'],
]
def self.numCategorie
return $categorie.length
end
def self.categoryInfo(what, v)
for i, j, k, z in $categorie do
if v == i then
return case what
when 'name'; j
when 'fa'; k
else; z
end
end
end
end
def self.editPostError(v)
return case v
when 'Ok'; 'Post modificato'
when '2'; 'Lunghezza post non valida'
when '3'; 'Post inesistente'
when '5'; 'Puoi aggiungere massimo 5 tags'
when '6'; 'Un tag può essere lungo max 10 caratteri'
else; 'Errore'
end
end
end
|
package com.curtisnewbie;
import com.curtisnewbie.demo.DummyBean;
import com.curtisnewbie.demo.MaskedTommy;
import com.curtisnewbie.demo.SomebodyBean;
import com.curtisnewbie.demo.TommyBean;
import com.curtisnewbie.module.ioc.annotations.MBean;
import com.curtisnewbie.module.ioc.context.ApplicationContext;
import com.curtisnewbie.module.ioc.aware.ApplicationContextAware;
import com.curtisnewbie.module.ioc.context.BeanRegistry;
import com.curtisnewbie.module.ioc.context.ApplicationContextFactory;
import com.curtisnewbie.module.ioc.context.ContextInitializer;
@MBean
public class App implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
// initialise context
ContextInitializer contextInitializer = ApplicationContextFactory.getNewContextInitializer();
// might mute the logs in context and context initializer
// if (contextInitializer.canMuteLog())
// contextInitializer.muteLog();
contextInitializer.initialize(App.class);
// get registry
BeanRegistry registry = applicationContext.getBeanRegistry();
// demo
SomebodyBean b = registry.getBeanByClass(SomebodyBean.class);
b.sayName();
MaskedTommy mt = registry.getBeanByClass(MaskedTommy.class);
mt.sayName();
TommyBean tb = registry.getBeanByClass(TommyBean.class);
tb.sayName();
DummyBean db = registry.getBeanByClass(DummyBean.class);
db.sayName();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
App.applicationContext = applicationContext;
}
}
|
from source import db, login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
#load users allows flask loging to load the current user and grab their # ID
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
###THIS FILE CREATES VIEWS/TABLES for the * DATABASE *
class User(db.Model,UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)#this ensures primary keys are used in this TABLES
email = db.Column(db.String(64),unique = True, index = True)
username = db.Column(db.String(64),unique = True, index = True)
password_hash = db.Column(db.String(128))
#creating instance of this object
def __init__(self, email, username, password):
self.email = email
self.username = username
self.password_hash = generate_password_hash(password)
#checking if the user credentials are correct
def check_password(self, ppassword):
return check_password_hash(self.password_hash,password)
|
namespace Amazon.Lambda.CloudWatchEvents.BatchEvents
{
/// <summary>
/// AWS Batch Event
/// https://docs.aws.amazon.com/batch/latest/userguide/batch_cwe_events.html
/// </summary>
public class BatchJobStateChangeEvent : CloudWatchEvent<Job>
{
}
}
|
package gl
import (
"errors"
"fmt"
"strings"
mgl "github.com/go-gl/mathgl/mgl32"
"github.com/gopherjs/gopherjs/js"
)
type Shader struct {
shader *js.Object
attribNames []string
}
const (
COMPILE_STATUS = 0x8B81
VERTEX_SHADER = 0x8B31
FRAGMENT_SHADER = 0x8B30
)
var (
currentBoundShader *Shader
)
func CompileShader(vertexCode, fragCode string) (*Shader, error) {
vertexCode, attribNames := convertToWebShader(vertexCode, true)
vertex := webgl.Call("createShader", VERTEX_SHADER)
webgl.Call("shaderSource", vertex, vertexCode)
webgl.Call("compileShader", vertex)
if err := checkError(vertex); err != nil {
return nil, err
}
fragCode, _ = convertToWebShader(fragCode, false)
frag := webgl.Call("createShader", FRAGMENT_SHADER)
webgl.Call("shaderSource", frag, fragCode)
webgl.Call("compileShader", frag)
if err := checkError(frag); err != nil {
return nil, err
}
shader := webgl.Call("createProgram")
webgl.Call("attachShader", shader, vertex)
webgl.Call("attachShader", shader, frag)
webgl.Call("linkProgram", shader)
return &Shader{shader, attribNames}, nil
}
// TODO actually make this work properly instead of just hacks
func convertToWebShader(shader string, isVertex bool) (string, []string) {
// Remove version tag
shader = strings.ReplaceAll(shader, "#version 410 core", "")
if isVertex {
return convertVertex(shader)
}
return convertFragment(shader)
}
func convertVertex(shader string) (string, []string) {
attribNames := []string{}
// TODO make this run instead of just relying on location
// Replace layout with attribute
for i := 0; i < 10; i++ {
shader = strings.ReplaceAll(shader,
fmt.Sprintf("layout (location = %d) in", i), "attribute")
}
// Replace out with varying
shader = strings.ReplaceAll(shader, "out", "varying")
// Get all attribute names
for _, v := range strings.Split(shader, "\n") {
if strings.Contains(v, "void main()") {
break
}
if strings.Contains(v, "attribute") {
bySpace := strings.Split(v, " ")
attribName := bySpace[len(bySpace)-1]
attribNames = append(attribNames, attribName[:len(attribName)-1])
}
}
return shader, attribNames
}
func convertFragment(shader string) (string, []string) {
shader = "precision mediump float;\n" + shader
// Remove out vec4 color;
shader = strings.ReplaceAll(shader, "out vec4 FragColor;", "")
// Replace color with gl_FragColor
shader = strings.ReplaceAll(shader, "FragColor", "gl_FragColor")
// Replace in with varying
shader = strings.ReplaceAll(shader, "in ", "varying ")
// Replace texture with texture2d
shader = strings.ReplaceAll(shader, "texture(", "texture2D(")
// Handle cubemaps making texture -> textureCube
for _, v := range strings.Split(shader, "\n") {
if strings.Contains(v, "void main()") {
break
}
if strings.Contains(v, "uniform samplerCube") {
bySpace := strings.Split(v, " ")
cubeName := bySpace[len(bySpace)-1]
cubeName = cubeName[:len(cubeName)-1]
shader = strings.ReplaceAll(shader, "texture2D("+cubeName,
"textureCube("+cubeName)
}
}
return shader, nil
}
func checkError(shader *js.Object) error {
if !webgl.Call("getShaderParameter", shader, COMPILE_STATUS).Bool() {
return errors.New(webgl.Call("getShaderInfoLog", shader).String())
}
return nil
}
func (s *Shader) Use() *Shader {
webgl.Call("useProgram", s.shader)
currentBoundShader = s
return s
}
func (s *Shader) SetBool(name string, value bool) *Shader {
var intValue int32 = 0
if value {
intValue = 1
}
webgl.Call("uniform1i", webgl.Call("getUniformLocation", s.shader, name),
intValue)
return s
}
func (s *Shader) SetInt(name string, value int32) *Shader {
webgl.Call("uniform1i", webgl.Call("getUniformLocation", s.shader, name),
value)
return s
}
func (s *Shader) SetFloat(name string, value float32) *Shader {
webgl.Call("uniform1f", webgl.Call("getUniformLocation", s.shader, name),
value)
return s
}
func (s *Shader) SetVec2(name string, value mgl.Vec2) *Shader {
webgl.Call("uniform2fv", webgl.Call("getUniformLocation", s.shader, name),
value) // TODO verify this
return s
}
func (s *Shader) SetVec3(name string, value mgl.Vec3) *Shader {
webgl.Call("uniform3fv", webgl.Call("getUniformLocation", s.shader, name),
value) // TODO verify this
return s
}
func (s *Shader) SetMat4(name string, value mgl.Mat4) *Shader {
webgl.Call("uniformMatrix4fv", webgl.Call("getUniformLocation", s.shader, name),
false, value) // TODO verify this
return s
}
|
import React from 'react';
import { useFormikContext } from 'formik';
import Form, { Row } from '../../components/form';
import { TextInput } from '../../components/input';
import { validate, notEmpty } from '../../validation';
export interface AddressValues {
firstName: string;
lastName: string;
companyName: string;
street: string;
zipCode: string;
city: string;
country: string;
}
export const INITIAL_ADDRESS_VALUES: AddressValues = {
firstName: '',
lastName: '',
companyName: '',
street: '',
zipCode: '',
city: '',
country: 'CHE',
};
export const validateAddress = validate([
notEmpty<AddressValues>('firstName'),
notEmpty<AddressValues>('lastName'),
notEmpty<AddressValues>('street'),
notEmpty<AddressValues>('zipCode'),
notEmpty<AddressValues>('city'),
]);
const AddressForm: React.FC = () => {
const formik = useFormikContext<AddressValues>();
return (
<Form>
<Row label="First name">
<TextInput
name="firstName"
value={formik.values.firstName || ''}
placeholder="First name"
onChange={formik.handleChange}
errors={formik.errors.firstName}
/>
</Row>
<Row label="Last name">
<TextInput
name="lastName"
value={formik.values.lastName || ''}
placeholder="Last name"
onChange={formik.handleChange}
errors={formik.errors.lastName}
/>
</Row>
<Row label="Company name">
<TextInput
name="companyName"
value={formik.values.companyName || ''}
placeholder="Company name"
onChange={formik.handleChange}
errors={formik.errors.companyName}
/>
</Row>
<Row label="Street">
<TextInput
name="street"
value={formik.values.street || ''}
placeholder="Street"
onChange={formik.handleChange}
errors={formik.errors.street}
/>
</Row>
<Row label="Zip code">
<TextInput
name="zipCode"
value={formik.values.zipCode || ''}
placeholder="Zip code"
onChange={formik.handleChange}
errors={formik.errors.zipCode}
/>
</Row>
<Row label="City">
<TextInput
name="city"
value={formik.values.city || ''}
placeholder="City"
onChange={formik.handleChange}
errors={formik.errors.city}
/>
</Row>
</Form>
);
};
export default AddressForm;
|
##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# http://www.morningstarsecurity.com/research/whatweb
##
Plugin.define "Tradingeye" do
author "Brendan Coles <[email protected]>" # 2011-07-13
version "0.1"
description "Tradingeye is a fully-featured web standards compliant Shopping Cart & CMS, built from the ground up with web accessibility and SEO in mind."
website "http://tradingeye.com/"
# Google results as at 2011-07-13 #
# 267 for "Powered by Tradingeye" "You are here: Home"
# Dorks #
dorks [
'"Powered by Tradingeye" "You are here: Home"'
]
# Matches #
matches [
# Aggressive # favicon.ico
{ :url=>"/favicon.ico", :md5=>"0ec12e5820517d3b62e56b9a8f1ee5bc" },
{ :url=>"/_assets/img/site/favicon.ico", :md5=>"0ec12e5820517d3b62e56b9a8f1ee5bc" },
# Powered by text
{ :text=>'<p id="credits"><a href="http://www.tradingeye.com/">powered by Tradingeye</a></p>' },
# Meta Author
{ :text=>'<meta name="author" content="dpivision.com Ltd" />' },
# p id="breadcrumbs"
{ :certainty=>25, :text=>'<p id="breadcrumbs">You are here:' },
# HTML Comment
{ :certainty=>25, :text=>'</div><!-- end body/inner -->' },
# skip to main content
{ :text=>'<p id="skip">[<a href="#main">skip to main content</a>]</p>' },
# Version Detection # Admin Page # Title
{ :version=>/<title>Tradingeye v([^\s]+) :: Online Admin<\/title>/ },
# Admin Page # th class="login_bg"
{ :text=>'<th class="login_bg" colspan="2">Tradingeye Login</th>' },
]
end
|
# Adapted from prior work by Simon Jupp @ EMBL-EBI
#
# https://github.com/HumanCellAtlas/hca_bundles_to_csv/blob/b516a3a/hca_bundle_tools/file_metadata_to_csv.py
import re
from typing import (
Any,
List,
Mapping,
MutableMapping,
MutableSet,
Optional,
Tuple,
Union,
)
from urllib import (
parse,
)
from azul.indexer import (
Bundle,
)
from azul.types import (
JSON,
MutableJSONs,
)
Output = MutableMapping[Union[str, Tuple[str]], Union[str, MutableSet[str]]]
class FullMetadata:
"""
Generates a more or less verbatim but unharmonized JSON representation of
the metadata in a bundle.
"""
column_order = [
'path',
'^\\*\\.file_core\\.file_name',
'^\\*\\.file_core\\.file_format',
'^sequence_file.*',
'^analysis_file.*',
'^donor_organism.*',
'^specimen_from_organism.*',
'^cell_suspension.*',
'^.*protocol.*',
'^project.',
'^analysis_process.*',
'^process.*',
'^bundle_.*',
'^file_.*'
]
ignored_fields = [
'describedBy',
'schema_type',
'submission_date',
'update_date',
'process_id',
'contributors',
'publications',
'protocol_id',
'project_description',
'file_format',
'file_name'
]
format_filter = None
uuid4hex = re.compile('^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', re.I)
def __init__(self):
self.output: List[JSON] = []
self.blocked_file_type = {'supplementary_file', 'reference_file'}
def _resolve_data_file_names(self,
manifest: List[JSON],
metadata_files: Mapping[str, JSON]) -> MutableMapping[str, Tuple[JSON, JSON]]:
"""
Associate each metadata document describing a data file with the UUID
of the data file it describes. The metadata only refers to data files by
name and we need the manifest to resolve those into UUIDs.
"""
manifest = {entry['name']: entry for entry in manifest}
file_info = {}
for metdata_file_name, metadata_file in metadata_files.items():
try:
schema_type = metadata_file['schema_type']
except KeyError:
raise MissingSchemaTypeError
else:
if schema_type == 'file' and not manifest[metdata_file_name].get('is_stitched', False):
file_name = self._deep_get(metadata_file, 'file_core', 'file_name')
if file_name is None:
raise MissingFileNameError
else:
manifest_entry = manifest[file_name]
file_info[manifest_entry['uuid']] = manifest_entry, metadata_file
if file_info:
return file_info
else:
raise EmptyBundleError
def _deep_get(self, d: JSON, *path: str) -> Optional[JSON]:
if d is not None and path:
key, *path = path
return self._deep_get(d.get(key), *path)
else:
return d
@staticmethod
def _set_value(output: Output, value: Any, *path: str) -> None:
value = str(value)
try:
old_value = output[path]
except KeyError:
output[path] = value
else:
if isinstance(old_value, set):
old_value.add(value)
else:
output[path] = {old_value, value}
def _flatten(self, output: Output, obj: JSON, *path: str) -> None:
for key, value in obj.items():
if key not in self.ignored_fields:
new_path = *path, key
if isinstance(value, dict):
self._flatten(output, obj[key], *new_path)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
self._flatten(output, item, *new_path)
else:
self._set_value(output, item, *new_path)
else:
self._set_value(output, value, *new_path)
@classmethod
def _get_schema_name(cls, obj: JSON):
try:
described_by = obj['describedBy']
except KeyError:
raise MissingDescribedByError
else:
return described_by.rsplit('/', 1)[-1]
def _handle_zarray_members(self, obj, anchor):
"""
Returns True, if and only if the given document describes a zarray
member that should be ignored. If the given file describes a zarray
member that represents the entire zarray store, the file_name property
of the document is changed to the path to the zarray file and False is
returned. For all other files, this method just returns False.
"""
file_name = obj['file_name']
try:
i = file_name.index(anchor)
except ValueError:
return False
else:
i += len(anchor) - 1
dir_name, file_name = file_name[0:i], file_name[i + 1:]
if file_name == '.zattrs':
obj['file_name'] = dir_name + '/'
return False
return True
def add_bundle(self, bundle: Bundle) -> None:
file_info = self._resolve_data_file_names(bundle.manifest, bundle.metadata_files)
for file_manifest, metadata_file in file_info.values():
output = {
'bundle_uuid': bundle.uuid,
'bundle_version': bundle.version,
'file_uuid': file_manifest['uuid'],
'file_version': file_manifest['version'],
'file_crc32c': file_manifest['crc32c'],
'file_sha256': file_manifest.get('sha256'), # sha256 not included in DCPv2 file manifests
'file_size': file_manifest['size'],
'file_name': self._deep_get(metadata_file, 'file_core', 'file_name'),
'file_format': self._deep_get(metadata_file, 'file_core', 'file_format'),
}
described_by = self._deep_get(metadata_file, 'describedBy')
assert isinstance(described_by, str)
described_by = parse.urlparse(described_by)
_, _, schema_type = described_by.path.rpartition('/')
if schema_type in self.blocked_file_type:
continue
if any(self._handle_zarray_members(output, anchor) for anchor in ('.zarr/', '.zarr!')):
continue
if self.format_filter and output['file_format'] not in self.format_filter:
continue
schema_name = self._get_schema_name(metadata_file)
self._flatten(output, metadata_file, schema_name)
for other_metadata_file in bundle.metadata_files.values():
if other_metadata_file['schema_type'] not in ('file', 'link_bundle'):
schema_name = self._get_schema_name(other_metadata_file)
self._flatten(output, other_metadata_file, schema_name)
self.output.append(self._output_to_json(output))
def _output_to_json(self, output: Output) -> JSON:
"""
Convert output to JSON by joining tuple keys with '.' and set values with '||'.
"""
return {
('.'.join(k) if isinstance(k, Tuple) else k): ('||'.join(sorted(v)) if isinstance(v, set) else v)
for k, v in output.items()
}
def dump(self) -> MutableJSONs:
output = self.output
self.output = None
return output
class Error(Exception):
msg = None
def __init__(self, *args: object) -> None:
super().__init__(self.msg, *args)
class MissingSchemaTypeError(Error):
"""
Prove that the traceback includes the message from `msg`
>>> raise MissingSchemaTypeError
Traceback (most recent call last):
...
azul.plugins.metadata.hca.full_metadata.MissingSchemaTypeError: Metadata document lacks `schema_type` property
"""
msg = 'Metadata document lacks `schema_type` property'
class MissingDescribedByError(Error):
msg = 'Metadata document lacks a `describedBy` property'
class EmptyBundleError(Error):
msg = 'Bundle contains no data files'
class MissingFileNameError(Error):
msg = 'Metadata document for data file lacks `file_core.file_name` property'
|
# fishBehavior
Analysis tools for Chen-min's fish behavior experiments.
--------------------------------------------------------------------------------
(c) COPYRIGHT 2015 The Salk Institute. All rights reserved.
The party (the "Recipient") receiving this software directly from the Salk
Institute may use this software and make copies thereof as reasonably necessary
solely for the purposes set forth in the agreement between the Recipient and
the Salk Institute (the "Agreement"). The software may be used in source code
form solely by the Recipient's employees. The Recipient shall have no right to
sublicense, assign, transfer or otherwise provide the source code to any
third party. Subject to the terms and conditions set forth in the Agreement,
this software, in binary form only, may be distributed by the Recipient to
its customers. The Salk Institute retains all ownership rights in and to the
software.
This notice shall supercede any other notices contained within the software.
Xin Wang <[email protected]>
--------------------------------------------------------------------------------
|
-- | The module introduces some types related to 'Core.Authorization'
-- module. It allows breaking dependency cycles between modules.
module Core.Permission
( Permission(..)
) where
import Core.Author
import Core.Deletable
import Core.User
data Permission
= AdminPermission
| AuthorshipPermission (Deletable AuthorId)
| AdminOrSpecificUserPermission UserId
deriving (Eq, Show)
|
require('../config/passport');
const express = require('express');
const Rating = require('../models/Rating');
const router = express.Router();
const isAuth = require('../middlewares/isAuthenticated.middleware');
// add new rating
router.post('/', [isAuth], (req, res) => {
const { id } = req.user;
const newRating = new Rating({
rating: parseInt(req.body.rating),
user: id,
});
newRating
.save()
.then((storedRating) => {
res.status(200).send(newRating);
})
.catch((err) => {
res.status(500).json(err.message);
});
});
//esta ruta es solo una prueba para saber como funciona el populate, se podrá borrar
//quizá no, así se busca el rating de un usuario, solo que en ruta autenticada mejor
router.get('/', [isAuth], (req, res) => {
const { id } = req.user;
Rating.findOne({ user: id })
.populate('user')
.then((rating) => {
return res.json(rating);
})
.catch((err) => {
res.status(500).json(err.message);
});
});
module.exports = router;
|
#!/usr/bin/env bash
set -e
source ./env.sh
echo "Destroying CDK Cloudformation Stack -- Some manual removal required"
npm run cdk-destroy --prefix cdk
|
<?php
class ScoreModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
/////////////////////////
// CRUD-actions
/////////////////////////
/** Returns all scores as an array */
public function get_all_scores()
{
return $this->db->get('score')->result();
}
/** Adds a score to the DB */
public function add_score($score)
{
$this->db->insert('score', $score);
return $this->db->insert_id();
}
/** Updates the score specified by the id with the details of the score */
public function update_score($score_id, $score)
{
$this->db->where('id', $score_id);
$this->db->update('score', $score);
}
/** Adds a score to the DB, updates when already exists */
public function add_or_update_score($score)
{
// TODO: has to be changed
$s = $this->get_score($score['testcat_id'], $score['participant_id']);
if ($s)
{
$this->update_score($s->id, $score);
return $s->id;
}
else return $this->add_score($score);
}
/** Deletes a score from the DB */
public function delete_score($score_id)
{
$this->db->delete('score', array('id' => $score_id));
}
/** Returns the score for an id */
public function get_score_by_id($score_id)
{
return $this->db->get_where('score', array('id' => $score_id))->row();
}
/** Retrieves a score for a test category and a testinvite (unique key) */
public function get_score_by_testcat_testinvite($testcat_id, $testinvite_id)
{
$this->db->where('testcat_id', $testcat_id);
$this->db->where('testinvite_id', $testinvite_id);
return $this->db->get('score')->row();
}
/////////////////////////
// Testinvites
/////////////////////////
/** Returns the scores for a testinvite */
public function get_scores_by_testinvite($testinvite_id)
{
$this->db->where('testinvite_id', $testinvite_id);
return $this->db->get('score')->result();
}
/** Returns the testinvite for a score */
public function get_testinvite_by_score($score)
{
return $this->db->get_where('testinvite', array('id' => $score->testinvite_id))->row();
}
/////////////////////////
// Testsurvey
/////////////////////////
/** Returns the scores for a testsurvey */
public function get_scores_by_testsurvey($testsurvey_id)
{
$this->db->join('testinvite', 'score.testinvite_id = testinvite.id');
$this->db->join('testsurvey', 'testinvite.testsurvey_id = testsurvey.id');
$this->db->where('testsurvey.id', $testsurvey_id);
return $this->db->get('score')->result();
}
/** Returns the testsurvey for a score */
public function get_testsurvey_by_score($score)
{
$this->db->select('testsurvey.*');
$this->db->from('testsurvey');
$this->db->join('testinvite', 'testinvite.testsurvey_id = testsurvey.id');
$this->db->join('score', 'score.testinvite_id = testinvite.id');
$this->db->where('testinvite.id', $score->testinvite_id);
return $this->db->get()->row();
}
/////////////////////////
// Participants
/////////////////////////
/** Returns the scores for a participant */
public function get_scores_by_participant($participant_id)
{
$this->db->select('score.*');
$this->db->join('testinvite', 'score.testinvite_id = testinvite.id');
$this->db->join('participant', 'testinvite.participant_id = participant.id');
$this->db->where('participant.id', $participant_id);
return $this->db->get('score')->result();
}
/** Returns the participant for a score */
public function get_participant_by_score($score)
{
$this->db->select('participant.*');
$this->db->join('testinvite', 'testinvite.participant_id = participant.id');
$this->db->where('testinvite.id', $score->testinvite_id);
return $this->db->get('participant')->row();
}
/////////////////////////
// Test categories
/////////////////////////
/** Returns all scores for a test category */
public function get_scores_by_testcat($testcat_id)
{
$this->db->where('testcat_id', $testcat_id);
return $this->db->get('score')->result();
}
/** Returns all scores for a test category, including that of its children */
public function get_all_scores_by_testcat($testcat_id)
{
$this->db->select('score.*');
$this->db->from('score');
$this->db->join('testcat', 'score.testcat_id = testcat.id');
$this->db->where('testcat.id', $testcat_id);
$this->db->or_where('testcat.parent_id', $testcat_id);
return $this->db->get()->result();
}
/** Returns the test category for a score */
public function get_testcat_by_score($score)
{
return $this->db->get_where('testcat', array('id' => $score->testcat_id))->row();
}
/** Returns the score for a test category and an array fo testinvite ids */
public function get_score($testcat_id, $testinvite_ids)
{
# assume no testinvite ids that appear in an emtpy array can be found
if(empty($testinvite_ids)) return NULL;
$this->db->select('score');
$this->db->where('testcat_id', $testcat_id);
$this->db->where_in('testinvite_id', $testinvite_ids);
return $this->db->get()->row();
}
/////////////////////////
// Tests
/////////////////////////
/** Returns all scores for a test */
public function get_scores_by_test($test_id)
{
$this->db->join('testcat', 'score.testcat_id = testcat.id');
$this->db->join('test', 'testcat.test_id = test.id');
$this->db->where('test.id', $test_id);
return $this->db->get('score')->result();
}
/** Returns the test for a score */
public function get_test_by_score($score)
{
$this->db->select('test.*');
$this->db->from('test');
$this->db->join('testcat', 'testcat.test_id = test.id');
$this->db->join('score', 'score.testcat_id = testcat.id');
$this->db->where('testcat.id', $score->testcat_id);
return $this->db->get()->row();
}
}
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This module contains functions for producing scatter plots with markers
that indicate which binary flags are set on each data point and accompanying
legends.
The output of the main scatterflags() function can be used as the input to
the flagbar() function to produce a colorbar.
Example usage:
import scatterflags as sf
import numpy as np
import matplotlib.pyplot as plt
npts=50
x = np.arange(npts)
y = np.random.randn(npts)
f,(ax0,ax1) = plt.subplots(2,1,figsize=(6,5),gridspec_kw={'height_ratios':[4,1]})
kwargs = sf.scatterflags(x,y,np.round(np.random.randint(1,64,npts)),ax=ax0)
ax0.scatter(x,y,c='0',s=1,zorder=10,marker='*')
ax0.set_xlabel('x')
ax0.set_ylabel('y')
sf.flagbar(cax=ax1,flaglabels=['flag'+str(i) for i in range(6)],barlabel='flags',**kwargs)
plt.tight_layout()
plt.show()
@author: [email protected]
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
def scatterflags(x,y,flags,r=5.,dr=5.,ax=None,nflags=None,colors=None,cmap=None,
minzorder=1,**kwargs):
"""Plot scatter markers that indicate associated set flags.
Args:
x, y: input data
flags: per-point flags (bitwise binary strings or base10 equiv ints)
r: radius (pixels) of smallest marker (default: 5)
dr: radius increase per flag (default: 5)
ax: axis for scatterplot (optional)
nflags: number of possible flags (can be inferred from flags)
colors: colors to plot for each flag
cmap: colormap to use for automaticly picking colors from (no jet!)
minzorder: zorder of last flag (each earlier flag has one higher zorder)
**kwargs: other keywords to pass to scatter (e.g. marker)
Returns:
kwargs for flagbar() function (produces colorbar legend)
"""
#Where is this plot going?
if ax is None:
ax = plt.gca()
#Convert all integer strings to bitwise flags
flags = [bin(num)[2:] for num in flags if isinstance(num, (int, long, np.integer))]
#Set number of flags if not explicit
if nflags is None:
nflags = max([len(flag) for flag in flags])
#Pad string flags to (at least) nflags
flags = [flag.zfill(nflags) for flag in flags]
#Each flag needs an associated color
#These may have been explicitly included
ncolors = nflags
#If fewer colors were included, cycle through
if colors is not None:
colors = [colors[i % len(colors)] for i in range(nflags)]
else: #colors not specified
colors = sns.color_palette(cmap,nflags)
#Define marker sizes
ms = (r+dr*np.arange(nflags))**2.
#Scatter plot for each flag
#Smallest to largest (highest zorder to lowest = minzorder)
for i in range(nflags):
flagged = np.where([int(chars[-i-1]) for chars in flags])
ax.scatter(x[flagged],y[flagged],s=ms[i],c=mpl.colors.to_hex(colors[i]),
lw=0,zorder=minzorder+nflags-i,**kwargs)
#Return dict of kwargs for formatting the colorbar
return dict({'r':r,'dr':dr,'nflags':nflags,'colors':colors},**kwargs)
def flagbar(cax=None,nflags=None,r=5.,dr=5.,colors=None,cmap=None,
flaglabels=None,barlabel=None,**kwargs):
"""Plot colorbar with scatter marker shapes/sizes
Args:
cax: target axis for colorbar (short and wide ideally)
nflags: number of different flags
r: radius (pixels) of smallest marker (default: 5)
dr: radius increase per flag (default: 5)
colors: colors to plot for each flag
cmap: colormap to use for automaticly picking colors from (no jet!)
flaglabels: str labels associated with each flag
barlabel: overall label for colorbar
**kwargs: other keywords to pass to scatter (e.g. marker)
Note: besides the cax, the returned dicts from scatterflags() will set
the rest of these args appropriately. Call as `flagbar(cax,**kwargs)`
where `kwargs = scatterflags(...)`
"""
#Determine number of flags to represent
if nflags is None:
if flaglabels is not None:
nflags = len(flaglabels)
elif colors is not None:
nflags = len(colors)
#Throw and error if number of flags not defined
try:
_ = int(nflags)
except TypeError:
raise ValueError("Must specify number of flags to flagbar, explicitly or implicitly.")
#Each flag needs an associated color
#These may have been explicitly included
ncolors = nflags
#If fewer colors were included, cycle through
if colors is not None:
colors = [colors[i % len(colors)] for i in range(nflags)]
else: #colors not specified
colors = sns.color_palette(cmap,nflags)
#Define marker sizes
ms = (r+dr*np.arange(nflags))**2.
#Length of flaglabels must be nflags
if flaglabels is None:
flaglabels = []
nflaglabels = len(flaglabels)
if nflaglabels < nflags:
flaglabels += [""]*(nflags-nflaglabels)
else:
flaglabels = flaglabels[:nflags]
#Where to plot
if cax is None: #Probably better to specify
cax = plt.gca()
#Plot colorbar
colorbounds = np.linspace(0,1,nflags+1)
colorcenters = (colorbounds[1:]+colorbounds[:-1])/2.
cb = mpl.colorbar.ColorbarBase(cax,cmap=mpl.colors.ListedColormap(colors),
ticks=colorcenters,spacing='proportional',
orientation='horizontal')
cb.ax.set_xticklabels(flaglabels,rotation=45) #label flags under colorbar
if barlabel is not None: #label y axis side
cax.set_ylabel(barlabel)
cax.scatter(colorcenters,[.5]*nflags,edgecolor='0',s=ms,c='none',**kwargs)
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.annotation.CallSuper
import androidx.annotation.IdRes
import androidx.annotation.MainThread
import androidx.annotation.NavigationRes
import androidx.annotation.RestrictTo
import androidx.core.app.TaskStackBuilder
import androidx.core.net.toUri
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.navigation.NavDestination.Companion.createRoute
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
/**
* NavController manages app navigation within a [NavHost].
*
* Apps will generally obtain a controller directly from a host, or by using one of the utility
* methods on the [Navigation] class rather than create a controller directly.
*
* Navigation flows and destinations are determined by the
* [navigation graph][NavGraph] owned by the controller. These graphs are typically
* [inflated][getNavInflater] from an Android resource, but, like views, they can also
* be constructed or combined programmatically or for the case of dynamic navigation structure.
* (For example, if the navigation structure of the application is determined by live data obtained'
* from a remote server.)
*/
public open class NavController(
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public val context: Context
) {
private var activity: Activity? = generateSequence(context) {
if (it is ContextWrapper) { it.baseContext } else null
}.firstOrNull { it is Activity } as Activity?
private var inflater: NavInflater? = null
private var _graph: NavGraph? = null
/**
* The topmost navigation graph associated with this NavController.
*
* When this is set any current navigation graph data (including back stack) will be replaced.
*
* @see NavController.setGraph
* @throws IllegalStateException if called before `setGraph()`.
*/
public open var graph: NavGraph
@MainThread
get() {
checkNotNull(_graph) { "You must call setGraph() before calling getGraph()" }
return _graph as NavGraph
}
@MainThread
@CallSuper
set(graph) {
setGraph(graph, null)
}
private var navigatorStateToRestore: Bundle? = null
private var backStackToRestore: Array<Parcelable>? = null
private var deepLinkHandled = false
/**
* Retrieve the current back stack.
*
* @return The current back stack.
* @hide
*/
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open val backQueue: ArrayDeque<NavBackStackEntry> = ArrayDeque()
private val backStackMap = mutableMapOf<Int, String?>()
private val backStackStates = mutableMapOf<String, ArrayDeque<NavBackStackEntryState>>()
private var lifecycleOwner: LifecycleOwner? = null
private var viewModel: NavControllerViewModel? = null
private val onDestinationChangedListeners =
mutableListOf<OnDestinationChangedListener>()
private val lifecycleObserver: LifecycleObserver = LifecycleEventObserver { _, event ->
if (_graph != null) {
for (entry in backQueue) {
entry.handleLifecycleEvent(event)
}
}
}
private val onBackPressedCallback: OnBackPressedCallback =
object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
popBackStack()
}
}
private var enableOnBackPressedCallback = true
/**
* OnDestinationChangedListener receives a callback when the
* [currentDestination] or its arguments change.
*/
public fun interface OnDestinationChangedListener {
/**
* Callback for when the [currentDestination] or its arguments change.
* This navigation may be to a destination that has not been seen before, or one that
* was previously on the back stack. This method is called after navigation is complete,
* but associated transitions may still be playing.
*
* @param controller the controller that navigated
* @param destination the new destination
* @param arguments the arguments passed to the destination
*/
public fun onDestinationChanged(
controller: NavController,
destination: NavDestination,
arguments: Bundle?
)
}
private var _navigatorProvider = NavigatorProvider()
@set:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
/**
* The NavController's [NavigatorProvider]. All [Navigators][Navigator] used
* to construct the [navigation graph][NavGraph] for this nav controller should be added
* to this navigator provider before the graph is constructed.
*
* This can only be set before the graph is set via `setGraph()`.
*
* Generally, the Navigators are set for you by the [NavHost] hosting this NavController
* and you do not need to manually interact with the navigator provider.
*
* @throws IllegalStateException If this set called after `setGraph()`
*/
public open var navigatorProvider: NavigatorProvider
get() = _navigatorProvider
/**
* @hide
*/
set(navigatorProvider) {
check(backQueue.isEmpty()) { "NavigatorProvider must be set before setGraph call" }
_navigatorProvider = navigatorProvider
}
private val navigatorState =
mutableMapOf<Navigator<out NavDestination>, NavControllerNavigatorState>()
private var addToBackStackHandler: ((backStackEntry: NavBackStackEntry) -> Unit)? = null
private var popFromBackStackHandler: ((popUpTo: NavBackStackEntry) -> Unit)? = null
/**
* Call [Navigator.navigate] while setting up a [handler] that receives callbacks
* when [NavigatorState.add] is called.
*/
private fun Navigator<out NavDestination>.navigateInternal(
entries: List<NavBackStackEntry>,
navOptions: NavOptions?,
navigatorExtras: Navigator.Extras?,
handler: (backStackEntry: NavBackStackEntry) -> Unit = {}
) {
addToBackStackHandler = handler
navigate(entries, navOptions, navigatorExtras)
addToBackStackHandler = null
}
/**
* Call [Navigator.popBackStack] while setting up a [handler] that receives callbacks
* when [NavigatorState.pop] is called.
*/
private fun Navigator<out NavDestination>.popBackStackInternal(
popUpTo: NavBackStackEntry,
saveState: Boolean,
handler: (popUpTo: NavBackStackEntry) -> Unit = {}
) {
popFromBackStackHandler = handler
popBackStack(popUpTo, saveState)
popFromBackStackHandler = null
}
private inner class NavControllerNavigatorState(
val navigator: Navigator<out NavDestination>
) : NavigatorState() {
override fun add(backStackEntry: NavBackStackEntry) {
val destinationNavigator: Navigator<out NavDestination> =
_navigatorProvider[backStackEntry.destination.navigatorName]
if (destinationNavigator == navigator) {
val handler = addToBackStackHandler
if (handler != null) {
handler(backStackEntry)
addInternal(backStackEntry)
} else {
// TODO handle the Navigator calling add() outside of a call to navigate()
Log.i(
TAG,
"Ignoring add of destination ${backStackEntry.destination} " +
"outside of the call to navigate(). "
)
}
} else {
val navigatorBackStack = checkNotNull(navigatorState[destinationNavigator]) {
"NavigatorBackStack for ${backStackEntry.destination.navigatorName} should " +
"already be created"
}
navigatorBackStack.add(backStackEntry)
}
}
fun addInternal(backStackEntry: NavBackStackEntry) {
super.add(backStackEntry)
}
override fun createBackStackEntry(
destination: NavDestination,
arguments: Bundle?
) = NavBackStackEntry.create(
context, destination, arguments,
lifecycleOwner, viewModel
)
override fun pop(popUpTo: NavBackStackEntry, saveState: Boolean) {
val destinationNavigator: Navigator<out NavDestination> =
_navigatorProvider[popUpTo.destination.navigatorName]
if (destinationNavigator == navigator) {
val handler = popFromBackStackHandler
if (handler != null) {
handler(popUpTo)
super.pop(popUpTo, saveState)
} else {
// TODO handle the Navigator calling pop() outside of a call to popBackStack()
Log.i(
TAG,
"Ignoring pop of destination ${popUpTo.destination} " +
"outside of the call to popBackStack(). "
)
}
} else {
navigatorState[destinationNavigator]!!.pop(popUpTo, saveState)
}
}
}
/**
* Constructs a new controller for a given [Context]. Controllers should not be
* used outside of their context and retain a hard reference to the context supplied.
* If you need a global controller, pass [Context.getApplicationContext].
*
* Apps should generally not construct controllers, instead obtain a relevant controller
* directly from a navigation host via [NavHost.getNavController] or by using one of
* the utility methods on the [Navigation] class.
*
* Note that controllers that are not constructed with an [Activity] context
* (or a wrapped activity context) will only be able to navigate to
* [new tasks][android.content.Intent.FLAG_ACTIVITY_NEW_TASK] or
* [new document tasks][android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT] when
* navigating to new activities.
*
* @param context context for this controller
*/
init {
_navigatorProvider.addNavigator(NavGraphNavigator(_navigatorProvider))
_navigatorProvider.addNavigator(ActivityNavigator(context))
}
/**
* Adds an [OnDestinationChangedListener] to this controller to receive a callback
* whenever the [currentDestination] or its arguments change.
*
* The current destination, if any, will be immediately sent to your listener.
*
* @param listener the listener to receive events
*/
public open fun addOnDestinationChangedListener(listener: OnDestinationChangedListener) {
// Inform the new listener of our current state, if any
if (backQueue.isNotEmpty()) {
val backStackEntry = backQueue.last()
listener.onDestinationChanged(
this,
backStackEntry.destination,
backStackEntry.arguments
)
}
onDestinationChangedListeners.add(listener)
}
/**
* Removes an [OnDestinationChangedListener] from this controller.
* It will no longer receive callbacks.
*
* @param listener the listener to remove
*/
public open fun removeOnDestinationChangedListener(listener: OnDestinationChangedListener) {
onDestinationChangedListeners.remove(listener)
}
/**
* Attempts to pop the controller's back stack. Analogous to when the user presses
* the system [Back][android.view.KeyEvent.KEYCODE_BACK] button when the associated
* navigation host has focus.
*
* @return true if the stack was popped at least once and the user has been navigated to
* another destination, false otherwise
*/
@MainThread
public open fun popBackStack(): Boolean {
return if (backQueue.isEmpty()) {
// Nothing to pop if the back stack is empty
false
} else {
popBackStack(currentDestination!!.id, true)
}
}
/**
* Attempts to pop the controller's back stack back to a specific destination.
*
* @param destinationId The topmost destination to retain
* @param inclusive Whether the given destination should also be popped.
*
* @return true if the stack was popped at least once and the user has been navigated to
* another destination, false otherwise
*/
@MainThread
public open fun popBackStack(@IdRes destinationId: Int, inclusive: Boolean): Boolean {
return popBackStack(destinationId, inclusive, false)
}
/**
* Attempts to pop the controller's back stack back to a specific destination.
*
* @param destinationId The topmost destination to retain
* @param inclusive Whether the given destination should also be popped.
* @param saveState Whether the back stack and the state of all destinations between the
* current destination and the [destinationId] should be saved for later
* restoration via [NavOptions.Builder.setRestoreState] or the `restoreState` attribute using
* the same [destinationId] (note: this matching ID is true whether
* [inclusive] is true or false).
*
* @return true if the stack was popped at least once and the user has been navigated to
* another destination, false otherwise
*/
@MainThread
public open fun popBackStack(
@IdRes destinationId: Int,
inclusive: Boolean,
saveState: Boolean
): Boolean {
val popped = popBackStackInternal(destinationId, inclusive, saveState)
// Only return true if the pop succeeded and we've dispatched
// the change to a new destination
return popped && dispatchOnDestinationChanged()
}
/**
* Attempts to pop the controller's back stack back to a specific destination.
*
* @param route The topmost destination to retain
* @param inclusive Whether the given destination should also be popped.
* @param saveState Whether the back stack and the state of all destinations between the
* current destination and the [route] should be saved for later
* restoration via [NavOptions.Builder.setRestoreState] or the `restoreState` attribute using
* the same [route] (note: this matching ID is true whether
* [inclusive] is true or false).
*
* @return true if the stack was popped at least once and the user has been navigated to
* another destination, false otherwise
*/
@MainThread
@JvmOverloads
public fun popBackStack(
route: String,
inclusive: Boolean,
saveState: Boolean = false
): Boolean = popBackStack(createRoute(route).hashCode(), inclusive, saveState)
/**
* Attempts to pop the controller's back stack back to a specific destination. This does
* **not** handle calling [dispatchOnDestinationChanged]
*
* @param destinationId The topmost destination to retain
* @param inclusive Whether the given destination should also be popped.
* @param saveState Whether the back stack and the state of all destinations between the
* current destination and the [destinationId] should be saved for later
* restoration via [NavOptions.Builder.setRestoreState] or the `restoreState` attribute using
* the same [destinationId] (note: this matching ID is true whether
* [inclusive] is true or false).
*
* @return true if the stack was popped at least once, false otherwise
*/
@MainThread
private fun popBackStackInternal(
@IdRes destinationId: Int,
inclusive: Boolean,
saveState: Boolean = false
): Boolean {
if (backQueue.isEmpty()) {
// Nothing to pop if the back stack is empty
return false
}
val popOperations = mutableListOf<Navigator<*>>()
val iterator = backQueue.reversed().iterator()
var foundDestination: NavDestination? = null
while (iterator.hasNext()) {
val destination = iterator.next().destination
val navigator = _navigatorProvider.getNavigator<Navigator<*>>(
destination.navigatorName
)
if (inclusive || destination.id != destinationId) {
popOperations.add(navigator)
}
if (destination.id == destinationId) {
foundDestination = destination
break
}
}
if (foundDestination == null) {
// We were passed a destinationId that doesn't exist on our back stack.
// Better to ignore the popBackStack than accidentally popping the entire stack
val destinationName = NavDestination.getDisplayName(
context, destinationId
)
Log.i(
TAG,
"Ignoring popBackStack to destination $destinationName as it was not found " +
"on the current back stack"
)
return false
}
var popped = false
val savedState = ArrayDeque<NavBackStackEntryState>()
for (navigator in popOperations) {
var receivedPop = false
navigator.popBackStackInternal(backQueue.last(), saveState) { entry ->
receivedPop = true
popped = true
popEntryFromBackStack(entry, saveState, savedState)
}
if (!receivedPop) {
// The pop did not complete successfully, so stop immediately
break
}
}
if (saveState) {
if (!inclusive) {
// If this isn't an inclusive pop, we need to explicitly map the
// saved state to the destination you've actually passed to popUpTo
// as well as its parents (if it is the start destination)
generateSequence(foundDestination) { destination ->
if (destination.parent?.startDestinationId == destination.id) {
destination.parent
} else {
null
}
}.takeWhile { destination ->
// Only add the state if it doesn't already exist
!backStackMap.containsKey(destination.id)
}.forEach { destination ->
backStackMap[destination.id] = savedState.firstOrNull()?.id
}
}
if (savedState.isNotEmpty()) {
val firstState = savedState.first()
// Whether is is inclusive or not, we need to map the
// saved state to the destination that was popped
// as well as its parents (if it is the start destination)
val firstStateDestination = findDestination(firstState.destinationId)
generateSequence(firstStateDestination) { destination ->
if (destination.parent?.startDestinationId == destination.id) {
destination.parent
} else {
null
}
}.takeWhile { destination ->
// Only add the state if it doesn't already exist
!backStackMap.containsKey(destination.id)
}.forEach { destination ->
backStackMap[destination.id] = firstState.id
}
// And finally, store the actual state itself
backStackStates[firstState.id] = savedState
}
}
updateOnBackPressedCallbackEnabled()
return popped
}
private fun popEntryFromBackStack(
popUpTo: NavBackStackEntry,
saveState: Boolean,
savedState: ArrayDeque<NavBackStackEntryState>
) {
val entry = backQueue.last()
check(entry == popUpTo) {
"Attempted to pop ${popUpTo.destination}, which is not the top of the back stack " +
"(${entry.destination})"
}
backQueue.removeLast()
if (entry.lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
if (saveState) {
// Move the state through STOPPED
entry.maxLifecycle = Lifecycle.State.CREATED
// Then save the state of the NavBackStackEntry
savedState.addFirst(NavBackStackEntryState(entry))
}
entry.maxLifecycle = Lifecycle.State.DESTROYED
}
if (!saveState) {
viewModel?.clear(entry.id)
}
}
/**
* Attempts to navigate up in the navigation hierarchy. Suitable for when the
* user presses the "Up" button marked with a left (or start)-facing arrow in the upper left
* (or starting) corner of the app UI.
*
* The intended behavior of Up differs from [Back][popBackStack] when the user
* did not reach the current destination from the application's own task. e.g. if the user
* is viewing a document or link in the current app in an activity hosted on another app's
* task where the user clicked the link. In this case the current activity (determined by the
* context used to create this NavController) will be [finished][Activity.finish] and
* the user will be taken to an appropriate destination in this app on its own task.
*
* @return true if navigation was successful, false otherwise
*/
@MainThread
public open fun navigateUp(): Boolean {
return if (destinationCountOnBackStack == 1) {
// If there's only one entry, then we've deep linked into a specific destination
// on another task so we need to find the parent and start our task from there
val currentDestination = currentDestination
var destId = currentDestination!!.id
var parent = currentDestination.parent
while (parent != null) {
if (parent.startDestinationId != destId) {
val args = Bundle()
if (activity != null && activity!!.intent != null) {
val data = activity!!.intent.data
// We were started via a URI intent.
if (data != null) {
// Include the original deep link Intent so the Destinations can
// synthetically generate additional arguments as necessary.
args.putParcelable(
KEY_DEEP_LINK_INTENT,
activity!!.intent
)
val matchingDeepLink = _graph!!.matchDeepLink(
NavDeepLinkRequest(activity!!.intent)
)
if (matchingDeepLink != null) {
val destinationArgs = matchingDeepLink.destination.addInDefaultArgs(
matchingDeepLink.matchingArgs
)
args.putAll(destinationArgs)
}
}
}
val parentIntents = NavDeepLinkBuilder(this)
.setDestination(parent.id)
.setArguments(args)
.createTaskStackBuilder()
parentIntents.startActivities()
activity?.finish()
return true
}
destId = parent.id
parent = parent.parent
}
// We're already at the startDestination of the graph so there's no 'Up' to go to
false
} else {
popBackStack()
}
}
/**
* Gets the number of non-NavGraph destinations on the back stack
*/
private val destinationCountOnBackStack: Int
get() = backQueue.count { entry ->
entry.destination !is NavGraph
}
/**
* Dispatch changes to all OnDestinationChangedListeners.
*
* If the back stack is empty, no events get dispatched.
*
* @return If changes were dispatched.
*/
private fun dispatchOnDestinationChanged(): Boolean {
// We never want to leave NavGraphs on the top of the stack
while (!backQueue.isEmpty() &&
backQueue.last().destination is NavGraph &&
popBackStackInternal(backQueue.last().destination.id, true)
) {
// Keep popping
}
if (!backQueue.isEmpty()) {
// First determine what the current resumed destination is and, if and only if
// the current resumed destination is a FloatingWindow, what destination is
// underneath it that must remain started.
var nextResumed: NavDestination? = backQueue.last().destination
var nextStarted: NavDestination? = null
if (nextResumed is FloatingWindow) {
// Find the next destination in the back stack as that destination
// should still be STARTED when the FloatingWindow destination is above it.
val iterator = backQueue.reversed().iterator()
while (iterator.hasNext()) {
val destination = iterator.next().destination
if (destination !is NavGraph && destination !is FloatingWindow) {
nextStarted = destination
break
}
}
}
// First iterate downward through the stack, applying downward Lifecycle
// transitions and capturing any upward Lifecycle transitions to apply afterwards.
// This ensures proper nesting where parent navigation graphs are started before
// their children and stopped only after their children are stopped.
val upwardStateTransitions = HashMap<NavBackStackEntry, Lifecycle.State>()
var iterator = backQueue.reversed().iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
val currentMaxLifecycle = entry.maxLifecycle
val destination = entry.destination
if (nextResumed != null && destination.id == nextResumed.id) {
// Upward Lifecycle transitions need to be done afterwards so that
// the parent navigation graph is resumed before their children
if (currentMaxLifecycle != Lifecycle.State.RESUMED) {
upwardStateTransitions[entry] = Lifecycle.State.RESUMED
}
nextResumed = nextResumed.parent
} else if (nextStarted != null && destination.id == nextStarted.id) {
if (currentMaxLifecycle == Lifecycle.State.RESUMED) {
// Downward transitions should be done immediately so children are
// paused before their parent navigation graphs
entry.maxLifecycle = Lifecycle.State.STARTED
} else if (currentMaxLifecycle != Lifecycle.State.STARTED) {
// Upward Lifecycle transitions need to be done afterwards so that
// the parent navigation graph is started before their children
upwardStateTransitions[entry] = Lifecycle.State.STARTED
}
nextStarted = nextStarted.parent
} else {
entry.maxLifecycle = Lifecycle.State.CREATED
}
}
// Apply all upward Lifecycle transitions by iterating through the stack again,
// this time applying the new lifecycle to the parent navigation graphs first
iterator = backQueue.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
val newState = upwardStateTransitions[entry]
if (newState != null) {
entry.maxLifecycle = newState
} else {
// Ensure the state is up to date
entry.updateState()
}
}
// Now call all registered OnDestinationChangedListener instances
val backStackEntry = backQueue.last()
for (listener in onDestinationChangedListeners) {
listener.onDestinationChanged(
this,
backStackEntry.destination,
backStackEntry.arguments
)
}
_currentBackStackEntryFlow.tryEmit(backStackEntry)
return true
}
return false
}
/**
* The [inflater][NavInflater] for this controller.
*
* @return inflater for loading navigation resources
*/
public open val navInflater: NavInflater by lazy {
inflater ?: NavInflater(context, _navigatorProvider)
}
/**
* Sets the [navigation graph][NavGraph] to the specified resource.
* Any current navigation graph data (including back stack) will be replaced.
*
* The inflated graph can be retrieved via [graph].
*
* @param graphResId resource id of the navigation graph to inflate
*
* @see NavController.navInflater
* @see NavController.setGraph
* @see NavController.graph
*/
@MainThread
@CallSuper
public open fun setGraph(@NavigationRes graphResId: Int) {
setGraph(navInflater.inflate(graphResId), null)
}
/**
* Sets the [navigation graph][NavGraph] to the specified resource.
* Any current navigation graph data (including back stack) will be replaced.
*
* The inflated graph can be retrieved via [graph].
*
* @param graphResId resource id of the navigation graph to inflate
* @param startDestinationArgs arguments to send to the start destination of the graph
*
* @see NavController.navInflater
* @see NavController.setGraph
* @see NavController.graph
*/
@MainThread
@CallSuper
public open fun setGraph(@NavigationRes graphResId: Int, startDestinationArgs: Bundle?) {
setGraph(navInflater.inflate(graphResId), startDestinationArgs)
}
/**
* Sets the [navigation graph][NavGraph] to the specified graph.
* Any current navigation graph data (including back stack) will be replaced.
*
* The graph can be retrieved later via [graph].
*
* @param graph graph to set
* @see NavController.setGraph
* @see NavController.graph
*/
@MainThread
@CallSuper
public open fun setGraph(graph: NavGraph, startDestinationArgs: Bundle?) {
_graph?.let { previousGraph ->
// Pop everything from the old graph off the back stack
popBackStackInternal(previousGraph.id, true)
}
_graph = graph
onGraphCreated(startDestinationArgs)
}
@MainThread
private fun onGraphCreated(startDestinationArgs: Bundle?) {
navigatorStateToRestore?.let { navigatorStateToRestore ->
val navigatorNames = navigatorStateToRestore.getStringArrayList(
KEY_NAVIGATOR_STATE_NAMES
)
if (navigatorNames != null) {
for (name in navigatorNames) {
val navigator = _navigatorProvider.getNavigator<Navigator<*>>(name)
val navigatorBackStack = navigatorState.getOrPut(navigator) {
NavControllerNavigatorState(navigator)
}
navigator.onAttach(navigatorBackStack)
val bundle = navigatorStateToRestore.getBundle(name)
if (bundle != null) {
navigator.onRestoreState(bundle)
}
}
}
}
// Mark all other Navigators as attached
_navigatorProvider.navigators.values.filterNot { it.isAttached }.forEach { navigator ->
val navigatorBackStack = navigatorState.getOrPut(navigator) {
NavControllerNavigatorState(navigator)
}
navigator.onAttach(navigatorBackStack)
}
backStackToRestore?.let { backStackToRestore ->
for (parcelable in backStackToRestore) {
val state = parcelable as NavBackStackEntryState
val node = findDestination(state.destinationId)
if (node == null) {
val dest = NavDestination.getDisplayName(
context,
state.destinationId
)
throw IllegalStateException(
"Restoring the Navigation back stack failed: destination $dest cannot be " +
"found from the current destination $currentDestination"
)
}
val entry = state.instantiate(context, node, lifecycleOwner, viewModel)
val navigator = _navigatorProvider.getNavigator<Navigator<*>>(node.navigatorName)
val navigatorBackStack = checkNotNull(navigatorState[navigator]) {
"NavigatorBackStack for ${node.navigatorName} should already be created"
}
backQueue.add(entry)
navigatorBackStack.addInternal(entry)
}
updateOnBackPressedCallbackEnabled()
this.backStackToRestore = null
}
if (_graph != null && backQueue.isEmpty()) {
val deepLinked =
!deepLinkHandled && activity != null && handleDeepLink(activity!!.intent)
if (!deepLinked) {
// Navigate to the first destination in the graph
// if we haven't deep linked to a destination
navigate(_graph!!, startDestinationArgs, null, null)
}
} else {
dispatchOnDestinationChanged()
}
}
/**
* Checks the given Intent for a Navigation deep link and navigates to the deep link if present.
* This is called automatically for you the first time you set the graph if you've passed in an
* [Activity] as the context when constructing this NavController, but should be manually
* called if your Activity receives new Intents in [Activity.onNewIntent].
*
* The types of Intents that are supported include:
*
* Intents created by [NavDeepLinkBuilder] or
* [createDeepLink]. This assumes that the current graph shares
* the same hierarchy to get to the deep linked destination as when the deep link was
* constructed.
* Intents that include a [data Uri][Intent.getData]. This Uri will be checked
* against the Uri patterns in the [NavDeepLinks][NavDeepLink] added via
* [NavDestination.addDeepLink].
*
* The [navigation graph][graph] should be set before calling this method.
* @param intent The Intent that may contain a valid deep link
* @return True if the navigation controller found a valid deep link and navigated to it.
* @throws IllegalStateException if deep link cannot be accessed from the current destination
* @see NavDestination.addDeepLink
*/
@MainThread
public open fun handleDeepLink(intent: Intent?): Boolean {
if (intent == null) {
return false
}
val extras = intent.extras
var deepLink = extras?.getIntArray(KEY_DEEP_LINK_IDS)
var deepLinkArgs = extras?.getParcelableArrayList<Bundle>(KEY_DEEP_LINK_ARGS)
val globalArgs = Bundle()
val deepLinkExtras = extras?.getBundle(KEY_DEEP_LINK_EXTRAS)
if (deepLinkExtras != null) {
globalArgs.putAll(deepLinkExtras)
}
if ((deepLink == null || deepLink.isEmpty()) && intent.data != null) {
val matchingDeepLink = _graph!!.matchDeepLink(NavDeepLinkRequest(intent))
if (matchingDeepLink != null) {
val destination = matchingDeepLink.destination
deepLink = destination.buildDeepLinkIds()
deepLinkArgs = null
val destinationArgs = destination.addInDefaultArgs(matchingDeepLink.matchingArgs)
globalArgs.putAll(destinationArgs)
}
}
if (deepLink == null || deepLink.isEmpty()) {
return false
}
val invalidDestinationDisplayName = findInvalidDestinationDisplayNameInDeepLink(deepLink)
if (invalidDestinationDisplayName != null) {
Log.i(
TAG,
"Could not find destination $invalidDestinationDisplayName in the " +
"navigation graph, ignoring the deep link from $intent"
)
return false
}
globalArgs.putParcelable(KEY_DEEP_LINK_INTENT, intent)
val args = arrayOfNulls<Bundle>(deepLink.size)
for (index in args.indices) {
val arguments = Bundle()
arguments.putAll(globalArgs)
if (deepLinkArgs != null) {
val deepLinkArguments = deepLinkArgs[index]
if (deepLinkArguments != null) {
arguments.putAll(deepLinkArguments)
}
}
args[index] = arguments
}
val flags = intent.flags
if (flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0 &&
flags and Intent.FLAG_ACTIVITY_CLEAR_TASK == 0
) {
// Someone called us with NEW_TASK, but we don't know what state our whole
// task stack is in, so we need to manually restart the whole stack to
// ensure we're in a predictably good state.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
val taskStackBuilder = TaskStackBuilder
.create(context)
.addNextIntentWithParentStack(intent)
taskStackBuilder.startActivities()
activity?.let { activity ->
activity.finish()
// Disable second animation in case where the Activity is created twice.
activity.overridePendingTransition(0, 0)
}
return true
}
if (flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0) {
// Start with a cleared task starting at our root when we're on our own task
if (!backQueue.isEmpty()) {
popBackStackInternal(_graph!!.id, true)
}
var index = 0
while (index < deepLink.size) {
val destinationId = deepLink[index]
val arguments = args[index++]
val node = findDestination(destinationId)
if (node == null) {
val dest = NavDestination.getDisplayName(
context, destinationId
)
throw IllegalStateException(
"Deep Linking failed: destination $dest cannot be found from the current " +
"destination $currentDestination"
)
}
navigate(
node, arguments,
NavOptions.Builder().setEnterAnim(0).setExitAnim(0).build(), null
)
}
return true
}
// Assume we're on another apps' task and only start the final destination
var graph = _graph
for (i in deepLink.indices) {
val destinationId = deepLink[i]
val arguments = args[i]
val node = if (i == 0) _graph else graph!!.findNode(destinationId)
if (node == null) {
val dest = NavDestination.getDisplayName(context, destinationId)
throw IllegalStateException(
"Deep Linking failed: destination $dest cannot be found in graph $graph"
)
}
if (i != deepLink.size - 1) {
// We're not at the final NavDestination yet, so keep going through the chain
if (node is NavGraph) {
graph = node
// Automatically go down the navigation graph when
// the start destination is also a NavGraph
while (graph!!.findNode(graph.startDestinationId) is NavGraph) {
graph = graph.findNode(graph.startDestinationId) as NavGraph?
}
}
} else {
// Navigate to the last NavDestination, clearing any existing destinations
navigate(
node,
arguments,
NavOptions.Builder()
.setPopUpTo(_graph!!.id, true)
.setEnterAnim(0)
.setExitAnim(0)
.build(),
null
)
}
}
deepLinkHandled = true
return true
}
/**
* Looks through the deep link for invalid destinations, returning the display name of
* any invalid destinations in the deep link array.
*
* @param deepLink array of deep link IDs that are expected to match the graph
* @return The display name of the first destination not found in the graph or null if
* all destinations were found in the graph.
*/
private fun findInvalidDestinationDisplayNameInDeepLink(deepLink: IntArray): String? {
var graph = _graph
for (i in deepLink.indices) {
val destinationId = deepLink[i]
val node =
(
if (i == 0)
if (_graph!!.id == destinationId) _graph
else null
else
graph!!.findNode(destinationId)
) ?: return NavDestination.getDisplayName(context, destinationId)
if (i != deepLink.size - 1) {
// We're not at the final NavDestination yet, so keep going through the chain
if (node is NavGraph) {
graph = node
// Automatically go down the navigation graph when
// the start destination is also a NavGraph
while (graph!!.findNode(graph.startDestinationId) is NavGraph) {
graph = graph.findNode(graph.startDestinationId) as NavGraph?
}
}
}
}
// We found every destination in the deepLink array, yay!
return null
}
/**
* The current destination.
*/
public open val currentDestination: NavDestination?
get() {
return currentBackStackEntry?.destination
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun findDestination(@IdRes destinationId: Int): NavDestination? {
if (_graph == null) {
return null
}
if (_graph!!.id == destinationId) {
return _graph
}
val currentNode = backQueue.lastOrNull()?.destination ?: _graph!!
return currentNode.findDestination(destinationId)
}
private fun NavDestination.findDestination(@IdRes destinationId: Int): NavDestination? {
if (id == destinationId) {
return this
}
val currentGraph = if (this is NavGraph) this else parent!!
return currentGraph.findNode(destinationId)
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun findDestination(destinationRoute: String): NavDestination? {
if (_graph == null) {
return null
}
if (_graph!!.route == destinationRoute) {
return _graph
}
val currentNode = backQueue.lastOrNull()?.destination ?: _graph!!
val currentGraph = if (currentNode is NavGraph) currentNode else currentNode.parent!!
return currentGraph.findNode(destinationRoute)
}
/**
* Navigate to a destination from the current navigation graph. This supports both navigating
* via an [action][NavDestination.getAction] and directly navigating to a destination.
*
* @param resId an [action][NavDestination.getAction] id or a destination id to
* navigate to
*
* @throws IllegalStateException if there is no current navigation node
* @throws IllegalArgumentException if the desired destination cannot be found from the
* current destination
*/
@MainThread
public open fun navigate(@IdRes resId: Int) {
navigate(resId, null)
}
/**
* Navigate to a destination from the current navigation graph. This supports both navigating
* via an [action][NavDestination.getAction] and directly navigating to a destination.
*
* @param resId an [action][NavDestination.getAction] id or a destination id to
* navigate to
* @param args arguments to pass to the destination
*
* @throws IllegalStateException if there is no current navigation node
* @throws IllegalArgumentException if the desired destination cannot be found from the
* current destination
*/
@MainThread
public open fun navigate(@IdRes resId: Int, args: Bundle?) {
navigate(resId, args, null)
}
/**
* Navigate to a destination from the current navigation graph. This supports both navigating
* via an [action][NavDestination.getAction] and directly navigating to a destination.
*
* @param resId an [action][NavDestination.getAction] id or a destination id to
* navigate to
* @param args arguments to pass to the destination
* @param navOptions special options for this navigation operation
*
* @throws IllegalStateException if there is no current navigation node
* @throws IllegalArgumentException if the desired destination cannot be found from the
* current destination
*/
@MainThread
public open fun navigate(@IdRes resId: Int, args: Bundle?, navOptions: NavOptions?) {
navigate(resId, args, navOptions, null)
}
/**
* Navigate to a destination from the current navigation graph. This supports both navigating
* via an [action][NavDestination.getAction] and directly navigating to a destination.
*
* @param resId an [action][NavDestination.getAction] id or a destination id to
* navigate to
* @param args arguments to pass to the destination
* @param navOptions special options for this navigation operation
* @param navigatorExtras extras to pass to the Navigator
*
* @throws IllegalStateException if there is no current navigation node
* @throws IllegalArgumentException if the desired destination cannot be found from the
* current destination
*/
@MainThread
public open fun navigate(
@IdRes resId: Int,
args: Bundle?,
navOptions: NavOptions?,
navigatorExtras: Navigator.Extras?
) {
var finalNavOptions = navOptions
val currentNode = (
if (backQueue.isEmpty())
_graph
else
backQueue.last().destination
) ?: throw IllegalStateException("no current navigation node")
@IdRes
var destId = resId
val navAction = currentNode.getAction(resId)
var combinedArgs: Bundle? = null
if (navAction != null) {
if (finalNavOptions == null) {
finalNavOptions = navAction.navOptions
}
destId = navAction.destinationId
val navActionArgs = navAction.defaultArguments
if (navActionArgs != null) {
combinedArgs = Bundle()
combinedArgs.putAll(navActionArgs)
}
}
if (args != null) {
if (combinedArgs == null) {
combinedArgs = Bundle()
}
combinedArgs.putAll(args)
}
if (destId == 0 && finalNavOptions != null && finalNavOptions.popUpToId != -1) {
popBackStack(finalNavOptions.popUpToId, finalNavOptions.isPopUpToInclusive())
return
}
require(destId != 0) {
"Destination id == 0 can only be used in conjunction with a valid navOptions.popUpTo"
}
val node = findDestination(destId)
if (node == null) {
val dest = NavDestination.getDisplayName(context, destId)
require(navAction == null) {
"Navigation destination $dest referenced from action " +
"${NavDestination.getDisplayName(context, resId)} cannot be found from " +
"the current destination $currentNode"
}
throw IllegalArgumentException(
"Navigation action/destination $dest cannot be found from the current " +
"destination $currentNode"
)
}
navigate(node, combinedArgs, finalNavOptions, navigatorExtras)
}
/**
* Navigate to a destination via the given deep link [Uri].
* [NavDestination.hasDeepLink] should be called on
* [the navigation graph][graph] prior to calling this method to check if the deep
* link is valid. If an invalid deep link is given, an [IllegalArgumentException] will be
* thrown.
*
* @param deepLink deepLink to the destination reachable from the current NavGraph
* @see NavController.navigate
*/
@MainThread
public open fun navigate(deepLink: Uri) {
navigate(NavDeepLinkRequest(deepLink, null, null))
}
/**
* Navigate to a destination via the given deep link [Uri].
* [NavDestination.hasDeepLink] should be called on
* [the navigation graph][graph] prior to calling this method to check if the deep
* link is valid. If an invalid deep link is given, an [IllegalArgumentException] will be
* thrown.
*
* @param deepLink deepLink to the destination reachable from the current NavGraph
* @param navOptions special options for this navigation operation
* @see NavController.navigate
*/
@MainThread
public open fun navigate(deepLink: Uri, navOptions: NavOptions?) {
navigate(NavDeepLinkRequest(deepLink, null, null), navOptions, null)
}
/**
* Navigate to a destination via the given deep link [Uri].
* [NavDestination.hasDeepLink] should be called on
* [the navigation graph][graph] prior to calling this method to check if the deep
* link is valid. If an invalid deep link is given, an [IllegalArgumentException] will be
* thrown.
*
* @param deepLink deepLink to the destination reachable from the current NavGraph
* @param navOptions special options for this navigation operation
* @param navigatorExtras extras to pass to the Navigator
* @see NavController.navigate
*/
@MainThread
public open fun navigate(
deepLink: Uri,
navOptions: NavOptions?,
navigatorExtras: Navigator.Extras?
) {
navigate(NavDeepLinkRequest(deepLink, null, null), navOptions, navigatorExtras)
}
/**
* Navigate to a destination via the given [NavDeepLinkRequest].
* [NavDestination.hasDeepLink] should be called on
* [the navigation graph][graph] prior to calling this method to check if the deep
* link is valid. If an invalid deep link is given, an [IllegalArgumentException] will be
* thrown.
*
* @param request deepLinkRequest to the destination reachable from the current NavGraph
*
* @throws IllegalArgumentException if the given deep link request is invalid
*/
@MainThread
public open fun navigate(request: NavDeepLinkRequest) {
navigate(request, null)
}
/**
* Navigate to a destination via the given [NavDeepLinkRequest].
* [NavDestination.hasDeepLink] should be called on
* [the navigation graph][graph] prior to calling this method to check if the deep
* link is valid. If an invalid deep link is given, an [IllegalArgumentException] will be
* thrown.
*
* @param request deepLinkRequest to the destination reachable from the current NavGraph
* @param navOptions special options for this navigation operation
*
* @throws IllegalArgumentException if the given deep link request is invalid
*/
@MainThread
public open fun navigate(request: NavDeepLinkRequest, navOptions: NavOptions?) {
navigate(request, navOptions, null)
}
/**
* Navigate to a destination via the given [NavDeepLinkRequest].
* [NavDestination.hasDeepLink] should be called on
* [the navigation graph][graph] prior to calling this method to check if the deep
* link is valid. If an invalid deep link is given, an [IllegalArgumentException] will be
* thrown.
*
* @param request deepLinkRequest to the destination reachable from the current NavGraph
* @param navOptions special options for this navigation operation
* @param navigatorExtras extras to pass to the Navigator
*
* @throws IllegalArgumentException if the given deep link request is invalid
*/
@MainThread
public open fun navigate(
request: NavDeepLinkRequest,
navOptions: NavOptions?,
navigatorExtras: Navigator.Extras?
) {
val deepLinkMatch = _graph!!.matchDeepLink(request)
if (deepLinkMatch != null) {
val destination = deepLinkMatch.destination
val args = destination.addInDefaultArgs(deepLinkMatch.matchingArgs) ?: Bundle()
val node = deepLinkMatch.destination
val intent = Intent().apply {
setDataAndType(request.uri, request.mimeType)
action = request.action
}
args.putParcelable(KEY_DEEP_LINK_INTENT, intent)
navigate(node, args, navOptions, navigatorExtras)
} else {
throw IllegalArgumentException(
"Navigation destination that matches request $request cannot be found in the " +
"navigation graph $_graph"
)
}
}
@MainThread
private fun navigate(
node: NavDestination,
args: Bundle?,
navOptions: NavOptions?,
navigatorExtras: Navigator.Extras?
) {
var popped = false
var launchSingleTop = false
var navigated = false
if (navOptions != null) {
if (navOptions.popUpToId != -1) {
popped = popBackStackInternal(
navOptions.popUpToId,
navOptions.isPopUpToInclusive(),
navOptions.shouldPopUpToSaveState()
)
}
}
val finalArgs = node.addInDefaultArgs(args)
val currentBackStackEntry = currentBackStackEntry
if (navOptions?.shouldLaunchSingleTop() == true &&
node.id == currentBackStackEntry?.destination?.id
) {
// Single top operations don't change the back stack, they just update arguments
launchSingleTop = true
currentBackStackEntry.replaceArguments(finalArgs)
val navigator = _navigatorProvider.getNavigator<Navigator<NavDestination>>(
node.navigatorName
)
navigator.onLaunchSingleTop(currentBackStackEntry)
}
// Now determine what new destinations we need to add to the back stack
if (navOptions?.shouldRestoreState() == true && backStackMap.containsKey(node.id)) {
val backStackId = backStackMap[node.id]
// Clear out the state we're going to restore so that it isn't restored a second time
backStackMap.values.removeAll { it == backStackId }
val backStackState = backStackStates.remove(backStackId)
// Now restore the back stack from its saved state
val entries = instantiateBackStack(backStackState)
// Split up the entries by Navigator so we can restore them as an atomic operation
val entriesGroupedByNavigator = mutableListOf<MutableList<NavBackStackEntry>>()
entries.filterNot { entry ->
// Skip navigation graphs - they'll be added by addEntryToBackStack()
entry.destination is NavGraph
}.forEach { entry ->
val previousEntryList = entriesGroupedByNavigator.lastOrNull()
val previousNavigatorName = previousEntryList?.last()?.destination?.navigatorName
if (previousNavigatorName == entry.destination.navigatorName) {
// Group back to back entries associated with the same Navigator together
previousEntryList += entry
} else {
// Create a new group for the new Navigator
entriesGroupedByNavigator += mutableListOf(entry)
}
}
// Now actually navigate to each set of entries
for (entryList in entriesGroupedByNavigator) {
val navigator = _navigatorProvider.getNavigator<Navigator<NavDestination>>(
entryList.first().destination.navigatorName
)
var lastNavigatedIndex = 0
var lastDestination = node
navigator.navigateInternal(entryList, navOptions, navigatorExtras) { entry ->
navigated = true
// If this destination is part of the restored back stack,
// pass all destinations between the last navigated entry and this one
// to ensure that any navigation graphs are properly restored as well
val entryIndex = entries.indexOf(entry)
val restoredEntries = if (entryIndex != -1) {
entries.subList(lastNavigatedIndex, entryIndex + 1).also {
lastNavigatedIndex = entryIndex + 1
lastDestination = entry.destination
}
} else {
emptyList()
}
addEntryToBackStack(lastDestination, finalArgs, entry, restoredEntries)
}
}
} else if (!launchSingleTop) {
// Not a single top operation, so we're looking to add the node to the back stack
val backStackEntry = NavBackStackEntry.create(
context, node, finalArgs, lifecycleOwner, viewModel
)
val navigator = _navigatorProvider.getNavigator<Navigator<NavDestination>>(
node.navigatorName
)
navigator.navigateInternal(listOf(backStackEntry), navOptions, navigatorExtras) {
navigated = true
addEntryToBackStack(node, finalArgs, it)
}
}
updateOnBackPressedCallbackEnabled()
if (popped || navigated || launchSingleTop) {
dispatchOnDestinationChanged()
}
}
private fun instantiateBackStack(
backStackState: ArrayDeque<NavBackStackEntryState>?
): List<NavBackStackEntry> {
val backStack = mutableListOf<NavBackStackEntry>()
var currentDestination = backQueue.lastOrNull()?.destination ?: graph
backStackState?.forEach { state ->
val node = currentDestination.findDestination(state.destinationId)
checkNotNull(node) {
val dest = NavDestination.getDisplayName(
context, state.destinationId
)
"Restore State failed: destination $dest cannot be found from the current " +
"destination $currentDestination"
}
backStack += state.instantiate(context, node, lifecycleOwner, viewModel)
currentDestination = node
}
return backStack
}
private fun addEntryToBackStack(
node: NavDestination,
finalArgs: Bundle?,
backStackEntry: NavBackStackEntry,
restoredEntries: List<NavBackStackEntry> = emptyList()
) {
val newDest = backStackEntry.destination
if (newDest !is FloatingWindow) {
// We've successfully navigating to the new destination, which means
// we should pop any FloatingWindow destination off the back stack
// before updating the back stack with our new destination
while (!backQueue.isEmpty() &&
backQueue.last().destination is FloatingWindow &&
popBackStackInternal(backQueue.last().destination.id, true)
) {
// Keep popping
}
}
// When you navigate() to a NavGraph, we need to ensure that a new instance
// is always created vs reusing an existing copy of that destination
val hierarchy = ArrayDeque<NavBackStackEntry>()
var destination: NavDestination? = newDest
if (node is NavGraph) {
do {
val parent = destination!!.parent
if (parent != null) {
val entry = restoredEntries.lastOrNull { restoredEntry ->
restoredEntry.destination == parent
} ?: NavBackStackEntry.create(
context, parent,
finalArgs, lifecycleOwner, viewModel
)
hierarchy.addFirst(entry)
// Pop any orphaned copy of that navigation graph off the back stack
if (backQueue.isNotEmpty() && backQueue.last().destination === parent) {
popBackStackInternal(parent.id, true)
}
}
destination = parent
} while (destination != null && destination !== node)
}
// Now collect the set of all intermediate NavGraphs that need to be put onto
// the back stack
destination = if (hierarchy.isEmpty()) newDest else hierarchy.first().destination
while (destination != null && findDestination(destination.id) == null) {
val parent = destination.parent
if (parent != null) {
val entry = restoredEntries.lastOrNull { restoredEntry ->
restoredEntry.destination == parent
} ?: NavBackStackEntry.create(
context, parent, parent.addInDefaultArgs(finalArgs), lifecycleOwner, viewModel
)
hierarchy.addFirst(entry)
}
destination = parent
}
val overlappingDestination: NavDestination =
if (hierarchy.isEmpty())
newDest
else
hierarchy.last().destination
// Pop any orphaned navigation graphs that don't connect to the new destinations
while (!backQueue.isEmpty() && backQueue.last().destination is NavGraph &&
(backQueue.last().destination as NavGraph).findNode(
overlappingDestination.id, false
) == null && popBackStackInternal(backQueue.last().destination.id, true)
) {
// Keep popping
}
// Now add the parent hierarchy to the NavigatorStates and back stack
hierarchy.forEach { entry ->
val navigator = _navigatorProvider.getNavigator<Navigator<*>>(
entry.destination.navigatorName
)
val navigatorBackStack = checkNotNull(navigatorState[navigator]) {
"NavigatorBackStack for ${node.navigatorName} should already be created"
}
navigatorBackStack.addInternal(entry)
}
backQueue.addAll(hierarchy)
// The _graph should always be on the back stack after you navigate()
if (backQueue.isEmpty() || backQueue.first().destination !== _graph) {
val entry = restoredEntries.lastOrNull { restoredEntry ->
restoredEntry.destination == _graph!!
} ?: NavBackStackEntry.create(
context, _graph!!, _graph!!.addInDefaultArgs(finalArgs), lifecycleOwner, viewModel
)
val navigator = _navigatorProvider.getNavigator<Navigator<*>>(
entry.destination.navigatorName
)
val navigatorBackStack = checkNotNull(navigatorState[navigator]) {
"NavigatorBackStack for ${node.navigatorName} should already be created"
}
navigatorBackStack.addInternal(entry)
backQueue.addFirst(entry)
}
// And finally, add the new destination
backQueue.add(backStackEntry)
}
/**
* Navigate via the given [NavDirections]
*
* @param directions directions that describe this navigation operation
*/
@MainThread
public open fun navigate(directions: NavDirections) {
navigate(directions.actionId, directions.arguments, null)
}
/**
* Navigate via the given [NavDirections]
*
* @param directions directions that describe this navigation operation
* @param navOptions special options for this navigation operation
*/
@MainThread
public open fun navigate(directions: NavDirections, navOptions: NavOptions?) {
navigate(directions.actionId, directions.arguments, navOptions)
}
/**
* Navigate via the given [NavDirections]
*
* @param directions directions that describe this navigation operation
* @param navigatorExtras extras to pass to the [Navigator]
*/
@MainThread
public open fun navigate(directions: NavDirections, navigatorExtras: Navigator.Extras) {
navigate(directions.actionId, directions.arguments, null, navigatorExtras)
}
/**
* Navigate to a route in the current NavGraph. If an invalid route is given, an
* [IllegalArgumentException] will be thrown.
*
* @param route route for the destination
* @param builder DSL for constructing a new [NavOptions]
*
* @throws IllegalArgumentException if the given route is invalid
*/
public fun navigate(route: String, builder: NavOptionsBuilder.() -> Unit) {
navigate(route, navOptions(builder))
}
/**
* Navigate to a route in the current NavGraph. If an invalid route is given, an
* [IllegalArgumentException] will be thrown.
*
* @param route route for the destination
* @param navOptions special options for this navigation operation
* @param navigatorExtras extras to pass to the [Navigator]
*
* @throws IllegalArgumentException if the given route is invalid
*/
@JvmOverloads
public fun navigate(
route: String,
navOptions: NavOptions? = null,
navigatorExtras: Navigator.Extras? = null
) {
navigate(
NavDeepLinkRequest.Builder.fromUri(createRoute(route).toUri()).build(), navOptions,
navigatorExtras
)
}
/**
* Create a deep link to a destination within this NavController.
*
* @return a [NavDeepLinkBuilder] suitable for constructing a deep link
*/
public open fun createDeepLink(): NavDeepLinkBuilder {
return NavDeepLinkBuilder(this)
}
/**
* Saves all navigation controller state to a Bundle.
*
* State may be restored from a bundle returned from this method by calling
* [restoreState]. Saving controller state is the responsibility
* of a [NavHost].
*
* @return saved state for this controller
*/
@CallSuper
public open fun saveState(): Bundle? {
var b: Bundle? = null
val navigatorNames = ArrayList<String>()
val navigatorState = Bundle()
for ((name, value) in _navigatorProvider.navigators) {
val savedState = value.onSaveState()
if (savedState != null) {
navigatorNames.add(name)
navigatorState.putBundle(name, savedState)
}
}
if (navigatorNames.isNotEmpty()) {
b = Bundle()
navigatorState.putStringArrayList(KEY_NAVIGATOR_STATE_NAMES, navigatorNames)
b.putBundle(KEY_NAVIGATOR_STATE, navigatorState)
}
if (backQueue.isNotEmpty()) {
if (b == null) {
b = Bundle()
}
val backStack = arrayOfNulls<Parcelable>(backQueue.size)
var index = 0
for (backStackEntry in this.backQueue) {
backStack[index++] = NavBackStackEntryState(backStackEntry)
}
b.putParcelableArray(KEY_BACK_STACK, backStack)
}
if (backStackMap.isNotEmpty()) {
if (b == null) {
b = Bundle()
}
val backStackDestIds = IntArray(backStackMap.size)
val backStackIds = ArrayList<String?>()
var index = 0
for ((destId, id) in backStackMap) {
backStackDestIds[index++] = destId
backStackIds += id
}
b.putIntArray(KEY_BACK_STACK_DEST_IDS, backStackDestIds)
b.putStringArrayList(KEY_BACK_STACK_IDS, backStackIds)
}
if (backStackStates.isNotEmpty()) {
if (b == null) {
b = Bundle()
}
val backStackStateIds = ArrayList<String>()
for ((id, backStackStates) in backStackStates) {
backStackStateIds += id
val states = arrayOfNulls<Parcelable>(backStackStates.size)
backStackStates.forEachIndexed { stateIndex, backStackState ->
states[stateIndex] = backStackState
}
b.putParcelableArray(KEY_BACK_STACK_STATES_PREFIX + id, states)
}
b.putStringArrayList(KEY_BACK_STACK_STATES_IDS, backStackStateIds)
}
if (deepLinkHandled) {
if (b == null) {
b = Bundle()
}
b.putBoolean(KEY_DEEP_LINK_HANDLED, deepLinkHandled)
}
return b
}
/**
* Restores all navigation controller state from a bundle. This should be called before any
* call to [setGraph].
*
* State may be saved to a bundle by calling [saveState].
* Restoring controller state is the responsibility of a [NavHost].
*
* @param navState state bundle to restore
*/
@CallSuper
public open fun restoreState(navState: Bundle?) {
if (navState == null) {
return
}
navState.classLoader = context.classLoader
navigatorStateToRestore = navState.getBundle(KEY_NAVIGATOR_STATE)
backStackToRestore = navState.getParcelableArray(KEY_BACK_STACK)
backStackStates.clear()
val backStackDestIds = navState.getIntArray(KEY_BACK_STACK_DEST_IDS)
val backStackIds = navState.getStringArrayList(KEY_BACK_STACK_IDS)
if (backStackDestIds != null && backStackIds != null) {
backStackDestIds.forEachIndexed { index, id ->
backStackMap[id] = backStackIds[index]
}
}
val backStackStateIds = navState.getStringArrayList(KEY_BACK_STACK_STATES_IDS)
backStackStateIds?.forEach { id ->
val backStackState = navState.getParcelableArray(KEY_BACK_STACK_STATES_PREFIX + id)
if (backStackState != null) {
backStackStates[id] = ArrayDeque<NavBackStackEntryState>(
backStackState.size
).apply {
for (parcelable in backStackState) {
add(parcelable as NavBackStackEntryState)
}
}
}
}
deepLinkHandled = navState.getBoolean(KEY_DEEP_LINK_HANDLED)
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open fun setLifecycleOwner(owner: LifecycleOwner) {
if (owner == lifecycleOwner) {
return
}
lifecycleOwner?.lifecycle?.removeObserver(lifecycleObserver)
lifecycleOwner = owner
owner.lifecycle.addObserver(lifecycleObserver)
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open fun setOnBackPressedDispatcher(dispatcher: OnBackPressedDispatcher) {
checkNotNull(lifecycleOwner) {
"You must call setLifecycleOwner() before calling setOnBackPressedDispatcher()"
}
// Remove the callback from any previous dispatcher
onBackPressedCallback.remove()
// Then add it to the new dispatcher
dispatcher.addCallback(lifecycleOwner!!, onBackPressedCallback)
// Make sure that listener for updating the NavBackStackEntry lifecycles comes after
// the dispatcher
lifecycleOwner!!.lifecycle.apply {
removeObserver(lifecycleObserver)
addObserver(lifecycleObserver)
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open fun enableOnBackPressed(enabled: Boolean) {
enableOnBackPressedCallback = enabled
updateOnBackPressedCallbackEnabled()
}
private fun updateOnBackPressedCallbackEnabled() {
onBackPressedCallback.isEnabled = (
enableOnBackPressedCallback && destinationCountOnBackStack > 1
)
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open fun setViewModelStore(viewModelStore: ViewModelStore) {
if (viewModel == NavControllerViewModel.getInstance(viewModelStore)) {
return
}
check(backQueue.isEmpty()) { "ViewModelStore should be set before setGraph call" }
viewModel = NavControllerViewModel.getInstance(viewModelStore)
}
/**
* Gets the [ViewModelStoreOwner] for a NavGraph. This can be passed to
* [androidx.lifecycle.ViewModelProvider] to retrieve a ViewModel that is scoped
* to the navigation graph - it will be cleared when the navigation graph is popped off
* the back stack.
*
* @param navGraphId ID of a NavGraph that exists on the back stack
* @throws IllegalStateException if called before the [NavHost] has called
* [NavHostController.setViewModelStore].
* @throws IllegalArgumentException if the NavGraph is not on the back stack
*/
public open fun getViewModelStoreOwner(@IdRes navGraphId: Int): ViewModelStoreOwner {
checkNotNull(viewModel) {
"You must call setViewModelStore() before calling getViewModelStoreOwner()."
}
val lastFromBackStack = getBackStackEntry(navGraphId)
require(lastFromBackStack.destination is NavGraph) {
"No NavGraph with ID $navGraphId is on the NavController's back stack"
}
return lastFromBackStack
}
/**
* Gets the topmost [NavBackStackEntry] for a destination id.
*
* This is always safe to use with [the current destination][currentDestination] or
* [its parent][NavDestination.parent] or grandparent navigation graphs as these
* destinations are guaranteed to be on the back stack.
*
* @param destinationId ID of a destination that exists on the back stack
* @throws IllegalArgumentException if the destination is not on the back stack
*/
public open fun getBackStackEntry(@IdRes destinationId: Int): NavBackStackEntry {
val lastFromBackStack: NavBackStackEntry? = backQueue.lastOrNull { entry ->
entry.destination.id == destinationId
}
requireNotNull(lastFromBackStack) {
"No destination with ID $destinationId is on the NavController's back stack. The " +
"current destination is $currentDestination"
}
return lastFromBackStack
}
/**
* Gets the topmost [NavBackStackEntry] for a route.
*
* This is always safe to use with [the current destination][currentDestination] or
* [its parent][NavDestination.parent] or grandparent navigation graphs as these
* destinations are guaranteed to be on the back stack.
*
* @param route route of a destination that exists on the back stack
* @throws IllegalArgumentException if the destination is not on the back stack
*/
public fun getBackStackEntry(route: String): NavBackStackEntry {
val lastFromBackStack: NavBackStackEntry? = backQueue.lastOrNull { entry ->
entry.destination.route == route
}
requireNotNull(lastFromBackStack) {
"No destination with route $route is on the NavController's back stack. The " +
"current destination is $currentDestination"
}
return lastFromBackStack
}
/**
* The topmost [NavBackStackEntry].
*
* @return the topmost entry on the back stack or null if the back stack is empty
*/
public open val currentBackStackEntry: NavBackStackEntry?
get() = backQueue.lastOrNull()
private val _currentBackStackEntryFlow: MutableSharedFlow<NavBackStackEntry> =
MutableSharedFlow(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
/**
* A [Flow] that will emit the currently active [NavBackStackEntry] whenever it changes. If
* there is no active [NavBackStackEntry], no item will be emitted.
*/
public val currentBackStackEntryFlow: Flow<NavBackStackEntry> =
_currentBackStackEntryFlow.asSharedFlow()
/**
* The previous visible [NavBackStackEntry].
*
* This skips over any [NavBackStackEntry] that is associated with a [NavGraph].
*
* @return the previous visible entry on the back stack or null if the back stack has less
* than two visible entries
*/
public open val previousBackStackEntry: NavBackStackEntry?
get() {
val iterator = backQueue.reversed().iterator()
// throw the topmost destination away.
if (iterator.hasNext()) {
iterator.next()
}
return iterator.asSequence().firstOrNull { entry ->
entry.destination !is NavGraph
}
}
public companion object {
private const val TAG = "NavController"
private const val KEY_NAVIGATOR_STATE = "android-support-nav:controller:navigatorState"
private const val KEY_NAVIGATOR_STATE_NAMES =
"android-support-nav:controller:navigatorState:names"
private const val KEY_BACK_STACK = "android-support-nav:controller:backStack"
private const val KEY_BACK_STACK_DEST_IDS =
"android-support-nav:controller:backStackDestIds"
private const val KEY_BACK_STACK_IDS =
"android-support-nav:controller:backStackIds"
private const val KEY_BACK_STACK_STATES_IDS =
"android-support-nav:controller:backStackStates"
private const val KEY_BACK_STACK_STATES_PREFIX =
"android-support-nav:controller:backStackStates:"
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public const val KEY_DEEP_LINK_IDS: String = "android-support-nav:controller:deepLinkIds"
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public const val KEY_DEEP_LINK_ARGS: String = "android-support-nav:controller:deepLinkArgs"
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@Suppress("IntentName")
public const val KEY_DEEP_LINK_EXTRAS: String =
"android-support-nav:controller:deepLinkExtras"
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public const val KEY_DEEP_LINK_HANDLED: String =
"android-support-nav:controller:deepLinkHandled"
/**
* The [Intent] that triggered a deep link to the current destination.
*/
public const val KEY_DEEP_LINK_INTENT: String =
"android-support-nav:controller:deepLinkIntent"
}
}
/**
* Construct a new [NavGraph]
*
* @param id the graph's unique id
* @param startDestination the route for the start destination
* @param builder the builder used to construct the graph
*/
public inline fun NavController.createGraph(
@IdRes id: Int = 0,
@IdRes startDestination: Int,
builder: NavGraphBuilder.() -> Unit
): NavGraph = navigatorProvider.navigation(id, startDestination, builder)
/**
* Construct a new [NavGraph]
*
* @param startDestination the route for the start destination
* @param route the route for the graph
* @param builder the builder used to construct the graph
*/
public fun NavController.createGraph(
startDestination: String,
route: String? = null,
builder: NavGraphBuilder.() -> Unit
): NavGraph = navigatorProvider.navigation(startDestination, route, builder)
|
#define UTS_RELEASE "2.4.6-rmk1-np2-embedix"
#define LINUX_VERSION_CODE 132102
#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
#define EMBEDIX_RELEASE "-011228"
|
package com.linecorp.kotlinjdsl.query.spec.expression
import com.linecorp.kotlinjdsl.query.spec.Froms
import com.linecorp.kotlinjdsl.query.spec.predicate.PredicateSpec
import com.linecorp.kotlinjdsl.test.WithKotlinJdslAssertions
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import javax.persistence.criteria.AbstractQuery
import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.Expression
import javax.persistence.criteria.Predicate
@ExtendWith(MockKExtension::class)
internal class CaseSpecTest : WithKotlinJdslAssertions {
@MockK
private lateinit var froms: Froms
@MockK
private lateinit var query: AbstractQuery<*>
@MockK
private lateinit var criteriaBuilder: CriteriaBuilder
@Test
fun toCriteriaExpression() {
// given
val predicateSpec1 = mockk<PredicateSpec>()
val predicateSpec2 = mockk<PredicateSpec>()
val predicate1 = mockk<Predicate>()
val predicate2 = mockk<Predicate>()
val resultSpec1 = mockk<ExpressionSpec<Int>>()
val resultSpec2 = mockk<ExpressionSpec<Int>>()
val result1 = mockk<Expression<Int>>()
val result2 = mockk<Expression<Int>>()
val when1 = CaseSpec.WhenSpec(predicateSpec1, resultSpec1)
val when2 = CaseSpec.WhenSpec(predicateSpec2, resultSpec2)
val otherwise1 = mockk<ExpressionSpec<Int?>>()
val otherwise1Expression = mockk<Expression<Int?>>()
val case = mockk<CriteriaBuilder.Case<Int>>()
val caseExpression = mockk<Expression<Int>>()
every { predicateSpec1.toCriteriaPredicate(any(), any(), any()) } returns predicate1
every { predicateSpec2.toCriteriaPredicate(any(), any(), any()) } returns predicate2
every { resultSpec1.toCriteriaExpression(any(), any(), any()) } returns result1
every { resultSpec2.toCriteriaExpression(any(), any(), any()) } returns result2
every { otherwise1.toCriteriaExpression(any(), any(), any()) } returns otherwise1Expression
every { criteriaBuilder.selectCase<Int>() } returns case
every { case.`when`(any(), any<Expression<Int>>()) } returns case
every { case.otherwise(any<Expression<Int>>()) } returns caseExpression
// when
val spec = CaseSpec(listOf(when1, when2), otherwise1)
val actual = spec.toCriteriaExpression(froms, query, criteriaBuilder)
// then
assertThat(actual).isEqualTo(caseExpression)
verify(exactly = 1) {
predicateSpec1.toCriteriaPredicate(froms, query, criteriaBuilder)
predicateSpec2.toCriteriaPredicate(froms, query, criteriaBuilder)
resultSpec1.toCriteriaExpression(froms, query, criteriaBuilder)
resultSpec2.toCriteriaExpression(froms, query, criteriaBuilder)
otherwise1.toCriteriaExpression(froms, query, criteriaBuilder)
criteriaBuilder.selectCase<Int>()
case.`when`(predicate1, result1)
case.`when`(predicate2, result2)
case.otherwise(otherwise1Expression)
}
confirmVerified(
predicateSpec1, predicateSpec2,
resultSpec1, resultSpec2,
otherwise1, case,
froms, query, criteriaBuilder
)
}
}
|
import lejos.nxt.Motor;
public class MeuPrimeiroRobo {
public static void main(String[] args) {
Motor.A.rotate(30);
}
}
|
var canvas;
var tileSize;
var m_Width, m_Height;
function setup() {
tileSize = 40;
m_Width = 8 * tileSize;
m_Height = 8 * tileSize;
canvas = new Canvas(2 * m_Width, m_Height);
textSize(18);
}
function DrawBoard() {
noStroke();
for(x = 0; x < m_Width / tileSize; x++) {
for(y = 0; y < m_Height / tileSize; y++) {
fill((x + y) % 2 ? [190 / 2.2, 180 / 2.2, 140 / 2.2] : [255 / 1.1, 248 / 1.1, 220 / 1.1]);
rect(x * tileSize, y * tileSize, tileSize, tileSize);
}
}
fill(200);
rect(m_Width, 0, m_Width * 2, m_Height);
}
function draw() {
DrawBoard();
fill(0);
text("Visualisation of the Neural Network", m_Width + 10, 10, m_Width - 10, m_Height - 10);
}
|
package br.com.leandroferreira.wizardform.pages
import android.databinding.ObservableField
import br.com.leandroferreira.wizard_forms.contract.WizardPageViewModel
import br.com.leandroferreira.wizardform.dto.User
class PageOneViewModel: WizardPageViewModel<User>() {
val name = ObservableField<String>()
fun goClick() {
stateHolder?.stateDto?.name = name.get()
stateHolder?.notifyStateChange()
navigator?.nextPage()
}
}
|
module HsCaml.TypeChecker.TypeChecker where
import Debug.Trace
import HsCaml.Common.Gensym
import HsCaml.FrontEnd.Types
import HsCaml.TypeChecker.CheckFinished
import HsCaml.TypeChecker.RenameSymsByScope
import HsCaml.TypeChecker.UFTypeChecker
typeCheck :: Expr -> Either CompileError Expr
typeCheck e = do
renameSymsByScope initialGensymState e >>= uftypeCheck >>= checkFinished
--let te' = initialTypeInfer e'
---- traceM $ show $ te'
--let constraints = collectTypeConstraints te'
---- traceM $ show $ constraints
--unified <- unify constraints
---- traceM $ show $ unified
--let typevarReplaced = setTypeConstraints unified te'
--checkTypeCheckIsFinished typevarReplaced
|
require "httparty"
require "pry"
require_relative "./nba/version"
require_relative "./nba/cli"
require_relative "./nba/api"
require_relative "./nba/team"
|
# encoding: utf-8
require 'spec_helper'
describe Processor do
describe '#call' do
context 'when the processor is no evaluator' do
it_behaves_like 'Processor::Call::Incoming#call' do
before do
expect(handler).to receive(:call).with(decomposed).and_return(handler_result)
expect(observers).to receive(:each).with(no_args).and_yield(observer)
expect(observer).to receive(:call).with(handler_result)
end
let(:klass) {
Class.new {
include Processor::Incoming
def call(request)
request.success(execute(request))
end
}
}
end
end
# needed for rspec-dm2 to cover all processor ivars
context 'when the processor is an evaluator' do
it_behaves_like 'Processor::Evaluator#call' do
let(:klass) { Processor::Evaluator::Request }
end
end
end
describe '#result' do
subject { object.result(response) }
include_context 'Request#initialize'
include_context 'Processor#initialize'
let(:klass) { Class.new { include Substation::Processor } }
let(:response) { Response::Success.new(request, input) }
it { should be(response) }
end
describe '#success?' do
subject { object.success?(response) }
include_context 'Processor#initialize'
let(:klass) { Class.new { include Substation::Processor } }
context 'with a successful response' do
let(:response) { double(:success? => true) }
it { should be(true) }
end
context 'with a failure response' do
let(:response) { double(:success? => false) }
it { should be(false) }
end
end
end
|
<?php
namespace Application\Application\Factory;
use Application\Application\Helper\ApplicationHelper;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
* アプリケーションヘルプファクトリーのクラス
*/
class ApplicationHelperFactory implements FactoryInterface
{
/**
* アプリケーションヘルプサービスの作成
* @param ServiceLocatorInterface $serviceLocator
* @return ApplicationHelper
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
return new ApplicationHelper($serviceLocator->getServiceLocator());
}
}
|
#!/bin/bash -eu
# File automatically generated. Do not edit.
usage() {
local ret=0
if [[ $# -gt 0 ]]; then
# Write to stderr on errors.
exec 1>&2
echo "ERROR: $*"
echo
ret=1
fi
echo "Usage: $0 [image] [part]"
echo "Example: $0 chromiumos_image.bin"
exit ${ret}
}
TARGET=${1:-}
PART=${2:-}
case ${TARGET} in
-h|--help)
usage
;;
"")
for TARGET in chromiumos_{,base_}image.bin ""; do
if [[ -e ${TARGET} ]]; then
echo "autodetected image: ${TARGET}"
break
fi
done
if [[ -z ${TARGET} ]]; then
usage "could not autodetect an image"
fi
;;
*)
if [[ ! -e ${TARGET} ]]; then
usage "image does not exist: ${TARGET}"
fi
esac
# start size part contents
# 0 1 PMBR (Boot GUID: 09ADDEBB-0333-4B48-8E1D-CB43C88C95DE)
# 1 1 Pri GPT header
# 2 32 Pri GPT table
# 2961408 12132352 1 Label: "STATE"
# Type: Linux data
# UUID: CC1A2390-0A9D-9D48-883B-626E7DD188CB
# 20480 32768 2 Label: "KERN-A"
# Type: ChromeOS kernel
# UUID: 71B947BB-2396-314B-8C78-2A62CBFC8024
# Attr: priority=15 tries=15 successful=0
# 319488 2641920 3 Label: "ROOT-A"
# Type: ChromeOS rootfs
# UUID: 5D3E9883-6405-B44A-9E79-E1125B5FDC9B
# 53248 32768 4 Label: "KERN-B"
# Type: ChromeOS kernel
# UUID: CC947588-A4F8-B64A-99DE-81243D71A4BE
# Attr: priority=0 tries=0 successful=0
# 315392 4096 5 Label: "ROOT-B"
# Type: ChromeOS rootfs
# UUID: 316ADC8E-FA80-194C-9C01-F562D280239F
# 16448 1 6 Label: "KERN-C"
# Type: ChromeOS kernel
# UUID: 6AD6BA67-5ED6-5C43-9DE1-238C7DA83B1A
# Attr: priority=0 tries=0 successful=0
# 16449 1 7 Label: "ROOT-C"
# Type: ChromeOS rootfs
# UUID: AA474C7E-3368-8047-9CC4-C6459C867D53
# 86016 32768 8 Label: "OEM"
# Type: Linux data
# UUID: 2B5DF82C-C3D0-4443-A90A-D2A3671D5C0E
# 16450 1 9 Label: "reserved"
# Type: ChromeOS reserved
# UUID: 23A9BEA8-8CCA-744C-9AD4-3408624F785D
# 16451 1 10 Label: "reserved"
# Type: ChromeOS reserved
# UUID: 56E34019-7E1F-D244-A74F-D594B637A18F
# 64 16384 11 Label: "RWFW"
# Type: ChromeOS firmware
# UUID: 529423BB-45F4-434B-846B-1A15A3ED987E
# 249856 65536 12 Label: "EFI-SYSTEM"
# Type: EFI System Partition
# UUID: 09ADDEBB-0333-4B48-8E1D-CB43C88C95DE
# Attr: legacy_boot=1
# 15126495 32 Sec GPT table
# 15126527 1 Sec GPT header
case ${PART:-1} in
1|"STATE")
(
mkdir -p dir_1
m=( sudo mount -o loop,offset=1516240896,sizelimit=6211764224 "${TARGET}" dir_1 )
if ! "${m[@]}"; then
if ! "${m[@]}" -o ro; then
rmdir dir_1
exit 0
fi
fi
ln -sfT dir_1 "dir_1_STATE"
) &
esac
case ${PART:-2} in
2|"KERN-A")
(
mkdir -p dir_2
m=( sudo mount -o loop,offset=10485760,sizelimit=16777216 "${TARGET}" dir_2 )
if ! "${m[@]}"; then
if ! "${m[@]}" -o ro; then
rmdir dir_2
exit 0
fi
fi
ln -sfT dir_2 "dir_2_KERN-A"
) &
esac
case ${PART:-3} in
3|"ROOT-A")
(
mkdir -p dir_3
m=( sudo mount -o loop,offset=163577856,sizelimit=1352663040 "${TARGET}" dir_3 )
if ! "${m[@]}"; then
if ! "${m[@]}" -o ro; then
rmdir dir_3
exit 0
fi
fi
ln -sfT dir_3 "dir_3_ROOT-A"
) &
esac
case ${PART:-4} in
4|"KERN-B")
(
mkdir -p dir_4
m=( sudo mount -o loop,offset=27262976,sizelimit=16777216 "${TARGET}" dir_4 )
if ! "${m[@]}"; then
if ! "${m[@]}" -o ro; then
rmdir dir_4
exit 0
fi
fi
ln -sfT dir_4 "dir_4_KERN-B"
) &
esac
case ${PART:-5} in
5|"ROOT-B")
(
mkdir -p dir_5
m=( sudo mount -o loop,offset=161480704,sizelimit=2097152 "${TARGET}" dir_5 )
if ! "${m[@]}"; then
if ! "${m[@]}" -o ro; then
rmdir dir_5
exit 0
fi
fi
ln -sfT dir_5 "dir_5_ROOT-B"
) &
esac
case ${PART:-6} in
6|"KERN-C")
esac
case ${PART:-7} in
7|"ROOT-C")
esac
case ${PART:-8} in
8|"OEM")
(
mkdir -p dir_8
m=( sudo mount -o loop,offset=44040192,sizelimit=16777216 "${TARGET}" dir_8 )
if ! "${m[@]}"; then
if ! "${m[@]}" -o ro; then
rmdir dir_8
exit 0
fi
fi
ln -sfT dir_8 "dir_8_OEM"
) &
esac
case ${PART:-9} in
9|"reserved")
esac
case ${PART:-10} in
10|"reserved")
esac
case ${PART:-11} in
11|"RWFW")
(
mkdir -p dir_11
m=( sudo mount -o loop,offset=32768,sizelimit=8388608 "${TARGET}" dir_11 )
if ! "${m[@]}"; then
if ! "${m[@]}" -o ro; then
rmdir dir_11
exit 0
fi
fi
ln -sfT dir_11 "dir_11_RWFW"
) &
esac
case ${PART:-12} in
12|"EFI-SYSTEM")
(
mkdir -p dir_12
m=( sudo mount -o loop,offset=127926272,sizelimit=33554432 "${TARGET}" dir_12 )
if ! "${m[@]}"; then
if ! "${m[@]}" -o ro; then
rmdir dir_12
exit 0
fi
fi
ln -sfT dir_12 "dir_12_EFI-SYSTEM"
) &
esac
wait
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace IteratorDemo
{
/// <summary>
/// Composite pattern, applies composition function to a set of
/// objects. CompositePainter is a "kind of" IPainter, can apply concept
/// of ProportionalPainter to ensure validity of implemented methods
/// </summary>
class CompositePainter<TPainter> : IPainter
where TPainter : IPainter
{
public bool IsAvailable
{
get { return this.Painters.Any(p => p.IsAvailable); }
set { throw new NotImplementedException(); }
}
private IEnumerable<TPainter> Painters { get; set; }
protected Func<double, IEnumerable<TPainter>, IPainter> Reduce { get; set; }
public CompositePainter(IEnumerable<TPainter> painters,
Func<double, IEnumerable<TPainter>, IPainter> reduce)
: this(painters)
{
this.Reduce = reduce;
}
protected CompositePainter(IEnumerable<TPainter> painters)
{
this.Painters = painters.ToList();
}
public TimeSpan EstimateTimeToPaint(double sqMeters)
{
return this.Reduce(sqMeters, this.Painters).EstimateTimeToPaint(sqMeters);
}
public double EstimateCompensation(double sqMeters)
{
return this.Reduce(sqMeters, this.Painters).EstimateCompensation(sqMeters);
}
}
}
|
create database dbAnicare;
use dbAnicare;
create table tbUsrMascota
(
idMascota varchar (30) primary key,
MscNombre varchar (60),
MscEspecie varchar (40),
MscRaza varchar (40)
);
create table tbUsrDueño
(
idDueño varchar (30) primary key,
dñUser varchar (40),
dñNombre varchar (60),
dñApePat varchar (30),
dñApeMat varchar (30),
dñPassword varchar (30)
);
create table tbRelDueñoMasc
(
idRelDueñoMasc varchar (30) primary key,
idDueño varchar (30),
idMascota varchar (30),
foreign key(idDueño) references tbUsrDueño(idDueño),
foreign key(idMascota) references tbUsrMascota(idMascota)
);
create table tbContacto
(
idContacto varchar (30) primary key,
idDueño varchar (30),
ctoTelefonoCel int (10),
ctoCorreo varchar (50),
foreign key(idDueño) references tbUsrDueño(idDueño)
);
create table tbMscHistorial
(
idMscHistorial varchar (30) primary key,
idMascota varchar (30),
hisEdad int (2),
hisGenero varchar (20),
hisVacunas varchar (60),
hisAlergias varchar (60),
hisPesokg int (3),
hisLargo float (5),
hisAncho float (5),
hisEnferm varchar (30),
foreign key(idMascota) references tbUsrMascota(idMascota)
);
create table tbVeterinario
(
idVeter varchar (30) primary key,
vtrNombre varchar (40),
vrtApePat varchar (40),
vtrApeMat varchar (40),
vtrConsult varchar (40)
);
create table tbRelVeterMasc
(
idRelVeterMasc varchar (30) primary key,
idMascota varchar (30),
idVeter varchar (30),
foreign key(idMascota) references tbUsrMascota(idMascota),
foreign key(idVeter) references tbVeterinario(idVeter)
);
create table tbEntrenador
(
idEntrenador varchar (30) primary key,
entNombre varchar (40),
entApePat varchar (40),
entApeMat varchar (40),
entLugar varchar (40)
);
create table tbEntrenamiento
(
idEntrenamiento varchar (30) primary key,
idEntrenador varchar (30),
idMascota varchar (30),
entrNivel varchar (5),
entrLugar varchar (40),
foreign key (idEntrenador) references tbEntrenador(idEntrenador),
foreign key (idMascota) references tbUsrMascota(idMascota)
);
|
package org.jboss.resteasy.test;
import org.jboss.resteasy.plugins.server.reactor.netty.ReactorNettyContainer;
import org.jboss.resteasy.plugins.server.reactor.netty.ReactorNettyJaxrsServer;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.jboss.resteasy.test.TestPortProvider.generateURL;
/**
* @author <a href="mailto:[email protected]">Ron Sigal</a>
* RESTEASY-1244
*
* @version $Revision: 1 $
*/
public class HeaderTooLongTest
{
private static final int MAX_HEADER_SIZE = 10;
final String longString =
IntStream.range(0, MAX_HEADER_SIZE + 1)
.mapToObj(i -> "a")
.collect(Collectors.joining());
@Path("/")
public static class Resource
{
@GET
@Path("/org/jboss/resteasy/test")
public String hello(@Context HttpHeaders headers)
{
return "hello world";
}
}
static Client client;
@BeforeClass
public static void setup() throws Exception
{
final ReactorNettyJaxrsServer reactorNettyJaxrsServer = new ReactorNettyJaxrsServer();
reactorNettyJaxrsServer.setDecoderSpecFn(spec -> spec.maxHeaderSize(MAX_HEADER_SIZE));
ReactorNettyContainer.start(reactorNettyJaxrsServer).getRegistry().addPerRequestResource(Resource.class);
client = ClientBuilder.newClient();
}
@AfterClass
public static void end() throws Exception
{
client.close();
ReactorNettyContainer.stop();
}
@Test
public void testLongHeader() throws Exception
{
WebTarget target = client.target(generateURL("/org/jboss/resteasy/test"));
Response response = target.request().header("xheader", longString).get();
// [AG] Discuss with @crankydillo. Yes, this is coming from Netty. Reactor Netty
// allows configuring the max value. When I changed our settings as below, I get 200,
// because the maxHeaderSize is quite large:
// HttpServer svrBuilder =
// HttpServer.create()
// .tcpConfiguration(this::configure)
// .port(configuredPort)
// .httpRequestDecoder(spec -> spec.maxHeaderSize(Integer.MAX_VALUE));
//
// The problem though.. Shouldn't it be 431 (Request Header Fields Too Large)
// instead of 413 (Payload Too Large)?
Assert.assertEquals(413, response.getStatus());
}
}
|
@extends('admin.templates.default')
@section('title', 'Data Categories')
@section('content')
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Data Categories</h3>
</div>
<div class="card-body">
@if(session()->has('message'))
<div class="alert alert-info alert-dismissible fade show" role="alert">
{{ session('message') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif
<a href="{{ route('admin.categories.create') }}" class="btn btn-primary mb-3">Add Category</a>
<table id="dataTable" class="table table-bordered table-hover">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Slug</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
@endsection
@push('styles')
<link rel="stylesheet" href="{{ asset('assets/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css') }}">
<link rel="stylesheet" href="{{ asset('assets/plugins/datatables-responsive/css/responsive.bootstrap4.min.css') }}">
<link rel="stylesheet" href="{{ asset('assets/plugins/sweetalert2-theme-bootstrap-4/bootstrap-4.min.css ') }}">
@endpush
@push('scripts')
<script src="{{ asset('assets/plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('assets/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js') }}"></script>
<script src="{{ asset('assets/plugins/datatables-responsive/js/dataTables.responsive.min.js') }}"></script>
<script src="{{ asset('assets/plugins/datatables-responsive/js/responsive.bootstrap4.min.js') }}"></script>
<script src="{{ asset('assets/plugins/sweetalert2/sweetalert2.min.js') }}"></script>
<script>
$(function () {
$('#dataTable').dataTable({
"processing": true,
"serverSide": true,
"responsive": true,
"autoWidth": true,
ajax: '{{ route('admin.categories.data') }}',
columns: [{
data: 'DT_RowIndex',
orderable: false,
searchable: false
}, {
data: 'name'
}, {
data: 'slug'
}, {
data: 'action'
}, ]
})
})
$('#dataTable').on('click', 'button#delete', function(e){
e.preventDefault();
var id = $(this).data('id');
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'DELETE',
url: '/admin/categories/' + id,
data: {
"id": id,
"_token": "{{ csrf_token() }}",
},
success: function(response){
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
location.reload(true);
}
});
}
})
})
</script>
@endpush
|
import { useReducer } from 'react';
import { NavbarContext, initialState } from './navbarContext';
import { navbarReducer } from '../reducerContext';
import { NAVBAR_ACTION } from '../actionContext';
interface IChildren {
children: React.ReactNode;
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const NavbarContextProvider = ({ children }: IChildren) => {
const [state, dispatch] = useReducer(navbarReducer, initialState);
const setOpen = (loading: boolean) => {
dispatch({
type: NAVBAR_ACTION.SET_OPEN,
payload: loading,
});
};
return <NavbarContext.Provider value={{ ...state, setOpen }}>{children}</NavbarContext.Provider>;
};
|
var searchData=
[
['find_5fblock',['find_block',['../buddy_8c.html#abdfe2346b53850f10cb4cb70a79e6334',1,'buddy.c']]],
['find_5ffree_5fblock',['find_free_block',['../buddy_8c.html#a2f7a9bf73e255fb58bf8e57855e67532',1,'buddy.c']]]
];
|
ALTER TABLE ${ohdsiSchema}.fe_analysis_criteria ADD criteria_type VARCHAR(255)
GO
UPDATE fc
SET criteria_type = CASE WHEN fa.stat_type = 'PREVALENCE' THEN 'CRITERIA_GROUP'
WHEN fa.stat_type = 'DISTRIBUTION' THEN 'WINDOWED_CRITERIA' END
FROM ${ohdsiSchema}.fe_analysis_criteria fc
JOIN ${ohdsiSchema}.fe_analysis fa ON fa.id = fc.fe_analysis_id;
|
<?php
require_once(__DIR__."/../controller/DBController.php");
require_once(__DIR__."/../model/Concurso.php");
require_once(__DIR__."/../core/ViewManager.php");
class ConcursoController extends DBController {
/*Variable que representa el objeto Concurso*/
private $concurso;
/*Constructor*/
public function __construct() {
parent::__construct();
//Inicializa la variable concurso
$this->concurso = new Concurso();
}
/*Este método hace que se muestren en la vista de consultar
concurso los datos del propio concurso*/
public function consultarConcurso() {
/*Metodo de la clase Concurso que devuelve los datos del concurso*/
$concu = $this->concurso->ver_datos();
/* Guarda el valor de la variable $concu en la variable concu accesible
desde la vista*/
$this->view->setVariable("concu", $concu);
/*Permite visualizar: view/vistas/consultaConcurso.php */
$this->view->render("vistas", "consultaConcurso");
}
/* Este metodo hace que se muestren los valores actuales del concurso y
permite que el usuario administrador los modifique*/
public function modificarConcurso() {
if(!$_SESSION["currentuser"]){
echo "<script>window.location.replace('index.php');</script>";
}
$concu= new Concurso();
if (isset($_POST["nombreC"])){
/*Metodo de la clase concurso que devuelve un boolean indicando si
el concurso existe en la base de datos*/
$existe=$concu->existConcurso();
/*Si el concurso no existe devuelve un mensaje de error*/
if(!$existe){
$errors = array();
$errors["nombreC"] = "Este concurso no existe, por lo que no se puede modificar";
$this->view->setVariable("errors", $errors);
/*Si el concurso si que existe, se guardan los valores introducidos en la
modificacion en la clase concurso*/
}else{
$concu->setIdC('1');
$concu->setNombreC($_POST["nombreC"]);
$ruta="./resources/bases/";//ruta carpeta donde queremos copiar las imagenes
$basesCTemp=$_FILES['basesC']['tmp_name'];//guarda el directorio temporal en el que se sube la imagen
$basesC=$ruta.$_FILES['basesC']['name'];//indica el directorio donde se guardaran las imagenes
move_uploaded_file($basesCTemp, $basesC);
$concu->setBasesC($basesC,$basesCTemp);
$concu->setCiudadC($_POST["ciudadC"]);
$concu->setFechaInicioC($_POST["fechaInicioC"]);
$concu->setFechaFinalC($_POST["fechaFinalC"]);
$concu->setFechaFinalistasC($_POST["fechaFinalistasC"]);
$concu->setPremioC($_POST["premioC"]);
$concu->setPatrocinadorC($_POST["patrocinadorC"]);
try{
/*Comprueba si los datos introducidos son validos*/
$concu->checkIsValidForRegister();
// Actualiza los datos del concurso
$concu->update();
//mensaje de confirmación y redirige al metodo consultarConcurso del controlador ConcursoCotroller
echo "<script> alert('Modificación realizada correctamente'); </script>";
echo "<script>window.location.replace('index.php?controller=concurso&action=consultarConcurso');</script>";
}catch(ValidationException $ex) {
$errors = $ex->getErrors();
$this->view->setVariable("errors", $errors);
}
}
}
/*Devuelve los datos del concurso para mostrarlos en la vista*/
$concu = $this->concurso->ver_datos();
/* Guarda el valor de la variable $concu en la variable concu accesible
desde la vista*/
$this->view->setVariable("concu", $concu);
/*Permite visualizar: view/vistas/modificacionConcurso.php */
$this->view->render("vistas", "modificacionConcurso");
}
/*Funcion para crear un nuevo concurso*/
public function registro() {
if(!$_SESSION["currentuser"]){
echo "<script>window.location.replace('index.php');</script>";
}
$concu= new Concurso();
if (isset($_POST["nombreC"])){
/*Comprueba si ya existe un concurso en la base de datos*/
$existe=$concu->existConcurso();
/*Si existe muestra un mensaje de error ya que solo puede existir un concurso
en la base de datos*/
if($existe){
$errors = array();
$errors["nombreC"] = "Ya existe un concurso registrado, no puede haber más";
$this->view->setVariable("errors", $errors);
/*Si no existe guarda los datos introducidos.*/
}else{
$concu->setIdC('1');
$concu->setNombreC($_POST["nombreC"]);
$ruta="./resources/bases/";//ruta carpeta donde queremos copiar las imagenes
$basesCTemp=$_FILES['basesC']['tmp_name'];//guarda el directorio temporal en el que se sube la imagen
$basesC=$ruta.$_FILES['basesC']['name'];//indica el directorio donde se guardaran las imagenes
move_uploaded_file($basesCTemp, $basesC);
$concu->setBasesC($basesC,$basesCTemp);
$concu->setCiudadC($_POST["ciudadC"]);
$concu->setFechaInicioC($_POST["fechaInicioC"]);
$concu->setFechaFinalC($_POST["fechaFinalC"]);
$concu->setFechaFinalistasC($_POST["fechaFinalistasC"]);
$concu->setPremioC($_POST["premioC"]);
$concu->setPatrocinadorC($_POST["patrocinadorC"]);
try{
/*Comprueba si los datos son validos*/
$concu->checkIsValidForRegister();
// guarda el objeto en la base de datos
$concu->save();
//mensaje de confirmación y redirige al metodo consultarConcurso del controlador ConcursoCotroller
echo "<script> alert('Concurso registrado correctamente'); </script>";
echo "<script>window.location.replace('index.php?controller=concurso&action=consultarConcurso');</script>";
}catch(ValidationException $ex) {
$errors = $ex->getErrors();
$this->view->setVariable("errors", $errors);
}
}
}
// renderiza la vista (/view/vistas/altaConcurso.php)
$this->view->render("vistas", "altaConcurso");
}
}
|
import colors from '../utils/colors';
const playersButtonStyle = {
backgroundColor: colors.default,
border: `4px solid ${colors.primary}`,
width: '85%',
maxWidth: 300,
height: '40%',
margin: 'auto',
cursor: 'auto',
};
const controlsAreaStyle = {
backgroundColor: colors.secondary,
width: 140,
margin: 'auto',
padding: '5px 0px',
display: 'flex',
justifyContent: 'space-around',
alignItems: 'center',
};
const controlsButtonStyle = {
height: '90%',
padding: 0,
borderColor: colors.secondary,
};
const controlsIconStyle = {
color: colors.disabled,
fontSize: '3em',
display: 'block',
};
const ModalContentStyle = {
display: 'flex',
justifyContent: 'space-between',
};
export {
playersButtonStyle,
controlsAreaStyle,
controlsButtonStyle,
controlsIconStyle,
ModalContentStyle,
};
|
module CitiesHelper
def city_space_summary(city)
"#{city.free_space} / #{city.total_space}"
end
def city_population_summary(city)
"#{city.population} / #{city.total_capacity}"
end
end
|
#!bin/bash
set -e
mkdir model
cd model
wget https://raw.githubusercontent.com/MTlab/onnx2caffe/master/model/MobileNetV2.onnx
|
#PATH TO APACHE MAVEN
export PATH={{opt_folder}}/{{apache_maven_folder}}/bin:$PATH
|
package xyz.fairportstudios.popularin.models
data class UserDetail(
val isSelf: Boolean,
val isFollower: Boolean,
var isFollowing: Boolean,
val isPointPositive: Boolean,
val hasRecentFavorite: Boolean,
val hasRecentReview: Boolean,
val totalReview: Int,
val totalFavorite: Int,
val totalWatchlist: Int,
var totalFollower: Int,
val totalFollowing: Int,
val totalPoint: String,
val fullName: String,
val username: String,
val profilePicture: String
)
|
var struct_i_t_c_stream_tag =
[
[ "Available", "struct_i_t_c_stream_tag.html#abce0b456a63dd9e0147e9e768ec2e9ad", null ],
[ "Close", "struct_i_t_c_stream_tag.html#a4d390d0c39d00116bf4c8a9378ce5d6d", null ],
[ "eof", "struct_i_t_c_stream_tag.html#a6c052602d1d43227768ad3807f7b7268", null ],
[ "Read", "struct_i_t_c_stream_tag.html#a390b800fa61369fda2d100bd9f771cfa", null ],
[ "ReadLock", "struct_i_t_c_stream_tag.html#ae03803884772435da061dc1c00170182", null ],
[ "ReadUnlock", "struct_i_t_c_stream_tag.html#a95a0b4875f4ef0ba7e442497b0115ea2", null ],
[ "Seek", "struct_i_t_c_stream_tag.html#a68f2a9d6ce3b36f0b00ffe3f47372e73", null ],
[ "size", "struct_i_t_c_stream_tag.html#a439227feff9d7f55384e8780cfc2eb82", null ],
[ "Tell", "struct_i_t_c_stream_tag.html#a4d50fd1cf9bc1dc9ba86a3a3473d626f", null ],
[ "Write", "struct_i_t_c_stream_tag.html#aa1126b97892a5f7e2a574d5102fd389d", null ],
[ "WriteLock", "struct_i_t_c_stream_tag.html#a625b8c401dd3bbacfa59cbd5eb0e7a77", null ],
[ "WriteUnlock", "struct_i_t_c_stream_tag.html#a8cbe1cd3c47a66e0f9dd7fa8bf2d6fee", null ]
];
|
#include "lymcodationlock.h"
LYMCodationLock::LYMCodationLock():mutex_(SDL_CreateMutex()),cond_(SDL_CreateCond())
{
}
LYMCodationLock::~LYMCodationLock(){
SDL_DestroyCond(cond_);
SDL_DestroyMutex(mutex_);
}
void LYMCodationLock::lock(){
SDL_LockMutex(mutex_);
}
void LYMCodationLock::unlock(){
SDL_UnlockMutex(mutex_);
}
void LYMCodationLock::wait(){
SDL_CondWait(cond_,mutex_);
}
void LYMCodationLock::signal(){
SDL_CondSignal(cond_);
}
void LYMCodationLock::broadcastSig(){
SDL_CondBroadcast(cond_);
}
|
. helpers.sh
start_test_server \
-line 1 -file data/nopersistency-close -reconnect \
-line 1 -file data/nopersistency-close
trap "stop_test_server" EXIT
request -get / -get / -run
# Because the reply contains a 'connection: close' header, it is expected
# that the second GET forces a new connection.
|
package io.jobial.scase.core
import scala.annotation.implicitNotFound
/**
* Type class to bind a request message type to a response type.
* It makes request-response mapping pluggable, without enforcing any kind of convention on the implementor.
*
* @tparam REQUEST
* @tparam RESPONSE
*/
@implicitNotFound("No mapping found from request type ${REQUEST} to response type ${RESPONSE}")
trait RequestResponseMapping[REQUEST, RESPONSE]
|
# Object Instance
Validates if the given input is object instance.
Valid values:
```js
validator.objectInstance().validate({});
validator.objectInstance().validate({foo: 'bar'});
validator.objectInstance().validate(new Object());
validator.objectInstance().validate(new Object({foo: 'bar'}));
validator.objectInstance().validate([]]);
validator.objectInstance().validate(new Array());
validator.objectInstance().validate(['foo']);
validator.objectInstance().validate(new Array('foo'));
```
Invalid values:
```js
validator.objectInstance().validate(null);
validator.objectInstance().validate(Object.create(null));
validator.objectInstance().validate(undefined);
validator.objectInstance().validate(true);
validator.objectInstance().validate(false);
validator.objectInstance().validate('foo');
validator.objectInstance().validate(0);
validator.objectInstance().validate(1);
```
|
require 'bundler/setup'
Bundler.require(:default, :development)
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.filter_run_excluding :perf => true
config.order = 'random'
end
require 'webmock/rspec'
RSpec.configure do |config|
config.before(:each) do
WebMock.disable_net_connect!
end
end
require 'vcr'
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock
c.configure_rspec_metadata!
end
require File.expand_path('../../lib/moodle_rb.rb', __FILE__)
|
## SQlite
### Purpose
This `sqlite` package provides a basic interface for interacting with the
embedded sqlite database used by various InfluxDB services which require storing
relational data.
The actual sqlite driver is provided by
[`mattn/go-sqlite3`](https://github.com/mattn/go-sqlite3).
### Usage
A single instance of `SqlStore` should be created using the `NewSqlStore`
function. Currently, this is done in the top-level `launcher` package, and a
pointer to the `SqlStore` instance is passed to services which require it as
part of their initialization.
The [`jmoiron/sqlx`](https://github.com/jmoiron/sqlx) package provides a
convenient and lightweight means to write and read structs into and out of the
database and is sufficient for performing simple, static queries. For more
complicated & dynamically constructed queries, the
[`Masterminds/squirrel`](https://github.com/Masterminds/squirrel) package can be
used as a query builder.
### Concurrent Access
An interesting aspect of using the file-based sqlite database is that while it
can support multiple concurrent read requests, only a single write request can
be processed at a time. A traditional RDBMS would manage concurrent write
requests on the database server, but for this sqlite implementation write
requests need to be managed in the application code.
In practice, this means that code intended to mutate the database needs to
obtain a write lock prior to making queries that would result in a change to the
data. If locks are not obtained in the application code, it is possible that
errors will be encountered if concurrent write requests hit the database file at
the same time.
### Migrations
A simple migration system is implemented in `migrator.go`. When starting the
influx daemon, the migrator runs migrations defined in `.sql` files using
sqlite-compatible sql scripts. Records of these migrations are maintained in a
table called "migrations". If records of migrations exist in the "migrations"
table that are not embedded in the binary, an error will be raised on startup.
When creating new migrations, follow the file naming convention established by
existing migration scripts, which should look like `00XX_script_name.up.sql` &
`00xx_script_name.down.sql` for the "up" and "down" migration, where `XX` is the
version number. New scripts should have the version number incremented by 1.
The "up" migrations are run when starting the influx daemon and when metadata
backups are restored. The "down" migrations are run with the `influxd downgrade`
command.
### In-Memory Database
When running `influxd` with the `--store=memory` flag, the database will be
opened using the `:memory:` path, and the maximum number of open database
connections is set to 1. Because of the way in-memory databases work with
sqlite, each connection would see a completely new database, so using only a
single connection will ensure that requests to `influxd` will return a
consistent set of data.
### Backup & Restore
Methods for backing up and restoring the sqlite database are available on the
`SqlStore` struct. These operations make use of the [sqlite backup
API](https://www.sqlite.org/backup.html) made available by the `go-sqlite3`
driver. It is possible to restore and backup into sqlite databases either stored
in memory or on disk.
### Sqlite Features / Extensions
There are many additional features and extensions available, see [the go-sqlite3
package docs](https://github.com/mattn/go-sqlite3#feature--extension-list) for
the full list.
We currently use the `sqlite_foreign_keys` and `sqlite_json` extensions for
foreign key support & JSON query support. These features are enabled using
build tags defined in the `Makefile` and `.goreleaser` config for use in
local builds & CI builds respectively.
|
package models
import (
"gorm.io/gorm"
)
// UpdateRate defined update_rate DB table
type UpdateRate struct {
gorm.Model
BaseCurrency string `json:"baseCurrency" gorm:"uniqueIndex:idx_name"`
TransactionCurrency string `json:"transactionCurrency" gorm:"uniqueIndex:idx_name"`
ExchangeRate float64 `json:"exchangeRate"`
EffectiveDate string `json:"effectiveDate" gorm:"uniqueIndex:idx_name"`
}
|
---
layout: post
title: "Puzzle: Sudoku Stories"
date: 2018-10-26 00:03:00 +0000
tags:
math
puzzles
---
Today I discovered a little book called [_Sudoku Stories_](https://amzn.to/2RAO0YB)
(Oscar Seurat, 2014). Each page presents a little encyclopedia entry on some
random topic accompanied by a sudoku puzzle whose pre-filled cells trace out
a shape corresponding to the entry. For example:

This got me thinking: There are 2<sup>81</sup> different "images" possible
on a 9x9 grid. For some of these images (e.g. the all-filled-in image, the
moose image), it's clearly possible to create a sudoku from them. For others
(e.g. any image containing [fewer than 17](https://arxiv.org/abs/1201.0749) pixels),
it's clearly impossible.
Roughly how many "sudoku-able" 9x9 images exist? Is it on the order of 2<sup>81</sup>?
On the order of 2<sup>30</sup>?
----
We can imagine a "meta-sudoku" version of the moose puzzle. Given *only*
the moose image,

I ask you to assign numbers to the black squares so that the resulting grid
is a valid sudoku puzzle (with only one possible completion, of course).
One solution to the moose meta-puzzle is Seurat's original moose puzzle.
Does the moose meta-puzzle have a _unique_ solution? (Trivially, no, because you
can always e.g. substitute `1` for `9` and `9` for `1`, to produce another
valid sudoku. But does it have a unique solution _up to_ swaps of that kind?)
Off the top of my head, I suspect that the moose meta-puzzle does *not* have
a unique solution. Can you come up with any meta-puzzle that *does* have a unique
solution (up to swaps)?
How many of the 2<sup>81</sup> metapuzzles have unique solutions?
|
import 'package:flutter/material.dart';
class TimerButton extends StatelessWidget {
TimerButton(
{Key? key, required this.text, required this.event, required this.icon})
: super(key: key);
final String text;
final Function event;
final IconData icon;
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return Padding(
padding: const EdgeInsets.only(left: 5.0),
child: SizedBox(
width: width / 2,
height: width / 7,
child: TextButton.icon(
onPressed: () {
event();
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.white10),
overlayColor: MaterialStateProperty.all<Color>(Colors.black),
),
icon: Icon(
icon,
color: Theme.of(context).textTheme.button!.color,
),
label: Text(
text,
style: Theme.of(context).textTheme.button,
),
),
),
);
}
}
|
import { LoginStore } from './pages/login/stores';
import { RegisterStore } from './pages/register/stores';
import { MainStore } from './pages/main/stores';
export interface AppStore {
loginReducer: LoginStore;
registerReducer: RegisterStore;
mainReducer: MainStore;
};
|
/*
* User: 覃贵锋
* Date: 2021/11/5
* Time: 14:53
*
*
*/
using System;
using BTreeEditor.Data;
namespace BTreeEditor
{
/// <summary>
/// 行为树工作空间
/// </summary>
public static class BTreeWorkspace
{
/// <summary>
/// 行为树工作空间是数据
/// </summary>
public static BTreeWorkspaceData CurrentWorkspaceData {set; get;}
/// <summary>
/// 通过方法名获取执行方法
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static MethodData GetActionWithName(string name)
{
foreach (MethodData data in BTreeWorkspace.CurrentWorkspaceData.Actions)
{
if(data.methodName == name)
{
return data;
}
}
return null;
}
/// <summary>
/// 通过方法名获取条件方法
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static MethodData GetConditionWithName(string name)
{
foreach (MethodData node in BTreeWorkspace.CurrentWorkspaceData.Conditions)
{
if(node.methodName == name)
{
return node;
}
}
return null;
}
}
}
|
require 'spec_helper'
describe "routing to product categories" do
it "routes /ecm_products_product_categories to #index" do
expect(:get => "/ecm_products_product_categories").to route_to(
:controller => "ecm/products/product_categories",
:action => "index"
)
end # it
it "routes /ecm_products_product_categories/example-category to #show" do
expect(:get => "/ecm_products_product_categories/example-category").to route_to(
:controller => "ecm/products/product_categories",
:action => "show",
:id => "example-category"
)
end # it
end
describe "routing to products" do
it "routes /ecm_products_products to #index" do
expect(:get => "/ecm_products_products").to route_to(
:controller => "ecm/products/products",
:action => "index"
)
end # it
it "routes /ecm_products_products/example-product to #show" do
expect(:get => "/ecm_products_products/example-product").to route_to(
:controller => "ecm/products/products",
:action => "show",
:id => "example-product"
)
end # it
end
|
import {Component} from "@angular/core";
import {Task} from "../models/task";
import {OnInit} from "@angular/core";
import {TaskService} from "../services/task-service";
import {TaskComponent} from "./task.component";
@Component({
selector: 'task-list',
templateUrl: './app/todo/components/task-list.html',
styleUrls: ['./app/todo/components/task-list.css'],
providers: [TaskService]
})
export class TaskListComponent implements OnInit {
todoCount:number;
selectedTask:Task;
tasks:Array<Task>;
constructor(private _taskService:TaskService) {
this.tasks = _taskService.getTasks();
this.calculateTodoCount();
}
ngOnInit() {
console.log("Todo component initialized with " + this.tasks.length + " tasks.");
}
calculateTodoCount() {
this.todoCount = this.tasks.filter(t => !t.done).length;
}
select(task:Task) {
this.selectedTask = task;
}
}
|
A dict of the INCAR parameters used for the relaxation calculation.
## Example response in JSON
```json
{
"@class": "Incar",
"@module": "pymatgen.io.vasp.inputs",
"ALGO": "Fast",
"EDIFF": 2e-06,
"ENCUT": 520,
"IBRION": 2,
"ICHARG": 1,
"ISIF": 3,
"ISMEAR": -5,
"ISPIN": 2,
"LREAL": "Auto",
"LWAVE": true,
"MAGMOM": [
0.6,
0.6,
0.6
],
"NELM": 100,
"NELMIN": 3,
"NPAR": 1,
"NSW": 200,
"PREC": "Accurate",
"SIGMA": 0.05,
"SYSTEM": "Rubyvaspy :: te"
}
```
|
---
authorName: myaleee n
canDelete: false
contentTrasformed: false
from: '"myaleee n" <myaleee@...>'
headers.inReplyToHeader: PENPTDEwNS1XNUNBNkQyMDlGRTFCNDAyNjA5NjBEOEJGNzBAcGh4LmdibD4=
headers.messageIdInHeader: PGloNzc1cStpMDBnQGVHcm91cHMuY29tPg==
headers.referencesHeader: .nan
layout: email
msgId: 1668
msgSnippet: 'Karo Niles Mi fo gene interese de u klari mode de tu grafo e translati.
Mi spe ke mi plu korekti de tu ero ne sio vexi tu, pardo! Lekto,place: * An pa kapti'
nextInTime: 1669
nextInTopic: 1669
numMessagesInTopic: 6
postDate: '1295458298'
prevInTime: 1667
prevInTopic: 1667
profile: myaleee
replyTo: LIST
senderId: nWoi1KsZIDJ77j1yWtt--_V-2VIidsK_nAGSS_vCutCnLAKg-FWWJV7XlJct_yR6YxYFa57E8uFox1r2fH24QsJaY2Q4cA
spamInfo.isSpam: false
spamInfo.reason: '0'
systemMessage: false
title: 'Re: Aesop 7: U Ju-an Casa plu Lokusta'
topicId: 1667
userId: 288947930
---
Karo Niles
Mi fo gene interese de u klari mode de tu grafo e translati. Mi =
spe ke mi plu korekti de tu ero ne sio vexi tu, pardo! Lekto,place:
* An p=
a kapti mega quantita de mu> An pa kapti mega Numera de mu
*e extende an ma=
nu te prende id> e extende AUTO manu te prende id(his own,refers to "an" no=
t someone else's)
* tem monstra id punge-ra> tem monstra AUTO punge-ra
*A =
fini mi fo volu ski qo-mode S. Miller puta de plu-ci?
Itere, mi fo mega pe=
nite pro vexi tu
tu ami myaleee!
--- In [email protected], Ian Nil=
es <ian_niles@...> wrote:
>
>
>
> U ju-an pa du casa plu lokusta. An pa=
kapti mega quantita de mu, kron an pa vide u skorpio. An ero-mode pa kred=
i; u skorpio es lokusta, e extende an manu te prende id. U skorpio, tem mo=
nstra id punge-ra, pa dice; si vi solo sio pa palpa mi, mi ami, vi sio pa l=
ose mi e panto vi plu lokusta plus.
>
> [Non-text portions of =
this message have been removed]
>
|
<?php
/*
* This file is part of the Behat Gherkin.
* (c) Konstantin Kudryashov <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Gherkin\Filter;
use Behat\Gherkin\Node\FeatureNode;
use Behat\Gherkin\Node\ScenarioInterface;
/**
* Filters features by their paths.
*
* @author Konstantin Kudryashov <[email protected]>
*/
class PathsFilter extends SimpleFilter
{
protected $filterPaths = array();
/**
* Initializes filter.
*
* @param string[] $paths List of approved paths
*/
public function __construct(array $paths)
{
$this->filterPaths = array_map(
function ($realpath) {
return rtrim($realpath, DIRECTORY_SEPARATOR) .
(is_dir($realpath) ? DIRECTORY_SEPARATOR : '');
},
array_filter(
array_map('realpath', $paths)
)
);
}
/**
* Checks if Feature matches specified filter.
*
* @param FeatureNode $feature Feature instance
*
* @return Boolean
*/
public function isFeatureMatch(FeatureNode $feature)
{
foreach ($this->filterPaths as $path) {
if (0 === strpos(realpath($feature->getFile()), $path)) {
return true;
}
}
return false;
}
/**
* Checks if scenario or outline matches specified filter.
*
* @param ScenarioInterface $scenario Scenario or Outline node instance
*
* @return false This filter is designed to work only with features
*/
public function isScenarioMatch(ScenarioInterface $scenario)
{
return false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AliyunDnsSDK.Model.EnumType
{
public enum DomainRecordStatus
{
Enable,
Disable
}
}
|
import "package:args/command_runner.dart";
import "package:multipack/commands/pub.dart";
import "package:multipack/commands/pubspec.dart";
void main(List<String> arguments) async {
final runner = CommandRunner<void>(
"multipack",
"Manages monorepo packages.",
)
..addCommand(PubCommand())
..addCommand(PubspecCommand());
await runner.run(arguments);
}
|
---
layout: post
title: ROS节点名字、话题名字总结
subtitle:
date: 2020-07-05
author: 白夜行的狼
header-img: img/black.jpeg
catalog: true
categories:
published: false
tags:
-
-
-
-
-
---
# 0. 写在最前面
本文持续更新地址:<https://haoqchen.site/2020/07/05/ros-node-name/>
ROS中有节点(node)和话题(topic)的概念,他们都会有一个唯一的名字(name)。但是当涉及到命名空间(namespace)的时候,就会变得复杂起来。本文将对相关知识点进行总结,争取一篇文章能将与话题和节点名称相关的都说清楚。
如果觉得写得还不错,可以找我其他文章来看看哦~~~可以的话帮我github点个赞呗。
**你的[Star](https://github.com/HaoQChen/HaoQChen.github.io)是作者坚持下去的最大动力哦~~~**
# 1. ROS名称定义
# 参考
<br>
**喜欢我的文章的话Star一下呗[Star](https://github.com/HaoQChen/HaoQChen.github.io)**
**版权声明:本文为白夜行的狼原创文章,未经允许不得以任何形式转载**
|
POSE_QUANTITY=$1
END=$2
for ((SEED=1;SEED<=END;SEED++))
do
python plot_g2o_slampp.py output_"$SEED".txt $POSE_QUANTITY
done
|
package ronybrosh.rocketlauncher.data.db.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "launchTable", indices = [Index(
value = ["rocketId", "flightNumber"],
unique = true
)]
)
data class LaunchRow(
@PrimaryKey(autoGenerate = true) val id: Long = 0L,
@ColumnInfo(name = "flightNumber") val flightNumber: Int,
@ColumnInfo(name = "rocketId") val rocketId: String,
@ColumnInfo(name = "missionName") val missionName: String,
@ColumnInfo(name = "launchYear") val launchYear: String,
@ColumnInfo(name = "patchImageUrl") val patchImageUrl: String?,
@ColumnInfo(name = "launchDateUnix") val launchDateUnix: Long,
@ColumnInfo(name = "isSuccessful") val isSuccessful: Boolean
)
|
# DIGITAL HEARING AID USING MATLAB
In this project we have created a DIGITAL HEARING AID using MATLAB software and Graphical User Interface
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\gatepass;
use App\Barang;
use App\Gatebar;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Auth;
class GatepassController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
if(Auth::user()->hasrole('admin'))
{
$gate = gatepass::all();
$gatebar = Gatebar::all();
}elseif(Auth::user()->hasrole('spv'))
{
$gate = gatepass::where('status','=','0')->get();
$gatebar = Gatebar::all();
}elseif(Auth::user()->hasrole('manager'))
{
$gate = gatepass::where('status','=','1')->get();
$gatebar = Gatebar::all();
}
elseif(Auth::user()->hasrole('authorized_manager'))
{
$gate = gatepass::where('status','=','2')->get();
$gatebar = Gatebar::all();
}elseif(Auth::user()->hasrole('security'))
{
$gate = gatepass::where('status','=','3')->get();
$gatebar = Gatebar::all();
}
// dd($gate);
return view('gatepass.index',compact('gate','gatebar'));
}
public function masuk()
{
$gate = gatepass::where('status','=','4')->get();
return view('gatepass.masuk',compact('gate'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$barang = Barang::all();
return view('gatepass.form',compact('barang'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$barang = Barang::all();
$gate = new gatepass();
// $gatebar->id_gatepass = $request->get('barang');
$gate->GO = $request->GO;
$gate->PO = $request->PO;
$gate->tgl = $request->tgl;
$gate->trans_agent = $request->trans_agent;
$gate->truck = $request->truck;
$gate->customer = $request->customer;
$gate->cust_address = $request->cusadd;
$gate->status = '0';
if($gate->save())
{
foreach($request->barang as $key =>$barang)
{
// dd($request->all());
$id_gatepass = $gate->id;
$gatebar = new Gatebar();
$gatebar->gatepass_id = $id_gatepass;
$gatebar->barang_id = $request->barang[$key];
$gatebar->quantity = $request->quantity[$key];
$gatebar->remarks = $request->remarks[$key];
$gatebar->save();
}
return redirect('gatepass');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
public function detail($id)
{
$gate = gatepass::findOrFail($id);
$gatebar = Gatebar::where('gatepass_id',$id)->get();
$data = [
'gate' => $gate,
'gatebar' => $gatebar
];
// dd($gatebar);
// dd($data);
return view('gatepass/detail',compact('gate','gatebar','data'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
gatepass::destroy($id);
return redirect('gatepass');
//
}
public function label(Request $request,$id)
{
$gate = gatepass::findOrFail($id);
return view('gatepass/form_label',compact('gate'));
}
public function detail_label()
{
// $label = gatepass::findOrFail($id);
return view('gatepass/detail_label');
}
public function paraf(Request $request)
{
if(Auth::user()->hasrole('spv'))
{
$imagedata = base64_decode($request->img_data);
$filename = md5(date("dmYhisA"));
$paraf = '../public/uploads/paraf_spv/'.$filename.'.png';
file_put_contents($paraf,$imagedata);
$gatepass = gatepass::find($request->gatepass_id);
$gatepass->despatch_spv = 'uploads/paraf_spv/'.$filename.'.png';
$gatepass->status = '1';
if($gatepass->save())
{
return response()->json([
'fail' => false,
]);
}
}elseif(Auth::user()->hasrole('manager'))
{
$imagedata = base64_decode($request->img_data);
$filename = md5(date("dmYhisA"));
$paraf = '../public/uploads/paraf_manag/'.$filename.'.png';
file_put_contents($paraf,$imagedata);
$gatepass = gatepass::find($request->gatepass_id);
$gatepass->despatch_manag = 'uploads/paraf_manag/'.$filename.'.png';
$gatepass->status = '2';
if($gatepass->save())
{
return response()->json([
'fail' => false,
]);
}
}elseif(Auth::user()->hasrole('authorized_manager'))
{
$imagedata = base64_decode($request->img_data);
$filename = md5(date("dmYhisA"));
$paraf = '../public/uploads/paraf_authorized/'.$filename.'.png';
file_put_contents($paraf,$imagedata);
$gatepass = gatepass::find($request->gatepass_id);
$gatepass->authorized_sign = 'uploads/paraf_authorized/'.$filename.'.png';
$gatepass->status = '3';
if($gatepass->save())
{
return response()->json([
'fail' => false,
]);
}
}else{
$imagedata = base64_decode($request->img_data);
$filename = md5(date("dmYhisA"));
$paraf = '../public/uploads/paraf_security/'.$filename.'.png';
file_put_contents($paraf,$imagedata);
$gatepass = gatepass::find($request->gatepass_id);
$gatepass->despatch_security = 'uploads/paraf_security/'.$filename.'.png';
$gatepass->status = '4';
if($gatepass->save())
{
return response()->json([
'fail' => false,
]);
}
}
}
}
|
/*
* Copyright 2017 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Lowers i64s to i32s by splitting variables and arguments
// into pairs of i32s. i64 return values are lowered by
// returning the low half and storing the high half into a
// global.
//
#include "abi/js.h"
#include "asmjs/shared-constants.h"
#include "emscripten-optimizer/istring.h"
#include "ir/flat.h"
#include "ir/iteration.h"
#include "ir/memory-utils.h"
#include "ir/module-utils.h"
#include "ir/names.h"
#include "pass.h"
#include "support/name.h"
#include "wasm-builder.h"
#include "wasm.h"
#include <algorithm>
namespace wasm {
static Name makeHighName(Name n) { return std::string(n.c_str()) + "$hi"; }
struct I64ToI32Lowering : public WalkerPass<PostWalker<I64ToI32Lowering>> {
struct TempVar {
TempVar(Index idx, Type ty, I64ToI32Lowering& pass)
: idx(idx), pass(pass), moved(false), ty(ty) {}
TempVar(TempVar&& other)
: idx(other), pass(other.pass), moved(false), ty(other.ty) {
assert(!other.moved);
other.moved = true;
}
TempVar& operator=(TempVar&& rhs) {
assert(!rhs.moved);
// free overwritten idx
if (!moved) {
freeIdx();
}
idx = rhs.idx;
rhs.moved = true;
moved = false;
return *this;
}
~TempVar() {
if (!moved) {
freeIdx();
}
}
bool operator==(const TempVar& rhs) {
assert(!moved && !rhs.moved);
return idx == rhs.idx;
}
operator Index() {
assert(!moved);
return idx;
}
// disallow copying
TempVar(const TempVar&) = delete;
TempVar& operator=(const TempVar&) = delete;
private:
void freeIdx() {
auto& freeList = pass.freeTemps[ty.getBasic()];
assert(std::find(freeList.begin(), freeList.end(), idx) ==
freeList.end());
freeList.push_back(idx);
}
Index idx;
I64ToI32Lowering& pass;
bool moved; // since C++ will still destruct moved-from values
Type ty;
};
// false since function types need to be lowered
// TODO: allow module-level transformations in parallel passes
bool isFunctionParallel() override { return false; }
Pass* create() override { return new I64ToI32Lowering; }
void doWalkModule(Module* module) {
if (!builder) {
builder = make_unique<Builder>(*module);
}
// add new globals for high bits
for (size_t i = 0, globals = module->globals.size(); i < globals; ++i) {
auto* curr = module->globals[i].get();
if (curr->type != Type::i64) {
continue;
}
originallyI64Globals.insert(curr->name);
curr->type = Type::i32;
auto* high = builder->makeGlobal(makeHighName(curr->name),
Type::i32,
builder->makeConst(int32_t(0)),
Builder::Mutable);
module->addGlobal(high);
if (curr->imported()) {
Fatal() << "TODO: imported i64 globals";
} else {
if (auto* c = curr->init->dynCast<Const>()) {
uint64_t value = c->value.geti64();
c->value = Literal(uint32_t(value));
c->type = Type::i32;
high->init = builder->makeConst(uint32_t(value >> 32));
} else if (auto* get = curr->init->dynCast<GlobalGet>()) {
high->init =
builder->makeGlobalGet(makeHighName(get->name), Type::i32);
} else {
WASM_UNREACHABLE("unexpected expression type");
}
curr->init->type = Type::i32;
}
}
// For functions that return 64-bit values, we use this global variable
// to return the high 32 bits.
auto* highBits = new Global();
highBits->type = Type::i32;
highBits->name = INT64_TO_32_HIGH_BITS;
highBits->init = builder->makeConst(int32_t(0));
highBits->mutable_ = true;
module->addGlobal(highBits);
PostWalker<I64ToI32Lowering>::doWalkModule(module);
}
void doWalkFunction(Function* func) {
Flat::verifyFlatness(func);
// create builder here if this is first entry to module for this object
if (!builder) {
builder = make_unique<Builder>(*getModule());
}
indexMap.clear();
highBitVars.clear();
freeTemps.clear();
Module temp;
auto* oldFunc = ModuleUtils::copyFunction(func, temp);
func->sig.params = Type::none;
func->vars.clear();
func->localNames.clear();
func->localIndices.clear();
Index newIdx = 0;
Names::ensureNames(oldFunc);
for (Index i = 0; i < oldFunc->getNumLocals(); ++i) {
assert(oldFunc->hasLocalName(i));
Name lowName = oldFunc->getLocalName(i);
Name highName = makeHighName(lowName);
Type paramType = oldFunc->getLocalType(i);
auto builderFunc =
(i < oldFunc->getVarIndexBase())
? Builder::addParam
: static_cast<Index (*)(Function*, Name, Type)>(Builder::addVar);
if (paramType == Type::i64) {
builderFunc(func, lowName, Type::i32);
builderFunc(func, highName, Type::i32);
indexMap[i] = newIdx;
newIdx += 2;
} else {
builderFunc(func, lowName, paramType);
indexMap[i] = newIdx++;
}
}
nextTemp = func->getNumLocals();
PostWalker<I64ToI32Lowering>::doWalkFunction(func);
}
void visitFunction(Function* func) {
if (func->imported()) {
return;
}
if (func->sig.results == Type::i64) {
func->sig.results = Type::i32;
// body may not have out param if it ends with control flow
if (hasOutParam(func->body)) {
TempVar highBits = fetchOutParam(func->body);
TempVar lowBits = getTemp();
LocalSet* setLow = builder->makeLocalSet(lowBits, func->body);
GlobalSet* setHigh = builder->makeGlobalSet(
INT64_TO_32_HIGH_BITS, builder->makeLocalGet(highBits, Type::i32));
LocalGet* getLow = builder->makeLocalGet(lowBits, Type::i32);
func->body = builder->blockify(setLow, setHigh, getLow);
}
}
int idx = 0;
for (size_t i = func->getNumLocals(); i < nextTemp; i++) {
Name tmpName("i64toi32_i32$" + std::to_string(idx++));
builder->addVar(func, tmpName, tempTypes[i]);
}
}
template<typename T>
using BuilderFunc = std::function<T*(std::vector<Expression*>&, Type)>;
// Fixes up a call. If we performed fixups, returns the call; otherwise
// returns nullptr;
template<typename T>
T* visitGenericCall(T* curr, BuilderFunc<T> callBuilder) {
bool fixed = false;
std::vector<Expression*> args;
for (auto* e : curr->operands) {
args.push_back(e);
if (hasOutParam(e)) {
TempVar argHighBits = fetchOutParam(e);
args.push_back(builder->makeLocalGet(argHighBits, Type::i32));
fixed = true;
}
}
if (curr->type != Type::i64) {
auto* ret = callBuilder(args, curr->type);
replaceCurrent(ret);
return fixed ? ret : nullptr;
}
TempVar lowBits = getTemp();
TempVar highBits = getTemp();
auto* call = callBuilder(args, Type::i32);
LocalSet* doCall = builder->makeLocalSet(lowBits, call);
LocalSet* setHigh = builder->makeLocalSet(
highBits, builder->makeGlobalGet(INT64_TO_32_HIGH_BITS, Type::i32));
LocalGet* getLow = builder->makeLocalGet(lowBits, Type::i32);
Block* result = builder->blockify(doCall, setHigh, getLow);
setOutParam(result, std::move(highBits));
replaceCurrent(result);
return call;
}
void visitCall(Call* curr) {
if (curr->isReturn &&
getModule()->getFunction(curr->target)->sig.results == Type::i64) {
Fatal()
<< "i64 to i32 lowering of return_call values not yet implemented";
}
auto* fixedCall = visitGenericCall<Call>(
curr, [&](std::vector<Expression*>& args, Type results) {
return builder->makeCall(curr->target, args, results, curr->isReturn);
});
// If this was to an import, we need to call the legal version. This assumes
// that legalize-js-interface has been run before.
if (fixedCall && getModule()->getFunction(fixedCall->target)->imported()) {
fixedCall->target = std::string("legalfunc$") + fixedCall->target.str;
return;
}
}
void visitCallIndirect(CallIndirect* curr) {
if (curr->isReturn && curr->sig.results == Type::i64) {
Fatal()
<< "i64 to i32 lowering of return_call values not yet implemented";
}
visitGenericCall<CallIndirect>(
curr, [&](std::vector<Expression*>& args, Type results) {
std::vector<Type> params;
for (auto param : curr->sig.params.expand()) {
if (param == Type::i64) {
params.push_back(Type::i32);
params.push_back(Type::i32);
} else {
params.push_back(param);
}
}
return builder->makeCallIndirect(
curr->target, args, Signature(Type(params), results), curr->isReturn);
});
}
void visitLocalGet(LocalGet* curr) {
const auto mappedIndex = indexMap[curr->index];
// Need to remap the local into the new naming scheme, regardless of
// the type of the local.
curr->index = mappedIndex;
if (curr->type != Type::i64) {
return;
}
curr->type = Type::i32;
TempVar highBits = getTemp();
LocalSet* setHighBits = builder->makeLocalSet(
highBits, builder->makeLocalGet(mappedIndex + 1, Type::i32));
Block* result = builder->blockify(setHighBits, curr);
replaceCurrent(result);
setOutParam(result, std::move(highBits));
}
void lowerTee(LocalSet* curr) {
TempVar highBits = fetchOutParam(curr->value);
TempVar tmp = getTemp();
curr->type = Type::i32;
LocalSet* setLow = builder->makeLocalSet(tmp, curr);
LocalSet* setHigh = builder->makeLocalSet(
curr->index + 1, builder->makeLocalGet(highBits, Type::i32));
LocalGet* getLow = builder->makeLocalGet(tmp, Type::i32);
Block* result = builder->blockify(setLow, setHigh, getLow);
replaceCurrent(result);
setOutParam(result, std::move(highBits));
}
void visitLocalSet(LocalSet* curr) {
const auto mappedIndex = indexMap[curr->index];
// Need to remap the local into the new naming scheme, regardless of
// the type of the local. Note that lowerTee depends on this happening.
curr->index = mappedIndex;
if (!hasOutParam(curr->value)) {
return;
}
if (curr->isTee()) {
lowerTee(curr);
return;
}
TempVar highBits = fetchOutParam(curr->value);
auto* setHigh = builder->makeLocalSet(
mappedIndex + 1, builder->makeLocalGet(highBits, Type::i32));
Block* result = builder->blockify(curr, setHigh);
replaceCurrent(result);
}
void visitGlobalGet(GlobalGet* curr) {
if (!getFunction()) {
return; // if in a global init, skip - we already handled that.
}
if (!originallyI64Globals.count(curr->name)) {
return;
}
curr->type = Type::i32;
TempVar highBits = getTemp();
LocalSet* setHighBits = builder->makeLocalSet(
highBits, builder->makeGlobalGet(makeHighName(curr->name), Type::i32));
Block* result = builder->blockify(setHighBits, curr);
replaceCurrent(result);
setOutParam(result, std::move(highBits));
}
void visitGlobalSet(GlobalSet* curr) {
if (!originallyI64Globals.count(curr->name)) {
return;
}
if (handleUnreachable(curr)) {
return;
}
TempVar highBits = fetchOutParam(curr->value);
auto* setHigh = builder->makeGlobalSet(
makeHighName(curr->name), builder->makeLocalGet(highBits, Type::i32));
replaceCurrent(builder->makeSequence(curr, setHigh));
}
void visitLoad(Load* curr) {
if (curr->type != Type::i64) {
return;
}
assert(!curr->isAtomic && "64-bit atomic load not implemented");
TempVar lowBits = getTemp();
TempVar highBits = getTemp();
TempVar ptrTemp = getTemp();
LocalSet* setPtr = builder->makeLocalSet(ptrTemp, curr->ptr);
LocalSet* loadHigh;
if (curr->bytes == 8) {
loadHigh = builder->makeLocalSet(
highBits,
builder->makeLoad(4,
curr->signed_,
curr->offset + 4,
std::min(uint32_t(curr->align), uint32_t(4)),
builder->makeLocalGet(ptrTemp, Type::i32),
Type::i32));
} else if (curr->signed_) {
loadHigh = builder->makeLocalSet(
highBits,
builder->makeBinary(ShrSInt32,
builder->makeLocalGet(lowBits, Type::i32),
builder->makeConst(int32_t(31))));
} else {
loadHigh =
builder->makeLocalSet(highBits, builder->makeConst(int32_t(0)));
}
curr->type = Type::i32;
curr->bytes = std::min(curr->bytes, uint8_t(4));
curr->align = std::min(uint32_t(curr->align), uint32_t(4));
curr->ptr = builder->makeLocalGet(ptrTemp, Type::i32);
Block* result =
builder->blockify(setPtr,
builder->makeLocalSet(lowBits, curr),
loadHigh,
builder->makeLocalGet(lowBits, Type::i32));
replaceCurrent(result);
setOutParam(result, std::move(highBits));
}
void visitStore(Store* curr) {
if (!hasOutParam(curr->value)) {
return;
}
assert(curr->offset + 4 > curr->offset);
assert(!curr->isAtomic && "atomic store not implemented");
TempVar highBits = fetchOutParam(curr->value);
uint8_t bytes = curr->bytes;
curr->bytes = std::min(curr->bytes, uint8_t(4));
curr->align = std::min(uint32_t(curr->align), uint32_t(4));
curr->valueType = Type::i32;
if (bytes == 8) {
TempVar ptrTemp = getTemp();
LocalSet* setPtr = builder->makeLocalSet(ptrTemp, curr->ptr);
curr->ptr = builder->makeLocalGet(ptrTemp, Type::i32);
curr->finalize();
Store* storeHigh =
builder->makeStore(4,
curr->offset + 4,
std::min(uint32_t(curr->align), uint32_t(4)),
builder->makeLocalGet(ptrTemp, Type::i32),
builder->makeLocalGet(highBits, Type::i32),
Type::i32);
replaceCurrent(builder->blockify(setPtr, curr, storeHigh));
}
}
void visitAtomicRMW(AtomicRMW* curr) {
if (handleUnreachable(curr)) {
return;
}
if (curr->type != Type::i64) {
return;
}
// We cannot break this up into smaller operations as it must be atomic.
// Lower to an instrinsic function that wasm2js will implement.
TempVar lowBits = getTemp();
TempVar highBits = getTemp();
auto* getLow = builder->makeCall(
ABI::wasm2js::ATOMIC_RMW_I64,
{builder->makeConst(int32_t(curr->op)),
builder->makeConst(int32_t(curr->bytes)),
builder->makeConst(int32_t(curr->offset)),
curr->ptr,
curr->value,
builder->makeLocalGet(fetchOutParam(curr->value), Type::i32)},
Type::i32);
auto* getHigh =
builder->makeCall(ABI::wasm2js::GET_STASHED_BITS, {}, Type::i32);
auto* setLow = builder->makeLocalSet(lowBits, getLow);
auto* setHigh = builder->makeLocalSet(highBits, getHigh);
auto* finalGet = builder->makeLocalGet(lowBits, Type::i32);
auto* result = builder->makeBlock({setLow, setHigh, finalGet});
setOutParam(result, std::move(highBits));
replaceCurrent(result);
}
void visitAtomicCmpxchg(AtomicCmpxchg* curr) {
assert(curr->type != Type::i64 && "64-bit AtomicCmpxchg not implemented");
}
void visitAtomicWait(AtomicWait* curr) {
// The last parameter is an i64, so we cannot leave it as it is
assert(curr->offset == 0);
replaceCurrent(builder->makeCall(
ABI::wasm2js::ATOMIC_WAIT_I32,
{curr->ptr,
curr->expected,
curr->timeout,
builder->makeLocalGet(fetchOutParam(curr->timeout), Type::i32)},
Type::i32));
}
void visitConst(Const* curr) {
if (!getFunction()) {
return; // if in a global init, skip - we already handled that.
}
if (curr->type != Type::i64) {
return;
}
TempVar highBits = getTemp();
Const* lowVal =
builder->makeConst(int32_t(curr->value.geti64() & 0xffffffff));
LocalSet* setHigh = builder->makeLocalSet(
highBits,
builder->makeConst(int32_t(uint64_t(curr->value.geti64()) >> 32)));
Block* result = builder->blockify(setHigh, lowVal);
setOutParam(result, std::move(highBits));
replaceCurrent(result);
}
void lowerEqZInt64(Unary* curr) {
TempVar highBits = fetchOutParam(curr->value);
auto* result = builder->makeUnary(
EqZInt32,
builder->makeBinary(
OrInt32, curr->value, builder->makeLocalGet(highBits, Type::i32)));
replaceCurrent(result);
}
void lowerExtendUInt32(Unary* curr) {
TempVar highBits = getTemp();
Block* result = builder->blockify(
builder->makeLocalSet(highBits, builder->makeConst(int32_t(0))),
curr->value);
setOutParam(result, std::move(highBits));
replaceCurrent(result);
}
void lowerExtendSInt32(Unary* curr) {
TempVar highBits = getTemp();
TempVar lowBits = getTemp();
LocalSet* setLow = builder->makeLocalSet(lowBits, curr->value);
LocalSet* setHigh = builder->makeLocalSet(
highBits,
builder->makeBinary(ShrSInt32,
builder->makeLocalGet(lowBits, Type::i32),
builder->makeConst(int32_t(31))));
Block* result = builder->blockify(
setLow, setHigh, builder->makeLocalGet(lowBits, Type::i32));
setOutParam(result, std::move(highBits));
replaceCurrent(result);
}
void lowerWrapInt64(Unary* curr) {
// free the temp var
fetchOutParam(curr->value);
replaceCurrent(curr->value);
}
void lowerReinterpretFloat64(Unary* curr) {
// Assume that the wasm file assumes the address 0 is invalid and roundtrip
// our f64 through memory at address 0
TempVar highBits = getTemp();
Block* result = builder->blockify(
builder->makeCall(
ABI::wasm2js::SCRATCH_STORE_F64, {curr->value}, Type::none),
builder->makeLocalSet(highBits,
builder->makeCall(ABI::wasm2js::SCRATCH_LOAD_I32,
{builder->makeConst(int32_t(1))},
Type::i32)),
builder->makeCall(ABI::wasm2js::SCRATCH_LOAD_I32,
{builder->makeConst(int32_t(0))},
Type::i32));
setOutParam(result, std::move(highBits));
replaceCurrent(result);
MemoryUtils::ensureExists(getModule()->memory);
ABI::wasm2js::ensureHelpers(getModule());
}
void lowerReinterpretInt64(Unary* curr) {
// Assume that the wasm file assumes the address 0 is invalid and roundtrip
// our i64 through memory at address 0
TempVar highBits = fetchOutParam(curr->value);
Block* result = builder->blockify(
builder->makeCall(ABI::wasm2js::SCRATCH_STORE_I32,
{builder->makeConst(int32_t(0)), curr->value},
Type::none),
builder->makeCall(ABI::wasm2js::SCRATCH_STORE_I32,
{builder->makeConst(int32_t(1)),
builder->makeLocalGet(highBits, Type::i32)},
Type::none),
builder->makeCall(ABI::wasm2js::SCRATCH_LOAD_F64, {}, Type::f64));
replaceCurrent(result);
MemoryUtils::ensureExists(getModule()->memory);
ABI::wasm2js::ensureHelpers(getModule());
}
void lowerTruncFloatToInt(Unary* curr) {
// hiBits = if abs(f) >= 1.0 {
// if f > 0.0 {
// (unsigned) min(
// floor(f / (float) U32_MAX),
// (float) U32_MAX - 1,
// )
// } else {
// (unsigned) ceil((f - (float) (unsigned) f) / ((float) U32_MAX))
// }
// } else {
// 0
// }
//
// loBits = (unsigned) f;
Literal litZero, litOne, u32Max;
UnaryOp trunc, convert, abs, floor, ceil;
Type localType;
BinaryOp ge, gt, min, div, sub;
switch (curr->op) {
case TruncSFloat32ToInt64:
case TruncUFloat32ToInt64: {
litZero = Literal((float)0);
litOne = Literal((float)1);
u32Max = Literal(((float)UINT_MAX) + 1);
trunc = TruncUFloat32ToInt32;
convert = ConvertUInt32ToFloat32;
localType = Type::f32;
abs = AbsFloat32;
ge = GeFloat32;
gt = GtFloat32;
min = MinFloat32;
floor = FloorFloat32;
ceil = CeilFloat32;
div = DivFloat32;
sub = SubFloat32;
break;
}
case TruncSFloat64ToInt64:
case TruncUFloat64ToInt64: {
litZero = Literal((double)0);
litOne = Literal((double)1);
u32Max = Literal(((double)UINT_MAX) + 1);
trunc = TruncUFloat64ToInt32;
convert = ConvertUInt32ToFloat64;
localType = Type::f64;
abs = AbsFloat64;
ge = GeFloat64;
gt = GtFloat64;
min = MinFloat64;
floor = FloorFloat64;
ceil = CeilFloat64;
div = DivFloat64;
sub = SubFloat64;
break;
}
default:
abort();
}
TempVar f = getTemp(localType);
TempVar highBits = getTemp();
Expression* gtZeroBranch = builder->makeBinary(
min,
builder->makeUnary(
floor,
builder->makeBinary(div,
builder->makeLocalGet(f, localType),
builder->makeConst(u32Max))),
builder->makeBinary(
sub, builder->makeConst(u32Max), builder->makeConst(litOne)));
Expression* ltZeroBranch = builder->makeUnary(
ceil,
builder->makeBinary(
div,
builder->makeBinary(
sub,
builder->makeLocalGet(f, localType),
builder->makeUnary(
convert,
builder->makeUnary(trunc, builder->makeLocalGet(f, localType)))),
builder->makeConst(u32Max)));
If* highBitsCalc = builder->makeIf(
builder->makeBinary(
gt, builder->makeLocalGet(f, localType), builder->makeConst(litZero)),
builder->makeUnary(trunc, gtZeroBranch),
builder->makeUnary(trunc, ltZeroBranch));
If* highBitsVal = builder->makeIf(
builder->makeBinary(
ge,
builder->makeUnary(abs, builder->makeLocalGet(f, localType)),
builder->makeConst(litOne)),
highBitsCalc,
builder->makeConst(int32_t(0)));
Block* result = builder->blockify(
builder->makeLocalSet(f, curr->value),
builder->makeLocalSet(highBits, highBitsVal),
builder->makeUnary(trunc, builder->makeLocalGet(f, localType)));
setOutParam(result, std::move(highBits));
replaceCurrent(result);
}
void lowerConvertIntToFloat(Unary* curr) {
// Here the same strategy as `emcc` is taken which takes the two halves of
// the 64-bit integer and creates a mathematical expression using float
// arithmetic to reassemble the final floating point value.
//
// For example for i64 -> f32 we generate:
//
// ((double) (unsigned) lowBits) +
// ((double) U32_MAX) * ((double) (int) highBits)
//
// Mostly just shuffling things around here with coercions and whatnot!
// Note though that all arithmetic is done with f64 to have as much
// precision as we can.
//
// NB: this is *not* accurate for i64 -> f32. Using f64s for intermediate
// operations can give slightly inaccurate results in some cases, as we
// round to an f64, then round again to an f32, which is not always the
// same as a single rounding of i64 to f32 directly. Example:
//
// #include <stdio.h>
// int main() {
// unsigned long long x = 18446743523953737727ULL;
// float y = x;
// double z = x;
// float w = z;
// printf("i64 : %llu\n"
// "i64->f32 : %f\n"
// "i64->f64 : %f\n"
// "i64->f64->f32: %f\n", x, y, z, w);
// }
//
// i64 : 18446743523953737727
// i64->f32 : 18446742974197923840.000000 ;; correct rounding to f32
// i64->f64 : 18446743523953737728.000000 ;; correct rounding to f64
// i64->f64->f32: 18446744073709551616.000000 ;; incorrect rounding to f32
//
// This is even a problem if we use BigInts in JavaScript to represent
// i64s, as Math.fround(BigInt) is not supported - the BigInt must be
// converted to a Number first, so we again have that extra rounding.
//
// A more precise approach could use compiled floatdisf/floatundisf from
// compiler-rt, but that is much larger and slower. (Note that we are in the
// interesting situation of having f32 and f64 operations and only missing
// i64 ones, so we have a different problem to solve than compiler-rt, and
// maybe there is a better solution we haven't found yet.)
TempVar highBits = fetchOutParam(curr->value);
TempVar lowBits = getTemp();
TempVar highResult = getTemp();
UnaryOp convertHigh;
switch (curr->op) {
case ConvertSInt64ToFloat32:
case ConvertSInt64ToFloat64:
convertHigh = ConvertSInt32ToFloat64;
break;
case ConvertUInt64ToFloat32:
case ConvertUInt64ToFloat64:
convertHigh = ConvertUInt32ToFloat64;
break;
default:
abort();
}
Expression* result = builder->blockify(
builder->makeLocalSet(lowBits, curr->value),
builder->makeLocalSet(highResult, builder->makeConst(int32_t(0))),
builder->makeBinary(
AddFloat64,
builder->makeUnary(ConvertUInt32ToFloat64,
builder->makeLocalGet(lowBits, Type::i32)),
builder->makeBinary(
MulFloat64,
builder->makeConst((double)UINT_MAX + 1),
builder->makeUnary(convertHigh,
builder->makeLocalGet(highBits, Type::i32)))));
switch (curr->op) {
case ConvertSInt64ToFloat32:
case ConvertUInt64ToFloat32: {
result = builder->makeUnary(DemoteFloat64, result);
break;
}
default:
break;
}
replaceCurrent(result);
}
void lowerCountZeros(Unary* curr) {
auto lower = [&](Block* result,
UnaryOp op32,
TempVar&& first,
TempVar&& second) {
TempVar highResult = getTemp();
TempVar firstResult = getTemp();
LocalSet* setFirst = builder->makeLocalSet(
firstResult,
builder->makeUnary(op32, builder->makeLocalGet(first, Type::i32)));
Binary* check =
builder->makeBinary(EqInt32,
builder->makeLocalGet(firstResult, Type::i32),
builder->makeConst(int32_t(32)));
If* conditional = builder->makeIf(
check,
builder->makeBinary(
AddInt32,
builder->makeUnary(op32, builder->makeLocalGet(second, Type::i32)),
builder->makeConst(int32_t(32))),
builder->makeLocalGet(firstResult, Type::i32));
LocalSet* setHigh =
builder->makeLocalSet(highResult, builder->makeConst(int32_t(0)));
setOutParam(result, std::move(highResult));
replaceCurrent(builder->blockify(result, setFirst, setHigh, conditional));
};
TempVar highBits = fetchOutParam(curr->value);
TempVar lowBits = getTemp();
LocalSet* setLow = builder->makeLocalSet(lowBits, curr->value);
Block* result = builder->blockify(setLow);
switch (curr->op) {
case ClzInt64:
lower(result, ClzInt32, std::move(highBits), std::move(lowBits));
break;
case CtzInt64:
WASM_UNREACHABLE("i64.ctz should be removed already");
break;
default:
abort();
}
}
bool unaryNeedsLowering(UnaryOp op) {
switch (op) {
case ClzInt64:
case CtzInt64:
case PopcntInt64:
case EqZInt64:
case ExtendSInt32:
case ExtendUInt32:
case WrapInt64:
case TruncSFloat32ToInt64:
case TruncUFloat32ToInt64:
case TruncSFloat64ToInt64:
case TruncUFloat64ToInt64:
case ReinterpretFloat64:
case ConvertSInt64ToFloat32:
case ConvertSInt64ToFloat64:
case ConvertUInt64ToFloat32:
case ConvertUInt64ToFloat64:
case ReinterpretInt64:
return true;
default:
return false;
}
}
void visitUnary(Unary* curr) {
if (!unaryNeedsLowering(curr->op)) {
return;
}
if (handleUnreachable(curr)) {
return;
}
assert(hasOutParam(curr->value) || curr->type == Type::i64 ||
curr->type == Type::f64);
switch (curr->op) {
case ClzInt64:
case CtzInt64:
lowerCountZeros(curr);
break;
case EqZInt64:
lowerEqZInt64(curr);
break;
case ExtendSInt32:
lowerExtendSInt32(curr);
break;
case ExtendUInt32:
lowerExtendUInt32(curr);
break;
case WrapInt64:
lowerWrapInt64(curr);
break;
case ReinterpretFloat64:
lowerReinterpretFloat64(curr);
break;
case ReinterpretInt64:
lowerReinterpretInt64(curr);
break;
case TruncSFloat32ToInt64:
case TruncUFloat32ToInt64:
case TruncSFloat64ToInt64:
case TruncUFloat64ToInt64:
lowerTruncFloatToInt(curr);
break;
case ConvertSInt64ToFloat32:
case ConvertSInt64ToFloat64:
case ConvertUInt64ToFloat32:
case ConvertUInt64ToFloat64:
lowerConvertIntToFloat(curr);
break;
case PopcntInt64:
WASM_UNREACHABLE("i64.popcnt should already be removed");
default:
std::cerr << "Unhandled unary operator: " << curr->op << std::endl;
abort();
}
}
Block* lowerAdd(Block* result,
TempVar&& leftLow,
TempVar&& leftHigh,
TempVar&& rightLow,
TempVar&& rightHigh) {
TempVar lowResult = getTemp();
TempVar highResult = getTemp();
LocalSet* addLow = builder->makeLocalSet(
lowResult,
builder->makeBinary(AddInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(rightLow, Type::i32)));
LocalSet* addHigh = builder->makeLocalSet(
highResult,
builder->makeBinary(AddInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32)));
LocalSet* carryBit = builder->makeLocalSet(
highResult,
builder->makeBinary(AddInt32,
builder->makeLocalGet(highResult, Type::i32),
builder->makeConst(int32_t(1))));
If* checkOverflow = builder->makeIf(
builder->makeBinary(LtUInt32,
builder->makeLocalGet(lowResult, Type::i32),
builder->makeLocalGet(rightLow, Type::i32)),
carryBit);
LocalGet* getLow = builder->makeLocalGet(lowResult, Type::i32);
result = builder->blockify(result, addLow, addHigh, checkOverflow, getLow);
setOutParam(result, std::move(highResult));
return result;
}
Block* lowerSub(Block* result,
TempVar&& leftLow,
TempVar&& leftHigh,
TempVar&& rightLow,
TempVar&& rightHigh) {
TempVar lowResult = getTemp();
TempVar highResult = getTemp();
TempVar borrow = getTemp();
LocalSet* subLow = builder->makeLocalSet(
lowResult,
builder->makeBinary(SubInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(rightLow, Type::i32)));
LocalSet* borrowBit = builder->makeLocalSet(
borrow,
builder->makeBinary(LtUInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(rightLow, Type::i32)));
LocalSet* subHigh1 = builder->makeLocalSet(
highResult,
builder->makeBinary(AddInt32,
builder->makeLocalGet(borrow, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32)));
LocalSet* subHigh2 = builder->makeLocalSet(
highResult,
builder->makeBinary(SubInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(highResult, Type::i32)));
LocalGet* getLow = builder->makeLocalGet(lowResult, Type::i32);
result =
builder->blockify(result, subLow, borrowBit, subHigh1, subHigh2, getLow);
setOutParam(result, std::move(highResult));
return result;
}
Block* lowerBitwise(BinaryOp op,
Block* result,
TempVar&& leftLow,
TempVar&& leftHigh,
TempVar&& rightLow,
TempVar&& rightHigh) {
BinaryOp op32;
switch (op) {
case AndInt64:
op32 = AndInt32;
break;
case OrInt64:
op32 = OrInt32;
break;
case XorInt64:
op32 = XorInt32;
break;
default:
abort();
}
result = builder->blockify(
result,
builder->makeLocalSet(
rightHigh,
builder->makeBinary(op32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32))),
builder->makeBinary(op32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(rightLow, Type::i32)));
setOutParam(result, std::move(rightHigh));
return result;
}
Block* makeLargeShl(Index highBits, Index leftLow, Index shift) {
return builder->blockify(
builder->makeLocalSet(
highBits,
builder->makeBinary(ShlInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(shift, Type::i32))),
builder->makeConst(int32_t(0)));
}
// a >> b where `b` >= 32
//
// implement as:
//
// hi = leftHigh >> 31 // copy sign bit
// lo = leftHigh >> (b - 32)
Block* makeLargeShrS(Index highBits, Index leftHigh, Index shift) {
return builder->blockify(
builder->makeLocalSet(
highBits,
builder->makeBinary(ShrSInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeConst(int32_t(31)))),
builder->makeBinary(ShrSInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(shift, Type::i32)));
}
Block* makeLargeShrU(Index highBits, Index leftHigh, Index shift) {
return builder->blockify(
builder->makeLocalSet(highBits, builder->makeConst(int32_t(0))),
builder->makeBinary(ShrUInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(shift, Type::i32)));
}
Block* makeSmallShl(Index highBits,
Index leftLow,
Index leftHigh,
Index shift,
Binary* shiftMask,
Binary* widthLessShift) {
Binary* shiftedInBits = builder->makeBinary(
AndInt32,
shiftMask,
builder->makeBinary(
ShrUInt32, builder->makeLocalGet(leftLow, Type::i32), widthLessShift));
Binary* shiftHigh =
builder->makeBinary(ShlInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(shift, Type::i32));
return builder->blockify(
builder->makeLocalSet(
highBits, builder->makeBinary(OrInt32, shiftedInBits, shiftHigh)),
builder->makeBinary(ShlInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(shift, Type::i32)));
}
// a >> b where `b` < 32
//
// implement as:
//
// hi = leftHigh >> b
// lo = (leftLow >>> b) | (leftHigh << (32 - b))
Block* makeSmallShrS(Index highBits,
Index leftLow,
Index leftHigh,
Index shift,
Binary* shiftMask,
Binary* widthLessShift) {
Binary* shiftedInBits = builder->makeBinary(
ShlInt32,
builder->makeBinary(
AndInt32, shiftMask, builder->makeLocalGet(leftHigh, Type::i32)),
widthLessShift);
Binary* shiftLow =
builder->makeBinary(ShrUInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(shift, Type::i32));
return builder->blockify(
builder->makeLocalSet(
highBits,
builder->makeBinary(ShrSInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(shift, Type::i32))),
builder->makeBinary(OrInt32, shiftedInBits, shiftLow));
}
Block* makeSmallShrU(Index highBits,
Index leftLow,
Index leftHigh,
Index shift,
Binary* shiftMask,
Binary* widthLessShift) {
Binary* shiftedInBits = builder->makeBinary(
ShlInt32,
builder->makeBinary(
AndInt32, shiftMask, builder->makeLocalGet(leftHigh, Type::i32)),
widthLessShift);
Binary* shiftLow =
builder->makeBinary(ShrUInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(shift, Type::i32));
return builder->blockify(
builder->makeLocalSet(
highBits,
builder->makeBinary(ShrUInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(shift, Type::i32))),
builder->makeBinary(OrInt32, shiftedInBits, shiftLow));
}
Block* lowerShift(BinaryOp op,
Block* result,
TempVar&& leftLow,
TempVar&& leftHigh,
TempVar&& rightLow,
TempVar&& rightHigh) {
assert(op == ShlInt64 || op == ShrUInt64 || op == ShrSInt64);
// shift left lowered as:
// if 32 <= rightLow % 64:
// high = leftLow << k; low = 0
// else:
// high = (((1 << k) - 1) & (leftLow >> (32 - k))) | (leftHigh << k);
// low = leftLow << k
// where k = shift % 32. shift right is similar.
TempVar shift = getTemp();
LocalSet* setShift = builder->makeLocalSet(
shift,
builder->makeBinary(AndInt32,
builder->makeLocalGet(rightLow, Type::i32),
builder->makeConst(int32_t(32 - 1))));
Binary* isLargeShift = builder->makeBinary(
LeUInt32,
builder->makeConst(int32_t(32)),
builder->makeBinary(AndInt32,
builder->makeLocalGet(rightLow, Type::i32),
builder->makeConst(int32_t(64 - 1))));
Block* largeShiftBlock;
switch (op) {
case ShlInt64:
largeShiftBlock = makeLargeShl(rightHigh, leftLow, shift);
break;
case ShrSInt64:
largeShiftBlock = makeLargeShrS(rightHigh, leftHigh, shift);
break;
case ShrUInt64:
largeShiftBlock = makeLargeShrU(rightHigh, leftHigh, shift);
break;
default:
abort();
}
Binary* shiftMask = builder->makeBinary(
SubInt32,
builder->makeBinary(ShlInt32,
builder->makeConst(int32_t(1)),
builder->makeLocalGet(shift, Type::i32)),
builder->makeConst(int32_t(1)));
Binary* widthLessShift =
builder->makeBinary(SubInt32,
builder->makeConst(int32_t(32)),
builder->makeLocalGet(shift, Type::i32));
Block* smallShiftBlock;
switch (op) {
case ShlInt64: {
smallShiftBlock = makeSmallShl(
rightHigh, leftLow, leftHigh, shift, shiftMask, widthLessShift);
break;
}
case ShrSInt64: {
smallShiftBlock = makeSmallShrS(
rightHigh, leftLow, leftHigh, shift, shiftMask, widthLessShift);
break;
}
case ShrUInt64: {
smallShiftBlock = makeSmallShrU(
rightHigh, leftLow, leftHigh, shift, shiftMask, widthLessShift);
break;
}
default:
abort();
}
If* ifLargeShift =
builder->makeIf(isLargeShift, largeShiftBlock, smallShiftBlock);
result = builder->blockify(result, setShift, ifLargeShift);
setOutParam(result, std::move(rightHigh));
return result;
}
Block* lowerEq(Block* result,
TempVar&& leftLow,
TempVar&& leftHigh,
TempVar&& rightLow,
TempVar&& rightHigh) {
return builder->blockify(
result,
builder->makeBinary(
AndInt32,
builder->makeBinary(EqInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(rightLow, Type::i32)),
builder->makeBinary(EqInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32))));
}
Block* lowerNe(Block* result,
TempVar&& leftLow,
TempVar&& leftHigh,
TempVar&& rightLow,
TempVar&& rightHigh) {
return builder->blockify(
result,
builder->makeBinary(
OrInt32,
builder->makeBinary(NeInt32,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(rightLow, Type::i32)),
builder->makeBinary(NeInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32))));
}
Block* lowerUComp(BinaryOp op,
Block* result,
TempVar&& leftLow,
TempVar&& leftHigh,
TempVar&& rightLow,
TempVar&& rightHigh) {
BinaryOp highOp, lowOp;
switch (op) {
case LtUInt64:
highOp = LtUInt32;
lowOp = LtUInt32;
break;
case LeUInt64:
highOp = LtUInt32;
lowOp = LeUInt32;
break;
case GtUInt64:
highOp = GtUInt32;
lowOp = GtUInt32;
break;
case GeUInt64:
highOp = GtUInt32;
lowOp = GeUInt32;
break;
default:
abort();
}
Binary* compHigh =
builder->makeBinary(highOp,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32));
Binary* eqHigh =
builder->makeBinary(EqInt32,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32));
Binary* compLow =
builder->makeBinary(lowOp,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(rightLow, Type::i32));
return builder->blockify(
result,
builder->makeBinary(
OrInt32, compHigh, builder->makeBinary(AndInt32, eqHigh, compLow)));
}
Block* lowerSComp(BinaryOp op,
Block* result,
TempVar&& leftLow,
TempVar&& leftHigh,
TempVar&& rightLow,
TempVar&& rightHigh) {
BinaryOp highOp1, highOp2, lowOp;
switch (op) {
case LtSInt64:
highOp1 = LtSInt32;
highOp2 = LeSInt32;
lowOp = GeUInt32;
break;
case LeSInt64:
highOp1 = LtSInt32;
highOp2 = LeSInt32;
lowOp = GtUInt32;
break;
case GtSInt64:
highOp1 = GtSInt32;
highOp2 = GeSInt32;
lowOp = LeUInt32;
break;
case GeSInt64:
highOp1 = GtSInt32;
highOp2 = GeSInt32;
lowOp = LtUInt32;
break;
default:
abort();
}
Binary* compHigh1 =
builder->makeBinary(highOp1,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32));
Binary* compHigh2 =
builder->makeBinary(highOp2,
builder->makeLocalGet(leftHigh, Type::i32),
builder->makeLocalGet(rightHigh, Type::i32));
Binary* compLow =
builder->makeBinary(lowOp,
builder->makeLocalGet(leftLow, Type::i32),
builder->makeLocalGet(rightLow, Type::i32));
If* lowIf = builder->makeIf(
compLow, builder->makeConst(int32_t(0)), builder->makeConst(int32_t(1)));
If* highIf2 =
builder->makeIf(compHigh2, lowIf, builder->makeConst(int32_t(0)));
If* highIf1 =
builder->makeIf(compHigh1, builder->makeConst(int32_t(1)), highIf2);
return builder->blockify(result, highIf1);
}
bool binaryNeedsLowering(BinaryOp op) {
switch (op) {
case AddInt64:
case SubInt64:
case MulInt64:
case DivSInt64:
case DivUInt64:
case RemSInt64:
case RemUInt64:
case AndInt64:
case OrInt64:
case XorInt64:
case ShlInt64:
case ShrUInt64:
case ShrSInt64:
case RotLInt64:
case RotRInt64:
case EqInt64:
case NeInt64:
case LtSInt64:
case LtUInt64:
case LeSInt64:
case LeUInt64:
case GtSInt64:
case GtUInt64:
case GeSInt64:
case GeUInt64:
return true;
default:
return false;
}
}
void visitBinary(Binary* curr) {
if (handleUnreachable(curr)) {
return;
}
if (!binaryNeedsLowering(curr->op)) {
return;
}
// left and right reachable, lower normally
TempVar leftLow = getTemp();
TempVar leftHigh = fetchOutParam(curr->left);
TempVar rightLow = getTemp();
TempVar rightHigh = fetchOutParam(curr->right);
LocalSet* setRight = builder->makeLocalSet(rightLow, curr->right);
LocalSet* setLeft = builder->makeLocalSet(leftLow, curr->left);
Block* result = builder->blockify(setLeft, setRight);
switch (curr->op) {
case AddInt64: {
replaceCurrent(lowerAdd(result,
std::move(leftLow),
std::move(leftHigh),
std::move(rightLow),
std::move(rightHigh)));
break;
}
case SubInt64: {
replaceCurrent(lowerSub(result,
std::move(leftLow),
std::move(leftHigh),
std::move(rightLow),
std::move(rightHigh)));
break;
}
case MulInt64:
case DivSInt64:
case DivUInt64:
case RemSInt64:
case RemUInt64:
case RotLInt64:
case RotRInt64:
WASM_UNREACHABLE("should have been removed by now");
case AndInt64:
case OrInt64:
case XorInt64: {
replaceCurrent(lowerBitwise(curr->op,
result,
std::move(leftLow),
std::move(leftHigh),
std::move(rightLow),
std::move(rightHigh)));
break;
}
case ShlInt64:
case ShrSInt64:
case ShrUInt64: {
replaceCurrent(lowerShift(curr->op,
result,
std::move(leftLow),
std::move(leftHigh),
std::move(rightLow),
std::move(rightHigh)));
break;
}
case EqInt64: {
replaceCurrent(lowerEq(result,
std::move(leftLow),
std::move(leftHigh),
std::move(rightLow),
std::move(rightHigh)));
break;
}
case NeInt64: {
replaceCurrent(lowerNe(result,
std::move(leftLow),
std::move(leftHigh),
std::move(rightLow),
std::move(rightHigh)));
break;
}
case LtSInt64:
case LeSInt64:
case GtSInt64:
case GeSInt64:
replaceCurrent(lowerSComp(curr->op,
result,
std::move(leftLow),
std::move(leftHigh),
std::move(rightLow),
std::move(rightHigh)));
break;
case LtUInt64:
case LeUInt64:
case GtUInt64:
case GeUInt64: {
replaceCurrent(lowerUComp(curr->op,
result,
std::move(leftLow),
std::move(leftHigh),
std::move(rightLow),
std::move(rightHigh)));
break;
}
default: {
std::cerr << "Unhandled binary op " << curr->op << std::endl;
abort();
}
}
}
void visitSelect(Select* curr) {
if (handleUnreachable(curr)) {
return;
}
if (!hasOutParam(curr->ifTrue)) {
assert(!hasOutParam(curr->ifFalse));
return;
}
assert(hasOutParam(curr->ifFalse));
TempVar highBits = getTemp();
TempVar lowBits = getTemp();
TempVar cond = getTemp();
Block* result = builder->blockify(
builder->makeLocalSet(cond, curr->condition),
builder->makeLocalSet(
lowBits,
builder->makeSelect(
builder->makeLocalGet(cond, Type::i32), curr->ifTrue, curr->ifFalse)),
builder->makeLocalSet(
highBits,
builder->makeSelect(
builder->makeLocalGet(cond, Type::i32),
builder->makeLocalGet(fetchOutParam(curr->ifTrue), Type::i32),
builder->makeLocalGet(fetchOutParam(curr->ifFalse), Type::i32))),
builder->makeLocalGet(lowBits, Type::i32));
setOutParam(result, std::move(highBits));
replaceCurrent(result);
}
void visitDrop(Drop* curr) {
if (!hasOutParam(curr->value)) {
return;
}
// free temp var
fetchOutParam(curr->value);
}
void visitReturn(Return* curr) {
if (!hasOutParam(curr->value)) {
return;
}
TempVar lowBits = getTemp();
TempVar highBits = fetchOutParam(curr->value);
LocalSet* setLow = builder->makeLocalSet(lowBits, curr->value);
GlobalSet* setHigh = builder->makeGlobalSet(
INT64_TO_32_HIGH_BITS, builder->makeLocalGet(highBits, Type::i32));
curr->value = builder->makeLocalGet(lowBits, Type::i32);
Block* result = builder->blockify(setLow, setHigh, curr);
replaceCurrent(result);
}
private:
std::unique_ptr<Builder> builder;
std::unordered_map<Index, Index> indexMap;
std::unordered_map<int, std::vector<Index>> freeTemps;
std::unordered_map<Expression*, TempVar> highBitVars;
std::unordered_map<Index, Type> tempTypes;
std::unordered_set<Name> originallyI64Globals;
Index nextTemp;
TempVar getTemp(Type ty = Type::i32) {
Index ret;
auto& freeList = freeTemps[ty.getBasic()];
if (freeList.size() > 0) {
ret = freeList.back();
freeList.pop_back();
} else {
ret = nextTemp++;
tempTypes[ret] = ty;
}
assert(tempTypes[ret] == ty);
return TempVar(ret, ty, *this);
}
bool hasOutParam(Expression* e) {
return highBitVars.find(e) != highBitVars.end();
}
void setOutParam(Expression* e, TempVar&& var) {
highBitVars.emplace(e, std::move(var));
}
TempVar fetchOutParam(Expression* e) {
auto outParamIt = highBitVars.find(e);
assert(outParamIt != highBitVars.end());
TempVar ret = std::move(outParamIt->second);
highBitVars.erase(e);
return ret;
}
// If e.g. a select is unreachable, then one arm may have an out param
// but not the other. In this case dce should really have been run
// before; handle it in a simple way here by replacing the node with
// a block of its children.
// This is valid only for nodes that execute their children
// unconditionally before themselves, so it is not valid for an if,
// in particular.
bool handleUnreachable(Expression* curr) {
if (curr->type != Type::unreachable) {
return false;
}
std::vector<Expression*> children;
bool hasUnreachable = false;
for (auto* child : ChildIterator(curr)) {
if (child->type.isConcrete()) {
child = builder->makeDrop(child);
} else if (child->type == Type::unreachable) {
hasUnreachable = true;
}
children.push_back(child);
}
if (!hasUnreachable) {
return false;
}
// This has an unreachable child, so we can replace it with
// the children.
auto* block = builder->makeBlock(children);
assert(block->type == Type::unreachable);
replaceCurrent(block);
return true;
}
};
Pass* createI64ToI32LoweringPass() { return new I64ToI32Lowering(); }
} // namespace wasm
|
require 'optparse'
require 'tempfile'
module VagrantPlugins
module RDP
class Command < Vagrant.plugin(2, :command)
def execute
opts = OptionParser.new do |opts|
opts.banner = "Usage: vagrant rdp [vm-name...]"
opts.separator ""
end
argv = parse_options(opts)
return -1 if !argv
with_target_vms(argv) do |vm|
@logger.info("Launching remote desktop session to: #{vm.name}")
rdp_connect(vm)
end
return 0
end
def rdp_connect(vm)
rdpport = nil
vm.provider.driver.read_forwarded_ports.each do |_, _, hostport, guestport|
rdpport = hostport if guestport == 3389
end
Tempfile.open('vagrant-rdp-shell-') do |tf|
rdp_file = rdp_file(vm, rdpport)
tf.puts <<EOS
open -a "/Applications/Microsoft Remote Desktop.app/Contents/MacOS/Microsoft Remote Desktop" "#{rdp_file}"
sleep 5 #HACK
rm "#{rdp_file}"
EOS
tf.close
# Spawn remote desktop and detach it so we can move on.
pid = spawn("/bin/bash", tf.path)
Process.detach(pid)
end
end
def rdp_file(vm, rdpport)
path = nil
Tempfile.open([ "vagrant-rdp-", ".rdp" ], vm.data_dir) { |fp|
path = fp.path
fp.unlink
}
File.open(path, "w") { |io|
io.puts <<EOF
screen mode id:i:0
desktopwidth:i:#{vm.config.rdp.width}
desktopheight:i:#{vm.config.rdp.height}
use multimon:i:1
session bpp:i:32
full address:s:localhost:#{rdpport}
audiomode:i:0
disable wallpaper:i:0
disable full window drag:i:0
disable menu anims:i:0
disable themes:i:0
alternate shell:s:
shell working directory:s:
authentication level:i:2
connect to console:i:0
gatewayusagemethod:i:0
disable cursor setting:i:0
allow font smoothing:i:1
allow desktop composition:i:1
bookmarktype:i:3
use redirection server name:i:0
EOF
}
path
end
end
end
end
|
from common import *
from sklearn import metrics as sklearn_metrics
##################################################################################################3
def remove_small_one(predict, min_size):
H,W = predict.shape
num_component, component = cv2.connectedComponents(predict.astype(np.uint8))
predict = np.zeros((H,W), np.bool)
for c in range(1,num_component):
p = (component==c)
if p.sum()>min_size:
predict[p] = True
return predict
def remove_small(predict, min_size):
for b in range(len(predict)):
for c in range(4):
predict[b,c] = remove_small_one(predict[b,c], min_size[c])
return predict
##################################################################################################3
def compute_eer(fpr,tpr,threshold):
""" Returns equal error rate (EER) and the corresponding threshold. """
fnr = 1-tpr
abs_diff = np.abs(fpr-fnr)
min_index = np.argmin(abs_diff)
eer = np.mean((fpr[min_index], fnr[min_index]))
return eer, threshold[min_index]
def compute_metric_label(truth_label, predict_label):
t = truth_label.reshape(-1,4)
p = predict_label.reshape(-1,4)
# num_truth, num_predict, correct, recall, precision
# (all) neg
# (all) pos
# neg1
# pos1
# ...
ts = np.array([
[1-t.reshape(-1),t.reshape(-1)],
[1-t[:,0],t[:,0]],
[1-t[:,1],t[:,1]],
[1-t[:,2],t[:,2]],
[1-t[:,3],t[:,3]],
]).reshape(-1)
ps = np.array([
[1-p.reshape(-1),p.reshape(-1)],
[1-p[:,0],p[:,0]],
[1-p[:,1],p[:,1]],
[1-p[:,2],p[:,2]],
[1-p[:,3],p[:,3]],
]).reshape(-1)
result = []
for tt,pp in zip(ts, ps):
num_truth = tt.sum()
num_predict = pp.sum()
num_correct = (tt*pp).sum()
recall = num_correct/num_truth
precision = num_correct/num_predict
result.append([num_truth, num_predict, num_correct, recall, precision])
## from kaggle probing ...
kaggle_pos = np.array([ 128,43,741,120 ])
kaggle_neg_all = 6172
kaggle_all = 1801*4
recall_neg_all = result[0][3]
recall_pos = np.array([
result[3][3],
result[5][3],
result[7][3],
result[9][3],
])
kaggle = []
for dice_pos in [1.00, 0.75, 0.50]:
k = (recall_neg_all*kaggle_neg_all + sum(dice_pos*recall_pos*kaggle_pos))/kaggle_all
kaggle.append([k,dice_pos])
return kaggle, result
def print_metric_label(kaggle, result):
text = ''
text += '* image level metric *\n'
text += ' num_truth, num_predict, num_correct, recall, precision\n'
text += ' (all) neg %4d %4d %4d %0.2f %0.2f \n'%(*result[0],)
text += ' (all) pos %4d %4d %4d %0.2f %0.2f \n'%(*result[1],)
text += '\n'
text += ' neg1 %4d %4d %4d %0.2f %0.2f \n'%(*result[2],)
text += ' pos1 %4d %4d %4d %0.2f %0.2f \n'%(*result[3],)
text += '\n'
text += ' neg2 %4d %4d %4d %0.2f %0.2f \n'%(*result[4],)
text += ' pos2 %4d %4d %4d %0.2f %0.2f \n'%(*result[5],)
text += '\n'
text += ' neg3 %4d %4d %4d %0.2f %0.2f \n'%(*result[6],)
text += ' pos3 %4d %4d %4d %0.2f %0.2f \n'%(*result[7],)
text += '\n'
text += ' neg4 %4d %4d %4d %0.2f %0.2f \n'%(*result[8],)
text += ' pos4 %4d %4d %4d %0.2f %0.2f \n'%(*result[9],)
text += '\n'
text += 'kaggle = %0.5f @ dice%0.3f\n'%(kaggle[0][0],kaggle[0][1])
text += ' = %0.5f @ dice%0.3f\n'%(kaggle[1][0],kaggle[1][1])
text += ' = %0.5f @ dice%0.3f\n'%(kaggle[2][0],kaggle[2][1])
text += '\n'
return text
def compute_roc_label(truth_label, probability_label):
t = truth_label.reshape(-1,4)
p = probability_label.reshape(-1,4)
auc=[]
result=[]
for c in [0,1,2,3]:
a = sklearn_metrics.roc_auc_score(t[:,c], p[:,c])
auc.append(a)
fpr, tpr, threshold = sklearn_metrics.roc_curve(t[:,c], p[:,c])
result.append([fpr, tpr, threshold])
return auc, result
def print_roc_label(auc, result):
text = ''
text += '%s\n'%(str(auc))
text +='\n'
for c,(fpr, tpr, threshold) in enumerate(result):
text += 'class%d\n'%(c+1)
text += 'bin\tfpr\ttpr\n'
for f,t,b in zip(fpr, tpr, threshold):
text += '%0.3f\t%0.3f\t%0.3f\n'%(b,f,t)
text +='\n'
return text
#---
##################################################################################################3
|
/*
* Copyright 2019 Intershop Communications AG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.intershop.gradle.icm.project
import org.gradle.api.file.Directory
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RegularFile
import org.gradle.api.provider.Provider
/**
* An enumeration of target directories and files of special
* environment typs - production, test and local server.
*/
enum class TargetConf(val value: String) {
PRODUCTION("production") {
override fun cartridges(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("container/cartridges")
override fun libs(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("container/prjlibs")
override fun config(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("container/config_folder")
override fun cartridgelist(projectLayout: ProjectLayout): Provider<RegularFile> =
projectLayout.buildDirectory.file("container/cartridgelist/cartridgelist.properties")
},
TEST("test") {
override fun cartridges(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("testcontainer/cartridges")
override fun libs(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("testcontainer/prjlibs")
override fun config(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("testcontainer/config_folder")
override fun cartridgelist(projectLayout: ProjectLayout): Provider<RegularFile> =
projectLayout.buildDirectory.file("testcontainer/cartridgelist/cartridgelist.properties")
},
DEVELOPMENT("server") {
override fun cartridges(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("server/cartridges")
override fun libs(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("server/prjlibs")
override fun config(projectLayout: ProjectLayout): Provider<Directory> =
projectLayout.buildDirectory.dir("server/config_folder")
override fun cartridgelist(projectLayout: ProjectLayout): Provider<RegularFile> =
projectLayout.buildDirectory.file("server/cartridgelist/cartridgelist.properties")
};
/**
* Returns the the provider of a directory
* for external cartridgs.
*
* @return Provider<Directory>
*/
abstract fun cartridges(projectLayout: ProjectLayout): Provider<Directory>
/**
* Returns the the provider of a directory
* for external project libraries.
*
* @return Provider<Directory>
*/
abstract fun libs(projectLayout: ProjectLayout): Provider<Directory>
/**
* Returns the the provider of a directory
* for config folders.
*
* @return Provider<Directory>
*/
abstract fun config(projectLayout: ProjectLayout): Provider<Directory>
/**
* Returns the the provider of a cartridge list file.
*
* @return Provider<RegularFile>
*/
abstract fun cartridgelist(projectLayout: ProjectLayout): Provider<RegularFile>
}
|
'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const changeCase = require('change-case');
module.exports = class extends Generator {
prompting() {
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the prime ' + chalk.red('generator-polymer-init-firebase-auth-roles') + ' generator!'
));
const prompts = [
{
name: 'appName',
type: 'input',
message: 'Name of the application',
default: this.appname
},
{
name: 'appDescription',
type: 'input',
message: 'Brief description of the application',
default: 'Brief description of the application'
},
{
name: 'firebaseApiKey',
type: 'input',
message: 'Firebase Api Key',
default: '~~firebaseApiKey~'
},
{
name: 'firebaseProjectId',
type: 'input',
message: 'Firebase Project Id',
default: '~~firebaseProjectId~'
},
{
name: 'firebaseMessagingSenderId',
type: 'input',
message: 'Firebase Messaging Sender Id',
default: '~~firebaseMessagingSenderId~'
}
];
return this.prompt(prompts).then(props => {
props.appNameDash = changeCase.paramCase(props.appName);
props.appNameCamel = changeCase.pascalCase(props.appName);
// To access props later use this.props.appName;
this.props = props;
});
}
writing() {
this.fs.copy(
this.templatePath('functions/*'),
this.destinationPath('functions/')
);
this.fs.copy(
this.templatePath('images/**/*'),
this.destinationPath('images/')
);
this.fs.copyTpl(
this.templatePath('src/_appShell.html'),
this.destinationPath(`src/${this.props.appNameDash}.html`),
this.props
);
this.fs.copyTpl(
this.templatePath('src') + '/!(_)*',
this.destinationPath('src/'),
this.props
);
this.fs.copyTpl(
this.templatePath('test/*'),
this.destinationPath('test/'),
this.props
);
this.fs.copy(
this.templatePath('test/.eslintrc.json'),
this.destinationPath('test/.eslintrc.json')
);
this.fs.copy(
this.templatePath('_gitignore'),
this.destinationPath('.gitignore')
);
this.fs.copyTpl(
this.templatePath('_firebase'),
this.destinationPath('.firebase'),
this.props
);
this.fs.copyTpl(
this.templatePath() + '/!(_)*',
this.destinationPath(),
this.props
);
}
install() {
this.installDependencies();
this.spawnCommand('npm', ['install'], {cwd: 'functions'});
}
};
|
<?php
return [
'clockify_api' => [
'base_url' => env('CLOCKIFY_API_BASE_URL'),
'reports_url' => env('CLOCKIFY_API_REPORTS_URL'),
'key' => env('CLOCKIFY_API_KEY'),
'workspace_id' => env('CLOCKIFY_API_WORKSPACE_ID'),
]
];
|
/*
* Copyright 2020 Alexi Bre
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.alexib.plaid.client.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Information about the APR on the account.
* @param aprPercentage Annual Percentage Rate applied.
*
* @param aprType The type of balance to which the APR applies.
* @param balanceSubjectToApr Amount of money that is subjected to the APR if a balance was carried
* beyond payment due date. How it is calculated can vary by card issuer. It is often calculated as an
* average daily balance.
* @param interestChargeAmount Amount of money charged due to interest from last statement.
*/
@Serializable
data class APR(
@SerialName("apr_percentage")
val aprPercentage: Double,
@SerialName("apr_type")
val aprType: AprType,
@SerialName("balance_subject_to_apr")
val balanceSubjectToApr: Double? = null,
@SerialName("interest_charge_amount")
val interestChargeAmount: Double? = null
) {
@Serializable
enum class AprType {
@SerialName("balance_transfer_apr")
BALANCE_TRANSFER_APR,
@SerialName("cash_apr")
CASH_APR,
@SerialName("purchase_apr")
PURCHASE_APR,
@SerialName("special")
SPECIAL
}
}
|
Event.create(distance: 100, date: "05/31/19", swimmer_id: 1)
Event.create(distance: 500, date: "01/31/19", swimmer_id: 2)
Swimmer.create(name: "Monica Jones", member_number: 123456, password: "monica")
Swimmer.create(name: "Harry Potter", member_number: 987654, password: "magic")
|
module Bestsign
module Helper
module Signature
def hexdigest(data)
private_key = File.read(configurate.private_path)
rsa = OpenSSL::PKey::RSA.new private_key
sign = rsa.sign('SHA1', data)
Base64.encode64(sign)
end
def verify?(data, signature)
public_key = File.read(configurate.public_path)
rsa = OpenSSL::PKey::RSA.new public_key
rsa.verify('SHA1', signature, data)
end
end
end
end
|
module InfinityTest
module Core
class CommandBuilder < String
# Just Syntax Sugar to add the keyword in the command
#
def add(command)
self << " #{command.to_s}"
self
end
# Put a double-dash in the command option.
#
def opt(command_option)
self << " --#{command_option}"
self
end
# Put one dash in the command option
#
def option(command_option)
self << " -#{command_option}"
self
end
# An Object that respond to all methods.
#
def respond_to?(method_name)
true
end
# Everytime will call a method will append to self.
#
# ==== Examples
#
# command.bundle.exec.rspec.spec
# command.bundle.install
#
def method_missing(method_name, *args, &block)
if self.empty?
self << "#{method_name.to_s}"
else
self << " #{method_name.to_s}"
end
self
end
end
end
end
|
import highlightjs from "highlight.js/lib/core";
import { nextTick } from "vue";
const plugin = {
install: function(Vue) {
Vue.directive("highlight", {
mounted(el) {
nextTick(function() {
el.innerHTML = escapeHTML(el);
highlightjs.highlightBlock(el);
});
}
});
}
};
function escapeHTML(el) {
return el.innerHTML
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
export default {
plugin,
registerLanguage: highlightjs.registerLanguage
};
|
# `dds-locale-modal`
## `Misc attributes`
#### `should render with minimum attributes`
```
<a
class="bx--visually-hidden"
href="javascript:void 0"
id="start-sentinel"
role="navigation"
>
</a>
<div
class="bx--modal-container"
tabindex="-1"
>
<div class="bx--modal-content">
<dds-expressive-modal-header data-autoid="dds--expressive-modal-header">
<dds-expressive-modal-close-button data-autoid="dds--expressive-modal-close-button">
</dds-expressive-modal-close-button>
<dds-expressive-modal-heading data-autoid="dds--expressive-modal-heading">
</dds-expressive-modal-heading>
</dds-expressive-modal-header>
<div class="bx--locale-modal bx--modal-content">
<slot name="regions-selector">
</slot>
</div>
<div>
<slot name="footer">
</slot>
</div>
</div>
</div>
<a
class="bx--visually-hidden"
href="javascript:void 0"
id="end-sentinel"
role="navigation"
>
</a>
```
#### `should render with various attributes`
```
<a
class="bx--visually-hidden"
href="javascript:void 0"
id="start-sentinel"
role="navigation"
>
</a>
<div
class="bx--modal-container"
tabindex="-1"
>
<div class="bx--modal-content">
<dds-expressive-modal-header data-autoid="dds--expressive-modal-header">
<dds-expressive-modal-close-button data-autoid="dds--expressive-modal-close-button">
</dds-expressive-modal-close-button>
<dds-expressive-modal-heading data-autoid="dds--expressive-modal-heading">
<p class="bx--modal-header__label bx--type-delta">
lang-display-foo
</p>
<p class="bx--modal-header__heading bx--type-beta">
header-title-foo
</p>
</dds-expressive-modal-heading>
</dds-expressive-modal-header>
<div class="bx--locale-modal bx--modal-content">
<slot name="regions-selector">
</slot>
</div>
<div>
<slot name="footer">
</slot>
</div>
</div>
</div>
<a
class="bx--visually-hidden"
href="javascript:void 0"
id="end-sentinel"
role="navigation"
>
</a>
```
#### `should render locale selector`
```
<a
class="bx--visually-hidden"
href="javascript:void 0"
id="start-sentinel"
role="navigation"
>
</a>
<div
class="bx--modal-container"
tabindex="-1"
>
<div class="bx--modal-content">
<dds-expressive-modal-header
data-autoid="dds--expressive-modal-header"
slot="header"
>
<dds-expressive-modal-close-button
data-autoid="dds--expressive-modal-close-button"
size=""
>
</dds-expressive-modal-close-button>
<dds-expressive-modal-heading data-autoid="dds--expressive-modal-heading">
<dds-link-with-icon
data-autoid="dds--link-with-icon"
href="#"
icon-placement="left"
>
header-title-foo
</dds-link-with-icon>
<p
class="bx--modal-header__heading bx--type-beta"
tabindex="0"
>
region-foo
</p>
</dds-expressive-modal-heading>
</dds-expressive-modal-header>
<slot name="locales-selector">
</slot>
<div>
<slot name="footer">
</slot>
</div>
</div>
</div>
<a
class="bx--visually-hidden"
href="javascript:void 0"
id="end-sentinel"
role="navigation"
>
</a>
```
|
curl -i -X POST -H "Content-Type:application/json" -d "{ \
\"Description\": \"Aliquam vulputate ullamcorper magna. Sed eu eros. Nam consequat\", \
\"Street\": \"190-4644 Est Avenue\", \
\"City\": \"Suwałki\", \
\"State\": \"PD\", \
\"ZipCode\": \"14707\", \
\"FirstName\": \"Colette\", \
\"LastName\": \"Atkinson\", \
\"PhoneNumber\": \"(725) 564-3651\", \
\"OutageType\": \"Gas leak\", \
\"IsEmergency\": \"false\", \
\"Resolved\": \"false\", \
\"Created\": \"2016-09-26T12:37:14-07:00\", \
\"LastModified\": \"2016-08-21T06:42:59-07:00\" }" \
http://localhost:9000/incidents
|
// TnzCore includes
#include "tsimplecolorstyles.h"
#include "timage_io.h"
#include "tconvert.h"
#include "tvectorimage.h"
#include "tpixelutils.h"
#include "tsystem.h"
#include "tstream.h"
// Qt includes
#include <QMutexLocker>
#include "tpalette.h"
#include <memory>
#include <sstream>
PERSIST_IDENTIFIER(TPalette, "palette")
TPersistDeclarationT<TPalette> auxPaletteDeclaration("vectorpalette");
DEFINE_CLASS_CODE(TPalette, 30)
//*************************************************************************************
// Local namespace stuff
//*************************************************************************************
namespace {
const std::string pointToString(const TColorStyle::PickedPosition &point) {
if (point.frame == 0)
return std::to_string(point.pos.x) + "," + std::to_string(point.pos.y);
else
return std::to_string(point.pos.x) + "," + std::to_string(point.pos.y) +
"," + std::to_string(point.frame);
}
// splitting string with ','
const TColorStyle::PickedPosition stringToPoint(const std::string &string) {
std::string buffer;
std::stringstream ss(string);
std::vector<std::string> result;
while (std::getline(ss, buffer, ',')) // split with comma
result.push_back(buffer);
int x = std::stoi(result[0]);
int y = std::stoi(result[1]);
int frame = 0;
if (result.size() == 3) // getting the third part of string - if any.
frame = std::stoi(result[2]);
return {TPoint(x, y), frame};
}
// convert refLevelFids to string for saving
std::string fidsToString(const std::vector<TFrameId> &fids) {
std::string str;
QList<int> numList;
for (const auto fid : fids) {
int num = fid.getNumber();
if (numList.isEmpty() || num == numList.last() + 1) {
numList.push_back(num);
continue;
}
// print
if (numList.count() == 1)
str += std::to_string(numList[0]) + ",";
else if (numList.count() == 2)
str +=
std::to_string(numList[0]) + "," + std::to_string(numList[1]) + ",";
else
str += std::to_string(numList[0]) + "-" + std::to_string(numList.last()) +
",";
numList.clear();
numList.push_back(num);
}
if (numList.count() == 1)
str += std::to_string(numList[0]);
else if (numList.count() == 2)
str += std::to_string(numList[0]) + "," + std::to_string(numList[1]);
else
str += std::to_string(numList[0]) + "-" + std::to_string(numList.last());
return str;
}
// convert loaded string to refLevelFids
std::vector<TFrameId> strToFids(std::string fidsStr) {
std::vector<TFrameId> ret;
QString str = QString::fromStdString(fidsStr);
QStringList chunks = str.split(',', QString::SkipEmptyParts);
for (const auto &chunk : chunks) {
QStringList nums = chunk.split('-', QString::SkipEmptyParts);
assert(nums.count() > 0 && nums.count() <= 2);
if (nums.count() == 1)
ret.push_back(TFrameId(nums[0].toInt()));
else { // nums.count() == 2
assert(nums[0].toInt() < nums[1].toInt());
for (int i = nums[0].toInt(); i <= nums[1].toInt(); i++)
ret.push_back(TFrameId(i));
}
}
return ret;
}
} // namespace
//===================================================================
//
// TPalette::Page
//
//-------------------------------------------------------------------
TPalette::Page::Page(std::wstring name)
: m_name(name), m_index(-1), m_palette(0) {}
//-------------------------------------------------------------------
TColorStyle *TPalette::Page::getStyle(int index) const {
assert(m_palette);
if (0 <= index && index < getStyleCount())
return m_palette->getStyle(m_styleIds[index]);
else
return 0;
}
//-------------------------------------------------------------------
int TPalette::Page::getStyleId(int index) const {
assert(m_palette);
if (0 <= index && index < getStyleCount())
return m_styleIds[index];
else
return -1;
}
//-------------------------------------------------------------------
int TPalette::Page::addStyle(int styleId) {
assert(m_palette);
if (styleId < 0 || styleId >= m_palette->getStyleCount()) return -1;
if (m_palette->m_styles[styleId].first != 0) return -1;
m_palette->m_styles[styleId].first = this;
int indexInPage = int(m_styleIds.size());
m_styleIds.push_back(styleId);
return indexInPage;
}
//-------------------------------------------------------------------
int TPalette::Page::addStyle(TColorStyle *style) {
assert(m_palette);
int stylesCount = int(m_palette->m_styles.size());
int styleId;
for (styleId = 0; styleId < stylesCount; styleId++)
if (m_palette->m_styles[styleId].first == 0) break;
if (styleId >= stylesCount - 1) return addStyle(m_palette->addStyle(style));
m_palette->setStyle(styleId, style);
return addStyle(styleId);
}
//-------------------------------------------------------------------
int TPalette::Page::addStyle(TPixel32 color) {
return addStyle(new TSolidColorStyle(color));
}
//-------------------------------------------------------------------
void TPalette::Page::insertStyle(int indexInPage, int styleId) {
assert(m_palette);
if (styleId < 0 || styleId >= m_palette->getStyleCount()) return;
if (m_palette->m_styles[styleId].first != 0) return;
m_palette->m_styles[styleId].first = this;
if (indexInPage < 0)
indexInPage = 0;
else if (indexInPage > getStyleCount())
indexInPage = getStyleCount();
m_styleIds.insert(m_styleIds.begin() + indexInPage, styleId);
}
//-------------------------------------------------------------------
void TPalette::Page::insertStyle(int indexInPage, TColorStyle *style) {
assert(m_palette);
int styleId = m_palette->addStyle(style);
if (styleId >= 0) insertStyle(indexInPage, styleId);
}
//-------------------------------------------------------------------
void TPalette::Page::insertStyle(int indexInPage, TPixel32 color) {
assert(m_palette);
int styleId = m_palette->addStyle(color);
if (styleId >= 0) insertStyle(indexInPage, styleId);
}
//-------------------------------------------------------------------
void TPalette::Page::removeStyle(int indexInPage) {
if (indexInPage < 0 || indexInPage >= getStyleCount()) return;
assert(m_palette);
int styleId = getStyleId(indexInPage);
assert(0 <= styleId && styleId < m_palette->getStyleCount());
assert(m_palette->m_styles[styleId].first == this);
m_palette->m_styles[styleId].first = 0;
m_styleIds.erase(m_styleIds.begin() + indexInPage);
}
//-------------------------------------------------------------------
int TPalette::Page::search(int styleId) const {
std::vector<int>::const_iterator it =
std::find(m_styleIds.begin(), m_styleIds.end(), styleId);
if (it == m_styleIds.end())
return -1;
else
return it - m_styleIds.begin();
}
//-------------------------------------------------------------------
int TPalette::Page::search(TColorStyle *style) const {
assert(style);
assert(m_palette);
for (int i = 0; i < getStyleCount(); i++)
if (m_palette->getStyle(m_styleIds[i]) == style) return i;
return -1;
}
//===================================================================
//
// TPalette
//
//-------------------------------------------------------------------
TPalette::TPalette()
: m_version(0)
, m_isCleanupPalette(false)
, m_currentFrame(-1)
, m_dirtyFlag(false)
, m_mutex(QMutex::Recursive)
, m_isLocked(false)
, m_askOverwriteFlag(false)
, m_shortcutScopeIndex(0)
, m_currentStyleId(1) {
QString tempName(QObject::tr("colors"));
std::wstring pageName = tempName.toStdWString();
Page *page = addPage(pageName);
page->addStyle(TPixel32(255, 255, 255, 0));
page->addStyle(TPixel32(0, 0, 0, 255));
getStyle(0)->setName(L"color_0");
getStyle(1)->setName(L"color_1");
for (int i = 0; i < 10; i++) m_shortcuts['0' + i] = i;
}
//-------------------------------------------------------------------
TPalette::~TPalette() {
std::set<TColorStyle *> table;
int i = 0;
for (i = 0; i < getStyleCount(); i++) {
assert(table.find(getStyle(i)) == table.end());
table.insert(getStyle(i));
}
clearPointerContainer(m_pages);
}
//-------------------------------------------------------------------
TPalette *TPalette::clone() const {
TPalette *palette = new TPalette;
palette->assign(this);
return palette;
}
//-------------------------------------------------------------------
TColorStyle *TPalette::getStyle(int index) const {
if (0 <= index && index < getStyleCount())
return m_styles[index].second.getPointer();
else {
static TSolidColorStyle *ss = new TSolidColorStyle(TPixel32::Red);
ss->addRef();
return ss;
}
}
//-------------------------------------------------------------------
int TPalette::getStyleInPagesCount() const {
int styleInPagesCount = 0;
for (int i = 0; i < getStyleCount(); i++)
if (m_styles[i].first != 0) styleInPagesCount++;
return styleInPagesCount;
}
//-------------------------------------------------------------------
int TPalette::getFirstUnpagedStyle() const {
for (int i = 0; i < getStyleCount(); i++)
if (m_styles[i].first == 0) return i;
return -1;
}
//-------------------------------------------------------------------
/*! Adding style with new styleId. Even if there are deleted styles in the
* palette, the new style will be appended to the end of the list.
*/
int TPalette::addStyle(TColorStyle *style) {
// limit the number of cleanup style to 7
if (isCleanupPalette() && getStyleInPagesCount() >= 8) return -1;
int styleId = int(m_styles.size());
if (styleId < 4096) {
// checking if the style is overlapped
int i = 0;
for (i = 0; i < styleId; i++)
if (getStyle(i) == style) break;
if (i == styleId) {
m_styles.push_back(std::make_pair((Page *)0, style));
return styleId;
}
}
delete style;
return -1;
}
//-------------------------------------------------------------------
int TPalette::addStyle(const TPixel32 &color) {
return addStyle(new TSolidColorStyle(color));
}
//-------------------------------------------------------------------
void TPalette::setStyle(int styleId, TColorStyle *style) {
std::unique_ptr<TColorStyle> styleOwner(style);
int styleCount = getStyleCount();
if (0 <= styleId && styleId < styleCount) {
// Find out if the supplied style is already in the palette
// with a different style id. In that case, bail out as a noop.
for (int i = 0; i < styleCount; ++i)
if (style == getStyle(i)) return;
// Substitution can take place
if (typeid(*m_styles[styleId].second.getPointer()) != typeid(*style))
m_styleAnimationTable.erase(styleId);
m_styles[styleId].second = styleOwner.release();
}
}
//-------------------------------------------------------------------
void TPalette::setStyle(int styleId, const TPixelRGBM32 &color) {
setStyle(styleId, new TSolidColorStyle(color));
}
//-------------------------------------------------------------------
int TPalette::getPageCount() const { return int(m_pages.size()); }
//-------------------------------------------------------------------
TPalette::Page *TPalette::getPage(int pageIndex) {
if (0 <= pageIndex && pageIndex < getPageCount()) {
Page *page = m_pages[pageIndex];
assert(page->getIndex() == pageIndex);
assert(page->m_palette == this);
return page;
} else
return 0;
}
//-------------------------------------------------------------------
const TPalette::Page *TPalette::getPage(int pageIndex) const {
if (0 <= pageIndex && pageIndex < getPageCount()) {
Page *page = m_pages[pageIndex];
assert(page->getIndex() == pageIndex);
assert(page->m_palette == this);
return page;
} else
return 0;
}
//-------------------------------------------------------------------
TPalette::Page *TPalette::addPage(std::wstring name) {
Page *page = new Page(name);
page->m_index = getPageCount();
page->m_palette = this;
m_pages.push_back(page);
return page;
}
//-------------------------------------------------------------------
void TPalette::erasePage(int index) {
Page *page = getPage(index);
if (!page) return;
m_pages.erase(m_pages.begin() + index);
int i;
for (i = 0; i < getPageCount(); i++) m_pages[i]->m_index = i;
for (i = 0; i < page->getStyleCount(); i++)
m_styles[page->getStyleId(i)].first = 0;
page->m_palette = 0;
delete page;
}
//-------------------------------------------------------------------
void TPalette::movePage(Page *page, int dstPageIndex) {
assert(page);
assert(page->m_palette == this);
dstPageIndex = tcrop(dstPageIndex, 0, getPageCount() - 1);
if (dstPageIndex == page->getIndex()) return;
m_pages.erase(m_pages.begin() + page->getIndex());
m_pages.insert(m_pages.begin() + dstPageIndex, page);
for (int i = 0; i < getPageCount(); i++) m_pages[i]->m_index = i;
assert(page->getIndex() == dstPageIndex);
}
//-------------------------------------------------------------------
TPalette::Page *TPalette::getStylePage(int styleId) const {
if (0 <= styleId && styleId < getStyleCount())
return m_styles[styleId].first;
else
return 0;
}
//-------------------------------------------------------------------
int TPalette::getClosestStyle(const TPixel32 &color) const {
struct locals {
static inline int getDistance2(const TPixel32 &a, const TPixel32 &b) {
return (a.r - b.r) * (a.r - b.r) + (a.g - b.g) * (a.g - b.g) +
(a.b - b.b) * (a.b - b.b) + (a.m - b.m) * (a.m - b.m);
}
}; // locals
if (color == TPixel32::Transparent) return 0;
int bestIndex = -1;
int bestDistance = 255 * 255 * 4 + 1;
for (int i = 1; i < (int)m_styles.size(); i++) {
// if(i==FirstUserStyle+2) continue;
TSolidColorStyle *scs =
dynamic_cast<TSolidColorStyle *>(m_styles[i].second.getPointer());
if (scs) {
int d = locals::getDistance2(scs->getMainColor(), color);
if (d < bestDistance) {
bestIndex = i;
bestDistance = d;
}
}
}
return bestIndex;
}
//-------------------------------------------------------------------
bool TPalette::getFxRects(const TRect &rect, TRect &rectIn, TRect &rectOut) {
int i;
bool ret = false;
int borderIn, borderOut, fullBorderIn = 0, fullBorderOut = 0;
for (i = 0; i < (int)m_styles.size(); i++)
if (m_styles[i].second->isRasterStyle()) {
m_styles[i].second->getRasterStyleFx()->getEnlargement(borderIn,
borderOut);
fullBorderIn = std::max(fullBorderIn, borderIn);
fullBorderOut = std::max(fullBorderOut, borderOut);
ret = true;
}
rectIn = rect.enlarge(fullBorderIn);
rectOut = rect.enlarge(fullBorderOut);
return ret;
}
//===================================================================
//
// I/O
//
//-------------------------------------------------------------------
namespace {
class StyleWriter final : public TOutputStreamInterface {
TOStream &m_os;
int m_index;
public:
static TFilePath m_rootDir;
StyleWriter(TOStream &os, int index) : m_os(os), m_index(index) {}
static void setRootDir(const TFilePath &fp) { m_rootDir = fp; }
TOutputStreamInterface &operator<<(double x) override {
m_os << x;
return *this;
};
TOutputStreamInterface &operator<<(int x) override {
m_os << x;
return *this;
};
TOutputStreamInterface &operator<<(std::string x) override {
m_os << x;
return *this;
};
TOutputStreamInterface &operator<<(UCHAR x) override {
m_os << (int)x;
return *this;
};
TOutputStreamInterface &operator<<(USHORT x) override {
m_os << (int)x;
return *this;
};
TOutputStreamInterface &operator<<(const TPixel32 &x) override {
m_os << x;
return *this;
};
TOutputStreamInterface &operator<<(const TRaster32P &ras) override {
assert(m_rootDir != TFilePath());
std::string name = "texture_" + std::to_string(m_index);
m_os << name;
TFilePath filename = ((m_rootDir + "textures") + name).withType("bmp");
if (!TFileStatus(m_rootDir + "textures").doesExist()) {
try {
TSystem::mkDir(m_rootDir + "textures");
} catch (...) {
}
}
TImageWriter::save(filename, ras);
return *this;
};
};
//-------------------------------------------------------------------
class StyleReader final : public TInputStreamInterface {
TIStream &m_is; //!< Wrapped input stream.
VersionNumber m_version; //!< Palette version number (overrides m_is's one).
public:
static TFilePath m_rootDir;
public:
StyleReader(TIStream &is, const VersionNumber &version)
: m_is(is), m_version(version) {}
static void setRootDir(const TFilePath &fp) { m_rootDir = fp; }
TInputStreamInterface &operator>>(double &x) override {
m_is >> x;
return *this;
}
TInputStreamInterface &operator>>(int &x) override {
m_is >> x;
return *this;
}
TInputStreamInterface &operator>>(std::string &x) override {
m_is >> x;
return *this;
}
TInputStreamInterface &operator>>(UCHAR &x) override {
int v;
m_is >> v;
x = v;
return *this;
}
TInputStreamInterface &operator>>(USHORT &x) override {
int v;
m_is >> v;
x = v;
return *this;
}
TInputStreamInterface &operator>>(TRaster32P &x) override {
assert(m_rootDir != TFilePath());
std::string name;
m_is >> name;
TFilePath filename = ((m_rootDir + "textures") + name).withType("bmp");
TRasterP ras;
if (TImageReader::load(filename, ras)) {
x = ras;
}
return *this;
}
TInputStreamInterface &operator>>(TPixel32 &x) override {
m_is >> x;
return *this;
}
/*!
\details Explicitly ovverrides the stream's version, returning m_version.
This is necessary since palettes have their \a own version number,
which is \a not the TIStream's file one.
*/
VersionNumber versionNumber() const override {
return m_version;
} //!< Returns the palette's version number.
};
TFilePath StyleWriter::m_rootDir = TFilePath();
TFilePath StyleReader::m_rootDir = TFilePath();
} // namespace
//===================================================================
void TPalette::setRootDir(const TFilePath &fp) {
StyleWriter::setRootDir(fp);
StyleReader::setRootDir(fp);
}
//-------------------------------------------------------------------
void TPalette::saveData(TOStream &os) {
os.child("version") << 71 << 0; // Inserting the version tag at this level.
// This is necessary to support the tpl format
if (m_refImgPath !=
TFilePath()) { // since it performs *untagged* stream output
if (m_areRefLevelFidsSpecified) {
std::map<std::string, std::string> attr;
attr["fids"] = fidsToString(m_refLevelFids);
os.openChild("refImgPath", attr);
} else
os.openChild("refImgPath");
os << m_refImgPath; // (the palette is streamed directly).
os.closeChild();
}
os.openChild("styles");
{
for (int i = 0; i < getStyleCount(); ++i) {
TColorStyleP style = m_styles[i].second;
if (style->getPickedPosition().pos == TPoint())
os.openChild("style");
else {
std::map<std::string, std::string> attr;
attr["pickedpos"] = pointToString(style->getPickedPosition());
os.openChild("style", attr);
}
{
StyleWriter w(os, i);
style->save(w);
}
os.closeChild();
}
}
os.closeChild();
os.openChild("stylepages");
{
for (int i = 0; i < getPageCount(); ++i) {
Page *page = getPage(i);
os.openChild("page");
{
os.child("name") << page->getName();
os.openChild("indices");
{
int m = page->getStyleCount();
for (int j = 0; j < m; ++j) os << page->getStyleId(j);
}
os.closeChild();
}
os.closeChild();
}
}
os.closeChild();
if (isAnimated()) {
os.openChild("animation");
{
StyleAnimationTable::iterator sat, saEnd = m_styleAnimationTable.end();
for (sat = m_styleAnimationTable.begin(); sat != saEnd; ++sat) {
int styleId = sat->first;
StyleAnimation &animation = sat->second;
std::map<std::string, std::string> attributes;
attributes["id"] = std::to_string(styleId);
os.openChild("style", attributes);
{
StyleAnimation::iterator kt, kEnd = animation.end();
for (kt = animation.begin(); kt != kEnd; ++kt) {
int frame = kt->first;
TColorStyle *cs = kt->second.getPointer();
assert(cs);
attributes.clear();
attributes["frame"] = std::to_string(frame);
/*os.openChild("keycolor", attributes); // Up
to Toonz 7.0, animations saved os << cs->getMainColor(); // the main
color only os.closeChild();*/ //
os.openChild("keyframe", attributes);
{
StyleWriter w(os, sat->first);
kt->second->save(w);
}
os.closeChild();
}
}
os.closeChild();
}
}
os.closeChild();
}
// salvo gli shortcuts solo se sono non standard
int i;
for (i = 0; i < 10; ++i)
if (getShortcutValue('0' + i) != i) break;
if (i < 10) {
os.openChild("shortcuts");
{
for (i = 0; i < 10; i++) os << getShortcutValue('0' + i);
}
os.closeChild();
}
if (isLocked()) {
os.openChild("lock");
os << 1;
os.closeChild();
}
}
//-------------------------------------------------------------------
void TPalette::loadData(TIStream &is) {
m_styles.clear();
clearPointerContainer(m_pages);
VersionNumber version = is.getVersion();
std::string tagName;
while (is.openChild(tagName)) {
if (tagName == "version") {
is >> version.first >> version.second;
if (version > VersionNumber(71, 0))
throw TException("palette, unsupported version number");
} else if (tagName == "styles") {
while (!is.eos()) // I think while(is.openChild(tagName))
{ // would be better. However, I don't trust
if (!is.openChild(tagName) ||
tagName !=
"style") // TIStream's implementation very much. Keeping it
throw TException(
"palette, expected tag <style>"); // like this for now.
{
StyleReader r(is, version);
TColorStyle *cs = TColorStyle::load(r);
std::string pickedPosStr;
if (is.getTagParam("pickedpos", pickedPosStr))
cs->setPickedPosition(stringToPoint(pickedPosStr));
addStyle(cs);
}
is.closeChild();
}
} else if (tagName == "stylepages") {
while (!is.eos()) {
if (!is.openChild(tagName) || tagName != "page")
throw TException("palette, expected tag <stylepage>");
{
std::wstring pageName;
if (!is.openChild(tagName) || tagName != "name")
throw TException("palette, expected tag <name>");
{ is >> pageName; }
is.closeChild();
Page *page = addPage(pageName);
if (!is.openChild(tagName) || tagName != "indices")
throw TException("palette, expected tag <indices>");
{
while (!is.eos()) {
int index;
is >> index;
page->addStyle(index);
}
}
is.closeChild();
}
is.closeChild();
}
} else if (tagName == "refImgPath") {
std::string fidsStr;
if (is.getTagParam("fids", fidsStr)) {
m_areRefLevelFidsSpecified = true;
m_refLevelFids = strToFids(fidsStr);
} else {
m_areRefLevelFidsSpecified = false;
m_refLevelFids.clear();
}
is >> m_refImgPath;
} else if (tagName == "animation") {
while (!is.eos()) {
if (!is.openChild(tagName) || tagName != "style")
throw TException("palette, expected tag <style>");
{
int styleId = 0;
if (!is.getTagParam("id", styleId))
throw TException("palette, missing id attribute in tag <style>");
StyleAnimation animation;
TColorStyle *style = getStyle(styleId);
assert(style);
while (is.matchTag(tagName)) {
TColorStyle *cs = 0;
int frame = 0;
if (tagName == "keycolor") {
if (!is.getTagParam("frame", frame))
throw TException(
"palette, missing frame attribute in tag <keycolor>");
TPixel32 color;
is >> color;
cs = style->clone();
cs->setMainColor(color);
} else if (tagName == "keyframe") {
if (!is.getTagParam("frame", frame))
throw TException(
"palette, missing frame attribute in tag <keyframe>");
StyleReader r(is, version);
cs = TColorStyle::load(r);
} else
throw TException("palette, expected <keyframe> tag");
animation[frame] = cs;
is.closeChild();
}
m_styleAnimationTable[styleId] = animation;
}
is.closeChild();
}
} else if (tagName == "stylepages") {
int key = '0';
while (!is.eos()) {
int styleId = 0;
is >> styleId;
if (key <= '9') setShortcutValue(key, styleId);
}
} else if (tagName == "shortcuts") {
for (int i = 0; i < 10; ++i) {
int v;
is >> v;
setShortcutValue('0' + i, v);
}
} else if (tagName == "lock") {
int lockValue;
is >> lockValue;
m_isLocked = (bool)lockValue;
} else
throw TException("palette, unknown tag: " + tagName);
is.closeChild();
}
}
//===================================================================
/*! if the palette is copied from studio palette, this function will modify the
* original names.
*/
void TPalette::assign(const TPalette *src, bool isFromStudioPalette) {
if (src == this) return;
int i;
m_isCleanupPalette = src->isCleanupPalette();
// for(i=0;i<getStyleCount();i++) delete getStyle(i);
m_styles.clear();
clearPointerContainer(m_pages);
for (i = 0; i < src->getStyleCount(); i++) {
TColorStyle *srcStyle = src->getStyle(i);
TColorStyle *dstStyle = srcStyle->clone();
dstStyle->setName(
srcStyle->getName()); // per un baco del TColorStyle::clone()
dstStyle->setGlobalName(
srcStyle->getGlobalName()); // per un baco del TColorStyle::clone()
// if the style is copied from studio palette, put its name to the original
// name.
// check if the style has the global name (i.e. it comes from studio
// palette)
if (isFromStudioPalette && srcStyle->getGlobalName() != L"") {
// If the original style has no original name (i.e. if the style is copied
// from the studio palette)
if (srcStyle->getOriginalName() == L"") {
// put the original style name to the "original name" of the pasted
// style.
dstStyle->setOriginalName(srcStyle->getName());
}
}
int j = addStyle(dstStyle);
assert(i == j);
}
for (i = 0; i < src->getPageCount(); i++) {
const Page *srcPage = src->getPage(i);
Page *dstPage = addPage(srcPage->getName());
for (int j = 0; j < srcPage->getStyleCount(); j++)
dstPage->addStyle(srcPage->getStyleId(j));
}
m_refImg = !!src->m_refImg ? src->m_refImg->cloneImage() : TImageP();
m_refImgPath = src->m_refImgPath;
StyleAnimationTable::iterator it;
StyleAnimation::iterator j;
for (it = m_styleAnimationTable.begin(); it != m_styleAnimationTable.end();
++it) {
// for(j = it->second.begin(); j != it->second.end(); ++j)
// delete j->second;
it->second.clear();
}
m_styleAnimationTable.clear();
StyleAnimationTable::const_iterator cit;
for (cit = src->m_styleAnimationTable.begin();
cit != src->m_styleAnimationTable.end(); ++cit) {
StyleAnimation animation = cit->second;
for (j = animation.begin(); j != animation.end(); j++)
j->second = j->second->clone();
m_styleAnimationTable[cit->first] = cit->second;
}
m_globalName = src->getGlobalName();
m_shortcuts = src->m_shortcuts;
m_currentFrame = src->m_currentFrame;
m_shortcutScopeIndex = src->m_shortcutScopeIndex;
// setDirtyFlag(true);
}
//-------------------------------------------------------------------
/*!if the palette is merged from studio palette, this function will modify the
* original names.
*/
void TPalette::merge(const TPalette *src, bool isFromStudioPalette) {
std::map<int, int> table;
int i;
for (i = 1; i < src->getStyleCount(); i++) {
TColorStyle *srcStyle = src->getStyle(i);
TColorStyle *dstStyle = srcStyle->clone();
dstStyle->setName(srcStyle->getName());
dstStyle->setGlobalName(srcStyle->getGlobalName());
// if the style is copied from studio palette, put its name to the original
// name.
// check if the style has the global name (i.e. it comes from studio
// palette)
if (isFromStudioPalette && srcStyle->getGlobalName() != L"") {
// If the original style has no original name (i.e. if the style is copied
// from the studio palette)
if (srcStyle->getOriginalName() == L"") {
// put the original style name to the "original name" of the pasted
// style.
dstStyle->setOriginalName(srcStyle->getName());
}
}
int j = addStyle(dstStyle);
table[i] = j;
}
int pageCount = src->getPageCount();
for (i = 0; i < pageCount; i++) {
const Page *srcPage = src->getPage(i);
std::wstring pageName = srcPage->getName();
if (pageName == L"colors" && src->getPaletteName() != L"")
pageName = src->getPaletteName();
Page *dstPage = addPage(pageName); //;
for (int j = 0; j < srcPage->getStyleCount(); j++) {
int styleId = srcPage->getStyleId(j);
if (styleId == 0) continue;
assert(table.find(styleId) != table.end());
dstPage->addStyle(table[styleId]);
}
assert(dstPage->m_palette == this);
}
}
//-------------------------------------------------------------------
void TPalette::setIsCleanupPalette(bool on) { m_isCleanupPalette = on; }
//-------------------------------------------------------------------
void TPalette::setRefImg(const TImageP &img) {
m_refImg = img;
if (img) {
assert(img->getPalette() == 0);
}
}
//-------------------------------------------------------------------
void TPalette::setRefLevelFids(const std::vector<TFrameId> fids,
bool specified) {
m_refLevelFids = fids;
m_areRefLevelFidsSpecified = specified;
}
//-------------------------------------------------------------------
std::vector<TFrameId> TPalette::getRefLevelFids() { return m_refLevelFids; }
//-------------------------------------------------------------------
void TPalette::setRefImgPath(const TFilePath &refImgPath) {
m_refImgPath = refImgPath;
}
//===================================================================
bool TPalette::isAnimated() const { return !m_styleAnimationTable.empty(); }
//-------------------------------------------------------------------
int TPalette::getFrame() const { return m_currentFrame; }
//-------------------------------------------------------------------
void TPalette::setFrame(int frame) {
QMutexLocker muLock(&m_mutex);
if (m_currentFrame == frame) return;
m_currentFrame = frame;
StyleAnimationTable::iterator sat, saEnd = m_styleAnimationTable.end();
for (sat = m_styleAnimationTable.begin(); sat != saEnd; ++sat) {
StyleAnimation &animation = sat->second;
assert(!animation.empty());
// Retrieve the associated style to interpolate
int styleId = sat->first;
assert(0 <= styleId && styleId < getStyleCount());
TColorStyle *cs = getStyle(styleId);
assert(cs);
// Buid the keyframes interval containing frame
StyleAnimation::iterator j0, j1;
j1 = animation.lower_bound(
frame); // j1 is the first element: j1->first >= frame
if (j1 == animation.begin())
cs->copy(*j1->second);
else {
j0 = j1, --j0;
assert(j0->first <= frame);
if (j1 == animation.end())
cs->copy(*j0->second);
else {
assert(frame <= j1->first);
cs->assignBlend(*j0->second, *j1->second,
(frame - j0->first) / double(j1->first - j0->first));
}
}
}
}
//-------------------------------------------------------------------
bool TPalette::isKeyframe(int styleId, int frame) const {
StyleAnimationTable::const_iterator it = m_styleAnimationTable.find(styleId);
if (it == m_styleAnimationTable.end()) return false;
return it->second.count(frame) > 0;
}
//-------------------------------------------------------------------
int TPalette::getKeyframeCount(int styleId) const {
StyleAnimationTable::const_iterator it = m_styleAnimationTable.find(styleId);
if (it == m_styleAnimationTable.end()) return 0;
return int(it->second.size());
}
//-------------------------------------------------------------------
int TPalette::getKeyframe(int styleId, int index) const {
StyleAnimationTable::const_iterator it = m_styleAnimationTable.find(styleId);
if (it == m_styleAnimationTable.end()) return -1;
const StyleAnimation &animation = it->second;
if (index < 0 || index >= (int)animation.size()) return -1;
StyleAnimation::const_iterator j = animation.begin();
std::advance(j, index);
return j->first;
}
//-------------------------------------------------------------------
void TPalette::setKeyframe(int styleId, int frame) {
assert(styleId >= 0 && styleId < getStyleCount());
assert(frame >= 0);
StyleAnimationTable::iterator sat = m_styleAnimationTable.find(styleId);
if (sat == m_styleAnimationTable.end())
sat =
m_styleAnimationTable.insert(std::make_pair(styleId, StyleAnimation()))
.first;
assert(sat != m_styleAnimationTable.end());
StyleAnimation &animation = sat->second;
animation[frame] = getStyle(styleId)->clone();
}
//-------------------------------------------------------------------
void TPalette::clearKeyframe(int styleId, int frame) {
assert(0 <= styleId && styleId < getStyleCount());
assert(0 <= frame);
StyleAnimationTable::iterator it = m_styleAnimationTable.find(styleId);
if (it == m_styleAnimationTable.end()) return;
StyleAnimation &animation = it->second;
StyleAnimation::iterator j = animation.find(frame);
if (j == animation.end()) return;
// j->second->release();
animation.erase(j);
if (animation.empty()) {
m_styleAnimationTable.erase(styleId);
}
}
//-------------------------------------------------------------------
int TPalette::getShortcutValue(int key) const {
assert(Qt::Key_0 <= key && key <= Qt::Key_9);
int shortcutIndex = (key == Qt::Key_0) ? 9 : key - Qt::Key_1;
int indexInPage = m_shortcutScopeIndex * 10 + shortcutIndex;
// shortcut is available only in the first page
return getPage(0)->getStyleId(indexInPage);
}
//-------------------------------------------------------------------
int TPalette::getStyleShortcut(int styleId) const {
assert(0 <= styleId && styleId < getStyleCount());
Page *page = getStylePage(styleId);
// shortcut is available only in the first page
if (!page || page->getIndex() != 0) return -1;
int indexInPage = page->search(styleId);
int shortcutIndex = indexInPage - m_shortcutScopeIndex * 10;
if (shortcutIndex < 0 || shortcutIndex > 9) return -1;
return (shortcutIndex == 9) ? Qt::Key_0 : Qt::Key_1 + shortcutIndex;
}
//-------------------------------------------------------------------
void TPalette::setShortcutValue(int key, int styleId) {
assert('0' <= key && key <= '9');
assert(styleId == -1 || 0 <= styleId && styleId < getStyleCount());
if (styleId == -1)
m_shortcuts.erase(key);
else {
std::map<int, int>::iterator it;
for (it = m_shortcuts.begin(); it != m_shortcuts.end(); ++it)
if (it->second == styleId) {
m_shortcuts.erase(it);
break;
}
m_shortcuts[key] = styleId;
}
}
//-------------------------------------------------------------------
// Returns true if there is at least one style with picked pos value
//-------------------------------------------------------------------
bool TPalette::hasPickedPosStyle() {
for (int i = 0; i < getStyleCount(); ++i) {
TColorStyleP style = m_styles[i].second;
if (style->getPickedPosition().pos != TPoint()) return true;
}
return false;
}
//-------------------------------------------------------------------
void TPalette::nextShortcutScope(bool invert) {
if (invert) {
if (m_shortcutScopeIndex > 0)
m_shortcutScopeIndex -= 1;
else
m_shortcutScopeIndex = getPage(0)->getStyleCount() / 10;
} else {
if ((m_shortcutScopeIndex + 1) * 10 < getPage(0)->getStyleCount())
m_shortcutScopeIndex += 1;
else
m_shortcutScopeIndex = 0;
}
}
|
export "package:ecoroutine/bloc/schedules/schedules.cubit.dart";
export "package:ecoroutine/bloc/schedules/schedules.state.dart";
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.