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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1aef8690170d80e8965fd8a5293542187ecd0636
| 38,335
|
lua
|
Lua
|
Skada/Modules/Healing.lua
|
bkader/Skada-Revisited
|
c34efa1d4f5e5a4b9c504674c5f0264473b4c55c
|
[
"MIT"
] | 26
|
2020-10-22T23:48:14.000Z
|
2021-05-07T16:36:54.000Z
|
Skada/Modules/Healing.lua
|
bkader/Skada-Revisited
|
c34efa1d4f5e5a4b9c504674c5f0264473b4c55c
|
[
"MIT"
] | 39
|
2020-10-29T14:37:46.000Z
|
2021-05-04T00:29:53.000Z
|
Skada/Modules/Healing.lua
|
bkader/Skada-Revisited
|
c34efa1d4f5e5a4b9c504674c5f0264473b4c55c
|
[
"MIT"
] | 12
|
2020-10-30T01:21:14.000Z
|
2021-03-07T00:06:16.000Z
|
assert(Skada, "Skada not found!")
-- cache frequently used globals
local pairs, ipairs, select, format, max = pairs, ipairs, select, string.format, math.max
local getSpellInfo, unitClass = Skada.getSpellInfo or GetSpellInfo, Skada.unitClass
local _
-- ============== --
-- Healing module --
-- ============== --
Skada:AddLoadableModule("Healing", function(Skada, L)
if Skada:IsDisabled("Healing") then return end
local mod = Skada:NewModule(L["Healing"])
local playermod = mod:NewModule(L["Healing spell list"])
local targetmod = mod:NewModule(L["Healed target list"])
local spellmod = targetmod:NewModule(L["Healing spell list"])
local tContains = tContains
-- spells in the following table will be ignored.
local ignoredSpells = {}
local function log_heal(set, data, tick)
if data.spellid and tContains(ignoredSpells, data.spellid) then return end
local player = Skada:get_player(set, data.playerid, data.playername, data.playerflags)
if player then
-- get rid of overheal
local amount = max(0, data.amount - data.overheal)
Skada:AddActiveTime(player, (player.role == "HEALER" and amount > 0 and not data.petname))
-- record the healing
player.heal = (player.heal or 0) + amount
set.heal = (set.heal or 0) + amount
-- record the overheal
player.overheal = (player.overheal or 0) + data.overheal
set.overheal = (set.overheal or 0) + data.overheal
-- record the spell
local spell = player.heal_spells and player.heal_spells[data.spellid]
if not spell then
player.heal_spells = player.heal_spells or {}
player.heal_spells[data.spellid] = {school = data.spellschool, amount = 0, overheal = 0}
spell = player.heal_spells[data.spellid]
end
spell.ishot = tick or nil
spell.count = (spell.count or 0) + 1
spell.amount = spell.amount + amount
spell.overheal = spell.overheal + data.overheal
if (not spell.min or amount < spell.min) and amount > 0 then
spell.min = amount
end
if (not spell.max or amount > spell.max) and amount > 0 then
spell.max = amount
end
if data.critical then
spell.critical = (spell.critical or 0) + 1
end
-- saving this to total set may become a memory hog deluxe.
if set == Skada.current and data.dstName then
-- spell targets
local target = spell.targets and spell.targets[data.dstName]
if not target then
spell.targets = spell.targets or {}
spell.targets[data.dstName] = {id = data.dstGUID, amount = amount, overheal = data.overheal}
target = spell.targets[data.dstName]
else
target.id = target.id or data.dstGUID -- GUID fix
target.amount = target.amount + amount
target.overheal = target.overheal + data.overheal
end
-- player targets
target = player.heal_targets and player.heal_targets[data.dstName]
if not target then
player.heal_targets = player.heal_targets or {}
player.heal_targets[data.dstName] = {id = data.dstGUID, amount = amount, overheal = data.overheal}
target = player.heal_targets[data.dstName]
else
target.id = target.id or data.dstGUID -- GUID fix
target.amount = target.amount + amount
target.overheal = target.overheal + data.overheal
end
end
end
end
local heal = {}
local function SpellHeal(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
local spellid = ...
srcGUID, srcName, srcFlags = Skada:FixUnit(spellid, srcGUID, srcName, srcFlags)
heal.playerid = srcGUID
heal.playername = srcName
heal.playerflags = srcFlags
heal.dstGUID = dstGUID
heal.dstName = dstName
heal.spellid, _, heal.spellschool, heal.amount, heal.overheal, _, heal.critical = ...
heal.petname = nil
Skada:FixPets(heal)
log_heal(Skada.current, heal, eventtype == "SPELL_PERIODIC_HEAL")
log_heal(Skada.total, heal, eventtype == "SPELL_PERIODIC_HEAL")
end
local function getHPS(set, player)
local amount = player.heal or 0
return amount / max(1, Skada:PlayerActiveTime(set, player)), amount
end
local function getRaidHPS(set)
return (set.heal or 0) / max(1, Skada:GetSetTime(set)), (set.heal or 0)
end
local function playermod_tooltip(win, id, label, tooltip)
local player = Skada:find_player(win:get_selected_set(), win.playerid)
if player then
local spell = player.heal_spells and player.heal_spells[id]
if spell then
tooltip:AddLine(player.name .. " - " .. label)
if spell.school then
local c = Skada.schoolcolors[spell.school]
local n = Skada.schoolnames[spell.school]
if c and n then
tooltip:AddLine(n, c.r, c.g, c.b)
end
end
tooltip:AddDoubleLine(L["Count"], spell.count, 1, 1, 1)
if spell.min and spell.max then
tooltip:AddDoubleLine(L["Minimum"], Skada:FormatNumber(spell.min), 1, 1, 1)
tooltip:AddDoubleLine(L["Maximum"], Skada:FormatNumber(spell.max), 1, 1, 1)
end
tooltip:AddDoubleLine(L["Average"], Skada:FormatNumber(spell.amount / spell.count), 1, 1, 1)
if (spell.critical or 0) > 0 then
tooltip:AddDoubleLine(L["Critical"], Skada:FormatPercent(spell.critical, spell.count), 1, 1, 1)
end
if spell.overheal > 0 then
tooltip:AddDoubleLine(L["Overhealing"], Skada:FormatPercent(spell.overheal, spell.overheal + spell.amount), 1, 1, 1)
end
end
end
end
function spellmod:Enter(win, id, label)
win.targetid, win.targetname = id, label
win.title = format(L["%s's healing on %s"], win.playername or UNKNOWN, label)
end
function spellmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's healing on %s"], player.name, win.targetname or UNKNOWN)
local total = 0
if player.heal_targets and win.targetname and player.heal_targets[win.targetname] then
total = player.heal_targets[win.targetname].amount
end
if total > 0 and player.heal_spells then
local maxvalue, nr = 0, 1
for spellid, spell in pairs(player.heal_spells) do
if spell.targets and spell.targets[win.targetname] then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = spell.targets[win.targetname].amount or 0
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function playermod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's healing spells"], label)
end
function playermod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's healing spells"], player.name)
local total = select(2, getHPS(set, player))
if total > 0 and player.heal_spells then
local maxvalue, nr = 0, 1
for spellid, spell in pairs(player.heal_spells) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = spell.amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function targetmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's healed targets"], label)
end
function targetmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's healed targets"], player.name)
local total = select(2, getHPS(set, player))
if total > 0 and player.heal_targets then
local maxvalue, nr = 0, 1
for targetname, target in pairs(player.heal_targets) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = target.id or targetname
d.label = targetname
d.class, d.role, d.spec = select(2, unitClass(d.id, nil, set))
d.value = target.amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function mod:Update(win, set)
win.title = L["Healing"]
local total = select(2, getRaidHPS(set))
if total > 0 then
local maxvalue, nr = 0, 1
for _, player in ipairs(set.players) do
if player.heal then
local hps, amount = getHPS(set, player)
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.text = Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
self.metadata.columns.Healing,
Skada:FormatNumber(hps),
self.metadata.columns.HPS,
Skada:FormatPercent(d.value, total),
self.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
function mod:OnEnable()
playermod.metadata = {tooltip = playermod_tooltip}
targetmod.metadata = {showspots = true, click1 = spellmod}
self.metadata = {
showspots = true,
click1 = playermod,
click2 = targetmod,
nototalclick = {targetmod},
columns = {Healing = true, HPS = true, Percent = true},
icon = "Interface\\Icons\\spell_nature_healingtouch"
}
Skada:RegisterForCL(SpellHeal, "SPELL_HEAL", {src_is_interesting = true})
Skada:RegisterForCL(SpellHeal, "SPELL_PERIODIC_HEAL", {src_is_interesting = true})
Skada:AddMode(self, L["Absorbs and Healing"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:GetSetSummary(set)
local hps, value = getRaidHPS(set)
return Skada:FormatValueText(
Skada:FormatNumber(value),
self.metadata.columns.Healing,
Skada:FormatNumber(hps),
self.metadata.columns.HPS
), value
end
end)
-- ================== --
-- Overhealing module --
-- ================== --
Skada:AddLoadableModule("Overhealing", function(Skada, L)
if Skada:IsDisabled("Healing", "Overhealing") then return end
local mod = Skada:NewModule(L["Overhealing"])
local playermod = mod:NewModule(L["Overheal spell list"])
local targetmod = mod:NewModule(L["Overhealed target list"])
local spellmod = targetmod:NewModule(L["Overheal spell list"])
function spellmod:Enter(win, id, label)
win.targetid, win.targetname = id, label
win.title = format(L["%s's overhealing on %s"], win.playername or UNKNOWN, label)
end
function spellmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's overhealing on %s"], player.name, win.targetname or UNKNOWN)
local total = 0
if player.heal_targets and win.targetname and player.heal_targets[win.targetname] then
total = player.heal_targets[win.targetname].overheal or 0
end
if total > 0 and player.heal_spells then
local maxvalue, nr = 0, 1
for spellid, spell in pairs(player.heal_spells) do
if spell.targets and spell.targets[win.targetname] then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = spell.targets[win.targetname].overheal or 0
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Overhealing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function playermod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's overheal spells"], label)
end
function playermod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's overheal spells"], player.name)
if player.heal_spells then
local maxvalue, nr = 0, 1
for spellid, spell in pairs(player.heal_spells) do
if spell.overheal > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = spell.overheal / (spell.amount + spell.overheal)
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(spell.overheal),
mod.metadata.columns.Overhealing,
Skada:FormatPercent(100 * d.value),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function targetmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's overhealed targets"], label)
end
function targetmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's overhealed targets"], player.name)
if player.heal_targets then
local maxvalue, nr = 0, 1
for targetname, target in pairs(player.heal_targets) do
if target.overheal > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = target.id or targetname
d.label = targetname
d.class, d.role, d.spec = select(2, unitClass(d.id, nil, set))
d.value = target.overheal / (target.amount + target.overheal)
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(target.overheal),
mod.metadata.columns.Overhealing,
Skada:FormatPercent(100 * d.value),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function mod:Update(win, set)
win.title = L["Overhealing"]
if (set.overheal or 0) > 0 then
local maxvalue, nr = 0, 1
for _, player in ipairs(set.players) do
if (player.overheal or 0) > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.text = Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
local total = player.heal + player.overheal
d.value = player.overheal
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
self.metadata.columns.Overhealing,
Skada:FormatPercent(d.value, total),
self.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
function mod:OnEnable()
targetmod.metadata = {click1 = spellmod}
self.metadata = {
showspots = true,
click1 = playermod,
click2 = targetmod,
nototalclick = {targetmod},
columns = {Overhealing = true, Percent = true},
icon = "Interface\\Icons\\spell_holy_holybolt"
}
Skada:AddMode(self, L["Absorbs and Healing"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:GetSetSummary(set)
return Skada:FormatNumber(set.overheal or 0), set.overheal or 0
end
end)
-- ==================== --
-- Total healing module --
-- ==================== --
Skada:AddLoadableModule("Total Healing", function(Skada, L)
if Skada:IsDisabled("Healing", "Total Healing") then return end
local mod = Skada:NewModule(L["Total Healing"])
local playermod = mod:NewModule(L["Healing spell list"])
local targetmod = mod:NewModule(L["Healed target list"])
local spellmod = targetmod:NewModule(L["Healing spell list"])
local function getHPS(set, player)
local amount = (player.heal or 0) + (player.overheal or 0)
return amount / max(1, Skada:PlayerActiveTime(set, player)), amount
end
local function getRaidHPS(set)
local amount = (set.heal or 0) + (set.overheal or 0)
return amount / max(1, Skada:GetSetTime(set)), amount
end
local function spell_tooltip(win, id, label, tooltip)
local player = Skada:find_player(win:get_selected_set(), win.playerid)
if player then
local spell = player.heal_spells and player.heal_spells[id]
if spell then
tooltip:AddLine(player.name .. " - " .. label)
if spell.school then
local c = Skada.schoolcolors[spell.school]
local n = Skada.schoolnames[spell.school]
if c and n then
tooltip:AddLine(n, c.r, c.g, c.b)
end
end
if spell.min and spell.max then
tooltip:AddDoubleLine(L["Minimum"], Skada:FormatNumber(spell.min), 1, 1, 1)
tooltip:AddDoubleLine(L["Maximum"], Skada:FormatNumber(spell.max), 1, 1, 1)
tooltip:AddDoubleLine(L["Average"], Skada:FormatNumber(spell.amount / spell.count), 1, 1, 1)
tooltip:AddLine(" ")
end
local total = spell.amount + spell.overheal
tooltip:AddDoubleLine(L["Total"], Skada:FormatNumber(total), 1, 1, 1)
if spell.amount > 0 then
tooltip:AddDoubleLine(L["Healing"], format("%s (%s)", Skada:FormatNumber(spell.amount), Skada:FormatPercent(spell.amount, total)), 1, 1, 1)
end
if spell.overheal > 0 then
tooltip:AddDoubleLine(L["Overhealing"], format("%s (%s)", Skada:FormatNumber(spell.overheal), Skada:FormatPercent(spell.overheal, total)), 1, 1, 1)
end
end
end
end
function spellmod:Enter(win, id, label)
win.targetid, win.targetname = id, label
win.title = format(L["%s's healing on %s"], win.playername or UNKNOWN, label)
end
function spellmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's healing on %s"], player.name, win.targetname or UNKNOWN)
local total = 0
if player.heal_targets and win.targetname and player.heal_targets[win.targetname] then
total = (player.heal_targets[win.targetname].amount or 0) + (player.heal_targets[win.targetname].overheal or 0)
end
if total > 0 and player.heal_spells then
local maxvalue, nr = 0, 1
for spellid, spell in pairs(player.heal_spells) do
if spell.targets and spell.targets[win.targetname] then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = (spell.targets[win.targetname].amount or 0) + (spell.targets[win.targetname].overheal or 0)
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function playermod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's healing spells"], label)
end
function playermod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's healing spells"], player.name)
local total = (player.heal or 0) + (player.overheal or 0)
if total > 0 and player.heal_spells then
local maxvalue, nr = 0, 1
for spellid, spell in pairs(player.heal_spells) do
local amount = spell.amount + spell.overheal
if amount > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function targetmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's healed targets"], label)
end
function targetmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's healed targets"], player.name)
local total = (player.heal or 0) + (player.overheal or 0)
if total > 0 and player.heal_targets then
local maxvalue, nr = 0, 1
for targetname, target in pairs(player.heal_targets) do
local amount = target.amount + target.overheal
if amount > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = target.id or targetname
d.label = targetname
d.class, d.role, d.spec = select(2, unitClass(d.id, nil, set))
d.value = amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function mod:Update(win, set)
win.title = L["Total Healing"]
local total = select(2, getRaidHPS(set))
if total > 0 then
local maxvalue, nr = 0, 1
for _, player in ipairs(set.players) do
local hps, amount = getHPS(set, player)
if amount > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.text = Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
self.metadata.columns.Healing,
Skada:FormatNumber(hps),
self.metadata.columns.HPS,
Skada:FormatPercent(d.value, total),
self.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
function mod:OnEnable()
targetmod.metadata = {showspots = true, click1 = spellmod}
playermod.metadata = {tooltip = spell_tooltip}
self.metadata = {
showspots = true,
click1 = playermod,
click2 = targetmod,
nototalclick = {targetmod},
columns = {Healing = true, HPS = true, Percent = true},
icon = "Interface\\Icons\\spell_holy_flashheal"
}
Skada:AddMode(self, L["Absorbs and Healing"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:GetSetSummary(set)
local hps, value = getRaidHPS(set)
return Skada:FormatValueText(
Skada:FormatNumber(value),
self.metadata.columns.Healing,
Skada:FormatNumber(hps),
self.metadata.columns.HPS
), value
end
end)
-- ============================== --
-- Healing and overheal module --
-- ============================== --
Skada:AddLoadableModule("Healing and Overhealing", function(Skada, L)
if Skada:IsDisabled("Healing", "Healing and Overhealing") then return end
local mod = Skada:NewModule(L["Healing and Overhealing"])
local playermod = mod:NewModule(L["Heal and overheal spells"])
local targetmod = mod:NewModule(L["Healed and overhealed targets"])
local spellmod = targetmod:NewModule(L["Heal and overheal spells"])
function spellmod:Enter(win, id, label)
win.targetid, win.targetname = id, label
win.title = format(L["%s's healing and overhealing on %s"], win.playername or UNKNOWN, label)
end
function spellmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's healing and overhealing on %s"], player.name, win.targetname or UNKNOWN)
local total = 0
if player.heal_targets and win.targetname and player.heal_targets[win.targetname] then
total = (player.heal_targets[win.targetname].amount or 0) + (player.heal_targets[win.targetname].overheal or 0)
end
if total > 0 and player.heal_spells then
local maxvalue, nr = 0, 1
for spellid, spell in pairs(player.heal_spells) do
if spell.targets and spell.targets[win.targetname] then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = (spell.targets[win.targetname].amount or 0) + (spell.targets[win.targetname].overheal or 0)
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(spell.targets[win.targetname].amount or 0),
mod.metadata.columns.Healing,
Skada:FormatNumber(spell.targets[win.targetname].overheal or 0),
mod.metadata.columns.Overhealing,
Skada:FormatPercent(spell.targets[win.targetname].overheal or 0, d.value),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function playermod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's heal and overheal spells"], label)
end
function playermod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's heal and overheal spells"], player.name)
local total = (player.heal or 0) + (player.overheal or 0)
if total > 0 and player.heal_spells then
local maxvalue, nr = 0, 1
for spellid, spell in pairs(player.heal_spells) do
local amount = spell.amount + spell.overheal
if amount > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(amount),
mod.metadata.columns.Healing,
Skada:FormatNumber(spell.overheal),
mod.metadata.columns.Overhealing,
Skada:FormatPercent(spell.overheal, amount),
mod.metadata.columns.Percent
)
if amount > maxvalue then
maxvalue = amount
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function targetmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's healed and overhealed targets"], label)
end
function targetmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's healed and overhealed targets"], player.name)
local total = (player.heal or 0) + (player.overheal or 0)
if total > 0 and player.heal_targets then
local maxvalue, nr = 0, 1
for targetname, target in pairs(player.heal_targets) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = target.id or targetname
d.label = targetname
d.class, d.role, d.spec = select(2, unitClass(d.id, nil, set))
d.value = target.amount + target.overheal
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatNumber(target.overheal),
mod.metadata.columns.Overhealing,
Skada:FormatPercent(target.overheal, d.value),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function mod:Update(win, set)
win.title = L["Healing and Overhealing"]
local total = (set.heal or 0) + (set.overheal or 0)
if total > 0 then
local maxvalue, nr = 0, 1
for _, player in ipairs(set.players) do
if (player.heal or 0) > 0 then
local amount = player.heal + (player.overheal or 0)
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.text = Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(amount),
self.metadata.columns.Healing,
Skada:FormatNumber(player.overheal),
self.metadata.columns.Overhealing,
Skada:FormatPercent(player.overheal, total),
self.metadata.columns.Percent
)
if amount > maxvalue then
maxvalue = amount
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
function mod:OnEnable()
targetmod.metadata = {showspots = true, click1 = spellmod}
self.metadata = {
showspots = true,
click1 = playermod,
click2 = targetmod,
nototalclick = {targetmod},
columns = {Healing = true, Overhealing = true, Percent = true},
icon = "Interface\\Icons\\spell_holy_prayerofhealing02"
}
Skada:AddMode(self, L["Absorbs and Healing"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:GetSetSummary(set)
local healing = set.heal or 0
local overheal = set.overheal or 0
local value = healing + overheal
return Skada:FormatValueText(
Skada:FormatNumber(value),
self.metadata.columns.Healing,
Skada:FormatNumber(overheal),
self.metadata.columns.Overhealing,
Skada:FormatPercent(overheal, value),
self.metadata.columns.Percent
), value
end
end)
-- ================ --
-- Healing taken --
-- ================ --
Skada:AddLoadableModule("Healing Taken", function(Skada, L)
if Skada:IsDisabled("Healing", "Healing Taken") then return end
local mod = Skada:NewModule(L["Healing Taken"])
local sourcemod = mod:NewModule(L["Healing source list"])
local spellmod = sourcemod:NewModule(L["Healing spell list"])
local newTable, delTable, cacheTable = Skada.newTable, Skada.delTable
function spellmod:Enter(win, id, label)
win.targetid, win.targetname = id, label
win.title = format(L["%s's healing on %s"], win.playername or UNKNOWN, label)
end
function spellmod:Update(win, set)
local player = Skada:find_player(set, win.targetid, win.targetname)
if player then
win.title = format(L["%s's healing on %s"], player.name, win.targetname or UNKNOWN)
local total = 0
if player.heal_targets and win.playername and player.heal_targets[win.playername] then
total = player.heal_targets[win.playername].amount
end
if player.absorb_targets and win.playername and player.absorb_targets[win.playername] then
total = player.absorb_targets[win.playername].amount
end
if total > 0 then
local maxvalue, nr = 0, 1
if player.heal_spells then
for spellid, spell in pairs(player.heal_spells) do
if spell.targets and spell.targets[win.playername] then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
if spell.ishot then
d.text = d.label .. L["HoT"]
end
d.value = spell.targets[win.playername].amount or 0
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
end
if player.absorb_spells then
for spellid, spell in pairs(player.absorb_spells) do
if spell.targets and spell.targets[win.playername] then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.spellschool = spell.school
d.label, _, d.icon = getSpellInfo(spellid)
d.value = spell.targets[win.playername].amount or 0
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
end
win.metadata.maxvalue = maxvalue
end
end
end
function sourcemod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's received healing"], label)
end
function sourcemod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's received healing"], player.name)
cacheTable = newTable()
local total = 0
for _, p in ipairs(set.players) do
if p.heal_targets then
for targetname, target in pairs(p.heal_targets) do
if targetname == player.name then
total = total + target.amount -- increment total
cacheTable[p.name] = {
id = p.id,
class = p.class,
role = p.role,
spec = p.spec,
amount = target.amount,
overheal = target.overheal
}
break
end
end
end
if p.absorb and p.absorb_targets then
for targetname, target in pairs(p.absorb_targets) do
if targetname == player.name then
total = total + target.amount -- increment total
if not cacheTable[p.name] then
cacheTable[p.name] = {
id = p.id,
class = p.class,
role = p.role,
spec = p.spec,
amount = target.amount,
overheal = 0
}
else
cacheTable[p.name].amount = cacheTable[p.name].amount + target.amount
end
break
end
end
end
end
if total > 0 then
local maxvalue, nr = 0, 1
for sourcename, source in pairs(cacheTable) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = source.id
d.label = sourcename
d.text = Skada:FormatName(sourcename, source.id)
d.class = source.class
d.role = source.role
d.spec = source.spec
d.value = source.amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatNumber(source.overheal or 0),
mod.metadata.columns.Overhealing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
delTable(cacheTable)
end
end
function mod:Update(win, set)
win.title = L["Healing Taken"]
local total = set.heal or 0
if total > 0 then
cacheTable = newTable()
for _, player in ipairs(set.players) do
if player.heal_targets then
for targetname, target in pairs(player.heal_targets) do
if not cacheTable[targetname] then
cacheTable[targetname] = {
id = target.id,
amount = target.amount,
overheal = target.overheal
}
else
cacheTable[targetname].amount = cacheTable[targetname].amount + target.amount
cacheTable[targetname].overheal = cacheTable[targetname].overheal + target.overheal
end
end
end
if player.absorb_targets then
for targetname, target in pairs(player.absorb_targets) do
if not cacheTable[targetname] then
cacheTable[targetname] = {
id = target.id,
amount = target.amount,
overheal = 0
}
else
cacheTable[targetname].amount = cacheTable[targetname].amount + target.amount
end
end
end
end
local maxvalue, nr = 0, 1
for playername, player in pairs(cacheTable) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = playername
d.text = Skada:FormatName(playername, player.id)
d.class, d.role, d.spec = select(2, unitClass(d.id, nil, set))
d.value = player.amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Healing,
Skada:FormatNumber(player.overheal),
mod.metadata.columns.Overhealing,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
delTable(cacheTable)
end
end
function mod:OnEnable()
sourcemod.metadata = {showspots = true, click1 = spellmod}
self.metadata = {
showspots = true,
click1 = sourcemod,
columns = {Healing = true, Overhealing = true, Percent = true},
icon = "Interface\\Icons\\spell_nature_resistnature"
}
Skada:AddMode(self, L["Absorbs and Healing"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:GetSetSummary(set)
local amount = (set.heal or 0) + (set.absorb or 0)
return Skada:FormatNumber(amount), amount
end
end)
| 28.417346
| 152
| 0.657728
|
02c4f515a6b71a8fbb043160292801f223f6ee4d
| 1,338
|
cpp
|
C++
|
src/test/subsidy_tests.cpp
|
OwenRay/zeroonecoin
|
c1cda5840196746a508de702e4c28fe8f017453b
|
[
"MIT"
] | 13
|
2018-03-25T20:35:46.000Z
|
2021-02-15T14:33:40.000Z
|
src/test/subsidy_tests.cpp
|
OwenRay/zeroonecoin
|
c1cda5840196746a508de702e4c28fe8f017453b
|
[
"MIT"
] | 21
|
2018-03-30T21:57:01.000Z
|
2020-08-05T23:06:41.000Z
|
src/test/subsidy_tests.cpp
|
OwenRay/zeroonecoin
|
c1cda5840196746a508de702e4c28fe8f017453b
|
[
"MIT"
] | 15
|
2018-03-29T13:40:27.000Z
|
2021-12-25T18:08:54.000Z
|
// Copyright (c) 2014-2018 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "validation.h"
#include "test/test_zeroone.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(subsidy_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
const Consensus::Params& consensusParams = Params(CBaseChainParams::MAIN).GetConsensus();
uint32_t nPrevBits;
int32_t nPrevHeight;
CAmount nSubsidy;
nPrevBits = 0x1c4a47c4;
nPrevHeight = 262770;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 2383333334ULL);
nPrevBits = 0x1c4a47c4;
nPrevHeight = 262801;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 2383333334ULL);
nPrevBits = 0x1c29ec00;
nPrevHeight = 525599;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 2184722223ULL);
nPrevBits = 0x1c29ec00;
nPrevHeight = 525601;
nSubsidy = GetBlockSubsidy(nPrevBits, nPrevHeight, consensusParams, false);
BOOST_CHECK_EQUAL(nSubsidy, 2184722223ULL);
}
BOOST_AUTO_TEST_SUITE_END()
| 30.409091
| 93
| 0.762332
|
7c064547ee317bb0ee4b5cdf5223b837a5a7f321
| 56
|
py
|
Python
|
src/rstatmon/random_int.py
|
git-ogawa/raspi-statmon
|
619d7a8f697cad92437e2f558de2e0a626b5072f
|
[
"BSD-3-Clause"
] | null | null | null |
src/rstatmon/random_int.py
|
git-ogawa/raspi-statmon
|
619d7a8f697cad92437e2f558de2e0a626b5072f
|
[
"BSD-3-Clause"
] | null | null | null |
src/rstatmon/random_int.py
|
git-ogawa/raspi-statmon
|
619d7a8f697cad92437e2f558de2e0a626b5072f
|
[
"BSD-3-Clause"
] | null | null | null |
import random
i = random.random()
print(i)
#"print(50)
| 9.333333
| 19
| 0.678571
|
a335f687c632fa6e8c0e2715061cca1ed7b70ce8
| 950
|
dart
|
Dart
|
lib/src/iran_app_market.dart
|
ali2236/iran_appmarket
|
836cc02bf920f164d1dd17433bee11683895146e
|
[
"MIT"
] | null | null | null |
lib/src/iran_app_market.dart
|
ali2236/iran_appmarket
|
836cc02bf920f164d1dd17433bee11683895146e
|
[
"MIT"
] | null | null | null |
lib/src/iran_app_market.dart
|
ali2236/iran_appmarket
|
836cc02bf920f164d1dd17433bee11683895146e
|
[
"MIT"
] | null | null | null |
import 'package:flutter/services.dart';
import 'package:iran_appmarket/src/app_market.dart';
import 'package:package_info_plus/package_info_plus.dart';
class IranAppMarket {
static MethodChannel _channel = MethodChannel('ir.aligator.iran.appmarket');
static const Map<AppMarket, int> _market_id = const {
AppMarket.cafeBazaar : 0,
AppMarket.myket : 1,
AppMarket.iranApps : 2,
AppMarket.jhoobin : 3,
};
static void showAppPage(AppMarket market) async{
final packageName = (await PackageInfo.fromPlatform()).packageName;
IAppMarket.ofType(market).showAppPage(packageName);
}
static void showAppComments(AppMarket market) async{
final packageName = (await PackageInfo.fromPlatform()).packageName;
IAppMarket.ofType(market).showAppComments(packageName);
}
static void showDeveloperApps(AppMarket market, String developerId) async{
IAppMarket.ofType(market).showDeveloperApps(developerId);
}
}
| 30.645161
| 78
| 0.758947
|
4655f5eb1e81e27dbbe31576da8d121217b6239a
| 1,965
|
php
|
PHP
|
src/Repository/Directories.php
|
K-Phoen/travelr
|
f434d814bdc6fad10060f571650390e19e6f2231
|
[
"MIT"
] | 4
|
2018-04-01T05:46:38.000Z
|
2020-03-02T20:48:56.000Z
|
src/Repository/Directories.php
|
K-Phoen/travelr
|
f434d814bdc6fad10060f571650390e19e6f2231
|
[
"MIT"
] | 2
|
2018-04-02T23:10:55.000Z
|
2018-04-16T13:38:38.000Z
|
src/Repository/Directories.php
|
K-Phoen/travelr
|
f434d814bdc6fad10060f571650390e19e6f2231
|
[
"MIT"
] | null | null | null |
<?php
declare(strict_types=1);
namespace Travelr\Repository;
use Symfony\Component\Finder\Finder;
use Travelr\Directory;
use Travelr\Config\DirectoryParser;
use Travelr\GlobalConfig;
class Directories
{
private const CONFIG_FILENAME = 'config.yaml';
private const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png'];
/** @var DirectoryParser */
private $configParser;
public function __construct(DirectoryParser $configParser)
{
$this->configParser = $configParser;
}
/**
* @return iterable|Directory[]
*/
public function findAll(string $webRoot, GlobalConfig $config): iterable
{
$finder = new Finder();
$finder
->files()
->name(self::CONFIG_FILENAME)
->depth(1)
->sortByName()
->in($webRoot.'/data');
foreach ($finder as $configFile) {
$directoryConfig = $this->configParser->read($configFile->getPathname());
yield new Directory(
\dirname($configFile->getPathname()),
$directoryConfig,
$this->imagesPaths($configFile->getPath(), $config)
);
}
}
private function imagesPaths(string $directory, GlobalConfig $config): iterable
{
$finder = new Finder();
$finder
->files()
->filter(function (\SplFileInfo $fileInfo) {
$extension = strtolower($fileInfo->getExtension());
return \in_array($extension, self::ALLOWED_EXTENSIONS, true);
})
->depth(0)
->in($directory);
if ($config->sortImagesBy() === GlobalConfig::SORT_BY_NAME) {
$finder->sortByName();
} elseif ($config->sortImagesBy() === GlobalConfig::SORT_BY_MODIFICATION_DATE) {
$finder->sortByModifiedTime();
}
foreach ($finder as $file) {
yield $file->getPathname();
}
}
}
| 26.554054
| 88
| 0.568448
|
44657595c9d00b2b46a57f53fe7d2cb40b41dc85
| 74
|
sql
|
SQL
|
hasura/migrations/1618704829679_alter_table_public_Room_add_column_videoRoomBackend/up.sql
|
LasseWolter/clowdr
|
4777fc8386a7cd4f09b7a366ccd01662608c3e01
|
[
"BSD-3-Clause"
] | 49
|
2021-01-09T07:09:08.000Z
|
2022-03-27T05:16:46.000Z
|
hasura/migrations/1618704829679_alter_table_public_Room_add_column_videoRoomBackend/up.sql
|
LasseWolter/clowdr
|
4777fc8386a7cd4f09b7a366ccd01662608c3e01
|
[
"BSD-3-Clause"
] | 333
|
2021-01-17T14:52:22.000Z
|
2022-03-10T02:38:53.000Z
|
hasura/migrations/1618704829679_alter_table_public_Room_add_column_videoRoomBackend/up.sql
|
LasseWolter/clowdr
|
4777fc8386a7cd4f09b7a366ccd01662608c3e01
|
[
"BSD-3-Clause"
] | 15
|
2021-01-29T14:17:38.000Z
|
2022-02-14T22:13:48.000Z
|
alter table "public"."Room" add column "videoRoomBackendName" text
null;
| 24.666667
| 66
| 0.77027
|
0dc2bd9edead0542f1daae3d5588361c94424750
| 1,013
|
cs
|
C#
|
src/Riven.EntityFrameworkCore.PostgreSQL/Storage/Internal/RivenPostgreSqlGenerationHelper.cs
|
rivenfx/EntityFrameworkCore
|
de4c6cd3d3970ffbb44da4a3060337b0aa87c800
|
[
"Apache-2.0"
] | 6
|
2020-11-25T01:08:33.000Z
|
2021-08-17T23:56:23.000Z
|
src/Riven.EntityFrameworkCore.PostgreSQL/Storage/Internal/RivenPostgreSqlGenerationHelper.cs
|
rivenfx/EntityFrameworkCore
|
de4c6cd3d3970ffbb44da4a3060337b0aa87c800
|
[
"Apache-2.0"
] | 1
|
2021-12-31T02:40:12.000Z
|
2021-12-31T02:40:12.000Z
|
src/Riven.EntityFrameworkCore.PostgreSQL/Storage/Internal/RivenPostgreSqlGenerationHelper.cs
|
rivenfx/EntityFrameworkCore
|
de4c6cd3d3970ffbb44da4a3060337b0aa87c800
|
[
"Apache-2.0"
] | 1
|
2020-12-15T08:16:56.000Z
|
2020-12-15T08:16:56.000Z
|
using JetBrains.Annotations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal;
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.EntityFrameworkCore.Storage.Internal
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "EF1001:Internal EF Core API usage.", Justification = "<挂起>")]
public class RivenPostgreSqlGenerationHelper : NpgsqlSqlGenerationHelper
{
public RivenPostgreSqlGenerationHelper([NotNull] RelationalSqlGenerationHelperDependencies dependencies)
: base(dependencies)
{
}
public override string EscapeIdentifier(string identifier)
{
return base.EscapeIdentifier(
identifier.ToLower()
);
}
public override void EscapeIdentifier(StringBuilder builder, string identifier)
{
base.EscapeIdentifier(
builder,
identifier.ToLower()
);
}
}
}
| 28.942857
| 124
| 0.659427
|
05e02ac2e78ea8cce2d41e9ee79a4091c181332c
| 714
|
py
|
Python
|
run.py
|
xiaoland/DaemonReminder
|
e9b23dca901a57b63bc244816dd85d81102016ec
|
[
"Apache-2.0"
] | null | null | null |
run.py
|
xiaoland/DaemonReminder
|
e9b23dca901a57b63bc244816dd85d81102016ec
|
[
"Apache-2.0"
] | null | null | null |
run.py
|
xiaoland/DaemonReminder
|
e9b23dca901a57b63bc244816dd85d81102016ec
|
[
"Apache-2.0"
] | null | null | null |
# author: Lan_zhijiang
# description: Launch program
# date: 2021/08/26
from log import Log
from tts import BaiduTts
from encryption import Encryption
from main import DaemonReminderMain
from ui import DaemonReminderApp
import json
class Base:
def __init__(self):
self.log = Log()
self.setting = json.load(open("./data/json/setting.json", "r", encoding="utf-8"))
self.tasks = json.load(open("data/json/reminds.json"))
# self.tts = BaiduTts(self.log, self.setting)
self.tts = None
self.encryption = Encryption()
if __name__ == "__main__":
base = Base()
main = DaemonReminderMain(base)
app = DaemonReminderApp(base, main)
app.MainLoop()
| 21
| 89
| 0.672269
|
b5cd574257b8ceda549125f724fcc11b4130d8be
| 1,353
|
kt
|
Kotlin
|
mapper/logic/src/test/java/ir/ac/iust/dml/kg/mapper/deprecated/templateequalities/LoaderTest.kt
|
IUST-DMLab/farsbase
|
2e020ae3d619a35ffa00079b9aeb31ca77ce2346
|
[
"Apache-2.0"
] | 1
|
2018-09-23T23:56:52.000Z
|
2018-09-23T23:56:52.000Z
|
mapper/logic/src/test/java/ir/ac/iust/dml/kg/mapper/deprecated/templateequalities/LoaderTest.kt
|
IUST-DMLab/farsbase
|
2e020ae3d619a35ffa00079b9aeb31ca77ce2346
|
[
"Apache-2.0"
] | null | null | null |
mapper/logic/src/test/java/ir/ac/iust/dml/kg/mapper/deprecated/templateequalities/LoaderTest.kt
|
IUST-DMLab/farsbase
|
2e020ae3d619a35ffa00079b9aeb31ca77ce2346
|
[
"Apache-2.0"
] | null | null | null |
/*
* Farsi Knowledge Graph Project
* Iran University of Science and Technology (Year 2017)
* Developed by Majid Asgari.
*/
package ir.ac.iust.dml.kg.mapper.deprecated.templateequalities
import ir.ac.iust.dml.kg.raw.utils.ConfigReader
import ir.ac.iust.dml.kg.raw.utils.dump.wiki.WikiDumpReader
import ir.ac.iust.dml.kg.raw.utils.dump.wiki.WikiDumpWriter
import java.nio.file.Files
/**
* It's not a real standard test!
*/
fun main(args: Array<String>) {
val path = ConfigReader.getPath("wiki.dump.article", "~/.pkg/data/fawiki-latest-pages-articles.xml")
Files.createDirectories(path.parent)
if (!Files.exists(path)) {
throw Exception("There is no file ${path.toAbsolutePath()} existed.")
}
var count = 0
val startTime = System.currentTimeMillis()
WikiDumpReader(path).use { reader ->
WikiDumpWriter(path.parent.resolve("just_templates.xml")).use { writer ->
while (reader.hasNext()) {
val article = reader.next()
if (count % 10000 == 0) println(count)
if (article.ns == 10
&& (article.title!!.startsWith("الگو:جعبه") || article.title!!.startsWith("الگو:Infobox"))
&& article.revision!!.text!!.contains("data1"))
writer.write(article)
count++
}
}
}
println("running time: ${(System.currentTimeMillis() - startTime) / 1000} seconds")
}
| 32.214286
| 102
| 0.672579
|
20d03ed336ae5526053954900ca188c14dfc561e
| 15,480
|
py
|
Python
|
models/nets.py
|
jonnybluesman/emomucs
|
656b271b476b21990629477759f98fbdd09ac4c9
|
[
"Unlicense"
] | 5
|
2020-10-10T17:39:24.000Z
|
2021-09-30T02:48:36.000Z
|
models/nets.py
|
jonnybluesman/emomucs
|
656b271b476b21990629477759f98fbdd09ac4c9
|
[
"Unlicense"
] | null | null | null |
models/nets.py
|
jonnybluesman/emomucs
|
656b271b476b21990629477759f98fbdd09ac4c9
|
[
"Unlicense"
] | 1
|
2021-03-30T14:37:27.000Z
|
2021-03-30T14:37:27.000Z
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
activations = nn.ModuleDict([
['sigmoid', nn.Sigmoid()],
['tanh', nn.Tanh()],
['lrelu', nn.LeakyReLU()],
['relu', nn.ReLU()],
['selu', nn.SELU()],
['elu', nn.ELU()]
])
def compute_flattened_maps(cnn_layers, input_shape):
"""
Utility function to compute the size of the flattened feature maps
after the convolutional layers, which should be passed as input
together with the shape of the input tensors.
"""
x = torch.randn(1, 1, *input_shape)
with torch.no_grad():
x = cnn_layers(x)
return np.prod(x.shape[1:])
def cnn_weights_init(m):
"""
Reinitialise the parameters of a network with custom init functions.
Xavier initialisation is used for Linear layers, whereas convolutional
layers are initialised with the Hu Kaiming method for more stability.
This method only supports, for the moment, conv and linear layers. The idea
of this method is "reset and refine", which ensures that all layer are reinit.
"""
if ("reset_parameters" in dir(m)):
m.reset_parameters() # first of all reset the layer
if isinstance(m, (nn.Conv1d, nn.Conv2d)):
nn.init.kaiming_uniform_(m.weight)
elif isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight)
def torch_weights_init(m):
"""
Reinitialise the parameters of a layer as the good torch would do.
This method is not very useful as it is right now.
"""
if ("reset_parameters" in dir(m)):
m.reset_parameters() # first reset the layer
# TODO: do something more from the specs
def create_dense_block(
in_feats, out_feats, architecture=['fc', 'act', 'drop'],
activation='relu', dropout_prob=0, wrapping=True):
"""
Factory method for fully connected layers, with the possibility
to choose the activation function and the regularisation technique.
TODO:
- add the support for batch normalisation;
"""
assert all(name in ['fc', 'act', 'drop'] for name in architecture)
dense_block = {
'fc': nn.Linear(in_feats, out_feats),
'act' : activations[activation],
'drop': nn.Dropout(p=dropout_prob),
}
dense_block = [dense_block[name] for name in architecture]
return nn.Sequential(*dense_block) if wrapping else dense_block
def create_2d_convolutional_block(
in_feats, num_filters, filter_size, architecture=['bn', 'act', 'pool', 'drop'],
pool_size=(2,2), padding=0, stride=1, activation='relu', dropout_prob=0):
"""
Factory method for convolutional layers, with the possibility.
Args:
in_features (int): number of input features;
num_filters (int): number of kernels;
filter_size (tuple): size of the 2D filters/kernels;
architecture (list): list of strings describing the cnn items;
pool_size (tuple): size of the pooling operation (same of stride);
padding (int or tuple): the amount of padding for each dimension;
stride (int or tuple): stride of the convolutional kernel;
activation (str): namne of the activation function;
dropout_prob (float): probability of dropping out;
"""
assert all(name in ['bn', 'act', 'pool', 'drop'] for name in architecture)
cnn_block = {
'bn' : nn.BatchNorm2d(num_filters),
'act' : activations[activation],
'pool': nn.MaxPool2d(pool_size),
'drop': nn.Dropout(p=dropout_prob),
}
return nn.Sequential(
nn.Conv2d(in_feats, num_filters, filter_size,
padding=padding, stride=stride),
*[cnn_block[name] for name in architecture])
class DeezerConv1d(nn.Module):
"""
Simple implementation of the AudioCNN presented in
"Music Mood Detection Based On Audio And Lyrics With Deep Neural Net".
Code adapted from https://github.com/Dohppak/Music_Emotion_Recognition
"""
def __init__(self, input_shape, n_kernels=[32, 16], kernel_sizes=[8, 8],
mpool_stride=[4, 4], fc_units=[64, 2]):
"""
Class constructor for the creation of a static 1DCNN.
Args:
input_shape (2-tuple): (number of mel bands, frames).
n_kernels (2-tuple): number of 1D filters per conv layer;
kernel_sizes (2-tuple): size of kernels as number of frames;
mpool_stride (2-tuple): strides of 1D max pooling (same as size);
fc_units (2-tuple): number of units in the last fully-connected layers.
TODO:
- Class constructor from sample input instead of specifying nmel;
- The parameterisation of the net can be more beautiful;
- It is still not clear which activation function is used in the first FCL.
"""
super(DeezerConv1d, self).__init__()
self.flattened_size = int(np.floor(
((np.floor((input_shape[1] - kernel_sizes[0] + 1) / mpool_stride[0]))
- kernel_sizes[1] + 1) / mpool_stride[1]) * n_kernels[-1])
self.conv_blocks = nn.Sequential(
nn.Sequential(
nn.Conv1d(input_shape[0], n_kernels[0], kernel_size=kernel_sizes[0]),
nn.MaxPool1d(mpool_stride[0], stride=mpool_stride[0]),
nn.BatchNorm1d(n_kernels[0])),
nn.Sequential(
nn.Conv1d(n_kernels[0], n_kernels[1], kernel_size=kernel_sizes[1]),
nn.MaxPool1d(mpool_stride[1], stride=mpool_stride[1]),
nn.BatchNorm1d(n_kernels[1]))
)
self._fcl = nn.Sequential(
nn.Dropout(),
nn.Linear(in_features=self.flattened_size, out_features=fc_units[0]),
#nn.Tanh(), # we use a relu instead
nn.ReLU(),
nn.Dropout(),
nn.Linear(in_features=fc_units[0], out_features=fc_units[1]),
)
self.apply(self._init_weights)
def convolutional_features(self, x):
x = self.conv_blocks(x)
return x.view(x.size(0), -1)
def forward(self, x):
x_cnn_flat = self.convolutional_features(x)
pred = self._fcl(x_cnn_flat)
return pred
def _init_weights(self, layer) -> None:
if isinstance(layer, nn.Conv1d):
nn.init.kaiming_uniform_(layer.weight)
elif isinstance(layer, nn.Linear):
nn.init.xavier_uniform_(layer.weight)
class VGGishEmoNet(nn.Module):
"""
A VGG-based 2dCNN typically used for music tagging and transfer learning as in:
"Transfer learning for music classification and regression tasks"
Architecture inspired from https://github.com/keunwoochoi/transfer_learning_music/
"""
def __init__(
self, input_shape, n_kernels=[32]*5, kernel_sizes=[(3,3)]*5,
pooling_sizes=None, dropout=0., cnn_activation='elu', fc_units=2):
"""
Class constructor for the creation of a static 2DCNN.
Args:
input_shape (2-tuple): (number of mel bands, frames).
n_kernels (list): number of 2D filters per conv layer;
kernel_sizes (list): size of kernels for each conc layer;
pooling_sizes (list): size of each 2D maxpooling operation;
dropout (float): probability of dropping out conv activations;
cnn_activation (str): name of the activation function for conv layers;
fc_units (int): number of units in the last fully-connected layer.
TODO:
- The parameterisation of the net can be more beautiful;
"""
super(VGGishEmoNet, self).__init__()
if pooling_sizes is None:
pooling_sizes = get_vggish_poolings_from_features(*input_shape)
assert len(n_kernels) == len(kernel_sizes) == len(pooling_sizes)
conv_input_shapes = [1] + n_kernels[:-1]
cnn_arch = ['bn', 'act', 'pool', 'drop']
conv_blocks = [create_2d_convolutional_block(
conv_input_shape, n_kernel, kernel_size, cnn_arch,
pooling_size, 1, 1, cnn_activation, dropout) \
for conv_input_shape, n_kernel, kernel_size, pooling_size \
in zip(conv_input_shapes, n_kernels, kernel_sizes, pooling_sizes)]
self.conv_blocks = nn.Sequential(
*conv_blocks, nn.AdaptiveAvgPool2d((1, 1)))
# the following operation is not needed as we already have the adaptive pooling
# self.flattened_size = compute_flattened_maps(self.conv_blocks, input_shape)
self.flattened_size = n_kernels[-1]
self._fcl = nn.Sequential(
nn.Linear(in_features=self.flattened_size, out_features=fc_units),
)
def convolutional_features(self, x):
x = x.unsqueeze(1) # to ensure n_channels is 1
x = self.conv_blocks(x)
return x.view(x.size(0), -1)
def forward(self, x):
x_cnn_flat = self.convolutional_features(x)
pred = self._fcl(x_cnn_flat)
return pred
class VGGishExplainable(nn.Module):
"""
A VGG-based 2dCNN designed for explainable MER, presented in:
"Towards explainable MER, by using mid-level features".
This is the model that is denoted as A2E in the paper.
"""
def __init__(
self, input_shape, n_kernels=[64, 64, 128, 128, 256, 256, 384, 512, 256],
kernel_sizes=[(5,5)]+[(3,3)]*8, pooling_sizes=[(2, 2), (2, 2)],
strides=[2]+[1]*8, paddings=[2]+[1]*7+[0], dropout=[.3, .3],
cnn_activation='relu', fc_units=2):
"""
Class constructor for the creation of a static 2DCNN.
Args:
input_shape (2-tuple): (number of mel bands, frames).
n_kernels (list): number of 2D filters per conv layer;
kernel_sizes (list): size of kernels for each conc layer;
pooling_sizes (list): size of each 2D maxpooling operation;
dropout (float): probability of dropping out conv activations;
cnn_activation (str): name of the activation function for conv layers;
fc_units (int): number of units in the last fully-connected layer.
TODO:
- The parameterisation of the net can be more beautiful;
"""
super(VGGishExplainable, self).__init__()
assert len(n_kernels) == len(kernel_sizes) == len(strides) == len(paddings)
conv_input_shapes = [1] + n_kernels[:-1]
conv_blocks = [create_2d_convolutional_block(
conv_input_shape, n_kernel, kernel_size, ['bn', 'act'],
None, padding, stride, cnn_activation) \
for conv_input_shape, n_kernel, kernel_size, padding, stride \
in zip(conv_input_shapes, n_kernels, kernel_sizes, paddings, strides)]
self.conv_blocks = nn.Sequential(
*conv_blocks[:2],
nn.MaxPool2d(pooling_sizes[0]),
nn.Dropout(p=dropout[0]),
*conv_blocks[2:4],
nn.MaxPool2d(pooling_sizes[1]),
nn.Dropout(p=dropout[1]),
*conv_blocks[4:],
nn.AdaptiveAvgPool2d((1, 1)),
)
# the following operation is not needed as we already have the adaptive pooling
# flattened_size = compute_flattened_maps(self.conv_blocks, input_shape)
self.flattened_size = n_kernels[-1]
self._fcl = nn.Sequential(
nn.Linear(in_features=self.flattened_size, out_features=fc_units),
)
def convolutional_features(self, x):
x = x.unsqueeze(1) # to ensure n_channels is 1
x = self.conv_blocks(x)
return x.view(x.size(0), -1)
def forward(self, x):
x_cnn_flat = self.convolutional_features(x)
pred = self._fcl(x_cnn_flat)
return pred
def get_vggish_poolings_from_features(n_mels=96, n_frames=1360):
"""
Get the pooling sizes for the standard VGG-based model for audio tagging.
Code from: https://github.com/keunwoochoi/transfer_learning_music/blob/master/models_transfer.py
Todo:
- This code is ugly, reorganise in a config file;
- This method is assuming (at the moment) a certain number of frames (1360 covering 30s);
"""
if n_mels >= 256:
poolings = [(2, 4), (4, 4), (4, 5), (2, 4), (4, 4)]
elif n_mels >= 128:
poolings = [(2, 4), (4, 4), (2, 5), (2, 4), (4, 4)]
elif n_mels >= 96:
poolings = [(2, 4), (3, 4), (2, 5), (2, 4), (4, 4)]
elif n_mels >= 72:
poolings = [(2, 4), (3, 4), (2, 5), (2, 4), (3, 4)]
elif n_mels >= 64:
poolings = [(2, 4), (2, 4), (2, 5), (2, 4), (4, 4)]
elif n_mels >= 48:
poolings = [(2, 4), (2, 4), (2, 5), (2, 4), (3, 4)]
elif n_mels >= 32:
poolings = [(2, 4), (2, 4), (2, 5), (2, 4), (2, 4)]
elif n_mels >= 24:
poolings = [(2, 4), (2, 4), (2, 5), (3, 4), (1, 4)]
elif n_mels >= 18:
poolings = [(2, 4), (1, 4), (3, 5), (1, 4), (3, 4)]
elif n_mels >= 18:
poolings = [(2, 4), (1, 4), (3, 5), (1, 4), (3, 4)]
elif n_mels >= 16:
poolings = [(2, 4), (2, 4), (2, 5), (2, 4), (1, 4)]
elif n_mels >= 12:
poolings = [(2, 4), (1, 4), (2, 5), (3, 4), (1, 4)]
elif n_mels >= 8:
poolings = [(2, 4), (1, 4), (2, 5), (2, 4), (1, 4)]
elif n_mels >= 6:
poolings = [(2, 4), (1, 4), (3, 5), (1, 4), (1, 4)]
elif n_mels >= 4:
poolings = [(2, 4), (1, 4), (2, 5), (1, 4), (1, 4)]
elif n_mels >= 2:
poolings = [(2, 4), (1, 4), (1, 5), (1, 4), (1, 4)]
else: # n_mels == 1
poolings = [(1, 4), (1, 4), (1, 5), (1, 4), (1, 4)]
ratio = n_frames / 1360 # as these measures are referred to this unit
# print([(poo_w, pool_l * ratio) for poo_w, pool_l in poolings])
return [(poo_w, round(pool_l * ratio)) for poo_w, pool_l in poolings]
def simple_param_count(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def tensor_shape_flows_through(conv_blocks, feat_shape):
"""
Currently works just for a CNN...
TODO:
- Make it general for any network
"""
print('Generating random batch of 2 x {} data'.format(feat_shape))
x = torch.rand((2, *feat_shape))
conv_blocks.eval()
conv_blocks.to(device=torch.device('cpu'), dtype=torch.float)
x.to(device=torch.device('cpu'), dtype=torch.float)
print("Initial shape: {}".format(x.shape))
for i, layer in enumerate(conv_blocks):
if isinstance(layer, nn.Sequential):
for j, sub_layer in enumerate(layer):
x = sub_layer(x)
if isinstance(sub_layer, nn.Conv2d) or isinstance(sub_layer, nn.MaxPool2d):
print("Layer {} ({}) | Shape after {}: {} "
.format(i, j, sub_layer.__class__.__name__, x.shape))
else:
x = layer(x)
# only print if the level is expected to afffect the shape
if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.MaxPool2d) or isinstance(layer, nn.AdaptiveAvgPool2d):
print("Layer {} | Shape after {}: {} "
.format(i, layer.__class__.__name__, x.shape))
| 38.034398
| 122
| 0.593605
|
702fe83880ed37ca1c4a68bbf00c395b3e575e2f
| 3,144
|
cpp
|
C++
|
Lesson5/Exercise27/graph_coloring.cpp
|
gogowonji/080239
|
e2af987cf5266f9da515fb2afe17dafe6b1ac01b
|
[
"MIT"
] | 33
|
2020-12-15T07:37:24.000Z
|
2022-03-08T16:26:37.000Z
|
Lesson5/Exercise27/graph_coloring.cpp
|
gogowonji/080239
|
e2af987cf5266f9da515fb2afe17dafe6b1ac01b
|
[
"MIT"
] | 1
|
2021-05-08T19:28:31.000Z
|
2021-05-08T19:28:31.000Z
|
Lesson5/Exercise27/graph_coloring.cpp
|
gogowonji/080239
|
e2af987cf5266f9da515fb2afe17dafe6b1ac01b
|
[
"MIT"
] | 26
|
2021-01-04T07:21:31.000Z
|
2022-02-07T12:39:42.000Z
|
#include <string>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <unordered_map>
using namespace std;
template <typename T>
struct Edge
{
unsigned src;
unsigned dst;
T weight;
// Edge 객체 비교는 가중치를 이용
inline bool operator< (const Edge<T>& e) const
{
return this->weight < e.weight;
}
inline bool operator> (const Edge<T>& e) const
{
return this->weight > e.weight;
}
};
template <typename T>
class Graph
{
public:
// N개의 정점으로 구성된 그래프
Graph(unsigned N) : V(N) {}
// 그래프의 정점 개수 반환
auto vertices() const { return V; }
// 전체 에지 리스트 반환
auto& edges() const { return edge_list; }
// 정점 v에서 나가는 모든 에지를 반환
auto edges(unsigned v) const
{
vector<Edge<T>> edges_from_v;
for (auto& e : edge_list)
{
if (e.src == v)
edges_from_v.emplace_back(e);
}
return edges_from_v;
}
void add_edge(Edge<T>&& e)
{
// 에지 양 끝 정점 ID가 유효한지 검사
if (e.src >= 1 && e.src <= V && e.dst >= 1 && e.dst <= V)
edge_list.emplace_back(e);
else
cerr << "에러: 유효 범위를 벗어난 정점!" << endl;
}
// 표준 출력 스트림 지원
template <typename U>
friend ostream& operator<< (ostream& os, const Graph<U>& G);
private:
unsigned V; // 정점 개수
vector<Edge<T>> edge_list;
};
template <typename U>
ostream& operator<< (ostream& os, const Graph<U>& G)
{
for (unsigned i = 1; i < G.vertices(); i++)
{
os << i << ":\t";
auto edges = G.edges(i);
for (auto& e : edges)
os << "{" << e.dst << ": " << e.weight << "}, ";
os << endl;
}
return os;
}
// 그래프 컬러링에 사용할 색상 번호
unordered_map<unsigned, string> color_map = {
{1, "Red"},
{2, "Blue"},
{3, "Green"},
{4, "Yellow"},
{5, "Black"},
{6, "White"}
};
template<typename T>
auto greedy_coloring(const Graph<T>& G)
{
auto size = G.vertices();
vector<unsigned> assigned_colors(size);
// 1번 정점부터 차례대로 검사합니다.
for (unsigned i = 1; i < size; i++)
{
auto outgoing_edges = G.edges(i);
// i번째 정점과 인접해있는 정점들의 현재 색상
set<unsigned> neighbours;
for (auto& e : outgoing_edges)
{
neighbours.insert(assigned_colors[e.dst]);
}
// 인접한 정점에 칠해지지 않은 색상 중에서 가장 작은 숫자의 색상을 선택
auto smallest = 1;
for (; smallest <= color_map.size(); smallest++)
{
if (neighbours.find(smallest) == neighbours.end())
break;
}
assigned_colors[i] = smallest;
}
return assigned_colors;
}
template <typename T>
void print_colors(vector<T>& colors)
{
for (auto i = 1; i < colors.size(); i++)
{
cout << i << ": " << color_map[colors[i]] << endl;
}
}
int main()
{
using T = unsigned;
// 그래프 객체 생성
Graph<T> G(9);
map<unsigned, vector<pair<unsigned, T>>> edge_map;
edge_map[1] = {{2, 0}, {5, 0}};
edge_map[2] = {{1, 0}, {5, 0}, {4, 0}};
edge_map[3] = {{4, 0}, {7, 0}};
edge_map[4] = {{2, 0}, {3, 0}, {5, 0}, {6, 0}, {8, 0}};
edge_map[5] = {{1, 0}, {2, 0}, {4, 0}, {8, 0}};
edge_map[6] = {{4, 0}, {7, 0}, {8, 0}};
edge_map[7] = {{3, 0}, {6, 0}};
edge_map[8] = {{4, 0}, {5, 0}, {6, 0}};
for (auto& i : edge_map)
for (auto& j : i.second)
G.add_edge(Edge<T>{ i.first, j.first, j.second });
cout << "[입력 그래프]" << endl;
cout << G << endl;
auto colors = greedy_coloring<T>(G);
cout << "[그래프 컬러링]" << endl;
print_colors(colors);
}
| 18.60355
| 61
| 0.579198
|
e06ebe30ba439f507fac29d35b8120691642bd6f
| 1,593
|
h
|
C
|
examples/reliability_block_diagrams/user_code/src/model/basic_types/bijection.h
|
coppit/yagg
|
8fd076d817f28ed6739e6ba0cd246e37e96fc00c
|
[
"FSFAP"
] | 4
|
2016-07-22T03:28:21.000Z
|
2020-08-20T23:38:36.000Z
|
examples/reliability_block_diagrams/user_code/src/model/basic_types/bijection.h
|
coppit/yagg
|
8fd076d817f28ed6739e6ba0cd246e37e96fc00c
|
[
"FSFAP"
] | null | null | null |
examples/reliability_block_diagrams/user_code/src/model/basic_types/bijection.h
|
coppit/yagg
|
8fd076d817f28ed6739e6ba0cd246e37e96fc00c
|
[
"FSFAP"
] | null | null | null |
#ifndef BIJECTION_H
#define BIJECTION_H
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
#pragma set woff 1174
#pragma set woff 1375
#endif
#include "basic_types/function.h"
#include <cassert>
#include <set>
using namespace std;
// Doesn't actually ensure that the values in the range are unique
template <class _Key, class _Tp>
class bijection : public function<_Key,_Tp>
{
public:
bijection()
{
}
~bijection()
{
}
typename bijection<_Key,_Tp>::iterator inverse_find(const _Tp& in_argument)
{
typename bijection<_Key,_Tp>::iterator a_mapping;
for (a_mapping = this->begin(); a_mapping != this->end(); a_mapping++)
{
if ((*a_mapping).second == in_argument)
return a_mapping;
}
return this->end();
}
typename bijection<_Key,_Tp>::const_iterator inverse_find(const _Tp& in_argument) const
{
typename bijection<_Key,_Tp>::const_iterator a_mapping;
for (a_mapping = this->begin(); a_mapping != this->end(); a_mapping++)
{
if ((*a_mapping).second == in_argument)
return a_mapping;
}
return this->end();
}
const _Key inverse_apply(const _Tp& in_argument) const
{
// Function applied to value outside its domain
assert(this->inverse_find(in_argument) != this->end());
typename bijection<_Key,_Tp>::const_iterator a_mapping;
for (a_mapping = this->begin(); a_mapping != this->end(); a_mapping++)
{
if ((*a_mapping).second == in_argument)
return (*a_mapping).first;
}
_Key temp;
return temp;
}
};
#endif // BIJECTION_H
| 22.125
| 89
| 0.664156
|
dba1e2f4931764e48794fc0bfbdd861488955f17
| 8,798
|
php
|
PHP
|
classes/taxonomies.php
|
igorgadelha/nesa
|
88b450f18cd0d31b455cf6cb3646379574b28413
|
[
"MIT"
] | null | null | null |
classes/taxonomies.php
|
igorgadelha/nesa
|
88b450f18cd0d31b455cf6cb3646379574b28413
|
[
"MIT"
] | null | null | null |
classes/taxonomies.php
|
igorgadelha/nesa
|
88b450f18cd0d31b455cf6cb3646379574b28413
|
[
"MIT"
] | null | null | null |
<?php
function odin_transparence_taxonomy() {
$video = new Odin_Taxonomy(
'Tipo de documento', // Nome (Singular) da nova Taxonomia.
'tipos-de-documento', // Slug do Taxonomia.
'transparencia' // Nome do tipo de conteúdo que a taxonomia irá fazer parte.
);
$video->set_labels(
array(
'menu_name' => __( 'Tipos de documento', 'odin' )
)
);
$video->set_arguments(
array(
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_tagcloud' => true,
'publicly_queryable' => true,
'show_in_nav_menus' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
)
);
}
add_action( 'init', 'odin_transparence_taxonomy', 1 );
function odin_pdf_group_taxonomy() {
$args = array(
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => false,
'show_tagcloud' => true,
);
$video = new Odin_Taxonomy(
__('Grupo de documento', 'odin'), // Nome (Singular) da nova Taxonomia.
'grupo-de-documento', // Slug do Taxonomia.
'pdf' // Nome do tipo de conteúdo que a taxonomia irá fazer parte.
);
$video->set_labels(
array(
'menu_name' => __( 'Grupos de documentos', 'odin' ),
'name' => __( 'grupo de documentos', 'odin' ),
'singular_name' => __( 'grupo de documentos', 'odin' ),
'add_new' => __( 'adicionar novo grupo de documentos', 'odin' ),
'new_item' => __( 'novo grupo de documentos', 'odin' ),
'edit_item' => __( 'editar grupo de documentos', 'odin' ),
'view_item' => __( 'Ver grupo de documentos', 'odin' ),
'all_items' => __( 'todos os grupos de documentos', 'odin' ),
'search_items' => __( 'pesquisar grupos de documentos', 'odin' ),
)
);
$video->set_arguments( $args );
}
add_action( 'init', 'odin_pdf_group_taxonomy', 1 );
function odin_partners_taxonomy() {
$args = array(
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => false,
'show_tagcloud' => true,
);
$video = new Odin_Taxonomy(
__('Grupo acionista', 'odin'), // Nome (Singular) da nova Taxonomia.
'grupos-acionistas', // Slug do Taxonomia.
'acionistas' // Nome do tipo de conteúdo que a taxonomia irá fazer parte.
);
$video->set_labels(
array(
'menu_name' => __( 'Grupos acionistas', 'odin' ),
'name' => __( 'grupo acionista', 'odin' ),
'singular_name' => __( 'grupo acionista', 'odin' ),
'add_new' => __( 'adicionar novo grupo acionista', 'odin' ),
'new_item' => __( 'novo grupo acionista', 'odin' ),
'edit_item' => __( 'editar grupo acionista', 'odin' ),
'view_item' => __( 'Ver grupo acionista', 'odin' ),
'all_items' => __( 'todos os grupos acionistas', 'odin' ),
'search_items' => __( 'pesquisar grupos acionistas', 'odin' ),
)
);
$video->set_arguments( $args );
}
add_action( 'init', 'odin_partners_taxonomy', 1 );
function odin_status_da_obra_taxonomy() {
$args = array(
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => false,
'show_tagcloud' => true,
);
$video = new Odin_Taxonomy(
'Sítio', // Nome (Singular) da nova Taxonomia.
'sitio-da-obra', // Slug do Taxonomia.
'status-da-obra' // Nome do tipo de conteúdo que a taxonomia irá fazer parte.
);
$video->set_labels(
array(
'menu_name' => __( 'Sítio', 'odin' )
)
);
$video->set_arguments( $args );
}
add_action( 'init', 'odin_status_da_obra_taxonomy', 1 );
function odin_acoes_da_obra__taxonomy() {
$args = array(
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => false,
'show_tagcloud' => true,
);
$video = new Odin_Taxonomy(
'Ação', // Nome (Singular) da nova Taxonomia.
'acoes-da-obra', // Slug do Taxonomia.
'status-da-obra' // Nome do tipo de conteúdo que a taxonomia irá fazer parte.
);
$video->set_labels(
array(
'menu_name' => __( 'Ações', 'odin' )
)
);
$video->set_arguments( $args );
}
add_action( 'init', 'odin_acoes_da_obra__taxonomy', 1 );
function odin_acoes_sociais_da_obra_taxonomy() {
$args = array(
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => false,
'show_tagcloud' => true,
);
$video = new Odin_Taxonomy(
'Local', // Nome (Singular) da nova Taxonomia.
'acoes-sociais-da-obra', // Slug do Taxonomia.
'acoes-sociais-obra' // Nome do tipo de conteúdo que a taxonomia irá fazer parte.
);
$video->set_labels(
array(
'menu_name' => __( 'Locais', 'odin' ),
'name' => __( 'local', 'odin' ),
'singular_name' => __( 'local', 'odin' ),
'add_new' => __( 'adicionar novo local', 'odin' ),
'new_item' => __( 'novo local', 'odin' ),
'edit_item' => __( 'editar local', 'odin' ),
'view_item' => __( 'Ver local', 'odin' ),
'all_items' => __( 'todos os locais', 'odin' ),
'search_items' => __( 'pesquisar locais', 'odin' ),
)
);
$video->set_arguments( $args );
}
add_action( 'init', 'odin_acoes_sociais_da_obra_taxonomy', 1 );
function odin_acoes_sociais_da_obra__taxonomy() {
$args = array(
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => false,
'show_tagcloud' => true,
);
$video = new Odin_Taxonomy(
__('ação social', 'odin'), // Nome (Singular) da nova Taxonomia.
'tag-acoes-sociais-da-obra', // Slug do Taxonomia.
'acoes-sociais-obra' // Nome do tipo de conteúdo que a taxonomia irá fazer parte.
);
$video->set_labels(
array(
'menu_name' => __( 'Ações sociais', 'odin' ),
'name' => __( 'ação social', 'odin' ),
'singular_name' => __( 'ação social', 'odin' ),
'add_new' => __( 'adicionar nova ação social', 'odin' ),
'new_item' => __( 'nova ação social', 'odin' ),
'edit_item' => __( 'editar ação social', 'odin' ),
'view_item' => __( 'Ver ação social', 'odin' ),
'all_items' => __( 'todas as ações sociais', 'odin' ),
'search_items' => __( 'pesquisar ações sociais', 'odin' ),
)
);
$video->set_arguments( $args );
}
add_action( 'init', 'odin_acoes_sociais_da_obra__taxonomy', 1 );
function odin_valores_category__taxonomy() {
$args = array(
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
$video = new Odin_Taxonomy(
__( 'categoria', 'odin' ), // Nome (Singular) da nova Taxonomia.
'valores-category', // Slug do Taxonomia.
'valores' // Nome do tipo de conteúdo que a taxonomia irá fazer parte.
);
$video->set_labels(
array(
'menu_name' => __( 'categoria', 'odin' )
)
);
$video->set_arguments( $args );
}
add_action( 'init', 'odin_valores_category__taxonomy', 1 );
| 33.838462
| 90
| 0.492953
|
15cf979a6e73964a6479c64ffd136e2b5c808560
| 974
|
gemspec
|
Ruby
|
resque-forker.gemspec
|
demandforce/resque-forker
|
f6395156265b6a6ffc2ed6c813568710f738075c
|
[
"MIT"
] | 3
|
2015-11-05T03:47:29.000Z
|
2021-01-09T18:01:20.000Z
|
resque-forker.gemspec
|
taf2/resque-forker
|
7c03db8c7453be9713918e158644da61ec04cc7e
|
[
"MIT"
] | null | null | null |
resque-forker.gemspec
|
taf2/resque-forker
|
7c03db8c7453be9713918e158644da61ec04cc7e
|
[
"MIT"
] | null | null | null |
$:.unshift File.expand_path(File.dirname(__FILE__) + "/lib")
require "resque/forker/version"
Gem::Specification.new do |spec|
spec.name = "resque-forker"
spec.version = Resque::Forker::VERSION
spec.author = "Assaf Arkin"
spec.email = "assaf@labnotes.org"
spec.homepage = "http://github.com/flowtown/resque-forker"
spec.summary = "Super awesome forking action for Resque workers"
spec.description = "Use the power of forking to run multiple Resque workers."
spec.post_install_message = ""
spec.executables = %w(resque-ctl)
spec.files = Dir["{lib,script,etc,bin}/**/*", "CHANGELOG", "MIT-LICENSE", "README.rdoc", "Rakefile", "*.gemspec"]
spec.extra_rdoc_files = "README.rdoc", "CHANGELOG"
spec.rdoc_options = "--title", "Resque Forker #{spec.version}", "--main", "README.rdoc", "--webcvs", spec.homepage
spec.required_ruby_version = '>= 1.8.7'
spec.add_dependency "resque"
end
| 42.347826
| 124
| 0.655031
|
cf2c34f5958ca895055cb6e1161e6ed4f3520f7b
| 21,599
|
php
|
PHP
|
src/Geometry/Extents/Extent1922.php
|
dvdoug/PHPCoord
|
a64be84d5f6410287bad74de423aae4c43a6f315
|
[
"MIT"
] | 81
|
2015-03-17T13:03:51.000Z
|
2021-12-10T19:59:58.000Z
|
src/Geometry/Extents/Extent1922.php
|
dvdoug/PHPCoord
|
a64be84d5f6410287bad74de423aae4c43a6f315
|
[
"MIT"
] | 29
|
2015-10-21T10:35:23.000Z
|
2022-01-29T19:21:04.000Z
|
src/Geometry/Extents/Extent1922.php
|
dvdoug/PHPCoord
|
a64be84d5f6410287bad74de423aae4c43a6f315
|
[
"MIT"
] | 13
|
2015-12-17T12:51:10.000Z
|
2022-03-16T05:43:21.000Z
|
<?php
/**
* PHPCoord.
*
* @author Doug Wright
*/
declare(strict_types=1);
namespace PHPCoord\Geometry\Extents;
/**
* Global/World - S hemisphere - 36°W to 30°W.
* @internal
*/
class Extent1922
{
public function __invoke(): array
{
return
[
[
[
[-36, -80], [-35.666666666667, -80], [-35.333333333333, -80], [-35, -80], [-34.666666666667, -80], [-34.333333333333, -80], [-34, -80], [-33.666666666667, -80], [-33.333333333333, -80], [-33, -80], [-32.666666666667, -80], [-32.333333333333, -80], [-32, -80], [-31.666666666667, -80], [-31.333333333333, -80], [-31, -80], [-30.666666666667, -80], [-30.333333333333, -80], [-30, -80], [-30, -79.833333333333], [-30, -79.666666666667], [-30, -79.5], [-30, -79.333333333333], [-30, -79.166666666667], [-30, -79], [-30, -78.833333333333], [-30, -78.666666666667], [-30, -78.5], [-30, -78.333333333333], [-30, -78.166666666667], [-30, -78], [-30, -77.833333333333], [-30, -77.666666666667], [-30, -77.5], [-30, -77.333333333333], [-30, -77.166666666667], [-30, -77], [-30, -76.833333333333], [-30, -76.666666666667], [-30, -76.5], [-30, -76.333333333333], [-30, -76.166666666667], [-30, -76], [-30, -75.833333333333], [-30, -75.666666666667], [-30, -75.5], [-30, -75.333333333333], [-30, -75.166666666667], [-30, -75], [-30, -74.833333333333], [-30, -74.666666666667], [-30, -74.5], [-30, -74.333333333333], [-30, -74.166666666667], [-30, -74], [-30, -73.833333333333], [-30, -73.666666666667], [-30, -73.5], [-30, -73.333333333333], [-30, -73.166666666667], [-30, -73], [-30, -72.833333333333], [-30, -72.666666666667], [-30, -72.5], [-30, -72.333333333333], [-30, -72.166666666667], [-30, -72], [-30, -71.833333333333], [-30, -71.666666666667], [-30, -71.5], [-30, -71.333333333333], [-30, -71.166666666667], [-30, -71], [-30, -70.833333333333], [-30, -70.666666666667], [-30, -70.5], [-30, -70.333333333333], [-30, -70.166666666667], [-30, -70], [-30, -69.833333333333], [-30, -69.666666666667], [-30, -69.5], [-30, -69.333333333333], [-30, -69.166666666667], [-30, -69], [-30, -68.833333333333], [-30, -68.666666666667], [-30, -68.5], [-30, -68.333333333333], [-30, -68.166666666667], [-30, -68], [-30, -67.833333333333], [-30, -67.666666666667], [-30, -67.5], [-30, -67.333333333333], [-30, -67.166666666667], [-30, -67], [-30, -66.833333333333], [-30, -66.666666666667], [-30, -66.5], [-30, -66.333333333333], [-30, -66.166666666667], [-30, -66], [-30, -65.833333333333], [-30, -65.666666666667], [-30, -65.5], [-30, -65.333333333333], [-30, -65.166666666667], [-30, -65], [-30, -64.833333333333], [-30, -64.666666666667], [-30, -64.5], [-30, -64.333333333333], [-30, -64.166666666667], [-30, -64], [-30, -63.833333333333], [-30, -63.666666666667], [-30, -63.5], [-30, -63.333333333334], [-30, -63.166666666667], [-30, -63], [-30, -62.833333333333], [-30, -62.666666666667], [-30, -62.5], [-30, -62.333333333333], [-30, -62.166666666667], [-30, -62], [-30, -61.833333333333], [-30, -61.666666666667], [-30, -61.5], [-30, -61.333333333333], [-30, -61.166666666667], [-30, -61], [-30, -60.833333333333], [-30, -60.666666666667], [-30, -60.5], [-30, -60.333333333333], [-30, -60.166666666667], [-30, -60], [-30, -59.833333333333], [-30, -59.666666666667], [-30, -59.5], [-30, -59.333333333333], [-30, -59.166666666667], [-30, -59], [-30, -58.833333333333], [-30, -58.666666666667], [-30, -58.5], [-30, -58.333333333333], [-30, -58.166666666667], [-30, -58], [-30, -57.833333333333], [-30, -57.666666666667], [-30, -57.5], [-30, -57.333333333333], [-30, -57.166666666667], [-30, -57], [-30, -56.833333333333], [-30, -56.666666666667], [-30, -56.5], [-30, -56.333333333333], [-30, -56.166666666667], [-30, -56], [-30, -55.833333333333], [-30, -55.666666666667], [-30, -55.5], [-30, -55.333333333333], [-30, -55.166666666667], [-30, -55], [-30, -54.833333333333], [-30, -54.666666666667], [-30, -54.5], [-30, -54.333333333333], [-30, -54.166666666667], [-30, -54], [-30, -53.833333333333], [-30, -53.666666666667], [-30, -53.5], [-30, -53.333333333333], [-30, -53.166666666667], [-30, -53], [-30, -52.833333333333], [-30, -52.666666666667], [-30, -52.5], [-30, -52.333333333333], [-30, -52.166666666667], [-30, -52], [-30, -51.833333333333], [-30, -51.666666666667], [-30, -51.5], [-30, -51.333333333333], [-30, -51.166666666667], [-30, -51], [-30, -50.833333333333], [-30, -50.666666666667], [-30, -50.5], [-30, -50.333333333333], [-30, -50.166666666667], [-30, -50], [-30, -49.833333333333], [-30, -49.666666666667], [-30, -49.5], [-30, -49.333333333333], [-30, -49.166666666667], [-30, -49], [-30, -48.833333333333], [-30, -48.666666666667], [-30, -48.5], [-30, -48.333333333333], [-30, -48.166666666667], [-30, -48], [-30, -47.833333333333], [-30, -47.666666666667], [-30, -47.5], [-30, -47.333333333333], [-30, -47.166666666667], [-30, -47], [-30, -46.833333333333], [-30, -46.666666666667], [-30, -46.5], [-30, -46.333333333333], [-30, -46.166666666667], [-30, -46], [-30, -45.833333333333], [-30, -45.666666666667], [-30, -45.5], [-30, -45.333333333333], [-30, -45.166666666667], [-30, -45], [-30, -44.833333333333], [-30, -44.666666666667], [-30, -44.5], [-30, -44.333333333333], [-30, -44.166666666667], [-30, -44], [-30, -43.833333333333], [-30, -43.666666666667], [-30, -43.5], [-30, -43.333333333333], [-30, -43.166666666667], [-30, -43], [-30, -42.833333333333], [-30, -42.666666666667], [-30, -42.5], [-30, -42.333333333333], [-30, -42.166666666667], [-30, -42], [-30, -41.833333333333], [-30, -41.666666666667], [-30, -41.5], [-30, -41.333333333333], [-30, -41.166666666667], [-30, -41], [-30, -40.833333333333], [-30, -40.666666666667], [-30, -40.5], [-30, -40.333333333333], [-30, -40.166666666667], [-30, -40], [-30, -39.833333333333], [-30, -39.666666666667], [-30, -39.5], [-30, -39.333333333333], [-30, -39.166666666667], [-30, -39], [-30, -38.833333333333], [-30, -38.666666666667], [-30, -38.5], [-30, -38.333333333333], [-30, -38.166666666667], [-30, -38], [-30, -37.833333333333], [-30, -37.666666666667], [-30, -37.5], [-30, -37.333333333333], [-30, -37.166666666667], [-30, -37], [-30, -36.833333333333], [-30, -36.666666666667], [-30, -36.5], [-30, -36.333333333333], [-30, -36.166666666667], [-30, -36], [-30, -35.833333333333], [-30, -35.666666666667], [-30, -35.5], [-30, -35.333333333333], [-30, -35.166666666667], [-30, -35], [-30, -34.833333333333], [-30, -34.666666666667], [-30, -34.5], [-30, -34.333333333333], [-30, -34.166666666667], [-30, -34], [-30, -33.833333333333], [-30, -33.666666666667], [-30, -33.5], [-30, -33.333333333333], [-30, -33.166666666667], [-30, -33], [-30, -32.833333333333], [-30, -32.666666666667], [-30, -32.5], [-30, -32.333333333333], [-30, -32.166666666667], [-30, -32], [-30, -31.833333333333], [-30, -31.666666666667], [-30, -31.5], [-30, -31.333333333333], [-30, -31.166666666667], [-30, -31], [-30, -30.833333333333], [-30, -30.666666666667], [-30, -30.5], [-30, -30.333333333333], [-30, -30.166666666667], [-30, -30], [-30, -29.833333333333], [-30, -29.666666666667], [-30, -29.5], [-30, -29.333333333333], [-30, -29.166666666667], [-30, -29], [-30, -28.833333333333], [-30, -28.666666666667], [-30, -28.5], [-30, -28.333333333333], [-30, -28.166666666667], [-30, -28], [-30, -27.833333333333], [-30, -27.666666666667], [-30, -27.5], [-30, -27.333333333333], [-30, -27.166666666667], [-30, -27], [-30, -26.833333333333], [-30, -26.666666666667], [-30, -26.5], [-30, -26.333333333333], [-30, -26.166666666667], [-30, -26], [-30, -25.833333333333], [-30, -25.666666666667], [-30, -25.5], [-30, -25.333333333333], [-30, -25.166666666667], [-30, -25], [-30, -24.833333333333], [-30, -24.666666666667], [-30, -24.5], [-30, -24.333333333333], [-30, -24.166666666667], [-30, -24], [-30, -23.833333333333], [-30, -23.666666666667], [-30, -23.5], [-30, -23.333333333333], [-30, -23.166666666667], [-30, -23], [-30, -22.833333333333], [-30, -22.666666666667], [-30, -22.5], [-30, -22.333333333333], [-30, -22.166666666667], [-30, -22], [-30, -21.833333333333], [-30, -21.666666666667], [-30, -21.5], [-30, -21.333333333333], [-30, -21.166666666667], [-30, -21], [-30, -20.833333333333], [-30, -20.666666666667], [-30, -20.5], [-30, -20.333333333333], [-30, -20.166666666667], [-30, -20], [-30, -19.833333333333], [-30, -19.666666666667], [-30, -19.5], [-30, -19.333333333333], [-30, -19.166666666667], [-30, -19], [-30, -18.833333333333], [-30, -18.666666666667], [-30, -18.5], [-30, -18.333333333333], [-30, -18.166666666667], [-30, -18], [-30, -17.833333333333], [-30, -17.666666666667], [-30, -17.5], [-30, -17.333333333333], [-30, -17.166666666667], [-30, -17], [-30, -16.833333333333], [-30, -16.666666666667], [-30, -16.5], [-30, -16.333333333333], [-30, -16.166666666667], [-30, -16], [-30, -15.833333333333], [-30, -15.666666666667], [-30, -15.5], [-30, -15.333333333333], [-30, -15.166666666667], [-30, -15], [-30, -14.833333333333], [-30, -14.666666666667], [-30, -14.5], [-30, -14.333333333333], [-30, -14.166666666667], [-30, -14], [-30, -13.833333333333], [-30, -13.666666666667], [-30, -13.5], [-30, -13.333333333333], [-30, -13.166666666667], [-30, -13], [-30, -12.833333333333], [-30, -12.666666666667], [-30, -12.5], [-30, -12.333333333333], [-30, -12.166666666667], [-30, -12], [-30, -11.833333333333], [-30, -11.666666666667], [-30, -11.5], [-30, -11.333333333333], [-30, -11.166666666667], [-30, -11], [-30, -10.833333333333], [-30, -10.666666666667], [-30, -10.5], [-30, -10.333333333333], [-30, -10.166666666667], [-30, -10], [-30, -9.8333333333333], [-30, -9.6666666666667], [-30, -9.5], [-30, -9.3333333333333], [-30, -9.1666666666667], [-30, -9], [-30, -8.8333333333333], [-30, -8.6666666666667], [-30, -8.5], [-30, -8.3333333333333], [-30, -8.1666666666667], [-30, -8], [-30, -7.8333333333333], [-30, -7.6666666666667], [-30, -7.5], [-30, -7.3333333333333], [-30, -7.1666666666667], [-30, -7], [-30, -6.8333333333333], [-30, -6.6666666666667], [-30, -6.5], [-30, -6.3333333333333], [-30, -6.1666666666667], [-30, -6], [-30, -5.8333333333333], [-30, -5.6666666666667], [-30, -5.5], [-30, -5.3333333333333], [-30, -5.1666666666667], [-30, -5], [-30, -4.8333333333333], [-30, -4.6666666666667], [-30, -4.5], [-30, -4.3333333333333], [-30, -4.1666666666667], [-30, -4], [-30, -3.8333333333333], [-30, -3.6666666666667], [-30, -3.5], [-30, -3.3333333333333], [-30, -3.1666666666667], [-30, -3], [-30, -2.8333333333333], [-30, -2.6666666666667], [-30, -2.5], [-30, -2.3333333333333], [-30, -2.1666666666667], [-30, -2], [-30, -1.8333333333333], [-30, -1.6666666666667], [-30, -1.5], [-30, -1.3333333333333], [-30, -1.1666666666667], [-30, -1], [-30, -0.83333333333334], [-30, -0.66666666666667], [-30, -0.5], [-30, -0.33333333333333], [-30, -0.16666666666666], [-30, 0], [-30.166666666667, 0], [-30.333333333333, 0], [-30.5, 0], [-30.666666666667, 0], [-30.833333333333, 0], [-31, 0], [-31.166666666667, 0], [-31.333333333333, 0], [-31.5, 0], [-31.666666666667, 0], [-31.833333333333, 0], [-32, 0], [-32.166666666667, 0], [-32.333333333333, 0], [-32.5, 0], [-32.666666666667, 0], [-32.833333333333, 0], [-33, 0], [-33.166666666667, 0], [-33.333333333333, 0], [-33.5, 0], [-33.666666666667, 0], [-33.833333333333, 0], [-34, 0], [-34.166666666667, 0], [-34.333333333333, 0], [-34.5, 0], [-34.666666666667, 0], [-34.833333333333, 0], [-35, 0], [-35.166666666667, 0], [-35.333333333333, 0], [-35.5, 0], [-35.666666666667, 0], [-35.833333333333, 0], [-36, 0], [-36, -0.16666666666669], [-36, -0.33333333333338], [-36, -0.50000000000005], [-36, -0.66666666666671], [-36, -0.83333333333336], [-36, -1], [-36, -1.1666666666667], [-36, -1.3333333333334], [-36, -1.5000000000001], [-36, -1.6666666666667], [-36, -1.8333333333333], [-36, -2], [-36, -2.1666666666667], [-36, -2.3333333333334], [-36, -2.5], [-36, -2.6666666666667], [-36, -2.8333333333333], [-36, -3], [-36, -3.1666666666667], [-36, -3.3333333333334], [-36, -3.5], [-36, -3.6666666666667], [-36, -3.8333333333333], [-36, -4], [-36, -4.1666666666667], [-36, -4.3333333333334], [-36, -4.5], [-36, -4.6666666666667], [-36, -4.8333333333333], [-36, -5], [-36, -5.1666666666667], [-36, -5.3333333333334], [-36, -5.5], [-36, -5.6666666666667], [-36, -5.8333333333333], [-36, -6], [-36, -6.1666666666667], [-36, -6.3333333333334], [-36, -6.5], [-36, -6.6666666666667], [-36, -6.8333333333333], [-36, -7], [-36, -7.1666666666667], [-36, -7.3333333333334], [-36, -7.5], [-36, -7.6666666666667], [-36, -7.8333333333333], [-36, -8], [-36, -8.1666666666667], [-36, -8.3333333333334], [-36, -8.5], [-36, -8.6666666666667], [-36, -8.8333333333333], [-36, -9], [-36, -9.1666666666667], [-36, -9.3333333333334], [-36, -9.5], [-36, -9.6666666666667], [-36, -9.8333333333333], [-36, -10], [-36, -10.166666666667], [-36, -10.333333333333], [-36, -10.5], [-36, -10.666666666667], [-36, -10.833333333333], [-36, -11], [-36, -11.166666666667], [-36, -11.333333333333], [-36, -11.5], [-36, -11.666666666667], [-36, -11.833333333333], [-36, -12], [-36, -12.166666666667], [-36, -12.333333333333], [-36, -12.5], [-36, -12.666666666667], [-36, -12.833333333333], [-36, -13], [-36, -13.166666666667], [-36, -13.333333333333], [-36, -13.5], [-36, -13.666666666667], [-36, -13.833333333333], [-36, -14], [-36, -14.166666666667], [-36, -14.333333333333], [-36, -14.5], [-36, -14.666666666667], [-36, -14.833333333333], [-36, -15], [-36, -15.166666666667], [-36, -15.333333333333], [-36, -15.5], [-36, -15.666666666667], [-36, -15.833333333333], [-36, -16], [-36, -16.166666666667], [-36, -16.333333333333], [-36, -16.5], [-36, -16.666666666667], [-36, -16.833333333333], [-36, -17], [-36, -17.166666666667], [-36, -17.333333333333], [-36, -17.5], [-36, -17.666666666667], [-36, -17.833333333333], [-36, -18], [-36, -18.166666666667], [-36, -18.333333333333], [-36, -18.5], [-36, -18.666666666667], [-36, -18.833333333333], [-36, -19], [-36, -19.166666666667], [-36, -19.333333333333], [-36, -19.5], [-36, -19.666666666667], [-36, -19.833333333333], [-36, -20], [-36, -20.166666666667], [-36, -20.333333333333], [-36, -20.5], [-36, -20.666666666667], [-36, -20.833333333333], [-36, -21], [-36, -21.166666666667], [-36, -21.333333333333], [-36, -21.5], [-36, -21.666666666667], [-36, -21.833333333333], [-36, -22], [-36, -22.166666666667], [-36, -22.333333333333], [-36, -22.5], [-36, -22.666666666667], [-36, -22.833333333333], [-36, -23], [-36, -23.166666666667], [-36, -23.333333333333], [-36, -23.5], [-36, -23.666666666667], [-36, -23.833333333333], [-36, -24], [-36, -24.166666666667], [-36, -24.333333333333], [-36, -24.5], [-36, -24.666666666667], [-36, -24.833333333333], [-36, -25], [-36, -25.166666666667], [-36, -25.333333333333], [-36, -25.5], [-36, -25.666666666667], [-36, -25.833333333333], [-36, -26], [-36, -26.166666666667], [-36, -26.333333333333], [-36, -26.5], [-36, -26.666666666667], [-36, -26.833333333333], [-36, -27], [-36, -27.166666666667], [-36, -27.333333333333], [-36, -27.5], [-36, -27.666666666667], [-36, -27.833333333333], [-36, -28], [-36, -28.166666666667], [-36, -28.333333333333], [-36, -28.5], [-36, -28.666666666667], [-36, -28.833333333333], [-36, -29], [-36, -29.166666666667], [-36, -29.333333333333], [-36, -29.5], [-36, -29.666666666667], [-36, -29.833333333333], [-36, -30], [-36, -30.166666666667], [-36, -30.333333333333], [-36, -30.5], [-36, -30.666666666667], [-36, -30.833333333333], [-36, -31], [-36, -31.166666666667], [-36, -31.333333333333], [-36, -31.5], [-36, -31.666666666667], [-36, -31.833333333333], [-36, -32], [-36, -32.166666666667], [-36, -32.333333333333], [-36, -32.5], [-36, -32.666666666667], [-36, -32.833333333333], [-36, -33], [-36, -33.166666666667], [-36, -33.333333333333], [-36, -33.5], [-36, -33.666666666667], [-36, -33.833333333333], [-36, -34], [-36, -34.166666666667], [-36, -34.333333333333], [-36, -34.5], [-36, -34.666666666667], [-36, -34.833333333333], [-36, -35], [-36, -35.166666666667], [-36, -35.333333333333], [-36, -35.5], [-36, -35.666666666667], [-36, -35.833333333333], [-36, -36], [-36, -36.166666666667], [-36, -36.333333333333], [-36, -36.5], [-36, -36.666666666667], [-36, -36.833333333333], [-36, -37], [-36, -37.166666666667], [-36, -37.333333333333], [-36, -37.5], [-36, -37.666666666667], [-36, -37.833333333333], [-36, -38], [-36, -38.166666666667], [-36, -38.333333333333], [-36, -38.5], [-36, -38.666666666667], [-36, -38.833333333333], [-36, -39], [-36, -39.166666666667], [-36, -39.333333333333], [-36, -39.5], [-36, -39.666666666667], [-36, -39.833333333333], [-36, -40], [-36, -40.166666666667], [-36, -40.333333333333], [-36, -40.5], [-36, -40.666666666667], [-36, -40.833333333333], [-36, -41], [-36, -41.166666666667], [-36, -41.333333333333], [-36, -41.5], [-36, -41.666666666667], [-36, -41.833333333333], [-36, -42], [-36, -42.166666666667], [-36, -42.333333333333], [-36, -42.5], [-36, -42.666666666667], [-36, -42.833333333333], [-36, -43], [-36, -43.166666666667], [-36, -43.333333333333], [-36, -43.5], [-36, -43.666666666667], [-36, -43.833333333333], [-36, -44], [-36, -44.166666666667], [-36, -44.333333333333], [-36, -44.5], [-36, -44.666666666667], [-36, -44.833333333333], [-36, -45], [-36, -45.166666666667], [-36, -45.333333333333], [-36, -45.5], [-36, -45.666666666667], [-36, -45.833333333333], [-36, -46], [-36, -46.166666666667], [-36, -46.333333333333], [-36, -46.5], [-36, -46.666666666667], [-36, -46.833333333333], [-36, -47], [-36, -47.166666666667], [-36, -47.333333333333], [-36, -47.5], [-36, -47.666666666667], [-36, -47.833333333333], [-36, -48], [-36, -48.166666666667], [-36, -48.333333333333], [-36, -48.5], [-36, -48.666666666667], [-36, -48.833333333333], [-36, -49], [-36, -49.166666666667], [-36, -49.333333333333], [-36, -49.5], [-36, -49.666666666667], [-36, -49.833333333333], [-36, -50], [-36, -50.166666666667], [-36, -50.333333333333], [-36, -50.5], [-36, -50.666666666667], [-36, -50.833333333333], [-36, -51], [-36, -51.166666666667], [-36, -51.333333333333], [-36, -51.5], [-36, -51.666666666667], [-36, -51.833333333333], [-36, -52], [-36, -52.166666666667], [-36, -52.333333333333], [-36, -52.5], [-36, -52.666666666667], [-36, -52.833333333333], [-36, -53], [-36, -53.166666666667], [-36, -53.333333333333], [-36, -53.5], [-36, -53.666666666667], [-36, -53.833333333333], [-36, -54], [-36, -54.166666666667], [-36, -54.333333333333], [-36, -54.5], [-36, -54.666666666667], [-36, -54.833333333333], [-36, -55], [-36, -55.166666666667], [-36, -55.333333333333], [-36, -55.5], [-36, -55.666666666667], [-36, -55.833333333333], [-36, -56], [-36, -56.166666666667], [-36, -56.333333333334], [-36, -56.5], [-36, -56.666666666667], [-36, -56.833333333333], [-36, -57], [-36, -57.166666666667], [-36, -57.333333333334], [-36, -57.5], [-36, -57.666666666667], [-36, -57.833333333333], [-36, -58], [-36, -58.166666666667], [-36, -58.333333333334], [-36, -58.5], [-36, -58.666666666667], [-36, -58.833333333333], [-36, -59], [-36, -59.166666666667], [-36, -59.333333333334], [-36, -59.5], [-36, -59.666666666667], [-36, -59.833333333333], [-36, -60], [-36, -60.166666666667], [-36, -60.333333333334], [-36, -60.5], [-36, -60.666666666667], [-36, -60.833333333333], [-36, -61], [-36, -61.166666666667], [-36, -61.333333333334], [-36, -61.5], [-36, -61.666666666667], [-36, -61.833333333333], [-36, -62], [-36, -62.166666666667], [-36, -62.333333333334], [-36, -62.5], [-36, -62.666666666667], [-36, -62.833333333333], [-36, -63], [-36, -63.166666666667], [-36, -63.333333333334], [-36, -63.5], [-36, -63.666666666667], [-36, -63.833333333333], [-36, -64], [-36, -64.166666666667], [-36, -64.333333333334], [-36, -64.5], [-36, -64.666666666667], [-36, -64.833333333333], [-36, -65], [-36, -65.166666666667], [-36, -65.333333333334], [-36, -65.5], [-36, -65.666666666667], [-36, -65.833333333333], [-36, -66], [-36, -66.166666666667], [-36, -66.333333333334], [-36, -66.5], [-36, -66.666666666667], [-36, -66.833333333333], [-36, -67], [-36, -67.166666666667], [-36, -67.333333333334], [-36, -67.5], [-36, -67.666666666667], [-36, -67.833333333333], [-36, -68], [-36, -68.166666666667], [-36, -68.333333333333], [-36, -68.5], [-36, -68.666666666667], [-36, -68.833333333333], [-36, -69], [-36, -69.166666666667], [-36, -69.333333333333], [-36, -69.5], [-36, -69.666666666667], [-36, -69.833333333333], [-36, -70], [-36, -70.166666666667], [-36, -70.333333333333], [-36, -70.5], [-36, -70.666666666667], [-36, -70.833333333333], [-36, -71], [-36, -71.166666666667], [-36, -71.333333333333], [-36, -71.5], [-36, -71.666666666667], [-36, -71.833333333333], [-36, -72], [-36, -72.166666666667], [-36, -72.333333333333], [-36, -72.5], [-36, -72.666666666667], [-36, -72.833333333333], [-36, -73], [-36, -73.166666666667], [-36, -73.333333333333], [-36, -73.5], [-36, -73.666666666667], [-36, -73.833333333333], [-36, -74], [-36, -74.166666666667], [-36, -74.333333333333], [-36, -74.5], [-36, -74.666666666667], [-36, -74.833333333333], [-36, -75], [-36, -75.166666666667], [-36, -75.333333333333], [-36, -75.5], [-36, -75.666666666667], [-36, -75.833333333333], [-36, -76], [-36, -76.166666666667], [-36, -76.333333333333], [-36, -76.5], [-36, -76.666666666667], [-36, -76.833333333333], [-36, -77], [-36, -77.166666666667], [-36, -77.333333333333], [-36, -77.5], [-36, -77.666666666667], [-36, -77.833333333333], [-36, -78], [-36, -78.166666666667], [-36, -78.333333333333], [-36, -78.5], [-36, -78.666666666667], [-36, -78.833333333333], [-36, -79], [-36, -79.166666666667], [-36, -79.333333333333], [-36, -79.5], [-36, -79.666666666667], [-36, -79.833333333333], [-36, -80],
],
],
];
}
}
| 744.793103
| 21,240
| 0.576925
|
4bac72371db0bf99458292a1f74ab2846fdae963
| 4,461
|
cc
|
C++
|
ash/first_run/first_run_helper_unittest.cc
|
iplo/Chain
|
8bc8943d66285d5258fffc41bed7c840516c4422
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231
|
2015-01-08T09:04:44.000Z
|
2021-12-30T03:03:10.000Z
|
ash/first_run/first_run_helper_unittest.cc
|
j4ckfrost/android_external_chromium_org
|
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2017-02-14T21:55:58.000Z
|
2017-02-14T21:55:58.000Z
|
ash/first_run/first_run_helper_unittest.cc
|
j4ckfrost/android_external_chromium_org
|
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268
|
2015-01-21T05:53:28.000Z
|
2022-03-25T22:09:01.000Z
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/first_run/first_run_helper.h"
#include "ash/first_run/desktop_cleaner.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ash/test/ash_test_base.h"
#include "ui/aura/test/event_generator.h"
#include "ui/events/event_handler.h"
#include "ui/views/window/dialog_delegate.h"
namespace ash {
namespace test {
namespace {
class TestModalDialogDelegate : public views::DialogDelegateView {
public:
TestModalDialogDelegate() {}
virtual ~TestModalDialogDelegate() {}
// Overridden from views::WidgetDelegate:
virtual ui::ModalType GetModalType() const OVERRIDE {
return ui::MODAL_TYPE_SYSTEM;
}
private:
DISALLOW_COPY_AND_ASSIGN(TestModalDialogDelegate);
};
class CountingEventHandler : public ui::EventHandler {
public:
// Handler resets |*mouse_events_registered_| during construction and updates
// it after each registered event.
explicit CountingEventHandler(int* mouse_events_registered)
: mouse_events_registered_(mouse_events_registered) {
*mouse_events_registered = 0;
}
virtual ~CountingEventHandler() {}
private:
// ui::EventHandler overrides.
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
++*mouse_events_registered_;
}
int* mouse_events_registered_;
DISALLOW_COPY_AND_ASSIGN(CountingEventHandler);
};
} // namespace
class FirstRunHelperTest : public AshTestBase,
public FirstRunHelper::Observer {
public:
FirstRunHelperTest() : cancelled_times_(0) {}
virtual ~FirstRunHelperTest() {}
virtual void SetUp() OVERRIDE {
AshTestBase::SetUp();
CheckContainersAreVisible();
helper_.reset(ash::Shell::GetInstance()->CreateFirstRunHelper());
helper_->AddObserver(this);
helper_->GetOverlayWidget()->Show();
}
virtual void TearDown() OVERRIDE {
EXPECT_TRUE(helper_.get());
helper_.reset();
CheckContainersAreVisible();
AshTestBase::TearDown();
}
void CheckContainersAreVisible() const {
aura::Window* root_window = Shell::GetInstance()->GetPrimaryRootWindow();
std::vector<int> containers_to_check =
internal::DesktopCleaner::GetContainersToHideForTest();
for (size_t i = 0; i < containers_to_check.size(); ++i) {
aura::Window* container =
Shell::GetContainer(root_window, containers_to_check[i]);
EXPECT_TRUE(container->IsVisible());
}
}
void CheckContainersAreHidden() const {
aura::Window* root_window = Shell::GetInstance()->GetPrimaryRootWindow();
std::vector<int> containers_to_check =
internal::DesktopCleaner::GetContainersToHideForTest();
for (size_t i = 0; i < containers_to_check.size(); ++i) {
aura::Window* container =
Shell::GetContainer(root_window, containers_to_check[i]);
EXPECT_TRUE(!container->IsVisible());
}
}
FirstRunHelper* helper() { return helper_.get(); }
int cancelled_times() const { return cancelled_times_; }
private:
// FirstRunHelper::Observer overrides.
virtual void OnCancelled() OVERRIDE {
++cancelled_times_;
}
scoped_ptr<FirstRunHelper> helper_;
int cancelled_times_;
DISALLOW_COPY_AND_ASSIGN(FirstRunHelperTest);
};
// This test creates helper, checks that containers are hidden and then
// destructs helper.
TEST_F(FirstRunHelperTest, ContainersAreHidden) {
CheckContainersAreHidden();
}
// Tests that helper correctly handles Escape key press.
TEST_F(FirstRunHelperTest, Cancel) {
GetEventGenerator().PressKey(ui::VKEY_ESCAPE, 0);
EXPECT_EQ(cancelled_times(), 1);
}
// Tests that modal window doesn't block events for overlay window.
TEST_F(FirstRunHelperTest, ModalWindowDoesNotBlock) {
views::Widget* modal_dialog = views::DialogDelegate::CreateDialogWidget(
new TestModalDialogDelegate(), CurrentContext(), NULL);
modal_dialog->Show();
// TODO(dzhioev): modal window should not steal focus from overlay window.
aura::Window* overlay_window = helper()->GetOverlayWidget()->GetNativeView();
overlay_window->Focus();
EXPECT_TRUE(overlay_window->HasFocus());
int mouse_events;
overlay_window->SetEventFilter(new CountingEventHandler(&mouse_events));
GetEventGenerator().PressLeftButton();
GetEventGenerator().ReleaseLeftButton();
EXPECT_EQ(mouse_events, 2);
}
} // namespace test
} // namespace ash
| 30.141892
| 79
| 0.732347
|
962344121a9ed5b031fd7eaf365f87843782a94c
| 189
|
rs
|
Rust
|
etk-4byte/tests/reverse.rs
|
ApeWorX/etk
|
88575d5fa6c7d185ce537a88f39a2d9d32f8d5fb
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
etk-4byte/tests/reverse.rs
|
ApeWorX/etk
|
88575d5fa6c7d185ce537a88f39a2d9d32f8d5fb
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
etk-4byte/tests/reverse.rs
|
ApeWorX/etk
|
88575d5fa6c7d185ce537a88f39a2d9d32f8d5fb
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
use etk_4byte::reverse_selector;
#[test]
fn set_custodian() {
let selectors: Vec<_> = reverse_selector(0x403f3731).collect();
assert_eq!(selectors, &["setCustodian(address)"],);
}
| 23.625
| 67
| 0.703704
|
a339e5c3b3aea6b11ce20d1c3f23d0eeec23ff74
| 3,119
|
h
|
C
|
solvers/SAGA-inl.h
|
albietz/stochs
|
3c3c4860c91ab59b2d8d5762583c722f73ab8608
|
[
"MIT"
] | 27
|
2017-03-22T15:21:59.000Z
|
2020-10-26T22:11:00.000Z
|
solvers/SAGA-inl.h
|
albietz/stochs
|
3c3c4860c91ab59b2d8d5762583c722f73ab8608
|
[
"MIT"
] | null | null | null |
solvers/SAGA-inl.h
|
albietz/stochs
|
3c3c4860c91ab59b2d8d5762583c722f73ab8608
|
[
"MIT"
] | 6
|
2017-03-26T23:56:19.000Z
|
2018-09-04T03:12:49.000Z
|
#include "Loss.h"
#include "Prox.h"
#include "Util.h"
namespace solvers {
template <typename Derived>
void SAGA::iterate(const Eigen::MatrixBase<Derived>& x, // x is a row vector
const Double y,
const size_t idx) {
const Double pred = x * w_;
Loss::computeGradient<Vector, Derived>(grad_, loss_, x, pred, y);
grad_ += lambda_ * w_;
w_ = w_ - lr_ * (grad_ - g_.row(idx).transpose() + gbar_);
gbar_ += 1.0 / n_ * (grad_ - g_.row(idx).transpose());
g_.row(idx) = grad_.transpose();
Prox::applyProx(w_, prox_, lr_ * proxWeight_);
++t_;
}
template <typename Derived>
void SparseSAGA::initFromX(const Eigen::SparseMatrixBase<Derived>& X) {
g_ = 0.0 * X;
}
inline void SparseSAGA::updateCoord(const size_t coord, const size_t t) {
const size_t dt = t - lastUpdate_[coord];
lastUpdate_[coord] = t;
ws_(coord) -= updateFactor_[dt] * lr_ * gbar_(coord) / s_;
}
inline void SparseSAGA::updateAllCoords(const size_t t) {
for (size_t i = 0; i < nfeatures(); ++i) {
updateCoord(i, t);
}
}
template <typename Derived>
void SparseSAGA::updateCoords(const Eigen::SparseMatrixBase<Derived>& x,
const size_t t) {
const auto& Xblock = x.derived();
const auto& X = Xblock.nestedExpression();
Util::iterateRowIndices(
[this, t](const size_t coord) { updateCoord(coord, t); }, X,
Xblock.startRow());
}
template <typename Derived>
void SparseSAGA::iterate(const Eigen::SparseMatrixBase<Derived>& x,
const Double y,
const size_t idx) {
if (t_ % maxDt_ == 0) {
// update everything when lags could exceed the max
updateAllCoords(t_ - 1);
} else {
// just-in-time update of ws_
updateCoords(x.derived(), t_ - 1);
}
const Double pred = s_ * static_cast<Double>(x * ws_);
gradDiff_ = -g_.row(idx); // gradient will be added below
// [hacky] retrieve original sparse matrix from the view x
// assumes that x was passed as a block of a sparse matrix
const auto& Xblock = x.derived();
const auto& X = Xblock.nestedExpression();
// get dense vector maps of non-zero values
RowVectorMap xMap = Util::denseRowMap<RowVector>(X, Xblock.startRow());
auto gMap = Util::denseRowMap<Vector>(g_, idx);
auto gDiffMap = Util::denseMap<Vector>(gradDiff_);
if (xMap.size() != gMap.size() || gDiffMap.size() != gMap.size()) {
LOG_EVERY_N(ERROR, 1000) << "size mismatch in sparse value arrays! ("
<< xMap.size() << ", " << gMap.size() << ", "
<< gDiffMap.size() << ") Did you call init?";
return;
}
grad_.resize(xMap.size());
Loss::computeGradient<Vector, RowVectorMap>(grad_, loss_, xMap, pred, y);
gDiffMap += grad_; // delta = grad - grad_old
s_ *= (1.0 - lr_ * lambda_);
ws_ -= (lr_ / s_) * gradDiff_; // sparse update
updateCoords(x, t_); // lazy dense update
gbar_ += (1.0 / n_) * gradDiff_;
gMap = grad_;
++t_;
// for numerical stability
if (s_ < 1e-9) {
LOG(INFO) << "resetting ws and s";
ws_ = s_ * ws_;
s_ = 1.0;
}
}
}
| 29.149533
| 76
| 0.611414
|
8f456a2e45897974a4e40a0aaa3fec52c19047b6
| 65
|
sh
|
Shell
|
run_dev_server.sh
|
JavierGSanchez/WorldScanner-backend
|
59a639c5f7db07489f1516a258588d744175ef5e
|
[
"MIT"
] | null | null | null |
run_dev_server.sh
|
JavierGSanchez/WorldScanner-backend
|
59a639c5f7db07489f1516a258588d744175ef5e
|
[
"MIT"
] | null | null | null |
run_dev_server.sh
|
JavierGSanchez/WorldScanner-backend
|
59a639c5f7db07489f1516a258588d744175ef5e
|
[
"MIT"
] | null | null | null |
#!/bin/bash
export FLASK_APP=main.py
flask run -p 5000 -h 0.0.0.0
| 21.666667
| 28
| 0.707692
|
cdfd8367672dc73fef0f9311cc1e6b26016db058
| 1,397
|
asm
|
Assembly
|
libsrc/fcntl/msxdos2/open.asm
|
jpoikela/z88dk
|
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
|
[
"ClArtistic"
] | 640
|
2017-01-14T23:33:45.000Z
|
2022-03-30T11:28:42.000Z
|
libsrc/fcntl/msxdos2/open.asm
|
jpoikela/z88dk
|
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
|
[
"ClArtistic"
] | 1,600
|
2017-01-15T16:12:02.000Z
|
2022-03-31T12:11:12.000Z
|
libsrc/fcntl/msxdos2/open.asm
|
jpoikela/z88dk
|
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
|
[
"ClArtistic"
] | 215
|
2017-01-17T10:43:03.000Z
|
2022-03-23T17:25:02.000Z
|
; int open(char *name,int access, mode_t mode)
;
; Flags is one of: O_RDONLY, O_WRONLY, O_RDWR
; Or'd with any of: O_CREAT, O_TRUNC, O_APPEND
;#define O_RDONLY 0
;#define O_WRONLY 1
;#define O_RDWR 2
;#define O_APPEND 256
;#define O_TRUNC 512
;#define O_CREAT 1024
SECTION code_clib
INCLUDE "target/msx/def/msxdos2.def"
PUBLIC open
PUBLIC _open
EXTERN MSXDOS
EXTERN msxdos_error
; char *name, int flags, mode_t mode)
.open
._open
push ix
ld ix,2
add ix,sp
ld e,(ix+6) ;Filename
ld d,(ix+7)
ld a,(ix+5) ;High byte flags
and 2
jr z,no_truncate
; Delete the file
ld c,_DELETE
call MSXDOS ;We don't care about the result
; And now create it
create_file:
ld e,(ix+6) ;Filename
ld d,(ix+7)
call get_mode ;Mode in c
ld a,c
ld b,@10000000 ;Create new
ld c,_CREATE
call MSXDOS
jr return
no_truncate:
; We don't want to truncate, try top open it
call get_mode ;Mode in c
ld a,c
ld c,_OPEN
call MSXDOS
and a
jr z,return
; We failed to open it, check for O_CREAT
bit 2,(ix+5)
jr nz,create_file
return:
ld (msxdos_error),a
pop ix ;Return callers
ld hl,0
ld h,b
and a
ret z
ld hl,-1
ret
get_mode:
ld a,(ix+4) ;Low byte flags
ld c,1
and a ;O_RDONLY
ret z
ld c,2
dec a ;O_WRONLY
ret z
ld c,0 ;O_RDWR
ret
| 17.910256
| 52
| 0.620616
|
1427bc053e9d041c49b050249c26d765d6a5c49f
| 1,071
|
ts
|
TypeScript
|
Ui/eTrackerWeb/app/interfaces/user.interface.ts
|
RajeevRanjanOneadvanced/eTracker
|
f1a6b7edf883302560f378491cba01e7df050001
|
[
"MIT"
] | null | null | null |
Ui/eTrackerWeb/app/interfaces/user.interface.ts
|
RajeevRanjanOneadvanced/eTracker
|
f1a6b7edf883302560f378491cba01e7df050001
|
[
"MIT"
] | null | null | null |
Ui/eTrackerWeb/app/interfaces/user.interface.ts
|
RajeevRanjanOneadvanced/eTracker
|
f1a6b7edf883302560f378491cba01e7df050001
|
[
"MIT"
] | null | null | null |
module etracker.interfaces {
export interface IMonthlyLimit {
Month: number;
Lowest: number;
Highest: number;
}
export interface IUserSetting {
IsActive: boolean;
IsAdmin: boolean;
IsEnable: boolean;
ModifiedDate: Date;
CreatedDate: Date;
}
export interface IUser {
Id: number;
FirstName: string;
LastName: string;
Email: string;
Password: string;
PhoneNumber: number;
MonthlyLimit: IMonthlyLimit;
SignUpCode: string;
Setting: IUserSetting;
}
export interface ITestuser {
Email: string;
Password: string;
}
}
// module etracker.enums {
// export enum Month {
// NotSet = 0,
// January = 1,
// February = 2,
// March = 3,
// April = 4,
// May = 5,
// June = 6,
// July = 7,
// August = 8,
// September = 9,
// October = 10,
// November = 11,
// December = 12,
// }
// }
| 20.207547
| 36
| 0.492997
|
67b9251ebb99fff64e7b3a6ebdacf91258ed45bd
| 514
|
sql
|
SQL
|
parse/src/test/resources/ddl/table/test_16.sql
|
Alvin4Jay/canal-dump
|
0bd3d8ec19c9460d7af42a050b807b9bcfd7c051
|
[
"Apache-2.0"
] | null | null | null |
parse/src/test/resources/ddl/table/test_16.sql
|
Alvin4Jay/canal-dump
|
0bd3d8ec19c9460d7af42a050b807b9bcfd7c051
|
[
"Apache-2.0"
] | null | null | null |
parse/src/test/resources/ddl/table/test_16.sql
|
Alvin4Jay/canal-dump
|
0bd3d8ec19c9460d7af42a050b807b9bcfd7c051
|
[
"Apache-2.0"
] | null | null | null |
CREATE TABLE `tb_cuyjfgcqed`
(
`col_rrdzqbksmd` set('enum_or_set_0','enum_or_set_1','enum_or_set_2') CHARACTER SET utf8mb4 DEFAULT 'enum_or_set_0',
`col_spveduzoyj` mediumint(219) zerofill NOT NULL,
`col_zghtsjnauz` datetime(3) NULL
) DEFAULT CHARSET=utf8;
RENAME
TABLE `tb_cuyjfgcqed` TO `tb_vtrbzichgg`;
RENAME
TABLE `tb_vtrbzichgg` TO `tb_tliqnbqkqf`;
RENAME
TABLE `tb_tliqnbqkqf` TO `tb_whudjjpowp`;
RENAME
TABLE `tb_whudjjpowp` TO `tb_bltssdqkjm`;
RENAME
TABLE `tb_bltssdqkjm` TO `tb_sqoczkufxp`;
| 30.235294
| 120
| 0.77821
|
5875d13bce369bda1c32ef993d2e8f9f85eee9aa
| 79
|
sql
|
SQL
|
spigot/src/main/resources/db/trade/GetSessionFromRequestId.sql
|
drhax9908/enjincraft
|
7058b77d0a00722d59a271443ee8c6595f3fd5c6
|
[
"Apache-2.0"
] | 56
|
2020-05-27T23:08:23.000Z
|
2022-03-06T07:15:34.000Z
|
spigot/src/main/resources/db/trade/GetSessionFromRequestId.sql
|
drhax9908/enjincraft
|
7058b77d0a00722d59a271443ee8c6595f3fd5c6
|
[
"Apache-2.0"
] | 29
|
2020-05-27T20:57:56.000Z
|
2022-03-28T22:30:01.000Z
|
spigot/src/main/resources/db/trade/GetSessionFromRequestId.sql
|
drhax9908/enjincraft
|
7058b77d0a00722d59a271443ee8c6595f3fd5c6
|
[
"Apache-2.0"
] | 25
|
2020-05-27T18:47:38.000Z
|
2022-01-28T20:53:24.000Z
|
SELECT * FROM TradeSessions
WHERE createRequestId = ?
OR completeRequestId = ?;
| 26.333333
| 27
| 0.78481
|
f27ee00672f409e7de4ecc685fc933f4ac69c80b
| 1,266
|
swift
|
Swift
|
Sources/App/Models/Social/Config/VKontakteConfig.swift
|
cocoaheadsru/server
|
3367dbfe3fec62056acd2a6cd604835356dc6243
|
[
"MIT"
] | 60
|
2017-10-11T19:37:09.000Z
|
2021-11-01T03:07:59.000Z
|
Sources/App/Models/Social/Config/VKontakteConfig.swift
|
cocoaheadsru/server
|
3367dbfe3fec62056acd2a6cd604835356dc6243
|
[
"MIT"
] | 20
|
2017-10-18T09:41:48.000Z
|
2018-05-22T13:21:34.000Z
|
Sources/App/Models/Social/Config/VKontakteConfig.swift
|
cocoaheadsru/server
|
3367dbfe3fec62056acd2a6cd604835356dc6243
|
[
"MIT"
] | 7
|
2017-10-24T21:19:13.000Z
|
2020-08-28T08:59:41.000Z
|
import Vapor
import Crypto
struct VkontakteConfig {
private let vk = Social.VK.self
let apiURL: String
let fields: String
let method: String
var secret: String = ""
var accessToken: String = ""
var userInfoURL: String {
return apiURL + method
}
init(_ config: Config) {
guard
let apiURL = config[vk.name, vk.apiURL]?.string,
let fields = config[vk.name, vk.fields]?.string,
let method = config[vk.name, vk.method]?.string
else {
fatalError("Can't read config from vkontakte.json")
}
self.apiURL = apiURL
self.fields = fields
self.method = method
if config.environment == .test {
guard
let secret = config[vk.name, vk.secret]?.string,
let accessToken = config[vk.name, vk.accessToken]?.string
else {
fatalError("Can't read token & secret from test vkontakte.json")
}
self.secret = secret
self.accessToken = accessToken
}
}
func getSignatureBased(on token: String, and secret: String)throws -> String {
let urlForSignature = "\(method)?\(vk.fields)=\(fields)&\(vk.version)=\(vk.versionValue)&\(vk.accessToken)=\(token + secret)"
print(urlForSignature)
return try CryptoHasher.makeMD5(from: urlForSignature)
}
}
| 26.375
| 129
| 0.650079
|
e7442f5654c99ac1dc8166195c04d7112414fa59
| 1,089
|
php
|
PHP
|
backend/views/brand/index.php
|
ql123ql/admin
|
a0a0185bbda4155ba07bea744b2c05a26aac11f9
|
[
"BSD-3-Clause"
] | null | null | null |
backend/views/brand/index.php
|
ql123ql/admin
|
a0a0185bbda4155ba07bea744b2c05a26aac11f9
|
[
"BSD-3-Clause"
] | null | null | null |
backend/views/brand/index.php
|
ql123ql/admin
|
a0a0185bbda4155ba07bea744b2c05a26aac11f9
|
[
"BSD-3-Clause"
] | null | null | null |
<?=\yii\bootstrap\Html::a("添加",["brand/add"],["class"=>"btn btn-info btn-sm"])?>
<table class="table table-bordered table-condensed">
<tr>
<th>ID</th>
<th>名称</th>
<th>简介</th>
<th>LOGO图片</th>
<th>排序</th>
<th>状态</th>
<th>操作</th>
</tr>
<?php foreach($brands as $brand): ?>
<tr>
<td><?=$brand->id ?></td>
<td><?=$brand->name?></td>
<td><?=$brand->intro?></td>
<td><?=\yii\bootstrap\Html::img( $brand->logo,["height"=>60]) ?></td>
<td><?=$brand->sort?></td>
<td><?=$brand->statustext?></td>
<td>
<?=\yii\bootstrap\Html::a('修改',['brand/edit','id'=>$brand->id],['class'=>'btn btn-sm btn-success'])?>
<?=\yii\bootstrap\Html::a('删除',['brand/del','id'=>$brand->id],['class'=>'btn btn-sm btn-success'])?>
</td>
</tr>
<?php endforeach;?>
</table>
<?php
echo \yii\widgets\LinkPager::widget(['pagination'=>$pager,'nextPageLabel'=>'下一页','prevPageLabel'=>'上一页','firstPageLabel'=>'首页']);
?>
| 37.551724
| 129
| 0.470156
|
0a871e7458c53bb258c522dc9271258465de86bf
| 534
|
cs
|
C#
|
Cryptolens.Licensing/LicenseRelated/Reseller.cs
|
Cryptolens/SKGL-Extension-for-dot-NET
|
15f1be1fad8b6daf8e2bc765528055e03262bbbc
|
[
"BSD-3-Clause"
] | 15
|
2018-08-29T12:35:50.000Z
|
2021-06-15T00:44:50.000Z
|
Cryptolens.Licensing/LicenseRelated/Reseller.cs
|
Cryptolens/cryptolens-dotnet
|
51cb7d6c614d454b7c4726fa3a969ffa587c77b9
|
[
"BSD-3-Clause"
] | 31
|
2018-07-05T12:02:34.000Z
|
2022-03-29T15:57:03.000Z
|
Cryptolens.Licensing/LicenseRelated/Reseller.cs
|
artemlos/SKGL-Extension-for-dot-NET
|
15f1be1fad8b6daf8e2bc765528055e03262bbbc
|
[
"BSD-3-Clause"
] | 10
|
2018-08-06T10:48:51.000Z
|
2021-09-07T03:22:32.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SKM.V3
{
public class Reseller
{
public int Id { get; set; }
public int InviteId { get; set; }
public int ResellerUserId { get; set; }
public DateTime Created { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
}
}
| 23.217391
| 47
| 0.593633
|
4383b1b10486a193c362c1a0d7a0341bd1e71844
| 933
|
tsx
|
TypeScript
|
packages/gamut/src/Truncate/__tests__/Truncate-test.tsx
|
yaronshahverdi/client-modules
|
91f9033f5bbb035f10eb4699d488da8efcc33ece
|
[
"MIT"
] | 11
|
2021-11-04T11:47:07.000Z
|
2022-03-16T18:39:28.000Z
|
packages/gamut/src/Truncate/__tests__/Truncate-test.tsx
|
yaronshahverdi/client-modules
|
91f9033f5bbb035f10eb4699d488da8efcc33ece
|
[
"MIT"
] | 159
|
2021-11-01T10:14:01.000Z
|
2022-03-31T20:56:56.000Z
|
packages/gamut/src/Truncate/__tests__/Truncate-test.tsx
|
yaronshahverdi/client-modules
|
91f9033f5bbb035f10eb4699d488da8efcc33ece
|
[
"MIT"
] | 5
|
2021-12-29T04:29:54.000Z
|
2022-03-16T20:22:34.000Z
|
import { mount } from 'enzyme';
import React from 'react';
import { Truncate } from '..';
describe('Truncate', () => {
it('configured truncate markup if defined', () => {
const renderedTruncate = mount(<Truncate lines={2}>Hello</Truncate>);
expect(renderedTruncate.find('TruncateMarkup')).toBeDefined();
});
it('renders a span by default if expanded', () => {
const renderedTruncate = mount(
<Truncate expanded lines={2}>
Hello
</Truncate>
);
expect(renderedTruncate.find('TruncateMarkup').length).toBe(0);
expect(renderedTruncate.find('span').length).toBe(1);
});
it('takes a callback to be called when text is truncated', () => {
const onTruncate = jest.fn();
mount(
<Truncate lines={2} onTruncate={onTruncate}>
Hello
</Truncate>
);
expect(onTruncate).toHaveBeenCalled();
expect(onTruncate).toHaveBeenCalledWith(true);
});
});
| 25.216216
| 73
| 0.632369
|
1a97d14e8eaa533ed885a8fa9678f2634faad4ab
| 1,757
|
py
|
Python
|
scripts/sdk_fetch_test_runner.py
|
PelionIoT/mbed-cloud-sdk-java
|
cc99c51db43cc9ae36601f20f20b7d8cd7515432
|
[
"Apache-2.0"
] | 7
|
2017-12-28T11:19:15.000Z
|
2020-03-23T19:15:31.000Z
|
scripts/sdk_fetch_test_runner.py
|
PelionIoT/mbed-cloud-sdk-java
|
cc99c51db43cc9ae36601f20f20b7d8cd7515432
|
[
"Apache-2.0"
] | 99
|
2018-01-09T23:56:13.000Z
|
2020-11-03T05:20:55.000Z
|
scripts/sdk_fetch_test_runner.py
|
PelionIoT/mbed-cloud-sdk-java
|
cc99c51db43cc9ae36601f20f20b7d8cd7515432
|
[
"Apache-2.0"
] | 5
|
2018-08-02T06:29:18.000Z
|
2019-10-23T11:43:59.000Z
|
#!/usr/bin/python
import sdk_common
import os
# Block in charge of fetching SDK test runner (Docker container)
class SDKTestRunnerFetcher(sdk_common.BuildStepUsingAWS):
def __init__(self, logger=None):
super(SDKTestRunnerFetcher, self).__init__('SDK test runner fetch', logger)
self.image_to_fetch = str(self.common_config.get_config().get_testrunner_docker_image())
self.fallback_image_to_fetch = str(self.common_config.get_config().get_default_testrunner_docker_image())
def pull_image(self, image, image_tag):
arguments = ["docker", "pull", image]
return_code = self.call_command(arguments, None, True)
if return_code == 0:
arguments = ["docker", "tag", image, image_tag]
self.call_command(arguments, None, True)
return return_code
def execute(self):
self.print_title()
try:
self.log_info("Logging to docker images repository")
self.login()
self.log_info("Fetching SDK test runner:")
self.log_info("[%s]" % self.image_to_fetch)
return_code = self.pull_image(self.image_to_fetch, self.image_to_fetch)
if return_code != 0:
self.log_warning("Failed fetching testrunner image [%s]" % self.image_to_fetch)
self.log_info("Fetching default image instead [%s]" % self.fallback_image_to_fetch)
return_code = self.pull_image(self.fallback_image_to_fetch, self.image_to_fetch)
if return_code != 0:
raise Exception('Error code', return_code)
except:
self.log_error('Failed to fetch SDK test runner')
return False
self.log_info("Done.")
return True
| 41.833333
| 113
| 0.648833
|
b003b7788a38fcaee48d6ac1d56248dfa3a3af03
| 3,597
|
py
|
Python
|
ThingESP.py
|
SiddheshNan/ThingESP-Python-Library
|
fb817b3bd3b267876f70821c388b2c4fe57687ac
|
[
"MIT"
] | null | null | null |
ThingESP.py
|
SiddheshNan/ThingESP-Python-Library
|
fb817b3bd3b267876f70821c388b2c4fe57687ac
|
[
"MIT"
] | null | null | null |
ThingESP.py
|
SiddheshNan/ThingESP-Python-Library
|
fb817b3bd3b267876f70821c388b2c4fe57687ac
|
[
"MIT"
] | null | null | null |
import paho.mqtt.client as mqtt
import json
from threading import Thread, Lock
import json
import requests
import cv2
thingesp_server = 'thingesp.siddhesh.me'
class Client(Thread):
def __init__(self, username, projectName, password):
Thread.__init__(self)
self.username = username
self.projectName = projectName
self.password = password
self.initalized = False
self.mqtt_client = mqtt.Client(client_id=projectName+"@"+username)
self.mqtt_client.on_connect = self.on_connect
self.mqtt_client.on_message = self.on_message
self.mqtt_client.username_pw_set(
username=projectName+"@"+username, password=password)
self.mqtt_client.connect(thingesp_server, 1893, 60)
def setCallback(self, func):
self.callback_func = func
self.initalized = True
return self
def on_connect(self, client, userdata, flags, rc):
print("Connected to thingesp with result code ", rc)
self.mqtt_client.subscribe(self.projectName + "/" + self.username)
def on_message(self, client, userdata, msg):
if self.initalized != True:
print('Please set the callback func!')
return
else:
payload = json.loads(msg.payload.decode("utf-8"))
print(payload)
if payload['action'] == 'query':
out = self.callback_func(payload['query'].lower()) or ""
sendr = {
"msg_id": payload['msg_id'], "action": "returned_api_response", "returned_api_response": out}
self.mqtt_client.publish(
self.projectName + "/" + self.username, json.dumps(sendr))
def device_call(self, to_num, msg):
out = {"action": "device_call", "to_number": to_num, "msg": msg}
self.mqtt_client.publish(
self.projectName+"/"+self.username, json.dumps(out))
def sendImage(self, img_name, to_num, msg):
url = f"https://{thingesp_server}/api/v1/user/{self.username}/project/{self.projectName}/img"
if not msg:
msg = ""
resp = requests.post(url, data={'credentials': self.password, 'to_number': to_num, "msg": msg}, files={
'img': (img_name, open(img_name, 'rb')),
})
print("Image sent! thingesp server response: " + str(resp.text))
def run(self):
self.mqtt_client.loop_forever()
class WebcamVideoStream():
def __init__(self, src=0):
self.stream = cv2.VideoCapture(src)
(self.grabbed, self.frame) = self.stream.read()
self.started = False
self.read_lock = Lock()
def start(self):
if self.started:
print("already started!!")
return None
self.started = True
self.thread = Thread(target=self.update, args=())
self.thread.start()
return self
def update(self):
while self.started:
(grabbed, frame) = self.stream.read()
self.read_lock.acquire()
self.grabbed, self.frame = grabbed, frame
self.read_lock.release()
def read(self):
self.read_lock.acquire()
frame = self.frame.copy()
self.read_lock.release()
return frame
def stop(self):
self.started = False
self.thread.join()
def saveImage(self, name="img.jpg"):
cv2.imwrite(name, self.frame)
print("{} written!".format(name))
def __exit__(self, exc_type, exc_value, traceback):
self.stream.release()
self.stop()
cv2.destroyAllWindows()
| 33.305556
| 113
| 0.604115
|
045d5239a640f562d1db24739285e7904e15ca7c
| 364
|
sql
|
SQL
|
creates/tables/create_table_wedeal_states.sql
|
platzimaster-wedeal/wescripts
|
015a01bb6812f2b1c46b9a0e60df5d7ea582c35f
|
[
"MIT"
] | null | null | null |
creates/tables/create_table_wedeal_states.sql
|
platzimaster-wedeal/wescripts
|
015a01bb6812f2b1c46b9a0e60df5d7ea582c35f
|
[
"MIT"
] | null | null | null |
creates/tables/create_table_wedeal_states.sql
|
platzimaster-wedeal/wescripts
|
015a01bb6812f2b1c46b9a0e60df5d7ea582c35f
|
[
"MIT"
] | null | null | null |
USE wedeal;
GO
IF OBJECT_ID(N'dbo.states') IS NOT NULL
BEGIN
DROP TABLE wedeal.dbo.states;
END
GO
CREATE TABLE dbo.states
(
id INT NOT NULL IDENTITY(1,1),
name VARCHAR(15) NOT NULL DEFAULT '',
id_country INT NOT NULL,
CONSTRAINT PK_STATES_ID PRIMARY KEY(id),
CONSTRAINT FK_STATES_ID_COUNTRY FOREIGN KEY(id_country) REFERENCES wedeal.dbo.countries(id),
);
GO
| 21.411765
| 93
| 0.769231
|
c980f4f477bda2dd290fc5d1d3f571eba7b97142
| 263
|
tsx
|
TypeScript
|
src/components/AboutMe/styled/SectionWrapper.tsx
|
mateki0/ModernSimple
|
962a34e208e306af9647f29ea54096bd4f8f0c48
|
[
"RSA-MD"
] | null | null | null |
src/components/AboutMe/styled/SectionWrapper.tsx
|
mateki0/ModernSimple
|
962a34e208e306af9647f29ea54096bd4f8f0c48
|
[
"RSA-MD"
] | null | null | null |
src/components/AboutMe/styled/SectionWrapper.tsx
|
mateki0/ModernSimple
|
962a34e208e306af9647f29ea54096bd4f8f0c48
|
[
"RSA-MD"
] | null | null | null |
import styled from 'styled-components';
const SectionWrapper = styled.div`
padding: 23px 0 0 0;
display: flex;
flex-direction: column;
width: 100%;
@media only screen and (min-width: 1024px) {
padding: 50px 0;
}
`;
export default SectionWrapper;
| 20.230769
| 46
| 0.695817
|
c2b8a0e78036a4ed0b48786a53a8481cded57987
| 1,030
|
c
|
C
|
code/Structured_Programming/ADT_stack.c
|
spiritsher/c_practice
|
472acff2b90f685bbf2d7102bfc5a987d9b72b2a
|
[
"MIT",
"Unlicense"
] | null | null | null |
code/Structured_Programming/ADT_stack.c
|
spiritsher/c_practice
|
472acff2b90f685bbf2d7102bfc5a987d9b72b2a
|
[
"MIT",
"Unlicense"
] | null | null | null |
code/Structured_Programming/ADT_stack.c
|
spiritsher/c_practice
|
472acff2b90f685bbf2d7102bfc5a987d9b72b2a
|
[
"MIT",
"Unlicense"
] | null | null | null |
#include <stdio.h>
#include <ctype.h>
#define MAX_LEN 1000
#define EMPTY -1
#define FULL (MAX_LEN-1)
typedef struct stack
{
char s[MAX_LEN];
int top;
} stack;
void reset(stack *stk)
{
stk->top = EMPTY;
}
void push (char c, stack *stk)
{
stk->top ++;
stk->s[stk->top] =c;
}
char pop(stack *stk)
{
return(stk->s[stk->top--]);
}
char top(const stack *stk)
{
return(stk->s[stk->top]);
}
int is_empty(stack *stk)
{
return (stk->top = EMPTY);
}
int is_full(stack *stk)
{
return (stk->top=FULL);
}
int main()
{
stack stack_of_char;
char *str = "i am otto am i";
char str_back[20];
int i=0;
reset(&stack_of_char);
printf("original is: %s\n", str);
while(str[i] != '\0')
{
printf("%c\n", str[i]);
push(str[i++], &stack_of_char);
}
i=0;
while (!is_empty(&stack_of_char)&& i<20)
{
str_back[i++]=pop(&stack_of_char);
}
printf("reverse is : %s\n", str_back);
printf("\n+++++++++++++++++++++++\n");
return 0;
}
| 15.606061
| 44
| 0.539806
|
692ad60bae765e04baebacf2ead4593f1dd679c2
| 252
|
jbuilder
|
Ruby
|
app/views/birst_process_group_collections/index.json.jbuilder
|
gnilrets/amylase
|
b9372f28b33b8fa3dc634e09a3f1e8cc30792c1c
|
[
"Apache-2.0"
] | null | null | null |
app/views/birst_process_group_collections/index.json.jbuilder
|
gnilrets/amylase
|
b9372f28b33b8fa3dc634e09a3f1e8cc30792c1c
|
[
"Apache-2.0"
] | null | null | null |
app/views/birst_process_group_collections/index.json.jbuilder
|
gnilrets/amylase
|
b9372f28b33b8fa3dc634e09a3f1e8cc30792c1c
|
[
"Apache-2.0"
] | 2
|
2016-01-22T18:36:46.000Z
|
2020-11-04T04:26:14.000Z
|
json.array!(@birst_process_group_collections) do |birst_process_group_collection|
json.extract! birst_process_group_collection, :id, :name, :description
json.url birst_process_group_collection_url(birst_process_group_collection, format: :json)
end
| 50.4
| 92
| 0.849206
|
5703a44d9ddfc5da7fd39ffe327fe8be4d3799d6
| 2,192
|
js
|
JavaScript
|
docs/.vuepress/dist/assets/js/22.89cbd53a.js
|
james-cain/My-blog
|
12f453704be0ca9b1bd96e0283eaafd5ba277681
|
[
"MIT"
] | 6
|
2019-01-18T03:30:24.000Z
|
2019-04-09T11:14:19.000Z
|
docs/.vuepress/dist/assets/js/22.89cbd53a.js
|
james-cain/My-blog
|
12f453704be0ca9b1bd96e0283eaafd5ba277681
|
[
"MIT"
] | null | null | null |
docs/.vuepress/dist/assets/js/22.89cbd53a.js
|
james-cain/My-blog
|
12f453704be0ca9b1bd96e0283eaafd5ba277681
|
[
"MIT"
] | 3
|
2019-01-11T03:38:55.000Z
|
2019-01-19T05:43:33.000Z
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[22],{173:function(t,s,a){"use strict";a.r(s);var n=a(0),e=Object(n.a)({},function(){this.$createElement;this._self._c;return this._m(0)},[function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("div",{staticClass:"content"},[a("h1",{attrs:{id:"mobile-兼容性"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#mobile-兼容性","aria-hidden":"true"}},[t._v("#")]),t._v(" mobile 兼容性")]),t._v(" "),a("h2",{attrs:{id:"ios转换时间问题"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#ios转换时间问题","aria-hidden":"true"}},[t._v("#")]),t._v(" IOS转换时间问题")]),t._v(" "),a("blockquote",[a("p",[t._v("ios年月日之间的连接符使用的是/,服务端如果返回的连接符为-时,在转换时间时,iOS是不认识的。")]),t._v(" "),a("p",[t._v("因此为了解决这个问题,需要在转换时间之前先替换时间格式")]),t._v(" "),a("p",[t._v("如下代码:")])]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),a("span",{attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),a("span",{attrs:{class:"token function"}},[t._v("getCompatibleDate")]),a("span",{attrs:{class:"token punctuation"}},[t._v("(")]),t._v("time"),a("span",{attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{attrs:{class:"token comment"}},[t._v("// 将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式")]),t._v("\n "),a("span",{attrs:{class:"token keyword"}},[t._v("return")]),t._v(" time"),a("span",{attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{attrs:{class:"token function"}},[t._v("replace")]),a("span",{attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{attrs:{class:"token regex"}},[t._v("/\\-/g")]),a("span",{attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{attrs:{class:"token string"}},[t._v("'/'")]),a("span",{attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("转换完时间后,iOS就不会有问题")])])}],!1,null,null,null);e.options.__file="Damn-hole-of-mobile-compatibility.md";s.default=e.exports}}]);
| 2,192
| 2,192
| 0.601734
|
df5b1d11103eb5a166a79f7f05c6fe954275bff2
| 2,548
|
ps1
|
PowerShell
|
PowerShellFar/Samples/Tests/Test-Panel-Tree-.ps1
|
zertyuiop/FarNet
|
e5a449adfb5ff6c43d53862a7a76415982aa7c0f
|
[
"BSD-3-Clause"
] | 100
|
2015-03-15T03:55:10.000Z
|
2022-02-26T11:46:53.000Z
|
PowerShellFar/Samples/Tests/Test-Panel-Tree-.ps1
|
zertyuiop/FarNet
|
e5a449adfb5ff6c43d53862a7a76415982aa7c0f
|
[
"BSD-3-Clause"
] | 20
|
2016-03-12T08:52:33.000Z
|
2022-01-07T07:16:53.000Z
|
PowerShellFar/Samples/Tests/Test-Panel-Tree-.ps1
|
zertyuiop/FarNet
|
e5a449adfb5ff6c43d53862a7a76415982aa7c0f
|
[
"BSD-3-Clause"
] | 17
|
2015-03-30T06:27:28.000Z
|
2021-04-08T01:52:14.000Z
|
<#
.Synopsis
Test panel mixed items on TreePanel
Author: Roman Kuzmin
.Description
Points of interest:
- root items of different types: Services, Processes, Provider items
- root items can be optionally pre-expanded: $p.AddRoot($r, $true)
- nested levels of different types: Providers\Drives\Items\..
- unlimited recursive expansion: $t.Fill = $0.Fill
- items are not expandable is .Fill is not set
- using .Data for later use of stored objects
- using .Description for extra information
- using custom handler of <Enter> event
#>
# Explorer
$explorer = New-Object PowerShellFar.TreeExplorer
# Add a root for services (not yet expanded)
$r = $explorer.RootFiles.Add()
$r.Description = 'Services and their statuses'
$r.Name = 'Services'
$r.Fill = {
param($0)
foreach($service in (Get-Service)) {
$t = $0.ChildFiles.Add()
$t.Data = $service
$t.Description = $service.Status
$t.Name = $service.ServiceName
}
}
# Add a root for processes (not yet expanded)
$r = $explorer.RootFiles.Add()
$r.Description = 'Processes and their paths'
$r.Name = 'Processes'
$r.Fill = {
param($0)
foreach($process in (Get-Process)) {
$t = $0.ChildFiles.Add()
$t.Data = $process
$t.Description = $process.Path
$t.Name = $process.ProcessName
}
}
# Add a root for Providers\Drives\Items\.. (pre-expanded)
$r = $explorer.RootFiles.Add()
$r.Description = 'Providers\Drives\Items\..'
$r.Name = 'Providers'
$r.Fill = {
param($0)
foreach($provider in (Get-PSProvider)) {
$t = $0.ChildFiles.Add()
$t.Data = $provider
$t.Description = $provider.Drives
$t.Name = $provider.Name
$t.Fill = {
param($0)
foreach($drive in $0.Data.Drives) {
$t = $0.ChildFiles.Add()
$t.Data = $drive.Name + ':\'
$t.Name = $drive.Name + ':'
$t.Fill = {
param($0)
foreach($item in (Get-ChildItem -LiteralPath $0.Data -ea 0)) {
$t = $0.ChildFiles.Add()
$t.Data = $item.PSPath
$t.Description = $item.Description
if ($item.PSChildName) {
$t.Name = $item.PSChildName
}
else {
$t.Name = $item.Name
}
if ($item.PSIsContainer) {
$t.Fill = $0.Fill
}
}
}
}
}
}
}
$r.Expand()
# New TreePanel
$panel = New-Object PowerShellFar.TreePanel $explorer
$panel.Title = 'Test-Panel-Tree-.ps1'
# On <Enter>: open a child member panel for a current object
# This is the same as [CtrlPgDn], we do it for testing only.
$panel.AsOpenFile = {
param($0, $_)
$_.File | Open-FarPanel -Title "$($_.File.Name) opened by [Enter]" -AsChild
}
# Go
$panel.Open()
| 24.737864
| 76
| 0.64325
|
2fa8817e605493be2a3c659ea58abcab7931b348
| 2,968
|
py
|
Python
|
election/forms.py
|
roipoussiere/moje
|
5f85f588c51af91b4398f50bbfd4118b44b1ee0c
|
[
"MIT"
] | 7
|
2019-01-05T11:48:18.000Z
|
2021-09-28T20:23:23.000Z
|
election/forms.py
|
roipoussiere/moje
|
5f85f588c51af91b4398f50bbfd4118b44b1ee0c
|
[
"MIT"
] | 4
|
2018-09-14T08:56:33.000Z
|
2018-09-14T09:01:06.000Z
|
election/forms.py
|
roipoussiere/moje
|
5f85f588c51af91b4398f50bbfd4118b44b1ee0c
|
[
"MIT"
] | 3
|
2018-10-10T09:03:58.000Z
|
2020-05-24T10:15:36.000Z
|
from django import forms
from django.forms.widgets import RadioSelect
from django.contrib.admin.widgets import AdminDateWidget
from django.forms.fields import DateField
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from vote.models import *
class FutureDateField(forms.DateField):
""" Validator for only date in the future """
def validate(self, value):
super().validate(value)
if value < timezone.now().date():
raise ValidationError(_("The date is not in the future"))
class GeneralStepForm(forms.Form):
def __init__(self,*args,**kwargs):
self.disabled = kwargs.pop('disabled') if 'disabled' in kwargs else False
super(GeneralStepForm,self).__init__(*args,**kwargs)
self.fields['name'].disabled = self.disabled
self.fields['note'].disabled = self.disabled
name = forms.CharField(
label=_("Election name"),
max_length=200,
widget=forms.TextInput(attrs={'class': 'form-control'}))
# start = FutureDateField(
# label="Date de début",
# widget=forms.DateInput(attrs={'class': "form-control"}),
# input_formats=['%d/%m/%Y'],
# disabled=self.disabled
# )
# end = FutureDateField(
# label="Date de fin",
# widget=forms.DateInput(attrs={'class': "form-control"}),
# input_formats=['%d/%m/%Y'],
# disabled=self.disabled
# )
note = forms.CharField(label=_("Question"),
widget=forms.Textarea(attrs={'class': "form-control"}))
class ConfigStepForm(forms.Form):
voting_system = forms.CharField(
label=_("Voting system"),
max_length=200,
widget=forms.TextInput(attrs={'class': 'form-control'})
)
class ConfirmStepForm(forms.Form):
pass
class CreateCandidateForm(forms.Form):
label = forms.CharField(label=_("Label"),
max_length=200,
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':_("Label")})
)
description = forms.CharField(
label=_("Description"),
max_length=200,
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':_("Description")})
)
class VotersListStepForm(forms.Form):
def __init__(self,*args,**kwargs):
super(VotersListStepForm,self).__init__(*args,**kwargs)
list = forms.CharField(
label=_("Voters list"),
widget=forms.Textarea(attrs={'class': 'form-control'}))
| 34.114943
| 117
| 0.555593
|
61360e2bc8e4b6d5845fb93db9123eba7c471299
| 111
|
swift
|
Swift
|
CovidMarketPlace/Account/Entity/Account.swift
|
lordkevinmo/covidmarketplace
|
4e4f3405fcd1ea4255739c263b8b12e54b1c08ec
|
[
"Apache-2.0"
] | null | null | null |
CovidMarketPlace/Account/Entity/Account.swift
|
lordkevinmo/covidmarketplace
|
4e4f3405fcd1ea4255739c263b8b12e54b1c08ec
|
[
"Apache-2.0"
] | null | null | null |
CovidMarketPlace/Account/Entity/Account.swift
|
lordkevinmo/covidmarketplace
|
4e4f3405fcd1ea4255739c263b8b12e54b1c08ec
|
[
"Apache-2.0"
] | null | null | null |
//
// Account.swift
// CovidMarketPlace
//
// Created by Moïse AGBENYA on 13/11/2020.
//
import Foundation
| 12.333333
| 43
| 0.675676
|
b5a07225ec9fa40fe7a359c2841e4f6854c64e79
| 4,295
|
swift
|
Swift
|
Pee break/ToiletsFlow/ToiletsController/ToiletsViewModel.swift
|
leobouilloux/PeeBreak
|
b8c2baa47ac1048df89e412ea44024201c637824
|
[
"MIT"
] | 1
|
2019-02-25T01:02:04.000Z
|
2019-02-25T01:02:04.000Z
|
Pee break/ToiletsFlow/ToiletsController/ToiletsViewModel.swift
|
leobouilloux/PeeBreak
|
b8c2baa47ac1048df89e412ea44024201c637824
|
[
"MIT"
] | null | null | null |
Pee break/ToiletsFlow/ToiletsController/ToiletsViewModel.swift
|
leobouilloux/PeeBreak
|
b8c2baa47ac1048df89e412ea44024201c637824
|
[
"MIT"
] | null | null | null |
//
// ToiletsViewModel.swift
// Pee break
//
// Created by Leo Marcotte on 22/02/2019.
// Copyright © 2019 Leo Marcotte. All rights reserved.
//
import CoreLocation
import MapKit
import RxCocoa
import RxSwift
final class ToiletsViewModel: ToiletsViewModelInterface {
let provider: Provider
let title = BehaviorRelay<String>(value: "Toilettes autour de vous")
var annotations: Driver<[MKPointAnnotation]> {
return privateAnnotations.asDriver(onErrorJustReturn: [])
}
let isLoading = PublishRelay<Bool>()
let output: ToiletsOutputInterface = ToiletsOutput()
let userLocation = BehaviorRelay<CLLocation?>(value: nil)
private let data = BehaviorRelay<[ToiletData]>(value: [])
let dataSource = BehaviorRelay<[ToiletsCellType]>(value: [])
private let privateAnnotations = BehaviorRelay<[MKPointAnnotation]>(value: [])
private let bag = DisposeBag()
init(with provider: Provider) {
self.provider = provider
getData()
setupRxBindings()
}
}
private extension ToiletsViewModel {
// *****************************************************************************
// - MARK: Provider
func getData() {
provider.dataProvider.getToilets().bind(to: data).disposed(by: bag)
}
func fetchToiletsData() {
isLoading.accept(true)
provider.dataProvider.updateData()
.subscribe({ [weak self] _ in
self?.isLoading.accept(false)
})
.disposed(by: bag)
}
// *****************************************************************************
// - MARK: Rx Bindings
func setupRxBindings() {
bindData()
bindUserLocation()
bindUpdateDataOutput()
}
func bindData() {
data
// swiftlint:disable:next closure_body_length
.subscribe(onNext: { [weak self] toiletsData in
let sortedToiletData = toiletsData.sorted(by: { data1, data2 -> Bool in
guard
let distance1 = data1.distance.value,
let distance2 = data2.distance.value
else { return false }
return distance1 < distance2
})
let cells = sortedToiletData.map { ToiletsCellType.toilet(value: $0) }
let annotations = sortedToiletData.map { toilet -> MKPointAnnotation in
let location = CLLocation(latitude: toilet.x, longitude: toilet.y)
let annotation = MKPointAnnotation()
if let distance = toilet.distance.value {
if Int(distance) / 1000 == 0 {
annotation.title = "\(distance)m"
annotation.title = String(format: "%.0fm", distance)
} else {
annotation.title = String(format: "%.1fkm", distance / 1000)
}
}
annotation.subtitle = toilet.hours
annotation.coordinate = location.coordinate
return annotation
}
self?.dataSource.accept(cells)
self?.privateAnnotations.accept(annotations)
})
.disposed(by: bag)
}
func bindUserLocation() {
userLocation
.skip(1)
.throttle(5, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] userLocation in
guard
let userLocation = userLocation,
let data = self?.data
else { return }
let newData = data.value.map { toiletData -> ToiletData in
let location = CLLocation(latitude: toiletData.x, longitude: toiletData.y)
toiletData.distance.value = Float(location.distance(from: userLocation))
return toiletData
}
data.accept(newData)
})
.disposed(by: bag)
}
func bindUpdateDataOutput() {
output.updateDataAction
.subscribe(onNext: { [weak self] in
self?.fetchToiletsData()
})
.disposed(by: bag)
}
}
| 34.36
| 94
| 0.53085
|
31992705984890934b73098b47ccc43b8d859d41
| 2,551
|
go
|
Go
|
routingtable/client_manager_test.go
|
mraerino/bio-rd
|
8f8c1730ab3271770747cdba023761c950b48268
|
[
"Apache-2.0"
] | null | null | null |
routingtable/client_manager_test.go
|
mraerino/bio-rd
|
8f8c1730ab3271770747cdba023761c950b48268
|
[
"Apache-2.0"
] | null | null | null |
routingtable/client_manager_test.go
|
mraerino/bio-rd
|
8f8c1730ab3271770747cdba023761c950b48268
|
[
"Apache-2.0"
] | null | null | null |
package routingtable
import (
"testing"
"github.com/bio-routing/bio-rd/net"
"github.com/bio-routing/bio-rd/route"
"github.com/bio-routing/bio-rd/routingtable/filter"
"github.com/stretchr/testify/assert"
)
type MockClient struct {
foo int
}
func (m MockClient) ClientCount() uint64 {
return 0
}
func (m MockClient) Dump() []*route.Route {
return nil
}
func (m MockClient) AddPath(net.Prefix, *route.Path) error {
return nil
}
func (m MockClient) RemovePath(net.Prefix, *route.Path) bool {
return false
}
func (m MockClient) UpdateNewClient(RouteTableClient) error {
return nil
}
func (m MockClient) Register(RouteTableClient) {
return
}
func (m MockClient) Unregister(RouteTableClient) {
return
}
func (m MockClient) RouteCount() int64 {
return 0
}
func (m MockClient) ReplaceFilterChain(c filter.Chain) {
}
func (m MockClient) ReplacePath(net.Prefix, *route.Path, *route.Path) {
}
func (m MockClient) RefreshRoute(net.Prefix, []*route.Path) {
}
func TestClients(t *testing.T) {
tests := []struct {
name string
clients []MockClient
expected []RouteTableClient
}{
{
name: "No clients",
clients: []MockClient{},
expected: []RouteTableClient{},
},
{
name: "No clients",
clients: []MockClient{
{
foo: 1,
},
{
foo: 2,
},
},
expected: []RouteTableClient{
MockClient{
foo: 1,
},
MockClient{
foo: 2,
},
},
},
}
for _, test := range tests {
cm := NewClientManager(MockClient{})
for _, client := range test.clients {
cm.RegisterWithOptions(client, ClientOptions{})
}
ret := cm.Clients()
for _, exp := range test.expected {
found := false
for _, client := range ret {
if exp == client {
found = true
continue
}
}
if !found {
t.Errorf("Test %q failed: Client %v not found in result: %v", test.name, exp, ret)
}
}
}
}
func TestGetMaxPaths(t *testing.T) {
tests := []struct {
name string
clientOptions ClientOptions
ecmpPaths uint
expected uint
}{
{
name: "Test #1",
clientOptions: ClientOptions{
BestOnly: true,
},
ecmpPaths: 8,
expected: 1,
},
{
name: "Test #2",
clientOptions: ClientOptions{
EcmpOnly: true,
},
ecmpPaths: 8,
expected: 8,
},
{
name: "Test #3",
clientOptions: ClientOptions{
MaxPaths: 100,
},
ecmpPaths: 10,
expected: 100,
},
}
for _, test := range tests {
res := test.clientOptions.GetMaxPaths(test.ecmpPaths)
assert.Equal(t, test.expected, res)
}
}
| 17.120805
| 86
| 0.624461
|
06835bc5ea7fe10bf1804a360d5db4a8cb2a38e6
| 47
|
sh
|
Shell
|
dissertation/count.sh
|
Dgleish/PartIIProj
|
617080e3b2fffd73b07de4fa59aca7ffb2389bac
|
[
"MIT"
] | null | null | null |
dissertation/count.sh
|
Dgleish/PartIIProj
|
617080e3b2fffd73b07de4fa59aca7ffb2389bac
|
[
"MIT"
] | null | null | null |
dissertation/count.sh
|
Dgleish/PartIIProj
|
617080e3b2fffd73b07de4fa59aca7ffb2389bac
|
[
"MIT"
] | null | null | null |
#!/bin/sh
texcount -total -template={sum} "$@"
| 15.666667
| 36
| 0.617021
|
e83157dd9e9f145b28affad9857c8eb26994acf3
| 532
|
cs
|
C#
|
CulverinEditor/CulverinEditor/UI_Scripts/Scene/ContinueButton.cs
|
elliotjb/CulverinEngine-Project3
|
cc386713dd786e2a52cc9b219a0d701a9398f202
|
[
"MIT"
] | 2
|
2018-01-20T18:17:22.000Z
|
2018-01-20T18:17:28.000Z
|
CulverinEditor/CulverinEditor/UI_Scripts/Scene/ContinueButton.cs
|
TempName0/TempMotor3D_P3
|
cc386713dd786e2a52cc9b219a0d701a9398f202
|
[
"MIT"
] | null | null | null |
CulverinEditor/CulverinEditor/UI_Scripts/Scene/ContinueButton.cs
|
TempName0/TempMotor3D_P3
|
cc386713dd786e2a52cc9b219a0d701a9398f202
|
[
"MIT"
] | 1
|
2018-06-16T16:12:11.000Z
|
2018-06-16T16:12:11.000Z
|
using CulverinEditor;
using CulverinEditor.SceneManagement;
using CulverinEditor.Debug;
public class ContinueButton : CulverinBehaviour
{
public bool reset = false;
private float volume = 0.0f;
void Start()
{
volume = Audio.GetVolume();
Audio.ChangeVolume(20);
}
public void Play()
{
if (reset)
StatsScore.ResetScore();
Audio.ChangeVolume(volume);
Input.SetInputManagerActive("GUI", false);
SceneManager.RemoveNoDestroy();
}
}
| 20.461538
| 50
| 0.62594
|
7f7163a4067f0fc615286f35ddec6e7712d6d0c6
| 2,453
|
php
|
PHP
|
single-work-ajax.php
|
nhumphrey2/WordPressCustom
|
dc81471236a677bfb1fb22129ab92dd4b31bf7b4
|
[
"MIT"
] | null | null | null |
single-work-ajax.php
|
nhumphrey2/WordPressCustom
|
dc81471236a677bfb1fb22129ab92dd4b31bf7b4
|
[
"MIT"
] | null | null | null |
single-work-ajax.php
|
nhumphrey2/WordPressCustom
|
dc81471236a677bfb1fb22129ab92dd4b31bf7b4
|
[
"MIT"
] | null | null | null |
<?php
/**
* The Template for displaying work items when displayed in lightbox.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
global $apollo13framework_a13;
the_post();
if(post_password_required()){
echo '<p>'.esc_html_e( 'To view it please enter your password below', 'rife-free' ).'</p>';
echo apollo13framework_password_form();//escaped on creation
}
else{
//main title
echo '<h1 class="page-title">'.esc_html(get_the_title()).'</h1>';
//subtitle
$subtitle = $apollo13framework_a13->get_meta('_subtitle');
if(strlen($subtitle)){
echo '<h2 class="subtitle">'.esc_html($subtitle).'</h2>';
}
// Disable default placement of addtoany widget but only in works
remove_filter( 'the_content', 'A2A_SHARE_SAVE_add_to_content', 98 );
$theme = 'slider';//for ajax loading we move images to slider always
$_id = get_the_ID();
$show_desc = get_post_meta( $_id, '_enable_desc', true);
$is_text_content = strlen( $post->post_content ) > 0;
$title_color = get_post_meta( $_id, '_slide_title_bg_color', true );
$title_color = ( $title_color === '' || $title_color === false || $title_color === 'transparent' ) ? '' : $title_color;
$thumbs = $apollo13framework_a13->get_meta( '_thumbs' );
$thumbs_on_load = $apollo13framework_a13->get_meta( '_thumbs_on_load' );
$ken_scale = $apollo13framework_a13->get_meta( '_ken_scale' );
$slider_opts = array(
'autoplay ' => $apollo13framework_a13->get_meta( '_autoplay' ),
'transition' => $apollo13framework_a13->get_meta( '_transition' ),
'fit_variant' => $apollo13framework_a13->get_meta( '_fit_variant' ),
'pattern' => $apollo13framework_a13->get_meta( '_pattern' ),
'gradient' => $apollo13framework_a13->get_meta( '_gradient' ),
'ken_burns_scale' => strlen($ken_scale) ? $ken_scale : 120,
'texts' => $show_desc,
'title_color' => $title_color,
'transition_time' => $apollo13framework_a13->get_option( 'work_slider_transition_time' ),
'slide_interval' => $apollo13framework_a13->get_option( 'work_slider_slide_interval' ),
'thumbs' => $thumbs,
'thumbs_on_load' => $thumbs_on_load,
'socials' => 'off'
);
apollo13framework_make_slider($slider_opts);
apollo13framework_single_work_text_content($is_text_content);
apollo13framework_similar_works();
}
| 39.564516
| 123
| 0.656747
|
b417d43ac4258e310b63e372901bd66f7586f846
| 2,239
|
lua
|
Lua
|
TestSocket.lua
|
stuta/Luajit-Tcp-Server
|
d89228c170debca554c3bc71b200b1e62ccdeb9e
|
[
"BSD-3-Clause"
] | 24
|
2015-01-15T16:28:33.000Z
|
2020-07-16T03:38:37.000Z
|
TestSocket.lua
|
stuta/Luajit-Tcp-Server
|
d89228c170debca554c3bc71b200b1e62ccdeb9e
|
[
"BSD-3-Clause"
] | null | null | null |
TestSocket.lua
|
stuta/Luajit-Tcp-Server
|
d89228c170debca554c3bc71b200b1e62ccdeb9e
|
[
"BSD-3-Clause"
] | 9
|
2017-03-08T18:22:42.000Z
|
2022-01-18T15:16:56.000Z
|
-- TestSocket.lua
print()
print(" -- TestSocket.lua start -- ")
print()
local arg = {...}
local util = require "lib_util"
local tcp = require "lib_tcp"
local socket = require "lib_socket"
local ffi = require("ffi")
local C = ffi.C
local port = 5001
local buflen = 16384
local recvbuflen = buflen
local recvbuf,recvbuf_ptr = util.createBuffer(buflen)
print("..Lua tcp server waiting on: 127.0.0.1:"..port)
print()
-- http://beej.us/guide/bgnet/output/html/multipage/syscalls.html#bind
local ListenSocket = tcp.listen(port)
-- Accept a client socketlocal
print("Waiting for client to connect to server socket number: " .. ListenSocket)
print("Point your brorser to 127.0.0.1:"..port.." and do refresh 3 times (or more).")
local ClientSocket,client_addr_ptr = tcp.accept(ListenSocket)
print("client ip:port = "..tcp.address(ClientSocket)) -- servInfo is post number
print()
-- Receive until the peer shuts down the connection
local totalBytesReceived = 0
local totalBytesSent = 0
local receiveFlags = 0
local sendFlags = 0
repeat
result = socket.recv(ClientSocket, recvbuf_ptr, recvbuflen, receiveFlags)
if result > 0 then
totalBytesReceived = totalBytesReceived + result
print(" *** Bytes received: ", result.." / "..totalBytesReceived.." total")
print(" *** Data received: \n\n", ffi.string(recvbuf_ptr))
print()
print()
-- Echo the buffer back to the sender
local send_result = socket.send(ClientSocket, recvbuf_ptr, result, sendFlags)
if send_result < 0 then
socket.cleanup(ClientSocket, send_result, "socket.send failed with error: ")
end
totalBytesSent = totalBytesSent + tonumber(send_result)
print(" *** Bytes sent: ", send_result.." / "..totalBytesSent.." total")
elseif result == 0 then
print(" *** Connection closing...")
else
socket.cleanup(ClientSocket, result, "socket.recv failed with error: ")
end
until result <= 0
tcp.close(ClientSocket)
tcp.close(ListenSocket)
-- shutdown the connection since we're done
result = socket.shutdown(ClientSocket, C.SD_SEND)
if result < 0 and result ~= -1 then
socket.cleanup(ClientSocket, result, "shutdown failed with error: ")
end
-- cleanup
socket.close(ClientSocket)
socket.cleanup()
print()
print(" -- TestSocket.lua end -- ")
print()
| 28.705128
| 85
| 0.723537
|
8b3ecc1f05713e608c92002e657ee8dd9f5080b6
| 638
|
rb
|
Ruby
|
app/workers/propagate_integration_inherit_descendant_worker.rb
|
Testiduk/gitlabhq
|
2d4f258f067f55894862e47ec32bbc54649d4741
|
[
"MIT"
] | 11,467
|
2015-01-01T02:37:54.000Z
|
2022-03-31T03:33:20.000Z
|
app/workers/propagate_integration_inherit_descendant_worker.rb
|
Testiduk/gitlabhq
|
2d4f258f067f55894862e47ec32bbc54649d4741
|
[
"MIT"
] | 2,862
|
2015-01-01T02:39:54.000Z
|
2022-01-03T16:58:41.000Z
|
app/workers/propagate_integration_inherit_descendant_worker.rb
|
Acidburn0zzz/gitlabhq
|
74015980b5259072bbf27b432b9b08fda9d27945
|
[
"MIT"
] | 4,353
|
2015-01-01T09:03:52.000Z
|
2022-03-31T08:09:05.000Z
|
# frozen_string_literal: true
class PropagateIntegrationInheritDescendantWorker
include ApplicationWorker
data_consistency :always
sidekiq_options retry: 3
feature_category :integrations
urgency :low
idempotent!
# rubocop: disable CodeReuse/ActiveRecord
def perform(integration_id, min_id, max_id)
integration = Integration.find_by_id(integration_id)
return unless integration
batch = Integration.inherited_descendants_from_self_or_ancestors_from(integration).where(id: min_id..max_id)
BulkUpdateIntegrationService.new(integration, batch).execute
end
# rubocop: enable CodeReuse/ActiveRecord
end
| 26.583333
| 112
| 0.810345
|
0293c79515c6e790fa16a5b36e679a3f3aa0b703
| 7,435
|
sql
|
SQL
|
sql/_27_banana_qa/issue_11089_percentile_disc/_02_analytic_function/cases/p_disc_expression.sql
|
Zhaojia2019/cubrid-testcases
|
475a828e4d7cf74aaf2611fcf791a6028ddd107d
|
[
"BSD-3-Clause"
] | 9
|
2016-03-24T09:51:52.000Z
|
2022-03-23T10:49:47.000Z
|
sql/_27_banana_qa/issue_11089_percentile_disc/_02_analytic_function/cases/p_disc_expression.sql
|
Zhaojia2019/cubrid-testcases
|
475a828e4d7cf74aaf2611fcf791a6028ddd107d
|
[
"BSD-3-Clause"
] | 173
|
2016-04-13T01:16:54.000Z
|
2022-03-16T07:50:58.000Z
|
sql/_27_banana_qa/issue_11089_percentile_disc/_02_analytic_function/cases/p_disc_expression.sql
|
Zhaojia2019/cubrid-testcases
|
475a828e4d7cf74aaf2611fcf791a6028ddd107d
|
[
"BSD-3-Clause"
] | 38
|
2016-03-24T17:10:31.000Z
|
2021-10-30T22:55:45.000Z
|
--using single/multiple expressions in partition by and order by clause
drop table if exists p_disc_expression;
create table p_disc_expression(
col1 int auto_increment primary key,
col2 smallint,
col3 char(30) default 'abc',
col4 date default SYSDATE,
col5 clob
);
insert into p_disc_expression(col2, col3, col4, col5) values(500, 'cubrid', '1990-10-10', 'aello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(500, 'cubrid', '1990-11-10', 'bello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(500, 'mysql', '1990-10-11', 'cello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(500, 'cubrid', '1990-10-10', 'dello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(500, 'cubrid', '1991-10-10', 'eello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(501, 'oracle', '1990-10-10', 'fello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(501, 'cubrid', '1992-10-10', 'gello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(501, 'oracle', '1990-11-10', 'hello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(501, 'mysql', '1990-10-10', 'iello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(501, 'cubrid', '1990-10-10', 'jello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(501, 'mysql', '1991-11-10', 'kello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(502, 'cubrid', '1990-10-10', 'lello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(502, 'mysql', '1990-10-10', 'mello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(502, 'mysql', '1992-10-10', 'nello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(503, 'mysql', '1992-10-10', 'oello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(503, 'cubrid', '1990-10-10', 'pello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(503, 'cubrid', '1990-10-10', 'qello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(503, 'oracle', '1993-11-10', 'rello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(503, 'oracle', '1993-10-10', 'sello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(503, 'cubrid', '1993-11-10', 'tello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(503, 'cubrid', '1992-10-10', 'uello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(504, 'mysql', '1994-10-10', 'vello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(504, 'mysql', '1990-10-10', null);
insert into p_disc_expression(col2, col3, col4, col5) values(504, 'cubrid', '1995-11-10', 'wello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(505, 'cubrid', '1991-10-10', '');
insert into p_disc_expression(col2, col3, col4, col5) values(505, 'cubrid', '1996-10-10', 'xello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(505, 'mysql', '1990-10-10', 'yello@domainname.com');
insert into p_disc_expression(col2, col3, col4, col5) values(505, 'cubrid', '1995-10-10', null);
insert into p_disc_expression(col2, col3, col4, col5) values(505, 'cubrid', '1990-10-10', 'zello@domainname.com');
--TEST: using single expression in partition by clause
select col1, percentile_disc(0.1) within group (order by col1) over(partition by 100) p_disc from p_disc_expression;
select col1, percentile_disc(0.9) within group (order by col1) over(partition by 2) p_disc from p_disc_expression;
select col2, percentile_disc(0.2) within group (order by col2) over(partition by -3) p_disc from p_disc_expression order by 1, 2;
select col4, percentile_disc(1) within group (order by col4) over(partition by null) p_disc from p_disc_expression order by 1, 2;
select col2, percentile_disc(0) within group (order by col4 desc) over(partition by 'a') p_disc from p_disc_expression order by 1, 2;
select col1, col2, col1+col2, percentile_disc(0.3) within group (order by col1) over(partition by col1+col2) p_disc from p_disc_expression order by 1, 2, 3, 4;
select col1, col2, left(col3, 3), percentile_disc(0.6) within group (order by col2) over(partition by left(col3, 3)) p_disc, col3 from p_disc_expression order by 1, 2, 3, 4;
select adddate(col4, 12), percentile_disc(0.8) within group (order by col1) over(partition by adddate(col4, 12)) p_disc, col4 from p_disc_expression order by 1, 2, 3;
select col1, incr(col2), percentile_disc(0.8) within group (order by col1) over(partition by incr(col2)) p_disc, col4 from p_disc_expression order by 1, 2, 3, 4;
--TEST: using multiple expressions in partition by clause
select col3, col2, percentile_disc(0.1) within group (order by col1) over(partition by col3, col2) p_disc from p_disc_expression order by 1, 2, 3;
select col4, col1, col2, clob_to_char(col5), percentile_disc(0.3) within group (order by col2) over(partition by col4, clob_to_char(col5)) p_disc from p_disc_expression order by 1, 2, 3, 4, 5;
select col3, col4, percentile_disc(0.7) within group (order by col1) over(partition by col3, col4) p_disc from p_disc_expression order by 1, 2, 3;
select col3, col4, percentile_disc(0.9) within group (order by col2) over(partition by SYSDATE, round(col1, 0)) p_disc from p_disc_expression order by 1, 2, 3;
select col2, col1-col2, col2-col1, percentile_disc(0.87) within group (order by col2) over(partition by col1-col2, col2-col1) p_disc, col1 from p_disc_expression order by 1, 2, 3, 4;
--TEST: using expressions in the first param
select col1, percentile_disc(-1) within group (order by col1) over(partition by col3) from p_disc_expression order by 1, 2;
select col1, percentile_disc(1000) within group (order by col1) over(partition by col3) from p_disc_expression order by 1, 2;
select col1, percentile_disc(null) within group (order by col1) over(partition by col3) from p_disc_expression order by 1, 2;
select col1, percentile_disc('a') within group (order by col1) over(partition by col3) from p_disc_expression order by 1, 2;
select col1, percentile_disc(abs(col1)) within group (order by col2 desc) over(partition by col3) from p_disc_expression order by 1, 2;
select col1, percentile_disc(decr(col2)) within group (order by col1) over(partition by col3) from p_disc_expression order by 1, 2;
--TEST: using expressions in the second param
select col1, col1*col2, percentile_disc(0.1) within group (order by col1*col2) over(partition by col4) p_disc from p_disc_expression order by 1, 2;
select col2, round((col2/col1+col1), 0) aaa, percentile_disc(0.34) within group (order by round((col2/col1+col1), 0)) over(partition by clob_to_char(col5)) p_disc from p_disc_expression order by 1, 2;
select col2, col4, last_day(col4), percentile_disc(0.5) within group (order by last_day(col4) desc) over(partition by col2) p_disc, col3 from p_disc_expression order by 1, 2, 3, 4, 5;
select col1, col2, clob_to_char(col5), percentile_disc(0.7) within group (order by char_length(clob_to_char(col5))) over(partition by col4) p_disc from p_disc_expression order by 1, 2, 3, 4;
delete from p_disc_expression;
drop table p_disc_expression;
| 86.453488
| 200
| 0.752925
|
7563bccb80c7693ce04efe2725cf74677b58ab98
| 800
|
css
|
CSS
|
style.css
|
jettairlines/messenger-moods
|
95bce404a149faebe98d01f8ec3ad2bd523da130
|
[
"WTFPL"
] | null | null | null |
style.css
|
jettairlines/messenger-moods
|
95bce404a149faebe98d01f8ec3ad2bd523da130
|
[
"WTFPL"
] | null | null | null |
style.css
|
jettairlines/messenger-moods
|
95bce404a149faebe98d01f8ec3ad2bd523da130
|
[
"WTFPL"
] | null | null | null |
@import url(https://fonts.googleapis.com/css?family=Oxygen:400,700);
#title {
padding: 10%,0,10%;
font-family: 'Oxygen', sans-serif;
font-weight: 400;
text-align: center;
color: #5B2E48; }
#title h1 {
font-weight: 700;
font-size: 3em;
margin-bottom: 5px; }
#title h4 {
display: flex;
justify-content: space-around; }
#title h4 div {
display: inline-block;
display: flex;
align-items: center; }
#canvas {
max-height: 100vh;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
flex-direction: row; }
.date {
height: 20px;
width: 20px;
background-color: #585563; }
.pos {
background-color: #5DA399; }
.neg {
background-color: #FF686B; }
.comp {
background-color: #CEB992; }
/*# sourceMappingURL=style.css.map */
| 19.047619
| 68
| 0.6275
|
14520be6a2c9c484c745a7867120d98d5b14c518
| 19,334
|
ts
|
TypeScript
|
src/migration/Migration.ts
|
oceanprotocol/v4-migration-lib
|
4a77cdf61b2e2bc22962cd58648ac929424acdba
|
[
"Apache-2.0"
] | 1
|
2022-01-06T10:47:02.000Z
|
2022-01-06T10:47:02.000Z
|
src/migration/Migration.ts
|
oceanprotocol/v4-migration-lib
|
4a77cdf61b2e2bc22962cd58648ac929424acdba
|
[
"Apache-2.0"
] | 6
|
2022-01-03T12:51:44.000Z
|
2022-01-06T10:46:44.000Z
|
src/migration/Migration.ts
|
oceanprotocol/v4-migration-lib
|
4a77cdf61b2e2bc22962cd58648ac929424acdba
|
[
"Apache-2.0"
] | null | null | null |
import Web3 from 'web3'
import { TransactionReceipt } from 'web3-eth'
import { AbiItem } from 'web3-utils'
import ERC721Factory from '../artifacts/ERC721Factory.json'
import ERC721Template from '../artifacts/ERC721Template.json'
import { getFairGasPrice } from '../utils'
import { getAndConvertDDO } from '../DDO/convertDDO'
import { getDDO } from '../DDO/importDDO'
import V4ProviderInstance from '../provider/Provider'
import sha256 from 'crypto-js/sha256'
import { SHA256 } from 'crypto-js'
import { Ocean as V3Ocean } from '../v3/ocean/Ocean'
import { ConfigHelper } from '../v3/utils/ConfigHelper'
import { Account } from '../v3'
import axios, { AxiosResponse } from 'axios'
import { DDO as v4DDO } from '../@types'
export interface MetadataProof {
validatorAddress?: string
r?: string
s?: string
v?: number
}
export interface DispenserData {
dispenserAddress: string
maxTokens: string
maxBalance: string
withMint: boolean
allowedSwapper: string
}
export class Migration {
public GASLIMIT_DEFAULT = 1000000
public web3: Web3
public startBlock: number
constructor(web3: Web3, startBlock?: number) {
this.web3 = web3
this.startBlock = startBlock || 0
}
public async generateDidv4(erc721Address: string): Promise<string> {
const chainId = 1 // await this.web3.eth.getChainId()
const checksum = SHA256(erc721Address + chainId.toString(10))
return `did:op:${checksum.toString()}`
}
public async getHash(message: string): Promise<string> {
let hex = ''
for (let i = 0; i < message.length; i++) {
hex += '' + message.charCodeAt(i).toString(16)
}
const hexMessage = '0x' + hex
return hexMessage as string
}
public async validateAssetAquariusV4(
asset: v4DDO,
v4MetadataCacheUri?: string
): Promise<{ validation: MetadataProof; response: any }> {
const metadataCacheUri =
v4MetadataCacheUri || 'https://v4.aquarius.oceanprotocol.com'
const data = JSON.stringify(asset)
const response: AxiosResponse<any> = await axios.post(
`${metadataCacheUri}/api/aquarius/assets/ddo/validate`,
data,
{ headers: { 'Content-Type': 'application/octet-stream' } }
)
if (!response || response.status !== 200 || !response.data)
return { response: null, validation: {} }
const { publicKey: validatorAddress, r, s, v } = response.data
return {
response: response.data,
validation: {
validatorAddress,
r: r[0],
s: s[0],
v: v
}
}
}
public async getAssetURL(
account: Account,
did: string,
network: string | number,
infuraProjectId?: string
): Promise<string> {
let urlResponse: string
// Workaround for testing
if (network === 'v4-testing') return 'http://oceanprotocol.com/test'
try {
const config = new ConfigHelper().getConfig(network, infuraProjectId)
config.web3Provider = this.web3
const ocean = await V3Ocean.getInstance(config)
urlResponse = await ocean.provider.getAssetURL(account, did, 1)
} catch (error) {
console.log('error', error)
}
return urlResponse
}
public async getEncryptedFiles(
v4ProviderUrl: string,
account: Account,
did: string,
network: string | number
): Promise<string> {
const assetURL = await this.getAssetURL(account, did, network)
const file = [
{
type: 'url',
url: assetURL,
method: 'GET'
}
]
try {
const response = await V4ProviderInstance.encrypt(file, v4ProviderUrl)
return response
} catch (error) {
console.error('Error parsing json: ' + error.message)
}
}
public async estGasPublishFixedRateAsset(
did: string,
description: string,
ERC721FactoryAddress: string,
nftName: string,
nftSymbol: string,
ownerAddress: string,
cap: number,
rate: string,
marketFee: number,
publishingMarketFeeAddress: string,
publishingMarketTokenAddress: string,
fixedRateExchangeAddress: string,
baseTokenAddress: string,
templateIndex: number,
dtName: string,
dtSymbol: string
): Promise<number> {
const ERC721FactoryContract = new this.web3.eth.Contract(
ERC721Factory.abi as AbiItem[],
ERC721FactoryAddress
)
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
const encodedMetadata = Buffer.from(
JSON.stringify({
name: nftName,
symbol: nftSymbol,
description: description
})
).toString('base64')
try {
estGas = await ERC721FactoryContract.methods
.createNftWithErc20WithFixedRate(
{
name: nftName,
symbol: nftSymbol,
templateIndex,
tokenURI: `data:application/json;base64,${encodedMetadata}`
},
{
strings: [dtName, dtSymbol],
templateIndex,
addresses: [
ownerAddress,
ownerAddress,
publishingMarketFeeAddress,
publishingMarketTokenAddress
],
uints: [cap, 0],
bytess: []
},
{
fixedPriceAddress: fixedRateExchangeAddress,
addresses: [
baseTokenAddress,
ownerAddress,
ownerAddress,
publishingMarketFeeAddress
],
uints: [18, 18, rate, marketFee, 0]
}
)
.estimateGas({ from: ownerAddress }, (err, estGas) =>
err ? gasLimitDefault : estGas
)
} catch (error) {
console.log('error', error)
}
return estGas
}
public async publishFixedRateAsset(
did: string,
description: string,
ERC721FactoryAddress: string,
nftName: string,
nftSymbol: string,
ownerAddress: string,
cap: number,
rate: string,
marketFee: number,
publishingMarketFeeAddress: string,
publishingMarketTokenAddress: string,
fixedRateExchangeAddress: string,
baseTokenAddress: string,
templateIndex: number,
dtName: string,
dtSymbol: string
): Promise<TransactionReceipt> {
const ERC721FactoryContract = new this.web3.eth.Contract(
ERC721Factory.abi as AbiItem[],
ERC721FactoryAddress
)
const estGas = await this.estGasPublishFixedRateAsset(
did,
description,
ERC721FactoryAddress,
nftName,
nftSymbol,
ownerAddress,
cap,
rate,
marketFee,
publishingMarketFeeAddress,
publishingMarketTokenAddress,
fixedRateExchangeAddress,
baseTokenAddress,
templateIndex,
dtName,
dtSymbol
)
let tx: TransactionReceipt
const encodedMetadata = Buffer.from(
JSON.stringify({
name: nftName,
symbol: nftSymbol,
description: description
})
).toString('base64')
try {
tx = await ERC721FactoryContract.methods
.createNftWithErc20WithFixedRate(
{
name: nftName,
symbol: nftSymbol,
templateIndex,
tokenURI: `data:application/json;base64,${encodedMetadata}`
},
{
strings: [dtName, dtSymbol],
templateIndex,
addresses: [
ownerAddress,
ownerAddress,
publishingMarketFeeAddress,
publishingMarketTokenAddress
],
uints: [cap, 0],
bytess: []
},
{
fixedPriceAddress: fixedRateExchangeAddress,
addresses: [
baseTokenAddress,
ownerAddress,
ownerAddress,
publishingMarketFeeAddress
],
uints: [18, 18, rate, marketFee, 0]
}
)
.send({
from: ownerAddress,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
} catch (error) {
console.log('error', error)
}
return tx
}
public async estGaspublishFreeAsset(
description: string,
ERC721FactoryAddress: string,
nftName: string,
nftSymbol: string,
ownerAddress: string,
cap: number,
publishingMarketFeeAddress: string,
publishingMarketTokenAddress: string,
templateIndex: number,
dtName: string,
dtSymbol: string,
dispenserData: DispenserData
): Promise<number> {
const ERC721FactoryContract = new this.web3.eth.Contract(
ERC721Factory.abi as AbiItem[],
ERC721FactoryAddress
)
const encodedMetadata = Buffer.from(
JSON.stringify({
name: nftName,
symbol: nftSymbol,
description: description
})
).toString('base64')
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
try {
estGas = await ERC721FactoryContract.methods
.createNftWithErc20WithDispenser(
{
name: nftName,
symbol: nftSymbol,
templateIndex,
tokenURI: `data:application/json;base64,${encodedMetadata}`
},
{
strings: [dtName, dtSymbol],
templateIndex,
addresses: [
ownerAddress,
ownerAddress,
publishingMarketFeeAddress,
publishingMarketTokenAddress
],
uints: [cap, 0],
bytess: []
},
dispenserData
)
.estimateGas({ from: ownerAddress }, (err, estGas) =>
err ? gasLimitDefault : estGas
)
} catch (error) {
console.log('error', error)
}
return estGas
}
public async publishFreeAsset(
description: string,
ERC721FactoryAddress: string,
nftName: string,
nftSymbol: string,
ownerAddress: string,
cap: number,
publishingMarketFeeAddress: string,
publishingMarketTokenAddress: string,
templateIndex: number,
dtName: string,
dtSymbol: string,
dispenserData: DispenserData
): Promise<TransactionReceipt> {
const ERC721FactoryContract = new this.web3.eth.Contract(
ERC721Factory.abi as AbiItem[],
ERC721FactoryAddress
)
const estGas = await this.estGaspublishFreeAsset(
description,
ERC721FactoryAddress,
nftName,
nftSymbol,
ownerAddress,
cap,
publishingMarketFeeAddress,
publishingMarketTokenAddress,
templateIndex,
dtName,
dtSymbol,
dispenserData
)
let tx: TransactionReceipt
const encodedMetadata = Buffer.from(
JSON.stringify({
name: nftName,
symbol: nftSymbol,
description: description
})
).toString('base64')
try {
tx = await ERC721FactoryContract.methods
.createNftWithErc20WithDispenser(
{
name: nftName,
symbol: nftSymbol,
templateIndex,
tokenURI: `data:application/json;base64,${encodedMetadata}`
},
{
strings: [dtName, dtSymbol],
templateIndex,
addresses: [
ownerAddress,
ownerAddress,
publishingMarketFeeAddress,
publishingMarketTokenAddress
],
uints: [cap, 0],
bytess: []
},
dispenserData
)
.send({
from: ownerAddress,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
} catch (error) {
console.log('error', error)
}
return tx
}
public async estGasUpdateMetadata(
ownerAddress: string,
txReceipt: TransactionReceipt,
metaDataState: number,
metaDataDecryptorUrl: string,
metaDataDecryptorAddress: string,
flags: string,
data: string,
dataHash: string,
metadataProofs?: MetadataProof[]
): Promise<number> {
const gasLimitDefault = this.GASLIMIT_DEFAULT
let estGas
const event = txReceipt.events.NFTCreated
const tokenAddress = event.returnValues.newTokenAddress
if (!metadataProofs) metadataProofs = []
const tokenERC721 = new this.web3.eth.Contract(
ERC721Template.abi as AbiItem[],
tokenAddress
)
try {
estGas = await tokenERC721.methods
.setMetaData(
metaDataState,
metaDataDecryptorUrl,
metaDataDecryptorAddress,
flags,
data,
dataHash,
metadataProofs
)
.estimateGas({ from: ownerAddress }, (err, estGas) =>
err ? gasLimitDefault : estGas
)
} catch (error) {
console.log('error', error)
}
return estGas
}
public async updateMetadata(
ownerAddress: string,
txReceipt: TransactionReceipt,
metaDataState: number,
metaDataDecryptorUrl: string,
metaDataDecryptorAddress: string,
flags: string,
data: string,
dataHash: string,
metadataProofs?: MetadataProof[]
) {
const event = txReceipt.events.NFTCreated
const tokenAddress = event.returnValues.newTokenAddress
if (!metadataProofs) metadataProofs = []
const tokenERC721 = new this.web3.eth.Contract(
ERC721Template.abi as AbiItem[],
tokenAddress
)
const estGas = await this.estGasUpdateMetadata(
ownerAddress,
txReceipt,
metaDataState,
metaDataDecryptorUrl,
metaDataDecryptorAddress,
flags,
data,
dataHash,
metadataProofs
)
let tx: TransactionReceipt
try {
tx = await tokenERC721.methods
.setMetaData(
metaDataState,
metaDataDecryptorUrl,
metaDataDecryptorAddress,
flags,
data,
dataHash,
metadataProofs
)
.send({
from: ownerAddress,
gas: estGas + 1,
gasPrice: await getFairGasPrice(this.web3)
})
} catch (error) {
console.log('setMetaDataAndTokenURI ERROR', error)
}
return tx
}
public async migrateFixedRateAsset(
v3Did: string,
ERC721FactoryAddress: string,
nftName: string,
nftSymbol: string,
ownerAddress: string,
ownerAccount: Account,
cap: number,
rate: string,
flags: string,
marketFee: number,
publishingMarketFeeAddress: string,
publishingMarketTokenAddress: string,
fixedRateExchangeAddress: string,
baseTokenAddress: string,
metaDataState: number,
metaDataDecryptorAddress: string,
v4ProviderUrl: string,
v3MetadataCacheUri: string,
templateIndex: number,
dtName: string,
dtSymbol: string,
network: string | number,
v4MetadataCacheUri?: string
) {
let txReceipt: TransactionReceipt
const v3DDO = await getDDO(v3Did, v3MetadataCacheUri)
const description =
v3DDO.service[0].attributes.additionalInformation.description
try {
txReceipt = await this.publishFixedRateAsset(
v3Did,
description,
ERC721FactoryAddress,
nftName,
nftSymbol,
ownerAddress,
cap,
rate,
marketFee,
publishingMarketFeeAddress,
publishingMarketTokenAddress,
fixedRateExchangeAddress,
baseTokenAddress,
templateIndex,
dtName,
dtSymbol
)
} catch (e) {
console.log('publishFixedRateAsset Error', e)
}
const nftAddress = txReceipt.events.NFTCreated.returnValues.newTokenAddress
const erc20Address =
txReceipt.events.TokenCreated.returnValues.newTokenAddress
const encryptedFiles = await this.getEncryptedFiles(
v4ProviderUrl,
ownerAccount,
v3Did,
network
)
const v4Did = await this.generateDidv4(nftAddress)
const ddo = await getAndConvertDDO(
v3Did,
v4Did,
nftAddress,
erc20Address,
v3MetadataCacheUri,
encryptedFiles
)
const v4Provider = await V4ProviderInstance
const encryptedDdo = await v4Provider.encrypt(ddo, v4ProviderUrl)
const dataHash = '0x' + sha256(JSON.stringify(ddo)).toString()
const { validation, response } = await this.validateAssetAquariusV4(
ddo,
v4MetadataCacheUri
)
const isValid = response.hash === dataHash // Should be true
if (isValid === false) {
console.log('Asset is not valid')
return new Error('Invalid DDO hash')
}
let txReceipt2: TransactionReceipt
try {
txReceipt2 = await this.updateMetadata(
ownerAddress,
txReceipt,
metaDataState,
v4ProviderUrl,
metaDataDecryptorAddress,
flags,
encryptedDdo,
dataHash,
[validation]
)
} catch (e) {
console.log('Error', e)
}
return { txReceipt, txReceipt2 }
}
public async migrateFreeAsset(
v3Did: string,
ERC721FactoryAddress: string,
nftName: string,
nftSymbol: string,
ownerAddress: string,
ownerAccount: Account,
cap: number,
flags: string,
publishingMarketFeeAddress: string,
publishingMarketTokenAddress: string,
metaDataState: number,
metaDataDecryptorAddress: string,
v4ProviderUrl: string,
v3MetadataCacheUri: string,
templateIndex: number,
dtName: string,
dtSymbol: string,
network: string | number,
dispenserData: DispenserData,
v4MetadataCacheUri?: string
) {
let txReceipt: TransactionReceipt
const v3DDO = await getDDO(v3Did, v3MetadataCacheUri)
const description =
v3DDO.service[0].attributes.additionalInformation.description
try {
txReceipt = await this.publishFreeAsset(
description,
ERC721FactoryAddress,
nftName,
nftSymbol,
ownerAddress,
cap,
publishingMarketFeeAddress,
publishingMarketTokenAddress,
templateIndex,
dtName,
dtSymbol,
dispenserData
)
} catch (e) {
console.log('publishFixedRateAsset Error', e)
}
const nftAddress = txReceipt.events.NFTCreated.returnValues.newTokenAddress
const erc20Address =
txReceipt.events.TokenCreated.returnValues.newTokenAddress
const encryptedFiles = await this.getEncryptedFiles(
v4ProviderUrl,
ownerAccount,
v3Did,
network
)
const v4Did = await this.generateDidv4(nftAddress)
const ddo = await getAndConvertDDO(
v3Did,
v4Did,
nftAddress,
erc20Address,
v3MetadataCacheUri,
encryptedFiles
)
const v4Provider = await V4ProviderInstance
const encryptedDdo = await v4Provider.encrypt(ddo, v4ProviderUrl)
const dataHash = '0x' + sha256(JSON.stringify(ddo)).toString()
const { validation, response } = await this.validateAssetAquariusV4(
ddo,
v4MetadataCacheUri
)
const isValid = response.hash === dataHash // Should be true
if (isValid === false) {
console.log('Asset is not valid')
return new Error('Invalid DDO hash')
}
let txReceipt2: TransactionReceipt
try {
txReceipt2 = await this.updateMetadata(
ownerAddress,
txReceipt,
metaDataState,
v4ProviderUrl,
metaDataDecryptorAddress,
flags,
encryptedDdo,
dataHash,
[validation]
)
} catch (e) {
console.log('Error', e)
}
return { txReceipt, txReceipt2 }
}
}
| 26.70442
| 79
| 0.620254
|
534fd16707a411a6eb5ac738f77d40fd6ad1da2f
| 790
|
html
|
HTML
|
_layouts/default.html
|
dmundra/accessibility-for-teams
|
111b04928f5e0ccc2c6dcdca393c5a861be4ba1b
|
[
"CC0-1.0"
] | 65
|
2018-06-27T19:22:33.000Z
|
2021-12-21T00:00:52.000Z
|
_layouts/default.html
|
jeremyzilar/accessibility-for-teams
|
6263052786667bfc16284711d84b2743211ebcee
|
[
"CC0-1.0"
] | 46
|
2018-06-12T22:38:48.000Z
|
2022-03-28T13:50:28.000Z
|
_layouts/default.html
|
jeremyzilar/accessibility-for-teams
|
6263052786667bfc16284711d84b2743211ebcee
|
[
"CC0-1.0"
] | 29
|
2018-07-10T19:52:45.000Z
|
2022-02-15T04:20:27.000Z
|
<!DOCTYPE html>
<html lang="{{ page.lang | default: site.lang | default: "en" }}">
{% include head.html %}
<body class="page-{{ page.title | slugify }} page-{{ page.layout }}">
{% include header.html %}
<main class="main-content{% unless page.title == 'Home' %} grid-container {% endunless %}" id="main-content" aria-label="Content">
<div>
{{ content }}
</div>
</main>
{% include footer.html %}
<script>
//<![CDATA[
var usasearch_config = { siteHandle:"a11y4teams" };
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//search.usa.gov/javascripts/remote.loader.js";
document.getElementsByTagName("head")[0].appendChild(script);
//]]>
</script>
</body>
</html>
| 23.939394
| 134
| 0.594937
|
e27098b3cc9e972f54a655e1b4a4168c966cfcd1
| 963
|
js
|
JavaScript
|
build/main/lib/logger.js
|
iteco-labss/smartapp-bridge
|
2288b84a123a215539aca2ad7f4c4860d21c8f55
|
[
"MIT"
] | null | null | null |
build/main/lib/logger.js
|
iteco-labss/smartapp-bridge
|
2288b84a123a215539aca2ad7f4c4860d21c8f55
|
[
"MIT"
] | null | null | null |
build/main/lib/logger.js
|
iteco-labss/smartapp-bridge
|
2288b84a123a215539aca2ad7f4c4860d21c8f55
|
[
"MIT"
] | 1
|
2022-01-10T07:25:58.000Z
|
2022-01-10T07:25:58.000Z
|
"use strict";
/* eslint-disable functional/functional-parameters */
Object.defineProperty(exports, "__esModule", { value: true });
/** @ignore */
const log = (...args) => {
const text = args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' ');
alert(text);
};
exports.default = log;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9nZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2xpYi9sb2dnZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLHFEQUFxRDs7QUFFckQsY0FBYztBQUNkLE1BQU0sR0FBRyxHQUFHLENBQUMsR0FBRyxJQUE0QixFQUFFLEVBQUU7SUFDOUMsTUFBTSxJQUFJLEdBQUcsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFDLEdBQVksRUFBVSxFQUFFLENBQUMsQ0FBQyxPQUFPLEdBQUcsS0FBSyxRQUFRLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsSUFBSSxDQUFDLFNBQVMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFBO0lBQ2hILEtBQUssQ0FBQyxJQUFJLENBQUMsQ0FBQTtBQUNiLENBQUMsQ0FBQTtBQUVELGtCQUFlLEdBQUcsQ0FBQSJ9
| 96.3
| 646
| 0.86812
|
6f69c4accf808e8ae43d59d0ecf59f92b44b0b4a
| 327
|
sh
|
Shell
|
bin/setup.sh
|
nova-os/oer-faq-wp
|
001f187355496ddf80cb73d062cd3081416d4e6e
|
[
"MIT"
] | null | null | null |
bin/setup.sh
|
nova-os/oer-faq-wp
|
001f187355496ddf80cb73d062cd3081416d4e6e
|
[
"MIT"
] | null | null | null |
bin/setup.sh
|
nova-os/oer-faq-wp
|
001f187355496ddf80cb73d062cd3081416d4e6e
|
[
"MIT"
] | null | null | null |
#!/bin/bash
# Create .env
sed \
-e "s;%COMPOSE_PROJECT_NAME%;$COMPOSE_PROJECT_NAME;g" \
-e "s;%SERVERNAME%;$SERVERNAME;g" \
-e "s;%HTTP_PORT%;$HTTP_PORT;g" \
-e "s;%PLUGIN_ACF_KEY%;$PLUGIN_ACF_KEY;g" \
./.env.template > .env
# Run after deploy to install depnencies and start server
./bin/after-deploy.sh
| 27.25
| 59
| 0.654434
|
c48c7af6d5b5e07d40e9d39738326825c8d30382
| 1,912
|
dart
|
Dart
|
example/text/tab_text_example.dart
|
rafamizes/dartoos
|
fa42628c54a21ea520aec9fe2ef0dcf91f08025e
|
[
"MIT"
] | 5
|
2021-10-04T17:45:50.000Z
|
2021-12-16T20:28:00.000Z
|
example/text/tab_text_example.dart
|
rafamizes/dartoos
|
fa42628c54a21ea520aec9fe2ef0dcf91f08025e
|
[
"MIT"
] | 34
|
2021-10-04T18:04:30.000Z
|
2022-01-09T19:17:22.000Z
|
example/text/tab_text_example.dart
|
rafamizes/dartoos
|
fa42628c54a21ea520aec9fe2ef0dcf91f08025e
|
[
"MIT"
] | 2
|
2021-10-04T17:48:44.000Z
|
2021-10-04T17:58:03.000Z
|
// ignore_for_file: avoid_print
import 'dart:typed_data';
import 'package:dartoos/func.dart';
import 'package:dartoos/radix.dart';
import 'package:dartoos/text.dart';
/// Left-padded text representation of [int].
class LeftPad implements Func<String, int> {
/// [width] defaults to 2; [padding] defaults to ' ' (a single space).
const LeftPad([int width = 2, String padding = ' '])
: _width = width,
_padding = padding;
final int _width;
final String _padding;
@override
String call(int i) => '$i'.padLeft(_width, _padding);
}
void main() {
print('Given the data values (numbers 1–31):\n$values');
const weekHeader = 'mon tue wed thu fri sat sun';
const tabCal = TabText(
header: Header(weekHeader),
footer: Footer('\tJanuary'),
elemAsText: LeftPad(),
colPerRow: 7,
colSep: Sep(' '),
);
final cal = tabCal(values);
// print('\nThe values as calendar (7 columns per row):\n$weekHeader\n$cal');
print(
'\nA calendar with weekday names as header and month as footer:\n\n$cal',
);
print('\nThe values as bytes in 4 numeric systems (7 columns per row):');
// Hex
final tabBytesHex = HexTab.w8(colPerRow: 7);
final hexTabText = tabBytesHex(values);
print('\nHexadecimal:\n$hexTabText');
// Uint
final tabBytesUint = UintTab.w8(colPerRow: 7);
final uintTabText = tabBytesUint(values);
print('\nUnsigned integer:\n$uintTabText');
// Octal
final tabBytesOct = OctTab.w8(colPerRow: 7);
final octTabText = tabBytesOct(values);
print('\nOctal:\n$octTabText');
// Binary
final tabBytesBin = BinTab.w8(colPerRow: 7);
final binTabText = tabBytesBin(values);
print('\nBinary:\n$binTabText');
}
final values = Uint8List.fromList(<int>[
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
]);
| 20.126316
| 79
| 0.640167
|
2f1ab51a64cc9c2d10346fd70f49d11c1ebdc277
| 689
|
js
|
JavaScript
|
force-app/core/default/aura/AlertLib/AlertLibHelper.js
|
jonathanwiesel/Repo-Explorer
|
302c9770ff9fed2d1275c0d2464502480d8bcc61
|
[
"MIT"
] | 5
|
2018-10-29T09:42:55.000Z
|
2020-03-08T22:33:55.000Z
|
force-app/main/default/aura/AlertLib/AlertLibHelper.js
|
jfz94/TFG
|
c2ea8cbc325e09f3974b42e8cbd93605357adf81
|
[
"Unlicense"
] | 7
|
2019-02-16T16:39:56.000Z
|
2021-09-03T10:29:12.000Z
|
force-app/main/default/aura/AlertLib/AlertLibHelper.js
|
jfz94/TFG
|
c2ea8cbc325e09f3974b42e8cbd93605357adf81
|
[
"Unlicense"
] | 1
|
2020-03-08T22:37:12.000Z
|
2020-03-08T22:37:12.000Z
|
({
toggleVisible : function(component, visible) {
var notifier = component.find('notifier');
var variant = component.get('v.variant');
if (visible) {
$A.util.removeClass(notifier, 'slds-hide');
$A.util.addClass(notifier, variant);
} else {
$A.util.addClass(notifier, 'slds-hide');
$A.util.removeClass(notifier, variant);
}
},
showMessage: function (component, event, variant) {
var params = event.getParam('arguments');
component.set('v.msg', params.message);
component.set('v.variant', variant);
this.toggleVisible(component, true);
}
})
| 26.5
| 55
| 0.564586
|
20db1621fb7bb8cad2a29ab6fa757510887d0e2c
| 1,570
|
py
|
Python
|
src/captions_attacks/cap_main.py
|
tahleen-rahman/all2friends
|
156ba257677def409661e8b68ccdfb1e896ba721
|
[
"Apache-2.0"
] | null | null | null |
src/captions_attacks/cap_main.py
|
tahleen-rahman/all2friends
|
156ba257677def409661e8b68ccdfb1e896ba721
|
[
"Apache-2.0"
] | 4
|
2021-06-08T21:47:39.000Z
|
2022-03-12T00:35:39.000Z
|
src/captions_attacks/cap_main.py
|
tahleen-rahman/all2friends
|
156ba257677def409661e8b68ccdfb1e896ba721
|
[
"Apache-2.0"
] | null | null | null |
# Created by rahman at 15:30 2020-03-09 using PyCharm
from shared_tools.utils import make_allPairs, classifiers, city, DATAPATH
from captions_attacks.captions_utils import make_features, score_all_aucs, make_dfwords, get_TFIDF_filtered
def attack_captions(th, sublinear):
"""
:param th: When building the vocabulary ignore terms that have a document
frequency strictly higher than the given threshold (corpus-specific stop words).
:param sublinear: boolean, default=False
Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).
:return:
"""
df = make_dfwords(city, DATAPATH)
#df=pd.read_csv(DATAPATH + "words.csv")
TFIDF_matrix = get_TFIDF_filtered(sublinear, th, df, DATAPATH, TFIDFfile = str(sublinear)+str(th)+'filt_TFIDF.npz')
#TFIDF_matrix = scipy.sparse.load_npz(DATAPATH+ TFIDFfile)
allPairs = make_allPairs(str(th)+str(sublinear)+"filt_TFIDF_pairs.csv",
u_list=df.uid,
DATAPATH=DATAPATH,
friendFile=city + ".target_friends",
makeStrangers=True)
#allPairs=pd.read_csv(DATAPATH+str(th)+"filt_TFIDF_pairs.csv", index_col=0)
data_file = "cap_dataset.csv" #no save
make_features(data_file, df, TFIDF_matrix, allPairs, DATAPATH)
score_all_aucs(data_file, DATAPATH) #, classifiers=classifiers)
print ("Created caption dataset at", data_file)
return data_file
if __name__ == '__main__':
data_file = attack_captions(th=0.01, sublinear=True)
| 32.040816
| 119
| 0.679618
|
58a8e164813bd50f4b520acad5f5888e8bf7e8d5
| 540
|
css
|
CSS
|
Game/old game/game.css
|
4za4s/test
|
c35c30d7ffb2b06026450e7597363d0396e59a93
|
[
"MIT"
] | null | null | null |
Game/old game/game.css
|
4za4s/test
|
c35c30d7ffb2b06026450e7597363d0396e59a93
|
[
"MIT"
] | null | null | null |
Game/old game/game.css
|
4za4s/test
|
c35c30d7ffb2b06026450e7597363d0396e59a93
|
[
"MIT"
] | null | null | null |
body {
font-family: monospace, "Lucida Console";
background-color : #202020;
color: white;
font-size: 14px;
}
.points {
background-color: #424242;
border: 3px inset silver;
color: white;
padding: 8px 15px;
text-decoration: none;
display: inline-block;
font-size: 18px;
}
.button {
background-color: #4a5151;
border: none;
color: white;
padding: 12px 15px;
text-decoration: none;
display: inline-block;
font-size: 14px;
}
.costs {
position: relative;
left: 103px;
top: -15px;
}
| 16.363636
| 42
| 0.638889
|
0d61dfcb97014567d77835aa5a114c8961e1caf7
| 283
|
cs
|
C#
|
Feature/Marketing/SitecoreDev.Feature.Marketing/Contacts/Facets/ITopicSubscriptionElement.cs
|
sitecoredevbook/SitecoreDev
|
b23d9d7849296afed27ee565c91c18da374ee2e4
|
[
"MIT"
] | 10
|
2017-01-05T18:55:23.000Z
|
2019-09-05T19:31:52.000Z
|
Feature/Marketing/SitecoreDev.Feature.Marketing/Contacts/Facets/ITopicSubscriptionElement.cs
|
claudiu04/SitecoreDev
|
b23d9d7849296afed27ee565c91c18da374ee2e4
|
[
"MIT"
] | 2
|
2016-12-27T15:01:08.000Z
|
2017-10-09T13:12:52.000Z
|
Feature/Marketing/SitecoreDev.Feature.Marketing/Contacts/Facets/ITopicSubscriptionElement.cs
|
claudiu04/SitecoreDev
|
b23d9d7849296afed27ee565c91c18da374ee2e4
|
[
"MIT"
] | 8
|
2016-03-25T15:33:32.000Z
|
2019-09-05T12:14:15.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.Analytics.Model.Framework;
namespace SitecoreDev.Feature.Marketing.Contacts.Facets
{
public interface ITopicSubscriptionElement : IElement
{
string Topic { get; set; }
}
}
| 21.769231
| 55
| 0.777385
|
2322e0da3f0d94ed8f2f46f3b4e283e466fa649a
| 4,357
|
css
|
CSS
|
frontend/web/css/media2.css
|
gulyasmir/transport
|
bda58f5e906eabb305951c736e42261d69740030
|
[
"BSD-3-Clause"
] | null | null | null |
frontend/web/css/media2.css
|
gulyasmir/transport
|
bda58f5e906eabb305951c736e42261d69740030
|
[
"BSD-3-Clause"
] | null | null | null |
frontend/web/css/media2.css
|
gulyasmir/transport
|
bda58f5e906eabb305951c736e42261d69740030
|
[
"BSD-3-Clause"
] | null | null | null |
/*========== Desktop First Method ==========*/
/* Large Devices, Wide Screens */
@media only screen and (max-width : 1200px) {
.main-menu {
width: 155px;
}
.search {
width: 75px;
}
.city {
padding: 0 15px;
}
.cabinet__text {
display: none;
}
.hdr-order {
max-width: 140px;
}
.service__icon {
margin-right: 10px;
}
.serv-descr {
margin: 40px 0 0 45px;
}
.serv-descr__text-wrap {
max-width: 380px;
}
.serv-list li {
padding: 12px 25px 12px 20px;
max-width: 300px;
}
.ftr-info {
max-width: 140px;
margin-right: 45px;
}
.service-item {
height: 210px;
}
}
/* Medium Devices, Desktops */
@media only screen and (max-width : 992px) {
.tracking__input {
max-width: 290px;
}
.sub-wrapp {
display: none;
}
.cabinet {
margin-left: auto;
}
.cabinet__text {
margin-right: 12px;
display: block;
}
.phone {
display: none;
}
.bars {
display: block;
}
.service {
font-size: 18px;
justify-content: flex-start;
border: none;
}
.serv-list li {
max-width: 480px;
}
.serv-descr {
-webkit-flex-direction: column;
-moz-flex-direction: column;
-ms-flex-direction: column;
-o-flex-direction: column;
flex-direction: column;
justify-content: center;
margin: 0;
text-align: center;
}
.serv-descr__img-wrap {
margin: 30px 0;
}
.serv-list {
padding: 35px 0;
}
.serv-list li {
font-size: 14px;
padding: 8px 10px 8px 10px;
margin-bottom: 10px;
}
.ftr-logo {
text-align: center;
margin-bottom: 30px;
}
.ftr-info {
text-align: center;
}
.contacts {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
justify-content: space-around;
margin: 40px 0 0 0;
}
.contacts__contact {
margin-bottom: 0;
}
}
/* Small Devices, Tablets */
@media only screen and (max-width : 768px) {
.tracking {
margin: 50px 0 50px 0;
}
.calculation__title {
margin-bottom: 20px;
}
.service {
font-size: 30px;
}
.serv-list li {
margin-right: 20px;
max-width: 380px;
}
.link {
padding-left: 0;
text-align: center;
}
.link-wrap {
margin-left: 0;
}
.service-item {
height: 155px;
}
.service-item__title {
font-size: 20px;
}
}
/* Extra Small Devices, Phones */
@media only screen and (max-width : 576px) {
.cabinet__text {
display: none;
}
.service-sub-wrap {
max-width: 380px;
margin: 0 auto;
}
.news__img-wrap {
max-height: 170px;
margin-right: 12px;
width: 160px;
}
.news__title {
margin: 5px 0 10px 0;
font-size: 20px;
}
.news__content {
padding: 12px 12px 0 0;
}
.news__text {
padding-bottom: 15px;
}
.contacts {
-webkit-flex-direction: column;
-moz-flex-direction: column;
-ms-flex-direction: column;
-o-flex-direction: column;
flex-direction: column;
-ms-align-items: center;
align-items: center;
}
.contacts__contact {
margin-bottom: 30px;
}
.ftr-info {
margin: 0 auto;
margin-bottom: 50px;
}
.contacts {
margin-top: 0;
}
.ftr-info {
max-width: 100%;
}
}
/* Extra Small Devices, Phones */
@media only screen and (max-width : 480px) {
.bars {
margin-right: 20px;
}
.hdr-order {
font-size: 12px;
max-width: 120px;
}
.news {
-webkit-flex-direction: column;
-moz-flex-direction: column;
-ms-flex-direction: column;
-o-flex-direction: column;
flex-direction: column;
-ms-align-items: center;
align-items: center;
text-align: center;
}
.about__title {
font-size: 24px;
}
}
/* Custom, iPhone Retina */
@media only screen and (max-width : 380px) {
.hdr-order {
padding: 5px 0;
max-width: 60px;
}
.hdr-order img {
display: block;
margin: 0 auto;
}
.hdr-order span {
display: none;
}
}
/* Custom, iPhone Retina */
@media only screen and (max-width : 320px) {
}
/*========== Mobile First Method ==========*/
/* Custom, iPhone Retina */
@media only screen and (min-width : 320px) {
}
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px) {
}
/* Small Devices, Tablets */
@media only screen and (min-width : 600px) {
}
/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {
}
/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {
}
/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {
}
| 16.441509
| 48
| 0.614184
|
ff8ac36e910156d4b4f0288d3f069eb9cc6cae74
| 5,594
|
py
|
Python
|
warbler.py/spectrogram/plot.py
|
braycarlson/warbler.py
|
6746dc6479c9360811634c2d627606d788538d7e
|
[
"MIT"
] | null | null | null |
warbler.py/spectrogram/plot.py
|
braycarlson/warbler.py
|
6746dc6479c9360811634c2d627606d788538d7e
|
[
"MIT"
] | null | null | null |
warbler.py/spectrogram/plot.py
|
braycarlson/warbler.py
|
6746dc6479c9360811634c2d627606d788538d7e
|
[
"MIT"
] | 1
|
2022-03-31T21:44:03.000Z
|
2022-03-31T21:44:03.000Z
|
import matplotlib.pyplot as plt
import numpy as np
from dataclass.signal import Signal
from dataclass.spectrogram import Spectrogram
from matplotlib import gridspec
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
def plot_spectrogram(spectrogram, **kwargs):
ax = kwargs.pop('ax')
signal = kwargs.pop('signal')
x_minimum = 0
x_maximum = signal.duration
y_minimum = 0
y_maximum = signal.rate / 2
extent = [
x_minimum,
x_maximum,
y_minimum,
y_maximum
]
image = ax.matshow(
spectrogram,
interpolation=None,
aspect='auto',
origin='lower',
extent=extent,
**kwargs
)
ax.initialize()
ax._x_lim(x_maximum)
ax._x_step(x_maximum)
return image
def plot_segmentation(signal, dts):
spectrogram = dts.get('spec')
onsets = dts.get('onsets')
offsets = dts.get('offsets')
fig, ax = plt.subplots(
constrained_layout=True,
figsize=(20, 4),
subplot_kw={'projection': 'luscinia'}
)
plt.xticks(
fontfamily='Arial',
fontsize=14,
fontweight=600
)
plt.yticks(
fontfamily='Arial',
fontsize=14,
fontweight=600
)
image = plot_spectrogram(
spectrogram,
ax=ax,
signal=signal,
cmap=plt.cm.Greys,
)
ylmin, ylmax = ax.get_ylim()
ysize = (ylmax - ylmin) * 0.1
ymin = ylmax - ysize
patches = []
for index, (onset, offset) in enumerate(zip(onsets, offsets), 0):
ax.axvline(
onset,
color='dodgerblue',
ls='dashed',
lw=1,
alpha=0.75
)
ax.axvline(
offset,
color='dodgerblue',
ls='dashed',
lw=1,
alpha=0.75
)
rectangle = Rectangle(
xy=(onset, ymin),
width=offset - onset,
height=1000,
)
rx, ry = rectangle.get_xy()
cx = rx + rectangle.get_width() / 2.0
cy = ry + rectangle.get_height() / 2.0
ax.annotate(
index,
(cx, cy),
color='white',
weight=600,
fontfamily='Arial',
fontsize=8,
ha='center',
va='center'
)
patches.append(rectangle)
collection = PatchCollection(
patches,
color='dodgerblue',
alpha=0.75
)
ax.add_collection(collection)
return image
def plot_segmentation_with_vocal_envelope(signal, dts):
spectrogram = dts.get('spec')
vocal_envelope = dts.get('vocal_envelope')
onsets = dts.get('onsets')
offsets = dts.get('offsets')
plt.figure(
figsize=(15, 5)
)
gs = gridspec.GridSpec(
2,
1,
height_ratios=[1, 3]
)
gs.update(hspace=0.0)
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1], projection='luscinia')
image = plot_spectrogram(
spectrogram,
ax=ax1,
signal=signal,
cmap=plt.cm.Greys,
)
ax0.plot(vocal_envelope, color='k')
ax0.set_xlim(
[0, len(vocal_envelope)]
)
ylmin, ylmax = ax1.get_ylim()
ysize = (ylmax - ylmin) * 0.1
ymin = ylmax - ysize
patches = []
for index, (onset, offset) in enumerate(zip(onsets, offsets), 0):
ax1.axvline(
onset,
color='dodgerblue',
ls='dashed',
lw=1,
alpha=0.75
)
ax1.axvline(
offset,
color='dodgerblue',
ls='dashed',
lw=1,
alpha=0.75
)
rectangle = Rectangle(
xy=(onset, ymin),
width=offset - onset,
height=1000,
)
rx, ry = rectangle.get_xy()
cx = rx + rectangle.get_width() / 2.0
cy = ry + rectangle.get_height() / 2.0
ax1.annotate(
index,
(cx, cy),
color='white',
weight=600,
fontfamily='Arial',
fontsize=8,
ha='center',
va='center'
)
patches.append(rectangle)
collection = PatchCollection(
patches,
color='dodgerblue',
alpha=0.75
)
ax1.add_collection(collection)
ax0.axis('off')
return image
def create_luscinia_spectrogram(path, parameters):
signal = Signal(path)
signal.filter(
parameters.butter_lowcut,
parameters.butter_highcut
)
spectrogram = Spectrogram(signal, parameters)
fig, ax = plt.subplots(
constrained_layout=True,
figsize=(20, 4),
subplot_kw={'projection': 'luscinia'}
)
plt.xticks(
fontfamily='Arial',
fontsize=14,
fontweight=600
)
plt.yticks(
fontfamily='Arial',
fontsize=14,
fontweight=600
)
plot_spectrogram(
spectrogram.data,
ax=ax,
signal=signal,
cmap=plt.cm.Greys,
)
return fig
def create_spectrogram(path, parameters):
signal = Signal(path)
signal.filter(
parameters.butter_lowcut,
parameters.butter_highcut
)
spectrogram = Spectrogram(signal, parameters)
fig, ax = plt.subplots(
figsize=(20, 3),
subplot_kw={'projection': 'spectrogram'}
)
plot_spectrogram(
spectrogram.data,
ax=ax,
signal=signal,
cmap=plt.cm.afmhot,
)
plt.tight_layout()
return fig
| 19.836879
| 69
| 0.531999
|
245b0670dc0865d06dd9dc331fbc897e3de51707
| 3,021
|
kt
|
Kotlin
|
game/src/main/kotlin/gg/rsmod/game/fs/def/AnimDef.kt
|
EtherealCrip/TestServer1
|
30d5298b471b94daddb7531c13aa069ed5e1b4bd
|
[
"Apache-2.0"
] | 139
|
2019-03-21T10:19:46.000Z
|
2022-03-11T22:20:50.000Z
|
game/src/main/kotlin/gg/rsmod/game/fs/def/AnimDef.kt
|
EtherealCrip/TestServer1
|
30d5298b471b94daddb7531c13aa069ed5e1b4bd
|
[
"Apache-2.0"
] | 138
|
2019-03-21T14:54:35.000Z
|
2022-01-04T22:02:26.000Z
|
game/src/main/kotlin/gg/rsmod/game/fs/def/AnimDef.kt
|
anthonyloukinas/rsmod
|
2ad28c2aad39d7d9cf48b82e0e0029118894b631
|
[
"Apache-2.0"
] | 175
|
2019-03-21T14:20:31.000Z
|
2022-02-06T04:30:47.000Z
|
package gg.rsmod.game.fs.def
import gg.rsmod.game.fs.Definition
import io.netty.buffer.ByteBuf
/**
* @author Tom <rspsmods@gmail.com>
*/
class AnimDef(id: Int) : Definition(id) {
private lateinit var frameIds: IntArray
private lateinit var frameLengths: IntArray
private var priority = -1
private var lengthInCycles = 0
val cycleLength: Int get() = lengthInCycles
override fun decode(buf: ByteBuf, opcode: Int) {
when (opcode) {
1 -> {
val frameCount = buf.readUnsignedShort()
var totalFrameLength = 0
frameIds = IntArray(frameCount)
frameLengths = IntArray(frameCount)
for (i in 0 until frameCount) {
frameLengths[i] = buf.readUnsignedShort()
/**
* The last frame on some animations, such as death animations,
* are set to be extremely long in length. We don't want to take
* that into account when converting to game cycles, so we
* only add frame lengths that are below a certain threshold
* or if the frame <strong>isn't</strong> the last frame on the
* animation.
*/
if (i < frameCount - 1 || frameLengths[i] < 200) {
totalFrameLength += frameLengths[i]
}
}
for (i in 0 until frameCount) {
frameIds[i] = buf.readUnsignedShort()
}
for (i in 0 until frameCount) {
frameIds[i] += buf.readUnsignedShort() shl 16
}
/**
* Convert the length of the combined frames into game cycles
* (assuming a game cycle is 600ms).
*/
lengthInCycles = Math.ceil((totalFrameLength * 20.0) / 600.0).toInt()
}
2 -> buf.readUnsignedShort()
3 -> {
val count = buf.readUnsignedByte()
for (i in 0 until count) {
buf.readUnsignedByte()
}
}
5 -> buf.readUnsignedByte()
6 -> buf.readUnsignedShort()
7 -> buf.readUnsignedShort()
8 -> buf.readUnsignedByte()
9 -> buf.readUnsignedByte()
10 -> priority = buf.readUnsignedByte().toInt()
11 -> buf.readUnsignedByte()
12 -> {
val count = buf.readUnsignedByte()
for (i in 0 until count) {
buf.readUnsignedShort()
}
for (i in 0 until count) {
buf.readUnsignedShort()
}
}
13 -> {
val count = buf.readUnsignedByte()
for (i in 0 until count) {
buf.readMedium()
}
}
}
}
}
| 34.329545
| 85
| 0.473353
|
e00a50649cc5152d62997724237fe767f8649019
| 4,044
|
php
|
PHP
|
app/Http/Controllers/admin/Auth/RegisterController.php
|
raselrana1147/socialCommunity
|
a217bf9e580b1990bc52471741c67f34f74269c2
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/admin/Auth/RegisterController.php
|
raselrana1147/socialCommunity
|
a217bf9e580b1990bc52471741c67f34f74269c2
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/admin/Auth/RegisterController.php
|
raselrana1147/socialCommunity
|
a217bf9e580b1990bc52471741c67f34f74269c2
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers\admin\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Notifications\VerifyMail;
use Illuminate\Support\Str;
use App\Models\Notification;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
public function checkusername(Request $request){
$user=User::where('username', $request->username)->count();
if ($user<1) {
$message=['status'=>'success','msg'=>'Username available ✓'];
}else{
$message=['status'=>'error','msg'=>'Username already exists ✗'];
}
return json_encode($message);
}
public function register(Request $request){
$this->validate($request,[
'email' => ['required', 'string', 'email', 'max:255','unique:users'],
'username' => ['required', 'unique:users'],
'password' => ['required', 'string', 'min:4','confirmed'],
]);
$user=User::create([
'parent_id' =>$request->parent_id,
'email' => $request->email,
'username' => $request->username,
'password' => Hash::make($request->password),
'remember_token' => strtolower(Str::random(60)),
'salt' => base64_encode($request->password),
]);
$parent=User::where('id',$request->parent_id)->first();
if ($request->filled('parent_id')) {
Notification::create([
'title'=>'Has been sign up with your referal name',
'type'=>1,
'notification_to'=>$parent->id,
'notification_from'=>$user->id,
]);
}
$user->notify(new VerifyMail($user));
session()->flash('send_message','Please Check your email account to verify email');
$notification=array(
'messege'=>'Account created successfully.',
'alert-type'=>'success'
);
return redirect(route('login'))->with($notification);
}
public function verifyEmail($token){
$user=User::where('remember_token',$token)->first();
if (!is_null($user)) {
$user->email_active=1;
$user->remember_token=Null;
$user->save();
session()->flash('verify_success_message','Email is now verified.Please sing in');
return redirect(route('login'));
}else{
session()->flash('verify_success_message','Email is now verified.Please sing in');
return redirect(route('login'));
}
}
}
| 28.885714
| 100
| 0.543521
|
6df3ebbe629bcdc80d8a7a7bf5fbdebf692eff1d
| 1,557
|
c
|
C
|
lex_pars/ft_addtree.c
|
matt2905/Minishell
|
11b8c55a766c844012e0379d46bb14c09126d241
|
[
"Unlicense"
] | null | null | null |
lex_pars/ft_addtree.c
|
matt2905/Minishell
|
11b8c55a766c844012e0379d46bb14c09126d241
|
[
"Unlicense"
] | null | null | null |
lex_pars/ft_addtree.c
|
matt2905/Minishell
|
11b8c55a766c844012e0379d46bb14c09126d241
|
[
"Unlicense"
] | null | null | null |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_addtree.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmartin <mmartin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/02/28 18:41:02 by mmartin #+# #+# */
/* Updated: 2014/03/07 13:09:47 by mmartin ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "ft_lexpars.h"
t_parser *ft_create_parser(char *str, int type, int rank)
{
t_parser *tmp;
if ((tmp = (t_parser *)malloc(sizeof(t_parser))) == NULL)
return (NULL);
tmp->str = str;
tmp->type = type;
tmp->rank = rank;
tmp->left = NULL;
tmp->right = NULL;
return (tmp);
}
void ft_add_tree(t_parser **tree, t_lexer *tmp, t_lexer *list, int check)
{
if (tmp && tmp->rank == check)
{
tmp->flag = 0;
*tree = ft_create_parser(tmp->str, tmp->type, tmp->rank);
ft_parser(&((*tree)->right), tmp->next, check);
check++;
ft_parser(&((*tree)->left), list, check);
}
else
{
check++;
ft_parser(tree, list, check);
}
}
| 33.847826
| 80
| 0.328195
|
fb0d48269104269c11b242f4b722c7437e244090
| 7,707
|
lua
|
Lua
|
minetest-ego/games/adventuretest/mods/handle_schematics/analyze_mc_schematic_file.lua
|
medialab-prado/Interactivos-15-Ego
|
4c7e184b9495d07fc1008573ef1b752d20ebc1ab
|
[
"MIT"
] | null | null | null |
minetest-ego/games/adventuretest/mods/handle_schematics/analyze_mc_schematic_file.lua
|
medialab-prado/Interactivos-15-Ego
|
4c7e184b9495d07fc1008573ef1b752d20ebc1ab
|
[
"MIT"
] | null | null | null |
minetest-ego/games/adventuretest/mods/handle_schematics/analyze_mc_schematic_file.lua
|
medialab-prado/Interactivos-15-Ego
|
4c7e184b9495d07fc1008573ef1b752d20ebc1ab
|
[
"MIT"
] | null | null | null |
-- This code is used to read Minecraft schematic files.
--
-- The .schematic file format is described here:
-- http://minecraft.gamepedia.com/Schematic_file_format?cookieSetup=true
-- It is based on the NBT format, which is described here:
-- http://minecraft.gamepedia.com/NBT_Format?cookieSetup=true
-- position in the decompressed string data_stream
local curr_index = 1;
-- helper arry so that the values do not have to be calculated anew each time
local pot256 = { 1 };
for i=1,8 do
pot256[ #pot256+1 ] = pot256[ #pot256 ] * 256;
end
-- read length bytes from data_stream and turn it into an integer value
local read_signed = function( data_stream, length)
local res = 0;
for i=length,1,-1 do
res = res + (string.byte( data_stream, curr_index )* pot256[ i ]);
-- move one further
curr_index = curr_index+1;
end
return res;
end
-- this table will collect the few tags we're actually intrested in
local mc_schematic_data = {};
-- this will be a recursive function
local read_tag;
-- needs to be defined now because it will contain a recursive function
local read_one_tag;
-- read payload of one tag (= a data element in a NBT data structure)
read_one_tag = function( data_stream, tag, title_tag )
if( tag<= 0 or not(data_stream)) then
return;
elseif( tag==1 ) then -- TAG_BYTE: 1 byte
return read_signed( data_stream, 1 );
elseif( tag==2 ) then -- TAG_SHORT: 2 bytes
return read_signed( data_stream, 2 );
elseif( tag==3 ) then -- TAG_INT: 4 bytes
return read_signed( data_stream, 4 );
elseif( tag==4 ) then -- TAG_LONG: 8 bytes
return read_signed( data_stream, 8 );
elseif( tag==5 ) then -- TAG_FLOAT: 4 bytes
return read_signed( data_stream, 4 ); -- the float values are unused here
elseif( tag==6 ) then -- TAG_DOUBLE: 8 bytes
return read_signed( data_stream, 8 ); -- the float values are unused here
elseif( tag==7 ) then -- TAG_Byte_Array
local size = read_signed( data_stream, 4 ); -- TAG_INT
local res = {};
for i=1,size do
-- a Byte_Array does not contain any sub-tags
res[i] = read_one_tag( data_stream, 1, nil ); -- read TAG_BYTE
end
return res;
elseif( tag==8 ) then -- TAG_String
local size = read_signed( data_stream, 2);
local res = string.sub( data_stream, curr_index, curr_index+size-1 );
-- move on in the data stream
curr_index = curr_index + size;
return res;
elseif( tag==9 ) then -- TAG_List
-- these exact values are not particulary intresting
local tagtyp = read_signed( data_stream, 1 ); -- TAG_BYTE
local size = read_signed( data_stream, 4 ); -- TAG_INT
local res = {};
for i=1,size do
-- we need to pass title_tag on to the "child"
res[i] = read_one_tag( data_stream, tagtyp, title_tag );
end
return res;
elseif( tag==10 ) then -- TAG_Compound
return read_tag( data_stream, title_tag );
elseif( tag==11 ) then -- TAG_Int_Array
local size = read_signed( data_stream, 4 ); -- TAG_INT
local res = {};
for i=1,size do
-- a Int_Array does not contain any sub-tags
res[i] = read_one_tag( data_stream, 3, nil ); -- TAG_INT
end
return res;
end
end
-- read tag type, tag name and call read_one_tag to get the payload;
read_tag = function( data_stream, title_tag )
local schematic_data = {};
while( data_stream ) do
local tag = string.byte( data_stream, curr_index);
-- move on in the data stream
curr_index = curr_index + 1;
if( not( tag ) or tag <= 0 ) then
return;
end
local tag_name_length = string.byte( data_stream, curr_index ) * 256 + string.byte(data_stream, curr_index + 1);
-- move 2 further
curr_index = curr_index + 2;
local tag_name = string.sub( data_stream, curr_index, curr_index+tag_name_length-1 );
-- move on...
curr_index = curr_index + tag_name_length;
--print('[analyze_mc_schematic_file] Found: Tag '..tostring( tag )..' <'..tostring( tag_name )..'>');
local res = read_one_tag( data_stream, tag, tag_name );
-- Entities and TileEntities are ignored
if( title_tag == 'Schematic'
and( tag_name == 'Width'
or tag_name == 'Height'
or tag_name == 'Length'
or tag_name == 'Materials' -- "Classic" or "Alpha" (=Survival)
or tag_name == 'Blocks'
or tag_name == 'Data'
)) then
mc_schematic_data[ tag_name ] = res;
end
end
return;
end
handle_schematics.analyze_mc_schematic_file = function( path )
-- these files are usually compressed; there is no point to start if the
-- decompress function is missing
if( minetest.decompress == nil) then
return nil;
end
local file, err = save_restore.file_access(path..'.schematic', "rb")
if (file == nil) then
-- print('[analyze_mc_schematic_file] ERROR: NO such file: '..tostring( path..'.schematic'));
return nil
end
local compressed_data = file:read( "*all" );
--local data_string = minetest.decompress(compressed_data, "deflate" );
local data_string = compressed_data; -- TODO
print('FILE SIZE: '..tostring( string.len( data_string ))); -- TODO
file.close(file)
-- we use this (to this file) global variable to store gathered information;
-- doing so inside the recursive functions proved problematic
mc_schematic_data = {};
-- this index will iterate through the schematic data
curr_index = 1;
-- actually analyze the data
read_tag( data_string, nil );
if( not( mc_schematic_data.Width )
or not( mc_schematic_data.Height )
or not( mc_schematic_data.Length )
or not( mc_schematic_data.Blocks )
or not( mc_schematic_data.Data )) then
print('[analyze_mc_schematic_file] ERROR: Failed to analyze '..tostring( path..'.schematic'));
return nil;
end
local translation_function = handle_schematics.findMC2MTConversion;
if( minetest.get_modpath('mccompat')) then
translation_function = mccompat.findMC2MTConversion;
end
local max_msg = 40; -- just for error handling
local size = {x=mc_schematic_data.Width, y=mc_schematic_data.Height, z=mc_schematic_data.Length};
local scm = {};
local nodenames = {};
local nodenames_id = {};
for y=1,size.y do
scm[y] = {};
for x=1,size.x do
scm[y][x] = {};
for z =1,size.z do
local new_node = translation_function(
-- (Y×length + Z)×width + X.
mc_schematic_data.Blocks[ ((y-1)*size.z + (z-1) )*size.x + (size.x-x) +1],
mc_schematic_data.Data[ ((y-1)*size.z + (z-1) )*size.x + (size.x-x) +1] );
-- some MC nodes store the information about a node in TWO block and data fields (doors, large flowers, ...)
if( new_node[3] and new_node[3]~=0 ) then
new_node = translation_function(
-- (Y×length + Z)×width + X.
mc_schematic_data.Blocks[ ((y-1)*size.z + (z-1) )*size.x + (size.x-x) +1],
mc_schematic_data.Data[ ((y-1)*size.z + (z-1) )*size.x + (size.x-x) +1],
mc_schematic_data.Blocks[ ((y-1+new_node[3])*size.z + (z-1) )*size.x + (size.x-x) +1],
mc_schematic_data.Data[ ((y-1+new_node[3])*size.z + (z-1) )*size.x + (size.x-x) +1] );
end
if( not( nodenames_id[ new_node[1]] )) then
nodenames_id[ new_node[1] ] = #nodenames + 1;
nodenames[ nodenames_id[ new_node[1] ]] = new_node[1];
end
-- print a few warning messages in case something goes wrong - but do not exaggerate
if( not( new_node[2] and max_msg>0)) then
-- print('[handle_schematics:schematic] MISSING param2: '..minetest.serialize( new_node ));
new_node[2]=0;
max_msg=max_msg-1;
end
-- save some space by not saving air
if( new_node[1] ~= 'air' ) then
scm[y][x][z] = { nodenames_id[ new_node[1]], new_node[2]};
end
end
end
end
return { size = { x=size.x, y=size.y, z=size.z}, nodenames = nodenames, on_constr = {}, after_place_node = {}, rotated=90, burried=0, scm_data_cache = scm, metadata = {}};
end
| 35.680556
| 172
| 0.676658
|
1a45f0bccc4a78e28a2f11339d96818bfcf3d924
| 145
|
py
|
Python
|
gpsearch/__init__.py
|
Fluid-Dynamics-Group/gpsearch
|
8c5758c9fb2b623ef79952c3e9c113cb157d79bc
|
[
"MIT"
] | 6
|
2020-07-13T00:02:17.000Z
|
2022-03-11T08:49:27.000Z
|
gpsearch/__init__.py
|
Fluid-Dynamics-Group/gpsearch
|
8c5758c9fb2b623ef79952c3e9c113cb157d79bc
|
[
"MIT"
] | null | null | null |
gpsearch/__init__.py
|
Fluid-Dynamics-Group/gpsearch
|
8c5758c9fb2b623ef79952c3e9c113cb157d79bc
|
[
"MIT"
] | 9
|
2020-07-18T13:29:46.000Z
|
2022-03-22T15:14:14.000Z
|
from .core import *
from .plotting import *
from .benchmarks import *
from .examples import *
import warnings
warnings.filterwarnings("ignore")
| 18.125
| 33
| 0.772414
|
874ed3ed6ad669d551e72b7c3da2e3c5db576e08
| 964
|
rb
|
Ruby
|
lib/numeric_with_unit/unit_definition/imperial.rb
|
diaphragm/ruby-numeric-with-unit
|
0c93d0e52f7c383d32905201cf9604b8934ced39
|
[
"MIT"
] | 12
|
2015-08-05T12:56:45.000Z
|
2019-12-19T10:59:56.000Z
|
lib/numeric_with_unit/unit_definition/imperial.rb
|
diaphragm/ruby-numeric-with-unit
|
0c93d0e52f7c383d32905201cf9604b8934ced39
|
[
"MIT"
] | null | null | null |
lib/numeric_with_unit/unit_definition/imperial.rb
|
diaphragm/ruby-numeric-with-unit
|
0c93d0e52f7c383d32905201cf9604b8934ced39
|
[
"MIT"
] | null | null | null |
# coding: utf-8
require 'numeric_with_unit/unit_definition/base'
Unit['yd'] = "0.9144".to_r , 'm'
Unit['ft'] = "1/3".to_r, 'yd'
Unit['th'] = "1/12000".to_r, 'ft'
Unit['in'] = "1/12".to_r, 'ft'
Unit['ch'] = 66, 'ft'
Unit['fur'] = 660, 'ft'
Unit['mi'] = 5280, 'ft'
Unit['lea'] = 15840, 'ft'
Unit['floz'] = "2.84130625e-05".to_r, 'm3'
Unit['gi'] = 5, 'floz'
Unit['pt'] = 20, 'floz'
Unit['qt'] = 40, 'floz'
Unit['gal'] = 160, 'floz'
Unit['bbl'] = "0.158987294928".to_r, 'm3'
Unit['oz'] = "0.45359237".to_r, 'kg'
Unit['gr'] = "1/7000".to_r, 'oz'
Unit['dr'] = "1/256".to_r, 'oz'
Unit['lb'] = "1/16".to_r, 'oz'
Unit['st'] = 14, 'oz'
Unit['qtr'] = 28, 'oz'
Unit['cwt'] = 112, 'oz'
Unit['t'] = 2240, 'oz'
Unit['degR'] = "9/5".to_r, 'K'
Unit << Unit.new do |conf|
deg_r = Unit['degR']
conf.symbol = '℉'
conf.dimension = deg_r.dimension
conf.from_si = ->(x){(deg_r.from_si(x)) - 459.67}
conf.to_si = ->(x){deg_r.to_si(x + 459.67)}
end
Unit['degF'] = '℉'
| 21.909091
| 51
| 0.54668
|
59c4f253f0734cf6eadea71bc6c232a63efa11c0
| 2,800
|
lua
|
Lua
|
cmd/daemon/simpledemo.lua
|
netsys-lab/panapi
|
08bdabf5e467d95b2f8ca40d26c9e24167b0ab7b
|
[
"Apache-2.0"
] | null | null | null |
cmd/daemon/simpledemo.lua
|
netsys-lab/panapi
|
08bdabf5e467d95b2f8ca40d26c9e24167b0ab7b
|
[
"Apache-2.0"
] | 23
|
2021-12-10T16:07:06.000Z
|
2022-01-25T10:45:02.000Z
|
cmd/daemon/simpledemo.lua
|
netsys-lab/panapi
|
08bdabf5e467d95b2f8ca40d26c9e24167b0ab7b
|
[
"Apache-2.0"
] | null | null | null |
print("HELLO FROM SIMPLE LUA DE(A)MO(N) SCRIPT")
-- global "path database variable",
-- not directly referenced from go
paths = {}
-- global table to keep track of connections
conns = {}
-- global table to keep track of connection identites
connids = {}
-- helper function
function rankpaths(raddr)
table.sort(
paths[raddr],
function(path_a, path_b)
return path_a.Expiry < path_b.Expiry
end
)
table.sort(
paths[raddr],
function(path_a, path_b)
return #path_a.Metadata.Interfaces < #path_b.Metadata.Interfaces
end
)
end
-- gets called when a set of paths to addr is known
function panapi.Initialize(prefs, laddr, raddr, ps)
panapi.Log("New connection [" .. laddr, "|", raddr .. "] Profile:", prefs.ConnCapacityProfile)
paths[raddr] = ps
conns[raddr] = conns[raddr] or {}
conns[raddr][laddr] = prefs
rankpaths(raddr)
end
function panapi.SetPreferences(prefs, laddr, raddr)
panapi.Log("Update Preferences [" .. laddr, "|", raddr .. "] Profile:", prefs.ConnCapacityProfile)
conns[raddr][laddr] = prefs
end
-- gets called for every packet
-- implementation needs to be efficient
function panapi.Path(laddr, raddr)
--panapi.Log("Path", laddr, raddr)
if #paths[raddr] > 0 then
if conns[raddr][laddr]["ConnCapacityProfile"] == "Scavenger" then
p = paths[raddr][#paths[raddr]]
return p
else
return paths[raddr][1]
end
end
end
-- gets called whenever a path disappears(?)
function panapi.PathDown(laddr, raddr, fp, pi)
panapi.Log("PathDown called with", laddr, raddr, fp, pi)
for i,path in ipairs(paths[raddr]) do
if path.Fingerprint == fp then
panapi.Log("found path at index " .. tostring(i) .. ", removing")
table.remove(paths[raddr], i)
break
end
end
end
function panapi.Refresh(laddr, raddr, ps)
panapi.Log("Refresh", raddr, ps)
paths[raddr] = ps
rankpaths(raddr)
end
function panapi.Close(laddr, raddr)
panapi.Log("Close", laddr, raddr)
conns[raddr][laddr] = nil
--paths[raddr] = nil
end
function panapi.Periodic(seconds)
--panapi.Log("Tick", seconds)
end
-- HELPER FUNCTIONS ---
--
-- Print contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
function tprint (tbl, indent)
if not indent then indent = 0 end
if type(tbl) == "table" then
local s = ""
for k, v in pairs(tbl) do
formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
--print(formatting)
s = s .. formatting .. "\n" .. tprint(v, indent+1)
else
s = s .. formatting .. tprint(v) .. "\n"
end
end
return s
else
return tostring(tbl)
end
end
| 25
| 101
| 0.626071
|
187f70bb50b36a532d10a274e721f98b20dc2045
| 4,827
|
go
|
Go
|
03_basics_gcf/go/main.go
|
rizasif/GCP_Quick_Starts
|
9df5e963d412d66e9a5119732d2a8193b63bbd6f
|
[
"Apache-2.0"
] | 13
|
2017-11-27T22:06:53.000Z
|
2019-04-18T07:11:30.000Z
|
03_basics_gcf/go/main.go
|
rizasif/GCP_Quick_Starts
|
9df5e963d412d66e9a5119732d2a8193b63bbd6f
|
[
"Apache-2.0"
] | null | null | null |
03_basics_gcf/go/main.go
|
rizasif/GCP_Quick_Starts
|
9df5e963d412d66e9a5119732d2a8193b63bbd6f
|
[
"Apache-2.0"
] | 11
|
2019-07-13T07:28:45.000Z
|
2022-01-27T19:26:33.000Z
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package testblog03a
import (
"context"
b64 "encoding/base64"
"fmt"
"net/http"
"os"
"golang.org/x/oauth2/google"
cloudiot "google.golang.org/api/cloudiot/v1"
)
/*
Variable block. Should be the only pieces needing editing
*/
// You shouldn't need to change this variable, it's here for illustration
// purposes. An advantage of calling a Cloud Function within the same project
// is that there are certain environment varibales you get for free like this
// one
var projectID = os.Getenv("GCP_PROJECT")
// change the following to match your project's values
// you could also easily modify the code to receieve these as variables
// in the GET call since I'm relying on that for the config/command switch
// as well as the actual message being sent
var registryID = "<registry_id>"
var gcpLocation = "<project location>"
var deviceID = "<device_id>"
// a couple default values just for the sake of having something there
var msg = "clear" // by default will reset the LED matrix
var which = "config" // by default will send a config message
/*
END VARIABLE BLOCK
*/
// getClient returns a client based on the environment variable GOOGLE_APPLICATION_CREDENTIALS
func getClient() (*cloudiot.Service, error) {
// Authorize the client using Application Default Credentials.
// See https://g.co/dv/identity/protocols/application-default-credentials
ctx := context.Background()
httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
if err != nil {
return nil, err
}
client, err := cloudiot.New(httpClient)
if err != nil {
return nil, err
}
return client, nil
}
// setConfig configures a device. If the device is online it will get it immediately,
// if not, it will fetch it upon next connection to IoT Core
func setConfig(client *cloudiot.Service) (*cloudiot.DeviceConfig, error) {
req := cloudiot.ModifyCloudToDeviceConfigRequest{
BinaryData: b64.StdEncoding.EncodeToString([]byte(msg)),
}
path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, gcpLocation, registryID, deviceID)
response, err := client.Projects.Locations.Registries.Devices.ModifyCloudToDeviceConfig(path, &req).Do()
if err != nil {
return nil, err
}
return response, nil
}
// sendCommand sends a command to a device listening for commands. Command lost if
// device isn't connected at time of send
func sendCommand(client *cloudiot.Service) (*cloudiot.SendCommandToDeviceResponse, error) {
req := cloudiot.SendCommandToDeviceRequest{
BinaryData: b64.StdEncoding.EncodeToString([]byte(msg)),
}
path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, gcpLocation, registryID, deviceID)
response, err := client.Projects.Locations.Registries.Devices.SendCommandToDevice(path, &req).Do()
if err != nil {
return nil, err
}
return response, nil
}
// UpdateDevice entry point for the cloud function
func UpdateDevice(w http.ResponseWriter, r *http.Request) {
// this fetches our authorized client using the default credentials
client, clientErr := getClient()
if clientErr != nil {
fmt.Println("Failed to get auth'd client: " + clientErr.Error())
return
}
// if a which variable was passed in the URL, update which mode we're in
reqWhich, ok := r.URL.Query()["which"]
if ok {
which = string(reqWhich[0])
}
// if a message variable was passed, update our msg variable to reflect it
reqMsg, ok := r.URL.Query()["message"]
if ok {
msg = string(reqMsg[0])
}
// switch on which method we got passed into the function (config/clear by default)
// sending back the proper response codes
if which == "config" {
_, configErr := setConfig(client)
if configErr != nil {
fmt.Println("Failed to configure something")
fmt.Printf("%s", configErr)
fmt.Fprintf(w, "%d", 500)
} else {
fmt.Println("I have successfully configured a device!")
fmt.Fprintf(w, "%d", 200)
}
} else if which == "command" {
_, commandErr := sendCommand(client)
if commandErr != nil {
fmt.Println("Failed to send command")
fmt.Printf("%s", commandErr)
fmt.Fprintf(w, "%d", 500)
} else {
fmt.Println("I have successfully sent a command!")
fmt.Fprintf(w, "%d", 200)
}
} else {
fmt.Fprintf(w, "%d", 500)
}
}
| 31.966887
| 119
| 0.722602
|
1a539429e54b69d7d5936b2637953a4045729a27
| 61
|
py
|
Python
|
catkin_ws/devel/lib/python2.7/dist-packages/pr2_gazebo_plugins/msg/__init__.py
|
Sinchiguano/Robotic-Arm-Imitation-by-Human-Gesture
|
28a6a855581881d3c9197619a318a5094294e5b6
|
[
"BSD-2-Clause"
] | null | null | null |
catkin_ws/devel/lib/python2.7/dist-packages/pr2_gazebo_plugins/msg/__init__.py
|
Sinchiguano/Robotic-Arm-Imitation-by-Human-Gesture
|
28a6a855581881d3c9197619a318a5094294e5b6
|
[
"BSD-2-Clause"
] | null | null | null |
catkin_ws/devel/lib/python2.7/dist-packages/pr2_gazebo_plugins/msg/__init__.py
|
Sinchiguano/Robotic-Arm-Imitation-by-Human-Gesture
|
28a6a855581881d3c9197619a318a5094294e5b6
|
[
"BSD-2-Clause"
] | null | null | null |
from ._ModelJointsState import *
from ._PlugCommand import *
| 20.333333
| 32
| 0.803279
|
f445732249aa594f6bca0079afd818100f4094a2
| 404
|
ts
|
TypeScript
|
src/facade/User/facade.ts
|
jose-estebanLZ/NodeJsExpress
|
c8e4e3790e34930ce9ec6664ef449833673ddd9b
|
[
"MIT"
] | 1
|
2021-01-16T05:55:02.000Z
|
2021-01-16T05:55:02.000Z
|
src/facade/User/facade.ts
|
jose-estebanLZ/NodeJsExpress
|
c8e4e3790e34930ce9ec6664ef449833673ddd9b
|
[
"MIT"
] | null | null | null |
src/facade/User/facade.ts
|
jose-estebanLZ/NodeJsExpress
|
c8e4e3790e34930ce9ec6664ef449833673ddd9b
|
[
"MIT"
] | 10
|
2021-01-15T15:40:51.000Z
|
2021-01-28T10:27:46.000Z
|
import { UserService } from "../../services";
import { IUserFacade } from "./interface";
/**
* @export
* @implements {IUserModelService}
*/
const UserFacade: IUserFacade = {
/**
* @returns {Promise < any[] >}
* @memberof UserFacade
*/
async findAll(): Promise<any[]> {
let users = await UserService.findAll();
return users;
}
}
export default UserFacade;
| 19.238095
| 48
| 0.594059
|
c95419dc06c6db1700e019d2be967645dbfc87cf
| 3,496
|
tsx
|
TypeScript
|
console/src/features/RemoteRelationships/RemoteSchemaRelationships/components/RemoteSchemaToDB/FormElements.tsx
|
catalinpit/graphql-engine
|
d058dafae22aa2165cf490c59ea5d67b62071a8d
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
console/src/features/RemoteRelationships/RemoteSchemaRelationships/components/RemoteSchemaToDB/FormElements.tsx
|
catalinpit/graphql-engine
|
d058dafae22aa2165cf490c59ea5d67b62071a8d
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
console/src/features/RemoteRelationships/RemoteSchemaRelationships/components/RemoteSchemaToDB/FormElements.tsx
|
catalinpit/graphql-engine
|
d058dafae22aa2165cf490c59ea5d67b62071a8d
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
import React, { useEffect, useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { useRemoteSchema } from '@/features/MetadataAPI';
// eslint-disable-next-line no-restricted-imports
import { useTableColumns } from '@/features/SqlQueries/hooks/useTableColumns';
import { InputField, Select } from '@/new-components/Form';
import { MapSelector } from '@/new-components/MapSelector';
import {
LinkBlockHorizontal,
LinkBlockVertical,
} from '@/new-components/LinkBlock';
import { RemoteDatabaseWidget } from '../RemoteDatabaseWidget';
import { RsSourceTypeSelector } from '../RsSourceTypeSelector';
import { Schema } from './schema';
import { getTypesFromIntrospection } from '../../utils';
export const FormElements = ({
sourceRemoteSchema,
}: {
sourceRemoteSchema: string;
}) => {
const { watch } = useFormContext<Schema>();
const database = watch('database');
const schema = watch('schema');
const table = watch('table');
const RSTypeName = watch('typeName');
const { fetchSchema, data, isLoading } = useRemoteSchema();
const { data: columnData } = useTableColumns(database, {
name: table,
schema,
});
const columns: string[] = columnData
? columnData.slice(1).map((x: string[]) => x[3])
: [];
React.useEffect(() => {
if (sourceRemoteSchema) {
fetchSchema(sourceRemoteSchema);
}
}, [fetchSchema, sourceRemoteSchema]);
const [typeMap, setTypeMap] = useState<{ field: string; column: string }[]>(
[]
);
useEffect(() => {
setTypeMap([]);
}, [RSTypeName]);
if (!data)
return (
<div className="grid border border-gray-300 rounded shadow-sm p-4">
Data is not ready
</div>
);
if (isLoading)
return (
<div className="grid border border-gray-300 rounded shadow-sm p-4">
Loading...
</div>
);
const remoteSchemaTypes = getTypesFromIntrospection(data);
return (
<>
<div className="w-full sm:w-6/12 my-md">
<div className="mb-md">
<InputField
name="relationshipName"
label="Name"
placeholder="Relationship name"
dataTest="rs-to-db-rel-name"
/>
</div>
<div className="mb-md">
<Select
name="relationshipType"
label="Type"
dataTest="select-rel-type"
placeholder="Select a relationship type..."
options={[
{
label: 'Array Relationship',
value: 'array',
},
{
label: 'Object Relationship',
value: 'object',
},
]}
/>
</div>
</div>
<div className="grid grid-cols-12">
<div className="col-span-5">
<RsSourceTypeSelector
types={remoteSchemaTypes.map(t => t.typeName)}
sourceTypeKey="typeName"
/>
</div>
<LinkBlockHorizontal />
<div className="col-span-5">
<RemoteDatabaseWidget />
</div>
</div>
{/* vertical connector line */}
<LinkBlockVertical title="Type Mapped To" />
<MapSelector
types={
remoteSchemaTypes.find(x => x.typeName === RSTypeName)?.fields ?? []
}
columns={columns}
typeMappings={typeMap}
placeholder=""
name="mapping"
onChange={e => {
setTypeMap([...e]);
}}
/>
</>
);
};
| 26.285714
| 78
| 0.566076
|
f04d269b5f1430e9e241c3bcdcd2678b4446c98e
| 381
|
go
|
Go
|
models/messenger/payload.go
|
AntoniPD/That-s-you-Bot-
|
6f0aed24b2038969d4fb193231227e08aeb28a83
|
[
"MIT"
] | null | null | null |
models/messenger/payload.go
|
AntoniPD/That-s-you-Bot-
|
6f0aed24b2038969d4fb193231227e08aeb28a83
|
[
"MIT"
] | null | null | null |
models/messenger/payload.go
|
AntoniPD/That-s-you-Bot-
|
6f0aed24b2038969d4fb193231227e08aeb28a83
|
[
"MIT"
] | null | null | null |
package models
type Payload struct {
URL string `json:"url,omitempty"`
TemplateType string `json:"template_type,omitempty"`
Sharable bool `json:"sharable,omitempty"`
ImageAspectRation string `json:"image_aspect_ratio,omitempty"`
Text string `json:"text,omitempty"`
Buttons []Button `json:"buttons,omitempty"`
}
| 34.636364
| 65
| 0.645669
|
eaa20d41bae11d64960c2ca89b89acea50e2a8c0
| 541
|
js
|
JavaScript
|
node_modules/@material-ui/system/merge.js
|
immbudden/buddeen
|
857703cd16e126a0d591161382de42e037476d17
|
[
"MIT"
] | 12
|
2021-09-22T07:15:32.000Z
|
2021-11-05T01:23:48.000Z
|
node_modules/@material-ui/system/merge.js
|
latonaio/ui-frontend-for-vr-face-recognition
|
54b70e6544301af2f002d4eabca224e769aa4d60
|
[
"MIT"
] | 28
|
2020-04-06T01:32:17.000Z
|
2022-03-24T11:35:11.000Z
|
node_modules/@material-ui/system/merge.js
|
latonaio/ui-frontend-for-vr-face-recognition
|
54b70e6544301af2f002d4eabca224e769aa4d60
|
[
"MIT"
] | 4
|
2020-04-15T03:01:38.000Z
|
2020-06-01T16:43:35.000Z
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _deepmerge = _interopRequireDefault(require("deepmerge"));
// < 1kb payload overhead when lodash/merge is > 3kb.
function merge(acc, item) {
if (!item) {
return acc;
}
return (0, _deepmerge.default)(acc, item, {
clone: false // No need to clone deep, it's way faster.
});
}
var _default = merge;
exports.default = _default;
| 21.64
| 85
| 0.698706
|
254ba8d9289ba7f63d23964811e0553475b054a9
| 279
|
rb
|
Ruby
|
config/routes.rb
|
MaximeCap/projetRails
|
d53b8a391ed98bacb80fb175adff1e75df3f80ea
|
[
"MIT"
] | null | null | null |
config/routes.rb
|
MaximeCap/projetRails
|
d53b8a391ed98bacb80fb175adff1e75df3f80ea
|
[
"MIT"
] | 17
|
2019-06-20T17:33:21.000Z
|
2022-02-11T23:01:06.000Z
|
config/routes.rb
|
MaximeCap/projetRails
|
d53b8a391ed98bacb80fb175adff1e75df3f80ea
|
[
"MIT"
] | null | null | null |
Rails.application.routes.draw do
get 'utilisateurs/new'
root 'statique#accueil'
get '/contact', to: 'statique#contact'
get '/team', to: 'statique#team'
get '/services', to: 'statique#services'
get '/signup', to: 'utilisateurs#new'
resources :utilisateurs
end
| 17.4375
| 42
| 0.688172
|
d2522cf91d828976ac8aea5f4622467d9a3f17c3
| 3,681
|
sql
|
SQL
|
nanda.sql
|
wmacibnc/nanda-vendas
|
b4ea220e9183f33b34952b33f1e256c4a9f86efe
|
[
"MIT"
] | null | null | null |
nanda.sql
|
wmacibnc/nanda-vendas
|
b4ea220e9183f33b34952b33f1e256c4a9f86efe
|
[
"MIT"
] | null | null | null |
nanda.sql
|
wmacibnc/nanda-vendas
|
b4ea220e9183f33b34952b33f1e256c4a9f86efe
|
[
"MIT"
] | null | null | null |
-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: 02-Out-2018 às 06:07
-- Versão do servidor: 10.1.31-MariaDB
-- PHP Version: 7.0.26
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `id7337092_nanda`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `CONTROLE`
--
CREATE TABLE `CONTROLE` (
`ID` int(5) NOT NULL,
`NOME` varchar(50) NOT NULL,
`CODIGO` varchar(20) NOT NULL,
`QUANTIDADE` int(5) NOT NULL,
`PRECOCUSTO` int(5) NOT NULL,
`PRECOVENDA` int(5) NOT NULL,
`DATA` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `CONTROLE`
--
INSERT INTO `CONTROLE` (`ID`, `NOME`, `CODIGO`, `QUANTIDADE`, `PRECOCUSTO`, `PRECOVENDA`, `DATA`) VALUES
(15, 'Anjo Pequeno', 'A', 13, 5, 10, '2018-10-02 05:51:57'),
(16, 'Anjo Grande', 'B', 6, 5, 13, '2018-10-02 05:52:31'),
(17, 'Coelho', 'C', 8, 22, 50, '2018-10-02 05:53:29'),
(18, 'Boneca Pitica', 'D', 5, 7, 25, '2018-10-02 05:54:00'),
(19, 'Boneca Julieta P', 'E', 2, 15, 35, '2018-10-02 05:54:40'),
(20, 'Boneca Julieta M', 'F', 5, 20, 60, '2018-10-02 05:55:08'),
(21, 'Boneca Julieta G', 'G', 5, 45, 100, '2018-10-02 05:55:39'),
(22, 'Noel Barbudão Sentado', 'H', 6, 15, 35, '2018-10-02 05:56:14'),
(23, 'Noel Porta Garrafa', 'J', 4, 20, 50, '2018-10-02 05:56:52'),
(24, 'Boneca Princesa Gigida', 'K', 4, 10, 35, '2018-10-02 05:57:23'),
(25, 'Anjo dos Zoião', 'L', 5, 15, 35, '2018-10-02 05:57:52'),
(26, 'Noel Porta Colher', 'M', 6, 25, 65, '2018-10-02 05:58:37'),
(27, 'Noel Pingente', 'N', 15, 8, 20, '2018-10-02 05:59:01'),
(28, 'Africana Bujão', 'O', 8, 20, 40, '2018-10-02 05:59:49'),
(29, 'Africana Olivia', 'P', 7, 20, 40, '2018-10-02 06:00:14'),
(30, 'Galinda', 'Q', 4, 15, 35, '2018-10-02 06:00:51'),
(31, 'Cachorrinho', 'R', 9, 6, 15, '2018-10-02 06:01:28'),
(32, 'Ponteira de Flôr', 'S', 45, 4, 10, '2018-10-02 06:02:11'),
(33, 'Bebê Miminha', 'T', 6, 20, 45, '2018-10-02 06:02:39'),
(34, 'Pingente de Arvoré', 'U', 6, 3, 5, '2018-10-02 06:03:31'),
(35, 'Boneca Moranguinho', 'V', 10, 4, 10, '2018-10-02 06:04:02'),
(36, 'Trio Noel', 'X', 5, 40, 100, '2018-10-02 06:04:53'),
(37, 'Noel Gigante', 'Y', 4, 25, 55, '2018-10-02 06:05:19'),
(38, 'Mamãe Noel', 'Z', 2, 25, 50, '2018-10-02 06:05:48');
-- --------------------------------------------------------
--
-- Estrutura da tabela `VENDA`
--
CREATE TABLE `VENDA` (
`ID_VENDA` int(5) NOT NULL,
`CODIGO` varchar(20) NOT NULL,
`VALOR` int(5) NOT NULL,
`DATA_HORA` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `CONTROLE`
--
ALTER TABLE `CONTROLE`
ADD PRIMARY KEY (`ID`);
--
-- Indexes for table `VENDA`
--
ALTER TABLE `VENDA`
ADD PRIMARY KEY (`ID_VENDA`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `CONTROLE`
--
ALTER TABLE `CONTROLE`
MODIFY `ID` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=39;
--
-- AUTO_INCREMENT for table `VENDA`
--
ALTER TABLE `VENDA`
MODIFY `ID_VENDA` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 30.675
| 104
| 0.618582
|
b8d12f7563ab2c8318376236eeee0acdb2e1cc51
| 1,387
|
py
|
Python
|
pop/scanner.py
|
thatch45/pop
|
b1ea83cf93c1ea28851129146d8507842363aa6a
|
[
"Apache-2.0"
] | null | null | null |
pop/scanner.py
|
thatch45/pop
|
b1ea83cf93c1ea28851129146d8507842363aa6a
|
[
"Apache-2.0"
] | null | null | null |
pop/scanner.py
|
thatch45/pop
|
b1ea83cf93c1ea28851129146d8507842363aa6a
|
[
"Apache-2.0"
] | 1
|
2021-02-05T04:18:33.000Z
|
2021-02-05T04:18:33.000Z
|
# -*- coding: utf-8 -*-
'''
Used to scan the given directories for loadable files
'''
# Import python libs
import os
import imp
import collections
PY_END = ('.py', '.pyc', '.pyo')
PYEXT_END = tuple([suffix[0] for suffix in imp.get_suffixes() if suffix[-1] == imp.C_EXTENSION])
CYTHON_END = ('.pyx',)
SKIP_DIRNAMES = ('__pycache__',)
def scan(dirs):
'''
Return a list of importable files
'''
ret = collections.OrderedDict()
ret['python'] = collections.OrderedDict()
ret['cython'] = collections.OrderedDict()
ret['ext'] = collections.OrderedDict()
ret['imp'] = collections.OrderedDict()
for dir_ in dirs:
for fn_ in os.listdir(dir_):
_apply_scan(ret, dir_, fn_)
return ret
def _apply_scan(ret, dir_, fn_):
'''
Convert the scan data into
'''
if fn_.startswith('_'):
return
if os.path.basename(dir_) in SKIP_DIRNAMES:
return
full = os.path.join(dir_, fn_)
if '.' not in full:
return
bname = full[:full.rindex('.')]
if fn_.endswith(PY_END):
if bname not in ret['python']:
ret['python'][bname] = {'path': full}
if fn_.endswith(CYTHON_END):
if bname not in ret['cython']:
ret['cython'][bname] = {'path': full}
if fn_.endswith(PYEXT_END):
if bname not in ret['ext']:
ret['ext'][bname] = {'path': full}
| 26.673077
| 96
| 0.594809
|
546d29c4a3a6b585d1eb3732a5dc4110ad63890f
| 101
|
swift
|
Swift
|
Tests/LinuxMain.swift
|
bantana/swiftlearn
|
cc7a3b0ccd8edcd756d9459d3be78889e828687d
|
[
"MIT"
] | null | null | null |
Tests/LinuxMain.swift
|
bantana/swiftlearn
|
cc7a3b0ccd8edcd756d9459d3be78889e828687d
|
[
"MIT"
] | null | null | null |
Tests/LinuxMain.swift
|
bantana/swiftlearn
|
cc7a3b0ccd8edcd756d9459d3be78889e828687d
|
[
"MIT"
] | null | null | null |
import XCTest
@testable import swiftlearnTests
XCTMain([
testCase(swiftlearnTests.allTests),
])
| 14.428571
| 39
| 0.782178
|
6601a609864f9d20a536e35dd8dfc839ba9332db
| 317
|
py
|
Python
|
Taller_secuencias_control_secuencial/ejercicio_2.py
|
willingtonino/Algoritmos_programacion_C4G2
|
2a2c94678ae981974539a8019f17108775521e23
|
[
"MIT"
] | null | null | null |
Taller_secuencias_control_secuencial/ejercicio_2.py
|
willingtonino/Algoritmos_programacion_C4G2
|
2a2c94678ae981974539a8019f17108775521e23
|
[
"MIT"
] | null | null | null |
Taller_secuencias_control_secuencial/ejercicio_2.py
|
willingtonino/Algoritmos_programacion_C4G2
|
2a2c94678ae981974539a8019f17108775521e23
|
[
"MIT"
] | 1
|
2021-10-31T22:54:45.000Z
|
2021-10-31T22:54:45.000Z
|
"""
Entradas
Salario bruto-->float-->salario
Salidas
Salario nuevo-->float-->sueldo
"""
#Entrada
salario=float(input("Digite el salario bruto: "))
#Caja negra
sueldo=0
if(salario<900000):
sueldo=salario*0.15+salario#float
else:
sueldo=salario*0.12+salario#float
#Salida
print("Su nuevo salario es de:",sueldo)
| 19.8125
| 49
| 0.731861
|
f93759343ff65dd9d0ef29302c41ddd0e3cae3bd
| 1,287
|
sh
|
Shell
|
scripts/testIosCI.sh
|
sierrakn/turtle
|
0cb05600c21cd8f26d94b3159a563d72345ce83a
|
[
"MIT"
] | null | null | null |
scripts/testIosCI.sh
|
sierrakn/turtle
|
0cb05600c21cd8f26d94b3159a563d72345ce83a
|
[
"MIT"
] | null | null | null |
scripts/testIosCI.sh
|
sierrakn/turtle
|
0cb05600c21cd8f26d94b3159a563d72345ce83a
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env bash
export NODE_ENV=test
export ENVIRONMENT="development"
export AWS_SQS_IOS_QUEUE_URL="https://sqs.us-west-2.amazonaws.com/274251141632/turtle_jobs_local_jakub_ios_in.fifo"
export AWS_SQS_ANDROID_QUEUE_URL="https://sqs.us-west-2.amazonaws.com/274251141632/turtle_jobs_local_jakub_android_in.fifo"
export AWS_SQS_IOS_PRIORITY_QUEUE_URL="https://sqs.us-west-2.amazonaws.com/274251141632/turtle_jobs_local_jakub_ios_in_priority.fifo"
export AWS_SQS_ANDROID_PRIORITY_QUEUE_URL="https://sqs.us-west-2.amazonaws.com/274251141632/turtle_jobs_local_jakub_android_in_priority.fifo"
export AWS_SQS_OUT_QUEUE_URL="https://sqs.us-west-2.amazonaws.com/274251141632/turtle_jobs_local_jakub_out.fifo"
export AWS_SQS_REGION="aws.west2"
export AWS_S3_BUCKET="exp-shell-app-assets"
export AWS_S3_REGION="us-west-1"
export AWS_CLOUDWATCH_REGION="us-west-1"
export API_PROTOCOL="https"
export API_HOSTNAME="staging.expo.io"
export API_PORT="443"
export REDIS_URL="noop"
export REDIS_CONFIG_URL="noop"
ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
$ROOT_DIR/scripts/ios/fetchRemoteIosTarball.sh
yarn test:smoke:ios
smoke_result=$?
yarn test:unit
unit_result=$?
[[ $smoke_result != 0 || $unit_result != 0 ]] && \
echo && \
echo "Tests failed." && \
exit -1
exit 0
| 35.75
| 141
| 0.797203
|
48eee3380e6f23e538ba95e83b8c8958ad60bb6d
| 500
|
ps1
|
PowerShell
|
Splatting/Splatting - Shorten line.ps1
|
t-demo/WorkshopGitDemo1
|
05ba93c75987677b7bfc4e8f3345d7cd05267761
|
[
"MIT"
] | 1
|
2021-11-10T14:08:42.000Z
|
2021-11-10T14:08:42.000Z
|
Splatting/Splatting - Shorten line.ps1
|
t-demo/WorkshopGitDemo1
|
05ba93c75987677b7bfc4e8f3345d7cd05267761
|
[
"MIT"
] | 1
|
2021-11-10T14:46:22.000Z
|
2021-11-10T14:46:22.000Z
|
Splatting/Splatting - Shorten line.ps1
|
raandree/WorkshopGitDemo1
|
05ba93c75987677b7bfc4e8f3345d7cd05267761
|
[
"MIT"
] | null | null | null |
#Splatting helps keep command lines short
Set-PSFLoggingProvider -Name 'sql' -InstanceName 'MyTask' -SqlServer 'DSCCASQL01.contoso.com' -Database 'LoggingDB' -Table 'Logs' -Enabled $true -Credential $cred
$paramSetPSFLoggingProvider = @{
Name = 'sql'
#InstanceName = 'MyTask'
SqlServer = 'DSCCASQL01.contoso.com'
Database = 'LoggingDB'
Table = 'Logs'
Enabled = $true
Credential = $cred
}
Set-PSFLoggingProvider @paramSetPSFLoggingProvider
| 29.411765
| 162
| 0.678
|
a120232d4a53c50de82ad0d470cba0c17c5fcd85
| 5,950
|
ts
|
TypeScript
|
spec/unit/search/search-by-number.spec.ts
|
Lionardo/redis-om-node
|
f6743b4a7403fc1d76e804cb9058c72295cedd2a
|
[
"BSD-3-Clause"
] | null | null | null |
spec/unit/search/search-by-number.spec.ts
|
Lionardo/redis-om-node
|
f6743b4a7403fc1d76e804cb9058c72295cedd2a
|
[
"BSD-3-Clause"
] | null | null | null |
spec/unit/search/search-by-number.spec.ts
|
Lionardo/redis-om-node
|
f6743b4a7403fc1d76e804cb9058c72295cedd2a
|
[
"BSD-3-Clause"
] | 1
|
2022-02-11T20:29:22.000Z
|
2022-02-11T20:29:22.000Z
|
import { mocked } from 'ts-jest/utils';
import Client from "../../../lib/client";
import Search from "../../../lib/search/search";
import WhereField from '../../../lib/search/where-field';
import { simpleSchema, SimpleEntity } from "../helpers/test-entity-and-schema";
jest.mock('../../../lib/client');
beforeEach(() => mocked(Client).mockReset());
describe("Search", () => {
describe("#query", () => {
let client: Client;
let search: Search<SimpleEntity>;
let where: WhereField<SimpleEntity>;
const AN_EQUAL_QUERY = "(@aNumber:[42 42])";
const A_NEGATED_EQUAL_QUERY = "(-@aNumber:[42 42])";
const A_GT_QUERY = "(@aNumber:[(42 +inf])";
const A_NEGATED_GT_QUERY = "(-@aNumber:[(42 +inf])";
const A_GTE_QUERY = "(@aNumber:[42 +inf])";
const A_NEGATED_GTE_QUERY = "(-@aNumber:[42 +inf])";
const AN_LT_QUERY = "(@aNumber:[-inf (42])";
const A_NEGATED_LT_QUERY = "(-@aNumber:[-inf (42])";
const AN_LTE_QUERY = "(@aNumber:[-inf 42])";
const A_NEGATED_LTE_QUERY = "(-@aNumber:[-inf 42])";
const A_BETWEEN_QUERY = "(@aNumber:[23 42])";
const A_NEGATED_BETWEEN_QUERY = "(-@aNumber:[23 42])";
beforeAll(() => client = new Client());
beforeEach(() => {
search = new Search<SimpleEntity>(simpleSchema, client);
where = search.where('aNumber');
});
describe("when generating a query with a number", () => {
type RangeChecker = (search: Search<SimpleEntity>) => void;
const expectToBeEqualQuery: RangeChecker = search => expect(search.query).toBe(AN_EQUAL_QUERY);
const expectToBeNegatedEqualQuery: RangeChecker = search => expect(search.query).toBe(A_NEGATED_EQUAL_QUERY);
const expectToBeGTQuery: RangeChecker = search => expect(search.query).toBe(A_GT_QUERY);
const expectToBeNegatedGTQuery: RangeChecker = search => expect(search.query).toBe(A_NEGATED_GT_QUERY);
const expectToBeGTEQuery: RangeChecker = search => expect(search.query).toBe(A_GTE_QUERY);
const expectToBeNegatedGTEQuery: RangeChecker = search => expect(search.query).toBe(A_NEGATED_GTE_QUERY);
const expectToBeLTQuery: RangeChecker = search => expect(search.query).toBe(AN_LT_QUERY);
const expectToBeNegatedLTQuery: RangeChecker = search => expect(search.query).toBe(A_NEGATED_LT_QUERY);
const expectToBeLTEQuery: RangeChecker = search => expect(search.query).toBe(AN_LTE_QUERY);
const expectToBeNegatedLTEQuery: RangeChecker = search => expect(search.query).toBe(A_NEGATED_LTE_QUERY);
const expectToBeBetweenQuery: RangeChecker = search => expect(search.query).toBe(A_BETWEEN_QUERY);
const expectToBeNegatedBetweenQuery: RangeChecker = search => expect(search.query).toBe(A_NEGATED_BETWEEN_QUERY);
it("generates a query with .eq", () => expectToBeEqualQuery(where.eq(42)));
it("generates a query with .not.eq", () => expectToBeNegatedEqualQuery(where.not.eq(42)));
it("generates a query with .equals", () => expectToBeEqualQuery(where.equals(42)));
it("generates a query with .does.equal", () => expectToBeEqualQuery(where.does.equal(42)));
it("generates a query with .does.not.equal", () => expectToBeNegatedEqualQuery(where.does.not.equal(42)));
it("generates a query with .is.equalTo", () => expectToBeEqualQuery(where.is.equalTo(42)));
it("generates a query with .is.not.equalTo", () => expectToBeNegatedEqualQuery(where.is.not.equalTo(42)));
it("generates a query with .gt", () => expectToBeGTQuery(where.gt(42)));
it("generates a query with .not.gt", () => expectToBeNegatedGTQuery(where.not.gt(42)));
it("generates a query with .greaterThan", () => expectToBeGTQuery(where.greaterThan(42)));
it("generates a query with .is.greaterThan", () => expectToBeGTQuery(where.is.greaterThan(42)));
it("generates a query with .is.not.greaterThan", () => expectToBeNegatedGTQuery(where.is.not.greaterThan(42)));
it("generates a query with .gte", () => expectToBeGTEQuery(where.gte(42)));
it("generates a query with .not.gte", () => expectToBeNegatedGTEQuery(where.not.gte(42)));
it("generates a query with .greaterThanOrEqualTo", () => expectToBeGTEQuery(where.greaterThanOrEqualTo(42)));
it("generates a query with .is.greaterThanOrEqualTo", () => expectToBeGTEQuery(where.is.greaterThanOrEqualTo(42)));
it("generates a query with .is.not.greaterThanOrEqualTo", () => expectToBeNegatedGTEQuery(where.is.not.greaterThanOrEqualTo(42)));
it("generates a query with .lt", () => expectToBeLTQuery(where.lt(42)));
it("generates a query with .not.lt", () => expectToBeNegatedLTQuery(where.not.lt(42)));
it("generates a query with .lessThan", () => expectToBeLTQuery(where.lessThan(42)));
it("generates a query with .is.lessThan", () => expectToBeLTQuery(where.is.lessThan(42)));
it("generates a query with .is.not.lessThan", () => expectToBeNegatedLTQuery(where.is.not.lessThan(42)));
it("generates a query with .lte", () => expectToBeLTEQuery(where.lte(42)));
it("generates a query with .not.lte", () => expectToBeNegatedLTEQuery(where.not.lte(42)));
it("generates a query with .lessThanOrEqualTo", () => expectToBeLTEQuery(where.lessThanOrEqualTo(42)));
it("generates a query with .is.lessThanOrEqualTo", () => expectToBeLTEQuery(where.is.lessThanOrEqualTo(42)));
it("generates a query with .is.not.lessThanOrEqualTo", () => expectToBeNegatedLTEQuery(where.is.not.lessThanOrEqualTo(42)));
it("generates a query with .between", () => expectToBeBetweenQuery(where.between(23, 42)));
it("generates a query with .not.between", () => expectToBeNegatedBetweenQuery(where.not.between(23, 42)));
it("generates a query with .is.between", () => expectToBeBetweenQuery(where.is.between(23, 42)));
it("generates a query with .is.not.between", () => expectToBeNegatedBetweenQuery(where.is.not.between(23, 42)));
});
});
});
| 61.979167
| 136
| 0.68521
|
9069b9d09897b1fa5278858e8100d3fe71d43b7f
| 4,690
|
rs
|
Rust
|
codegen/src/codegen/gpio.rs
|
seanybaggins/stm32f3xx-hal
|
6884b72d8b49bf595003b3d05a97134fc15b37e6
|
[
"0BSD"
] | null | null | null |
codegen/src/codegen/gpio.rs
|
seanybaggins/stm32f3xx-hal
|
6884b72d8b49bf595003b3d05a97134fc15b37e6
|
[
"0BSD"
] | null | null | null |
codegen/src/codegen/gpio.rs
|
seanybaggins/stm32f3xx-hal
|
6884b72d8b49bf595003b3d05a97134fc15b37e6
|
[
"0BSD"
] | null | null | null |
use crate::cubemx::ip::gpio;
use anyhow::{Context, Result};
use once_cell::sync::Lazy;
use regex::Regex;
use std::collections::HashMap;
struct Port<'a> {
id: char,
pins: Vec<&'a gpio::Pin>,
}
pub fn gen_mappings(gpio_ips: &[gpio::Ip]) -> Result<()> {
for ip in gpio_ips.iter() {
println!();
gen_gpio_ip(ip)?;
}
Ok(())
}
fn gen_gpio_ip(ip: &gpio::Ip) -> Result<()> {
let feature = ip_version_to_feature(&ip.version)?;
let ports = merge_pins_by_port(&ip.pins)?;
println!(
r#"#[cfg(all(feature = "{}", feature = "numbered_imri_pri_rstri_ftsri"))]"#,
feature
);
let numbered_imri_pri_rstri_ftsri = true;
gen_gpio_macro_call(&ports, &feature, numbered_imri_pri_rstri_ftsri)?;
println!(
r#"#[cfg(all(feature = "{}", not(feature = "numbered_imri_pri_rstri_ftsri")))]"#,
feature
);
let numbered_imri_pri_rstri_ftsri = false;
gen_gpio_macro_call(&ports, &feature, numbered_imri_pri_rstri_ftsri)?;
Ok(())
}
fn ip_version_to_feature(ip_version: &str) -> Result<String> {
static VERSION: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^STM32(?P<version>\w+)_gpio_v1_0$").unwrap());
let captures = VERSION
.captures(&ip_version)
.with_context(|| format!("invalid GPIO IP version: {}", ip_version))?;
let version = captures.name("version").unwrap().as_str();
let feature = format!("gpio-{}", version.to_lowercase());
Ok(feature)
}
fn merge_pins_by_port(pins: &[gpio::Pin]) -> Result<Vec<Port>> {
let mut pins_by_port = HashMap::new();
for pin in pins.iter() {
pins_by_port
.entry(pin.port()?)
.and_modify(|e: &mut Vec<_>| e.push(pin))
.or_insert_with(|| vec![pin]);
}
let mut ports = Vec::new();
for (id, mut pins) in pins_by_port {
pins.sort_by_key(|p| p.number().unwrap_or_default());
pins.dedup_by_key(|p| p.number().unwrap_or_default());
ports.push(Port { id, pins });
}
ports.sort_by_key(|p| p.id);
Ok(ports)
}
fn gen_gpio_macro_call(
ports: &[Port],
feature: &str,
numbered_imri_pri_rstri_ftsri: bool,
) -> Result<()> {
println!("gpio!([");
print!(" ");
match numbered_imri_pri_rstri_ftsri {
false => println!(r#"imri: imr,
pri: pr,
rtsri: rtsr,
ftsri: ftsr,
"#),
true => println!(r#"imri: imr1,
pri: pr1,
rtsri: rtsr1,
ftsri: ftsr1,
"#)
}
for port in ports {
gen_port(port, feature)?;
}
println!("]);");
Ok(())
}
fn gen_port(port: &Port, feature: &str) -> Result<()> {
let pac_module = get_port_pac_module(port, feature);
let extigpionr = match port.id {
'A' => 0,
'B' => 1,
'C' => 2,
'D' => 3,
'E' => 4,
'F' => 5,
'G' => 6,
'H' => 7,
_ => unreachable!(),
};
println!(" {{");
println!(
" port: ({}/{}, pac: {}, extigpionr: {}),",
port.id,
port.id.to_lowercase(),
pac_module,
extigpionr,
);
println!(" pins: [");
for pin in &port.pins {
gen_pin(pin)?;
}
println!(" ],");
println!(" }},");
Ok(())
}
fn get_port_pac_module(port: &Port, feature: &str) -> &'static str {
// The registers in ports A and B have different reset values due to the
// presence of debug pins, so they get dedicated PAC modules.
match port.id {
'A' => "gpioa",
'B' => "gpiob",
'D' if feature == "gpio-f373" => "gpiod",
_ => "gpioc",
}
}
fn gen_pin(pin: &gpio::Pin) -> Result<()> {
let nr = pin.number()?;
let reset_mode = get_pin_reset_mode(pin)?;
let afr = if nr < 8 { 'L' } else { 'H' };
let af_numbers = get_pin_af_numbers(pin)?;
let exticri = pin.number()? / 4 + 1;
println!(
" {} => {{ reset: {}, afr: {}/{}, exticri: {}, af: {:?} }},",
nr,
reset_mode,
afr,
afr.to_lowercase(),
exticri,
af_numbers,
);
Ok(())
}
fn get_pin_reset_mode(pin: &gpio::Pin) -> Result<&'static str> {
// Debug pins default to their debug function (AF0), everything else
// defaults to floating input.
let mode = match (pin.port()?, pin.number()?) {
('A', 13) | ('A', 14) | ('A', 15) | ('B', 3) | ('B', 4) => "AF0",
_ => "Input<Floating>",
};
Ok(mode)
}
fn get_pin_af_numbers(pin: &gpio::Pin) -> Result<Vec<u8>> {
let mut numbers = Vec::new();
for signal in &pin.pin_signals {
numbers.push(signal.af()?);
}
numbers.sort();
numbers.dedup();
Ok(numbers)
}
| 25.215054
| 89
| 0.535181
|
dafcd1f68e05828ad2fd42e748e19d8500f4959b
| 973
|
swift
|
Swift
|
UploadImages/RxQBImagePickerControllerDelegateProxy.swift
|
DianQK/rx-sample-code
|
d121f3f2e63dff7936356923861486755f4833d7
|
[
"MIT"
] | 184
|
2016-09-30T01:38:56.000Z
|
2021-11-16T10:03:22.000Z
|
UploadImages/RxQBImagePickerControllerDelegateProxy.swift
|
DianQK/rx-sample-code
|
d121f3f2e63dff7936356923861486755f4833d7
|
[
"MIT"
] | 6
|
2017-01-18T09:53:13.000Z
|
2019-01-25T08:15:27.000Z
|
UploadImages/RxQBImagePickerControllerDelegateProxy.swift
|
DianQK/rx-sample-code
|
d121f3f2e63dff7936356923861486755f4833d7
|
[
"MIT"
] | 27
|
2016-09-30T03:03:22.000Z
|
2021-12-21T13:49:52.000Z
|
//
// RxQBImagePickerControllerDelegateProxy.swift
// UploadImageDemo
//
// Created by DianQK on 05/01/2017.
// Copyright © 2017 T. All rights reserved.
//
import UIKit
import QBImagePicker
import RxSwift
import RxCocoa
public class RxQBImagePickerControllerDelegateProxy: DelegateProxy, DelegateProxyType, QBImagePickerControllerDelegate {
/**
For more information take a look at `DelegateProxyType`.
*/
public class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
let imagePickerController = object as? QBImagePickerController
imagePickerController?.delegate = delegate as? QBImagePickerControllerDelegate
}
/**
For more information take a look at `DelegateProxyType`.
*/
public class func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
let imagePickerController = object as? QBImagePickerController
return imagePickerController?.delegate
}
}
| 29.484848
| 120
| 0.738952
|
90d493dc2ee448e2435a1f35ff231e60a2771cdc
| 67,969
|
rs
|
Rust
|
src/types/wlr_xdg_decoration_v1.rs
|
RoastVeg/wlrusts
|
8f86cc8662256916aaa529d36da5ce55e3db93c5
|
[
"MIT"
] | null | null | null |
src/types/wlr_xdg_decoration_v1.rs
|
RoastVeg/wlrusts
|
8f86cc8662256916aaa529d36da5ce55e3db93c5
|
[
"MIT"
] | 1
|
2019-12-10T16:29:26.000Z
|
2019-12-10T16:29:26.000Z
|
src/types/wlr_xdg_decoration_v1.rs
|
RoastVeg/wlrusts
|
8f86cc8662256916aaa529d36da5ce55e3db93c5
|
[
"MIT"
] | null | null | null |
use libc;
extern "C" {
pub type wl_event_source;
pub type wl_display;
/* Generated by wayland-scanner 1.17.0 */
pub type wl_client;
pub type wl_global;
pub type xkb_keymap;
pub type xkb_state;
pub type wlr_keyboard_impl;
pub type wlr_keyboard_group;
pub type wlr_texture;
pub type wlr_renderer;
pub type wlr_backend;
pub type wlr_output_impl;
pub type wlr_data_source;
pub type wlr_drag;
pub type wlr_primary_selection_source;
#[no_mangle]
fn __assert_fail(__assertion: *const libc::c_char,
__file: *const libc::c_char, __line: libc::c_uint,
__function: *const libc::c_char) -> !;
#[no_mangle]
fn calloc(_: libc::c_ulong, _: libc::c_ulong) -> *mut libc::c_void;
#[no_mangle]
fn free(__ptr: *mut libc::c_void);
#[no_mangle]
fn wlr_xdg_surface_schedule_configure(surface: *mut wlr_xdg_surface)
-> uint32_t;
#[no_mangle]
fn wlr_xdg_surface_from_toplevel_resource(resource: *mut wl_resource)
-> *mut wlr_xdg_surface;
#[no_mangle]
fn wlr_surface_has_buffer(surface: *mut wlr_surface) -> bool;
#[no_mangle]
fn wl_list_init(list: *mut wl_list);
#[no_mangle]
fn wl_list_insert(list: *mut wl_list, elm: *mut wl_list);
#[no_mangle]
fn wl_list_remove(elm: *mut wl_list);
#[no_mangle]
fn wl_display_add_destroy_listener(display: *mut wl_display,
listener: *mut wl_listener);
#[no_mangle]
fn wl_global_create(display: *mut wl_display,
interface: *const wl_interface, version: libc::c_int,
data: *mut libc::c_void, bind: wl_global_bind_func_t)
-> *mut wl_global;
#[no_mangle]
fn wl_global_destroy(global: *mut wl_global);
#[no_mangle]
fn wl_client_post_no_memory(client: *mut wl_client);
#[no_mangle]
fn wl_resource_post_event(resource: *mut wl_resource, opcode: uint32_t,
_: ...);
#[no_mangle]
fn wl_resource_post_error(resource: *mut wl_resource, code: uint32_t,
msg: *const libc::c_char, _: ...);
#[no_mangle]
fn wl_resource_create(client: *mut wl_client,
interface: *const wl_interface,
version: libc::c_int, id: uint32_t)
-> *mut wl_resource;
#[no_mangle]
fn wl_resource_set_implementation(resource: *mut wl_resource,
implementation: *const libc::c_void,
data: *mut libc::c_void,
destroy: wl_resource_destroy_func_t);
#[no_mangle]
fn wl_resource_destroy(resource: *mut wl_resource);
#[no_mangle]
fn wl_resource_get_user_data(resource: *mut wl_resource)
-> *mut libc::c_void;
#[no_mangle]
fn wl_resource_get_version(resource: *mut wl_resource) -> libc::c_int;
#[no_mangle]
fn wl_resource_instance_of(resource: *mut wl_resource,
interface: *const wl_interface,
implementation: *const libc::c_void)
-> libc::c_int;
/*
* This is a stable interface of wlroots. Future changes will be limited to:
*
* - New functions
* - New struct members
* - New enum members
*
* Note that wlroots does not make an ABI compatibility promise - in the future,
* the layout and size of structs used by wlroots may change, requiring code
* depending on this header to be recompiled (but not edited).
*
* Breaking changes are announced by email and follow a 1-year deprecation
* schedule. Send an email to ~sircmpwn/wlroots-announce+subscribe@lists.sr.ht
* to receive these announcements.
*/
// Will log all messages less than or equal to `verbosity`
// If `callback` is NULL, wlr will use its default logger.
// The function can be called multiple times to update the verbosity or
// callback function.
// Returns the log verbosity provided to wlr_log_init
#[no_mangle]
fn _wlr_log(verbosity: wlr_log_importance, format: *const libc::c_char,
_: ...);
#[no_mangle]
fn wlr_signal_emit_safe(signal: *mut wl_signal, data: *mut libc::c_void);
/* *
* @page page_iface_zxdg_decoration_manager_v1 zxdg_decoration_manager_v1
* @section page_iface_zxdg_decoration_manager_v1_desc Description
*
* This interface allows a compositor to announce support for server-side
* decorations.
*
* A window decoration is a set of window controls as deemed appropriate by
* the party managing them, such as user interface components used to move,
* resize and change a window's state.
*
* A client can use this protocol to request being decorated by a supporting
* compositor.
*
* If compositor and client do not negotiate the use of a server-side
* decoration using this protocol, clients continue to self-decorate as they
* see fit.
*
* Warning! The protocol described in this file is experimental and
* backward incompatible changes may be made. Backward compatible changes
* may be added together with the corresponding interface version bump.
* Backward incompatible changes are done by bumping the version number in
* the protocol and interface names and resetting the interface version.
* Once the protocol is to be declared stable, the 'z' prefix and the
* version number in the protocol and interface names are removed and the
* interface version number is reset.
* @section page_iface_zxdg_decoration_manager_v1_api API
* See @ref iface_zxdg_decoration_manager_v1.
*/
/* *
* @defgroup iface_zxdg_decoration_manager_v1 The zxdg_decoration_manager_v1 interface
*
* This interface allows a compositor to announce support for server-side
* decorations.
*
* A window decoration is a set of window controls as deemed appropriate by
* the party managing them, such as user interface components used to move,
* resize and change a window's state.
*
* A client can use this protocol to request being decorated by a supporting
* compositor.
*
* If compositor and client do not negotiate the use of a server-side
* decoration using this protocol, clients continue to self-decorate as they
* see fit.
*
* Warning! The protocol described in this file is experimental and
* backward incompatible changes may be made. Backward compatible changes
* may be added together with the corresponding interface version bump.
* Backward incompatible changes are done by bumping the version number in
* the protocol and interface names and resetting the interface version.
* Once the protocol is to be declared stable, the 'z' prefix and the
* version number in the protocol and interface names are removed and the
* interface version number is reset.
*/
#[no_mangle]
static zxdg_decoration_manager_v1_interface: wl_interface;
/* *
* @page page_iface_zxdg_toplevel_decoration_v1 zxdg_toplevel_decoration_v1
* @section page_iface_zxdg_toplevel_decoration_v1_desc Description
*
* The decoration object allows the compositor to toggle server-side window
* decorations for a toplevel surface. The client can request to switch to
* another mode.
*
* The xdg_toplevel_decoration object must be destroyed before its
* xdg_toplevel.
* @section page_iface_zxdg_toplevel_decoration_v1_api API
* See @ref iface_zxdg_toplevel_decoration_v1.
*/
/* *
* @defgroup iface_zxdg_toplevel_decoration_v1 The zxdg_toplevel_decoration_v1 interface
*
* The decoration object allows the compositor to toggle server-side window
* decorations for a toplevel surface. The client can request to switch to
* another mode.
*
* The xdg_toplevel_decoration object must be destroyed before its
* xdg_toplevel.
*/
#[no_mangle]
static zxdg_toplevel_decoration_v1_interface: wl_interface;
}
pub type size_t = libc::c_ulong;
pub type __int32_t = libc::c_int;
pub type __uint32_t = libc::c_uint;
pub type __time_t = libc::c_long;
pub type __syscall_slong_t = libc::c_long;
pub type int32_t = __int32_t;
pub type uint32_t = __uint32_t;
#[repr(C)]#[derive(Copy, Clone)]
pub struct wl_object {
pub interface: *const wl_interface,
pub implementation: *const libc::c_void,
pub id: uint32_t,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wl_interface {
pub name: *const libc::c_char,
pub version: libc::c_int,
pub method_count: libc::c_int,
pub methods: *const wl_message,
pub event_count: libc::c_int,
pub events: *const wl_message,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wl_message {
pub name: *const libc::c_char,
pub signature: *const libc::c_char,
pub types: *mut *const wl_interface,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wl_list {
pub prev: *mut wl_list,
pub next: *mut wl_list,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wl_listener {
pub link: wl_list,
pub notify: wl_notify_func_t,
}
pub type wl_notify_func_t
=
Option<unsafe extern "C" fn(_: *mut wl_listener, _: *mut libc::c_void)
-> ()>;
pub type wl_global_bind_func_t
=
Option<unsafe extern "C" fn(_: *mut wl_client, _: *mut libc::c_void,
_: uint32_t, _: uint32_t) -> ()>;
#[repr(C)]#[derive(Copy, Clone)]
pub struct wl_resource {
pub object: wl_object,
pub destroy: wl_resource_destroy_func_t,
pub link: wl_list,
pub destroy_signal: wl_signal,
pub client: *mut wl_client,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wl_signal {
pub listener_list: wl_list,
}
pub type wl_resource_destroy_func_t
=
Option<unsafe extern "C" fn(_: *mut wl_resource) -> ()>;
#[repr(C)]#[derive(Copy, Clone)]
pub struct pixman_region32_data {
pub size: libc::c_long,
pub numRects: libc::c_long,
}
pub type pixman_region32_data_t = pixman_region32_data;
#[repr(C)]#[derive(Copy, Clone)]
pub struct pixman_box32 {
pub x1: int32_t,
pub y1: int32_t,
pub x2: int32_t,
pub y2: int32_t,
}
pub type pixman_box32_t = pixman_box32;
#[repr(C)]#[derive(Copy, Clone)]
pub struct pixman_region32 {
pub extents: pixman_box32_t,
pub data: *mut pixman_region32_data_t,
}
pub type pixman_region32_t = pixman_region32;
pub type wl_output_subpixel = libc::c_uint;
pub const WL_OUTPUT_SUBPIXEL_VERTICAL_BGR: wl_output_subpixel = 5;
pub const WL_OUTPUT_SUBPIXEL_VERTICAL_RGB: wl_output_subpixel = 4;
pub const WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR: wl_output_subpixel = 3;
pub const WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB: wl_output_subpixel = 2;
pub const WL_OUTPUT_SUBPIXEL_NONE: wl_output_subpixel = 1;
pub const WL_OUTPUT_SUBPIXEL_UNKNOWN: wl_output_subpixel = 0;
pub type wl_output_transform = libc::c_uint;
pub const WL_OUTPUT_TRANSFORM_FLIPPED_270: wl_output_transform = 7;
pub const WL_OUTPUT_TRANSFORM_FLIPPED_180: wl_output_transform = 6;
pub const WL_OUTPUT_TRANSFORM_FLIPPED_90: wl_output_transform = 5;
pub const WL_OUTPUT_TRANSFORM_FLIPPED: wl_output_transform = 4;
pub const WL_OUTPUT_TRANSFORM_270: wl_output_transform = 3;
pub const WL_OUTPUT_TRANSFORM_180: wl_output_transform = 2;
pub const WL_OUTPUT_TRANSFORM_90: wl_output_transform = 1;
pub const WL_OUTPUT_TRANSFORM_NORMAL: wl_output_transform = 0;
/*
* This an unstable interface of wlroots. No guarantees are made regarding the
* future consistency of this API.
*/
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_box {
pub x: libc::c_int,
pub y: libc::c_int,
pub width: libc::c_int,
pub height: libc::c_int,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct timespec {
pub tv_sec: __time_t,
pub tv_nsec: __syscall_slong_t,
}
pub type wlr_button_state = libc::c_uint;
pub const WLR_BUTTON_PRESSED: wlr_button_state = 1;
pub const WLR_BUTTON_RELEASED: wlr_button_state = 0;
pub type xkb_mod_index_t = uint32_t;
pub type xkb_mod_mask_t = uint32_t;
pub type xkb_led_index_t = uint32_t;
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_keyboard_modifiers {
pub depressed: xkb_mod_mask_t,
pub latched: xkb_mod_mask_t,
pub locked: xkb_mod_mask_t,
pub group: xkb_mod_mask_t,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_keyboard {
pub impl_0: *const crate::src::backend::headless::input_device::wlr_keyboard_impl,
pub group: *mut crate::src::types::wlr_keyboard_group::wlr_keyboard_group,
pub keymap_string: *mut libc::c_char,
pub keymap_size: size_t,
pub keymap: *mut xkb_keymap,
pub xkb_state: *mut xkb_state,
pub led_indexes: [xkb_led_index_t; 3],
pub mod_indexes: [xkb_mod_index_t; 8],
pub keycodes: [uint32_t; 32],
pub num_keycodes: size_t,
pub modifiers: wlr_keyboard_modifiers,
pub repeat_info: C2RustUnnamed_0,
pub events: C2RustUnnamed,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed {
pub key: wl_signal,
pub modifiers: wl_signal,
pub keymap: wl_signal,
pub repeat_info: wl_signal,
pub destroy: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_0 {
pub rate: int32_t,
pub delay: int32_t,
}
pub type wlr_axis_source = libc::c_uint;
pub const WLR_AXIS_SOURCE_WHEEL_TILT: wlr_axis_source = 3;
pub const WLR_AXIS_SOURCE_CONTINUOUS: wlr_axis_source = 2;
pub const WLR_AXIS_SOURCE_FINGER: wlr_axis_source = 1;
pub const WLR_AXIS_SOURCE_WHEEL: wlr_axis_source = 0;
pub type wlr_axis_orientation = libc::c_uint;
pub const WLR_AXIS_ORIENTATION_HORIZONTAL: wlr_axis_orientation = 1;
pub const WLR_AXIS_ORIENTATION_VERTICAL: wlr_axis_orientation = 0;
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_buffer {
pub resource: *mut wl_resource,
pub texture: *mut crate::src::backend::drm::atomic::wlr_texture,
pub released: bool,
pub n_refs: size_t,
pub resource_destroy: wl_listener,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_output_mode {
pub width: int32_t,
pub height: int32_t,
pub refresh: int32_t,
pub preferred: bool,
pub link: wl_list,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_output_cursor {
pub output: *mut wlr_output,
pub x: libc::c_double,
pub y: libc::c_double,
pub enabled: bool,
pub visible: bool,
pub width: uint32_t,
pub height: uint32_t,
pub hotspot_x: int32_t,
pub hotspot_y: int32_t,
pub link: wl_list,
pub texture: *mut crate::src::backend::drm::atomic::wlr_texture,
pub surface: *mut wlr_surface,
pub surface_commit: wl_listener,
pub surface_destroy: wl_listener,
pub events: C2RustUnnamed_1,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_1 {
pub destroy: wl_signal,
}
/*
* This an unstable interface of wlroots. No guarantees are made regarding the
* future consistency of this API.
*/
// mHz
// only when using a software cursor without a surface
// only when using a cursor surface
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_surface {
pub resource: *mut wl_resource,
pub renderer: *mut crate::src::backend::drm::atomic::wlr_renderer,
pub buffer: *mut wlr_buffer,
pub sx: libc::c_int,
pub sy: libc::c_int,
pub buffer_damage: pixman_region32_t,
pub opaque_region: pixman_region32_t,
pub input_region: pixman_region32_t,
pub current: wlr_surface_state,
pub pending: wlr_surface_state,
pub previous: wlr_surface_state,
pub role: *const wlr_surface_role,
pub role_data: *mut libc::c_void,
pub events: C2RustUnnamed_2,
pub subsurfaces: wl_list,
pub subsurface_pending_list: wl_list,
pub renderer_destroy: wl_listener,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_2 {
pub commit: wl_signal,
pub new_subsurface: wl_signal,
pub destroy: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_surface_role {
pub name: *const libc::c_char,
pub commit: Option<unsafe extern "C" fn(_: *mut wlr_surface) -> ()>,
pub precommit: Option<unsafe extern "C" fn(_: *mut wlr_surface) -> ()>,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_surface_state {
pub committed: uint32_t,
pub buffer_resource: *mut wl_resource,
pub dx: int32_t,
pub dy: int32_t,
pub surface_damage: pixman_region32_t,
pub buffer_damage: pixman_region32_t,
pub opaque: pixman_region32_t,
pub input: pixman_region32_t,
pub transform: wl_output_transform,
pub scale: int32_t,
pub frame_callback_list: wl_list,
pub width: libc::c_int,
pub height: libc::c_int,
pub buffer_width: libc::c_int,
pub buffer_height: libc::c_int,
pub buffer_destroy: wl_listener,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_output {
pub impl_0: *const crate::src::backend::drm::backend::wlr_output_impl,
pub backend: *mut crate::src::backend::backend::wlr_backend,
pub display: *mut wl_display,
pub global: *mut wl_global,
pub resources: wl_list,
pub name: [libc::c_char; 24],
pub make: [libc::c_char; 56],
pub model: [libc::c_char; 16],
pub serial: [libc::c_char; 16],
pub phys_width: int32_t,
pub phys_height: int32_t,
pub modes: wl_list,
pub current_mode: *mut wlr_output_mode,
pub width: int32_t,
pub height: int32_t,
pub refresh: int32_t,
pub enabled: bool,
pub scale: libc::c_float,
pub subpixel: wl_output_subpixel,
pub transform: wl_output_transform,
pub needs_frame: bool,
pub damage: pixman_region32_t,
pub frame_pending: bool,
pub transform_matrix: [libc::c_float; 9],
pub pending: wlr_output_state,
pub commit_seq: uint32_t,
pub events: C2RustUnnamed_3,
pub idle_frame: *mut wl_event_source,
pub idle_done: *mut wl_event_source,
pub attach_render_locks: libc::c_int,
pub cursors: wl_list,
pub hardware_cursor: *mut wlr_output_cursor,
pub software_cursor_locks: libc::c_int,
pub display_destroy: wl_listener,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_3 {
pub frame: wl_signal,
pub needs_frame: wl_signal,
pub precommit: wl_signal,
pub commit: wl_signal,
pub present: wl_signal,
pub enable: wl_signal,
pub mode: wl_signal,
pub scale: wl_signal,
pub transform: wl_signal,
pub destroy: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_output_state {
pub committed: uint32_t,
pub damage: pixman_region32_t,
pub buffer_type: wlr_output_state_buffer_type,
pub buffer: *mut wlr_buffer,
}
pub type wlr_output_state_buffer_type = libc::c_uint;
pub const WLR_OUTPUT_STATE_BUFFER_SCANOUT: wlr_output_state_buffer_type = 1;
pub const WLR_OUTPUT_STATE_BUFFER_RENDER: wlr_output_state_buffer_type = 0;
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_serial_range {
pub min_incl: uint32_t,
pub max_incl: uint32_t,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_serial_ringset {
pub data: [wlr_serial_range; 128],
pub end: libc::c_int,
pub count: libc::c_int,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat_client {
pub client: *mut wl_client,
pub seat: *mut wlr_seat,
pub link: wl_list,
pub resources: wl_list,
pub pointers: wl_list,
pub keyboards: wl_list,
pub touches: wl_list,
pub data_devices: wl_list,
pub events: C2RustUnnamed_4,
pub serials: wlr_serial_ringset,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_4 {
pub destroy: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat {
pub global: *mut wl_global,
pub display: *mut wl_display,
pub clients: wl_list,
pub name: *mut libc::c_char,
pub capabilities: uint32_t,
pub last_event: timespec,
pub selection_source: *mut crate::src::types::data_device::wlr_data_device::wlr_data_source,
pub selection_serial: uint32_t,
pub selection_offers: wl_list,
pub primary_selection_source: *mut crate::src::types::wlr_data_control_v1::wlr_primary_selection_source,
pub primary_selection_serial: uint32_t,
pub drag: *mut crate::src::types::data_device::wlr_data_device::wlr_drag,
pub drag_source: *mut crate::src::types::data_device::wlr_data_device::wlr_data_source,
pub drag_serial: uint32_t,
pub drag_offers: wl_list,
pub pointer_state: wlr_seat_pointer_state,
pub keyboard_state: wlr_seat_keyboard_state,
pub touch_state: wlr_seat_touch_state,
pub display_destroy: wl_listener,
pub selection_source_destroy: wl_listener,
pub primary_selection_source_destroy: wl_listener,
pub drag_source_destroy: wl_listener,
pub events: C2RustUnnamed_5,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_5 {
pub pointer_grab_begin: wl_signal,
pub pointer_grab_end: wl_signal,
pub keyboard_grab_begin: wl_signal,
pub keyboard_grab_end: wl_signal,
pub touch_grab_begin: wl_signal,
pub touch_grab_end: wl_signal,
pub request_set_cursor: wl_signal,
pub request_set_selection: wl_signal,
pub set_selection: wl_signal,
pub request_set_primary_selection: wl_signal,
pub set_primary_selection: wl_signal,
pub request_start_drag: wl_signal,
pub start_drag: wl_signal,
pub destroy: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat_touch_state {
pub seat: *mut wlr_seat,
pub touch_points: wl_list,
pub grab_serial: uint32_t,
pub grab_id: uint32_t,
pub grab: *mut wlr_seat_touch_grab,
pub default_grab: *mut wlr_seat_touch_grab,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat_touch_grab {
pub interface: *const wlr_touch_grab_interface,
pub seat: *mut wlr_seat,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_touch_grab_interface {
pub down: Option<unsafe extern "C" fn(_: *mut wlr_seat_touch_grab,
_: uint32_t,
_: *mut wlr_touch_point)
-> uint32_t>,
pub up: Option<unsafe extern "C" fn(_: *mut wlr_seat_touch_grab,
_: uint32_t, _: *mut wlr_touch_point)
-> ()>,
pub motion: Option<unsafe extern "C" fn(_: *mut wlr_seat_touch_grab,
_: uint32_t,
_: *mut wlr_touch_point) -> ()>,
pub enter: Option<unsafe extern "C" fn(_: *mut wlr_seat_touch_grab,
_: uint32_t,
_: *mut wlr_touch_point) -> ()>,
pub cancel: Option<unsafe extern "C" fn(_: *mut wlr_seat_touch_grab)
-> ()>,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_touch_point {
pub touch_id: int32_t,
pub surface: *mut wlr_surface,
pub client: *mut wlr_seat_client,
pub focus_surface: *mut wlr_surface,
pub focus_client: *mut wlr_seat_client,
pub sx: libc::c_double,
pub sy: libc::c_double,
pub surface_destroy: wl_listener,
pub focus_surface_destroy: wl_listener,
pub client_destroy: wl_listener,
pub events: C2RustUnnamed_6,
pub link: wl_list,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_6 {
pub destroy: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat_keyboard_state {
pub seat: *mut wlr_seat,
pub keyboard: *mut wlr_keyboard,
pub focused_client: *mut wlr_seat_client,
pub focused_surface: *mut wlr_surface,
pub keyboard_destroy: wl_listener,
pub keyboard_keymap: wl_listener,
pub keyboard_repeat_info: wl_listener,
pub surface_destroy: wl_listener,
pub grab: *mut wlr_seat_keyboard_grab,
pub default_grab: *mut wlr_seat_keyboard_grab,
pub events: C2RustUnnamed_7,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_7 {
pub focus_change: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat_keyboard_grab {
pub interface: *const wlr_keyboard_grab_interface,
pub seat: *mut wlr_seat,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_keyboard_grab_interface {
pub enter: Option<unsafe extern "C" fn(_: *mut wlr_seat_keyboard_grab,
_: *mut wlr_surface,
_: *mut uint32_t, _: size_t,
_: *mut wlr_keyboard_modifiers)
-> ()>,
pub key: Option<unsafe extern "C" fn(_: *mut wlr_seat_keyboard_grab,
_: uint32_t, _: uint32_t,
_: uint32_t) -> ()>,
pub modifiers: Option<unsafe extern "C" fn(_: *mut wlr_seat_keyboard_grab,
_: *mut wlr_keyboard_modifiers)
-> ()>,
pub cancel: Option<unsafe extern "C" fn(_: *mut wlr_seat_keyboard_grab)
-> ()>,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat_pointer_state {
pub seat: *mut wlr_seat,
pub focused_client: *mut wlr_seat_client,
pub focused_surface: *mut wlr_surface,
pub sx: libc::c_double,
pub sy: libc::c_double,
pub grab: *mut wlr_seat_pointer_grab,
pub default_grab: *mut wlr_seat_pointer_grab,
pub buttons: [uint32_t; 16],
pub button_count: size_t,
pub grab_button: uint32_t,
pub grab_serial: uint32_t,
pub grab_time: uint32_t,
pub surface_destroy: wl_listener,
pub events: C2RustUnnamed_8,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_8 {
pub focus_change: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_seat_pointer_grab {
pub interface: *const wlr_pointer_grab_interface,
pub seat: *mut wlr_seat,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_pointer_grab_interface {
pub enter: Option<unsafe extern "C" fn(_: *mut wlr_seat_pointer_grab,
_: *mut wlr_surface,
_: libc::c_double,
_: libc::c_double) -> ()>,
pub motion: Option<unsafe extern "C" fn(_: *mut wlr_seat_pointer_grab,
_: uint32_t, _: libc::c_double,
_: libc::c_double) -> ()>,
pub button: Option<unsafe extern "C" fn(_: *mut wlr_seat_pointer_grab,
_: uint32_t, _: uint32_t,
_: wlr_button_state) -> uint32_t>,
pub axis: Option<unsafe extern "C" fn(_: *mut wlr_seat_pointer_grab,
_: uint32_t,
_: wlr_axis_orientation,
_: libc::c_double, _: int32_t,
_: wlr_axis_source) -> ()>,
pub frame: Option<unsafe extern "C" fn(_: *mut wlr_seat_pointer_grab)
-> ()>,
pub cancel: Option<unsafe extern "C" fn(_: *mut wlr_seat_pointer_grab)
-> ()>,
}
pub type xdg_positioner_anchor = libc::c_uint;
pub const XDG_POSITIONER_ANCHOR_BOTTOM_RIGHT: xdg_positioner_anchor = 8;
pub const XDG_POSITIONER_ANCHOR_TOP_RIGHT: xdg_positioner_anchor = 7;
pub const XDG_POSITIONER_ANCHOR_BOTTOM_LEFT: xdg_positioner_anchor = 6;
pub const XDG_POSITIONER_ANCHOR_TOP_LEFT: xdg_positioner_anchor = 5;
pub const XDG_POSITIONER_ANCHOR_RIGHT: xdg_positioner_anchor = 4;
pub const XDG_POSITIONER_ANCHOR_LEFT: xdg_positioner_anchor = 3;
pub const XDG_POSITIONER_ANCHOR_BOTTOM: xdg_positioner_anchor = 2;
pub const XDG_POSITIONER_ANCHOR_TOP: xdg_positioner_anchor = 1;
pub const XDG_POSITIONER_ANCHOR_NONE: xdg_positioner_anchor = 0;
pub type xdg_positioner_gravity = libc::c_uint;
pub const XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT: xdg_positioner_gravity = 8;
pub const XDG_POSITIONER_GRAVITY_TOP_RIGHT: xdg_positioner_gravity = 7;
pub const XDG_POSITIONER_GRAVITY_BOTTOM_LEFT: xdg_positioner_gravity = 6;
pub const XDG_POSITIONER_GRAVITY_TOP_LEFT: xdg_positioner_gravity = 5;
pub const XDG_POSITIONER_GRAVITY_RIGHT: xdg_positioner_gravity = 4;
pub const XDG_POSITIONER_GRAVITY_LEFT: xdg_positioner_gravity = 3;
pub const XDG_POSITIONER_GRAVITY_BOTTOM: xdg_positioner_gravity = 2;
pub const XDG_POSITIONER_GRAVITY_TOP: xdg_positioner_gravity = 1;
pub const XDG_POSITIONER_GRAVITY_NONE: xdg_positioner_gravity = 0;
pub type xdg_positioner_constraint_adjustment = libc::c_uint;
pub const XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y:
xdg_positioner_constraint_adjustment =
32;
pub const XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X:
xdg_positioner_constraint_adjustment =
16;
pub const XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_Y:
xdg_positioner_constraint_adjustment =
8;
pub const XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_X:
xdg_positioner_constraint_adjustment =
4;
pub const XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y:
xdg_positioner_constraint_adjustment =
2;
pub const XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X:
xdg_positioner_constraint_adjustment =
1;
pub const XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_NONE:
xdg_positioner_constraint_adjustment =
0;
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_shell {
pub global: *mut wl_global,
pub clients: wl_list,
pub popup_grabs: wl_list,
pub ping_timeout: uint32_t,
pub display_destroy: wl_listener,
pub events: C2RustUnnamed_9,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_9 {
pub new_surface: wl_signal,
pub destroy: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_client {
pub shell: *mut wlr_xdg_shell,
pub resource: *mut wl_resource,
pub client: *mut wl_client,
pub surfaces: wl_list,
pub link: wl_list,
pub ping_serial: uint32_t,
pub ping_timer: *mut wl_event_source,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_positioner {
pub resource: *mut wl_resource,
pub anchor_rect: wlr_box,
pub anchor: xdg_positioner_anchor,
pub gravity: xdg_positioner_gravity,
pub constraint_adjustment: xdg_positioner_constraint_adjustment,
pub size: C2RustUnnamed_11,
pub offset: C2RustUnnamed_10,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_10 {
pub x: int32_t,
pub y: int32_t,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_11 {
pub width: int32_t,
pub height: int32_t,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_popup {
pub base: *mut wlr_xdg_surface,
pub link: wl_list,
pub resource: *mut wl_resource,
pub committed: bool,
pub parent: *mut wlr_surface,
pub seat: *mut wlr_seat,
pub geometry: wlr_box,
pub positioner: wlr_xdg_positioner,
pub grab_link: wl_list,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_surface {
pub client: *mut wlr_xdg_client,
pub resource: *mut wl_resource,
pub surface: *mut wlr_surface,
pub link: wl_list,
pub role: wlr_xdg_surface_role,
pub c2rust_unnamed: C2RustUnnamed_13,
pub popups: wl_list,
pub added: bool,
pub configured: bool,
pub mapped: bool,
pub configure_serial: uint32_t,
pub configure_idle: *mut wl_event_source,
pub configure_next_serial: uint32_t,
pub configure_list: wl_list,
pub has_next_geometry: bool,
pub next_geometry: wlr_box,
pub geometry: wlr_box,
pub surface_destroy: wl_listener,
pub surface_commit: wl_listener,
pub events: C2RustUnnamed_12,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_12 {
pub destroy: wl_signal,
pub ping_timeout: wl_signal,
pub new_popup: wl_signal,
pub map: wl_signal,
pub unmap: wl_signal,
pub configure: wl_signal,
pub ack_configure: wl_signal,
}
#[repr ( C )]#[derive(Copy, Clone)]
pub union C2RustUnnamed_13 {
pub toplevel: *mut wlr_xdg_toplevel,
pub popup: *mut wlr_xdg_popup,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_toplevel {
pub resource: *mut wl_resource,
pub base: *mut wlr_xdg_surface,
pub added: bool,
pub parent: *mut wlr_xdg_surface,
pub parent_unmap: wl_listener,
pub client_pending: wlr_xdg_toplevel_state,
pub server_pending: wlr_xdg_toplevel_state,
pub current: wlr_xdg_toplevel_state,
pub title: *mut libc::c_char,
pub app_id: *mut libc::c_char,
pub events: C2RustUnnamed_14,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_14 {
pub request_maximize: wl_signal,
pub request_fullscreen: wl_signal,
pub request_minimize: wl_signal,
pub request_move: wl_signal,
pub request_resize: wl_signal,
pub request_show_window_menu: wl_signal,
pub set_parent: wl_signal,
pub set_title: wl_signal,
pub set_app_id: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_toplevel_state {
pub maximized: bool,
pub fullscreen: bool,
pub resizing: bool,
pub activated: bool,
pub tiled: uint32_t,
pub width: uint32_t,
pub height: uint32_t,
pub max_width: uint32_t,
pub max_height: uint32_t,
pub min_width: uint32_t,
pub min_height: uint32_t,
pub fullscreen_output: *mut wlr_output,
pub fullscreen_output_destroy: wl_listener,
}
pub type wlr_xdg_surface_role = libc::c_uint;
pub const WLR_XDG_SURFACE_ROLE_POPUP: wlr_xdg_surface_role = 2;
pub const WLR_XDG_SURFACE_ROLE_TOPLEVEL: wlr_xdg_surface_role = 1;
pub const WLR_XDG_SURFACE_ROLE_NONE: wlr_xdg_surface_role = 0;
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_surface_configure {
pub surface: *mut wlr_xdg_surface,
pub link: wl_list,
pub serial: uint32_t,
pub toplevel_state: *mut wlr_xdg_toplevel_state,
}
pub type wlr_xdg_toplevel_decoration_v1_mode = libc::c_uint;
pub const WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE:
wlr_xdg_toplevel_decoration_v1_mode =
2;
pub const WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE:
wlr_xdg_toplevel_decoration_v1_mode =
1;
pub const WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_NONE:
wlr_xdg_toplevel_decoration_v1_mode =
0;
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_decoration_manager_v1 {
pub global: *mut wl_global,
pub decorations: wl_list,
pub display_destroy: wl_listener,
pub events: C2RustUnnamed_15,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_15 {
pub new_toplevel_decoration: wl_signal,
pub destroy: wl_signal,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_toplevel_decoration_v1_configure {
pub link: wl_list,
pub surface_configure: *mut wlr_xdg_surface_configure,
pub mode: wlr_xdg_toplevel_decoration_v1_mode,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct wlr_xdg_toplevel_decoration_v1 {
pub resource: *mut wl_resource,
pub surface: *mut wlr_xdg_surface,
pub manager: *mut wlr_xdg_decoration_manager_v1,
pub link: wl_list,
pub added: bool,
pub current_mode: wlr_xdg_toplevel_decoration_v1_mode,
pub client_pending_mode: wlr_xdg_toplevel_decoration_v1_mode,
pub server_pending_mode: wlr_xdg_toplevel_decoration_v1_mode,
pub configure_list: wl_list,
pub events: C2RustUnnamed_16,
pub surface_destroy: wl_listener,
pub surface_configure: wl_listener,
pub surface_ack_configure: wl_listener,
pub surface_commit: wl_listener,
pub data: *mut libc::c_void,
}
#[repr(C)]#[derive(Copy, Clone)]
pub struct C2RustUnnamed_16 {
pub destroy: wl_signal,
pub request_mode: wl_signal,
}
/* *
* @ingroup iface_zxdg_decoration_manager_v1
* @struct zxdg_decoration_manager_v1_interface
*/
#[repr(C)]#[derive(Copy, Clone)]
pub struct zxdg_decoration_manager_v1_interface {
pub destroy: Option<unsafe extern "C" fn(_: *mut wl_client,
_: *mut wl_resource) -> ()>,
pub get_toplevel_decoration: Option<unsafe extern "C" fn(_:
*mut wl_client,
_:
*mut wl_resource,
_: uint32_t,
_:
*mut wl_resource)
-> ()>,
}
pub type wlr_log_importance = libc::c_uint;
pub const WLR_LOG_IMPORTANCE_LAST: wlr_log_importance = 4;
pub const WLR_DEBUG: wlr_log_importance = 3;
pub const WLR_INFO: wlr_log_importance = 2;
pub const WLR_ERROR: wlr_log_importance = 1;
pub const WLR_SILENT: wlr_log_importance = 0;
/* ZXDG_TOPLEVEL_DECORATION_V1_MODE_ENUM */
/* *
* @ingroup iface_zxdg_toplevel_decoration_v1
* @struct zxdg_toplevel_decoration_v1_interface
*/
#[repr(C)]#[derive(Copy, Clone)]
pub struct zxdg_toplevel_decoration_v1_interface {
pub destroy: Option<unsafe extern "C" fn(_: *mut wl_client,
_: *mut wl_resource) -> ()>,
pub set_mode: Option<unsafe extern "C" fn(_: *mut wl_client,
_: *mut wl_resource,
_: uint32_t) -> ()>,
pub unset_mode: Option<unsafe extern "C" fn(_: *mut wl_client,
_: *mut wl_resource) -> ()>,
}
/* ZXDG_TOPLEVEL_DECORATION_V1_ERROR_ENUM */
/* *
* @ingroup iface_zxdg_toplevel_decoration_v1
* window decoration modes
*
* These values describe window decoration modes.
*/
pub type zxdg_toplevel_decoration_v1_mode = libc::c_uint;
/* *
* server-side window decoration
*/
pub const ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE:
zxdg_toplevel_decoration_v1_mode =
2;
/* *
* no server-side window decoration
*/
pub const ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE:
zxdg_toplevel_decoration_v1_mode =
1;
/* *
* xdg_toplevel has a buffer attached before configure
*/
pub const ZXDG_TOPLEVEL_DECORATION_V1_ERROR_UNCONFIGURED_BUFFER:
zxdg_toplevel_decoration_v1_error =
0;
/* *
* @ingroup iface_zxdg_decoration_manager_v1
*/
/* *
* @ingroup iface_zxdg_decoration_manager_v1
*/
pub type zxdg_toplevel_decoration_v1_error = libc::c_uint;
/* *
* xdg_toplevel destroyed before the decoration object
*/
pub const ZXDG_TOPLEVEL_DECORATION_V1_ERROR_ORPHANED:
zxdg_toplevel_decoration_v1_error =
2;
/* *
* xdg_toplevel already has a decoration object
*/
pub const ZXDG_TOPLEVEL_DECORATION_V1_ERROR_ALREADY_CONSTRUCTED:
zxdg_toplevel_decoration_v1_error =
1;
#[inline]
unsafe extern "C" fn wl_signal_init(mut signal: *mut wl_signal) {
wl_list_init(&mut (*signal).listener_list);
}
#[inline]
unsafe extern "C" fn wl_signal_add(mut signal: *mut wl_signal,
mut listener: *mut wl_listener) {
wl_list_insert((*signal).listener_list.prev, &mut (*listener).link);
}
/* *
* @ingroup iface_zxdg_toplevel_decoration_v1
*/
/* *
* @ingroup iface_zxdg_toplevel_decoration_v1
*/
/* *
* @ingroup iface_zxdg_toplevel_decoration_v1
*/
/* *
* @ingroup iface_zxdg_toplevel_decoration_v1
*/
/* *
* @ingroup iface_zxdg_toplevel_decoration_v1
* Sends an configure event to the client owning the resource.
* @param resource_ The client's resource
* @param mode the decoration mode
*/
#[inline]
unsafe extern "C" fn zxdg_toplevel_decoration_v1_send_configure(mut resource_:
*mut wl_resource,
mut mode:
uint32_t) {
wl_resource_post_event(resource_, 0i32 as uint32_t, mode);
}
unsafe extern "C" fn toplevel_decoration_from_resource(mut resource:
*mut wl_resource)
-> *mut wlr_xdg_toplevel_decoration_v1 {
if wl_resource_instance_of(resource,
&zxdg_toplevel_decoration_v1_interface,
&toplevel_decoration_impl as
*const zxdg_toplevel_decoration_v1_interface
as *const libc::c_void) != 0 {
} else {
__assert_fail(b"wl_resource_instance_of(resource, &zxdg_toplevel_decoration_v1_interface, &toplevel_decoration_impl)\x00"
as *const u8 as *const libc::c_char,
b"../types/wlr_xdg_decoration_v1.c\x00" as *const u8 as
*const libc::c_char, 17i32 as libc::c_uint,
(*::std::mem::transmute::<&[u8; 95],
&[libc::c_char; 95]>(b"struct wlr_xdg_toplevel_decoration_v1 *toplevel_decoration_from_resource(struct wl_resource *)\x00")).as_ptr());
};
return wl_resource_get_user_data(resource) as
*mut wlr_xdg_toplevel_decoration_v1;
}
unsafe extern "C" fn toplevel_decoration_handle_destroy(mut client:
*mut wl_client,
mut resource:
*mut wl_resource) {
wl_resource_destroy(resource);
}
unsafe extern "C" fn toplevel_decoration_handle_set_mode(mut client:
*mut wl_client,
mut resource:
*mut wl_resource,
mut mode:
zxdg_toplevel_decoration_v1_mode) {
let mut decoration: *mut wlr_xdg_toplevel_decoration_v1 =
toplevel_decoration_from_resource(resource);
(*decoration).client_pending_mode =
mode as wlr_xdg_toplevel_decoration_v1_mode;
wlr_signal_emit_safe(&mut (*decoration).events.request_mode,
decoration as *mut libc::c_void);
}
unsafe extern "C" fn toplevel_decoration_handle_unset_mode(mut client:
*mut wl_client,
mut resource:
*mut wl_resource) {
let mut decoration: *mut wlr_xdg_toplevel_decoration_v1 =
toplevel_decoration_from_resource(resource);
(*decoration).client_pending_mode =
WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_NONE;
wlr_signal_emit_safe(&mut (*decoration).events.request_mode,
decoration as *mut libc::c_void);
}
static mut toplevel_decoration_impl: zxdg_toplevel_decoration_v1_interface =
unsafe {
{
let mut init =
zxdg_toplevel_decoration_v1_interface{destroy:
Some(toplevel_decoration_handle_destroy
as
unsafe extern "C" fn(_:
*mut wl_client,
_:
*mut wl_resource)
-> ()),
set_mode:
::std::mem::transmute::<Option<unsafe extern "C" fn(_:
*mut wl_client,
_:
*mut wl_resource,
_:
zxdg_toplevel_decoration_v1_mode)
->
()>,
Option<unsafe extern "C" fn(_:
*mut wl_client,
_:
*mut wl_resource,
_:
uint32_t)
->
()>>(Some(toplevel_decoration_handle_set_mode
as
unsafe extern "C" fn(_:
*mut wl_client,
_:
*mut wl_resource,
_:
zxdg_toplevel_decoration_v1_mode)
->
())),
unset_mode:
Some(toplevel_decoration_handle_unset_mode
as
unsafe extern "C" fn(_:
*mut wl_client,
_:
*mut wl_resource)
->
()),};
init
}
};
#[no_mangle]
pub unsafe extern "C" fn wlr_xdg_toplevel_decoration_v1_set_mode(mut decoration:
*mut wlr_xdg_toplevel_decoration_v1,
mut mode:
wlr_xdg_toplevel_decoration_v1_mode)
-> uint32_t {
if mode as libc::c_uint !=
WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_NONE as libc::c_int as
libc::c_uint {
} else {
__assert_fail(b"mode != WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_NONE\x00"
as *const u8 as *const libc::c_char,
b"../types/wlr_xdg_decoration_v1.c\x00" as *const u8 as
*const libc::c_char, 56i32 as libc::c_uint,
(*::std::mem::transmute::<&[u8; 132],
&[libc::c_char; 132]>(b"uint32_t wlr_xdg_toplevel_decoration_v1_set_mode(struct wlr_xdg_toplevel_decoration_v1 *, enum wlr_xdg_toplevel_decoration_v1_mode)\x00")).as_ptr());
};
(*decoration).server_pending_mode = mode;
return wlr_xdg_surface_schedule_configure((*decoration).surface);
}
unsafe extern "C" fn toplevel_decoration_handle_resource_destroy(mut resource:
*mut wl_resource) {
let mut decoration: *mut wlr_xdg_toplevel_decoration_v1 =
toplevel_decoration_from_resource(resource);
wlr_signal_emit_safe(&mut (*decoration).events.destroy,
decoration as *mut libc::c_void);
wl_list_remove(&mut (*decoration).surface_commit.link);
wl_list_remove(&mut (*decoration).surface_destroy.link);
wl_list_remove(&mut (*decoration).surface_configure.link);
wl_list_remove(&mut (*decoration).surface_ack_configure.link);
let mut configure: *mut wlr_xdg_toplevel_decoration_v1_configure =
0 as *mut wlr_xdg_toplevel_decoration_v1_configure;
let mut tmp: *mut wlr_xdg_toplevel_decoration_v1_configure =
0 as *mut wlr_xdg_toplevel_decoration_v1_configure;
configure =
((*decoration).configure_list.next as *mut libc::c_char).offset(-0) as
*mut wlr_xdg_toplevel_decoration_v1_configure;
tmp =
((*configure).link.next as *mut libc::c_char).offset(-0) as
*mut wlr_xdg_toplevel_decoration_v1_configure;
while &mut (*configure).link as *mut wl_list !=
&mut (*decoration).configure_list as *mut wl_list {
free(configure as *mut libc::c_void);
configure = tmp;
tmp =
((*configure).link.next as *mut libc::c_char).offset(-0) as
*mut wlr_xdg_toplevel_decoration_v1_configure
}
wl_list_remove(&mut (*decoration).link);
free(decoration as *mut libc::c_void);
}
unsafe extern "C" fn toplevel_decoration_handle_surface_destroy(mut listener:
*mut wl_listener,
mut data:
*mut libc::c_void) {
let mut decoration: *mut wlr_xdg_toplevel_decoration_v1 =
(listener as *mut libc::c_char).offset(-104) as
*mut wlr_xdg_toplevel_decoration_v1;
wl_resource_destroy((*decoration).resource);
}
unsafe extern "C" fn toplevel_decoration_handle_surface_configure(mut listener:
*mut wl_listener,
mut data:
*mut libc::c_void) {
let mut decoration: *mut wlr_xdg_toplevel_decoration_v1 =
(listener as *mut libc::c_char).offset(-128) as
*mut wlr_xdg_toplevel_decoration_v1;
let mut surface_configure: *mut wlr_xdg_surface_configure =
data as *mut wlr_xdg_surface_configure;
if (*decoration).current_mode as libc::c_uint ==
(*decoration).server_pending_mode as libc::c_uint {
return
}
let mut configure: *mut wlr_xdg_toplevel_decoration_v1_configure =
calloc(1i32 as libc::c_ulong,
::std::mem::size_of::<wlr_xdg_toplevel_decoration_v1_configure>()
as libc::c_ulong) as
*mut wlr_xdg_toplevel_decoration_v1_configure;
if configure.is_null() { return }
(*configure).surface_configure = surface_configure;
(*configure).mode = (*decoration).server_pending_mode;
wl_list_insert((*decoration).configure_list.prev, &mut (*configure).link);
zxdg_toplevel_decoration_v1_send_configure((*decoration).resource,
(*configure).mode as uint32_t);
}
unsafe extern "C" fn toplevel_decoration_handle_surface_ack_configure(mut listener:
*mut wl_listener,
mut data:
*mut libc::c_void) {
let mut decoration: *mut wlr_xdg_toplevel_decoration_v1 =
(listener as *mut libc::c_char).offset(-152) as
*mut wlr_xdg_toplevel_decoration_v1;
let mut surface_configure: *mut wlr_xdg_surface_configure =
data as *mut wlr_xdg_surface_configure;
let mut found: bool = 0i32 != 0;
let mut configure: *mut wlr_xdg_toplevel_decoration_v1_configure =
0 as *mut wlr_xdg_toplevel_decoration_v1_configure;
configure =
((*decoration).configure_list.next as *mut libc::c_char).offset(-0) as
*mut wlr_xdg_toplevel_decoration_v1_configure;
while &mut (*configure).link as *mut wl_list !=
&mut (*decoration).configure_list as *mut wl_list {
if (*configure).surface_configure == surface_configure {
found = 1i32 != 0;
break ;
} else {
configure =
((*configure).link.next as *mut libc::c_char).offset(-0) as
*mut wlr_xdg_toplevel_decoration_v1_configure
}
}
if !found { return }
(*decoration).current_mode = (*configure).mode;
wl_list_remove(&mut (*configure).link);
free(configure as *mut libc::c_void);
}
unsafe extern "C" fn toplevel_decoration_handle_surface_commit(mut listener:
*mut wl_listener,
mut data:
*mut libc::c_void) {
let mut decoration: *mut wlr_xdg_toplevel_decoration_v1 =
(listener as *mut libc::c_char).offset(-176) as
*mut wlr_xdg_toplevel_decoration_v1;
let mut manager: *mut wlr_xdg_decoration_manager_v1 =
(*decoration).manager;
if (*(*decoration).surface).added {
wl_list_remove(&mut (*decoration).surface_commit.link);
wl_list_init(&mut (*decoration).surface_commit.link);
(*decoration).added = 1i32 != 0;
wlr_signal_emit_safe(&mut (*manager).events.new_toplevel_decoration,
decoration as *mut libc::c_void);
};
}
unsafe extern "C" fn decoration_manager_from_resource(mut resource:
*mut wl_resource)
-> *mut wlr_xdg_decoration_manager_v1 {
if wl_resource_instance_of(resource,
&zxdg_decoration_manager_v1_interface,
&decoration_manager_impl as
*const zxdg_decoration_manager_v1_interface
as *const libc::c_void) != 0 {
} else {
__assert_fail(b"wl_resource_instance_of(resource, &zxdg_decoration_manager_v1_interface, &decoration_manager_impl)\x00"
as *const u8 as *const libc::c_char,
b"../types/wlr_xdg_decoration_v1.c\x00" as *const u8 as
*const libc::c_char, 155i32 as libc::c_uint,
(*::std::mem::transmute::<&[u8; 93],
&[libc::c_char; 93]>(b"struct wlr_xdg_decoration_manager_v1 *decoration_manager_from_resource(struct wl_resource *)\x00")).as_ptr());
};
return wl_resource_get_user_data(resource) as
*mut wlr_xdg_decoration_manager_v1;
}
unsafe extern "C" fn decoration_manager_handle_destroy(mut client:
*mut wl_client,
mut manager_resource:
*mut wl_resource) {
wl_resource_destroy(manager_resource);
}
unsafe extern "C" fn decoration_manager_handle_get_toplevel_decoration(mut client:
*mut wl_client,
mut manager_resource:
*mut wl_resource,
mut id:
uint32_t,
mut toplevel_resource:
*mut wl_resource) {
let mut manager: *mut wlr_xdg_decoration_manager_v1 =
decoration_manager_from_resource(manager_resource);
let mut surface: *mut wlr_xdg_surface =
wlr_xdg_surface_from_toplevel_resource(toplevel_resource);
if (*surface).role as libc::c_uint ==
WLR_XDG_SURFACE_ROLE_TOPLEVEL as libc::c_int as libc::c_uint {
} else {
__assert_fail(b"surface->role == WLR_XDG_SURFACE_ROLE_TOPLEVEL\x00" as
*const u8 as *const libc::c_char,
b"../types/wlr_xdg_decoration_v1.c\x00" as *const u8 as
*const libc::c_char, 171i32 as libc::c_uint,
(*::std::mem::transmute::<&[u8; 129],
&[libc::c_char; 129]>(b"void decoration_manager_handle_get_toplevel_decoration(struct wl_client *, struct wl_resource *, uint32_t, struct wl_resource *)\x00")).as_ptr());
};
if wlr_surface_has_buffer((*surface).surface) {
wl_resource_post_error(manager_resource,
ZXDG_TOPLEVEL_DECORATION_V1_ERROR_UNCONFIGURED_BUFFER
as libc::c_int as uint32_t,
b"xdg_toplevel_decoration must not have a buffer at creation\x00"
as *const u8 as *const libc::c_char);
return
}
let mut decoration: *mut wlr_xdg_toplevel_decoration_v1 =
calloc(1i32 as libc::c_ulong,
::std::mem::size_of::<wlr_xdg_toplevel_decoration_v1>() as
libc::c_ulong) as *mut wlr_xdg_toplevel_decoration_v1;
if decoration.is_null() { wl_client_post_no_memory(client); return }
(*decoration).manager = manager;
(*decoration).surface = surface;
let mut version: uint32_t =
wl_resource_get_version(manager_resource) as uint32_t;
(*decoration).resource =
wl_resource_create(client, &zxdg_toplevel_decoration_v1_interface,
version as libc::c_int, id);
if (*decoration).resource.is_null() {
free(decoration as *mut libc::c_void);
wl_client_post_no_memory(client);
return
}
wl_resource_set_implementation((*decoration).resource,
&toplevel_decoration_impl as
*const zxdg_toplevel_decoration_v1_interface
as *const libc::c_void,
decoration as *mut libc::c_void,
Some(toplevel_decoration_handle_resource_destroy
as
unsafe extern "C" fn(_:
*mut wl_resource)
-> ()));
_wlr_log(WLR_DEBUG,
b"[%s:%d] new xdg_toplevel_decoration %p (res %p)\x00" as
*const u8 as *const libc::c_char,
b"../types/wlr_xdg_decoration_v1.c\x00" as *const u8 as
*const libc::c_char, 202i32, decoration,
(*decoration).resource);
wl_list_init(&mut (*decoration).configure_list);
wl_signal_init(&mut (*decoration).events.destroy);
wl_signal_init(&mut (*decoration).events.request_mode);
wl_signal_add(&mut (*surface).events.destroy,
&mut (*decoration).surface_destroy);
(*decoration).surface_destroy.notify =
Some(toplevel_decoration_handle_surface_destroy as
unsafe extern "C" fn(_: *mut wl_listener,
_: *mut libc::c_void) -> ());
wl_signal_add(&mut (*surface).events.configure,
&mut (*decoration).surface_configure);
(*decoration).surface_configure.notify =
Some(toplevel_decoration_handle_surface_configure as
unsafe extern "C" fn(_: *mut wl_listener,
_: *mut libc::c_void) -> ());
wl_signal_add(&mut (*surface).events.ack_configure,
&mut (*decoration).surface_ack_configure);
(*decoration).surface_ack_configure.notify =
Some(toplevel_decoration_handle_surface_ack_configure as
unsafe extern "C" fn(_: *mut wl_listener,
_: *mut libc::c_void) -> ());
wl_list_init(&mut (*decoration).surface_commit.link);
wl_list_insert(&mut (*manager).decorations, &mut (*decoration).link);
if (*surface).added {
(*decoration).added = 1i32 != 0;
wlr_signal_emit_safe(&mut (*manager).events.new_toplevel_decoration,
decoration as *mut libc::c_void);
} else {
wl_list_remove(&mut (*decoration).surface_commit.link);
wl_signal_add(&mut (*(*surface).surface).events.commit,
&mut (*decoration).surface_commit);
(*decoration).surface_commit.notify =
Some(toplevel_decoration_handle_surface_commit as
unsafe extern "C" fn(_: *mut wl_listener,
_: *mut libc::c_void) -> ())
};
}
static mut decoration_manager_impl: zxdg_decoration_manager_v1_interface =
{
{
let mut init =
zxdg_decoration_manager_v1_interface{destroy:
Some(decoration_manager_handle_destroy
as
unsafe extern "C" fn(_:
*mut wl_client,
_:
*mut wl_resource)
-> ()),
get_toplevel_decoration:
Some(decoration_manager_handle_get_toplevel_decoration
as
unsafe extern "C" fn(_:
*mut wl_client,
_:
*mut wl_resource,
_:
uint32_t,
_:
*mut wl_resource)
->
()),};
init
}
};
unsafe extern "C" fn decoration_manager_bind(mut client: *mut wl_client,
mut data: *mut libc::c_void,
mut version: uint32_t,
mut id: uint32_t) {
let mut manager: *mut wlr_xdg_decoration_manager_v1 =
data as *mut wlr_xdg_decoration_manager_v1;
let mut resource: *mut wl_resource =
wl_resource_create(client, &zxdg_decoration_manager_v1_interface,
version as libc::c_int, id);
if resource.is_null() { wl_client_post_no_memory(client); return }
wl_resource_set_implementation(resource,
&decoration_manager_impl as
*const zxdg_decoration_manager_v1_interface
as *const libc::c_void,
manager as *mut libc::c_void, None);
}
unsafe extern "C" fn handle_display_destroy(mut listener: *mut wl_listener,
mut data: *mut libc::c_void) {
let mut manager: *mut wlr_xdg_decoration_manager_v1 =
(listener as *mut libc::c_char).offset(-24) as
*mut wlr_xdg_decoration_manager_v1;
wlr_signal_emit_safe(&mut (*manager).events.destroy,
manager as *mut libc::c_void);
wl_list_remove(&mut (*manager).display_destroy.link);
wl_global_destroy((*manager).global);
free(manager as *mut libc::c_void);
}
// wlr_xdg_toplevel_decoration::link
// struct wlr_xdg_toplevel_decoration *
// wlr_xdg_toplevel_decoration::configure_list
// wlr_xdg_decoration_manager_v1::link
// wlr_xdg_toplevel_decoration_v1_configure::link
#[no_mangle]
pub unsafe extern "C" fn wlr_xdg_decoration_manager_v1_create(mut display:
*mut wl_display)
-> *mut wlr_xdg_decoration_manager_v1 {
let mut manager: *mut wlr_xdg_decoration_manager_v1 =
calloc(1i32 as libc::c_ulong,
::std::mem::size_of::<wlr_xdg_decoration_manager_v1>() as
libc::c_ulong) as *mut wlr_xdg_decoration_manager_v1;
if manager.is_null() { return 0 as *mut wlr_xdg_decoration_manager_v1 }
(*manager).global =
wl_global_create(display, &zxdg_decoration_manager_v1_interface, 1i32,
manager as *mut libc::c_void,
Some(decoration_manager_bind as
unsafe extern "C" fn(_: *mut wl_client,
_: *mut libc::c_void,
_: uint32_t,
_: uint32_t) -> ()));
if (*manager).global.is_null() {
free(manager as *mut libc::c_void);
return 0 as *mut wlr_xdg_decoration_manager_v1
}
wl_list_init(&mut (*manager).decorations);
wl_signal_init(&mut (*manager).events.new_toplevel_decoration);
wl_signal_init(&mut (*manager).events.destroy);
(*manager).display_destroy.notify =
Some(handle_display_destroy as
unsafe extern "C" fn(_: *mut wl_listener,
_: *mut libc::c_void) -> ());
wl_display_add_destroy_listener(display, &mut (*manager).display_destroy);
return manager;
}
| 42.454091
| 221
| 0.585708
|
937a2287edad60d7ed437b90fd46250acb044a29
| 4,027
|
cs
|
C#
|
src/SevenDigital.Messaging.Integration.Tests/LocalQueue/LocalQueueErrorHookTests.cs
|
i-e-b/SevenDigital.Messaging
|
3c8e84592e70d37148c09727ae57cb7c9eb99bcb
|
[
"BSD-3-Clause"
] | 9
|
2016-09-02T19:11:39.000Z
|
2021-11-30T06:33:50.000Z
|
src/SevenDigital.Messaging.Integration.Tests/LocalQueue/LocalQueueErrorHookTests.cs
|
i-e-b/SevenDigital.Messaging
|
3c8e84592e70d37148c09727ae57cb7c9eb99bcb
|
[
"BSD-3-Clause"
] | null | null | null |
src/SevenDigital.Messaging.Integration.Tests/LocalQueue/LocalQueueErrorHookTests.cs
|
i-e-b/SevenDigital.Messaging
|
3c8e84592e70d37148c09727ae57cb7c9eb99bcb
|
[
"BSD-3-Clause"
] | null | null | null |
using System;
using System.IO;
using System.Threading;
using NUnit.Framework;
using ServiceStack.Text;
using SevenDigital.Messaging.EventHooks;
using SevenDigital.Messaging.Integration.Tests._Helpers;
using SevenDigital.Messaging.Integration.Tests._Helpers.Messages;
using SevenDigital.Messaging.Routing;
using StructureMap;
namespace SevenDigital.Messaging.Integration.Tests.LocalQueue
{
[TestFixture]
public class LocalQueueErrorHookTests
{
IColourMessage _sampleMessage;
const string LocalQueuePath = "./localQueue";
const string ErrorQueuePath = "./errorQueue";
protected TimeSpan ShortInterval { get { return TimeSpan.FromSeconds(5); } }
[SetUp]
public void when_a_handler_throws_an_exception ()
{
with_local_queue_messaging_and_an_error_queue();
and_a_triggering_message();
MessagingSystem.Receiver().Listen(_=>_.Handle<IColourMessage>().With<ExceptionSample>());
MessagingSystem.Sender().SendMessage(_sampleMessage);
}
void and_a_triggering_message()
{
_sampleMessage = DynamicProxy.GetInstanceFor<IColourMessage>();
_sampleMessage.CorrelationId = Guid.NewGuid();
_sampleMessage.Text = "Hello, world";
}
void with_local_queue_messaging_and_an_error_queue()
{
if (Directory.Exists(LocalQueuePath))
Directory.Delete(LocalQueuePath, true);
if (Directory.Exists(ErrorQueuePath))
Directory.Delete(ErrorQueuePath, true);
MessagingSystem
.Configure
.WithLocalQueue(LocalQueuePath)
.SendHandlerErrorsToQueue(ErrorQueuePath);
ObjectFactory.Configure(map => map.For<IUniqueEndpointGenerator>().Use<TestEndpointGenerator>());
MessagingSystem.Events.AddEventHook<ConsoleEventHook>();
ExceptionSample.AutoResetEvent = new AutoResetEvent(false);
TestTrigger.AutoResetEvent = new AutoResetEvent(false);
}
[Test]
public void handler_errors_should_be_persisted_the_the_designated_queue ()
{
Assert.True(ExceptionSample.AutoResetEvent.WaitOne(ShortInterval), "initial message not received");
ReconnectToErrorQueue();
// pick up the (hopefully) waiting message
MessagingSystem.Receiver().Listen(_=>_.Handle<IHandlerExceptionMessage>().With<TestTrigger>());
Assert.True(TestTrigger.AutoResetEvent.WaitOne(ShortInterval), "error message not stored");
Assert.That(TestTrigger.LastMessage.CausingMessage.CorrelationId , Is.EqualTo(_sampleMessage.CorrelationId));
Assert.That(TestTrigger.LastMessage.Date.Day, Is.EqualTo(DateTime.UtcNow.Day)); // don't run at midnight :-)
Assert.That(TestTrigger.LastMessage.Exception, Is.EqualTo("System.IO.IOException: I/O error occurred."));
Assert.That(TestTrigger.LastMessage.HandlerTypeName, Is.EqualTo(typeof(ExceptionSample).FullName));
}
static void ReconnectToErrorQueue()
{
MessagingSystem.Control.Shutdown();
MessagingSystem.Configure.WithLocalQueue(ErrorQueuePath);
ObjectFactory.Configure(map => map.For<IUniqueEndpointGenerator>().Use<TestEndpointGenerator>());
MessagingSystem.Events.AddEventHook<ConsoleEventHook>();
}
[TestFixtureTearDown]
public void Stop() { MessagingSystem.Control.Shutdown(); }
[RetryMessage(typeof(IOException))]
public class ExceptionSample : IHandle<IColourMessage>
{
public static int handledTimes = 0;
readonly object lockobj = new Object();
public static AutoResetEvent AutoResetEvent { get; set; }
public void Handle(IColourMessage message)
{
try
{
lock (lockobj)
{
handledTimes++;
}
if (handledTimes == 1) throw new IOException();
}
finally
{
AutoResetEvent.Set();
}
}
}
}
public class TestTrigger : IHandle<IHandlerExceptionMessage>
{
public static AutoResetEvent AutoResetEvent { get; set; }
public static IHandlerExceptionMessage LastMessage { get; set; }
public void Handle(IHandlerExceptionMessage message)
{
LastMessage = message;
AutoResetEvent.Set();
}
}
}
| 32.216
| 113
| 0.73479
|
3945b2fc0df3c7b3738bde77ca6d9e10e5ecb399
| 77
|
py
|
Python
|
run.py
|
m20-sch57/Fejudge
|
3eba1879be608e119b7891a1dbe7c9e450cc3914
|
[
"MIT"
] | 2
|
2019-12-25T14:06:09.000Z
|
2020-04-02T22:06:28.000Z
|
run.py
|
m20-sch57/Fejudge
|
3eba1879be608e119b7891a1dbe7c9e450cc3914
|
[
"MIT"
] | 9
|
2020-05-14T16:15:29.000Z
|
2020-09-01T14:17:19.000Z
|
run.py
|
m20-sch57/Fejudge
|
3eba1879be608e119b7891a1dbe7c9e450cc3914
|
[
"MIT"
] | null | null | null |
from app import app, socketio
socketio.run(app, host='0.0.0.0', port=3113)
| 15.4
| 44
| 0.701299
|
b75d44febf8380f8be76304cc07dfba54fa17725
| 1,197
|
cc
|
C++
|
chrome/browser/android/blimp/blimp_contents_profile_attachment.cc
|
xzhan96/chromium.src
|
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2021-01-07T18:51:03.000Z
|
2021-01-07T18:51:03.000Z
|
chrome/browser/android/blimp/blimp_contents_profile_attachment.cc
|
emilio/chromium.src
|
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
chrome/browser/android/blimp/blimp_contents_profile_attachment.cc
|
emilio/chromium.src
|
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/blimp/blimp_contents_profile_attachment.h"
#include "base/logging.h"
#include "base/supports_user_data.h"
#include "blimp/client/public/contents/blimp_contents.h"
namespace {
const char kBlimpContentsProfileAttachment[] =
"blimp_contents_profile_attachment";
// A holder struct for a Profile that can be used as data.
struct Attachment : public base::SupportsUserData::Data {
Profile* profile;
};
} // namespace
void AttachProfileToBlimpContents(blimp::client::BlimpContents* blimp_contents,
Profile* profile) {
DCHECK(profile);
Attachment* attachment = new Attachment;
attachment->profile = profile;
blimp_contents->SetUserData(kBlimpContentsProfileAttachment, attachment);
}
Profile* GetProfileFromBlimpContents(
blimp::client::BlimpContents* blimp_contents) {
Attachment* attachment = static_cast<Attachment*>(
blimp_contents->GetUserData(kBlimpContentsProfileAttachment));
DCHECK(attachment);
return attachment->profile;
}
| 32.351351
| 79
| 0.759398
|
c491824e4c2d94f6e0cb1902c7fb9ca02e48d2c9
| 2,293
|
hpp
|
C++
|
private/inc/avb_watchdog/IasWatchdogResult.hpp
|
tnishiok/AVBStreamHandler
|
7621daf8c9238361e030fe35188b921ee8ea2466
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 13
|
2018-09-26T13:32:35.000Z
|
2021-05-20T10:01:12.000Z
|
private/inc/avb_watchdog/IasWatchdogResult.hpp
|
tnishiok/AVBStreamHandler
|
7621daf8c9238361e030fe35188b921ee8ea2466
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 23
|
2018-10-03T22:45:21.000Z
|
2020-03-05T23:40:12.000Z
|
private/inc/avb_watchdog/IasWatchdogResult.hpp
|
tnishiok/AVBStreamHandler
|
7621daf8c9238361e030fe35188b921ee8ea2466
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 22
|
2018-09-14T03:55:34.000Z
|
2021-12-07T01:13:27.000Z
|
/*
* Copyright (C) 2018 Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#ifndef IAS_MONITORING_AND_LIFECYCLE_WATCHDOG_IAS_WATCHDOG_RESULT_HPP
#define IAS_MONITORING_AND_LIFECYCLE_WATCHDOG_IAS_WATCHDOG_RESULT_HPP
#include "media_transport/avb_streamhandler_api/IasAvbStreamHandlerTypes.hpp"
#include "avb_helper/IasResult.hpp"
#include <dlt/dlt_cpp_extension.hpp>
#include <string>
/**
* @brief Ias
*/
namespace IasWatchdog
{
/**
* @brief Ias
*/
enum IasResultMonitoringAndLifecycleGroups {
cIasResultGroupWatchdog
};
/**
* @brief Custom result class for the Watchdog component.
*/
class /*IAS_DSO_PUBLIC*/ IasWatchdogResult : public IasMediaTransportAvb::IasResult
{
public:
/**
* @brief WatchdogResult Constructor.
* @param[in] value the value of the thread result.
*/
explicit IasWatchdogResult(uint32_t const value)
: IasResult(value, cIasResultGroupWatchdog, IasMediaTransportAvb::cIasResultModuleMonitoringAndLifeCycle)
{
}
/**
* @brief IasWatchdogResult Constructor creating IasWatchdogResult from IasResult.
* @param[in] result IasResult to convert.
*/
IasWatchdogResult(IasMediaTransportAvb::IasResult const & result)
: IasResult(result)
{
}
virtual std::string toString()const;
static const IasWatchdogResult cObjectNotFound; /**< Result value cObjectNotFound */
static const IasWatchdogResult cAlreadyRegistered; /**< Result value cAlreadyRegistered */
static const IasWatchdogResult cWatchdogUnregistered; /**< Result value cWatchdogUnregistered */
static const IasWatchdogResult cWatchdogNotConnected; /**< Result value cWatchdogNotConnected */
static const IasWatchdogResult cAcquireLockFailed; /**<acquire of lock failed */
static const IasWatchdogResult cIncorrectThread; /**<reset called by incorrect thread */
static const IasWatchdogResult cTimedOut; /**<reset called too late. Watchdog already timed out */
static const IasWatchdogResult cWatchdogNotPreconfigured;/**< Result value cWatchdogNotPreconfigured */
};
}
template<>
IAS_DSO_PUBLIC int32_t logToDlt(DltContextData &log, IasWatchdog::IasWatchdogResult const & value);
#endif // IAS_MONITORING_AND_LIFECYCLE_WATCHDOG_IAS_WATCHDOG_RESULT_HPP
| 32.295775
| 115
| 0.764065
|
40f1771d2f298312b69d8339b091c51458659207
| 2,330
|
rb
|
Ruby
|
test/shopify-cli/core/finalize_test.rb
|
mkevinosullivan/shopify-app-cli
|
f1599dcf10a1f0ea794ba6838be093330cc1ffc2
|
[
"MIT"
] | null | null | null |
test/shopify-cli/core/finalize_test.rb
|
mkevinosullivan/shopify-app-cli
|
f1599dcf10a1f0ea794ba6838be093330cc1ffc2
|
[
"MIT"
] | 1
|
2021-02-23T14:06:03.000Z
|
2021-02-23T14:06:03.000Z
|
test/shopify-cli/core/finalize_test.rb
|
mkevinosullivan/shopify-app-cli
|
f1599dcf10a1f0ea794ba6838be093330cc1ffc2
|
[
"MIT"
] | 1
|
2020-11-12T11:00:44.000Z
|
2020-11-12T11:00:44.000Z
|
require 'test_helper'
module ShopifyCli
module Core
class FinalizeTest < MiniTest::Test
def test_deliver_returns_early_if_no_values_set
IO.expects(:new).never
assert_nil(Finalize.deliver!)
end
def test_deliver_puts_request_cd_if_provided
mock_io = mock
mock_io.expects(:puts).with("cd:path/to/cd")
IO.expects(:new).returns(mock_io)
Finalize.request_cd('path/to/cd')
assert_nil(Finalize.deliver!)
end
def test_deliver_puts_reload_shopify_from_if_provided
mock_io = mock
mock_io.expects(:puts).with("reload_shopify_cli_from:path/to/reload")
IO.expects(:new).returns(mock_io)
Finalize.reload_shopify_from('path/to/reload')
assert_nil(Finalize.deliver!)
end
def test_deliver_puts_set_env_values_if_provided
mock_io = mock
mock_io.expects(:puts).with("cd:path/to/cd\nreload_shopify_cli_from:path/to/reload\nsetenv:testkey=testvalue")
IO.expects(:new).returns(mock_io)
Finalize.setenv('testkey', 'testvalue')
Finalize.request_cd('path/to/cd')
Finalize.reload_shopify_from('path/to/reload')
assert_nil(Finalize.deliver!)
end
def test_discard_error_if_io_error
IO.expects(:new).raises(IOError.new)
Finalize.request_cd('path/to/cd')
output = capture_io do
Finalize.deliver!
end
assert_equal "", output[1]
end
def test_deliver_raises_argument_error_if_io_not_found
IO.expects(:new).raises(ArgumentError.new)
IO.any_instance.stubs(:closed?).returns(true)
Finalize.request_cd('path/to/cd')
assert_raises ArgumentError do
Finalize.deliver!
end
end
def test_deliver_raises_shopifycli_bug_if_io_found_but_used
IO.expects(:new).raises(ArgumentError.new)
IO.any_instance.stubs(:closed?).returns(false)
IO.any_instance.stubs(:fileno).returns(9).twice
IO.any_instance.expects(:stat).returns(mock(ftype: 'testtype'))
Finalize.request_cd('path/to/cd')
error = assert_raises ShopifyCli::Bug do
Finalize.deliver!
end
assert_equal "File descriptor 9, of type testtype, is not available.", error.message
end
end
end
end
| 31.066667
| 118
| 0.667811
|
07d0ba350cda308112aa637a857fbbdb00a20dc9
| 348
|
css
|
CSS
|
src/main/webapp/rs/css/mdcss/component/effect/ripple.css
|
lihongwu19921215/nutz-book-project
|
8624bb310b358f9d6dfa37b9dd800df442cabd0a
|
[
"Apache-2.0"
] | 260
|
2015-05-20T05:15:08.000Z
|
2021-05-23T14:12:59.000Z
|
nutzcn-yvr/src/main/resources/assets/yvr/css/mdcss/component/effect/ripple.css
|
diycoder/nutz-book-project
|
4528d6934a13cb39abb8155cd39a5f79a1170a66
|
[
"Apache-2.0"
] | 47
|
2015-06-01T12:31:19.000Z
|
2022-01-14T07:10:56.000Z
|
nutzcn-yvr/src/main/resources/assets/yvr/css/mdcss/component/effect/ripple.css
|
diycoder/nutz-book-project
|
4528d6934a13cb39abb8155cd39a5f79a1170a66
|
[
"Apache-2.0"
] | 159
|
2015-06-09T01:45:11.000Z
|
2021-09-11T03:17:53.000Z
|
.ripple-circle {
position: absolute;
border-radius: 50%;
}
@keyframes ripple-animation {
from {
transform: scale(0);
opacity: 1;
}
to {
transform: scale(3);
opacity: 0;
}
}
@-webkit-keyframes ripple-animation {
from {
transform: scale(0);
opacity: 1;
}
to {
transform: scale(3);
opacity: 0;
}
}
| 13.384615
| 37
| 0.574713
|
c0546e24ef761526427b1ad534e9e6014d6d7e99
| 970
|
cs
|
C#
|
utility/StringExtensions.cs
|
stephbu/aoc2021
|
0e002d490560a1930023a82bf22baa4b59f611fe
|
[
"MIT"
] | null | null | null |
utility/StringExtensions.cs
|
stephbu/aoc2021
|
0e002d490560a1930023a82bf22baa4b59f611fe
|
[
"MIT"
] | null | null | null |
utility/StringExtensions.cs
|
stephbu/aoc2021
|
0e002d490560a1930023a82bf22baa4b59f611fe
|
[
"MIT"
] | null | null | null |
namespace Aoc2021.Utility
{
using System;
using System.Linq;
public static class StringExtensions
{
public static string Format(this string format, params object[] args) {
return string.Format(format,args);
}
public static string ExcludeDistinctChars(this string sortString, string exclusions){
var distinctExcludedChars = sortString.Select(c => exclusions.Contains(c) ? "" : new String(c,1)).Distinct();
return String.Concat(distinctExcludedChars);
}
public static string ConcatSortDistinctChars(this string str1, string str2){
return String.Concat((str1 + str2).Distinct().OrderBy(c => c));
}
public static bool IncludesAll(this string str1, string str2){
foreach(var c in str2) {
if(str1.IndexOf(c) < 0) {
return false;
}
}
return true;
}
}
}
| 31.290323
| 121
| 0.587629
|
b20caac3dc8e13bd7a67a123d78027ef851aa407
| 8,621
|
dart
|
Dart
|
.pub/deps/debug/angular2/lib/src/modules/testing/lib/src/ng_test_bed.dart
|
psykoterro/Test-Angular-2-Dart
|
23ef81094c54f6698c3bfdbc4dab63f1d314252a
|
[
"MIT"
] | 1
|
2020-04-10T20:09:06.000Z
|
2020-04-10T20:09:06.000Z
|
docs/packages/angular2/src/modules/testing/lib/src/ng_test_bed.dart
|
ngyewch/choropleth-map-angular-dart
|
e2e0a99ed0eed02a33273885f89168439ee7e599
|
[
"BSD-3-Clause"
] | null | null | null |
docs/packages/angular2/src/modules/testing/lib/src/ng_test_bed.dart
|
ngyewch/choropleth-map-angular-dart
|
e2e0a99ed0eed02a33273885f89168439ee7e599
|
[
"BSD-3-Clause"
] | null | null | null |
import 'dart:async';
import 'dart:html';
import 'package:angular2/angular2.dart';
import 'package:angular2/src/core/application_ref.dart';
import 'package:test/test.dart';
import 'errors.dart';
import 'ng_test_bootstrap.dart';
import 'ng_test_stabilizer.dart';
NgTestFixture _activeTest;
void _failIfTestRunning() {
if (_activeTest != null) {
fail('Another test is currently still live. NgTestBed support *one* test '
'executing at a time in order to avoid timing conflicts or stability '
'issues with applications sharing the browser DOM.\n\n'
'When you are done with your test, make sure to "dipose" your '
'NgTetsFixture, or for convenience use "disposeAnyRunningTest":\n\n'
' tearDown(() => disposeAnyRunningTest());\n\n'
'Please note that this method returns a Future that must be completed '
'before setting up another test ("tearDown" handles this for you if '
'you return the future as seen above).');
}
}
// Returns a new immutable list merging a and b.
List/*<E>*/ _concat/*<E>*/(Iterable/*<E>*/ a, Iterable/*<E>*/ b) =>
new List/*<E>*/ .unmodifiable(/*<E>*/ new List/*<E>*/ .from(a)..addAll(b));
/// If any [NgTestController] is currently executing, calls [dispose] on it.
///
/// Returns a [Future] that completes when the test is destroyed.
///
/// This function is meant to be used within the
/// [`tearDown`](https://goo.gl/qT4fxc) function of `package:test`:
/// tearDown(() => disposeAnyRunningTest());
Future<Null> disposeAnyRunningTest() async {
await _activeTest?.dispose();
_activeTest = null;
}
/// An immutable builder for creating a pre-configured Angular application.
///
/// The root component type [T] that is created will build and work similarly
/// to how you would configure and run an application using `bootstrap` in
/// production.
///
/// For a simple test:
/// group('$HelloWorldComponent', () {
/// tearDown(() => disposeAnyRunningTest());
///
/// test('should render "Hello World", () async {
/// var bed = new NgTestBed<HelloWorldComponent>();
/// var fixture = await bed.create();
/// expect(controller, containsText('Hello World'));
/// });
/// });
///
/// New behavior and features can be added in a hierarchy of tests, such as:
/// group('My tests', () {
/// NgTestBed<HelloWorldComponent> bed;
/// NgTextFixture<HelloWorldComponent> fixture;
///
/// setUp(() => bed = new NgTestBed<HelloWorldComponent>());
/// tearDown(() => disposeAnyRunningTest());
///
/// test('should render "Hello World", () async {
/// fixture = await bed.create();
/// expect(fixture.rootElement, containsText('Hello World'));
/// });
///
/// test('should render "Hello World" in all-caps', () async {
/// bed = bed.addProviders(const [
/// const Provider(TextFormatter, useClass: AllCapsTextFormatter),
/// ]);
/// fixture = await bed.create();
/// expect(fixture.rootElement, containsText('HELLO WORLD'));
/// });
/// });
class NgTestBed<T> {
static Element _createDefaultHost() {
final host = new Element.tag('ng-test-bed');
document.body.append(host);
return host;
}
final Element _host;
final List<Object> _providers;
final List<RegisterStabilizer> _stabilizers;
/// Create a new empty [NgTestBed].
///
/// By default, stabilizers are added that understand the Angular lifecycle;
/// they can be omitted by setting [watchAngularLifecycle] to false.
factory NgTestBed({
Element host,
bool watchAngularLifecycle: true,
}) {
if (T == dynamic) {
throw new GenericTypeRequiredError<NgTestBed>();
}
var bed = new NgTestBed<T>._();
if (host != null) {
bed = bed.setHost(host);
}
if (watchAngularLifecycle) {
bed = bed.addStabilizers([
new RegisterStabilizer<NgZoneStabilizer>(),
]);
}
return bed;
}
NgTestBed._([
this._host,
this._providers = const [],
this._stabilizers = const [],
]) {
// A factory should never invoke this constructor without T.
assert(T != dynamic);
}
/// Creates a new instance of [NgTestBed] with [providers] added.
///
/// If any element in [providers] is not an [Iterable], [Type], or [Provider]
/// throws a [InvalidProviderTypeException] with details about the invalid
/// element.
///
/// __Example use__:
/// ngTestBed = ngTestBed.addProviders([
/// const Provide(Foo, useClass: StubFoo),
/// ])
NgTestBed<T> addProviders(Iterable<Object> providers) {
return fork(providers: _concat(_providers, providers));
}
/// Creates a new instance of [NgTestBed] with [stabilizers] added.
///
/// __Example use__:
/// ngTestBed = ngTestBed.addStabilizers([
/// const RegisterStabilizer<NgZoneStabilizer>()
/// ])
NgTestBed<T> addStabilizers(Iterable<RegisterStabilizer> stabilizers) {
var types = stabilizers.map/*<Type>*/((s) => s.type);
return fork(
providers: _concat(_providers, types),
stabilizers: _concat(_stabilizers, stabilizers),
);
}
/// Create a new application with a root component.
///
/// If [onLoad] is specified, is called back _before_ initialization.
///
/// Returns a [Future] that completes with a created component.
Future<NgTestFixture<T>> create({
void onLoad(T instance),
}) {
// Purposefully does not use async/await, due to that starting an additional
// microtask at the beginning. We want this assert to happen synchronously
// to immediately catch an error.
_failIfTestRunning();
return new Future<NgTestFixture<T>>.sync(() {
return ngTestBootstrap(
T,
_host ?? _createDefaultHost(),
onLoad: onLoad,
userProviders: _providers,
).then((componentRef) async {
// Check one more time, because someone could have forgot to 'await'
// this create statement and a test started since the last asynchronous
// event.
_failIfTestRunning();
final stabilizer = new NgTestStabilizer.all(
_stabilizers.map/*<NgTestStabilizer>*/(
(s) => componentRef.injector.get(s.type),
),
);
final fixture = new NgTestFixture<T>._(
componentRef.injector.get(ApplicationRef),
componentRef,
stabilizer,
);
return fixture;
});
});
}
/// Creates a new instance of [NgTestBed] with some properties changed.
///
/// __Example use__:
/// ngTestBed = ngTestBed.fork(providers: [ ... ], stabilizers: [ ... ]);
NgTestBed<T> fork({
Element host,
List<Object> providers,
List<RegisterStabilizer> stabilizers,
}) {
return new NgTestBed<T>._(
host ?? _host,
providers ?? _providers,
stabilizers ?? _stabilizers,
);
}
/// Creates a new instance of [NgTestBed] with a new [host].
NgTestBed<T> setHost(Element host) => fork(host: host);
}
/// Represents a running instance of Angular for a test case.
class NgTestFixture<T> {
final ApplicationRef _applicationRef;
final ComponentRef _componentRef;
final NgTestStabilizer _stabilizer;
NgTestFixture._(
this._applicationRef,
this._componentRef,
this._stabilizer,
) {
assert(T != dynamic);
}
/// Destroys the test case, returing a future that completes after disposed.
///
/// In most cases, it is preferable to use [disposeAnyRunningTest].
Future<Null> dispose() async {
_componentRef.location.nativeElement.remove();
_applicationRef.dispose();
}
/// Root DOM element of the test.
Element get element => _componentRef.location.nativeElement;
/// Returns a [Future] that completes after the DOM is reported stable.
///
/// It is import to `update` before making an assertion on the DOM, as Angular
/// (and other services) could be waiting (asynchronously) to make a change -
/// and often you'd want to assert against the _final_ state.
///
/// __Example use__:
/// expect(fixture.element.text, contains('Loading...'));
/// await fixture.update();
/// expect(fixture.element.text, contains('Hello World'));
///
/// Optionally, pass a [fn] to run _before_ stabilizing:
/// await fixture.update((c) {
/// c.value = 5;
/// });
/// expect(fixture.element.text, contains('5 little piggues'));
Future<Null> update([void fn(T instance)]) async {
await _stabilizer.update(() {
if (fn != null) {
fn(_componentRef.instance);
}
});
}
}
| 33.157692
| 80
| 0.637977
|
5b576a80e7ae1eea2cc1d087a413cfba004f87c5
| 36
|
lua
|
Lua
|
src/mod/map_editor/init.lua
|
Ruin0x11/OpenNefia
|
548f1a1442eca704bb1c16b1a1591d982a34919f
|
[
"MIT"
] | 109
|
2020-04-07T16:56:38.000Z
|
2022-02-17T04:05:40.000Z
|
src/mod/map_editor/init.lua
|
Ruin0x11/OpenNefia
|
548f1a1442eca704bb1c16b1a1591d982a34919f
|
[
"MIT"
] | 243
|
2020-04-07T08:25:15.000Z
|
2021-10-30T07:22:10.000Z
|
src/mod/map_editor/init.lua
|
Ruin0x11/OpenNefia
|
548f1a1442eca704bb1c16b1a1591d982a34919f
|
[
"MIT"
] | 15
|
2020-04-25T12:28:55.000Z
|
2022-02-23T03:20:43.000Z
|
require("mod.map_editor.data.init")
| 18
| 35
| 0.777778
|
3752d2b97fc95949f1cc5105870c9710cf37b46c
| 1,200
|
ps1
|
PowerShell
|
Examples/RunMe-Test17.ps1
|
danubie/PSEventViewer
|
35207625341b79bc4f995cad3bdd16ecf1a1deba
|
[
"MIT"
] | 72
|
2018-04-25T19:03:36.000Z
|
2022-03-23T06:27:24.000Z
|
Examples/RunMe-Test17.ps1
|
danubie/PSEventViewer
|
35207625341b79bc4f995cad3bdd16ecf1a1deba
|
[
"MIT"
] | 13
|
2019-03-07T02:46:17.000Z
|
2022-03-21T09:53:28.000Z
|
Examples/RunMe-Test17.ps1
|
danubie/PSEventViewer
|
35207625341b79bc4f995cad3bdd16ecf1a1deba
|
[
"MIT"
] | 18
|
2019-01-07T01:20:38.000Z
|
2022-03-25T06:25:02.000Z
|
Import-Module PSEventViewer -Force
$AllEvents = Get-Events -LogName 'Application' -ID 1001 -MaxEvents 1 -Verbose -DisableParallel
$Message = $AllEvents[0].Message
$M = [ordered] @{}
foreach ($SubMessage in $Message.Split([Environment]::NewLine)) {
if ($SubMessage -like '*:*') {
$T = $SubMessage.Split(':')
$M[($T[0])] = $T[1]
} else {
if ($SubMessage.Trim() -ne '') {
}
}
}
<#
Fault bucket 2058674454742653114, type 5
Event Name: RADAR_PRE_LEAK_64
Response: Not available
Cab Id: 0
Problem signature:
P1: Code.exe
P2: 1.36.0.0
P3: 10.0.18362.2.0.0
P4:
P5:
P6:
P7:
P8:
P9:
P10:
Attached files:
\\?\C:\Users\PRZEMY~1.KLY\AppData\Local\Temp\RDR7D2A.tmp\empty.txt
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER7D2B.tmp.WERInternalMetadata.xml
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER7D3C.tmp.xml
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER7D98.tmp.csv
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER7DD7.tmp.txt
These files may be available here:
Analysis symbol:
Rechecking for solution: 0
Report Id: a0709c03-7dbf-42e3-977b-9b53a404444a
Report Status: 268435456
Hashed bucket: 74775b34cbd39705dc91e1825f1b58ba
Cab Guid: 0
#>
| 21.818182
| 94
| 0.701667
|
7e1deb7e5207932e80e69ce6c50996eeb4c58ff7
| 166
|
rb
|
Ruby
|
lib/generators/plug/templates/plug.rb
|
boost/plug
|
c41885b46ef874f3282ec2b80be6f0b20798cce1
|
[
"MIT"
] | 2
|
2020-03-03T16:16:09.000Z
|
2021-10-13T17:45:00.000Z
|
lib/generators/plug/templates/plug.rb
|
hapiben/plug
|
c41885b46ef874f3282ec2b80be6f0b20798cce1
|
[
"MIT"
] | 23
|
2018-02-21T22:43:55.000Z
|
2022-02-11T20:51:37.000Z
|
lib/generators/plug/templates/plug.rb
|
hapiben/plug
|
c41885b46ef874f3282ec2b80be6f0b20798cce1
|
[
"MIT"
] | null | null | null |
# /config/initializers/plug.rb
Plug.configure do |config|
config.auth_user = 'admin'
config.auth_password = 'password'
config.themes = ['default', 'dark']
end
| 23.714286
| 37
| 0.710843
|
2ccf317633f8a8f8e27fa1ddb8028622cce1da18
| 1,023
|
py
|
Python
|
kkanbu/operation/views.py
|
coding-kkanbu/teameet_backend
|
2af1c5fb3ed7f0c2d374afbdf53f318ecc6ae69d
|
[
"MIT"
] | 1
|
2022-01-09T13:40:41.000Z
|
2022-01-09T13:40:41.000Z
|
kkanbu/operation/views.py
|
coding-kkanbu/teameet_backend
|
2af1c5fb3ed7f0c2d374afbdf53f318ecc6ae69d
|
[
"MIT"
] | 33
|
2022-01-04T10:27:55.000Z
|
2022-03-31T10:32:53.000Z
|
kkanbu/operation/views.py
|
coding-kkanbu/teameet_backend
|
2af1c5fb3ed7f0c2d374afbdf53f318ecc6ae69d
|
[
"MIT"
] | null | null | null |
from rest_framework.mixins import CreateModelMixin, ListModelMixin
from rest_framework.viewsets import GenericViewSet
from .models import CommentBlame, CommentLike, PostBlame, PostLike
from .serializers import (
CommentBlameSerializer,
CommentLikeSerializer,
PostBlameSerializer,
PostLikeSerializer,
)
class PostLikeViewSet(
GenericViewSet,
CreateModelMixin,
ListModelMixin,
):
serializer_class = PostLikeSerializer
queryset = PostLike.objects.all()
class CommentLikeViewSet(
GenericViewSet,
CreateModelMixin,
ListModelMixin,
):
serializer_class = CommentLikeSerializer
queryset = CommentLike.objects.all()
class PostBlameViewSet(
GenericViewSet,
CreateModelMixin,
ListModelMixin,
):
serializer_class = PostBlameSerializer
queryset = PostBlame.objects.all()
class CommentBlameViewSet(
GenericViewSet,
CreateModelMixin,
ListModelMixin,
):
serializer_class = CommentBlameSerializer
queryset = CommentBlame.objects.all()
| 21.765957
| 66
| 0.765396
|
0b8deb252d1348ca9a851523cda7ec7075e5d45d
| 4,793
|
swift
|
Swift
|
Pages/Collision Detection.xcplaygroundpage/Contents.swift
|
thatseeyou/SpriteKitExamples
|
fba573edccae7eb2ad8296a2d4fc6bebb4a69a0a
|
[
"0BSD"
] | 1
|
2016-06-14T15:08:01.000Z
|
2016-06-14T15:08:01.000Z
|
Pages/Collision Detection.xcplaygroundpage/Contents.swift
|
thatseeyou/SpriteKitExamples
|
fba573edccae7eb2ad8296a2d4fc6bebb4a69a0a
|
[
"0BSD"
] | null | null | null |
Pages/Collision Detection.xcplaygroundpage/Contents.swift
|
thatseeyou/SpriteKitExamples
|
fba573edccae7eb2ad8296a2d4fc6bebb4a69a0a
|
[
"0BSD"
] | null | null | null |
/*:
### collision & contact test
- collisionBitMask
* bodyA.categoryBitMask & bodyB.collisionBitMask > 0 && bodyB.categoryBitMask & bodyA.collisionBitMask > 0
* 짝충돌은 없다. 서로 충돌인 경우에만 충돌로 처리한다.
- contactTestBitMask
* bodyA.categoryBitMask & bodyB.contactTestBitMask > 0 || bodyB.categoryBitMask & bodyA.contactTestBitMask > 0
* 한 쪽만 조건에 맞으면 가능하다.
* 충돌이 없는 경우에는 test는 가능하다.
*/
import UIKit
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMove(to view: SKView) {
self.name = "scene"
// SKScene의 경계에 physicsbody 설정
self.physicsWorld.gravity = CGVector(dx: 0, dy: -10)
self.physicsWorld.speed = 0.3
self.physicsWorld.contactDelegate = self
// Test1. collision & test
let ball1 = ballWithRadius(10)
do {
ball1.name = "ball1"
ball1.fillColor = #colorLiteral(red: 0.7540004253387451, green: 0, blue: 0.2649998068809509, alpha: 1)
ball1.position = CGPoint(x: 55,y: 400)
ball1.physicsBody?.categoryBitMask = 0x1
ball1.physicsBody?.collisionBitMask = 0x10
ball1.physicsBody?.contactTestBitMask = 0
}
let bar1 = barWithSize(CGSize(width: 100,height: 10))
do {
bar1.name = "bar1"
bar1.position = CGPoint(x: 55, y: 100)
bar1.physicsBody?.categoryBitMask = 0x10
bar1.physicsBody?.collisionBitMask = 0x1
bar1.physicsBody?.contactTestBitMask = 0x1
}
// Test2. collision only
let ball2 = ballWithRadius(20)
do {
ball2.name = "ball2"
ball2.fillColor = #colorLiteral(red: 0.2818343937397003, green: 0.5693024396896362, blue: 0.1281824260950089, alpha: 1)
ball2.position = CGPoint(x: 160,y: 400)
ball2.physicsBody?.categoryBitMask = 0x2
ball2.physicsBody?.collisionBitMask = 0x20
ball2.physicsBody?.contactTestBitMask = 0
}
let bar2 = barWithSize(CGSize(width: 100,height: 10))
do {
bar2.name = "bar2"
bar2.position = CGPoint(x: 160, y: 100)
bar2.physicsBody?.categoryBitMask = 0x20
bar2.physicsBody?.collisionBitMask = 0x2
bar2.physicsBody?.contactTestBitMask = 0
}
// Test3. test only
let ball3 = ballWithRadius(30)
do {
ball3.name = "ball3"
ball3.fillColor = #colorLiteral(red: 0.4120420813560486, green: 0.8022739887237549, blue: 0.9693969488143921, alpha: 1)
ball3.position = CGPoint(x: 265,y: 400)
ball3.physicsBody?.categoryBitMask = 0x4
ball3.physicsBody?.collisionBitMask = 0
ball3.physicsBody?.contactTestBitMask = 0
}
let bar3 = barWithSize(CGSize(width: 100,height: 10))
do {
bar3.name = "bar3"
bar3.position = CGPoint(x: 265, y: 100)
bar3.physicsBody?.categoryBitMask = 0
bar3.physicsBody?.collisionBitMask = 0
bar3.physicsBody?.contactTestBitMask = 0x4
}
addChild(bar1)
addChild(bar2)
addChild(bar3)
addChild(ball1)
addChild(ball2)
addChild(ball3)
}
func didBegin(_ contact: SKPhysicsContact) {
print("START: \(contact.bodyA.node?.name) - \(contact.bodyB.node?.name)")
}
func didEnd(_ contact: SKPhysicsContact) {
print("END: \(contact.bodyA.node?.name) - \(contact.bodyB.node?.name)")
}
func ballWithRadius(_ radius:CGFloat) -> SKShapeNode {
let ballShape = SKShapeNode(circleOfRadius: radius)
do {
ballShape.physicsBody = SKPhysicsBody(circleOfRadius: radius)
}
return ballShape
}
func barWithSize(_ size:CGSize) -> SKSpriteNode {
let ballShape = SKSpriteNode(color: #colorLiteral(red: 0.3586547076702118, green: 0, blue: 0.1448745727539062, alpha: 1), size: size)
do {
ballShape.physicsBody = SKPhysicsBody(rectangleOf: size)
ballShape.physicsBody?.isDynamic = false
}
return ballShape
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// add SKView
do {
let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480))
skView.showsFPS = true
//skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
let scene = GameScene(size: CGSize(width: 320, height: 480))
scene.scaleMode = .aspectFit
skView.presentScene(scene)
self.view.addSubview(skView)
}
}
}
PlaygroundHelper.showViewController(ViewController())
| 34.482014
| 141
| 0.604423
|
b09d0e57ce0b7cd22cec7c4f56cc37a967b927e0
| 3,464
|
py
|
Python
|
src/dataset.py
|
hrkz/SubgridTransportNN
|
174c759ae26eb3d6ffe1b95de62cf61d5067da83
|
[
"MIT"
] | 5
|
2020-10-12T12:55:09.000Z
|
2020-12-07T11:38:45.000Z
|
src/dataset.py
|
hrkz/subgridtransportNN
|
174c759ae26eb3d6ffe1b95de62cf61d5067da83
|
[
"MIT"
] | null | null | null |
src/dataset.py
|
hrkz/subgridtransportNN
|
174c759ae26eb3d6ffe1b95de62cf61d5067da83
|
[
"MIT"
] | 2
|
2020-11-03T12:50:51.000Z
|
2021-01-22T16:40:51.000Z
|
import torch
import numpy as np
import h5py
import matplotlib
import matplotlib.pyplot as plt
import glob
plt.rcParams.update({'mathtext.fontset':'cm'})
class SubgridDataset(torch.utils.data.Dataset):
def __init__(self, device, path, samples, size, x, y, established=0):
self.device = device
self.path = path
self.samples = samples - established
self.size = size
self.established = established
self.x = x
self.y = y
self.inputs = torch.zeros(self.samples, len(x), size, size, size, dtype=torch.float32)
self.labels = torch.zeros(self.samples, len(y), size, size, size, dtype=torch.float32)
for i, f in enumerate(x):
for j, c in enumerate(sorted(glob.glob(path + f + '_*'))):
if j < established:
# dynamic not established
continue
elif j >= samples:
break
# transform
p = j - established
file = h5py.File(c, 'r')
dset = file[f]
self.inputs[p][i] = torch.from_numpy(dset[()])
for i, f in enumerate(y):
for j, c in enumerate(sorted(glob.glob(path + f + '_*'))):
if j < established:
# dynamic not established
continue
elif j >= samples:
break
# transform
p = j - established
#to_pytorch(self.labels[p][i], f, c)
file = h5py.File(c, 'r')
dset = file[f]
self.labels[p][i] = torch.from_numpy(dset[()])
def plot(self, ylabels, plot_samples=5, slice=5):
features_inputs = self.inputs.shape[1]
features_labels = self.labels.shape[1]
features = features_inputs + features_labels
fig, ax = plt.subplots(
nrows=features,
ncols=plot_samples + 1,
figsize=(plot_samples * 2.5, features * 2.5),
constrained_layout=True,
gridspec_kw={"width_ratios": np.append(np.repeat(1, plot_samples), 0.05)}
)
fig.suptitle(r'Cut in dataset throughout the simulation of $\mathcal{S}$')
max_input, _ = self.inputs[:,:,slice].flatten(start_dim=2).max(2)[0].max(0)
min_input, _ = self.inputs[:,:,slice].flatten(start_dim=2).min(2)[0].min(0)
max_label, _ = self.labels[:,:,slice].flatten(start_dim=2).max(2)[0].max(0)
min_label, _ = self.labels[:,:,slice].flatten(start_dim=2).min(2)[0].min(0)
for j in range(plot_samples):
sample = int(
(j) *
((self.samples - 1) /
(plot_samples - 1) ))
off = len(self.x)
for i, f in enumerate(self.x):
c = ax[i, j].contourf(self.inputs[sample][i][slice], 100, cmap='bwr', vmin=min_input[i], vmax=max_input[i])
if j < 1:
# add label
ax[i, j].set_ylabel(ylabels[i], fontsize=20.0)
fig.colorbar(c, cax=ax[i, plot_samples])
for i, f in enumerate(self.y):
l = ax[i + off, j].contourf(self.labels[sample][i][slice], 100, cmap='bwr', vmin=min_label[0], vmax=max_label[0])
if j < 1:
# add label
ax[i + off, j].set_ylabel(ylabels[i + off], fontsize=20.0)
fig.colorbar(l, cax=ax[i + off, plot_samples])
ax[i + off, j].set_xlabel(r'$\mathcal{S}_{' + str((self.established + sample + 1) * 500) + r'}$', fontsize=20.0)
#fig.savefig('dataset.png')
def __len__(self):
return self.samples
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
inputs = self.inputs[idx]
labels = self.labels[idx]
return (inputs.to(self.device), labels.to(self.device))
| 33.307692
| 121
| 0.598152
|
7ad969a093e00865731aed1f7e145c2ae8dfaad6
| 1,401
|
cs
|
C#
|
tests/Zaabee.Extensions.UnitTest/Commons/MyCollection.cs
|
Mutuduxf/Zaabee.Extensions
|
5d6a94d3861253e2617936c84860eb847a466043
|
[
"MIT"
] | 2
|
2020-11-25T10:03:38.000Z
|
2022-01-17T01:45:34.000Z
|
tests/Zaabee.Extensions.UnitTest/Commons/MyCollection.cs
|
Mutuduxf/Zaabee.Extensions
|
5d6a94d3861253e2617936c84860eb847a466043
|
[
"MIT"
] | null | null | null |
tests/Zaabee.Extensions.UnitTest/Commons/MyCollection.cs
|
Mutuduxf/Zaabee.Extensions
|
5d6a94d3861253e2617936c84860eb847a466043
|
[
"MIT"
] | 1
|
2019-10-16T02:11:33.000Z
|
2019-10-16T02:11:33.000Z
|
using System.Collections;
using System.Collections.Generic;
namespace Zaabee.Extensions.UnitTest.Commons
{
class MyCollection<T> : IList<T>
{
private readonly IList<T> _list = new List<T>();
#region Implementation of IEnumerable
public IEnumerator<T> GetEnumerator() => _list.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
#region Implementation of ICollection<T>
public void Add(T item) => _list.Add(item);
public void Clear() => _list.Clear();
public bool Contains(T item) => _list.Contains(item);
public void CopyTo(T[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex);
public bool Remove(T item) => _list.Remove(item);
public int Count => _list.Count;
public bool IsReadOnly => _list.IsReadOnly;
#endregion
#region Implementation of IList<T>
public int IndexOf(T item) => _list.IndexOf(item);
public void Insert(int index, T item) => _list.Insert(index, item);
public void RemoveAt(int index) => _list.RemoveAt(index);
public T this[int index]
{
get => _list[index];
set => _list[index] = value;
}
#endregion
#region Your Added Stuff
// Add new features to your collection.
#endregion
}
}
| 24.155172
| 89
| 0.61242
|
f424ab51ea2d793d0127be7c128738d0ebfee3e5
| 284
|
css
|
CSS
|
client/src/components/Footer/Footer.css
|
b1506704/Real-Estate-Shop
|
f00c58634f3d268bf6ba66ac2e48f413835e3778
|
[
"MIT"
] | null | null | null |
client/src/components/Footer/Footer.css
|
b1506704/Real-Estate-Shop
|
f00c58634f3d268bf6ba66ac2e48f413835e3778
|
[
"MIT"
] | null | null | null |
client/src/components/Footer/Footer.css
|
b1506704/Real-Estate-Shop
|
f00c58634f3d268bf6ba66ac2e48f413835e3778
|
[
"MIT"
] | null | null | null |
footer {
bottom: 0;
user-select: none;
background-color: rgba(0, 0, 0, 0.534);
color: rgb(238, 253, 255);
width: 100%;
padding-left: 120px;
}
footer h1{
font-size: 20px;
margin: 0;
color: rgb(238, 253, 255);
padding: 24px 0;
letter-spacing: 2px;
background: transparent;
}
| 17.75
| 40
| 0.658451
|
65ca1caea6df581f6da6168a6bcce12f1130558e
| 3,747
|
lua
|
Lua
|
library/lib-BLYNK2.lua
|
alexxlabs/esuite-lua
|
447060468f072232a10214083ec2d0eae0e54e01
|
[
"MIT"
] | 20
|
2017-09-08T06:17:11.000Z
|
2021-05-11T19:44:11.000Z
|
library/lib-BLYNK2.lua
|
alexxlabs/esuite-lua
|
447060468f072232a10214083ec2d0eae0e54e01
|
[
"MIT"
] | 2
|
2017-09-17T23:47:53.000Z
|
2018-09-06T09:54:36.000Z
|
library/lib-BLYNK2.lua
|
alexxlabs/esuite-lua
|
447060468f072232a10214083ec2d0eae0e54e01
|
[
"MIT"
] | 11
|
2017-10-17T10:18:26.000Z
|
2021-04-04T12:19:19.000Z
|
-- part2
function blynk.queue(self,message,s)
table.insert(self.message_queue, message)
self:process_queue(s)
end
function blynk.process_queue(self, s)
if s == nil then
s = self.conn
end
if #self.message_queue > 0 and s:getaddr() then -- occasional net fail appears here before "disconnect"
s:send(table.remove(self.message_queue,1))
end
end
function blynk.disconnect(self) -- unsafe to call, tmr alive
self.conn:close()
return self
end
function blynk.split(self,cmd)
local result = { }
local from = 1
local delim_from, delim_to = string.find( cmd, '\0', from )
while delim_from do
table.insert( result, string.sub( cmd, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( cmd, '\0', from )
end
table.insert( result, string.sub( cmd, from ) )
return result
end
function blynk.pack (self,...)
return table.concat(arg, string.char(0))
end
function blynk.on(self, message, func)
self.callbacks[message] = func
return self
end
function blynk.mid(self)
self.message_id = self.message_id+1
return self.message_id
end
-- create and send
function blynk.send_message ( self, cmd, mid, payload )
self:queue(self:create_message(cmd,mid,payload))
end
-- a blynk message is 8bit type, 16bit mid, 16bit length, payload and '\0'
function blynk.create_message ( self, cmd, mid, payload )
local msg
if payload ~= nil then
--print ( "message is: " .. cmd .. " " .. mid .. " " .. string.len(payload) .. ' ' .. payload)
msg = struct.pack ( ">BI2I2c0", cmd, mid, string.len(payload), payload)
else
--print ( "message is: " .. cmd .. " " .. mid )
msg = struct.pack ( ">BI2I2", cmd, mid, 0)
end
if self.dump then self:dump(msg,"out") end
return msg
end
function blynk.write(self, pintype, vpin, payload) -- pintype "vw" or "dw"
self:send_message(self.commands["hardware"], self:mid(), self:pack(pintype, tostring(vpin), tostring(payload)))
end
-- following function is for common generic (automated) dw and dr and adc0 GPIO action.
-- Will be nil'd if not used (abt 1kB)
-- Usage: b = blynk.new ( token ) The nil callback installs autogpio
-- alternatively, use regular setup_callback(b) as in b = blynk.new ( token, setup_cb)
-- and inside the callback manually call "blynk_autogpio(b)"
-- autogpio still needs user project to preconfigure gpio modes:
-- some gpio.mode() notes:
-- the gpio.write() in auto-gpio function will usually CAUSE that gpio to go to output mode.
-- the onboard led on D4 is an exception. Your project MUST explicitly set that to output if you want to use it.
-- the gpio.read() in auto-gpio function will always read pin value, and most pins start INPUT by default.
-- however, it's best to explicitly set your inputs in your project, and especially those needing pullup.
function blynk_autogpio(b)
-- all digital writes & digital reads to be handled automatically. No special code per each.
b:on ('dw', function (cmd)
gpio.write(cmd[2],cmd[3]) -- and will implicitly set mode to output
end)
b:on ('dr', function (cmd, orig_msgid)
b:send_message(blynk.commands["hardware"], orig_msgid, b:pack('dw', cmd[2], tostring(gpio.read(cmd[2]))))
end)
b:on ('ar', function (cmd, orig_msgid) -- adc0 only. Caution: user may need check "force_init_mode" first.
b:send_message(blynk.commands["hardware"], orig_msgid, b:pack('aw', cmd[2], tostring(adc.read(0))))
end)
b:on ('pm', function (cmd)
uart.write(0, "Gpio req: ") for i=2, #cmd, 2 do uart.write(0, cmd[i]..cmd[i+1].." ") end print("")
-- Only a report. Project file needs to make these mode settings
end)
b.autogpio=true
end
| 36.028846
| 115
| 0.673872
|
6505ae049a455b06843a7ef1860d32c2735efa79
| 291
|
rb
|
Ruby
|
test/system/landing_pages_test.rb
|
matthewl/WriteAbout
|
3e0c55b57820f2916b1928647721392804e2fa88
|
[
"MIT"
] | 6
|
2020-01-14T09:42:07.000Z
|
2022-02-12T03:10:00.000Z
|
test/system/landing_pages_test.rb
|
matthewl/Writeabout
|
4d1ca2f1f5c179e6b50ec1ca6d3996420b0a1475
|
[
"MIT"
] | 16
|
2020-01-08T21:45:03.000Z
|
2022-02-26T08:49:38.000Z
|
test/system/landing_pages_test.rb
|
matthewl/Writeabout
|
4d1ca2f1f5c179e6b50ec1ca6d3996420b0a1475
|
[
"MIT"
] | null | null | null |
require 'application_system_test_case'
class LandingPagesTest < ApplicationSystemTestCase
test 'visiting the index' do
visit root_url
assert_selector 'h1', text: 'Write About'
assert_selector 'h2', text: "A writing prompt generator for when you have writer's block"
end
end
| 29.1
| 93
| 0.766323
|
ef508c5eaa4b01b6abf3267d3c1b3ee99e3f4a50
| 4,556
|
h
|
C
|
app/dnn/src/dnn/dnn.h
|
alexrenz/bosen-2
|
c61ac4e892ba2f6e02bd4595632b15f9e53450e2
|
[
"BSD-3-Clause"
] | 370
|
2015-06-30T09:46:17.000Z
|
2017-01-21T07:14:00.000Z
|
app/dnn/src/dnn/dnn.h
|
alexrenz/bosen-2
|
c61ac4e892ba2f6e02bd4595632b15f9e53450e2
|
[
"BSD-3-Clause"
] | 3
|
2016-11-08T19:45:19.000Z
|
2016-11-11T13:21:19.000Z
|
app/dnn/src/dnn/dnn.h
|
alexrenz/bosen-2
|
c61ac4e892ba2f6e02bd4595632b15f9e53450e2
|
[
"BSD-3-Clause"
] | 159
|
2015-07-03T05:58:31.000Z
|
2016-12-29T20:59:01.000Z
|
// Copyright (c) 2014, Sailing Lab
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the <ORGANIZATION> nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//author: Pengtao Xie (pengtaox@cs.cmu.edu)
#ifndef DNN_H_
#define DNN_H_
#include <petuum_ps_common/include/petuum_ps.hpp>
#include "paras.h"
#include "util.h"
#include "types.h"
#include <atomic>
#include <string>
//class of deep neural network
class dnn
{
private :
//meta parameters
int num_layers;//number of layers
int * num_units_ineach_layer;//number of unis in each layer
int num_epochs;//number of epochs in stochastic gradient descent (SGD)
float stepsize;//stepsize of SGD
int num_worker_threads;//number of worker threads
int size_minibatch;//mini batch size
//data
float ** input_features;//input features
int * output_labels;//labels
int num_train_data;//number of training data
//thread control
boost::scoped_ptr<boost::barrier> process_barrier;//process barrier to sync threads
boost::thread_specific_ptr<int> thread_id;//id of thread
std::atomic<int> thread_counter;
//misc
int staleness;//staleness value
int client_id;//id of the client (machine)
int num_smps_evaluate;//when evaluating objective function, randomly sample <num_smps_evaluate> points to evaluate the objective function
int num_iters_evaluate;//every <num_iters_evaluate> iterations, evaluate the objective function
//do forward activation
void forward_activation(int index_lower_layer, float ** local_weights, float * local_bias, float * visible, float * hidden);
//compute error in output layer
void compute_error_output_layer(float * error_output_layer, float * activation_output_layer,int idx_data);
//compute backward error
void backward_error_computation(int index_lower_index, float ** local_weights, float * activation, float * error_lower_layer, float * error_higher_layer);
//compute the gradient of a single data point
void compute_gradient_single_data(int idx_data,float *** local_weights, float ** local_biases, float *** delta_weights, float ** delta_biases, float ** z, float ** delta);
//stochastic gradient descent on a mini batch
void sgd_mini_batch(int * idxes_batch, mat * weights, mat* biases, float *** local_weights, float ** local_biases, float *** delta_weights, float ** delta_biases, float ** z, float ** delta, int ** rand_idxes_weight, int * rand_idxes_bias);
//compute loss over the whole batch
float compute_loss( float*** weights, float** biases);
//compute the cross entropy loss
float compute_cross_entropy_loss(float * output, int idx_data);
//train neural network
void train(mat * weights, mat* biases);
//save model
void save_model(mat * weights, mat *biases, const char * mdl_weight_file, const char * mdl_biases_file);
public :
//constructor
dnn(dnn_paras para,int client_id, int num_worker_threads, int staleness, int num_train_data);
//init parameters
void init_paras(mat* weights, mat* biases);
//load input data
void load_data(char * data_file);
//run the whole DNN learning process
void run(std::string model_weight_file, std::string model_bias_file);
};
#endif
| 44.666667
| 242
| 0.763389
|