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
listlengths
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
listlengths
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
listlengths
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
051f76c129b4c7af97ba1fb26ab42b9278001260
367
swift
Swift
integration_tests/PrebuiltPodIntegrationTests/Tests/UICommonsDynamicTests.swift
pandaleecn/cocoapods-binary-ht
aec4f832304eb44ec176254ea04fc62268db8283
[ "MIT" ]
null
null
null
integration_tests/PrebuiltPodIntegrationTests/Tests/UICommonsDynamicTests.swift
pandaleecn/cocoapods-binary-ht
aec4f832304eb44ec176254ea04fc62268db8283
[ "MIT" ]
null
null
null
integration_tests/PrebuiltPodIntegrationTests/Tests/UICommonsDynamicTests.swift
pandaleecn/cocoapods-binary-ht
aec4f832304eb44ec176254ea04fc62268db8283
[ "MIT" ]
null
null
null
// // UICommonsDynamicTests.swift // PrebuiltPodIntegrationTests // // Created by Ngoc Thuyen Trinh on 09/10/2020. // Copyright © 2020 panda. All rights reserved. // import XCTest import UICommonsDynamic final class UICommonsDynamicTests: XCTestCase { func testUICommonsDynamicTests() { XCTAssertNotNil(UICommonsDynamic.jsonString(from: "dynamic")) } }
21.588235
65
0.757493
7c249ddde0e6670d397d9b27655fcca3c5cb798e
20,466
lua
Lua
addons/pac3-master/lua/pac3/editor/client/mctrl.lua
Jck123/gmodserver
584d0529f22aa11f5dc2402b1597ffdbb1c69781
[ "Apache-2.0" ]
null
null
null
addons/pac3-master/lua/pac3/editor/client/mctrl.lua
Jck123/gmodserver
584d0529f22aa11f5dc2402b1597ffdbb1c69781
[ "Apache-2.0" ]
null
null
null
addons/pac3-master/lua/pac3/editor/client/mctrl.lua
Jck123/gmodserver
584d0529f22aa11f5dc2402b1597ffdbb1c69781
[ "Apache-2.0" ]
null
null
null
pace.mctrl = {} local mctrl = pace.mctrl mctrl.AXIS_X = 1 mctrl.AXIS_Y = 2 mctrl.AXIS_Z = 3 mctrl.AXIS_VIEW = 4 mctrl.MODE_MOVE = 1 mctrl.MODE_ROTATE = 2 mctrl.MODE_SCALE = 3 local AXIS_X, AXIS_Y, AXIS_Z, AXIS_VIEW = mctrl.AXIS_X, mctrl.AXIS_Y, mctrl.AXIS_Z, mctrl.AXIS_VIEW local MODE_MOVE, MODE_ROTATE, MODE_SCALE = mctrl.MODE_MOVE, mctrl.MODE_ROTATE, mctrl.MODE_SCALE mctrl.radius_scale = 1.1 mctrl.grab_dist = 15 mctrl.angle_pos = 0.5 mctrl.scale_pos = 0.25 do -- pace mctrl.target = pac.NULL function mctrl.SetTarget(part) part = part or pac.NULL if not part:IsValid() then mctrl.target = pac.NULL return end if (part.NonPhysical and part.ClassName ~= 'group') or part.HideGizmo then mctrl.target = pac.NULL else mctrl.target = part end end function mctrl.GetTarget() return mctrl.target:IsValid() and not mctrl.target:IsHidden() and mctrl.target or pac.NULL end function mctrl.GetAxes(ang) return ang:Forward(), ang:Right() *-1, ang:Up() end function mctrl.GetTargetPos() local part = mctrl.GetTarget() if part:IsValid() then if part.ClassName ~= 'group' then return part:GetDrawPosition() elseif part.centrePos then return part.centrePos + part.centrePosMV, part.centreAngle else return part.centrePos, part.centreAngle end end end function mctrl.GetBonePos() local part = mctrl.GetTarget() if part:IsValid() then if part.ClassName ~= 'group' then return part:GetBonePosition() else return part.centrePos, Angle(0, 0, 0) end end end function mctrl.GetTargetPosition(pos, ang) local wpos, wang = mctrl.GetBonePos() if wpos and wang then return WorldToLocal(pos, ang, wpos, wang) end end function mctrl.GetCameraOrigin() return pace.GetViewPos() end function mctrl.GetCameraFOV() if pace.editing_viewmodel or pace.editing_hands then return LocalPlayer():GetActiveWeapon().ViewModelFOV or 55 end return pace.GetViewFOV() end function mctrl.GetCameraAngles() return pace.GetViewAngles() end function mctrl.GetMousePos() return gui.MousePos() end function mctrl.VecToScreen(vec) local x,y,vis = pace.VectorToLPCameraScreen( (vec - EyePos()):GetNormalized(), ScrW(), ScrH(), EyeAngles(), math.rad(mctrl.GetCameraFOV()) ) return {x=x-1,y=y-1, visible = vis == 1} end function mctrl.ScreenToVec(x,y) local vec = pace.LPCameraScreenToVector( x, y, ScrW(), ScrH(), EyeAngles(), math.rad(mctrl.GetCameraFOV()) ) return vec end function mctrl.GetCalculatedScale() local part = pace.current_part if pace.editing_viewmodel or pace.editing_hands then return 5 end if part.ClassName == "clip" then part = part.Parent end if part.ClassName == "camera" then return 30 end if part.ClassName == "group" then return 45 end if not part:IsValid() then return 3 end local dist = (part.cached_pos:Distance(pace.GetViewPos()) / 50) if dist > 1 then dist = 1 / dist end return 5 * math.rad(pace.GetViewFOV()) / dist end local cvar_pos_grid = CreateClientConVar("pac_grid_pos_size", "4") local groupOriginalValues function mctrl.OnMove(part, pos) if input.IsKeyDown(KEY_LCONTROL) then local num = cvar_pos_grid:GetInt("pac_grid_pos_size") pos.x = math.Round(pos.x/num) * num pos.y = math.Round(pos.y/num) * num pos.z = math.Round(pos.z/num) * num end if part.ClassName ~= 'group' then pace.Call("VariableChanged", part, "Position", pos, 0.25) timer.Create("pace_refresh_properties", 0.1, 1, function() pace.PopulateProperties(part) end) else local undo = {} local diffVector = part.centrePosMV - pos diffVector.y = -diffVector.y part.centrePosMV = pos diffVector:Rotate(Angle(-180, -pac.LocalPlayer:EyeAngles().y, 0)) for i, child in ipairs(part:GetChildren()) do if child.GetAngles and child.GetPosition then if not groupOriginalValues then groupOriginalValues = {} for i, child in ipairs(part:GetChildren()) do if child.GetAngles and child.GetPosition then groupOriginalValues[i] = Vector(child:GetPosition()) end end end -- too complex, putting comments -- getting part's bone position to use as one point of local coordinate system local bpos, bang = child:GetBonePosition() -- getting our groun calculated position local gpos, gang = mctrl.GetTargetPos() -- translating GROUP position to be relative to BONE's position local lbpos, lbang = WorldToLocal(gpos, gang, bpos, bang) -- now we have diff vector and angles between group position and part's bone position -- let's get relative position of our part to group local pos, ang = Vector(child:GetPosition()), Angle(child:GetAngles()) local lpos, lang = WorldToLocal(pos, ang, lbpos, lbang) -- we finally got our position and angles! now rotate lpos = lpos + diffVector -- rotated, restore local positions to be relative to GROUP's LOCAL position (stack up) local fpos, fang = LocalToWorld(lpos, lang, lbpos, lbang) table.insert(undo, { child, Vector(groupOriginalValues[i]), Vector(fpos), }) pace.Call("VariableChanged", child, "Position", fpos, false) end end if #undo ~= 0 then timer.Create('pac3_apply_undo_func', 0.25, 1, function() groupOriginalValues = nil pace.AddUndo(nil, function() for i, data in ipairs(undo) do pace.Call("VariableChanged", data[1], "Position", data[2], false) end end, function() for i, data in ipairs(undo) do pace.Call("VariableChanged", data[1], "Position", data[3], false) end end) end) end end end local cvar_ang_grid = CreateClientConVar("pac_grid_ang_size", "45") function mctrl.OnRotate(part, ang) if input.IsKeyDown(KEY_LCONTROL) then local num = cvar_ang_grid:GetInt("pac_grid_ang_size") ang.p = math.Round(ang.p/num) * num ang.y = math.Round(ang.y/num) * num ang.r = math.Round(ang.r/num) * num end if part.ClassName ~= 'group' then pace.Call("VariableChanged", part, "Angles", ang, 0.25) timer.Create("pace_refresh_properties", 0.1, 1, function() pace.PopulateProperties(part) end) else local undo = {} local diffAngle = part.centreAngle - ang part.centreAngle = ang for i, child in ipairs(part:GetChildren()) do if child.GetAngles and child.GetPosition then if not groupOriginalValues then groupOriginalValues = {} for i, child in ipairs(part:GetChildren()) do if child.GetAngles and child.GetPosition then groupOriginalValues[i] = {Vector(child:GetPosition()), Angle(child:GetAngles())} end end end -- too complex, putting comments -- getting part's bone position to use as one point of local coordinate system local bpos, bang = child:GetBonePosition() -- getting our groun calculated position local gpos, gang = mctrl.GetTargetPos() -- translating GROUP position to be relative to BONE's position local lbpos, lbang = WorldToLocal(gpos, gang, bpos, bang) -- now we have diff vector and angles between group position and part's bone position -- let's get relative position of our part to group local pos, ang = Vector(child:GetPosition()), Angle(child:GetAngles()) local lpos, lang = WorldToLocal(pos, ang, lbpos, lbang) -- we finally got our position and angles! now rotate lpos:Rotate(-diffAngle) lang = lang + diffAngle -- rotated, restore local positions to be relative to GROUP's LOCAL position (stack up) local fpos, fang = LocalToWorld(lpos, lang, lbpos, lbang) table.insert(undo, { child, Angle(groupOriginalValues[i][2]), Vector(groupOriginalValues[i][1]), Angle(fang), Vector(fpos), }) pace.Call("VariableChanged", child, "Angles", fang, false) pace.Call("VariableChanged", child, "Position", fpos, false) end end if #undo ~= 0 then timer.Create('pac3_apply_undo_func', 0.25, 1, function() groupOriginalValues = nil pace.AddUndo(nil, function() for i, data in ipairs(undo) do pace.Call("VariableChanged", data[1], "Angles", data[2], false) pace.Call("VariableChanged", data[1], "Position", data[3], false) end end, function() for i, data in ipairs(undo) do pace.Call("VariableChanged", data[1], "Angles", data[4], false) pace.Call("VariableChanged", data[1], "Position", data[5], false) end end) end) end end end end -- -- Math functions -- local function dot(x1, y1, x2, y2) return (x1 * x2 + y1 * y2) end local function line_plane_intersection(p, n, lp, ln) local d = p:Dot(n) local t = d - lp:Dot(n) / ln:Dot(n) if t < 0 then return end return lp + ln * t end -- Mctrl functions function mctrl.LinePlaneIntersection(pos, normal, x, y) return line_plane_intersection( Vector(0, 0, 0), normal, mctrl.GetCameraOrigin() - pos, mctrl.ScreenToVec(x, y) ) end function mctrl.PointToAxis(pos, axis, x, y) local origin = mctrl.VecToScreen(pos) local point = mctrl.VecToScreen(pos + axis * 10) local a = math.atan2(point.y - origin.y, point.x - origin.x) local d = dot(math.cos(a), math.sin(a), point.x - x, point.y - y) return point.x + math.cos(a) * -d, point.y + math.sin(a) * -d end function mctrl.CalculateMovement(axis, x, y, offset) local target = mctrl.GetTarget() if target:IsValid() then local pos, ang = mctrl.GetTargetPos() if pos and ang then local forward, right, up = mctrl.GetAxes(ang) if axis == AXIS_X then local x, y = mctrl.PointToAxis(pos, forward, x, y) local localpos = mctrl.LinePlaneIntersection(pos, right, x, y) return localpos and (mctrl.GetTargetPosition(pos + localpos:Dot(forward)*forward - forward*offset, ang)) elseif axis == AXIS_Y then local x, y = mctrl.PointToAxis(pos, right, x, y) local localpos = mctrl.LinePlaneIntersection(pos, forward, x, y) return localpos and (mctrl.GetTargetPosition(pos + localpos:Dot(right)*right - right*offset, ang)) elseif axis == AXIS_Z then local x, y = mctrl.PointToAxis(pos, up, x, y) local localpos = mctrl.LinePlaneIntersection(pos, forward, x, y) or mctrl.LinePlaneIntersection(pos, right, x, y) return localpos and (mctrl.GetTargetPosition(pos + localpos:Dot(up)*up - up*offset, ang)) elseif axis == AXIS_VIEW then local camnormal = mctrl.GetCameraAngles():Forward() local localpos = mctrl.LinePlaneIntersection(pos, camnormal, x, y) return localpos and (mctrl.GetTargetPosition(pos + localpos, ang)) end end end end function mctrl.CalculateScale(axis, x, y, offset) local target = mctrl.GetTarget() if target:IsValid() then local pos, ang = mctrl.GetTargetPos() if pos and ang then local forward, right, up = mctrl.GetAxes(ang) offset = -offset + offset + (mctrl.scale_pos * mctrl.GetCalculatedScale()) if axis == AXIS_X then local x, y = mctrl.PointToAxis(pos, forward, x, y) local localpos = mctrl.LinePlaneIntersection(pos, right, x, y) return localpos and (mctrl.GetTargetPosition(pos + localpos:Dot(forward)*forward - forward*offset, ang)), AXIS_X elseif axis == AXIS_Y then local x, y = mctrl.PointToAxis(pos, right, x, y) local localpos = mctrl.LinePlaneIntersection(pos, forward, x, y) return localpos and (mctrl.GetTargetPosition(pos + localpos:Dot(right)*right - right*offset, ang)), AXIS_Y elseif axis == AXIS_Z then local x, y = mctrl.PointToAxis(pos, up, x, y) local localpos = mctrl.LinePlaneIntersection(pos, forward, x, y) or mctrl.LinePlaneIntersection(pos, right, x, y) return localpos and (mctrl.GetTargetPosition(pos + localpos:Dot(up)*up - up*offset, ang)), AXIS_Z end end end end function mctrl.CalculateRotation(axis, x, y) local target = mctrl.GetTarget() if target:IsValid() then local pos, ang = mctrl.GetTargetPos() if pos and ang then local forward, right, up = mctrl.GetAxes(ang) if axis == AXIS_X then local localpos = mctrl.LinePlaneIntersection(pos, right, x, y) if localpos then local diffang = (pos - (localpos + pos)):Angle() diffang:RotateAroundAxis(right, 180) local _, localang = WorldToLocal(vector_origin, diffang, vector_origin, ang) local _, newang = LocalToWorld(vector_origin, Angle(math.NormalizeAngle(localang.p + localang.y), 0, 0), vector_origin, ang) return select(2, mctrl.GetTargetPosition(vector_origin, newang)) end elseif axis == AXIS_Y then local localpos = mctrl.LinePlaneIntersection(pos, up, x, y) if localpos then local diffang = (pos - (localpos + pos)):Angle() diffang:RotateAroundAxis(up, 90) local _, localang = WorldToLocal(vector_origin, diffang, vector_origin, ang) local _, newang = LocalToWorld(vector_origin, Angle(0, math.NormalizeAngle(localang.p + localang.y), 0), vector_origin, ang) return select(2, mctrl.GetTargetPosition(vector_origin, newang)) end elseif axis == AXIS_Z then local localpos = mctrl.LinePlaneIntersection(pos, forward, x, y) if localpos then local diffang = (pos - (localpos + pos)):Angle() diffang:RotateAroundAxis(forward, -90) local _, localang = WorldToLocal(vector_origin, diffang, vector_origin, ang) local _, newang = LocalToWorld(vector_origin, Angle(0, 0, math.NormalizeAngle(localang.p)), vector_origin, ang) return select(2, mctrl.GetTargetPosition(vector_origin, newang)) end end end end end function mctrl.Move(axis, x, y, offset) local target = mctrl.GetTarget() if target:IsValid() then local pos = mctrl.CalculateMovement(axis, x, y, offset) if pos then mctrl.OnMove(target, pos) end end end function mctrl.Scale(axis, x, y, offset) local target = mctrl.GetTarget() if target:IsValid() then local scale, axis = mctrl.CalculateScale(axis, x, y, offset) if scale then mctrl.OnScale(target, scale, axis) end end end function mctrl.Rotate(axis, x, y) local target = mctrl.GetTarget() if target:IsValid() then local ang = mctrl.CalculateRotation(axis, x, y) if ang then mctrl.OnRotate(target, ang) end end end mctrl.grab = {mode = nil, axis = nil} local GRAB_AND_CLONE = CreateClientConVar('pac_grab_clone', '1', true, false, 'Holding shift when moving or rotating a part creates its clone') function mctrl.GUIMousePressed(mc) if mc ~= MOUSE_LEFT then return end local target = mctrl.GetTarget() if not target:IsValid() then return end local x, y = mctrl.GetMousePos() local pos, ang = mctrl.GetTargetPos() if not pos or not ang then return end local forward, right, up = mctrl.GetAxes(ang) local r = mctrl.GetCalculatedScale() -- Movement local axis local dist = mctrl.grab_dist for i, v in pairs { [AXIS_X] = mctrl.VecToScreen(pos + forward * r), [AXIS_Y] = mctrl.VecToScreen(pos + right * r), [AXIS_Z] = mctrl.VecToScreen(pos + up * r), [AXIS_VIEW] = mctrl.VecToScreen(pos) } do local d = math.sqrt((v.x - x)^2 + (v.y - y)^2) if d <= dist then axis = i dist = d end end if axis then mctrl.grab.mode = MODE_MOVE mctrl.grab.axis = axis if GRAB_AND_CLONE:GetBool() and input.IsShiftDown() then local copy = target:Clone() copy:SetParent(copy:GetParent()) pace.AddUndoPartCreation(copy) end return true end --[[ Scale local axis local dist = mctrl.grab_dist for i, v in pairs { [AXIS_X] = mctrl.VecToScreen(pos + forward * r * mctrl.scale_pos), [AXIS_Y] = mctrl.VecToScreen(pos + right * r * mctrl.scale_pos), [AXIS_Z] = mctrl.VecToScreen(pos + up * r * mctrl.scale_pos) } do local d = math.sqrt((v.x - x)^2 + (v.y - y)^2) if d <= dist then axis = i dist = d end end if axis then mctrl.grab.mode = MODE_SCALE mctrl.grab.axis = axis return true end]] -- Rotation local axis local dist = mctrl.grab_dist for i, v in pairs { [AXIS_X] = mctrl.VecToScreen(pos + forward * r * mctrl.angle_pos), [AXIS_Y] = mctrl.VecToScreen(pos + right * r * mctrl.angle_pos), [AXIS_Z] = mctrl.VecToScreen(pos + up * r * mctrl.angle_pos) } do local d = math.sqrt((v.x - x)^2 + (v.y - y)^2) if d <= dist then axis = i dist = d end end if axis then mctrl.grab.mode = MODE_ROTATE mctrl.grab.axis = axis if GRAB_AND_CLONE:GetBool() and input.IsShiftDown() then local copy = target:Clone() copy:SetParent(copy:GetParent()) pace.AddUndoPartCreation(copy) end return true end end function mctrl.GUIMouseReleased(mc) if mc == MOUSE_LEFT then mctrl.grab.mode = nil mctrl.grab.axis = nil end end local white = surface.GetTextureID("gui/center_gradient.vtf") local function DrawLineEx(x1,y1, x2,y2, w, skip_tex) w = w or 1 if not skip_tex then surface.SetTexture(white) end local dx,dy = x1-x2, y1-y2 local ang = math.atan2(dx, dy) local dst = math.sqrt((dx * dx) + (dy * dy)) x1 = x1 - dx * 0.5 y1 = y1 - dy * 0.5 surface.DrawTexturedRectRotated(x1, y1, w, dst, math.deg(ang)) end local function DrawLine(x,y, a,b) DrawLineEx(x,y, a,b, 3) end local function DrawOutlinedRect(x,y, w,h) surface.DrawOutlinedRect(x,y, w,h) surface.DrawOutlinedRect(x+1,y+1, w-2,h-2) end local function DrawCircleEx(x, y, rad, res, ...) res = res or 16 local spacing = (res/rad) - 0.1 for i = 0, res do local i1 = ((i+0) / res) * math.pi * 2 local i2 = ((i+1 + spacing) / res) * math.pi * 2 DrawLineEx( x + math.sin(i1) * rad, y + math.cos(i1) * rad, x + math.sin(i2) * rad, y + math.cos(i2) * rad, ... ) end end function mctrl.LineToBox(origin, point, siz) siz = siz or 7 DrawLine(origin.x, origin.y, point.x, point.y) DrawCircleEx(point.x, point.y, siz, 32, 2) end function mctrl.RotationLines(pos, dir, dir2, r) local pr = mctrl.VecToScreen(pos + dir * r * mctrl.angle_pos) local pra = mctrl.VecToScreen(pos + dir * r * (mctrl.angle_pos * 0.9) + dir2*r*0.08) local prb = mctrl.VecToScreen(pos + dir * r * (mctrl.angle_pos * 0.9) + dir2*r*-0.08) DrawLine(pr.x, pr.y, pra.x, pra.y) DrawLine(pr.x, pr.y, prb.x, prb.y) end function mctrl.HUDPaint() mctrl.LastThinkCall = FrameNumber() if pace.IsSelecting then return end local target = mctrl.GetTarget() if not target then return end local pos, ang = mctrl.GetTargetPos() if not pos or not ang then return end local forward, right, up = mctrl.GetAxes(ang) local radius = mctrl.GetCalculatedScale() local origin = mctrl.VecToScreen(pos) local forward_point = mctrl.VecToScreen(pos + forward * radius) local right_point = mctrl.VecToScreen(pos + right * radius) local up_point = mctrl.VecToScreen(pos + up * radius) if origin.visible or forward_point.visible or right_point.visible or up_point.visible then if mctrl.grab.axis == AXIS_X or mctrl.grab.axis == AXIS_VIEW then surface.SetDrawColor(255, 200, 0, 255) else surface.SetDrawColor(255, 80, 80, 255) end mctrl.LineToBox(origin, forward_point) --mctrl.LineToBox(o, mctrl.VecToScreen(pos + forward * r * mctrl.scale_pos), 8) mctrl.RotationLines(pos, forward, up, radius) if mctrl.grab.axis == AXIS_Y or mctrl.grab.axis == AXIS_VIEW then surface.SetDrawColor(255, 200, 0, 255) else surface.SetDrawColor(80, 255, 80, 255) end mctrl.LineToBox(origin, right_point) --mctrl.LineToBox(o, mctrl.VecToScreen(pos + right * r * mctrl.scale_pos), 8) mctrl.RotationLines(pos, right, forward, radius) if mctrl.grab.axis == AXIS_Z or mctrl.grab.axis == AXIS_VIEW then surface.SetDrawColor(255, 200, 0, 255) else surface.SetDrawColor(80, 80, 255, 255) end mctrl.LineToBox(origin, up_point) --mctrl.LineToBox(o, mctrl.VecToScreen(pos + up * r * mctrl.scale_pos), 8) mctrl.RotationLines(pos, up, right, radius) surface.SetDrawColor(255, 200, 0, 255) DrawCircleEx(origin.x, origin.y, 4, 32, 2) end end function mctrl.Think() if pace.IsSelecting then return end if not mctrl.target:IsValid() then return end local x, y = mctrl.GetMousePos() if mctrl.grab.axis and mctrl.grab.mode == MODE_MOVE then mctrl.Move(mctrl.grab.axis, x, y, mctrl.GetCalculatedScale()) elseif mctrl.grab.axis and mctrl.grab.mode == MODE_SCALE then mctrl.Scale(mctrl.grab.axis, x, y, mctrl.GetCalculatedScale()) elseif mctrl.grab.axis and mctrl.grab.mode == MODE_ROTATE then mctrl.Rotate(mctrl.grab.axis, x, y) end end pac.AddHook("Think", "pace_mctrl_Think", mctrl.Think) pace.mctrl = mctrl
28.074074
143
0.685772
a9897519d4b5f92ae58bb925e01c52d2e1e6e2d8
4,971
swift
Swift
Travelly/Modules/Feed/RestaurantsFeed/RestaurantsTableViewCell.swift
SmartDuck9000/travelly-ios
0d8a46cec1d874b9e83a2985a8e27cbf939652ba
[ "MIT" ]
null
null
null
Travelly/Modules/Feed/RestaurantsFeed/RestaurantsTableViewCell.swift
SmartDuck9000/travelly-ios
0d8a46cec1d874b9e83a2985a8e27cbf939652ba
[ "MIT" ]
3
2021-02-13T22:41:14.000Z
2021-04-14T22:49:10.000Z
Travelly/Modules/Feed/RestaurantsFeed/RestaurantsTableViewCell.swift
SmartDuck9000/travelly-ios
0d8a46cec1d874b9e83a2985a8e27cbf939652ba
[ "MIT" ]
null
null
null
// // RestaurantsTableViewCell.swift // Travelly // // Created by Георгий Куликов on 16.04.2021. // import UIKit fileprivate struct LayoutConstants { static let containerViewHeight: CGFloat = 100 static let containerViewTopSpace: CGFloat = 5 static let containerViewBottomSpace: CGFloat = -10 static let containerViewLeftSpace: CGFloat = 15 static let containerViewRightSpace: CGFloat = -15 static let topSpace: CGFloat = 10 static let bottomSpace: CGFloat = -10 static let leftSpace: CGFloat = 10 static let rightSpace: CGFloat = -10 static let betweenTopSpace: CGFloat = 10 static let betweenLeftSpace: CGFloat = 0 static let betweenRightSpace: CGFloat = 0 static let starsWidth: CGFloat = 15 static let ratingWidth: CGFloat = 15 static let ratingText = "Рейтинг: " static let starImageName = "Star" static let starImageSize: CGFloat = 24 } class RestaurantsTableViewCell: UITableViewCell { private let containerView = UIView() private let restaurantNameLabel = UILabel() private let ratingLabel = UILabel() private let countryCityNameLabel = UILabel() override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setRestaurantName(_ hotelName: String) { self.restaurantNameLabel.text = hotelName } func setRating(_ rating: Double) { self.ratingLabel.text = LayoutConstants.ratingText + "\(rating)" } func setCountryCityName(_ countryName: String, cityName: String) { self.countryCityNameLabel.text = countryName + ", " + cityName } func setupCell() { containerView.frame = CGRect(x: LayoutConstants.containerViewLeftSpace, y: LayoutConstants.containerViewTopSpace, width: self.frame.width - LayoutConstants.containerViewLeftSpace * 2, height: LayoutConstants.containerViewHeight) containerView.backgroundColor = FeedCellAppearance.backgroungColor containerView.layer.cornerRadius = self.frame.width / 40 self.addSubview(containerView) setupRestaurantNameLabel() setupCountryCityNameLabel() setupRatingLabel() } private func setupRestaurantNameLabel() { containerView.addSubview(restaurantNameLabel) restaurantNameLabel.textColor = FeedCellAppearance.textColor restaurantNameLabel.font = FeedCellAppearance.boldFont restaurantNameLabel.translatesAutoresizingMaskIntoConstraints = false restaurantNameLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: LayoutConstants.topSpace).isActive = true restaurantNameLabel.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: LayoutConstants.leftSpace).isActive = true restaurantNameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor, constant: LayoutConstants.betweenRightSpace).isActive = true } private func setupCountryCityNameLabel() { containerView.addSubview(countryCityNameLabel) countryCityNameLabel.textColor = FeedCellAppearance.textColor countryCityNameLabel.font = FeedCellAppearance.font countryCityNameLabel.translatesAutoresizingMaskIntoConstraints = false countryCityNameLabel.topAnchor.constraint(equalTo: restaurantNameLabel.bottomAnchor, constant: LayoutConstants.betweenTopSpace).isActive = true countryCityNameLabel.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: LayoutConstants.leftSpace).isActive = true countryCityNameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor, constant: LayoutConstants.rightSpace).isActive = true } private func setupRatingLabel() { containerView.addSubview(ratingLabel) ratingLabel.textColor = FeedCellAppearance.textColor ratingLabel.font = FeedCellAppearance.font ratingLabel.translatesAutoresizingMaskIntoConstraints = false ratingLabel.topAnchor.constraint(equalTo: countryCityNameLabel.bottomAnchor, constant: LayoutConstants.betweenTopSpace).isActive = true ratingLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: LayoutConstants.bottomSpace).isActive = true ratingLabel.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: LayoutConstants.leftSpace).isActive = true ratingLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor, constant: LayoutConstants.rightSpace).isActive = true } }
41.773109
147
0.704084
411b09fd08d5ddafdebfddb3f2ff209d0061c158
7,546
swift
Swift
ChannelIO/Source/Models/CHUserChat.swift
konifar/channel-plugin-ios
fa459a7b0c9f1c0fbdfd391bbb44be9be79edf7b
[ "MIT" ]
12
2017-11-03T09:16:46.000Z
2020-11-17T03:43:15.000Z
ChannelIO/Source/Models/CHUserChat.swift
konifar/channel-plugin-ios
fa459a7b0c9f1c0fbdfd391bbb44be9be79edf7b
[ "MIT" ]
93
2018-05-31T09:36:25.000Z
2020-09-26T09:52:13.000Z
ChannelIO/Source/Models/CHUserChat.swift
konifar/channel-plugin-ios
fa459a7b0c9f1c0fbdfd391bbb44be9be79edf7b
[ "MIT" ]
11
2017-04-01T05:17:23.000Z
2021-12-14T01:50:44.000Z
// // UserChat.swift // CHPlugin // // Created by 이수완 on 2017. 1. 14.. // Copyright © 2017년 ZOYI. All rights reserved. // import Foundation import ObjectMapper import RxSwift enum ReviewType: String { case like case dislike } enum UserChatState: String { case unassigned case assigned case holding case solved case closed case trash } enum ChatType: String { case userChat = "userChat" init?(_ type: String?) { guard let type = type else { return nil } switch type { case "UserChat": self = .userChat default: return nil } } } enum PersonType: String { case manager = "manager" case user = "user" case bot = "bot" init?(_ type: String?) { guard let type = type else { return nil } switch type { case "Manager": self = .manager case "User": self = .user case "Bot": self = .bot default: return nil } } } enum ChatHandlingStatus: String { case support } struct CHUserChat: ModelType { // ModelType var id = "" // UserChat var userId: String = "" var channelId: String = "" var name: String = "" var state: UserChatState? var review: String = "" var createdAt: Date? var openedAt: Date? var updatedAt: Date? var followedAt: Date? var resolvedAt: Date? var closedAt: Date? var assigneeId: String? = nil var managerIds: [String] = [] var handling: ChatHandlingStatus? var frontMessageId: String? var resolutionTime: Int = 0 var askedAt: Date? var firstOpenedAt: Date? // Dependencies var lastMessage: CHMessage? var session: CHSession? var channel: CHChannel? var hasRemoved: Bool = false var assignee: CHEntity? { return personSelector( state: mainStore.state, personType: .manager, personId: self.assigneeId ) } var readableUpdatedAt: String { if let updatedAt = self.lastMessage?.createdAt { return updatedAt.readableTimeStamp() } return "" } } extension CHUserChat: Mappable { init?(map: Map) {} init(chatId: String, lastMessageId: String) { self.id = chatId self.state = nil self.frontMessageId = lastMessageId self.createdAt = Date() self.updatedAt = Date() } mutating func mapping(map: Map) { id <- map["id"] userId <- map["userId"] name <- map["name"] channelId <- map["channelId"] managerIds <- map["managerIds"] review <- map["review"] createdAt <- (map["createdAt"], CustomDateTransform()) openedAt <- (map["openedAt"], CustomDateTransform()) followedAt <- (map["followedAt"], CustomDateTransform()) resolvedAt <- (map["resolvedAt"], CustomDateTransform()) closedAt <- (map["closedAt"], CustomDateTransform()) updatedAt <- (map["frontUpdatedAt"], CustomDateTransform()) askedAt <- (map["askedAt"], CustomDateTransform()) firstOpenedAt <- (map["firstOpenedAt"], CustomDateTransform()) handling <- map["handling"] frontMessageId <- map["frontMessageId"] assigneeId <- map["assigneeId"] resolutionTime <- map["resolutionTime"] state <- map["state"] self.updatedAt = self.updatedAt ?? self.createdAt } } //TODO: Refactor to AsyncActionCreator extension CHUserChat { static func get(userChatId: String) -> Observable<ChatResponse> { return UserChatPromise.getChat(userChatId: userChatId) } static func getChats( since: String? = nil, limit: Int, showCompleted: Bool = false) -> Observable<UserChatsResponse> { return UserChatPromise.getChats( since: since, limit: limit, showCompleted: showCompleted ) } static func getMessages( userChatId: String, since: String?, limit: Int, sortOrder:String) -> Observable<[String: Any]> { return UserChatPromise.getMessages( userChatId: userChatId, since: since, limit: limit, sortOrder: sortOrder) } static func create() -> Observable<ChatResponse>{ return UserChatPromise.createChat( pluginId: mainStore.state.plugin.id, url: ChannelIO.hostTopControllerName ?? "" ) } func remove() -> Observable<Any?> { return UserChatPromise.remove(userChatId: self.id) } func close(actionId: String, requestId: String = "") -> Observable<CHUserChat> { return UserChatPromise.close( userChatId: self.id, actionId: actionId, requestId: requestId ) } func review( actionId: String, rating: ReviewType, requestId: String) -> Observable<CHUserChat> { return UserChatPromise.review( userChatId: self.id, actionId: actionId, rating: rating, requestId: requestId ) } func shouldRequestRead(otherChat: CHUserChat?) -> Bool { guard let otherChat = otherChat else { return false } return (self.updatedAt?.miliseconds != otherChat.updatedAt?.miliseconds) || (self.session?.alert != otherChat.session?.alert) } func read() { guard self.session != nil else { return } _ = UserChatPromise.setMessageRead(userChatId: self.id) .subscribe(onNext: { (_) in mainStore.dispatch(ReadSession(payload: self.session)) }, onError: { (error) in }) } func read() -> Observable<Bool> { return Observable.create({ (subscriber) in let signal = UserChatPromise.setMessageRead(userChatId: self.id) let dispose = signal.subscribe(onNext: { (_) in mainStore.dispatch(ReadSession(payload: self.session)) subscriber.onNext(true) subscriber.onCompleted() }, onError: { (error) in subscriber.onNext(false) subscriber.onCompleted() }) return Disposables.create { dispose.dispose() } }) } } extension CHUserChat { var isActive: Bool { return self.state != .closed && self.state != .solved && self.state != .trash } var isClosed: Bool { return self.state == .closed } var isRemoved: Bool { return self.state == .trash } var isSolved: Bool { return self.state == .solved } var isCompleted: Bool { return self.state == .closed || self.state == .solved || self.state == .trash } var isReadyOrOpen: Bool { return self.state == nil || self.state == .unassigned } var isUnassigned: Bool { return self.state == .unassigned } var isReady: Bool { return self.state == nil && self.handling == nil } var isEngaged: Bool { return self.state == .solved || self.state == .closed || self.state == .assigned } var isSupporting: Bool { return self.state == nil && self.handling == .support } static func becomeActive(current: CHUserChat?, next: CHUserChat?) -> Bool { guard let current = current, let next = next else { return false } return current.isReadyOrOpen && !next.isReadyOrOpen } static func becomeOpen(current: CHUserChat?, next: CHUserChat?) -> Bool { guard let current = current, let next = next else { return false } return current.isSolved && next.isReadyOrOpen } } extension CHUserChat: Equatable { static func ==(lhs: CHUserChat, rhs: CHUserChat) -> Bool { return lhs.id == rhs.id && lhs.session?.alert == rhs.session?.alert && lhs.state == rhs.state && lhs.lastMessage == rhs.lastMessage && lhs.assigneeId == rhs.assigneeId && lhs.resolutionTime == rhs.resolutionTime } }
25.069767
84
0.626955
3fc5bfd43fa3a6a1c333208062593defd7698fc0
1,751
c
C
package/pikaRTDevice/pikaRTDevice_GPIO.c
ccccmagicboy2022/pikascript
154ccd8e90e0d50e1551536d32bd2a3648e194d2
[ "MIT" ]
228
2021-09-11T06:09:43.000Z
2022-03-30T08:09:01.000Z
package/pikaRTDevice/pikaRTDevice_GPIO.c
ccccmagicboy2022/pikascript
154ccd8e90e0d50e1551536d32bd2a3648e194d2
[ "MIT" ]
48
2021-09-25T01:23:43.000Z
2022-03-31T07:34:43.000Z
package/pikaRTDevice/pikaRTDevice_GPIO.c
ccccmagicboy2022/pikascript
154ccd8e90e0d50e1551536d32bd2a3648e194d2
[ "MIT" ]
31
2021-09-17T12:06:45.000Z
2022-03-19T16:10:11.000Z
#include "pikaRTDevice_GPIO.h" #include <rtthread.h> #include <rtdevice.h> rt_base_t pika_get_rt_mode_num(char *mode, char* pull); void pikaRTDevice_GPIO_platformEnable(PikaObj *self){ char* pin = obj_getStr(self, "pin"); char* mode = obj_getStr(self, "mode"); char* pull = obj_getStr(self, "pull"); rt_base_t pin_num = rt_pin_get(pin); if(pin_num < 0){ obj_setSysOut(self, "[error]: gpio hardware fault, can not get pin number."); obj_setErrorCode(self, 1); } rt_base_t mode_num = pika_get_rt_mode_num(mode, pull); rt_pin_mode(pin_num, mode_num); } rt_base_t pika_get_rt_mode_num(char *mode, char* pull){ if(strEqu(mode, "out")){ return PIN_MODE_OUTPUT; } if(strEqu(mode, "in")){ if(strEqu(pull, "none")){ return PIN_MODE_INPUT; } if(strEqu(pull, "up")){ return PIN_MODE_INPUT_PULLUP; } if(strEqu(pull, "down")){ return PIN_MODE_INPUT_PULLDOWN; } } /* default */ return PIN_MODE_OUTPUT; } void pikaRTDevice_GPIO_platformDisable(PikaObj *self){ } void pikaRTDevice_GPIO_platformHigh(PikaObj *self){ char* pin = obj_getStr(self, "pin"); rt_base_t pin_num = rt_pin_get(pin); rt_pin_write(pin_num, PIN_HIGH); } void pikaRTDevice_GPIO_platformLow(PikaObj *self){ char* pin = obj_getStr(self, "pin"); rt_base_t pin_num = rt_pin_get(pin); rt_pin_write(pin_num, PIN_LOW); } void pikaRTDevice_GPIO_platformRead(PikaObj *self){ char* pin = obj_getStr(self, "pin"); rt_base_t pin_num = rt_pin_get(pin); obj_setInt(self, "readBuff", rt_pin_read(pin_num)); } void pikaRTDevice_GPIO_platformSetMode(PikaObj *self){ pikaRTDevice_GPIO_platformEnable(self); }
30.189655
85
0.671616
96a1909c75ce3b7af367690f5d6f3cb78f37e470
6,357
html
HTML
src/write.html
SoftwareEngineeringG4/CSE4006
52daaf48c94a481662a03033d48ceaa9bb3a02fa
[ "MIT" ]
1
2018-12-08T07:45:14.000Z
2018-12-08T07:45:14.000Z
src/write.html
SoftwareEngineeringG4/CSE4006
52daaf48c94a481662a03033d48ceaa9bb3a02fa
[ "MIT" ]
6
2018-11-26T04:09:23.000Z
2018-12-09T14:55:40.000Z
src/write.html
SoftwareEngineeringG4/CSE4006
52daaf48c94a481662a03033d48ceaa9bb3a02fa
[ "MIT" ]
4
2018-11-25T14:09:54.000Z
2018-12-09T01:52:06.000Z
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Write something else you want</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bootstrap.css') }}"> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/navbar.css') }}"> </head> <body> <center> <nav id="topMenu"> <ul> <li class="topMenuLi"> <a class="menuLink" href="{{ url_for('main_page') }}">HOME</a> <ul class="submenu"> {% if session.logged_in %} <li><a href="{{ url_for('check_myinfo') }}" class="submenuLink longLink">내정보확인</a></li> <li><a href="{{ url_for('logout') }}" class="submenuLink longLink">로그아웃</a></li> <li><a href="{{ url_for('check_mypost') }}" class="submenuLink longLink">내글확인</a></li> {% if auth %} <li><a href="{{ url_for('admin_page') }}" class="submenuLink longLink">관리자페이지</a></li> {% endif%} {% else %} <li><a href="{{ url_for('register') }}" class="submenuLink longLink">회원가입</a></li> <li><a href="{{ url_for('login') }}" class="submenuLink longLink">로그인</a></li> <li><a href="{{ url_for('main_page') }}" class="submenuLink longLink">비밀번호찾기</a></li> {% endif %} </ul> </li> <li>|</li> <li class="topMenuLi"> <a class="menuLink" href="#">Search</a> <ul class="submenu"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous"> <div class="container"> <div class="row justify-content-center"> <div class="col-12 col-md-10 col-lg-8"> <form action="/herehere" class="card card-sm" method="post"> <div class="card-body row no-gutters align-items-center"> <div class="col-auto"> <i class="fas fa-search h4 text-body"></i> </div> <!--end of col--> <div class="col"> <input class="form-control form-control-lg form-control-borderless" name ="search" type="search" placeholder="Search topics or keywords"> </div> <!--end of col--> <div class="col-auto"> <button class="btn btn-lg btn-success" type="submit">Search</button> </div> <!--end of col--> </div> </form> </div> <!--end of col--> </div> </div> </ul> </li> {% for listValue in list %} <li>|</li> <li class="topMenuLi"> <a class="menuLink" href="{{ url_for('board_open', board_name=listValue[1]) }}">{{ listValue[1] }}</a> {% endfor %} </ul> </nav> <div class="container"> <table class="table table-striped"> <thead> <center><h1>글쓰기</h1></center> {% for message in get_flashed_messages() %} <br/> <div class="alert alert-info alert-dismissable"> <a herf="#" class="close" data-dismiss="alert" aria-label="close">x</a> {{ message }} </div> {% endfor %} </thead> <tbody> <form action="{{ url_for('write_post') }}" method="POST" encType="multiplart/form-data"> <tr> <th>제목: </th> <td><input type="text" placeholder="제목을 입력하세요. " name="subject" class="form-control"/></td> </tr> <tr> <th>내용: </th> <td><textarea cols="10" rows="20" placeholder="내용을 입력하세요. " name="content" class="form-control"></textarea></td> </tr> <tr> <td colspan="2"> <button class="btn btn-primary float-left pull-right" type="submit">Post</button> <!-- <a class="btn btn-default" onclick="sendData()"> 등록 </a> <a class="btn btn-default" type="reset"> reset </a> <a class="btn btn-default" onclick="javascript:location.href='list.jsp'">글 목록으로...</a> --> </td> </tr> </form> </tbody> </table> </div> </center> </body> </html>
51.682927
218
0.487337
7c369e549bc00775e3bf49b257449b383e63aa12
1,380
rs
Rust
fancy-test-runner/build.rs
auxoncorp/ferros-fancy-test
4b07601e375c06916e7e9ee080fbb35402e7c879
[ "Apache-2.0" ]
null
null
null
fancy-test-runner/build.rs
auxoncorp/ferros-fancy-test
4b07601e375c06916e7e9ee080fbb35402e7c879
[ "Apache-2.0" ]
null
null
null
fancy-test-runner/build.rs
auxoncorp/ferros-fancy-test
4b07601e375c06916e7e9ee080fbb35402e7c879
[ "Apache-2.0" ]
null
null
null
#[cfg(not(workaround_build))] fn main() { cargo_5730::run_build_script(); } #[cfg(workaround_build)] fn main() { use ferros_build::*; use regex::Regex; use std::fs::{self, DirEntry}; use std::path::Path; use std::vec::Vec; let out_dir = Path::new(&std::env::var_os("OUT_DIR").unwrap()).to_owned(); let resources_rs = out_dir.join("resources.rs"); let bin_dir = out_dir.join("..").join("..").join(".."); let mut rs = vec!(); // test executable names end in "-<16 hex digits>" let test_filename_regex = Regex::new(".*\\-[0-9a-f]{16}$").unwrap(); println!("cargo:rerun-if-changed={}", bin_dir.display()); for entry in fs::read_dir(bin_dir).unwrap() { let entry = entry.unwrap(); let path = entry.path(); let file_name = path.file_name().unwrap().to_str().unwrap(); if entry.file_type().unwrap().is_file() && test_filename_regex.is_match(file_name) { rs.push(DataResource { path: path.to_owned(), image_name: file_name.to_owned(), }); println!("cargo:rerun-if-changed={}", path.display()); } } let mut resources : Vec<&dyn Resource> = vec![]; for r in rs.iter() { resources.push(r as &dyn Resource); } embed_resources( &resources_rs, resources, ); }
27.6
92
0.563768
2dcfd15accc517ca7757fb43ee024c706b78f99c
15,443
rs
Rust
carbide_core/src/text/markup/polar_bear_markup.rs
HolgerGottChriestensen/conrod
48b80a0c8915b2d478a445f1e5a8e0f396598652
[ "Apache-2.0", "MIT" ]
null
null
null
carbide_core/src/text/markup/polar_bear_markup.rs
HolgerGottChriestensen/conrod
48b80a0c8915b2d478a445f1e5a8e0f396598652
[ "Apache-2.0", "MIT" ]
null
null
null
carbide_core/src/text/markup/polar_bear_markup.rs
HolgerGottChriestensen/conrod
48b80a0c8915b2d478a445f1e5a8e0f396598652
[ "Apache-2.0", "MIT" ]
null
null
null
use nom::branch::alt; use nom::bytes::complete::{is_not, tag, take}; use nom::combinator::{map, not}; use nom::IResult; use nom::multi::{many0, many1}; use nom::sequence::{delimited, preceded, tuple}; use crate::prelude::Environment; use crate::text::{FontStyle, FontWeight, TextSpanGenerator}; use crate::text::text_decoration::TextDecoration; use crate::text::text_span::TextSpan; use crate::text::text_style::TextStyle; #[derive(PartialEq, Debug, Clone)] pub enum PolarItem { Header1(String), Header2(String), Header3(String), Header4(String), Header5(String), Header6(String), Italic(String), Bold(String), Underline(String), Strike(String), //LineSeparator, Newline, Paragraph(String), } pub fn parse_polar_bear_markup(input: &str) -> IResult<&str, Vec<PolarItem>> { let (left, parsed) = many0(alt(( parse_header_1, parse_header_2, parse_header_3, parse_header_4, parse_header_5, parse_header_6, parse_underline, parse_strike_through, parse_italic, parse_bold, parse_paragraph, parse_newline, )))(input)?; Ok((left, parsed)) } #[test] fn parse_polar_bear_markup_test() { assert_eq!( parse_polar_bear_markup("Hejsa1"), Ok(("", vec![PolarItem::Paragraph("Hejsa1".to_string())])) ); assert_eq!( parse_polar_bear_markup("/Hejsa2/"), Ok(("", vec![PolarItem::Italic("Hejsa2".to_string())])) ); assert_eq!( parse_polar_bear_markup("/Hejsa3/ verden!"), Ok(( "", vec![ PolarItem::Italic("Hejsa3".to_string()), PolarItem::Paragraph(" verden!".to_string()), ] )) ); assert_eq!( parse_polar_bear_markup("Hejsa4 /verden!/"), Ok(( "", vec![ PolarItem::Paragraph("Hejsa4 ".to_string()), PolarItem::Italic("verden!".to_string()), ] )) ); assert_eq!( parse_polar_bear_markup("/Hejsa5 / verden!"), Ok(( "", vec![PolarItem::Paragraph("/Hejsa5 / verden!".to_string())] )) ); } fn parse_header_1(input: &str) -> IResult<&str, PolarItem> { let (left, (_, _, parsed, _)): (&str, (_, _, &str, _)) = tuple((tag("#"), tag(" "), is_not("\n"), tag("\n")))(input)?; Ok((left, PolarItem::Header1(parsed.to_string()))) } fn parse_header_2(input: &str) -> IResult<&str, PolarItem> { let (left, (_, _, parsed, _)): (&str, (_, _, &str, _)) = tuple((tag("##"), tag(" "), is_not("\n"), tag("\n")))(input)?; Ok((left, PolarItem::Header2(parsed.to_string()))) } fn parse_header_3(input: &str) -> IResult<&str, PolarItem> { let (left, (_, _, parsed, _)): (&str, (_, _, &str, _)) = tuple((tag("###"), tag(" "), is_not("\n"), tag("\n")))(input)?; Ok((left, PolarItem::Header3(parsed.to_string()))) } fn parse_header_4(input: &str) -> IResult<&str, PolarItem> { let (left, (_, _, parsed, _)): (&str, (_, _, &str, _)) = tuple((tag("####"), tag(" "), is_not("\n"), tag("\n")))(input)?; Ok((left, PolarItem::Header4(parsed.to_string()))) } fn parse_header_5(input: &str) -> IResult<&str, PolarItem> { let (left, (_, _, parsed, _)): (&str, (_, _, &str, _)) = tuple((tag("#####"), tag(" "), is_not("\n"), tag("\n")))(input)?; Ok((left, PolarItem::Header5(parsed.to_string()))) } fn parse_header_6(input: &str) -> IResult<&str, PolarItem> { let (left, (_, _, parsed, _)): (&str, (_, _, &str, _)) = tuple((tag("######"), tag(" "), is_not("\n"), tag("\n")))(input)?; Ok((left, PolarItem::Header6(parsed.to_string()))) } fn parse_newline(input: &str) -> IResult<&str, PolarItem> { let (left, _parsed): (&str, &str) = tag("\n")(input)?; Ok((left, PolarItem::Newline)) } fn parse_underline(input: &str) -> IResult<&str, PolarItem> { let (left, parsed): (&str, String) = delimited(tag("_"), parse_text, tag("_"))(input)?; let italic = PolarItem::Underline(parsed); Ok((left, italic)) } fn parse_strike_through(input: &str) -> IResult<&str, PolarItem> { let (left, parsed): (&str, String) = delimited(tag("-"), parse_text, tag("-"))(input)?; let italic = PolarItem::Strike(parsed); Ok((left, italic)) } fn parse_italic(input: &str) -> IResult<&str, PolarItem> { let (left, parsed): (&str, String) = delimited(tag("/"), parse_text, tag("/"))(input)?; let italic = PolarItem::Italic(parsed); Ok((left, italic)) } fn parse_bold(input: &str) -> IResult<&str, PolarItem> { let (left, parsed): (&str, String) = delimited(tag("*"), parse_text, tag("*"))(input)?; let italic = PolarItem::Bold(parsed); Ok((left, italic)) } fn parse_paragraph(input: &str) -> IResult<&str, PolarItem> { let (left, parsed): (&str, String) = parse_text(input)?; let paragraph = PolarItem::Paragraph(parsed); Ok((left, paragraph)) } fn parse_text(input: &str) -> IResult<&str, String> { let (left, parsed): (&str, String) = map( many1(preceded( not(alt((tag("/"), tag("*"), tag("-"), tag("_"), tag("\n")))), take(1u8), )), |vec| vec.join(""), )(input)?; Ok((left, parsed)) } #[derive(Debug, Clone)] pub struct PolarBearMarkup; impl PolarBearMarkup { pub fn new() -> PolarBearMarkup { PolarBearMarkup {} } } impl TextSpanGenerator for PolarBearMarkup { // https://bear.app/faq/Markup%20:%20Markdown/Polar%20Bear%20markup%20language/ fn generate(&self, string: &str, style: &TextStyle, env: &mut Environment) -> Vec<TextSpan> { let default_font_family_name = &style.font_family; let scale_factor = env.get_scale_factor(); let polars = parse_polar_bear_markup(string).unwrap().1; let mut spans = vec![]; for polar in polars { match polar { PolarItem::Header1(text) => { let style = TextStyle { font_family: default_font_family_name.clone(), font_size: 30, font_style: FontStyle::Normal, font_weight: FontWeight::Bold, text_decoration: TextDecoration::None, color: None, }; let font = style.get_font(env); let (widths, glyphs) = font.get_glyphs(&text, style.font_size, scale_factor, env); let ascending_pixels = font.ascend(style.font_size, scale_factor); let line_height = font.descend(style.font_size, scale_factor); let line_gap = font.line_gap(style.font_size, scale_factor); let span = TextSpan::Text { style: Some(style.clone()), text: text.to_string(), glyphs, widths, ascend: ascending_pixels, descend: line_height, line_gap, }; spans.push(span); spans.push(TextSpan::NewLine) } PolarItem::Header2(text) => { let style = TextStyle { font_family: default_font_family_name.clone(), font_size: 20, font_style: FontStyle::Normal, font_weight: FontWeight::Normal, text_decoration: TextDecoration::None, color: None, }; let font = style.get_font(env); let (widths, glyphs) = font.get_glyphs(&text, style.font_size, scale_factor, env); let ascending_pixels = font.ascend(style.font_size, scale_factor); let line_height = font.descend(style.font_size, scale_factor); let line_gap = font.line_gap(style.font_size, scale_factor); let span = TextSpan::Text { style: Some(style.clone()), text: text.to_string(), glyphs, widths, ascend: ascending_pixels, descend: line_height, line_gap, }; spans.push(span); spans.push(TextSpan::NewLine) } PolarItem::Italic(text) => { let style = TextStyle { font_family: default_font_family_name.clone(), font_size: 14, font_style: FontStyle::Italic, font_weight: FontWeight::Normal, text_decoration: TextDecoration::None, color: None, }; let font = style.get_font(env); let (widths, glyphs) = font.get_glyphs(&text, style.font_size, scale_factor, env); let ascending_pixels = font.ascend(style.font_size, scale_factor); let line_height = font.descend(style.font_size, scale_factor); let line_gap = font.line_gap(style.font_size, scale_factor); let span = TextSpan::Text { style: Some(style.clone()), text: text.to_string(), glyphs, widths, ascend: ascending_pixels, descend: line_height, line_gap, }; spans.push(span); } PolarItem::Bold(text) => { let style = TextStyle { font_family: default_font_family_name.clone(), font_size: 14, font_style: FontStyle::Normal, font_weight: FontWeight::Bold, text_decoration: TextDecoration::None, color: None, }; let font = style.get_font(env); let (widths, glyphs) = font.get_glyphs(&text, style.font_size, scale_factor, env); let ascending_pixels = font.ascend(style.font_size, scale_factor); let line_height = font.descend(style.font_size, scale_factor); let line_gap = font.line_gap(style.font_size, scale_factor); let span = TextSpan::Text { style: Some(style.clone()), text: text.to_string(), glyphs, widths, ascend: ascending_pixels, descend: line_height, line_gap, }; spans.push(span); } PolarItem::Paragraph(text) => { let style = TextStyle { font_family: default_font_family_name.clone(), font_size: 14, font_style: FontStyle::Normal, font_weight: FontWeight::Normal, text_decoration: TextDecoration::None, color: None, }; let font = style.get_font(env); let (widths, glyphs) = font.get_glyphs(&text, style.font_size, scale_factor, env); let ascending_pixels = font.ascend(style.font_size, scale_factor); let line_height = font.descend(style.font_size, scale_factor); let line_gap = font.line_gap(style.font_size, scale_factor); let span = TextSpan::Text { style: Some(style.clone()), text: text.to_string(), glyphs, widths, ascend: ascending_pixels, descend: line_height, line_gap, }; spans.push(span); } PolarItem::Underline(text) => { let style = TextStyle { font_family: default_font_family_name.clone(), font_size: 14, font_style: FontStyle::Normal, font_weight: FontWeight::Normal, text_decoration: TextDecoration::Underline(vec![]), color: None, }; let font = style.get_font(env); let (widths, glyphs) = font.get_glyphs(&text, style.font_size, scale_factor, env); let ascending_pixels = font.ascend(style.font_size, scale_factor); let line_height = font.descend(style.font_size, scale_factor); let line_gap = font.line_gap(style.font_size, scale_factor); let span = TextSpan::Text { style: Some(style.clone()), text: text.to_string(), glyphs, widths, ascend: ascending_pixels, descend: line_height, line_gap, }; spans.push(span); } PolarItem::Strike(text) => { let style = TextStyle { font_family: default_font_family_name.clone(), font_size: 14, font_style: FontStyle::Normal, font_weight: FontWeight::Normal, text_decoration: TextDecoration::StrikeThrough(vec![]), color: None, }; let font = style.get_font(env); let (widths, glyphs) = font.get_glyphs(&text, style.font_size, scale_factor, env); let ascending_pixels = font.ascend(style.font_size, scale_factor); let line_height = font.descend(style.font_size, scale_factor); let line_gap = font.line_gap(style.font_size, scale_factor); let span = TextSpan::Text { style: Some(style.clone()), text: text.to_string(), glyphs, widths, ascend: ascending_pixels, descend: line_height, line_gap, }; spans.push(span); } PolarItem::Newline => spans.push(TextSpan::NewLine), _ => (), } } spans } fn store_color(&self) -> bool { true } } impl Into<Box<dyn TextSpanGenerator>> for PolarBearMarkup { fn into(self) -> Box<dyn TextSpanGenerator> { Box::new(self) } }
36.336471
97
0.484232
0bb427571da83fcfcbebc710899df6fa24da6219
260
js
JavaScript
src/widget/utils/index.js
greenglobal/ppsloop
a20344df117439b0a38a2539bf09336db49a88a7
[ "MIT" ]
1
2019-03-19T20:12:59.000Z
2019-03-19T20:12:59.000Z
src/widget/utils/index.js
greenglobal/ppsloop
a20344df117439b0a38a2539bf09336db49a88a7
[ "MIT" ]
null
null
null
src/widget/utils/index.js
greenglobal/ppsloop
a20344df117439b0a38a2539bf09336db49a88a7
[ "MIT" ]
1
2019-12-23T10:05:28.000Z
2019-12-23T10:05:28.000Z
export * from './preloadImages'; export * from './onTransitionEnd'; export * from './getElementPosition'; export * from './getLocatePoint'; export * from './shuffle'; export * from './existsInArray'; export * from './getItemFrom'; export * from './translate';
28.888889
37
0.692308
74b2249147b43e67b13f5133a4a8cfc381745743
4,845
js
JavaScript
web/world.js
BEN1JEN/uniblocks
cca0303f5cd430da9c56d99f50e934f77354841e
[ "0BSD" ]
null
null
null
web/world.js
BEN1JEN/uniblocks
cca0303f5cd430da9c56d99f50e934f77354841e
[ "0BSD" ]
null
null
null
web/world.js
BEN1JEN/uniblocks
cca0303f5cd430da9c56d99f50e934f77354841e
[ "0BSD" ]
null
null
null
"use strict"; function bufToRuid(buf, start) { let ruid = ""; for (let i = 0; i < 16; i++) { ruid += ("0"+buf[start+i].toString(16)).slice(-2); } return ruid; } function ruidToBuf(ruid, buf, start) { for (let i = 0; i < 16; i++) { buf[start+i] = parseInt(ruid.substr(i*2, 2), 16); } } class World { constructor() { this.regions = {}; this.tiles = {}; this.loadedPositionMin = {"x": NaN, "y": NaN}; this.defaultTile = new Tile("00000000000000000000000000000000", "Unknown", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4woIEBISRGtRKQAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAJElEQVQoz2NkwAH+M/zHKs7EQCIY1UAMYMQV3owMjKOhRD8NACTzBB3yj0euAAAAAElFTkSuQmCC", ""); for (let i = -3; i <= 3; i++) { socket.emit("WorldSetTile", i, -3, "65a5fce8876d8e5bad5da510edb9a3f"); socket.emit("WorldSetTile", 3, i, "65a5fce8876d8e5bad5da510edb9a3f"); } socket.emit("WorldSetTile", 0, 0, "65a5fce8876d8e5bad5da510edb9a3f"); } loadTile(ruid, callback) { if (typeof(this.tiles[ruid]) === "undefined") { socket.emit("WorldGetTile", ruid, (success, data)=>{ if (success) { this.tiles[ruid] = new Tile(ruid, data.name, data.graphic, data.code); } else { console.error("Error getting tile #" + ruid); this.tiles[ruid] = this.defaultTile; } if (typeof(callback) === "function") { callback(this.tiles[ruid]); } }); } else if (typeof(callback) === "function") { callback(this.tiles[ruid]); } } fetch(rx, ry) { socket.emit("WorldGetRegion", rx, ry, reg=>{ if(typeof(this.regions[rx]) === "undefined") { this.regions[rx] = {}; } this.regions[rx][ry] = new Uint8Array(reg); console.log("loadedregion: ", rx, "/", ry); let toLoad = {}; for (let i = 0; i < 65536*16; i += 16) { const ruid = bufToRuid(this.regions[rx][ry], i); if (ruid !== "00000000000000000000000000000000" && typeof(this.tiles[ruid]) === "undefined" && typeof(toLoad[ruid]) === "undefined") { toLoad[ruid] = true; console.log("loadtile@", i); } } for (const ruid of Object.keys(toLoad)) { this.loadTile(ruid); } }); } update() { // The four regions that are closest to the player should always be loaded const playerRegionMin = {"x": Math.floor((player.collider.x-128)/256),"y": Math.floor((player.collider.y-128)/256)}; let overlap = {}; // Overlap of regions, from the perspective of the NEW region (false=reload, true=keep) overlap.ll = (playerRegionMin.x === this.loadedPositionMin.x || playerRegionMin.x === this.loadedPositionMin.x+1) && (playerRegionMin.y === this.loadedPositionMin.y || playerRegionMin.y === this.loadedPositionMin.y+1); overlap.lh = (playerRegionMin.x === this.loadedPositionMin.x || playerRegionMin.x === this.loadedPositionMin.x+1) && (playerRegionMin.y+1 === this.loadedPositionMin.y || playerRegionMin.y+1 === this.loadedPositionMin.y+1); overlap.hl = (playerRegionMin.x+1 === this.loadedPositionMin.x || playerRegionMin.x+1 === this.loadedPositionMin.x+1) && (playerRegionMin.y === this.loadedPositionMin.y || playerRegionMin.y === this.loadedPositionMin.y+1); overlap.hh = (playerRegionMin.x+1 === this.loadedPositionMin.x || playerRegionMin.x+1 === this.loadedPositionMin.x+1) && (playerRegionMin.y+1 === this.loadedPositionMin.y || playerRegionMin.y+1 === this.loadedPositionMin.y+1); if (!overlap.ll) { this.fetch(playerRegionMin.x, playerRegionMin.y); } if (!overlap.lh) { this.fetch(playerRegionMin.x, playerRegionMin.y+1); } if (!overlap.hl) { this.fetch(playerRegionMin.x+1, playerRegionMin.y); } if (!overlap.hh) { this.fetch(playerRegionMin.x+1, playerRegionMin.y+1); } this.loadedPositionMin = playerRegionMin; } draw() { let blocksSize = {"x": Math.ceil(vpSize.x/camera.zoom/2), "y": Math.ceil(vpSize.y/camera.zoom/2)}; for (let x = Math.floor(camera.x)-blocksSize.x; x <= Math.floor(camera.x)+blocksSize.x; x++) { for (let y = Math.floor(camera.y)-blocksSize.y; y <= Math.floor(camera.y)+blocksSize.y; y++) { const t = this.getTile(x, y); if (t !== 0 && typeof(this.tiles[t]) !== "undefined") { this.tiles[t].draw(x, y); } } } } getTile(x, y) { if (typeof(this.regions[Math.floor(x/256)]) !== "undefined" && typeof(this.regions[Math.floor(x/256)][Math.floor(y/256)]) !== "undefined") { return bufToRuid(this.regions[Math.floor(x/256)][Math.floor(y/256)], ((x&255)+((y&255)*256))*16); } else { return "00000000000000000000000000000000"; } } setTile(x, y, tileId) { if (typeof(this.regions[Math.floor(x/256)]) !== "undefined" && typeof(this.regions[Math.floor(x/256)][Math.floor(y/256)]) !== "undefined") { ruidToBuf(tileId, this.regions[Math.floor(x/256)][Math.floor(y/256)], ((x&255)+((y&255)*256))*16); } } }
40.375
339
0.654902
e7ea9b418ef09dc2361de5d9ada98bfd38198af3
19
py
Python
login.py
XM001-creater/test_one
1cf96a45c8dfbf988125e3d250d86fb06fe65c34
[ "MIT" ]
null
null
null
login.py
XM001-creater/test_one
1cf96a45c8dfbf988125e3d250d86fb06fe65c34
[ "MIT" ]
null
null
null
login.py
XM001-creater/test_one
1cf96a45c8dfbf988125e3d250d86fb06fe65c34
[ "MIT" ]
null
null
null
num1 =1 num2 = 222
6.333333
10
0.631579
85bcf010cab7ef0bfc36b7ec9a70eee3925bd199
4,357
js
JavaScript
commands/fusecards.js
DiscordCards/Bot
6afc663aad5ae1968d60ba26dd1bea031041c21a
[ "Apache-2.0" ]
3
2019-06-06T11:45:08.000Z
2019-06-06T12:45:21.000Z
commands/fusecards.js
DiscordCards/Bot
6afc663aad5ae1968d60ba26dd1bea031041c21a
[ "Apache-2.0" ]
null
null
null
commands/fusecards.js
DiscordCards/Bot
6afc663aad5ae1968d60ba26dd1bea031041c21a
[ "Apache-2.0" ]
null
null
null
const Fuse = require("fuse.js"); module.exports = { Execute: (Args, message, _) => { if(Args.length >= 1){ let User = new DiscordCards.classHandler.classes.User(message.author); User.get().then(user => { if(user === null){ message.channel.send(_('no_start')); return; } let item = Args.join(" "); DiscordCards.classHandler.classes.Series.getAll().then((series) => { let y = {}; series.map((a) => { y[a.id] = a; }); let isId = item.startsWith("#"); let results = isId ? series.filter(i=>i.id===item.slice(1)) : Common.qSearch(series, item); let found = false; Object.keys(y).map((a) => { if(item.toLowerCase() === y[a].name.toLowerCase() || (isId && item.slice(1) === y[a].id)){ let embedPerms = false; let filePerms = false; if(message.channel.type !== "text"){ embedPerms = true; filePerms = true; }else{ if(message.channel.permissionsFor(DiscordCards.user).has("EMBED_LINKS")){ embedPerms = true; } if(message.channel.permissionsFor(DiscordCards.user).has("ATTACH_FILES")){ filePerms = true; } } found = true; let currentSeries = y[a]; let Series = new DiscordCards.classHandler.classes.Series(currentSeries.id); if(user.badges[currentSeries.id]){ message.channel.send(_('has_badge', {user:message.author.username})); }else{ Series.getCards().then((cards) => { let badCards = cards.filter(card=>{return !(user.inv[card.id] && user.inv[card.id] > 0)}); if(badCards.length > 0){ message.channel.send(`${_('missing_cards')} ${badCards.map(c=>"`"+c.name+"`").sort().join(", ")}`); }else if(currentSeries.locked){ message.channel.send(_('series_locked')); }else{ User.addBadge(currentSeries.id).then(()=>{ let cache = new Date().valueOf().toString(36); Promise.all(cards.map(c=>User.removeItems(c.id, 1))).then(()=>{ let msg = _('earned_badge', {user:message.author.username}) let embed = { embed: { author: { icon_url: message.author.avatarURL, name: msg }, color: user.settings.displayColor ? user.settings.displayColor : 0x7289da, image: { url: `http://discord.cards/i/b/${currentSeries.id}.png?r=${cache}` } } }; if(embedPerms){ message.channel.send('', embed) }else if(filePerms){ message.channel.startTyping(); message.channel.sendFile(msg, {file:{attachment:`http://discord.cards/i/b/${currentSeries.id}.png?r=${cache}`, name:`${currentItem.id}.png`}}); message.channel.stopTyping(); }else{ message.channel.send(msg); } }).catch((e) => {Common.sendError(message, e);}); }).catch((e) => {Common.sendError(message, e);}); } }).catch((e) => {Common.sendError(message, e);}); } } }); if(results.length > 0 && !found){ let itmFound = []; let msg = (results.length === 1 ? _('item_found') : _('items_found', {amount:results.length.formatNumber()}))+"\n" results.map((a) => { itmFound.push("``"+a.name+"``"); }); msg += itmFound.sort().join(", "); if(msg.length > 2000){ msg = `${_('items_found', {amount:results.length.formatNumber()})} ${_('found_specific')}`; } message.channel.send(msg); return; } if(!found){ if(isId){ message.channel.send(_('no_series_id_found', {user:message.author.username})); }else{ message.channel.send(_('no_series_exist_found', {user:message.author.username})); } } }).catch((e) => {Common.sendError(message, e);}); }).catch((e) => {Common.sendError(message, e);}); }else{ message.channel.send(_('specify_card_pack', {user:message.author.username})); } }, Description: "Fuses all cards of one series into a badge.", Usage: "[series]", Cooldown: 2, Category: "Shop", Extra: { "_(help_extra.modifiers)": [ "`#_(help_extra.mod_series_id)` - _(help_extra.fusecards_series_id)" ] }, Aliases: ["makebadge"] }
34.307087
156
0.548084
1679ff66764249a2fc600985cfca9bf02891b62f
6,018
h
C
include/owl/btntextg.h
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
include/owl/btntextg.h
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
include/owl/btntextg.h
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
//----------------------------------------------------------------------------// // ObjectWindows 1998 Copyright by Yura Bidus // // // // Used code and ideas from Dieter Windau and Joseph Parrello // // // // // // THIS CLASS AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // // PARTICULAR PURPOSE. // /// \file // /// Definition of classes TButtonTextGadget. // //----------------------------------------------------------------------------// #if !defined(OWL_BTNTEXTG_H) #define OWL_BTNTEXTG_H #include <owl/private/defs.h> #if defined(BI_HAS_PRAGMA_ONCE) # pragma once #endif #if defined(BI_COMP_WATCOM) # pragma read_only_file #endif #include <owl/buttonga.h> namespace owl { #include <owl/preclass.h> // /// \addtogroup gadgets /// @{ /// \class TButtonTextGadget /// Derived from TButtonGadget, TButtonTextGadget represents buttons with bitmap and /// text, or with text only, or with bitmap only, that you can click on or off. You /// can also apply attributes such as color, style, and shape (notched or unnotched) /// to your button-text gadgets. /// /// In addition to TButtonGadget, TButtonTextGadget has several types to deal with text: /// /// - \c \b TAlign Defines alignment for text (aLeft, aCenter, aRight), /// - \c \b TStyle Defines style of gadget (sBitmap, sText, sBitmapText). /// - \c \b TLayoutStyle Defines Layout Bitmap with text(lTextLeft,lTextTop,lTextRight,lTextBottom). // class _OWLCLASS TButtonTextGadget : public TButtonGadget { public: // /// Enumerates the text-alignment attributes. // enum TAlign { aLeft, ///< Aligns the text at the left edge of the bounding rectangle. aCenter, ///< Aligns the text horizontally at the center of the bounding rectangle. aRight ///< Aligns the text at the right edge of the bounding rectangle. }; // /// TStyle contains values that defines how gadget will be displayed: // enum TStyle { sBitmap=0x001, ///< Only the bitmap is displayed. sText=0x002, ///< Only text is displayed. sBitmapText=0x003 ///< Both text and bitmap are displayed. }; // /// TLayoutStyle contains values that defines how bitmap and text will be layout. // enum TLayoutStyle { lTextLeft, ///< Text left, bitmap right. lTextTop, ///< Text top, bitmap bottom. lTextRight, ///< Text right, bitmap left. lTextBottom ///< Text bottom, bitmap top. }; TButtonTextGadget( int id, TResId glyphResIdOrIndex, TStyle style = sBitmapText, TType type = Command, bool enabled = false, TState state = Up, bool sharedGlyph = false, uint numChars = 4); virtual ~TButtonTextGadget(); LPCTSTR GetText() const; void SetText(const tstring& text, bool repaint=true); void SetText(LPCTSTR s, bool repaint = true) {SetText(s ? owl::tstring(s) : owl::tstring(), repaint);} TStyle GetStyle() const; void SetStyle(const TStyle style, bool repaint=true); TAlign GetAlign() const; void SetAlign(const TAlign align, bool repaint=true); TLayoutStyle GetLayoutStyle() const; void SetLayoutStyle(const TLayoutStyle style, bool repaint=true); const TFont& GetFont() const; void SetFont(const TFont&, bool repaint = true); // // Override virtual methods defined in TGadget // virtual void GetDesiredSize(TSize &size); virtual void SetBounds(const TRect& rect); // // Override and initiate a WM_COMMAND_ENABLE message // virtual void CommandEnable(); protected: virtual void Paint(TDC& dc); virtual void Created(); virtual void Layout(TRect& srcRect, TRect& textRect, TRect& btnRect); virtual void PaintText(TDC& dc, TRect& rect, const tstring& text); virtual void SysColorChange(); void GetTextSize(TSize& size); // // Data members -- will become private // protected_data: tstring Text; uint NumChars; ///< Number of chars to reserve space for TAlign Align; ///< Alignment: left, center or right TStyle Style; ///< Style Bitmap, Text, Bitmap and Text TLayoutStyle LayoutStyle;///< Layout style TFont* Font; ///< The display font; if Font == 0, it will try to get the font from TGadgetWindow. private: // // Hidden to prevent accidental copying or assignment // TButtonTextGadget(const TButtonTextGadget&); TButtonTextGadget& operator =(const TButtonTextGadget&); }; /// @} #include <owl/posclass.h> // // -------------------------------------------------------------------------- // Inline implementation // // /// Returns the Style for the gadget. // inline TButtonTextGadget::TStyle TButtonTextGadget::GetStyle() const{ return Style; } // /// Returns the text for the gadget. // inline LPCTSTR TButtonTextGadget::GetText() const { return Text.c_str(); } // /// Returns the Align for the gadget. // inline TButtonTextGadget::TAlign TButtonTextGadget::GetAlign() const { return Align; } // /// Returns the LayoutStyle for the gadget. // inline TButtonTextGadget::TLayoutStyle TButtonTextGadget::GetLayoutStyle() const{ return LayoutStyle; } } // OWL namespace #endif // OWL_BTNTEXTG_H
32.354839
107
0.578598
2a092ee9883c22829cffa83f66836ac3d35bcbd7
4,668
lua
Lua
totalRP3/modules/dashboard/HTMLContent.lua
pthoelken/Total-RP-3
758f52214f522244d3a3dcf311593ac0aca56787
[ "Apache-2.0" ]
null
null
null
totalRP3/modules/dashboard/HTMLContent.lua
pthoelken/Total-RP-3
758f52214f522244d3a3dcf311593ac0aca56787
[ "Apache-2.0" ]
2
2019-05-23T05:52:42.000Z
2020-06-30T10:23:52.000Z
totalRP3/modules/dashboard/HTMLContent.lua
Solanya/Total-RP-3
0714ad2bf0cb70556b49bfb711bb14ee6fd43dd3
[ "Apache-2.0" ]
null
null
null
---------------------------------------------------------------------------------- --- Total RP 3 --- Dashboard HTML Content Frame --- ------------------------------------------------------------------------------ --- Copyright 2018 Daniel "Meorawr" Yates <[email protected]> --- --- Licensed under the Apache License, Version 2.0 (the "License"); --- you may not use this file except in compliance with the License. --- You may obtain a copy of the License at --- --- http://www.apache.org/licenses/LICENSE-2.0 --- --- Unless required by applicable law or agreed to in writing, software --- distributed under the License is distributed on an "AS IS" BASIS, --- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --- See the License for the specific language governing permissions and --- limitations under the License. ---------------------------------------------------------------------------------- ---@type TRP3_API local addonName, TRP3_API = ...; local Ellyb = Ellyb(addonName); -- Lua imports local strformat = string.format; -- Ellyb imports local Popups = Ellyb.Popups; -- WoW imports local hooksecurefunc = hooksecurefunc; local twipe = table.wipe; -- Total RP 3 imports local loc = TRP3_API.loc; --- Mixin for the SimpleHTML content frame that provides a GetText() method, --- as well as script handlers for hyperlinks. TRP3_DashboardHTMLContentMixin = {}; function TRP3_DashboardHTMLContentMixin:OnLoad() -- Reuse the main tooltip for our hyperlink goodness. self.tooltip = TRP3_MainTooltip; -- Mapping of URL identifiers to a single handler function. self.urlHandlers = {}; -- Replace the SetText method with a hooked equivalent. hooksecurefunc(self, "SetText", self.OnTextChanged); end --- Returns the content of the text currently displayed by this frame. function TRP3_DashboardHTMLContentMixin:GetText() return self.text; end --- Called when a hyperlink in the frame is clicked. function TRP3_DashboardHTMLContentMixin:OnHyperlinkClick(url, text, button) -- If there's a custom URL handler installed that matches this, dispatch. local handler = self.urlHandlers[url]; if handler then return handler(url, text, button); end -- Otherwise try some builtins. if url:sub(1, 7) == "twitter" then -- Twitter link. return self:OnHyperlinkClickTwitter(url, text, button); end -- Fallback: Allow the user to just copy the URL. Popups:OpenURL(url, loc.UI_LINK_SAFE); end function TRP3_DashboardHTMLContentMixin:OnHyperlinkClickTwitter(url, _, button) -- Left click opens the Social UI, right-click gives you a profile link. if Social_ToggleShow and button == "LeftButton" then Social_ToggleShow(url:gsub("twitter", "|cff61AAEE@") .. "|r "); else url = url:gsub("twitter", "http://twitter.com/"); Popups:OpenURL(url, "|cff55aceeTwitter profile|r\n"); end end --- Called when any hyperlinks in the content are moused-over. function TRP3_DashboardHTMLContentMixin:OnHyperlinkEnter(url, text) local tooltip = self.tooltip; tooltip:Hide(); tooltip:SetOwner(self, "ANCHOR_CURSOR"); if Social_ToggleShow and url:sub(1, 7) == "twitter" then -- Display the Twitter handle of the user and a two-line instruction -- with left and right click actions. tooltip:AddLine(url:gsub("twitter", "|cff61AAEE@"), 1, 1, 1, true); tooltip:AddLine(strformat( "|cffffff00%s:|r %s|n|cffffff00%s:|r %s", loc.CM_CLICK, loc.CM_TWEET, loc.CM_R_CLICK, loc.CM_TWEET_PROFILE ), 1, 1, 1, true); else -- Display the text of the hyperlink and a single left-click -- line that clicking this means opening a popup. tooltip:AddLine(text, 1, 1, 1, true); tooltip:AddLine(strformat( "|cffffff00%s:|r %s", loc.CM_CLICK, loc.CM_OPEN ), 1, 1, 1, true); end tooltip:Show(); end --- Called when any hyperlinks in the content are no longer moused-over. function TRP3_DashboardHTMLContentMixin:OnHyperlinkLeave() self.tooltip:Hide(); end --- Called when the text on the widget has changed. Stores the text for --- retrieval via GetText(). function TRP3_DashboardHTMLContentMixin:OnTextChanged(text) self.text = text; end --- Registers a handler for the given URL. When clicked, this handler will --- be called. Only a single handler may be present for any URL at a given time. function TRP3_DashboardHTMLContentMixin:RegisterHyperlink(url, handler) self.urlHandlers[url] = handler; end --- Unregisters any active handler for the given URL. function TRP3_DashboardHTMLContentMixin:UnregisterHyperlink(url) self.urlHandlers[url] = nil; end --- Unregisters all registered URL handler functions. function TRP3_DashboardHTMLContentMixin:UnregisterAllHyperlinks() twipe(self.urlHandlers); end
33.582734
82
0.706512
2eedce5527fe78c97dfdb2b6cfb9060ae52cb36d
905
kt
Kotlin
coil-base/src/test/java/coil/disk/SimpleTestDispatcher.kt
kimhc999/coil
017002109defceffcb6366d56356d78b24ef8260
[ "Apache-2.0" ]
null
null
null
coil-base/src/test/java/coil/disk/SimpleTestDispatcher.kt
kimhc999/coil
017002109defceffcb6366d56356d78b24ef8260
[ "Apache-2.0" ]
null
null
null
coil-base/src/test/java/coil/disk/SimpleTestDispatcher.kt
kimhc999/coil
017002109defceffcb6366d56356d78b24ef8260
[ "Apache-2.0" ]
null
null
null
package coil.disk import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Runnable import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicInteger import kotlin.coroutines.CoroutineContext /** * A simple test dispatcher that queues all tasks and executes one when [runNextTask] is called. */ class SimpleTestDispatcher : CoroutineDispatcher() { private val tasks = ConcurrentLinkedQueue<Runnable>() private val inProgressTasks = AtomicInteger() fun isIdle() = tasks.isEmpty() && inProgressTasks.get() == 0 fun runNextTask() { val block = tasks.remove() try { inProgressTasks.getAndIncrement() block.run() } finally { inProgressTasks.getAndDecrement() } } override fun dispatch(context: CoroutineContext, block: Runnable) { tasks += block } }
27.424242
96
0.698343
8652721fca9ad4443910abc4a2e557210ba9f1f6
4,233
rs
Rust
algebra-core/src/curves/models/bls12/g2.rs
minatools/zexe
669970590d80ad5d8d63a5cdc4b1301982b9ccbc
[ "Apache-2.0", "MIT" ]
6
2020-08-13T20:03:40.000Z
2021-12-22T21:56:09.000Z
algebra-core/src/curves/models/bls12/g2.rs
minatools/zexe
669970590d80ad5d8d63a5cdc4b1301982b9ccbc
[ "Apache-2.0", "MIT" ]
16
2019-12-10T22:34:50.000Z
2021-07-28T17:50:53.000Z
algebra-core/src/curves/models/bls12/g2.rs
minatools/zexe
669970590d80ad5d8d63a5cdc4b1301982b9ccbc
[ "Apache-2.0", "MIT" ]
6
2019-12-10T14:35:43.000Z
2021-08-07T14:47:20.000Z
use crate::{ bytes::ToBytes, curves::{ bls12::{Bls12Parameters, TwistType}, models::SWModelParameters, short_weierstrass_jacobian::{GroupAffine, GroupProjective}, AffineCurve, }, fields::{BitIterator, Field, Fp2}, io::{Result as IoResult, Write}, Vec, }; use num_traits::{One, Zero}; pub type G2Affine<P> = GroupAffine<<P as Bls12Parameters>::G2Parameters>; pub type G2Projective<P> = GroupProjective<<P as Bls12Parameters>::G2Parameters>; #[derive(Derivative)] #[derivative( Clone(bound = "P: Bls12Parameters"), Debug(bound = "P: Bls12Parameters"), PartialEq(bound = "P: Bls12Parameters"), Eq(bound = "P: Bls12Parameters") )] pub struct G2Prepared<P: Bls12Parameters> { // Stores the coefficients of the line evaluations as calculated in // https://eprint.iacr.org/2013/722.pdf pub ell_coeffs: Vec<(Fp2<P::Fp2Params>, Fp2<P::Fp2Params>, Fp2<P::Fp2Params>)>, pub infinity: bool, } #[derive(Derivative)] #[derivative( Clone(bound = "P: Bls12Parameters"), Copy(bound = "P: Bls12Parameters"), Debug(bound = "P: Bls12Parameters") )] struct G2HomProjective<P: Bls12Parameters> { x: Fp2<P::Fp2Params>, y: Fp2<P::Fp2Params>, z: Fp2<P::Fp2Params>, } impl<P: Bls12Parameters> Default for G2Prepared<P> { fn default() -> Self { Self::from(G2Affine::<P>::prime_subgroup_generator()) } } impl<P: Bls12Parameters> ToBytes for G2Prepared<P> { fn write<W: Write>(&self, mut writer: W) -> IoResult<()> { for coeff in &self.ell_coeffs { coeff.0.write(&mut writer)?; coeff.1.write(&mut writer)?; coeff.2.write(&mut writer)?; } self.infinity.write(writer) } } impl<P: Bls12Parameters> From<G2Affine<P>> for G2Prepared<P> { fn from(q: G2Affine<P>) -> Self { let two_inv = P::Fp::one().double().inverse().unwrap(); if q.is_zero() { return Self { ell_coeffs: vec![], infinity: true, }; } let mut ell_coeffs = vec![]; let mut r = G2HomProjective { x: q.x, y: q.y, z: Fp2::one(), }; for i in BitIterator::new(P::X).skip(1) { ell_coeffs.push(doubling_step::<P>(&mut r, &two_inv)); if i { ell_coeffs.push(addition_step::<P>(&mut r, &q)); } } Self { ell_coeffs, infinity: false, } } } impl<P: Bls12Parameters> G2Prepared<P> { pub fn is_zero(&self) -> bool { self.infinity } } fn doubling_step<B: Bls12Parameters>( r: &mut G2HomProjective<B>, two_inv: &B::Fp, ) -> (Fp2<B::Fp2Params>, Fp2<B::Fp2Params>, Fp2<B::Fp2Params>) { // Formula for line function when working with // homogeneous projective coordinates. let mut a = r.x * &r.y; a.mul_assign_by_fp(two_inv); let b = r.y.square(); let c = r.z.square(); let e = B::G2Parameters::COEFF_B * &(c.double() + &c); let f = e.double() + &e; let mut g = b + &f; g.mul_assign_by_fp(two_inv); let h = (r.y + &r.z).square() - &(b + &c); let i = e - &b; let j = r.x.square(); let e_square = e.square(); r.x = a * &(b - &f); r.y = g.square() - &(e_square.double() + &e_square); r.z = b * &h; match B::TWIST_TYPE { TwistType::M => (i, j.double() + &j, -h), TwistType::D => (-h, j.double() + &j, i), } } fn addition_step<B: Bls12Parameters>( r: &mut G2HomProjective<B>, q: &G2Affine<B>, ) -> (Fp2<B::Fp2Params>, Fp2<B::Fp2Params>, Fp2<B::Fp2Params>) { // Formula for line function when working with // homogeneous projective coordinates. let theta = r.y - &(q.y * &r.z); let lambda = r.x - &(q.x * &r.z); let c = theta.square(); let d = lambda.square(); let e = lambda * &d; let f = r.z * &c; let g = r.x * &d; let h = e + &f - &g.double(); r.x = lambda * &h; r.y = theta * &(g - &h) - &(e * &r.y); r.z *= &e; let j = theta * &q.x - &(lambda * &q.y); match B::TWIST_TYPE { TwistType::M => (j, -theta, lambda), TwistType::D => (lambda, -theta, j), } }
28.033113
83
0.550201
b2d93ba833cf1e0c7961b1add21037470175c381
1,550
py
Python
api/standup/utils/email.py
adoval4/standup
307200b46952c8129a36931103920d3200640b83
[ "BSD-2-Clause" ]
null
null
null
api/standup/utils/email.py
adoval4/standup
307200b46952c8129a36931103920d3200640b83
[ "BSD-2-Clause" ]
11
2020-02-12T02:27:29.000Z
2022-03-12T00:08:22.000Z
api/standup/utils/email.py
adoval4/standup
307200b46952c8129a36931103920d3200640b83
[ "BSD-2-Clause" ]
null
null
null
# django from django.core.mail import EmailMessage from django.conf import settings from django.template.loader import render_to_string # utiltities import threading class EmailThread(threading.Thread): """ Class uses a thread to send email """ def __init__(self, subject, content, recipient_list, is_html): self.subject = subject self.recipient_list = recipient_list self.content = content self.is_html = is_html threading.Thread.__init__(self) def run (self): msg = EmailMessage( self.subject, self.content, settings.DEFAULT_FROM_EMAIL, self.recipient_list ) if self.is_html: msg.content_subtype = "html" msg.send() def send_mail(subject, content, recipients, is_html=False): """ Sends email using EmailThread class """ EmailThread(subject, content, recipients, is_html).start() def send_template_mail(subject, template_name, context, recipients, is_html): """ Send email using EmailThread class with a template """ if len(recipients) == 0: return None content = render_to_string(template_name, context) send_mail(subject, content, recipients, is_html) def send_html_template_mail(subject, template_name, context, recipients): """ Send email using EmailThread class with a html template """ send_template_mail(subject, template_name, context, recipients, True) def send_text_template_mail(subject, template_name, context, recipients): """ Send email using EmailThread class with a plain text template """ send_template_mail(subject, template_name, context, recipients, False)
24.21875
77
0.762581
a43c42f3638a1f35bc0d79c521f0d78ac67298b7
63
sql
SQL
src/main/resources/db/migration/V1_58__brukernotifikasjon_forsokt_sendt_tid.sql
navikt/veilarbaktivitet
893b40370a1575d8f926fea3be0a65e0049c9911
[ "MIT" ]
null
null
null
src/main/resources/db/migration/V1_58__brukernotifikasjon_forsokt_sendt_tid.sql
navikt/veilarbaktivitet
893b40370a1575d8f926fea3be0a65e0049c9911
[ "MIT" ]
294
2020-09-15T09:48:27.000Z
2022-03-31T11:11:52.000Z
src/main/resources/db/migration/V1_58__brukernotifikasjon_forsokt_sendt_tid.sql
navikt/veilarbaktivitet
893b40370a1575d8f926fea3be0a65e0049c9911
[ "MIT" ]
null
null
null
alter table BRUKERNOTIFIKASJON add forsokt_sendt timestamp;
31.5
32
0.84127
165427bc843f2ac2a9208219e1a6fbea29a79b06
251
h
C
wutong/wutong/Session/View/CellView/WTChartletMessageCellView.h
GitDino/WTLife-App
d5f91bf228bf7ba2595ffffef8a5b4fc6839c3da
[ "MIT" ]
null
null
null
wutong/wutong/Session/View/CellView/WTChartletMessageCellView.h
GitDino/WTLife-App
d5f91bf228bf7ba2595ffffef8a5b4fc6839c3da
[ "MIT" ]
null
null
null
wutong/wutong/Session/View/CellView/WTChartletMessageCellView.h
GitDino/WTLife-App
d5f91bf228bf7ba2595ffffef8a5b4fc6839c3da
[ "MIT" ]
null
null
null
// // WTChartletMessageCellView.h // ChatBoxDemo // // Created by 魏欣宇 on 2018/7/8. // Copyright © 2018年 wutonglife. All rights reserved. // #import "WTCommonMessageCellView.h" @interface WTChartletMessageCellView : WTCommonMessageCellView @end
17.928571
62
0.749004
19edf707a985cff05742af41fdeea240fc2e18c4
213
sql
SQL
post-service/src/test/resources/schema.sql
jakubowski1005/microblog
4e0400e3621e8f351e14a1f774792b568efa78a4
[ "MIT" ]
null
null
null
post-service/src/test/resources/schema.sql
jakubowski1005/microblog
4e0400e3621e8f351e14a1f774792b568efa78a4
[ "MIT" ]
null
null
null
post-service/src/test/resources/schema.sql
jakubowski1005/microblog
4e0400e3621e8f351e14a1f774792b568efa78a4
[ "MIT" ]
null
null
null
DROP TABLE IF EXISTS post; CREATE TABLE IF NOT EXISTS post ( id INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, content VARCHAR(2048) NOT NULL, tags VARCHAR(2048) NOT NULL, owner VARCHAR(100) NOT NULL );
26.625
50
0.732394
20c069c67e691f88dfe2c2f0b5945beaa9f9a739
579
css
CSS
personal_blog/assets/static/style.css
Alisa-lisa/blog
9e9aaa50390742fcb416c382b2ab5d222a23f960
[ "MIT" ]
null
null
null
personal_blog/assets/static/style.css
Alisa-lisa/blog
9e9aaa50390742fcb416c382b2ab5d222a23f960
[ "MIT" ]
null
null
null
personal_blog/assets/static/style.css
Alisa-lisa/blog
9e9aaa50390742fcb416c382b2ab5d222a23f960
[ "MIT" ]
null
null
null
body { font-family: 'Verdana', sans-serif; margin: 0px; } a { color: #2a99b6; } a:hover { color: #33bbdf; } header, footer, div.page { background: #0d0f23; margin: 0 auto; padding: 45px 50px; } header h1 { margin-top: -25px; float: left; color: #4f656b; font-weight: normal; font-size: 42px; } nav { font-weight: bolder; float: right; } header nav ul { list-style: none; margin: 0; padding: 0; } header nav ul li { display: inline; margin: 0 8px 0 0; padding: 0; } div.page { background: #f1fbfe; }
12.0625
39
0.578584
8979f13fce45117d54031c274b93bbfeb47b6305
3,151
kt
Kotlin
quickstartKotlin/src/main/java/com/twllio/video/quickstart/kotlin/utils/RemoteParticipantEventHandler.kt
yandiquesada/twilio_examples
c4c9cfae432b63625dead94c6c122327a2717eb7
[ "MIT" ]
null
null
null
quickstartKotlin/src/main/java/com/twllio/video/quickstart/kotlin/utils/RemoteParticipantEventHandler.kt
yandiquesada/twilio_examples
c4c9cfae432b63625dead94c6c122327a2717eb7
[ "MIT" ]
null
null
null
quickstartKotlin/src/main/java/com/twllio/video/quickstart/kotlin/utils/RemoteParticipantEventHandler.kt
yandiquesada/twilio_examples
c4c9cfae432b63625dead94c6c122327a2717eb7
[ "MIT" ]
null
null
null
package com.twllio.video.quickstart.kotlin.utils import com.twilio.video.* interface RemoteParticipantEventHandler { fun onAudioTrackPublished(remoteParticipant: RemoteParticipant, remoteAudioTrackPublication: RemoteAudioTrackPublication) fun onAudioTrackUnpublished(remoteParticipant: RemoteParticipant, remoteAudioTrackPublication: RemoteAudioTrackPublication) fun onDataTrackPublished(remoteParticipant: RemoteParticipant, remoteDataTrackPublication: RemoteDataTrackPublication) fun onDataTrackUnpublished(remoteParticipant: RemoteParticipant, remoteDataTrackPublication: RemoteDataTrackPublication) fun onVideoTrackPublished(remoteParticipant: RemoteParticipant, remoteVideoTrackPublication: RemoteVideoTrackPublication) fun onVideoTrackUnpublished(remoteParticipant: RemoteParticipant, remoteVideoTrackPublication: RemoteVideoTrackPublication) fun onAudioTrackSubscribed(remoteParticipant: RemoteParticipant, remoteAudioTrackPublication: RemoteAudioTrackPublication, remoteAudioTrack: RemoteAudioTrack) fun onAudioTrackUnsubscribed(remoteParticipant: RemoteParticipant, remoteAudioTrackPublication: RemoteAudioTrackPublication, remoteAudioTrack: RemoteAudioTrack) fun onAudioTrackSubscriptionFailed(remoteParticipant: RemoteParticipant, remoteAudioTrackPublication: RemoteAudioTrackPublication, twilioException: TwilioException) fun onDataTrackSubscribed(remoteParticipant: RemoteParticipant, remoteDataTrackPublication: RemoteDataTrackPublication, remoteDataTrack: RemoteDataTrack) fun onDataTrackUnsubscribed(remoteParticipant: RemoteParticipant, remoteDataTrackPublication: RemoteDataTrackPublication, remoteDataTrack: RemoteDataTrack) fun onDataTrackSubscriptionFailed(remoteParticipant: RemoteParticipant, remoteDataTrackPublication: RemoteDataTrackPublication, twilioException: TwilioException) fun onVideoTrackSubscribed(remoteParticipant: RemoteParticipant, remoteVideoTrackPublication: RemoteVideoTrackPublication, remoteVideoTrack: RemoteVideoTrack) fun onVideoTrackUnsubscribed(remoteParticipant: RemoteParticipant, remoteVideoTrackPublication: RemoteVideoTrackPublication, remoteVideoTrack: RemoteVideoTrack) fun onVideoTrackSubscriptionFailed(remoteParticipant: RemoteParticipant, remoteVideoTrackPublication: RemoteVideoTrackPublication, twilioException: TwilioException) }
70.022222
96
0.662647
0e49697cc14af08306ca3be571829824c7168381
1,326
html
HTML
ex015/index.html
gabrielguedesjj/HTML-CSS
975a259f531a3e7a2dd94aaabe9182663431eed2
[ "MIT" ]
null
null
null
ex015/index.html
gabrielguedesjj/HTML-CSS
975a259f531a3e7a2dd94aaabe9182663431eed2
[ "MIT" ]
null
null
null
ex015/index.html
gabrielguedesjj/HTML-CSS
975a259f531a3e7a2dd94aaabe9182663431eed2
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Estilos Externos </title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Capitulo 1</h1> <h2 >Capitulo 1.1</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Esse error ex quas repudiandae est! Doloremque repellendus consequuntur ut, delectus hic quasi quia labore sequi est, vitae minima nisi tenetur eos.</p> <h2>Capitulo 1.2</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consectetur, odit cumque necessitatibus culpa nihil mollitia eius porro veritatis incidunt, unde vero, amet nam eum corrupti voluptatum? Recusandae maxime molestias quo.</p> <h1 >Capitulo 2</h1> <h2 >Capitulo 2.1</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestiae, amet. Minus perferendis culpa at libero, molestiae expedita voluptate, ut nemo voluptatum omnis doloremque necessitatibus provident eligendi voluptates possimus exercitationem laborum.</p> <p style="text-align: right;"> <a href="pagina02.html" target="_self">ir para a pagina 2</a></p> </body> </html>
53.04
267
0.69457
df2b1474e5c17f08dd6392b700af4edd192e0d97
249
kt
Kotlin
kotlin-antd/antd-samples/src/main/kotlin/samples/empty/Simple.kt
xlj44400/kotlin-js-wrappers
ce8216c0332abdfefcc0a06cf5fbbbf24e669931
[ "Apache-2.0" ]
null
null
null
kotlin-antd/antd-samples/src/main/kotlin/samples/empty/Simple.kt
xlj44400/kotlin-js-wrappers
ce8216c0332abdfefcc0a06cf5fbbbf24e669931
[ "Apache-2.0" ]
null
null
null
kotlin-antd/antd-samples/src/main/kotlin/samples/empty/Simple.kt
xlj44400/kotlin-js-wrappers
ce8216c0332abdfefcc0a06cf5fbbbf24e669931
[ "Apache-2.0" ]
null
null
null
package samples.empty import antd.empty.* import react.* import styled.* fun RBuilder.simple() { styledDiv { css { +EmptyStyles.simple } empty { attrs.image = EmptyComponent.PRESENTED_IMAGE_SIMPLE } } }
16.6
63
0.618474
4a0aa0368fca0b7cbc976c43da626bc00d34e4fc
4,814
sql
SQL
distro/sql/upgrade/all/flowable.oracle.upgradestep.6.6.0.to.6.7.0.all.sql
jiandiao/flowable-engine
1bd26b2b2706fc334264603c69bd021c9152f244
[ "Apache-2.0" ]
5,250
2016-10-13T08:15:16.000Z
2022-03-31T13:53:26.000Z
distro/sql/upgrade/all/flowable.oracle.upgradestep.6.6.0.to.6.7.0.all.sql
jiandiao/flowable-engine
1bd26b2b2706fc334264603c69bd021c9152f244
[ "Apache-2.0" ]
1,736
2016-10-13T17:03:10.000Z
2022-03-31T19:27:39.000Z
distro/sql/upgrade/all/flowable.oracle.upgradestep.6.6.0.to.6.7.0.all.sql
jiandiao/flowable-engine
1bd26b2b2706fc334264603c69bd021c9152f244
[ "Apache-2.0" ]
2,271
2016-10-13T08:27:26.000Z
2022-03-31T15:36:02.000Z
update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'common.schema.version'; update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'entitylink.schema.version'; update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'identitylink.schema.version'; create index ACT_IDX_TJOB_DUEDATE on ACT_RU_TIMER_JOB(DUEDATE_); update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'job.schema.version'; update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'batch.schema.version'; update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'task.schema.version'; update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'variable.schema.version'; update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'eventsubscription.schema.version'; alter table ACT_HI_PROCINST add PROPAGATED_STAGE_INST_ID_ NVARCHAR2(255); create index ACT_IDX_EXEC_REF_ID_ on ACT_RU_EXECUTION(REFERENCE_ID_); create index ACT_IDX_RU_ACTI_TASK on ACT_RU_ACTINST(TASK_ID_); update ACT_GE_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'schema.version'; update ACT_ID_PROPERTY set VALUE_ = '6.7.0.0' where NAME_ = 'schema.version'; UPDATE FLOWABLE.ACT_APP_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.10.1 (192.168.10.1)', LOCKGRANTED = TO_TIMESTAMP('2021-08-30 13:46:13.533', 'YYYY-MM-DD HH24:MI:SS.FF') WHERE ID = 1 AND LOCKED = 0; UPDATE FLOWABLE.ACT_APP_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1; UPDATE FLOWABLE.ACT_CMMN_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.10.1 (192.168.10.1)', LOCKGRANTED = TO_TIMESTAMP('2021-08-30 13:46:16.949', 'YYYY-MM-DD HH24:MI:SS.FF') WHERE ID = 1 AND LOCKED = 0; ALTER TABLE FLOWABLE.ACT_CMMN_RU_CASE_INST ADD LAST_REACTIVATION_TIME_ TIMESTAMP(3); ALTER TABLE FLOWABLE.ACT_CMMN_RU_CASE_INST ADD LAST_REACTIVATION_USER_ID_ VARCHAR2(255); ALTER TABLE FLOWABLE.ACT_CMMN_HI_CASE_INST ADD LAST_REACTIVATION_TIME_ TIMESTAMP(3); ALTER TABLE FLOWABLE.ACT_CMMN_HI_CASE_INST ADD LAST_REACTIVATION_USER_ID_ VARCHAR2(255); INSERT INTO FLOWABLE.ACT_CMMN_DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, MD5SUM, DESCRIPTION, COMMENTS, EXECTYPE, CONTEXTS, LABELS, LIQUIBASE, DEPLOYMENT_ID) VALUES ('14', 'flowable', 'org/flowable/cmmn/db/liquibase/flowable-cmmn-db-changelog.xml', SYSTIMESTAMP, 13, '8:086b40b3a05596dcc8a8d7479922d494', 'addColumn tableName=ACT_CMMN_RU_CASE_INST; addColumn tableName=ACT_CMMN_HI_CASE_INST', '', 'EXECUTED', NULL, NULL, '4.3.5', '0331179599'); UPDATE FLOWABLE.ACT_CMMN_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1; UPDATE FLOWABLE.FLW_EV_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.10.1 (192.168.10.1)', LOCKGRANTED = TO_TIMESTAMP('2021-08-30 13:46:20.013', 'YYYY-MM-DD HH24:MI:SS.FF') WHERE ID = 1 AND LOCKED = 0; UPDATE FLOWABLE.FLW_EV_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1; UPDATE FLOWABLE.ACT_DMN_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.10.1 (192.168.10.1)', LOCKGRANTED = TO_TIMESTAMP('2021-08-30 13:46:23.077', 'YYYY-MM-DD HH24:MI:SS.FF') WHERE ID = 1 AND LOCKED = 0; UPDATE FLOWABLE.ACT_DMN_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1; UPDATE FLOWABLE.ACT_FO_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.10.1 (192.168.10.1)', LOCKGRANTED = TO_TIMESTAMP('2021-08-30 13:46:26.319', 'YYYY-MM-DD HH24:MI:SS.FF') WHERE ID = 1 AND LOCKED = 0; CREATE INDEX FLOWABLE.ACT_IDX_FORM_TASK ON FLOWABLE.ACT_FO_FORM_INSTANCE(TASK_ID_); CREATE INDEX FLOWABLE.ACT_IDX_FORM_PROC ON FLOWABLE.ACT_FO_FORM_INSTANCE(PROC_INST_ID_); CREATE INDEX FLOWABLE.ACT_IDX_FORM_SCOPE ON FLOWABLE.ACT_FO_FORM_INSTANCE(SCOPE_ID_, SCOPE_TYPE_); INSERT INTO FLOWABLE.ACT_FO_DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, MD5SUM, DESCRIPTION, COMMENTS, EXECTYPE, CONTEXTS, LABELS, LIQUIBASE, DEPLOYMENT_ID) VALUES ('6', 'flowable', 'org/flowable/form/db/liquibase/flowable-form-db-changelog.xml', SYSTIMESTAMP, 5, '8:384bbd364a649b67c3ca1bcb72fe537f', 'createIndex indexName=ACT_IDX_FORM_TASK, tableName=ACT_FO_FORM_INSTANCE; createIndex indexName=ACT_IDX_FORM_PROC, tableName=ACT_FO_FORM_INSTANCE; createIndex indexName=ACT_IDX_FORM_SCOPE, tableName=ACT_FO_FORM_INSTANCE', '', 'EXECUTED', NULL, NULL, '4.3.5', '0331189147'); UPDATE FLOWABLE.ACT_FO_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1; UPDATE FLOWABLE.ACT_CO_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.10.1 (192.168.10.1)', LOCKGRANTED = TO_TIMESTAMP('2021-08-30 13:46:29.559', 'YYYY-MM-DD HH24:MI:SS.FF') WHERE ID = 1 AND LOCKED = 0; UPDATE FLOWABLE.ACT_CO_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1;
65.945205
601
0.777939
32c483f16aea58341ca820b0a2e6438a9a740659
257
sql
SQL
sakila/query9.sql
Awes35/sakila-sql
efe1cf4ebc5ec99ea23043fc3d7096ada2ee7362
[ "MIT" ]
null
null
null
sakila/query9.sql
Awes35/sakila-sql
efe1cf4ebc5ec99ea23043fc3d7096ada2ee7362
[ "MIT" ]
null
null
null
sakila/query9.sql
Awes35/sakila-sql
efe1cf4ebc5ec99ea23043fc3d7096ada2ee7362
[ "MIT" ]
null
null
null
use sakila; #author Kollen Gruizenga #query 9 #count number of films with category type Horror SELECT DISTINCT count(f.film_id) FROM category c, film f, film_category fc WHERE c.name = 'Horror' AND f.film_id = fc.film_id AND c.category_id = fc.category_id
23.363636
48
0.77821
e991557b0369bc3e731b391a06f8f80f4631b4f2
9,387
rs
Rust
src/config.rs
Gui-Yom/ultralight-rs
58d480aa483f29ddad6ac20ecb8c49078737d231
[ "Apache-2.0" ]
null
null
null
src/config.rs
Gui-Yom/ultralight-rs
58d480aa483f29ddad6ac20ecb8c49078737d231
[ "Apache-2.0" ]
null
null
null
src/config.rs
Gui-Yom/ultralight-rs
58d480aa483f29ddad6ac20ecb8c49078737d231
[ "Apache-2.0" ]
null
null
null
use ultralight_sys::{ ulConfigSetAnimationTimerDelay, ulConfigSetCachePath, ulConfigSetDeviceScale, ulConfigSetEnableImages, ulConfigSetEnableJavaScript, ulConfigSetFaceWinding, ulConfigSetFontFamilyFixed, ulConfigSetFontFamilySansSerif, ulConfigSetFontFamilySerif, ulConfigSetFontFamilyStandard, ulConfigSetFontGamma, ulConfigSetFontHinting, ulConfigSetForceRepaint, ulConfigSetMemoryCacheSize, ulConfigSetMinLargeHeapSize, ulConfigSetMinSmallHeapSize, ulConfigSetOverrideRAMSize, ulConfigSetPageCacheSize, ulConfigSetRecycleDelay, ulConfigSetResourcePath, ulConfigSetScrollTimerDelay, ulConfigSetUseGPURenderer, ulConfigSetUserAgent, ulConfigSetUserStylesheet, ulCreateConfig, ulDestroyConfig, ULConfig, ULFaceWinding, ULFontHinting, }; use crate::string::ULString; #[derive(Clone)] pub struct Config { pub raw: ULConfig, created: bool, } pub type FaceWinding = ULFaceWinding; pub type FontHinting = ULFontHinting; impl Config { /// Create config with default values pub fn new() -> Self { unsafe { Config { raw: ulCreateConfig(), created: true, } } } /// The file path to the directory that contains Ultralight's bundled /// resources (eg, cacert.pem and other localized resources). pub fn resource_path(&self, resource_path: &str) { unsafe { let ulstr: ULString = resource_path.into(); ulConfigSetResourcePath(self.raw, ulstr.into()); } } /// The file path to a writable directory that will be used to store cookies, /// cached resources, and other persistent data. pub fn cache_path(&self, cache_path: &str) { unsafe { let ulstr: ULString = cache_path.into(); ulConfigSetCachePath(self.raw, ulstr.into()); } } /// When enabled, each View will be rendered to an offscreen GPU texture /// using the GPU driver set in Platform::set_gpu_driver. You can fetch /// details for the texture via View::render_target. /// /// When disabled (the default), each View will be rendered to an offscreen /// pixel buffer. This pixel buffer can optionally be provided by the user-- /// for more info see <Ultralight/platform/Surface.h> and View::surface. pub fn use_gpu_renderer(&self, use_gpu: bool) { unsafe { ulConfigSetUseGPURenderer(self.raw, use_gpu); } } /// The amount that the application DPI has been scaled (200% = 2.0). /// This should match the device scale set for the current monitor. /// /// Note: Device scales are rounded to nearest 1/8th (eg, 0.125). pub fn device_scale(&self, device_scale: f64) { unsafe { ulConfigSetDeviceScale(self.raw, device_scale); } } /// The winding order for front-facing triangles. /// /// Note: This is only used when the GPU renderer is enabled. pub fn face_winding(&self, face_winding: FaceWinding) { unsafe { ulConfigSetFaceWinding(self.raw, face_winding); } } /// Whether or not images should be enabled. pub fn enable_images(&self, enable_images: bool) { unsafe { ulConfigSetEnableImages(self.raw, enable_images); } } /// Whether or not JavaScript should be enabled. pub fn enable_javascript(&self, enable_javascript: bool) { unsafe { ulConfigSetEnableJavaScript(self.raw, enable_javascript); } } /// The hinting algorithm to use when rendering fonts. pub fn font_hinting(&self, font_hinting: FontHinting) { unsafe { ulConfigSetFontHinting(self.raw, font_hinting); } } /// The gamma to use when compositing font glyphs, change this value to /// adjust contrast (Adobe and Apple prefer 1.8, others may prefer 2.2). pub fn font_gamma(&self, font_gamma: f64) { unsafe { ulConfigSetFontGamma(self.raw, font_gamma); } } /// Default font-family to use. pub fn font_family_standard(&self, font_family_standard: &str) { unsafe { let ulstr: ULString = font_family_standard.into(); ulConfigSetFontFamilyStandard(self.raw, ulstr.into()); } } /// Default font-family to use for fixed fonts. (pre/code) pub fn font_family_fixed(&self, font_family_fixed: &str) { unsafe { let ulstr: ULString = font_family_fixed.into(); ulConfigSetFontFamilyFixed(self.raw, ulstr.into()); } } /// Default font-family to use for serif fonts. pub fn font_family_serif(&self, font_family_serif: &str) { unsafe { let ulstr: ULString = font_family_serif.into(); ulConfigSetFontFamilySerif(self.raw, ulstr.into()); } } /// Default font-family to use for sans-serif fonts. pub fn font_family_sans_serif(&self, font_family_sans_serif: &str) { unsafe { let ulstr: ULString = font_family_sans_serif.into(); ulConfigSetFontFamilySansSerif(self.raw, ulstr.into()); } } /// Default user-agent string. pub fn user_agent(&self, user_agent: &str) { unsafe { let ulstr: ULString = user_agent.into(); ulConfigSetUserAgent(self.raw, ulstr.into()); } } /// Default user stylesheet. You should set this to your own custom CSS /// string to define default styles for various DOM elements, scrollbars, /// and platform input widgets. pub fn user_stylesheet(&self, user_stylesheet: &str) { unsafe { let ulstr: ULString = user_stylesheet.into(); ulConfigSetUserStylesheet(self.raw, ulstr.into()); } } /// Whether or not we should continuously repaint any Views or compositor /// layers, regardless if they are dirty or not. This is mainly used to /// diagnose painting/shader issues. pub fn force_repaint(&self, force_repaint: bool) { unsafe { ulConfigSetForceRepaint(self.raw, force_repaint); } } /// When a CSS animation is active, the amount of time (in seconds) to wait /// before triggering another repaint. Default is 60 Hz. pub fn animation_timer_delay(&self, animation_timer_delay: f64) { unsafe { ulConfigSetAnimationTimerDelay(self.raw, animation_timer_delay); } } /// When a smooth scroll animation is active, the amount of time (in seconds) /// to wait before triggering another repaint. Default is 60 Hz. pub fn scroll_timer_delay(&self, scroll_timer_delay: f64) { unsafe { ulConfigSetScrollTimerDelay(self.raw, scroll_timer_delay); } } /// The amount of time (in seconds) to wait before running the recycler (will /// attempt to return excess memory back to the system). pub fn recycle_delay(&self, recycle_delay: f64) { unsafe { ulConfigSetRecycleDelay(self.raw, recycle_delay); } } /// Size of WebCore's memory cache in bytes. /// /// You should increase this if you anticipate handling pages with /// large resources, Safari typically uses 128+ MiB for its cache. pub fn memory_cache_size(&self, memory_cache_size: u32) { unsafe { ulConfigSetMemoryCacheSize(self.raw, memory_cache_size); } } /// Number of pages to keep in the cache. Defaults to 0 (none). /// /// Safari typically caches about 5 pages and maintains an on-disk /// cache to support typical web-browsing activities. If you increase /// this, you should probably increase the memory cache size as well. pub fn page_cache_size(&self, page_cache_size: u32) { unsafe { ulConfigSetPageCacheSize(self.raw, page_cache_size); } } /// JavaScriptCore tries to detect the system's physical RAM size to set /// reasonable allocation limits. Set this to anything other than 0 to /// override the detected value. Size is in bytes. /// /// This can be used to force JavaScriptCore to be more conservative with /// its allocation strategy (at the cost of some performance). pub fn override_ram_size(&self, override_ram_size: u32) { unsafe { ulConfigSetOverrideRAMSize(self.raw, override_ram_size); } } /// The minimum size of large VM heaps in JavaScriptCore. Set this to a /// lower value to make these heaps start with a smaller initial value. pub fn min_large_heap_size(&self, min_large_heap_size: u32) { unsafe { ulConfigSetMinLargeHeapSize(self.raw, min_large_heap_size); } } /// The minimum size of small VM heaps in JavaScriptCore. Set this to a /// lower value to make these heaps start with a smaller initial value. pub fn min_small_heap_size(&self, min_small_heap_size: u32) { unsafe { ulConfigSetMinSmallHeapSize(self.raw, min_small_heap_size); } } } impl From<ULConfig> for Config { fn from(raw: ULConfig) -> Self { Config { raw, created: false, } } } impl Drop for Config { fn drop(&mut self) { unsafe { if self.created { ulDestroyConfig(self.raw); } } } }
35.422642
95
0.64813
9e005082946ada0eae1eb760b6ebe8cd0a685020
442
rs
Rust
trait_bound_demo/src/main.rs
hello2mao/Learn-Rust
7295b41447ddad9d16cffe0062cb2c1962d5a7f4
[ "Apache-2.0" ]
null
null
null
trait_bound_demo/src/main.rs
hello2mao/Learn-Rust
7295b41447ddad9d16cffe0062cb2c1962d5a7f4
[ "Apache-2.0" ]
null
null
null
trait_bound_demo/src/main.rs
hello2mao/Learn-Rust
7295b41447ddad9d16cffe0062cb2c1962d5a7f4
[ "Apache-2.0" ]
null
null
null
trait GetName { fn get_name(&self) -> &String; } trait GetAge { fn get_age(&self) -> u32; } //1 fn print_info_1<T: GetName + GetAge>(item: T) { println!("name = {}", item.get_name()); println!("age = {}", item.get_age()); } //2 fn print_info_2<T>(item: T) where T: GetName + GetAge, { println!("name = {}", item.get_name()); println!("age = {}", item.get_age()); } fn main() { println!("Hello, world!"); }
16.37037
47
0.552036
ec978320b4e4e743526f7a428b830eb43c1267a5
3,626
asm
Assembly
chapter7/Project6.asm
pcooksey/Assembly-x86-64
4abe63454787eaea78e10de545bb61b047f702c1
[ "MIT" ]
null
null
null
chapter7/Project6.asm
pcooksey/Assembly-x86-64
4abe63454787eaea78e10de545bb61b047f702c1
[ "MIT" ]
null
null
null
chapter7/Project6.asm
pcooksey/Assembly-x86-64
4abe63454787eaea78e10de545bb61b047f702c1
[ "MIT" ]
null
null
null
;;; ;;; This is Suggested Project 7.9.2.6 ;;; Basically do simple signed addition, subtraction, multiplication, modulo ;;; With signed double-word and quad-word sizes ;;; Pg. 137 for the problem ;;; Pg. 24 for Registers ;;; Pg. 48 for Data Types SECTION .data SUCCESS: equ 0 ; Default success value SYS_EXIT: equ 60 ; Default system exit value ;; Variables used by the project dNum1: dd -900000 dNum2: dd -350000 dNum3: dd -450000 dNum4: dd -750000 qNum1: dq -700000000000000 ;; Answers dAns1: dd 0 ; dAns1 = dNum1 + dNum2 -1250000 dAns2: dd 0 ; dAns2 = dNum1 + dNum3 -1350000 dAns3: dd 0 ; dAns3 = dNum3 + dNum4 -1200000 dAns6: dd 0 ; dAns6 = dNum1 - dNum2 -550000 dAns7: dd 0 ; dAns7 = dNum1 - dNum3 -450000 dAns8: dd 0 ; dAns8 = dNum2 - dNum4 400000 qAns11: dq 0 ; qAns11 = dNum1 * dNum3 405000000000 qAns12: dq 0 ; qAns12 = dNum2 * dNum2 122500000000 qAns13: dq 0 ; qAns13 = dNum2 * dNum4 262500000000 dAns16: dd 0 ; dAns16 = dNum1 / dNum2 2 dAns17: dd 0 ; dAns17 = dNum3 / dNum4 0 dAns18: dd 0 ; dAns18 = qNum1 / dNum4 933333333 dRem18: dd 0 ; dRem18 = qNum1 % dNum4 -250000 SECTION .text ; Code Section global _start ; Standard start _start: ;; dAns1 = dNum1 + dNum2 mov eax, dword [dNum1] add eax, dword [dNum2] mov dword [dAns1], eax ;; dAns2 = dNum1 + dNum3 mov eax, dword [dNum1] add eax, dword [dNum3] mov dword [dAns2], eax ;; dAns3 = dNum3 + dNum4 mov eax, dword [dNum3] add eax, dword [dNum4] mov dword [dAns3], eax ;; dAns6 = dNum1 - dNum2 mov eax, dword [dNum1] sub eax, dword [dNum2] mov dword [dAns6], eax ;; dAns7 = dNum1 - dNum3 mov eax, dword [dNum1] sub eax, dword [dNum3] mov dword [dAns7], eax ;; dAns8 = dNum2 - dNum4 mov eax, dword [dNum2] sub eax, dword [dNum4] mov dword [dAns8], eax ;; dAns11 = dNum1 * dNum3 mov eax, dword [dNum1] imul dword [dNum3] ; Pg. 102 multi tables mov dword [qAns11], eax mov dword [qAns11+4], edx ;; dAns12 = dNum2 * dNum2 mov eax, dword [dNum2] imul eax mov dword [qAns12], eax mov dword [qAns12+4], edx ;; dAns13 = dNum2 * dNum4 mov eax, dword [dNum2] imul dword [dNum4] mov dword [qAns13], eax mov dword [qAns13+4], edx ;; dAns16 = dNum1 / dNum2 mov eax, dword [dNum1] cdq idiv dword [dNum2] ; Pg. 110 Divide tables mov dword [dAns16], eax ;; dAns17 = dNum3 / dNum4 mov eax, dword [dNum3] cdq idiv dword [dNum4] mov dword [dAns17], eax ;; dAns18 = qNum1 / dNum4 mov rax, qword [qNum1] cqo ; Pg. 91 Convert qword to qword rdx:rax movsxd rcx, dword [dNum4] ; Specific command for signed dword to qword idiv rcx mov dword [dAns18], eax mov dword [dRem18], edx ; Remember the remainder is stored in dx ; Done, terminate program last: mov rax, SYS_EXIT ; Call code for exit mov rdi, SUCCESS ; Exit with success syscall
36.626263
84
0.516547
74b77bde808ed2a639e3c647a65f2579b9159b75
2,234
js
JavaScript
Moves in squared strings (II).js
Dnmrk4/codewars-6kyu
5e522edaf0fd0528bb7bf34a689b837b32169b46
[ "MIT" ]
82
2019-02-18T11:05:06.000Z
2022-03-31T19:08:03.000Z
Moves in squared strings (II).js
Dnmrk4/codewars-6kyu
5e522edaf0fd0528bb7bf34a689b837b32169b46
[ "MIT" ]
null
null
null
Moves in squared strings (II).js
Dnmrk4/codewars-6kyu
5e522edaf0fd0528bb7bf34a689b837b32169b46
[ "MIT" ]
45
2019-05-26T04:11:05.000Z
2022-03-28T17:11:37.000Z
/* Description: You are given a string of n lines, each substring being n characters long: For example: s = "abcd\nefgh\nijkl\nmnop" We will study some transformations of this square of strings. Clock rotation 180 degrees: rot rot(s) => "ponm\nlkji\nhgfe\ndcba" selfie_and_rot(s) (or selfieAndRot or selfie-and-rot) It is initial string + string obtained by clock rotation 180 degrees with dots interspersed in order (hopefully) to better show the rotation when printed. s = "abcd\nefgh\nijkl\nmnop" --> "abcd....\nefgh....\nijkl....\nmnop....\n....ponm\n....lkji\n....hgfe\n....dcba" or printed: |rotation |selfie_and_rot |abcd --> ponm |abcd --> abcd.... |efgh lkji |efgh efgh.... |ijkl hgfe |ijkl ijkl.... |mnop dcba |mnop mnop.... ....ponm ....lkji ....hgfe ....dcba #Task: Write these two functions rotand selfie_and_rot and high-order function oper(fct, s) where fct is the function of one variable f to apply to the string s (fct will be one of rot, selfie_and_rot) #Examples: s = "abcd\nefgh\nijkl\nmnop" oper(rot, s) => "ponm\nlkji\nhgfe\ndcba" oper(selfie_and_rot, s) => "abcd....\nefgh....\nijkl....\nmnop....\n....ponm\n....lkji\n....hgfe\n....dcba" Notes: The form of the parameter fct in oper changes according to the language. You can see each form according to the language in "Your test cases". It could be easier to take these katas from number (I) to number (IV) Forthcoming katas will study other tranformations. Bash Note: The input strings are separated by , instead of \n. The ouput strings should be separated by \r instead of \n. See "Sample Tests". */ function rot(strng) { let arr=strng.slice().split('\n').reverse().map(v=>v.split('').reverse().join(``)).join('\n') return arr } function selfieAndRot(strng) { let n=strng.slice().split('\n')[0].length let arr=strng.slice().split('\n').reverse().map(v=>v.split('').reverse().join(``)).join(`\n${'.'.repeat(n)}`) let arr2=strng.slice().split('\n').join(`${'.'.repeat(n)}\n`) return arr2+`${'.'.repeat(n)}\n${'.'.repeat(n)}`+arr } function oper(fct, s) { return fct(s) }
38.517241
208
0.632945
014d16daf9ca5aaac4012a2ba8202d0b03575096
434
rs
Rust
arwa/src/window/pop_state_event.rs
RSSchermer/rudo
6413eff6c6b500e529a6a42d9bc35d0e48dcef18
[ "MIT" ]
null
null
null
arwa/src/window/pop_state_event.rs
RSSchermer/rudo
6413eff6c6b500e529a6a42d9bc35d0e48dcef18
[ "MIT" ]
null
null
null
arwa/src/window/pop_state_event.rs
RSSchermer/rudo
6413eff6c6b500e529a6a42d9bc35d0e48dcef18
[ "MIT" ]
null
null
null
use std::marker; use delegate::delegate; use wasm_bindgen::JsValue; use crate::event::impl_typed_event_traits; #[derive(Clone)] pub struct PopStateEvent<T> { inner: web_sys::PopStateEvent, _marker: marker::PhantomData<T>, } impl<T> PopStateEvent<T> { delegate! { to self.inner { pub fn state(&self) -> JsValue; } } } impl_typed_event_traits!(PopStateEvent, PopStateEvent, "popstate");
18.869565
67
0.665899
4d966e657ff3902bb8baa25746bcf1c53de37b31
17,471
html
HTML
index.html
radioblast/radioblast.github.io
5fdfd5c2e884e3d883bb476722a5cbdabc347a0c
[ "MIT" ]
null
null
null
index.html
radioblast/radioblast.github.io
5fdfd5c2e884e3d883bb476722a5cbdabc347a0c
[ "MIT" ]
null
null
null
index.html
radioblast/radioblast.github.io
5fdfd5c2e884e3d883bb476722a5cbdabc347a0c
[ "MIT" ]
null
null
null
<html lang="en"><head> <meta charset="utf-8"> <title>RadioBlast</title> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="manifest" href="/site.webmanifest"> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"> <meta name="msapplication-TileColor" content="#b91d47"> <meta name="theme-color" content="#ffffff"> <meta name="description" content="Blended as STANers"> <meta name="author" content="RadioBlast"> <link rel="stylesheet" type="text/css" href="css/foundation.min.css"> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,900" rel="stylesheet"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/foundation.min.js"></script> <script type="text/javascript" src="js/functions.js"></script> <script type="text/javascript" src="./dist/amplitude.js"></script> <link rel="stylesheet" type="text/css" href="css/app.css"> <style type="text/css"> html, body { height: 100%; } html { display: table; margin: auto; } body { display: table-cell; vertical-align: middle; } @font-face { font-family: Bariol; src: url("Bariol.otf") format("opentype"); } body>img{ width: 400px; position: relative; margin: auto; display: block;} html { overflow:hidden; } @media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2) { body>img{ width: 800px; position: relative; margin: auto; display: block; } #white-player { width: 240px !important; height: 240px !important; } #play-pause { width: 170px !important; height: 170px !important; } #white-player-controls #play-pause.amplitude-paused { position: relative; background-repeat: no-repeat; background-size: 170px !important; } #white-player-controls #play-pause.amplitude-playing { position: relative; background-repeat: no-repeat; background-size: 170px !important; } #play-pause { margin-top: 16px !important; } } </style> </head> <body style="background: #ffffff;"> <img src="https://radioblast.my.id/radioblast2.png"><br> <div id="white-player" style=" width: 120px; height: 120px; "> <div id="white-player-center" style=" height: 18px; "> <div class="song-meta-data"> </div> <div class="time-progress"> <div class="grid-x"> <div class="large-12 medium-12 small-12 cell"> </div> </div> <div class="grid-x"> </div> </div> </div> <div id="white-player-controls"> <div class="grid-x"> <div class="large-12 medium-12 small-12 cell"> <div class="amplitude-play-pause amplitude-paused" amplitude-main-play-pause="true" id="play-pause" style=" margin-right: 0px; margin-bottom: 0px; "></div> </div> <script type="text/javascript"> Amplitude.init({ "songs": [ { "name": "RadioBlast", "artist": "Blended as STANers", "album": "", "url": "https://podcast.radioblast.online:8443/live", "cover_art_url": "../album-art/radioblast.png", "live": "true",} ] }); </script> </div></div></div> <div class="soc" align="center" style="margin-top: 50px;"> <a href="http://line.me/ti/p/@hnk5560y" target="_blank"><img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHg9IjBweCIgeT0iMHB4IgogICAgIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIKICAgICB2aWV3Qm94PSIwIDAgMzIgMzIiCiAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDsiPjxnIGlkPSJzdXJmYWNlMSI+PHBhdGggc3R5bGU9IiAiIGQ9Ik0gOS42MjUgNSBDIDcuMDg5ODQ0IDUgNSA3LjA4OTg0NCA1IDkuNjI1IEwgNSAyMi4zNzUgQyA1IDI0LjkxMDE1NiA3LjA4OTg0NCAyNyA5LjYyNSAyNyBMIDIyLjM3NSAyNyBDIDI0LjkxMDE1NiAyNyAyNyAyNC45MTAxNTYgMjcgMjIuMzc1IEwgMjcgOS42MjUgQyAyNyA3LjA4OTg0NCAyNC45MTAxNTYgNSAyMi4zNzUgNSBaIE0gOS42MjUgNyBMIDIyLjM3NSA3IEMgMjMuODI4MTI1IDcgMjUgOC4xNzE4NzUgMjUgOS42MjUgTCAyNSAyMi4zNzUgQyAyNSAyMy44MjgxMjUgMjMuODI4MTI1IDI1IDIyLjM3NSAyNSBMIDkuNjI1IDI1IEMgOC4xNzE4NzUgMjUgNyAyMy44MjgxMjUgNyAyMi4zNzUgTCA3IDkuNjI1IEMgNyA4LjE3MTg3NSA4LjE3MTg3NSA3IDkuNjI1IDcgWiBNIDE2IDkuMjE4NzUgQyAxMS45ODQzNzUgOS4yMTg3NSA4LjcxODc1IDExLjg2NzE4OCA4LjcxODc1IDE1LjEyNSBDIDguNzE4NzUgMTguMDQ2ODc1IDExLjMxMjUgMjAuNDc2NTYzIDE0LjgxMjUgMjAuOTM3NSBDIDE1LjA1MDc4MSAyMC45ODgyODEgMTUuMzU1NDY5IDIxLjEwOTM3NSAxNS40Mzc1IDIxLjMxMjUgQyAxNS41MTE3MTkgMjEuNDk2MDk0IDE1LjQ5MjE4OCAyMS43ODEyNSAxNS40Njg3NSAyMS45Njg3NSBDIDE1LjQ2ODc1IDIxLjk2ODc1IDE1LjM5NDUzMSAyMi40ODQzNzUgMTUuMzc1IDIyLjU5Mzc1IEMgMTUuMzQzNzUgMjIuNzc3MzQ0IDE1LjIyMjY1NiAyMy4zMjgxMjUgMTYgMjMgQyAxNi43NzczNDQgMjIuNjcxODc1IDIwLjE5MTQwNiAyMC41MDc4MTMgMjEuNzE4NzUgMTguNzUgQyAyMi43NzM0MzggMTcuNTkzNzUgMjMuMjgxMjUgMTYuNDI5Njg4IDIzLjI4MTI1IDE1LjEyNSBDIDIzLjI4MTI1IDExLjg2NzE4OCAyMC4wMTU2MjUgOS4yMTg3NSAxNiA5LjIxODc1IFogTSAxMS43MTg3NSAxMy40MDYyNSBDIDExLjkyOTY4OCAxMy40MDYyNSAxMi4wOTM3NSAxMy41NzAzMTMgMTIuMDkzNzUgMTMuNzgxMjUgTCAxMi4wOTM3NSAxNi4yODEyNSBMIDEzLjE1NjI1IDE2LjI4MTI1IEMgMTMuMzY3MTg4IDE2LjI4MTI1IDEzLjUzMTI1IDE2LjQ3NjU2MyAxMy41MzEyNSAxNi42ODc1IEMgMTMuNTMxMjUgMTYuODk4NDM4IDEzLjM2NzE4OCAxNy4wNjI1IDEzLjE1NjI1IDE3LjA2MjUgTCAxMS43MTg3NSAxNy4wNjI1IEMgMTEuNTA3ODEzIDE3LjA2MjUgMTEuMzEyNSAxNi44OTg0MzggMTEuMzEyNSAxNi42ODc1IEwgMTEuMzEyNSAxMy43ODEyNSBDIDExLjMxMjUgMTMuNTcwMzEzIDExLjUwNzgxMyAxMy40MDYyNSAxMS43MTg3NSAxMy40MDYyNSBaIE0gMTQuMjgxMjUgMTMuNDA2MjUgQyAxNC40OTIxODggMTMuNDA2MjUgMTQuNjU2MjUgMTMuNTcwMzEzIDE0LjY1NjI1IDEzLjc4MTI1IEwgMTQuNjU2MjUgMTYuNjg3NSBDIDE0LjY1NjI1IDE2Ljg5ODQzOCAxNC40OTIxODggMTcuMDYyNSAxNC4yODEyNSAxNy4wNjI1IEMgMTQuMDcwMzEzIDE3LjA2MjUgMTMuODc1IDE2Ljg5ODQzOCAxMy44NzUgMTYuNjg3NSBMIDEzLjg3NSAxMy43ODEyNSBDIDEzLjg3NSAxMy41NzAzMTMgMTQuMDcwMzEzIDEzLjQwNjI1IDE0LjI4MTI1IDEzLjQwNjI1IFogTSAxNS40Njg3NSAxMy40MDYyNSBDIDE1LjUwNzgxMyAxMy4zOTQ1MzEgMTUuNTU0Njg4IDEzLjQwNjI1IDE1LjU5Mzc1IDEzLjQwNjI1IEMgMTUuNzEwOTM4IDEzLjQwNjI1IDE1LjgwNDY4OCAxMy40NjQ4NDQgMTUuODc1IDEzLjU2MjUgTCAxNy4zNzUgMTUuNTYyNSBMIDE3LjM3NSAxMy43ODEyNSBDIDE3LjM3NSAxMy41NzAzMTMgMTcuNTM5MDYzIDEzLjQwNjI1IDE3Ljc1IDEzLjQwNjI1IEMgMTcuOTYwOTM4IDEzLjQwNjI1IDE4LjEyNSAxMy41NzAzMTMgMTguMTI1IDEzLjc4MTI1IEwgMTguMTI1IDE2LjY4NzUgQyAxOC4xMjUgMTYuODUxNTYzIDE4LjAzMTI1IDE2Ljk4MDQ2OSAxNy44NzUgMTcuMDMxMjUgQyAxNy44MzU5MzggMTcuMDQyOTY5IDE3Ljc4OTA2MyAxNy4wNjI1IDE3Ljc1IDE3LjA2MjUgQyAxNy42MzI4MTMgMTcuMDYyNSAxNy41MDc4MTMgMTcuMDAzOTA2IDE3LjQzNzUgMTYuOTA2MjUgTCAxNS45Njg3NSAxNC44NzUgTCAxNS45Njg3NSAxNi42ODc1IEMgMTUuOTY4NzUgMTYuODk4NDM4IDE1LjgwNDY4OCAxNy4wNjI1IDE1LjU5Mzc1IDE3LjA2MjUgQyAxNS4zODI4MTMgMTcuMDYyNSAxNS4xODc1IDE2Ljg5ODQzOCAxNS4xODc1IDE2LjY4NzUgTCAxNS4xODc1IDEzLjc4MTI1IEMgMTUuMTg3NSAxMy42MTcxODggMTUuMzEyNSAxMy40NTcwMzEgMTUuNDY4NzUgMTMuNDA2MjUgWiBNIDE5LjAzMTI1IDEzLjQwNjI1IEwgMjAuNDY4NzUgMTMuNDA2MjUgQyAyMC42Nzk2ODggMTMuNDA2MjUgMjAuODQzNzUgMTMuNTcwMzEzIDIwLjg0Mzc1IDEzLjc4MTI1IEMgMjAuODQzNzUgMTMuOTkyMTg4IDIwLjY3OTY4OCAxNC4xNTYyNSAyMC40Njg3NSAxNC4xNTYyNSBMIDE5LjQwNjI1IDE0LjE1NjI1IEwgMTkuNDA2MjUgMTQuODQzNzUgTCAyMC40Njg3NSAxNC44NDM3NSBDIDIwLjY3OTY4OCAxNC44NDM3NSAyMC44NDM3NSAxNS4wMDc4MTMgMjAuODQzNzUgMTUuMjE4NzUgQyAyMC44NDM3NSAxNS40Mjk2ODggMjAuNjc5Njg4IDE1LjYyNSAyMC40Njg3NSAxNS42MjUgTCAxOS40MDYyNSAxNS42MjUgTCAxOS40MDYyNSAxNi4yODEyNSBMIDIwLjQ2ODc1IDE2LjI4MTI1IEMgMjAuNjc5Njg4IDE2LjI4MTI1IDIwLjg0Mzc1IDE2LjQ3NjU2MyAyMC44NDM3NSAxNi42ODc1IEMgMjAuODQzNzUgMTYuODk4NDM4IDIwLjY3OTY4OCAxNy4wNjI1IDIwLjQ2ODc1IDE3LjA2MjUgTCAxOS4wMzEyNSAxNy4wNjI1IEMgMTguODIwMzEzIDE3LjA2MjUgMTguNjU2MjUgMTYuODk4NDM4IDE4LjY1NjI1IDE2LjY4NzUgTCAxOC42NTYyNSAxMy43ODEyNSBDIDE4LjY1NjI1IDEzLjU3MDMxMyAxOC44MjAzMTMgMTMuNDA2MjUgMTkuMDMxMjUgMTMuNDA2MjUgWiAiPjwvcGF0aD48L2c+PC9zdmc+" style="width: 17%"></a> <a href="http://instagram.com/radioblast_" target="_blank"> <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHg9IjBweCIgeT0iMHB4IgogICAgIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIKICAgICB2aWV3Qm94PSIwIDAgMzIgMzIiCiAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDsiPjxnIGlkPSJzdXJmYWNlMSI+PHBhdGggc3R5bGU9IiAiIGQ9Ik0gMTEuNDY4NzUgNSBDIDcuOTE3OTY5IDUgNSA3LjkxNDA2MyA1IDExLjQ2ODc1IEwgNSAyMC41MzEyNSBDIDUgMjQuMDgyMDMxIDcuOTE0MDYzIDI3IDExLjQ2ODc1IDI3IEwgMjAuNTMxMjUgMjcgQyAyNC4wODIwMzEgMjcgMjcgMjQuMDg1OTM4IDI3IDIwLjUzMTI1IEwgMjcgMTEuNDY4NzUgQyAyNyA3LjkxNzk2OSAyNC4wODU5MzggNSAyMC41MzEyNSA1IFogTSAxMS40Njg3NSA3IEwgMjAuNTMxMjUgNyBDIDIzLjAwMzkwNiA3IDI1IDguOTk2MDk0IDI1IDExLjQ2ODc1IEwgMjUgMjAuNTMxMjUgQyAyNSAyMy4wMDM5MDYgMjMuMDAzOTA2IDI1IDIwLjUzMTI1IDI1IEwgMTEuNDY4NzUgMjUgQyA4Ljk5NjA5NCAyNSA3IDIzLjAwMzkwNiA3IDIwLjUzMTI1IEwgNyAxMS40Njg3NSBDIDcgOC45OTYwOTQgOC45OTYwOTQgNyAxMS40Njg3NSA3IFogTSAyMS45MDYyNSA5LjE4NzUgQyAyMS40MDIzNDQgOS4xODc1IDIxIDkuNTg5ODQ0IDIxIDEwLjA5Mzc1IEMgMjEgMTAuNTk3NjU2IDIxLjQwMjM0NCAxMSAyMS45MDYyNSAxMSBDIDIyLjQxMDE1NiAxMSAyMi44MTI1IDEwLjU5NzY1NiAyMi44MTI1IDEwLjA5Mzc1IEMgMjIuODEyNSA5LjU4OTg0NCAyMi40MTAxNTYgOS4xODc1IDIxLjkwNjI1IDkuMTg3NSBaIE0gMTYgMTAgQyAxMi42OTkyMTkgMTAgMTAgMTIuNjk5MjE5IDEwIDE2IEMgMTAgMTkuMzAwNzgxIDEyLjY5OTIxOSAyMiAxNiAyMiBDIDE5LjMwMDc4MSAyMiAyMiAxOS4zMDA3ODEgMjIgMTYgQyAyMiAxMi42OTkyMTkgMTkuMzAwNzgxIDEwIDE2IDEwIFogTSAxNiAxMiBDIDE4LjIyMjY1NiAxMiAyMCAxMy43NzczNDQgMjAgMTYgQyAyMCAxOC4yMjI2NTYgMTguMjIyNjU2IDIwIDE2IDIwIEMgMTMuNzc3MzQ0IDIwIDEyIDE4LjIyMjY1NiAxMiAxNiBDIDEyIDEzLjc3NzM0NCAxMy43NzczNDQgMTIgMTYgMTIgWiAiPjwvcGF0aD48L2c+PC9zdmc+" style="width: 17%"></a> <a href="http://twitter.com/radioblast_" target="_blank"><svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width=17% viewBox="0 0 224 224" style=" fill:#000000; vertical-align:middle;"><g transform="translate(30.24,30.24) scale(0.73,0.73)"><g fill="none" fill-rule="nonzero" stroke="none" stroke-width="none" stroke-linecap="butt" stroke-linejoin="none" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"><g fill="#000000" stroke="#000000" stroke-width="10" stroke-linejoin="round"><path d="M165.76,13.44c24.69018,0 44.8,20.10523 44.8,44.8v107.52c0,24.69078 -20.10922,44.8 -44.8,44.8h-107.52c-24.69078,0 -44.8,-20.10922 -44.8,-44.8v-107.52c0,-24.69078 20.10922,-44.8 44.8,-44.8zM22.4,58.24v107.52c0,19.84938 15.99062,35.84 35.84,35.84h107.52c19.84938,0 35.84,-15.99062 35.84,-35.84v-107.52c0,-19.85435 -15.99002,-35.84 -35.84,-35.84h-107.52c-19.84938,0 -35.84,15.99062 -35.84,35.84zM156.2225,70.105c4.55613,-1.06915 8.9477,-2.60808 12.8625,-4.935c1.60023,-0.95486 3.62441,-0.81955 5.08332,0.3398c1.45891,1.15935 2.04792,3.10066 1.47918,4.87521c-0.49433,1.54628 -1.51792,2.78707 -2.24875,4.20875c1.80771,-0.55319 3.76813,0.08777 4.89989,1.60202c1.13176,1.51425 1.19132,3.57592 0.14886,5.15298c-3.11167,4.67171 -7.21958,8.54575 -11.585,12.0575c0.0112,0.5227 0.035,1.03467 0.035,1.56625c0,17.57146 -6.5997,36.22469 -19.31125,50.68c-12.71155,14.45531 -31.72627,24.5875 -55.79,24.5875c-14.89092,0 -28.79515,-4.37971 -40.46,-11.89125c-1.75773,-1.12994 -2.50099,-3.32489 -1.79142,-5.29031c0.70956,-1.96542 2.68352,-3.17939 4.75768,-2.92594c1.75189,0.21038 3.54088,0.30625 5.38125,0.30625c6.90499,0 13.16105,-1.9654 19.005,-4.7075c-7.30953,-3.44179 -13.13484,-9.55858 -15.63625,-17.36c-0.52353,-1.6305 -0.07186,-3.4168 1.16375,-4.6025c-6.01278,-5.38689 -10.0625,-12.91006 -10.0625,-21.595v-0.315c-0.00021,-2.11702 1.48137,-3.94529 3.5525,-4.38375c-2.02747,-4.00057 -3.35125,-8.4416 -3.35125,-13.2125c0,-5.35495 1.43387,-10.41666 3.955,-14.76125c0.73914,-1.27275 2.05623,-2.10132 3.52353,-2.21661c1.46729,-0.11529 2.89763,0.49741 3.82647,1.63911c10.38651,12.76936 25.50685,21.22392 42.595,23.5025c-0.00134,-0.11644 -0.04375,-0.22459 -0.04375,-0.34125c0,-16.1552 13.1588,-29.365 29.295,-29.365c7.22439,0 13.59446,3.0094 18.71625,7.385zM117.17125,92.085c0,1.61237 0.17595,3.15767 0.525,4.6375c0.3235,1.37103 -0.01664,2.81437 -0.91828,3.89669c-0.90164,1.08232 -2.25981,1.67757 -3.66672,1.60706c-19.06591,-0.9651 -35.99599,-9.3467 -48.72,-21.97125c-0.28986,1.37309 -1.07625,2.54012 -1.07625,4.0075c0,7.11499 3.58509,13.33253 9.0475,16.9925c1.65846,1.11291 2.38001,3.18917 1.76915,5.09073c-0.61085,1.90156 -2.40658,3.16917 -4.40291,3.10803c-2.02841,-0.06471 -3.70113,-1.09655 -5.60875,-1.5575c2.11462,7.20871 7.89591,12.78382 15.295,14.28c2.03707,0.40676 3.5274,2.16036 3.60035,4.23636c0.07295,2.076 -1.29061,3.92989 -3.2941,4.47864c-1.28651,0.35569 -2.68397,0.36778 -4.03375,0.5425c3.64898,4.65295 8.54496,8.24973 14.8925,8.365c1.89189,0.03733 3.55636,1.2592 4.15887,3.05298c0.60251,1.79378 0.01313,3.77268 -1.47262,4.94452c-6.41592,5.04738 -14.24778,7.97212 -22.5225,9.72125c6.64666,2.26412 13.62882,3.7625 21.0525,3.7625c21.583,0 37.88407,-8.82211 49.07,-21.5425c11.18589,-12.72037 17.07125,-29.46223 17.07125,-44.765c0,-1.01011 -0.02744,-2.02636 -0.07,-3.03625c-0.06098,-1.50237 0.6357,-2.93515 1.855,-3.815c0.32153,-0.2329 0.50706,-0.61607 0.8225,-0.8575c-2.0288,0.03757 -3.82957,-1.29305 -4.38946,-3.24342c-0.55989,-1.95038 0.2609,-4.03355 2.00071,-5.07783c0.10179,-0.06115 0.16188,-0.17335 0.2625,-0.23625c-0.68404,0.16306 -1.24027,0.6068 -1.93375,0.74375c-1.51666,0.30047 -3.08106,-0.20225 -4.13875,-1.33c-3.70886,-3.96958 -8.96515,-6.44 -14.84,-6.44c-11.2814,0 -20.335,9.07988 -20.335,20.405z"></path></g><path d="M0,224v-224h224v224z" fill="none" stroke="none" stroke-width="1" stroke-linejoin="miter"></path><g fill="#000000" stroke="none" stroke-width="1" stroke-linejoin="miter"><path d="M58.24,13.44c-24.69078,0 -44.8,20.10922 -44.8,44.8v107.52c0,24.69078 20.10922,44.8 44.8,44.8h107.52c24.69078,0 44.8,-20.10922 44.8,-44.8v-107.52c0,-24.69477 -20.10982,-44.8 -44.8,-44.8zM58.24,22.4h107.52c19.84998,0 35.84,15.98565 35.84,35.84v107.52c0,19.84938 -15.99062,35.84 -35.84,35.84h-107.52c-19.84938,0 -35.84,-15.99062 -35.84,-35.84v-107.52c0,-19.84938 15.99062,-35.84 35.84,-35.84zM137.50625,62.72c-16.1362,0 -29.295,13.2098 -29.295,29.365c0,0.11665 0.04241,0.22481 0.04375,0.34125c-17.08815,-2.27857 -32.20849,-10.73313 -42.595,-23.5025c-0.92885,-1.1417 -2.35918,-1.7544 -3.82647,-1.63911c-1.46729,0.11529 -2.78438,0.94385 -3.52353,2.21661c-2.52113,4.34459 -3.955,9.4063 -3.955,14.76125c0,4.7709 1.32378,9.21193 3.35125,13.2125c-2.07112,0.43846 -3.55271,2.26673 -3.5525,4.38375v0.315c0,8.68494 4.04971,16.20811 10.0625,21.595c-1.23561,1.1857 -1.68728,2.972 -1.16375,4.6025c2.50141,7.80142 8.32672,13.91821 15.63625,17.36c-5.84394,2.7421 -12.10001,4.7075 -19.005,4.7075c-1.84038,0 -3.62936,-0.09587 -5.38125,-0.30625c-2.07416,-0.25346 -4.04811,0.96051 -4.75768,2.92594c-0.70956,1.96542 0.0337,4.16037 1.79142,5.29031c11.66485,7.51154 25.56908,11.89125 40.46,11.89125c24.06373,0 43.07845,-10.13219 55.79,-24.5875c12.71155,-14.45531 19.31125,-33.10854 19.31125,-50.68c0,-0.53158 -0.0238,-1.04355 -0.035,-1.56625c4.36542,-3.51175 8.47332,-7.38579 11.585,-12.0575c1.04246,-1.57706 0.9829,-3.63873 -0.14886,-5.15298c-1.13176,-1.51425 -3.09218,-2.1552 -4.89989,-1.60202c0.73083,-1.42168 1.75442,-2.66247 2.24875,-4.20875c0.56874,-1.77455 -0.02027,-3.71586 -1.47918,-4.87521c-1.45891,-1.15935 -3.48309,-1.29465 -5.08332,-0.3398c-3.9148,2.32693 -8.30637,3.86585 -12.8625,4.935c-5.12179,-4.3756 -11.49187,-7.385 -18.71625,-7.385zM137.50625,71.68c5.87485,0 11.13114,2.47042 14.84,6.44c1.05769,1.12775 2.6221,1.63047 4.13875,1.33c0.69348,-0.13695 1.2497,-0.58069 1.93375,-0.74375c-0.10062,0.0629 -0.16072,0.1751 -0.2625,0.23625c-1.73981,1.04428 -2.5606,3.12745 -2.00071,5.07783c0.55989,1.95038 2.36066,3.28099 4.38946,3.24342c-0.31544,0.24143 -0.50097,0.6246 -0.8225,0.8575c-1.21931,0.87984 -1.91598,2.31263 -1.855,3.815c0.04256,1.0099 0.07,2.02614 0.07,3.03625c0,15.30277 -5.88536,32.04463 -17.07125,44.765c-11.18593,12.72039 -27.487,21.5425 -49.07,21.5425c-7.42368,0 -14.40584,-1.49838 -21.0525,-3.7625c8.27472,-1.74913 16.10657,-4.67387 22.5225,-9.72125c1.48575,-1.17184 2.07513,-3.15074 1.47262,-4.94452c-0.60251,-1.79378 -2.26698,-3.01565 -4.15887,-3.05298c-6.34754,-0.11527 -11.24352,-3.71205 -14.8925,-8.365c1.34978,-0.17472 2.74724,-0.18682 4.03375,-0.5425c2.00349,-0.54875 3.36705,-2.40264 3.2941,-4.47864c-0.07295,-2.076 -1.56329,-3.8296 -3.60035,-4.23636c-7.39909,-1.49618 -13.18038,-7.07129 -15.295,-14.28c1.90762,0.46096 3.58034,1.49279 5.60875,1.5575c1.99633,0.06114 3.79205,-1.20647 4.40291,-3.10803c0.61085,-1.90156 -0.1107,-3.97781 -1.76915,-5.09073c-5.46241,-3.65996 -9.0475,-9.87751 -9.0475,-16.9925c0,-1.46739 0.78639,-2.63441 1.07625,-4.0075c12.72401,12.62455 29.65409,21.00615 48.72,21.97125c1.40691,0.07052 2.76507,-0.52474 3.66672,-1.60706c0.90164,-1.08232 1.24178,-2.52566 0.91828,-3.89669c-0.34905,-1.47983 -0.525,-3.02513 -0.525,-4.6375c0,-11.32513 9.0536,-20.405 20.335,-20.405z"></path></g><path d="" fill="none" stroke="none" stroke-width="1" stroke-linejoin="miter"></path></g></g></svg></a> <a href="https://podcast.radioblast.online"><div style="font-family:Bariol; font-size:150%;">podcast.radioblast.online</div></a> </div> <script src="upup.min.js"></script> <script> UpUp.start({ 'content-url': 'offline.html', 'assets': [ 'css/app.css', 'css/app.css.map', 'css/foundation.min.css', 'dist/amplitude.js', 'dist/amplitude.js.map', 'dist/amplitude.min.js', 'img/pause.svg', 'img/play.svg', 'js/foundation.min.js', 'js/function.js', 'js/jquery.js' ] }); </script> </body></html>
88.685279
7,186
0.772366
12616c359aae2736514418c29926e3f30bfa5307
793
h
C
net/internet/http/logger.h
guidoreina/gsniffer
0a5d619312a986204edf6372de8b2277596a255a
[ "BSD-2-Clause" ]
null
null
null
net/internet/http/logger.h
guidoreina/gsniffer
0a5d619312a986204edf6372de8b2277596a255a
[ "BSD-2-Clause" ]
null
null
null
net/internet/http/logger.h
guidoreina/gsniffer
0a5d619312a986204edf6372de8b2277596a255a
[ "BSD-2-Clause" ]
null
null
null
#ifndef NET_INTERNET_HTTP_LOGGER_H #define NET_INTERNET_HTTP_LOGGER_H #include <time.h> #include <limits.h> #include "fs/file.h" #include "net/ip_address.h" #include "net/connection.h" namespace net { namespace internet { namespace http { class logger { public: // Constructor. logger(); // Destructor. ~logger(); // Create. bool create(const char* dir); // Log HTTP request. bool log(time_t t, const connection* conn); protected: char _M_dir[PATH_MAX + 1]; fs::file _M_file; struct tm _M_time_prev_log; // Open log file. bool open(const struct tm* stm); }; inline logger::~logger() { if (_M_file.fd() != -1) { _M_file.close(); } } } } } #endif // NET_INTERNET_HTTP_LOGGER_H
16.183673
48
0.612863
21f73f69f7870406b8d55adf6a06e06c394d5cd6
5,153
html
HTML
pushsafer/config_api.html
LasseSchnepel/node-red-contrib-pushsafer
b5dd8cd9dfe0134998afde512167f5286296d9ba
[ "MIT" ]
null
null
null
pushsafer/config_api.html
LasseSchnepel/node-red-contrib-pushsafer
b5dd8cd9dfe0134998afde512167f5286296d9ba
[ "MIT" ]
null
null
null
pushsafer/config_api.html
LasseSchnepel/node-red-contrib-pushsafer
b5dd8cd9dfe0134998afde512167f5286296d9ba
[ "MIT" ]
null
null
null
<!--Type definition node for the api key--> <script type="text/x-red" data-template-name="pushsafer-config-api"> <div class="form-row"> <label for="node-config-input-apikey"><i class="fa fa-key"></i> <span data-i18n="pushsafer.config_api.apiKey"></span></label> <input type="text" id="node-config-input-apikey"> </div> <div class="form-row"> <label for="node-config-input-username"><i class="fa fa-user"></i> <span data-i18n="pushsafer.config_api.username"></span></label> <input type="text" id="node-config-input-username"> </div> <br/> <div class="form-row"> <label for="node-config-input-check"><i class="fa fa-question"></i> <span data-i18n="pushsafer.config_api.check"></span></label> <div style="display: inline-block; position: relative; width: 70%; height: 20px;"> <a id="node-config-input-check" class="editor-button" style="width:100%;"> <span data-i18n="pushsafer.config_api.checkButtonStandard"></span> </a> </div> </div> <br/> <div class="form-row"> <label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label> <input type="text" id="node-config-input-name" data-i18n="[placeholder]pushsafer.config_api.namePlaceholder"> </div> </script> <script type="text/x-red" data-help-name="pushsafer-config-api"> <p>Configures the API config of Pushsafer</p> <dl class="message-properties"> <dt>API-Key<span class="property-type">string</span></dt> <dd>Your private or alias key is required for authentication each time a push notification is sent.<br/> You can find it in your Pushsafer dashboard.<br/> Alias Key, you can set and use with predefined parameters.</dd> <dt>Username<span class="property-type">string</span></dt> <dd>Your login username is required for getting device information and API key check.</dd> </dl> </script> <script type="text/javascript"> RED.nodes.registerType('pushsafer-config-api', { category: 'config', defaults: { name: { value: '' } }, credentials: { apikey: { type: 'text', required: true, validate: function(v) { return String(v).length === 20 ? true : false; } }, username: { type: 'text', required: true, validate: function(v) { return String(v).length <= 255 ? true : false; } } }, label: function() { return this.name || this._('pushsafer.config_api.nodeName'); }, oneditprepare: function() { let node = this; let elementNodeConfigInputCheck = $('#node-config-input-check'); let elementNodeConfigInputCheckIcon = $('#node-config-input-check-icon'); let timeoutId = null; elementNodeConfigInputCheck.on('click', function() { if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; } elementNodeConfigInputCheck.text(node._('pushsafer.config_api.requestServer')); elementNodeConfigInputCheckIcon.remove(); let apiKey = $('#node-config-input-apikey').val(); let username = $('#node-config-input-username').val(); $.getJSON('pushsafer/checkConfigApi', { k: apiKey, u: username }) .done(function(result) { if (result.status === 1) { elementNodeConfigInputCheck.text(node._('pushsafer.config_api.checkButtonValid')); elementNodeConfigInputCheck.css({ 'background-color': 'rgba(0,255,0,0.2)' }); elementNodeConfigInputCheck.append('<i id="node-config-input-check-icon" class="fa fa-check"></i>'); } else { elementNodeConfigInputCheck.text(node._('pushsafer.config_api.checkButtonInvalid')); elementNodeConfigInputCheck.css({ 'background-color': 'rgba(255,0,0,0.2)' }); elementNodeConfigInputCheck.append('<i id="node-config-input-check-icon" class="fa fa-exclamation"></i>'); } elementNodeConfigInputCheckIcon = $('#node-config-input-check-icon'); timeoutId = setTimeout(function() { elementNodeConfigInputCheck.text(node._('pushsafer.config_api.checkButtonStandard')); elementNodeConfigInputCheck.css({ 'background-color': '' }); elementNodeConfigInputCheckIcon.remove(); timeoutId = null; }, 5000); }) .fail(function() { RED.notify('Request failed! Please retry.', 'error'); }); }); } }); </script>
47.712963
138
0.542791
e1907041297544139a2c06e541b05534d4f9b98c
39,375
asm
Assembly
Ports/Blackfin/VDSP++/os_cpu_a.asm
Cojayx/uC-OS2
cec4ab5ab6ef77ca7f6ba35b9b9288bf65c0aaf6
[ "Apache-2.0" ]
1
2021-05-04T08:20:25.000Z
2021-05-04T08:20:25.000Z
Ports/Blackfin/VDSP++/os_cpu_a.asm
Cojayx/uC-OS2
cec4ab5ab6ef77ca7f6ba35b9b9288bf65c0aaf6
[ "Apache-2.0" ]
null
null
null
Ports/Blackfin/VDSP++/os_cpu_a.asm
Cojayx/uC-OS2
cec4ab5ab6ef77ca7f6ba35b9b9288bf65c0aaf6
[ "Apache-2.0" ]
null
null
null
/* ********************************************************************************************************* * uC/OS-II * The Real-Time Kernel * * Copyright 1992-2020 Silicon Laboratories Inc. www.silabs.com * * SPDX-License-Identifier: APACHE-2.0 * * This software is subject to an open source license and is distributed by * Silicon Laboratories Inc. pursuant to the terms of the Apache License, * Version 2.0 available at www.apache.org/licenses/LICENSE-2.0. * ********************************************************************************************************* */ /* ********************************************************************************************************* * * uCOS-II port for Analog Device's Blackfin 533 * Visual DSP++ 5.0 * * This port was made with a large contribution from the Analog Devices Inc development team * * Filename : os_cpu_a.asm * Version : V2.93.00 ********************************************************************************************************* */ /* ********************************************************************************************************* * INCLUDE FILES ********************************************************************************************************* */ #include <os_cfg.h> #include <os_cpu.h> /* ********************************************************************************************************* * LOCAL MACROS ********************************************************************************************************* */ #define UPPER_( x ) (((x) >> 16) & 0x0000FFFF) #define LOWER_( x ) ((x) & 0x0000FFFF) #define LOAD(x, y) x##.h = UPPER_(y); x##.l = LOWER_(y) #define LOADA(x, y) x##.h = y; x##.l = y /* ********************************************************************************************************* * PUBLIC FUNCTIONS ********************************************************************************************************* */ .global _OS_CPU_EnableIntEntry; .global _OS_CPU_DisableIntEntry; .global _OS_CPU_SR_Save; .global _OS_CPU_SR_Restore; .global _OS_CPU_NESTING_ISR; .global _OS_CPU_NON_NESTING_ISR; .global _OS_CPU_ISR_Entry; .global _OS_CPU_ISR_Exit; .global _OSStartHighRdy; .global _OSCtxSw; .global _OSIntCtxSw; .global _OS_CPU_Invalid_Task_Return; /* ********************************************************************************************************* * Blackfin C Run-Time stack/frame Macros ********************************************************************************************************* */ #define INIT_C_RUNTIME_STACK(frame_size) \ LINK frame_size; \ SP += -12; /* make space for outgoing arguments */ /* when calling C-functions */ #define DEL_C_RUNTIME_STACK() \ UNLINK; /* ********************************************************************************************************* * WORKAROUND for Anomaly 05-00-0283 Macro ********************************************************************************************************* */ #define WORKAROUND_05000283() \ CC = R0 == R0; /* always true */ \ P0.L = 0x14; /* MMR space - CHIPID */ \ P0.H = 0xffc0; \ IF CC JUMP 4; \ R0 = [ P0 ]; /* bogus MMR read that is speculatively */ /* read and killed - never executed */ /* ********************************************************************************************************* * EXTERNAL FUNCTIONS ********************************************************************************************************* */ .extern _OS_CPU_IntHandler; .extern _OSTaskSwHook; .extern _OSIntEnter; .extern _OSIntExit; /* ********************************************************************************************************* * EXTERNAL VARIABLES ********************************************************************************************************* */ .extern _OSIntNesting; .extern _OSPrioCur; .extern _OSPrioHighRdy; .extern _OSRunning; .extern _OSTCBCur; .extern _OSTCBHighRdy; .section program; /* ********************************************************************************************************* * OS_CPU_EnableIntEntry(); * * Description : Enables an interrupt entry. Interrupt vector to enable is represented by the argument * passed to this function. * * * * Arguments : Interrupt vector number (0 to 15) passed into R0 register * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_EnableIntEntry: R1 = 1; R1 <<= R0; CLI R0; R1 = R1 | R0; STI R1; _OS_CPU_EnableIntEntry.end: RTS; /* ********************************************************************************************************* * OS_CPU_DisableIntEntry(); * * Description : Disables an interrupt entry. Interrupt vector to disable is represented by the argument * passed to this function. * * * * Arguments : Interrupt vector number (0 to 15) passed into R0 register * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_DisableIntEntry: R1 = 1; R1 <<= R0; R1 = ~R1; CLI R0; R1 = R1 & R0; STI R1; _OS_CPU_DisableIntEntry.end: RTS; /* ********************************************************************************************************* * OS_CPU_SR_Save() * * Description : Disables interrupts and save IMASK register into R0. * * * Arguments : None * * Returns : Current IMASK contents in R0 * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_SR_Save: CLI R0; _OS_CPU_SR_Save.end: RTS; /* ********************************************************************************************************* * OS_CPU_SR_Restore() * * * Description : Enables interrupts and load IMASK register with the value passed as an argument to * this routine. * * * Arguments : Value to load into IMASK register. R0 holds this new value. * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_SR_Restore: STI R0; _OS_CPU_SR_Restore.end: RTS; /* ********************************************************************************************************* * NESTING INTERRUPTS HANDLER * OS_CPU_NESTING_ISR(); * * Description : This routine is intented to the target of the interrupt processing functionality with * nesting support. * * It saves the current Task context (see _OS_CPU_ISR_Entry), * and calls the application interrupt handler OS_CPU_IntHandler (see os_cpu_c.c) * * * Arguments : None * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_NESTING_ISR: [ -- SP ] = R0; [ -- SP ] = P1; [ -- SP ] = RETS; R0 = NESTED; /* To indicate that this ISR supports nesting */ CALL.X _OS_CPU_ISR_Entry; WORKAROUND_05000283() INIT_C_RUNTIME_STACK(0x0) CALL.X _OS_CPU_IntHandler; /* See os_cpu_c.c */ SP += -4; /* Disable interrupts by this artificial pop */ RETI = [ SP++ ]; /* of RETI register. Restore context need to */ CALL.X _OSIntExit; /* be done while interrupts are disabled */ DEL_C_RUNTIME_STACK() JUMP.X _OS_CPU_ISR_Exit; _OS_CPU_NESTING_ISR.end: NOP; /* ********************************************************************************************************* * NON NESTING INTERRUPTS HANDLER * OS_CPU_NON_NESTING_ISR(); * * Description : This routine is intented to the target of the interrupt processing functionality without * nesting support. * * It saves the current Task context (see _OS_CPU_ISR_Entry), * and calls the application interrupt handler OS_CPU_IntHandler (see os_cpu_c.c) * * * Arguments : None * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_NON_NESTING_ISR: [ -- SP ] = R0; [ -- SP ] = P1; [ -- SP ] = RETS; R0 = NOT_NESTED; /* This ISR doesn't support nesting */ CALL.X _OS_CPU_ISR_Entry; WORKAROUND_05000283() INIT_C_RUNTIME_STACK(0x0) CALL.X _OS_CPU_IntHandler; /* See os_cpu_c.c */ CALL.X _OSIntExit; DEL_C_RUNTIME_STACK() JUMP.X _OS_CPU_ISR_Exit; _OS_CPU_NON_NESTING_ISR.end: NOP; /* ********************************************************************************************************* * OS_CPU_ISR_Entry() * * Description : This routine serves as the interrupt entry function for ISRs. * * * __OS_CPU_ISR_Entry consists of * * 1.'uCOS Interrupt Entry management' - incremements OSIntNesting and saves SP in the TCB if * OSIntNesting == 1. * 2.'CPU context save' - After OSIntNesting is incremented, it is safe to re-enable interrupts. * Then the rest of the processor's context is saved. * * Refer to VisualDSP++ C/C++ Compiler and Library Manual for Blackfin Processors * and ADSP-BF53x/BF56x Blackfin(R) Processor Programming Reference Manual. * * The convention for the task frame (after context save is complete) is as follows: * (stack represented from high to low memory as per convention) * (*** High memory ***) R0 * P1 * RETS (function return address of thread) * R1 * R2 * P0 * P2 * ASTAT * RETI (interrupt return address: $PC of thread) * R7:3 (R7 is lower than R3) * P5:3 (P5 is lower than P3) * FP (frame pointer) * I3:0 (I3 is lower than I0) * B3:0 (B3 is lower than B0) * L3:0 (L3 is lower than L0) * M3:0 (M3 is lower than M0) * A0.x * A0.w * A1.x * A1.w * LC1:0 (LC1 is lower than LC0) * LT1:0 (LT1 is lower than LT0) * OSTCBHighRdy--> OSTCBStkPtr --> (*** Low memory ***)LB1:0 (LB1 is lower than LB0) * * Arguments : RO is set to NESTED or NOT_NESTED constant. * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_ISR_Entry: ucos_ii_interrupt_entry_mgmt: [ -- SP ] = R1; [ -- SP ] = R2; [ -- SP ] = P0; [ -- SP ] = P2; [ -- SP ] = ASTAT; LOADA(P0 , _OSRunning); R2 = B [ P0 ] ( Z ); CC = R2 == 1; /* Is OSRunning set */ IF ! CC JUMP ucos_ii_interrupt_entry_mgmt.end; LOADA(P0, _OSIntNesting); R2 = B [ P0 ] ( Z ); R1 = 255 ( X ); CC = R2 < R1; /* Nesting < 255 */ IF ! CC JUMP ucos_ii_interrupt_entry_mgmt.end; R2 = R2.B (X); R2 += 1; /* Increment OsIntNesting */ B [ P0 ] = R2; CC = R2 == 1; /* Save SP if OSIntNesting == 1 */ IF ! CC JUMP ucos_ii_interrupt_entry_mgmt.end; LOADA(P2, _OSTCBCur); P0 = [ P2 ]; R2 = SP; R1 = 144; R2 = R2 - R1; [ P0 ] = R2; ucos_ii_interrupt_entry_mgmt.end: NOP; interrupt_cpu_save_context: CC = R0 == NESTED; IF !CC JUMP non_reetrant_isr; reetrant_isr: [ -- SP ] = RETI; /* If ISR is REENTRANT, then simply push RETI onto stack */ /* IPEND[4] is currently set, globally disabling interrupts */ /* IPEND[4] will be cleared when RETI is pushed onto stack */ JUMP save_remaining_context; non_reetrant_isr: R1 = RETI; /* If ISR is NON-REENTRANT, then save RETI through R1 */ [ -- SP ] = R1; /* IPEND[4] is currently set, globally disabling interrupts */ /* IPEND[4] will stay set when RETI is saved through R1 */ save_remaining_context: [ -- SP ] = (R7:3, P5:3); [ -- SP ] = FP; [ -- SP ] = I0; [ -- SP ] = I1; [ -- SP ] = I2; [ -- SP ] = I3; [ -- SP ] = B0; [ -- SP ] = B1; [ -- SP ] = B2; [ -- SP ] = B3; [ -- SP ] = L0; [ -- SP ] = L1; [ -- SP ] = L2; [ -- SP ] = L3; [ -- SP ] = M0; [ -- SP ] = M1; [ -- SP ] = M2; [ -- SP ] = M3; R1.L = A0.x; [ -- SP ] = R1; R1 = A0.w; [ -- SP ] = R1; R1.L = A1.x; [ -- SP ] = R1; R1 = A1.w; [ -- SP ] = R1; [ -- SP ] = LC0; R3 = 0; LC0 = R3; [ -- SP ] = LC1; R3 = 0; LC1 = R3; [ -- SP ] = LT0; [ -- SP ] = LT1; [ -- SP ] = LB0; [ -- SP ] = LB1; L0 = 0 ( X ); L1 = 0 ( X ); L2 = 0 ( X ); L3 = 0 ( X ); interrupt_cpu_save_context.end: _OS_CPU_ISR_Entry.end: RTS; /* ********************************************************************************************************* * OS_CPU_ISR_Exit () * * * Description : ThIS routine serves as the interrupt exit function for all ISRs (whether reentrant * (nested) or non-reentrant (non-nested)). RETI is populated by a stack pop for both nested * as well non-nested interrupts. * * This is a straigtforward implementation restoring the processor's context as per the * following task stack frame convention, returns from the interrupt with the RTI instruction. * * Refer to VisualDSP++ C/C++ Compiler and Library Manual for Blackfin Processors * and ADSP-BF53x/BF56x Blackfin(R) Processor Programming Reference Manual. * * The convention for the task frame (after context save is complete) is as follows: * (stack represented from high to low memory as per convention) * (*** High memory ***) R0 * P1 * RETS (function return address of thread) * R1 * R2 * P0 * P2 * ASTAT * RETI (interrupt return address: $PC of thread) * R7:3 (R7 is lower than R3) * P5:3 (P5 is lower than P3) * FP (frame pointer) * I3:0 (I3 is lower than I0) * B3:0 (B3 is lower than B0) * L3:0 (L3 is lower than L0) * M3:0 (M3 is lower than M0) * A0.x * A0.w * A1.x * A1.w * LC1:0 (LC1 is lower than LC0) * LT1:0 (LT1 is lower than LT0) * OSTCBHighRdy--> OSTCBStkPtr --> (*** Low memory ***)LB1:0 (LB1 is lower than LB0) * * Arguments : None * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_ISR_Exit: interrupt_cpu_restore_context: LB1 = [ SP ++ ]; LB0 = [ SP ++ ]; LT1 = [ SP ++ ]; LT0 = [ SP ++ ]; LC1 = [ SP ++ ]; LC0 = [ SP ++ ]; R0 = [ SP ++ ]; A1 = R0; R0 = [ SP ++ ]; A1.x = R0.L; R0 = [ SP ++ ]; A0 = R0; R0 = [ SP ++ ]; A0.x = R0.L; M3 = [ SP ++ ]; M2 = [ SP ++ ]; M1 = [ SP ++ ]; M0 = [ SP ++ ]; L3 = [ SP ++ ]; L2 = [ SP ++ ]; L1 = [ SP ++ ]; L0 = [ SP ++ ]; B3 = [ SP ++ ]; B2 = [ SP ++ ]; B1 = [ SP ++ ]; B0 = [ SP ++ ]; I3 = [ SP ++ ]; I2 = [ SP ++ ]; I1 = [ SP ++ ]; I0 = [ SP ++ ]; FP = [ SP ++ ]; (R7:3, P5:3) = [ SP ++ ]; RETI = [ SP ++ ]; /* IPEND[4] will stay set when RETI popped from stack */ ASTAT = [ SP ++ ]; P2 = [ SP ++ ]; P0 = [ SP ++ ]; R2 = [ SP ++ ]; R1 = [ SP ++ ]; RETS = [ SP ++ ]; P1 = [ SP ++ ]; interrupt_cpu_restore_context.end: R0 = [ SP ++ ]; RTI; /* Reenable interrupts via IPEND[4] bit after RTI executes. */ NOP; /* Return to task */ NOP; _OS_CPU_ISR_Exit.end: NOP; /* ********************************************************************************************************* * START MULTITASKING * OSStartHighRdy() * * Description: Starts the highest priority task that is available to run.OSStartHighRdy() MUST: * * a) Call OSTaskSwHook() then, * b) Set OSRunning to TRUE, * c) Switch to the highest priority task. * * Refer to VisualDSP++ C/C++ Compiler and Library Manual for Blackfin Processors * and ADSP-BF53x/BF56x Blackfin(R) Processor Programming Reference Manual. * * The convention for the task frame (after context save is complete) is as follows: * (stack represented from high to low memory as per convention) * * (*** High memory ***) R0 * P1 * RETS (function return address of thread) * R1 * R2 * P0 * P2 * ASTAT * RETI (interrupt return address: $PC of thread) * R7:3 (R7 is lower than R3) * P5:3 (P5 is lower than P3) * FP (frame pointer) * I3:0 (I3 is lower than I0) * B3:0 (B3 is lower than B0) * L3:0 (L3 is lower than L0) * M3:0 (M3 is lower than M0) * A0.x * A0.w * A1.x * A1.w * LC1:0 (LC1 is lower than LC0) * LT1:0 (LT1 is lower than LT0) * OSTCBHighRdy--> OSTCBStkPtr --> (*** Low memory ***)LB1:0 (LB1 is lower than LB0) * * Arguments : None * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OSStartHighRdy: #if (OS_TASK_SW_HOOK_EN == 1) /* Do the task switch hook function - don't need to save */ /* RETS since _OSStartHighRdy never returns */ INIT_C_RUNTIME_STACK(0x0) /* Setup C-runtime stack - call OSTaskSwHook() */ CALL.X _OSTaskSwHook; DEL_C_RUNTIME_STACK() /* Tear down C run-time stack - restores SP */ #endif LOADA(P1, _OSTCBHighRdy); /* Get the SP for the highest ready task */ P2 = [ P1 ]; SP = [ P2 ]; LOADA(P1, _OSRunning); /* Set OSRunning to true */ R1 = 1; [ P1 ] = R1; /* Restore CPU context without popping off RETI */ P1 = 140; /* Skipping over LB1:0, LT1:0, LC1:0, A1:0, M3:0, */ SP = SP + P1; /* L3:0, B3:0, I3:0, FP, P5:3, R7:3 */ RETS = [ SP ++ ]; /* Pop off RETI value into RETS */ SP += 12; /* Skipping over ASAT, P2, P0 */ R1 = 0; /* Zap loop counters to zero, to make sure */ LC0 = R1; LC1 = R1; /* that hw loops are disabled */ L0 = R1; L1 = R1; /* Clear the DAG Length regs too, so that it's safe */ L2 = R1; L3 = R1; /* to use I-regs without them wrapping around. */ R2 = [ SP ++ ]; /* Loading the 3rd argument of the C function - R2 */ R1 = [ SP ++ ]; /* Loading the 2nd argument of the C function - R1 */ SP += 8; /* Skipping over RETS, P1 */ R0 = [ SP ++ ]; /* Loading the 1st argument of the C function - R0 */ /* Return to high ready task */ _OSStartHighRdy.end: RTS; /* ********************************************************************************************************* * O/S CPU Context Switch * OSCtxSw() * * Description : This function is called to switch the context of the current running task * This function is registered as the IVG14 handler and will be called to handle both * interrupt and task level context switches. * * Refer to VisualDSP++ C/C++ Compiler and Library Manual for Blackfin Processors * and ADSP-BF53x/BF56x Blackfin(R) Processor Programming Reference Manual. * * The convention for the task frame (after context save is complete) is as follows: * (stack represented from high to low memory as per convention) * (*** High memory ***) R0 * P1 * RETS (function return address of thread) * R1 * R2 * P0 * P2 * ASTAT * RETI (interrupt return address: $PC of thread) * R7:3 (R7 is lower than R3) * P5:3 (P5 is lower than P3) * FP (frame pointer) * I3:0 (I3 is lower than I0) * B3:0 (B3 is lower than B0) * L3:0 (L3 is lower than L0) * M3:0 (M3 is lower than M0) * A0.x * A0.w * A1.x * A1.w * LC1:0 (LC1 is lower than LC0) * LT1:0 (LT1 is lower than LT0) * OSTCBHighRdy--> OSTCBStkPtr --> (*** Low memory ***)LB1:0 (LB1 is lower than LB0) * * Arguments : None * * Returns : None * * Note(s) : Note 1 * * If new priority == current priority, don't do anything. * This condition is triggered by the following sequence of events: * * 1. OS_Sched() is called at a task level and interrupts are disabled. * 2. A HW interrupt happens during the protected section of the task level call to OS_Sched(). * 3. OS_Sched() decides to perform a context switch, updates both OSPrioHighRdy and * OSTCBHighRdy, and issues a trap 14. * 4. OS_Sched() re-enabled interrupts. * 5. The higher priority HW interrupt fires and results in an event that makes the * original task switched out by #3 ready to run again. This results in OSPrioHighRdy * begin set back to OSPrioCur. * 6. The scheduling logic in OSIntExit() decides to do nothing because OSPrioHighRdy * equals OSPrioCur. This means OSTCBHighRdy is now invalid and cannot be used because * it points to the context of the task scheduled in #3. * 7. The trap 14 interrupt fires * 8. If OSPrioHighRdy == OSPrioCur ignore the invalid OSTCBHighRdy and continue running the * task that was originally running upon entering #1. * ********************************************************************************************************* */ _OSCtxSw: /* Save context, interrupts disabled by IPEND[4] bit */ [ -- SP ] = R0; [ -- SP ] = P1; [ -- SP ] = RETS; [ -- SP ] = R1; [ -- SP ] = R2; [ -- SP ] = P0; [ -- SP ] = P2; [ -- SP ] = ASTAT; R1 = RETI; /* IPEND[4] is currently set, globally disabling interrupts */ /* IPEND[4] will stay set when RETI is saved through R1 */ [ -- SP ] = R1; [ -- SP ] = (R7:3, P5:3); [ -- SP ] = FP; [ -- SP ] = I0; [ -- SP ] = I1; [ -- SP ] = I2; [ -- SP ] = I3; [ -- SP ] = B0; [ -- SP ] = B1; [ -- SP ] = B2; [ -- SP ] = B3; [ -- SP ] = L0; [ -- SP ] = L1; [ -- SP ] = L2; [ -- SP ] = L3; [ -- SP ] = M0; [ -- SP ] = M1; [ -- SP ] = M2; [ -- SP ] = M3; R1.L = A0.x; [ -- SP ] = R1; R1 = A0.w; [ -- SP ] = R1; R1.L = A1.x; [ -- SP ] = R1; R1 = A1.w; [ -- SP ] = R1; [ -- SP ] = LC0; R3 = 0; LC0 = R3; [ -- SP ] = LC1; R3 = 0; LC1 = R3; [ -- SP ] = LT0; [ -- SP ] = LT1; [ -- SP ] = LB0; [ -- SP ] = LB1; L0 = 0 ( X ); L1 = 0 ( X ); L2 = 0 ( X ); L3 = 0 ( X ); /* Note: OSCtxSw uses call-preserved registers (R4:7, P3:5) */ /* unlike OSIntCtxSw to allow calling _OSTaskSwHook. */ LOADA(P3, _OSPrioHighRdy); /* Get a high ready task priority */ R4 = B[ P3 ](Z); LOADA(P3, _OSPrioCur); /* Get a current task priority */ R5 = B[ P3 ](Z); CC = R4 == R5; /* If new priority == current priority, don't do anything. */ IF CC JUMP _AbortOSCtxSw; /* See Note 1 */ LOADA(P4, _OSTCBCur); /* Get a pointer to the current task's TCB */ P5 = [ P4 ]; [ P5 ] = SP; /* Context save done so save SP in the TCB */ #if (OS_TASK_SW_HOOK_EN == 1) INIT_C_RUNTIME_STACK(0x0) /* Setup C-runtime stack - call OSTaskSwHook() */ CALL.X _OSTaskSwHook; DEL_C_RUNTIME_STACK() /* Tear down C run-time stack - restores SP */ #endif B[ P3 ] = R4; /* OSPrioCur = OSPrioHighRdy */ LOADA(P3, _OSTCBHighRdy); /* Get a pointer to the high ready task's TCB */ P5 = [ P3 ]; [ P4 ] = P5; /* OSTCBCur = OSTCBHighRdy */ _OSCtxSw_modify_SP: SP = [ P5 ]; /* Make it the current task by switching the stack pointer */ _AbortOSCtxSw: _CtxSwRestoreCtx: _OSCtxSw.end: /* Restoring CPU context and return to task */ LB1 = [ SP ++ ]; LB0 = [ SP ++ ]; LT1 = [ SP ++ ]; LT0 = [ SP ++ ]; LC1 = [ SP ++ ]; LC0 = [ SP ++ ]; R0 = [ SP ++ ]; A1 = R0; R0 = [ SP ++ ]; A1.x = R0.L; R0 = [ SP ++ ]; A0 = R0; R0 = [ SP ++ ]; A0.x = R0.L; M3 = [ SP ++ ]; M2 = [ SP ++ ]; M1 = [ SP ++ ]; M0 = [ SP ++ ]; L3 = [ SP ++ ]; L2 = [ SP ++ ]; L1 = [ SP ++ ]; L0 = [ SP ++ ]; B3 = [ SP ++ ]; B2 = [ SP ++ ]; B1 = [ SP ++ ]; B0 = [ SP ++ ]; I3 = [ SP ++ ]; I2 = [ SP ++ ]; I1 = [ SP ++ ]; I0 = [ SP ++ ]; FP = [ SP ++ ]; (R7:3, P5:3) = [ SP ++ ]; RETI = [ SP ++ ]; /* IPEND[4] will stay set when RETI popped from stack */ ASTAT = [ SP ++ ]; P2 = [ SP ++ ]; P0 = [ SP ++ ]; R2 = [ SP ++ ]; R1 = [ SP ++ ]; RETS = [ SP ++ ]; P1 = [ SP ++ ]; R0 = [ SP ++ ]; RTI; /* Reenable interrupts via IPEND[4] bit after RTI executes. */ /* Return to task */ /* ********************************************************************************************************* * OSIntCtxSw() * * Description : Performs the Context Switch from an ISR. * * OSIntCtxSw() must implement the following pseudo-code: * * OSTaskSwHook(); * OSPrioCur = OSPrioHighRdy; * OSTCBCur = OSTCBHighRdy; * SP = OSTCBHighRdy->OSTCBStkPtr; * * * * Arguments : None * * Returns : None * * Note(s) : OSIntCtxSw uses scratch registers (R0:3, P0:2, ASTAT) * unlike OSCtxSw because it is called from OSIntExit and will * return back to OSIntExit through an RTS. ********************************************************************************************************* */ _OSIntCtxSw: #if (OS_TASK_SW_HOOK_EN == 1) INIT_C_RUNTIME_STACK(0x0) /* Setup C-runtime stack - call OSTaskSwHook() */ CALL.X _OSTaskSwHook; DEL_C_RUNTIME_STACK() /* Tear down C run-time stack - restores SP */ #endif LOADA(P0, _OSPrioCur); /* Get a current task priority */ LOADA(P1, _OSPrioHighRdy); /* Get a high ready task priority */ R0 = B[ P1 ](Z); B[ P0 ] = R0; /* OSPrioCur = OSPrioHighRdy */ LOADA(P0, _OSTCBCur); /* Get a pointer to the current task's TCB */ LOADA(P1, _OSTCBHighRdy); /* Get a pointer to the high ready task's TCB */ P2 = [ P1 ]; [ P0 ] = P2; /* OSTCBCur = OSTCBHighRdy */ _OSIntCtxSw_modify_SP: /* Load stack pointer into P0 from task TCB. Do not modify SP because we return to */ /* OSIntExit, which modifies SP through the the UNLINK instruction. Instead, we */ /* modify the FP of the ISR frame. This essentially 'moves the frame of the ISR */ /* 'above' the frame the of the new task. Thus, when the UNLINK instruction that */ /* unlinks the frame of the ISR, the SP of the new task is loaded. Thus, the new */ /* context is restored. */ R0 = [ P2 ]; /* Get stack pointer to the high ready task */ R0 += -8; /* Subtract 2 stack items for FP, RETS (LINK instruction */ /* pushes FP, RETS onto stack) */ [ FP ] = R0; /* Modify the FP of ISR with the task's SP. */ SP += -4; /* Interrupts are re-enabled when OSIntCtxSw() returns */ RETI = [ SP++ ]; /* to OSIntExit() (where OS_EXIT_CRITICAL() restores */ /* original IMASK value). */ /* However, the context restore process must be */ /* uninterruptible - we accomplish this by an artificial'*/ /* stack pop into the RETI register, thus setting the */ /* global interrupts disable bit (IPEND[4]) */ /* Before the stack pop, adjust the stack pointer. */ _OSIntCtxSw.end: RTS; /* ********************************************************************************************************* * _OS_Invalid_Task_Return () * * Description : All tasks (threads) within uCOS-II are while(1) loops - once done with it's operations, * task can supsend, delete itself etc. to yield the processor. Under NO circumstances can * a task return with a RTS. However, in case of a return, the following function serves * as a placeholder for debugging purposes. * * Arguments : None * * Returns : None * * Note(s) : None ********************************************************************************************************* */ _OS_CPU_Invalid_Task_Return: _OS_CPU_Invalid_Task_Return.end: /* Stay here */ JUMP 0;
41.622622
116
0.341486
2679a9c835b35aa7dd0a1b235e3c4df20469b4f4
44
sql
SQL
setup/run-with-docker/example.sql
marcopeg/amazing-postgres
f3efeb63fc5a9031e52d215c259e576b34506d76
[ "MIT" ]
3
2021-08-19T16:27:47.000Z
2021-08-25T09:42:06.000Z
setup/run-with-docker/example.sql
marcopeg/amazing-postgresql
f3efeb63fc5a9031e52d215c259e576b34506d76
[ "MIT" ]
null
null
null
setup/run-with-docker/example.sql
marcopeg/amazing-postgresql
f3efeb63fc5a9031e52d215c259e576b34506d76
[ "MIT" ]
null
null
null
select now() as "d1"; select now() as "d2";
14.666667
21
0.590909
e718cf9e3f8dd68524c0a30edcabf469881c7791
1,401
js
JavaScript
lib/serviceManager.js
yonathan9669/easyqJS
c1c82696d56495f42e40894df5acba2ab89518a3
[ "MIT" ]
null
null
null
lib/serviceManager.js
yonathan9669/easyqJS
c1c82696d56495f42e40894df5acba2ab89518a3
[ "MIT" ]
null
null
null
lib/serviceManager.js
yonathan9669/easyqJS
c1c82696d56495f42e40894df5acba2ab89518a3
[ "MIT" ]
null
null
null
//Own Modules var Handle = require('./handle'); var Services = function (settings, db) { this.url = settings.url; this.queryHandle = new Handle(db); var self = this; settings.services.forEach(function (service) { if (process.env.VERBOSE) { console.log("//----------------------------------------//"); console.log("Name = " + service.name); console.log("Description = " + service.description); console.log("Service = http://" + self.url + "/" + service.name); } self.queryHandle.add(service.name, { sql: service.sql, params: service.params }); if (process.env.VERBOSE) { console.log("\t\t||----------------------------------------||"); console.log("\t\tRequired Values: "); service.params.forEach(function (value) { console.log("\t\t - Name: " + value.name + "\t\t| Type: " + value.type + "\t\t| Description: " + value.description); }); } }); }; Services.prototype.handleService = function (path, data, callback) { if (!this.queryHandle.execute(this._getService(path), data, callback)) callback(404); }; Services.prototype._getService = function (path) { path = path.split('/'); return path[path.length - 1]; }; module.exports = Services;
31.133333
77
0.514632
264057dbb477e65fa84a8615095e68f9db4b0400
1,679
swift
Swift
SwiftUI-QuickActionsWaterMyPlants/WaterMyPlants/Application/DependencyContainer.swift
luannguyen252/my-swift-journey
788d66f256358dc5aefa2f3093ef74fd572e83b3
[ "MIT" ]
14
2020-12-09T08:53:39.000Z
2021-12-07T09:15:44.000Z
SwiftUI-QuickActionsWaterMyPlants/WaterMyPlants/Application/DependencyContainer.swift
luannguyen252/my-swift-journey
788d66f256358dc5aefa2f3093ef74fd572e83b3
[ "MIT" ]
2
2020-05-08T23:31:44.000Z
2020-05-11T20:45:48.000Z
WaterMyPlants/Application/DependencyContainer.swift
laevandus/WaterMyPlants
edc5f3ed2ecc08805cbbb3ab679cc6df369a1ca1
[ "MIT" ]
8
2020-12-10T05:59:26.000Z
2022-01-03T07:49:21.000Z
// // DependencyContainer.swift // WaterMyPlants // // Created by Toomas Vahter on 12.01.2020. // Copyright © 2020 Augmented Code. All rights reserved. // import CoreData final class DependencyContainer { let persistentContainer: NSPersistentContainer private(set) lazy var connectivityProvider = WatchConnectivityProvider(persistentContainer: persistentContainer) init() { self.persistentContainer = NSPersistentContainer(name: "Plants") } func loadDependencies(withCompletionHandler completionHandler: @escaping () -> Void) { persistentContainer.loadPersistentStores { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } completionHandler() } } }
43.051282
199
0.649196
e78d9a69e4a3c2f56dc8595e03973140678cc5bd
2,025
js
JavaScript
start/routes.js
acidbutter96/flutterapi
be7a331ce7e4d7681d707a9c5c65a3c7829a7c63
[ "MIT" ]
null
null
null
start/routes.js
acidbutter96/flutterapi
be7a331ce7e4d7681d707a9c5c65a3c7829a7c63
[ "MIT" ]
null
null
null
start/routes.js
acidbutter96/flutterapi
be7a331ce7e4d7681d707a9c5c65a3c7829a7c63
[ "MIT" ]
null
null
null
'use strict' const { put } = require('@adonisjs/framework/src/Route/Manager') /* |-------------------------------------------------------------------------- | Routes |-------------------------------------------------------------------------- | | Http routes are entry points to your web application. You can create | routes for different URLs and bind Controller actions to them. | | A complete guide on routing is available here. | http://adonisjs.com/docs/4.1/routing | */ /** @type {typeof import('@adonisjs/framework/src/Route/Manager')} */ const Route = use('Route') // User Route.post('v1/users', 'UserController.create') Route.get('v1/users', 'UserController.index') .middleware('auth') Route.get('v1/users/:id', 'UserController.show') .middleware('auth') Route.put('v1/users/:id', 'UserController.update') .middleware('auth') Route.delete('v1/users/:id', 'UserController.delete') .middleware('auth') // Session Route.post('v1/sessions', 'SessionController.create') Route.get('v1/sessions', 'SessionController.destroy') .middleware('auth') //Content Route.resource('contents', 'ContentController') .apiOnly() .middleware('auth') Route.get('v1/contents/:type?', 'ContentController.index') .middleware('auth') Route.post('v1/contents', 'ContentController.store') .middleware('auth') Route.put('v1/contents/:id', 'ContentController.update') .middleware('auth') Route.delete('v1/contents/:id', 'ImageController.destroy') .middleware('auth') //Content > Images Route.post('v1/contents/:id/images', 'ImageController.store') .middleware('auth') Route.get('v1/contents/images/:filename', 'ImageController.show') .middleware('auth') Route.get('v1/content/image/:id?', 'ContentController.index_img') .middleware('auth') Route.delete('v1/contents/image/:filename', 'ImageController.destroy') .middleware('auth') Route.delete('v1/contents/images/:id', 'ImageController.searchNdestroy') .middleware('auth') Route.put('v1/contents/image/:id', 'ImageController.update') .middleware('auth')
31.640625
75
0.666173
d0dff0482b086f417e7ceadc390643a0bf7e52ee
666
css
CSS
src/components/Clientes/Clientes.css
netinhoteixeira/avaliacao-selecao-desenvolvedor-senior-ui-react
968d18a63a11e1050df6e8bbbf57344c46a7c50c
[ "Unlicense" ]
null
null
null
src/components/Clientes/Clientes.css
netinhoteixeira/avaliacao-selecao-desenvolvedor-senior-ui-react
968d18a63a11e1050df6e8bbbf57344c46a7c50c
[ "Unlicense" ]
null
null
null
src/components/Clientes/Clientes.css
netinhoteixeira/avaliacao-selecao-desenvolvedor-senior-ui-react
968d18a63a11e1050df6e8bbbf57344c46a7c50c
[ "Unlicense" ]
null
null
null
.Clientes { } .Clientes h2 { display: flex; justify-content: space-between; } .Clientes tr td.record-tools { display: flex; justify-content: flex-end; } .Clientes tr td.record-tools button { margin-right: 1em; } .Clientes tr td.record-tools button:last-child { margin-right: 0; } .Clientes tr.info { } .Clientes tr.info td { padding-bottom: 1em; } .Clientes tr.info td .form-label { font-weight: bold; } .Clientes tr.info td .form-control { padding-left: 0; border: none; border-radius: 0; text-align: justify; cursor: default; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
15.488372
48
0.644144
0d1440c5fd6660d80269060cfef8bfddca7b67ef
3,791
swift
Swift
WeChatSwift/Chats/ChatRoom/EmoticonBoard/EmoticonGridCellNode.swift
InHisName/WeChatSwift
3bbd4bf1abc741226aad5b05c333eb6db819bff9
[ "MIT" ]
132
2019-07-15T11:14:28.000Z
2022-02-21T02:56:26.000Z
WeChatSwift/Chats/ChatRoom/EmoticonBoard/EmoticonGridCellNode.swift
InHisName/WeChatSwift
3bbd4bf1abc741226aad5b05c333eb6db819bff9
[ "MIT" ]
6
2019-08-19T09:48:33.000Z
2021-11-03T01:34:20.000Z
WeChatSwift/Chats/ChatRoom/EmoticonBoard/EmoticonGridCellNode.swift
InHisName/WeChatSwift
3bbd4bf1abc741226aad5b05c333eb6db819bff9
[ "MIT" ]
33
2019-08-04T15:16:47.000Z
2022-01-07T07:06:04.000Z
// // EmoticonGridCellNode.swift // WeChatSwift // // Created by xu.shuifeng on 2019/7/17. // Copyright © 2019 alexiscn. All rights reserved. // import AsyncDisplayKit class EmoticonGridCellNode: ASCellNode { var didTapEmoticon: ((_ emoticon: Emoticon) -> Void)? var didTapDeleteButton: (() -> Void)? private var nodes: [EmoticonGridItemNode] = [] private let viewModel: EmoticonViewModel private var cameraEntryNode: EmoticonBoardCameraEntryNode? init(viewModel: EmoticonViewModel, emoticons: [Emoticon]) { self.viewModel = viewModel super.init() let columns = viewModel.layout.columns let insetX = viewModel.layout.marginLeft let insetY = viewModel.layout.marginTop let itemSize = viewModel.layout.itemSize let spacingX = viewModel.layout.spacingX let spacingY = viewModel.layout.spacingY let numberOfPerPage = viewModel.layout.numberOfItemsInPage for index in 0 ..< emoticons.count { let page = index / numberOfPerPage // 当前的页数 let offsetInPage = index - page * numberOfPerPage // 在当前页的索引 let col = CGFloat(offsetInPage % columns) // 在当前页的列数 let row = CGFloat(offsetInPage/columns) // 在当前页的行数 let x = insetX + col * (spacingX + itemSize.width) + CGFloat(page) * Constants.screenWidth let y = insetY + row * (spacingY + itemSize.height) let emoticon = emoticons[index] let node = EmoticonGridItemNode(emoticon: emoticon, itemSize: itemSize) node.style.preferredSize = itemSize node.style.layoutPosition = CGPoint(x: x, y: y) addSubnode(node) nodes.append(node) } if viewModel.type == .cameraEmoticon { let node = EmoticonBoardCameraEntryNode() addSubnode(node) self.cameraEntryNode = node } } override func didLoad() { super.didLoad() addDeleteButtonIfNeeded() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:))) self.view.addGestureRecognizer(tapGesture) } func addDeleteButtonIfNeeded() { guard viewModel.type == .expression else { return } let layout = viewModel.layout let x = layout.marginLeft + CGFloat(layout.columns - 1) * (layout.spacingX + layout.itemSize.width) let y = layout.marginTop + CGFloat(layout.rows - 1) * (layout.spacingY + layout.itemSize.height) let deleteButton = UIButton(type: .custom) deleteButton.addTarget(self, action: #selector(deleteEmoticonButtonClicked), for: .touchUpInside) deleteButton.setImage(UIImage(named: "DeleteEmoticonBtn_32x32_"), for: .normal) deleteButton.frame = CGRect(origin: CGPoint(x: x, y: y), size: layout.itemSize) deleteButton.contentEdgeInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2) self.view.addSubview(deleteButton) } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { if let cameraNode = cameraEntryNode { return ASInsetLayoutSpec(insets: .zero, child: cameraNode) } return ASAbsoluteLayoutSpec(children: nodes) } } // MARK: - Event Handlers extension EmoticonGridCellNode { @objc private func deleteEmoticonButtonClicked() { didTapDeleteButton?() } @objc private func handleTapGesture(_ gesture: UITapGestureRecognizer) { let point = gesture.location(in: self.view) if let node = nodes.first(where: { $0.frame.contains(point) }) { didTapEmoticon?(node.emoticon) } } }
36.805825
107
0.639145
1945bc7d6b07cfec4677d793b434120da56b119e
1,112
kt
Kotlin
src/main/kotlin/Main.kt
smartsleep/activity
c2e814d9d46757bbd0a0ea59558bad7f91513c6f
[ "MIT" ]
null
null
null
src/main/kotlin/Main.kt
smartsleep/activity
c2e814d9d46757bbd0a0ea59558bad7f91513c6f
[ "MIT" ]
null
null
null
src/main/kotlin/Main.kt
smartsleep/activity
c2e814d9d46757bbd0a0ea59558bad7f91513c6f
[ "MIT" ]
1
2019-11-21T15:51:52.000Z
2019-11-21T15:51:52.000Z
import dk.ku.sund.handler.* import io.javalin.Javalin import io.javalin.apibuilder.ApiBuilder.* import org.slf4j.LoggerFactory fun main(args: Array<String>) { val logger = LoggerFactory.getLogger("MainKt") val restHandler = RestHandler() val sleepHandler = SleepHandler() val attendeeHandler = AttendeeHandler() val app = Javalin.create() app.requestLogger { ctx, timeMs -> logger.info("${ctx.method()} ${ctx.path()} took $timeMs ms") } app.before("/*") { ctx -> authorized(ctx) } app.before("/*") { ctx -> ctx.header("Content-Type", "Content-Type: application/json; charset=utf-8") } app.routes { get("/") { ctx -> ctx .header("Content-Type", "Content-Type: text/plain; charset=utf-8") .result("Nothing to see here") } crud("/activity/:id", ActivityHandler()) get("/rest", restHandler::getAll) get("/sleep", sleepHandler::getAll) post("/sleep", sleepHandler::create) post("/sleep/bulk", sleepHandler::createBulk) put("/attendee", attendeeHandler::update) } app.start(7000) }
34.75
107
0.627698
a111cd10d3d0a4f5ac48e603e2e0532131bc0bb4
10,149
go
Go
x/issuer/keeper/msg_server.go
allinbits/cosmos-cash
4af9df08f74ebc85375dc621d14ec48f926b6d13
[ "Apache-2.0" ]
29
2021-01-20T19:35:12.000Z
2022-02-17T05:46:43.000Z
x/issuer/keeper/msg_server.go
allinbits/cosmos-cash
4af9df08f74ebc85375dc621d14ec48f926b6d13
[ "Apache-2.0" ]
204
2021-03-01T11:28:15.000Z
2022-03-24T02:09:55.000Z
x/issuer/keeper/msg_server.go
allinbits/cosmos-cash
4af9df08f74ebc85375dc621d14ec48f926b6d13
[ "Apache-2.0" ]
8
2021-03-22T05:02:40.000Z
2022-03-29T03:59:57.000Z
package keeper import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" didtypes "github.com/allinbits/cosmos-cash/x/did/types" "github.com/allinbits/cosmos-cash/x/issuer/types" vctypes "github.com/allinbits/cosmos-cash/x/verifiable-credential/types" ) type msgServer struct { Keeper } // NewMsgServerImpl returns an implementation of the MsgServer interface // for the provided Keeper. func NewMsgServerImpl(keeper Keeper) types.MsgServer { return &msgServer{Keeper: keeper} } var _ types.MsgServer = msgServer{} // CreateIssuer creates a new e-money token issuer func (k msgServer) CreateIssuer( goCtx context.Context, msg *types.MsgCreateIssuer, ) (*types.MsgCreateIssuerResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // Check to see if the provided verifiable credential is in the store vc, found := k.Keeper.vcKeeper.GetVerifiableCredential(ctx, []byte(msg.LicenseCredId)) if !found { return nil, sdkerrors.Wrapf( types.ErrLicenseCredentialNotFound, "verifiable credential not found", ) } // Validate the provided issuer credential err := k.validateIssuerCredential(ctx, msg.IssuerDid, vc, msg.Owner) if err != nil { return nil, err } _, found = k.Keeper.GetIssuer(ctx, []byte(msg.IssuerDid)) if found { return nil, sdkerrors.Wrapf( types.ErrIssuerFound, "issuer already exists", ) } _, found = k.Keeper.GetIssuerByToken(ctx, []byte(msg.Token)) if found { return nil, sdkerrors.Wrapf( types.ErrTokenAlreadyExists, "token denom already exists", ) } issuer := types.Issuer{ Token: msg.Token, Fee: msg.Fee, IssuerDid: msg.IssuerDid, Paused: false, } k.Keeper.SetIssuer(ctx, issuer) ctx.EventManager().EmitEvent( types.NewIssuerCreatedEvent(msg.Owner, msg.Token), ) return &types.MsgCreateIssuerResponse{}, nil } // BurnToken burns a token for an e-money issuer func (k msgServer) BurnToken( goCtx context.Context, msg *types.MsgBurnToken, ) (*types.MsgBurnTokenResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // Check to see if the provided verifiable credential is in the store vc, found := k.Keeper.vcKeeper.GetVerifiableCredential(ctx, []byte(msg.LicenseCredId)) if !found { return nil, sdkerrors.Wrapf( types.ErrLicenseCredentialNotFound, "verifiable credential not found", ) } // Validate the provided issuer credential err := k.validateIssuerCredential(ctx, msg.IssuerDid, vc, msg.Owner) if err != nil { return nil, err } issuer, found := k.Keeper.GetIssuer(ctx, []byte(msg.IssuerDid)) if !found { return nil, sdkerrors.Wrapf( types.ErrIssuerFound, "issuer does not exists", ) } // parse the token amount and verify that the amount requested is for the issuer token amounts, err := sdk.ParseCoinsNormalized(msg.Amount) if err != nil { return nil, sdkerrors.Wrapf( sdk.ErrInvalidDecimalStr, "coin string format not recognized", ) } for _, a := range amounts { if a.GetDenom() != issuer.Token { return nil, sdkerrors.Wrapf( types.ErrInvalidIssuerDenom, "issuer can only burn tokens of %s (requested %s)", issuer.Token, a.GetDenom(), ) } } // sender is the issuer sender, _ := sdk.AccAddressFromBech32(msg.Owner) if err := k.bk.SendCoinsFromAccountToModule( ctx, sender, types.ModuleName, amounts, ); err != nil { return nil, sdkerrors.Wrapf( types.ErrBurningTokens, "cannot send tokens from issuer account to module", ) } if err := k.bk.BurnCoins( ctx, types.ModuleName, amounts, ); err != nil { return nil, sdkerrors.Wrapf( types.ErrBurningTokens, "cannot burn coins", ) } ctx.EventManager().EmitEvent( types.NewTokenBurnedEvent(msg.Owner, issuer.Token, string(msg.Amount)), ) return &types.MsgBurnTokenResponse{}, nil } // MintToken mints a token for an e-money issuer func (k msgServer) MintToken( goCtx context.Context, msg *types.MsgMintToken, ) (*types.MsgMintTokenResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // Check to see if the provided verifiable credential is in the store vc, found := k.Keeper.vcKeeper.GetVerifiableCredential(ctx, []byte(msg.LicenseCredId)) if !found { return nil, sdkerrors.Wrapf( types.ErrLicenseCredentialNotFound, "verifiable credential not found", ) } // Validate the provided issuer credential err := k.validateIssuerCredential(ctx, msg.IssuerDid, vc, msg.Owner) if err != nil { return nil, err } issuer, found := k.Keeper.GetIssuer(ctx, []byte(msg.IssuerDid)) if !found { return nil, sdkerrors.Wrapf( types.ErrIssuerFound, "issuer does not exists", ) } // parse the token amount and verify that the amount requested is for the issuer token amounts, err := sdk.ParseCoinsNormalized(msg.Amount) if err != nil { return nil, sdkerrors.Wrapf( sdk.ErrInvalidDecimalStr, "coin string format not recognized", ) } for _, a := range amounts { if a.GetDenom() != issuer.Token { return nil, sdkerrors.Wrapf( types.ErrInvalidIssuerDenom, "issuer can only issue tokens of %s (requested %s)", issuer.Token, a.GetDenom(), ) } // Validate the minting amount is in range err := k.validateMintingAmount(ctx, vc, a) if err != nil { return nil, err } } // the recipient is the signer of the message recipient, _ := sdk.AccAddressFromBech32(msg.Owner) if err := k.bk.MintCoins( ctx, types.ModuleName, amounts, ); err != nil { return nil, sdkerrors.Wrapf( types.ErrMintingTokens, "cannot mint coins", ) } if err := k.bk.SendCoinsFromModuleToAccount( ctx, types.ModuleName, recipient, amounts, ); err != nil { return nil, sdkerrors.Wrapf( types.ErrMintingTokens, "failed sending tokens from module to issuer", ) } ctx.EventManager().EmitEvent( types.NewTokenMintedEvent(msg.Owner, issuer.Token, string(msg.Amount)), ) return &types.MsgMintTokenResponse{}, nil } // PauseToken pauses a token for an issuer func (k msgServer) PauseToken( goCtx context.Context, msg *types.MsgPauseToken, ) (*types.MsgPauseTokenResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // Check to see if the provided verifiable credential is in the store vc, found := k.Keeper.vcKeeper.GetVerifiableCredential(ctx, []byte(msg.LicenseCredId)) if !found { return nil, sdkerrors.Wrapf( types.ErrLicenseCredentialNotFound, "verifiable credential not found", ) } // Validate the provided issuer credential err := k.validateIssuerCredential(ctx, msg.IssuerDid, vc, msg.Owner) if err != nil { return nil, err } issuer, found := k.Keeper.GetIssuer(ctx, []byte(msg.IssuerDid)) if !found { return nil, sdkerrors.Wrapf( types.ErrIssuerFound, "issuer does not exists", ) } issuer.Paused = !issuer.Paused k.Keeper.SetIssuer(ctx, issuer) ctx.EventManager().EmitEvent( types.NewTokenPausedEvent(msg.Owner, issuer.Token), ) return &types.MsgPauseTokenResponse{}, nil } // validateIssuerCredential validate the signer of the message is part of the issuer did and the provided credential func (k msgServer) validateIssuerCredential( ctx sdk.Context, issuerDid string, licenseCred vctypes.VerifiableCredential, signer string, ) error { // Check to see if the provided did is in the store did, _, err := k.Keeper.didKeeper.ResolveDid(ctx, didtypes.DID(issuerDid)) if err != nil { return sdkerrors.Wrapf( types.ErrDidDocumentDoesNotExist, "did does not exists", ) } // Check to see if the msg signer has a verification relationship in the did document if !did.HasRelationship(didtypes.NewBlockchainAccountID(ctx.ChainID(), signer), didtypes.Authentication) { return sdkerrors.Wrapf( types.ErrIncorrectControllerOfDidDocument, "msg sender not in auth array in did document", ) } // Validate the credential subject ID the same as the provided did document // TODO: dig deeper into the license type issuerCred := licenseCred.GetLicenseCred() if issuerCred.Id != did.Id { return sdkerrors.Wrapf( types.ErrIncorrectLicenseCredential, "issuer id not correct", ) } return nil } // validateMintingAmount validates the amount being minted is correct func (k msgServer) validateMintingAmount( ctx sdk.Context, licenseCred vctypes.VerifiableCredential, mintingAmount sdk.Coin, ) error { // Get the supply from the bank keeper supply := k.bk.GetSupply(ctx, mintingAmount.Denom) // Calculate the reserve by subtraction the supply from the issuer credential circulation limit reserve := licenseCred.GetLicenseCred().CirculationLimit.Amount.Sub(supply.Amount) // Validate the reserve is greater that the amount being minted if reserve.LT(mintingAmount.Amount) { return sdkerrors.Wrapf( types.ErrMintingTokens, "issuer cannot mint more than the circulation limit defined in their credential", ) } return nil } // IssueUserCredential activates a regulator func (k msgServer) IssueUserCredential( goCtx context.Context, msg *types.MsgIssueUserCredential, ) (*types.MsgIssueUserCredentialResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) k.Logger(ctx).Info("issue user credential request", "credential", msg.Credential, "address", msg.Owner) // check that the issuer is a holder of LicenseCredential // TODO: need to go a bit deeper about the type of the license vcs := k.vcKeeper.GetVerifiableCredentialWithType(ctx, msg.Credential.GetIssuer(), vctypes.LicenseCredential) if len(vcs) != 1 { // there must be exactly one err := sdkerrors.Wrapf(types.ErrLicenseCredentialNotFound, "credential issuer is not a licensed e-money issuer") k.Logger(ctx).Error(err.Error()) return nil, err } // store the credentials if vcErr := k.vcKeeper.SetVerifiableCredential(ctx, []byte(msg.Credential.Id), *msg.Credential); vcErr != nil { err := sdkerrors.Wrapf(vcErr, "credential proof cannot be verified") k.Logger(ctx).Error(err.Error()) return nil, err } k.Logger(ctx).Info("issue user credential request successful", "credentialID", msg.Credential.Id) ctx.EventManager().EmitEvent( vctypes.NewCredentialCreatedEvent(msg.Owner, msg.Credential.Id), ) return &types.MsgIssueUserCredentialResponse{}, nil }
27.42973
116
0.729234
b2c9fa26df1819fd78986e0d91479f1228f910e7
53
rs
Rust
build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/fill/JRSubreportRunnable.rs
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/fill/JRSubreportRunnable.rs
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/fill/JRSubreportRunnable.rs
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
net.sf.jasperreports.engine.fill.JRSubreportRunnable
26.5
52
0.886792
855d19978d2eff52d15045de74e07d13ad1573be
1,414
js
JavaScript
packages/wizzi-starter-formik/app/src/components/fields/SliderField.js
stfnbssl/wizzi-examples
6817c499a67ea75bccac793e87968cbb1ba1752c
[ "MIT" ]
null
null
null
packages/wizzi-starter-formik/app/src/components/fields/SliderField.js
stfnbssl/wizzi-examples
6817c499a67ea75bccac793e87968cbb1ba1752c
[ "MIT" ]
19
2021-03-09T08:47:41.000Z
2022-02-27T06:26:11.000Z
packages/wizzi-starter-formik/app/src/components/fields/SliderField.js
stfnbssl/wizzi-examples
6817c499a67ea75bccac793e87968cbb1ba1752c
[ "MIT" ]
1
2020-12-26T14:36:17.000Z
2020-12-26T14:36:17.000Z
/* artifact generator: C:\My\wizzi\wizzi-examples\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js primary source IttfDocument: C:\My\wizzi\wizzi-examples\packages\formik\.wizzi\src\components\fields\SliderField.js.ittf */ 'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Slider from '@material-ui/lab/Slider'; class SliderField extends React.Component { handleChange = (event, value) => { const { fkFieldProp, setFieldValue } = this.props; console.log('Slider.handleChange', event, value, setFieldValue); setFieldValue(fkFieldProp.name, value); } handleBlur = () => { const { fkFieldProp, setFieldTouched } = this.props; setFieldTouched(fkFieldProp.name); } render() { const { fkFieldProp, localProps } = this.props; const { disabled, accessForbidden, ...optional } = localProps; const _disabled = accessForbidden || disabled; return ( <Slider id={ fkFieldProp.name } onChange={this.handleChange} onDragEnd={this.handleBlur} value={fkFieldProp.value} disabled={_disabled} {...optional}> </Slider> ) ; } } export default SliderField;
31.422222
166
0.598303
7740a0adbcf76ca43fb285cf4e0fcbc14512f3f9
3,537
swift
Swift
mCardsContainer/Classes/CardsMenuLayout.swift
Swift-Gurus/mCardsContainer
f64c110f49902493bd0b431ea0e0df6c59408c4d
[ "MIT" ]
null
null
null
mCardsContainer/Classes/CardsMenuLayout.swift
Swift-Gurus/mCardsContainer
f64c110f49902493bd0b431ea0e0df6c59408c4d
[ "MIT" ]
null
null
null
mCardsContainer/Classes/CardsMenuLayout.swift
Swift-Gurus/mCardsContainer
f64c110f49902493bd0b431ea0e0df6c59408c4d
[ "MIT" ]
null
null
null
// // CardsMenuLayout.swift // mCardsContainer // // Created by Alex Hmelevski on 2019-09-04. // import Foundation public struct CardsMenuLayoutConfig { public let menuContainerKind: String let cardsLayoutConfig: LayoutConfig public init(kind: String = "CardsMenuKind", cardsLayoutConfig: LayoutConfig) { self.menuContainerKind = kind self.cardsLayoutConfig = cardsLayoutConfig } } public final class CardsMenuLayout: CardsHorizontalLayout { private let config: CardsMenuLayoutConfig private var menuAttributes: UICollectionViewLayoutAttributes private var menuState: Bool = false public init(config: CardsMenuLayoutConfig) { self.config = config menuAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: config.menuContainerKind, with: IndexPath(row: 0, section: 0)) super.init(config: config.cardsLayoutConfig) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var stopPoint: CGPoint = { guard let attributes = cachedAttributes.first else { return .zero } return CGPoint(x: attributes.frame.origin.x - basicOffset, y: 0) }() public override func prepare() { let height = _collectionView.bounds.size.height menuAttributes.frame = CGRect(x: 0, y: 0, width: itemWidth, height: height) super.prepare() _collectionView.setContentOffset(stopPoint, animated: false) } override func getXCoordinates(using itemWidth: CGFloat, cvWidth: CGFloat, index: Int) -> CGFloat { let superX = super.getXCoordinates(using: itemWidth, cvWidth: cvWidth, index: index) return superX + self.itemWidth } public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes = super.layoutAttributesForElements(in: rect) ?? [] if menuAttributes.frame.intersects(rect) { attributes.append(menuAttributes) } return attributes } public override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return menuAttributes } public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { if currentItemIndex == 0 && velocity.x < 0 { menuState = true return menuAttributes.frame.origin } if currentItemIndex == 0 && velocity.x > 0 && menuState { menuState = false let frame = cachedAttributes[currentItemIndex].frame let newSuggestedOffset = CGPoint(x: frame.origin.x - basicOffset, y: proposedContentOffset.y) return newSuggestedOffset } return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) } }
36.463918
153
0.599943
91c80bf1b58e4e46b7bae16cd273a8ff363c8f19
380
kt
Kotlin
src/main/kotlin/interface/Contrato.kt
rafamaneschy/atividadesDH
0d0e60f7f2b19511cabe9202d0fa872d4d3d0c80
[ "MIT" ]
null
null
null
src/main/kotlin/interface/Contrato.kt
rafamaneschy/atividadesDH
0d0e60f7f2b19511cabe9202d0fa872d4d3d0c80
[ "MIT" ]
null
null
null
src/main/kotlin/interface/Contrato.kt
rafamaneschy/atividadesDH
0d0e60f7f2b19511cabe9202d0fa872d4d3d0c80
[ "MIT" ]
null
null
null
package `interface` class Contrato(var numeroContrato: Int): Imprimivel { override var nome: String = "CONTRATO DE TRABALHO" override var tipoDeDocumento: String = "CONTRATO" override fun imprimir() { println("""================$nome======================= | |$tipoDeDocumento Nº: $numeroContrato""".trimMargin()) } }
22.352941
70
0.55
38a5534847ca26fd9af8d17c22625813ff67b2bc
10,861
h
C
NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/tcharm/tcharm_impl.h
scottkwarren/config-db
fb5c3da2465e5cff0ad30950493b11d452bd686b
[ "MIT" ]
1
2019-01-17T20:07:23.000Z
2019-01-17T20:07:23.000Z
NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/tcharm/tcharm_impl.h
scottkwarren/config-db
fb5c3da2465e5cff0ad30950493b11d452bd686b
[ "MIT" ]
null
null
null
NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/tcharm/tcharm_impl.h
scottkwarren/config-db
fb5c3da2465e5cff0ad30950493b11d452bd686b
[ "MIT" ]
null
null
null
/* Threaded Charm++ "Framework Framework" Implementation header Implements an array of migratable threads. Provides utility routines for registering user data, stopping, starting, and migrating threads. Orion Sky Lawlor, [email protected], 11/19/2001 */ #ifndef __CHARM_TCHARM_IMPL_H #define __CHARM_TCHARM_IMPL_H #include "pup.h" #include "pup_c.h" #include "charm-api.h" #include "tcharmc.h" #include "cklists.h" #include "memory-isomalloc.h" #include "cmitls.h" class TCharmTraceLibList; /// Used to ship around system calls. class callSystemStruct { public: const char *cmd; ///< Shell command to execute. int *ret; ///< Place to store command's return value. }; PUPbytes(callSystemStruct) #include "tcharm.decl.h" class TCharm; // This little class holds values between a call to TCHARM_Set_* // and the subsequent TCHARM_Create_*. It should be moved // into a parameter to TCHARM_Create. class TCHARM_Thread_options { public: int stackSize; /* size of thread execution stack, in bytes */ int exitWhenDone; /* flag: call CkExit when thread is finished. */ // Fill out the default thread options: TCHARM_Thread_options(int doDefault); TCHARM_Thread_options() {} void sanityCheck(void); }; class TCharmInitMsg : public CMessage_TCharmInitMsg { public: //Function to start thread with: //CthVoidFn threadFn; int threadFn; //Initial thread parameters: TCHARM_Thread_options opts; //Array size (number of elements) int numElements; //Data to pass to thread: char *data; TCharmInitMsg(int threadFn_,const TCHARM_Thread_options &opts_) :threadFn(threadFn_), opts(opts_) {} }; //Thread-local variables: CtvExtern(TCharm *,_curTCharm); class TCharm: public CBase_TCharm { public: //User's heap-allocated/global data: class UserData { // void *data; //user data pointer CthThread t; size_t pos; char mode; TCHARM_Pup_fn cfn; TCHARM_Pup_global_fn gfn; public: UserData(int i=0) {pos=0; mode='?'; cfn=NULL; gfn=NULL;} UserData(TCHARM_Pup_fn cfn_,CthThread t_,void *p) {cfn=cfn_; t=t_; pos=CthStackOffset(t, (char *)p); mode='c';} UserData(TCHARM_Pup_global_fn gfn_,CthThread t_,void *p) {gfn=gfn_; t=t_; pos=CthStackOffset(t, (char *)p); mode='g';} inline void *getData(void) const {return pos==0?NULL:CthPointer(t, pos);} void pup(PUP::er &p); void update(CthThread t_) { t=t_; } friend inline void operator|(PUP::er &p,UserData &d) {d.pup(p);} }; //New interface for user data: CkVec<UserData> sud; //Tiny semaphore-like pointer producer/consumer class TCharmSemaphore { public: int id; //User-defined identifier void *data; //User-defined data CthThread thread; //Waiting thread, or 0 if none TCharmSemaphore() { id=-1; data=NULL; thread=NULL; } TCharmSemaphore(int id_) { id=id_; data=NULL; thread=NULL; } }; /// Short, unordered list of waiting semaphores. CkVec<TCharmSemaphore> sema; TCharmSemaphore *findSema(int id); TCharmSemaphore *getSema(int id); void freeSema(TCharmSemaphore *); /// Store data at the semaphore "id". /// The put can come before or after the get. void semaPut(int id,void *data); /// Retreive data from the semaphore "id", returning NULL if not there. void *semaPeek(int id); /// Retreive data from the semaphore "id". /// Blocks if the data is not immediately available. void *semaGets(int id); /// Retreive data from the semaphore "id". /// Blocks if the data is not immediately available. /// Consumes the data, so another put will be required for the next get. void *semaGet(int id); //One-time initialization static void nodeInit(void); static void procInit(void); private: //Informational data about the current thread: class ThreadInfo { public: CProxy_TCharm tProxy; //Our proxy int thisElement; //Index of current element int numElements; //Number of array elements }; TCharmInitMsg *initMsg; //Thread initialization data CthThread tid; //Our migratable thread friend class TCharmAPIRoutine; //So he can get to heapBlocks: CmiIsomallocBlockList *heapBlocks; //Migratable heap data CtgGlobals threadGlobals; //Global data void pupThread(PUP::er &p); //isSelfDone is added for out-of-core emulation in BigSim //when thread is brought back into core, ResumeFromSync is called //so if the thread has finished its stuff, it should not start again bool isStopped, resumeAfterMigration, exitWhenDone, isSelfDone, skipResume; ThreadInfo threadInfo; double timeOffset; //Value to add to CkWallTimer to get my clock //Old interface for user data: enum {maxUserData=16}; int nUd; UserData ud[maxUserData]; void ResumeFromSync(void); public: TCharm(TCharmInitMsg *initMsg); TCharm(CkMigrateMessage *); ~TCharm(); virtual void ckJustMigrated(void); virtual void ckJustRestored(void); virtual void ckAboutToMigrate(void); void migrateDelayed(int destPE); void atBarrier(CkReductionMsg *); void atExit(CkReductionMsg *); void clear(); //Pup routine packs the user data and migrates the thread virtual void pup(PUP::er &p); //Start running the thread for the first time void run(void); inline double getTimeOffset(void) const { return timeOffset; } //Client-callable routines: //Sleep till entire array is here void barrier(void); //Block, migrate to destPE, and resume void migrateTo(int destPE); void evacuate(); //Thread finished running void done(void); //Register user data to be packed with the thread int add(const UserData &d); void *lookupUserData(int ud); inline static TCharm *get(void) { TCharm *c=getNULL(); #if CMK_ERROR_CHECKING if (!c) ::CkAbort("TCharm has not been initialized!\n"); #endif return c; } inline static TCharm *getNULL(void) {return CtvAccess(_curTCharm);} inline CthThread getThread(void) {return tid;} inline const CProxy_TCharm &getProxy(void) const {return threadInfo.tProxy;} inline int getElement(void) const {return threadInfo.thisElement;} inline int getNumElements(void) const {return threadInfo.numElements;} //Start/stop load balancer measurements inline void stopTiming(void) {ckStopTiming();} inline void startTiming(void) {ckStartTiming();} //Block our thread, run the scheduler, and come back void schedule(void); //As above, but start/stop the thread itself, too. void stop(void); //Blocks; will not return until "start" called. void start(void); //Aliases: inline void suspend(void) {stop();} inline void resume(void) { //printf("in thcarm::resume, isStopped=%d\n", isStopped); if (isStopped){ start(); } else { //printf("[%d] TCharm resume called on already running thread pe %d \n",thisIndex,CkMyPe()); } } //Go to sync, block, possibly migrate, and then resume void migrate(void); void async_migrate(void); void allow_migrate(void); //Entering thread context: turn stuff on static void activateThread(void) { TCharm *tc=CtvAccess(_curTCharm); if (tc!=NULL) { if (tc->heapBlocks) CmiIsomallocBlockListActivate(tc->heapBlocks); if (tc->threadGlobals) CtgInstall(tc->threadGlobals); } } //Leaving this thread's context: turn stuff back off static void deactivateThread(void) { CmiIsomallocBlockListActivate(NULL); CtgInstall(NULL); } static void activateVariable(const void *ptr) { TCharm *tc=CtvAccess(_curTCharm); if (tc!=NULL) { if (tc->threadGlobals) CtgInstall_var(tc->threadGlobals, (char *)ptr); } } static void deactivateVariable(const void *ptr) { TCharm *tc=CtvAccess(_curTCharm); if (tc!=NULL) { if (tc->threadGlobals) CtgUninstall_var(tc->threadGlobals, (char *)ptr); } } /// System() call emulation: int system(const char *cmd); void callSystem(const callSystemStruct &s); inline CthThread getTid() { return tid; } }; void TCHARM_Api_trace(const char *routineName, const char *libraryName); // Created in all API routines: // - Disables/enables migratable malloc // - Traces library code entry/exit with appropriate build flags class TCharmAPIRoutine { int state; //stores if the isomallocblockactivate and ctginstall need to be skipped during activation CtgGlobals oldGlobals; // this is actually a pointer tlsseg_t oldtlsseg; // for TLS globals bool actLikeMainThread; // Whether memory allocation and globals should switch away from the application thread #ifdef CMK_BIGSIM_CHARM void *callEvent; // The BigSim-level event that called into the library int pe; // in case thread migrates #endif public: // Entering Charm++ from user code TCharmAPIRoutine(const char *routineName, const char *libraryName, bool actLikeMainThread_ = true) : actLikeMainThread(actLikeMainThread_) { #ifdef CMK_BIGSIM_CHARM // Start a new event, so we can distinguish between client // execution and library execution _TRACE_BG_TLINE_END(&callEvent); _TRACE_BG_END_EXECUTE(0); pe = CmiMyPe(); _TRACE_BG_BEGIN_EXECUTE_NOMSG(routineName, &callEvent, 0); #endif if (actLikeMainThread) { state = 0; //TCharm *tc=CtvAccess(_curTCharm); // if memory is not isomalloc (swap global not installed) // or thread has already been deactivated if(CmiIsomallocBlockListCurrent() == NULL){ state |= 0x1; //skip CmiIsomallocBlockListActivate } if(CtgCurrentGlobals() == NULL){ state |= 0x10; // skip CtgInstall } if (CmiThreadIs(CMI_THREAD_IS_TLS)) { CtgInstallTLS(&oldtlsseg, NULL); //switch to main thread } //Disable migratable memory allocation while in Charm++: TCharm::deactivateThread(); } #if CMK_TRACE_ENABLED TCHARM_Api_trace(routineName,libraryName); #endif } // Returning to user code from Charm++ ~TCharmAPIRoutine() { if (actLikeMainThread) { CmiIsomallocBlockList *oldHeapBlock; TCharm *tc=CtvAccess(_curTCharm); if(tc != NULL){ if(state & 0x1){ oldHeapBlock = tc->heapBlocks; tc->heapBlocks = NULL; } if(state & 0x10){ oldGlobals = tc->threadGlobals; tc->threadGlobals = NULL; } } //Reenable migratable memory allocation TCharm::activateThread(); if(tc != NULL){ if(state & 0x1){ tc->heapBlocks = oldHeapBlock; } if(state & 0x10){ tc->threadGlobals = oldGlobals; } } if (CmiThreadIs(CMI_THREAD_IS_TLS)) { tlsseg_t cur; CtgInstallTLS(&cur, &oldtlsseg); } } #ifdef CMK_BIGSIM_CHARM void *log; _TRACE_BG_TLINE_END(&log); _TRACE_BG_END_EXECUTE(0); _TRACE_BG_BEGIN_EXECUTE_NOMSG("user_code", &log, 0); if (CmiMyPe() == pe) _TRACE_BG_ADD_BACKWARD_DEP(callEvent); #endif } }; #define TCHARMAPI(routineName) TCHARM_API_TRACE(routineName,"tcharm"); //Node setup callbacks: called at startup on each node FDECL void FTN_NAME(TCHARM_USER_NODE_SETUP,tcharm_user_node_setup)(void); FDECL void FTN_NAME(TCHARM_USER_SETUP,tcharm_user_setup)(void); #endif
28.581579
112
0.717613
f7e9a9b08517c3b14fb2705c904f3abed9341ce4
931
sql
SQL
backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/ddl/public/functions/getCostPrice.sql
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
1,144
2016-02-14T10:29:35.000Z
2022-03-30T09:50:41.000Z
backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/ddl/public/functions/getCostPrice.sql
vestigegroup/metasfresh
4b2d48c091fb2a73e6f186260a06c715f5e2fe96
[ "RSA-MD" ]
8,283
2016-04-28T17:41:34.000Z
2022-03-30T13:30:12.000Z
backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/ddl/public/functions/getCostPrice.sql
vestigegroup/metasfresh
4b2d48c091fb2a73e6f186260a06c715f5e2fe96
[ "RSA-MD" ]
441
2016-04-29T08:06:07.000Z
2022-03-28T06:09:56.000Z
-- DROP FUNCTION getCostPrice(numeric, numeric, numeric); CREATE OR REPLACE FUNCTION getCostPrice ( p_M_Product_ID numeric, p_AD_Client_ID numeric, p_AD_Org_ID numeric ) RETURNS numeric AS $BODY$ SELECT COALESCE(sum(cost.CurrentCostPrice), 0) FROM M_Cost cost INNER JOIN C_AcctSchema acs on acs.C_AcctSchema_ID=cost.C_AcctSchema_ID INNER JOIN M_CostElement ce on cost.M_CostElement_ID = ce.M_CostElement_ID WHERE cost.M_Product_ID = p_M_Product_ID AND cost.AD_Client_ID = p_AD_Client_ID AND cost.AD_Org_ID = p_AD_Org_ID AND cost.C_AcctSchema_ID = (select ci.C_AcctSchema1_ID from AD_ClientInfo ci where ci.AD_Client_ID = p_AD_Client_ID) AND ce.CostingMethod = acs.CostingMethod -- UNION ALL ( SELECT 0 ) LIMIT 1 $BODY$ LANGUAGE sql STABLE ; COMMENT ON FUNCTION getCostPrice(numeric, numeric, numeric) IS ' -- TEST : SELECT M_Product_ID, getCostPrice(M_Product_ID, 1000000, 1000000) from M_Product; ' ;
25.861111
117
0.787325
15763905a2ae36832d8dff2b22575dce55500a74
5,590
rb
Ruby
test/services/import_eleves_test.rb
sgmap/dossiersco
04a1ae00e4007485efbc9268f2b55b788d664455
[ "MIT" ]
5
2019-02-21T20:57:59.000Z
2021-06-15T19:17:08.000Z
test/services/import_eleves_test.rb
sgmap/dossiersco
04a1ae00e4007485efbc9268f2b55b788d664455
[ "MIT" ]
502
2018-02-26T10:46:39.000Z
2022-03-30T22:59:23.000Z
test/services/import_eleves_test.rb
sgmap/dossiersco
04a1ae00e4007485efbc9268f2b55b788d664455
[ "MIT" ]
10
2018-02-25T21:17:55.000Z
2021-03-21T21:38:18.000Z
# frozen_string_literal: true require "test_helper" class ImportElevesTest < ActiveSupport::TestCase include ActionDispatch::TestProcess::FixtureFile test "enregistre les données élèves" do etablissement = Fabricate(:etablissement, uai: "0752387M") dossier = Fabricate(:dossier_eleve, identifiant: "070832327JA", ville_naiss: "blu", commune_insee_naissance: nil) fichier_xml = fixture_file_upload("files/eleves_avec_adresse_simple.xml") tache = Fabricate(:tache_import, type_fichier: "eleves", fichier: fichier_xml, etablissement: etablissement) assert_nothing_raised do ImportEleves.new.perform(tache) dossier.reload assert_equal "10210001110", dossier.mef_an_dernier assert_equal "4 D", dossier.division_an_dernier assert_equal "3 A", dossier.division assert_equal "93066", dossier.commune_insee_naissance assert_equal "ST DENIS", dossier.ville_naiss end end test "n'écrase pas les données présente" do etablissement = Fabricate(:etablissement, uai: "0752387M") dossier = Fabricate(:dossier_eleve, identifiant: "070832327JA", ville_naiss: "Saint Denis", commune_insee_naissance: "93066") fichier_xml = fixture_file_upload("files/eleves_avec_adresse_simple.xml") tache = Fabricate(:tache_import, type_fichier: "eleves", fichier: fichier_xml, etablissement: etablissement) assert_nothing_raised do ImportEleves.new.perform(tache) dossier.reload assert_equal "93066", dossier.commune_insee_naissance assert_equal "Saint Denis", dossier.ville_naiss end end test "récolte le ID_PRV_ELE du fichier avec l'élève" do etablissement = Fabricate(:etablissement, uai: "0752387M") dossier = Fabricate(:dossier_eleve, identifiant: "060375611AC", id_prv_ele: nil) autre_dossier = Fabricate(:dossier_eleve, identifiant: "070832327JA", id_prv_ele: nil) fichier_xml = fixture_file_upload("files/eleves_avec_adresse_simple.xml") tache = Fabricate(:tache_import, type_fichier: "eleves", fichier: fichier_xml, etablissement: etablissement) ImportEleves.new.perform(tache) dossier.reload assert_equal "9065", dossier.id_prv_ele autre_dossier.reload assert_nil autre_dossier.id_prv_ele end test "récolte PRENOM2 et PRENOM3" do etablissement = Fabricate(:etablissement, uai: "0752387M") dossier_avec_3_prenoms = Fabricate(:dossier_eleve, identifiant: "060375611AC") fichier_xml = fixture_file_upload("files/eleves_avec_adresse_simple.xml") tache = Fabricate(:tache_import, type_fichier: "eleves", fichier: fichier_xml, etablissement: etablissement) ImportEleves.new.perform(tache) dossier_avec_3_prenoms.reload assert_equal "PRENOM2", dossier_avec_3_prenoms.prenom_2 assert_equal "PRENOM3", dossier_avec_3_prenoms.prenom_3 end test "préserve des PRENOM2 et PRENOM3 renseignés dans DossierSCO" do etablissement = Fabricate(:etablissement, uai: "0752387M") dossier_avec_3_prenoms = Fabricate(:dossier_eleve, identifiant: "060375611AC", prenom_2: "Prénom 2 DossierSCO", prenom_3: "Prénom 3 DossierSCO") fichier_xml = fixture_file_upload("files/eleves_avec_adresse_simple.xml") tache = Fabricate(:tache_import, type_fichier: "eleves", fichier: fichier_xml, etablissement: etablissement) ImportEleves.new.perform(tache) dossier_avec_3_prenoms.reload assert_equal "Prénom 2 DossierSCO", dossier_avec_3_prenoms.prenom_2 assert_equal "Prénom 3 DossierSCO", dossier_avec_3_prenoms.prenom_3 end test "met à jour l'information à propos des possibilité de retour siecle" do etablissement = Fabricate(:etablissement, uai: "0752387M") Fabricate(:dossier_eleve, identifiant: "070832327JA", ville_naiss: "blu", commune_insee_naissance: nil) dossier_valide = Fabricate(:dossier_eleve_valide, etablissement: etablissement) dossier_invalide = Fabricate(:dossier_eleve, mef_destination: nil, etablissement: etablissement) fichier_xml = fixture_file_upload("files/eleves_avec_adresse_simple.xml") tache = Fabricate(:tache_import, type_fichier: "eleves", fichier: fichier_xml, etablissement: etablissement) ImportEleves.new.perform(tache) dossier_valide.reload assert_equal "", dossier_valide.retour_siecle_impossible dossier_invalide.reload assert_equal I18n.t("retour_siecles.dossier_non_valide"), dossier_invalide.retour_siecle_impossible end test "quand il y deux structures, on ne prend que la premier (la deuxième correspond au groupe)" do etablissement = Fabricate(:etablissement, uai: "0660864F") dossier_valide = Fabricate(:dossier_eleve_valide, etablissement: etablissement, division: nil, identifiant: "070876696HA") fichier_xml = fixture_file_upload("files/eleves_avec_adresse_avec_double_structure.xml") tache = Fabricate(:tache_import, type_fichier: "eleves", fichier: fichier_xml, etablissement: etablissement) ImportEleves.new.perform(tache) dossier_valide.reload assert_equal "", dossier_valide.retour_siecle_impossible assert_equal "301", dossier_valide.division end test "n'importe pas un fichier avec le mauvais UAJ" do etablissement = Fabricate(:etablissement, uai: "0752387E") fichier_xml = fixture_file_upload("files/eleves_avec_adresse_simple.xml") tache = Fabricate(:tache_import, type_fichier: "eleves", fichier: fichier_xml, etablissement: etablissement) dossier_eleve = Fabricate(:dossier_eleve, identifiant: "070832327JA") ImportEleves.new.perform(tache) dossier_eleve.reload assert_nil dossier_eleve.prenom_2 end end
43.671875
148
0.772272
bcb2a99ad404c4be7eddea9545f1026e33ae4a73
533
js
JavaScript
lib/utils/MazeSettings.js
nylira/nylira-maze
423b2bb2c68386d6348d740fab491b7213fbd9c9
[ "MIT" ]
10
2015-03-23T10:21:28.000Z
2020-02-21T17:18:48.000Z
lib/utils/MazeSettings.js
nylira/nylira-maze
423b2bb2c68386d6348d740fab491b7213fbd9c9
[ "MIT" ]
1
2017-08-15T12:32:04.000Z
2017-08-15T12:32:04.000Z
lib/utils/MazeSettings.js
nylira/nylira-maze
423b2bb2c68386d6348d740fab491b7213fbd9c9
[ "MIT" ]
null
null
null
(function(){ 'use strict' function MazeSettings() { var globals = {} var N = 1 var S = 2 var E = 4 var W = 8 var DIRS = ['N', 'S', 'E', 'W'] var DIRS_VAL = { N: N, S: S, E: E, W: W } var DX = { E: 1, W: -1, N: 0, S: 0 } var DY = { E: 0, W: 0, N: -1, S: 1 } var OPPOSITE = { E: W, W: E, N: S, S: N } globals = { n: N , s: S , e: E , w: W , dirs: DIRS , dirsVal: DIRS_VAL , dx: DX , dy: DY , opposite: OPPOSITE } return globals } module.exports = MazeSettings }())
16.151515
45
0.454034
98ae89d5471044135af6271c72382fd21dd537bb
206
kt
Kotlin
algorithms-kotlin/src/main/kotlin/io/github/brunogabriel/helpers/MaxHelper.kt
brunogabriel/algorithms
050a7093c0f2cf3864157c74adb84a969dea8882
[ "MIT" ]
3
2020-09-16T12:12:51.000Z
2020-09-18T09:15:11.000Z
algorithms-kotlin/src/main/kotlin/io/github/brunogabriel/helpers/MaxHelper.kt
brunogabriel/algorithms
050a7093c0f2cf3864157c74adb84a969dea8882
[ "MIT" ]
null
null
null
algorithms-kotlin/src/main/kotlin/io/github/brunogabriel/helpers/MaxHelper.kt
brunogabriel/algorithms
050a7093c0f2cf3864157c74adb84a969dea8882
[ "MIT" ]
null
null
null
package io.github.brunogabriel.helpers inline fun <T : Comparable<T>> max(a: T, b: T, maxFunction: (T) -> T): T { return if (maxFunction(a) > maxFunction(b)) { a } else { b } }
20.6
74
0.553398
af26ba164bc1ddb68f96c914889f2dd49883d0e0
218
kt
Kotlin
src/main/kotlin/es/urjc/realfood/restaurants/api/security/Constants.kt
MasterCloudApps-Projects/realfood-restaurants
39cdfde55a6347ba33ebe7e43de3530cb76abbf4
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/es/urjc/realfood/restaurants/api/security/Constants.kt
MasterCloudApps-Projects/realfood-restaurants
39cdfde55a6347ba33ebe7e43de3530cb76abbf4
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/es/urjc/realfood/restaurants/api/security/Constants.kt
MasterCloudApps-Projects/realfood-restaurants
39cdfde55a6347ba33ebe7e43de3530cb76abbf4
[ "Apache-2.0" ]
null
null
null
package es.urjc.realfood.restaurants.api.security import java.time.Duration const val TOKEN_BEARER_PREFIX = "Bearer " const val ISSUER_INFO = "realfood-inc" val TOKEN_EXPIRATION_TIME = Duration.ofHours(1).toMillis()
27.25
58
0.807339
652cc5a124cb82089fec9b806d9345c58673911c
7,292
rs
Rust
src/clash/progression/gambler.rs
chamons/ArenaGS
0d3c8d4ebc818198b21a8c99dc853286cc16b7c2
[ "MIT" ]
null
null
null
src/clash/progression/gambler.rs
chamons/ArenaGS
0d3c8d4ebc818198b21a8c99dc853286cc16b7c2
[ "MIT" ]
126
2017-05-14T19:41:31.000Z
2020-11-24T15:53:49.000Z
src/clash/progression/gambler.rs
chamons/ArenaGS
0d3c8d4ebc818198b21a8c99dc853286cc16b7c2
[ "MIT" ]
null
null
null
use std::cmp; use std::collections::HashMap; use rand::prelude::*; use specs::prelude::*; use super::super::*; pub fn get_reward_request(ecs: &World, count: u32) -> Vec<(EquipmentRarity, u32)> { let mut rng = ecs.write_resource::<RandomComponent>(); let choices = vec![EquipmentRarity::Common, EquipmentRarity::Uncommon, EquipmentRarity::Rare]; let mut requests = HashMap::new(); let mut add_request = |kind: EquipmentRarity| *requests.entry(kind).or_insert(0) += 1; for _ in 0..count { add_request( *choices .choose_weighted(&mut rng.rand, |i| match i { EquipmentRarity::Common => 75, EquipmentRarity::Uncommon => 15, EquipmentRarity::Rare => 10, EquipmentRarity::Standard => 0, }) .unwrap(), ); } requests.iter().map(|x| (*x.0, *x.1)).collect() } pub fn get_merchant_items(ecs: &World) -> Vec<EquipmentItem> { get_random_items( ecs, vec![(EquipmentRarity::Rare, 1), (EquipmentRarity::Uncommon, 2), (EquipmentRarity::Common, 5)], ) } pub fn get_random_items(ecs: &World, requests: Vec<(EquipmentRarity, u32)>) -> Vec<EquipmentItem> { let equipment = ecs.read_resource::<EquipmentResource>(); let progression = ecs.read_resource::<ProgressionComponent>(); let available: Vec<&EquipmentItem> = equipment.all().filter(|e| !progression.state.items.contains(&e.name)).collect(); let rare: Vec<&EquipmentItem> = available.iter().filter(|e| e.rarity == EquipmentRarity::Rare).copied().collect(); let uncommon: Vec<&EquipmentItem> = available.iter().filter(|e| e.rarity == EquipmentRarity::Uncommon).copied().collect(); let common: Vec<&EquipmentItem> = available.iter().filter(|&e| e.rarity == EquipmentRarity::Common).copied().collect(); let rare_request_count: u32 = requests.iter().filter(|r| r.0 == EquipmentRarity::Rare).map(|r| r.1).sum(); let mut uncommon_request_count: u32 = requests.iter().filter(|r| r.0 == EquipmentRarity::Uncommon).map(|r| r.1).sum(); let mut common_request_count: u32 = requests.iter().filter(|r| r.0 == EquipmentRarity::Common).map(|r| r.1).sum(); let rare_count = cmp::min(rare_request_count, rare.len() as u32); if rare_count < rare_request_count { uncommon_request_count += rare_request_count - rare_count; } let uncommon_count = cmp::min(uncommon_request_count, uncommon.len() as u32); if uncommon_count < uncommon_request_count { common_request_count += uncommon_request_count - uncommon_count; } let common_count = cmp::min(common_request_count, common.len() as u32); let mut rng = ecs.write_resource::<RandomComponent>(); let mut chosen = Vec::with_capacity((rare_request_count + uncommon_request_count + common_request_count) as usize); chosen.extend(rare.choose_multiple(&mut rng.rand, rare_count as usize).map(|&e| e.clone())); chosen.extend(uncommon.choose_multiple(&mut rng.rand, uncommon_count as usize).map(|&e| e.clone())); chosen.extend(common.choose_multiple(&mut rng.rand, common_count as usize).map(|&e| e.clone())); // Reverse so rare at end chosen.reverse(); chosen } #[cfg(test)] mod tests { use super::*; #[test] fn selects_items() { let mut ecs = World::new(); let equipments = EquipmentResource::init_with(&[ EquipmentItem::init("a", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), EquipmentItem::init("b", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), EquipmentItem::init("c", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), EquipmentItem::init("d", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), ]); let progression = ProgressionComponent::init(ProgressionState::init(0, 0, &["a"], CharacterWeaponKind::Gunslinger, Equipment::init_empty())); ecs.insert(RandomComponent::init()); ecs.insert(progression); ecs.insert(equipments); for _ in 0..10 { let chosen = get_random_items(&ecs, vec![(EquipmentRarity::Common, 2)]); assert_eq!(2, chosen.len()); assert!(chosen.iter().all(|c| c.name == "b" || c.name == "c" || c.name == "d")); } } #[test] fn downgrades_when_too_few() { let mut ecs = World::new(); let equipments = EquipmentResource::init_with(&[ EquipmentItem::init("a", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), EquipmentItem::init("b", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), EquipmentItem::init("c", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), EquipmentItem::init("d", None, EquipmentKinds::Accessory, EquipmentRarity::Uncommon, &[EquipmentEffect::None]), EquipmentItem::init("e", None, EquipmentKinds::Accessory, EquipmentRarity::Uncommon, &[EquipmentEffect::None]), EquipmentItem::init("f", None, EquipmentKinds::Accessory, EquipmentRarity::Rare, &[EquipmentEffect::None]), ]); let progression = ProgressionComponent::init(ProgressionState::init(0, 0, &["a"], CharacterWeaponKind::Gunslinger, Equipment::init_empty())); ecs.insert(RandomComponent::init()); ecs.insert(progression); ecs.insert(equipments); for _ in 0..10 { let chosen = get_random_items( &ecs, vec![(EquipmentRarity::Common, 2), (EquipmentRarity::Uncommon, 2), (EquipmentRarity::Rare, 2)], ); assert_eq!(5, chosen.len()); assert!(chosen.iter().all(|c| c.name != "a")); } } #[test] fn too_few_total_items() { let mut ecs = World::new(); let equipments = EquipmentResource::init_with(&[ EquipmentItem::init("a", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), EquipmentItem::init("b", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), EquipmentItem::init("c", None, EquipmentKinds::Accessory, EquipmentRarity::Common, &[EquipmentEffect::None]), ]); let progression = ProgressionComponent::init(ProgressionState::init(0, 0, &["a"], CharacterWeaponKind::Gunslinger, Equipment::init_empty())); ecs.insert(RandomComponent::init()); ecs.insert(progression); ecs.insert(equipments); for _ in 0..10 { let chosen = get_random_items( &ecs, vec![(EquipmentRarity::Common, 12), (EquipmentRarity::Uncommon, 2), (EquipmentRarity::Rare, 2)], ); assert_eq!(2, chosen.len()); assert!(chosen.iter().all(|c| c.name != "a")); } } #[test] fn random_reward() { let mut ecs = World::new(); ecs.insert(RandomComponent::init()); let request = get_reward_request(&ecs, 3); assert_eq!(3, request.iter().map(|r| r.1).sum::<u32>()); } }
43.147929
149
0.629868
f058d42b2a4bde7d77c5bec6bcceb20fe27da1e3
2,081
js
JavaScript
web/js/main.js
denisTsvirko/restoyii.io
6db9ea7fa98e9545b7c86c2ec33733ea78964a54
[ "BSD-3-Clause" ]
null
null
null
web/js/main.js
denisTsvirko/restoyii.io
6db9ea7fa98e9545b7c86c2ec33733ea78964a54
[ "BSD-3-Clause" ]
null
null
null
web/js/main.js
denisTsvirko/restoyii.io
6db9ea7fa98e9545b7c86c2ec33733ea78964a54
[ "BSD-3-Clause" ]
null
null
null
$(function () { $('.rating_2').rating({ fx: 'float', image: 'images/starsss.png', width: '1px', loader: 'images/ajax-loader.gif', url: 'site/index', callback: function (responce) { this.vote_success.fadeOut(2000); this._data.val = responce[0]; this._data.votes = responce[1]; this.render(); } }); $('#button_style').bind('click', function () { console.log('+++'); $.ajax({ url: '/index-add', data: {date: 'all'}, type: 'POST', datatype: 'json', success: function (res) { goWriteMenu(JSON.parse(res)); }, error: function () { alert('Error!'); } }); }); function goWriteMenu(data) { $('.left div').remove(); $('.right div').remove(); var i = 0; for (i; i < data.length; i++) { if (i < data.length / 2) { $('.left').append('<div class = \"container_prise\">' + '<div class=\"container_menu_el\">' + '<div class=\"name_eat\">' + data[i].name + '</div>' + '<div class=\"med_line\"></div>' + '<div class=\"cost_eat\">$' + data[i].cost + '</div>' + '</div>' + '<div class=\"info_eat\">' + data[i].info + '</div>' + '</div>'); } else { $('.right').append('<div class = \"container_prise\">' + '<div class=\"container_menu_el\">' + '<div class=\"name_eat\">' + data[i].name + '</div>' + '<div class=\"med_line\"></div>' + '<div class=\"cost_eat\">$' + data[i].cost + '</div>' + '</div>' + '<div class=\"info_eat\">' + data[i].info + '</div>' + '</div>'); } } $("#button_style").css("display", "none"); } })
32.015385
75
0.38395
040e190e0368ecd734725045a8016a6c9dab78fc
2,581
js
JavaScript
components/author/author.js
linmujing/lvyingWeChat
2fc8632b5bcee5d21196eee8eec54b1f5defa790
[ "Apache-2.0" ]
null
null
null
components/author/author.js
linmujing/lvyingWeChat
2fc8632b5bcee5d21196eee8eec54b1f5defa790
[ "Apache-2.0" ]
null
null
null
components/author/author.js
linmujing/lvyingWeChat
2fc8632b5bcee5d21196eee8eec54b1f5defa790
[ "Apache-2.0" ]
null
null
null
// components/mydist/author.js var app = getApp(); Component({ /** * 组件的属性列表 */ properties: { }, /** * 组件的初始数据 */ data: { // 组件显示 authorShow: true }, ready(){ }, /** * 组件的方法列表 */ methods: { // 获取用户信息 onGotUserInfo(res) { console.log(res) wx.showLoading({ title: '获取授权中...', mask: true }) let that = this; // 小程序接口参数 let url = app.GO.api + 'wechat/login/mp/customer/userInfo'; let param = { encryptedData: res.detail.encryptedData, iv: res.detail.iv }; //调用登录接口 wx.login({ success: function (res) { // wx.showModal({ // title: '1', // content: JSON.stringify(res), // }) console.log(res) param.code = res.code; wx.request({ url: url, method: 'get', data: param, success: function (res) { // wx.showModal({ // title: '2', // content: JSON.stringify(res), // }) wx.hideLoading() console.log(res.data) let data = res.data; if(data.code == 200){ wx.setStorageSync('recommend_customer_id', data.content.ciCode); wx.setStorageSync('recommend_customer_name', data.content.ciName); wx.setStorageSync('recommend_customer_phone', data.content.ciPhone); wx.setStorageSync('recommend_customer_img', data.content.ciProfileUrl); wx.setStorageSync('unionLongId', data.content.unionLongId); //鉴权 app.GO.util.getStorageData(app); wx.showToast({ title: '获取授权成功!' }) setTimeout(() => { wx.navigateBack() },500); }else{ wx.showToast({ title: '获取授权失败!' , 'icon':'none'}) } }, fail: function (err) { // wx.showModal({ // title: '3', // content: JSON.stringify(err), // }) wx.hideLoading() wx.showToast({ title: '获取授权失败,请重新检查网络是否正常!', icon: 'none' }) } }) }, fail: function (res) { // wx.showModal({ // title: '4', // content: JSON.stringify(res), // }) wx.hideLoading() wx.showToast({ title: '获取授权失败,请重新检查网络是否正常!', icon: 'none' }) } }) }, } })
24.349057
88
0.444789
05f8b800d2ec0cd6027194a2e0c5f587897639ff
215
rb
Ruby
test/test_helper.rb
wyhaines/simplereactor
09605bdc3b1b1708552e6d28f84478b0bc3ddf4e
[ "MIT" ]
1
2016-05-04T20:03:08.000Z
2016-05-04T20:03:08.000Z
test/test_helper.rb
wyhaines/simplereactor
09605bdc3b1b1708552e6d28f84478b0bc3ddf4e
[ "MIT" ]
null
null
null
test/test_helper.rb
wyhaines/simplereactor
09605bdc3b1b1708552e6d28f84478b0bc3ddf4e
[ "MIT" ]
null
null
null
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'simplereactor' require 'minitest/autorun' class Object def false? self ? false : true end def true? self ? true : false end end
14.333333
58
0.674419
7ada649d7e513bcadaed369314edb41e9760ef1d
1,631
rb
Ruby
test/cookbooks/puppet-test/recipes/default.rb
balleman-tt/puppet_compat
93a0dc2dd6e8e6d9719c892e86544dd5e4b21f7d
[ "Apache-2.0" ]
null
null
null
test/cookbooks/puppet-test/recipes/default.rb
balleman-tt/puppet_compat
93a0dc2dd6e8e6d9719c892e86544dd5e4b21f7d
[ "Apache-2.0" ]
2
2018-09-11T18:41:17.000Z
2020-05-06T13:45:48.000Z
test/cookbooks/puppet-test/recipes/default.rb
balleman-tt/puppet_compat
93a0dc2dd6e8e6d9719c892e86544dd5e4b21f7d
[ "Apache-2.0" ]
1
2020-07-09T18:59:03.000Z
2020-07-09T18:59:03.000Z
include_recipe 'puppet_compat' # place test files %w(cfg ini).each do |ext| cookbook_file "/tmp/test.#{ext}" do mode 0666 source "test.#{ext}" end end # tests for file_line file_line 'Add a line' do path '/tmp/test.cfg' line 'line: ADD' end file_line 'Delete with match' do path '/tmp/test.cfg' match '^todelete' match_for_absence true action :delete end file_line 'Delete the line' do path '/tmp/test.cfg' line 'yetanother: delete' action :delete end file_line 'Change one line with match' do path '/tmp/test.cfg' match '^tochange' line 'tochange: changed' end # tests for ini_setting ini_setting 'Set option' do path '/tmp/test.ini' section 'test' setting 'option_add' value 'added' separator '=' end ini_setting 'Delete option' do path '/tmp/test.ini' section 'test' setting 'option_two' action :delete end ini_setting 'Change option' do path '/tmp/test.ini' section 'test' setting 'option_chg' value 'nice' end ini_setting 'Delete section' do path '/tmp/test.ini' section 'del' action :delete end ini_setting 'Settings in hash' do path '/tmp/test.ini' section 'settings_test' setting node['settings_test'] end ini_setting 'Sections in hash' do path '/tmp/test.ini' section node['sections_test'] end ini_setting 'Delete settings in array' do path '/tmp/test.ini' section 'test' setting node['settings_del'] action :delete end ini_setting 'Delete sections in array' do path '/tmp/test.ini' section node['sections_del'] action :delete end
21.746667
41
0.666462
81581b5cf16f2c5edd9b673f426d86d79dc9d348
13,551
rs
Rust
proxy/src/proxy.rs
ctring/zenith
214567bf8fafed56cd867698d9e54fafc7001b45
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
proxy/src/proxy.rs
ctring/zenith
214567bf8fafed56cd867698d9e54fafc7001b45
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
proxy/src/proxy.rs
ctring/zenith
214567bf8fafed56cd867698d9e54fafc7001b45
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
use crate::auth; use crate::cancellation::{self, CancelMap}; use crate::config::{ProxyConfig, TlsConfig}; use crate::stream::{MetricsStream, PqStream, Stream}; use anyhow::{bail, Context}; use futures::TryFutureExt; use lazy_static::lazy_static; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncWrite}; use zenith_metrics::{new_common_metric_name, register_int_counter, IntCounter}; use zenith_utils::pq_proto::{BeMessage as Be, *}; const ERR_INSECURE_CONNECTION: &str = "connection is insecure (try using `sslmode=require`)"; const ERR_PROTO_VIOLATION: &str = "protocol violation"; lazy_static! { static ref NUM_CONNECTIONS_ACCEPTED_COUNTER: IntCounter = register_int_counter!( new_common_metric_name("num_connections_accepted"), "Number of TCP client connections accepted." ) .unwrap(); static ref NUM_CONNECTIONS_CLOSED_COUNTER: IntCounter = register_int_counter!( new_common_metric_name("num_connections_closed"), "Number of TCP client connections closed." ) .unwrap(); static ref NUM_BYTES_PROXIED_COUNTER: IntCounter = register_int_counter!( new_common_metric_name("num_bytes_proxied"), "Number of bytes sent/received between any client and backend." ) .unwrap(); } /// A small combinator for pluggable error logging. async fn log_error<R, F>(future: F) -> F::Output where F: std::future::Future<Output = anyhow::Result<R>>, { future.await.map_err(|err| { println!("error: {}", err); err }) } pub async fn thread_main( config: &'static ProxyConfig, listener: tokio::net::TcpListener, ) -> anyhow::Result<()> { scopeguard::defer! { println!("proxy has shut down"); } // When set for the server socket, the keepalive setting // will be inherited by all accepted client sockets. socket2::SockRef::from(&listener).set_keepalive(true)?; let cancel_map = Arc::new(CancelMap::default()); loop { let (socket, peer_addr) = listener.accept().await?; println!("accepted connection from {}", peer_addr); let cancel_map = Arc::clone(&cancel_map); tokio::spawn(log_error(async move { socket .set_nodelay(true) .context("failed to set socket option")?; handle_client(config, &cancel_map, socket).await })); } } async fn handle_client( config: &ProxyConfig, cancel_map: &CancelMap, stream: impl AsyncRead + AsyncWrite + Unpin, ) -> anyhow::Result<()> { // The `closed` counter will increase when this future is destroyed. NUM_CONNECTIONS_ACCEPTED_COUNTER.inc(); scopeguard::defer! { NUM_CONNECTIONS_CLOSED_COUNTER.inc(); } let tls = config.tls_config.clone(); let (stream, creds) = match handshake(stream, tls, cancel_map).await? { Some(x) => x, None => return Ok(()), // it's a cancellation request }; let client = Client::new(stream, creds); cancel_map .with_session(|session| client.connect_to_db(config, session)) .await } /// Establish a (most probably, secure) connection with the client. /// For better testing experience, `stream` can be any object satisfying the traits. /// It's easier to work with owned `stream` here as we need to updgrade it to TLS; /// we also take an extra care of propagating only the select handshake errors to client. async fn handshake<S: AsyncRead + AsyncWrite + Unpin>( stream: S, mut tls: Option<TlsConfig>, cancel_map: &CancelMap, ) -> anyhow::Result<Option<(PqStream<Stream<S>>, auth::ClientCredentials)>> { // Client may try upgrading to each protocol only once let (mut tried_ssl, mut tried_gss) = (false, false); let mut stream = PqStream::new(Stream::from_raw(stream)); loop { let msg = stream.read_startup_packet().await?; println!("got message: {:?}", msg); use FeStartupPacket::*; match msg { SslRequest => match stream.get_ref() { Stream::Raw { .. } if !tried_ssl => { tried_ssl = true; // We can't perform TLS handshake without a config let enc = tls.is_some(); stream.write_message(&Be::EncryptionResponse(enc)).await?; if let Some(tls) = tls.take() { // Upgrade raw stream into a secure TLS-backed stream. // NOTE: We've consumed `tls`; this fact will be used later. stream = PqStream::new(stream.into_inner().upgrade(tls).await?); } } _ => bail!(ERR_PROTO_VIOLATION), }, GssEncRequest => match stream.get_ref() { Stream::Raw { .. } if !tried_gss => { tried_gss = true; // Currently, we don't support GSSAPI stream.write_message(&Be::EncryptionResponse(false)).await?; } _ => bail!(ERR_PROTO_VIOLATION), }, StartupMessage { params, .. } => { // Check that the config has been consumed during upgrade // OR we didn't provide it at all (for dev purposes). if tls.is_some() { stream.throw_error_str(ERR_INSECURE_CONNECTION).await?; } // Here and forth: `or_else` demands that we use a future here let creds = async { params.try_into() } .or_else(|e| stream.throw_error(e)) .await?; break Ok(Some((stream, creds))); } CancelRequest(cancel_key_data) => { cancel_map.cancel_session(cancel_key_data).await?; break Ok(None); } } } } /// Thin connection context. struct Client<S> { /// The underlying libpq protocol stream. stream: PqStream<S>, /// Client credentials that we care about. creds: auth::ClientCredentials, } impl<S> Client<S> { /// Construct a new connection context. fn new(stream: PqStream<S>, creds: auth::ClientCredentials) -> Self { Self { stream, creds } } } impl<S: AsyncRead + AsyncWrite + Unpin> Client<S> { /// Let the client authenticate and connect to the designated compute node. async fn connect_to_db( self, config: &ProxyConfig, session: cancellation::Session<'_>, ) -> anyhow::Result<()> { let Self { mut stream, creds } = self; // Authenticate and connect to a compute node. let auth = creds.authenticate(config, &mut stream).await; let db_info = async { auth }.or_else(|e| stream.throw_error(e)).await?; let (db, version, cancel_closure) = db_info.connect().or_else(|e| stream.throw_error(e)).await?; let cancel_key_data = session.enable_cancellation(cancel_closure); stream .write_message_noflush(&BeMessage::ParameterStatus( BeParameterStatusMessage::ServerVersion(&version), ))? .write_message_noflush(&Be::BackendKeyData(cancel_key_data))? .write_message(&BeMessage::ReadyForQuery) .await?; /// This function will be called for writes to either direction. fn inc_proxied(cnt: usize) { // Consider inventing something more sophisticated // if this ever becomes a bottleneck (cacheline bouncing). NUM_BYTES_PROXIED_COUNTER.inc_by(cnt as u64); } // Starting from here we only proxy the client's traffic. let mut db = MetricsStream::new(db, inc_proxied); let mut client = MetricsStream::new(stream.into_inner(), inc_proxied); let _ = tokio::io::copy_bidirectional(&mut client, &mut db).await?; Ok(()) } } #[cfg(test)] mod tests { use super::*; use tokio::io::DuplexStream; use tokio_postgres::config::SslMode; use tokio_postgres::tls::{MakeTlsConnect, NoTls}; use tokio_postgres_rustls::MakeRustlsConnect; async fn dummy_proxy( client: impl AsyncRead + AsyncWrite + Unpin, tls: Option<TlsConfig>, ) -> anyhow::Result<()> { let cancel_map = CancelMap::default(); // TODO: add some infra + tests for credentials let (mut stream, _creds) = handshake(client, tls, &cancel_map) .await? .context("no stream")?; stream .write_message_noflush(&Be::AuthenticationOk)? .write_message_noflush(&BeParameterStatusMessage::encoding())? .write_message(&BeMessage::ReadyForQuery) .await?; Ok(()) } fn generate_certs( hostname: &str, ) -> anyhow::Result<(rustls::Certificate, rustls::Certificate, rustls::PrivateKey)> { let ca = rcgen::Certificate::from_params({ let mut params = rcgen::CertificateParams::default(); params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); params })?; let cert = rcgen::generate_simple_self_signed(vec![hostname.into()])?; Ok(( rustls::Certificate(ca.serialize_der()?), rustls::Certificate(cert.serialize_der_with_signer(&ca)?), rustls::PrivateKey(cert.serialize_private_key_der()), )) } #[tokio::test] async fn handshake_tls_is_enforced_by_proxy() -> anyhow::Result<()> { let (client, server) = tokio::io::duplex(1024); let server_config = { let (_ca, cert, key) = generate_certs("localhost")?; let mut config = rustls::ServerConfig::new(rustls::NoClientAuth::new()); config.set_single_cert(vec![cert], key)?; config }; let proxy = tokio::spawn(dummy_proxy(client, Some(server_config.into()))); let client_err = tokio_postgres::Config::new() .user("john_doe") .dbname("earth") .ssl_mode(SslMode::Disable) .connect_raw(server, NoTls) .await .err() // -> Option<E> .context("client shouldn't be able to connect")?; assert!(client_err.to_string().contains(ERR_INSECURE_CONNECTION)); let server_err = proxy .await? .err() // -> Option<E> .context("server shouldn't accept client")?; assert!(client_err.to_string().contains(&server_err.to_string())); Ok(()) } #[tokio::test] async fn handshake_tls() -> anyhow::Result<()> { let (client, server) = tokio::io::duplex(1024); let (ca, cert, key) = generate_certs("localhost")?; let server_config = { let mut config = rustls::ServerConfig::new(rustls::NoClientAuth::new()); config.set_single_cert(vec![cert], key)?; config }; let proxy = tokio::spawn(dummy_proxy(client, Some(server_config.into()))); let client_config = { let mut config = rustls::ClientConfig::new(); config.root_store.add(&ca)?; config }; let mut mk = MakeRustlsConnect::new(client_config); let tls = MakeTlsConnect::<DuplexStream>::make_tls_connect(&mut mk, "localhost")?; let (_client, _conn) = tokio_postgres::Config::new() .user("john_doe") .dbname("earth") .ssl_mode(SslMode::Require) .connect_raw(server, tls) .await?; proxy.await? } #[tokio::test] async fn handshake_raw() -> anyhow::Result<()> { let (client, server) = tokio::io::duplex(1024); let proxy = tokio::spawn(dummy_proxy(client, None)); let (_client, _conn) = tokio_postgres::Config::new() .user("john_doe") .dbname("earth") .ssl_mode(SslMode::Prefer) .connect_raw(server, NoTls) .await?; proxy.await? } #[tokio::test] async fn give_user_an_error_for_bad_creds() -> anyhow::Result<()> { let (client, server) = tokio::io::duplex(1024); let proxy = tokio::spawn(dummy_proxy(client, None)); let client_err = tokio_postgres::Config::new() .ssl_mode(SslMode::Disable) .connect_raw(server, NoTls) .await .err() // -> Option<E> .context("client shouldn't be able to connect")?; // TODO: this is ugly, but `format!` won't allow us to extract fmt string assert!(client_err.to_string().contains("missing in startup packet")); let server_err = proxy .await? .err() // -> Option<E> .context("server shouldn't accept client")?; assert!(client_err.to_string().contains(&server_err.to_string())); Ok(()) } #[tokio::test] async fn keepalive_is_inherited() -> anyhow::Result<()> { use tokio::net::{TcpListener, TcpStream}; let listener = TcpListener::bind("127.0.0.1:0").await?; let port = listener.local_addr()?.port(); socket2::SockRef::from(&listener).set_keepalive(true)?; let t = tokio::spawn(async move { let (client, _) = listener.accept().await?; let keepalive = socket2::SockRef::from(&client).keepalive()?; anyhow::Ok(keepalive) }); let _ = TcpStream::connect(("127.0.0.1", port)).await?; assert!(t.await??, "keepalive should be inherited"); Ok(()) } }
34.306329
93
0.590584
cf17f4ced861fad1838270e68fa5d68abbeb5304
3,608
css
CSS
pages/cardNumber/cardNumber.css
DigvijayDheer/Indian-Government-All-Scheme-Portal
015521401db2494f03208f8cb1a384d9ac64aed4
[ "MIT" ]
1
2020-12-24T12:10:02.000Z
2020-12-24T12:10:02.000Z
pages/cardNumber/cardNumber.css
DigvijayDheer/Indian-Government-All-Scheme-Portal
015521401db2494f03208f8cb1a384d9ac64aed4
[ "MIT" ]
null
null
null
pages/cardNumber/cardNumber.css
DigvijayDheer/Indian-Government-All-Scheme-Portal
015521401db2494f03208f8cb1a384d9ac64aed4
[ "MIT" ]
null
null
null
body { margin: 0; padding: 0; box-sizing: border-box; background: url(../../images/bg.jpg); background-position: center; background-size: cover; background-repeat: no-repeat; } .container { height: 100vh; width: 100vw; background-color: rgba(1, 1, 20, 0.9); overflow: hidden; } .welcomeNote { display: flex; flex-direction: row; justify-content: center; align-items: center; margin-top: 15px; } span { font-family: 'Times New Roman',serif; letter-spacing: 5px; font-size: 40px; font-weight: bold; text-decoration: underline #cb9b51; background-image: linear-gradient( to right, #462d23 0, #cb9b51 22%, #f6e27a 45%, #f6f2c0 50%, #f6e27a 55%, #cb9b51 78%, #462523 100% ); color:transparent; -webkit-background-clip:text; } .main-hadding { display: flex; justify-content: center; font-size: 40px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #d3bb46; } .use-keyboard-input { position: fixed; left: 30%; top: 26%; width: 500px; height: 70px; padding: 0 45px; font-size: 40px; letter-spacing: 5px; border-radius: 10px; color: #000; font-weight: bold; background-color: rgba(255, 255, 255, 0.2); outline: none; border: 0.5px solid #cb9b51; cursor: pointer; } .advisory { position: fixed; left: 31%; top: 35%; color: rgb(129, 127, 127); font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-size: 20px; } .use-keyboard-input:focus { background-color: rgba(255, 255, 255, 0.6); } .keyboard { position: fixed; left: 0; bottom: 20%; width: 100%; padding: 5px 0; user-select: none; transition: bottom 0.4s; } .keyboard__keys { text-align: center; } .keyboard__key { height: 50px; width: 10%; max-width: 100px; margin: 3px; border-radius: 4px; border: none; background: rgba(94, 48, 245, 0.6); color: #cb9b51; font-size: 1.2rem; outline: none; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; vertical-align: top; padding: 0; -webkit-tap-highlight-color: transparent; position: relative; } .keyboard__key:active { background: rgba(255, 255, 255, 0.12); } .keyboard__key--wide { width: 12%; } .keyboard__key--extra-wide { width: 36%; max-width: 500px; } .keyboard__key--activatable::after { content: ''; top: 10px; right: 10px; position: absolute; width: 8px; height: 8px; background: rgba(0, 0, 0, 0.4); border-radius: 50%; } .keyboard__key--active::after { background: #08ff00; } .keyboard__key--dark { background: rgba(0, 0, 0, 0.25); } .nextButton { height: 70px; width: 300px; position: fixed; left: 40%; bottom: 10%; font-size: 26px; border: none; outline: none; border-radius: 50px; color: #f1d755; background-color: #5E30F5; cursor: pointer; } .nextButton:hover { background-color: #311983; color: #ecc810; } .nextButton:focus { background-color: #f1d755; color: #5E30F5; } marquee { position: fixed; left: 0; bottom: 3.5%; margin-top: 130px; font-size: 20px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #f1d755; }
19.294118
65
0.569568
1a10e6693dd2b16aabf0cfd36e9c4c7f36dbba59
152
rs
Rust
test/1.1.0/doc-core/libcore_iter_rs_0008.rs
brson/ctrs
cd0a46bf647f439067f45238f59a445181c8cb6d
[ "DOC" ]
4
2015-09-17T21:14:42.000Z
2015-11-26T14:58:21.000Z
test/1.1.0/doc-core/libcore_iter_rs_0008.rs
brson/ctrs
cd0a46bf647f439067f45238f59a445181c8cb6d
[ "DOC" ]
2
2015-10-20T09:36:04.000Z
2016-07-22T18:19:45.000Z
test/1.1.0/doc-core/libcore_iter_rs_0008.rs
brson/ctrs
cd0a46bf647f439067f45238f59a445181c8cb6d
[ "DOC" ]
null
null
null
fn main() { let a = [1, 2]; let mut it = a.iter().filter(|&x| *x > 1); assert_eq!(it.next(), Some(&2)); assert!(it.next().is_none()); }
21.714286
46
0.480263
eba5425055a189c70eeb99fe186356b09b375ebc
118
rs
Rust
src/domain/mbox/mod.rs
igbanam/himalaya
767eee95f52f86000b76f2f10dde951046214bff
[ "BSD-3-Clause" ]
3
2021-05-22T21:40:30.000Z
2022-03-02T03:00:38.000Z
src/domain/mbox/mod.rs
igbanam/himalaya
767eee95f52f86000b76f2f10dde951046214bff
[ "BSD-3-Clause" ]
27
2021-08-19T19:51:00.000Z
2021-09-10T22:10:58.000Z
src/domain/mbox/mod.rs
igbanam/himalaya
767eee95f52f86000b76f2f10dde951046214bff
[ "BSD-3-Clause" ]
1
2021-08-31T19:58:35.000Z
2021-08-31T19:58:35.000Z
//! Module related to mailbox. pub mod mbox_arg; pub mod mbox_handler; pub mod mbox_entity; pub use mbox_entity::*;
14.75
30
0.745763
39c7c5e2407f06220f2bb54d28910b08c814ab13
252
js
JavaScript
models/payments.js
engjames256/time-out-server
adfd94d46b76aa9e8c50448914530f58472f1e78
[ "MIT" ]
1
2022-03-28T03:51:32.000Z
2022-03-28T03:51:32.000Z
models/payments.js
engjames256/time-out-server
adfd94d46b76aa9e8c50448914530f58472f1e78
[ "MIT" ]
null
null
null
models/payments.js
engjames256/time-out-server
adfd94d46b76aa9e8c50448914530f58472f1e78
[ "MIT" ]
null
null
null
import mongoose from "mongoose"; const paymentSchema = new mongoose.Schema({ price: { type: Number, required: [true, "Must provide Product Price"], }, }); const payment = mongoose.model("payment", paymentSchema); export default payment;
19.384615
57
0.698413
380433c7084b10df29215ce2d82234904ab8d212
19,483
swift
Swift
Sources/Objects/Types - errors/PyBaseException.swift
LiarPrincess/Violet
0a4268649b0eec3ab631d19015d7043394c6571e
[ "MIT" ]
null
null
null
Sources/Objects/Types - errors/PyBaseException.swift
LiarPrincess/Violet
0a4268649b0eec3ab631d19015d7043394c6571e
[ "MIT" ]
6
2021-10-14T15:55:16.000Z
2022-03-31T14:04:02.000Z
Sources/Objects/Types - errors/PyBaseException.swift
LiarPrincess/Violet
0a4268649b0eec3ab631d19015d7043394c6571e
[ "MIT" ]
null
null
null
import VioletCore // In CPython: // Objects -> exceptions.c // Lib->test->exception_hierarchy.txt <-- this is amazing // https://docs.python.org/3.7/c-api/exceptions.html // https://www.python.org/dev/peps/pep-0415/#proposal // swiftlint:disable static_operator public func === (lhs: PyBaseException, rhs: PyBaseException) -> Bool { lhs.ptr === rhs.ptr } public func !== (lhs: PyBaseException, rhs: PyBaseException) -> Bool { lhs.ptr !== rhs.ptr } // sourcery: pyerrortype = BaseException, isDefault, isBaseType, hasGC // sourcery: isBaseExceptionSubclass, instancesHave__dict__ public struct PyBaseException: PyErrorMixin { // sourcery: pytypedoc internal static let doc = "Common base class for all exceptions" // MARK: - Properties public static let defaultSuppressContext = false private static let suppressContextFlag = PyObject.Flags.custom0 // sourcery: storedProperty internal var args: PyTuple { get { self.argsPtr.pointee } nonmutating set { self.argsPtr.pointee = newValue } } // sourcery: storedProperty internal var traceback: PyTraceback? { get { self.tracebackPtr.pointee } nonmutating set { self.tracebackPtr.pointee = newValue } } // sourcery: storedProperty /// `raise from xxx`. internal var cause: PyBaseException? { get { self.causePtr.pointee } nonmutating set { self.causePtr.pointee = newValue } } // sourcery: storedProperty /// Another exception during whose handling this exception was raised. internal var context: PyBaseException? { get { self.contextPtr.pointee } nonmutating set { self.contextPtr.pointee = newValue } } /// Should we use `self.cause` or `self.context`? /// /// If we have `cause` then probably `cause`, otherwise `context`. internal var suppressContext: Bool { get { let object = PyObject(ptr: self.ptr) return object.flags.isSet(Self.suppressContextFlag) } nonmutating set { let object = PyObject(ptr: self.ptr) object.flags.set(Self.suppressContextFlag, value: newValue) } } // MARK: - Initialize/deinitialize public let ptr: RawPtr public init(ptr: RawPtr) { self.ptr = ptr } internal func initialize( _ py: Py, type: PyType, args: PyTuple, traceback: PyTraceback? = nil, cause: PyBaseException? = nil, context: PyBaseException? = nil, suppressContext: Bool = PyBaseException.defaultSuppressContext ) { self.initializeBase(py, type: type) self.argsPtr.initialize(to: args) self.tracebackPtr.initialize(to: traceback) self.causePtr.initialize(to: cause) self.contextPtr.initialize(to: context) self.suppressContext = suppressContext } // Nothing to do here. internal func beforeDeinitialize(_ py: Py) {} // MARK: - Debug internal static func createDebugInfo(ptr: RawPtr) -> PyObject.DebugMirror { let zelf = PyBaseException(ptr: ptr) var result = PyObject.DebugMirror(object: zelf) Self.fillDebug(zelf: zelf, debug: &result) return result } internal static func fillDebug(zelf: PyBaseException, debug: inout PyObject.DebugMirror) { debug.append(name: "args", value: zelf.args, includeInDescription: true) debug.append(name: "traceback", value: zelf.traceback as Any) debug.append(name: "cause", value: zelf.cause as Any) debug.append(name: "context", value: zelf.context as Any) debug.append(name: "suppressContext", value: zelf.suppressContext) } // MARK: - Message /// Try to get message from first `self.args`. /// /// If it fails then… /// Well whatever. internal func getMessage(_ py: Py) -> PyString? { guard let firstArg = self.args.elements.first else { return nil } // Even when we start with 'string', it may not be a message if we have other. guard self.args.elements.count == 1 else { return nil } guard let string = py.cast.asString(firstArg) else { return nil } return string } // MARK: - String // sourcery: pymethod = __repr__ internal static func __repr__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__repr__") } let name = zelf.typeName let args = zelf.args if args.count == 1 { // BaseException('Elsa') let first = args.elements[0] switch py.reprString(first) { case let .value(s): let result = name + "(" + s + ")" return PyResult(py, result) case let .error(e): return .error(e) } } // BaseException('Elsa', 'Anna') switch args.repr(py) { case let .empty(s), let .reprLock(s), let .value(s): let result = name + s return PyResult(py, result) case let .error(e): return .error(e) } } // sourcery: pymethod = __str__ internal static func __str__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__str__") } return Self.str(py, zelf: zelf) } internal static func str(_ py: Py, zelf: PyBaseException) -> PyResult { let args = zelf.args switch args.count { case 0: return PyResult(py.emptyString) case 1: let first = args.elements[0] let result = py.str(first) return PyResult(result) default: let result = py.str(args.asObject) return PyResult(result) } } // MARK: - Dict // sourcery: pyproperty = __dict__ internal static func __dict__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__dict__") } let result = zelf.getDict(py) return PyResult(result) } internal func getDict(_ py: Py) -> PyDict { let object = PyObject(ptr: self.ptr) guard let result = object.get__dict__(py) else { py.trapMissing__dict__(object: self) } return result } // MARK: - Class // sourcery: pyproperty = __class__ internal static func __class__(_ py: Py, zelf: PyObject) -> PyType { return zelf.type } // MARK: - Attributes // sourcery: pymethod = __getattribute__ internal static func __getattribute__(_ py: Py, zelf _zelf: PyObject, name: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__getattribute__") } return AttributeHelper.getAttribute(py, object: zelf.asObject, name: name) } // sourcery: pymethod = __setattr__ internal static func __setattr__(_ py: Py, zelf _zelf: PyObject, name: PyObject, value: PyObject?) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__setattr__") } return AttributeHelper.setAttribute(py, object: zelf.asObject, name: name, value: value) } // sourcery: pymethod = __delattr__ internal static func __delattr__(_ py: Py, zelf _zelf: PyObject, name: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__delattr__") } return AttributeHelper.delAttribute(py, object: zelf.asObject, name: name) } // MARK: - Args // sourcery: pyproperty = args, setter internal static func args(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "args") } let result = zelf.getArgs() return PyResult(result) } internal func getArgs() -> PyTuple { return self.args } internal static func args(_ py: Py, zelf _zelf: PyObject, value: PyObject?) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "args") } if let error = zelf.setArgs(py, value: value) { return .error(error) } return .none(py) } internal func setArgs(_ py: Py, value: PyObject?) -> PyBaseException? { guard let value = value else { let error = py.newTypeError(message: "args may not be deleted") return error.asBaseException } if let tuple = py.cast.asTuple(value) { self.setArgs(tuple) return nil } switch py.newTuple(iterable: value) { case let .value(tuple): self.args = tuple return nil case let .error(e): return e } } internal func setArgs(_ value: PyTuple) { self.args = value } // MARK: - Traceback // sourcery: pyproperty = __traceback__, setter internal static func __traceback__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__traceback__") } let result = zelf.getTraceback() return PyResult(py, result) } internal func getTraceback() -> PyTraceback? { return self.traceback } internal static func __traceback__(_ py: Py, zelf _zelf: PyObject, value: PyObject?) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__traceback__") } if let error = zelf.setTraceback(py, value: value) { return .error(error) } return .none(py) } private func setTraceback(_ py: Py, value: PyObject?) -> PyBaseException? { guard let value = value else { let error = py.newTypeError(message: "__traceback__ may not be deleted") return error.asBaseException } if py.cast.isNone(value) { self.traceback = nil return nil } if let traceback = py.cast.asTraceback(value) { self.setTraceback(traceback) return nil } let error = py.newTypeError(message: "__traceback__ must be a traceback or None") return error.asBaseException } internal func setTraceback(_ value: PyTraceback) { self.traceback = value } // MARK: - With traceback internal static let withTracebackDoc = """ Exception.with_traceback(tb) -- set zelf.__traceback__ to tb and return zelf. """ // sourcery: pymethod = with_traceback, doc = withTracebackDoc internal static func with_traceback(_ py: Py, zelf _zelf: PyObject, traceback: PyObject?) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "with_traceback") } if let error = zelf.setTraceback(py, value: traceback) { return .error(error) } return PyResult(zelf) } // MARK: - Cause internal static let getCauseDoc = "exception cause" // sourcery: pyproperty = __cause__, setter, doc = getCauseDoc internal static func __cause__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__cause__") } return PyResult(py, zelf.cause) } internal func getCause() -> PyBaseException? { return self.cause } internal static func __cause__(_ py: Py, zelf _zelf: PyObject, value: PyObject?) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__cause__") } guard let value = value else { // set to 'None' instead return .typeError(py, message: "__cause__ may not be deleted") } if py.cast.isNone(value) { zelf.delCause() return .none(py) } if let e = py.cast.asBaseException(value) { zelf.setCause(e) return .none(py) } let message = "exception cause must be None or derive from BaseException" return .typeError(py, message: message) } internal func setCause(_ value: PyBaseException) { // https://www.python.org/dev/peps/pep-0415/#proposal self.suppressContext = true self.cause = value } internal func delCause() { self.cause = nil } // MARK: - Context internal static let getContextDoc = "exception context" // sourcery: pyproperty = __context__, setter, doc = getContextDoc internal static func __context__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__context__") } let result = zelf.getContext() return PyResult(py, result) } internal func getContext() -> PyBaseException? { return self.context } internal static func __context__(_ py: Py, zelf _zelf: PyObject, value: PyObject?) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__context__") } guard let value = value else { return .typeError(py, message: "__context__ may not be deleted") // use 'None' } if py.cast.isNone(value) { zelf.delContext() return .none(py) } if let context = py.cast.asBaseException(value) { zelf.setContext(context) return .none(py) } let message = "exception context must be None or derive from BaseException" return .typeError(py, message: message) } internal func setContext(_ value: PyBaseException) { // When we are just setting the '__context__' property we are allowed // to have cycles: // // elsa = NotImplementedError('elsa') // anna = NotImplementedError('anna') // // elsa.__context__ = anna # Just setting the property, nothing fancy // anna.__context__ = elsa // // assert elsa.__context__ == anna // assert anna.__context__ == elsa self.setContext(value, checkAndPossiblyBreakCycle: false) } /// What are those `cycles` and where can I (not) get one? /// /// So, when we want to set exception as `__context__`, it is possible /// that this exception is already in an exception stack. /// For example: `e1.__context__` is `e2` and we try to set /// `e2.__context__` to `e1`. /// /// Note that for just an ordinary assignment (`elsa.__context__ = anna`) /// cycles are allowed, so here we are just talking about `raise/except`. /// /// Run this: /// ``` py /// elsa = NotImplementedError('elsa') /// anna = NotImplementedError('anna') /// /// try: /// try: /// try: /// raise elsa /// except: /// # this will set: anna.__context__ = elsa /// raise anna /// except: /// # this will set: elsa.__context__ = anna /// # but we can't do that because: anna.__context__ = elsa /// # we have to clear: anna.__context__ = None /// raise elsa /// except: /// assert elsa.__context__ == anna /// assert anna.__context__ == None # Yep, it is 'None'! /// ``` /// /// Also, setting itself as a `__context__` should not work: /// /// ```py /// try: /// try: /// raise elsa /// except: /// raise elsa /// except: /// assert elsa.__context__ == None /// ``` internal func setContext(_ value: PyBaseException, checkAndPossiblyBreakCycle: Bool) { if checkAndPossiblyBreakCycle { if value.ptr === self.ptr { // Setting itself as a '__context__' should not change existing context. // try: // try: // elsa.__context__ = anna # Change 'anna' -> 'elsa' to get infinite loop // raise elsa // except: // # Normally this should set 'elsa.__context__ = elsa' // # But it will not do this, because that would be a cycle. // raise elsa // except: // assert elsa.__context__ == anna # Context is still 'anna' return } self.avoidCycleInContexts(with: value) } // quite boring, compared to all of the fanciness above self.context = value } private func avoidCycleInContexts(with other: PyBaseException) { var current = other // Traverse contexts down/up (however you want to call it) looking for 'self'. while let context = current.context { if context.ptr === self.ptr { // Clear context // We can return, because when setting 'context' exception // we also ran 'avoidCycleInContext' // (or the user tempered with context manually, so all bets are off). current.delContext() return } current = context } } private func delContext() { self.context = nil } // MARK: - Suppress context // sourcery: pyproperty = __suppress_context__, setter internal static func __suppress_context__(_ py: Py, zelf _zelf: PyObject) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__suppress_context__") } let result = zelf.getSuppressContext() return PyResult(py, result) } internal func getSuppressContext() -> Bool { return self.suppressContext } internal static func __suppress_context__(_ py: Py, zelf _zelf: PyObject, value: PyObject?) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__suppress_context__") } guard let value = value else { zelf.suppressContext = false return .none(py) } switch py.isTrueBool(object: value) { case let .value(b): zelf.suppressContext = b return .none(py) case let .error(e): return .error(e) } } // MARK: - Python new // sourcery: pystaticmethod = __new__ internal static func __new__(_ py: Py, type: PyType, args: [PyObject], kwargs: PyDict?) -> PyResult { let argsTuple = py.newTuple(elements: args) let result = py.memory.newBaseException(type: type, args: argsTuple) return PyResult(result) } // MARK: - Python init // sourcery: pymethod = __init__ internal static func __init__(_ py: Py, zelf _zelf: PyObject, args: [PyObject], kwargs: PyDict?) -> PyResult { guard let zelf = Self.downcast(py, _zelf) else { return Self.invalidZelfArgument(py, _zelf, "__init__") } // Copy args if needed if !zelf.areArgsEqual(to: args) { let argsTuple = py.newTuple(elements: args) zelf.setArgs(argsTuple) } // Copy kwargs if let kwargs = kwargs { let dict = py.get__dict__(error: zelf) if let e = dict.update(py, from: kwargs.elements, onKeyDuplicate: .continue) { return .error(e) } } return .none(py) } private func areArgsEqual(to objects: [PyObject]) -> Bool { let selfArgs = self.args.elements return selfArgs.count == objects.count && zip(selfArgs, objects).allSatisfy { $0.0.ptr === $0.1.ptr } } }
28.821006
92
0.617564
f90d407f614093f6d9888b1dab379e85250a8dc0
2,277
sql
SQL
Eva Version 1/01 - Planilla Quincenal/03 - Factores/37 - EvoData - OtrosDescuentos.sql
mbustamanteAseinfo/configManager
dd3a2a179d3db51b9dc59a6b44b9644fa0a2271e
[ "MIT" ]
null
null
null
Eva Version 1/01 - Planilla Quincenal/03 - Factores/37 - EvoData - OtrosDescuentos.sql
mbustamanteAseinfo/configManager
dd3a2a179d3db51b9dc59a6b44b9644fa0a2271e
[ "MIT" ]
null
null
null
Eva Version 1/01 - Planilla Quincenal/03 - Factores/37 - EvoData - OtrosDescuentos.sql
mbustamanteAseinfo/configManager
dd3a2a179d3db51b9dc59a6b44b9644fa0a2271e
[ "MIT" ]
1
2017-01-24T13:23:39.000Z
2017-01-24T13:23:39.000Z
/* Script Generado por Evolution - Editor de Formulación de Planillas. 16-01-2017 11:50 AM */ begin transaction delete from [sal].[fac_factores] where [fac_codigo] = '9559bb84-5dfe-4a9d-aad8-f581d8cbe0f4'; insert into [sal].[fac_factores] ([fac_codigo],[fac_id],[fac_descripcion],[fac_vbscript],[fac_codfld],[fac_codpai],[fac_size]) values ('9559bb84-5dfe-4a9d-aad8-f581d8cbe0f4','OtrosDescuentos','Procesa Otros Descuentos asociados al periodo de pago','Function OtrosDescuentos() liquido = Factores("SalarioBruto").Value - _ Factores("SeguroSocial").Value - _ Factores("SegEducativo").Value - _ Factores("ISR").Value sum = 0 valor = 0 horas = 0.00 if Emp_OtrosDescuentos.RecordCount > 0 then Emp_OtrosDescuentos.MoveFirst do until Emp_OtrosDescuentos.EOF valor = round(Emp_OtrosDescuentos.Fields("ods_valor_a_descontar").Value, 2) horas = CDbl(Emp_OtrosDescuentos.Fields("ods_num_horas").Value) if valor > liquido then Emp_OtrosDescuentos.Fields("ods_aplicado_planilla").Value = 0 else liquido = liquido - valor sum = sum + valor Emp_OtrosDescuentos.Fields("ods_aplicado_planilla").Value = 1 if horas > 0 then agrega_descuentos_historial Agrupadores, _ DescuentosEstaPlanilla, _ Emp_InfoSalario.Fields("EMP_CODIGO").Value, _ Pla_Periodo.Fields("PPL_CODPPL").Value, _ Emp_OtrosDescuentos.Fields("ODS_CODTDC").Value, _ valor, 0, 0, "PAB", horas, "Horas" else agrega_descuentos_historial Agrupadores, _ DescuentosEstaPlanilla, _ Emp_InfoSalario.Fields("EMP_CODIGO").Value, _ Pla_Periodo.Fields("PPL_CODPPL").Value, _ Emp_OtrosDescuentos.Fields("ODS_CODTDC").Value, _ valor, 0, 0, "PAB", 0, "" end if end if Emp_OtrosDescuentos.MoveNext loop end if OtrosDescuentos = sum End Function','double','pa',0); commit transaction;
42.166667
275
0.594203
d2e7a81b393956889220ef385a83312ad9953d65
303
asm
Assembly
data/wild/maps/Route13.asm
opiter09/ASM-Machina
75d8e457b3e82cc7a99b8e70ada643ab02863ada
[ "CC0-1.0" ]
1
2022-02-15T00:19:44.000Z
2022-02-15T00:19:44.000Z
data/wild/maps/Route13.asm
opiter09/ASM-Machina
75d8e457b3e82cc7a99b8e70ada643ab02863ada
[ "CC0-1.0" ]
null
null
null
data/wild/maps/Route13.asm
opiter09/ASM-Machina
75d8e457b3e82cc7a99b8e70ada643ab02863ada
[ "CC0-1.0" ]
null
null
null
Route13WildMons: def_grass_wildmons 20 ; encounter rate db 33, FEAROW db 34, POLIWHIRL db 32, POLIWHIRL db 35, MANKEY db 34, WEEPINBELL db 33, GOLBAT db 36, DITTO db 37, PIDGEOTTO db 38, DUGTRIO db 41, CHARIZARD end_grass_wildmons def_water_wildmons 0 ; encounter rate end_water_wildmons
17.823529
39
0.765677
0c8aee4b13af709adea28d410ab48e9fcca43ac4
83
py
Python
pyqt_horizontal_selection_square_graphics_view/__init__.py
berty-2007/pyqt-horizontal-selection-square-graphics-view
29d3d6f63a2d464b0c4b1d64c451439de6f1eded
[ "MIT" ]
1
2021-12-23T14:44:07.000Z
2021-12-23T14:44:07.000Z
pyqt_horizontal_selection_square_graphics_view/__init__.py
berty-2007/pyqt-horizontal-selection-square-graphics-view
29d3d6f63a2d464b0c4b1d64c451439de6f1eded
[ "MIT" ]
null
null
null
pyqt_horizontal_selection_square_graphics_view/__init__.py
berty-2007/pyqt-horizontal-selection-square-graphics-view
29d3d6f63a2d464b0c4b1d64c451439de6f1eded
[ "MIT" ]
null
null
null
from .horizontalSelectionSquareGraphicsView import * from .selectionSquare import *
41.5
52
0.86747
38e9a723f3f65a673ab544f9f204cf84113134b2
2,221
swift
Swift
ios/Classes/Settings/Security/Views/SecuritySettingsView.swift
MikeOwino/algorand-wallet
fbf93582d06dd1c46d7114a1ee686bfecca4ec18
[ "Apache-2.0" ]
14
2022-02-20T12:14:39.000Z
2022-03-28T11:05:19.000Z
ios/Classes/Settings/Security/Views/SecuritySettingsView.swift
perawallet/pera-wallet
fbf93582d06dd1c46d7114a1ee686bfecca4ec18
[ "Apache-2.0" ]
10
2022-02-23T08:48:52.000Z
2022-03-31T08:49:11.000Z
ios/Classes/Settings/Security/Views/SecuritySettingsView.swift
perawallet/algorand-wallet
ecacd9f00dd49bce912e0961c50fe77d2d071dce
[ "Apache-2.0" ]
3
2022-03-03T14:19:38.000Z
2022-03-13T14:34:47.000Z
// Copyright 2022 Pera Wallet, LDA // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SecuritySettingsView.swift import UIKit import MacaroonUIKit final class SecuritySettingsView: View { private lazy var theme = SecuritySettingsViewTheme() private(set) lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumLineSpacing = theme.cellSpacing flowLayout.sectionInset = UIEdgeInsets(theme.sectionInset) let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = theme.backgroundColor.uiColor collectionView.register(SettingsDetailCell.self) collectionView.register(SettingsToggleCell.self) collectionView.register(header: SingleGrayTitleHeaderSuplementaryView.self) return collectionView }() override init(frame: CGRect) { super.init(frame: frame) customize(theme) } func customize(_ theme: SecuritySettingsViewTheme) { customizeBaseAppearance(backgroundColor: theme.backgroundColor) addCollectionView() } func customizeAppearance(_ styleSheet: StyleSheet) {} func prepareLayout(_ layoutSheet: LayoutSheet) {} } extension SecuritySettingsView { private func addCollectionView() { addSubview(collectionView) collectionView.snp.makeConstraints { $0.top.equalToSuperview().inset(theme.topInset) $0.leading.trailing.bottom.equalToSuperview() } } }
34.703125
93
0.722647
769994e9a29379aabe68ab24749157b02dfaccba
229
sql
SQL
script/block-schema.sql
joshtechnologygroup/blockchain
479dd6527164b2e1b6e086c28e9a9955ed49aa94
[ "MIT" ]
null
null
null
script/block-schema.sql
joshtechnologygroup/blockchain
479dd6527164b2e1b6e086c28e9a9955ed49aa94
[ "MIT" ]
null
null
null
script/block-schema.sql
joshtechnologygroup/blockchain
479dd6527164b2e1b6e086c28e9a9955ed49aa94
[ "MIT" ]
2
2018-02-25T18:56:03.000Z
2018-10-21T01:40:17.000Z
CREATE TABLE IF NOT EXISTS block ( index serial primary key, hash varchar not null, previous_hash varchar not null, payload jsonb not null, timestamp timestamp not null );
28.625
39
0.598253
81070d953ec7381f828d8ed420856493dead8c86
18,977
swift
Swift
p2p_wallet/Scenes/Main/TransactionInfo/TransactionInfoRootView.swift
opencompute/p2p-wallet-ios
8714702b1c53d6a0a5cd37b1dbfaf4bfa3366417
[ "MIT" ]
null
null
null
p2p_wallet/Scenes/Main/TransactionInfo/TransactionInfoRootView.swift
opencompute/p2p-wallet-ios
8714702b1c53d6a0a5cd37b1dbfaf4bfa3366417
[ "MIT" ]
null
null
null
p2p_wallet/Scenes/Main/TransactionInfo/TransactionInfoRootView.swift
opencompute/p2p-wallet-ios
8714702b1c53d6a0a5cd37b1dbfaf4bfa3366417
[ "MIT" ]
null
null
null
// // TransactionInfoRootView.swift // p2p_wallet // // Created by Chung Tran on 08/04/2021. // import UIKit import RxSwift class TransactionInfoRootView: ScrollableVStackRootView { // MARK: - Constants // MARK: - Properties private let viewModel: TransactionInfoViewModel let disposeBag = DisposeBag() // MARK: - Headers lazy var headerView = UIStackView(axis: .vertical, spacing: 5, alignment: .fill, distribution: .fill, arrangedSubviews: [ // type transactionTypeLabel, // timestamp transactionTimestampLabel ]) .padding(.init(top: 30, left: 20, bottom: 54, right: 20)) private lazy var transactionTypeLabel = UILabel(textSize: 21, weight: .semibold, textAlignment: .center) private lazy var transactionTimestampLabel = UILabel(textSize: 13, weight: .medium, textColor: .textSecondary, textAlignment: .center) private lazy var transactionIconImageView = UIImageView(width: 30, height: 30, tintColor: .white) // MARK: - SummaryViews private lazy var defaultSummaryView = DefaultTransactionSummaryView(forAutoLayout: ()) private lazy var swapSummaryView = SwapTransactionSummaryView(forAutoLayout: ()) // MARK: - Status view private lazy var statusView = TransactionStatusView() // MARK: - Sections private lazy var fromToSectionsView = UIStackView(axis: .vertical, spacing: 0, alignment: .fill, distribution: .fill) private lazy var transactionDetailView = UIStackView(axis: .vertical, spacing: 0, alignment: .fill, distribution: .fill) private lazy var transactionIdSection = createTransactionIdSection(signatureLabel: signatureLabel) private lazy var blockNumSection = createLabelsOnlySection(title: L10n.blockNumber) private lazy var feeSection = createFeeSection() // private lazy var transactionFromSection = createLabelsOnlySection(title: L10n.from) // private lazy var sourcePubkeyLabel = UILabel(weight: .semibold) // private lazy var destinationPubkeyLabel = UILabel(weight: .semibold) // private lazy var amountDetailLabel = sectionContent() // private lazy var valueLabel = sectionContent() // private lazy var blockNumLabel = sectionContent() private lazy var signatureLabel = UILabel(weight: .semibold, numberOfLines: 0) private lazy var toggleShowHideTransactionDetailsButton = WLButton.stepButton(enabledColor: .grayPanel, textColor: .a3a5baStatic.onDarkMode(.white), label: L10n.showTransactionDetails) // MARK: - Initializers init(viewModel: TransactionInfoViewModel) { self.viewModel = viewModel super.init(frame: .zero) } // MARK: - Methods override func commonInit() { super.commonInit() layout() bind() } // MARK: - Layout private func layout() { // header addSubview(headerView) headerView.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .bottom) // configure scroll view scrollView.contentInset.left = 0 scrollView.contentInset.right = 0 scrollView.contentInset.top = 56 scrollView.contentInset.bottom = 20 scrollView.constraintToSuperviewWithAttribute(.top)?.isActive = false headerView.autoPinEdge(.bottom, to: .top, of: scrollView) // icon addSubview( transactionIconImageView .padding(.init(all: 16), backgroundColor: .h5887ff, cornerRadius: 12) ) transactionIconImageView.wrapper?.autoAlignAxis(toSuperviewAxis: .vertical) transactionIconImageView.wrapper?.autoPinEdge(.top, to: .bottom, of: headerView, withOffset: -28) // separator let separator = UIView.defaultSeparator() addSubview(separator) separator.autoPinEdge(toSuperviewEdge: .leading) separator.autoPinEdge(toSuperviewEdge: .trailing) separator.autoAlignAxis(.horizontal, toSameAxisOf: transactionIconImageView) // setup content stackView.spacing = 0 stackView.addArrangedSubviews { // status statusView.centeredHorizontallyView BEStackViewSpacing(30) // from/to fromToSectionsView // detail transactionDetailView // sections transactionIdSection // buttons UIView.defaultSeparator() BEStackViewSpacing(20) toggleShowHideTransactionDetailsButton .onTap(viewModel, action: #selector(TransactionInfoViewModel.toggleShowDetailTransaction)) .padding(.init(x: 20, y: 0)) } } private func bind() { let transactionDriver = viewModel.transaction.asDriver() let showDetailTransactionDriver = viewModel.showDetailTransaction.asDriver() // header transactionDriver .drive(onNext: {[weak self] transaction in self?.transactionTypeLabel.text = transaction.label self?.transactionTimestampLabel.text = transaction.blockTime?.string(withFormat: "dd MMM yyyy @ HH:mm a") self?.transactionIconImageView.image = transaction.icon }) .disposed(by: disposeBag) // setUp transactionDriver .drive(onNext: {[weak self] transaction in self?.setUp(transaction: transaction) }) .disposed(by: disposeBag) // detail showDetailTransactionDriver .map {!$0} .drive(transactionDetailView.rx.isHidden) .disposed(by: disposeBag) showDetailTransactionDriver .map {$0 ? L10n.hideTransactionDetails: L10n.showTransactionDetails} .drive(toggleShowHideTransactionDetailsButton.rx.title(for: .normal)) .disposed(by: disposeBag) // signature transactionDriver .map {$0.signature} .drive(signatureLabel.rx.text) .disposed(by: disposeBag) } private func setUp(transaction: SolanaSDK.ParsedTransaction?) { guard let transaction = transaction else {return} // summary if let summaryView = stackView.arrangedSubviews.first as? TransactionSummaryView { summaryView.superview?.removeFromSuperview() } // transaction detail view transactionDetailView.arrangedSubviews.forEach {$0.removeFromSuperview()} // if detail shown blockNumSection.contentView.text = "#\(transaction.slot ?? 0)" feeSection.contentView.text = "\(transaction.fee ?? 0)" + " lamports" // status statusView.setUp(status: transaction.status) // modify switch transaction.value { case let transaction as SolanaSDK.SwapTransaction: setUpWithSwapTransaction(transaction) default: setUpWithOtherTransaction(transaction) } } private func setUpWithSwapTransaction(_ transaction: SolanaSDK.SwapTransaction) { var index = 0 stackView.insertArrangedSubviewsWithCustomSpacing( [ swapSummaryView, BEStackViewSpacing(24) ], at: &index ) swapSummaryView.setUp( from: transaction.source?.token, to: transaction.destination?.token, inputAmount: transaction.sourceAmount?.toLamport(decimals: transaction.source?.token.decimals ?? 0), estimatedAmount: transaction.destinationAmount?.toLamport(decimals: transaction.destination?.token.decimals ?? 0) ) let fromSection = createLabelsOnlySection(title: L10n.from) fromSection.contentView.text = transaction.source?.pubkey let toSection = createLabelsOnlySection(title: L10n.to) toSection.contentView.text = transaction.destination?.pubkey let amountSection = createLabelsOnlySection(title: L10n.amount.uppercaseFirst) var amountText: String = transaction.sourceAmount .toString(maximumFractionDigits: 9, showMinus: false) amountText += " " amountText += transaction.source?.token.symbol ?? "" amountText += " \(L10n.to.lowercased()) " amountText += transaction.destinationAmount .toString(maximumFractionDigits: 9, showMinus: false) amountText += " " amountText += transaction.destination?.token.symbol ?? "" amountSection.contentView.text = amountText fromToSectionsView.isHidden = true transactionDetailView.addArrangedSubviews([ fromSection, toSection, amountSection, feeSection, blockNumSection ]) } private func setUpWithOtherTransaction(_ transaction: SolanaSDK.ParsedTransaction) { var index = 0 stackView.insertArrangedSubviewsWithCustomSpacing( [ defaultSummaryView, BEStackViewSpacing(24) ], at: &index ) defaultSummaryView.amountInFiatLabel.text = transaction.amountInFiat.toString(maximumFractionDigits: 9, showPlus: true) + " " + Defaults.fiat.symbol defaultSummaryView.amountInTokenLabel.text = transaction.amount.toString(maximumFractionDigits: 9, showPlus: true) + " " + transaction.symbol // disable fee for receive action var shouldAddFeeSection = true var wasPaidByP2POrg = false switch transaction.value { case let transferTransaction as SolanaSDK.TransferTransaction: var fromIconView: UIView? var toIconView: UIView? var fromFirstText: String? var toFirstText: String? let coinLogoImageView = CoinLogoImageView(size: 45) wasPaidByP2POrg = transferTransaction.wasPaidByP2POrg switch transferTransaction.transferType { case .send: coinLogoImageView.setUp(token: transferTransaction.source?.token) fromIconView = coinLogoImageView toIconView = UIImageView(width: 25, height: 25, image: .walletIcon, tintColor: .iconSecondary) .padding(.init(all: 10), backgroundColor: .grayPanel, cornerRadius: 12) fromFirstText = transferTransaction.source?.token.symbol toFirstText = L10n.wallet case .receive: shouldAddFeeSection = false fromIconView = UIImageView(width: 25, height: 25, image: .walletIcon, tintColor: .iconSecondary) .padding(.init(all: 10), backgroundColor: .grayPanel, cornerRadius: 12) coinLogoImageView.setUp(token: transferTransaction.destination?.token) toIconView = coinLogoImageView fromFirstText = L10n.wallet toFirstText = transferTransaction.destination?.token.symbol default: fromIconView = UIImageView(width: 25, height: 25, image: .walletIcon, tintColor: .iconSecondary) .padding(.init(all: 10), backgroundColor: .grayPanel, cornerRadius: 12) toIconView = UIImageView(width: 25, height: 25, image: .walletIcon, tintColor: .iconSecondary) .padding(.init(all: 10), backgroundColor: .grayPanel, cornerRadius: 12) } fromToSectionsView.addArrangedSubviews { createWalletInfo( title: L10n.from, iconView: fromIconView, firstText: fromFirstText, secondText: transferTransaction.authority ?? transferTransaction.source?.pubkey, selector: #selector( TransactionInfoViewModel.copySourceAddressToClipboard ) ) createWalletInfo( title: L10n.to, iconView: toIconView, firstText: toFirstText, secondText: transferTransaction.destinationAuthority ?? transferTransaction.destination?.pubkey, selector: #selector( TransactionInfoViewModel.copyDestinationAddressToClipboard ) ) } case let createAccountTransaction as SolanaSDK.CreateAccountTransaction: fromToSectionsView.addArrangedSubview( createWalletInfo( title: L10n.newWallet, iconView: CoinLogoImageView(size: 45) .with(token: createAccountTransaction.newWallet?.token), firstText: createAccountTransaction.newWallet?.token.symbol, secondText: createAccountTransaction.newWallet?.pubkey?.truncatingMiddle() ) ) case let closedAccountTransaction as SolanaSDK.CloseAccountTransaction: fromToSectionsView.addArrangedSubview( createWalletInfo( title: L10n.closedWallet, iconView: CoinLogoImageView(size: 45) .with(token: closedAccountTransaction.closedWallet?.token), firstText: closedAccountTransaction.closedWallet?.token.symbol, secondText: closedAccountTransaction.closedWallet?.pubkey?.truncatingMiddle() ) ) default: fromToSectionsView.isHidden = true } transactionDetailView.addArrangedSubviews([ createLabelsOnlySection( title: L10n.amount.uppercaseFirst, content: transaction.amount.toString(maximumFractionDigits: 9, showMinus: false) + " " + transaction.symbol ), createLabelsOnlySection( title: L10n.value, content: "\(Defaults.fiat.symbol) " + transaction.amountInFiat?.toString(maximumFractionDigits: 9, showMinus: false) ) ]) if shouldAddFeeSection { transactionDetailView.addArrangedSubview(feeSection) feeSection.titleView.arrangedSubviews.first(where: {$0.tag == 2})?.isHidden = !wasPaidByP2POrg } transactionDetailView.addArrangedSubview(blockNumSection) } } // MARK: - View builders private extension TransactionInfoRootView { func createLabelsOnlySection(title: String, content: String? = nil) -> TransactionInfoSection<UILabel, UILabel> { let section = TransactionInfoSection( titleView: createSectionTitle(title), contentView: createContentLabel() ) section.contentView.text = content return section } func createFeeSection() -> TransactionInfoSection<UIStackView, UILabel> { TransactionInfoSection( titleView: UIStackView(axis: .horizontal, spacing: 10, alignment: .center, distribution: .equalSpacing, builder: { createSectionTitle(L10n.fee) UILabel(text: L10n.PaidByP2p.org, textSize: 13, weight: .semibold, textColor: .h5887ff) .padding(.init(x: 8, y: 2), backgroundColor: .eff3ff, cornerRadius: 4) .withTag(2) .hidden() }), contentView: createContentLabel() ) } func createTransactionIdSection(signatureLabel: UILabel) -> TransactionInfoSection<UILabel, UIStackView> { TransactionInfoSection( titleView: createSectionTitle(L10n.transactionID), contentView: UIStackView( axis: .horizontal, spacing: 16, alignment: .center, distribution: .fill, arrangedSubviews: [ signatureLabel, UIImageView(width: 16, height: 16, image: .link, tintColor: .iconSecondary) .padding( .init(all: 10), backgroundColor: UIColor.a3a5ba.withAlphaComponent(0.1).onDarkMode(.grayPanel), cornerRadius: 12 ) .onTap(viewModel, action: #selector(TransactionInfoViewModel.showExplorer)) ] ) ) } func createWalletInfo( title: String, iconView: UIView?, firstText: String?, secondText: String?, selector: Selector? = nil ) -> TransactionInfoSection<UILabel, UIStackView> { var arrangedSubviews: [BEStackViewElement] = [] if let iconView = iconView { arrangedSubviews.append(iconView) } arrangedSubviews.append( UIStackView(axis: .vertical, spacing: 7, alignment: .fill, distribution: .fill, arrangedSubviews: [ UILabel(text: firstText, textSize: 17, weight: .semibold), UILabel(text: secondText, weight: .semibold, textColor: .textSecondary) ]) ) if let selector = selector { arrangedSubviews.append( UIImageView(width: 24, height: 24, image: .copyToClipboard, tintColor: .iconSecondary) .padding( .init(all: 6), backgroundColor: UIColor.a3a5ba.withAlphaComponent(0.1).onDarkMode(.grayPanel), cornerRadius: 12 ) .onTap(viewModel, action: selector) ) } let section = TransactionInfoSection( titleView: createSectionTitle(title), contentView: UIStackView( axis: .horizontal, spacing: 16, alignment: .center, distribution: .fill, arrangedSubviews: arrangedSubviews ) ) section.spacing = 20 return section } func createSectionTitle(_ title: String?) -> UILabel { UILabel(text: title, textSize: 13, weight: .medium, textColor: .textSecondary) } func createContentLabel() -> UILabel { UILabel(weight: .semibold, numberOfLines: 0) } } extension TransactionInfoRootView { override func fittingHeight(targetWidth: CGFloat) -> CGFloat { super.fittingHeight(targetWidth: targetWidth) + headerView.fittingHeight(targetWidth: targetWidth) } }
40.376596
188
0.600516
0cfdd69003365202954e59ba474c596cdd274c91
10,386
py
Python
stanCode_Projects/break_out_game/breakoutgraphics.py
kunyi1022/sc-projects
0ab0019b2cdc86c434a0acff39b862263dcbc970
[ "MIT" ]
null
null
null
stanCode_Projects/break_out_game/breakoutgraphics.py
kunyi1022/sc-projects
0ab0019b2cdc86c434a0acff39b862263dcbc970
[ "MIT" ]
null
null
null
stanCode_Projects/break_out_game/breakoutgraphics.py
kunyi1022/sc-projects
0ab0019b2cdc86c434a0acff39b862263dcbc970
[ "MIT" ]
null
null
null
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao File: breakoutgraphics.py Name: 林坤毅 Jordan ------------------------- This python file will create a class named BreakoutGraphics for the break out game. This class will contain the building block for creating that game. """ from campy.graphics.gwindow import GWindow from campy.graphics.gobjects import GOval, GRect, GLabel from campy.gui.events.mouse import onmouseclicked, onmousemoved import random BRICK_SPACING = 5 # Space between bricks (in pixels). This space is used for horizontal and vertical spacing. BRICK_WIDTH = 40 # Height of a brick (in pixels). BRICK_HEIGHT = 15 # Height of a brick (in pixels). BRICK_ROWS = 10 # Number of rows of bricks. BRICK_COLS = 10 # Number of columns of bricks. BRICK_OFFSET = 50 # Vertical offset of the topmost brick from the window top (in pixels). BALL_RADIUS = 10 # Radius of the ball (in pixels). PADDLE_WIDTH = 75 # Width of the paddle (in pixels). PADDLE_HEIGHT = 15 # Height of the paddle (in pixels). PADDLE_OFFSET = 50 # Vertical offset of the paddle from the window bottom (in pixels). INITIAL_Y_SPEED = 7 # Initial vertical speed for the ball. MAX_X_SPEED = 5 # Maximum initial horizontal speed for the ball. class BreakoutGraphics: def __init__(self, ball_radius = BALL_RADIUS, paddle_width = PADDLE_WIDTH, paddle_height = PADDLE_HEIGHT, paddle_offset = PADDLE_OFFSET, brick_rows = BRICK_ROWS, brick_cols = BRICK_COLS, brick_width = BRICK_WIDTH, brick_height = BRICK_HEIGHT, brick_offset = BRICK_OFFSET, brick_spacing = BRICK_SPACING, title='Breakout'): """ The basic parameters for building these breakout game. :param ball_radius: The radius of the ball. :param paddle_width: The width of the paddle. :param paddle_height: The height of the paddle. :param paddle_offset: The distance between paddle and the bottom of the window. :param brick_rows: The number of rows in bricks. :param brick_cols: The number of column in bricks. :param brick_width: The width of each brick. :param brick_height: The height of each brick. :param brick_offset: The distance between the first row of bricks and the top of the window. :param brick_spacing: The spacing between each brick. :param title: The name of this program. """ # Create a graphical window, with some extra space self.window_width = brick_cols * (brick_width + brick_spacing) - brick_spacing self.window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing) self.window = GWindow(width=self.window_width, height=self.window_height, title=title) # Create a paddle self.paddle = GRect(paddle_width, paddle_height, x=(self.window_width-paddle_width)/2, y=(self.window_height-paddle_offset)) self.paddle.filled = True self.paddle.color = 'black' self.paddle.fill_color = 'black' self.window.add(self.paddle) self.paddle_width = paddle_width self.paddle_height = paddle_height self.paddle_offset = paddle_offset # Center a filled ball in the graphical window self.ball = GOval(ball_radius*2, ball_radius*2, x=(self.window_width-ball_radius*2)/2, y=(self.window_height-ball_radius*2)/2) self.ball.filled = True self.ball.fill_color = 'black' self.window.add(self.ball) self.ball_radius = ball_radius # Default initial velocity for the ball self.__dx = 0 # self.__dx = random.randint(1, MAX_X_SPEED) self.__dy = 0 # self.__dy = INITIAL_Y_SPEED # if random.random() > 0.5: # self.__dx = -self.__dx # The above is the mistake I made during doing this homework. # Draw bricks for i in range(brick_cols): for j in range(brick_rows): # Crucial point! This can't be placed at the outside of for loop. brick = GRect(brick_width, brick_height) brick.x = (brick_width+brick_spacing)*i brick.y = brick_offset+(brick_height+brick_spacing)*j brick.filled = True if j < 2: brick.fill_color = 'red' elif j < 4: brick.fill_color = 'orange' elif j < 6: brick.fill_color = 'yellow' elif j < 8: brick.fill_color = 'green' elif j < 10: brick.fill_color = 'blue' elif j < 12: brick.fill_color = 'teal' elif j < 14: brick.fill_color = 'chocolate' self.window.add(brick) # Initialize our mouse listeners onmouseclicked(self.is_start_game) onmousemoved(self.moving_paddle) # Total bricks self.total_bricks = brick_cols * brick_rows def is_start_game(self, event): # Crucial point!!! Stuck here for three days! The initial velocity! """ The check point of the game start. :param event: The information of the mouse, including (x,y) of it. :return: Set the __dx and __dy of the ball. """ if event.x != -1 and event.y != -1 and self.__dx == 0 and self.__dy == 0: self.__dx = random.randint(1, MAX_X_SPEED) self.__dy = INITIAL_Y_SPEED if random.random() > 0.5: self.__dx = -self.__dx def check_for_collisions(self): """ Four check points of the ball to check the collision with objects. :return: boolean value. Build the information of object that the ball collide with. """ one = self.window.get_object_at(self.ball.x, self.ball.y) two = self.window.get_object_at(self.ball.x + 2*self.ball_radius, self.ball.y) three = self.window.get_object_at(self.ball.x, self.ball.y + 2*self.ball_radius) four = self.window.get_object_at(self.ball.x + 2*self.ball_radius, self.ball.y + 2*self.ball_radius) if one is not None: self.obj = self.window.get_object_at(self.ball.x, self.ball.y) return True elif two is not None: self.obj = self.window.get_object_at(self.ball.x + 2*self.ball_radius, self.ball.y) return True elif three is not None: self.obj = self.window.get_object_at(self.ball.x, self.ball.y + 2*self.ball_radius) return True elif four is not None: self.obj = self.window.get_object_at(self.ball.x + 2*self.ball_radius, self.ball.y + 2*self.ball_radius) return True def check_object_type(self): """ The objects above the half of the window height are bricks and the object below the half of the window height is paddle. :return: boolean value. Bricks return True and paddle returns False. """ if self.ball.y > self.window.height/2: return True else: return False def moving_ball(self): """ The method for moving ball. :return: The moving result of the ball. """ self.ball.move(self.__dx, self.__dy) def moving_paddle(self, event): """ The method for moving paddle. :param event: The information of the mouse, including (x,y) of it. :return: The moving result of the paddle. """ if event.x - self.paddle_width/2 >= 0 and event.x-self.paddle_width/2 <= self.window_width-self.paddle_width: self.paddle.x = event.x - self.paddle_width / 2 def reset_ball(self): """ As the ball falls below the paddle and the game hasn't overed, the ball will be reset to the original position. :return: The ball at the original position. """ self.ball = GOval(self.ball_radius * 2, self.ball_radius * 2, x=(self.window_width - self.ball_radius * 2) / 2, y=(self.window_height - self.ball_radius * 2) / 2) self.ball.filled = True self.ball.fill_color = 'black' self.window.add(self.ball) self.ball_radius = self.ball_radius self.__dx = 0 self.__dy = 0 def set_dx(self, new_dx): """ Set the new __dx. :param new_dx: The new dx. :return: __dx. """ self.__dx = new_dx def set_dy(self, new_dy): """ Set the new __dy. :param new_dy: The new dy. :return: __dy. """ self.__dy = new_dy def get_dx(self): """ Get the information of __dx from class BreakoutGraphics. :return: The __dx for the ball. """ return self.__dx def get_dy(self): """ Get the information of __dy from class BreakoutGraphics. :return: The __dy for the ball. """ return self.__dy def set_dx_collision(self, new_dx): """ Set the new __dx for ball after colliding with bricks. :param new_dx: The new dx. :return: __dx. """ if random.random() > 0.5: self.__dx = new_dx else: self.__dx = -new_dx def game_over(self): """ The label for game over. :return: The label for game over. """ label = GLabel('Game Over!!!') # The condition below is for 10*10 bricks. # If coder change the number of rows or columns, the size would probably not fit. label.font = '-40' self.window.add(label, x= self.window_width/2 - 100, y=self.window_height/2 + 100) def game_win(self): """ The label for game win. :return: The label for game win. """ label = GLabel('You Win!!!') # The condition below is for 10*10 bricks. # If coder change the number of rows or columns, the size would probably not fit. label.font = '-40' self.window.add(label, x=self.window_width / 2 - 100, y=self.window_height / 2 + 100)
39.192453
134
0.604756
cdc4dce7f99b2f2387563d57c32951c5b0cf7056
91
rs
Rust
10_constants/src/main.rs
foxx3r/learn_rust
2aab6ea99b5e7a8ef081908618659ccc2d44555e
[ "MIT" ]
null
null
null
10_constants/src/main.rs
foxx3r/learn_rust
2aab6ea99b5e7a8ef081908618659ccc2d44555e
[ "MIT" ]
null
null
null
10_constants/src/main.rs
foxx3r/learn_rust
2aab6ea99b5e7a8ef081908618659ccc2d44555e
[ "MIT" ]
null
null
null
const MAX: i16 = 200; fn main() { for n in 1..MAX { println!("{}", n); } }
13
26
0.417582
7b7da3899d0201188d6dc8520dcfd61629f04197
1,292
css
CSS
data/usercss/165930.user.css
33kk/uso-archive
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
[ "MIT" ]
118
2020-08-28T19:59:28.000Z
2022-03-26T16:28:40.000Z
data/usercss/165930.user.css
33kk/uso-archive
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
[ "MIT" ]
38
2020-09-02T01:08:45.000Z
2022-01-23T02:47:24.000Z
data/usercss/165930.user.css
33kk/uso-archive
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
[ "MIT" ]
21
2020-08-19T01:12:43.000Z
2022-03-15T21:55:17.000Z
/* ==UserStyle== @name MeioBit Dark @namespace USO Archive @author Carlos Cabral @description `MeioBit Dark Theme` @version 20181212.2.22 @license CC-BY-4.0 @preprocessor uso ==/UserStyle== */ @-moz-document domain("meiobit.com") { .banner, .col-articles-list, .elm-button, .post .wp-caption .wp-caption-text, .single-page, body, html { background: #232323!important } #breadcrumbs, .post h1 a, .post h2, .post li a, .post p, .post p a, .sectionh3, .sidebar-featured span, .single-bit-article .caption h2, .single-bit-article .caption p.details, .single-bit-article.bit-sidebar .caption span, body { color: #f5f5f5!important } .post blockquote p { color: #9e9e9e!important } } @-moz-document regexp("https?://disqus\\.com/embed/comments/.*meiobit.com.*") { .dropdown-menu li > a:hover, .tab-conversation.active > a, body { color: #f5f5f5!important } .dropdown-toggle:hover, .label:hover, .nav-tab > a:hover, a:hover { color: #039be5!important } .btn.busy:active, .btn.busy:hover, .dropdown-menu { background: #232323!important } .comment__footer .vote-down, .comment__footer a, .comment__header .vote-down, .comment__header a, .dropdown-toggle, .nav-tab > a { color: #9e9e9e!important } }
20.1875
80
0.664861
0cc92881b3783140afbb04ec688ee09d279aa156
2,794
py
Python
distla/distla_core/distla_core/linalg/qr/test_qr_ooc.py
google/distla_core
7f0d8ab7b847a75e0fc713627488643a8984712a
[ "Apache-2.0" ]
2
2021-12-19T21:17:06.000Z
2021-12-25T09:19:47.000Z
distla/distla_core/distla_core/linalg/qr/test_qr_ooc.py
google/distla_core
7f0d8ab7b847a75e0fc713627488643a8984712a
[ "Apache-2.0" ]
null
null
null
distla/distla_core/distla_core/linalg/qr/test_qr_ooc.py
google/distla_core
7f0d8ab7b847a75e0fc713627488643a8984712a
[ "Apache-2.0" ]
1
2021-12-25T09:19:56.000Z
2021-12-25T09:19:56.000Z
"""Tests for qr.py.""" from jax import lax import jax.numpy as jnp import numpy as np import pytest import tempfile from distla_core.linalg.utils import testutils from distla_core.linalg.qr import qr_ooc from distla_core.utils import pops DTYPE = jnp.float32 seeds = [0, 1] flags = [True, False] def _dephase_qr(R, Q=None): """ Maps the Q and R factor from an arbitrary QR decomposition to the unique with non-negative diagonal entries. """ phases_data = np.sign(np.diagonal(R)) m, n = R.shape if m > n: phases = np.ones(m) phases[:n] = phases_data else: phases = phases_data R = phases.conj()[:, None] * R if Q is not None: Q = Q * phases return Q, R @pytest.mark.parametrize("N", [8, 32, 128]) @pytest.mark.parametrize("aspect_ratio", [1, 2, 10]) @pytest.mark.parametrize("panel_size", [1, 2]) @pytest.mark.parametrize("seed", [0, 1]) def test_qr_ooc(N, aspect_ratio, panel_size, seed): dtype = np.float32 M = N * aspect_ratio np.random.seed(seed) A = np.random.randn(M, N).astype(dtype) _, expected = np.linalg.qr(A) _, expected = _dephase_qr(expected) with tempfile.NamedTemporaryFile(delete=False) as f: np.save(f, A) f.close() # Explicit close needed to open again as a memmap. # The file is still deleted when the context goes out of scope. result = qr_ooc.qr_ooc(f.name, caqr_panel_size=panel_size) result = pops.undistribute(result) _, result = _dephase_qr(result) atol = testutils.eps(lax.Precision.HIGHEST, dtype=dtype) atol *= np.linalg.norm(A) ** 2 testutils.assert_allclose(result, expected, atol=atol) @pytest.mark.parametrize("N", [8, 32, 128]) @pytest.mark.parametrize("aspect_ratio", [1, 2, 10]) @pytest.mark.parametrize("panel_size", [1, 2]) @pytest.mark.parametrize("seed", [0, 1]) def test_fake_cholesky(N, aspect_ratio, panel_size, seed): fname = "fake_cholesky_test_matrix" dtype = np.float32 M = N * aspect_ratio np.random.seed(seed) A = np.random.randn(M, N).astype(dtype) cond = np.linalg.cond(A) expected_gram = np.dot(A.T, A) expected_chol = np.linalg.cholesky(expected_gram).T _, expected_chol = _dephase_qr(expected_chol) np.save(fname, A) fread = fname + ".npy" chol_fname = "cholesky_transpose" gram_fname = "gram_matrix" qr_ooc.fake_cholesky(fread, caqr_panel_size=panel_size, chol_fname=chol_fname, gram_fname=gram_fname) result_gram = np.load(gram_fname + ".npy") result_chol = np.load(chol_fname + ".npy") _, result_chol = _dephase_qr(result_chol) atol = testutils.eps(lax.Precision.HIGHEST, dtype=dtype) atol *= cond * np.linalg.norm(expected_gram) ** 2 testutils.assert_allclose(result_chol, expected_chol, atol=10 * atol) testutils.assert_allclose(result_gram, expected_gram, atol=atol)
30.703297
78
0.700787
e379940be8af47efeb871e1c9d74187c96059eba
363
lua
Lua
Full Speed Swarm/lua/carrydata.lua
NUTIEisBADYT/NUTIEisBADYTS-PD2-Modpack
2d217f41dace5c9ebc2777ccc54d3d8264c272ee
[ "MIT" ]
null
null
null
Full Speed Swarm/lua/carrydata.lua
NUTIEisBADYT/NUTIEisBADYTS-PD2-Modpack
2d217f41dace5c9ebc2777ccc54d3d8264c272ee
[ "MIT" ]
null
null
null
Full Speed Swarm/lua/carrydata.lua
NUTIEisBADYT/NUTIEisBADYTS-PD2-Modpack
2d217f41dace5c9ebc2777ccc54d3d8264c272ee
[ "MIT" ]
3
2020-04-12T11:54:38.000Z
2021-12-20T15:47:08.000Z
local key = ModPath .. ' ' .. RequiredScript if _G[key] then return else _G[key] = true end local fs_original_carrydata_init = CarryData.init function CarryData:init(unit) fs_original_carrydata_init(self, unit) if Network:is_client() or self._carry_id and not self:can_explode() then unit:set_extension_update_enabled(Idstring("carry_data"), false) end end
33
73
0.782369
7303466ad8d5d3e15ad8e7c3991447f0408dcb8f
285
sql
SQL
app/src/androidTest/assets/fixtures.sql
BspbOrg/smartbirds-android
d69af45dd2959b12f89df918647e65fb209a09cd
[ "Apache-2.0" ]
null
null
null
app/src/androidTest/assets/fixtures.sql
BspbOrg/smartbirds-android
d69af45dd2959b12f89df918647e65fb209a09cd
[ "Apache-2.0" ]
183
2019-10-08T06:41:01.000Z
2022-03-25T16:08:17.000Z
app/src/androidTest/assets/fixtures.sql
BspbOrg/smartbirds-android
d69af45dd2959b12f89df918647e65fb209a09cd
[ "Apache-2.0" ]
null
null
null
INSERT INTO zones VALUES('TEST123', 1, '{"coordinates":[{"latitude":42.27038021,"longitude":22.57638592},{"latitude":42.26137738,"longitude":22.57616159},{"latitude":42.26154334,"longitude":22.56404167},{"latitude":42.27054622,"longitude":22.56426427}],"id":"TEST123","locationId":1}')
285
285
0.729825
f0226dfe718e12b1ebfe3c206d874ce8fa4454c9
284
js
JavaScript
widgets/Legend/setting/nls/hr/strings.js
merinogeospatial/arcgis
6b7e0dc7fed15e44ce9b5a192fad6595eb000fee
[ "Apache-2.0", "MIT" ]
null
null
null
widgets/Legend/setting/nls/hr/strings.js
merinogeospatial/arcgis
6b7e0dc7fed15e44ce9b5a192fad6595eb000fee
[ "Apache-2.0", "MIT" ]
null
null
null
widgets/Legend/setting/nls/hr/strings.js
merinogeospatial/arcgis
6b7e0dc7fed15e44ce9b5a192fad6595eb000fee
[ "Apache-2.0", "MIT" ]
null
null
null
define({ "left": "Poravnaj lijevo", "right": "Poravnaj desno", "arrangement": "Raspored", "autoUpdate": "Automatsko ažuriranje", "respectCurrentMapScale": "Poštuj trenutačno mjerilo karte", "layerSelectorTitle": "Izaberite koji će slojevi prikazivati legende: " });
35.5
74
0.700704
d0b2d2c208b7d9148dcbbf31a5903bced1f65bd3
822
asm
Assembly
oeis/297/A297443.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/297/A297443.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/297/A297443.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A297443: a(n) = a(n-1) + 2*a(n-2) - 2*a(n-3) + 3*a(n-4) - 3*a(n-5), where a(0) = 1, a(1) = 3, a(2) = 6, a(3) = 11, a(4) = 20, a(5) = 33. ; Submitted by Jamie Morken(s3) ; 1,3,6,11,20,33,60,101,182,303,546,911,1640,2733,4920,8201,14762,24603,44286,73811,132860,221433,398580,664301,1195742,1992903,3587226,5978711,10761680,17936133,32285040,53808401,96855122,161425203,290565366,484275611,871696100,1452826833,2615088300,4358480501,7845264902,13075441503,23535794706,39226324511,70607384120,117678973533,211822152360,353036920601,635466457082,1059110761803,1906399371246,3177332285411,5719198113740,9531996856233,17157594341220,28595990568701,51472783023662 mov $3,2 lpb $0 sub $0,1 mov $2,$3 add $2,$1 add $2,2 sub $3,$1 sub $3,$1 mov $1,$3 add $3,$2 lpe add $3,$2 mov $1,$3 div $1,4 mov $0,$1 add $0,1
39.142857
487
0.710462
101383a5f4281f2cb193aa86fc80a749e73a21e5
5,541
swift
Swift
Maskara/UI/MaskedTextField.swift
epam-mobile-lab/maskara
723c0a6140a97e3723978b056f158f1bef834e61
[ "Apache-2.0" ]
3
2019-07-01T08:53:48.000Z
2019-10-29T08:26:50.000Z
Maskara/UI/MaskedTextField.swift
epam-mobile-lab/maskara
723c0a6140a97e3723978b056f158f1bef834e61
[ "Apache-2.0" ]
null
null
null
Maskara/UI/MaskedTextField.swift
epam-mobile-lab/maskara
723c0a6140a97e3723978b056f158f1bef834e61
[ "Apache-2.0" ]
null
null
null
// // UIMaskara.swift // Maskara // // Created by Evgeny Kamyshanov on 10/06/2019. // Copyright © 2019 EPAM Systems. All rights reserved. // import Foundation import UIKit open class MaskedTextField: UITextField, UITextFieldDelegate { private var editor: MaskedTextEditor? public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override public init(frame: CGRect) { super.init(frame: frame) self.setup() } private func setup() { autocorrectionType = .no super.delegate = self } public private(set) var maskPattern: String? /// Sets the mask pattern for editing /// /// - Parameter mask: mask pattern string, like "+?D(DDD)DDD-DD-DD" /// - Throws: throws MaskParser.MaskParserError in case of invalid mask pattern open func setMaskPattern(mask: String) throws { editor = try MaskedTextEditor(maskPattern: mask) } /// Enum with clean data without mask chars public var extractedText: ExtractResult? { return editor?.extractedText } /// If true allows to copy/cut clean data without mask chars into Pasteboard public var copyExtracted: Bool = true /// Error handler for handling invalid chars being inserted public var matchErrorHandler: ((Error)->Void)? override open var delegate: UITextFieldDelegate? { get { return internalDelegate } set { internalDelegate = newValue } } // MARK: - Implementation private var internalDelegate: UITextFieldDelegate? override open func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() guard let editor = editor, result else { return result } if text?.isEmpty ?? true { text = editor.text } if let cursorPosition = position(from: beginningOfDocument, offset: 0) { selectedTextRange = textRange(from: cursorPosition, to: cursorPosition) } return true } override open func deleteBackward() { //TODO: just swallow? } override open func paste(_ sender: Any?) { if let string = UIPasteboard.general.string, let selectedRange = self.selectedTextRange { _ = textField(self, shouldChangeCharactersIn: normalizedRange(from: selectedRange), replacementString: string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) } } override open func copy(_ sender: Any?) { if let selectedRange = self.selectedTextRange { let range = normalizedRange(from: selectedRange) if copyExtracted { UIPasteboard.general.string = editor?.extractedText(from: range.location, length: range.length) ?? "" return } UIPasteboard.general.string = editor?.text.substring(from: range.location, length: range.length) ?? "" } } override open func cut(_ sender: Any?) { copy(nil) if let selectedRange = self.selectedTextRange { _ = textField(self, shouldChangeCharactersIn: normalizedRange(from: selectedRange), replacementString: "") } } // MARK: - Implementation internal final func normalizedRange(from textRange: UITextRange) -> NSRange { let start = offset(from: beginningOfDocument, to: textRange.start) let end = offset(from: beginningOfDocument, to: textRange.end) return NSRange(location: min(start, end), length: abs(end - start)) } // MARK: UITextFieldDelegate public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let editor = editor else { return false } do { let cursorPosition = try editor.replace(from: range.location, length: range.length, replacementString: string) text = editor.text if let cursorPosition = position(from: beginningOfDocument, offset: cursorPosition) { selectedTextRange = textRange(from: cursorPosition, to: cursorPosition) } } catch let error { matchErrorHandler?(error) return false } _ = internalDelegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) return false } public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return internalDelegate?.textFieldShouldBeginEditing?(textField) ?? true } public func textFieldDidBeginEditing(_ textField: UITextField) { internalDelegate?.textFieldDidBeginEditing?(textField) } public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return internalDelegate?.textFieldShouldEndEditing?(textField) ?? true } public func textFieldDidEndEditing(_ textField: UITextField) { internalDelegate?.textFieldDidEndEditing?(textField) } public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { internalDelegate?.textFieldDidEndEditing?(textField, reason: reason) } public func textFieldShouldClear(_ textField: UITextField) -> Bool { return internalDelegate?.textFieldShouldClear?(textField) ?? true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return internalDelegate?.textFieldShouldReturn?(textField) ?? true } }
33.179641
182
0.663599
adcf8d8090d30bbb254b1cb3ec83e1c4274e86b3
2,257
rs
Rust
research/gaia-x/pegasus/executor/benches/std_atomic.rs
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
[ "Apache-2.0" ]
1,521
2020-10-28T03:20:24.000Z
2022-03-31T12:42:51.000Z
research/gaia-x/pegasus/executor/benches/std_atomic.rs
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
[ "Apache-2.0" ]
850
2020-12-15T03:17:32.000Z
2022-03-31T11:40:13.000Z
research/gaia-x/pegasus/executor/benches/std_atomic.rs
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
[ "Apache-2.0" ]
180
2020-11-10T03:43:21.000Z
2022-03-28T11:13:31.000Z
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. #![feature(test)] extern crate test; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use test::Bencher; fn fib(n: usize) -> usize { assert!(n <= 10); if n <= 1 { return 1; } else { fib(n - 1) + fib(n - 2) } } #[bench] fn bench_fib(bench: &mut Bencher) { bench.iter(|| { fib(10); }) } #[bench] fn atomic_bool_read(bench: &mut Bencher) { let signal = Arc::new(AtomicBool::new(false)); bench.iter(|| { assert!(!signal.load(Ordering::SeqCst)); }) } #[bench] fn atomic_bool_concurrent_busy_read(bench: &mut Bencher) { let signal = Arc::new(AtomicBool::new(false)); let signal_cp = signal.clone(); let _g = ::std::thread::spawn(move || { while !signal_cp.load(Ordering::SeqCst) { // } }); bench.iter(|| { assert!(!signal.load(Ordering::SeqCst)); }); signal.store(true, Ordering::SeqCst); } #[bench] fn atomic_usize_concurrent_read_with_write(bench: &mut Bencher) { let signal = Arc::new(AtomicBool::new(false)); let signal_usize = Arc::new(AtomicUsize::new(1)); let mut guards = Vec::new(); for i in 0..8 { let signal_cp = signal.clone(); let signal_usize_cp = signal_usize.clone(); guards.push(::std::thread::spawn(move || { while !signal_cp.load(Ordering::SeqCst) { signal_usize_cp.fetch_add(1, Ordering::SeqCst); fib(10); } })); } bench.iter(|| { assert!(signal_usize.load(Ordering::SeqCst) >= 1); }); signal.store(true, Ordering::SeqCst); }
27.52439
76
0.613203
0b9c785217108c50a088739a34c9253315495b39
458
sql
SQL
Faces.sql
jmanzion/jessica-personal-website
68b7cad3f6b82259796f00aee48bbe2b581cd1a2
[ "MIT" ]
null
null
null
Faces.sql
jmanzion/jessica-personal-website
68b7cad3f6b82259796f00aee48bbe2b581cd1a2
[ "MIT" ]
null
null
null
Faces.sql
jmanzion/jessica-personal-website
68b7cad3f6b82259796f00aee48bbe2b581cd1a2
[ "MIT" ]
null
null
null
BEGIN; SET client_encoding = 'UTF8'; #CREATE USER admin WITH PASSWORD 'datascience'; CREATE TABLE Faces ( id integer NOT NULL, name text NOT NULL, path text NOT NULL ); INSERT INTO Faces (id,name,path) VALUES (1,'subject01','subject01.happy.gif'); ALTER TABLE ONLY Faces ADD CONSTRAINT faces_pkey PRIMARY KEY (id); --ALTER TABLE ONLY country --ADD CONSTRAINT country_capital_fkey FOREIGN KEY (capital) REFERENCES city(id); COMMIT;
20.818182
84
0.724891
63ec4c3f190d9b4fb70b067b900766367fb0aed6
4,212
kt
Kotlin
android-views/src/main/kotlin/com/boswelja/ephemeris/views/pager/HeightAdjustingPager.kt
boswelja/Ephemeris
23ea74921e18386de4b81fb635eb4cd9f1b0a11a
[ "MIT" ]
3
2022-02-07T02:48:26.000Z
2022-02-22T10:53:43.000Z
android-views/src/main/kotlin/com/boswelja/ephemeris/views/pager/HeightAdjustingPager.kt
boswelja/Ephemeris
23ea74921e18386de4b81fb635eb4cd9f1b0a11a
[ "MIT" ]
20
2022-03-06T01:31:19.000Z
2022-03-31T08:05:46.000Z
android-views/src/main/kotlin/com/boswelja/ephemeris/views/pager/HeightAdjustingPager.kt
boswelja/Ephemeris
23ea74921e18386de4b81fb635eb4cd9f1b0a11a
[ "MIT" ]
null
null
null
package com.boswelja.ephemeris.views.pager import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.View import android.view.View.MeasureSpec import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.PagerSnapHelper import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator /** * An implementation of [RecyclerView] that provides seemingly infinite left/right paging support. * Implementations of this must subclass [InfinitePagerAdapter] for their adapter. */ internal class HeightAdjustingPager @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RecyclerView(context, attrs, defStyleAttr) { private var snapPositionChangeListener: ((page: Int) -> Unit)? = null private val snapHelper = PagerSnapHelper() /** * The current page that the pager is snapped to. */ var currentPage: Int = 0 private set init { layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) snapHelper.attachToRecyclerView(this) // Disable item change animations, otherwise we get a crossfade when changing a page (itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false } /** * Called when the pager is snapping to a new page. */ private fun onPageSnapping(page: Int) { snapPositionChangeListener?.invoke(page) } fun setOnSnapPositionChangeListener(listener: (page: Int) -> Unit) { snapPositionChangeListener = listener } override fun onScrolled(dx: Int, dy: Int) { super.onScrolled(dx, dy) if (scrollState != SCROLL_STATE_DRAGGING) { val snapTarget = snapHelper.findTargetSnapPosition(layoutManager, dx, dy) if (snapTarget != NO_POSITION) { val snapPage = positionToPage(snapTarget) maybeNotifySnapPositionChange(snapPage) } } } override fun smoothScrollToPosition(position: Int) { super.smoothScrollToPosition(pageToPosition(position)) } override fun scrollToPosition(position: Int) { super.scrollToPosition(pageToPosition(position)) // Since scrollToPosition doesn't actually trigger a scroll state change, we need to manually // notify listeners. Maybe there's a better way of handling this? maybeNotifySnapPositionChange(position) } override fun setAdapter(adapter: Adapter<*>?) { super.setAdapter(adapter) super.scrollToPosition(pageToPosition(currentPage)) } private fun maybeNotifySnapPositionChange(snapPosition: Int) { val snapPositionChanged = currentPage != snapPosition if (snapPositionChanged) { currentPage = snapPosition updateHeight() onPageSnapping(snapPosition) } } private fun updateHeight() { val viewHolder = findViewHolderForLayoutPosition(pageToPosition(currentPage)) if (viewHolder == null) { Log.w("HeightAdjustingPager", "Failed to get the child view holder at page $currentPage") return } // Measure the child val newHeight = viewHolder.itemView.measureForUnboundedHeight() // Apply the new height setHeight(newHeight) } /** * Maps a position from the underlying RecyclerView to a pager page. */ private fun positionToPage(position: Int): Int { return (adapter as InfinitePagerAdapter).positionToPage(position) } /** * Maps a pager page to the underlying RecyclerView position */ private fun pageToPosition(page: Int): Int { return (adapter as InfinitePagerAdapter).pageToPosition(page) } } private fun View.measureForUnboundedHeight(): Int { measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) ) return measuredHeight } private fun View.setHeight(newHeight: Int) { layoutParams = layoutParams.apply { height = newHeight } }
32.90625
101
0.691833
03b8fb6d145f0cf59894925a4f20e93f384ab9f2
1,604
kt
Kotlin
testing/src/main/kotlin/Combinations.kt
AtricoSoftware/atrico.kotlib
273fd90cb345818d0333be205ba46b0950aeb340
[ "MIT" ]
null
null
null
testing/src/main/kotlin/Combinations.kt
AtricoSoftware/atrico.kotlib
273fd90cb345818d0333be205ba46b0950aeb340
[ "MIT" ]
null
null
null
testing/src/main/kotlin/Combinations.kt
AtricoSoftware/atrico.kotlib
273fd90cb345818d0333be205ba46b0950aeb340
[ "MIT" ]
null
null
null
package atrico.kotlib.testing import java.util.* // Calculate the combinations of a set fun <T> calculateCombinations(items: Collection<T>, count: Int): Sequence<Iterable<T>> { fun itemIterator(items: Collection<T>): Sequence<Iteration<T>> { return sequence { val queue = ArrayDeque(items) while (!queue.isEmpty()) { yield(Iteration(queue.pop(), queue)) } } } return calculateImpl(items, count) { col -> itemIterator(col) } } data class Iteration<T>(val item: T, val remaining: Collection<T>) private fun <T> calculateImpl( items: Collection<T>, count: Int, itemIterator: (Collection<T>) -> Sequence<Iteration<T>> ): Sequence<Iterable<T>> { fun calculate(items: Collection<T>, count: Int): Sequence<Iterable<T>> { return sequence { for (iteration in itemIterator(items)) { if (count == 1) yield(listOf(iteration.item)) else { for (tail in calculate(iteration.remaining, count - 1)) { yield(listOf(iteration.item) + tail) } } } } } // Validate the params if (items.count() == 0) throw IllegalArgumentException("Elements cannot be empty") if (count < 1) throw IllegalArgumentException("Count must be greater than 0") if (count > items.count()) throw IllegalArgumentException("Count must be less than or equal to elements count") // Calculate value return calculate(items, count) }
35.644444
116
0.585411
b2eaad3cf6ba61735dc17fc8cd249e0de4bd056b
8,879
py
Python
examples/json_serializer.py
trisongz/lazycls
701bad1a358ed3bb136347d0c5eb81de3201f6a3
[ "MIT" ]
2
2021-12-02T00:13:16.000Z
2022-02-26T11:18:33.000Z
examples/json_serializer.py
trisongz/lazycls
701bad1a358ed3bb136347d0c5eb81de3201f6a3
[ "MIT" ]
null
null
null
examples/json_serializer.py
trisongz/lazycls
701bad1a358ed3bb136347d0c5eb81de3201f6a3
[ "MIT" ]
null
null
null
""" This test will show how to use the various Json serializer(s) """ from lazy.io.pathz import get_path from lazy.serialize import SimdJson, OrJson, Json, Serializer from lazy.utils import get_logger, timer logger = get_logger('lazytest') test_file = './files/naics_codes.json' test_path = get_path(test_file, resolve=True) test_keys = [ '112930', '11299', '112990', '1131', '11311', '113110', '1132', '11321', '113210', '1133', '11331', '113310', '1141', '11411', '114111', '114112', '114119', '1142', '11421', '114210', '1151', '11511', '115111', '115112', '115113', '115114', '115115', '115116', '1152', '11521', '115210', '1153', '11531', '115310', '2111', '21112', '211120', '21113', '211130', '2121', '21211', '212111', '212112', '212113', '2122', '21221', '212210', '21222', '212221', '212222', '21223', '212230', '21229', '212291', '212299', '2123', '21231', '212311', '212312', '212313', '212319', '21232', '212321', '212322', '212324', '212325', '21239', '212391', '212392', '212393', '212399', '2131', '21311', '213111', '213112', '213113', '213114', '213115', '2211', '22111', '221111', '221112', '221113', '221114', '221115', '221116', '221117', '221118', '22112', '221121', '221122', '2212', '22121', '221210', '2213', '22131', '221310', '22132', '221320', '22133', '221330', '2361', '23611', '236115', '236116', '236117', '236118', '2362', '23621', '236210', '23622', '236220', '2371', '23711', '237110', '23712', '237120', '23713', '237130', '2372', '23721', '237210', '2373', '23731', '237310', '2379', '23799', '237990', '2381', '23811', '238110', '32412', '324121', '324122', '32419', '324191', '324199', '3251', '32511', '325110', '32512', '325120', '32513', '325130', '32518', '325180', '32519', '325193', '325194', '325199', '3252', '32521', '325211', '325212', '32522', '325220', '3253', '32531', '325311', '325312', '325314', '32532', '325320', '3254', '32541', '325411', '325412', '325413', '325414', '3255', '32551', '325510', '32552', '325520', '3256', '32561', '325611', '325612', '325613', '32562', '325620', '3259', '32591', '325910', '32592', '325920', '32599', '325991', '325992', '325998', '3261', '32611', '326111', '326112', '326113', '32612', '326121', '326122', '32613', '326130', '32614', '326140', '32615', '326150', '32616', '326160', '32619', '326191', '326199', '3262', '32621', '326211', '326212', '32622', '326220', '32629', '326291', '326299', '3271', '32711', '327110', '32712', '327120', '3272', '32721', '327211', '327212', '327213', '327215', '3273', '32731', '327310', '32732', '327320', '32733', '327331', '327332', '32739', '327390', '3274', '32741', '327410', '32742', '327420', '3279', '32791', '327910', '32799', '327991', '327992', '327993', '327999', '3311', '33111', '331110', '3312', '33121', '331210', '33122', '3312', '333413', '333414', '333415', '3335', '33351', '333511', '333514', '333515', '333517', '333519', '3336', '33361', '333611', '333612', '333613', '333618', '3339', '33391', '333912', '333914', '33392', '333921', '333922', '333923', '333924', '33399', '333991', '333992', '333993', '333994', '333995', '333996', '333997', '333999', '3341', '33411', '334111', '334112', '334118', '3342', '33421', '334210', '33422', '334220', '33429', '334290', '3343', '33431', '334310', '3344', '33441', '334412', '334413', '334416', '334417', '334418', '334419', '3345', '33451', '334510', '334511', '334512', '334513', '334514', '334515', '334516', '334517', '334519', '3346', '33461', '334613', '334614', '3351', '33511', '335110', '33512', '335121', '335122', '335129', '3352', '33521', '335210', '33522', '335220', '3353', '33531', '335311', '335312', '335313', '335314', '3359', '33591', '335911', '335912', '33592', '335921', '335929', '33593', '335931', '335932', '33599', '335991', '335999', '3361', '33611', '336111', '519190', '5211', '52111', '521110', '5221', '52211', '522110', '52212', '522120', '52213', '522130', '52219', '522190', '5222', '52221', '522210', '52222', '522220', '52229', '522291', '522292', '522293', '522294', '522298', '5223', '52231', '522310', '52232', '522320', '52239', '522390', '5231', '52311', '523110', '52312', '523120', '52313', '523130', '52314', '523140', '5232', '52321', '523210', '5239', '52391', '7113', '71131', '711310', '71132', '711320', '7114', '71141', '711410', '7115', '71151', '711510', '7121', '71211', '712110', '71212', '712120', '71213', '712130', '71219', '712190', '7131', '71311', '713110', '71312', '713120', '7132', '71321', '713210', '71329', '713290', '7139', '71391', '713910', '71392', '713920', '71393', '713930', '71394', '713940', '71395', '713950', '71399', '713990', '7211', '72111', '721110', '72112', '721120', '72119', '721191', '721199', '7212', '72121', '721211', '721214', '7213', '72131', '721310', '7223', '72231', '722310', '72232', '722320', '72233', '722330', '7224', '72241', '722410', '7225', '72251', '722511', '722513', '722514', '722515', '8111', '81111', '811111', '811112', '811113', '811118', '81112', '811121', '811122', '81119', '811191', '811192', '811198', '8112', '81121', '811211', '811212', '811213', '811219', '8113', '81131', '811310', '8114', '81141', '811411', '811412', '81142', '811420', '81143', '811430', '81149', '811490', '8121', '81211', '812111', ] def get_text(): s = timer() text = test_path.read_text() logger(f'Time to Read Text: {timer(s, as_string=True, short=True)}') return text def test_simdjson(): js = timer() text = get_text() t = SimdJson.parse(text) logger(f'[SimdJson] Time to Parse: {timer(js, as_string=True, short=True)}') num_keys = len(t.keys) logger(f'[SimdJson] Time to Load {num_keys} Keys: {timer(js, as_string=True, short=True)}') lt = timer() for i in test_keys: _ = t[i] logger(f'[SimdJson] Time to Read {len(test_keys)} Items: {timer(lt, as_string=True, short=True)}') lt = timer() _ = SimdJson.dumps(t) logger(f'[SimdJson] Time to Dump {len(test_keys)} Items: {timer(lt, as_string=True, short=True)}') logger(f'[SimdJson] Completed Test in: {timer(js, as_string=True, short=True)}') logger('----------------------------------------------------------------') def test_orjson(): js = timer() text = get_text() t = OrJson.loads(text) num_keys = len(t.keys()) logger(f'[OrJson] Time to Load with {num_keys} Total Items: {timer(js, as_string=True, short=True)}') lt = timer() for i in test_keys: _ = t[i] logger(f'[OrJson] Time to Read {len(test_keys)} Items: {timer(lt, as_string=True, short=True)}') lt = timer() _ = OrJson.dumps(t) logger(f'[OrJson] Time to Dump {len(test_keys)} Items: {timer(lt, as_string=True, short=True)}') logger(f'[OrJson] Completed Test in: {timer(js, as_string=True, short=True)}') logger('----------------------------------------------------------------') def test_json(): js = timer() text = get_text() ## Explicitly disable Parser Json.parser_enabled = False t = Json.loads(text) logger(f'[Json] Time to Load: {timer(js, as_string=True, short=True)}') lt = timer() for i in test_keys: _ = t[i] logger(f'[Json] Time to [Loads]Read {len(test_keys)} Items: {timer(lt, as_string=True, short=True)}') t = Json.parse(text) logger(f'[Json] Time to Parse: {timer(js, as_string=True, short=True)}') lt = timer() for i in test_keys: _ = t[i] logger(f'[Json] Time to [Parse]Read {len(test_keys)} Items: {timer(lt, as_string=True, short=True)}') lt = timer() _ = Json.dumps(t) logger(f'[Json] Time to Dump {len(test_keys)} Items: {timer(lt, as_string=True, short=True)}') logger(f'[Json] Completed Test in: {timer(js, as_string=True, short=True)}') logger('----------------------------------------------------------------') """ Expected Results Time to Read Text: 0.00095 secs [OrJson] Time to Load with 2077 Total Items: 0.00378 secs [OrJson] Time to Read 520 Items: 2e-05 secs [OrJson] Time to Dump 520 Items: 0.00097 secs [OrJson] Completed Test in: 0.00497 secs ---------------------------------------------------------------- Time to Read Text: 0.00022 secs [Json] Time to Load: 0.00234 secs [Json] Time to [Loads]Read 520 Items: 2e-05 secs [Json] Time to Parse: 0.0032 secs [Json] Time to [Parse]Read 520 Items: 0.00237 secs [Json] Time to Dump 520 Items: 0.00238 secs [Json] Completed Test in: 0.00814 secs ---------------------------------------------------------------- Time to Read Text: 0.00023 secs [SimdJson] Time to Parse: 0.00051 secs [SimdJson] Time to Load 2077 Keys: 0.00214 secs [SimdJson] Time to Read 520 Items: 0.00011 secs [SimdJson] Time to Dump 520 Items: 0.00365 secs [SimdJson] Completed Test in: 0.00611 secs ---------------------------------------------------------------- """ if __name__ == '__main__': test_orjson() test_json() test_simdjson()
75.245763
1,231
0.582273
690f9a5118a01808640f6cf856ee184652cc5ccb
2,670
kt
Kotlin
app/src/main/java/com/tiixel/periodictableprofessor/ui/tutorial/Tutorial.kt
TiiXel/periodic-table-professor
c9b878171db42d7ed01852f144f32c35acb91816
[ "MIT" ]
null
null
null
app/src/main/java/com/tiixel/periodictableprofessor/ui/tutorial/Tutorial.kt
TiiXel/periodic-table-professor
c9b878171db42d7ed01852f144f32c35acb91816
[ "MIT" ]
null
null
null
app/src/main/java/com/tiixel/periodictableprofessor/ui/tutorial/Tutorial.kt
TiiXel/periodic-table-professor
c9b878171db42d7ed01852f144f32c35acb91816
[ "MIT" ]
null
null
null
package com.tiixel.periodictableprofessor.ui.tutorial import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.content.res.ResourcesCompat import com.hololo.tutorial.library.Step import com.hololo.tutorial.library.TutorialActivity import com.tiixel.periodictableprofessor.R import com.tiixel.periodictableprofessor.ui.MainActivity class Tutorial : TutorialActivity() { companion object { val tutorialSharedPreferencesFile = "com.tiixel.periodictableprofessor.tutorial" val tutorialCompletedSharedPreferencesKey = "com.tiixel.periodictableprofessor.tutorial.completed" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addFragment( Step.Builder() .setTitle(getString(R.string.tutorial_welcome_title)) .setContent(getString(R.string.tutorial_welcome_content)) .setBackgroundColor(ResourcesCompat.getColor(resources, R.color.colorPrimaryDark, baseContext.theme)) .build() ) addFragment( Step.Builder() .setTitle(getString(R.string.tutorial_cards_title)) .setContent(getString(R.string.tutorial_cards_content)) .setDrawable(R.drawable.tutorial_card) .setBackgroundColor(ResourcesCompat.getColor(resources, R.color.colorPrimaryDark, baseContext.theme)) .build() ) addFragment( Step.Builder() .setTitle(getString(R.string.tutorial_reviewing_title)) .setContent(getString(R.string.tutorial_reviewing_content)) .setDrawable(R.drawable.tutorial_reviewing_picture) .setBackgroundColor(ResourcesCompat.getColor(resources, R.color.colorPrimaryDark, baseContext.theme)) .build() ) addFragment( Step.Builder() .setTitle(getString(R.string.tutorial_intervals_title)) .setContent(getString(R.string.tutorial_intervals_content)) .setDrawable(R.drawable.tutorial_reviewing_all) .setBackgroundColor(ResourcesCompat.getColor(resources, R.color.colorPrimaryDark, baseContext.theme)) .build() ) } override fun finishTutorial() { val sharedPref = getSharedPreferences(tutorialSharedPreferencesFile, Context.MODE_PRIVATE) with (sharedPref.edit()) { putBoolean(tutorialCompletedSharedPreferencesKey, true) commit() } startActivity(Intent(this, MainActivity::class.java)) } }
42.380952
117
0.677528
ff48404986634c175fd0de936eab2df784f1808b
1,246
sql
SQL
src/main/resources/db/openidconnect/mysql/crimson-care-management-client.sql
nschwertner/reference-apps
276d10d1f13c49789b44b5966bed20007b89b5cd
[ "Apache-2.0" ]
null
null
null
src/main/resources/db/openidconnect/mysql/crimson-care-management-client.sql
nschwertner/reference-apps
276d10d1f13c49789b44b5966bed20007b89b5cd
[ "Apache-2.0" ]
null
null
null
src/main/resources/db/openidconnect/mysql/crimson-care-management-client.sql
nschwertner/reference-apps
276d10d1f13c49789b44b5966bed20007b89b5cd
[ "Apache-2.0" ]
null
null
null
SET AUTOCOMMIT = 0; START TRANSACTION; INSERT INTO client_details (client_id, client_name, access_token_validity_seconds, logo_uri, token_endpoint_auth_method) VALUES ('d827bd57-1be6-49a6-8f23-577c7edb51df', 'Crimson Care Management', 86400, 'https://sandbox.hspconsortium.org/dstu2/hspc-reference-apps/static/images/apps/ccm_homepage_icon.png', 'NONE'); INSERT INTO client_redirect_uri (owner_id, redirect_uri) VALUES ((SELECT id from client_details where client_id = 'd827bd57-1be6-49a6-8f23-577c7edb51df'), 'https://fhirdemo.advisory.com/launcherHspc'); INSERT INTO client_scope (owner_id, scope) VALUES ((SELECT id from client_details where client_id = 'd827bd57-1be6-49a6-8f23-577c7edb51df'), 'launch'), ((SELECT id from client_details where client_id = 'd827bd57-1be6-49a6-8f23-577c7edb51df'), 'launch/patient'), ((SELECT id from client_details where client_id = 'd827bd57-1be6-49a6-8f23-577c7edb51df'), 'patient/*.*'), ((SELECT id from client_details where client_id = 'd827bd57-1be6-49a6-8f23-577c7edb51df'), 'user/*.*'); INSERT INTO client_grant_type (owner_id, grant_type) VALUES ((SELECT id from client_details where client_id = 'd827bd57-1be6-49a6-8f23-577c7edb51df'), 'authorization_code'); COMMIT; SET AUTOCOMMIT = 1;
54.173913
188
0.781701
df2bfa67c45984f8982f896c1d7b0d2a46b22a52
341
asm
Assembly
programs/oeis/139/A139817.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/139/A139817.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/139/A139817.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A139817: 2^n - number of digits of 2^n. ; 0,1,3,7,14,30,62,125,253,509,1020,2044,4092,8188,16379,32763,65531,131066,262138,524282,1048569,2097145,4194297,8388601,16777208,33554424,67108856,134217719,268435447,536870903,1073741814,2147483638,4294967286,8589934582 mov $2,2 pow $2,$0 mov $0,$2 mov $1,$2 lpb $0,1 div $0,10 sub $1,1 lpe
28.416667
222
0.741935
d9bfe622c46c0537a41526218e7145494b376979
3,043
rs
Rust
hello-world/src/main.rs
Becavalier/rust-by-example-cases
8e2d52986aa5bd27b06cbc26dd04ea20a46872c3
[ "MIT" ]
2
2021-04-20T08:43:35.000Z
2021-04-20T10:33:06.000Z
hello-world/src/main.rs
Becavalier/rust-by-example-cases
8e2d52986aa5bd27b06cbc26dd04ea20a46872c3
[ "MIT" ]
null
null
null
hello-world/src/main.rs
Becavalier/rust-by-example-cases
8e2d52986aa5bd27b06cbc26dd04ea20a46872c3
[ "MIT" ]
null
null
null
fn main() { let x = String::from("world!"); let s = format!("Hello, {}", &x); print!("{}", s); println!("{}", s); // with newline, to io::stdout. eprint!("{}", s); eprintln!("{0}", s); // use the first value. println!("{:b}", 100); // with formatting flags (binary). println!("{}", 100u32); // use named arguments. println!( "{subject} {verb} {object}.", object = "the lazy dog", subject = "the quick brown fox", verb = "jumps over" ); // align to right, padding with zero numerical extension. println!("{number:>width$} {number:<0width$}", number = 1, width = 6); // print compound types with Debug trait. #[derive(Debug)] struct SA(i32); println!("{:#?}", &SA(10)); // print compound types with custom Display trait. use std::fmt; #[derive(Debug)] struct Person<'a> { name: &'a str, age: u8, } impl<'a> Person<'a> { fn new(name: &'a str, age: u8) -> Self { Person { name, age } } } impl<'a> fmt::Display for Person<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {}", &self.name, &self.age) } } println!("{}", &Person::new("Jason", 19)); println!("{:#?}", &Person::new("Alice", 21)); // implementing Display trait for Vec. struct List(Vec<i32>); impl fmt::Display for List { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let vec = &self.0; write!(f, "[")?; // propagate the error to the outer scope if any. for (index, &v) in vec.iter().enumerate() { if index == 0 { write!(f, "{}", v)?; } else { write!(f, ",{}", v)?; } } write!(f, "]") } } println!("{}", &List(vec![1, 2, 3])); // formatting with macro format!. let foo = 3735928559i64; println!("{}", format!("{}", foo)); println!("{}", format!("0x{:X}", foo)); println!("{}", format!("b'{:b}", foo)); println!("{}", format!("0o{:o}", foo)); struct City { name: &'static str, lat: f32, lon: f32, } impl fmt::Display for City { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' }; let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' }; write!( f, "{}: {:.3}°{} {:.3}°{}", self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c ) } } for city in [ // pattern matching. City { name: "Dublin", lat: 53.347778, lon: -6.259722, }, City { name: "Oslo", lat: 59.95, lon: 10.75, }, ] .iter() { println!("{}", city); } }
27.663636
78
0.425895
d291e66cfdb81ee8551c1266aab7b439cf428b9e
2,984
prc
SQL
data/train/sql/60be89f8fbb8abd4d0daed407cdbd3c5d3e6a2farandezvous.prc
aliostad/deep-learning-lang-detection
d6b031f3ebc690cf2ffd0ae1b08ffa8fb3b38a62
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/sql/60be89f8fbb8abd4d0daed407cdbd3c5d3e6a2farandezvous.prc
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/sql/60be89f8fbb8abd4d0daed407cdbd3c5d3e6a2farandezvous.prc
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
import studio import f1 program randezvous #auto [[gospoda] [gospoda ada]] [[gospoda *task] [var [pieczywo 0] [mieso 0]] [task *task [gospoda dostarczmieso dostarczpieczywo status exit] [FOREVER [show "ready...."] [pieczywo : *p] [mieso : *m] [SELECT [[*task select status [*p *m] [show "pieczywo = " *p] [show "mieso = " *m]]] [[*task select exit []] [*task] [timeout]] [[*task select dostarczpieczywo [*pieczywo] [pieczywo *pieczywo] [show "Dostalem pieczywo [" *pieczywo "]"]]] [[*task select dostarczmieso [*mieso] [mieso *mieso] [show "Dostalem mieso [" *mieso "]"]]] [[greater *p 0] [greater *m 0] [*task select gospoda [*pk] [rnd *time 1000 5000] [write "gotuje => " [*time]] [wait *time] [write " mieso\n"] [sum *m *p *pk] [wait 4000] [pieczywo 0] [mieso 0] ]] [[*task wait]] ] [show "..... loop"] ] ] ] [[train *task] [task *task[exit status]]] [[train] [train ada]] [[a] [crack [ada accept exit [1 2 3] [show "processing...."] [wait 2000] [show "....processed"]] [show "accepted"]]] [[s] [crack [ada select exit [1 2 3] [show "selecting...."] [wait 2000] [show "....selected"]] [show "accepted"]]] [[ss] [crack [ada select status [5 6 7] [show "status selecting....."] [wait 2000] [show "....status selected"]] [show "accepted"]]] [[b] [crack [ada enter exit 1 *x 3] [show *x]]] [[bs] [crack [ada enter status : *x] [show *x]]] end := [[set_colors 16776960 0] [auto_atoms] [command]] . auto := [ [VARIABLE kanapki] [kanapki 0] [VARIABLE pieczywo] [pieczywo 0] [VARIABLE mieso] [mieso 0] ] [[gotujmieso *m] [rnd *time 100 5000] [mieso : *m] [write "gotuje => "] [wait *time] [show "mieso " [*time *m]] [mieso 0] ] [[robkanapki *k] [pieczywo : *p] [mieso : *mieso] [less 0 *mieso] [less 0 *p] [gotujmieso *m] [add *m *p *k] [pieczywo 0] [kanapki *k] ] [[robkanapki] [write " Nie moge zrobic kanapek.\n"]] [[status] [mieso : *m] [pieczywo : *p] [kanapki : *k] [show "mieso " [*m] " pieczywo " [*p] " kanapki " [*k]] ] [[akceptuj_pieczywo *task 0] [accept *task dostarczpieczywo [*pieczywo]] [pieczywo *pieczywo] [show "Dostalem pieczywo => " *pieczywo] ] [[akceptuj_mieso *task 0] [accept *task dostarczmieso [*mieso]] [mieso *mieso] [show "Dostalem mieso => " *mieso] ] [[akceptuj_klienta *task *p *m] [less 0 *p] [less 0 *m] [accept *task gospoda [*pk] [robkanapki *pk] [show " Zrobilem kanapki => " *pk] ] [wait 4000] [kanapki 0] ] [[gospoda *task] [task *task [dostarczpieczywo dostarczmieso gospoda status exit] [FOREVER [pieczywo : *p] [mieso : *m] [select *task [[akceptuj_pieczywo *task *p]] [[akceptuj_mieso *task *m]] [[akceptuj_klienta *task *p *m]] [[accept *task exit [] [show "EXITING...."]] [show "applying timeout"] [timeout [show "timeout"]]] ] [show " .... done one loop"] [show " .... done another loop"] ] ] ] auto := [[gospoda ada]] end := [[set_colors 16776960 0] [auto_atoms] [command]] .
27.127273
132
0.592158
12a9f7fb0284e0d39d0abddf5d1213285c123fe7
507
h
C
Framework/Sources/View/UITextView+HLSExtensions.h
defagos/CoconutKit
8534e14bec19e843ba564ff7a182717126904eba
[ "BSD-3-Clause" ]
294
2015-01-01T12:52:03.000Z
2022-02-06T10:10:16.000Z
Framework/Sources/View/UITextView+HLSExtensions.h
jennyb2911/CoconutKit
e2c19f27519726b3240773b5ef328a3d679a130c
[ "BSD-3-Clause" ]
14
2015-03-17T20:25:27.000Z
2019-08-07T07:14:18.000Z
Framework/Sources/View/UITextView+HLSExtensions.h
jennyb2911/CoconutKit
e2c19f27519726b3240773b5ef328a3d679a130c
[ "BSD-3-Clause" ]
41
2015-01-04T15:31:57.000Z
2021-01-18T06:07:42.000Z
// // Copyright (c) Samuel Défago. All rights reserved. // // License information is available from the LICENSE file. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UITextView (HLSExtensions) /** * If set to YES, the text view resigns its first responder status when the user taps outside it * * The default value is NO */ @property (nonatomic, getter=isResigningFirstResponderOnTap) BOOL resigningFirstResponderOnTap; @end NS_ASSUME_NONNULL_END
21.125
96
0.765286
0b9851847b18a4b7b38e82d6bd87af07dc1c57a9
1,531
py
Python
examples/imu.py
dan-stone/canal
8a6b03a46102f7e5ca457538eb03ab9526eec095
[ "MIT" ]
2
2017-02-08T20:27:39.000Z
2019-07-15T00:34:05.000Z
examples/imu.py
dan-stone/canal
8a6b03a46102f7e5ca457538eb03ab9526eec095
[ "MIT" ]
null
null
null
examples/imu.py
dan-stone/canal
8a6b03a46102f7e5ca457538eb03ab9526eec095
[ "MIT" ]
1
2018-05-31T14:09:19.000Z
2018-05-31T14:09:19.000Z
import datetime import canal from influxdb import InfluxDBClient class IMU(canal.Measurement): accelerometer_x = canal.IntegerField() accelerometer_y = canal.IntegerField() accelerometer_z = canal.IntegerField() gyroscope_x = canal.IntegerField() gyroscope_y = canal.IntegerField() gyroscope_z = canal.IntegerField() user_id = canal.Tag() if __name__ == "__main__": start_date = datetime.datetime.now(datetime.timezone.utc) duration = datetime.timedelta(seconds=60) user_id = 12345678 client = InfluxDBClient( host="localhost", port=8086, database="canal" ) # Write some dummy IMU data, sampled once per second num_imu_samples = int(duration.total_seconds()) imu = IMU( time=[start_date + datetime.timedelta(seconds=d) for d in range(num_imu_samples)], acc_x=range(0, 1 * num_imu_samples, 1), acc_y=range(0, 2 * num_imu_samples, 2), acc_z=range(0, 3 * num_imu_samples, 3), gyro_x=range(0, 4 * num_imu_samples, 4), gyro_y=range(0, 5 * num_imu_samples, 5), gyro_z=range(0, 6 * num_imu_samples, 6), user_id=user_id ) client.write( data=imu.to_line_protocol(), params=dict( db="canal" ) ) # Read back the IMU data imu_resp = client.query(IMU.make_query_string( time__gte=start_date, time__lte=start_date + duration, user_id=user_id )) assert imu == IMU.from_json(imu_resp.raw)
27.836364
65
0.640758
96a17ce17d22ee334506b805163adbbcbb08864f
24,140
html
HTML
_posts/2015-03-20-the-surechembl-map-file-is-out.html
chembl/chembl.github.io
15e9e8169533e07759dad0b12e98b6f21b241fbb
[ "MIT" ]
null
null
null
_posts/2015-03-20-the-surechembl-map-file-is-out.html
chembl/chembl.github.io
15e9e8169533e07759dad0b12e98b6f21b241fbb
[ "MIT" ]
null
null
null
_posts/2015-03-20-the-surechembl-map-file-is-out.html
chembl/chembl.github.io
15e9e8169533e07759dad0b12e98b6f21b241fbb
[ "MIT" ]
null
null
null
--- layout: post title: The SureChEMBL map file is out date: '2015-03-20T13:16:00.000Z' author: George Papadatos tags: - data - Patents - Databases - SureChEMBL modified_time: '2015-03-20T15:51:34.507Z' thumbnail: http://4.bp.blogspot.com/-nZbpPeBAbgU/VQwJSfxv6WI/AAAAAAAAAaY/ptLNY2QS-ZU/s72-c/Screen%2BShot%2B2015-03-20%2Bat%2B11.48.28.png blogger_id: tag:blogger.com,1999:blog-2546008714740235720.post-4010781409222082694 blogger_orig_url: http://chembl.blogspot.com/2015/03/the-surechembl-map-file-is-out.html --- <div dir="ltr" style="text-align: left;" trbidi="on"> <div class="separator" style="clear: both; text-align: center;"> <a href="http://imgs.xkcd.com/comics/documents.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://imgs.xkcd.com/comics/documents.png" height="400" width="240" /></a></div> <div class="separator" style="clear: both; text-align: center;"> <br /></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">As many of you know, SureChEMBL taps into the wealth of knowledge hidden in the patent documents. More specifically, SureChEMBL extracts and indexes chemistry from the full-text patent corpus (EPO, WIPO and USPTO; JPO titles and abstracts only) by means of automated text- and image-mining, on a daily basis. We have recently hosted a webinar about it which turned out to be very popular - for those who missed it, the video and slides are <a href="http://www.ebi.ac.uk/training/online/course/surechembl-accessing-chemical-patent-data-webinar" target="_blank">here</a>. </span></div> <div class="separator" style="clear: both; text-align: justify;"> <b id="docs-internal-guid-6722a609-3698-9f61-ffda-53850f878937" style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Besides the interface, SureChEMBL compound data can be accessed in various ways, such as <a href="https://www.ebi.ac.uk/unichem/ucquery/sourceDetails/15" target="_blank">UniChem</a> and <a href="https://www.ncbi.nlm.nih.gov/pcsubstance?term=%22SureChEMBL%22[sourcename]" target="_blank">PubChem</a>. The full compound dump is also available as a flat file download from our <a href="ftp://ftp.ebi.ac.uk/pub/databases/chembl/SureChEMBL/data/" target="_blank">ftp server</a>.</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Since the release of the SureChEMBL interface last September, we have received numerous requests for a way to access compound </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: italic; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">and </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">patent data in a batch way. Typical use-cases would include retrieving all compounds for a list of patent IDs, or </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: italic; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">vice versa</span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">, retrieving all patents where one or more compounds have been extracted from. As a result, we have now produced this so-called </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: italic; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">map</span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"> file which connects SureChEMBL compounds and patents.</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">It is available <a href="ftp://ftp.ebi.ac.uk/pub/databases/chembl/SureChEMBL/data/map/" target="_blank">here</a>.</span></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">More information can be found in the <a href="ftp://ftp.ebi.ac.uk/pub/databases/chembl/SureChEMBL/data/map/README" target="_blank">README</a> file.</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">What is this file?</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">There is a total of 216,892,266 rows in the map, indicating a compound extracted from a specific section of a specific patent document. The format of the file is quite simple: it contains compound information (SCHEMBL ID, SMILES, InChI Key, corpus frequency), patent information (patent ID and publication data), and finally location information, such as the field ID and frequency. The field ID indicates the specific section in the patent where the compound was extracted from (1:Description, 2:Claims, 3:Abstract, 4:Title, 5:Image, 6:MOL attachment). The frequency is the number of times the compound was found in a given section of a given patent. More information on the format of the file in the <a href="ftp://ftp.ebi.ac.uk/pub/databases/chembl/SureChEMBL/data/map/README" target="_blank">README</a> file. </span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">How many compounds and patents are there?</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">There are 187,958,584 unique patent-compound pairs, involving 14,076,090 unique compound IDs extracted from 3,585,233 EP, JP, WO and US patent documents - an average of ~52 compounds per patent. The patent coverage is from 1960 to 31-12-2014 inclusive. </span><br /> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><br /></span> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Here's a breakdown of the patents in the map per year and patent authority:</span><br /> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><br /></span> <br /> <div class="separator" style="clear: both; text-align: center;"> </div> <div class="separator" style="clear: both; text-align: center;"> <a href="http://4.bp.blogspot.com/-nZbpPeBAbgU/VQwJSfxv6WI/AAAAAAAAAaY/ptLNY2QS-ZU/s1600/Screen%2BShot%2B2015-03-20%2Bat%2B11.48.28.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-nZbpPeBAbgU/VQwJSfxv6WI/AAAAAAAAAaY/ptLNY2QS-ZU/s1600/Screen%2BShot%2B2015-03-20%2Bat%2B11.48.28.png" height="368" width="640" /></a></div> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><br /></span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Are these </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: italic; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">all</span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"> the compounds and patents in SureChEMBL? </span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><a href="http://xkcd.com/1475/" target="_blank">Technically</a>, no - in practice, yes. We excluded chemically annotated patents that are not immediately relevant to life sciences, such as <a href="https://www.surechembl.org/document/US-20150077909-A1" target="_blank">this</a> one. For the filtering, we used a list of relevant <a href="http://web2.wipo.int/ipcpub/#refresh=page" target="_blank">IPCR</a> and related patent classification codes. At the same time, we excluded too small, too large, too trivial compounds, along with non-organic and radical/fragment compounds. </span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Are these compounds genuinely claimed as novel in their respective patents? </span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Automated methods to assess which are the important and relevant compounds in a pharmaceutical patent is a field of research and one of our future plans. For now, the map file include </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: italic; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">all</span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"> extracted chemistry mentioned in all sections of a patent, subject to the filters listed in the previous section. A quick and effective trick to filter out trivial and/or uninformative compounds is to use the corpus frequency column and exclude everything with a value more than, say, 1000. Note that, in this way, you will also exclude drug compounds such as sildenafil, which are casually mentioned in </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: italic; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">a lot</span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"> of patents. You could also look for compounds mentioned only in claims, description or images sections by filtering by the corresponding field ID.</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">What can I do with this?</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Well, you can start by 'grepping' for one or more patent IDs or SCHEMBL IDs or InChI keys, followed by further filtering. Many of you will choose to normalise the flat file into 3 database tables (say compounds, documents and doc_to_compound) for centralised access and easy querying. </span></div> <br /> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">For example, to find the patents the drug <a href="https://www.ebi.ac.uk/chembl/compound/inspect/CHEMBL189963" target="_blank">palbociclib</a> has been extracted from:</span></div> <script src="https://gist.github.com/madgpap/f9b20c2e2ea902b92687.js"></script><br /> <span style="font-family: 'Trebuchet MS'; font-size: 16px; font-weight: bold; line-height: 1.38; text-align: justify; white-space: pre-wrap;">Any plans to update this map file? &nbsp;</span><br /> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">New patents and chemistry arrive and are stored to SureChEMBL every day. We are planning to release new versions and incremental updates of the map file every quarter, in sync with the update of the compound dump files. </span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">I couldn’t find my compound / patent - this compound should not be there</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Don’t forget this an automated, live, high-throughput text-mining effort against an inherently noisy corpus such as patents. We are constantly working on improving data quality. If you find anything strange, <a href="mailto:[email protected]" target="_blank">let us know</a>. </span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: bold; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Can I join more metadata, such as patent assignee and title?</span></div> <div class="separator" style="clear: both; text-align: justify;"> <b style="font-weight: normal;"><br /> </b></div> <div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt; text-align: justify;"> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Obviously your first port of call would be the SureChEMBL website for patent metadata, but other services you may wish to use include the <a href="http://www.epo.org/searching/free/ops.html" target="_blank">EPO web services</a> for programmatic access.</span><br /> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><br /></span> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><span style="font-weight: bold; line-height: 22.0799999237061px;">Is there anything else?</span></span><br /> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><span style="font-weight: bold; line-height: 22.0799999237061px;"><br /></span></span> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">Errr, yes. Watch this space for another post on storing and accessing </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><i>live</i></span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"> SureChEMBL data, </span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><i>behind</i></span><span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"> your firewall.&nbsp;</span><br /> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><br /></span> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;"><br /></span> <span style="background-color: transparent; color: black; font-family: 'Trebuchet MS'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;">The SureChEMBL Team </span></div> <br /></div>
174.927536
2,174
0.742336
5809e88b76ebda3ea06cd47453fa78dec8545319
357
h
C
ARReader/ARComposing/ARAsyncLayer/ARTransaction.h
ArchyVan/ARReader
f3f7b705756f3704043732f4fc17cd2bc3153818
[ "MIT" ]
6
2017-02-04T10:08:50.000Z
2021-04-24T16:28:34.000Z
ARReader/ARComposing/ARAsyncLayer/ARTransaction.h
ArchyVan/ARReader
f3f7b705756f3704043732f4fc17cd2bc3153818
[ "MIT" ]
4
2017-03-08T07:46:04.000Z
2017-09-02T00:08:31.000Z
ARReader/ARComposing/ARAsyncLayer/ARTransaction.h
ArchyVan/ARReader
f3f7b705756f3704043732f4fc17cd2bc3153818
[ "MIT" ]
null
null
null
// // ARTransaction.h // ARReader // // Created by Objective-C on 2017/1/26. // Copyright © 2017年 Archy Van. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface ARTransaction : NSObject + (ARTransaction *)transactionWithTarget:(id)target selector:(SEL)selector; - (void)commit; @end NS_ASSUME_NONNULL_END
16.227273
75
0.739496
e15e6ab50ca21f2828214564fdbc7b011f2cc62b
6,044
asm
Assembly
non_regression/switch_x86_macosx.s.asm
LRGH/plasmasm
4cd50546c3dc895763d72dd60b7c46179c1916bc
[ "Apache-2.0" ]
1
2021-02-28T21:31:18.000Z
2021-02-28T21:31:18.000Z
non_regression/switch_x86_macosx.s.asm
LRGH/plasmasm
4cd50546c3dc895763d72dd60b7c46179c1916bc
[ "Apache-2.0" ]
null
null
null
non_regression/switch_x86_macosx.s.asm
LRGH/plasmasm
4cd50546c3dc895763d72dd60b7c46179c1916bc
[ "Apache-2.0" ]
null
null
null
.macosx_version_min 10, 10 .section __TEXT,__text,regular,pure_instructions .align 4, 0x90 .globl _PyToken_OneChar _PyToken_OneChar: pushl %ebp movl %esp, %ebp movl 8(%ebp), %ecx cmpl $93, %ecx jg LBB0_7 cmpl $57, %ecx jg LBB0_5 cmpl $37, %ecx jne LBB0_3 movl $24, %eax popl %ebp ret LBB0_7: cmpl $95, %ecx jg LBB0_10 cmpl $94, %ecx jne LBB0_23 movl $33, %eax popl %ebp ret LBB0_5: addl $-58, %ecx cmpl $6, %ecx ja LBB0_23 call L0$pb L0$pb: popl %edx movl $11, %eax addl Ltmp0(%edx,%ecx,4), %edx jmp *%edx LBB0_18: movl $22, %eax popl %ebp ret LBB0_10: cmpl $124, %ecx jg LBB0_14 cmpl $96, %ecx jne LBB0_12 movl $25, %eax popl %ebp ret LBB0_3: cmpl $46, %ecx jne LBB0_23 movl $23, %eax popl %ebp ret LBB0_14: cmpl $125, %ecx jne LBB0_15 movl $27, %eax popl %ebp ret LBB0_12: cmpl $123, %ecx jne LBB0_23 movl $26, %eax popl %ebp ret LBB0_15: cmpl $126, %ecx jne LBB0_23 movl $32, %eax popl %ebp ret LBB0_23: movl $51, %eax LBB0_24: popl %ebp ret LBB0_17: movl $21, %eax popl %ebp ret LBB0_22: movl $50, %eax popl %ebp ret .align 2, 0x90 LJTI0_0: .long L0_0_set_24 .long L0_0_set_23 .long L0_0_set_23 .long L0_0_set_18 .long L0_0_set_17 .long L0_0_set_23 .long L0_0_set_22 # ---------------------- .align 4, 0x90 .globl _PyToken_TwoChars _PyToken_TwoChars: pushl %ebp movl %esp, %ebp movl 12(%ebp), %ecx movl 8(%ebp), %eax cmpl $60, %eax jg LBB1_3 addl $-33, %eax cmpl $14, %eax ja LBB1_20 call L1$pb L1$pb: popl %edx addl Ltmp1(%edx,%eax,4), %edx jmp *%edx LBB1_11: movl $29, %eax jmp LBB1_19 LBB1_3: cmpl $93, %eax jg LBB1_7 cmpl $61, %eax jne LBB1_5 movl $28, %eax jmp LBB1_19 LBB1_7: cmpl $94, %eax jne LBB1_8 movl $44, %eax jmp LBB1_19 LBB1_5: cmpl $62, %eax jne LBB1_20 cmpl $62, %ecx movl $35, %eax movl $51, %edx cmove %eax, %edx cmpl $61, %ecx movl $31, %eax cmovne %edx, %eax popl %ebp ret LBB1_8: cmpl $124, %eax jne LBB1_20 movl $43, %eax jmp LBB1_19 LBB1_16: movl $41, %eax jmp LBB1_19 LBB1_17: movl $42, %eax jmp LBB1_19 LBB1_14: cmpl $61, %ecx movl $39, %eax movl $51, %edx cmove %eax, %edx cmpl $42, %ecx movl $36, %eax cmovne %edx, %eax popl %ebp ret LBB1_12: movl $37, %eax jmp LBB1_19 LBB1_13: movl $38, %eax LBB1_19: cmpl $61, %ecx je LBB1_21 LBB1_20: movl $51, %eax LBB1_21: popl %ebp ret LBB1_15: cmpl $61, %ecx movl $40, %eax movl $51, %edx cmove %eax, %edx cmpl $47, %ecx movl $48, %eax cmovne %edx, %eax popl %ebp ret .align 2, 0x90 LJTI1_0: .long L1_0_set_11 .long L1_0_set_20 .long L1_0_set_20 .long L1_0_set_20 .long L1_0_set_16 .long L1_0_set_17 .long L1_0_set_20 .long L1_0_set_20 .long L1_0_set_20 .long L1_0_set_14 .long L1_0_set_12 .long L1_0_set_20 .long L1_0_set_13 .long L1_0_set_20 .long L1_0_set_15 # ---------------------- .align 4, 0x90 .globl _main _main: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi movl $51, %ecx movl 8(%ebp), %edx cmpl $93, %edx jg LBB2_7 cmpl $57, %edx jg LBB2_5 cmpl $37, %edx jne LBB2_3 movl $24, %eax jmp LBB2_28 LBB2_7: cmpl $95, %edx jg LBB2_12 cmpl $94, %edx jne LBB2_9 movl $33, %eax jmp LBB2_28 LBB2_5: leal -58(%edx), %esi cmpl $6, %esi ja LBB2_9 call L2$pb L2$pb: popl %edi movl $11, %eax addl Ltmp2(%edi,%esi,4), %edi jmp *%edi LBB2_22: movl $28, %ecx movl $22, %eax jmp LBB2_28 LBB2_12: cmpl $124, %edx jg LBB2_16 cmpl $96, %edx jne LBB2_14 movl $25, %eax jmp LBB2_28 LBB2_3: cmpl $46, %edx jne LBB2_9 movl $23, %eax jmp LBB2_28 LBB2_16: cmpl $125, %edx jne LBB2_17 movl $27, %eax jmp LBB2_28 LBB2_14: cmpl $123, %edx jne LBB2_9 movl $26, %eax jmp LBB2_28 LBB2_17: cmpl $126, %edx jne LBB2_9 movl $32, %eax jmp LBB2_28 LBB2_9: movl $51, %eax cmpl $42, %edx jne LBB2_10 movl $36, %ecx jmp LBB2_28 LBB2_10: cmpl $47, %edx jne LBB2_11 movl $48, %ecx jmp LBB2_28 LBB2_11: movl $51, %ecx jmp LBB2_28 LBB2_23: movl $35, %ecx movl $21, %eax jmp LBB2_28 LBB2_21: movl $50, %eax LBB2_28: addl %ecx, %eax popl %esi popl %edi popl %ebp ret .align 2, 0x90 LJTI2_0: .long L2_0_set_28 .long L2_0_set_9 .long L2_0_set_9 .long L2_0_set_22 .long L2_0_set_23 .long L2_0_set_9 .long L2_0_set_21 # ---------------------- .set Ltmp0,LJTI0_0-L0$pb .set L0_0_set_24,LBB0_24-L0$pb .set L0_0_set_23,LBB0_23-L0$pb .set L0_0_set_18,LBB0_18-L0$pb .set L0_0_set_17,LBB0_17-L0$pb .set L0_0_set_22,LBB0_22-L0$pb .set Ltmp1,LJTI1_0-L1$pb .set L1_0_set_11,LBB1_11-L1$pb .set L1_0_set_20,LBB1_20-L1$pb .set L1_0_set_16,LBB1_16-L1$pb .set L1_0_set_17,LBB1_17-L1$pb .set L1_0_set_14,LBB1_14-L1$pb .set L1_0_set_12,LBB1_12-L1$pb .set L1_0_set_13,LBB1_13-L1$pb .set L1_0_set_15,LBB1_15-L1$pb .set Ltmp2,LJTI2_0-L2$pb .set L2_0_set_28,LBB2_28-L2$pb .set L2_0_set_9,LBB2_9-L2$pb .set L2_0_set_22,LBB2_22-L2$pb .set L2_0_set_23,LBB2_23-L2$pb .set L2_0_set_21,LBB2_21-L2$pb .subsections_via_symbols
18.596923
55
0.545334
f072cc874989ac32c7859004d98fca21a19fe6f9
46
js
JavaScript
app/config/server/index.js
Hartorn/poc-remote-react
df8599ad88cf98280e3bed9d50bb2fd85f2d1920
[ "MIT" ]
1
2017-02-25T00:03:23.000Z
2017-02-25T00:03:23.000Z
app/config/server/index.js
Hartorn/poc-remote-react
df8599ad88cf98280e3bed9d50bb2fd85f2d1920
[ "MIT" ]
null
null
null
app/config/server/index.js
Hartorn/poc-remote-react
df8599ad88cf98280e3bed9d50bb2fd85f2d1920
[ "MIT" ]
null
null
null
export const apiRoot = `${__API_ROOT__}api/`;
23
45
0.717391
7547ffc11ff32a82cb5b68590f3d682a43591e2a
2,500
h
C
UIShop/Template/IM_Resource.h
swjsky/sktminest
42fa47d9ffb0f50a5727e42811e949fff920bec9
[ "MIT" ]
3
2019-12-03T09:04:04.000Z
2021-01-29T02:03:30.000Z
UIShop/Template/IM_Resource.h
swjsky/sktminest
42fa47d9ffb0f50a5727e42811e949fff920bec9
[ "MIT" ]
null
null
null
UIShop/Template/IM_Resource.h
swjsky/sktminest
42fa47d9ffb0f50a5727e42811e949fff920bec9
[ "MIT" ]
2
2019-09-12T07:49:42.000Z
2019-12-24T22:28:49.000Z
//WARNING: DO NOT EDIT OR DELETE THIS HEADER FILE! #pragma once #define IDW_LOGIN 1000 #define IDC_BTN_MIN 1001 #define IDC_BTN_CLOSE 1002 #define IDC_EDT_NAME 1003 #define IDC_EDT_PASSWORD 1004 #define IDC_CHK_REMEMBER_PASSWORD 1005 #define IDC_CHK_AUTO_LOGIN 1006 #define IDC_BTN_LOGIN 1007 #define IDC_BTN_FORGET_PASSWORD 1008 #define IDC_BTN_REGISTER 1009 #define IDW_MAIN 1010 #define IDC_BTN_SKIN 1011 #define IDC_CHK_MAX 1012 #define IDC_BTN_HEADER 1013 #define IDC_CHK_STATUS 1014 #define IDC_BTN_MAIL 1015 #define IDC_BTN_ZONE 1016 #define IDC_BTN_MESSAGE 1017 #define IDC_EDT_SEARCH 1018 #define IDC_BTN_SEARCH_WEB 1019 #define IDC_RAD_FRIEND 1020 #define IDC_RAD_GROUP 1021 #define IDC_RAD_RECENT 1022 #define IDC_CHK_START 1023 #define IDC_BTN_GAME 1024 #define IDC_BTN_SETTING 1025 #define IDC_BTN_MSG 1026 #define IDC_BTN_SECURE 1027 #define IDC_BTN_SEARCH 1028 #define IDC_BTN_APP_MGR 1029 #define IDC_BTN_WEATHER 1030 #define IDC_STA_NAME 1031 #define IDC_BTN_SIGN 1032 #define IDC_STA_TITLE 1033 #define IDC_TWMGR_MAIN 1034 #define IDC_PNL_UGRID_TAB 1035 #define IDW_FRIEND_PAGE 1036 #define IDW_GROUP_PAGE 1037 #define IDC_STA_GROUP 1038 #define IDW_RECENT_PAGE 1039 #define IDC_STA_RECENT 1040 #define IDW_START_MENU 1041 #define IDW_CHAT_FRAME 1042 #define IDC_BTN_EXIT 1043 #define IDC_BTN_VIDEO 1044 #define IDC_BTN_AUDIO 1045 #define IDC_BTN_TRANS_FILE 1046 #define IDC_BTN_CREATE_GROUP 1047 #define IDC_BTN_REMOTE 1048 #define IDC_BTN_MORE 1049 #define IDC_CHK_FONT 1050 #define IDC_CHK_FACE 1051 #define IDC_BTN_SEND 1052 #define IDC_BTN_SEND2 1053
42.372881
51
0.5368
501f5480e25a1561f518bc7d75ac0beb747defbd
7,180
go
Go
pkg/c8y/vendor/github.com/obeattie/ohmyglob/glob.go
ricardnacher/go-c8y
362a3775d9ffde5f14cff366044423347bacf064
[ "MIT" ]
8
2015-02-21T20:21:49.000Z
2021-03-14T15:45:41.000Z
pkg/c8y/vendor/github.com/obeattie/ohmyglob/glob.go
ricardnacher/go-c8y
362a3775d9ffde5f14cff366044423347bacf064
[ "MIT" ]
4
2019-05-25T07:07:46.000Z
2021-09-20T08:53:31.000Z
pkg/c8y/vendor/github.com/obeattie/ohmyglob/glob.go
ricardnacher/go-c8y
362a3775d9ffde5f14cff366044423347bacf064
[ "MIT" ]
2
2016-01-25T14:30:37.000Z
2018-10-24T18:48:49.000Z
// Package ohmyglob provides a minimal glob matching utility. package ohmyglob import ( "bytes" "fmt" "io" "os" "regexp" "strings" log "github.com/cihub/seelog" ) var ( // Logger is used to log trace-level info; logging is completely disabled by default but can be changed by replacing // this with a configured logger Logger log.LoggerInterface // Escaper is the character used to escape a meaningful character Escaper = '\\' // Runes that, in addition to the separator, mean something when they appear in the glob (includes Escaper) expanders = []rune{'?', '*', '!', Escaper} ) func init() { if Logger == nil { var err error Logger, err = log.LoggerFromWriterWithMinLevel(os.Stderr, log.CriticalLvl) // seelog bug means we can't use log.Off if err != nil { panic(err) } } } type processedToken struct { contents *bytes.Buffer tokenType tc } type parserState struct { options *Options // The regex-escaped separator character escapedSeparator string processedTokens []processedToken } // GlobMatcher is the basic interface of a Glob or GlobSet. It provides a Regexp-style interface for checking matches. type GlobMatcher interface { // Match reports whether the Glob matches the byte slice b Match(b []byte) bool // MatchReader reports whether the Glob matches the text read by the RuneReader MatchReader(r io.RuneReader) bool // MatchString reports whether the Glob matches the string s MatchString(s string) bool } // Glob is a single glob pattern; implements GlobMatcher. A Glob is immutable. type Glob interface { GlobMatcher // String returns the pattern that was used to create the Glob String() string // IsNegative returns whether the pattern was negated (prefixed with !) IsNegative() bool } // Glob is a glob pattern that has been compiled into a regular expression. type globImpl struct { *regexp.Regexp // The separator from options, escaped for appending to the regexBuffer (only available during parsing) // The input pattern globPattern string // State only available during parsing parserState *parserState // Set to true if the pattern was negated negated bool } // Options modify the behaviour of Glob parsing type Options struct { // The character used to split path components Separator rune // Set to false to allow any prefix before the glob match MatchAtStart bool // Set to false to allow any suffix after the glob match MatchAtEnd bool } // DefaultOptions are a default set of Options that uses a forward slash as a separator, and require a full match var DefaultOptions = &Options{ Separator: '/', MatchAtStart: true, MatchAtEnd: true, } func (g *globImpl) String() string { return g.globPattern } func (g *globImpl) IsNegative() bool { return g.negated } func popLastToken(state *parserState) *processedToken { state.processedTokens = state.processedTokens[:len(state.processedTokens)-1] if len(state.processedTokens) > 0 { return &state.processedTokens[len(state.processedTokens)-1] } return &processedToken{} } // Compile parses the given glob pattern and convertes it to a Glob. If no options are given, the DefaultOptions are // used. func Compile(pattern string, options *Options) (Glob, error) { pattern = strings.TrimSpace(pattern) reader := strings.NewReader(pattern) if options == nil { options = DefaultOptions } else { // Check that the separator is not an expander for _, expander := range expanders { if options.Separator == expander { return nil, fmt.Errorf("'%s' is not allowed as a separator", string(options.Separator)) } } } state := &parserState{ options: options, escapedSeparator: escapeRegexComponent(string(options.Separator)), processedTokens: make([]processedToken, 0, 10), } glob := &globImpl{ Regexp: nil, globPattern: pattern, negated: false, parserState: state, } regexBuf := new(bytes.Buffer) if options.MatchAtStart { regexBuf.WriteRune('^') } var err error // Transform into a regular expression pattern // 1. Parse negation prefixes err = parseNegation(reader, glob) if err != nil { return nil, err } // 2. Tokenise and convert! tokeniser := newGlobTokeniser(reader, options) lastProcessedToken := &processedToken{} for tokeniser.Scan() { if err = tokeniser.Err(); err != nil { return nil, err } token, tokenType := tokeniser.Token() t := processedToken{ contents: nil, tokenType: tokenType, } // Special cases if tokenType == tcGlobStar && tokeniser.Peek() { // If this is a globstar and the next token is a separator, consume it (the globstar pattern itself includes // a separator) if err = tokeniser.PeekErr(); err != nil { return nil, err } _, peekedType := tokeniser.PeekToken() if peekedType == tcSeparator { tokeniser.Scan() } } if tokenType == tcGlobStar && lastProcessedToken.tokenType == tcGlobStar { // If the last token was a globstar and this is too, remove the last. We don't remove this globstar because // it may now be the last in the pattern, which is special lastProcessedToken = popLastToken(state) } if tokenType == tcGlobStar && lastProcessedToken.tokenType == tcSeparator && !tokeniser.Peek() { // If this is the last token, and it's a globstar, remove a preceeding separator lastProcessedToken = popLastToken(state) } t.contents, err = processToken(token, tokenType, glob, tokeniser) if err != nil { return nil, err } lastProcessedToken = &t state.processedTokens = append(state.processedTokens, t) } for _, t := range state.processedTokens { t.contents.WriteTo(regexBuf) } if options.MatchAtEnd { regexBuf.WriteRune('$') } regexString := regexBuf.String() Logger.Tracef("[ohmyglob:Glob] Compiled \"%s\" to regex `%s` (negated: %v)", pattern, regexString, glob.negated) re, err := regexp.Compile(regexString) if err != nil { return nil, err } glob.parserState = nil glob.Regexp = re return glob, nil } func parseNegation(r io.RuneScanner, glob *globImpl) error { for { char, _, err := r.ReadRune() if err != nil { return err } else if char == '!' { glob.negated = !glob.negated } else { r.UnreadRune() return nil } } } func processToken(token string, tokenType tc, glob *globImpl, tokeniser *globTokeniser) (*bytes.Buffer, error) { state := glob.parserState buf := new(bytes.Buffer) switch tokenType { case tcGlobStar: // Globstars also take care of surrounding separators; separator components before and after a globstar are // suppressed isLast := !tokeniser.Peek() buf.WriteString("(?:") if isLast && len(glob.parserState.processedTokens) > 0 { buf.WriteString(state.escapedSeparator) } buf.WriteString(".+") if !isLast { buf.WriteString(state.escapedSeparator) } buf.WriteString(")?") case tcStar: buf.WriteString("[^") buf.WriteString(state.escapedSeparator) buf.WriteString("]*") case tcAny: buf.WriteString("[^") buf.WriteString(state.escapedSeparator) buf.WriteString("]") case tcSeparator: buf.WriteString(state.escapedSeparator) case tcLiteral: buf.WriteString(escapeRegexComponent(token)) } return buf, nil }
26.791045
118
0.713788
f01fc3a0e111eb1fdc7c976c904c96287ba0042c
573
js
JavaScript
lib/amqp.js
RocksonZeta/co-punch
9f7097cf2fe99d500c08a58e7fb71537cc73c013
[ "MIT" ]
1
2015-03-26T11:06:39.000Z
2015-03-26T11:06:39.000Z
lib/amqp.js
RocksonZeta/co-punch
9f7097cf2fe99d500c08a58e7fb71537cc73c013
[ "MIT" ]
null
null
null
lib/amqp.js
RocksonZeta/co-punch
9f7097cf2fe99d500c08a58e7fb71537cc73c013
[ "MIT" ]
null
null
null
'use strict'; module.exports = function(){ var cofy = require('cofy'); var amqp = require('amqp'); amqp.$createConnection = cofy.fn(amqp.createConnection ,false , amqp); cofy.class(amqp.Connection); cofy.class(require('amqp/lib/exchange.js') , true , ['bind','publish','unbind','bind_headers']); cofy.class(require('amqp/lib/queue.js') , true , ['bind']); amqp.Connection.prototype.$ready = function() { var _this = this; return function(done){ _this.on('ready' , function(){ done(); }); _this.on('error',function(e){ done(e); }); }; }; };
28.65
97
0.635253
2c16092449a8b0f800c18420b3d129fc380bca13
1,254
kt
Kotlin
buildSrc/src/main/kotlin/utils/Vers.kt
linqu-tech/webpb
814dff55d0e84b37001997964bfcbe8684c22339
[ "Apache-2.0" ]
3
2021-05-08T09:41:10.000Z
2021-07-17T13:36:06.000Z
buildSrc/src/main/kotlin/utils/Vers.kt
linqu-tech/webpb
814dff55d0e84b37001997964bfcbe8684c22339
[ "Apache-2.0" ]
null
null
null
buildSrc/src/main/kotlin/utils/Vers.kt
linqu-tech/webpb
814dff55d0e84b37001997964bfcbe8684c22339
[ "Apache-2.0" ]
3
2021-06-02T08:14:57.000Z
2021-08-25T06:47:17.000Z
package utils import org.gradle.api.Project import kotlin.reflect.KMutableProperty import kotlin.reflect.full.memberProperties object Vers { private var initialized = false lateinit var checkstyle: String lateinit var commonsIo: String lateinit var commonsLang3: String lateinit var compileTesting: String lateinit var jackson: String lateinit var jacoco: String lateinit var javaparser: String lateinit var jupiter: String lateinit var lombok: String lateinit var mockito: String lateinit var protobuf: String lateinit var protoc: String lateinit var reactorNetty: String lateinit var servletApi: String lateinit var springFramework: String lateinit var webpb: String fun initialize(project: Project) { if (initialized) { return } this.webpb = project.version.toString() this::class.memberProperties.forEach { val key = "version" + it.name.capitalize() if (project.hasProperty(key)) { val value = project.property(key) if (it is KMutableProperty<*>) { it.setter.call(this, value) } } } initialized = true } }
28.5
54
0.644338
3aa174cd239666c01bfbda9b7112ce6d1e0f323a
1,084
sql
SQL
contrib/pg_pathman/sql/pathman_callbacks.sql
Komzpa/postgrespro
9086b754eb42fc0ee3481a3016360f31a27f2271
[ "PostgreSQL" ]
28
2016-04-08T10:11:07.000Z
2021-11-01T19:43:27.000Z
contrib/pg_pathman/sql/pathman_callbacks.sql
Komzpa/postgrespro
9086b754eb42fc0ee3481a3016360f31a27f2271
[ "PostgreSQL" ]
6
2016-04-11T14:08:36.000Z
2018-11-11T01:41:42.000Z
contrib/pg_pathman/sql/pathman_callbacks.sql
Komzpa/postgrespro
9086b754eb42fc0ee3481a3016360f31a27f2271
[ "PostgreSQL" ]
5
2016-12-01T15:06:10.000Z
2020-06-22T16:06:37.000Z
\set VERBOSITY terse CREATE EXTENSION pg_pathman; CREATE SCHEMA callbacks; /* Check callbacks */ CREATE OR REPLACE FUNCTION callbacks.abc_on_part_created_callback( args JSONB) RETURNS VOID AS $$ BEGIN RAISE WARNING 'callback arg: %', args::TEXT; END $$ language plpgsql; /* set callback to be called on RANGE partitions */ CREATE TABLE callbacks.abc(a serial, b int); SELECT create_range_partitions('callbacks.abc', 'a', 1, 100, 2); SELECT set_init_callback('callbacks.abc', 'callbacks.abc_on_part_created_callback'); INSERT INTO callbacks.abc VALUES (123, 1); INSERT INTO callbacks.abc VALUES (223, 1); SELECT append_range_partition('callbacks.abc'); SELECT prepend_range_partition('callbacks.abc'); SELECT add_range_partition('callbacks.abc', 401, 502); SELECT drop_partitions('callbacks.abc'); /* set callback to be called on HASH partitions */ SELECT set_init_callback('callbacks.abc', 'callbacks.abc_on_part_created_callback'); SELECT create_hash_partitions('callbacks.abc', 'a', 5); DROP SCHEMA callbacks CASCADE; DROP EXTENSION pg_pathman CASCADE;
25.809524
66
0.767528