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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
af52bb3bb575efc916314fb9d7ddde1b5466f619 | 119 | rb | Ruby | lib/bullhorn/rest/entities/tearsheet_recipient.rb | evanrolfe/bullhorn-rest | bb34350f1f85f760397b1a0291a6dfbd35327ae4 | [
"MIT"
] | 9 | 2015-02-04T23:38:42.000Z | 2022-02-17T21:51:01.000Z | lib/bullhorn/rest/entities/tearsheet_recipient.rb | evanrolfe/bullhorn-rest | bb34350f1f85f760397b1a0291a6dfbd35327ae4 | [
"MIT"
] | 4 | 2015-04-14T13:55:41.000Z | 2016-04-07T14:35:17.000Z | lib/bullhorn/rest/entities/tearsheet_recipient.rb | evanrolfe/bullhorn-rest | bb34350f1f85f760397b1a0291a6dfbd35327ae4 | [
"MIT"
] | 12 | 2015-02-13T07:50:58.000Z | 2021-11-01T16:41:53.000Z | module Bullhorn
module Rest
module Entities
module TearsheetRecipient
extend Base
define_methods
end
end
end
end | 9.153846 | 25 | 0.823529 |
c1b76121aed58669f645d931b3e482f05b51056f | 4,881 | rs | Rust | tab-command/src/service/tab/create_tab.rs | casonadams/tab-rs | 5c31638843e550909c36a3aa2fe8f315a3f4bbe9 | [
"MIT"
] | null | null | null | tab-command/src/service/tab/create_tab.rs | casonadams/tab-rs | 5c31638843e550909c36a3aa2fe8f315a3f4bbe9 | [
"MIT"
] | null | null | null | tab-command/src/service/tab/create_tab.rs | casonadams/tab-rs | 5c31638843e550909c36a3aa2fe8f315a3f4bbe9 | [
"MIT"
] | null | null | null | use crate::{
env::terminal_size,
message::tabs::CreateTabRequest,
prelude::*,
state::{
tabs::ActiveTabsState,
workspace::{WorkspaceState, WorkspaceTab},
},
utils::await_state,
};
use anyhow::anyhow;
use std::{collections::HashMap, sync::Arc};
use std::{env, path::PathBuf};
use tab_api::tab::{normalize_name, CreateTabMetadata};
/// Receives CreateTabRequests, and decides whether to send the daemon issue a create request.
/// Assembles the CreateTabMetadata.
pub struct CreateTabService {
_request_tab: Lifeline,
}
impl Service for CreateTabService {
type Bus = TabBus;
type Lifeline = anyhow::Result<Self>;
fn spawn(bus: &Self::Bus) -> Self::Lifeline {
let mut rx = bus.rx::<CreateTabRequest>()?;
let mut rx_tabs_state = bus.rx::<Option<ActiveTabsState>>()?.into_inner();
let mut rx_workspace = bus.rx::<Option<WorkspaceState>>()?.into_inner();
let mut tx_websocket = bus.tx::<Request>()?;
let _request_tab = Self::try_task("request_tab", async move {
while let Some(request) = rx.recv().await {
match request {
CreateTabRequest::Named(name) => {
let tab_exists = await_state(&mut rx_tabs_state)
.await?
.tabs
.values()
.find(|tab| tab.name == name)
.is_some();
if !tab_exists {
let workspace = await_state(&mut rx_workspace).await?;
Self::create_named(name, workspace.tabs, &mut tx_websocket).await?;
}
}
}
}
Ok(())
});
Ok(Self { _request_tab })
}
}
impl CreateTabService {
pub async fn create_named(
name: String,
workspace: Arc<Vec<WorkspaceTab>>,
tx_websocket: &mut impl Sender<Request>,
) -> anyhow::Result<()> {
let name = normalize_name(name.as_str());
let workspace_tab = workspace.iter().find(|tab| tab.name == name);
let dimensions = terminal_size()?;
let shell = Self::compute_shell(workspace_tab);
let directory = Self::compute_directory(workspace_tab)?;
let env = Self::compute_env(workspace_tab);
let metadata = CreateTabMetadata {
name: Self::compute_name(workspace_tab, name.as_str()),
doc: workspace_tab.map(|tab| tab.doc.clone()).flatten(),
dir: directory
.to_str()
.ok_or_else(|| {
anyhow!(
"The working directory {} could not be parsed as a string",
directory.to_string_lossy()
)
})?
.to_string(),
env,
dimensions,
shell,
};
let request = Request::CreateTab(metadata);
tx_websocket.send(request).await?;
Ok(())
}
fn compute_shell(tab: Option<&WorkspaceTab>) -> String {
if let Some(tab) = tab {
if let Some(ref shell) = tab.shell {
return shell.clone();
}
}
std::env::var("SHELL").unwrap_or("/usr/bin/env bash".to_string())
}
fn compute_env(tab: Option<&WorkspaceTab>) -> HashMap<String, String> {
let mut env = tab
.map(|tab| tab.env.clone())
.flatten()
.unwrap_or(HashMap::with_capacity(0));
Self::copy_env(&mut env, "TERM");
Self::copy_env(&mut env, "COLORTERM");
env
}
/// Copies the environment variable from the current environment,
/// if it does not already exist in the map
fn copy_env(env_map: &mut HashMap<String, String>, var: &str) {
let var = var.to_string();
if !env_map.contains_key(&var) {
if let Ok(value) = env::var(&var) {
env_map.insert(var.clone(), value);
}
}
}
fn compute_directory(tab: Option<&WorkspaceTab>) -> anyhow::Result<PathBuf> {
if let Some(tab) = tab {
if tab.directory.exists() {
return Ok(tab.directory.clone());
} else {
warn!(
"The configured working directory for '{}' was not found: {}",
tab.name,
tab.directory.as_path().to_string_lossy()
);
// fall through to current directory
}
}
std::env::current_dir().map_err(|err| err.into())
}
fn compute_name(tab: Option<&WorkspaceTab>, name: &str) -> String {
if let Some(tab) = tab {
tab.name.clone()
} else {
name.to_string()
}
}
}
| 31.490323 | 95 | 0.518132 |
5fa1f90abfbeda912100daecc126bd894d4783d9 | 3,124 | c | C | main.c | Palhares17/Projeto-RPG | 1ca6fd486c0590827c21728480145b3d89f8cf6f | [
"MIT"
] | null | null | null | main.c | Palhares17/Projeto-RPG | 1ca6fd486c0590827c21728480145b3d89f8cf6f | [
"MIT"
] | 1 | 2021-12-15T03:53:30.000Z | 2021-12-15T03:53:30.000Z | main.c | Palhares17/Projeto-RPG | 1ca6fd486c0590827c21728480145b3d89f8cf6f | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
int main() {
// Variaveis
int personagem;
char nome[30];
int vida = 100;
printf("\n-----------------------------------------------\n");
// Inicio
printf("Qual eh seu nome bravo aventureiro.\n");
scanf("%s", nome);
printf("\nEscolha seu personagem: ");
printf("\n");
printf("1 - Barbaro / 2 - Arqueiro / 3 - Mago / 4 - Guerreiro\n");
scanf("%d", &personagem);
switch (personagem) {
case 1:
printf("\nVoce selecionou o Barbaro.\n");
break;
case 2:
printf("\nVoce selecionou o Arqueiro.\n");
break;
case 3:
printf("\nVoce selecionou o Mago.\n");
break;
case 4:
printf("\nVoce selecionou o Guerreiro.\n");
break;
default:
printf("\nVoce nao selecionou nenhum personagem.\n");
}
printf("\n-----------------------------------------------\n");
// Comeco da historia
printf("Bem-vendo %s\n", nome);
int caminhos;
printf("Vamos comecar a sua aventura, voce tem 3 caminhos a percorrer.\n");
printf("Voce pode percorrer para o oceano de Delfin, ir para a floresta densa de Orlof ou ir para o deserto de Thalis.\n");
printf("\n1 - Oceano de Delfin / 2 - Floresta densa de Orlof / 3 - Deserto de Thalis\n");
scanf("%d", &caminhos);
char caminhoSelecionado[100];
switch (caminhos){
case 1:
printf("Entao voce ira para o Oceano de Delfin.\nEntao, que a aventura comece.\n");
caminhoSelecionado[100] = "Oceano de Delfin";
break;
case 2:
printf("Entao voce ira para o Floresta densa de Orlof.\nEntao, que a aventura comece.\n");
caminhoSelecionado[100] = "Floresta densa de Orlof";
break;
case 3:
printf("Entao voce ira para o Deserto de Thalis.\nEntao, que a aventura comece.\n");
caminhoSelecionado[100] = "Deserto de Thalis";
break;
}
char escolha[30];
printf("\n-----------------------------------------------\n");
printf("\n-> Capitulo 1\n");
printf("Voce entrou no %s.\n", caminhoSelecionado);
printf("Cuidado voce entrou no covil do Ogro targon.");
printf("Voce vai lutar ou correr ?");
scanf("%s", escolha);
if(strcmp(escolha, "Lutar") == 0 || strcmp(escolha, "lutar") == 0) {
printf("Voce vai para cima do ogro\n");
int dano;
int vidaOgro = 50, danoOgro;
// COMEÇO DA LUTA
while(vidaOgro <= 0 || vida <= 0) {
dano = rand() % 10;
danoOgro = rand() % 10;
printf("Você dá %d de dano\n", dano);
printf("O dano do ogro eh de %d\n", danoOgro);
vida -= danoOgro;
vidaOgro -= dano;
}
printf("\nFinal da batalha!!!\n");
if(vidaOgro <=0) {
printf("Parabens voce derrotou o Ogro targon\n");
} else {
printf("Voce morreu, acontece!!!");
}
}
return 0;
} | 30.627451 | 127 | 0.510883 |
26f52adca5db3c17402a1480c503c345aa810349 | 11,166 | sql | SQL | DBSQLExsport/dblarabook.sql | itramayana/larabook | 7cd556b2efb144d8d7f107b2782fca4911c0843c | [
"MIT"
] | null | null | null | DBSQLExsport/dblarabook.sql | itramayana/larabook | 7cd556b2efb144d8d7f107b2782fca4911c0843c | [
"MIT"
] | null | null | null | DBSQLExsport/dblarabook.sql | itramayana/larabook | 7cd556b2efb144d8d7f107b2782fca4911c0843c | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.3.11
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Oct 25, 2016 at 05:09 AM
-- Server version: 5.6.24
-- PHP Version: 5.6.8
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 utf8 */;
--
-- Database: `dblarabook`
--
-- --------------------------------------------------------
--
-- Table structure for table `authors`
--
CREATE TABLE IF NOT EXISTS `authors` (
`id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `authors`
--
INSERT INTO `authors` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'Agus', '2016-10-23 23:51:29', '2016-10-23 23:51:29'),
(2, 'Satria', '2016-10-23 23:51:29', '2016-10-23 23:51:29'),
(3, 'Prabawa', '2016-10-23 23:51:29', '2016-10-23 23:51:29');
-- --------------------------------------------------------
--
-- Table structure for table `books`
--
CREATE TABLE IF NOT EXISTS `books` (
`id` int(10) unsigned NOT NULL,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`author_id` int(10) unsigned NOT NULL,
`amount` int(10) unsigned NOT NULL,
`cover` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `books`
--
INSERT INTO `books` (`id`, `title`, `author_id`, `amount`, `cover`, `created_at`, `updated_at`) VALUES
(1, 'Babi Terbang', 1, 3, '', '2016-10-23 23:51:29', '2016-10-23 23:51:29'),
(2, 'Babi Naik Pesawat', 2, 2, '', '2016-10-23 23:51:29', '2016-10-23 23:51:29'),
(3, 'Ayam makan Pepaya', 3, 4, '7a9a8f857bf20df39dcd69d399949542.png', '2016-10-23 23:51:29', '2016-10-24 01:04:52'),
(4, 'Teletubies', 3, 3, '', '2016-10-23 23:51:29', '2016-10-23 23:51:29');
-- --------------------------------------------------------
--
-- Table structure for table `borrow_logs`
--
CREATE TABLE IF NOT EXISTS `borrow_logs` (
`id` int(10) unsigned NOT NULL,
`book_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`is_returned` tinyint(1) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `borrow_logs`
--
INSERT INTO `borrow_logs` (`id`, `book_id`, `user_id`, `is_returned`, `created_at`, `updated_at`) VALUES
(1, 1, 2, 0, '2016-10-23 23:51:29', '2016-10-23 23:51:29'),
(2, 2, 2, 0, '2016-10-23 23:51:30', '2016-10-23 23:51:30'),
(3, 3, 2, 1, '2016-10-23 23:51:30', '2016-10-23 23:51:30'),
(4, 3, 2, 0, '2016-10-24 01:36:30', '2016-10-24 01:36:30');
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE IF NOT EXISTS `migrations` (
`migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`migration`, `batch`) VALUES
('2014_10_12_000000_create_users_table', 1),
('2014_10_12_100000_create_password_resets_table', 1),
('2016_10_17_035655_entrust_setup_tables', 1),
('2016_10_17_060443_create_authors_table', 1),
('2016_10_17_060500_create_books_table', 1),
('2016_10_24_073538_create_borrow_logs_table', 1);
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE IF NOT EXISTS `password_resets` (
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `permissions`
--
CREATE TABLE IF NOT EXISTS `permissions` (
`id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`display_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `permission_role`
--
CREATE TABLE IF NOT EXISTS `permission_role` (
`permission_id` int(10) unsigned NOT NULL,
`role_id` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `roles`
--
CREATE TABLE IF NOT EXISTS `roles` (
`id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`display_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `roles`
--
INSERT INTO `roles` (`id`, `name`, `display_name`, `description`, `created_at`, `updated_at`) VALUES
(1, 'admin', 'Admin', NULL, '2016-10-23 23:51:29', '2016-10-23 23:51:29'),
(2, 'member', 'Member', NULL, '2016-10-23 23:51:29', '2016-10-23 23:51:29');
-- --------------------------------------------------------
--
-- Table structure for table `role_user`
--
CREATE TABLE IF NOT EXISTS `role_user` (
`user_id` int(10) unsigned NOT NULL,
`role_id` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `role_user`
--
INSERT INTO `role_user` (`user_id`, `role_id`) VALUES
(1, 1),
(2, 2);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, 'Admin Larabook', 'admin@gmail.com', '$2y$10$6X3NTbDMaeadThdhDSs0T.OoDgaVyNTdgHBxIX0rPc4wZj6ZJDrri', '6Pe5bF2isSf02h3ygjhGuscsSvrAT2aowN9dJsQLRqMZpQro6FInhRn2iqw0', '2016-10-23 23:51:29', '2016-10-24 01:36:16'),
(2, 'Sample Member', 'member@gmail.com', '$2y$10$FTXwwwwqfrL5PhTZqvDvm.kgLXCuhaKjaotXf16d26X6/mk72hsYW', '21VABqlr9lbxhIqjHrbHUt28mCfzFxZ38JCylcCaD5fZ0MKB395xn5XYIzib', '2016-10-23 23:51:29', '2016-10-24 01:40:27');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `authors`
--
ALTER TABLE `authors`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `books`
--
ALTER TABLE `books`
ADD PRIMARY KEY (`id`), ADD KEY `books_author_id_foreign` (`author_id`);
--
-- Indexes for table `borrow_logs`
--
ALTER TABLE `borrow_logs`
ADD PRIMARY KEY (`id`), ADD KEY `borrow_logs_book_id_index` (`book_id`), ADD KEY `borrow_logs_user_id_index` (`user_id`);
--
-- Indexes for table `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`), ADD KEY `password_resets_token_index` (`token`);
--
-- Indexes for table `permissions`
--
ALTER TABLE `permissions`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `permissions_name_unique` (`name`);
--
-- Indexes for table `permission_role`
--
ALTER TABLE `permission_role`
ADD PRIMARY KEY (`permission_id`,`role_id`), ADD KEY `permission_role_role_id_foreign` (`role_id`);
--
-- Indexes for table `roles`
--
ALTER TABLE `roles`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `roles_name_unique` (`name`);
--
-- Indexes for table `role_user`
--
ALTER TABLE `role_user`
ADD PRIMARY KEY (`user_id`,`role_id`), ADD KEY `role_user_role_id_foreign` (`role_id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `authors`
--
ALTER TABLE `authors`
MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `books`
--
ALTER TABLE `books`
MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `borrow_logs`
--
ALTER TABLE `borrow_logs`
MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `permissions`
--
ALTER TABLE `permissions`
MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `roles`
--
ALTER TABLE `roles`
MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `books`
--
ALTER TABLE `books`
ADD CONSTRAINT `books_author_id_foreign` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `borrow_logs`
--
ALTER TABLE `borrow_logs`
ADD CONSTRAINT `borrow_logs_book_id_foreign` FOREIGN KEY (`book_id`) REFERENCES `books` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `borrow_logs_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `permission_role`
--
ALTER TABLE `permission_role`
ADD CONSTRAINT `permission_role_permission_id_foreign` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `permission_role_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `role_user`
--
ALTER TABLE `role_user`
ADD CONSTRAINT `role_user_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `role_user_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
/*!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 */;
| 31.994269 | 215 | 0.685653 |
5ba9fe9e4e301c4786bdd5563653c91957d077bc | 1,155 | rs | Rust | src/command.rs | zatoichi-labs/yubihsm-rs | 2952153a1a9b0bd2bba1d78223e2f6645c95bb65 | [
"Apache-2.0",
"MIT"
] | 42 | 2020-02-29T16:54:24.000Z | 2022-03-11T01:20:46.000Z | src/command.rs | zatoichi-labs/yubihsm-rs | 2952153a1a9b0bd2bba1d78223e2f6645c95bb65 | [
"Apache-2.0",
"MIT"
] | 208 | 2020-02-29T20:24:20.000Z | 2022-03-31T22:23:01.000Z | src/command.rs | zatoichi-labs/yubihsm-rs | 2952153a1a9b0bd2bba1d78223e2f6645c95bb65 | [
"Apache-2.0",
"MIT"
] | 11 | 2020-03-23T18:57:04.000Z | 2022-02-14T00:30:27.000Z | //! YubiHSM commands: types and traits for modeling the commands supported
//! by the HSM device, implemented in relevant modules.
mod code;
mod error;
mod message;
pub use self::{
code::Code,
error::{Error, ErrorKind},
};
pub(crate) use self::message::Message;
use crate::{response::Response, serialization::serialize};
use serde::{de::DeserializeOwned, ser::Serialize};
/// Maximum size of a message sent to/from the YubiHSM
pub const MAX_MSG_SIZE: usize = 2048;
/// Structured command (i.e. requests) which are encrypted and then sent to
/// the HSM. Every command has a corresponding `ResponseType`.
///
/// See <https://developers.yubico.com/YubiHSM2/Commands>
// TODO(tarcieri): add a `Zeroize` bound to clear sensitive data
pub(crate) trait Command: Serialize + DeserializeOwned + Sized {
/// Response type for this command
type ResponseType: Response;
/// Command ID for this command
const COMMAND_CODE: Code = Self::ResponseType::COMMAND_CODE;
}
impl<'c, C: Command> From<&'c C> for Message {
fn from(command: &C) -> Message {
Self::create(C::COMMAND_CODE, serialize(command).unwrap()).unwrap()
}
}
| 30.394737 | 75 | 0.705628 |
53d27b6e65a9322f7b9f754835644159d97ea8ad | 3,971 | java | Java | src/main/java/ua/leomovskii/tg/mybucketlist/db/WishHandler.java | leomovskii/My-Bucket-List | cd58026f0dac480ac87698fdbf859867f66e206e | [
"MIT"
] | null | null | null | src/main/java/ua/leomovskii/tg/mybucketlist/db/WishHandler.java | leomovskii/My-Bucket-List | cd58026f0dac480ac87698fdbf859867f66e206e | [
"MIT"
] | null | null | null | src/main/java/ua/leomovskii/tg/mybucketlist/db/WishHandler.java | leomovskii/My-Bucket-List | cd58026f0dac480ac87698fdbf859867f66e206e | [
"MIT"
] | null | null | null | package ua.leomovskii.tg.mybucketlist.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import ua.leomovskii.tg.mybucketlist.Logger;
public class WishHandler {
private String db_url, db_user, db_pass;
private ArrayList<Wish> wish_list;
public WishHandler() {
db_url = System.getenv("DB_URL");
db_user = System.getenv("DB_USERNAME");
db_pass = System.getenv("DB_PASSWORD");
this.wish_list = getWishList();
Logger.info(String.format("Loaded %d Wish records.", wish_list.size()));
}
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(db_url, db_user, db_pass);
}
public ArrayList<Wish> getWishList() {
String query = "SELECT * FROM `bucketlist`.`wishlist`;";
ArrayList<Wish> list = new ArrayList<>();
try (Connection c = getConnection(); Statement s = c.createStatement()) {
ResultSet rs = s.executeQuery(query);
while (rs.next())
list.add(new Wish(rs.getInt("INDEX"), rs.getLong("OWNER_ID"), rs.getString("TITLE"),
rs.getInt("CHECKED") == 1));
} catch (SQLException e) {
Logger.error(e.getLocalizedMessage());
}
return list;
}
private Wish getWish(int index) {
for (Wish w : wish_list)
if (w.index == index)
return w;
return null;
}
public void addWish(long ownerId, String title) {
String query1 = "INSERT INTO `bucketlist`.`wishlist` (`OWNER`, `TITLE`) VALUES ('%d', '%s');";
String query2 = "SELECT MAX(`ID`) FROM `bucketlist`.`wishlist`;";
try (Connection c = getConnection();
Statement s = c.createStatement();
PreparedStatement ps = getConnection().prepareStatement(query2)) {
s.execute(String.format(query1, ownerId, title, 0));
ResultSet rs = ps.executeQuery();
rs.next();
this.wish_list.add(new Wish(rs.getInt(1), ownerId, title));
} catch (SQLException e) {
Logger.error(e.getLocalizedMessage());
}
}
public void setWishTitle(int index, String title) {
String query = "UPDATE `bucketlist`.`wishlist` SET `TITLE` = '%s' WHERE (`INDEX` = '%d');";
try (Connection c = getConnection(); Statement s = c.createStatement()) {
s.execute(String.format(query, title, index));
getWish(index).title = title;
} catch (SQLException e) {
Logger.error(e.getLocalizedMessage());
}
}
public String getWishTitle(int index) {
return new String(getWish(index).title);
}
public void setWishChecked(int index, boolean checked) {
String query = "UPDATE `bucketlist`.`wishlist` SET `CHECKED` = '%d' WHERE (`INDEX` = '%d');";
try (Connection c = getConnection(); Statement s = c.createStatement()) {
s.execute(String.format(query, checked ? 1 : 0, index));
getWish(index).checked = checked;
} catch (SQLException e) {
Logger.error(e.getLocalizedMessage());
}
}
public boolean isWishChecked(int index) {
return getWish(index).checked;
}
public void removeWish(int index) {
Wish wish = getWish(index);
try (Connection c = getConnection(); Statement s = c.createStatement()) {
String query = "DELETE FROM `bucketlist`.`wishlist` WHERE (`INDEX` = '%d');";
s.execute(String.format(query, index));
this.wish_list.remove(wish);
} catch (SQLException e) {
Logger.error(e.getLocalizedMessage());
}
}
public HashMap<Integer, String> getWishesOf(long userId) {
HashMap<Integer, String> map = new HashMap<>();
for (Wish w : wish_list)
if (w.ownerId == userId)
map.put(w.index, w.title);
return map;
}
private class Wish {
int index;
long ownerId;
String title;
boolean checked;
Wish(int index, long ownerId, String title, boolean checked) {
this.index = index;
this.ownerId = ownerId;
this.title = title;
this.checked = checked;
}
Wish(int index, long ownerId, String title) {
this(index, ownerId, title, false);
}
}
} | 25.785714 | 96 | 0.6827 |
7473a96827405bbf4cada0397cce89d68ecf4cfe | 14,459 | c | C | Src/main.c | shomagan/projek | 884cc08a78e272aa6bea08ca300469f775927de2 | [
"Apache-2.0"
] | null | null | null | Src/main.c | shomagan/projek | 884cc08a78e272aa6bea08ca300469f775927de2 | [
"Apache-2.0"
] | null | null | null | Src/main.c | shomagan/projek | 884cc08a78e272aa6bea08ca300469f775927de2 | [
"Apache-2.0"
] | null | null | null | /**
******************************************************************************
* File Name : main.c
* Description : Main program body
******************************************************************************
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_hal.h"
#include "step.h"
#include "saver.h"
#include "frame_control.h"
#include "data_transfer.h"
#include "hw_config.h"
#include "usb_lib.h"
#include "usb_desc.h"
ADC_HandleTypeDef hadc2;
IWDG_HandleTypeDef hiwdg;
RTC_HandleTypeDef hrtc;
TIM_HandleTypeDef htim1;
UART_HandleTypeDef huart1;
u32 time_ms;
u8 config;
RTC_TimeTypeDef Time;
RTC_DateTypeDef Date;
settings_t settings;
u8 buff_temp[256];
u32 lenta;
u32 speed_control;
void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_IWDG_Init(void);
static void MX_RTC_Init(void);
static void MX_TIM1_Init(void);
static void MX_ADC2_Init(void);
static void MX_USART1_UART_Init(void);
static u8 work_time(void);
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);
extern uint8_t Receive_Buffer[64];
extern uint32_t Receive_length ;
extern uint32_t length ;
uint8_t Send_Buffer[64];
uint32_t packet_sent=1;
uint32_t packet_receive=1;
u16 time_for_state_memory_left;
u16 time_for_state_memory_midle;
/* USER CODE END 0 */
int main(void){
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_IWDG_Init();
MX_RTC_Init();
MX_TIM1_Init();
USB_Interrupts_Config();
USB_Init();
MX_ADC2_Init();
MX_USART1_UART_Init();
init_frame_struct(0);
HAL_GPIO_WritePin(GPIOA,BIT(5),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOA,BIT(4),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOB,BIT(0),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOB,BIT(1),GPIO_PIN_SET);
time_ms = uwTick;
config = 0;
HAL_IWDG_Start(&hiwdg);
motor_init(GPIOB,8,9,12,&motor_two);
motor_init(GPIOB,10,11,13,&motor_one);
frame_init();
u32 timer;
timer = uwTick;
speed_control = uwTick;
lenta = 1;
while (1){
HAL_IWDG_Refresh(&hiwdg);
if (config & STEP_TIME){
config &=~STEP_TIME;
if (settings.vars.state!=STOPED_TIME){
frame_control_hadler();
}
step_motor_control(&motor_one);
step_motor_control(&motor_two);
if(time_for_state_memory_left){
time_for_state_memory_left--;
}else{
settings.vars.init_state &= ~DID_LEFT_OPT;
}
if(time_for_state_memory_midle){
time_for_state_memory_midle--;
}else{
settings.vars.init_state &= ~DID_MIDLE_OPT;
}
}
if(uwTick>(timer+1000)){
timer = uwTick;
}
if (bDeviceState == CONFIGURED){
CDC_Receive_DATA();
/*Check to see if we have data yet */
if (Receive_length != 0){
receive_packet_hanling(Receive_Buffer);
/* if (packet_sent == 1){
CDC_Send_DATA ((unsigned char*)Receive_Buffer,Receive_length);
}*/
Receive_length = 0;
}
}
/* if (settings.vars.usb_tranceiver_state & USB_RECIVE_OR_TRANSMIT_PACKET){
settings.vars.usb_tranceiver_state &= ~USB_RECIVE_OR_TRANSMIT_PACKET;
receive_packet_hanling(UserRxBufferFS);
}*/
if (config & SECOND){
config &= ~SECOND;
if ((work_time()==0) && (settings.vars.state!=STOPED_TIME)){
settings.vars.state=STOPED_TIME;
stop_rotate(&motor_one);
stop_rotate(&motor_two);
disable_led();
}else if(work_time()&&(settings.vars.state==STOPED_TIME)){
break_to_init();
}
}
HAL_RTC_GetTime(&hrtc, &Time, RTC_FORMAT_BCD);
HAL_RTC_GetDate(&hrtc, &Date, RTC_FORMAT_BCD);
}
}
/** System Clock Configuration
*/
void SystemClock_Config(void){
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_PeriphCLKInitTypeDef PeriphClkInit;
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_HSE
|RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.LSEState = RCC_LSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.LSIState = RCC_LSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK){
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV4;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK){
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC|RCC_PERIPHCLK_ADC
|RCC_PERIPHCLK_USB;
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK){
Error_Handler();
}
/**Configure the Systick interrupt time
*/
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
/**Configure the Systick
*/
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
/* SysTick_IRQn interrupt configuration */
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* ADC2 init function */
static void MX_ADC2_Init(void){
ADC_ChannelConfTypeDef sConfig;
/**Common config
*/
hadc2.Instance = ADC2;
hadc2.Init.ScanConvMode = ADC_SCAN_DISABLE;
hadc2.Init.ContinuousConvMode = DISABLE;
hadc2.Init.DiscontinuousConvMode = DISABLE;
hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc2.Init.NbrOfConversion = 1;
if (HAL_ADC_Init(&hadc2) != HAL_OK){
Error_Handler();
}
/**Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = 1;
sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK){
Error_Handler();
}
}
/* IWDG init function */
static void MX_IWDG_Init(void)
{
hiwdg.Instance = IWDG;
hiwdg.Init.Prescaler = IWDG_PRESCALER_4;
hiwdg.Init.Reload = 4095;
if (HAL_IWDG_Init(&hiwdg) != HAL_OK)
{
Error_Handler();
}
}
/* RTC init function */
static void MX_RTC_Init(void){
RTC_TimeTypeDef sTime;
RTC_DateTypeDef DateToUpdate;
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_RCC_BKP_CLK_ENABLE();
HAL_PWR_EnableBkUpAccess();
/**Initialize RTC Only
*/
hrtc.Instance = RTC;
hrtc.Init.AsynchPrediv = RTC_AUTO_1_SECOND;
hrtc.Init.OutPut = RTC_OUTPUTSOURCE_ALARM;
if (HAL_RTC_Init(&hrtc) != HAL_OK){
Error_Handler();
}
/**Initialize RTC and set the Time and Date
*/
if(HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BCD)!= HAL_OK){
sTime.Hours = 0x1;
sTime.Minutes = 0x0;
sTime.Seconds = 0x0;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK){
Error_Handler();
}
}
BKP->DR1 = sTime.Hours;
BKP->DR2 = sTime.Minutes;
BKP->DR3 = sTime.Seconds;
if(HAL_RTC_GetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD)!=HAL_OK){
DateToUpdate.WeekDay = RTC_WEEKDAY_MONDAY;
DateToUpdate.Month = RTC_MONTH_JANUARY;
DateToUpdate.Date = 0x1;
DateToUpdate.Year = 0x0;
if (HAL_RTC_SetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
}
BKP->DR4 = DateToUpdate.WeekDay ;
BKP->DR5 = DateToUpdate.Month ;
BKP->DR6 = DateToUpdate.Date ;
BKP->DR7 = DateToUpdate.Year ;
}
/* TIM1 init function */
static void MX_TIM1_Init(void){
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig;
TIM_OC_InitTypeDef sConfigOC;
TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig;
htim1.Instance = TIM1;
htim1.Init.Prescaler = 0;
htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
htim1.Init.Period = 0;
htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim1.Init.RepetitionCounter = 0;
if (HAL_TIM_Base_Init(&htim1) != HAL_OK){
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK){
Error_Handler();
}
if (HAL_TIM_OC_Init(&htim1) != HAL_OK){
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK){
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_TIMING;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if (HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_1) != HAL_OK){
Error_Handler();
}
sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
sBreakDeadTimeConfig.DeadTime = 0;
sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
if (HAL_TIMEx_ConfigBreakDeadTime(&htim1, &sBreakDeadTimeConfig) != HAL_OK){
Error_Handler();
}
HAL_TIM_MspPostInit(&htim1);
}
/* USART1 init function */
static void MX_USART1_UART_Init(void){
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK){
Error_Handler();
}
}
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin : PA5,PA6,PA7 */
GPIO_InitStruct.Pin = GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PB8 dir motor 2
PB9 step motor 2
PB12 enable low is active
PB10 dir motor 1
PB11 step motor 1
PB13 enable low is active
PB14 pin reset
*/
GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : Pa4 led enable */
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
HAL_GPIO_WritePin(GPIOB, BIT(8)|BIT(9)|BIT(10)|BIT(11), GPIO_PIN_RESET);//dir step
HAL_GPIO_WritePin(GPIOB, BIT(12)|BIT(13), GPIO_PIN_RESET);//enable is active
HAL_GPIO_WritePin(GPIOB, BIT(14), GPIO_PIN_SET);//pin reset disable
HAL_GPIO_WritePin(GPIOA, BIT(4), GPIO_PIN_SET);//led disable
}
/* USER CODE BEGIN 4 */
u8 work_time(void){
RTC_TimeTypeDef sTime;
u16 min_up,min_down,min_current;
min_up = settings.vars.up_time.hour*60+settings.vars.up_time.min;
min_down = settings.vars.down_time.hour*60+settings.vars.down_time.min;
if(HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN)== HAL_OK){
min_current = sTime.Hours*60+sTime.Minutes;
}else{
min_current = 1442;
}
if ((min_up>1440)||(min_down>1440)||(min_current>1440)){
return 1;
}else{
if (min_up>min_down){
if ((min_current >= min_up)||(min_current < min_down)){
return 1;
}else{
return 0;
}
}else if(min_up<min_down){
if ((min_current >= min_up)&&(min_current < min_down)){
return 1;
}else{
return 0;
}
}else{
return 1;
}
}
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @param None
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler */
/* User can add his own implementation to report the HAL error return state */
BKP->DR7++;
while(1){
}
/* USER CODE END Error_Handler */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
BKP->DR8++;
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 27.859345 | 106 | 0.686216 |
3be905294edf9bfc655f7fbf8ad4593fdefc844e | 2,439 | c | C | Labs/08-project/project/project/gpio.c | mbs908/digitalelectronics | f5a674e245743cc8d71b0174f702afa12ac6a160 | [
"MIT"
] | null | null | null | Labs/08-project/project/project/gpio.c | mbs908/digitalelectronics | f5a674e245743cc8d71b0174f702afa12ac6a160 | [
"MIT"
] | null | null | null | Labs/08-project/project/project/gpio.c | mbs908/digitalelectronics | f5a674e245743cc8d71b0174f702afa12ac6a160 | [
"MIT"
] | null | null | null | /***********************************************************************
*
* GPIO library for AVR-GCC.
* ATmega328P (Arduino Uno), 16 MHz, AVR 8-bit Toolchain 3.6.2
*
* Copyright (c) 2019-2020 Tomas Fryza
* Dept. of Radio Electronics, Brno University of Technology, Czechia
* This work is licensed under the terms of the MIT license.
*
**********************************************************************/
/* Includes ----------------------------------------------------------*/
#include "gpio.h"
#include <util/delay.h> // Functions for busy-wait delay loops
#include <avr/io.h> // AVR device-specific IO definitions
#include <avr/sfr_defs.h>
/* Function definitions ----------------------------------------------*/
void GPIO_config_output(volatile uint8_t *reg_name, uint8_t pin_num)
{
*reg_name = *reg_name | (1<<pin_num);
}
/*--------------------------------------------------------------------*/
/* GPIO_config_input_nopull */
void GPIO_config_input_nopull(volatile uint8_t *reg_name, uint8_t pin_num){
*reg_name = *reg_name & ~(1<<pin_num); // Data Direction Register
*reg_name++; // Change pointer to Data Register
*reg_name = *reg_name & ~(1<<pin_num); // Data Register
}
/*--------------------------------------------------------------------*/
void GPIO_config_input_pullup(volatile uint8_t *reg_name, uint8_t pin_num)
{
*reg_name = *reg_name & ~(1<<pin_num); // Data Direction Register
*reg_name++; // Change pointer to Data Register
*reg_name = *reg_name | (1<<pin_num); // Data Register
}
/*--------------------------------------------------------------------*/
void GPIO_write_low(volatile uint8_t *reg_name, uint8_t pin_num)
{
*reg_name = *reg_name & ~(1<<pin_num);
}
/*--------------------------------------------------------------------*/
/* GPIO_write_high */
void GPIO_write_high(volatile uint8_t *reg_name, uint8_t pin_num){
*reg_name = *reg_name | (1<<pin_num);
}
/*--------------------------------------------------------------------*/
/* GPIO_toggle */
void GPIO_toggle(volatile uint8_t *reg_name, uint8_t pin_num){
*reg_name = *reg_name ^ (1<<pin_num);
}
/*--------------------------------------------------------------------*/
/* GPIO_read */
uint8_t GPIO_read(volatile uint8_t *reg_name, uint8_t pin_num){
uint8_t input;
if(bit_is_set(*reg_name,pin_num)){
input=1;
}
else{
input=0;
}
return(input);
} | 34.842857 | 75 | 0.491595 |
7450d6924deb3e4719ae721403dda0018d783d55 | 1,337 | kt | Kotlin | library/src/main/java/ru/anbazhan/library/recycler/BaseRVAdapter.kt | anbazhan/mvvmcore | 12e8dca66371b4b999cb96cf2287895d2615b9de | [
"MIT"
] | 4 | 2021-09-02T11:31:08.000Z | 2022-01-06T10:02:29.000Z | library/src/main/java/ru/anbazhan/library/recycler/BaseRVAdapter.kt | anbazhan/mvvmcore | 12e8dca66371b4b999cb96cf2287895d2615b9de | [
"MIT"
] | null | null | null | library/src/main/java/ru/anbazhan/library/recycler/BaseRVAdapter.kt | anbazhan/mvvmcore | 12e8dca66371b4b999cb96cf2287895d2615b9de | [
"MIT"
] | null | null | null | package ru.anbazhan.library.recycler
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
open class BaseRVAdapter<T, B : BindingItem<T>>(
var items: MutableList<B> = mutableListOf()
) : LiveDataBindingRVAdapter<BaseRVAdapter.ViewHolder>() {
override fun getItemViewType(position: Int): Int {
return getItem(position).layoutResource
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
viewType,
parent,
false
)
).apply { binding.lifecycleOwner = this }
}
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
getItem(position).let {
holder.binding.setVariable(it.brId, it.item)
}
}
fun getItem(position: Int): B {
return items[position]
}
open fun updateItems(items: MutableList<B>) {
this.items = items
notifyDataSetChanged()
}
open class ViewHolder(val binding: ViewDataBinding) :
LiveDataBindingRVAdapter.ViewHolder(binding.root)
} | 29.065217 | 83 | 0.66193 |
64e6e59afbe799d34fa97fda39687ed89d26deea | 81 | sql | SQL | src/katas/kyu8/register_for_the_party_SQL_for_beginners_3.sql | pimentelra/codewars | adb6ce4e49c5d9f93d9785a801988a25c815214a | [
"BSD-3-Clause"
] | null | null | null | src/katas/kyu8/register_for_the_party_SQL_for_beginners_3.sql | pimentelra/codewars | adb6ce4e49c5d9f93d9785a801988a25c815214a | [
"BSD-3-Clause"
] | null | null | null | src/katas/kyu8/register_for_the_party_SQL_for_beginners_3.sql | pimentelra/codewars | adb6ce4e49c5d9f93d9785a801988a25c815214a | [
"BSD-3-Clause"
] | null | null | null | INSERT INTO participants VALUES('name', '21', TRUE);
SELECT * FROM participants; | 27 | 52 | 0.740741 |
8ae0112ce6e0046e29295f6e54dc7d9b71e725f8 | 13,208 | rs | Rust | src/proc/bin/starnix/fs/tarfs.rs | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | src/proc/bin/starnix/fs/tarfs.rs | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | src/proc/bin/starnix/fs/tarfs.rs | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 Fabio D'Urso. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::Error;
use fuchsia_zircon as zx;
use log::warn;
use std::collections::HashMap;
use std::convert::TryInto;
use std::os::unix::ffi::OsStrExt;
use std::sync::Arc;
use std::sync::RwLock;
use super::*;
use crate::fs::{fileops_impl_directory, fs_node_impl_symlink};
use crate::task::CurrentTask;
use crate::types::*;
struct ZxioReader<'a> {
file: &'a syncio::Zxio,
}
impl<'a> ZxioReader<'a> {
fn new(file: &'a syncio::Zxio) -> ZxioReader<'a> {
ZxioReader { file }
}
}
impl<'a> std::io::Read for ZxioReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.file.read(buf).map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))
}
}
static WHITEOUT_PREFIX: &[u8] = b".wh.";
pub struct TarFilesystem {
tar_files: Vec<syncio::Zxio>,
inodes: RwLock<HashMap<ino_t, TarInode>>,
}
// If a PAX linkpath extension is present, it overrides the path contained in the regular fixed-size
// header. This usually happens when the path is too long to fit in it.
fn read_link_path<'a, R: 'a + std::io::Read>(
entry: &mut tar::Entry<'a, R>,
) -> Result<Vec<u8>, Error> {
if let Some(exts) = entry.pax_extensions()? {
for ext in exts {
let ext = ext?;
if ext.key_bytes() == b"linkpath" {
return Ok(ext.value_bytes().to_vec());
}
}
}
if let Some(link_name) = entry.link_name_bytes() {
return Ok(link_name.to_vec());
}
anyhow::bail!("Failed to read link name");
}
impl TarFilesystem {
pub fn new(tar_files: Vec<syncio::Zxio>) -> Result<FileSystemHandle, Error> {
let tar_fs = Arc::new(TarFilesystem { tar_files, inodes: RwLock::new(HashMap::new()) });
let tar_root = TarDirectory::new(Arc::clone(&tar_fs));
tar_fs.add_inode(TarInode::Directory(Arc::clone(&tar_root)));
let fs_handle = FileSystem::new(TarFileSystemOps);
fs_handle.set_root(tar_root.build_ops());
for (tar_file_index, tar_file) in tar_fs.tar_files.iter().enumerate() {
let mut archive = tar::Archive::new(ZxioReader::new(&tar_file));
let mut path_to_inode = HashMap::new(); // to resolve hard links
for tar_entry in archive.entries()? {
let mut tar_entry = tar_entry?;
// Split path into ancestors and name
let path = tar_entry.path()?.into_owned();
let (ancestors, name) = parse_path(&path)?;
let parent = get_or_create_parent_directory(
Arc::clone(&tar_root),
&ancestors,
tar_file_index,
)?;
let mut dentries_w = parent.dentries.write().unwrap();
// Handle whiteouts
if tar_file_index != 0 && name.starts_with(WHITEOUT_PREFIX) {
if name == b".wh..wh..opq" || name == b".wh.__dir_opaque" {
// Drop all dentries from previous tar files
dentries_w.retain(|_, (i, _)| tar_file_index == *i)
} else {
dentries_w.remove(&name[WHITEOUT_PREFIX.len()..]);
}
continue;
}
// Store and resolve tar entry to inode number
let inode_num = match tar_entry.header().entry_type() {
tar::EntryType::Directory => {
if dentries_w.contains_key(name) {
// Do not overwite existing directory from a previous layer. By keeping
// it, this layer's files will be merged into it.
continue;
}
let dir = TarDirectory::new(Arc::clone(&tar_fs));
tar_fs.add_inode(TarInode::Directory(dir))
}
tar::EntryType::Regular => {
let file = TarFile::new(
Arc::clone(&tar_fs),
tar_file_index,
tar_entry.raw_file_position(),
tar_entry.header().size()?,
);
tar_fs.add_inode(TarInode::File(file))
}
tar::EntryType::Link => {
let inode_num = path_to_inode.get(&read_link_path(&mut tar_entry)?);
if let Some(inode_num) = inode_num {
*inode_num
} else {
warn!("Skipping hard link that does not refer to an already-seen file");
continue;
}
}
tar::EntryType::Symlink => {
let symlink = TarSymlink::new(read_link_path(&mut tar_entry)?);
tar_fs.add_inode(TarInode::Symlink(symlink))
}
_ => {
warn!("Skipping tar entry type: {:?}", tar_entry.header().entry_type());
continue;
}
};
path_to_inode.insert(tar_entry.path_bytes().into_owned(), inode_num);
dentries_w.insert(name.to_owned(), (tar_file_index, inode_num));
}
}
// These directories must always exist
let extra_tar_file_index = tar_fs.tar_files.len();
get_or_create_parent_directory(Arc::clone(&tar_root), &[b"dev"], extra_tar_file_index)?;
get_or_create_parent_directory(Arc::clone(&tar_root), &[b"proc"], extra_tar_file_index)?;
get_or_create_parent_directory(Arc::clone(&tar_root), &[b"tmp"], extra_tar_file_index)?;
Ok(fs_handle)
}
fn add_inode(self: &Arc<TarFilesystem>, inode: TarInode) -> ino_t {
let mut inodes_w = self.inodes.write().unwrap();
let num = inodes_w.len() as ino_t + 1;
let r = inodes_w.insert(num, inode);
assert!(r.is_none()); // inode numbers must be unique
num
}
fn get_or_create_node(
self: &Arc<TarFilesystem>,
fs: &FileSystemHandle,
inode_num: ino_t,
) -> Result<FsNodeHandle, Errno> {
fs.get_or_create_node(Some(inode_num), |inode_num| {
let inodes_r = self.inodes.read().unwrap();
let inode = inodes_r.get(&inode_num).unwrap();
let (ops, mode) = match inode {
TarInode::Directory(dir) => (
Box::new(dir.build_ops()) as Box<dyn FsNodeOps>,
FileMode::IFDIR | FileMode::ALLOW_ALL,
),
TarInode::File(file) => (
Box::new(file.build_ops()) as Box<dyn FsNodeOps>,
FileMode::IFREG | FileMode::ALLOW_ALL,
),
TarInode::Symlink(symlink) => (
Box::new(symlink.build_ops()) as Box<dyn FsNodeOps>,
FileMode::IFLNK | FileMode::ALLOW_ALL,
),
};
let fs_node = FsNode::new(ops, fs, inode_num, mode);
if let TarInode::File(file) = inode {
fs_node.info_write().size = file.size.try_into().expect("file too big");
}
Ok(fs_node)
})
}
}
struct TarFileSystemOps;
impl FileSystemOps for TarFileSystemOps {}
enum TarInode {
Directory(Arc<TarDirectory>),
File(Arc<TarFile>),
Symlink(Arc<TarSymlink>),
}
struct TarDirectory {
fs: Arc<TarFilesystem>,
dentries: RwLock<HashMap<FsString, (usize, ino_t)>>,
}
impl TarDirectory {
fn new(fs: Arc<TarFilesystem>) -> Arc<TarDirectory> {
Arc::new(TarDirectory { fs, dentries: RwLock::new(HashMap::new()) })
}
fn build_ops(self: &Arc<TarDirectory>) -> TarDirectoryOps {
TarDirectoryOps { inner: Arc::clone(self) }
}
}
struct TarDirectoryOps {
inner: Arc<TarDirectory>,
}
impl FsNodeOps for TarDirectoryOps {
fn open(&self, _node: &FsNode, _flags: OpenFlags) -> Result<Box<dyn FileOps>, Errno> {
Ok(Box::new(TarDirectoryFileObject { inner: Arc::clone(&self.inner) }))
}
fn lookup(&self, node: &FsNode, name: &FsStr) -> Result<FsNodeHandle, Errno> {
let inode_num = if let Some((_, inode_num)) = self.inner.dentries.read().unwrap().get(name)
{
*inode_num
} else {
return error!(ENOENT);
};
self.inner.fs.get_or_create_node(&node.fs(), inode_num)
}
}
struct TarDirectoryFileObject {
inner: Arc<TarDirectory>,
}
impl FileOps for TarDirectoryFileObject {
fileops_impl_directory!();
fn seek(
&self,
file: &FileObject,
_current_task: &CurrentTask,
offset: off_t,
whence: SeekOrigin,
) -> Result<off_t, Errno> {
file.unbounded_seek(offset, whence)
}
fn readdir(
&self,
file: &FileObject,
_current_task: &CurrentTask,
sink: &mut dyn DirentSink,
) -> Result<(), Errno> {
let mut offset = file.offset.lock();
emit_dotdot(file, sink, &mut offset)?;
let dentries_r = self.inner.dentries.read().unwrap();
let iter = dentries_r.iter().skip((*offset - 2).try_into().map_err(|_| errno!(ENOMEM))?);
for (name, (_, inode_num)) in iter {
let next_offset = *offset + 1;
sink.add(*inode_num, next_offset, DirectoryEntryType::UNKNOWN, name)?;
*offset = next_offset;
}
Ok(())
}
}
struct TarFile {
fs: Arc<TarFilesystem>,
tar_file_index: usize,
offset: u64,
size: u64,
}
impl TarFile {
fn new(fs: Arc<TarFilesystem>, tar_file_index: usize, offset: u64, size: u64) -> Arc<TarFile> {
Arc::new(TarFile { fs, tar_file_index, offset, size })
}
fn build_ops(self: &Arc<TarFile>) -> TarFileOps {
TarFileOps { inner: Arc::clone(self) }
}
}
struct TarFileOps {
inner: Arc<TarFile>,
}
// based on ExtFile::open
impl FsNodeOps for TarFileOps {
fn open(&self, _node: &FsNode, _flags: OpenFlags) -> Result<Box<dyn FileOps>, Errno> {
let tar_file = &self.inner.fs.tar_files[self.inner.tar_file_index];
let vmo = zx::Vmo::create(self.inner.size).map_err(|_| errno!(ENOMEM))?;
// TODO: read in chunks to avoid allocating a single big buffer
let mut buffer = vec![0; self.inner.size as usize];
if tar_file.read_at(self.inner.offset, &mut buffer) != Ok(buffer.len()) {
panic!();
}
vmo.write(&buffer, 0).unwrap();
Ok(Box::new(VmoFileObject::new(Arc::new(vmo))))
}
}
struct TarSymlink {
target: FsString,
}
impl TarSymlink {
fn new(target: FsString) -> Arc<TarSymlink> {
Arc::new(TarSymlink { target })
}
fn build_ops(self: &Arc<TarSymlink>) -> TarSymlinkOps {
TarSymlinkOps { inner: Arc::clone(self) }
}
}
struct TarSymlinkOps {
inner: Arc<TarSymlink>,
}
impl FsNodeOps for TarSymlinkOps {
fs_node_impl_symlink!();
fn readlink(
&self,
_node: &FsNode,
_current_task: &CurrentTask,
) -> Result<SymlinkTarget, Errno> {
Ok(SymlinkTarget::Path(self.inner.target.clone()))
}
}
fn parse_path(path: &std::path::Path) -> Result<(Vec<&FsStr>, &FsStr), Error> {
let mut ancestors = Vec::new();
for c in path.components() {
if let std::path::Component::Normal(os_str) = c {
ancestors.push(os_str.as_bytes());
}
}
if let Some(name) = ancestors.pop() {
Ok((ancestors, name))
} else {
anyhow::bail!("path cannot be empty");
}
}
fn get_or_create_parent_directory(
current_dir: Arc<TarDirectory>,
path: &[&FsStr],
current_tar_file_index: usize,
) -> Result<Arc<TarDirectory>, Error> {
if path.len() == 0 {
return Ok(current_dir);
}
let fs = ¤t_dir.fs;
let head = path[0];
let tail = &path[1..];
// Lookup head
let mut dentries_w = current_dir.dentries.write().unwrap();
let head_dir = if let Some((tar_file_index, inode_num)) = dentries_w.get_mut(head) {
// Update the existing tar_file_index to prevent the dentry from being removed should an
// opaque whiteout occur to its parent directory in the current tar file.
*tar_file_index = current_tar_file_index;
let inodes_r = fs.inodes.read().unwrap();
if let TarInode::Directory(ref dir) = inodes_r.get(inode_num).unwrap() {
Arc::clone(dir)
} else {
anyhow::bail!("Cannot traverse non-directory {:?}", head);
}
} else {
let tar_directory = TarDirectory::new(Arc::clone(&fs));
let inode_num = fs.add_inode(TarInode::Directory(Arc::clone(&tar_directory)));
dentries_w.insert(head.to_owned(), (current_tar_file_index, inode_num));
tar_directory
};
get_or_create_parent_directory(head_dir, tail, current_tar_file_index)
}
| 32.937656 | 100 | 0.561024 |
afcda87aa2368dabf03f32c32a0058eb11a48f6b | 2,059 | swift | Swift | Patterns/Command.playground/Contents.swift | Xroyzen/swift-algorithm-app | dd4fb5931e7adb41445443c37397e916079de988 | [
"MIT"
] | null | null | null | Patterns/Command.playground/Contents.swift | Xroyzen/swift-algorithm-app | dd4fb5931e7adb41445443c37397e916079de988 | [
"MIT"
] | null | null | null | Patterns/Command.playground/Contents.swift | Xroyzen/swift-algorithm-app | dd4fb5931e7adb41445443c37397e916079de988 | [
"MIT"
] | null | null | null |
class Account {
var accountName: String
var balance: Int
init(accountName: String, balance: Int){
self.accountName = accountName
self.balance = balance
}
}
protocol Command {
func execute()
var isComplete: Bool { get set }
}
class Deposit: Command {
private var _account: Account
private var _amount: Int
var isComplete = false
init(account: Account, amount: Int){
self._account = account
self._amount = amount
}
func execute() {
_account.balance += _amount
isComplete = true
}
}
class Withdraw: Command {
private var _account: Account
private var _amount: Int
var isComplete = false
init(account: Account, amount: Int){
self._account = account
self._amount = amount
}
func execute() {
if _account.balance >= _amount {
_account.balance -= _amount
isComplete = true
}
else {
print("Not enough money")
}
}
}
class TransactionManager {
static let shared = TransactionManager()
private init() {}
private var _transaction: [Command] = []
var pendingTransactions: [Command] {
get {
return _transaction.filter{ $0.isComplete == false }
}
}
func addTransaction(command: Command){
_transaction.append(command)
}
func processingTransactions(){
_transaction.filter { $0.isComplete == false }.forEach{ $0.execute() }
}
}
// function main()...
let account = Account(accountName: "I'm", balance: 1000)
let transactionManager = TransactionManager.shared
transactionManager.addTransaction(command: Deposit(account: account, amount: 150))
transactionManager.addTransaction(command: Withdraw(account: account, amount: 250))
transactionManager.pendingTransactions
account.balance
transactionManager.processingTransactions()
transactionManager.pendingTransactions
account.balance
| 16.472 | 83 | 0.621661 |
31d0c7b304fda7e3ffa14de558453f43c8b8b9b3 | 1,331 | swift | Swift | XiaoHongshu_Swift/Classes/Other/AppDelegate.swift | SeekForSunny/XiaoHongshu_Swift | 25a6c422f9e9d96b1aaf02c87510b17c663f73ad | [
"MIT"
] | null | null | null | XiaoHongshu_Swift/Classes/Other/AppDelegate.swift | SeekForSunny/XiaoHongshu_Swift | 25a6c422f9e9d96b1aaf02c87510b17c663f73ad | [
"MIT"
] | null | null | null | XiaoHongshu_Swift/Classes/Other/AppDelegate.swift | SeekForSunny/XiaoHongshu_Swift | 25a6c422f9e9d96b1aaf02c87510b17c663f73ad | [
"MIT"
] | null | null | null | //
// AppDelegate.swift
// XiaoHongshu_Swift
//
// Created by SMART on 2017/7/6.
// Copyright © 2017年 com.smart.swift. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//获取接口信息
static func apiInfo() -> [String:Any] {
var dic:[String:Any] = [:]
if let path = Bundle.main.path(forResource: "api.json", ofType: nil){
if let data = NSData(contentsOfFile: path){
do {
if let info = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any]{
dic = info
}
} catch {
print(HomeIndexContentView.self,"Error",error);
}
}
}
return dic
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds);
window?.rootViewController = MainController();
window?.makeKeyAndVisible();
return true
}
}
| 25.596154 | 165 | 0.547708 |
e72c909dbe21feecbf02577df658c19581ea09ce | 3,155 | js | JavaScript | web/admin/supplier/pages/supplier_wallet/js/withdraw_deposit_ctrl.js | ITsunshineboys/myProject | c4248920882280b2fec10e0d01440e4240cb214a | [
"BSD-3-Clause"
] | null | null | null | web/admin/supplier/pages/supplier_wallet/js/withdraw_deposit_ctrl.js | ITsunshineboys/myProject | c4248920882280b2fec10e0d01440e4240cb214a | [
"BSD-3-Clause"
] | null | null | null | web/admin/supplier/pages/supplier_wallet/js/withdraw_deposit_ctrl.js | ITsunshineboys/myProject | c4248920882280b2fec10e0d01440e4240cb214a | [
"BSD-3-Clause"
] | null | null | null | /**
* Created by Administrator on 2017/9/25/025.
*/
let withdraw_deposit = angular.module("withdraw_depositModule", []);
withdraw_deposit.controller("withdraw_deposit_ctrl", function (_ajax, $rootScope,$scope, $http, $state, $anchorScroll, $location, $window) {
$rootScope.crumbs = [{
name: '钱包',
icon: 'icon-qianbao',
link: 'supplier_wallet'
}, {
name: '商家账户信息',
link: 'supplier_account'
},{
name: '提现'
}];
let reg = /^\d+(\.\d{1,2})?$/; //金额正则
$scope.psdwarning = false;
$scope.moneywarning = false;
$scope.alljudgefalse = false;
$scope.moneyflag = false;
$scope.pwdflag = false;
$scope.money_num = '';
$scope.password = '';
totalMoney();
/*可提现金额*/
function totalMoney() {
_ajax.post('/withdrawals/find-supplier-balance',{},function (res) {
$scope.totalmoney = res.data;
})
}
/*确认提现*/
$scope.sureWithdraw = function (val, error) {
$scope.moneyflag = false;
$scope.moneywarning = false;
$scope.psdwarning = false;
$scope.pwdflag = false;
/*默认的情况*/
if (!val) {
$scope.alljudgefalse = true;
//循环错误,定位到第一次错误,并聚焦
for (let [key, value] of error.entries()) {
if (value.$invalid) {
$anchorScroll.yOffset = 150;
$location.hash(value.$name);
$anchorScroll();
$window.document.getElementById(value.$name).focus();
break;
}
}
return;
}
if(reg.test($scope.money_num)&&Number($scope.money_num)>0){
let data = {money: +$scope.money_num, pay_pwd: +$scope.password};
_ajax.post('/withdrawals/supplier-withdrawals-apply',data,function (res) {
switch (res.code)
{
case 1055:
$scope.psdwarning = true;
$scope.psdwrong = res.msg;
$scope.pwdflag = true;
break;
case 1054:
$scope.moneywarning = true;
$scope.moneywrong = res.msg;
$scope.moneyflag = true;
break;
case 1000:
$scope.failwarning = res.msg;
$("#withdraw_warning").modal('show');
$scope.backpage = false;
break;
case 200:
$scope.failwarning = "提现已提交,到账时间一般是3-5个工作日,如提现失败,请重新提现";
$("#withdraw_warning").modal('show');
$scope.backpage = true;
break;
}
})
}else{
$scope.moneywarning = true;
$scope.moneywrong = '您的输入不正确,请重新输入';
$scope.moneyflag = true;
}
}
/*成功后返回上一页面*/
$scope.backpPage = () => {
setTimeout(() => {
$state.go("supplier_account")
}, 200);
}
}) | 31.868687 | 140 | 0.460856 |
dd43a5c114b469f822003c3ea35523f246d78e9f | 17,871 | go | Go | go/client/cmd_ctl_nix.go | yan0908/client | 2debd54aa01e01f91cb5ef81104b1932a5cd681f | [
"BSD-3-Clause"
] | 6 | 2019-11-04T17:14:31.000Z | 2019-12-05T01:59:42.000Z | go/client/cmd_ctl_nix.go | joergpanke/client | e310b28b4e58987ffb1228650d35e07b9a379669 | [
"BSD-3-Clause"
] | 8 | 2021-01-28T21:27:26.000Z | 2022-03-28T21:54:15.000Z | go/client/cmd_ctl_nix.go | joergpanke/client | e310b28b4e58987ffb1228650d35e07b9a379669 | [
"BSD-3-Clause"
] | 1 | 2021-02-01T08:11:17.000Z | 2021-02-01T08:11:17.000Z | // Copyright 2019 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
// +build !darwin,!windows
package client
import (
"fmt"
"io"
"os"
"os/exec"
"syscall"
"github.com/keybase/cli"
"github.com/keybase/client/go/install"
"github.com/keybase/client/go/libcmdline"
"github.com/keybase/client/go/libkb"
)
const backtick = "`"
type CmdCtlAutostart struct {
libkb.Contextified
ToggleOn bool
}
func NewCmdCtlAutostart(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
cmd := &CmdCtlAutostart{
Contextified: libkb.NewContextified(g),
}
return cli.Command{
Name: "autostart",
Usage: `Configure autostart settings via the XDG autostart standard.
This creates a file at ~/.config/autostart/keybase.desktop.
If you change this file after initial install, it will not be changed unless
you run ` + backtick + `keybase ctl autostart` + backtick + ` or delete
the sentinel file at ~/.config/keybase/autostart_created.
If you are using a headless machine or a minimal window manager that doesn't
respect this standard, you will need to configure autostart in another way.
If you are running Keybase on a headless machine using systemd, you may be
interested in enabling the systemd user manager units keybase.service and
kbfs.service: ` + backtick + `systemctl --user enable keybase kbfs
keybase-redirector` + backtick + `.
`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "enable",
Usage: "Toggle on Keybase, KBFS, and GUI autostart on startup.",
},
cli.BoolFlag{
Name: "disable",
Usage: "Toggle off Keybase, KBFS, and GUI autostart on startup.",
},
},
ArgumentHelp: "",
Action: func(c *cli.Context) {
cl.ChooseCommand(cmd, "autostart", c)
cl.SetForkCmd(libcmdline.NoFork)
cl.SetLogForward(libcmdline.LogForwardNone)
},
}
}
func (c *CmdCtlAutostart) ParseArgv(ctx *cli.Context) error {
toggleOn := ctx.Bool("enable")
toggleOff := ctx.Bool("disable")
if toggleOn && toggleOff {
return fmt.Errorf("Cannot specify both --enable and --disable.")
}
if !toggleOn && !toggleOff {
return fmt.Errorf("Must specify either --enable or --disable.")
}
c.ToggleOn = toggleOn
return nil
}
func (c *CmdCtlAutostart) Run() error {
err := install.ToggleAutostart(c.G(), c.ToggleOn, false)
if err != nil {
return err
}
return nil
}
func (c *CmdCtlAutostart) GetUsage() libkb.Usage {
return libkb.Usage{
Config: true,
API: true,
}
}
type CmdCtlRedirector struct {
libkb.Contextified
ToggleOn bool
Status bool
RootRedirectorMount string
RootConfigFilename string
RootConfigDirectory string
}
func NewCmdCtlRedirector(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
cmd := &CmdCtlRedirector{
Contextified: libkb.NewContextified(g),
}
return cli.Command{
Name: "redirector",
Usage: `Configure keybase-redirector settings.
This option requires root privileges, and must use the root config file
at /etc/keybase/config.json.
The Keybase redirector allows every user to access KBFS files at /keybase,
which will show different information depending on the requester.
Enabling the root redirector will set suid root on /usr/bin/keybase-redirector,
allowing any user to run it with root privileges. It is enabled by default.
If the redirector is disabled, you can still access your files in the mount
directory given by ` + backtick + `keybase config get -d -b mountdir` + backtick + `,
which is owned by your user, but you won't be able to access your files at
/keybase.
More information is available at
https://keybase.io/docs/kbfs/understanding_kbfs#mountpoints.
Examples (prepend sudo, if not root):
` + backtick + backtick + backtick + `
keybase --use-root-config-file ctl redirector --status
keybase --use-root-config-file ctl redirector --enable
keybase --use-root-config-file ctl redirector --disable
` + backtick + backtick + backtick + `
`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "status",
Usage: "Print whether the KBFS redirector is enabled or disabled.",
},
cli.BoolFlag{
Name: "enable",
Usage: "Toggle on the KBFS redirector.",
},
cli.BoolFlag{
Name: "disable",
Usage: "Toggle off the KBFS redirector.",
},
},
ArgumentHelp: "",
Action: func(c *cli.Context) {
cl.ChooseCommand(cmd, "redirector", c)
cl.SetForkCmd(libcmdline.NoFork)
cl.SetLogForward(libcmdline.LogForwardNone)
},
}
}
func xor3(a, b, c bool) (ret bool) {
ret = ret != a
ret = ret != b
ret = ret != c
return ret
}
func (c *CmdCtlRedirector) ParseArgv(ctx *cli.Context) error {
toggleOn := ctx.Bool("enable")
toggleOff := ctx.Bool("disable")
status := ctx.Bool("status")
if !xor3(toggleOn, toggleOff, status) || (toggleOn && toggleOff && status) {
return fmt.Errorf("Must specify exactly one of --enable, --disable, --status.")
}
c.ToggleOn = toggleOn
c.Status = status
return nil
}
func (c *CmdCtlRedirector) isRedirectorEnabled() (bool, error) {
config := c.G().Env.GetConfig()
if config == nil {
return false, fmt.Errorf("could not get config reader")
}
i, err := config.GetInterfaceAtPath(libkb.DisableRootRedirectorConfigKey)
if err != nil {
// Config key or file nonexistent, but possibly other errors as well.
return true, nil
}
val, ok := i.(bool)
if !ok {
return false, fmt.Errorf("config corruption: not a boolean value; please delete the %s key in %s manually.",
libkb.DisableRootRedirectorConfigKey, c.RootConfigFilename)
}
return !val, nil
}
func redirectorPerm(toggleOn bool) uint32 {
if toggleOn {
// suid set; octal.
return 04755
}
// suid unset; octal.
return 0755
}
func (c *CmdCtlRedirector) createMount() error {
rootMountPerm := 0755 | os.ModeDir
mountedPerm := 0555 | os.ModeDir // permissions different when mounted
fileInfo, err := os.Stat(c.RootRedirectorMount)
switch {
case os.IsNotExist(err):
err := os.Mkdir(c.RootRedirectorMount, rootMountPerm)
if err != nil {
c.G().Log.Errorf("Failed to create mountpoint at %s: %s", c.RootRedirectorMount, err)
return err
}
fmt.Println("Redirector mount created.")
case err == nil:
c.G().Log.Warning("Root mount already exists; will not re-create.")
if fileInfo.Mode() != rootMountPerm && fileInfo.Mode() != mountedPerm {
return fmt.Errorf("Root mount exists at %s, but has incorrect file mode %s. Delete %s and try again.",
c.RootRedirectorMount, fileInfo.Mode(), c.RootRedirectorMount)
}
dir, err := os.Open(c.RootRedirectorMount)
if err != nil {
return fmt.Errorf("Root mount exists at %s, but failed to open: %s. Delete %s and try again.", c.RootRedirectorMount, err, c.RootRedirectorMount)
}
defer dir.Close()
_, err = dir.Readdir(1)
switch err {
case io.EOF:
// doesn't fall-through.
case nil:
return fmt.Errorf("Root mount exists at %s, but is non-empty (is the redirector currently running?). Run `# pkill -f keybase-redirector`, delete directory %s and try again.", c.RootRedirectorMount, c.RootRedirectorMount)
default:
return fmt.Errorf("Unexpected error while reading %s: %s", c.RootRedirectorMount, err)
}
default:
c.G().Log.Errorf("Unexpected error while trying to stat mount: %s", err)
return err
}
return nil
}
func (c *CmdCtlRedirector) deleteMount() error {
err := os.Remove(c.RootRedirectorMount)
switch {
case os.IsNotExist(err):
c.G().Log.Warning("Root mountdir already nonexistent.")
case err == nil:
fmt.Println("Redirector mount deletion successful.")
default:
c.G().Log.Errorf("Failed to delete mountpoint at %s: %s", c.RootRedirectorMount, err)
c.G().Log.Errorf("If KBFS is not being used, run `# pkill -f keybase-redirector`, delete %s and try again.", c.RootRedirectorMount)
return err
}
return nil
}
func (c *CmdCtlRedirector) tryAtomicallySetConfigAndChmodRedirector(originallyEnabled bool) error {
configWriter := c.G().Env.GetConfigWriter()
if configWriter == nil {
return fmt.Errorf("could not get config writer")
}
// By default, writing a config file uses libkb.PermFile which is only readable by the creator.
// Since we're writing to the root config file, re-allow other users to read it.
defer func() {
// Don't check if err != nil here, since we want this to run even if, e.g.,
// the syscall.Chmod call failed.
_ = os.Chmod(c.RootConfigDirectory, 0755|os.ModeDir)
_ = os.Chmod(c.RootConfigFilename, 0644)
}()
err := configWriter.SetBoolAtPath(libkb.DisableRootRedirectorConfigKey, !c.ToggleOn)
if err != nil {
c.G().Log.Errorf("Failed to write to %s. Do you have root privileges?", c.RootConfigFilename)
return err
}
redirectorPath, err := exec.LookPath("keybase-redirector")
if err != nil {
c.G().Log.Warning("configuration successful, but keybase-redirector not found in $PATH (it may not be installed), so not updating permissions.")
return nil
}
// os.Chmod doesn't work with suid bit, so use syscall.
err = syscall.Chmod(redirectorPath, redirectorPerm(c.ToggleOn))
if err != nil {
// If flipping bit, attempt to restore old config value to maintain consistency between config and redirector mode.
if originallyEnabled != c.ToggleOn {
configErr := configWriter.SetBoolAtPath(libkb.DisableRootRedirectorConfigKey, !originallyEnabled)
if configErr != nil {
c.G().Log.Errorf("Failed to revert config after chmod failure; config may be in inconsistent state.")
return fmt.Errorf("Error during chmod: %s. Error during config revert: %s.", err, configErr)
}
}
return err
}
return nil
}
func (c *CmdCtlRedirector) configureEnv() error {
rootRedirectorMount, err := c.G().Env.GetRootRedirectorMount()
if err != nil {
return err
}
c.RootRedirectorMount = rootRedirectorMount
rootConfigFilename, err := c.G().Env.GetRootConfigFilename()
if err != nil {
return err
}
c.RootConfigFilename = rootConfigFilename
if c.RootConfigFilename != c.G().Env.GetConfigFilename() {
return fmt.Errorf("Must specify --use-root-config-file to `keybase`.")
}
return nil
}
func (c *CmdCtlRedirector) Run() error {
// Don't do this setup in ParseArgv because environment variables have not
// yet been populated then.
err := c.configureEnv()
if err != nil {
return err
}
rootConfigDirectory, err := c.G().Env.GetRootConfigDirectory()
if err != nil {
return err
}
c.RootConfigDirectory = rootConfigDirectory
enabled, err := c.isRedirectorEnabled()
if err != nil {
return err
}
if c.Status {
if enabled {
fmt.Println("enabled")
} else {
fmt.Println("disabled")
}
return nil
}
err = c.tryAtomicallySetConfigAndChmodRedirector(enabled)
if err != nil {
return err
}
fmt.Println("Redirector configuration updated.")
if c.ToggleOn {
err := c.createMount()
if err != nil {
return err
}
fmt.Println("Please run `run_keybase` to start the redirector for each user using KBFS.")
} else {
err := c.deleteMount()
if err != nil {
return err
}
fmt.Println("Please run `# pkill -f keybase-redirector` to stop the redirector for all users.")
}
return nil
}
func (c *CmdCtlRedirector) GetUsage() libkb.Usage {
return libkb.Usage{
Config: true,
API: true,
AllowRoot: true,
}
}
type CmdCtlInit struct {
libkb.Contextified
DryRun bool
}
func NewCmdCtlInit(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
cmd := &CmdCtlInit{
Contextified: libkb.NewContextified(g),
}
return cli.Command{
Name: "init",
Usage: `Set up initial Keybase configuration.
Performed by ` + backtick + `run_keybase` + backtick + ` automatically.
Execute this command first, preferably before each time Keybase is started, to
avoid using run_keybase.
Among other things, sets up a environment file for Keybase processes to use,
which is needed in init systems like systemd which hide the user environment
from its processes by default. If environment variables change, this command
must be executed again.
`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "dry-run",
Usage: "Print a human-readable description of what will occur without writing any changes to disk. Do not parse.",
},
},
ArgumentHelp: "",
Action: func(c *cli.Context) {
cl.ChooseCommand(cmd, "init", c)
cl.SetForkCmd(libcmdline.NoFork)
cl.SetLogForward(libcmdline.LogForwardNone)
},
}
}
func (c *CmdCtlInit) ParseArgv(ctx *cli.Context) error {
c.DryRun = ctx.Bool("dry-run")
return nil
}
type EnvSetting struct {
Name string
Value *string
Unset bool
}
func (c *CmdCtlInit) Envs() []EnvSetting {
strPtr := func(s string) *string { return &s }
return []EnvSetting{
// This is for the system tray icon in new versions of Ubuntu that do not use Unity.
// See https://github.com/electron/electron/issues/10887.
{Name: "XDG_CURRENT_DESKTOP", Value: strPtr("Unity")},
// * This section is for the Keybase GUI.
// Some older distros (e.g. Ubuntu 16.04) don't make X session variables
// available to user units automatically. Whitelisting them is safer than
// dumping the entire environment, even though there's a chance we might
// miss something, because some environment variables might contain
// passwords or keys. Hopefully this section won't be needed someday.
// (Arch Linux doesn't need it today.)
// See: graphical-session.target.
{Name: "DISPLAY", Value: nil},
{Name: "XAUTHORITY", Value: nil},
// * This section is for the Keybase GUI.
// The following enable CJK and other alternative input methods.
// See https://github.com/keybase/client/issues/9861.
{Name: "CLUTTER_IM_MODULE", Value: nil},
{Name: "GTK_IM_MODULE", Value: nil},
{Name: "QT_IM_MODULE", Value: nil},
{Name: "QT4_IM_MODULE", Value: nil},
{Name: "XMODIFIERS", Value: nil},
// * This section is for the Keybase GUI.
// Arbitrary environment variables from bashrc and similar aren't
// automatically available in the systemd session, and users probably
// didn't use pam to define their XDG directories. Export them just in
// case.
{Name: "XDG_DOWNLOAD_DIR", Value: nil},
// * This section is for the service, KBFS, and the Keybase GUI.
{Name: "XDG_CACHE_HOME", Value: nil},
{Name: "XDG_CONFIG_HOME", Value: nil},
{Name: "XDG_DATA_HOME", Value: nil},
{Name: "XDG_RUNTIME_DIR", Value: nil},
{Name: "DBUS_SESSION_BUS_ADDRESS", Value: nil},
}
}
// We can't really use environment generators for this because... If
// systemd version is before 233 (e.g., in Ubuntu 16.04 LTS), environment
// generators are unsupported. Also, by design, environment generators are
// not able to get user environment variables which might be specified,
// e.g., in a interactive shell file (rather than in say pam_environment).
// Thus, we always manually create the environment file again. It should
// only be needed once during every login to populate that file, after
// that, as long as they don't change, systemctl will work without
// run_keybase. Work around by directly creating an environment file that
// unit files read. If a user really doesn't want to use run_keybase, they
// can specify their environment variables in a more standard way and
// import $DISPLAY and $KEYBASE_AUTOSTART into the user manager environment
// themselves, if the GUI is needed. # (graphical-session.target doesn't
// have great support either) We don't do this *and* the environment
// generator because we don't want to pollute the user manager environment
// with bad data. If stable, user can pipe this to a local config file to
// remove this need.
func (c *CmdCtlInit) RunEnv() error {
envs := c.Envs()
envfileName, err := c.G().Env.GetEnvfileName()
if err != nil {
return err
}
overrideEnvfileName, err := c.G().Env.GetOverrideEnvfileName()
if err != nil {
return err
}
s := "# Autogenerated by `keybase ctl init`; do not edit.\n"
s += "# Only used when running Keybase via systemd user manager.\n"
s += fmt.Sprintf("# To override individual variables, write to %s\n", overrideEnvfileName)
for _, env := range envs {
if env.Value == nil {
val, ok := os.LookupEnv(env.Name)
env.Value = &val
env.Unset = !ok
}
if env.Unset {
s += fmt.Sprintf("# %s (unset)\n", env.Name)
} else {
s += fmt.Sprintf("%s=%s\n", env.Name, *env.Value)
}
}
if c.DryRun {
fmt.Printf("Writing following text to %s...\n", envfileName)
fmt.Print(s)
} else {
dir, err := c.G().Env.GetEnvFileDir()
if err != nil {
return err
}
err = os.MkdirAll(dir, 0755)
if err != nil {
return err
}
envfile, err := os.OpenFile(envfileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
_, err = envfile.WriteString(s)
if err != nil {
return err
}
}
return nil
}
func (c *CmdCtlInit) Run() error {
err := c.RunEnv()
if err != nil {
return err
}
return nil
}
func (c *CmdCtlInit) GetUsage() libkb.Usage {
return libkb.Usage{
Config: true,
API: true,
}
}
type CmdCtlWantsSystemd struct {
libkb.Contextified
}
func NewCmdCtlWantsSystemd(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
cmd := &CmdCtlWantsSystemd{
Contextified: libkb.NewContextified(g),
}
return cli.Command{
Name: "wants-systemd",
// no Usage to hide command
// returns 0 iff systemd management is wanted
Flags: []cli.Flag{},
ArgumentHelp: "",
Action: func(c *cli.Context) {
cl.ChooseCommand(cmd, "wants-systemd", c)
cl.SetForkCmd(libcmdline.NoFork)
cl.SetLogForward(libcmdline.LogForwardNone)
},
}
}
func (c *CmdCtlWantsSystemd) ParseArgv(ctx *cli.Context) error {
return nil
}
func (c *CmdCtlWantsSystemd) Run() error {
// Modeless so output is given in devel
on := c.G().Env.ModelessWantsSystemd()
if !on {
return fmt.Errorf("Systemd not wanted.")
}
return nil
}
func (c *CmdCtlWantsSystemd) GetUsage() libkb.Usage {
return libkb.Usage{
Config: true,
API: true,
}
}
| 29.884615 | 223 | 0.703542 |
ec24bb53988377ed990b6ad0aa5867c1ede391ea | 595 | sql | SQL | sql/V40__Criacao_Tabela_Ferias.sql | ualisonaguiar/ordem-servico-datainfo | e3245f7c5fca2989ebded0beac5522d6427b4243 | [
"BSD-3-Clause"
] | null | null | null | sql/V40__Criacao_Tabela_Ferias.sql | ualisonaguiar/ordem-servico-datainfo | e3245f7c5fca2989ebded0beac5522d6427b4243 | [
"BSD-3-Clause"
] | null | null | null | sql/V40__Criacao_Tabela_Ferias.sql | ualisonaguiar/ordem-servico-datainfo | e3245f7c5fca2989ebded0beac5522d6427b4243 | [
"BSD-3-Clause"
] | null | null | null | CREATE TABLE tb_ferias (
id_ferias INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL,
id_usuario INTEGER REFERENCES tb_usuario (id_usuario)
NOT NULL,
dt_inicio DATE NOT NULL,
dt_fim DATE NOT NULL,
id_usuario_alteracao INTEGER REFERENCES tb_usuario (id_usuario)
NOT NULL,
dt_alteracao DATETIME NOT NULL
);
CREATE UNIQUE INDEX uk_usuario_periodicidade ON tb_ferias (
id_usuario,
dt_inicio,
dt_fim
);
| 33.055556 | 68 | 0.546218 |
7a3e85cfe560e3c617b26261739450a2d96403eb | 84 | rb | Ruby | lib/mina/hooks/version.rb | elskwid/mina-hooks | 51abffa10fdb7e43c15ccf7bde518b44d1db3e7e | [
"MIT"
] | 10 | 2015-03-31T21:37:16.000Z | 2021-06-03T18:45:48.000Z | lib/mina/hooks/version.rb | elskwid/mina-hooks | 51abffa10fdb7e43c15ccf7bde518b44d1db3e7e | [
"MIT"
] | 3 | 2015-01-23T09:13:09.000Z | 2017-07-16T13:54:10.000Z | lib/mina/hooks/version.rb | elskwid/mina-hooks | 51abffa10fdb7e43c15ccf7bde518b44d1db3e7e | [
"MIT"
] | 8 | 2015-12-24T06:17:23.000Z | 2018-11-19T12:35:29.000Z | module Mina
module Hooks
# mina-hooks version
VERSION = "0.2.1"
end
end
| 12 | 24 | 0.630952 |
29077d6526e6872758f4f7ff19d3e36abd645065 | 3,452 | py | Python | sobi_route_to_gpx.py | loisaidasam/sobi-save-to-strava | cc9958d699dc266fc6f1cdde0bec570da901b531 | [
"MIT"
] | null | null | null | sobi_route_to_gpx.py | loisaidasam/sobi-save-to-strava | cc9958d699dc266fc6f1cdde0bec570da901b531 | [
"MIT"
] | null | null | null | sobi_route_to_gpx.py | loisaidasam/sobi-save-to-strava | cc9958d699dc266fc6f1cdde0bec570da901b531 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import argparse
import datetime
import json
import gpxpy.gpx
import pytz
TIMEZONE_DEFAULT = 'America/New_York'
# This is the `gpxpy`'s default `creator` value:
# CREATOR_DEFAULT = 'gpx.py -- https://github.com/tkrajina/gpxpy'
# TODO: Come up with our own, something like this:
# CREATOR_DEFAULT = 'sobi-route-to-gpx.py -- https://github.com/loisaidasam/sobi-route-to-gpx'
CREATOR_DEFAULT = None
def main():
args = parse_args()
with open(args.route_filename, 'r') as fp:
route = json.load(fp)
timezone = args.timezone and pytz.timezone(args.timezone) or None
gpx = convert(route, timezone)
if args.creator:
gpx.creator = args.creator
print gpx.to_xml()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('route_filename',
help="The filename of a JSON file representing a SoBi route")
# TODO: Use `route`'s `start_time` / `finish_time` for auto-detecting timezone
parser.add_argument('--timezone',
default=TIMEZONE_DEFAULT,
help="The timezone the coordinates came from. Default: '%s'" % TIMEZONE_DEFAULT)
parser.add_argument('--creator',
default=CREATOR_DEFAULT,
help="A custom value for the base gpx element's 'creator' attribute")
return parser.parse_args()
def convert(route, timezone):
"""Convert a JSON representation of a SoBi route into a gpxpy.gpx.GPX object
"""
# TODO: Determine good values for `name`/`description`
name = "SoBi route #%s" % route['id']
description = None
# The GPX object
gpx = gpxpy.gpx.GPX()
# The GPXTrack
gpx_track = gpxpy.gpx.GPXTrack(name=name, description=description)
gpx.tracks.append(gpx_track)
# The GPXTrackSegment
gpx_segment = gpxpy.gpx.GPXTrackSegment()
gpx_track.segments.append(gpx_segment)
# Now add all of the coordinate data
coordinates = route_coordinates_generator(route, timezone)
for coordinate in coordinates:
trackpoint = gpxpy.gpx.GPXTrackPoint(**coordinate)
gpx_segment.points.append(trackpoint)
return gpx
def route_coordinates_generator(route, timezone):
"""
{
"path": {
"type": "LineString",
"coordinates": [
[
-84.36963166666666,
33.746605,
1549299522
],
...
}
"""
# Make sure the route looks like we think it should
path = route['path']
# Not sure what other types can be here:
assert path['type'] == "LineString"
for coordinate in path['coordinates']:
yield format_route_path_coordinate(coordinate, timezone)
def format_route_path_coordinate(coordinate, timezone):
"""
Params:
coordinate::tuple(
longitude::float
latitude::float
timestamp::int
A timezone-naive local timestamp
)
timezone::datetime.tzinfo
Returns:
::dict{
latitude::float
longitude::float
time::datetime.datetime
}
"""
longitude, latitude, timestamp = coordinate
time = datetime.datetime.fromtimestamp(timestamp, tz=timezone)
time_utc = time.astimezone(pytz.utc)
return {
'latitude': latitude,
'longitude': longitude,
'time': time_utc,
}
if __name__ == '__main__':
main()
| 29.008403 | 104 | 0.628331 |
40d2360d3963958839c90bdfd05ac309545e2583 | 463 | html | HTML | themes/vocabulary_theme/templates/authors.html | Aakash2408/creativecommons.github.io-source | cb9c138de69d29be85061525318027bba9100e01 | [
"MIT"
] | 70 | 2019-03-06T16:16:07.000Z | 2022-03-15T22:41:12.000Z | themes/vocabulary_theme/templates/authors.html | Aakash2408/creativecommons.github.io-source | cb9c138de69d29be85061525318027bba9100e01 | [
"MIT"
] | 326 | 2019-01-31T16:44:44.000Z | 2022-03-09T21:59:07.000Z | themes/vocabulary_theme/templates/authors.html | Aakash2408/creativecommons.github.io-source | cb9c138de69d29be85061525318027bba9100e01 | [
"MIT"
] | 158 | 2019-02-08T13:37:32.000Z | 2022-03-15T22:41:18.000Z | {% extends "layout.html" %}
{% from "macros/authors.html" import render_authors %}
{% block title %} Authors {% endblock %}
{% block body %}
<div class="all-authors">
<div class="header">
<h1 class="container">Authors</h1>
</div>
<div class="authors-list">
<div class="container">
<div class="columns is-multiline is-mobile">
{{ render_authors(this) }}
</div>
</div>
</div>
</div>
{% endblock %}
| 22.047619 | 54 | 0.561555 |
749824db1f395d734cf6936f24ff4c0576d41c00 | 470 | rs | Rust | src/html/frontend/tag.rs | axumrs/axum-rs | 019b0df81f7dad76dac93708a2b8072465d27053 | [
"MIT"
] | 6 | 2021-11-09T13:32:10.000Z | 2022-03-16T05:52:13.000Z | src/html/frontend/tag.rs | axumrs/axum-rs | 019b0df81f7dad76dac93708a2b8072465d27053 | [
"MIT"
] | 1 | 2021-11-09T13:30:05.000Z | 2022-01-01T05:59:38.000Z | src/html/frontend/tag.rs | axumrs/axum-rs | 019b0df81f7dad76dac93708a2b8072465d27053 | [
"MIT"
] | 2 | 2021-12-14T15:11:23.000Z | 2022-01-15T05:48:26.000Z | use askama::Template;
use crate::{
db::pagination::Pagination,
model::{SubjectTopicWithTagsAndTopicSummary, Tag},
};
#[derive(Template)]
#[template(path = "frontend/tag/index.html")]
pub struct IndexTemplate {
pub tags: Vec<Tag>,
}
#[derive(Template)]
#[template(path = "frontend/tag/topics.html")]
pub struct TopicsTemplate {
pub page: u32,
pub list: Pagination<Vec<SubjectTopicWithTagsAndTopicSummary>>,
pub name: String,
pub tag: Tag,
}
| 22.380952 | 67 | 0.697872 |
3f458a8c47f6ff21107209d52cbedab142c64a3f | 769 | swift | Swift | VietNamToGo/Models/Places/Places+CoreDataProperties.swift | frtlupsvn/Vietnam-To-Go | be011dcd6b4b26108ff48799529f114cbae60f72 | [
"MIT"
] | null | null | null | VietNamToGo/Models/Places/Places+CoreDataProperties.swift | frtlupsvn/Vietnam-To-Go | be011dcd6b4b26108ff48799529f114cbae60f72 | [
"MIT"
] | null | null | null | VietNamToGo/Models/Places/Places+CoreDataProperties.swift | frtlupsvn/Vietnam-To-Go | be011dcd6b4b26108ff48799529f114cbae60f72 | [
"MIT"
] | null | null | null | //
// Places+CoreDataProperties.swift
// Fuot
//
// Created by Zoom Nguyen on 1/4/16.
// Copyright © 2016 Zoom Nguyen. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Places {
@NSManaged var namePlace: String?
@NSManaged var othernamePlace: String?
@NSManaged var descriptionPlace: String?
@NSManaged var estimationPlace: NSNumber?
@NSManaged var longtitude: NSNumber?
@NSManaged var latitude: NSNumber?
@NSManaged var imageUrlPlace: String?
@NSManaged var objectId: String?
@NSManaged var updatedAt: NSDate?
@NSManaged var createdAt: NSDate?
}
| 26.517241 | 76 | 0.728218 |
d27b3d81ae52dca9394cf68d2dcc2d16d4c09750 | 4,826 | php | PHP | models/MArticle.php | yjhu/wowewe | 176519a44a329bf611576683cac238845ac3e8e5 | [
"BSD-3-Clause"
] | 1 | 2017-04-12T13:16:03.000Z | 2017-04-12T13:16:03.000Z | models/MArticle.php | yjhu/wowewe | 176519a44a329bf611576683cac238845ac3e8e5 | [
"BSD-3-Clause"
] | 1 | 2015-10-16T09:33:24.000Z | 2015-10-16T09:33:24.000Z | models/MArticle.php | yjhu/wowewe | 176519a44a329bf611576683cac238845ac3e8e5 | [
"BSD-3-Clause"
] | 2 | 2016-01-30T17:59:03.000Z | 2021-08-29T10:14:58.000Z | <?php
namespace app\models;
use Yii;
use yii\helpers\Url;
use yii\helpers\FileHelper;
use yii\imagine\Image;
use app\models\MArticle;
use app\models\MArticleMultArticle;
/*
DROP TABLE IF EXISTS wx_article;
CREATE TABLE IF NOT EXISTS wx_article (
gh_id VARCHAR(32) NOT NULL DEFAULT '',
article_id int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
photo_id int(10) unsigned NOT NULL DEFAULT '0',
title VARCHAR(128) NOT NULL DEFAULT '' COMMENT '标题',
author VARCHAR(64) NOT NULL DEFAULT '' COMMENT '作者',
digest VARCHAR(256) NOT NULL DEFAULT '',
content text NOT NULL DEFAULT '',
content_source_url VARCHAR(256) NOT NULL DEFAULT '' COMMENT '原文链接',
show_cover_pic tinyint(3) unsigned NOT NULL DEFAULT 0,
create_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
*/
class MArticle extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'wx_article';
}
public function rules()
{
return [
[['create_time', 'photo_id', 'article_id', 'gh_id'], 'safe'],
[['title'], 'string', 'max' => 128],
[['content'], 'string'],
[['show_cover_pic'], 'integer'],
[['author', 'digest', 'content_source_url'], 'string', 'max' => 256]
];
}
public function attributeLabels()
{
return [
'article_id' => Yii::t('app', 'Article ID'),
'title' => Yii::t('app', 'Title'),
'pic_url' => Yii::t('app', 'Pic Url'),
'create_time' => Yii::t('app', 'Create Time'),
];
}
public function getPhoto()
{
return $this->hasOne(MPhoto::className(), ['photo_id' => 'photo_id']);
}
public function getArticleMultArticles()
{
return $this->hasMany(MArticleMultArticle::className(), ['article_id' => 'article_id']);
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($insert) {
$this->gh_id = Yii::$app->user->gh->gh_id;
}
return true;
}
return false;
}
public function afterDelete()
{
foreach($this->articleMultArticles as $articleMultArticle) {
$articleMultArticle->delete();
}
parent::afterDelete();
}
public function getResp($wechat)
{
$FromUserName = $wechat->getRequest('FromUserName');
$openid = $wechat->getRequest('FromUserName');
$gh_id = $wechat->getRequest('ToUserName');
$MsgType = $wechat->getRequest('MsgType');
$Event = $wechat->getRequest('Event');
$EventKey = $wechat->getRequest('EventKey');
$user = $wechat->getUser();
$dict = [
'{nickname}' => empty($user->nickname) ? '' : $user->nickname,
'{openid}' => $openid,
'{gh_id}' => $gh_id,
];
$title = strtr($this->title, $dict);
$description = strtr($this->content, $dict);
$picUrl = empty($this->photo) ? '' : $this->photo->getPicUrl();
$url = strtr($this->content_source_url, $dict);
$items = [
new RespNewsItem($title, $description, $picUrl, $url),
];
return $wechat->responseNews($items);
}
public function getMediaId()
{
$wechat = Yii::$app->user->getWechat();
$articles = [
['thumb_media_id' =>$this->photo->getMediaId(), 'author' =>$this->author, 'title' =>$this->title,'content_source_url' =>$this->content_source_url,'content' =>$this->content,'digest' =>$this->digest, 'show_cover_pic'=>$this->show_cover_pic]
];
$arr = $wechat->WxMediaUploadNews($articles);
return $arr['media_id'];
}
public function messageCustomSend($openids)
{
$wechat = Yii::$app->user->getWechat();
$articles = [
['title'=>$this->title, 'description'=>$this->content, 'url'=>$this->content_source_url, 'picurl'=>$this->photo->getPicUrl()]
];
foreach($openids as $openid) {
$arr = $wechat->WxMessageCustomSendNews($openid, $articles);
}
}
public function messageMassSend($openids)
{
$wechat = Yii::$app->user->getWechat();
$media_id = $this->getMediaId();
$wechat->WxMessageMassSendNews($openids, $media_id);
}
public function messageMassPreview($openid)
{
$wechat = Yii::$app->user->getWechat();
$media_id = $this->getMediaId();
$wechat->WxMessageMassPreviewNews($openid, $media_id);
}
public function messageMassSendByGroupid($group_id)
{
$wechat = Yii::$app->user->getWechat();
$media_id = $this->getMediaId();
$wechat->WxMessageMassSendNewsByGroupid($group_id, $media_id);
}
}
| 30.738854 | 251 | 0.581641 |
5b87b5b4b6d6f7b5453617ce38299c233cc53ebc | 3,377 | swift | Swift | KCD/CommandRegister.swift | masakih/KCD | fa6a0a0b51735ab1f9a4caef2dc9bad3ec09bd9e | [
"BSD-2-Clause"
] | null | null | null | KCD/CommandRegister.swift | masakih/KCD | fa6a0a0b51735ab1f9a4caef2dc9bad3ec09bd9e | [
"BSD-2-Clause"
] | null | null | null | KCD/CommandRegister.swift | masakih/KCD | fa6a0a0b51735ab1f9a4caef2dc9bad3ec09bd9e | [
"BSD-2-Clause"
] | null | null | null | //
// CommandRegister.swift
// KCD
//
// Created by Hori,Masaki on 2017/01/08.
// Copyright © 2017年 Hori,Masaki. All rights reserved.
//
import Cocoa
enum JSONCommandError: Error {
case canNotFindCommand
}
final class CommandRegister {
private static var registeredClasses: [JSONCommand.Type] = []
class func register() {
registerClass(Start2Command.self)
registerClass(MemberNDockCommand.self)
registerClass(MemberKDockCommand.self)
registerClass(MemberDeckCommand.self)
registerClass(MemberMaterialCommand.self)
registerClass(MemberBasicCommand.self)
registerClass(MemberShipCommand.self)
registerClass(MemberSlotItemCommand.self)
registerClass(MemberShip2Command.self)
registerClass(MemberShip3Command.self)
registerClass(MemberRequireInfoCommand.self)
registerClass(CreateShipCommand.self)
registerClass(DestroyItem2Command.self)
registerClass(MapStartCommand.self)
registerClass(BattleCommand.self)
registerClass(GuardShelterCommand.self)
registerClass(MapInfoCommand.self)
registerClass(SetPlaneCommand.self)
registerClass(SetActionCommand.self)
registerClass(CreateSlotItemCommand.self)
registerClass(GetShipCommand.self)
registerClass(DestroyShipCommand.self)
registerClass(PowerUpCommand.self)
registerClass(RemodelSlotCommand.self)
registerClass(ShipDeckCommand.self)
registerClass(ChangeHenseiCommand.self)
registerClass(KaisouLockCommand.self)
registerClass(SlotResetCommand.self)
registerClass(CombinedCommand.self)
registerClass(SlotDepriveCommand.self)
registerClass(QuestListCommand.self)
registerClass(ClearItemGetComand.self)
registerClass(NyukyoStartCommand.self)
registerClass(HokyuChargeCommand.self)
registerClass(NyukyoSpeedChangeCommand.self)
registerClass(PortCommand.self)
registerClass(AirCorpsSupplyCommand.self)
registerClass(AirCorpsChangeNameCommand.self)
}
class func command(for response: APIResponse) -> JSONCommand {
func concreteCommand(for response: APIResponse) -> JSONCommand {
if !response.success {
return FailedCommand(apiResponse: response)
}
if IgnoreCommand.canExecuteAPI(response.api) {
return IgnoreCommand(apiResponse: response)
}
if let c = registeredClasses.first(where: { $0.canExecuteAPI(response.api) }) {
return c.init(apiResponse: response)
}
return UnknownComand(apiResponse: response)
}
#if ENABLE_JSON_LOG
return JSONViewCommand(apiResponse: response, command: concreteCommand(for: response))
#else
return concreteCommand(for: response)
#endif
}
class func registerClass(_ commandClass: JSONCommand.Type) {
if registeredClasses.contains(where: { $0 == commandClass }) {
return
}
registeredClasses.append(commandClass)
}
}
| 32.161905 | 98 | 0.645247 |
a194e83b82f05d3c3cacd302ad01bd0ce7a8bef8 | 728 | h | C | sdk/engine/include/ui/IUI.h | NcStudios/NcEngine | ce04eca00211b50188d80e59604bfa67bb9c15b6 | [
"MIT"
] | null | null | null | sdk/engine/include/ui/IUI.h | NcStudios/NcEngine | ce04eca00211b50188d80e59604bfa67bb9c15b6 | [
"MIT"
] | 3 | 2022-03-26T15:14:43.000Z | 2022-03-27T16:12:53.000Z | sdk/engine/include/ui/IUI.h | NcStudios/NcEngine | ce04eca00211b50188d80e59604bfa67bb9c15b6 | [
"MIT"
] | null | null | null | #pragma once
#include "UIElement.h"
namespace nc::ui
{
/** @note For internal use only. Derived classes should
* inherit from UIFlexible or UIFixed. */
class IUI
{
public:
virtual ~IUI() = default;
virtual void Draw() = 0;
virtual bool IsHovered() = 0;
};
class UIFlexible : public IUI, public UIElement
{
public:
UIFlexible()
: UIElement(true)
{
}
};
class UIFixed : public IUI, public UIFixedElement
{
public:
UIFixed(UIPosition position, Vector2 dimensions)
: UIFixedElement(true, position, dimensions)
{
}
};
} | 21.411765 | 60 | 0.512363 |
85fd01be825199cfec5c725b39b000a536ea4a5a | 548 | h | C | 大麦/Classes/Show/Model/ShowRequestModel.h | LoveZYForever/DaMai | 70cbf4a58610cc08d2eb535126c8bf3e7150d9d4 | [
"MIT"
] | 1 | 2021-01-19T14:48:44.000Z | 2021-01-19T14:48:44.000Z | 大麦/Classes/Show/Model/ShowRequestModel.h | SilenceLove/DaMai | 70cbf4a58610cc08d2eb535126c8bf3e7150d9d4 | [
"MIT"
] | null | null | null | 大麦/Classes/Show/Model/ShowRequestModel.h | SilenceLove/DaMai | 70cbf4a58610cc08d2eb535126c8bf3e7150d9d4 | [
"MIT"
] | 1 | 2019-11-02T06:13:18.000Z | 2019-11-02T06:13:18.000Z | //
// ShowRequestModel.h
// 大麦
//
// Created by 洪欣 on 16/12/21.
// Copyright © 2016年 洪欣. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ShowRequestModel : NSObject
@property (copy, nonatomic) NSString *EndTime;
@property (copy, nonatomic) NSString *StartTime;
@property (copy, nonatomic) NSString *cc;
@property (copy, nonatomic) NSString *cityid;
@property (copy, nonatomic) NSString *mc;
@property (copy, nonatomic) NSString *ot;
@property (copy, nonatomic) NSString *p;
@property (copy, nonatomic) NSString *ps;
@end
| 26.095238 | 48 | 0.724453 |
06de4c69da31f4cc50133fdaaaf6307f7a57885b | 302 | sql | SQL | Aula3/handsOn_03C.sql | arthurnovello/Banco-de-Dados-2019 | e0ef70d8d10400d02b0316ca40d0888466b142e0 | [
"MIT"
] | 2 | 2019-03-22T13:02:07.000Z | 2019-04-20T17:58:15.000Z | Aula3/handsOn_03C.sql | arthurnovello/Banco-de-Dados-2019 | e0ef70d8d10400d02b0316ca40d0888466b142e0 | [
"MIT"
] | null | null | null | Aula3/handsOn_03C.sql | arthurnovello/Banco-de-Dados-2019 | e0ef70d8d10400d02b0316ca40d0888466b142e0 | [
"MIT"
] | null | null | null | CREATE TABLE TABG (
V1 CHAR (20),
V2 VARCHAR (20),
V3 INT PRIMARY KEY
);
INSERT INTO TABG VALUES ('MAUA', 'COMP', 10);
INSERT INTO TABG VALUES ('ABC', 'XY', 23);
INSERT INTO TABG VALUES ('ANA', 'PAULO', 25);
INSERT INTO TABG VALUES ('PEDRO', 'JOSE', 34);
INSERT INTO TABG VALUES ('SOUZA', 'IVO', 5); | 30.2 | 46 | 0.649007 |
67aa911286e2e7bef378176953f4c5827368dcba | 14,289 | swift | Swift | Turn Touch iOS/Modes/Ifttt/TTModeIfttt.swift | samuelclay/turntouch-ios | f0cc0e3819cd1e7ca568c4fe55c37c8dddad02ff | [
"MIT"
] | 8 | 2019-01-06T15:38:15.000Z | 2021-07-31T15:19:08.000Z | Turn Touch iOS/Modes/Ifttt/TTModeIfttt.swift | samuelclay/turntouch-ios | f0cc0e3819cd1e7ca568c4fe55c37c8dddad02ff | [
"MIT"
] | 10 | 2019-07-31T23:35:51.000Z | 2020-11-19T00:45:01.000Z | Turn Touch iOS/Modes/Ifttt/TTModeIfttt.swift | samuelclay/turntouch-ios | f0cc0e3819cd1e7ca568c4fe55c37c8dddad02ff | [
"MIT"
] | null | null | null | //
// TTModeIfttt.swift
// Turn Touch iOS
//
// Created by Samuel Clay on 12/30/16.
// Copyright © 2016 Turn Touch. All rights reserved.
//
import UIKit
import SafariServices
import Alamofire
struct TTModeIftttConstants {
static let kIftttUserIdKey = "TT:IFTTT:shared_user_id"
static let kIftttDeviceIdKey = "TT:IFTTT:device_id"
static let kIftttIsActionSetup = "isActionSetup"
static let kIftttTapType = "tapType"
}
enum TTIftttState {
case disconnected
case connecting
case connected
}
protocol TTModeIftttDelegate {
func changeState(_ state: TTIftttState, mode: TTModeIfttt)
}
class TTModeIfttt: TTMode {
var delegate: TTModeIftttDelegate!
static var IftttState = TTIftttState.disconnected
var oauthViewController: SFSafariViewController!
required init() {
super.init()
}
override class func title() -> String {
return "IFTTT"
}
override class func subtitle() -> String {
return "Buttons for If This Then That"
}
override class func imageName() -> String {
return "mode_ifttt.png"
}
// MARK: Actions
override class func actions() -> [String] {
return [
"TTModeIftttTriggerAction",
]
}
// MARK: Action titles
func titleTTModeIftttTriggerAction() -> String {
return "Trigger action"
}
// MARK: Action images
func imageTTModeIftttTriggerAction() -> String {
return "lightning"
}
// MARK: Defaults
override func defaultNorth() -> String {
return "TTModeIftttTriggerAction"
}
override func defaultEast() -> String {
return "TTModeIftttTriggerAction"
}
override func defaultWest() -> String {
return "TTModeIftttTriggerAction"
}
override func defaultSouth() -> String {
return "TTModeIftttTriggerAction"
}
// MARK: Action methods
override func activate() {
}
override func deactivate() {
}
func runTTModeIftttTriggerAction() {
self.trigger(doubleTap: false)
}
func doubleRunTTModeIftttTriggerAction() {
self.trigger(doubleTap: true)
}
func trigger(doubleTap: Bool) {
let modeName = type(of: self).title()
let modeDirection = appDelegate().modeMap.directionName(self.modeDirection)
let actionName = self.action.actionName
let actionTitle = self.actionTitleForAction(actionName!, buttonMoment: .button_MOMENT_PRESSUP)!
let actionDirection = appDelegate().modeMap.directionName(self.action.direction)
let tapType = self.action.optionValue(TTModeIftttConstants.kIftttTapType) as! String
let trigger = ["app_label": modeName,
"app_direction": modeDirection,
"button_label": actionTitle,
"button_direction": actionDirection,
"button_tap_type": tapType,
]
let params: [String: Any] = [
"user_id": appDelegate().modeMap.userId(),
"device_id": appDelegate().modeMap.deviceId(),
"triggers": [trigger],
]
Alamofire.request("https://turntouch.com/ifttt/button_trigger", method: .post,
parameters: params, encoding: JSONEncoding.default).responseJSON
{ response in
print(" ---> IFTTT Button trigger: \(response)")
}
}
func beginConnectingToIfttt() {
self.registerTriggers()
self.authorizeIfttt()
TTModeIfttt.IftttState = .connecting
delegate?.changeState(TTModeIfttt.IftttState, mode: self)
}
func authorizeIfttt() {
let attrs = appDelegate().modeMap.deviceAttrs() as! [String: String]
let params = (attrs.compactMap({ (key, value) -> String in
return "\(key)=\(value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)"
}) as Array).joined(separator: "&")
let url = "https://turntouch.com/ifttt/begin?\(params)"
oauthViewController = SFSafariViewController(url: URL(string: url)!, configuration: SFSafariViewController.Configuration())
oauthViewController.modalPresentationStyle = .formSheet
appDelegate().mainViewController.present(oauthViewController, animated: true, completion: nil)
}
func openRecipe(direction: TTModeDirection) {
let modeDirection = appDelegate().modeMap.directionName(self.modeDirection)
let actionDirection = appDelegate().modeMap.directionName(direction)
var attrs = appDelegate().modeMap.deviceAttrs() as! [String: String]
attrs["app_direction"] = modeDirection
attrs["button_direction"] = actionDirection
let params = (attrs.compactMap({ (key, value) -> String in
return "\(key)=\(value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)"
}) as Array).joined(separator: "&")
let url = "https://turntouch.com/ifttt/open_recipe?\(params)"
oauthViewController = SFSafariViewController(url: URL(string: url)!, configuration: SFSafariViewController.Configuration())
oauthViewController.modalPresentationStyle = .formSheet
appDelegate().mainViewController.present(oauthViewController, animated: true, completion: nil)
}
func purgeRecipe(direction: TTModeDirection, callback: (() -> Void)? = nil) {
let modeDirection = appDelegate().modeMap.directionName(self.modeDirection)
let actionDirection = appDelegate().modeMap.directionName(direction)
var params = appDelegate().modeMap.deviceAttrs() as! [String: String]
params["app_direction"] = modeDirection
params["button_direction"] = actionDirection
print(" ---> Purging: \(params)")
Alamofire.request("https://turntouch.com/ifttt/purge_trigger", method: .post,
parameters: params, encoding: URLEncoding.default).responseJSON
{ response in
print(" ---> Purged: \(response)")
if let callback = callback {
callback()
}
}
}
func registerTriggers(callback: (() -> Void)? = nil) {
let triggers = self.collectTriggers()
let params: [String: Any] = [
"user_id": appDelegate().modeMap.userId(),
"device_id": appDelegate().modeMap.deviceId(),
"triggers": triggers,
]
print(" ---> Registering: \(params)")
Alamofire.request("https://turntouch.com/ifttt/register_triggers", method: .post,
parameters: params, encoding: JSONEncoding.default).responseJSON
{ response in
print(" ---> Registered: \(response)")
if let callback = callback {
callback()
}
}
}
func collectTriggers() -> [[String: String]] {
var triggers: [[String: String]] = []
let prefs = UserDefaults.standard
// Primary modes first
for modeDirection: TTModeDirection in [.north, .east, .west, .south] {
let mode = appDelegate().modeMap.modeInDirection(modeDirection)
let modeName = type(of: mode).title()
for actionDirection: TTModeDirection in [.north, .east, .west, .south] {
let actionName = mode.actionNameInDirection(actionDirection)
if actionName == "TTModeIftttTriggerAction" {
let tapType = self.actionOptionValue(TTModeIftttConstants.kIftttTapType,
actionName: actionName, direction: actionDirection) as! String
triggers.append(["app_label": modeName,
"app_direction": appDelegate().modeMap.directionName(modeDirection),
"button_label": self.actionTitleForAction(actionName, buttonMoment: .button_MOMENT_PRESSUP)!,
"button_direction": appDelegate().modeMap.directionName(actionDirection),
"button_tap_type": tapType,
])
}
let modeBatchActionKey = appDelegate().modeMap.batchActions.modeBatchActionKey(modeDirection: modeDirection,
actionDirection: actionDirection)
let batchActionKeys: [String]? = prefs.object(forKey: modeBatchActionKey) as? [String]
if let keys = batchActionKeys {
for batchActionKey in keys {
if batchActionKey.contains("TTModeIftttTriggerAction") {
let action = TTAction(batchActionKey: batchActionKey, direction: actionDirection)
action.mode.modeDirection = modeDirection
let tapType = action.mode.batchActionOptionValue(batchActionKey: batchActionKey,
optionName: TTModeIftttConstants.kIftttTapType,
actionName: action.actionName,
actionDirection: actionDirection) as! String
triggers.append(["app_label": modeName,
"app_direction": appDelegate().modeMap.directionName(modeDirection),
"button_label": mode.actionTitleForAction(actionName, buttonMoment: .button_MOMENT_PRESSUP)!,
"button_direction": appDelegate().modeMap.directionName(actionDirection),
"button_tap_type": tapType,
])
}
}
}
}
}
for modeDirection: TTModeDirection in [.single, .double, .hold] {
for actionDirection: TTModeDirection in [.north, .east, .west, .south] {
if let directionModeName = prefs.string(forKey: "TT:mode-\(appDelegate().modeMap.directionName(modeDirection)):\(appDelegate().modeMap.directionName(actionDirection))") {
let className = "Turn_Touch_iOS.\(directionModeName)"
let modeClass = NSClassFromString(className) as! TTMode.Type
let mode = modeClass.init()
mode.modeDirection = actionDirection;
let modeName = type(of: mode).title()
let actionName = mode.actionNameInDirection(actionDirection)
if actionName == "TTModeIftttTriggerAction" {
let tapType = self.actionOptionValue(TTModeIftttConstants.kIftttTapType,
actionName: actionName, direction: actionDirection) as! String
triggers.append(["app_label": modeName,
"app_direction": appDelegate().modeMap.directionName(modeDirection),
"button_label": self.actionTitleForAction(actionName, buttonMoment: .button_MOMENT_PRESSUP)!,
"button_direction": appDelegate().modeMap.directionName(actionDirection),
"button_tap_type": tapType,
])
}
let modeBatchActionKey = appDelegate().modeMap.batchActions.modeBatchActionKey(modeDirection: modeDirection,
actionDirection: actionDirection)
let batchActionKeys: [String]? = prefs.object(forKey: modeBatchActionKey) as? [String]
if let keys = batchActionKeys {
for batchActionKey in keys {
if batchActionKey.contains("TTModeIftttTriggerAction") {
let action = TTAction(batchActionKey: batchActionKey, direction: actionDirection)
action.mode.modeDirection = modeDirection
let tapType = action.mode.batchActionOptionValue(batchActionKey: batchActionKey,
optionName: TTModeIftttConstants.kIftttTapType,
actionName: action.actionName,
actionDirection: actionDirection) as! String
triggers.append(["app_label": modeName,
"app_direction": appDelegate().modeMap.directionName(modeDirection),
"button_label": mode.actionTitleForAction(actionName, buttonMoment: .button_MOMENT_PRESSUP)!,
"button_direction": appDelegate().modeMap.directionName(actionDirection),
"button_tap_type": tapType,
])
}
}
}
}
}
}
return triggers
}
func cancelConnectingToIfttt() {
TTModeIfttt.IftttState = .disconnected
delegate?.changeState(TTModeIfttt.IftttState, mode: self)
}
func IftttReady() {
TTModeIfttt.IftttState = .connected
delegate?.changeState(TTModeIfttt.IftttState, mode: self)
}
func logMessage(_ message: String) {
print(" ---> Ifttt API: \(message)")
}
}
| 44.653125 | 186 | 0.549794 |
9fbdfcd96c506100d29ce99bbb75354826b034c8 | 155 | kt | Kotlin | addscreen/src/main/java/kekmech/ru/addscreen/parser/ParserSchedule.kt | mazuninky/mpeiapp | ab24976df01c1cc469e0aaffaa515c3ffc9554ae | [
"MIT"
] | 1 | 2019-11-11T21:48:27.000Z | 2019-11-11T21:48:27.000Z | addscreen/src/main/java/kekmech/ru/addscreen/parser/ParserSchedule.kt | mazuninky/mpeiapp | ab24976df01c1cc469e0aaffaa515c3ffc9554ae | [
"MIT"
] | null | null | null | addscreen/src/main/java/kekmech/ru/addscreen/parser/ParserSchedule.kt | mazuninky/mpeiapp | ab24976df01c1cc469e0aaffaa515c3ffc9554ae | [
"MIT"
] | null | null | null | package kekmech.ru.addscreen.parser
import java.util.*
data class ParserSchedule(
val couples: List<ParserCouple>,
val firstCoupleDay: Calendar
) | 19.375 | 36 | 0.767742 |
9176edc93dfca6921fdf1566bee73219f335a940 | 525 | html | HTML | lib/naas/index.html | herry13/nuri | 6d3468f5213f60eebc82d8a3bd5960257fd33b4b | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | lib/naas/index.html | herry13/nuri | 6d3468f5213f60eebc82d8a3bd5960257fd33b4b | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | lib/naas/index.html | herry13/nuri | 6d3468f5213f60eebc82d8a3bd5960257fd33b4b | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | <html>
<head>
<title>Nuri as a Service</title>
<script src="jquery.js"></script>
<script src="d3.js"></script>
<script src="index.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="menu">
<a href="javascript:menu.specification();">Specification</a> |
<a href="javascript:menu.state();">State</a> |
<a href="javascript:menu.modules();">Modules</a> |
<a href="javascript:menu.logs();">Logs</a>
</div>
<div id="main">Hello World!</div>
</body>
</html>
| 27.631579 | 65 | 0.617143 |
c2ab6b80352bdaf18ba263127e7a1ae61cf8030d | 4,164 | go | Go | cmd/root.go | paul-nelson-baker/git-export-zip | 491494043f0424a90cdbb1dfd275a166dc62bf30 | [
"MIT"
] | null | null | null | cmd/root.go | paul-nelson-baker/git-export-zip | 491494043f0424a90cdbb1dfd275a166dc62bf30 | [
"MIT"
] | null | null | null | cmd/root.go | paul-nelson-baker/git-export-zip | 491494043f0424a90cdbb1dfd275a166dc62bf30 | [
"MIT"
] | null | null | null | /*
Copyright © 2020 Paul Nelson Baker
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
"github.com/iancoleman/strcase"
"github.com/spf13/cobra"
"github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
var cfgFile string
var rootCmd = &cobra.Command{
Use: "git-export-zip",
Short: "Export the current git HEAD as a zip file",
Long: `In the parent directory above the current git project,
a new zip file is created with the UTC date at the time
of action as well as the hash of the current commit. This
helps ensure that the file exported is easy to differentiate
from another zip. This is useful when iterating multiple days
and/or across many commits`,
Run: func(cmd *cobra.Command, args []string) {
gitRootDirCmd := exec.Command("git", "rev-parse", "--show-toplevel")
rootDirBytes, err := gitRootDirCmd.CombinedOutput()
if err != nil {
fmt.Printf("Could not determine current git hash: %v\n", err)
os.Exit(1)
}
gitBaseFilename := filepath.Base(strings.TrimSuffix(string(rootDirBytes), "\n"))
projectParentDirectory := path.Dir(string(rootDirBytes))
gitHeadHashCmd := exec.Command("git", "log", "--pretty=format:'%h'", "-n", "1")
hashBytes, err := gitHeadHashCmd.CombinedOutput()
if err != nil {
fmt.Printf("Could not determine HEAD commit hash: %v\n", err)
os.Exit(1)
}
hashValue := string(hashBytes[1 : len(hashBytes)-1])
formattedTimestamp := time.Now().UTC().Format("01-02-2006")
projectName := strcase.ToSnake(gitBaseFilename)
outputArchiveFilename := fmt.Sprintf("%s/%s-%s-%s.zip",
projectParentDirectory, projectName, formattedTimestamp, hashValue)
gitArchiveCmd := exec.Command("git", "archive", "-o", outputArchiveFilename, "HEAD")
gitArchiveCmd.Stdout = os.Stdout
gitArchiveCmd.Stdin = os.Stdin
gitArchiveCmd.Stderr = os.Stderr
if err := gitArchiveCmd.Run(); err != nil {
fmt.Printf("Could not export archive: %v\n", err)
os.Exit(1)
} else {
fmt.Printf("Exported to: %s", outputArchiveFilename)
}
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.git-export-zip.yaml)")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".git-export-zip" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".git-export-zip")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
| 33.580645 | 115 | 0.722863 |
c228ea7c961c10919d6b2957c364cbb87abecf9a | 5,367 | go | Go | generate_test.go | ismailmustafa/derivatex | 10616d1071af34d435d1e08fb20f6e806c9d85f3 | [
"MIT"
] | null | null | null | generate_test.go | ismailmustafa/derivatex | 10616d1071af34d435d1e08fb20f6e806c9d85f3 | [
"MIT"
] | null | null | null | generate_test.go | ismailmustafa/derivatex | 10616d1071af34d435d1e08fb20f6e806c9d85f3 | [
"MIT"
] | null | null | null | package main
import (
"math/rand"
"reflect"
"testing"
)
func Test_byteInBounds(t *testing.T) {
cases := []struct {
b byte
bounds []byteBounds
in bool
}{
{
byte(33),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
true,
},
{
byte(40),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
true,
},
{
byte(47),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
true,
},
{
byte(58),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
true,
},
{
byte(64),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
true,
},
{
byte(52),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
false,
},
{
byte(120),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
false,
},
{
byte(0),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
false,
},
{
byte(255),
[]byteBounds{byteBounds{33, 47}, byteBounds{58, 64}},
false,
},
}
for _, c := range cases {
out := byteInBounds(c.b, c.bounds)
if out != c.in {
t.Errorf("byteInBounds(%v, %v) == %v want %v", c.b, c.bounds, out, c.in)
}
}
}
func Test_byteAsciiType(t *testing.T) {
cases := []struct {
b byte
t asciiType
}{
{
byte(0),
asciiOther,
},
{
byte(33),
asciiSymbol,
},
{
byte(50),
asciiDigit,
},
{
byte(62),
asciiSymbol,
},
{
byte(68),
asciiUppercase,
},
{
byte(100),
asciiLowercase,
},
{
byte(125),
asciiSymbol,
},
{
byte(150),
asciiOther,
},
}
for _, c := range cases {
out := byteAsciiType(c.b)
if out != c.t {
t.Errorf("byteAsciiType(%v) == %v want %v", c.b, out, c.t)
}
}
}
func Test_shuffleAsciiOrder(t *testing.T) {
cases := []struct {
asciiOrder []asciiType
randSource rand.Source
shuffledAsciiOrder []asciiType
}{
{
[]asciiType{asciiLowercase},
rand.NewSource(1),
[]asciiType{asciiLowercase},
},
{
[]asciiType{asciiLowercase, asciiUppercase},
rand.NewSource(0),
[]asciiType{asciiLowercase, asciiUppercase},
},
{
[]asciiType{asciiLowercase, asciiUppercase},
rand.NewSource(1),
[]asciiType{asciiUppercase, asciiLowercase},
},
{
[]asciiType{asciiLowercase, asciiUppercase, asciiDigit},
rand.NewSource(10),
[]asciiType{asciiUppercase, asciiDigit, asciiLowercase},
},
{
[]asciiType{asciiLowercase, asciiUppercase, asciiSymbol},
rand.NewSource(2645),
[]asciiType{asciiSymbol, asciiLowercase, asciiUppercase},
},
{
[]asciiType{asciiLowercase, asciiUppercase, asciiDigit, asciiSymbol},
rand.NewSource(0),
[]asciiType{asciiDigit, asciiSymbol, asciiLowercase, asciiUppercase},
},
{
[]asciiType{asciiLowercase, asciiUppercase, asciiDigit, asciiSymbol},
rand.NewSource(1),
[]asciiType{asciiLowercase, asciiSymbol, asciiUppercase, asciiDigit},
},
}
for _, c := range cases {
shuffleAsciiOrder(&c.asciiOrder, c.randSource)
if !reflect.DeepEqual(c.asciiOrder, c.shuffledAsciiOrder) {
t.Errorf("shuffleAsciiOrder(&c.asciiOrder, c.randSource) == %v want %v", c.asciiOrder, c.shuffledAsciiOrder)
}
}
}
func Test_determinePassword(t *testing.T) {
cases := []struct {
masterDigest []byte
websiteName []byte
user []byte
passwordLength uint8
round uint16
unallowedCharacters unallowedCharactersType
password string
}{
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte(""),
0,
1,
unallowedCharactersType{},
``,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte(""),
2,
1,
unallowedCharactersType{},
`Fq`,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte(""),
4,
1,
unallowedCharactersType{},
`jA9;`,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte(""),
10,
1,
unallowedCharactersType{},
`U1b5&O/Zyu`,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("facebook"),
[]byte(""),
10,
1,
unallowedCharactersType{},
`Otf}Aw82T*`,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte(""),
50,
1,
unallowedCharactersType{},
`I7AlJ{/Ly69*qY~)V_O64N~k6a<mYp}9R~*x2a?p0P7w6y1NIr`,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte(""),
10,
1,
buildUnallowedCharacters(false, false, true, true, ""),
`<636/\/)38`,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte(""),
10,
1,
buildUnallowedCharacters(true, false, false, false, ""),
`j3nlfCL08L`,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte("a@b.com"),
50,
1,
unallowedCharactersType{},
`uT6AA,;l_bYe..5ly]4|n0g\D1tST39q4W!vH18E-?VuP78:iK`,
},
{
[]byte{17, 5, 2, 85, 178, 255, 0, 29},
[]byte("google"),
[]byte("b@b.com"),
50,
1,
unallowedCharactersType{},
`G;we2320ABKq2A12bD"w}XjS38J'jH~=tyI0gyj>#3oX:]8(}V`,
},
}
for _, c := range cases {
out := determinePassword(&c.masterDigest, c.websiteName, c.user, c.passwordLength, c.round, c.unallowedCharacters)
if out != c.password {
t.Errorf("byteAsciiType(%v, %s, %d) == %s want %s", c.masterDigest, string(c.websiteName), c.passwordLength, out, c.password)
}
}
}
| 19.659341 | 128 | 0.575182 |
8b4e81bf66c881cdb3da71fd3c7cd5fac1ccab3e | 7,557 | sql | SQL | db/sql/4347__create_view_vipunentk_sa_v_sa_6_3_Koulutuksen_jarjestajan_koko.sql | CSCfi/antero | e762c09e395cb01e334f2a04753ba983107ac7d7 | [
"MIT"
] | 6 | 2017-08-03T08:49:17.000Z | 2021-11-14T17:09:27.000Z | db_archive/sql_archive/4347__create_view_vipunentk_sa_v_sa_6_3_Koulutuksen_jarjestajan_koko.sql | CSC-IT-Center-for-Science/antero | 2835d7fd07cd7399a348033a6230d1b16634fb3b | [
"MIT"
] | 3 | 2017-05-03T08:45:42.000Z | 2020-10-27T06:30:40.000Z | db_archive/sql_archive/4347__create_view_vipunentk_sa_v_sa_6_3_Koulutuksen_jarjestajan_koko.sql | CSC-IT-Center-for-Science/antero | 2835d7fd07cd7399a348033a6230d1b16634fb3b | [
"MIT"
] | 4 | 2017-10-19T11:31:43.000Z | 2022-01-05T14:53:57.000Z | USE [Vipunen_koodisto]
GO
/****** Object: View [dbo].[v_koulutuksen_jarjestaja_koko] Script Date: 12.1.2021 6:16:45 ******/
DROP VIEW IF EXISTS [dbo].[v_koulutuksen_jarjestaja_koko]
GO
USE [VipunenTK_SA]
GO
DROP VIEW IF EXISTS [dbo].[v_sa_6_3_Koulutuksen_jarjestajan_koko]
GO
/****** Object: View [dbo].[v_koulutuksen_jarjestaja_koko] Script Date: 12.1.2021 6:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[v_sa_6_3_Koulutuksen_jarjestajan_koko] AS
--truncate table [ANTERO].[dw].[d_jarjestajankoko]
--insert into [ANTERO].[dw].[d_jarjestajankoko]
--select * from dbo.v_sa_6_3_Koulutuksen_jarjestajan_koko
--drop table if exists [ANTERO].[dw].[d_jarjestajankoko]
--select * into [ANTERO].[dw].[d_jarjestajankoko]
--from dbo.v_sa_6_3_Koulutuksen_jarjestajan_koko
SELECT id = ROW_NUMBER() over(order by tilv, jarj)
,[tilv] = cast(tilv as varchar(4))
,[jarj] = cast(jarj as varchar(10))
,[yopp01] = cast(coalesce(yopp01,0) as int)
,[yopp02] = cast(coalesce(yopp02,0) as int)
,[yopp19] = cast(coalesce(yopp19,0) as int)
,[yopp10] = cast(coalesce(yopp10,0) as int)
,[yopp21] = cast(coalesce(yopp21,0) as int)
,[yopp22] = cast(coalesce(yopp22,0) as int)
,[yopp31] = cast(coalesce(yopp31,0) as int)
,[yopp32] = cast(coalesce(yopp32,0) as int)
,[yopp33] = cast(coalesce(yopp33,0) as int)
,[yopp34] = cast(coalesce(yopp34,0) as int)
,[yopp35] = cast(coalesce(yopp35,0) as int)
,[yopp36] = cast(coalesce(yopp36,0) as int)
,[yopp37] = cast(coalesce(yopp37,0) as int)
,[yopp38] = cast(coalesce(yopp38,0) as int)
,[yopp91] = cast(coalesce(yopp91,0) as int)
,[yopp31ophal] = cast(coalesce(yopp31ophal,0) as int)
,[yopp32ophal] = cast(coalesce(yopp32ophal,0) as int)
,[yopp33ophal] = cast(coalesce(yopp33ophal,0) as int)
,[yopp34ophal] = cast(coalesce(yopp34ophal,0) as int)
,[yopp35ophal] = cast(coalesce(yopp35ophal,0) as int)
,[yopp36ophal] = cast(coalesce(yopp36ophal,0) as int)
,[yopp37ophal] = cast(coalesce(yopp37ophal,0) as int)
,[yopp38ophal] = cast(coalesce(yopp38ophal,0) as int)
,[source] = 'Tilastokeskus 6.3'
FROM (
--lisää uusi sopv tähän
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_20
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_19
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_18
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_17
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_16
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_15
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_14
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_13
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_12
UNION ALL
SELECT DISTINCT [tilv]
,[jarj]
,[yopp01]
,[yopp02]
,[yopp19]
,[yopp10]
,[yopp21]
,[yopp22]
,[yopp31]
,[yopp32]
,[yopp33]
,[yopp34]
,[yopp35]
,[yopp36]
,[yopp37]
,[yopp38]
,[yopp91]
,[yopp31ophal]
,[yopp32ophal]
,[yopp33ophal]
,[yopp34ophal]
,[yopp35ophal]
,[yopp36ophal]
,[yopp37ophal]
,[yopp38ophal]
FROM TK_H9098_CSC.dbo.TK_6_3_sopv_11
) KaikkiVuodet
--päivitä tarvittaessa
where 0 < [yopp01]+[yopp02]+[yopp19]+[yopp10]+[yopp21]+[yopp22]+[yopp31]+[yopp32]+[yopp33]+[yopp34]+[yopp35]+[yopp36]+[yopp37]+[yopp38]+[yopp91]+[yopp31ophal]+[yopp32ophal]+[yopp33ophal]+[yopp34ophal]+[yopp35ophal]+[yopp36ophal]+[yopp37ophal]+[yopp38ophal]
GO
use antero
| 20.933518 | 256 | 0.547042 |
1a6e6a5983baee1c69f3bc6141f2d66e2c57dde8 | 10,637 | rs | Rust | marwood/tests/core.rs | strtok/marwood | 21b80ec1373ea6520bac5c02cf136fc4d88e31d3 | [
"Apache-2.0",
"MIT"
] | 11 | 2022-01-02T22:29:17.000Z | 2022-03-06T21:32:54.000Z | marwood/tests/core.rs | strtok/lisp | 2a33501c603beebfe000c40f9da681185ecf3662 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-02-23T20:50:58.000Z | 2022-02-24T17:15:36.000Z | marwood/tests/core.rs | strtok/marwood | 21b80ec1373ea6520bac5c02cf136fc4d88e31d3 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-12-29T04:08:46.000Z | 2021-12-29T04:08:46.000Z | #[macro_use]
mod common;
use marwood::cell;
use marwood::cell::Cell;
use marwood::error::Error::{
InvalidProcedure, InvalidSyntax, InvalidUsePrimitive, UnquotedNil, VariableNotBound,
};
use marwood::lex;
use marwood::parse;
use marwood::vm::Vm;
#[test]
fn comments() {
evals![
"1 ;number one" => "1",
"(+ 10 ;adding 10\n 5;to the number 5\n)" => "15"
];
}
#[test]
fn eval_literal() {
evals![
"1" => "1",
"-10" => "-10",
"#t" => "#t",
"#f" => "#f",
"'()" => "()"
];
fails!["foo" => VariableNotBound("foo".into()),
"()" => UnquotedNil];
}
#[test]
fn eval_quote() {
evals![
"'1" => "1",
"'#t" => "#t",
"'#f" => "#f",
"'()" => "()",
"'(1 2 3)" => "(1 2 3)"
];
}
#[test]
fn procedure_display() {
prints![
"+" => "#<procedure:+>",
"(lambda (x y) (+ x y))" => "#<procedure:(λ (x y))>"
];
}
#[test]
fn if_expressions() {
evals![
"(if (list? '(1 2 3)) 'yep 'nope)" => "yep",
"(if (list? #t) 'yep 'nope)" => "nope",
"(if (list? '(1 2 3)) 'yep)" => "yep",
"(if (list? #t) 'yep)" => "#<void>"
];
}
#[test]
fn gc_cleans_intern_map() {
evals![
"'foo" => "foo",
"'foo" => "foo"
]
}
#[test]
fn invalid_procedure_calls() {
fails![
"(1 2 3)" => InvalidProcedure(cell![1]),
"((+ 1 1) 2 3)" => InvalidProcedure(cell![2])
];
}
#[test]
fn lambdas() {
evals![
"((lambda () 10))" => "10",
"(+ ((lambda () 50)) ((lambda () 100)))" => "150"
];
}
#[test]
fn tge_capturing_lambda() {
evals![
"(define x 100)" => "#<void>",
"(define y 50)" => "#<void>",
"((lambda () x))" => "100",
"(+ ((lambda () x)) ((lambda () y)))" => "150",
"(define x 1000)" => "#<void>",
"(define y 500)" => "#<void>",
"(+ ((lambda () x)) ((lambda () y)))" => "1500"
];
}
#[test]
fn lambda_with_args() {
// Identity
evals![
"(define identity (lambda (x) x))" => "#<void>",
"(identity '(1 2 3))" => "(1 2 3)"
];
// Two arg
evals![
"(define make-pair (lambda (x y) (cons x y)))" => "#<void>",
"(make-pair 'apples 'bananas)" => "(apples . bananas)"
];
// Mixed arg and global
evals![
"(define x 100)" => "#<void>",
"(define add-to-x (lambda (y) (+ x y)))" => "#<void>",
"(add-to-x 50)" => "150"
];
}
#[test]
fn lambda_operator_is_expression() {
evals![
"(define proc (lambda () add))" => "#<void>",
"(define add (lambda (x y) (+ x y)))" => "#<void>",
"((proc) 1 2)" => "3"
];
}
#[test]
fn iof_argument_capture() {
evals![
"(define make-adder (lambda (x) (lambda (y) (+ x y))))" => "#<void>",
"(define add-10 (make-adder 10))" => "#<void>",
"(add-10 20)" => "30"
];
}
#[test]
fn iof_environment_capture() {
evals![
"(define make-make-adder (lambda (x) (lambda (y) (lambda (z) (+ x y z)))))" => "#<void>",
"(define make-adder (make-make-adder 1000))" => "#<void>",
"(define add-1000-100 (make-adder 100))" => "#<void>",
"(add-1000-100 10)" => "1110"
];
evals![
"(define (make-make-adder x) (lambda (y) (lambda (z) (+ x y z))))" => "#<void>",
"(define make-adder (make-make-adder 1000))" => "#<void>",
"(define add-1000-100 (make-adder 100))" => "#<void>",
"(add-1000-100 10)" => "1110"
];
evals![
"(define f 0)" => "#<void>",
"(define (make-make-adder x) (lambda (y) (set! f (lambda (x) x)) (lambda (z) (+ x y z))))" => "#<void>",
"(define make-adder (make-make-adder 1000))" => "#<void>",
"(define add-1000-100 (make-adder 100))" => "#<void>",
"(add-1000-100 10)" => "1110"
];
}
#[test]
fn iof_environment_capture_with_first_class_procedure() {
evals![
"(define make-adder-adder (lambda (adder num) (lambda (n) (+ ((adder num) n)))))" => "#<void>",
"((make-adder-adder (lambda (i) (lambda (j) (+ i j))) 100) 1000)" => "1100"
];
}
#[test]
fn define_special_forms() {
evals![
"(define (make-adder x) (lambda (y) (+ x y)))" => "#<void>",
"(define add-10 (make-adder 10))" => "#<void>",
"(add-10 20)" => "30"
];
}
#[test]
fn vararg() {
evals![
"((lambda l l))" => "()",
"((lambda l l) 10)" => "(10)",
"((lambda l l) 10 20)" => "(10 20)"
];
evals![
"(define (list . a) a)" => "#<void>",
"(list)" => "()",
"(list 10)" => "(10)",
"(list 10 20)" => "(10 20)"
];
evals![
"((lambda (x . y) (cons x y)) 10)" => "(10 . ())",
"((lambda (x . y) (cons x y)) 10 20)" => "(10 . (20))",
"((lambda (x y . z) (cons (+ x y) z)) 10 20)" => "(30 . ())",
"((lambda (x y . z) (cons (+ x y) z)) 10 20 30)" => "(30 . (30))",
"((lambda (x y . z) (cons (+ x y) z)) 10 20 30 40)" => "(30 . (30 40))"
];
}
#[test]
fn tail_recursive() {
evals![r#"(define (nth l n)
(if (null? l) '()
(if (eq? n 0) (car l)
(nth (cdr l) (- n 1)))))"# => "#<void>",
"(nth '(1 2 3 4 5) 4)" => "5",
"(nth '(1 2 3 4 5) 5)" => "()"
];
}
#[test]
fn disallow_aliasing_syntactic_symbol() {
fails!["(define if 42)" => InvalidUsePrimitive("if".into())];
fails!["(define my-if if)" => InvalidUsePrimitive("if".into())];
fails!["(lambda (if) 42)" => InvalidUsePrimitive("if".into())];
}
#[test]
fn or() {
evals!["(or 5)" => "5"];
evals!["(or #f 5)" => "5"];
evals!["(or (eq? 1 2) 'apples)" => "apples"];
}
#[test]
fn and() {
evals!["(and 5)" => "5"];
evals!["(and #t 5)" => "5"];
evals!["(and #f 5)" => "#f"];
evals!["(and #t #t 5)" => "5"];
}
#[test]
fn begin() {
evals!["(begin (+ 10 10) (+ 20 20) (+ 5 5))" => "10"];
}
#[test]
fn unless() {
evals!["(unless #t 10)" => "#<void>"];
evals!["(unless #f 10)" => "10"];
}
#[test]
fn let_lambda() {
evals!["(let () (+ 10 20))" => "30"];
evals!["(let ([x 10] [y 20]) (+ x y))" => "30"];
}
#[test]
fn let_star() {
evals!["(let* ([x 10] [y (* x x)]) (+ x y))" => "110"]
}
#[test]
fn set() {
evals!["(define (generator) (let ([x 0]) (lambda () (set! x (+ x 1)) x)))" => "#<void>",
"(define counter (generator))" => "#<void>",
"(counter)" => "1",
"(counter)" => "2",
"(counter)" => "3"
];
}
#[test]
fn set_pair() {
evals!["(define l '(1 2 3))" => "#<void>",
"(set-car! (cdr l) 100))" => "#<void>",
"l" => "(1 100 3)"
];
evals!["(define l '(1 2 3))" => "#<void>",
"(set-cdr! (cdr (cdr l)) '(4 5 6)))" => "#<void>",
"l" => "(1 2 3 4 5 6)"
];
}
#[test]
fn internal_define() {
evals!["((lambda (x) (define y 10) (+ x y)) 20)" => "30"];
fails!["(lambda (x) (define y 10) (+ x y) (define z 10))" =>
InvalidSyntax("out of context define: (define z 10)".into())];
}
#[test]
fn internal_define_is_lexical() {
evals![
"(define y 100)" => "#<void>",
"((lambda (x) (define y 10) (+ x y)) 20)" => "30",
"y" => "100"
];
evals![
"(define (y) 100)" => "#<void>",
"((lambda (x) (define (y) 10) (+ x (y))) 20)" => "30",
"(y)" => "100"
];
}
#[test]
fn find_primes() {
evals![
r#"
(define (find-primes n)
(define (make-sieve n)
(define (init-sieve v n)
(cond
((zero? n) v)
(else (vector-set! v (- n 1) (- n 1)) (init-sieve v (- n 1)))))
(init-sieve (make-vector n) n))
(define (mark-multiples-of v m i)
(cond
((>= (* m i) (vector-length v)) v)
(else (vector-set! v (* m i) #f) (mark-multiples-of v m (+ i 1)))))
(define (sieve v i)
(cond
((>= i (vector-length v)) v)
((eq? (vector-ref v i) #f) (sieve v (+ i 1)))
(else (sieve (mark-multiples-of v i i) (+ i 1)))))
(define (sieve->list v)
(define (sieve->list v i)
(cond
((= i (vector-length v)) '())
((eq? (vector-ref v i) #f) (sieve->list v (+ i 1)))
(else (cons i (sieve->list v (+ i 1))))))
(sieve->list v 0))
(sieve->list (sieve (make-sieve n) 2)))
"# => "#<void>",
"(find-primes 100)" => "(0 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)"
];
}
#[test]
fn copy_closure() {
evals![r#"
(define (copy a b)
((lambda (partial) (cons a partial))
(if (= b 0)
'eol
(copy (+ a 1) (- b 1)))))"# => "#<void>",
"(copy 100 10)" => "(100 101 102 103 104 105 106 107 108 109 110 . eol)"
];
}
#[test]
fn apply_makes_environment() {
evals![
"(define x 0)" => "#<void>",
"(let ~ ((i (* 9)))
(if (< 1 i) (~ (- i 1)))
(set! x (+ x i)))" => "#<void>",
"x" => "45"
];
}
#[test]
fn eval() {
evals![
"(eval 10)" => "10",
"(define x 42)" => "#<void>",
"(eval 'x)" => "42"
];
evals![
"(eval '((lambda (x y) (+ x y)) 10 20))" => "30"
];
fails![
"(eval +)" => InvalidSyntax("#<procedure:+>".into())
];
}
#[test]
fn apply() {
evals![
"(apply + '())" => "0",
"(apply + 10 '())" => "10",
"(apply + '(10))" => "10",
"(apply + 10 '(20))" => "30",
"(apply + 10 20 '(30 40))" => "100"
];
fails![
"(apply + 10 20)" => InvalidSyntax("the last argument to apply must be a proper list".into()),
"(apply + 10 '(10 . 20))" => InvalidSyntax("the last argument to apply must be a proper list".into())
];
}
#[test]
fn case() {
evals!["(case (+ 3 5)
[(1 2 3 4 5) 'small]
[(6 7 8 9 10) 'big])" => "big"];
}
#[test]
fn void_is_value() {
evals!["(define void (define void 0))" => "#<void>",
"void" => "#<void>"
];
}
#[test]
fn map() {
evals!["(map + '(1 2 3))" => "(1 2 3)"];
evals!["(map + '(1 2 3) '(4 5 6))" => "(5 7 9)"];
}
#[test]
fn for_each() {
evals!["(map + '(1 2 3))" => "(1 2 3)"];
}
| 25.447368 | 112 | 0.401805 |
13b38c81cc394ace948b979f1b0686c4c17c9439 | 1,861 | swift | Swift | MasterProject/Extensions/Dictionary+Extensions.swift | satishbabariya/swift-boilerplate | 1992600835b34110d8dc0d0dd737a36bb2624fe8 | [
"MIT"
] | 16 | 2019-08-13T09:12:41.000Z | 2022-02-27T18:53:07.000Z | MasterProject/Extensions/Dictionary+Extensions.swift | mohsinalimat/swift-boilerplate | e152a5143f73a069f8bdbad1315b4f640bc9d179 | [
"MIT"
] | 1 | 2021-03-26T17:18:57.000Z | 2021-05-22T12:38:23.000Z | MasterProject/Extensions/Dictionary+Extensions.swift | mohsinalimat/swift-boilerplate | e152a5143f73a069f8bdbad1315b4f640bc9d179 | [
"MIT"
] | 3 | 2019-10-15T07:29:59.000Z | 2020-10-12T06:21:52.000Z | //
// Dictionary+Extensions.swift
// MasterProject
//
// Created by Satish Babariya on 28/12/18.
// Copyright © 2018 Satish Babariya. All rights reserved.
//
import Foundation
extension Dictionary {
/// Dictionary to JSON String
///
/// - Returns: jsonstring
public func JSONString() -> String {
var jsonString: NSString = ""
do {
let jsonData: Data = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)!
} catch let error as NSError {
Log.error(error.localizedDescription)
}
return jsonString as String
}
}
extension NSDictionary {
/// Get JSON formatted String
///
/// - Returns: string
public func JSONString() -> String {
var jsonString: NSString = ""
do {
let jsonData: Data = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)!
} catch let error as NSError {
Log.error(error.localizedDescription)
}
return jsonString as String
}
}
extension NSArray {
/// Get JSON formatted String
///
/// - Returns: string
public func JSONString() -> String {
var jsonString: NSString = ""
do {
let jsonData: Data = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)!
} catch let error as NSError {
Log.error(error.localizedDescription)
}
return jsonString as String
}
}
| 29.078125 | 137 | 0.635142 |
fb0c25e68fda72ee1b757549d5ad80faf08c2736 | 1,058 | go | Go | internal/paths_test.go | neolit123/pkgsite | 28de4e97f3da23622300a23848ba9dea3f8e6900 | [
"BSD-3-Clause"
] | 1 | 2021-06-29T00:24:17.000Z | 2021-06-29T00:24:17.000Z | internal/paths_test.go | neolit123/pkgsite | 28de4e97f3da23622300a23848ba9dea3f8e6900 | [
"BSD-3-Clause"
] | 3 | 2022-01-15T03:42:44.000Z | 2022-03-30T05:43:34.000Z | internal/paths_test.go | neolit123/pkgsite | 28de4e97f3da23622300a23848ba9dea3f8e6900 | [
"BSD-3-Clause"
] | 1 | 2020-08-14T04:29:27.000Z | 2020-08-14T04:29:27.000Z | // Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package internal
import (
"testing"
"github.com/google/go-cmp/cmp"
)
func TestCandidateModulePaths(t *testing.T) {
for _, test := range []struct {
in string
want []string
}{
{"", nil},
{".", nil},
{"///foo", nil},
{"github.com/google", nil},
{"std", []string{"std"}},
{"encoding/json", []string{"std"}},
{
"example.com/green/eggs/and/ham",
[]string{
"example.com/green/eggs/and/ham",
"example.com/green/eggs/and",
"example.com/green/eggs",
"example.com/green",
"example.com",
},
},
{
"github.com/google/go-cmp/cmp",
[]string{"github.com/google/go-cmp/cmp", "github.com/google/go-cmp"},
},
{
"bitbucket.org/ok/sure/no$dollars/allowed",
[]string{"bitbucket.org/ok/sure"},
},
} {
got := CandidateModulePaths(test.in)
if !cmp.Equal(got, test.want) {
t.Errorf("%q: got %v, want %v", test.in, got, test.want)
}
}
}
| 21.591837 | 72 | 0.60775 |
bccdb6b11daa6429e5f3570b4e61d917ab15d02f | 596 | js | JavaScript | webgl/source/test/sky/geometryfactoryquadposuv.js | DavidCoenFish/chica | 8233ec08ebd8ddd8ce33b909cfab61515c7085ff | [
"Unlicense"
] | null | null | null | webgl/source/test/sky/geometryfactoryquadposuv.js | DavidCoenFish/chica | 8233ec08ebd8ddd8ce33b909cfab61515c7085ff | [
"Unlicense"
] | null | null | null | webgl/source/test/sky/geometryfactoryquadposuv.js | DavidCoenFish/chica | 8233ec08ebd8ddd8ce33b909cfab61515c7085ff | [
"Unlicense"
] | null | null | null | import {Model} from "./../../components/webgl/resource/model/model.js";
import {DataStream} from "./../../components/webgl/resource/model/datastream.js";
export const geometryFactoryQuadPosUv = function(in_context){
return in_context.createModel(
Model.modeEnum.triangles,
6,
[
new DataStream(
"a_position",
2,
new Int8Array([
-1, -1, //-1,
-1, 1,
1, -1,
1,1,
1,-1,
-1,1
]),
),
new DataStream(
"a_uv",
2,
new Uint8Array([
0, 0,
0, 1,
1, 0,
1, 1,
1, 0,
0, 1
]),
),
]
);
};
| 16.555556 | 81 | 0.511745 |
547010772d840b6845ea3edaa92900076bfde14c | 3,105 | go | Go | internal/xmlParser/node.go | lightSoulDev/pixi-xml-test-compiler | 3462ca150ef58101b6364c123d8062bbc904aab3 | [
"MIT"
] | null | null | null | internal/xmlParser/node.go | lightSoulDev/pixi-xml-test-compiler | 3462ca150ef58101b6364c123d8062bbc904aab3 | [
"MIT"
] | null | null | null | internal/xmlParser/node.go | lightSoulDev/pixi-xml-test-compiler | 3462ca150ef58101b6364c123d8062bbc904aab3 | [
"MIT"
] | null | null | null | package xmlParser
import (
"encoding/xml"
"fmt"
"strings"
)
type Node struct {
XMLName xml.Name
Attrs []xml.Attr `xml:",any,attr"`
Content []byte `xml:",innerxml"`
Nodes []Node `xml:",any"`
Module string
}
func (x *XmlParser) nodeXml(n *Node, depth int) string {
if len(n.Nodes) == 0 {
return fmt.Sprintf("<%s %s/>", n.XMLName.Local, n.XmlAttributes())
} else {
result := fmt.Sprintf("<%s %s>", n.XMLName.Local, n.XmlAttributes())
closing := fmt.Sprintf("</%s>", n.XMLName.Local)
inner := ""
for _, n := range n.Nodes {
inner += x.nodeXml(&n, depth+1)
}
result = result + inner + closing
return result
}
}
func (n *Node) JsonAttributes() string {
attrReprs := []string{}
for _, a := range n.Attrs {
attrReprs = append(attrReprs, fmt.Sprintf("%s : %s", a.Name.Local, a.Value))
}
if len(attrReprs) > 0 {
return "{ " + strings.Join(attrReprs, ", ") + " }"
} else {
return ""
}
}
func (n *Node) XmlAttributes() string {
attrReprs := []string{}
for _, a := range n.Attrs {
value := a.Value
value = strings.ReplaceAll(value, "&", "&")
value = strings.ReplaceAll(value, "\"", """)
value = strings.ReplaceAll(value, "'", "'")
value = strings.ReplaceAll(value, "<", "<")
value = strings.ReplaceAll(value, ">", ">")
attrReprs = append(attrReprs, fmt.Sprintf("%s=\"%s\"", a.Name.Local, value))
}
if len(attrReprs) > 0 {
return strings.Join(attrReprs, " ")
} else {
return ""
}
}
func (x *XmlParser) GetXmlAttribute(attrs []xml.Attr, name string) (string, error) {
for _, a := range attrs {
if a.Name.Local == name {
return a.Value, nil
}
}
return "", fmt.Errorf("missing attribute %s", name)
}
func (x *XmlParser) Walk(nodes []Node, depth *int, f func(Node) (bool, error)) error {
initialDepth := (*depth)
for _, n := range nodes {
(*depth) = initialDepth
next, err := f(n)
if err != nil {
return err
} else if next {
(*depth)++
err := x.Walk(n.Nodes, depth, f)
if err != nil {
return err
}
}
}
return nil
}
func (x *XmlParser) NestedWalk(parent Node, f func(c Node, p Node) (bool, error)) error {
nodes := parent.Nodes
for _, n := range nodes {
next, err := f(n, parent)
if err != nil {
return err
} else if next {
err := x.NestedWalk(n, f)
if err != nil {
return err
}
}
}
return nil
}
func (x *XmlParser) PointerWalk(nodes *[]Node, depth *int, f func(*Node) (bool, error)) error {
initialDepth := (*depth)
for i := range *nodes {
(*depth) = initialDepth
n := &(*nodes)[i]
next, err := f(n)
if err != nil {
return err
} else if next {
(*depth)++
err := x.PointerWalk(&n.Nodes, depth, f)
if err != nil {
return err
}
}
}
return nil
}
func (x *XmlParser) NestedPointerWalk(parent *Node, f func(c *Node, p *Node) (bool, error)) error {
nodes := &(*parent).Nodes
for i := range *nodes {
n := &(*nodes)[i]
next, err := f(n, parent)
if err != nil {
return err
} else if next {
err := x.NestedPointerWalk(n, f)
if err != nil {
return err
}
}
}
return nil
}
| 19.528302 | 99 | 0.582609 |
85ca7e185c0f141c7f2114c5c7766ec424c82137 | 138 | js | JavaScript | templates/react/default/entities/Characters/api.js | wintercounter/mhy-boot | 166a6cd511fcd66981e17bddbc37753b59f523ca | [
"MIT"
] | 1 | 2018-10-17T12:44:28.000Z | 2018-10-17T12:44:28.000Z | templates/react/default/entities/Characters/api.js | wintercounter/mhy-boot | 166a6cd511fcd66981e17bddbc37753b59f523ca | [
"MIT"
] | 4 | 2018-10-17T09:00:04.000Z | 2018-10-18T07:59:08.000Z | templates/react/default/entities/Characters/api.js | wintercounter/mhy-boot | 166a6cd511fcd66981e17bddbc37753b59f523ca | [
"MIT"
] | 1 | 2018-10-17T07:06:55.000Z | 2018-10-17T07:06:55.000Z | import { RickAndMorty } from '@services'
export const getCharacter = (opt = {}) => RickAndMorty('character', opt) // eslint-disable-line
| 34.5 | 95 | 0.702899 |
6294c5752e18359c58f9cb995f0587e746d15dbd | 8,767 | rs | Rust | dora/src/os/allocator.rs | ashwanidausodia/dora | 265a8fe38570f3e4c83541db40f7400941a10283 | [
"MIT"
] | null | null | null | dora/src/os/allocator.rs | ashwanidausodia/dora | 265a8fe38570f3e4c83541db40f7400941a10283 | [
"MIT"
] | 1 | 2019-03-22T22:25:17.000Z | 2019-03-22T22:25:17.000Z | dora/src/os/allocator.rs | soc/dora | 7ccf8e0f755694a8b05c789bde3087526fe39ca9 | [
"MIT"
] | null | null | null | use std::ptr;
use crate::gc::Address;
use crate::mem;
use crate::os::page_size;
#[cfg(target_family = "unix")]
fn reserve(size: usize) -> Address {
debug_assert!(mem::is_page_aligned(size));
let ptr = unsafe {
libc::mmap(
ptr::null_mut(),
size,
libc::PROT_NONE,
libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE,
-1,
0,
) as *mut libc::c_void
};
if ptr == libc::MAP_FAILED {
panic!("reserving memory with mmap() failed");
}
Address::from_ptr(ptr)
}
#[cfg(target_family = "windows")]
fn reserve(size: usize) -> Address {
debug_assert!(mem::is_page_aligned(size));
use winapi::um::memoryapi::VirtualAlloc;
use winapi::um::winnt::{MEM_RESERVE, PAGE_NOACCESS};
let ptr = unsafe { VirtualAlloc(ptr::null_mut(), size, MEM_RESERVE, PAGE_NOACCESS) };
if ptr.is_null() {
panic!("VirtualAlloc failed");
}
Address::from_ptr(ptr)
}
#[cfg(target_family = "unix")]
pub fn free(ptr: Address, size: usize) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
let result = unsafe { libc::munmap(ptr.to_mut_ptr(), size) };
if result != 0 {
panic!("munmap() failed");
}
}
#[cfg(target_family = "windows")]
pub fn free(ptr: Address, size: usize) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
use winapi::um::memoryapi::VirtualFree;
use winapi::um::winnt::MEM_RELEASE;
let result = unsafe { VirtualFree(ptr.to_mut_ptr(), 0, MEM_RELEASE) };
if result == 0 {
panic!("VirtualFree failed");
}
}
pub struct Reservation {
pub start: Address,
pub unaligned_start: Address,
pub unaligned_size: usize,
}
pub fn reserve_align(size: usize, align: usize) -> Reservation {
debug_assert!(mem::is_page_aligned(size));
debug_assert!(mem::is_page_aligned(align));
let align = if align == 0 { page_size() } else { align };
let unaligned_size = size + align - page_size();
let unaligned_start = reserve(unaligned_size);
let aligned_start: Address = mem::align_usize(unaligned_start.to_usize(), align).into();
let gap_start = aligned_start.offset_from(unaligned_start);
let gap_end = unaligned_size - size - gap_start;
if gap_start > 0 {
uncommit(unaligned_start, gap_start);
}
if gap_end > 0 {
uncommit(aligned_start.offset(size), gap_end);
}
if cfg!(target_family = "unix") {
Reservation {
start: aligned_start,
unaligned_start: aligned_start,
unaligned_size: size,
}
} else if cfg!(target_family = "windows") {
Reservation {
start: aligned_start,
unaligned_start,
unaligned_size,
}
} else {
unreachable!();
}
}
#[cfg(target_family = "unix")]
pub fn commit(size: usize, executable: bool) -> Address {
debug_assert!(mem::is_page_aligned(size));
let mut prot = libc::PROT_READ | libc::PROT_WRITE;
if executable {
prot |= libc::PROT_EXEC;
}
let ptr = unsafe {
libc::mmap(
ptr::null_mut(),
size,
prot,
libc::MAP_PRIVATE | libc::MAP_ANON,
-1,
0,
)
};
if ptr == libc::MAP_FAILED {
panic!("committing memory with mmap() failed");
}
Address::from_ptr(ptr)
}
#[cfg(target_family = "windows")]
pub fn commit(size: usize, executable: bool) -> Address {
debug_assert!(mem::is_page_aligned(size));
use winapi::um::memoryapi::VirtualAlloc;
use winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE};
let prot = if executable {
PAGE_EXECUTE_READWRITE
} else {
PAGE_READWRITE
};
let ptr = unsafe { VirtualAlloc(ptr::null_mut(), size, MEM_COMMIT | MEM_RESERVE, prot) };
if ptr.is_null() {
panic!("VirtualAlloc failed");
}
Address::from_ptr(ptr)
}
#[cfg(target_family = "unix")]
pub fn commit_at(ptr: Address, size: usize, executable: bool) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
let mut prot = libc::PROT_READ | libc::PROT_WRITE;
if executable {
prot |= libc::PROT_EXEC;
}
let val = unsafe {
libc::mmap(
ptr.to_mut_ptr(),
size,
prot,
libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_FIXED,
-1,
0,
)
};
if val == libc::MAP_FAILED {
panic!("committing memory with mmap() failed");
}
}
#[cfg(target_family = "windows")]
pub fn commit_at(ptr: Address, size: usize, executable: bool) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
use winapi::um::memoryapi::VirtualAlloc;
use winapi::um::winnt::{MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE};
let prot = if executable {
PAGE_EXECUTE_READWRITE
} else {
PAGE_READWRITE
};
let result = unsafe { VirtualAlloc(ptr.to_mut_ptr(), size, MEM_COMMIT, prot) };
if result != ptr.to_mut_ptr() {
panic!("VirtualAlloc failed");
}
}
#[cfg(target_family = "unix")]
fn uncommit(ptr: Address, size: usize) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
let result = unsafe { libc::munmap(ptr.to_mut_ptr(), size) };
if result != 0 {
panic!("munmap() failed");
}
}
#[cfg(target_family = "windows")]
fn uncommit(ptr: Address, size: usize) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
use winapi::um::memoryapi::VirtualFree;
use winapi::um::winnt::MEM_DECOMMIT;
let result = unsafe { VirtualFree(ptr.to_mut_ptr(), size, MEM_DECOMMIT) };
if result == 0 {
panic!("VirtualFree failed");
}
}
#[cfg(target_family = "unix")]
pub fn discard(ptr: Address, size: usize) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
let res = unsafe { libc::madvise(ptr.to_mut_ptr(), size, libc::MADV_DONTNEED) };
if res != 0 {
panic!("discarding memory with madvise() failed");
}
let res = unsafe { libc::mprotect(ptr.to_mut_ptr(), size, libc::PROT_NONE) };
if res != 0 {
panic!("discarding memory with mprotect() failed");
}
}
#[cfg(target_family = "windows")]
pub fn discard(ptr: Address, size: usize) {
debug_assert!(ptr.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
use winapi::um::memoryapi::VirtualFree;
use winapi::um::winnt::MEM_DECOMMIT;
let result = unsafe { VirtualFree(ptr.to_mut_ptr(), size, MEM_DECOMMIT) };
if result == 0 {
panic!("VirtualFree failed");
}
}
#[cfg(target_family = "unix")]
pub fn protect(start: Address, size: usize, access: Access) {
debug_assert!(start.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
if access.is_none() {
discard(start, size);
return;
}
let protection = match access {
Access::None => unreachable!(),
Access::Read => libc::PROT_READ,
Access::ReadWrite => libc::PROT_READ | libc::PROT_WRITE,
Access::ReadExecutable => libc::PROT_READ | libc::PROT_EXEC,
Access::ReadWriteExecutable => libc::PROT_READ | libc::PROT_WRITE | libc::PROT_EXEC,
};
let res = unsafe { libc::mprotect(start.to_mut_ptr(), size, protection) };
if res != 0 {
panic!("mprotect() failed");
}
}
#[cfg(target_family = "windows")]
pub fn protect(start: Address, size: usize, access: Access) {
debug_assert!(start.is_page_aligned());
debug_assert!(mem::is_page_aligned(size));
use winapi::um::memoryapi::VirtualAlloc;
use winapi::um::winnt::{
MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READONLY, PAGE_READWRITE,
};
if access.is_none() {
discard(start, size);
return;
}
let protection = match access {
Access::None => unreachable!(),
Access::Read => PAGE_READONLY,
Access::ReadWrite => PAGE_READWRITE,
Access::ReadExecutable => PAGE_EXECUTE_READ,
Access::ReadWriteExecutable => PAGE_EXECUTE_READWRITE,
};
let ptr = unsafe { VirtualAlloc(start.to_mut_ptr(), size, MEM_COMMIT, protection) };
if ptr.is_null() {
panic!("VirtualAlloc failed");
}
}
pub enum Access {
None,
Read,
ReadWrite,
ReadExecutable,
ReadWriteExecutable,
}
impl Access {
fn is_none(&self) -> bool {
match self {
Access::None => true,
_ => false,
}
}
}
| 25.33815 | 93 | 0.611155 |
d1e14f018361940a4c1f3a40f13d6997caee2071 | 253 | rs | Rust | lightproc/tests/stack.rs | rtyler/bastion | c0f555ca583ab14e20cec1af88eab57fb49f4b56 | [
"Apache-2.0",
"MIT"
] | null | null | null | lightproc/tests/stack.rs | rtyler/bastion | c0f555ca583ab14e20cec1af88eab57fb49f4b56 | [
"Apache-2.0",
"MIT"
] | null | null | null | lightproc/tests/stack.rs | rtyler/bastion | c0f555ca583ab14e20cec1af88eab57fb49f4b56 | [
"Apache-2.0",
"MIT"
] | null | null | null | use lightproc::proc_stack::ProcStack;
#[test]
fn stack_copy() {
let stack = ProcStack::default().with_pid(12).with_after_panic(|| {
println!("After panic!");
});
let stack2 = stack.clone();
assert_eq!(stack2.get_pid(), 12);
}
| 19.461538 | 71 | 0.620553 |
5f8b552a189f94c9db7a96f7f8001bf55b218bb3 | 1,233 | h | C | src/specex_gauss_hermite_psf.h | tskisner/specex | c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2 | [
"BSD-3-Clause"
] | null | null | null | src/specex_gauss_hermite_psf.h | tskisner/specex | c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2 | [
"BSD-3-Clause"
] | 39 | 2016-06-17T19:58:17.000Z | 2022-01-07T00:11:25.000Z | src/specex_gauss_hermite_psf.h | tskisner/specex | c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2 | [
"BSD-3-Clause"
] | 4 | 2016-06-16T17:43:38.000Z | 2021-07-18T16:32:34.000Z | #ifndef SPECEX_GAUSS_HERMITE_PSF__H
#define SPECEX_GAUSS_HERMITE_PSF__H
#include "specex_psf.h"
#include <string>
#include <vector>
namespace specex {
class GaussHermitePSF : public PSF {
protected :
int degree;
public :
typedef std::shared_ptr <GaussHermitePSF> pshr;
GaussHermitePSF(int ideg=3);
virtual ~GaussHermitePSF(){};
void SetDegree(const int ideg);
int LocalNAllPar() const;
double Degree() const {
return degree;
}
double Profile(const double &X, const double &Y,
const unbls::vector_double &Params,
unbls::vector_double *PosDer = 0,
unbls::vector_double *ParamGradient = 0) const;
// needed for analytic integration
double PixValue(const double &Xc, const double &Yc,
const double &XPix, const double &YPix,
const unbls::vector_double &Params,
unbls::vector_double *PosDer,
unbls::vector_double *ParamDer) const;
unbls::vector_double DefaultParams() const;
std::vector<std::string> DefaultParamNames() const;
bool CheckParams(const unbls::vector_double &Params) const
{ return true;}
void Append(const specex::PSF_p other);
};
}
#endif
| 21.631579 | 63 | 0.662612 |
437c2d3b7451ddf8b6dae3266a9ad8f7118fd370 | 2,418 | go | Go | operator/pkg/client/namespaces.go | MikaelSmith/kotsadm | 8e06a3805a9f8be42d8cac9a636d3b8126aa1018 | [
"Apache-2.0"
] | 292 | 2019-11-20T17:11:17.000Z | 2021-07-16T10:34:32.000Z | operator/pkg/client/namespaces.go | MikaelSmith/kotsadm | 8e06a3805a9f8be42d8cac9a636d3b8126aa1018 | [
"Apache-2.0"
] | 89 | 2019-11-22T15:03:30.000Z | 2020-05-29T19:28:40.000Z | operator/pkg/client/namespaces.go | MikaelSmith/kotsadm | 8e06a3805a9f8be42d8cac9a636d3b8126aa1018 | [
"Apache-2.0"
] | 7 | 2020-01-15T05:21:29.000Z | 2021-07-22T16:07:59.000Z | package client
import (
"log"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
)
func (c *Client) runNamespacesInformer() error {
restconfig, err := rest.InClusterConfig()
if err != nil {
return errors.Wrap(err, "failed to get in cluster config")
}
clientset, err := kubernetes.NewForConfig(restconfig)
if err != nil {
return errors.Wrap(err, "failed to get new kubernetes client")
}
c.namespaceStopChan = make(chan struct{})
factory := informers.NewSharedInformerFactory(clientset, 0)
nsInformer := factory.Core().V1().Namespaces().Informer()
nsInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
addedNamespace := obj.(*corev1.Namespace)
for _, watchedNamespace := range c.watchedNamespaces {
deployImagePullSecret := false
if watchedNamespace == "*" {
deployImagePullSecret = true
} else {
if watchedNamespace == addedNamespace.Name {
deployImagePullSecret = true
}
}
if !deployImagePullSecret {
continue
}
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, _, err := decode([]byte(c.imagePullSecret), nil, nil)
if err != nil {
log.Print(err)
return
}
secret := obj.(*corev1.Secret)
secret.Namespace = addedNamespace.Name
foundSecret, err := clientset.CoreV1().Secrets(addedNamespace.Name).Get(secret.Name, metav1.GetOptions{})
if err != nil {
if kuberneteserrors.IsNotFound(err) {
// create it
_, err := clientset.CoreV1().Secrets(addedNamespace.Name).Create(secret)
if err != nil {
log.Print(err)
return
}
} else {
log.Print(err)
return
}
} else {
// Update it
foundSecret.Data[".dockerconfigjson"] = secret.Data[".dockerconfigjson"]
if _, err := clientset.CoreV1().Secrets(addedNamespace.Name).Update(secret); err != nil {
log.Print(err)
return
}
}
}
},
})
go nsInformer.Run(c.namespaceStopChan)
return nil
}
func (c *Client) shutdownNamespacesInformer() {
if c.namespaceStopChan != nil {
c.namespaceStopChan <- struct{}{}
}
c.namespaceStopChan = nil
}
| 24.927835 | 109 | 0.666253 |
7b90d3960038dcdb48e9ac2483712396354d84bb | 14,350 | sql | SQL | sql file/metorik-dashboard.sql | GemsPatel/admin-theme-setup | f48c69860c69daa81bbfccc88569f3be0b39b3e2 | [
"MIT"
] | null | null | null | sql file/metorik-dashboard.sql | GemsPatel/admin-theme-setup | f48c69860c69daa81bbfccc88569f3be0b39b3e2 | [
"MIT"
] | null | null | null | sql file/metorik-dashboard.sql | GemsPatel/admin-theme-setup | f48c69860c69daa81bbfccc88569f3be0b39b3e2 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.6.6deb5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Feb 28, 2020 at 05:02 PM
-- Server version: 5.7.28-0ubuntu0.19.04.2
-- PHP Version: 7.2.26-1+ubuntu19.04.1+deb.sury.org+1
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 */;
--
-- Database: `metorik-dashboard`
--
-- --------------------------------------------------------
--
-- Table structure for table `appointment`
--
CREATE TABLE `appointment` (
`id` bigint(20) UNSIGNED NOT NULL,
`category_id` bigint(20) DEFAULT NULL,
`service_id` bigint(20) DEFAULT NULL,
`user_id` bigint(20) DEFAULT NULL,
`price` double(20,4) DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`contact_number` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`date` date DEFAULT NULL,
`time` time DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `appointment`
--
INSERT INTO `appointment` (`id`, `category_id`, `service_id`, `user_id`, `price`, `name`, `email`, `contact_number`, `date`, `time`, `created_at`, `updated_at`, `deleted_at`) VALUES
(2, 1, 1, NULL, 150.0000, 'Nik', 'nil@example.com', '458487456', '2020-03-10', '12:03:00', '2020-02-10 06:34:56', '2020-02-12 01:55:06', NULL),
(3, 1, 1, NULL, 150.0000, 'Vicky', 'vicky@example.com', '345345353', '2020-02-13', '02:00:00', '2020-02-10 23:55:51', '2020-02-12 01:49:13', NULL),
(4, 3, 13, NULL, 400.0000, 'Alex', 'alex@example.com', '6789323122', '2020-02-22', '10:00:00', '2020-02-12 02:37:02', '2020-02-12 02:37:02', NULL),
(5, 2, 7, 3, 1500.0000, NULL, NULL, NULL, '2020-04-09', '13:30:00', '2020-02-12 02:38:31', '2020-02-12 02:38:31', NULL),
(6, 3, 11, NULL, 2000.0000, 'Johnny', 'johnny@example.com', '9876543215', '2020-02-03', '07:25:00', '2020-02-12 02:36:04', '2020-02-12 02:41:28', NULL),
(7, 1, 3, 3, 200.0000, NULL, NULL, NULL, '2020-03-15', '12:30:00', '2020-02-12 02:41:23', '2020-02-12 02:41:57', NULL),
(9, 1, 3, NULL, 200.0000, 'Anna', 'anna@example.com', '434345566', '2020-03-26', '08:33:00', '2020-02-12 03:04:49', '2020-02-12 03:05:07', NULL),
(10, 3, 14, NULL, 1500.0000, 'Carl Price', 'carl@exmple.in', '56789023', '2020-03-01', '08:00:00', '2020-02-12 03:25:02', '2020-02-12 03:25:02', NULL),
(11, 3, 11, NULL, 2000.0000, 'Mark Lucas', 'marklucas@example.com', '344556672', '2020-03-22', '10:45:00', '2020-02-12 03:26:45', '2020-02-12 03:27:27', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `board`
--
CREATE TABLE `board` (
`id` bigint(20) UNSIGNED NOT NULL,
`title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`color` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`status` tinyint(3) UNSIGNED DEFAULT NULL,
`sequence` tinyint(3) UNSIGNED DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `board`
--
INSERT INTO `board` (`id`, `title`, `color`, `status`, `sequence`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'Todo', '#65ccf7', 1, 1, NULL, '2020-02-12 23:46:54', NULL),
(2, 'Planning', '#827af3', 1, 2, '2020-02-11 06:40:23', '2020-02-12 23:46:54', NULL),
(3, 'Working', '#3dbb58', 1, 3, '2020-02-11 22:15:55', '2020-02-12 23:46:54', NULL),
(4, 'Complete', '#fbc647', 1, 4, '2020-02-12 04:52:30', '2020-02-12 23:46:54', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `board_task`
--
CREATE TABLE `board_task` (
`id` bigint(20) UNSIGNED NOT NULL,
`board_id` bigint(20) UNSIGNED DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`description` text COLLATE utf8mb4_unicode_ci,
`priority` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`date` date DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `board_task`
--
INSERT INTO `board_task` (`id`, `board_id`, `name`, `description`, `priority`, `date`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 1, 'Contact with john', 'Contact with jones for new project', '2', '2020-02-13', '2020-02-11 05:55:31', '2020-02-12 23:53:10', NULL),
(2, 2, 'Presentations', 'New project\'s presentations', '2', '2020-02-13', '2020-02-11 06:40:48', '2020-02-12 23:53:08', NULL),
(3, 1, 'Assign Project', 'Assign new project to Emma', '3', '2020-02-19', '2020-02-11 22:32:18', '2020-02-12 23:53:00', NULL),
(4, 2, 'Meeting', 'Discuss point of new project', '1', '2020-02-26', '2020-02-12 00:03:24', '2020-02-12 07:14:55', NULL),
(5, 3, 'Product Campaign', 'Marketing Strategy , Planning , Discussion', '3', '2020-02-12', '2020-02-12 04:48:29', '2020-02-12 04:51:10', NULL),
(6, 4, 'Meeting', 'Meeting with Mr Alex about new project', '1', '2020-02-13', '2020-02-12 04:57:31', '2020-02-12 07:15:01', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `category`
--
CREATE TABLE `category` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`status` tinyint(4) DEFAULT '1',
`color` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `category`
--
INSERT INTO `category` (`id`, `name`, `status`, `color`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'Salon', 1, '#0a0c0a', '2020-02-12 06:09:22', '2020-02-12 00:47:43', NULL),
(2, 'Dental Clinic', 1, '#90acac', '2020-02-12 00:47:22', '2020-02-12 00:51:54', NULL),
(3, 'Cleaning', 1, '#00d0ff', '2020-02-12 01:18:51', '2020-02-12 01:18:51', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `ci_sessions`
--
CREATE TABLE `ci_sessions` (
`session_id` varchar(40) COLLATE utf8_bin NOT NULL DEFAULT '0',
`ip_address` varchar(16) COLLATE utf8_bin NOT NULL DEFAULT '0',
`user_agent` varchar(150) COLLATE utf8_bin NOT NULL,
`last_activity` int(10) UNSIGNED NOT NULL DEFAULT '0',
`user_data` text COLLATE utf8_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- --------------------------------------------------------
--
-- Table structure for table `login_attempts`
--
CREATE TABLE `login_attempts` (
`id` int(11) NOT NULL,
`ip_address` varchar(40) COLLATE utf8_bin NOT NULL,
`login` varchar(50) COLLATE utf8_bin NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- --------------------------------------------------------
--
-- Table structure for table `permissions`
--
CREATE TABLE `permissions` (
`id` int(11) NOT NULL,
`name` varchar(100) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `permission_roles`
--
CREATE TABLE `permission_roles` (
`role_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `roles`
--
CREATE TABLE `roles` (
`id` smallint(5) UNSIGNED NOT NULL,
`name` varchar(200) NOT NULL,
`status` int(11) DEFAULT '1',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;
-- --------------------------------------------------------
--
-- Table structure for table `roles_users`
--
CREATE TABLE `roles_users` (
`user_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `roles_users`
--
INSERT INTO `roles_users` (`user_id`, `role_id`) VALUES
(1, 1);
-- --------------------------------------------------------
--
-- Table structure for table `service`
--
CREATE TABLE `service` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`label` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
`status` tinyint(4) DEFAULT '1',
`price` double DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `service`
--
INSERT INTO `service` (`id`, `name`, `label`, `category_id`, `status`, `price`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'Boy Hair Cut', NULL, 1, 1, 150, '2020-02-10 06:30:23', '2020-02-12 00:57:17', NULL),
(2, 'Orthodontics', NULL, 2, 1, 2500, '2020-02-10 06:30:38', '2020-02-12 00:52:20', NULL),
(3, 'Girl Hair Cut', NULL, 1, 1, 200, '2020-02-12 00:56:28', '2020-02-12 00:56:28', NULL),
(4, 'Beard trim', NULL, 1, 1, 100, '2020-02-12 00:56:58', '2020-02-12 00:56:58', NULL),
(5, 'Teeth cleaning and Polishing', NULL, 2, 1, 999, '2020-02-12 00:59:14', '2020-02-12 00:59:14', NULL),
(6, 'Tooth Extraction', NULL, 2, 1, 1500, '2020-02-12 01:00:13', '2020-02-12 01:00:13', NULL),
(7, 'Root canal treatment - front teeth', NULL, 2, 1, 1500, '2020-02-12 01:02:30', '2020-02-12 01:03:12', NULL),
(8, 'Root canal treatment - back teeth', NULL, 2, 1, 2000, '2020-02-12 01:02:55', '2020-02-12 01:02:55', NULL),
(9, 'Tooth Extraction - Regular', NULL, 2, 1, 550, '2020-02-12 01:04:33', '2020-02-12 01:04:33', NULL),
(10, 'Curtains', NULL, 3, 1, 120, '2020-02-12 01:28:47', '2020-02-12 01:28:47', NULL),
(11, 'Leather Sofa', NULL, 3, 1, 2000, '2020-02-12 01:56:09', '2020-02-12 01:56:09', NULL),
(12, 'Carpet Shampooing', NULL, 3, 1, 750, '2020-02-12 01:56:43', '2020-02-12 01:56:43', NULL),
(13, 'Mattress Shampooing', NULL, 3, 1, 400, '2020-02-12 01:57:17', '2020-02-12 01:57:17', NULL),
(14, 'Kichen , Bathrooms', NULL, 3, 1, 1500, '2020-02-12 03:23:57', '2020-02-12 03:23:57', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(50) COLLATE utf8_bin NOT NULL,
`password` varchar(255) COLLATE utf8_bin NOT NULL,
`email` varchar(100) COLLATE utf8_bin NOT NULL,
`activated` tinyint(1) NOT NULL DEFAULT '1',
`banned` tinyint(1) NOT NULL DEFAULT '0',
`ban_reason` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`new_password_key` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`new_password_requested` datetime DEFAULT NULL,
`new_email` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`new_email_key` varchar(50) COLLATE utf8_bin DEFAULT NULL,
`last_ip` varchar(40) COLLATE utf8_bin NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_login` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_type` varchar(20) COLLATE utf8_bin DEFAULT NULL,
`contact_number` varchar(15) COLLATE utf8_bin DEFAULT NULL,
`address` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`profile_image` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`gender` varchar(5) COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `email`, `activated`, `banned`, `ban_reason`, `new_password_key`, `new_password_requested`, `new_email`, `new_email_key`, `last_ip`, `modified`, `last_login`, `created`, `user_type`, `contact_number`, `address`, `profile_image`, `gender`) VALUES
(1, 'admin', '$2a$08$XZJGTIxzgK54dJvxFzOEIeuHjTPZwKSpOgzaHfFEtNaFjDMB1OAgu', 'admin@admin.com', 1, 0, NULL, NULL, NULL, NULL, '982bebf97a4b113a41e9a2d4ac6f3d21', '127.0.0.1', '2020-02-18 02:35:17', '2020-02-18 13:35:17', '2020-02-06 10:13:21', 'admin', NULL, NULL, NULL, NULL);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `appointment`
--
ALTER TABLE `appointment`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `board`
--
ALTER TABLE `board`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `board_task`
--
ALTER TABLE `board_task`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `category`
--
ALTER TABLE `category`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `service`
--
ALTER TABLE `service`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `appointment`
--
ALTER TABLE `appointment`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `board`
--
ALTER TABLE `board`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `board_task`
--
ALTER TABLE `board_task`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `category`
--
ALTER TABLE `category`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `service`
--
ALTER TABLE `service`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
/*!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 */;
| 38.994565 | 296 | 0.657282 |
26b18266bc367e2d62b3746e80c216070ebd81fb | 3,433 | java | Java | z-kkb-netty-demo/09-tomcat/src/main/java/com/abc/tomcat/TomcatServer.java | su787910081/netty | 26438b53b18b4ed9673b4398c2d02d4ae185a5fe | [
"Apache-2.0"
] | null | null | null | z-kkb-netty-demo/09-tomcat/src/main/java/com/abc/tomcat/TomcatServer.java | su787910081/netty | 26438b53b18b4ed9673b4398c2d02d4ae185a5fe | [
"Apache-2.0"
] | null | null | null | z-kkb-netty-demo/09-tomcat/src/main/java/com/abc/tomcat/TomcatServer.java | su787910081/netty | 26438b53b18b4ed9673b4398c2d02d4ae185a5fe | [
"Apache-2.0"
] | null | null | null | package com.abc.tomcat;
import com.abc.servnet.Servnet;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Tomcat功能的实现
*/
public class TomcatServer {
// key为servnet的简单类名,value为对应servnet实例
private Map<String, Servnet> nameToServnetMap = new ConcurrentHashMap<>();
// key为servnet的简单类名,value为对应servnet类的全限定性类名
private Map<String, String> nameToClassNameMap = new HashMap<>();
private String basePackage;
public TomcatServer(String basePackage) {
this.basePackage = basePackage;
}
// 启动tomcat
public void start() throws Exception {
// 加载指定包中的所有Servnet的类名
cacheClassName(basePackage);
// 启动server服务
runServer();
}
private void cacheClassName(String basePackage) {
// 获取指定包中的资源
URL resource = this.getClass().getClassLoader()
// com.abc.webapp => com/abc/webapp
.getResource(basePackage.replaceAll("\\.", "/"));
// 若目录中没有任何资源,则直接结束
if (resource == null) {
return;
}
// 将URL资源转换为File资源
File dir = new File(resource.getFile());
// 遍历指定包及其子孙包中的所有文件,查找所有.class文件
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
// 若当前遍历的file为目录,则递归调用当前方法
cacheClassName(basePackage + "." + file.getName());
} else if (file.getName().endsWith(".class")) {
String simpleClassName = file.getName().replace(".class", "").trim();
// key为简单类名,value为全限定性类名
nameToClassNameMap.put(simpleClassName.toLowerCase(), basePackage + "." + simpleClassName);
}
}
// System.out.println(nameToClassNameMap);
}
private void runServer() throws Exception {
EventLoopGroup parent = new NioEventLoopGroup();
EventLoopGroup child = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(parent, child)
// 指定存放请求的队列的长度
.option(ChannelOption.SO_BACKLOG, 1024)
// 指定是否启用心跳机制来检测长连接的存活性,即客户端的存活性
.childOption(ChannelOption.SO_KEEPALIVE, true)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new TomcatHandler(nameToServnetMap, nameToClassNameMap));
}
});
ChannelFuture future = bootstrap.bind(8888).sync();
System.out.println("Tomcat启动成功:监听端口号为8888");
future.channel().closeFuture().sync();
} finally {
parent.shutdownGracefully();
child.shutdownGracefully();
}
}
}
| 35.391753 | 107 | 0.60268 |
d2e0be744bf0a2efe7a9dde024f3632a10ad9380 | 4,203 | php | PHP | resources/views/post.blade.php | limsenkeat/learnlaravel-blog | 6fefcabd540ffda4635020f0b06c9927cfcc6237 | [
"MIT"
] | null | null | null | resources/views/post.blade.php | limsenkeat/learnlaravel-blog | 6fefcabd540ffda4635020f0b06c9927cfcc6237 | [
"MIT"
] | 6 | 2020-05-05T17:49:53.000Z | 2022-02-27T04:12:25.000Z | resources/views/post.blade.php | limsenkeat/learnlaravel-blog | 6fefcabd540ffda4635020f0b06c9927cfcc6237 | [
"MIT"
] | null | null | null | @extends('layouts.home')
@section('external_css')
<link href="{{asset('css/blog-post.css')}}" rel="stylesheet">
@endsection
@section('content')
<!-- Title -->
<h1 class="mt-4">{{$post->title}}</h1>
<!-- Author -->
<p class="lead">
by
<a href="#">{{$post->user->name}}</a>
</p>
<hr>
<!-- Date/Time -->
<p>Posted on {{$post->created_at->diffForHumans()}}</p>
<hr>
<!-- Preview Image -->
<img class="img-fluid rounded" src="{{ Storage::exists($post->image) ? asset($post->image) : 'http://placehold.it/750x300' }}" alt="{{$post->title}}">
<hr>
<!-- Post Content -->
{{$post->body}}
<hr>
<!-- Comments Form -->
<div class="card my-4">
<h5 class="card-header">Leave a Comment:</h5>
<div class="card-body">
@if(!Auth::check())
Please <a href="{{route('login')}}">login</a> to add comment.
@else
@if(session('status'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{session('status')}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif
{!! Form::open(['method' => 'POST', 'action' => 'PostCommentsController@store']) !!}
@csrf
<input type="hidden" name="post_id" value="{{$post->id}}">
<div class="form-group">
{!! Form::textarea('body', null, ['class' => 'form-control '.($errors->has('body') ? 'is-invalid' : '').'', 'rows' => 3]) !!}
</div>
@error('body')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
{!! Form::submit('Submit', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
@endif
</div>
</div>
@if (count($post->comments()->whereIsActive(1)->get()) > 0)
@foreach ($post->comments()->whereIsActive(1)->get() as $comment)
<!-- Single Comment -->
<div class="media mb-4">
<img class="d-flex mr-3 rounded-circle" src="http://placehold.it/50x50" alt="">
<div class="media-body">
<h5 class="mt-0">{{$comment->author}} <small class="text-muted">{{$comment->created_at->diffForHumans()}}</small></h5>
{{$comment->body}}
@if (count($comment->replies()->whereIsActive(1)->get()) > 0)
@foreach ($comment->replies()->whereIsActive(1)->get() as $reply)
<div class="media mt-4">
<img class="d-flex mr-3 rounded-circle" src="http://placehold.it/50x50" alt="">
<div class="media-body">
<h5 class="mt-0">{{$reply->author}} <small class="text-muted">{{$reply->created_at->diffForHumans()}}</small></h5>
{{$reply->body}}
</div>
</div>
@endforeach
@endif
<div class="media mt-4">
<div class="media-body">
@if(Auth::check())
@if(session('status_'.$comment->id))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{session('status_'.$comment->id)}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif
{!! Form::open(['method' => 'POST', 'action' => 'CommentRepliesController@store']) !!}
@csrf
<input type="hidden" name="comment_id" value="{{$comment->id}}">
<div class="form-group">
{!! Form::textarea('body', null, ['class' => 'form-control '.($errors->has('body') ? 'is-invalid' : '').'', 'rows' => 1]) !!}
</div>
@error('body')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
{!! Form::submit('Reply', ['class' => 'btn btn-primary float-right']) !!}
{!! Form::close() !!}
@endif
</div>
</div>
</div>
</div>
@endforeach
@endif
@endsection
| 35.618644 | 150 | 0.489888 |
cb533c32980e6093857b7b00c79c1eac2dbbf6a2 | 38,458 | html | HTML | plain/chapter11/instance.html | c10342/typescript-axios | e12105cf8177d2dac0072a8b8e8c49aca41ab37f | [
"MIT"
] | null | null | null | plain/chapter11/instance.html | c10342/typescript-axios | e12105cf8177d2dac0072a8b8e8c49aca41ab37f | [
"MIT"
] | null | null | null | plain/chapter11/instance.html | c10342/typescript-axios | e12105cf8177d2dac0072a8b8e8c49aca41ab37f | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Axios 实例模块单元测试 | TypeScript 从零实现 axios</title>
<meta name="description" content="学习使用 TypeScript 从零实现 axios 库">
<link rel="preload" href="/assets/css/0.styles.eb66b6c2.css" as="style"><link rel="preload" href="/assets/js/app.c982d9fb.js" as="script"><link rel="preload" href="/assets/js/2.9f28cd09.js" as="script"><link rel="preload" href="/assets/js/17.e951ed3d.js" as="script"><link rel="prefetch" href="/assets/js/10.e9e7dcfc.js"><link rel="prefetch" href="/assets/js/11.c95440e2.js"><link rel="prefetch" href="/assets/js/12.43692db9.js"><link rel="prefetch" href="/assets/js/13.7ea88eb2.js"><link rel="prefetch" href="/assets/js/14.7e95317d.js"><link rel="prefetch" href="/assets/js/15.5ab7f496.js"><link rel="prefetch" href="/assets/js/16.0254cc50.js"><link rel="prefetch" href="/assets/js/18.81135b7c.js"><link rel="prefetch" href="/assets/js/19.28094298.js"><link rel="prefetch" href="/assets/js/20.110ec749.js"><link rel="prefetch" href="/assets/js/21.196fc08f.js"><link rel="prefetch" href="/assets/js/22.3b445db6.js"><link rel="prefetch" href="/assets/js/23.d5323df3.js"><link rel="prefetch" href="/assets/js/24.1f0ac3da.js"><link rel="prefetch" href="/assets/js/25.31e99865.js"><link rel="prefetch" href="/assets/js/26.7a904beb.js"><link rel="prefetch" href="/assets/js/27.fc4b3419.js"><link rel="prefetch" href="/assets/js/28.a670561c.js"><link rel="prefetch" href="/assets/js/29.612c1654.js"><link rel="prefetch" href="/assets/js/3.8490615e.js"><link rel="prefetch" href="/assets/js/30.56acc278.js"><link rel="prefetch" href="/assets/js/31.a629ea15.js"><link rel="prefetch" href="/assets/js/32.1f3d90b5.js"><link rel="prefetch" href="/assets/js/33.9eb3010d.js"><link rel="prefetch" href="/assets/js/34.24fafee5.js"><link rel="prefetch" href="/assets/js/35.0f3bdaea.js"><link rel="prefetch" href="/assets/js/36.9e578602.js"><link rel="prefetch" href="/assets/js/37.8eb8534b.js"><link rel="prefetch" href="/assets/js/38.f8db0a66.js"><link rel="prefetch" href="/assets/js/39.31305cc0.js"><link rel="prefetch" href="/assets/js/4.78dc510e.js"><link rel="prefetch" href="/assets/js/40.10bcf033.js"><link rel="prefetch" href="/assets/js/41.a49470df.js"><link rel="prefetch" href="/assets/js/42.9ce3e417.js"><link rel="prefetch" href="/assets/js/43.51a89bf9.js"><link rel="prefetch" href="/assets/js/44.540b4295.js"><link rel="prefetch" href="/assets/js/45.9bfb5051.js"><link rel="prefetch" href="/assets/js/46.bfe02766.js"><link rel="prefetch" href="/assets/js/47.4fdf4ea9.js"><link rel="prefetch" href="/assets/js/48.41ccbbc0.js"><link rel="prefetch" href="/assets/js/49.38a918bf.js"><link rel="prefetch" href="/assets/js/5.e38ee6ad.js"><link rel="prefetch" href="/assets/js/50.afab68d5.js"><link rel="prefetch" href="/assets/js/51.f1081f78.js"><link rel="prefetch" href="/assets/js/52.d862e142.js"><link rel="prefetch" href="/assets/js/53.f337c5d4.js"><link rel="prefetch" href="/assets/js/54.24f6dbc1.js"><link rel="prefetch" href="/assets/js/6.e70dce57.js"><link rel="prefetch" href="/assets/js/7.2b5160e1.js"><link rel="prefetch" href="/assets/js/8.f7cff187.js"><link rel="prefetch" href="/assets/js/9.af5debf6.js">
<link rel="stylesheet" href="/assets/css/0.styles.eb66b6c2.css">
</head>
<body>
<div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">TypeScript 从零实现 axios</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <!----></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><!----> <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>初识 TypeScript</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter1/" class="sidebar-link">Introduction</a></li><li><a href="/chapter1/install.html" class="sidebar-link">安装 TypeScript</a></li><li><a href="/chapter1/start.html" class="sidebar-link">编写第一个 TypeScript 程序</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>TypeScript 常用语法</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter2/type.html" class="sidebar-link">基础类型</a></li><li><a href="/chapter2/declare.html" class="sidebar-link">变量声明</a></li><li><a href="/chapter2/interface.html" class="sidebar-link">接口</a></li><li><a href="/chapter2/class.html" class="sidebar-link">类</a></li><li><a href="/chapter2/function.html" class="sidebar-link">函数</a></li><li><a href="/chapter2/generic.html" class="sidebar-link">泛型</a></li><li><a href="/chapter2/inference.html" class="sidebar-link">类型推断</a></li><li><a href="/chapter2/advance.html" class="sidebar-link">高级类型</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>ts-axios 项目初始化</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter3/require.html" class="sidebar-link">需求分析</a></li><li><a href="/chapter3/init.html" class="sidebar-link">初始化项目</a></li><li><a href="/chapter3/base.html" class="sidebar-link">编写基础请求代码</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>ts-axios 基础功能实现</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter4/url.html" class="sidebar-link">处理请求 url 参数</a></li><li><a href="/chapter4/data.html" class="sidebar-link">处理请求 body 数据</a></li><li><a href="/chapter4/header.html" class="sidebar-link">处理请求 header</a></li><li><a href="/chapter4/response.html" class="sidebar-link">获取响应数据</a></li><li><a href="/chapter4/response-header.html" class="sidebar-link">处理响应 header</a></li><li><a href="/chapter4/response-data.html" class="sidebar-link">处理响应 data</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>ts-axios 异常情况处理</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter5/error.html" class="sidebar-link">错误处理</a></li><li><a href="/chapter5/enhance.html" class="sidebar-link">错误信息增强</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>ts-axios 接口扩展</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter6/extend.html" class="sidebar-link">扩展接口</a></li><li><a href="/chapter6/overload.html" class="sidebar-link">axios 函数重载</a></li><li><a href="/chapter6/generic.html" class="sidebar-link">响应数据支持泛型</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>ts-axios 拦截器实现</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter7/interceptor.html" class="sidebar-link">拦截器设计与实现</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>ts-axios 配置化实现</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter8/merge.html" class="sidebar-link">合并配置的设计与实现</a></li><li><a href="/chapter8/transform.html" class="sidebar-link">请求和响应配置化</a></li><li><a href="/chapter8/create.html" class="sidebar-link">扩展 axios.create 静态接口</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>ts-axios 取消功能实现</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter9/cancel.html" class="sidebar-link">取消功能的设计与实现</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading"><span>ts-axios 更多功能实现</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter10/withCredentials.html" class="sidebar-link">withCredentials</a></li><li><a href="/chapter10/xsrf.html" class="sidebar-link">XSRF 防御</a></li><li><a href="/chapter10/upload-download.html" class="sidebar-link">上传和下载的进度监控</a></li><li><a href="/chapter10/auth.html" class="sidebar-link">HTTP 授权</a></li><li><a href="/chapter10/validateStatus.html" class="sidebar-link">自定义合法状态码</a></li><li><a href="/chapter10/paramsSerializer.html" class="sidebar-link">自定义参数序列化</a></li><li><a href="/chapter10/baseURL.html" class="sidebar-link">baseURL</a></li><li><a href="/chapter10/static.html" class="sidebar-link">静态方法扩展</a></li></ul></section></li><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>ts-axios 单元测试</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/chapter11/preface.html" class="sidebar-link">前言</a></li><li><a href="/chapter11/jest.html" class="sidebar-link">Jest 安装和配置</a></li><li><a href="/chapter11/helpers.html" class="sidebar-link">辅助模块单元测试</a></li><li><a href="/chapter11/requests.html" class="sidebar-link">请求模块单元测试</a></li><li><a href="/chapter11/headers.html" class="sidebar-link">headers 模块单元测试</a></li><li><a href="/chapter11/instance.html" class="active sidebar-link">Axios 实例模块单元测试</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/chapter11/instance.html#测试代码编写" class="sidebar-link">测试代码编写</a></li></ul></li><li><a href="/chapter11/interceptor.html" class="sidebar-link">拦截器模块单元测试</a></li><li><a href="/chapter11/mergeConfig.html" class="sidebar-link">mergeConfig 模块单元测试</a></li><li><a href="/chapter11/cancel.html" class="sidebar-link">请求取消模块单元测试</a></li><li><a href="/chapter11/more.html" class="sidebar-link">剩余模块单元测试</a></li></ul></section></li></ul> </aside> <main class="page"> <div class="content default"><h1 id="axios-实例模块单元测试"><a href="#axios-实例模块单元测试" aria-hidden="true" class="header-anchor">#</a> Axios 实例模块单元测试</h1> <p><code>ts-axios</code> 提供了 <code>axios.create</code> 静态方法,返回一个 <code>instance</code> 实例,我们需要对这个模块做测试。</p> <h2 id="测试代码编写"><a href="#测试代码编写" aria-hidden="true" class="header-anchor">#</a> 测试代码编写</h2> <p><code>test/instance.spec.ts</code>:</p> <div class="language-typescript extra-class"><pre class="language-typescript"><code><span class="token keyword">import</span> axios<span class="token punctuation">,</span> <span class="token punctuation">{</span> AxiosRequestConfig<span class="token punctuation">,</span> AxiosResponse <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'../src/index'</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> getAjaxRequest <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'./helper'</span>
<span class="token function">describe</span><span class="token punctuation">(</span><span class="token string">'instance'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">beforeEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
jasmine<span class="token punctuation">.</span>Ajax<span class="token punctuation">.</span><span class="token function">install</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">afterEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
jasmine<span class="token punctuation">.</span>Ajax<span class="token punctuation">.</span><span class="token function">uninstall</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should make a http request without verb helper'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token function">instance</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>url<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should make a http request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span><span class="token keyword">get</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>url<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'GET'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should make a post request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span><span class="token function">post</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'POST'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should make a put request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'PUT'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should make a patch request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span><span class="token function">patch</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'PATCH'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should make a options request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span><span class="token function">options</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'OPTIONS'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should make a delete request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span><span class="token keyword">delete</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'DELETE'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should make a head request'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span><span class="token function">head</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>method<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'HEAD'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should use instance options'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">{</span> timeout<span class="token punctuation">:</span> <span class="token number">1000</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span><span class="token keyword">get</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> <span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>timeout<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should have defaults.headers'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">{</span> baseURL<span class="token punctuation">:</span> <span class="token string">'https://api.example.com'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">expect</span><span class="token punctuation">(</span><span class="token keyword">typeof</span> instance<span class="token punctuation">.</span>defaults<span class="token punctuation">.</span>headers<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'object'</span><span class="token punctuation">)</span>
<span class="token function">expect</span><span class="token punctuation">(</span><span class="token keyword">typeof</span> instance<span class="token punctuation">.</span>defaults<span class="token punctuation">.</span>headers<span class="token punctuation">.</span>common<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span><span class="token string">'object'</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should have interceptors on the instance'</span><span class="token punctuation">,</span> done <span class="token operator">=></span> <span class="token punctuation">{</span>
axios<span class="token punctuation">.</span>interceptors<span class="token punctuation">.</span>request<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>config <span class="token operator">=></span> <span class="token punctuation">{</span>
config<span class="token punctuation">.</span>timeout <span class="token operator">=</span> <span class="token number">2000</span>
<span class="token keyword">return</span> config
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">const</span> instance <span class="token operator">=</span> axios<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
instance<span class="token punctuation">.</span>interceptors<span class="token punctuation">.</span>request<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>config <span class="token operator">=></span> <span class="token punctuation">{</span>
config<span class="token punctuation">.</span>withCredentials <span class="token operator">=</span> <span class="token boolean">true</span>
<span class="token keyword">return</span> config
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">let</span> response<span class="token punctuation">:</span> AxiosResponse
instance<span class="token punctuation">.</span><span class="token keyword">get</span><span class="token punctuation">(</span><span class="token string">'/foo'</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>res <span class="token operator">=></span> <span class="token punctuation">{</span>
response <span class="token operator">=</span> res
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">getAjaxRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>request <span class="token operator">=></span> <span class="token punctuation">{</span>
request<span class="token punctuation">.</span><span class="token function">respondWith</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
status<span class="token punctuation">:</span> <span class="token number">200</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token function">expect</span><span class="token punctuation">(</span>response<span class="token punctuation">.</span>config<span class="token punctuation">.</span>timeout<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toEqual</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
<span class="token function">expect</span><span class="token punctuation">(</span>response<span class="token punctuation">.</span>config<span class="token punctuation">.</span>withCredentials<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toEqual</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span>
<span class="token function">done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token string">'should get the computed uri'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
<span class="token keyword">const</span> fakeConfig<span class="token punctuation">:</span> AxiosRequestConfig <span class="token operator">=</span> <span class="token punctuation">{</span>
baseURL<span class="token punctuation">:</span> <span class="token string">'https://www.baidu.com/'</span><span class="token punctuation">,</span>
url<span class="token punctuation">:</span> <span class="token string">'/user/12345'</span><span class="token punctuation">,</span>
params<span class="token punctuation">:</span> <span class="token punctuation">{</span>
idClient<span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
idTest<span class="token punctuation">:</span> <span class="token number">2</span><span class="token punctuation">,</span>
testString<span class="token punctuation">:</span> <span class="token string">'thisIsATest'</span>
<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token function">expect</span><span class="token punctuation">(</span>axios<span class="token punctuation">.</span><span class="token function">getUri</span><span class="token punctuation">(</span>fakeConfig<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toBe</span><span class="token punctuation">(</span>
<span class="token string">'https://www.baidu.com/user/12345?idClient=1&idTest=2&testString=thisIsATest'</span>
<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div><p>至此我们完成了 <code>ts-axios</code> 库 <code>Axios</code> 实例模块相关业务逻辑的测试,下一节课我们会对拦截器模块做测试。</p></div> <footer class="page-edit"><!----> <!----></footer> <div class="page-nav"><p class="inner"><span class="prev">
←
<a href="/chapter11/headers.html" class="prev">
headers 模块单元测试
</a></span> <span class="next"><a href="/chapter11/interceptor.html">
拦截器模块单元测试
</a>
→
</span></p></div> </main></div><div class="global-ui"></div></div>
<script src="/assets/js/app.c982d9fb.js" defer></script><script src="/assets/js/2.9f28cd09.js" defer></script><script src="/assets/js/17.e951ed3d.js" defer></script>
</body>
</html>
| 211.307692 | 7,571 | 0.710177 |
a1bbc1bfa4638bc758b8f7470c6802b1b8f58046 | 326 | go | Go | api/controller/controller.go | mylxsw/wizard-personal | a18d6c55bdc9e2e333c85c62009f0b09610ad214 | [
"MIT"
] | null | null | null | api/controller/controller.go | mylxsw/wizard-personal | a18d6c55bdc9e2e333c85c62009f0b09610ad214 | [
"MIT"
] | 1 | 2020-05-11T06:21:32.000Z | 2020-05-11T06:21:32.000Z | api/controller/controller.go | mylxsw/wizard-personal | a18d6c55bdc9e2e333c85c62009f0b09610ad214 | [
"MIT"
] | null | null | null | package controller
import "github.com/pkg/errors"
type OperationResponse struct {
Message string `json:"message"`
}
func Success() (*OperationResponse, error) {
return &OperationResponse{Message: "操作成功"}, nil
}
func Error(err error, message string) (*OperationResponse, error) {
return nil, errors.Wrap(err, message)
}
| 20.375 | 67 | 0.745399 |
9dcdeab5a42bcc9bbc484e7e418f4bce890da817 | 2,887 | kt | Kotlin | inference/inference-core/src/commonMain/kotlin/io/kinference.core/operators/quantization/DequantizeLinear.kt | JetBrains-Research/kotlin-inference | 65ac98cfcb1d9f996fc389001fc84a3536e59e28 | [
"Apache-2.0"
] | 1 | 2020-05-07T00:17:20.000Z | 2020-05-07T00:17:20.000Z | inference/inference-core/src/commonMain/kotlin/io/kinference.core/operators/quantization/DequantizeLinear.kt | JetBrains-Research/kotlin-inference | 65ac98cfcb1d9f996fc389001fc84a3536e59e28 | [
"Apache-2.0"
] | null | null | null | inference/inference-core/src/commonMain/kotlin/io/kinference.core/operators/quantization/DequantizeLinear.kt | JetBrains-Research/kotlin-inference | 65ac98cfcb1d9f996fc389001fc84a3536e59e28 | [
"Apache-2.0"
] | null | null | null | package io.kinference.core.operators.quantization
import io.kinference.attribute.Attribute
import io.kinference.core.data.tensor.KITensor
import io.kinference.core.data.tensor.asTensor
import io.kinference.data.ONNXData
import io.kinference.graph.Contexts
import io.kinference.ndarray.arrays.NumberNDArray
import io.kinference.operator.*
import kotlin.time.ExperimentalTime
import io.kinference.protobuf.message.AttributeProto
import io.kinference.protobuf.message.TensorProto
sealed class DequantizeLinear(info: OperatorInfo, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) : Operator<KITensor, KITensor>(info, attributes, inputs, outputs) {
companion object {
private val DEFAULT_VERSION = VersionInfo(sinceVersion = 10)
operator fun invoke(version: Int?, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) = when (version ?: DEFAULT_VERSION.sinceVersion) {
in DequantizeLinearVer1.VERSION.asRange() -> DequantizeLinearVer1(attributes, inputs, outputs)
else -> error("Unsupported version of DequantizeLinear operator: $version")
}
}
}
@ExperimentalTime
class DequantizeLinearVer1(attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) : DequantizeLinear(INFO, attributes, inputs, outputs) {
companion object {
private val IN_TYPE_CONSTRAINTS = setOf(TensorProto.DataType.INT8, TensorProto.DataType.UINT8)
private val OUT_TYPE_CONSTRAINTS = setOf(TensorProto.DataType.FLOAT, TensorProto.DataType.FLOAT16)
private val ATTRIBUTES_INFO = listOf(
AttributeInfo("axis", setOf(AttributeProto.AttributeType.INT), required = false, default = 1)
)
private val INPUTS_INFO = listOf(
IOInfo(0, IN_TYPE_CONSTRAINTS, "x", optional = false),
IOInfo(0, OUT_TYPE_CONSTRAINTS, "x_scale", optional = false),
IOInfo(0, IN_TYPE_CONSTRAINTS, "x_zero_point", optional = true)
)
private val OUTPUTS_INFO = listOf(IOInfo(0, OUT_TYPE_CONSTRAINTS, "y", optional = false))
internal val VERSION = VersionInfo(sinceVersion = 10)
private val INFO = OperatorInfo("DequantizeLinear", ATTRIBUTES_INFO, INPUTS_INFO, OUTPUTS_INFO, VERSION, OperatorInfo.DEFAULT_DOMAIN)
}
private val axis: Int by attribute { it: Number -> it.toInt() }
override fun <D : ONNXData<*, *>> apply(contexts: Contexts<D>, inputs: List<KITensor?>): List<KITensor?> {
val input = inputs[0]!!.data as NumberNDArray
val scale = inputs[1]!!.data
val zeroPoint = inputs.getOrNull(2)?.data
require(zeroPoint == null || scale.shape.contentEquals(zeroPoint.shape)) { "Zero point and scale tensors should have the same dims" }
return listOf(input.dequantize(zeroPoint, scale, axis).asTensor("y"))
}
}
| 47.327869 | 203 | 0.72151 |
2cb4c0b1df7e272bcc35772887e4f8e04647067c | 118 | kt | Kotlin | delivery-app/delivery-domain/src/main/kotlin/mija/hex/domain/delivery/port/primary/DeliveryCommandService.kt | jacol84/mija-hex | 061e017be49a1f9f5a04df6e159362ffe0425c21 | [
"MIT"
] | 1 | 2020-06-12T12:00:32.000Z | 2020-06-12T12:00:32.000Z | delivery-app/delivery-domain/src/main/kotlin/mija/hex/domain/delivery/port/primary/DeliveryCommandService.kt | jacol84/mija-hex | 061e017be49a1f9f5a04df6e159362ffe0425c21 | [
"MIT"
] | 2 | 2020-06-05T16:45:54.000Z | 2020-06-05T16:56:53.000Z | delivery-app/delivery-domain/src/main/kotlin/mija/hex/domain/delivery/port/primary/DeliveryCommandService.kt | jacol84/mija-hex | 061e017be49a1f9f5a04df6e159362ffe0425c21 | [
"MIT"
] | null | null | null | package mija.hex.domain.delivery.port.primary
interface DeliveryCommandService {
fun deliverOrder(orderId: Int)
} | 23.6 | 45 | 0.805085 |
384e3c037447b3c7a6b2c45b5112213d7760a28a | 980 | kt | Kotlin | src/main/kotlin/org/test/Bootstrap.kt | mvysny/vaadin-coroutines-demo | 7bc5d0099e5b6233d6e9addef6cf8a406421b9a2 | [
"MIT"
] | 5 | 2017-12-18T14:43:10.000Z | 2022-01-16T16:40:29.000Z | src/main/kotlin/org/test/Bootstrap.kt | mvysny/vaadin-coroutines-demo | 7bc5d0099e5b6233d6e9addef6cf8a406421b9a2 | [
"MIT"
] | 3 | 2020-10-29T07:13:50.000Z | 2022-03-30T06:16:12.000Z | src/main/kotlin/org/test/Bootstrap.kt | mvysny/vaadin-coroutines-demo | 7bc5d0099e5b6233d6e9addef6cf8a406421b9a2 | [
"MIT"
] | 2 | 2019-03-18T11:40:01.000Z | 2021-01-12T23:09:11.000Z | package org.test
import com.vaadin.flow.component.notification.Notification
import com.vaadin.flow.component.notification.NotificationVariant
import com.vaadin.flow.server.ErrorHandler
import com.vaadin.flow.server.ServiceInitEvent
import com.vaadin.flow.server.VaadinServiceInitListener
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class Bootstrap : VaadinServiceInitListener {
override fun serviceInit(event: ServiceInitEvent) {
event.source.addSessionInitListener {
it.session.errorHandler = ErrorHandler { event ->
log.error("UI error", event.throwable)
Notification("Internal error: ${event.throwable}", 5000, Notification.Position.TOP_CENTER).apply {
addThemeVariants(NotificationVariant.LUMO_ERROR)
}.open()
}
}
}
companion object {
@JvmStatic
private val log: Logger = LoggerFactory.getLogger(Bootstrap::class.java)
}
} | 36.296296 | 114 | 0.706122 |
7478e1566a003a7252637ba7df239d0382f53cca | 42,946 | h | C | PersistentList.h | spratt/PersistentList | 4f2f5b8beddfb86e22cc824cff76dad63cc6e88c | [
"0BSD"
] | 2 | 2016-04-18T05:29:25.000Z | 2016-06-17T05:47:36.000Z | PersistentList.h | spratt/PersistentList | 4f2f5b8beddfb86e22cc824cff76dad63cc6e88c | [
"0BSD"
] | null | null | null | PersistentList.h | spratt/PersistentList | 4f2f5b8beddfb86e22cc824cff76dad63cc6e88c | [
"0BSD"
] | null | null | null | //-*- mode: c++ -*-////////////////////////////////////////////////////////////
// Copyright (c) 2011 - 2012 by //
// Simon Pratt //
// (All rights reserved) //
///////////////////////////////////////////////////////////////////////////////
// //
// FILE: PersistentList.h //
// //
// MODULE: Persistent List //
// //
// PURPOSE: Implements a persistent list data structure. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////////
// //
// Public Variable: Description: //
// ---------------- ------------ //
// T ListNode.data The data to be stored within a node //
// ListNode<T, Compare>* next The next node in the list //
// //
///////////////////////////////////////////////////////////////////////////////
// //
// Public Methods: //
// //
// ListNode<T>::ListNode(int t, const T& original_data) //
// ListNode<T>::getNextIndex(int t) //
// ListNode<T>::getNextAtIndex(int t) //
// ListNode<T>::numberOfChangeIndices(int t) //
// ListNode<T>::getNext(int t) //
// ListNode<T>::setNext(int t, ListNode<T>* ln) //
// ListNode<T>::printList(int t) //
// //
// PersistentList<T, Compare>::PersistentList() //
// int PersistentList<T, Compare>::setHead(int t, ListNode<T>* ln) //
// ListNode<T>* PersistentList<T, Compare>::getList(int t) //
// size_t PersistentList<T, Compare>::size() //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef PERSISTENTLIST_H
#define PERSISTENTLIST_H
#include <iostream>
#include <vector>
#include <map>
#include <assert.h>
using namespace std;
namespace persistent_list {
/////////////////////////////////////////////////////////////////////////////
// PersistentList empty declaration //
// (for forward reference) //
/////////////////////////////////////////////////////////////////////////////
template <class T, class Compare = less<T> >
class PersistentList;
/////////////////////////////////////////////////////////////////////////////
// ListNode interface //
/////////////////////////////////////////////////////////////////////////////
template <class T, class Compare = less<T> >
class ListNode {
int* time;
ListNode<T, Compare>** next;
int _SIZE;
int _LAST;
public:
T data;
PersistentList<T, Compare>* list;
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: ListNode //
// //
// PURPOSE: Basic constructor //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: T/original_data //
// Description: The value to store in the data of the ListNode //
// //
// Type/Name: int/size //
// Description: How many next pointers the node should have. If this //
// ever fills up, a new node will be created to //
// store next pointers at times after the node was filled.//
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
ListNode(const T& original_data, int size, PersistentList<T, Compare>* list)
: _SIZE(size), _LAST(-1), data(original_data), list(list) {
time = new int[size];
next = new ListNode<T, Compare>*[size];
}
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: ~ListNode //
// //
// PURPOSE: Destructor //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: Void. //
// Description: None. //
// //
// RETURN: Void. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
~ListNode() {
delete time;
delete next;
}
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: getSize //
// //
// PURPOSE: Returns the size of the node. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: Void. //
// Description: None. //
// //
// RETURN: //
// Type/Name: int //
// Description: The size of the node. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
int getSize();
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: getNextIndex //
// //
// PURPOSE: Given a time t, gives the change index of the nearest //
// time. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: int/t //
// Description: The time for which to search. //
// //
// RETURN: The nearest change index in the next pointer vector. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
int getNextIndex(int t);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: getNextAtIndex //
// //
// PURPOSE: Allows next pointer to be retrieved by change //
// index. This is useful for efficient //
// construction of persistent lists. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: int/ci //
// Description: The change index at which to retrieve the next pointer.//
// //
// RETURN: //
// Type/Name: ListNode<T, Compare>* //
// Description: The next pointer at the given change index. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
ListNode<T, Compare>* getNextAtIndex(int ci);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: numberOfChangeIndices //
// //
// PURPOSE: Returns the number of change indices, i.e. the number //
// of times this node's next pointer has been changed and //
// stored. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: Void. //
// Description: None. //
// //
// RETURN: //
// Type/Name: int //
// Description: The number of change indices of the current node. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
int numberOfChangeIndices();
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: getNext //
// //
// PURPOSE: Retrieves the next pointer at a given time. If //
// the given time is not set, returns the pointer //
// which would directly precede it. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: int/t //
// Description: The time at which to retrieve the pointer //
// //
// RETURN: //
// Type/Name: ListNode<T, Compare>* //
// Description: The next pointer at time t. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
ListNode<T, Compare>* getNext(int t);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: setNext //
// //
// PURPOSE: Set the next pointer at time t //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: int/t //
// Description: The time at which to set the pointer. //
// //
// Type/Name: ListNode<T, Compare>*/ln //
// Description: The pointer to which to assign next. //
// //
// RETURN: int return code. 0 means success //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
virtual int setNext(int t, ListNode<T, Compare>* ln);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: printList //
// //
// PURPOSE: Prints a list at time t to cout. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: int/t //
// Description: The time at which to print the list. //
// //
// RETURN: int return code. 0 means success. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
int printList(int t);
};
/////////////////////////////////////////////////////////////////////////////
// ListNode implementation //
/////////////////////////////////////////////////////////////////////////////
template <class T, class Compare>
int ListNode<T, Compare>::getSize() { return _SIZE; }
template <class T, class Compare>
int ListNode<T, Compare>::getNextIndex(int t) {
assert(this != NULL);
assert(t >= 0);
int index = -1;
int begin = 0, end = _LAST;
// binary search
while(begin <= end) {
index = (begin+end)/2;
if(t == time[index]) {
// done, break out of loop
break;
} else if(t < time[index]) {
// repeat binary search on left half
end = index -1;
} else {
// repeat binary search on right half
begin = index +1;
}
}
assert(index <= t);
// report final index
return index;
}
template <class T, class Compare>
ListNode<T, Compare>* ListNode<T, Compare>::getNextAtIndex(int ci) {
assert(this != NULL);
assert(ci >= 0);
assert(ci < numberOfChangeIndices());
return next[ci];
}
template <class T, class Compare>
int ListNode<T, Compare>::numberOfChangeIndices() {
assert(this != NULL);
return _LAST + 1;
}
template <class T, class Compare>
ListNode<T, Compare>* ListNode<T, Compare>::getNext(int t) {
assert(this != NULL);
assert(t >= 0);
// find nearest time
int index = getNextIndex(t);
// if there are no next pointers, bail
if(index == -1) return NULL;
// default to NULL
ListNode<T, Compare>* ln = NULL;
// while the time at index is greater than the desired time
while(time[index] > t) {
// decrement if not first
--index;
// if first, bail
if(index < 0)
return NULL;
}
// find and return next pointer at nearest time less than or equal to given
ln = getNextAtIndex(index);
return ln;
}
template <class T, class Compare>
int ListNode<T, Compare>::setNext(int t, ListNode<T, Compare>* ln) {
assert(this != NULL);
// since NULL is the default
if(ln == NULL)
return -1; // bail if trying to set next to NULL
// if trying to set next to previous next pointer, bail
// since getNext will by default return the node at the largest
// time before the requested time
if(_LAST >= 0 && next[_LAST] == ln)
return 1;
// check if the node has room
if(_LAST+1 < _SIZE) { // has room
// since we have restricted point insertion to strictly increasing
// time, we can simply push these values to the back of their arrays
++_LAST;
time[_LAST] = t;
next[_LAST] = ln;
} else { // full
// create new node
ListNode<T, Compare>* new_ln = list->createNode(data);
// save the new node for use in all future lists
list->addToBuildTree(data,new_ln);
// set next on new node (guaranteed not full) to given next node
new_ln->setNext(t,ln);
// if this node is head
ListNode<T, Compare>* node = list->getList(t);
if(this == node) {
// set head at t to newly created node
list->setHead(t,new_ln);
} else { // otherwise there is a node which precedes this node
// find node
typename map< T, ListNode<T, Compare>*, Compare >::iterator it =
list->findInBuildTree(data);
// move to preceding node
--it;
// set next to new node
it->second->setNext(t,new_ln);
}
}
// success
return 0;
}
template <class T, class Compare>
int ListNode<T, Compare>::printList(int t) {
assert(this != NULL);
assert(t >= 0);
cout << data << "->" << flush; // inefficient to flush every line
ListNode<T, Compare>* ln = getNext(t);
if(ln != NULL)
ln->printList(t);
else
cout << "NULL" << flush;
// success
return 0;
}
/////////////////////////////////////////////////////////////////////////////
// PersistentList interface //
/////////////////////////////////////////////////////////////////////////////
template < class T, class Compare >
class PersistentList {
vector< ListNode<T, Compare>* > lists;
map< T, ListNode<T, Compare>*, Compare >* build_tree;
vector< ListNode<T, Compare>* > all_nodes;
int _NODE_SIZE;
bool _LOCKED;
int nNodes;
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: setHead //
// //
// PURPOSE: Sets a node to the head of the list at time t. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: int/t //
// Description: Time t at which to set //
// //
// Type/Name: ListNode<T, Compare>*/ln //
// Description: A pointer to the node to set //
// //
// RETURN: //
// Type/Name: int //
// Description: A return code, 0 means success. //
// //
// NOTES: Assumes list at time t exists or is one past the end. //
// //
///////////////////////////////////////////////////////////////////////////
int setHead(int t, ListNode<T, Compare>* ln);
public:
friend class ListNode<T, Compare>;
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: PersistentList //
// //
// PURPOSE: Empty constructor //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: int/size //
// Description: The number of next pointers each node should have. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
PersistentList(int size)
: lists(), all_nodes(), _NODE_SIZE(size), _LOCKED(false), nNodes(0)
{
build_tree = new map< T, ListNode<T, Compare>*, Compare >();
}
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: ~PersistentList //
// //
// PURPOSE: Destructor //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: Void. //
// Description: None. //
// //
// RETURN: Void. //
// //
// NOTES: Frees all allocated memory. //
// //
///////////////////////////////////////////////////////////////////////////
virtual ~PersistentList() {
if(!_LOCKED)
lock();
for(int i = 0; i < (int)all_nodes.size(); ++i)
delete all_nodes[i];
}
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: insert //
// //
// PURPOSE: Inserts a data node into the structure. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: const T&/data //
// Description: The data to be inserted //
// //
// RETURN: //
// Type/Name: int //
// Description: 0 for success. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
int insert(const T& data);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: addToBuildTree //
// //
// PURPOSE: Saves a node to the build tree //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: const T&/key //
// Description: The key at which to save the node //
// //
// Type/Name: ListNode<T, Compare>*/node //
// Description: The node to save. //
// //
// RETURN: int return code. 0 means success. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
int addToBuildTree(const T& key, ListNode<T, Compare>* node);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: findInBuildTree //
// //
// PURPOSE: Retrieves a node in the build tree. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: T/datum //
// Description: Item to find in build tree. //
// //
// RETURN: //
// Type/Name: map<T, ListNode<T, Compare>*, Compare >::iterator //
// Description: An iterator to the object in the build tree. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
typename map<T, ListNode<T, Compare>*, Compare >::iterator
findInBuildTree(const T& datum);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: lock //
// //
// PURPOSE: Locks the list, preventing any further updates //
// to the data and freeing temporary structures //
// used in building the list. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: Void. //
// Description: None. //
// //
// RETURN: Void. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
int lock();
///////////////////////////////////////////////////////////////////////////
//
// FUNCTION NAME: createNode
//
// PURPOSE: Creates a node with the specified size
// containing a given value.
//
// SECURITY: public
//
// PARAMETERS
// Type/Name: T/data
// Description: The data which will be stored in the node.
//
// RETURN:
// Type/Name: ListNode<T, Compare>*
// Description: A pointer to a new node containing the given data.
//
// NOTES: Allocates the node on the heap. It will belong
// to the invoker and it will be their
// responsibilty to free the space once it is no
// longer in use.
//
///////////////////////////////////////////////////////////////////////////
ListNode<T, Compare>* createNode(const T& data);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: getList //
// //
// PURPOSE: Gets the list at time t. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: int/t //
// Description: The time at which to retrieve the list. //
// //
// RETURN: The first node in the list at time t. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
ListNode<T, Compare>* getList(int t);
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: size //
// //
// PURPOSE: Returns the number of points in the structure //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: Void. //
// Description: None. //
// //
// RETURN: //
// Type/Name: size_t //
// Description: The number of points in the structure //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
size_t size();
///////////////////////////////////////////////////////////////////////////
// //
// FUNCTION NAME: memoryUsage //
// //
// PURPOSE: Returns the amount of memory used by the structure. //
// //
// SECURITY: public //
// //
// PARAMETERS //
// Type/Name: Void. //
// Description: None. //
// //
// RETURN: //
// Type/Name: size_t //
// Description: The amount of memory used by the structure. //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////
size_t memoryUsage();
};
/////////////////////////////////////////////////////////////////////////////
// PersistentList implementation //
/////////////////////////////////////////////////////////////////////////////
template <class T, class Compare>
int PersistentList<T, Compare>::insert(const T& data) {
assert(!_LOCKED);
// check for duplicate
if(build_tree->find(data) != build_tree->end())
return -1;
// determine the time
int t = build_tree->size();
// create a new node
ListNode<T, Compare>* ln = createNode(data);
// insert point into tree O(logn)
addToBuildTree(data,ln);
// find previous node O(logn)ish
typename map<T, ListNode<T, Compare>*, Compare >::iterator it =
build_tree->find(data);
// if new node is at the beginning
if(it == build_tree->begin()) {
// set head to new node
setHead(t,ln);
// if this isn't the first node
if(t > 0)
// set next on the node to the previous head
ln->setNext(t,getList(t-1));
}
// otherwise, the new node must not be at the beginning
else {
// create a new head for the list
setHead(t,getList(t-1));
// find previous node
ListNode<T, Compare>* prev = (--it)->second;
// set next on new node to next of previous node
prev->setNext(t,ln);
// put the iterator back into its initial state
++it;
// if the new node was not at the end
if(++it != build_tree->end()) {
// set the next pointer on the new node
ln->setNext(t,it->second);
}
}
// success
return 0;
}
template <class T, class Compare>
int PersistentList<T, Compare>::addToBuildTree(const T& key,
ListNode<T, Compare>* node) {
assert(!_LOCKED);
(*build_tree)[key] = node;
// success
return 0;
}
template <class T, class Compare>
typename map<T, ListNode<T, Compare>*, Compare >::iterator
PersistentList<T, Compare>::findInBuildTree(const T& datum) {
assert(!_LOCKED);
return build_tree->find(datum);
}
template <class T, class Compare>
int PersistentList<T, Compare>::lock() {
if(_LOCKED)
return 1; // already locked
// otherwise
_LOCKED = true;
delete build_tree;
// success
return 0;
}
template <class T, class Compare>
ListNode<T, Compare>* PersistentList<T, Compare>::createNode(const T& data) {
++nNodes;
ListNode<T, Compare>* ln = new ListNode<T, Compare>(data,(int)_NODE_SIZE,this);
all_nodes.push_back(ln);
return ln;
}
template <class T, class Compare>
int PersistentList<T, Compare>::setHead(int t, ListNode<T, Compare>* ln) {
assert(t >= 0);
assert(t <= (int)lists.size());
if(t == (int)lists.size())
lists.push_back(ln);
else
lists[t] = ln;
return 0; // success
}
template <class T, class Compare>
ListNode<T, Compare>* PersistentList<T, Compare>::getList(int t) {
assert(t < (int)lists.size());
return lists[t];
}
template <class T, class Compare>
size_t PersistentList<T, Compare>::size() {
return lists.size();
}
template <class T, class Compare>
size_t PersistentList<T, Compare>::memoryUsage() {
size_t s = nNodes * sizeof(ListNode<T, Compare>);
if(!_LOCKED)
s += nNodes * (sizeof(T) + sizeof(ListNode<T, Compare>));
return s;
}
}
#endif
| 55.919271 | 83 | 0.243818 |
55925e1b90b547f8461608004ad2ef613aa36249 | 177 | html | HTML | src/main/resources/static/501.html | ser1103/PlainServer | eb04d3f55ed2f23ac03444a8adb165a54649a299 | [
"MIT"
] | null | null | null | src/main/resources/static/501.html | ser1103/PlainServer | eb04d3f55ed2f23ac03444a8adb165a54649a299 | [
"MIT"
] | null | null | null | src/main/resources/static/501.html | ser1103/PlainServer | eb04d3f55ed2f23ac03444a8adb165a54649a299 | [
"MIT"
] | null | null | null | <html>
<head><title>Error</title></head>
<body>
<h2>Error: 501 Not Implemented</h2>
<p>Oops! It seems that you send not supported operation, try again.</p>
</body>
</html> | 25.285714 | 72 | 0.666667 |
bee4832c20bb1bf45dec3918bc94c0a089401196 | 1,163 | html | HTML | _layouts/agency.html | DaveSkender/pif-website | f69960f6b8aae535507b5e6bfdff665cca55cd61 | [
"CC0-1.0"
] | 16 | 2016-03-12T01:59:15.000Z | 2022-03-03T14:58:41.000Z | _layouts/agency.html | DaveSkender/pif-website | f69960f6b8aae535507b5e6bfdff665cca55cd61 | [
"CC0-1.0"
] | 129 | 2015-08-31T17:21:10.000Z | 2022-03-30T21:15:22.000Z | _layouts/agency.html | DaveSkender/pif-website | f69960f6b8aae535507b5e6bfdff665cca55cd61 | [
"CC0-1.0"
] | 70 | 2015-10-03T21:45:52.000Z | 2022-03-14T21:01:04.000Z | ---
layout: default-main
---
<div class="usa-layout-docs usa-section">
<div class="grid-container">
<div class="grid-row grid-gap">
<div class="usa-layout-docs__main desktop:grid-col-9 usa-prose">
<div class="clearfix">
<h4 class="text-uppercase text-secondary-dark float-left margin-0">{{ page.agency }}</h4>
{% if page.project_link %}
<a href="{{ page.url }}" class="usa-button float-right usa-button--secondary">
Agency website
</a>
{% endif %}
</div>
<h1 class="title">{{ page.fullname }}</h1>
<div class="grid-container">
<div class="grid-row grid-gap">
<div class="tablet:grid-col-3">
{% if page.agency_logo %}
{% asset "{{ page.agency_logo }}" class="img-circle img-responsive project-image margin-auto" alt="{{ page.name }}" %}
{% endif %}
</div>
<div class="grid-col-9">
<p class="usa-intro">
{{ page.description }}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
| 29.820513 | 132 | 0.49785 |
81be133e32de8913b47737180af313282a38fc9a | 1,133 | rs | Rust | src/controller.rs | OCzarnecki/status-monitor | c8a0e61966c84da7a69ffb082b3f06048ed391fb | [
"MIT"
] | null | null | null | src/controller.rs | OCzarnecki/status-monitor | c8a0e61966c84da7a69ffb082b3f06048ed391fb | [
"MIT"
] | null | null | null | src/controller.rs | OCzarnecki/status-monitor | c8a0e61966c84da7a69ffb082b3f06048ed391fb | [
"MIT"
] | null | null | null | use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio;
use crate::{Config, Timeouts};
use crate::config::Service;
use crate::telegram_api;
pub async fn start_daemon(cfg_other: Arc<Config>, timeouts_other: Arc<Mutex<Timeouts>>) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(60));
let cfg = cfg_other.clone();
let timeouts = timeouts_other.clone();
loop {
interval.tick().await;
let failed: Vec<Service>;
{
let mut mut_timeouts = timeouts.lock().unwrap();
failed = mut_timeouts.get_failed();
}
send_failure_report(cfg.clone(), &failed).await;
}
})
}
async fn send_failure_report(cfg: Arc<Config>, failed_services: &Vec<Service>) {
if failed_services.is_empty() {
return
}
let mut message = "The following services failed to report:".to_owned();
for s in failed_services {
message += &format!("\n - {}", s.name);
}
telegram_api::fire_message(cfg, &message).await;
}
| 29.815789 | 120 | 0.60459 |
1100fa83bcdae17702b26ae6b20ae59adb7a9d7f | 168 | kt | Kotlin | src/main/java/opengis/model/app/request/wmts/Layer.kt | chris-hatton/opengis-client-kotlin | 9b98feec99baf651b2e0c731052a321cd0cdb64b | [
"MIT"
] | 4 | 2017-10-31T02:36:36.000Z | 2022-01-05T05:06:55.000Z | src/main/java/opengis/model/app/request/wmts/Layer.kt | chris-hatton/opengis-client-kotlin | 9b98feec99baf651b2e0c731052a321cd0cdb64b | [
"MIT"
] | null | null | null | src/main/java/opengis/model/app/request/wmts/Layer.kt | chris-hatton/opengis-client-kotlin | 9b98feec99baf651b2e0c731052a321cd0cdb64b | [
"MIT"
] | null | null | null | package opengis.model.app.request.wmts
/**
* Created by Chris on 11/08/2017.
*/
data class Layer( val name: String ) {
override fun toString(): String = name
}
| 16.8 | 42 | 0.672619 |
067d23d8e51c954f1596fd56aac4a30d34cbf4be | 8,056 | swift | Swift | Sources/SwiftyPress/Repositories/Post/PostRepository.swift | nidegen/SwiftyPress | 123dd685b8ae0835c8b0f73fa02ae119905e70ed | [
"MIT"
] | 58 | 2016-05-18T17:28:27.000Z | 2021-12-29T07:43:28.000Z | Sources/SwiftyPress/Repositories/Post/PostRepository.swift | nidegen/SwiftyPress | 123dd685b8ae0835c8b0f73fa02ae119905e70ed | [
"MIT"
] | 19 | 2017-03-25T19:50:48.000Z | 2020-01-06T01:49:27.000Z | Sources/SwiftyPress/Repositories/Post/PostRepository.swift | nidegen/SwiftyPress | 123dd685b8ae0835c8b0f73fa02ae119905e70ed | [
"MIT"
] | 18 | 2017-03-25T19:51:07.000Z | 2020-12-22T00:59:07.000Z | //
// PostRepository.swift
// SwiftPress
//
// Created by Basem Emara on 2018-05-29.
// Copyright © 2019 Zamzam Inc. All rights reserved.
//
import Foundation.NSURL
import ZamzamCore
public struct PostRepository {
private let service: PostService
private let cache: PostCache
private let dataRepository: DataRepository
private let preferences: Preferences
private let constants: Constants
private let log: LogRepository
public init(
service: PostService,
cache: PostCache,
dataRepository: DataRepository,
preferences: Preferences,
constants: Constants,
log: LogRepository
) {
self.service = service
self.cache = cache
self.dataRepository = dataRepository
self.preferences = preferences
self.constants = constants
self.log = log
}
}
public extension PostRepository {
func fetch(id: Int, completion: @escaping (Result<ExtendedPost, SwiftyPressError>) -> Void) {
cache.fetch(id: id) {
let request = PostAPI.ItemRequest(
taxonomies: self.constants.taxonomies,
postMetaKeys: self.constants.postMetaKeys
)
// Retrieve missing cache data from cloud if applicable
if case .nonExistent? = $0.error {
self.service.fetch(id: id, with: request) {
guard case let .success(item) = $0 else {
completion($0)
return
}
self.cache.createOrUpdate(item, completion: completion)
}
return
}
// Immediately return local response
completion($0)
guard case let .success(cacheElement) = $0 else { return }
// Sync remote updates to cache if applicable
self.service.fetch(id: id, with: request) {
// Validate if any updates occurred and return
guard case let .success(element) = $0,
element.post.modifiedAt > cacheElement.post.modifiedAt else {
return
}
// Update local storage with updated data
self.cache.createOrUpdate(element) {
guard case .success = $0 else {
self.log.error("Could not save updated post locally from remote storage: \(String(describing: $0.error))")
return
}
// Callback handler again if updated
completion($0)
}
}
}
}
func fetch(slug: String, completion: @escaping (Result<Post, SwiftyPressError>) -> Void) {
cache.fetch(slug: slug) { result in
// Retrieve missing cache data from cloud if applicable
if case .nonExistent? = result.error {
// Sync remote updates to cache if applicable
self.dataRepository.fetch {
// Validate if any updates that needs to be stored
guard case let .success(item) = $0, item.posts.contains(where: { $0.slug == slug }) else {
completion(result)
return
}
self.cache.fetch(slug: slug, completion: completion)
}
return
}
completion(result)
}
}
func fetch(url: String, completion: @escaping (Result<Post, SwiftyPressError>) -> Void) {
guard let slug = slug(from: url) else { return completion(.failure(.nonExistent)) }
fetch(slug: slug, completion: completion)
}
}
public extension PostRepository {
func fetch(with request: PostAPI.FetchRequest, completion: @escaping (Result<[Post], SwiftyPressError>) -> Void) {
cache.fetch(with: request) {
// Immediately return local response
completion($0)
guard case .success = $0 else { return }
// Sync remote updates to cache if applicable
self.dataRepository.fetch {
// Validate if any updates that needs to be stored
guard case let .success(item) = $0, !item.posts.isEmpty else { return }
self.cache.fetch(with: request, completion: completion)
}
}
}
func fetchPopular(with request: PostAPI.FetchRequest, completion: @escaping (Result<[Post], SwiftyPressError>) -> Void) {
cache.fetchPopular(with: request) {
// Immediately return local response
completion($0)
guard case .success = $0 else { return }
// Sync remote updates to cache if applicable
self.dataRepository.fetch {
// Validate if any updates that needs to be stored
guard case let .success(item) = $0, !item.posts.isEmpty else { return }
self.cache.fetchPopular(with: request, completion: completion)
}
}
}
func fetchTopPicks(with request: PostAPI.FetchRequest, completion: @escaping (Result<[Post], SwiftyPressError>) -> Void) {
fetch(byTermIDs: [constants.featuredCategoryID], with: request, completion: completion)
}
}
public extension PostRepository {
func fetch(ids: Set<Int>, completion: @escaping (Result<[Post], SwiftyPressError>) -> Void) {
cache.fetch(ids: ids) {
// Immediately return local response
completion($0)
guard case .success = $0 else { return }
// Sync remote updates to cache if applicable
self.dataRepository.fetch {
// Validate if any updates that needs to be stored
guard case let .success(item) = $0,
item.posts.contains(where: { ids.contains($0.id) }) else {
return
}
self.cache.fetch(ids: ids, completion: completion)
}
}
}
func fetch(byTermIDs ids: Set<Int>, with request: PostAPI.FetchRequest, completion: @escaping (Result<[Post], SwiftyPressError>) -> Void) {
cache.fetch(byTermIDs: ids, with: request) {
// Immediately return local response
completion($0)
guard case .success = $0 else { return }
// Sync remote updates to cache if applicable
self.dataRepository.fetch {
guard case let .success(item) = $0 else { return }
// Validate if any updates that needs to be stored
let modifiedIDs = Set(item.posts.flatMap { $0.terms })
guard ids.contains(where: modifiedIDs.contains) else { return }
self.cache.fetch(byTermIDs: ids, with: request, completion: completion)
}
}
}
}
public extension PostRepository {
func search(with request: PostAPI.SearchRequest, completion: @escaping (Result<[Post], SwiftyPressError>) -> Void) {
cache.search(with: request, completion: completion)
}
}
public extension PostRepository {
func getID(bySlug slug: String) -> Int? {
cache.getID(bySlug: slug)
}
func getID(byURL url: String) -> Int? {
guard let slug = slug(from: url) else { return nil }
return getID(bySlug: slug)
}
}
// MARK: - Helpers
private extension PostRepository {
func slug(from url: String) -> String? {
URL(string: url)?.relativePath.lowercased()
.replacing(regex: "\\d{4}/\\d{2}/\\d{2}/", with: "") // Handle legacy permalinks
.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
}
}
| 35.804444 | 143 | 0.543818 |
855bbc10cf781ed8d6491630c861a9a9cd4c6e16 | 15,144 | js | JavaScript | dbots/bots.ondiscord.xyz/_nuxt/b6e08d56b876a86f2321.js | zyoncommunity/xxxxx | d36066b8e752dce6adcff37305f1944f9c3f5dc9 | [
"MIT"
] | null | null | null | dbots/bots.ondiscord.xyz/_nuxt/b6e08d56b876a86f2321.js | zyoncommunity/xxxxx | d36066b8e752dce6adcff37305f1944f9c3f5dc9 | [
"MIT"
] | null | null | null | dbots/bots.ondiscord.xyz/_nuxt/b6e08d56b876a86f2321.js | zyoncommunity/xxxxx | d36066b8e752dce6adcff37305f1944f9c3f5dc9 | [
"MIT"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[18],{1319:function(t,e,s){"use strict";s.r(e);s(28),s(26);var a=s(1),r=s.n(a),i=(s(46),s(51),s(106),s(34),s(12)),n=s.n(i),o=(s(65),s(486),s(100),s(17),s(66),s(27)),c=s(171),l={props:{bot:{type:Object,required:!0},search:Object},data:function(){for(var t={details:{}},e=Object.keys(this.search),s=0;s<e.length;s++){var a=e[s];Array.isArray(this.search[a])?t.details[a]=Array.from(this.search[a]):t.details[a]=this.search[a]}return t},computed:n()({},Object(o.b)(["user","isAuthenticated"]),{totalWeeklyVotes:function(){return this.bot.votes?this.bot.votes.slice(0,-1).reduce(function(t,e){return t+e.votes},0):0},totalWeeklyInvites:function(){return this.bot.invites?this.bot.invites.slice(0,-1).reduce(function(t,e){return t+e.invites},0):0},markedDescription:function(){return this.details&&this.details.description?Object(c.b)(this.bot.description).replace(new RegExp(Object(c.c)(this.details.description),"gi"),"<mark>$&</mark>"):this.bot.description},matchedTags:function(){var t=this;return this.bot.tags.filter(function(e){return t.details.tags.includes(e.type)})},avatar:function(){return Object(c.a)(this.bot,64,this.$store.getters.avatarFormat)}}),methods:{inviteBot:function(){return this.$axios.post("/api/stats/".concat(this.bot.id,"/invited")).catch(function(t){return console.error(t)}),this.$ga.event("Bot","invite",this.bot.id),window.open(this.bot.inviteUrl)}}},u=(s(488),s(19)),h=Object(u.a)(l,function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("div",{staticClass:"bot-card extended"},[s("div",{staticClass:"bot-card--header"},[s("figure",{staticClass:"bot-card--avatar"},[s("img",{attrs:{src:t.avatar,alt:t.bot.username+" avatar"}})]),t._v(" "),s("div",[s("p",{staticClass:"bot-card--name"},[t._v(t._s(t.bot.username||t.bot.id))]),t._v(" "),s("p",{staticClass:"bot-card--owner"},[t._v("By "+t._s(t.bot.owner.username)+"#"+t._s(t.bot.owner.discriminator))])])]),t._v(" "),s("div",{staticClass:"bot-card--content"},[s("div",{staticClass:"bot-card--description"},[s("p",{domProps:{innerHTML:t._s(t.markedDescription)}})]),t._v(" "),s("div",{directives:[{name:"show",rawName:"v-show",value:t.details.tags.length>0,expression:"details.tags.length > 0"}],staticClass:"bot-card--tags"},[t.bot.tags&&t.bot.tags.length>0?s("div",{staticClass:"bot-card--tagsWrapper"},t._l(t.matchedTags,function(e){return s("b-tooltip",{key:e.type,attrs:{type:"is-dark",label:e.description||"No description",position:"is-top",multilined:"",size:e.description?"is-large":"is-small"}},[s("b-tag",{attrs:{type:"is-primary",size:"is-small"}},[t._v(t._s(e.type))])],1)})):t._e()])]),t._v(" "),s("div",{staticClass:"bot-card--footer"},[s("div",{staticClass:"bot-card--statistics"},[s("p",[s("i",{staticClass:"fa fa-arrow-alt-circle-up"}),t._v(t._s(t.totalWeeklyVotes.toLocaleString())+" Vote"+t._s(1===t.totalWeeklyVotes?"":"s"))]),t._v(" "),s("p",[s("i",{staticClass:"fa fa-user-plus"}),t._v(t._s(t.totalWeeklyInvites.toLocaleString())+" Invite"+t._s(1===t.totalWeeklyInvites?"":"s"))])]),t._v(" "),s("div",{staticClass:"bot-card--actions"},[s("nuxt-link",{staticClass:"button is-primary",attrs:{to:"/bots/"+t.bot.id}},[s("i",{staticClass:"fa fa-address-card"}),s("span",[t._v("Info")])]),t._v(" "),s("a",{staticClass:"button is-primary",on:{click:function(e){return e.preventDefault(),t.inviteBot(e)}}},[s("i",{staticClass:"fa fa-user-plus"})]),t._v(" "),t.isAuthenticated&&(t.user.id===t.bot.owner.id||t.bot.editors&&t.bot.editors.includes(t.user.id))?s("nuxt-link",{staticClass:"button is-warning",attrs:{to:"/bots/"+t.bot.id+"/edit"}},[s("i",{staticClass:"fa fa-cog"})]):t._e()],1)])])},[],!1,null,"7d54b157",null);h.options.__file="ExtendedBotCard.vue";var d,g=h.exports,p=s(382),v=s(15),f={head:{title:"Search Bots on Discord",meta:[{hid:"description",name:"description",content:"Search the best Discord bot list and find the perfect bot for your server."},{hid:"og:title",property:"og:title",content:"Search"},{hid:"og:description",property:"og:description",content:"Search the best Discord bot list and find the perfect bot for your server."}]},components:{ExtendedBotCard:g,Pagination:p.a},asyncData:function(t){var e=t.error,s=t.app,a=t.store,r=a.getters.searchState;if(r)return{searchOptions:JSON.parse(JSON.stringify(r.searchOptions)),page:r.page,showExtra:r.showExtra,allTags:v.b,filteredTags:v.b,bots:r.bots.slice(0),searching:!1,hasSearched:r.hasSearched,seq:0};var i={searchOptions:{name:"",description:"",tags:[],sort:"top"},page:1,showExtra:!0,allTags:v.b,filteredTags:v.b,bots:[],searching:!1,hasSearched:!1,seq:0};return s.$axios.post("/api/bots/search",{limit:30}).then(function(t){return i.hasSearched=!0,i.bots=t.data.results,i.showExtra=30===t.data.results.length,a.commit("searchState",i),i}).catch(function(t){return t&&t.response?(e({statusCode:t.response.status||500,message:t.response.data.message||"Unknown API error"}),i):e({statusCode:500,message:"Unknown error"})})},computed:{showNoResults:function(){return this.hasSearched&&!this.searching&&0===this.bots.length},totalPages:function(){return Math.ceil(this.bots.length/10)},thisPage:function(){var t=1===this.page?0:10*(this.page-1);return this.bots.slice(t,t+10)}},methods:{getFilteredTags:function(t){var e=this;return this.filteredTags=t?this.allTags.filter(function(s){return!e.searchOptions.tags.includes(s)&&s.toLowerCase().indexOf(t)>-1}):this.allTags.filter(function(t){return!e.searchOptions.tags.includes(t)}),this.filteredTags},changePage:function(t){if(!(t===this.page||t<1))return t<=this.totalPages&&(this.page=t,this.$store.commit("searchPage",t)),this.showExtra&&t>=this.totalPages?this.getResults(!0,t):void 0},getResults:(d=r()(regeneratorRuntime.mark(function t(){var e,s,a,r,i,n=arguments;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(e=n.length>0&&void 0!==n[0]&&n[0],s=n.length>1&&void 0!==n[1]?n[1]:1,!this.searching){t.next=4;break}return t.abrupt("return");case 4:return this.hasSearched=!0,this.searching=!0,t.prev=6,a=Object.assign({},this.searchOptions,{limit:30,skip:e?10*this.totalPages:0}),t.next=10,this.$axios.post("/api/bots/search",a,{timeout:2e4});case 10:r=t.sent,e?r.data.results.length>0?(this.bots=this.bots.concat(r.data.results),this.page=s,r.data.results.length<30&&(this.showExtra=!1)):(this.page=s-1,this.showExtra=!1):(this.bots=r.data.results,this.page=1,this.showExtra=30===r.data.results.length,this.seq++),this.$store.commit("searchState",this),this.searching=!1,t.next=22;break;case 16:return t.prev=16,t.t0=t.catch(6),this.searching=!1,i=null,t.t0&&t.t0.response?t.t0.response.data&&(i=t.t0.response.data.message):console.log(t.t0),t.abrupt("return",this.$dialog.alert({title:"Error",message:i||"Unknown error while attempting to get search results.",type:"is-danger",hasIcon:!0,icon:"times-circle",iconPack:"fa"}));case 22:case"end":return t.stop()}},t,this,[[6,16]])})),function(){return d.apply(this,arguments)})}},b=(s(489),Object(u.a)(f,function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("section",{staticClass:"section"},[s("div",{staticClass:"container search-panel"},[s("div",{staticClass:"columns"},[s("div",{staticClass:"column queries"},[s("b-field",{attrs:{label:"Bot name"}},[s("b-input",{attrs:{maxlength:35,"has-counter":!1,placeholder:"Input name",icon:"id-card"},model:{value:t.searchOptions.name,callback:function(e){t.$set(t.searchOptions,"name",e)},expression:"searchOptions.name"}})],1),t._v(" "),s("b-field",{attrs:{label:"Description"}},[s("b-input",{attrs:{maxlength:100,"has-counter":!1,placeholder:"Input text",icon:"file-alt"},model:{value:t.searchOptions.description,callback:function(e){t.$set(t.searchOptions,"description",e)},expression:"searchOptions.description"}})],1),t._v(" "),s("b-field",{attrs:{label:"Tags"}},[s("b-taginput",{attrs:{data:t.filteredTags,autocomplete:"","keep-first":"","open-on-focus":"",allowNew:!1,icon:"tags",placeholder:"Select tags"},on:{typing:t.getFilteredTags},model:{value:t.searchOptions.tags,callback:function(e){t.$set(t.searchOptions,"tags",e)},expression:"searchOptions.tags"}})],1)],1),t._v(" "),s("div",{staticClass:"column is-one-quarter-desktop is-one-third search"},[s("b-field",{attrs:{label:"Sort Method"}},[s("b-select",{attrs:{icon:"sort",placeholder:"Select a method",expanded:""},model:{value:t.searchOptions.sort,callback:function(e){t.$set(t.searchOptions,"sort",e)},expression:"searchOptions.sort"}},[s("option",{attrs:{value:"top"}},[t._v("Most votes")]),t._v(" "),s("option",{attrs:{value:"new"}},[t._v("Newest")])])],1),t._v(" "),s("button",{staticClass:"button is-success",on:{click:function(e){t.getResults()}}},[s("b-icon",{attrs:{icon:"search",size:"is-small"}}),t._v("Find Bots")],1)],1)])]),t._v(" "),s("div",{staticClass:"container search-results"},[s("article",{directives:[{name:"show",rawName:"v-show",value:t.showNoResults,expression:"showNoResults"}],staticClass:"message is-info"},[s("div",{staticClass:"message-body"},[t._v("\n\t\t\t\tThere are no bots matching your search. Try making a less-specific search to get results.\n\t\t\t")])]),t._v(" "),s("div",{directives:[{name:"show",rawName:"v-show",value:t.bots.length>0,expression:"bots.length > 0"}],staticClass:"pagination-wrapper"},[s("pagination",{attrs:{pages:t.totalPages,currentPage:t.page,showExtra:t.showExtra},on:{change:t.changePage}}),t._v(" "),s("div",{staticClass:"bot-list"},t._l(t.thisPage,function(e){return s("extended-bot-card",{key:e.id+"-"+t.seq,attrs:{bot:e,search:t.searchOptions}})})),t._v(" "),s("pagination",{attrs:{pages:t.totalPages,currentPage:t.page,showExtra:t.showExtra},on:{change:t.changePage}})],1)])])},[],!1,null,"7c5ce0fd",null));b.options.__file="search.vue";e.default=b.exports},171:function(t,e,s){"use strict";s.d(e,"a",function(){return a}),s.d(e,"b",function(){return i}),s.d(e,"c",function(){return n});s(26),s(1),s(34);function a(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:64,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"png";return"webp"===s&&(e*=2),t&&t.avatarHash?"https://cdn.discordapp.com/avatars/".concat(t.id,"/").concat(t.avatarHash,".").concat(s,"?size=").concat(e):"https://cdn.discordapp.com/embed/avatars/0.png"}var r={"<":"<",">":">","&":"&"};function i(t){return t.replace(/(<|>|&)/g,function(t){return r[t]})}function n(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}},303:function(t,e,s){},312:function(t,e,s){"use strict";var a=s(3),r=s(16),i=s(21),n=s(97),o=s(48),c=s(10),l=s(49).f,u=s(64).f,h=s(9).f,d=s(313).trim,g=a.Number,p=g,v=g.prototype,f="Number"==i(s(63)(v)),b="trim"in String.prototype,m=function(t){var e=o(t,!1);if("string"==typeof e&&e.length>2){var s,a,r,i=(e=b?e.trim():d(e,3)).charCodeAt(0);if(43===i||45===i){if(88===(s=e.charCodeAt(2))||120===s)return NaN}else if(48===i){switch(e.charCodeAt(1)){case 66:case 98:a=2,r=49;break;case 79:case 111:a=8,r=55;break;default:return+e}for(var n,c=e.slice(2),l=0,u=c.length;l<u;l++)if((n=c.charCodeAt(l))<48||n>r)return NaN;return parseInt(c,a)}}return+e};if(!g(" 0o1")||!g("0b1")||g("+0x1")){g=function(t){var e=arguments.length<1?0:t,s=this;return s instanceof g&&(f?c(function(){v.valueOf.call(s)}):"Number"!=i(s))?n(new p(m(e)),s,g):m(e)};for(var _,w=s(6)?l(p):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),x=0;w.length>x;x++)r(p,_=w[x])&&!r(g,_)&&h(g,_,u(p,_));g.prototype=v,v.constructor=g,s(11)(a,"Number",g)}},313:function(t,e,s){var a=s(5),r=s(20),i=s(10),n=s(314),o="["+n+"]",c=RegExp("^"+o+o+"*"),l=RegExp(o+o+"*$"),u=function(t,e,s){var r={},o=i(function(){return!!n[t]()||"
"!="
"[t]()}),c=r[t]=o?e(h):n[t];s&&(r[s]=c),a(a.P+a.F*o,"String",r)},h=u.trim=function(t,e){return t=String(r(t)),1&e&&(t=t.replace(c,"")),2&e&&(t=t.replace(l,"")),t};t.exports=u},314:function(t,e){t.exports="\t\n\v\f\r \u2028\u2029\ufeff"},342:function(t,e,s){},343:function(t,e,s){"use strict";var a=s(303);s.n(a).a},344:function(t,e,s){},382:function(t,e,s){"use strict";s(312);var a={props:{pages:{type:Number,required:!0},currentPage:{type:Number,required:!0},showExtra:{type:Boolean,default:!1}},methods:{goToPage:function(t){return this.$emit("change",t)}}},r=(s(343),s(19)),i=Object(r.a)(a,function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("div",{staticClass:"bots-pagination"},[s("button",{staticClass:"button",attrs:{disabled:t.currentPage<2},on:{click:function(e){t.goToPage(1)}}},[s("b-icon",{attrs:{icon:"angle-double-left",size:"is-small"}})],1),t._v(" "),s("button",{staticClass:"button",attrs:{disabled:t.currentPage<2},on:{click:function(e){t.goToPage(t.currentPage-1)}}},[s("b-icon",{attrs:{icon:"angle-left",size:"is-small"}})],1),t._v(" "),s("div",{staticClass:"bots-pagination--pages"},[s("button",{directives:[{name:"show",rawName:"v-show",value:t.currentPage>2,expression:"currentPage > 2"}],staticClass:"button",on:{click:function(e){t.goToPage(t.currentPage-2)}}},[t._v(t._s(t.currentPage-2))]),t._v(" "),s("button",{directives:[{name:"show",rawName:"v-show",value:t.currentPage>1,expression:"currentPage > 1"}],staticClass:"button",on:{click:function(e){t.goToPage(t.currentPage-1)}}},[t._v(t._s(t.currentPage-1))]),t._v(" "),s("button",{staticClass:"button is-primary"},[t._v(t._s(t.currentPage))]),t._v(" "),s("button",{directives:[{name:"show",rawName:"v-show",value:t.showExtra||t.currentPage<t.pages,expression:"showExtra || currentPage < pages"}],staticClass:"button",on:{click:function(e){t.goToPage(t.currentPage+1)}}},[t._v(t._s(t.currentPage+1))]),t._v(" "),s("button",{directives:[{name:"show",rawName:"v-show",value:t.currentPage+1<t.pages,expression:"currentPage + 1 < pages"}],staticClass:"button",on:{click:function(e){t.goToPage(t.currentPage+2)}}},[t._v(t._s(t.currentPage+2))])]),t._v(" "),s("button",{staticClass:"button",attrs:{disabled:!t.showExtra&&t.currentPage===t.pages},on:{click:function(e){t.goToPage(t.currentPage+1)}}},[s("b-icon",{attrs:{icon:"angle-right",size:"is-small"}})],1),t._v(" "),s("button",{staticClass:"button",attrs:{disabled:!t.showExtra&&t.currentPage===t.pages},on:{click:function(e){t.goToPage(t.showExtra?t.pages+1:t.pages)}}},[s("b-icon",{attrs:{icon:"angle-double-right",size:"is-small"}})],1)])},[],!1,null,"7317bead",null);i.options.__file="Pagination.vue";e.a=i.exports},486:function(t,e,s){"use strict";var a=s(22),r=s(5),i=s(37),n=s(101),o=s(102),c=s(36),l=s(487),u=s(103);r(r.S+r.F*!s(104)(function(t){Array.from(t)}),"Array",{from:function(t){var e,s,r,h,d=i(t),g="function"==typeof this?this:Array,p=arguments.length,v=p>1?arguments[1]:void 0,f=void 0!==v,b=0,m=u(d);if(f&&(v=a(v,p>2?arguments[2]:void 0,2)),null==m||g==Array&&o(m))for(s=new g(e=c(d.length));e>b;b++)l(s,b,f?v(d[b],b):d[b]);else for(h=m.call(d),s=new g;!(r=h.next()).done;b++)l(s,b,f?n(h,v,[r.value,b],!0):r.value);return s.length=b,s}})},487:function(t,e,s){"use strict";var a=s(9),r=s(35);t.exports=function(t,e,s){e in t?a.f(t,e,r(0,s)):t[e]=s}},488:function(t,e,s){"use strict";var a=s(342);s.n(a).a},489:function(t,e,s){"use strict";var a=s(344);s.n(a).a}}]); | 15,144 | 15,144 | 0.682184 |
8b193655fcb7a04d8a825b1e7c2effce651253f7 | 121 | sql | SQL | problems/database/combine_two_tables.sql | bvegaM/leetcode_problems | d7f87ec263618d2292309b65e20ef9234d1fedd6 | [
"MIT"
] | null | null | null | problems/database/combine_two_tables.sql | bvegaM/leetcode_problems | d7f87ec263618d2292309b65e20ef9234d1fedd6 | [
"MIT"
] | null | null | null | problems/database/combine_two_tables.sql | bvegaM/leetcode_problems | d7f87ec263618d2292309b65e20ef9234d1fedd6 | [
"MIT"
] | null | null | null | select p.FirstName,
p.LastName,
d.City,
d.State
from Person p
left join Address d on d.PersonId = p.PersonId | 20.166667 | 47 | 0.68595 |
c077b84eb46e5f341c24af2d75e83d67017bbe10 | 10,176 | html | HTML | events.html | jasonww11/mudikaWebsite | 228fa40348a1ff8a92a2b63060305848568e8140 | [
"MIT"
] | null | null | null | events.html | jasonww11/mudikaWebsite | 228fa40348a1ff8a92a2b63060305848568e8140 | [
"MIT"
] | null | null | null | events.html | jasonww11/mudikaWebsite | 228fa40348a1ff8a92a2b63060305848568e8140 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1">
<title>True Church</title>
<!-- Loading third party fonts -->
<link href="fonts/novecento-font/novecento-font.css" rel="stylesheet" type="text/css">
<link href="fonts/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- Loading main css file -->
<link rel="stylesheet" href="style.css">
<!--[if lt IE 9]>
<script src="js/ie-support/html5.js"></script>
<script src="js/ie-support/respond.js"></script>
<![endif]-->
</head>
<body>
<div class="site-content">
<header class="site-header">
<div class="container">
<a href="#" class="branding">
<img src="images/logo.png" alt="" class="logo">
<h1 class="site-title">True Church</h1>
</a>
<div class="main-navigation">
<button class="menu-toggle"><i class="fa fa-bars"></i> Menu</button>
<ul class="menu">
<li class="menu-item"><a href="index.html">Homepage <small>Lorem ipsum</small></a></li>
<li class="menu-item"><a href="#">Pastors <small>Cupidatat non proident</small></a></li>
<li class="menu-item"><a href="seremons.html">Seremons <small>Laboris nisi aliquip</small></a></li>
<li class="menu-item current-menu-item"><a href="events.html">Events <small>Sunt in culpa</small></a></li>
<li class="menu-item"><a href="families.html">Families <small>Aute irure</small></a></li>
<li class="menu-item"><a href="#">Contact <small>lorem ipsum</small></a></li>
</ul>
</div>
<div class="mobile-navigation"></div>
</div>
</header> <!-- .site-header -->
<div class="page-head" data-bg-image="images/page-head-1.jpg">
<div class="container">
<h2 class="page-title">Seremons</h2>
</div>
</div>
<main class="main-content">
<div class="fullwidth-block">
<div class="container">
<div class="row">
<div class="content col-md-8">
<h2 class="section-title">Upcoming Events</h2>
<ul class="event-list large">
<li>
<h3 class="event-title"><a href="#">africa mission trip</a></h3>
<span class="event-meta">
<span><i class="fa fa-calendar"></i>30 mar 2014</span>
<span><i class="fa fa-map-marker"></i> Africa</span>
</span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque recusandae rerum alias veniam nisi repellat, libero molestias praesentium dolore harum quisquam quam dolorum repudiandae et, earum doloremque repellendus fugiat ab.</p>
<a href="#" class="button">Join to this event</a>
<a href="#" class="button secondary">Ask a question</a>
</li>
<li>
<h3 class="event-title"><a href="#">Bible school</a></h3>
<span class="event-meta">
<span><i class="fa fa-calendar"></i>30 mar 2014</span>
<span><i class="fa fa-map-marker"></i> Saint paul church</span>
</span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sit, consectetur explicabo beatae blanditiis dignissimos hic esse, voluptatum eaque maxime magni id possimus repudiandae ut exercitationem et temporibus ex vitae? Consequuntur!</p>
<a href="#" class="button">Join to this event</a>
<a href="#" class="button secondary">Ask a question</a>
</li>
<li>
<h3 class="event-title"><a href="#">praying for kids</a></h3>
<span class="event-meta">
<span><i class="fa fa-calendar"></i>30 mar 2014</span>
<span><i class="fa fa-map-marker"></i> true church</span>
</span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sit dicta dolores vero ipsum mollitia, laborum maiores beatae molestias numquam, eaque rerum optio facere nobis et voluptate, similique harum totam! At.</p>
<a href="#" class="button">Join to this event</a>
<a href="#" class="button secondary">Ask a question</a>
</li>
<li>
<h3 class="event-title"><a href="#">love giving</a></h3>
<span class="event-meta">
<span><i class="fa fa-calendar"></i>30 mar 2014</span>
<span><i class="fa fa-map-marker"></i> St cathedral</span>
</span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sit earum, minus error ipsum optio praesentium exercitationem necessitatibus accusamus reiciendis veritatis iste, aliquam nulla neque magni debitis deleniti harum molestias. Suscipit.</p>
<a href="#" class="button">Join to this event</a>
<a href="#" class="button secondary">Ask a question</a>
</li>
<li>
<h3 class="event-title"><a href="#">god ont the vacation</a></h3>
<span class="event-meta">
<span><i class="fa fa-calendar"></i>30 mar 2014</span>
<span><i class="fa fa-map-marker"></i> greenie lake</span>
</span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae error officia, vero quo ducimus maiores, itaque consequatur vitae tempore nulla beatae quis. Asperiores perspiciatis facere harum ducimus doloribus. Neque, accusamus?</p>
<a href="#" class="button">Join to this event</a>
<a href="#" class="button secondary">Ask a question</a>
</li>
<li>
<h3 class="event-title"><a href="#">homeless helping</a></h3>
<span class="event-meta">
<span><i class="fa fa-calendar"></i>30 mar 2014</span>
<span><i class="fa fa-map-marker"></i> Detroit city</span>
</span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum, minus perspiciatis. Ad vero maxime iusto nemo, id optio iure officiis quisquam incidunt, ipsum suscipit! Unde facilis nisi totam. Reiciendis, accusamus.</p>
<a href="#" class="button">Join to this event</a>
<a href="#" class="button secondary">Ask a question</a>
</li>
</ul>
</div>
<div class="sidebar col-md-3 col-md-offset-1">
<div class="widget">
<h3 class="widget-title">Categories</h3>
<ul class="arrow">
<li><a href="#">Perspiciatis unde</a></li>
<li><a href="#">Omnis iste natus</a></li>
<li><a href="#">Voluptatem accusantium</a></li>
<li><a href="#">Doloremque eaque</a></li>
<li><a href="#">Totam rem aperiam</a></li>
</ul>
</div>
<div class="widget">
<h3 class="widget-title">Donations</h3>
<p>Distinctio unde consequuntur delectus, repudiandae, impedit atque earum adipisci, explicabo perferendis.</p>
<a href="#" class="button">Make a donation</a>
</div>
<div class="widget">
<h3 class="widget-title">Gallery updates</h3>
<div class="galery-thumb">
<a href="#"><img src="images/gallery-thumb-1.jpg" alt=""></a>
<a href="#"><img src="images/gallery-thumb-2.jpg" alt=""></a>
<a href="#"><img src="images/gallery-thumb-3.jpg" alt=""></a>
<a href="#"><img src="images/gallery-thumb-4.jpg" alt=""></a>
<a href="#"><img src="images/gallery-thumb-5.jpg" alt=""></a>
<a href="#"><img src="images/gallery-thumb-6.jpg" alt=""></a>
</div>
</div>
<div class="widget">
<h3 class="widget-title">Text widget </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum aliquam obcaecati velit, atque necessitatibus molestias ullam tempore itaque quidem sequi ea sed consectetur, eligendi cupiditate saepe! Hic veniam maiores explicabo.</p>
</div>
</div>
</div>
</div>
</div>
</main> <!-- .main-content -->
<footer class="site-footer">
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="widget">
<h3 class="widget-title">Our address</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Modi perspiciatis magnam, ab ipsa laboriosam tempore tenetur, aliquid repellat, ex cum dicta reiciendis accusamus. Omnis repudiandae quasi mollitia, iusto odio dignissimos.</p>
<ul class="address">
<li><i class="fa fa-map-marker"></i> 329 Church St, Garland, TX 75042</li>
<li><i class="fa fa-phone"></i> (425) 853 442 552</li>
<li><i class="fa fa-envelope"></i> info@yourchurch.com</li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class="widget">
<h3 class="widget-title">Topics from last meeting</h3>
<ul class="bullet">
<li><a href="#">Lorem ipsum dolor sit amet</a></li>
<li><a href="#">Consectetur adipisicing elit quis nostrud</a></li>
<li><a href="#">Eiusmod tempor incididunt ut labore et dolore magna</a></li>
<li><a href="#">Ut enim ad minim veniam cillum</a></li>
<li><a href="#">Exercitation ullamco laboris nisi ut aliquip</a></li>
<li><a href="#">Duis aute irure dolor in reprehenderit in voluptate</a></li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class="widget">
<h3 class="widget-title">Contact form</h3>
<form action="#" class="contact-form">
<div class="row">
<div class="col-md-6"><input type="text" placeholder="Your name..."></div>
<div class="col-md-6"><input type="text" placeholder="Email..."></div>
</div>
<textarea name="" placeholder="Your message..."></textarea>
<div class="text-right"><input type="submit" value="Send message"></div>
</form>
</div>
</div>
</div> <!-- .row -->
<p class="colophon">Copyright 2014 True Church. All right reserved</p>
</div><!-- .container -->
</footer> <!-- .site-footer -->
</div>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/app.js"></script>
</body>
</html> | 45.632287 | 258 | 0.588149 |
331c64b5688bf0f03e29dded9df8fd3ced9edae7 | 461 | py | Python | tests/programs/misc/causality_1.py | astraldawn/pylps | e9964a24bb38657b180d441223b4cdb9e1dadc8a | [
"MIT"
] | 1 | 2018-05-19T18:28:12.000Z | 2018-05-19T18:28:12.000Z | tests/programs/misc/causality_1.py | astraldawn/pylps | e9964a24bb38657b180d441223b4cdb9e1dadc8a | [
"MIT"
] | 12 | 2018-04-26T00:58:11.000Z | 2018-05-13T22:03:39.000Z | tests/programs/misc/causality_1.py | astraldawn/pylps | e9964a24bb38657b180d441223b4cdb9e1dadc8a | [
"MIT"
] | null | null | null | from pylps.core import *
initialise(max_time=2)
create_fluents('test(_, _)')
create_actions('hello(_, _)')
create_variables('Person', 'Years', 'NewYears', 'OldYears',)
initially(test('A', 0),)
reactive_rule(True).then(
hello('A', 5),
)
hello(Person, Years).initiates(test(Person, NewYears)).iff(
test(Person, OldYears), NewYears.is_(OldYears + Years)
)
hello(Person, Years).terminates(test(Person, OldYears))
execute(debug=False)
show_kb_log()
| 18.44 | 60 | 0.704989 |
6d2627551f223e70e3495ed8e16ca8a8fe2d5310 | 323 | sql | SQL | textrepo-app/db/V004__add-version-metadata-table.sql | BasLee/textrepo | c858e9eb190ddbd51949c620fa3af6233b0d7e05 | [
"Apache-2.0"
] | null | null | null | textrepo-app/db/V004__add-version-metadata-table.sql | BasLee/textrepo | c858e9eb190ddbd51949c620fa3af6233b0d7e05 | [
"Apache-2.0"
] | 30 | 2020-10-26T09:29:59.000Z | 2022-03-15T13:35:36.000Z | textrepo-app/db/V004__add-version-metadata-table.sql | BasLee/textrepo | c858e9eb190ddbd51949c620fa3af6233b0d7e05 | [
"Apache-2.0"
] | 1 | 2021-11-18T04:57:49.000Z | 2021-11-18T04:57:49.000Z | -- Version metadata: each entry is a key-value pair linked to a version.
create table versions_metadata (
version_id uuid not null,
key varchar not null,
value text,
primary key (version_id, key),
constraint versions_metadata_version_id_fkey foreign key (version_id) references versions (id) on delete cascade
);
| 35.888889 | 114 | 0.77709 |
0552c12f0cdc05d3e3b19a38932f70165d071063 | 3,857 | kt | Kotlin | project/src/main/kotlin/cga/exercise/components/Collision/Collision.kt | lucaremberg/CGA_Project | 58fed139c2e7c44ba7ede301223d70c370aca8bb | [
"MIT"
] | null | null | null | project/src/main/kotlin/cga/exercise/components/Collision/Collision.kt | lucaremberg/CGA_Project | 58fed139c2e7c44ba7ede301223d70c370aca8bb | [
"MIT"
] | null | null | null | project/src/main/kotlin/cga/exercise/components/Collision/Collision.kt | lucaremberg/CGA_Project | 58fed139c2e7c44ba7ede301223d70c370aca8bb | [
"MIT"
] | null | null | null | package cga.exercise.components.Collision
import cga.exercise.components.geometry.Renderable
import cga.exercise.components.geometry.RenderableList
import cga.exercise.components.geometry.Transformable
import cga.framework.OBJLoader
class Collision {
fun checkCollision(t1: Transformable, box: ArrayList<Renderable>, tallBox: ArrayList<Renderable>, laser: ArrayList<Renderable>, vertLaser: Renderable): Boolean{
return checkCollisionBikeBox(t1, box) || checkCollisionBikeTallBox(t1, tallBox) || checkCollisionBikeLaser(t1, laser) || checkCollisionBikeVerticalLaser(t1, vertLaser)
}
fun checkCollisionBikeBox(t1: Transformable, tList: ArrayList<Renderable>): Boolean {
tList.forEach {
if (t1.getWorldPosition().z + 3f >= it.getWorldPosition().z && it.getWorldPosition().z + 1f >= t1.getWorldPosition().z){
if (t1.getWorldPosition().x + 1f >= it.getWorldPosition().x && it.getWorldPosition().x + 4.5f >= t1.getWorldPosition().x){
if (t1.getWorldPosition().y + 1f >= it.getWorldPosition().y && it.getWorldPosition().y + 1.5f >= t1.getWorldPosition().y) {
return true
}
}
}
}
return false
}
fun checkCollisionBikeTallBox(t1: Transformable, tList: ArrayList<Renderable>): Boolean {
tList.forEach {
if (t1.getWorldPosition().z + 3f >= it.getWorldPosition().z && it.getWorldPosition().z + 1f >= t1.getWorldPosition().z){
if (t1.getWorldPosition().x + 1f >= it.getWorldPosition().x && it.getWorldPosition().x + 4.5f >= t1.getWorldPosition().x){
if (t1.getWorldPosition().y + 1f >= it.getWorldPosition().y && it.getWorldPosition().y + 3f >= t1.getWorldPosition().y) {
return true
}
}
}
}
return false
}
fun checkCollisionBikeLaser(t1: Transformable, tList: ArrayList<Renderable>): Boolean {
tList.forEach {
if (t1.getWorldPosition().z + 3f >= it.getWorldPosition().z && it.getWorldPosition().z + 0.3f >= t1.getWorldPosition().z) {
if (t1.getWorldPosition().x + 1f >= it.getWorldPosition().x && it.getWorldPosition().x + 15f >= t1.getWorldPosition().x) {
if (t1.getWorldPosition().y + 1f >= it.getWorldPosition().y && it.getWorldPosition().y + 2f >= t1.getWorldPosition().y) {
return true
}
}
}
}
return false
}
fun checkCollisionBikeVerticalLaser(t1: Transformable, tObj: Renderable): Boolean {
if (t1.getWorldPosition().z + 3f >= tObj.getWorldPosition().z && tObj.getWorldPosition().z + 0.3f >= t1.getWorldPosition().z){
if (t1.getWorldPosition().x + 1f >= tObj.getWorldPosition().x && tObj.getWorldPosition().x + 2f >= t1.getWorldPosition().x){
if (t1.getWorldPosition().y + 1f >= tObj.getWorldPosition().y && tObj.getWorldPosition().y + 15f >= t1.getWorldPosition().y) {
return true
}
}
}
return false
}
fun checkCollisionBikePowerUp(t1: Transformable, tObj: Renderable): Boolean {
if (t1.getWorldPosition().z + 3f >= tObj.getWorldPosition().z && tObj.getWorldPosition().z + 1f >= t1.getWorldPosition().z){
if (t1.getWorldPosition().x + 1f >= tObj.getWorldPosition().x && tObj.getWorldPosition().x + 2f >= t1.getWorldPosition().x){
if (t1.getWorldPosition().y + 1f >= tObj.getWorldPosition().y && tObj.getWorldPosition().y + 1.5f >= t1.getWorldPosition().y) {
return true
}
}
}
return false
}
} | 52.121622 | 176 | 0.581022 |
ddb325ecf737baa9d7cabb4399f12f2e31dde31e | 3,169 | php | PHP | index.php | alexuriarte/test | 9b8aab7be1a6e3fb0f33c54bff9e3dffd20c686f | [
"Apache-2.0"
] | null | null | null | index.php | alexuriarte/test | 9b8aab7be1a6e3fb0f33c54bff9e3dffd20c686f | [
"Apache-2.0"
] | null | null | null | index.php | alexuriarte/test | 9b8aab7be1a6e3fb0f33c54bff9e3dffd20c686f | [
"Apache-2.0"
] | null | null | null | <?php
include_once("constants.php");
include_once("functions.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Autoscaling Demo App JPL</title>
<link type="text/css" href="/static/css/bootstrap.css" rel="stylesheet">
<link type="text/css" href="/static/css/bootstrap-responsive.css" rel="stylesheet">
<link type="image/x-icon" href="/static/img/favicon.ico" rel="shortcut icon" />
<style type="text/css">code{color:#15d;} code.error{color:#d14}.hero-unit img{margin-right:10px;margin-top:10px}</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="hero-unit">
<img src="/static/img/scalr-logo.png" alt="Scalr Logo" class="pull-left"/>
<h1>Autoscaling Demo App</h1>
<p>This is the autoscaling demo app.</p>
<p>This application lets you monitor, as well as simulate CPU load.</p>
</div>
<div class="container">
<?php
$n_cpus = get_n_cpus();
$stress_cli = sprintf("stress --cpu %s --io %s", $n_cpus * LOAD_FACTOR, $n_cpus * LOAD_FACTOR);
if (METHOD === "GET") {
?>
<h2>CPU Status</h2>
<div>
<p>Number of CPUS: <code><?php echo $n_cpus; ?></code></p>
</div>
<div>
<p>Load generation command: <code><?php echo $stress_cli; ?></code></p>
</div>
<div>
<p>Uptime: <code><?php echo exec('uptime'); ?></code></p>
<small class="muted">This value will be used by Scalr for autoscaling.</small>
</div>
<h2>Load Simulation</h2>
<?php
if (is_running(PID_FILE)) {
$status = "Currently simulating load";
$cta = "Stop simulating load";
$button = "Stop";
$cls = "btn-danger";
$action = ACTION_STOP;
} else {
$status = "Currently not simulating load";
$cta = "Start simulating load";
$button = "Start";
$cls = "btn-success";
$action = ACTION_START;
}
?>
<p><?php echo $status; ?></p>
<h2><?php echo $cta; ?></h2>
<form action="/" method="post" class="form-inline">
<fieldset>
<div class="input-append">
<input type="hidden" name="action" value="<?php echo $action; ?>" />
<input type="submit" class="btn <?php echo $cls; ?>" value="<?php echo $button; ?>"/>
</div>
</fieldset>
</form>
<hr/>
<h2>Configuring autoscaling</h2>
<p>To make sure that Scalr autoscales your app, define an autoscaling policy using Load Averages.</p>
<?php
} elseif (METHOD === "POST") {
$action = $_POST["action"];
if ($action === ACTION_START) {
if (!is_running(PID_FILE)) {
start_process($stress_cli, OUTPUT_FILE, PID_FILE);
}
header("Location: /");
} elseif ($action === ACTION_STOP) {
if (is_running(PID_FILE)) {
kill_process(PID_FILE);
}
header("Location: /");
} else {
?>
<div class="alert alert-error">
This action is invalid: "<?php echo $action; ?>"
</div>
<div class="text-center">
<a href="/" class="btn btn-large btn-primary" type="button">Please try again!</a>
</div>
<?php
}
} else {
echo "Unsupported method! (Try GET!)";
}
?>
</div>
</body>
</html>
| 30.180952 | 124 | 0.583149 |
c6972983298133da839f29feb19b165375a34180 | 5,331 | rb | Ruby | lib/octopress-ink/plugin_asset_pipeline.rb | chauncey-garrett/ink | 56b01d36b663f4ae8f49b6c8082880738a2b776c | [
"MIT"
] | null | null | null | lib/octopress-ink/plugin_asset_pipeline.rb | chauncey-garrett/ink | 56b01d36b663f4ae8f49b6c8082880738a2b776c | [
"MIT"
] | null | null | null | lib/octopress-ink/plugin_asset_pipeline.rb | chauncey-garrett/ink | 56b01d36b663f4ae8f49b6c8082880738a2b776c | [
"MIT"
] | null | null | null | module Octopress
module Ink
module PluginAssetPipeline
# Compile CSS to take advantage of Sass's compression settings
#
def self.compile_css(content)
configs = sass_converter.sass_configs
configs[:syntax] = :scss
configs[:style] ||= :compressed if Ink.configuration['compress_css']
Sass.compile(content, configs)
end
def self.compile_sass(sass)
Sass.compile(sass.render, sass_configs(sass))
end
# Gets default Sass configuration hash from Jekyll
#
def self.sass_configs(sass)
configs = sass_converter.sass_configs
configs[:syntax] = sass.ext.sub(/^\./,'').to_sym
if sass.respond_to? :load_paths
configs[:load_paths] = sass.load_paths
end
configs
end
# Access Jekyll's built in Sass converter
#
def self.sass_converter
if @sass_converter
@sass_converter
else
Octopress.site.converters.each do |c|
@sass_converter = c if c.kind_of?(Jekyll::Converters::Sass)
end
@sass_converter
end
end
# Return a link tag, for all plugins' stylesheets
#
def self.combined_stylesheet_tag
tags = ''
combine_stylesheets.keys.each do |media|
tags.concat "<link href='#{Filters.expand_url(combined_stylesheet_path(media))}' media='#{media}' rel='stylesheet' type='text/css'>"
end
tags
end
def self.combined_javascript_tag
unless combine_javascripts == ''
"<script src='#{Filters.expand_url(combined_javascript_path)}'></script>"
end
end
# Combine stylesheets from each plugin
#
# Returns a hash of stylesheets grouped by media types
#
# output: { 'screen' => 'body { background... }' }
#
def self.combine_stylesheets
if @combined_stylesheets
@combined_stylesheets
else
combined = {}
stylesheets.clone.each do |media,files|
files.each do |file|
header = "/* #{file.plugin.type.capitalize}: #{file.plugin.name} */"
combined[media] ||= ''
combined[media] << "#{header}\n" unless combined[media] =~ /#{file.plugin.name}/
combined[media] << (file.ext.match(/\.s[ca]ss/) ? file.compile : file.content)
end
end
@combined_stylesheets = combined
end
end
def self.write_combined_stylesheet
@combined_stylesheets = nil
css = combine_stylesheets
css.keys.each do |media|
contents = compile_css(css[media])
write_files(contents, combined_stylesheet_path(media))
end
end
def self.combined_stylesheet_path(media)
File.join('stylesheets', "#{media}-#{stylesheet_fingerprint(media)}.css")
end
def self.stylesheet_fingerprint(media)
@stylesheet_fingerprint ||= {}
@stylesheet_fingerprint[media] ||=
fingerprint(stylesheets[media].clone.map {|f| f.path })
end
# Get all plugins stylesheets
#
# Returns a hash of assets grouped by media
#
# output: { 'screen' => [Octopress::Ink::Assets::Stylesheet, ..]
#
def self.stylesheets
if @stylesheets
@stylesheets
else
files = {}
Plugins.plugins.clone.each do |plugin|
plugin.stylesheets.each do |file|
files[file.media] ||= []
files[file.media] << file
end
end
@stylesheets = files
end
end
def self.javascripts
@javascripts ||=
Plugins.plugins.clone.map { |p| p.javascripts }.flatten
end
def self.javascript_fingerprint
@javascript_fingerprint ||=
fingerprint(javascripts.clone.map {|f| f.path })
end
def self.combine_javascripts
if @combined_javascripts
@combined_javascripts
else
js = ""
javascripts.clone.each do |file|
unless js =~ /#{file.plugin.name}/
js += "/* #{file.plugin.type.capitalize}: #{file.plugin.name} */\n"
end
js += (file.ext.match(/.coffee/) ? file.compile : file.content)
end
@combined_javascripts = js
end
end
def self.combined_javascript_path
File.join('javascripts', "all-#{javascript_fingerprint}.js")
end
def self.write_combined_javascript
@combined_javascripts = nil
js = combine_javascripts
unless js == ''
if Ink.configuration['compress_js']
settings = Jekyll::Utils.symbolize_hash_keys(Ink.configuration['uglifier'])
js = Uglifier.new(settings).compile(js)
end
write_files(js, combined_javascript_path)
end
end
def self.write_files(source, dest)
Plugins.static_files << StaticFileContent.new(source, dest)
end
def self.fingerprint(paths)
return '' if ENV['JEKYLL_ENV'] == 'test'
paths = [paths] unless paths.is_a? Array
Digest::MD5.hexdigest(paths.clone.map! { |path| "#{File.mtime(path).to_i}" }.join)
end
end
end
end
| 29.291209 | 142 | 0.578878 |
df68f200ddaa5505adca70013640757a86b35b03 | 348 | rb | Ruby | farandula-ruby/lib/farandula/models/price.rb | perlaruizaviles/farandula | e18c4b512d588e47a5b9eeaf54e00d62c1e2218d | [
"Apache-2.0"
] | null | null | null | farandula-ruby/lib/farandula/models/price.rb | perlaruizaviles/farandula | e18c4b512d588e47a5b9eeaf54e00d62c1e2218d | [
"Apache-2.0"
] | null | null | null | farandula-ruby/lib/farandula/models/price.rb | perlaruizaviles/farandula | e18c4b512d588e47a5b9eeaf54e00d62c1e2218d | [
"Apache-2.0"
] | null | null | null | module Farandula
class Price
attr_accessor :amount
attr_accessor :currency_code
def initialize(
amount = nil,
currency_code = nil
)
@amount = amount
@currency_code = currency_code
end
def to_s
"amount #{amount}, currency code #{currency_code}."
end
end
end
| 15.130435 | 57 | 0.58046 |
56cd8c4938a98ace7021bf336e9c5dbf419e0046 | 103 | sql | SQL | src/test/resources/sql/select/4f8ea574.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/select/4f8ea574.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/select/4f8ea574.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:json.sql ln:481 expect:true
SELECT js FROM json_populate_record(NULL::jsrec, '{"js": null}') q
| 34.333333 | 66 | 0.718447 |
15b800493158ed475cd91bf7d79a420ba57fe39e | 96 | rb | Ruby | webTest/features/word_count.rb | MarkCTest/cucumber | dc91d0a562b5c9ab48ad5ea21c01bffe51db33ea | [
"MIT"
] | null | null | null | webTest/features/word_count.rb | MarkCTest/cucumber | dc91d0a562b5c9ab48ad5ea21c01bffe51db33ea | [
"MIT"
] | null | null | null | webTest/features/word_count.rb | MarkCTest/cucumber | dc91d0a562b5c9ab48ad5ea21c01bffe51db33ea | [
"MIT"
] | null | null | null | class WordCount
def initialize(text)
@text = text
end
def result
3
end
end | 9.6 | 22 | 0.604167 |
8ab026cdd9878697ffcb37fb383caa5d9bb951d7 | 7,947 | rs | Rust | src/guiding.rs | mconsidine/vidoxide | dd7d8e637a2c1176dbd5b4fbcab385808314f1cc | [
"MIT"
] | null | null | null | src/guiding.rs | mconsidine/vidoxide | dd7d8e637a2c1176dbd5b4fbcab385808314f1cc | [
"MIT"
] | null | null | null | src/guiding.rs | mconsidine/vidoxide | dd7d8e637a2c1176dbd5b4fbcab385808314f1cc | [
"MIT"
] | null | null | null | //
// Vidoxide - Image acquisition for amateur astronomy
// Copyright (c) 2020-2021 Filip Szczerek <ga.software@yahoo.com>
//
// This project is licensed under the terms of the MIT license
// (see the LICENSE file for details).
//
//!
//! Guiding.
//!
use crate::ProgramData;
use crate::gui::show_message;
use crate::mount;
use glib::clone;
use std::cell::RefCell;
use std::rc::Rc;
//TODO: set it from GUI
const GUIDE_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_millis(2000);
pub fn start_guiding(program_data_rc: &Rc<RefCell<ProgramData>>) {
let failed: bool = if program_data_rc.borrow().tracking.is_none() {
show_message("Target tracking is not enabled.", "Error", gtk::MessageType::Error);
true
} else if program_data_rc.borrow().mount_data.calibration.is_none() {
show_message("Calibration has not been performed.", "Error", gtk::MessageType::Error);
true
} else { false };
if failed {
program_data_rc.borrow().gui.as_ref().unwrap().mount_widgets().disable_guide();
return;
}
let mut pd = program_data_rc.borrow_mut();
pd.mount_data.guiding_pos = Some(pd.tracking.as_ref().unwrap().pos);
pd.mount_data.guiding_timer.run_once(
GUIDE_CHECK_INTERVAL,
clone!(@weak program_data_rc => @default-panic, move || guiding_step(&program_data_rc))
);
}
pub fn stop_guiding(program_data_rc: &Rc<RefCell<ProgramData>>) {
let mut pd = program_data_rc.borrow_mut();
let sd_on = pd.mount_data.sidereal_tracking_on;
pd.mount_data.mount.as_mut().unwrap().set_motion(
mount::Axis::Primary,
if sd_on { 1.0 * mount::SIDEREAL_RATE } else { 0.0 }
).unwrap();
pd.mount_data.mount.as_mut().unwrap().stop_motion(mount::Axis::Secondary).unwrap();
pd.mount_data.guiding_timer.stop();
pd.mount_data.guide_slewing = false;
pd.mount_data.guiding_pos = None;
}
pub fn guiding_step(program_data_rc: &Rc<RefCell<ProgramData>>) {
/// Max acceptable X and Y difference between current and desired tracking position at the end of a guiding slew.
const GUIDE_POS_MARGIN: i32 = 5;
const GUIDE_DIR_UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1000);
let mut pd = program_data_rc.borrow_mut();
let dpos = *pd.mount_data.guiding_pos.as_ref().unwrap() - pd.tracking.as_ref().unwrap().pos;
if dpos.x.abs() > GUIDE_POS_MARGIN || dpos.y.abs() > GUIDE_POS_MARGIN {
let guide_dir_axis_space =
guiding_direction(pd.mount_data.calibration.as_ref().unwrap().img_to_mount_axes.as_ref().unwrap(), dpos);
let speed = pd.gui.as_ref().unwrap().mount_widgets().guide_speed() * mount::SIDEREAL_RATE;
let sd_on = pd.mount_data.sidereal_tracking_on;
pd.mount_data.mount.as_mut().unwrap().set_motion(
mount::Axis::Primary,
speed * guide_dir_axis_space.0 + if sd_on { 1.0 * mount::SIDEREAL_RATE } else { 0.0 }
).unwrap();
pd.mount_data.mount.as_mut().unwrap().set_motion(mount::Axis::Secondary, speed * guide_dir_axis_space.1).unwrap();
pd.mount_data.guide_slewing = true;
pd.mount_data.guiding_timer.run_once(
GUIDE_DIR_UPDATE_INTERVAL,
clone!(@weak program_data_rc => @default-panic, move || guiding_step(&program_data_rc))
);
} else {
let st_on = pd.mount_data.sidereal_tracking_on;
pd.mount_data.mount.as_mut().unwrap().set_motion(
mount::Axis::Primary,
if st_on { mount::SIDEREAL_RATE } else { 0.0 }
).unwrap();
pd.mount_data.mount.as_mut().unwrap().stop_motion(mount::Axis::Secondary).unwrap();
pd.mount_data.guide_slewing = false;
pd.mount_data.guiding_timer.run_once(
GUIDE_CHECK_INTERVAL,
clone!(@weak program_data_rc => @default-panic, move || guiding_step(&program_data_rc))
);
}
}
/// Returns guiding direction (unit vector in RA&Dec space) in order to move along `target_offset` in image space.
fn guiding_direction(img_to_mount_axes_matrix: &[[f64; 2]; 2], target_offset: ga_image::point::Point) -> (f64, f64) {
#[allow(non_snake_case)]
let M = img_to_mount_axes_matrix;
let mut guide_dir_axis_space: (f64, f64) = (
M[0][0] * target_offset.x as f64 + M[0][1] * target_offset.y as f64,
M[1][0] * target_offset.x as f64 + M[1][1] * target_offset.y as f64
);
let len = (guide_dir_axis_space.0.powi(2) + guide_dir_axis_space.1.powi(2)).sqrt();
guide_dir_axis_space.0 /= len;
guide_dir_axis_space.1 /= len;
guide_dir_axis_space
}
/// Creates a matrix transforming image-space vectors to mount-axes-space.
///
/// # Parameters
///
/// * `primary_dir` - Direction in image space corresponding to positive slew around primary axis.
/// * `secondary_dir` - Direction in image space corresponding to positive slew around secondary axis.
///
pub fn create_img_to_mount_axes_matrix(primary_dir: (f64, f64), secondary_dir: (f64, f64)) -> [[f64; 2]; 2] {
// telescope-axes-space-to-image-space transformation matrix
let axes_to_img: [[f64; 2]; 2] = [[primary_dir.0, secondary_dir.0], [primary_dir.1, secondary_dir.1]];
let determinant = axes_to_img[0][0] * axes_to_img[1][1] - axes_to_img[0][1] * axes_to_img[1][0];
// axes_to_img⁻¹
[
[ axes_to_img[1][1] / determinant, -axes_to_img[0][1] / determinant],
[-axes_to_img[1][0] / determinant, axes_to_img[0][0] / determinant]
]
}
mod tests {
use super::*;
macro_rules! assert_almost_eq {
($expected:expr, $actual:expr) => {
if ($expected.0 - $actual.0).abs() > 1.0e-9 {
panic!("expected: {}, but was: {}", $expected.0, $actual.0);
}
if ($expected.1 - $actual.1).abs() > 1.0e-9 {
panic!("expected: {}, but was: {}", $expected.1, $actual.1);
}
};
}
#[test]
fn test_guiding_direction() {
let point = |x, y| { ga_image::point::Point{ x, y } };
let mat = |primary_dir, secondary_dir| { create_img_to_mount_axes_matrix(primary_dir, secondary_dir) };
let s2 = 1.0 / 2.0f64.sqrt();
// All test cases ask for primary & secondary axis direction corresponding to image space vector [1, 0].
assert_almost_eq!((1.0, 0.0), guiding_direction(&mat((1.0, 0.0), (0.0, 1.0)), point(1, 0)));
assert_almost_eq!((1.0, 0.0), guiding_direction(&mat((1.0, 0.0), (0.0, -1.0)), point(1, 0)));
assert_almost_eq!((s2, -s2), guiding_direction(&mat((1.0, 1.0), (-1.0, 1.0)), point(1, 0)));
assert_almost_eq!((s2, s2), guiding_direction(&mat((1.0, 1.0), (1.0, -1.0)), point(1, 0)));
assert_almost_eq!((0.0, 1.0), guiding_direction(&mat((0.0, 1.0), (1.0, 0.0)), point(1, 0)));
assert_almost_eq!((0.0, -1.0), guiding_direction(&mat((0.0, 1.0), (-1.0, 0.0)), point(1, 0)));
assert_almost_eq!((-s2, s2), guiding_direction(&mat((-1.0, 1.0), (1.0, 1.0)), point(1, 0)));
assert_almost_eq!((-s2, -s2), guiding_direction(&mat((-1.0, 1.0), (-1.0, -1.0)), point(1, 0)));
assert_almost_eq!((-1.0, 0.0), guiding_direction(&mat((-1.0, 0.0), (0.0, 1.0)), point(1, 0)));
assert_almost_eq!((-1.0, 0.0), guiding_direction(&mat((-1.0, 0.0), (0.0, -1.0)), point(1, 0)));
assert_almost_eq!((-s2, -s2), guiding_direction(&mat((-1.0, -1.0), (-1.0, 1.0)), point(1, 0)));
assert_almost_eq!((-s2, s2), guiding_direction(&mat((-1.0, -1.0), (1.0, -1.0)), point(1, 0)));
assert_almost_eq!((0.0, 1.0), guiding_direction(&mat((0.0, -1.0), (1.0, 0.0)), point(1, 0)));
assert_almost_eq!((0.0, -1.0), guiding_direction(&mat((0.0, -1.0), (-1.0, 0.0)), point(1, 0)));
assert_almost_eq!((s2, s2), guiding_direction(&mat((1.0, -1.0), (1.0, 1.0)), point(1, 0)));
assert_almost_eq!((s2, -s2), guiding_direction(&mat((1.0, -1.0), (-1.0, -1.0)), point(1, 0)));
}
}
| 42.956757 | 122 | 0.629168 |
743cb69b68a316c29fff2cc27d3fea0b538cb92e | 1,369 | h | C | usr/libexec/nsurlsessiond/PDURLSessionProxyCredential.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | usr/libexec/nsurlsessiond/PDURLSessionProxyCredential.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | usr/libexec/nsurlsessiond/PDURLSessionProxyCredential.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | //
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <ProtocolBuffer/PBCodable.h>
#import "NSCopying-Protocol.h"
@class NSData;
@interface PDURLSessionProxyCredential : PBCodable <NSCopying>
{
NSData *_archiveList; // 8 = 0x8
unsigned int _version; // 16 = 0x10
CDStruct_f20694ce _has; // 20 = 0x14
}
- (void).cxx_destruct; // IMP=0x000000010003fb48
@property(retain, nonatomic) NSData *archiveList; // @synthesize archiveList=_archiveList;
@property(nonatomic) unsigned int version; // @synthesize version=_version;
- (void)mergeFrom:(id)arg1; // IMP=0x000000010003fa9c
- (unsigned long long)hash; // IMP=0x000000010003fa38
- (_Bool)isEqual:(id)arg1; // IMP=0x000000010003f960
- (id)copyWithZone:(struct _NSZone *)arg1; // IMP=0x000000010003f8b8
- (void)copyTo:(id)arg1; // IMP=0x000000010003f840
- (void)writeTo:(id)arg1; // IMP=0x000000010003f7d0
- (_Bool)readFrom:(id)arg1; // IMP=0x000000010003f7c8
- (id)dictionaryRepresentation; // IMP=0x000000010003f6fc
- (id)description; // IMP=0x000000010003f648
@property(readonly, nonatomic) _Bool hasArchiveList;
@property(nonatomic) _Bool hasVersion;
- (id)_actualCredential; // IMP=0x000000010003659c
- (id)_initWithActualCredential:(id)arg1; // IMP=0x00000001000364cc
@end
| 35.102564 | 120 | 0.745069 |
c629a3799004d209b39f03561a233ae235c31dc7 | 216 | rb | Ruby | lib/github/ldap/membership_validators.rb | cjs/github-ldap | 34c2685bd07ae79c6283f14f1263d1276a162f28 | [
"MIT"
] | 98 | 2015-01-10T01:32:22.000Z | 2021-08-10T18:48:03.000Z | lib/github/ldap/membership_validators.rb | cjs/github-ldap | 34c2685bd07ae79c6283f14f1263d1276a162f28 | [
"MIT"
] | 25 | 2015-01-15T00:51:35.000Z | 2021-06-02T14:29:46.000Z | lib/github/ldap/membership_validators.rb | cjs/github-ldap | 34c2685bd07ae79c6283f14f1263d1276a162f28 | [
"MIT"
] | 33 | 2015-03-09T07:43:27.000Z | 2021-11-30T04:37:02.000Z | require 'github/ldap/membership_validators/base'
require 'github/ldap/membership_validators/classic'
require 'github/ldap/membership_validators/recursive'
require 'github/ldap/membership_validators/active_directory'
| 43.2 | 60 | 0.87037 |
268dbeccd716cf6a81c0c7b9a6cd4de3a111d230 | 332 | java | Java | src/main/java/com/tqi/analisecredito/domain/repository/EmprestimoRepository.java | Nilcelso/tqi_evolution_backend_2021 | d5dad6a06c77ad149c5a7c77d483d433bd6fa260 | [
"MIT"
] | null | null | null | src/main/java/com/tqi/analisecredito/domain/repository/EmprestimoRepository.java | Nilcelso/tqi_evolution_backend_2021 | d5dad6a06c77ad149c5a7c77d483d433bd6fa260 | [
"MIT"
] | null | null | null | src/main/java/com/tqi/analisecredito/domain/repository/EmprestimoRepository.java | Nilcelso/tqi_evolution_backend_2021 | d5dad6a06c77ad149c5a7c77d483d433bd6fa260 | [
"MIT"
] | null | null | null | package com.tqi.analisecredito.domain.repository;
import com.tqi.analisecredito.domain.model.Emprestimo;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface EmprestimoRepository extends JpaRepository<Emprestimo, Long> {
List<Emprestimo> findAllByClienteId(Long clienteId);
}
| 30.181818 | 79 | 0.831325 |
0c914d8fbc8a5b30dab1155628e15079383dc757 | 1,342 | py | Python | apps/images/migrations/0001_initial.py | coogger/coogger | 9e5e3ca172d8a14272948284a6822000b119119c | [
"MIT"
] | 48 | 2018-04-13T13:00:10.000Z | 2020-03-17T23:35:23.000Z | apps/images/migrations/0001_initial.py | coogger/coogger | 9e5e3ca172d8a14272948284a6822000b119119c | [
"MIT"
] | 77 | 2018-03-25T13:17:12.000Z | 2020-08-11T08:24:49.000Z | apps/images/migrations/0001_initial.py | coogger/coogger | 9e5e3ca172d8a14272948284a6822000b119119c | [
"MIT"
] | 35 | 2018-03-30T21:43:21.000Z | 2020-08-11T05:51:46.000Z | # Generated by Django 3.0.3 on 2020-02-28 13:21
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Image",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"title",
models.CharField(
blank=True,
help_text="Title | Optional",
max_length=55,
null=True,
verbose_name="",
),
),
(
"image",
models.ImageField(upload_to="images/", verbose_name=""),
),
(
"created",
models.DateTimeField(
default=django.utils.timezone.now,
verbose_name="Created",
),
),
],
),
]
| 26.84 | 76 | 0.354694 |
8a45f86cb8836f7fc9633b882648fa3531465788 | 1,689 | rs | Rust | rust/reqwest-pipeline/src/request.rs | roeap/flight-fusion | 14f73c99c5214277d0abcced633d83b37f1d5292 | [
"Apache-2.0",
"MIT"
] | 5 | 2021-12-24T06:21:40.000Z | 2022-01-16T12:21:06.000Z | rust/reqwest-pipeline/src/request.rs | roeap/flight-fusion | 14f73c99c5214277d0abcced633d83b37f1d5292 | [
"Apache-2.0",
"MIT"
] | 66 | 2021-12-15T17:08:21.000Z | 2022-03-29T10:36:18.000Z | rust/reqwest-pipeline/src/request.rs | roeap/flight-fusion | 14f73c99c5214277d0abcced633d83b37f1d5292 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-02-08T21:07:08.000Z | 2022-02-08T21:07:08.000Z | use crate::SeekableStream;
use http::{HeaderMap, Method, Uri};
use std::fmt::Debug;
/// An HTTP Body.
#[derive(Debug, Clone)]
pub enum Body {
/// A body of a known size.
Bytes(bytes::Bytes),
/// A streaming body.
SeekableStream(Box<dyn SeekableStream>),
}
impl From<bytes::Bytes> for Body {
fn from(bytes: bytes::Bytes) -> Self {
Self::Bytes(bytes)
}
}
impl From<Box<dyn SeekableStream>> for Body {
fn from(seekable_stream: Box<dyn SeekableStream>) -> Self {
Self::SeekableStream(seekable_stream)
}
}
/// A pipeline request.
///
/// A pipeline request is composed by a destination (uri), a method, a collection of headers and a
/// body. Policies are expected to enrich the request by mutating it.
#[derive(Debug, Clone)]
pub struct Request {
pub(crate) uri: Uri,
pub(crate) method: Method,
pub(crate) headers: HeaderMap,
pub(crate) body: Body,
}
impl Request {
pub fn uri(&self) -> &Uri {
&self.uri
}
pub fn method(&self) -> Method {
self.method.clone()
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.headers
}
pub fn body(&self) -> &Body {
&self.body
}
pub fn set_body(&mut self, body: Body) {
self.body = body;
}
}
impl From<http::Request<bytes::Bytes>> for Request {
fn from(request: http::Request<bytes::Bytes>) -> Self {
let (parts, body) = request.into_parts();
Self {
uri: parts.uri,
method: parts.method,
headers: parts.headers,
body: Body::Bytes(body),
}
}
}
| 22.52 | 98 | 0.59029 |
8604d0a086bc9afa97db8d51f167cf1b6adfe016 | 4,518 | go | Go | ikuzo/resource/formats/jsonld/parser.go | jaclu/hub3 | 1a60c948133e82d9342480d5c776b5d5cac5cbf7 | [
"Apache-2.0"
] | null | null | null | ikuzo/resource/formats/jsonld/parser.go | jaclu/hub3 | 1a60c948133e82d9342480d5c776b5d5cac5cbf7 | [
"Apache-2.0"
] | null | null | null | ikuzo/resource/formats/jsonld/parser.go | jaclu/hub3 | 1a60c948133e82d9342480d5c776b5d5cac5cbf7 | [
"Apache-2.0"
] | null | null | null | // Package jsonld provides tools to parse and serialize RDF data in the JSON-LD format.
//
// For more information about JSON-LD, see - https://json-ld.org.
package jsonld
import (
"bytes"
"fmt"
"io"
"net/http"
"github.com/delving/hub3/ikuzo/resource"
jsonld "github.com/kiivihal/gojsonld"
"github.com/piprate/json-gold/ld"
)
func Parse(r io.Reader, g *resource.Graph) (*resource.Graph, error) {
if g == nil {
g = resource.NewGraph()
}
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(r)
if err != nil {
return g, err
}
jsonData, err := jsonld.ReadJSON(buf.Bytes())
if err != nil {
return g, err
}
options := &jsonld.Options{}
options.Base = ""
options.ProduceGeneralizedRdf = false
dataSet, err := jsonld.ToRDF(jsonData, options)
if err != nil {
return g, err
}
for triple := range dataSet.IterTriples() {
t, err := jtriple2triple(triple)
if err != nil {
return g, err
}
g.Add(t)
}
return g, nil
}
func ParseWithContext(r io.Reader, g *resource.Graph) (*resource.Graph, error) {
if g == nil {
g = resource.NewGraph()
}
doc, err := ld.DocumentFromReader(r)
if err != nil {
return g, err
}
proc := ld.NewJsonLdProcessor()
options := ld.NewJsonLdOptions("")
client := &http.Client{}
nl := ld.NewDefaultDocumentLoader(client)
// testing caching
cdl := ld.NewCachingDocumentLoader(nl)
// cdl.PreloadWithMapping(map[string]string{
// "https://schema.org/": "/home/fils/Project418/gleaner/docs/jsonldcontext.json",
// "http://schema.org/": "/home/fils/Project418/gleaner/docs/jsonldcontext.json",
// "https://schema.org": "/home/fils/Project418/gleaner/docs/jsonldcontext.json",
// "http://schema.org": "/home/fils/Project418/gleaner/docs/jsonldcontext.json",
// })
options.DocumentLoader = cdl
// options.Format = "application/nquads"
rdf, err := proc.ToRDF(doc, options)
if err != nil {
return g, err
}
dataset, ok := rdf.(*ld.RDFDataset)
if !ok {
return g, fmt.Errorf("*ld.RDFDataset should have been returned")
}
for graph, quads := range dataset.Graphs {
if graph != "@default" {
continue
}
for _, quad := range quads {
t, err := quad2triple(quad)
if err != nil {
return g, err
}
g.Add(t)
}
}
return g, nil
}
func quad2triple(quad *ld.Quad) (*resource.Triple, error) {
s, err := ldnode2term(quad.Subject)
if err != nil {
return nil, err
}
p, err := ldnode2term(quad.Predicate)
if err != nil {
return nil, err
}
o, err := ldnode2term(quad.Object)
if err != nil {
return nil, err
}
return resource.NewTriple(s.(resource.Subject), p.(resource.Predicate), o.(resource.Object)), nil
}
func ldnode2term(node ld.Node) (resource.Term, error) {
switch term := node.(type) {
case *ld.BlankNode:
return resource.NewBlankNode(term.GetValue())
case *ld.Literal:
if len(term.Language) > 0 {
return resource.NewLiteralWithLang(term.GetValue(), term.Language)
}
if term.Datatype != "" {
dt, err := resource.NewIRI(term.Datatype)
if err != nil {
return nil, err
}
return resource.NewLiteralWithType(term.Value, &dt)
}
return resource.NewLiteral(term.Value)
case *ld.IRI:
return resource.NewIRI(term.GetValue())
}
return nil, fmt.Errorf("unknown resource.TermType")
}
func jtriple2triple(triple *jsonld.Triple) (*resource.Triple, error) {
s, err := jterm2term(triple.Subject)
if err != nil {
return nil, err
}
p, err := jterm2term(triple.Predicate)
if err != nil {
return nil, err
}
o, err := jterm2term(triple.Object)
if err != nil {
return nil, err
}
return resource.NewTriple(s.(resource.Subject), p.(resource.Predicate), o.(resource.Object)), nil
}
func jterm2term(term jsonld.Term) (resource.Term, error) {
switch term := term.(type) {
case *jsonld.BlankNode:
return resource.NewBlankNode(term.RawValue())
case *jsonld.Literal:
if len(term.Language) > 0 {
return resource.NewLiteralWithLang(term.RawValue(), term.Language)
}
if term.Datatype != nil && len(term.Datatype.String()) > 0 {
dt, err := resource.NewIRI(term.Datatype.RawValue())
if err != nil {
return nil, err
}
return resource.NewLiteralWithType(term.Value, &dt)
}
return resource.NewLiteral(term.Value)
case *jsonld.Resource:
return resource.NewIRI(term.RawValue())
}
return nil, fmt.Errorf("unknown resource.TermType")
}
// compile time check of interface
var _ resource.Parser = (*p)(nil)
type p struct{}
func (p p) Parse(r io.Reader, g *resource.Graph) (*resource.Graph, error) {
return Parse(r, g)
}
| 21.617225 | 98 | 0.66888 |
2a639044ad6c7b721b9debd978307444bf5025eb | 88 | java | Java | xmppbot-commands/src/main/java/de/raion/xmppbot/command/package-info.java | brndkfr/xmppbot | e21ca352fd5fc270e6a8563c340dc2c549d17734 | [
"Apache-2.0"
] | null | null | null | xmppbot-commands/src/main/java/de/raion/xmppbot/command/package-info.java | brndkfr/xmppbot | e21ca352fd5fc270e6a8563c340dc2c549d17734 | [
"Apache-2.0"
] | null | null | null | xmppbot-commands/src/main/java/de/raion/xmppbot/command/package-info.java | brndkfr/xmppbot | e21ca352fd5fc270e6a8563c340dc2c549d17734 | [
"Apache-2.0"
] | null | null | null | /**
* optional commands available for the xmppbot
*/
package de.raion.xmppbot.command; | 22 | 46 | 0.75 |
119ddbe487ff641ee6389651d1a26ce47c498ffb | 1,866 | rs | Rust | src/common/util/string_util.rs | AffogatoLang/moka-rust | e1bad1d529682827a44b75ceccedb7069d5cce16 | [
"BSD-3-Clause"
] | null | null | null | src/common/util/string_util.rs | AffogatoLang/moka-rust | e1bad1d529682827a44b75ceccedb7069d5cce16 | [
"BSD-3-Clause"
] | null | null | null | src/common/util/string_util.rs | AffogatoLang/moka-rust | e1bad1d529682827a44b75ceccedb7069d5cce16 | [
"BSD-3-Clause"
] | null | null | null | use std::ffi::OsStr;
pub fn get_line_col(src: &String, index: usize) -> (usize, usize) {
let slices = src.split_at(index);
let prev:&str = slices.0;
let mut cur_index = 0;
let mut line = 0;
let mut index_of_line = 0;
for ch in prev.chars() {
match ch {
'\n' => {line = line + 1; index_of_line = cur_index;},
_ => ()
}
cur_index = cur_index + 1;
}
let column = index - index_of_line;
(line+1, column+1) // Line and column aren't typically 0 based
}
pub fn generate_syntax_error(src : &String, location : (usize, usize)) -> String {
generate_syntax_error_with_slug(src, location, "")
}
pub fn generate_syntax_error_with_slug<'a>(src: &String, location: (usize, usize), slug: &'a str) -> String {
let mut out : String = "Syntax Error at [".to_string();
out.push_str(&(location.0.to_string()));
out.push_str(", ");
out.push_str(&(location.1.to_string()));
out.push_str("] : ");
let prelength = out.len();
out.push_str(src.lines().skip(location.0 - 1).next().unwrap());
// Location.1 is column, which is not 0 based for display but should be for spacing
let mut pointing : String = String::from_utf8(vec![b' ';prelength + location.1 - 1]).unwrap();
pointing.push_str("^~~~ ");
pointing.push_str(slug);
out.push_str("\n");
out + &pointing
}
pub fn generate_syntax_error_with_slug_from_index<'a>(src: &String, index: usize, slug: &'a str) -> String {
generate_syntax_error_with_slug(src, get_line_col(src, index), slug)
}
pub fn generate_syntax_error_from_index(src: &String, index: usize) -> String {
generate_syntax_error(src, get_line_col(src, index))
}
pub fn osstr_to_string (input: &OsStr) -> Option<String> {
match input.to_str() {
None => None,
Some(val) => Some(val.into())
}
}
| 30.096774 | 109 | 0.626474 |
dd9bfe4dbc7d217988ef992dd9025fc806453208 | 3,458 | go | Go | api/v1/create_statefulset_applicationspec_test.go | dhirupandey/coherence-operator | 6e5cc77f129ac5a5b59b68e0bdd1eba8f5217257 | [
"UPL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | api/v1/create_statefulset_applicationspec_test.go | dhirupandey/coherence-operator | 6e5cc77f129ac5a5b59b68e0bdd1eba8f5217257 | [
"UPL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | api/v1/create_statefulset_applicationspec_test.go | dhirupandey/coherence-operator | 6e5cc77f129ac5a5b59b68e0bdd1eba8f5217257 | [
"UPL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020, Oracle and/or its affiliates.
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
package v1_test
import (
coh "github.com/oracle/coherence-operator/api/v1"
corev1 "k8s.io/api/core/v1"
"testing"
)
func TestCreateStatefulSetWithApplicationType(t *testing.T) {
// Create a spec with an ApplicationSpec with an application type
spec := coh.CoherenceResourceSpec{
Application: &coh.ApplicationSpec{
Type: stringPtr("foo"),
},
}
// Create the test deployment
deployment := createTestDeployment(spec)
// Create expected StatefulSet
stsExpected := createMinimalExpectedStatefulSet(deployment)
// Add the expected environment variables
addEnvVars(stsExpected, coh.ContainerNameCoherence, corev1.EnvVar{Name: coh.EnvVarAppType, Value: "foo"})
// assert that the StatefulSet is as expected
assertStatefulSetCreation(t, deployment, stsExpected)
}
func TestCreateStatefulSetWithApplicationMain(t *testing.T) {
// Create a spec with an ApplicationSpec with a main
mainClass := "com.tangosol.net.CacheFactory"
spec := coh.CoherenceResourceSpec{
Application: &coh.ApplicationSpec{
Main: stringPtr(mainClass),
},
}
// Create the test deployment
deployment := createTestDeployment(spec)
// Create expected StatefulSet
stsExpected := createMinimalExpectedStatefulSet(deployment)
// Add the expected environment variables
addEnvVars(stsExpected, coh.ContainerNameCoherence, corev1.EnvVar{Name: "COH_MAIN_CLASS", Value: mainClass})
// assert that the StatefulSet is as expected
assertStatefulSetCreation(t, deployment, stsExpected)
}
func TestCreateStatefulSetWithApplicationMainArgs(t *testing.T) {
// Create a spec with an ApplicationSpec with a main
spec := coh.CoherenceResourceSpec{
Application: &coh.ApplicationSpec{
Args: []string{"arg1", "arg2"},
},
}
// Create the test deployment
deployment := createTestDeployment(spec)
// Create expected StatefulSet
stsExpected := createMinimalExpectedStatefulSet(deployment)
// Add the expected environment variables
addEnvVars(stsExpected, coh.ContainerNameCoherence, corev1.EnvVar{Name: coh.EnvVarAppMainArgs, Value: "arg1 arg2"})
// assert that the StatefulSet is as expected
assertStatefulSetCreation(t, deployment, stsExpected)
}
func TestCreateStatefulSetWithApplicationMainArgsEmpty(t *testing.T) {
// Create a spec with an ApplicationSpec with a main
spec := coh.CoherenceResourceSpec{
Application: &coh.ApplicationSpec{
Args: []string{},
},
}
// Create the test deployment
deployment := createTestDeployment(spec)
// Create expected StatefulSet
stsExpected := createMinimalExpectedStatefulSet(deployment)
// assert that the StatefulSet is as expected
assertStatefulSetCreation(t, deployment, stsExpected)
}
func TestCreateStatefulSetWithWorkingDirectory(t *testing.T) {
// Create a spec with an ApplicationSpec with an application directory
dir := "/home/foo/app"
spec := coh.CoherenceResourceSpec{
Application: &coh.ApplicationSpec{
WorkingDir: &dir,
},
}
// Create the test deployment
deployment := createTestDeployment(spec)
// Create expected StatefulSet
stsExpected := createMinimalExpectedStatefulSet(deployment)
addEnvVars(stsExpected, coh.ContainerNameCoherence, corev1.EnvVar{Name: coh.EnvVarCohAppDir, Value: dir})
// assert that the StatefulSet is as expected
assertStatefulSetCreation(t, deployment, stsExpected)
}
| 32.018519 | 116 | 0.775593 |
b997ca968f23cb82c0ba32eeb595ef893ac55919 | 378 | h | C | src/tools/runner/run.h | dMajoIT/aqb | 7d9bc71f8bdc64a6edc49fec6815b42bb3050fda | [
"MIT"
] | 51 | 2020-09-07T08:44:29.000Z | 2022-03-30T02:07:19.000Z | src/tools/runner/run.h | dMajoIT/aqb | 7d9bc71f8bdc64a6edc49fec6815b42bb3050fda | [
"MIT"
] | 17 | 2021-09-27T07:24:01.000Z | 2022-03-23T19:33:59.000Z | src/tools/runner/run.h | dMajoIT/aqb | 7d9bc71f8bdc64a6edc49fec6815b42bb3050fda | [
"MIT"
] | 7 | 2021-09-09T15:35:24.000Z | 2022-03-09T17:37:35.000Z | #ifndef HAVE_RUN_H
#define HAVE_RUN_H
#ifdef __amigaos__
#include <dos/dosextens.h>
typedef enum {RUN_stateRunning, RUN_stateStopped} RUN_state;
void RUN_start (const char *binfn);
void RUN_init (struct MsgPort *debugPort, struct FileHandle *output);
void RUN_handleMessages(void);
RUN_state RUN_getState(void);
void RUN_break (void);
#endif
#endif
| 17.181818 | 74 | 0.743386 |
6cbd02a6d8d83be0bca0ec1edbc195aef615b601 | 102,058 | go | Go | pkg/contracts/adm/admanager.go | atatur9/kaleido-backend-1 | dc588d802f4269bbe3f1938dbcd9fef8bb5ecf74 | [
"MIT"
] | null | null | null | pkg/contracts/adm/admanager.go | atatur9/kaleido-backend-1 | dc588d802f4269bbe3f1938dbcd9fef8bb5ecf74 | [
"MIT"
] | null | null | null | pkg/contracts/adm/admanager.go | atatur9/kaleido-backend-1 | dc588d802f4269bbe3f1938dbcd9fef8bb5ecf74 | [
"MIT"
] | null | null | null | // Code generated - DO NOT EDIT.
// This file is a generated binding and any manual changes will be lost.
package contracts
import (
"errors"
"math/big"
"strings"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
)
// Reference imports to suppress errors if they are not otherwise used.
var (
_ = errors.New
_ = big.NewInt
_ = strings.NewReader
_ = ethereum.NotFound
_ = bind.Bind
_ = common.Big1
_ = types.BloomLookup
_ = event.NewSubscription
)
// ContractsMetaData contains all meta data concerning the Contracts contract.
var ContractsMetaData = &bind.MetaData{
ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"accept\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"string\",\"name\":\"tokenMetadata\",\"type\":\"string\"}],\"name\":\"acceptOffer\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"accepted\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"spaceMetadata\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"displayStartTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"displayEndTimestamp\",\"type\":\"uint256\"}],\"name\":\"adId\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"adPoolAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"allPeriods\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"mediaProxy\",\"type\":\"address\"},{\"internalType\":\"string\",\"name\":\"spaceMetadata\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"tokenMetadata\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"saleStartTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"saleEndTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"displayStartTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"displayEndTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"enumAd.Pricing\",\"name\":\"pricing\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"minPrice\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"startPrice\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"sold\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"balance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"bid\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"bidding\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"bidder\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"price\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"buy\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"buyBasedOnTime\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"currentPrice\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"deletePeriod\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"deniedReason\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"string\",\"name\":\"reason\",\"type\":\"string\"}],\"name\":\"deny\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"spaceMetadata\",\"type\":\"string\"}],\"name\":\"display\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"eventEmitterAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"title\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"baseURI\",\"type\":\"string\"},{\"internalType\":\"address\",\"name\":\"nameRegistry\",\"type\":\"address\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"mediaFactoryAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"mediaRegistryAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"nameRegistryAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"spaceMetadata\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"tokenMetadata\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"saleEndTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"displayStartTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"displayEndTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"enumAd.Pricing\",\"name\":\"pricing\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"minPrice\",\"type\":\"uint256\"}],\"name\":\"newPeriod\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"spaceMetadata\",\"type\":\"string\"}],\"name\":\"newSpace\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"spaceMetadata\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"displayStartTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"displayEndTimestamp\",\"type\":\"uint256\"}],\"name\":\"offerPeriod\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"offered\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"spaceMetadata\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"displayStartTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"displayEndTimestamp\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"price\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"string\",\"name\":\"metadata\",\"type\":\"string\"}],\"name\":\"propose\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"proposed\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"receiveToken\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"operator\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"name\":\"spaced\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"spaceMetadata\",\"type\":\"string\"}],\"name\":\"tokenIdsOf\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"\",\"type\":\"uint256[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"transferToBundle\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newMediaEOA\",\"type\":\"address\"},{\"internalType\":\"string\",\"name\":\"newMetadata\",\"type\":\"string\"}],\"name\":\"updateMedia\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"vaultAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdraw\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]",
}
// ContractsABI is the input ABI used to generate the binding from.
// Deprecated: Use ContractsMetaData.ABI instead.
var ContractsABI = ContractsMetaData.ABI
// Contracts is an auto generated Go binding around an Ethereum contract.
type Contracts struct {
ContractsCaller // Read-only binding to the contract
ContractsTransactor // Write-only binding to the contract
ContractsFilterer // Log filterer for contract events
}
// ContractsCaller is an auto generated read-only Go binding around an Ethereum contract.
type ContractsCaller struct {
contract *bind.BoundContract // Generic contract wrapper for the low level calls
}
// ContractsTransactor is an auto generated write-only Go binding around an Ethereum contract.
type ContractsTransactor struct {
contract *bind.BoundContract // Generic contract wrapper for the low level calls
}
// ContractsFilterer is an auto generated log filtering Go binding around an Ethereum contract events.
type ContractsFilterer struct {
contract *bind.BoundContract // Generic contract wrapper for the low level calls
}
// ContractsSession is an auto generated Go binding around an Ethereum contract,
// with pre-set call and transact options.
type ContractsSession struct {
Contract *Contracts // Generic contract binding to set the session for
CallOpts bind.CallOpts // Call options to use throughout this session
TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session
}
// ContractsCallerSession is an auto generated read-only Go binding around an Ethereum contract,
// with pre-set call options.
type ContractsCallerSession struct {
Contract *ContractsCaller // Generic contract caller binding to set the session for
CallOpts bind.CallOpts // Call options to use throughout this session
}
// ContractsTransactorSession is an auto generated write-only Go binding around an Ethereum contract,
// with pre-set transact options.
type ContractsTransactorSession struct {
Contract *ContractsTransactor // Generic contract transactor binding to set the session for
TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session
}
// ContractsRaw is an auto generated low-level Go binding around an Ethereum contract.
type ContractsRaw struct {
Contract *Contracts // Generic contract binding to access the raw methods on
}
// ContractsCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract.
type ContractsCallerRaw struct {
Contract *ContractsCaller // Generic read-only contract binding to access the raw methods on
}
// ContractsTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract.
type ContractsTransactorRaw struct {
Contract *ContractsTransactor // Generic write-only contract binding to access the raw methods on
}
// NewContracts creates a new instance of Contracts, bound to a specific deployed contract.
func NewContracts(address common.Address, backend bind.ContractBackend) (*Contracts, error) {
contract, err := bindContracts(address, backend, backend, backend)
if err != nil {
return nil, err
}
return &Contracts{ContractsCaller: ContractsCaller{contract: contract}, ContractsTransactor: ContractsTransactor{contract: contract}, ContractsFilterer: ContractsFilterer{contract: contract}}, nil
}
// NewContractsCaller creates a new read-only instance of Contracts, bound to a specific deployed contract.
func NewContractsCaller(address common.Address, caller bind.ContractCaller) (*ContractsCaller, error) {
contract, err := bindContracts(address, caller, nil, nil)
if err != nil {
return nil, err
}
return &ContractsCaller{contract: contract}, nil
}
// NewContractsTransactor creates a new write-only instance of Contracts, bound to a specific deployed contract.
func NewContractsTransactor(address common.Address, transactor bind.ContractTransactor) (*ContractsTransactor, error) {
contract, err := bindContracts(address, nil, transactor, nil)
if err != nil {
return nil, err
}
return &ContractsTransactor{contract: contract}, nil
}
// NewContractsFilterer creates a new log filterer instance of Contracts, bound to a specific deployed contract.
func NewContractsFilterer(address common.Address, filterer bind.ContractFilterer) (*ContractsFilterer, error) {
contract, err := bindContracts(address, nil, nil, filterer)
if err != nil {
return nil, err
}
return &ContractsFilterer{contract: contract}, nil
}
// bindContracts binds a generic wrapper to an already deployed contract.
func bindContracts(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
parsed, err := abi.JSON(strings.NewReader(ContractsABI))
if err != nil {
return nil, err
}
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
}
// Call invokes the (constant) contract method with params as input values and
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.
func (_Contracts *ContractsRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _Contracts.Contract.ContractsCaller.contract.Call(opts, result, method, params...)
}
// Transfer initiates a plain transaction to move funds to the contract, calling
// its default method if one is available.
func (_Contracts *ContractsRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _Contracts.Contract.ContractsTransactor.contract.Transfer(opts)
}
// Transact invokes the (paid) contract method with params as input values.
func (_Contracts *ContractsRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _Contracts.Contract.ContractsTransactor.contract.Transact(opts, method, params...)
}
// Call invokes the (constant) contract method with params as input values and
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.
func (_Contracts *ContractsCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {
return _Contracts.Contract.contract.Call(opts, result, method, params...)
}
// Transfer initiates a plain transaction to move funds to the contract, calling
// its default method if one is available.
func (_Contracts *ContractsTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _Contracts.Contract.contract.Transfer(opts)
}
// Transact invokes the (paid) contract method with params as input values.
func (_Contracts *ContractsTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _Contracts.Contract.contract.Transact(opts, method, params...)
}
// Accepted is a free data retrieval call binding the contract method 0xf19b8273.
//
// Solidity: function accepted(uint256 ) view returns(string)
func (_Contracts *ContractsCaller) Accepted(opts *bind.CallOpts, arg0 *big.Int) (string, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "accepted", arg0)
if err != nil {
return *new(string), err
}
out0 := *abi.ConvertType(out[0], new(string)).(*string)
return out0, err
}
// Accepted is a free data retrieval call binding the contract method 0xf19b8273.
//
// Solidity: function accepted(uint256 ) view returns(string)
func (_Contracts *ContractsSession) Accepted(arg0 *big.Int) (string, error) {
return _Contracts.Contract.Accepted(&_Contracts.CallOpts, arg0)
}
// Accepted is a free data retrieval call binding the contract method 0xf19b8273.
//
// Solidity: function accepted(uint256 ) view returns(string)
func (_Contracts *ContractsCallerSession) Accepted(arg0 *big.Int) (string, error) {
return _Contracts.Contract.Accepted(&_Contracts.CallOpts, arg0)
}
// AdId is a free data retrieval call binding the contract method 0xc531c236.
//
// Solidity: function adId(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp) pure returns(uint256)
func (_Contracts *ContractsCaller) AdId(opts *bind.CallOpts, spaceMetadata string, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int) (*big.Int, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "adId", spaceMetadata, displayStartTimestamp, displayEndTimestamp)
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
// AdId is a free data retrieval call binding the contract method 0xc531c236.
//
// Solidity: function adId(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp) pure returns(uint256)
func (_Contracts *ContractsSession) AdId(spaceMetadata string, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int) (*big.Int, error) {
return _Contracts.Contract.AdId(&_Contracts.CallOpts, spaceMetadata, displayStartTimestamp, displayEndTimestamp)
}
// AdId is a free data retrieval call binding the contract method 0xc531c236.
//
// Solidity: function adId(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp) pure returns(uint256)
func (_Contracts *ContractsCallerSession) AdId(spaceMetadata string, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int) (*big.Int, error) {
return _Contracts.Contract.AdId(&_Contracts.CallOpts, spaceMetadata, displayStartTimestamp, displayEndTimestamp)
}
// AdPoolAddress is a free data retrieval call binding the contract method 0xc9cd71b5.
//
// Solidity: function adPoolAddress() view returns(address)
func (_Contracts *ContractsCaller) AdPoolAddress(opts *bind.CallOpts) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "adPoolAddress")
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// AdPoolAddress is a free data retrieval call binding the contract method 0xc9cd71b5.
//
// Solidity: function adPoolAddress() view returns(address)
func (_Contracts *ContractsSession) AdPoolAddress() (common.Address, error) {
return _Contracts.Contract.AdPoolAddress(&_Contracts.CallOpts)
}
// AdPoolAddress is a free data retrieval call binding the contract method 0xc9cd71b5.
//
// Solidity: function adPoolAddress() view returns(address)
func (_Contracts *ContractsCallerSession) AdPoolAddress() (common.Address, error) {
return _Contracts.Contract.AdPoolAddress(&_Contracts.CallOpts)
}
// AllPeriods is a free data retrieval call binding the contract method 0xb3a0ebc9.
//
// Solidity: function allPeriods(uint256 ) view returns(address mediaProxy, string spaceMetadata, string tokenMetadata, uint256 saleStartTimestamp, uint256 saleEndTimestamp, uint256 displayStartTimestamp, uint256 displayEndTimestamp, uint8 pricing, uint256 minPrice, uint256 startPrice, bool sold)
func (_Contracts *ContractsCaller) AllPeriods(opts *bind.CallOpts, arg0 *big.Int) (struct {
MediaProxy common.Address
SpaceMetadata string
TokenMetadata string
SaleStartTimestamp *big.Int
SaleEndTimestamp *big.Int
DisplayStartTimestamp *big.Int
DisplayEndTimestamp *big.Int
Pricing uint8
MinPrice *big.Int
StartPrice *big.Int
Sold bool
}, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "allPeriods", arg0)
outstruct := new(struct {
MediaProxy common.Address
SpaceMetadata string
TokenMetadata string
SaleStartTimestamp *big.Int
SaleEndTimestamp *big.Int
DisplayStartTimestamp *big.Int
DisplayEndTimestamp *big.Int
Pricing uint8
MinPrice *big.Int
StartPrice *big.Int
Sold bool
})
if err != nil {
return *outstruct, err
}
outstruct.MediaProxy = *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
outstruct.SpaceMetadata = *abi.ConvertType(out[1], new(string)).(*string)
outstruct.TokenMetadata = *abi.ConvertType(out[2], new(string)).(*string)
outstruct.SaleStartTimestamp = *abi.ConvertType(out[3], new(*big.Int)).(**big.Int)
outstruct.SaleEndTimestamp = *abi.ConvertType(out[4], new(*big.Int)).(**big.Int)
outstruct.DisplayStartTimestamp = *abi.ConvertType(out[5], new(*big.Int)).(**big.Int)
outstruct.DisplayEndTimestamp = *abi.ConvertType(out[6], new(*big.Int)).(**big.Int)
outstruct.Pricing = *abi.ConvertType(out[7], new(uint8)).(*uint8)
outstruct.MinPrice = *abi.ConvertType(out[8], new(*big.Int)).(**big.Int)
outstruct.StartPrice = *abi.ConvertType(out[9], new(*big.Int)).(**big.Int)
outstruct.Sold = *abi.ConvertType(out[10], new(bool)).(*bool)
return *outstruct, err
}
// AllPeriods is a free data retrieval call binding the contract method 0xb3a0ebc9.
//
// Solidity: function allPeriods(uint256 ) view returns(address mediaProxy, string spaceMetadata, string tokenMetadata, uint256 saleStartTimestamp, uint256 saleEndTimestamp, uint256 displayStartTimestamp, uint256 displayEndTimestamp, uint8 pricing, uint256 minPrice, uint256 startPrice, bool sold)
func (_Contracts *ContractsSession) AllPeriods(arg0 *big.Int) (struct {
MediaProxy common.Address
SpaceMetadata string
TokenMetadata string
SaleStartTimestamp *big.Int
SaleEndTimestamp *big.Int
DisplayStartTimestamp *big.Int
DisplayEndTimestamp *big.Int
Pricing uint8
MinPrice *big.Int
StartPrice *big.Int
Sold bool
}, error) {
return _Contracts.Contract.AllPeriods(&_Contracts.CallOpts, arg0)
}
// AllPeriods is a free data retrieval call binding the contract method 0xb3a0ebc9.
//
// Solidity: function allPeriods(uint256 ) view returns(address mediaProxy, string spaceMetadata, string tokenMetadata, uint256 saleStartTimestamp, uint256 saleEndTimestamp, uint256 displayStartTimestamp, uint256 displayEndTimestamp, uint8 pricing, uint256 minPrice, uint256 startPrice, bool sold)
func (_Contracts *ContractsCallerSession) AllPeriods(arg0 *big.Int) (struct {
MediaProxy common.Address
SpaceMetadata string
TokenMetadata string
SaleStartTimestamp *big.Int
SaleEndTimestamp *big.Int
DisplayStartTimestamp *big.Int
DisplayEndTimestamp *big.Int
Pricing uint8
MinPrice *big.Int
StartPrice *big.Int
Sold bool
}, error) {
return _Contracts.Contract.AllPeriods(&_Contracts.CallOpts, arg0)
}
// Balance is a free data retrieval call binding the contract method 0xb69ef8a8.
//
// Solidity: function balance() view returns(uint256)
func (_Contracts *ContractsCaller) Balance(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "balance")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
// Balance is a free data retrieval call binding the contract method 0xb69ef8a8.
//
// Solidity: function balance() view returns(uint256)
func (_Contracts *ContractsSession) Balance() (*big.Int, error) {
return _Contracts.Contract.Balance(&_Contracts.CallOpts)
}
// Balance is a free data retrieval call binding the contract method 0xb69ef8a8.
//
// Solidity: function balance() view returns(uint256)
func (_Contracts *ContractsCallerSession) Balance() (*big.Int, error) {
return _Contracts.Contract.Balance(&_Contracts.CallOpts)
}
// BalanceOf is a free data retrieval call binding the contract method 0x70a08231.
//
// Solidity: function balanceOf(address owner) view returns(uint256)
func (_Contracts *ContractsCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "balanceOf", owner)
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
// BalanceOf is a free data retrieval call binding the contract method 0x70a08231.
//
// Solidity: function balanceOf(address owner) view returns(uint256)
func (_Contracts *ContractsSession) BalanceOf(owner common.Address) (*big.Int, error) {
return _Contracts.Contract.BalanceOf(&_Contracts.CallOpts, owner)
}
// BalanceOf is a free data retrieval call binding the contract method 0x70a08231.
//
// Solidity: function balanceOf(address owner) view returns(uint256)
func (_Contracts *ContractsCallerSession) BalanceOf(owner common.Address) (*big.Int, error) {
return _Contracts.Contract.BalanceOf(&_Contracts.CallOpts, owner)
}
// Bidding is a free data retrieval call binding the contract method 0xcc889b0b.
//
// Solidity: function bidding(uint256 ) view returns(uint256 tokenId, address bidder, uint256 price)
func (_Contracts *ContractsCaller) Bidding(opts *bind.CallOpts, arg0 *big.Int) (struct {
TokenId *big.Int
Bidder common.Address
Price *big.Int
}, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "bidding", arg0)
outstruct := new(struct {
TokenId *big.Int
Bidder common.Address
Price *big.Int
})
if err != nil {
return *outstruct, err
}
outstruct.TokenId = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
outstruct.Bidder = *abi.ConvertType(out[1], new(common.Address)).(*common.Address)
outstruct.Price = *abi.ConvertType(out[2], new(*big.Int)).(**big.Int)
return *outstruct, err
}
// Bidding is a free data retrieval call binding the contract method 0xcc889b0b.
//
// Solidity: function bidding(uint256 ) view returns(uint256 tokenId, address bidder, uint256 price)
func (_Contracts *ContractsSession) Bidding(arg0 *big.Int) (struct {
TokenId *big.Int
Bidder common.Address
Price *big.Int
}, error) {
return _Contracts.Contract.Bidding(&_Contracts.CallOpts, arg0)
}
// Bidding is a free data retrieval call binding the contract method 0xcc889b0b.
//
// Solidity: function bidding(uint256 ) view returns(uint256 tokenId, address bidder, uint256 price)
func (_Contracts *ContractsCallerSession) Bidding(arg0 *big.Int) (struct {
TokenId *big.Int
Bidder common.Address
Price *big.Int
}, error) {
return _Contracts.Contract.Bidding(&_Contracts.CallOpts, arg0)
}
// CurrentPrice is a free data retrieval call binding the contract method 0x7a3c4c17.
//
// Solidity: function currentPrice(uint256 tokenId) view returns(uint256)
func (_Contracts *ContractsCaller) CurrentPrice(opts *bind.CallOpts, tokenId *big.Int) (*big.Int, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "currentPrice", tokenId)
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
// CurrentPrice is a free data retrieval call binding the contract method 0x7a3c4c17.
//
// Solidity: function currentPrice(uint256 tokenId) view returns(uint256)
func (_Contracts *ContractsSession) CurrentPrice(tokenId *big.Int) (*big.Int, error) {
return _Contracts.Contract.CurrentPrice(&_Contracts.CallOpts, tokenId)
}
// CurrentPrice is a free data retrieval call binding the contract method 0x7a3c4c17.
//
// Solidity: function currentPrice(uint256 tokenId) view returns(uint256)
func (_Contracts *ContractsCallerSession) CurrentPrice(tokenId *big.Int) (*big.Int, error) {
return _Contracts.Contract.CurrentPrice(&_Contracts.CallOpts, tokenId)
}
// DeniedReason is a free data retrieval call binding the contract method 0xa9a86f0e.
//
// Solidity: function deniedReason(uint256 ) view returns(string)
func (_Contracts *ContractsCaller) DeniedReason(opts *bind.CallOpts, arg0 *big.Int) (string, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "deniedReason", arg0)
if err != nil {
return *new(string), err
}
out0 := *abi.ConvertType(out[0], new(string)).(*string)
return out0, err
}
// DeniedReason is a free data retrieval call binding the contract method 0xa9a86f0e.
//
// Solidity: function deniedReason(uint256 ) view returns(string)
func (_Contracts *ContractsSession) DeniedReason(arg0 *big.Int) (string, error) {
return _Contracts.Contract.DeniedReason(&_Contracts.CallOpts, arg0)
}
// DeniedReason is a free data retrieval call binding the contract method 0xa9a86f0e.
//
// Solidity: function deniedReason(uint256 ) view returns(string)
func (_Contracts *ContractsCallerSession) DeniedReason(arg0 *big.Int) (string, error) {
return _Contracts.Contract.DeniedReason(&_Contracts.CallOpts, arg0)
}
// Display is a free data retrieval call binding the contract method 0x53c14776.
//
// Solidity: function display(string spaceMetadata) view returns(string)
func (_Contracts *ContractsCaller) Display(opts *bind.CallOpts, spaceMetadata string) (string, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "display", spaceMetadata)
if err != nil {
return *new(string), err
}
out0 := *abi.ConvertType(out[0], new(string)).(*string)
return out0, err
}
// Display is a free data retrieval call binding the contract method 0x53c14776.
//
// Solidity: function display(string spaceMetadata) view returns(string)
func (_Contracts *ContractsSession) Display(spaceMetadata string) (string, error) {
return _Contracts.Contract.Display(&_Contracts.CallOpts, spaceMetadata)
}
// Display is a free data retrieval call binding the contract method 0x53c14776.
//
// Solidity: function display(string spaceMetadata) view returns(string)
func (_Contracts *ContractsCallerSession) Display(spaceMetadata string) (string, error) {
return _Contracts.Contract.Display(&_Contracts.CallOpts, spaceMetadata)
}
// EventEmitterAddress is a free data retrieval call binding the contract method 0xf0726291.
//
// Solidity: function eventEmitterAddress() view returns(address)
func (_Contracts *ContractsCaller) EventEmitterAddress(opts *bind.CallOpts) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "eventEmitterAddress")
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// EventEmitterAddress is a free data retrieval call binding the contract method 0xf0726291.
//
// Solidity: function eventEmitterAddress() view returns(address)
func (_Contracts *ContractsSession) EventEmitterAddress() (common.Address, error) {
return _Contracts.Contract.EventEmitterAddress(&_Contracts.CallOpts)
}
// EventEmitterAddress is a free data retrieval call binding the contract method 0xf0726291.
//
// Solidity: function eventEmitterAddress() view returns(address)
func (_Contracts *ContractsCallerSession) EventEmitterAddress() (common.Address, error) {
return _Contracts.Contract.EventEmitterAddress(&_Contracts.CallOpts)
}
// GetApproved is a free data retrieval call binding the contract method 0x081812fc.
//
// Solidity: function getApproved(uint256 tokenId) view returns(address)
func (_Contracts *ContractsCaller) GetApproved(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "getApproved", tokenId)
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// GetApproved is a free data retrieval call binding the contract method 0x081812fc.
//
// Solidity: function getApproved(uint256 tokenId) view returns(address)
func (_Contracts *ContractsSession) GetApproved(tokenId *big.Int) (common.Address, error) {
return _Contracts.Contract.GetApproved(&_Contracts.CallOpts, tokenId)
}
// GetApproved is a free data retrieval call binding the contract method 0x081812fc.
//
// Solidity: function getApproved(uint256 tokenId) view returns(address)
func (_Contracts *ContractsCallerSession) GetApproved(tokenId *big.Int) (common.Address, error) {
return _Contracts.Contract.GetApproved(&_Contracts.CallOpts, tokenId)
}
// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5.
//
// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool)
func (_Contracts *ContractsCaller) IsApprovedForAll(opts *bind.CallOpts, owner common.Address, operator common.Address) (bool, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "isApprovedForAll", owner, operator)
if err != nil {
return *new(bool), err
}
out0 := *abi.ConvertType(out[0], new(bool)).(*bool)
return out0, err
}
// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5.
//
// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool)
func (_Contracts *ContractsSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) {
return _Contracts.Contract.IsApprovedForAll(&_Contracts.CallOpts, owner, operator)
}
// IsApprovedForAll is a free data retrieval call binding the contract method 0xe985e9c5.
//
// Solidity: function isApprovedForAll(address owner, address operator) view returns(bool)
func (_Contracts *ContractsCallerSession) IsApprovedForAll(owner common.Address, operator common.Address) (bool, error) {
return _Contracts.Contract.IsApprovedForAll(&_Contracts.CallOpts, owner, operator)
}
// MediaFactoryAddress is a free data retrieval call binding the contract method 0x8f6059d6.
//
// Solidity: function mediaFactoryAddress() view returns(address)
func (_Contracts *ContractsCaller) MediaFactoryAddress(opts *bind.CallOpts) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "mediaFactoryAddress")
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// MediaFactoryAddress is a free data retrieval call binding the contract method 0x8f6059d6.
//
// Solidity: function mediaFactoryAddress() view returns(address)
func (_Contracts *ContractsSession) MediaFactoryAddress() (common.Address, error) {
return _Contracts.Contract.MediaFactoryAddress(&_Contracts.CallOpts)
}
// MediaFactoryAddress is a free data retrieval call binding the contract method 0x8f6059d6.
//
// Solidity: function mediaFactoryAddress() view returns(address)
func (_Contracts *ContractsCallerSession) MediaFactoryAddress() (common.Address, error) {
return _Contracts.Contract.MediaFactoryAddress(&_Contracts.CallOpts)
}
// MediaRegistryAddress is a free data retrieval call binding the contract method 0x6a58767e.
//
// Solidity: function mediaRegistryAddress() view returns(address)
func (_Contracts *ContractsCaller) MediaRegistryAddress(opts *bind.CallOpts) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "mediaRegistryAddress")
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// MediaRegistryAddress is a free data retrieval call binding the contract method 0x6a58767e.
//
// Solidity: function mediaRegistryAddress() view returns(address)
func (_Contracts *ContractsSession) MediaRegistryAddress() (common.Address, error) {
return _Contracts.Contract.MediaRegistryAddress(&_Contracts.CallOpts)
}
// MediaRegistryAddress is a free data retrieval call binding the contract method 0x6a58767e.
//
// Solidity: function mediaRegistryAddress() view returns(address)
func (_Contracts *ContractsCallerSession) MediaRegistryAddress() (common.Address, error) {
return _Contracts.Contract.MediaRegistryAddress(&_Contracts.CallOpts)
}
// Name is a free data retrieval call binding the contract method 0x06fdde03.
//
// Solidity: function name() view returns(string)
func (_Contracts *ContractsCaller) Name(opts *bind.CallOpts) (string, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "name")
if err != nil {
return *new(string), err
}
out0 := *abi.ConvertType(out[0], new(string)).(*string)
return out0, err
}
// Name is a free data retrieval call binding the contract method 0x06fdde03.
//
// Solidity: function name() view returns(string)
func (_Contracts *ContractsSession) Name() (string, error) {
return _Contracts.Contract.Name(&_Contracts.CallOpts)
}
// Name is a free data retrieval call binding the contract method 0x06fdde03.
//
// Solidity: function name() view returns(string)
func (_Contracts *ContractsCallerSession) Name() (string, error) {
return _Contracts.Contract.Name(&_Contracts.CallOpts)
}
// NameRegistryAddress is a free data retrieval call binding the contract method 0x27b7a2f5.
//
// Solidity: function nameRegistryAddress() view returns(address)
func (_Contracts *ContractsCaller) NameRegistryAddress(opts *bind.CallOpts) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "nameRegistryAddress")
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// NameRegistryAddress is a free data retrieval call binding the contract method 0x27b7a2f5.
//
// Solidity: function nameRegistryAddress() view returns(address)
func (_Contracts *ContractsSession) NameRegistryAddress() (common.Address, error) {
return _Contracts.Contract.NameRegistryAddress(&_Contracts.CallOpts)
}
// NameRegistryAddress is a free data retrieval call binding the contract method 0x27b7a2f5.
//
// Solidity: function nameRegistryAddress() view returns(address)
func (_Contracts *ContractsCallerSession) NameRegistryAddress() (common.Address, error) {
return _Contracts.Contract.NameRegistryAddress(&_Contracts.CallOpts)
}
// Offered is a free data retrieval call binding the contract method 0x01b99e04.
//
// Solidity: function offered(uint256 ) view returns(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp, address sender, uint256 price)
func (_Contracts *ContractsCaller) Offered(opts *bind.CallOpts, arg0 *big.Int) (struct {
SpaceMetadata string
DisplayStartTimestamp *big.Int
DisplayEndTimestamp *big.Int
Sender common.Address
Price *big.Int
}, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "offered", arg0)
outstruct := new(struct {
SpaceMetadata string
DisplayStartTimestamp *big.Int
DisplayEndTimestamp *big.Int
Sender common.Address
Price *big.Int
})
if err != nil {
return *outstruct, err
}
outstruct.SpaceMetadata = *abi.ConvertType(out[0], new(string)).(*string)
outstruct.DisplayStartTimestamp = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)
outstruct.DisplayEndTimestamp = *abi.ConvertType(out[2], new(*big.Int)).(**big.Int)
outstruct.Sender = *abi.ConvertType(out[3], new(common.Address)).(*common.Address)
outstruct.Price = *abi.ConvertType(out[4], new(*big.Int)).(**big.Int)
return *outstruct, err
}
// Offered is a free data retrieval call binding the contract method 0x01b99e04.
//
// Solidity: function offered(uint256 ) view returns(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp, address sender, uint256 price)
func (_Contracts *ContractsSession) Offered(arg0 *big.Int) (struct {
SpaceMetadata string
DisplayStartTimestamp *big.Int
DisplayEndTimestamp *big.Int
Sender common.Address
Price *big.Int
}, error) {
return _Contracts.Contract.Offered(&_Contracts.CallOpts, arg0)
}
// Offered is a free data retrieval call binding the contract method 0x01b99e04.
//
// Solidity: function offered(uint256 ) view returns(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp, address sender, uint256 price)
func (_Contracts *ContractsCallerSession) Offered(arg0 *big.Int) (struct {
SpaceMetadata string
DisplayStartTimestamp *big.Int
DisplayEndTimestamp *big.Int
Sender common.Address
Price *big.Int
}, error) {
return _Contracts.Contract.Offered(&_Contracts.CallOpts, arg0)
}
// Owner is a free data retrieval call binding the contract method 0x8da5cb5b.
//
// Solidity: function owner() view returns(address)
func (_Contracts *ContractsCaller) Owner(opts *bind.CallOpts) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "owner")
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// Owner is a free data retrieval call binding the contract method 0x8da5cb5b.
//
// Solidity: function owner() view returns(address)
func (_Contracts *ContractsSession) Owner() (common.Address, error) {
return _Contracts.Contract.Owner(&_Contracts.CallOpts)
}
// Owner is a free data retrieval call binding the contract method 0x8da5cb5b.
//
// Solidity: function owner() view returns(address)
func (_Contracts *ContractsCallerSession) Owner() (common.Address, error) {
return _Contracts.Contract.Owner(&_Contracts.CallOpts)
}
// OwnerOf is a free data retrieval call binding the contract method 0x6352211e.
//
// Solidity: function ownerOf(uint256 tokenId) view returns(address)
func (_Contracts *ContractsCaller) OwnerOf(opts *bind.CallOpts, tokenId *big.Int) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "ownerOf", tokenId)
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// OwnerOf is a free data retrieval call binding the contract method 0x6352211e.
//
// Solidity: function ownerOf(uint256 tokenId) view returns(address)
func (_Contracts *ContractsSession) OwnerOf(tokenId *big.Int) (common.Address, error) {
return _Contracts.Contract.OwnerOf(&_Contracts.CallOpts, tokenId)
}
// OwnerOf is a free data retrieval call binding the contract method 0x6352211e.
//
// Solidity: function ownerOf(uint256 tokenId) view returns(address)
func (_Contracts *ContractsCallerSession) OwnerOf(tokenId *big.Int) (common.Address, error) {
return _Contracts.Contract.OwnerOf(&_Contracts.CallOpts, tokenId)
}
// Proposed is a free data retrieval call binding the contract method 0x58ba1bb8.
//
// Solidity: function proposed(uint256 ) view returns(string)
func (_Contracts *ContractsCaller) Proposed(opts *bind.CallOpts, arg0 *big.Int) (string, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "proposed", arg0)
if err != nil {
return *new(string), err
}
out0 := *abi.ConvertType(out[0], new(string)).(*string)
return out0, err
}
// Proposed is a free data retrieval call binding the contract method 0x58ba1bb8.
//
// Solidity: function proposed(uint256 ) view returns(string)
func (_Contracts *ContractsSession) Proposed(arg0 *big.Int) (string, error) {
return _Contracts.Contract.Proposed(&_Contracts.CallOpts, arg0)
}
// Proposed is a free data retrieval call binding the contract method 0x58ba1bb8.
//
// Solidity: function proposed(uint256 ) view returns(string)
func (_Contracts *ContractsCallerSession) Proposed(arg0 *big.Int) (string, error) {
return _Contracts.Contract.Proposed(&_Contracts.CallOpts, arg0)
}
// Spaced is a free data retrieval call binding the contract method 0x65045a65.
//
// Solidity: function spaced(string ) view returns(bool)
func (_Contracts *ContractsCaller) Spaced(opts *bind.CallOpts, arg0 string) (bool, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "spaced", arg0)
if err != nil {
return *new(bool), err
}
out0 := *abi.ConvertType(out[0], new(bool)).(*bool)
return out0, err
}
// Spaced is a free data retrieval call binding the contract method 0x65045a65.
//
// Solidity: function spaced(string ) view returns(bool)
func (_Contracts *ContractsSession) Spaced(arg0 string) (bool, error) {
return _Contracts.Contract.Spaced(&_Contracts.CallOpts, arg0)
}
// Spaced is a free data retrieval call binding the contract method 0x65045a65.
//
// Solidity: function spaced(string ) view returns(bool)
func (_Contracts *ContractsCallerSession) Spaced(arg0 string) (bool, error) {
return _Contracts.Contract.Spaced(&_Contracts.CallOpts, arg0)
}
// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7.
//
// Solidity: function supportsInterface(bytes4 interfaceId) pure returns(bool)
func (_Contracts *ContractsCaller) SupportsInterface(opts *bind.CallOpts, interfaceId [4]byte) (bool, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "supportsInterface", interfaceId)
if err != nil {
return *new(bool), err
}
out0 := *abi.ConvertType(out[0], new(bool)).(*bool)
return out0, err
}
// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7.
//
// Solidity: function supportsInterface(bytes4 interfaceId) pure returns(bool)
func (_Contracts *ContractsSession) SupportsInterface(interfaceId [4]byte) (bool, error) {
return _Contracts.Contract.SupportsInterface(&_Contracts.CallOpts, interfaceId)
}
// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7.
//
// Solidity: function supportsInterface(bytes4 interfaceId) pure returns(bool)
func (_Contracts *ContractsCallerSession) SupportsInterface(interfaceId [4]byte) (bool, error) {
return _Contracts.Contract.SupportsInterface(&_Contracts.CallOpts, interfaceId)
}
// Symbol is a free data retrieval call binding the contract method 0x95d89b41.
//
// Solidity: function symbol() view returns(string)
func (_Contracts *ContractsCaller) Symbol(opts *bind.CallOpts) (string, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "symbol")
if err != nil {
return *new(string), err
}
out0 := *abi.ConvertType(out[0], new(string)).(*string)
return out0, err
}
// Symbol is a free data retrieval call binding the contract method 0x95d89b41.
//
// Solidity: function symbol() view returns(string)
func (_Contracts *ContractsSession) Symbol() (string, error) {
return _Contracts.Contract.Symbol(&_Contracts.CallOpts)
}
// Symbol is a free data retrieval call binding the contract method 0x95d89b41.
//
// Solidity: function symbol() view returns(string)
func (_Contracts *ContractsCallerSession) Symbol() (string, error) {
return _Contracts.Contract.Symbol(&_Contracts.CallOpts)
}
// TokenByIndex is a free data retrieval call binding the contract method 0x4f6ccce7.
//
// Solidity: function tokenByIndex(uint256 index) view returns(uint256)
func (_Contracts *ContractsCaller) TokenByIndex(opts *bind.CallOpts, index *big.Int) (*big.Int, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "tokenByIndex", index)
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
// TokenByIndex is a free data retrieval call binding the contract method 0x4f6ccce7.
//
// Solidity: function tokenByIndex(uint256 index) view returns(uint256)
func (_Contracts *ContractsSession) TokenByIndex(index *big.Int) (*big.Int, error) {
return _Contracts.Contract.TokenByIndex(&_Contracts.CallOpts, index)
}
// TokenByIndex is a free data retrieval call binding the contract method 0x4f6ccce7.
//
// Solidity: function tokenByIndex(uint256 index) view returns(uint256)
func (_Contracts *ContractsCallerSession) TokenByIndex(index *big.Int) (*big.Int, error) {
return _Contracts.Contract.TokenByIndex(&_Contracts.CallOpts, index)
}
// TokenIdsOf is a free data retrieval call binding the contract method 0xd028bd66.
//
// Solidity: function tokenIdsOf(string spaceMetadata) view returns(uint256[])
func (_Contracts *ContractsCaller) TokenIdsOf(opts *bind.CallOpts, spaceMetadata string) ([]*big.Int, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "tokenIdsOf", spaceMetadata)
if err != nil {
return *new([]*big.Int), err
}
out0 := *abi.ConvertType(out[0], new([]*big.Int)).(*[]*big.Int)
return out0, err
}
// TokenIdsOf is a free data retrieval call binding the contract method 0xd028bd66.
//
// Solidity: function tokenIdsOf(string spaceMetadata) view returns(uint256[])
func (_Contracts *ContractsSession) TokenIdsOf(spaceMetadata string) ([]*big.Int, error) {
return _Contracts.Contract.TokenIdsOf(&_Contracts.CallOpts, spaceMetadata)
}
// TokenIdsOf is a free data retrieval call binding the contract method 0xd028bd66.
//
// Solidity: function tokenIdsOf(string spaceMetadata) view returns(uint256[])
func (_Contracts *ContractsCallerSession) TokenIdsOf(spaceMetadata string) ([]*big.Int, error) {
return _Contracts.Contract.TokenIdsOf(&_Contracts.CallOpts, spaceMetadata)
}
// TokenOfOwnerByIndex is a free data retrieval call binding the contract method 0x2f745c59.
//
// Solidity: function tokenOfOwnerByIndex(address owner, uint256 index) view returns(uint256)
func (_Contracts *ContractsCaller) TokenOfOwnerByIndex(opts *bind.CallOpts, owner common.Address, index *big.Int) (*big.Int, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "tokenOfOwnerByIndex", owner, index)
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
// TokenOfOwnerByIndex is a free data retrieval call binding the contract method 0x2f745c59.
//
// Solidity: function tokenOfOwnerByIndex(address owner, uint256 index) view returns(uint256)
func (_Contracts *ContractsSession) TokenOfOwnerByIndex(owner common.Address, index *big.Int) (*big.Int, error) {
return _Contracts.Contract.TokenOfOwnerByIndex(&_Contracts.CallOpts, owner, index)
}
// TokenOfOwnerByIndex is a free data retrieval call binding the contract method 0x2f745c59.
//
// Solidity: function tokenOfOwnerByIndex(address owner, uint256 index) view returns(uint256)
func (_Contracts *ContractsCallerSession) TokenOfOwnerByIndex(owner common.Address, index *big.Int) (*big.Int, error) {
return _Contracts.Contract.TokenOfOwnerByIndex(&_Contracts.CallOpts, owner, index)
}
// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd.
//
// Solidity: function tokenURI(uint256 tokenId) view returns(string)
func (_Contracts *ContractsCaller) TokenURI(opts *bind.CallOpts, tokenId *big.Int) (string, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "tokenURI", tokenId)
if err != nil {
return *new(string), err
}
out0 := *abi.ConvertType(out[0], new(string)).(*string)
return out0, err
}
// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd.
//
// Solidity: function tokenURI(uint256 tokenId) view returns(string)
func (_Contracts *ContractsSession) TokenURI(tokenId *big.Int) (string, error) {
return _Contracts.Contract.TokenURI(&_Contracts.CallOpts, tokenId)
}
// TokenURI is a free data retrieval call binding the contract method 0xc87b56dd.
//
// Solidity: function tokenURI(uint256 tokenId) view returns(string)
func (_Contracts *ContractsCallerSession) TokenURI(tokenId *big.Int) (string, error) {
return _Contracts.Contract.TokenURI(&_Contracts.CallOpts, tokenId)
}
// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd.
//
// Solidity: function totalSupply() view returns(uint256)
func (_Contracts *ContractsCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "totalSupply")
if err != nil {
return *new(*big.Int), err
}
out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)
return out0, err
}
// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd.
//
// Solidity: function totalSupply() view returns(uint256)
func (_Contracts *ContractsSession) TotalSupply() (*big.Int, error) {
return _Contracts.Contract.TotalSupply(&_Contracts.CallOpts)
}
// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd.
//
// Solidity: function totalSupply() view returns(uint256)
func (_Contracts *ContractsCallerSession) TotalSupply() (*big.Int, error) {
return _Contracts.Contract.TotalSupply(&_Contracts.CallOpts)
}
// VaultAddress is a free data retrieval call binding the contract method 0x430bf08a.
//
// Solidity: function vaultAddress() view returns(address)
func (_Contracts *ContractsCaller) VaultAddress(opts *bind.CallOpts) (common.Address, error) {
var out []interface{}
err := _Contracts.contract.Call(opts, &out, "vaultAddress")
if err != nil {
return *new(common.Address), err
}
out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)
return out0, err
}
// VaultAddress is a free data retrieval call binding the contract method 0x430bf08a.
//
// Solidity: function vaultAddress() view returns(address)
func (_Contracts *ContractsSession) VaultAddress() (common.Address, error) {
return _Contracts.Contract.VaultAddress(&_Contracts.CallOpts)
}
// VaultAddress is a free data retrieval call binding the contract method 0x430bf08a.
//
// Solidity: function vaultAddress() view returns(address)
func (_Contracts *ContractsCallerSession) VaultAddress() (common.Address, error) {
return _Contracts.Contract.VaultAddress(&_Contracts.CallOpts)
}
// Accept is a paid mutator transaction binding the contract method 0x19b05f49.
//
// Solidity: function accept(uint256 tokenId) returns()
func (_Contracts *ContractsTransactor) Accept(opts *bind.TransactOpts, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "accept", tokenId)
}
// Accept is a paid mutator transaction binding the contract method 0x19b05f49.
//
// Solidity: function accept(uint256 tokenId) returns()
func (_Contracts *ContractsSession) Accept(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.Accept(&_Contracts.TransactOpts, tokenId)
}
// Accept is a paid mutator transaction binding the contract method 0x19b05f49.
//
// Solidity: function accept(uint256 tokenId) returns()
func (_Contracts *ContractsTransactorSession) Accept(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.Accept(&_Contracts.TransactOpts, tokenId)
}
// AcceptOffer is a paid mutator transaction binding the contract method 0x444115f6.
//
// Solidity: function acceptOffer(uint256 tokenId, string tokenMetadata) returns()
func (_Contracts *ContractsTransactor) AcceptOffer(opts *bind.TransactOpts, tokenId *big.Int, tokenMetadata string) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "acceptOffer", tokenId, tokenMetadata)
}
// AcceptOffer is a paid mutator transaction binding the contract method 0x444115f6.
//
// Solidity: function acceptOffer(uint256 tokenId, string tokenMetadata) returns()
func (_Contracts *ContractsSession) AcceptOffer(tokenId *big.Int, tokenMetadata string) (*types.Transaction, error) {
return _Contracts.Contract.AcceptOffer(&_Contracts.TransactOpts, tokenId, tokenMetadata)
}
// AcceptOffer is a paid mutator transaction binding the contract method 0x444115f6.
//
// Solidity: function acceptOffer(uint256 tokenId, string tokenMetadata) returns()
func (_Contracts *ContractsTransactorSession) AcceptOffer(tokenId *big.Int, tokenMetadata string) (*types.Transaction, error) {
return _Contracts.Contract.AcceptOffer(&_Contracts.TransactOpts, tokenId, tokenMetadata)
}
// Approve is a paid mutator transaction binding the contract method 0x095ea7b3.
//
// Solidity: function approve(address to, uint256 tokenId) returns()
func (_Contracts *ContractsTransactor) Approve(opts *bind.TransactOpts, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "approve", to, tokenId)
}
// Approve is a paid mutator transaction binding the contract method 0x095ea7b3.
//
// Solidity: function approve(address to, uint256 tokenId) returns()
func (_Contracts *ContractsSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.Approve(&_Contracts.TransactOpts, to, tokenId)
}
// Approve is a paid mutator transaction binding the contract method 0x095ea7b3.
//
// Solidity: function approve(address to, uint256 tokenId) returns()
func (_Contracts *ContractsTransactorSession) Approve(to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.Approve(&_Contracts.TransactOpts, to, tokenId)
}
// Bid1 is a paid mutator transaction binding the contract method 0x454a2ab3.
//
// Solidity: function bid(uint256 tokenId) payable returns()
func (_Contracts *ContractsTransactor) Bid1(opts *bind.TransactOpts, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "bid", tokenId)
}
// Bid1 is a paid mutator transaction binding the contract method 0x454a2ab3.
//
// Solidity: function bid(uint256 tokenId) payable returns()
func (_Contracts *ContractsSession) Bid1(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.Bid1(&_Contracts.TransactOpts, tokenId)
}
// Bid1 is a paid mutator transaction binding the contract method 0x454a2ab3.
//
// Solidity: function bid(uint256 tokenId) payable returns()
func (_Contracts *ContractsTransactorSession) Bid1(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.Bid1(&_Contracts.TransactOpts, tokenId)
}
// Buy is a paid mutator transaction binding the contract method 0xd96a094a.
//
// Solidity: function buy(uint256 tokenId) payable returns()
func (_Contracts *ContractsTransactor) Buy(opts *bind.TransactOpts, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "buy", tokenId)
}
// Buy is a paid mutator transaction binding the contract method 0xd96a094a.
//
// Solidity: function buy(uint256 tokenId) payable returns()
func (_Contracts *ContractsSession) Buy(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.Buy(&_Contracts.TransactOpts, tokenId)
}
// Buy is a paid mutator transaction binding the contract method 0xd96a094a.
//
// Solidity: function buy(uint256 tokenId) payable returns()
func (_Contracts *ContractsTransactorSession) Buy(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.Buy(&_Contracts.TransactOpts, tokenId)
}
// BuyBasedOnTime is a paid mutator transaction binding the contract method 0xd8680069.
//
// Solidity: function buyBasedOnTime(uint256 tokenId) payable returns()
func (_Contracts *ContractsTransactor) BuyBasedOnTime(opts *bind.TransactOpts, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "buyBasedOnTime", tokenId)
}
// BuyBasedOnTime is a paid mutator transaction binding the contract method 0xd8680069.
//
// Solidity: function buyBasedOnTime(uint256 tokenId) payable returns()
func (_Contracts *ContractsSession) BuyBasedOnTime(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.BuyBasedOnTime(&_Contracts.TransactOpts, tokenId)
}
// BuyBasedOnTime is a paid mutator transaction binding the contract method 0xd8680069.
//
// Solidity: function buyBasedOnTime(uint256 tokenId) payable returns()
func (_Contracts *ContractsTransactorSession) BuyBasedOnTime(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.BuyBasedOnTime(&_Contracts.TransactOpts, tokenId)
}
// DeletePeriod is a paid mutator transaction binding the contract method 0x4b455a51.
//
// Solidity: function deletePeriod(uint256 tokenId) returns()
func (_Contracts *ContractsTransactor) DeletePeriod(opts *bind.TransactOpts, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "deletePeriod", tokenId)
}
// DeletePeriod is a paid mutator transaction binding the contract method 0x4b455a51.
//
// Solidity: function deletePeriod(uint256 tokenId) returns()
func (_Contracts *ContractsSession) DeletePeriod(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.DeletePeriod(&_Contracts.TransactOpts, tokenId)
}
// DeletePeriod is a paid mutator transaction binding the contract method 0x4b455a51.
//
// Solidity: function deletePeriod(uint256 tokenId) returns()
func (_Contracts *ContractsTransactorSession) DeletePeriod(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.DeletePeriod(&_Contracts.TransactOpts, tokenId)
}
// Deny is a paid mutator transaction binding the contract method 0x7393f289.
//
// Solidity: function deny(uint256 tokenId, string reason) returns()
func (_Contracts *ContractsTransactor) Deny(opts *bind.TransactOpts, tokenId *big.Int, reason string) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "deny", tokenId, reason)
}
// Deny is a paid mutator transaction binding the contract method 0x7393f289.
//
// Solidity: function deny(uint256 tokenId, string reason) returns()
func (_Contracts *ContractsSession) Deny(tokenId *big.Int, reason string) (*types.Transaction, error) {
return _Contracts.Contract.Deny(&_Contracts.TransactOpts, tokenId, reason)
}
// Deny is a paid mutator transaction binding the contract method 0x7393f289.
//
// Solidity: function deny(uint256 tokenId, string reason) returns()
func (_Contracts *ContractsTransactorSession) Deny(tokenId *big.Int, reason string) (*types.Transaction, error) {
return _Contracts.Contract.Deny(&_Contracts.TransactOpts, tokenId, reason)
}
// Initialize is a paid mutator transaction binding the contract method 0x077f224a.
//
// Solidity: function initialize(string title, string baseURI, address nameRegistry) returns()
func (_Contracts *ContractsTransactor) Initialize(opts *bind.TransactOpts, title string, baseURI string, nameRegistry common.Address) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "initialize", title, baseURI, nameRegistry)
}
// Initialize is a paid mutator transaction binding the contract method 0x077f224a.
//
// Solidity: function initialize(string title, string baseURI, address nameRegistry) returns()
func (_Contracts *ContractsSession) Initialize(title string, baseURI string, nameRegistry common.Address) (*types.Transaction, error) {
return _Contracts.Contract.Initialize(&_Contracts.TransactOpts, title, baseURI, nameRegistry)
}
// Initialize is a paid mutator transaction binding the contract method 0x077f224a.
//
// Solidity: function initialize(string title, string baseURI, address nameRegistry) returns()
func (_Contracts *ContractsTransactorSession) Initialize(title string, baseURI string, nameRegistry common.Address) (*types.Transaction, error) {
return _Contracts.Contract.Initialize(&_Contracts.TransactOpts, title, baseURI, nameRegistry)
}
// NewPeriod is a paid mutator transaction binding the contract method 0x899c9989.
//
// Solidity: function newPeriod(string spaceMetadata, string tokenMetadata, uint256 saleEndTimestamp, uint256 displayStartTimestamp, uint256 displayEndTimestamp, uint8 pricing, uint256 minPrice) returns()
func (_Contracts *ContractsTransactor) NewPeriod(opts *bind.TransactOpts, spaceMetadata string, tokenMetadata string, saleEndTimestamp *big.Int, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int, pricing uint8, minPrice *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "newPeriod", spaceMetadata, tokenMetadata, saleEndTimestamp, displayStartTimestamp, displayEndTimestamp, pricing, minPrice)
}
// NewPeriod is a paid mutator transaction binding the contract method 0x899c9989.
//
// Solidity: function newPeriod(string spaceMetadata, string tokenMetadata, uint256 saleEndTimestamp, uint256 displayStartTimestamp, uint256 displayEndTimestamp, uint8 pricing, uint256 minPrice) returns()
func (_Contracts *ContractsSession) NewPeriod(spaceMetadata string, tokenMetadata string, saleEndTimestamp *big.Int, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int, pricing uint8, minPrice *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.NewPeriod(&_Contracts.TransactOpts, spaceMetadata, tokenMetadata, saleEndTimestamp, displayStartTimestamp, displayEndTimestamp, pricing, minPrice)
}
// NewPeriod is a paid mutator transaction binding the contract method 0x899c9989.
//
// Solidity: function newPeriod(string spaceMetadata, string tokenMetadata, uint256 saleEndTimestamp, uint256 displayStartTimestamp, uint256 displayEndTimestamp, uint8 pricing, uint256 minPrice) returns()
func (_Contracts *ContractsTransactorSession) NewPeriod(spaceMetadata string, tokenMetadata string, saleEndTimestamp *big.Int, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int, pricing uint8, minPrice *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.NewPeriod(&_Contracts.TransactOpts, spaceMetadata, tokenMetadata, saleEndTimestamp, displayStartTimestamp, displayEndTimestamp, pricing, minPrice)
}
// NewSpace is a paid mutator transaction binding the contract method 0x2bc4bc68.
//
// Solidity: function newSpace(string spaceMetadata) returns()
func (_Contracts *ContractsTransactor) NewSpace(opts *bind.TransactOpts, spaceMetadata string) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "newSpace", spaceMetadata)
}
// NewSpace is a paid mutator transaction binding the contract method 0x2bc4bc68.
//
// Solidity: function newSpace(string spaceMetadata) returns()
func (_Contracts *ContractsSession) NewSpace(spaceMetadata string) (*types.Transaction, error) {
return _Contracts.Contract.NewSpace(&_Contracts.TransactOpts, spaceMetadata)
}
// NewSpace is a paid mutator transaction binding the contract method 0x2bc4bc68.
//
// Solidity: function newSpace(string spaceMetadata) returns()
func (_Contracts *ContractsTransactorSession) NewSpace(spaceMetadata string) (*types.Transaction, error) {
return _Contracts.Contract.NewSpace(&_Contracts.TransactOpts, spaceMetadata)
}
// OfferPeriod is a paid mutator transaction binding the contract method 0x1daf7ff9.
//
// Solidity: function offerPeriod(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp) payable returns()
func (_Contracts *ContractsTransactor) OfferPeriod(opts *bind.TransactOpts, spaceMetadata string, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "offerPeriod", spaceMetadata, displayStartTimestamp, displayEndTimestamp)
}
// OfferPeriod is a paid mutator transaction binding the contract method 0x1daf7ff9.
//
// Solidity: function offerPeriod(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp) payable returns()
func (_Contracts *ContractsSession) OfferPeriod(spaceMetadata string, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.OfferPeriod(&_Contracts.TransactOpts, spaceMetadata, displayStartTimestamp, displayEndTimestamp)
}
// OfferPeriod is a paid mutator transaction binding the contract method 0x1daf7ff9.
//
// Solidity: function offerPeriod(string spaceMetadata, uint256 displayStartTimestamp, uint256 displayEndTimestamp) payable returns()
func (_Contracts *ContractsTransactorSession) OfferPeriod(spaceMetadata string, displayStartTimestamp *big.Int, displayEndTimestamp *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.OfferPeriod(&_Contracts.TransactOpts, spaceMetadata, displayStartTimestamp, displayEndTimestamp)
}
// Propose is a paid mutator transaction binding the contract method 0xd4f6b5ec.
//
// Solidity: function propose(uint256 tokenId, string metadata) returns()
func (_Contracts *ContractsTransactor) Propose(opts *bind.TransactOpts, tokenId *big.Int, metadata string) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "propose", tokenId, metadata)
}
// Propose is a paid mutator transaction binding the contract method 0xd4f6b5ec.
//
// Solidity: function propose(uint256 tokenId, string metadata) returns()
func (_Contracts *ContractsSession) Propose(tokenId *big.Int, metadata string) (*types.Transaction, error) {
return _Contracts.Contract.Propose(&_Contracts.TransactOpts, tokenId, metadata)
}
// Propose is a paid mutator transaction binding the contract method 0xd4f6b5ec.
//
// Solidity: function propose(uint256 tokenId, string metadata) returns()
func (_Contracts *ContractsTransactorSession) Propose(tokenId *big.Int, metadata string) (*types.Transaction, error) {
return _Contracts.Contract.Propose(&_Contracts.TransactOpts, tokenId, metadata)
}
// ReceiveToken is a paid mutator transaction binding the contract method 0x37df00c9.
//
// Solidity: function receiveToken(uint256 tokenId) payable returns()
func (_Contracts *ContractsTransactor) ReceiveToken(opts *bind.TransactOpts, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "receiveToken", tokenId)
}
// ReceiveToken is a paid mutator transaction binding the contract method 0x37df00c9.
//
// Solidity: function receiveToken(uint256 tokenId) payable returns()
func (_Contracts *ContractsSession) ReceiveToken(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.ReceiveToken(&_Contracts.TransactOpts, tokenId)
}
// ReceiveToken is a paid mutator transaction binding the contract method 0x37df00c9.
//
// Solidity: function receiveToken(uint256 tokenId) payable returns()
func (_Contracts *ContractsTransactorSession) ReceiveToken(tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.ReceiveToken(&_Contracts.TransactOpts, tokenId)
}
// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e.
//
// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "safeTransferFrom", from, to, tokenId)
}
// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e.
//
// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.SafeTransferFrom(&_Contracts.TransactOpts, from, to, tokenId)
}
// SafeTransferFrom is a paid mutator transaction binding the contract method 0x42842e0e.
//
// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.SafeTransferFrom(&_Contracts.TransactOpts, from, to, tokenId)
}
// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde.
//
// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns()
func (_Contracts *ContractsTransactor) SafeTransferFrom0(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "safeTransferFrom0", from, to, tokenId, _data)
}
// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde.
//
// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns()
func (_Contracts *ContractsSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {
return _Contracts.Contract.SafeTransferFrom0(&_Contracts.TransactOpts, from, to, tokenId, _data)
}
// SafeTransferFrom0 is a paid mutator transaction binding the contract method 0xb88d4fde.
//
// Solidity: function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) returns()
func (_Contracts *ContractsTransactorSession) SafeTransferFrom0(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {
return _Contracts.Contract.SafeTransferFrom0(&_Contracts.TransactOpts, from, to, tokenId, _data)
}
// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465.
//
// Solidity: function setApprovalForAll(address operator, bool approved) returns()
func (_Contracts *ContractsTransactor) SetApprovalForAll(opts *bind.TransactOpts, operator common.Address, approved bool) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "setApprovalForAll", operator, approved)
}
// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465.
//
// Solidity: function setApprovalForAll(address operator, bool approved) returns()
func (_Contracts *ContractsSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) {
return _Contracts.Contract.SetApprovalForAll(&_Contracts.TransactOpts, operator, approved)
}
// SetApprovalForAll is a paid mutator transaction binding the contract method 0xa22cb465.
//
// Solidity: function setApprovalForAll(address operator, bool approved) returns()
func (_Contracts *ContractsTransactorSession) SetApprovalForAll(operator common.Address, approved bool) (*types.Transaction, error) {
return _Contracts.Contract.SetApprovalForAll(&_Contracts.TransactOpts, operator, approved)
}
// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd.
//
// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsTransactor) TransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "transferFrom", from, to, tokenId)
}
// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd.
//
// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.TransferFrom(&_Contracts.TransactOpts, from, to, tokenId)
}
// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd.
//
// Solidity: function transferFrom(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsTransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.TransferFrom(&_Contracts.TransactOpts, from, to, tokenId)
}
// TransferToBundle is a paid mutator transaction binding the contract method 0xd1b900cd.
//
// Solidity: function transferToBundle(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsTransactor) TransferToBundle(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "transferToBundle", from, to, tokenId)
}
// TransferToBundle is a paid mutator transaction binding the contract method 0xd1b900cd.
//
// Solidity: function transferToBundle(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsSession) TransferToBundle(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.TransferToBundle(&_Contracts.TransactOpts, from, to, tokenId)
}
// TransferToBundle is a paid mutator transaction binding the contract method 0xd1b900cd.
//
// Solidity: function transferToBundle(address from, address to, uint256 tokenId) returns()
func (_Contracts *ContractsTransactorSession) TransferToBundle(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {
return _Contracts.Contract.TransferToBundle(&_Contracts.TransactOpts, from, to, tokenId)
}
// UpdateMedia is a paid mutator transaction binding the contract method 0x179bcff7.
//
// Solidity: function updateMedia(address newMediaEOA, string newMetadata) returns()
func (_Contracts *ContractsTransactor) UpdateMedia(opts *bind.TransactOpts, newMediaEOA common.Address, newMetadata string) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "updateMedia", newMediaEOA, newMetadata)
}
// UpdateMedia is a paid mutator transaction binding the contract method 0x179bcff7.
//
// Solidity: function updateMedia(address newMediaEOA, string newMetadata) returns()
func (_Contracts *ContractsSession) UpdateMedia(newMediaEOA common.Address, newMetadata string) (*types.Transaction, error) {
return _Contracts.Contract.UpdateMedia(&_Contracts.TransactOpts, newMediaEOA, newMetadata)
}
// UpdateMedia is a paid mutator transaction binding the contract method 0x179bcff7.
//
// Solidity: function updateMedia(address newMediaEOA, string newMetadata) returns()
func (_Contracts *ContractsTransactorSession) UpdateMedia(newMediaEOA common.Address, newMetadata string) (*types.Transaction, error) {
return _Contracts.Contract.UpdateMedia(&_Contracts.TransactOpts, newMediaEOA, newMetadata)
}
// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b.
//
// Solidity: function withdraw() returns()
func (_Contracts *ContractsTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) {
return _Contracts.contract.Transact(opts, "withdraw")
}
// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b.
//
// Solidity: function withdraw() returns()
func (_Contracts *ContractsSession) Withdraw() (*types.Transaction, error) {
return _Contracts.Contract.Withdraw(&_Contracts.TransactOpts)
}
// Withdraw is a paid mutator transaction binding the contract method 0x3ccfd60b.
//
// Solidity: function withdraw() returns()
func (_Contracts *ContractsTransactorSession) Withdraw() (*types.Transaction, error) {
return _Contracts.Contract.Withdraw(&_Contracts.TransactOpts)
}
// ContractsApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Contracts contract.
type ContractsApprovalIterator struct {
Event *ContractsApproval // Event containing the contract specifics and raw log
contract *bind.BoundContract // Generic contract to use for unpacking event data
event string // Event name to use for unpacking event data
logs chan types.Log // Log channel receiving the found contract events
sub ethereum.Subscription // Subscription for errors, completion and termination
done bool // Whether the subscription completed delivering logs
fail error // Occurred error to stop iteration
}
// Next advances the iterator to the subsequent event, returning whether there
// are any more events found. In case of a retrieval or parsing error, false is
// returned and Error() can be queried for the exact failure.
func (it *ContractsApprovalIterator) Next() bool {
// If the iterator failed, stop iterating
if it.fail != nil {
return false
}
// If the iterator completed, deliver directly whatever's available
if it.done {
select {
case log := <-it.logs:
it.Event = new(ContractsApproval)
if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil {
it.fail = err
return false
}
it.Event.Raw = log
return true
default:
return false
}
}
// Iterator still in progress, wait for either a data or an error event
select {
case log := <-it.logs:
it.Event = new(ContractsApproval)
if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil {
it.fail = err
return false
}
it.Event.Raw = log
return true
case err := <-it.sub.Err():
it.done = true
it.fail = err
return it.Next()
}
}
// Error returns any retrieval or parsing error occurred during filtering.
func (it *ContractsApprovalIterator) Error() error {
return it.fail
}
// Close terminates the iteration process, releasing any pending underlying
// resources.
func (it *ContractsApprovalIterator) Close() error {
it.sub.Unsubscribe()
return nil
}
// ContractsApproval represents a Approval event raised by the Contracts contract.
type ContractsApproval struct {
Owner common.Address
Approved common.Address
TokenId *big.Int
Raw types.Log // Blockchain specific contextual infos
}
// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925.
//
// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)
func (_Contracts *ContractsFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, approved []common.Address, tokenId []*big.Int) (*ContractsApprovalIterator, error) {
var ownerRule []interface{}
for _, ownerItem := range owner {
ownerRule = append(ownerRule, ownerItem)
}
var approvedRule []interface{}
for _, approvedItem := range approved {
approvedRule = append(approvedRule, approvedItem)
}
var tokenIdRule []interface{}
for _, tokenIdItem := range tokenId {
tokenIdRule = append(tokenIdRule, tokenIdItem)
}
logs, sub, err := _Contracts.contract.FilterLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule)
if err != nil {
return nil, err
}
return &ContractsApprovalIterator{contract: _Contracts.contract, event: "Approval", logs: logs, sub: sub}, nil
}
// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925.
//
// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)
func (_Contracts *ContractsFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *ContractsApproval, owner []common.Address, approved []common.Address, tokenId []*big.Int) (event.Subscription, error) {
var ownerRule []interface{}
for _, ownerItem := range owner {
ownerRule = append(ownerRule, ownerItem)
}
var approvedRule []interface{}
for _, approvedItem := range approved {
approvedRule = append(approvedRule, approvedItem)
}
var tokenIdRule []interface{}
for _, tokenIdItem := range tokenId {
tokenIdRule = append(tokenIdRule, tokenIdItem)
}
logs, sub, err := _Contracts.contract.WatchLogs(opts, "Approval", ownerRule, approvedRule, tokenIdRule)
if err != nil {
return nil, err
}
return event.NewSubscription(func(quit <-chan struct{}) error {
defer sub.Unsubscribe()
for {
select {
case log := <-logs:
// New log arrived, parse the event and forward to the user
event := new(ContractsApproval)
if err := _Contracts.contract.UnpackLog(event, "Approval", log); err != nil {
return err
}
event.Raw = log
select {
case sink <- event:
case err := <-sub.Err():
return err
case <-quit:
return nil
}
case err := <-sub.Err():
return err
case <-quit:
return nil
}
}
}), nil
}
// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925.
//
// Solidity: event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)
func (_Contracts *ContractsFilterer) ParseApproval(log types.Log) (*ContractsApproval, error) {
event := new(ContractsApproval)
if err := _Contracts.contract.UnpackLog(event, "Approval", log); err != nil {
return nil, err
}
event.Raw = log
return event, nil
}
// ContractsApprovalForAllIterator is returned from FilterApprovalForAll and is used to iterate over the raw logs and unpacked data for ApprovalForAll events raised by the Contracts contract.
type ContractsApprovalForAllIterator struct {
Event *ContractsApprovalForAll // Event containing the contract specifics and raw log
contract *bind.BoundContract // Generic contract to use for unpacking event data
event string // Event name to use for unpacking event data
logs chan types.Log // Log channel receiving the found contract events
sub ethereum.Subscription // Subscription for errors, completion and termination
done bool // Whether the subscription completed delivering logs
fail error // Occurred error to stop iteration
}
// Next advances the iterator to the subsequent event, returning whether there
// are any more events found. In case of a retrieval or parsing error, false is
// returned and Error() can be queried for the exact failure.
func (it *ContractsApprovalForAllIterator) Next() bool {
// If the iterator failed, stop iterating
if it.fail != nil {
return false
}
// If the iterator completed, deliver directly whatever's available
if it.done {
select {
case log := <-it.logs:
it.Event = new(ContractsApprovalForAll)
if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil {
it.fail = err
return false
}
it.Event.Raw = log
return true
default:
return false
}
}
// Iterator still in progress, wait for either a data or an error event
select {
case log := <-it.logs:
it.Event = new(ContractsApprovalForAll)
if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil {
it.fail = err
return false
}
it.Event.Raw = log
return true
case err := <-it.sub.Err():
it.done = true
it.fail = err
return it.Next()
}
}
// Error returns any retrieval or parsing error occurred during filtering.
func (it *ContractsApprovalForAllIterator) Error() error {
return it.fail
}
// Close terminates the iteration process, releasing any pending underlying
// resources.
func (it *ContractsApprovalForAllIterator) Close() error {
it.sub.Unsubscribe()
return nil
}
// ContractsApprovalForAll represents a ApprovalForAll event raised by the Contracts contract.
type ContractsApprovalForAll struct {
Owner common.Address
Operator common.Address
Approved bool
Raw types.Log // Blockchain specific contextual infos
}
// FilterApprovalForAll is a free log retrieval operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31.
//
// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved)
func (_Contracts *ContractsFilterer) FilterApprovalForAll(opts *bind.FilterOpts, owner []common.Address, operator []common.Address) (*ContractsApprovalForAllIterator, error) {
var ownerRule []interface{}
for _, ownerItem := range owner {
ownerRule = append(ownerRule, ownerItem)
}
var operatorRule []interface{}
for _, operatorItem := range operator {
operatorRule = append(operatorRule, operatorItem)
}
logs, sub, err := _Contracts.contract.FilterLogs(opts, "ApprovalForAll", ownerRule, operatorRule)
if err != nil {
return nil, err
}
return &ContractsApprovalForAllIterator{contract: _Contracts.contract, event: "ApprovalForAll", logs: logs, sub: sub}, nil
}
// WatchApprovalForAll is a free log subscription operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31.
//
// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved)
func (_Contracts *ContractsFilterer) WatchApprovalForAll(opts *bind.WatchOpts, sink chan<- *ContractsApprovalForAll, owner []common.Address, operator []common.Address) (event.Subscription, error) {
var ownerRule []interface{}
for _, ownerItem := range owner {
ownerRule = append(ownerRule, ownerItem)
}
var operatorRule []interface{}
for _, operatorItem := range operator {
operatorRule = append(operatorRule, operatorItem)
}
logs, sub, err := _Contracts.contract.WatchLogs(opts, "ApprovalForAll", ownerRule, operatorRule)
if err != nil {
return nil, err
}
return event.NewSubscription(func(quit <-chan struct{}) error {
defer sub.Unsubscribe()
for {
select {
case log := <-logs:
// New log arrived, parse the event and forward to the user
event := new(ContractsApprovalForAll)
if err := _Contracts.contract.UnpackLog(event, "ApprovalForAll", log); err != nil {
return err
}
event.Raw = log
select {
case sink <- event:
case err := <-sub.Err():
return err
case <-quit:
return nil
}
case err := <-sub.Err():
return err
case <-quit:
return nil
}
}
}), nil
}
// ParseApprovalForAll is a log parse operation binding the contract event 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31.
//
// Solidity: event ApprovalForAll(address indexed owner, address indexed operator, bool approved)
func (_Contracts *ContractsFilterer) ParseApprovalForAll(log types.Log) (*ContractsApprovalForAll, error) {
event := new(ContractsApprovalForAll)
if err := _Contracts.contract.UnpackLog(event, "ApprovalForAll", log); err != nil {
return nil, err
}
event.Raw = log
return event, nil
}
// ContractsTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Contracts contract.
type ContractsTransferIterator struct {
Event *ContractsTransfer // Event containing the contract specifics and raw log
contract *bind.BoundContract // Generic contract to use for unpacking event data
event string // Event name to use for unpacking event data
logs chan types.Log // Log channel receiving the found contract events
sub ethereum.Subscription // Subscription for errors, completion and termination
done bool // Whether the subscription completed delivering logs
fail error // Occurred error to stop iteration
}
// Next advances the iterator to the subsequent event, returning whether there
// are any more events found. In case of a retrieval or parsing error, false is
// returned and Error() can be queried for the exact failure.
func (it *ContractsTransferIterator) Next() bool {
// If the iterator failed, stop iterating
if it.fail != nil {
return false
}
// If the iterator completed, deliver directly whatever's available
if it.done {
select {
case log := <-it.logs:
it.Event = new(ContractsTransfer)
if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil {
it.fail = err
return false
}
it.Event.Raw = log
return true
default:
return false
}
}
// Iterator still in progress, wait for either a data or an error event
select {
case log := <-it.logs:
it.Event = new(ContractsTransfer)
if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil {
it.fail = err
return false
}
it.Event.Raw = log
return true
case err := <-it.sub.Err():
it.done = true
it.fail = err
return it.Next()
}
}
// Error returns any retrieval or parsing error occurred during filtering.
func (it *ContractsTransferIterator) Error() error {
return it.fail
}
// Close terminates the iteration process, releasing any pending underlying
// resources.
func (it *ContractsTransferIterator) Close() error {
it.sub.Unsubscribe()
return nil
}
// ContractsTransfer represents a Transfer event raised by the Contracts contract.
type ContractsTransfer struct {
From common.Address
To common.Address
TokenId *big.Int
Raw types.Log // Blockchain specific contextual infos
}
// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef.
//
// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)
func (_Contracts *ContractsFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address, tokenId []*big.Int) (*ContractsTransferIterator, error) {
var fromRule []interface{}
for _, fromItem := range from {
fromRule = append(fromRule, fromItem)
}
var toRule []interface{}
for _, toItem := range to {
toRule = append(toRule, toItem)
}
var tokenIdRule []interface{}
for _, tokenIdItem := range tokenId {
tokenIdRule = append(tokenIdRule, tokenIdItem)
}
logs, sub, err := _Contracts.contract.FilterLogs(opts, "Transfer", fromRule, toRule, tokenIdRule)
if err != nil {
return nil, err
}
return &ContractsTransferIterator{contract: _Contracts.contract, event: "Transfer", logs: logs, sub: sub}, nil
}
// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef.
//
// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)
func (_Contracts *ContractsFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *ContractsTransfer, from []common.Address, to []common.Address, tokenId []*big.Int) (event.Subscription, error) {
var fromRule []interface{}
for _, fromItem := range from {
fromRule = append(fromRule, fromItem)
}
var toRule []interface{}
for _, toItem := range to {
toRule = append(toRule, toItem)
}
var tokenIdRule []interface{}
for _, tokenIdItem := range tokenId {
tokenIdRule = append(tokenIdRule, tokenIdItem)
}
logs, sub, err := _Contracts.contract.WatchLogs(opts, "Transfer", fromRule, toRule, tokenIdRule)
if err != nil {
return nil, err
}
return event.NewSubscription(func(quit <-chan struct{}) error {
defer sub.Unsubscribe()
for {
select {
case log := <-logs:
// New log arrived, parse the event and forward to the user
event := new(ContractsTransfer)
if err := _Contracts.contract.UnpackLog(event, "Transfer", log); err != nil {
return err
}
event.Raw = log
select {
case sink <- event:
case err := <-sub.Err():
return err
case <-quit:
return nil
}
case err := <-sub.Err():
return err
case <-quit:
return nil
}
}
}), nil
}
// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef.
//
// Solidity: event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)
func (_Contracts *ContractsFilterer) ParseTransfer(log types.Log) (*ContractsTransfer, error) {
event := new(ContractsTransfer)
if err := _Contracts.contract.UnpackLog(event, "Transfer", log); err != nil {
return nil, err
}
event.Raw = log
return event, nil
}
| 47.757604 | 14,723 | 0.733779 |
40d105da2e3e3bd8f1cc56e9f22e7786f9b9cfa9 | 5,384 | html | HTML | pipermail/antlr-interest/2003-July/004505.html | hpcc-systems/website-antlr3 | aa6181595356409f8dc624e54715f56bd10707a8 | [
"BSD-3-Clause"
] | null | null | null | pipermail/antlr-interest/2003-July/004505.html | hpcc-systems/website-antlr3 | aa6181595356409f8dc624e54715f56bd10707a8 | [
"BSD-3-Clause"
] | null | null | null | pipermail/antlr-interest/2003-July/004505.html | hpcc-systems/website-antlr3 | aa6181595356409f8dc624e54715f56bd10707a8 | [
"BSD-3-Clause"
] | null | null | null | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE> [antlr-interest] GCJ
</TITLE>
<LINK REL="Index" HREF="index.html" >
<LINK REL="made" HREF="mailto:antlr-interest%40antlr.org?Subject=%5Bantlr-interest%5D%20GCJ&In-Reply-To=20030711160059.G20099%40cs.utwente.nl">
<META NAME="robots" CONTENT="index,nofollow">
<META http-equiv="Content-Type" content="text/html; charset=us-ascii">
<LINK REL="Previous" HREF="004502.html">
<LINK REL="Next" HREF="004508.html">
</HEAD>
<BODY BGCOLOR="#ffffff">
<H1>[antlr-interest] GCJ</H1>
<B>Robert Colquhoun</B>
<A HREF="mailto:antlr-interest%40antlr.org?Subject=%5Bantlr-interest%5D%20GCJ&In-Reply-To=20030711160059.G20099%40cs.utwente.nl"
TITLE="[antlr-interest] GCJ">rjc at trump.net.au
</A><BR>
<I>Sun Jul 13 19:19:32 PDT 2003</I>
<P><UL>
<LI>Previous message: <A HREF="004502.html">[antlr-interest] GCJ
</A></li>
<LI>Next message: <A HREF="004508.html">[antlr-interest] GCJ
</A></li>
<LI> <B>Messages sorted by:</B>
<a href="date.html#4505">[ date ]</a>
<a href="thread.html#4505">[ thread ]</a>
<a href="subject.html#4505">[ subject ]</a>
<a href="author.html#4505">[ author ]</a>
</LI>
</UL>
<HR>
<!--beginarticle-->
<PRE>Hello,
At 04:00 PM 11/07/2003 +0200, Ric Klaren wrote:
><i>Hi,
</I>><i>
</I>><i>On Fri, Jul 11, 2003 at 11:47:49PM +1000, Robert Colquhoun wrote:
</I>><i> > I need to fix the patch up first, gjc complained about some synchronization
</I>><i> > in the antlr.collections.impl classes, i went overboard and removed the
</I>><i> > Vector and Stack classes and replaced with java.util versions...
</I>><i>
</I>><i>Think those existed for some older java version not sure. But I still look
</I>><i>forward to a patch.
</I>
It builds with lots of warnings but i have put a simple(2 line) patch to
build with gcj at:
<A HREF="http://www.trump.net.au/~rjc/antlr/">http://www.trump.net.au/~rjc/antlr/</A>
From scratch:
wget <A HREF="http://www.antlr.org/download/antlr-2.7.2.tar.gz">http://www.antlr.org/download/antlr-2.7.2.tar.gz</A>
wget <A HREF="http://www.trump.net.au/~rjc/antlr/antlr-gcj.diff">http://www.trump.net.au/~rjc/antlr/antlr-gcj.diff</A>
tar xvfz antlr-2.7.2.tar.gz
cd antlr-2.7.2
patch -p1 < ../antlr-gcj.diff
find antlr -name '*.class' -exec rm {} \;
javac -classpath . antlr/build/*.java
javac -classpath . antlr/J*.java
java -classpath . antlr.build.Tool build
java -classpath . antlr.build.Tool jar
gcj -o antlr --main antlr.Tool antlr.jar
And there should be an executable called 'antlr' which runs antlr.Tool in
the current directory
><i>That's a stripped binary? If I make a redhat 9 rpm I hope it can use the
</I>><i>redhat installed gcj.so, probably it's also possible to compile it
</I>><i>staticaly (or only do gcj.so statically).
</I>
I am not sure but i think libgcj has a hidden bytecode interpreter
somewhere in the library for the dynamic java code generation and
loading...might not link statically very well without pulling in the whole
library.
><i> And what's 2.6 Mb nowadays ;)
</I>><i>Advantage of using gcj is that it comes default nowadays with most linux
</I>><i>distributions, this unlike java for which you have to dig around first.
</I>><i>Also no classpath trouble. No trouble in figuring out you'd have to run
</I>><i>antlr.Tool etc. It would also open the opportunity for distributions to
</I>><i>ship antlr with/in place of pccts.
</I>
I also looked at the 2.7.2 configure/make/make install system - that
appears to have got out of step with the java antlr.build system. For
instance antlr.jar is only the runtime if built with configure/make but is
the whole lot if done with antlr.build
Also java source files are kind of different from C/C++ there are no
includes(making for a much faster compile) and dependencies can be very
complicated it might be better if the configure/make system just compiles
everything from scratch. This would also get rid of the 300k java_deps
file reducing download size.
ie What is faster compiling 100k lines of java files or parsing a 300k text
file figuring dependencies and stat'ing all the java source files then
finally getting around to compiling the resulting set plus crossing fingers
that java_deps is up to date and the one line java change you just made
hasn't destroyed the dependency tree.
- Robert
Your use of Yahoo! Groups is subject to <A HREF="http://docs.yahoo.com/info/terms/">http://docs.yahoo.com/info/terms/</A>
</PRE>
<!--endarticle-->
<HR>
<P><UL>
<!--threads-->
<LI>Previous message: <A HREF="004502.html">[antlr-interest] GCJ
</A></li>
<LI>Next message: <A HREF="004508.html">[antlr-interest] GCJ
</A></li>
<LI> <B>Messages sorted by:</B>
<a href="date.html#4505">[ date ]</a>
<a href="thread.html#4505">[ thread ]</a>
<a href="subject.html#4505">[ subject ]</a>
<a href="author.html#4505">[ author ]</a>
</LI>
</UL>
<hr>
<a href="http://www.antlr.org/mailman/listinfo/antlr-interest">More information about the antlr-interest
mailing list</a><br>
</body></html>
| 41.099237 | 146 | 0.669948 |
127ae60a8af2cba736c79a18c3a3cd7a55b5671c | 17,486 | c | C | src/alg/grid/grid.c | bergolho1337/MonoPurkinje1D | da544a8338c44de941b04cc2c6caacb8bb954760 | [
"MIT"
] | null | null | null | src/alg/grid/grid.c | bergolho1337/MonoPurkinje1D | da544a8338c44de941b04cc2c6caacb8bb954760 | [
"MIT"
] | null | null | null | src/alg/grid/grid.c | bergolho1337/MonoPurkinje1D | da544a8338c44de941b04cc2c6caacb8bb954760 | [
"MIT"
] | null | null | null | //
// Created by sachetto on 29/09/17.
//
#include "grid.h"
#include <assert.h>
#include "inttypes.h"
struct grid* new_grid() {
struct grid* result = (struct grid*) malloc(sizeof(struct grid));
result->first_cell = NULL;
result->active_cells = NULL;
result->refined_this_step = NULL;
result->free_sv_positions = NULL;
sb_reserve(result->refined_this_step, 128);
sb_reserve(result->free_sv_positions, 128);
// Purkinje
result->the_purkinje_network = new_graph();
return result;
}
void initialize_and_construct_grid (struct grid *the_grid, double side_length) {
assert(the_grid);
initialize_grid (the_grid, side_length);
construct_grid (the_grid);
}
void initialize_grid (struct grid *the_grid, double side_length) {
assert(the_grid);
the_grid->side_length = side_length;
the_grid->number_of_cells = 0;
}
void construct_grid (struct grid *the_grid) {
assert(the_grid);
double side_length = the_grid->side_length;
// Cell nodes.
struct cell_node *front_northeast_cell, *front_northwest_cell, *front_southeast_cell, *front_southwest_cell,
*back_northeast_cell, *back_northwest_cell, *back_southeast_cell, *back_southwest_cell;
front_northeast_cell = new_cell_node ();
front_northwest_cell = new_cell_node ();
front_southeast_cell = new_cell_node ();
front_southwest_cell = new_cell_node ();
back_northeast_cell = new_cell_node ();
back_northwest_cell = new_cell_node ();
back_southeast_cell = new_cell_node ();
back_southwest_cell = new_cell_node ();
// Transition nodes.
struct transition_node *north_transition_node, *south_transition_node, *east_transition_node, *west_transition_node,
*front_transition_node, *back_transition_node;
north_transition_node = new_transition_node ();
south_transition_node = new_transition_node ();
east_transition_node = new_transition_node ();
west_transition_node = new_transition_node ();
front_transition_node = new_transition_node ();
back_transition_node = new_transition_node ();
double half_side_length = side_length / 2.0f;
double quarter_side_length = side_length / 4.0f;
//__________________________________________________________________________
// Initialization of transition nodes.
//__________________________________________________________________________
// East transition node.
set_transition_node_data (east_transition_node, 1, 'e', NULL, front_southeast_cell, back_southeast_cell,
back_northeast_cell, front_northeast_cell);
// North transition node.
set_transition_node_data (north_transition_node, 1, 'n', NULL, front_northwest_cell, front_northeast_cell,
back_northeast_cell, back_northwest_cell);
// West transition node.
set_transition_node_data (west_transition_node, 1, 'w', NULL, front_southwest_cell, back_southwest_cell,
back_northwest_cell, front_northwest_cell);
// South transition node.
set_transition_node_data (south_transition_node, 1, 's', NULL, front_southwest_cell, front_southeast_cell,
back_southeast_cell, back_southwest_cell);
// Front transition node.
set_transition_node_data (front_transition_node, 1, 'f', NULL, front_southwest_cell, front_southeast_cell,
front_northeast_cell, front_northwest_cell);
// Back transition node.
set_transition_node_data (back_transition_node, 1, 'b', NULL, back_southwest_cell, back_southeast_cell,
back_northeast_cell, back_northwest_cell);
//__________________________________________________________________________
// Initialization of cell nodes.
//__________________________________________________________________________
// front Northeast subcell initialization.
set_cell_node_data (front_northeast_cell, half_side_length, quarter_side_length, 1, east_transition_node,
north_transition_node, front_northwest_cell, front_southeast_cell, front_transition_node,
back_northeast_cell, NULL, back_northeast_cell, 0, 1, half_side_length + quarter_side_length,
half_side_length + quarter_side_length, half_side_length + quarter_side_length);
// back Northeast subcell initialization.
set_cell_node_data (back_northeast_cell, half_side_length, quarter_side_length, 2, east_transition_node,
north_transition_node, back_northwest_cell, back_southeast_cell, front_northeast_cell,
back_transition_node, front_northeast_cell, back_northwest_cell, 1, 2, quarter_side_length,
half_side_length + quarter_side_length, half_side_length + quarter_side_length);
// back Northwest subcell initialization.
set_cell_node_data (back_northwest_cell, half_side_length, quarter_side_length, 3, back_northeast_cell,
north_transition_node, west_transition_node, back_southwest_cell, front_northwest_cell,
back_transition_node, back_northeast_cell, front_northwest_cell, 2, 2, quarter_side_length,
quarter_side_length, half_side_length + quarter_side_length);
// front Northwest subcell initialization.
set_cell_node_data (front_northwest_cell, half_side_length, quarter_side_length, 4, front_northeast_cell,
north_transition_node, west_transition_node, front_southwest_cell, front_transition_node,
back_northwest_cell, back_northwest_cell, front_southwest_cell, 3, 3,
half_side_length + quarter_side_length, quarter_side_length,
half_side_length + quarter_side_length);
// front Southwest subcell initialization.
set_cell_node_data (front_southwest_cell, half_side_length, quarter_side_length, 5, front_southeast_cell,
front_northwest_cell, west_transition_node, south_transition_node, front_transition_node,
back_southwest_cell, front_northwest_cell, back_southwest_cell, 4, 3,
half_side_length + quarter_side_length, quarter_side_length, quarter_side_length);
// back Southwest subcell initialization.
set_cell_node_data (back_southwest_cell, half_side_length, quarter_side_length, 6, back_southeast_cell,
back_northwest_cell, west_transition_node, south_transition_node, front_southwest_cell,
back_transition_node, front_southwest_cell, back_southeast_cell, 5, 4, quarter_side_length,
quarter_side_length, quarter_side_length);
// back Southeast subcell initialization.
set_cell_node_data (back_southeast_cell, half_side_length, quarter_side_length, 7, east_transition_node,
back_northeast_cell, back_southwest_cell, south_transition_node, front_southeast_cell,
back_transition_node, back_southwest_cell, front_southeast_cell, 6, 4, quarter_side_length,
half_side_length + quarter_side_length, quarter_side_length);
// front Southeast subcell initialization.
set_cell_node_data (front_southeast_cell, half_side_length, quarter_side_length, 8, east_transition_node,
front_northeast_cell, front_southwest_cell, south_transition_node, front_transition_node,
back_southeast_cell, back_southeast_cell, NULL, 7, 5, half_side_length + quarter_side_length,
half_side_length + quarter_side_length, quarter_side_length);
// Grid initialization
the_grid->first_cell = front_northeast_cell;
the_grid->number_of_cells = 8;
}
void print_grid (struct grid *the_grid, FILE *output_file) {
struct cell_node *grid_cell = the_grid->first_cell;
double center_x, center_y, center_z, half_face;
double v;
while (grid_cell != 0) {
if (grid_cell->active) {
center_x = grid_cell->center_x;
center_y = grid_cell->center_y;
center_z = grid_cell->center_z;
v = grid_cell->v;
half_face = grid_cell->half_face_length;
fprintf (output_file, "%lf,%lf,%lf,%lf,%lf\n", center_x, center_y, center_z, half_face, v);
}
grid_cell = grid_cell->next;
}
}
bool print_grid_and_check_for_activity(const struct grid *the_grid, FILE *output_file, const int count, const bool binary) {
struct cell_node *grid_cell = the_grid->first_cell;
double center_x, center_y, center_z, half_face;
double v;
bool act = false;
while (grid_cell != 0) {
if (grid_cell->active) {
center_x = grid_cell->center_x;
center_y = grid_cell->center_y;
center_z = grid_cell->center_z;
v = grid_cell->v;
half_face = grid_cell->half_face_length;
if (count > 0) {
if (grid_cell->v > -86.0) {
act = true;
}
} else {
act = true;
}
if(binary) {
fwrite (¢er_x, sizeof(center_x), 1, output_file);
fwrite (¢er_y, sizeof(center_y), 1, output_file);
fwrite (¢er_z, sizeof(center_z), 1, output_file);
fwrite (&half_face, sizeof(half_face), 1, output_file);
fwrite (&v, sizeof(v), 1, output_file);
}
else {
fprintf(output_file, "%g,%g,%g,%g,%g\n", center_x, center_y, center_z, half_face, v);
}
}
grid_cell = grid_cell->next;
}
return act;
}
void print_grid_with_scar_info(struct grid *the_grid, FILE *output_file, bool binary) {
struct cell_node *grid_cell = the_grid->first_cell;
double center_x, center_y, center_z, half_face;
double v;
while (grid_cell != 0) {
v = -1.0;
if (grid_cell->active) {
center_x = grid_cell->center_x;
center_y = grid_cell->center_y;
center_z = grid_cell->center_z;
if(grid_cell->fibrotic)
v = 1.0;
else if(grid_cell->border_zone)
v = 2.0;
half_face = grid_cell->half_face_length;
if(binary) {
fwrite (¢er_x, sizeof(center_x), 1, output_file);
fwrite (¢er_y, sizeof(center_y), 1, output_file);
fwrite (¢er_z, sizeof(center_z), 1, output_file);
fwrite (&half_face, sizeof(half_face), 1, output_file);
fwrite (&v, sizeof(v), 1, output_file);
}
else {
fprintf (output_file, "%lf,%lf,%lf,%lf,%.4lf\n", center_x, center_y, center_z, half_face, v);
}
}
grid_cell = grid_cell->next;
}
}
void order_grid_cells (struct grid *the_grid) {
struct cell_node *grid_cell;
grid_cell = the_grid->first_cell;
//Here we allocate the maximum number of cells we will need for the whole simulation
if (the_grid->active_cells == NULL)
{
the_grid->active_cells = (struct cell_node **)malloc (sizeof (struct cell_node *) * the_grid->number_of_cells);
}
uint32_t counter = 0;
while (grid_cell != 0)
{
if (grid_cell->active)
{
grid_cell->grid_position = counter;
the_grid->active_cells[counter] = grid_cell;
counter++;
}
grid_cell = grid_cell->next;
}
the_grid->num_active_cells = counter;
}
void clean_grid (struct grid *the_grid)
{
assert(the_grid);
uint32_t number_of_cells = the_grid->number_of_cells;
struct cell_node *grid_cell = the_grid->first_cell;
// We will only delete the cells nodes in Purkinje case
if(grid_cell)
{
// Deleting cells nodes.
while (grid_cell)
{
struct cell_node *next = grid_cell->next;
free_cell_node(grid_cell);
grid_cell = next;
}
}
if (the_grid->the_purkinje_network)
{
free_graph(the_grid->the_purkinje_network);
}
if (the_grid->refined_this_step)
{
sb_clear(the_grid->refined_this_step);
}
if (the_grid->free_sv_positions)
{
sb_clear(the_grid->free_sv_positions);
}
}
void clean_and_free_grid(struct grid* the_grid) {
assert(the_grid);
clean_grid(the_grid);
if (the_grid->active_cells) {
free (the_grid->active_cells);
}
sb_free (the_grid->refined_this_step);
sb_free (the_grid->free_sv_positions);
free (the_grid);
}
// Prints grid discretization matrix.
void print_grid_matrix (struct grid *the_grid, FILE *output_file) {
assert(the_grid);
assert(output_file);
struct cell_node *grid_cell;
grid_cell = the_grid->first_cell;
struct element element;
struct element *cell_elements;
while (grid_cell != 0) {
if (grid_cell->active) {
cell_elements = grid_cell->elements;
size_t max_el = sb_count(cell_elements);
for(size_t i = 0; i < max_el; i++) {
element = cell_elements[i];
if(element.cell != NULL) {
fprintf(output_file, "%" PRIu32 " " "%" PRIu32 " %.15lf\n",
grid_cell->grid_position + 1,
(element.column) + 1,
element.value);
}
else {
break;
}
}
}
grid_cell = grid_cell->next;
}
}
void print_grid_vector(struct grid* the_grid, FILE *output_file, char name)
{
struct cell_node *grid_cell;
grid_cell = the_grid->first_cell;
while( grid_cell != 0 )
{
if( grid_cell->active )
{
if(name == 'b')
fprintf(output_file, "%.15lf\n", grid_cell->b);
else if (name == 'x')
fprintf(output_file, "%.15lf\n", grid_cell->v);
}
grid_cell = grid_cell->next;
}
}
double * grid_vector_to_array(struct grid *the_grid, char name, uint32_t *num_lines) {
struct cell_node *grid_cell;
grid_cell = the_grid->first_cell;
*num_lines = the_grid->num_active_cells;
double *vector = (double*) malloc(*num_lines*sizeof(double));
while( grid_cell != 0 )
{
if( grid_cell->active )
{
if(name == 'b')
vector[grid_cell->grid_position] = grid_cell->b;
else if (name == 'x')
vector[grid_cell->grid_position] = grid_cell->v;
}
grid_cell = grid_cell->next;
}
return vector;
}
void save_grid_domain (struct grid * the_grid, const char *file_name) {
struct cell_node *grid_cell = the_grid->first_cell;
FILE *f = fopen (file_name, "w");
while (grid_cell != 0) {
if (grid_cell->active) {
fprintf (f, "%lf,%lf,%lf,%lf\n", grid_cell->center_x, grid_cell->center_y,
grid_cell->center_z, grid_cell->half_face_length);
}
grid_cell = grid_cell->next;
}
fclose (f);
}
void initialize_grid_purkinje (struct grid *the_grid)
{
assert(the_grid);
the_grid->number_of_cells = 0;
}
void construct_grid_purkinje (struct grid *the_grid)
{
assert(the_grid);
double side_length = the_grid->the_purkinje_network->dx;
double half_side_length = side_length / 2.0f;
double quarter_side_length = side_length / 4.0f;
printf("Side length = %lf\n",side_length);
printf("Half_side length = %lf\n",half_side_length);
printf("Quarter_side length = %lf\n",quarter_side_length);
int total_nodes = the_grid->the_purkinje_network->total_nodes;
// Create an array of cell nodes
struct cell_node **cells = (struct cell_node**)malloc(sizeof(struct cell_node*)*total_nodes);
for (int i = 0; i < total_nodes; i++)
cells[i] = new_cell_node();
// Pass through the Purkinje graph and set the cell nodes.
struct node *n = the_grid->the_purkinje_network->list_nodes;
for (int i = 0; i < total_nodes; i++)
{
if (i == 0)
set_cell_node_data (cells[i],side_length,half_side_length,0,\
NULL,NULL,NULL,NULL,NULL,NULL,\
NULL,cells[i+1],i,0,\
n->x,n->y,n->z);
else if (i == total_nodes-1)
set_cell_node_data (cells[i],side_length,half_side_length,0,\
NULL,NULL,NULL,NULL,NULL,NULL,\
cells[i-1],NULL,i,0,\
n->x,n->y,n->z);
else
set_cell_node_data (cells[i],side_length,half_side_length,0,\
NULL,NULL,NULL,NULL,NULL,NULL,\
cells[i-1],cells[i+1],i,0,\
n->x,n->y,n->z);
// Do not refine the Purkinje cells !
cells[i]->can_change = false;
n = n->next;
}
// Grid initialization
the_grid->first_cell = cells[0];
the_grid->number_of_cells = total_nodes;
}
void initialize_and_construct_grid_purkinje (struct grid *the_grid)
{
assert(the_grid);
initialize_grid_purkinje(the_grid);
construct_grid_purkinje(the_grid);
} | 34.353635 | 124 | 0.636681 |
a9b99738dcaa4bee186a6a3d2fe75e79080459b1 | 2,001 | html | HTML | common/templates/accounts/registration_form.html | andyzsf/ConMan | e8d4aa9eeda7a85b39d8d897dbdba43de3cee9c1 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 7 | 2015-05-28T19:18:57.000Z | 2021-04-16T04:13:26.000Z | common/templates/accounts/registration_form.html | andyzsf/ConMan | e8d4aa9eeda7a85b39d8d897dbdba43de3cee9c1 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | common/templates/accounts/registration_form.html | andyzsf/ConMan | e8d4aa9eeda7a85b39d8d897dbdba43de3cee9c1 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 3 | 2018-11-05T09:33:45.000Z | 2022-02-18T14:27:22.000Z | {% extends "base_forms.html" %}
{% block title %}Sign up{% endblock %}
{% block primaryContent %}Sign up
<script type="text/javascript">
$(document).ready(function(){
$('#id_password1').pstrength();
$('#id_password2').pstrength();
});
</script>
{% block formsWrapper %}
{% if form.errors %}
<p class="error">Please correct the errors below:</p>
{% endif %}
<form method="post" action="">
<dl>
<dt><label for="id_username">Username:</label>{% if form.username.help_text %} (<font color="green"><i>{{ form.username.help_text }}</i></font>){% endif %}{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %} </dt>
<dd>{{ form.username }}</dd>
<dt><label for="id_email">Email address:</label>{% if form.email.help_text %} (<font color="green"><i>{{ form.email.help_text }}</i></font>){% endif %}{% if form.email.errors %} <span class="error">{{ form.email.errors|join:", " }}</span>{% endif %}</dd>
<dd>{{ form.email }}</dd>
<dt><label for="id_password1">Password:</label>{% if form.password1.help_text %} (<font color="green"><i>{{ form.password1.help_text }}</i></font>){% endif %}{% if form.password1.errors %} <span class="error">{{ form.password1.errors|join:", " }}</span>{% endif %}</dt>
<dd>{{ form.password1 }}</dd>
<dt><label for="id_password2">Password :</label>{% if form.password2.help_text %} (<font color="green"><i>{{ form.password2.help_text }}</i></font>){% endif %}{% if form.password2.errors %} <span class="error">{{ form.password2.errors|join:", " }}</span>{% endif %}</dt>
<dd>{{ form.password2 }}</dd>
<dt><label for="id_tos">I have read and agree to the <a href="/about/tos/">Terms of Service</a>:</label>{% if form.tos.help_text %} (<font color="green"><i>{{ form.tos.help_text }}</i></font>){% endif %}{% if form.tos.errors %} <span class="error">{{ form.tos.errors|join:", " }}</span>{% endif %} {{ form.tos }}
<dt><input type="submit" value="Register" /></dt>
</dl>
</form>
{% endblock %}
{% endblock %}
| 58.852941 | 328 | 0.628686 |
38a40b60affba95625420e5f6c7a25bec67727ec | 247 | h | C | Budget/RageIAPHelper.h | nspassov/budgetapp | 4c3cde185e2f1e04a3f7e0d6b25da6bf6929259d | [
"MIT"
] | 1 | 2021-07-02T19:06:17.000Z | 2021-07-02T19:06:17.000Z | Budget/RageIAPHelper.h | nspassov/budgetapp | 4c3cde185e2f1e04a3f7e0d6b25da6bf6929259d | [
"MIT"
] | null | null | null | Budget/RageIAPHelper.h | nspassov/budgetapp | 4c3cde185e2f1e04a3f7e0d6b25da6bf6929259d | [
"MIT"
] | null | null | null | //
// RageIAPHelper.h
// In App Rage
//
// Created by Ray Wenderlich on 9/5/12.
// Copyright (c) 2012 Razeware LLC. All rights reserved.
//
#import "IAPHelper.h"
@interface RageIAPHelper : IAPHelper
+ (RageIAPHelper *)sharedInstance;
@end
| 15.4375 | 57 | 0.688259 |
e95488f8f292202f0ffdc7495983c32c8d76d2d3 | 2,406 | go | Go | cmd/generate/generate_internal_test.go | gandarez/semver-action | b1588211654f16a6e55d534cc757b70fcc6bcb07 | [
"MIT"
] | 1 | 2021-09-22T20:38:19.000Z | 2021-09-22T20:38:19.000Z | cmd/generate/generate_internal_test.go | gandarez/semver-action | b1588211654f16a6e55d534cc757b70fcc6bcb07 | [
"MIT"
] | null | null | null | cmd/generate/generate_internal_test.go | gandarez/semver-action | b1588211654f16a6e55d534cc757b70fcc6bcb07 | [
"MIT"
] | 1 | 2021-02-22T00:34:10.000Z | 2021-02-22T00:34:10.000Z | package generate
import (
"testing"
"github.com/alecthomas/assert"
)
func TestDetermineBumpStrategy(t *testing.T) {
tests := map[string]struct {
SourceBranch string
DestBranch string
Bump string
ExpectedMethod string
ExpectedVersion string
}{
"source branch bugfix, dest branch develop and auto bump": {
SourceBranch: "bugfix/some",
DestBranch: "develop",
Bump: "auto",
ExpectedMethod: "build",
ExpectedVersion: "patch",
},
"source branch doc, dest branch develop and auto bump": {
SourceBranch: "doc/some",
DestBranch: "develop",
Bump: "auto",
ExpectedMethod: "build",
ExpectedVersion: "",
},
"source branch feature, dest branch develop and auto bump": {
SourceBranch: "feature/some",
DestBranch: "develop",
Bump: "auto",
ExpectedMethod: "build",
ExpectedVersion: "minor",
},
"source branch major, dest branch develop and auto bump": {
SourceBranch: "major/some",
DestBranch: "develop",
Bump: "auto",
ExpectedMethod: "build",
ExpectedVersion: "major",
},
"source branch misc, dest branch develop and auto bump": {
SourceBranch: "misc/some",
DestBranch: "develop",
Bump: "auto",
ExpectedMethod: "build",
ExpectedVersion: "",
},
"source branch hotfix, dest branch master and auto bump": {
SourceBranch: "hotfix/some",
DestBranch: "master",
Bump: "auto",
ExpectedMethod: "hotfix",
},
"source branch develop, dest branch master and auto bump": {
SourceBranch: "develop",
DestBranch: "master",
Bump: "auto",
ExpectedMethod: "final",
},
"not a valid source branch prefix and auto bump": {
SourceBranch: "some-branch",
Bump: "auto",
ExpectedMethod: "build",
},
"patch bump": {
Bump: "patch",
ExpectedMethod: "patch",
},
"minor bump": {
Bump: "minor",
ExpectedMethod: "minor",
},
"major bump": {
Bump: "major",
ExpectedMethod: "major",
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
method, version := determineBumpStrategy(test.Bump, test.SourceBranch, test.DestBranch, "master", "develop")
assert.Equal(t, test.ExpectedMethod, method)
assert.Equal(t, test.ExpectedVersion, version)
})
}
}
| 26.152174 | 111 | 0.604323 |
867571f9622562d0fb3e468d144cc144d9b13406 | 4,498 | rs | Rust | day15/src/main.rs | jstuczyn/AdventOfCode2021 | e7e94b8b31c47f3814760834284ade02cc07805d | [
"Apache-2.0"
] | null | null | null | day15/src/main.rs | jstuczyn/AdventOfCode2021 | e7e94b8b31c47f3814760834284ade02cc07805d | [
"Apache-2.0"
] | 6 | 2021-12-02T19:57:42.000Z | 2021-12-21T16:54:15.000Z | day15/src/main.rs | jstuczyn/AdventOfCode2021 | e7e94b8b31c47f3814760834284ade02cc07805d | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Jedrzej Stuczynski
//
// 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.
use pathfinding::prelude::dijkstra;
use std::ops::Index;
use std::str::FromStr;
use utils::execution::execute_struct;
use utils::input_read::read_parsed;
#[derive(Debug, Clone)]
struct RiskLevelMap {
rows: Vec<Vec<usize>>,
}
type Pos = (usize, usize);
impl FromStr for RiskLevelMap {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let rows: Vec<Vec<_>> = s
.lines()
.map(|row| {
row.chars()
.map(|char| char.to_digit(10).unwrap() as usize)
.collect()
})
.collect();
Ok(Self { rows })
}
}
impl Index<Pos> for RiskLevelMap {
type Output = usize;
fn index(&self, index: Pos) -> &Self::Output {
let (x, y) = index;
&self.rows[y][x]
}
}
impl RiskLevelMap {
fn lowest_risk_path_cost(&self) -> usize {
let start = (0usize, 0usize);
let end = (self.rows[0].len() - 1, self.rows.len() - 1);
let (_, cost) = dijkstra(&start, |pos| self.node_successors(pos), |&p| p == end).unwrap();
cost
}
fn node_successors(&self, node: &Pos) -> Vec<(Pos, usize)> {
let mut successors = Vec::new();
if node.0 > 0 {
let left = (node.0 - 1, node.1);
successors.push((left, self[left]))
}
if node.0 < self.rows[0].len() - 1 {
let right = (node.0 + 1, node.1);
successors.push((right, self[right]))
}
if node.1 > 0 {
let top = (node.0, node.1 - 1);
successors.push((top, self[top]))
}
if node.1 < self.rows.len() - 1 {
let bottom = (node.0, node.1 + 1);
successors.push((bottom, self[bottom]))
}
successors
}
fn map_value(i: usize, val: usize) -> usize {
if i == 0 {
val
} else {
let res = val + i;
if res > 9 {
res - 9
} else {
res
}
}
}
fn expand_row_five_folds(&mut self, row: usize) {
let old = std::mem::take(&mut self.rows[row]);
self.rows[row] = std::iter::repeat(old)
.take(5)
.enumerate()
.flat_map(|(i, vals)| vals.into_iter().map(move |v| Self::map_value(i, v)))
.collect::<Vec<_>>();
}
fn expand_columns_five_folds(&mut self) {
let rows = self.rows.clone();
for i in 1..=4 {
for row in rows.clone() {
let new_row = row
.clone()
.into_iter()
.map(|v| Self::map_value(i, v))
.collect();
self.rows.push(new_row);
}
}
}
fn expand_five_folds(&mut self) {
for i in 0..self.rows.len() {
self.expand_row_five_folds(i)
}
self.expand_columns_five_folds()
}
}
fn part1(risk_map: RiskLevelMap) -> usize {
risk_map.lowest_risk_path_cost()
}
fn part2(mut risk_map: RiskLevelMap) -> usize {
risk_map.expand_five_folds();
risk_map.lowest_risk_path_cost()
}
#[cfg(not(tarpaulin))]
fn main() {
execute_struct("input", read_parsed, part1, part2)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_sample_input() {
let input = "1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581"
.parse()
.unwrap();
let expected = 40;
assert_eq!(expected, part1(input))
}
#[test]
fn part2_sample_input() {
let input = "1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581"
.parse()
.unwrap();
let expected = 315;
assert_eq!(expected, part2(input))
}
}
| 23.925532 | 98 | 0.541129 |
7f8c4d0e6ee5d993aabcffb852edf240bb09a30a | 13,031 | rs | Rust | xtokens/src/mock.rs | jonathanxuu/open-runtime-module-library | 4a94fb75234a12d86f6cdd132d28b2939c208652 | [
"Apache-2.0"
] | null | null | null | xtokens/src/mock.rs | jonathanxuu/open-runtime-module-library | 4a94fb75234a12d86f6cdd132d28b2939c208652 | [
"Apache-2.0"
] | null | null | null | xtokens/src/mock.rs | jonathanxuu/open-runtime-module-library | 4a94fb75234a12d86f6cdd132d28b2939c208652 | [
"Apache-2.0"
] | null | null | null | #![cfg(test)]
use super::*;
use crate as orml_xtokens;
use frame_support::parameter_types;
use orml_traits::parameter_type_with_key;
use orml_xcm_support::{IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, XcmHandler as XcmHandlerT};
use polkadot_parachain::primitives::Sibling;
use serde::{Deserialize, Serialize};
use sp_io::TestExternalities;
use sp_runtime::AccountId32;
use xcm::v0::{Junction, MultiLocation::*, NetworkId};
use xcm_builder::{
AccountId32Aliases, LocationInverter, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,
SiblingParachainConvertsVia, SignedAccountId32AsNative, SovereignSignedViaLocation,
};
use xcm_executor::Config as XcmConfigT;
use xcm_simulator::{decl_test_network, decl_test_parachain, prelude::*};
pub const ALICE: AccountId32 = AccountId32::new([0u8; 32]);
pub const BOB: AccountId32 = AccountId32::new([1u8; 32]);
#[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum CurrencyId {
/// Relay chain token.
R,
/// Parachain A token.
A,
/// Parachain B token.
B,
}
pub struct CurrencyIdConvert;
impl Convert<CurrencyId, Option<MultiLocation>> for CurrencyIdConvert {
fn convert(id: CurrencyId) -> Option<MultiLocation> {
match id {
CurrencyId::R => Some(Junction::Parent.into()),
CurrencyId::A => Some(
(
Junction::Parent,
Junction::Parachain { id: 1 },
Junction::GeneralKey("A".into()),
)
.into(),
),
CurrencyId::B => Some(
(
Junction::Parent,
Junction::Parachain { id: 2 },
Junction::GeneralKey("B".into()),
)
.into(),
),
}
}
}
impl Convert<MultiLocation, Option<CurrencyId>> for CurrencyIdConvert {
fn convert(l: MultiLocation) -> Option<CurrencyId> {
let a: Vec<u8> = "A".into();
let b: Vec<u8> = "B".into();
match l {
X1(Parent) => Some(CurrencyId::R),
X3(Junction::Parent, Junction::Parachain { id: 1 }, Junction::GeneralKey(k)) if k == a => {
Some(CurrencyId::A)
}
X3(Junction::Parent, Junction::Parachain { id: 2 }, Junction::GeneralKey(k)) if k == b => {
Some(CurrencyId::B)
}
_ => None,
}
}
}
impl Convert<MultiAsset, Option<CurrencyId>> for CurrencyIdConvert {
fn convert(a: MultiAsset) -> Option<CurrencyId> {
if let MultiAsset::ConcreteFungible { id, amount: _ } = a {
Self::convert(id)
} else {
None
}
}
}
pub type Balance = u128;
pub type Amount = i128;
decl_test_parachain! {
pub struct ParaA {
new_ext = parachain_ext::<para_a::Runtime>(1),
para_id = 1,
}
pub mod para_a {
test_network = super::TestNetwork,
xcm_config = {
use super::*;
parameter_types! {
pub ParaANetwork: NetworkId = NetworkId::Any;
pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();
pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain {
id: ParachainInfo::get().into(),
});
pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R;
}
pub type LocationConverter = (
ParentIsDefault<AccountId>,
SiblingParachainConvertsVia<Sibling, AccountId>,
AccountId32Aliases<ParaANetwork, AccountId>,
);
pub type LocalAssetTransactor = MultiCurrencyAdapter<
Tokens,
(),
IsNativeConcrete<CurrencyId, CurrencyIdConvert>,
AccountId,
LocationConverter,
CurrencyId,
CurrencyIdConvert,
>;
pub type LocalOriginConverter = (
SovereignSignedViaLocation<LocationConverter, Origin>,
RelayChainAsNative<RelayChainOrigin, Origin>,
SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,
SignedAccountId32AsNative<ParaANetwork, Origin>,
);
pub struct XcmConfig;
impl XcmConfigT for XcmConfig {
type Call = Call;
type XcmSender = XcmHandler;
type AssetTransactor = LocalAssetTransactor;
type OriginConverter = LocalOriginConverter;
type IsReserve = MultiNativeAsset;
type IsTeleporter = ();
type LocationInverter = LocationInverter<Ancestry>;
}
},
extra_config = {
parameter_type_with_key! {
pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance {
Default::default()
};
}
impl orml_tokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
type Amount = Amount;
type CurrencyId = super::CurrencyId;
type WeightInfo = ();
type ExistentialDeposits = ExistentialDeposits;
type OnDust = ();
}
pub struct HandleXcm;
impl XcmHandlerT<AccountId> for HandleXcm {
fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult {
XcmHandler::execute_xcm(origin, xcm)
}
}
pub struct AccountId32Convert;
impl Convert<AccountId, [u8; 32]> for AccountId32Convert {
fn convert(account_id: AccountId) -> [u8; 32] {
account_id.into()
}
}
parameter_types! {
pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into();
}
impl orml_xtokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
type CurrencyId = CurrencyId;
type CurrencyIdConvert = CurrencyIdConvert;
type AccountId32Convert = AccountId32Convert;
type SelfLocation = SelfLocation;
type XcmHandler = HandleXcm;
}
},
extra_modules = {
Tokens: orml_tokens::{Pallet, Storage, Event<T>, Config<T>},
XTokens: orml_xtokens::{Pallet, Storage, Call, Event<T>},
},
}
}
decl_test_parachain! {
pub struct ParaB {
new_ext = parachain_ext::<para_b::Runtime>(2),
para_id = 2,
}
pub mod para_c {
test_network = super::TestNetwork,
xcm_config = {
use super::*;
parameter_types! {
pub ParaANetwork: NetworkId = NetworkId::Any;
pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();
pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain {
id: ParachainInfo::get().into(),
});
pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R;
}
pub type LocationConverter = (
ParentIsDefault<AccountId>,
SiblingParachainConvertsVia<Sibling, AccountId>,
AccountId32Aliases<ParaANetwork, AccountId>,
);
pub type LocalAssetTransactor = MultiCurrencyAdapter<
Tokens,
(),
IsNativeConcrete<CurrencyId, CurrencyIdConvert>,
AccountId,
LocationConverter,
CurrencyId,
CurrencyIdConvert,
>;
pub type LocalOriginConverter = (
SovereignSignedViaLocation<LocationConverter, Origin>,
RelayChainAsNative<RelayChainOrigin, Origin>,
SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,
SignedAccountId32AsNative<ParaANetwork, Origin>,
);
pub struct XcmConfig;
impl XcmConfigT for XcmConfig {
type Call = Call;
type XcmSender = XcmHandler;
type AssetTransactor = LocalAssetTransactor;
type OriginConverter = LocalOriginConverter;
type IsReserve = MultiNativeAsset;
type IsTeleporter = ();
type LocationInverter = LocationInverter<Ancestry>;
}
},
extra_config = {
parameter_type_with_key! {
pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance {
Default::default()
};
}
impl orml_tokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
type Amount = Amount;
type CurrencyId = super::CurrencyId;
type WeightInfo = ();
type ExistentialDeposits = ExistentialDeposits;
type OnDust = ();
}
pub struct HandleXcm;
impl XcmHandlerT<AccountId> for HandleXcm {
fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult {
XcmHandler::execute_xcm(origin, xcm)
}
}
pub struct AccountId32Convert;
impl Convert<AccountId, [u8; 32]> for AccountId32Convert {
fn convert(account_id: AccountId) -> [u8; 32] {
account_id.into()
}
}
parameter_types! {
pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into();
}
impl orml_xtokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
type CurrencyId = CurrencyId;
type CurrencyIdConvert = CurrencyIdConvert;
type AccountId32Convert = AccountId32Convert;
type SelfLocation = SelfLocation;
type XcmHandler = HandleXcm;
}
},
extra_modules = {
Tokens: orml_tokens::{Pallet, Storage, Event<T>, Config<T>},
XTokens: orml_xtokens::{Pallet, Storage, Call, Event<T>},
},
}
}
decl_test_parachain! {
pub struct ParaC {
new_ext = parachain_ext::<para_b::Runtime>(3),
para_id = 3,
}
pub mod para_b {
test_network = super::TestNetwork,
xcm_config = {
use super::*;
parameter_types! {
pub ParaANetwork: NetworkId = NetworkId::Any;
pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();
pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain {
id: ParachainInfo::get().into(),
});
pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R;
}
pub type LocationConverter = (
ParentIsDefault<AccountId>,
SiblingParachainConvertsVia<Sibling, AccountId>,
AccountId32Aliases<ParaANetwork, AccountId>,
);
pub type LocalAssetTransactor = MultiCurrencyAdapter<
Tokens,
(),
IsNativeConcrete<CurrencyId, CurrencyIdConvert>,
AccountId,
LocationConverter,
CurrencyId,
CurrencyIdConvert,
>;
pub type LocalOriginConverter = (
SovereignSignedViaLocation<LocationConverter, Origin>,
RelayChainAsNative<RelayChainOrigin, Origin>,
SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,
SignedAccountId32AsNative<ParaANetwork, Origin>,
);
pub struct XcmConfig;
impl XcmConfigT for XcmConfig {
type Call = Call;
type XcmSender = XcmHandler;
type AssetTransactor = LocalAssetTransactor;
type OriginConverter = LocalOriginConverter;
type IsReserve = MultiNativeAsset;
type IsTeleporter = ();
type LocationInverter = LocationInverter<Ancestry>;
}
},
extra_config = {
parameter_type_with_key! {
pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance {
Default::default()
};
}
impl orml_tokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
type Amount = Amount;
type CurrencyId = super::CurrencyId;
type WeightInfo = ();
type ExistentialDeposits = ExistentialDeposits;
type OnDust = ();
}
pub struct HandleXcm;
impl XcmHandlerT<AccountId> for HandleXcm {
fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult {
XcmHandler::execute_xcm(origin, xcm)
}
}
pub struct AccountId32Convert;
impl Convert<AccountId, [u8; 32]> for AccountId32Convert {
fn convert(account_id: AccountId) -> [u8; 32] {
account_id.into()
}
}
parameter_types! {
pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into();
}
impl orml_xtokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
type CurrencyId = CurrencyId;
type CurrencyIdConvert = CurrencyIdConvert;
type AccountId32Convert = AccountId32Convert;
type SelfLocation = SelfLocation;
type XcmHandler = HandleXcm;
}
},
extra_modules = {
Tokens: orml_tokens::{Pallet, Storage, Event<T>, Config<T>},
XTokens: orml_xtokens::{Pallet, Storage, Call, Event<T>},
},
}
}
decl_test_network! {
pub struct TestNetwork {
relay_chain = default,
parachains = vec![
(1, ParaA),
(2, ParaB),
(3, ParaC),
],
}
}
pub type ParaAXtokens = orml_xtokens::Pallet<para_a::Runtime>;
pub type ParaATokens = orml_tokens::Pallet<para_a::Runtime>;
pub type ParaBTokens = orml_tokens::Pallet<para_b::Runtime>;
pub type ParaCTokens = orml_tokens::Pallet<para_c::Runtime>;
pub type RelayBalances = pallet_balances::Pallet<relay::Runtime>;
pub struct ParaExtBuilder;
impl Default for ParaExtBuilder {
fn default() -> Self {
ParaExtBuilder
}
}
impl ParaExtBuilder {
pub fn build<
Runtime: frame_system::Config<AccountId = AccountId32> + orml_tokens::Config<CurrencyId = CurrencyId, Balance = Balance>,
>(
self,
para_id: u32,
) -> TestExternalities
where
<Runtime as frame_system::Config>::BlockNumber: From<u64>,
{
let mut t = frame_system::GenesisConfig::default()
.build_storage::<Runtime>()
.unwrap();
parachain_info::GenesisConfig {
parachain_id: para_id.into(),
}
.assimilate_storage(&mut t)
.unwrap();
orml_tokens::GenesisConfig::<Runtime> {
endowed_accounts: vec![(ALICE, CurrencyId::R, 100)],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = TestExternalities::new(t);
ext.execute_with(|| frame_system::Pallet::<Runtime>::set_block_number(1.into()));
ext
}
}
pub fn parachain_ext<
Runtime: frame_system::Config<AccountId = AccountId32> + orml_tokens::Config<CurrencyId = CurrencyId, Balance = Balance>,
>(
para_id: u32,
) -> TestExternalities
where
<Runtime as frame_system::Config>::BlockNumber: From<u64>,
{
ParaExtBuilder::default().build::<Runtime>(para_id)
}
| 27.666667 | 123 | 0.69327 |
68e382ea613928c890cc1c093eaf35542b124c76 | 291 | swift | Swift | Shared/SVGgh_TesterApp.swift | Kireyin/SVGgh | 41a5b031abaaf807fb5f3355a53071f4e2c50fbb | [
"MIT"
] | 133 | 2015-01-13T11:49:19.000Z | 2022-03-16T22:12:38.000Z | Shared/SVGgh_TesterApp.swift | Kireyin/SVGgh | 41a5b031abaaf807fb5f3355a53071f4e2c50fbb | [
"MIT"
] | 36 | 2015-01-27T15:09:53.000Z | 2021-03-23T02:10:46.000Z | Shared/SVGgh_TesterApp.swift | Kireyin/SVGgh | 41a5b031abaaf807fb5f3355a53071f4e2c50fbb | [
"MIT"
] | 48 | 2015-02-20T18:18:27.000Z | 2022-02-25T15:55:48.000Z | //
// SVGgh_TesterApp.swift
// Shared
//
// Created by Glenn Howes on 9/7/21.
// Copyright © 2021 Generally Helpful. All rights reserved.
//
import SwiftUI
@main
struct SVGgh_TesterApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 15.315789 | 60 | 0.604811 |
856135c49f67413f648c470b5e6107ee629b1569 | 2,331 | rs | Rust | src/sim.rs | nehalem501/ke04z4-pac | 79ef1fc566863207a20e2a8a937f4290792018c6 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | src/sim.rs | nehalem501/ke04z4-pac | 79ef1fc566863207a20e2a8a937f4290792018c6 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | src/sim.rs | nehalem501/ke04z4-pac | 79ef1fc566863207a20e2a8a937f4290792018c6 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | #[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - System Reset Status and ID Register"]
pub srsid: crate::Reg<srsid::SRSID_SPEC>,
#[doc = "0x04 - System Options Register"]
pub sopt: crate::Reg<sopt::SOPT_SPEC>,
#[doc = "0x08 - Pin Selection Register"]
pub pinsel: crate::Reg<pinsel::PINSEL_SPEC>,
#[doc = "0x0c - System Clock Gating Control Register"]
pub scgc: crate::Reg<scgc::SCGC_SPEC>,
#[doc = "0x10 - Universally Unique Identifier Low Register"]
pub uuidl: crate::Reg<uuidl::UUIDL_SPEC>,
#[doc = "0x14 - Universally Unique Identifier Middle Low Register"]
pub uuidml: crate::Reg<uuidml::UUIDML_SPEC>,
#[doc = "0x18 - Universally Unique Identifier Middle High Register"]
pub uuidmh: crate::Reg<uuidmh::UUIDMH_SPEC>,
#[doc = "0x1c - Clock Divider Register"]
pub clkdiv: crate::Reg<clkdiv::CLKDIV_SPEC>,
}
#[doc = "SRSID register accessor: an alias for `Reg<SRSID_SPEC>`"]
pub type SRSID = crate::Reg<srsid::SRSID_SPEC>;
#[doc = "System Reset Status and ID Register"]
pub mod srsid;
#[doc = "SOPT register accessor: an alias for `Reg<SOPT_SPEC>`"]
pub type SOPT = crate::Reg<sopt::SOPT_SPEC>;
#[doc = "System Options Register"]
pub mod sopt;
#[doc = "PINSEL register accessor: an alias for `Reg<PINSEL_SPEC>`"]
pub type PINSEL = crate::Reg<pinsel::PINSEL_SPEC>;
#[doc = "Pin Selection Register"]
pub mod pinsel;
#[doc = "SCGC register accessor: an alias for `Reg<SCGC_SPEC>`"]
pub type SCGC = crate::Reg<scgc::SCGC_SPEC>;
#[doc = "System Clock Gating Control Register"]
pub mod scgc;
#[doc = "UUIDL register accessor: an alias for `Reg<UUIDL_SPEC>`"]
pub type UUIDL = crate::Reg<uuidl::UUIDL_SPEC>;
#[doc = "Universally Unique Identifier Low Register"]
pub mod uuidl;
#[doc = "UUIDML register accessor: an alias for `Reg<UUIDML_SPEC>`"]
pub type UUIDML = crate::Reg<uuidml::UUIDML_SPEC>;
#[doc = "Universally Unique Identifier Middle Low Register"]
pub mod uuidml;
#[doc = "UUIDMH register accessor: an alias for `Reg<UUIDMH_SPEC>`"]
pub type UUIDMH = crate::Reg<uuidmh::UUIDMH_SPEC>;
#[doc = "Universally Unique Identifier Middle High Register"]
pub mod uuidmh;
#[doc = "CLKDIV register accessor: an alias for `Reg<CLKDIV_SPEC>`"]
pub type CLKDIV = crate::Reg<clkdiv::CLKDIV_SPEC>;
#[doc = "Clock Divider Register"]
pub mod clkdiv;
| 43.981132 | 72 | 0.700987 |
3d8bf421b9f2c88db36b566a71993e398f7f6d04 | 1,085 | rs | Rust | src/free/v1_53.rs | jhpratt/standback | 395e77837ad0c7763e9be1f0851cf13e570767fc | [
"Apache-2.0",
"MIT"
] | 17 | 2020-03-09T21:42:05.000Z | 2022-03-01T02:41:42.000Z | src/free/v1_53.rs | jhpratt/standback | 395e77837ad0c7763e9be1f0851cf13e570767fc | [
"Apache-2.0",
"MIT"
] | 11 | 2020-03-06T11:14:34.000Z | 2021-04-07T14:02:00.000Z | src/free/v1_53.rs | jhpratt/standback | 395e77837ad0c7763e9be1f0851cf13e570767fc | [
"Apache-2.0",
"MIT"
] | 6 | 2020-03-06T17:48:15.000Z | 2021-07-29T16:53:15.000Z | pub(crate) mod array {
pub fn from_ref<T>(s: &T) -> &[T; 1] {
unsafe { &*(s as *const T as *const [T; 1]) }
}
pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
unsafe { &mut *(s as *mut T as *mut [T; 1]) }
}
}
pub(crate) mod cmp {
use core::cmp::Ordering;
#[must_use]
pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
match compare(&v1, &v2) {
Ordering::Less | Ordering::Equal => v1,
Ordering::Greater => v2,
}
}
#[must_use]
pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
}
#[must_use]
pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
match compare(&v1, &v2) {
Ordering::Less | Ordering::Equal => v2,
Ordering::Greater => v1,
}
}
#[must_use]
pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
}
}
| 30.138889 | 84 | 0.463594 |
3be6620b5225fa1efc3c6a286568d9a227113682 | 594 | sql | SQL | compose/db/schema/mysql/20190427210922.namespace-tbl.up.sql | gil0109/corteza-server | 7b47ee0c9e72d06ca0264f2e77df365fef6f47d4 | [
"Apache-2.0"
] | null | null | null | compose/db/schema/mysql/20190427210922.namespace-tbl.up.sql | gil0109/corteza-server | 7b47ee0c9e72d06ca0264f2e77df365fef6f47d4 | [
"Apache-2.0"
] | null | null | null | compose/db/schema/mysql/20190427210922.namespace-tbl.up.sql | gil0109/corteza-server | 7b47ee0c9e72d06ca0264f2e77df365fef6f47d4 | [
"Apache-2.0"
] | null | null | null | CREATE TABLE `compose_namespace` (
`id` BIGINT(20) UNSIGNED NOT NULL,
`name` VARCHAR(64) NOT NULL COMMENT 'Name',
`slug` VARCHAR(64) NOT NULL COMMENT 'URL slug',
`enabled` BOOLEAN NOT NULL COMMENT 'Is namespace enabled?',
`meta` JSON NOT NULL COMMENT 'Meta data',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME DEFAULT NULL,
`deleted_at` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
| 39.6 | 76 | 0.577441 |
e993f0ff8e9cfceeb5d3ace7ec0d80f6c5650b4a | 16,841 | rs | Rust | src/lib.rs | MakotoE/rust-fahapi | 256095430dd395639bfbebc3e17a631da60ab2e3 | [
"MIT"
] | 1 | 2020-11-08T09:23:33.000Z | 2020-11-08T09:23:33.000Z | src/lib.rs | MakotoE/rust-fahapi | 256095430dd395639bfbebc3e17a631da60ab2e3 | [
"MIT"
] | 1 | 2021-11-13T15:05:27.000Z | 2021-11-13T16:50:38.000Z | src/lib.rs | MakotoE/rust-fahapi | 256095430dd395639bfbebc3e17a631da60ab2e3 | [
"MIT"
] | null | null | null | //! Folding@home client API wrapper for Rust. Use
//! [`API::connect_timeout()`](./struct.API.html#method.connect_timeout) to connect to your FAH
//! client.
//!
//! [rust-fahapi on Github](https://github.com/MakotoE/rust-fahapi)
mod connection;
mod types;
pub use connection::*;
pub use types::*;
pub use anyhow::{Error, Result};
use std::net;
lazy_static::lazy_static! {
/// Default TCP address of the FAH client.
pub static ref DEFAULT_ADDR: net::SocketAddr = {
net::SocketAddr::V4(net::SocketAddrV4::new(net::Ipv4Addr::LOCALHOST, 36330))
};
}
/// Wrapper for the FAH API. Use API::connect_timeout() to initialize.
///
/// Example
/// ```no_run
/// fn example() -> fahapi::Result<()> {
/// let mut api = fahapi::API::connect_timeout(&fahapi::DEFAULT_ADDR, std::time::Duration::from_secs(1))?;
/// api.pause_all()?;
/// api.unpause_all()
/// }
/// ```
#[derive(Debug)]
pub struct API {
pub conn: Connection,
pub buf: Vec<u8>,
}
impl API {
/// Connects to your FAH client with a timeout. `DEFAULT_ADDR` is the default address.
pub fn connect_timeout(addr: &net::SocketAddr, timeout: core::time::Duration) -> Result<API> {
Ok(API {
conn: Connection::connect_timeout(addr, timeout)?,
buf: Vec::new(),
})
}
/// Returns a listing of the FAH API commands.
pub fn help(&mut self) -> Result<String> {
self.conn.exec("help", &mut self.buf)?;
Ok(std::str::from_utf8(self.buf.as_slice())?.to_string())
}
/// Enables or disables log updates. Returns current log.
pub fn log_updates(&mut self, arg: LogUpdatesArg) -> Result<String> {
/*
This command is weird. It returns the log after the next prompt, like this:
> log-updates start
>
PyON 1 log-update...
*/
let command = format!("log-updates {}", arg);
self.conn.exec(command.as_str(), &mut self.buf)?;
self.conn.exec_eval("eval", &mut self.buf)?;
// The string contains a bunch of \x00 sequences that are not valid JSON and cannot be
// parsed using parse_pyon().
parse_log(std::str::from_utf8(&self.buf)?)
}
/// Unpauses all slots which are paused waiting for a screensaver and pause them again on
/// disconnect.
pub fn screensaver(&mut self) -> Result<()> {
self.conn.exec("screensaver", &mut self.buf)
}
/// Sets a slot to be always on.
pub fn always_on(&mut self, slot: i64) -> Result<()> {
let command = format!("always_on {}", slot);
self.conn.exec(command.as_str(), &mut self.buf)
}
/// Returns true if the client has set a user, team or passkey.
pub fn configured(&mut self) -> Result<bool> {
self.conn.exec("configured", &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
Ok(serde_json::from_str(pyon_to_json(&s)?.as_str())?)
}
/// Runs one client cycle.
pub fn do_cycle(&mut self) -> Result<()> {
self.conn.exec("do-cycle", &mut self.buf)
}
/// Pauses a slot when its current work unit is completed.
pub fn finish_slot(&mut self, slot: i64) -> Result<()> {
let command = format!("finish {}", slot);
self.conn.exec(command.as_str(), &mut self.buf)
}
/// Pauses all slots one-by-one when their current work unit is completed.
pub fn finish_all(&mut self) -> Result<()> {
self.conn.exec("finish", &mut self.buf)
}
/// Returns FAH build and machine info. See `info_struct()`.
pub fn info(&mut self) -> Result<Vec<Vec<serde_json::Value>>> {
self.conn.exec("info", &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
Ok(serde_json::from_str(pyon_to_json(s)?.as_str())?)
}
/// Converts Info() data into a structure. Consider this interface to be very unstable.
pub fn info_struct(&mut self) -> Result<Info> {
Info::new(self.info()?)
}
/// Returns the number of slots.
pub fn num_slots(&mut self) -> Result<i64> {
self.conn.exec("num-slots", &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
Ok(serde_json::from_str(pyon_to_json(s)?.as_str())?)
}
/// Sets a slot to run only when idle.
pub fn on_idle(&mut self, slot: i64) -> Result<()> {
let command = format!("on_idle {}", slot);
self.conn.exec(command.as_str(), &mut self.buf)
}
/// Sets all slots to run only when idle.
pub fn on_idle_all(&mut self) -> Result<()> {
self.conn.exec("on_idle", &mut self.buf)
}
/// Returns the FAH client options.
pub fn options_get(&mut self) -> Result<Options> {
self.conn.exec("options -a", &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
Ok(serde_json::from_str(pyon_to_json(s)?.as_str())?)
}
/// Sets an option.
pub fn options_set<N>(&mut self, key: &str, value: N) -> Result<()>
where
N: std::fmt::Display,
{
let value_str = format!("{}", value);
if key.contains(&['=', ' ', '!'] as &[char]) || value_str.contains(' ') {
return Err(Error::msg(format!(
"key or value contains bad character: {}={}",
key, value
)));
}
let command = format!("options {}={}", key, value_str);
self.conn.exec(command.as_str(), &mut self.buf)
}
/// Pauses all slots.
pub fn pause_all(&mut self) -> Result<()> {
self.conn.exec("pause", &mut self.buf)
}
/// Pauses a slot.
pub fn pause_slot(&mut self, slot: i64) -> Result<()> {
let command = format!("pause {}", slot);
self.conn.exec(command.as_str(), &mut self.buf)
}
// Returns the total estimated points per day.
pub fn ppd(&mut self) -> Result<f64> {
self.conn.exec("ppd", &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
Ok(serde_json::from_str(pyon_to_json(s)?.as_str())?)
}
/// Returns info about the current work unit.
pub fn queue_info(&mut self) -> Result<Vec<SlotQueueInfo>> {
self.conn.exec("queue-info", &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
let json = pyon_to_json(s)?;
serde_json::from_str(&json).map_err(|e| Error::new(e).context(json))
}
/// Requests an ID from the assignment server.
pub fn request_id(&mut self) -> Result<()> {
self.conn.exec("request-id", &mut self.buf)
}
/// Requests work server assignment from the assignment server.
pub fn request_ws(&mut self) -> Result<()> {
self.conn.exec("request-ws", &mut self.buf)
}
/// Ends all FAH processes.
pub fn shutdown(&mut self) -> Result<()> {
self.conn.exec("shutdown", &mut self.buf)
}
/// Returns the simulation information for a slot.
pub fn simulation_info(&mut self, slot: i64) -> Result<SimulationInfo> {
// "just like the simulations"
let command = format!("simulation-info {}", slot);
self.conn.exec(command.as_str(), &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
Ok(serde_json::from_str(pyon_to_json(s)?.as_str())?)
}
/// Deletes a slot.
pub fn slot_delete(&mut self, slot: i64) -> Result<()> {
let command = format!("slot-delete {}", slot);
self.conn.exec(command.as_str(), &mut self.buf)
}
/// Returns information about each slot.
pub fn slot_info(&mut self) -> Result<Vec<SlotInfo>> {
self.conn.exec("slot-info", &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
Ok(serde_json::from_str(pyon_to_json(s)?.as_str())?)
}
/// Returns slot options.
pub fn slot_options_get(&mut self, slot: i64) -> Result<SlotOptions> {
let command = format!("slot-options {} -a", slot);
self.conn.exec(command.as_str(), &mut self.buf)?;
let s = std::str::from_utf8(&self.buf)?;
Ok(serde_json::from_str(pyon_to_json(s)?.as_str())?)
}
/// Sets slot option.
pub fn slot_options_set<N>(&mut self, slot: i64, key: &str, value: N) -> Result<()>
where
N: std::fmt::Display,
{
let command = format!("slot-options {} {} {}", slot, key, value);
self.conn.exec(command.as_str(), &mut self.buf)
}
/// Unpauses all slots.
pub fn unpause_all(&mut self) -> Result<()> {
self.conn.exec("unpause", &mut self.buf)
}
/// Unpauses a slot.
pub fn unpause_slot(&mut self, slot: i64) -> Result<()> {
let command = format!("unpause {}", slot);
self.conn.exec(command.as_str(), &mut self.buf)
}
/// Returns FAH uptime.
pub fn uptime(&mut self) -> Result<FAHDuration> {
self.conn.exec_eval("uptime", &mut self.buf)?;
let duration = humantime::parse_duration(std::str::from_utf8(&self.buf)?)?;
Ok(chrono::Duration::from_std(duration)?.into())
}
/// Blocks until all slots are paused.
pub fn wait_for_units(&mut self) -> Result<()> {
self.conn.exec("wait-for-units", &mut self.buf)
}
}
#[derive(Debug, Copy, Clone)]
pub enum LogUpdatesArg {
Start,
Restart,
Stop,
}
impl std::fmt::Display for LogUpdatesArg {
fn fmt(&self, f: &mut std::fmt::Formatter) -> core::fmt::Result {
let s = match self {
LogUpdatesArg::Start => "start",
LogUpdatesArg::Restart => "restart",
LogUpdatesArg::Stop => "stop",
};
write!(f, "{}", s)
}
}
pub fn parse_log(s: &str) -> Result<String> {
// The log looks like this: PyON 1 log-update\n"..."\n---\n\n
const SUFFIX: &str = "\n---\n\n";
let mut removed_suffix = s;
if s.len() > SUFFIX.len() && s[s.len() - SUFFIX.len()..] == *SUFFIX {
removed_suffix = &s[..s.len() - SUFFIX.len()]
}
let start = match removed_suffix.find('\n') {
Some(i) => i + 1,
None => 0,
};
parse_pyon_string(&removed_suffix[start..])
}
pub fn parse_pyon_string(s: &str) -> Result<String> {
if s.len() < 2 || s.bytes().next().unwrap() != b'"' || s.bytes().nth_back(0).unwrap() != b'"' {
return Err(Error::msg(format!("cannot parse {}", s)));
}
lazy_static::lazy_static! {
static ref MATCH_ESCAPED: regex::Regex = regex::Regex::new(r#"\\x..|\\n|\\r|\\"|\\\\"#).unwrap();
}
let replace_fn: fn(®ex::Captures) -> String = |caps: ®ex::Captures| {
let capture = &caps[0];
if capture.bytes().next().unwrap() == b'\\' {
return match capture.bytes().nth(1).unwrap() {
b'n' => "\n".to_string(),
b'r' => "\r".to_string(),
b'"' => "\"".to_string(),
b'\\' => "\\".to_string(),
b'x' => {
let hex: String = capture.chars().skip(2).collect();
let n = match u32::from_str_radix(hex.as_str(), 16) {
Ok(n) => n,
Err(_) => return capture.to_string(),
};
match std::char::from_u32(n) {
Some(c) => c.to_string(),
None => capture.to_string(),
}
}
_ => capture.to_string(),
};
}
capture.to_string()
};
Ok((*MATCH_ESCAPED.replace_all(&s[1..s.len() - 1], replace_fn)).to_string())
}
pub fn pyon_to_json(s: &str) -> Result<String> {
// https://pypi.org/project/pon/
const PREFIX: &str = "PyON";
const SUFFIX: &str = "\n---";
if s.len() < PREFIX.len()
|| s.bytes().take(PREFIX.len()).ne(PREFIX.bytes())
|| s.len() < SUFFIX.len()
|| s.bytes().skip(s.len() - SUFFIX.len()).ne(SUFFIX.bytes())
{
return Err(Error::msg(format!("invalid PyON format: {}", s)));
}
let mut start = match s.find('\n') {
Some(i) => i + 1,
None => 0,
};
let end = s.len() - SUFFIX.len();
if start > end {
start = end;
}
Ok(match &s[start..end] {
"True" => "true".to_string(),
"False" => "false".to_string(),
_ => s[start..end]
.replace(": None", r#": """#)
.replace(": False", ": false")
.replace(": True", ": true"),
})
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[test]
fn test_parse_log() {
struct Test {
s: &'static str,
expected: &'static str,
expect_error: bool,
}
let tests = vec![
Test {
s: "",
expected: "",
expect_error: true,
},
Test {
s: r#"PyON 1 log-update"#,
expected: "",
expect_error: true,
},
Test {
s: r#""""#,
expected: "",
expect_error: false,
},
Test {
s: r#"\n---\n\n"#,
expected: "",
expect_error: true,
},
Test {
s: "\n\"\"\n---\n\n",
expected: "",
expect_error: false,
},
Test {
s: "PyON 1 log-update\n\n---\n\n",
expected: "",
expect_error: true,
},
Test {
s: "PyON 1 log-update\n\"a\"\n---\n\n",
expected: "a",
expect_error: false,
},
];
for (i, test) in tests.iter().enumerate() {
let result = parse_log(test.s);
assert_eq!(result.is_err(), test.expect_error, "{}", i);
if !test.expect_error {
assert_eq!(result.unwrap(), test.expected, "{}", i);
}
}
}
#[test]
fn test_parse_pyon_string() {
struct Test {
s: &'static str,
expected: &'static str,
expect_error: bool,
}
let tests = vec![
Test {
s: "",
expected: "",
expect_error: true,
},
Test {
s: r#""""#,
expected: "",
expect_error: false,
},
Test {
s: r#""\n\"\\\x01""#,
expected: "\n\"\\\x01",
expect_error: false,
},
Test {
s: r#""a\x01a""#,
expected: "a\x01a",
expect_error: false,
},
];
for (i, test) in tests.iter().enumerate() {
let result = parse_pyon_string(test.s);
assert_eq!(result.is_err(), test.expect_error, "{}", i);
if !test.expect_error {
assert_eq!(result.unwrap(), test.expected, "{}", i);
}
}
}
#[test]
fn test_pyon_to_json() {
struct Test {
s: &'static str,
expected: &'static str,
expect_error: bool,
}
let tests = vec![
Test {
s: "",
expected: "",
expect_error: true,
},
Test {
s: "PyON",
expected: "",
expect_error: true,
},
Test {
s: "PyON\n---",
expected: "",
expect_error: false,
},
Test {
s: "PyON\n\n---",
expected: "",
expect_error: false,
},
Test {
s: "PyON\n1\n---",
expected: "1",
expect_error: false,
},
Test {
s: "PyON\nTrue\n---",
expected: "true",
expect_error: false,
},
Test {
s: "PyON\n{\"\": None}\n---",
expected: "{\"\": \"\"}",
expect_error: false,
},
Test {
s: "\n}÷ ",
expected: "",
expect_error: true,
},
];
for (i, test) in tests.iter().enumerate() {
let result = pyon_to_json(test.s);
assert_eq!(result.is_err(), test.expect_error, "{}", i);
if !test.expect_error {
assert_eq!(result.unwrap(), test.expected, "{}", i);
}
}
}
}
bencher::benchmark_group!(benches, bench_pyon_to_json);
bencher::benchmark_main!(benches);
fn bench_pyon_to_json(b: &mut bencher::Bencher) {
// test bench_pyon_to_json ... bench: 33 ns/iter (+/- 1)
b.iter(|| pyon_to_json("PyON\nFalse\n---"))
}
#[cfg(test)]
mod integration_tests;
| 31.014733 | 110 | 0.50187 |
408ab99ef78089e5ce8a3fd8b3fdcc16b849a668 | 422 | py | Python | backend/app/api/__init__.py | fish2018/openpms | 88ca124ba0980aef5dd5474af03209f2dbefdcca | [
"Apache-2.0"
] | 40 | 2019-09-12T00:41:22.000Z | 2022-03-25T03:29:28.000Z | backend/app/api/__init__.py | fish2018/openpms | 88ca124ba0980aef5dd5474af03209f2dbefdcca | [
"Apache-2.0"
] | null | null | null | backend/app/api/__init__.py | fish2018/openpms | 88ca124ba0980aef5dd5474af03209f2dbefdcca | [
"Apache-2.0"
] | 14 | 2019-09-07T11:49:55.000Z | 2022-03-25T03:36:20.000Z | from flask_restplus import Api
authorizations = {
'apikey': {
'type': 'apiKey',
'in': 'header',
'name': 'X-Token'
}
}
api = Api(version='1.0', title='PMS API', description='PMS API', authorizations=authorizations)
api.namespaces.pop(0)
ns = api.namespace('v1', description='这是自定义名称空间')
from .user import UserView
from .pms import ResourceApi, GetUsers, GetPerms, GroupView, PermissionApi
| 26.375 | 95 | 0.670616 |
5da5b6341ddd9f08031a833b1504aa3b3fb0e62e | 1,858 | kt | Kotlin | app/src/main/java/in/dimigo/dimigoin/ui/main/fragment/timetable/TimetableFragment.kt | dimigoin/dimigoin-android-application | b89dbdb7f5a540d59a0b70bc91fb29eb7d6a9846 | [
"Apache-2.0"
] | 22 | 2020-06-30T15:11:53.000Z | 2022-01-29T15:50:49.000Z | app/src/main/java/in/dimigo/dimigoin/ui/main/fragment/timetable/TimetableFragment.kt | dimigoin/dimigoin-android-application | b89dbdb7f5a540d59a0b70bc91fb29eb7d6a9846 | [
"Apache-2.0"
] | 48 | 2020-03-22T06:49:07.000Z | 2021-12-30T06:04:12.000Z | app/src/main/java/in/dimigo/dimigoin/ui/main/fragment/timetable/TimetableFragment.kt | dimigoin/dimigoin-android-application | b89dbdb7f5a540d59a0b70bc91fb29eb7d6a9846 | [
"Apache-2.0"
] | 4 | 2020-07-03T02:08:01.000Z | 2021-04-01T08:18:32.000Z | package `in`.dimigo.dimigoin.ui.main.fragment.timetable
import `in`.dimigo.dimigoin.R
import `in`.dimigo.dimigoin.databinding.FragmentTimetableBinding
import `in`.dimigo.dimigoin.ui.BaseFragment
import `in`.dimigo.dimigoin.ui.custom.DimigoinDialog
import `in`.dimigo.dimigoin.ui.util.DateChangedLiveData
import `in`.dimigo.dimigoin.ui.util.sharedGraphViewModel
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import java.text.DateFormatSymbols
import java.util.*
class TimetableFragment : BaseFragment<FragmentTimetableBinding>(R.layout.fragment_timetable) {
private val viewModel: TimetableViewModel by sharedGraphViewModel(R.id.main_nav_graph)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
val dateChangedLiveData = DateChangedLiveData(requireContext())
val adapter = TimetableRecyclerViewAdapter(dateChangedLiveData)
val dateFormatSymbols = DateFormatSymbols(Locale.getDefault())
binding.apply {
lifecycleOwner = viewLifecycleOwner
vm = viewModel
user = userData
shortWeekDays = dateFormatSymbols.shortWeekdays.toList()
date = dateChangedLiveData
recyclerView.adapter = adapter
}
viewModel.timetable.observe(viewLifecycleOwner) {
adapter.updateItems(it)
}
dateChangedLiveData.observe(viewLifecycleOwner) {
adapter.updateItems()
}
viewModel.timetableFetchFailedEvent.observe(viewLifecycleOwner) {
DimigoinDialog(requireContext()).alert(DimigoinDialog.AlertType.ERROR, R.string.failed_to_fetch_timetable)
}
return binding.root
}
}
| 37.16 | 118 | 0.73789 |
349d8f2391921db0a18c2d41f7dbddaa9aa172d4 | 8,598 | sql | SQL | db_file/data_prepare/database_distribusi_v4.sql | hasanah150999/distribusi_gas-master | 7c2d7c16def5df1dcfbcb4aa6502c9e63a7a8430 | [
"MIT"
] | null | null | null | db_file/data_prepare/database_distribusi_v4.sql | hasanah150999/distribusi_gas-master | 7c2d7c16def5df1dcfbcb4aa6502c9e63a7a8430 | [
"MIT"
] | null | null | null | db_file/data_prepare/database_distribusi_v4.sql | hasanah150999/distribusi_gas-master | 7c2d7c16def5df1dcfbcb4aa6502c9e63a7a8430 | [
"MIT"
] | null | null | null | -- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 10.4.11-MariaDB - mariadb.org binary distribution
-- Server OS: Win64
-- HeidiSQL Version: 11.2.0.6213
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!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 structure for table db_distribusi.ci_sessions
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(250) NOT NULL,
`ip_address` varchar(50) NOT NULL,
`timestamp` int(11) DEFAULT NULL,
`data` blob NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for function db_distribusi.func_rfid
DELIMITER //
CREATE FUNCTION `func_rfid`(`data_alat` BIGINT
) RETURNS varchar(250) CHARSET utf8mb4
BEGIN
-- Deklarasi Variabel
DECLARE message VARCHAR(100);
DECLARE nama VARCHAR(150);
DECLARE jenis CHAR(1);
-- If agen
IF(data_alat IN(SELECT pel.data_rfid FROM tb_pelanggan pel WHERE pel.data_rfid = data_alat))
THEN
INSERT INTO `db_distribusi`.`tb_log_device` (`data_rfid`, `jenis_rfid`, `create_date`, `change_date`)
VALUES (data_alat, 'P', CURRENT_TIME(), CURRENT_TIME());
SELECT pel.nama INTO nama FROM tb_pelanggan pel WHERE pel.data_rfid = data_alat LIMIT 1;
SET message = 'Tapping Kartu: ';
-- else if masyarakat
ELSEIF(data_alat IN(SELECT ag.data_rfid FROM tb_agen ag WHERE ag.data_rfid = data_alat))
THEN
INSERT INTO `db_distribusi`.`tb_log_device` (`data_rfid`, `jenis_rfid`, `create_date`, `change_date`)
VALUES (data_alat, 'A', CURRENT_TIME(), CURRENT_TIME());
SELECT ag.nama INTO nama FROM tb_agen ag WHERE ag.data_rfid = data_alat LIMIT 1;
SET message = 'Tapping Kartu: ';
ELSE
INSERT INTO `db_distribusi`.`tb_log_device` (`data_rfid`, `jenis_rfid`, `create_date`, `change_date`)
VALUES (data_alat, 'N', CURRENT_TIME(), CURRENT_TIME());
SET message = 'Tapping Kartu ';
SET nama = 'Data Baru';
END IF;
RETURN CONCAT(message, nama);
END//
DELIMITER ;
-- Dumping structure for function db_distribusi.func_temp_rfid
DELIMITER //
CREATE FUNCTION `func_temp_rfid`(`data_alat` BIGINT
) RETURNS tinytext CHARSET utf8mb4
BEGIN
INSERT INTO `db_distribusi`.tb_temp_rfid (`data_rfid`, `create_date`)
VALUES (data_alat, CURRENT_TIME());
RETURN '';
END//
DELIMITER ;
-- Dumping structure for table db_distribusi.tb_agen
CREATE TABLE IF NOT EXISTS `tb_agen` (
`id_agen` int(11) NOT NULL AUTO_INCREMENT,
`nama` varchar(50) NOT NULL,
`alamat` text NOT NULL,
`no_reg` int(10) NOT NULL,
`data_rfid` bigint(20) NOT NULL,
`no_telepon` varchar(50) DEFAULT NULL,
`jumlah_pelanggan` bigint(20) NOT NULL DEFAULT 0,
`jumlah_tabung` bigint(20) NOT NULL DEFAULT 0,
`photo` varchar(250) DEFAULT NULL,
`jenis` char(1) NOT NULL DEFAULT 'A',
`create_date` datetime NOT NULL,
`change_date` datetime NOT NULL,
PRIMARY KEY (`id_agen`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_distribusi_agen
CREATE TABLE IF NOT EXISTS `tb_distribusi_agen` (
`id_distribusi_agen` int(11) NOT NULL AUTO_INCREMENT,
`id_agen` int(11) NOT NULL,
`jumlah_tabung` bigint(20) NOT NULL,
`tanggal_pengambilan` datetime NOT NULL,
`status_pengambilan` varchar(50) NOT NULL,
`create_date` datetime NOT NULL,
`change_date` datetime NOT NULL,
PRIMARY KEY (`id_distribusi_agen`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_distribusi_masyarakat
CREATE TABLE IF NOT EXISTS `tb_distribusi_masyarakat` (
`id_distribusi_masyarakat` int(11) NOT NULL AUTO_INCREMENT,
`id_pelanggan` int(11) NOT NULL,
`id_agen` int(11) NOT NULL,
`jumlah_tabung` bigint(20) NOT NULL,
`status_pembelian` varchar(50) NOT NULL DEFAULT '0',
`tanggal_pembelian` datetime NOT NULL,
`create_date` datetime NOT NULL,
`change_date` datetime NOT NULL,
PRIMARY KEY (`id_distribusi_masyarakat`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_jenis
CREATE TABLE IF NOT EXISTS `tb_jenis` (
`id_jenis` int(11) NOT NULL,
`nama` tinytext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_kabupaten
CREATE TABLE IF NOT EXISTS `tb_kabupaten` (
`id_kab` char(4) NOT NULL,
`id_prov` char(2) NOT NULL,
`nama` tinytext NOT NULL,
`id_jenis` int(11) NOT NULL,
PRIMARY KEY (`id_kab`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_kecamatan
CREATE TABLE IF NOT EXISTS `tb_kecamatan` (
`id_kec` char(6) NOT NULL,
`id_kab` char(4) NOT NULL,
`nama` tinytext NOT NULL,
PRIMARY KEY (`id_kec`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_kelurahan
CREATE TABLE IF NOT EXISTS `tb_kelurahan` (
`id_kel` char(10) NOT NULL,
`id_kec` char(6) DEFAULT NULL,
`nama` tinytext DEFAULT NULL,
`id_jenis` int(11) NOT NULL,
PRIMARY KEY (`id_kel`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_log_device
CREATE TABLE IF NOT EXISTS `tb_log_device` (
`id_log` int(10) unsigned NOT NULL AUTO_INCREMENT,
`data_rfid` bigint(20) NOT NULL DEFAULT 0,
`jenis_rfid` enum('A','P','N') NOT NULL,
`create_date` datetime NOT NULL,
`change_date` datetime NOT NULL,
PRIMARY KEY (`id_log`)
) ENGINE=InnoDB AUTO_INCREMENT=88 DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_pelanggan
CREATE TABLE IF NOT EXISTS `tb_pelanggan` (
`id_pelanggan` int(11) NOT NULL AUTO_INCREMENT,
`nama` varchar(50) NOT NULL,
`alamat` text NOT NULL,
`nik` varchar(50) NOT NULL,
`rt` varchar(5) DEFAULT NULL,
`rw` varchar(5) DEFAULT NULL,
`kelurahan` text DEFAULT NULL,
`kecamatan` text DEFAULT NULL,
`kab_kota` text DEFAULT NULL,
`provinsi` text DEFAULT NULL,
`data_rfid` bigint(20) NOT NULL,
`jenis` char(1) NOT NULL DEFAULT 'P',
`create_date` datetime NOT NULL,
`change_date` datetime NOT NULL,
PRIMARY KEY (`id_pelanggan`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_pengguna
CREATE TABLE IF NOT EXISTS `tb_pengguna` (
`id_pengguna` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(25) NOT NULL,
`password` varchar(50) NOT NULL,
`status` varchar(10) NOT NULL,
`priviledge_id` int(11) NOT NULL,
`email` varchar(50) NOT NULL,
`profile_id` int(11) DEFAULT NULL,
`create_date` datetime NOT NULL,
`change_date` datetime NOT NULL,
PRIMARY KEY (`id_pengguna`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_priviledge
CREATE TABLE IF NOT EXISTS `tb_priviledge` (
`priviledge_id` int(11) NOT NULL AUTO_INCREMENT,
`priviledge_name` varchar(50) NOT NULL,
`status` enum('A','D') NOT NULL,
`create_date` datetime NOT NULL,
`change_date` datetime NOT NULL,
PRIMARY KEY (`priviledge_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_provinsi
CREATE TABLE IF NOT EXISTS `tb_provinsi` (
`id_prov` char(2) NOT NULL,
`nama` tinytext NOT NULL,
PRIMARY KEY (`id_prov`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
-- Dumping structure for table db_distribusi.tb_temp_rfid
CREATE TABLE IF NOT EXISTS `tb_temp_rfid` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`data_rfid` bigint(20) NOT NULL DEFAULT 0,
`create_date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8mb4;
-- Data exporting was unselected.
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;
| 34.53012 | 105 | 0.724122 |
c04f8f704910b214470d4f3d37a910d4f0afba54 | 1,609 | lua | Lua | src/common/AssetCatagories.lua | Nimblz/eg-legacy | 60e2c6381ec58011378708246cf12a8608a60068 | [
"MIT"
] | 6 | 2020-06-19T15:19:02.000Z | 2022-01-03T13:01:16.000Z | src/common/AssetCatagories.lua | Nimblz/eg-legacy | 60e2c6381ec58011378708246cf12a8608a60068 | [
"MIT"
] | 3 | 2019-04-02T04:49:03.000Z | 2019-06-15T10:15:41.000Z | src/common/AssetCatagories.lua | Nimblz/eg | 60e2c6381ec58011378708246cf12a8608a60068 | [
"MIT"
] | 2 | 2020-05-19T07:23:11.000Z | 2020-06-19T15:19:07.000Z | local ReplicatedStorage = game:GetService("ReplicatedStorage")
local common = ReplicatedStorage:WaitForChild("common")
local EquipmentRenderers = require(common:WaitForChild("EquipmentRenderers"))
local by = require(script.Parent.util:WaitForChild("by"))
local catagories = {
{
id = "hat",
image = "rbxassetid://3185662736", -- image used to represent this catagory
name = "Hat",
maxEquipped = 3,
defaultRenderer = EquipmentRenderers.HatRenderer
},
{
id = "face",
image = "rbxassetid://3206646591",
name = "Face",
maxEquipped = 1,
defaultRenderer = EquipmentRenderers.FaceRenderer
},
{
id = "material",
image = "rbxassetid://3185662381",
name = "Material",
maxEquipped = 1,
defaultRenderer = EquipmentRenderers.MaterialRenderer
},
{
id = "effect",
image = "rbxassetid://3185662510",
name = "Effect",
maxEquipped = 3,
defaultRenderer = EquipmentRenderers.EffectRenderer
},
-- {
-- id = "tool",
-- image = "rbxassetid://3185662627",
-- name = "Tool",
-- maxEquipped = 3,
-- },
-- {
-- id = "ability",
-- image = "rbxassetid://3185662029",
-- name = "Ability",
-- maxEquipped = 99,
-- },
{
id = "pet",
image = "rbxassetid://3210207976",
name = "Pets",
maxEquipped = 1,
defaultRenderer = EquipmentRenderers.PetRenderer
},
}
return {
all = catagories,
byId = by("id", catagories),
} | 26.377049 | 83 | 0.556246 |
1ae9dacfef19c6b735c43c61e76e9e0217ed93d7 | 4,722 | rs | Rust | ringbuffer/src/lib.rs | michaelmelanson/kernel | 1b1abdd0387ceaadd6198322451b5ac2ae13d535 | [
"BSD-2-Clause"
] | 2 | 2020-03-30T18:36:03.000Z | 2020-04-01T17:30:49.000Z | ringbuffer/src/lib.rs | michaelmelanson/kernel | 1b1abdd0387ceaadd6198322451b5ac2ae13d535 | [
"BSD-2-Clause"
] | 2 | 2019-04-02T15:45:59.000Z | 2019-04-02T15:45:59.000Z | ringbuffer/src/lib.rs | michaelmelanson/kernel | 1b1abdd0387ceaadd6198322451b5ac2ae13d535 | [
"BSD-2-Clause"
] | 1 | 2018-12-02T19:09:51.000Z | 2018-12-02T19:09:51.000Z | #![no_std]
extern crate alloc;
extern crate spin;
use self::alloc::vec::Vec;
use self::alloc::sync::Arc;
use spin::Mutex;
/// A thread-safe circular buffer.
///
/// # Basic usage
///
/// You can write items to the buffer...
///
/// ```
/// # use ringbuffer::RingBuffer;
/// let ringbuffer = RingBuffer::new_with_capacity(10);
///
/// // It starts off empty.
/// assert_eq!(0, ringbuffer.size());
///
/// // Push some data into it.
/// ringbuffer.push(55);
/// ringbuffer.push(42);
///
/// // It now has data in it.
/// assert_eq!(2, ringbuffer.size());
/// ```
///
/// ... and read them out again in order ...
///
/// ```
/// # use ringbuffer::RingBuffer;
/// # let ringbuffer = RingBuffer::new_with_capacity(10);
/// # ringbuffer.push(55);
/// # ringbuffer.push(42);
/// let first = ringbuffer.pop();
/// let second = ringbuffer.pop();
///
/// assert_eq!(55, first);
/// assert_eq!(42, second);
/// ```
///
/// # Overflow / Underflow
///
/// When you put too many items in, it starts overwriting the oldest. This
/// means that readers can never block writers by failing to consume the
/// data.
///
/// ```
/// # use ringbuffer::RingBuffer;
/// let ringbuffer = RingBuffer::new_with_capacity(5);
///
/// // Push some data into it.
/// ringbuffer.push(1);
/// ringbuffer.push(2);
/// ringbuffer.push(3);
/// ringbuffer.push(4);
/// ringbuffer.push(5);
///
/// // It's now full, with five items.
/// assert_eq!(5, ringbuffer.size());
///
/// // Put another item in.
/// ringbuffer.push(6);
///
/// // There's still five items.
/// assert_eq!(5, ringbuffer.size());
///
/// // The first item is '2' -- the '1' was dropped -- and it continues from
/// // there.
/// assert_eq!(2, ringbuffer.pop());
/// assert_eq!(3, ringbuffer.pop());
/// assert_eq!(4, ringbuffer.pop());
/// assert_eq!(5, ringbuffer.pop());
/// assert_eq!(6, ringbuffer.pop());
/// ```
///
/// When you read too fast, it spins until data is available:
///
/// ```
/// # use ringbuffer::RingBuffer;
/// let ringbuffer = RingBuffer::new_with_capacity(10);
///
/// let reader_lock = ringbuffer.clone();
/// let reader = std::thread::spawn(move || {
/// // No data is available yet.
/// assert_eq!(None, reader_lock.poll());
///
/// // Block until we get data then return it
/// assert_eq!(55, reader_lock.pop());
/// });
///
/// std::thread::sleep(std::time::Duration::from_millis(100));
/// ringbuffer.push(55);
///
/// reader.join().expect("oh no the reader failed");
/// ```
///
#[derive(Clone)]
pub struct RingBuffer<Item: Clone> {
mutex: Arc<Mutex<RingBufferData<Item>>>
}
/// The thread-unsafe innards.
struct RingBufferData<Item: Clone> {
array: Vec<Item>,
start: usize,
count: usize
}
impl <Item: Clone> RingBuffer<Item> {
pub fn new_with_capacity(capacity: usize) -> Self {
RingBuffer {
mutex: Arc::new(
Mutex::new(RingBufferData {
array: Vec::with_capacity(capacity),
start: 0,
count: 0
})
)
}
}
#[inline]
pub fn capacity(&self) -> usize {
self.mutex.lock().capacity()
}
#[inline]
pub fn size(&self) -> usize {
self.mutex.lock().size()
}
pub fn push(&self, item: Item) {
let mut inner = self.mutex.lock();
inner.push(item)
}
pub fn poll(&self) -> Option<Item> {
let mut inner = self.mutex.lock();
inner.poll()
}
pub fn pop(&self) -> Item {
loop {
match self.poll() {
Some(item) => { return item; },
None => {}
}
}
}
}
/// The thread-unsafe innards of the ring buffer.
impl <Item: Clone> RingBufferData<Item> {
#[inline]
pub fn capacity(&self) -> usize {
self.array.capacity()
}
#[inline]
pub fn size(&self) -> usize {
self.count
}
#[inline]
fn is_full(&self) -> bool {
self.count == self.capacity()
}
#[inline]
fn is_empty(&self) -> bool {
self.count == 0
}
#[inline]
fn wrap_index(&self, index: usize) -> usize {
index % self.capacity()
}
#[inline]
fn write_position(&self) -> usize {
self.wrap_index(self.start + self.count)
}
#[inline]
fn read_position(&self) -> usize {
self.start
}
pub fn push(&mut self, item: Item) {
let index = self.write_position();
if index == self.array.len() {
self.array.push(item);
} else {
self.array[index] = item;
}
if self.is_full() {
self.start = self.wrap_index(self.start + 1);
} else {
self.count += 1;
}
}
pub fn poll(&mut self) -> Option<Item> {
if self.is_empty() {
None
} else {
let index = self.read_position();
let item = self.array[index].clone();
self.start = self.wrap_index(self.start + 1);
self.count -= 1;
Some(item)
}
}
}
| 20.893805 | 76 | 0.581533 |
0b5cea9d906ea2c35bda5ccee23fdca482e7e9b4 | 335 | py | Python | atest/testresources/testlibs/objecttoreturn.py | userzimmermann/robotframework | 7aa16338ce2120cb082605cf548c0794956ec901 | [
"Apache-2.0"
] | 7 | 2015-02-25T10:55:02.000Z | 2015-11-04T03:20:05.000Z | atest/testresources/testlibs/objecttoreturn.py | userzimmermann/robotframework | 7aa16338ce2120cb082605cf548c0794956ec901 | [
"Apache-2.0"
] | 12 | 2015-02-24T17:00:06.000Z | 2015-07-31T08:32:07.000Z | atest/testresources/testlibs/objecttoreturn.py | userzimmermann/robotframework | 7aa16338ce2120cb082605cf548c0794956ec901 | [
"Apache-2.0"
] | 2 | 2015-12-15T11:00:35.000Z | 2018-02-24T18:11:24.000Z | try:
import exceptions
except ImportError: # Python 3
import builtins as exceptions
class ObjectToReturn:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def exception(self, name, msg=""):
exception = getattr(exceptions, name)
raise exception(msg)
| 19.705882 | 45 | 0.647761 |
0a16e8e06ab54b6ada8dc2f89d3f94dc0e2ba32a | 1,148 | h | C | src/hpgl.pyd/py_sgs_params.h | hpgl/hpgl | 72d8c4113c242295de740513093f5779c94ba84a | [
"BSD-3-Clause"
] | 70 | 2015-01-21T12:24:50.000Z | 2022-03-16T02:10:45.000Z | src/hpgl.pyd/py_sgs_params.h | hpgl/hpgl | 72d8c4113c242295de740513093f5779c94ba84a | [
"BSD-3-Clause"
] | 8 | 2015-04-22T13:14:30.000Z | 2021-11-23T12:16:32.000Z | src/hpgl.pyd/py_sgs_params.h | hpgl/hpgl | 72d8c4113c242295de740513093f5779c94ba84a | [
"BSD-3-Clause"
] | 18 | 2015-02-15T18:04:31.000Z | 2021-01-16T08:54:32.000Z | /*
Copyright 2009 HPGL Team
This file is part of HPGL (High Perfomance Geostatistics Library).
HPGL is free software: you can redistribute it and/or modify it under the terms of the BSD License.
You should have received a copy of the BSD License along with HPGL.
*/
#ifndef __PY_SGS_PARAMS_H__A82C5906_7AE1_4CBE_804A_4F004CCACD5F__
#define __PY_SGS_PARAMS_H__A82C5906_7AE1_4CBE_804A_4F004CCACD5F__
#include <sgs_params.h>
namespace hpgl
{
class py_sgs_params_t
{
public:
sgs_params_t m_sgs_params;
bool m_auto_region_size;
void set_covariance_type(int type);
void set_ranges(double r1, double r2, double r3);
void set_angles(double a1, double a2, double a3);
void set_sill(double sill);
void set_nugget(double nugget);
void set_radiuses(size_t , size_t , size_t );
void set_max_neighbours(size_t mn);
void set_mean(double mean);
void set_kriging_kind(int kind);
void set_seed(long int seed);
void set_mean_kind(const std::string & mean_kind);
void set_min_neighbours(long int min_n);
};
}
#endif //__PY_SGS_PARAMS_H__A82C5906_7AE1_4CBE_804A_4F004CCACD5F__
| 30.210526 | 103 | 0.751742 |
856d85a3960eb2e439732f9afba48b3a23c2a361 | 738 | js | JavaScript | src/containers/Root.js | cloudapp/zendesk-react-redux-boilerplate | cd10346838b291fd3eda97b16cc50f5f4881f4b4 | [
"Apache-2.0"
] | 11 | 2017-01-29T21:17:30.000Z | 2021-07-25T10:45:47.000Z | src/containers/Root.js | cloudapp/zendesk-react-redux-boilerplate | cd10346838b291fd3eda97b16cc50f5f4881f4b4 | [
"Apache-2.0"
] | 1 | 2018-02-26T01:17:32.000Z | 2018-12-17T19:20:08.000Z | src/containers/Root.js | cloudapp/zendesk-react-redux-boilerplate | cd10346838b291fd3eda97b16cc50f5f4881f4b4 | [
"Apache-2.0"
] | 4 | 2018-02-26T01:20:26.000Z | 2021-03-30T02:28:54.000Z | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
export default class Root extends Component {
createElement(Component, props) {
return <Component { ...this.props.store } />;
}
get content() {
return (
<Router history={ this.props.history } >
{ this.props.routes }
</Router>
);
}
render() {
return (
<Provider store={ this.props.store }>
<div style={{ height: '100%' }}>
{ this.content }
</div>
</Provider>
);
}
}
Root.propTypes = {
history: React.PropTypes.object.isRequired,
routes: React.PropTypes.element.isRequired,
store: React.PropTypes.object.isRequired
};
| 21.085714 | 49 | 0.601626 |
a397ab899ea8696650bb7259afe4779b5b68f6cd | 627 | sql | SQL | vulnerable-webapp/sql/create_schema_and_seed.sql | dm-istomin/cs-gy-9163-application-security | 00c073a700a264d14980b3e19725d63928435aaf | [
"MIT"
] | null | null | null | vulnerable-webapp/sql/create_schema_and_seed.sql | dm-istomin/cs-gy-9163-application-security | 00c073a700a264d14980b3e19725d63928435aaf | [
"MIT"
] | null | null | null | vulnerable-webapp/sql/create_schema_and_seed.sql | dm-istomin/cs-gy-9163-application-security | 00c073a700a264d14980b3e19725d63928435aaf | [
"MIT"
] | null | null | null | CREATE DATABASE IF NOT EXISTS vulnerable_webapp;
USE vulnerable_webapp;
CREATE TABLE IF NOT EXISTS users(
id int auto_increment,
username varchar(255) UNIQUE NOT NULL,
role varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO users(username, role, password) VALUES (
'admin_user',
'admin',
'password'
);
INSERT INTO users(username, role, password) VALUES (
'user1',
'user',
'password'
);
INSERT INTO users(username, role, password) VALUES (
'user2',
'user',
'password'
);
INSERT INTO users(username, role, password) VALUES (
'user3',
'user',
'password'
);
| 19 | 52 | 0.69378 |