text
stringlengths 27
775k
|
|---|
import asyncio
import sys
from os import path
from arsenic import get_session, browsers, services, keys
class AsyncTigerAlgebra:
def __init__(self, loop=asyncio.get_event_loop()):
apath = path.dirname(path.dirname(__file__))
sys.path.append(path.abspath(apath))
self.bin = apath + '/solvemyproblem/drivers/phantomjs/bin/phantomjs.exe'
self.link = 'https://www.tiger-algebra.com/'
self.browser = browsers.PhantomJS()
self.service = services.PhantomJS(binary=self.bin)
self.loop = loop
async def solve(self, problem):
async with get_session(self.service, self.browser) as session:
await session.get(self.link)
box = await session.get_element('#ctl00_drill')
await box.send_keys(problem)
await box.send_keys(keys.RETURN)
solution = await session.get_element('.solution')
text = await solution.get_text()
answers = []
for stroke in text.split('\n')[2:]:
if 'Rearrange' in stroke or 'ends' in stroke:
break
elif any(word in stroke for word in ['Terminated', 'Quadratic']):
return
answers.append(stroke[1:] if stroke.startswith(' ') else stroke)
await session.close()
return '\n'.join(answers)
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BounceEase.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace AvaloniaExamples.Examples.AnimationsDemo
{
using System;
public class BounceEase : IEasingFunction
{
public BounceEase()
{
this.Bounces = 3;
this.Bounciness = 2d;
}
public int Bounces { get; set; }
public double Bounciness { get; set; }
public double Ease(double value)
{
double y1 = Math.Max(0.0, (double)this.Bounces);
double num1 = this.Bounciness;
if (num1 < 1.0 || num1 == 1d)
num1 = 1001.0 / 1000.0;
double num2 = Math.Pow(num1, y1);
double num3 = 1.0 - num1;
double num4 = (1.0 - num2) / num3 + num2 * 0.5;
double y2 = Math.Floor(Math.Log(-(value * num4) * (1.0 - num1) + 1.0, num1));
double y3 = y2 + 1.0;
double num5 = (1.0 - Math.Pow(num1, y2)) / (num3 * num4);
double num6 = (1.0 - Math.Pow(num1, y3)) / (num3 * num4);
double num7 = (num5 + num6) * 0.5;
double num8 = value - num7;
double num9 = num7 - num5;
double num10 = -Math.Pow(1.0 / num1, y1 - y2);
double num11 = num9;
double num12 = num11 * num11;
return num10 / num12 * (num8 - num9) * (num8 + num9);
}
}
}
|
<?php
session_start();
//bersihkan variabel SES_USER dari variabel
session_unregister("SES_USER");
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
?>
|
# frozen_string_literal: true
module AnnualBillingHelper
include AnnualBillingDataFileFormat
def annual_billing_csv_column_descriptions_for(regime)
items = ["<dl class='row'>"]
send("#{regime.to_param}_columns").each do |c|
items << "<dt class='col-sm-4 col-md-3'>#{c[:header].to_s.humanize.titlecase}</dt>"
items << "<dd class='col-sm-7 col-md-8'>#{DESCRIPTIONS[c[:header]]}</dd>"
end
items << "</dl>"
items.join.html_safe
end
end
|
gcc -Wall -fPIC -I.. -c prova.c
gcc -shared -Wl,-soname,prova.so -o prova.so prova.o -lSDL -lpthread
gcc -Wall -fPIC -I.. -c console.c
gcc -shared -Wl,-soname,console.so -o console.so console.o
|
package tomasvolker.numeriko.core.probability.continuous
import tomasvolker.numeriko.core.interfaces.array1d.double.DoubleArray1D
import tomasvolker.numeriko.core.interfaces.factory.doubleArray1D
import kotlin.random.Random
interface ContinuousProbabilityDistribution {
val mean: Double
val variance: Double
fun probabilityDensity(x: Double): Double
fun cumulativeDensity(x: Double): Double
fun nextDouble(random: Random = Random): Double
fun nextDoubleArray1D(size: Int, random: Random = Random): DoubleArray1D =
doubleArray1D(size) { nextDouble(Random) }
fun sequence(random: Random = Random): Sequence<Double> =
generateSequence { nextDouble(Random) }
}
fun ContinuousProbabilityDistribution.pdf(x: Double): Double = probabilityDensity(x)
fun ContinuousProbabilityDistribution.cdf(x: Double): Double = cumulativeDensity(x)
|
import unittest
import re
from sqlalchemy.exc import IntegrityError
from base import TestCase
from factories import build_user
from therminator import db
from therminator.models import User
class TestUser(TestCase):
def test_password_verification(self):
user = build_user(password='secret')
assert user.is_correct_password('secret')
assert not user.is_correct_password('bogus')
def test_generate_api_key_on_insert(self):
user = build_user()
db.session.add(user)
db.session.commit()
assert user.api_key, 'unexpected api_key: {}'.format(user.api_key)
def test_email_must_be_unique(self):
users = [build_user(email='alice@example.com') for _ in range(2)]
db.session.add_all(users)
with self.assertRaises(IntegrityError) as cm:
db.session.commit()
self.assertRegex(
cm.exception.args[0],
r'Key \(email\)=\(alice@example\.com\) already exists',
)
if __name__ == '__main__':
unittest.main()
|
# Infeasible methods
function InfeasibleProblem(prob::Problem, Z0::SampledTrajectory, R_inf::Real)
@assert !isnan(sum(sum.(states(Z0))))
nx,nu = dims(prob) # original sizes
N = TO.horizonlength(prob)
# Create model with augmented controls
model_inf = InfeasibleModel.(prob.model)
# Get a trajectory that is dynamically feasible for the augmented problem
# and matches the states and controls of the original guess
Z = infeasible_trajectory(model_inf, Z0)
# Convert constraints so that they accept new dimensions
conSet = TO.change_dimension(get_constraints(prob), nx[1], nu[1]+nx[1], 1:nx[1], 1:nu[1])
# Constrain additional controls to be zero
inf = InfeasibleConstraint(model_inf[1]) # TODO: handle multiple sizes
TO.add_constraint!(conSet, inf, 1:N-1)
# Infeasible Objective
obj = infeasible_objective(prob.obj, R_inf)
# Create new problem
Problem(model_inf, obj, conSet, prob.x0, prob.xf, Z, N, TO.get_initial_time(prob),
TO.get_final_time(prob))
end
function infeasible_objective(obj::Objective, regularizer)
n,m = TO.state_dim(obj.cost[1]), TO.control_dim(obj.cost[1])
Rd = [@SVector zeros(m); @SVector fill(regularizer,n)]
R = Diagonal(Rd)
cost_inf = TO.DiagonalCost(Diagonal(@SVector zeros(n)), R, checks=false)
costs = map(obj.cost) do cost
cost_idx = TO.change_dimension(cost, n, n+m, 1:n, 1:m)
cost_idx + cost_inf
end
TO.Objective(costs)
end
############################################################################################
# INFEASIBLE MODELS #
############################################################################################
RD.@autodiff struct InfeasibleModel{Nx,Nu,D<:DiscreteDynamics} <: DiscreteDynamics
model::D
_u::SVector{Nu,Int} # inds to original controls
_ui::SVector{Nx,Int} # inds to infeasible controls
function InfeasibleModel{Nx,Nu}(model::D) where {Nx,Nu,D<:DiscreteDynamics}
_u = SVector{Nu}(1:Nu)
_ui = SVector{Nx}((1:Nx) .+ Nu)
new{Nx,Nu,D}(model, _u, _ui)
end
end
"""
InfeasibleModel
An infeasible model is an augmented dynamics model that makes the system artifically fully
actuated by augmenting the control vector with `n` additional controls. The dynamics are
handled explicitly in discrete time:
``x_{k+1} = f(x_k,u_k,dt) + w_k``
where ``w_k`` are the additional `n`-dimensional controls. In practice, these are constrained
to be zero by the end of the solve.
# Constructors
```julia
InfeasibleModel(model::AbstractModel)
```
"""
InfeasibleModel
function InfeasibleModel(model::AbstractModel)
n,m = RD.dims(model)
InfeasibleModel{n,m}(model)
end
RD.statevectortype(::Type{<:InfeasibleModel{<:Any,<:Any,D}}) where D = RD.statevectortype(D)
RD.LieState(model::InfeasibleModel) = RD.LieState(model.model)
@inline RD.rotation_type(model::InfeasibleModel) where D = rotation_type(model.model)
RD.default_diffmethod(model::InfeasibleModel) = RD.default_diffmethod(model.model)
RD.default_signature(model::InfeasibleModel) = RD.default_signature(model.model)
# Generic Infeasible Methods
@inline RD.state_dim(model::InfeasibleModel{n}) where n = n
@inline RD.control_dim(model::InfeasibleModel{n,m}) where {n,m} = n+m
@inline RD.errstate_dim(model::InfeasibleModel) = RD.errstate_dim(model.model)
function RD.discrete_dynamics(model::InfeasibleModel,
x, u, t, dt)
u0 = u[model._u]
ui = u[model._ui]
RobotDynamics.discrete_dynamics(model.model, x, u0, t, dt) + ui
end
function RD.discrete_dynamics!(model::InfeasibleModel{Nx,Nu}, xn,
x, u, t, dt) where {Nx,Nu}
u0 = view(u, 1:Nu)
ui = view(u, Nu+1:Nx+Nu)
RobotDynamics.discrete_dynamics!(model.model, xn, x, u0, t, dt)
xn .+= ui
return
end
function RD.jacobian!(::RD.InPlace, diffmethod::DiffMethod, model::InfeasibleModel{Nx,Nu},
J, y, z) where {Nx,Nu}
n,m = RD.dims(model.model)
# Evaluate original Jacobian
J0 = view(J, :, 1:n+m)
z0 = RD.StaticKnotPoint{Nx,Nu}(n,m, view(z.z, 1:n+m), z.t, z.dt)
RD.jacobian!(RD.InPlace(), diffmethod, model.model, J0, y, z0)
# Fill in the rest manually
for i = 1:n
J[i, n+m+i] = 1
end
return
end
@inline RD.state_diff(model::InfeasibleModel, x::SVector, x0::SVector) =
RD.state_diff(model.model, x, x0)
@inline RobotDynamics.state_diff_jacobian!(G, model::InfeasibleModel, Z::SampledTrajectory) =
RobotDynamics.state_diff_jacobian!(G, model.model, Z)
@inline RobotDynamics.∇²differential!(∇G, model::InfeasibleModel, x::SVector, dx::SVector) =
∇²differential!(∇G, model.model, x, dx)
Base.position(model::InfeasibleModel, x::SVector) = position(model.model, x)
RobotDynamics.orientation(model::InfeasibleModel, x::SVector) = orientation(model.model, x)
"Calculate a dynamically feasible initial trajectory for an infeasible problem, given a
desired trajectory"
function infeasible_trajectory(models::Vector{<:InfeasibleModel}, Z0::SampledTrajectory{Nx,Nu}) where {Nx,Nu}
if Nx != Any && Nu != Any
Nū = Nx + Nu
else
Nū = Any
end
Z = map(Z0) do z
n = state_dim(z)
m = control_dim(z)
ui = @SVector zeros(n)
KnotPoint{Nx,Nū}(n, m + n, [RD.getdata(z); ui], z.t, z.dt)
end
N = length(Z0)
for k = 1:N-1
n = state_dim(models[k])
RD.propagate_dynamics!(RD.default_signature(models[k]), models[k], Z[k+1], Z[k])
x′ = state(Z[k+1])
u_slack = state(Z0[k+1]) - x′
u = [control(Z0[k]); u_slack]
RD.setcontrol!(Z[k], u)
RD.setstate!(Z[k+1], x′ + u_slack)
end
return SampledTrajectory(Z)
end
############################################################################################
# INFEASIBLE CONSTRAINT #
############################################################################################
"""
InfeasibleConstraint
Constraints additional ``infeasible'' controls to be zero.
Constructors: ```julia
InfeasibleConstraint(model::InfeasibleModel)
InfeasibleConstraint(n,m)
```
"""
struct InfeasibleConstraint{Nx,Nu} <: TO.ControlConstraint
ui::SVector{Nx,Int}
function InfeasibleConstraint{Nx,Nu}() where {Nx,Nu}
ui = SVector{Nx}((1:Nx) .+ Nu)
new{Nx,Nu}(ui)
end
end
InfeasibleConstraint(model::InfeasibleModel{n,m}) where {n,m} = InfeasibleConstraint{n,m}()
RobotDynamics.state_dim(con::InfeasibleConstraint{n,m}) where {n,m} = n
RobotDynamics.control_dim(con::InfeasibleConstraint{n,m}) where {n,m} = n+m
@inline TO.sense(::InfeasibleConstraint) = TO.Equality()
@inline RD.output_dim(::InfeasibleConstraint{n}) where n = n
RD.evaluate(con::InfeasibleConstraint, u::RD.DataVector) = u[con.ui] # infeasible controls
function RD.evaluate!(con::InfeasibleConstraint, c, u::RD.DataVector)
for (i,j) in enumerate(con.ui)
c[i] = u[j]
end
return
end
function RD.jacobian!(con::InfeasibleConstraint{Nx}, ∇c, c, u::RD.DataVector) where {Nx}
for (i,j) in enumerate(con.ui)
∇c[i,j] = 1
end
return
end
|
#using Infiltrator
function fold(dict::Dict)
io = IOBuffer()
TOML.print(io, dict)
return take!(io)
end
unfold(bytes::Vector{UInt8}) = TOML.parse(String(copy(bytes)))
struct Contract
signatures::Vector
end
Contract(signatures::Vector{Vector{UInt8}}) = Dict[unfold(s) for s in signatures]
PeaceCypher.id(c::Contract, notary::Notary) = [id(s, notary) for s in c.signatures]
function PeaceCypher.verify(document, c::Contract, notary::Notary)
for signature in c.signatures
verify(document, signature, notary) || return false
end
return true
end
struct Mixer <: Agent
mixer::ID
end
struct MetaData
mix::ID
gk::ID
hash::Hash
end
function Base.Dict(m::MetaData)
dict = Dict()
dict["mix"] = string(m.mix, base=16)
dict["gk"] = string(m.gk, base=16)
dict["N"] = m.hash.N
dict["hash"] = string(m.hash.hash, base=16)
return dict
end
function MetaData(dict::Dict)
mix = parse(BigInt, dict["mix"], base=16)
gk = parse(BigInt, dict["gk"], base=16)
N = dict["N"]
hash = parse(BigInt, dict["hash"], base=16)
return MetaData(ID(mix), ID(gk), Hash(N, hash))
end
struct SynchronicBraid <: Braid
metadata::MetaData
pseudonyms::Vector{ID}
end
function SynchronicBraid(ballot::Ballot)
metadata = MetaData(unfold(ballot.metadata))
pseudonyms = ID[]
for i in 1:size(ballot.votes, 2)
bytes = ballot.votes[:,i]
str = String(copy(bytes))
id = parse(BigInt, str, base=16)
push!(pseudonyms, ID(id))
end
return SynchronicBraid(metadata, pseudonyms)
end
# struct SynchronicBraid{ID} <: Braid
# braider::ID #Braider{ID}
# mix::ID #Mixer{ID}
# hash::Hash
# pseudonyms::Vector{ID}
# end
pseudonyms(braid::SynchronicBraid) = braid.pseudonyms
function validate(state::State, braid::SynchronicBraid, signers::Vector)
# @infiltrate
# for id in braid.pseudonyms
# id in state.pseudonyms || return false
# end
length(unique(braid.pseudonyms)) == length(unique(signers)) == length(signers) || return false
braid.metadata.gk in state.braiders || return false
for signer in signers
signer in state.pseudonyms || return false
end
return true
end
function Base.push!(tlog::BraidChain, row::Transaction{T}) where T <: Braid
#signers = [id(s, tlog.crypto) for s in row.signatures]
signers = id(row.signature, tlog.notary)
@assert validate(tlog.state, row.document, signers)
### At this point we are also able to validate also that ledger is also validated by hashes
@assert validate(tlog, row.document.metadata.hash)
@assert verify(row.document, row.signature, tlog.notary)
push!(tlog.state, row.document, signers)
push!(tlog.transactions, row)
end
|
package gaussian
import (
"math"
"github.com/mafredri/go-mathextra"
)
// NormCdf returns the cumulative gaussian distribution (cdf) at the point of interest.
func NormCdf(t float64) float64 {
return mathextra.Erfc(-t/math.Sqrt2) / 2.0
}
// NormPdf returns the probability density function (pdf) at the point of interest.
func NormPdf(t float64) float64 {
return mathextra.InvSqrt2Pi * math.Exp(-(t * t / 2.0))
}
// NormPpf returns the percent point function (ppf, the inverse of cdf) at the point of interest.
func NormPpf(p float64) float64 {
return -math.Sqrt2 * mathextra.InvErfc(2.0*p)
}
|
CREATE PROCEDURE [dbo].[GetRandomMessages]
@TemplateId VARCHAR(20),
@Level INT
AS
BEGIN
--DECLARE @Messages TABLE (
-- [Text] VARCHAR(100) NOT NULL
--);
SELECT TOP 5 [MessageId], [Text]
--INTO @Messages
FROM [dbo].[Messages]
WHERE [TemplateId] = @TemplateId
--AND (ABS(CAST((BINARY_CHECKSUM(*) * RAND()) AS INT)) % 100) < 10
ORDER BY (ABS(CAST((BINARY_CHECKSUM(*) * RAND()) AS INT)) % 100)
;
--TODO: Randomly distort the messages
END
|
package com.hms.command;
import com.hms.main.Route;
import com.hms.main.Util;
public class DistanceRequestHandler implements Receiver {
@Override
public void action() {
float distance = Util.distanceCalculator(Route.getInstance().getPoints());
System.out.println("Distance covered is: "+ distance+ " Kilometers");
}
}
|
package com.wasu.demo19.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName:UserController
* @Description: TODO
* @Author: Syl
* @Date: 2021/7/27 14:33
*/
@RestController()
@RequestMapping("/user")
public class UserController {
@RequestMapping("/{id}")
public void user(@PathVariable String id){
try{
System.out.println(id);
}catch (Exception e){
throw new RuntimeException();
}
}
}
|
package justcompany.noughtsandcrosses;
public enum Status {
CLEAR(0),
CROSS(1),
NOUGHT(2);
public Integer value;
Status(Integer value) {
this.value = value;
}
}
|
package io.koalaql.sql
import io.koalaql.Assignment
import io.koalaql.ddl.TableColumn
import io.koalaql.dsl.value
import io.koalaql.expr.*
import io.koalaql.identifier.Named
import io.koalaql.query.*
import io.koalaql.query.built.*
import io.koalaql.values.ValuesRow
import io.koalaql.window.*
import io.koalaql.window.built.BuiltWindow
class ScopedSqlBuilder(
val output: CompiledSqlBuilder,
val scope: Scope,
val compiler: Compiler
) {
fun addSql(sql: String) {
output.addSql(sql)
}
fun addAlias(alias: Alias) {
output.addIdentifier(scope[alias])
}
fun parenthesize(emitParens: Boolean = true, block: () -> Unit) {
if (!emitParens) return block()
output.addSql("(")
block()
output.addSql(")")
}
fun prefix(initial: String, after: String): SqlPrefix {
var pref = initial
return object : SqlPrefix {
override fun next(block: () -> Unit) {
addSql(pref)
block()
pref = after
}
}
}
fun addError(error: String) = output.addError(error)
fun selectFields(
fields: List<SelectedExpr<*>>,
compileExpr: (Expr<*>) -> Unit
) {
if (fields.isNotEmpty()) {
prefix("", "\n, ").forEach(fields) {
val resolved = when (it.expr) {
is AsReference -> scope.resolveOrNull(it.asReference())
else -> null
}
val relabel = scope.nameOf(it.name)
compileExpr(it.expr)
if (resolved?.innerName != relabel) {
addSql(" ")
output.addIdentifier(scope.nameOf(it.name))
}
}
} else {
addError("unable to generate empty selection")
}
}
fun selectClause(
query: BuiltSelectQuery,
compileExpr: (Expr<*>) -> Unit
) {
val selected = query.selected
addSql("SELECT ")
if (query.distinctness == Distinctness.DISTINCT) addSql("DISTINCT ")
selectFields(selected, compileExpr)
}
fun returningClause(
query: BuiltReturning,
compileExpr: (Expr<*>) -> Unit
) {
val returned = query.returned
addSql("RETURNING ")
selectFields(returned, compileExpr)
}
fun compileRangeMarker(direction: String, marker: FrameRangeMarker<*>, compileExpr: (Expr<*>) -> Unit) {
when (marker) {
CurrentRow -> addSql("CURRENT ROW")
is Following<*> -> compileExpr(marker.offset)
is Preceding<*> -> compileExpr(marker.offset)
Unbounded -> addSql("UNBOUNDED $direction")
}
}
fun compileWindow(
window: BuiltWindow,
compileExpr: (Expr<*>) -> Unit,
compileOrderBy: (List<Ordinal<*>>) -> Unit
) {
val partitionedBy = window.partitions.partitions
val orderBy = window.partitions.orderBy
val prefix = prefix("", " ")
window.partitions.from?.let {
prefix.next {
addWindow(it)
}
}
if (partitionedBy.isNotEmpty()) prefix.next {
prefix("PARTITION BY ", ", ").forEach(partitionedBy) {
compileExpr(it)
}
}
if (orderBy.isNotEmpty()) prefix.next {
compileOrderBy(orderBy)
}
window.type?.let { windowType ->
prefix.next {
addSql(windowType.sql)
addSql(" ")
val until = window.until
if (until == null) {
compileRangeMarker("PRECEDING", window.from) { compileExpr(it) }
} else {
addSql("BETWEEN ")
compileRangeMarker("PRECEDING", window.from) { compileExpr(it) }
addSql(" AND ")
compileRangeMarker("FOLLOWING", until) { compileExpr(it) }
}
}
}
}
fun compileWindowClause(
windows: List<LabeledWindow>,
compileWindow: (BuiltWindow) -> Unit
) {
prefix("\nWINDOW ", "\n, ").forEach(windows) { window ->
addWindow(window.label)
addSql(" AS ")
addSql("(")
compileWindow(BuiltWindow.from(window.window))
addSql(")")
}
}
fun compileJoins(
joins: Iterable<BuiltJoin>,
compileRelation: (BuiltRelation) -> Unit,
compileExpr: (Expr<*>) -> Unit
) {
joins.forEach { join ->
addSql("\n")
addSql(join.type.sql)
addSql(" ")
compileRelation(join.to)
join.on?.let { on ->
addSql(" ON ")
compileExpr(on)
}
}
}
fun compileFullQuery(
query: BuiltQuery,
compileWiths: (BuiltWithable) -> Unit,
compileSubquery: (BuiltUnionOperandQuery) -> Boolean,
compileSetOperation: (BuiltSetOperation) -> Unit = {
addSql("\n")
addSql(it.type.sql)
when (it.distinctness) {
Distinctness.ALL -> addSql(" ALL")
Distinctness.DISTINCT -> { }
}
addSql("\n")
compileSubquery(it.body)
},
compileOrderBy: (List<Ordinal<*>>) -> Unit
): Boolean {
compileWiths(query)
val nonEmptyHead = compileSubquery(query.head)
query.unioned.forEach(compileSetOperation)
if (query.orderBy.isNotEmpty()) {
addSql("\n")
compileOrderBy(query.orderBy)
}
query.limit?.let {
addSql("\nLIMIT ")
compiler.addLiteral(this, value(it))
}
if (query.offset != 0) {
addSql("\nOFFSET ")
compiler.addLiteral(this, value(query.offset))
}
return nonEmptyHead || query.unioned.isNotEmpty()
}
fun compileUpdate(
update: BuiltUpdate,
compileWiths: (BuiltWithable) -> Unit,
compileRelation: (BuiltRelation) -> Unit,
compileAssignment: (Assignment<*>) -> Unit,
compileExpr: (Expr<*>) -> Unit
): Boolean {
val query = update.query
compileWiths(update)
if (update.withs.isNotEmpty()) addSql("\n")
addSql("UPDATE ")
compileRelation(update.query.relation)
addSql("\nSET ")
check(query.joins.isEmpty()) {
"H2 does not support JOIN in update"
}
val wasNonEmpty = if (update.assignments.isEmpty()) {
addError("empty assignment list")
false
} else {
prefix("", ", ").forEach(update.assignments) {
compileAssignment(it)
}
true
}
query.where?.let {
addSql("\nWHERE ")
compileExpr(it)
}
return wasNonEmpty
}
fun compileOrderBy(
ordinals: List<Ordinal<*>>,
compileExpr: (Expr<*>) -> Unit
) {
prefix("ORDER BY ", ", ").forEach(ordinals) {
val orderKey = it.toOrderKey()
compileExpr(orderKey.expr)
addSql(" ${orderKey.order.sql}")
when (orderKey.nulls) {
NullOrdering.FIRST -> addSql(" NULLS FIRST")
NullOrdering.LAST -> addSql(" NULLS LAST")
null -> { }
}
}
}
fun compileInsertLine(
insert: BuiltInsert,
table: TableRelation = insert.unwrapTable(),
compileName: () -> Unit = { addTableReference(table) }
) {
val columns = insert.query.columns
if (insert.ignore) {
addSql("INSERT IGNORE INTO ")
} else {
addSql("INSERT INTO ")
}
val tableColumnMap = table.columns.associateBy { it }
compileName()
parenthesize {
prefix("", ", ").forEach(columns) {
val column = checkNotNull(tableColumnMap[it]) {
"can't insert $it into ${table.tableName}"
}
addIdentifier(column.symbol)
}
}
}
fun compileQueryBody(
body: BuiltQueryBody,
compileExpr: (Expr<*>) -> Unit,
compileRelation: (BuiltRelation) -> Unit,
compileWindows: (windows: List<LabeledWindow>) -> Unit,
compileJoins: (List<BuiltJoin>) -> Unit = { joins ->
this.compileJoins(joins, compileRelation, compileExpr)
},
compileWhere: (Expr<*>) -> Unit = { where ->
addSql("\nWHERE ")
compileExpr(where)
},
compileGroupBy: (List<Expr<*>>) -> Unit = {
prefix("\nGROUP BY ", ", ").forEach(body.groupBy) {
compileExpr(it)
}
},
compileHaving: (Expr<*>) -> Unit = {
addSql("\nHAVING ")
compileExpr(it)
},
compileOrderBy: (List<Ordinal<*>>) -> Unit = { orderBys ->
this.compileOrderBy(orderBys) {
compileExpr(it)
}
}
) {
compileRelation(body.relation)
if (body.joins.isNotEmpty()) compileJoins(body.joins)
body.where?.let(compileWhere)
if (body.groupBy.isNotEmpty()) compileGroupBy(body.groupBy)
body.having?.let(compileHaving)
if (body.windows.isNotEmpty()) compileWindows(body.windows)
if (body.orderBy.isNotEmpty()) {
addSql("\n")
compileOrderBy(body.orderBy)
}
body.limit?.let {
addSql("\nLIMIT ")
compiler.addLiteral(this, value(it))
}
if (body.offset != 0) {
addSql("\nOFFSET ")
compiler.addLiteral(this, value(body.offset))
}
body.locking?.let { locking ->
when (locking) {
LockMode.SHARE -> addSql("\nFOR SHARE")
LockMode.UPDATE -> addSql("\nFOR UPDATE")
}
}
}
fun compileRow(
columns: List<Reference<*>>,
row: ValuesRow,
compileExpr: (Expr<*>) -> Unit
) {
addSql("(")
prefix("", ", ").forEach(columns) {
@Suppress("unchecked_cast")
compileExpr(row[it])
}
addSql(")")
}
fun compileValues(
query: BuiltValuesQuery,
compileExpr: (Expr<*>) -> Unit,
compileRow: (List<Reference<*>>, ValuesRow) -> Unit = { columns, it ->
this.compileRow(columns, it, compileExpr)
}
): Boolean {
val values = query.values
addSql("VALUES ")
val iter = values.valuesIterator()
var count = 0
return if (iter.next()) {
val rowPrefix = prefix("", "\n, ")
do {
if (count == 1) output.beginAbridgement()
rowPrefix.next {
compileRow(values.columns, iter.row)
}
count++
} while (iter.next())
if (count > 1) output.endAbridgement(" /* VALUES had ${count - 1} more rows here */")
true
} else {
addError("couldn't generate empty values")
false
}
}
fun addColumnMappings(columns: List<TableColumn<*>>) {
columns.forEach { output.addMapping(it.builtDef.columnType) }
}
fun addIdentifier(id: String) = output.addIdentifier(Named(id))
fun addTableReference(table: TableRelation) {
addColumnMappings(table.columns)
addIdentifier(table.tableName)
}
fun compileOnConflict(
onConflict: OnConflictOrDuplicateAction?,
compileAssignment: (Assignment<*>) -> Unit
) {
val assignments = when (onConflict) {
is OnConflictIgnore -> {
addSql("\nON CONFLICT ON CONSTRAINT ")
addIdentifier(onConflict.key.name)
addSql(" DO NOTHING")
return
}
is OnConflictUpdate -> {
addSql("\nON CONFLICT ON CONSTRAINT ")
addIdentifier(onConflict.key.name)
addSql(" DO UPDATE SET")
onConflict.assignments
}
is OnDuplicateUpdate -> {
addSql("\nON DUPLICATE KEY UPDATE")
onConflict.assignments
}
null -> return
}
if (assignments.isNotEmpty()) {
prefix(" ", "\n,").forEach(assignments) {
compileAssignment(it)
}
} else {
addError("empty assignment list")
}
}
fun compileInsert(
insert: BuiltInsert,
compileInsertLine: (BuiltInsert) -> Unit,
compileQuery: (BuiltQuery) -> Boolean,
compileOnConflict: (OnConflictOrDuplicateAction) -> Unit
): Boolean {
compileInsertLine(insert)
addSql("\n")
val nonEmpty = compileQuery(insert.query)
insert.onConflict?.let(compileOnConflict)
return nonEmpty
}
fun compileDelete(
delete: BuiltDelete,
compileWiths: (BuiltWithable) -> Unit,
compileQueryBody: (BuiltQueryBody) -> Unit
) {
compileWiths(delete)
addSql("DELETE FROM ")
compileQueryBody(delete.query)
}
fun compileWiths(
withable: BuiltWithable,
compileCte: (Cte) -> Unit,
compileRelabels : (List<Reference<*>>) -> Unit,
compileQuery: (BuiltSubquery) -> Boolean
) {
val prefix = prefix(
when (withable.withType) {
WithType.RECURSIVE -> "WITH RECURSIVE "
WithType.NOT_RECURSIVE -> "WITH "
},
"\n, "
)
prefix.forEach(withable.withs) {
compileCte(it.cte)
if (it.query.columnsUnnamed()) compileRelabels(it.query.columns)
addSql(" AS (")
compileQuery(it.query)
addSql(")")
}
}
fun transformScope(operation: (Scope) -> Scope) =
ScopedSqlBuilder(output, operation(scope), compiler)
fun withScope(query: PopulatesScope) = transformScope { scope ->
val innerScope = scope.innerScope()
query.populateScope(innerScope)
innerScope
}
fun withCtes(withable: BuiltWithable) = transformScope { scope ->
val innerScope = scope.innerScope()
withable.withs.forEach {
innerScope.cte(it.cte, it.query.columns)
}
innerScope
}
fun withColumns(columns: List<Column<*>>, alias: Alias? = null) = transformScope { scope ->
val innerScope = scope.innerScope()
columns.forEach {
innerScope.internal(it, Named(it.symbol), alias)
}
innerScope
}
fun addReference(reference: Reference<*>) {
output.addIdentifier(scope.nameOf(reference))
}
fun resolveReference(reference: Reference<*>) {
output.withResult(scope.resolve(reference)) {
output.addResolved(it)
}
}
fun resolveWithoutAlias(reference: Reference<*>) {
output.withResult(scope.resolve(reference)) {
output.addIdentifier(it.innerName)
}
}
fun addCte(cte: Cte) {
output.addIdentifier(scope[cte])
}
fun addWindow(window: WindowLabel) {
output.addIdentifier(scope.nameOf(window))
}
private inline fun <T> scopedIn(query: PopulatesScope, block: ScopedSqlBuilder.() -> T): T {
return withScope(query).block()
}
fun compileReturning(
dml: BuiltReturning,
compileStmt: ScopedSqlBuilder.(BuiltStatement) -> Boolean,
compileExpr: ScopedSqlBuilder.(Expr<*>) -> Unit
): Boolean = scopedIn(dml.stmt) {
val nonEmpty = compileStmt(dml.stmt)
addSql("\n")
returningClause(dml) { compileExpr(it) }
nonEmpty
}
fun compile(
dml: BuiltDml,
compileQuery: ScopedSqlBuilder.(BuiltSubquery) -> Boolean,
compileStmt: ScopedSqlBuilder.(BuiltStatement) -> Boolean
): CompiledSql? {
val nonEmpty = when (dml) {
is BuiltSubquery -> compileQuery(dml)
is BuiltStatement -> scopedIn(dml) { compileStmt(dml) }
}
return if (nonEmpty) {
toSql()
} else {
null
}
}
fun toSql() = output.toSql()
}
|
##Common API Action: get()
###Applies to All IWC APIs
###Retrieves a Given Node
To retrieve a node stored in an API the `get` action is used on
**a reference to the node**. The retrieval is asynchronous, and the response is
passed through the resolution of the action's promise.
```
var ballRef = new iwc.data.Reference("/ball"); // generate the reference to the resource
var ballVal;
ballRef.get().then(function(value){
ballVal = value;
});
```
The value of the promise resolution is the value assigned to the resource. The
value can be any valid Javascript primitive or array.
If further detail is required on the IWC response, refer to the [Comprehensive
IWC Requests]() section.
##Requesting a node that does not exist
Requesting a node that does not exist is not an valid action, this will result
in an promise rejection with a containing the string `'noResource'`.
Given that the resource `/ball` above does not exist in the IWC:
```
ballRef.get().catch(function(err){
console.log("Could not retrieve. Reason: ", err);
});
```
|
package ru.romashov.blogapp.utils;
import org.jsoup.Jsoup;
public class StringUtils {
/**
* Ref: https://core.telegram.org/bots/api#markdownv2-style
* Characters '_‘, ’*‘, ’[‘, ’]‘, ’(‘, ’)‘, ’~‘, ’`‘, ’>‘, ’#‘, ’+‘, ’-‘, ’=‘, ’|‘, ’{‘, ’}‘, ’.‘, ’!‘
* must be escaped with the preceding character ’\'.
*/
public static String escapeString(String string) {
return Jsoup.parse(string).text()
.replaceAll("([_*\\[\\]()~`>#+\\-=|{}.!])", "\\\\$1");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class Sfx : MonoBehaviour {
public AudioClip[] Clips;
private AudioSource Source;
private int Index = -1;
private bool InitializedIndex = false;
// This is mostly just a way to let someone who spawns a gameobject with this component
// trigger the index rolling without waiting for Start().
public void InitializeIndex(int index) {
Index = index;
if (Index < 0 || Index >= Clips.Length) {
Index = Random.Range(0, Clips.Length);
}
InitializedIndex = true;
}
private void Start() {
Source = GetComponent<AudioSource>();
if (!InitializedIndex) InitializeIndex(Index);
Source.clip = Clips[Index];
Source.Play();
}
private void Update() {
if (!Source.isPlaying) {
Destroy(gameObject);
}
}
}
|
package com.rc_long.Entity;
import com.rc_long.anotation.RcLongTable;
import com.rc_long.Anrequest.TableName;
/**
* 栏目实体类
* @author longge
*
*/
@RcLongTable(name=TableName.ProgramaBean)
public class ProgramaBean extends EntitiBaseBean<ProgramaBean> {
/**
*
*/
private static final long serialVersionUID = 1L;
private String programa_name;//栏目名称
private String programa_id;//栏目id
private String programa_pid;//上级id
private String programa_desc;//描述
private String programa_img;//封面
private Integer programa_wathers;//栏目人气
private Integer programa_videos;//视频数
public String getPrograma_img() {
return programa_img;
}
public void setPrograma_img(String programa_img) {
this.programa_img = programa_img;
}
public String getPrograma_name() {
return programa_name;
}
public void setPrograma_name(String programa_name) {
this.programa_name = programa_name;
}
public String getPrograma_id() {
return programa_id;
}
public void setPrograma_id(String programa_id) {
this.programa_id = programa_id;
}
public String getPrograma_pid() {
return programa_pid;
}
public void setPrograma_pid(String programa_pid) {
this.programa_pid = programa_pid;
}
public Integer getPrograma_wathers() {
return programa_wathers;
}
public void setPrograma_wathers(Integer programa_wathers) {
this.programa_wathers = programa_wathers;
}
public Integer getPrograma_videos() {
return programa_videos;
}
public void setPrograma_videos(Integer programa_videos) {
this.programa_videos = programa_videos;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getPrograma_desc() {
return programa_desc;
}
public void setPrograma_desc(String programa_desc) {
this.programa_desc = programa_desc;
}
}
|
require "sanitize"
require "htmlentities"
require "yaml"
class Blinkbox::Onix2Processor::Processor
def normalize_tags(array)
array.collect do |tag|
(SHORT_TAGS[tag.downcase] || tag).downcase
end
end
def sanitize_html(html)
Sanitize.clean(html, @@valid_html)
end
def product_failure(state, name, data = {})
state[:product_failures].push(
error_code: name,
data: data
)
end
def self.yaml_config(file)
YAML.load(open(File.join(__dir__, "../../../../config/#{file}.yaml"))).freeze
end
SHORT_TAGS = yaml_config("short_codes")
end
class String
def clever_decode!
2.times do
break unless self.match(/&(?:#?\d{2,3}|[a-z]+);/)
self.replace(HTMLEntities.new.decode(self))
end
self
end
end
|
# Defining config file
We want to move the config options into a config file:
**webpack.config.js**
```js
module.exports = {
entry: './entry.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.css$/, loader: 'style!css' }
]
}
};
```
Now we can just run:
```bash
webpack
```
to compile:
```bash
Version: webpack 1.12.11
Time: 379ms
Asset Size Chunks Chunk Names
bundle.js 10.7 kB 0 [emitted] main
chunk {0} bundle.js (main) 8.86 kB [rendered]
[0] ./tutorials/getting-started/config-file/entry.js 65 bytes {0} [built]
[1] ./tutorials/getting-started/config-file/style.css 943 bytes {0} [built]
[2] ../~/css-loader!./tutorials/getting-started/config-file/style.css 201 bytes {0} [built]
[3] ../~/css-loader/lib/css-base.js 1.51 kB {0} [built]
[4] ../~/style-loader/addStyles.js 6.09 kB {0} [built]
[5] ./tutorials/getting-started/config-file/content.js 45 bytes {0} [built]
```
*The webpack command-line will try to load the file `webpack.config.js` in the current directory.*
|
const REGEX_HAS_PARAMS = /\?\w+=/
const REGEX_URL_VALUE = /:([\w_]+)/gi
const REGEX_URL_QUERY = /([?&])([\w_-]+)=:([\w_-]+)/gi
const addURLParam = (url, param, value) =>
`${url}${REGEX_HAS_PARAMS.test(url) ? '&' : '?'}${param}=${value}`
export const expandURL = (url, data = {}, method = 'get') => {
const usedKeys = {}
const tmp = url.split(' ')
if (tmp.length > 1) {
method = tmp[0].toLowerCase()
url = tmp[1]
}
url = url
.replace(REGEX_URL_VALUE, (match, dataKey) => {
if (data[dataKey] !== undefined) {
usedKeys[dataKey] = true
return data[dataKey]
}
return ''
})
.replace(REGEX_URL_QUERY, (match, prefix, parameter, dataKey) => {
if (data[dataKey] !== undefined) {
usedKeys[dataKey] = true
return `${prefix}${parameter}=${data[dataKey]}`
}
return ''
})
// Adding other params from data by key
if (method === 'get') {
for (let dataKey of Object.keys(data).filter(k => !usedKeys[k])) {
if (data[dataKey] !== undefined) {
usedKeys[dataKey] = true
url = addURLParam(url, dataKey, data[dataKey])
}
}
}
const dataWithoutUnusedKeys = Object
.keys(data)
.filter(key => !usedKeys[key])
.reduce((acc, key) => {
acc[key] = data[key]
return acc
}, {})
// console.log('{method, route: url}: ', { method, route: url })
return { method, url, data: dataWithoutUnusedKeys, originalData: data }
}
|
if [[ $1 -eq 1 ]]; then
> echo "1 was passed in first argument"
> elif [[ $1 -gt 2 ]]; then
> echo "2 was not passed in the first parameter"
> else
> echo "the first argument was passed was not 1 nor greater than 2"
> fi
|
#pragma once
// table.hpp: generate a posit table
//
// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <iostream>
#include <iomanip>
#include <cmath> // for frexp/frexpf
#include <typeinfo> // for typeid()
namespace sw::universal {
// generate a full binary representation table for a given posit configuration
template<size_t nbits, size_t es>
void GeneratePositTable(std::ostream& ostr, bool csvFormat = false) {
static constexpr size_t fbits = (es + 2 >= nbits ? 0 : nbits - 3 - es);
const size_t size = (1 << nbits);
posit<nbits, es> p;
if (csvFormat) {
ostr << "\"Generate Posit Lookup table for a POSIT<" << nbits << "," << es << "> in CSV format\"" << std::endl;
ostr << "#, Binary, Decoded, k, sign, scale, regime, exponent, fraction, value, posit\n";
for (size_t i = 0; i < size; i++) {
p.set_raw_bits(i);
bool s;
regime<nbits, es> r;
exponent<nbits, es> e;
fraction<fbits> f;
decode(p.get(), s, r, e, f);
ostr << i << ","
<< p.get() << ","
<< decoded(p) << ","
<< r.regime_k() << ","
<< s << ","
<< scale(p) << ","
<< std::right << r << ","
<< std::right << e << ","
<< std::right << f << ","
<< to_string(p, 22) << ","
<< p
<< '\n';
}
ostr << std::endl;
}
else {
ostr << "Generate Posit Lookup table for a POSIT<" << nbits << "," << es << "> in TXT format" << std::endl;
const size_t index_column = 5;
const size_t bin_column = 16;
const size_t k_column = 8;
const size_t sign_column = 8;
const size_t scale_column = 8;
const size_t regime_column = 16;
const size_t exponent_column = 16;
const size_t fraction_column = 16;
const size_t value_column = 30;
const size_t posit_format_column = 16;
ostr << std::setw(index_column) << " # "
<< std::setw(bin_column) << "Binary"
<< std::setw(bin_column) << "Decoded"
<< std::setw(k_column) << "k"
<< std::setw(sign_column) << "sign"
<< std::setw(scale_column) << "scale"
<< std::setw(regime_column) << "regime"
<< std::setw(exponent_column) << "exponent"
<< std::setw(fraction_column) << "fraction"
<< std::setw(value_column) << "value"
<< std::setw(posit_format_column) << "posit_format"
<< std::endl;
for (size_t i = 0; i < size; i++) {
p.set_raw_bits(i);
bool s;
regime<nbits, es> r;
exponent<nbits, es> e;
fraction<fbits> f;
decode(p.get(), s, r, e, f);
ostr << std::setw(4) << i << ": "
<< std::setw(bin_column) << p.get()
<< std::setw(bin_column) << decoded(p)
<< std::setw(k_column) << r.regime_k()
<< std::setw(sign_column) << s
<< std::setw(scale_column) << scale(p)
<< std::setw(regime_column) << std::right << to_string(r)
<< std::setw(exponent_column) << std::right << to_string(e)
<< std::setw(fraction_column) << std::right << to_string(f)
<< std::setw(value_column) << to_string(p, 22) << " "
<< std::setw(posit_format_column) << std::right << p
<< std::endl;
}
}
}
} // namespace sw::universal
|
using System;
namespace Bellight.Core.Misc
{
public interface IStaticLogProvider
{
void Error(string message);
void Error(Exception ex, string messageTemplate);
void Warning(string message);
void Information(string message);
}
}
|
var pages = pages || {};
pages.agendamento = pages.agendamento || {};
pages.agendamento.model = pages.agendamento.model || {};
pages.agendamento.services = pages.agendamento.services || {};
pages.metadata = pages.metadata || {};
pages.dataServices = pages.dataServices || {};
pages.utils = pages.utils || {};
pages.agendamento.visualizarViewModel = function () {
var model = pages.agendamento.model;
var service = pages.agendamento.services;
var id = window.location.href.split("/").lastOrDefault();
ko.applyBindings(new function () {
var self = this;
self.agendamento = ko.observable();
self.init = function () {
self.obterAgendamentoPorId(id);
};
self.obterAgendamentoPorId = function (agendamentoId) {
pages.dataServices.bloquearTela();
service.obterPorId(agendamentoId).then(function (result) {
self.agendamento(new model.vmAgendamentoListagem(result.data));
}).catch(function (result) {
console.log(result.data);
}).finally(function () {
pages.dataServices.desbloquearTela();
});
};
self.voltar = function () {
pages.dataServices.bloquearTela();
window.location.href = "/Agendamento/Index";
};
self.init();
}, bindingBody);
}();
|
require 'rails_helper'
RSpec.describe Product, type: :model do
it {should validate_presence_of :title}
it {should validate_presence_of :price}
it {should have_many(name :galleries)}
it {should belong_to(:category)}
it {should have_many(name :related_products)}
it {should have_many(name :related)}
end
|
import _pipe from './utils/_pipe';
import _arity from './utils/_arity';
import _tail from './utils/_tail';
import reduce from './reduce';
/**
* 管道方法 从左到右执行函数
* @func
* @member {Function}
* @param {...Function} functions
* @returns {*}
* @tutorial compose
* @example
*
* pipe(f1, f2, f3)({x:1,y:2});
* pipe(f1)(f2)(f3)({x:1,y:2}, 8, 10);
*/
const pipe = function () {
var fns = [].slice.call(arguments);
return _arity(fns.length, reduce(_pipe, _tail(fns), fns[0]));
}
export default pipe;
|
namespace ECS.Config
{
using ECS.Common;
using UnityEngine;
using System.Collections.Generic;
using System;
public sealed class ConfigManager
{
Dictionary<string, ScriptableObject> _configDict = new Dictionary<string, ScriptableObject>();
public T Get<T>(string name = null) where T : ScriptableObject
{
var configName = name != null ? name : typeof(T).ToString();
#if DEBUG
if (!_configDict.ContainsKey(configName))
{
Log.E("failed to find config " + configName);
return null;
}
#endif
return _configDict[configName] as T;
}
public void LoadConfig(ScriptableObject config, string name = null)
{
var configName = name != null ? name : config.GetType().ToString();
#if DEBUG
if (_configDict.ContainsKey(configName))
{
Log.W("duplicate config " + configName + " will replac the old one!");
}
#endif
_configDict[configName] = config;
}
public void LoadConfigGroup(ConfigGroup configGroup)
{
foreach (var configGroupInfo in configGroup.configGroupInfoList)
{
LoadConfig(configGroupInfo.config, configGroupInfo.name);
}
}
}
}
|
use strict;
use warnings;
use Test::More;
use DNS::Resolver;
my $resolver = DNS::Resolver->new;
my $domain = "www.google.com";
my @ip = $resolver->resolve($domain);
ok @ip;
note "$domain -> $_" for @ip;
my $ok;
for my $ip (@ip) {
my $domain = $resolver->reverse_resolve($ip);
if ($domain) {
note "$ip -> $domain";
$ok++;
} else {
note "$ip -> FAIL, " . $resolver->error;
}
}
ok $ok;
done_testing;
|
import React, { Fragment } from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import Box from './Box';
storiesOf('Box').add('with text inside', () => (
<Fragment>
<Box m={1} p={1} color="white" backgroundColor="tomato">
<p>paragraph inside a box m 1 p 1</p>
</Box>
</Fragment>
));
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using J = Newtonsoft.Json.JsonPropertyAttribute;
namespace NugetAuditor.Core
{
public partial class CatalogEntryResponse
{
[J("@id")] public string Id { get; set; }
[J("isPrerelease")] public bool IsPrerelease { get; set; }
[J("projectUrl")] public string ProjectUrl { get; set; }
[J("licenseUrl")] public string LicenceUrl { get; set; }
[J("iconUrl")] public string IconUrl { get; set; }
}
}
|
%%-------------------------------------------------------------------
%% @author
%% ChicagoBoss Team and contributors, see AUTHORS file in root directory
%% @end
%% @copyright
%% This file is part of ChicagoBoss project.
%% See AUTHORS file in root directory
%% for license information, see LICENSE file in root directory
%% @end
%% @doc
%%-------------------------------------------------------------------
-module(boss_mail_driver_mock).
-export([start/0, stop/1, deliver/5, read/2, push/0, pop/0]).
start() ->
register(boss_mock_inbox, spawn(fun() -> loop([]) end)),
{ok, undefined}.
stop(_) ->
ok.
loop([]) ->
loop([dict:new()]);
loop([InboxDict|OldState] = State) ->
receive
{From, {read, ToAddress, Subject}} ->
Inbox = case dict:find(ToAddress, InboxDict) of
{ok, Val} -> Val;
_ -> []
end,
case first_email_with_subject(Subject, Inbox) of
undefined ->
From ! {boss_mock_inbox, undefined},
loop(State);
Email ->
NewInbox = lists:delete(Email, Inbox),
From ! {boss_mock_inbox, Email},
loop([dict:store(ToAddress, NewInbox, InboxDict)|OldState])
end;
{From, {deliver, _FromAddress, ToAddress, Email}} ->
Inbox = case dict:find(ToAddress, InboxDict) of
{ok, Val} -> Val;
_ -> []
end,
DecodableEmail = iolist_to_binary(Email),
ParsedEmail = mimemail:decode(DecodableEmail),
From ! {boss_mock_inbox, ok},
loop([dict:store(ToAddress, [ParsedEmail|Inbox], InboxDict)|OldState]);
{From, push} ->
From ! {boss_mock_inbox, ok},
loop([InboxDict|State]);
{From, pop} ->
From ! {boss_mock_inbox, ok},
loop(OldState)
end.
deliver(_, FromAddress, ToAddress, BodyFun, _ResultFun) ->
% TODO use ResultFun
boss_mock_inbox ! {self(), {deliver, FromAddress, ToAddress, BodyFun()}},
receive
{boss_mock_inbox, ok} ->
ok
end.
read(ToAddress, Subject) ->
boss_mock_inbox ! {self(), {read, ToAddress, Subject}},
receive
{boss_mock_inbox, Email} ->
Email
end.
push() ->
case lists:member(boss_mock_inbox, erlang:registered()) of
true ->
boss_mock_inbox ! {self(), push},
receive {boss_mock_inbox, ok} -> ok end;
false ->
ok
end.
pop() ->
case lists:member(boss_mock_inbox, erlang:registered()) of
true ->
boss_mock_inbox ! {self(), pop},
receive {boss_mock_inbox, ok} -> ok end;
false ->
ok
end.
% internal
first_email_with_subject(Subject, Inbox) when is_list(Subject) ->
first_email_with_subject(list_to_binary(Subject), Inbox);
first_email_with_subject(_Subject, []) ->
undefined;
first_email_with_subject(Subject, [{_, _, Headers, _, _} = Email|Rest]) ->
case proplists:get_value(<<"Subject">>, Headers) of
Subject -> Email;
_ -> first_email_with_subject(Subject, Rest)
end.
|
package compose.tablature
trait StringHelpers {
object StartsWithChar {
def unapply(str: String) =
if(str.length == 0) {
None
} else {
Some((str.charAt(0), str.substring(1)))
}
}
object StartsWithFret {
def unapply(str: String) = {
if(str.length == 0) {
None
} else {
str.indexWhere(x => !x.isDigit) match {
case -1 => Some((str.toInt, ""))
case 0 => None
case n => Some((str.substring(0, n).toInt, str.substring(n)))
}
}
}
}
}
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
require File.expand_path('../seed/base', __FILE__) # all necessary for gameplay
require File.expand_path('../seed/initial_app_roles', __FILE__) # initial app roles
unless Rails.env.test? || Rails.env.production?
require File.expand_path('../seed/city1', __FILE__) # example city
end
|
import { Engine } from './engine';
import { Dictionary, ListDefinition, TypeDefinition } from './types';
import { Expression } from './expression';
import {
BehaviorSubject,
concat,
Observable,
throwError,
TimeoutError,
} from 'rxjs';
import { LinkError } from './errors';
import {
catchError,
distinctUntilChanged,
filter,
map,
shareReplay,
skip,
switchMap,
take,
tap,
timeout,
} from 'rxjs/operators';
import invariant from 'ts-invariant';
export class Input extends Expression {
line: number = 0;
column: number = 0;
constructor(public readonly name: string) {
super(0, 0);
}
}
export class Inputs {
private readonly _inputIsUpdating = new BehaviorSubject(0);
constructor(public readonly engine: Engine) {}
registerInput(
name: string,
type: TypeDefinition,
sink: Observable<any>
): void {
if (this.input(name, 0, 0)) {
throw new Error(`input ${name} is already registered`);
}
const inp = new Input(name);
inp.typeDefinition = type;
inp.sink = sink.pipe(
distinctUntilChanged(),
tap((x) => this.engine.logInputValue(name, x)),
filter((x) => {
// pass through everything in release mode
if (!this.engine.debug) {
return true;
}
const correct = type.isTypeCorrect(x);
if (!correct) {
console.error(
`wrong type for input ${name}: expected value of type ${type.typeName}, got ${x}`
);
}
return correct;
}),
switchMap((x) => {
return new Observable<typeof x>((subscriber) => {
this.beginUpdates();
subscriber.next(x);
this.endUpdates();
subscriber.complete();
});
}),
shareReplay({ bufferSize: 1, refCount: true })
);
if (this.engine.debug) {
const head = inp.sink.pipe(
take(1),
timeout(1000),
catchError((err) => {
if (err instanceof TimeoutError) {
console.error(
`inconsistency for input ${name}: no value came in 1s`
);
return throwError(
new Error(
`inconsistency for input ${name}: no value came in 1s`
)
);
} else {
return throwError(err);
}
})
);
const tail = inp.sink.pipe(skip(1));
inp.sink = concat(head, tail);
}
this.inputs[name] = inp;
}
registerInputReference(
keyPath: string,
type: string,
line: number,
column: number
) {
const inp = this.input(keyPath, line, column);
if (!inp)
throw new LinkError(
line,
column,
`property ${keyPath} is not defined`
);
const def = this.engine.type(type);
if (!def)
throw new LinkError(line, column, `type ${type} is not defined`);
if (inp.typeDefinition && inp.typeDefinition !== def) {
throw new LinkError(
line,
column,
`type for ${keyPath} is already set to ${inp.typeDefinition} while trying to set it to ${def}`
);
}
inp.typeDefinition = def;
inp.line = line;
inp.column = column;
}
input(name: string, line: number, column: number): Input | null {
const input = this.inputs[name];
if (input) return input;
const match = name.match(/^(.*)\.count$/);
if (match) {
const source = match[1];
const collection = this.inputs[source];
if (collection) {
if (collection.typeDefinition instanceof ListDefinition) {
const i = new Input(name);
i.typeDefinition = this.engine.numberType();
i.sink = collection.sink.pipe(map((arr) => arr.length));
return i;
} else {
throw new LinkError(
line,
column,
`type for ${name} is not list: got ${collection.typeDefinition} instead`
);
}
}
}
return null;
}
public beginUpdates() {
this._inputIsUpdating.next(this._inputIsUpdating.value + 1);
}
public endUpdates() {
invariant(
this._inputIsUpdating.value > 0,
'unmatched call to endUpdates()'
);
this._inputIsUpdating.next(this._inputIsUpdating.value - 1);
}
get inputIsUpdating(): Observable<boolean> {
return this._inputIsUpdating.pipe(
map((x) => x > 0),
distinctUntilChanged()
);
}
private inputs: Dictionary<Input> = {};
}
|
import React from "react";
import { View, StyleSheet } from "react-native";
import AppConfiguration from "../config/AppConfiguration";
import ColorPallete from "../config/ColorPallete";
import AppText from "./AppText";
import AudioPlayer from "./AudioPlayer";
import ImageMessage from "./ImageMessage";
import TextMessage from "./TextMessage";
const BaseURL = AppConfiguration.BaseURL;
function SendMessage({
Message,
Time,
Date,
Read,
Type,
File,
Mime,
CustomFile,
PreviewFile,
ProfilePicture,
Name,
onPress,
CurrentPlaying,
}) {
return (
<>
{Date ? <AppText Title={Date} style={styles.Date} /> : null}
<View style={styles.FileContainer}>
{Type === "Text" ? (
<TextMessage Message={Message} Time={Time} />
) : Mime === "audio" ? (
<AudioPlayer
Message={Message}
Time={Time}
File={File}
CustomFile={CustomFile}
ProfilePicture={ProfilePicture}
Name={Name}
CurrentPlaying={CurrentPlaying}
/>
) : (
<ImageMessage
File={Mime === "image" ? File : BaseURL + PreviewFile}
PreviewFile={Mime === "image" ? PreviewFile : BaseURL + PreviewFile}
CustomFile={
Mime === "image"
? CustomFile
: CustomFile
? PreviewFile
: BaseURL + PreviewFile
}
onPress={onPress}
Mime={Mime}
Time={Time}
isVideo={Mime === "video" ? true : false}
/>
)}
</View>
<View style={styles.SeenBox}>
{Read !== null || Read !== undefined ? (
Read === true ? (
<AppText Title="Seen" style={styles.Seen} />
) : null
) : null}
</View>
</>
);
}
export default SendMessage;
const styles = StyleSheet.create({
FileContainer: {
flexDirection: "row-reverse",
overflow: "hidden",
marginBottom: 10,
},
Date: {
alignSelf: "center",
color: "white",
marginBottom: 10,
backgroundColor: ColorPallete.DateColor,
padding: 5,
borderRadius: 5,
},
SeenBox: {
flexDirection: "row-reverse",
},
Seen: {
alignSelf: "flex-end",
color: "grey",
marginBottom: 0,
marginTop: -10,
marginRight: 5,
},
});
|
#!/usr/bin/env python3.6
import uuid
from unittest.mock import patch
from ... import UploadTestCaseUsingMockAWS, EnvironmentSetup
from . import client_for_test_api_server
from upload.common.uploaded_file import UploadedFile
from upload.common.upload_area import UploadArea
from upload.common.validation_event import ValidationEvent
from upload.common.checksum_event import ChecksumEvent
from upload.common.database import UploadDB
from upload.common.upload_api_client import update_event
from upload.common.upload_config import UploadConfig
class TestUploadApiClient(UploadTestCaseUsingMockAWS):
def setUp(self):
super().setUp()
# Environment
self.environment = {
'CSUM_DOCKER_IMAGE': 'bogoimage',
'API_HOST': 'bogohost'
}
self.environmentor = EnvironmentSetup(self.environment)
self.environmentor.enter()
# Setup authentication
self.authentication_header = {'Api-Key': UploadConfig().api_key}
# Setup app
self.client = client_for_test_api_server()
def tearDown(self):
super().tearDown()
self.environmentor.exit()
def _create_area(self):
area_uuid = str(uuid.uuid4())
self.client.post(f"/v1/area/{area_uuid}", headers=self.authentication_header)
return area_uuid
@patch('upload.lambdas.api_server.v1.area.IngestNotifier.format_and_send_notification')
def test_update_event_with_validation_event(self, mock_format_and_send_notification):
validation_id = str(uuid.uuid4())
area_id = self._create_area()
s3obj = self.mock_upload_file_to_s3(area_id, 'foo.json')
upload_area = UploadArea(area_id)
uploaded_file = UploadedFile(upload_area, s3object=s3obj)
validation_event = ValidationEvent(file_ids=[uploaded_file.db_id],
validation_id=validation_id,
job_id='12345',
status="SCHEDULED")
validation_event.create_record()
validation_event.status = "VALIDATING"
response = update_event(validation_event, uploaded_file.info(), self.client)
self.assertEqual(204, response.status_code)
record = UploadDB().get_pg_record("validation", validation_id)
self.assertEqual("VALIDATING", record["status"])
self.assertEqual("<class 'datetime.datetime'>", str(type(record.get("validation_started_at"))))
self.assertEqual(None, record["validation_ended_at"])
self.assertEqual(None, record.get("results"))
validation_event.status = "VALIDATED"
response = update_event(validation_event, uploaded_file.info(), self.client)
self.assertEqual(204, response.status_code)
record = UploadDB().get_pg_record("validation", validation_id)
self.assertEqual("VALIDATED", record["status"])
self.assertEqual("<class 'datetime.datetime'>", str(type(record.get("validation_started_at"))))
self.assertEqual("<class 'datetime.datetime'>", str(type(record.get("validation_ended_at"))))
self.assertEqual(uploaded_file.info(), record.get("results"))
@patch('upload.lambdas.api_server.v1.area.IngestNotifier.format_and_send_notification')
def test_update_event_with_checksum_event(self, mock_format_and_send_notification):
checksum_id = str(uuid.uuid4())
area_uuid = self._create_area()
s3obj = self.mock_upload_file_to_s3(area_uuid, 'foo.json')
upload_area = UploadArea(area_uuid)
uploaded_file = UploadedFile(upload_area, s3object=s3obj)
checksum_event = ChecksumEvent(file_id=uploaded_file.db_id,
checksum_id=checksum_id,
job_id='12345',
status="SCHEDULED")
checksum_event.create_record()
checksum_event.status = "CHECKSUMMING"
response = update_event(checksum_event, uploaded_file.info(), self.client)
self.assertEqual(204, response.status_code)
record = UploadDB().get_pg_record("checksum", checksum_id)
self.assertEqual("CHECKSUMMING", record["status"])
self.assertEqual("<class 'datetime.datetime'>", str(type(record.get("checksum_started_at"))))
self.assertEqual(None, record["checksum_ended_at"])
checksum_event.status = "CHECKSUMMED"
response = update_event(checksum_event, uploaded_file.info(), self.client)
self.assertEqual(204, response.status_code)
record = UploadDB().get_pg_record("checksum", checksum_id)
self.assertEqual("CHECKSUMMED", record["status"])
self.assertEqual("<class 'datetime.datetime'>", str(type(record.get("checksum_started_at"))))
self.assertEqual("<class 'datetime.datetime'>", str(type(record.get("checksum_ended_at"))))
|
```{include} ../../src/elchempy/README.md
```
|
import * as reducer from "../reducer";
import * as sagas from "../sagas";
import * as selectors from "../selectors";
import { createJWT } from "../index";
describe("createJWT", () => {
it("should create object correctly", () => {
const mockCreateReducer = jest.spyOn(reducer, "createReducer").mockReturnValue("test createReducer");
const mockCreateRootSaga = jest.spyOn(sagas, "createRootSaga").mockReturnValue("test createRootSaga");
const mockCreateSelectors = jest.spyOn(selectors, "createSelectors").mockReturnValue("test createSelectors");
const config: any = {
setTokens: "test setToken",
getTokens: "test getToken",
stateSelector: "test stateSelector",
};
expect(createJWT(config)).toEqual({
createSelectors: "test createSelectors",
reducer: "test createReducer",
saga: "test createRootSaga",
});
expect(mockCreateReducer).toBeCalledWith(config);
expect(mockCreateRootSaga).toBeCalledWith(config);
expect(mockCreateSelectors).toBeCalledWith(config);
});
});
|
// Copyright 2017 HP Development Company, L.P.
// SPDX-License-Identifier: MIT
package com.hp.jipp.encoding
/**
* An [AttributeType] for values bitwise OR'd together. Only used by CUPS.
* Values are expressed as Long to allow for values of 0x80000000 and above, but are
* transmitted as 4-byte integers.
*/
class BitfieldType(
override val name: String
) : AttributeTypeImpl<Int>(name, Int::class.java) {
override fun coerce(value: Any): Int? =
when (value) {
is UntypedEnum -> value.code
is Int -> value
else -> { println("Value: $value, ${value.javaClass}"); super.coerce(value) }
}
override fun toString() = "BitwiseType($name)"
companion object {
val codec = Codec(Tag.enumValue, {
readIntValue().toLong()
}, {
writeIntValue(it.toInt())
})
}
}
|
<?php
declare(strict_types = 1);
namespace Com\Incoders\SampleMS\Domain\Query\File;
use Com\Incoders\Cqrs\Application\Cqs\QueryInterface;
class ListFilesQuery implements QueryInterface
{
}
|
import checksum = require('check-sum');
import * as fs from 'fs';
const stream = fs.createReadStream('package.json');
checksum(stream, {
md5: 'asdfasdfasdf',
sha1: 'asdfasdfasdf'
}, err => {
err; // $ExpectType any
});
checksum('package.json', {
md5: 'asdfasdfasdf',
sha1: 'asdfasdfasdf'
}, err => {
err; // $ExpectType Error | ChecksumError | undefined
});
|
import i18next from 'i18next';
import resources from '../translations.json';
import { initReactI18next } from 'react-i18next';
import config_constants from '../constants';
import { createContext } from 'react';
i18next.use(initReactI18next).init({
lng: 'en',
resources
});
const defaultT = i18next.getFixedT(config_constants.defaultLang);
const TranslationContext = createContext(defaultT);
export default TranslationContext;
export const i18n = i18next;
|
#!/bin/bash
http_port=$1;
game_mode=$2
stack build asteroids && stack exec server $http_port $game_mode;
|
package org.jetbrains.plugins.scala.codeInspection.scaladoc
import org.jetbrains.plugins.scala.codeInspection.ScalaQuickFixTestBase
class ScalaDocUnbalancedHeaderInspection2Test extends ScalaQuickFixTestBase {
override protected val classOfInspection = classOf[ScalaDocUnbalancedHeaderInspection]
override protected val description = "All text from header closing tag to end of line will be lost"
private val hintMoveAfter = "Move text after header closing to new line"
def testMoveTextAfterHeader(): Unit =
testQuickFix(
"""/** ==header 1== some text after */""",
"""/** ==header 1==
| * some text after */""".stripMargin,
hintMoveAfter
)
def testMoveTextAfterHeader_SeveralLeadingSpaces(): Unit =
testQuickFix(
"""/** ==header 1== some text after */""",
"""/** ==header 1==
| * some text after */""".stripMargin,
hintMoveAfter
)
def testMoveTextAfterHeader_TextWithSyntaxElements(): Unit =
testQuickFix(
"""/** ==header 1== some `text` __after__ */""",
"""/** ==header 1==
| * some `text` __after__ */""".stripMargin,
hintMoveAfter
)
def testMoveTextAfterUnbalancedHeader(): Unit =
testQuickFix(
"""/** ===unbalanced header==== some text after */""",
"""/** ===unbalanced header====
| * some text after */""".stripMargin,
hintMoveAfter
)
def testNoMoveTextAfterHeaderInspection_NoTextAfterHeader(): Unit = {
checkNotFixable(
"""/**==header==*/
|class A""".stripMargin,
hintMoveAfter
)
checkNotFixable(
"""/** ==header== */
|class A""".stripMargin,
hintMoveAfter
)
checkNotFixable(
"""/** ==header==
| */
|class A""".stripMargin,
hintMoveAfter
)
}
def testNoMoveTextAfterHeaderInspection_NoAsterisksAfterHeader(): Unit = {
checkNotFixable(
"""/**
| * ==header
|
|
| */
|class A""".stripMargin,
hintMoveAfter
)
checkNotFixable(
"""/**
| * ==header==
|
|
| */
|class A""".stripMargin,
hintMoveAfter
)
}
}
|
#!/bin/bash
root -l $@ ${ARTUSPATH}/Utility/scripts/tBrowser.C
|
frappe.ui.form.on("Stock Entry", {
stock_entry_type: function (frm) {
frm.toggle_reqd(
"customer_cf",
["Material Receipt", "Material Issue"].includes(frm.doc.stock_entry_type)
);
frm.toggle_reqd(
"received_as_cf",
["Material Receipt"].includes(frm.doc.stock_entry_type)
);
frm.toggle_reqd(
"pallet_outbound_qty_cf",
["Material Issue"].includes(frm.doc.stock_entry_type)
);
},
received_as_cf: function (frm) {
frm.toggle_reqd("pallet_qty_cf", frm.doc.received_as_cf == "Pallet");
frm.toggle_reqd(
"loose_cartons_qty_cf",
frm.doc.received_as_cf == "Loose Cartons"
);
frm.toggle_reqd(
"container_type_cf",
frm.doc.received_as_cf == "Loose Cartons"
);
},
refresh: function (frm) {
frappe.db
.get_single_value(
"Third Party Logistics Settings",
"container_item_group"
)
.then((item_group) => {
frm.set_query("container_type_cf", function () {
return {
filters: [["Item", "item_group", "=", item_group]],
};
});
});
},
validate: function (frm) {
let messages = [];
if (frm.doc.stock_entry_type == "Material Issue") {
if (!frm.doc.customer_cf) {
messages.push("Please select a 'For Customer' ");
}
if (!frm.doc.pallet_outbound_qty_cf) {
messages.push("Please set the Outbound Pallet Qty");
}
}
if (frm.doc.stock_entry_type == "Material Receipt") {
if (!frm.doc.customer_cf) {
messages.push("Please select a 'For Customer' ");
}
if (frm.doc.received_as_cf == "Pallet") {
if (!frm.doc.pallet_qty_cf) {
messages.push("Please set the Pallet Qty");
} else if (frm.doc.received_as_cf == "Loose Cartons") {
if (!frm.doc.loose_cartons_qty_cf) {
messages.push("Please set the Loose Cartons Qty");
}
if (!frm.doc.container_type_cf) {
messages.push("Please select a Container Type");
}
}
}
}
if (messages.length) {
frappe.msgprint(__(messages.join("\n")));
frappe.validated = 0;
}
},
});
|
composer install
yarn install
yarn build &
php bin/console doctrine:schema:create
php bin/console server:run 0.0.0.0:80
|
@extends('layouts.app', ['page' => __('Icons'), 'pageSlug' => 'icons'])
@section('content')
<subjects/>
@endsection
@push('js')
<script src="{{ mix('js/app.js') }}"></script>
@endpush
|
;;;; priority-queue-benchmark.asd
(asdf:defsystem #:priority-queue-benchmark
:description "Figure out the fastest priority queue implementation yourself."
:author "Michał \"phoe\" Herda <phoe@disroot.org>"
:license "MIT"
:version "0.0.1"
:serial t
:depends-on
(;; Benchmark dependencies
#:alexandria #:trivial-garbage
;; Contestants
#:pettomato-indexed-priority-queue #:priority-queue #:queues.priority-queue
#:pileup #:bodge-heap #:cl-heap #:heap #:minheap
#:damn-fast-priority-queue #:damn-fast-stable-priority-queue)
:components ((:file "benchmark"))
:perform (test-op (o c) (symbol-call "PRIORITY-QUEUE-BENCHMARK" "RUN")))
|
<?php
namespace Intervention\Gif;
class GraphicControlExtension extends AbstractExtension
{
public const LABEL = "\xF9";
public const BLOCKSIZE = "\x04";
/**
* Delay time of instance
*
* @var integer
*/
protected $delay = 0;
/**
* Disposal method of instance
*
* @var int
*/
protected $disposalMethod = 0;
/**
* Existance flag of transparent color
*
* @var boolean
*/
protected $transparentColorExistance = false;
/**
* Transparent color index
*
* @var integer
*/
protected $transparentColorIndex = 0;
/**
* User input flag
*
* @var boolean
*/
protected $userInput = false;
/**
* Set delay time (1/100 second)
*
* @param int $value
*/
public function setDelay(int $value): self
{
$this->delay = $value;
return $this;
}
/**
* Return delay time (1/100 second)
*
* @return int
*/
public function getDelay(): int
{
return $this->delay;
}
/**
* Set disposal method
*
* @param int $method
* @return self
*/
public function setDisposalMethod(int $method): self
{
$this->disposalMethod = $method;
return $this;
}
/**
* Get disposal method
*
* @return int
*/
public function getDisposalMethod(): int
{
return $this->disposalMethod;
}
/**
* Get transparent color index
*
* @return int
*/
public function getTransparentColorIndex(): int
{
return $this->transparentColorIndex;
}
/**
* Set transparent color index
*
* @param int $index
*/
public function setTransparentColorIndex(int $index): self
{
$this->transparentColorIndex = $index;
return $this;
}
/**
* Get current transparent color existance
*
* @return bool
*/
public function getTransparentColorExistance(): bool
{
return $this->transparentColorExistance;
}
/**
* Set existance flag of transparent color
*
* @param boolean $existance
*/
public function setTransparentColorExistance(bool $existance = true): self
{
$this->transparentColorExistance = $existance;
return $this;
}
/**
* Get user input flag
*
* @return bool
*/
public function getUserInput(): bool
{
return $this->userInput;
}
/**
* Set user input flag
*
* @param bool $value
*/
public function setUserInput(bool $value = true): self
{
$this->userInput = $value;
return $this;
}
}
|
(ns com.yetanalytics.pan.graph
(:require [clojure.spec.alpha :as s]
[loom.graph]
[loom.attr]
[loom.alg]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Graph functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Return a node and its attributes, in the form of [node attribute-map].
;; Only special implementation is in the pattern namespace
(defmulti node-with-attrs #(:type %))
;; Default node-creation function
(defmethod node-with-attrs :default [node]
(let [node-name (:id node)
node-attrs {:type (:type node)
:inScheme (:inScheme node)}]
(vector node-name node-attrs)))
;; Return a vector of all outgoing edges, in the form [src dest attribute-map].
;; Special implementations are found for all concepts + patterns and templates.
(defmulti edges-with-attrs #(:type %))
;; Default edge creation function (returns an empty vector)
(defmethod edges-with-attrs :default [_] [])
(defn collect-edges
"Flatten a collection of edges (ie. vectors of form [src dest attrs] such
that it is a 1D vector of vectors."
[attr-edges]
(reduce concat attr-edges))
;; Thin wrappers for Loom functions
(defn new-digraph
"Init a new directed graph."
[]
(loom.graph/digraph))
(defn nodes
"Given a graph, return its nodes."
[g]
(loom.graph/nodes g))
(defn edges
"Given a graph, return its edges."
[g]
(loom.graph/edges g))
(defn add-nodes
"Add a list or vector of nodes to a graph, where each node has the form
[node attr-map]."
[g nodes]
(reduce (fn [g [node attrs]]
(reduce-kv (fn [g k v] (loom.attr/add-attr g node k v))
(loom.graph/add-nodes g node)
attrs))
g
nodes))
(defn add-edges
"Add a list or vector of directed edges to a graph, where each node has the
form [src dest attr-map]."
[g edges]
(reduce (fn [g [src dest attrs]]
(reduce-kv (fn [g k v] (loom.attr/add-attr g src dest k v))
(loom.graph/add-edges g [src dest])
attrs))
g
edges))
(defn src
"Return the source node of a directed edge."
[edge]
(loom.graph/src edge))
(defn dest
"Return the destination node of a directed edge."
[edge]
(loom.graph/dest edge))
(defn attr
"Return the attribute of a particular node or edge in a graph."
[g node-or-edge attr]
(loom.attr/attr g node-or-edge attr))
(defn in-degree
"Return the in-degree of a node in a digraph."
[g node]
(loom.graph/in-degree g node))
(defn out-degree
"Return the out-degree of a node in a digraph."
[g node]
(loom.graph/out-degree g node))
;; Need to manually rewrite transpose and scc function due to Issue #131 in Loom
(defn- transpose [{in :in adj :adj :as g}] (assoc g :adj in :in adj))
(defn- scc* ;; Copy-paste of code from loom.alg namespace
[g]
(let [gt (transpose g)]
(loop [stack (reverse (loom.alg/post-traverse g))
seen #{}
cc (transient [])]
(if (empty? stack)
(persistent! cc)
(if (seen (first stack))
(recur (rest stack) seen cc)
(let [[c seen]
(loom.alg/post-traverse gt (first stack)
:seen seen
:return-seen true)]
(recur (rest stack)
seen
(conj! cc c))))))))
(defn scc
"Return the strongly-connected components of a digraph as a vector of
vectors. Uses Kosaraju's algorithm."
[g]
(scc* g))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Graph specs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(s/def ::not-self-loop
(fn not-self-loop? [edge] (not= (src edge) (dest edge))))
;; All strongly connected components (subgraphs where all nodes can be
;; reached from any other node in the subgraph) must be singletons. (Imagine
;; a SCC of two nodes - there must be a cycle present; induct from there.)
;; We find our SCCs using Kosaraju's Algorithm (which is what Loom uses in
;; alg/scc), which has a time complexity of O(V+E); we then validate that they
;; all only have one member node.
;;
;; Note that Loom has a built-in function for DAG determination (which does
;; correctly identify self-loops), but we use this algorithm to make our spec
;; errors cleaner.
;;
;; The following specs are to be used on the result of graph/scc.
(s/def ::singleton-scc
(s/coll-of any? :kind vector? :min-count 1 :max-count 1))
(s/def ::singleton-sccs
(s/coll-of ::singleton-scc :kind vector?))
|
#!/usr/bin/env bash
cd ../DIS-java-core && mvn clean install -DskipTests
cd -
mvn clean package
EXAMPLE_TAR=DIS-java-example-1.9.0-deploy.tar.gz
ROOT_DIR=./env
mkdir -p $ROOT_DIR
cd $ROOT_DIR
serverID = 1
for((folderNum=$serverID;folderNum<=128;folderNum = folderNum+23)
do
mkdir node$folderNum
cd node$folderNum
cp -f ../../target/$EXAMPLE_TAR .
tar -zxvf $EXAMPLE_TAR
chmod +x ./bin/*.sh
cd -
done
mkdir client
cd client
cp -f ../../target/$EXAMPLE_TAR .
tar -zxvf $EXAMPLE_TAR
chmod +x ./bin/*.sh
cd -
|
#pragma once
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#ifdef _WIN32
#include <cstdint>
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#endif
#endif
#define FIN return 0;
#define CHARS 256
#define dictionary_add(k,v) strcpy(dictionary(k),v )
#define dictionary_print(k) puts(dctionary(k))
#define dictionary_destroy() dictionary("destroy()")
class memory
{
private:
public:
char bytesAllocated;
void* data;
int32_t size;
memory( void* aowner, int32_t asize, int32_t abytesAllocated );
memory( void* aowner, std::string value );
~memory();
void* add( void* apointer, int32_t asize );
};
char * dictionary(char * k);
|
package com.technocreatives.beckon.mesh.data.serializer
import com.technocreatives.beckon.mesh.data.Model
import com.technocreatives.beckon.mesh.data.ModelData
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
@ExperimentalSerializationApi
@Serializer(forClass = Model::class)
object ModelSerializer : KSerializer<Model> {
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor("Model", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Model) {
return encoder.encodeSerializableValue(ModelData.serializer(), value.toSerialization())
}
override fun deserialize(decoder: Decoder): Model {
val data = decoder.decodeSerializableValue(ModelData.serializer())
return data.toModel()
}
}
|
#/usr/bin/env bash
for i in {1..10000}
do
echo "#### $i ####"
curl -X POST -F image_file=@$1 http://localhost:1234/post > /dev/null
done
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tuweni.evm
import org.apache.tuweni.bytes.Bytes
import org.apache.tuweni.bytes.Bytes32
import org.apache.tuweni.eth.AccountState
import org.apache.tuweni.eth.Address
import org.apache.tuweni.eth.Hash
import org.apache.tuweni.eth.Log
import org.apache.tuweni.eth.repository.BlockchainRepository
import org.apache.tuweni.trie.MerklePatriciaTrie
import org.apache.tuweni.units.bigints.UInt256
import org.apache.tuweni.units.ethereum.Gas
import org.apache.tuweni.units.ethereum.Wei
import org.slf4j.LoggerFactory
/**
* EVM context that records changes to the world state, so they can be applied atomically.
*/
class TransactionalEVMHostContext(
val repository: BlockchainRepository,
val ethereumVirtualMachine: EthereumVirtualMachine,
val depth: Int,
val sender: Address,
val destination: Address,
val value: Bytes,
val code: Bytes,
val gas: Gas,
private val gasPrice: Wei,
val currentCoinbase: Address,
val currentNumber: Long,
val currentTimestamp: Long,
val currentGasLimit: Long,
val currentDifficulty: UInt256
) : HostContext {
companion object {
private val logger = LoggerFactory.getLogger(TransactionalEVMHostContext::class.java)
}
val accountChanges = HashMap<Address, HashMap<Bytes, Bytes32>>()
val logs = mutableListOf<Log>()
val accountsToDestroy = mutableListOf<Address>()
val balanceChanges = HashMap<Address, Wei>()
val warmedUpStorage = HashSet<Bytes>()
/**
* Check account existence function.
*
*
* This function is used by the VM to check if there exists an account at given address.
*
* @param address The address of the account the query is about.
* @return true if exists, false otherwise.
*/
override suspend fun accountExists(address: Address): Boolean {
logger.trace("Entering accountExists")
return accountChanges.containsKey(address) ||
repository.accountsExists(address)
}
override suspend fun getRepositoryStorage(address: Address, keyBytes: Bytes): Bytes32 {
logger.trace("Entering getRepositoryStorage")
val key = Bytes32.wrap(keyBytes)
val value = repository.getAccountStoreValue(address, key)
logger.info("Found value $value")
return value ?: Bytes32.ZERO
}
/**
* Get storage function.
*
*
* This function is used by a VM to query the given account storage entry.
*
* @param address The address of the account.
* @param key The index of the account's storage entry.
* @return The storage value at the given storage key or null bytes if the account does not exist.
*/
override suspend fun getStorage(address: Address, key: Bytes32): Bytes32 {
logger.trace("Entering getStorage")
var value = accountChanges[address]?.get(key)
logger.info("Found value $value")
if (value == null) {
value = repository.getAccountStoreValue(address, key)?.let { UInt256.fromBytes(it) }
}
return value ?: UInt256.ZERO
}
/**
* Set storage function.
*
*
* This function is used by a VM to update the given account storage entry. The VM MUST make
* sure that the account exists. This requirement is only a formality because VM implementations
* only modify storage of the account of the current execution context (i.e. referenced by
* evmc_message::destination).
*
* @param address The address of the account.
* @param key The index of the storage entry.
* @param value The value to be stored.
* @return The effect on the storage item:
* The value of a storage item has been left unchanged: 0 -> 0 and X -> X.
* EVMC_STORAGE_UNCHANGED = 0,
* The value of a storage item has been modified: X -> Y.
* EVMC_STORAGE_MODIFIED = 1,
* A storage item has been modified after being modified before: X -> Y -> Z.
* EVMC_STORAGE_MODIFIED_AGAIN = 2,
* A new storage item has been added: 0 -> X.
* EVMC_STORAGE_ADDED = 3,
* A storage item has been deleted: X -> 0.
* EVMC_STORAGE_DELETED = 4
*/
override suspend fun setStorage(address: Address, key: Bytes, value: Bytes32): Int {
logger.trace("Entering setStorage {} {} {}", address, key, value)
var newAccount = false
accountChanges.computeIfAbsent(address) {
newAccount = true
HashMap()
}
val map = accountChanges[address]!!
val oldValue = map.get(key)
val storageAdded = newAccount || oldValue == null
val storageWasModifiedBefore = map.containsKey(key)
val storageModified = !(value == UInt256.ZERO && oldValue == null) && !value.equals(oldValue)
if (!storageModified) {
return 0
}
map.put(key, value)
if (value.size() == 0) {
return 4
}
if (storageModified) {
if (storageAdded) {
return 3
}
if (storageWasModifiedBefore) {
return 2
}
return 1
}
return 0
}
/**
* Get balance function.
*
*
* This function is used by a VM to query the balance of the given account.
*
* @param address The address of the account.
* @return The balance of the given account or 0 if the account does not exist.
*/
override suspend fun getBalance(address: Address): Wei {
logger.trace("Entering getBalance")
val balance = balanceChanges[address]
balance?.let {
return it
}
val account = repository.getAccount(address)
return account?.balance ?: Wei.valueOf(0)
}
/**
* Get code size function.
*
*
* This function is used by a VM to get the size of the code stored in the account at the given
* address.
*
* @param address The address of the account.
* @return The size of the code in the account or 0 if the account does not exist.
*/
override suspend fun getCodeSize(address: Address): Int {
logger.trace("Entering getCodeSize")
val code = repository.getAccountCode(address)
return code?.size() ?: 0
}
/**
* Get code hash function.
*
*
* This function is used by a VM to get the keccak256 hash of the code stored in the account at
* the given address. For existing accounts not having a code, this function returns keccak256
* hash of empty data.
*
* @param address The address of the account.
* @return The hash of the code in the account or null bytes if the account does not exist.
*/
override suspend fun getCodeHash(address: Address): Bytes32 {
logger.trace("Entering getCodeHash")
val account = repository.getAccount(address)
return account?.codeHash ?: Bytes32.ZERO
}
/**
* Copy code function.
*
*
* This function is used by an EVM to request a copy of the code of the given account to the
* memory buffer provided by the EVM. The Client MUST copy the requested code, starting with the
* given offset, to the provided memory buffer up to the size of the buffer or the size of the
* code, whichever is smaller.
*
* @param address The address of the account.
* @return A copy of the requested code.
*/
override suspend fun getCode(address: Address): Bytes {
logger.trace("Entering getCode")
val code = repository.getAccountCode(address)
return code ?: Bytes.EMPTY
}
/**
* Selfdestruct function.
*
*
* This function is used by an EVM to SELFDESTRUCT given contract. The execution of the
* contract will not be stopped, that is up to the EVM.
*
* @param address The address of the contract to be selfdestructed.
* @param beneficiary The address where the remaining ETH is going to be transferred.
*/
override suspend fun selfdestruct(address: Address, beneficiary: Address) {
logger.trace("Entering selfdestruct")
accountsToDestroy.add(address)
val account = repository.getAccount(address)
val beneficiaryAccountState = repository.getAccount(beneficiary)
if (beneficiaryAccountState === null) {
repository.storeAccount(
beneficiary,
AccountState(
UInt256.ZERO, Wei.valueOf(0),
Hash.fromBytes(
MerklePatriciaTrie.storingBytes().rootHash()
),
Hash.hash(Bytes.EMPTY)
)
)
}
account?.apply {
val balance = balanceChanges.putIfAbsent(beneficiary, account.balance)
balance?.let {
balanceChanges[beneficiary] = it.add(account.balance)
}
}
logger.trace("Done selfdestruct")
}
/**
* This function supports EVM calls.
*
* @param msg The call parameters.
* @return The result of the call.
*/
override suspend fun call(evmMessage: EVMMessage): EVMResult {
logger.trace("Entering call")
val result = ethereumVirtualMachine.executeInternal(
evmMessage.sender,
evmMessage.destination,
evmMessage.value,
Bytes.EMPTY,
evmMessage.inputData,
evmMessage.gas,
depth = depth + 1,
hostContext = this
)
return result
}
/**
* Get transaction context function.
*
*
* This function is used by an EVM to retrieve the transaction and block context.
*
* @return The transaction context.
*/
override fun getTxContext(): Bytes? {
logger.trace("Entering getTxContext")
return Bytes.concatenate(
gasPrice.toBytes(),
sender, currentCoinbase, Bytes.ofUnsignedLong(currentNumber),
Bytes.ofUnsignedLong(currentTimestamp),
Bytes.ofUnsignedLong(currentGasLimit),
currentDifficulty.toBytes(),
UInt256.ONE.toBytes()
)
}
override fun getBlockHash(number: Long): Bytes32 {
logger.trace("Entering getBlockHash")
val listOfCandidates = repository.findBlockByHashOrNumber(UInt256.valueOf(number).toBytes())
return listOfCandidates.firstOrNull() ?: Bytes32.ZERO
}
override fun emitLog(address: Address, data: Bytes, topics: List<Bytes32>) {
logger.trace("Entering emitLog")
logs.add(Log(Address.fromBytes(Bytes.wrap(address)), data, topics))
}
override fun warmUpAccount(address: Address): Boolean =
!warmedUpStorage.add(address)
override fun warmUpStorage(address: Address, key: UInt256): Boolean =
!warmedUpStorage.add(Bytes.concatenate(address, Bytes.fromHexString("0x0f"), key))
override fun getGasPrice() = gasPrice
override fun getGasLimit() = currentGasLimit
override fun getBlockNumber() = currentNumber
override fun getBlockHash() = getBlockHash(currentNumber)
override fun getCoinbase() = currentCoinbase
override fun timestamp(): UInt256 = UInt256.valueOf(currentTimestamp)
override fun getDifficulty() = currentDifficulty
override fun increaseBalance(address: Address, amount: Wei) {
balanceChanges[address] = balanceChanges[address]?.add(amount) ?: amount
}
override suspend fun setBalance(address: Address, balance: Wei) {
balanceChanges[address] = getBalance(address).subtract(balance)
}
}
|
package org.codehaus.xfire.client;
import java.util.List;
import javax.xml.stream.XMLStreamReader;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.XFireRuntimeException;
import org.codehaus.xfire.exchange.MessageExchange;
import org.codehaus.xfire.exchange.OutMessage;
import org.codehaus.xfire.fault.XFireFault;
import org.codehaus.xfire.handler.HandlerPipeline;
import org.codehaus.xfire.service.Binding;
import org.codehaus.xfire.service.OperationInfo;
import org.codehaus.xfire.service.binding.ServiceInvocationHandler;
import org.codehaus.xfire.soap.Soap11;
import org.codehaus.xfire.soap.Soap11Binding;
import org.codehaus.xfire.soap.Soap12;
import org.codehaus.xfire.soap.Soap12Binding;
public class Invocation
{
static final String CONTEXT_KEY = "client.call";
private Object[] response;
private MessageContext context;
private Exception fault;
private Client client;
public Invocation(Client client)
{
this.client = client;
}
public MessageContext getContext()
{
return context;
}
Object[] invoke(OperationInfo op, OutMessage msg) throws Exception
{
try
{
msg.setChannel(client.getOutChannel());
// TODO this should probably be in a seperate handler.
// We'll have to address this when we add REST support.
Binding binding = client.getBinding();
if (binding instanceof Soap11Binding)
msg.setSoapVersion(Soap11.getInstance());
else if (binding instanceof Soap12Binding)
msg.setSoapVersion(Soap12.getInstance());
context = new MessageContext();
context.setService(client.getService());
context.setXFire(client.getXFire());
context.setBinding(binding);
context.setProperty(Client.CLIENT_MODE, Boolean.TRUE);
context.setClient(client);
context.setProperty(CONTEXT_KEY, this);
MessageExchange exchange = new MessageExchange(context);
exchange.setOperation(op);
exchange.setOutMessage(msg);
context.setCurrentMessage(msg);
HandlerPipeline outPipe = new HandlerPipeline(client.getXFire().getOutPhases());
outPipe.addHandlers(client.getXFire().getOutHandlers());
outPipe.addHandlers(client.getOutHandlers());
outPipe.addHandlers(client.getTransport().getOutHandlers());
context.setOutPipeline(outPipe);
ServiceInvocationHandler.writeHeaders(context, null);
outPipe.invoke(context);
}
catch (Exception e1)
{
throw XFireFault.createFault(e1);
}
waitForResponse();
if (fault != null)
{
Exception localFault = fault;
fault = null;
throw localFault;
}
Object[] localResponse = response;
response = null;
return localResponse;
}
Object[] invoke(OperationInfo op, XMLStreamReader reader) throws Exception{
OutMessage msg = new OutMessage(client.getUrl());
msg.setSerializer(new RawDataSerializer(reader));
return invoke(op,msg);
}
Object[] invoke(OperationInfo op, Object[] params) throws Exception
{
OutMessage msg = new OutMessage(client.getUrl());
msg.setBody(params);
return invoke(op,msg);
}
/**
* Waits for a response from the service.
*/
protected void waitForResponse()
{
/**
* If this is an asynchronous channel, we'll need to sleep() and wait
* for a response. Channels such as HTTP will have the response set
* by the time we get to this point.
*/
if (!client.getOutChannel().isAsync() ||
response != null ||
fault != null ||
!context.getExchange().getOperation().hasOutput())
{
return;
}
int count = 0;
while (response == null && fault == null && count < client.getTimeout())
{
try
{
Thread.sleep(50);
count += 50;
}
catch (InterruptedException e)
{
break;
}
}
if(response == null && fault == null)
throw new XFireRuntimeException("Invocation timeout when waiting for resonse.");
}
public void receive(Object response)
{
this.response = ((List) response).toArray();
}
public void receiveFault(Exception fault)
{
this.fault = fault;
}
}
|
/*
Copyright 2013 Twitter, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.twitter.summingbird.chill
import org.scalacheck.{ Arbitrary, Properties }
import org.scalacheck.Prop._
import org.specs2.mutable._
import com.twitter.chill._
import com.twitter.summingbird.batch._
object SerializationLaws extends Properties("SerializationLaws") {
implicit val batchId: Arbitrary[BatchID] =
Arbitrary(Arbitrary.arbitrary[Long].map(BatchID(_)))
implicit val timestamp: Arbitrary[Timestamp] =
Arbitrary(Arbitrary.arbitrary[Long].map(Timestamp(_)))
implicit def batchSer: KSerializer[BatchID] = new BatchIDSerializer
implicit def timestampSer: KSerializer[Timestamp] = new TimestampSerializer
def round[T](ser: KSerializer[T], t: T): T = {
val kinst = (new ScalaKryoInstantiator)
.withRegistrar({ (k: Kryo) => k.register(t.getClass, ser); () })
KryoPool.withBuffer(1, kinst, 100, 10000).deepCopy(t)
}
def roundTrips[T:Arbitrary:KSerializer:Equiv] = forAll { (t: T) =>
val kser = implicitly[KSerializer[T]]
Equiv[T].equiv(round(kser, t), t)
}
property("BatchID roundtrips with Kryo") = roundTrips[BatchID]
property("Timestamp roundtrips with Kryo") = roundTrips[Timestamp]
}
|
export opt_gauss_newton!
"""
(iter,resnorm)=opt_gauss_newton!(
graph,
objfun,
discr;
maxit = 100,
logger = 0,
errtype = :abserr,
stoptol = 1e-6,
cref = get_all_cref(graph),
input = :A,
γ0 = 1.0,
linlsqr = :backslash,
droptol = 0,
)
Applies the Gauss–Newton algorithm to solve the nonlinear least squares problem:
Fit the output of the `graph` to the values of `objfun`, in the points `discr`.
The variable `graph` is modified during the iterations. The function returns the
iteration `iter` where it terminated, and the corresponding residual norm
`resnorm`.
The kwargs are as follows:
- `maxit` determines the maximum number of iterations. If `logger` has a
value >0, then the intermediate results are printed.
- `errtype` determines the error type measured, see `adjust_for_errtype!`.
- `stoptol` is the corresponding stopping tolerance.
- `cref` is a `Vector{Tuple{Symbol,Int}}` that determines which coefficients
of `graph` that are considered free variables and optimized.
- `input` is the label corresponding to the input node of the graph.
- The stepsize can be scaled with `γ0`.
- `linlsqr` and `droptol` determines how the inner linear least squares
problem is solved; see [`solve_linlsqr!`](@ref).
"""
function opt_gauss_newton!(
graph,
objfun,
discr;
maxit = 100,
logger = 0,
errtype = :abserr,
stoptol = 1e-6,
cref = get_all_cref(graph),
input = :A,
γ0 = 1.0,
linlsqr = :backslash,
droptol = 0,
)
resnorm = Inf
iter = maxit
vals = init_vals_eval_graph!(graph, discr, nothing, input)
objfun_vals = objfun.(discr)
for j = 1:maxit
F = eval_graph(graph, discr, vals = vals, input = input)
res = F - objfun_vals
Jac = eval_jac(graph, discr, cref, vals = vals, input = input)
adjust_for_errtype!(Jac, res, objfun_vals, errtype)
resnorm = norm(res)
if (logger > 0)
@show j, resnorm
end
if (resnorm < stoptol)
iter = j
break
end
d = solve_linlsqr!(Jac, res, linlsqr, droptol)
x = get_coeffs(graph, cref)
x -= γ0 * d
set_coeffs!(graph, x, cref)
end
return (iter, resnorm)
end
|
<?php if ( ! defined('YPATH')) exit('Access Denied !');
/**
* Yalamo framework
*
* A fast,light, and constraint-free Php framework.
*
* @package Yalamo
* @author Evance Soumaoro
* @copyright Copyright (c) 2009 - 2011, Evansofts.
* @license http://projects.evansofts.com/yalamof/license.html
* @link http://evansofts.com
* @version Version 0.1
* @filesource Core.php
*/
/*
* CORE HELPER
*
* Includes usefull functions for user that want to use the framework in procedural mode
* about core functionalities. These functions can be called from oo mode
*/
function AppConfig($key){
return Environment::Application($key);
}
function loadModule($modules){
$load=new Loader();
if(is_array($modules)){
$load->Module($modules);
return;
}
$load->Modules($modules);
}
function loadHelper($helpers){
$load=new Loader();
if(is_array($helpers)){
$load->Helper($helpers);
return;
}
$load->Helpers($helpers);
}
function loadExtension($extensions){
$load=new Loader();
if(is_array($extensions)){
$load->Extension($extensions);
return;
}
$load->Extensions($extensions);
}
function loadModel($model){
$load=new Loader();
return $load->Model($model);
}
function loadView($view, $data=null){
$load=new Loader();
$load->View($view, $data);
}
function loadController($controller){
$load=new Loader();
$load->Controller($controller);
}
|
use ast::*;
use namespace::Namespace;
use line_info::LineInfo;
use std::rc::Rc;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DebugInfo {
pub kind: DebugKind,
pub segment_span: LineInfo,
pub common: CommonInfo,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DebugKind {
VarSub(Namespace, Path),
StrSub, //TODO: add detailed information for var subs WITHIN string
CmdSub(Box<DebugInfo>, Vec<DebugInfo>),
CmdExec(Box<DebugInfo>, Vec<DebugInfo>),
Literal,
VarInsertion,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommonInfo {
pub root_stmt_span: LineInfo,
pub cmd_span: LineInfo,
pub original_string: Rc<String>,
}
pub trait InfoGenerator {
fn info(&self) -> CommonInfo;
}
#[macro_use]
macro_rules! dliteral {
($segment_span: expr, $common: expr) => {
DebugInfo {
kind: DebugKind::Literal,
segment_span: $segment_span,
common: $common
}
}
}
#[macro_use]
macro_rules! dvar_sub {
($namespace: expr, $path: expr, $segment_span: expr, $common: expr) => {
DebugInfo {
kind: DebugKind::VarSub($namespace, $path),
segment_span: $segment_span,
common: $common
}
}
}
#[macro_use]
macro_rules! dcmd_sub {
($cmd: expr, $debug_info: expr, $segment_span: expr, $common: expr) => {
DebugInfo {
kind: DebugKind::CmdSub($cmd, $debug_info),
segment_span: $segment_span,
common: $common,
}
}
}
#[macro_use]
macro_rules! dcmd_exec {
($cmd: expr, $debug_info: expr, $segment_span: expr, $common: expr) => {
DebugInfo {
kind: DebugKind::CmdExec($cmd, $debug_info),
segment_span: $segment_span,
common: $common,
}
}
}
#[macro_use]
macro_rules! dstr_sub {
($segment_span: expr, $common: expr) => {
DebugInfo {
kind: DebugKind::StrSub,
segment_span: $segment_span,
common: $common,
}
}
}
|
package app.allever.android.lib.core.base
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.WindowManager
abstract class AbstractDialog : Dialog {
constructor(
context: Context,
styleRes: Int
) : super(context, styleRes) {
//宽度占满屏
val window = window
window?.setGravity(getGravity())
// 把 DecorView 的默认 padding 取消,同时 DecorView 的默认大小也会取消
window?.decorView?.setPadding(0, 0, 0, 0)
val layoutParams = window?.attributes
// 设置宽度
layoutParams?.width = WindowManager.LayoutParams.MATCH_PARENT
window?.attributes = layoutParams
// 给 DecorView 设置背景颜色,很重要,不然导致 Dialog 内容显示不全,有一部分内容会充当 padding,上面例子有举出
window?.decorView?.setBackgroundColor(Color.TRANSPARENT)
setContentView(getLayoutId())
}
init {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initView()
}
abstract fun getLayoutId(): Int
abstract fun initView()
open fun getGravity(): Int {
return Gravity.BOTTOM
}
}
|
TODO:
* What are filters?
* List+explain all existing filters (pongo2 + pongo2-addons)
Implemented filters so far which needs documentation:
* escape
* e (alias of `escape`)
* safe
* escapejs
* add
* addslashes
* capfirst
* center
* cut
* date
* default
* default_if_none
* divisibleby
* first
* floatformat
* get_digit
* iriencode
* join
* last
* length
* length_is
* linebreaks
* linebreaksbr
* linenumbers
* ljust
* lower
* make_list
* phone2numeric
* pluralize
* random
* removetags
* rjust
* slice
* stringformat
* striptags
* time
* title
* truncatechars
* truncatechars_html
* truncatewords
* truncatewords_html
* upper
* urlencode
* urlize
* urlizetrunc
* wordcount
* wordwrap
* yesno
* filesizeformat*
* slugify*
* truncatesentences*
* truncatesentences_html*
* markdown*
* intcomma*
* ordinal*
* naturalday*
* timesince*
* timeuntil*
* naturaltime*
Filters marked with * are available through [pongo2-addons](https://github.com/flosch/pongo2-addons).
|
#!/usr/bin/bash
pushd traditional/minecraft
# molecule destroy --all
sed -i -e 's/server.jar/spigot.jar/' templates/minecraft.service.j2
git add templates/minecraft.service.j2
git commit -m "Breaking the role for my demo"
git push origin master
molecule converge && WAIT_SECONDS=5 molecule verify
molecule converge -s vagrant && WAIT_SECONDS=5 molecule verify -s vagrant
popd
pushd kubernetes
# molecule destroy --all
molecule converge && molecule verify
molecule converge -s operator && molecule verify -s operator
popd
export KUBECONFIG=~/.cache/molecule/kubernetes/operator/.kubeconfig
doitlive play demo.sh
|
class BookRoutePath {
BookRoutePath(this.id, this.isUnknown);
BookRoutePath.home()
: this.id = null,
this.isUnknown = false;
BookRoutePath.details(this.id) : isUnknown = false;
BookRoutePath.unknown()
: this.id = null,
this.isUnknown = true;
final int? id;
final bool isUnknown;
bool get isHomePage => id == null;
bool get isDetailPage => id != null;
}
|
using System;
using RiskAnalysisTool.Instruments;
namespace RiskAnalysisTool.MobileApp.ViewModels
{
internal class BondDetailViewModel : InstrumentDetailViewModel<Bond>
{
private DateTime _maturity;
private double _price;
public DateTime Maturity
{
get { return _maturity; }
set { SetProperty(ref _maturity, value); }
}
public double Price
{
get { return _price; }
set { SetProperty(ref _price, value); }
}
public override void LoadModel(Bond instrument)
{
base.LoadModel(instrument);
Maturity = instrument.MaturityDate.Date;
Price = instrument.Price;
}
public override void UpdateModel(Bond instrument)
{
base.UpdateModel(instrument);
instrument.MaturityDate = Maturity.Date;
instrument.Price = Price;
}
}
}
|
# eGov-Base
전자정보프레임워크 초기 설정
|<center>No<center>|<center>적용기술<center>|<center>Version<center>|
|:------:|:------:|:------:|
|<center>1<center>|<center>Java-OpenJDK<center> |<center>1.8<center>|
|<center>2<center>|<center>eGovFramework<center> |<center>3.8<center>|
|<center>3<center>|<center>Tomcat<center> |<center>8.5<center>|
|<center>4<center>|<center>Dynamic Web Moudule version<center> |<center>3.1<center>|
|<center>5<center>|<center>SpringFramwork<center> |<center>4.3.6<center>|
|
if __name__ == "__main__":
import sys
sys.path.insert(0, "..")
sys.path.insert(0, "../..")
import unittest
from hamcrest.core.core.isanything import *
from hamcrest_unit_test.matcher_test import MatcherTest
__author__ = "Jon Reid"
__copyright__ = "Copyright 2011 hamcrest.org"
__license__ = "BSD, see License.txt"
class IsAnythingTest(MatcherTest):
def testAlwaysEvaluatesToTrue(self):
self.assert_matches("None", anything(), None)
self.assert_matches("object", anything(), object())
self.assert_matches("string", anything(), "hi")
def testHasUsefulDefaultDescription(self):
self.assert_description("ANYTHING", anything())
def testCanOverrideDescription(self):
description = "DESCRIPTION"
self.assert_description(description, anything(description))
def testMatchAlwaysSucceedsSoShouldNotGenerateMismatchDescription(self):
self.assert_no_mismatch_description(anything(), "hi")
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/env bash
SRC="/apc/RecSys-MPD" # source code directory
META="/apc/metadata" # metadata directory
CID="" # spotify developer client ID
CSEC="" # spotify developer client secret
# go to source code directory and update project
cd $SRC
git pull
# run audio feature extraction application
python3 $SRC"/python/collect_audio_features.py" $CID $CSEC $META
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:flutter/material.dart';
import 'package:molarity/widgets/chemoinfomatics/data.dart';
class PreferencedCompoundsProvider extends ChangeNotifier {
final List<CompoundData> savedCompounds = [];
void removeSavedCompountAt(int index) {
savedCompounds.removeAt(index);
notifyListeners();
}
void addSavedCompound(CompoundData compound) {
savedCompounds.add(compound);
notifyListeners();
}
}
final preferencedCompoundsProvider = ChangeNotifierProvider((ref) => PreferencedCompoundsProvider());
|
package api
import (
"github.com/cmatrixprobe/proxygool/store"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"net/http"
)
// Run HTTP server.
func Run() {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
r.GET("/", RandomProxyHandler)
r.GET("/https", HTTPSProxyHandler)
server := viper.Sub("server")
ip := server.GetString("host")
port := server.GetString("port")
address := ip + ":" + port
logrus.Fatal(r.Run(address))
}
// RandomProxyHandler returns a random JSON-encoded address.
func RandomProxyHandler(c *gin.Context) {
c.JSON(http.StatusOK, store.RandomOne())
}
// HTTPSProxyHandler returns a random JSON-encoded https protocol address.
func HTTPSProxyHandler(c *gin.Context) {
c.JSON(http.StatusOK, store.RandomHTTPS())
}
|
#pragma once
#ifndef TTCPIP_H
#define TTCPIP_H
#include <memory>
#include "tcommon.h"
#include <QString>
#include <QThread>
//---------------------------------------------------------------------
#ifdef TFARMAPI
#undef TFARMAPI
#endif
#ifdef WIN32
#ifdef TFARM_EXPORTS
#define TFARMAPI __declspec(dllexport)
#else
#define TFARMAPI __declspec(dllimport)
#endif
#else
#define TFARMAPI
#endif
//---------------------------------------------------------------------
class TTcpIpServerImp;
class TFARMAPI TTcpIpServer : public QThread {
int m_exitCode;
public:
TTcpIpServer(int port);
virtual ~TTcpIpServer();
int getPort() const;
void run();
int shutdown();
virtual void onReceive(int socket, const QString &data) = 0;
void sendReply(int socket, const QString &reply);
int getExitCode() const;
private:
std::shared_ptr<TTcpIpServerImp> m_imp;
};
//---------------------------------------------------------------------
enum {
OK,
STARTUP_FAILED,
HOST_UNKNOWN,
SOCKET_CREATION_FAILED,
CONNECTION_FAILED,
CONNECTION_REFUSED,
CONNECTION_TIMEDOUT,
SEND_FAILED,
RECEIVE_FAILED
};
class TFARMAPI TTcpIpClient {
public:
TTcpIpClient();
~TTcpIpClient();
int connect(const QString &name, const QString &addr, int port, int &sock);
int disconnect(int sock);
int send(int sock, const QString &data);
int send(int sock, const QString &data, QString &reply);
};
#endif
|
# oop.py
"""Introductory Labs: Object Oriented Programming.
<Name>
<Class>
<Date>
"""
class Backpack(object):
"""A Backpack object class. Has a name and a list of contents.
Attributes:
name (str): the name of the backpack's owner.
contents (list): the contents of the backpack.
"""
# Problem 1: Modify __init__() and put(), and write dump().
def __init__(self, name):
"""Set the name and initialize an empty contents list.
Inputs:
name (str): the name of the backpack's owner.
Returns:
A Backpack object wth no contents.
"""
self.name = name
self.contents = []
def put(self, item):
"""Add 'item' to the backpack's list of contents."""
self.contents.append(item)
def take(self, item):
"""Remove 'item' from the backpack's list of contents."""
self.contents.remove(item)
# Magic Methods -----------------------------------------------------------
# Problem 3: Write __eq__() and __str__().
def __add__(self, other):
"""Add the number of contents of each Backpack."""
return len(self.contents) + len(other.contents)
def __lt__(self, other):
"""Compare two backpacks. If 'self' has fewer contents
than 'other', return True. Otherwise, return False.
"""
return len(self.contents) < len(other.contents)
# An example of inheritance. You are not required to modify this class.
class Knapsack(Backpack):
"""A Knapsack object class. Inherits from the Backpack class.
A knapsack is smaller than a backpack and can be tied closed.
Attributes:
name (str): the name of the knapsack's owner.
color (str): the color of the knapsack.
max_size (int): the maximum number of items that can fit
in the knapsack.
contents (list): the contents of the backpack.
closed (bool): whether or not the knapsack is tied shut.
"""
def __init__(self, name, color, max_size=3):
"""Use the Backpack constructor to initialize the name, color,
and max_size attributes. A knapsack only holds 3 item by default
instead of 5.
Inputs:
name (str): the name of the knapsack's owner.
color (str): the color of the knapsack.
max_size (int): the maximum number of items that can fit
in the knapsack. Defaults to 3.
Returns:
A Knapsack object with no contents.
"""
Backpack.__init__(self, name, color, max_size)
self.closed = True
def put(self, item):
"""If the knapsack is untied, use the Backpack.put() method."""
if self.closed:
print("I'm closed!")
else:
Backpack.put(self, item)
def take(self, item):
"""If the knapsack is untied, use the Backpack.take() method."""
if self.closed:
print("I'm closed!")
else:
Backpack.take(self, item)
# Problem 2: Write a 'Jetpack' class that inherits from the 'Backpack' class.
# Problem 4: Write a 'ComplexNumber' class.
|
# frozen_string_literal: true
FactoryBot.define do
factory :offender_category, class: HmppsApi::OffenderCategory do
initialize_with { HmppsApi::OffenderCategory.new(attributes.reject { |_k, v| v.nil? }.stringify_keys) }
classificationCode { 'A' }
classification { 'Cat A' }
approvalDate { 3.days.ago }
trait :without_approval_date do
approvalDate { nil }
assessmentDate { 5.days.ago }
end
# Men's categories
trait :cat_a do
classificationCode { 'A' }
classification { 'Cat A' }
end
trait :cat_b do
classificationCode { 'B' }
classification { 'Cat B' }
end
trait :cat_c do
classificationCode { 'C' }
classification { 'Cat C' }
end
trait :cat_d do
classificationCode { 'D' }
classification { 'Cat D' }
end
# Women's categories
trait :female_restricted do
classificationCode { 'Q' }
classification { 'Female Restricted' }
end
trait :female_closed do
classificationCode { 'R' }
classification { 'Female Closed' }
end
trait :female_semi do
classificationCode { 'S' }
classification { 'Female Semi' }
end
trait :female_open do
classificationCode { 'T' }
classification { 'Female Open' }
end
end
end
|
/*
* Copyright 2018 Analytics Zoo 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.zoo.examples.localEstimator
import java.io.ByteArrayOutputStream
import java.net.URI
import java.nio.ByteBuffer
import java.nio.file.{Files, Paths}
import com.intel.analytics.bigdl.dataset.ByteRecord
import com.intel.analytics.bigdl.dataset.image.LabeledGreyImage
import com.intel.analytics.zoo.pipeline.estimator.EstimateSupportive
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FSDataInputStream, FileSystem, Path}
import org.apache.hadoop.io.IOUtils
import org.slf4j.LoggerFactory
object MnistDataLoader extends ImageProcessing with EstimateSupportive {
val logger = LoggerFactory.getLogger(getClass)
val trainMean = 0.13066047740239506
val trainStd = 0.3081078
val testMean = 0.13251460696903547
val testStd = 0.31048024
def loadTrainData(imageDirPath: String): Array[LabeledGreyImage] = {
val records = timing("load bytes from bin") {
val trainDataPath = imageDirPath + "/train-images-idx3-ubyte"
val trainLabelPath = imageDirPath + "/train-labels-idx1-ubyte"
loadData(trainDataPath, trainLabelPath)
}
logger.info(s"${records.length} train data loaded")
val labeledGreyImages = timing("transfer bytes to labeledGreyImages") {
records.map(record => bytesToGreyImage(record, 28, 28))
}
val normalized = timing("normalize labeledGreyImages") {
labeledGreyImages.map(record => greyImgNormalize(record, trainMean, trainStd))
}
normalized
}
def loadTestData(imageDirPath: String): Array[LabeledGreyImage] = {
val records = timing("load bytes from bin") {
val validationDataPath = imageDirPath + "/t10k-images-idx3-ubyte"
val validationLabelPath = imageDirPath + "/t10k-labels-idx1-ubyte"
MnistDataLoader.loadData(validationDataPath, validationLabelPath)
}
logger.info(s"${records.length} train data loaded")
val labeledGreyImages = timing("transfer bytes to labeledGreyImages") {
records.map(record => bytesToGreyImage(record, 28, 28))
}
val normalized = timing("normalize labeledGreyImages") {
labeledGreyImages.map(record => greyImgNormalize(record, testMean, testStd))
}
normalized
}
def loadData(featureFile: String, labelFile: String): Array[ByteRecord] = {
val featureBuffer = if (featureFile.startsWith("hdfs:")) {
ByteBuffer.wrap(readHdfsByte(featureFile))
} else {
ByteBuffer.wrap(Files.readAllBytes(Paths.get(featureFile)))
}
val labelBuffer = if (featureFile.startsWith("hdfs:")) {
ByteBuffer.wrap(readHdfsByte(labelFile))
} else {
ByteBuffer.wrap(Files.readAllBytes(Paths.get(labelFile)))
}
val labelMagicNumber = labelBuffer.getInt()
require(labelMagicNumber == 2049, "labelMagicNumber should be 2049")
val featureMagicNumber = featureBuffer.getInt()
require(featureMagicNumber == 2051, "featureMagicNumber should be 2051")
val labelCount = labelBuffer.getInt()
val featureCount = featureBuffer.getInt()
require(labelCount == featureCount)
val rowNum = featureBuffer.getInt()
val colNum = featureBuffer.getInt()
val result = new Array[ByteRecord](featureCount)
var i = 0
while (i < featureCount) {
val img = new Array[Byte]((rowNum * colNum))
var y = 0
while (y < rowNum) {
var x = 0
while (x < colNum) {
img(x + y * colNum) = featureBuffer.get()
x += 1
}
y += 1
}
result(i) = ByteRecord(img, labelBuffer.get().toFloat + 1.0f)
i += 1
}
result
}
private def readHdfsByte(fileName: String): Array[Byte] = {
val src: Path = new Path(fileName)
var fs: FileSystem = null
var in: FSDataInputStream = null
try {
fs = FileSystem.newInstance(new URI(fileName), new Configuration())
in = fs.open(src)
val byteArrayOut = new ByteArrayOutputStream()
IOUtils.copyBytes(in, byteArrayOut, 1024, true)
byteArrayOut.toByteArray
} finally {
if (null != in) in.close()
if (null != fs) fs.close()
}
}
}
|
package manifold_test
import (
"context"
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
"github.com/manifoldco/go-manifold/integrations"
"github.com/manifoldco/go-manifold/integrations/primitives"
)
func TestManifoldResource_CustomCredential(t *testing.T) {
conf := `
resource "manifold_credential" "test_credential" {
project = "terraform"
resource = "custom-resource3-1"
key = "NEW_KEY"
value = "my-value"
}
`
resource.Test(t, resource.TestCase{
PreCheck: testProviderPreCheck(t),
Providers: testProviders,
CheckDestroy: testAPICredentialDestroy,
Steps: []resource.TestStep{
{
Config: conf,
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("manifold_credential.test_credential", "id"),
resource.TestCheckResourceAttrSet("manifold_credential.test_credential", "value"),
),
},
},
})
}
func testAPICredentialDestroy(s *terraform.State) error {
cl := testProviders["manifold"].(*schema.Provider).Meta().(*integrations.Client)
for _, rs := range s.RootModule().Resources {
if rs.Type != "manifold_credential" {
continue
}
ctx := context.Background()
projectLabel := rs.Primary.Attributes["project"]
resourceLabel := rs.Primary.Attributes["resource"]
res := &primitives.Resource{Name: resourceLabel}
resource, err := cl.GetResource(ctx, &projectLabel, res)
if err != nil {
return err
}
credentials, err := cl.Resources.GetConfig(ctx, resource.ID)
if err != nil {
return err
}
if credentials == nil {
return nil
}
creds := *credentials
if _, ok := creds[rs.Primary.Attributes["key"]]; ok {
return fmt.Errorf("Credential '%s' still exists", rs.Primary.ID)
}
}
return nil
}
|
# GridArrays.jl Documentation
For a full description of the functionality use the manual:
```@contents
Pages = ["man/GridArrays.md"]
```
|
import 'instruction.dart';
/// The base class to derive from when implementing assembler syntax helpers
abstract class AsmBuilderBase {
List<String> _instructions = [];
AsmBuilderBase();
/// Builds the string to be assembled by the Keystone engine
String build() {
return _instructions.join(';');
}
/// Resets the instruction list
void reset() {
_instructions = [];
}
/// Appends an [instruction] to the instructions list
AsmBuilderBase append(Instruction instruction) {
_instructions.add(instruction.format());
return this;
}
/// Appends a [raw] string to the instructions list
AsmBuilderBase appendRaw(String raw) {
_instructions.add(raw);
return this;
}
}
|
package Parse::Template::Directives::JS;
use strict;
our $VERSION = 0;
use Perl::Module;
use Error::Logical;
use Data::Format::XFR;
use Data::Hub::Util qw(:all);
our $Xfr = Data::Format::XFR->new('base64');
#
# XXX Changes made to the /sys/response/head need to be reflected
# in js.lsn.includeHeadJS
#
sub new {
my $class = ref($_[0]) ? ref(shift) : shift;
bless {
'var' => [\&_js_var],
'extend' => [\&_js_extend],
'src' => [\&_js_src],
'event' => [\&_js_event],
'closure' => [\&_js_closure],
'global' => [\&_js_global],
'*' => [\&_js],
}, $class;
}
# :js:var /data/colors.hf
sub _js_var {
my $parser = shift;
my $value = $parser->_get_data_value(@_);
'js.data.xfr.parse(\'' . $Xfr->format($value) . '\')';
}
# :js:extend 'local'
# ...
# :end js:extend
sub _js_extend {
my $parser = shift;
my $name = shift;
my $opts = my_opts(\@_, {inline => 0});
my $spec = shift;
my $value = '';
if (my $block = _my_slurp($parser, $name, $opts)) {
$parser->_invoke(text => $block, out => \$value);
my $ns = $parser->get_value_str(\$spec);
my $content = $parser->{Hub}->{"/sys/response/head/extend/js/$ns"} || '';
$parser->{Hub}->{"/sys/response/head/extend/js/$ns"} = "$content\n$value";
}
$parser->get_ctx->{'collapse'} = 1;
'';
}
# :js:src '/res/js/livesite.js'
# :js:src '/res/js/livesite.js' -priority
sub _js_src {
my $parser = shift;
my $name = shift;
my $opts = my_opts(\@_, {inline => 0});
my $src = shift;
my %args = @_;
my %attrs = ();
foreach my $k (keys %args) {
$attrs{$k} = $parser->get_compiled_value(\$args{$k});
}
$attrs{'type'} ||= 'text/javascript';
$attrs{'src'} = $parser->_mk_url($parser->get_compiled_value(\$src));
if ($$opts{'inline'}) {
# By setting this `have_linked` semiphore, the normal responder will suppress
# this URL from being emitted should it also be inlcuded in a non-inline
# js directive.
my $have_linked = $parser->{Hub}->{"/sys/response/head/have_linked"} ||= {};
$$have_linked{$attrs{'src'}} = 1;
my $attr_str = join ' ', map {$_ . '=' . _quote($attrs{$_})} sort keys %attrs;
$parser->get_ctx->{'collapse'} = 0;
return "<script $attr_str></script>";
} else {
my $links = $parser->{Hub}->{"/sys/response/head/links/js"} ||= [];
push @$links, \%attrs;
}
$parser->get_ctx->{'collapse'} = 1;
'';
}
# :js:event 'window,load'
# ...
# :end js:event
sub _js_event {
my $parser = shift;
my $name = shift;
my $opts = my_opts(\@_);
my $event = shift;
my $value = '';
if (my $block = _my_slurp($parser, $name, $opts)) {
$parser->_invoke(text => $block, out => \$value);
my ($target, $event_name)
= split /[\s;,]\s*/, $parser->get_value_str(\$event);
$parser->{Hub}->{"/sys/response/head/events/js/$target/<next>"} = {
key => $event_name,
value => $value,
};
}
$parser->get_ctx->{'collapse'} = 1;
'';
}
# :js:closure
# ...
# :end js:closure
sub _js_closure {
my $parser = shift;
my $name = shift;
my $opts = my_opts(\@_);
my $value = '';
if (my $block = _my_slurp($parser, $name, $opts)) {
$parser->_invoke(text => $block, out => \$value);
$parser->{Hub}->{"/sys/response/head/blocks/js/<next>"} = $value;
}
$parser->get_ctx->{'collapse'} = 1;
'';
}
# :js:global
# ...
# :end js:global
sub _js_global {
my $parser = shift;
my $name = shift;
my $opts = my_opts(\@_);
my $value = '';
if (my $block = _my_slurp($parser, $name, $opts)) {
$parser->_invoke(text => $block, out => \$value);
my $content = $parser->{Hub}->{"/sys/response/head/js"} || '';
$parser->{Hub}->{"/sys/response/head/js"} = $content
? "$content\n$value"
: $value;
}
$parser->get_ctx->{'collapse'} = 1;
'';
}
# :js
# ...
# :end js
#
# :js -global
# ...
# :end js
#
# :js src='/res/js/livesite.js'
#
# :js event='window,load'
# ...
# :end js
#
# :js extend='local'
# ...
# :end js
sub _js {
my $parser = shift;
my $name = shift;
my $opts = my_opts(\@_);
my %args = @_;
my $result = '';
if (my $src = delete $args{'src'}) {
$result = _js_src($parser, $name, $src, %args, -opts => $opts);
} elsif (my $event = delete $args{'event'}) {
$result = _js_event($parser, $name, $event, %args, -opts => $opts);
} elsif (my $extend = delete $args{'extend'}) {
$result = _js_extend($parser, $name, $extend, %args, -opts => $opts);
} elsif ($$opts{'global'}) {
$result = _js_global($parser, $name, %args, -opts => $opts);
} else {
$result = _js_closure($parser, $name, %args, -opts => $opts);
}
$result;
}
sub _my_slurp {
my $parser = shift;
my $name = shift;
my $opts = shift; # note passed by ref
my $block = $parser->_slurp($name);
# Unique id (supresses multiple inclusion) of block content
my $uid = undef;
if ($uid = $$opts{'uid'}) {
# -uid trumps -once
} elsif (my $once = $$opts{'once'}) {
$uid = join(':',
$parser->get_ctx->{'path'},
$parser->get_ctx->{'name'},
$parser->get_ctx->{'elem'}{'B'},
);
}
if ($uid) {
$$parser{'Hub'}{'/sys/log'}->debug("Unique block uid=$uid");
return '' if $$parser{'included'}{$uid};
$$parser{'included'}{$uid} = 1;
}
$block;
}
sub _quote {
my $value = shift;
$value =~ s/(?<!\\)"/\\"/g;
'"' . $value . '"';
}
1;
|
package org.vaadin.addons.vaactor
import Forwarder._
import TestComponent._
import TestServlet._
import TestUI._
import akka.actor.{ ActorIdentity, ActorRef, Identify }
class VaactorSpec extends WebBrowserSpec {
var forwarder: ActorRef = _
"remote ActorSystem should be found" in {
VaactorServlet.system.actorSelection(ForwarderPath) ! Identify("")
val id = expectMsgType[ActorIdentity]
id.ref should not be None
id.ref.get.path.toString shouldBe ForwarderPath
forwarder = id.ref.get // store for later use
forwarder ! Register(TestActorName)
}
"remote Vaactor Actor should" - {
"be created" in {
forwarder ! Lookup(VaactorActorName)
val reg = expectMsgType[Registered]
reg.name shouldBe VaactorActorName
reg.actor.path.toString should startWith(RemoteSystemPath + "/user/ui/ui-UiActor-")
reg.actor.path.toString should include("-VaactorProxyActor-")
}
}
"remote Vaactor should" - {
"set SessionState on ButtonClick" in {
val testState = "$Hurzi"
forwarder ! Lookup(SessionActorName)
val reg = expectMsgType[Registered]
reg.actor ! VaactorSession.RequestSessionState
expectMsgType[SessionState] shouldBe EmptySessionState
textField(CompTextName).value = testState
click on CompButtonName
Thread.sleep(100) // maybe Click needs some time
reg.actor ! VaactorSession.RequestSessionState
expectMsgType[SessionState] shouldBe SessionState(testState)
}
"respond with Text-Content on RequestText(sender)" in {
val testContent = "$Quaxi"
forwarder ! Lookup(VaactorActorName)
val reg = expectMsgType[Registered]
textField(CompTextName).value = testContent
click on CompButtonName // seems to trigger Vaadin transport
Thread.sleep(100) // maybe Click needs some time
reg.actor ! RequestText(self)
expectMsgType[ReplyText] shouldBe ReplyText(testContent)
lastSender shouldBe reg.actor
}
"respond with Text-Content on RequestText" in {
val testContent = "$Murksi"
forwarder ! Lookup(VaactorActorName)
val reg = expectMsgType[Registered]
textField(CompTextName).value = testContent
click on CompButtonName // seems to trigger Vaadin transport
Thread.sleep(100) // maybe Click needs some time
reg.actor ! RequestText
expectMsgType[ReplyText] shouldBe ReplyText(testContent)
lastSender shouldBe reg.actor
}
}
"remote VaactorComponentActor should" - {
"be created and terminated" in {
val testContent = "$Quaxi-dyn"
click on AddComponentButtonName
forwarder ! Lookup(VaactorActorName + NameSuffix)
val reg = expectMsgType[Registered]
textField(CompTextName + NameSuffix).value = testContent
click on CompButtonName + NameSuffix // seems to trigger Vaadin transport
reg.actor ! RequestText(self)
expectMsgType[ReplyText] shouldBe ReplyText(testContent)
lastSender shouldBe reg.actor
click on RemoveComponentButtonName
reg.actor ! RequestText(self)
expectNoMessage(noMessageWait)
}
"subscribe and unsubscribe" in {
forwarder ! Lookup(SessionActorName)
val reg = expectMsgType[Registered]
reg.actor ! Attach
expectMsgType[Attach.type]
click on AddSubscriberButtonName
expectMsgType[Attach.type]
click on RemoveSubscriberButtonName
expectMsgType[Detach.type]
}
}
}
|
# markdown-extensions [](https://travis-ci.org/sindresorhus/markdown-extensions)
> List of Markdown file extensions
The list is just a [JSON file](markdown-extensions.json) and can be used wherever.
## Install
```
$ npm install --save markdown-extensions
```
## Usage
```js
var markdownExtensions = require('markdown-extensions');
console.log(markdownExtensions);
//=> ['md', ...]
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
|
source cleanup.sh
vivado -mode batch -source create_proj.tcl -source sim_proj.tcl
source test_dpi.sh
|
/*
Copyright (C) 2016 -2017 Jerry Jin
*/
#ifndef capfloor_h
#define capfloor_h
#include <nan.h>
#include <string>
#include <queue>
#include <utility>
#include "../quantlibnode.hpp"
#include <oh/objecthandler.hpp>
using namespace node;
using namespace v8;
using namespace std;
class CapFloorWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mOptionType;
string mLegID;
std::vector<double> mStrikes;
string mReturnValue;
string mError;
CapFloorWorker(
Nan::Callback *callback
,string ObjectID
,string OptionType
,string LegID
,std::vector<double> Strikes
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mOptionType(OptionType)
,mLegID(LegID)
,mStrikes(Strikes)
{
};
//~CapFloorWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class MakeCapFloorWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mOptionType;
string mLength;
string mIborIndex;
double mStrike;
string mForwardStart;
string mPricingEngineID;
string mReturnValue;
string mError;
MakeCapFloorWorker(
Nan::Callback *callback
,string ObjectID
,string OptionType
,string Length
,string IborIndex
,double Strike
,string ForwardStart
,string PricingEngineID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mOptionType(OptionType)
,mLength(Length)
,mIborIndex(IborIndex)
,mStrike(Strike)
,mForwardStart(ForwardStart)
,mPricingEngineID(PricingEngineID)
{
};
//~MakeCapFloorWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class CapFloorTypeWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
CapFloorTypeWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~CapFloorTypeWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class CapFloorCapRatesWorker : public Nan::AsyncWorker {
public:
string mObjectID;
std::vector<double> mReturnValue;
string mError;
CapFloorCapRatesWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~CapFloorCapRatesWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class CapFloorFloorRatesWorker : public Nan::AsyncWorker {
public:
string mObjectID;
std::vector<double> mReturnValue;
string mError;
CapFloorFloorRatesWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~CapFloorFloorRatesWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class CapFloorAtmRateWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mYieldCurve;
double mReturnValue;
string mError;
CapFloorAtmRateWorker(
Nan::Callback *callback
,string ObjectID
,string YieldCurve
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mYieldCurve(YieldCurve)
{
};
//~CapFloorAtmRateWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class CapFloorStartDateWorker : public Nan::AsyncWorker {
public:
string mObjectID;
long mReturnValue;
string mError;
CapFloorStartDateWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~CapFloorStartDateWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class CapFloorMaturityDateWorker : public Nan::AsyncWorker {
public:
string mObjectID;
long mReturnValue;
string mError;
CapFloorMaturityDateWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~CapFloorMaturityDateWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class CapFloorImpliedVolatilityWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mPrice;
ObjectHandler::property_t mYieldCurve;
double mGuess;
double mAccuracy;
ObjectHandler::property_t mMaxIter;
double mMinVol;
double mMaxVol;
string mVolatilityType;
double mDisplacement;
double mReturnValue;
string mError;
CapFloorImpliedVolatilityWorker(
Nan::Callback *callback
,string ObjectID
,double Price
,ObjectHandler::property_t YieldCurve
,double Guess
,double Accuracy
,ObjectHandler::property_t MaxIter
,double MinVol
,double MaxVol
,string VolatilityType
,double Displacement
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mPrice(Price)
,mYieldCurve(YieldCurve)
,mGuess(Guess)
,mAccuracy(Accuracy)
,mMaxIter(MaxIter)
,mMinVol(MinVol)
,mMaxVol(MaxVol)
,mVolatilityType(VolatilityType)
,mDisplacement(Displacement)
{
};
//~CapFloorImpliedVolatilityWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class CapFloorLegAnalysisWorker : public Nan::AsyncWorker {
public:
string mObjectID;
ObjectHandler::property_t mAfterDate;
std::vector< std::vector<string> > mReturnValue;
string mError;
CapFloorLegAnalysisWorker(
Nan::Callback *callback
,string ObjectID
,ObjectHandler::property_t AfterDate
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mAfterDate(AfterDate)
{
};
//~CapFloorLegAnalysisWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
#endif
|
var _a_a_b_b_8h =
[
[ "AABB", "class_a_a_b_b.html", "class_a_a_b_b" ],
[ "ShortestDistance_AABB_Point", "_a_a_b_b_8h.html#acdd878bc13924b0296de2eedd3c67a5a", null ],
[ "ShortestDistanceSquareAABB_Segment1D_Point", "_a_a_b_b_8h.html#abe938b9bf761a88c071bfaa6f6bb0415", null ]
];
|
import { useQuery } from "@apollo/client";
import { Spin } from "antd";
import { USER_DETAIL_HOME_QUERY } from "../gqlQueries";
import { UserDetail } from "../components/UserDetail";
import type { UserDetailHomeResponseType } from "../types";
const UserHomePage: React.FC = () => {
const { error, data, loading } = useQuery<UserDetailHomeResponseType>(
USER_DETAIL_HOME_QUERY,
);
if (error) {
console.log("Error in user home detail: ", error);
return <span>Something went wrong. Sorry...</span>;
}
if (!loading && data)
return (
<UserDetail
username={data.users.detail.record.username}
email={data.users.detail.record.email}
registeredAt={data.users.detail.record.registeredAt}
/>
);
else return <Spin style={{ margin: "auto" }} />;
};
export { UserHomePage };
|
module GithubBackup
class Backup
attr_reader :debug, :username, :client, :gists, :starred_gists, :wikis, :config
def initialize(username, options = {})
@username = username
@debug = false
@gists = options.delete(:gists)
@starred_gists = options.delete(:starred_gists)
@wikis = options.delete(:wikis)
@config = Config.new(options)
@client = Octokit::Client.new(:access_token => config.token)
end
def execute
backup_all
rescue Octokit::Unauthorized
puts "Github API authentication failed."
puts "Please add a [github] section to your ~/.gitconfig"
puts " See: http://github.com/guides/tell-git-your-user-name-and-email-address"
puts "Or, use the arguments to authenticate with your username and API token."
end
private
def backup_all
make_backup_root
repo_collection.repos(username).each { |r| r.backup(config.backup_root) }
if gists
repo_collection.gists(username).
each { |r| r.backup(config.backup_root) }
end
if starred_gists
repo_collection.starred_gists(username).
each { |r| r.backup(config.backup_root) }
end
if wikis
repo_collection.wikis(username).
each { |r| r.backup(config.backup_root) }
end
end
def repo_collection
@repo_collection ||= GithubBackup::GithubRepositoryCollection.new(client)
end
def backup_directory_for(repository)
File.join(config.backup_root, repository.backup_path)
end
def make_backup_root
# TODO: Handle errors
FileUtils.mkdir_p(config.backup_root)
end
end
end
|
$$( document ).ready(function() {
console.log( "ready!" );
});
const form = document.querySelector(".top-banner form");
const msg = document.querySelector(".top-banner .msg");
const list = document.querySelector(".ajax-section .cities");
var submitBtn = document.querySelector("#searchweather");
var outputArea = document.querySelector("#output");
let input = document.querySelector(".top-banner input");
function getWeather() {
let inputVal = input.value;
let url="http://api.openweathermap.org/data/2.5/weather?q=" + inputVal + "&appid=0ca33d0294b3d8458a733eb1abbf9384";
fetch(url,{method: 'GET'})
.then(response => response.json())
.then(data => outputArea.value = JSON.stringify(data));
}
|
import { style, styleMap } from 'sku/treat';
import { Properties } from 'csstype';
import { darken, lighten } from 'polished';
import { getLightVariant, isLight, mapToStyleProperty } from '../../utils';
import { Theme } from 'treat/theme';
const spaceMapToCss = (
theme: Theme,
cssPropertyName: keyof Properties,
breakpoint: keyof Theme['breakpoint'],
) => {
const spaceWithNone = {
...theme.space,
none: 0,
};
return mapToStyleProperty(
spaceWithNone,
cssPropertyName,
(value, propertyName) => {
const styles = {
[propertyName]: value * theme.grid,
};
const minWidth = theme.breakpoint[breakpoint];
return minWidth === 0
? styles
: {
'@media': {
[`screen and (min-width: ${minWidth}px)`]: styles,
},
};
},
);
};
export const margin = {
top: styleMap(theme => spaceMapToCss(theme, 'marginTop', 'mobile')),
bottom: styleMap(theme => spaceMapToCss(theme, 'marginBottom', 'mobile')),
left: styleMap(theme => spaceMapToCss(theme, 'marginLeft', 'mobile')),
right: styleMap(theme => spaceMapToCss(theme, 'marginRight', 'mobile')),
};
export const marginTablet = {
top: styleMap(theme => spaceMapToCss(theme, 'marginTop', 'tablet')),
bottom: styleMap(theme => spaceMapToCss(theme, 'marginBottom', 'tablet')),
left: styleMap(theme => spaceMapToCss(theme, 'marginLeft', 'tablet')),
right: styleMap(theme => spaceMapToCss(theme, 'marginRight', 'tablet')),
};
export const marginDesktop = {
top: styleMap(theme => spaceMapToCss(theme, 'marginTop', 'desktop')),
bottom: styleMap(theme => spaceMapToCss(theme, 'marginBottom', 'desktop')),
left: styleMap(theme => spaceMapToCss(theme, 'marginLeft', 'desktop')),
right: styleMap(theme => spaceMapToCss(theme, 'marginRight', 'desktop')),
};
export const padding = {
top: styleMap(theme => spaceMapToCss(theme, 'paddingTop', 'mobile')),
bottom: styleMap(theme => spaceMapToCss(theme, 'paddingBottom', 'mobile')),
left: styleMap(theme => spaceMapToCss(theme, 'paddingLeft', 'mobile')),
right: styleMap(theme => spaceMapToCss(theme, 'paddingRight', 'mobile')),
};
export const paddingTablet = {
top: styleMap(theme => spaceMapToCss(theme, 'paddingTop', 'tablet')),
bottom: styleMap(theme => spaceMapToCss(theme, 'paddingBottom', 'tablet')),
left: styleMap(theme => spaceMapToCss(theme, 'paddingLeft', 'tablet')),
right: styleMap(theme => spaceMapToCss(theme, 'paddingRight', 'tablet')),
};
export const paddingDesktop = {
top: styleMap(theme => spaceMapToCss(theme, 'paddingTop', 'desktop')),
bottom: styleMap(theme => spaceMapToCss(theme, 'paddingBottom', 'desktop')),
left: styleMap(theme => spaceMapToCss(theme, 'paddingLeft', 'desktop')),
right: styleMap(theme => spaceMapToCss(theme, 'paddingRight', 'desktop')),
};
export const transform = {
touchable: style(({ transforms }) => ({
':active': { transform: transforms.touchable },
})),
};
export const transition = styleMap(({ transitions }) =>
mapToStyleProperty(transitions, 'transition'),
);
const borderRadiusRules = {
full: '100%',
};
export const borderRadius = {
...styleMap(
mapToStyleProperty(borderRadiusRules, 'borderRadius'),
'borderRadius',
),
...styleMap(
({ border }) => mapToStyleProperty(border.radius, 'borderRadius'),
'borderRadius',
),
};
const widthRules = {
full: '100%',
};
export const width = {
...styleMap(mapToStyleProperty(widthRules, 'width'), 'width'),
...styleMap(
theme => ({
touchable: { width: theme.grid * theme.touchableSize },
}),
'width',
),
};
const heightRules = {
full: '100%',
};
export const height = {
...styleMap(mapToStyleProperty(heightRules, 'height'), 'height'),
...styleMap(
theme => ({
touchable: { height: theme.grid * theme.touchableSize },
}),
'height',
),
};
const positionRules = {
absolute: 'absolute',
relative: 'relative',
fixed: 'fixed',
};
export const position = styleMap(mapToStyleProperty(positionRules, 'position'));
const displayRules = {
block: 'block',
inline: 'inline',
none: 'none',
inlineBlock: 'inline-block',
flex: 'flex',
};
export const display = styleMap(mapToStyleProperty(displayRules, 'display'));
export const displayTablet = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(displayRules, 'display', (value, propertyName) =>
responsiveStyle({
tablet: { [propertyName]: value },
}),
),
);
export const displayDesktop = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(displayRules, 'display', (value, propertyName) =>
responsiveStyle({
desktop: { [propertyName]: value },
}),
),
);
const alignItemsRules = {
flexStart: 'flex-start',
center: 'center',
flexEnd: 'flex-end',
};
export const alignItems = styleMap(
mapToStyleProperty(alignItemsRules, 'alignItems'),
);
export const alignItemsTablet = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(alignItemsRules, 'alignItems', (value, propertyName) =>
responsiveStyle({
tablet: { [propertyName]: value },
}),
),
);
export const alignItemsDesktop = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(alignItemsRules, 'alignItems', (value, propertyName) =>
responsiveStyle({
desktop: { [propertyName]: value },
}),
),
);
const justifyContentRules = {
flexStart: 'flex-start',
center: 'center',
flexEnd: 'flex-end',
spaceBetween: 'space-between',
};
export const justifyContent = styleMap(
mapToStyleProperty(justifyContentRules, 'justifyContent'),
);
export const justifyContentTablet = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(
justifyContentRules,
'justifyContent',
(value, propertyName) =>
responsiveStyle({
tablet: { [propertyName]: value },
}),
),
);
export const justifyContentDesktop = styleMap(
({ utils: { responsiveStyle } }) =>
mapToStyleProperty(
justifyContentRules,
'justifyContent',
(value, propertyName) =>
responsiveStyle({
desktop: { [propertyName]: value },
}),
),
);
const flexDirectionRules = {
row: 'row',
rowReverse: 'row-reverse',
column: 'column',
columnReverse: 'column-reverse',
};
export const flexDirection = styleMap(
mapToStyleProperty(flexDirectionRules, 'flexDirection'),
);
export const flexDirectionTablet = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(
flexDirectionRules,
'flexDirection',
(value, propertyName) =>
responsiveStyle({
tablet: { [propertyName]: value },
}),
),
);
export const flexDirectionDesktop = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(
flexDirectionRules,
'flexDirection',
(value, propertyName) =>
responsiveStyle({
desktop: { [propertyName]: value },
}),
),
);
const getActiveColor = (color: string) =>
isLight(color) ? darken(0.1, color) : darken(0.05, color);
const getHoverColor = (color: string) =>
isLight(color) ? darken(0.05, color) : lighten(0.05, color);
export const background = styleMap(({ color }) => ({
...mapToStyleProperty(color.background, 'background'),
formAccentActive: { background: getActiveColor(color.background.formAccent) },
formAccentHover: { background: getHoverColor(color.background.formAccent) },
brandAccentActive: {
background: getActiveColor(color.background.brandAccent),
},
brandAccentHover: { background: getHoverColor(color.background.brandAccent) },
infoLight: { background: getLightVariant(color.background.info) },
promoteLight: { background: getLightVariant(color.background.promote) },
criticalLight: { background: getLightVariant(color.background.critical) },
positiveLight: { background: getLightVariant(color.background.positive) },
neutralLight: { background: getLightVariant(color.background.neutral) },
}));
export const boxShadow = styleMap(
({ border: { width: borderWidth, color }, shadows }) => ({
...mapToStyleProperty(shadows, 'boxShadow'),
outlineFocus: {
boxShadow: `0 0 0 ${borderWidth.large}px ${color.focus}`,
},
borderStandard: {
boxShadow: `inset 0 0 0 ${borderWidth.standard}px ${color.standard}`,
},
borderStandardInverted: {
boxShadow: `inset 0 0 0 ${borderWidth.standard}px ${color.standardInverted}`,
},
borderCritical: {
boxShadow: `inset 0 0 0 ${borderWidth.standard}px ${color.critical}`,
},
borderFormHover: {
boxShadow: `inset 0 0 0 ${borderWidth.standard}px ${color.formHover}`,
},
borderFormAccent: {
boxShadow: `inset 0 0 0 ${borderWidth.standard}px ${color.formAccent}`,
},
borderFormAccentLarge: {
boxShadow: `inset 0 0 0 ${borderWidth.large}px ${color.formAccent}`,
},
borderStandardInvertedLarge: {
boxShadow: `inset 0 0 0 ${borderWidth.large}px ${color.standardInverted}`,
},
}),
);
export const cursor = styleMap({
pointer: { cursor: 'pointer' },
});
export const pointerEvents = styleMap({
none: { pointerEvents: 'none' },
});
const textAlignRules = {
left: 'left',
center: 'center',
right: 'right',
};
export const textAlign = styleMap(
mapToStyleProperty(textAlignRules, 'textAlign'),
);
export const textAlignTablet = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(textAlignRules, 'textAlign', (value, propertyName) =>
responsiveStyle({
tablet: { [propertyName]: value },
}),
),
);
export const textAlignDesktop = styleMap(({ utils: { responsiveStyle } }) =>
mapToStyleProperty(textAlignRules, 'textAlign', (value, propertyName) =>
responsiveStyle({
desktop: { [propertyName]: value },
}),
),
);
|
* 使用img.member-logo无效,用注释掉的css有效,为什么?
```
<div class="rightwarp">
<img class="menber-logo" src="../03/img/icon01.png" alt="" >
```
```
.rightwarp{float: right;padding: 20px;background-color: #fff;}
.member-logo{display: block;width:80px;height: 80px;}
/*.rightwarp img{display: block;width:80px;height: 80px;}*/
```
需要补充的知识点:?
|
<?php
namespace App\Http\Controllers\Alipay;
use App\Models\Device;
use \App\Utils\IdGenerator;
use App\Utils\IotDevice;
use App\Models\Trade;
use App\Models\UserVipCard;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
class VipCardController extends Controller
{
/*
* 显示商品信息
* */
public function showCardInfo(Request $request)
{
$device_id = $request->input('device_id', -1);
$card_id = $request->input('card_id', -1);
//获取设备信息
$device = Device::find($device_id);
if (!$device)
{
return view('alipay.error')->withErrors(['无设备信息,请重试!编号: '.$device_id]);
}
//获取会员卡信息
$card = UserVipCard::find($card_id);
if (!$card)
{
return view('alipay.error')->withErrors(['无会员卡信息,请重试!卡号: '.$card_id]);
}
//检查会员卡是否可以在本机使用
if ($device['owner_id'] !== $card['owner_id'])
{
return view('alipay.error')->withErrors(['会员卡不适用于该网点,请付费使用!']);
}
//检查用户的openid
if ($card['user_openid'] !== $this->openid())
{
return view('alipay.error')->withErrors(['用户身份错误,请重试!']);
}
//检查可用次数
if ($card['used_count'] >= $card['total_count'])
{
return view('alipay.error')->withErrors(['会员卡可用次数已用完,请重新购买!']);
}
//检查会员卡的有效期
if ($card->leftTime() <= 0)
{
return view('alipay.error')->withErrors(['会员卡已过期,请重新购买!']);
}
$today_count = Trade::whereDate('created_at', (string)Carbon::today())
->where('user_openid', '=', $this->openId())
->where('card_id', '=', $card->id)
->where('payment_type', Trade::PaymentType_VipCard)
->count();
if ($today_count >= $card->today_limit)
{
return view('alipay.error')->withErrors(['会员卡当天可用次数已用完,请购买单次使用的套餐!']);
}
//2018-09-14 由于回调的时候,是支付宝回调的,所以需要提前保存用户的IP
//保存扫码的时候的用户ip
Session::put('user_ip', $request->getClientIp());
$token = (string)Str::uuid();
session()->push('token', $token);
return view('alipay.showCardInfo', compact('device', 'card', 'token'));
}
/*
* 开机
* */
public function carWash(Request $request)
{
$device_id = $request->input('device_id', -1);
$card_id = $request->input('card_id', -1);
$token = $request->input('token');
$data = session()->pull('token');
$oldToken = $data ? $data[0] : null;
if ($oldToken !== $token) {
Log::debug('token miss match', ['token' => $token, 'oldToken' => $oldToken]);
return redirect()->route('alipay.error')->withErrors(['请勿重复提交!']);
}
//获取设备信息
$device = Device::find($device_id);
if (!$device)
{
return view('alipay.error')->withErrors(['无设备信息,请重试!编号: '.$device_id]);
}
//获取会员卡信息
$card = UserVipCard::find($card_id);
if (!$card)
{
return view('alipay.error')->withErrors(['无会员卡信息,请重试!卡号: '.$card_id]);
}
//检查会员卡是否可以在本机使用
if ($device['owner_id'] !== $card['owner_id'])
{
return view('alipay.error')->withErrors(['会员卡不适用于该网点,请付费使用!']);
}
//检查用户的openid
if ($card['user_openid'] !== $this->openid())
{
return view('alipay.error')->withErrors(['用户身份错误,请重试!']);
}
//检查可用次数
if ($card['used_count'] >= $card['total_count'])
{
return view('alipay.error')->withErrors(['会员卡可用次数已用完,请重新购买!']);
}
//检查会员卡的有效期
if ($card->leftTime() <= -60)
{
return view('alipay.error')->withErrors(['会员卡已过期,请重新购买!']);
}
$tradeId = IdGenerator::tradeId();
if ($this->sendOrder($device->id, $tradeId, $card->seconds))
{
$trade = $this->saveRecord($device, $tradeId, $card);
return redirect()->route('alipay.success', [
'device_id' => $device->id,
'trade_id' => $trade->id,
'card_id' => $card->id,
]);
}
else
{
return view('alipay.showCardInfo', compact('device', 'card'))
->withErrors(['系统忙碌,请稍后重试!']);
}
}
/*
* 开机成功
* */
public function success(Request $request)
{
// dd($request->all());
//设备信息
$device = Device::find($request->input('device_id', -1));
if (!$device)
{
return view('alipay.error')->withErrors(['无设备信息!']);
}
//订单信息
$trade = Trade::find($request->input('trade_id', -1));
if (!$trade)
{
return view('alipay.error')->withErrors(['无订单信息']);
}
//会员卡信息
$card = UserVipCard::find($request->input('card_id', -1));
if (!$card)
{
return view('alipay.error')->withErrors(['无会员开信息']);
}
//检查会员卡的有效期,如果过期时间在60秒以内,允许使用
if ($card->leftTime() <= -60)
{
return view('alipay.error')->withErrors(['会员卡已过期,请重新购买!']);
}
//这里检查一下用户,是否就是创建记录的人。
if ($trade['user_openid'] !== $this->openId())
{
return view('alipay.error')->withErrors(['用户身份错误']);
}
return view('alipay.success', compact('device', 'trade', 'card'));
}
public function error()
{
return view('alipay.error');
}
protected function openid() : string
{
$user = Session::get('alipay.oauth_user.default'); // 拿到授权用户资料
Log::debug('alipay user', ['user' => $user] );
return $user ? $user['id'] : str_random(64);
}
/*
* 发送订单给设备
* */
public function sendOrder($device_id, $trade_id, $seconds)
{
$iot = new IotDevice($device_id);
return $iot->netOrder($trade_id, $seconds);
}
/*
* 保存记录
* */
public function saveRecord($device, $trade_id, $card) : Trade
{
$request = new Request();
$trade = new Trade();
try
{
DB::beginTransaction();
//记录会员卡的使用次数
$card->used_count++;
$card->save();
$trade['id'] = $trade_id;
$trade['payment_type'] = Trade::PaymentType_VipCard;
$trade['payment_status'] = Trade::PaymentStatus_Success;
$trade['confirm_status'] = Trade::GoodsStatus_Confirmed;
$trade['refund_status'] = Trade::RefundStatus_None;
$trade['withdraw_status'] = Trade::WithdrawState_Disable;
$trade['payment_money'] = 0;
$trade['refund_money'] = 0;
$trade['withdraw_money'] = 0;
$trade['platform_money'] = 0;
$trade['user_ip'] = Session::get('user_ip');
$trade['user_openid'] = $this->openId();
$trade['owner_id'] = $device['owner_id'];
$trade['device_id'] = $device['id'];
$trade['is_self'] = $device['is_self'];
$trade['goods_name'] = $card['goods_name'];
$trade['goods_seconds'] = $card['seconds'];
$trade['card_id'] = $card['id'];
$trade['platform_fee_rate'] = 1000;
$trade['confirm_status'] = Trade::GoodsStatus_Confirmed;
$trade['confirmed_at'] = Carbon::now();
$trade->save();
DB::commit();
Log::debug('save trade info', [$trade]);
}
catch (\Exception $exception)
{
DB::rollBack();
\Log::debug('exception', [$exception]);
dd($exception);
}
return $trade;
}
}
|
<?php
namespace App\Admin\Repositories;
use App\Models\AssetsLog as Model;
use Dcat\Admin\Repositories\EloquentRepository;
class AssetsLog extends EloquentRepository
{
/**
* Model.
*
* @var string
*/
protected $eloquentClass = Model::class;
/**
* 类型.
*/
const OPERATE_TYPE_WITHDRAW_TO_WALLET = 'withdraw_to_wallet';
const OPERATE_TYPE_MARKET_BUSINESS = 'give_market_business';
const OPERATE_TYPE_WITHDRAW_TO_WALLET_FEE = 'withdraw_to_wallet_fee';
const OPERATE_TYPE_REFUSE_WITHDRAW = 'refuse_withdraw';
const OPERATE_TYPE_CHARITY_REBATE = 'charity_rebate';//公益捐赠分红
const OPERATE_TYPE_PLATFORM_REBATE = 'platform_rebate';//平台分红
const OPERATE_TYPE_USER_REBATE = 'user_rebate';//用户分红
const OPERATE_TYPE_BUSINESS_REBATE = 'business_rebate';//商家分红
const OPERATE_TYPE_INVITE_REBATE = 'invite_rebate';//邀请分红
const OPERATE_TYPE_DISTRICT_REBATE = 'district_rebate';//区站长分红
const OPERATE_TYPE_CITY_REBATE = 'city_rebate';//市站长分红
const OPERATE_TYPE_SHARE_B_REBATE = 'share_b_rebate';//邀请商家
const OPERATE_TYPE_EXCHANGE_IETS = 'exchagne_iets';//兑换iets
const OPERATE_TYPE_EXCHANGE_IETS_SUB_ENCOURATGE = 'exchagne_iets_sub';//兑换扣除
const OPERATE_TYPE_IETS_TO_USDT = 'IETS兑换为USDT';
const OPERATE_TYPE_RECHARGE_LPJ = 'recharge_lpj';
const OPERATE_TYPE_PROVINCE_REBATE = 'province_rebate';//省站长分红
/**
* 类型文本.
*
* @var array
*/
public static $operateTypeTexts = [
self::OPERATE_TYPE_WITHDRAW_TO_WALLET => '提现到钱包',
self::OPERATE_TYPE_MARKET_BUSINESS => '赠送给市商',
self::OPERATE_TYPE_WITHDRAW_TO_WALLET_FEE => '提现到钱包手续费',
self::OPERATE_TYPE_REFUSE_WITHDRAW => '拒绝提现',
self::OPERATE_TYPE_CHARITY_REBATE => '公益捐赠分红',
self::OPERATE_TYPE_PLATFORM_REBATE => '平台分红',
self::OPERATE_TYPE_USER_REBATE => '用户分红',
self::OPERATE_TYPE_BUSINESS_REBATE => '商家分红',
self::OPERATE_TYPE_INVITE_REBATE => '邀请分红',
self::OPERATE_TYPE_DISTRICT_REBATE => '区站长分红',
self::OPERATE_TYPE_CITY_REBATE => '市站长分红',
self::OPERATE_TYPE_SHARE_B_REBATE => '邀请商家分红',
self::OPERATE_TYPE_EXCHANGE_IETS => '兑换',
self::OPERATE_TYPE_EXCHANGE_IETS_SUB_ENCOURATGE => '兑换扣除',
self::OPERATE_TYPE_IETS_TO_USDT => 'IETS兑换为USDT',
self::OPERATE_TYPE_RECHARGE_LPJ => '兑换来拼金',
self::OPERATE_TYPE_PROVINCE_REBATE => '省站长分红',
];
}
|
import { getAnimation, registerAnimation } from '../../../src/animate/animation';
describe('Animation', () => {
it('registerAnimation && getAnimation', () => {
registerAnimation('test', () => {});
expect(getAnimation('text')).toBeUndefined();
expect(getAnimation('whatever')).toBeUndefined();
});
});
|
package edgedb.internal.protocol;
import lombok.Data;
@Data
public class DataElement implements ServerProtocolBehaviour {
int dataLength;
byte[] dataElement;
byte[] dataElementInBinary;
String dataElementInString;
String[] dataElementInStringArray;
}
|
package javathreads.examples.ch02;
import java.util.Vector;
/**
* 字母事件处理器
*/
public class CharacterEventHandler {
private Vector listeners = new Vector();
public void addCharacterListener(CharacterListener cl) {
listeners.add(cl);
}
public void removeCharacterListener(CharacterListener cl) {
listeners.remove(cl);
}
public void fireNewCharacter(CharacterSource source, int c) {
CharacterEvent ce = new CharacterEvent(source, c);
CharacterListener[] cl = (CharacterListener[])
listeners.toArray(new CharacterListener[0]);
for (int i = 0; i < cl.length; i++)
cl[i].newCharacter(ce);
}
}
|
<?php
use Illuminate\Database\Seeder;
use database\seeds\SeederHelper;
use App\Models\Bible\BibleEquivalent;
use App\Models\Bible\BibleBook;
use App\Models\Bible\Book;
use App\Models\Bible\Bible;
use Illuminate\Support\Facades\DB;
class bible_books_pivot_seeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('bible_books')->delete();
$tables = DB::connection('sophia')->select('SHOW TABLES');
foreach($tables as $table) {
$table_id = $table->Tables_in_sophia;
$bible_id = substr($table_id,0,-4);
if((strpos($table_id, '_vpl') == false)) { continue; }
$bible = Bible::find($bible_id);
if(!$bible) { echo "\n Missing: ". $bible_id;continue;}
$books_reponse = DB::connection('sophia')->table($table_id)->distinct()->select('book','chapter')->get();
$books = [];
foreach($books_reponse as $book) {
if(!isset($books[$book->book])) $books[$book->book] = [];
$books[$book->book][] = $book->chapter;
}
foreach($books as $book_id => $chapters) {
$book = Book::where('id_usfx',$book_id)->orWhere('id',$book_id)->orWhere('id_osis',$book_id)->first();
if(!$book) { echo "\nMissing Book_ID: ". $book_id; continue;}
BibleBook::create([
'bible_id' => $bible->id,
'book_id' => $book->id,
'name' => $book->name,
'name_short' => "",
'chapters' => implode(',',$chapters)
]);
}
}
}
}
|
namespace EventHorizon.Game.Server.Asset.Common.Import.Model;
using EventHorizon.Game.Server.Asset.Common.Model;
public class ImportArtifact
: ExportArtifactBase
{
}
|
#!/bin/bash
source setenv.sh
echo "Gemfire Shell (gfsh) is command-line interface to launch, manage and monitor Gemfire processes"
echo "Type connect to connect to the grid if its running"
gfsh
|
package mnemonic
import (
"bytes"
"testing"
)
func TestMnemonic(t *testing.T) {
// new
phrase, err := New()
if err != nil {
t.Fatal(err)
}
// t.Logf("Phrase: %v", phrase)
// get private key from phrase
pk, err := Recover(phrase, "password")
if err != nil {
t.Fatal(err)
}
// t.Logf("Private Key: %v", pk.String())
// phrase is valid
if !Valid(phrase) {
t.Fatal("Should be valid phrase")
}
// phrase is invalid
if Valid(phrase + " hello") {
t.Fatal("Should be invalid phrase")
}
// recover with invalid phrase
if _, err := Recover(phrase+" hello", "password"); err == nil {
t.Fatal("Should fail on invalid phrase")
}
// recover with valid phrase but wrong password
wrongPK, err := Recover(phrase, "wrong password")
if err != nil {
t.Fatal(err)
}
if bytes.Equal(wrongPK.Bytes(), pk.Bytes()) {
t.Fatal("Should be different private key")
}
// recover with valid phrase but empty password
wrongPK, err = Recover(phrase, "")
if err != nil {
t.Fatal(err)
}
if bytes.Equal(wrongPK.Bytes(), pk.Bytes()) {
t.Fatal("Should be different private key")
}
// recover again with
samePK, err := Recover(phrase, "password")
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(samePK.Bytes(), pk.Bytes()) {
t.Fatal("Should be same private key")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.