hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequencelengths 1
10
| max_stars_count
int64 1
368k
โ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
โ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
โ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequencelengths 1
10
| max_issues_count
int64 1
134k
โ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
โ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
โ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequencelengths 1
10
| max_forks_count
int64 1
105k
โ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
โ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
โ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4454b6abe0370d8b2d8775ed54d8b4a40ff7e3de | 214 | py | Python | python_BJ/test1.py | DongUk-Park/im_coma | b5c1acdea3957dead6d884f5d4b257df3ae931aa | [
"MIT"
] | null | null | null | python_BJ/test1.py | DongUk-Park/im_coma | b5c1acdea3957dead6d884f5d4b257df3ae931aa | [
"MIT"
] | 1 | 2022-03-22T02:30:53.000Z | 2022-03-22T02:31:43.000Z | python_BJ/test1.py | DongUk-Park/im_coma | b5c1acdea3957dead6d884f5d4b257df3ae931aa | [
"MIT"
] | null | null | null | a,b,c = input().split() #ํ๋ฒ์ ์ฌ๋ฌ๊ฐ์ ์
๋ ฅ์ ๋ฐ๊ธฐ ์ํด .split()
a = int(a)
b = int(b)
c = int(c) # ํ์ด์ฌ์ ์
๋ ฅ์ ๋ฐ์ ๋ ๋ฌธ์์ด๋ก ์
๋ ฅ์ ๋ฐ๊ธฐ ๋๋ฌธ์ int๋ก ํ๋ณํ
if a>b:
print(">")
elif a==b:
print("==")
else:
print("<")
| 15.285714 | 53 | 0.490654 |
56ac3c9c9122e6c59dcf3bff6c5416e41b4b3c42 | 3,411 | rs | Rust | crates/spirv-std/src/arch/barrier.rs | Arc-blroth/rust-gpu | f500a8418e1b8e2928a193a7402bb0d7835791c8 | [
"Apache-2.0",
"MIT"
] | null | null | null | crates/spirv-std/src/arch/barrier.rs | Arc-blroth/rust-gpu | f500a8418e1b8e2928a193a7402bb0d7835791c8 | [
"Apache-2.0",
"MIT"
] | null | null | null | crates/spirv-std/src/arch/barrier.rs | Arc-blroth/rust-gpu | f500a8418e1b8e2928a193a7402bb0d7835791c8 | [
"Apache-2.0",
"MIT"
] | null | null | null | use crate::memory::{Scope, Semantics};
/// Wait for other invocations of this module to reach the current point
/// of execution.
///
/// All invocations of this module within Execution scope reach this point of
/// execution before any invocation proceeds beyond it.
///
/// When Execution is [`Scope::Workgroup`] or larger, behavior is undefined
/// unless all invocations within Execution execute the same dynamic instance of
/// this instruction. When Execution is Subgroup or Invocation, the behavior of
/// this instruction in non-uniform control flow is defined by the client API.
///
/// If [`Semantics`] is not [`Semantics::None`], this instruction also serves as
/// an [`memory_barrier`] function call, and also performs and adheres to the
/// description and semantics of an [`memory_barrier`] function with the same
/// `MEMORY` and `SEMANTICS` operands. This allows atomically specifying both a
/// control barrier and a memory barrier (that is, without needing two
/// instructions). If [`Semantics`] is [`Semantics::None`], `MEMORY` is ignored.
///
/// Before SPIRV-V version 1.3, it is only valid to use this instruction with
/// `TessellationControl`, `GLCompute`, or `Kernel` execution models. There is
/// no such restriction starting with version 1.3.
///
/// If used with the `TessellationControl` execution model, it also implicitly
/// synchronizes the [`crate::storage_class::Output`] Storage Class: Writes to
/// `Output` variables performed by any invocation executed prior to a
/// [`control_barrier`] are visible to any other invocation proceeding beyond
/// that [`control_barrier`].
#[spirv_std_macros::gpu_only]
#[doc(alias = "OpControlBarrier")]
#[inline]
pub unsafe fn control_barrier<
const EXECUTION: Scope,
const MEMORY: Scope,
const SEMANTICS: Semantics,
>() {
asm! {
"%u32 = OpTypeInt 32 0",
"%execution = OpConstant %u32 {execution}",
"%memory = OpConstant %u32 {memory}",
"%semantics = OpConstant %u32 {semantics}",
"OpControlBarrier %execution %memory %semantics",
execution = const EXECUTION as u8,
memory = const MEMORY as u8,
semantics = const SEMANTICS as u8,
}
}
/// Control the order that memory accesses are observed.
///
/// Ensures that memory accesses issued before this instruction are observed
/// before memory accesses issued after this instruction. This control is
/// ensured only for memory accesses issued by this invocation and observed by
/// another invocation executing within `MEMORY` scope. If the `vulkan` memory
/// model is declared, this ordering only applies to memory accesses that
/// use the `NonPrivatePointer` memory operand or `NonPrivateTexel`
/// image operand.
///
/// `SEMANTICS` declares what kind of memory is being controlled and what kind
/// of control to apply.
///
/// To execute both a memory barrier and a control barrier,
/// see [`control_barrier`].
#[spirv_std_macros::gpu_only]
#[doc(alias = "OpMemoryBarrier")]
#[inline]
// FIXME(eddyb) use a `bitflags!` `Semantics` for `SEMANTICS`.
pub unsafe fn memory_barrier<const MEMORY: Scope, const SEMANTICS: u32>() {
asm! {
"%u32 = OpTypeInt 32 0",
"%memory = OpConstant %u32 {memory}",
"%semantics = OpConstant %u32 {semantics}",
"OpMemoryBarrier %memory %semantics",
memory = const MEMORY as u8,
semantics = const SEMANTICS,
}
}
| 43.177215 | 80 | 0.707124 |
5bbf5d4e991c0cfb534721717ef82e205034bdbd | 3,672 | css | CSS | public/frontend/css/list.css | TrungPham2810/truyennew | 8ba0283209afb1c0b8a494be033c88925d7b71c9 | [
"MIT"
] | null | null | null | public/frontend/css/list.css | TrungPham2810/truyennew | 8ba0283209afb1c0b8a494be033c88925d7b71c9 | [
"MIT"
] | null | null | null | public/frontend/css/list.css | TrungPham2810/truyennew | 8ba0283209afb1c0b8a494be033c88925d7b71c9 | [
"MIT"
] | null | null | null | .section-breadcrumb li:first-child:after {
display: inline-block;
vertical-align: middle;
content: ">";
font-size: 15px;
margin-left: 5px;
font-weight: 100;
}
ul.menu.breadcrumb li {
display: inline;
padding: 10px 2px;
}
ul.menu.breadcrumb li a {
color: #000;
}
.section-breadcrumb li.active span {
color: #888;
}
ul.menu.breadcrumb {
font-size: 15px;
}
.search-advance select {
width: 96%;
padding: 10px;
margin: 5px 2%;
border: 1px solid #ccc;
border-radius: 8px;
background-color: #fff;
font-size: 13px;
color: #888;
}
.select-filter {
display: flex;
flex-flow: wrap;
}
.select-filter div {
width: 50%;
}
.search-check {
display: flex;
padding: 10px 4px;
margin-bottom: 10px;
}
.check {
width: 50%;
font-size: 14px;
color: #3b7f61 ;
}
.check span, .check input {
vertical-align: middle;
}
#search-form {
margin-bottom: 20px;
}
#search-form button {
padding: 8px 15px;
font-size: 15px;
border-radius: 8px;
border: 1px solid #888;
width: 80%;
margin: auto;
display: block;
cursor: pointer;
}
#search-form button:focus {
border: 1px solid #888;
}
#search-form button:hover {
background: #f9b349;
}
.switch-layout {
float: right;
border: 1px solid;
border-radius: 4px;
display: flex;
margin: 15px;
}
.switch-layout div {
padding: 7px;
}
.switch-layout .grid {
background: #fff;
border-radius: 4px 0 0 4px;
}
.switch-layout .list {
background: #fff;
border-radius: 0 4px 4px 0 ;
}
.switch-layout .active {
background: #f9b349;
}
.description-category {
font-weight: 400;
color: #888;
font-size: 15px;
}
.type_list td.chap {
vertical-align: initial;
text-align: right;
}
.type_list td.chap a{
font-size: 14px;
line-height: 1.7;
color: #f9b349;
display: none;
white-space: nowrap;
}
.type_list td.info {
vertical-align: baseline;
padding: 5px;
}
.chap_mobile {
padding: 5px;
border: 1px solid #f9b349;
display: inline-block;
border-radius: 8px;
}
.chap_mobile a {
font-size: 14px;
color: #f9b349;
}
h3.rv-home-a-title a {
font-size: 16px;
color: #000;
transition: all .3s;
}
h3.rv-home-a-title a:hover {
color: #f9b349;
}
.book-status {
display: none;
}
@media (min-width: 558px){
ul.menu.breadcrumb, .section-breadcrumb li:first-child:after {
font-size: 18px;
}
}
.rv-sr-a, .genre {
color: #f9b349;
font-size: 13px;
font-weight: 500;
line-height: 1.3;
}
tbody {
width: 100%;
}
.type_list td.image {
width: 25%;
}
img.image-book {
width: 100%;
}
table {
width: 100%;
}
img.image-book {
width: 100%;
}
.type_list tr {
padding: 10px 0;
display: block;
border-bottom: 1px dotted #888;
}
.type_list .meta {
display: flex;
}
/*css for type grid*/
.type_grid tr {
display: flex;
flex-flow: column;
width: 31%;
float: left;
padding: 1%;
}
.type_grid .chap_mobile {
display: none;
}
.type_grid .meta .view {
display: none;
}
.type_grid .book-status, .type_grid .chap, .type_grid .tab-type, .type_grid .author {
display: none;
}
@media (max-width: 544px){
.type_grid h3.rv-home-a-title a {
font-size: 13px;
}
}
@media (min-width: 768px){
#search-form button {
width: 30%;
}
.description-category {
font-size: 17px;
}
.type_list td.chap a{
display: block;
}
.book-status {
display: block;
}
.chap_mobile {
display: none;
}
.type_grid tr {
width: 23%;
}
} | 15.827586 | 85 | 0.590142 |
e007ae5939d98a94ab910c4ee571ba5e24c5d2cd | 99 | php | PHP | src/Core/Domain/UpdatedAt.php | opencrypter/api | 9901f41a67751302c9ca582fad5f43c57e974197 | [
"MIT"
] | 3 | 2018-08-03T07:47:29.000Z | 2019-01-27T11:00:12.000Z | src/Core/Domain/UpdatedAt.php | opencrypter/api | 9901f41a67751302c9ca582fad5f43c57e974197 | [
"MIT"
] | 33 | 2018-07-17T16:25:21.000Z | 2019-05-19T09:52:13.000Z | src/Core/Domain/UpdatedAt.php | opencrypter/api | 9901f41a67751302c9ca582fad5f43c57e974197 | [
"MIT"
] | null | null | null | <?php
declare(strict_types=1);
namespace Core\Domain;
final class UpdatedAt extends DateTime
{
}
| 11 | 38 | 0.767677 |
2c9cf497f125e2c9d07587e86f42a6d73c994725 | 397 | py | Python | chapter_11-Interfaces-FromProtocolsToABCs/sample_11_1.py | zixingkong/Fluent-Python | 6f05ec5f27a1cf582ddc5a09959f446d455b6c4a | [
"MIT"
] | null | null | null | chapter_11-Interfaces-FromProtocolsToABCs/sample_11_1.py | zixingkong/Fluent-Python | 6f05ec5f27a1cf582ddc5a09959f446d455b6c4a | [
"MIT"
] | null | null | null | chapter_11-Interfaces-FromProtocolsToABCs/sample_11_1.py | zixingkong/Fluent-Python | 6f05ec5f27a1cf582ddc5a09959f446d455b6c4a | [
"MIT"
] | 1 | 2022-03-14T15:04:58.000Z | 2022-03-14T15:04:58.000Z | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name๏ผ sample_11.1
Description :
date๏ผ 2022/2/18
-------------------------------------------------
"""
class Vector2d:
typecode = 'd'
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __iter__(self):
return (i for i in (self.x, self.y))
| 19.85 | 49 | 0.375315 |
235bce3c095bf341878bf93bc6fcb08c02f765e4 | 8,390 | lua | Lua | Milo Yip's ray-tracing bencmark/smallpt_lua/smallpt.lua | THISISAGOODNAME/miniRayTracing | 48b8fc54df0f11d784bcd783885bc9b39d5ae7b1 | [
"MIT"
] | 2 | 2017-07-13T08:06:32.000Z | 2018-11-22T05:04:44.000Z | Milo Yip's ray-tracing bencmark/smallpt_lua/smallpt.lua | THISISAGOODNAME/miniRayTracing | 48b8fc54df0f11d784bcd783885bc9b39d5ae7b1 | [
"MIT"
] | null | null | null | Milo Yip's ray-tracing bencmark/smallpt_lua/smallpt.lua | THISISAGOODNAME/miniRayTracing | 48b8fc54df0f11d784bcd783885bc9b39d5ae7b1 | [
"MIT"
] | null | null | null | function RandomLCG(seed)
return function ()
seed = (214013 * seed + 2531011) % 4294967296
return seed * (1.0 / 4294967296.0)
end
end
---------------------------------------
Vec = {}
Vec.__index = Vec
function Vec.new(x_, y_, z_)
local self = { x = x_, y = y_, z = z_}
setmetatable(self, Vec)
return self
end
function Vec.__add(a, b)
return Vec.new(a.x + b.x, a.y + b.y, a.z + b.z)
end
function Vec.__sub(a, b)
return Vec.new(a.x - b.x, a.y - b.y, a.z - b.z)
end
function Vec.__mul(a, b)
return Vec.new(a.x * b, a.y * b, a.z * b)
end
-- component-wise multiplication
function Vec:mult(b)
return Vec.new(self.x * b.x, self.y * b.y, self.z * b.z)
end
function Vec:norm()
return self * (1.0 / math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z))
end
function Vec:dot(b)
return self.x * b.x + self.y * b.y + self.z * b.z
end
-- cross product
function Vec.__mod(a, b)
return Vec.new(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x)
end
Vec.Zero = Vec.new(0, 0, 0)
Vec.XAxis = Vec.new(1, 0, 0)
Vec.YAxis = Vec.new(0, 1, 0)
Vec.ZAxis = Vec.new(0, 0, 1)
---------------------------------------
Refl =
{
DIFF = 0,
SPEC = 1,
REFR = 2
}
---------------------------------------
Ray = {}
Ray.__index = Ray
function Ray.new(o_, d_)
local self = { o = o_, d = d_ }
setmetatable(self, Ray)
return self
end
---------------------------------------
Sphere = {}
Sphere.__index = Sphere
function Sphere.new(rad_, p_, e_, c_, refl_)
local self = { rad = rad_, p = p_, e = e_, c = c_, refl = refl_ }
self.sqRad = rad_ * rad_
self.maxC = math.max(math.max(c_.x, c_.y), c_.z)
self.cc = c_ * (1.0 / self.maxC)
setmetatable(self, Sphere)
return self
end
function Sphere:intersect(r)
-- Solve t^2*d.d + 2*t*(o-p).d + (o-p).(o-p)-R^2 = 0
local op = self.p - r.o
local b = op:dot(r.d)
local det = b * b - op:dot(op) + self.sqRad
local eps = 1e-4
if det < 0 then
return 0
else
local dets = math.sqrt(det)
if b - dets > eps then
return b - dets
elseif b + dets > eps then
return b + dets
else
return 0
end
end
end
---------------------------------------
-- Scene: radius, position, emission, color, material
spheres =
{
Sphere.new(1e5, Vec.new( 1e5+1,40.8,81.6), Vec.Zero, Vec.new(.75,.25,.25), Refl.DIFF), --Left
Sphere.new(1e5, Vec.new(-1e5+99,40.8,81.6), Vec.Zero, Vec.new(.25,.25,.75), Refl.DIFF), --Rght
Sphere.new(1e5, Vec.new(50,40.8, 1e5), Vec.Zero, Vec.new(.75,.75,.75), Refl.DIFF), --Back
Sphere.new(1e5, Vec.new(50,40.8,-1e5+170), Vec.Zero, Vec.Zero, Refl.DIFF), --Frnt
Sphere.new(1e5, Vec.new(50, 1e5, 81.6), Vec.Zero, Vec.new(.75,.75,.75), Refl.DIFF), --Botm
Sphere.new(1e5, Vec.new(50,-1e5+81.6,81.6), Vec.Zero, Vec.new(.75,.75,.75), Refl.DIFF), --Top
Sphere.new(16.5, Vec.new(27,16.5,47), Vec.Zero, Vec.new(1,1,1)*.999, Refl.SPEC), --Mirr
Sphere.new(16.5, Vec.new(73,16.5,78), Vec.Zero, Vec.new(1,1,1)*.999, Refl.REFR), --Glas
Sphere.new(600, Vec.new(50,681.6-.27,81.6), Vec.new(12,12,12), Vec.Zero, Refl.DIFF) --Lite
}
rand = RandomLCG(0)
function clamp(x)
if x < 0 then
return 0
elseif x > 1 then
return 1
else
return x
end
end
function toInt(x)
return (clamp(x) ^ (1 / 2.2)) * 255 + .5
end
function intersect(r)
local t = 1e20
local obj
for i, s in ipairs(spheres) do
local d = s:intersect(r)
if d ~= 0 and d < t then
t = d
obj = s
end
end
return obj, t
end
function radiance(r, depth)
local obj, t
obj, t = intersect(r)
if obj == nil then
return Vec.Zero
else
local newDepth = depth + 1
local isMaxDepth = newDepth > 100
-- Russian roulette for path termination
local isUseRR = newDepth > 5
local isRR = isUseRR and rand() < obj.maxC
if isMaxDepth or (isUseRR and not isRR) then
return obj.e
else
local f = (isUseRR and isRR) and obj.cc or obj.c
local x = r.o + r.d * t
local n = (x - obj.p):norm()
local nl = (n:dot(r.d) < 0) and n or (n * -1)
if obj.refl == Refl.DIFF then -- Ideal DIFFUSE reflection
local r1 = 2 * math.pi * rand()
local r2 = rand()
local r2s = math.sqrt(r2)
local w = nl
local wo = (math.abs(w.x) > .1) and Vec.YAxis or Vec.XAxis
local u = (wo % w):norm()
local v = w % u
local d = (u * math.cos(r1) * r2s + v * math.sin(r1) * r2s + w * math.sqrt(1 - r2)):norm()
return obj.e + f:mult(radiance(Ray.new(x, d), newDepth))
elseif obj.refl == Refl.SPEC then -- Ideal SPECULAR reflection
return obj.e + f:mult(radiance(Ray.new(x, r.d - n * 2 * n:dot(r.d)), newDepth))
else -- Ideal dielectric REFRACTION
local reflRay = Ray.new(x, r.d - n * (2 * n:dot(r.d)))
local into = n:dot(nl) > 0 -- Ray from outside going in?
local nc = 1
local nt = 1.5
local nnt = into and (nc / nt) or (nt / nc)
local ddn = r.d:dot(nl)
local cos2t = 1 - nnt * nnt * (1 - ddn * ddn)
if cos2t < 0 then -- Total internal reflection
return obj.e + f:mult(radiance(reflRay, newDepth))
else
local tdir = (r.d * nnt - n * ((into and 1 or -1) * (ddn * nnt + math.sqrt(cos2t)))):norm()
local a = nt - nc
local b = nt + nc
local R0 = (a * a) / (b * b)
local c = 1 - (into and -ddn or tdir:dot(n))
local Re = R0 + (1 - R0) * c * c * c * c * c
local Tr = 1 - Re
local P = .25 + .5 * Re
local RP = Re / P
local TP = Tr / (1 - P)
local result
if newDepth > 2 then
-- Russian roulette and splitting for selecting reflection and/or refraction
if rand() < P then
result = radiance(reflRay, newDepth) * RP
else
result = radiance(Ray.new(x, tdir), newDepth) * TP
end
else
result = radiance(reflRay, newDepth) * Re + radiance(Ray.new(x, tdir), newDepth) * Tr
end
return obj.e + f:mult(result)
end
end
end
end
end
local start = os.clock()
local w = 256
local h = 256
local samps = 25
-- cam pos, dir
local cam = Ray.new(Vec.new(50, 52, 295.6), Vec.new(0, -0.042612, -1):norm())
local cx = Vec.new(w * .5135 / h, 0, 0)
local cy = (cx % cam.d):norm() * .5135
-- final color buffer
local c = {}
-- Loop over image rows
for y = 0, h - 1 do
io.stderr:write(string.format("\rRendering (%d spp) %5.2f%%", samps * 4, 100 * y / (h - 1)))
-- Loop cols
for x = 0, w - 1 do
local i = (h - y - 1) * w + x
c[i] = Vec.Zero
-- 2x2 subpixel rows
for sy = 0, 1 do
-- 2x2 subpixel cols
for sx = 0, 1 do
local r = Vec.Zero
for s = 1, samps do
local r1 = 2 * rand()
local r2 = 2 * rand()
local dx = (r1 < 1) and (math.sqrt(r1) - 1) or (1 - math.sqrt(2 - r1))
local dy = (r2 < 1) and (math.sqrt(r2) - 1) or (1 - math.sqrt(2 - r2))
local d = cx * (((sx + .5 + dx) / 2 + x) / w - .5) +
cy * (((sy + .5 + dy) / 2 + y) / h - .5) + cam.d
-- Camera rays are pushed forward to start in interior
local camRay = Ray.new(cam.o + d * 140, d:norm())
-- Accumuate radiance
r = r + radiance(camRay, 0) * (1.0 / samps)
end
-- Convert radiance to color
c[i] = c[i] + Vec.new(clamp(r.x), clamp(r.y), clamp(r.z)) * .25
end
end
end
end
print(string.format("\n%f sec", os.clock() - start))
local f = io.open("image.ppm", "w")
f:write(string.format("P3\n%d %d\n%d\n", w, h, 255))
for i = 0, w * h -1 do
f:write(string.format("%d %d %d\n", toInt(c[i].x), toInt(c[i].y), toInt(c[i].z)))
end
| 28.831615 | 111 | 0.493325 |
9816b417b85814c0967ceff1a4383ff3d6a18a54 | 622 | py | Python | sources/migrations/0011_auto_20170106_1632.py | jaymcgrath/ewe_ebooks | 06ffa6c881d205ab00a55c195ee79bccd2da77ec | [
"MIT"
] | 4 | 2016-12-05T18:32:48.000Z | 2019-01-26T21:42:53.000Z | sources/migrations/0011_auto_20170106_1632.py | jaymcgrath/ewe_ebooks | 06ffa6c881d205ab00a55c195ee79bccd2da77ec | [
"MIT"
] | 14 | 2016-11-30T01:03:59.000Z | 2019-01-26T21:37:25.000Z | sources/migrations/0011_auto_20170106_1632.py | jaymcgrath/ewe_ebooks | 06ffa6c881d205ab00a55c195ee79bccd2da77ec | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-01-07 00:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sources', '0010_auto_20170106_1603'),
]
operations = [
migrations.RemoveField(
model_name='corpus',
name='type',
),
migrations.AddField(
model_name='corpus',
name='variety',
field=models.CharField(choices=[('TW', 'Twitter User'), ('EX', 'Text Excerpt')], default='TW', max_length=2),
),
]
| 24.88 | 121 | 0.583601 |
b637a491716e29d00402e10fc1f712e83108a30f | 2,018 | rb | Ruby | lib/maven_pom/pom.rb | finn-no/maven_pom | 30c4f9f38dc6c7b19d5a644e918742d1b8f01cb6 | [
"MIT"
] | 1 | 2015-11-05T01:00:54.000Z | 2015-11-05T01:00:54.000Z | lib/maven_pom/pom.rb | finn-no/maven_pom | 30c4f9f38dc6c7b19d5a644e918742d1b8f01cb6 | [
"MIT"
] | null | null | null | lib/maven_pom/pom.rb | finn-no/maven_pom | 30c4f9f38dc6c7b19d5a644e918742d1b8f01cb6 | [
"MIT"
] | 2 | 2015-04-09T18:17:54.000Z | 2019-05-06T17:58:17.000Z | module MavenPom
class Pom
attr_reader :uri
def initialize(str, uri)
@pom = Nokogiri.XML(str)
@uri = uri
MavenPom.all[key] = self
end
def as_json(opts = nil)
{
:key => key,
:name => name,
:parent => parent,
:packaging => packaging
}
end
def to_json(*args)
as_json.to_json(*args)
end
def inspect
"#<MavenPom::Pom:0x%x key=%s name=%s parent=%s>" % [object_id << 1, key.inspect, name.inspect, parent.inspect]
end
def packaging
@pom.css("project > packaging").text
end
def name
@pom.css("project > name").text.strip
end
def build_plugins
@pom.css("plugins > plugin").map do |node|
dependency_name_from(node)
end
end
def parent
parent = @pom.css("project > parent").first
if parent
gid = parent.css("groupId").text
aid = parent.css("artifactId").text
"#{gid}:#{aid}"
end
end
def group_id
gid = @pom.css("project > groupId").text
gid = @pom.css("project > parent > groupId").text if gid.empty?
if gid.empty?
raise MissingGroupIdError, "could not find groupId in pom (uri=#{uri.inspect})"
end
gid
end
def parent_pom
MavenPom.all[parent]
end
def artifact_id
@pom.css("project > artifactId").text
end
def key
@key ||= "#{group_id}:#{artifact_id}"
end
def dependencies
@pom.css("dependencies > dependency").map do |node|
dependency_name_from(node)
end
end
def properties
props = {}
@pom.css("project > properties > *").each do |element|
props[element.name] = element.inner_text
end
props
end
def dependency_name_from(node)
gid = node.css("groupId").text
aid = node.css("artifactId").text
gid = group_id if gid == "${project.groupId}" # ugh
"#{gid}:#{aid}"
end
end # Pom
end # Maven
| 19.403846 | 116 | 0.5555 |
ff50b468006ef1acf085a7e58e05f893b9ed02fd | 656 | py | Python | layers/poky/meta/lib/oeqa/sdk/cases/perl.py | dtischler/px30-test | 55dce0b7aff1c4a7dea3ac94f94cc9c67fba7c9f | [
"Apache-2.0"
] | 53 | 2018-02-28T08:51:32.000Z | 2022-02-28T06:49:23.000Z | meta/lib/oeqa/sdk/cases/perl.py | nareshgbhat/luv-yocto | 48976c54238dda0791e274927371265d259c0e5a | [
"MIT"
] | 27 | 2018-01-25T00:26:53.000Z | 2020-08-09T05:20:04.000Z | meta/lib/oeqa/sdk/cases/perl.py | nareshgbhat/luv-yocto | 48976c54238dda0791e274927371265d259c0e5a | [
"MIT"
] | 51 | 2018-02-21T04:46:08.000Z | 2022-03-02T04:20:41.000Z | import unittest
from oeqa.sdk.case import OESDKTestCase
class PerlTest(OESDKTestCase):
@classmethod
def setUpClass(self):
if not (self.tc.hasHostPackage("nativesdk-perl") or
self.tc.hasHostPackage("perl-native")):
raise unittest.SkipTest("No perl package in the SDK")
def test_perl(self):
try:
cmd = "perl -e '$_=\"Uryyb, jbeyq\"; tr/a-zA-Z/n-za-mN-ZA-M/;print'"
output = self._run(cmd)
self.assertEqual(output, "Hello, world")
except subprocess.CalledProcessError as e:
self.fail("Unexpected exit %d (output %s)" % (e.returncode, e.output))
| 36.444444 | 82 | 0.615854 |
89baae91903b47687d2513bcff5a7ea50e7738cc | 10,440 | swift | Swift | ApplepieDemo/ApplepieTests/UI/Router/APRouterTests.swift | cdtschange/ios-applepie | e0db0cb5b6564011e4f55342a701909e876853e3 | [
"MIT"
] | 3 | 2018-11-14T10:08:40.000Z | 2021-02-03T07:20:49.000Z | ApplepieDemo/ApplepieTests/UI/Router/APRouterTests.swift | cdtschange/ios-applepie | e0db0cb5b6564011e4f55342a701909e876853e3 | [
"MIT"
] | null | null | null | ApplepieDemo/ApplepieTests/UI/Router/APRouterTests.swift | cdtschange/ios-applepie | e0db0cb5b6564011e4f55342a701909e876853e3 | [
"MIT"
] | 1 | 2018-11-17T18:08:49.000Z | 2018-11-17T18:08:49.000Z | //
// APRouterTests.swift
// ApplepieTests
//
// Created by ๅฑฑๅคฉๅคง็ on 2018/12/13.
// Copyright ยฉ 2018 ๅฑฑๅคฉๅคง็. All rights reserved.
//
import XCTest
import Applepie
import PromiseKit
class APRouterTests: BaseTestCase {
@objc(ViewController1)
private class ViewController1: UIViewController {}
@objc(ViewController2)
private class ViewController2: UIViewController, APRouterProtocol {
var params: [String : Any] = [:]
}
@objc(ViewController3)
private class ViewController3: UIViewController {}
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testRouter() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let expectation = XCTestExpectation(description: "Complete")
let root = UIViewController.topMostViewController()
var v2: ViewController2?
let delayTime = 1000
firstly {
assert(root != nil)
root?.tabBarController?.selectedIndex = 1
return after(.seconds(1))
}.then { () -> Guarantee<Void> in
root?.tabBarController?.selectedIndex = 0
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
APRouter.route(toName: "ListTypeViewController", params: ["type": "both"], animation: false, pop: false)
return after(.seconds(2))
}.then { () -> Guarantee<Void> in
APRouter.routeBack()
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
APRouter.route(toName: "BaseWebViewController", params: ["url": "https://www.baidu.com"], storyboardName: nil, animation: false, pop: false)
return after(.seconds(2))
}.then { () -> Guarantee<Void> in
APRouter.routeBack()
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.route(toName: "None", animation: false, pop: true) == false)
assert(APRouter.route(toName: "routeToLogin", animation: false, pop: true) == true)
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ApplepieDemo.ViewController")
assert(APRouter.routeBack(animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(UIViewController.topMostViewController() == root)
let nav = UINavigationController(rootViewController: ViewController1())
root?.present(nav, animated: false, completion: nil)
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController1")
assert(APRouter.route(toUrl: "http://test", name: "ViewController2", params: ["a": "1", "b": 2, "c": true, "d": 1.2], animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController2")
v2 = UIViewController.topMostViewController() as? ViewController2
assert((v2?.params["a"] as? String) == "1")
assert((v2?.params["b"] as? Int) == 2)
assert((v2?.params["c"] as? Bool) == true)
assert((v2?.params["d"] as? Double) == 1.2)
assert((v2?.params["url"] as? String) == "http://test")
assert(UIViewController.topMostViewController()?.navigationController?.viewControllers.count == 2)
assert(APRouter.route(toName: "ViewController3", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController3")
assert(UIViewController.topMostViewController()?.ap.containsViewControllerInNavigation("ViewController2") == true)
assert(UIViewController.topMostViewController()?.ap.containsViewControllerInNavigation("ViewController1") == true)
assert(UIViewController.topMostViewController()?.ap.containsViewControllerInNavigation("ViewController3") == true)
assert(UIViewController.topMostViewController()?.ap.containsViewControllerInNavigation("ViewController4") == false)
assert(APRouter.routeBack(params: ["a": "2"], animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController2")
assert((v2?.params["a"] as? String) == "2")
assert(APRouter.route(toName: "ViewController3", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.routeBack(toName: "ViewController4", animation: false) == false)
assert(APRouter.routeBack(toName: "ViewController2", params: ["a": "3"], animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController2")
assert((v2?.params["a"] as? String) == "3")
assert(APRouter.routeBack(toName: "ViewController1", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController1")
assert(APRouter.route(toName: "ViewController2", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.route(toName: "ViewController3", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.routeBack(skip: 0, animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController2")
assert(APRouter.route(toName: "ViewController3", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.routeBack(skip: 1, animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController1")
assert(APRouter.route(toName: "ViewController2", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.route(toName: "ViewController3", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.route(toName: "ViewController2", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.route(toName: "ViewController3", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(APRouter.route(toName: "ViewController2", animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(UIViewController.topMostViewController()?.navigationController?.viewControllers.count == 6)
assert(APRouter.route(toName: "ViewController3", animation: false, pop: true) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController3")
assert(APRouter.routeBack(toName: "ViewController2", animation: false) == false)
assert(APRouter.routeBack(animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController2")
assert(APRouter.route(toName: "ViewController3", animation: false, pop: true) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController3")
assert(APRouter.routeBack(skip: 1, animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController2")
assert(APRouter.routeBack(skip: 5, animation: false) == false)
assert(APRouter.routeToRoot(animation: false) == true)
return after(.milliseconds(delayTime))
}.then { () -> Guarantee<Void> in
assert(NSStringFromClass(UIViewController.topMostViewController()!.classForCoder) == "ViewController1")
assert(APRouter.routeBack(animation: false) == true)
return after(.milliseconds(delayTime))
}.done { _ in
expectation.fulfill()
}
wait(for: [expectation], timeout: 60)
}
}
| 60.697674 | 160 | 0.609291 |
43bb19569b634ef339ee3fdba26c4b86ce79b570 | 1,148 | tsx | TypeScript | src/components/homePage/functionalities.tsx | MargotDem/website-netlify | d2076758bc5b55d9b91dc6f192a2f12ab1f30bbe | [
"MIT"
] | null | null | null | src/components/homePage/functionalities.tsx | MargotDem/website-netlify | d2076758bc5b55d9b91dc6f192a2f12ab1f30bbe | [
"MIT"
] | null | null | null | src/components/homePage/functionalities.tsx | MargotDem/website-netlify | d2076758bc5b55d9b91dc6f192a2f12ab1f30bbe | [
"MIT"
] | null | null | null | import React from "react";
import Slides from "./slides";
const Functionalities = () => {
return (
<div className="functionalities-container">
<section className="home-section">
<div className="home-section-top">
<h2>Simple, mais pas simpliste</h2>
<p>
Comme nous savons faire la diffรฉrence entre un produit โรฉpurรฉโ et
une solution โvideโ,
</p>
<p>
nous avons dotรฉ Nua.ge de fonctionnalitรฉs que nous jugeons
indispensables.
</p>
</div>
<div className="functionalities-slides column is-10">
{/* <Slides /> */}
</div>
<div className="home-section-bottom">
<p>Vous nโen attendiez ni plus ni moins ?</p>
<div className="home-section-bottom-buttons">
<button className="button purple-button">Testez-nous</button>
<button className="button transparent-button transparent-purple-button">
Discutez avec lโรฉquipe
</button>
</div>
</div>
</section>
</div>
);
};
export default Functionalities;
| 29.435897 | 84 | 0.56446 |
06bf9bebf1a6b0287bec229f815666d1c1f01952 | 870 | py | Python | GetElementIsHidden.py | gnomesoup/pyDynamo | dea046e96f7973fcb6c28a274a3092b246457551 | [
"Unlicense",
"MIT"
] | null | null | null | GetElementIsHidden.py | gnomesoup/pyDynamo | dea046e96f7973fcb6c28a274a3092b246457551 | [
"Unlicense",
"MIT"
] | null | null | null | GetElementIsHidden.py | gnomesoup/pyDynamo | dea046e96f7973fcb6c28a274a3092b246457551 | [
"Unlicense",
"MIT"
] | null | null | null | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.Elements)
doc = DocumentManager.Instance.CurrentDBDocument
views = UnwrapElement(IN[0])
elementList = UnwrapElement(IN[1])
outList = []
for view, elements in zip(views, elementList):
hiddenList = []
for element in elements:
hidden = element.IsHidden(view)
category = element.Category
while (not hidden) and (category is not None):
try:
hidden = not category.get_Visible(view)
category = category.Parent
except:
category = None
hiddenList.append(hidden)
outList.append(hiddenList)
OUT = outList
| 24.166667 | 55 | 0.686207 |
e4aa306d5b8eecf2c73db3ad842e56d227454d41 | 338 | rs | Rust | src/mpi_request.rs | sushant94/mpirs | f1e2e241fb94200f93eee7ad280f68049a1ee83a | [
"Apache-2.0",
"MIT"
] | 1 | 2019-02-25T15:53:15.000Z | 2019-02-25T15:53:15.000Z | src/mpi_request.rs | sushant94/mpirs | f1e2e241fb94200f93eee7ad280f68049a1ee83a | [
"Apache-2.0",
"MIT"
] | null | null | null | src/mpi_request.rs | sushant94/mpirs | f1e2e241fb94200f93eee7ad280f68049a1ee83a | [
"Apache-2.0",
"MIT"
] | 2 | 2019-02-23T11:39:11.000Z | 2019-02-25T11:59:17.000Z | // MPIRequest structure
#[derive(Debug, Clone, Default)]
pub struct MPIRequest {
src: Option<usize>,
dest: Option<usize>,
tag: Option<u64>
}
impl MPIRequest {
pub fn new(src: usize, dest: usize, tag: u64) -> MPIRequest{
MPIRequest{
src: Some(src),
dest: Some(dest),
tag: Some(tag)
}
}
}
| 17.789474 | 64 | 0.588757 |
cc9569688c140cd3cc12d1da24a378d1780958e1 | 235 | rb | Ruby | db/migrate/20190305161420_create_tips.rb | catmando/roll365 | 004ce355be088a3809fcf197f5e960b0bd34aac8 | [
"MIT"
] | null | null | null | db/migrate/20190305161420_create_tips.rb | catmando/roll365 | 004ce355be088a3809fcf197f5e960b0bd34aac8 | [
"MIT"
] | 10 | 2020-02-29T04:03:54.000Z | 2022-02-26T10:29:16.000Z | db/migrate/20190305161420_create_tips.rb | catmando/roll365 | 004ce355be088a3809fcf197f5e960b0bd34aac8 | [
"MIT"
] | 1 | 2019-08-15T21:35:11.000Z | 2019-08-15T21:35:11.000Z | class CreateTips < ActiveRecord::Migration[5.2]
def change
create_table :tips do |t|
t.string :name
t.integer :company_id
t.decimal :fee
t.string :fire_ant_risk_level
t.timestamps
end
end
end
| 18.076923 | 47 | 0.646809 |
7f60ea9b78951071e82ea74d1836614b1a85a446 | 12,477 | php | PHP | application/controllers/Petugas.php | rahmatrafli1/perpustakaan | 827c495ec0caa71bd61228bdd3278db54198dd02 | [
"MIT"
] | null | null | null | application/controllers/Petugas.php | rahmatrafli1/perpustakaan | 827c495ec0caa71bd61228bdd3278db54198dd02 | [
"MIT"
] | null | null | null | application/controllers/Petugas.php | rahmatrafli1/perpustakaan | 827c495ec0caa71bd61228bdd3278db54198dd02 | [
"MIT"
] | null | null | null | <?php
defined('BASEPATH') or exit('No direct script access allowed');
class Petugas extends CI_Controller
{
function __construct()
{
parent::__construct();
// cek session yang login, jika session status tidak sama dengan session petugas_login,maka halaman akan di alihkan kembali ke halaman login.
if ($this->session->userdata('status') != "petugas_login") {
redirect(base_url() . 'login?alert=belum_login');
}
}
function index()
{
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_index');
$this->load->view('petugas/v_footer');
}
function logout()
{
$this->session->sess_destroy();
redirect(base_url() . 'login/?alert=logout');
}
function ganti_password()
{
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_ganti_password');
$this->load->view('petugas/v_footer');
}
function ganti_password_aksi()
{
$baru = $this->input->post('password_baru');
$ulang = $this->input->post('password_ulang');
$this->form_validation->set_rules('password_baru', 'Password Baru', 'required|matches[password_ulang]');
$this->form_validation->set_rules('password_ulang', 'Ulangi
Password', 'required');
if ($this->form_validation->run() != false) {
$id = $this->session->userdata('id');
$where = array('id' => $id);
$data = array('password' => md5($baru));
$this->m_data->update_data($where, $data, 'petugas');
redirect(base_url() . 'petugas/ganti_password/?alert=sukses');
} else {
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_ganti_password');
$this->load->view('petugas/v_footer');
}
}
// crud anggota
function anggota()
{
// mengambil data dari database
$data['anggota'] = $this->m_data->get_data('anggota')->result();
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_anggota', $data);
$this->load->view('petugas/v_footer');
}
function anggota_tambah()
{
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_anggota_tambah');
$this->load->view('petugas/v_footer');
}
function anggota_tambah_aksi()
{
$nama = $this->input->post('nama');
$nik = $this->input->post('nik');
$alamat = $this->input->post('alamat');
$data = array(
'nama' => $nama,
'nik' => $nik,
'alamat' => $alamat
);
// insert data ke database
$this->m_data->insert_data($data, 'anggota');
// mengalihkan halaman ke halaman data anggota
redirect(base_url() . 'petugas/anggota');
}
function anggota_edit($id)
{
$where = array('id' => $id);
// mengambil data dari database sesuai id
$data['anggota'] = $this->m_data->edit_data($where, 'anggota')->result();
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_anggota_edit', $data);
$this->load->view('petugas/v_footer');
}
function anggota_update()
{
$id = $this->input->post('id');
$nama = $this->input->post('nama');
$nik = $this->input->post('nik');
$alamat = $this->input->post('alamat');
$where = array(
'id' => $id
);
$data = array(
'nama' => $nama,
'nik' => $nik,
'alamat' => $alamat
);
// update data ke database
$this->m_data->update_data($where, $data, 'anggota');
// mengalihkan halaman ke halaman data anggota
redirect(base_url() . 'petugas/anggota');
}
function anggota_hapus($id)
{
$where = array(
'id' => $id
);
// menghapus data anggota dari database sesuai id
$this->m_data->delete_data($where, 'anggota');
// mengalihkan halaman ke halaman data anggota
redirect(base_url() . 'petugas/anggota');
}
function anggota_kartu($id)
{
$where = array('id' => $id);
// mengambil data dari database sesuai id
$data['anggota'] = $this->m_data->edit_data($where, 'anggota')->result();
$this->load->view('petugas/v_anggota_kartu', $data);
}
// akhir crud anggota
// crud buku
function buku()
{
// mengambil data dari database
$data['buku'] = $this->m_data->get_data('buku')->result();
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_buku', $data);
$this->load->view('petugas/v_footer');
}
function buku_tambah()
{
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_buku_tambah');
$this->load->view('petugas/v_footer');
}
function buku_tambah_aksi()
{
$judul = $this->input->post('judul');
$tahun = $this->input->post('tahun');
$penulis = $this->input->post('penulis');
$data = array(
'judul' => $judul,
'tahun' => $tahun,
'penulis' => $penulis,
'status' => 1
);
// insert data ke database
$this->m_data->insert_data($data, 'buku');
// mengalihkan halaman ke halaman data buku
redirect(base_url() . 'petugas/buku');
}
function buku_edit($id)
{
$where = array('id' => $id);
// mengambil data dari database sesuai id
$data['buku'] = $this->m_data->edit_data($where, 'buku')->result();
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_buku_edit', $data);
$this->load->view('petugas/v_footer');
}
function buku_update()
{
$id = $this->input->post('id');
$judul = $this->input->post('judul');
$tahun = $this->input->post('tahun');
$penulis = $this->input->post('penulis');
$status = $this->input->post('status');
$where = array(
'id' => $id
);
$data = array(
'judul' => $judul,
'tahun' => $tahun,
'penulis' => $penulis,
'status' => $status
);
// update data ke database
$this->m_data->update_data($where, $data, 'buku');
// mengalihkan halaman ke halaman data buku
redirect(base_url() . 'petugas/buku');
}
function buku_hapus($id)
{
$where = array(
'id' => $id
);
// menghapus data buku dari database sesuai id
$this->m_data->delete_data($where, 'buku');
// mengalihkan halaman ke halaman data buku
redirect(base_url() . 'petugas/buku');
}
// akhir crud buku
// proses transaksi_peminjaman
function peminjaman()
{
// mengambil data peminjaman buku dari database | dan mengurutkan data dari id peminjaman terbesar ke terkecil (desc)
$data['peminjaman'] = $this->db->query("select * from
peminjaman,buku,anggota where peminjaman.peminjaman_buku=buku.id and
peminjaman.peminjaman_anggota=anggota.id order by peminjaman_id desc")->result();
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_peminjaman', $data);
$this->load->view('petugas/v_footer');
}
function peminjaman_tambah()
{
// mengambil data buku yang berstatus 1 (tersedia) dari database
$where = array('status' => 1);
$data['buku'] = $this->m_data->edit_data($where, 'buku')->result();
// mengambil data anggota dari database
$data['anggota'] = $this->m_data->get_data('anggota')->result();
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_peminjaman_tambah', $data);
$this->load->view('petugas/v_footer');
}
function peminjaman_aksi()
{
$buku = $this->input->post('buku');
$anggota = $this->input->post('anggota');
$tanggal_mulai = $this->input->post('tanggal_mulai');
$tanggal_sampai = $this->input->post('tanggal_sampai');
$data = array(
'peminjaman_buku' => $buku,
'peminjaman_anggota' => $anggota,
'peminjaman_tanggal_mulai' => $tanggal_mulai,
'peminjaman_tanggal_sampai' => $tanggal_sampai,
'peminjaman_status' => 2
);
// insert data ke database
$this->m_data->insert_data($data, 'peminjaman');
// mengubah status buku menjadi di pinjam (2)
$w = array(
'id' => $buku
);
$d = array(
'status' => 2
);
$this->m_data->update_data($w, $d, 'buku');
// mengalihkan halaman ke halaman data peminjaman
redirect(base_url() . 'petugas/peminjaman');
}
function peminjaman_batalkan($id)
{
$where = array(
'peminjaman_id' => $id
);
// mengambil data buku pada peminjaman ber id tersebut
$data = $this->m_data->edit_data($where, 'peminjaman')->row();
$buku = $data->peminjaman_buku;
// mengembalikan status buku kembali ke tersedia (1)
$w = array(
'id' => $buku
);
$d = array(
'status' => 1
);
$this->m_data->update_data($w, $d, 'buku');
// menghapus data peminjaman dari database sesuai id
$this->m_data->delete_data($where, 'peminjaman');
// mengalihkan halaman ke halaman data buku
redirect(base_url() . 'petugas/peminjaman');
}
function peminjaman_selesai($id)
{
$where = array(
'peminjaman_id' => $id
);
// mengambil data buku pada peminjaman ber id tersebut
$data = $this->m_data->edit_data($where, 'peminjaman')->row();
$buku = $data->peminjaman_buku;
// mengembalikan status buku kembali ke tersedia (1)
$w = array(
'id' => $buku
);
$d = array(
'status' => 1
);
$this->m_data->update_data($w, $d, 'buku');
// mengubah status peminjaman menjadi selesai (1)
$this->m_data->update_data($where, array('peminjaman_status' => 1), 'peminjaman');
// mengalihkan halaman ke halaman data buku
redirect(base_url() . 'petugas/peminjaman');
}
function peminjaman_laporan()
{
if (isset($_GET['tanggal_mulai']) && isset($_GET['tanggal_sampai'])) {
$mulai = $this->input->get('tanggal_mulai');
$sampai = $this->input->get('tanggal_sampai');
// mengambil data peminjaman berdasarkan tanggal mulai sampai tanggal sampai
$data['peminjaman'] = $this->db->query("select * from
peminjaman,buku,anggota where peminjaman.peminjaman_buku=buku.id and
peminjaman.peminjaman_anggota=anggota.id and date(peminjaman_tanggal_mulai) >=
'$mulai' and date(peminjaman_tanggal_mulai) <= '$sampai' order by peminjaman_id
desc")->result();
} else {
// mengambil data peminjaman buku dari database | dan mengurutkan data dari id peminjaman terbesar ke terkecil (desc)
$data['peminjaman'] = $this->db->query("select * from
peminjaman,buku,anggota where peminjaman.peminjaman_buku=buku.id and
peminjaman.peminjaman_anggota=anggota.id order by peminjaman_id desc")->result();
}
$this->load->view('petugas/v_header');
$this->load->view('petugas/v_peminjaman_laporan', $data);
$this->load->view('petugas/v_footer');
}
function peminjaman_cetak()
{
if (isset($_GET['tanggal_mulai']) && isset($_GET['tanggal_sampai'])) {
$mulai = $this->input->get('tanggal_mulai');
$sampai = $this->input->get('tanggal_sampai');
// mengambil data peminjaman berdasarkan tanggal mulai sampai tanggal sampai
$data['peminjaman'] = $this->db->query("select * from
peminjaman,buku,anggota where peminjaman.peminjaman_buku=buku.id and
peminjaman.peminjaman_anggota=anggota.id and date(peminjaman_tanggal_mulai) >=
'$mulai' and date(peminjaman_tanggal_mulai) <= '$sampai' order by peminjaman_id
desc")->result();
$this->load->view('petugas/v_peminjaman_cetak', $data);
} else {
redirect(base_url() . 'petugas/peminjaman');
}
}
}
| 35.648571 | 149 | 0.562074 |
5aeec4098a7c63966614c2ef44ef528e2069f4d2 | 240 | cs | C# | Tauron.Application.Wpf/AppCore/SimpleSplashScreen.cs | augustoproiete-bot/Project-Manager-Akka | 1b2df6e34079a71121ab7e20dad4f2ec18afc9c4 | [
"MIT"
] | null | null | null | Tauron.Application.Wpf/AppCore/SimpleSplashScreen.cs | augustoproiete-bot/Project-Manager-Akka | 1b2df6e34079a71121ab7e20dad4f2ec18afc9c4 | [
"MIT"
] | null | null | null | Tauron.Application.Wpf/AppCore/SimpleSplashScreen.cs | augustoproiete-bot/Project-Manager-Akka | 1b2df6e34079a71121ab7e20dad4f2ec18afc9c4 | [
"MIT"
] | null | null | null | ๏ปฟnamespace Tauron.Application.Wpf.AppCore
{
public sealed class SimpleSplashScreen<TSplash> : ISplashScreen
where TSplash : System.Windows.Window, new()
{
public System.Windows.Window Window => new TSplash();
}
} | 30 | 67 | 0.691667 |
7904924e644f6b006781706d6816f56a48b198c7 | 2,607 | lua | Lua | test_scripts/API/ButtonSubscription/Versioning/007_UnsubscribeButton_PLAY_PAUSE_majorVersion_5.lua | LuxoftSDL/sdl_atf_test_scripts | 2594ac912640008fb990594f377068d8e9e2e785 | [
"BSD-3-Clause"
] | 3 | 2016-03-17T02:26:56.000Z | 2021-11-06T08:04:19.000Z | test_scripts/API/ButtonSubscription/Versioning/007_UnsubscribeButton_PLAY_PAUSE_majorVersion_5.lua | smartdevicelink/sdl_atf_test_scripts | 2594ac912640008fb990594f377068d8e9e2e785 | [
"BSD-3-Clause"
] | 1,335 | 2016-03-14T18:29:40.000Z | 2022-03-30T10:40:28.000Z | test_scripts/API/ButtonSubscription/Versioning/007_UnsubscribeButton_PLAY_PAUSE_majorVersion_5.lua | smartdevicelink/sdl_atf_test_scripts | 2594ac912640008fb990594f377068d8e9e2e785 | [
"BSD-3-Clause"
] | 72 | 2016-03-30T13:44:17.000Z | 2021-07-26T06:48:24.000Z | ------------------------------------------------------------------------------------------------------------------------
-- Proposal:
-- https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0192-button_subscription_response_from_hmi.md
------------------------------------------------------------------------------------------------------------------------
-- Description: Check processing of UnsubscribeButton request with 'PLAY_PAUSE' parameter in case
-- mobile app is registered with syncMsgVersion (5.0)
------------------------------------------------------------------------------------------------------------------------
-- In case:
-- 1. Mobile app is registered with major version=5.0
-- 2. Mobile app requests SubscribeButton(PLAY_PAUSE)
-- 3. Mobile app requests UnsubscribeButton(PLAY_PAUSE)
-- SDL does:
-- - send Buttons.UnsubscribeButton(PLAY_PAUSE, appId) to HMI
-- - wait response from HMI
-- - receive Buttons.UnsubscribeButton(SUCCESS)
-- - respond UnsubscribeButton(SUCCESS) to mobile app
-- - send OnHashChange with updated hashId to mobile app
-- In case:
-- 4. HMI sends OnButtonEvent and OnButtonPress notifications for "PLAY_PAUSE"
-- SDL does:
-- - not transfer OnButtonEvent and OnButtonPress to App
------------------------------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require('test_scripts/API/ButtonSubscription/commonButtonSubscription')
--[[ Test Configuration ]]
config.application1.registerAppInterfaceParams.syncMsgVersion.majorVersion = 5
--[[ Local Variables ]]
local appSessionId1 = 1
local buttonName = "PLAY_PAUSE"
--[[ Scenario ]]
common.runner.Title("Preconditions")
common.runner.Step("Clean environment", common.preconditions)
common.runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
common.runner.Step("App registration", common.registerAppWOPTU)
common.runner.Step("App activation", common.activateApp)
common.runner.Step("SubscribeButton " .. buttonName, common.rpcSuccess,
{ appSessionId1, "SubscribeButton", buttonName })
common.runner.Step("On Button Press " .. buttonName, common.buttonPress, { appSessionId1, buttonName })
common.runner.Title("Test")
common.runner.Step("UnsubscribeButton " .. buttonName, common.rpcSuccess,
{ appSessionId1, "UnsubscribeButton", buttonName })
common.runner.Step("Check unsubscribe " .. buttonName, common.buttonPress,
{ appSessionId1, buttonName, common.isNotExpected })
common.runner.Title("Postconditions")
common.runner.Step("Stop SDL", common.postconditions)
| 51.117647 | 120 | 0.633679 |
114fe17217938b4471ff361de3da7e3a3c4fb1c0 | 321 | lua | Lua | GameClient/FGUIProject/plugins/gen_lua_bind/LuaAPI/CS_UnityEngine_LightmapSettings.lua | HappGame/Think | ebf2d9e94a9df54278e0d182abc13f4dd9ff6202 | [
"MIT"
] | 1 | 2021-12-31T01:01:31.000Z | 2021-12-31T01:01:31.000Z | GameClient/FGUIProject/plugins/gen_lua_bind/LuaAPI/CS_UnityEngine_LightmapSettings.lua | HappGame/Think | ebf2d9e94a9df54278e0d182abc13f4dd9ff6202 | [
"MIT"
] | null | null | null | GameClient/FGUIProject/plugins/gen_lua_bind/LuaAPI/CS_UnityEngine_LightmapSettings.lua | HappGame/Think | ebf2d9e94a9df54278e0d182abc13f4dd9ff6202 | [
"MIT"
] | null | null | null | ---@class CS.UnityEngine.LightmapSettings : CS.UnityEngine.Object
---@field public lightmaps LightmapData[]
---@field public lightmapsMode number
---@field public lightProbes CS.UnityEngine.LightProbes
---@type CS.UnityEngine.LightmapSettings
CS.UnityEngine.LightmapSettings = { }
return CS.UnityEngine.LightmapSettings
| 35.666667 | 65 | 0.803738 |
ef9139bec86c88124f0e6b9da8e3deefcb09003c | 823 | rs | Rust | src/bin/triangle2.rs | SiegeEngine/siege-mesh | 369df0361bc98e3573bee308be76951d36f9e2c4 | [
"MIT"
] | null | null | null | src/bin/triangle2.rs | SiegeEngine/siege-mesh | 369df0361bc98e3573bee308be76951d36f9e2c4 | [
"MIT"
] | null | null | null | src/bin/triangle2.rs | SiegeEngine/siege-mesh | 369df0361bc98e3573bee308be76951d36f9e2c4 | [
"MIT"
] | null | null | null | extern crate bincode;
extern crate siege_mesh;
use siege_mesh::{ColoredVertex, Mesh, VertexType};
pub fn main() {
let mesh = define_mesh();
mesh.save(VertexType::Colored, "triangle2.mesh").unwrap();
println!("Saved.");
}
fn define_mesh() -> Mesh<ColoredVertex> {
let vertices = vec![
ColoredVertex {
pos: [-0.97, 0.93, 1.0],
color: [1.0, 0.0, 0.0],
normal: [0.0, 0.0, -1.0],
},
ColoredVertex {
pos: [-0.95, 0.95, 0.0],
color: [1.0, 0.0, 0.0],
normal: [0.0, 0.0, -1.0],
},
ColoredVertex {
pos: [-0.93, 0.93, 1.0],
color: [1.0, 0.0, 0.0],
normal: [0.0, 0.0, -1.0],
},
];
let mut mesh = Mesh::new();
mesh.vertices = vertices;
mesh
}
| 22.861111 | 62 | 0.471446 |
9812b72e70eb0af16ea15bca043e246e57c8dc15 | 414 | py | Python | noteapp/migrations/0002_alter_note_tags.py | saloni027/backend-coding-challenge | 84366d0a9fbbace6d2a4c2fde20caa41ad060483 | [
"MIT"
] | null | null | null | noteapp/migrations/0002_alter_note_tags.py | saloni027/backend-coding-challenge | 84366d0a9fbbace6d2a4c2fde20caa41ad060483 | [
"MIT"
] | null | null | null | noteapp/migrations/0002_alter_note_tags.py | saloni027/backend-coding-challenge | 84366d0a9fbbace6d2a4c2fde20caa41ad060483 | [
"MIT"
] | null | null | null | # Generated by Django 4.0.3 on 2022-03-22 20:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('noteapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='note',
name='tags',
field=models.ManyToManyField(blank=True, related_name='notes', to='noteapp.tag'),
),
]
| 21.789474 | 93 | 0.599034 |
c4f661c8c449dcd035b8b4d25db23c292483ffa0 | 106 | swift | Swift | Tests/SwiftLintTests/TestSwiftSelfAware.swift | MontakOleg/SwiftLintAppCode | 33bae022c6ba07fd2b2417bbec9628a98fdb39f1 | [
"MIT"
] | 45 | 2016-10-09T14:36:34.000Z | 2022-03-06T21:04:36.000Z | Tests/SwiftLintTests/TestSwiftSelfAware.swift | MontakOleg/SwiftLintAppCode | 33bae022c6ba07fd2b2417bbec9628a98fdb39f1 | [
"MIT"
] | 50 | 2017-01-11T11:35:12.000Z | 2022-02-11T19:39:48.000Z | Tests/SwiftLintTests/TestSwiftSelfAware.swift | MontakOleg/SwiftLintAppCode | 33bae022c6ba07fd2b2417bbec9628a98fdb39f1 | [
"MIT"
] | 12 | 2016-10-10T14:52:51.000Z | 2022-02-08T17:53:26.000Z | public class TestSwiftSelfAware {
var test: Int = 0
func test() {
self.test = 32
}
}
| 13.25 | 33 | 0.54717 |
7567b1e5156d0d3c394ed94ef87c034854859d7b | 1,599 | css | CSS | src/App.css | Sigfried/drugutil | 61a6ac12a9317c86ef8292c7b73c0312d340287e | [
"Apache-2.0"
] | null | null | null | src/App.css | Sigfried/drugutil | 61a6ac12a9317c86ef8292c7b73c0312d340287e | [
"Apache-2.0"
] | null | null | null | src/App.css | Sigfried/drugutil | 61a6ac12a9317c86ef8292c7b73c0312d340287e | [
"Apache-2.0"
] | null | null | null | .App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 80px;
}
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}
.App-intro {
font-size: large;
}
@keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.drugrollup {
text-align: left;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
div.timelines {
margin: 5px;
}
div.timeline {
width: 100%;
background-color: cornsilk;
border: 1px solid gray;
margin: 7px;
border-radius: 2%/8%;
padding: 4px;
}
.timeline svg {
}
rect.exposure {
stroke: white;
}
rect.era {
fill: lightgray;
}
.timedist rect {
fill-opacity: 0;
stroke-width: 1.5;
stroke: black;
}
.timedist line.zero {
stroke: red;
}
.distbars line.bar {
stroke: skyblue;
stroke-width: 1;
}
.gapdist line.bar {
stroke: salmon;
stroke-width: 1;
}
div.timeline .description span {
background-color: antiquewhite;
border-radius: 4px;
padding: 1px;
cursor: pointer;
}
.rollup-table {
margin: 10px;
}
.axis path {
display: none;
}
.axis line {
shape-rendering: crispEdges;
stroke: #000;
}
.axis .minor line {
stroke: #777;
stroke-dasharray: 2,2;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
input[type=number]{
width: 60px;
}
.explorer-modal {
width: 95%;
}
| 12.895161 | 47 | 0.646029 |
dd8174ef4e34df65403db322b19a98fe82588a84 | 737 | java | Java | IO/Output.java | himanshugawari/java-code | 115ca4c35e7797b6c11fef9bf041350dbad89357 | [
"MIT"
] | null | null | null | IO/Output.java | himanshugawari/java-code | 115ca4c35e7797b6c11fef9bf041350dbad89357 | [
"MIT"
] | null | null | null | IO/Output.java | himanshugawari/java-code | 115ca4c35e7797b6c11fef9bf041350dbad89357 | [
"MIT"
] | null | null | null | package IO;
import java.lang.Math;
class Output {
// println , print
// public static void main(String[] args) {
// int x = 10, y = 20;
// char z = 'a';
// String str = "GFG";
// System.out.println(x);
// System.out.println(x + y);
// System.out.println(x + " " + y);
// System.out.print(str + " ");
// System.out.print("Courses");
// System.out.print("\n");
// System.out.println(z);
// System.out.println(z + 1);
// System.out.println(z + 'a');
// }
// printf, format
public static void main(String[] args) {
int x = 100, y = 200;
double z = Math.PI;
System.out.format("Value of x is %d\n", x);
System.out.println(z);
System.out.printf("x=%d and y=%d and z=%f", x, y, z);
}
} | 23.774194 | 57 | 0.552239 |
a39781258c8294744eb166d772d6ec1c9d97b184 | 10,330 | java | Java | src/main/java/com/jcraft/jsch/KeyPairDSA.java | danielgrahl/jsch | 79ecf181fad5b1b7ea6479105d30eb08ea90bde8 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/jcraft/jsch/KeyPairDSA.java | danielgrahl/jsch | 79ecf181fad5b1b7ea6479105d30eb08ea90bde8 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/jcraft/jsch/KeyPairDSA.java | danielgrahl/jsch | 79ecf181fad5b1b7ea6479105d30eb08ea90bde8 | [
"BSD-3-Clause"
] | null | null | null | /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2002-2018 ymnk, JCraft,Inc. All rights reserved.
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 following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
package com.jcraft.jsch;
public class KeyPairDSA extends KeyPair{
private byte[] P_array;
private byte[] Q_array;
private byte[] G_array;
private byte[] pub_array;
private byte[] prv_array;
//private int key_size=0;
private int key_size=1024;
public KeyPairDSA(JSch jsch){
this(jsch, null, null, null, null, null);
}
public KeyPairDSA(JSch jsch,
byte[] P_array,
byte[] Q_array,
byte[] G_array,
byte[] pub_array,
byte[] prv_array){
super(jsch);
this.P_array = P_array;
this.Q_array = Q_array;
this.G_array = G_array;
this.pub_array = pub_array;
this.prv_array = prv_array;
if(P_array!=null)
key_size = (new java.math.BigInteger(P_array)).bitLength();
}
void generate(int key_size) throws JSchException{
this.key_size=key_size;
try{
Class c=Class.forName(jsch.getConfig("keypairgen.dsa"));
KeyPairGenDSA keypairgen=(KeyPairGenDSA)(c.newInstance());
keypairgen.init(key_size);
P_array=keypairgen.getP();
Q_array=keypairgen.getQ();
G_array=keypairgen.getG();
pub_array=keypairgen.getY();
prv_array=keypairgen.getX();
keypairgen=null;
}
catch(Exception e){
//System.err.println("KeyPairDSA: "+e);
if(e instanceof Throwable)
throw new JSchException(e.toString(), (Throwable)e);
throw new JSchException(e.toString());
}
}
private static final byte[] begin=Util.str2byte("-----BEGIN DSA PRIVATE KEY-----");
private static final byte[] end=Util.str2byte("-----END DSA PRIVATE KEY-----");
byte[] getBegin(){ return begin; }
byte[] getEnd(){ return end; }
byte[] getPrivateKey(){
int content=
1+countLength(1) + 1 + // INTEGER
1+countLength(P_array.length) + P_array.length + // INTEGER P
1+countLength(Q_array.length) + Q_array.length + // INTEGER Q
1+countLength(G_array.length) + G_array.length + // INTEGER G
1+countLength(pub_array.length) + pub_array.length + // INTEGER pub
1+countLength(prv_array.length) + prv_array.length; // INTEGER prv
int total=
1+countLength(content)+content; // SEQUENCE
byte[] plain=new byte[total];
int index=0;
index=writeSEQUENCE(plain, index, content);
index=writeINTEGER(plain, index, new byte[1]); // 0
index=writeINTEGER(plain, index, P_array);
index=writeINTEGER(plain, index, Q_array);
index=writeINTEGER(plain, index, G_array);
index=writeINTEGER(plain, index, pub_array);
index=writeINTEGER(plain, index, prv_array);
return plain;
}
boolean parse(byte[] plain){
try{
if(vendor==VENDOR_FSECURE){
if(plain[0]!=0x30){ // FSecure
Buffer buf=new Buffer(plain);
buf.getInt();
P_array=buf.getMPIntBits();
G_array=buf.getMPIntBits();
Q_array=buf.getMPIntBits();
pub_array=buf.getMPIntBits();
prv_array=buf.getMPIntBits();
if(P_array!=null)
key_size = (new java.math.BigInteger(P_array)).bitLength();
return true;
}
return false;
}
else if(vendor==VENDOR_PUTTY){
Buffer buf=new Buffer(plain);
buf.skip(plain.length);
try {
byte[][] tmp = buf.getBytes(1, "");
prv_array = tmp[0];
}
catch(JSchException e){
return false;
}
return true;
}
int index=0;
int length=0;
if(plain[index]!=0x30)return false;
index++; // SEQUENCE
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
if(plain[index]!=0x02)return false;
index++; // INTEGER
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
P_array=new byte[length];
System.arraycopy(plain, index, P_array, 0, length);
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
Q_array=new byte[length];
System.arraycopy(plain, index, Q_array, 0, length);
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
G_array=new byte[length];
System.arraycopy(plain, index, G_array, 0, length);
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
pub_array=new byte[length];
System.arraycopy(plain, index, pub_array, 0, length);
index+=length;
index++;
length=plain[index++]&0xff;
if((length&0x80)!=0){
int foo=length&0x7f; length=0;
while(foo-->0){ length=(length<<8)+(plain[index++]&0xff); }
}
prv_array=new byte[length];
System.arraycopy(plain, index, prv_array, 0, length);
index+=length;
if(P_array!=null)
key_size = (new java.math.BigInteger(P_array)).bitLength();
}
catch(Exception e){
//System.err.println(e);
//e.printStackTrace();
return false;
}
return true;
}
public byte[] getPublicKeyBlob(){
byte[] foo=super.getPublicKeyBlob();
if(foo!=null) return foo;
if(P_array==null) return null;
byte[][] tmp = new byte[5][];
tmp[0] = sshdss;
tmp[1] = P_array;
tmp[2] = Q_array;
tmp[3] = G_array;
tmp[4] = pub_array;
return Buffer.fromBytes(tmp).buffer;
}
private static final byte[] sshdss=Util.str2byte("ssh-dss");
byte[] getKeyTypeName(){return sshdss;}
public int getKeyType(){return DSA;}
public int getKeySize(){
return key_size;
}
public byte[] getSignature(byte[] data){
try{
Class c=Class.forName((String)jsch.getConfig("signature.dss"));
SignatureDSA dsa=(SignatureDSA)(c.newInstance());
dsa.init();
dsa.setPrvKey(prv_array, P_array, Q_array, G_array);
dsa.update(data);
byte[] sig = dsa.sign();
byte[][] tmp = new byte[2][];
tmp[0] = sshdss;
tmp[1] = sig;
return Buffer.fromBytes(tmp).buffer;
}
catch(Exception e){
//System.err.println("e "+e);
}
return null;
}
public byte[] getSignature(byte[] data, String alg){
return getSignature(data);
}
public Signature getVerifier(){
try{
Class c=Class.forName((String)jsch.getConfig("signature.dss"));
SignatureDSA dsa=(SignatureDSA)(c.newInstance());
dsa.init();
if(pub_array == null && P_array == null && getPublicKeyBlob()!=null){
Buffer buf = new Buffer(getPublicKeyBlob());
buf.getString();
P_array = buf.getString();
Q_array = buf.getString();
G_array = buf.getString();
pub_array = buf.getString();
}
dsa.setPubKey(pub_array, P_array, Q_array, G_array);
return dsa;
}
catch(Exception e){
//System.err.println("e "+e);
}
return null;
}
public Signature getVerifier(String alg){
return getVerifier();
}
static KeyPair fromSSHAgent(JSch jsch, Buffer buf) throws JSchException {
byte[][] tmp = buf.getBytes(7, "invalid key format");
byte[] P_array = tmp[1];
byte[] Q_array = tmp[2];
byte[] G_array = tmp[3];
byte[] pub_array = tmp[4];
byte[] prv_array = tmp[5];
KeyPairDSA kpair = new KeyPairDSA(jsch,
P_array, Q_array, G_array,
pub_array, prv_array);
kpair.publicKeyComment = new String(tmp[6]);
kpair.vendor=VENDOR_OPENSSH;
return kpair;
}
public byte[] forSSHAgent() throws JSchException {
if(isEncrypted()){
throw new JSchException("key is encrypted.");
}
Buffer buf = new Buffer();
buf.putString(sshdss);
buf.putString(P_array);
buf.putString(Q_array);
buf.putString(G_array);
buf.putString(pub_array);
buf.putString(prv_array);
buf.putString(Util.str2byte(publicKeyComment));
byte[] result = new byte[buf.getLength()];
buf.getByte(result, 0, result.length);
return result;
}
public void dispose(){
super.dispose();
Util.bzero(prv_array);
}
}
| 30.293255 | 85 | 0.620716 |
1371279abd5333a751affd405955a211979159ca | 2,499 | h | C | src/tests/cornell_box.h | shiinamiyuki/LuisaCompute | f8358f8ec138950a84f570c0ede24cc76fc159de | [
"BSD-3-Clause"
] | 31 | 2020-11-21T08:16:53.000Z | 2021-09-05T13:46:32.000Z | src/tests/cornell_box.h | shiinamiyuki/LuisaCompute | f8358f8ec138950a84f570c0ede24cc76fc159de | [
"BSD-3-Clause"
] | 1 | 2021-03-08T04:15:26.000Z | 2021-03-19T04:40:02.000Z | src/tests/cornell_box.h | shiinamiyuki/LuisaCompute | f8358f8ec138950a84f570c0ede24cc76fc159de | [
"BSD-3-Clause"
] | 4 | 2020-12-02T09:41:22.000Z | 2021-03-06T06:36:40.000Z | //
// Created by Mike Smith on 2021/7/27.
//
#pragma once
static const char *obj_string = R"(
# The original Cornell Box in OBJ format.
# Note that the real box is not a perfect cube, so
# the faces are imperfect in this data set.
#
# Created by Guedis Cardenas and Morgan McGuire at Williams College, 2011
# Released into the Public Domain.
#
# http://graphics.cs.williams.edu/data
# http://www.graphics.cornell.edu/online/box/data.html
#
mtllib CornellBox-Original.mtl
g floor
v -1.01 0.00 0.99
v 1.00 0.00 0.99
v 1.00 0.00 -1.04
v -0.99 0.00 -1.04
f -4 -3 -2 -1
g ceiling
v -1.02 1.99 0.99
v -1.02 1.99 -1.04
v 1.00 1.99 -1.04
v 1.00 1.99 0.99
f -4 -3 -2 -1
g backWall
v -0.99 0.00 -1.04
v 1.00 0.00 -1.04
v 1.00 1.99 -1.04
v -1.02 1.99 -1.04
f -4 -3 -2 -1
g rightWall
v 1.00 0.00 -1.04
v 1.00 0.00 0.99
v 1.00 1.99 0.99
v 1.00 1.99 -1.04
f -4 -3 -2 -1
g leftWall
v -1.01 0.00 0.99
v -0.99 0.00 -1.04
v -1.02 1.99 -1.04
v -1.02 1.99 0.99
f -4 -3 -2 -1
g shortBox
# Top Face
v 0.53 0.60 0.75
v 0.70 0.60 0.17
v 0.13 0.60 0.00
v -0.05 0.60 0.57
f -4 -3 -2 -1
# Left Face
v -0.05 0.00 0.57
v -0.05 0.60 0.57
v 0.13 0.60 0.00
v 0.13 0.00 0.00
f -4 -3 -2 -1
# Front Face
v 0.53 0.00 0.75
v 0.53 0.60 0.75
v -0.05 0.60 0.57
v -0.05 0.00 0.57
f -4 -3 -2 -1
# Right Face
v 0.70 0.00 0.17
v 0.70 0.60 0.17
v 0.53 0.60 0.75
v 0.53 0.00 0.75
f -4 -3 -2 -1
# Back Face
v 0.13 0.00 0.00
v 0.13 0.60 0.00
v 0.70 0.60 0.17
v 0.70 0.00 0.17
f -4 -3 -2 -1
# Bottom Face
v 0.53 0.00 0.75
v 0.70 0.00 0.17
v 0.13 0.00 0.00
v -0.05 0.00 0.57
f -12 -11 -10 -9
g tallBox
# Top Face
v -0.53 1.20 0.09
v 0.04 1.20 -0.09
v -0.14 1.20 -0.67
v -0.71 1.20 -0.49
f -4 -3 -2 -1
# Left Face
v -0.53 0.00 0.09
v -0.53 1.20 0.09
v -0.71 1.20 -0.49
v -0.71 0.00 -0.49
f -4 -3 -2 -1
# Back Face
v -0.71 0.00 -0.49
v -0.71 1.20 -0.49
v -0.14 1.20 -0.67
v -0.14 0.00 -0.67
f -4 -3 -2 -1
# Right Face
v -0.14 0.00 -0.67
v -0.14 1.20 -0.67
v 0.04 1.20 -0.09
v 0.04 0.00 -0.09
f -4 -3 -2 -1
# Front Face
v 0.04 0.00 -0.09
v 0.04 1.20 -0.09
v -0.53 1.20 0.09
v -0.53 0.00 0.09
f -4 -3 -2 -1
# Bottom Face
v -0.53 0.00 0.09
v 0.04 0.00 -0.09
v -0.14 0.00 -0.67
v -0.71 0.00 -0.49
f -8 -7 -6 -5
g light
v -0.24 1.98 0.16
v -0.24 1.98 -0.22
v 0.23 1.98 -0.22
v 0.23 1.98 0.16
f -4 -3 -2 -1)";
| 16.66 | 73 | 0.532213 |
c4e3d07d776db49308d954d04a4ab6c874d5feef | 8,647 | dart | Dart | lib/src/widget/switch.dart | digitalnomadacademy/neumorphic_null_safety | c8edf2c9c6cfa51138ba218a701389a7e8424109 | [
"Apache-2.0"
] | null | null | null | lib/src/widget/switch.dart | digitalnomadacademy/neumorphic_null_safety | c8edf2c9c6cfa51138ba218a701389a7e8424109 | [
"Apache-2.0"
] | null | null | null | lib/src/widget/switch.dart | digitalnomadacademy/neumorphic_null_safety | c8edf2c9c6cfa51138ba218a701389a7e8424109 | [
"Apache-2.0"
] | null | null | null | import 'package:flutter/widgets.dart';
import 'package:flutter_neumorphic/src/widget/animation/animated_scale.dart';
import '../../flutter_neumorphic.dart';
import '../neumorphic_box_shape.dart';
import '../theme/neumorphic_theme.dart';
import 'container.dart';
/// A style to customize the [NeumorphicSwitch]
///
/// you can define the track : [activeTrackColor], [inactiveTrackColor], [trackDepth]
///
/// you can define the thumb : [activeTrackColor], [inactiveTrackColor], [thumbDepth]
/// and [thumbShape] @see [NeumorphicShape]
///
class NeumorphicSwitchStyle {
final double? trackDepth;
final Color? activeTrackColor;
final Color? inactiveTrackColor;
final Color? activeThumbColor;
final Color? inactiveThumbColor;
final NeumorphicShape? thumbShape;
final double? thumbDepth;
final LightSource? lightSource;
final bool disableDepth;
final NeumorphicBorder thumbBorder;
final NeumorphicBorder trackBorder;
const NeumorphicSwitchStyle({
this.trackDepth,
this.thumbShape = NeumorphicShape.concave,
this.activeTrackColor,
this.inactiveTrackColor,
this.activeThumbColor,
this.inactiveThumbColor,
this.thumbDepth,
this.lightSource,
this.disableDepth = false,
this.thumbBorder = const NeumorphicBorder.none(),
this.trackBorder = const NeumorphicBorder.none(),
});
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is NeumorphicSwitchStyle &&
runtimeType == other.runtimeType &&
trackDepth == other.trackDepth &&
trackBorder == other.trackBorder &&
thumbBorder == other.thumbBorder &&
lightSource == other.lightSource &&
activeTrackColor == other.activeTrackColor &&
inactiveTrackColor == other.inactiveTrackColor &&
activeThumbColor == other.activeThumbColor &&
inactiveThumbColor == other.inactiveThumbColor &&
thumbShape == other.thumbShape &&
thumbDepth == other.thumbDepth &&
disableDepth == other.disableDepth;
@override
int get hashCode =>
trackDepth.hashCode ^
activeTrackColor.hashCode ^
trackBorder.hashCode ^
thumbBorder.hashCode ^
lightSource.hashCode ^
inactiveTrackColor.hashCode ^
activeThumbColor.hashCode ^
inactiveThumbColor.hashCode ^
thumbShape.hashCode ^
thumbDepth.hashCode ^
disableDepth.hashCode;
}
/// Used to toggle the on/off state of a single setting.
///
/// The switch itself does not maintain any state. Instead, when the state of the switch changes, the widget calls the onChanged callback.
/// Most widgets that use a switch will listen for the onChanged callback and rebuild the switch with a new value to update the visual appearance of the switch.
///
/// ```
/// bool _switch1Value = false;
/// bool _switch2Value = false;
///
/// Widget _buildSwitches() {
/// return Row(children: <Widget>[
///
/// NeumorphicSwitch(
/// value: _switch1Value,
/// style: NeumorphicSwitchStyle(
/// thumbShape: NeumorphicShape.concave,
/// ),
/// onChanged: (value) {
/// setState(() {
/// _switch1Value = value;
/// });
/// },
/// ),
///
/// NeumorphicSwitch(
/// value: _switch2Value,
/// style: NeumorphicSwitchStyle(
/// thumbShape: NeumorphicShape.flat,
/// ),
/// onChanged: (value) {
/// setState(() {
/// _switch2Value = value;
/// });
/// },
/// ),
///
/// ]);
/// }
/// ```
///
@immutable
class NeumorphicSwitch extends StatelessWidget {
static const MIN_EMBOSS_DEPTH = -1.0;
final bool value;
final ValueChanged<bool>? onChanged;
final NeumorphicSwitchStyle style;
final double height;
final Duration duration;
final Curve curve;
final bool isEnabled;
const NeumorphicSwitch({
this.style = const NeumorphicSwitchStyle(),
Key? key,
this.curve = Neumorphic.DEFAULT_CURVE,
this.duration = const Duration(milliseconds: 200),
this.value = false,
this.onChanged,
this.height = 40,
this.isEnabled = true,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final NeumorphicThemeData theme = NeumorphicTheme.currentTheme(context);
return SizedBox(
height: this.height,
child: AspectRatio(
aspectRatio: 2 / 1,
child: GestureDetector(
onTap: () {
// animation breaking prevention
if (!this.isEnabled) {
return;
}
if (this.onChanged != null) {
this.onChanged!(!this.value);
}
},
child: Neumorphic(
drawSurfaceAboveChild: false,
style: NeumorphicStyle(
boxShape: NeumorphicBoxShape.stadium(),
lightSource: this.style.lightSource ?? theme.lightSource,
border: this.style.trackBorder,
disableDepth: this.style.disableDepth,
depth: _getTrackDepth(theme.depth),
shape: NeumorphicShape.flat,
color: _getTrackColor(theme, this.isEnabled),
),
child: CustomAnimatedScale(
scale: this.isEnabled ? 1 : 0,
alignment: this.value ? Alignment(0.5, 0) : Alignment(-0.5, 0),
child: AnimatedThumb(
curve: this.curve,
disableDepth: this.style.disableDepth,
depth: this._thumbDepth,
duration: this.duration,
alignment: this._alignment,
shape: _getThumbShape,
lightSource: this.style.lightSource ?? theme.lightSource,
border: style.thumbBorder,
thumbColor: _getThumbColor(theme),
),
),
),
),
),
);
}
Alignment get _alignment {
if (this.value) {
return Alignment.centerRight;
} else {
return Alignment.centerLeft;
}
}
double get _thumbDepth {
if (!this.isEnabled) {
return 0;
} else
return this.style.thumbDepth ?? neumorphicDefaultTheme.depth;
}
NeumorphicShape get _getThumbShape {
return this.style.thumbShape ?? NeumorphicShape.flat;
}
double? _getTrackDepth(double? themeDepth) {
if (themeDepth == null) return themeDepth;
//force negative to have emboss
final double depth = -1 * (this.style.trackDepth ?? themeDepth).abs();
return depth.clamp(Neumorphic.MIN_DEPTH, NeumorphicSwitch.MIN_EMBOSS_DEPTH);
}
Color _getTrackColor(NeumorphicThemeData theme, bool enabled) {
if (!enabled) {
return this.style.inactiveTrackColor ?? theme.baseColor;
}
return this.value == true
? this.style.activeTrackColor ?? theme.accentColor
: this.style.inactiveTrackColor ?? theme.baseColor;
}
Color _getThumbColor(NeumorphicThemeData theme) {
Color? color = this.value == true
? this.style.activeThumbColor
: this.style.inactiveThumbColor;
return color ?? theme.baseColor;
}
}
class AnimatedThumb extends StatelessWidget {
final Color? thumbColor;
final Alignment alignment;
final Duration duration;
final NeumorphicShape shape;
final double? depth;
final Curve curve;
final bool disableDepth;
final NeumorphicBorder border;
final LightSource lightSource;
AnimatedThumb({
Key? key,
this.thumbColor,
required this.alignment,
required this.duration,
required this.shape,
this.depth,
this.curve = Curves.linear,
this.border = const NeumorphicBorder.none(),
this.lightSource = LightSource.topLeft,
this.disableDepth = false,
}) : super(key: key);
@override
Widget build(BuildContext context) {
// This Container is actually the inner track containing the thumb
return AnimatedAlign(
curve: this.curve,
alignment: this.alignment,
duration: this.duration,
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Neumorphic(
style: NeumorphicStyle(
boxShape: NeumorphicBoxShape.circle(),
disableDepth: this.disableDepth,
shape: shape,
depth: this.depth,
color: thumbColor,
border: this.border,
lightSource: this.lightSource,
),
child: AspectRatio(
aspectRatio: 1,
child: FractionallySizedBox(
heightFactor: 1,
child: Container(),
//width: THUMB_WIDTH,
),
),
),
),
);
}
}
| 30.024306 | 160 | 0.626229 |
c6b93c77cca2e59db6740fac50f93884f8354fd1 | 1,757 | py | Python | tools/ipgeo/ipgeo.py | onurrozkaan/interrogator | 799613bdb39cfdf00ad19381a8121be2a7291c2b | [
"MIT"
] | 5 | 2019-03-09T09:45:58.000Z | 2021-06-27T10:18:24.000Z | tools/ipgeo/ipgeo.py | ozkanonur/interrogator | 799613bdb39cfdf00ad19381a8121be2a7291c2b | [
"MIT"
] | null | null | null | tools/ipgeo/ipgeo.py | ozkanonur/interrogator | 799613bdb39cfdf00ad19381a8121be2a7291c2b | [
"MIT"
] | null | null | null |
import urllib.request
import sys
import json
from assets.styling.colors import *
def getOutput():
print(purple + "Enter the Target IP:")
sys.stdout.write(green + "> ")
ip_input = input()
with urllib.request.urlopen("http://ip-api.com/json/" + ip_input) as url:
def is_input_ip(checker_value):
data = checker_value.split('.')
if len(data) != 4:
return False
for x in data:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
if is_input_ip(ip_input) == True:
data = url.read().decode()
output = data.strip('"').split(",")
print("\r")
for value in output:
print(red + "--> " + value.replace('"', "").replace("}", "").replace("{", "").replace("as:", yellow + "AS: "+ green).replace("city:", yellow + "CITY: "+ green).replace("country:", yellow + "COUNTRY: " + green).replace("isp:", yellow + "ISP: " +green ).replace("lat:", yellow + "LAT: " +green ).replace("countryCode:", yellow + "COUNTRY CODE: " +green ).replace(
"lon:", yellow + "LON: " +green ).replace("org:", yellow + "ORG: " +green ).replace("query:", yellow + "QUERY: " +green ).replace("region:", yellow + "REGION: " +green ).replace("regionName:", yellow + "REGION NAME: " +green ).replace("status:", yellow + "STATUS: " +green ).replace("timezone:", yellow + "TIMEZONE: " +green ).replace("zip:", yellow + "ZIP: " +green ))
else:
print("\r")
print(red + "Value looks like not an Ip Address, please enter a correct Ip Address.") | 45.051282 | 389 | 0.525327 |
b15cd49091c953b7367b285547445d5531de6d14 | 979 | swift | Swift | AeroEditor/ChooseViewController.swift | nick-merrill/AeroEditor | 93dc6fdd560b4ca0c850f38231c009484228eb0f | [
"MIT"
] | 1 | 2020-09-30T06:49:27.000Z | 2020-09-30T06:49:27.000Z | AeroEditor/ChooseViewController.swift | cloudrave/AeroEditor | 93dc6fdd560b4ca0c850f38231c009484228eb0f | [
"MIT"
] | null | null | null | AeroEditor/ChooseViewController.swift | cloudrave/AeroEditor | 93dc6fdd560b4ca0c850f38231c009484228eb0f | [
"MIT"
] | 1 | 2021-02-06T21:40:05.000Z | 2021-02-06T21:40:05.000Z | //
// ChooseViewController.swift
// AeroEditor
//
// Created by Nick Merrill on 8/10/15.
// Copyright ยฉ 2015 Nick Merrill. All rights reserved.
//
import Cocoa
class ChooseViewController: SubMainViewController {
lazy var chooseSplitVC: ChooseSplitViewController = self.storyboard!.instantiateController(withIdentifier: "ChooseSplitViewController") as! ChooseSplitViewController
override func viewDidLoad() {
super.viewDidLoad()
self.addChildViewController(chooseSplitVC)
self.view.addSubview(chooseSplitVC.view)
NotificationCenter.default.addObserver(self, selector: #selector(NSWindowDelegate.windowDidResize(_:)), name: NSNotification.Name.NSWindowDidResize, object: self.view.window)
self.layoutSubviews()
}
func windowDidResize(_ notification: Notification) {
self.layoutSubviews()
}
func layoutSubviews() {
chooseSplitVC.view.frame = self.view.bounds
}
}
| 30.59375 | 182 | 0.715015 |
b012ad0c971c267943ac3d2a61abc9a5cd4191c0 | 1,264 | py | Python | tests/test_headers.py | gezpage/chocs | cf64a792989e3f23dc7f400045898761511a229a | [
"MIT"
] | null | null | null | tests/test_headers.py | gezpage/chocs | cf64a792989e3f23dc7f400045898761511a229a | [
"MIT"
] | null | null | null | tests/test_headers.py | gezpage/chocs | cf64a792989e3f23dc7f400045898761511a229a | [
"MIT"
] | null | null | null | import pytest
from chocs.headers import Headers
def test_can_instantiate():
headers = Headers()
assert isinstance(headers, Headers)
def test_normalize_wsgi_headers():
headers = Headers({"HTTP_USER_AGENT": "Test Agent", "HTTP_ACCEPT": "plain/text"})
assert headers["User-Agent"] == "Test Agent"
assert headers["HTTP_USER_AGENT"] == "Test Agent"
assert headers["USER_AGENT"] == "Test Agent"
assert headers["USER-AGENT"] == "Test Agent"
assert headers.get("User-Agent") == "Test Agent"
def test_add_header():
headers = Headers()
headers.set("USER_AGENT", "Test Agent")
assert headers["HTTP_USER_AGENT"] == "Test Agent"
assert headers["USER_AGENT"] == "Test Agent"
assert headers["USER-AGENT"] == "Test Agent"
assert headers.get("User-Agent") == "Test Agent"
def test_non_unique_headers():
headers = Headers()
headers.set("Set-Cookie", "123")
headers.set("Set-Cookie", "456")
headers.set("Set-Cookie", "789")
assert headers["Set-Cookie"] == [
"123",
"456",
"789",
]
# test items view
assert [(key, value) for key, value in headers.items()] == [
("set-cookie", "123"),
("set-cookie", "456"),
("set-cookie", "789"),
]
| 26.333333 | 85 | 0.61788 |
a38f8e021babfcef47777307e514c3669335e83e | 1,037 | java | Java | src/main/java/it/smartcommunitylab/aac/repository/StringOrArraySerializer.java | civts/AAC | 7e137c8ca2a6826168d02efa95c32b298dce6688 | [
"Apache-2.0"
] | 2 | 2020-01-22T18:19:09.000Z | 2020-06-06T16:12:19.000Z | src/main/java/it/smartcommunitylab/aac/repository/StringOrArraySerializer.java | civts/AAC | 7e137c8ca2a6826168d02efa95c32b298dce6688 | [
"Apache-2.0"
] | 24 | 2020-02-17T13:54:42.000Z | 2022-03-31T15:00:12.000Z | src/main/java/it/smartcommunitylab/aac/repository/StringOrArraySerializer.java | civts/AAC | 7e137c8ca2a6826168d02efa95c32b298dce6688 | [
"Apache-2.0"
] | 1 | 2019-07-08T08:27:09.000Z | 2019-07-08T08:27:09.000Z | package it.smartcommunitylab.aac.repository;
import java.io.IOException;
import java.util.Set;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import it.smartcommunitylab.aac.SystemKeys;
public class StringOrArraySerializer extends StdSerializer<Set<String>> {
private static final long serialVersionUID = SystemKeys.AAC_COMMON_SERIAL_VERSION;
public StringOrArraySerializer() {
super(Set.class, false);
}
@Override
public void serialize(Set<String> value, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (value != null) {
if (value.size() == 1) {
gen.writeString(value.iterator().next());
} else {
gen.writeStartArray();
for (String s : value) {
gen.writeString(s);
}
gen.writeEndArray();
}
}
}
}
| 26.589744 | 113 | 0.643202 |
15d10270ff4b7e2f37b308103582beca8e0adfef | 5,040 | dart | Dart | lib/keystore/keystore.dart | cochainio/coefi | bfb3af0fa083c10540476e1b1fca63b5fbd4e0ca | [
"Apache-2.0"
] | null | null | null | lib/keystore/keystore.dart | cochainio/coefi | bfb3af0fa083c10540476e1b1fca63b5fbd4e0ca | [
"Apache-2.0"
] | null | null | null | lib/keystore/keystore.dart | cochainio/coefi | bfb3af0fa083c10540476e1b1fca63b5fbd4e0ca | [
"Apache-2.0"
] | null | null | null | import 'dart:convert';
import 'dart:typed_data';
import 'package:bip32/bip32.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:uuid/uuid.dart';
import 'package:uuid/uuid_util.dart';
import 'crypto.dart';
import 'mnemonic.dart';
export 'bip44.dart';
export 'crypto.dart';
export 'keystore.convert.dart';
export 'mnemonic.dart';
part 'keystore.g.dart';
enum KeystoreType {
BTC, // ignore: constant_identifier_names
BTCMnemonic, // ignore: constant_identifier_names
ETH, // ignore: constant_identifier_names
ETHMnemonic, // ignore: constant_identifier_names
}
@JsonSerializable()
class KeystoreMeta {
KeystoreMeta();
factory KeystoreMeta.fromJson(Map<String, dynamic> json) => _$KeystoreMetaFromJson(json);
Map<String, dynamic> toJson() => _$KeystoreMetaToJson(this);
}
@JsonSerializable(explicitToJson: true)
class Keystore {
String id;
int version;
late Crypto crypto;
@JsonKey(includeIfNull: false)
KeystoreMeta meta;
static const defaultVersion = 3;
Keystore({String? id, this.version = defaultVersion, Crypto? crypto, KeystoreMeta? meta})
: id = id ?? const Uuid().v4(options: {'grng': UuidUtil.cryptoRNG}),
meta = meta ?? KeystoreMeta() {
if (crypto != null) {
this.crypto = crypto;
}
preValidate();
}
factory Keystore.from(String password, Uint8List secret, {String? id, KeystoreMeta? meta, bool clearCache = true}) {
final k = Keystore(id: id, meta: meta);
k.crypto = Crypto.from(password, secret, cacheDerivedKey: !clearCache);
return k;
}
void cacheDerivedKey(String password) {
crypto.cacheDerivedKey(password);
}
void clearCache() {
crypto.clearCache();
}
void preValidate() {
if (version != defaultVersion) {
throw ArgumentError.value(version, 'version');
}
}
bool validate(String password, {bool willThrow = false, bool cacheDerivedKey = false}) {
return crypto.validate(password, willThrow: willThrow, cacheDerivedKey: cacheDerivedKey);
}
void changePassword(String password, String newPassword, {bool cacheDerivedKey = false}) {
validate(password, willThrow: true, cacheDerivedKey: true);
final secret = crypto.secret(password);
crypto = Crypto.from(newPassword, secret, cacheDerivedKey: cacheDerivedKey);
}
Uint8List secret(String password) {
return crypto.secret(password);
}
String export() {
return jsonEncode(this);
}
factory Keystore.fromJson(Map<String, dynamic> json) => _$KeystoreFromJson(json);
Map<String, dynamic> toJson() => _$KeystoreToJson(this);
}
@JsonSerializable()
class MnemonicKeystore extends Keystore {
late EncryptedMessage encryptedMnemonic;
late EncryptedMessage encryptedExtendedPrivateKey;
String? hdPath;
MnemonicKeystore();
/// If [hdPath] is not given, the master key seeded from [mnemonic] is persisted into [crypto]. Otherwise,
/// the derived key corresponding to [hdPath] is persisted.
/// [isMainnet] = false is only useful for BTC-like testnet.
MnemonicKeystore.from(String password,
{String? mnemonic,
String? language,
this.hdPath,
bool isMainnet = true,
String? id,
KeystoreMeta? meta,
bool clearCache = true})
: super(id: id, meta: meta) {
// Generate random mnemonic
mnemonic ??= Mnemonic.generateMnemonic(language);
final master = BIP32.fromSeed(Mnemonic.mnemonicToSeed(mnemonic), isMainnet ? BITCOIN : TESTNET);
final extendedPrivateKey = hdPath == null ? master : master.derivePath(hdPath!);
crypto = Crypto.from(password, extendedPrivateKey.privateKey!, cacheDerivedKey: true);
encryptedMnemonic = crypto.encryptMessage(password, utf8.encode(mnemonic) as Uint8List);
encryptedExtendedPrivateKey =
crypto.encryptMessage(password, utf8.encode(extendedPrivateKey.toBase58()) as Uint8List);
if (clearCache) this.clearCache();
}
@override
void changePassword(String password, String newPassword, {bool cacheDerivedKey = false}) {
this.cacheDerivedKey(password);
final mnemonic = this.mnemonic(password);
final extendedPrivateKey = base58(password);
super.changePassword(password, newPassword, cacheDerivedKey: true);
encryptedMnemonic = crypto.encryptMessage(newPassword, utf8.encode(mnemonic) as Uint8List);
encryptedExtendedPrivateKey = crypto.encryptMessage(newPassword, utf8.encode(extendedPrivateKey) as Uint8List);
if (!cacheDerivedKey) clearCache();
}
String mnemonic(String password) {
return utf8.decode(crypto.decryptMessage(password, encryptedMnemonic));
}
BIP32 extendedPrivateKey(String password) {
return BIP32.fromBase58(base58(password));
}
String base58(String password) {
return utf8.decode(crypto.decryptMessage(password, encryptedExtendedPrivateKey));
}
factory MnemonicKeystore.fromJson(Map<String, dynamic> json) {
final k = _$MnemonicKeystoreFromJson(json);
k.preValidate();
return k;
}
@override
Map<String, dynamic> toJson() => _$MnemonicKeystoreToJson(this);
}
| 31.304348 | 118 | 0.723016 |
c8a1040c7568ca83baa0835c0f2d9072714ac63f | 847 | css | CSS | AV/Blockchain/BlockExample.css | dwgillies/OpenDSA | e012925896070a86bd7c3a4cbb75fa5682d9b9e2 | [
"MIT"
] | 200 | 2015-02-08T05:27:52.000Z | 2022-03-23T02:44:38.000Z | AV/Blockchain/BlockExample.css | dwgillies/OpenDSA | e012925896070a86bd7c3a4cbb75fa5682d9b9e2 | [
"MIT"
] | 119 | 2015-03-22T22:38:21.000Z | 2022-03-15T04:38:52.000Z | AV/Blockchain/BlockExample.css | dwgillies/OpenDSA | e012925896070a86bd7c3a4cbb75fa5682d9b9e2 | [
"MIT"
] | 105 | 2015-01-03T08:55:00.000Z | 2022-03-19T00:51:45.000Z | #outer {
width: 100%;
}
#container {
width: 269px;
height: 225px;
position: relative;
display: table;
}
.instructions {
border: 0;
padding: 0;
margin: 0;
text-align: center;
}
.bsize {
position: absolute;
left: 10px;
top: 42px;
}
#blockNum {
position: absolute;
left: 175px;
top: 55px;
width: 50px;
}
.tsize {
position: absolute;
left: 10px;
top: 70px;
}
#tablesize {
position: absolute;
left: 10px;
top: 110px;
right: 10px;
height: 50px;
width: 250px;
resize: none;
}
.outputLabel {
position: absolute;
top: 160px;
left: 10px;
display: inline-block;
}
.output {
position: absolute;
left: 60px;
top: 174px;
text-align:center;
font-size: 10pt;
font-family: Courier;
display: inline-block;
}
| 13.234375 | 26 | 0.569067 |
3af363a999350abc3e9e0da9e71b0a46f4d26edf | 87,039 | swift | Swift | libPhoneNumber/PhoneNumberUtil.swift | sereivoanyong/libPhoneNumber | 62966ef401a19f92a429072ad4887a606bb8c585 | [
"MIT"
] | null | null | null | libPhoneNumber/PhoneNumberUtil.swift | sereivoanyong/libPhoneNumber | 62966ef401a19f92a429072ad4887a606bb8c585 | [
"MIT"
] | null | null | null | libPhoneNumber/PhoneNumberUtil.swift | sereivoanyong/libPhoneNumber | 62966ef401a19f92a429072ad4887a606bb8c585 | [
"MIT"
] | null | null | null | //
// PhoneNumberUtil.swift
//
// Created by Sereivoan Yong on 12/3/20.
//
import Foundation
/// Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
/// ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
private let kAsciiDigitMappings: [Character: Character] = ["0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6", "7": "7", "8": "8", "9": "9"]
final public class PhoneNumberUtil {
/// Flags to use when compiling regular expressions for phone numbers.
static let regexOptions: NSRegularExpression.Options = [.caseInsensitive]
/// The minimum and maximum length of the national significant number.
private static let minimumLengthForNSN: Int = 2
/// The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
static let maximumLengthForNSN: Int = 17
/// The maximum length of the country calling code.
static let maximumLengthForCountryCode: Int32 = 3
// We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
// input from overflowing the regular-expression engine.
private static let maximumInputStringLength: Int = 250
/// Region-code for the unknown region.
private static let unknownRegionCode: String = "ZZ"
private static let nanpaCountryCode: Int32 = 1
/// The prefix that needs to be inserted in front of a Colombian landline number when dialed from
/// a mobile phone in Colombia.
private static let colombiaMobileToFixedLinePrefix: String = "3"
/// Map of country calling codes that use a mobile token before the area code. One example of when
/// this is relevant is when determining the length of the national destination code, which should
/// be the length of the area code plus the length of the mobile token.
private static let mobileTokenMappings: [Int32: String] = [:]
/// Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES
/// below) which are not based on *area codes*. For example, in China mobile numbers start with a
/// carrier indicator, and beyond that are geographically assigned: this carrier indicator is not
/// considered to be an area code.
private static let geoMobileCountryCodesWithoutMobileAreaCodes: Set<Int32> = {
var geoMobileCountryCodesWithoutMobileAreaCodes = Set<Int32>()
geoMobileCountryCodesWithoutMobileAreaCodes.insert(86) // China
return geoMobileCountryCodesWithoutMobileAreaCodes
}()
/// Set of country calling codes that have geographically assigned mobile numbers. This may not be
/// complete; we add calling codes case by case, as we find geographical mobile numbers or hear
/// from user reports. Note that countries like the US, where we can't distinguish between
/// fixed-line or mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE to be
/// a possibly geographically-related type anyway (like FIXED_LINE).
private static let geoMobileCountryCodes: Set<Int32> = {
var geoMobileCountryCodes = Set<Int32>()
geoMobileCountryCodes.insert(52) // Mexico
geoMobileCountryCodes.insert(54) // Argentina
geoMobileCountryCodes.insert(55) // Brazil
geoMobileCountryCodes.insert(62) // Indonesia: some prefixes only (fixed CMDA wireless)
geoMobileCountryCodes.formUnion(geoMobileCountryCodesWithoutMobileAreaCodes)
return geoMobileCountryCodes
}()
// 99
/// The PLUS_SIGN signifies the international prefix.
static let plusSign: Character = "+"
private static let starSign: Character = "*"
private static let rfc3966ExtnPrefix = ";ext="
// 104
private static let rfc3966Prefix = "tel:"
private static let rfc3966PhoneContext = ";phone-context="
private static let rfc3966ISDNSubaddress = ";isub="
/// A map that contains characters that are essential when dialling. That means any of the
/// characters in this map must not be removed from a number when dialling, otherwise the call
/// will not reach the intended destination.
private static let diallableCharMappings: [Character: Character] = kAsciiDigitMappings.merging([plusSign: plusSign, "*": "*", "#": "#"]) { _, _ in fatalError("duplicated characters") }
// Only upper-case variants of alpha characters are stored.
private static let alphaMappings: [Character: Character] = {
var alphaMappings = [Character: Character](minimumCapacity: 40)
alphaMappings["A"] = "2"
alphaMappings["B"] = "2"
alphaMappings["C"] = "2"
alphaMappings["D"] = "3"
alphaMappings["E"] = "3"
alphaMappings["F"] = "3"
alphaMappings["G"] = "4"
alphaMappings["H"] = "4"
alphaMappings["I"] = "4"
alphaMappings["J"] = "5"
alphaMappings["K"] = "5"
alphaMappings["L"] = "5"
alphaMappings["M"] = "6"
alphaMappings["N"] = "6"
alphaMappings["O"] = "6"
alphaMappings["P"] = "7"
alphaMappings["Q"] = "7"
alphaMappings["R"] = "7"
alphaMappings["S"] = "7"
alphaMappings["T"] = "8"
alphaMappings["U"] = "8"
alphaMappings["V"] = "8"
alphaMappings["W"] = "9"
alphaMappings["X"] = "9"
alphaMappings["Y"] = "9"
alphaMappings["Z"] = "9"
return alphaMappings
}()
// 117
/// For performance reasons, amalgamate both into one map.
private static let alphaPhoneMappings: [Character: Character] = alphaMappings.merging(kAsciiDigitMappings) { _, _ in fatalError("duplicated characters") }
// 121
/// Separate map of all symbols that we wish to retain when formatting alpha numbers. This
/// includes digits, ASCII letters and number grouping symbols such as "-" and " ".
private static let allPlusNumberGroupingSymbols: [Character: Character] = alphaMappings.keys
.reduce(into: [:]) { result, character in
result[Character(character.lowercased())] = character
result[character] = character
}
.merging(kAsciiDigitMappings) { _, _ in fatalError("character mismatch") }
.merging([
"-": "-",
"\u{FF0D}": "-",
"\u{2010}": "-",
"\u{2011}": "-",
"\u{2012}": "-",
"\u{2013}": "-",
"\u{2014}": "-",
"\u{2015}": "-",
"\u{2212}": "-",
"/": "/",
"\u{FF0F}": "/",
" ": " ",
"\u{3000}": " ",
"\u{2060}": " ",
".": ".",
"\u{FF0E}": "."
]) { _, _ in fatalError("character mismatch") }
/// 229
/// Pattern that makes it easy to distinguish whether a region has a single international dialing
/// prefix or not. If a region has a single international prefix (e.g. 011 in USA), it will be
/// represented as a string that contains a sequence of ASCII digits, and possibly a tilde, which
/// signals waiting for the tone. If there are multiple available international prefixes in a
/// region, they will be represented as a regex string that always contains one or more characters
/// that are not ASCII digits or a tilde.
private static let singleInternationalPrefixPattern: NSRegularExpression = try! NSRegularExpression(pattern: "[\\d]+(?:[~\u{2053}\u{223C}\u{FF5E}][\\d]+)?", options: [])
// 238
/// Regular expression of acceptable punctuation found in phone numbers, used to find numbers in
/// text and to decide what is a viable phone number. This excludes diallable characters.
/// This consists of dash characters, white space characters, full stops, slashes,
/// square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
/// placeholder for carrier information in some phone numbers. Full-width variants are also
/// present.
static let validPunctuation: String = "-x\u{2010}-\u{2015}\u{2212}\u{30FC}\u{FF0D}-\u{FF0F}\u{00A0}\u{00AD}\u{200B}\u{2060}\u{3000}()\u{FF08}\u{FF09}\u{FF3B}\u{FF3D}.\\[\\]/~\u{2053}\u{223C}\u{FF5E}"
// 241
private static let digits: String = "\\p{Nd}"
/// We accept alpha characters in phone numbers, ASCII only, upper and lower case.
private static let validAlpha: String = String(alphaMappings.keys).replacingOccurrences(of: "[, \\[\\]]", with: "") + String(alphaMappings.keys).lowercased().replacingOccurrences(of: "[, \\[\\]]", with: "")
static let plusChars: String = "+\u{FF0B}"
static let plusCharsPattern: NSRegularExpression = try! NSRegularExpression(pattern: "[\(plusChars)]+", options: [])
private static let separatorPattern: NSRegularExpression = try! NSRegularExpression(pattern: "[\(validPunctuation)]+", options: [])
private static let capturingDigitsPattern: NSRegularExpression = try! NSRegularExpression(pattern: "(\(digits))", options: [])
// 258
/// Regular expression of acceptable characters that may start a phone number for the purposes of
/// parsing. This allows us to strip away meaningless prefixes to phone numbers that may be
/// mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This
/// does not contain alpha characters, although they may be used later in the number. It also does
/// not include other punctuation, as this will be stripped later during parsing and is of no
/// information value when parsing a number.
private static let validStartChar: String = "[\(plusChars)\(digits)]"
private static let validStartCharPattern: NSRegularExpression = try! NSRegularExpression(pattern: validStartChar, options: [])
// 266
/// Regular expression of characters typically used to start a second phone number for the purposes
/// of parsing. This allows us to strip off parts of the number that are actually the start of
/// another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this
/// actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
/// extension so that the first number is parsed correctly.
private static let secondNumberStart: String = "[\\\\/] *x"
static let secondNumberStartPattern: NSRegularExpression = try! NSRegularExpression(pattern: secondNumberStart, options: [])
// 272
/// Regular expression of trailing characters that we want to remove. We remove all characters that
/// are not alpha or numerical characters. The hash character is retained here, as it may signify
/// the previous block was an extension.
private static let unwantedEndChars: String = "[[\\P{N}&&\\P{L}]&&[^#]]+$"
static let unwantedEndCharsPattern: NSRegularExpression = try! NSRegularExpression(pattern: unwantedEndChars, options: [])
/// 277
/// We use this pattern to check if the phone number has at least three letters in it - if so, then
/// we treat it as a number where some phone-number digits are represented by letters.
private static let validAlphaPhonePattern: NSRegularExpression = try! NSRegularExpression(pattern: "(?:.*?[A-Za-z]){3}.*", options: [])
// 295
/// Regular expression of viable phone numbers. This is location independent. Checks we have at
/// least three leading digits, and only valid punctuation, alpha characters and
/// digits in the phone number. Does not include extension data.
/// The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
/// carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
/// the start.
/// Corresponds to the following:
/// [digits]{minLengthNsn}|
/// plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
///
/// The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
/// as "15" etc, but only if there is no punctuation in them. The second expression restricts the
/// number of digits to three or more, but then allows them to be in international form, and to
/// have alpha-characters and punctuation.
///
/// Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
private static let validPhoneNumber: String = "\(digits){\(minimumLengthForNSN)}|[\(plusChars)]*+(?:[\(validPunctuation)\(starSign)]*\(digits)){3,}[\(validPunctuation)\(starSign)\(validAlpha)\(digits)]*"
// 309
/// Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
/// case-insensitive regexp match. Wide character versions are also provided after each ASCII
/// version.
private static let extnPatternsForParsing: String = extnPattern(forParsing: true)
// 310
static let extnPatternsForMatching: String = extnPattern(forParsing: false)
// 316
/// Helper method for constructing regular expressions for parsing. Creates an expression that
/// captures up to maxLength digits.
private static func extnDigits(maximumLength: Int) -> String {
return "(\(digits){1,\(maximumLength)})"
}
/// Helper initialiser method to create the regular-expression pattern to match extensions.
/// Note that there are currently six capturing groups for the extension itself. If this number is
/// changed, MaybeStripExtension needs to be updated.
private static func extnPattern(forParsing: Bool) -> String {
// We cap the maximum length of an extension based on the ambiguity of the way the extension is
// prefixed. As per ITU, the officially allowed length for extensions is actually 40, but we
// don't support this since we haven't seen real examples and this introduces many false
// interpretations as the extension labels are not standardized.
let extLimitAfterExplicitLabel = 20
let extLimitAfterLikelyLabel = 15
let extLimitAfterAmbiguousChar = 9
let extLimitWhenNotSure = 6
let possibleSeparatorsBetweenNumberAndExtLabel = "[ \u{00A0}\\t,]*"
// Optional full stop (.) or colon, followed by zero or more spaces/tabs/commas.
let possibleCharsAfterExtLabel = "[:\\.\u{FF0E}]?[ \u{00A0}\\t,-]*"
let optionalExtnSuffix = "#?"
// Here the extension is called out in more explicit way, i.e mentioning it obvious patterns
// like "ext.". Canonical-equivalence doesn't seem to be an option with Android java, so we
// allow two options for representing the accented o - the character itself, and one in the
// unicode decomposed form with the combining acute accent.
let explicitExtLabels = "(?:e?xt(?:ensi(?:o\u{0301}?|\u{00F3}))?n?|\u{FF45}?\u{FF58}\u{FF54}\u{FF4E}?|\u{0434}\u{043E}\u{0431}|anexo)"
// One-character symbols that can be used to indicate an extension, and less commonly used
// or more ambiguous extension labels.
let ambiguousExtLabels = "(?:[x\u{FF58}#\u{FF03}~\u{FF5E}]|int|\u{FF49}\u{FF4E}\u{FF54})"
// When extension is not separated clearly.
let ambiguousSeparator = "[- ]+"
let rfcExtn = rfc3966ExtnPrefix + extnDigits(maximumLength: extLimitAfterExplicitLabel)
let explicitExtn = possibleSeparatorsBetweenNumberAndExtLabel + explicitExtLabels
+ possibleCharsAfterExtLabel + extnDigits(maximumLength: extLimitAfterExplicitLabel)
+ optionalExtnSuffix
let ambiguousExtn = possibleSeparatorsBetweenNumberAndExtLabel + ambiguousExtLabels
+ possibleCharsAfterExtLabel + extnDigits(maximumLength: extLimitAfterAmbiguousChar)
+ optionalExtnSuffix
let americanStyleExtnWithSuffix = "\(ambiguousSeparator)\(extnDigits(maximumLength: extLimitWhenNotSure))#"
// The first regular expression covers RFC 3966 format, where the extension is added using
// ";ext=". The second more generic where extension is mentioned with explicit labels like
// "ext:". In both the above cases we allow more numbers in extension than any other extension
// labels. The third one captures when single character extension labels or less commonly used
// labels are used. In such cases we capture fewer extension digits in order to reduce the
// chance of falsely interpreting two numbers beside each other as a number + extension. The
// fourth one covers the special case of American numbers where the extension is written with a
// hash at the end, such as "- 503#".
let extensionPattern = "\(rfcExtn)|\(explicitExtn)|\(ambiguousExtn)|\(americanStyleExtnWithSuffix)"
// Additional pattern that is supported when parsing extensions, not when matching.
if forParsing {
// This is same as possibleSeparatorsBetweenNumberAndExtLabel, but not matching comma as
// extension label may have it.
let possibleSeparatorsNumberExtLabelNoComma = "[ \u{00A0}\\t]*"
// ",," is commonly used for auto dialling the extension when connected. First comma is matched
// through possibleSeparatorsBetweenNumberAndExtLabel, so we do not repeat it here. Semi-colon
// works in Iphone and Android also to pop up a button with the extension number following.
let autoDiallingAndExtLabelsFound = "(?:,{2}|;)"
let autoDiallingExtn = possibleSeparatorsNumberExtLabelNoComma
+ autoDiallingAndExtLabelsFound + possibleCharsAfterExtLabel
+ extnDigits(maximumLength: extLimitAfterLikelyLabel) + optionalExtnSuffix
let onlyCommasExtn = "\(possibleSeparatorsNumberExtLabelNoComma)(?:,)+\(possibleCharsAfterExtLabel)\(extnDigits(maximumLength: extLimitAfterAmbiguousChar))\(optionalExtnSuffix)"
// Here the first pattern is exclusively for extension autodialling formats which are used
// when dialling and in this case we accept longer extensions. However, the second pattern
// is more liberal on the number of commas that acts as extension labels, so we have a strict
// cap on the number of digits in such extensions.
return "\(extensionPattern)|\(autoDiallingExtn)|\(onlyCommasExtn)"
}
return extensionPattern
}
// 402
/// Regexp of all known extension prefixes used by different regions followed by 1 or more valid
/// digits, for use when parsing.
private static let extnPattern = try! NSRegularExpression(pattern: "(?:\(extnPatternsForParsing))$", options: regexOptions)
// 407
/// We append optionally the extension pattern to the end here, as a valid phone number may
/// have an extension prefix appended, followed by 1 or more digits.
private static let validPhoneNumberPattern: NSRegularExpression = try! NSRegularExpression(pattern: "\(validPhoneNumber)(?:\(extnPatternsForParsing))?", options: regexOptions)
// 410
static let nonDigitsPattern: NSRegularExpression = try! NSRegularExpression(pattern: "(\\D+)", options: [])
/// The `firstGroupPattern` was originally set to $1 but there are some countries for which the
/// first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
/// correctly. Therefore, we use \d, so that the first group actually used in the pattern will be
/// matched.
private static let firstGroupPattern: NSRegularExpression = try! NSRegularExpression(pattern: "(\\$\\d)", options: [])
/// Constants used in the formatting rules to represent the national prefix, first group and
/// carrier code respectively.
private static let npString: String = "$NP"
private static let fgString: String = "$FG"
private static let ccString: String = "$CC"
// 426
/// A pattern that is used to determine if the national prefix formatting rule has the first group
/// only, i.e., does not start with the national prefix. Note that the pattern explicitly allows
/// for unbalanced parentheses.
private static let firstGroupOnlyPrefixPattern: NSRegularExpression = try! NSRegularExpression(pattern: "\\(?\\$1\\)?", options: [])
// 430
public static let regionCodeForNonGeoEntity: String = "001"
// 648 - Aka metadataSource
/// A source of metadata for different regions.
let metadataManager: MetadataManager
// 654
/// A mapping from a country calling code to the region codes which denote the region represented
/// by that country calling code. In the case of multiple regions sharing a calling code, such as
/// the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
/// first.
private let regionCodesByCountryCode: [Int32: [String]]
// 662
/// The set of regions that share country calling code 1.
/// There are roughly 26 regions.
/// We set the initial capacity of the HashSet to 35 to offer a load factor of roughly 0.75.
private let nanpaRegionCodes: Set<String>
// 667
/// A cache for frequently used region-specific regular expressions.
let regexCache: RegexCache
// 672
/// The set of region codes the library supports.
/// There are roughly 240 of them and we set the initial capacity of the HashSet to 320 to offer a
/// load factor of roughly 0.75.
public let supportedRegionCodes: Set<String>
//676
/// The set of country calling codes that map to the non-geo entity region ("001"). This set
/// currently contains < 12 elements so the default capacity of 16 (load factor=0.75) is fine.
private let countryCodesForNonGeographicalRegion: Set<Int32>
// MARK: Lifecycle
public init() {
metadataManager = MetadataManager()
regionCodesByCountryCode = RegionCodesByCountryCode.regionCodesByCountryCode()
regexCache = RegexCache()
var supportedRegionCodes = Set<String>(minimumCapacity: 320)
var countryCodesForNonGeographicalRegion = Set<Int32>()
for (countryCode, regionCodes) in regionCodesByCountryCode {
// We can assume that if the country calling code maps to the non-geo entity region code then
// that's the only region code it maps to.
if regionCodes.count == 1 && regionCodes[0] == Self.regionCodeForNonGeoEntity {
// This is the subset of all country codes that map to the non-geo entity region code.
countryCodesForNonGeographicalRegion.insert(countryCode)
} else {
// The supported regions set does not include the "001" non-geo entity region code.
supportedRegionCodes.formUnion(regionCodes)
}
}
self.supportedRegionCodes = supportedRegionCodes
self.countryCodesForNonGeographicalRegion = countryCodesForNonGeographicalRegion
// If the non-geo entity still got added to the set of supported regions it must be because
// there are entries that list the non-geo entity alongside normal regions (which is wrong).
// If we discover this, remove the non-geo entity from the set of supported regions and log.
if supportedRegionCodes.remove(Self.regionCodeForNonGeoEntity) != nil {
debugPrint("WARNING", "invalid metadata (country calling code was mapped to the non-geo entity as well as specific region(s))")
}
var nanpaRegionCodes = Set<String>(minimumCapacity: 35)
nanpaRegionCodes.formUnion(regionCodesByCountryCode[Self.nanpaCountryCode]!)
self.nanpaRegionCodes = nanpaRegionCodes
}
// MARK: Parsing
/// Parses a number string, used to create PhoneNumber objects. Throws.
///
/// - Parameters:
/// - numberString: the raw number string.
/// - regionCode: ISO 639 compliant region code.
/// - ignoreType: Avoids number type checking for faster performance.
/// - Returns: PhoneNumber object.
public func parse(_ numberString: String, regionCode: String = PhoneNumberUtil.defaultRegionCode(), ignoreType: Bool = false) throws -> PhoneNumber {
var numberStringWithPlus = numberString
do {
return try parseHelper(numberString, regionCode: regionCode, ignoreType: ignoreType)
} catch {
if numberStringWithPlus.first != "+" {
numberStringWithPlus = "+" + numberStringWithPlus
}
}
return try parseHelper(numberStringWithPlus, regionCode: regionCode, ignoreType: ignoreType)
}
// MARK: Checking
/// Checks if a number string is a valid PhoneNumber object
///
/// - Parameters:
/// - numberString: the raw number string.
/// - region: ISO 639 compliant region code.
/// - ignoreType: Avoids number type checking for faster performance.
/// - Returns: Bool
public func isValidPhoneNumber(_ numberString: String, regionCode: String = PhoneNumberUtil.defaultRegionCode(), ignoreType: Bool = false) -> Bool {
return (try? parse(numberString, regionCode: regionCode, ignoreType: ignoreType)) != nil
}
// MARK: Formatting
/// Formats a PhoneNumber object for dispaly.
///
/// - parameter phoneNumber: PhoneNumber object.
/// - parameter format: PhoneNumberFormat enum.
/// - parameter withPrefix: Whether or not to include the prefix.
///
/// - returns: Formatted representation of the PhoneNumber.
public func format(_ phoneNumber: PhoneNumber, format: PhoneNumberFormat, withPrefix: Bool = true) -> String {
if format == .e164 {
let formattedNationalNumber = phoneNumber.adjustedNationalNumber()
if !withPrefix {
return formattedNationalNumber
}
return "+\(phoneNumber.countryCode)\(formattedNationalNumber)"
} else {
let metadata = metadataManager.metadataByCountryCode[phoneNumber.countryCode]
let formattedNationalNumber = self.format(phoneNumber: phoneNumber, format: format, metadata: metadata)
if format == .international, withPrefix {
return "+\(phoneNumber.countryCode) \(formattedNationalNumber)"
} else {
return formattedNationalNumber
}
}
}
// MARK: Country and region code
/// Get leading digits for an ISO 639 compliant region code.
///
/// - parameter regionCode: ISO 639 compliant region code.
///
/// - returns: leading digits (e.g. 876 for Jamaica).
public func leadingDigits(forRegionCode regionCode: String) -> String? {
return metadataManager.metadataByRegionCode[regionCode]?.leadingDigits
}
/// Get a formatted example phone number for an ISO 639 compliant region code.
///
/// - parameter regionCode: ISO 639 compliant region code.
/// - parameter type: `PhoneNumberType` desired. default: `.mobile`
/// - parameter format: `PhoneNumberFormat` to use for formatting. default: `.international`
/// - parameter withPrefix: Whether or not to include the prefix.
///
/// - returns: A formatted example phone number
public func formattedExampleNumber(
forRegionCode regionCode: String,
ofType type: PhoneNumberType = .mobile,
format: PhoneNumberFormat = .international,
withPrefix: Bool = true
) -> String? {
return exampleNumber(regionCode: regionCode, type: type)
.flatMap { self.format($0, format: format, withPrefix: withPrefix) }
}
/// Get an array of Metadata objects corresponding to a given country code.
///
/// - parameter countryCode: international country code (e.g 44 for the UK)
public func metadata(forCountryCode countryCode: Int32) -> PhoneMetadata? {
return metadataManager.metadataByCountryCode[countryCode]
}
/// Get an array of Metadata objects corresponding to a given country code.
///
/// - parameter countryCode: international country code (e.g 44 for the UK)
public func metadatas(forCountryCode countryCode: Int32) -> [PhoneMetadata]? {
return metadataManager.metadatasByCountryCode[countryCode]
}
/// Get an array of possible phone number lengths for the country, as specified by the parameters.
///
/// - parameter country: ISO 639 compliant region code.
/// - parameter phoneNumberType: PhoneNumberType enum.
/// - parameter lengthType: PossibleLengthType enum.
///
/// - returns: Array of possible lengths for the country. May be empty.
public func possiblePhoneNumberLengths(regionCode: String, phoneNumberType: PhoneNumberType, lengthType: PhoneNumberPossibleLengthType) -> [Int] {
guard let metadata = metadataManager.metadataByRegionCode[regionCode] else { return [] }
let possibleLengths = possiblePhoneNumberLengths(metadata: metadata, phoneNumberType: phoneNumberType)
switch lengthType {
case .national: return possibleLengths?.national.flatMap { parsePossibleLengths($0) } ?? []
case .localOnly: return possibleLengths?.localOnly.flatMap { parsePossibleLengths($0) } ?? []
}
}
private func possiblePhoneNumberLengths(metadata: PhoneMetadata, phoneNumberType: PhoneNumberType) -> PhoneNumberPossibleLengths? {
switch phoneNumberType {
case .fixedLine: return metadata.fixedLine?.possibleLengths
case .mobile: return metadata.mobile?.possibleLengths
case .pager: return metadata.pager?.possibleLengths
case .personalNumber: return metadata.personalNumber?.possibleLengths
case .premiumRate: return metadata.premiumRate?.possibleLengths
case .sharedCost: return metadata.sharedCost?.possibleLengths
case .tollFree: return metadata.tollFree?.possibleLengths
case .voicemail: return metadata.voicemail?.possibleLengths
case .voip: return metadata.voip?.possibleLengths
case .uan: return metadata.uan?.possibleLengths
case .fixedLineOrMobile: return nil // caller needs to combine results for .fixedLine and .mobile
case .unknown: return nil
}
}
/// Parse lengths string into array of Int, e.g. "6,[8-10]" becomes [6,8,9,10]
private func parsePossibleLengths(_ lengths: String) -> [Int] {
let components = lengths.components(separatedBy: ",")
let results = components.reduce([Int](), { result, component in
let newComponents = parseLengthComponent(component)
return result + newComponents
})
return results
}
/// Parses numbers and ranges into array of Int
private func parseLengthComponent(_ component: String) -> [Int] {
if let int = Int(component) {
return [int]
} else {
let trimmedComponent = component.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
let rangeLimits = trimmedComponent.components(separatedBy: "-").compactMap { Int($0) }
guard rangeLimits.count == 2,
let rangeStart = rangeLimits.first,
let rangeEnd = rangeLimits.last
else { return [] }
return Array(rangeStart...rangeEnd)
}
}
}
// MARK: - Manager for parsing flow.
extension PhoneNumberUtil {
/**
Parse a string into a phone number object with a custom region. Can throw.
- Parameter numberString: String to be parsed to phone number struct.
- Parameter regionCode: ISO 639 compliant region code.
- parameter ignoreType: Avoids number type checking for faster performance.
*/
func parseHelper(_ numberString: String, regionCode: String, ignoreType: Bool) throws -> PhoneNumber {
assert(regionCode == regionCode.uppercased())
// Extract number (2)
var nationalNumber = numberString
let match = try regexCache.phoneDataDetectorMatch(numberString)
let matchedNumber = nationalNumber.substring(with: match.range)
// Replace Arabic and Persian numerals and let the rest unchanged
nationalNumber = regexCache.stringByReplacingOccurrences(matchedNumber, map: PhoneNumberPatterns.allNormalizationMappings, keepUnmapped: true)
// Strip and extract extension (3)
var numberExtension: String?
if let rawExtension = stripExtension(&nationalNumber) {
numberExtension = normalizePhoneNumber(rawExtension)
}
// Country code parse (4)
guard var metadata = metadataManager.metadataByRegionCode[regionCode] else {
throw PhoneNumberError.invalidCountryCode
}
var countryCode: Int32
do {
countryCode = try extractCountryCode(nationalNumber, nationalNumber: &nationalNumber, metadata: metadata)
} catch {
let plusRemovedNumberString = regexCache.replaceStringByRegex(pattern: PhoneNumberPatterns.leadingPlusCharsPattern, string: nationalNumber)
countryCode = try extractCountryCode(plusRemovedNumberString, nationalNumber: &nationalNumber, metadata: metadata)
}
if countryCode == 0 {
countryCode = metadata.countryCode
}
// Normalized number (5)
let normalizedNationalNumber = normalizePhoneNumber(nationalNumber)
nationalNumber = normalizedNationalNumber
// If country code is not default, grab correct metadata (6)
if countryCode != metadata.countryCode, let metadataByCountry = metadataManager.metadataByCountryCode[countryCode] {
metadata = metadataByCountry
}
// National Prefix Strip (7)
stripNationalPrefix(&nationalNumber, metadata: metadata)
// Test number against general number description for correct metadata (8)
if let generalNumberDesc = metadata.generalDesc, !regexCache.hasValue(generalNumberDesc.nationalNumberPattern) || !isNumberMatchingDesc(nationalNumber, numberDesc: generalNumberDesc) {
throw PhoneNumberError.notANumber
}
// Finalize remaining parameters and create phone number object (9)
let leadingZero = nationalNumber.hasPrefix("0")
guard let finalNationalNumber = UInt64(nationalNumber) else {
throw PhoneNumberError.notANumber
}
// Check if the number if of a known type (10)
var type: PhoneNumberType = .unknown
if !ignoreType {
if let regionCode = regionCodeHelper(nationalNumber: finalNationalNumber, countryCode: countryCode, leadingZero: leadingZero), let foundMetadata = metadataManager.metadataByRegionCode[regionCode] {
metadata = foundMetadata
}
type = phoneNumberType(nationalNumber: String(nationalNumber), metadata: metadata, leadingZero: leadingZero)
if type == .unknown {
throw PhoneNumberError.unknownType
}
}
return PhoneNumber(countryCode: countryCode, nationalNumber: finalNationalNumber, extension: numberExtension, italianLeadingZero: leadingZero, numberOfLeadingZeros: 0, rawInput: numberString, countryCodeSource: .unspecified, preferredDomesticCarrierCode: nil, type: type)
}
// Parse task
/// Get correct ISO 639 compliant region code for a number.
///
/// - Parameters:
/// - nationalNumber: national number.
/// - countryCode: country code.
/// - leadingZero: whether or not the number has a leading zero.
/// - Returns: ISO 639 compliant region code.
func regionCodeHelper(nationalNumber: UInt64, countryCode: Int32, leadingZero: Bool) -> String? {
guard let metadatas = metadataManager.metadatasByCountryCode[countryCode] else { return nil }
if metadatas.count == 1 {
return metadatas[0].regionCode
}
let nationalNumberString = String(nationalNumber)
for metadata in metadatas {
if let leadingDigits = metadata.leadingDigits {
if regexCache.matchesAtStartByRegex(pattern: leadingDigits, string: nationalNumberString) {
return metadata.regionCode
}
}
if leadingZero && phoneNumberType(nationalNumber: "0" + nationalNumberString, metadata: metadata, leadingZero: false) != .unknown {
return metadata.regionCode
}
if phoneNumberType(nationalNumber: nationalNumberString, metadata: metadata, leadingZero: false) != .unknown {
return metadata.regionCode
}
}
return nil
}
}
// MARK: - Parser. Contains parsing functions.
extension PhoneNumberUtil {
// MARK: Normalizations
/**
Normalize a phone number (e.g +33 612-345-678 to 33612345678).
- Parameter number: Phone number string.
- Returns: Normalized phone number string.
*/
func normalizePhoneNumber(_ number: String) -> String {
let normalizationMappings = PhoneNumberPatterns.allNormalizationMappings
return regexCache.stringByReplacingOccurrences(number, map: normalizationMappings)
}
// MARK: Extractions
/**
Extract country code (e.g +33 612-345-678 to 33).
- Parameter number: Number string.
- Parameter nationalNumber: National number string - inout.
- Parameter metadata: Metadata object.
- Returns: Country code is UInt64.
*/
func extractCountryCode(_ number: String, nationalNumber: inout String, metadata: PhoneMetadata) throws -> Int32 {
var fullNumber = number
guard let possibleCountryIddPrefix = metadata.internationalPrefix else {
return 0
}
let countryCodeSource = stripInternationalPrefixAndNormalize(&fullNumber, possibleIddPrefix: possibleCountryIddPrefix)
if countryCodeSource != .fromDefaultCountry {
if fullNumber.count <= PhoneNumberConstants.minLengthForNSN {
throw PhoneNumberError.tooShort
}
if let potentialCountryCode = extractPotentialCountryCode(fullNumber, nationalNumber: &nationalNumber), potentialCountryCode != 0 {
return potentialCountryCode
} else {
return 0
}
} else {
let defaultCountryCode = String(metadata.countryCode)
if fullNumber.hasPrefix(defaultCountryCode) {
var potentialNationalNumber = (fullNumber as NSString).substring(from: defaultCountryCode.utf16.count)
guard let validNumberPattern = metadata.generalDesc?.nationalNumberPattern, let possibleNumberPattern = metadata.generalDesc?.possibleNumberPattern else {
return 0
}
stripNationalPrefix(&potentialNationalNumber, metadata: metadata)
let potentialNationalNumberStr = potentialNationalNumber
if (!regexCache.matchesEntirelyByRegex(pattern: validNumberPattern, string: fullNumber) && regexCache.matchesEntirelyByRegex(pattern: validNumberPattern, string: potentialNationalNumberStr)) || !regexCache.testStringLengthAgainstPattern(pattern: possibleNumberPattern, string: fullNumber) {
nationalNumber = potentialNationalNumberStr
if let countryCode = Int32(defaultCountryCode) {
return countryCode
}
}
}
}
return 0
}
/**
Extract potential country code (e.g +33 612-345-678 to 33).
- Parameter fullNumber: Full number string.
- Parameter nationalNumber: National number string.
- Returns: Country code is UInt64. Optional.
*/
func extractPotentialCountryCode(_ fullNumber: String, nationalNumber: inout String) -> Int32? {
let fullNumber = fullNumber as NSString
if fullNumber.length == 0 || fullNumber.substring(to: 1) == "0" {
return 0
}
let numberLength = fullNumber.length
let maxCountryCode = PhoneNumberConstants.maxLengthCountryCode
var startPosition = 0
if fullNumber.hasPrefix("+") {
if fullNumber.length == 1 {
return 0
}
startPosition = 1
}
for i in 1...numberLength {
if i > maxCountryCode {
break
}
let stringRange = NSRange(location: startPosition, length: i)
let subNumber = fullNumber.substring(with: stringRange)
if let potentialCountryCode = Int32(subNumber), metadataManager.metadatasByCountryCode[potentialCountryCode] != nil {
nationalNumber = fullNumber.substring(from: i)
return potentialCountryCode
}
}
return 0
}
// MARK: Validations
func phoneNumberType(nationalNumber: String, metadata: PhoneMetadata, leadingZero: Bool = true) -> PhoneNumberType {
if leadingZero {
let type = self.phoneNumberType(nationalNumber: "0" + nationalNumber, metadata: metadata, leadingZero: false)
if type != .unknown {
return type
}
}
guard let generalNumberDesc = metadata.generalDesc else {
return .unknown
}
if !regexCache.hasValue(generalNumberDesc.nationalNumberPattern) || !isNumberMatchingDesc(nationalNumber, numberDesc: generalNumberDesc) {
return .unknown
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.pager) {
return .pager
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.premiumRate) {
return .premiumRate
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.tollFree) {
return .tollFree
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.sharedCost) {
return .sharedCost
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.voip) {
return .voip
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.personalNumber) {
return .personalNumber
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.uan) {
return .uan
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.voicemail) {
return .voicemail
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.fixedLine) {
if metadata.fixedLine?.nationalNumberPattern == metadata.mobile?.nationalNumberPattern {
return .fixedLineOrMobile
} else if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.mobile) {
return .fixedLineOrMobile
} else {
return .fixedLine
}
}
if isNumberMatchingDesc(nationalNumber, numberDesc: metadata.mobile) {
return .mobile
}
return .unknown
}
/**
Checks if number matches description.
- Parameter nationalNumber: National number string.
- Parameter numberDesc: PhoneNumberDesc of a given phone number type.
- Returns: True or false.
*/
func isNumberMatchingDesc(_ nationalNumber: String, numberDesc: PhoneNumberDesc?) -> Bool {
return regexCache.matchesEntirelyByRegex(pattern: numberDesc?.nationalNumberPattern, string: nationalNumber)
}
/**
Checks and strips if prefix is international dialing pattern.
- Parameter number: Number string.
- Parameter iddPattern: iddPattern for a given country.
- Returns: True or false and modifies the number accordingly.
*/
func parsePrefixAsIdd(_ number: inout String, iddPattern: String) -> Bool {
guard regexCache.stringPositionByRegex(pattern: iddPattern, string: number) == 0 else {
return false
}
do {
guard let match = try? regexCache.matchesByRegex(pattern: iddPattern, string: number).first else {
return false
}
let matchedString = number.substring(with: match.range)
let matchEnd = matchedString.count
let remainString = (number as NSString).substring(from: matchEnd)
let capturingDigitPatterns = try NSRegularExpression(pattern: PhoneNumberPatterns.capturingDigitPattern, options: .caseInsensitive)
if let firstMatch = capturingDigitPatterns.firstMatch(in: remainString, options: [], range: NSRange(location: 0, length: remainString.utf16.count)) {
let digitMatched = remainString.substring(with: firstMatch.range)
if !digitMatched.isEmpty {
let normalizedGroup = regexCache.stringByReplacingOccurrences(digitMatched, map: PhoneNumberPatterns.allNormalizationMappings)
if normalizedGroup == "0" {
return false
}
}
}
number = remainString
return true
} catch {
return false
}
}
// MARK: Strip helpers
/**
Strip an extension (e.g +33 612-345-678 ext.89 to 89).
- Parameter number: Number string.
- Returns: Modified number without extension and optional extension as string.
*/
func stripExtension(_ number: inout String) -> String? {
if let match = try? regexCache.matchesByRegex(pattern: PhoneNumberPatterns.extnPattern, string: number).first {
let adjustedRange = NSRange(location: match.range.location + 1, length: match.range.length - 1)
let matchString = number.substring(with: adjustedRange)
let stringRange = NSRange(location: 0, length: match.range.location)
number = number.substring(with: stringRange)
return matchString
}
return nil
}
/**
Strip international prefix.
- Parameter number: Number string.
- Parameter possibleIddPrefix: Possible idd prefix for a given country.
- Returns: Modified normalized number without international prefix and a PNCountryCodeSource enumeration.
*/
func stripInternationalPrefixAndNormalize(_ number: inout String, possibleIddPrefix: String?) -> PhoneNumber.CountryCodeSource {
if regexCache.matchesAtStartByRegex(pattern: PhoneNumberPatterns.leadingPlusCharsPattern, string: number) {
number = regexCache.replaceStringByRegex(pattern: PhoneNumberPatterns.leadingPlusCharsPattern, string: number)
return .fromNumberWithPlusSign
}
number = normalizePhoneNumber(number)
guard let possibleIddPrefix = possibleIddPrefix else {
return .fromNumberWithoutPlusSign
}
let prefixResult = parsePrefixAsIdd(&number, iddPattern: possibleIddPrefix)
if prefixResult {
return .fromNumberWithIDD
} else {
return .fromDefaultCountry
}
}
/**
Strip national prefix.
- Parameter number: Number string.
- Parameter metadata: Final country's metadata.
- Returns: Modified number without national prefix.
*/
func stripNationalPrefix(_ number: inout String, metadata: PhoneMetadata) {
guard let possibleNationalPrefix = metadata.nationalPrefixForParsing else {
return
}
let prefixPattern = String(format: "^(?:%@)", possibleNationalPrefix)
guard let firstMatch = try? regexCache.matchesByRegex(pattern: prefixPattern, string: number).first else {
return
}
let nationalNumberRule = metadata.generalDesc?.nationalNumberPattern
let firstMatchString = number.substring(with: firstMatch.range)
let numOfGroups = firstMatch.numberOfRanges - 1
var transformedNumber = ""
let firstRange = firstMatch.range(at: numOfGroups)
let firstMatchStringWithGroup = firstRange.length > 0 && firstRange.location < number.utf16.count ? number.substring(with: firstRange) : ""
let firstMatchStringWithGroupHasValue = regexCache.hasValue(firstMatchStringWithGroup)
if let transformRule = metadata.nationalPrefixTransformRule, firstMatchStringWithGroupHasValue {
transformedNumber = regexCache.replaceFirstStringByRegex(pattern: prefixPattern, string: number, template: transformRule)
} else {
let index = number.index(number.startIndex, offsetBy: firstMatchString.count)
transformedNumber = String(number[index...])
}
if regexCache.hasValue(nationalNumberRule) && regexCache.matchesEntirelyByRegex(pattern: nationalNumberRule, string: number) && !regexCache.matchesEntirelyByRegex(pattern: nationalNumberRule, string: transformedNumber) {
return
}
number = transformedNumber
}
}
// MARK: - Formatter
extension PhoneNumberUtil {
// MARK: Formatting functions
/// Formats phone numbers for display
///
/// - Parameters:
/// - phoneNumber: Phone number object.
/// - format: Format.
/// - metadata: Region meta data.
/// - Returns: Formatted Modified national number ready for display.
func format(phoneNumber: PhoneNumber, format: PhoneNumberFormat, metadata: PhoneMetadata?) -> String {
var formattedNationalNumber = phoneNumber.adjustedNationalNumber()
if let metadata = metadata {
formattedNationalNumber = formatNationalNumber(formattedNationalNumber, metadata: metadata, format: format)
if let formattedExtension = formatExtension(phoneNumber.extension, metadata: metadata) {
formattedNationalNumber = formattedNationalNumber + formattedExtension
}
}
return formattedNationalNumber
}
/// Formats extension for display
///
/// - Parameters:
/// - numberExtension: Number extension string.
/// - metadata: Region meta data.
/// - Returns: Modified number extension with either a preferred extension prefix or the default one.
func formatExtension(_ numberExtension: String?, metadata: PhoneMetadata) -> String? {
if let extns = numberExtension {
if let preferredExtnPrefix = metadata.preferredExtnPrefix {
return "\(preferredExtnPrefix)\(extns)"
} else {
return "\(PhoneNumberConstants.defaultExtnPrefix)\(extns)"
}
}
return nil
}
/// Formats national number for display
///
/// - Parameters:
/// - nationalNumber: National number string.
/// - metadata: Region meta data.
/// - format: Format.
/// - Returns: Modified nationalNumber for display.
func formatNationalNumber(_ nationalNumber: String, metadata: PhoneMetadata, format: PhoneNumberFormat) -> String {
let formats = metadata.numberFormats
var selectedFormat: NumberFormat?
for format in formats {
if let leadingDigitPattern = format.leadingDigitsPatterns?.last {
if regexCache.stringPositionByRegex(pattern: leadingDigitPattern, string: nationalNumber) == 0 {
if regexCache.matchesEntirelyByRegex(pattern: format.pattern, string: nationalNumber) {
selectedFormat = format
break
}
}
} else {
if regexCache.matchesEntirelyByRegex(pattern: format.pattern, string: nationalNumber) {
selectedFormat = format
break
}
}
}
if let formatPattern = selectedFormat {
guard let numberFormatRule = (format == PhoneNumberFormat.international && formatPattern.intlFormat != nil) ? formatPattern.intlFormat : formatPattern.format, let pattern = formatPattern.pattern else {
return nationalNumber
}
var formattedNationalNumber = ""
var prefixFormattingRule = ""
if let nationalPrefixFormattingRule = formatPattern.nationalPrefixFormattingRule, let nationalPrefix = metadata.nationalPrefix {
prefixFormattingRule = regexCache.replaceStringByRegex(pattern: PhoneNumberPatterns.npPattern, string: nationalPrefixFormattingRule, template: nationalPrefix)
prefixFormattingRule = regexCache.replaceStringByRegex(pattern: PhoneNumberPatterns.fgPattern, string: prefixFormattingRule, template: "\\$1")
}
if format == PhoneNumberFormat.national, regexCache.hasValue(prefixFormattingRule) {
let replacePattern = regexCache.replaceFirstStringByRegex(pattern: PhoneNumberPatterns.firstGroupPattern, string: numberFormatRule, template: prefixFormattingRule)
formattedNationalNumber = regexCache.replaceStringByRegex(pattern: pattern, string: nationalNumber, template: replacePattern)
} else {
formattedNationalNumber = regexCache.replaceStringByRegex(pattern: pattern, string: nationalNumber, template: numberFormatRule)
}
return formattedNationalNumber
} else {
return nationalNumber
}
}
}
extension PhoneNumberUtil {
// 723
/// Attempts to extract a possible number from the string passed in. This currently strips all
/// leading characters that cannot be used to start a phone number. Characters that can be used to
/// start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
/// are found in the number passed in, an empty string is returned. This function also attempts to
/// strip off any alternative extensions or endings if two or more are present, such as in the case
/// of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
/// (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
/// number is parsed correctly.
///
/// - Parameter string: the string that might contain a phone number.
/// - Returns: the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
/// string if no character used to start phone numbers (such as + or any digit) is found in the
/// number.
func extractPossibleNumber(_ string: String) -> String {
if let match = Self.validStartCharPattern.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) {
var number = (string as NSString).substring(with: NSRange(location: match.range.location, length: string.utf16.count - match.range.location))
// Remove trailing non-alpha non-numerical characters.
if let trailingCharsMatch = Self.unwantedEndCharsPattern.firstMatch(in: number, options: [], range: NSRange(location: 0, length: number.utf16.count)) {
number = (number as NSString).substring(with: NSRange(location: 0, length: trailingCharsMatch.range.location))
}
// Check for extra numbers at the end.
if let secondNumberMatch = Self.secondNumberStartPattern.firstMatch(in: number, options: [], range: NSRange(location: 0, length: number.utf16.count)) {
number = (number as NSString).substring(with: NSRange(location: 0, length: secondNumberMatch.range.location))
}
return number
} else {
return ""
}
}
// 754
/// Checks to see if the string of characters could possibly be a phone number at all. At the
/// moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
/// commonly found in phone numbers.
/// This method does not require the number to be normalized in advance - but does assume that
/// leading non-number symbols have been removed, such as by the method extractPossibleNumber.
///
/// - Parameter string: string to be checked for viability as a phone number.
/// - Returns: true if the number could be a phone number of some sort, otherwise false.
static func isViablePhoneNumber(string: String) -> Bool {
if string.utf16.count < Self.minimumLengthForNSN {
return false
}
return Self.validPhoneNumberPattern.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) != nil
}
// 778
/// Normalizes a string of characters representing a phone number. This performs the following
/// conversions:
/// - Punctuation is stripped.
/// For ALPHA/VANITY numbers:
/// - Letters are converted to their numeric representation on a telephone keypad. The keypad
/// used here is the one defined in ITU Recommendation E.161. This is only done if there are 3
/// or more letters in the number, to lessen the risk that such letters are typos.
/// For other numbers:
/// - Wide-ascii digits are converted to normal ASCII (European) digits.
/// - Arabic-Indic numerals are converted to European numerals.
/// - Spurious alpha characters are stripped.
///
/// - Parameter number: a StringBuilder of characters representing a phone number that will be
/// normalized in place
static func normalize(_ string: String) -> String {
var normalizedString: String
if validAlphaPhonePattern.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) != nil {
normalizedString = normalizeHelper(string, normalizationReplacements: Self.alphaPhoneMappings, removeNonMatches: true)
} else {
normalizedString = normalizeDigitsOnly(string)
}
return normalizedString
}
// 795
/// Normalizes a string of characters representing a phone number. This converts wide-ascii and
/// arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
/// - Parameter number: a string of characters representing a phone number.
/// - Returns: the normalized string version of the phone number.
public static func normalizeDigitsOnly(_ string: String) -> String {
return normalizeDigits(string, keepNonDigits: false /* strip non-digits */)
}
// 799
static func normalizeDigits(_ string: String, keepNonDigits: Bool) -> String {
var normalizedDigits = ""
for character in string {
let digit = Int(String(character), radix: 10)
if digit != -1 {
normalizedDigits.append(character)
} else if keepNonDigits {
normalizedDigits.append(character)
}
}
return normalizedDigits
}
// 820
/// Normalizes a string of characters representing a phone number. This strips all characters which
/// are not diallable on a mobile phone keypad (including all non-ASCII digits).
/// - Parameter number: a string of characters representing a phone number.
/// - Returns: the normalized string version of the phone number.
public static func normalizeDiallableCharsOnly(_ string: String) -> String {
return normalizeHelper(string, normalizationReplacements: Self.diallableCharMappings, removeNonMatches: true /* remove non matches */)
}
// 828
/// Converts all alpha characters in a number to their respective digits on a keypad, but retains
/// existing formatting.
public static func convertAlphaCharactersInNumber(_ string: String) -> String {
return normalizeHelper(string, normalizationReplacements: Self.alphaPhoneMappings, removeNonMatches: false)
}
// 1002
/// Normalizes a string of characters representing a phone number by replacing all characters found
/// in the accompanying map with the values therein, and stripping all other characters if
/// removeNonMatches is true.
/// - Parameters:
/// - string: a string of characters representing a phone number.
/// - normalizationReplacements: a mapping of characters to what they should be replaced by in
/// the normalized version of the phone number
/// - removeNonMatches: indicates whether characters that are not able to be replaced should
/// be stripped from the number. If this is false, they will be left unchanged in the number.
/// - Returns: the normalized string version of the phone number.
private static func normalizeHelper(_ string: String, normalizationReplacements: [Character: Character], removeNonMatches: Bool) -> String {
var normalizedString = ""
for character in string {
if let newDigit = normalizationReplacements[character] {
normalizedString.append(newDigit)
} else if !removeNonMatches {
normalizedString.append(character)
}
// If neither of the above are true, we remove this character.
}
return normalizedString
}
// 1044
/// Returns all global network calling codes the library has metadata for.
/// - Returns: An unordered set of the country calling codes for every non-geographical entity the
/// library supports.
public func supportedGlobalNetworkCountryCodes() -> Set<Int32> {
return countryCodesForNonGeographicalRegion
}
// 1057
/// Returns all country calling codes the library has metadata for, covering both non-geographical
/// entities (global network calling codes) and those used for geographical entities. This could be
/// used to populate a drop-down box of country calling codes for a phone-number widget, for
/// instance.
/// - Returns: An unordered set of the country calling codes for every geographical and
/// non-geographical entity the library supports
public func supportedCountryCodes() -> Set<Int32> {
return Set<Int32>(regionCodesByCountryCode.keys)
}
// 1210
/// Tests whether a phone number has a geographical association. It checks if the number is
/// associated with a certain region in the country to which it belongs. Note that this doesn't
/// verify if the number is actually in use.
@available(*, unavailable)
public func isGeographical(_ phoneNumber: PhoneNumber) -> Bool {
fatalError()
// FIXME:
// return isNumberGeographical(getNumberType(phoneNumber), phoneNumber.getCountryCode());
}
// 1218
/// Overload of isNumberGeographical(PhoneNumber), since calculating the phone number type is
/// expensive; if we have already done this, we don't want to do it again.
public func isGeographicalPhoneNumber(type: PhoneNumberType, countryCode: Int32) -> Bool {
return type == .fixedLine || type == .fixedLineOrMobile || (Self.geoMobileCountryCodes.contains(countryCode) && type == .mobile)
}
// 1228
/// Helper function to check region code is not unknown or null.
private func isValid(regionCode: String) -> Bool {
return supportedRegionCodes.contains(regionCode)
}
// 1235
/// Helper function to check the country calling code is valid.
private func hasValid(countryCode: Int32) -> Bool {
return regionCodesByCountryCode.keys.contains(countryCode)
}
// 1402
private func metadata(countryCode: Int32, regionCode: String) -> PhoneMetadata? {
return regionCode == Self.regionCodeForNonGeoEntity ? metadataForNonGeographicalRegion(countryCode: countryCode) : metadata(forRegionCode: regionCode)
}
// 1875
/// Gets the national significant number of a phone number. Note a national significant number
/// doesn't contain a national prefix or any formatting.
/// - Parameter number: the phone number for which the national significant number is needed.
/// - Returns: the national significant number of the PhoneNumber object passed in.
public func nationalSignificantNumber(of phoneNumber: PhoneNumber) -> String {
// If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
var nationalNumber = ""
if phoneNumber.italianLeadingZero && phoneNumber.numberOfLeadingZeros > 0 {
let zeros = [Character](repeating: "0", count: phoneNumber.numberOfLeadingZeros)
nationalNumber += String(zeros)
}
nationalNumber += String(phoneNumber.nationalNumber)
return nationalNumber
}
// 1890
/// A helper function that is used by format and formatByPattern.
private func prefixNumber(countryCode: Int32, numberFormat: PhoneNumberFormat, formattedNumber: inout String) {
switch numberFormat {
case .e164:
formattedNumber = "\(Self.plusSign)\(countryCode)\(formattedNumber)"
case .international:
formattedNumber = "\(Self.plusSign)\(countryCode) \(formattedNumber)"
case .rfc3966:
formattedNumber = "\(Self.rfc3966Prefix)\(Self.plusSign)\(countryCode)-\(formattedNumber)"
case .national:
return
}
}
// 1911
/// Simple wrapper of formatNsn for the common case of no carrier code.
@available(*, unavailable)
private func formatNsn(string: String, metadata: PhoneMetadata, numberFormat: PhoneNumberFormat) -> String {
fatalError()
// FIXME:
// "return formatNsn(number, metadata, numberFormat, null);
}
// 2108
/// Gets a valid number for the specified number type (it may belong to any country).
/// - Parameter type: the type of number that is needed.
/// - Returns: a valid number for the specified type. Returns null when the metadata
/// does not contain such information. This should only happen when no numbers of this type are
/// allocated anywhere in the world anymore.
public func exampleNumber(type: PhoneNumberType) -> PhoneNumber? {
for regionCode in supportedRegionCodes {
if let exampleNumber = exampleNumber(regionCode: regionCode, type: type) {
return exampleNumber
}
}
// If there wasn't an example number for a region, try the non-geographical entities.
for countryCode in countryCodesForNonGeographicalRegion {
guard let desc = numberDesc(metadata: metadataForNonGeographicalRegion(countryCode: countryCode)!, type: type) else {
continue
}
if let exampleNumber = desc.exampleNumber {
do {
return try parse("+\(countryCode)\(exampleNumber)", defaultRegionCode: Self.unknownRegionCode)
} catch {
debugPrint("SEVERE", error)
}
}
}
// There are no example numbers of this type for any country in the library.
return nil
}
// 2184
func numberDesc(metadata: PhoneMetadata, type: PhoneNumberType) -> PhoneNumberDesc? {
switch type {
case .premiumRate:
return metadata.premiumRate
case .tollFree:
return metadata.tollFree
case .mobile:
return metadata.mobile
case .fixedLine, .fixedLineOrMobile:
return metadata.fixedLine
case .sharedCost:
return metadata.sharedCost
case .voip:
return metadata.voip
case .personalNumber:
return metadata.personalNumber
case .pager:
return metadata.pager
case .uan:
return metadata.uan
case .voicemail:
return metadata.voicemail
default:
return metadata.generalDesc
}
}
// 2280
/// Returns the metadata for the given region code or {@code null} if the region code is invalid
/// or unknown.
func metadata(forRegionCode regionCode: String) -> PhoneMetadata? {
if !isValid(regionCode: regionCode) {
return nil
}
return metadataManager.metadata(forRegionCode: regionCode)
}
// 2287
func metadataForNonGeographicalRegion(countryCode: Int32) -> PhoneMetadata? {
if !regionCodesByCountryCode.keys.contains(countryCode) {
return nil
}
return metadataManager.metadataForNonGeographicalRegion(forCountryCode: countryCode)
}
// 2338
public func isValid(phoneNumber: PhoneNumber, regionCode: String) -> Bool {
let countryCode = phoneNumber.countryCode
guard let metadata = self.metadata(countryCode: countryCode, regionCode: regionCode) else {
return false
}
if regionCode != Self.regionCodeForNonGeoEntity && countryCode != (try? self.countryCode(forValidRegionCode: regionCode)) {
// Either the region code was invalid, or the country calling code for this number does not
// match that of the region code.
return false
}
let nationalSignificantNumber = self.nationalSignificantNumber(of: phoneNumber)
return phoneNumberType(nationalNumber: nationalSignificantNumber, metadata: metadata) != .unknown
}
// 2361
/// Returns the region where a phone number is from. This could be used for geocoding at the region
/// level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid
/// numbers).
/// - Parameter number: the phone number whose origin we want to know.
/// - Returns: the region where the phone number is from, or null if no region matches this calling
/// code.
public func regionCode(for phoneNumber: PhoneNumber) -> String? {
let countryCode = phoneNumber.countryCode
guard let regionCodes = regionCodesByCountryCode[countryCode] else {
debugPrint("INFO", "Missing/invalid country_code (\(countryCode))")
return nil
}
if regionCodes.count == 1 {
return regionCodes.first
} else {
return regionCode(for: phoneNumber, in: regionCodes)
}
}
// 2375
private func regionCode(for phoneNumber: PhoneNumber, in regionCodes: [String]) -> String? {
let nationalNumber = nationalSignificantNumber(of: phoneNumber)
for regionCode in regionCodes {
// If leadingDigits is present, use this. Otherwise, do full validation.
// Metadata cannot be null because the region codes come from the country calling code map.
if let metadata = self.metadata(forRegionCode: regionCode) {
if let leadingDigits = metadata.leadingDigits {
if try! regexCache.regex(pattern: leadingDigits).firstMatch(in: nationalNumber, options: [], range: NSRange(location: 0, length: nationalNumber.utf16.count)) != nil {
return regionCode
}
} else if phoneNumberType(nationalNumber: nationalNumber, metadata: metadata) != .unknown {
return regionCode
}
}
}
return nil
}
// 2402
/// Returns the region code that matches the specific country calling code. In the case of no
/// region code being found, ZZ will be returned. In the case of multiple regions, the one
/// designated in the metadata as the "main" region for this calling code will be returned. If the
/// countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
/// non-geographical calling codes like 800) the value "001" will be returned (corresponding to
/// the value for World in the UN M.49 schema).
public func regionCode(forCountryCode countryCode: Int32) -> String? {
return regionCodesByCountryCode[countryCode]?.first
}
// 2412
/// Returns a list with the region codes that match the specific country calling code. For
/// non-geographical country calling codes, the region code 001 is returned. Also, in the case
/// of no region code being found, an empty list is returned.
public func regionCodes(forCountryCode countryCode: Int32) -> [String]? {
return regionCodesByCountryCode[countryCode]
}
// 2425
/// Returns the country calling code for a specific region. For example, this would be 1 for the
/// United States, and 64 for New Zealand.
/// - Parameter regionCode: the region that we want to get the country calling code for.
/// - Returns: the country calling code for the region denoted by regionCode.
public func countryCode(forRegionCode regionCode: String) -> Int32? {
if !isValid(regionCode: regionCode) {
debugPrint("WARNING", "Invalid region code (\(regionCode)) provided.")
return nil
}
return try! countryCode(forValidRegionCode: regionCode)
}
// 2444
/// Returns the country calling code for a specific region. For example, this would be 1 for the
/// United States, and 64 for New Zealand. Assumes the region is already valid.
/// - Parameter regionCode: the region that we want to get the country calling code for.
/// - Throws: `NSError` if the region is invalid.
/// - Returns: The country calling code for the region denoted by regionCode.
private func countryCode(forValidRegionCode regionCode: String) throws -> Int32 {
guard let metadata = metadata(forRegionCode: regionCode) else {
throw NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid region code: \(regionCode)"])
}
return metadata.countryCode
}
/// Parses a string and returns it as a phone number in proto buffer format. The method is quite
/// lenient and looks for a number in the input text (raw input) and does not check whether the
/// string is definitely only a phone number. To do this, it ignores punctuation and white-space,
/// as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits.
/// It will accept a number in any format (E164, national, international etc), assuming it can be
/// interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters
/// into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
///
/// <p> This method will throw a {@link com.google.i18n.phonenumbers.NumberParseException} if the
/// number is not considered to be a possible number. Note that validation of whether the number
/// is actually a valid number for a particular region is not performed. This can be done
/// separately with {@link #isValidNumber}.
///
/// <p> Note this method canonicalizes the phone number such that different representations can be
/// easily compared, no matter what form it was originally entered in (e.g. national,
/// international). If you want to record context about the number being parsed, such as the raw
/// input that was entered, how the country code was derived etc. then call {@link
/// #parseAndKeepRawInput} instead.
///
/// - Parameters:
/// - numberToParse: number that we are attempting to parse. This can contain formatting such
/// as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966
/// format.
/// - defaultRegionCode: region that we are expecting the number to be from. This is only used if
/// the number being parsed is not written in international format. The country_code for the
/// number in this case would be stored as that of the default region supplied. If the number
/// is guaranteed to start with a '+' followed by the country calling code, then RegionCode.ZZ
/// or null can be supplied.
/// - Throws: NumberParseException if the string is not considered to be a viable phone number (e.g.
/// too few or too many digits) or if no default region was supplied and the number is not in
/// international format (does not start with +)
/// - Returns: A phone number proto buffer filled with the parsed number.
public func parse(_ numberToParse: String, defaultRegionCode: String) throws -> PhoneNumber {
fatalError()
// FIXME:
// return parse(numberToParse, defaultRegion, phoneNumber)
}
// 3567
/// Returns true if the supplied region supports mobile number portability. Returns false for
/// invalid, unknown or regions that don't support mobile number portability.
/// - Parameter regionCode: the region for which we want to know whether it supports mobile number
/// portability or not.
public func isMobileNumberPortableRegion(regionCode: String) -> Bool {
guard let metadata = metadata(forRegionCode: regionCode) else {
return false
}
return metadata.mobileNumberPortableRegion
}
// 2083
/// Gets a valid number for the specified region and number type.
/// - Parameters:
/// - regionCode: the region for which an example number is needed.
/// - type: the type of number that is needed.
/// - Returns: a valid number for the specified region and type. Returns null when the metadata
/// does not contain such information or if an invalid region or region 001 was entered.
/// For 001 (representing non-geographical numbers), call
/// {@link #getExampleNumberForNonGeoEntity} instead.
public func exampleNumber(regionCode: String, type: PhoneNumberType) -> PhoneNumber? {
// Check the region code is valid.
if !isValid(regionCode: regionCode) {
return nil
}
if let desc = numberDesc(metadata: metadata(forRegionCode: regionCode)!, type: type) {
if let exampleNumber = desc.exampleNumber {
return try? parse(exampleNumber, regionCode: regionCode)
}
}
return nil
}
/*
// 3202
/// Parses a string and fills up the phoneNumber. This method is the same as the public
/// parse() method, with the exception that it allows the default region to be null, for use by
/// isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
/// to be null or unknown ("ZZ").
///
/// Note if any new field is added to this method that should always be filled in, even when
/// keepRawInput is false, it should also be handled in the copyCoreFieldsOnly() method.
private func parseHelper(numberToParse: String?, defaultRegion: String?, keepRawInput: Bool, checkRegion: Bool) throws -> PhoneNumber {
guard let numberToParse = numberToParse else {
throw PhoneNumberParseError.notANumber("The phone number supplied was null.")
}
guard numberToParse.utf16.count <= Self.maximumInputStringLength else {
throw PhoneNumberParseError.tooLong("The string supplied was too long to parse.")
}
var nationalNumber = ""
var numberBeingParsed = numberToParse
buildNationalNumberForParsing(numberBeingParsed, nationalNumber);
if (!isViablePhoneNumber(nationalNumber)) {
throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
"The string supplied did not seem to be a phone number.");
}
// Check the region supplied is valid, or that the extracted number starts with some sort of +
// sign so the number's region can be determined.
if (checkRegion && !checkRegionForParsing(nationalNumber, defaultRegion)) {
throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
"Missing or invalid default region.");
}
if (keepRawInput) {
phoneNumber.setRawInput(numberBeingParsed);
}
// Attempt to parse extension first, since it doesn't require region-specific data and we want
// to have the non-normalised number here.
String extension = maybeStripExtension(nationalNumber);
if (extension.length() > 0) {
phoneNumber.setExtension(extension);
}
PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
// Check to see if the number is given in international format so we know whether this number is
// from the default region or not.
StringBuilder normalizedNationalNumber = new StringBuilder();
int countryCode = 0;
try {
// TODO: This method should really just take in the string buffer that has already
// been created, and just remove the prefix, rather than taking in a string and then
// outputting a string buffer.
countryCode = maybeExtractCountryCode(nationalNumber, regionMetadata,
normalizedNationalNumber, keepRawInput, phoneNumber);
} catch (NumberParseException e) {
Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber);
if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE
&& matcher.lookingAt()) {
// Strip the plus-char, and try again.
countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
regionMetadata, normalizedNationalNumber,
keepRawInput, phoneNumber);
if (countryCode == 0) {
throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
"Could not interpret numbers after plus-sign.");
}
} else {
throw new NumberParseException(e.getErrorType(), e.getMessage());
}
}
if (countryCode != 0) {
String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
if (!phoneNumberRegion.equals(defaultRegion)) {
// Metadata cannot be null because the country calling code is valid.
regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
}
} else {
// If no extracted country calling code, use the region supplied instead. The national number
// is just the normalized version of the number we were given to parse.
normalizedNationalNumber.append(normalize(nationalNumber));
if (defaultRegion != null) {
countryCode = regionMetadata.getCountryCode();
phoneNumber.setCountryCode(countryCode);
} else if (keepRawInput) {
phoneNumber.clearCountryCodeSource();
}
}
if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
"The string supplied is too short to be a phone number.");
}
if (regionMetadata != null) {
StringBuilder carrierCode = new StringBuilder();
StringBuilder potentialNationalNumber = new StringBuilder(normalizedNationalNumber);
maybeStripNationalPrefixAndCarrierCode(potentialNationalNumber, regionMetadata, carrierCode);
// We require that the NSN remaining after stripping the national prefix and carrier code be
// long enough to be a possible length for the region. Otherwise, we don't do the stripping,
// since the original number could be a valid short number.
ValidationResult validationResult = testNumberLength(potentialNationalNumber, regionMetadata);
if (validationResult != ValidationResult.TOO_SHORT
&& validationResult != ValidationResult.IS_POSSIBLE_LOCAL_ONLY
&& validationResult != ValidationResult.INVALID_LENGTH) {
normalizedNationalNumber = potentialNationalNumber;
if (keepRawInput && carrierCode.length() > 0) {
phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
}
}
}
int lengthOfNationalNumber = normalizedNationalNumber.length();
if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
"The string supplied is too short to be a phone number.");
}
if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
"The string supplied is too long to be a phone number.");
}
setItalianLeadingZerosForPhoneNumber(normalizedNationalNumber, phoneNumber);
phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
}
*/
// 3321
/// Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
/// written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
private func buildNationalNumberForParsing(numberToParse: String, nationalNumber: inout String) {
if let indexOfPhoneContext = numberToParse.range(of: Self.rfc3966PhoneContext)?.lowerBound {
let phoneContextStart = numberToParse.index(indexOfPhoneContext, offsetBy: Self.rfc3966PhoneContext.count)
// If the phone context contains a phone number prefix, we need to capture it, whereas domains
// will be ignored.
if ..<numberToParse.endIndex ~= phoneContextStart && numberToParse[phoneContextStart] == Self.plusSign {
// Additional parameters might follow the phone context. If so, we will remove them here
// because the parameters after phone context are not important for parsing the
// phone number.
if let phoneContextEnd = numberToParse.range(of: ";", range: phoneContextStart..<numberToParse.endIndex)?.lowerBound {
nationalNumber += numberToParse[phoneContextStart...phoneContextEnd]
} else {
nationalNumber += numberToParse[phoneContextStart...]
}
}
// Now append everything between the "tel:" prefix and the phone-context. This should include
// the national number, an optional extension or isdn-subaddress component. Note we also
// handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
// In that case, we append everything from the beginning.
let indexOfNationalNumber: String.Index
if let indexOfRfc3966Prefix = numberToParse.range(of: Self.rfc3966Prefix)?.lowerBound {
indexOfNationalNumber = numberToParse.index(indexOfRfc3966Prefix, offsetBy: Self.rfc3966Prefix.count)
} else {
indexOfNationalNumber = numberToParse.startIndex
}
nationalNumber += numberToParse[indexOfNationalNumber...indexOfPhoneContext]
} else {
// Extract a possible number from the string passed in (this strips leading characters that
// could not be the start of a phone number.)
nationalNumber.append(extractPossibleNumber(numberToParse))
}
// Delete the isdn-subaddress and everything after it if it is present. Note extension won't
// appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
if let indexOfIsdn = nationalNumber.range(of: Self.rfc3966ISDNSubaddress)?.lowerBound {
nationalNumber.removeSubrange(indexOfIsdn..<nationalNumber.endIndex)
}
// If both phone context and isdn-subaddress are absent but other parameters are present, the
// parameters are left in nationalNumber. This is because we are concerned about deleting
// content from a potential number string when there is no strong evidence that the number is
// actually written in RFC3966.
}
// 3371
/// Returns a new phone number containing only the fields needed to uniquely identify a phone
/// number, rather than any fields that capture the context in which the phone number was created.
/// These fields correspond to those set in parse() rather than parseAndKeepRawInput().
private static func copyCoreFieldsOnly(phoneNumberIn: PhoneNumber) -> PhoneNumber {
return PhoneNumber(
countryCode: phoneNumberIn.countryCode,
nationalNumber: phoneNumberIn.nationalNumber,
extension: phoneNumberIn.extension,
italianLeadingZero: phoneNumberIn.italianLeadingZero,
numberOfLeadingZeros: phoneNumberIn.numberOfLeadingZeros,
rawInput: "",
countryCodeSource: .unspecified,
preferredDomesticCarrierCode: nil,
type: .unknown
)
}
}
#if canImport(CoreTelephony)
import CoreTelephony
extension CTTelephonyNetworkInfo {
// The returned value is lowercased.
func isoCountryCode() -> String? {
guard #available(iOS 12.0, *) else {
return subscriberCellularProvider?.isoCountryCode
}
guard let serviceSubscriberCellularProviders = serviceSubscriberCellularProviders else {
return nil
}
if #available(iOS 13.0, *), let dataServiceIdentifier = dataServiceIdentifier {
if let isoCountryCode = serviceSubscriberCellularProviders[dataServiceIdentifier]?.isoCountryCode {
return isoCountryCode
}
}
for carrier in serviceSubscriberCellularProviders.values {
if let isoCountryCode = carrier.isoCountryCode {
return isoCountryCode
}
}
return nil
}
}
#endif
extension PhoneNumberUtil {
public static func defaultRegionCode() -> String {
#if canImport(CoreTelephony)
let networkInfo = CTTelephonyNetworkInfo()
if let isoCountryCode = networkInfo.isoCountryCode() {
return isoCountryCode.uppercased()
}
#endif
return Locale.current.regionCode ?? PhoneNumberConstants.defaultRegionCode
}
}
| 49.821981 | 306 | 0.694413 |
f619649cdc5f0e650489a927b1e3198de377f5df | 5,105 | cpp | C++ | GlobalIllumination/src/Material.cpp | raptoravis/voxelbasedgi | aaf2b02929edfaf72528c2f029696728c5f1d30f | [
"MIT"
] | null | null | null | GlobalIllumination/src/Material.cpp | raptoravis/voxelbasedgi | aaf2b02929edfaf72528c2f029696728c5f1d30f | [
"MIT"
] | null | null | null | GlobalIllumination/src/Material.cpp | raptoravis/voxelbasedgi | aaf2b02929edfaf72528c2f029696728c5f1d30f | [
"MIT"
] | null | null | null | #include <stdafx.h>
#include <Demo.h>
#include <Material.h>
#define NUM_RENDER_STATES 27 // number of render-states that can be specified in material file
struct MaterialInfo
{
const char *name; // info as string
int mode; // info as int
};
// render-states
static const MaterialInfo renderStateList[NUM_RENDER_STATES] =
{
"NONE_CULL",NONE_CULL, "FRONT_CULL",FRONT_CULL, "BACK_CULL",BACK_CULL,
"ZERO_BLEND",ZERO_BLEND, "ONE_BLEND",ONE_BLEND, "SRC_COLOR_BLEND",SRC_COLOR_BLEND,
"INV_SRC_COLOR_BLEND",INV_SRC_COLOR_BLEND, "DST_COLOR_BLEND",DST_COLOR_BLEND,
"INV_DST_COLOR_BLEND",INV_DST_COLOR_BLEND, "SRC_ALPHA_BLEND",SRC_ALPHA_BLEND,
"INV_SRC_ALPHA_BLEND",INV_SRC_ALPHA_BLEND, "DST_ALPHA_BLEND",DST_ALPHA_BLEND,
"INV_DST_ALPHA_BLEND",INV_DST_ALPHA_BLEND, "CONST_COLOR_BLEND",CONST_COLOR_BLEND,
"INV_CONST_COLOR_BLEND",INV_CONST_COLOR_BLEND, "CONST_ALPHA_BLEND",CONST_ALPHA_BLEND,
"INV_CONST_ALPHA_BLEND",INV_CONST_ALPHA_BLEND, "SRC_ALPHA_SAT_BLEND",SRC_ALPHA_SAT_BLEND,
"SRC1_COLOR_BLEND",SRC1_COLOR_BLEND, "INV_SRC1_COLOR_BLEND",INV_SRC1_COLOR_BLEND,
"SRC1_ALPHA_BLEND",SRC1_ALPHA_BLEND, "INV_SRC1_ALPHA_BLEND",INV_SRC1_ALPHA_BLEND,
"ADD_BLEND_OP",ADD_BLEND_OP, "SUBTRACT_BLEND_OP",SUBTRACT_BLEND_OP,
"REV_SUBTRACT_BLEND_OP",REV_SUBTRACT_BLEND_OP, "MIN_BLEND_OP",MIN_BLEND_OP,
"MAX_BLEND_OP",MAX_BLEND_OP
};
// map string into corresponding render-state
#define STR_TO_STATE(str, stateType, state) \
for(unsigned int i=0; i<NUM_RENDER_STATES; i++) \
if(strcmp(renderStateList[i].name, str.c_str()) == 0) \
state = (stateType)renderStateList[i].mode;
bool Material::LoadTextures(std::ifstream &file)
{
std::string str, token;
file >> token;
while (true)
{
file >> str;
if ((str == "}") || (file.eof()))
break;
else if (str == "ColorTexture")
{
file >> str;
colorTexture = Demo::resourceManager->LoadTexture(str.c_str());
if (!colorTexture)
return false;
}
else if (str == "NormalTexture")
{
file >> str;
normalTexture = Demo::resourceManager->LoadTexture(str.c_str());
if (!normalTexture)
return false;
}
else if (str == "SpecularTexture")
{
file >> str;
specularTexture = Demo::resourceManager->LoadTexture(str.c_str());
if (!specularTexture)
return false;
}
}
return true;
}
void Material::LoadRenderStates(std::ifstream &file)
{
std::string str, token;
file >> token;
while (true)
{
file >> str;
if ((str == "}") || (file.eof()))
break;
else if (str == "cull")
{
file >> str;
STR_TO_STATE(str, cullModes, rasterDesc.cullMode);
}
else if (str == "noDepthTest")
depthStencilDesc.depthTest = false;
else if (str == "noDepthMask")
depthStencilDesc.depthMask = false;
else if (str == "colorBlend")
{
blendDesc.blend = true;
file >> str;
STR_TO_STATE(str, blendOptions, blendDesc.srcColorBlend);
file >> str;
STR_TO_STATE(str, blendOptions, blendDesc.dstColorBlend);
file >> str;
STR_TO_STATE(str, blendOps, blendDesc.blendColorOp);
}
else if (str == "alphaBlend")
{
blendDesc.blend = true;
file >> str;
STR_TO_STATE(str, blendOptions, blendDesc.srcAlphaBlend);
file >> str;
STR_TO_STATE(str, blendOptions, blendDesc.dstAlphaBlend);
file >> str;
STR_TO_STATE(str, blendOps, blendDesc.blendAlphaOp);
}
}
}
bool Material::LoadShader(std::ifstream &file)
{
std::string str, token;
unsigned int permutationMask = 0;
file >> token;
while (true)
{
file >> str;
if ((str == "}") || (file.eof()))
break;
else if (str == "permutation")
{
file >> permutationMask;
}
else if (str == "file")
{
file >> str;
shader = Demo::resourceManager->LoadShader(str.c_str(), permutationMask);
if (!shader)
return false;
}
}
return true;
}
bool Material::Load(const char *fileName)
{
strcpy(name, fileName);
char filePath[DEMO_MAX_FILEPATH];
if (!Demo::fileManager->GetFilePath(fileName, filePath))
return false;
std::ifstream file(filePath, std::ios::in);
if (!file.is_open())
return false;
std::string str, token;
file >> str;
while (!file.eof())
{
if (str == "Textures")
{
if (!LoadTextures(file))
{
file.close();
return false;
}
}
else if (str == "RenderStates")
{
LoadRenderStates(file);
}
else if (str == "Shader")
{
if (!LoadShader(file))
{
file.close();
return false;
}
}
file >> str;
}
file.close();
rasterizerState = Demo::renderer->CreateRasterizerState(rasterDesc);
if (!rasterizerState)
return false;
// Increment for all opaque geometry the stencil buffer. In this way direct as well
// as indirect illumination can be restricted to the area, where actually the scene
// geometry is located. On the other hand the sky can be easily rendered to the area,
// where the stencil buffer is still left to 0.
if (!blendDesc.blend)
depthStencilDesc.stencilTest = true;
depthStencilState = Demo::renderer->CreateDepthStencilState(depthStencilDesc);
if (!depthStencilState)
return false;
blendState = Demo::renderer->CreateBlendState(blendDesc);
if (!blendState)
return false;
return true;
}
| 26.045918 | 94 | 0.697747 |
b149686145c5f7eb3e955e98e7348ccbcc245399 | 1,453 | py | Python | storage_engine/base.py | JackInTaiwan/ViDB | d658fd4f6a1ad2d7d36bb270fde2a373d3cc965d | [
"MIT"
] | 2 | 2021-05-29T06:57:24.000Z | 2021-06-15T09:13:38.000Z | storage_engine/base.py | JackInTaiwan/ViDB | d658fd4f6a1ad2d7d36bb270fde2a373d3cc965d | [
"MIT"
] | null | null | null | storage_engine/base.py | JackInTaiwan/ViDB | d658fd4f6a1ad2d7d36bb270fde2a373d3cc965d | [
"MIT"
] | null | null | null | import abc
import json
class BaseStorageEngine(metaclass=abc.ABCMeta):
@abc.abstractmethod
def init_storage(self):
return NotImplemented
@abc.abstractmethod
def create_one(self, image:str, thumbnail:str, features, metadata:json):
return NotImplemented
@abc.abstractmethod
def create_many(self, image:list, thumbnail:list, features:list, metadata:list):
return NotImplemented
@abc.abstractmethod
def read_one(self, index, mode):
return NotImplemented
@abc.abstractmethod
def read_many(self, index:list, mode):
return NotImplemented
@abc.abstractmethod
def delete_one(self, index):
return NotImplemented
@abc.abstractmethod
def delete_many(self, index:list): # TBD: how to relocate files
return NotImplemented
@abc.abstractmethod
def update_one(self, index, metadata):
return NotImplemented
@abc.abstractmethod
def update_many(self, index, metadata):
return NotImplemented
@abc.abstractmethod
def generate_id(self):
return NotImplemented
@abc.abstractmethod
def generate_c_at(self): # create time
return NotImplemented
@abc.abstractmethod
def locate_id(self, index): # TBD: how to relocate files
return NotImplemented
@abc.abstractmethod
def update_storage_table(self, file_path, delete=False):
return NotImplemented | 21.367647 | 84 | 0.689608 |
a105b1f9800a48c86492e84787793fc49ba3377c | 355 | ts | TypeScript | trash/trash1/clientSessionApp/redux/initialState.ts | adamwong246/SpaceTrash | 79cd10113c9cab71781d0be2a02bd63cec19b73f | [
"MIT"
] | 5 | 2020-04-06T00:56:46.000Z | 2020-08-17T17:21:40.000Z | trash/trash1/clientSessionApp/redux/initialState.ts | adamwong246/SpaceTrash | 79cd10113c9cab71781d0be2a02bd63cec19b73f | [
"MIT"
] | 7 | 2020-08-23T22:30:37.000Z | 2022-03-25T19:03:34.000Z | trash/trash1/clientSessionApp/redux/initialState.ts | adamwong246/SpaceTrash | 79cd10113c9cab71781d0be2a02bd63cec19b73f | [
"MIT"
] | null | null | null | import * as React from "react";
export default {
loadState: {},
commandQueues: {},
terminalLines: [
"booting spaceTrash session terminal",
],
clock: {
time: Date.now(),
lastTime: 0,
halted: false,
},
userGeneratedView: null,
usr: {},
userScripts: null,
userFiles: [],
openFileContents: "Hello initial state"
};
| 14.2 | 42 | 0.616901 |
29af3aa1b29c0f0324da8ab7510baf10e26cac9d | 50 | sql | SQL | SQLoginStatements/updatePersonnelnickName.sql | Damian2057/BookSystem | 5507c1a0b1ab318f1be1b74c0fba0f545fc64ffc | [
"BSD-2-Clause"
] | 1 | 2022-02-08T21:11:45.000Z | 2022-02-08T21:11:45.000Z | SQLoginStatements/updatePersonnelnickName.sql | Damian2057/BookSystem | 5507c1a0b1ab318f1be1b74c0fba0f545fc64ffc | [
"BSD-2-Clause"
] | null | null | null | SQLoginStatements/updatePersonnelnickName.sql | Damian2057/BookSystem | 5507c1a0b1ab318f1be1b74c0fba0f545fc64ffc | [
"BSD-2-Clause"
] | null | null | null | update Personnel set nickName = (?) where id = (?) | 50 | 50 | 0.66 |
02caa5f3c7d730e77ef9a47742232d53e52cf02f | 1,041 | cpp | C++ | UVA/DP/uva_10819_knapsack.cpp | raphasramos/competitive-programming | 749b6726bd9d517d9143af7e9236d3e5e8cef49b | [
"MIT"
] | 3 | 2020-05-15T17:15:10.000Z | 2021-04-24T17:54:26.000Z | UVA/DP/uva_10819_knapsack.cpp | raphasramos/competitive-programming | 749b6726bd9d517d9143af7e9236d3e5e8cef49b | [
"MIT"
] | null | null | null | UVA/DP/uva_10819_knapsack.cpp | raphasramos/competitive-programming | 749b6726bd9d517d9143af7e9236d3e5e8cef49b | [
"MIT"
] | 1 | 2019-06-24T18:41:49.000Z | 2019-06-24T18:41:49.000Z | #include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define ll long long
#define pq priority_queue
#define mii map<int,int>
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef set<int> si;
typedef vector<vi> vii;
typedef vector<ii> vpi;
typedef vector<ll> vll;
int oo = (1e9) + 7;
int tb[10205][105];
int m, n;
int tmp;
vi p, f;
int dp(int money, int i) {
if(money > tmp and money <= 2000 and i == n) return -oo;
if(i == n or money == m) return 0;
if(tb[money][i] != -1) return tb[money][i];
int ans = dp(money, i+1);
if(money + p[i] <= m) ans = max(ans, dp(money + p[i], i+1) + f[i]);
tb[money][i] = ans;
return ans;
}
int main() {
while(scanf("%d %d", &m, &n) != EOF) {
p.assign(n+5, 0);
f.assign(n+5, 0);
for(int i = 0; i < n; i++)
{
scanf("%d %d", &p[i], &f[i]);
}
memset(tb, -1, sizeof tb);
tmp = m;
if(m + 200 > 2000) m += 200;
printf("%d\n", dp(0, 0));
}
}
| 20.82 | 71 | 0.513929 |
d00b9d8d7344ff904c32a720495edaf7a4c57d70 | 20,026 | cpp | C++ | Platformer 2D/Motor2D/j1Player.cpp | Scarzard/Game_Development_HO | fe3441c23df03c15120d159671f0cd41d7b8c370 | [
"MIT"
] | null | null | null | Platformer 2D/Motor2D/j1Player.cpp | Scarzard/Game_Development_HO | fe3441c23df03c15120d159671f0cd41d7b8c370 | [
"MIT"
] | null | null | null | Platformer 2D/Motor2D/j1Player.cpp | Scarzard/Game_Development_HO | fe3441c23df03c15120d159671f0cd41d7b8c370 | [
"MIT"
] | 1 | 2018-11-18T21:30:45.000Z | 2018-11-18T21:30:45.000Z | #include "p2Log.h"
#include "j1Player.h"
#include "j1App.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Textures.h"
#include "j1Map.h"
#include "p2Log.h"
#include <string>
#include "j1Input.h"
#include "j1Collision.h"
#include "j1Scene.h"
#include "Brofiler/Brofiler.h"
#include <math.h>
j1Player::j1Player()
{
name.create("player");
}
j1Player::~j1Player()
{
}
bool j1Player::Awake(pugi::xml_node &config)
{
player1 = new Player;
player1->alive = config.child("alive").attribute("value").as_bool();
player1->position.x = config.child("position").attribute("x").as_int();
player1->position.y = config.child("position").attribute("y").as_int();
player1->camera1.x = config.child("cameraStartPos1").attribute("x").as_int();
player1->camera1.y = config.child("cameraStartPos1").attribute("y").as_int();
player1->camera2.x = config.child("cameraStartPos2").attribute("x").as_int();
player1->camera2.y = config.child("cameraStartPos2").attribute("y").as_int();
player1->playerSpeed = config.child("playerSpeed").attribute("value").as_int();
player1->jumpStrength = config.child("jumpStrength").attribute("value").as_int();
player1->gravity = config.child("gravity").attribute("value").as_int();
return true;
}
bool j1Player::Start()
{
player1->playerTexture = App->tex->Load("textures/main_character.png");
player1->godmodeTexture = App->tex->Load("textures/main_character_godmode.png");
App->render->camera.x = player1->camera1.x;
App->render->camera.y = player1->camera1.y;
pugi::xml_parse_result result = storedAnims.load_file("textures/animations.tmx");
if (result == NULL)
LOG("Couldn't load player animations! Error:", result.description());
else
{
LoadAnimations();
}
player1->playerCollider = App->collision->FindPlayer();
player1->playerNextFrameCol = App->collision->AddCollider({ player1->playerCollider->rect.x, player1->playerCollider->rect.y,
player1->playerCollider->rect.w, player1->playerCollider->rect.h }, COLLIDER_PLAYERFUTURE, this);
player1->currentAnimation = &player1->idle;
player1->jumpsLeft = 2;
return true;
}
bool j1Player::PreUpdate()
{
BROFILER_CATEGORY("Player_PreUpdate", Profiler::Color::Aquamarine)
if (player1->alive == true) {
SetSpeed();
player1->normalizedSpeed.x = player1->speed.x * player1->dtPlayer;
player1->normalizedSpeed.y = player1->speed.y * player1->dtPlayer;
player1->playerNextFrameCol->SetPos(player1->playerCollider->rect.x + player1->speed.x, player1->playerCollider->rect.y + player1->speed.y);
if (player1->jumping == false)
player1->jumpsLeft = 2;
}
return true;
}
bool j1Player::Update(float dt)
{
BROFILER_CATEGORY("Player_Update", Profiler::Color::Orchid)
dt = player1->dtPlayer;
//Player controls
if (player1->alive == true)
{
if (player1->godmode)
player1->jumpsLeft = 2;
if (App->render->camera.x > 4500)App->render->camera.x = 4000;
if (App->render->camera.x < 0)App->render->camera.x = 0;
//Check Horizontal Movement
//Right
if (App->input->GetKey(SDL_SCANCODE_D) == KEY_DOWN)
player1->facingLeft = false;
//Left
else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
player1->facingLeft = true;
//---------------------------
//Prevent animations from glitching
if (player1->speed.x > 0)
player1->facingLeft = false;
if (player1->speed.x < 0)
player1->facingLeft = true;
//---------------------------------
//Check Jump ----------------------
if (App->input->GetKey(SDL_SCANCODE_J) == KEY_DOWN && player1->jumpsLeft != 0)
{
player1->jumpsLeft--;
player1->jumping = true;
}
if (player1->jumpsLeft == 2 && player1->speed.y > 0)
player1->jumpsLeft--;
//---------------------------------
//Check godmode debug -------------
if (App->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN)
player1->godmode = !player1->godmode;
// Set the correct animation for current movement
SetAnimations();
// Move player as of its current speed
Move();
// Update present collider
player1->playerCollider->SetPos(player1->position.x + player1->colliderOffset.x, player1->position.y + player1->colliderOffset.y);
// Blit player
if (player1->facingLeft)
{
if (!player1->godmode)
App->render->Blit(player1->playerTexture, player1->position.x, player1->position.y, &player1->currentAnimation->GetCurrentFrame(), SDL_FLIP_NONE);
else if (player1->godmode)
App->render->Blit(player1->godmodeTexture, player1->position.x, player1->position.y, &player1->currentAnimation->GetCurrentFrame(), SDL_FLIP_NONE);
}
else if (!player1->facingLeft)
{
if (!player1->godmode)
App->render->Blit(player1->playerTexture, player1->position.x, player1->position.y, &player1->currentAnimation->GetCurrentFrame(), SDL_FLIP_HORIZONTAL);
else if (player1->godmode)
App->render->Blit(player1->godmodeTexture, player1->position.x, player1->position.y, &player1->currentAnimation->GetCurrentFrame(), SDL_FLIP_HORIZONTAL);
}
CenterCameraOnPlayer();
}
else if (!player1->alive)
{
Respawn();
}
if (player1->changingLevel)
RespawnInNewLevel();
return true;
}
bool j1Player::PostUpdate()
{
BROFILER_CATEGORY("Player_PostUpdate", Profiler::Color::Crimson)
p2List_item<ImageLayer*>* img = nullptr;
for (img = App->map->data.image.start; img; img = img->next)
{
if (img->data->speed > 0)
{
if (player1->parallaxToLeft = true)
{
img->data->position.x += player1->speed.x / img->data->speed;
}
else if (player1->parallaxToRight = true)
{
img->data->position.x -= player1->speed.x / img->data->speed;
}
}
}
return true;
}
bool j1Player::CleanUp()
{
App->tex->UnLoad(player1->playerTexture);
App->tex->UnLoad(player1->godmodeTexture);
player1->currentAnimation = nullptr;
delete player1;
return true;
}
void j1Player::LoadAnimations()
{
std::string tmp;
// Loop all different animations (each one is an object layer in the tmx)
for (animFinder = storedAnims.child("map").child("objectgroup"); animFinder; animFinder = animFinder.next_sibling())
{
tmp = animFinder.child("properties").first_child().attribute("value").as_string();
// Load idle
if (tmp == "idle")
{
// Loop all frames and push them into animation
for (pugi::xml_node frameIterator = animFinder.child("object"); frameIterator; frameIterator = frameIterator.next_sibling())
{
SDL_Rect frameToPush = { frameIterator.attribute("x").as_int(), frameIterator.attribute("y").as_int(), frameIterator.attribute("width").as_int(), frameIterator.attribute("height").as_int() };
player1->idle.PushBack(frameToPush);
}
for (pugi::xml_node propertyIterator = animFinder.child("properties").first_child(); propertyIterator; propertyIterator = propertyIterator.next_sibling())
{
std::string checkName = propertyIterator.attribute("name").as_string();
if (checkName == "loop")
player1->idle.loop = propertyIterator.attribute("value").as_bool();
else if (checkName == "speed")
player1->idle.speed = propertyIterator.attribute("value").as_float();
}
}
// Load run
if (tmp == "run")
{
// Loop all frames and push them into animation
for (pugi::xml_node frameIterator = animFinder.child("object"); frameIterator; frameIterator = frameIterator.next_sibling())
{
SDL_Rect frameToPush = { frameIterator.attribute("x").as_int(), frameIterator.attribute("y").as_int(), frameIterator.attribute("width").as_int(), frameIterator.attribute("height").as_int() };
player1->run.PushBack(frameToPush);
}
for (pugi::xml_node propertyIterator = animFinder.child("properties").first_child(); propertyIterator; propertyIterator = propertyIterator.next_sibling())
{
std::string checkName = propertyIterator.attribute("name").as_string();
if (checkName == "loop")
player1->run.loop = propertyIterator.attribute("value").as_bool();
else if (checkName == "speed")
player1->run.speed = propertyIterator.attribute("value").as_float();
}
}
// Load jump
if (tmp == "jump")
{
// Loop all frames and push them into animation
for (pugi::xml_node frameIterator = animFinder.child("object"); frameIterator; frameIterator = frameIterator.next_sibling())
{
SDL_Rect frameToPush = { frameIterator.attribute("x").as_int(), frameIterator.attribute("y").as_int(), frameIterator.attribute("width").as_int(), frameIterator.attribute("height").as_int() };
player1->jump.PushBack(frameToPush);
}
for (pugi::xml_node propertyIterator = animFinder.child("properties").first_child(); propertyIterator; propertyIterator = propertyIterator.next_sibling())
{
std::string checkName = propertyIterator.attribute("name").as_string();
if (checkName == "loop")
player1->jump.loop = propertyIterator.attribute("value").as_bool();
else if (checkName == "speed")
player1->jump.speed = propertyIterator.attribute("value").as_float();
}
}
// Load fall
if (tmp == "fall")
{
// Loop all frames and push them into animation
for (pugi::xml_node frameIterator = animFinder.child("object"); frameIterator; frameIterator = frameIterator.next_sibling())
{
SDL_Rect frameToPush = { frameIterator.attribute("x").as_int(), frameIterator.attribute("y").as_int(), frameIterator.attribute("width").as_int(), frameIterator.attribute("height").as_int() };
player1->fall.PushBack(frameToPush);
}
for (pugi::xml_node propertyIterator = animFinder.child("properties").first_child(); propertyIterator; propertyIterator = propertyIterator.next_sibling())
{
std::string checkName = propertyIterator.attribute("name").as_string();
if (checkName == "loop")
player1->fall.loop = propertyIterator.attribute("value").as_bool();
else if (checkName == "speed")
player1->fall.speed = propertyIterator.attribute("value").as_float();
}
}
}
}
void j1Player::ApplyGravity()
{
if (player1->speed.y < 9)
player1->speed.y += player1->gravity;
else if (player1->speed.y > 9)
player1->speed.y = player1->gravity;
}
void j1Player::Respawn()
{
player1->speed.SetToZero();
player1->position.x = App->map->data.startingPointX;
player1->position.y = App->map->data.startingPointY;
App->render->cameraRestart = true;
ResetParallax();
player1->alive = true;
}
void j1Player::RespawnInNewLevel()
{
player1->speed.SetToZero();
player1->position.x = App->map->data.startingPointX;
player1->position.y = App->map->data.startingPointY;
player1->playerCollider = nullptr;
player1->playerNextFrameCol = nullptr;
player1->playerCollider = App->collision->FindPlayer();
player1->playerNextFrameCol = App->collision->AddCollider({ player1->playerCollider->rect.x, player1->playerCollider->rect.y,
player1->playerCollider->rect.w, player1->playerCollider->rect.h }, COLLIDER_PLAYERFUTURE, this);
App->render->cameraRestart = true;
ResetParallax();
player1->changingLevel = false;
}
void j1Player::SetAnimations()
{
// Reset to idle if no input is received
player1->currentAnimation = &player1->idle;
// Run if moving on the x axis
if (player1->speed.x != 0)
player1->currentAnimation = &player1->run;
// Idle if A and D are pressed simultaneously
if (player1->speed.x == 0)
player1->currentAnimation = &player1->idle;
// Set jumping animations
if (App->input->GetKey(SDL_SCANCODE_J) == KEY_DOWN)
player1->jump.Reset();
if (player1->jumping)
{
if (player1->speed.y > 0)
player1->currentAnimation = &player1->fall;
else if (player1->speed.y < 0)
player1->currentAnimation = &player1->jump;
}
}
void j1Player::SetSpeed()
{
// Apply gravity in each frame
ApplyGravity();
// Check for horizontal movement
if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_A) != KEY_REPEAT)
player1->speed.x = player1->playerSpeed;
else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_D) != KEY_REPEAT)
player1->speed.x = -player1->playerSpeed;
else
player1->speed.x = 0;
// Check for jumps
if (App->input->GetKey(SDL_SCANCODE_J) == KEY_DOWN && player1->jumpsLeft > 0)
player1->speed.y = -player1->jumpStrength;
}
void j1Player::Move()
{
player1->position.x += player1->speed.x;
player1->position.y += player1->speed.y;
}
void j1Player::ResetParallax()
{
p2List_item<ImageLayer*>* img = nullptr;
if (!player1->alive)
{
for (img = App->map->data.image.start; img; img = img->next)
{
img->data->position.x = 0;
}
}
}
void j1Player::OnCollision(Collider* collider1, Collider* collider2)
{
// COLLISIONS ------------------------------------------------------------------------------------ //
if (collider1->type == COLLIDER_PLAYERFUTURE && collider2->type == COLLIDER_SOLID_FLOOR)
{
SDL_Rect intersectCol;
if (SDL_IntersectRect(&collider1->rect, &collider2->rect, &intersectCol));
//future player collider and a certain wall collider have collided
{
if (player1->speed.y > 0) // If player is falling
{
if (collider1->rect.y < collider2->rect.y) // Checking if player is colliding from above
{
if (player1->speed.x == 0)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else if (player1->speed.x < 0)
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x <= collider2->rect.x + collider2->rect.w)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else
player1->speed.x += intersectCol.w;
}
else
player1->speed.y -= intersectCol.h, player1->jumping = false;
else if (player1->speed.x > 0)
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x + collider1->rect.w <= collider2->rect.x)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else
player1->speed.x -= intersectCol.w;
}
else
player1->speed.y -= intersectCol.h, player1->jumping = false;
}
else
{
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
else if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
}
}
else if (player1->speed.y == 0) // If player is not moving vertically
{
if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
}
else if (player1->speed.y < 0) // If player is moving up
{
if (collider1->rect.y + collider1->rect.h > collider2->rect.y + collider2->rect.h) // Checking if player is colliding from below
{
if (player1->speed.x == 0)
player1->speed.y += intersectCol.h;
else if (player1->speed.x < 0)
{
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x <= collider2->rect.x + collider2->rect.w)
player1->speed.y += intersectCol.h;
else
player1->speed.x += intersectCol.w;
}
else
player1->speed.y += intersectCol.h;
}
else if (player1->speed.x > 0)
{
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x + collider1->rect.w >= collider2->rect.x)
player1->speed.y += intersectCol.h;
else
player1->speed.x -= intersectCol.w;
}
else
player1->speed.y += intersectCol.h;
}
}
else
{
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
else if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
}
}
}
}
// COLLISIONS ------------------------------------------------------------------------------------ //
else if (collider1->type == COLLIDER_PLAYERFUTURE && collider2->type == COLLIDER_DEATH)
{
if (!player1->godmode)
player1->alive = false;
else if (player1->godmode)
{
SDL_Rect intersectCol;
if (SDL_IntersectRect(&collider1->rect, &collider2->rect, &intersectCol));
//future player collider and a certain wall collider have collided
{
if (player1->speed.y > 0) // If player is falling
{
if (collider1->rect.y < collider2->rect.y) // Checking if player is colliding from above
{
if (player1->speed.x == 0)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else if (player1->speed.x < 0)
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x <= collider2->rect.x + collider2->rect.w)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else
player1->speed.x += intersectCol.w;
}
else
player1->speed.y -= intersectCol.h, player1->jumping = false;
else if (player1->speed.x > 0)
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x + collider1->rect.w <= collider2->rect.x)
player1->speed.y -= intersectCol.h, player1->jumping = false;
else
player1->speed.x -= intersectCol.w;
}
else
player1->speed.y -= intersectCol.h, player1->jumping = false;
}
else
{
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
else if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
}
}
else if (player1->speed.y == 0) // If player is not moving vertically
{
if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
}
else if (player1->speed.y < 0) // If player is moving up
{
if (collider1->rect.y + collider1->rect.h > collider2->rect.y + collider2->rect.h) // Checking if player is colliding from below
{
if (player1->speed.x == 0)
player1->speed.y += intersectCol.h;
else if (player1->speed.x < 0)
{
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x <= collider2->rect.x + collider2->rect.w)
player1->speed.y += intersectCol.h;
else
player1->speed.x += intersectCol.w;
}
else
player1->speed.y += intersectCol.h;
}
else if (player1->speed.x > 0)
{
if (intersectCol.h >= intersectCol.w)
{
if (collider1->rect.x + collider1->rect.w >= collider2->rect.x)
player1->speed.y += intersectCol.h;
else
player1->speed.x -= intersectCol.w;
}
else
player1->speed.y += intersectCol.h;
}
}
else
{
if (player1->speed.x < 0)
player1->speed.x += intersectCol.w;
else if (player1->speed.x > 0)
player1->speed.x -= intersectCol.w;
}
}
}
}
}
else if (collider1->type == COLLIDER_PLAYERFUTURE && collider2->type == COLLIDER_LEVELEND)
{
App->player->player1->changingLevel = true;
if (App->scene->currentLevel == 1)
App->scene->LoadLevel(2), App->scene->currentLevel = 2;
else if (App->scene->currentLevel == 2)
App->scene->LoadLevel(1), App->scene->currentLevel = 1;
}
}
bool j1Player::CenterCameraOnPlayer()
{
uint w, h;
App->win->GetWindowSize(w, h);
if (player1->position.x > App->render->camera.x + w)
{
App->render->camera.x -= player1->speed.x * 2;
player1->parallaxToRight = true;
}
else if (player1->position.x < App->render->camera.x + w)
{
App->render->camera.x += player1->speed.x * 2;
player1->parallaxToLeft = true;
}
if (player1->position.y > App->render->camera.y + h) { App->render->camera.y -= player1->speed.y * 2; }
else if (player1->position.y < App->render->camera.y + h) { App->render->camera.y += player1->speed.y * 2; }
return true;
}
bool j1Player::Load(pugi::xml_node &node)
{
player1->position.x = node.child("position").attribute("x").as_int();
player1->position.y = node.child("position").attribute("y").as_int();
return true;
}
bool j1Player::Save(pugi::xml_node &node) const
{
pugi::xml_node position = node.append_child("position");
position.append_attribute("x") = player1->position.x;
position.append_attribute("y") = player1->position.y;
return true;
} | 28.897547 | 195 | 0.647159 |
c686f85d0964dfe80dced26956a649efb6fc6992 | 782 | py | Python | new/servo_test.py | Deepakbaskar94/Autonomous_car_base_program | 9ab79aacccabb4720f9eb419838497c565d01665 | [
"Apache-2.0"
] | null | null | null | new/servo_test.py | Deepakbaskar94/Autonomous_car_base_program | 9ab79aacccabb4720f9eb419838497c565d01665 | [
"Apache-2.0"
] | null | null | null | new/servo_test.py | Deepakbaskar94/Autonomous_car_base_program | 9ab79aacccabb4720f9eb419838497c565d01665 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
"""
servo_test.py
www.bluetin.io
16/01/2018
"""
__author__ = "Mark Heywood"
__version__ = "0.01"
__license__ = "MIT"
from gpiozero import Servo
from time import sleep
# Adjust the pulse values to set rotation range
min_pulse = 0.000544 # Library default = 1/1000
max_pulse = 0.0024 # Library default = 2/1000
# Initial servo position
pos = 0
test = 0
tet = 0
servo = Servo(23, pos, min_pulse, max_pulse, 20/1000, None)
while True:
tet = input()
test = int(tet)
while test < 20:
pos = test * 0.1 - 1
servo.value = pos
print(pos)
test = test + 1
sleep(0.05)
while test > 0:
pos = test * 0.1 - 1
servo.value = pos
print(pos)
test = test - 1
sleep(0.05)
| 17.772727 | 59 | 0.594629 |
464ee3c3704beb69accfa258b5f733c9a15ab965 | 435 | php | PHP | app/Http/Resources/System/HostnameResource.php | gohunter/devfacturapro | 225990f5bbc3d382eedcc80412aa2f2fe279780f | [
"MIT"
] | 2 | 2021-11-21T17:34:36.000Z | 2021-12-21T05:53:39.000Z | app/Http/Resources/System/HostnameResource.php | gohunter/devfacturapro | 225990f5bbc3d382eedcc80412aa2f2fe279780f | [
"MIT"
] | 1 | 2021-12-17T03:19:43.000Z | 2021-12-17T03:19:43.000Z | app/Http/Resources/System/HostnameResource.php | gohunter/devfacturapro | 225990f5bbc3d382eedcc80412aa2f2fe279780f | [
"MIT"
] | 6 | 2021-04-10T03:13:16.000Z | 2021-07-08T03:45:29.000Z | <?php
namespace App\Http\Resources\System;
use Illuminate\Http\Resources\Json\JsonResource;
class HostnameResource extends JsonResource
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function toArray($request)
{
return [
'id' => $this->id,
'fqdn' => $this->fqdn
];
}
} | 19.772727 | 55 | 0.586207 |
cccdd3edd70a1fd07eca22bcea3fb0abc99781a6 | 91 | swift | Swift | Sources/xcbeautify/setup.swift | chriszielinski/xcbeautify | f7dfcdba7506284981db05aa68610fe0fdcaac8f | [
"MIT"
] | null | null | null | Sources/xcbeautify/setup.swift | chriszielinski/xcbeautify | f7dfcdba7506284981db05aa68610fe0fdcaac8f | [
"MIT"
] | null | null | null | Sources/xcbeautify/setup.swift | chriszielinski/xcbeautify | f7dfcdba7506284981db05aa68610fe0fdcaac8f | [
"MIT"
] | null | null | null | import Guaka
func setupCommands() {
GuakaConfig.helpGenerator = XcbeautifyHelp.self
}
| 15.166667 | 51 | 0.769231 |
d1cefbb7bc025967eb3be6d54e25f84c3ca3142c | 76 | sql | SQL | aws-test/tests/aws_cloudfront_origin_request_policy/test-notfound-query.sql | blinkops/blink-aws-query | 21b0d5eee6b0b5554c040867b9e25681e7ba6559 | [
"Apache-2.0"
] | 61 | 2021-01-21T19:06:48.000Z | 2022-03-28T20:09:46.000Z | aws-test/tests/aws_cloudfront_origin_request_policy/test-notfound-query.sql | blinkops/blink-aws-query | 21b0d5eee6b0b5554c040867b9e25681e7ba6559 | [
"Apache-2.0"
] | 592 | 2021-01-23T05:27:12.000Z | 2022-03-31T14:16:19.000Z | aws-test/tests/aws_cloudfront_origin_request_policy/test-notfound-query.sql | blinkops/blink-aws-query | 21b0d5eee6b0b5554c040867b9e25681e7ba6559 | [
"Apache-2.0"
] | 30 | 2021-01-21T18:43:25.000Z | 2022-03-12T15:14:05.000Z | select *
from aws_cloudfront_origin_request_policy
where id = 'azlkokdp12w'; | 25.333333 | 41 | 0.842105 |
c65d268e17ddada13f57df3482c5e152addc4044 | 676 | py | Python | localization/scripts/sort_loc.py | Ubastic/SlayTheSpire_Modify | 0ed92839fff2b35fc602cb879c32aeb0af322cab | [
"Apache-2.0"
] | null | null | null | localization/scripts/sort_loc.py | Ubastic/SlayTheSpire_Modify | 0ed92839fff2b35fc602cb879c32aeb0af322cab | [
"Apache-2.0"
] | 2 | 2021-12-14T20:46:50.000Z | 2021-12-14T21:40:10.000Z | localization/scripts/sort_loc.py | Ubastic/SlayTheSpire_Modify | 0ed92839fff2b35fc602cb879c32aeb0af322cab | [
"Apache-2.0"
] | null | null | null | import json
import sys
import io
from util import read_json, flatten, get_json_files, get_loc_dirs
if sys.version_info.major < 3:
raise Exception("must use python 3")
def write_json(filename, data): # TODO: replace with util.write_json once sorting loc files is common.
with io.open(filename, 'w', encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False, sort_keys=True)
def main():
lang_packs = [x for x in get_loc_dirs()]
json_files = flatten(map(get_json_files, lang_packs))
for filepath in json_files:
contents = read_json(filepath)
write_json(filepath, contents)
if __name__ == "__main__":
main()
| 25.037037 | 103 | 0.702663 |
27dd78534660337a301edbd9d64e1f2e099dfe47 | 214 | dart | Dart | null_safety/lib/LateConcept.dart | kaleliguray/Flutter | 61c7948ce1df547cc096b09aabfba8afc8e98809 | [
"MIT"
] | null | null | null | null_safety/lib/LateConcept.dart | kaleliguray/Flutter | 61c7948ce1df547cc096b09aabfba8afc8e98809 | [
"MIT"
] | null | null | null | null_safety/lib/LateConcept.dart | kaleliguray/Flutter | 61c7948ce1df547cc096b09aabfba8afc8e98809 | [
"MIT"
] | null | null | null | class LateConcept{
// we can not use variable like this due to "null safety"
//int x;
late int x; // with late, we tell that we will assing a variable later
int y = 10; // or we can use without "late"
} | 21.4 | 72 | 0.658879 |
aa55cb5c923de708ca20f883425e603f80d7ab0b | 1,245 | swift | Swift | Appt/Helpers/ViewEmbedder.swift | appt-nl/appt-ios | 1ed33c3390b682ad97b9d238727d1a4852e9e4d8 | [
"MIT"
] | null | null | null | Appt/Helpers/ViewEmbedder.swift | appt-nl/appt-ios | 1ed33c3390b682ad97b9d238727d1a4852e9e4d8 | [
"MIT"
] | null | null | null | Appt/Helpers/ViewEmbedder.swift | appt-nl/appt-ios | 1ed33c3390b682ad97b9d238727d1a4852e9e4d8 | [
"MIT"
] | null | null | null | //
// ViewEmbedder.swift
// Appt
//
// Created by Yurii Kozlov on 5/14/21.
// Copyright ยฉ 2021 Stichting Appt. All rights reserved.
//
import UIKit
final class ViewEmbedder {
class func embed(parent: UIViewController, container: UIView, child: UIViewController, previous: UIViewController?) {
if let previous = previous {
removeFromParent(vc: previous)
}
child.willMove(toParent: parent)
parent.addChild(child)
container.addSubview(child.view)
child.didMove(toParent: parent)
let width = container.frame.size.width
let height = container.frame.size.height
child.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
}
class func removeFromParent(vc: UIViewController) {
vc.willMove(toParent: nil)
vc.view.removeFromSuperview()
vc.removeFromParent()
}
class func embed(withIdentifier id: String, parent: UIViewController, container: UIView, completion:((UIViewController) -> Void)? = nil) {
let vc = parent.storyboard!.instantiateViewController(withIdentifier: id)
embed(parent: parent, container: container, child: vc, previous: parent.children.first)
completion?(vc)
}
}
| 32.763158 | 142 | 0.669076 |
4355d9355bfebc05d2f42b2024b3c0af6603cd8e | 1,371 | ts | TypeScript | src/constants/strings.ts | aghasemi/woertchen | 0fac35e1e2b9a4b95781bf0882722ca682356f4a | [
"MIT"
] | null | null | null | src/constants/strings.ts | aghasemi/woertchen | 0fac35e1e2b9a4b95781bf0882722ca682356f4a | [
"MIT"
] | null | null | null | src/constants/strings.ts | aghasemi/woertchen | 0fac35e1e2b9a4b95781bf0882722ca682356f4a | [
"MIT"
] | null | null | null | export const GAME_TITLE = 'Schweizerdeutsch Wordle'
export const GAME_URL = 'https://sgwordle.now.sh'
export const WIN_MESSAGES = [
'Gut gemacht!',
'Super!',
'Geiles Gehirn, Gรผnter!',
'Mega',
'Stark',
'Voll gut ey',
'Du scheinst kluk zu sein',
'Weiter so',
'Toll!',
'Darauf eine Scheibe Vollkornbrot!',
'So muss die Baklava schmecken',
'Stabile Leistung',
]
export const GAME_COPIED_MESSAGE = 'Spielverlauf kopiert'
export const ABOUT_GAME_MESSAGE = 'รber Schweizerdeutsch Wordle'
export const NOT_ENOUGH_LETTERS_MESSAGE = 'Nicht genug Buchstaben'
export const WORD_NOT_FOUND_MESSAGE = 'Wort nicht gefunden. Siehe <a href="https://raw.githubusercontent.com/aghasemi/swissgermanwords/master/sg-words.csv" className="underline font-bold">hier</a> fรผr einige Beispiele'
export const CORRECT_WORD_MESSAGE = (solution: string) =>
`Das gesuchte Wort war ${solution}`
export const ENTER_TEXT = 'Eingabe'
export const DELETE_TEXT = 'Lรถschen'
export const STATISTICS_TITLE = 'Statistik'
export const GUESS_DISTRIBUTION_TEXT = 'Versuchsverteilung'
export const NEW_WORD_TEXT = 'Neues Wort in'
export const SHARE_TEXT = 'Spielverlauf kopieren'
export const TOTAL_TRIES_TEXT = 'Spiele gesamt'
export const SUCCESS_RATE_TEXT = 'Spiele gewonnen'
export const CURRENT_STREAK_TEXT = 'Aktuelle Gewinnserie'
export const BEST_STREAK_TEXT = 'Lรคngste Gewinnserie'
| 40.323529 | 218 | 0.773158 |
1ac898b1a051a8a96dda8efd1fdbb90bd45e58d1 | 364 | py | Python | py_tdlib/constructors/input_inline_query_result_contact.py | Mr-TelegramBot/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 24 | 2018-10-05T13:04:30.000Z | 2020-05-12T08:45:34.000Z | py_tdlib/constructors/input_inline_query_result_contact.py | MrMahdi313/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 3 | 2019-06-26T07:20:20.000Z | 2021-05-24T13:06:56.000Z | py_tdlib/constructors/input_inline_query_result_contact.py | MrMahdi313/python-tdlib | 2e2d21a742ebcd439971a32357f2d0abd0ce61eb | [
"MIT"
] | 5 | 2018-10-05T14:29:28.000Z | 2020-08-11T15:04:10.000Z | from ..factory import Type
class inputInlineQueryResultContact(Type):
id = None # type: "string"
contact = None # type: "contact"
thumbnail_url = None # type: "string"
thumbnail_width = None # type: "int32"
thumbnail_height = None # type: "int32"
reply_markup = None # type: "ReplyMarkup"
input_message_content = None # type: "InputMessageContent"
| 30.333333 | 60 | 0.714286 |
28175147a3970d2a7e54e5f420a7f6788f501df3 | 1,695 | ps1 | PowerShell | Active-Directory/AD-generate-OID.ps1 | badgumby/powershell-scripts | 24cc5f15543c99e915fe61d03574db31e58aac35 | [
"MIT"
] | null | null | null | Active-Directory/AD-generate-OID.ps1 | badgumby/powershell-scripts | 24cc5f15543c99e915fe61d03574db31e58aac35 | [
"MIT"
] | null | null | null | Active-Directory/AD-generate-OID.ps1 | badgumby/powershell-scripts | 24cc5f15543c99e915fe61d03574db31e58aac35 | [
"MIT"
] | null | null | null | #------------------------------------------------------------------------------------------
# You can create subsequent OIDs for new schema classes and attributes by appending a .X to the OID where X may be any number that you choose.
# A common schema extension scheme generally uses the following structure:
# If your assigned OID was: 1.2.840.113556.1.8000.2554.999999
# then classes could be under: 1.2.840.113556.1.8000.2554.999999.1
# which makes the first class OID: 1.2.840.113556.1.8000.2554.999999.1.1
# the second class OID: 1.2.840.113556.1.8000.2554.999999.1.2 etc...
# Using this example attributes could be under: 1.2.840.113556.1.8000.2554.999999.2
# which makes the first attribute OID: 1.2.840.113556.1.8000.2554.999999.2.1
# the second attribute OID: 1.2.840.113556.1.8000.2554.999999.2.2 etc...
#------------------------------------------------------------------------------------------
$Prefix="1.2.840.113556.1.8000.2554"
$GUID=[System.Guid]::NewGuid().ToString()
$Parts=@()
$Parts+=[UInt64]::Parse($guid.SubString(0,4),"AllowHexSpecifier")
$Parts+=[UInt64]::Parse($guid.SubString(4,4),"AllowHexSpecifier")
$Parts+=[UInt64]::Parse($guid.SubString(9,4),"AllowHexSpecifier")
$Parts+=[UInt64]::Parse($guid.SubString(14,4),"AllowHexSpecifier")
$Parts+=[UInt64]::Parse($guid.SubString(19,4),"AllowHexSpecifier")
$Parts+=[UInt64]::Parse($guid.SubString(24,6),"AllowHexSpecifier")
$Parts+=[UInt64]::Parse($guid.SubString(30,6),"AllowHexSpecifier")
$OID=[String]::Format("{0}.{1}.{2}.{3}.{4}.{5}.{6}.{7}",$prefix,$Parts[0],$Parts[1],$Parts[2],$Parts[3],$Parts[4],$Parts[5],$Parts[6])
$oid
#------------------------------------------------------------------------------------------
| 67.8 | 142 | 0.60236 |
1a2f8873b884c3ec3c3e0535fbe94b19ca1bf26e | 4,198 | py | Python | flicks/videos/tests/test_forms.py | Mozilla-GitHub-Standards/6f0d85288b5b0ef8beecb60345173dc14c98e40f48e1307a444ab1e08231e695 | bf6a382913901ad193d907f022086931df0de8c4 | [
"BSD-3-Clause"
] | 1 | 2016-04-15T11:43:02.000Z | 2016-04-15T11:43:02.000Z | flicks/videos/tests/test_forms.py | Mozilla-GitHub-Standards/6f0d85288b5b0ef8beecb60345173dc14c98e40f48e1307a444ab1e08231e695 | bf6a382913901ad193d907f022086931df0de8c4 | [
"BSD-3-Clause"
] | 2 | 2015-03-03T23:02:19.000Z | 2019-03-30T04:45:51.000Z | flicks/videos/tests/test_forms.py | Mozilla-GitHub-Standards/6f0d85288b5b0ef8beecb60345173dc14c98e40f48e1307a444ab1e08231e695 | bf6a382913901ad193d907f022086931df0de8c4 | [
"BSD-3-Clause"
] | 2 | 2016-04-15T11:43:05.000Z | 2016-04-15T11:43:15.000Z | from django.core.exceptions import ValidationError
from django.test.client import RequestFactory
from mock import patch
from nose.tools import assert_raises, eq_, ok_
from waffle import Flag
from flicks.base.regions import NORTH_AMERICA
from flicks.base.tests import TestCase
from flicks.videos.forms import VideoSearchForm
from flicks.videos.search import AUTOCOMPLETE_FIELDS
class VideoSearchFormTests(TestCase):
def setUp(self):
super(VideoSearchFormTests, self).setUp()
self.factory = RequestFactory()
self.request = self.factory.get('/')
def test_popular_sort_include(self):
"""If the voting-end waffle flag is not set, include the popular option for sorting."""
Flag.objects.create(name='voting-end', everyone=False)
form = VideoSearchForm(self.request)
ok_('popular' in [c[0] for c in form.fields['sort'].choices])
def test_popular_sort_exclude(self):
"""If the voting-end waffle flag is set, do not include the popular option for sorting."""
Flag.objects.create(name='voting-end', everyone=True)
form = VideoSearchForm(self.request)
ok_('popular' not in [c[0] for c in form.fields['sort'].choices])
@patch('flicks.videos.forms.search_videos')
def test_valid_search(self, search_videos):
form = VideoSearchForm(self.request, {
'query': 'asdf',
'field': 'title',
'region': NORTH_AMERICA,
'sort': 'popular'
})
eq_(form.perform_search(), search_videos.return_value)
search_videos.assert_called_with(
query='asdf',
fields=AUTOCOMPLETE_FIELDS['title'],
region=NORTH_AMERICA,
sort='popular'
)
@patch('flicks.videos.forms.search_videos')
def test_empty_field_passes_none(self, search_videos):
"""If the field isn't specified, pass None to the fields parameter."""
form = VideoSearchForm(self.request, {
'query': 'asdf',
'region': NORTH_AMERICA,
'sort': 'popular'
})
eq_(form.perform_search(), search_videos.return_value)
search_videos.assert_called_with(query='asdf', fields=None,
region=NORTH_AMERICA, sort='popular')
def test_invalid_form(self):
"""If the form fails validation, throw a ValidationError."""
form = VideoSearchForm(self.request, {
'region': -5,
'sort': 'invalid'
})
with assert_raises(ValidationError):
form.perform_search()
def test_clean_no_query(self):
"""
If no search query is specified, do not alter the sort value or
choices.
"""
form = VideoSearchForm(self.request, {'region': NORTH_AMERICA, 'sort': 'title'})
form.full_clean()
eq_(form.cleaned_data['sort'], 'title')
choice_values = zip(*form.fields['sort'].choices)[0]
ok_('' in choice_values)
def test_clean_query(self):
"""
If a search query is specified, remove the random option from the sort
choices and, if the sort is currently set to random, switch to title
sort.
"""
form = VideoSearchForm(self.request, {'query': 'blah', 'sort': ''})
form.full_clean()
eq_(form.cleaned_data['sort'], 'title')
choice_values = zip(*form.fields['sort'].choices)[0]
ok_('' not in choice_values)
# Check that sort is preserved if it is not random.
form = VideoSearchForm(self.request, {'query': 'blah', 'sort': 'popular'})
form.full_clean()
eq_(form.cleaned_data['sort'], 'popular')
choice_values = zip(*form.fields['sort'].choices)[0]
ok_('' not in choice_values)
def test_invalid_sort(self):
"""
An invalid value for sort should not break clean.
Regression test for an issue where a user was attempting to break Flicks by submitting a
bunch of invalid values for sort.
"""
form = VideoSearchForm(self.request, {'query': 'blah', 'sort': 'invalid'})
form.full_clean()
eq_(form.is_valid(), False)
| 36.504348 | 98 | 0.627203 |
0d4408fdffb4cd7e183f2fe1a89d4ac17533f8a5 | 305 | asm | Assembly | programs/oeis/110/A110963.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/110/A110963.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/110/A110963.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A110963: Fractalization of Kimberling's sequence beginning with 1.
; 1,1,1,1,2,1,1,1,3,2,2,1,4,1,1,1,5,3,3,2,6,2,2,1,7,4,4,1,8,1,1,1,9,5,5,3,10,3,3,2,11,6,6,2,12,2,2,1,13,7,7,4,14,4,4
mul $0,2
mov $4,9
lpb $4,14
add $4,$0
div $0,2
mov $6,$4
add $4,45
gcd $4,2
lpe
mov $1,$6
div $1,4
add $1,1
| 19.0625 | 116 | 0.577049 |
c9c472b466070cea0e0316cd206675b4818bf00e | 83 | ts | TypeScript | src/taskpane/components/IAppProps.ts | automate-this/M42-Outlook-TicketAddin | 32720446affd43b3a4767c507d98d4c7c0a3c383 | [
"MIT"
] | null | null | null | src/taskpane/components/IAppProps.ts | automate-this/M42-Outlook-TicketAddin | 32720446affd43b3a4767c507d98d4c7c0a3c383 | [
"MIT"
] | null | null | null | src/taskpane/components/IAppProps.ts | automate-this/M42-Outlook-TicketAddin | 32720446affd43b3a4767c507d98d4c7c0a3c383 | [
"MIT"
] | null | null | null | export interface IAppProps {
title: string;
isOfficeInitialized: boolean;
} | 20.75 | 33 | 0.73494 |
b36e1c2289027ada956cc59ba2f5a5624dfdd969 | 870 | py | Python | arborlife/utils.py | rogerhurwitz/arborlife | 36777200940a0be22340bea938cdad6b45c9ab6e | [
"MIT"
] | 1 | 2020-11-17T17:16:20.000Z | 2020-11-17T17:16:20.000Z | arborlife/utils.py | rogerhurwitz/arborlife | 36777200940a0be22340bea938cdad6b45c9ab6e | [
"MIT"
] | 6 | 2019-11-30T18:19:36.000Z | 2019-12-16T06:50:53.000Z | arborlife/utils.py | rogerhurwitz/arborlife | 36777200940a0be22340bea938cdad6b45c9ab6e | [
"MIT"
] | null | null | null | import math
import numpy as np
import scipy.stats as stats
def calc_cubic(a, b, c, d):
p = -b / (3 * a)
q = math.pow(p, 3) + (b * c - 3 * a * d) / (6 * math.pow(a, 2))
r = c / (3 * a)
x = (
math.pow(
q + (math.pow(math.pow(q, 2) + (math.pow(r - math.pow(p, 2), 3)), 0.5)), 1 / 3, # noqa: E501
)
+ math.pow(
q - (math.pow(math.pow(q, 2) + (math.pow(r - math.pow(p, 2), 3)), 0.5)), 1 / 3, # noqa: E501
)
+ p
)
return x
def calc_truncnorm(mean, sd, *, clip_a=-np.inf, clip_b=np.inf):
"""Returns a float in a normal distribution (mean, sd) clipped (clip_a, clip_b)."""
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.truncnorm.html
return stats.truncnorm.rvs(
a=(clip_a - mean) / sd, b=(clip_b - mean) / sd, loc=mean, scale=sd
)
| 29 | 108 | 0.514943 |
97ede007645c8831d9c0a559359d0ec4f48b2cb0 | 164 | swift | Swift | Remy/Remy/Models/Vitals.swift | peachbiotech/remy | cffeb0b9e65f9e7782689f8a7b9618310469b4a7 | [
"MIT"
] | null | null | null | Remy/Remy/Models/Vitals.swift | peachbiotech/remy | cffeb0b9e65f9e7782689f8a7b9618310469b4a7 | [
"MIT"
] | null | null | null | Remy/Remy/Models/Vitals.swift | peachbiotech/remy | cffeb0b9e65f9e7782689f8a7b9618310469b4a7 | [
"MIT"
] | null | null | null | //
// Vitals.swift
// Remy
//
// Created by Jia Chun Xie on 1/11/22.
//
import Foundation
struct Vitals: Codable {
var heartRate: Int
var o2Sat: Int
}
| 11.714286 | 39 | 0.621951 |
e2bad93ce8df5aafc95712be9a4601ac36fb93c7 | 270 | sql | SQL | ConflitosBelicos/SQL/consultarOrganizacoes.sql | KleberASGC/Conflitos-Belicos | c384dc96f7d851c48ae74019b0058e87ddce878f | [
"MIT"
] | null | null | null | ConflitosBelicos/SQL/consultarOrganizacoes.sql | KleberASGC/Conflitos-Belicos | c384dc96f7d851c48ae74019b0058e87ddce878f | [
"MIT"
] | null | null | null | ConflitosBelicos/SQL/consultarOrganizacoes.sql | KleberASGC/Conflitos-Belicos | c384dc96f7d851c48ae74019b0058e87ddce878f | [
"MIT"
] | null | null | null |
SELECT
codigoOrg as Codigo_Organizaรงรฃo,
COUNT(codigoOrg) as Quantidade_Mediacoes
FROM entradMed
WHERE codConflito NOT IN (SELECT codConflito FROM saidaMed)
GROUP BY codigoOrg
ORDER BY COUNT(codigoOrg) DESC
LIMIT 5
DELETE FROM saidaMed WHERE codigoOrg = 2
| 19.285714 | 59 | 0.792593 |
5c7b5852391e958848935303e604a6754108c7ad | 67,041 | rs | Rust | dpx/src/dpx_pdfdev.rs | chirsz-ever/tectonic | 1fbc8a7e1adedc2a819bffad0af94f3b04c88750 | [
"MIT"
] | null | null | null | dpx/src/dpx_pdfdev.rs | chirsz-ever/tectonic | 1fbc8a7e1adedc2a819bffad0af94f3b04c88750 | [
"MIT"
] | null | null | null | dpx/src/dpx_pdfdev.rs | chirsz-ever/tectonic | 1fbc8a7e1adedc2a819bffad0af94f3b04c88750 | [
"MIT"
] | null | null | null | /* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
Copyright (C) 2002-2016 by Jin-Hwan Cho and Shunsaku Hirata,
the dvipdfmx project team.
Copyright (C) 1998, 1999 by Mark A. Wicks <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#![allow(
mutable_transmutes,
non_camel_case_types,
non_snake_case,
non_upper_case_globals,
)]
use euclid::point2;
use crate::DisplayExt;
use crate::{info, warn};
use std::ffi::CStr;
use std::ptr;
use super::dpx_cff::cff_charsets_lookup_cid;
use super::dpx_cmap::{CMap_cache_get, CMap_decode};
use super::dpx_dvi::dvi_is_tracking_boxes;
use super::dpx_fontmap::pdf_lookup_fontmap_record;
use super::dpx_mem::{new, renew};
use super::dpx_mfileio::work_buffer_u8 as work_buffer;
use super::dpx_pdfcolor::{pdf_color_clear_stack, pdf_color_get_current};
use super::dpx_pdfdoc::pdf_doc_expand_box;
use super::dpx_pdfdoc::{pdf_doc_add_page_content, pdf_doc_add_page_resource};
use super::dpx_pdfdraw::{
pdf_dev_clear_gstates, pdf_dev_current_depth, pdf_dev_grestore, pdf_dev_grestore_to,
pdf_dev_gsave, pdf_dev_init_gstates, pdf_dev_rectclip,
};
use super::dpx_pdfdraw::{pdf_dev_concat, pdf_dev_set_color, pdf_dev_transform};
use super::dpx_pdffont::{
pdf_font_findresource, pdf_get_font_encoding, pdf_get_font_reference, pdf_get_font_subtype,
pdf_get_font_usedchars, pdf_get_font_wmode,
};
use super::dpx_pdfximage::{
pdf_ximage_get_reference, pdf_ximage_get_resname, pdf_ximage_scale_image,
};
use crate::dpx_pdfobj::{pdf_link_obj, pdf_obj, pdf_release_obj, pdfobj_escape_str};
use crate::shims::sprintf;
use crate::streq_ptr;
use libc::{free, strcpy};
pub type size_t = u64;
#[derive(Clone, Copy, PartialEq)]
pub enum MotionState {
GRAPHICS_MODE = 1,
TEXT_MODE = 2,
STRING_MODE = 3,
}
#[derive(Clone, Copy, PartialEq)]
pub enum TextWMode {
HH = 0,
HV = 1,
VH = 4,
VV = 5,
HD = 3,
VD = 7,
}
impl From<i32> for TextWMode {
fn from(r: i32) -> Self {
use TextWMode::*;
match r {
0 => HH,
1 => HV,
4 => VH,
5 => VV,
3 => HD,
7 => VD,
_ => unreachable!(),
}
}
}
fn ANGLE_CHANGES(m1: TextWMode, m2: TextWMode) -> bool {
!(((m1 as i32) - (m2 as i32)).abs() % 5 == 0)
}
fn ROTATE_TEXT(m: TextWMode) -> bool {
(m != TextWMode::HH) && (m != TextWMode::VV)
}
pub type spt_t = i32;
pub type TMatrix = euclid::Transform2D<f64, (), ()>;
pub type Rect = euclid::Box2D<f64, ()>;
impl DisplayExt for Rect {
type Adapter = String;
fn display(self) -> Self::Adapter {
format!(
"[{}, {}, {}, {}]",
self.min.x, self.min.y, self.max.x, self.max.y
)
}
}
pub trait Corner {
fn lower_left(&self) -> Point;
fn upper_right(&self) -> Point;
fn lower_right(&self) -> Point;
fn upper_left(&self) -> Point;
}
impl Corner for Rect {
fn lower_left(&self) -> Point {
self.min
}
fn upper_right(&self) -> Point {
self.max
}
fn lower_right(&self) -> Point {
point2(self.max.x, self.min.y)
}
fn upper_left(&self) -> Point {
point2(self.min.x, self.max.y)
}
}
/// Pointinate (point) in TeX document
pub type Point = euclid::Point2D<f64, ()>;
pub trait Equal {
fn equal(&self, other: &Self) -> bool;
}
impl Equal for Point {
fn equal(&self, other: &Self) -> bool {
((self.x - other.x).abs() < 1e-7) && ((self.y - other.y).abs() < 1e-7)
}
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct transform_info {
pub width: f64,
pub height: f64,
pub depth: f64,
pub matrix: TMatrix,
pub bbox: Rect,
pub flags: i32,
}
impl transform_info {
pub const fn new() -> Self {
Self {
width: 0.,
height: 0.,
depth: 0.,
matrix: TMatrix {
m11: 1.,
m12: 0.,
m21: 0.,
m22: 1.,
m31: 0.,
m32: 0.,
_unit: core::marker::PhantomData,
},
bbox: Rect::new(point2(0., 0.), point2(0., 0.)),
flags: 0,
}
}
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct dev_font {
pub short_name: [i8; 7],
pub used_on_this_page: i32,
pub tex_name: *mut i8,
pub sptsize: spt_t,
pub font_id: i32,
pub enc_id: i32,
pub real_font_index: i32,
pub resource: *mut pdf_obj,
pub used_chars: *mut i8,
pub format: i32,
pub wmode: i32,
pub extend: f64,
pub slant: f64,
pub bold: f64,
pub mapc: i32,
pub ucs_group: i32,
pub ucs_plane: i32,
pub is_unicode: i32,
pub cff_charsets: *mut cff_charsets,
}
use super::dpx_cff::cff_charsets;
/*
* Unit conversion, formatting and others.
*/
#[derive(Copy, Clone)]
#[repr(C)]
pub struct DevUnit {
pub dvi2pts: f64,
pub min_bp_val: i32,
pub precision: i32,
/* Number of decimal digits (in fractional part) kept. */
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct TextState {
pub font_id: i32,
pub offset: spt_t,
pub ref_x: spt_t,
pub ref_y: spt_t,
pub raise: spt_t,
pub leading: spt_t,
pub matrix: FontMatrix,
pub bold_param: f64,
pub dir_mode: i32,
pub force_reset: i32,
pub is_mb: i32,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct FontMatrix {
pub slant: f64,
pub extend: f64,
pub rotate: TextWMode,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct DevParam {
pub autorotate: i32,
pub colormode: i32,
}
/* Mapping types, MAP_IS_NAME is not supported. */
/* Lookup flags */
/* DEBUG */
/* Codespacerange */
use super::dpx_fontmap::fontmap_rec;
/* tectonic/core-strutils.h: miscellaneous C string utilities
Copyright 2016-2018 the Tectonic Project
Licensed under the MIT License.
*/
/* Note that we explicitly do *not* change this on Windows. For maximum
* portability, we should probably accept *either* forward or backward slashes
* as directory separators. */
static mut verbose: i32 = 0i32;
pub unsafe fn pdf_dev_set_verbose(level: i32) {
verbose = level;
}
/* Not working yet... */
pub unsafe fn pdf_dev_scale() -> f64 {
1.0f64
}
static mut dev_unit: DevUnit = DevUnit {
dvi2pts: 0.0f64,
min_bp_val: 658i32,
precision: 2i32,
};
pub unsafe fn dev_unit_dviunit() -> f64 {
1.0f64 / dev_unit.dvi2pts
}
static mut ten_pow: [u32; 10] = [
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
];
static mut ten_pow_inv: [f64; 10] = [
1.0f64,
0.1f64,
0.01f64,
0.001f64,
0.0001f64,
0.00001f64,
0.000001f64,
0.0000001f64,
0.00000001f64,
0.000000001f64,
];
unsafe fn p_itoa(mut value: i32, buf: *mut i8) -> u32 {
let mut p: *mut i8 = buf;
let sign = if value < 0i32 {
let fresh0 = p;
p = p.offset(1);
*fresh0 = '-' as i32 as i8;
value = -value;
1
} else {
0
};
let mut ndigits = 0_u32;
loop
/* Generate at least one digit in reverse order */
{
let fresh1 = ndigits;
ndigits = ndigits.wrapping_add(1);
*p.offset(fresh1 as isize) = (value % 10i32 + '0' as i32) as i8;
value /= 10i32;
if !(value != 0i32) {
break;
}
}
/* Reverse the digits */
for i in 0..ndigits.wrapping_div(2_u32) {
let tmp: i8 = *p.offset(i as isize);
*p.offset(i as isize) = *p.offset(ndigits.wrapping_sub(i).wrapping_sub(1_u32) as isize);
*p.offset(ndigits.wrapping_sub(i).wrapping_sub(1_u32) as isize) = tmp;
}
*p.offset(ndigits as isize) = '\u{0}' as i32 as i8;
return if sign != 0 {
ndigits.wrapping_add(1_u32)
} else {
ndigits
};
}
/* NOTE: Acrobat 5 and prior uses 16.16 fixed point representation for
* real numbers.
*/
fn p_dtoa(mut value: f64, prec: i32, buf: &mut [u8]) -> usize {
let p: [i32; 10] = [
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
];
let mut n = if value < 0. {
value = -value;
buf[0] = b'-';
1
} else {
0
};
let f = value.fract();
let mut i = value.trunc();
let mut g = (f * p[prec as usize] as f64 + 0.5) as i32;
if g == p[prec as usize] {
g = 0;
i += 1.
}
if i != 0. {
let fv = format!("{:.0}", i);
let m = fv.as_bytes().len();
buf[n..n + m].copy_from_slice(&fv.as_bytes());
n += m
} else if g == 0i32 {
buf[0] = b'0';
n = 1;
}
if g != 0 {
let mut j: i32 = prec;
buf[n] = b'.';
loop {
let fresh4 = j;
j = j - 1;
if !(fresh4 != 0) {
break;
}
buf[n + 1 + j as usize] = (g % 10) as u8 + b'0';
g /= 10
}
n += 1 + prec as usize;
while buf[n - 1] == b'0' {
n -= 1
}
}
buf[n] = 0;
n as usize
}
unsafe fn dev_sprint_bp(buf: &mut [u8], value: spt_t, error: *mut spt_t) -> usize {
let prec: i32 = dev_unit.precision;
let value_in_bp = value as f64 * dev_unit.dvi2pts;
if !error.is_null() {
let error_in_bp = value_in_bp
- (value_in_bp / ten_pow_inv[prec as usize] + 0.5f64).floor()
* ten_pow_inv[prec as usize];
*error = (error_in_bp / dev_unit.dvi2pts).round() as spt_t
}
p_dtoa(value_in_bp, prec, buf)
}
/* They are affected by precision (set at device initialization). */
pub fn pdf_sprint_matrix(buf: &mut [u8], M: &TMatrix) -> usize {
let precision = unsafe { dev_unit.precision };
let prec2: i32 = if precision + 2 < 8i32 {
precision + 2
} else {
8i32
}; /* xxx_sprint_xxx NULL terminates strings. */
let prec0: i32 = if precision > 2i32 { precision } else { 2i32 }; /* xxx_sprint_xxx NULL terminates strings. */
let mut len = p_dtoa(M.m11, prec2, buf); /* xxx_sprint_xxx NULL terminates strings. */
buf[len] = b' '; /* xxx_sprint_xxx NULL terminates strings. */
len += 1;
len += p_dtoa(M.m12, prec2, &mut buf[len..]);
buf[len] = b' ';
len += 1;
len += p_dtoa(M.m21, prec2, &mut buf[len..]);
buf[len] = b' ';
len += 1;
len += p_dtoa(M.m22, prec2, &mut buf[len..]);
buf[len] = b' ';
len += 1;
len += p_dtoa(M.m31, prec0, &mut buf[len..]);
buf[len] = b' ';
len += 1;
len += p_dtoa(M.m32, prec0, &mut buf[len..]);
buf[len] = b'\x00';
len
}
pub fn pdf_sprint_rect(buf: &mut [u8], rect: &Rect) -> usize {
let precision = unsafe { dev_unit.precision };
let mut len = p_dtoa(rect.min.x, precision, buf);
buf[len] = b' ';
len += 1;
len += p_dtoa(rect.min.y, precision, &mut buf[len..]);
buf[len] = b' ';
len += 1;
len += p_dtoa(rect.max.x, precision, &mut buf[len..]);
buf[len] = b' ';
len += 1;
len += p_dtoa(rect.max.y, precision, &mut buf[len..]);
buf[len] = 0;
len
}
pub fn pdf_sprint_coord(buf: &mut [u8], p: &Point) -> usize {
let precision = unsafe { dev_unit.precision };
let mut len = p_dtoa(p.x, precision, buf);
buf[len] = b' ';
len += 1;
len += p_dtoa(p.y, precision, &mut buf[len..]);
buf[len] = 0;
len
}
pub fn pdf_sprint_length(buf: &mut [u8], value: f64) -> usize {
let len = p_dtoa(value, unsafe { dev_unit.precision }, buf);
buf[len] = 0;
len
}
pub fn pdf_sprint_number(buf: &mut [u8], value: f64) -> usize {
let len = p_dtoa(value, 8, buf);
buf[len] = 0;
len
}
static mut dev_param: DevParam = DevParam {
autorotate: 1i32,
colormode: 1i32,
};
static mut motion_state: MotionState = MotionState::GRAPHICS_MODE;
static mut format_buffer: [u8; 4096] = [0; 4096];
static mut text_state: TextState = TextState {
font_id: -1,
offset: 0,
ref_x: 0,
ref_y: 0,
raise: 0,
leading: 0,
matrix: FontMatrix {
slant: 0.,
extend: 1.,
rotate: TextWMode::HH,
},
bold_param: 0.,
dir_mode: 0,
force_reset: 0,
is_mb: 0,
};
static mut dev_fonts: *mut dev_font = std::ptr::null_mut();
static mut num_dev_fonts: i32 = 0i32;
static mut max_dev_fonts: i32 = 0i32;
static mut num_phys_fonts: i32 = 0i32;
unsafe fn dev_set_text_matrix(
xpos: spt_t,
ypos: spt_t,
slant: f64,
extend: f64,
rotate: TextWMode,
) {
let mut len = 0;
/* slant is negated for vertical font so that right-side
* is always lower. */
let tma;
let tmb;
let tmc;
let tmd;
match rotate {
TextWMode::VH => {
/* Vertical font */
tma = slant;
tmb = 1.;
tmc = -extend;
tmd = 0.;
}
TextWMode::HV => {
/* Horizontal font */
tma = 0.;
tmb = -extend;
tmc = 1.;
tmd = -slant;
}
TextWMode::HH => {
/* Horizontal font */
tma = extend;
tmb = 0.;
tmc = slant;
tmd = 1.;
}
TextWMode::VV => {
/* Vertical font */
tma = 1.;
tmb = -slant;
tmc = 0.;
tmd = extend;
}
TextWMode::HD => {
/* Horizontal font */
tma = 0.;
tmb = extend;
tmc = -1.;
tmd = slant;
}
TextWMode::VD => {
/* Vertical font */
tma = -1.; /* op: Tm */
tmb = slant;
tmc = 0.;
tmd = -extend;
}
}
let mut tm = TMatrix::row_major(
tma,
tmb,
tmc,
tmd,
xpos as f64 * dev_unit.dvi2pts,
ypos as f64 * dev_unit.dvi2pts,
);
format_buffer[len] = b' ';
len += 1;
len += pdf_sprint_matrix(&mut format_buffer[len..], &mut tm) as usize;
format_buffer[len] = b' ';
len += 1;
format_buffer[len] = b'T';
len += 1;
format_buffer[len] = b'm';
len += 1;
pdf_doc_add_page_content(&format_buffer[..len]);
text_state.ref_x = xpos;
text_state.ref_y = ypos;
text_state.matrix.slant = slant;
text_state.matrix.extend = extend;
text_state.matrix.rotate = rotate;
}
/*
* reset_text_state() outputs a BT and does any necessary coordinate
* transformations to get ready to ship out text.
*/
unsafe fn reset_text_state() {
/*
* We need to reset the line matrix to handle slanted fonts.
*/
pdf_doc_add_page_content(b" BT"); /* op: BT */
/*
* text_state.matrix is identity at top of page.
* This sometimes write unnecessary "Tm"s when transition from
* GRAPHICS_MODE to TEXT_MODE occurs.
*/
if text_state.force_reset != 0
|| text_state.matrix.slant != 0.0f64
|| text_state.matrix.extend != 1.0f64
|| ROTATE_TEXT(text_state.matrix.rotate)
{
dev_set_text_matrix(
0i32,
0i32,
text_state.matrix.slant,
text_state.matrix.extend,
text_state.matrix.rotate,
); /* op: TJ */
} /* op: TJ */
text_state.ref_x = 0i32;
text_state.ref_y = 0i32;
text_state.offset = 0i32;
text_state.force_reset = 0i32;
}
unsafe fn text_mode() {
match motion_state {
MotionState::STRING_MODE => {
pdf_doc_add_page_content(if text_state.is_mb != 0 {
b">]TJ"
} else {
b")]TJ"
});
}
MotionState::GRAPHICS_MODE => {
reset_text_state();
}
MotionState::TEXT_MODE => {}
}
motion_state = MotionState::TEXT_MODE;
text_state.offset = 0i32;
}
pub unsafe fn graphics_mode() {
match motion_state {
MotionState::GRAPHICS_MODE => {}
MotionState::STRING_MODE | MotionState::TEXT_MODE => {
if let MotionState::STRING_MODE = motion_state {
pdf_doc_add_page_content(if text_state.is_mb != 0 {
b">]TJ"
} else {
b")]TJ"
});
}
pdf_doc_add_page_content(b" ET"); /* op: ET */
text_state.force_reset = 0i32;
text_state.font_id = -1i32
}
}
motion_state = MotionState::GRAPHICS_MODE;
}
unsafe fn start_string(xpos: spt_t, ypos: spt_t, slant: f64, extend: f64, rotate: TextWMode) {
let mut error_delx: spt_t = 0i32;
let mut error_dely: spt_t = 0i32;
let mut len = 0_usize;
let delx = xpos - text_state.ref_x;
let dely = ypos - text_state.ref_y;
/*
* Precompensating for line transformation matrix.
*
* Line transformation matrix L for horizontal font in horizontal
* mode and it's inverse I is
*
* | e 0| | 1/e 0|
* L_hh = | | , I_hh = | |
* | s 1| |-s/e 1|
*
* For vertical font in vertical mode,
*
* | 1 -s| | 1 s/e|
* L_vv = | | , I_vv = | |
* | 0 e| | 0 1/e|
*
* For vertical font in horizontal mode,
*
* | s 1| | 0 1|
* L_vh = | | = L_vv x | |
* |-e 0| |-1 0|
*
* | 0 -1|
* I_vh = | | x I_vv
* | 1 0|
*
* For horizontal font in vertical mode,
*
* | 0 -e| | 0 -1|
* L_hv = | | = L_hh x | |
* | 1 -s| | 1 0|
*
* | 0 1|
* I_hv = | | x I_hh
* |-1 0|
*
*/
match rotate {
TextWMode::VH => {
/* Vertical font in horizontal mode: rot = +90
* | 0 -1/e|
* d_user = d x I_vh = d x | |
* | 1 s/e|
*/
let desired_delx = dely;
let desired_dely = (-(delx as f64 - dely as f64 * slant) / extend) as spt_t;
/* error_del is in device space
*
* | 0 1|
* e = e_user x | | = (-e_user_y, e_user_x)
* |-1 0|
*
* We must care about rotation here but not extend/slant...
* The extend and slant actually is font matrix.
*/
let fresh18 = len;
len = len + 1;
format_buffer[fresh18 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_delx, &mut error_dely);
let fresh19 = len;
len = len + 1;
format_buffer[fresh19 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_dely, &mut error_delx);
error_delx = -error_delx
}
TextWMode::HV => {
/* Horizontal font in vertical mode: rot = -90
*
* |-s/e 1|
* d_user = d x I_hv = d x | |
* |-1/e 0|
*/
let desired_delx = (-(dely as f64 + delx as f64 * slant) / extend) as spt_t;
let desired_dely = delx;
/*
* e = (e_user_y, -e_user_x)
*/
let fresh20 = len;
len = len + 1;
format_buffer[fresh20 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_delx, &mut error_dely);
let fresh21 = len;
len = len + 1;
format_buffer[fresh21 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_dely, &mut error_delx);
error_dely = -error_dely
}
TextWMode::HH => {
/* Horizontal font in horizontal mode:
* | 1/e 0|
* d_user = d x I_hh = d x | |
* |-s/e 1|
*/
let desired_delx = ((delx as f64 - dely as f64 * slant) / extend) as spt_t;
let desired_dely = dely;
let fresh22 = len;
len = len + 1;
format_buffer[fresh22 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_delx, &mut error_delx);
let fresh23 = len;
len = len + 1;
format_buffer[fresh23 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_dely, &mut error_dely)
}
TextWMode::VV => {
/* Vertical font in vertical mode:
* | 1 s/e|
* d_user = d x I_vv = d x | |
* | 0 1/e|
*/
let desired_delx = delx;
let desired_dely = ((dely as f64 + delx as f64 * slant) / extend) as spt_t;
let fresh24 = len;
len = len + 1;
format_buffer[fresh24 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_delx, &mut error_delx);
let fresh25 = len;
len = len + 1;
format_buffer[fresh25 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_dely, &mut error_dely)
}
TextWMode::HD => {
/* Horizontal font in down-to-up mode: rot = +90
*
* | s/e -1|
* d_user = d x -I_hv = d x | |
* | 1/e 0|
*/
let desired_delx = -((-(dely as f64 + delx as f64 * slant) / extend) as spt_t);
let desired_dely = -delx;
let fresh26 = len;
len = len + 1;
format_buffer[fresh26 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_delx, &mut error_dely);
let fresh27 = len;
len = len + 1;
format_buffer[fresh27 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_dely, &mut error_delx);
error_delx = -error_delx;
error_dely = -error_dely
}
TextWMode::VD => {
/* Vertical font in down-to-up mode: rot = 180
* |-1 -s/e|
* d_user = d x -I_vv = d x | |
* | 0 -1/e|
*/
let desired_delx = -delx; /* op: */
let desired_dely = -(((dely as f64 + delx as f64 * slant) / extend) as spt_t);
let fresh28 = len;
len = len + 1;
format_buffer[fresh28 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_delx, &mut error_delx);
let fresh29 = len;
len = len + 1;
format_buffer[fresh29 as usize] = b' ';
len += dev_sprint_bp(&mut format_buffer[len..], desired_dely, &mut error_dely);
error_delx = -error_delx;
error_dely = -error_dely
}
}
pdf_doc_add_page_content(&format_buffer[..len as usize]);
/*
* dvipdfm wrongly using "TD" in place of "Td".
* The TD operator set leading, but we are not using T* etc.
*/
pdf_doc_add_page_content(if text_state.is_mb != 0 {
b" Td[<"
} else {
b" Td[("
}); /* op: Td */
/* Error correction */
text_state.ref_x = xpos - error_delx;
text_state.ref_y = ypos - error_dely;
text_state.offset = 0i32;
}
unsafe fn string_mode(xpos: spt_t, ypos: spt_t, slant: f64, extend: f64, rotate: TextWMode) {
match motion_state {
MotionState::GRAPHICS_MODE | MotionState::TEXT_MODE => {
if let MotionState::GRAPHICS_MODE = motion_state {
reset_text_state();
}
if text_state.force_reset != 0 {
dev_set_text_matrix(xpos, ypos, slant, extend, rotate); /* op: */
pdf_doc_add_page_content(if text_state.is_mb != 0 { b"[<" } else { b"[(" });
text_state.force_reset = 0i32
} else {
start_string(xpos, ypos, slant, extend, rotate);
}
}
MotionState::STRING_MODE => {}
}
motion_state = MotionState::STRING_MODE;
}
/*
* The purpose of the following routine is to force a Tf only
* when it's actually necessary. This became a problem when the
* VF code was added. The VF spec says to instantiate the
* first font contained in the VF file before drawing a virtual
* character. However, that font may not be used for
* many characters (e.g. small caps fonts). For this reason,
* dev_select_font() should not force a "physical" font selection.
* This routine prevents a PDF Tf font selection until there's
* really a character in that font.
*/
unsafe fn dev_set_font(font_id: i32) -> i32 {
/* text_mode() must come before text_state.is_mb is changed. */
text_mode(); /* Caller should check font_id. */
let font = &mut *dev_fonts.offset(font_id as isize) as *mut dev_font; /* space not necessary. */
assert!(!font.is_null());
let real_font = if (*font).real_font_index >= 0i32 {
&mut *dev_fonts.offset((*font).real_font_index as isize) as *mut dev_font
} else {
font
};
text_state.is_mb = if (*font).format == 3i32 { 1i32 } else { 0i32 };
let vert_font = if (*font).wmode != 0 { 1 } else { 0 };
let vert_dir = if dev_param.autorotate != 0 {
text_state.dir_mode
} else {
vert_font
};
let text_rotate = TextWMode::from(vert_font << 2 | vert_dir);
if (*font).slant != text_state.matrix.slant
|| (*font).extend != text_state.matrix.extend
|| ANGLE_CHANGES(text_rotate, text_state.matrix.rotate)
{
text_state.force_reset = 1i32
}
text_state.matrix.slant = (*font).slant;
text_state.matrix.extend = (*font).extend;
text_state.matrix.rotate = text_rotate;
if (*real_font).resource.is_null() {
(*real_font).resource = pdf_get_font_reference((*real_font).font_id);
(*real_font).used_chars = pdf_get_font_usedchars((*real_font).font_id)
}
if (*real_font).used_on_this_page == 0 {
pdf_doc_add_page_resource(
"Font",
(*real_font).short_name.as_mut_ptr(),
pdf_link_obj((*real_font).resource),
);
(*real_font).used_on_this_page = 1i32
}
let font_scale = (*font).sptsize as f64 * dev_unit.dvi2pts;
let mut len = sprintf(
format_buffer.as_mut_ptr() as *mut i8,
b" /%s\x00" as *const u8 as *const i8,
(*real_font).short_name.as_mut_ptr(),
) as usize;
let fresh30 = len;
len = len + 1;
format_buffer[fresh30 as usize] = b' ';
len += p_dtoa(
font_scale,
if dev_unit.precision + 1i32 < 8i32 {
dev_unit.precision + 1i32
} else {
8i32
},
&mut format_buffer[len..],
) as usize;
let fresh31 = len;
len = len + 1;
format_buffer[fresh31 as usize] = b' ';
let fresh32 = len;
len = len + 1;
format_buffer[fresh32 as usize] = b'T';
let fresh33 = len;
len = len + 1;
format_buffer[fresh33 as usize] = b'f';
pdf_doc_add_page_content(&format_buffer[..len]);
if (*font).bold > 0.0f64 || (*font).bold != text_state.bold_param {
if (*font).bold <= 0.0f64 {
len = sprintf(
format_buffer.as_mut_ptr() as *mut i8,
b" 0 Tr\x00" as *const u8 as *const i8,
) as usize
} else {
len = sprintf(
format_buffer.as_mut_ptr() as *mut i8,
b" 2 Tr %.6f w\x00" as *const u8 as *const i8,
(*font).bold,
) as usize
}
pdf_doc_add_page_content(&format_buffer[..len]);
/* op: Tr w */
}
text_state.bold_param = (*font).bold;
text_state.font_id = font_id;
0i32
}
/* Access text state parameters.
*/
pub unsafe fn pdf_dev_get_font_wmode(font_id: i32) -> i32 {
let font = &mut *dev_fonts.offset(font_id as isize) as *mut dev_font;
if !font.is_null() {
return (*font).wmode;
}
0i32
}
static mut sbuf0: [u8; 4096] = [0; 4096];
static mut sbuf1: [u8; 4096] = [0; 4096];
unsafe fn handle_multibyte_string(
font: *mut dev_font,
str_ptr: *mut *const u8,
str_len: *mut size_t,
ctype: i32,
) -> i32 {
let mut p = *str_ptr;
let mut length = *str_len;
if ctype == -1i32 && !(*font).cff_charsets.is_null() {
/* freetype glyph indexes */
/* Convert freetype glyph indexes to CID. */
let mut inbuf: *const u8 = p;
let mut outbuf: *mut u8 = sbuf0.as_mut_ptr();
for _ in (0..length).step_by(2) {
let fresh34 = inbuf;
inbuf = inbuf.offset(1);
let mut gid = ((*fresh34 as i32) << 8i32) as u32;
let fresh35 = inbuf;
inbuf = inbuf.offset(1);
gid = gid.wrapping_add(*fresh35 as u32);
gid = cff_charsets_lookup_cid((*font).cff_charsets, gid as u16) as u32;
let fresh36 = outbuf;
outbuf = outbuf.offset(1);
*fresh36 = (gid >> 8i32) as u8;
let fresh37 = outbuf;
outbuf = outbuf.offset(1);
*fresh37 = (gid & 0xff_u32) as u8;
}
p = sbuf0.as_mut_ptr();
length = outbuf.wrapping_offset_from(sbuf0.as_mut_ptr()) as i64 as size_t
} else if (*font).is_unicode != 0 {
/* _FIXME_ */
/* UCS-4 */
if ctype == 1i32 {
if length.wrapping_mul(4i32 as u64) >= 4096i32 as u64 {
warn!("Too long string...");
return -1i32;
}
for i in 0..length {
sbuf1[i.wrapping_mul(4i32 as u64) as usize] = (*font).ucs_group as u8;
sbuf1[i.wrapping_mul(4i32 as u64).wrapping_add(1i32 as u64) as usize] =
(*font).ucs_plane as u8;
sbuf1[i.wrapping_mul(4i32 as u64).wrapping_add(2i32 as u64) as usize] =
'\u{0}' as i32 as u8;
sbuf1[i.wrapping_mul(4i32 as u64).wrapping_add(3i32 as u64) as usize] =
*p.offset(i as isize);
}
length = (length as u64).wrapping_mul(4i32 as u64) as size_t as size_t
} else if ctype == 2i32 {
let mut len: size_t = 0i32 as size_t;
if length.wrapping_mul(2i32 as u64) >= 4096i32 as u64 {
warn!("Too long string...");
return -1i32;
}
let mut i = 0i32 as size_t;
while i < length {
sbuf1[len as usize] = (*font).ucs_group as u8;
if *p.offset(i as isize) as i32 & 0xf8i32 == 0xd8i32 {
/* Check for valid surrogate pair. */
if *p.offset(i as isize) as i32 & 0xfci32 != 0xd8i32
|| i.wrapping_add(2i32 as u64) >= length
|| *p.offset(i.wrapping_add(2i32 as u64) as isize) as i32 & 0xfci32
!= 0xdci32
{
warn!(
"Invalid surrogate p[{}]={:02X}...",
i,
*p.offset(i as isize) as i32,
);
return -1i32;
}
let c = ((*p.offset(i as isize) as i32 & 0x3i32) << 10i32
| (*p.offset(i.wrapping_add(1i32 as u64) as isize) as i32) << 2i32
| *p.offset(i.wrapping_add(2i32 as u64) as isize) as i32 & 0x3i32)
+ 0x100i32;
sbuf1[len.wrapping_add(1i32 as u64) as usize] = (c >> 8i32 & 0xffi32) as u8;
sbuf1[len.wrapping_add(2i32 as u64) as usize] = (c & 0xffi32) as u8;
i = (i as u64).wrapping_add(2i32 as u64) as size_t as size_t
} else {
sbuf1[len.wrapping_add(1i32 as u64) as usize] = (*font).ucs_plane as u8;
sbuf1[len.wrapping_add(2i32 as u64) as usize] = *p.offset(i as isize)
}
sbuf1[len.wrapping_add(3i32 as u64) as usize] =
*p.offset(i.wrapping_add(1i32 as u64) as isize);
i = (i as u64).wrapping_add(2i32 as u64) as size_t as size_t;
len = (len as u64).wrapping_add(4i32 as u64) as size_t as size_t
}
length = len
}
p = sbuf1.as_mut_ptr()
} else if ctype == 1i32 && (*font).mapc >= 0i32 {
/* Omega workaround...
* Translate single-byte chars to double byte code space.
*/
if length.wrapping_mul(2i32 as u64) >= 4096i32 as u64 {
warn!("Too long string...");
return -1i32;
}
for i in 0..length {
sbuf1[i.wrapping_mul(2i32 as u64) as usize] = ((*font).mapc & 0xffi32) as u8;
sbuf1[i.wrapping_mul(2i32 as u64).wrapping_add(1i32 as u64) as usize] =
*p.offset(i as isize);
}
length = (length as u64).wrapping_mul(2i32 as u64) as size_t as size_t;
p = sbuf1.as_mut_ptr()
}
/*
* Font is double-byte font. Output is assumed to be 16-bit fixed length
* encoding.
* TODO: A character decomposed to multiple characters.
*/
if ctype != -1i32 && (*font).enc_id >= 0i32 {
let cmap = CMap_cache_get((*font).enc_id);
let mut inbuf_0 = p;
let mut outbuf_0 = sbuf0.as_mut_ptr();
let mut inbytesleft = length;
let mut outbytesleft = 4096i32 as size_t;
CMap_decode(
cmap,
&mut inbuf_0,
&mut inbytesleft,
&mut outbuf_0,
&mut outbytesleft,
);
if inbytesleft != 0i32 as u64 {
warn!("CMap conversion failed. ({} bytes remains)", inbytesleft,);
return -1i32;
}
length = (4096i32 as u64).wrapping_sub(outbytesleft);
p = sbuf0.as_mut_ptr()
}
*str_ptr = p;
*str_len = length;
0i32
}
static mut dev_coords: *mut Point = std::ptr::null_mut();
static mut num_dev_coords: i32 = 0i32;
static mut max_dev_coords: i32 = 0i32;
pub unsafe fn pdf_dev_get_coord() -> Point {
if num_dev_coords > 0i32 {
(*dev_coords.offset((num_dev_coords - 1i32) as isize))
} else {
Point::zero()
}
}
pub unsafe fn pdf_dev_push_coord(xpos: f64, ypos: f64) {
if num_dev_coords >= max_dev_coords {
max_dev_coords += 4i32;
dev_coords = renew(
dev_coords as *mut libc::c_void,
(max_dev_coords as u32 as u64).wrapping_mul(::std::mem::size_of::<Point>() as u64)
as u32,
) as *mut Point
}
(*dev_coords.offset(num_dev_coords as isize)).x = xpos;
(*dev_coords.offset(num_dev_coords as isize)).y = ypos;
num_dev_coords += 1;
}
pub unsafe fn pdf_dev_pop_coord() {
if num_dev_coords > 0i32 {
num_dev_coords -= 1
};
}
/*
* ctype:
* -1 input string contains 2-byte Freetype glyph index values
* (XeTeX only)
* 0 byte-width of char can be variable and input string
* is properly encoded.
* n Single character cosumes n bytes in input string.
*
* _FIXME_
* -->
* selectfont(font_name, point_size) and show_string(pos, string)
*/
pub unsafe fn pdf_dev_set_string(
mut xpos: spt_t,
mut ypos: spt_t,
instr_ptr: *const libc::c_void,
instr_len: size_t,
width: spt_t,
font_id: i32,
ctype: i32,
) {
/* Pointer to the reencoded string. */
let mut len: size_t = 0i32 as size_t;
if font_id < 0i32 || font_id >= num_dev_fonts {
panic!("Invalid font: {} ({})", font_id, num_dev_fonts);
}
if font_id != text_state.font_id {
dev_set_font(font_id);
}
let font = if text_state.font_id < 0i32 {
ptr::null_mut()
} else {
&mut *dev_fonts.offset(text_state.font_id as isize) as *mut dev_font
};
if font.is_null() {
panic!("Currentfont not set.");
}
let real_font = if (*font).real_font_index >= 0i32 {
&mut *dev_fonts.offset((*font).real_font_index as isize) as *mut dev_font
} else {
font
};
let text_xorigin = text_state.ref_x;
let text_yorigin = text_state.ref_y;
let mut str_ptr = instr_ptr as *const u8;
let mut length = instr_len;
if (*font).format == 3i32 {
if handle_multibyte_string(font, &mut str_ptr, &mut length, ctype) < 0i32 {
panic!("Error in converting input string...");
}
if !(*real_font).used_chars.is_null() {
for i in (0..length).step_by(2) {
let cid: u16 = ((*str_ptr.offset(i as isize) as i32) << 8i32
| *str_ptr.offset(i.wrapping_add(1i32 as u64) as isize) as i32)
as u16;
let ref mut fresh38 = *(*real_font).used_chars.offset((cid as i32 / 8i32) as isize);
*fresh38 = (*fresh38 as i32 | 1i32 << 7i32 - cid as i32 % 8i32) as i8;
}
}
} else if !(*real_font).used_chars.is_null() {
for i in 0..length {
*(*real_font)
.used_chars
.offset(*str_ptr.offset(i as isize) as isize) = 1_i8;
}
}
if num_dev_coords > 0i32 {
xpos -= ((*dev_coords.offset((num_dev_coords - 1i32) as isize)).x / dev_unit.dvi2pts)
.round() as spt_t;
ypos -= ((*dev_coords.offset((num_dev_coords - 1i32) as isize)).y / dev_unit.dvi2pts)
.round() as spt_t
}
/*
* Kern is in units of character units, i.e., 1000 = 1 em.
*
* Positive kern means kerning (reduce excess white space).
*
* The following formula is of the form a*x/b where a, x, and b are signed long
* integers. Since in integer arithmetic (a*x) could overflow and a*(x/b) would
* not be accurate, we use floating point arithmetic rather than trying to do
* this all with integer arithmetic.
*
* 1000.0 / (font->extend * font->sptsize) is caluculated each times...
* Is accuracy really a matter? Character widths are always rounded to integer
* (in 1000 units per em) but dvipdfmx does not take into account of this...
*/
let (delh, delv) = if text_state.dir_mode == 0i32 {
/* Left-to-right */
(text_xorigin + text_state.offset - xpos, ypos - text_yorigin)
} else if text_state.dir_mode == 1i32 {
/* Top-to-bottom */
(ypos - text_yorigin + text_state.offset, xpos - text_xorigin)
} else {
/* Bottom-to-top */
(ypos + text_yorigin + text_state.offset, xpos + text_xorigin)
};
/* White-space more than 3em is not considered as a part of single text.
* So we will break string mode in that case.
* Dvipdfmx spend most of time processing strings with kern = 0 (but far
* more times in font handling).
* You may want to use pre-calculated value for WORD_SPACE_MAX.
* More text compression may be possible by replacing kern with space char
* when -kern is equal to space char width.
*/
let kern = if text_state.force_reset != 0
|| (delv as i64).abs() > dev_unit.min_bp_val as i64
|| (delh as i64).abs() > (3.0f64 * (*font).extend * (*font).sptsize as f64) as spt_t as i64
{
text_mode();
0
} else {
(1000.0f64 / (*font).extend * delh as f64 / (*font).sptsize as f64) as spt_t
};
/* Inaccucary introduced by rounding of character width appears within
* single text block. There are point_size/1000 rounding error per character.
* If you really care about accuracy, you should compensate this here too.
*/
if motion_state != MotionState::STRING_MODE {
string_mode(
xpos,
ypos,
(*font).slant,
(*font).extend,
text_state.matrix.rotate,
);
} else if kern != 0i32 {
/*
* Same issues as earlier. Use floating point for simplicity.
* This routine needs to be fast, so we don't call sprintf() or strcpy().
*/
text_state.offset -=
(kern as f64 * (*font).extend * ((*font).sptsize as f64 / 1000.0f64)) as spt_t; /* op: */
let fresh39 = len;
len = len.wrapping_add(1);
format_buffer[fresh39 as usize] = (if text_state.is_mb != 0 {
'>' as i32
} else {
')' as i32
}) as u8;
if (*font).wmode != 0 {
len = (len as u64).wrapping_add(p_itoa(
-kern,
(format_buffer.as_mut_ptr() as *mut i8).offset(len as isize),
) as u64) as size_t as size_t
} else {
len = (len as u64).wrapping_add(p_itoa(
kern,
(format_buffer.as_mut_ptr() as *mut i8).offset(len as isize),
) as u64) as size_t as size_t
}
let fresh40 = len;
len = len.wrapping_add(1);
format_buffer[fresh40 as usize] = (if text_state.is_mb != 0 {
'<' as i32
} else {
'(' as i32
}) as u8;
pdf_doc_add_page_content(&format_buffer[..len as usize]);
len = 0i32 as size_t
}
if text_state.is_mb != 0 {
if (4096i32 as u64).wrapping_sub(len) < (2i32 as u64).wrapping_mul(length) {
panic!("Buffer overflow...");
}
for i in 0..length {
let first = *str_ptr.offset(i as isize) as i32 >> 4i32 & 0xfi32;
let second = *str_ptr.offset(i as isize) as i32 & 0xfi32;
let fresh41 = len;
len = len.wrapping_add(1);
format_buffer[fresh41 as usize] = (if first >= 10i32 {
first + 'W' as i32
} else {
first + '0' as i32
}) as u8;
let fresh42 = len;
len = len.wrapping_add(1);
format_buffer[fresh42 as usize] = (if second >= 10i32 {
second + 'W' as i32
} else {
second + '0' as i32
}) as u8;
}
} else {
len = (len as u64).wrapping_add(pdfobj_escape_str(
(format_buffer.as_mut_ptr() as *mut i8).offset(len as isize),
(4096i32 as u64).wrapping_sub(len),
str_ptr,
length,
)) as size_t as size_t
}
/* I think if you really care about speed, you should avoid memcopy here. */
pdf_doc_add_page_content(&format_buffer[..len as usize]); /* op: */
text_state.offset += width;
}
pub unsafe fn pdf_init_device(dvi2pts: f64, precision: i32, black_and_white: i32) {
if precision < 0i32 || precision > 8i32 {
warn!("Number of decimal digits out of range [0-{}].", 8i32);
}
if precision < 0i32 {
dev_unit.precision = 0i32
} else if precision > 8i32 {
dev_unit.precision = 8i32
} else {
dev_unit.precision = precision
}
dev_unit.dvi2pts = dvi2pts;
dev_unit.min_bp_val =
((1.0f64 / (ten_pow[dev_unit.precision as usize] as f64 * dvi2pts) / 1i32 as f64 + 0.5f64)
.floor()
* 1i32 as f64) as i32;
if dev_unit.min_bp_val < 0i32 {
dev_unit.min_bp_val = -dev_unit.min_bp_val
}
dev_param.colormode = if black_and_white != 0 { 0i32 } else { 1i32 };
graphics_mode();
pdf_color_clear_stack();
pdf_dev_init_gstates();
max_dev_fonts = 0i32;
num_dev_fonts = max_dev_fonts;
dev_fonts = ptr::null_mut();
max_dev_coords = 0i32;
num_dev_coords = max_dev_coords;
dev_coords = ptr::null_mut();
}
pub unsafe fn pdf_close_device() {
if !dev_fonts.is_null() {
for i in 0..num_dev_fonts {
free((*dev_fonts.offset(i as isize)).tex_name as *mut libc::c_void);
pdf_release_obj((*dev_fonts.offset(i as isize)).resource);
let ref mut fresh43 = (*dev_fonts.offset(i as isize)).tex_name;
*fresh43 = ptr::null_mut();
let ref mut fresh44 = (*dev_fonts.offset(i as isize)).resource;
*fresh44 = ptr::null_mut();
let ref mut fresh45 = (*dev_fonts.offset(i as isize)).cff_charsets;
*fresh45 = ptr::null_mut();
}
free(dev_fonts as *mut libc::c_void);
}
free(dev_coords as *mut libc::c_void);
pdf_dev_clear_gstates();
}
/*
* BOP, EOP, and FONT section.
* BOP and EOP manipulate some of the same data structures
* as the font stuff.
*/
pub unsafe fn pdf_dev_reset_fonts(newpage: i32) {
for i in 0..num_dev_fonts {
(*dev_fonts.offset(i as isize)).used_on_this_page = 0i32;
}
text_state.font_id = -1i32;
text_state.matrix.slant = 0.0f64;
text_state.matrix.extend = 1.0f64;
text_state.matrix.rotate = TextWMode::HH;
if newpage != 0 {
text_state.bold_param = 0.0f64
}
text_state.is_mb = 0i32;
}
pub unsafe fn pdf_dev_reset_color(force: i32) {
let (sc, fc) = pdf_color_get_current();
pdf_dev_set_color(sc, 0, force);
pdf_dev_set_color(fc, 0x20, force);
}
pub unsafe fn pdf_dev_bop(M: &TMatrix) {
graphics_mode();
text_state.force_reset = 0i32;
pdf_dev_gsave();
pdf_dev_concat(M);
pdf_dev_reset_fonts(1i32);
pdf_dev_reset_color(0i32);
}
pub unsafe fn pdf_dev_eop() {
graphics_mode();
let depth = pdf_dev_current_depth();
if depth != 1 {
warn!("Unbalenced q/Q nesting...: {}", depth);
pdf_dev_grestore_to(0);
} else {
pdf_dev_grestore();
};
}
unsafe fn print_fontmap(font_name: *const i8, mrec: *mut fontmap_rec) {
if mrec.is_null() {
return;
}
info!("\n");
info!(
"fontmap: {} -> {}",
CStr::from_ptr(font_name).display(),
CStr::from_ptr((*mrec).font_name).display(),
);
if !(*mrec).enc_name.is_null() {
info!("({})", CStr::from_ptr((*mrec).enc_name).display());
}
if (*mrec).opt.extend != 1.0f64 {
info!("[extend:{}]", (*mrec).opt.extend);
}
if (*mrec).opt.slant != 0.0f64 {
info!("[slant:{}]", (*mrec).opt.slant);
}
if (*mrec).opt.bold != 0.0f64 {
info!("[bold:{}]", (*mrec).opt.bold);
}
if (*mrec).opt.flags & 1i32 << 1i32 != 0 {
info!("[noemb]");
}
if (*mrec).opt.mapc >= 0i32 {
info!("[map:<{:02x}>]", (*mrec).opt.mapc);
}
if !(*mrec).opt.charcoll.is_null() {
info!("[csi:{}]", CStr::from_ptr((*mrec).opt.charcoll).display());
}
if (*mrec).opt.index != 0 {
info!("[index:{}]", (*mrec).opt.index);
}
match (*mrec).opt.style {
1 => {
info!("[style:bold]");
}
2 => {
info!("[style:italic]");
}
3 => {
info!("[style:bolditalic]");
}
_ => {}
}
info!("\n");
}
/* _FIXME_
* Font is identified with font_name and point_size as in DVI here.
* However, except for PDF_FONTTYPE_BITMAP, we can share the
* short_name, resource and used_chars between multiple instances
* of the same font at different sizes.
*/
pub unsafe fn pdf_dev_locate_font(font_name: &CStr, ptsize: spt_t) -> i32 {
/* found a dev_font that matches the request */
if ptsize == 0i32 {
panic!("pdf_dev_locate_font() called with the zero ptsize.");
}
let mut i = 0;
while i < num_dev_fonts {
if streq_ptr(font_name.as_ptr(), (*dev_fonts.offset(i as isize)).tex_name) {
if ptsize == (*dev_fonts.offset(i as isize)).sptsize {
return i;
}
if (*dev_fonts.offset(i as isize)).format != 2i32 {
break;
}
/* new dev_font will share pdf resource with /i/ */
}
i += 1
}
/*
* Make sure we have room for a new one, even though we may not
* actually create one.
*/
if num_dev_fonts >= max_dev_fonts {
max_dev_fonts += 16i32;
dev_fonts = renew(
dev_fonts as *mut libc::c_void,
(max_dev_fonts as u32 as u64).wrapping_mul(::std::mem::size_of::<dev_font>() as u64)
as u32,
) as *mut dev_font
}
let font = &mut *dev_fonts.offset(num_dev_fonts as isize) as *mut dev_font;
/* New font */
let mrec = pdf_lookup_fontmap_record(font_name.to_bytes());
if verbose > 1i32 {
print_fontmap(font_name.as_ptr(), mrec);
}
(*font).font_id =
pdf_font_findresource(font_name.as_ptr(), ptsize as f64 * dev_unit.dvi2pts, mrec);
if (*font).font_id < 0i32 {
return -1i32;
}
if !mrec.is_null() {
(*font).cff_charsets = (*mrec).opt.cff_charsets as *mut cff_charsets
}
/* We found device font here. */
if i < num_dev_fonts {
(*font).real_font_index = i; /* NULL terminated here */
strcpy(
(*font).short_name.as_mut_ptr(),
(*dev_fonts.offset(i as isize)).short_name.as_mut_ptr(),
); /* Don't ref obj until font is actually used. */
} else {
(*font).real_font_index = -1i32;
(*font).short_name[0] = 'F' as i32 as i8;
p_itoa(
num_phys_fonts + 1i32,
&mut *(*font).short_name.as_mut_ptr().offset(1),
);
num_phys_fonts += 1
}
(*font).used_on_this_page = 0i32;
(*font).tex_name = new(font_name.to_bytes().len() as u32 + 1) as *mut i8;
strcpy((*font).tex_name, font_name.as_ptr());
(*font).sptsize = ptsize;
match pdf_get_font_subtype((*font).font_id) {
2 => (*font).format = 2i32,
4 => (*font).format = 3i32,
_ => (*font).format = 1i32,
}
(*font).wmode = pdf_get_font_wmode((*font).font_id);
(*font).enc_id = pdf_get_font_encoding((*font).font_id);
(*font).resource = ptr::null_mut();
(*font).used_chars = ptr::null_mut();
(*font).extend = 1.0f64;
(*font).slant = 0.0f64;
(*font).bold = 0.0f64;
(*font).mapc = -1i32;
(*font).is_unicode = 0i32;
(*font).ucs_group = 0i32;
(*font).ucs_plane = 0i32;
if !mrec.is_null() {
(*font).extend = (*mrec).opt.extend;
(*font).slant = (*mrec).opt.slant;
(*font).bold = (*mrec).opt.bold;
if (*mrec).opt.mapc >= 0i32 {
(*font).mapc = (*mrec).opt.mapc >> 8i32 & 0xffi32
} else {
(*font).mapc = -1i32
}
if streq_ptr((*mrec).enc_name, b"unicode\x00" as *const u8 as *const i8) {
(*font).is_unicode = 1i32;
if (*mrec).opt.mapc >= 0i32 {
(*font).ucs_group = (*mrec).opt.mapc >> 24i32 & 0xffi32;
(*font).ucs_plane = (*mrec).opt.mapc >> 16i32 & 0xffi32
} else {
(*font).ucs_group = 0i32;
(*font).ucs_plane = 0i32
}
} else {
(*font).is_unicode = 0i32
}
}
let fresh46 = num_dev_fonts;
num_dev_fonts = num_dev_fonts + 1;
fresh46
}
/* This does not remember current stroking width. */
unsafe fn dev_sprint_line(
buf: &mut [u8],
width: spt_t,
p0_x: spt_t,
p0_y: spt_t,
p1_x: spt_t,
p1_y: spt_t,
) -> usize {
let mut len = 0_usize;
let w = width as f64 * dev_unit.dvi2pts;
len += p_dtoa(
w,
if dev_unit.precision + 1i32 < 8i32 {
dev_unit.precision + 1i32
} else {
8i32
},
&mut buf[len..],
);
buf[len] = b' ';
len += 1;
buf[len] = b'w';
len += 1;
buf[len] = b' ';
len += 1;
len += dev_sprint_bp(&mut buf[len..], p0_x, ptr::null_mut());
buf[len] = b' ';
len += 1;
len += dev_sprint_bp(&mut buf[len..], p0_y, ptr::null_mut());
buf[len] = b' ';
len += 1;
buf[len] = b'm';
len += 1;
buf[len] = b' ';
len += 1;
len += dev_sprint_bp(&mut buf[len..], p1_x, ptr::null_mut());
buf[len] = b' ';
len += 1;
len += dev_sprint_bp(&mut buf[len..], p1_y, ptr::null_mut());
buf[len] = b' ';
len += 1;
buf[len] = b'l';
len += 1;
buf[len] = b' ';
len += 1;
buf[len] = b'S';
len += 1;
len
}
pub unsafe fn pdf_dev_set_rule(mut xpos: spt_t, mut ypos: spt_t, width: spt_t, height: spt_t) {
let mut len = 0_usize;
if num_dev_coords > 0i32 {
xpos -= ((*dev_coords.offset((num_dev_coords - 1i32) as isize)).x / dev_unit.dvi2pts)
.round() as spt_t;
ypos -= ((*dev_coords.offset((num_dev_coords - 1i32) as isize)).y / dev_unit.dvi2pts)
.round() as spt_t
}
graphics_mode();
let fresh59 = len;
len = len + 1;
format_buffer[fresh59 as usize] = b' ';
let fresh60 = len;
len = len + 1;
format_buffer[fresh60 as usize] = b'q';
let fresh61 = len;
len = len + 1;
format_buffer[fresh61 as usize] = b' ';
/* Don't use too thick line. */
let width_in_bp = (if width < height { width } else { height }) as f64 * dev_unit.dvi2pts;
if width_in_bp < 0.0f64 || width_in_bp > 5.0f64 {
let mut rect = Rect::zero();
rect.min.x = dev_unit.dvi2pts * xpos as f64;
rect.min.y = dev_unit.dvi2pts * ypos as f64;
rect.max.x = dev_unit.dvi2pts * width as f64;
rect.max.y = dev_unit.dvi2pts * height as f64;
len += pdf_sprint_rect(&mut format_buffer[len..], &rect);
let fresh62 = len;
len = len + 1;
format_buffer[fresh62 as usize] = b' ';
let fresh63 = len;
len = len + 1;
format_buffer[fresh63 as usize] = b'r';
let fresh64 = len;
len = len + 1;
format_buffer[fresh64 as usize] = b'e';
let fresh65 = len;
len = len + 1;
format_buffer[fresh65 as usize] = b' ';
let fresh66 = len;
len = len + 1;
format_buffer[fresh66 as usize] = b'f'
} else if width > height {
/* NOTE:
* A line width of 0 denotes the thinnest line that can be rendered at
* device resolution. See, PDF Reference Manual 4th ed., sec. 4.3.2,
* "Details of Graphics State Parameters", p. 185.
*/
if height < dev_unit.min_bp_val {
warn!("Too thin line: height={} ({} bp)", height, width_in_bp,);
warn!("Please consider using \"-d\" option.");
}
len += dev_sprint_line(
&mut format_buffer[len..],
height,
xpos,
ypos + height / 2i32,
xpos + width,
ypos + height / 2i32,
) as usize
} else {
if width < dev_unit.min_bp_val {
warn!("Too thin line: width={} ({} bp)", width, width_in_bp,);
warn!("Please consider using \"-d\" option.");
}
len += dev_sprint_line(
&mut format_buffer[len..],
width,
xpos + width / 2i32,
ypos,
xpos + width / 2i32,
ypos + height,
) as usize
}
let fresh67 = len;
len = len + 1;
format_buffer[fresh67 as usize] = b' ';
let fresh68 = len;
len = len + 1;
format_buffer[fresh68 as usize] = b'Q';
pdf_doc_add_page_content(&format_buffer[..len]);
/* op: q re f Q */
}
/* Rectangle in device space coordinate. */
pub unsafe fn pdf_dev_set_rect(
rect: &mut Rect,
x_user: spt_t,
y_user: spt_t,
width: spt_t,
height: spt_t,
depth: spt_t,
) {
let mut p0 = Point::zero();
let mut p1 = Point::zero();
let mut p2 = Point::zero();
let mut p3 = Point::zero();
let dev_x = x_user as f64 * dev_unit.dvi2pts; /* currentmatrix */
let dev_y = y_user as f64 * dev_unit.dvi2pts; /* 0 for B&W */
if text_state.dir_mode != 0 {
p0.x = dev_x - dev_unit.dvi2pts * depth as f64;
p0.y = dev_y - dev_unit.dvi2pts * width as f64;
p1.x = dev_x + dev_unit.dvi2pts * height as f64;
p1.y = p0.y;
p2.x = p1.x;
p2.y = dev_y;
p3.x = p0.x;
p3.y = p2.y
} else {
p0.x = dev_x;
p0.y = dev_y - dev_unit.dvi2pts * depth as f64;
p1.x = dev_x + dev_unit.dvi2pts * width as f64;
p1.y = p0.y;
p2.x = p1.x;
p2.y = dev_y + dev_unit.dvi2pts * height as f64;
p3.x = p0.x;
p3.y = p2.y
}
pdf_dev_transform(&mut p0, None);
pdf_dev_transform(&mut p1, None);
pdf_dev_transform(&mut p2, None);
pdf_dev_transform(&mut p3, None);
let min_x = p0.x.min(p1.x).min(p2.x).min(p3.x);
let max_x = p0.x.max(p1.x).max(p2.x).max(p3.x);
let min_y = p0.y.min(p1.y).min(p2.y).min(p3.y);
let max_y = p0.y.max(p1.y).max(p2.y).max(p3.y);
*rect = Rect::new(point2(min_x, min_y), point2(max_x, max_y));
}
pub unsafe fn pdf_dev_get_dirmode() -> i32 {
text_state.dir_mode
}
pub unsafe fn pdf_dev_set_dirmode(text_dir: i32) {
let font = if text_state.font_id < 0i32 {
ptr::null_mut()
} else {
&mut *dev_fonts.offset(text_state.font_id as isize) as *mut dev_font
};
let vert_font = if !font.is_null() && (*font).wmode != 0 {
1
} else {
0
};
let vert_dir = if dev_param.autorotate != 0 {
text_dir
} else {
vert_font
};
let text_rotate = TextWMode::from(vert_font << 2 | vert_dir);
if !font.is_null() && ANGLE_CHANGES(text_rotate, text_state.matrix.rotate) {
text_state.force_reset = 1i32
}
text_state.matrix.rotate = text_rotate;
text_state.dir_mode = text_dir;
}
unsafe fn dev_set_param_autorotate(auto_rotate: i32) {
let font = if text_state.font_id < 0i32 {
ptr::null_mut()
} else {
&mut *dev_fonts.offset(text_state.font_id as isize) as *mut dev_font
};
let vert_font = if !font.is_null() && (*font).wmode != 0 {
1
} else {
0
};
let vert_dir = if auto_rotate != 0 {
text_state.dir_mode
} else {
vert_font
};
let text_rotate = TextWMode::from(vert_font << 2 | vert_dir);
if ANGLE_CHANGES(text_rotate, text_state.matrix.rotate) {
text_state.force_reset = 1i32
}
text_state.matrix.rotate = text_rotate;
dev_param.autorotate = auto_rotate;
}
pub unsafe fn pdf_dev_get_param(param_type: i32) -> i32 {
match param_type {
1 => dev_param.autorotate,
2 => dev_param.colormode,
_ => {
panic!("Unknown device parameter: {}", param_type);
}
}
}
pub unsafe fn pdf_dev_set_param(param_type: i32, value: i32) {
match param_type {
1 => {
dev_set_param_autorotate(value);
}
2 => dev_param.colormode = value,
_ => {
panic!("Unknown device parameter: {}", param_type);
}
};
}
pub unsafe fn pdf_dev_put_image(
id: i32,
p: &mut transform_info,
mut ref_x: f64,
mut ref_y: f64,
) -> i32 {
let mut r = Rect::zero();
if num_dev_coords > 0i32 {
ref_x -= (*dev_coords.offset((num_dev_coords - 1i32) as isize)).x;
ref_y -= (*dev_coords.offset((num_dev_coords - 1i32) as isize)).y
}
let mut M = p.matrix;
M.m31 += ref_x;
M.m32 += ref_y;
/* Just rotate by -90, but not tested yet. Any problem if M has scaling? */
if dev_param.autorotate != 0 && text_state.dir_mode != 0 {
let tmp = -M.m11;
M.m11 = M.m12;
M.m12 = tmp;
let tmp = -M.m21;
M.m21 = M.m22;
M.m22 = tmp
}
graphics_mode();
pdf_dev_gsave();
let M1 = pdf_ximage_scale_image(id, &mut r, p);
M = M1.post_transform(&M);
pdf_dev_concat(&mut M);
/* Clip */
if p.flags & 1i32 << 3i32 != 0 {
pdf_dev_rectclip(&r); /* op: Do */
}
let res_name = pdf_ximage_get_resname(id);
let len = sprintf(
work_buffer.as_mut_ptr() as *mut i8,
b" /%s Do\x00" as *const u8 as *const i8,
res_name,
) as usize;
pdf_doc_add_page_content(&work_buffer[..len]);
pdf_dev_grestore();
pdf_doc_add_page_resource("XObject", res_name, pdf_ximage_get_reference(id));
if dvi_is_tracking_boxes() {
let mut rect = Rect::zero();
let mut corner: [Point; 4] = [Point::zero(); 4];
pdf_dev_set_rect(
&mut rect,
(65536. * ref_x) as spt_t,
(65536. * ref_y) as spt_t,
(65536. * r.size().width) as spt_t,
(65536. * r.size().height) as spt_t,
0i32,
);
corner[0] = rect.lower_left();
corner[1] = rect.upper_left();
corner[2] = rect.upper_right();
corner[3] = rect.lower_right();
let P = p.matrix;
for c in corner.iter_mut() {
*c -= rect.min.to_vector();
pdf_dev_transform(c, Some(&P));
*c += rect.min.to_vector();
}
rect.min = corner[0];
rect.max = corner[0];
for c in corner.iter() {
if c.x < rect.min.x {
rect.min.x = c.x
}
if c.x > rect.max.x {
rect.max.x = c.x
}
if c.y < rect.min.y {
rect.min.y = c.y
}
if c.y > rect.max.y {
rect.max.y = c.y
}
}
pdf_doc_expand_box(&mut rect);
}
0i32
}
pub unsafe fn transform_info_clear(info: &mut transform_info) {
/* Physical dimensions */
info.width = 0.;
info.height = 0.;
info.depth = 0.;
info.bbox = Rect::zero();
/* Transformation matrix */
info.matrix = TMatrix::identity();
info.flags = 0;
}
pub unsafe fn pdf_dev_begin_actualtext(mut unicodes: *mut u16, mut count: i32) {
let mut pdf_doc_enc = 1_usize;
/* check whether we can use PDFDocEncoding for this string
(we punt on the 0x80..0xA0 range that does not directly correspond to unicode) */
/* if using PDFDocEncoding, we only care about the low 8 bits,
so start with the second byte of our pair */
for i in 0..count {
if *unicodes.offset(i as isize) as i32 > 0xffi32
|| *unicodes.offset(i as isize) as i32 > 0x7fi32
&& (*unicodes.offset(i as isize) as i32) < 0xa1i32
{
pdf_doc_enc = 0;
break;
}
}
graphics_mode();
let mut len = sprintf(
work_buffer.as_mut_ptr() as *mut i8,
b"\n/Span<</ActualText(\x00" as *const u8 as *const i8,
);
if pdf_doc_enc == 0 {
len += sprintf(
(work_buffer.as_mut_ptr() as *mut i8).offset(len as isize),
b"\xfe\xff\x00" as *const u8 as *const i8,
)
}
pdf_doc_add_page_content(&work_buffer[..len as usize]);
loop {
let fresh69 = count;
count = count - 1;
if !(fresh69 > 0i32) {
break;
}
let s: [u8; 2] = (*unicodes).to_be_bytes();
len = 0i32;
for i in pdf_doc_enc..2 {
let c: u8 = s[i];
if c as i32 == '(' as i32 || c as i32 == ')' as i32 || c as i32 == '\\' as i32 {
len += sprintf(
(work_buffer.as_mut_ptr() as *mut i8).offset(len as isize),
b"\\%c\x00" as *const u8 as *const i8,
c as i32,
)
} else if (c as i32) < ' ' as i32 {
len += sprintf(
(work_buffer.as_mut_ptr() as *mut i8).offset(len as isize),
b"\\%03o\x00" as *const u8 as *const i8,
c as i32,
)
} else {
len += sprintf(
(work_buffer.as_mut_ptr() as *mut i8).offset(len as isize),
b"%c\x00" as *const u8 as *const i8,
c as i32,
)
}
}
pdf_doc_add_page_content(&work_buffer[..len as usize]);
unicodes = unicodes.offset(1)
}
len = sprintf(
work_buffer.as_mut_ptr() as *mut i8,
b")>>BDC\x00" as *const u8 as *const i8,
);
pdf_doc_add_page_content(&work_buffer[..len as usize]);
}
/* Not in spt_t. */
/* unit_conv: multiplier for input unit (spt_t) to bp conversion.
* precision: How many fractional digits preserved in output (not real
* accuracy control).
* is_bw: Ignore color related special instructions.
*/
/* returns 1.0/unit_conv */
/* Draw texts and rules:
*
* xpos, ypos, width, and height are all fixed-point numbers
* converted to big-points by multiplying unit_conv (dvi2pts).
* They must be position in the user space.
*
* ctype:
* 0 - input string is in multi-byte encoding.
* 1 - input string is in 8-bit encoding.
* 2 - input string is in 16-bit encoding.
*/
/* Place XObject */
/* The design_size and ptsize required by PK font support...
*/
/* The following two routines are NOT WORKING.
* Dvipdfmx doesn't manage gstate well..
*/
/* Always returns 1.0, please rename this. */
/* Access text state parameters. */
/* ps: special support want this (pTeX). */
/* Text composition (direction) mode
* This affects only when auto_rotate is enabled.
*/
/* Set rect to rectangle in device space.
* Unit conversion spt_t to bp and transformation applied within it.
*/
/* Accessor to various device parameters.
*/
/* Text composition mode is ignored (always same as font's
* writing mode) and glyph rotation is not enabled if
* auto_rotate is unset.
*/
/*
* For pdf_doc, pdf_draw and others.
*/
/* Force reselecting font and color:
* XFrom (content grabbing) and Metapost support want them.
*/
/* Initialization of transformation matrix with M and others.
* They are called within pdf_doc_begin_page() and pdf_doc_end_page().
*/
/* Text is normal and line art is not normal in dvipdfmx. So we don't have
* begin_text (BT in PDF) and end_text (ET), but instead we have graphics_mode()
* to terminate text section. pdf_dev_flushpath() and others call this.
*/
pub unsafe fn pdf_dev_end_actualtext() {
graphics_mode();
pdf_doc_add_page_content(b" EMC");
}
/* The name transform_info is misleading.
* I'll put this here for a moment...
*/
/* Physical dimensions
*
* If those values are given, images will be scaled
* and/or shifted to fit within a box described by
* those values.
*/
/* transform matrix */
/* user_bbox */
pub unsafe fn pdf_dev_reset_global_state() {
dev_fonts = ptr::null_mut();
num_dev_fonts = 0i32;
max_dev_fonts = 0i32;
num_phys_fonts = 0i32;
}
| 32.782885 | 115 | 0.545099 |
2390f10fb51e33e0e948c3d34a3198c0688b9cb7 | 444 | sql | SQL | sos21-database/migrations/20210302103321_add_project_index.sql | sohosai/sos21-backend | f1883844b0e5c68d6b3f9d159c9268142abc81b4 | [
"Apache-2.0",
"MIT"
] | 10 | 2021-03-01T05:27:59.000Z | 2022-03-27T11:52:11.000Z | sos21-database/migrations/20210302103321_add_project_index.sql | sohosai/sos21-backend | f1883844b0e5c68d6b3f9d159c9268142abc81b4 | [
"Apache-2.0",
"MIT"
] | 39 | 2021-03-01T05:03:10.000Z | 2021-11-28T17:56:44.000Z | sos21-database/migrations/20210302103321_add_project_index.sql | sohosai/sos21-backend | f1883844b0e5c68d6b3f9d159c9268142abc81b4 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-11-10T13:12:50.000Z | 2021-11-10T13:12:50.000Z | ALTER TABLE projects ADD COLUMN index smallint UNIQUE CHECK (index BETWEEN 0 AND 999);
UPDATE projects SET index = numbers.index
FROM (SELECT id, (row_number() over () - 1) as index FROM projects)
AS numbers
WHERE projects.id = numbers.id;
ALTER TABLE projects ALTER COLUMN index SET NOT NULL;
CREATE SEQUENCE count_projects AS smallint MINVALUE 0 MAXVALUE 999;
SELECT setval('count_projects', (SELECT count(*) FROM projects), false);
| 44.4 | 86 | 0.763514 |
2ff889dfc6c15c1cdc3a57c85d132c3cf2bca7ec | 5,854 | py | Python | tests/unit/dataset/import_dataset_from_datalake_test.py | abeja-inc/abeja-platform-cli | bed60642ee46656a5bfec5577d876e54c88bfd3f | [
"Apache-2.0"
] | 2 | 2020-06-19T23:07:38.000Z | 2021-06-03T10:44:39.000Z | tests/unit/dataset/import_dataset_from_datalake_test.py | abeja-inc/abeja-platform-cli | bed60642ee46656a5bfec5577d876e54c88bfd3f | [
"Apache-2.0"
] | 20 | 2020-04-07T07:48:42.000Z | 2020-09-07T09:18:43.000Z | tests/unit/dataset/import_dataset_from_datalake_test.py | abeja-inc/abeja-platform-cli | bed60642ee46656a5bfec5577d876e54c88bfd3f | [
"Apache-2.0"
] | 1 | 2021-06-01T13:38:19.000Z | 2021-06-01T13:38:19.000Z | """Tests related to ``model`` and ``deployment``"""
import math
import random
from unittest import TestCase
import requests_mock
from click.testing import CliRunner
from abejacli.config import (
ABEJA_API_URL,
DATASET_CHUNK_SIZE,
ORGANIZATION_ENDPOINT
)
from abejacli.dataset import (
create_request_element,
filter_items_by_max_size,
import_dataset_from_datalake,
register_dataset_items
)
DATASET_ID = 1
CHANNEL_ID = '1111111111111'
FILE_ID = '20180306T062909-e5d12928-36b6-4b84-bb33-e3e298034550'
METADATA_LABEL_KEY = 'label'
METADATA_LABEL_VALUE = 'cat'
METADATA_LABEL_ID_KEY = 'label_id'
METADATA_LABEL_ID_VALUE = '1'
CATEGORY_ID = 1
DATALAKE_FILE_RESPONSE = {
'url_expires_on': '2018-03-15T09:04:28+00:00',
'uploaded_at': '2018-03-06T06:29:09+00:00',
'metadata': {
'x-abeja-meta-{}'.format(METADATA_LABEL_KEY): METADATA_LABEL_VALUE,
'x-abeja-meta-{}'.format(METADATA_LABEL_ID_KEY): METADATA_LABEL_ID_VALUE,
'x-abeja-meta-filename': '000000060482.jpg'
},
'file_id': FILE_ID,
'download_uri': 'https://abeja-datalake-dev.s3.amazonaws.com/e498-1379786645868/20180306/'
'062909-e5d12928-36b6-4b84-bb33-e3e298034550?AWSAccessKeyId=ASIAJUSKQAOZ67OHU3NQ&Signature=xxxx',
'content_type': 'image/jpeg'
}
DATASET_ITEM_RESPONSE = {
'dataset_id': DATASET_ID,
'source_data': [
{
'data_type': 'image/jpeg',
'data_uri': 'datalake://1234567890123/20170815T044617-f20dde80-1e3b-4496-bc06-1b63b026b872'
}
],
'attributes': {
'classification': [
{
'category_id': CATEGORY_ID,
METADATA_LABEL_KEY: METADATA_LABEL_VALUE,
METADATA_LABEL_ID_KEY: METADATA_LABEL_ID_VALUE
}
]
}
}
class DatasetImportFromDatalakeTest(TestCase):
def setUp(self):
self.runner = CliRunner()
def test_create_request_element(self):
expected = {
'source_data': [{
'data_uri': 'datalake://{}/{}'.format(CHANNEL_ID, FILE_ID),
'data_type': 'image/jpeg'
}],
'attributes': {
'classification': [
{
'category_id': CATEGORY_ID,
METADATA_LABEL_KEY: METADATA_LABEL_VALUE,
METADATA_LABEL_ID_KEY: METADATA_LABEL_ID_VALUE
}
]
}
}
actual = create_request_element(
CHANNEL_ID, DATALAKE_FILE_RESPONSE,
[METADATA_LABEL_KEY, METADATA_LABEL_ID_KEY],
CATEGORY_ID, 'classification'
)
self.assertEqual(actual, expected)
@requests_mock.Mocker()
def test_register_dataset_items(self, mock):
url = '{}/datasets/{}/items'.format(ORGANIZATION_ENDPOINT, DATASET_ID)
mock.register_uri('POST', url, json=DATASET_ITEM_RESPONSE)
item_count = 1501
dataset_items = [DATASET_ITEM_RESPONSE for _ in range(item_count)]
register_dataset_items(DATASET_ID, dataset_items)
expected_request_count = math.ceil(item_count / DATASET_CHUNK_SIZE)
self.assertEqual(expected_request_count, len(mock.request_history))
def test_filter_items_by_max_size(self):
def generate_labeled_dataset_item(label):
return {
'source_data': [{
'data_uri': 'datalake://{}/{}'.format(CHANNEL_ID, FILE_ID),
'data_type': 'image/jpeg'
}],
'attributes': {
'classification': [
{
'label': label,
}
]
}
}
label1 = '1'
label1_count = 10
label1_items = [generate_labeled_dataset_item(
label1) for _ in range(label1_count)]
label2 = '2'
label2_count = 11
label2_items = [generate_labeled_dataset_item(
label2) for _ in range(label2_count)]
label3 = '3'
label3_count = 9
label3_items = [generate_labeled_dataset_item(
label3) for _ in range(label3_count)]
dataset_items = label1_items + label2_items + label3_items
random.shuffle(dataset_items)
filtered_dataset_items = filter_items_by_max_size(dataset_items, 10)
self.assertEqual(10, sum(label1 == i['attributes']['classification'][0]['label']
for i in filtered_dataset_items))
self.assertEqual(10, sum(label2 == i['attributes']['classification'][0]['label']
for i in filtered_dataset_items))
self.assertEqual(9, sum(label3 == i['attributes']['classification'][0]['label']
for i in filtered_dataset_items))
@requests_mock.Mocker()
def test_register_dataset_items_from_datalake(self, mock):
url = '{}/channels/{}'.format(ABEJA_API_URL, CHANNEL_ID)
file_list_response = {
'files': [
DATALAKE_FILE_RESPONSE,
DATALAKE_FILE_RESPONSE
]
}
mock.register_uri('GET', url, json=file_list_response)
url = '{}/datasets/{}/items'.format(ORGANIZATION_ENDPOINT, DATASET_ID)
mock.register_uri('POST', url, json=DATASET_ITEM_RESPONSE)
result = import_dataset_from_datalake(
CHANNEL_ID, DATASET_ID,
[METADATA_LABEL_KEY, METADATA_LABEL_ID_KEY], CATEGORY_ID,
'classification', 30
)
expected = {
'result': 'success',
'dataset_items': len(file_list_response['files']),
'dataset_id': DATASET_ID,
'channel_id': CHANNEL_ID
}
self.assertEqual(expected, result)
| 34.034884 | 117 | 0.597882 |
d6d5e7de34ad580979de28b44fcabcdae522c49d | 5,204 | sql | SQL | contrib/pgcrypto/pgcrypto--1.2.sql | carloszab/postgresfc | 7ccf1bd18a6ac96a4efbe58f01d1aa5352c691b1 | [
"PostgreSQL"
] | 63 | 2016-08-14T19:07:40.000Z | 2022-03-14T22:55:43.000Z | contrib/pgcrypto/pgcrypto--1.2.sql | carloszab/postgresfc | 7ccf1bd18a6ac96a4efbe58f01d1aa5352c691b1 | [
"PostgreSQL"
] | 6 | 2016-04-11T14:08:36.000Z | 2018-11-11T01:41:42.000Z | contrib/pgcrypto/pgcrypto--1.2.sql | carloszab/postgresfc | 7ccf1bd18a6ac96a4efbe58f01d1aa5352c691b1 | [
"PostgreSQL"
] | 14 | 2017-01-12T11:09:09.000Z | 2019-04-19T09:58:20.000Z | /* contrib/pgcrypto/pgcrypto--1.2.sql */
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION pgcrypto" to load this file. \quit
CREATE FUNCTION digest(text, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_digest'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION digest(bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_digest'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION hmac(text, text, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_hmac'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION hmac(bytea, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_hmac'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION crypt(text, text)
RETURNS text
AS 'MODULE_PATHNAME', 'pg_crypt'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION gen_salt(text)
RETURNS text
AS 'MODULE_PATHNAME', 'pg_gen_salt'
LANGUAGE C VOLATILE STRICT;
CREATE FUNCTION gen_salt(text, int4)
RETURNS text
AS 'MODULE_PATHNAME', 'pg_gen_salt_rounds'
LANGUAGE C VOLATILE STRICT;
CREATE FUNCTION encrypt(bytea, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_encrypt'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION decrypt(bytea, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_decrypt'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION encrypt_iv(bytea, bytea, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_encrypt_iv'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION decrypt_iv(bytea, bytea, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_decrypt_iv'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION gen_random_bytes(int4)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_random_bytes'
LANGUAGE C VOLATILE STRICT;
CREATE FUNCTION gen_random_uuid()
RETURNS uuid
AS 'MODULE_PATHNAME', 'pg_random_uuid'
LANGUAGE C VOLATILE;
--
-- pgp_sym_encrypt(data, key)
--
CREATE FUNCTION pgp_sym_encrypt(text, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_sym_encrypt_text'
LANGUAGE C STRICT;
CREATE FUNCTION pgp_sym_encrypt_bytea(bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_sym_encrypt_bytea'
LANGUAGE C STRICT;
--
-- pgp_sym_encrypt(data, key, args)
--
CREATE FUNCTION pgp_sym_encrypt(text, text, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_sym_encrypt_text'
LANGUAGE C STRICT;
CREATE FUNCTION pgp_sym_encrypt_bytea(bytea, text, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_sym_encrypt_bytea'
LANGUAGE C STRICT;
--
-- pgp_sym_decrypt(data, key)
--
CREATE FUNCTION pgp_sym_decrypt(bytea, text)
RETURNS text
AS 'MODULE_PATHNAME', 'pgp_sym_decrypt_text'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION pgp_sym_decrypt_bytea(bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_sym_decrypt_bytea'
LANGUAGE C IMMUTABLE STRICT;
--
-- pgp_sym_decrypt(data, key, args)
--
CREATE FUNCTION pgp_sym_decrypt(bytea, text, text)
RETURNS text
AS 'MODULE_PATHNAME', 'pgp_sym_decrypt_text'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION pgp_sym_decrypt_bytea(bytea, text, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_sym_decrypt_bytea'
LANGUAGE C IMMUTABLE STRICT;
--
-- pgp_pub_encrypt(data, key)
--
CREATE FUNCTION pgp_pub_encrypt(text, bytea)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_pub_encrypt_text'
LANGUAGE C STRICT;
CREATE FUNCTION pgp_pub_encrypt_bytea(bytea, bytea)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_pub_encrypt_bytea'
LANGUAGE C STRICT;
--
-- pgp_pub_encrypt(data, key, args)
--
CREATE FUNCTION pgp_pub_encrypt(text, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_pub_encrypt_text'
LANGUAGE C STRICT;
CREATE FUNCTION pgp_pub_encrypt_bytea(bytea, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_pub_encrypt_bytea'
LANGUAGE C STRICT;
--
-- pgp_pub_decrypt(data, key)
--
CREATE FUNCTION pgp_pub_decrypt(bytea, bytea)
RETURNS text
AS 'MODULE_PATHNAME', 'pgp_pub_decrypt_text'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION pgp_pub_decrypt_bytea(bytea, bytea)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_pub_decrypt_bytea'
LANGUAGE C IMMUTABLE STRICT;
--
-- pgp_pub_decrypt(data, key, psw)
--
CREATE FUNCTION pgp_pub_decrypt(bytea, bytea, text)
RETURNS text
AS 'MODULE_PATHNAME', 'pgp_pub_decrypt_text'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION pgp_pub_decrypt_bytea(bytea, bytea, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_pub_decrypt_bytea'
LANGUAGE C IMMUTABLE STRICT;
--
-- pgp_pub_decrypt(data, key, psw, arg)
--
CREATE FUNCTION pgp_pub_decrypt(bytea, bytea, text, text)
RETURNS text
AS 'MODULE_PATHNAME', 'pgp_pub_decrypt_text'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION pgp_pub_decrypt_bytea(bytea, bytea, text, text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pgp_pub_decrypt_bytea'
LANGUAGE C IMMUTABLE STRICT;
--
-- PGP key ID
--
CREATE FUNCTION pgp_key_id(bytea)
RETURNS text
AS 'MODULE_PATHNAME', 'pgp_key_id_w'
LANGUAGE C IMMUTABLE STRICT;
--
-- pgp armor
--
CREATE FUNCTION armor(bytea)
RETURNS text
AS 'MODULE_PATHNAME', 'pg_armor'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION armor(bytea, text[], text[])
RETURNS text
AS 'MODULE_PATHNAME', 'pg_armor'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION dearmor(text)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_dearmor'
LANGUAGE C IMMUTABLE STRICT;
CREATE FUNCTION pgp_armor_headers(text, key OUT text, value OUT text)
RETURNS SETOF record
AS 'MODULE_PATHNAME', 'pgp_armor_headers'
LANGUAGE C IMMUTABLE STRICT;
| 23.87156 | 74 | 0.795158 |
586b2adbebedbfc6e0001fb35dded98f54a627fb | 380 | rb | Ruby | lib/redcap2omop/methods/models/redcap_event.rb | NUARIG/redcap2omop | 31a3b2a1b88d6a8374419f51b57ad9d65820e1f0 | [
"MIT"
] | 2 | 2021-02-23T22:18:44.000Z | 2021-09-08T01:04:54.000Z | lib/redcap2omop/methods/models/redcap_event.rb | NUARIG/redcap2omop | 31a3b2a1b88d6a8374419f51b57ad9d65820e1f0 | [
"MIT"
] | 51 | 2020-11-10T12:29:03.000Z | 2021-07-24T10:03:59.000Z | lib/redcap2omop/methods/models/redcap_event.rb | NUARIG/redcap2omop | 31a3b2a1b88d6a8374419f51b57ad9d65820e1f0 | [
"MIT"
] | null | null | null | module Redcap2omop::Methods::Models::RedcapEvent
def self.included(base)
base.send :include, Redcap2omop::SoftDelete
# Associations
base.send :belongs_to, :redcap_data_dictionary
base.send :has_many, :redcap_event_maps
base.send :include, InstanceMethods
base.extend(ClassMethods)
end
module InstanceMethods
end
module ClassMethods
end
end
| 20 | 50 | 0.747368 |
278eb027059177732b1aaf1ea6f5e1a0f562d4c2 | 1,133 | rs | Rust | derive/src/lib.rs | MathieuTricoire/identifier | 3ad560617205265c9512574f5156b47e4be6c22e | [
"Apache-2.0",
"MIT"
] | 3 | 2020-11-20T05:02:55.000Z | 2022-02-13T16:42:18.000Z | derive/src/lib.rs | MathieuTricoire/identifier | 3ad560617205265c9512574f5156b47e4be6c22e | [
"Apache-2.0",
"MIT"
] | null | null | null | derive/src/lib.rs | MathieuTricoire/identifier | 3ad560617205265c9512574f5156b47e4be6c22e | [
"Apache-2.0",
"MIT"
] | 1 | 2021-02-11T06:46:24.000Z | 2021-02-11T06:46:24.000Z | mod identifier;
mod internals;
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Identifier, attributes(identifier))]
pub fn derive_identifier(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
identifier::expand_derive_identifier(&input)
.unwrap_or_else(to_compile_errors)
.into()
}
#[proc_macro_derive(Display)]
pub fn derive_display(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
identifier::expand_derive_display(&input)
.unwrap_or_else(to_compile_errors)
.into()
}
#[proc_macro_derive(FromStr)]
pub fn derive_from_str(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
identifier::expand_derive_from_str(&input)
.unwrap_or_else(to_compile_errors)
.into()
}
fn to_compile_errors(errors: Vec<syn::Error>) -> proc_macro2::TokenStream {
let compile_errors = errors.iter().map(syn::Error::to_compile_error);
quote!(#(#compile_errors)*)
}
| 29.815789 | 75 | 0.733451 |
699da0c85ebc4ed066f1f6d4a5cf0103b2e74249 | 440 | rb | Ruby | config/environment.rb | fabienlimzk/sei23-project-three-lunch-buddy | 29eb279c7d6727d260e820a30343f44dc99c145e | [
"FSFAP"
] | null | null | null | config/environment.rb | fabienlimzk/sei23-project-three-lunch-buddy | 29eb279c7d6727d260e820a30343f44dc99c145e | [
"FSFAP"
] | null | null | null | config/environment.rb | fabienlimzk/sei23-project-three-lunch-buddy | 29eb279c7d6727d260e820a30343f44dc99c145e | [
"FSFAP"
] | null | null | null | # Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
# SMTP settings for gmail
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => ENV['gmail_username'],
:password => ENV['gmail_password'],
:authentication => "plain",
:enable_starttls_auto => true
} | 29.333333 | 49 | 0.622727 |
2fc46d8307244629aad2c8b5503e2a8f6924a734 | 384 | py | Python | art_gallery/point.py | chaitan94/2d-visibility-optimization | 2d1cc4aee18265814b072d89560284086680965d | [
"MIT"
] | null | null | null | art_gallery/point.py | chaitan94/2d-visibility-optimization | 2d1cc4aee18265814b072d89560284086680965d | [
"MIT"
] | null | null | null | art_gallery/point.py | chaitan94/2d-visibility-optimization | 2d1cc4aee18265814b072d89560284086680965d | [
"MIT"
] | null | null | null | class Point:
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def collinear(self, p, q):
if p.x - self.x == 0 and q.x - self.x == 0:
return True
if p.x - self.x == 0 or q.x - self.x == 0:
return False
m1 = (p.y-self.y)/(p.x-self.x)
m2 = (q.y-self.y)/(q.x-self.x)
return m1 == m2
def __str__(self):
return "Point [%f, %f]" % (self.x, self.y)
| 22.588235 | 46 | 0.541667 |
4421f80394e045cf88406b4aa3a4e8476cf69b79 | 1,225 | py | Python | ads/migrations/0003_auto_20160218_2343.py | japsu/tracontent | 169fe84c49c1a30133e927f1be50abba171ebe68 | [
"PostgreSQL",
"Unlicense",
"MIT"
] | null | null | null | ads/migrations/0003_auto_20160218_2343.py | japsu/tracontent | 169fe84c49c1a30133e927f1be50abba171ebe68 | [
"PostgreSQL",
"Unlicense",
"MIT"
] | 7 | 2020-11-26T18:41:07.000Z | 2022-01-18T09:27:00.000Z | ads/migrations/0003_auto_20160218_2343.py | tracon/tracontent | 65bd8c15b7909a90ebe5ed28cbbf66683a4e3c2c | [
"MIT",
"PostgreSQL",
"Unlicense"
] | null | null | null | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ads', '0002_site_m2m'),
]
operations = [
migrations.AlterField(
model_name='banner',
name='active',
field=models.BooleanField(default=True, help_text=b'Voit piilottaa bannerin poistamatta sit\xc3\xa4 ottamalla t\xc3\xa4st\xc3\xa4 ruksin pois.', verbose_name=b'Aktiivinen'),
),
migrations.AlterField(
model_name='banner',
name='title',
field=models.CharField(help_text=b'Esimerkiksi mainostettavan yrityksen tai sivuston nimi. N\xc3\xa4ytet\xc3\xa4\xc3\xa4n alt- ja hover-tekstin\xc3\xa4.', max_length=1023, verbose_name=b'Otsikko'),
),
migrations.AlterField(
model_name='banner',
name='url',
field=models.CharField(help_text=b'Bannerin klikkaaja ohjataan t\xc3\xa4h\xc3\xa4n osoitteeseen.', max_length=1023, verbose_name=b'Osoite'),
),
migrations.AlterField(
model_name='bannerclick',
name='date',
field=models.DateField(verbose_name=b'P\xc3\xa4iv\xc3\xa4m\xc3\xa4\xc3\xa4r\xc3\xa4'),
),
]
| 38.28125 | 209 | 0.63102 |
0cf1db801568036532c7cde0681a2431bd3b07e7 | 252 | rb | Ruby | spec/station_spec.rb | TiagoManuelPC/Oystercard | 63bcfa9391d6612481c47c1a28ef74b3c6a9fe60 | [
"MIT"
] | null | null | null | spec/station_spec.rb | TiagoManuelPC/Oystercard | 63bcfa9391d6612481c47c1a28ef74b3c6a9fe60 | [
"MIT"
] | null | null | null | spec/station_spec.rb | TiagoManuelPC/Oystercard | 63bcfa9391d6612481c47c1a28ef74b3c6a9fe60 | [
"MIT"
] | null | null | null | require 'station'
describe Station do
subject(:station) {described_class.new("London", 1)}
it 'has a name' do
expect(station.name).to eq("London")
end
it' has a zone' do
expect(station.zone).to eq(1)
end
end | 16.8 | 56 | 0.603175 |
05df34fc367e1ccca6387acc1b54ed269d52abe7 | 21 | py | Python | openstack_dashboard/dashboards/admin/systemlogs/__init__.py | xuweiliang/Codelibrary | 54e45b2daa205132c05b0ff5a2c3db7fca2853a7 | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/dashboards/admin/systemlogs/__init__.py | xuweiliang/Codelibrary | 54e45b2daa205132c05b0ff5a2c3db7fca2853a7 | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/dashboards/admin/systemlogs/__init__.py | xuweiliang/Codelibrary | 54e45b2daa205132c05b0ff5a2c3db7fca2853a7 | [
"Apache-2.0"
] | null | null | null | __author__ = 'Zero'
| 10.5 | 20 | 0.666667 |
2003c19caf4c21741f7293766b0ae3d9eef44f56 | 11,896 | py | Python | byconeer/biosamplesInserter.py | sofiapfund/bycon | d7993eaf99cfce46f3025718ab3aa3c0f812badd | [
"CC0-1.0"
] | null | null | null | byconeer/biosamplesInserter.py | sofiapfund/bycon | d7993eaf99cfce46f3025718ab3aa3c0f812badd | [
"CC0-1.0"
] | 1 | 2021-03-18T12:17:59.000Z | 2021-03-18T12:19:24.000Z | byconeer/biosamplesInserter.py | sofiapfund/bycon | d7993eaf99cfce46f3025718ab3aa3c0f812badd | [
"CC0-1.0"
] | null | null | null | #!/usr/local/bin/python3
import re, argparse
import datetime, time
import sys, base36
import json
import pandas as pd
from pymongo import MongoClient
import random
from os import path, environ, pardir
from progress.bar import Bar
from pydoc import locate
# from jsonschema import validate
# local
dir_path = path.dirname( path.abspath(__file__) )
pkg_path = path.join( dir_path, pardir )
sys.path.append( pkg_path )
from beaconServer.lib.read_specs import *
from beaconServer.lib.parse_filters import *
from beaconServer.lib.service_utils import *
from lib.table_tools import *
"""
## `newSampleInserter`
"""
################################################################################
################################################################################
def _get_args(byc):
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--test', help='No. of samples for test run')
parser.add_argument('-d', '--output_db', help='the database to write into.')
parser.add_argument('-s', '--source', help='which repo is input data from')
byc.update({"args": parser.parse_args() })
return byc
################################################################################
def main():
biosamples_inserter()
################################################################################
def biosamples_inserter():
curr_time = datetime.datetime.now()
byc = initialize_service()
_get_args(byc)
if not byc['args'].source in byc["these_prefs"]['data_sources']:
print( 'No accepted "--source" data source has been provided...')
exit()
table_prefs = read_local_prefs( "datatables", dir_path )
for d_k, d_v in table_prefs.items():
byc.update( { d_k: d_v } )
# TODO: check for import_path
# ... prompt for continuation w/ Q "new dataset ??? etc."
################################################################################
### read in meta table
metapath = path.join(byc['import_path'])
mytable = pd.read_csv(metapath, sep = '\t', dtype = str)
mytable = mytable.where((pd.notnull(mytable)), None) ## convert pd.nan to None
### define list/dictionary of objects to insert in 4 collections
variants_list = []
callsets_dict = {}
biosamples_dict = {}
individuals_dict = {}
### find all existing ids in each output database and collections.
exist_callset_id = {}
exist_biosample_id = {}
exist_individual_id = {}
mongo_client = MongoClient( )
ds_id = byc['args'].output_db
data_db = mongo_client[ds_id]
exist_callset_id[ds_id] = data_db.callsets.distinct('info.legacy_id')
exist_biosample_id[ds_id] = data_db.biosamples.distinct('info.legacy_id')
exist_individual_id[ds_id] = data_db.individuals.distinct('info.legacy_id')
no_row = mytable.shape[0]
if byc['args'].test:
test = int(byc['args'].test)
bar_length = test
rdm_row = random.sample(range(no_row), test)
mytable = mytable.iloc[rdm_row, :]
print( f"TEST MODE for {test} of samples.")
else:
bar_length = no_row
bar = Bar("Reading in metadata table", max = bar_length, suffix="%(percent)d%%"+" of "+str(bar_length) )
for row in mytable.itertuples():
if row.loc['status'].startswith('excluded'):
continue
### assign variables from info fields
info_field = {}
column_names = io_table_header( **byc )
field_to_db = io_map_to_db( **byc )
bs = 'biosamples'
cs = 'callsets'
ind = 'individuals'
for field in column_names:
if field in row:
if field in field_to_db:
info_field[field_to_db[field][0]][field] = row.loc[field]
else:
info_field[field] = row.loc[field]
if byc['args'].source == 'arrayexpress':
info_field['uid'] = 'AE-'+ info_field['experiment'].replace('E-','').replace('-','_') + '-' +\
info_field['uid'].replace("-", "_").replace(' ', '_').replace('.CEL','') + '-' +\
byc['platform_rename'][info_field['platform_id']] ## initial rename
# TODO: default should **not** be blood but rather icdot-C76.9: ill-defined
if not info_field[bs]['icdot::id']:
info_field[bs]['icdot::id'] = 'C42.0'
if not info_field[bs]['icdot::label']:
info_field[bs]['icdot::label'] = 'Blood'
if info_field[bs]['icdom::id']:
info_field[bs]['icdom::id'] = info_field[bs]['icdom::id'].replace('/','')
else:
info_field[bs]['icdom::id'] = '00000'
info_field[bs]['icdom::label'] = 'Normal'
if not 'description' in info_field:
info_field[bs]['description'] = ''
if 'age_iso' not in info_field[bs] and info_field['age']:
try:
# TODO: separate method; also e.g. using a split or regex after stringify
age = int(info_field['age'])
info_field[bs]['age_iso'] = 'P'+str(v)+'Y'
except ValueError:
age = float(info_field['age'])
rem_age = age - int(age)
info_field[bs]['age_iso'] = 'P'+str(int(age)) +'Y'+ str(round(rem_age*12)) + 'M'
if 'PATO::id' not in info_field[ind] and info_field['sex']:
sex = info_field['sex'].lower()
if sex == 'female':
info_field[ind]['PATO::id'] = 'PATO:0020002'
info_field[ind]['PATO::label'] = 'female genotypic sex'
elif sex == 'male':
info_field[ind]['PATO::id'] = 'PATO:0020001'
info_field[ind]['PATO::label'] = 'male genotypic sex'
### derived attributes that are shared by collections
info_field[bs]['legacy_id'] = 'PGX_AM_BS_' + info_field['uid']
info_field[cs]['legacy_id'] = 'pgxcs::{}::{}'.format(info_field['experiment'], info_field['uid'])
info_field[ind]['legacy_id'] = 'PGX_IND_' + info_field['uid']
info_field[bs]['id'] = _generate_id('pgxbs')
info_field[cs]['id'] = _generate_id('pgxcs')
info_field[cs]['biosample_id'] = info_field[bs]['id']
info_field[ind]['id'] = _generate_id('pgxind')
info_field[bs]['individual_id'] = info_field[ind]['id']
info_field[bs]['EFO::id'] = 'EFO:0009654' if info_field[bs]['icdom::id'] == '00000' else 'EFO:0009656'
info_field[bs]['EFO::label'] = 'reference sample' if info_field[bs]['icdom::id'] == '00000' else 'neoplastic sample'
info_field[ind]['NCBITaxon::id'] = 'NCBITaxon:9606'
info_field[ind]['NCBITaxon::label'] = 'Homo sapiens'
for collection in [bs, cs, ind]:
info_field[collection]['DUO::id'] = 'DUO:0000004'
info_field[collection]['DUO::label'] = 'no restriction'
############################
## variants & callsets ##
############################
variants, callset = _initiate_vs_cs(info_field['experiment'], info_field['uid'], **byc)
## variants
for variant in variants:
variant['callset_id'] = info_field[cs]['id']
variant['biosample_id'] = info_field[bs]['id']
variant['updated'] = curr_time
variants_list.append(variants)
## callsets
for k,v in info_field[cs].items():
db_key, attr_type = field_to_db['.'.join([cs,k])]
assign_nested_value(callset, db_key, locate(attr_type)(v))
if info_field['platform_id']:
callset['description'] = _retrievePlatformLabel(mongo_client, info_field['platform_id'])
callsets_dict[info_field[cs]['legacy_id']] = callset
############################
###### biosamples #######
############################
biosample= {
'updated': curr_time,
}
if byc['args']['source'] == 'arrayexpress':
info_field[bs][bs+'.'+'arrayexpress::id'] = 'arrayexpress:'+ info_field['experiment'],
biosample['project_id'] = 'A' + info_field['experiment']
for k,v in info_field[bs].items():
db_key, attr_type = field_to_db['.'.join([bs,k])]
assign_nested_value(biosample, db_key, locate(attr_type)(v))
biosamples_dict[info_field[bs]['legacy_id']] = biosample
############################
###### individuals ######
############################
individual = {
'updated': curr_time
}
for k,v in info_field[ind].items():
db_key, attr_type = field_to_db['.'.join([ind,k])]
assign_nested_value(individual, db_key, locate(attr_type)(v))
individuals_dict[info_field[ind]['legacy_id']] = individual
bar.next()
bar.finish()
############################
### database write-in ###
############################
confirm = input("""Processed {} variants, {} callsets, {} biosamples and {} individuals for update.
Do you want to continue? [y/n]""".format(sum([len(v) for v in variants_list]), len(callsets_dict), len(biosamples_dict),
len(individuals_dict)))
update = input("""In case of existing record (matching info.legacy_id). Do you want to update? [y/n] """)
if confirm == 'y':
for variant_obj in variants_list:
try:
data_db.variants.insert_many(variant_obj)
except TypeError:
pass
for callset_id_leg, callset_obj in callsets_dict.items():
if (not update) and (callset_id_leg in exist_callset_id[ds_id]):
continue
data_db.callsets.insert_one(callset_obj)
for biosample_id_leg, biosample_obj in biosamples_dict.items():
if (not update) and (biosample_id_leg in exist_biosample_id[ds_id]):
continue
data_db.biosamples.insert_one(biosample_obj)
for individual_id_leg, individual_obj in individuals_dict.items():
if (not update) and (individual_id_leg in exist_individual_id[ds_id]):
continue
data_db.individuals.insert_one(individual_obj)
################################################################################
################################################################################
def _generate_id(prefix):
time.sleep(.001)
return '{}-{}'.format(prefix, base36.dumps(int(time.time() * 1000))) ## for time in ms
################################################################################
def _initiate_vs_cs(ser, arr, **byc):
## variant collections
# TODO: use path.join( )
v_j_p == path.join(byc['json_file_root'], ser, arr, "variants.json")
with open(v_j_p) as json_data:
variants_json = json.load(json_data)
variant_obj = []
for v in variants_json:
v.pop('no', None)
v['info']['cnv_value'] = v['info'].pop('value')
v['info']['var_length'] = v['info'].pop('svlen')
v['info'].pop('probes', None)
v['variantset_id'] = 'AM_VS_GRCH38'
variant_obj.append(v)
## callset collections
# TODO: use path.join( )
cs_j_p == path.join(byc['json_file_root'], ser, arr, "callset.json")
with open(cs_j_p) as json_data:
callset_json = json.load(json_data)
callset_json.pop('callset_id', None)
callset_obj = callset_json
return variant_obj, callset_obj
################################################################################
################################################################################
################################################################################
if __name__ == '__main__':
main()
| 37.05919 | 124 | 0.534633 |
4f12b4f46d6ad3adca1a17ab34476ea9986d807b | 826 | kt | Kotlin | kotlin-js-action/src/main/kotlin/internal/artifact/artifact-client.module_@actions_artifact.kt | rnett/kotlin-js-action | 6b596b2fbb08c786b454cd93a2936daa891608bb | [
"Apache-2.0"
] | 7 | 2021-05-06T20:28:20.000Z | 2022-01-21T12:21:01.000Z | kotlin-js-action/src/main/kotlin/internal/artifact/artifact-client.module_@actions_artifact.kt | rnett/kotlin-js-action | 6b596b2fbb08c786b454cd93a2936daa891608bb | [
"Apache-2.0"
] | null | null | null | kotlin-js-action/src/main/kotlin/internal/artifact/artifact-client.module_@actions_artifact.kt | rnett/kotlin-js-action | 6b596b2fbb08c786b454cd93a2936daa891608bb | [
"Apache-2.0"
] | null | null | null | @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
@file:JsModule("@actions/artifact")
@file:JsNonModule
package internal.artifact
import com.rnett.action.artifact.DownloadResponse
import com.rnett.action.artifact.UploadResponse
import kotlin.js.Promise
internal external interface ArtifactClient {
fun uploadArtifact(name: String, files: Array<String>, rootDirectory: String, options: UploadOptions = definedExternally): Promise<UploadResponse>
fun downloadArtifact(name: String, path: String = definedExternally, options: DownloadOptions = definedExternally): Promise<DownloadResponse>
fun downloadAllArtifacts(path: String = definedExternally): Promise<Array<DownloadResponse>>
}
internal external fun create(): ArtifactClient | 48.588235 | 150 | 0.822034 |
7facd65cf38831c966997e9994e677abf8b5e569 | 1,288 | php | PHP | platform/common/Helpers/file_type_icons_helper.php | krishnaguragain/ciWebApp | 4d68513a22553028e95d0fe917f356c0a49c78d7 | [
"MIT"
] | 4 | 2020-06-01T04:20:06.000Z | 2021-02-25T01:48:11.000Z | platform/common/Helpers/file_type_icons_helper.php | krishnaguragain/ciWebApp | 4d68513a22553028e95d0fe917f356c0a49c78d7 | [
"MIT"
] | 8 | 2020-06-06T00:40:49.000Z | 2021-04-28T09:13:05.000Z | platform/common/Helpers/file_type_icons_helper.php | krishnaguragain/ciWebApp | 4d68513a22553028e95d0fe917f356c0a49c78d7 | [
"MIT"
] | 2 | 2020-06-01T04:20:12.000Z | 2020-08-06T02:22:15.000Z | <?php
if (!function_exists('file_type_icon')) {
function file_type_icon($path = null) {
static $_icons;
if (!isset($_icons)) {
$icons = config('FileTypeIcons')->icons;
$_icons = [];
if (!empty($icons)) {
foreach ($icons as $key => $icon) {
if (is_array($icon)) {
foreach ($icon as $i) {
$_icons[(string) $i] = $key;
}
} else {
$_icons[(string) $icon] = $key;
}
}
}
}
if ($path === null) {
return $_icons;
}
$ext = extension($path);
if (isset($_icons[$ext])) {
return $_icons[$ext];
}
return null;
}
}
if (!function_exists('file_type_icon_fa')) {
function file_type_icon_fa($path) {
$result = file_type_icon($path);
if (is_array($result)) {
foreach ($result as $key => & $value) {
$value = 'fa-file-'.$value;
}
return $result;
}
if ($result == '') {
return 'fa-file';
}
return 'fa-file-'.$result;
}
}
| 18.666667 | 56 | 0.384317 |
57e4a0617afe52a211190946c56ce6c3053d14f1 | 2,040 | php | PHP | app/Models/Category.php | iamsuzon/thornior-alternative | 768adf1d23d44210ca728db2e86acff1420bae2e | [
"MIT"
] | null | null | null | app/Models/Category.php | iamsuzon/thornior-alternative | 768adf1d23d44210ca728db2e86acff1420bae2e | [
"MIT"
] | null | null | null | app/Models/Category.php | iamsuzon/thornior-alternative | 768adf1d23d44210ca728db2e86acff1420bae2e | [
"MIT"
] | null | null | null | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Category extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'name',
'slug',
'status'
];
public function image_post_1()
{
return $this->morphedByMany(ImagePostTemplateOne::class, 'taggable');
}
public function image_post_2()
{
return $this->morphedByMany(ImagePostTemplateTwo::class, 'taggable');
}
public function image_post_3()
{
return $this->morphedByMany(ImagePostTemplateThree::class, 'taggable');
}
public function image_post_4()
{
return $this->morphedByMany(ImagePostTemplateFour::class, 'taggable');
}
public function image_post_5()
{
return $this->morphedByMany(ImagePostTemplateFive::class, 'taggable');
}
public function image_post_6()
{
return $this->morphedByMany(ImagePostTemplateSix::class, 'taggable');
}
public function video_post_1()
{
return $this->morphedByMany(VideoPostTemplateOne::class, 'taggable');
}
public function video_post_2()
{
return $this->morphedByMany(VideoPostTemplateTwo::class, 'taggable');
}
public function video_post_3()
{
return $this->morphedByMany(VideoPostTemplateThree::class, 'taggable');
}
public function video_post_4()
{
return $this->morphedByMany(VideoPostTemplateFour::class, 'taggable');
}
public function video_post_5()
{
return $this->morphedByMany(VideoPostTemplateFive::class, 'taggable');
}
public function video_post_6()
{
return $this->morphedByMany(VideoPostTemplateSix::class, 'taggable');
}
public function image()
{
return $this->morphedByMany(Image::class, 'taggable');
}
public function video()
{
return $this->morphedByMany(Video::class,'taggable');
}
}
| 25.822785 | 79 | 0.654412 |
ef5b20d43aa814ce9027aae10ef421f1b3b3da85 | 532 | js | JavaScript | src/utils/util-object.js | chrisgfortes/octaform-validate | 6013ceb352f4626eaeb0d9ed2ea627b91b701fba | [
"MIT"
] | null | null | null | src/utils/util-object.js | chrisgfortes/octaform-validate | 6013ceb352f4626eaeb0d9ed2ea627b91b701fba | [
"MIT"
] | 1 | 2021-08-31T19:57:58.000Z | 2021-08-31T19:57:58.000Z | src/utils/util-object.js | chrisgfortes/octaform-validate | 6013ceb352f4626eaeb0d9ed2ea627b91b701fba | [
"MIT"
] | null | null | null | const stringToPath = path => {
const containsBracketNotation = /\[[0-9]+\]/g;
if (path.match(containsBracketNotation)) {
path = path.replace(
containsBracketNotation,
s => `.${s.substring(1, s.length - 1)}`
);
}
return path.split('.');
};
const get = (source, path, defaultArgument) => {
return (
stringToPath(path).reduce((nestedObject, key) => {
return nestedObject && key in nestedObject ? nestedObject[key] : void 0;
}, source) || defaultArgument
);
};
export default {
get,
};
| 23.130435 | 78 | 0.614662 |
be5e447e38d63655cb7a037b7bb65f540b3d2b7e | 240 | ts | TypeScript | src/sharedTypes.ts | jauggy/storybook-background-issues | 1beeb34b2d0ae6854572c354a7d75cd29f0246b3 | [
"MIT"
] | 1 | 2020-08-29T10:04:30.000Z | 2020-08-29T10:04:30.000Z | src/sharedTypes.ts | jauggy/storybook-background-issues | 1beeb34b2d0ae6854572c354a7d75cd29f0246b3 | [
"MIT"
] | null | null | null | src/sharedTypes.ts | jauggy/storybook-background-issues | 1beeb34b2d0ae6854572c354a7d75cd29f0246b3 | [
"MIT"
] | null | null | null | /**
* "primary"|"secondary", etc.
*/
export type Color = typeof colorArray[number];
const colorArray = [
"primary",
"secondary",
"success",
"warning",
"danger",
"info",
"light",
"dark",
] as const;
export { colorArray };
| 15 | 46 | 0.595833 |
2932615e8aa0936a4713d040c954a3c19e862fbc | 7,509 | rs | Rust | mayastor/src/core/block_device.rs | reitermarkus/mayastor | 8b88fd46021ec25193080af6f8c29fda0d41f0ed | [
"Apache-2.0"
] | 84 | 2021-06-26T11:42:12.000Z | 2022-03-29T16:39:55.000Z | mayastor/src/core/block_device.rs | mayadata-io/mayastor | c95ab938343a019034967d2d6f964e1d587c8059 | [
"Apache-2.0"
] | 151 | 2021-06-28T08:11:53.000Z | 2022-03-30T12:54:30.000Z | mayastor/src/core/block_device.rs | mayadata-io/mayastor | c95ab938343a019034967d2d6f964e1d587c8059 | [
"Apache-2.0"
] | 25 | 2021-07-05T04:42:31.000Z | 2022-03-28T06:18:17.000Z | use super::{CoreError, DeviceEventSink, IoCompletionStatus, IoType};
use spdk_rs::{DmaBuf, DmaError, IoVec};
use async_trait::async_trait;
use merge::Merge;
use nix::errno::Errno;
use std::os::raw::c_void;
use uuid::Uuid;
/// TODO
#[derive(Debug, Default, Clone, Copy, Merge)]
pub struct BlockDeviceIoStats {
#[merge(strategy = merge::num::saturating_add)]
pub num_read_ops: u64,
#[merge(strategy = merge::num::saturating_add)]
pub num_write_ops: u64,
#[merge(strategy = merge::num::saturating_add)]
pub bytes_read: u64,
#[merge(strategy = merge::num::saturating_add)]
pub bytes_written: u64,
#[merge(strategy = merge::num::saturating_add)]
pub num_unmap_ops: u64,
#[merge(strategy = merge::num::saturating_add)]
pub bytes_unmapped: u64,
}
/// Core trait that represents a block device.
/// TODO: Add text.
#[async_trait(?Send)]
pub trait BlockDevice {
/// Returns total size in bytes of the device.
fn size_in_bytes(&self) -> u64;
/// Returns the size of a block of the underlying device
fn block_len(&self) -> u64;
/// Returns number of blocks for the device.
fn num_blocks(&self) -> u64;
/// Returns the UUID of the device.
fn uuid(&self) -> Uuid;
/// Returns configured product name for the device.
fn product_name(&self) -> String;
/// Returns the name of driver module for the device.
fn driver_name(&self) -> String;
/// Returns the name of the device.
fn device_name(&self) -> String;
/// Returns aligment of the device.
fn alignment(&self) -> u64;
/// Checks whether target I/O type is supported by the device.
fn io_type_supported(&self, io_type: IoType) -> bool;
/// Obtains I/O statistics for the device.
async fn io_stats(&self) -> Result<BlockDeviceIoStats, CoreError>;
/// Checks if block device has been claimed.
fn claimed_by(&self) -> Option<String>;
/// Open device and obtain a descriptor.
fn open(
&self,
read_write: bool,
) -> Result<Box<dyn BlockDeviceDescriptor>, CoreError>;
/// Obtain I/O controller for device.
fn get_io_controller(&self) -> Option<Box<dyn DeviceIoController>>;
/// Register device event listener.
fn add_event_listener(
&self,
listener: DeviceEventSink,
) -> Result<(), CoreError>;
}
/// Core trait that represents a descriptor for an opened block device.
/// TODO: Add text.
pub trait BlockDeviceDescriptor: Send {
/// TODO
fn get_device(&self) -> Box<dyn BlockDevice>;
/// TODO
fn into_handle(
self: Box<Self>,
) -> Result<Box<dyn BlockDeviceHandle>, CoreError>;
/// TODO
fn get_io_handle(&self) -> Result<Box<dyn BlockDeviceHandle>, CoreError>;
/// TODO
fn unclaim(&self);
}
/// TODO
pub type IoCompletionCallbackArg = *mut c_void;
/// TODO
pub type IoCompletionCallback =
fn(&dyn BlockDevice, IoCompletionStatus, IoCompletionCallbackArg) -> ();
/// TODO
pub type OpCompletionCallbackArg = *mut c_void;
/// TODO
pub type OpCompletionCallback = fn(bool, OpCompletionCallbackArg) -> ();
/// Core trait that represents a device I/O handle.
/// TODO: Add text.
#[async_trait(?Send)]
pub trait BlockDeviceHandle {
// Generic functions.
/// TODO
fn get_device(&self) -> &dyn BlockDevice;
/// TODO
fn dma_malloc(&self, size: u64) -> Result<DmaBuf, DmaError>;
// Futures-based I/O functions.
/// TODO
async fn read_at(
&self,
offset: u64,
buffer: &mut DmaBuf,
) -> Result<u64, CoreError>;
/// TODO
async fn write_at(
&self,
offset: u64,
buffer: &DmaBuf,
) -> Result<u64, CoreError>;
// Callback-based I/O functions.
/// TODO
fn readv_blocks(
&self,
iov: *mut IoVec,
iovcnt: i32,
offset_blocks: u64,
num_blocks: u64,
cb: IoCompletionCallback,
cb_arg: IoCompletionCallbackArg,
) -> Result<(), CoreError>;
/// TODO
fn writev_blocks(
&self,
iov: *mut IoVec,
iovcnt: i32,
offset_blocks: u64,
num_blocks: u64,
cb: IoCompletionCallback,
cb_arg: IoCompletionCallbackArg,
) -> Result<(), CoreError>;
/// TODO
fn reset(
&self,
cb: IoCompletionCallback,
cb_arg: IoCompletionCallbackArg,
) -> Result<(), CoreError>;
/// TODO
fn unmap_blocks(
&self,
offset_blocks: u64,
num_blocks: u64,
cb: IoCompletionCallback,
cb_arg: IoCompletionCallbackArg,
) -> Result<(), CoreError>;
/// TODO
fn write_zeroes(
&self,
offset_blocks: u64,
num_blocks: u64,
cb: IoCompletionCallback,
cb_arg: IoCompletionCallbackArg,
) -> Result<(), CoreError>;
// NVMe only.
/// TODO
async fn nvme_admin_custom(&self, opcode: u8) -> Result<(), CoreError>;
/// TODO
async fn nvme_admin(
&self,
nvme_cmd: &spdk_rs::libspdk::spdk_nvme_cmd,
buffer: Option<&mut DmaBuf>,
) -> Result<(), CoreError>;
/// TODO
async fn nvme_identify_ctrlr(&self) -> Result<DmaBuf, CoreError>;
/// TODO
async fn create_snapshot(&self) -> Result<u64, CoreError>;
/// TODO
async fn nvme_resv_register(
&self,
_current_key: u64,
_new_key: u64,
_register_action: u8,
_cptpl: u8,
) -> Result<(), CoreError> {
Err(CoreError::NotSupported {
source: Errno::EOPNOTSUPP,
})
}
/// TODO
async fn nvme_resv_acquire(
&self,
_current_key: u64,
_preempt_key: u64,
_acquire_action: u8,
_resv_type: u8,
) -> Result<(), CoreError> {
Err(CoreError::NotSupported {
source: Errno::EOPNOTSUPP,
})
}
/// TODO
async fn nvme_resv_report(
&self,
_cdw11: u32,
_buffer: &mut DmaBuf,
) -> Result<(), CoreError> {
Err(CoreError::NotSupported {
source: Errno::EOPNOTSUPP,
})
}
/// TODO
async fn io_passthru(
&self,
nvme_cmd: &spdk_rs::libspdk::spdk_nvme_cmd,
_buffer: Option<&mut DmaBuf>,
) -> Result<(), CoreError> {
Err(CoreError::NvmeIoPassthruDispatch {
source: Errno::EOPNOTSUPP,
opcode: nvme_cmd.opc(),
})
}
/// TODO
async fn host_id(&self) -> Result<[u8; 16], CoreError> {
Err(CoreError::NotSupported {
source: Errno::EOPNOTSUPP,
})
}
}
/// TODO
pub trait LbaRangeController {}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum DeviceTimeoutAction {
/// Abort I/O operation that times out.
Abort,
/// Reset the whole device in case any single command times out.
Reset,
/// Do not take any actions on command timeout.
Ignore,
/// Remove the device from the configuration
HotRemove,
}
impl ToString for DeviceTimeoutAction {
fn to_string(&self) -> String {
match *self {
Self::Abort => "Abort",
Self::Reset => "Reset",
Self::Ignore => "Ignore",
Self::HotRemove => "HotRemove",
}
.to_string()
}
}
/// TODO
pub trait DeviceIoController {
/// TODO
fn get_timeout_action(&self) -> Result<DeviceTimeoutAction, CoreError>;
/// TODO
fn set_timeout_action(
&mut self,
action: DeviceTimeoutAction,
) -> Result<(), CoreError>;
}
| 24.864238 | 77 | 0.600213 |
0fa292e2c6968723d058c2148e77bd4d924fb5a2 | 803 | sh | Shell | .github/scripts/k3sup.sh | rafaribe/k3s-cluster | aacfb9d8e6199c3118bf73f0978a3483d2beebe6 | [
"MIT"
] | null | null | null | .github/scripts/k3sup.sh | rafaribe/k3s-cluster | aacfb9d8e6199c3118bf73f0978a3483d2beebe6 | [
"MIT"
] | 7 | 2022-02-06T13:00:00.000Z | 2022-02-12T00:06:25.000Z | .github/scripts/k3sup.sh | rafaribe/home-ops | 473111447a05fd55a1888822a654bcffc156b6a5 | [
"MIT"
] | null | null | null | #!/usr/bin/env bash
K3S_VERSION=v1.24.0-rc1+k3s1
K3S_SERVER_IP="10.0.1.200"
K3S_USER="rafaribe"
k3sup install --ip=$K3S_SERVER_IP --user=$K3S_USER --k3s-version="${K3S_VERSION}" --k3s-extra-args="--disable servicelb --disable traefik --disable local-storage --flannel-backend=none --disable-network-policy" --local-path=./kubeconfig --ssh-key=/home/rafaribe/.ssh/id_ed25519
k3sup join \
--ip=10.0.1.201 \
--server-ip=$K3S_SERVER_IP \
--server-user=$K3S_USER \
--k3s-version="${K3S_VERSION}" \
--user=$K3S_USER --ssh-key=/home/rafaribe/.ssh/id_ed25519
k3sup join \
--ip=10.0.1.202 \
--server-ip=$K3S_SERVER_IP \
--server-user=$K3S_USER \
--k3s-version="${K3S_VERSION}" \
--user=$K3S_USER --ssh-key=/home/rafaribe/.ssh/id_ed25519
cp ./kubeconfig ~/.kube/teivas
| 34.913043 | 277 | 0.678705 |
7531d3e73ea54cbcc873a4a40ffbb294162d5836 | 1,361 | css | CSS | assets/stylesheets/styles.css | mateomh/Vidyo_Conference_Test | fb6040b14faaad547fdeacab1b75bc94601ed4bc | [
"MIT"
] | 2 | 2021-02-13T02:13:20.000Z | 2021-02-15T21:21:57.000Z | assets/stylesheets/styles.css | mateomh/Vidyo_Conference_Test | fb6040b14faaad547fdeacab1b75bc94601ed4bc | [
"MIT"
] | 1 | 2021-02-15T14:39:47.000Z | 2021-02-15T14:39:47.000Z | assets/stylesheets/styles.css | mateomh/Vidyo_Conference_Test | fb6040b14faaad547fdeacab1b75bc94601ed4bc | [
"MIT"
] | null | null | null | *,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #444444;
display: flex;
justify-content: space-around;
align-items: center;
padding: 0;
margin: 2vh;
}
.sidebar {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
width: 30vw;
height: 96vh;
/* background-color: #0857C3 ; */
background-color: #DDDAE8;
border-radius: 3vh;
}
.logo {
height: 20%;
cursor: pointer;
}
.meetinginfo {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
height: 50vh;
}
.label {
display: inline-block;
font-weight: bolder;
font-size: 3vh;
color: #001871;
text-align: center;
width: 100%;
}
.input {
padding: 2vh;
text-align: center;
border-radius: 1.5vh;
border: 0.3vh solid #8BC400;
width: 100%;
font-size: 2vh;
font-weight: bold;
outline: none;
}
.button {
padding: 2vh;
border: none;
border-radius: 1.5vh;
width: 100%;
font-size: 3vh;
font-weight: bolder;
color: white;
background-color: #8BC400;
cursor: pointer;
box-shadow: 1vh 1vh 2vh black;
outline: none;
}
.button:hover {
background-color: #001871;
}
.button:active {
transform: scale(0.95);
background-color: #8BC400;
}
.renderer {
z-index: 99;
height: 96vh;
width: 70vw;
} | 15.122222 | 35 | 0.643644 |
dc046eb3c273b51defe681cf211a1122df73bad9 | 83 | rb | Ruby | app/models/user_story.rb | sophieqgu/life-story | 77e3d0d23fe0fd4e475e89c6c7bf6741fdbb6b53 | [
"MIT"
] | null | null | null | app/models/user_story.rb | sophieqgu/life-story | 77e3d0d23fe0fd4e475e89c6c7bf6741fdbb6b53 | [
"MIT"
] | 4 | 2021-02-19T02:00:05.000Z | 2022-02-26T06:24:03.000Z | app/models/user_story.rb | sophieqgu/life-story | 77e3d0d23fe0fd4e475e89c6c7bf6741fdbb6b53 | [
"MIT"
] | null | null | null | class UserStory < ActiveRecord::Base
belongs_to :user
belongs_to :story
end | 20.75 | 37 | 0.746988 |
6b5591d1a12cc61ec2eb944bc687690e98907598 | 1,359 | js | JavaScript | client/modules/Event/pages/EventDetailPage/EventDetailPage.js | Innogator/b-social | c3ad81780a813a1205259d34cf612ba7a7ad7f46 | [
"MIT"
] | null | null | null | client/modules/Event/pages/EventDetailPage/EventDetailPage.js | Innogator/b-social | c3ad81780a813a1205259d34cf612ba7a7ad7f46 | [
"MIT"
] | null | null | null | client/modules/Event/pages/EventDetailPage/EventDetailPage.js | Innogator/b-social | c3ad81780a813a1205259d34cf612ba7a7ad7f46 | [
"MIT"
] | null | null | null | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import styles from '../../components/EventListItem/EventListItem.css';
import { fetchEvent } from '../../EventActions';
import { getEvent } from '../../EventReducer';
export function EventDetailPage(props) {
return (
<div>
<Helmet title={props.event.title} />
<div className={`${styles['single-event']} ${styles['event-detail']}`}>
<h3 className={styles['event-title']}>{props.event.title}</h3>
<p className={styles['event-date']}>{props.event.date}</p>
<p className={styles['event-desc']}>{props.event.description}</p>
</div>
</div>
);
}
// Actions required to provide data for this component to render in server-side
EventDetailPage.need = [params => {
return fetchEvent(params.cuid);
}];
// Retrieve data form store as props
function mapStateToProps(state, props) {
return {
event: getEvent(state, props.params.cuid)
};
}
EventDetailPage.propTypes = {
event: PropTypes.shape({
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
date: PropTypes.instanceOf(Date).isRequired,
slug: PropTypes.string.isRequired,
cuid: PropTypes.string.isRequired
}).isRequired
};
export default connect(mapStateToProps)(EventDetailPage);
| 28.914894 | 79 | 0.685063 |
4587b24935f24ffdcda299047c2da705ecf90d2c | 840 | py | Python | dicotomia.py | lauralardies/ordenar | f1f926b4fc17a4ed798c0c0880ccac581bfa0d22 | [
"Apache-2.0"
] | null | null | null | dicotomia.py | lauralardies/ordenar | f1f926b4fc17a4ed798c0c0880ccac581bfa0d22 | [
"Apache-2.0"
] | null | null | null | dicotomia.py | lauralardies/ordenar | f1f926b4fc17a4ed798c0c0880ccac581bfa0d22 | [
"Apache-2.0"
] | null | null | null | class Dicotomia():
def __init__(self, tabla) -> None:
self.fin = len(tabla) - 1
self.tabla = tabla
self.tablaordenada =[]
def bubbleSort(self):
for i in range(0, self.fin):
for j in range(0, self.fin - i):
if self.tabla[j] > self.tabla[j + 1]:
temp = self.tabla[j]
self.tabla[j] = self.tabla[j+1]
self.tabla[j+1] = temp
def insercion (self):
for i in range (0,self.fin+1):
self.tablaordenada.append (self.tabla[i])
for j in range (i,0,-1):
if self.tablaordenada[j-1]>self.tablaordenada[j]:
aux = self.tablaordenada[j]
self.tablaordenada[j]=self.tablaordenada[j-1]
self.tablaordenada[j-1]=aux | 36.521739 | 65 | 0.495238 |
8cc9c656ba7c5eefb0b2f0123fd2f8b599680aa0 | 2,983 | dart | Dart | examples/api/lib/cupertino/scrollbar/cupertino_scrollbar.0.dart | Mayb3Nots/flutter | a31bed7890e502278723074c8f82d402f9f8041f | [
"BSD-3-Clause"
] | 5 | 2021-02-23T01:42:16.000Z | 2021-09-22T05:41:24.000Z | examples/api/lib/cupertino/scrollbar/cupertino_scrollbar.0.dart | Mayb3Nots/flutter | a31bed7890e502278723074c8f82d402f9f8041f | [
"BSD-3-Clause"
] | 20 | 2021-01-11T06:43:57.000Z | 2022-03-31T03:32:41.000Z | examples/api/lib/cupertino/scrollbar/cupertino_scrollbar.0.dart | Mayb3Nots/flutter | a31bed7890e502278723074c8f82d402f9f8041f | [
"BSD-3-Clause"
] | 3 | 2021-03-11T04:52:43.000Z | 2021-09-18T02:53:16.000Z | // Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Template: dev/snippets/config/templates/stateless_widget_scaffold.tmpl
//
// Comment lines marked with "โผโผโผ" and "โฒโฒโฒ" are used for authoring
// of samples, and may be ignored if you are just exploring the sample.
// Flutter code sample for CupertinoScrollbar
//
//***************************************************************************
//* โผโผโผโผโผโผโผโผ description โผโผโผโผโผโผโผโผ (do not modify or remove section marker)
// This sample shows a [CupertinoScrollbar] that fades in and out of view as scrolling occurs.
// The scrollbar will fade into view as the user scrolls, and fade out when scrolling stops.
// The `thickness` of the scrollbar will animate from 6 pixels to the `thicknessWhileDragging` of 10
// when it is dragged by the user. The `radius` of the scrollbar thumb corners will animate from 34
// to the `radiusWhileDragging` of 0 when the scrollbar is being dragged by the user.
//* โฒโฒโฒโฒโฒโฒโฒโฒ description โฒโฒโฒโฒโฒโฒโฒโฒ (do not modify or remove section marker)
//***************************************************************************
//****************************************************************************
//* โผโผโผโผโผโผโผโผ code-imports โผโผโผโผโผโผโผโผ (do not modify or remove section marker)
import 'package:flutter/cupertino.dart';
//* โฒโฒโฒโฒโฒโฒโฒโฒ code-imports โฒโฒโฒโฒโฒโฒโฒโฒ (do not modify or remove section marker)
//****************************************************************************
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),
),
);
}
}
/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
//********************************************************************
//* โผโผโผโผโผโผโผโผ code โผโผโผโผโผโผโผโผ (do not modify or remove section marker)
@override
Widget build(BuildContext context) {
return CupertinoScrollbar(
thickness: 6.0,
thicknessWhileDragging: 10.0,
radius: const Radius.circular(34.0),
radiusWhileDragging: Radius.zero,
child: ListView.builder(
itemCount: 120,
itemBuilder: (BuildContext context, int index) {
return Center(
child: Text('item $index'),
);
},
),
);
}
//* โฒโฒโฒโฒโฒโฒโฒโฒ code โฒโฒโฒโฒโฒโฒโฒโฒ (do not modify or remove section marker)
//********************************************************************
}
| 35.511905 | 100 | 0.567214 |
03f8f8e1808c7f23157b9c304248496e1aba6448 | 21,707 | swift | Swift | Example/Pods/CaamDauForm/Form/Core/Row/Row.swift | testing2007/ZQSwiftTools | ef958346ee60341f79b2be646cfb0e9a1b344c40 | [
"MIT"
] | 2 | 2020-09-28T06:35:43.000Z | 2020-12-16T08:46:11.000Z | Example/Pods/CaamDauForm/Form/Core/Row/Row.swift | testing2007/ZQSwiftTools | ef958346ee60341f79b2be646cfb0e9a1b344c40 | [
"MIT"
] | 1 | 2020-11-04T09:04:59.000Z | 2020-11-06T00:58:35.000Z | Example/Pods/CaamDauForm/Form/Core/Row/Row.swift | testing2007/ZQSwiftTools | ef958346ee60341f79b2be646cfb0e9a1b344c40 | [
"MIT"
] | null | null | null | //Created on 2018/12/6 by LCD :https://github.com/liucaide .
/***** ๆจกๅๆๆกฃ *****
* Row UI ๆ็็ปไปถ
*/
import UIKit
import Foundation
//MARK:-------------------- ๆฐ็ ่กจๅๅ่ฎฎ --------------------
public typealias RowDidSelectBlock = () -> Void
public typealias RowCallBack = (Any?) -> Void
public typealias RowCompletionHandle = (Any?) -> (Any?)
//MARK:--- UI ๆฐๆฎๆบๅ้
็ฝฎๅ่ฎฎ ----------
public typealias UIDataSourceConfigModel = UIDataSource & UIConfigModel
//MARK:--- UI ๆฐๆฎๆบๅ่ฎฎ๏ผ ----------
public protocol UIDataSource {
associatedtype DataSource
var dataSource:DataSource? { set get }
func row_update(dataSource data: DataSource)
}
extension UIDataSource {
/// ้จๅๅฐๆนๆฏไธ้่ฆ็จๅฐ็๏ผ้่ฆไฝฟ็จๅฐ็ๅฐๆน้ๅๅณๅฏ
public var dataSource: DataSource? {
get { return nil }
set {}
}
func row_update(dataSource data: DataSource) {}
}
//MARK:--- UI ้
็ฝฎๅ่ฎฎ๏ผ ----------
public protocol UIConfigModel {
associatedtype ConfigModel
var config:ConfigModel? { set get }
func row_update(config data: ConfigModel)
}
extension UIConfigModel {
/// ้จๅๅฐๆนๆฏไธ้่ฆ็จๅฐ็๏ผ้่ฆไฝฟ็จๅฐ็ๅฐๆน้ๅๅณๅฏ
public var config: ConfigModel? {
get { return nil }
set {}
}
func row_update(config data: ConfigModel){}
}
//MARK:--- UI ๅ่ฎฎ ----------
public protocol UIProtocol {
var dataSource:Any? { set get }
var config:Any? { set get }
var bundleFrom:String? { get }
var autoLayout:Bool { get }
var frame:CGRect { set get }
var x:CGFloat { set get }
var y:CGFloat { set get }
var w:CGFloat { set get }
var h:CGFloat { set get }
var size:CGSize { set get }
var insets:UIEdgeInsets { set get }
var insetsTitle:UIEdgeInsets { set get }
var callBack:RowCallBack?{ set get }
var tapBlock:RowDidSelectBlock?{ set get }
func bind(_ obj: AnyObject)
}
extension UIProtocol {
//public var dataSource: Any? { set{} get{ return nil} }
//public var config: Any? { set{} get{ return nil} }
public var bundleFrom: String? { return nil }
public var autoLayout: Bool { return true }
public var frame: CGRect { set{} get{ return .zero }}
public var x:CGFloat {
get{ return frame.origin.x }
set{ frame.origin.x = newValue }
}
public var y:CGFloat{
get{ return frame.origin.y }
set{ frame.origin.y = newValue }
}
public var w:CGFloat{
get{ return frame.size.width }
set{ frame.size.width = newValue }
}
public var h:CGFloat{
get{ return frame.size.height }
set{ frame.size.height = newValue }
}
public var size:CGSize{
get{ return frame.size }
set{ frame.size = newValue }
}
public var insets:UIEdgeInsets{ set{} get{ return .zero }}
public var insetsTitle:UIEdgeInsets{ set{} get{ return .zero }}
public var callBack:RowCallBack?{ set{} get{ return nil} }
public var tapBlock:RowDidSelectBlock?{ set{} get{ return nil} }
public func bind(_ obj: AnyObject) {
}
}
//MARK:--- UI ๆงๅถๅจ ViewControllers ๅ่กจๅ่ฎฎ๏ผ ----------
public protocol RowVCProtocol: UIProtocol {
var vc:UIViewController { get }
var view:UIView { get }
}
extension RowVCProtocol {
public var view:UIView { get{ return vc.view} }
public var dataSource: Any? { set{} get{ return nil} }
public var config: Any? { set{} get{ return nil} }
}
public protocol UIViewControllerProtocol: UIDataSourceConfigModel {
/// UIViewController ไฝฟ็จๆญคๆนๆณๅๅงๅ
static func row_init(withDataSource dataSource:DataSource?, config:ConfigModel?, callBack:RowCallBack?, tapBlock:RowDidSelectBlock?) -> UIViewController
}
extension UIViewControllerProtocol {
// public static func row_init(withDataSource dataSource:DataSource? = nil, config:ConfigModel? = nil, callBack:RowCallBack? = nil, tapBlock:RowDidSelectBlock? = nil) -> UIViewController {
// return UIViewController()
// }
public func row_update(config data: ConfigModel) {
}
public func row_update(dataSource data: DataSource) {
}
}
public protocol RowViewProtocol: UIProtocol {
var view:UIView { get }
func row_show(withSuperView vv:UIView, callBack:((UIView)->Void)?)
}
extension RowViewProtocol {
public var dataSource: Any? { set{} get{ return nil} }
public var config: Any? { set{} get{ return nil} }
public func row_show(withSuperView vv:UIView, callBack:((UIView)->Void)? = nil) {
vv.addSubview(view)
callBack?(view)
}
}
public protocol UIViewProtocol: UIDataSourceConfigModel {
/// UIView ไฝฟ็จๆญคๆนๆณๅๅงๅ
static func row_init(withDataSource dataSource:DataSource?, config:ConfigModel?, callBack:RowCallBack?, tapBlock:RowDidSelectBlock?) -> UIView
}
extension UIViewProtocol {
// public static func row_init(withDataSource dataSource:DataSource? = nil, config:ConfigModel? = nil, callBack:RowCallBack? = nil, tapBlock:RowDidSelectBlock? = nil) -> UIView {
// return UIView()
// }
public func row_update(config data: ConfigModel) {
}
public func row_update(dataSource data: DataSource) {
}
}
//MARK:--- UI ๆงๅถๅจ ViewControllers ๅ่ฎฎๅ
ณ่ๆจกๅ ----------
public struct RowVC<T:UIViewControllerProtocol>:RowVCProtocol where T:UIViewController {
public var vc:UIViewController
public var _dataSource:T.DataSource?
public var _config:T.ConfigModel?
public var frame:CGRect
public var autoLayout:Bool
public init(dataSource:T.DataSource? = nil,
config:T.ConfigModel? = nil,
frame:CGRect = .zero,
autoLayout:Bool = true,
callBack:RowCallBack? = nil,
tapBlock:RowDidSelectBlock? = nil) {
self.vc = T.row_init(withDataSource: dataSource, config: config, callBack:callBack, tapBlock:tapBlock)
self._dataSource = dataSource
self._config = config
self.frame = frame
self.autoLayout = autoLayout
}
public func bind(_ obj: AnyObject) {
guard let item = obj as? T else {
return
}
if let m = _config {
item.row_update(config: m)
}
if let d = _dataSource {
item.row_update(dataSource:d)
}
}
public var dataSource: Any? {
set{
_dataSource = newValue as? T.DataSource
}
get{
return _dataSource
}
}
public var config: Any? {
set{
_config = newValue as? T.ConfigModel
}
get{
return _config
}
}
}
//MARK:--- UI View ๅ่ฎฎๅ
ณ่ๆจกๅ ----------
public struct RowView<T:UIViewProtocol>: RowViewProtocol where T:UIView {
public var view:UIView
public var _dataSource:T.DataSource?
public var _config:T.ConfigModel?
public var frame:CGRect
public var autoLayout:Bool
public init(dataSource:T.DataSource? = nil,
config:T.ConfigModel? = nil,
frame:CGRect = .zero,
autoLayout:Bool = true,
callBack:RowCallBack? = nil,
tapBlock:RowDidSelectBlock? = nil) {
self.view = T.row_init(withDataSource: dataSource, config: config, callBack:callBack, tapBlock:tapBlock)
self._dataSource = dataSource
self._config = config
self.frame = frame
self.autoLayout = autoLayout
}
public func bind(_ obj: AnyObject) {
guard let item = obj as? T else {return}
if let m = _config {
item.row_update(config: m)
}
if let d = _dataSource {
item.row_update(dataSource:d)
}
}
public var dataSource: Any? {
set{
_dataSource = newValue as? T.DataSource
}
get{
return _dataSource
}
}
public var config: Any? {
set{
_config = newValue as? T.ConfigModel
}
get{
return _config
}
}
}
/// RowView ๅผ็จ็ฑปๅ ไธ่ฌ็จไธ้ข็ struct
public class RowViewClass<T:UIViewProtocol>: RowViewProtocol where T:UIView {
public var view:UIView
public var _dataSource:T.DataSource?
public var _config:T.ConfigModel?
public var frame:CGRect
public var autoLayout:Bool
public init(dataSource:T.DataSource? = nil,
config:T.ConfigModel? = nil,
frame:CGRect = .zero,
autoLayout:Bool = true,
callBack:RowCallBack? = nil,
tapBlock:RowDidSelectBlock? = nil) {
self.view = T.row_init(withDataSource: dataSource, config: config, callBack:callBack, tapBlock:tapBlock)
self._dataSource = dataSource
self._config = config
self.frame = frame
self.autoLayout = autoLayout
}
public func bind(_ obj: AnyObject) {
guard let item = obj as? T else {return}
if let m = _config {
item.row_update(config: m)
}
if let d = _dataSource {
item.row_update(dataSource:d)
}
}
public var dataSource: Any? {
set{
_dataSource = newValue as? T.DataSource
}
get{
return _dataSource
}
}
public var config: Any? {
set{
_config = newValue as? T.ConfigModel
}
get{
return _config
}
}
}
//MARK:--- TableViewCell CollectionViewCell ๅ่ฎฎ ----------
public protocol CellProtocol:UIProtocol {
var cellId: String { get }
var cellClass:AnyClass { get }
}
//MARK:--- ๆฐๆฎๆบๆดๆฐๅ่ฎฎ ---
public protocol RowCellUpdateProtocol:UIDataSourceConfigModel {
func row_update(callBack block:RowCallBack?)
}
extension RowCellUpdateProtocol {
public func row_update(config data: ConfigModel) {}
public func row_update(dataSource data: DataSource) {}
public func row_update(callBack block:RowCallBack?) {}
}
public struct RowCell<T:RowCellUpdateProtocol>:CellProtocol where T: UIView {
public var cellId: String
public var cellClass:AnyClass
public var _dataSource:T.DataSource?
public var _config:T.ConfigModel?
public var bundleFrom:String?
public var frame:CGRect
public var insets:UIEdgeInsets
public var insetsTitle:UIEdgeInsets
public var callBack:RowCallBack?
public var _didSelect:RowDidSelectBlock?
/*
data ๏ผView Data ๆฐๆฎๆบ
id ๏ผView Id ๆ ่ฏ ่พๅ
ฅ็ฉบๅ้ป่ฎคไปฅ็ฑปๅ viewClass ไธบๆ ่ฏ
tag ๏ผView Tag ๆ ็ญพ - ๅ็ฑปไธๅๆฐๆฎๆบๆๅๆงไปถไธๅUIๅฑ็คบๆๆๅๅบๅ
frame ๏ผView frame ๆฐๆฎๆบ
insets ๏ผView UIButton imageEdgeInsets | UICollectionView sectionInset
ๅฆ UICollectionView LineSpacing InteritemSpacing ไฝฟ็จ frame - x y
insetsTitle ๏ผView UIButton titleEdgeInsets
bundleFrom ๏ผView bundle ็ดขๅผ๏ผ็ปไปถๅ | pod nib ่ตๆบใใใใ๏ผ
callBack ๏ผ View ็ฑปๅ
ๆง่กๅ่ฐ
didSelect ๏ผ View ็นๅปๅ่ฐ UITableView | UICollectionView didSelectRow
*/
public init(data: T.DataSource? = nil,
config:T.ConfigModel? = nil,
id: String? = nil,
frame:CGRect = .zero,
insets:UIEdgeInsets = .zero,
insetsTitle:UIEdgeInsets = .zero,
bundleFrom:String = "",
callBack:RowCallBack? = nil,
didSelect:RowDidSelectBlock? = nil) {
self._dataSource = data
self._config = config
self.cellClass = T.self
self.cellId = id ?? String(describing: T.self)
self.frame = frame
self.bundleFrom = bundleFrom
self.insets = insets
self.insetsTitle = insetsTitle
self.callBack = callBack
self._didSelect = didSelect
}
public func bind(_ obj: AnyObject) {
guard let item = obj as? T else {return}
if let m = _config {
item.row_update(config: m)
}
if let d = _dataSource {
item.row_update(dataSource:d)
}
if let back = callBack {
item.row_update(callBack: back)
}
}
public var dataSource: Any? {
set{
_dataSource = newValue as? T.DataSource
}
get{
return _dataSource
}
}
public var config: Any? {
set{
_config = newValue as? T.ConfigModel
}
get{
return _config
}
}
}
extension RowCell {
public var tapBlock: RowDidSelectBlock? {
get { return _didSelect}
set { _didSelect = newValue}
}
}
/// RowCell ๅผ็จ็ฑปๅ ไธ่ฌ็จไธ้ข็ struct
public class RowCellClass<T:RowCellUpdateProtocol>:CellProtocol where T: UIView {
public var cellId: String
public var cellClass:AnyClass
public var _dataSource:T.DataSource?
public var _config:T.ConfigModel?
public var bundleFrom:String?
public var frame:CGRect
public var insets:UIEdgeInsets
public var insetsTitle:UIEdgeInsets
public var callBack:RowCallBack?
public var _didSelect:RowDidSelectBlock?
/*
data ๏ผView Data ๆฐๆฎๆบ
id ๏ผView Id ๆ ่ฏ ่พๅ
ฅ็ฉบๅ้ป่ฎคไปฅ็ฑปๅ viewClass ไธบๆ ่ฏ
tag ๏ผView Tag ๆ ็ญพ - ๅ็ฑปไธๅๆฐๆฎๆบๆๅๆงไปถไธๅUIๅฑ็คบๆๆๅๅบๅ
frame ๏ผView frame ๆฐๆฎๆบ
insets ๏ผView UIButton imageEdgeInsets | UICollectionView sectionInset
ๅฆ UICollectionView LineSpacing InteritemSpacing ไฝฟ็จ frame - x y
insetsTitle ๏ผView UIButton titleEdgeInsets
bundleFrom ๏ผView bundle ็ดขๅผ๏ผ็ปไปถๅ | pod nib ่ตๆบใใใใ๏ผ
callBack ๏ผ View ็ฑปๅ
ๆง่กๅ่ฐ
didSelect ๏ผ View ็นๅปๅ่ฐ UITableView | UICollectionView didSelectRow
*/
public init(data: T.DataSource? = nil,
config:T.ConfigModel? = nil,
id: String? = nil,
frame: CGRect = .zero,
insets:UIEdgeInsets = .zero,
insetsTitle:UIEdgeInsets = .zero,
bundleFrom:String = "",
callBack:RowCallBack? = nil,
didSelect:RowDidSelectBlock? = nil) {
self._dataSource = data
self._config = config
self.cellClass = T.self
self.cellId = id ?? String(describing: T.self)
self.frame = frame
self.bundleFrom = bundleFrom
self.insets = insets
self.insetsTitle = insetsTitle
self.callBack = callBack
self._didSelect = didSelect
}
public func bind(_ obj: AnyObject) {
guard let item = obj as? T else {return}
if let m = _config {
item.row_update(config: m)
}
if let d = _dataSource {
item.row_update(dataSource:d)
}
if let back = callBack {
item.row_update(callBack: back)
}
}
public var dataSource: Any? {
set{
_dataSource = newValue as? T.DataSource
}
get{
return _dataSource
}
}
public var config: Any? {
set{
_config = newValue as? T.ConfigModel
}
get{
return _config
}
}
}
extension RowCellClass {
public var tapBlock: RowDidSelectBlock? {
get { return _didSelect}
set { _didSelect = newValue}
}
}
//MARK:--- ------------------- ๆง็ ่กจๅ ๅ่ฎฎ --------------------
/*
//MARK:--- ๅๅ
ๆ ผ้
็ฝฎๅ่ฎฎ ---
/// ๆง็ๅ่ฎฎ๏ผๅผ็จ
@available(*, deprecated, message: "ๆง็ๅ่ฎฎ๏ผๅผ็จ")
public protocol RowProtocol {
var tag:Int { get }
var viewId: String { get }
var viewClass:AnyClass { get }
var bundleFrom:String { get }
var datas: Any { set get }
var frame: CGRect { set get }
var x:CGFloat { set get }
var y:CGFloat { set get }
var w:CGFloat { set get }
var h:CGFloat { set get }
var size:CGSize { set get }
var insets:UIEdgeInsets { set get }
var insetsTitle:UIEdgeInsets { set get }
var callBack:RowCallBack?{ set get }
var didSelect:RowDidSelectBlock?{ set get }
func bind(_ view: AnyObject)
}
//MARK:--- ๆฐๆฎๆบๆดๆฐๅ่ฎฎ ---
/// ๆง็ๅ่ฎฎ๏ผๅผ็จ
@available(*, deprecated, message: "ๆง็ๅ่ฎฎ๏ผๅผ็จ")
public protocol RowUpdateProtocol {
/// ๆฐๆฎๆบ ๅ
ณ่็ฑปๅ
associatedtype DataSource
func row_update(_ data: DataSource, id:String, tag:Int, frame:CGRect, callBack:RowCallBack?)
}
public extension RowUpdateProtocol{
func row_update(_ data: DataSource, id:String , tag:Int, frame:CGRect, callBack:RowCallBack?) {}
}
//MARK:--- ๅปบ่ฎพๅๅ
ๆ ผๆจกๅ ---
/// ๆง็ๅ่ฎฎ๏ผๅผ็จ
@available(*, deprecated, message: "ๆง็ๅ่ฎฎ๏ผๅผ็จ")
public struct Row<T> where T: UIView, T: RowUpdateProtocol {
public var data: T.DataSource
public let id: String
public var tag:Int
public var frame: CGRect
public let viewClass:AnyClass = T.self
public let bundleFrom:String
public var callBack:RowCallBack? = nil
public var didSelect:RowDidSelectBlock? = nil
public var insets:UIEdgeInsets
public var insetsTitle:UIEdgeInsets
/*
data ๏ผView Data ๆฐๆฎๆบ
id ๏ผView Id ๆ ่ฏ ่พๅ
ฅ็ฉบๅ้ป่ฎคไปฅ็ฑปๅ viewClass ไธบๆ ่ฏ
tag ๏ผView Tag ๆ ็ญพ - ๅ็ฑปไธๅๆฐๆฎๆบๆๅๆงไปถไธๅUIๅฑ็คบๆๆๅๅบๅ
frame ๏ผView frame ๆฐๆฎๆบ
insets ๏ผView UIButton imageEdgeInsets | UICollectionView sectionInset
ๅฆ UICollectionView LineSpacing InteritemSpacing ไฝฟ็จ frame - x y
insetsTitle ๏ผView UIButton titleEdgeInsets
bundleFrom ๏ผView bundle ็ดขๅผ๏ผ็ปไปถๅ | pod nib ่ตๆบใใใใ๏ผ
callBack ๏ผ View ็ฑปๅ
ๆง่กๅ่ฐ
didSelect ๏ผ View ็นๅปๅ่ฐ UITableView | UICollectionView didSelectRow
*/
public init(data: T.DataSource,
id: String = "",
tag:Int = 0,
frame: CGRect = .zero,
insets:UIEdgeInsets = .zero,
insetsTitle:UIEdgeInsets = .zero,
bundleFrom:String = "",
callBack:RowCallBack? = nil,
didSelect:RowDidSelectBlock? = nil) {
self.data = data
self.id = id
self.frame = frame
self.tag = tag
self.bundleFrom = bundleFrom
self.callBack = callBack
self.didSelect = didSelect
self.insets = insets
self.insetsTitle = insetsTitle
}
}
extension Row:RowProtocol {
// ๅๅ
ๆ ผๆจกๅ็ปๅฎๅๅ
ๆ ผๅฎไพ
public func bind(_ view: AnyObject) {
if let v = view as? T {
v.row_update(self.data, id:self.id, tag:self.tag, frame:self.frame, callBack:self.callBack)
}
}
}
//MARK:--- ้ๅ ---
extension Row {
public var viewId:String {
get{
return id=="" ? String(describing: viewClass) : id
}
}
public var datas: Any {
get { return data }
set { data = newValue as! T.DataSource }
}
public var x:CGFloat {
get{ return frame.origin.x }
set{ frame.origin.x = newValue }
}
public var y:CGFloat{
get{ return frame.origin.y }
set{ frame.origin.y = newValue }
}
public var w:CGFloat{
get{ return frame.size.width }
set{ frame.size.width = newValue }
}
public var h:CGFloat{
get{ return frame.size.height }
set{ frame.size.height = newValue }
}
public var size:CGSize{
get{ return frame.size }
set{ frame.size = newValue }
}
}
//MARK:--- RowClass ๅฏน่ฑก ----------
/// ๆง็ๅ่ฎฎ๏ผๅผ็จ
@available(*, deprecated, message: "ๆง็ๅ่ฎฎ๏ผๅผ็จ")
public class RowClass<T> where T: UIView, T: RowUpdateProtocol {
public var data: T.DataSource
public let id: String
public var tag:Int
public var frame: CGRect
public let viewClass:AnyClass = T.self
public let bundleFrom:String
public var callBack:RowCallBack? = nil
public var didSelect:RowDidSelectBlock? = nil
public var insets:UIEdgeInsets
public var insetsTitle:UIEdgeInsets
/*
data ๏ผView Data ๆฐๆฎๆบ
id ๏ผView Id ๆ ่ฏ ่พๅ
ฅ็ฉบๅ้ป่ฎคไปฅ็ฑปๅ viewClass ไธบๆ ่ฏ
tag ๏ผView Tag ๆ ็ญพ - ๅ็ฑปไธๅๆฐๆฎๆบๆๅๆงไปถไธๅUIๅฑ็คบๆๆๅๅบๅ
frame ๏ผView frame ๆฐๆฎๆบ
insets ๏ผView UIButton imageEdgeInsets | UICollectionView sectionInset
ๅฆ UICollectionView LineSpacing InteritemSpacing ไฝฟ็จ frame - x y
insetsTitle ๏ผView UIButton titleEdgeInsets
bundleFrom ๏ผView bundle ็ดขๅผ๏ผ็ปไปถๅ | pod nib ่ตๆบใใใใ๏ผ
callBack ๏ผ View ็ฑปๅ
ๆง่กๅ่ฐ
didSelect ๏ผ View ็นๅปๅ่ฐ UITableView | UICollectionView didSelectRow
*/
public init(data: T.DataSource,
id: String = "",
tag:Int = 0,
frame: CGRect = .zero,
insets:UIEdgeInsets = .zero,
insetsTitle:UIEdgeInsets = .zero,
bundleFrom:String = "",
callBack:RowCallBack? = nil,
didSelect:RowDidSelectBlock? = nil) {
self.data = data
self.id = id
self.frame = frame
self.tag = tag
self.bundleFrom = bundleFrom
self.callBack = callBack
self.didSelect = didSelect
self.insets = insets
self.insetsTitle = insetsTitle
}
}
extension RowClass:RowProtocol {
// ๅๅ
ๆ ผๆจกๅ็ปๅฎๅๅ
ๆ ผๅฎไพ
public func bind(_ view: AnyObject) {
if let v = view as? T {
//if v.conforms(to: RowUpdateProtocol.self)
v.row_update(self.data, id:self.id, tag:self.tag, frame:self.frame, callBack:self.callBack)
}
}
}
//MARK:--- ้ๅ ---
extension RowClass {
public var viewId:String {
get{
return id=="" ? String(describing: viewClass) : id
}
}
public var datas: Any {
get { return data }
set { data = newValue as! T.DataSource }
}
public var x:CGFloat {
get{ return frame.origin.x }
set{ frame.origin.x = newValue }
}
public var y:CGFloat{
get{ return frame.origin.y }
set{ frame.origin.y = newValue }
}
public var w:CGFloat{
get{ return frame.size.width }
set{ frame.size.width = newValue }
}
public var h:CGFloat{
get{ return frame.size.height }
set{ frame.size.height = newValue }
}
public var size:CGSize{
get{ return frame.size }
set{ frame.size = newValue }
}
}
*/
| 29.982044 | 195 | 0.604644 |
4d014e37380fa2c92f11d18bc7a00cb9a6e7ba1f | 740 | cs | C# | ESIConnectionLibrary/ESIConnectionLibrary/Automapper Profiles/FleetsProfile.cs | Dusty-Meg/ESIConnectionLibrary | b45efc9c81ac34006d5226b029bd2babea0bec26 | [
"MIT"
] | 4 | 2018-02-28T03:01:50.000Z | 2018-07-29T17:09:14.000Z | ESIConnectionLibrary/ESIConnectionLibrary/Automapper Profiles/FleetsProfile.cs | Dusty-Meg/ESIConnectionLibrary | b45efc9c81ac34006d5226b029bd2babea0bec26 | [
"MIT"
] | 23 | 2019-01-24T11:17:05.000Z | 2022-03-21T16:24:17.000Z | ESIConnectionLibrary/ESIConnectionLibrary/Automapper Profiles/FleetsProfile.cs | Dusty-Meg/ESIConnectionLibrary | b45efc9c81ac34006d5226b029bd2babea0bec26 | [
"MIT"
] | null | null | null | ๏ปฟusing AutoMapper;
using ESIConnectionLibrary.ESIModels;
using ESIConnectionLibrary.PublicModels;
namespace ESIConnectionLibrary.Automapper_Profiles
{
internal class FleetsProfile : Profile
{
public FleetsProfile()
{
CreateMap<EsiV1FleetWing, V1FleetWing>();
CreateMap<EsiV1FleetWingSquad, V1FleetWingSquad>();
CreateMap<EsiV1FleetMemberMove, V1FleetMemberMove>();
CreateMap<EsiV1FleetMemberInvite, V1FleetMemberInvite>();
CreateMap<EsiV1FleetMember, V1FleetMember>();
CreateMap<EsiV1FleetUpdate, V1FleetUpdate>();
CreateMap<EsiV1Fleet, V1Fleet>();
CreateMap<EsiV1FleetCharacter, V1FleetCharacter>();
}
}
}
| 33.636364 | 69 | 0.683784 |
2fa83fccf35cfb2fd3210b9d776af61ccad5a8e3 | 9,497 | py | Python | yarll/agents/tf1/knowledgetransfer/knowledge_transfer.py | hknozturk/yarll | c5293e6455e3debe6e4d4d21f713937a24a654f3 | [
"MIT"
] | 62 | 2016-11-05T19:27:11.000Z | 2018-09-20T13:29:39.000Z | yarll/agents/tf1/knowledgetransfer/knowledge_transfer.py | hknozturk/yarll | c5293e6455e3debe6e4d4d21f713937a24a654f3 | [
"MIT"
] | 4 | 2020-07-09T16:46:19.000Z | 2022-01-26T07:18:06.000Z | yarll/agents/tf1/knowledgetransfer/knowledge_transfer.py | hknozturk/yarll | c5293e6455e3debe6e4d4d21f713937a24a654f3 | [
"MIT"
] | 18 | 2016-11-24T14:17:15.000Z | 2018-07-04T16:33:00.000Z | import os
import numpy as np
import tensorflow as tf
from yarll.agents.agent import Agent
from yarll.agents.env_runner import EnvRunner
from yarll.misc.utils import discount_rewards, FastSaver
from yarll.misc.reporter import Reporter
from yarll.misc.network_ops import create_accumulative_gradients_op, add_accumulative_gradients_op, reset_accumulative_gradients_op
class TaskPolicy(object):
"""Policy for a specific class."""
def __init__(self, action, master):
super().__init__()
self.action = action
self.master = master
def choose_action(self, state):
"""Choose an action."""
return self.master.session.run([self.action], feed_dict={self.master.states: [state]})[0]
def new_trajectory(self):
pass
class KnowledgeTransfer(Agent):
"""Learner for variations of a task."""
def __init__(self, envs, monitor_path, **usercfg):
super().__init__(**usercfg)
self.envs = envs
self.n_tasks = len(envs)
self.monitor_path = monitor_path
self.nA = envs[0].action_space.n
self.config.update(dict(
timesteps_per_batch=10000,
trajectories_per_batch=10,
batch_update="timesteps",
n_iter=100,
switch_at_iter=None,
gamma=0.99, # Discount past rewards by a percentage
decay=0.9, # Decay of RMSProp optimizer
epsilon=1e-9, # Epsilon of RMSProp optimizer
learning_rate=0.005,
n_hidden_units=10,
repeat_n_actions=1,
n_sparse_units=10,
feature_extraction=False
))
self.config.update(usercfg)
self.build_networks()
self.task_runners = [EnvRunner(envs[i], TaskPolicy(action, self), self.config) for i, action in enumerate(self.action_tensors)]
if self.config["save_model"]:
for action_tensor in self.action_tensors:
tf.add_to_collection("action", action_tensor)
tf.add_to_collection("states", self.states)
self.saver = FastSaver()
def build_networks(self):
self.session = tf.Session()
with tf.variable_scope("shared"):
self.states = tf.placeholder(tf.float32, [None] + list(self.envs[0].observation_space.shape), name="states")
self.action_taken = tf.placeholder(tf.float32, name="action_taken")
self.advantage = tf.placeholder(tf.float32, name="advantage")
L1 = None
if self.config["feature_extraction"]:
L1 = tf.contrib.layers.fully_connected(
inputs=self.states,
num_outputs=self.config["n_hidden_units"],
activation_fn=tf.tanh,
weights_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.02),
biases_initializer=tf.zeros_initializer(),
scope="L1")
else:
L1 = self.states
knowledge_base = tf.Variable(tf.truncated_normal([L1.get_shape()[-1].value, self.config["n_sparse_units"]], mean=0.0, stddev=0.02), name="knowledge_base")
self.shared_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="shared")
# Every task has its own (sparse) representation
sparse_representations = [
tf.Variable(tf.truncated_normal([self.config["n_sparse_units"], self.nA], mean=0.0, stddev=0.02), name="sparse%d" % i)
for i in range(self.n_tasks)
]
self.probs_tensors = [tf.nn.softmax(tf.matmul(L1, tf.matmul(knowledge_base, s))) for s in sparse_representations]
self.action_tensors = [tf.squeeze(tf.multinomial(tf.math.log(probs), 1)) for probs in self.probs_tensors]
self.optimizer = tf.train.RMSPropOptimizer(
learning_rate=self.config["learning_rate"],
decay=self.config["decay"],
epsilon=self.config["epsilon"]
)
net_vars = self.shared_vars + sparse_representations
self.accum_grads = create_accumulative_gradients_op(net_vars, 0)
self.loss = tf.placeholder("float", name="loss")
summary_loss = tf.summary.scalar("Loss", self.loss)
self.rewards = tf.placeholder("float", name="Rewards")
summary_rewards = tf.summary.scalar("Reward", self.rewards)
self.episode_lengths = tf.placeholder("float", name="Episode_lengths")
summary_episode_lengths = tf.summary.scalar("Length", self.episode_lengths)
self.summary_op = tf.summary.merge([summary_loss, summary_rewards, summary_episode_lengths])
self.summary_writers = []
self.losses = []
regularizer = tf.contrib.layers.l1_regularizer(.05)
for i, probabilities in enumerate(self.probs_tensors):
good_probabilities = tf.reduce_sum(tf.multiply(probabilities, tf.one_hot(tf.cast(self.action_taken, tf.int32), self.nA)),
reduction_indices=[1])
eligibility = tf.math.log(good_probabilities) * self.advantage
loss = -tf.reduce_sum(eligibility) + regularizer(sparse_representations[i])
self.losses.append(loss)
writer = tf.summary.FileWriter(os.path.join(self.monitor_path, "task" + str(i)), self.session.graph)
self.summary_writers.append(writer)
# An add op for every task & its loss
self.add_accum_grads = []
for i, loss in enumerate(self.losses):
# Use all variables if the switch tasks experiment is disactivated or it's not the last task
all_vars = self.config["switch_at_iter"] is None or i != len(self.losses) - 1
self.add_accum_grads.append(add_accumulative_gradients_op(
(self.shared_vars if all_vars else []) + [sparse_representations[i]],
([self.accum_grads[0]] if all_vars else []) + [self.accum_grads[i + 1]],
loss,
i
))
self.apply_gradients = self.optimizer.apply_gradients(
zip(self.accum_grads, net_vars))
self.reset_accum_grads = reset_accumulative_gradients_op(net_vars, self.accum_grads, 0)
self.init_op = tf.global_variables_initializer()
def _initialize(self):
self.session.run(self.init_op)
def learn(self):
"""Run learning algorithm"""
self._initialize()
reporter = Reporter()
config = self.config
total_n_trajectories = np.zeros(len(self.envs))
for iteration in range(config["n_iter"]):
self.session.run([self.reset_accum_grads])
for i, task_runner in enumerate(self.task_runners):
if self.config["switch_at_iter"] is not None:
if iteration >= self.config["switch_at_iter"] and i != (len(self.task_runners) - 1):
continue
elif iteration < self.config["switch_at_iter"] and i == len(self.task_runners) - 1:
continue
# Collect trajectories until we get timesteps_per_batch total timesteps
trajectories = task_runner.get_trajectories()
total_n_trajectories[i] += len(trajectories)
all_state = np.concatenate([trajectory["state"] for trajectory in trajectories])
# Compute discounted sums of rewards
rets = [discount_rewards(trajectory["reward"], config["gamma"]) for trajectory in trajectories]
max_len = max(len(ret) for ret in rets)
padded_rets = [np.concatenate([ret, np.zeros(max_len - len(ret))]) for ret in rets]
# Compute time-dependent baseline
baseline = np.mean(padded_rets, axis=0)
# Compute advantage function
advs = [ret - baseline[:len(ret)] for ret in rets]
all_action = np.concatenate([trajectory["action"] for trajectory in trajectories])
all_adv = np.concatenate(advs)
# Do policy gradient update step
episode_rewards = np.array([trajectory["reward"].sum() for trajectory in trajectories]) # episode total rewards
episode_lengths = np.array([len(trajectory["reward"]) for trajectory in trajectories]) # episode lengths
results = self.session.run([self.losses[i], self.add_accum_grads[i], self.accum_grads], feed_dict={
self.states: all_state,
self.action_taken: all_action,
self.advantage: all_adv
})
summary = self.session.run([self.summary_op], feed_dict={
self.loss: results[0],
self.rewards: np.mean(episode_rewards),
self.episode_lengths: np.mean(episode_lengths)
})
self.summary_writers[i].add_summary(summary[0], iteration)
self.summary_writers[i].flush()
print("Task:", i)
reporter.print_iteration_stats(iteration, episode_rewards, episode_lengths, total_n_trajectories[i])
# Apply accumulated gradient after all the gradients of each task are summed
self.session.run([self.apply_gradients])
if self.config["save_model"]:
if not os.path.exists(self.monitor_path):
os.makedirs(self.monitor_path)
self.saver.save(self.session, os.path.join(self.monitor_path, "model"))
| 48.702564 | 166 | 0.621249 |
9837ebecc423aa21ac03f60dce3fdff0026fb9b2 | 771 | swift | Swift | SwiftySyntaxTests/Sample.JSON.swift | ZkHaider/SwiftySyntax | c623c798df1c9f00c94d10c1dab5246b9349b56c | [
"MIT"
] | 2 | 2021-09-12T21:13:24.000Z | 2021-11-14T15:45:44.000Z | SwiftySyntaxTests/Sample.JSON.swift | ZkHaider/SwiftySyntax | c623c798df1c9f00c94d10c1dab5246b9349b56c | [
"MIT"
] | null | null | null | SwiftySyntaxTests/Sample.JSON.swift | ZkHaider/SwiftySyntax | c623c798df1c9f00c94d10c1dab5246b9349b56c | [
"MIT"
] | null | null | null | //
// Sample.JSON.swift
// SwiftySyntaxTests
//
// Created by Haider Khan on 10/13/19.
// Copyright ยฉ 2019 zkhaider. All rights reserved.
//
import Foundation
let sampleJSON: String = """
{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
"""
| 18.804878 | 62 | 0.501946 |
5ac9a8cddfe685b6e2a773b076774cefae49d667 | 419 | cs | C# | LCT/LCT.Application/Teams/Queries/GetTeamsQueryHandler.cs | AGranosik/LetChooseTeams | 5363249451a8f91cb57f2809a362c88321a8ca8a | [
"MIT"
] | null | null | null | LCT/LCT.Application/Teams/Queries/GetTeamsQueryHandler.cs | AGranosik/LetChooseTeams | 5363249451a8f91cb57f2809a362c88321a8ca8a | [
"MIT"
] | null | null | null | LCT/LCT.Application/Teams/Queries/GetTeamsQueryHandler.cs | AGranosik/LetChooseTeams | 5363249451a8f91cb57f2809a362c88321a8ca8a | [
"MIT"
] | null | null | null | ๏ปฟusing LCT.Core.Entities.Tournaments.Types;
using MediatR;
namespace LCT.Application.Teams.Queries
{
public class GetTeamsQuery : IRequest<List<string>>
{
}
public class GetTeamsQueryHandler : IRequestHandler<GetTeamsQuery, List<string>>
{
public async Task<List<string>> Handle(GetTeamsQuery request, CancellationToken cancellationToken)
=> TournamentTeamNames.Teams;
}
}
| 26.1875 | 106 | 0.72315 |
e37070b4da0ad4a4d43c1127ff8f5937ba13b972 | 207 | rb | Ruby | lib/dul_hydra/solr_helper.rb | duke-libraries/dul-hydra | 3b2c831262add9a02ddd45468327fcf6922e6957 | [
"BSD-3-Clause"
] | 8 | 2015-01-28T03:16:06.000Z | 2019-11-01T16:30:11.000Z | lib/dul_hydra/solr_helper.rb | duke-libraries/dul-hydra | 3b2c831262add9a02ddd45468327fcf6922e6957 | [
"BSD-3-Clause"
] | 425 | 2015-01-05T15:19:18.000Z | 2019-11-06T13:47:25.000Z | lib/dul_hydra/solr_helper.rb | duke-libraries/dul-hydra | 3b2c831262add9a02ddd45468327fcf6922e6957 | [
"BSD-3-Clause"
] | 1 | 2015-11-02T16:53:34.000Z | 2015-11-02T16:53:34.000Z | module DulHydra::SolrHelper
def af_model_filter(solr_params, user_params)
solr_params[:fq] ||= []
solr_params[:fq] << "+#{Ddr::IndexFields::ACTIVE_FEDORA_MODEL}:#{user_params[:model]}"
end
end
| 23 | 90 | 0.700483 |
6db770ca017d39a438911f7db811b4e85bdc4d9c | 296 | ts | TypeScript | lib/renderers/Form/Container.d.ts | lunlunshiwo/ax-editor-package | 1f99b438c456e791dcd820c909a5691a52608dc2 | [
"Apache-2.0"
] | 1 | 2020-04-08T01:57:32.000Z | 2020-04-08T01:57:32.000Z | lib/renderers/Form/Container.d.ts | lunlunshiwo/ax-editor-package | 1f99b438c456e791dcd820c909a5691a52608dc2 | [
"Apache-2.0"
] | null | null | null | lib/renderers/Form/Container.d.ts | lunlunshiwo/ax-editor-package | 1f99b438c456e791dcd820c909a5691a52608dc2 | [
"Apache-2.0"
] | null | null | null | /// <reference types="react" />
import Container from '../Container';
import { FormControlProps } from './Item';
export interface ContainerProps extends FormControlProps {
}
export declare class ContainerControlRenderer extends Container<ContainerProps> {
renderBody(): JSX.Element | null;
}
| 32.888889 | 81 | 0.760135 |
38957bd9872642afe129e20fc66afa1bd55cb5bb | 3,889 | php | PHP | models/Ticket.php | keiosweb/oc-support-plugin | 45ec56220613679438314121ee303e5ef80f9f69 | [
"MIT"
] | 5 | 2016-02-02T05:41:20.000Z | 2021-05-12T14:15:15.000Z | models/Ticket.php | keiosweb/oc-support-plugin | 45ec56220613679438314121ee303e5ef80f9f69 | [
"MIT"
] | null | null | null | models/Ticket.php | keiosweb/oc-support-plugin | 45ec56220613679438314121ee303e5ef80f9f69 | [
"MIT"
] | 3 | 2016-01-18T13:16:02.000Z | 2021-08-12T17:53:57.000Z | <?php namespace Keios\Support\Models;
use Backend\Models\User;
use Keios\Support\Classes\SupportHelpers;
use Keios\Support\Classes\SupportMailer;
use Model;
/**
* Ticket Model
*/
class Ticket extends Model
{
/**
* @var string The database table used by the model.
*/
public $table = 'keios_support_tickets';
/**
* @var array Guarded fields
*/
protected $guarded = ['*'];
/**
* @var array Fillable fields
*/
protected $fillable = [];
public $hasMany = [
'files' => ['Keios\Support\Models\TicketAttachment'],
];
/**
* @var array Relations
*/
public $belongsTo = [
'category' => 'Keios\Support\Models\TicketCategory',
'priority' => 'Keios\Support\Models\TicketPriority',
'status' => 'Keios\Support\Models\TicketStatus',
'creator' => 'Keios\ProUser\Models\User',
'user' => 'Backend\Models\User',
];
/**
* @var array Relations
*/
public $attachOne = [];
/**
* @var array Relations
*/
public $attachMany = [
];
/**
* @var array
*/
public $belongsToMany = [
'comments' => [
'Keios\Support\Models\TicketComment',
'table' => 'keios_support_ticket_ticket_comment',
'key' => 'ticket_id',
'otherKey' => 'comment_id',
],
];
/**
* Provides user list for assignation purposes.
*
* @return array
*/
public function getUserOptions()
{
$user = User::lists('email', 'id');
return $user;
}
/**
* Before create method
*
* Generate temporary invalid hash id, that will be replaced in after create.
*
* Changes from new to assigned if detects assigned user
*/
public function beforeCreate()
{
$user = $this->user_id;
$statusId = $this->status_id;
$newStatus = TicketStatus::where('name', 'New')->first()->id;
$assignedStatus = TicketStatus::where('name', 'Assigned')->first()->id;
if ($user != null && $statusId == $newStatus) {
$this->status_id = $assignedStatus;
}
if (!$this->hash_id) {
$this->hash_id = 'invalid';
}
}
/**
* After create method
*
* Changes temporary hash id to proper basing on a record id
*/
public function afterCreate()
{
if ($this->hash_id == 'invalid') {
$helpers = new SupportHelpers();
$hashId = $helpers->generateHashId($this->id);
$this->hash_id = $hashId;
$this->save();
}
}
/**
* Before Update method
*
* Changes from new to assigned if detects assigned user
*/
public function beforeUpdate()
{
$user = $this->user_id;
$statusId = $this->status->id;
$newStatus = TicketStatus::where('name', 'New')->first()->id;
$assignedStatus = TicketStatus::where('name', 'Assigned')->first()->id;
if ($user != null && $statusId == $newStatus) {
$this->status_id = $assignedStatus;
}
}
/**
* After Update method
*
* Triggers mail sender on update.
*/
public function afterUpdate()
{
$mailer = new SupportMailer();
$email = $this->creator->email;
$address = Settings::get('address');
$vars = [
'ticket_number' => $this->hash_id,
'ticket_link' => $address.'/'.$this->hash_id,
'ticket_status' => $this->status->name,
];
if ($this->status == 'Closed' || $this->status == 'Resolved') {
$mailer->sendAfterTicketClosed($email, $vars);
} else {
if ($this->is_support == 1) {
$mailer->sendAfterTicketUpdated($email, $vars);
}
}
}
} | 23.713415 | 81 | 0.524042 |
79adaed895c5753784a7b37f91bea99a02e096b7 | 2,028 | php | PHP | resources/views/internet/mac_addresses/list.blade.php | michaela546/mars | 07e2ad50dcf732f98aaee9688e18bc52f3c74362 | [
"MIT"
] | null | null | null | resources/views/internet/mac_addresses/list.blade.php | michaela546/mars | 07e2ad50dcf732f98aaee9688e18bc52f3c74362 | [
"MIT"
] | null | null | null | resources/views/internet/mac_addresses/list.blade.php | michaela546/mars | 07e2ad50dcf732f98aaee9688e18bc52f3c74362 | [
"MIT"
] | null | null | null | <div id="mac-addresses-table"></div>
<script type="application/javascript">
$(document).ready(function () {
var deleteButton = function (cell, formatterParams, onRendered) {
return $("<button type=\"button\" class=\"btn btn-sm btn-danger float-left\">@lang('internet.delete')</button>").click(function () {
var data = cell.getRow().getData();
confirm('@lang('internet.delete')', '@lang('internet.confirm_delete')', '@lang('internet.cancel')', '@lang('internet.delete')', function() {
$.ajax({
type: "POST",
url: "{{ route('internet.mac_addresses.delete', [':id']) }}".replace(':id', data.id),
success: function () {
cell.getTable().setPage(cell.getTable().getPage());
},
error: function(error) {
ajaxError('@lang('internet.error')', '@lang('internet.ajax_error')', '@lang('internet.ok')', error);
}
});
});
})[0];
};
var table = new Tabulator("#mac-addresses-table", {
paginationSizeSelector: [10, 25, 50, 100, 250, 500],
paginationSize: 10,
pagination: "remote", //enable remote pagination
ajaxURL: "{{ route('internet.mac_addresses.users') }}", //set url for ajax request
ajaxSorting: true,
ajaxFiltering: true,
layout: "fitColumns",
placeholder: "No Data Set",
columns: [
{title: "@lang('internet.mac_address')", field: "mac_address", sorter: "string"},
{title: "@lang('internet.comment')", field: "comment", sorter: "string"},
{title: "@lang('internet.state')", field: "state", sorter: "string"},
{title: "", field: "id", headerSort: false, formatter: deleteButton},
]
});
});
</script>
| 50.7 | 156 | 0.495069 |
2c4be5b8c216efbf134873ad26befbe21f48a89b | 9,195 | py | Python | server/trydocpie.py | TylerTemp/trydocpie | 4d48255cb05178c8d636fb085f69943dd87ea67f | [
"MIT"
] | null | null | null | server/trydocpie.py | TylerTemp/trydocpie | 4d48255cb05178c8d636fb085f69943dd87ea67f | [
"MIT"
] | 6 | 2021-03-09T01:55:42.000Z | 2022-02-26T10:12:14.000Z | server/trydocpie.py | TylerTemp/trydocpie | 4d48255cb05178c8d636fb085f69943dd87ea67f | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Usage:
trydocpie web [<port>]
trydocpie gen
"""
import logging
# import time
import json
import shlex
import sys
import os
import re
import textwrap
# import inspect
import html
try:
from io import StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
from urllib.parse import urlparse, urlunparse
except ImportError:
from urlparse import urlparse, urlunparse
import flask
import markdown
# import markdown2
from docutils import core
from docutils.writers.html4css1 import Writer,HTMLTranslator
from bs4 import BeautifulSoup
import docpie
logging.getLogger('docpie').setLevel(logging.CRITICAL)
logger = logging.getLogger('trydocpie')
app = flask.Flask(__name__)
class StdoutRedirect(StringIO):
if sys.hexversion >= 0x03000000:
def u(self, string):
return string
else:
def u(self, string):
return unicode(string)
def write(self, s):
super(StdoutRedirect, self).write(self.u(s))
def __enter__(self):
self.real_out = sys.stdout
sys.stdout = self
return super(StdoutRedirect, self).__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self.real_out
return super(StdoutRedirect, self).__exit__(exc_type, exc_val, exc_tb)
def trydocpie(doc, argv, *a, **k):
with StdoutRedirect() as stdout:
error = False
try:
pie = docpie.docpie(doc, argv, *a, **k)
except (docpie.DocpieExit, SystemExit) as e:
error = True
output = str(e)
else:
output = str(pie)
if not output.strip():
output = stdout.getvalue()
return error, output
@app.route('/', methods=('POST',))
def trydocpiehandler():
body = flask.request.get_data().decode('utf-8')
args = json.loads(body)
argvstr = args.pop('argvnofilestr')
argv = shlex.split('pie.py ' + argvstr)
args['argv'] = argv
unexpected_error = False
try:
expected_error, output = trydocpie(**args)
except BaseException as e:
logger.error(e, exc_info=True)
unexpected_error = True
output = '{}: {}'.format(e.__class__.__name__, (e.args[0] if e.args else '') or '')
if unexpected_error:
code = 500
resp = {
'message': output
}
else:
code = 200
resp = {
'ok': (not expected_error),
'result': output
}
return flask.Response(json.dumps(resp), status=code, mimetype='application/json')
@app.route('/', methods=('GET',))
def trydocpieinfohandler():
info = {
'version_time': docpie.__timestamp__,
'version': docpie.__version__,
}
return flask.Response(json.dumps(info), mimetype='application/json')
class HTMLFragmentTranslator( HTMLTranslator ):
def __init__( self, document ):
HTMLTranslator.__init__( self, document )
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
def gen_folder():
project_root = os.path.normpath(os.path.join(__file__, '..', '..'))
codebase = os.path.join(project_root, 'server', 'codebase')
configs = (
{
'source': os.path.join(codebase, 'docpie'),
'target': os.path.join(project_root, 'build', 'static', 'docpie'),
},
{
'source': os.path.join(codebase, 'docpie.wiki'),
'target': os.path.join(project_root, 'build', 'static', 'docpie-wiki'),
},
)
fenced_code_re = re.compile(r'(?P<indent>\s+)```(?P<lang>[\w\ \-_]*)(?P<content>.*?)\ +```', re.DOTALL)
for config in configs:
source_folder = config['source']
target_folder = config['target']
if not os.path.isdir(target_folder):
os.makedirs(target_folder)
_dirpath, _dirnames, filenames = next(os.walk(source_folder))
for filename in filenames:
print('processing {}'.format(filename))
filebase, fileext = os.path.splitext(filename)
fileext_lower = fileext.lower()
if fileext_lower == '.md':
filetype = 'md'
elif fileext_lower == '.rst':
filetype = 'rst'
else:
continue
with open(os.path.join(source_folder, filename), 'r', encoding='utf-8') as f:
content_raw = f.read()
if '```' in content_raw:
# middle_parts = []
# content_parts = content_raw.split('```')
# # first_part = content_parts.pop(0)
# last_part = content_parts.pop(-1)
# for content, codepart in zip(content_parts[::2], content_parts[1::2]):
# middle_parts.append(content)
#
# print(codepart)
# code_parts = codepart.splitlines()
# language = code_parts.pop(0)
# code_rejoined = textwrap.dedent('\n'.join(code_parts)).replace('\n','<br />').rstrip()
#
# middle_parts.append("""
# <div class="codehilite">
# <pre class="language-{lang}"><code>{content}</code></pre>
# </div>
# """.format(lang=language, content=code_rejoined)
# )
# content = '\n'.join(middle_parts) + last_part
content = fenced_code_re.sub(lambda matchobj: """
{indent}<div class="codehilite"><pre class="language-{lang}"><code>{content}</code></pre></div>
""".format(
lang=matchobj.groupdict()['lang'],
indent=matchobj.groupdict()['indent'].replace('\n', ''),
content=html.escape(textwrap.dedent(matchobj.groupdict()['content']).rstrip())[1:]
).replace('\n', '<br />'),
content_raw
)
# print(content)
# assert False
else:
content = content_raw
if filetype == 'md':
if filebase == 'Usage-Format':
# content = content.replace('\\<argument\\>', '<argument>')
content_body = content.split('\n\n', 1)[1].replace('\\<argument\\>', '<argument>')
content = '[TOC]\n\n' + content_body
html_content = markdown.markdown(content, extensions=[
'markdown.extensions.fenced_code',
'markdown.extensions.footnotes',
'markdown.extensions.codehilite',
'markdown.extensions.toc',
])
# html_content = content
# html = markdown2.markdown(content, extras=[
# 'toc',
# 'fenced-code-blocks',
# 'footnotes',
# ])
elif filetype == 'rst':
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
html_content = core.publish_string(content, writer=html_fragment_writer).decode('utf-8')
if filebase in ('Home', '_Sidebar'):
html_content = re.sub('\\[\\[(.*?)\\]\\]', lambda matchobj: '<a href="/document/{link}">{linkname}</a>'.format(link=matchobj.group(1).replace(' ', '-'), linkname=matchobj.group(1)), html_content)
soup = BeautifulSoup(html_content, 'html5lib')
for link in soup.find_all('a'):
href = link.get('href')
if href and (href.startswith('http://') or href.startswith('https://')):
url_obj = urlparse(href)
if url_obj.hostname in ('docpie.comes.today', 'docpie.notexists.top'):
url = urlunparse(('', '', url_obj.path, url_obj.params, url_obj.query, url_obj.fragment))
link['href'] = url
for pre in soup.find_all('pre'):
# break
inner_pre = pre.decode_contents()
pre_class = pre.get('class') or []
inner_break = inner_pre.replace('\n', '<br />')
pre_soup = BeautifulSoup('<pre class="{classes}">{content}</pre>'.format(classes=' '.join(pre_class), content=inner_break), 'html5lib')
pre.replace_with(pre_soup.find('pre'))
body = soup.body.decode_contents()
target_filename = filebase + '.html'
logger.info('saving %s', target_filename)
with open(os.path.join(target_folder, target_filename), 'w', encoding='utf-8') as t:
t.write(body)
if __name__ == '__main__':
args = docpie.docpie(__doc__)
logging.basicConfig()
logger.setLevel(logging.DEBUG)
if args['web']:
args_port = args['<port>']
port = int(args_port) if args_port is not None else 8080
app.run(debug=False, port=port)
elif args['gen']:
# folder = args['<folder>']
gen_folder()
| 34.438202 | 211 | 0.554214 |
74c4473c59083174163d3f6c16e3dfce15977f62 | 3,264 | css | CSS | public/css/style.css | ezekiel37/expertsystem | ecacb2a78d43ca556ceb36ebc7d779a9e789b008 | [
"MIT"
] | null | null | null | public/css/style.css | ezekiel37/expertsystem | ecacb2a78d43ca556ceb36ebc7d779a9e789b008 | [
"MIT"
] | null | null | null | public/css/style.css | ezekiel37/expertsystem | ecacb2a78d43ca556ceb36ebc7d779a9e789b008 | [
"MIT"
] | null | null | null | * {
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
}
.hero{
display:flex;
background-color: white;
justify-content: center;
align-items: center;
overflow:hidden;
}
h1 {
font-size: 1.5rem;
font-weight: 400;
color:#3B82F6;
}
h3{
font-size: 1.5rem;
font-weight: 400;
color:#3B82F6;
}
p {
color: #334155;
line-height: 1.6;
}
body {
background-color: rgb(27, 96, 223);
background-size: 100% 1.2em;
}
.mainhero{
width:80%;
height:95vh;
margin-left: auto;
margin-right:auto;
padding-top: 3em;
background-color: rgb(255, 255, 255);
justify-content: center;
background-image: url("/expert.png");
background-repeat: no-repeat;
}
.image{
margin-left:-90px;
display: flex;
}
.image>img{
width:300px;
height:250px;
}
}
.maintext{
color:black;
font-size:2em;
margin:0px;
padding:0px;
text-align: center;
}
.ptext{
margin:0px;
position: absolute;
top:500px;
left:230px;
padding:0px;
text-align: center;
font-size: 1em;
}
.customlink{
text-decoration: none;
color:white;
background-color: #3B82F6;
padding: .6em 1.2em .6em 1.2em;
margin-top:2em;
margin-left:40%;
margin-right:auto;
position: absolute;
top:400px;
}
.info{
position: absolute;
top:520px;
margin:0px;
left:350px;
}
.copy{
position:absolute;
top:540px;
margin:0px;
left:600px;
}
.fixed-container {
position: absolute;
background-color: white;
border: black 1px solid;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
min-height: 36rem;
width: 48rem;
/* border: solid red 1px; */
overflow: hidden;
}
@media(min-width: 480px) {
.fixed-container {
width: 36rem;
}
}
.question-container {
padding: 2rem 4rem;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
.question-container--on-standby {
transform: translateY(200%);
visibility: hidden;
}
.question-container--slide-in {
transform: translateY(0);
visibility: visible;
transition: transform .6s cubic-bezier(0.4, 0.0, 1, 1),
visibility 0s cubic-bezier(0.4, 0.0, 1, 1);
}
.question-container--slide-out {
transform: translateY(-200%);
visibility: hidden;
transition: transform .8s cubic-bezier(0.0, 0.0, 0.2, 1),
visibility .8s cubic-bezier(0.0, 0.0, 0.2, 1);
}
.submit {
margin-top: 1rem;
padding: .5rem 1rem;
border: none;
background-color: #3B82F6;
color: white;
font-size: 1rem;
border-radius: 5px;
cursor: pointer;
transition: background-color linear .5s;
}
.submit:hover {
background-color: #60A5FA;
}
/* form starting stylings ------------------------------- */
input {
font-size:18px;
padding:10px 10px 10px 5px;
display:block;
width:300px;
border:none;
border-bottom:1px solid #757575;
}
input:focus { outline:none; }
::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
color: gray;
opacity: 1; /* Firefox */
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
color: gray;
}
::-ms-input-placeholder { /* Microsoft Edge */
color: gray;
}
.try-agn-btn {
margin-top: 1rem;
padding: .5rem 1rem;
border: none;
background-color: #3B82F6;
color: white;
font-size: 1rem;
border-radius: 5px;
cursor: pointer;
transition: background-color linear .5s;
} | 17.089005 | 60 | 0.643382 |
3abc4a489bd0cb56e01112b151c200c050c1b524 | 158 | swift | Swift | Frameworks/IpcCommon/Support/IpcMethodsRegisterer/IpcMethodHandlersRegisterer.swift | maxim4to/Mixbox | 350a707b117621e5f461e63075d341c2c21b6117 | [
"MIT"
] | 3 | 2019-10-15T08:17:19.000Z | 2019-11-15T08:15:50.000Z | Frameworks/IpcCommon/Support/IpcMethodsRegisterer/IpcMethodHandlersRegisterer.swift | maxim4to/Mixbox | 350a707b117621e5f461e63075d341c2c21b6117 | [
"MIT"
] | null | null | null | Frameworks/IpcCommon/Support/IpcMethodsRegisterer/IpcMethodHandlersRegisterer.swift | maxim4to/Mixbox | 350a707b117621e5f461e63075d341c2c21b6117 | [
"MIT"
] | null | null | null | #if MIXBOX_ENABLE_IN_APP_SERVICES
import MixboxIpc
public protocol IpcMethodHandlersRegisterer: class {
func registerIn(ipcRouter: IpcRouter)
}
#endif
| 15.8 | 52 | 0.816456 |
1a62787ee76c35bb93375fd7a2815c9641b5c3fa | 1,747 | py | Python | 05-07-a2/server_07_tone.py | hiro345g/raspi_magazine_201610_toku1 | f5dde65409eaeef15e15e6e2d5c86cbf0ac88ef5 | [
"MIT"
] | null | null | null | 05-07-a2/server_07_tone.py | hiro345g/raspi_magazine_201610_toku1 | f5dde65409eaeef15e15e6e2d5c86cbf0ac88ef5 | [
"MIT"
] | null | null | null | 05-07-a2/server_07_tone.py | hiro345g/raspi_magazine_201610_toku1 | f5dde65409eaeef15e15e6e2d5c86cbf0ac88ef5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request
import time, wiringpi
# -- ๅฎๆฐๅฎฃ่จ -- #
SPK_PIN = 5 # ๅง้ปในใใผใซใผใฎGPIO็ชๅท
# -- ้ขๆฐ -- #
def init():
""" wiringpiใจใฝใใใฆใงใขใใผใณใฎๅๆๅ """
wiringpi.wiringPiSetupGpio() # wiringpiๅๆๅ
wiringpi.softToneCreate(SPK_PIN) # ใฝใใใฆใงใขใใผใณๅๆๅ
def play(index):
""" wiringpiใซใใใฝใใใฆใงใขใใผใณๅ็"""
melody_list = [
((262, 0.5), (294, 0.5), (330, 0.5), (349, 0.5), (392, 0.5), (440, 0.5), (494, 0.5), (525, 0.5)),
((525, 0.5), (494, 0.5), (440, 0.5), (392, 0.5), (349, 0.5), (330, 0.5), (294, 0.5), (262, 0.5)),
((262, 1), (294, 1), (330, 1), (349, 1), (392, 1), (440, 1), (494, 1), (525, 1)),
]
for v, play_time in melody_list[index]: # ๆๅฎใใใใกใญใใฃใผใฎๅ็
wiringpi.softToneWrite(SPK_PIN, v) # ใใผใณ็บ็
time.sleep(play_time) # ๅใ้ณใๅบๅใใใใใซๅฆ็ใ้
ๅปถ
play_stop()
def play_stop():
""" ๅ็็ตไบ """
wiringpi.softToneWrite(SPK_PIN, 0) # ๅ็็ตไบ
def shutdown_server():
""" ใตใผใใผๅๆญข """
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
# -- ๅๆๅใ Flaskใขใใชใฎ็จๆ -- #
init()
app = Flask(__name__) # ใขใใชๆฌไฝ็จ
# -- ใซใผใใฃใณใฐ -- #
@app.route('/speaker/', methods=['GET'])
def speaker():
"""ใชใขใผใๅง้ปในใใผใซใผ็จใกใใฅใผ่กจ็คบ"""
return render_template('app_07_speaker.html')
@app.route('/speaker/<int:id>', methods=['POST'])
def speaker_play(id):
"""ใชใขใผใๅง้ปในใใผใซใผๅ็"""
play(id)
return render_template('app_07_speaker.html')
@app.route('/shutdown', methods=['POST'])
def shutdown():
play_stop()
shutdown_server()
return 'Server shutting down...'
if __name__ == '__main__':
app.run(host='0.0.0.0')
| 24.605634 | 105 | 0.594734 |
711c1915f45532fab523f3e6ea35c5063f726ca6 | 2,400 | lua | Lua | scripts/enemy_generator.lua | gabrielnaves/Fireboy-Ludum-Dare-40 | 3638f0d6fefb95525870ca03434b5c9394b96dc4 | [
"MIT"
] | null | null | null | scripts/enemy_generator.lua | gabrielnaves/Fireboy-Ludum-Dare-40 | 3638f0d6fefb95525870ca03434b5c9394b96dc4 | [
"MIT"
] | null | null | null | scripts/enemy_generator.lua | gabrielnaves/Fireboy-Ludum-Dare-40 | 3638f0d6fefb95525870ca03434b5c9394b96dc4 | [
"MIT"
] | null | null | null | -- enemy = require("enemy.lua")
enemyGenerator = {}
enemyGenerator.enemies = {}
enemyGenerator.enemyAmount = 0
-- Timers
enemyGenerator.initialDelayTimer = 0
enemyGenerator.initialDelay = 4
enemyGenerator.enemyGenTimer = 0
enemyGenerator.startingGenTime = 4
enemyGenerator.enemyGenTime = 4
function enemyGenerator.update(dt)
if gamestate.state == gamestate.states.ingame then
enemyGenerator.initialDelayTimer = enemyGenerator.initialDelayTimer + dt
if enemyGenerator.initialDelayTimer > enemyGenerator.initialDelay then
enemyGenerator.scaleGenTimeWithFireLevel()
enemyGenerator.enemyGenTimer = enemyGenerator.enemyGenTimer + dt
if enemyGenerator.enemyGenTimer > enemyGenerator.enemyGenTime then
enemyGenerator.enemyGenTimer = 0
enemyGenerator.generateEnemy(love.math.random(-10, 370), camera.y - 32)
end
enemyGenerator.updateEnemyArray(dt)
end
end
end
function enemyGenerator.scaleGenTimeWithFireLevel()
if firebar.fire <= 100 then
enemyGenerator.enemyGenTime = enemyGenerator.startingGenTime
else
enemyGenerator.enemyGenTime = enemyGenerator.startingGenTime *
(1 - firebar.fire / firebar.maxFire) + 0.8
end
end
function enemyGenerator.generateEnemy(xPos, yPos)
local newEnemy = base_enemy:createEnemy(xPos, yPos)
table.insert(enemyGenerator.enemies, newEnemy)
enemyGenerator.enemyAmount = enemyGenerator.enemyAmount + 1
end
function enemyGenerator.updateEnemyArray(dt)
for i, enemy in ipairs(enemyGenerator.enemies) do
if enemy.y - camera.y > 640*3 then
enemyGenerator.killEnemy(i)
else
base_enemy.update(dt, enemy, i)
end
end
end
function enemyGenerator.draw(dt)
for i, enemy in ipairs(enemyGenerator.enemies) do
base_enemy.draw(dt, enemy)
end
end
function enemyGenerator.reset()
enemyGenerator.enemyGenTimer = 0
enemyGenerator.enemies = {}
enemyGenerator.enemyAmount = 0
enemyGenerator.initialDelayTimer = 0
end
function enemyGenerator.killEnemy(i)
animationManager.newAnimation(enemyDeath.animIndex, enemyGenerator.enemies[i].x, enemyGenerator.enemies[i].y)
table.remove(enemyGenerator.enemies, i)
enemyGenerator.enemyAmount = enemyGenerator.enemyAmount - 1
end
return enemyGenerator
| 32.432432 | 113 | 0.721667 |
af8a5e60b53f239fae73143bff4ffaa80fca775c | 5,023 | py | Python | core/randomdata.py | ducanh-99/project_design | 9f59aa4a0748a26d9c58dab8f69fce22e372ecb0 | [
"MIT"
] | null | null | null | core/randomdata.py | ducanh-99/project_design | 9f59aa4a0748a26d9c58dab8f69fce22e372ecb0 | [
"MIT"
] | null | null | null | core/randomdata.py | ducanh-99/project_design | 9f59aa4a0748a26d9c58dab8f69fce22e372ecb0 | [
"MIT"
] | null | null | null | from hashlib import new
import random
import bisect
import csv
import datetime
import time
class StartDate:
year = 2020
month = 1
date = 1
class EndDate:
year = 2021
month = 1
date = 1
class graph:
def __init__(self, gdict=None, res=[]):
if gdict is None:
gdict = {}
self.gdict = gdict
self.res = res
def getVertices(self):
return list(self.gdict.keys())
def addVertex(self, v):
if v not in self.gdict:
self.gdict[v] = {}
def addEdge(self, v1, v2, w):
if v1 in self.gdict:
self.gdict[v1][v2] = w
else:
self.gdict[v1] = [[v2, w]]
def printGraph(self):
for vertex in self.gdict:
for edge in self.gdict[vertex]:
print(str(vertex) + " -> " + str(edge) +
", edge weight: " + str(self.gdict[vertex][edge]))
def getSubGraph(self, vertexSet):
res = graph(None)
for v1 in vertexSet:
#print("First vertex is :", v1)
res.addVertex(v1)
for v2 in vertexSet:
#print("Second vertex is :", v2)
if v2 in self.gdict[v1]:
#print(v1, " --> ", v2)
res.addEdge(v1, v2, self.gdict[v1][v2])
#print ("-----")
return res
def getRandomWeightedVertex(self, v):
sums = {}
S = 0
for vertex in self.gdict[v]:
if vertex not in self.res:
# print "Adding " + str(self.gdict[v][vertex])
S += self.gdict[v][vertex]
sums[vertex] = S
# print sums
r = random.uniform(0, S)
for k in sums.keys():
if (r <= sums[k]):
return k
def randomWeightedPath(self, first_edge, max_len):
self.res = []
prev_vertex = 0
self.res.append(first_edge)
weight_value = 0
while(len(self.res) < len(self.gdict.keys())):
new_vertex = self.getRandomWeightedVertex(prev_vertex)
if len(self.res) >= max_len:
break
if new_vertex not in self.res:
self.res.append(new_vertex)
weight_value += self.gdict[prev_vertex][new_vertex]
prev_vertex = new_vertex
else:
continue
return self.res, weight_value
def generateTime(self, duration):
rtime = int(random.random()*86400)
hours = 0
while hours < 7 or (12 < hours and hours < 12) or 17 < hours:
rtime = int(random.random()*86400)
hours = int(rtime/3600)
minutes = int((rtime - hours*3600)/60)
seconds = rtime - hours*3600 - minutes*60
time_string = datetime.time(hour=hours, minute=minutes, second=seconds)
return time_string
def generateDate(self):
start_date = datetime.date(
StartDate.year, StartDate.month, StartDate.date)
end_date = datetime.date(EndDate.year, EndDate.month, EndDate.date)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + \
datetime.timedelta(days=random_number_of_days)
print(random_date)
def autoPlus(self, duration, start_time):
minutes_added = datetime.timedelta(minutes=duration)
end_time = start_time + minutes_added
print(end_time)
return end_time
testgraph = graph({0: {1: 5, 2: 0, 3: 5, 4: 0, 5: 1, 6: 1, 7: 4, 8: 2, 9: 0, 10: 12},
1: {0: 0, 2: 2, 3: 8, 4: 0, 5: 1, 6: 1, 7: 15, 8: 0, 9: 4, 10: 1},
2: {0: 0, 1: 5, 3: 5, 4: 0, 5: 0, 6: 4, 7: 3, 8: 2, 9: 1, 10: 1},
3: {0: 0, 1: 4, 2: 6, 4: 0, 5: 1, 6: 3, 7: 2, 8: 0, 9: 1, 10: 6},
4: {0: 3, 1: 4, 2: 3, 5: 2, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0},
5: {0: 2, 1: 4, 2: 10, 4: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0},
6: {0: 2, 1: 4, 2: 10, 4: 0, 5: 0, 7: 1, 8: 0, 9: 1, 10: 0},
7: {0: 2, 1: 4, 2: 10, 4: 0, 5: 0, 6: 0, 8: 0, 9: 1, 10: 0},
8: {0: 2, 1: 4, 2: 10, 4: 0, 5: 0, 6: 10, 7: 0, 9: 1, 10: 2},
9: {0: 2, 1: 4, 2: 10, 4: 0, 5: 0, 6: 3, 7: 4, 8: 0, 10: 2},
10: {0: 2, 1: 4, 2: 10, 4: 0, 5: 0, 6: 2, 7: 8, 8: 5, 9: 3}
})
res = []
for i in range(5):
max_len = random.randrange(1, 10)
first_edge = random.randrange(0, 9)
# print(testgraph.randomWeightedPath(first_edge, max_len))
a = testgraph.generateTime(5)
# testgraph.generateDate()
testgraph.autoPlus(start_time=a, duration=4)
# res.append(testgraph.randomWeightedPath(
# first_edge=first_edge, max_len=max_len)[0])
# f = open('data.csv', 'a')
# with f:
# writer = csv.writer(f)
# for row in res:
# writer.writerow(row)
| 31.198758 | 85 | 0.506868 |
8e51b8861eab47911303b826082c89ef4ad0970a | 408 | c | C | srclua5/ctrl/iuplua_filedlg.c | hleuwer/iup | 6bafeb94b652c2a3ea1ef8ef3a9de6fd819e6b6e | [
"MIT"
] | 1 | 2018-03-14T15:39:18.000Z | 2018-03-14T15:39:18.000Z | srclua5/ctrl/iuplua_filedlg.c | hleuwer/iup | 6bafeb94b652c2a3ea1ef8ef3a9de6fd819e6b6e | [
"MIT"
] | 1 | 2019-01-14T07:02:42.000Z | 2019-01-14T07:02:42.000Z | srclua5/ctrl/iuplua_filedlg.c | hleuwer/iup | 6bafeb94b652c2a3ea1ef8ef3a9de6fd819e6b6e | [
"MIT"
] | 3 | 2017-03-24T00:31:58.000Z | 2018-12-27T09:41:59.000Z |
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
#include "iup.h"
#include "iuplua.h"
#include "iupfiledlg.h"
#include "il.h"
int iupfiledlglua_open(lua_State* L)
{
if (iuplua_opencall_internal(L))
IupNewFileDlgOpen();
return 0;
}
/* obligatory to use require"iupluafiledlg" */
int luaopen_iupluafiledlg(lua_State* L)
{
return iupfiledlglua_open(L);
}
| 15.692308 | 47 | 0.659314 |
a38695c06c859e2497654214c773f5867e9a6971 | 2,858 | tsx | TypeScript | frontend/pages/queries/QueryPage/components/TargetsInput/TargetsInputHostsTableConfig.tsx | groob/fleetdm-fleet | e286ee387ecb987ea402c86bda8084e023975727 | [
"MIT"
] | 1 | 2021-04-20T21:29:18.000Z | 2021-04-20T21:29:18.000Z | frontend/pages/queries/QueryPage/components/TargetsInput/TargetsInputHostsTableConfig.tsx | clong/fleet | b11c6ffe319e1d394713def6cf9bd66bba4fd6bd | [
"MIT"
] | 2 | 2022-03-24T04:36:15.000Z | 2022-03-31T18:55:02.000Z | frontend/pages/queries/QueryPage/components/TargetsInput/TargetsInputHostsTableConfig.tsx | clong/fleet | b11c6ffe319e1d394713def6cf9bd66bba4fd6bd | [
"MIT"
] | null | null | null | /* eslint-disable react/prop-types */
import React from "react";
import { Cell, UseRowSelectInstanceProps } from "react-table";
import { IDataColumn } from "interfaces/datatable_config";
// @ts-ignore
import Checkbox from "components/forms/fields/Checkbox";
import TextCell from "components/TableContainer/DataTable/TextCell";
import StatusCell from "components/TableContainer/DataTable/StatusCell/StatusCell";
interface ITargetHostsTableData {
hostname: string;
status: string;
primary_ip: string;
primary_mac: string;
os_version: string;
osquery_version: string;
}
// NOTE: cellProps come from react-table
// more info here https://react-table.tanstack.com/docs/api/useTable#cell-properties
export const generateTableHeaders = (
shouldShowSelectionHeader: boolean
): IDataColumn[] => {
const selectionHeader = shouldShowSelectionHeader
? [
{
id: "selection",
Header: (
cellProps: UseRowSelectInstanceProps<ITargetHostsTableData>
): JSX.Element => {
const props = cellProps.getToggleAllRowsSelectedProps();
const checkboxProps = {
value: props.checked,
indeterminate: props.indeterminate,
onChange: () => cellProps.toggleAllRowsSelected(),
};
return <Checkbox {...checkboxProps} />;
},
Cell: (cellProps: Cell): JSX.Element => {
const props = cellProps.row.getToggleRowSelectedProps();
const checkboxProps = {
value: props.checked,
onChange: () => cellProps.row.toggleRowSelected(),
};
return <Checkbox {...checkboxProps} />;
},
disableHidden: true,
},
]
: [];
return [
...selectionHeader,
{
title: "Hostname",
Header: "Hostname",
disableSortBy: true,
accessor: "hostname",
Cell: (cellProps) => <TextCell value={cellProps.cell.value} />,
},
{
title: "Status",
Header: "Status",
disableSortBy: true,
accessor: "status",
Cell: (cellProps) => <StatusCell value={cellProps.cell.value} />,
},
{
title: "IP address",
Header: "IP address",
accessor: "primary_ip",
Cell: (cellProps) => <TextCell value={cellProps.cell.value} />,
},
{
title: "MAC address",
Header: "MAC address",
accessor: "primary_mac",
Cell: (cellProps) => <TextCell value={cellProps.cell.value} />,
},
{
title: "OS",
Header: "OS",
accessor: "os_version",
Cell: (cellProps) => <TextCell value={cellProps.cell.value} />,
},
{
title: "Osquery",
Header: "Osquery",
accessor: "osquery_version",
Cell: (cellProps) => <TextCell value={cellProps.cell.value} />,
},
];
};
export default null;
| 28.868687 | 84 | 0.601819 |
a3838802f2504ce3fa37436915c85dbe757d1687 | 9,454 | java | Java | compiler/src/test-integration/java/io/neow3j/compiler/ByteStringIntegrationTest.java | neow3j/neow3j | dab05124e063032c9176471563416abba46cb1e7 | [
"Apache-2.0"
] | 135 | 2018-12-09T16:54:43.000Z | 2022-03-21T18:42:27.000Z | compiler/src/test-integration/java/io/neow3j/compiler/ByteStringIntegrationTest.java | neow3j/neow3j | dab05124e063032c9176471563416abba46cb1e7 | [
"Apache-2.0"
] | 620 | 2018-12-18T13:08:36.000Z | 2022-03-29T15:26:49.000Z | compiler/src/test-integration/java/io/neow3j/compiler/ByteStringIntegrationTest.java | neow3j/neow3j | dab05124e063032c9176471563416abba46cb1e7 | [
"Apache-2.0"
] | 27 | 2018-12-21T08:09:46.000Z | 2022-02-09T03:24:37.000Z | package io.neow3j.compiler;
import io.neow3j.protocol.core.stackitem.StackItem;
import io.neow3j.types.ContractParameter;
import io.neow3j.devpack.ByteString;
import io.neow3j.protocol.core.response.InvocationResult;
import io.neow3j.types.NeoVMStateType;
import io.neow3j.types.StackItemType;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import java.io.IOException;
import java.math.BigInteger;
import static io.neow3j.types.ContractParameter.byteArray;
import static io.neow3j.types.ContractParameter.byteArrayFromString;
import static io.neow3j.types.ContractParameter.integer;
import static io.neow3j.types.ContractParameter.string;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class ByteStringIntegrationTest {
@Rule
public TestName testName = new TestName();
@ClassRule
public static ContractTestRule ct = new ContractTestRule(
ByteStringIntegrationTest.ByteStringIntegrationTestContract.class.getName());
@Test
public void createByteStringFromString() throws IOException {
InvocationResult res = ct.callInvokeFunction(testName).getInvocationResult();
assertThat(res.getStack().get(0).getString(), is("hello, world!"));
}
@Test
public void createByteStringFromByteArray() throws IOException {
InvocationResult res = ct.callInvokeFunction(testName).getInvocationResult();
assertThat(res.getStack().get(0).getByteArray(), is(new byte[]{0x00, 0x01, 0x02, 0x03}));
}
@Test
public void getElementsOfByteString() throws IOException {
ContractParameter byteString = byteArray("00010203");
InvocationResult res = ct.callInvokeFunction(testName, byteString, integer(0))
.getInvocationResult();
assertThat(res.getStack().get(0).getInteger().intValue(), is(0));
res = ct.callInvokeFunction(testName, byteString, integer(3))
.getInvocationResult();
assertThat(res.getStack().get(0).getInteger().intValue(), is(3));
}
@Test
public void getByteStringLength() throws IOException {
ContractParameter byteString = byteArray("00010203");
InvocationResult res = ct.callInvokeFunction(testName, byteString).getInvocationResult();
assertThat(res.getStack().get(0).getInteger().intValue(), is(4));
byteString = string("hello, world!");
res = ct.callInvokeFunction(testName, byteString).getInvocationResult();
assertThat(res.getStack().get(0).getInteger().intValue(), is(13));
}
@Test
public void byteStringToInteger() throws IOException {
ContractParameter byteString = byteArray("00010203");
InvocationResult res = ct.callInvokeFunction(testName, byteString).getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.INTEGER));
assertThat(item.getInteger(), is(new BigInteger("50462976")));
}
@Test
public void byteStringToIntegerNull() throws IOException {
// Test that instructions return null if no value was found for the provided key.
InvocationResult res = ct.callInvokeFunction(testName).getInvocationResult();
assertThat(res.getStack(), hasSize(0));
assertThat(res.getState(), is(NeoVMStateType.FAULT));
}
@Test
public void byteStringToIntOrZero() throws IOException {
ContractParameter byteString = byteArray("0001020304");
InvocationResult res = ct.callInvokeFunction(testName, byteString).getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.INTEGER));
assertThat(item.getInteger(), is(new BigInteger("17230332160")));
}
@Test
public void byteStringToIntOrZeroNull() throws IOException {
InvocationResult res = ct.callInvokeFunction(testName).getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.INTEGER));
assertThat(item.getInteger(), is(BigInteger.ZERO));
}
@Test
public void byteStringToByteArray() throws IOException {
ContractParameter byteString = string("hello, world!");
InvocationResult res = ct.callInvokeFunction(testName, byteString).getInvocationResult();
assertThat(res.getStack().get(0).getHexString(), is("68656c6c6f2c20776f726c6421"));
}
@Test
public void byteStringAsString() throws IOException {
ContractParameter byteString = string("hello, world!");
InvocationResult res = ct.callInvokeFunction(testName, byteString).getInvocationResult();
assertThat(res.getStack().get(0).getString(), is("hello, world!"));
}
@Test
public void concatenateByteStrings() throws IOException {
ContractParameter s1 = string("hello, ");
ContractParameter s2 = string("world!");
InvocationResult res = ct.callInvokeFunction(testName, s1, s2).getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.BYTE_STRING));
assertThat(item.getString(), is("hello, world!"));
}
@Test
public void concatenateWithByteArray() throws IOException {
ContractParameter s = byteArray("00010203");
InvocationResult res = ct.callInvokeFunction(testName, s).getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.BYTE_STRING));
assertThat(item.getHexString(), is("00010203040506"));
}
@Test
public void concatenateWithString() throws IOException {
ContractParameter s = byteArrayFromString("hello, ");
InvocationResult res = ct.callInvokeFunction(testName, s).getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.BYTE_STRING));
assertThat(item.getString(), is("hello, moon!"));
}
@Test
public void getRangeOfByteString() throws IOException {
ContractParameter s = byteArray("0001020304");
InvocationResult res = ct.callInvokeFunction(testName, s, integer(2), integer(3))
.getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.BYTE_STRING));
assertThat(item.getHexString(), is("020304"));
}
@Test
public void takeNFirstBytesOfByteString() throws IOException {
ContractParameter s = byteArray("0001020304");
InvocationResult res = ct.callInvokeFunction(testName, s, integer(2))
.getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.BYTE_STRING));
assertThat(item.getHexString(), is("0001"));
}
@Test
public void takeNLastBytesOfByteString() throws IOException {
ContractParameter s = byteArray("0001020304");
InvocationResult res = ct.callInvokeFunction(testName, s, integer(2))
.getInvocationResult();
StackItem item = res.getStack().get(0);
assertThat(item.getType(), is(StackItemType.BYTE_STRING));
assertThat(item.getHexString(), is("0304"));
}
static class ByteStringIntegrationTestContract {
public static ByteString createByteStringFromString() {
return new ByteString("hello, world!");
}
public static ByteString createByteStringFromByteArray() {
return new ByteString(new byte[]{0x00, 0x01, 0x02, 0x03});
}
public static byte getElementsOfByteString(ByteString s, int index) {
return s.get(index);
}
public static int getByteStringLength(ByteString s) {
return s.length();
}
public static String byteStringAsString(ByteString s) {
return s.toString();
}
public static byte[] byteStringToByteArray(ByteString s) {
return s.toByteArray();
}
public static int byteStringToInteger(ByteString s) {
return s.toInt();
}
public static int byteStringToIntegerNull() {
ByteString s = null;
return s.toInt();
}
public static int byteStringToIntOrZero(ByteString s) {
return s.toIntOrZero();
}
public static int byteStringToIntOrZeroNull() {
ByteString s = null;
return s.toIntOrZero();
}
public static ByteString concatenateByteStrings(ByteString s1, ByteString s2) {
return s1.concat(s2);
}
public static ByteString concatenateWithByteArray(ByteString s) {
byte[] bs = new byte[]{0x04, 0x05, 0x06};
return s.concat(bs);
}
public static ByteString concatenateWithString(ByteString s) {
return s.concat("moon!");
}
public static ByteString getRangeOfByteString(ByteString s, int start, int n) {
return s.range(start, n);
}
public static ByteString takeNFirstBytesOfByteString(ByteString s, int n) {
return s.take(n);
}
public static ByteString takeNLastBytesOfByteString(ByteString s, int n) {
return s.last(n);
}
}
}
| 38.275304 | 97 | 0.672414 |
30e99fa8ce59598800f89a6be6e0f8f6d70612ad | 2,941 | php | PHP | resources/views/layouts/nav-header.blade.php | edgardominguez23/bookstore | 6873bf0711a0f630a46f1c48f97b553687dfd2e8 | [
"MIT"
] | null | null | null | resources/views/layouts/nav-header.blade.php | edgardominguez23/bookstore | 6873bf0711a0f630a46f1c48f97b553687dfd2e8 | [
"MIT"
] | null | null | null | resources/views/layouts/nav-header.blade.php | edgardominguez23/bookstore | 6873bf0711a0f630a46f1c48f97b553687dfd2e8 | [
"MIT"
] | null | null | null | <nav id="barraNaveg" class="navbar navbar-expand-lg navbar-dark bg-dark">
<a href="/" style="text-decoration:none"><h3 class="text-white mr-5">BookStore</h3></a>
<form class="form-inline my-2 my-lg-0 ml-5" action="{{route('home.search')}}" method="GET">
<div class="input-group">
<input type="search" class="form-control" placeholder="Libro" name="text"
<div class="input-group-append">
<button class="btn btn-warning" type="submit">Buscar</button>
</div>
</div>
</form>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"></ul>
<ul class="navbar-nav">
@if (Route::has('login'))
@auth <!--Usuario autenticado-->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Cuenta
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<span class="dropdown-item">{{ Auth::user()->name }}</span>
@if (Auth::user()->rol_id == 2)
<a class="dropdown-item" href="/admin">Administracion</a>
@elseif (Auth::user()->rol_id == 3)
<a class="dropdown-item" href="/dashboard/book">Administracion</a>
@else
<a class="dropdown-item" href="/historial-compras">Historial de compras</a>
@endif
<a class="dropdown-item" type="submit" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
@csrf
</form>
</div>
</li>
@else <!--Usuario no autenticado-->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Identificate
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="{{ route('login') }}">Log in</a>
<a class="dropdown-item" href="{{ route('register') }}">Register</a>
</div>
</li>
@endauth
<li class="nav-item">
<a type="submit" class="btn btn-black" href="{{route('cart.list')}}">
<span class="text-white mr-1">Carrito</span><span class="badge badge-success">{{ Cart::getTotalQuantity()}}</span>
<span class="sr-only">unread messages</span>
</a>
</li>
@endif
</ul>
</div>
</nav> | 50.706897 | 167 | 0.533492 |
ed3d76ad8f56236c91611ee40baee869fb0bc222 | 865 | h | C | openmit/tools/util/type_conversion.h | openmit/openmit | 01e3262d69d47fbe38bad1ba95c7d1ade110d01e | [
"Apache-2.0"
] | 15 | 2017-06-28T08:39:51.000Z | 2019-03-27T14:08:45.000Z | openmit/tools/util/type_conversion.h | openmit/openmit | 01e3262d69d47fbe38bad1ba95c7d1ade110d01e | [
"Apache-2.0"
] | null | null | null | openmit/tools/util/type_conversion.h | openmit/openmit | 01e3262d69d47fbe38bad1ba95c7d1ade110d01e | [
"Apache-2.0"
] | 3 | 2017-07-30T08:50:45.000Z | 2017-10-24T14:41:30.000Z | /*!
* Copyright 2016 by Contributors
* \file type_conversion.h
* \brief basic type conversion
* \author ZhouYong
*/
#ifndef OPENMIT_TOOLS_UTIL_TYPE_CONVERSION_H_
#define OPENMIT_TOOLS_UTIL_TYPE_CONVERSION_H_
#include <sstream>
#include <stdint.h>
#include <string>
namespace mit {
/*!
* \brief convert string to real type.
* std::string str = "12345678";
* uint32_t value = StringToNum<uint32_t>(str);
*/
template <typename Type>
Type StringToNum(const std::string & str) {
std::istringstream buffer(str);
Type value; buffer >> value;
return value;
}
/*!
* \brief convert numeric type to string type
*/
template <typename Type>
std::string NumToString(const Type & value) {
std::ostringstream buffer;
buffer << value;
return std::string(buffer.str());
}
} // namespace mit
#endif // OPENMIT_TOOLS_UTIL_TYPE_CONVERSION_H_
| 21.097561 | 54 | 0.710983 |
f93687b56a461d7b338de8059812cc1f19675a72 | 261 | ps1 | PowerShell | src/Internal/Test-Administrator.ps1 | CodeblackNL/UPCluster | a1ee9887f8eab9c561c47e427f733cdf75ef616f | [
"MIT"
] | null | null | null | src/Internal/Test-Administrator.ps1 | CodeblackNL/UPCluster | a1ee9887f8eab9c561c47e427f733cdf75ef616f | [
"MIT"
] | null | null | null | src/Internal/Test-Administrator.ps1 | CodeblackNL/UPCluster | a1ee9887f8eab9c561c47e427f733cdf75ef616f | [
"MIT"
] | null | null | null | #Requires -Version 5.0
function Test-Administrator {
return (New-Object -TypeName Security.Principal.WindowsPrincipal -ArgumentList ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
} | 52.2 | 202 | 0.796935 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.