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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7dfd0ceed4a2830eab2de12ce82ac9daba1b10f | 7,010 | sql | SQL | application/modules/setup/sql/019_1.4.7.sql | daseparo/InvoicePlaneFIskal | dd0e99f344be138314aaf79f0cb8ce732698772c | [
"MIT"
] | 2 | 2019-04-12T06:33:49.000Z | 2019-07-03T18:00:00.000Z | application/modules/setup/sql/019_1.4.7.sql | daseparo/InvoicePlaneFIskal | dd0e99f344be138314aaf79f0cb8ce732698772c | [
"MIT"
] | null | null | null | application/modules/setup/sql/019_1.4.7.sql | daseparo/InvoicePlaneFIskal | dd0e99f344be138314aaf79f0cb8ce732698772c | [
"MIT"
] | null | null | null | # IP-406 - Update the web preview for invoices and quotes
UPDATE ip_settings
SET setting_value = 'InvoicePlane_Web'
WHERE setting_key = 'public_invoice_template' AND
setting_value = 'default';
UPDATE ip_settings
SET setting_value = 'InvoicePlane_Web'
WHERE setting_key = 'public_quote_template' AND
setting_value = 'default';
# IP-255 - Do not generate invoice number for draft invoices, set default value
INSERT INTO ip_settings (setting_key, setting_value)
VALUES ('generate_invoice_number_for_draft', '1');
INSERT INTO ip_settings (setting_key, setting_value)
VALUES ('generate_quote_number_for_draft', '1');
ALTER TABLE `ip_invoices`
MODIFY COLUMN invoice_number VARCHAR(100) NULL DEFAULT NULL;
ALTER TABLE `ip_quotes`
MODIFY COLUMN quote_number VARCHAR(100) NULL DEFAULT NULL;
# IP-408 - Add reference to products to items
ALTER TABLE `ip_invoice_items`
ADD COLUMN `item_product_id` INT(11) DEFAULT NULL
AFTER `item_tax_rate_id`;
ALTER TABLE `ip_quote_items`
ADD COLUMN `item_product_id` INT(11) DEFAULT NULL
AFTER `item_tax_rate_id`;
# IP-303 - Incorrect decimal value: '' for column 'item_discount_amount'
ALTER TABLE `ip_invoices`
MODIFY COLUMN invoice_discount_amount DECIMAL(20, 2) NULL DEFAULT NULL,
MODIFY COLUMN invoice_discount_percent DECIMAL(20, 2) NULL DEFAULT NULL;
ALTER TABLE `ip_invoice_item_amounts`
MODIFY COLUMN item_discount DECIMAL(20, 2) NULL DEFAULT NULL;
ALTER TABLE `ip_invoice_items`
MODIFY COLUMN item_discount_amount DECIMAL(20, 2) NULL DEFAULT NULL;
ALTER TABLE `ip_invoice_tax_rates`
MODIFY COLUMN invoice_tax_rate_amount DECIMAL(10, 2) NOT NULL DEFAULT 0.00;
ALTER TABLE `ip_quotes`
MODIFY COLUMN quote_discount_amount DECIMAL(20, 2) NULL DEFAULT NULL,
MODIFY COLUMN quote_discount_percent DECIMAL(20, 2) NULL DEFAULT NULL;
ALTER TABLE `ip_quote_item_amounts`
MODIFY COLUMN item_discount DECIMAL(20, 2) NULL DEFAULT NULL;
ALTER TABLE `ip_quote_items`
MODIFY COLUMN item_discount_amount DECIMAL(20, 2) NULL DEFAULT NULL;
ALTER TABLE `ip_products`
MODIFY COLUMN purchase_price DECIMAL(20, 2) NULL DEFAULT NULL;
ALTER TABLE `ip_products`
MODIFY COLUMN product_price DECIMAL(20, 2) NULL DEFAULT NULL;
# IP-322 - Invoice item_name database field should be larger + additional db changes
ALTER TABLE ip_clients
MODIFY COLUMN client_name TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_address_1 TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_address_2 TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_city TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_state TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_zip TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_country TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_phone TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_fax TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_mobile TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_email TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_web TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_vat_id TEXT;
ALTER TABLE ip_clients
MODIFY COLUMN client_tax_code TEXT;
ALTER TABLE ip_custom_fields
MODIFY COLUMN custom_field_table VARCHAR(255);
ALTER TABLE ip_custom_fields
MODIFY COLUMN custom_field_label TEXT;
ALTER TABLE ip_custom_fields
MODIFY COLUMN custom_field_column TEXT;
ALTER TABLE ip_email_templates
MODIFY COLUMN email_template_title TEXT;
ALTER TABLE ip_email_templates
MODIFY COLUMN email_template_subject TEXT;
ALTER TABLE ip_email_templates
MODIFY COLUMN email_template_from_name TEXT;
ALTER TABLE ip_email_templates
MODIFY COLUMN email_template_from_email TEXT;
ALTER TABLE ip_email_templates
MODIFY COLUMN email_template_cc TEXT;
ALTER TABLE ip_email_templates
MODIFY COLUMN email_template_bcc TEXT;
ALTER TABLE ip_families
MODIFY COLUMN family_name TEXT;
ALTER TABLE ip_invoice_groups
MODIFY COLUMN invoice_group_name TEXT;
ALTER TABLE ip_invoice_items
MODIFY COLUMN item_name TEXT DEFAULT NULL;
ALTER TABLE ip_invoice_items
MODIFY COLUMN item_description LONGTEXT DEFAULT NULL;
ALTER TABLE ip_invoice_items
MODIFY COLUMN item_price DECIMAL(20, 2) DEFAULT NULL;
ALTER TABLE ip_payment_methods
MODIFY COLUMN payment_method_name TEXT;
ALTER TABLE ip_payments
MODIFY COLUMN payment_amount DECIMAL(20, 2);
ALTER TABLE ip_products
MODIFY COLUMN product_sku TEXT;
ALTER TABLE ip_products
MODIFY COLUMN product_name TEXT;
ALTER TABLE ip_projects
MODIFY COLUMN project_name TEXT;
ALTER TABLE ip_quote_items
MODIFY COLUMN item_name TEXT DEFAULT NULL;
ALTER TABLE ip_quote_items
MODIFY COLUMN item_description TEXT DEFAULT NULL;
ALTER TABLE ip_quote_items
MODIFY COLUMN item_quantity DECIMAL(20, 2) DEFAULT NULL;
ALTER TABLE ip_quote_items
MODIFY COLUMN item_price DECIMAL(20, 2);
ALTER TABLE ip_quote_tax_rates
MODIFY COLUMN quote_tax_rate_amount DECIMAL(20, 2);
ALTER TABLE ip_tasks
MODIFY COLUMN task_name TEXT;
ALTER TABLE ip_tasks
MODIFY COLUMN task_price DECIMAL(20, 2);
ALTER TABLE ip_tax_rates
MODIFY COLUMN tax_rate_name TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_name TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_company TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_address_1 TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_address_2 TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_city TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_state TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_zip TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_country TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_phone TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_fax TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_mobile TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_email TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_web TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_vat_id TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_tax_code TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_psalt TEXT;
ALTER TABLE ip_users
MODIFY COLUMN user_tax_code TEXT;
# IP-417 - Improve product database handling
ALTER TABLE ip_products
MODIFY COLUMN family_id INT(11) NULL DEFAULT NULL;
ALTER TABLE ip_products
MODIFY COLUMN tax_rate_id INT(11) NULL DEFAULT NULL;
ALTER TABLE ip_products
ADD COLUMN provider_name TEXT NULL DEFAULT NULL
AFTER purchase_price;
# Change values for read-only setting
UPDATE ip_settings
SET setting_value = 2
WHERE setting_key = 'read_only_toggle' AND
setting_value = 'sent';
UPDATE ip_settings
SET setting_value = 3
WHERE setting_key = 'read_only_toggle' AND
setting_value = 'viewed';
UPDATE ip_settings
SET setting_value = 4
WHERE setting_key = 'read_only_toggle' AND
setting_value = 'paid';
# IP-422 - Improve session security
CREATE TABLE IF NOT EXISTS `ip_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);
| 32.757009 | 84 | 0.808417 |
46ac45031a676517750c6483b393180b84fd3e8d | 592 | ps1 | PowerShell | cicd_tools/Get-MainProjects.ps1 | rapidcore/rapidcore | 1856b53f37f2ea5d21d96b5303836bec99d1bb8a | [
"MIT"
] | 6 | 2017-05-17T12:41:39.000Z | 2022-02-08T09:48:12.000Z | cicd_tools/Get-MainProjects.ps1 | rapidcore/rapidcore | 1856b53f37f2ea5d21d96b5303836bec99d1bb8a | [
"MIT"
] | 138 | 2017-05-19T18:59:53.000Z | 2022-03-28T12:56:02.000Z | cicd_tools/Get-MainProjects.ps1 | rapidcore/rapidcore | 1856b53f37f2ea5d21d96b5303836bec99d1bb8a | [
"MIT"
] | 2 | 2019-06-22T11:46:29.000Z | 2020-01-07T11:26:25.000Z | function Get-MainProjects {
Param ([string]$relativePathToSrc)
$mainProjects = "${relativePathToSrc}core\main\rapidcore.csproj",
"${relativePathToSrc}google-cloud\main\rapidcore.google-cloud.csproj",
"${relativePathToSrc}mongo\main\rapidcore.mongo.csproj",
"${relativePathToSrc}postgresql\main\rapidcore.postgresql.csproj",
"${relativePathToSrc}redis\main\rapidcore.redis.csproj",
"${relativePathToSrc}xunit\main\rapidcore.xunit.csproj",
"${relativePathToSrc}sqlserver\main\rapidcore.sqlserver.csproj"
return $mainProjects
}
| 42.285714 | 78 | 0.721284 |
58fc271e01304d8ccad96226ff12412152ddd6f7 | 245 | lua | Lua | build/simpleKeyLog.lua | Eforen/PlutocratOS | 9a5011bcd33ab6fe0d5c89d5dbd54dd42e5e2c13 | [
"MIT"
] | null | null | null | build/simpleKeyLog.lua | Eforen/PlutocratOS | 9a5011bcd33ab6fe0d5c89d5dbd54dd42e5e2c13 | [
"MIT"
] | null | null | null | build/simpleKeyLog.lua | Eforen/PlutocratOS | 9a5011bcd33ab6fe0d5c89d5dbd54dd42e5e2c13 | [
"MIT"
] | null | null | null | --[[ Generated with https://github.com/TypeScriptToLua/TypeScriptToLua ]]
print(nil, "To exit hold CTRL+T to send Terminate Interrupt")
while true do
local event, arg1, arg2, arg3 = os.pullEvent()
print(nil, event, arg1, arg2, arg3)
end
| 35 | 73 | 0.718367 |
7116b22b9f7edc0383910e6f90db0d53c40349b2 | 895 | ts | TypeScript | src/index.ts | lwp2333/gapi-tool | 51737dfbb96b31ce28873fb06d5fecfc141a41a7 | [
"MIT"
] | null | null | null | src/index.ts | lwp2333/gapi-tool | 51737dfbb96b31ce28873fb06d5fecfc141a41a7 | [
"MIT"
] | null | null | null | src/index.ts | lwp2333/gapi-tool | 51737dfbb96b31ce28873fb06d5fecfc141a41a7 | [
"MIT"
] | null | null | null | import ora from 'ora'
import { IGapiConfig } from './interface/config'
import { configCheck } from './utils'
import { genarateAxiosFn } from './utils'
export declare function defineGapiConfig(cb: () => IGapiConfig): IGapiConfig
export const run = async () => {
const spinner = ora('配置检查中...').start()
try {
// 配置检查
// await configCheck()
// 核心工作
const taskList = Array.from(new Array(1000).keys())
const jobsNum = taskList.length
const runJobs = async () => {
const num = taskList.shift() || 0
await genarateAxiosFn(num)
const percent = (num / jobsNum) * 100
spinner.text = `当前进度${percent.toFixed(1)}%`
}
while (taskList.length) {
await runJobs()
}
// 同步完成
spinner.succeed('同步完成!')
} catch (error) {
// 同步失败
console.log(error)
spinner.fail(error as string)
}
}
| 24.861111 | 77 | 0.588827 |
dc0b9409e7e2e666fbb80bb73c135a61767a9731 | 2,926 | py | Python | src/ncarglow/plots.py | scivision/NCAR-GLOW | 09cfd372ec6f87c24f0a5c2d63f916166c1c98fa | [
"Apache-2.0"
] | 4 | 2019-06-06T15:13:51.000Z | 2021-09-16T08:50:52.000Z | src/ncarglow/plots.py | space-physics/NCAR-GLOW | 09cfd372ec6f87c24f0a5c2d63f916166c1c98fa | [
"Apache-2.0"
] | 3 | 2019-09-29T17:03:05.000Z | 2021-04-14T15:38:15.000Z | src/ncarglow/plots.py | space-physics/NCAR-GLOW | 09cfd372ec6f87c24f0a5c2d63f916166c1c98fa | [
"Apache-2.0"
] | 3 | 2019-06-06T15:07:45.000Z | 2021-10-06T16:17:11.000Z | from matplotlib.pyplot import figure
import xarray
import numpy as np
__all__ = ["precip", "ver"]
def density(iono: xarray.Dataset):
fig = figure()
axs = fig.subplots(1, 2, sharey=True)
fig.suptitle("Number Density")
ax = axs[0]
for v in ("O", "N2", "O2", "NO"):
ax.plot(iono[v], iono[v].alt_km, label=v)
ax.set_xscale("log")
ax.set_ylabel("altitude [km]")
ax.set_xlabel("Density [cm$^{-3}$]")
ax.set_title("Neutrals")
ax.grid(True)
ax.set_xlim(1, None)
ax.legend(loc="best")
ax = axs[1]
for v in ("O+", "O2+", "NO+", "N2D"):
ax.plot(iono[v], iono[v].alt_km, label=v)
ax.set_xscale("log")
ax.set_title("Ions")
ax.grid(True)
ax.set_xlim(1, None)
ax.legend(loc="best")
def precip(precip: xarray.DataArray):
ax = figure().gca()
ax.plot(precip["energy"] / 1e3, precip)
ax.set_xlabel("Energy bin centers [keV]")
ax.set_ylabel("hemispherical flux [cm$^{-2}$ s$^{-1}$ eV$^{-1}$]")
ax.set_title("precipitation: differential number flux")
ax.grid(True)
def temperature(iono: xarray.Dataset):
time = iono.time
location = iono.glatlon
tail = f"\n{time} {location}"
ax = figure().gca()
ax.plot(iono["Ti"], iono["Ti"].alt_km, label="$T_i$")
ax.plot(iono["Te"], iono["Te"].alt_km, label="$T_e$")
ax.plot(iono["Tn"], iono["Tn"].alt_km, label="$T_n$")
ax.set_xlabel("Temperature [K]")
ax.set_ylabel("altitude [km]")
ax.set_title("Ion, Electron, Neutral temperatures" + tail)
ax.grid(True)
ax.legend()
def altitude(iono: xarray.Dataset):
ax = figure().gca()
ax.plot(iono.alt_km)
ax.set_xlabel("altitude grid index #")
ax.set_ylabel("altitude [km]")
ax.set_title("altitude grid cells")
ax.grid(True)
def ver(iono: xarray.Dataset):
time = iono.time
location = iono.glatlon
tail = f"\n{time} {location}"
fig = figure(constrained_layout=True)
axs = fig.subplots(1, 3, sharey=True)
fig.suptitle(tail)
ver_group(iono["ver"].loc[:, ["4278", "5577", "6300", "5200"]], "Visible", axs[0])
ver_group(iono["ver"].loc[:, ["7320", "7774", "8446", "10400"]], "Infrared", axs[1])
ver_group(
iono["ver"].loc[:, ["3371", "3644", "3726", "1356", "1493", "1304", "LBH"]],
"Ultraviolet",
axs[2],
)
axs[0].set_ylabel("altitude [km]")
axs[0].set_xlabel("Volume Emission Rate [Rayleigh]")
def ver_group(iono: xarray.DataArray, ttxt: str, ax):
nm = np.nanmax(iono)
if nm == 0 or np.isnan(nm):
return
colors = {
"4278": "blue",
"5577": "xkcd:dark lime green",
"5200": "xkcd:golden yellow",
"6300": "red",
}
for w in iono.wavelength:
ax.plot(iono.loc[:, w], iono.alt_km, label=w.item(), color=colors.get(w.item()))
ax.set_xscale("log")
ax.set_ylim(90, 500)
ax.set_title(ttxt)
ax.grid(True)
ax.legend()
| 27.345794 | 88 | 0.585441 |
a5a843aceb8f3322ee63c9d6c92d5d36873170c6 | 771 | sql | SQL | openGaussBase/testcase/KEYWORDS/Grouping/Opengauss_Function_Keyword_Grouping_Case0035.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/KEYWORDS/Grouping/Opengauss_Function_Keyword_Grouping_Case0035.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/KEYWORDS/Grouping/Opengauss_Function_Keyword_Grouping_Case0035.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | -- @testpoint:opengauss关键字Grouping(非保留),自定义数据类型名为explain
--关键字explain作为数据类型不带引号,创建成功
drop type if exists Grouping;
CREATE TYPE Grouping AS (f1 int, f2 text);
select typname from pg_type where typname ='Grouping';
drop type Grouping;
--关键字explain作为数据类型加双引号,创建成功
drop type if exists "Grouping";
CREATE TYPE "Grouping" AS (f1 int, f2 text);
select typname from pg_type where typname ='Grouping';
drop type "Grouping";
--关键字explain作为数据类型加单引号,合理报错
drop type if exists 'Grouping';
CREATE TYPE 'Grouping' AS (f1 int, f2 text);
select * from pg_type where typname ='Grouping';
drop type 'Grouping';
--关键字explain作为数据类型加反引号,合理报错
drop type if exists `Grouping`;
CREATE TYPE `Grouping` AS (f1 int, f2 text);
select * from pg_type where typname =`Grouping`;
drop type `Grouping`; | 30.84 | 57 | 0.76524 |
f968ebf9c7907e8193311537933dd95e396c5b8e | 848 | ps1 | PowerShell | images/win/scripts/Installers/Install-PowershellCore.ps1 | dmitryikh/virtual-environments | 5ad9793f2955e4d3cbd1ea183337776b44a51a57 | [
"MIT"
] | 5,673 | 2019-09-27T23:08:40.000Z | 2022-03-31T23:57:06.000Z | images/win/scripts/Installers/Install-PowershellCore.ps1 | dmitryikh/virtual-environments | 5ad9793f2955e4d3cbd1ea183337776b44a51a57 | [
"MIT"
] | 3,368 | 2019-09-30T04:59:16.000Z | 2022-03-31T20:16:26.000Z | images/win/scripts/Installers/Install-PowershellCore.ps1 | dmitryikh/virtual-environments | 5ad9793f2955e4d3cbd1ea183337776b44a51a57 | [
"MIT"
] | 2,247 | 2019-09-29T13:59:05.000Z | 2022-03-31T21:46:45.000Z | ################################################################################
## File: Install-PowershellCore.ps1
## Desc: Install PowerShell Core
################################################################################
Invoke-Expression "& { $(Invoke-RestMethod https://aka.ms/install-powershell.ps1) } -UseMSI -Quiet"
# about_update_notifications
# While the update check happens during the first session in a given 24-hour period, for performance reasons,
# the notification will only be shown on the start of subsequent sessions.
# Also for performance reasons, the check will not start until at least 3 seconds after the session begins.
[System.Environment]::SetEnvironmentVariable("POWERSHELL_UPDATECHECK", "Off", [System.EnvironmentVariableTarget]::Machine)
Invoke-PesterTests -TestFile "Tools" -TestName "PowerShell Core"
| 56.533333 | 122 | 0.636792 |
c2fee1875eb95a65000f9c1dec46c26940b99305 | 2,902 | sql | SQL | wwwroot/ewcommon/sqlUpdate/toV4/4.1.1.89/tblCodes.sql | SteveyCoops/ProteanCMS | b934debadebb959d974350b78ac788056f03fca2 | [
"Apache-2.0"
] | 1 | 2021-04-14T18:35:44.000Z | 2021-04-14T18:35:44.000Z | wwwroot/ewcommon/sqlUpdate/toV4/4.1.1.89/tblCodes.sql | beachcomber/ProteanCMS | 8e70ce2912c60262398461b45064ee6f98df640d | [
"Apache-2.0"
] | null | null | null | wwwroot/ewcommon/sqlUpdate/toV4/4.1.1.89/tblCodes.sql | beachcomber/ProteanCMS | 8e70ce2912c60262398461b45064ee6f98df640d | [
"Apache-2.0"
] | 1 | 2020-04-27T21:56:13.000Z | 2020-04-27T21:56:13.000Z | /****** Object: Table [dbo].[tblCodes] Script Date: 03/16/2011 19:23:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
des
CREATE TABLE [dbo].[tblCodes](
[nCodeKey] [int] IDENTITY(1,1) NOT NULL,
[cCodeName] [nvarchar](50) NULL,
[nCodeType] [int] NULL,
[nCodeParentId] [int] NULL,
[cCodeGroups] [nvarchar](50) NULL,
[cCode] [nvarchar](255) NOT NULL,
[nUseId] [int] NULL,
[dUseDate] [datetime] NULL,
[nAuditId] [int] NULL,
CONSTRAINT [PK_tblCodes] PRIMARY KEY CLUSTERED
(
[nCodeKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
GO
/****** Object: StoredProcedure [dbo].[spGetCodes] Script Date: 03/16/2011 19:40:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGetCodes]
(
@type int = NULL
)
AS
BEGIN
SELECT nCodeKey,cCodeName,nCodeType,cCodeGroups ,nCodeParentId,tblAudit.dPublishDate,tblAudit.dExpireDate,tblAudit.nStatus,
((SELECT Count(child.nCodeKey) FROM tblCodes child WHERE (child.nCodeParentId = Codes.nCodeKey) AND ((child.nUseId IS NULL) OR (child.nUseId = 0) ) )) AS nUnused,
((SELECT Count(child.nCodeKey) FROM tblCodes child WHERE child.nCodeParentId = Codes.nCodeKey AND child.nUseId > 0 )) AS nUsed
FROM tblCodes Codes INNER JOIN tblAudit ON Codes.nAuditId = tblAudit.nAuditKey
WHERE
Codes.nCodeType =
CASE WHEN @type IS NULL
THEN
Codes.nCodeType
ELSE
@type
END
AND (nCodeParentId IS NULL or nCodeParentId = 0)
ORDER BY Codes.nCodeType, Codes.cCodeName
END
/****** Object: StoredProcedure [dbo].[spGetCodeDirectoryGroups] Script Date: 03/16/2011 19:41:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spGetCodeDirectoryGroups]
(
@Codes nvarchar(255) = NULL
)
AS
BEGIN
DECLARE @tblCodes TABLE (nCodeId int)
INSERT INTO @tblCodes SELECT * FROM fxn_CSVTableINTEGERS(@Codes)
--SELECT * FROM @tblCodes
DECLARE @tblGroups TABLE (nCodeKey int, nDirKey int, cDirName nvarchar(255))
DECLARE curGroups CURSOR FOR SELECT nCodeId FROM @tblCodes
DECLARE @CodeId int
OPEN curGroups
FETCH NEXT FROM curGroups INTO @CodeId
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE @GroupsString nvarchar(255)
SET @GroupsString = (SELECT cCodeGroups FROM tblCodes WHERE nCodeKey = @CodeId)
INSERT INTO @tblGroups (nCodeKey, nDirKey, cDirName)
SELECT @CodeId, groups.value, tblDirectory.cDirName
FROM fxn_CSVTableINTEGERS(@GroupsString) groups
LEFT OUTER JOIN tblDirectory ON groups.value = tblDirectory.nDirKey
--SELECT * FROM fxn_CSVTableINTEGERS(@GroupsString) groups
--LEFT OUTER JOIN tblDirectory ON groups.value = tblDirectory.nDirKey
FETCH NEXT FROM curGroups INTO @CodeId
END
CLOSE curGroups
DEALLOCATE curGroups
--Return
SELECT * FROM @tblGroups ORDER BY cDirName
END | 30.547368 | 163 | 0.732598 |
04f4dae6f777c564b7954e9f4b50e401147c8823 | 1,503 | java | Java | guokeui/src/main/java/com/guohao/guokeui/hencoder/hencoderpracticedraw6/sample/sample08/Sample08ObjectAnimatorLayout.java | guoke24/GuoKeUI | e7ceacd05bd0505e5e2f2c1edcd090a6aff9ebf7 | [
"Apache-2.0"
] | null | null | null | guokeui/src/main/java/com/guohao/guokeui/hencoder/hencoderpracticedraw6/sample/sample08/Sample08ObjectAnimatorLayout.java | guoke24/GuoKeUI | e7ceacd05bd0505e5e2f2c1edcd090a6aff9ebf7 | [
"Apache-2.0"
] | null | null | null | guokeui/src/main/java/com/guohao/guokeui/hencoder/hencoderpracticedraw6/sample/sample08/Sample08ObjectAnimatorLayout.java | guoke24/GuoKeUI | e7ceacd05bd0505e5e2f2c1edcd090a6aff9ebf7 | [
"Apache-2.0"
] | null | null | null | package com.guohao.guokeui.hencoder.hencoderpracticedraw6.sample.sample08;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import com.guohao.guokeui.R;
public class Sample08ObjectAnimatorLayout extends RelativeLayout {
Sample08ObjectAnimatorView view;
Button animateBt;
public Sample08ObjectAnimatorLayout(Context context) {
super(context);
}
public Sample08ObjectAnimatorLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Sample08ObjectAnimatorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
view = (Sample08ObjectAnimatorView) findViewById(R.id.objectAnimatorView);
animateBt = (Button) findViewById(R.id.animateBt);
animateBt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "progress", 0, 65);
animator.setDuration(1000);
animator.setInterpolator(new FastOutSlowInInterpolator());
animator.start();
}
});
}
}
| 30.673469 | 96 | 0.707917 |
8acb2e0fd18df10fda2753fef34d0603f54349b6 | 26,706 | sql | SQL | sipas_cloud.sql | rioanugrah/laravel_sipas_cloud | fc8adb76c23c2cf937d95d830dcafe0b6a4fb6f2 | [
"MIT"
] | null | null | null | sipas_cloud.sql | rioanugrah/laravel_sipas_cloud | fc8adb76c23c2cf937d95d830dcafe0b6a4fb6f2 | [
"MIT"
] | null | null | null | sipas_cloud.sql | rioanugrah/laravel_sipas_cloud | fc8adb76c23c2cf937d95d830dcafe0b6a4fb6f2 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Sep 07, 2020 at 05:28 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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: `sipas_cloud`
--
-- --------------------------------------------------------
--
-- Table structure for table `authsrc`
--
CREATE TABLE `authsrc` (
`auth_src_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`auth_src_usr` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`auth_src_provider` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`auth_src_prop` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `jab`
--
CREATE TABLE `jab` (
`jab_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`jab_nama` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
`jab_kode` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`jab_isaktif` int(11) NOT NULL,
`jab_isnomor` int(11) NOT NULL,
`jab_org` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`jab_induk` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`jab_ishapus` int(11) NOT NULL,
`jab_level` int(11) NOT NULL,
`jab_path` int(11) NOT NULL,
`jab_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `jab`
--
INSERT INTO `jab` (`jab_id`, `jab_nama`, `jab_kode`, `jab_isaktif`, `jab_isnomor`, `jab_org`, `jab_induk`, `jab_ishapus`, `jab_level`, `jab_path`, `jab_prop`) VALUES
('1', 'Administrasi Aplikasi', '5619412', 1, 157, '1', '1659124912641', 0, 1, 1, '1');
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `org`
--
CREATE TABLE `org` (
`org_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`org_nama` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_kode` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_alamat` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_telp` varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_usr` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_ishapus` int(11) DEFAULT NULL,
`org_isaktif` int(11) DEFAULT NULL,
`org_aktif_akhir_tgl` date DEFAULT NULL,
`org_tenggang_akhir_tgl` date DEFAULT NULL,
`org_status` int(11) DEFAULT NULL,
`org_tipe` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_bidang` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_provinsi` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_kota` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_induk` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_paket` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`org_prop` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `org`
--
INSERT INTO `org` (`org_id`, `org_nama`, `org_kode`, `org_alamat`, `org_telp`, `org_usr`, `org_ishapus`, `org_isaktif`, `org_aktif_akhir_tgl`, `org_tenggang_akhir_tgl`, `org_status`, `org_tipe`, `org_bidang`, `org_provinsi`, `org_kota`, `org_induk`, `org_paket`, `org_prop`) VALUES
('1', 'Sekawan Media Informatika', 'SM', 'Jl. Maninjau Raya No.29, Sawojajar, Kec. Kedungkandang, Kota Malang, Jawa Timur 65139', '03413021661', '1', 0, 1, '2020-08-02', '2020-08-05', 1, 'POLTEKOM', 'KOMINFO', 'Jawa Timur', 'Malang', NULL, '1', NULL),
('2', 'Sekawan Media', 'SM', 'Jl. Maninjau Raya No.29, Sawojajar, Kec. Kedungkandang, Kota Malang, Jawa Timur 65139', '03413021661', '3', 0, 1, '2020-08-02', '2020-08-05', 1, '-', 'KOMINFO', 'Jawa Timur', 'Malang', NULL, '3', NULL),
('3', 'Sekawan Media', 'SM', 'Jl. Maninjau Raya No.29, Sawojajar, Kec. Kedungkandang, Kota Malang, Jawa Timur 65139', '03413021661', '2', 0, 1, '2020-08-02', '2020-08-05', 1, '-', 'KOMINFO', 'Jawa Timur', 'Malang', NULL, '5', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `orgadm`
--
CREATE TABLE `orgadm` (
`org_adm_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`org_adm_user` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`org_adm_org` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`org_adm_isaktif` int(11) NOT NULL,
`org_adm_ishapus` int(11) NOT NULL,
`org_adm_role` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`org_adm_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `orgadm`
--
INSERT INTO `orgadm` (`org_adm_id`, `org_adm_user`, `org_adm_org`, `org_adm_isaktif`, `org_adm_ishapus`, `org_adm_role`, `org_adm_prop`) VALUES
('1', '1', '1', 1, 0, 'Owner', '471381'),
('2', '2', '2', 1, 0, 'Moderator', '881731'),
('3', '3', '3', 1, 0, 'Admin', '77562');
-- --------------------------------------------------------
--
-- Table structure for table `orgrole`
--
CREATE TABLE `orgrole` (
`org_role_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`org_role_nama` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
`org_role_isaktif` int(11) NOT NULL,
`org_role_akses` text COLLATE utf8mb4_unicode_ci NOT NULL,
`org_role_ishapus` int(11) NOT NULL,
`org_role_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `orgrole`
--
INSERT INTO `orgrole` (`org_role_id`, `org_role_nama`, `org_role_isaktif`, `org_role_akses`, `org_role_ishapus`, `org_role_prop`) VALUES
('1', 'Owner', 1, 'Divisi Sekretaris', 0, '88571');
-- --------------------------------------------------------
--
-- Table structure for table `paket`
--
CREATE TABLE `paket` (
`paket_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`paket_nama` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL,
`paket_tipe` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`paket_ishapus` int(11) NOT NULL,
`paket_isaktif` int(11) NOT NULL,
`paket_nominal` int(11) NOT NULL,
`paket_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `paket`
--
INSERT INTO `paket` (`paket_id`, `paket_nama`, `paket_tipe`, `paket_ishapus`, `paket_isaktif`, `paket_nominal`, `paket_prop`) VALUES
('1', 'Paket 1', 'Paket 1', 0, 2, 7500000, '573811'),
('2', 'Paket 2', 'Paket 2', 0, 0, 4500000, '51847'),
('3', 'Paket 3', 'Paket 3', 0, 0, 7500000, '18195'),
('4', 'Paket 4', 'Paket 4', 0, 0, 7500000, '99412'),
('5', 'Paket 5', 'Paket 5', 0, 1, 7500000, '99471');
-- --------------------------------------------------------
--
-- Table structure for table `payment`
--
CREATE TABLE `payment` (
`payment_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`payment_nomor` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL,
`payment_user` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`payment_tgl` datetime NOT NULL,
`payment_nominal` int(11) NOT NULL,
`payment_status` int(11) NOT NULL,
`payment_org` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`payment_subslog` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`payment_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `payment`
--
INSERT INTO `payment` (`payment_id`, `payment_nomor`, `payment_user`, `payment_tgl`, `payment_nominal`, `payment_status`, `payment_org`, `payment_subslog`, `payment_prop`) VALUES
('1', '84542', '1', '2020-09-03 10:36:19', 2500000, 1, '1', NULL, '1');
-- --------------------------------------------------------
--
-- Table structure for table `profil`
--
CREATE TABLE `profil` (
`profil_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`profil_staf` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`profil_staf_nama` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
`profil_unit` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`profil_unit_nama` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
`profil_jab` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`profil_jab_nama` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
`profil_buat_tgl` datetime NOT NULL,
`profil_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `profil`
--
INSERT INTO `profil` (`profil_id`, `profil_staf`, `profil_staf_nama`, `profil_unit`, `profil_unit_nama`, `profil_jab`, `profil_jab_nama`, `profil_buat_tgl`, `profil_prop`) VALUES
('1', '1', 'Asri Ayu', '1', 'Divisi Sekretaris', '1', 'Administrasi Aplikasi', '2020-09-03 08:44:34', '1');
-- --------------------------------------------------------
--
-- Table structure for table `prop`
--
CREATE TABLE `prop` (
`prop_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`prop_buat_staf` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`prop_buat_tgl` datetime DEFAULT NULL,
`prop_ubah_staf` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`prop_ubah_tgl` datetime DEFAULT NULL,
`prop_hapus_staf` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`prop_hapus_tgl` datetime DEFAULT NULL,
`prop_entitas_id` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`prop_entitas` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`prop_slug` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `prop`
--
INSERT INTO `prop` (`prop_id`, `prop_buat_staf`, `prop_buat_tgl`, `prop_ubah_staf`, `prop_ubah_tgl`, `prop_hapus_staf`, `prop_hapus_tgl`, `prop_entitas_id`, `prop_entitas`, `prop_slug`) VALUES
('1', '1', '2020-09-04 09:45:15', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `propbuatdata`
--
CREATE TABLE `propbuatdata` (
`prop_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`prop_data` text COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `propbuatdata`
--
INSERT INTO `propbuatdata` (`prop_id`, `prop_data`) VALUES
('1', 'Hello');
-- --------------------------------------------------------
--
-- Table structure for table `prophapusdata`
--
CREATE TABLE `prophapusdata` (
`prop_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`prop_data` text COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `propubahdata`
--
CREATE TABLE `propubahdata` (
`prop_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`prop_data` text COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `staf`
--
CREATE TABLE `staf` (
`staf_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_nama` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_peran` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_kode` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_isaktif` int(11) NOT NULL,
`staf_kelamin` int(11) NOT NULL,
`staf_ishapus` int(11) NOT NULL,
`staf_org` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_unit` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_jab` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_usr` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_profil` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`staf_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `staf`
--
INSERT INTO `staf` (`staf_id`, `staf_nama`, `staf_peran`, `staf_kode`, `staf_isaktif`, `staf_kelamin`, `staf_ishapus`, `staf_org`, `staf_unit`, `staf_jab`, `staf_usr`, `staf_profil`, `staf_prop`) VALUES
('1', 'Administrasi Server', 'Divisi Teknis', '163812', 1, 1, 0, '1', '1', '1', '1', '1', '1');
-- --------------------------------------------------------
--
-- Table structure for table `subslog`
--
CREATE TABLE `subslog` (
`subslog_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`subslog_paket_nama` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL,
`subslog_paket_storage` int(11) NOT NULL,
`subslog_jumlah_user` int(11) NOT NULL,
`subslog_org` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`subslog_jumlah_unit` int(11) NOT NULL,
`subslog_jabatan` int(11) NOT NULL,
`subslog_payment_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`subslog_jumlah_surat` int(11) NOT NULL,
`subslog_jumlah_disposisi` int(11) NOT NULL,
`subslog_jumlah_arsip` int(11) NOT NULL,
`subslog_jumlah_dokumen` int(11) NOT NULL,
`subslog_payment_tgl` date NOT NULL,
`subslog_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `subslog`
--
INSERT INTO `subslog` (`subslog_id`, `subslog_paket_nama`, `subslog_paket_storage`, `subslog_jumlah_user`, `subslog_org`, `subslog_jumlah_unit`, `subslog_jabatan`, `subslog_payment_id`, `subslog_jumlah_surat`, `subslog_jumlah_disposisi`, `subslog_jumlah_arsip`, `subslog_jumlah_dokumen`, `subslog_payment_tgl`, `subslog_prop`) VALUES
('1', '1', 15, 55, '1', 15, 1, '1', 1, 1, 1, 1, '2020-09-03', '1');
-- --------------------------------------------------------
--
-- Table structure for table `unit`
--
CREATE TABLE `unit` (
`unit_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_nama` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_kode` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_rubrik` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_isaktif` int(11) NOT NULL,
`unit_org` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_induk` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_ishapus` int(11) NOT NULL,
`unit_manager` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_level` text COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_path` text COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_prop` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `unit`
--
INSERT INTO `unit` (`unit_id`, `unit_nama`, `unit_kode`, `unit_rubrik`, `unit_isaktif`, `unit_org`, `unit_induk`, `unit_ishapus`, `unit_manager`, `unit_level`, `unit_path`, `unit_prop`) VALUES
('1', 'Divisi Kesekretariatan', '5712128', '-', 1, '1', '58819992612', 0, 'Atasan', 'hiuashiashdzxnczxnckahsdl', 'ahschakshcjkahckjac', '1');
-- --------------------------------------------------------
--
-- Table structure for table `unitcakupan`
--
CREATE TABLE `unitcakupan` (
`unit_cakupan_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_cakupan_unit` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`unit_cakupan_jab` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `unitcakupan`
--
INSERT INTO `unitcakupan` (`unit_cakupan_id`, `unit_cakupan_unit`, `unit_cakupan_jab`) VALUES
('1', '1', '1');
-- --------------------------------------------------------
--
-- Table structure for table `usr`
--
CREATE TABLE `usr` (
`usr_id` varchar(36) COLLATE utf8mb4_unicode_ci NOT NULL,
`usr_nama` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL,
`usr_email` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL,
`usr_sandi` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
`usr_isaktif` int(11) NOT NULL,
`usr_registrasi_tgl` date NOT NULL,
`usr_registrasi_status` int(11) NOT NULL,
`usr_staf` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`usr_org` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`usr_auth` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`usr_ishapus` int(11) NOT NULL,
`usr_lastmasuk` datetime NOT NULL,
`usr_prop` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `usr`
--
INSERT INTO `usr` (`usr_id`, `usr_nama`, `usr_email`, `usr_sandi`, `usr_isaktif`, `usr_registrasi_tgl`, `usr_registrasi_status`, `usr_staf`, `usr_org`, `usr_auth`, `usr_ishapus`, `usr_lastmasuk`, `usr_prop`) VALUES
('1', 'Asri Ayu', 'asriayu@gmail.com', '0192023a7bbd73250516f069df18b500', 1, '2020-09-01', 1, NULL, NULL, NULL, 0, '2020-09-01 09:00:41', NULL),
('2', 'Drs. Ayudia Ana S.E.', 'ayudiana@gmail.com', '0192023a7bbd73250516f069df18b500', 1, '2020-09-01', 1, NULL, NULL, NULL, 0, '2020-09-01 09:01:19', NULL),
('3', 'Drs. Adam Aditya, S.H.', 'adamaditya@gmail.com', '0192023a7bbd73250516f069df18b500', 1, '2020-09-01', 1, NULL, NULL, NULL, 0, '2020-09-01 09:02:12', NULL);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `authsrc`
--
ALTER TABLE `authsrc`
ADD PRIMARY KEY (`auth_src_id`),
ADD UNIQUE KEY `authsrc_auth_src_usr_unique` (`auth_src_usr`),
ADD UNIQUE KEY `authsrc_auth_src_provider_unique` (`auth_src_provider`),
ADD UNIQUE KEY `authsrc_auth_src_prop_unique` (`auth_src_prop`);
--
-- Indexes for table `jab`
--
ALTER TABLE `jab`
ADD PRIMARY KEY (`jab_id`),
ADD UNIQUE KEY `jab_jab_org_unique` (`jab_org`),
ADD UNIQUE KEY `jab_jab_induk_unique` (`jab_induk`),
ADD UNIQUE KEY `jab_jab_prop_unique` (`jab_prop`),
ADD KEY `jab_jab_nama_index` (`jab_nama`),
ADD KEY `jab_jab_kode_index` (`jab_kode`);
--
-- Indexes for table `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `org`
--
ALTER TABLE `org`
ADD PRIMARY KEY (`org_id`),
ADD UNIQUE KEY `org_org_usr_unique` (`org_usr`),
ADD UNIQUE KEY `org_org_induk_unique` (`org_induk`),
ADD UNIQUE KEY `org_org_paket_unique` (`org_paket`),
ADD UNIQUE KEY `org_org_prop_unique` (`org_prop`),
ADD KEY `org_org_nama_index` (`org_nama`),
ADD KEY `org_org_kode_index` (`org_kode`),
ADD KEY `org_org_alamat_index` (`org_alamat`(768));
--
-- Indexes for table `orgadm`
--
ALTER TABLE `orgadm`
ADD PRIMARY KEY (`org_adm_id`),
ADD UNIQUE KEY `orgadm_org_adm_user_unique` (`org_adm_user`),
ADD UNIQUE KEY `orgadm_org_adm_org_unique` (`org_adm_org`),
ADD UNIQUE KEY `orgadm_org_adm_prop_unique` (`org_adm_prop`);
--
-- Indexes for table `orgrole`
--
ALTER TABLE `orgrole`
ADD PRIMARY KEY (`org_role_id`),
ADD UNIQUE KEY `orgrole_org_role_prop_unique` (`org_role_prop`),
ADD KEY `orgrole_org_role_nama_index` (`org_role_nama`);
--
-- Indexes for table `paket`
--
ALTER TABLE `paket`
ADD PRIMARY KEY (`paket_id`),
ADD UNIQUE KEY `paket_paket_prop_unique` (`paket_prop`),
ADD KEY `paket_paket_nama_index` (`paket_nama`);
--
-- Indexes for table `payment`
--
ALTER TABLE `payment`
ADD PRIMARY KEY (`payment_id`),
ADD UNIQUE KEY `payment_payment_user_unique` (`payment_user`),
ADD UNIQUE KEY `payment_payment_org_unique` (`payment_org`),
ADD UNIQUE KEY `payment_payment_prop_unique` (`payment_prop`),
ADD UNIQUE KEY `payment_payment_sublog_unique` (`payment_subslog`),
ADD KEY `payment_payment_nomor_index` (`payment_nomor`);
--
-- Indexes for table `profil`
--
ALTER TABLE `profil`
ADD PRIMARY KEY (`profil_id`),
ADD UNIQUE KEY `profil_profil_staf_unique` (`profil_staf`),
ADD UNIQUE KEY `profil_profil_unit_unique` (`profil_unit`),
ADD UNIQUE KEY `profil_profil_jab_unique` (`profil_jab`),
ADD UNIQUE KEY `profil_profil_prop_unique` (`profil_prop`),
ADD KEY `profil_profil_staf_nama_index` (`profil_staf_nama`),
ADD KEY `profil_profil_unit_nama_index` (`profil_unit_nama`),
ADD KEY `profil_profil_jab_nama_index` (`profil_jab_nama`),
ADD KEY `profil_profil_buat_tgl_index` (`profil_buat_tgl`);
--
-- Indexes for table `prop`
--
ALTER TABLE `prop`
ADD PRIMARY KEY (`prop_id`),
ADD UNIQUE KEY `prop_prop_buat_staf_unique` (`prop_buat_staf`),
ADD UNIQUE KEY `prop_prop_ubah_staf_unique` (`prop_ubah_staf`),
ADD UNIQUE KEY `prop_prop_hapus_staf_unique` (`prop_hapus_staf`),
ADD KEY `prop_prop_buat_tgl_index` (`prop_buat_tgl`),
ADD KEY `prop_prop_ubah_tgl_index` (`prop_ubah_tgl`),
ADD KEY `prop_prop_hapus_tgl_index` (`prop_hapus_tgl`),
ADD KEY `prop_prop_entitas_index` (`prop_entitas`),
ADD KEY `prop_prop_slug_index` (`prop_slug`);
--
-- Indexes for table `propbuatdata`
--
ALTER TABLE `propbuatdata`
ADD PRIMARY KEY (`prop_id`);
--
-- Indexes for table `prophapusdata`
--
ALTER TABLE `prophapusdata`
ADD PRIMARY KEY (`prop_id`);
--
-- Indexes for table `propubahdata`
--
ALTER TABLE `propubahdata`
ADD PRIMARY KEY (`prop_id`);
--
-- Indexes for table `staf`
--
ALTER TABLE `staf`
ADD PRIMARY KEY (`staf_id`),
ADD UNIQUE KEY `staf_peran` (`staf_peran`),
ADD UNIQUE KEY `staf_org` (`staf_org`),
ADD UNIQUE KEY `staf_unit` (`staf_unit`),
ADD UNIQUE KEY `staf_jab` (`staf_jab`,`staf_usr`,`staf_profil`,`staf_prop`),
ADD KEY `staf_nama` (`staf_nama`),
ADD KEY `staf_kode` (`staf_kode`),
ADD KEY `staf_usr` (`staf_usr`);
--
-- Indexes for table `subslog`
--
ALTER TABLE `subslog`
ADD PRIMARY KEY (`subslog_id`),
ADD UNIQUE KEY `subslog_subslog_org_unique` (`subslog_org`),
ADD UNIQUE KEY `subslog_subslog_payment_id_unique` (`subslog_payment_id`),
ADD KEY `subslog_subslog_paket_nama_index` (`subslog_paket_nama`),
ADD KEY `subslog_subslog_paket_storage_index` (`subslog_paket_storage`);
--
-- Indexes for table `unit`
--
ALTER TABLE `unit`
ADD PRIMARY KEY (`unit_id`),
ADD UNIQUE KEY `unit_unit_org_unique` (`unit_org`),
ADD UNIQUE KEY `unit_unit_induk_unique` (`unit_induk`),
ADD UNIQUE KEY `unit_unit_manager_unique` (`unit_manager`),
ADD UNIQUE KEY `unit_unit_prop_unique` (`unit_prop`),
ADD KEY `unit_unit_nama_index` (`unit_nama`),
ADD KEY `unit_unit_kode_index` (`unit_kode`),
ADD KEY `unit_unit_rubrik_index` (`unit_rubrik`);
--
-- Indexes for table `unitcakupan`
--
ALTER TABLE `unitcakupan`
ADD PRIMARY KEY (`unit_cakupan_id`),
ADD UNIQUE KEY `unitcakupan_unit_cakupan_unit_unique` (`unit_cakupan_unit`),
ADD UNIQUE KEY `unitcakupan_unit_cakupan_jab_unique` (`unit_cakupan_jab`);
--
-- Indexes for table `usr`
--
ALTER TABLE `usr`
ADD PRIMARY KEY (`usr_id`),
ADD UNIQUE KEY `usr_usr_prop_unique` (`usr_prop`),
ADD UNIQUE KEY `usr_usr_staf_unique` (`usr_staf`),
ADD UNIQUE KEY `usr_usr_org_unique` (`usr_org`),
ADD UNIQUE KEY `usr_usr_auth_unique` (`usr_auth`),
ADD KEY `usr_usr_nama_index` (`usr_nama`),
ADD KEY `usr_usr_email_index` (`usr_email`),
ADD KEY `usr_usr_registrasi_tgl_index` (`usr_registrasi_tgl`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `authsrc`
--
ALTER TABLE `authsrc`
ADD CONSTRAINT `authsrc_ibfk_1` FOREIGN KEY (`auth_src_usr`) REFERENCES `usr` (`usr_id`);
--
-- Constraints for table `jab`
--
ALTER TABLE `jab`
ADD CONSTRAINT `jab_ibfk_1` FOREIGN KEY (`jab_org`) REFERENCES `org` (`org_id`);
--
-- Constraints for table `org`
--
ALTER TABLE `org`
ADD CONSTRAINT `org_ibfk_2` FOREIGN KEY (`org_paket`) REFERENCES `paket` (`paket_id`),
ADD CONSTRAINT `org_ibfk_3` FOREIGN KEY (`org_usr`) REFERENCES `usr` (`usr_id`);
--
-- Constraints for table `orgadm`
--
ALTER TABLE `orgadm`
ADD CONSTRAINT `orgadm_ibfk_2` FOREIGN KEY (`org_adm_org`) REFERENCES `org` (`org_id`),
ADD CONSTRAINT `orgadm_ibfk_3` FOREIGN KEY (`org_adm_user`) REFERENCES `usr` (`usr_id`);
--
-- Constraints for table `payment`
--
ALTER TABLE `payment`
ADD CONSTRAINT `payment_ibfk_1` FOREIGN KEY (`payment_org`) REFERENCES `org` (`org_id`),
ADD CONSTRAINT `payment_ibfk_2` FOREIGN KEY (`payment_subslog`) REFERENCES `subslog` (`subslog_id`);
--
-- Constraints for table `profil`
--
ALTER TABLE `profil`
ADD CONSTRAINT `profil_ibfk_1` FOREIGN KEY (`profil_jab`) REFERENCES `jab` (`jab_id`),
ADD CONSTRAINT `profil_ibfk_2` FOREIGN KEY (`profil_unit`) REFERENCES `unit` (`unit_id`),
ADD CONSTRAINT `profil_ibfk_3` FOREIGN KEY (`profil_staf`) REFERENCES `staf` (`staf_id`);
--
-- Constraints for table `prop`
--
ALTER TABLE `prop`
ADD CONSTRAINT `prop_ibfk_1` FOREIGN KEY (`prop_buat_staf`) REFERENCES `propbuatdata` (`prop_id`) ON UPDATE CASCADE,
ADD CONSTRAINT `prop_ibfk_2` FOREIGN KEY (`prop_ubah_staf`) REFERENCES `propubahdata` (`prop_id`) ON UPDATE CASCADE,
ADD CONSTRAINT `prop_ibfk_3` FOREIGN KEY (`prop_hapus_staf`) REFERENCES `prophapusdata` (`prop_id`) ON DELETE CASCADE;
--
-- Constraints for table `staf`
--
ALTER TABLE `staf`
ADD CONSTRAINT `staf_ibfk_1` FOREIGN KEY (`staf_unit`) REFERENCES `unit` (`unit_id`),
ADD CONSTRAINT `staf_ibfk_2` FOREIGN KEY (`staf_jab`) REFERENCES `jab` (`jab_id`),
ADD CONSTRAINT `staf_ibfk_3` FOREIGN KEY (`staf_usr`) REFERENCES `usr` (`usr_id`),
ADD CONSTRAINT `staf_ibfk_4` FOREIGN KEY (`staf_org`) REFERENCES `org` (`org_id`);
--
-- Constraints for table `subslog`
--
ALTER TABLE `subslog`
ADD CONSTRAINT `subslog_ibfk_1` FOREIGN KEY (`subslog_payment_id`) REFERENCES `payment` (`payment_id`);
--
-- Constraints for table `unit`
--
ALTER TABLE `unit`
ADD CONSTRAINT `unit_ibfk_1` FOREIGN KEY (`unit_org`) REFERENCES `org` (`org_id`);
--
-- Constraints for table `unitcakupan`
--
ALTER TABLE `unitcakupan`
ADD CONSTRAINT `unitcakupan_ibfk_1` FOREIGN KEY (`unit_cakupan_unit`) REFERENCES `unit` (`unit_id`),
ADD CONSTRAINT `unitcakupan_ibfk_2` FOREIGN KEY (`unit_cakupan_jab`) REFERENCES `jab` (`jab_id`);
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 */;
| 37.298883 | 333 | 0.703475 |
53e8acbfa692ab646840fd433685b525e55a2792 | 1,222 | kt | Kotlin | app/src/main/java/com/rodrigodominguez/mixanimationsmotionlayout/rotationcard/RotationCardHomeActivity.kt | rodrigomartind/MixAnimationsMotionLayout | 17e3d8ad36a3b9806c828bd03cc71eb37af789dc | [
"Apache-2.0"
] | 527 | 2020-06-03T22:28:00.000Z | 2022-03-15T03:14:50.000Z | app/src/main/java/com/rodrigodominguez/mixanimationsmotionlayout/rotationcard/RotationCardHomeActivity.kt | doctorcode9/MixAnimationsMotionLayout | 291f7dd40baa19cfb5c550db0cae1dcbdfbf6912 | [
"Apache-2.0"
] | 2 | 2020-08-18T17:22:43.000Z | 2021-07-18T00:47:46.000Z | app/src/main/java/com/rodrigodominguez/mixanimationsmotionlayout/rotationcard/RotationCardHomeActivity.kt | doctorcode9/MixAnimationsMotionLayout | 291f7dd40baa19cfb5c550db0cae1dcbdfbf6912 | [
"Apache-2.0"
] | 60 | 2020-06-03T22:28:06.000Z | 2022-03-20T11:21:45.000Z | package com.rodrigodominguez.mixanimationsmotionlayout.rotationcard
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.rodrigodominguez.mixanimationsmotionlayout.R
import com.rodrigodominguez.mixanimationsmotionlayout.rotationcard.scenes.RotationCardScene1Activity
import com.rodrigodominguez.mixanimationsmotionlayout.rotationcard.scenes.RotationCardScene2Activity
import kotlinx.android.synthetic.main.activity_rotation_card_home.*
class RotationCardHomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rotation_card_home)
demoRotationCard.setOnClickListener {
startActivity(
Intent(this, RotationCardDemoActivity::class.java)
)
}
rotationCardScene1.setOnClickListener {
startActivity(
Intent(this, RotationCardScene1Activity::class.java)
)
}
rotationCardScene2.setOnClickListener {
startActivity(
Intent(this, RotationCardScene2Activity::class.java)
)
}
}
} | 39.419355 | 100 | 0.734861 |
0342fe203cbcfd0590cf1d06a60c9e4d62b0d3d5 | 2,115 | ps1 | PowerShell | Cas/CAS-CreateJob-SubjectNode.ps1 | Cinegy/powershell | 0d1cc61ac9174445108b015e28bc353630dfb5c9 | [
"Apache-2.0"
] | null | null | null | Cas/CAS-CreateJob-SubjectNode.ps1 | Cinegy/powershell | 0d1cc61ac9174445108b015e28bc353630dfb5c9 | [
"Apache-2.0"
] | null | null | null | Cas/CAS-CreateJob-SubjectNode.ps1 | Cinegy/powershell | 0d1cc61ac9174445108b015e28bc353630dfb5c9 | [
"Apache-2.0"
] | null | null | null | Param(
[Parameter(Mandatory=$true)][string]$JobDropTargetId,
[Parameter(Mandatory=$true)][string]$SubjectNodeId,
[Parameter(Mandatory=$false)][string]$JobName="",
[Parameter(Mandatory=$false)][bool]$CreateDisabled=$false)
# $JobDropTargetId = job drop target node id where new job should be created
# $SubjectNodeId = node id to be added to the job drop target
# $JobName = (optional) job name to be created, default is "New Job"
# $CreateDisabled = (optional) specifies whether the job should be created as disabled, default is "FALSE"
. .\CAS-Core.ps1
# connect to CAS
$context = Get-CasContext
# find job drop target to be used
$jobDropTargetNodeResult = Invoke-CasMethod -MethodRelativeUrl "/node/$($JobDropTargetId)?f=1" -Context $context
if($jobDropTargetNodeResult.retCode -ne 0)
{
Write-Host "Failed to locate the job drop target node [$JobDropTargetId]: $($jobDropTargetNodeResult.error)"
}
else
{
# find subject node to be added
$subjectNodeResult = Invoke-CasMethod -MethodRelativeUrl "/node/$($SubjectNodeId)?f=1" -Context $context
if($subjectNodeResult.retCode -ne 0)
{
Write-Host "Failed to locate the subject node [$SubjectNodeId]: $($subjectNodeResult.error)"
}
else
{
# job creation parameters
$jobParameters = [PSCustomObject]@{
parent_id = $jobDropTargetId
name = $JobName
job_disabled = $CreateDisabled
subjects = @( $subjectNodeResult.node.node )
}
# generate request body, use Depth to properly serialize "subjects"
$parametersJson = (ConvertTo-Json -InputObject $jobParameters -Depth 3)
# create job node
$response = Invoke-CasMethod -MethodRelativeUrl '/createjob' -Method POST -Body $parametersJson -Context $context
if($response.retCode -ne 0)
{
Write-Host "Failed to create job: $($response.error)"
}
else
{
Write-Host "Created new job with ID [$($response.node._id._nodeid_id)]"
}
}
}
# logout session
Invoke-CasLogout -Context $context
| 34.672131 | 123 | 0.669504 |
904d0869e6add979fded32c2885974590007c47a | 5,996 | py | Python | FALCON/src/train_test/train.py | zijiantang168/Reproducability-FALCON | eef9d8d72ae3b763d6a88107b90db9533afedd9e | [
"Apache-2.0"
] | null | null | null | FALCON/src/train_test/train.py | zijiantang168/Reproducability-FALCON | eef9d8d72ae3b763d6a88107b90db9533afedd9e | [
"Apache-2.0"
] | null | null | null | FALCON/src/train_test/train.py | zijiantang168/Reproducability-FALCON | eef9d8d72ae3b763d6a88107b90db9533afedd9e | [
"Apache-2.0"
] | 1 | 2021-05-13T13:52:37.000Z | 2021-05-13T13:52:37.000Z | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
FALCON: FAst and Lightweight CONvolution
File: train_test/train.py
- Contain training code for execution for model.
Version: 1.0
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import time
from train_test.validation import validation
from utils.optimizer_option import get_optimizer
from utils.load_data import load_cifar10, load_cifar100, load_svhn, load_mnist, load_tiny_imagenet
from utils.lr_decay import adjust_lr
def train(net,
lr,
log=None,
optimizer_option='SGD',
data='cifar100',
epochs=200,
batch_size=128,
is_train=True,
net_st=None,
beta=0.0,
lrd=10):
"""
Train the model.
:param net: model to be trained
:param lr: learning rate
:param optimizer_option: optimizer type
:param data: datasets used to train
:param epochs: number of training epochs
:param batch_size: batch size
:param is_train: whether it is a training process
:param net_st: uncompressed model
:param beta: transfer parameter
"""
net.train()
if net_st != None:
net_st.eval()
if data == 'cifar10':
trainloader = load_cifar10(is_train, batch_size)
valloader = load_cifar10(False, batch_size)
elif data == 'cifar100':
trainloader = load_cifar100(is_train, batch_size)
valloader = load_cifar100(False, batch_size)
elif data == 'svhn':
trainloader = load_svhn(is_train, batch_size)
valloader = load_svhn(False, batch_size)
elif data == 'mnist':
trainloader = load_mnist(is_train, batch_size)
elif data == 'tinyimagenet':
trainloader, valloader = load_tiny_imagenet(is_train, batch_size)
else:
exit()
criterion = nn.CrossEntropyLoss()
criterion_mse = nn.MSELoss()
optimizer = get_optimizer(net, lr, optimizer_option)
start_time = time.time()
last_time = 0
best_acc = 0
best_param = net.state_dict()
iteration = 0
outputfile = open(str(start_time) + ".txt", "w")
for epoch in range(epochs):
print("****************** EPOCH = %d ******************" % epoch)
if log != None:
log.write("****************** EPOCH = %d ******************\n" % epoch)
total = 0
correct = 0
loss_sum = 0
# change learning rate
if epoch == 150 or epoch == 250:
lr = adjust_lr(lr, lrd=lrd, log=log)
optimizer = get_optimizer(net, lr, optimizer_option)
for i, data in enumerate(trainloader, 0):
iteration += 1
# foward
inputs, labels = data
inputs_V, labels_V = Variable(inputs.cuda()), Variable(labels.cuda())
outputs, outputs_conv = net(inputs_V)
loss = criterion(outputs, labels_V)
if net_st != None:
outputs_st, outputs_st_conv = net_st(inputs_V)
# loss += beta * transfer_loss(outputs_conv, outputs_st_conv)
for i in range(len(outputs_st_conv)):
# print("!!!!! %d" % i)
if i != (len(outputs_st_conv)-1):
loss += beta / 50 * criterion_mse(outputs_conv[i], outputs_st_conv[i].detach())
else:
loss += beta * criterion_mse(outputs_conv[i], outputs_st_conv[i].detach())
# backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
_, predicted = torch.max(F.softmax(outputs, -1), 1)
total += labels_V.size(0)
correct += (predicted == labels_V).sum()
loss_sum += loss
if iteration % 100 == 99:
now_time = time.time()
accuracy_xy = (float(100) * float(correct) / float(total))
print('accuracy: %f %%; loss: %f; time: %ds'
% (accuracy_xy, loss, (now_time - last_time)))
outputfile.write("%f %f %d\n" % (accuracy_xy, loss, iteration))
outputfile.flush()
if log != None:
log.write('accuracy: %f %%; loss: %f; time: %ds\n'
% ((float(100) * float(correct) / float(total)), loss, (now_time - last_time)))
total = 0
correct = 0
loss_sum = 0
last_time = now_time
# validation
if data == 'tinyimagenet':
if epoch % 10 == 9:
net.eval()
val_acc = validation(net, valloader, log)
net.train()
if val_acc > best_acc:
best_acc = val_acc
best_param = net.state_dict()
else:
if epoch % 10 == 9:
best_param = net.state_dict()
net.eval()
validation(net, valloader, log)
net.train()
outputfile.close()
print('Finished Training. It took %ds in total' % (time.time() - start_time))
if log != None:
log.write('Finished Training. It took %ds in total\n' % (time.time() - start_time))
return best_param
| 32.945055 | 109 | 0.58072 |
39b6b268199ed1897906826fabde0d9ea26d22c0 | 182 | swift | Swift | Tuna/Tuna/Internal/Networking/Models/StartSessionResponse.swift | tuna-software/ios-core-sdk | 3ad9d94cd42705b98e29d2a416abc3873e9b1cd0 | [
"BSD-2-Clause"
] | 1 | 2021-06-25T15:30:57.000Z | 2021-06-25T15:30:57.000Z | Tuna/Tuna/Internal/Networking/Models/StartSessionResponse.swift | tuna-software/ios-core-sdk | 3ad9d94cd42705b98e29d2a416abc3873e9b1cd0 | [
"BSD-2-Clause"
] | null | null | null | Tuna/Tuna/Internal/Networking/Models/StartSessionResponse.swift | tuna-software/ios-core-sdk | 3ad9d94cd42705b98e29d2a416abc3873e9b1cd0 | [
"BSD-2-Clause"
] | null | null | null | //
// StartSessionResponse.swift
// Tuna
//
// Created by Guilherme Rambo on 24/03/21.
//
import Foundation
struct StartSessionResponse: Decodable {
let sessionId: String
}
| 14 | 43 | 0.708791 |
4529b4c0669b553d91834f2836935fff0ed7df36 | 6,732 | sql | SQL | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5455620_sys_FRESH-1236-customer-vendor-subtab-bpartner-webui.sql | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5455620_sys_FRESH-1236-customer-vendor-subtab-bpartner-webui.sql | vestigegroup/metasfresh | 4b2d48c091fb2a73e6f186260a06c715f5e2fe96 | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5455620_sys_FRESH-1236-customer-vendor-subtab-bpartner-webui.sql | vestigegroup/metasfresh | 4b2d48c091fb2a73e6f186260a06c715f5e2fe96 | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z | -- 27.01.2017 10:58
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayed='Y',Updated=TO_TIMESTAMP('2017-01-27 10:58:16','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000245
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsAdvancedField='Y',Updated=TO_TIMESTAMP('2017-01-27 10:59:36','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000245
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=10,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000245
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=20,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000253
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=30,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000260
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=40,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000254
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=50,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000249
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=60,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000250
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=70,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000251
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=80,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000252
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=90,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000255
;
-- 27.01.2017 10:59
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=100,Updated=TO_TIMESTAMP('2017-01-27 10:59:51','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000266
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsAdvancedField='Y', IsDisplayed='Y',Updated=TO_TIMESTAMP('2017-01-27 11:01:45','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000276
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=10,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000276
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=20,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000277
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=30,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000278
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=40,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000271
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=50,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000281
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=60,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000273
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=70,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000279
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=80,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000274
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=90,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000280
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=100,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000282
;
-- 27.01.2017 11:01
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsDisplayedGrid='Y', SeqNoGrid=110,Updated=TO_TIMESTAMP('2017-01-27 11:01:57','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000283
;
-- 27.01.2017 11:04
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsAdvancedField='N',Updated=TO_TIMESTAMP('2017-01-27 11:04:21','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000245
;
-- 27.01.2017 11:06
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_UI_Element SET IsAdvancedField='N',Updated=TO_TIMESTAMP('2017-01-27 11:06:41','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_UI_Element_ID=1000276
;
| 51.389313 | 174 | 0.785205 |
4efddd29a98b19030d2cbb25880c9beda285031b | 463 | sql | SQL | scripts/remove.sql | esther509/uag-db-netflix | 247ca70bbd092480931bcba8dcf3dca526e5ecb3 | [
"MIT"
] | null | null | null | scripts/remove.sql | esther509/uag-db-netflix | 247ca70bbd092480931bcba8dcf3dca526e5ecb3 | [
"MIT"
] | null | null | null | scripts/remove.sql | esther509/uag-db-netflix | 247ca70bbd092480931bcba8dcf3dca526e5ecb3 | [
"MIT"
] | null | null | null | DROP TABLE IF EXISTS public.directed_by;
DROP TABLE IF EXISTS public.acts_in;
DROP TABLE IF EXISTS public.watched_by;
DROP TABLE IF EXISTS public.commented_by;
DROP TABLE IF EXISTS public.rated_by;
DROP TABLE IF EXISTS public.movie_category;
DROP TABLE IF EXISTS public.movie_award;
DROP TABLE IF EXISTS public.movie;
DROP TABLE IF EXISTS public.director;
DROP TABLE IF EXISTS public.user;
DROP TABLE IF EXISTS public.award;
DROP TABLE IF EXISTS public.category;
| 35.615385 | 43 | 0.818575 |
fe0f6e5b339c9ad3019d13ec187c7fd2af164a80 | 26 | asm | Assembly | pkgs/tools/yasm/src/modules/objfmts/bin/tests/multisect/vfollows-notfound-err.asm | manggoguy/parsec-modified | d14edfb62795805c84a4280d67b50cca175b95af | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | pkgs/tools/yasm/src/modules/objfmts/bin/tests/multisect/vfollows-notfound-err.asm | manggoguy/parsec-modified | d14edfb62795805c84a4280d67b50cca175b95af | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | pkgs/tools/yasm/src/modules/objfmts/bin/tests/multisect/vfollows-notfound-err.asm | manggoguy/parsec-modified | d14edfb62795805c84a4280d67b50cca175b95af | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | section foo vfollows=bar
| 8.666667 | 24 | 0.807692 |
071cdcec201319ee722df54114a460b4ba2194a3 | 2,605 | sql | SQL | gpff-sql/procedures/tablehelp/procCountTableHelp.sql | jestevez/portfolio-trusts-funds | 0ec2e8431587209f7b59b55b3692ec24a84a8b78 | [
"Apache-2.0"
] | 1 | 2019-07-02T10:01:31.000Z | 2019-07-02T10:01:31.000Z | gpff-sql/procedures/tablehelp/procCountTableHelp.sql | jestevez/portfolio-trusts-funds | 0ec2e8431587209f7b59b55b3692ec24a84a8b78 | [
"Apache-2.0"
] | null | null | null | gpff-sql/procedures/tablehelp/procCountTableHelp.sql | jestevez/portfolio-trusts-funds | 0ec2e8431587209f7b59b55b3692ec24a84a8b78 | [
"Apache-2.0"
] | 1 | 2021-04-21T18:52:59.000Z | 2021-04-21T18:52:59.000Z |
--DROP PROCEDURE GPSQLWEB.procCountTableHelp
CREATE PROCEDURE GPSQLWEB.procCountTableHelp (
IN P_ID INTEGER ,
IN P_CODE varchar(2) ,
IN P_NAME varchar(100) ,
IN P_TABLENAME varchar(100) ,
IN P_TABLECODE varchar(100) ,
IN P_TABLEDESC varchar(100) ,
IN P_TABLEPARENT varchar(100) ,
IN P_USERNAME VARCHAR(50),
IN P_IPADDRESS VARCHAR(255),
IN P_USERAGENT VARCHAR(32000),
OUT TOTAL INTEGER
)
RESULT SETS 1
LANGUAGE SQL
BEGIN
Declare StringSQL Varchar(32000) Not Null Default '';
Declare WhereClause Varchar(32000) Not Null Default '';
Declare SortClause Varchar(32000) Not Null Default '';
Declare C1 Cursor With Return For stmt1;
-- WHERE CLAUSE
IF P_ID > 0 THEN
SET WhereClause = WhereClause || ' AND ID = '|| P_ID ||' ';
END IF;
IF P_CODE IS NOT NULL AND length(P_CODE)>0 THEN
SET P_CODE = UPPER(TRIM(P_CODE));
SET WhereClause = WhereClause || ' AND CODE LIKE ''%'|| P_CODE ||'%'' ';
END IF;
IF P_NAME IS NOT NULL AND length(P_NAME)>0 THEN
SET P_NAME = UPPER(TRIM(P_NAME));
SET WhereClause = WhereClause || ' AND NAME LIKE ''%'|| P_NAME ||'%'' ';
END IF;
IF P_TABLENAME IS NOT NULL AND length(P_TABLENAME)>0 THEN
SET P_TABLENAME = UPPER(TRIM(P_TABLENAME));
SET WhereClause = WhereClause || ' AND TABLENAME LIKE ''%'|| P_TABLENAME ||'%'' ';
END IF;
IF P_TABLECODE IS NOT NULL AND length(P_TABLECODE)>0 THEN
SET P_TABLECODE = UPPER(TRIM(P_TABLECODE));
SET WhereClause = WhereClause || ' AND TABLECODE LIKE ''%'|| P_TABLECODE ||'%'' ';
END IF;
IF P_TABLEDESC IS NOT NULL AND length(P_TABLEDESC)>0 THEN
SET P_TABLEDESC = UPPER(TRIM(P_TABLEDESC));
SET WhereClause = WhereClause || ' AND TABLEDESC LIKE ''%'|| P_TABLEDESC ||'%'' ';
END IF;
IF P_TABLEPARENT IS NOT NULL AND length(P_TABLEPARENT)>0 THEN
SET P_TABLEPARENT = UPPER(TRIM(P_TABLEPARENT));
SET WhereClause = WhereClause || ' AND TABLEPARENT LIKE ''%'|| P_TABLEPARENT ||'%'' ';
END IF;
Set StringSQL = 'SELECT COUNT(1) FROM GPSQLWEB.TABLEHELP WHERE 1=1 ' || WhereClause;
PREPARE stmt1 FROM StringSQL;
CALL GPSQLWEB.procCreateWebAudit (P_IPADDRESS, P_USERAGENT, P_USERNAME, 'Contar', 'procCountTableHelp', StringSQL);
OPEN c1;
FETCH c1 into total;
CLOSE c1;
END
GO
--call GPSQLWEB.procCountTableHelp(0,'','','','','','', '', '', '')
| 32.160494 | 115 | 0.607678 |
6c2ae6dc7e114628e128c795cac50b748fba72d3 | 2,752 | go | Go | src/backend/go-docker-manager/docker.go | atkinson137/docker-game-manager | 4aa543a0e54057ee3c45875d44e9e9af6d8ce68a | [
"MIT"
] | null | null | null | src/backend/go-docker-manager/docker.go | atkinson137/docker-game-manager | 4aa543a0e54057ee3c45875d44e9e9af6d8ce68a | [
"MIT"
] | 1 | 2018-07-07T21:03:32.000Z | 2018-07-07T21:03:32.000Z | src/backend/go-docker-manager/docker.go | atkinson137/docker-game-manager | 4aa543a0e54057ee3c45875d44e9e9af6d8ce68a | [
"MIT"
] | null | null | null | package main
import (
"context"
"io"
"os"
"time"
"docker.io/go-docker"
"docker.io/go-docker/api/types"
"docker.io/go-docker/api/types/container"
"github.com/hhkbp2/go-logging"
)
type dockerContainer struct {
log *logging.Logger
imageName string
}
func getCli() *docker.Client {
cli, err := docker.NewEnvClient()
if err != nil {
panic(err)
}
return cli
}
func getContainers(cli *docker.Client) []types.Container {
containerList, err := (*cli).ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
panic(err)
}
return containerList
}
func makeContainer(cli *docker.Client, imageName string, mainlog *logging.Logger) *dockerContainer {
containerId, reader := bootContainer(cli, imageName, mainlog)
filePath := "./logs/docker/" + containerId + ".log"
fileMode := os.O_APPEND
bufferSize := 0
bufferFlushTime := 30 * time.Second
inputChanSize := 1
// set the maximum size of every file to 100 M bytes
fileMaxBytes := uint64(100 * 1024 * 1024)
// keep 9 backup at most(including the current using one,
// there could be 10 log file at most)
backupCount := uint32(9)
// create a handler(which represents a log message destination)
handler := logging.MustNewRotatingFileHandler(
filePath, fileMode, bufferSize, bufferFlushTime, inputChanSize,
fileMaxBytes, backupCount)
// the format for the whole log message
format := "%(asctime)s %(levelname)s (%(filename)s:%(lineno)d) " +
"%(name)s %(message)s"
// the format for the time part
dateFormat := "%Y-%m-%d %H:%M:%S.%3n"
// create a formatter(which controls how log messages are formatted)
formatter := logging.NewStandardFormatter(format, dateFormat)
// set formatter for handler
handler.SetFormatter(formatter)
// create a logger(which represents a log message source)
dockerLog := logging.GetLogger(imageName)
dockerLog.SetLevel(logging.LevelInfo)
dockerLog.AddHandler(handler)
infoLog(reader, &dockerLog)
dCont := dockerContainer{&dockerLog, imageName}
return &dCont
}
func bootContainer(cli *docker.Client, image string, mainlog *logging.Logger) (string, io.Reader) {
defer func() {
if r := recover(); r != nil {
(*mainlog).Errorf("BootContainer filed: %s", r)
}
}()
(*mainlog).Infof("Pulling container: %s", image)
closer, imgPullErr := cli.ImagePull(context.Background(), image, types.ImagePullOptions{})
if imgPullErr != nil {
panic(imgPullErr)
}
config := &container.Config{
Image: image,
}
body, err1 := cli.ContainerCreate(context.Background(), config, nil, nil, "")
if err1 != nil {
panic(err1)
}
err := cli.ContainerStart(context.Background(), body.ID, types.ContainerStartOptions{})
if err != nil {
//fmt.Println(err)
panic(err)
}
return body.ID, closer
}
| 25.481481 | 100 | 0.707485 |
e7ea946532831388997e4802f68739577a16154d | 1,122 | asm | Assembly | programs/oeis/009/A009759.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/009/A009759.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/009/A009759.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A009759: Expansion of (3 - 21*x + 4*x^2)/((x-1)*(x^2 - 6*x + 1)).
; -3,0,17,116,693,4056,23657,137900,803757,4684656,27304193,159140516,927538917,5406093000,31509019097,183648021596,1070379110493,6238626641376,36361380737777,211929657785300,1235216565974037,7199369738058936,41961001862379593,244566641436218636,1425438846754932237,8308066439093374800,48422959787805316577,282229692287738524676,1644955193938625831493,9587501471344016464296,55880053634125472954297,325692820333408821261500,1898276868366327454614717,11063968389864555906426816,64485533470821007983946193,375849232435061491997250356,2190609861139547943999555957,12767809934402226172000085400,74416249745273809088000956457,433729688537240628356005653356,2527961881478169961048032963693,14734041600331779137932192128816,85876287720512504866545119809217,500523684722743250061338526726500,2917265820615946995501486040549797,17003071238972938722947577716572296,99101161613221685342183980258883993,577603898440357173330156303836731676
mov $1,2
mov $2,1
lpb $0
sub $0,1
add $1,$2
add $2,$1
add $2,$1
add $1,$2
lpe
add $0,1
add $0,$2
sub $0,8
div $0,2
| 66 | 927 | 0.865419 |
5e9d7f019f809024250efad0f11ff036ba9beb88 | 338 | swift | Swift | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Service Protocols/RSTBElementGenerator.swift | CuriosityHealth/ResearchSuiteApplicationFramework-iOS | 0971e53b7055d26b67761caa247ea967fdf3035a | [
"Apache-2.0"
] | null | null | null | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Service Protocols/RSTBElementGenerator.swift | CuriosityHealth/ResearchSuiteApplicationFramework-iOS | 0971e53b7055d26b67761caa247ea967fdf3035a | [
"Apache-2.0"
] | null | null | null | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Service Protocols/RSTBElementGenerator.swift | CuriosityHealth/ResearchSuiteApplicationFramework-iOS | 0971e53b7055d26b67761caa247ea967fdf3035a | [
"Apache-2.0"
] | 3 | 2020-02-14T17:54:10.000Z | 2021-06-21T19:05:03.000Z | //
// RSTBElementGenerator.swift
// Pods
//
// Created by James Kizer on 1/9/17.
//
//
import Gloss
public protocol RSTBElementGenerator {
func generateElements(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> [JSON]?
func supportsType(type: String) -> Bool
func supportedStepTypes() -> [String]
}
| 18.777778 | 99 | 0.686391 |
9e9d0d35371499f94aa40603911268589046d78b | 2,771 | sql | SQL | macros/utils/time_macros.sql | katsugeneration/dbt-re-data | d3bcc3c751f38015bc609797b67e56cf6a6e13a7 | [
"MIT"
] | 50 | 2021-06-09T18:23:22.000Z | 2022-03-27T02:40:39.000Z | macros/utils/time_macros.sql | katsugeneration/dbt-re-data | d3bcc3c751f38015bc609797b67e56cf6a6e13a7 | [
"MIT"
] | 16 | 2021-06-19T09:29:44.000Z | 2022-03-02T11:42:51.000Z | macros/utils/time_macros.sql | katsugeneration/dbt-re-data | d3bcc3c751f38015bc609797b67e56cf6a6e13a7 | [
"MIT"
] | 11 | 2021-07-19T06:13:47.000Z | 2022-03-22T21:14:25.000Z |
{% macro time_filter(column_name, column_type) %}
case when {{ re_data.is_datetime(column_type)}} = true
then
column_name
else
null
end
{% endmacro %}
{% macro time_window_start() %}
cast('{{- var('re_data:time_window_start') -}}' as timestamp)
{% endmacro %}
{% macro time_window_end() %}
cast('{{- var('re_data:time_window_end') -}}' as timestamp)
{% endmacro %}
{% macro anamaly_detection_time_window_start() %}
{{ adapter.dispatch('anamaly_detection_time_window_start', 're_data')() }}
{% endmacro %}
{% macro default__anamaly_detection_time_window_start() %}
{{ time_window_start() }} - interval '{{var('re_data:anomaly_detection_look_back_days')}} days'
{% endmacro %}
{% macro bigquery__anamaly_detection_time_window_start() %}
DATE_ADD({{ time_window_start() }}, INTERVAL -{{var('re_data:anomaly_detection_look_back_days')}} DAY)
{% endmacro %}
{% macro snowflake__anamaly_detection_time_window_start() %}
DATEADD('DAY', -{{-var('re_data:anomaly_detection_look_back_days')-}}, {{ time_window_start() }})
{% endmacro %}
{% macro interval_length_sec(start_timestamp, end_timestamp) %}
{{ adapter.dispatch('interval_length_sec', 're_data')(start_timestamp, end_timestamp) }}
{% endmacro %}
{% macro default__interval_length_sec(start_timestamp, end_timestamp) %}
EXTRACT(EPOCH FROM ({{ end_timestamp }} - {{ start_timestamp }} ))
{% endmacro %}
{% macro bigquery__interval_length_sec(start_timestamp, end_timestamp) %}
TIMESTAMP_DIFF ({{ end_timestamp }}, {{ start_timestamp }}, SECOND)
{% endmacro %}
{% macro snowflake__interval_length_sec(start_timestamp, end_timestamp) %}
timediff(second, {{ start_timestamp }}, {{ end_timestamp }})
{% endmacro %}
{% macro redshift__interval_length_sec(start_timestamp, end_timestamp) %}
DATEDIFF(second, {{ start_timestamp }}, {{ end_timestamp }})
{% endmacro %}
{% macro before_time_window_end(time_column) %}
{{ adapter.dispatch('before_time_window_end', 're_data')(time_column) }}
{% endmacro %}
{% macro default__before_time_window_end(time_column) %}
{{time_column}} < {{- time_window_end() -}}
{% endmacro %}
{% macro bigquery__before_time_window_end(time_column) %}
timestamp({{time_column}}) < {{- time_window_end() -}}
{% endmacro %}
{% macro in_time_window(time_column) %}
{{ adapter.dispatch('in_time_window', 're_data')(time_column) }}
{% endmacro %}
{% macro default__in_time_window(time_column) %}
{{time_column}} >= {{ time_window_start() }} and
{{time_column}} < {{ time_window_end() }}
{% endmacro %}
{% macro bigquery__in_time_window(time_column) %}
timestamp({{time_column}}) >= {{ time_window_start() }} and
timestamp({{time_column}}) < {{ time_window_end() }}
{% endmacro %}
| 31.850575 | 106 | 0.692891 |
d1398e6704455d2a847fdb935e9c6a5864f3b956 | 933 | ps1 | PowerShell | ReleaseProcessScript/tools/PesterTester/GitCommandsForReferenceDir/Hotfix-PreRelease-Alpha-TaggedCommonAncestor/Initialize.ps1 | re-motion/SharedSource-Build | b9ccfb5889783eedb564684d83daf22d2da85ede | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | ReleaseProcessScript/tools/PesterTester/GitCommandsForReferenceDir/Hotfix-PreRelease-Alpha-TaggedCommonAncestor/Initialize.ps1 | re-motion/SharedSource-Build | b9ccfb5889783eedb564684d83daf22d2da85ede | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2020-02-05T11:57:57.000Z | 2021-06-21T12:12:52.000Z | ReleaseProcessScript/tools/PesterTester/GitCommandsForReferenceDir/Hotfix-PreRelease-Alpha-TaggedCommonAncestor/Initialize.ps1 | re-motion/SharedSource-Build | b9ccfb5889783eedb564684d83daf22d2da85ede | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2015-09-25T11:52:13.000Z | 2020-04-20T19:48:13.000Z | git checkout -b "support/v2.28" *>$NULL
git commit -m "Commit on Support Branch" --allow-empty *>$NULL
git tag -a "v2.28.0" -m "v2.28.0" *>$NULL
git checkout -b "support/v2.29" *>$NULL
git checkout -b "hotfix/v2.29.1" *>$NULL
git commit -m "Feature-A" --allow-empty *>$NULL
git checkout -b "prelease/v2.29.1-alpha.1" *>$NULL
git commit -m "Update metadata to version '2.29.1-alpha.1'." --allow-empty *>$NULL
git tag -a "v2.29.1-alpha.1" -m "v2.29.1-alpha.1" *>$NULL
git checkout "hotfix/v2.29.1" *>$NULL
git merge "prelease/v2.29.1-alpha.1" --no-ff *>$NULL
git checkout "hotfix/v2.29.1" *>$NULL
git commit -m "Feature-B" --allow-empty *>$NULL
git checkout -b "prelease/v2.29.1-alpha.2" *>$NULL
git commit -m "Update metadata to version '2.29.1-alpha.2'." --allow-empty *>$NULL
git tag -a "v2.29.1-alpha.2" -m "v2.29.1-alpha.2" *>$NULL
git checkout "hotfix/v2.29.1" *>$NULL
git merge "prelease/v2.29.1-alpha.2" --no-ff *>$NULL
| 35.884615 | 82 | 0.655949 |
e521e4ccfc14c1849428e9160ad7251cbe09828f | 3,295 | tsx | TypeScript | src/components/ContactPage/light.tsx | agenciaglobal/web | 50c98afcb89ff71ba747c3fd99862181b86a320e | [
"MIT"
] | null | null | null | src/components/ContactPage/light.tsx | agenciaglobal/web | 50c98afcb89ff71ba747c3fd99862181b86a320e | [
"MIT"
] | 56 | 2020-07-23T19:43:42.000Z | 2020-08-27T15:28:28.000Z | src/components/ContactPage/light.tsx | agenciaglobal/web | 50c98afcb89ff71ba747c3fd99862181b86a320e | [
"MIT"
] | null | null | null | export const lightMap = {
mapTypeControl: false,
streetViewControl: false,
disableDefaultUI: true,
fullscreenControl: false,
styles: [
{
elementType: "geometry",
stylers: [{ color: "#f5f5f5" }],
},
{
elementType: "labels.text.fill",
stylers: [{ color: "#7D7D7D" }],
},
{
elementType: "labels.text.stroke",
stylers: [{ color: "#f5f1e6" }],
},
{
featureType: "administrative",
elementType: "geometry.stroke",
stylers: [{ color: "#f5f5f5" }],
},
{
featureType: "administrative.land_parcel",
elementType: "geometry.stroke",
stylers: [{ color: "#f5f5f5" }],
},
{
featureType: "administrative.land_parcel",
elementType: "labels.text.fill",
stylers: [{ color: "#f5f5f5" }],
},
{
featureType: "landscape.natural",
elementType: "geometry",
stylers: [{ color: "#f5f5f5" }],
},
{
featureType: "poi",
elementType: "geometry",
stylers: [{ visibility: "off" }],
},
{
featureType: "poi",
elementType: "labels.icon",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi",
elementType: "labels.text.fill",
stylers: [{ visibility: "off" }],
},
{
featureType: "poi.park",
elementType: "geometry.fill",
stylers: [{ color: "#f5f5f5" }],
},
{
featureType: "poi.park",
elementType: "labels.text.fill",
stylers: [{ color: "#447530" }],
},
{
featureType: "road",
elementType: "geometry",
stylers: [{ color: "#FFFFFF" }],
},
{
featureType: "road.arterial",
elementType: "geometry",
stylers: [{ color: "#FFFFFF" }],
},
{
featureType: "road.highway",
elementType: "geometry",
stylers: [{ color: "#FFFFFF" }],
},
{
featureType: "road.highway",
elementType: "geometry.stroke",
stylers: [{ color: "#FFFFFF" }],
},
{
featureType: "road.highway.controlled_access",
elementType: "geometry",
stylers: [{ color: "#FFFFFF" }],
},
{
featureType: "road.highway.controlled_access",
elementType: "geometry.stroke",
stylers: [{ color: "#FFFFFF" }],
},
{
featureType: "road.local",
elementType: "labels.text.fill",
stylers: [{ color: "#A5A5A5" }],
},
{
featureType: "road.local",
elementType: "labels.text.stroke",
stylers: [{ color: "#f5f1e6" }],
},
{
featureType: "transit.line",
elementType: "geometry",
stylers: [{ color: "#dfd2ae" }],
},
{
featureType: "transit.line",
elementType: "labels.text.fill",
stylers: [{ color: "#8f7d77" }],
},
{
featureType: "transit.line",
elementType: "labels.text.stroke",
stylers: [{ color: "#ebe3cd" }],
},
{
featureType: "transit.station",
elementType: "geometry",
stylers: [{ color: "#dfd2ae" }],
},
{
featureType: "water",
elementType: "geometry.fill",
stylers: [{ color: "#b9d3c2" }],
},
{
featureType: "water",
elementType: "labels.text.fill",
stylers: [{ color: "#92998d" }],
},
],
}
| 23.535714 | 52 | 0.516237 |
8a3782673f3f50f18497b04fd15b113517b74ce5 | 331 | swift | Swift | Sources/NonNullCodable+CastingCodable.swift | chan614/DefaultCodable | d700ca098e9fc46c93819d5561f36bc408cd876a | [
"MIT"
] | null | null | null | Sources/NonNullCodable+CastingCodable.swift | chan614/DefaultCodable | d700ca098e9fc46c93819d5561f36bc408cd876a | [
"MIT"
] | null | null | null | Sources/NonNullCodable+CastingCodable.swift | chan614/DefaultCodable | d700ca098e9fc46c93819d5561f36bc408cd876a | [
"MIT"
] | null | null | null | //
// NonNullCodable+CastingCodable.swift
//
//
// Created by parkjichan on 2022/03/17.
//
public protocol NonNullCodable {
associatedtype Value: Codable
static var defaultValue: Value { get }
}
public protocol CastingCodable {
associatedtype Value: Codable
static func cast(stringValue: String?) -> Value
}
| 18.388889 | 51 | 0.70997 |
c0306a2d9301d62a7be8798e1b3d0895c88a0e7d | 646 | asm | Assembly | oeis/030/A030629.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/030/A030629.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/030/A030629.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A030629: Numbers with 11 divisors.
; Submitted by Jon Maiga
; 1024,59049,9765625,282475249,25937424601,137858491849,2015993900449,6131066257801,41426511213649,420707233300201,819628286980801,4808584372417849,13422659310152401,21611482313284249,52599132235830049,174887470365513049,511116753300641401,713342911662882601,1822837804551761449,3255243551009881201,4297625829703557649,9468276082626847201,15516041187205853449,31181719929966183601,73742412689492826049,110462212541120451001,134391637934412192049,196715135728956532249,236736367459211723401
mul $0,2
max $0,1
seq $0,173919 ; Numbers that are prime or one less than a prime.
pow $0,10
| 71.777778 | 489 | 0.882353 |
5b55491db472a5bdba8cfc308a2c148a3bfc0a09 | 531 | asm | Assembly | oeis/350/A350387.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/350/A350387.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/350/A350387.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A350387: a(n) is the sum of the odd exponents in the prime factorization of n.
; Submitted by Jon Maiga
; 0,1,1,0,1,2,1,3,0,2,1,1,1,2,2,0,1,1,1,1,2,2,1,4,0,2,3,1,1,3,1,5,2,2,2,0,1,2,2,4,1,3,1,1,1,2,1,1,0,1,2,1,1,4,2,4,2,2,1,2,1,2,1,0,2,3,1,1,2,3,1,3,1,2,1,1,2,3,1,1,0,2,1,2,2,2,2,4,1,2,2,1,2,2,2,6,1,1,1,0
seq $0,350389 ; a(n) is the largest unitary divisor of n that is an exponentially odd number (A268335).
sub $0,1
seq $0,1222 ; Number of prime divisors of n counted with multiplicity (also called bigomega(n) or Omega(n)).
| 66.375 | 201 | 0.647834 |
7abe3d31cb2ec9b8413fbb807c16c0e530e5a366 | 1,208 | rb | Ruby | spec/controllers/refinery/admin/videos/videos_controller_spec.rb | adexin/refinerycms-videojs | af1935adfa543a33d0a1ea019cd5d070fd2bb99f | [
"MIT"
] | 12 | 2017-09-21T23:26:55.000Z | 2020-12-19T00:33:58.000Z | spec/controllers/refinery/admin/videos/videos_controller_spec.rb | adexin/refinerycms-videojs | af1935adfa543a33d0a1ea019cd5d070fd2bb99f | [
"MIT"
] | 11 | 2020-03-02T09:27:37.000Z | 2022-02-26T06:47:36.000Z | spec/controllers/refinery/admin/videos/videos_controller_spec.rb | adexin-team/refinerycms-videojs | af1935adfa543a33d0a1ea019cd5d070fd2bb99f | [
"MIT"
] | 17 | 2015-02-19T10:25:35.000Z | 2017-03-17T06:53:32.000Z | require 'spec_helper'
describe Refinery::Videos::Admin::VideosController, type: :controller do
render_views
before do
@user = Refinery::Authentication::Devise::User.create!(:username => 'admin@admin.com',
:email => 'admin@admin.com',
:password => 'admin@admin.com',
:password_confirmation => 'admin@admin.com')
@user.create_first
sign_in @user
end
describe 'insert video' do
before do
@video = FactoryGirl.create(:valid_video, :title => "TestVideo")
end
it 'should get videos html' do
get :insert, params: { app_dialog: true, dialog: true }
response.should be_success
response.body.should match(/TestVideo/)
end
it 'should get preview' do
get :dialog_preview, params: { id: "video_#{@video.id}" }, format: :js, xhr: true
response.should be_success
response.body.should match(/iframe/)
end
it 'should get preview' do
post :append_to_wym, params: { video_id: @video.id, video: { height: 100 } }, format: :js
response.should be_success
response.body.should match(/iframe/)
end
end
end
| 30.2 | 95 | 0.607616 |
3087226d326b4973135e50d5432fb1e511537a6e | 1,612 | htm | HTML | game/data/html/mods/buffer/Buffer-3.htm | TheDemonLife/Lineage2Server-Interlude | d23d145db533fd899d4064026e4bc7ee45c6624a | [
"Apache-2.0"
] | 10 | 2019-07-27T13:12:11.000Z | 2022-01-15T19:13:26.000Z | game/data/html/mods/buffer/Buffer-3.htm | TheDemonLife/Lineage2Server-Interlude | d23d145db533fd899d4064026e4bc7ee45c6624a | [
"Apache-2.0"
] | 1 | 2021-08-06T12:15:01.000Z | 2021-08-09T10:18:47.000Z | game/data/html/mods/buffer/Buffer-3.htm | TheDemonLife/Lineage2Server-Interlude | d23d145db533fd899d4064026e4bc7ee45c6624a | [
"Apache-2.0"
] | 2 | 2020-02-20T23:02:26.000Z | 2020-11-22T09:27:51.000Z | <html><body>
<br>
<center>
<table width=230>
<tr>
<td width=5></td>
<td valign=top><img src=icon.skill0271 width=32 height=32 align=left></td>
<td><a action="bypass -h Quest 50000_Buffer Buff 271">Warrior</a></td>
<td valign=top><img src=icon.skill0272 width=32 height=32 align=left></td>
<td><a action="bypass -h Quest 50000_Buffer Buff 272">Inspiration</a></td>
</tr>
<tr>
<td width=5></td>
<td valign=top><img src=icon.skill0273 width=32 height=32 align=left></td>
<td><a action="bypass -h Quest 50000_Buffer Buff 273">Mystic</a></td>
<td valign=top><img src=icon.skill0274 width=32 height=32 align=left></td>
<td><a action="bypass -h Quest 50000_Buffer Buff 274">Fire</a></td>
</tr>
<tr>
<td width=5></td>
<td valign=top><img src=icon.skill0275 width=32 height=32 align=left></td>
<td><a action="bypass -h Quest 50000_Buffer Buff 275">Fury</a></td>
<td valign=top><img src=icon.skill0276 width=32 height=32 align=left></td>
<td><a action="bypass -h Quest 50000_Buffer Buff 276">Concentration</a></td>
</tr>
<tr>
<td width=5></td>
<td valign=top><img src=icon.skill0310 width=32 height=32 align=left></td>
<td><a action="bypass -h Quest 50000_Buffer Buff 310">Vampire</a></td>
<td valign=top><img src=icon.skill0365 width=32 height=32 align=left></td>
<td><a action="bypass -h Quest 50000_Buffer Buff 365">Siren's Dance</a></td>
</tr>
</table>
</center>
<br><br><br><br><br><br><br>
<center><button value="Назад" action="bypass -h Quest 50000_Buffer Chat 0" width=75 height=21 back="L2UI_ch3.Btn1_normalOn" fore="L2UI_ch3.Btn1_normal"></center>
</body>
</html>
| 40.3 | 161 | 0.681762 |
4207a327ad36226c884e16a5ea6e85e9ba03055e | 789 | html | HTML | src/Umbraco.Web.UI.Client/src/views/propertyeditors/checkboxlist/checkboxlist.html | nul800sebastiaan/Umbraco-CMS | dfdb498537a6253c417f4f755283959416608243 | [
"MIT"
] | 3,375 | 2015-01-02T17:21:08.000Z | 2022-03-31T17:56:19.000Z | src/Umbraco.Web.UI.Client/src/views/propertyeditors/checkboxlist/checkboxlist.html | nul800sebastiaan/Umbraco-CMS | dfdb498537a6253c417f4f755283959416608243 | [
"MIT"
] | 9,473 | 2015-01-02T01:10:10.000Z | 2022-03-31T23:39:34.000Z | src/Umbraco.Web.UI.Client/src/views/propertyeditors/checkboxlist/checkboxlist.html | nul800sebastiaan/Umbraco-CMS | dfdb498537a6253c417f4f755283959416608243 | [
"MIT"
] | 3,059 | 2015-01-02T04:31:28.000Z | 2022-03-31T05:27:07.000Z | <div class="umb-property-editor umb-checkboxlist" ng-controller="Umbraco.PropertyEditors.CheckboxListController as vm">
<ng-form name="checkboxListFieldForm">
<ul class="unstyled">
<li ng-repeat="item in vm.viewItems track by item.key">
<umb-checkbox name="{{::model.alias}}_{{::vm.uniqueId}}" value="{{::item.value}}" model="item.checked" text="{{::item.value}}" on-change="vm.change(model, value)" required="model.validation.mandatory && !model.value.length"></umb-checkbox>
</li>
</ul>
<div ng-messages="checkboxListFieldForm[model.alias + '_' + vm.uniqueId].$error" show-validation-on-submit>
<p class="help-inline" ng-message="required">{{mandatoryMessage}}</p>
</div>
</ng-form>
</div>
| 46.411765 | 255 | 0.632446 |
c1e35e769470d9d45ca7840c2ba8582bfbefdd26 | 1,620 | lua | Lua | vendor/RainbowRepacker/tool/engine_android(5)/assets/scripts/view/kScreen_1280_800/hall/recharge/rechargeTopAd.lua | huangtao/cloud-test | 8087b1337d47daab9eb39335ca6e286df0e4b4dc | [
"Apache-2.0"
] | 1 | 2018-09-12T15:43:32.000Z | 2018-09-12T15:43:32.000Z | vendor/RainbowRepacker/tool/engine_android(5)/assets/scripts/view/kScreen_1280_800/hall/recharge/rechargeTopAd.lua | huangtao/cloud-test | 8087b1337d47daab9eb39335ca6e286df0e4b4dc | [
"Apache-2.0"
] | null | null | null | vendor/RainbowRepacker/tool/engine_android(5)/assets/scripts/view/kScreen_1280_800/hall/recharge/rechargeTopAd.lua | huangtao/cloud-test | 8087b1337d47daab9eb39335ca6e286df0e4b4dc | [
"Apache-2.0"
] | 3 | 2018-09-12T15:43:33.000Z | 2019-07-10T09:50:15.000Z | local market_pin_map = require("qnFiles/qnPlist/hall/market_pin");
local rechargeTopAd=
{
name="rechargeTopAd",type=0,typeName="View",time=0,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTop,
{
name="commonLayer",type=0,typeName="View",time=105705540,x=0,y=100,width=1280,height=70,nodeAlign=kAlignTop,visible=1,fillParentWidth=1,fillParentHeight=0,
{
name="ad_bg",type=0,typeName="Image",time=105705753,x=51,y=-81,width=1178,height=32,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0,file=market_pin_map['ad_bg.png'],fillTopLeftX=51,fillTopLeftY=19,fillBottomRightY=19,fillBottomRightX=51,gridLeft=5,gridRight=5,gridTop=5,gridBottom=5,
{
name="adView",type=0,typeName="View",time=105725697,x=0,y=0,width=998,height=32,nodeAlign=kAlignTopLeft,visible=1,fillParentWidth=0,fillParentHeight=0,fillTopLeftY=0,fillBottomRightY=0,fillTopLeftX=20,fillBottomRightX=160,
{
name="adText",type=0,typeName="Text",time=105725599,x=0,y=0,width=1,height=30,nodeAlign=kAlignLeft,visible=1,fillParentWidth=0,fillParentHeight=0,fontSize=20,textAlign=kAlignLeft,colorRed=255,colorGreen=238,colorBlue=193
}
}
},
{
name="bagBtn",type=0,typeName="Button",time=105705971,x=50,y=-5,width=180,height=50,nodeAlign=kAlignRight,visible=1,fillParentWidth=0,fillParentHeight=0,file="isolater/bg_blank.png",
{
name="img",type=0,typeName="Image",time=105706050,x=3,y=3,width=184,height=53,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0,file=market_pin_map['btn_bag.png']
}
}
}
}
return rechargeTopAd; | 67.5 | 308 | 0.779012 |
cdc29e6813eadec07d1c93f42bb25209c58cadd9 | 849 | sql | SQL | AttachDBWithoutLogFile.sql | treebat1/SQL | 388c4dc59618589725a8761d5711169452650192 | [
"MIT"
] | null | null | null | AttachDBWithoutLogFile.sql | treebat1/SQL | 388c4dc59618589725a8761d5711169452650192 | [
"MIT"
] | null | null | null | AttachDBWithoutLogFile.sql | treebat1/SQL | 388c4dc59618589725a8761d5711169452650192 | [
"MIT"
] | null | null | null |
USE [master]
GO
CREATE DATABASE [ProductsDB] ON
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\ProductsDB.mdf' )
FOR ATTACH
GO
/*
Once the above T-SQL code has executed successfully you will get the below message which informs you that SQL Server has created a new transaction log file for the database.
File activation failure. The physical file name "C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\ProductsDB_log.ldf" may be incorrect.
New log file 'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\ProductsDB_log.LDF' was created.
Verify Logical and Physical Integrity of Database
DBAs can check the logical and physical integrity of all the objects within the database by executing a DBCC CHECKDB. In our case we are using the "ProductsDB" database.
*/ | 44.684211 | 174 | 0.779741 |
ec4142e06d47a3ec2ab3de6d2ea062b6618318d2 | 1,396 | swift | Swift | 0162. Find Peak Element.swift | sergeyleschev/leetcode-swift | b73b8fa61a14849e48fb38e27e51ea6c12817d64 | [
"MIT"
] | 10 | 2021-05-16T07:19:41.000Z | 2021-08-02T19:02:00.000Z | 0162. Find Peak Element.swift | sergeyleschev/leetcode-swift | b73b8fa61a14849e48fb38e27e51ea6c12817d64 | [
"MIT"
] | null | null | null | 0162. Find Peak Element.swift | sergeyleschev/leetcode-swift | b73b8fa61a14849e48fb38e27e51ea6c12817d64 | [
"MIT"
] | 1 | 2021-08-18T05:33:00.000Z | 2021-08-18T05:33:00.000Z | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 162. Find Peak Element
// A peak element is an element that is strictly greater than its neighbors.
// Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
// You may imagine that nums[-1] = nums[n] = -∞.
// You must write an algorithm that runs in O(log n) time.
// Example 1:
// Input: nums = [1,2,3,1]
// Output: 2
// Explanation: 3 is a peak element and your function should return the index number 2.
// Example 2:
// Input: nums = [1,2,1,3,5,6,4]
// Output: 5
// Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
// Constraints:
// 1 <= nums.length <= 1000
// -2^31 <= nums[i] <= 2^31 - 1
// nums[i] != nums[i + 1] for all valid i.
func findPeakElement(_ nums: [Int]) -> Int {
if nums.count == 1 { return 0 }
var left = 0
var right = nums.count - 1
while left < right {
var mid = (left + right) / 2
if nums[mid] < nums[mid + 1] {
left = mid + 1
} else {
right = mid
}
}
return left
}
} | 31.727273 | 154 | 0.551576 |
668955631d768f1f0f46e07760a5d9b2c2017637 | 4,399 | swift | Swift | Sources/BeeTracking/AppearanceRAE+Serialization.swift | brandoDecu/SwiftFusion | 50f1bdc5c7695d1f3c8c1c6004b6a7cf00041d73 | [
"Apache-2.0"
] | null | null | null | Sources/BeeTracking/AppearanceRAE+Serialization.swift | brandoDecu/SwiftFusion | 50f1bdc5c7695d1f3c8c1c6004b6a7cf00041d73 | [
"Apache-2.0"
] | null | null | null | Sources/BeeTracking/AppearanceRAE+Serialization.swift | brandoDecu/SwiftFusion | 50f1bdc5c7695d1f3c8c1c6004b6a7cf00041d73 | [
"Apache-2.0"
] | null | null | null | import PythonKit
import TensorFlow
extension Dense where Scalar: NumpyScalarCompatible {
/// Loads weights and bias from the numpy arrays in `weights`.
///
/// `weights[0]` is the dense weight matrix and `weights[1]` is the bias.
mutating func load(weights: PythonObject) {
let weight = Tensor<Scalar>(numpy: weights[0])!
let bias = Tensor<Scalar>(numpy: weights[1])!
precondition(
self.weight.shape == weight.shape,
"expected weight matrix \(self.weight.shape) but got \(weight.shape)")
precondition(
self.bias.shape == bias.shape, "expected bias \(self.bias.shape) but got \(bias.shape)")
self.weight = weight
self.bias = bias
}
/// The weight and bias as numpy arrays.
///
/// `numpyWeights[0]` is the dense weight matrix and `numpyWeights[1]` is the bias.
var numpyWeights: PythonObject {
Python.list([self.weight.makeNumpyArray(), self.bias.makeNumpyArray()])
}
}
extension Conv2D where Scalar: NumpyScalarCompatible {
/// Loads filter and bias from the numpy arrays in `weights`.
///
/// `weights[0]` is the filter and `weights[1]` is the bias.
mutating func load(weights: PythonObject) {
let filter = Tensor<Scalar>(numpy: weights[0])!
let bias = Tensor<Scalar>(numpy: weights[1])!
precondition(
self.filter.shape == filter.shape,
"expected filter matrix \(self.filter.shape) but got \(filter.shape)")
precondition(
self.bias.shape == bias.shape, "expected bias \(self.bias.shape) but got \(bias.shape)")
self.filter = filter
self.bias = bias
}
/// The filter and bias as numpy arrays.
///
/// `numpyWeights[0]` is the filter and `numpyWeights[1]` is the bias.
var numpyWeights: PythonObject {
Python.list([self.filter.makeNumpyArray(), self.bias.makeNumpyArray()])
}
}
extension DenseRAE {
/// Loads model weights from the numpy arrays in `weights`.
public mutating func load(weights: PythonObject) {
self.encoder_conv1.load(weights: weights[0..<2])
self.encoder1.load(weights: weights[2..<4])
self.encoder2.load(weights: weights[4..<6])
self.decoder1.load(weights: weights[6..<8])
self.decoder2.load(weights: weights[8..<10])
self.decoder_conv1.load(weights: weights[10..<12])
}
/// The model weights as numpy arrays.
public var numpyWeights: PythonObject {
[
self.encoder_conv1.numpyWeights,
self.encoder1.numpyWeights,
self.encoder2.numpyWeights,
self.decoder1.numpyWeights,
self.decoder2.numpyWeights,
self.decoder_conv1.numpyWeights
].reduce([], +)
}
}
extension NNClassifier {
/// Loads model weights from the numpy arrays in `weights`.
public mutating func load(weights: PythonObject) {
self.encoder_conv1.load(weights: weights[0..<2])
self.encoder1.load(weights: weights[2..<4])
self.encoder2.load(weights: weights[4..<6])
self.encoder3.load(weights: weights[6..<8])
}
/// The model weights as numpy arrays.
public var numpyWeights: PythonObject {
[
self.encoder_conv1.numpyWeights,
self.encoder1.numpyWeights,
self.encoder2.numpyWeights,
self.encoder3.numpyWeights
].reduce([], +)
}
}
extension SmallerNNClassifier {
/// Loads model weights from the numpy arrays in `weights`.
public mutating func load(weights: PythonObject) {
self.encoder_conv1.load(weights: weights[0..<2])
self.encoder1.load(weights: weights[2..<4])
self.encoder2.load(weights: weights[4..<6])
}
/// The model weights as numpy arrays.
public var numpyWeights: PythonObject {
[
self.encoder_conv1.numpyWeights,
self.encoder1.numpyWeights,
self.encoder2.numpyWeights,
].reduce([], +)
}
}
extension LargerNNClassifier {
/// Loads model weights from the numpy arrays in `weights`.
public mutating func load(weights: PythonObject) {
self.encoder_conv1.load(weights: weights[0..<2])
self.encoder1.load(weights: weights[2..<4])
self.encoder2.load(weights: weights[4..<6])
self.encoder3.load(weights: weights[6..<8])
self.encoder4.load(weights: weights[8..<10])
}
/// The model weights as numpy arrays.
public var numpyWeights: PythonObject {
[
self.encoder_conv1.numpyWeights,
self.encoder1.numpyWeights,
self.encoder2.numpyWeights,
self.encoder3.numpyWeights,
self.encoder4.numpyWeights
].reduce([], +)
}
}
| 31.198582 | 94 | 0.678791 |
327cf59143a5490807b7ebabf1184a9defda38fd | 187 | swift | Swift | Sources/Neon/Compatibility.swift | ChimeHQ/TreeSitterClient | f3cae6e27fde78cf5a02378323d562b3ec5f894d | [
"BSD-3-Clause"
] | 2 | 2022-03-20T13:59:52.000Z | 2022-03-21T04:30:05.000Z | Sources/Neon/Compatibility.swift | ChimeHQ/TreeSitterClient | f3cae6e27fde78cf5a02378323d562b3ec5f894d | [
"BSD-3-Clause"
] | null | null | null | Sources/Neon/Compatibility.swift | ChimeHQ/TreeSitterClient | f3cae6e27fde78cf5a02378323d562b3ec5f894d | [
"BSD-3-Clause"
] | null | null | null | import Foundation
func preconditionOnMainQueue() {
if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
dispatchPrecondition(condition: .onQueue(.main))
}
}
| 23.375 | 69 | 0.668449 |
0593064ad2ab05d2de92ade1c7b24efb3f39def7 | 1,878 | ps1 | PowerShell | edgelet/build/windows/openssl.ps1 | ngi644/iotedge | 32860a7794e88932f83f4e01582d5f1d8f553347 | [
"MIT"
] | 2 | 2019-02-04T20:18:48.000Z | 2019-03-22T13:38:47.000Z | edgelet/build/windows/openssl.ps1 | ngi644/iotedge | 32860a7794e88932f83f4e01582d5f1d8f553347 | [
"MIT"
] | null | null | null | edgelet/build/windows/openssl.ps1 | ngi644/iotedge | 32860a7794e88932f83f4e01582d5f1d8f553347 | [
"MIT"
] | null | null | null | # Copyright (c) Microsoft. All rights reserved.
function Get-OpenSSL
{
if (!((Test-Path -Path $env:HOMEDRIVE\vcpkg) -and ((Test-Path -Path $env:HOMEDRIVE\vcpkg\vcpkg.exe))))
{
Write-Host "Installing vcpkg from github..."
git clone https://github.com/Microsoft/vcpkg $env:HOMEDRIVE\vcpkg
if ($LastExitCode)
{
Throw "Failed to clone vcpkg repo with exit code $LastExitCode"
}
Write-Host "Bootstrapping vcpkg..."
& "$env:HOMEDRIVE\vcpkg\bootstrap-vcpkg.bat"
if ($LastExitCode)
{
Throw "Failed to bootstrap vcpkg with exit code $LastExitCode"
}
Write-Host "Installing vcpkg..."
& $env:HOMEDRIVE\\vcpkg\\vcpkg.exe integrate install
if ($LastExitCode)
{
Throw "Failed to install vcpkg with exit code $LastExitCode"
}
}
Write-Host "Installing OpenSSL for x64..."
& $env:HOMEDRIVE\\vcpkg\\vcpkg.exe install openssl:x64-windows
if ($LastExitCode)
{
Throw "Failed to install openssl vcpkg with exit code $LastExitCode"
}
Write-Host "Setting env variable OPENSSL_ROOT_DIR..."
if ((Test-Path env:TF_BUILD) -and ($env:TF_BUILD -eq $true))
{
# When executing within TF (VSTS) environment, install the env variable
# such that all follow up build tasks have visibility of the env variable
Write-Host "VSTS installation detected"
Write-Host "##vso[task.setvariable variable=OPENSSL_ROOT_DIR;]$env:HOMEDRIVE\vcpkg\installed\x64-windows"
}
else
{
# for local installation, set the env variable within the USER scope
Write-Host "Local installation detected"
[System.Environment]::SetEnvironmentVariable("OPENSSL_ROOT_DIR", "$env:HOMEDRIVE\vcpkg\installed\x64-windows", [System.EnvironmentVariableTarget]::User)
}
}
| 39.125 | 160 | 0.65016 |
3ccd61e3e70ce4376f1a2444976059fbde913ad8 | 170 | ps1 | PowerShell | build/Chocolatey/gsudo/tools/chocolateybeforemodify.ps1 | bluPhy/gsudo | 3af405949cfdb1485fa899bcfd08115d10ab0b3f | [
"MIT"
] | 2,246 | 2019-11-29T10:41:17.000Z | 2022-03-31T17:12:12.000Z | build/Chocolatey/gsudo/tools/chocolateybeforemodify.ps1 | bluPhy/gsudo | 3af405949cfdb1485fa899bcfd08115d10ab0b3f | [
"MIT"
] | 121 | 2019-12-19T22:06:14.000Z | 2022-03-31T13:35:14.000Z | build/Chocolatey/gsudo/tools/chocolateybeforemodify.ps1 | bluPhy/gsudo | 3af405949cfdb1485fa899bcfd08115d10ab0b3f | [
"MIT"
] | 80 | 2019-12-27T15:40:01.000Z | 2022-03-31T15:04:47.000Z | $ErrorActionPreference = "SilentlyContinue"
$running = Get-Process gsudo -ErrorAction SilentlyContinue
if ($running) {
gsudo.exe -k
Start-Sleep -Milliseconds 500
}
| 18.888889 | 58 | 0.758824 |
40f77061b2ad02054f9eb6e9a7e09b99c817063f | 1,756 | py | Python | reproduction/text_classification/train_lstm.py | KuNyaa/fastNLP | 22f9b87c54a4eebec7352c7ff772cd24685c7186 | [
"Apache-2.0"
] | 1 | 2019-10-05T06:02:44.000Z | 2019-10-05T06:02:44.000Z | reproduction/text_classification/train_lstm.py | awesomemachinelearning/fastNLP | 945b30bb6174751130744231aa26119bf9bb2601 | [
"Apache-2.0"
] | 1 | 2019-12-09T06:34:44.000Z | 2019-12-09T06:34:44.000Z | reproduction/text_classification/train_lstm.py | awesomemachinelearning/fastNLP | 945b30bb6174751130744231aa26119bf9bb2601 | [
"Apache-2.0"
] | null | null | null | # 首先需要加入以下的路径到环境变量,因为当前只对内部测试开放,所以需要手动申明一下路径
import os
os.environ['FASTNLP_BASE_URL'] = 'http://10.141.222.118:8888/file/download/'
os.environ['FASTNLP_CACHE_DIR'] = '/remote-home/hyan01/fastnlp_caches'
from fastNLP.io.data_loader import IMDBLoader
from fastNLP.embeddings import StaticEmbedding
from model.lstm import BiLSTMSentiment
from fastNLP import CrossEntropyLoss, AccuracyMetric
from fastNLP import Trainer
from torch.optim import Adam
class Config():
train_epoch= 10
lr=0.001
num_classes=2
hidden_dim=256
num_layers=1
nfc=128
task_name = "IMDB"
datapath={"train":"IMDB_data/train.csv", "test":"IMDB_data/test.csv"}
save_model_path="./result_IMDB_test/"
opt=Config()
# load data
dataloader=IMDBLoader()
datainfo=dataloader.process(opt.datapath)
# print(datainfo.datasets["train"])
# print(datainfo)
# define model
vocab=datainfo.vocabs['words']
embed = StaticEmbedding(vocab, model_dir_or_name='en-glove-840b-300', requires_grad=True)
model=BiLSTMSentiment(init_embed=embed, num_classes=opt.num_classes, hidden_dim=opt.hidden_dim, num_layers=opt.num_layers, nfc=opt.nfc)
# define loss_function and metrics
loss=CrossEntropyLoss()
metrics=AccuracyMetric()
optimizer= Adam([param for param in model.parameters() if param.requires_grad==True], lr=opt.lr)
def train(datainfo, model, optimizer, loss, metrics, opt):
trainer = Trainer(datainfo.datasets['train'], model, optimizer=optimizer, loss=loss,
metrics=metrics, dev_data=datainfo.datasets['test'], device=0, check_code_level=-1,
n_epochs=opt.train_epoch, save_path=opt.save_model_path)
trainer.train()
if __name__ == "__main__":
train(datainfo, model, optimizer, loss, metrics, opt) | 29.762712 | 135 | 0.747153 |
f587e81adf6d3218953adfcc788fc652d6c0aca6 | 2,917 | css | CSS | TutorGet/Content/Infragistics/css/themes/bootstrap3/flatly/style-guide/style-guide.css | Kewang0068/TutorGetApp | fd8908eaca184cbdd28ce3357e081d6e540a07b0 | [
"MIT"
] | null | null | null | TutorGet/Content/Infragistics/css/themes/bootstrap3/flatly/style-guide/style-guide.css | Kewang0068/TutorGetApp | fd8908eaca184cbdd28ce3357e081d6e540a07b0 | [
"MIT"
] | null | null | null | TutorGet/Content/Infragistics/css/themes/bootstrap3/flatly/style-guide/style-guide.css | Kewang0068/TutorGetApp | fd8908eaca184cbdd28ce3357e081d6e540a07b0 | [
"MIT"
] | null | null | null | .paragraph-styles p,body{margin:0}.g-box-color,.text-center{text-align:center}.brand-color,.flex-group,.paragraph-styles,.section-column{display:flex}body{padding:0}.container{max-width:960px;margin:100px auto}.style-guide-header{margin-bottom:40px}.g-row{margin-left:-20px;margin-right:-20px}.g-box-color,.g-box-text{flex:1;margin:10px 20px}.brand-color{color:#fff}.g-title-small{padding-top:15px;border-top:1px solid #ddd}.container :first-of-type .g-title-small{border:none}.container .flex-group .g-title-small{border-top:1px solid #ddd}.g-box-color{padding:20px}.text-right{text-align:right}.text-left{text-align:left}.inherit{color:#555}.section{margin-bottom:50px}.flex-group>*{flex:1;margin:10px 20px}.serif-font{font-family:Georgia,"Times New Roman",Times,serif}body,h1,h2,h3,h4,h5,h6{font-family:Lato,"Helvetica Neue",Helvetica,Arial,sans-serif}.section-column{flex-direction:column;align-items:flex-start}.section-column .g-input-field{width:100%}.g-input-field{margin-bottom:15px;padding:0 10px}.g-input-field:last-of-type{margin-bottom:0}.g-label{margin-bottom:5px;margin-top:15px}.g-flex-row-start{display:flex;align-items:center;justify-content:flex-start}.checkbox-wrap{margin-bottom:10px}.checkbox-wrap:last-of-type{margin-bottom:0}input[type=radio],input[type=checkbox]{margin:0 5px 2px 0}body{background:#fff;color:#2C3E50;line-height:1.42857143}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:10px;font-weight:400;line-height:1.1;color:inherit}h1{font-size:39px}h2{font-size:32px}h3{font-size:26px}h4{font-size:19px}h5{font-size:15px}h6{font-size:13px}a,a:hover{color:#18BC9C}.bg-primary{background:#2C3E50}.bg-success{background:#18BC9C}.bg-info{background:#3498DB}.bg-warning{background:#F39C12}.bg-danger{background:#E74C3C}.bg-gray-base{background:#000}.bg-gray-darker{background:#222}.bg-gray-dark{background:#7b8a8b}.bg-gray{background:#95a5a6}.bg-gray-light{background:#b4bcc2}.bg-gray-lighter{background:#ecf0f1}.text-color{color:#2C3E50}.text-muted{color:#b4bcc2}.alert-box{padding:5px}.text-success{color:#fff;background:#18BC9C;border:1px solid #18BC9C}.text-info{color:#fff;background:#3498DB;border:1px solid #3498DB}.text-warning{color:#fff;background:#F39C12;border:1px solid #F39C12}.text-danger{color:#fff;background:#E74C3C;border:1px solid #E74C3C}.g-input-field{height:45px;background:#fff;color:#2C3E50;border:1px solid #dce4ec;border-radius:4px}.g-input-field:focus{border-color:#2C3E50}.input--large{height:66px}.input--small{height:35px}.g-input-field[disabled]{background:#ecf0f1}.has-error .g-label{color:#E74C3C}.has-error .g-input-field{border-color:#E74C3C}.has-warning .g-label{color:#F39C12}.has-warning .g-input-field{border-color:#F39C12}.has-success .g-label{color:#18BC9C}.has-success .g-input-field{border-color:#18BC9C}::-webkit-input-placeholder{color:#acb6c0}::-moz-placeholder{color:#acb6c0}:-ms-input-placeholder{color:#acb6c0}:-moz-placeholder{color:#acb6c0} | 2,917 | 2,917 | 0.785053 |
04403aca717e288007c1ec9cb13bbeb7a8d69f4f | 4,002 | asm | Assembly | Transynther/x86/_processed/NC/_zr_/i9-9900K_12_0xa0_notsx.log_21829_158.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NC/_zr_/i9-9900K_12_0xa0_notsx.log_21829_158.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NC/_zr_/i9-9900K_12_0xa0_notsx.log_21829_158.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
// REPMOV
lea addresses_D+0x9296, %rsi
lea addresses_D+0xb7ce, %rdi
nop
nop
cmp %rdx, %rdx
mov $20, %rcx
rep movsb
nop
nop
nop
nop
and %rsi, %rsi
// Faulty Load
mov $0x3939c20000000bce, %rdx
nop
nop
nop
nop
dec %rsi
movb (%rdx), %r11b
lea oracles, %r10
and $0xff, %r11
shlq $12, %r11
mov (%r10,%r11,1), %r11
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_NC', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D', 'congruent': 10, 'same': False}}
[Faulty Load]
{'src': {'type': 'addresses_NC', 'AVXalign': False, 'size': 1, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
| 65.606557 | 2,999 | 0.662419 |
45226197b0ba0e82a8e9233f35ab237cdb51cd74 | 830 | sql | SQL | Server/htdocs/AppController/commands_RSM/updater/server/phpUpdate_From_v6.2.0.3.149_to_v6.3.0.3.150/update_post.sql | Redsauce/RSM-Core | 9fd0c674dc81d3d344a3d86e11c782f8b2d2f34c | [
"MIT"
] | 2 | 2017-12-14T17:21:58.000Z | 2020-09-27T09:31:13.000Z | Server/htdocs/AppController/commands_RSM/updater/server/phpUpdate_From_v6.2.0.3.149_to_v6.3.0.3.150/update_post.sql | Redsauce/RSM-Core | 9fd0c674dc81d3d344a3d86e11c782f8b2d2f34c | [
"MIT"
] | null | null | null | Server/htdocs/AppController/commands_RSM/updater/server/phpUpdate_From_v6.2.0.3.149_to_v6.3.0.3.150/update_post.sql | Redsauce/RSM-Core | 9fd0c674dc81d3d344a3d86e11c782f8b2d2f34c | [
"MIT"
] | null | null | null | # Insert the application version with changes in the PHP layer
INSERT INTO rs_dbchanges (RS_ID, RS_PREVIOUS_VERSION, RS_NEW_VERSION, RS_EXECUTION_DATE, RS_COMMENTS)
VALUES (NULL, '6.2.0.3.149', '6.3.0.3.150', NOW(), 'Support for financial documents booking dates. Allow to work with designated financial documents already booked.');
UPDATE rs_property_app_definitions SET RS_NAME = 'financial.documents.bookDate', RS_DESCRIPTION = 'Indicates the date in which the document was booked' WHERE rs_property_app_definitions.RS_ID = 155;
REPLACE INTO rs_property_app_definitions (RS_ID, RS_NAME, RS_ITEM_TYPE_ID, RS_DESCRIPTION, RS_DEFAULTVALUE, RS_TYPE, RS_REFERRED_ITEMTYPE) VALUES ('198', 'financial.documents.ignoreBooked', '37', 'Allow to work with the financial document independently of the booked state', NULL, 'text', '0');
| 103.75 | 295 | 0.798795 |
eb00bc6d11dbfa950f0d87c9c83935a5b1512b00 | 597 | swift | Swift | Sources/KeyboardKitSwiftUI/Settings/PersistedKeyboardSetting+Identifiable.swift | Brennanium/KeyboardKitSwiftUI | 843b36c106afd1c31b49b6e1ea5e1f3e570b631b | [
"MIT"
] | 70 | 2020-03-20T00:26:46.000Z | 2022-02-28T13:37:17.000Z | Sources/KeyboardKitSwiftUI/Settings/PersistedKeyboardSetting+Identifiable.swift | Brennanium/KeyboardKitSwiftUI | 843b36c106afd1c31b49b6e1ea5e1f3e570b631b | [
"MIT"
] | 9 | 2020-09-06T11:56:13.000Z | 2021-01-26T21:36:55.000Z | Sources/KeyboardKitSwiftUI/Settings/PersistedKeyboardSetting+Identifiable.swift | Brennanium/KeyboardKitSwiftUI | 843b36c106afd1c31b49b6e1ea5e1f3e570b631b | [
"MIT"
] | 8 | 2020-06-16T04:36:40.000Z | 2021-01-16T06:24:33.000Z | //
// PersistedKeyboardSetting+Identifiable.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2020-06-09.
// Copyright © 2020 Daniel Saidi. All rights reserved.
//
import Foundation
import KeyboardKit
public extension PersistedKeyboardSetting {
init<Context: Identifiable>(
_ setting: KeyboardSetting,
context: Context,
default defaultValue: Value,
userDefaults: UserDefaults = .standard) {
self.init(
key: setting.key(for: context),
default: defaultValue,
userDefaults: userDefaults
)
}
}
| 22.961538 | 55 | 0.644891 |
17b472daad2c75b28d5661fff6c6ab3bf169b478 | 1,482 | kt | Kotlin | src/test/kotlin/me/lensvol/blackconnect/FileSaveTriggerTestCase.kt | studioj/intellij-blackconnect | cd52aff0ffb7a6fd038a578e26699af73b836527 | [
"MIT"
] | 31 | 2020-06-04T19:07:46.000Z | 2022-03-17T04:05:46.000Z | src/test/kotlin/me/lensvol/blackconnect/FileSaveTriggerTestCase.kt | studioj/intellij-blackconnect | cd52aff0ffb7a6fd038a578e26699af73b836527 | [
"MIT"
] | 25 | 2020-05-20T01:11:52.000Z | 2022-03-30T06:33:25.000Z | src/test/kotlin/me/lensvol/blackconnect/FileSaveTriggerTestCase.kt | studioj/intellij-blackconnect | cd52aff0ffb7a6fd038a578e26699af73b836527 | [
"MIT"
] | 3 | 2020-09-04T20:01:55.000Z | 2021-12-01T04:22:52.000Z | package me.lensvol.blackconnect
import org.junit.Test
class FileSaveTriggerTestCase : BlackConnectTestCase() {
@Test
fun test_file_reformatted_on_save_if_enabled() {
val unformattedFile = openFileInEditor("unformatted.py")
val document = documentForFile(unformattedFile)
setupBlackdResponse(BlackdResponse.Blackened("print(\"123\")"))
pluginConfiguration.triggerOnEachSave = true
FileSaveListener(myFixture.project).beforeDocumentSaving(document)
myFixture.checkResult("print(\"123\")")
}
@Test
fun test_file_is_not_reformatted_on_save_if_disabled() {
val unformattedFile = openFileInEditor("unformatted.py")
val document = documentForFile(unformattedFile)
setupBlackdResponse(BlackdResponse.Blackened("print(\"123\")"))
pluginConfiguration.triggerOnEachSave = false
FileSaveListener(myFixture.project).beforeDocumentSaving(document)
myFixture.checkResultByFile("unformatted.py")
}
@Test
fun test_unsupported_file_is_not_reformatted_on_save_even_if_enabled() {
val unformattedFile = openFileInEditor("not_python.txt")
val document = documentForFile(unformattedFile)
setupBlackdResponse(BlackdResponse.Blackened("print(\"123\")"))
pluginConfiguration.triggerOnEachSave = true
FileSaveListener(myFixture.project).beforeDocumentSaving(document)
myFixture.checkResultByFile("not_python.txt")
}
}
| 35.285714 | 76 | 0.734143 |
0265c3f8254ce9a43580511caab61592b57f4845 | 278 | asm | Assembly | non-destructive-payload32.asm | fiercebrute/d0zer | cd81a8e709ec649fba77372cdf05b08e2aa9ee91 | [
"MIT"
] | 137 | 2021-06-16T22:31:52.000Z | 2022-02-19T19:25:40.000Z | non-destructive-payload32.asm | chennqqi/d0zer | cd81a8e709ec649fba77372cdf05b08e2aa9ee91 | [
"MIT"
] | null | null | null | non-destructive-payload32.asm | chennqqi/d0zer | cd81a8e709ec649fba77372cdf05b08e2aa9ee91 | [
"MIT"
] | 29 | 2021-06-17T04:56:54.000Z | 2022-02-11T11:42:53.000Z | global _start
section .text
_start:
jmp message
message:
call shellcode
db "hello -- this is a non-destructive payload", 0xa
shellcode:
pop ecx
mov ebx, 1
mov edx, 0x2a
mov eax, 4
int 0x80
;mov eax, 1
;mov ebx, 0
;int 0x80 | 13.9 | 56 | 0.589928 |
2166d80e92d15fc8fa27df504509af19b8a142cb | 7,611 | lua | Lua | modules/autoskill.lua | TryBane/FGO_LuaAdjustments | 78d0e3e60739578e2db22f84c44e6bdd17e40728 | [
"MIT"
] | null | null | null | modules/autoskill.lua | TryBane/FGO_LuaAdjustments | 78d0e3e60739578e2db22f84c44e6bdd17e40728 | [
"MIT"
] | 1 | 2019-01-21T10:21:10.000Z | 2019-01-21T10:21:10.000Z | modules/autoskill.lua | TryBane/FGO_LuaAdjustments | 78d0e3e60739578e2db22f84c44e6bdd17e40728 | [
"MIT"
] | null | null | null | -- modules
local _battle
local _card
-- consts
local SKILL_OK_CLICK = Location(1680,850)
local MASTER_SKILL_OPEN_CLICK = Location(2380,640)
local ORDER_CHANGE_OK_CLICK = Location(1280,1260)
local SKILL_1_CLICK = Location( 140,1160)
local SKILL_2_CLICK = Location( 340,1160)
local SKILL_3_CLICK = Location( 540,1160)
local SKILL_4_CLICK = Location( 770,1160)
local SKILL_5_CLICK = Location( 970,1160)
local SKILL_6_CLICK = Location(1140,1160)
local SKILL_7_CLICK = Location(1400,1160)
local SKILL_8_CLICK = Location(1600,1160)
local SKILL_9_CLICK = Location(1800,1160)
local MASTER_SKILL_1_CLICK = Location(1820,620)
local MASTER_SKILL_2_CLICK = Location(2000,620)
local MASTER_SKILL_3_CLICK = Location(2160,620)
local SERVANT_1_CLICK = Location(700,880)
local SERVANT_2_CLICK = Location(1280,880)
local SERVANT_3_CLICK = Location(1940,880)
local SKILL_CLICK_ARRAY = {
[ 1] = SKILL_1_CLICK,
[ 2] = SKILL_2_CLICK,
[ 3] = SKILL_3_CLICK,
[ 4] = SKILL_4_CLICK,
[ 5] = SKILL_5_CLICK,
[ 6] = SKILL_6_CLICK,
[ 7] = SKILL_7_CLICK,
[ 8] = SKILL_8_CLICK,
[ 9] = SKILL_9_CLICK,
[ 10] = MASTER_SKILL_1_CLICK,
[ 11] = MASTER_SKILL_2_CLICK,
[ 12] = MASTER_SKILL_3_CLICK,
[-47] = SERVANT_1_CLICK,
[-46] = SERVANT_2_CLICK,
[-45] = SERVANT_3_CLICK
}
-- Order Change (front)
local STARTING_MEMBER_1_CLICK = Location( 280,700)
local STARTING_MEMBER_2_CLICK = Location( 680,700)
local STARTING_MEMBER_3_CLICK = Location(1080,700)
local STARTING_MEMBER_CLICK_ARRAY = {
[-47] = STARTING_MEMBER_1_CLICK,
[-46] = STARTING_MEMBER_2_CLICK,
[-45] = STARTING_MEMBER_3_CLICK
}
-- Order Change (back)
local SUB_MEMBER_1_CLICK = Location(1480,700)
local SUB_MEMBER_2_CLICK = Location(1880,700)
local SUB_MEMBER_3_CLICK = Location(2280,700)
local SUB_MEMBER_CLICK_ARRAY = {
[-47] = SUB_MEMBER_1_CLICK,
[-46] = SUB_MEMBER_2_CLICK,
[-45] = SUB_MEMBER_3_CLICK
}
-- state vars
local _hasFinishedCastingNp
local _isOrderChanging = 0
local _stageCountByUserInput = 1
local _commandsForEachStageArray = {{}, {}, {}, {}, {}}
local _totalNeededTurnArray = {0, 0, 0, 0, 0}
local _turnCounterForEachStageArray
-- functions
local init
local initDependencies
local initCommands
local resetState
local executeSkill
local decodeSkill
local hasFinishedCastingNp
init = function(battle, card)
initDependencies(battle, card)
if Enable_Autoskill == 1 then
initCommands()
end
resetState()
end
initDependencies = function(battle, card)
_battle = battle
_card = card
SKILL_CLICK_ARRAY[-44] = _card.getNpCardLocation(1)
SKILL_CLICK_ARRAY[-43] = _card.getNpCardLocation(2)
SKILL_CLICK_ARRAY[-42] = _card.getNpCardLocation(3)
end
initCommands = function()
for char in string.gmatch(Skill_Command, "[^,]+") do
if string.match(char, "[^0]") ~= nil then
if string.match(char, "^[1-3]") ~= nil then
scriptExit("Error at '" .. char .. "': Skill Command cannot start with number '1', '2' and '3'!")
elseif string.match(char, "[%w+][#]") ~= nil or string.match(char, "[#][%w+]") ~= nil then
scriptExit("Error at '" .. char .. "': '#' must be preceded and followed by ','! Correct: ',#,' ")
elseif string.match(char, "[^a-l^1-6^#^x]") ~= nil then
scriptExit("Error at '" .. char .. "': Skill Command exceeded alphanumeric range! Expected 'x' or range 'a' to 'l' for alphabets and '0' to '6' for numbers.")
end
end
if char == '#' then
_stageCountByUserInput = _stageCountByUserInput + 1
if _stageCountByUserInput > 5 then
scriptExit("Error: Detected commands for more than 5 stages")
end
end
-- Autoskill table popup.
if char ~= '#' then
table.insert(_commandsForEachStageArray[_stageCountByUserInput], char)
_totalNeededTurnArray[_stageCountByUserInput] = _totalNeededTurnArray[_stageCountByUserInput] + 1
end
end
end
resetState = function()
_hasFinishedCastingNp = Enable_Autoskill == 0
_turnCounterForEachStageArray = {0, 0, 0, 0, 0}
end
executeSkill = function ()
local currentStage = _battle.getCurrentStage()
_turnCounterForEachStageArray[currentStage] = _turnCounterForEachStageArray[currentStage] + 1
local currentTurn = _turnCounterForEachStageArray[currentStage]
if currentTurn <= _totalNeededTurnArray[currentStage] then
-- _commandsForEachStageArray is a two-dimensional array with something like abc1jkl4.
local currentSkill = _commandsForEachStageArray[currentStage][currentTurn]
--[[Prevent exessive delay between skill clickings.
isFirstSkill = 1 means more delay, cause one has to wait for battle animation.
isFirstSkill = 0 means less delay.
--]]
local isFirstSkill = 1
if currentSkill ~= '0' and currentSkill ~= '#' then
for command in string.gmatch(currentSkill, ".") do
decodeSkill(command, isFirstSkill)
isFirstSkill = 0
end
end
if not _battle.hasClickedAttack() then
-- Wait for regular servant skill animation executed last time. Then proceed to next turn.
wait(2.7)
end
end
-- this will allow NP spam AFTER all of the autoskill commands finish
if currentStage >= _stageCountByUserInput and _commandsForEachStageArray[currentStage][currentTurn] == nil then
_hasFinishedCastingNp = true
end
end
decodeSkill = function(str, isFirstSkill)
-- magic number - check ascii code, a == 97. http://www.asciitable.com/
local index = string.byte(str) - 96
--[[isFirstSkill == 0: Not yet proceeded to next turn.
index >= -44 and _isOrderChanging == 0: Not currently doing Order Change.
Therefore, script is casting regular servant skills.
--]]
if isFirstSkill == 0 and not _battle.hasClickedAttack() and index >= -44 and _isOrderChanging == 0 then
-- Wait for regular servant skill animation executed last time.
-- Do not make it shorter, at least 2.9s. Napoleon's skill animation is ridiculously long.
wait(3.3)
end
--[[In ascii, char(4, 5, 6) command for servant NP456 = decimal(52, 53, 54) respectively.
Hence:
52 - 96 = -44
53 - 96 = -43
54 - 96 = -42
--]]
if index >= -44 and index <= -42 and not _battle.hasClickedAttack() then
_battle.clickAttack()
end
--[[In ascii, char(j, k, l) and char(x) command for master skill = decimal(106, 107, 108) and decimal(120) respectively.
Hence:
106 - 96 = 10
107 - 96 = 11
108 - 96 = 12
120 - 96 = 24
--]]
if index >= 10 then
-- Click master skill menu icon, ready to cast master skill.
click(MASTER_SKILL_OPEN_CLICK)
wait(0.3)
end
--[[Enter Order Change Mode.
In ascii, char(x) = decimal(120)
120 - 96 = 24
--]]
if index == 24 then
_isOrderChanging = 1
end
-- MysticCode-OrderChange master skill implementation.
-- Actual clicking is done by the default case here.
if _isOrderChanging == 1 then
-- click Order Change icon.
click(SKILL_CLICK_ARRAY[12])
_isOrderChanging = 2
elseif _isOrderChanging == 2 then
click(STARTING_MEMBER_CLICK_ARRAY[index])
_isOrderChanging = 3
elseif _isOrderChanging == 3 then
click(SUB_MEMBER_CLICK_ARRAY[index])
wait(0.3)
click(ORDER_CHANGE_OK_CLICK)
_isOrderChanging = 0
wait(5)
else
-- cast skills, NPs, or select target.
click(SKILL_CLICK_ARRAY[index])
end
if index > 0 and Skill_Confirmation == 1 then
click(SKILL_OK_CLICK)
end
end
local hasFinishedCastingNp = function()
return _hasFinishedCastingNp
end
-- "public" interface
return {
init = init,
resetState = resetState,
executeSkill = executeSkill,
hasFinishedCastingNp = hasFinishedCastingNp
} | 30.566265 | 163 | 0.704112 |
3b46ff879819c4b3524a0458971307e931db9255 | 9,017 | asm | Assembly | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_775.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_775.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48_notsx.log_21829_775.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r8
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x1c634, %rsi
lea addresses_UC_ht+0xa34c, %rdi
nop
nop
nop
xor $34784, %r11
mov $97, %rcx
rep movsq
nop
nop
and %r8, %r8
lea addresses_WT_ht+0x1c3b4, %rsi
lea addresses_WT_ht+0x183cc, %rdi
nop
nop
nop
nop
nop
dec %r10
mov $118, %rcx
rep movsq
nop
nop
nop
nop
nop
xor %rdi, %rdi
lea addresses_normal_ht+0x3d54, %rsi
nop
xor $8035, %r10
mov $0x6162636465666768, %r8
movq %r8, (%rsi)
nop
and $56840, %rdi
lea addresses_WT_ht+0x156b4, %rdi
nop
xor %r9, %r9
mov (%rdi), %r10
nop
nop
xor $53883, %r11
lea addresses_normal_ht+0x19b4, %r9
nop
nop
nop
nop
nop
xor %r11, %r11
movw $0x6162, (%r9)
nop
nop
nop
nop
nop
and %r9, %r9
lea addresses_D_ht+0x1a8b4, %rsi
lea addresses_UC_ht+0x25b4, %rdi
nop
nop
nop
sub $33624, %r12
mov $1, %rcx
rep movsw
nop
mfence
lea addresses_A_ht+0x15fb4, %rsi
lea addresses_normal_ht+0x1bfb4, %rdi
nop
nop
cmp $48637, %r8
mov $35, %rcx
rep movsb
nop
nop
xor %r11, %r11
lea addresses_A_ht+0x167c4, %rsi
lea addresses_D_ht+0xd3b4, %rdi
dec %r8
mov $21, %rcx
rep movsl
nop
and $21466, %r11
lea addresses_UC_ht+0x126aa, %r10
nop
and %rdi, %rdi
vmovups (%r10), %ymm4
vextracti128 $0, %ymm4, %xmm4
vpextrq $1, %xmm4, %rcx
xor %rsi, %rsi
lea addresses_A_ht+0x1794, %r11
nop
nop
nop
nop
inc %r10
vmovups (%r11), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $1, %xmm2, %r9
nop
nop
nop
nop
nop
sub $34184, %r10
lea addresses_normal_ht+0x5bf4, %r8
and %rsi, %rsi
mov (%r8), %r9w
nop
nop
nop
add %r9, %r9
lea addresses_WT_ht+0x1d44, %rsi
lea addresses_WT_ht+0xb04, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
add $17955, %r10
mov $15, %rcx
rep movsb
nop
nop
nop
nop
lfence
lea addresses_WT_ht+0x1dbb4, %rsi
lea addresses_normal_ht+0x16174, %rdi
dec %r10
mov $20, %rcx
rep movsw
nop
nop
sub %rcx, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r15
push %r9
push %rax
push %rcx
push %rdx
push %rsi
// Store
lea addresses_normal+0x21b4, %rdx
nop
nop
nop
nop
nop
dec %r12
movb $0x51, (%rdx)
nop
nop
nop
and $16130, %rsi
// Store
lea addresses_A+0x1b610, %rcx
nop
nop
nop
nop
nop
dec %r15
mov $0x5152535455565758, %rdx
movq %rdx, %xmm6
movups %xmm6, (%rcx)
nop
add $45261, %rdx
// Store
lea addresses_RW+0x13934, %r9
nop
nop
nop
inc %r12
mov $0x5152535455565758, %rcx
movq %rcx, %xmm1
movups %xmm1, (%r9)
sub %r12, %r12
// Store
lea addresses_WC+0xde65, %r9
nop
nop
nop
xor $18253, %rdx
mov $0x5152535455565758, %r12
movq %r12, %xmm4
movups %xmm4, (%r9)
nop
nop
add %r9, %r9
// Store
mov $0x35fe9e0000000ed4, %r15
nop
nop
nop
cmp $33139, %rsi
movl $0x51525354, (%r15)
nop
nop
nop
nop
sub $21600, %r15
// Load
lea addresses_RW+0x1e834, %r12
nop
nop
nop
cmp %rsi, %rsi
vmovups (%r12), %ymm1
vextracti128 $1, %ymm1, %xmm1
vpextrq $1, %xmm1, %rax
nop
nop
nop
nop
nop
xor $58374, %r15
// Faulty Load
lea addresses_PSE+0xbfb4, %rdx
nop
nop
nop
sub %r12, %r12
mov (%rdx), %ax
lea oracles, %r12
and $0xff, %rax
shlq $12, %rax
mov (%r12,%rax,1), %rax
pop %rsi
pop %rdx
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_PSE', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_normal', 'congruent': 9}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A', 'congruent': 2}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_RW', 'congruent': 4}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WC', 'congruent': 0}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_NC', 'congruent': 5}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_RW', 'congruent': 5}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_PSE', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_UC_ht'}}
{'dst': {'same': True, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_WT_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal_ht', 'congruent': 5}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WT_ht', 'congruent': 7}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal_ht', 'congruent': 9}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 8, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_D_ht'}}
{'dst': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_A_ht'}}
{'dst': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 1, 'type': 'addresses_A_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC_ht', 'congruent': 1}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 5}}
{'OP': 'LOAD', 'src': {'same': True, 'NT': True, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal_ht', 'congruent': 5}}
{'dst': {'same': False, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 3, 'type': 'addresses_WT_ht'}}
{'dst': {'same': False, 'congruent': 6, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
| 30.462838 | 2,999 | 0.656649 |
d7199d89b889fea94ef3fba8066278736bc53ced | 429 | sql | SQL | openGaussBase/testcase/KEYWORDS/admin/Opengauss_Function_Keyword_Admin_Case0032.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/KEYWORDS/admin/Opengauss_Function_Keyword_Admin_Case0032.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/KEYWORDS/admin/Opengauss_Function_Keyword_Admin_Case0032.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | -- @testpoint:opengauss关键字admin(非保留),作为用户名
--关键字admin作为用户名不带引号,创建成功
drop user if exists admin;
CREATE USER admin PASSWORD 'Bigdata@123';
--清理环境
drop user admin;
--关键字admin作为用户名加双引号,创建成功
drop user if exists "admin";
CREATE USER "admin" PASSWORD 'Bigdata@123';
--清理环境
drop user "admin";
--关键字admin作为用户名加单引号,合理报错
CREATE USER 'admin' PASSWORD 'Bigdata@123';
--关键字admin作为用户名加反引号,合理报错
CREATE USER `admin` PASSWORD 'Bigdata@123';
| 20.428571 | 43 | 0.759907 |
d2bb8894aa32fdc6285f266f9035c4cb67927d82 | 3,809 | sql | SQL | tablas_necesarias.sql | jaimeirazabal1/productos_espera | 36e20efbc662c18458f4051651521294e1fffb85 | [
"BSD-3-Clause"
] | null | null | null | tablas_necesarias.sql | jaimeirazabal1/productos_espera | 36e20efbc662c18458f4051651521294e1fffb85 | [
"BSD-3-Clause"
] | null | null | null | tablas_necesarias.sql | jaimeirazabal1/productos_espera | 36e20efbc662c18458f4051651521294e1fffb85 | [
"BSD-3-Clause"
] | null | null | null |
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 03-04-2016 a las 12:16:18
-- Versión del servidor: 10.1.9-MariaDB
-- Versión de PHP: 5.6.15
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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 */;
--
-- Base de datos: `productos_espera_cesar`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `estado_productos`
--
CREATE TABLE `estado_productos` (
`id` int(11) NOT NULL,
`estado_id` int(11) NOT NULL,
`productos_espera_id` int(11) NOT NULL,
`creado` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `estado_productos`
--
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `estado_productos`
--
ALTER TABLE `estado_productos`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `estado_productos`
--
ALTER TABLE `estado_productos`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 03-04-2016 a las 12:16:59
-- Versión del servidor: 10.1.9-MariaDB
-- Versión de PHP: 5.6.15
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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 */;
--
-- Base de datos: `productos_espera_cesar`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `productos_espera`
--
CREATE TABLE `productos_espera` (
`id` int(11) NOT NULL,
`producto` varchar(10) NOT NULL,
`nombre_producto` varchar(200) NOT NULL,
`sucursal` varchar(10) NOT NULL,
`cliente` varchar(200) NOT NULL,
`telefono` varchar(100) NOT NULL,
`estado_producto_id` int(11) DEFAULT NULL,
`fecha` datetime NOT NULL,
`observacion` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `productos_espera`
--
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `productos_espera`
--
ALTER TABLE `productos_espera`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `productos_espera`
--
ALTER TABLE `productos_espera`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
CREATE TABLE `estado` (
`id` int(11) NOT NULL,
`nombre` varchar(150) NOT NULL,
`color` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Volcado de datos para la tabla `estado`
--
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `estado`
--
ALTER TABLE `estado`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `estado`
--
ALTER TABLE `estado`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
| 22.538462 | 67 | 0.695721 |
2908a64626d13cd6ee7897d652cff7427ee39c1e | 162 | py | Python | twiml/voice/say/say-2/say-2.6.x.py | Tshisuaka/api-snippets | 52b50037d4af0f3b96adf76197964725a1501e96 | [
"MIT"
] | 234 | 2016-01-27T03:04:38.000Z | 2022-02-25T20:13:43.000Z | twiml/voice/say/say-2/say-2.6.x.py | Tshisuaka/api-snippets | 52b50037d4af0f3b96adf76197964725a1501e96 | [
"MIT"
] | 351 | 2016-04-06T16:55:33.000Z | 2022-03-10T18:42:36.000Z | twiml/voice/say/say-2/say-2.6.x.py | Tshisuaka/api-snippets | 52b50037d4af0f3b96adf76197964725a1501e96 | [
"MIT"
] | 494 | 2016-03-30T15:28:20.000Z | 2022-03-28T19:39:36.000Z | from twilio.twiml.voice_response import VoiceResponse, Say
response = VoiceResponse()
response.say('Chapeau!', voice='alice', language='fr-FR')
print(response)
| 23.142857 | 58 | 0.771605 |
0576b97a39ec7d7acd1c1cf296ee2828b8e9fe2f | 2,239 | rb | Ruby | spec/unit/desk_platform_rpt/twitter_stream_consumer_spec.rb | montague/desk_platform_rpt | b084010be71c941b6a9fbaf8124600ce64bd96c1 | [
"MIT"
] | null | null | null | spec/unit/desk_platform_rpt/twitter_stream_consumer_spec.rb | montague/desk_platform_rpt | b084010be71c941b6a9fbaf8124600ce64bd96c1 | [
"MIT"
] | 4 | 2016-02-25T15:59:04.000Z | 2016-02-26T14:56:32.000Z | spec/unit/desk_platform_rpt/twitter_stream_consumer_spec.rb | montague/desk_platform_rpt | b084010be71c941b6a9fbaf8124600ce64bd96c1 | [
"MIT"
] | null | null | null | require 'spec_helper'
describe DeskPlatformRpt::TwitterStreamConsumer do
describe '#consume' do
let(:consumer) { DeskPlatformRpt::TwitterStreamConsumer.new }
it 'initializes its inner state to be empty' do
expect(consumer.raw_messages_queue).to be_empty
expect(consumer.fragment).to be_empty
end
it 'loads messages on its queue' do
consumer.consume("1234\r\n")
expect(consumer.raw_messages_queue.pop).to eq "1234\r\n"
expect(consumer.raw_messages_queue).to be_empty
end
it "loads the stream_sample on its queue with a chunk size of 1500" do
file_path = File.expand_path('../../../fixtures/stream_sample.txt', __FILE__)
chunk_size = 500 # nice and chunky
File.open(file_path) do |io|
while chunk = io.read(chunk_size)
consumer.consume(chunk)
end
end
expect(consumer.raw_messages_queue.size).to eq 26
end
it 'does not push a fragment onto its queue' do
consumer.consume("1234\r\n567")
expect(consumer.raw_messages_queue.pop).to eq "1234\r\n"
expect(consumer.raw_messages_queue).to be_empty
end
it 'consumes a message that has emoji' do
consumer.consume("1234\r\n567😀\r\n")
expect(consumer.raw_messages_queue.pop).to eq "1234\r\n"
expect(consumer.raw_messages_queue.pop).to eq "567😀\r\n"
expect(consumer.raw_messages_queue).to be_empty
end
it 'assembles chunked messages when the length is not followed by a message' do
consumer.consume("1234\r\nomg")
consumer.consume("5678\r\n")
expect(consumer.raw_messages_queue.pop).to eq "1234\r\n"
expect(consumer.raw_messages_queue.pop).to eq "omg5678\r\n"
expect(consumer.raw_messages_queue).to be_empty
end
it 'assembles chunked messages when the message is split over more than two chunks' do
consumer.consume("123\r\n123")
consumer.consume("456")
consumer.consume("789\r\n1234\r\n")
expect(consumer.raw_messages_queue.pop).to eq "123\r\n"
expect(consumer.raw_messages_queue.pop).to eq "123456789\r\n"
expect(consumer.raw_messages_queue.pop).to eq "1234\r\n"
expect(consumer.raw_messages_queue).to be_empty
end
end
end
| 32.926471 | 90 | 0.69406 |
445e764b2394327a86e7f8d25ca3295c31c35e96 | 292 | sql | SQL | Tables/BL/Version.sql | voicenter/MySwaggerHub | 7abd559682a488024e32f73f8a7d3765a12bd07f | [
"MIT"
] | null | null | null | Tables/BL/Version.sql | voicenter/MySwaggerHub | 7abd559682a488024e32f73f8a7d3765a12bd07f | [
"MIT"
] | null | null | null | Tables/BL/Version.sql | voicenter/MySwaggerHub | 7abd559682a488024e32f73f8a7d3765a12bd07f | [
"MIT"
] | null | null | null | CREATE TABLE Version
(
VersionID int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
VersionNumber double DEFAULT '0.1',
VersionName varchar(32),
VersionStatus tinyint(4),
InfoDescription varchar(1024),
InfoTitle varchar(64),
Host varchar(32),
SwaggerTemplate json
); | 26.545455 | 58 | 0.712329 |
0ed19351b5015cdf546df3d8a459ef30a38ae9f4 | 2,214 | sql | SQL | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/14.de.metas.dataentry/5521500_sys_gh5162_further group_to_tab_renames.sql | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/14.de.metas.dataentry/5521500_sys_gh5162_further group_to_tab_renames.sql | vestigegroup/metasfresh | 4b2d48c091fb2a73e6f186260a06c715f5e2fe96 | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/14.de.metas.dataentry/5521500_sys_gh5162_further group_to_tab_renames.sql | vestigegroup/metasfresh | 4b2d48c091fb2a73e6f186260a06c715f5e2fe96 | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z | -- 2019-05-14T06:17:04.114
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Window SET InternalName='DataEntry_Tab',Updated=TO_TIMESTAMP('2019-05-14 06:17:04','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Window_ID=540571
;
-- 2019-05-14T06:17:48.863
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Tab SET InternalName='DataEntry_SubTab',Updated=TO_TIMESTAMP('2019-05-14 06:17:48','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Tab_ID=541520
;
-- 2019-05-14T06:17:56.636
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Tab SET InternalName='DataEntry_Tab',Updated=TO_TIMESTAMP('2019-05-14 06:17:56','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Tab_ID=541519
;
-- 2019-05-14T06:47:12.889
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Column SET DefaultValue='@SQL=SELECT COALESCE(MAX(SeqNo),0)+10 AS DefaultValue FROM DataEntry_Tab WHERE DataEntry_TargetWindow_ID=@DataEntry_TargetWindow_ID/0@',Updated=TO_TIMESTAMP('2019-05-14 06:47:12','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=564209
;
-- 2019-05-14T06:53:03.615
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Column SET DefaultValue='@SQL=SELECT COALESCE(MAX(SeqNo),0)+10 AS DefaultValue FROM DataEntry_SubTab WHERE DataEntry_Group_ID=@DataEntry_Group_ID/0@',Updated=TO_TIMESTAMP('2019-05-14 06:53:03','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=564210
;
-- 2019-05-14T06:58:13.857
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Column SET DefaultValue='@SQL=SELECT COALESCE(MAX(SeqNo),0)+10 AS DefaultValue FROM DataEntry_SubTab WHERE DataEntry_Tab_ID=@DataEntry_Group_ID/0@',Updated=TO_TIMESTAMP('2019-05-14 06:58:13','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=564210
;
-- 2019-05-14T06:58:31.008
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Column SET DefaultValue='@SQL=SELECT COALESCE(MAX(SeqNo),0)+10 AS DefaultValue FROM DataEntry_SubTab WHERE DataEntry_Tab_ID=@DataEntry_Tab_ID/0@',Updated=TO_TIMESTAMP('2019-05-14 06:58:31','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=564210
;
| 61.5 | 278 | 0.794941 |
282ae3725a6ed0fbc911f576145e1913ae37390e | 5,072 | go | Go | model.go | banachtech/msmgo | b374fb967d90a5ad8786442a10265b5b62bf287d | [
"MIT"
] | null | null | null | model.go | banachtech/msmgo | b374fb967d90a5ad8786442a10265b5b62bf287d | [
"MIT"
] | null | null | null | model.go | banachtech/msmgo | b374fb967d90a5ad8786442a10265b5b62bf287d | [
"MIT"
] | null | null | null | package msm
import (
"fmt"
"math"
"os"
"sort"
"math/bits"
"golang.org/x/exp/rand"
"gonum.org/v1/gonum/mat"
"time"
"gonum.org/v1/gonum/stat"
"gonum.org/v1/gonum/stat/distuv"
"gonum.org/v1/gonum/optimize"
)
const ISPI = 1.0 / math.Sqrt2 / math.SqrtPi
// Compute transition probability matrix
func probMat(p []float64) *mat.Dense {
x := 1
a := mat.NewDense(2, 2, []float64{1, 1, 1, 1})
c := mat.NewDense(1, 1, []float64{1.0})
var tmp mat.Dense
for i := range p {
gi := p[i] * 0.5
a.Set(0, 0, 1.0-gi)
a.Set(0, 1, gi)
a.Set(1, 0, gi)
a.Set(1, 1, 1.0-gi)
tmp.Kronecker(c, a)
x = x * 2
c.Grow(x, x)
c.CloneFrom(&tmp)
tmp.Reset()
}
return c
}
// Compute volatilities corresponding to states
func sigma(m0 float64, s0 float64, k int, M []int) []float64 {
n := len(M)
s := make([]float64, n)
m1 := 2.0 - m0
for i := range s {
s[i] = s0 * math.Sqrt(math.Pow(m1, float64(M[i]))*math.Pow(m0, float64(k-M[i])))
}
return s
}
/* States expressed as number of "ON" states in total as that is what matters in computing volatility
*/
func states(k int) []int {
n := int(math.Pow(2.0, float64(k)))
st := make([]int, n)
for i := range st {
st[i] = bits.OnesCount(uint(i))
}
return st
}
// Sigmoid function
func sigmoid(x float64) float64 {
return 1.0 / (1.0 + math.Exp(-1.0*x))
}
// Compute negative log likelihood of MSM model
func negloglik(par []float64, x []float64, k int, states []int) float64 {
// Transform (-inf, inf) domain to appropriate parameter domains
p := transformParams(par)
n := len(states)
// Compute transition probability matrix for product of Markov chains
A := probMat(p[2:])
// Compute volatility of each state
s := sigma(p[0], p[1], k, states)
// Initialise unconditional probability distribution of states
B := make([]float64, n)
for i := range B {
B[i] = 1.0 / float64(n)
}
// Auxiliary variables
wx := make([]float64, n)
var tmp mat.Dense
sw := 0.0
// Initialise log-likelihood
ll := 0.0
for i := range x {
for j := range wx {
wx[j] = ISPI * math.Exp(-0.5*x[i]*x[i]/s[j]/s[j]) / s[j]
}
tmp.Mul(A, mat.NewDense(n, 1, B))
sw = 0.0
for j := range wx {
sw += wx[j] * tmp.At(j, 0)
}
ll += math.Log(sw)
for j := range B {
B[j] = wx[j] * tmp.At(j, 0) / sw
}
}
return -ll
}
func transformParams(par []float64) []float64 {
m := len(par)
p := make([]float64, m)
// Transform (-inf, inf) domain to (1,2) and (0,inf)
p[0], p[1] = 1.0+sigmoid(par[0]), math.Exp(par[1])
// Transform (-inf, inf) domain to probabilities
for i := 2; i < m; i++ {
p[i] = sigmoid(par[i])
}
return p
}
func simulate(par []float64, nsims int) []float64 {
m0, s0 := par[0], par[1]
p := par[2:]
k := len(p)
A := probMat(p)
M := states(k)
s := sigma(m0, s0, k, M)
x := make([]float64, nsims)
var st int
q := mat.Row(nil, 0, A)
d2 := distuv.NewCategorical(q, rand.NewSource(uint64(time.Now().UnixNano())))
st = int(d2.Rand())
d1 := distuv.Normal{Mu: 0.0, Sigma: 1.0}
x[0] = d1.Rand() * s[st]
for i := 1; i < nsims; i++ {
q = mat.Row(nil, st, A)
d2 = distuv.NewCategorical(q, rand.NewSource(uint64(time.Now().UnixNano())))
st = int(d2.Rand())
x[i] = d1.Rand() * s[st]
}
return x
}
func Predict(par []float64, paths int, pathLen int) []float64 {
vol := make([]float64, paths)
ret := make([]float64, pathLen)
for i := range vol {
ret = simulate(par, pathLen)
vol[i] = stat.StdDev(ret, nil)
}
res := make([]float64, 2)
res[0], res[1] = stat.MeanStdDev(vol, nil)
fmt.Printf("-------------- Vol prediction ---------------\n")
fmt.Printf("Mean:\t%0.4f\n", res[0])
fmt.Printf("SD:\t%0.4f\n", res[1])
fmt.Printf("----------------------------------------------\n")
return res
}
// Fit an MSM-BT model of dimension k to data x
func Fit(x []float64, k int) []float64 {
// initialise parameters for negloglik function
par := make([]float64, k+2)
dist := distuv.Normal{Mu: 0.0, Sigma: 1.0}
for i := range par {
par[i] = dist.Rand()
}
// Use sample standard deviation for s0 param of model
sd := stat.StdDev(x, nil)
par[1] = math.Log(sd)
// calculate Markov chain states
M := states(k)
// compute negative of log likelihood
start := time.Now()
problem := optimize.Problem{
Func: func(par []float64) float64 {
return negloglik(par, x, k, M)
},
}
result, err := optimize.Minimize(problem, par, nil, &optimize.NelderMead{})
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
fmt.Printf("---------- MSM-BT Model Fit Results ----------\n")
fmt.Printf("MLE took %v seconds\n", time.Since(start))
fmt.Printf("Numberof func evals: %d\n", result.Stats.FuncEvaluations)
fmt.Printf("Status:\t%v\n", result.Status)
fmt.Printf("Loglik:\t%0.f\n", result.F)
res := transformParams(result.X)
fmt.Printf("-------------- Model parameters --------------\n")
fmt.Printf("m0:\t%0.4f\n", res[0])
fmt.Printf("s0:\t%0.4f\n", res[1])
ps := res[2:]
sort.Float64s(ps)
for i := range ps {
fmt.Printf("p%d:\t%0.4f\n", i+1, ps[i])
}
// Return model parameters and objective value
res = append(res, result.F)
return res
}
| 23.159817 | 101 | 0.597003 |
39c62d49c65bdcac5e89a64ac7c3d0643a3b2c16 | 39 | js | JavaScript | packages/2036/04/28/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 7 | 2017-07-03T19:53:01.000Z | 2021-04-05T18:15:55.000Z | packages/2036/04/28/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 1 | 2018-09-05T11:53:41.000Z | 2018-12-16T12:36:21.000Z | packages/2036/04/28/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 2 | 2019-01-27T16:57:34.000Z | 2020-10-11T09:30:25.000Z | module.exports = new Date(2036, 3, 28)
| 19.5 | 38 | 0.692308 |
1c436f6ef993dcad3d6330a68e46825dee9ff012 | 928 | sql | SQL | testdata/initdb/sql/inserts.sql | jfkw/protoc-gen-map | 2028a1f5da9f382736362ea76b10bc727928434e | [
"Apache-2.0"
] | 131 | 2019-10-21T01:17:12.000Z | 2022-02-27T01:10:59.000Z | testdata/initdb/sql/inserts.sql | jfkw/protoc-gen-map | 2028a1f5da9f382736362ea76b10bc727928434e | [
"Apache-2.0"
] | 9 | 2019-11-04T12:48:26.000Z | 2020-07-21T16:26:39.000Z | testdata/initdb/sql/inserts.sql | jfkw/protoc-gen-map | 2028a1f5da9f382736362ea76b10bc727928434e | [
"Apache-2.0"
] | 10 | 2019-11-04T05:49:08.000Z | 2022-02-08T03:03:10.000Z | {{define "InsertAuthor" }}
INSERT INTO author
VALUES (
{{ .Id }},
{{ .Username | squote }},
{{ .Password | squote }},
{{ .Email | squote }},
{{ .Bio | squote }},
{{ .FavouriteSection | squote }}
);
{{end}}
{{define "InsertBlog" }}
INSERT INTO blog
VALUES (
{{ .Id }},
{{ .Title | squote }},
{{ .AuthorId }}
);
{{end}}
{{define "InsertComment" }}
INSERT INTO comment
VALUES (
{{ .Id }},
{{ .PostId }},
{{ .Name | squote }},
{{ .Comment | squote }}
);
{{end}}
{{define "InsertPost" }}
INSERT INTO post
VALUES (
{{ .Id }},
{{ .AuthorId }},
{{ .BlogId }},
{{ .CreatedOn | timestamp | squote }},
{{ .Section | squote }},
{{ .Subject | squote }},
{{ .Draft | squote }},
{{ .Body | squote }}
);
{{end}}
{{define "InsertPostTag" }}
INSERT INTO post_tag
VALUES (
{{ .PostId }},
{{ .TagId }}
);
{{end}}
{{define "InsertTag" }}
INSERT INTO tag
VALUES (
{{ .Id }},
{{ .Name | squote }}
);
{{end}}
| 14.967742 | 39 | 0.520474 |
6727bb43af1314e126065d0b4ac4004b647c9263 | 8,919 | lua | Lua | themes/thunderclouds/components/startscreen.lua | ffs97/awesome-config | 1ef4e3f1973af79574fa970074b00054791ca0f6 | [
"MIT"
] | null | null | null | themes/thunderclouds/components/startscreen.lua | ffs97/awesome-config | 1ef4e3f1973af79574fa970074b00054791ca0f6 | [
"MIT"
] | null | null | null | themes/thunderclouds/components/startscreen.lua | ffs97/awesome-config | 1ef4e3f1973af79574fa970074b00054791ca0f6 | [
"MIT"
] | null | null | null | -- =====================================================================================
-- Name: keys.lua
-- Author: Gurpreet Singh
-- Url: https://github.com/ffs97/awesome-config/themes/thunderclouds/ ...
-- ... widgets/startscreen.lua
-- License: The MIT License (MIT)
--
-- Widget for custom dashboard
-- =====================================================================================
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local beautiful = require("beautiful").startscreen
-- -------------------------------------------------------------------------------------
-- Including Custom Helper Libraries
local helpers = require("helpers")
local animation = require("animation.animation")
-- -------------------------------------------------------------------------------------
-- Defining Helper Functions for Creating Startscreen
local function get_width()
local width = beautiful.width
if type(width) == "function" then
width = width()
else
width = width or awful.screen.focused().geometry.width
end
return width + (beautiful.border_width or 0) * 2
end
local function get_height()
local height = beautiful.height
if type(height) == "function" then
height = height()
else
height = height or awful.screen.focused().geometry.height
end
return height + (beautiful.border_width or 0) * 2
end
local function get_x(width)
local x = beautiful.x
if type(x) == "function" then
x = x()
else
x = x or (awful.screen.focused().geometry.width - width) / 2
end
return x
end
local function get_y(height)
local y = beautiful.y
if type(y) == "function" then
y = y()
else
y = y or (awful.screen.focused().geometry.height - height) / 2
end
return y
end
-- -------------------------------------------------------------------------------------
-- Defining Function to Create a Startscreen
local function create_startscreen(screen)
----------------------------------------------------------------------------
-- Creating the StartScreen
local startscreen = wibox {visible = false, ontop = true, type = "dock"}
local startscreen_bg =
wibox.widget {
helpers.empty_widget,
opacity = beautiful.bg_opacity,
widget = wibox.container.background
}
if beautiful.bg_image then
local bg_image = gears.surface(beautiful.bg_image)
local bg_width, bg_height = gears.surface.get_size(bg_image)
local function bg_image_function(_, cr, width, height)
cr:scale(width / bg_width, height / bg_height)
cr:set_source_surface(bg_image)
cr:paint()
end
startscreen_bg.bgimage = bg_image_function
end
startscreen.bg = beautiful.bg
startscreen.fg = beautiful.fg or "#FFFFFF"
if beautiful.border_radius then
startscreen.shape = helpers.rrect(beautiful.border_radius)
end
----------------------------------------------------------------------------
-- Adding Toggle Controls with Animation to the Widget
startscreen.animator = nil
startscreen.visibility = false
function startscreen:show(width, height, x, y)
self.visibility = true
width = width or get_width()
height = height or get_height()
self.width = width
self.height = height
x = x or get_x(width)
y = y or get_y(height)
if not self.animator then
if beautiful.animation.style == "opacity" then
-- Non-zero to avoid glitches with full-screen windows
self.opacity = 0.01
else
self.opacity = beautiful.opacity
end
if beautiful.animation.style == "slide_tb" then
self.x = x
self.y = -height
elseif beautiful.animation.style == "slide_lr" then
self.x = -width
self.y = y
else
self.x = x
self.y = y
end
end
self.visible = true
if beautiful.animation.style ~= "none" then
if self.animator then
self.animator:stopAnimation()
end
self.animator =
animation(
self,
beautiful.animation.duration,
{
opacity = beautiful.opacity,
x = x,
y = y
},
beautiful.animation.easing
)
self.animator:startAnimation()
end
end
function startscreen:hide(width, height, x, y)
self.visibility = false
if beautiful.animation.style ~= "none" then
width = width or get_width()
height = height or get_height()
x = x or get_x(width)
y = y or get_y(height)
local target = {}
if beautiful.animation.style == "opacity" then
-- Non-zero to avoid glitches with full-screen windows
target.opacity = 0.01
else
target.opacity = beautiful.opacity
end
if beautiful.animation.style == "slide_tb" then
target.x = x
target.y = -height
elseif beautiful.animation.style == "slide_lr" then
target.x = -width
target.y = y
else
target.x = x
target.y = y
end
if self.animator then
self.animator:stopAnimation()
end
self.animator =
animation(
self,
beautiful.animation.duration,
target,
beautiful.animation.easing
)
self.animator:startAnimation()
self.animator:connect_signal(
"anim::animation_finished",
function()
self.visible = false
end
)
else
self.visible = false
end
end
function startscreen:toggle()
local width, height = get_width(), get_height()
local x, y = get_x(width), get_y(height)
if not self.visibility then
self:show(width, height, x, y)
else
self:hide(width, height, x, y)
end
end
----------------------------------------------------------------------------
-- Setting up the Layout of the StartScreen
local dpi = require("beautiful").dpi
local boxed = function(widget, width, height, ignore_center)
return helpers.boxed(
widget,
width,
height,
ignore_center,
beautiful.widgetbox.bg,
beautiful.widgetbox.border_radius,
beautiful.widgetbox.margin
)
end
-- boxed = helpers.create_widget_box
local boxes = {
{
-- Column: 1
boxed(require("widgets.user"), beautiful.column_widths[1], dpi(500)),
boxed(require("widgets.player"), beautiful.column_widths[1], dpi(310)),
layout = wibox.layout.fixed.vertical
},
{
-- Column: 2
boxed(require("widgets.datetime"), beautiful.column_widths[2], dpi(450)),
boxed(require("widgets.notes"), beautiful.column_widths[2], dpi(360), true),
layout = wibox.layout.fixed.vertical
},
{
-- Column: 3
boxed(require("widgets.calendar"), beautiful.column_widths[3], dpi(510)),
require("widgets.controls"),
layout = wibox.layout.fixed.vertical
},
layout = wibox.layout.fixed.horizontal
}
boxes = helpers.centered(boxes)
startscreen:setup {
startscreen_bg,
{
{
{
require("widgets.host"),
nil,
require("widgets.battery"),
expand = "none",
layout = wibox.layout.align.horizontal
},
layout = wibox.layout.fixed.vertical
},
top = dpi(5),
left = dpi(10),
right = dpi(10),
widget = wibox.container.margin
},
{
boxes,
margins = beautiful.border_width or 0,
color = beautiful.border_color,
widget = wibox.container.margin
},
layout = wibox.layout.stack
}
----------------------------------------------------------------------------
return startscreen
end
-- -------------------------------------------------------------------------------------
return create_startscreen
| 28.957792 | 88 | 0.488283 |
e883d7d66a98e1691280816acc46afb18c7b0dd9 | 11,826 | lua | Lua | lua_lib/pattern.lua | Arnaz87/Lua-parser | 12a33e6c251111b1405e1f271fe7b972d5bc6278 | [
"MIT"
] | 6 | 2017-12-09T23:06:42.000Z | 2017-12-31T08:38:37.000Z | lua_lib/pattern.lua | Arnaz87/aulua | 12a33e6c251111b1405e1f271fe7b972d5bc6278 | [
"MIT"
] | null | null | null | lua_lib/pattern.lua | Arnaz87/aulua | 12a33e6c251111b1405e1f271fe7b972d5bc6278 | [
"MIT"
] | null | null | null |
--[[ Depends on the functions:
- ipairs
- string.sub
- string.byte
- string.lower
- table.insert
]]
-- Provides string.find, string.match
-- TODO: Captures, string.gmatch, string.gsub, remove string.charat
function string:charat(i) return self:sub(i, i) end
-- Basic classes
local function digit (code) return code >= 48 and code <= 57 end
local function lower (code) return code >= 97 and code <= 122 end
local function upper (code) return code >= 65 and code <= 90 end
local function letter (code) return lower(code) or upper(code) end
local function space (code) return code == 9 or code == 10 or code == 32 end
local function control (code) return code < 32 or code == 127 end
local function printable (code) return not control(code) and not space(code) end
local function alphanum (code) return letter(code) or digit(code) end
local function punctuation (code) return printable(code) and not alphanum(code) end
local function hex (code) return digit(code) or (code >= 65 and code <= 70) or (code >= 97 and code <= 102) end
local function all () return true end
local function complement (item)
return function (code)
return not item(code)
end
end
local function make_range (_a, _b)
local a, b = _a:byte(), _b:byte()
return function (code)
return code >= a and code <= b
end
end
local function make_charset (str)
local bytes = {str:byte(1, #str)}
return function (code)
for _, c in ipairs(bytes) do
if code == c then return true end
end
return false
end
end
local function try_escape_class (patt, i)
if patt:charat(i) ~= "%" then return end
local item
local char = patt:charat(i+1)
local c = char:lower()
if c == "a" then item=letter
elseif c == "c" then item=control
elseif c == "d" then item=digit
elseif c == "g" then item=printable
elseif c == "l" then item=lower
elseif c == "p" then item=punctuation
elseif c == "s" then item=space
elseif c == "u" then item=upper
elseif c == "w" then item=alphanum
elseif c == "x" then item=hex end
if item then
if c ~= char then
item = complement(item)
end
return item, i+2
else
return make_charset(char), i+2
end
end
local function parse_set (patt, i)
local ch = patt:charat(i)
if ch == "^" then
local set, _i = parse_set(patt, i+1)
return complement(set), _i
end
local charset = ""
local set = {}
while ch and ch ~= "]" do
local class, _i = try_escape_class(patt, i, true)
if class then i = _i
elseif patt:charat(i+1) == "-" then
class = make_range(ch, patt:charat(i+2))
i = i+2
else
charset = charset .. ch
i = i+1
end
if class then table.insert(set, class) end
ch = patt:sub(i, i)
end
if charset ~= "" then
table.insert(set, make_charset(charset))
end
if ch == "]" then
local f = function (code)
for _, class in ipairs(set) do
if class(code) then return true end
end
return false
end
return f, i+1
end
end
local function parse_class (patt, i)
local ch = patt:charat(i)
if ch == "[" then
return parse_set(patt, i+1)
elseif ch == "." then
return all, i+1
else
return try_escape_class(patt, i)
end
end
-- Basic Items
local function string_item (patt, next)
return function (str, i, captures)
local section = str:sub(i, i + #patt - 1)
if section == patt then
return next(str, i+#patt, captures)
end
end
end
local function class_item (class, next)
return function (str, i, captures)
if i > #str then return end
if class(str:byte(i)) then
return next(str, i+1, captures)
end
end
end
local function end_item (str, i) return i-1 end
-- repetitions
local function more_or_zero (class, next)
return function (str, i, captures)
local n = i
while n <= #str and class(str:byte(n)) do
n = n+1
end
while n >= i do
local result = next(str, n, captures)
if result then return result end
n = n-1
end
end
end
local function zero_or_more (class, next)
return function (str, i, captures)
while true do
local result = next(str, i, captures)
if result then return result end
if i <= #str and class(str:byte(i)) then i = i+1
else return end
end
end
end
local function one_or_zero (class, next)
return function (str, i, captures)
if class(str:byte(i)) then
local result = next(str, i+1, captures)
if result then return result end
end
return next(str, i, captures)
end
end
-- captures
local function capture_pos (index, next)
return function (str, i, captures)
captures[index] = i
return next(str, i, captures)
end
end
local function capture_start (index, next)
return function (str, i, captures)
captures[index] = {start=i}
return next(str, i, captures)
end
end
local function capture_end (index, next)
return function (str, i, captures)
captures[index]["end"] = i - 1
return next(str, i, captures)
end
end
local function parse_pattern (patt, i)
local seq = {}
local function push (type, value)
table.insert(seq, {type=type, value=value})
end
local capture_index = 1
local index_stack = {}
local str = ""
while i <= #patt do
if patt:sub(i, i+1) == "()" then
push("()", capture_index)
capture_index = capture_index + 1
i = i+2
elseif patt:charat(i) == "(" then
push("(", capture_index)
table.insert(index_stack, capture_index)
capture_index = capture_index + 1
i = i+1
elseif patt:charat(i) == ")" then
push(")", table.remove(index_stack))
i = i+1
else
local class, _i = parse_class(patt, i)
if class then
if str ~= "" then
push("string", str)
str = ""
end
i = _i
else
class = patt:charat(i)
i = i+1
end
local ch = patt:charat(i)
if ch == "+" or ch == "*" or ch == "-" or ch == "?" then
if type(class) == "string" then
class = make_charset(class)
end
push(ch, class)
i = i+1
elseif type(class) == "string" then
str = str .. class
else push("class", class) end
end
end
if str ~= "" then
push("string", str)
end
local item = end_item
for i = #seq, 1, -1 do
local obj = seq[i]
if obj.type == "string" then
item = string_item(obj.value, item)
elseif obj.type == "class" then
item = class_item(obj.value, item)
elseif obj.type == "*" then
item = more_or_zero(obj.value, item)
elseif obj.type == "+" then
item = more_or_zero(obj.value, item)
item = class_item(obj.value, item)
elseif obj.type == "-" then
item = zero_or_more(obj.value, item)
elseif obj.type == "?" then
item = one_or_zero(obj.value, item)
elseif obj.type == "()" then
item = capture_pos(obj.value, item)
elseif obj.type == "(" then
item = capture_start(obj.value, item)
elseif obj.type == ")" then
item = capture_end(obj.value, item)
end
end
return item
end
local function find (str, patt, init)
local captures = {}
local pattern = parse_pattern(patt, 1)
return pattern(str, init or 1)
end
--[[
-- classes
assert(find("a", "."))
assert(find("a", "%l"))
assert(not find("a", "%d"))
assert(find("a", "[abc]"))
assert(find("b", "[abc]"))
assert(not find("d", "[abc]"))
assert(not find("a", "[^abc]"))
assert(find("e", "[b-e]"))
assert(not find("a", "[b-e]"))
assert(find("a", "[%d%l]"))
assert(find("v", "[%duvz]"))
assert(not find("a", "[%dxyz]"))
-- strings
assert(not find("a", "abc"))
assert(find("abcd", "abc"))
assert(find("a3cb", "a%wc"))
assert(not find("ab3c", "a%wc"))
-- repetitions
assert(find("abc3", "%l") == 1)
assert(find("abc3", "%l*") == 3)
assert(find("3", "%l*") == 0)
assert(find("abc3", "%l+") == 3)
assert(find("a1b2", "%w+%d") == 4)
assert(find("a1b2", "%w-%d") == 2)
assert(not find("3", "%l+"))
assert(find("a0", ".?%d") == 2)
assert(find("0", ".?%d") == 1)
local function capt (str, patt, expected)
local captures = {}
local pattern = parse_pattern(patt, 1)
pattern(str, 1, captures)
if #captures ~= #expected then goto err end
for i = 1, #captures do
local c = captures[i]
if type(c) == "table" then
c = str:sub(c.start, c["end"])
end
if c ~= expected[i] then goto err end
end
do return end
::err::
error("failed " .. str .. " with pattern " .. patt)
end
capt("abc", "%w", {})
capt("abc", "()%w()()", {1, 2, 2})
capt("abc", "(%w)", {"a"})
capt("abcd", ".(%w).(%w)", {"b", "d"})
capt("abc", "(%w(%w))", {"ab", "b"})
--]]
local function finish_captures (captures, str)
for i = 1, #captures do
local c = captures[i]
if type(c) == "table" then
captures[i] = str:sub(c.start, c["end"])
end
end
return table.unpack(captures)
end
function string:find (patt, init, plain)
if not patt then
error("bad argument #1 to 'string.find' (value expected)")
elseif type(patt) == "number" then
patt = tostring(patt)
elseif type(patt) ~= "string" then
error("bad argument #1 to 'string.find' (string expected, got " .. type(patt) .. ")")
end
local orig_init = init
if init == nil then init = 1 end
init = tonumber(init)
if not init then
error("bad argument #2 to 'string.find' (number expected, got " .. type(orig_init) .. ")")
end
if init < 0 then init = #self + 1 + init end
if init < 1 then init = 1 end
if plain then
for i = init, #self + 1 - #patt do
local j = i + #patt - 1
local sub = self:sub(i, j)
if sub == patt then return i, j end
end
else
local max_start = #self
if patt:charat(1) == "^" then
max_start = 1
patt = patt:sub(2, -1)
end
local min_end = 0
if patt:charat(-1) == "$" and patt:charat(-2) ~= "%" then
min_end = #self
patt = patt:sub(1, -2)
end
local pattern = parse_pattern(patt, 1)
local captures = {}
for i = init, max_start do
local endpos = pattern(self, i, captures)
if endpos and endpos >= min_end then
return i, endpos, finish_captures(captures, self)
end
end
end
end
function string:match (patt, init, plain)
local r = {self:find(patt, init, plain)}
if #r > 2 then
return table.unpack(r, 3)
elseif #r > 0 then
return self:sub(r[1], r[2])
end
end
function string.gsub (s, patt, repl, max_count)
local function sep (a, b, ...) return a, b, {...} end
local f
if type(repl) == "function" then
function f (_, ...) return repl(...) end
elseif type(repl) == "table" then
function f (_, k) return repl[k] end
elseif type(repl) == "string" then
function f (...)
local arg = {...}
local t = {["%"] = "%%"}
for i = 1, #arg do
t[tostring(i-1)] = arg[i]
end
return repl:gsub("%%([%d%%])", t)
end
else error("bad argument #3 to 'string.gsub' (string/function/table expected)") end
local i, r, count = 1, "", 0
while i < #s and (not max_count or count < max_count) do
local j, j2, captures = sep(s:find(patt, i))
if not j then break end
r = r .. s:sub(i, j-1) .. f(s:sub(j, j2), table.unpack(captures))
i = j2+1
count = count+1
end
r = r .. s:sub(i)
return r, count
end
--[[
assert(("abcd"):find("%w") == 1)
assert(("abcd"):find("^%w") == 1)
assert(("abcd"):find("%w$") == 4)
assert(("abcd"):find("^%w$") == nil)
assert(("ab2c"):find("%w%d") == 2)
assert(("ab2c"):find("^%w%d") == nil)
assert(("a$"):find("%w$") == nil)
assert(("a$b"):find("%w%$") == 1)
do
local a, b = ("+ -"):find("^[ \b\n\r\t\v]*")
assert(a == 1) assert(b == 0)
end
print(("abc"):find("%w%w"))
print(("abc"):find("%w(%w)"))
print(("abc"):find("(()%w(%w))"))
print(("abc"):match("%w%w"))
print(("abc"):match("(()%w(%w))"))
]] | 24.792453 | 111 | 0.592085 |
cb5b93e7902e06c369ad0002c254f3ba2fbeebf4 | 136 | c | C | restart.c | ok100/dwm | 19c14f4fafd76f9b834301a5a6cb726c89b1629d | [
"MIT"
] | 3 | 2015-05-01T22:25:33.000Z | 2020-09-27T10:47:12.000Z | restart.c | ok100/dwm | 19c14f4fafd76f9b834301a5a6cb726c89b1629d | [
"MIT"
] | null | null | null | restart.c | ok100/dwm | 19c14f4fafd76f9b834301a5a6cb726c89b1629d | [
"MIT"
] | 1 | 2020-02-01T12:15:52.000Z | 2020-02-01T12:15:52.000Z | #include <unistd.h>
void restart(const Arg *arg) {
char *const argv[] = {"/usr/local/bin/dwm", NULL};
execv(argv[0], argv);
}
| 17 | 54 | 0.595588 |
4af9d091d8206ffa79c6081123285246f475f81c | 3,603 | swift | Swift | EssentialFeed/EssentialFeediOSTests/ImageCommentsSnapshotTests.swift | Cronay/ios-lead-essentials-image-comments-challenge | aa6de55854f6b30a0b2c7e4cde423125bf06c5c7 | [
"MIT"
] | null | null | null | EssentialFeed/EssentialFeediOSTests/ImageCommentsSnapshotTests.swift | Cronay/ios-lead-essentials-image-comments-challenge | aa6de55854f6b30a0b2c7e4cde423125bf06c5c7 | [
"MIT"
] | null | null | null | EssentialFeed/EssentialFeediOSTests/ImageCommentsSnapshotTests.swift | Cronay/ios-lead-essentials-image-comments-challenge | aa6de55854f6b30a0b2c7e4cde423125bf06c5c7 | [
"MIT"
] | null | null | null | //
// ImageCommentsSnapshotTests.swift
// EssentialFeediOSTests
//
// Created by Cronay on 23.12.20.
// Copyright © 2020 Essential Developer. All rights reserved.
//
import XCTest
@testable import EssentialFeed
import EssentialFeediOS
class ImageCommentsSnapshotTests: XCTestCase {
func test_emptyComments() {
let sut = makeSUT()
sut.display(noComments())
assert(snapshot: sut.snapshot(for: .iPhone8(style: .light)), named: "EMPTY_IMAGE_COMMENTS_light")
assert(snapshot: sut.snapshot(for: .iPhone8(style: .dark)), named: "EMPTY_IMAGE_COMMENTS_dark")
}
func test_commentsWithErrorMessage() {
let sut = makeSUT()
sut.display(errorMessage("This is\na multi-line\nerror message"))
assert(snapshot: sut.snapshot(for: .iPhone8(style: .light)), named: "COMMENTS_WITH_ERROR_MESSAGE_light")
assert(snapshot: sut.snapshot(for: .iPhone8(style: .dark)), named: "COMMENTS_WITH_ERROR_MESSAGE_dark")
assert(snapshot: sut.snapshot(for: .iPhone8(style: .light, contentSize: .extraLarge)), named: "COMMENTS_WITH_ERROR_MESSAGE_extra_large_content_size")
}
func test_commentsWithContent() {
let sut = makeSUT()
sut.display(comments())
assert(snapshot: sut.snapshot(for: .iPhone8(style: .light)), named: "LOADED_COMMENTS_light")
assert(snapshot: sut.snapshot(for: .iPhone8(style: .dark)), named: "LOADED_COMMENTS_dark")
assert(snapshot: sut.snapshot(for: .iPhone8(style: .light, contentSize: .extraLarge)), named: "LOADED_COMMENTS_extra_large_content_size")
}
// MARK: - Helpers
private func makeSUT() -> ImageCommentsViewController {
let bundle = Bundle(for: ImageCommentsViewController.self)
let storyboard = UIStoryboard(name: "ImageComments", bundle: bundle)
let controller = storyboard.instantiateInitialViewController() as! ImageCommentsViewController
controller.loadViewIfNeeded()
controller.tableView.showsVerticalScrollIndicator = false
controller.tableView.showsHorizontalScrollIndicator = false
return controller
}
private func noComments() -> ImageCommentsViewModel {
return ImageCommentsViewModel(presentables: [])
}
private func errorMessage(_ message: String) -> ImageCommentsErrorViewModel {
return ImageCommentsErrorViewModel(message: message)
}
private func comments() -> ImageCommentsViewModel {
let comment0 = PresentableImageComment(username: "Some User", message: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr.", date: "1 year ago")
let comment1 = PresentableImageComment(username: "A very long long long username", message: "Lorem ipsum!\n.\n.\n.\n.", date: "6 month ago")
let comment2 = PresentableImageComment(username: "Another User", message: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.", date: "1 day ago")
let comment3 = PresentableImageComment(username: "Last User", message: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.", date: "Just now")
return ImageCommentsViewModel(presentables: [comment0, comment1, comment2, comment3])
}
}
| 50.041667 | 689 | 0.772967 |
0a0dfa28f59b81e2ff456dc6360f10f15b2ee539 | 19,500 | h | C | src/compiler/parser.h | ternary-club/terry | 4dbd89490afb61a97c21e7fe73303240fa583576 | [
"MIT"
] | null | null | null | src/compiler/parser.h | ternary-club/terry | 4dbd89490afb61a97c21e7fe73303240fa583576 | [
"MIT"
] | null | null | null | src/compiler/parser.h | ternary-club/terry | 4dbd89490afb61a97c21e7fe73303240fa583576 | [
"MIT"
] | null | null | null | #ifndef STD_BOOL_H
#define STD_BOOL_H
#include "../std/bool.h"
#endif
#ifndef COMPILER_TOKEN_H
#define COMPILER_TOKEN_H
#include "token.h"
#endif
#ifndef COMPILER_ERROR_H
#define COMPILER_ERROR_H
#include "error.h"
#endif
#define MAIN_BUFFER_SIZE 64
#define TOKEN_BUFFER_SIZE 32
// File
intptr file;
// Main buffer
char mBuffer[MAIN_BUFFER_SIZE * 2];
// Interval pointers
char *start;
char *end;
// Reset cursor and buffer pointers
void begin() {
start = end;
first = last;
}
// Rewind cursor and buffer pointers
void rewind() {
end = start;
last = first;
}
// New line
void next_line() {
last.line++;
last.column = 0;
}
// New column
void next_column() { last.column++; }
// Check if a character is end of text
bool is_etx() { return *end == '\x03' || *end == '\0'; }
// Check if a character is the beginning of a commentary
bool is_comment() { return *end == '#'; }
// Check if a character is an underscore
bool is_underscore() { return *end == '_'; }
// Check if a character is a lowercase letter
bool is_lowercase() { return *end >= 'a' && *end <= 'z'; }
// Check if a character is an upper letter
bool is_uppercase() { return *end >= 'A' && *end <= 'Z'; }
// Check if a character is a letter
bool is_letter() { return is_lowercase() || is_uppercase(); }
// Check if a character is a number
bool is_number() { return *end >= '0' && *end <= '9'; }
// Check if a character is a heptavintimal number
bool is_heptavintimal() { return is_number() || *end >= 'A' && *end <= 'Q'; }
// Check if a character is a whitespace or \t
bool is_empty() { return *end == ' ' || *end == '\t'; }
// Check if a character is CR
bool is_carriage() { return *end == '\r'; }
// Check if a character is LF
bool is_newline() { return *end == '\n'; }
// Check if a character is CR/LF
bool is_line_end() { return is_newline() || is_carriage(); }
// Check if a character is a balanced ternary number
bool is_balanced() { return *end == 'N' || *end == '0' || *end == '1'; }
// Check if a character is a ternary number
bool is_ternary() { return *end >= '0' && *end <= '2'; }
// Check if a character is a quaternary operator
bool is_quaternary() { return *end == '?'; }
// Check if a character is zero
bool is_zero() { return *end == '0'; }
// Check if a character is an assertion
bool is_assertion() { return *end == '='; }
// Check if a character is part of operator
bool is_operator() {
return *end == '+' || *end == '-' || *end == '*' || *end == '/' ||
*end == '%' || *end == '~' || *end == '&' || *end == '|' ||
*end == '^' || *end == '\\';
}
// Check if a character is part of an outcome (excludes =)
bool is_outcome() {
return *end == '>' || *end == '<' || *end == ':' || *end == '!';
}
// Check if a character is a separator
bool is_separator() { return is_line_end() || is_empty() || is_etx(); }
// Compare string with interval string
bool strcmp_i(const char *a, uint8_t offset) {
char *b = start + offset;
while (*a || b < end)
if (*a++ != *b++) return false;
return true;
}
// Paste interval string in buffer
void strcpy_i(char *a) {
char *b = start;
while (b < end && b < start + TOKEN_BUFFER_SIZE) *a++ = *b++;
*a = '\0';
}
// Get interval string as number
uint16_t atoi_i() {
uint16_t n = 0;
for (char *b = end - 1; b >= start; b--)
n += power(10, end - b - 1) * (*b - '0');
return n;
}
// Next char
void next() {
// If its a newline character, then jump to the next line
if (is_newline())
next_line();
else if (!is_carriage())
next_column();
// Jump to next character
end++;
// If it has reached the end of buffer, load next chars
if (end >= mBuffer + 2 * MAIN_BUFFER_SIZE - 1) {
for (uint64_t i = 0; i < MAIN_BUFFER_SIZE; i++)
mBuffer[i] = mBuffer[i + MAIN_BUFFER_SIZE];
int bytesRead =
read(file, mBuffer + MAIN_BUFFER_SIZE, MAIN_BUFFER_SIZE);
if (bytesRead < MAIN_BUFFER_SIZE)
mBuffer[bytesRead + MAIN_BUFFER_SIZE] = 0;
start -= MAIN_BUFFER_SIZE;
end -= MAIN_BUFFER_SIZE;
}
}
// Detect token
TOKEN parse_token() {
// Current token
TOKEN t = NEW_TOKEN;
// Save cursor's checkpoint
begin();
// Try to parse a comment
if (is_comment()) do
next();
while (!is_line_end() && !is_etx());
// Try to parse a newline
if (is_line_end()) {
do next();
while (is_line_end());
t.tag = T_NEWLINE;
return t;
}
// Try to parse the end of text
if (is_etx()) {
t.tag = T_ENDPOINT;
return t;
}
// Try to parse quaternary operator
if (is_quaternary()) {
next();
t.tag = T_QUATERNARY;
return t;
}
// Try to parse base literals
if (is_zero()) {
next();
switch (*end) {
case 't':
next();
// If it has got 0 algarism, then throw error
if (is_separator())
report_error(E_EMPTY_BASE_LITERAL);
else
while (is_ternary()) next();
// If it finds a strange character, it's likely
// a wrong ternary number, so finish it and throw error
if (!is_separator()) {
do next();
while (!is_separator());
report_error(E_INVALID_BASE_LITERAL);
}
t.tag = T_INT3;
return t;
case 'b':
next();
// If it has got 0 algarism, then throw error
if (is_separator())
report_error(E_EMPTY_BASE_LITERAL);
else
while (is_balanced()) next();
// If it finds a strange character, it's likely
// a wrong trinary number, so finish it and throw error
if (!is_separator()) {
do next();
while (!is_separator());
report_error(E_INVALID_BASE_LITERAL);
}
t.tag = T_INTB3;
return t;
case 'h':
next();
// If it has got 0 algarism, then throw error
if (is_separator())
report_error(E_EMPTY_BASE_LITERAL);
else
while (is_heptavintimal()) next();
// If it finds a strange character, it's likely
// a wrong heptavintimal number, so finish it and throw error
if (!is_separator()) {
do next();
while (!is_separator());
report_error(E_INVALID_BASE_LITERAL);
}
t.tag = T_INT27;
return t;
default:
// If it doesn't fit anywhere else and if it's a character,
// then it's an unknown base literal, so finish the string and
// throw error
if (is_lowercase()) {
report_error(E_UNKNOWN_BASE_LITERAL);
next();
// If it has got 0 algarism, then throw error
if (is_separator())
report_error(E_EMPTY_BASE_LITERAL);
else
while (!is_separator()) next();
t.tag = T_INT10;
return t;
}
// If it isn't a letter, then it's not a base literal, so
// get back
rewind();
break;
}
}
// Try to parse register
if (is_number()) {
bool isExistingRegister = true;
int8_t registerNum = *end - '0';
// If it's out of the registers intervals, then it's a non-existing
// register
if (registerNum < 1 || registerNum > 3 && registerNum != 9)
isExistingRegister = false;
next();
if (is_lowercase()) {
char registerLetter = *end - 'a';
// If it's out of the registers intervals, then it's a non-existing
// register
if (isExistingRegister &&
(registerLetter < 0 || registerLetter > 8) ||
(registerLetter > 2) && registerNum == 9)
isExistingRegister = false;
next();
// If it's exactly a number and a letter, then it's
// likely a register
if (is_separator()) {
if (!isExistingRegister) report_error(E_UNKNOWN_REGISTER);
t.tag = T_REGISTER;
return t;
} else
rewind();
} else
rewind();
}
// Try to parse base 10 number
if (is_number()) {
do next();
while (is_number());
// If it finds a strange character, it's likely
// a wrong decimal number, so finish it and throw error
if (!is_separator()) {
do next();
while (!is_separator());
report_error(E_INVALID_NUMBER);
}
t.tag = T_INT10;
puts("buffer: ");
write(stdout, start, end - start);
puts(" ");
puts("atoi: ");
puts(itoa(atoi_i()));
puts("\n");
*((uint16_t *)t.content) = atoi_i();
return t;
}
// Try to parse an outcome
if (is_assertion() || is_outcome()) {
// If it has outcome-exclusive characters or if it's
// just assertions
bool hasOutcomeChar = is_outcome();
// Read outcome characters
do {
next();
// Check if it already found an outcome character
if (!hasOutcomeChar) hasOutcomeChar = is_outcome();
} while (is_assertion() || is_outcome());
// Filter comparisons (not exactly necessary here, but
// this checking would be needed filter errors and it's
// more idiomatic and optimized this way)
if (!hasOutcomeChar) {
if (strcmp_i("==", 0)) {
*((uint8_t *)t.content) = O_EQUAL;
t.tag = T_OUTCOME;
return t;
}
// If it has no outcome characters, it's likely a
// logical operator or something else, so rewind
else
rewind();
} else {
t.tag = T_OUTCOME;
if (strcmp_i(">", 0))
*((uint8_t *)t.content) = O_GREATER;
else if (strcmp_i(">=", 0))
*((uint8_t *)t.content) = O_GREATER | O_EQUAL;
else if (strcmp_i("<", 0))
*((uint8_t *)t.content) = O_LESS;
else if (strcmp_i("<=", 0))
*((uint8_t *)t.content) = O_LESS | O_EQUAL;
else if (strcmp_i(":", 0))
*((uint8_t *)t.content) = O_ELSE;
else if (strcmp_i("!=", 0))
*((uint8_t *)t.content) = O_GREATER | O_LESS;
// If it has a outcome characters but it isn't any
// known outcome, it's likely a mistyped outcome,
// so throw error
else
report_error(E_INVALID_OUTCOME);
return t;
}
}
// Try to parse an assertion
bool isLogical = false;
if (is_assertion()) {
next();
if (!is_operator()) {
t.tag = T_ASSERTION;
// Represents no operator
*((uint8_t *)t.content) = 0;
return t;
} else
isLogical = true;
}
// Try to parse an operator
if (is_operator()) {
// If the operator is diadic and tritwise (both necessary for it to be
// logical)
bool isDiadicTritwise = false;
// Read operator characters
do next();
while (is_operator());
// String comparisons below use isLogical as offset because if it's true
// (1), the initial assertion is skipped (even if the operator doesn't
// support logical assertions like monadic operators, it still should
// not be treated as an unknown operator).
// Multidic operator
if (strcmp_i("-", isLogical)) {
*((uint8_t *)t.content) = M_SUBTRACTION;
t.tag = T_MULTIDIC;
}
// Monadic operators
else if (strcmp_i("~", isLogical)) {
*((uint8_t *)t.content) = M_NEGATION;
t.tag = T_MONADIC;
} else if (strcmp_i("+/", isLogical)) {
*((uint8_t *)t.content) = M_INCREMENT;
t.tag = T_MONADIC;
} else if (strcmp_i("-/", isLogical)) {
*((uint8_t *)t.content) = M_DECREMENT;
t.tag = T_MONADIC;
} else if (strcmp_i("%|", isLogical)) {
*((uint8_t *)t.content) = M_ISTRUE;
t.tag = T_MONADIC;
} else if (strcmp_i("%/", isLogical)) {
*((uint8_t *)t.content) = M_ISUNKNOWN;
t.tag = T_MONADIC;
} else if (strcmp_i("%-", isLogical)) {
*((uint8_t *)t.content) = M_ISFALSE;
t.tag = T_MONADIC;
} else if (strcmp_i("/\\", isLogical)) {
*((uint8_t *)t.content) = M_CLAMPUP;
t.tag = T_MONADIC;
} else if (strcmp_i("\\/", isLogical)) {
*((uint8_t *)t.content) = M_CLAMPDOWN;
t.tag = T_MONADIC;
}
// Diadic operators
else if (strcmp_i("+", isLogical)) {
*((uint8_t *)t.content) = D_ADDITION;
t.tag = T_DIADIC;
} else if (strcmp_i("-", isLogical)) {
*((uint8_t *)t.content) = D_SUBTRACTION;
t.tag = T_DIADIC;
} else if (strcmp_i("*", isLogical)) {
*((uint8_t *)t.content) = D_MULTIPLICATION;
t.tag = T_DIADIC;
} else if (strcmp_i("/", isLogical)) {
*((uint8_t *)t.content) = D_DIVISION;
t.tag = T_DIADIC;
} else if (strcmp_i("%", isLogical)) {
*((uint8_t *)t.content) = D_MODULO;
t.tag = T_DIADIC;
} else if (strcmp_i("|", isLogical)) {
*((uint8_t *)t.content) = D_OR;
t.tag = T_DIADIC;
isDiadicTritwise = true;
} else if (strcmp_i("&", isLogical)) {
*((uint8_t *)t.content) = D_AND;
t.tag = T_DIADIC;
isDiadicTritwise = true;
} else if (strcmp_i("^", isLogical)) {
*((uint8_t *)t.content) = D_XOR;
t.tag = T_DIADIC;
isDiadicTritwise = true;
} else if (strcmp_i("**", isLogical)) {
*((uint8_t *)t.content) = D_ANY;
t.tag = T_DIADIC;
isDiadicTritwise = true;
} else if (strcmp_i("/%", isLogical)) {
*((uint8_t *)t.content) = D_CONSENSUS;
t.tag = T_DIADIC;
isDiadicTritwise = true;
} else if (strcmp_i("/+", isLogical)) {
*((uint8_t *)t.content) = D_SUM;
t.tag = T_DIADIC;
isDiadicTritwise = true;
} else if (strcmp_i("~|", isLogical)) {
*((uint8_t *)t.content) = D_NOR;
t.tag = T_DIADIC;
isDiadicTritwise = true;
} else if (strcmp_i("~&", isLogical)) {
*((uint8_t *)t.content) = D_NAND;
t.tag = T_DIADIC;
isDiadicTritwise = true;
}
// Unknown
else {
// Throw error
report_error(E_UNKNOWN_OPERATOR);
// Invalid operators are treated as multidic and diadic tritwise
// so they don't cause additional inter token problems
t.tag = T_MULTIDIC;
isDiadicTritwise = true;
}
// If the final token is an assertion, it means it's an assertion
// operator
if (is_assertion()) {
// Throw error
if (t.tag != T_DIADIC || isLogical)
report_error(E_LOGICAL_MONADIC_ASSERTION_OPERATOR);
t.tag = T_ASSERTION;
// Advance
next();
}
// If it's a logical operator, replace the tag
else {
if (isLogical) {
// If it's not a diadic tritwise operator, throw error
if (!isDiadicTritwise)
report_error(E_LOGICAL_NON_DIADIC_TRITWISE);
t.tag = T_LOGICAL;
}
// Check if operators are separated
if (!is_separator()) report_error(E_UNSPACED_OPERATOR);
}
return t;
}
// Try to parse label
if (is_uppercase()) {
do next();
while (is_lowercase() || is_number() || is_uppercase());
// If it finds a strange character, it's likely
// a wrong label name, so finish it and throw error
if (!is_separator()) {
do next();
while (!is_separator());
report_error(E_INVALID_LABEL);
}
// Copy string
strcpy_i((char *)t.content);
t.tag = T_LABEL;
return t;
}
// Try to parse variable size
if (is_lowercase()) {
bool isVarSize = true;
do next();
while (is_lowercase());
// If it finds a strange character, it's likely not
// a wrong variable size, so mark it as false
if (!is_separator()) isVarSize = false;
// Try to compare variable sizes
else if (strcmp_i("const", 0))
*((uint8_t *)t.content) = VS_CONST;
else if (strcmp_i("tryte", 0))
*((uint8_t *)t.content) = VS_TRYTE;
else if (strcmp_i("word", 0))
*((uint8_t *)t.content) = VS_WORD;
else if (strcmp_i("triple", 0))
*((uint8_t *)t.content) = VS_TRIPLE;
else
isVarSize = false;
// Rewind if is not a known variable size or return if it is
if (isVarSize) {
t.tag = T_VARSIZE;
return t;
} else
rewind();
}
// Try to parse command
if (is_lowercase()) {
bool isCommand = true;
do next();
while (is_lowercase());
// If it finds a strange character, it's likely not
// a command, so mark it as false
if (!is_separator()) isCommand = false;
// Try to compare commands
else if (strcmp_i("call", 0))
*((uint8_t *)t.content) = C_CALL;
else if (strcmp_i("goto", 0))
*((uint8_t *)t.content) = C_GOTO;
else
isCommand = false;
// Rewind if is not a known variable size or return if it is
if (isCommand) {
t.tag = T_COMMAND;
return t;
} else
rewind();
}
// Try to parse variable name
if (is_lowercase() || is_underscore()) {
do next();
while (is_lowercase() || is_underscore() || is_number());
// If it doesn't fit anywhere else and if it's a character, it's likely
// a bad variable name, so finish the string, throw error and return
if (!is_separator()) {
do next();
while (!is_separator());
report_error(E_INVALID_NAME);
}
t.tag = T_NAME;
strcpy_i((char *)t.content);
return t;
}
// If it's nothing else, then return T_NOTOKEN
do next();
while (!is_separator() && !is_assertion() && !is_number() && !is_letter() &&
!is_comment() && !is_operator());
t.tag = T_NOTOKEN;
return t;
} | 31.810767 | 80 | 0.509333 |
b2d8b14f8188a2112f4bdf4db0fef92891d9717a | 6,062 | py | Python | Scaffold_Code/test scripts/test10_vm.py | tzortzispanagiotis/nbc-blockchain-python | 4e59bfd3f8aa6fb72ce89f430909a1d5c90629e2 | [
"MIT"
] | null | null | null | Scaffold_Code/test scripts/test10_vm.py | tzortzispanagiotis/nbc-blockchain-python | 4e59bfd3f8aa6fb72ce89f430909a1d5c90629e2 | [
"MIT"
] | null | null | null | Scaffold_Code/test scripts/test10_vm.py | tzortzispanagiotis/nbc-blockchain-python | 4e59bfd3f8aa6fb72ce89f430909a1d5c90629e2 | [
"MIT"
] | 1 | 2021-03-20T20:18:40.000Z | 2021-03-20T20:18:40.000Z | import requests, json, time
from multiprocessing.dummy import Pool
pool = Pool(100)
transactions0 = []
transactions1 = []
transactions2 = []
transactions3 = []
transactions4 = []
transactions5 = []
transactions6 = []
transactions7 = []
transactions8 = []
transactions9 = []
nodeid = {
'id0': 0,
'id1': 1,
'id2': 2,
'id3': 3,
'id4': 4,
'id5': 5,
'id6': 6,
'id7': 7,
'id8': 8,
'id9': 9,
}
node = {
'0': 'http://192.168.0.1:5000',
'1': 'http://192.168.0.2:5001',
'2': 'http://192.168.0.3:5002',
'3': 'http://192.168.0.4:5003',
'4': 'http://192.168.0.5:5004',
'5': 'http://192.168.0.1:5005',
'6': 'http://192.168.0.2:5006',
'7': 'http://192.168.0.3:5007',
'8': 'http://192.168.0.4:5008',
'9': 'http://192.168.0.5:5009'
}
def trans(transactions, src_id):
for t in transactions:
temp = {
"id": nodeid[t[0]],
"amount": int(t[1])
}
body = json.dumps(temp)
r = requests.post(node[src_id]+'/createtransaction', data=body)
if __name__ == '__main__':
with open('../assignment_docs/transactions/10nodes/transactions0.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions0.append(line.split(' '))
# print(transactions0)
with open('../assignment_docs/transactions/10nodes/transactions1.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions1.append(line.split(' '))
# print(transactions1)
with open('../assignment_docs/transactions/10nodes/transactions2.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions2.append(line.split(' '))
# print(transactions2)
with open('../assignment_docs/transactions/10nodes/transactions3.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions3.append(line.split(' '))
# print(transactions3)
with open('../assignment_docs/transactions/10nodes/transactions4.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions4.append(line.split(' '))
# print(transactions4)
with open('../assignment_docs/transactions/10nodes/transactions5.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions5.append(line.split(' '))
with open('../assignment_docs/transactions/10nodes/transactions6.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions6.append(line.split(' '))
with open('../assignment_docs/transactions/10nodes/transactions7.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions7.append(line.split(' '))
with open('../assignment_docs/transactions/10nodes/transactions8.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions8.append(line.split(' '))
with open('../assignment_docs/transactions/10nodes/transactions9.txt') as f:
lines = [line.rstrip('\n') for line in f]
for line in lines:
transactions9.append(line.split(' '))
futures = []
r = requests.get(node['1']+'/selfregister')
r = requests.get(node['2']+'/selfregister')
r = requests.get(node['3']+'/selfregister')
r = requests.get(node['4']+'/selfregister')
r = requests.get(node['5']+'/selfregister')
r = requests.get(node['6']+'/selfregister')
r = requests.get(node['7']+'/selfregister')
r = requests.get(node['8']+'/selfregister')
r = requests.get(node['9']+'/selfregister')
r = requests.get(node['0']+'/timerstart')
r = requests.get(node['1']+'/timerstart')
r = requests.get(node['2']+'/timerstart')
r = requests.get(node['3']+'/timerstart')
r = requests.get(node['4']+'/timerstart')
r = requests.get(node['5']+'/timerstart')
r = requests.get(node['6']+'/timerstart')
r = requests.get(node['7']+'/timerstart')
r = requests.get(node['8']+'/timerstart')
r = requests.get(node['9']+'/timerstart')
target_url = node['0']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['1']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['2']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['3']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['4']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['5']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['6']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['7']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['8']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
target_url = node['9']+'/startwork'
futures.append(pool.apply_async(requests.get, [target_url]))
time.sleep(5)
futures = []
futures.append(pool.apply_async(trans, [transactions0,'0']))
futures.append(pool.apply_async(trans, [transactions1,'1']))
futures.append(pool.apply_async(trans, [transactions2,'2']))
futures.append(pool.apply_async(trans, [transactions3,'3']))
futures.append(pool.apply_async(trans, [transactions4,'4']))
futures.append(pool.apply_async(trans, [transactions5,'5']))
futures.append(pool.apply_async(trans, [transactions6,'6']))
futures.append(pool.apply_async(trans, [transactions7,'7']))
futures.append(pool.apply_async(trans, [transactions8,'8']))
futures.append(pool.apply_async(trans, [transactions9,'9']))
for future in futures:
future.get() | 35.040462 | 80 | 0.615473 |
8b3df990ba69e8c804b91c271e3ee35288b4de0d | 319 | asm | Assembly | oeis/021/A021856.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/021/A021856.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/021/A021856.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A021856: Decimal expansion of 1/852.
; Submitted by Jon Maiga
; 0,0,1,1,7,3,7,0,8,9,2,0,1,8,7,7,9,3,4,2,7,2,3,0,0,4,6,9,4,8,3,5,6,8,0,7,5,1,1,7,3,7,0,8,9,2,0,1,8,7,7,9,3,4,2,7,2,3,0,0,4,6,9,4,8,3,5,6,8,0,7,5,1,1,7,3,7,0,8,9,2,0,1,8,7,7,9,3,4,2,7,2,3,0,0,4,6,9,4
seq $0,199685 ; a(n) = 5*10^n+1.
div $0,426
mod $0,10
| 39.875 | 199 | 0.554859 |
90ab517acc42fb5e2ef68f7e72c5f125825ac588 | 2,515 | py | Python | setup.py | chrissimpkins/pyapp | 0392f27d83d7c5d53e3217d15603659c9a69b590 | [
"Apache-2.0"
] | 4 | 2016-08-18T07:25:52.000Z | 2019-01-20T07:01:57.000Z | setup.py | chrissimpkins/pyapp | 0392f27d83d7c5d53e3217d15603659c9a69b590 | [
"Apache-2.0"
] | null | null | null | setup.py | chrissimpkins/pyapp | 0392f27d83d7c5d53e3217d15603659c9a69b590 | [
"Apache-2.0"
] | 1 | 2016-12-20T23:27:55.000Z | 2016-12-20T23:27:55.000Z | import io
import os
import sys
from setuptools import find_packages, setup
# Package meta-data.
NAME = "{{ PROJECT }}"
DESCRIPTION = "{{ DESCRIPTION }}"
LICENSE = "{{ LICENSE }}"
URL = "{{ URL }}"
EMAIL = "{{ EMAIL }}"
AUTHOR = "{{ AUTHOR }}"
REQUIRES_PYTHON = ">={{ PYTHON }}"
INSTALL_REQUIRES = [""]
# Optional packages
EXTRAS_REQUIRES = {
# for developer installs
"dev": ["coverage", "pytest", "tox", "flake8", "mypy"],
# for maintainer installs
"maintain": ["wheel", "setuptools", "twine"],
}
this_file_path = os.path.abspath(os.path.dirname(__file__))
# Version
main_namespace = {}
version_fp = os.path.join(this_file_path, "lib", "{{ PROJECT }}", "__init__.py")
try:
with io.open(version_fp) as v:
exec(v.read(), main_namespace)
except IOError as version_e:
sys.stderr.write(
"[ERROR] setup.py: Failed to read data for the version definition: {}".format(
str(version_e)
)
)
raise version_e
# Use repository Markdown README.md for PyPI long description
try:
with io.open("README.md", encoding="utf-8") as f:
readme = f.read()
except IOError as readme_e:
sys.stderr.write(
"[ERROR] setup.py: Failed to read README.md for the long description: {}".format(
str(readme_e)
)
)
raise readme_e
setup(
name=NAME,
version=main_namespace["__version__"],
description=DESCRIPTION,
author=AUTHOR,
author_email=EMAIL,
url=URL,
license=LICENSE,
platforms=["Any"],
long_description=readme,
long_description_content_type="text/markdown",
package_dir={"": "lib"},
packages=find_packages("lib"),
include_package_data=True,
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRES,
python_requires=REQUIRES_PYTHON,
entry_points={"console_scripts": ["{{ PROJECT }} = {{ PROJECT }}.__main__:main"]},
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
)
| 28.908046 | 89 | 0.629821 |
a95eba34b21b49df7133b94c1ca9e9d796679d63 | 1,054 | sql | SQL | src/main/resources/db/migration/V1_91__courts.sql | ministryofjustice/offender-assessments-api | f9a293f90f2240f984cebcf607b117e01d1cb0d0 | [
"MIT"
] | 2 | 2019-11-27T14:11:14.000Z | 2020-03-10T10:46:21.000Z | src/main/resources/db/migration/V1_91__courts.sql | noms-digital-studio/offender-assessments-api | f9a293f90f2240f984cebcf607b117e01d1cb0d0 | [
"MIT"
] | 1 | 2020-03-25T10:04:25.000Z | 2020-03-25T10:04:25.000Z | src/main/resources/db/migration/V1_91__courts.sql | noms-digital-studio/offender-assessments-api | f9a293f90f2240f984cebcf607b117e01d1cb0d0 | [
"MIT"
] | 1 | 2021-04-11T06:33:12.000Z | 2021-04-11T06:33:12.000Z | INSERT INTO COURT (COURT_PK, COURT_CODE, COURT_NAME, COURT_TYPE_ELM, COURT_TYPE_CAT, LOCAL_JUSTICE_AREA_ELM, LOCAL_JUSTICE_AREA_CAT, START_DATE, END_DATE, GENERAL_CODE, CHECKSUM, CREATE_DATE, CREATE_USER, LASTUPD_DATE, LASTUPD_USER) VALUES (525, 'LEEDCC', 'Leeds Crown Court', 'CC', 'COURT_TYPE', null, null, TO_DATE('2000-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'), null, '0429', '', TO_DATE('2012-10-16 10:16:21', 'YYYY-MM-DD HH24:MI:SS'), 'SYS', TO_DATE('2012-10-16 10:16:21', 'YYYY-MM-DD HH24:MI:SS'), 'SYS');
INSERT INTO COURT (COURT_PK, COURT_CODE, COURT_NAME, COURT_TYPE_ELM, COURT_TYPE_CAT, LOCAL_JUSTICE_AREA_ELM, LOCAL_JUSTICE_AREA_CAT, START_DATE, END_DATE, GENERAL_CODE, CHECKSUM, CREATE_DATE, CREATE_USER, LASTUPD_DATE, LASTUPD_USER) VALUES (813, 'SHEFCC', 'Sheffield Crown Court', 'CC', 'COURT_TYPE', '34', 'LOCAL_CRIMINAL_JUSTICE_BOARD', TO_DATE('2000-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'), null, null, '', TO_DATE('2012-10-16 10:16:21', 'YYYY-MM-DD HH24:MI:SS'), 'SYS', TO_DATE('2012-10-16 10:16:21', 'YYYY-MM-DD HH24:MI:SS'), 'SYS');
| 351.333333 | 540 | 0.734345 |
264a25d67e0bdb39edc0139353a803ce71ca7b9a | 1,413 | asm | Assembly | src/firmware-tests/Platform/ShiftRegister/EnableDisable/EnableDisablePortTest.asm | pete-restall/Cluck2Sesame-Prototype | 99119b6748847a7b6aeadc4bee42cbed726f7fdc | [
"MIT"
] | 1 | 2019-12-12T09:07:08.000Z | 2019-12-12T09:07:08.000Z | src/firmware-tests/Platform/ShiftRegister/EnableDisable/EnableDisablePortTest.asm | pete-restall/Cluck2Sesame-Prototype | 99119b6748847a7b6aeadc4bee42cbed726f7fdc | [
"MIT"
] | null | null | null | src/firmware-tests/Platform/ShiftRegister/EnableDisable/EnableDisablePortTest.asm | pete-restall/Cluck2Sesame-Prototype | 99119b6748847a7b6aeadc4bee42cbed726f7fdc | [
"MIT"
] | null | null | null | #include "Platform.inc"
#include "FarCalls.inc"
#include "ShiftRegister.inc"
#include "TestFixture.inc"
radix decimal
udata
global numberOfEnableCalls
global numberOfDisableCalls
global forcePortcBeforeEnable
global forcePortcBeforeDisable
global expectedPortc
numberOfEnableCalls res 1
numberOfDisableCalls res 1
forcePortcBeforeEnable res 1
forcePortcBeforeDisable res 1
expectedPortc res 1
EnableDisablePortTest code
global testArrange
testArrange:
banksel ANSEL
clrf ANSEL
banksel ANSELH
clrf ANSELH
fcall initialiseShiftRegister
banksel forcePortcBeforeEnable
movf forcePortcBeforeEnable, W
banksel PORTC
movwf PORTC
testAct:
banksel numberOfEnableCalls
movf numberOfEnableCalls
btfsc STATUS, Z
goto callDisableShiftRegister
callEnableShiftRegister:
fcall enableShiftRegister
banksel numberOfEnableCalls
decfsz numberOfEnableCalls
goto callEnableShiftRegister
callDisableShiftRegister:
banksel numberOfDisableCalls
movf numberOfDisableCalls
btfsc STATUS, Z
goto testAssert
banksel forcePortcBeforeDisable
movf forcePortcBeforeDisable, W
banksel PORTC
movwf PORTC
callDisableShiftRegisterInLoop:
fcall disableShiftRegister
banksel numberOfDisableCalls
decfsz numberOfDisableCalls
goto callDisableShiftRegisterInLoop
testAssert:
.aliasForAssert PORTC, _a
.aliasForAssert expectedPortc, _b
.assert "_a == _b, 'PORTC expectation failure.'"
return
end
| 19.094595 | 49 | 0.84218 |
995107f302714fb41af1c0fa4a1b2d71e0b4025f | 1,315 | h | C | src/datanode/dn_conf.h | gogobody/OpendfsSource | 22f76e610cd94e550b5dc911d2e5d7ca89f6f7c6 | [
"MIT"
] | null | null | null | src/datanode/dn_conf.h | gogobody/OpendfsSource | 22f76e610cd94e550b5dc911d2e5d7ca89f6f7c6 | [
"MIT"
] | null | null | null | src/datanode/dn_conf.h | gogobody/OpendfsSource | 22f76e610cd94e550b5dc911d2e5d7ca89f6f7c6 | [
"MIT"
] | null | null | null | #ifndef DN_CONF_H
#define DN_CONF_H
#include "dfs_types.h"
#include "dfs_array.h"
#include "dfs_conf.h"
typedef struct conf_server_s conf_server_t;
// cycle -> sconf
struct conf_server_s
{
int daemon;
int worker_n;
array_t bind_for_cli;
string_t ns_srv;
string_t listen_for_other_dn; // used for other dn
string_t my_paxos; // dn's own paxos
string_t ot_paxos; // paxos's NodeList
uint32_t connection_n; // 连接
string_t error_log;
string_t coredump_dir;
string_t pid_file;
uint32_t log_level;
uint32_t recv_buff_len;
uint32_t send_buff_len;
uint32_t max_tqueue_len;
string_t data_dir;
uint32_t heartbeat_interval;
uint32_t block_report_interval;
};
conf_object_t *get_dn_conf_object(void);
#define DEF_RBUFF_LEN 64 * 1024
#define DEF_SBUFF_LEN 64 * 1024
#define DEF_MMAX_TQUEUE_LEN 1000
#define set_def_string(key, value) do { \
if (!(key)->len) { \
(key)->data = (uchar_t *)(value); \
(key)->len = sizeof(value); \
}\
} while (0)
#define set_def_int(key, value) do { \
if ((key) == CONF_SIZE_NOT_SET) { \
(key) = value; \
} \
} while (0)
#define set_def_time(key, value) do { \
if ((key) == CONF_TIME_T_NOT_SET) { \
(key) = value;\
}\
} while (0)
#endif
| 21.916667 | 51 | 0.64943 |
262cde6bc98afc5e87c9b3b7464c1dbf3372b1c7 | 4,622 | java | Java | src/main/java/org/apache/hadoop/hbase/regionserver/wal/LogScannerByFile.java | logkv/logbase_changed | a5c5b9ac144079828c411e3aad4fffa454c748e6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/hadoop/hbase/regionserver/wal/LogScannerByFile.java | logkv/logbase_changed | a5c5b9ac144079828c411e3aad4fffa454c748e6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/hadoop/hbase/regionserver/wal/LogScannerByFile.java | logkv/logbase_changed | a5c5b9ac144079828c411e3aad4fffa454c748e6 | [
"Apache-2.0"
] | null | null | null | package org.apache.hadoop.hbase.regionserver.wal;
import java.io.IOException;
import java.util.List;
import java.util.SortedMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.regionserver.MemIndex;
import org.apache.hadoop.io.LongWritable;
public class LogScannerByFile extends LogScanner{
HLog.Entry entry = new HLog.Entry();
List<KeyValue> kvs = null;
List<LogEntryOffset> keyvalueOffset = null;
KeyValue.Key tmpKey = new KeyValue.Key();
int kvIdx = 0;
long beginOffset;
//WangSheng
public void init(SortedMap<LongWritable, Path> outputfiles, FileSystem fs, Configuration conf, MemIndex index, LogStoreCache cache)throws IOException{
initial(outputfiles, fs, conf);
this.index = index;
this.currentFileNum = this.files.firstKey();
this.currentFileReader = this.getReader(this.currentFileNum);
this.logCache = cache;
}
public void init(SortedMap<LongWritable, Path> outputfiles, FileSystem fs, Configuration conf, MemIndex index)throws IOException{
initial(outputfiles, fs, conf);
this.index = index;
this.currentFileNum = this.files.firstKey();
this.currentFileReader = this.getReader(this.currentFileNum);
}
// @Override
// public KeyValue next() throws IOException {
// while(true){
// if(kvs != null && kvIdx < kvs.size()){
// KeyValue kv = kvs.get(kvIdx);
// kv.getKeyForLog(tmpKey);
// LogEntryOffset memIndexOffset = this.index.getOffset(tmpKey);
// LogEntryOffset currentOffset = this.keyvalueOffset.get(kvIdx);
// kvIdx ++;
// if(memIndexOffset.compareTo(currentOffset) != 0){
// continue;
// }else
// return kv;
// }
// this.beginOffset = this.currentFileReader.getPosition();
// HLog.Entry ret = this.currentFileReader.next(entry);
// if(ret == null){
// // reach the final file
// if(this.currentFileNum.compareTo(this.files.lastKey()) == 0){
// return null;
// }
// // move to another log file
// LongWritable tmpFileNum = new LongWritable();
// tmpFileNum.set(this.currentFileNum.get() + 1);
// this.currentFileNum = this.files.tailMap(tmpFileNum).firstKey();
// this.currentFileReader = this.getReader(this.currentFileNum);
// continue;
// }else{
// kvs = entry.getEdit().getKeyValues();
// keyvalueOffset = entry.getKeyValueOffset(beginOffset, (int)currentFileNum.get(), keyvalueOffset);
// kvIdx = 0;
// continue;
// }
// }
// }
//wangsheng 2013-8-13
@Override
public KeyValue next() throws IOException {
while(true){
if(kvs != null && kvIdx < kvs.size()){
KeyValue kv = kvs.get(kvIdx);
// kv.getKeyForLog(tmpKey);
// LogEntryOffset memIndexOffset = this.index.getOffset(tmpKey);
// LogEntryOffset currentOffset = this.keyvalueOffset.get(kvIdx);
kvIdx ++;
// if(memIndexOffset.compareTo(currentOffset) != 0){
// continue;
// }else
if (kv == null) continue;
return kv;
}
this.beginOffset = this.currentFileReader.getPosition();
HLog.Entry ret = this.currentFileReader.next(entry);
if(ret == null){
// System.err.println("current file: "+this.currentFileNum.get());
// System.err.println("all "+files.size()+" files: "+files.firstKey().get()+" , "+files.lastKey().get());
// System.err.println(files.toString());
// reach the final file
if(this.currentFileNum.compareTo(this.files.lastKey()) == 0){
return null;
}
// System.out.println("Move to File: "+this.currentFileNum+1);
// move to another log file
LongWritable tmpFileNum = new LongWritable();
tmpFileNum.set(this.currentFileNum.get() + 1);
this.currentFileNum = this.files.tailMap(tmpFileNum).firstKey();
this.currentFileReader = this.getReader(this.currentFileNum);
continue;
}else{
kvs = entry.getEdit().getKeyValues();
keyvalueOffset = entry.getKeyValueOffset(beginOffset, (int)currentFileNum.get(), keyvalueOffset);
kvIdx = 0;
continue;
}
}
}
/**
* set scanner position
*/
public void setPosition(LogEntryOffset offset) throws IOException{
// this.currentFileNum.set(offset.filenum);
this.currentFileReader = this.getReader(new LongWritable(offset.filenum));
// System.err.println(this.currentFileReader.getPosition());
this.currentFileReader.seek(offset.offset-35);
// System.err.println(this.currentFileReader.getPosition());
}
public void seek(KeyValue.Key key) throws IOException{
throw new IOException("Scanner by File do not support seek() function");
}
}
| 35.282443 | 152 | 0.693423 |
ece97e24035218b93fdd248665a66eec7b5ab38d | 1,509 | ps1 | PowerShell | Public/Converts/ConvertFrom-NetbiosName.ps1 | MikeYEG/PSSharedGoods | b049a7f85e7e9fa97eb552165556b8e3a28307dc | [
"MIT"
] | 147 | 2018-09-21T16:11:51.000Z | 2022-03-25T07:08:24.000Z | Public/Converts/ConvertFrom-NetbiosName.ps1 | MikeYEG/PSSharedGoods | b049a7f85e7e9fa97eb552165556b8e3a28307dc | [
"MIT"
] | 19 | 2019-01-09T06:53:21.000Z | 2021-10-20T09:53:44.000Z | Public/Converts/ConvertFrom-NetbiosName.ps1 | MikeYEG/PSSharedGoods | b049a7f85e7e9fa97eb552165556b8e3a28307dc | [
"MIT"
] | 35 | 2018-10-29T10:12:11.000Z | 2022-03-11T12:30:08.000Z | function ConvertFrom-NetbiosName {
[cmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 0)]
[string[]] $Identity
)
process {
foreach ($Ident in $Identity) {
if ($Ident -like '*\*') {
$NetbiosWithObject = $Ident -split "\\"
if ($NetbiosWithObject.Count -eq 2) {
$LDAPQuery = ([ADSI]"LDAP://$($NetbiosWithObject[0])")
$DomainName = ConvertFrom-DistinguishedName -DistinguishedName $LDAPQuery.distinguishedName -ToDomainCN
[PSCustomObject] @{
DomainName = $DomainName
Name = $NetbiosWithObject[1]
}
} else {
# we can't be sure what we got so lets push back what we got
[PSCustomObject] @{
DomainName = ''
Name = $Ident
}
}
} else {
# we can't be sure what we got so lets push back what we got
[PSCustomObject] @{
DomainName = ''
Name = $Ident
}
}
}
}
}
<#
'TEST\Domain Admins', 'EVOTEC\Domain Admins', 'EVOTECPL\Domain Admins' | ConvertFrom-NetbiosName
ConvertFrom-NetbiosName -Identity 'TEST\Domain Admins', 'EVOTEC\Domain Admins', 'EVOTECPL\Domain Admins'
#> | 39.710526 | 123 | 0.487078 |
613df1e7beee8b14a21bbef2e405144c4ad6e73e | 268 | css | CSS | docs/assets/hear2021.css | neuralaudio/neuralaudio.github.io | f541e987f778a8112f645e1dafc6ffbc72cd56a1 | [
"Apache-2.0"
] | 4 | 2021-04-25T21:27:19.000Z | 2022-02-10T07:44:24.000Z | docs/assets/hear2021.css | neuralaudio/neuralaudio.github.io | f541e987f778a8112f645e1dafc6ffbc72cd56a1 | [
"Apache-2.0"
] | 4 | 2021-06-03T18:09:57.000Z | 2021-08-24T19:28:54.000Z | docs/assets/hear2021.css | neuralaudio/neuralaudio.github.io | f541e987f778a8112f645e1dafc6ffbc72cd56a1 | [
"Apache-2.0"
] | 2 | 2021-05-08T18:03:03.000Z | 2022-02-10T07:44:29.000Z | #hear-toc li {
margin-bottom: 5px;
}
article ul li {
margin-bottom: 4px;
margin-top: 4px;
}
.team-affiliation p {
font-size: medium;
margin-bottom: -6px;
}
.team-members sup {
font-size: x-small;
}
.bibliography p {
font-size: medium;
} | 12.761905 | 24 | 0.604478 |
594f6c6aac4c18b980f419a7f8b659029a503d52 | 531 | asm | Assembly | oeis/099/A099628.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/099/A099628.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/099/A099628.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A099628: Numbers m where m-th Catalan number A000108(m) = binomial(2m,m)/(m+1) is divisible by 2 but not by 4, i.e., where A048881(m) = 1.
; Submitted by Jamie Morken(s2)
; 2,4,5,8,9,11,16,17,19,23,32,33,35,39,47,64,65,67,71,79,95,128,129,131,135,143,159,191,256,257,259,263,271,287,319,383,512,513,515,519,527,543,575,639,767,1024,1025,1027,1031,1039,1055,1087,1151,1279,1535,2048
seq $0,130328 ; Triangle of differences between powers of 2, read by rows.
mul $0,2
seq $0,3188 ; Decimal equivalent of Gray code for n.
sub $0,1
| 59 | 210 | 0.713748 |
03a2aa392ca7ee290f7f03da2ec696bb76d490d2 | 834 | kt | Kotlin | Todo/app/src/main/java/com/example/todo/model/DataModel.kt | rockman/learn-android-todo | 64e5f459246e92ca9e85510ed5505056916173b2 | [
"MIT"
] | null | null | null | Todo/app/src/main/java/com/example/todo/model/DataModel.kt | rockman/learn-android-todo | 64e5f459246e92ca9e85510ed5505056916173b2 | [
"MIT"
] | null | null | null | Todo/app/src/main/java/com/example/todo/model/DataModel.kt | rockman/learn-android-todo | 64e5f459246e92ca9e85510ed5505056916173b2 | [
"MIT"
] | null | null | null | package com.example.todo.model
const val ITEM_POSITION = "ITEM_POSITION"
data class Todo(val todoId: String, val title: String) {
override fun toString(): String {
return title
}
}
data class Detail(var todo: Todo, val title: String, var text: String)
object DataManager {
val todoItems = HashMap<String, Todo>()
val detailItems = ArrayList<Detail>()
init {
addTodo("alpha", "Do Alpha")
addTodo("beta", "Do Beta")
addDetail("Title 1", "Text 1")
addDetail("Title 2", "Text 2")
}
private fun addTodo(todoId: String, title: String) {
todoItems[todoId] = Todo(todoId, title)
}
private fun addDetail(title: String, text: String) {
detailItems.add(Detail(todoItems.values.random(), title, text))
}
}
| 23.828571 | 72 | 0.606715 |
fc99b19502c2f16aa570a2101f8bb71e4bc71401 | 651 | css | CSS | InstagramWrapper.Web.Test/Content/css/style.css | cagrik/csharp-instagram-wrapper | 821402279bdf15bca2e4f880bae04b15345fd41e | [
"MIT"
] | 23 | 2015-06-11T20:47:03.000Z | 2021-02-09T17:43:44.000Z | InstagramWrapper.Web.Test/Content/css/style.css | jungilmoon/csharp-instagram-wrapper | 821402279bdf15bca2e4f880bae04b15345fd41e | [
"MIT"
] | 3 | 2016-01-04T08:01:45.000Z | 2016-06-17T20:14:58.000Z | InstagramWrapper.Web.Test/Content/css/style.css | jungilmoon/csharp-instagram-wrapper | 821402279bdf15bca2e4f880bae04b15345fd41e | [
"MIT"
] | 7 | 2015-01-23T17:35:24.000Z | 2017-10-24T07:12:01.000Z | body {
margin: 0 auto;
width: 65%;
}
#main {
width: 100%;
height: auto;
float: left;
}
#main header {
height:100px;
width:100%;
color:blue;
}
#b {
width: 100%;
height: auto;
float: left;
}
#main #b .content {
height: auto;
width: 100%;
float: left;
margin: 12px 0px 12px 0px;
}
#main #b .content .left {
float: left;
height: 550px;
width: 20%;
}
#main #b .content .right {
float: left;
height: 550px;
width: 80%;
}
.like {
background-color:#000000;
}
.liked{background-color:#ff0000;}
| 14.795455 | 33 | 0.485407 |
45ff22a1c9b107996fa06d799dc182751c4bc02d | 3,973 | sql | SQL | database/slchildren.sql | FrancisDcruz04/ChildLearningAssistance | 13278106934948a3dd54783869fed9ea09a05bcf | [
"MIT"
] | 3 | 2020-09-20T08:08:09.000Z | 2021-08-16T08:12:56.000Z | database/slchildren.sql | FrancisDcruz04/ChildLearningAssistance | 13278106934948a3dd54783869fed9ea09a05bcf | [
"MIT"
] | null | null | null | database/slchildren.sql | FrancisDcruz04/ChildLearningAssistance | 13278106934948a3dd54783869fed9ea09a05bcf | [
"MIT"
] | 1 | 2020-11-30T17:07:06.000Z | 2020-11-30T17:07:06.000Z | -- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 01, 2019 at 01:46 PM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 5.6.40
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: `slchildren`
--
-- --------------------------------------------------------
--
-- Table structure for table `rating`
--
CREATE TABLE `rating` (
`rid` int(20) NOT NULL,
`listening` int(5) NOT NULL,
`reading` int(5) NOT NULL,
`speaking` int(5) NOT NULL,
`writing` int(5) NOT NULL,
`disability` int(5) NOT NULL,
`mobility` int(5) NOT NULL,
`level` varchar(30) NOT NULL,
`sid` int(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `rating`
--
INSERT INTO `rating` (`rid`, `listening`, `reading`, `speaking`, `writing`, `disability`, `mobility`, `level`, `sid`) VALUES
(8, 5, 5, 4, 5, 5, 5, 'EXCELLENT', 1),
(9, 1, 1, 1, 1, 1, 1, 'LOW', 2),
(10, 1, 1, 1, 1, 1, 1, 'LOW', 3),
(11, 3, 2, 2, 2, 2, 3, 'NORMAL', 4),
(12, 4, 4, 3, 3, 3, 3, 'GOOD', 5);
-- --------------------------------------------------------
--
-- Table structure for table `student`
--
CREATE TABLE `student` (
`sid` int(20) NOT NULL,
`name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
`password` varchar(100) NOT NULL,
`tid` int(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `student`
--
INSERT INTO `student` (`sid`, `name`, `email`, `password`, `tid`) VALUES
(1, 'mayur', 'mayur@gmail.com', '123456', 7),
(4, 'Prasad', 'prasad@gmail.com', '123456', 10),
(3, 'Francis', 'francis@gmail.com', '123456', 9),
(5, 'sebin', 'sebin@gmail.com', '123456', 11);
-- --------------------------------------------------------
--
-- Table structure for table `teacher`
--
CREATE TABLE `teacher` (
`tid` int(20) NOT NULL,
`name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL,
`password` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `teacher`
--
INSERT INTO `teacher` (`tid`, `name`, `email`, `password`) VALUES
(1, 'madam', 'madam@slc.com', '123456'),
(2, 'madam', 'madam@slc.org', '123456'),
(3, 'madama', 'madam@sly.com', '123456789'),
(4, 'asdfg', 'sasfasdf@asd.com', '123456789'),
(5, 'madam', 'asdfg@qwer.vom', '123456789'),
(6, 'madam', 'asd@asd.nom', '123456789'),
(7, 'vijit', 'vijit@gmail.com', '123456'),
(8, 'ram', 'ram@gmail.com', '123456'),
(9, 'Jetso', 'jetso@gmail.com', '123456'),
(10, 'Yashwita', 'yashwita@gmail.com', '123456'),
(11, 'sapan', 'sapan@gmail.com', '123456');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `rating`
--
ALTER TABLE `rating`
ADD PRIMARY KEY (`rid`),
ADD KEY `sid` (`sid`);
--
-- Indexes for table `student`
--
ALTER TABLE `student`
ADD PRIMARY KEY (`sid`),
ADD KEY `tid` (`tid`),
ADD KEY `tid_2` (`tid`);
--
-- Indexes for table `teacher`
--
ALTER TABLE `teacher`
ADD PRIMARY KEY (`tid`),
ADD UNIQUE KEY `email` (`email`),
ADD KEY `tid` (`tid`),
ADD KEY `tid_2` (`tid`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `rating`
--
ALTER TABLE `rating`
MODIFY `rid` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `student`
--
ALTER TABLE `student`
MODIFY `sid` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `teacher`
--
ALTER TABLE `teacher`
MODIFY `tid` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
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 */;
| 24.524691 | 124 | 0.614649 |
2698c93fb482b985d265374fcf320db58b5011f5 | 2,273 | java | Java | app/src/main/java/ca/klapstein/baudit/activities/ViewAccountActivity.java | CMPUT301F18T16/Baudit | 3ead64a2a3916809906e9d8e9eb0fa2aa4a39589 | [
"MIT"
] | null | null | null | app/src/main/java/ca/klapstein/baudit/activities/ViewAccountActivity.java | CMPUT301F18T16/Baudit | 3ead64a2a3916809906e9d8e9eb0fa2aa4a39589 | [
"MIT"
] | 182 | 2018-10-11T14:02:45.000Z | 2018-12-03T21:36:05.000Z | app/src/main/java/ca/klapstein/baudit/activities/ViewAccountActivity.java | CMPUT301F18T16/Baudit | 3ead64a2a3916809906e9d8e9eb0fa2aa4a39589 | [
"MIT"
] | 1 | 2018-10-12T03:27:38.000Z | 2018-10-12T03:27:38.000Z | package ca.klapstein.baudit.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import ca.klapstein.baudit.R;
import ca.klapstein.baudit.presenters.ViewAccountPresenter;
import ca.klapstein.baudit.views.ViewAccountView;
public class ViewAccountActivity extends AppCompatActivity implements ViewAccountView {
public static String VIEW_ACCOUNT_USERNAME_EXTRA = "username";
private String username;
private ViewAccountPresenter presenter;
private TextView nameView;
private TextView usernameView;
private TextView emailView;
private TextView phoneNumberView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_account);
username = getIntent().getStringExtra(VIEW_ACCOUNT_USERNAME_EXTRA);
presenter = new ViewAccountPresenter(this, getApplicationContext());
nameView = findViewById(R.id.view_account_name);
usernameView = findViewById(R.id.view_account_username);
emailView = findViewById(R.id.view_account_email);
phoneNumberView = findViewById(R.id.view_account_phone_number);
Button okButton = findViewById(R.id.view_account_ok_button);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public void onStart() {
super.onStart();
presenter.viewStarted(username);
}
@Override
public void updateNameDisplay(String firstName, String lastName) {
String name = firstName + " " + lastName;
nameView.setText(name);
}
@Override
public void updateUsernameDisplay(String username) {
usernameView.setText(username);
}
@Override
public void updateEmailDisplay(String email) {
emailView.setText(email);
}
@Override
public void updatePhoneNumberDisplay(String phoneNumber) {
phoneNumberView.setText(phoneNumber);
}
@Override
public void updateViewAccountError() {
finish();
}
}
| 29.141026 | 87 | 0.704795 |
0ba58112cd9b83adb66bbb157c35557326dccf99 | 10,409 | py | Python | src/github4/session.py | staticdev/github3.py | b9af598dcf1771c083dcc512a2aa8e5008bf4ea8 | [
"MIT"
] | null | null | null | src/github4/session.py | staticdev/github3.py | b9af598dcf1771c083dcc512a2aa8e5008bf4ea8 | [
"MIT"
] | 32 | 2021-02-17T19:46:21.000Z | 2021-05-12T05:56:03.000Z | src/github4/session.py | staticdev/github3.py | b9af598dcf1771c083dcc512a2aa8e5008bf4ea8 | [
"MIT"
] | null | null | null | """Module containing session and auth logic."""
import collections.abc as abc_collections
import datetime
from contextlib import contextmanager
from logging import getLogger
import dateutil.parser
import requests
from . import __version__
from . import exceptions as exc
__url_cache__ = {}
__logs__ = getLogger(__package__)
def requires_2fa(response):
"""Determine whether a response requires us to prompt the user for 2FA."""
if (
response.status_code == 401
and "X-GitHub-OTP" in response.headers
and "required" in response.headers["X-GitHub-OTP"]
):
return True
return False
class BasicAuth(requests.auth.HTTPBasicAuth):
"""Sub-class requests's class so we have a nice repr."""
def __repr__(self):
"""Use the username as the representation."""
return "basic {}".format(self.username)
class TokenAuth(requests.auth.AuthBase):
"""Auth class that handles simple tokens."""
header_format_str = "token {}"
def __init__(self, token):
"""Store our token."""
self.token = token
def __repr__(self):
"""Return a nice view of the token in use."""
return "token {}...".format(self.token[:4])
def __ne__(self, other):
"""Test for equality, or the lack thereof."""
return not self == other
def __eq__(self, other):
"""Test for equality, or the lack thereof."""
return self.token == getattr(other, "token", None)
def __call__(self, request):
"""Add the authorization header and format it."""
request.headers["Authorization"] = self.header_format_str.format(self.token)
return request
class GitHubSession(requests.Session):
"""Our slightly specialized Session object.
Normally this is created automatically by
:class:`~github4.github.GitHub`. To use alternate values for
network timeouts, this class can be instantiated directly and
passed to the GitHub object. For example:
.. code-block:: python
gh = github.GitHub(session=session.GitHubSession(
default_connect_timeout=T, default_read_timeout=N))
:param default_connect_timeout:
the number of seconds to wait when establishing a connection to
GitHub
:type default_connect_timeout:
float
:param default_read_timeout:
the number of seconds to wait for a response from GitHub
:type default_read_timeout:
float
"""
auth = None
__attrs__ = requests.Session.__attrs__ + [
"base_url",
"two_factor_auth_cb",
"default_connect_timeout",
"default_read_timeout",
"request_counter",
]
def __init__(self, default_connect_timeout=4, default_read_timeout=10):
"""Slightly modify how we initialize our session."""
super(GitHubSession, self).__init__()
self.default_connect_timeout = default_connect_timeout
self.default_read_timeout = default_read_timeout
self.headers.update(
{
# Only accept JSON responses
"Accept": "application/vnd.github.v3.full+json",
# Only accept UTF-8 encoded data
"Accept-Charset": "utf-8",
# Always sending JSON
"Content-Type": "application/json",
# Set our own custom User-Agent string
"User-Agent": f"github4.py/{__version__}",
}
)
self.base_url = "https://api.github.com"
self.two_factor_auth_cb = None
self.request_counter = 0
@property
def timeout(self):
"""Return the timeout tuple as expected by Requests"""
return (self.default_connect_timeout, self.default_read_timeout)
def basic_auth(self, username, password):
"""Set the Basic Auth credentials on this Session.
:param str username: Your GitHub username
:param str password: Your GitHub password
"""
if not (username and password):
return
self.auth = BasicAuth(username, password)
def build_url(self, *args, **kwargs):
"""Build a new API url from scratch."""
parts = [kwargs.get("base_url") or self.base_url]
parts.extend(args)
parts = [str(p) for p in parts]
key = tuple(parts)
__logs__.info("Building a url from %s", key)
if key not in __url_cache__:
__logs__.info("Missed the cache building the url")
__url_cache__[key] = "/".join(parts)
return __url_cache__[key]
def handle_two_factor_auth(self, args, kwargs):
"""Handler for when the user has 2FA turned on."""
headers = kwargs.pop("headers", {})
headers.update({"X-GitHub-OTP": str(self.two_factor_auth_cb())})
kwargs.update(headers=headers)
return super(GitHubSession, self).request(*args, **kwargs)
def has_auth(self):
"""Check for whether or not the user has authentication configured."""
return self.auth or self.headers.get("Authorization")
def oauth2_auth(self, client_id, client_secret):
"""Use OAuth2 for authentication.
It is suggested you install requests-oauthlib to use this.
:param str client_id: Client ID retrieved from GitHub
:param str client_secret: Client secret retrieved from GitHub
"""
raise NotImplementedError("These features are not implemented yet")
def request(self, *args, **kwargs):
"""Make a request, count it, and handle 2FA if necessary."""
kwargs.setdefault("timeout", self.timeout)
response = super(GitHubSession, self).request(*args, **kwargs)
self.request_counter += 1
if requires_2fa(response) and self.two_factor_auth_cb:
# No need to flatten and re-collect the args in
# handle_two_factor_auth
new_response = self.handle_two_factor_auth(args, kwargs)
new_response.history.append(response)
response = new_response
return response
def retrieve_client_credentials(self):
"""Return the client credentials.
:returns: tuple(client_id, client_secret)
"""
client_id = self.params.get("client_id")
client_secret = self.params.get("client_secret")
return (client_id, client_secret)
def two_factor_auth_callback(self, callback):
"""Register our 2FA callback specified by the user."""
if not callback:
return
if not isinstance(callback, abc_collections.Callable):
raise ValueError("Your callback should be callable")
self.two_factor_auth_cb = callback
def token_auth(self, token):
"""Use an application token for authentication.
:param str token: Application token retrieved from GitHub's
/authorizations endpoint
"""
if not token:
return
self.auth = TokenAuth(token)
def app_bearer_token_auth(self, headers, expire_in):
"""Authenticate as an App to be able to view its metadata."""
if not headers:
return
self.auth = AppBearerTokenAuth(headers, expire_in)
def app_installation_token_auth(self, json):
"""Use an access token generated by an App's installation."""
if not json:
return
self.auth = AppInstallationTokenAuth(json["token"], json["expires_at"])
@contextmanager
def temporary_basic_auth(self, *auth):
"""Allow us to temporarily swap out basic auth credentials."""
old_basic_auth = self.auth
old_token_auth = self.headers.get("Authorization")
self.basic_auth(*auth)
yield
self.auth = old_basic_auth
if old_token_auth:
self.headers["Authorization"] = old_token_auth
@contextmanager
def no_auth(self):
"""Unset authentication temporarily as a context manager."""
old_basic_auth, self.auth = self.auth, None
old_token_auth = self.headers.pop("Authorization", None)
yield
self.auth = old_basic_auth
if old_token_auth:
self.headers["Authorization"] = old_token_auth
def _utcnow():
return datetime.datetime.now(dateutil.tz.UTC)
class AppInstallationTokenAuth(TokenAuth):
"""Use token authentication but throw an exception on expiration."""
def __init__(self, token, expires_at):
"""Set-up our authentication handler."""
super(AppInstallationTokenAuth, self).__init__(token)
self.expires_at_str = expires_at
self.expires_at = dateutil.parser.parse(expires_at)
def __repr__(self):
"""Return a nice view of the token in use."""
return "app installation token {}... expiring at {}".format(
self.token[:4], self.expires_at_str
)
@property
def expired(self):
"""Indicate whether our token is expired or not."""
now = _utcnow()
return now > self.expires_at
def __call__(self, request):
"""Add the authorization header and format it."""
if self.expired:
raise exc.AppInstallationTokenExpired(
"Your app installation token expired at {}".format(self.expires_at_str)
)
return super(AppInstallationTokenAuth, self).__call__(request)
class AppBearerTokenAuth(TokenAuth):
"""Use JWT authentication but throw an exception on expiration."""
header_format_str = "Bearer {}"
def __init__(self, token, expire_in):
"""Set-up our authentication handler."""
super(AppBearerTokenAuth, self).__init__(token)
expire_in = datetime.timedelta(seconds=expire_in)
self.expires_at = _utcnow() + expire_in
def __repr__(self):
"""Return a helpful view of the token."""
return "app bearer token {} expiring at {}".format(
self.token[:4], str(self.expires_at)
)
@property
def expired(self):
"""Indicate whether our token is expired or not."""
now = _utcnow()
return now > self.expires_at
def __call__(self, request):
"""Add the authorization header and format it."""
if self.expired:
raise exc.AppTokenExpired(
"Your app token expired at {}".format(str(self.expires_at))
)
return super(AppBearerTokenAuth, self).__call__(request)
| 33.149682 | 87 | 0.639639 |
0faf7687733dc92f35e7bf39b80e9365499cacc7 | 263 | swift | Swift | Echo/Classes/ViewModel.swift | JanX2/Echo | ccc0fcc0bbfb798e5091b71b881c66fae149deda | [
"MIT"
] | 29 | 2020-01-13T21:58:17.000Z | 2022-02-19T23:23:21.000Z | Echo/Classes/ViewModel.swift | JanX2/Echo | ccc0fcc0bbfb798e5091b71b881c66fae149deda | [
"MIT"
] | null | null | null | Echo/Classes/ViewModel.swift | JanX2/Echo | ccc0fcc0bbfb798e5091b71b881c66fae149deda | [
"MIT"
] | 2 | 2021-03-18T03:18:24.000Z | 2022-01-18T11:16:53.000Z | //
// ViewModel.swift
// Echo
//
// Created by Yoshimasa Niwa on 5/1/21.
// Copyright © 2021 Yoshimasa Niwa. All rights reserved.
//
import Combine
import Foundation
final class ViewModel: ObservableObject {
@Published
var isRunning: Bool = false
}
| 16.4375 | 57 | 0.695817 |
f6abe41af42f0563d0de4646d3c0a0dc8b8bd227 | 426 | kt | Kotlin | ktor-hosts/ktor-netty/src/org/jetbrains/ktor/netty/NettyApplicationCallHandler.kt | sitexa/sweet | 83ba798597c4c09bb972a839fea2e9d06f647ea3 | [
"Apache-2.0"
] | null | null | null | ktor-hosts/ktor-netty/src/org/jetbrains/ktor/netty/NettyApplicationCallHandler.kt | sitexa/sweet | 83ba798597c4c09bb972a839fea2e9d06f647ea3 | [
"Apache-2.0"
] | null | null | null | ktor-hosts/ktor-netty/src/org/jetbrains/ktor/netty/NettyApplicationCallHandler.kt | sitexa/sweet | 83ba798597c4c09bb972a839fea2e9d06f647ea3 | [
"Apache-2.0"
] | null | null | null | package org.jetbrains.ktor.netty
import io.netty.channel.*
import org.jetbrains.ktor.pipeline.*
internal class NettyApplicationCallHandler(private val host: NettyApplicationHost) : SimpleChannelInboundHandler<NettyApplicationCall>() {
override fun channelRead0(context: ChannelHandlerContext, msg: NettyApplicationCall) {
launchAsync(context.executor()) {
host.pipeline.execute(msg)
}
}
} | 35.5 | 138 | 0.753521 |
63730fbc7d0ed79dd01118dd1f61f84ec460f149 | 3,250 | ps1 | PowerShell | Tests/Update-TeamviewerDevice.Tests.ps1 | Ninja-Tw1sT/PoSh-TeamViewer | 17629621e107dc41fe4dd9d432dc7712779f467b | [
"MIT"
] | 15 | 2016-06-07T22:37:27.000Z | 2021-04-13T16:09:51.000Z | Tests/Update-TeamviewerDevice.Tests.ps1 | Ninja-Tw1sT/PoSh-TeamViewer | 17629621e107dc41fe4dd9d432dc7712779f467b | [
"MIT"
] | 3 | 2016-06-08T22:54:59.000Z | 2016-07-06T23:02:02.000Z | Tests/Update-TeamviewerDevice.Tests.ps1 | Ninja-Tw1sT/PoSh-TeamViewer | 17629621e107dc41fe4dd9d432dc7712779f467b | [
"MIT"
] | 6 | 2016-06-08T20:48:11.000Z | 2019-09-03T22:10:57.000Z | Import-Module Pester -ErrorAction Stop
Import-Module $PSScriptRoot\..\Posh-Teamviewer\Posh-TeamViewer.psd1
InModuleScope 'Posh-Teamviewer' {
Describe 'Update-TeamviewerDevice' {
$AccessToken = ConvertTo-SecureString -String 'Fake-AccessTokenText123456789' -AsPlainText -Force
$Password = 'FakePassword'
Context 'Updates Device Description and Alias' {
$MockedDeviceId = 'r123456789'
$Description = 'Test Lab Device 1'
$Alias = 'Test1 (Test Lab)'
Mock Get-TeamviewerDeviceProperty { Return $MockedDeviceId } -Verifiable
Mock Set-TeamviewerDeviceList {}
Mock Invoke-RestMethod { Return ($Body | ConvertFrom-Json) } -Verifiable
$Results = Update-TeamviewerDevice -ComputerName 'Test1' -Description $Description -Alias $Alias -AccessToken $AccessToken
It 'Should Return Proper Json Description' {
$Results.Description | Should Be $Description
}
It 'Should Return Proper Json Alias' {
$Results.Alias | Should Be $Alias
}
It 'Should Not Set Device List' {
Assert-MockCalled Set-TeamviewerDeviceList -Times 0
}
It "Should Assert Mocks" {
Assert-VerifiableMocks
}
It 'Should Return DeviceId' {
Get-TeamviewerDeviceProperty -ComputerName 'Test1' | Should Be $MockedDeviceId
}
}
Context 'Updates Password with Update Switch' {
$MockedDeviceId = 'r123456789'
Mock Get-TeamviewerDeviceProperty { Return $MockedDeviceId } -Verifiable
Mock Set-TeamviewerDeviceList {} -Verifiable
Mock Invoke-RestMethod { Return ($Body | ConvertFrom-Json) } -Verifiable
$Results = Update-TeamviewerDevice -ComputerName 'Test1' -Password $Password -AccessToken $AccessToken -UpdateDeviceList
It 'Should Return Proper Json Password' {
$Results.Password | Should Be $Password
}
It 'Should Set Device List' {
Assert-MockCalled Set-TeamviewerDeviceList -Times 1
}
It "Should Assert Mocks" {
Assert-VerifiableMocks
}
It 'Should Return DeviceId' {
Get-TeamviewerDeviceProperty -ComputerName 'Test1' | Should Be $MockedDeviceId
}
}
Context 'Rest-Method Returns an Error' {
$MockedDeviceId = 'r123456789'
Mock Get-TeamviewerDeviceProperty { Return $MockedDeviceId } -Verifiable
Mock ConvertFrom-Json {} -Verifiable
Mock Invoke-RestMethod { Get-Content -Path .\Fakepath.txt -ErrorVariable TVError -ErrorAction SilentlyContinue } -Verifiable
It 'Should Throw TVError' {
$Results = { Update-TeamviewerDevice -ComputerName 'Test1' -Password $Password -AccessToken $AccessToken }
$Results | Should Throw
}
It 'Should Assert Mocks' {
Assert-VerifiableMocks
}
}
}
} | 39.156627 | 136 | 0.584615 |
a8dd7c94353138f76165a205da547c0aec1acf71 | 3,439 | sql | SQL | sql/sga_advice_selective.sql | fatdba/oracle-script-lib | efa9f5623bc3f27cea37a815f5bc3766d21b1b19 | [
"MIT"
] | null | null | null | sql/sga_advice_selective.sql | fatdba/oracle-script-lib | efa9f5623bc3f27cea37a815f5bc3766d21b1b19 | [
"MIT"
] | null | null | null | sql/sga_advice_selective.sql | fatdba/oracle-script-lib | efa9f5623bc3f27cea37a815f5bc3766d21b1b19 | [
"MIT"
] | 2 | 2022-01-16T20:34:08.000Z | 2022-02-10T16:45:46.000Z | -- gv$sga_target_advice
-- display if more than min_pct
set linesize 200 trimspool on
set pagesize 100
set verify off
def min_pct_gain=5
@@legacy-exclude
clear break
break on inst_id skip 1
set linesize 200 trimspool on
set pagesize 100
col inst_id format 9999 head 'INST|ID'
col con_id format 999 head 'CON|ID'
col sga_size format 9,999,999,999 head 'SGA|Megabytes'
col old_sga_size format 9,999,999,999 head 'Old SGA|Megabytes'
col sga_size_factor format 90.0999 head 'SGA|Size|Factor'
col old_sga_size_factor format 90.0999 head 'Old SGA|Size|Factor'
col estd_db_time format 99,999,999 head 'EST|DB TIME'
col old_estd_db_time format 99,999,999 head 'Old EST|DB TIME'
col old_time_factor format 90.0999 head 'Old TIME|FACTOR'
col new_time_factor format 90.0999 head 'New TIME|FACTOR'
col estd_buffer_cache_size format 99,999,999 head 'EST|Buffer|Cache Meg'
col estd_shared_pool_size format 99,999,999 head 'EST|Shared|Pool Meg'
col factor_saved_pct format 90.99 head 'EST|Saved|Pct'
with data as (
SELECT inst_id
&legacy_db , con_id
, sga_size
, sga_size_factor
, estd_db_time
, estd_db_time_factor
, estd_physical_reads
&legacy_db , estd_buffer_cache_size
&legacy_db , estd_shared_pool_size
from gv$sga_target_advice
),
curr_sga as (
select d.*
from data d
-- change from 1 to previous value for testing
--where d.sga_size_factor = .5
where d.sga_size_factor = 1
),
max_sga as (
select d.*
from data d
where (d.inst_id, d.sga_size_factor) in (
select inst_id, max(sga_size_factor) sga_size_factor
from data d
group by inst_id
)
),
min_reads as (
select /*+ nomerge */
inst_id
, min(estd_physical_reads) estd_physical_reads
from gv$sga_target_advice
group by inst_id
),
opt_sga as (
select
a.inst_id
&legacy_db , a.con_id
, sga_size
, sga_size_factor
, estd_db_time
, estd_db_time_factor
, a.estd_physical_reads
&legacy_db , estd_buffer_cache_size
&legacy_db , estd_shared_pool_size
, rank() over (partition by a.inst_id, a.estd_physical_reads order by a.sga_size_factor) opt_sga_rank
from gv$sga_target_advice a
, min_reads m
where m.inst_id = a.inst_id
and m.estd_physical_reads = a.estd_physical_reads
),
selector as (
select c.inst_id
&legacy_db , c.con_id
, c.sga_size old_sga_size
, m.sga_size new_sga_size
, c.sga_size_factor old_sga_size_factor
, m.sga_size_factor new_sga_size_factor
, c.estd_db_time_factor old_estd_db_time_factor
, m.estd_db_time_factor new_estd_db_time_factor
, c.estd_db_time old_estd_db_time
, m.estd_db_time new_estd_db_time
, (c.estd_db_time_factor - m.estd_db_time_factor) * 100 factor_saved_pct
from curr_sga c
, opt_sga m
where c.inst_id = m.inst_id
&legacy_db and c.con_id = m.con_id
and m.opt_sga_rank = 1
and (c.estd_db_time_factor - m.estd_db_time_factor ) * 100 > &min_pct_gain
)
select distinct
d.inst_id
&legacy_db , d.con_id
, s.old_sga_size
, d.sga_size
, s.old_sga_size_factor
, d.sga_size_factor
, s.old_estd_db_time
, d.estd_db_time
, s.old_estd_db_time_factor old_time_factor
, d.estd_db_time_factor new_time_factor
&legacy_db , estd_buffer_cache_size
&legacy_db , estd_shared_pool_size
, s.factor_saved_pct
from data d
join selector s on s.inst_id = d.inst_id
&legacy_db and s.con_id = d.con_id
and s.new_sga_size_factor = d.sga_size_factor
--and d.shared_pool_size_factor in ( s.max_factor, s.shared_pool_size_factor )
order by d.inst_id, d.sga_size_factor
/
| 27.293651 | 103 | 0.771736 |
2bf79dd27e61b513cda55152693b3a9bdc819888 | 7,245 | sql | SQL | Databases/office_management_system.sql | lanka97/bightstar_enterprise | a308ea5070e6808a7b02169c523a6f35c333ca0d | [
"MIT"
] | null | null | null | Databases/office_management_system.sql | lanka97/bightstar_enterprise | a308ea5070e6808a7b02169c523a6f35c333ca0d | [
"MIT"
] | null | null | null | Databases/office_management_system.sql | lanka97/bightstar_enterprise | a308ea5070e6808a7b02169c523a6f35c333ca0d | [
"MIT"
] | null | null | null | -- MySQL dump 10.13 Distrib 8.0.12, for Win64 (x86_64)
--
-- Host: localhost Database: office_management_system
-- ------------------------------------------------------
-- Server version 8.0.11
/*!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 */;
SET NAMES utf8 ;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Dumping data for table `available_machines`
--
LOCK TABLES `available_machines` WRITE;
/*!40000 ALTER TABLE `available_machines` DISABLE KEYS */;
INSERT INTO `available_machines` VALUES ('7812345673','Toshiba','Color','0','Brand New','New Machine'),('7871236789','Toshiba','Color','1000','Good Condition','Used Machine,Available For 2nd User'),('7872347890','Toshiba','Color','0','Brand New','New Machine'),('8812344567','Ricoh','Black','2000','Good Condition','Used Machine,Available For 2nd User'),('8812389021','Ricoh','Black','0','Brand New','New Machine'),('8912456789','Ricoh','Color','3000','Good Condition','Used Machine,Available For 2nd User'),('8912789087','Ricoh','Color','500','Good Condition','Used Machine,Available For 2nd User'),('8990919293','Ricoh','Color','0','Brand New','New Machine'),('Ricoh','Color','8971236540','400','Brand New','Brand New Machine');
/*!40000 ALTER TABLE `available_machines` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `payment`
--
LOCK TABLES `payment` WRITE;
/*!40000 ALTER TABLE `payment` DISABLE KEYS */;
/*!40000 ALTER TABLE `payment` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `rent`
--
LOCK TABLES `rent` WRITE;
/*!40000 ALTER TABLE `rent` DISABLE KEYS */;
INSERT INTO `rent` VALUES ('689012349V','Toshiba','7623120987','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('689012349V','Ricoh','8990919489','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('689076531V','Toshiba','7624119832','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('741258963V','Ricoh','7898521470','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('741258963V','Ricoh','3698521470','September',NULL,NULL,NULL,NULL,NULL,'Pending'),('781234098V','Ricoh','8976120985','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('897654123V','Toshiba','7669871230','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('897654123V','Toshiba','4569871230','September',NULL,NULL,NULL,NULL,NULL,'Pending'),('899076234V','Ricoh','7632109876','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('919076723V','Toshiba','2345670981','March ',325,'Cash Payment','2018-09-28','No','No','Completed'),('919076723V','Toshiba','8945670981','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('919076723V','Toshiba','2345670981','September',NULL,NULL,NULL,NULL,NULL,'Pending'),('951100374V','Ricoh','8945210981','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('962791790V','Toshiba','7687213456','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('962890712V','Ricoh','9871236540','May',5000,'Cash Payment','2018-10-01','No','No','Completed'),('962890712V','Toshiba','7687172731','October',NULL,NULL,NULL,NULL,NULL,'Pending'),('962890712V','Toshiba','7654321098','September',250,'Cash Payment','2018-09-30','No','No','Completed'),('962890712V','Ricoh','9871236540','September',5000,'Cash Payment','2018-10-01','No','No','Completed'),('971290456V','Toshiba','7823123456','October',NULL,NULL,NULL,NULL,NULL,'Pending');
/*!40000 ALTER TABLE `rent` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `rented_customers`
--
LOCK TABLES `rented_customers` WRITE;
/*!40000 ALTER TABLE `rented_customers` DISABLE KEYS */;
INSERT INTO `rented_customers` VALUES ('689012349V','Customer Two','No 2,Street 2,City 2','+94761234560','usertwo@gmail.com','20000','Cash Payment','No','No'),('689076531V','Customer Two','No 2,Street 2,City 2','+94125678901','customer2@gmail.com','10000','Cash Payment','No','No'),('741258963V','User Four','Address','+94766218901','userfour@gmail.com','10000','Cash Payment','No','No'),('781234098V','Customer Test','No 3,Street 3,City 3','+94768902341','user3@gamil.com','20000','Cash Payment','No','No'),('897654123V','Customer Test Test','No 1,Street 1,City 1','+94112345098','testemail@gmail.com','10000','Cash Payment','No','No'),('899076234V','Customer Eight','Address','+94112890765','pasindubahagya@outlook.com','20000','Cash Payment','No','No'),('919076723V','User Test','12/A , Main Street , Nugegoda.','+94112751918','usertest@gmail.com','20000','Cash Payment','No','No'),('951100374V','Naveen','Address','+94779090433','naveenb@gmail.com','10000','Cash Payment','No','No'),('962791790V','Pasindu','No 1,Street 1,City 1,Postal Code','+94112987654','pasindubahagya@gmail.com','40000','Cheque Payment','Peoples Bank','234098'),('962890712V','Customer Five','No 5,Street 5,City 5','+94766121660','pasindubahagya@gmail.com','10000','Cheque Payment','Peoples Bank','258741'),('971290456V','Customer Four','No 4,Street 4,City 4','+94112890876','customerfour@gmail.com','20000','Cash Payment','No','No');
/*!40000 ALTER TABLE `rented_customers` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `rented_machine_records`
--
LOCK TABLES `rented_machine_records` WRITE;
/*!40000 ALTER TABLE `rented_machine_records` DISABLE KEYS */;
INSERT INTO `rented_machine_records` VALUES ('689012349V','Toshiba','Black','7623120987',200,'Brand New','New Machine','2018-09-21'),('689012349V','Ricoh','Color','8990919489',0,'Brand New','New Machine','2018-10-03'),('689076531V','Toshiba','Black','7624119832',2000,'Good Condition','Used Machine','2018-09-22'),('741258963V','Ricoh','Color','7898521470',0,'Brand New','New Machine','2018-09-05'),('781234098V','Ricoh','Color','8976120985',2000,'Brand New','New Machine','2018-10-03'),('897654123V','Toshiba','Black','7669871230',1000,'Brand New','Used','2018-09-30'),('899076234V','Ricoh','Black','7632109876',1000,'Good Condition','Used Machine','2018-10-01'),('919076723V','Toshiba','Color','8945670981',200,'Good Condition','New','2018-09-05'),('951100374V','Ricoh','Color','8945210981',1000,'Brand New','Brand New Machine','2018-09-24'),('962791790V','Toshiba','Black','7687213456',5000,'Brand New','Used Machine,Available For 2nd User','2018-10-04'),('962890712V','Toshiba','Black','7687172731',0,'Brand New','New Machine','2018-10-04'),('971290456V','Toshiba','Color','7823123456',0,'Brand New ','New Machine','2018-10-02');
/*!40000 ALTER TABLE `rented_machine_records` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!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 */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-10-05 10:10:14
| 94.090909 | 1,670 | 0.708213 |
fd7ff743ba146e71e25174ffdeb47c4af738f883 | 5,548 | lua | Lua | lua/entities/gmod_wire_wheel.lua | dvdvideo1234/wire | ebade4ed012ae5268da9315d99fc2d67db9ab142 | [
"Apache-2.0"
] | 367 | 2015-01-01T19:37:11.000Z | 2022-03-28T16:52:18.000Z | lua/entities/gmod_wire_wheel.lua | viral32111/wiremod | da2cb7333258088f0e5a2b07715c8344ef90d785 | [
"Apache-2.0"
] | 1,381 | 2015-01-01T00:50:19.000Z | 2022-03-29T21:44:45.000Z | lua/entities/gmod_wire_wheel.lua | viral32111/wiremod | da2cb7333258088f0e5a2b07715c8344ef90d785 | [
"Apache-2.0"
] | 370 | 2015-01-04T14:53:50.000Z | 2022-03-15T07:50:19.000Z | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Wheel"
ENT.WireDebugName = "Wheel"
if CLIENT then return end -- No more client
-- As motor constraints can't have their initial torque updated,
-- we always create it with 1000 initial torque (needs to be > friction) and then Scale it with a multiplier
local WHEEL_BASE_TORQUE = 1000
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetUseType( SIMPLE_USE )
self.BaseTorque = 1
self.Breaking = 0
self.SpeedMod = 0
self.Go = 0
self.Inputs = Wire_CreateInputs(self, { "A: Go", "B: Break", "C: SpeedMod" })
end
function ENT:Setup(fwd, bck, stop, torque, direction, axis)
self.fwd = fwd
self.bck = bck
self.stop = stop
if torque then self:SetTorque(math.max(1, torque)) end
if direction then self:SetDirection( direction ) end
if axis then self.Axis = axis end
self:UpdateOverlayText()
end
function ENT:UpdateOverlayText(speed)
local motor = self:GetMotor()
local friction = 0
if IsValid(motor) then friction = motor.friction end
self:SetOverlayText(
"Torque: " .. math.floor( self.BaseTorque ) ..
"\nFriction: " .. friction ..
"\nSpeed: " .. (speed or 0) ..
"\nBreak: " .. self.Breaking ..
"\nSpeedMod: " .. math.floor( self.SpeedMod * 100 ) .. "%" )
end
function ENT:SetAxis( vec )
self.Axis = self:GetPos() + vec * 512
self.Axis = self:NearestPoint( self.Axis )
self.Axis = self:WorldToLocal( self.Axis )
end
function ENT:OnTakeDamage( dmginfo )
self:TakePhysicsDamage( dmginfo )
end
function ENT:SetMotor( Motor )
self.Motor = Motor
self:UpdateOverlayText()
end
function ENT:GetMotor()
if not self.Motor then
self.Motor = constraint.FindConstraintEntity( self, "Motor" )
if not IsValid(self.Motor) then
self.Motor = nil
end
end
return self.Motor
end
function ENT:SetDirection( dir )
self:SetNWInt( 1, dir )
self.direction = dir
end
function ENT:Forward( mul )
if not self:IsValid() then return false end
local Motor = self:GetMotor()
if not IsValid(Motor) then return false end
mul = mul or 1
local mdir = Motor.direction
local Speed = mdir * mul * (self.BaseTorque / WHEEL_BASE_TORQUE) * (1 + self.SpeedMod)
self:UpdateOverlayText(mul ~= 0 and (mdir * mul * (1 + self.SpeedMod)) or 0)
Motor:Fire( "Scale", Speed, 0 )
Motor:GetTable().forcescale = Speed
Motor:Fire( "Activate", "" , 0 )
return true
end
function ENT:TriggerInput(iname, value)
if (iname == "A: Go") then
if ( value == self.fwd ) then self.Go = 1
elseif ( value == self.bck ) then self.Go = -1
elseif ( value == self.stop ) then self.Go =0 end
elseif (iname == "B: Break") then
self.Breaking = value
elseif (iname == "C: SpeedMod") then
self.SpeedMod = (value / 100)
end
self:Forward( self.Go )
end
--[[---------------------------------------------------------
Name: PhysicsUpdate
Desc: happy fun time breaking function
---------------------------------------------------------]]
function ENT:PhysicsUpdate( physobj )
local vel = physobj:GetVelocity()
if (self.Breaking > 0) then -- to prevent badness
if (self.Breaking >= 100) then --100% breaking!!!
vel.x = 0 --full stop!
vel.y = 0
else
vel.x = vel.x * ((100.0 - self.Breaking)/100.0)
vel.y = vel.y * ((100.0 - self.Breaking)/100.0)
end
else
return -- physobj:SetVelocity(physobj:GetVelocity()) will create constant acceleration
end
physobj:SetVelocity(vel)
end
function ENT:SetTorque( torque )
self.BaseTorque = torque
local Motor = self:GetMotor()
if not IsValid(Motor) then return end
Motor:Fire( "Scale", Motor:GetTable().direction * Motor:GetTable().forcescale * (torque / WHEEL_BASE_TORQUE), 0 )
self:UpdateOverlayText()
end
--[[---------------------------------------------------------
Creates the direction arrows on the wheel
---------------------------------------------------------]]
function ENT:DoDirectionEffect()
local Motor = self:GetMotor()
if not IsValid(Motor) then return end
local effectdata = EffectData()
effectdata:SetOrigin( self.Axis )
effectdata:SetEntity( self )
effectdata:SetScale( Motor.direction )
util.Effect( "wheel_indicator", effectdata, true, true )
end
--[[---------------------------------------------------------
Reverse the wheel direction when a player uses the wheel
---------------------------------------------------------]]
function ENT:Use( activator, caller, type, value )
local Motor = self:GetMotor()
local Owner = self:GetPlayer()
if (Motor and (Owner == nil or Owner == activator)) then
if (Motor:GetTable().direction == 1) then
Motor:GetTable().direction = -1
else
Motor:GetTable().direction = 1
end
Motor:Fire( "Scale", Motor:GetTable().direction * Motor:GetTable().forcescale * (self.BaseTorque / WHEEL_BASE_TORQUE), 0 )
self:SetDirection( Motor:GetTable().direction )
self:DoDirectionEffect()
end
end
duplicator.RegisterEntityClass("gmod_wire_wheel", WireLib.MakeWireEnt, "Data", "fwd", "bck", "stop", "BaseTorque", "direction", "Axis")
function ENT:SetWheelBase(Base)
Base:DeleteOnRemove( self )
self.Base = Base
end
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if IsValid(self.Base) then
info.Base = self.Base:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
local Base = GetEntByID(info.Base)
if IsValid(Base) then
self:SetWheelBase(Base)
end
self:UpdateOverlayText()
end
| 27.465347 | 135 | 0.663843 |
fbeb53bb378739ef878c28e952900264d1564620 | 70 | lua | Lua | autoboot_script/spectrum_cass.lua | Bob-Z/RandoMame | 2073d0f1f3de6b7c2f7c090ee79509adb2a1d302 | [
"Apache-2.0"
] | 2 | 2021-11-13T16:28:04.000Z | 2022-02-24T16:56:15.000Z | autoboot_script/spectrum_cass.lua | FollyMaddy/RandoMame | 3c6d1defbce2aeb50b7b83419ade6f9fef280af1 | [
"Apache-2.0"
] | null | null | null | autoboot_script/spectrum_cass.lua | FollyMaddy/RandoMame | 3c6d1defbce2aeb50b7b83419ade6f9fef280af1 | [
"Apache-2.0"
] | 1 | 2021-11-13T16:26:19.000Z | 2021-11-13T16:26:19.000Z | emu.keypost('\nj""\n')
manager.machine.cassettes[":cassette"]:play()
| 17.5 | 45 | 0.685714 |
46a17f399e45748d08337ade00e373d7121b9d53 | 11,243 | swift | Swift | SmartAILibrary/Strategy/GameData/Techs.swift | mrommel/Colony | 7cd79957baffa56e098324eef7ed8a8bf6e33644 | [
"MIT"
] | 9 | 2020-03-10T05:22:09.000Z | 2022-02-08T09:53:43.000Z | SmartAILibrary/Strategy/GameData/Techs.swift | mrommel/Colony | 7cd79957baffa56e098324eef7ed8a8bf6e33644 | [
"MIT"
] | 117 | 2020-07-20T11:28:07.000Z | 2022-03-31T18:51:17.000Z | SmartAILibrary/Strategy/GameData/Techs.swift | mrommel/Colony | 7cd79957baffa56e098324eef7ed8a8bf6e33644 | [
"MIT"
] | null | null | null | //
// Tech.swift
// SmartAILibrary
//
// Created by Michael Rommel on 28.01.20.
// Copyright © 2020 Michael Rommel. All rights reserved.
//
import Foundation
public protocol AbstractTechs: AnyObject, Codable {
var player: AbstractPlayer? { get set }
// techs
func has(tech: TechType) -> Bool
func discover(tech: TechType) throws
func currentScienceProgress() -> Double
func currentScienceTurnsRemaining() -> Int
func lastScienceEarned() -> Double
func needToChooseTech() -> Bool
func possibleTechs() -> [TechType]
func setCurrent(tech: TechType, in gameModel: GameModel?) throws
func currentTech() -> TechType?
func numberOfDiscoveredTechs() -> Int
func add(science: Double)
func chooseNextTech() -> TechType
func checkScienceProgress(in gameModel: GameModel?) throws
// eurekas
func eurekaValue(for techType: TechType) -> Int
func changeEurekaValue(for techType: TechType, change: Int)
func eurekaTriggered(for techType: TechType) -> Bool
func triggerEureka(for techType: TechType, in gameModel: GameModel?)
}
enum TechError: Error {
case cantSelectCurrentTech
case alreadyDiscovered
}
class Techs: AbstractTechs {
enum CodingKeys: CodingKey {
case techs
case currentTech
case lastScienceEarned
case progress
case eurekas
}
// tech tree
var techs: [TechType] = []
// user properties / values
var player: AbstractPlayer?
private var currentTechValue: TechType?
var lastScienceEarnedValue: Double = 1.0
private var progress: WeightedTechList
// heureka
private var eurekas: TechEurekas
// MARK: internal types
class WeightedTechList: WeightedList<TechType> {
override func fill() {
for techType in TechType.all {
self.add(weight: 0, for: techType)
}
}
}
// MARK: constructor
init(player: Player?) {
self.player = player
self.eurekas = TechEurekas()
self.progress = WeightedTechList()
self.progress.fill()
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.techs = try container.decode([TechType].self, forKey: .techs)
self.currentTechValue = try container.decodeIfPresent(TechType.self, forKey: .currentTech)
self.lastScienceEarnedValue = try container.decode(Double.self, forKey: .lastScienceEarned)
self.progress = try container.decode(WeightedTechList.self, forKey: .progress)
self.eurekas = try container.decode(TechEurekas.self, forKey: .eurekas)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.techs, forKey: .techs)
try container.encode(self.currentTechValue, forKey: .currentTech)
try container.encode(self.lastScienceEarnedValue, forKey: .lastScienceEarned)
try container.encode(self.progress, forKey: .progress)
try container.encode(self.eurekas, forKey: .eurekas)
}
public func currentScienceProgress() -> Double {
if let currentTech = self.currentTechValue {
return self.progress.weight(of: currentTech)
}
return 0.0
}
private func turnsRemaining(for techType: TechType) -> Int {
if self.lastScienceEarnedValue > 0.0 {
let cost: Double = Double(techType.cost())
let remaining = cost - self.progress.weight(of: techType)
return Int(remaining / self.lastScienceEarnedValue + 0.5)
}
return 1
}
public func currentScienceTurnsRemaining() -> Int {
if let currentTech = self.currentTechValue {
return self.turnsRemaining(for: currentTech)
}
return 1
}
public func lastScienceEarned() -> Double {
return self.lastScienceEarnedValue
}
// MARK: manage progress
func flavorWeighted(of tech: TechType, for flavor: FlavorType) -> Double {
guard let player = self.player else {
return 0.0
}
return Double(tech.flavorValue(for: flavor) * player.leader.flavor(for: flavor))
}
func chooseNextTech() -> TechType {
let weightedTechs: WeightedTechList = WeightedTechList()
let possibleTechsList = self.possibleTechs()
weightedTechs.items.removeAll()
for possibleTech in possibleTechsList {
var weightByFlavor = 0.0
// weight of current tech
for flavor in FlavorType.all {
weightByFlavor += flavorWeighted(of: possibleTech, for: flavor)
}
// add techs that can be research with this tech, but only with a little less weight
for activatedTech in possibleTech.leadsTo() {
for flavor in FlavorType.all {
weightByFlavor += (flavorWeighted(of: activatedTech, for: flavor) * 0.75)
}
for secondActivatedTech in activatedTech.leadsTo() {
for flavor in FlavorType.all {
weightByFlavor += (flavorWeighted(of: secondActivatedTech, for: flavor) * 0.5)
}
for thirdActivatedTech in secondActivatedTech.leadsTo() {
for flavor in FlavorType.all {
weightByFlavor += (flavorWeighted(of: thirdActivatedTech, for: flavor) * 0.25)
}
}
}
}
// revalue based on cost / number of turns
let numberOfTurnsLeft = self.turnsRemaining(for: possibleTech)
let additionalTurnCostFactor = 0.015 * Double(numberOfTurnsLeft)
let totalCostFactor = 0.15 + additionalTurnCostFactor
let weightDivisor = pow(Double(numberOfTurnsLeft), totalCostFactor)
// modify weight
weightByFlavor = Double(weightByFlavor) / weightDivisor
weightedTechs.add(weight: weightByFlavor, for: possibleTech)
}
// select one
let numberOfSelectable = min(3, possibleTechsList.count)
let selectedIndex = Int.random(number: numberOfSelectable)
let weightedTechsArray: [(TechType, Double)] = weightedTechs.items.sortedByValue.reversed()
let selectedTech = weightedTechsArray[selectedIndex].0
return selectedTech
}
// MARK: manage tech tree
func has(tech: TechType) -> Bool {
return self.techs.contains(tech)
}
func discover(tech: TechType) throws {
if self.techs.contains(tech) {
throw TechError.alreadyDiscovered
}
self.techs.append(tech)
}
func needToChooseTech() -> Bool {
return self.currentTechValue == nil
}
func currentTech() -> TechType? {
return self.currentTechValue
}
func eurekaValue(for techType: TechType) -> Int {
return Int(self.eurekas.eurekaCounter.weight(of: techType))
}
func changeEurekaValue(for techType: TechType, change: Int) {
self.eurekas.eurekaCounter.add(weight: change, for: techType)
}
func eurekaTriggered(for techType: TechType) -> Bool {
return self.eurekas.eurakaTrigger.triggered(for: techType)
}
func triggerEureka(for techType: TechType, in gameModel: GameModel?) {
guard let player = self.player else {
fatalError("Can't trigger eurake - no player present")
}
// check if eureka is still needed
if self.has(tech: techType) {
return
}
// check if eureka is already active
if self.eurekaTriggered(for: techType) {
return
}
self.eurekas.eurakaTrigger.trigger(for: techType)
// update progress
self.progress.add(weight: Double(techType.cost()) * 0.5, for: techType)
// trigger event to user
if player.isHuman() {
gameModel?.userInterface?.showPopup(popupType: .eurekaTechActivated(tech: techType))
}
}
func numberOfDiscoveredTechs() -> Int {
var number = 0
for tech in TechType.all {
if self.has(tech: tech) {
number += 1
}
}
return number
}
func setCurrent(tech: TechType, in gameModel: GameModel?) throws {
guard let gameModel = gameModel else {
fatalError("cant get gameModel")
}
guard let player = self.player else {
fatalError("Can't add science - no player present")
}
if !self.possibleTechs().contains(tech) {
throw TechError.cantSelectCurrentTech
}
self.currentTechValue = tech
if player.isHuman() {
gameModel.userInterface?.select(tech: tech)
}
}
func possibleTechs() -> [TechType] {
var returnTechs: [TechType] = []
for tech in TechType.all {
if self.has(tech: tech) {
continue
}
var allRequiredPresent = true
for req in tech.required() {
if !self.has(tech: req) {
allRequiredPresent = false
}
}
if allRequiredPresent {
returnTechs.append(tech)
}
}
return returnTechs
}
func add(science: Double) {
if let currentTech = self.currentTechValue {
self.progress.add(weight: science, for: currentTech)
}
self.lastScienceEarnedValue = science
}
func checkScienceProgress(in gameModel: GameModel?) throws {
guard let player = self.player else {
fatalError("Can't add science - no player present")
}
guard let currentTech = self.currentTechValue else {
if !player.isHuman() {
let bestTech = chooseNextTech()
try self.setCurrent(tech: bestTech, in: gameModel)
}
return
}
if self.currentScienceProgress() >= Double(currentTech.cost()) {
do {
try self.discover(tech: currentTech)
// trigger event to user
if player.isHuman() {
gameModel?.userInterface?.showPopup(popupType: .techDiscovered(tech: currentTech))
}
// enter era
if currentTech.era() > player.currentEra() {
gameModel?.enter(era: currentTech.era(), for: player)
if player.isHuman() {
gameModel?.userInterface?.showPopup(popupType: .eraEntered(era: currentTech.era()))
}
player.set(era: currentTech.era())
}
self.currentTechValue = nil
if player.isHuman() {
self.player?.notifications()?.add(notification: .techNeeded)
}
} catch {
fatalError("Can't discover science - already discovered")
}
}
}
}
| 27.355231 | 107 | 0.594948 |
de7058bf51cb70584df525ebba1f5acfb94c68c6 | 244 | ps1 | PowerShell | Chapter23/1.4.3.Set-StrictMode_InvalidVariableName_Error.ps1 | wagnerhsu/packt-Mastering-Windows-PowerShell-Scripting-Fourth-Edition | be9f5cad2bf28de7c0a250590c65b72994800aeb | [
"MIT"
] | 27 | 2020-04-21T13:28:29.000Z | 2022-03-09T12:19:24.000Z | Chapter23/1.4.3.Set-StrictMode_InvalidVariableName_Error.ps1 | wagnerhsu/packt-Mastering-Windows-PowerShell-Scripting-Fourth-Edition | be9f5cad2bf28de7c0a250590c65b72994800aeb | [
"MIT"
] | null | null | null | Chapter23/1.4.3.Set-StrictMode_InvalidVariableName_Error.ps1 | wagnerhsu/packt-Mastering-Windows-PowerShell-Scripting-Fourth-Edition | be9f5cad2bf28de7c0a250590c65b72994800aeb | [
"MIT"
] | 15 | 2020-05-03T01:24:33.000Z | 2022-01-26T04:57:23.000Z | # Requires 1.4.2
Test-StrictMode
# Expects error:
#
# InvalidOperation:
# Line |
# 5 | foreach ($name in $naems) {
# | ~~~~~~
# | The variable '$naems' cannot be retrieved because it has not been set.
| 20.333333 | 79 | 0.536885 |
40c8428f4ca671de824dc675040f42550d196432 | 7,886 | py | Python | nda.py | Bangsat-XD/JANDAKU | 0e386e161a6718b866f1fccbb0759cc4df9c64f5 | [
"Apache-2.0"
] | 2 | 2021-11-17T03:35:03.000Z | 2021-12-08T06:00:31.000Z | nda.py | Bangsat-XD/JANDAKU | 0e386e161a6718b866f1fccbb0759cc4df9c64f5 | [
"Apache-2.0"
] | null | null | null | nda.py | Bangsat-XD/JANDAKU | 0e386e161a6718b866f1fccbb0759cc4df9c64f5 | [
"Apache-2.0"
] | 2 | 2021-11-05T18:07:48.000Z | 2022-02-24T21:25:07.000Z | ''' ___ ____ ___ ____ ____ ____ ____ ____ ____ ___ ____
|__] |___ |__] |__| [__ |__/ |___ | | | | \ |___
|__] |___ |__] | | ___] | \ |___ |___ |__| |__/ |___ '''
#!/bin/usr/python
from multiprocessing.pool import ThreadPool
from getpass import getpass
import os, urllib.request, sys, json, time, hashlib, random, shutil, re, threading
from bs4 import BeautifulSoup
try:
import mechanize
import requests
except ImportError:
os.system('pip install mechanize')
os.system('pip install requests')
if sys.version[0] == '2':
print(green('[INFO]'),(k),'Ini Menggunakan Python3!')
sys.exit(1)
sleep = time.sleep
h = '\x1b[32m'
r = '\x1b[1;91m'
k = '\x1b[1;97m'
n = '\033[94m'
W = "\033[0m"
G = '\033[32;1m'
R = '\033[31;1m'
time.sleep(1)
back = 0
lol = []
idd = []
threads = []
berhasil = []
cekpoint = []
gagal = []
idb = []
listgrup = []
id = []
ibb = []
s = (' Thanks to : Indo'+n+'⟬'+R+'X'+n+'⟭'+k+'ploit'+r+' and '+k+'Python Indonesia')
t = (' Token')
m = (' Multibruteforce Facebook')
user_agent_list = [
#Chrome
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
#Firefox
'Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)',
'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)',
'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)',
]
proxies_list = [
'http://10.10.1.10:3128',
'http://77.232.139.200:8080',
'http://78.111.125.146:8080',
'http://77.239.133.146:3128',
'http://74.116.59.8:53281',
'http://67.53.121.67:8080',
'http://67.78.143.182:8080',
'http://62.64.111.42:53281',
'http://62.210.251.74:3128',
'http://62.210.105.103:3128',
'http://5.189.133.231:80',
'http://46.101.78.9:8080',
'http://45.55.86.49:8080',
'http://40.87.66.157:80',
'http://45.55.27.246:8080',
'http://45.55.27.246:80',
'http://41.164.32.58:8080',
'http://45.125.119.62:8080',
'http://37.187.116.199:80',
'http://43.250.80.226:80',
'http://43.241.130.242:8080',
'http://38.64.129.242:8080',
'http://41.203.183.50:8080',
'http://36.85.90.8:8080',
'http://36.75.128.3:80',
'http://36.81.255.73:8080',
'http://36.72.127.182:8080',
'http://36.67.230.209:8080',
'http://35.198.198.12:8080',
'http://35.196.159.241:8080',
'http://35.196.159.241:80',
'http://27.122.224.183:80',
'http://223.206.114.195:8080',
'http://221.120.214.174:8080',
'http://223.205.121.223:8080',
'http://222.124.30.138:80',
'http://222.165.205.204:8080',
'http://217.61.15.26:80',
'http://217.29.28.183:8080',
'http://217.121.243.43:8080',
'http://213.47.184.186:8080',
'http://207.148.17.223:8080',
'http://210.213.226.3:8080',
'http://202.70.80.233:8080',
]
sleep(0.2)
os.system('clear')
def tik(s):
for c in s + '\n':
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(random.random() * 0.1)
print(k)
def logo():
os.system('clear')
print(R,' ╔═╗ ╔═╗╔╗')
print(R,' ║╔╝ ║╔╝║║')
print(R,' ╔╝╚╗╔══╗╔═╗╔══╗╔══╗ ╔╝╚╗║╚═╗',G,'Author : As'+R+'_'+G+'Min')
print(R,' ╚╗╔╝║╔╗║║╔╝║╔═╝║║═╣ ╚╗╔╝║╔╗║',G,'Github : asmin19',k)
print(' ║║ ║╚╝║║║ ║╚═╗║║═╣ ║║ ║╚╝║',G,'Version : 3.0',k)
print(' ╚╝ ╚══╝╚╝ ╚══╝╚══╝ ╚╝ ╚══╝')
print(r+'###################################################'+k)
a = ('===================================================')
def about():
logo()
print('')
tik(s)
print('')
print(R+'...................[INFORMATION]...................'+k)
print('')
print('Creator Asmin')
print('About this tools All about hacking facebook accounts')
print('Version 3.0')
print('Special thanks to '+G+' Khoirul Amsori'+k+' and'+G+' Ez Nhana Hna'+k)
print('Code name As'+r+'_'+k+'Min')
print('Team Buton '+R+'Sec'+k+'.')
print('E-mail asmin987asmin@gmail.com')
print('Github asmin19')
print('Telegram @asmin19')
print('WhatsApp +62 852-6834-5036')
print('Date 20:15 13-07-2019')
print('Region Baubau,Sulawesi Tenggara, Indonesia')
print('Support Password xxx123, xxx12345, xxx12, xxx, birthday, sayang, minions, number, and many more')
print('New Features You can crack with'+R+' Super-Multibruteforce'+k+' from friendlist your friends')
print(n+'Coming Soon Checker IG')
print('')
tik(G+'* contact author to '+R+'BUY'+G+' the script ')
print(k)
input('[+] Press [Enter] to return ')
menu()
def menu():
print(k)
logo()
print(s)
print(a)
print(''' [ 01 ] Create Wordlist
[ 02 ] Bruteforce
[ 03 ] Multibruteforce Facebook
[ 04 ] Friends Information
[ 05 ] Token
[ 06 ] About
[ 00 ] Exit
''')
try:
asm = input(n+'[#] Asmin'+k+'/' + r+'~' + k + '> ')
if asm in ['']:
tik(R+'[!] Please enter your choice ')
input('[+] Press [Enter] to return ')
menu()
elif asm in ['1','01']:
about()
elif asm in ['2','02']:
about()
elif asm in ['3','03']:
about()
elif asm in ['4','04']:
about()
elif asm in ['5','05']:
about()
elif asm in ['6','06']:
about()
elif asm in ['0','00']:
exit()
else:
tik(R+'[!] Wrong input')
input(n+'[+] Press [Enter] to return ')
os.system('clear')
logo()
print(s)
print(a)
menu()
except EOFError:
exit()
except KeyboardInterrupt:
exit()
menu()
| 37.732057 | 134 | 0.531195 |
63cc73b84788c619938dd91ad0255a6172a86494 | 1,577 | swift | Swift | Weibo/Weibo/Home/Story/WBStoryView.swift | fanyu/WeiboSwiftUI | 477b01a013b7396df0737b60f4e6ebfdbe3d627e | [
"MIT"
] | null | null | null | Weibo/Weibo/Home/Story/WBStoryView.swift | fanyu/WeiboSwiftUI | 477b01a013b7396df0737b60f4e6ebfdbe3d627e | [
"MIT"
] | null | null | null | Weibo/Weibo/Home/Story/WBStoryView.swift | fanyu/WeiboSwiftUI | 477b01a013b7396df0737b60f4e6ebfdbe3d627e | [
"MIT"
] | null | null | null | //
// WBStoryView.swift
// SwiftUIHub
//
// Created by Yu Fan on 2019/6/24.
// Copyright © 2019 Yu Fan. All rights reserved.
//
import SwiftUI
struct WBStoryView : View {
@ObjectBinding var weiboStory: WeiboStore
var body: some View {
ScrollView {
HStack {
ForEach(self.weiboStory.storys) { story in
WBStoryUserView(user: story)
}
}
}
}
}
struct WBStoryUserView : View {
private let avatarSize: CGFloat = 50
private let iconSize: CGFloat = 16
var user: WBStoryUser
var body: some View {
VStack {
ZStack(alignment: .bottomTrailing) {
// avatar
Image(user.avatar)
.frame(width: avatarSize, height: avatarSize)
.clipShape(Circle())
.background(Color.white)
.padding(2)
.border(Color.red, width: 1, cornerRadius: (avatarSize+2) / 2)
// icon
Image(user.icon)
.frame(width: iconSize, height: iconSize)
}
// name
Text(user.name)
.foregroundColor(Color.primary)
.font(Font.system(.body, design: .default))
.lineLimit(1)
}
.frame(width: 80, height: 120)
}
}
#if DEBUG
struct WBStoryView_Previews : PreviewProvider {
static var previews: some View {
WBStoryView(weiboStory: WeiboStore())
}
}
#endif
| 23.537313 | 82 | 0.506658 |
04f3316a7ea6269186edad082076fd6c08ee049a | 572 | java | Java | src/main/java/com/christophecvb/elitedangerous/events/fleetcarriers/CarrierDepositFuelEvent.java | ChristopheCVB/EliteDangerousAPI | d88ce9607a05859f41638e5d5dba9598b053eb5e | [
"MIT"
] | 9 | 2020-10-10T13:53:59.000Z | 2022-02-20T19:12:45.000Z | src/main/java/com/christophecvb/elitedangerous/events/fleetcarriers/CarrierDepositFuelEvent.java | ChristopheCVB/EliteDangerousAPI | d88ce9607a05859f41638e5d5dba9598b053eb5e | [
"MIT"
] | 40 | 2020-10-10T18:23:48.000Z | 2022-03-03T13:10:48.000Z | src/main/java/com/christophecvb/elitedangerous/events/fleetcarriers/CarrierDepositFuelEvent.java | ChristopheCVB/EliteDangerousAPI | d88ce9607a05859f41638e5d5dba9598b053eb5e | [
"MIT"
] | 2 | 2020-10-10T14:31:11.000Z | 2022-02-21T19:29:53.000Z | package com.christophecvb.elitedangerous.events.fleetcarriers;
import com.christophecvb.elitedangerous.events.Event;
public class CarrierDepositFuelEvent extends Event {
public Integer total, amount;
public Long carrierID;
public interface Listener extends Event.Listener {
@Override
default <T extends Event> void onTriggered(T event) {
this.onCarrierDepositFuelEventTriggered((CarrierDepositFuelEvent) event);
}
void onCarrierDepositFuelEventTriggered(CarrierDepositFuelEvent carrierDepositFuelEvent);
}
}
| 31.777778 | 97 | 0.758741 |
fcb4111ce22f87ddedf30e1a8592ee0531a0c673 | 1,389 | sql | SQL | cmn-data-svc-server/db-scripts/cmn-data-svc-base-mysql.sql | zhaojizhuang4/common-dataservice | 03961b462961bddadc041f258367e9c053257a05 | [
"Apache-2.0"
] | null | null | null | cmn-data-svc-server/db-scripts/cmn-data-svc-base-mysql.sql | zhaojizhuang4/common-dataservice | 03961b462961bddadc041f258367e9c053257a05 | [
"Apache-2.0"
] | 1 | 2021-02-10T14:02:44.000Z | 2021-02-10T14:02:44.000Z | cmn-data-svc/cmn-data-svc-server/db-scripts/cmn-data-svc-base-mysql.sql | ai4eu/common-dataservice | 2cd2e0b48771549f54f2f30bfb65db01be62754f | [
"Apache-2.0"
] | 6 | 2018-05-08T11:36:05.000Z | 2021-01-28T14:21:53.000Z | -- ===============LICENSE_START=======================================================
-- Acumos Apache-2.0
-- ===================================================================================
-- Copyright (C) 2017-2018 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
-- ===================================================================================
-- This Acumos software file is distributed by AT&T and Tech Mahindra
-- under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- This file 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.
-- ===============LICENSE_END=========================================================
-- This script creates a database and two user entries for that database.
-- Replace CAPITALIZED TOKENS for other databases, users, passwords, etc.
drop database if exists CDS;
create database CDS;
create user 'CDS_USER'@'localhost' identified by 'CDS_PASS';
grant all on CDS.* to 'CDS_USER'@'localhost';
create user 'CCDS_USER'@'%' identified by 'CDS_PASS';
grant all on CDS.* to 'CDS_USER'@'%';
| 51.444444 | 91 | 0.571634 |
3d3bcf99475027804349c3cd0c03701f1a77c41a | 9,684 | rs | Rust | src/days/day16.rs | Jazzinghen/2021-AoC | 13b9372ad081da3cf4e2bcb8af7178bdd2c3816a | [
"MIT"
] | null | null | null | src/days/day16.rs | Jazzinghen/2021-AoC | 13b9372ad081da3cf4e2bcb8af7178bdd2c3816a | [
"MIT"
] | null | null | null | src/days/day16.rs | Jazzinghen/2021-AoC | 13b9372ad081da3cf4e2bcb8af7178bdd2c3816a | [
"MIT"
] | null | null | null | use std::iter::FromIterator;
use itertools::Itertools;
#[derive(Eq, PartialEq, Debug)]
enum Packet {
Literal(LiteralPayload),
Operator(OperatorPayload),
}
impl Packet {
pub fn get_size(&self) -> usize {
match self {
Packet::Literal(lit) => lit.size,
Packet::Operator(op) => op.size,
}
}
pub fn get_total_version(&self) -> u64 {
match self {
Packet::Literal(lit) => lit.version.into(),
Packet::Operator(op) => op.total_version,
}
}
pub fn get_value(&self) -> u64 {
match self {
Packet::Literal(lit) => lit.value,
Packet::Operator(op) => op.value,
}
}
}
#[derive(Eq, PartialEq, Debug)]
struct LiteralPayload {
version: u8,
value: u64,
size: usize,
}
#[derive(Eq, PartialEq, Debug)]
struct OperatorPayload {
version: u8,
value: u64,
total_version: u64,
size: usize,
}
fn hex_payload_to_binary(input: &str) -> String {
let mut binary_payload: String = String::new();
for c in input
.to_uppercase()
.chars()
.take_while(|c| !c.is_whitespace())
{
let binary = match c {
'0' => "0000",
'1' => "0001",
'2' => "0010",
'3' => "0011",
'4' => "0100",
'5' => "0101",
'6' => "0110",
'7' => "0111",
'8' => "1000",
'9' => "1001",
'A' => "1010",
'B' => "1011",
'C' => "1100",
'D' => "1101",
'E' => "1110",
'F' => "1111",
_ => {
panic!("Provided a value that's not an hexadecimal digit")
}
};
binary_payload.push_str(binary);
}
binary_payload
}
fn parse_packet(input: &str) -> Packet {
let type_string: String = input.chars().skip(3).take(3).collect();
let type_id = u8::from_str_radix(&type_string, 2).unwrap();
if type_id == 4u8 {
Packet::Literal(parse_literal(input))
} else {
Packet::Operator(parse_operator(input))
}
}
fn parse_literal(input: &str) -> LiteralPayload {
let version_string: String = input.chars().take(3).collect();
let version = u8::from_str_radix(&version_string, 2).unwrap();
let mut final_value = 0u64;
let mut last_chunk = 0usize;
for (chunk_idx, chunk) in input[6..]
.chars()
.chunks(5)
.into_iter()
.map(String::from_iter)
.enumerate()
{
let chunk_value = u64::from_str_radix(&chunk, 2).unwrap();
let value: u64 = chunk_value & !0b10000;
final_value <<= 4;
final_value += value;
if chunk_value & 0b10000 == 0 {
last_chunk = chunk_idx + 1;
break;
}
}
LiteralPayload {
version,
value: final_value,
size: 6usize + last_chunk * 5usize,
}
}
fn parse_operator(input: &str) -> OperatorPayload {
let version_string: String = input.chars().take(3).collect();
let version = u8::from_str_radix(&version_string, 2).unwrap();
let actual_input = &input[6..];
let size_in_chars = actual_input.starts_with('0');
let size_displacement = if size_in_chars { 15usize } else { 11usize };
let mut remaining_data =
usize::from_str_radix(&actual_input[1..size_displacement + 1], 2).unwrap();
let mut sub_packets: Vec<Packet> = Vec::new();
while remaining_data > 0usize {
let sub_size: usize = sub_packets.iter().map(Packet::get_size).sum();
let sub_start = sub_size + size_displacement;
let sub_package = parse_packet(&actual_input[sub_start + 1..]);
remaining_data -= if size_in_chars {
sub_package.get_size()
} else {
1
};
sub_packets.push(sub_package);
}
let total_version: u64 = sub_packets
.iter()
.map(Packet::get_total_version)
.sum::<u64>()
+ u64::from(version);
let size: usize =
sub_packets.iter().map(Packet::get_size).sum::<usize>() + size_displacement + 7usize;
let op_string: String = input.chars().skip(3).take(3).collect();
let op_id = u8::from_str_radix(&op_string, 2).unwrap();
let value: u64 = match op_id {
0u8 => sub_packets.iter().map(Packet::get_value).sum(),
1u8 => sub_packets.iter().map(Packet::get_value).product(),
2u8 => sub_packets.iter().map(Packet::get_value).min().unwrap(),
3u8 => sub_packets.iter().map(Packet::get_value).max().unwrap(),
5u8 => {
if sub_packets[0].get_value() > sub_packets[1].get_value() {
1u64
} else {
0u64
}
}
6u8 => {
if sub_packets[0].get_value() < sub_packets[1].get_value() {
1u64
} else {
0u64
}
}
7u8 => {
if sub_packets[0].get_value() == sub_packets[1].get_value() {
1u64
} else {
0u64
}
}
_ => {
panic!("Invalid operation id {}", op_id)
}
};
OperatorPayload {
version,
value,
total_version,
size,
}
}
pub fn part1(input: &str) {
let input_binary = hex_payload_to_binary(input);
let parsed_package = parse_packet(&input_binary);
println!(
"Sum of all the version numbers: {}",
parsed_package.get_total_version()
);
}
pub fn part2(input: &str) {
let input_binary = hex_payload_to_binary(input);
let parsed_package = parse_packet(&input_binary);
println!("Computed value: {}", parsed_package.get_value());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_conversion() {
let input_string = "D2FE28";
assert_eq!(
hex_payload_to_binary(input_string),
"110100101111111000101000"
)
}
#[test]
fn literal_parse() {
let input_string = "D2FE28";
let input_binary = hex_payload_to_binary(input_string);
let comparison_packet = Packet::Literal(LiteralPayload {
version: 6u8,
value: 2021u64,
size: 21usize,
});
assert_eq!(comparison_packet, parse_packet(&input_binary));
}
#[test]
fn basic_operator_char_size() {
let input_binary = hex_payload_to_binary("38006F45291200");
// 001 110 0 000000000011011 110 100 01010 010 100 10001 00100 0000000
// VVV TTT I LLLLLLLLLLLLLLL AAA AAA AAAAA BBB BBB BBBBB BBBBB XXXXXXX
let comparison_operator = Packet::Operator(OperatorPayload {
version: 1u8,
total_version: 9u64,
value: 1u64,
size: 49usize,
});
assert_eq!(parse_packet(&input_binary), comparison_operator);
}
#[test]
fn basic_operator_sub_size() {
let input_binary = hex_payload_to_binary("EE00D40C823060");
// 111 011 1 00000000011 010 100 00001 100 100 00010 001 100 00011 00000
// VVV TTT I LLLLLLLLLLL AAA AAA AAAAA BBB BBB BBBBB CCC CCC CCCCC XXXXX
let comparison_operator = Packet::Operator(OperatorPayload {
version: 7u8,
total_version: 14u64,
value: 3u64,
size: 51usize,
});
assert_eq!(parse_packet(&input_binary), comparison_operator);
}
#[test]
fn version_sum() {
let input_binary = hex_payload_to_binary("8A004A801A8002F478");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_total_version(), 16u64);
let input_binary = hex_payload_to_binary("620080001611562C8802118E34");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_total_version(), 12u64);
let input_binary = hex_payload_to_binary("C0015000016115A2E0802F182340");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_total_version(), 23u64);
let input_binary = hex_payload_to_binary("A0016C880162017C3686B18A3D4780");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_total_version(), 31u64);
}
#[test]
fn compute_operators_results() {
let input_binary = hex_payload_to_binary("C200B40A82");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_value(), 3u64);
let input_binary = hex_payload_to_binary("04005AC33890");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_value(), 54u64);
let input_binary = hex_payload_to_binary("880086C3E88112");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_value(), 7u64);
let input_binary = hex_payload_to_binary("CE00C43D881120");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_value(), 9u64);
let input_binary = hex_payload_to_binary("D8005AC2A8F0");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_value(), 1u64);
let input_binary = hex_payload_to_binary("F600BC2D8F");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_value(), 0u64);
let input_binary = hex_payload_to_binary("9C005AC2F8F0");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_value(), 0u64);
let input_binary = hex_payload_to_binary("9C0141080250320F1802104A08");
let operator = parse_packet(&input_binary);
assert_eq!(operator.get_value(), 1u64);
}
}
| 28.315789 | 93 | 0.580235 |
a58fe4129a4efe49de4a49978f5252852651cf14 | 12,323 | dart | Dart | lib/Conference.dart | SariskaIO/sariska-flutter-sdk-releases | b418715da5751d803811def586c2867de87532f7 | [
"MIT"
] | null | null | null | lib/Conference.dart | SariskaIO/sariska-flutter-sdk-releases | b418715da5751d803811def586c2867de87532f7 | [
"MIT"
] | 1 | 2021-06-08T07:31:59.000Z | 2021-06-08T07:31:59.000Z | lib/Conference.dart | SariskaIO/sariska-flutter-sdk-releases | b418715da5751d803811def586c2867de87532f7 | [
"MIT"
] | null | null | null | import 'dart:async';
import 'package:flutter/services.dart';
import 'JitsiLocalTrack.dart';
import 'JitsiRemoteTrack.dart';
import 'Participant.dart';
typedef void ConferenceCallbackParam0();
typedef void ConferenceCallbackParam1<W>(W w);
typedef void ConferenceCallbackParam2<W, X>(W w, X x);
typedef void ConferenceCallbackParam3<W, X, Y>(W w, X x, Y y);
typedef void ConferenceCallbackParam4<W, X, Y, Z>(W w, X x, Y y, Z z);
class ConferenceBinding<T> {
String event;
T callback;
ConferenceBinding(this.event, T this.callback) {
this.event = event;
this.callback = callback;
}
String getEvent() {
return this.event;
}
T getCallback() {
return this.callback;
}
}
class Conference {
static var _bindings = <ConferenceBinding>[];
static var remoteTracks = <JitsiRemoteTrack>[];
static var localTracks = <JitsiLocalTrack>[];
static var participants = <Participant>[];
static const MethodChannel _methodChannel = MethodChannel('conference');
static const EventChannel _eventChannel = EventChannel('conference/events');
static String userId = '';
static String role = '';
static bool hidden = false;
static bool dtmf = false;
static String name = '';
static String email = '';
static String avatar = '';
Conference() {
_invokeMethod('createConference');
}
Conference._() {
_eventChannel.receiveBroadcastStream().listen((event) {
final eventMap = Map<String, dynamic>.from(event);
final action = eventMap['action'] as String;
final m = Map<String, dynamic>.from(eventMap['m']);
for (var i = 0; i < _bindings.length; i++) {
if (_bindings[i].getEvent() == action) {
switch (action) {
case "CONFERENCE_LEFT":
case "CONFERENCE_FAILED":
case "CONFERENCE_ERROR":
case "BEFORE_STATISTICS_DISPOSED":
case "TALK_WHILE_MUTED":
case "NO_AUDIO_INPUT":
case "AUDIO_INPUT_STATE_CHANGE":
case "NOISY_MIC":
(_bindings[i].getCallback() as ConferenceCallbackParam0)();
break;
case "CONFERENCE_JOINED":
userId = m["userId"];
role = m["role"];
hidden = m["hidden"];
dtmf = m["dtmf"];
name = m["name"];
email = m["email"];
avatar = m["avatar"];
(_bindings[i].getCallback() as ConferenceCallbackParam0)();
break;
case "LOCAL_STATS_UPDATED":
(_bindings[i].getCallback()
as ConferenceCallbackParam1)(m["statsObject"]);
break;
case 'DOMINANT_SPEAKER_CHANGED':
(_bindings[i].getCallback() as ConferenceCallbackParam1)(m["id"]);
break;
case 'SUBJECT_CHANGED':
(_bindings[i].getCallback()
as ConferenceCallbackParam1)(m["subject"]);
break;
case 'CONFERENCE_UNIQUE_ID_SET':
(_bindings[i].getCallback()
as ConferenceCallbackParam1)(m["meetingId"]);
break;
case 'DTMF_SUPPORT_CHANGED':
dtmf = m["support"];
(_bindings[i].getCallback()
as ConferenceCallbackParam1)(m["support"]);
break;
case 'TRACK_ADDED':
JitsiRemoteTrack track = new JitsiRemoteTrack(m);
remoteTracks.add(track);
(_bindings[i].getCallback() as ConferenceCallbackParam1)(track);
break;
case 'TRACK_REMOVED':
JitsiRemoteTrack track =
remoteTracks.firstWhere((t) => t.id == m["id"]);
(_bindings[i].getCallback() as ConferenceCallbackParam1)(track);
break;
case 'TRACK_MUTE_CHANGED':
JitsiRemoteTrack track =
remoteTracks.firstWhere((t) => t.id == m["id"]);
track.setMuted(m["muted"]);
(_bindings[i].getCallback() as ConferenceCallbackParam1)(track);
break;
case 'TRACK_AUDIO_LEVEL_CHANGED':
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["id"], m["audioLevel"]);
break;
case 'USER_JOINED':
Participant participant = new Participant(m);
participants.add(participant);
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["id"], participant);
break;
case 'USER_LEFT':
Participant participant =
participants.firstWhere((p) => p.id == m["id"]);
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["id"], participant);
break;
case 'DISPLAY_NAME_CHANGED':
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["id"], m["displayName"]);
break;
case "LAST_N_ENDPOINTS_CHANGED":
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["enterArrayIds"], m["leavingArrayIds"]);
break;
case "USER_ROLE_CHANGED":
role = m["role"];
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["id"], m["role"]);
break;
case "USER_STATUS_CHANGED":
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["id"], m["status"]);
break;
case "KICKED":
Participant participant = participants
.firstWhere((p) => p.id == m["participant"]["id"]);
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
participant, m["reason"]);
break;
case "START_MUTED_POLICY_CHANGED":
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["audio"], m["video"]);
break;
case "STARTED_MUTED":
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["audio"], m["video"]);
break;
case "ENDPOINT_MESSAGE_RECEIVED":
Participant participant = participants
.firstWhere((p) => p.id == m["participant"]["id"]);
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
participant, m["message"]);
break;
case "REMOTE_STATS_UPDATED":
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["id"], m["statsObject"]);
break;
case "AUTH_STATUS_CHANGED":
(_bindings[i].getCallback() as ConferenceCallbackParam2)(
m["isAuthEnabled"], m["authIdentity"]);
break;
case "MESSAGE_RECEIVED":
(_bindings[i].getCallback() as ConferenceCallbackParam3)(
m["id"], m["text"], m["ts"]);
break;
case "PARTICIPANT_KICKED":
Participant kicked = participants
.firstWhere((p) => p.id == m["kickedParticipant"]["id"]);
Participant actor = participants
.firstWhere((p) => p.id == m["actorParticipant"]["id"]);
(_bindings[i].getCallback() as ConferenceCallbackParam3)(
actor, kicked, m["reason"]);
break;
default:
}
}
}
});
}
static Future<T?> _invokeMethod<T>(String method,
[Map<String, dynamic>? arguments]) {
return _methodChannel.invokeMethod(method, arguments);
}
bool isHidden() {
return hidden;
}
bool isDTMFSupported() {
return dtmf;
}
String getUserId() {
return userId;
}
String getUserRole() {
return role;
}
String getUserEmail() {
return email;
}
String getUserAvatar() {
return avatar;
}
String getUserName() {
return userId;
}
void join([String password = '']) {
if (password != '') {
_invokeMethod('join', {'password': password});
} else {
_invokeMethod('join');
}
}
void grantOwner(String id) {
_invokeMethod('grantOwner', {'id': id});
}
void setStartMutedPolicy(Map<String, bool> policy) {
_invokeMethod('setStartMutedPolicy', {'policy': policy});
}
void setReceiverVideoConstraint(int resolution) {
_invokeMethod('setReceiverVideoConstraint', {'resolution': resolution});
}
void setSenderVideoConstraint(int resolution) {
_invokeMethod('setSenderVideoConstraint', {'resolution': resolution});
}
void sendMessage(String message, [String to = '']) {
if (to != '') {
_invokeMethod('sendMessage', {message: 'message', 'to': to});
} else {
_invokeMethod('sendMessage', {message: 'message'});
}
}
void setLastN(int num) {
_invokeMethod('setLastN', {'num': num});
}
void muteParticipant(String id, String mediaType) {
if (mediaType != "") {
_invokeMethod('muteParticipant', {'id': id, 'mediaType': mediaType});
} else {
_invokeMethod('muteParticipant', {'id': id});
}
}
void setDisplayName(String displayName) {
_invokeMethod('displayName', {'displayName': displayName});
}
void addTrack(JitsiLocalTrack track) {
_invokeMethod('addTrack', {'trackId': track.getId()});
}
void removeTrack(JitsiLocalTrack track) {
_invokeMethod('removeTrack', {'trackId': track.getId()});
}
void replaceTrack(JitsiLocalTrack oldTrack, JitsiLocalTrack newTrack) {
_invokeMethod('replaceTrack',
{'oldTrackId': oldTrack.getId(), 'newTrackId': newTrack.getId()});
}
void lock(String password) {
_invokeMethod('lock', {'password': password});
}
void setSubject(String subject) {
_invokeMethod('setSubject', {'subject': subject});
}
void unlock() {
_invokeMethod('unlock');
}
void kickParticipant(String id) {
_invokeMethod('kickParticipant', {'id': id});
}
void pinParticipant(String id) {
_invokeMethod('pinParticipant', {'id': id});
}
void selectParticipant(String id) {
_invokeMethod('selectParticipant', {'id': id});
}
void startTranscriber() {
_invokeMethod('startTranscriber');
}
void stopTranscriber() {
_invokeMethod('stopTranscriber');
}
void revokeOwner(String id) {
_invokeMethod('startRecording', {'id': id});
}
void startRecording(Map<String, dynamic> options) {
_invokeMethod('startRecording', {'options': options});
}
void stopRecording(String sessionID) {
_invokeMethod('stopRecording', {'sessionID': sessionID});
}
void setLocalParticipantProperty(String propertyKey, String propertyValue) {
_invokeMethod('setLocalParticipantProperty',
{'propertyKey': propertyKey, 'propertyValue': propertyValue});
}
void sendFeedback(String overallFeedback, String detailedFeedback) {
_invokeMethod('sendFeedback', {
'overallFeedback': overallFeedback,
'detailedFeedback': detailedFeedback
});
}
void leave() {
_invokeMethod('leave');
}
void removeLocalParticipantProperty(String name) {
_invokeMethod('removeLocalParticipantProperty', {'name': name});
}
void dial(int number) {
_invokeMethod('dial', {
'number': number,
});
}
void selectParticipants(List<String> participantIds) {
_invokeMethod('selectParticipants', {
'participantIds': participantIds,
});
}
int getParticipantCount(bool hidden) {
var total = 0;
for (var participant in participants) {
if (participant.isHidden()) {
total++;
}
}
if (!hidden) {
return participants.length - total + 1;
} else {
return participants.length + 1;
}
}
List<Participant> getParticipants(bool hidden) {
return participants;
}
List<JitsiLocalTrack> getLocalTracks(bool hidden) {
return localTracks;
}
List<JitsiRemoteTrack> getRemoteTracks(bool hidden) {
return remoteTracks;
}
void addEventListener(String event, dynamic callback) {
_bindings.add(new ConferenceBinding(event, callback));
}
void removeEventListener(event) {
_bindings = _bindings.where((binding) => binding.event != event).toList();
}
}
| 30.654229 | 80 | 0.586302 |
8573bfb9e9ef856d88d880b9816629a55e207d68 | 129 | js | JavaScript | tests/fixtures/export-module-example.js | SKalt/cookiecutter-webpack-es6-plus | 6181c832baad6202dde98541df0abea39a908ba9 | [
"MIT"
] | null | null | null | tests/fixtures/export-module-example.js | SKalt/cookiecutter-webpack-es6-plus | 6181c832baad6202dde98541df0abea39a908ba9 | [
"MIT"
] | null | null | null | tests/fixtures/export-module-example.js | SKalt/cookiecutter-webpack-es6-plus | 6181c832baad6202dde98541df0abea39a908ba9 | [
"MIT"
] | null | null | null | /**
* returns 1 (required jsdoc)
* @return {Number} 1
*/
export function foo() {
return 1;
};
export default {
bar: 2
};
| 10.75 | 29 | 0.581395 |
28209f69e9db4d23fffb2d05340d207fe35ac34a | 4,135 | go | Go | micro-services/service.notification-live/handler/handler.go | KonstantinGasser/datalab | a67b36e44d41f8b88f8f2f7f28ef47914158316d | [
"Apache-2.0"
] | null | null | null | micro-services/service.notification-live/handler/handler.go | KonstantinGasser/datalab | a67b36e44d41f8b88f8f2f7f28ef47914158316d | [
"Apache-2.0"
] | 5 | 2021-07-20T15:37:48.000Z | 2021-07-20T15:39:22.000Z | micro-services/service.notification-live/handler/handler.go | KonstantinGasser/datalab | a67b36e44d41f8b88f8f2f7f28ef47914158316d | [
"Apache-2.0"
] | null | null | null | package handler
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/KonstantinGasser/datalab/service.notification-live/domain"
"github.com/sirupsen/logrus"
)
const (
// accessControlAllowOrigin describes the allowed request origins
accessControlAllowOrigin = "Access-Control-Allow-Origin"
// accessControlAllowMethods describes the methods allowed by this API
accessControlAllowMethods = "Access-Control-Allow-Methods"
// accessControlAllowHeader describes a header -> ???
accessControlAllowHeader = "Access-Control-Allow-Headers"
)
// WithAllowedOrigins overrides the default setting for
// "Access-Control-Allow-Origin: *" with the given origins
func WithAllowedOrigins(origins ...string) func(*Handler) {
return func(handler *Handler) {
handler.allowedOrigins = origins
}
}
type Handler struct {
// *** CORS-Configurations ***
// accessOrigin refers to the AccessControlAllowOrigin Header
// which can be set in a request
allowedOrigins []string
// allowedMethods refers to the allowedControlAllowMethods Header
// which can be set in a request
allowedMethods []string
// allowedHeader refers to the allowedControlAllowHeader Header
// which can be set in a request
allowedHeaders []string
// onSuccessJSON returns a successful response to the client
// marshaling the passed data allowing to avoid code duplication
// content-type will always be application/json
onSuccessJSON func(w http.ResponseWriter, data interface{}, status int)
// onError response to request if an error occurs
onError func(w http.ResponseWriter, err string, status int)
// *** Service Dependencies ***
domain domain.NotificationLogic
}
func NewHandler(domain domain.NotificationLogic) *Handler {
return &Handler{
// *** CORS-Configurations ***
allowedOrigins: []string{"*"},
allowedMethods: []string{"GET", "POST", "OPTIONS"},
allowedHeaders: []string{"*"},
// onSuccessJSON returns a marshaled interface{} with a given status code
// to the client as its response
onSuccessJSON: func(w http.ResponseWriter, data interface{}, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(data); err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"status_code": 500, "msg": "an error occurred"}`))
return
}
},
// onError is a custom function returning a given error back as response.
// This way code duplication can be avoided
onError: func(w http.ResponseWriter, err string, status int) {
http.Error(w, err, status)
},
// *** Service Dependencies ***
domain: domain,
}
}
// Apply applies an API-CORS configuration on the API instance
func (handler *Handler) Apply(options ...func(*Handler)) {
for _, option := range options {
option(handler)
}
}
// AddRoute maps a route to a given http.HandlerFunc and can proxy middleware before the execution
// of the http.HandlerFunc
func (handler *Handler) Register(route string, h http.HandlerFunc, middleware ...func(http.HandlerFunc) http.HandlerFunc) {
logrus.Infof("[handler.Register] %v\n", route)
var final = h
for i := len(middleware) - 1; i >= 0; i-- {
final = middleware[i](final)
}
http.HandleFunc(route, final)
}
// decode is a custom wrapper to decode the request.Body if in JSON.
// Allows to avoid code duplication. Data is decoded into a map[string]interface{}
func (handler *Handler) decode(body io.ReadCloser, data interface{}) error {
if data == nil {
return fmt.Errorf("passed data can not be nil")
}
defer body.Close()
if err := json.NewDecoder(body).Decode(data); err != nil {
logrus.Errorf("[api.decode] could not decode r.Body: %v", err)
return fmt.Errorf("cloud not decode r.Body: %v", err)
}
return nil
}
// encode is a custom wrapper to encode any data to a byte slice in order
// for it to be returned to in the response. Allows to avoid code duplication
func (handler *Handler) encode(data interface{}) ([]byte, error) {
b, err := json.Marshal(data)
if err != nil {
logrus.Errorf("[api.encode] could not encode data: %v", err)
return nil, err
}
return b, nil
}
| 34.173554 | 123 | 0.725756 |
bc227f457b3e5879a8c9b09825aa59fb0c61f038 | 7,281 | ps1 | PowerShell | testscripts/nw_check_vmxnet3_multiqueue.ps1 | HiRoySoft/ESX-LISA | 46629104fd70694794f72385309d43c38c15c238 | [
"Apache-2.0"
] | 8 | 2017-09-01T01:31:57.000Z | 2019-09-19T09:51:01.000Z | testscripts/nw_check_vmxnet3_multiqueue.ps1 | HiRoySoft/ESX-LISA | 46629104fd70694794f72385309d43c38c15c238 | [
"Apache-2.0"
] | 26 | 2017-02-06T08:13:34.000Z | 2020-11-23T18:11:42.000Z | testscripts/nw_check_vmxnet3_multiqueue.ps1 | HiRoySoft/ESX-LISA | 46629104fd70694794f72385309d43c38c15c238 | [
"Apache-2.0"
] | 13 | 2017-01-11T09:47:27.000Z | 2019-09-02T09:18:07.000Z | ########################################################################################
## Description:
## Check the VMXNET3 multiqueue support
## Revision:
## v1.0.0 - xinhu - 11/15/2019 - Build the script.
########################################################################################
<#
.Synopsis
Vertify the VMXNET3 support multiqueue
.Description
<test>
<testName>nw_check_vmxnet3_multiqueue</testName>
<testID>ESX-NW_24</testID>
<setupScript>setupscripts\change_cpu.ps1</setupScript>
<testScript>testscripts/nw_check_vmxnet3_multiqueue.ps1</testScript>
<RevertDefaultSnapshot>True</RevertDefaultSnapshot>
<timeout>3600</timeout>
<testParams>
<param>VCPU=4</param>
<param>TC_COVERED=RHEL7-50933</param>
</testParams>
<onError>Continue</onError>
<noReboot>False</noReboot>
</test>
.Parameter vmName
Name of the test VM.
.Parameter hvServer
Name of the VIServer hosting the VM.
.Parameter testParams
Semicolon separated list of test parameters.
#>
# Checking the input arguments.
param([String] $vmName, [String] $hvServer, [String] $testParams)
if (-not $vmName) {
"ERROR: VM name cannot be null!"
exit 1
}
if (-not $hvServer) {
"ERROR: hvServer cannot be null!"
exit 1
}
if (-not $testParams) {
Throw "ERROR: No test parameters specified."
}
# Output test parameters so they are captured in log file.
"TestParams : '${testParams}'"
# Parse test parameters.
$rootDir = $null
$sshKey = $null
$ipv4 = $null
$numCPUs = $null
$params = $testParams.Split(";")
foreach ($p in $params) {
$fields = $p.Split("=")
switch ($fields[0].Trim()) {
"rootDir" { $rootDir = $fields[1].Trim() }
"sshKey" { $sshKey = $fields[1].Trim() }
"ipv4" { $ipv4 = $fields[1].Trim() }
"VCPU" { $numCPUs = [int]$fields[1].Trim() }
default {}
}
}
# Check all parameters are valid.
if (-not $rootDir) {
"WARN: no rootdir was specified."
}
else {
if ( (Test-Path -Path "${rootDir}") ) {
Set-Location $rootDir
}
else {
"WARN: rootdir '${rootDir}' does not exist."
}
}
if ($null -eq $sshKey) {
"ERROR: Test parameter sshKey was not specified."
return $False
}
if ($null -eq $ipv4) {
"ERROR: Test parameter ipv4 was not specified."
return $False
}
if ($null -eq $numCPUs) {
"ERROR: Test parameter numCPUs was not specified."
return $False
}
# Source tcutils.ps1
. .\setupscripts\tcutils.ps1
PowerCLIImport
ConnectToVIServer $env:ENVVISIPADDR `
$env:ENVVISUSERNAME `
$env:ENVVISPASSWORD `
$env:ENVVISPROTOCOL
########################################################################################
## Main Body
########################################################################################
$retValdhcp = $Failed
# Define the network queues.
$queues = "rx-0","rx-1","rx-2","rx-3","tx-0","tx-1","tx-2","tx-3"
# Function to stop VMB and disconnect with VIserver.
Function StopVMB($hvServer, $vmNameB)
{
$vmObjB = Get-VMHost -Name $hvServer | Get-VM -Name $vmNameB
Stop-VM -VM $vmObjB -Confirm:$false -RunAsync:$true -ErrorAction SilentlyContinue
DisconnectWithVIServer
}
# Function to check network queues.
Function CheckQueues($sshKey, $ip, $NIC, $queues)
{
LogPrint "INFO: Start to check queues of ${ip}."
$result = bin\plink.exe -i ssh\${sshKey} root@${ip} "ls /sys/class/net/$NIC/queues"
$compare = Compare-Object $result $queues -SyncWindow 0
LogPrint "DEBUG: compare: ${compare}."
if ($compare -ne $null)
{
LogPrint "ERROR: The queues of ${ipv4} is $result , not equal to ${queues}."
return $false
}
return $true
}
# Function to install netperf on vms.
Function InstalNetperf(${sshKey},${ip})
{
LogPrint "INFO: Start to install netperf on ${ip}"
# Current have a error "don't have command makeinfo" when install netperf, So cannot judge by echo $?
$install = bin\plink.exe -i ssh\${sshKey} root@${ip} "yum install -y automake && git clone https://github.com/HewlettPackard/netperf.git && cd netperf && ./autogen.sh && ./configure && make; make install; netperf -h; echo `$?"
LogPrint "DEBUG: install: $install"
if ( $install[-1] -eq 127)
{
LogPrint "ERROR: Install netperf failed."
return $false
}
return $true
}
# Prepare VMB.
$vmOut = Get-VMHost -Name $hvServer | Get-VM -Name $vmName
$vmNameB = $vmName -creplace ("-A$"),"-B"
LogPrint "INFO: Start to revert snapshot of ${vmNameB}."
$revert = RevertSnapshotVM $vmNameB $hvServer
LogPrint "DEBUG: revert: ${revert}."
if ($revert[-1] -ne $true)
{
LogPrint "ERROR: RevertSnap $vmNameB failed."
DisconnectWithVIServer
return $Aborted
}
LogPrint "INFO: Set $vmNameB vCpuNum = 4."
$State = Set-VM -VM $vmNameB -NumCpu $numCPUs -Confirm:$false
LogPrint "DEBUG: State: ${State}."
if (-not $?) {
LogPrint "ERROR: Failed to set $vmNameB vCpuNum = 4."
DisconnectWithVIServer
return $Aborted
}
$vmObjB = Get-VMHost -Name $hvServer | Get-VM -Name $vmNameB
LogPrint "INFO: Starting ${vmNameB}."
$on = Start-VM -VM $vmObjB -Confirm:$false -RunAsync:$true -ErrorAction SilentlyContinue
$ret = WaitForVMSSHReady $vmNameB $hvServer ${sshKey} 300
if ($ret -ne $true)
{
LogPrint "ERROR: Failed to start VM."
DisconnectWithVIServer
return $Aborted
}
# Refresh status
$vmObjB = Get-VMHost -Name $hvServer | Get-VM -Name $vmNameB
$IPB = GetIPv4ViaPowerCLI $vmNameB $hvServer
# Get NIC name of VMs
$NIC = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "ls /sys/class/net/ | grep ^e[tn][hosp]"
LogPrint "INFO: Get NIC name $NIC"
# Check network queues
$CheckA = CheckQueues ${sshKey} ${ipv4} $NIC $queues
if ($CheckA[-1] -ne $true)
{
LogPrint "ERROR: Check network queues: $CheckA"
StopVMB $hvServer $vmNameB
return $Aborted
}
$CheckB = CheckQueues ${sshKey} ${IPB} $NIC $queues
if ($CheckB[-1] -ne $true)
{
LogPrint "ERROR: Check network queues: $CheckB"
StopVMB $hvServer $vmNameB
return $Aborted
}
# Install Netperf on VMs
$IsInsA = InstalNetperf ${sshKey} ${ipv4}
if ($IsInsA[-1] -ne $true)
{
LogPrint "ERROR: Check network queues: $IsInsA"
StopVMB $hvServer $vmNameB
return $Aborted
}
$IsInsB = InstalNetperf ${sshKey} ${IPB}
if ($IsInsB[-1] -ne $true)
{
LogPrint "ERROR: Check network queues: $IsInsB"
StopVMB $hvServer $vmNameB
return $Aborted
}
# Start to netperf from VMB to VMA(as server)
$serer = "Unknown ERROR"
$server = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "netserver;echo `$?"
LogPrint "DEBUG: server: ${server}."
if ($server[-1] -ne 0)
{
LogPrint "ERROR: Make ${ipv4} as netserver Failed as ${server}."
StopVMB $hvServer $vmNameB
return $Aborted
}
# Run netperf.
$stime=Get-date
LogPrint "DEBUG: stime: ${stime}."
bin\plink.exe -i ssh\${sshKey} root@${IPB} "netperf -H ${ipv4} -l 2700"
$etime=Get-date
LogPrint "DEBUG: etime: ${etime}."
# Check interrupts.
$Checkqueues = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "cat /proc/interrupts | grep $NIC"
LogPrint "DEBUG: Checkqueues: ${Checkqueues}"
if ($Checkqueues.count -ge 4)
{
$retValdhcp = $Passed
}
StopVMB $hvServer $vmNameB
return $retValdhcp
| 25.193772 | 230 | 0.620244 |
7d58700e173e58096cb72cadd854f0c2ac51217c | 1,082 | html | HTML | manuscript/page-91/body.html | marvindanig/pascals-pensees | 807318b225258c9be2439a796c42ac0b39792c6c | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | manuscript/page-91/body.html | marvindanig/pascals-pensees | 807318b225258c9be2439a796c42ac0b39792c6c | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | manuscript/page-91/body.html | marvindanig/pascals-pensees | 807318b225258c9be2439a796c42ac0b39792c6c | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | <div class="leaf "><div class="inner justify"><p class="no-indent ">lot is always distant from either extreme, what matters it that man should have a little more knowledge of the universe? If he has it, he but gets a little higher. Is he not always infinitely removed from the end, and is not the duration of our life equally removed from eternity, even if it lasts ten years longer?</p><p>In comparison with these Infinites all finites are equal, and I see no reason for fixing our imagination on one more than on another. The only comparison which we make of ourselves to the finite is painful to us.</p><p>If man made himself the first object of study, he would see how incapable he is of going further. How can a part know the whole? But he may perhaps aspire to know at least the parts to which he bears some proportion. But the parts of the world are all so related and linked to one another, that I believe it impossible to know one without the other and without the whole.</p><p class=" stretch-last-line ">Man, for instance, is related to all he knows. He</p></div> </div> | 1,082 | 1,082 | 0.767098 |
b92760f5872f25e319f8c68e209cf07910ecba49 | 2,414 | go | Go | vendor/github.com/spacemonkeygo/httpsig/rsa.go | kernt/infrakit | 41da4a601bbb18514c61ebaed12a229098ddcd3e | [
"Apache-2.0"
] | 2,289 | 2016-10-04T07:56:14.000Z | 2019-07-24T06:42:41.000Z | vendor/github.com/spacemonkeygo/httpsig/rsa.go | kernt/infrakit | 41da4a601bbb18514c61ebaed12a229098ddcd3e | [
"Apache-2.0"
] | 711 | 2016-10-04T08:27:58.000Z | 2019-07-15T11:02:03.000Z | vendor/github.com/spacemonkeygo/httpsig/rsa.go | kernt/infrakit | 41da4a601bbb18514c61ebaed12a229098ddcd3e | [
"Apache-2.0"
] | 280 | 2016-10-04T07:58:06.000Z | 2019-07-16T07:03:38.000Z | // Copyright (C) 2017 Space Monkey, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpsig
import (
"crypto"
"crypto/rsa"
)
// RSASHA1 implements RSA PKCS1v15 signatures over a SHA1 digest
var RSASHA1 Algorithm = rsa_sha1{}
type rsa_sha1 struct{}
func (rsa_sha1) Name() string {
return "rsa-sha1"
}
func (a rsa_sha1) Sign(key interface{}, data []byte) ([]byte, error) {
k := toRSAPrivateKey(key)
if k == nil {
return nil, unsupportedAlgorithm(a)
}
return RSASign(k, crypto.SHA1, data)
}
func (a rsa_sha1) Verify(key interface{}, data, sig []byte) error {
k := toRSAPublicKey(key)
if k == nil {
return unsupportedAlgorithm(a)
}
return RSAVerify(k, crypto.SHA1, data, sig)
}
// RSASHA256 implements RSA PKCS1v15 signatures over a SHA256 digest
var RSASHA256 Algorithm = rsa_sha256{}
type rsa_sha256 struct{}
func (rsa_sha256) Name() string {
return "rsa-sha256"
}
func (a rsa_sha256) Sign(key interface{}, data []byte) ([]byte, error) {
k := toRSAPrivateKey(key)
if k == nil {
return nil, unsupportedAlgorithm(a)
}
return RSASign(k, crypto.SHA256, data)
}
func (a rsa_sha256) Verify(key interface{}, data, sig []byte) error {
k := toRSAPublicKey(key)
if k == nil {
return unsupportedAlgorithm(a)
}
return RSAVerify(k, crypto.SHA256, data, sig)
}
// RSASign signs a digest of the data hashed using the provided hash
func RSASign(key *rsa.PrivateKey, hash crypto.Hash, data []byte) (
signature []byte, err error) {
h := hash.New()
if _, err := h.Write(data); err != nil {
return nil, err
}
return rsa.SignPKCS1v15(Rand, key, hash, h.Sum(nil))
}
// RSAVerify verifies a signed digest of the data hashed using the provided hash
func RSAVerify(key *rsa.PublicKey, hash crypto.Hash, data, sig []byte) (
err error) {
h := hash.New()
if _, err := h.Write(data); err != nil {
return err
}
return rsa.VerifyPKCS1v15(key, hash, h.Sum(nil), sig)
}
| 25.956989 | 80 | 0.702983 |
562ef86002918b743edd05345a5f92557e86ace1 | 2,744 | dart | Dart | lib/components/switch_selector.dart | KroneRadicSenger/GuessTheMove-App | 486c161cd28bcfbd9b57a3f11de009702da76491 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T06:24:31.000Z | 2021-07-14T06:25:47.000Z | lib/components/switch_selector.dart | KroneRadicSenger/GuessTheMove-App | 486c161cd28bcfbd9b57a3f11de009702da76491 | [
"BSD-3-Clause"
] | null | null | null | lib/components/switch_selector.dart | KroneRadicSenger/GuessTheMove-App | 486c161cd28bcfbd9b57a3f11de009702da76491 | [
"BSD-3-Clause"
] | null | null | null | import 'dart:io' show Platform;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:guess_the_move/bloc/user_settings_bloc.dart';
import 'package:guess_the_move/model/game_mode.dart';
import 'package:guess_the_move/theme/theme.dart';
class SwitchSelector extends StatefulWidget {
final String title;
final bool initialValue;
final EdgeInsets padding;
final double titleSize;
final GameModeEnum gameMode;
final Function(bool) onChanged;
SwitchSelector({
Key? key,
required this.initialValue,
required this.title,
required this.onChanged,
this.padding = const EdgeInsets.fromLTRB(15, 0, 5, 0),
this.titleSize = 14,
this.gameMode = GameModeEnum.findTheGrandmasterMoves,
}) : super(key: key);
@override
SwitchSelectorState createState() => SwitchSelectorState();
}
class SwitchSelectorState extends State<SwitchSelector> {
bool _value = false;
@override
void initState() {
_value = widget.initialValue;
super.initState();
}
@override
Widget build(BuildContext context) => BlocBuilder<UserSettingsBloc, UserSettingsState>(builder: (context, userSettingsState) {
return Container(
decoration: BoxDecoration(color: appTheme(context, userSettingsState.userSettings.themeMode).cardBackgroundColor, borderRadius: BorderRadius.all(Radius.circular(10))),
child: Padding(
padding: widget.padding,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
widget.title,
style: TextStyle(
color: appTheme(context, userSettingsState.userSettings.themeMode).gameModeThemes[widget.gameMode]!.accentColor,
fontWeight: FontWeight.w600,
fontSize: widget.titleSize,
),
),
),
Transform.scale(
scale: Platform.isAndroid ? 0.9 : 0.65,
child: Switch.adaptive(
activeColor: appTheme(context, userSettingsState.userSettings.themeMode).gameModeThemes[widget.gameMode]!.accentColor,
onChanged: (value) {
_value = value;
widget.onChanged(value);
},
value: _value,
),
),
],
),
),
);
});
void updateValue(final bool newValue) {
setState(() {
_value = newValue;
});
}
}
| 32.666667 | 177 | 0.606778 |
2c9e171562db01432baf677692ac6fc62e97d85f | 275 | dart | Dart | lib/constants.dart | adityathakurxd/Shades | 4f2d1360b54e9fd4d9558c8a01119cc6f728a3f4 | [
"Apache-2.0"
] | 3 | 2021-04-29T16:00:48.000Z | 2021-11-28T22:06:14.000Z | lib/constants.dart | adityathakurxd/shades | 4f2d1360b54e9fd4d9558c8a01119cc6f728a3f4 | [
"Apache-2.0"
] | null | null | null | lib/constants.dart | adityathakurxd/shades | 4f2d1360b54e9fd4d9558c8a01119cc6f728a3f4 | [
"Apache-2.0"
] | null | null | null | import 'package:flutter/material.dart';
const Color skin1 = Color(0xFFF0D7C9);
const Color skin2 = Color(0xFFDBB69B);
const Color skin3 = Color(0xFFBF9178);
const Color skin4 = Color(0xFF816241);
const Color skin5 = Color(0xFF755136);
const Color skin6 = Color(0xFF493324);
| 30.555556 | 39 | 0.770909 |
5fe00e6dec68f64c6235b9b864dc253477ce4a4d | 993 | swift | Swift | Tests/VCoreTests/Tests/Extensions/UIKit/UIImageRotatedTests.swift | VakhoKontridze/VCore | 7feb5f442da98199d891ef3f6a2236b418d683da | [
"MIT"
] | 29 | 2022-01-03T08:45:23.000Z | 2022-02-01T18:18:33.000Z | Tests/VCoreTests/Tests/Extensions/UIKit/UIImageRotatedTests.swift | VakhoKontridze/VCore | 7feb5f442da98199d891ef3f6a2236b418d683da | [
"MIT"
] | null | null | null | Tests/VCoreTests/Tests/Extensions/UIKit/UIImageRotatedTests.swift | VakhoKontridze/VCore | 7feb5f442da98199d891ef3f6a2236b418d683da | [
"MIT"
] | 1 | 2022-01-06T08:00:23.000Z | 2022-01-06T08:00:23.000Z | //
// UIImageRotatedTests.swift
// VCore
//
// Created by Vakhtang Kontridze on 10.05.22.
//
#if canImport(UIKit) && !os(watchOS)// averageColor doesn't work on watchOS
import XCTest
@testable import VCore
// MARK: - Tests
final class UIImageRotatedTests: XCTestCase { // Not testing helper methods
func test() {
let image1: UIImage = .init(size: .init(dimension: 100), color: .red)! // fatalError
let image2: UIImage = .init(size: .init(dimension: 100), color: .blue)! // fatalError
let mergedImage: UIImage = .mergeHorizontally(image1, with: image2)! // fatalError
let rotatedImage: UIImage = mergedImage.rotated(by: .init(value: 90, unit: .degrees))! // fatalError
let croppedImage: UIImage = rotatedImage.cropped(to: .init(
origin: .zero,
size: .init(dimension: 100)
))
XCTAssertEqualColor(croppedImage.averageColor!, .red) // fatalError
}
}
#endif
| 29.205882 | 108 | 0.626385 |
a11fec1f6b9dd4ba9f7f819746d6c3b7380dc471 | 2,943 | go | Go | cmd/cloudAccount_delete.go | krotscheck/cli | 3b227503cf30b120883f590d4717c2498a3703c6 | [
"Apache-2.0"
] | null | null | null | cmd/cloudAccount_delete.go | krotscheck/cli | 3b227503cf30b120883f590d4717c2498a3703c6 | [
"Apache-2.0"
] | null | null | null | cmd/cloudAccount_delete.go | krotscheck/cli | 3b227503cf30b120883f590d4717c2498a3703c6 | [
"Apache-2.0"
] | null | null | null | // Copyright © 2016 Paul Allen <paul@cloudcoreo.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"io"
"strings"
"github.com/CloudCoreo/cli/pkg/aws"
"github.com/CloudCoreo/cli/pkg/command"
"fmt"
"github.com/CloudCoreo/cli/cmd/content"
"github.com/CloudCoreo/cli/cmd/util"
"github.com/CloudCoreo/cli/pkg/coreo"
"github.com/spf13/cobra"
)
type cloudDeleteCmd struct {
out io.Writer
client command.Interface
cloud command.CloudProvider
cloudID string
deleteRole bool
awsProfile string
awsProfilePath string
}
func newCloudDeleteCmd(client command.Interface, out io.Writer) *cobra.Command {
cloudDelete := &cloudDeleteCmd{
out: out,
client: client,
}
cmd := &cobra.Command{
Use: content.CmdDeleteUse,
Short: content.CmdCloudDeleteShort,
Long: content.CmdCloudDeleteLong,
RunE: func(cmd *cobra.Command, args []string) error {
if err := util.CheckCloudShowOrDeleteFlag(cloudDelete.cloudID, verbose); err != nil {
return err
}
if cloudDelete.client == nil {
cloudDelete.client = coreo.NewClient(
coreo.Host(apiEndpoint),
coreo.RefreshToken(key))
}
if cloudDelete.deleteRole && (cloudDelete.cloud == nil) {
newServiceInput := &aws.NewServiceInput{
AwsProfile: cloudDelete.awsProfile,
AwsProfilePath: cloudDelete.awsProfilePath,
}
cloudDelete.cloud = aws.NewService(newServiceInput)
}
return cloudDelete.run()
},
}
f := cmd.Flags()
f.StringVarP(&cloudDelete.cloudID, content.CmdFlagCloudIDLong, "", "", content.CmdFlagCloudIDDescription)
f.BoolVarP(&cloudDelete.deleteRole, content.CmdFlagDeleteRole, "", false, content.CmdFLagDeleteRoleDescription)
f.StringVarP(&cloudDelete.awsProfile, content.CmdFlagAwsProfile, "", "", content.CmdFlagAwsProfileDescription)
f.StringVarP(&cloudDelete.awsProfilePath, content.CmdFlagAwsProfilePath, "", "", content.CmdFlagAwsProfilePathDescription)
return cmd
}
func (t *cloudDeleteCmd) run() error {
var roleName string
if t.deleteRole {
cloud, err := t.client.ShowCloudAccountByID(t.cloudID)
if err != nil {
return err
}
roleNames := strings.Split(cloud.Arn, "/")
roleName = roleNames[len(roleNames)-1]
t.cloud.DeleteRole(roleName)
}
err := t.client.DeleteCloudAccountByID(t.cloudID)
if err != nil {
return err
}
fmt.Fprintln(t.out, content.InfoCloudAccountDeleted)
return nil
}
| 26.754545 | 123 | 0.721373 |
0e11573e1d86ec7fa5d664b0c4d59a4748be50d3 | 198 | swift | Swift | Sources/ScreenData/Views/SomeSpacer.swift | ServerDriven/ScreenData-swift | 12b971861ad45ff2178d4fc498e3afe3c3157e49 | [
"MIT"
] | 3 | 2021-05-22T11:53:57.000Z | 2021-08-09T14:57:41.000Z | Sources/ScreenData/Views/SomeSpacer.swift | ServerDriven/ScreenData-swift | 12b971861ad45ff2178d4fc498e3afe3c3157e49 | [
"MIT"
] | 1 | 2021-01-22T01:44:15.000Z | 2021-01-25T14:47:11.000Z | Sources/ScreenData/Views/SomeSpacer.swift | ServerDriven/ScreenData-swift | 12b971861ad45ff2178d4fc498e3afe3c3157e49 | [
"MIT"
] | null | null | null | public struct SomeSpacer: Codable, Hashable {
public var size: Int
public var type: ViewType {
.spacer
}
public init(size: Int) {
self.size = size
}
}
| 15.230769 | 45 | 0.550505 |