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
be7a7c779c59636c6d7d5ad918492ceef091c65a
5,187
sql
SQL
migrations/versions/b3e73cf868d6.sql
kokes/ockovani-covid
09810ccf187a22b7a5bb5aeae6156b62175fbda7
[ "Apache-2.0" ]
62
2021-01-16T18:02:57.000Z
2022-01-12T21:10:34.000Z
migrations/versions/b3e73cf868d6.sql
kokes/ockovani-covid
09810ccf187a22b7a5bb5aeae6156b62175fbda7
[ "Apache-2.0" ]
224
2021-01-16T19:11:01.000Z
2022-03-15T19:42:37.000Z
migrations/versions/b3e73cf868d6.sql
kokes/ockovani-covid
09810ccf187a22b7a5bb5aeae6156b62175fbda7
[ "Apache-2.0" ]
13
2021-01-16T18:38:11.000Z
2021-07-02T20:09:47.000Z
CREATE TABLE public.ockovani_registrace_part ( datum date NOT NULL, ockovaci_misto_id character varying COLLATE pg_catalog."default" NOT NULL, vekova_skupina character varying COLLATE pg_catalog."default" NOT NULL, povolani character varying COLLATE pg_catalog."default" NOT NULL, stat character varying COLLATE pg_catalog."default" NOT NULL, rezervace boolean NOT NULL, datum_rezervace date NOT NULL, pocet integer, import_id integer NOT NULL, CONSTRAINT ockovani_registrace_part_pkey PRIMARY KEY (datum, ockovaci_misto_id, vekova_skupina, povolani, stat, rezervace, datum_rezervace, import_id), CONSTRAINT ockovani_registrace_part_import_id_fkey FOREIGN KEY (import_id) REFERENCES public.importy (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE, CONSTRAINT ockovani_registrace_part_ockovaci_misto_id_fkey FOREIGN KEY (ockovaci_misto_id) REFERENCES public.ockovaci_mista (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION )PARTITION BY hash(import_id); CREATE TABLE ockovani_registrace_part_0 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 0); CREATE TABLE ockovani_registrace_part_1 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 1); CREATE TABLE ockovani_registrace_part_2 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 2); CREATE TABLE ockovani_registrace_part_3 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 3); CREATE TABLE ockovani_registrace_part_4 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 4); CREATE TABLE ockovani_registrace_part_5 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 5); CREATE TABLE ockovani_registrace_part_6 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 6); CREATE TABLE ockovani_registrace_part_7 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 7); CREATE TABLE ockovani_registrace_part_8 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 8); CREATE TABLE ockovani_registrace_part_9 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 9); CREATE TABLE ockovani_registrace_part_10 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 10); CREATE TABLE ockovani_registrace_part_11 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 11); CREATE TABLE ockovani_registrace_part_12 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 12); CREATE TABLE ockovani_registrace_part_13 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 13); CREATE TABLE ockovani_registrace_part_14 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 14); CREATE TABLE ockovani_registrace_part_15 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 15); CREATE TABLE ockovani_registrace_part_16 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 16); CREATE TABLE ockovani_registrace_part_17 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 17); CREATE TABLE ockovani_registrace_part_18 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 18); CREATE TABLE ockovani_registrace_part_19 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 19); CREATE TABLE ockovani_registrace_part_20 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 20); CREATE TABLE ockovani_registrace_part_21 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 21); CREATE TABLE ockovani_registrace_part_22 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 22); CREATE TABLE ockovani_registrace_part_23 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 23); CREATE TABLE ockovani_registrace_part_24 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 24); CREATE TABLE ockovani_registrace_part_25 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 25); CREATE TABLE ockovani_registrace_part_26 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 26); CREATE TABLE ockovani_registrace_part_27 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 27); CREATE TABLE ockovani_registrace_part_28 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 28); CREATE TABLE ockovani_registrace_part_29 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 29); CREATE TABLE ockovani_registrace_part_30 PARTITION OF ockovani_registrace_part FOR VALUES WITH (MODULUS 31, REMAINDER 30); insert into ockovani_registrace_part select * from ockovani_registrace; alter table public.ockovani_registrace rename to ockovani_registrace_old; alter table public.ockovani_registrace_part rename to ockovani_registrace; create index idx_o_r_ockovaci_misto_id on ockovani_registrace (ockovaci_misto_id);
92.625
155
0.839792
67b34ca8fcd911e380888f5404211be678d68592
748
rs
Rust
build.rs
Freaky/nomino
09234704cc6bb070c417bdf9b87c6460ef7a4c29
[ "Apache-2.0", "MIT" ]
406
2020-04-17T10:36:01.000Z
2022-03-21T20:38:39.000Z
build.rs
Freaky/nomino
09234704cc6bb070c417bdf9b87c6460ef7a4c29
[ "Apache-2.0", "MIT" ]
10
2020-04-18T19:51:09.000Z
2022-02-15T03:25:11.000Z
build.rs
Freaky/nomino
09234704cc6bb070c417bdf9b87c6460ef7a4c29
[ "Apache-2.0", "MIT" ]
14
2020-04-18T02:04:28.000Z
2022-01-28T13:12:36.000Z
use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()> { // Read template file let mut template = File::open("data/opts-template.yml")?; let mut template_contents = String::new(); template.read_to_string(&mut template_contents)?; // Replace metadata from Cargo.toml template_contents = template_contents .replace("%VERSION%", env!("CARGO_PKG_VERSION")) .replace("%NAME%", env!("CARGO_PKG_NAME")) .replace("%REPOSITORY%", env!("CARGO_PKG_REPOSITORY")) .replace("%DESCRIPTION%", env!("CARGO_PKG_DESCRIPTION")); // Write to opts let mut opts = File::create("src/opts.yml")?; opts.write_all(template_contents.as_bytes())?; opts.sync_all()?; Ok(()) }
31.166667
65
0.63369
0df880a04be7e74da773daf4d638116fd3640da6
552
rb
Ruby
core/config/routes.rb
appotry/cloud_wordpress
b89f027ce3c7a82972d8279e70faf8ffee96749a
[ "MIT" ]
23
2020-08-19T08:24:07.000Z
2022-03-02T22:22:31.000Z
core/config/routes.rb
just0911/cloud_wordpress
04678f3f51ba1422ad2f61617255cd6cf69005f8
[ "MIT" ]
null
null
null
core/config/routes.rb
just0911/cloud_wordpress
04678f3f51ba1422ad2f61617255cd6cf69005f8
[ "MIT" ]
11
2020-08-19T11:40:29.000Z
2022-03-09T02:54:45.000Z
Wordpress::Core::Engine.add_routes do if defined? authenticate require 'sidekiq/web' authenticate :admin_user, lambda { |u| u.admin? } do mount Sidekiq::Web => '/sidekiq' end end match '/api/v1', to: 'api#show', as: :api, via: [:get, :post] get '/api/v1/code', to: 'api#code', as: :api_code get '/server/install/*os', to: 'server#index' , as: :server get '/server/mysql/install/*os', to: 'server#mysql' , as: :server_mysql root to: 'home#index' end Wordpress::Core::Engine.draw_routes
36.8
75
0.608696
e024cfd515477308d1dc633537765587c72684e9
25,925
c
C
src/sg_senddiag.c
ystk/debian-sg3-utils
9ce112d2b919f8c33952b92975daf6d80d9e81ed
[ "DOC" ]
null
null
null
src/sg_senddiag.c
ystk/debian-sg3-utils
9ce112d2b919f8c33952b92975daf6d80d9e81ed
[ "DOC" ]
null
null
null
src/sg_senddiag.c
ystk/debian-sg3-utils
9ce112d2b919f8c33952b92975daf6d80d9e81ed
[ "DOC" ]
null
null
null
#include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <getopt.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "sg_lib.h" #include "sg_cmds_basic.h" #include "sg_cmds_extra.h" /* A utility program originally written for the Linux OS SCSI subsystem * Copyright (C) 2003-2009 D. Gilbert * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. This program issues the SCSI SEND DIAGNOSTIC command and in one case the SCSI RECEIVE DIAGNOSTIC command to list supported diagnostic pages. */ static char * version_str = "0.36 20090617"; #define ME "sg_senddiag: " #define MX_ALLOC_LEN (1024 * 4) static struct option long_options[] = { {"doff", 0, 0, 'd'}, {"extdur", 0, 0, 'e'}, {"help", 0, 0, 'h'}, {"hex", 0, 0, 'H'}, {"list", 0, 0, 'l'}, {"new", 0, 0, 'N'}, {"old", 0, 0, 'O'}, {"pf", 0, 0, 'p'}, {"raw", 1, 0, 'r'}, {"selftest", 1, 0, 's'}, {"test", 0, 0, 't'}, {"uoff", 0, 0, 'u'}, {"verbose", 0, 0, 'v'}, {"version", 0, 0, 'V'}, {0, 0, 0, 0}, }; struct opts_t { int do_doff; int do_extdur; int do_help; int do_hex; int do_list; int do_pf; int do_raw; int do_selftest; int do_deftest; int do_uoff; int do_verbose; int do_version; const char * device_name; const char * raw_arg; int opt_new; }; static void usage() { printf("Usage: sg_senddiag [--doff] [--extdur] [--help] [--hex] " "[--list] [--pf]\n" " [--raw=H,H...] [--selftest=ST] " "[--test] [--uoff]\n" " [--verbose] [--version] " "[DEVICE]\n" " where:\n" " --doff|-d device online (def: 0, only with '--test')\n" " --extdur|-e duration of an extended self-test (from mode " "page 0xa)\n" " --help|-h print usage message then exit\n" " --hex|H output in hex\n" " --list|-l list supported page codes (with or without " "DEVICE)\n" " --pf|-p set PF bit (def: 0)\n" " --raw=H,H...|-r H,H... sequence of hex bytes to form " "diag page to send\n" " --raw=-|-r - read stdin for sequence of bytes to send\n" " --selftest=ST|-s ST self-test code, default: 0 " "(inactive)\n" " 1->background short, 2->background " "extended\n" " 4->abort test\n" " 5->foreground short, 6->foreground " "extended\n" " --test|-t default self-test\n" " --uoff|-u unit offline (def: 0, only with '--test')\n" " --verbose|-v increase verbosity\n" " --version|-V output version string then exit\n\n" "Performs a SCSI SEND DIAGNOSTIC (and/or a RECEIVE DIAGNOSTIC " "RESULTS) command\n" ); } static void usage_old() { printf("Usage: sg_senddiag [-doff] [-e] [-h] [-H] [-l] [-pf]" " [-raw=H,H...]\n" " [-s=SF] [-t] [-uoff] [-v] [-V] " "[DEVICE]\n" " where:\n" " -doff device online (def: 0, only with '-t')\n" " -e duration of an extended self-test (from mode page " "0xa)\n" " -h output in hex\n" " -H output in hex (same as '-h')\n" " -l list supported page codes\n" " -pf set PF bit (def: 0)\n" " -raw=H,H... sequence of bytes to form diag page to " "send\n" " -raw=- read stdin for sequence of bytes to send\n" " -s=SF self-test code (def: 0)\n" " 1->background short, 2->background extended," " 4->abort test\n" " 5->foreground short, 6->foreground extended\n" " -t default self-test\n" " -uoff unit offline (def: 0, only with '-t')\n" " -v increase verbosity (print issued SCSI cmds)\n" " -V output version string\n" " -? output this usage message\n\n" "Performs a SCSI SEND DIAGNOSTIC (and/or a RECEIVE DIAGNOSTIC " "RESULTS) command\n" ); } static int process_cl_new(struct opts_t * optsp, int argc, char * argv[]) { int c, n; while (1) { int option_index = 0; c = getopt_long(argc, argv, "dehHlNOpr:s:tuvV", long_options, &option_index); if (c == -1) break; switch (c) { case 'd': optsp->do_doff = 1; break; case 'e': optsp->do_extdur = 1; break; case 'h': case '?': ++optsp->do_help; break; case 'H': ++optsp->do_hex; break; case 'l': ++optsp->do_list; break; case 'N': break; /* ignore */ case 'O': optsp->opt_new = 0; return 0; case 'p': optsp->do_pf = 1; break; case 'r': optsp->raw_arg = optarg; optsp->do_raw = 1; break; case 's': n = sg_get_num(optarg); if ((n < 0) || (n > 7)) { fprintf(stderr, "bad argument to '--selftest='\n"); usage(); return SG_LIB_SYNTAX_ERROR; } optsp->do_selftest = n; break; case 't': optsp->do_deftest = 1; break; case 'u': optsp->do_uoff = 1; break; case 'v': ++optsp->do_verbose; break; case 'V': ++optsp->do_version; break; default: fprintf(stderr, "unrecognised option code %c [0x%x]\n", c, c); if (optsp->do_help) break; usage(); return SG_LIB_SYNTAX_ERROR; } } if (optind < argc) { if (NULL == optsp->device_name) { optsp->device_name = argv[optind]; ++optind; } if (optind < argc) { for (; optind < argc; ++optind) fprintf(stderr, "Unexpected extra argument: %s\n", argv[optind]); usage(); return SG_LIB_SYNTAX_ERROR; } } return 0; } static int process_cl_old(struct opts_t * optsp, int argc, char * argv[]) { int k, jmp_out, plen, num; unsigned int u; const char * cp; for (k = 1; k < argc; ++k) { cp = argv[k]; plen = strlen(cp); if (plen <= 0) continue; if ('-' == *cp) { for (--plen, ++cp, jmp_out = 0; plen > 0; --plen, ++cp) { switch (*cp) { case 'd': if (0 == strncmp("doff", cp, 4)) { optsp->do_doff = 1; cp += 3; plen -= 3; } else jmp_out = 1; break; case 'e': optsp->do_extdur = 1; break; case 'h': case 'H': ++optsp->do_hex; break; case 'l': ++optsp->do_list; break; case 'N': optsp->opt_new = 1; return 0; case 'O': break; case 'p': if (0 == strncmp("pf", cp, 2)) { optsp->do_pf = 1; ++cp; --plen; } else jmp_out = 1; break; case 't': optsp->do_deftest = 1; break; case 'u': if (0 == strncmp("uoff", cp, 4)) { optsp->do_uoff = 1; cp += 3; plen -= 3; } else jmp_out = 1; break; case 'v': ++optsp->do_verbose; break; case 'V': ++optsp->do_version; break; case '?': ++optsp->do_help; break; default: jmp_out = 1; break; } if (jmp_out) break; } if (plen <= 0) continue; if (0 == strncmp("raw=", cp, 4)) { optsp->raw_arg = cp + 4; optsp->do_raw = 1; } else if (0 == strncmp("s=", cp, 2)) { num = sscanf(cp + 2, "%x", &u); if ((1 != num) || (u > 7)) { printf("Bad page code after '-s=' option\n"); usage_old(); return SG_LIB_SYNTAX_ERROR; } optsp->do_selftest = u; } else if (0 == strncmp("-old", cp, 5)) ; else if (jmp_out) { fprintf(stderr, "Unrecognized option: %s\n", cp); usage_old(); return SG_LIB_SYNTAX_ERROR; } } else if (0 == optsp->device_name) optsp->device_name = cp; else { fprintf(stderr, "too many arguments, got: %s, not expecting: " "%s\n", optsp->device_name, cp); usage_old(); return SG_LIB_SYNTAX_ERROR; } } return 0; } static int process_cl(struct opts_t * optsp, int argc, char * argv[]) { int res; char * cp; cp = getenv("SG3_UTILS_OLD_OPTS"); if (cp) { optsp->opt_new = 0; res = process_cl_old(optsp, argc, argv); if ((0 == res) && optsp->opt_new) res = process_cl_new(optsp, argc, argv); } else { optsp->opt_new = 1; res = process_cl_new(optsp, argc, argv); if ((0 == res) && (0 == optsp->opt_new)) res = process_cl_old(optsp, argc, argv); } return res; } /* Return of 0 -> success, otherwise see sg_ll_send_diag() */ static int do_senddiag(int sg_fd, int sf_code, int pf_bit, int sf_bit, int devofl_bit, int unitofl_bit, void * outgoing_pg, int outgoing_len, int noisy, int verbose) { int long_duration = 0; if ((0 == sf_bit) && ((5 == sf_code) || (6 == sf_code))) long_duration = 1; /* foreground self-tests */ return sg_ll_send_diag(sg_fd, sf_code, pf_bit, sf_bit, devofl_bit, unitofl_bit, long_duration, outgoing_pg, outgoing_len, noisy, verbose); } /* Get expected extended self-test time from mode page 0xa (for '-e' option) */ static int do_modes_0a(int sg_fd, void * resp, int mx_resp_len, int noisy, int mode6, int verbose) { int res; if (mode6) res = sg_ll_mode_sense6(sg_fd, 1 /* dbd */, 0 /* pc */, 0xa /* page */, 0, resp, mx_resp_len, noisy, verbose); else res = sg_ll_mode_sense10(sg_fd, 0 /* llbaa */, 1 /* dbd */, 0, 0xa, 0, resp, mx_resp_len, noisy, verbose); if (SG_LIB_CAT_INVALID_OP == res) fprintf(stderr, "Mode sense (%s) command not supported\n", (mode6 ? "6" : "10")); else if (SG_LIB_CAT_ILLEGAL_REQ == res) fprintf(stderr, "bad field in Mode sense (%s) command\n", (mode6 ? "6" : "10")); else if (SG_LIB_CAT_NOT_READY == res) fprintf(stderr, "Mode sense (%s) failed, device not ready\n", (mode6 ? "6" : "10")); else if (SG_LIB_CAT_UNIT_ATTENTION == res) fprintf(stderr, "Mode sense (%s) failed, unit attention\n", (mode6 ? "6" : "10")); else if (SG_LIB_CAT_ABORTED_COMMAND == res) fprintf(stderr, "Mode sense (%s) failed, aborted command\n", (mode6 ? "6" : "10")); return res; } /* Read hex numbers from command line (comma separated list) or from */ /* stdin (one per line, comma separated list or space separated list). */ /* Returns 0 if ok, or 1 if error. */ static int build_diag_page(const char * inp, unsigned char * mp_arr, int * mp_arr_len, int max_arr_len) { int in_len, k, j, m; unsigned int h; const char * lcp; char * cp; char * c2p; if ((NULL == inp) || (NULL == mp_arr) || (NULL == mp_arr_len)) return 1; lcp = inp; in_len = strlen(inp); if (0 == in_len) *mp_arr_len = 0; if ('-' == inp[0]) { /* read from stdin */ char line[512]; int off = 0; for (j = 0; j < 512; ++j) { if (NULL == fgets(line, sizeof(line), stdin)) break; in_len = strlen(line); if (in_len > 0) { if ('\n' == line[in_len - 1]) { --in_len; line[in_len] = '\0'; } } if (0 == in_len) continue; lcp = line; m = strspn(lcp, " \t"); if (m == in_len) continue; lcp += m; in_len -= m; if ('#' == *lcp) continue; k = strspn(lcp, "0123456789aAbBcCdDeEfF ,\t"); if ((k < in_len) && ('#' != lcp[k])) { fprintf(stderr, "build_diag_page: syntax error at " "line %d, pos %d\n", j + 1, m + k + 1); return 1; } for (k = 0; k < 1024; ++k) { if (1 == sscanf(lcp, "%x", &h)) { if (h > 0xff) { fprintf(stderr, "build_diag_page: hex number " "larger than 0xff in line %d, pos %d\n", j + 1, (int)(lcp - line + 1)); return 1; } if ((off + k) >= max_arr_len) { fprintf(stderr, "build_diag_page: array length " "exceeded\n"); return 1; } mp_arr[off + k] = h; lcp = strpbrk(lcp, " ,\t"); if (NULL == lcp) break; lcp += strspn(lcp, " ,\t"); if ('\0' == *lcp) break; } else { if ('#' == *lcp) { --k; break; } fprintf(stderr, "build_diag_page: error in " "line %d, at pos %d\n", j + 1, (int)(lcp - line + 1)); return 1; } } off += (k + 1); } *mp_arr_len = off; } else { /* hex string on command line */ k = strspn(inp, "0123456789aAbBcCdDeEfF, "); if (in_len != k) { fprintf(stderr, "build_diag_page: error at pos %d\n", k + 1); return 1; } for (k = 0; k < max_arr_len; ++k) { if (1 == sscanf(lcp, "%x", &h)) { if (h > 0xff) { fprintf(stderr, "build_diag_page: hex number larger " "than 0xff at pos %d\n", (int)(lcp - inp + 1)); return 1; } mp_arr[k] = h; cp = strchr(lcp, ','); c2p = strchr(lcp, ' '); if (NULL == cp) cp = c2p; if (NULL == cp) break; if (c2p && (c2p < cp)) cp = c2p; lcp = cp + 1; } else { fprintf(stderr, "build_diag_page: error at pos %d\n", (int)(lcp - inp + 1)); return 1; } } *mp_arr_len = k + 1; if (k == max_arr_len) { fprintf(stderr, "build_diag_page: array length exceeded\n"); return 1; } } return 0; } struct page_code_desc { int page_code; const char * desc; }; static struct page_code_desc pc_desc_arr[] = { {0x0, "Supported diagnostic pages"}, {0x1, "Configuration (SES)"}, {0x2, "Enclosure status/control (SES)"}, {0x3, "Help text (SES)"}, {0x4, "String In/Out (SES)"}, {0x5, "Threshold In/Out (SES)"}, {0x6, "Array Status/Control (SES, obsolete)"}, {0x7, "Element descriptor (SES)"}, {0x8, "Short enclosure status (SES)"}, {0x9, "Enclosure busy (SES-2)"}, {0xa, "Additional (device) element status (SES-2)"}, {0xb, "Subenclosure help text (SES-2)"}, {0xc, "Subenclosure string In/Out (SES-2)"}, {0xd, "Supported SES diagnostic pages (SES-2)"}, {0xe, "Download microcode diagnostic pages (SES-2)"}, {0xf, "Subenclosure nickname diagnostic pages (SES-2)"}, {0x3f, "Protocol specific (SAS transport)"}, {0x40, "Translate address (direct access)"}, {0x41, "Device status (direct access)"}, }; static const char * find_page_code_desc(int page_num) { int k; int num = sizeof(pc_desc_arr) / sizeof(pc_desc_arr[0]); const struct page_code_desc * pcdp = &pc_desc_arr[0]; for (k = 0; k < num; ++k, ++pcdp) { if (page_num == pcdp->page_code) return pcdp->desc; else if (page_num < pcdp->page_code) return NULL; } return NULL; } static void list_page_codes() { int k; int num = sizeof(pc_desc_arr) / sizeof(pc_desc_arr[0]); const struct page_code_desc * pcdp = &pc_desc_arr[0]; printf("Page_Code Description\n"); for (k = 0; k < num; ++k, ++pcdp) printf(" 0x%02x %s\n", pcdp->page_code, (pcdp->desc ? pcdp->desc : "<unknown>")); } int main(int argc, char * argv[]) { int sg_fd, k, num, rsp_len, res; unsigned char rsp_buff[MX_ALLOC_LEN]; int rsp_buff_size = MX_ALLOC_LEN; int read_in_len = 0; const char * cp; unsigned char read_in[MX_ALLOC_LEN]; int ret = 0; struct opts_t opts; memset(&opts, 0, sizeof(opts)); res = process_cl(&opts, argc, argv); if (res) return SG_LIB_SYNTAX_ERROR; if (opts.do_help) { if (opts.opt_new) usage(); else usage_old(); return 0; } if (opts.do_version) { fprintf(stderr, "Version string: %s\n", version_str); return 0; } if (NULL == opts.device_name) { fprintf(stderr, "No DEVICE argument given\n"); if (opts.opt_new) usage(); else usage_old(); return SG_LIB_SYNTAX_ERROR; } if (opts.do_raw) { if (build_diag_page(opts.raw_arg, read_in, &read_in_len, sizeof(read_in))) { if (opts.opt_new) { printf("Bad sequence after '--raw=' option\n"); usage(); } else { printf("Bad sequence after '-raw=' option\n"); usage_old(); } return SG_LIB_SYNTAX_ERROR; } } if ((opts.do_doff || opts.do_uoff) && (! opts.do_deftest)) { if (opts.opt_new) { printf("setting --doff or --uoff only useful when -t is set\n"); usage(); } else { printf("setting -doff or -uoff only useful when -t is set\n"); usage_old(); } return SG_LIB_SYNTAX_ERROR; } if ((opts.do_selftest > 0) && opts.do_deftest) { if (opts.opt_new) { printf("either set --selftest=SF or --test (not both)\n"); usage(); } else { printf("either set -s=SF or -t (not both)\n"); usage_old(); } return SG_LIB_SYNTAX_ERROR; } if (opts.do_raw) { if ((opts.do_selftest > 0) || opts.do_deftest || opts.do_extdur || opts.do_list) { if (opts.opt_new) { printf("'--raw=' cannot be used with self-tests, '-e' or " "'-l'\n"); usage(); } else { printf("'-raw=' cannot be used with self-tests, '-e' or " "'-l'\n"); usage_old(); } return SG_LIB_SYNTAX_ERROR; } if (! opts.do_pf) { if (opts.opt_new) printf(">>> warning, '--pf' probably should be used with " "'--raw='\n"); else printf(">>> warning, '-pf' probably should be used with " "'-raw='\n"); } } if (NULL == opts.device_name) { if (opts.do_list) { list_page_codes(); return 0; } fprintf(stderr, "No DEVICE argument given\n"); if (opts.opt_new) usage(); else usage_old(); return SG_LIB_SYNTAX_ERROR; } if ((sg_fd = sg_cmds_open_device(opts.device_name, 0 /* rw */, opts.do_verbose)) < 0) { fprintf(stderr, ME "error opening file: %s: %s\n", opts.device_name, safe_strerror(-sg_fd)); return SG_LIB_FILE_ERROR; } if (opts.do_extdur) { res = do_modes_0a(sg_fd, rsp_buff, 32, 1, 0, opts.do_verbose); if (0 == res) { /* Assume mode sense(10) response without block descriptors */ num = (rsp_buff[0] << 8) + rsp_buff[1] - 6; if (num >= 0xc) { int secs; secs = (rsp_buff[18] << 8) + rsp_buff[19]; #ifdef SG_LIB_MINGW printf("Expected extended self-test duration=%d seconds " "(%g minutes)\n", secs, secs / 60.0); #else printf("Expected extended self-test duration=%d seconds " "(%.2f minutes)\n", secs, secs / 60.0); #endif } else printf("Extended self-test duration not available\n"); } else { ret = res; printf("Extended self-test duration (mode page 0xa) failed\n"); goto err_out9; } } else if (opts.do_list) { memset(rsp_buff, 0, sizeof(rsp_buff)); res = do_senddiag(sg_fd, 0, 1 /* pf */, 0, 0, 0, rsp_buff, 4, 1, opts.do_verbose); if (0 == res) { if (0 == sg_ll_receive_diag(sg_fd, 0, 0, rsp_buff, rsp_buff_size, 1, opts.do_verbose)) { printf("Supported diagnostic pages response:\n"); rsp_len = (rsp_buff[2] << 8) + rsp_buff[3] + 4; if (opts.do_hex) dStrHex((const char *)rsp_buff, rsp_len, 1); else { for (k = 0; k < (rsp_len - 4); ++k) { cp = find_page_code_desc(rsp_buff[k + 4]); printf(" 0x%02x %s\n", rsp_buff[k + 4], (cp ? cp : "<unknown>")); } } } else { ret = res; fprintf(stderr, "RECEIVE DIAGNOSTIC RESULTS command " "failed\n"); goto err_out9; } } else { ret = res; goto err_out; } } else if (opts.do_raw) { res = do_senddiag(sg_fd, 0, opts.do_pf, 0, 0, 0, read_in, read_in_len, 1, opts.do_verbose); if (res) { ret = res; goto err_out; } } else { res = do_senddiag(sg_fd, opts.do_selftest, opts.do_pf, opts.do_deftest, opts.do_doff, opts.do_uoff, NULL, 0, 1, opts.do_verbose); if (0 == res) { if ((5 == opts.do_selftest) || (6 == opts.do_selftest)) printf("Foreground self-test returned GOOD status\n"); else if (opts.do_deftest && (! opts.do_doff) && (! opts.do_uoff)) printf("Default self-test returned GOOD status\n"); } else { ret = res; goto err_out; } } res = sg_cmds_close_device(sg_fd); if ((res < 0) && (0 == ret)) return SG_LIB_SYNTAX_ERROR; return (ret >= 0) ? ret : SG_LIB_CAT_OTHER; err_out: if (SG_LIB_CAT_UNIT_ATTENTION == res) fprintf(stderr, "SEND DIAGNOSTIC, unit attention\n"); else if (SG_LIB_CAT_ABORTED_COMMAND == res) fprintf(stderr, "SEND DIAGNOSTIC, aborted command\n"); else if (SG_LIB_CAT_NOT_READY == res) fprintf(stderr, "SEND DIAGNOSTIC, device not " "ready\n"); else fprintf(stderr, "SEND DIAGNOSTIC command, failed\n"); err_out9: if (opts.do_verbose < 2) fprintf(stderr, " try again with '-vv' for more information\n"); res = sg_cmds_close_device(sg_fd); if ((res < 0) && (0 == ret)) return SG_LIB_FILE_ERROR; return (ret >= 0) ? ret : SG_LIB_CAT_OTHER; }
33.581606
79
0.4427
1bad3ded437009a78529873ac34b46358e08fbc8
988
swift
Swift
Kapesni zachranar/View/Subclass/UITableViewCell/CustomTableViewCell.swift
MelicharT1/Kapesni_Zachranar
7858ae0067d81387ef58802c614e8f8e3037593f
[ "MIT" ]
null
null
null
Kapesni zachranar/View/Subclass/UITableViewCell/CustomTableViewCell.swift
MelicharT1/Kapesni_Zachranar
7858ae0067d81387ef58802c614e8f8e3037593f
[ "MIT" ]
null
null
null
Kapesni zachranar/View/Subclass/UITableViewCell/CustomTableViewCell.swift
MelicharT1/Kapesni_Zachranar
7858ae0067d81387ef58802c614e8f8e3037593f
[ "MIT" ]
null
null
null
// // CustomTableViewCell.swift // Kapesni zachranar // // Created by Tomáš Melichar on 03/12/2019. // Copyright © 2019 Tomáš Melichar. All rights reserved. // import UIKit class CustomTableViewCell: UITableViewCell { @IBOutlet private weak var nameLabelOutlet: UILabel! @IBOutlet private weak var detailLabelOutlet: UILabel! @IBOutlet private weak var symbolLabelOutlet: UILabel! public var tableItem: TableItem! { didSet { nameLabelOutlet.text = tableItem.name detailLabelOutlet.text = tableItem.discription symbolLabelOutlet.text = tableItem.symbol } } // MARK: Awake from nib override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } /* Implementace pro Universal table view for symbol */
27.444444
65
0.673077
fffa2095fabacdd14e246c7718536722f10c77eb
272
lua
Lua
EasyLD/love/LoveShader.lua
Goutye/EasyLD
9015939902094279b6f504771366543ce827ea49
[ "MIT" ]
null
null
null
EasyLD/love/LoveShader.lua
Goutye/EasyLD
9015939902094279b6f504771366543ce827ea49
[ "MIT" ]
null
null
null
EasyLD/love/LoveShader.lua
Goutye/EasyLD
9015939902094279b6f504771366543ce827ea49
[ "MIT" ]
null
null
null
local class = require 'EasyLD.lib.middleclass' local Shader = class('Shader') function Shader.static:useDefault() love.graphics.setShader() end function Shader:initialize(code, vertexCode) end function Shader:use() love.graphics.setShader(self.s) end return Shader
16
46
0.779412
c48275d7bd69f5f138c89b4a20251267a824a99d
290
cpp
C++
sand_box_6.cpp
gwamoniak/Cpp
b1815464412f8d282f578cbf3ecc4b07a480b7d3
[ "MIT" ]
null
null
null
sand_box_6.cpp
gwamoniak/Cpp
b1815464412f8d282f578cbf3ecc4b07a480b7d3
[ "MIT" ]
null
null
null
sand_box_6.cpp
gwamoniak/Cpp
b1815464412f8d282f578cbf3ecc4b07a480b7d3
[ "MIT" ]
1
2022-01-16T16:29:05.000Z
2022-01-16T16:29:05.000Z
#include <utility> #include <iostream> #include <algorithm> #include <vector> #include <memory_resource> constexpr double pow(const double x, std::size_t y) { return y!= 1 ? x*pow(x,y-1) :x; } int main() { auto out = pow(3.0,6); std::cout << out << '\n'; return 0; }
13.181818
52
0.6
73d0ea256f6dfa76860ef50e43df223a91efc85a
1,946
php
PHP
src/Data/Unlike.php
creativechain/trantor-php
d71392777ef2e226143312e324a29a6aff476d48
[ "Unlicense" ]
null
null
null
src/Data/Unlike.php
creativechain/trantor-php
d71392777ef2e226143312e324a29a6aff476d48
[ "Unlicense" ]
null
null
null
src/Data/Unlike.php
creativechain/trantor-php
d71392777ef2e226143312e324a29a6aff476d48
[ "Unlicense" ]
null
null
null
<?php /** * Created by PhpStorm. * User: ander * Date: 16/03/18 * Time: 14:57 */ namespace Trantor\Data; use Trantor\Constants; class Unlike extends ContentData { /** @var string */ private $author; /** @var string */ private $contentAddress; /** * Unlike constructor. * @param string $followerAddress * @param string $contentAddress */ public function __construct($followerAddress, $contentAddress) { parent::__construct(Constants::VERSION, Constants::TYPE_UNLIKE); $this->author = $followerAddress; $this->contentAddress = $contentAddress; } /** * @return string */ protected function serialize() { $bufferHex = ContentData::serializeNumber($this->getVersion()); $bufferHex .= ContentData::serializeNumber($this->getType()); $bufferHex .= ContentData::decodeAddress($this->author); $bufferHex .= ContentData::decodeAddress($this->contentAddress); return $bufferHex; } /** * @param array $data * @param int $offset * @return int */ protected function deserialize($data, $offset) { $offset = parent::deserialize($data, $offset); $author = array_slice($data, $offset, 20); $this->author = ContentData::encodeAddress($author); $offset += 20; $contentAddress = array_slice($data, $offset, 20); $this->contentAddress = ContentData::encodeAddress($contentAddress); $offset += 20; return $offset; } /** * @return string */ public function getAuthor() { return $this->author; } /** * @return string */ public function getContentAddress() { return $this->contentAddress; } /** * @return Unlike */ public static function newEmpty() { $unlike = new Unlike(null, null); return $unlike; } }
22.367816
77
0.581706
339b28896197598fcae6cf37062c21c9aac73a28
8,538
c
C
lib/nnc/cmd/nms/ccv_nnc_nms_cpu_ref.c
neonkingfr/ccv
579d21e9065d5378be4b21a4b9c0224327fb0a9f
[ "CC0-1.0", "CC-BY-4.0" ]
3,296
2015-01-01T02:05:51.000Z
2022-03-31T00:29:55.000Z
lib/nnc/cmd/nms/ccv_nnc_nms_cpu_ref.c
neonkingfr/ccv
579d21e9065d5378be4b21a4b9c0224327fb0a9f
[ "CC0-1.0", "CC-BY-4.0" ]
111
2015-01-12T15:55:58.000Z
2022-01-05T18:13:11.000Z
lib/nnc/cmd/nms/ccv_nnc_nms_cpu_ref.c
neonkingfr/ccv
579d21e9065d5378be4b21a4b9c0224327fb0a9f
[ "CC0-1.0", "CC-BY-4.0" ]
940
2015-01-02T02:21:34.000Z
2022-03-24T23:27:43.000Z
#include "ccv.h" #include "ccv_internal.h" #include "nnc/ccv_nnc.h" #include "nnc/ccv_nnc_easy.h" #include "nnc/ccv_nnc_internal.h" #ifdef USE_OPENMP #include <omp.h> #endif #ifdef USE_DISPATCH #include <dispatch/dispatch.h> #endif typedef struct { float v[5]; } float5; #define less_than(a, b, aux) ((a).v[0] > (b).v[0]) #define swap_func(a, b, array, aux, t) do { \ (t) = (a); \ (a) = (b); \ (b) = (t); \ int _t = aux[&(a) - array]; \ aux[&(a) - array] = aux[&(b) - array]; \ aux[&(b) - array] = _t; \ } while (0) CCV_IMPLEMENT_QSORT_EX(_ccv_nnc_nms_sortby_f5_32f, float5, less_than, swap_func, int*) #undef less_than #undef swap_func static int _ccv_nnc_nms_forw(const ccv_nnc_cmd_t cmd, const ccv_nnc_hint_t hint, const int flags, ccv_nnc_tensor_t* const* const inputs, const int input_size, ccv_nnc_tensor_t* const* const outputs, const int output_size, ccv_nnc_stream_context_t* const stream_context) { assert(input_size == 1); const ccv_nnc_tensor_view_t* a = (ccv_nnc_tensor_view_t*)inputs[0]; assert(output_size == 2); ccv_nnc_tensor_view_t* b = (ccv_nnc_tensor_view_t*)outputs[0]; ccv_nnc_tensor_view_t* c = (ccv_nnc_tensor_view_t*)outputs[1]; const int a_nd = ccv_nnc_tensor_nd(a->info.dim); const int b_nd = ccv_nnc_tensor_nd(b->info.dim); const int c_nd = ccv_nnc_tensor_nd(c->info.dim); assert(a_nd == b_nd); int i; for (i = 0; i < a_nd; i++) { assert(a->info.dim[i] == b->info.dim[i]); } const int* ainc = CCV_IS_TENSOR_VIEW(a) ? a->inc : a->info.dim; const int* binc = CCV_IS_TENSOR_VIEW(b) ? b->inc : b->info.dim; const int* cinc = CCV_IS_TENSOR_VIEW(c) ? c->inc : c->info.dim; const int n = a_nd >= 3 ? a->info.dim[0] : 1; const int aninc = a_nd >= 3 ? ainc[1] * ainc[2] : 0; const int bninc = b_nd >= 3 ? binc[1] * binc[2] : 0; const int cninc = c_nd >= 2 ? cinc[1] : 0; const int m = a_nd >= 3 ? a->info.dim[1] : a->info.dim[0]; if (c_nd == 1) { assert(m == c->info.dim[0]); } else { assert(c_nd == 2 && n == c->info.dim[0] && m == c->info.dim[1]); } const int aminc = ainc[a_nd - 1]; const int bminc = binc[b_nd - 1]; const int d = a_nd <= 1 ? 1 : a->info.dim[a_nd - 1]; const float iou_threshold = cmd.info.nms.iou_threshold; if (d == 5 && aminc == 5 && aminc == bminc) // If it is 5, we can use our quick sort implementation. { parallel_for(i, n) { int x, y; const float* const ap = a->data.f32 + i * aninc; float* const bp = b->data.f32 + i * bninc; int* const cp = c->data.i32 + i * cninc; for (x = 0; x < m; x++) cp[x] = x; for (x = 0; x < m * d; x++) bp[x] = ap[x]; _ccv_nnc_nms_sortby_f5_32f((float5*)bp, m, cp); for (x = 0; x < m; x++) { float v = bp[x * 5]; if (v == -FLT_MAX) // Suppressed. continue; const float area1 = bp[x * 5 + 3] * bp[x * 5 + 4]; for (y = x + 1; y < m; y++) { const float u = bp[y * 5]; if (u == -FLT_MAX) // Suppressed. continue; const float area2 = bp[y * 5 + 3] * bp[y * 5 + 4]; const float xdiff = ccv_max(0, ccv_min(bp[x * 5 + 1] + bp[x * 5 + 3], bp[y * 5 + 1] + bp[y * 5 + 3]) - ccv_max(bp[x * 5 + 1], bp[y * 5 + 1])); const float ydiff = ccv_max(0, ccv_min(bp[x * 5 + 2] + bp[x * 5 + 4], bp[y * 5 + 2] + bp[y * 5 + 4]) - ccv_max(bp[x * 5 + 2], bp[y * 5 + 2])); const float intersection = xdiff * ydiff; const float iou = intersection / (area1 + area2 - intersection); if (iou >= iou_threshold) bp[y * 5] = -FLT_MAX; } } // Move these values up and move suppressed to the end. for (x = 0, y = 0; x < m; x++) if (bp[x * 5] != -FLT_MAX) { int j; if (x != y) { for (j = 0; j < 5; j++) bp[y * 5 + j] = bp[x * 5 + j]; cp[y] = cp[x]; } ++y; } for (x = y; x < m; x++) cp[x] = -1, bp[x * 5] = -FLT_MAX; } parallel_endfor } else { // Otherwise, fall to use selection sort. parallel_for(i, n) { int x, y; const float* const ap = a->data.f32 + i * aninc; float* const bp = b->data.f32 + i * bninc; int* const cp = c->data.i32 + i * cninc; for (x = 0; x < m; x++) cp[x] = x; for (x = 0; x < m; x++) for (y = 0; y < d; y++) bp[x * bminc + y] = ap[x * aminc + y]; for (x = 0; x < m; x++) { float v = bp[x * bminc]; int k = x; for (y = x + 1; y < m; y++) { const float u = bp[y * bminc]; if (u > v) k = y, v = u; } for (y = 0; y < d; y++) { const float t = bp[k * bminc + y]; bp[k * bminc + y] = bp[x * bminc + y]; bp[x * bminc + y] = t; const int u = cp[k]; cp[k] = cp[x]; cp[x] = u; } } for (x = 0; x < m; x++) { float v = bp[x * bminc]; if (v == -FLT_MAX) // Suppressed. continue; const float area1 = bp[x * bminc + 3] * bp[x * bminc + 4]; for (y = x + 1; y < m; y++) { const float u = bp[y * bminc]; if (u == -FLT_MAX) // Suppressed. continue; const float area2 = bp[y * bminc + 3] * bp[y * bminc + 4]; const float xdiff = ccv_max(0, ccv_min(bp[x * bminc + 1] + bp[x * bminc + 3], bp[y * bminc + 1] + bp[y * bminc + 3]) - ccv_max(bp[x * bminc + 1], bp[y * bminc + 1])); const float ydiff = ccv_max(0, ccv_min(bp[x * bminc + 2] + bp[x * bminc + 4], bp[y * bminc + 2] + bp[y * bminc + 4]) - ccv_max(bp[x * bminc + 2], bp[y * bminc + 2])); const float intersection = xdiff * ydiff; const float iou = intersection / (area1 + area2 - intersection); if (iou >= iou_threshold) bp[y * bminc] = -FLT_MAX; } } for (x = 0, y = 0; x < m; x++) if (bp[x * bminc] != -FLT_MAX) { int j; if (x != y) { for (j = 0; j < 5; j++) bp[y * bminc + j] = bp[x * bminc + j]; cp[y] = cp[x]; } ++y; } for (x = y; x < m; x++) cp[x] = -1, bp[x * bminc] = -FLT_MAX; } parallel_endfor } return CCV_NNC_EXEC_SUCCESS; } static int _ccv_nnc_nms_back(const ccv_nnc_cmd_t cmd, const ccv_nnc_hint_t hint, const int flags, ccv_nnc_tensor_t* const* const inputs, const int input_size, ccv_nnc_tensor_t* const* const outputs, const int output_size, ccv_nnc_stream_context_t* const stream_context) { assert(input_size >= 5); const ccv_nnc_tensor_view_t* a = (ccv_nnc_tensor_view_t*)inputs[0]; const ccv_nnc_tensor_view_t* c = (ccv_nnc_tensor_view_t*)inputs[4]; assert(output_size == 1); ccv_nnc_tensor_view_t* b = (ccv_nnc_tensor_view_t*)outputs[0]; const int a_nd = ccv_nnc_tensor_nd(a->info.dim); const int b_nd = ccv_nnc_tensor_nd(b->info.dim); const int c_nd = ccv_nnc_tensor_nd(c->info.dim); assert(a_nd == b_nd); int i; for (i = 0; i < a_nd; i++) { assert(a->info.dim[i] == b->info.dim[i]); } const int* ainc = CCV_IS_TENSOR_VIEW(a) ? a->inc : a->info.dim; const int* binc = CCV_IS_TENSOR_VIEW(b) ? b->inc : b->info.dim; const int* cinc = CCV_IS_TENSOR_VIEW(c) ? c->inc : c->info.dim; const int n = a_nd >= 3 ? a->info.dim[0] : 1; const int aninc = a_nd >= 3 ? ainc[1] * ainc[2] : 0; const int bninc = b_nd >= 3 ? binc[1] * binc[2] : 0; const int cninc = c_nd >= 2 ? cinc[1] : 0; const int m = a_nd >= 3 ? a->info.dim[1] : a->info.dim[0]; if (c_nd == 1) { assert(m == c->info.dim[0]); } else { assert(c_nd == 2 && n == c->info.dim[0] && m == c->info.dim[1]); } const int aminc = ainc[a_nd - 1]; const int bminc = binc[b_nd - 1]; const int d = a_nd <= 1 ? 1 : a->info.dim[a_nd - 1]; parallel_for(i, n) { int x, y; const float* const ap = a->data.f32 + i * aninc; const int* const cp = c->data.i32 + i * cninc; float* const bp = b->data.f32 + i * bninc; for (x = 0; x < m; x++) for (y = 0; y < d; y++) bp[x * bminc + y] = 0; for (x = 0; x < m; x++) { const int k = cp[x]; if (k < 0) break; for (y = 0; y < d; y++) bp[k * bminc + y] = ap[x * aminc + y]; } } parallel_endfor return CCV_NNC_EXEC_SUCCESS; } REGISTER_COMMAND_BACKEND(CCV_NNC_NMS_FORWARD, CCV_NNC_BACKEND_CPU_REF)(ccv_nnc_cmd_backend_registry_t* const registry) { registry->tensor_formats = CCV_TENSOR_FORMAT_NHWC | CCV_TENSOR_FORMAT_NCHW; registry->tensor_datatypes = CCV_32F | CCV_32S; registry->tensor_memory = CCV_TENSOR_CPU_MEMORY; registry->algorithms = 1; registry->exec = _ccv_nnc_nms_forw; } REGISTER_COMMAND_BACKEND(CCV_NNC_NMS_BACKWARD, CCV_NNC_BACKEND_CPU_REF)(ccv_nnc_cmd_backend_registry_t* const registry) { registry->tensor_formats = CCV_TENSOR_FORMAT_NHWC | CCV_TENSOR_FORMAT_NCHW; registry->tensor_datatypes = CCV_32F | CCV_32S; registry->tensor_memory = CCV_TENSOR_CPU_MEMORY; registry->algorithms = 1; registry->exec = _ccv_nnc_nms_back; }
34.566802
269
0.578004
0aced9d908175abddbfec7fa93f5e0ca3ad46abc
201
rs
Rust
jormungandr/src/log/mod.rs
cleverca22/jormungandr
852f82e3ab55896565d33cda55b931913e3f299e
[ "Apache-2.0", "MIT" ]
null
null
null
jormungandr/src/log/mod.rs
cleverca22/jormungandr
852f82e3ab55896565d33cda55b931913e3f299e
[ "Apache-2.0", "MIT" ]
null
null
null
jormungandr/src/log/mod.rs
cleverca22/jormungandr
852f82e3ab55896565d33cda55b931913e3f299e
[ "Apache-2.0", "MIT" ]
null
null
null
mod asyncable_drain; mod json_drain; pub use self::asyncable_drain::AsyncableDrain; pub use self::json_drain::JsonDrain; pub const KEY_TASK: &str = "task"; pub const KEY_SUB_TASK: &str = "sub_task";
22.333333
46
0.761194
db9fd67902d72e5454c4dd5ebd35796c0e5947a5
139
php
PHP
_config.php
qunabucom/silverstripe-blocks
787de164428bd505a818a7a27e37029b7db08f2a
[ "BSD-3-Clause" ]
null
null
null
_config.php
qunabucom/silverstripe-blocks
787de164428bd505a818a7a27e37029b7db08f2a
[ "BSD-3-Clause" ]
null
null
null
_config.php
qunabucom/silverstripe-blocks
787de164428bd505a818a7a27e37029b7db08f2a
[ "BSD-3-Clause" ]
2
2017-07-31T14:22:51.000Z
2017-08-01T13:49:08.000Z
<?php if (!defined('SS_QUNABU_BLOCKS_DIR')) { define('SS_QUNABU_BLOCKS_DIR', basename(rtrim(dirname(__FILE__), DIRECTORY_SEPARATOR))); }
27.8
90
0.755396
b74bbc80eb268e57feaa92f26ba3c43df8ab73c6
981
cs
C#
TDLib.Api/Functions/RemoveContacts.cs
mostafa8026/tdsharp
ccf55a3137da924e74b9e1d2f2fcd5c78fc05e65
[ "MIT" ]
null
null
null
TDLib.Api/Functions/RemoveContacts.cs
mostafa8026/tdsharp
ccf55a3137da924e74b9e1d2f2fcd5c78fc05e65
[ "MIT" ]
null
null
null
TDLib.Api/Functions/RemoveContacts.cs
mostafa8026/tdsharp
ccf55a3137da924e74b9e1d2f2fcd5c78fc05e65
[ "MIT" ]
null
null
null
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public partial class TdApi { /// <summary> /// Removes users from the contact list /// </summary> public class RemoveContacts : Function<Ok> { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "removeContacts"; /// <summary> /// Extra data attached to the message /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } /// <summary> /// Identifiers of users to be deleted /// </summary> [JsonConverter(typeof(Converter))] [JsonProperty("user_ids")] public int[] UserIds { get; set; } } } }
27.25
77
0.497452
07bbdc35eaac29728808bf9e9715b26ad22f01c3
418
rb
Ruby
src/compiler/processors/uncomplexify.rb
thomas-pendragon/dablang
f8e1e0835138b6dc6a675da231e176ca20b1347a
[ "MIT" ]
2
2017-06-02T02:55:36.000Z
2017-06-02T22:15:46.000Z
src/compiler/processors/uncomplexify.rb
thomas-pendragon/dablang
f8e1e0835138b6dc6a675da231e176ca20b1347a
[ "MIT" ]
1
2020-06-19T15:58:33.000Z
2020-06-19T15:58:33.000Z
src/compiler/processors/uncomplexify.rb
thomas-pendragon/dablang
f8e1e0835138b6dc6a675da231e176ca20b1347a
[ "MIT" ]
1
2017-06-02T22:17:52.000Z
2017-06-02T22:17:52.000Z
class Uncomplexify def run(node) return unless complex_arg = node.uncomplexify_args.detect { |arg| !node.accepts?(arg) } id = node.function.allocate_tempvar arg_dup = complex_arg.dup reg = node.function.allocate_ssa setter = DabNodeSSASet.new(arg_dup, reg, id) getter = DabNodeSSAGet.new(reg, id) node.prepend_instruction(setter) complex_arg.replace_with!(getter) true end end
27.866667
91
0.720096
da8d5d92ee500cbd9bd239ffae962eb0e61c78e9
1,459
php
PHP
app/Http/routes.php
BooMamoo/website
420cc6f578af50f70814fbe9275e19c7fd52d802
[ "MIT" ]
null
null
null
app/Http/routes.php
BooMamoo/website
420cc6f578af50f70814fbe9275e19c7fd52d802
[ "MIT" ]
null
null
null
app/Http/routes.php
BooMamoo/website
420cc6f578af50f70814fbe9275e19c7fd52d802
[ "MIT" ]
null
null
null
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::post('/user/login', 'UserController@login'); Route::post('/user/register', 'UserController@register'); Route::get('/user/logout', 'UserController@logout'); Route::get('/user/permission', 'UserController@index'); Route::post('/admin/local', 'UserController@local'); Route::get('/data/local', 'DataController@local'); Route::get('/data/local/{local_id}/device', 'DataController@device'); Route::get('/data/device/{device_id}/info', 'DataController@getInfo'); Route::get('/data/device/{device_id}/type/{type_id}/data', 'DataController@getData'); Route::get('/data/device/{device_id}/type/{type_id}/current', 'DataController@getCurrentData'); Route::get('/data/device/{device_id}/type/{type_id}/chart', 'DataController@chart'); Route::get('/data/gateway', 'GatewayController@index'); Route::post('/store/gateway', 'GatewayController@store'); Route::get('/download/gateway/{gateway_id}', 'GatewayController@download'); Route::get('/', [ 'as' => 'root', 'uses' => 'IndexController@index' ]); Route::get('{any}', 'IndexController@index')->where('any', '.*');
39.432432
95
0.636737
f4555e1cc628d1f218d1fb28112f3c7416924e53
1,023
ts
TypeScript
frontend/src/pages/HomePage/Header/styled.ts
cesko-digital/zacni-uc
281c56aec5509d5dd8bbbd60f054ffcd9156609e
[ "MIT" ]
4
2021-02-26T09:28:14.000Z
2021-07-08T19:21:57.000Z
frontend/src/pages/HomePage/Header/styled.ts
cesko-digital/zacni-uc
281c56aec5509d5dd8bbbd60f054ffcd9156609e
[ "MIT" ]
35
2021-01-27T08:38:59.000Z
2021-12-13T19:42:38.000Z
frontend/src/pages/HomePage/Header/styled.ts
cesko-digital/zacni-uc
281c56aec5509d5dd8bbbd60f054ffcd9156609e
[ "MIT" ]
5
2021-01-21T21:35:42.000Z
2022-01-06T10:07:58.000Z
import { mediaQueriesUp } from 'src/common/mediaQueries'; import styled from 'styled-components'; export const Wrapper = styled.div` position: relative; padding: 32px 130px 0 0; ${mediaQueriesUp('sm')` padding: 80px 130px 0 0; `} `; export const MainTitle = styled.h1` font-size: 2rem; margin: 0; padding: 0; ${mediaQueriesUp('sm')` font-size: 5rem; margin: 0 0 -20px; `} ${mediaQueriesUp('md')` font-size: 6rem; `} `; export const CanITeachButtonWrapper = styled.div` display: flex; align-items: center; margin-bottom: 30px; ` export const ButtonWrapper = styled.span` margin-right: 16px; &:last-child { margin: 0; } `; export const LinksWrapper = styled.div` width: calc(100% + 100px); `; export const Image = styled.img` position: absolute; top: 0; right: -16px; ${mediaQueriesUp('sm')` top: 80px; `} `; export const Paragraph = styled.p` max-width: 90%; margin-bottom: 30px; ${mediaQueriesUp('sm')` font-size: 1.5rem; `} `;
15.984375
57
0.638319
4378ea5c6d909ceb5cc003b7ead65725153a1802
647
ts
TypeScript
src/store/reducers.ts
dnlnav/booking-mask-exercise
c3252a8bdd10ba49eaea73ab3bedd431fc95ff61
[ "MIT" ]
null
null
null
src/store/reducers.ts
dnlnav/booking-mask-exercise
c3252a8bdd10ba49eaea73ab3bedd431fc95ff61
[ "MIT" ]
null
null
null
src/store/reducers.ts
dnlnav/booking-mask-exercise
c3252a8bdd10ba49eaea73ab3bedd431fc95ff61
[ "MIT" ]
null
null
null
import { searchAirportCodes } from './thunks'; import { createSlice, PayloadAction } from '@reduxjs/toolkit'; export interface stateType { airportList: string[][]; } const initialState: stateType = { airportList: [], }; const bookingReducer = createSlice({ name: 'booking', initialState, reducers: { emptyAirportList(state) { state.airportList = []; }, }, extraReducers: (builder) => builder.addCase(searchAirportCodes.fulfilled, (state, action) => { state.airportList = action.payload || []; }), }); export const { emptyAirportList } = bookingReducer.actions; export default bookingReducer.reducer;
22.310345
70
0.681607
3f75461929d9c5de1d7c5d732d59a14dfb5f1624
2,205
swift
Swift
Metal Archives/Metal Archives/Models/Search/SimpleSearch/SimpleSearchResultMusicGenre.swift
ntnhon/Metal-Archives-iOS
274527b791c90b916511d76f6e37982fb5742a42
[ "Apache-2.0" ]
15
2019-04-05T07:27:56.000Z
2021-12-27T02:05:17.000Z
Metal Archives/Metal Archives/Models/Search/SimpleSearch/SimpleSearchResultMusicGenre.swift
ntnhon/Metal-Archives-iOS
274527b791c90b916511d76f6e37982fb5742a42
[ "Apache-2.0" ]
7
2020-08-05T06:30:23.000Z
2021-04-01T07:59:08.000Z
Metal Archives/Metal Archives/Models/Search/SimpleSearch/SimpleSearchResultMusicGenre.swift
ntnhon/Metal-Archives-iOS
274527b791c90b916511d76f6e37982fb5742a42
[ "Apache-2.0" ]
5
2019-04-05T07:28:00.000Z
2022-03-04T13:26:01.000Z
// // SimpleSearchResultMusicGenre.swift // Metal Archives // // Created by Thanh-Nhon Nguyen on 05/03/2019. // Copyright © 2019 Thanh-Nhon Nguyen. All rights reserved. // import Foundation final class SimpleSearchResultMusicGenre: SimpleSearchResultBandNameOrMusicGenre, Pagable { static var rawRequestURLString = "https://www.metal-archives.com/search/ajax-band-search/?field=genre&query=<QUERY>&sEcho=2&iColumns=3&sColumns=&iDisplayStart=<DISPLAY_START>&iDisplayLength=200&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2" static var displayLength = 200 init?(from array: [String]) { var band: BandLite? var aka: String? if array.indices.contains(0) { var bandName: String? var urlString: String? if let subString = array[0].subString(after: "\">", before: "</a>", options: .caseInsensitive) { bandName = String(subString) } if let subString = array[0].subString(after: "href=\"", before: "\">", options: .caseInsensitive) { urlString = String(subString) } if let `bandName` = bandName, let `urlString` = urlString { band = BandLite(name: bandName, urlString: urlString) } if array[0].contains("a.k.a") { if let subString = array[0].subString(after: "</a> (", before: ")", options: .caseInsensitive) { aka = subString.replacingOccurrences(of: "<strong>", with: "").replacingOccurrences(of: "</strong>", with: "") } } } let genre: String? = array.indices.contains(1) ? array[1] : nil let countryName: String? = array.indices.contains(2) ? array[2] : nil var country: Country? if let countryName = countryName { country = Country(name: countryName) } if let band = band, let genre = genre, let country = country { super.init(band: band, aka: aka, genre: genre, country: country) } else { return nil } } }
36.75
240
0.560091
5a2d9a68b7f7e6eb0caa473b075c0042cd8176ba
2,057
ps1
PowerShell
tests/scripts/TakePackageOwnership.ps1
ArianGhotbiMSFT/MSIX-PackageSupportFramework
0aed87768099b85415cf0a0af921c187e0cf23ed
[ "MIT" ]
63
2019-05-22T01:20:59.000Z
2022-03-24T03:34:00.000Z
tests/scripts/TakePackageOwnership.ps1
riverar/MSIX-PackageSupportFramework
a424e79c9d47f6004c37200d972475e5a82b94f6
[ "MIT" ]
79
2019-05-24T22:17:31.000Z
2022-03-23T21:54:49.000Z
tests/scripts/TakePackageOwnership.ps1
riverar/MSIX-PackageSupportFramework
a424e79c9d47f6004c37200d972475e5a82b94f6
[ "MIT" ]
34
2019-07-15T17:14:00.000Z
2022-03-24T03:34:03.000Z
<# .DESCRIPTION Changes the ownership of all executables, dlls, and a few key files in a package's root path to the device's administrator group. Note that you must have permission to replace these files.This script must be run from an admin Powershell command window .PARAMETER Name The package name (note: _not_ family name/full name) of the package you wish to replace binaries for. Wildcards are technically allowed, in which case this will execute for any package returned by 'Get-AppxPackage' #> [CmdletBinding()] Param ( [Parameter(Mandatory=$True)] [string]$Name ) function TakeOwnership($pkg) { # All files we want to take ownership of live at the root of the package path $pkgRoot = $pkg.InstallLocation $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators", "FullControl", "Allow") function Impl($path) { Write-Verbose "Taking ownership of $path" # First take ownership takeown.exe /F "$path" /A | Out-Null if ($LASTEXITCODE -ne 0) { throw "Failed to take ownership of $path" } # Give full control to admin $acl = Get-Acl "$path" if ($acl) { $acl.SetAccessRule($accessRule) Set-Acl "$path" $acl } else { Write-Warning "Failed to get ACL for $path" } if ((Get-Item $path).Attributes -eq [System.IO.FileAttributes]::Directory) { foreach ($item in (Get-ChildItem $path)) { Impl $item.FullName } } } # Change ownership permissions for all executables, dlls, and files we may want to replace in the root directory to admin Impl $pkg.InstallLocation } $packages = Get-AppxPackage -Name $Name if ($packages -is [array]) { foreach ($pkg in $packages) { TakeOwnership $pkg } } else { TakeOwnership $packages }
27.426667
126
0.60282
b6eb803b24d8aa4d3413a0a724e85f7b2e59d0bf
26
sql
SQL
spec/util/testQuery.sql
wms/collimator
77d5e92f412da7a551007e8dab3bf777fb82f04a
[ "BSD-3-Clause" ]
6
2016-05-12T19:02:39.000Z
2017-06-28T14:22:27.000Z
spec/util/testQuery.sql
wms/collimator
77d5e92f412da7a551007e8dab3bf777fb82f04a
[ "BSD-3-Clause" ]
6
2016-01-14T03:34:32.000Z
2016-06-24T18:46:38.000Z
spec/util/testQuery.sql
wms/collimator
77d5e92f412da7a551007e8dab3bf777fb82f04a
[ "BSD-3-Clause" ]
3
2016-01-13T12:43:27.000Z
2016-06-24T14:47:35.000Z
SELECT * FROM test_query;
13
25
0.769231
976666a191f25b26ba4c9c4cab8e7f41643babd2
1,201
ts
TypeScript
src/app/maps/maps.module.ts
whileLooper/small_finance_app
c7078f6353784190ce3410d29356d31c567c98a0
[ "MIT" ]
null
null
null
src/app/maps/maps.module.ts
whileLooper/small_finance_app
c7078f6353784190ce3410d29356d31c567c98a0
[ "MIT" ]
null
null
null
src/app/maps/maps.module.ts
whileLooper/small_finance_app
c7078f6353784190ce3410d29356d31c567c98a0
[ "MIT" ]
null
null
null
import 'jvectormap/jquery-jvectormap.min.js'; import 'jvectormap-world/jquery-jvectormap-world-mill-en.js'; import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AlertModule, TooltipModule } from 'ngx-bootstrap'; import { ButtonsModule, BsDropdownModule } from 'ngx-bootstrap'; import { AgmCoreModule } from '@agm/core'; import { MapsGoogleComponent } from './google/maps-google.component'; import { MapsVectorComponent } from './vector/maps-vector.component'; export const routes = [ {path: '', redirectTo: 'google', pathMatch: 'full'}, {path: 'google', component: MapsGoogleComponent}, {path: 'vector', component: MapsVectorComponent} ]; @NgModule({ declarations: [ // Components / Directives/ Pipes MapsGoogleComponent, MapsVectorComponent ], imports: [ CommonModule, RouterModule.forChild(routes), AlertModule.forRoot(), TooltipModule.forRoot(), ButtonsModule.forRoot(), BsDropdownModule.forRoot(), AgmCoreModule.forRoot({ apiKey: 'AIzaSyDe_oVpi9eRSN99G4o6TwVjJbFBNr58NxE' }) ] }) export class MapsModule { static routes = routes; }
28.595238
69
0.71607
dd85b03d5b34e45bc3cc048ed79a5dbcb10638b9
2,035
java
Java
src/main/java/nl/clockwork/ebms/admin/web/LocalDateTimeConverter.java
eluinstra/ebms-admin
c08fb15b0bcba0452d0cad9d08ee8e67ba7e888f
[ "Apache-2.0" ]
2
2020-08-25T09:53:04.000Z
2021-02-16T10:13:50.000Z
src/main/java/nl/clockwork/ebms/admin/web/LocalDateTimeConverter.java
eluinstra/ebms-admin
c08fb15b0bcba0452d0cad9d08ee8e67ba7e888f
[ "Apache-2.0" ]
9
2020-07-23T19:26:40.000Z
2021-12-14T21:51:52.000Z
src/main/java/nl/clockwork/ebms/admin/web/LocalDateTimeConverter.java
eluinstra/ebms-admin
c08fb15b0bcba0452d0cad9d08ee8e67ba7e888f
[ "Apache-2.0" ]
2
2021-08-16T14:52:53.000Z
2021-12-13T21:45:52.000Z
/** * Copyright 2013 Clockwork * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.clockwork.ebms.admin.web; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Locale; import org.apache.wicket.util.convert.ConversionException; import org.apache.wicket.util.convert.IConverter; import org.apache.wicket.util.string.Strings; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.val; import lombok.experimental.FieldDefaults; @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) @AllArgsConstructor public class LocalDateTimeConverter implements IConverter<LocalDateTime> { private static final long serialVersionUID = 1L; @NonNull String datePattern; @Override public LocalDateTime convertToObject(String value, Locale locale) { if (Strings.isEmpty(value)) return null; try { val date = LocalDate.from(DateTimeFormatter.ofPattern(datePattern).parse(value)); val time = LocalTime.MIDNIGHT; return LocalDateTime.of(date,time); } catch (RuntimeException e) { throw newConversionException(e,locale); } } private ConversionException newConversionException(RuntimeException cause, Locale locale) { return new ConversionException(cause).setVariable("format",datePattern); } @Override public String convertToString(LocalDateTime value, Locale locale) { return DateTimeFormatter.ofPattern(datePattern).format(value); } }
29.071429
90
0.779361
a35a0153c8b1ff4fa217244d46a6c5bc79f9ef36
4,971
java
Java
TreeRowSelection/src/java/example/MainPanel.java
OctaviantoVyan/jwswing
e2873359ed23b8baeeb89c1dcf99225dd541f6b4
[ "MIT" ]
null
null
null
TreeRowSelection/src/java/example/MainPanel.java
OctaviantoVyan/jwswing
e2873359ed23b8baeeb89c1dcf99225dd541f6b4
[ "MIT" ]
null
null
null
TreeRowSelection/src/java/example/MainPanel.java
OctaviantoVyan/jwswing
e2873359ed23b8baeeb89c1dcf99225dd541f6b4
[ "MIT" ]
null
null
null
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import javax.swing.*; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JPanel p = new JPanel(new GridLayout(1, 2)); p.add(new JScrollPane(new JTree())); p.add(new JScrollPane(new RowSelectionTree())); add(p); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class RowSelectionTree extends JTree { private static final Color SELECTED_COLOR = new Color(0x64_96_C8); // private Handler handler; @Override protected void paintComponent(Graphics g) { int[] sr = getSelectionRows(); if (sr == null) { super.paintComponent(g); return; } g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(SELECTED_COLOR); // for (int i : sr) { // Rectangle r = getRowBounds(i); // g2.fillRect(0, r.y, getWidth(), r.height); // } Arrays.stream(sr).mapToObj(this::getRowBounds) .forEach(r -> g2.fillRect(0, r.y, getWidth(), r.height)); super.paintComponent(g); if (hasFocus()) { Optional.ofNullable(getLeadSelectionPath()).ifPresent(path -> { Rectangle r = getRowBounds(getRowForPath(path)); g2.setPaint(SELECTED_COLOR.darker()); g2.drawRect(0, r.y, getWidth() - 1, r.height - 1); }); // TreePath path = getLeadSelectionPath(); // if (Objects.nonNull(path)) { // Rectangle r = getRowBounds(getRowForPath(path)); // g2.setPaint(SELECTED_COLOR.darker()); // g2.drawRect(0, r.y, getWidth() - 1, r.height - 1); // } } g2.dispose(); } @Override public void updateUI() { // removeFocusListener(handler); setCellRenderer(null); super.updateUI(); setUI(new BasicTreeUI() { @Override public Rectangle getPathBounds(JTree tree, TreePath path) { if (Objects.nonNull(tree) && Objects.nonNull(treeState)) { return getPathBounds2(path, tree.getInsets(), new Rectangle()); } return null; } private Rectangle getPathBounds2(TreePath path, Insets insets, Rectangle bounds) { Rectangle rect = treeState.getBounds(path, bounds); if (Objects.nonNull(rect)) { rect.width = tree.getWidth(); rect.y += insets.top; } return rect; } }); UIManager.put("Tree.repaintWholeRow", Boolean.TRUE); // handler = new Handler(); // addFocusListener(handler); TreeCellRenderer r = getCellRenderer(); setCellRenderer((tree, value, selected, expanded, leaf, row, hasFocus) -> { Component c = r.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); c.setBackground(selected ? SELECTED_COLOR : tree.getBackground()); if (c instanceof JComponent) { ((JComponent) c).setOpaque(true); } return c; }); setOpaque(false); } } // class Handler extends DefaultTreeCellRenderer { // implements FocusListener { // @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // Component c = super.getTreeCellRendererComponent( // tree, value, selected, expanded, leaf, row, hasFocus); // c.setBackground(selected ? SELECTED_COLOR : tree.getBackground()); // if (c instanceof JComponent) { // ((JComponent) c).setOpaque(true); // } // return c; // } // // // @Override public void focusGained(FocusEvent e) { // // e.getComponent().repaint(); // // } // // // @Override public void focusLost(FocusEvent e) { // // e.getComponent().repaint(); // // // TEST: // // // if (Objects.nonNull(tree.getLeadSelectionPath())) { // // // Rectangle r = tree.getRowBounds(tree.getRowForPath(tree.getLeadSelectionPath())); // // // r.width += r.x; // // // r.x = 0; // // // tree.repaint(r); // // // } // // } // }
34.047945
165
0.641521
e8a5b90b05b1064480bfdfb496c9d757b9790860
3,182
lua
Lua
hydro/tooltip.lua
thenumbernine/hydro-cl-lua
857ac71ba8f5cf722a1b43789cde1693e9ecf7b7
[ "MIT" ]
15
2016-10-11T18:50:34.000Z
2021-12-21T01:32:28.000Z
hydro/tooltip.lua
thenumbernine/hydro-cl-lua
857ac71ba8f5cf722a1b43789cde1693e9ecf7b7
[ "MIT" ]
null
null
null
hydro/tooltip.lua
thenumbernine/hydro-cl-lua
857ac71ba8f5cf722a1b43789cde1693e9ecf7b7
[ "MIT" ]
2
2018-08-03T01:49:36.000Z
2018-10-16T23:51:13.000Z
-- wrapper for imgui stuff to put a tooltip over it (and give it no title) -- (and push/pop id strs so the no-title doesn't cause a problem) local ffi = require 'ffi' local ig = require 'ffi.imgui' local table = require 'ext.table' local function hoverTooltip(name) if ig.igIsItemHovered(ig.ImGuiHoveredFlags_None) then ig.igBeginTooltip() ig.igText(name) ig.igEndTooltip() end end local function makeWrapTooltip(f) return function(name, ...) ig.igPushIDStr(name) local result = f('', ...) hoverTooltip(name) ig.igPopID() return result end end local function tooltipLabel(label, str) ig.igPushIDStr(label) ig.igText(str) hoverTooltip(label) ig.igPopID() end -- naive wrappers of makeWrapTooltip local wrap = table.map({ slider = ig.igSliderFloat, combo = ig.igCombo, button = ig.igButton, float = ig.igInputFloat, int = ig.igInputInt, checkbox = ig.igCheckbox, text = ig.igInputText, }, function(f, wrapName) return makeWrapTooltip(f), wrapName end) -- wrappers for table[key] access rather than ffi-allocated primitive access local function makeTableAccess(prim, orig) local ptr = ffi.new(prim..'[1]') return function(title, t, k, ...) if t[k] == nil then error("failed to find value "..k.." in table "..tostring(t)) end ptr[0] = t[k] if orig(title, ptr, ...) then t[k] = ptr[0] return true end end end local checkboxTable = makeTableAccess('bool', wrap.checkbox) local intTable = makeTableAccess('int', wrap.int) local sliderTable = makeTableAccess('float', wrap.slider) -- unlike others, this is a bit more than simple ffi primitive read/write -- because imgui's float formatting isn't very flexible -- also not 'tableFloat' because of the higher accuracy of double/string than float/string serializing local buf = ffi.new'char[256]' local function numberTable(title, t, k, ...) local s = tostring(t[k]) ffi.copy(buf, s, ffi.sizeof(buf)) -- TODO maybe ig.ImGuiInputTextFlags_EnterReturnsTrue if wrap.text(title, buf, ffi.sizeof(buf), ...) then local s = ffi.string(buf, ffi.sizeof(buf)) local v = tonumber(s) if v then t[k] = v return true end end end -- here's another exception: combo boxes -- because t[k] is Lua-based, lets make our values 1-based instead of 0-based local int = ffi.new'int[1]' local function comboTable(title, t, k, ...) assert(t[k]) assert(type(t[k]) == 'number') int[0] = t[k]-1 if wrap.combo(title, int, ...) then t[k] = int[0]+1 return true end end -- TODO dynamic sized buffer? local str = ffi.new'char[256]' local function textTable(title, t, k, ...) local src = tostring(t[k]) local len = math.min(ffi.sizeof(str)-1, #src) ffi.copy(str, src, len) str[len] = 0 if wrap.text(title, str, ffi.sizeof(str), ...) then t[k] = ffi.string(str) return true end end -- tooltip wrappers local tooltip = { button = wrap.button, checkbox = wrap.checkbox, combo = wrap.combo, float = wrap.float, int = wrap.int, slider = wrap.slider, sliderTable = sliderTable, checkboxTable = checkboxTable, intTable = intTable, numberTable = numberTable, comboTable = comboTable, text = wrap.text, textTable = textTable, label = tooltipLabel, } return tooltip
24.106061
102
0.700503
0a88a41a80c714757f313a802c52cd735153266b
802
lua
Lua
Mods ChoGGi/Fix InDome Buildings Pack Logos/metadata.lua
aiawar/SurvivingMars_CheatMods
079c523be3c443b0aa911102e0bdfa20be11a639
[ "MIT" ]
64
2018-03-27T02:05:29.000Z
2022-02-28T09:44:22.000Z
Mods ChoGGi/Fix InDome Buildings Pack Logos/metadata.lua
aiawar/SurvivingMars_CheatMods
079c523be3c443b0aa911102e0bdfa20be11a639
[ "MIT" ]
50
2018-03-23T09:43:21.000Z
2022-03-27T02:48:04.000Z
Mods ChoGGi/Fix InDome Buildings Pack Logos/metadata.lua
aiawar/SurvivingMars_CheatMods
079c523be3c443b0aa911102e0bdfa20be11a639
[ "MIT" ]
54
2018-03-25T23:12:12.000Z
2022-03-02T15:10:20.000Z
return PlaceObj("ModDef", { "title", "Fix InDome Buildings Pack Logos", "id", "ChoGGi_FixInDomeBuildingsPackLogos", "steam_id", "2538526304", "pops_any_uuid", "e06f1b9b-46c9-4978-ac43-039132a8aca1", "lua_revision", 1007000, -- Picard "version", 1, "version_major", 0, "version_minor", 1, "image", "Preview.jpg", "author", "ChoGGi", "code", { "Code/Script.lua", }, "has_options", true, "TagOther", true, "description", [[ The logos don't show up on rockets or other buildings. I'm a little surprised no one mentioned it till now? (or I haven't seen mention till now) This mod will be updated when a fixed version is released to disable it. https://forum.paradoxplaza.com/forum/threads/surviving-mars-new-logos-do-not-display-on-rockets-mars-in-dome-building-pack-dlc.1482063/ ]], })
29.703704
135
0.715711
a141d2cc4e06aef5b5381bd3f1691545b54d5824
927
ts
TypeScript
it/EatAction.ts
bsneade/utility-agent
a579d69c80e75800e35643697b28d1e4ff0387ff
[ "MIT" ]
1
2017-06-17T03:13:56.000Z
2017-06-17T03:13:56.000Z
it/EatAction.ts
bsneade/utility-agent
a579d69c80e75800e35643697b28d1e4ff0387ff
[ "MIT" ]
3
2019-07-19T19:45:07.000Z
2021-07-21T18:42:36.000Z
it/EatAction.ts
bsneade/utility-agent
a579d69c80e75800e35643697b28d1e4ff0387ff
[ "MIT" ]
1
2017-06-17T03:48:10.000Z
2017-06-17T03:48:10.000Z
import { Action, Context } from ".."; export class EatAction implements Action { name = "Eat"; execute(context: Context): Promise<Context> { return new Promise((resolve, reject) => { const itContext = <ITContext> context; if (itContext.hunger > 0) { itContext.hunger -= .4; // less hunger per tick for eating if (itContext.hunger < 0) { itContext.hunger = 0; } console.info(`Eating. Hunger now ${itContext.hunger}`); } else { console.warn(`Already saited. Waiting instead.`); // TODO - invoke the wait action } resolve(context); }) as Promise<Context>; } terminated(context: Context): Context { console.info("Terminated EatAction"); return context; } } import { ITContext } from "./ITContext";
30.9
74
0.530744
ddc17bbcd8f4edc80a53ac16a81cd0657a451700
718
java
Java
src/main/java/work/lclpnet/mmo/facade/character/DynamicCharacterData.java
LCLPYT/LCLPMMO
4010ff62e77cdcac1268878976c350334ba1a533
[ "MIT" ]
1
2021-01-27T11:54:10.000Z
2021-01-27T11:54:10.000Z
src/main/java/work/lclpnet/mmo/facade/character/DynamicCharacterData.java
LCLPYT/LCLPMMO
4010ff62e77cdcac1268878976c350334ba1a533
[ "MIT" ]
5
2021-02-22T22:21:08.000Z
2022-01-18T14:21:53.000Z
src/main/java/work/lclpnet/mmo/facade/character/DynamicCharacterData.java
LCLPYT/LCLPMMO
4010ff62e77cdcac1268878976c350334ba1a533
[ "MIT" ]
null
null
null
package work.lclpnet.mmo.facade.character; import com.google.gson.annotations.Expose; import work.lclpnet.mmo.facade.DynamicData; import work.lclpnet.mmo.facade.quest.QuestBook; public class DynamicCharacterData extends DynamicData { /* * Make sure the JSON representation of this object is as small as possible. * If possible, set default values to null. * Also make sure field names aren't too long. */ @Expose public Integer tutorialState = null; @Expose private final QuestBook questBook = null; public QuestBook getQuestBook() { return questBook; } public static DynamicCharacterData empty() { return new DynamicCharacterData(); } }
26.592593
81
0.707521
e84be06535881504bdcbe367831df74fb9656da7
2,557
cs
C#
WlToolsLib/JsonHelper/NewtonExpandFunc.cs
wlfsky/WLToolsLib
b3bcd70c4fc122e09d0763322725630f1a4e3d9b
[ "MIT" ]
null
null
null
WlToolsLib/JsonHelper/NewtonExpandFunc.cs
wlfsky/WLToolsLib
b3bcd70c4fc122e09d0763322725630f1a4e3d9b
[ "MIT" ]
null
null
null
WlToolsLib/JsonHelper/NewtonExpandFunc.cs
wlfsky/WLToolsLib
b3bcd70c4fc122e09d0763322725630f1a4e3d9b
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WlToolsLib.Expand; namespace WlToolsLib.JsonHelper { #region --json扩展-- /// <summary> /// json扩展方法 /// </summary> public static class JsonExpandFunc { /// <summary> /// 对象转换json, 全转换 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="self"></param> /// <returns></returns> public static string ToJson<T>(this T self) { IJsonHelper jh = new NewtonJsonHelper(); var jsonStr = jh.Serialize<T>(self); return jsonStr; } /// <summary> /// 对象转换json,指定字段转换 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="self"></param> /// <returns></returns> public static string ToJson<T>(this T self, IList<string> showField) { if (showField.IsNull()) { showField = new List<string>(); } IJsonHelper jh = new NewtonJsonHelper(); var jsonStr = jh.Serialize<T>(self, showField); return jsonStr; } /// <summary> /// 给字段组加入默认值 /// 注意只能使用在 /// </summary> /// <param name="self"></param> /// <returns></returns> public static IList<string> WithDefaultField(this IList<string> self) { return self.AddRange(new string[] { "Success", "Data", "Info", "Infos", "Version", "Time", "Code" }); } /// <summary> /// json转换对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="self"></param> /// <returns></returns> public static T ToObj<T>(this string self) { if (self.NullEmpty()) { return default(T); } IJsonHelper jh = new NewtonJsonHelper(); var result = jh.Deserialize<T>(self); return result; } /// <summary> /// 从json字符串转换成实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="self"></param> /// <returns></returns> public static T FormJson<T>(this string self) { if (self.NotNullEmpty()) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(self); } return default(T); } } #endregion --json扩展-- }
27.793478
113
0.493156
85206f40fe884c7bbb63b5712c189d909b569ab3
51,654
cs
C#
DataStructures/BinarySearchTree.cs
JUNLAN2015/DataStructure
32489d2bce687e8c6021ed10b8115031916caae5
[ "MIT" ]
null
null
null
DataStructures/BinarySearchTree.cs
JUNLAN2015/DataStructure
32489d2bce687e8c6021ed10b8115031916caae5
[ "MIT" ]
null
null
null
DataStructures/BinarySearchTree.cs
JUNLAN2015/DataStructure
32489d2bce687e8c6021ed10b8115031916caae5
[ "MIT" ]
null
null
null
using System; using System.Collections; using System.Collections.Generic; using DataStructures.Common; namespace DataStructures.Trees { public class BinarySearchTree<T> : IBinarySearchTree<T> where T : IComparable<T> { public enum TraversalMode { InOrder = 0, PreOrder = 1, PostOrder = 2 } public BinarySearchTree() { _count = 0; _allowDuplicates = true; Root = null; } public BinarySearchTree(bool allowDuplicates) { _count = 0; _allowDuplicates = allowDuplicates; Root = null; } protected int _count { get; set; } protected bool _allowDuplicates { get; set; } protected virtual BSTNode<T> _root { get; set; } public virtual BSTNode<T> Root { get { return _root; } internal set { _root = value; } } public virtual int Count { get { return _count; } } public virtual bool IsEmpty { get { return _count == 0; } } public virtual int Height { get { if (IsEmpty) return 0; var currentNode = Root; return _getTreeHeight(currentNode); } } public virtual bool AllowsDuplicates { get { return _allowDuplicates; } } public virtual void Insert(T item) { var newNode = new BSTNode<T>(item); var success = _insertNode(newNode); if (success == false && _allowDuplicates == false) throw new InvalidOperationException("Tree does not allow inserting duplicate elements."); } /// <summary> /// Inserts an array of elements to the tree. /// </summary> public virtual void Insert(T[] collection) { if (collection == null) throw new ArgumentNullException(); if (collection.Length > 0) { for (var i = 0; i < collection.Length; ++i) { Insert(collection[i]); } } } /// <summary> /// Inserts a list of elements to the tree. /// </summary> public virtual void Insert(List<T> collection) { if (collection == null) throw new ArgumentNullException(); if (collection.Count > 0) { for (var i = 0; i < collection.Count; ++i) { Insert(collection[i]); } } } /// <summary> /// Deletes an element from the tree /// </summary> /// <param name="item">item to remove.</param> public virtual void Remove(T item) { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findNode(Root, item); var status = _remove(node); // If the element was found, remove it. if (status == false) throw new Exception("Item was not found."); } /// <summary> /// Removes the min value from tree. /// </summary> public virtual void RemoveMin() { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findMinNode(Root); _remove(node); } /// <summary> /// Removes the max value from tree. /// </summary> public virtual void RemoveMax() { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findMaxNode(Root); _remove(node); } /// <summary> /// Clears all elements from tree. /// </summary> public virtual void Clear() { Root = null; _count = 0; } /// <summary> /// Checks for the existence of an item /// </summary> public virtual bool Contains(T item) { return _findNode(_root, item) != null; } /// <summary> /// Finds the minimum in tree /// </summary> /// <returns>Min</returns> public virtual T FindMin() { if (IsEmpty) throw new Exception("Tree is empty."); return _findMinNode(Root).Value; } /// <summary> /// Finds the maximum in tree /// </summary> /// <returns>Max</returns> public virtual T FindMax() { if (IsEmpty) throw new Exception("Tree is empty."); return _findMaxNode(Root).Value; } /// <summary> /// Find the item in the tree. Throws an exception if not found. /// </summary> /// <param name="item">Item to find.</param> /// <returns>Item.</returns> public virtual T Find(T item) { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findNode(Root, item); if (node != null) return node.Value; throw new Exception("Item was not found."); } /// <summary> /// Given a predicate function, find all the elements that match it. /// </summary> /// <param name="searchPredicate">The search predicate</param> /// <returns>ArrayList<T> of elements.</returns> public virtual IEnumerable<T> FindAll(Predicate<T> searchPredicate) { var list = new List<T>(); _findAll(Root, searchPredicate, ref list); return list; } /// <summary> /// Returns an array of nodes' values. /// </summary> /// <returns>The array.</returns> public virtual T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Returns a list of the nodes' value. /// </summary> public virtual List<T> ToList() { var list = new List<T>(); _inOrderTraverse(Root, ref list); return list; } /*********************************************************************/ /// <summary> /// Returns an enumerator that visits node in the order: parent, left child, right child /// </summary> public virtual IEnumerator<T> GetPreOrderEnumerator() { return new BinarySearchTreePreOrderEnumerator(this); } /// <summary> /// Returns an enumerator that visits node in the order: left child, parent, right child /// </summary> public virtual IEnumerator<T> GetInOrderEnumerator() { return new BinarySearchTreeInOrderEnumerator(this); } /// <summary> /// Returns an enumerator that visits node in the order: left child, right child, parent /// </summary> public virtual IEnumerator<T> GetPostOrderEnumerator() { return new BinarySearchTreePostOrderEnumerator(this); } /// <summary> /// Replaces the node's value from it's parent node object with the newValue. /// Used in the recusive _remove function. /// </summary> /// <param name="node">BST node.</param> /// <param name="newNode">New value.</param> protected virtual void _replaceNodeInParent(BSTNode<T> node, BSTNode<T> newNode = null) { if (node.Parent != null) { if (node.IsLeftChild) node.Parent.LeftChild = newNode; else node.Parent.RightChild = newNode; } if (newNode != null) newNode.Parent = node.Parent; } /// <summary> /// Remove the specified node. /// </summary> /// <param name="node">Node.</param> /// <returns>>True if removed successfully; false if node wasn't found.</returns> protected virtual bool _remove(BSTNode<T> node) { if (node == null) return false; var parent = node.Parent; if (node.ChildrenCount == 2) // if both children are present { var successor = node.RightChild; node.Value = successor.Value; return true && _remove(successor); } if (node.HasLeftChild) // if the node has only a LEFT child { _replaceNodeInParent(node, node.LeftChild); _count--; } else if (node.HasRightChild) // if the node has only a RIGHT child { _replaceNodeInParent(node, node.RightChild); _count--; } else //this node has no children { _replaceNodeInParent(node, null); _count--; } return true; } /// <summary> /// Inserts a new node to the tree. /// </summary> /// <param name="currentNode">Current node to insert afters.</param> /// <param name="newNode">New node to be inserted.</param> protected virtual bool _insertNode(BSTNode<T> newNode) { if (Root == null) { Root = newNode; _count++; return true; } if (newNode.Parent == null) newNode.Parent = Root; if (_allowDuplicates == false && newNode.Parent.Value.IsEqualTo(newNode.Value)) { return false; } // Go Left if (newNode.Parent.Value.IsGreaterThan(newNode.Value)) // newNode < parent { if (newNode.Parent.HasLeftChild == false) { newNode.Parent.LeftChild = newNode; _count++; return true; } newNode.Parent = newNode.Parent.LeftChild; return _insertNode(newNode); } // Go Right if (newNode.Parent.HasRightChild == false) { newNode.Parent.RightChild = newNode; _count++; return true; } newNode.Parent = newNode.Parent.RightChild; return _insertNode(newNode); } /// <summary> /// Time-complexity: O(n), where n = number of nodes. protected virtual int _getTreeHeight(BSTNode<T> node) { if (node == null) return 0; // Is leaf node if (node.IsLeafNode) return 1; // Has two children if (node.ChildrenCount == 2) return 1 + Math.Max(_getTreeHeight(node.LeftChild), _getTreeHeight(node.RightChild)); // Has only left if (node.HasLeftChild) return 1 + _getTreeHeight(node.LeftChild); // Has only right return 1 + _getTreeHeight(node.RightChild); } protected virtual BSTNode<T> _findNode(BSTNode<T> currentNode, T item) { if (currentNode == null) return currentNode; if (item.IsEqualTo(currentNode.Value)) { return currentNode; } if (currentNode.HasLeftChild && item.IsLessThan(currentNode.Value)) { return _findNode(currentNode.LeftChild, item); } if (currentNode.HasRightChild && item.IsGreaterThan(currentNode.Value)) { return _findNode(currentNode.RightChild, item); } // Return-functions-fix return null; } protected virtual BSTNode<T> _findMinNode(BSTNode<T> node) { if (node == null) return node; var currentNode = node; while (currentNode.HasLeftChild) currentNode = currentNode.LeftChild; return currentNode; } protected virtual BSTNode<T> _findMaxNode(BSTNode<T> node) { if (node == null) return node; var currentNode = node; while (currentNode.HasRightChild) currentNode = currentNode.RightChild; return currentNode; } protected virtual BSTNode<T> _findNextSmaller(BSTNode<T> node) { if (node == null) return node; if (node.HasLeftChild) return _findMaxNode(node.LeftChild); var currentNode = node; while (currentNode.Parent != null && currentNode.IsLeftChild) currentNode = currentNode.Parent; return currentNode.Parent; } protected virtual BSTNode<T> _findNextLarger(BSTNode<T> node) { if (node == null) return node; if (node.HasRightChild) return _findMinNode(node.RightChild); var currentNode = node; while (currentNode.Parent != null && currentNode.IsRightChild) currentNode = currentNode.Parent; return currentNode.Parent; } protected virtual void _findAll(BSTNode<T> currentNode, Predicate<T> match, ref List<T> list) { if (currentNode == null) return; // call the left child _findAll(currentNode.LeftChild, match, ref list); if (match(currentNode.Value)) // match { list.Add(currentNode.Value); } // call the right child _findAll(currentNode.RightChild, match, ref list); } protected virtual void _inOrderTraverse(BSTNode<T> currentNode, ref List<T> list) { if (currentNode == null) return; _inOrderTraverse(currentNode.LeftChild, ref list); list.Add(currentNode.Value); _inOrderTraverse(currentNode.RightChild, ref list); } public virtual T FindNextSmaller(T item) { var node = _findNode(Root, item); var nextSmaller = _findNextSmaller(node); if (nextSmaller == null) throw new Exception("Item was not found."); return nextSmaller.Value; } public virtual T FindNextLarger(T item) { var node = _findNode(Root, item); var nextLarger = _findNextLarger(node); if (nextLarger == null) throw new Exception("Item was not found."); return nextLarger.Value; } internal class BinarySearchTreePreOrderEnumerator : IEnumerator<T> { private BSTNode<T> current; internal Queue<BSTNode<T>> traverseQueue; private BinarySearchTree<T> tree; public BinarySearchTreePreOrderEnumerator(BinarySearchTree<T> tree) { this.tree = tree; //Build queue traverseQueue = new Queue<BSTNode<T>>(); visitNode(this.tree.Root); } public T Current { get { return current.Value; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { current = null; tree = null; } public void Reset() { current = null; } public bool MoveNext() { if (traverseQueue.Count > 0) current = traverseQueue.Dequeue(); else current = null; return current != null; } private void visitNode(BSTNode<T> node) { if (node == null) return; traverseQueue.Enqueue(node); visitNode(node.LeftChild); visitNode(node.RightChild); } } internal class BinarySearchTreeInOrderEnumerator : IEnumerator<T> { private BSTNode<T> current; internal Queue<BSTNode<T>> traverseQueue; private BinarySearchTree<T> tree; public BinarySearchTreeInOrderEnumerator(BinarySearchTree<T> tree) { this.tree = tree; //Build queue traverseQueue = new Queue<BSTNode<T>>(); visitNode(this.tree.Root); } public T Current { get { return current.Value; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { current = null; tree = null; } public void Reset() { current = null; } public bool MoveNext() { if (traverseQueue.Count > 0) current = traverseQueue.Dequeue(); else current = null; return current != null; } private void visitNode(BSTNode<T> node) { if (node == null) return; visitNode(node.LeftChild); traverseQueue.Enqueue(node); visitNode(node.RightChild); } } internal class BinarySearchTreePostOrderEnumerator : IEnumerator<T> { private BSTNode<T> current; internal Queue<BSTNode<T>> traverseQueue; private BinarySearchTree<T> tree; public BinarySearchTreePostOrderEnumerator(BinarySearchTree<T> tree) { this.tree = tree; //Build queue traverseQueue = new Queue<BSTNode<T>>(); visitNode(this.tree.Root); } public T Current { get { return current.Value; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { current = null; tree = null; } public void Reset() { current = null; } public bool MoveNext() { if (traverseQueue.Count > 0) current = traverseQueue.Dequeue(); else current = null; return current != null; } private void visitNode(BSTNode<T> node) { if (node == null) return; visitNode(node.LeftChild); visitNode(node.RightChild); traverseQueue.Enqueue(node); } } } //end-of-binary-search-tree public class BinarySearchTreeMap<TKey, TValue> : IBinarySearchTree<TKey, TValue> where TKey : IComparable<TKey> { public enum TraversalMode { InOrder = 0, PreOrder = 1, PostOrder = 2 } public BinarySearchTreeMap() { _count = 0; _allowDuplicates = true; Root = null; } public BinarySearchTreeMap(bool allowDuplicates) { _count = 0; _allowDuplicates = allowDuplicates; Root = null; } protected int _count { get; set; } protected bool _allowDuplicates { get; set; } protected virtual BSTMapNode<TKey, TValue> _root { get; set; } public virtual BSTMapNode<TKey, TValue> Root { get { return _root; } internal set { _root = value; } } public virtual int Count { get { return _count; } } public virtual bool IsEmpty { get { return _count == 0; } } /// Time-complexity: O(n), where n = number of nodes. public virtual int Height { get { if (IsEmpty) return 0; var currentNode = Root; return _getTreeHeight(currentNode); } } public virtual bool AllowsDuplicates { get { return _allowDuplicates; } } public virtual void Insert(TKey key, TValue value) { var newNode = new BSTMapNode<TKey, TValue>(key, value); // Insert node recursively starting from the root. check for success status. var success = _insertNode(newNode); if (success == false && _allowDuplicates == false) throw new InvalidOperationException("Tree does not allow inserting duplicate elements."); } public virtual void Insert(KeyValuePair<TKey, TValue> keyValuePair) { Insert(keyValuePair.Key, keyValuePair.Value); } public virtual void Insert(KeyValuePair<TKey, TValue>[] collection) { if (collection == null) throw new ArgumentNullException(); if (collection.Length > 0) { for (var i = 0; i < collection.Length; ++i) { Insert(collection[i].Key, collection[i].Value); } } } public virtual void Insert(List<KeyValuePair<TKey, TValue>> collection) { if (collection == null) throw new ArgumentNullException(); if (collection.Count > 0) { for (var i = 0; i < collection.Count; ++i) { Insert(collection[i].Key, collection[i].Value); } } } public virtual void Remove(TKey key) { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findNode(Root, key); if (node == null) throw new KeyNotFoundException("Key doesn't exist in tree."); _remove(node); } public virtual void RemoveMin() { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findMinNode(Root); _remove(node); } public virtual void RemoveMax() { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findMaxNode(Root); _remove(node); } public virtual void Clear() { Root = null; _count = 0; } public virtual bool Contains(TKey key) { return _findNode(_root, key) != null; } public virtual KeyValuePair<TKey, TValue> FindMin() { if (IsEmpty) throw new Exception("Tree is empty."); var minNode = _findMinNode(Root); return new KeyValuePair<TKey, TValue>(minNode.Key, minNode.Value); } public virtual KeyValuePair<TKey, TValue> FindMax() { if (IsEmpty) throw new Exception("Tree is empty."); var maxNode = _findMaxNode(Root); return new KeyValuePair<TKey, TValue>(maxNode.Key, maxNode.Value); } public virtual KeyValuePair<TKey, TValue> Find(TKey key) { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findNode(Root, key); if (node != null) return new KeyValuePair<TKey, TValue>(node.Key, node.Value); throw new KeyNotFoundException("Item was not found."); } public virtual IEnumerable<KeyValuePair<TKey, TValue>> FindAll(Predicate<TKey> searchPredicate) { var list = new List<KeyValuePair<TKey, TValue>>(); _findAll(Root, searchPredicate, ref list); return list; } public virtual KeyValuePair<TKey, TValue>[] ToArray() { return ToList().ToArray(); } public virtual List<KeyValuePair<TKey, TValue>> ToList() { var list = new List<KeyValuePair<TKey, TValue>>(); _inOrderTraverse(Root, ref list); return list; } protected virtual int _getTreeHeight(BSTMapNode<TKey, TValue> node) { if (node == null) return 0; // Is leaf node if (node.IsLeafNode) return 1; // Has two children if (node.ChildrenCount == 2) return 1 + Math.Max(_getTreeHeight(node.LeftChild), _getTreeHeight(node.RightChild)); // Has only left if (node.HasLeftChild) return 1 + _getTreeHeight(node.LeftChild); // Has only right return 1 + _getTreeHeight(node.RightChild); } /// <summary> /// Inserts a new node to the tree. /// </summary> protected virtual bool _insertNode(BSTMapNode<TKey, TValue> newNode) { // Handle empty trees if (Root == null) { Root = newNode; _count++; return true; } if (newNode.Parent == null) newNode.Parent = Root; // Check for value equality and whether inserting duplicates is allowed if (_allowDuplicates == false && newNode.Parent.Key.IsEqualTo(newNode.Key)) { return false; } // Go Left if (newNode.Parent.Key.IsGreaterThan(newNode.Key)) // newNode < parent { if (newNode.Parent.HasLeftChild == false) { newNode.Parent.LeftChild = newNode; // Increment count. _count++; return true; } newNode.Parent = newNode.Parent.LeftChild; return _insertNode(newNode); } // Go Right if (newNode.Parent.HasRightChild == false) { newNode.Parent.RightChild = newNode; // Increment count. _count++; return true; } newNode.Parent = newNode.Parent.RightChild; return _insertNode(newNode); } /// <summary> /// Replaces the node's value from it's parent node object with the newValue. /// Used in the recusive _remove function. /// </summary> protected virtual void _replaceNodeInParent(BSTMapNode<TKey, TValue> node, BSTMapNode<TKey, TValue> newNode = null) { if (node.Parent != null) { if (node.IsLeftChild) node.Parent.LeftChild = newNode; else node.Parent.RightChild = newNode; } if (newNode != null) newNode.Parent = node.Parent; } /// <summary> /// Remove the specified node. /// </summary> protected virtual bool _remove(BSTMapNode<TKey, TValue> node) { if (node == null) return false; var parent = node.Parent; if (node.ChildrenCount == 2) // if both children are present { var successor = node.RightChild; node.Key = successor.Key; node.Value = successor.Value; return true && _remove(successor); } if (node.HasLeftChild) // if the node has only a LEFT child { _replaceNodeInParent(node, node.LeftChild); _count--; } else if (node.HasRightChild) // if the node has only a RIGHT child { _replaceNodeInParent(node, node.RightChild); _count--; } else //this node has no children { _replaceNodeInParent(node, null); _count--; } return true; } /// <summary> /// Finds a node inside another node's subtrees, given it's value. /// </summary> protected virtual BSTMapNode<TKey, TValue> _findNode(BSTMapNode<TKey, TValue> currentNode, TKey key) { if (currentNode == null) return currentNode; if (key.IsEqualTo(currentNode.Key)) { return currentNode; } if (currentNode.HasLeftChild && key.IsLessThan(currentNode.Key)) { return _findNode(currentNode.LeftChild, key); } if (currentNode.HasRightChild && key.IsGreaterThan(currentNode.Key)) { return _findNode(currentNode.RightChild, key); } // Return-functions-fix return null; } /// <summary> /// Returns the min-node in a subtree. /// Used in the recusive _remove function. /// </summary> protected virtual BSTMapNode<TKey, TValue> _findMinNode(BSTMapNode<TKey, TValue> node) { if (node == null) return node; var currentNode = node; while (currentNode.HasLeftChild) currentNode = currentNode.LeftChild; return currentNode; } /// <summary> /// Returns the max-node in a subtree. /// Used in the recusive _remove function. /// </summary> protected virtual BSTMapNode<TKey, TValue> _findMaxNode(BSTMapNode<TKey, TValue> node) { if (node == null) return node; var currentNode = node; while (currentNode.HasRightChild) currentNode = currentNode.RightChild; return currentNode; } /// <summary> /// Finds the next smaller node in value compared to the specified node. /// </summary> protected virtual BSTMapNode<TKey, TValue> _findNextSmaller(BSTMapNode<TKey, TValue> node) { if (node == null) return node; if (node.HasLeftChild) return _findMaxNode(node.LeftChild); var currentNode = node; while (currentNode.Parent != null && currentNode.IsLeftChild) currentNode = currentNode.Parent; return currentNode.Parent; } /// <summary> /// Finds the next larger node in value compared to the specified node. /// </summary> protected virtual BSTMapNode<TKey, TValue> _findNextLarger(BSTMapNode<TKey, TValue> node) { if (node == null) return node; if (node.HasRightChild) return _findMinNode(node.RightChild); var currentNode = node; while (currentNode.Parent != null && currentNode.IsRightChild) currentNode = currentNode.Parent; return currentNode.Parent; } /// <summary> /// A recursive private method. Used in the public FindAll(predicate) functions. /// Implements in-order traversal to find all the matching elements in a subtree. /// </summary> protected virtual void _findAll(BSTMapNode<TKey, TValue> currentNode, Predicate<TKey> match, ref List<KeyValuePair<TKey, TValue>> list) { if (currentNode == null) return; // call the left child _findAll(currentNode.LeftChild, match, ref list); if (match(currentNode.Key)) // match list.Add(new KeyValuePair<TKey, TValue>(currentNode.Key, currentNode.Value)); // call the right child _findAll(currentNode.RightChild, match, ref list); } /// <summary> /// In-order traversal of the subtrees of a node. Returns every node it vists. /// </summary> protected virtual void _inOrderTraverse(BSTMapNode<TKey, TValue> currentNode, ref List<KeyValuePair<TKey, TValue>> list) { if (currentNode == null) return; // call the left child _inOrderTraverse(currentNode.LeftChild, ref list); // visit node list.Add(new KeyValuePair<TKey, TValue>(currentNode.Key, currentNode.Value)); // call the right child _inOrderTraverse(currentNode.RightChild, ref list); } /// <summary> /// Inserts an array of elements to the tree. /// </summary> public virtual void Insert(TKey[] collection) { if (collection == null) throw new ArgumentNullException(); if (collection.Length > 0) { for (var i = 0; i < collection.Length; ++i) { Insert(collection[i], default(TValue)); } } } /// <summary> /// Inserts a list of elements to the tree. /// </summary> public virtual void Insert(List<TKey> collection) { if (collection == null) throw new ArgumentNullException(); if (collection.Count > 0) { for (var i = 0; i < collection.Count; ++i) { Insert(collection[i], default(TValue)); } } } /// <summary> /// Updates the node of a specific key with a new value. /// </summary> public virtual void Update(TKey key, TValue newValue) { if (IsEmpty) throw new Exception("Tree is empty."); var node = _findNode(Root, key); if (node == null) throw new KeyNotFoundException("Key doesn't exist in tree."); node.Value = newValue; } /// <summary> /// Finds the next smaller element in tree, compared to the specified item. /// </summary> public virtual KeyValuePair<TKey, TValue> FindNextSmaller(TKey key) { var node = _findNode(Root, key); var nextSmaller = _findNextSmaller(node); if (nextSmaller == null) throw new Exception("Item was not found."); return new KeyValuePair<TKey, TValue>(nextSmaller.Key, nextSmaller.Value); } /// <summary> /// Finds the next larger element in tree, compared to the specified item. /// </summary> public virtual KeyValuePair<TKey, TValue> FindNextLarger(TKey item) { var node = _findNode(Root, item); var nextLarger = _findNextLarger(node); if (nextLarger == null) throw new Exception("Item was not found."); return new KeyValuePair<TKey, TValue>(nextLarger.Key, nextLarger.Value); } /*********************************************************************/ /// <summary> /// Returns an enumerator that visits node in the order: parent, left child, right child /// </summary> public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetPreOrderEnumerator() { return new BinarySearchTreePreOrderEnumerator(this); } /// <summary> /// Returns an enumerator that visits node in the order: left child, parent, right child /// </summary> public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetInOrderEnumerator() { return new BinarySearchTreeInOrderEnumerator(this); } /// <summary> /// Returns an enumerator that visits node in the order: left child, right child, parent /// </summary> public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetPostOrderEnumerator() { return new BinarySearchTreePostOrderEnumerator(this); } /*********************************************************************/ /// <summary> /// Returns an preorder-traversal enumerator for the tree values /// </summary> internal class BinarySearchTreePreOrderEnumerator : IEnumerator<KeyValuePair<TKey, TValue>> { private BSTMapNode<TKey, TValue> current; internal Queue<BSTMapNode<TKey, TValue>> traverseQueue; private BinarySearchTreeMap<TKey, TValue> tree; public BinarySearchTreePreOrderEnumerator(BinarySearchTreeMap<TKey, TValue> tree) { this.tree = tree; //Build queue traverseQueue = new Queue<BSTMapNode<TKey, TValue>>(); visitNode(this.tree.Root); } public KeyValuePair<TKey, TValue> Current { get { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); } } object IEnumerator.Current { get { return Current; } } public void Dispose() { current = null; tree = null; } public void Reset() { current = null; } public bool MoveNext() { if (traverseQueue.Count > 0) current = traverseQueue.Dequeue(); else current = null; return current != null; } private void visitNode(BSTMapNode<TKey, TValue> node) { if (node == null) return; traverseQueue.Enqueue(node); visitNode(node.LeftChild); visitNode(node.RightChild); } } /// <summary> /// Returns an inorder-traversal enumerator for the tree values /// </summary> internal class BinarySearchTreeInOrderEnumerator : IEnumerator<KeyValuePair<TKey, TValue>> { private BSTMapNode<TKey, TValue> current; internal Queue<BSTMapNode<TKey, TValue>> traverseQueue; private BinarySearchTreeMap<TKey, TValue> tree; public BinarySearchTreeInOrderEnumerator(BinarySearchTreeMap<TKey, TValue> tree) { this.tree = tree; //Build queue traverseQueue = new Queue<BSTMapNode<TKey, TValue>>(); visitNode(this.tree.Root); } public KeyValuePair<TKey, TValue> Current { get { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); } } object IEnumerator.Current { get { return Current; } } public void Dispose() { current = null; tree = null; } public void Reset() { current = null; } public bool MoveNext() { if (traverseQueue.Count > 0) current = traverseQueue.Dequeue(); else current = null; return current != null; } private void visitNode(BSTMapNode<TKey, TValue> node) { if (node == null) return; visitNode(node.LeftChild); traverseQueue.Enqueue(node); visitNode(node.RightChild); } } /// <summary> /// Returns a postorder-traversal enumerator for the tree values /// </summary> internal class BinarySearchTreePostOrderEnumerator : IEnumerator<KeyValuePair<TKey, TValue>> { private BSTMapNode<TKey, TValue> current; internal Queue<BSTMapNode<TKey, TValue>> traverseQueue; private BinarySearchTreeMap<TKey, TValue> tree; public BinarySearchTreePostOrderEnumerator(BinarySearchTreeMap<TKey, TValue> tree) { this.tree = tree; //Build queue traverseQueue = new Queue<BSTMapNode<TKey, TValue>>(); visitNode(this.tree.Root); } public KeyValuePair<TKey, TValue> Current { get { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); } } object IEnumerator.Current { get { return Current; } } public void Dispose() { current = null; tree = null; } public void Reset() { current = null; } public bool MoveNext() { if (traverseQueue.Count > 0) current = traverseQueue.Dequeue(); else current = null; return current != null; } private void visitNode(BSTMapNode<TKey, TValue> node) { if (node == null) return; visitNode(node.LeftChild); visitNode(node.RightChild); traverseQueue.Enqueue(node); } } } //end-of-binary-search-tree public class BSTMapNode<TKey, TValue> : IComparable<BSTMapNode<TKey, TValue>> where TKey : IComparable<TKey> { public BSTMapNode() { } public BSTMapNode(TKey key) : this(key, default(TValue), 0, null, null, null) { } public BSTMapNode(TKey key, TValue value) : this(key, value, 0, null, null, null) { } public BSTMapNode(TKey key, TValue value, int subTreeSize, BSTMapNode<TKey, TValue> parent, BSTMapNode<TKey, TValue> left, BSTMapNode<TKey, TValue> right) { Key = key; Value = value; Parent = parent; LeftChild = left; RightChild = right; } public virtual TKey Key { get; set; } public virtual TValue Value { get; set; } public virtual BSTMapNode<TKey, TValue> Parent { get; set; } public virtual BSTMapNode<TKey, TValue> LeftChild { get; set; } public virtual BSTMapNode<TKey, TValue> RightChild { get; set; } /// <summary> /// Checks whether this node has any children. /// </summary> public virtual bool HasChildren { get { return ChildrenCount > 0; } } /// <summary> /// Checks whether this node has left child. /// </summary> public virtual bool HasLeftChild { get { return LeftChild != null; } } /// <summary> /// Checks whether this node has right child. /// </summary> public virtual bool HasRightChild { get { return RightChild != null; } } /// <summary> /// Checks whether this node is the left child of it's parent. /// </summary> public virtual bool IsLeftChild { get { return Parent != null && Parent.LeftChild == this; } } /// <summary> /// Checks whether this node is the left child of it's parent. /// </summary> public virtual bool IsRightChild { get { return Parent != null && Parent.RightChild == this; } } /// <summary> /// Checks whether this node is a leaf node. /// </summary> public virtual bool IsLeafNode { get { return ChildrenCount == 0; } } /// <summary> /// Returns number of direct descendents: 0, 1, 2 (none, left or right, or both). /// </summary> /// <returns>Number (0,1,2)</returns> public virtual int ChildrenCount { get { var count = 0; if (HasLeftChild) count++; if (HasRightChild) count++; return count; } } /// <summary> /// Compares to. /// </summary> public virtual int CompareTo(BSTMapNode<TKey, TValue> other) { if (other == null) return -1; return Key.CompareTo(other.Key); } } //end-of-bstnode public class BSTNode<T> : IComparable<BSTNode<T>> where T : IComparable<T> { public BSTNode() : this(default(T), 0, null, null, null) { } public BSTNode(T value) : this(value, 0, null, null, null) { } public BSTNode(T value, int subTreeSize, BSTNode<T> parent, BSTNode<T> left, BSTNode<T> right) { Value = value; Parent = parent; LeftChild = left; RightChild = right; } public virtual T Value { get; set; } public virtual BSTNode<T> Parent { get; set; } public virtual BSTNode<T> LeftChild { get; set; } public virtual BSTNode<T> RightChild { get; set; } /// <summary> /// Checks whether this node has any children. /// </summary> public virtual bool HasChildren { get { return ChildrenCount > 0; } } /// <summary> /// Checks whether this node has left child. /// </summary> public virtual bool HasLeftChild { get { return LeftChild != null; } } /// <summary> /// Checks whether this node has right child. /// </summary> public virtual bool HasRightChild { get { return RightChild != null; } } /// <summary> /// Checks whether this node is the left child of it's parent. /// </summary> public virtual bool IsLeftChild { get { return Parent != null && Parent.LeftChild == this; } } /// <summary> /// Checks whether this node is the left child of it's parent. /// </summary> public virtual bool IsRightChild { get { return Parent != null && Parent.RightChild == this; } } /// <summary> /// Checks whether this node is a leaf node. /// </summary> public virtual bool IsLeafNode { get { return ChildrenCount == 0; } } /// <summary> /// Returns number of direct descendents: 0, 1, 2 (none, left or right, or both). /// </summary> /// <returns>Number (0,1,2)</returns> public virtual int ChildrenCount { get { var count = 0; if (HasLeftChild) count++; if (HasRightChild) count++; return count; } } /// <summary> /// Compares to. /// </summary> public virtual int CompareTo(BSTNode<T> other) { if (other == null) return -1; return Value.CompareTo(other.Value); } } //end-of-bstnode public interface IBinarySearchTree<T> where T : IComparable<T> { // Returns a copy of the tree root BSTNode<T> Root { get; } // Returns the number of elements in the Tree int Count { get; } // Checks if the tree is empty. bool IsEmpty { get; } // Returns the height of the tree. int Height { get; } // Returns true if tree allows inserting duplicates; otherwise, false bool AllowsDuplicates { get; } // Inserts an element to the tree void Insert(T item); // Inserts an array of elements to the tree. void Insert(T[] collection); // Inserts a list of items to the tree. void Insert(List<T> collection); // Removes the min value from tree void RemoveMin(); // Removes the max value from tree void RemoveMax(); // Remove an element from tree void Remove(T item); // Check for the existence of an item bool Contains(T item); // Finds the minimum element. T FindMin(); // Finds the maximum element. T FindMax(); // Find the element in the tree, returns null if not found. T Find(T item); // Finds all the elements in the tree that match the predicate. IEnumerable<T> FindAll(Predicate<T> searchPredicate); // Return an array of the tree elements T[] ToArray(); // Return an array of the tree elements List<T> ToList(); // Returns an enumerator that visits node in the order: parent, left child, right child IEnumerator<T> GetPreOrderEnumerator(); // Returns an enumerator that visits node in the order: left child, parent, right child IEnumerator<T> GetInOrderEnumerator(); // Returns an enumerator that visits node in the order: left child, right child, parent IEnumerator<T> GetPostOrderEnumerator(); // Clear this tree. void Clear(); } public interface IBinarySearchTree<TKey, TValue> where TKey : IComparable<TKey> { BSTMapNode<TKey, TValue> Root { get; } int Count { get; } bool IsEmpty { get; } int Height { get; } bool AllowsDuplicates { get; } void Insert(TKey key, TValue value); void Insert(KeyValuePair<TKey, TValue> keyValuePair); void Insert(KeyValuePair<TKey, TValue>[] collection); void Insert(List<KeyValuePair<TKey, TValue>> collection); void RemoveMin(); void RemoveMax(); void Remove(TKey item); bool Contains(TKey item); KeyValuePair<TKey, TValue> FindMin(); KeyValuePair<TKey, TValue> FindMax(); KeyValuePair<TKey, TValue> Find(TKey item); IEnumerable<KeyValuePair<TKey, TValue>> FindAll(Predicate<TKey> searchPredicate); KeyValuePair<TKey, TValue>[] ToArray(); List<KeyValuePair<TKey, TValue>> ToList(); void Clear(); } }
29.415718
115
0.494289
3efc6146e83ff4e0bb9a0932e9717c12552851af
4,449
js
JavaScript
js/quizzes.js
Sebarbossus/lab
2a0dea07907a66fd706f1e122ac898d8cf03d8b1
[ "Apache-2.0" ]
null
null
null
js/quizzes.js
Sebarbossus/lab
2a0dea07907a66fd706f1e122ac898d8cf03d8b1
[ "Apache-2.0" ]
null
null
null
js/quizzes.js
Sebarbossus/lab
2a0dea07907a66fd706f1e122ac898d8cf03d8b1
[ "Apache-2.0" ]
1
2021-10-08T07:22:44.000Z
2021-10-08T07:22:44.000Z
/* Logic for the handling of questions and quizzes */ window.addEventListener("load", (e) => { if (localStorage) { // If the quiz was already taken, do not show it let path = window.location.pathname, pathAtoms = path.split("/"), courseName = pathAtoms[3]; // There cannot be more than 50 quizzes in a lesson for (let i=1; i < 51; i++) { let questionNum = `${courseName}-q${i}`, questionBool = `${questionNum}-question_isAnswered`, questionId = `${questionNum}-question_question`, answerId = `${questionNum}-question_answer`, answersContainerId = `${questionNum}-answers-container`, ownAnswerContainerId = `${questionNum}-oa`, questionMadeContainerId = `${questionNum}-qm`, ownAnswerId = `${questionNum}-oa_done`, questionMadeId = `${questionNum}-qm_done`, responseId = `${questionNum}-question_response`; // Fetch all questions that were not answered yet if (document.getElementById(answersContainerId)) { let answersContainer = document.getElementById(answersContainerId); answersContainer.classList.remove("none"); answersContainer.classList.add("block"); // Do not show the questions that were already answered if (localStorage.getItem(questionBool) === "true") { let ownAnswerContainer = document.getElementById(ownAnswerContainerId), questionMadeContainer = document.getElementById(questionMadeContainerId), ownAnswer = document.getElementById(ownAnswerId), questionMade = document.getElementById(questionMadeId), question = localStorage.getItem(questionId), chosenAnswer = localStorage.getItem(answerId), response = localStorage.getItem(responseId), responseContainer = document.getElementById(response); answersContainer.classList.remove("block"); answersContainer.classList.add("none"); questionMade.innerText = question; ownAnswer.innerText = chosenAnswer; questionMadeContainer.classList.remove("none"); questionMadeContainer.classList.add("block"); ownAnswerContainer.classList.remove("none"); ownAnswerContainer.classList.add("block"); responseContainer.classList.remove("none"); responseContainer.classList.add("block"); } } } } }); function submittedRadioQuestion (e) { const submitBtnId = e.id, questionContainerId = submitBtnId.replace("-submit", "-answers-container"), questionContainer = document.getElementById(questionContainerId), questionId = submitBtnId.replace("-submit", "-question"), question = document.getElementById(questionId), answersGroupId = submitBtnId.replace("-submit", ""), answersIds = document.getElementsByName(answersGroupId); let answered = "false"; for (let i=0; i<answersIds.length; i++) { if (answersIds[i].checked) { let chosenAnswerId = `${answersGroupId}-a${i + 1}`; let chosenAnswer = document.getElementById(chosenAnswerId); let responseId = `${answersGroupId}-r${i + 1}`; let response = document.getElementById(responseId); questionContainer.classList.remove("block"); questionContainer.classList.add("none"); response.classList.remove("none"); response.classList.add("block"); answered = "true"; if (localStorage) { localStorage.setItem(`${questionId}_question`, question.innerText); localStorage.setItem(`${questionId}_answer`, chosenAnswer.innerText); localStorage.setItem(`${questionId}_response`, responseId); localStorage.setItem(`${questionId}_isAnswered`, answered); } // It does not make sense to select more than one radio button break; } } }
53.60241
98
0.576984
79e80674fc8542b222b598d3986a2385525ce9e7
3,285
php
PHP
vendor/predis/predis/tests/Predis/Option/ClientClusterTest.php
cannon14/Event-Scheduling-System
a5456c6cd40c443771998994140e3324a93eda16
[ "MIT" ]
null
null
null
vendor/predis/predis/tests/Predis/Option/ClientClusterTest.php
cannon14/Event-Scheduling-System
a5456c6cd40c443771998994140e3324a93eda16
[ "MIT" ]
null
null
null
vendor/predis/predis/tests/Predis/Option/ClientClusterTest.php
cannon14/Event-Scheduling-System
a5456c6cd40c443771998994140e3324a93eda16
[ "MIT" ]
null
null
null
<?php /* * This file is part of the Predis package. * * (c) Daniele Alessandri <suppakilla@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Predis\Option; use PredisTestCase; /** * */ class ClientClusterTest extends PredisTestCase { /** * @group disconnected */ public function testValidationAcceptsFQNStringAsInitializer() { $clusterClass = get_class($this->getMock('Predis\Connection\ClusterConnectionInterface')); $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientCluster(); $cluster = $option->filter($options, $clusterClass); $this->assertInstanceOf('Predis\Connection\ClusterConnectionInterface', $cluster); } /** * @group disconnected */ public function testValidationRecognizesCertainPredefinedShortNames() { $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientCluster(); $cluster = $option->filter($options, 'predis'); $this->assertInstanceOf('Predis\Connection\ClusterConnectionInterface', $cluster); } /** * @group disconnected */ public function testValidationAcceptsCallableObjectAsInitializers() { $value = $this->getMock('Predis\Connection\ClusterConnectionInterface'); $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientCluster(); $initializer = $this->getMock('stdClass', array('__invoke')); $initializer->expects($this->once())->method('__invoke')->with($this->isInstanceOf('Predis\Option\ClientOptionsInterface'), $option)->will($this->returnValue($value)); $cluster = $option->filter($options, $initializer, $option); $this->assertInstanceOf('Predis\Connection\ClusterConnectionInterface', $cluster); $this->assertSame($value, $cluster); } /** * @group disconnected */ public function testValidationThrowsExceptionOnInvalidClassTypes() { $this->setExpectedException('InvalidArgumentException'); $connectionClass = get_class($this->getMock('Predis\Connection\SingleConnectionInterface')); $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientCluster(); $option->filter($options, $connectionClass); } /** * @group disconnected */ public function testValidationThrowsExceptionOnInvalidShortName() { $this->setExpectedException('InvalidArgumentException'); $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientCluster(); $option->filter($options, 'unknown'); } /** * @group disconnected */ public function testValidationThrowsExceptionOnInvalidObjectReturnedByCallback() { $this->setExpectedException('InvalidArgumentException'); $value = function ($options) { return new \stdClass(); }; $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientCluster(); $option->filter($options, $value); } /** * @group disconnected */ public function testValidationThrowsExceptionOnInvalidArguments() { $this->setExpectedException('InvalidArgumentException'); $options = $this->getMock('Predis\Option\ClientOptionsInterface'); $option = new ClientCluster(); $option->filter($options, new \stdClass()); } }
26.28
169
0.729985
bcd7fec4e562162b6c1515cc1994163e27c1fc0d
12,408
swift
Swift
SwiftMKit/Extension/String+Extension.swift
Lves/SwiftMKit
6a65aa2854f9acb32c18f190a6ce36be49e9d1cc
[ "MIT" ]
null
null
null
SwiftMKit/Extension/String+Extension.swift
Lves/SwiftMKit
6a65aa2854f9acb32c18f190a6ce36be49e9d1cc
[ "MIT" ]
null
null
null
SwiftMKit/Extension/String+Extension.swift
Lves/SwiftMKit
6a65aa2854f9acb32c18f190a6ce36be49e9d1cc
[ "MIT" ]
null
null
null
// // String+Extension.swift // SwiftMKitDemo // // Created by Mao on 4/17/16. // Copyright © 2016 cdts. All rights reserved. // import Foundation import CocoaLumberjack import CommonCrypto extension String { public func stringByAddingPercentEncodingForURLQueryValue() -> String? { let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") var str:String? if #available(iOS 9, *){ str = self.addingPercentEncoding(withAllowedCharacters: allowedCharacters) }else { str = self } return str } public func withoutSeparator() -> String { return self.components(separatedBy: CharacterSet.whitespacesAndNewlines).joined(separator: "") } /// 解码Url public var decodeUrl: String { return self.removingPercentEncoding! } /// 编码Url public var encodeUrl: String { return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } public var unicodeStr:String { let tempStr1 = self.replacingOccurrences(of: "\\u", with: "\\U") let tempStr2 = tempStr1.replacingOccurrences(of:"\"", with: "\\\"") let tempStr3 = "\"".appending(tempStr2).appending("\"") let tempData = tempStr3.data(using: .utf8) var returnStr:String = "" do { returnStr = try PropertyListSerialization.propertyList(from: tempData!, options: [.mutableContainers], format: nil) as! String } catch { print(error) } return returnStr.replacingOccurrences(of:"\\r\\n", with: "\n") } // MARK: Format public func formatCurrency(locale: String = "en_US") -> String { return NSString(string: self).doubleValue.formatCurrency(locale: locale) } public func formatCurrencyWithoutDot(locale: String = "en_US") -> String { return NSString(string: self).doubleValue.formatCurrencyWithoutDot(locale: locale) } public func jsonStringToDictionary() -> [String: AnyObject]? { if let data = self.data(using: String.Encoding.utf8) { do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] } catch let error as NSError { DDLogError(error.description) } } return nil } public func formatMask(_ range : NSRange) -> String { var mask: String = "" for _ in 0..<range.length { mask += "*" } let result: NSMutableString = NSMutableString(string: self) if self.length >= range.location + range.length { result.replaceCharacters(in: range, with: mask) return result as String } else if self.length >= range.location { return result.substring(to: range.location) + mask } else { return mask } } public func urlEncode() -> String? { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) } // MARK: Encrypt public var md5: String { //TODO return "" let str = self.cString(using: String.Encoding.utf8) let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.deallocate() let encryptString = String(format: hash as String) DDLogVerbose("Encrypt before:\(self)") DDLogVerbose("Encrypt after:\(encryptString)") return encryptString } public func fromBase64() -> String { let data = Data(base64Encoded: self, options: NSData.Base64DecodingOptions(rawValue: 0)) return String(data: data!, encoding: String.Encoding.utf8)! } public func toBase64() -> String { let data = self.data(using: String.Encoding.utf8) return data!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) } public func transformToPinyin() -> String? { let str = NSMutableString(string: self) as CFMutableString if CFStringTransform(str, nil, kCFStringTransformMandarinLatin, false) == true { if CFStringTransform(str, nil, kCFStringTransformStripDiacritics, false) == true { return str as String } } return nil } // MARK: Reverse public func reverse() -> String { return String(self.reversed()) } /// 加密手机号(186****6789) public func encryPhoneNo() -> String { if self.length == 11 { let startIndex = self.index(self.startIndex, offsetBy: 3) let endIndex = self.index(startIndex, offsetBy: 4) let range = (startIndex ..< endIndex) let newPhone = self.replacingCharacters(in: range, with: "****") return newPhone } else { return self } } public func formatToDateString(withFormat format: String = "yyyy-MM-dd") -> String { guard self.length > 0 else { return "" } let timestamp = self.toDouble() ?? 0 let date = Date(timeIntervalSince1970: timestamp) let fmt = DateFormatter() fmt.dateFormat = format return fmt.string(from: date) } public func formatTimestampToDateString(withFormat format: String = "yyyy-MM-dd") -> String { guard self.length > 0 else { return "" } let tmp = self.toDouble() ?? 0 // NSTimeInterval let timestamp = self.length >= 13 ? tmp / 1000.0 : tmp let date = Date(timeIntervalSince1970: timestamp) let fmt = DateFormatter() fmt.dateFormat = format return fmt.string(from: date) } public func formatDateStringToOtherFormat(orignFormat oFormat:String = "yyyyMMdd", targetFormat toFormat:String = "yyyy-MM-dd") -> String { guard self.length > 0 else { return "" } let date = Date(fromString: self, format: oFormat) let fmt = DateFormatter() fmt.dateFormat = toFormat return date == nil ? self : fmt.string(from: date!) } // /// 字符串 -> N为小数 // /// // /// :param: digit N // /// // /// :returns: 指定格式的字符串 // func formatFloatString(digit: UInt = 2) -> String { // let fmt = "%.\(digit)f" // return String(format: fmt, self.toDouble() ?? 0) // } /// 字符串 -> N为小数 /// /// :param: digit N /// :param: percent 标识是否显示成百分比字符串 /// /// :returns: 指定格式的字符串 public func formatFloatString(digit: UInt = 2, percent: Bool = false) -> String { var fmt = "%.\(digit)f" if percent { fmt = "%.\(digit)f%%" } return String(format: fmt, self.toDouble() ?? 0) } public static func getAttributedStringHeight(matchWidth width:CGFloat, attributedString:NSAttributedString?) -> CGFloat { let options: NSStringDrawingOptions = [NSStringDrawingOptions.usesLineFragmentOrigin, NSStringDrawingOptions.usesFontLeading] let size = attributedString?.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: options, context: nil) return size?.height ?? 0 } public func getAttributedString(withFont font: UIFont, lineSpacing: CGFloat, alignment: NSTextAlignment? = .left,textColor:UIColor? = nil) -> NSMutableAttributedString { guard self.length > 0 else { return NSMutableAttributedString() } var attributes:[NSAttributedStringKey : Any] = [.font:font] if let textColor = textColor { attributes[.foregroundColor] = textColor } let attributedString = NSMutableAttributedString(string: self, attributes:attributes) let style = NSMutableParagraphStyle() style.lineSpacing = lineSpacing style.alignment = alignment ?? .left attributedString.addAttribute(.paragraphStyle, value: style, range: NSMakeRange(0, attributedString.length)) return attributedString } /** * 获取字符串的宽度和高度 * * @param text:NSString * @param font:UIFont * * @return CGRect */ public func getTextRectSize(text:NSString,font:UIFont,size:CGSize) -> CGRect { let attributes = [NSAttributedStringKey.font: font] let option = NSStringDrawingOptions.usesLineFragmentOrigin let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil) return rect; } /** * 获取字符串的宽度和高度 * * @param text:NSString * @param font:UIFont * * @return CGRect */ public func textRectSize(font:UIFont,size:CGSize) -> CGRect { let attributes = [NSAttributedStringKey.font: font] let option = NSStringDrawingOptions.usesLineFragmentOrigin let rect:CGRect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil) return rect; } /* * url字符串拼接参数 */ public func urlStringAddParams(params: [String:Any]?) -> String { guard let params = params ,params.count > 0 else { return self } //获得参数字符串 var paramsStr:String = "" for (index ,key) in params.keys.enumerated() { if let value = params[key] { if type(of: value) is AnyClass { continue } if index == (params.count-1) { paramsStr += "\(key)=\(value)" }else { paramsStr += "\(key)=\(value)&" } } } //拼接到url var resultUrl = self if paramsStr.length > 0 { if self.contains("?"){ //url上已有参数 resultUrl += ("&"+paramsStr.encodeUrl) }else{ resultUrl += ("?"+paramsStr.encodeUrl) } } return resultUrl } public func removeDecimalTailZero() -> String{ var outNumber = self var i = 1 if self.contains("."){ while i < self.count{ if outNumber.hasSuffix("0"){ outNumber.remove(at: outNumber.index(before: outNumber.endIndex)) i = i + 1 }else{ break } } if outNumber.hasSuffix("."){ outNumber.remove(at: outNumber.index(before: outNumber.endIndex)) } return outNumber } else{ return self } } public func toDictionary() -> [String: Any]? { if let data = self.data(using: .utf8) { do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { print(error.localizedDescription) } } return nil } public var friendlyTime: String { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "zh_CN") dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm:ss") if let date = dateFormatter.date(from: self) { return date.friendlyTime } return self } public var decodeUnicode: String { let str = NSMutableString(string: self) str.replaceOccurrences(of: "\\U", with: "\\u", options: [], range: NSMakeRange(0, str.length)) CFStringTransform(str, nil, "Any-Hex/Java" as NSString, true) str.replaceOccurrences(of: "\\\"", with: "\"", options: [], range: NSMakeRange(0, str.length)) return str as String } }
35.655172
173
0.568665
72c4ec6d1d410369ed479ffcf9816a44a403c7b0
1,184
cs
C#
Legacy/EnvironmentChart.cs
k76-0G/0G
82acb75c8443e398cde295147300d9894b1ada56
[ "MIT" ]
null
null
null
Legacy/EnvironmentChart.cs
k76-0G/0G
82acb75c8443e398cde295147300d9894b1ada56
[ "MIT" ]
null
null
null
Legacy/EnvironmentChart.cs
k76-0G/0G
82acb75c8443e398cde295147300d9894b1ada56
[ "MIT" ]
null
null
null
using System.Collections.Generic; using UnityEngine; namespace _0G.Legacy { [CreateAssetMenu( fileName = "SomeWhere_EnvironmentChart.asset", menuName = "0G Legacy Scriptable Object/Environment Chart", order = 514 )] public class EnvironmentChart : Docket { // CONSTANTS public const string ENVIRONMENT_CHART_SUFFIX = "_EnvironmentChart"; // SERIALIZED FIELDS [Header("Game Object Data")] [Enum(typeof(EnvironmentID))] public int EnvironmentID; [Header("Environment Data")] // DO NOT STORE REFERENCES TO BUNDLED ASSETS // strings identifying assets are OK // --- // (references will be null since the asset pack is not loaded) public Texture2D MapIcon; // PROPERTIES public override int ID => EnvironmentID; public override string BundleName => GetBundleName(EnvironmentID); public override string DocketSuffix => ENVIRONMENT_CHART_SUFFIX; // METHODS public static string GetBundleName(int environmentID) { return "_e" + environmentID.ToString("D5"); } } }
25.73913
75
0.631757
17b23e33becf205fc52b1b29655485c212621957
17,158
lua
Lua
Framework/EsoUi/ingame/restyle/gamepad/outfit_selector_gamepad.lua
martin-repo/eso-addon-framework
5a0873e624abee2b560b47cdd8571bb24b526663
[ "MIT" ]
3
2021-09-19T00:31:05.000Z
2021-12-22T07:30:15.000Z
Framework/EsoUi/ingame/restyle/gamepad/outfit_selector_gamepad.lua
martin-repo/eso-addon-framework
5a0873e624abee2b560b47cdd8571bb24b526663
[ "MIT" ]
null
null
null
Framework/EsoUi/ingame/restyle/gamepad/outfit_selector_gamepad.lua
martin-repo/eso-addon-framework
5a0873e624abee2b560b47cdd8571bb24b526663
[ "MIT" ]
null
null
null
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_Outfit_Selector_Header_Focus_Gamepad = ZO_InitializingCallbackObject:Subclass() function ZO_Outfit_Selector_Header_Focus_Gamepad:Initialize(control) self.control = control self.label = control:GetNamedChild("OutfitName") self.dropdownChevron = control:GetNamedChild("OpenDropdown") self.active = false self.enabled = true end function ZO_Outfit_Selector_Header_Focus_Gamepad:Activate() self.active = true self:Update() self:FireCallbacks("FocusActivated") end function ZO_Outfit_Selector_Header_Focus_Gamepad:Enable() self.enabled = true self:Update() end function ZO_Outfit_Selector_Header_Focus_Gamepad:Deactivate() self.active = false self:Update() self:FireCallbacks("FocusDeactivated") end function ZO_Outfit_Selector_Header_Focus_Gamepad:Disable() self.enabled = false self:Update() end function ZO_Outfit_Selector_Header_Focus_Gamepad:Update() if self.active then if self.enabled then self.label:SetColor(ZO_SELECTED_TEXT:UnpackRGBA()) else self.label:SetColor(ZO_GAMEPAD_DISABLED_SELECTED_COLOR:UnpackRGBA()) end else if self.enabled then self.label:SetColor(ZO_DISABLED_TEXT:UnpackRGBA()) else self.label:SetColor(ZO_GAMEPAD_DISABLED_UNSELECTED_COLOR:UnpackRGBA()) end end end function ZO_Outfit_Selector_Header_Focus_Gamepad:IsActive() return self.active end -- ZO_Outfit_Selector_Gamepad -- ZO_Outfit_Selector_Gamepad = ZO_InitializingObject:Subclass() function ZO_Outfit_Selector_Gamepad:Initialize(control) self.control = control local function OnRefreshOutfitName(actorCategory, outfitIndex) self:UpdateOutfitList() end GAMEPAD_OUTFITS_SELECTION_SCENE = ZO_InteractScene:New("gamepad_outfits_selection", SCENE_MANAGER, ZO_DYEING_STATION_INTERACTION) GAMEPAD_OUTFITS_SELECTION_SCENE:SetInputPreferredMode(INPUT_PREFERRED_MODE_ALWAYS_GAMEPAD) GAMEPAD_OUTFITS_SELECTOR_FRAGMENT = ZO_FadeSceneFragment:New(ZO_Outfits_Selector_Gamepad) GAMEPAD_OUTFITS_SELECTOR_FRAGMENT:RegisterCallback("StateChange", function(oldState, newState) if newState == SCENE_SHOWING then self:PerformDeferredInitialization() ITEM_PREVIEW_GAMEPAD:ResetOutfitPreview() self:UpdateOutfitList() self:RefreshHeader() self.outfitSelectorList:Activate() local dataIndex = 1 if self.currentOutfitIndex then dataIndex = dataIndex + self.currentOutfitIndex end self.outfitSelectorList:SetSelectedIndexWithoutAnimation(dataIndex) KEYBIND_STRIP:RemoveDefaultExit() KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptor) ZO_OUTFIT_MANAGER:RegisterCallback("RefreshOutfitName", OnRefreshOutfitName) self:PreviewOutfit(self.currentActorCategory, self.currentOutfitIndex) elseif newState == SCENE_HIDDEN then ZO_OUTFIT_MANAGER:UnregisterCallback("RefreshOutfitName", OnRefreshOutfitName) self.outfitSelectorList:Deactivate() GAMEPAD_TOOLTIPS:ClearLines(GAMEPAD_LEFT_TOOLTIP) KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptor) KEYBIND_STRIP:RestoreDefaultExit() if self.currentOutfitIndex then ZO_OUTFIT_MANAGER:EquipOutfit(self.currentActorCategory, self.currentOutfitIndex) else ZO_OUTFIT_MANAGER:UnequipOutfit(self.currentActorCategory) end end end) self.currentActorCategory = GAMEPLAY_ACTOR_CATEGORY_PLAYER self.currentOutfitIndex = ZO_OUTFIT_MANAGER:GetEquippedOutfitIndex(self.currentActorCategory) ZO_OUTFIT_MANAGER:RegisterCallback("RefreshEquippedOutfitIndex", function() self:UpdateCurrentOutfitIndex() end) EVENT_MANAGER:RegisterForEvent("gamepad_outfits_selection", EVENT_CURRENCY_UPDATE, function(eventId, ...) self:OnCurrencyChanged(...) end) end function ZO_Outfit_Selector_Gamepad:PerformDeferredInitialization() if self.initialized then return end self.initialized = true self:InitializeKeybindDescriptors() self:InitializeRenameDialog() local function SetupCheckBoxEntry(control, data, selected, reselectingDuringRebuild, enabled, active) ZO_GamepadCheckBoxTemplate_Setup(control, data, selected, reselectingDuringRebuild, enabled, active) control.statusIcon:ClearIcons() if data.outfitIndex == self.currentOutfitIndex then ZO_CheckButton_SetChecked(control.checkBox) if data.isHiddenByVisualLayer then control.statusIcon:AddIcon("EsoUI/Art/Inventory/inventory_icon_hiddenBy.dds") control.statusIcon:Show() end else ZO_CheckButton_SetUnchecked(control.checkBox) end end local EQUALITY_FUNCTION = nil self.outfitSelectorList = ZO_GamepadVerticalItemParametricScrollList:New(self.control:GetNamedChild("Mask"):GetNamedChild("Container"):GetNamedChild("RootList")) self.outfitSelectorList:SetAlignToScreenCenter(true) self.outfitSelectorList:AddDataTemplate("ZO_GamepadItemEntryTemplate", ZO_SharedGamepadEntry_OnSetup, ZO_GamepadMenuEntryTemplateParametricListFunction) self.outfitSelectorList:AddDataTemplate("ZO_OutfitSelector_CheckBoxTemplate_Gamepad", SetupCheckBoxEntry, ZO_GamepadMenuEntryTemplateParametricListFunction) self.outfitSelectorList:AddDataTemplateWithHeader("ZO_OutfitSelector_CheckBoxTemplate_Gamepad", SetupCheckBoxEntry, ZO_GamepadMenuEntryTemplateParametricListFunction, EQUALITY_FUNCTION, "ZO_GamepadMenuEntryHeaderTemplate") self.outfitSelectorList:SetOnSelectedDataChangedCallback(function(list, selectedData) self:OnListDataChanged(selectedData) end) self.header = self.control:GetNamedChild("HeaderContainer"):GetNamedChild("Header") ZO_GamepadGenericHeader_Initialize(self.header, ZO_GAMEPAD_HEADER_TABBAR_DONT_CREATE) local function UpdateCarriedCurrencyControl(control) ZO_CurrencyControl_SetSimpleCurrency(control, CURT_STYLE_STONES, GetCurrencyAmount(CURT_STYLE_STONES, CURRENCY_LOCATION_ACCOUNT), ZO_GAMEPAD_CURRENCY_OPTIONS_LONG_FORMAT) return true end local IS_PLURAL = false local IS_UPPER = false self.headerData = { titleText = GetString(SI_GAMEPAD_OUTFITS_SELECTOR_HEADER), data1HeaderText = zo_strformat(SI_CURRENCY_NAME_FORMAT, GetCurrencyName(CURT_STYLE_STONES, IS_PLURAL, IS_UPPER)), data1Text = UpdateCarriedCurrencyControl, } end function ZO_Outfit_Selector_Gamepad:InitializeRenameDialog() local parametricDialog = ZO_GenericGamepadDialog_GetControl(GAMEPAD_DIALOGS.PARAMETRIC) local function UpdateSelectedName(name) if self.selectedName ~= name or not self.noViolations then self.selectedName = name self.nameViolations = { IsValidOutfitName(self.selectedName) } self.noViolations = #self.nameViolations == 0 if not self.noViolations then local HIDE_UNVIOLATED_RULES = true local violationString = ZO_ValidNameInstructions_GetViolationString(self.selectedName, self.nameViolations, HIDE_UNVIOLATED_RULES) local headerData = { titleText = GetString(SI_INVALID_NAME_DIALOG_TITLE), messageText = violationString, messageTextAlignment = TEXT_ALIGN_LEFT, } GAMEPAD_TOOLTIPS:ShowGenericHeader(GAMEPAD_LEFT_DIALOG_TOOLTIP, headerData) ZO_GenericGamepadDialog_ShowTooltip(parametricDialog) else ZO_GenericGamepadDialog_HideTooltip(parametricDialog) end end KEYBIND_STRIP:UpdateCurrentKeybindButtonGroups() end ZO_Dialogs_RegisterCustomDialog("GAMEPAD_RENAME_OUFIT", { canQueue = true, gamepadInfo = { dialogType = GAMEPAD_DIALOGS.PARAMETRIC, }, setup = function(dialog) dialog:setupFunc() end, title = { text = SI_OUTFIT_RENAME_TITLE, }, mainText = { text = SI_OUTFIT_RENAME_DESCRIPTION, }, parametricList = { -- user name { template = "ZO_GamepadTextFieldItem", templateData = { nameField = true, textChangedCallback = function(control) local inputText = control:GetText() UpdateSelectedName(inputText) end, setup = function(control, data, selected, reselectingDuringRebuild, enabled, active) local dialog = data.dialog control.editBoxControl.textChangedCallback = data.textChangedCallback control.editBoxControl:SetMaxInputChars(OUTFIT_NAME_MAX_LENGTH) data.control = control if parametricDialog.data then control.editBoxControl:SetText(parametricDialog.data.name) else ZO_EditDefaultText_Initialize(control.editBoxControl, "") end end, }, }, }, blockDialogReleaseOnPress = true, buttons = { { keybind = "DIALOG_PRIMARY", text = SI_GAMEPAD_SELECT_OPTION, callback = function(dialog) local data = dialog.entryList:GetTargetData() data.control.editBoxControl:TakeFocus() end, }, { keybind = "DIALOG_SECONDARY", text = SI_GAMEPAD_COLLECTIONS_SAVE_NAME_OPTION, callback = function(dialog) local outfitIndex = dialog.data.outfitIndex local outfitManipulator = ZO_OUTFIT_MANAGER:GetOutfitManipulator(GAMEPLAY_ACTOR_CATEGORY_PLAYER, outfitIndex) outfitManipulator:SetOutfitName(self.selectedName) ZO_Dialogs_ReleaseDialogOnButtonPress("GAMEPAD_RENAME_OUFIT") end, visible = function() return self.noViolations end, clickSound = SOUNDS.DIALOG_ACCEPT, }, { keybind = "DIALOG_NEGATIVE", text = SI_DIALOG_CANCEL, callback = function(dialog) ZO_Dialogs_ReleaseDialogOnButtonPress("GAMEPAD_RENAME_OUFIT") end, }, } }) end function ZO_Outfit_Selector_Gamepad:InitializeKeybindDescriptors() -- Main list. self.keybindStripDescriptor = { alignment = KEYBIND_STRIP_ALIGN_LEFT, -- Back KEYBIND_STRIP:GenerateGamepadBackButtonDescriptor(function() SCENE_MANAGER:HideCurrentScene() end), -- Select { name = GetString(SI_GAMEPAD_SELECT_OPTION), keybind = "UI_SHORTCUT_PRIMARY", callback = function() self:UseCurrentSelection() end, }, -- Change Name { name = GetString(SI_OUTFIT_CHANGE_NAME), keybind = "UI_SHORTCUT_TERTIARY", callback = function() local currentlySelectedData = self.outfitSelectorList:GetTargetData() local outfitManipulator = ZO_OUTFIT_MANAGER:GetOutfitManipulator(GAMEPLAY_ACTOR_CATEGORY_PLAYER, currentlySelectedData.outfitIndex) ZO_Dialogs_ShowGamepadDialog("GAMEPAD_RENAME_OUFIT", { outfitIndex = currentlySelectedData.outfitIndex, name = outfitManipulator:GetOutfitName() }) end, visible = function() local currentlySelectedData = self.outfitSelectorList:GetTargetData() return not (self.currentActorCategory == GAMEPLAY_ACTOR_CATEGORY_COMPANION or currentlySelectedData.noOutfitEntry or currentlySelectedData.newOutfitEntry) end, }, } end function ZO_Outfit_Selector_Gamepad:UseCurrentSelection() local currentlySelectedData = self.outfitSelectorList:GetTargetData() if currentlySelectedData.newOutfitEntry then ShowMarketAndSearch("", MARKET_OPEN_OPERATION_UNLOCK_NEW_OUTFIT) elseif currentlySelectedData.outfitIndex ~= self.currentOutfitIndex then self:PreviewOutfit(currentlySelectedData.actorCategory, currentlySelectedData.outfitIndex) self.currentActorCategory = currentlySelectedData.actorCategory self.currentOutfitIndex = currentlySelectedData.outfitIndex self:UpdateOutfitList() end end function ZO_Outfit_Selector_Gamepad:PreviewOutfit(actorCategory, outfitIndex) if outfitIndex then ITEM_PREVIEW_GAMEPAD:PreviewOutfit(actorCategory, outfitIndex) else ITEM_PREVIEW_GAMEPAD:PreviewUnequipOutfit(actorCategory) end end function ZO_Outfit_Selector_Gamepad:UpdateOutfitList() self.outfitSelectorList:Clear() -- No Outfit Entry local data = ZO_GamepadEntryData:New(GetString(SI_NO_OUTFIT_EQUIP_ENTRY)) data.noOutfitEntry = true data.actorCategory = self.currentActorCategory self.outfitSelectorList:AddEntry("ZO_OutfitSelector_CheckBoxTemplate_Gamepad", data) local numOutfits = ZO_OUTFIT_MANAGER:GetNumOutfits(self.currentActorCategory) for i = 1, numOutfits do local outfitManipulator = ZO_OUTFIT_MANAGER:GetOutfitManipulator(self.currentActorCategory, i) local data = ZO_GamepadEntryData:New(outfitManipulator:GetOutfitName()) data.actorCategory = self.currentActorCategory data.outfitIndex = i local isHidden, highestPriorityVisualLayerThatIsShowing = WouldOutfitBeHidden(i, data.actorCategory) data.isHiddenByVisualLayer = isHidden data.hiddenVisualLayer = highestPriorityVisualLayerThatIsShowing if i == 1 then local maxOutfits = self.currentActorCategory == GAMEPLAY_ACTOR_CATEGORY_COMPANION and MAX_COMPANION_OUTFITS or MAX_OUTFIT_UNLOCKS data:SetHeader(zo_strformat(SI_GAMEPAD_OUTFITS_SELECTOR_ENTRY_HEADER, numOutfits, maxOutfits)) self.outfitSelectorList:AddEntryWithHeader("ZO_OutfitSelector_CheckBoxTemplate_Gamepad", data) else self.outfitSelectorList:AddEntry("ZO_OutfitSelector_CheckBoxTemplate_Gamepad", data) end end -- Unlock New Outfit Entry only if in player outfit mode if self.currentActorCategory == GAMEPLAY_ACTOR_CATEGORY_PLAYER and numOutfits < MAX_OUTFIT_UNLOCKS then local data = ZO_GamepadEntryData:New(GetString(SI_UNLOCK_NEW_OUTFIT_EQUIP_ENTRY), "EsoUI/Art/currency/gamepad/gp_crowns.dds") data.newOutfitEntry = true self.outfitSelectorList:AddEntry("ZO_GamepadItemEntryTemplate", data) end self.outfitSelectorList:Commit() end function ZO_Outfit_Selector_Gamepad:OnListDataChanged(newSelectedData) GAMEPAD_TOOLTIPS:ClearLines(GAMEPAD_LEFT_TOOLTIP) if newSelectedData.isHiddenByVisualLayer and newSelectedData.outfitIndex == self.currentOutfitIndex then GAMEPAD_TOOLTIPS:LayoutTitleAndDescriptionTooltip(GAMEPAD_LEFT_TOOLTIP, GetString(SI_GAMEPAD_OUTFITS_OUTFIT_HIDDEN_TITLE), GetHiddenByStringForVisualLayer(newSelectedData.hiddenVisualLayer)) end KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor) end function ZO_Outfit_Selector_Gamepad:OnCurrencyChanged(currencyType, currencyLocation, newAmount, oldAmount, reason) if currencyType == CURT_STYLE_STONES then if SCENE_MANAGER:IsShowing("gamepad_outfits_selection") then self:RefreshHeader() end end end function ZO_Outfit_Selector_Gamepad:UpdateCurrentOutfitIndex() self.currentOutfitIndex = ZO_OUTFIT_MANAGER:GetEquippedOutfitIndex(self.currentActorCategory) end function ZO_Outfit_Selector_Gamepad:RefreshHeader() ZO_GamepadGenericHeader_RefreshData(self.header, self.headerData) end function ZO_Outfit_Selector_Gamepad:SetCurrentActorCategory(actorCategory) if self.currentActorCategory ~= actorCategory then self.currentActorCategory = actorCategory self:UpdateCurrentOutfitIndex() end end function ZO_Outfit_Selector_Gamepad:GetCurrentActorCategoryAndIndex() return self.currentActorCategory, self.currentOutfitIndex end -- XML functions -- function ZO_OutfitSlot_Selector_OnInitialize(control) ZO_OUTFITS_SELECTOR_GAMEPAD = ZO_Outfit_Selector_Gamepad:New(control) end
41.9511
226
0.705094
2fa1f479f53c3f2e4de760c0e8fd5baf829aa143
1,628
py
Python
tests/TestFinDate.py
suhasghorp/FinancePy
567486785b33768f229a404e860f92fd042034a2
[ "BSD-3-Clause" ]
null
null
null
tests/TestFinDate.py
suhasghorp/FinancePy
567486785b33768f229a404e860f92fd042034a2
[ "BSD-3-Clause" ]
1
2020-05-07T14:38:23.000Z
2020-05-07T14:38:23.000Z
tests/TestFinDate.py
suhasghorp/FinancePy
567486785b33768f229a404e860f92fd042034a2
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Sat Feb 06 07:26:46 2016 @author: Dominic O'Kane """ from financepy.finutils.FinTestCases import FinTestCases, globalTestCaseMode from financepy.finutils.FinDate import FinDate import sys sys.path.append("..//..") testCases = FinTestCases(__file__, globalTestCaseMode) def test_FinDate(): startDate = FinDate(2018, 1, 1) testCases.header("DATE", "MONTHS", "CDS DATE") for numMonths in range(0, 120): nextCDSDate = startDate.nextCDSDate(numMonths) testCases.print(str(startDate), numMonths, str(nextCDSDate)) startDate = FinDate(2018, 1, 1) testCases.header("STARTDATE", "MONTHS", "CDS DATE") for numMonths in range(0, 365): startDate = startDate.addDays(1) nextIMMDate = startDate.nextIMMDate() testCases.print(numMonths, str(startDate), str(nextIMMDate)) def test_FinDateTenors(): startDate = FinDate(2018, 2, 23) tenor = "5d" print(tenor, startDate.addTenor(tenor)) tenor = "7D" print(tenor, startDate.addTenor(tenor)) tenor = "1W" print(tenor, startDate.addTenor(tenor)) tenor = "4W" print(tenor, startDate.addTenor(tenor)) tenor = "1M" print(tenor, startDate.addTenor(tenor)) tenor = "24M" print(tenor, startDate.addTenor(tenor)) tenor = "2Y" print(tenor, startDate.addTenor(tenor)) tenor = "10y" print(tenor, startDate.addTenor(tenor)) tenor = "0m" print(tenor, startDate.addTenor(tenor)) tenor = "20Y" print(tenor, startDate.addTenor(tenor)) test_FinDate() test_FinDateTenors() testCases.compareTestCases()
21.421053
76
0.672604
70ccdb1f9c2191a27a33940a64fe4568e37b26a7
45
lua
Lua
Limited Multiattack/LimitedAttack.lua
RealMelwei/WarlightMods
c949e7950c6fe67dd6bcc5d0061c4c8d09c27763
[ "MIT" ]
null
null
null
Limited Multiattack/LimitedAttack.lua
RealMelwei/WarlightMods
c949e7950c6fe67dd6bcc5d0061c4c8d09c27763
[ "MIT" ]
null
null
null
Limited Multiattack/LimitedAttack.lua
RealMelwei/WarlightMods
c949e7950c6fe67dd6bcc5d0061c4c8d09c27763
[ "MIT" ]
null
null
null
function LimitedAttack(game, standing) end
15
39
0.8
dd786a1064d4a944a9c098e693726917c6f7ed9c
1,609
java
Java
sample-business/src/main/java/com/cn/boot/sample/business/aop/CorsFilter.java
a327919006/-boot-sample
a85be6437ceb5741aee322253404dfc546c62c3b
[ "Apache-2.0" ]
4
2019-12-13T17:54:45.000Z
2021-01-14T09:39:50.000Z
sample-business/src/main/java/com/cn/boot/sample/business/aop/CorsFilter.java
a327919006/-boot-sample
a85be6437ceb5741aee322253404dfc546c62c3b
[ "Apache-2.0" ]
5
2020-07-02T03:42:49.000Z
2022-03-15T02:21:36.000Z
sample-business/src/main/java/com/cn/boot/sample/business/aop/CorsFilter.java
a327919006/-boot-sample
a85be6437ceb5741aee322253404dfc546c62c3b
[ "Apache-2.0" ]
6
2019-09-02T14:13:08.000Z
2022-03-23T10:38:30.000Z
package com.cn.boot.sample.business.aop; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 跨域过滤器 * * @author Chen Nan */ @Slf4j @Component @WebFilter(filterName = "cors", urlPatterns = "/*") public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; // 允许请求的域名,*为所有,*可改成指定域名,http://test.com.cn,http://manager.com.cn response.setHeader("Access-Control-Allow-Origin", "*"); // 允许的请求方法 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE ,PUT"); // 允许的有效时间 response.setHeader("Access-Control-Max-Age", "3600"); // 允许的请求头 response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, accessToken, Content-Type, Origin, Accept, User-Agent"); // 允许访问cookie response.setHeader("Access-Control-Allow-Credentials", "true"); if (RequestMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } }
35.755556
149
0.702921
3a9fc18207401602ac4b70f5f094c4328ef215a2
1,432
lua
Lua
data.lua
ZwerOxotnik/modders-stuff
ff3f15a0b397ef49be838bf2d1c6a8f819136bf0
[ "MIT" ]
1
2021-12-19T23:26:18.000Z
2021-12-19T23:26:18.000Z
data.lua
ZwerOxotnik/modders-stuff
ff3f15a0b397ef49be838bf2d1c6a8f819136bf0
[ "MIT" ]
null
null
null
data.lua
ZwerOxotnik/modders-stuff
ff3f15a0b397ef49be838bf2d1c6a8f819136bf0
[ "MIT" ]
null
null
null
data:extend{ { type = "tile", name = "red", order = "z-z-r", collision_mask = {"ground-tile"}, layer = 70, variants = { main = { { picture = "__modders-stuff__/graphics/terrain/lab-tiles/red.png", count = 1, size = 1 } }, empty_transitions = true }, map_color={r=1, g=0, b=0}, pollution_absorption_per_second = 0 }, { type = "tile", name = "green", order = "z-z-g", collision_mask = {"ground-tile"}, layer = 70, variants = { main = { { picture = "__modders-stuff__/graphics/green.png", count = 1, size = 1 } }, empty_transitions = true }, map_color={r=0, g=1, b=0}, pollution_absorption_per_second = 0 }, { type = "tile", name = "blue", order = "z-z-b", collision_mask = {"ground-tile"}, layer = 70, variants = { main = { { picture = "__modders-stuff__/graphics/blue.png", count = 1, size = 1 } }, empty_transitions = true }, map_color={r=0, g=0, b=1}, pollution_absorption_per_second = 0 } }
22.030769
77
0.402933
b55810db9be34589cacc4f0375a220780e277e4c
1,822
swift
Swift
leetcode-swift/Easy/q009-palindrome-number.swift
wty21cn/leetcode-swift
7235f243a799dcb6903ab6a7d6d615509148d93a
[ "MIT" ]
72
2016-07-02T16:31:52.000Z
2022-03-04T17:03:27.000Z
leetcode-swift/Easy/q009-palindrome-number.swift
raulsilvamx/leetcode-swift
7235f243a799dcb6903ab6a7d6d615509148d93a
[ "MIT" ]
null
null
null
leetcode-swift/Easy/q009-palindrome-number.swift
raulsilvamx/leetcode-swift
7235f243a799dcb6903ab6a7d6d615509148d93a
[ "MIT" ]
22
2016-07-03T05:36:32.000Z
2022-03-05T08:43:23.000Z
// // q009-palindrome-number.swift // leetcode-swift // Source* : https://leetcode.com/problems/palindrome-number/ // Category* : Math // // Created by Tianyu Wang on 16/7/4. // Github : http://github.com/wty21cn // Website : http://wty.im // Linkedin : https://www.linkedin.com/in/wty21cn // Mail : mailto:wty21cn@gmail.com /********************************************************************************** * * Determine whether an integer is a palindrome. Do this without extra space. * * * Some hints: * * Could negative integers be palindromes? (ie, -1) * * If you are thinking of converting the integer to string, note the restriction of using extra space. * * You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", * you know that the reversed integer might overflow. How would you handle such case? * * There is a more generic way of solving this problem. * **********************************************************************************/ import Foundation struct q9 { class Solution { func isPalindrome(_ x: Int) -> Bool { if x < 0 || x % 10 == 0 { return x == 0 } var x = x var halfReversedX = 0 while x > halfReversedX { halfReversedX = halfReversedX * 10 + x % 10 x /= 10 } // even num of digits situation || odd num of digits situaition return x == halfReversedX || x == halfReversedX / 10 } } static func getSolution() -> Void { print(Solution().isPalindrome(12344321)) print(Solution().isPalindrome(123421)) print(Solution().isPalindrome(0)) print(Solution().isPalindrome(10)) } }
29.868852
102
0.537322
4410e87e6117bc5dfe33cf6364f7ca605cbea611
4,412
py
Python
function/python/brightics/function/classification/test/classification_test.py
GSByeon/studio
782cf484541c6d68e1451ff6a0d3b5dc80172664
[ "Apache-2.0" ]
null
null
null
function/python/brightics/function/classification/test/classification_test.py
GSByeon/studio
782cf484541c6d68e1451ff6a0d3b5dc80172664
[ "Apache-2.0" ]
null
null
null
function/python/brightics/function/classification/test/classification_test.py
GSByeon/studio
782cf484541c6d68e1451ff6a0d3b5dc80172664
[ "Apache-2.0" ]
1
2020-11-19T06:44:15.000Z
2020-11-19T06:44:15.000Z
import unittest from brightics.function.classification import svm_classification_train, svm_classification_predict from brightics.function.transform import split_data from brightics.common.datasets import load_iris import pandas as pd import random from brightics.function.classification.decision_tree_classification import decision_tree_classification_train, \ decision_tree_classification_predict from brightics.function.classification.logistic_regression import logistic_regression_train, \ logistic_regression_predict from brightics.function.classification.xgb_classification import xgb_classification_train, \ xgb_classification_predict class SVMTest(unittest.TestCase): def test1(self): iris = load_iris() df_splitted = split_data(table=iris, train_ratio=0.7, test_ratio=0.3) train_df = df_splitted['train_table'] test_df = df_splitted['test_table'] train_out = svm_classification_train(table=train_df, feature_cols=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'], label_col='species') # print(train_out['model']['svc_model']) predict_out = svm_classification_predict(table=test_df, model=train_out['model']) print(predict_out['out_table'][['species', 'prediction']]) def test_predict_thresholds(self): iris = load_iris() df_splitted = split_data(table=iris, train_ratio=0.7, test_ratio=0.3) train_df = df_splitted['train_table'] test_df = df_splitted['test_table'] train_out = svm_classification_train(table=train_df, feature_cols=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'], label_col='species') # print(train_out['model']['svc_model']) predict_out = svm_classification_predict(table=test_df, model=train_out['model'], thresholds=[0.1, 0.2, 0.3]) print(predict_out['out_table'][['species', 'prediction']]) def test_groupby1(self): df = load_iris() random_group = [] for i in range(len(df)): random_group.append(random.randint(1, 2)) df['random_group'] = random_group train_out = svm_classification_train(table=df, feature_cols=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'], label_col='species', group_by=['random_group']) predict_out = svm_classification_predict(table=df, model=train_out['model']) print(predict_out['out_table'][['species', 'prediction']]) class DecisionTreeClassificationTest(unittest.TestCase): def test_groupby1(self): df = load_iris() random_group = [] for i in range(len(df)): random_group.append(random.randint(1, 2)) df['random_group'] = random_group train_out = decision_tree_classification_train(table=df, feature_cols=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'], label_col='species', group_by=['random_group']) predict_out = decision_tree_classification_predict(table=df, model=train_out['model']) print(predict_out['out_table'][['species', 'prediction']]) class LogisticRegressionTest(unittest.TestCase): def test_groupby1(self): df = load_iris() random_group = [] for i in range(len(df)): random_group.append(random.randint(1, 2)) df['random_group'] = random_group train_out = logistic_regression_train(table=df, feature_cols=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'], label_col='species', group_by=['random_group']) predict_out = logistic_regression_predict(table=df, model=train_out['model']) print(predict_out['out_table'][['species', 'prediction']]) class XGBClassificationTest(unittest.TestCase): def test_groupby1(self): df = load_iris() random_group = [] for i in range(len(df)): random_group.append(random.randint(1, 2)) df['random_group'] = random_group train_out = xgb_classification_train(table=df, feature_cols=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'], label_col='species', group_by=['random_group']) predict_out = xgb_classification_predict(table=df, model=train_out['model']) print(predict_out['out_table'][['species', 'prediction']])
46.442105
189
0.684723
a91e67e06955200eb25010734c56c0517b8f5504
119
css
CSS
examples/angular2-datepicker/src/app/app.component.css
TBear79/headless-datepicker
882a4738c1ec31f05a071dd1ca50dbc00119f343
[ "MIT" ]
6
2017-12-25T18:18:51.000Z
2021-11-21T10:10:40.000Z
examples/angular2-datepicker/src/app/app.component.css
TBear79/headless-datepicker
882a4738c1ec31f05a071dd1ca50dbc00119f343
[ "MIT" ]
1
2017-12-25T18:19:52.000Z
2018-01-04T13:41:03.000Z
examples/angular2-datepicker/src/app/app.component.css
TBear79/headless-datepicker
882a4738c1ec31f05a071dd1ca50dbc00119f343
[ "MIT" ]
null
null
null
.example { float: left; margin: 1em 1em; } p { width: 20em; min-height: 4em; } h2 { clear: left }
9.153846
20
0.512605
54e4c4fd3d85570e09bf75846f4b1ed8e1246ba0
1,057
h
C
src/CQGnuPlotTitle.h
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
null
null
null
src/CQGnuPlotTitle.h
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
null
null
null
src/CQGnuPlotTitle.h
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
1
2019-04-01T13:08:45.000Z
2019-04-01T13:08:45.000Z
#ifndef CQGnuPlotTitle_H #define CQGnuPlotTitle_H #include <CQGnuPlotObject.h> #include <CGnuPlotTitle.h> #include <CQGnuPlot.h> #include <QColor> #include <QFont> class CQGnuPlotGroup; class CQGnuPlotTitle : public CQGnuPlotObject, public CGnuPlotTitle { Q_OBJECT Q_PROPERTY(bool displayed READ isDisplayed WRITE setDisplayed) Q_PROPERTY(QString text READ text WRITE setText ) Q_PROPERTY(QPointF offset READ offset WRITE setOffset ) Q_PROPERTY(QFont font READ getFont WRITE setFont ) Q_PROPERTY(QColor color READ color WRITE setColor ) Q_PROPERTY(bool enhanced READ isEnhanced WRITE setEnhanced ) public: CQGnuPlotTitle(CQGnuPlotGroup *group); ~CQGnuPlotTitle(); QString text() const; void setText(const QString &s); QPointF offset() const; void setOffset(const QPointF &p); QColor color() const; void setColor(const QColor &c); QFont getFont() const; void setFont(const QFont &f); void draw(CGnuPlotRenderer *renderer) const override; }; #endif
25.166667
69
0.720908
b96beedcc0d11b3480853ecb7fbe9e574bf83025
3,215
lua
Lua
premake5.lua
saad039/cusp
4b4ef25e1523ec38553e04cc1d094f51b69ed75e
[ "MIT" ]
6
2020-03-18T01:39:45.000Z
2020-06-27T18:02:25.000Z
premake5.lua
Broever101/cusp
72fafc847343aa2a5ab820566b5979a5e8a7d93c
[ "MIT" ]
2
2020-05-21T00:25:53.000Z
2020-06-01T09:48:28.000Z
premake5.lua
Broever101/cusp
72fafc847343aa2a5ab820566b5979a5e8a7d93c
[ "MIT" ]
3
2020-04-12T12:55:54.000Z
2020-04-15T17:23:18.000Z
workspace "cusp" startproject "cusp" architecture "x86_64" configurations{ "Debug", "Release" } project "spdlog" location "build/spdlog" kind "Staticlib" language"C++" toolset "gcc" cppdialect "C++17" staticruntime "on" targetdir ("bin/%{prj.name}/%{cfg.buildcfg}") objdir("bin-init/%{prj.name}/%{cfg.buildcfg}") defines{ "SPDLOG_COMPILED_LIB" } files{ "dependencies/spdlog/include/**.h", "dependencies/spdlog/src/**.cpp" } includedirs{ "dependencies/spdlog/include" } links{ "pthread" } filter "configurations:Debug" defines { "DEBUG" } runtime "Debug" symbols "on" filter "configurations:Release" defines { "NDEBUG" } runtime "Release" optimize "On" project "ordered-map" location "build/ordered-map" kind "StaticLib" language"C++" toolset "gcc" cppdialect "C++17" staticruntime "on" targetdir ("bin/%{prj.name}/%{cfg.buildcfg}") objdir("bin-init/%{prj.name}/%{cfg.buildcfg}") files{ "dependencies/ordered-map/include/**.h", "dependencies/ordered-map/src/**.cpp" } includedirs{ "dependencies/ordered-map/include" } filter "configurations:Debug" defines { "DEBUG" } runtime "Debug" symbols "on" filter "configurations:Release" defines { "NDEBUG" } runtime "Release" optimize "On" project "json" location "build/json" kind "Staticlib" language"C++" toolset "gcc" cppdialect "C++17" staticruntime "on" targetdir ("bin/%{prj.name}/%{cfg.buildcfg}") objdir("bin-init/%{prj.name}/%{cfg.buildcfg}") files{ "dependencies/json/single_include/nlohmann/**.hpp", "dependencies/json/single_include/nlohmann/**.cpp" } includedirs{ "dependencies/json/single_include/nlohmann", } filter "configurations:Debug" defines { "DEBUG" } runtime "Debug" symbols "on" filter "configurations:Release" defines { "NDEBUG" } runtime "Release" optimize "On" project "cusp" location "build/cusp" kind "ConsoleApp" language "C++" toolset "gcc" cppdialect "C++17" staticruntime "on" targetdir ("bin/%{prj.name}/%{cfg.buildcfg}") objdir("bin-init/%{prj.name}/%{cfg.buildcfg}") files{ "cusp/src/**.cpp", "cusp/include/**.h" } includedirs{ "dependencies/spdlog/include", "dependencies/json/single_include/nlohmann", "dependencies/ordered-map/include", "cusp/include" } pchheader "cusppch.h" pchsource "cusp/src/cusppch.cpp" links{ "spdlog", "json", "ordered-map" } filter "configurations:Debug" defines { "DEBUG" } runtime "Debug" symbols "on" filter "configurations:Release" defines { "NDEBUG" } runtime "Release" optimize "on"
19.136905
59
0.544635
2b7e9d0b6f7478fc054aa5cb2706437daaa45722
530
asm
Assembly
programs/oeis/089/A089124.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/089/A089124.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/089/A089124.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A089124: Largest prime factor of numbers of the form A^2 + 3. ; 2,7,3,19,7,13,13,67,7,103,31,7,43,199,19,37,73,109,13,31,37,487,19,193,157,97,61,787,211,43,241,79,13,61,307,433,7,1447,127,229,421,31,463,277,13,163,79,769,601,2503,31,2707,37,139,757,73,271,37,67,1201,19,3847,331,4099,151,1453,1123,661,397,4903,97,19,43,5479,67,5779,1483,2029,223,337,547,31,1723,181,139,151,631,127,283,73,109,8467,103,8839,61,439,181,739,43,1429 add $0,1 pow $0,2 add $0,2 seq $0,6530 ; Gpf(n): greatest prime dividing n, for n >= 2; a(1)=1.
66.25
368
0.698113
2cca39bb3a93d03cb3422c1b43bff4a7063a1ec0
49
py
Python
PokeType/__main__.py
Daggy1234/PokeType
a79c8115ca9bb13e24c4fd4db4931b3094a96549
[ "MIT" ]
2
2021-11-06T14:09:40.000Z
2021-11-14T21:24:56.000Z
PokeType/__main__.py
Daggy1234/PokeType
a79c8115ca9bb13e24c4fd4db4931b3094a96549
[ "MIT" ]
null
null
null
PokeType/__main__.py
Daggy1234/PokeType
a79c8115ca9bb13e24c4fd4db4931b3094a96549
[ "MIT" ]
null
null
null
if __name__ == '__main__': print("CLI soon:tm:")
24.5
26
0.653061
b9ffd6dc7051aa24402462a9ce1758c0e40aaf57
2,488
swift
Swift
Coronapp/CoronaUI/GlobalSituationCaseView/GlobalSituationCaseView.swift
barisuyar/Coronapp
e968693229caa04bb5603092c4e67638381f9bc6
[ "MIT" ]
6
2020-04-30T12:21:46.000Z
2021-05-12T11:50:37.000Z
Coronapp/CoronaUI/GlobalSituationCaseView/GlobalSituationCaseView.swift
barisuyar/Coronapp
e968693229caa04bb5603092c4e67638381f9bc6
[ "MIT" ]
null
null
null
Coronapp/CoronaUI/GlobalSituationCaseView/GlobalSituationCaseView.swift
barisuyar/Coronapp
e968693229caa04bb5603092c4e67638381f9bc6
[ "MIT" ]
null
null
null
// // GlobalSituationCaseView.swift // CoronaUI // // Created by Barış Uyar on 28.03.2020. // Copyright © 2020 Barış Uyar. All rights reserved. // import Common import UIKit public protocol GlobalCaseProtocol { var caseName: String? { get } var caseCount: String? { get } var totalCaseCount: String? { get } var caseType: CaseType { get } } public enum CaseType { case confirmed case dead case recover } public class GlobalSituationCaseView: NibView { @IBOutlet private weak var caseDot: UIView! { didSet { caseDot.roundCorners(.allCorners, radius: 6) } } @IBOutlet private weak var caseNameLabel: UILabel! { didSet { caseNameLabel.textColor = .textColor } } @IBOutlet private weak var caseCountLabel: UILabel! { didSet { caseCountLabel.textColor = .textColor } } @IBOutlet private weak var caseProgress: UIView! { didSet { caseProgress.roundCorners(.allCorners, radius: 4) } } @IBOutlet private weak var caseRatio: UILabel! { didSet { caseRatio.isHidden = true caseRatio.textColor = .appRed } } @IBOutlet weak var caseProgressStackView: UIStackView! public func configure(with model: GlobalCaseProtocol) { let color: UIColor! switch model.caseType { case .confirmed: color = .appOrange case .dead: color = .appRed caseRatio.isHidden = false case .recover: color = .appCyan } caseDot.backgroundColor = color caseProgress.backgroundColor = color caseNameLabel.text = model.caseName caseCountLabel.text = model.caseCount if let caseFloat = (model.caseCount?.replacingOccurrences(of: ",", with: "") as NSString?)?.floatValue, let totalFloat = (model.totalCaseCount?.replacingOccurrences(of: ",", with: "") as NSString?)?.floatValue { caseProgress.translatesAutoresizingMaskIntoConstraints = false let ratio = caseFloat / totalFloat caseProgress.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: CGFloat(ratio)).isActive = true if case .dead = model.caseType { caseRatio.text = String(format: "%.2f", ratio * 100) } } else { caseProgressStackView.isHidden = true } } }
29.619048
119
0.607315
05b634a8c059d2bb71a3445843476ec62e3b3af8
2,204
py
Python
Adafruit_7Segment.py
VipSaran/Py_Led_Clock
715a8a6f285a7cd3b91880841794b9147f381616
[ "Apache-2.0" ]
5
2015-02-02T23:12:58.000Z
2019-09-11T00:56:26.000Z
Adafruit_7Segment.py
VipSaran/Py_Led_Clock
715a8a6f285a7cd3b91880841794b9147f381616
[ "Apache-2.0" ]
null
null
null
Adafruit_7Segment.py
VipSaran/Py_Led_Clock
715a8a6f285a7cd3b91880841794b9147f381616
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python import time import datetime from Adafruit_LEDBackpack import LEDBackpack # =========================================================================== # 7-Segment Display # =========================================================================== # This class is meant to be used with the four-character, seven segment # displays available from Adafruit class SevenSegment: disp = None # Hexadecimal character lookup table (row 1 = 0..9, row 2 = A..F) digits = [ 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, \ 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71 ] # Constructor def __init__(self, address=0x72, debug=False): if (debug): print "Initializing a new instance of LEDBackpack at 0x%02X" % address self.disp = LEDBackpack(address=address, debug=debug) # self.disp.setBrightness(1) def writeDigitRaw(self, charNumber, value): "Sets a digit using the raw 16-bit value" if (charNumber > 7): return # Set the appropriate digit self.disp.setBufferRow(charNumber, value) def writeDigit(self, charNumber, value, dot=False): "Sets a single decimal or hexademical value (0..9 and A..F)" if (charNumber > 7): return if (value > 0xF): return # Set the appropriate digit self.disp.setBufferRow(charNumber, self.digits[value] | (dot << 7)) def setColon(self, state=True): "Enables or disables the colon character" # Warning: This function assumes that the colon is character '2', # which is the case on 4 char displays, but may need to be modified # if another display type is used if (state): self.disp.setBufferRow(2, 0xFFFF) else: self.disp.setBufferRow(2, 0) def setBrightness(self, brightness=15): # print "setBrightness called", brightness "Sets the display brightness" if (self.is_number(brightness) and brightness >= 0 and brightness <= 15): # print "Setting brightness to", brightness self.disp.setBrightness(brightness) def clear(self, update=True): self.disp.clear(update) def is_number(self, s): try: float(s) return True except ValueError: return False
31.042254
77
0.625681
e2e7981c25c7d38d2efa490648e1d00e45657143
534
py
Python
knitscript/__main__.py
logicologist/knitscript
fbef1abe9a68995b91d791da9463e9acdc7d6b77
[ "MIT" ]
5
2019-07-19T21:32:53.000Z
2021-10-31T08:21:19.000Z
knitscript/__main__.py
logicologist/knitscript
fbef1abe9a68995b91d791da9463e9acdc7d6b77
[ "MIT" ]
22
2019-06-21T19:46:21.000Z
2019-07-19T21:45:32.000Z
knitscript/__main__.py
logicologist/knitscript
fbef1abe9a68995b91d791da9463e9acdc7d6b77
[ "MIT" ]
2
2019-06-21T03:53:28.000Z
2021-09-01T10:44:17.000Z
import sys from knitscript.interpreter import InterpretError from knitscript.loader import load_file def main() -> None: """ Prints the knitting instructions for a KnitScript pattern which is read from a file, or stdin if no filename is provided. """ if len(sys.argv) != 2: print(f"usage: knitscript <filename>") else: try: load_file(sys.argv[1], sys.stdout) except (IOError, InterpretError) as e: print(f"error: {e}") if __name__ == "__main__": main()
23.217391
75
0.632959
879ccec5ab771b692cffae3fbc75417db686e3e5
2,214
rb
Ruby
mingw-zlib.rb
xamarin/homebrew-xamarin-android-windeps
f4cc90845ff1953800d8d71035566a12d9b7aa24
[ "MIT" ]
1
2020-06-17T17:49:40.000Z
2020-06-17T17:49:40.000Z
mingw-zlib.rb
xamarin/homebrew-xamarin-android-windeps
f4cc90845ff1953800d8d71035566a12d9b7aa24
[ "MIT" ]
1
2020-10-30T17:34:51.000Z
2021-01-06T22:53:18.000Z
mingw-zlib.rb
xamarin/homebrew-xamarin-android-windeps
f4cc90845ff1953800d8d71035566a12d9b7aa24
[ "MIT" ]
null
null
null
class MingwZlib < Formula desc "zlib build for MinGW" homepage "https://zlib.net/" url "https://zlib.net/zlib-1.2.11.tar.gz" version "1.2.11" sha256 "c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1" bottle :unneded depends_on "mingw-w64" def targets ["i686-w64-mingw32", "x86_64-w64-mingw32"].freeze end def install targets.each do |target| mkdir "build-#{target}" do system "ln -s ../*.[ch] ../*.pc.in ../test ../win32 ." system "make -f win32/Makefile.gcc PREFIX=#{target}- DESTDIR=#{prefix} BINARY_PATH=/usr/#{target}/lib INCLUDE_PATH=/usr/#{target}/include LIBRARY_PATH=/usr/#{target}/lib SHARED_MODE=1 prefix=/usr install" end end end def caveats; <<~EOS In order to use Win32/Win64 zlib in your program you will need to pass the following flags to MinGW compilers: * Win32 -L#{prefix}/usr/i686-w64-mingw32/lib -I#{prefix}/usr/i686-w64-mingw32/include * Win64 -L#{prefix}/usr/x86_64-w64-mingw32/lib -I#{prefix}/usr/x86_64-w64-mingw32/include EOS end def post_install # Code commented out for now because for some reason symlink creation fails when executed # from this script but it *works* when ln -sf is executed from command line on the same # machine with exactly the same parameters. No clue what's going on # mingw_root = File.realpath("#{Formula["mingw-w64"].prefix}") # link_to_mingw "i686-w64-mingw32", "i686", mingw_root # link_to_mingw "x86_64-w64-mingw32", "x86_64", mingw_root end def link_to_mingw(target, toolchain, mingw_root) Dir.glob("#{prefix}/usr/#{target}/include/*.h") do |from| src = Pathname.new "#{mingw_root}/toolchain-#{toolchain}/#{target}/include" dest = Pathname.new(from).relative_path_from(src) Dir.chdir(src) do ln_sf dest, File.basename(from) end end Dir.glob("#{prefix}/usr/#{target}/lib/*.*") do |from| src = Pathname.new "#{mingw_root}/toolchain-#{toolchain}/#{target}/lib" dest = Pathname.new(from).relative_path_from(src) Dir.chdir(src) do ln_sf dest, File.basename(from) end end end end
32.086957
212
0.655827
472a961967b32a1fd38ba36093e6ad389886d05f
692
rb
Ruby
test/locate_test.rb
baya/ground
9cc51037691c390dae8116dcc806b6e115e82b1e
[ "MIT" ]
1
2017-10-20T14:17:13.000Z
2017-10-20T14:17:13.000Z
test/locate_test.rb
baya/ground
9cc51037691c390dae8116dcc806b6e115e82b1e
[ "MIT" ]
null
null
null
test/locate_test.rb
baya/ground
9cc51037691c390dae8116dcc806b6e115e82b1e
[ "MIT" ]
null
null
null
require 'test_helper' require 'routes' class LocateTest < Test::Unit::TestCase def test_locate location = Ground::Locate(verb: 'get', path: '/') assert_equal location, ['/', SiteIndex] location = Ground::Locate(verb: 'get', path: '/books') assert_equal location, ['/books', BooksIndex] location = Ground::Locate(verb: 'get', path: '/book/2') assert_equal location, ['/book/:id', BookShow] location = Ground::Locate(verb: 'post', path: '/book/3/comments') assert_equal location, ['/book/:id/comments', BookComments] location = Ground::Locate(verb: 'get', path: '/jim/notes') assert_equal location, ['/:username/notes', UserNotes] end end
28.833333
69
0.657514
7061a1ac28376b805db184206cb9ccdbfd5c7347
477
lua
Lua
Lua/Mgrs/ActionManager.lua
slove3000/emo
7c4a210298f06c915983280b85ec5db90d897378
[ "MIT" ]
10
2020-07-27T06:01:48.000Z
2022-03-18T09:58:53.000Z
Lua/Mgrs/ActionManager.lua
slove3000/emo
7c4a210298f06c915983280b85ec5db90d897378
[ "MIT" ]
null
null
null
Lua/Mgrs/ActionManager.lua
slove3000/emo
7c4a210298f06c915983280b85ec5db90d897378
[ "MIT" ]
6
2020-07-15T14:34:52.000Z
2021-08-18T10:07:57.000Z
local ActionManager = { actions = {} } function ActionManager.Add(action) table.insert(ActionManager.actions, action) end function ActionManager.Remove(action) for i, v in ipairs(ActionManager.actions) do if v == action then table.remove(ActionManager.actions, i) break; end end end function ActionManager.Update() for i, v in ipairs(ActionManager.actions) do v:Update() end end return ActionManager
19.08
50
0.662474
c9ec677d6274a895d252047b2312773cef329684
290
ts
TypeScript
models/riff-chunk.ts
BlauesMonster/WAV-Decoder
dbec99af00cff788dd8a60d7c47837c5a232607a
[ "MIT" ]
null
null
null
models/riff-chunk.ts
BlauesMonster/WAV-Decoder
dbec99af00cff788dd8a60d7c47837c5a232607a
[ "MIT" ]
null
null
null
models/riff-chunk.ts
BlauesMonster/WAV-Decoder
dbec99af00cff788dd8a60d7c47837c5a232607a
[ "MIT" ]
null
null
null
export class RIFFChunk{ public ChunkID: string; public ChunkSize: number; public Format: string constructor(_chunkID: string,_chunkSize: number, _format: string) { this.ChunkID = _chunkID; this.ChunkSize = _chunkSize; this.Format = _format; } }
24.166667
71
0.658621
143bf35ebaa2e23c9a7d60ed9a3e36e81c6e6432
315
ts
TypeScript
src/constants/punctuation.ts
Brettm12345/lunar
3195a1d38e778af55f9d6d6a2166fbb901173c50
[ "MIT" ]
null
null
null
src/constants/punctuation.ts
Brettm12345/lunar
3195a1d38e778af55f9d6d6a2166fbb901173c50
[ "MIT" ]
null
null
null
src/constants/punctuation.ts
Brettm12345/lunar
3195a1d38e778af55f9d6d6a2166fbb901173c50
[ "MIT" ]
null
null
null
export enum punctuation { comma = ',', semicolon = ';', openParenthesis = '(', closeParenthesis = ')', openBracket = '{', closeBracket = '}', openSquareBracket = '[', closeSquareBracket = ']' } export const punctuationValues = Object.values(punctuation).filter( current => current.length === 1 )
21
67
0.64127
e2d029e85b0fa0dde305f8e8e1b427ee36e05931
1,220
py
Python
supervised_learning/linear_regression.py
jrpespinas/Machine-Learning
9e58f78a2908bc4de83a51e78043ced360293acd
[ "Apache-2.0" ]
2
2020-05-13T19:28:39.000Z
2021-01-08T04:17:52.000Z
supervised_learning/linear_regression.py
jrpespinas/Machine-Learning
9e58f78a2908bc4de83a51e78043ced360293acd
[ "Apache-2.0" ]
null
null
null
supervised_learning/linear_regression.py
jrpespinas/Machine-Learning
9e58f78a2908bc4de83a51e78043ced360293acd
[ "Apache-2.0" ]
null
null
null
"""Linear Regression using Numpy""" from __future__ import absolute_import from __future__ import division from __future__ import print_function __version__ = '0.1.0' __author__ = 'Jan Rodolf Espinas' import numpy as np class LinearRegression: def __init__(self): self.weights = None self.bias = 0 def initialize_weights(self, X): num_features = X.shape[1] return np.zeros(num_features) def predict(self, X): return np.dot(X, self.weights) + self.bias def loss(self, y, y_hat): return np.sum(np.power((y_hat - y), 2)) / (2 * len(y)) def fit(self, X, y, learning_rate: float = 0.1, epochs: int = 300, verbosity: bool = True): self.weights = self.initialize_weights(X) num_samples = X.shape[0] for epoch in range(epochs): y_hat = self.predict(X) pd_w = (1 / num_samples) * np.dot(X.T, (y_hat - y)) pd_b = (1 / num_samples) * np.sum(y_hat - y) loss = self.loss(y, y_hat) self.weights -= learning_rate * pd_w self.bias -= learning_rate * pd_b if verbosity: print("Epoch: {}, Loss: {}".format(epoch, loss))
26.521739
64
0.589344
8db60f4757dd8f237ad8495ed1f1fbf6dce2b257
4,519
js
JavaScript
data/src/routes/entity.js
kosinix/ridsys-admin
ab5e90a2edef8c6ade326ee17d0b9b77625d9e62
[ "MIT" ]
null
null
null
data/src/routes/entity.js
kosinix/ridsys-admin
ab5e90a2edef8c6ade326ee17d0b9b77625d9e62
[ "MIT" ]
null
null
null
data/src/routes/entity.js
kosinix/ridsys-admin
ab5e90a2edef8c6ade326ee17d0b9b77625d9e62
[ "MIT" ]
null
null
null
//// Core modules const fs = require('fs') //// External modules const express = require('express') const fileUpload = require('express-fileupload') const flash = require('kisapmata') const phAddress = require('ph-address') const lodash = require('lodash') const moment = require('moment') const qr = require('qr-image') //// Modules const db = require('../db'); const middlewares = require('../middlewares'); const paginator = require('../paginator'); const passwordMan = require('../password-man'); // Router let router = express.Router() router.use('/entity', middlewares.requireAuthUser ) router.get('/entity/all', middlewares.guardRoute(['read_all_entity', 'read_entity']), async (req, res, next) => { try { let page = parseInt(lodash.get(req, 'query.page', 1)) let perPage = parseInt(lodash.get(req, 'query.perPage', 1)) let sortBy = lodash.get(req, 'query.sortBy', '_id') let sortOrder = parseInt(lodash.get(req, 'query.sortOrder', 1)) let customSort = parseInt(lodash.get(req, 'query.customSort')) let query = {} let projection = {} // Pagination let totalDocs = await db.main.Entity.countDocuments(query) let pagination = paginator.paginate( page, totalDocs, perPage, '/entity/all', req.query ) let options = { skip: (page - 1) * perPage, limit: perPage }; let sort = {} sort = lodash.set(sort, sortBy, sortOrder) console.log(query, projection, options, sort) let entities = await db.main.Entity.find(query, projection, options).sort(sort).lean() let doors = [] entities.forEach((entity)=>{ doors.push(db.main.Door.find({ entityId: entity._id })) // return array of doors }) doors = await Promise.all(doors) entities.forEach((entity, i)=>{ entity.doors = doors[i] }) res.render('entity/all.html', { flash: flash.get(req, 'entity'), entities: entities, pagination: pagination, query: req.query, }); } catch (err) { next(err); } }); router.get('/entity/create', middlewares.guardRoute(['create_entity']), async (req, res, next) => { try { res.render('entity/create.html', { }); } catch (err) { next(err); } }); router.post('/entity/create', middlewares.guardRoute(['create_entity']), async (req, res, next) => { try { let body = req.body let patch = {} lodash.set(patch, 'name', lodash.get(body, 'name')) let entity = new db.main.Entity(patch) await entity.save() flash.ok(req, 'entity', `Added ${entity.name}.`) res.redirect(`/entity/${entity._id}`) } catch (err) { next(err); } }); router.get('/entity/:entityId', middlewares.getEntity, async (req, res, next) => { try { let entity = res.entity.toObject() entity.doors = await db.main.Door.find({entityId: entity._id}); res.render('entity/read.html', { flash: flash.get(req, 'entity'), entity: entity, }); } catch (err) { next(err); } }); router.get('/entity/:entityId/door/create', middlewares.getEntity, async (req, res, next) => { try { let entity = res.entity res.render('entity/door/create.html', { flash: flash.get(req, 'entity'), entity: entity, }); } catch (err) { next(err); } }); router.post('/entity/:entityId/door/create', middlewares.getEntity, async (req, res, next) => { try { let entity = res.entity let body = req.body let patch = {} let password = passwordMan.randomString(8) let salt = passwordMan.randomString(16) let passwordHash = passwordMan.hashPassword(password, salt) lodash.set(patch, 'entityId', lodash.get(entity, '_id')) lodash.set(patch, 'name', lodash.get(body, 'name')) lodash.set(patch, 'passwordHash', passwordHash) lodash.set(patch, 'salt', salt) let door = new db.main.Door(patch) await door.save() flash.ok(req, 'entity', `Added ${door.name}. ID is "${door.uid}" and password is "${password}". You will only see your password once so please save it in a secure place.`) res.redirect(`/entity/${entity._id}`) } catch (err) { next(err); } }); module.exports = router;
30.328859
179
0.578225
c67cd3b4d699cb7cd92bf9300c852b286d9c97d4
489
lua
Lua
plugins/utils.lua
drmargarido/dr-tracker
9bd7568719c72741156b8898b92050e29c3ecc4b
[ "MIT" ]
17
2019-11-17T01:04:48.000Z
2021-11-06T09:40:52.000Z
plugins/utils.lua
drmargarido/dr-tracker
9bd7568719c72741156b8898b92050e29c3ecc4b
[ "MIT" ]
3
2020-02-07T12:43:42.000Z
2020-08-06T18:24:32.000Z
plugins/utils.lua
drmargarido/d-tracker
99e6ed113f655cc8e90aefacad7b82b0cc55a6de
[ "MIT" ]
null
null
null
local ui = require "tek.ui" return { register_window = function(app, window) ui.Application.connect(window) app:addMember(window) end, show_window = function(self, app, id) local _, _, x, y = self.Window.Drawable:getAttrs() -- Archor to the main window position local window = app:getById(id) window:setValue("Top", y) window:setValue("Left", x) -- Display window with the options to select the theme window:setValue("Status", "show") end }
23.285714
58
0.666667
01601116b070a3520ae10f71bc1f244a87e2f9a3
43
sql
SQL
languages/modules/weixin/uninstall/weixin_menu.sql
lupengyu0226/www.zhikunet.org
eca9428f831eb023c99bf0825b401d88ab09c804
[ "Apache-2.0" ]
null
null
null
languages/modules/weixin/uninstall/weixin_menu.sql
lupengyu0226/www.zhikunet.org
eca9428f831eb023c99bf0825b401d88ab09c804
[ "Apache-2.0" ]
null
null
null
languages/modules/weixin/uninstall/weixin_menu.sql
lupengyu0226/www.zhikunet.org
eca9428f831eb023c99bf0825b401d88ab09c804
[ "Apache-2.0" ]
null
null
null
DROP TABLE IF EXISTS `shuyang_weixin_menu`;
43
43
0.837209
d662ddeda4723273ef7546a6d17afec7369a4c95
477
cs
C#
src/Extras/Jabberwock.Extras.NewRelic.Sc/Pipelines/RenderRendering/StartResponseTimeMetricProcessor.cs
kmazzoni/Jabberwocky
4ece32e1806b1b51ea681e1f94533a719f9650da
[ "MIT" ]
5
2016-12-13T15:12:25.000Z
2018-07-23T15:32:21.000Z
src/Extras/Jabberwock.Extras.NewRelic.Sc/Pipelines/RenderRendering/StartResponseTimeMetricProcessor.cs
kmazzoni/Jabberwocky
4ece32e1806b1b51ea681e1f94533a719f9650da
[ "MIT" ]
6
2016-11-10T02:13:36.000Z
2018-02-23T17:09:36.000Z
src/Extras/Jabberwock.Extras.NewRelic.Sc/Pipelines/RenderRendering/StartResponseTimeMetricProcessor.cs
kmazzoni/Jabberwocky
4ece32e1806b1b51ea681e1f94533a719f9650da
[ "MIT" ]
7
2016-11-10T15:15:34.000Z
2019-06-04T21:06:56.000Z
using System.Diagnostics; using Jabberwocky.Extras.NewRelic.Sc.Reference; using Sitecore.Mvc.Pipelines.Response.RenderRendering; namespace Jabberwocky.Extras.NewRelic.Sc.Pipelines.RenderRendering { public class StartResponseTimeMetricProcessor : RenderRenderingProcessor { public override void Process(RenderRenderingArgs args) { var stopwatch = new Stopwatch(); stopwatch.Start(); args.CustomData.Add(Constants.NewRelicBeginStartTimeKey, stopwatch); } } }
28.058824
73
0.805031
e83af7217276d350f97069c1ef45e72435f2c1f8
271
cshtml
C#
docs/input/docs/reference/modes/index.cshtml
mglochsen/GitVersion
e9013533474e8e46b6a0ca60d20d02f3680b5980
[ "MIT" ]
1
2021-03-08T09:31:44.000Z
2021-03-08T09:31:44.000Z
docs/input/docs/reference/modes/index.cshtml
mglochsen/GitVersion
e9013533474e8e46b6a0ca60d20d02f3680b5980
[ "MIT" ]
55
2021-01-07T07:09:39.000Z
2022-03-22T08:18:02.000Z
docs/input/docs/reference/modes/index.cshtml
mglochsen/GitVersion
e9013533474e8e46b6a0ca60d20d02f3680b5980
[ "MIT" ]
null
null
null
--- Order: 50 Title: Versioning Modes Description: The different modes of versioning GitVersion supports --- <p> GitVersion supports a few different versioning modes. They are described in detail on the pages enumerated below. </p> @Html.Partial("_ChildPages")
20.846154
76
0.752768
38c6cd24962400fe95204da0cb26489c44b9b814
4,462
php
PHP
web/profiles/varbase/modules/contrib/responsive_preview/src/ResponsivePreview.php
jadamsbit/jamie-auto
6800411075e9c3b2bc23cbce8fc2790043b35ee9
[ "MIT" ]
null
null
null
web/profiles/varbase/modules/contrib/responsive_preview/src/ResponsivePreview.php
jadamsbit/jamie-auto
6800411075e9c3b2bc23cbce8fc2790043b35ee9
[ "MIT" ]
8
2019-04-27T00:11:03.000Z
2021-09-01T07:04:50.000Z
docroot/modules/contrib/responsive_preview/src/ResponsivePreview.php
DiversiCon/uc-d8-deploy
39294a57583639883bc6b9b87bf818de471aed13
[ "MIT" ]
null
null
null
<?php namespace Drupal\responsive_preview; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Path\CurrentPathStack; use Drupal\Core\Routing\AdminContext; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\Core\Session\AccountProxyInterface; use Drupal\Core\Url; use Drupal\responsive_preview\Entity\Device; /** * ResponsivePreview service. */ class ResponsivePreview implements ResponsivePreviewInterface { /** * Admin context service. * * @var \Drupal\Core\Routing\AdminContext */ protected $routerAdminContext; /** * The current path. * * @var \Drupal\Core\Path\CurrentPathStack */ protected $currentPathStack; /** * The route match service. * * @var \Drupal\Core\Routing\RouteMatchInterface */ protected $routeMatch; /** * The entity type manager. * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; /** * The current user. * * @var \Drupal\Core\Session\AccountProxyInterface */ protected $currentUser; /** * ResponsivePreview constructor. * * @param \Drupal\Core\Routing\AdminContext $adminContext * Admin context service. * @param \Drupal\Core\Path\CurrentPathStack $currentPathStack * CurrentPathStack service to get the path. * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch * The route match service. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager * The entity type manager. * @param \Drupal\Core\Session\AccountProxyInterface $currentUser * The current user. */ public function __construct(AdminContext $adminContext, CurrentPathStack $currentPathStack, RouteMatchInterface $routeMatch, EntityTypeManagerInterface $entityTypeManager, AccountProxyInterface $currentUser) { $this->routerAdminContext = $adminContext; $this->currentPathStack = $currentPathStack; $this->routeMatch = $routeMatch; $this->entityTypeManager = $entityTypeManager; $this->currentUser = $currentUser; } /** * {@inheritdoc} */ public function getUrl() { $url = NULL; if (!$this->routerAdminContext->isAdminRoute()) { $url = $this->currentPathStack->getPath(); } else { // If we are on an edit-form, try to resolve the canonical url. $form = $this->routeMatch->getRouteObject()->getDefault("_entity_form"); if ($form) { $entity_type = current(explode('.', $form)); /** @var \Drupal\Core\Entity\EntityInterface $entity */ $entity = $this->routeMatch->getParameter($entity_type); if ($entity && $entity->hasLinkTemplate('canonical')) { $url = $entity->toUrl()->toString(); } } } return $url; } /** * {@inheritdoc} */ public function getRenderableDevicesList() { $links = []; /** @var \Drupal\responsive_preview\Entity\Device[] $devices */ $devices = $this->entityTypeManager ->getStorage('responsive_preview_device') ->loadByProperties(['status' => 1]); uasort($devices, [Device::class, 'sort']); foreach ($devices as $name => $entity) { $dimensions = $entity->getDimensions(); $links[$name] = [ '#type' => 'html_tag', '#tag' => 'button', '#value' => $entity->label(), '#attributes' => [ 'data-responsive-preview-name' => $name, 'data-responsive-preview-width' => $dimensions['width'], 'data-responsive-preview-height' => $dimensions['height'], 'data-responsive-preview-dppx' => $dimensions['dppx'], 'class' => [ 'responsive-preview-device', 'responsive-preview-icon', 'responsive-preview-icon-active', ], ], ]; } // Add a configuration link. $links['configure_link'] = [ '#type' => 'link', '#title' => t('Configure devices'), '#url' => Url::fromRoute('entity.responsive_preview_device.collection'), '#access' => $this->currentUser->hasPermission('administer responsive preview'), '#attributes' => [ 'class' => ['responsive-preview-configure'], ], ]; return [ '#theme' => 'item_list__responsive_preview', '#items' => $links, '#attributes' => [ 'class' => ['responsive-preview-options'], ], '#wrapper_attributes' => [ 'class' => ['responsive-preview-item-list'], ], ]; } }
28.240506
211
0.630435
2ce95a4f2a6bb7558949c48cd0cf73414da05e50
798
cpp
C++
examples/cppwin2/TensorflowTTSCppInference/MultiBandMelGAN.cpp
ronggong/TensorFlowTTS
7541ee6cdf2f6e264384d2a47a74ae56d6305d33
[ "Apache-2.0" ]
null
null
null
examples/cppwin2/TensorflowTTSCppInference/MultiBandMelGAN.cpp
ronggong/TensorFlowTTS
7541ee6cdf2f6e264384d2a47a74ae56d6305d33
[ "Apache-2.0" ]
null
null
null
examples/cppwin2/TensorflowTTSCppInference/MultiBandMelGAN.cpp
ronggong/TensorFlowTTS
7541ee6cdf2f6e264384d2a47a74ae56d6305d33
[ "Apache-2.0" ]
null
null
null
#include "MultiBandMelGAN.h" bool MultiBandMelGAN::Initialize(const std::string & VocoderPath) { MelGAN = std::make_unique<Model>(VocoderPath); return true; } Tensor MultiBandMelGAN::DoInference(Tensor& InMel) { VX_IF_EXCEPT(!MelGAN, "Tried to infer MB-MelGAN on uninitialized model!!!!"); // Convenience reference so that we don't have to constantly derefer pointers. Tensor input_mels{ *MelGAN,"serving_default_mels" }; input_mels.set_data(InMel.get_data<float>(), InMel.get_shape()); Tensor out_audio{ *MelGAN, "StatefulPartitionedCall" }; MelGAN->run(input_mels, out_audio); // TFTensor<float> RetTensor = VoxUtil::CopyTensor<float>(out_audio); return out_audio; } MultiBandMelGAN::MultiBandMelGAN() { // MelGAN = nullptr; } MultiBandMelGAN::~MultiBandMelGAN() { }
19.95
81
0.741855
05fff90dfc18ca80e2f44024da43ab6b85d2a93a
3,331
py
Python
bisnode/constants.py
FundedByMe/django-bisnode
51659c69d5208e238dd3bfeb9feed27b5424c7ac
[ "MIT" ]
null
null
null
bisnode/constants.py
FundedByMe/django-bisnode
51659c69d5208e238dd3bfeb9feed27b5424c7ac
[ "MIT" ]
5
2015-01-16T08:39:00.000Z
2015-10-23T13:01:43.000Z
bisnode/constants.py
FundedByMe/django-bisnode
51659c69d5208e238dd3bfeb9feed27b5424c7ac
[ "MIT" ]
2
2015-08-06T09:49:09.000Z
2020-04-29T09:46:06.000Z
from django.utils.translation import ugettext_lazy as _ COMPANY_STANDARD_REPORT = "NRGCompanyReportStandard" COMPANY_RATING_REPORT = "NRGCompanyReportRating" CURRENCY = "SEK" HIGH = 'AAA' GOOD = 'AA' WORTHY = 'A' NEW = 'AN' BELOW_AVERAGE = 'B' BAD = 'C' MISSING = '-' NEWLY_FORMED = 'NYTT' RATING_CHOICES = ( (HIGH, _("Highest credit worthiness")), (GOOD, _("Good credit worthiness")), (WORTHY, _("Credit worthy")), (NEW, _("New company")), (BELOW_AVERAGE, _("Credit with safety measurements")), (BAD, _("Credit advised against")), (MISSING, _("Rating not applicable")), (NEWLY_FORMED, _("Newly formed company")), ) WELL_ESTABLISHED = 'AGE010' ESTABLISHED = 'AGE020' SMALLER_SCALE = 'AGE030' LESS_THAN_TWO_YEARS = 'AGE040' OPERATION_CHOICES = ( (WELL_ESTABLISHED, _('Well-established')), (ESTABLISHED, _('Established')), (SMALLER_SCALE, _('2-4 years')), (LESS_THAN_TWO_YEARS, _('Less than two years')), ) OPERATION_CHOICES_DICT = dict(OPERATION_CHOICES) SATISFACTORY = 'OWN030' NOTES_ON_RECORD = 'OWN100' NEGATIVE_ON_RECORD = 'OWN040' CURRENT_NEGATIVE = 'OWN050' NEGATIVE_GROUP = 'OWN090' INCOMPLETE = 'OWN080' MANAGEMENT_CHOICES = ( (SATISFACTORY, _('Satisfactory')), (NOTES_ON_RECORD, _('Notes on record')), (NEGATIVE_ON_RECORD, _('Negative info on record')), (NEGATIVE_GROUP, _('Negative info - group')), (CURRENT_NEGATIVE, _('Current negative info')), (INCOMPLETE, _('Incomplete')) ) MANAGEMENT_CHOICES_DICT = dict(MANAGEMENT_CHOICES) VERY_GOOD_FINANCES = 'ECO010' GOOD_FINANCES = 'ECO020' SATISFACTORY_FINANCES = 'ECO030' UNSATISFACTORY_FINANCES = 'ECO040' WEAK_FINANCES = 'ECO050' SEE_SPECIFICATIONS = 'ECO060' NOT_UPDATED = 'ECO070' NOT_UPDATED2 = 'ECO090' NOT_UPDATED3 = 'ECO100' UNAVAILABLE = 'ECO110' FINANCES_CHOICES = ( (VERY_GOOD_FINANCES, _('Very good')), (GOOD_FINANCES, _('Good')), (SATISFACTORY_FINANCES, _('Satisfactory')), (UNSATISFACTORY_FINANCES, _('Unsatisfactory')), (WEAK_FINANCES, _('Weak')), (SEE_SPECIFICATIONS, _('See financial specifications')), (NOT_UPDATED, _('Annual accounts not updated')), (NOT_UPDATED2, _('Annual accounts not updated')), (NOT_UPDATED3, _('Annual accounts not updated')), (UNAVAILABLE, _('Annual accounts unavailable')) ) FINANCES_CHOICES_DICT = dict(FINANCES_CHOICES) VERY_GOOD_SOLVENCY = 'PAY010' VERY_GOOD_NOTES_ON_RECORD = 'PAY020' GOOD_SOLVENCY = 'PAY030' GOOD_NOTES_ON_RECORD = 'PAY040' SATISFACTORY_SOLVENCY = 'PAY050' SATISFACTORY_NOTES_ON_RECORD = 'PAY060' UNSATISFACTORY_SOLVENCY = 'PAY070' WEAK_SOLVENCY = 'PAY080' VERY_WEAK_SOLVENCY = 'PAY090' SOLVENCY_CHOICES = ( (VERY_GOOD_SOLVENCY, _('Very good')), (VERY_GOOD_NOTES_ON_RECORD, _('Very good - notes on record')), (GOOD_SOLVENCY, _('Good')), (GOOD_NOTES_ON_RECORD, _('Good - notes on record')), (SATISFACTORY_SOLVENCY, _('Satisfactory')), (SATISFACTORY_NOTES_ON_RECORD, _('Satisfactory - notes on record')), (UNSATISFACTORY_SOLVENCY, _('Unsatisfactory')), (WEAK_SOLVENCY, _('Weak')), (VERY_WEAK_SOLVENCY, _('Very weak')), ) SOLVENCY_CHOICES_DICT = dict(SOLVENCY_CHOICES) BOARD_MEMBERS_FUNCTION_CHOICES = ( ('00', _('Member managing dir.')), ('20', _('Member')), ('32', _('Deputy')), ('97', _('Auditor')), ('', _('Member')), )
27.528926
72
0.70009
c6c77ec4272db4da3dadeb51954f7bca17db36e5
311
css
CSS
src/locale/DE/styles/flex/ratio--1x4.css
HarunaOrg/paypal-messaging-components
93aa82e15bf8d59827da2725de2cc33df8bcf356
[ "Apache-2.0" ]
21
2019-06-04T16:23:13.000Z
2021-12-22T22:41:07.000Z
src/locale/DE/styles/flex/ratio--1x4.css
HarunaOrg/paypal-messaging-components
93aa82e15bf8d59827da2725de2cc33df8bcf356
[ "Apache-2.0" ]
473
2019-09-07T17:09:58.000Z
2022-03-29T17:26:04.000Z
src/locale/DE/styles/flex/ratio--1x4.css
HarunaOrg/paypal-messaging-components
93aa82e15bf8d59827da2725de2cc33df8bcf356
[ "Apache-2.0" ]
47
2019-06-11T14:05:14.000Z
2022-03-22T20:16:57.000Z
.message__logo-container { width: 100%; margin-bottom: 30%; } .message__headline { font-size: 1.4rem; margin-bottom: 30%; } .message__disclaimer span.multi:nth-of-type(1) { display: inline; } @media (max-aspect-ratio: 11/40) { .message__headline { margin-bottom: 50%; } }
15.55
48
0.620579
c3bfffaa8c0af17d8ede359602a1bf50881fe96f
8,477
dart
Dart
fluttersamples/lib/samples/gridview_samples.dart
futteranddart/flutterSamples
70d759255563ac5510252e345c9456e3404db818
[ "BSD-3-Clause" ]
2
2019-03-05T12:48:51.000Z
2019-10-16T08:25:27.000Z
fluttersamples/lib/samples/gridview_samples.dart
futteranddart/flutterSamples
70d759255563ac5510252e345c9456e3404db818
[ "BSD-3-Clause" ]
null
null
null
fluttersamples/lib/samples/gridview_samples.dart
futteranddart/flutterSamples
70d759255563ac5510252e345c9456e3404db818
[ "BSD-3-Clause" ]
1
2020-11-27T08:17:35.000Z
2020-11-27T08:17:35.000Z
/* * @Author: Tan Dong * @Date: 2019-02-22 22:29:39 * @Last Modified by: Tan Dong * @Last Modified time: 2019-02-22 22:29:39 */ import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class GridViewSamples extends StatefulWidget { @override State<StatefulWidget> createState() { return GridViewSamplesState(); } } class GridViewSamplesState extends State<GridViewSamples> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GridView'), backgroundColor: Colors.teal, primary: true, ), body: gridView5(), ); } Widget gridView1() { return GridView( ///设置Grid属性: ///SliverGridDelegateWithMaxCrossAxisExtent: ///按照设置最大扩展宽度计算item个数 ///SliverGridDelegateWithFixedCrossAxisCount: ///可以固定设置每行item个数 gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, ), children: <Widget>[ Stack( children: <Widget>[ Positioned( bottom: 0, child: Text('data'), ), Positioned( top: 0, left: 0, right: 0, bottom: 0, child: Image.asset( 'assets/flutter-mark-square-64.png', fit: BoxFit.cover, ), ), ], ), Stack( alignment: AlignmentDirectional.bottomCenter, children: <Widget>[ Image.asset('assets/flutter-mark-square-64.png'), Text('data'), ], ), Stack( alignment: AlignmentDirectional.bottomCenter, children: <Widget>[ Image.asset('assets/flutter-mark-square-64.png'), Text('data'), ], ), Stack( alignment: AlignmentDirectional.bottomCenter, children: <Widget>[ Image.asset('assets/flutter-mark-square-64.png'), Text('data'), ], ), Stack( alignment: AlignmentDirectional.bottomCenter, children: <Widget>[ Image.asset('assets/flutter-mark-square-64.png'), Text('data'), ], ), ], ); } Widget gridView2() { return GridView.builder( itemCount: 20, itemBuilder: (BuildContext context, int index) { return GridTile( header: GridTileBar( title: Text( 'header', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, leading: Icon( Icons.star, color: Colors.white, ), ), child: Image.asset('assets/flutter-mark-square-64.png'), footer: GridTileBar( title: Text( 'bottom', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, ), ); }, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, ), ); } Widget gridView3() { return GridView.custom( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, childAspectRatio: 2, ), childrenDelegate: SliverChildBuilderDelegate((BuildContext context, int index) { return Container( child: Text( 'GridTile', style: TextStyle(fontSize: 16), ), ); }, childCount: 20), ); } Widget gridView4() { return GridView.count( crossAxisCount: 2, mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1, children: <Widget>[ GridTile( child: Image.asset('assets/flutter-mark-square-64.png'), ), GridTile( child: Image.asset('assets/flutter-mark-square-64.png'), ), GridTile( child: Image.asset('assets/flutter-mark-square-64.png'), ), GridTile( child: Image.asset('assets/flutter-mark-square-64.png'), ), GridTile( child: Image.asset('assets/flutter-mark-square-64.png'), ), GridTile( child: Image.asset('assets/flutter-mark-square-64.png'), ), ], ); } ///GridView.extent构建GridView,根据最大宽度自动计算item数量 Widget gridView5() { return GridView.extent( maxCrossAxisExtent: 150, crossAxisSpacing: 10, mainAxisSpacing: 10, childAspectRatio: 1, children: <Widget>[ GridTile( header: GridTileBar( title: Text( 'header', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, leading: Icon( Icons.star, color: Colors.white, ), ), child: Image.asset('assets/flutter-mark-square-64.png'), footer: GridTileBar( title: Text( 'bottom', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, ), ), GridTile( header: GridTileBar( title: Text( 'header', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, leading: Icon( Icons.star, color: Colors.white, ), ), child: Image.asset('assets/flutter-mark-square-64.png'), footer: GridTileBar( title: Text( 'bottom', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, ), ), GridTile( header: GridTileBar( title: Text( 'header', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, leading: Icon( Icons.star, color: Colors.white, ), ), child: Image.asset('assets/flutter-mark-square-64.png'), footer: GridTileBar( title: Text( 'bottom', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, ), ), GridTile( header: GridTileBar( title: Text( 'header', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, leading: Icon( Icons.star, color: Colors.white, ), ), child: Image.asset('assets/flutter-mark-square-64.png'), footer: GridTileBar( title: Text( 'bottom', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, ), ), GridTile( header: GridTileBar( title: Text( 'header', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, leading: Icon( Icons.star, color: Colors.white, ), ), child: Image.asset('assets/flutter-mark-square-64.png'), footer: GridTileBar( title: Text( 'bottom', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, ), ), GridTile( header: GridTileBar( title: Text( 'header', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, leading: Icon( Icons.star, color: Colors.white, ), ), child: Image.asset('assets/flutter-mark-square-64.png'), footer: GridTileBar( title: Text( 'bottom', style: TextStyle(fontSize: 20), ), backgroundColor: Colors.black45, ), ), ], ); } }
26.573668
72
0.48956
5bf17b1e056cd001f4e4592e8ef1d65d2dc77950
1,193
sql
SQL
sql/withdraw.sql
xyrit/huogouadmin
26ec6286a846e6645b739eadb6b06187dc5207f0
[ "BSD-3-Clause" ]
2
2018-12-03T06:55:51.000Z
2019-05-05T07:25:17.000Z
sql/withdraw.sql
raoxy5/huogouadmin
26ec6286a846e6645b739eadb6b06187dc5207f0
[ "BSD-3-Clause" ]
null
null
null
sql/withdraw.sql
raoxy5/huogouadmin
26ec6286a846e6645b739eadb6b06187dc5207f0
[ "BSD-3-Clause" ]
1
2021-06-03T05:22:02.000Z
2021-06-03T05:22:02.000Z
CREATE TABLE `withdraw` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` INT(10) NOT NULL COMMENT '申请用户ID', `money` SMALLINT(6) UNSIGNED NOT NULL COMMENT '申请提现金额(分)', `account` VARCHAR(20) NOT NULL COMMENT '开户人', `bank` VARCHAR(40) NOT NULL COMMENT '银行名称', `branch` VARCHAR(100) NOT NULL COMMENT '开户支行', `phone` CHAR(11) NOT NULL COMMENT '联系电话', `bank_number` CHAR(30) NOT NULL COMMENT '银行账号', `service_charge` SMALLINT(6) NOT NULL DEFAULT '0' COMMENT '手续费(分)', `status` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '审核状态,0表示未审核', `payment` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '支付方式', `payment_no` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '支付单号', `payment_money` SMALLINT(6) NOT NULL DEFAULT 0 COMMENT '支付金额', `apply_time` INT(10) NOT NULL DEFAULT 0 COMMENT '申请时间', `audit_time` INT(10) NOT NULL DEFAULT 0 COMMENT '审核时间', `pass_time` INT(10) NOT NULL DEFAULT 0 COMMENT '完成时间', `audit_user` INT(10) NOT NULL DEFAULT 0 COMMENT '审核人', `pass_user` INT(10) NOT NULL DEFAULT 0 COMMENT '处理人', `fail_type` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '失败原因,驳回原因', PRIMARY KEY (`id`), KEY `user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='提现表';
51.869565
69
0.702431
a32bfbedd34b1f2e6ccf317caab48f1a5af24876
1,853
java
Java
schedoscope-export/src/main/java/org/schedoscope/export/ftp/outputformat/JsonRecordWriter.java
cwsteinbach/schedoscope
5fa5d6c2a672ff61722fbd8f1959fe0406f44a9b
[ "Apache-2.0" ]
112
2015-05-12T19:30:58.000Z
2022-01-13T09:26:56.000Z
schedoscope-export/src/main/java/org/schedoscope/export/ftp/outputformat/JsonRecordWriter.java
cwsteinbach/schedoscope
5fa5d6c2a672ff61722fbd8f1959fe0406f44a9b
[ "Apache-2.0" ]
44
2015-06-24T13:53:05.000Z
2018-03-27T08:25:32.000Z
schedoscope-export/src/main/java/org/schedoscope/export/ftp/outputformat/JsonRecordWriter.java
cwsteinbach/schedoscope
5fa5d6c2a672ff61722fbd8f1959fe0406f44a9b
[ "Apache-2.0" ]
33
2015-07-27T12:51:58.000Z
2021-12-15T17:27:10.000Z
/** * Copyright 2016 Otto (GmbH & Co KG) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.schedoscope.export.ftp.outputformat; /** * The Json Record Writer is used to write the records as JSON to a file. */ import org.apache.avro.generic.GenericRecord; import org.apache.avro.mapred.AvroValue; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.DataOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class JsonRecordWriter<K, V> extends RecordWriter<K, V> { private static final String NEWLINE = "\n"; private DataOutputStream out; /** * The constructor to initialize the Json Record Writer. * * @param out A data output stream. */ public JsonRecordWriter(DataOutputStream out) { this.out = out; } @SuppressWarnings("unchecked") @Override public void write(K key, V value) throws IOException { AvroValue<GenericRecord> avroValue = (AvroValue<GenericRecord>) value; out.write(avroValue.datum().toString().getBytes(StandardCharsets.UTF_8)); out.write(NEWLINE.getBytes(StandardCharsets.UTF_8)); } @Override public void close(TaskAttemptContext context) throws IOException { out.close(); } }
29.412698
81
0.717215
a9e9eac8d7efc0c03b31437d9e89af6d230984c7
1,876
php
PHP
app/Http/Controllers/EEBillingController.php
franklinff/neosoftmbd
31a50f6e9ea713c512af9c696b6612caea7963c5
[ "MIT" ]
null
null
null
app/Http/Controllers/EEBillingController.php
franklinff/neosoftmbd
31a50f6e9ea713c512af9c696b6612caea7963c5
[ "MIT" ]
null
null
null
app/Http/Controllers/EEBillingController.php
franklinff/neosoftmbd
31a50f6e9ea713c512af9c696b6612caea7963c5
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class EEBillingController extends Controller { public function Login(){ return view('admin.ee_billing.login'); } public function Dashboard(){ return view('admin.ee_billing.dashboard'); } public function ListOfSocieties(){ return view('admin.ee_billing.list-of-societies'); } public function AddRates(){ return view('admin.ee_billing.add-rates'); } public function ArrearsChargesRate(){ return view('admin.ee_billing.arrears-charges-rate'); } public function AddBuilding(){ return view('admin.ee_billing.add-building'); } public function EditBuilding(){ return view('admin.ee_billing.edit-building'); } public function ManageMasters(){ return view('admin.ee_billing.manage-masters'); } public function BillingLevel(){ return view('admin.ee_billing.billing-level'); } public function WardColony(){ return view('admin.ee_billing.ward-colony'); } public function AddTenant(){ return view('admin.ee_billing.add-tenant'); } public function SocietyBillGeneration(){ return view('admin.ee_billing.society-bill-generation'); } public function TenantBillGeneration(){ return view('admin.ee_billing.tenant-bill-generation'); } public function SocietyConveyanceApplication(){ return view('admin.ee_billing.society-conveyance-application'); } public function ArrearsCalculation(){ return view('admin.ee_billing.arrears-calculation'); } public function ViewBillDetailsSociety(){ return view('admin.ee_billing.view-bill-details-society'); } public function GenerateReceipt(){ return view('admin.ee_billing.generate-receipt'); } }
24.684211
71
0.666311
e1f3714412cbdc73a43a7f230bb36a735f8816b0
245
cpp
C++
SelfTrainBeforeGBLTContest/L1-041.cpp
YaKaiLi/YaKaiLi-PAT-Related
5eca2d90a6e7fc069fd8c320721d337676200ade
[ "MIT" ]
null
null
null
SelfTrainBeforeGBLTContest/L1-041.cpp
YaKaiLi/YaKaiLi-PAT-Related
5eca2d90a6e7fc069fd8c320721d337676200ade
[ "MIT" ]
null
null
null
SelfTrainBeforeGBLTContest/L1-041.cpp
YaKaiLi/YaKaiLi-PAT-Related
5eca2d90a6e7fc069fd8c320721d337676200ade
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> #include <math.h> using namespace std; int main(){ int flag=1; int inputTmp=0; while(1){ cin>>inputTmp; if(inputTmp==250){ cout<<flag; break; } flag++; } return 0; }
12.25
20
0.628571
3fa70dbde6fb3418384961a6bd7a1edc5eb75161
525
php
PHP
routes/api.php
AndrianiClaudio/laravel-mail-auth
7ac7ef9a61f359de214803ed9192efc8e5f70fed
[ "MIT" ]
null
null
null
routes/api.php
AndrianiClaudio/laravel-mail-auth
7ac7ef9a61f359de214803ed9192efc8e5f70fed
[ "MIT" ]
null
null
null
routes/api.php
AndrianiClaudio/laravel-mail-auth
7ac7ef9a61f359de214803ed9192efc8e5f70fed
[ "MIT" ]
null
null
null
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::middleware('auth:api') ->get('/user', function (Request $request) { return $request->user(); }); Route::namespace ('Api') ->group(function () { Route::post('/contacts', 'ContactController@store'); Route::get('/projects', 'ProjectController@all'); Route::get('/technologies', 'TechnologyController@all'); Route::get('/projects/technologies', 'ProjectController@filterByTechnologies'); });
32.8125
87
0.647619
ea366fe81894e2951b3c633aab1abc400e8211f5
348
dart
Dart
flutter_app/lib/commonWidget/CustomSrollViewBar.dart
coder-oneone/flutter_study
caeecec26626c8d27ef4f3ab73ad0d3fd24e51ea
[ "Apache-2.0" ]
null
null
null
flutter_app/lib/commonWidget/CustomSrollViewBar.dart
coder-oneone/flutter_study
caeecec26626c8d27ef4f3ab73ad0d3fd24e51ea
[ "Apache-2.0" ]
null
null
null
flutter_app/lib/commonWidget/CustomSrollViewBar.dart
coder-oneone/flutter_study
caeecec26626c8d27ef4f3ab73ad0d3fd24e51ea
[ "Apache-2.0" ]
null
null
null
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class CustomSrollContainer extends StatelessWidget { Widget child; CustomSrollContainer({required this.child}); @override Widget build(BuildContext context) { return CupertinoScrollbar( child: SafeArea( child: child, ), ); } }
20.470588
52
0.704023
a7e63dea6394322215c1f887aad242b4a581003b
756
css
CSS
Session 01/css/styles.css
waylayio/external-dashboarding
0305657ab08892e06b7e4c68467bbe42636615c2
[ "MIT" ]
1
2022-03-04T15:56:44.000Z
2022-03-04T15:56:44.000Z
Session 01/css/styles.css
waylayio/external-dashboarding
0305657ab08892e06b7e4c68467bbe42636615c2
[ "MIT" ]
null
null
null
Session 01/css/styles.css
waylayio/external-dashboarding
0305657ab08892e06b7e4c68467bbe42636615c2
[ "MIT" ]
null
null
null
#cover { position: fixed; height: 100%; width: 100%; top:0; left: 0; background: #FFF; z-index:9999;} .ui-autocomplete { position: absolute; z-index: 1000; top: 0; left: 0; cursor: default; color: white; /* background-color: #fff;*/ padding:3px; /*border: 1px solid #ccc*/ } .ui-autocomplete > li.ui-state-focus { background-color: #FF6C00; } button:hover { background-color : rgba(26, 13, 3, 0.26); } ul { list-style: none; padding: 0; } .popup { position: fixed; display: inline-block; z-index: 999; top: 50%; left: 50%; box-shadow: rgb(38, 57, 77) 0px 10px 10px -5px; } .btn-color{ background-color: #0e1c36; color: #fff; } .page-wrapper { max-width: 900px; margin: auto; }
16.8
101
0.599206
e224d0696c1af16e73129442343ada2d4715b48e
3,395
py
Python
289_Game-of-Life.py
Coalin/Daily-LeetCode-Exercise
a064dcdc3a82314be4571d342c4807291a24f69f
[ "MIT" ]
3
2018-07-05T05:51:10.000Z
2019-05-04T08:35:44.000Z
289_Game-of-Life.py
Coalin/Daily-LeetCode-Exercise
a064dcdc3a82314be4571d342c4807291a24f69f
[ "MIT" ]
null
null
null
289_Game-of-Life.py
Coalin/Daily-LeetCode-Exercise
a064dcdc3a82314be4571d342c4807291a24f69f
[ "MIT" ]
null
null
null
class Solution: def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ if not board: return board last = copy.deepcopy(board) for i in range(len(board)): for j in range(len(board[0])): cur_count = self.findCount(last, i, j) print(cur_count) if board[i][j] == 1: if cur_count < 2 or cur_count > 3: board[i][j] = 0 else: if cur_count == 3: board[i][j] = 1 def findCount(self, board, i, j): count = 0 if len(board) == 1 and len(board[0]) == 1: return 0 if len(board[0]) == 1: try: count += board[i][j-1] except: pass try: count += board[i][j+1] except: pass return count if len(board) == 1: try: count += board[i-1][j] except: pass try: count += board[i+1][j] except: pass return count if i > 0 and i < len(board)-1 and j > 0 and j < len(board[0])-1: count += board[i-1][j] count += board[i-1][j-1] count += board[i-1][j+1] count += board[i][j-1] count += board[i][j+1] count += board[i+1][j-1] count += board[i+1][j] count += board[i+1][j+1] return count if i == 0 and j == 0: count += board[i][j+1] count += board[i+1][j] count += board[i+1][j+1] return count if i == 0 and j == len(board[0])-1: count += board[i][j-1] count += board[i+1][j] count += board[i+1][j-1] return count if i == len(board)-1 and j == 0: count += board[i][j+1] count += board[i-1][j] count += board[i-1][j+1] return count if i == len(board)-1 and j == len(board[0])-1: count += board[i][j-1] count += board[i-1][j] count += board[i-1][j-1] return count if i == 0: count += board[i][j-1] count += board[i][j+1] count += board[i+1][j] count += board[i+1][j-1] count += board[i+1][j+1] return count if i == len(board)-1: count += board[i][j-1] count += board[i][j+1] count += board[i-1][j] count += board[i-1][j-1] count += board[i-1][j+1] return count if j == 0: count += board[i-1][j] count += board[i+1][j] count += board[i-1][j+1] count += board[i][j+1] count += board[i+1][j+1] return count if j == len(board[0])-1: count += board[i-1][j] count += board[i+1][j] count += board[i-1][j-1] count += board[i][j-1] count += board[i+1][j-1] return count
30.585586
75
0.377025
14fce740dbf446748abbc243fa5eb76e9eca9e05
993
ts
TypeScript
src/apollo/apolloServer.ts
sexyGuyKangSungWoo/DDB-back
b1c80bceb64cbd0ddf78cbbce738eea8f3018ac7
[ "MIT" ]
null
null
null
src/apollo/apolloServer.ts
sexyGuyKangSungWoo/DDB-back
b1c80bceb64cbd0ddf78cbbce738eea8f3018ac7
[ "MIT" ]
null
null
null
src/apollo/apolloServer.ts
sexyGuyKangSungWoo/DDB-back
b1c80bceb64cbd0ddf78cbbce738eea8f3018ac7
[ "MIT" ]
null
null
null
import { ApolloServer, ExpressContext } from 'apollo-server-express'; import { AuthChecker, buildSchema } from 'type-graphql'; import { getUser } from '../auth/userToken'; import UserResolver from './resolvers/UserResolver'; export interface ApolloContext { user?: string; } const authChecker: AuthChecker<ApolloContext> = ( { root, args, context: { user }, info }, roles ) => { if(roles.length === 0) { return user !== undefined; } return false; }; function context({ req }: ExpressContext): ApolloContext { const token = req.headers.authorization || ''; try { const user = getUser(token); return { user }; } catch(e) { return {}; } }; export async function getApolloServer() { const apolloServer = new ApolloServer({ schema: await buildSchema({ resolvers: [ UserResolver ], authChecker }), context }); return apolloServer; }
22.568182
69
0.594159
c0f9069446590c96bc9a2341be6acf0adc3a403f
2,593
sh
Shell
source/xdg_base_directory_specification.sh
drew7721/dotfiles
09161529902ed77a00693f55b60a9d107819cbd7
[ "MIT" ]
10
2015-01-11T20:45:58.000Z
2021-08-14T16:07:02.000Z
source/xdg_base_directory_specification.sh
drew7721/dotfiles
09161529902ed77a00693f55b60a9d107819cbd7
[ "MIT" ]
15
2015-09-24T16:49:52.000Z
2021-11-09T15:57:24.000Z
source/xdg_base_directory_specification.sh
drew7721/dotfiles
09161529902ed77a00693f55b60a9d107819cbd7
[ "MIT" ]
12
2015-02-05T14:42:08.000Z
2020-06-30T18:50:38.000Z
# vim: ft=sh ## # xdg_base_directory_specification # # Create XDG environment variables and directories. # # Note that this only implements the XDG Base Directory Specification from: # - https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html # # For additional information about support, and partial support # workarounds read: # - https://wiki.archlinux.org/index.php/XDG_Base_Directory # # The xdg-user-dirs specification is not implemented, because the specified # directories typically already exist on popular operating systems, though # they don't typically create the corresponding $XDG_* environment variables. # Regardless, to learn more about the xdg-user-dirs specification, read: # - https://www.freedesktop.org/wiki/Software/xdg-user-dirs/ # # Note that on some operating systems, namely MacOS, the $TMPDIR environment # variable has a trailing forward slash. This is corrected in an ephemeral # environment variable before its possible use. # # @author Dane MacMillan <work@danemacmillan.com> # @link https://github.com/danemacmillan/dotfiles # @license MIT export XDG_DATA_HOME="${XDG_DATA_HOME:-${HOME}/.local/share}" export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-${HOME}/.config}" export XDG_DATA_DIRS="${XDG_DATA_DIRS:-/usr/local/share/:/usr/share/}" export XDG_CONFIG_DIRS="${XDG_CONFIG_DIRS:-/etc/xdg}" export XDG_CACHE_HOME="${XDG_CACHE_HOME:-${HOME}/.cache}" __tmpdir="${TMPDIR%/}" export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-"${__tmpdir:-/tmp}/uid${UID}"}" unset __tmpdir [[ ! -e "${XDG_DATA_HOME}" ]] && mkdir -p "${XDG_DATA_HOME}" [[ ! -e "${XDG_CONFIG_HOME}" ]] && mkdir -p "${XDG_CONFIG_HOME}" [[ ! -e "${XDG_CACHE_HOME}" ]] && mkdir -p "${XDG_CACHE_HOME}" [[ ! -e "${XDG_RUNTIME_DIR}" ]] && mkdir -p "${XDG_RUNTIME_DIR}" && chmod 700 "${XDG_RUNTIME_DIR}" ## # Unofficial XDG, though should be part of it. # # References: # - https://www.freedesktop.org/software/systemd/man/file-hierarchy.html#Home%20Directory # - https://theos.kyriasis.com/~kyrias/basedir-spec.html export XDG_BIN_HOME="${XDG_BIN_HOME:-${HOME}/.local/bin}" export XDG_LIB_HOME="${XDG_LIB_HOME:-${HOME}/.local/lib}" [[ ! -e "${XDG_BIN_HOME}" ]] && mkdir -p "${XDG_BIN_HOME}" [[ ! -e "${XDG_LIB_HOME}" ]] && mkdir -p "${XDG_LIB_HOME}" ## # Unofficial XDG. # # This a proposal from Debian to include a STATE directory, which would be # useful for storing files such as logs. # # References: # - https://wiki.debian.org/XDGBaseDirectorySpecification export XDG_STATE_HOME="${XDG_STATE_HOME:-${HOME}/.local/state}" [[ ! -e "${XDG_STATE_HOME}" ]] && mkdir -p "${XDG_STATE_HOME}"
40.515625
98
0.726957
8c350911233418ea8106f7fff2a32d2ff6c15117
1,437
lua
Lua
components/Transformable.lua
unek/zombies
b6b31e543137ed392cd6f9f518c2de0ac1946bad
[ "MIT" ]
2
2015-01-27T03:07:18.000Z
2016-10-30T03:01:58.000Z
components/Transformable.lua
unek/zombies
b6b31e543137ed392cd6f9f518c2de0ac1946bad
[ "MIT" ]
null
null
null
components/Transformable.lua
unek/zombies
b6b31e543137ed392cd6f9f518c2de0ac1946bad
[ "MIT" ]
null
null
null
local Transformable = Component:extend("Transformable") function Transformable:initialize(x, y, r, sx, sy) self.pos = {} self.pos.x = x or 0 self.pos.y = y or 0 self.rotation = r or 0 self.scale = {} self.scale.x = sx or 1 self.scale.y = sy or self.scale.x end function Transformable:getPosition() return self.pos.x, self.pos.y end function Transformable:setPosition(x, y) self.pos.x = x self.pos.y = y return self end function Transformable:getRotation() return self.rotation end function Transformable:setRotation(angle) self.rotation = r return self end function Transformable:getScale() return self.scale.x, self.scale.y end function Transformable:setScale(sx, sy) self.scale.x = x self.scale.y = y return self end function Transformable:getDistanceTo(entity) return MathUtils.dist(self.pos.x, self.pos.y, entity.pos.x, entity.pos.y) end function Transformable:move(dx, dy) self.pos.x, self.pos.y = self.pos.x + dx, self.pos.y + dy return self end function Transformable:rotate(delta_angle) self.rotation = (self.rotation + delta_angle) % math.pi * 2 return self end function Transformable:lookAt(x, y) self.rotation = math.atan2(y - self.pos.y, x - self.pos.x) return self end function Transformable:getTransforms() return self.pos.x, self.pos.y, self.rotation, self.scale.x, self.scale.y end
20.239437
77
0.686848
aecfb92480a12482604efd2eb7b7842db1842340
1,682
cs
C#
Library/PackageCache/com.unity.ads@3.4.4/Tests/Runtime/Advertisement/UnityAdsTestListener.cs
aflathmann/unity-game
9707ce34bfea052239e5bb4941fd09e9505b16f0
[ "MIT" ]
1
2021-09-06T14:18:40.000Z
2021-09-06T14:18:40.000Z
Library/PackageCache/com.unity.ads@3.4.5/Tests/Runtime/Advertisement/UnityAdsTestListener.cs
taylorbauer/Scraper
7aa3d5ec4f5d09cf911d96cc7daf127fcf215473
[ "MIT" ]
5
2020-09-26T01:23:05.000Z
2022-02-10T01:58:20.000Z
Library/PackageCache/com.unity.ads@3.4.5/Tests/Runtime/Advertisement/UnityAdsTestListener.cs
taylorbauer/Scraper
7aa3d5ec4f5d09cf911d96cc7daf127fcf215473
[ "MIT" ]
null
null
null
using UnityEngine.Events; namespace UnityEngine.Advertisements.Tests { public class UnityAdsTestListener : IUnityAdsListener { public bool HasBeenCalled; private UnityAction<string> m_UnityAdsReadyCallback; private UnityAction<string> m_UnityAdsDidErrorCallback; private UnityAction<string> m_UnityAdsDidStartCallback; private UnityAction<string, ShowResult> m_UnityAdsDidFinishCallback; public UnityAdsTestListener(UnityAction<string> readyCallback, UnityAction<string> errorCallback, UnityAction<string> startCallback, UnityAction<string, ShowResult> finishCallback) { HasBeenCalled = false; m_UnityAdsReadyCallback = readyCallback; m_UnityAdsDidErrorCallback = errorCallback; m_UnityAdsDidStartCallback = startCallback; m_UnityAdsDidFinishCallback = finishCallback; } public void OnUnityAdsReady(string placementId) { HasBeenCalled = true; m_UnityAdsReadyCallback?.Invoke(placementId); } public void OnUnityAdsDidError(string message) { HasBeenCalled = true; m_UnityAdsDidErrorCallback?.Invoke(message); } public void OnUnityAdsDidStart(string placementId) { HasBeenCalled = true; m_UnityAdsDidStartCallback?.Invoke(placementId); } public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) { HasBeenCalled = true; m_UnityAdsDidFinishCallback?.Invoke(placementId, showResult); } } }
35.787234
189
0.65874
af04d4d6a71f4ac8c1417e39e76d2505a9711e43
1,046
py
Python
redsocks/websocket.py
pkkid/django-redsocks
615805c6b99aeedd59a2a66ea3bd25f7b606b968
[ "MIT" ]
null
null
null
redsocks/websocket.py
pkkid/django-redsocks
615805c6b99aeedd59a2a66ea3bd25f7b606b968
[ "MIT" ]
null
null
null
redsocks/websocket.py
pkkid/django-redsocks
615805c6b99aeedd59a2a66ea3bd25f7b606b968
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from redsocks.exceptions import WebSocketError from redsocks.utils import uwsgi class uWSGIWebsocket(object): def __init__(self): self.closed = False def get_file_descriptor(self): try: return uwsgi.connection_fd() except IOError as err: self.close(err=err) def receive(self): try: if self.closed: raise WebSocketError('Connection is already closed') return uwsgi.websocket_recv_nb() except IOError as err: self.close(err=err) def flush(self): try: uwsgi.websocket_recv_nb() except IOError as err: self.close(err=err) def send(self, message, binary=None): try: uwsgi.websocket_send(message) except IOError as err: self.close(err=err) def close(self, *args, **kwargs): self.closed = True if kwargs.get('err'): raise WebSocketError(kwargs.get('err', 'NA'))
26.15
68
0.571702
cea085fe95d702ac28a4875732f3304673f91eeb
54,433
rs
Rust
gtk/src/subclass/widget.rs
BrainBlasted/gtk-rs
6868cbb9fa8fc07eeefd22ac0e65ba795594138e
[ "MIT-0", "MIT" ]
null
null
null
gtk/src/subclass/widget.rs
BrainBlasted/gtk-rs
6868cbb9fa8fc07eeefd22ac0e65ba795594138e
[ "MIT-0", "MIT" ]
null
null
null
gtk/src/subclass/widget.rs
BrainBlasted/gtk-rs
6868cbb9fa8fc07eeefd22ac0e65ba795594138e
[ "MIT-0", "MIT" ]
null
null
null
use libc::c_int; use std::mem; use glib::translate::*; use glib::subclass::prelude::*; use glib::{Cast, Object}; use crate::Allocation; use crate::DragResult; use crate::Inhibit; use crate::Orientation; use crate::SelectionData; use crate::SizeRequestMode; use crate::TextDirection; use crate::Widget; use crate::WidgetExt; pub trait WidgetImpl: WidgetImplExt + ObjectImpl { fn adjust_baseline_allocation(&self, widget: &Self::Type, baseline: &mut i32) { self.parent_adjust_baseline_allocation(widget, baseline) } fn adjust_baseline_request( &self, widget: &Self::Type, minimum_baseline: &mut i32, natural_baseline: &mut i32, ) { self.parent_adjust_baseline_request(widget, minimum_baseline, natural_baseline) } fn adjust_size_allocation( &self, widget: &Self::Type, orientation: Orientation, minimum_size: &mut i32, natural_size: &mut i32, allocated_pos: &mut i32, allocated_size: &mut i32, ) { self.parent_adjust_size_allocation( widget, orientation, minimum_size, natural_size, allocated_pos, allocated_size, ) } fn adjust_size_request( &self, widget: &Self::Type, orientation: Orientation, minimum_size: &mut i32, natural_size: &mut i32, ) { self.parent_adjust_size_request(widget, orientation, minimum_size, natural_size) } fn button_press_event(&self, widget: &Self::Type, event: &gdk::EventButton) -> Inhibit { self.parent_button_press_event(widget, event) } fn button_release_event(&self, widget: &Self::Type, event: &gdk::EventButton) -> Inhibit { self.parent_button_release_event(widget, event) } fn child_notify(&self, widget: &Self::Type, child_property: &glib::ParamSpec) { self.parent_child_notify(widget, child_property) } fn composited_changed(&self, widget: &Self::Type) { self.parent_composited_changed(widget) } fn compute_expand(&self, widget: &Self::Type, hexpand: &mut bool, vexpand: &mut bool) { self.parent_compute_expand(widget, hexpand, vexpand) } fn configure_event(&self, widget: &Self::Type, event: &gdk::EventConfigure) -> Inhibit { self.parent_configure_event(widget, event) } fn damage_event(&self, widget: &Self::Type, event: &gdk::EventExpose) -> Inhibit { self.parent_damage_event(widget, event) } fn delete_event(&self, widget: &Self::Type, event: &gdk::Event) -> Inhibit { self.parent_delete_event(widget, event) } fn destroy(&self, widget: &Self::Type) { self.parent_destroy(widget) } fn destroy_event(&self, widget: &Self::Type, event: &gdk::Event) -> Inhibit { self.parent_destroy_event(widget, event) } fn direction_changed(&self, widget: &Self::Type, previous_direction: TextDirection) { self.parent_direction_changed(widget, previous_direction) } fn dispatch_child_properties_changed(&self, widget: &Self::Type, pspecs: &[glib::ParamSpec]) { self.parent_dispatch_child_properties_changed(widget, pspecs) } fn drag_begin(&self, widget: &Self::Type, context: &gdk::DragContext) { self.parent_drag_begin(widget, context) } fn drag_data_delete(&self, widget: &Self::Type, context: &gdk::DragContext) { self.parent_drag_data_delete(widget, context) } fn drag_data_get( &self, widget: &Self::Type, context: &gdk::DragContext, selection_data: &SelectionData, info: u32, time: u32, ) { self.parent_drag_data_get(widget, context, selection_data, info, time) } fn drag_data_received( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, selection_data: &SelectionData, info: u32, time: u32, ) { self.parent_drag_data_received(widget, context, x, y, selection_data, info, time) } fn drag_drop( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, time: u32, ) -> Inhibit { self.parent_drag_drop(widget, context, x, y, time) } fn drag_end(&self, widget: &Self::Type, context: &gdk::DragContext) { self.parent_drag_end(widget, context) } fn drag_failed( &self, widget: &Self::Type, context: &gdk::DragContext, result: DragResult, ) -> Inhibit { self.parent_drag_failed(widget, context, result) } fn drag_leave(&self, widget: &Self::Type, context: &gdk::DragContext, time: u32) { self.parent_drag_leave(widget, context, time) } fn drag_motion( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, time: u32, ) -> Inhibit { self.parent_drag_motion(widget, context, x, y, time) } fn draw(&self, widget: &Self::Type, cr: &cairo::Context) -> Inhibit { self.parent_draw(widget, cr) } // fn can_activate_accel(&self, widget: &Self::Type, signal_id: u32) -> bool { // self.parent_can_activate_accel(widget, signal_id) // } fn get_request_mode(&self, widget: &Self::Type) -> SizeRequestMode { self.parent_get_request_mode(widget) } fn get_preferred_width(&self, widget: &Self::Type) -> (i32, i32) { self.parent_get_preferred_width(widget) } fn get_preferred_width_for_height(&self, widget: &Self::Type, height: i32) -> (i32, i32) { self.parent_get_preferred_width_for_height(widget, height) } fn get_preferred_height(&self, widget: &Self::Type) -> (i32, i32) { self.parent_get_preferred_height(widget) } fn get_preferred_height_for_width(&self, widget: &Self::Type, width: i32) -> (i32, i32) { self.parent_get_preferred_height_for_width(widget, width) } fn size_allocate(&self, widget: &Self::Type, allocation: &Allocation) { self.parent_size_allocate(widget, allocation) } fn realize(&self, widget: &Self::Type) { self.parent_realize(widget); } fn unrealize(&self, widget: &Self::Type) { self.parent_unrealize(widget); } fn map(&self, widget: &Self::Type) { self.parent_map(widget); } fn unmap(&self, widget: &Self::Type) { self.parent_unmap(widget); } fn motion_notify_event(&self, widget: &Self::Type, event: &gdk::EventMotion) -> Inhibit { self.parent_motion_notify_event(widget, event) } fn scroll_event(&self, widget: &Self::Type, event: &gdk::EventScroll) -> Inhibit { self.parent_scroll_event(widget, event) } } pub trait WidgetImplExt: ObjectSubclass { fn parent_adjust_baseline_allocation(&self, widget: &Self::Type, baseline: &mut i32); fn parent_adjust_baseline_request( &self, widget: &Self::Type, minimum_baseline: &mut i32, natural_baseline: &mut i32, ); fn parent_adjust_size_allocation( &self, widget: &Self::Type, orientation: Orientation, minimum_size: &mut i32, natural_size: &mut i32, allocated_pos: &mut i32, allocated_size: &mut i32, ); fn parent_adjust_size_request( &self, widget: &Self::Type, orientation: Orientation, minimum_size: &mut i32, natural_size: &mut i32, ); fn parent_button_press_event(&self, widget: &Self::Type, event: &gdk::EventButton) -> Inhibit; fn parent_button_release_event(&self, widget: &Self::Type, event: &gdk::EventButton) -> Inhibit; // fn parent_can_activate_accel(&self, widget: &Self::Type, signal_id: u32) -> bool; fn parent_child_notify(&self, widget: &Self::Type, child_property: &glib::ParamSpec); fn parent_composited_changed(&self, widget: &Self::Type); fn parent_compute_expand(&self, widget: &Self::Type, hexpand: &mut bool, vexpand: &mut bool); fn parent_configure_event(&self, widget: &Self::Type, event: &gdk::EventConfigure) -> Inhibit; fn parent_damage_event(&self, widget: &Self::Type, event: &gdk::EventExpose) -> Inhibit; fn parent_delete_event(&self, widget: &Self::Type, event: &gdk::Event) -> Inhibit; fn parent_destroy(&self, widget: &Self::Type); fn parent_destroy_event(&self, widget: &Self::Type, event: &gdk::Event) -> Inhibit; fn parent_direction_changed(&self, widget: &Self::Type, previous_direction: TextDirection); fn parent_dispatch_child_properties_changed( &self, widget: &Self::Type, pspecs: &[glib::ParamSpec], ); fn parent_drag_begin(&self, widget: &Self::Type, context: &gdk::DragContext); fn parent_drag_data_delete(&self, widget: &Self::Type, context: &gdk::DragContext); fn parent_drag_data_get( &self, widget: &Self::Type, context: &gdk::DragContext, selection_data: &SelectionData, info: u32, time: u32, ); fn parent_drag_data_received( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, selection_data: &SelectionData, info: u32, time: u32, ); fn parent_drag_drop( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, time: u32, ) -> Inhibit; fn parent_drag_end(&self, widget: &Self::Type, context: &gdk::DragContext); fn parent_drag_failed( &self, widget: &Self::Type, context: &gdk::DragContext, result: DragResult, ) -> Inhibit; fn parent_drag_leave(&self, widget: &Self::Type, context: &gdk::DragContext, time: u32); fn parent_drag_motion( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, time: u32, ) -> Inhibit; fn parent_draw(&self, widget: &Self::Type, cr: &cairo::Context) -> Inhibit; fn parent_get_request_mode(&self, widget: &Self::Type) -> SizeRequestMode; fn parent_get_preferred_width(&self, widget: &Self::Type) -> (i32, i32); fn parent_get_preferred_width_for_height(&self, widget: &Self::Type, height: i32) -> (i32, i32); fn parent_get_preferred_height(&self, widget: &Self::Type) -> (i32, i32); fn parent_get_preferred_height_for_width(&self, widget: &Self::Type, width: i32) -> (i32, i32); fn parent_size_allocate(&self, widget: &Self::Type, allocation: &Allocation); fn parent_realize(&self, widget: &Self::Type); fn parent_unrealize(&self, widget: &Self::Type); fn parent_map(&self, widget: &Self::Type); fn parent_unmap(&self, widget: &Self::Type); fn parent_motion_notify_event(&self, widget: &Self::Type, event: &gdk::EventMotion) -> Inhibit; fn parent_scroll_event(&self, widget: &Self::Type, event: &gdk::EventScroll) -> Inhibit; } impl<T: WidgetImpl> WidgetImplExt for T { fn parent_adjust_baseline_allocation(&self, widget: &Self::Type, baseline: &mut i32) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class) .adjust_baseline_allocation .expect("No parent class impl for \"adjust_baseline_allocation\""); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, baseline, ) } } fn parent_adjust_baseline_request( &self, widget: &Self::Type, minimum_baseline: &mut i32, natural_baseline: &mut i32, ) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class) .adjust_baseline_request .expect("No parent class impl for \"adjust_baseline_request\""); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, minimum_baseline, natural_baseline, ) } } fn parent_adjust_size_allocation( &self, widget: &Self::Type, orientation: Orientation, minimum_size: &mut i32, natural_size: &mut i32, allocated_pos: &mut i32, allocated_size: &mut i32, ) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class) .adjust_size_allocation .expect("No parent class impl for \"adjust_size_allocation\""); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, orientation.to_glib(), minimum_size, natural_size, allocated_pos, allocated_size, ) } } fn parent_adjust_size_request( &self, widget: &Self::Type, orientation: Orientation, minimum_size: &mut i32, natural_size: &mut i32, ) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class) .adjust_size_request .expect("No parent class impl for \"adjust_size_request\""); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, orientation.to_glib(), minimum_size as *mut i32, natural_size as *mut i32, ) } } fn parent_button_press_event(&self, widget: &Self::Type, event: &gdk::EventButton) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).button_press_event { let ev_glib = glib::translate::mut_override(event.to_glib_none().0); Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, ev_glib, ))) } else { Inhibit(false) } } } fn parent_button_release_event( &self, widget: &Self::Type, event: &gdk::EventButton, ) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).button_release_event { let ev_glib = glib::translate::mut_override(event.to_glib_none().0); Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, ev_glib, ))) } else { Inhibit(false) } } } // fn parent_can_activate_accel(&self, widget: &Self::Type, signal_id: u32) -> bool { // unsafe { // let data = T::type_data(); // let parent_class = // data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; // let f = (*parent_class) // .can_activate_accel // .expect("No parent class impl for \"can_activate_accel\""); // f(widget.unsafe_cast_ref::<Widget>().to_glib_none().0, signal_id) != 0 // } // } fn parent_child_notify(&self, widget: &Self::Type, child_property: &glib::ParamSpec) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).child_notify { let pspec_glib = glib::translate::mut_override(child_property.to_glib_none().0); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, pspec_glib, ) } } } fn parent_composited_changed(&self, widget: &Self::Type) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).composited_changed { f(widget.unsafe_cast_ref::<Widget>().to_glib_none().0) } } } fn parent_compute_expand(&self, widget: &Self::Type, hexpand: &mut bool, vexpand: &mut bool) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let widget = widget.unsafe_cast_ref::<Widget>(); if let Some(f) = (*parent_class).compute_expand { let mut hexpand_glib = hexpand.to_glib(); let mut vexpand_glib = vexpand.to_glib(); f( widget.to_glib_none().0, &mut hexpand_glib, &mut vexpand_glib, ); *hexpand = from_glib(hexpand_glib); *vexpand = from_glib(vexpand_glib); } } } fn parent_configure_event(&self, widget: &Self::Type, event: &gdk::EventConfigure) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).configure_event { let ev_glib = glib::translate::mut_override(event.to_glib_none().0); Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, ev_glib, ))) } else { Inhibit(false) } } } fn parent_damage_event(&self, widget: &Self::Type, event: &gdk::EventExpose) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).damage_event { let ev_glib = glib::translate::mut_override(event.to_glib_none().0); Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, ev_glib, ))) } else { Inhibit(false) } } } fn parent_delete_event(&self, widget: &Self::Type, event: &gdk::Event) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).delete_event { let ev_glib = glib::translate::mut_override(event.to_glib_none().0); Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, ev_glib, ))) } else { Inhibit(false) } } } fn parent_destroy(&self, widget: &Self::Type) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).destroy { f(widget.unsafe_cast_ref::<Widget>().to_glib_none().0) } } } fn parent_destroy_event(&self, widget: &Self::Type, event: &gdk::Event) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).destroy_event { let ev_glib = glib::translate::mut_override(event.to_glib_none().0); Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, ev_glib, ))) } else { Inhibit(false) } } } fn parent_direction_changed(&self, widget: &Self::Type, previous_direction: TextDirection) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).direction_changed { f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, previous_direction.to_glib(), ) } } } fn parent_dispatch_child_properties_changed( &self, widget: &Self::Type, pspecs: &[glib::ParamSpec], ) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).dispatch_child_properties_changed { let mut pspecs_array = pspecs .iter() .map(|p| p.to_glib_none().0) .collect::<Vec<_>>(); let pspecs_ptr = pspecs_array.as_mut_ptr(); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, pspecs.len() as u32, pspecs_ptr, ) } } } fn parent_drag_begin(&self, widget: &Self::Type, context: &gdk::DragContext) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_begin { f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, ) } } } fn parent_drag_data_delete(&self, widget: &Self::Type, context: &gdk::DragContext) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_data_delete { f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, ) } } } fn parent_drag_data_get( &self, widget: &Self::Type, context: &gdk::DragContext, selection_data: &SelectionData, info: u32, time: u32, ) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_data_get { let selection_mut = glib::translate::mut_override(selection_data.to_glib_none().0); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, selection_mut, info, time, ) } } } fn parent_drag_data_received( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, selection_data: &SelectionData, info: u32, time: u32, ) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_data_received { let selection_mut = glib::translate::mut_override(selection_data.to_glib_none().0); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, x, y, selection_mut, info, time, ) } } } fn parent_drag_drop( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, time: u32, ) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_drop { Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, x, y, time, ))) } else { Inhibit(false) } } } fn parent_drag_end(&self, widget: &Self::Type, context: &gdk::DragContext) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_end { f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, ) } } } fn parent_drag_failed( &self, widget: &Self::Type, context: &gdk::DragContext, result: DragResult, ) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_failed { Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, result.to_glib(), ))) } else { Inhibit(false) } } } fn parent_drag_leave(&self, widget: &Self::Type, context: &gdk::DragContext, time: u32) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_leave { f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, time, ) } } } fn parent_drag_motion( &self, widget: &Self::Type, context: &gdk::DragContext, x: i32, y: i32, time: u32, ) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).drag_motion { Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, context.to_glib_none().0, x, y, time, ))) } else { Inhibit(false) } } } fn parent_draw(&self, widget: &Self::Type, cr: &cairo::Context) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).draw { Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, cr.to_glib_none().0, ))) } else { Inhibit(false) } } } fn parent_get_request_mode(&self, widget: &Self::Type) -> SizeRequestMode { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class).get_request_mode.unwrap(); from_glib(f(widget.unsafe_cast_ref::<Widget>().to_glib_none().0)) } } fn parent_get_preferred_width(&self, widget: &Self::Type) -> (i32, i32) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class).get_preferred_width.unwrap(); let mut minimum_size = mem::MaybeUninit::uninit(); let mut natural_size = mem::MaybeUninit::uninit(); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, minimum_size.as_mut_ptr(), natural_size.as_mut_ptr(), ); (minimum_size.assume_init(), natural_size.assume_init()) } } fn parent_get_preferred_width_for_height( &self, widget: &Self::Type, height: i32, ) -> (i32, i32) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class).get_preferred_width_for_height.unwrap(); let mut minimum_size = mem::MaybeUninit::uninit(); let mut natural_size = mem::MaybeUninit::uninit(); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, height, minimum_size.as_mut_ptr(), natural_size.as_mut_ptr(), ); (minimum_size.assume_init(), natural_size.assume_init()) } } fn parent_get_preferred_height(&self, widget: &Self::Type) -> (i32, i32) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class).get_preferred_height.unwrap(); let mut minimum_size = mem::MaybeUninit::uninit(); let mut natural_size = mem::MaybeUninit::uninit(); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, minimum_size.as_mut_ptr(), natural_size.as_mut_ptr(), ); (minimum_size.assume_init(), natural_size.assume_init()) } } fn parent_get_preferred_height_for_width(&self, widget: &Self::Type, width: i32) -> (i32, i32) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class).get_preferred_height_for_width.unwrap(); let mut minimum_size = mem::MaybeUninit::uninit(); let mut natural_size = mem::MaybeUninit::uninit(); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, width, minimum_size.as_mut_ptr(), natural_size.as_mut_ptr(), ); (minimum_size.assume_init(), natural_size.assume_init()) } } fn parent_size_allocate(&self, widget: &Self::Type, allocation: &Allocation) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; let f = (*parent_class) .size_allocate .expect("No parent class impl for \"size_allocate\""); f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, mut_override(allocation.to_glib_none().0), ); } } fn parent_realize(&self, widget: &Self::Type) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).realize { f(widget.unsafe_cast_ref::<Widget>().to_glib_none().0); } } } fn parent_unrealize(&self, widget: &Self::Type) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).unrealize { f(widget.unsafe_cast_ref::<Widget>().to_glib_none().0); } } } fn parent_map(&self, widget: &Self::Type) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).map { f(widget.unsafe_cast_ref::<Widget>().to_glib_none().0); } } } fn parent_unmap(&self, widget: &Self::Type) { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).unmap { f(widget.unsafe_cast_ref::<Widget>().to_glib_none().0); } } } fn parent_motion_notify_event(&self, widget: &Self::Type, event: &gdk::EventMotion) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).motion_notify_event { Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, mut_override(event.to_glib_none().0), ))) } else { Inhibit(false) } } } fn parent_scroll_event(&self, widget: &Self::Type, event: &gdk::EventScroll) -> Inhibit { unsafe { let data = T::type_data(); let parent_class = data.as_ref().get_parent_class() as *mut ffi::GtkWidgetClass; if let Some(f) = (*parent_class).scroll_event { Inhibit(from_glib(f( widget.unsafe_cast_ref::<Widget>().to_glib_none().0, mut_override(event.to_glib_none().0), ))) } else { Inhibit(false) } } } } unsafe impl<T: WidgetImpl> IsSubclassable<T> for Widget { fn override_vfuncs(class: &mut ::glib::Class<Self>) { <Object as IsSubclassable<T>>::override_vfuncs(class); let klass = class.as_mut(); klass.adjust_baseline_allocation = Some(widget_adjust_baseline_allocation::<T>); klass.adjust_baseline_request = Some(widget_adjust_baseline_request::<T>); klass.adjust_size_allocation = Some(widget_adjust_size_allocation::<T>); klass.adjust_size_request = Some(widget_adjust_size_request::<T>); klass.button_press_event = Some(widget_button_press_event::<T>); klass.button_release_event = Some(widget_button_release_event::<T>); // klass.can_activate_accel = Some(widget_can_activate_accel::<T>); klass.child_notify = Some(widget_child_notify::<T>); klass.composited_changed = Some(widget_composited_changed::<T>); klass.compute_expand = Some(widget_compute_expand::<T>); klass.configure_event = Some(widget_configure_event::<T>); klass.damage_event = Some(widget_damage_event::<T>); klass.delete_event = Some(widget_delete_event::<T>); klass.destroy = Some(widget_destroy::<T>); klass.destroy_event = Some(widget_destroy_event::<T>); klass.direction_changed = Some(widget_direction_changed::<T>); klass.dispatch_child_properties_changed = Some(widget_dispatch_child_properties_changed::<T>); klass.drag_begin = Some(widget_drag_begin::<T>); klass.drag_data_delete = Some(widget_drag_data_delete::<T>); klass.drag_data_get = Some(widget_drag_data_get::<T>); klass.drag_data_received = Some(widget_drag_data_received::<T>); klass.drag_drop = Some(widget_drag_drop::<T>); klass.drag_end = Some(widget_drag_end::<T>); klass.drag_failed = Some(widget_drag_failed::<T>); klass.drag_leave = Some(widget_drag_leave::<T>); klass.drag_motion = Some(widget_drag_motion::<T>); klass.draw = Some(widget_draw::<T>); klass.get_request_mode = Some(widget_get_request_mode::<T>); klass.get_preferred_width = Some(widget_get_preferred_width::<T>); klass.get_preferred_height_for_width = Some(widget_get_preferred_height_for_width::<T>); klass.get_preferred_height = Some(widget_get_preferred_height::<T>); klass.get_preferred_width_for_height = Some(widget_get_preferred_width_for_height::<T>); klass.size_allocate = Some(widget_size_allocate::<T>); klass.realize = Some(widget_realize::<T>); klass.unrealize = Some(widget_unrealize::<T>); klass.map = Some(widget_map::<T>); klass.unmap = Some(widget_unmap::<T>); klass.motion_notify_event = Some(widget_motion_notify_event::<T>); klass.scroll_event = Some(widget_scroll_event::<T>); } } unsafe extern "C" fn widget_adjust_baseline_allocation<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, baseptr: *mut i32, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.adjust_baseline_allocation(wrap.unsafe_cast_ref(), &mut *baseptr) } unsafe extern "C" fn widget_adjust_baseline_request<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, minptr: *mut i32, natptr: *mut i32, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.adjust_baseline_request(wrap.unsafe_cast_ref(), &mut *minptr, &mut *natptr) } unsafe extern "C" fn widget_adjust_size_allocation<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, orientation: ffi::GtkOrientation, minptr: *mut i32, natptr: *mut i32, posptr: *mut i32, sizeptr: *mut i32, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let wrap_orientation: Orientation = from_glib(orientation); imp.adjust_size_allocation( wrap.unsafe_cast_ref(), wrap_orientation, &mut *minptr, &mut *natptr, &mut *posptr, &mut *sizeptr, ) } unsafe extern "C" fn widget_adjust_size_request<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, orientation: ffi::GtkOrientation, minptr: *mut i32, natptr: *mut i32, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let wrap_orientation: Orientation = from_glib(orientation); imp.adjust_size_request( wrap.unsafe_cast_ref(), wrap_orientation, &mut *minptr, &mut *natptr, ) } unsafe extern "C" fn widget_button_press_event<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, btnptr: *mut gdk::ffi::GdkEventButton, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let evwrap: Borrowed<gdk::EventButton> = from_glib_borrow(btnptr); imp.button_press_event(wrap.unsafe_cast_ref(), &evwrap) .to_glib() } unsafe extern "C" fn widget_button_release_event<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, btnptr: *mut gdk::ffi::GdkEventButton, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let evwrap: Borrowed<gdk::EventButton> = from_glib_borrow(btnptr); imp.button_release_event(wrap.unsafe_cast_ref(), &evwrap) .to_glib() } // unsafe extern "C" fn widget_can_activate_accel<T: WidgetImpl>( // ptr: *mut ffi::GtkWidget, // signal_id: u32, // ) -> glib::ffi::gboolean // { // let instance = &*(ptr as *mut T::Instance); // let imp = instance.get_impl(); // let wrap: Widget = from_glib_borrow(ptr); // imp.can_activate_accel(wrap.unsafe_cast_ref(), signal_id) as glib::ffi::gboolean // } unsafe extern "C" fn widget_child_notify<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, paramptr: *mut glib::gobject_ffi::GParamSpec, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let paramwrap: Borrowed<glib::ParamSpec> = from_glib_borrow(paramptr); imp.child_notify(wrap.unsafe_cast_ref(), &paramwrap) } unsafe extern "C" fn widget_composited_changed<T: WidgetImpl>(ptr: *mut ffi::GtkWidget) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.composited_changed(wrap.unsafe_cast_ref()) } unsafe extern "C" fn widget_compute_expand<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, hexpand_ptr: *mut glib::ffi::gboolean, vexpand_ptr: *mut glib::ffi::gboolean, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let widget = wrap.unsafe_cast_ref::<Widget>(); let mut hexpand: bool = if widget.get_hexpand_set() { widget.get_hexpand() } else { from_glib(*hexpand_ptr) }; let mut vexpand: bool = if widget.get_vexpand_set() { widget.get_vexpand() } else { from_glib(*vexpand_ptr) }; imp.compute_expand(wrap.unsafe_cast_ref(), &mut hexpand, &mut vexpand); *hexpand_ptr = hexpand.to_glib(); *vexpand_ptr = vexpand.to_glib(); } unsafe extern "C" fn widget_configure_event<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, confptr: *mut gdk::ffi::GdkEventConfigure, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let evwrap: Borrowed<gdk::EventConfigure> = from_glib_borrow(confptr); imp.configure_event(wrap.unsafe_cast_ref(), &evwrap) .to_glib() } unsafe extern "C" fn widget_damage_event<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, exposeptr: *mut gdk::ffi::GdkEventExpose, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let evwrap: Borrowed<gdk::EventExpose> = from_glib_borrow(exposeptr); imp.damage_event(wrap.unsafe_cast_ref(), &evwrap).to_glib() } unsafe extern "C" fn widget_delete_event<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, anyptr: *mut gdk::ffi::GdkEventAny, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let evwrap: Borrowed<gdk::Event> = from_glib_borrow(anyptr); imp.delete_event(wrap.unsafe_cast_ref(), &evwrap).to_glib() } unsafe extern "C" fn widget_destroy<T: WidgetImpl>(ptr: *mut ffi::GtkWidget) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.destroy(wrap.unsafe_cast_ref()) } unsafe extern "C" fn widget_destroy_event<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, anyptr: *mut gdk::ffi::GdkEventAny, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let evwrap: Borrowed<gdk::Event> = from_glib_borrow(anyptr); imp.destroy_event(wrap.unsafe_cast_ref(), &evwrap).to_glib() } unsafe extern "C" fn widget_direction_changed<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, directnptr: ffi::GtkTextDirection, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let dirwrap: TextDirection = from_glib(directnptr); imp.direction_changed(wrap.unsafe_cast_ref(), dirwrap) } unsafe extern "C" fn widget_dispatch_child_properties_changed<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, n_pspec_ptr: u32, pspecsptr: *mut *mut glib::gobject_ffi::GParamSpec, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let pspecs: Vec<glib::ParamSpec> = FromGlibContainer::from_glib_none_num(pspecsptr, n_pspec_ptr as usize); imp.dispatch_child_properties_changed(wrap.unsafe_cast_ref(), &pspecs) } unsafe extern "C" fn widget_drag_begin<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); imp.drag_begin(wrap.unsafe_cast_ref(), &context) } unsafe extern "C" fn widget_drag_data_delete<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); imp.drag_data_delete(wrap.unsafe_cast_ref(), &context) } unsafe extern "C" fn widget_drag_data_get<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, selectptr: *mut ffi::GtkSelectionData, info: u32, time: u32, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); let selection_data: Borrowed<SelectionData> = from_glib_borrow(selectptr); imp.drag_data_get( wrap.unsafe_cast_ref(), &context, &selection_data, info, time, ) } unsafe extern "C" fn widget_drag_data_received<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, x: i32, y: i32, selectptr: *mut ffi::GtkSelectionData, info: u32, time: u32, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); let selection_data: Borrowed<SelectionData> = from_glib_borrow(selectptr); imp.drag_data_received( wrap.unsafe_cast_ref(), &context, x, y, &selection_data, info, time, ) } unsafe extern "C" fn widget_drag_drop<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, x: i32, y: i32, time: u32, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); imp.drag_drop(wrap.unsafe_cast_ref(), &context, x, y, time) .to_glib() } unsafe extern "C" fn widget_drag_end<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); imp.drag_end(wrap.unsafe_cast_ref(), &context) } unsafe extern "C" fn widget_drag_failed<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, resultptr: ffi::GtkDragResult, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); let result: DragResult = from_glib(resultptr); imp.drag_failed(wrap.unsafe_cast_ref(), &context, result) .to_glib() } unsafe extern "C" fn widget_drag_leave<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, time: u32, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); imp.drag_leave(wrap.unsafe_cast_ref(), &context, time) } unsafe extern "C" fn widget_drag_motion<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ctxptr: *mut gdk::ffi::GdkDragContext, x: i32, y: i32, time: u32, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let context: Borrowed<gdk::DragContext> = from_glib_borrow(ctxptr); imp.drag_motion(wrap.unsafe_cast_ref(), &context, x, y, time) .to_glib() } unsafe extern "C" fn widget_draw<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, cr_ptr: *mut cairo::ffi::cairo_t, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let cr: Borrowed<cairo::Context> = from_glib_borrow(cr_ptr); imp.draw(wrap.unsafe_cast_ref(), &cr).to_glib() } unsafe extern "C" fn widget_get_request_mode<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, ) -> ffi::GtkSizeRequestMode { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.get_request_mode(wrap.unsafe_cast_ref()).to_glib() } unsafe extern "C" fn widget_get_preferred_height<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, minptr: *mut c_int, natptr: *mut c_int, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let (min_size, nat_size) = imp.get_preferred_height(wrap.unsafe_cast_ref()); if !minptr.is_null() { *minptr = min_size; } if !natptr.is_null() { *natptr = nat_size; } } unsafe extern "C" fn widget_get_preferred_width_for_height<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, height: c_int, min_width_ptr: *mut c_int, nat_width_ptr: *mut c_int, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let (min_width, nat_width) = imp.get_preferred_width_for_height(wrap.unsafe_cast_ref(), height); if !min_width_ptr.is_null() { *min_width_ptr = min_width; } if !nat_width_ptr.is_null() { *nat_width_ptr = nat_width; } } unsafe extern "C" fn widget_get_preferred_width<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, minptr: *mut c_int, natptr: *mut c_int, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let (min_size, nat_size) = imp.get_preferred_width(wrap.unsafe_cast_ref()); if !minptr.is_null() { *minptr = min_size; } if !natptr.is_null() { *natptr = nat_size; } } unsafe extern "C" fn widget_get_preferred_height_for_width<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, width: c_int, min_height_ptr: *mut c_int, nat_height_ptr: *mut c_int, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let (min_height, nat_height) = imp.get_preferred_height_for_width(wrap.unsafe_cast_ref(), width); if !min_height_ptr.is_null() { *min_height_ptr = min_height; } if !nat_height_ptr.is_null() { *nat_height_ptr = nat_height; } } unsafe extern "C" fn widget_size_allocate<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, allocation: *mut ffi::GtkAllocation, ) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let allocate: &Allocation = &from_glib_none(allocation); imp.size_allocate(wrap.unsafe_cast_ref(), allocate); } unsafe extern "C" fn widget_realize<T: WidgetImpl>(ptr: *mut ffi::GtkWidget) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.realize(wrap.unsafe_cast_ref()); } unsafe extern "C" fn widget_unrealize<T: WidgetImpl>(ptr: *mut ffi::GtkWidget) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.unrealize(wrap.unsafe_cast_ref()); } unsafe extern "C" fn widget_map<T: WidgetImpl>(ptr: *mut ffi::GtkWidget) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.map(wrap.unsafe_cast_ref()); } unsafe extern "C" fn widget_unmap<T: WidgetImpl>(ptr: *mut ffi::GtkWidget) { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); imp.unmap(wrap.unsafe_cast_ref()); } unsafe extern "C" fn widget_motion_notify_event<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, mptr: *mut gdk::ffi::GdkEventMotion, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let event: Borrowed<gdk::EventMotion> = from_glib_borrow(mptr); imp.motion_notify_event(wrap.unsafe_cast_ref(), &event) .to_glib() } unsafe extern "C" fn widget_scroll_event<T: WidgetImpl>( ptr: *mut ffi::GtkWidget, mptr: *mut gdk::ffi::GdkEventScroll, ) -> glib::ffi::gboolean { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borrowed<Widget> = from_glib_borrow(ptr); let event: Borrowed<gdk::EventScroll> = from_glib_borrow(mptr); imp.scroll_event(wrap.unsafe_cast_ref(), &event).to_glib() }
34.803708
100
0.592233
25820a4626f7213280a8548e04a807c149e838f2
2,811
cs
C#
ReportService/Operations/DataImporters/PackageConsumerBase.cs
MakArs/ReportServer
0c287ed48e495880e182011c80e4d71e78eb2adb
[ "MIT" ]
2
2019-01-18T11:47:47.000Z
2020-01-22T14:37:43.000Z
ReportService/Operations/DataImporters/PackageConsumerBase.cs
MakArs/ReportServer
0c287ed48e495880e182011c80e4d71e78eb2adb
[ "MIT" ]
2
2020-10-28T14:06:29.000Z
2021-05-27T17:06:50.000Z
ReportService/Operations/DataImporters/PackageConsumerBase.cs
MakArs/ReportServer
0c287ed48e495880e182011c80e4d71e78eb2adb
[ "MIT" ]
9
2018-03-23T13:03:02.000Z
2021-09-28T06:27:27.000Z
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using AutoMapper; using ReportService.Entities; using ReportService.Interfaces.Protobuf; using ReportService.Interfaces.ReportTask; using ReportService.Operations.DataImporters.Configurations; using ReportService.Operations.DataImporters.Helpers; namespace ReportService.Operations.DataImporters { public abstract class PackageConsumerBase : BaseDbImporter { private class RegexpMatchEqualityComparer : IEqualityComparer<Match> { bool IEqualityComparer<Match>.Equals(Match x, Match y) => x.Value == y.Value; int IEqualityComparer<Match>.GetHashCode(Match obj) => 0; } public const string ReportPackageKeyword = "#RepPack"; protected readonly SqlCommandInitializer commandInitializer; private static readonly Regex reportPackageRegex = new Regex($@"\B\{ReportPackageKeyword}\w*\b"); private static readonly IEqualityComparer<Match> matchComparer = new RegexpMatchEqualityComparer(); private readonly BasePackageExportScriptCreator complexScriptCreator; protected PackageConsumerBase( IMapper mapper, DbImporterConfig config, IPackageBuilder builder, ThreadSafeRandom rnd, BasePackageExportScriptCreator exportScriptCreator, SqlCommandInitializer sqlCommandInitializer) : base(mapper, config, builder, rnd) { this.complexScriptCreator = exportScriptCreator; this.commandInitializer = sqlCommandInitializer; } public override async Task ExecuteAsync(IReportTaskRunContext taskContext) { int parameterGlobalIdx = 0; foreach (var packageName in GetRequiredPackageNames(Query)) { if (taskContext.Packages.ContainsKey(packageName) == false) throw new InvalidOperationException($"Required package, name:{packageName} doesn`t exist in the task context."); complexScriptCreator.BuildPackageExportQuery(taskContext.Packages[packageName], packageName, commandInitializer, ref parameterGlobalIdx); } complexScriptCreator.BuildMainQuery(taskContext.Parameters, Query, commandInitializer, parameterGlobalIdx); await ExecuteCommand(taskContext); } protected abstract Task ExecuteCommand(IReportTaskRunContext taskContext); private string[] GetRequiredPackageNames(string baseQuery) => reportPackageRegex.Matches(baseQuery).Distinct(matchComparer) .Select(x=>x.Value.Replace(ReportPackageKeyword, string.Empty)).ToArray(); } }
41.955224
153
0.710068
a4aa2b096351bf53dc2caf8e97c5ce57387f6fda
5,501
php
PHP
application/models/Crud.php
solusi-cipta-media/paket
c4aa17eff19c04092db2cdb5166753f39a7d0fa0
[ "MIT" ]
null
null
null
application/models/Crud.php
solusi-cipta-media/paket
c4aa17eff19c04092db2cdb5166753f39a7d0fa0
[ "MIT" ]
null
null
null
application/models/Crud.php
solusi-cipta-media/paket
c4aa17eff19c04092db2cdb5166753f39a7d0fa0
[ "MIT" ]
null
null
null
<?php class Crud extends CI_Model { public function get_where($table, $where) { $this->db->order_by("id", "DESC"); return $this->db->get_where($table, $where); } public function get_all($table) { $this->db->order_by("id", "DESC"); return $this->db->get($table); } public function get_all_limit($table) { $this->db->order_by("id", "DESC"); $this->db->limit(1); return $this->db->get($table); } public function get_between($table, $from, $to, $field, $ekspedisi) { $this->db->where("substr(scan_receive,1,10) BETWEEN '$from' AND '$to'"); $this->db->where($ekspedisi); return $this->db->get($table); } public function get_between2($table, $from, $to, $field, $ekspedisi) { $this->db->where("substr(terima_gudang,1,10) BETWEEN '$from' AND '$to'"); $this->db->where($ekspedisi); return $this->db->get($table); } public function get_between_tbl_mutasi($table, $from, $to) { $this->db->where("substr(scan_receive,1,10) BETWEEN '$from' AND '$to'"); return $this->db->get($table); } public function get_between_tbl_mutasi_return($table, $from, $to) { $this->db->where("substr(terima_gudang,1,10) BETWEEN '$from' AND '$to'"); return $this->db->get($table); } public function get_between_tbl_resi($table, $from, $to) { $this->db->where("substr(date_reg,1,10) BETWEEN '$from' AND '$to'"); return $this->db->get($table); } public function insert($table, $data) { $this->db->insert($table, $data); } public function delete($table, $data) { $this->db->delete($table, $data); return $this->db->affected_rows(); } public function update($table, $data, $where) { $this->db->where($where); $this->db->update($table, $data); return $this->db->affected_rows(); } public function join_data($select, $table1, $table2, $like, $where) { $this->db->select($select); $this->db->from($table1); $this->db->join($table2, $like); $this->db->where($where); return $this->db->get(); } private function _get_datatables_query($table, $select, $column_order, $column_search, $order, $where) { // $this->db->select("id, invoice_number, invoice_date, reference2"); $this->db->select($select); $this->db->from($table); if (!empty($where)) $this->db->where($where); $i = 0; foreach ($column_search as $item) // looping awal { if ($_POST['search']['value']) // jika datatable mengirimkan pencarian dengan metode POST { if ($i === 0) // looping awal { $this->db->group_start(); $this->db->like($item, $_POST['search']['value']); } else $this->db->or_like($item, $_POST['search']['value']); if (count($column_search) - 1 == $i) $this->db->group_end(); } $i++; } if (isset($_POST['order'])) $this->db->order_by($column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']); else if (isset($this->order)) $this->db->order_by(key($order), $order[key($order)]); } function get_datatables($table, $select, $column_order, $column_search, $order = null, $where = null) { $this->_get_datatables_query($table, $select, $column_order, $column_search, $order, $where); if ($_POST['length'] != -1) $this->db->limit($_POST['length'], $_POST['start']); return $this->db->get()->result(); } function count_filtered($table, $select, $column_order, $column_search, $order = null, $where = null) { $this->_get_datatables_query($table, $select, $column_order, $column_search, $order, $where); $query = $this->db->get(); return $query->num_rows(); } public function count_all($table, $where = null) { $this->db->from($table); if ($where != null) $this->db->where($where); return $this->db->count_all_results(); } public function count_where($table, $where) { $this->db->from($table); $this->db->where($where); return $this->db->count_all_results(); } public function sum_where($table, $where, $select) { $this->db->select_sum($select); $this->db->where($where); return $this->db->get($table); } function get_task_autocomplete($title, $table, $where) { $this->db->like('name', $title, 'both'); $this->db->order_by('name', 'ASC'); $this->db->where($where); $this->db->limit(10); return $this->db->get($table)->result(); } function get_task_autocomplete_sampah($title, $table) { $this->db->like('nama_sampah', $title, 'both'); $this->db->order_by('nama_sampah', 'ASC'); $this->db->limit(10); return $this->db->get($table)->result(); } function get_nomor_transaksi_terakhir($select, $table, $where) { $this->db->select($select); $this->db->from($table); $this->db->where($where); $this->db->limit(1); $this->db->order_by('id', 'desc'); return $this->db->get(); } }
30.561111
108
0.533539
da8c9a52c3290f9c1efad21175926e430dac9b70
946
php
PHP
Modules/HR/Events/InterviewCommunicationEmailSent.php
coloredcow-admin/employee-portal
84884d0ae59947111e837f499f9455a265b8fad6
[ "MIT" ]
22
2018-04-14T13:30:08.000Z
2021-02-24T15:10:39.000Z
Modules/HR/Events/InterviewCommunicationEmailSent.php
coloredcow-admin/employee-portal
84884d0ae59947111e837f499f9455a265b8fad6
[ "MIT" ]
482
2021-07-19T14:07:27.000Z
2022-03-31T13:55:28.000Z
Modules/HR/Events/InterviewCommunicationEmailSent.php
coloredcow-admin/employee-portal
84884d0ae59947111e837f499f9455a265b8fad6
[ "MIT" ]
17
2021-07-30T10:58:10.000Z
2022-03-26T16:52:55.000Z
<?php namespace Modules\HR\Events; use Illuminate\Queue\SerializesModels; class InterviewCommunicationEmailSent { use SerializesModels; private $condition; private $options; /** * Create a new event instance. * * @return void */ public function __construct($condition, $options) { $this->setCondition($condition); $this->setOptions($options); } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return []; } public function setCondition($condition) { $this->condition = $condition; } public function getCondition() { return $this->condition; } public function setOptions($options) { $this->options = $options; } public function getOptions($key) { return $this->options[$key] ?? null; } }
17.2
57
0.582452
a341834745d70313ff3791249100ec8021ff0ba9
2,457
swift
Swift
Sources/AppLogger/Views/FiltersView.swift
ipedro/AppLogger
1ec454678f898dbf81b9926b98954079a45ca329
[ "MIT" ]
3
2022-03-11T01:02:03.000Z
2022-03-18T17:22:25.000Z
Sources/AppLogger/Views/FiltersView.swift
ipedro/AppLogger
1ec454678f898dbf81b9926b98954079a45ca329
[ "MIT" ]
null
null
null
Sources/AppLogger/Views/FiltersView.swift
ipedro/AppLogger
1ec454678f898dbf81b9926b98954079a45ca329
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Pedro Almeida // // 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. import Foundation import SwiftUI struct FiltersView: View { var title: String private let spacing: CGFloat = 8 @Binding var filters: [Filter] var body: some View { LazyVStack(alignment: .leading, spacing: spacing) { Text("\(title) (\(filters.count))") .font(.caption) .foregroundColor(.secondary) .padding(.horizontal, spacing * 2) ScrollView(.horizontal, showsIndicators: false) { LazyHStack(spacing: spacing) { ForEach($filters, id: \.query) { FilterView(filter: $0) } } .padding(.horizontal, spacing * 2) .padding(.vertical, spacing) } } } } // MARK: - Previews struct FiltersViewPreviews: PreviewProvider { static var previews: some View { FiltersView( title: "Filters", filters: .constant([ .init(query: "0", displayName: "Inactive Filter", isActive: false), .init(query: "1", displayName: "Active Filter", isActive: true), .init(query: "2", displayName: "Another Active Filter", isActive: true) ]) ) .padding() .previewLayout(.sizeThatFits) } }
37.227273
87
0.627188
383d83e6a852a07b3fd936bdec7292eb5252f804
1,323
php
PHP
src/SprykerEco/Yves/Adyen/Form/SofortSubForm.php
spryker-eco/adyen
08602c87284074282e3cf14cd66139851ff4ec31
[ "MIT" ]
null
null
null
src/SprykerEco/Yves/Adyen/Form/SofortSubForm.php
spryker-eco/adyen
08602c87284074282e3cf14cd66139851ff4ec31
[ "MIT" ]
13
2018-11-15T09:08:21.000Z
2022-02-04T11:40:20.000Z
src/SprykerEco/Yves/Adyen/Form/SofortSubForm.php
spryker-eco/adyen
08602c87284074282e3cf14cd66139851ff4ec31
[ "MIT" ]
null
null
null
<?php /** * MIT License * For full license information, please view the LICENSE file that was distributed with this source code. */ namespace SprykerEco\Yves\Adyen\Form; use Generated\Shared\Transfer\AdyenSofortPaymentTransfer; use Generated\Shared\Transfer\PaymentTransfer; use SprykerEco\Shared\Adyen\AdyenConfig; use Symfony\Component\OptionsResolver\OptionsResolver; class SofortSubForm extends AbstractSubForm { /** * @var string */ protected const PAYMENT_METHOD = 'sofort'; /** * @return string */ public function getName(): string { return PaymentTransfer::ADYEN_SOFORT; } /** * @return string */ public function getPropertyPath(): string { return PaymentTransfer::ADYEN_SOFORT; } /** * @return string */ public function getTemplatePath(): string { return AdyenConfig::PROVIDER_NAME . DIRECTORY_SEPARATOR . static::PAYMENT_METHOD; } /** * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver * * @return void */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => AdyenSofortPaymentTransfer::class, ])->setRequired(static::OPTIONS_FIELD_NAME); } }
22.810345
105
0.664399
ee2782266368874304770be10b8ac739a211e9d4
2,279
dart
Dart
lib/page/tutorial/tutorial3_page.dart
kitProject-dev/idea_note
01b1f7279f677df195f1610383185ac7c82a2550
[ "Apache-2.0" ]
null
null
null
lib/page/tutorial/tutorial3_page.dart
kitProject-dev/idea_note
01b1f7279f677df195f1610383185ac7c82a2550
[ "Apache-2.0" ]
null
null
null
lib/page/tutorial/tutorial3_page.dart
kitProject-dev/idea_note
01b1f7279f677df195f1610383185ac7c82a2550
[ "Apache-2.0" ]
null
null
null
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:idea_note/config/assets.dart'; import 'package:idea_note/config/route.dart'; class Tutorial3Page extends StatelessWidget { const Tutorial3Page(this._pageController); final PageController _pageController; @override Widget build(BuildContext context) { final themeData = Theme.of(context); return Container( color: Colors.green[300], child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.only(top: 200, bottom: 20), child: Image.asset(Assets.tutorial3), ), Expanded( child: Center( child: Padding( padding: const EdgeInsets.only(right: 5, left: 5), child: Text( AppLocalizations.of(context).tutorialText3, style: themeData.primaryTextTheme.bodyText2 .copyWith(color: Colors.white), ), ), ), ), ElevatedButton( child: Text(AppLocalizations.of(context).doSetting), style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(3), ), ), onPressed: () async { await Navigator.of(context).pushNamed(RoutePath.settingTitle); }, ), Padding( padding: const EdgeInsets.only(bottom: 20, right: 20, left: 20), child: Row( children: <Widget>[ const Spacer(), TextButton( child: Text( AppLocalizations.of(context).next, style: themeData.textTheme.button .copyWith(color: Colors.white), ), onPressed: () { _pageController.nextPage( duration: const Duration(milliseconds: 500), curve: Curves.ease); }, ), ], ), ), ], ), ); } }
32.098592
76
0.512067
585f13fe313f998af18d2d7f79016d15c5730217
6,752
css
CSS
css/Qualification.css
Abhijit-Dey100/Portfolio
a6a2e57a899b2bf5917c92a2274b41f3fc987ea5
[ "MIT" ]
null
null
null
css/Qualification.css
Abhijit-Dey100/Portfolio
a6a2e57a899b2bf5917c92a2274b41f3fc987ea5
[ "MIT" ]
3
2020-11-28T13:20:42.000Z
2021-01-01T16:53:34.000Z
css/Qualification.css
Sushant2024/cv
168b1dcc1f56b6fc3d3bd74fc640ea828fcfa0b9
[ "MIT" ]
2
2020-11-23T17:25:40.000Z
2020-11-23T17:41:54.000Z
/*==================================================== AWARD ======================================================*/ #awards { background: #f0f0f0; } #award-box { overflow: hidden; position: relative; padding: 60px 0; } #award-box:before { content: ""; width: 1px; height: 100%; background: #cfcdcd; position: absolute; top: 0; left: 50%; } #award-box .award { width: 50%; clear: both; position: relative; } #award-box .award:before, #award-box .award:after { content: ""; display: block; clear: both; } #award-box .award:first-child:before, #award-box .award:last-child:before { content: ""; width: 11px; height: 11px; background: #cfcdcd; box-sizing: content-box; border: 5px solid #fff; box-shadow: 0 0 0 2px #cfcdcd; position: absolute; top: -54px; right: -11px; transform: rotate(45deg); } #award-box .award:last-child:before { top: auto; bottom: -54px; } #award-box .award:last-child:nth-child(even):before { right: auto; left: -11px; } #award-box .award-icon { width: 24px; height: 24px; background: #fff; border: 1px solid #cfcdcd; position: absolute; top: 17px; right: -13px; z-index: 1; transform: rotate(45deg); } #award-box .award-icon:before { content: ""; display: block; width: 15px; height: 15px; background: #fff; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); transition: background-color 0.2s ease 0s; } #award-box .award:hover .award-icon:before { background: #39b3ff; } #award-box .award-content { width: 85%; padding: 18px 30px; background: #fff; text-align: right; float: left; border: 1px solid transparent; position: relative; transition: all 0.3s ease 0s; } #award-box .award:hover .award-content { border: 1px solid #cfcdcd; } #award-box .award-content:before { content: ""; display: block; width: 14px; height: 14px; background: #fff; border: 1px solid #cfcdcd; position: absolute; top: 21px; right: -7.3px; transform: rotate(45deg); transition: all 0.2s ease 0s; } #award-box .award:hover .award-content:before { background: #39b3ff; border-color: #39b3ff; } #award-box .award-content:after { content: ""; width: 11%; height: 1px; background: #cfcdcd; position: absolute; top: 28px; right: -14%; } #award-box .date { display: block; font-size: 15px; font-weight: 600; color: #39b3ff; margin: 0 0 8px; transition: all 0.3s ease 0s; } #award-box .alignL { font-size: 16px; color: #777; line-height: 28px; text-align: left; float: left; margin: 0 10px 8px; } #award-box .alignR { font-size: 16px; color: #777; line-height: 28px; text-align: left; float: left; margin: 0 10px 8px; } #award-box .award:hover .date { color: #444; } #award-box .title { font-size: 18px; color: #444; margin-top: 0; transition: all 0.3s ease 0s; } #award-box .award:hover .title { color: #39b3ff; } #award-box .description { font-size: 16px; color: #777; line-height: 28px; margin-top: 8px; } #award-box .award:nth-child(2n), #award-box .award:nth-child(2n) .award-content { float: right; text-align: left; } #award-box .award:nth-child(2n) .award-icon { right: 0; left: -12px; } #award-box .award:nth-child(2n) .award-content:before { left: -7.3px; } #award-box .award:nth-child(2n) .award-content:after { left: -14%; } @media only screen and (max-width: 767px) { #award-box { padding-left: 20px; } #award-box:before { left: 20px; } #award-box .award { width: 100%; } #award-box .award, #award-box .award-content { float: right; padding:5px; text-align: left; } #award-box .award:first-child:before, #award-box .award:last-child:nth-child(odd):before { right: auto; left: -11px; } #award-box .award-icon { right: 0; left: -12px; } #award-box .award-content:before { left: -7.3px; } #award-box .award-content:after { left: -14%; } } /* Already responsive page */ /*-------------------------------------------- CARD MODEL -----------------------------------------------*/ .container{ display: flex; justify-content: center; align-items: center; max-width: 1200px; flex-wrap: wrap; padding: 80px 0; } .container p{ text-align: left; } .container .card{ position: relative; width: 320px; height: 440px; box-shadow: inset 5px 5px 5px rgba(0, 0, 0, .05), inset -5px -5px 5px rgba(255, 255, 255, 0.5), 5px 5px 5px rgba(0, 0, 0, .05), -5px -5px 5px rgba(255, 255, 255, 0.5); border-radius: 15px; margin: 30px; } .container .card .box{ position: absolute; top: 20px; left: 20px; right: 20px; bottom: 20px; background: #ebf5fc; box-shadow: 0 10px 20px rgba(0, 0, 0, .1); border-radius: 15px; display: flex; justify-content: center; align-items: center; transition: 0.5s; } .container .card:hover .box{ transform: translateY(-50px); box-shadow: 0 10px 40px rgba(0, 0, 0, .3); background: linear-gradient(45deg, #b95ce4, #4f29cd); } .container .card .box .content { padding: 20px; text-align: center; } /* change -------------------------------------------- */ .container .card .box .content h2{ position: absolute; top: -10px; right: 30px; font-size: 8em; color: rgba(0, 0, 0, .05); transition: 0.5s; pointer-events: none; } .container .card:hover .box .content h2{ color: rgba(0, 0, 0, .05); } .container .card .box .content h3{ font-size: 1.8em; color: #000; z-index: 1; transition: 0.5s; } .container .card .box .content h5{ color: #777; z-index: 1; transition: 0.5s; } .container .card .box .content p{ font-size: 1em; font-weight: 300; color: #777; z-index: 1; transition: 0.5s; } .container .card:hover .box .content p, .container .card:hover .box .content h3, .container .card:hover .box .content h5{ color: #fff; } .container .card .box .content a{ position: relative; display: inline-block; padding: 8px 20px; background: #03a9f4; margin-top: 15px; border-radius: 20px; color: #fff; text-decoration: none; font-weight: 400; box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2); } .container .card:hover .box .content a{ background: #ff568f; }
19.514451
107
0.563981
94a340ad2c5bf177c668a2600e40b6e3c37cf1b3
12,558
sql
SQL
ecafe/cafe.sql
YadavAnurag/ecafe
f3eee034044d957bb800d6a3d859e7ed0480d81a
[ "MIT" ]
null
null
null
ecafe/cafe.sql
YadavAnurag/ecafe
f3eee034044d957bb800d6a3d859e7ed0480d81a
[ "MIT" ]
null
null
null
ecafe/cafe.sql
YadavAnurag/ecafe
f3eee034044d957bb800d6a3d859e7ed0480d81a
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Feb 04, 2018 at 04:04 PM -- Server version: 10.1.28-MariaDB -- PHP Version: 7.1.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `cafe` -- -- -------------------------------------------------------- -- -- Table structure for table `feedbacks` -- CREATE TABLE `feedbacks` ( `feedback_id` int(10) UNSIGNED NOT NULL, `email` varchar(60) NOT NULL, `body` longtext NOT NULL, `date_entered` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `feedbacks` -- INSERT INTO `feedbacks` (`feedback_id`, `email`, `body`, `date_entered`) VALUES (1, '1', 'Your starter is good', '2018-01-26 20:07:32'), (2, 'hi@gmail.com', 'This is measdfkjas', '0000-00-00 00:00:00'), (4, 'hei@gmail.com', 'This is measdfkjas', '0000-00-00 00:00:00'), (6, 'anuragyadav@gmail.com', 'how are you This is measdfkjas', '0000-00-00 00:00:00'), (8, 'hiiiii@gmail.com', 'hi how are you', '0000-00-00 00:00:00'), (13, 'asdfljk@gmail.com', 'adf;lajfd;lka', '0000-00-00 00:00:00'), (15, 'a@gmail.com', 'Fuck you', '0000-00-00 00:00:00'), (19, 'lalpanne0084@gmail.com', 'your site is good', '0000-00-00 00:00:00'), (20, 'anu@gmail.com', '', '0000-00-00 00:00:00'), (21, 'tanu@gmail.com', 'Fuck You', '0000-00-00 00:00:00'), (23, 'h@gmail.com', 'hi this is me', '2018-01-28 19:38:38'), (24, 'cp@gmail.com', 'dsdgsdgfsgf', '2018-01-28 20:12:15'), (25, 'darkmooon@gmail.com', 'Hiiiiiiii', '2018-01-29 11:42:16'), (26, 'salman@gmail.com', 'this is my feedback', '2018-01-29 13:09:04'), (27, 'sfdasa@gmail.com', 'asfdasdfasdfasdfsadfsdaf', '2018-01-29 21:08:23'), (28, 'sarvesh@gmail.com', 'this is my feedback', '2018-01-29 23:30:31'), (32, 'ausaf78650@gmail.com', 'this is the best one', '2018-01-31 15:06:43'); -- -------------------------------------------------------- -- -- Table structure for table `genders` -- CREATE TABLE `genders` ( `gender_id` int(10) UNSIGNED NOT NULL, `gender` enum('Male','Female','Other') NOT NULL DEFAULT 'Male' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `genders` -- INSERT INTO `genders` (`gender_id`, `gender`) VALUES (1, 'Male'), (2, 'Female'), (3, 'Other'); -- -------------------------------------------------------- -- -- Table structure for table `menus` -- CREATE TABLE `menus` ( `menu_id` int(10) UNSIGNED NOT NULL, `category_id` int(10) UNSIGNED NOT NULL, `name` varchar(40) NOT NULL, `info` varchar(100) DEFAULT NULL, `price` int(4) NOT NULL, `date_entered` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `menus` -- INSERT INTO `menus` (`menu_id`, `category_id`, `name`, `info`, `price`, `date_entered`) VALUES (1, 2, 'samosa', 'this is our samosa which is best', 5, '2018-01-28 13:19:14'), (3, 3, 'Maggi', 'University canteen make best maggi', 10, '2018-01-28 18:23:16'), (4, 2, 'asfd', 'asdf', 32, '0000-00-00 00:00:00'), (5, 2, 'Chola', 'pudi chola', 100, '0000-00-00 00:00:00'), (6, 1, 'adsf', 'afds', 89, '0000-00-00 00:00:00'), (7, 1, 'ADSas', 'safd', 100, '0000-00-00 00:00:00'), (9, 3, 'Kadahi Panner', 'Anuradha serves worst food in the contry', 100, '0000-00-00 00:00:00'), (10, 2, 'Item', 'about the item', 44, '0000-00-00 00:00:00'), (11, 1, 'ewsargsad', 'sadf', 100, '0000-00-00 00:00:00'), (12, 2, 'asdfsafdsaf', 'adsf', 100, '2018-01-28 19:25:28'), (13, 2, 'Pudi', 'this is pudi', 23, '2018-01-28 20:13:15'), (14, 1, 'sdfg', 'sdfg', 100, '2018-01-29 04:17:09'), (15, 2, 'Pannerer', 'asfdsadfsadf', 100, '2018-01-29 04:17:22'), (16, 2, 'sadfsadf', 'asfd', 34, '2018-01-29 04:17:31'), (17, 2, 'Pizza', 'THis is pizza', 85, '2018-01-29 11:40:58'), (19, 3, 'Adi Masala', 'This is best', 100, '2018-01-29 23:31:56'), (20, 2, 'Sakoda', 'Desi Soup, If you wish...', 45, '2018-01-30 04:40:26'), (21, 2, 'Lunch Item', 'THis is lunch item', 45, '2018-01-30 21:31:56'), (24, 2, 'Mix Vage', 'this is mix vage', 50, '2018-01-30 21:34:23'), (25, 3, 'asfdkjh', 'akjfl', 23, '2018-01-30 21:38:22'), (27, 2, 'a;ldkfja;fdlkasj;kl', 'adfka', 100, '2018-01-30 21:38:59'), (28, 2, 'dsfgafafafafdaa', 'asfa', 12, '2018-01-30 21:40:59'), (29, 3, 'dsfgafafafafdaadsg', 'asfaasfdas', 100, '2018-01-30 21:43:25'), (31, 2, 'kfdj;kldfaj', 'sadsdfgds', 100, '2018-01-30 21:44:38'), (32, 1, 'Breakfast', 'this isa the', 60, '2018-01-31 15:10:32'), (34, 1, 'Samosasa', 'ABE BHUKKHA KHI KE SAMOSA KHANA HAI KYA TO AA JAO\r\nHI THIS IS ME ANURAG YADAV\r\nAND WHO ARE YOU', 100, '2018-01-31 22:00:20'), (35, 1, 'How are You', 'ABE BHUKKHA KHI KE SAMOSA KHANA HAI KYA TO AA JAO HI THIS IS ME ANURAG YADAV AND WHO ARE YOU\r\nABE BH', 50, '2018-01-31 22:51:47'), (36, 1, 'Rabdi', 'This is rabdi', 100, '2018-02-01 03:03:25'); -- -------------------------------------------------------- -- -- Table structure for table `menu_category` -- CREATE TABLE `menu_category` ( `category_id` int(10) UNSIGNED NOT NULL, `name` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `menu_category` -- INSERT INTO `menu_category` (`category_id`, `name`) VALUES (3, 'Dinner'), (2, 'Lunch'), (1, 'Starter'); -- -------------------------------------------------------- -- -- Table structure for table `reservations` -- CREATE TABLE `reservations` ( `reservation_id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED NOT NULL, `table_no` int(10) UNSIGNED NOT NULL, `table_datetime` datetime NOT NULL, `people` int(10) UNSIGNED NOT NULL, `date_entered` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `reservations` -- INSERT INTO `reservations` (`reservation_id`, `user_id`, `table_no`, `table_datetime`, `people`, `date_entered`) VALUES (18, 28, 3, '2018-01-18 12:00:00', 1, '2018-01-31 01:47:30'), (19, 24, 6, '2018-01-09 10:00:00', 1, '2018-01-31 03:14:16'), (22, 2, 10, '2018-01-09 10:00:00', 1, '2018-01-31 03:15:29'), (24, 29, 2, '2018-02-01 12:00:00', 3, '2018-01-31 15:06:03'), (25, 2, 1, '2018-02-07 10:00:00', 1, '2018-02-02 07:23:48'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `user_id` int(10) UNSIGNED NOT NULL, `first_name` varchar(40) NOT NULL, `middle_name` varchar(60) DEFAULT NULL, `last_name` varchar(60) DEFAULT NULL, `gender_id` int(10) UNSIGNED NOT NULL, `email` varchar(60) NOT NULL, `pass` char(40) NOT NULL, `mobile` varchar(12) NOT NULL, `address` longtext NOT NULL, `date_entered` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `first_name`, `middle_name`, `last_name`, `gender_id`, `email`, `pass`, `mobile`, `address`, `date_entered`) VALUES (1, 'fuck', 'you', '', 1, 'anufz00@gmail.com', 'e727d1464ae12436e899a726da5b2f11d8381b26', '83', 'want to know my address fuck you!!!!!!', '2018-01-23 04:02:24'), (2, 'Hello', 'asdf', '', 2, 'anu@gmail.com', 'SHA1(hi)', '66925', 'asfasf', '2018-01-25 04:48:32'), (3, 'Dark', 'Middle', '', 2, 'anurag@gmail.com', 'SHA1(anu)', '653217', 'safdasfyasoiu', '2018-01-25 10:58:26'), (5, 'Dark', 'Middle', '', 2, 'anuragfz@gmail.com', 'SHA1(123)', '653217', 'safdasfyasoiuSDFG', '2018-01-25 11:00:57'), (6, 'anuragaf', 'klfsj', '', 1, 'hiii@gmail.com', 'SHA1(op)', '993515352', 'skajfdhalskj', '2018-01-26 20:56:15'), (7, 'panne', '', '', 1, 'lalpanne0084@gmail.com', 'SHA1(123)', '9648004984', 'Tagore Bhawan ,room no.F-17 \r\nMMMUT GKP', '2018-01-27 01:43:47'), (8, 'sakjdf', 'aksjfhalkjafl', '', 1, 'ag@gmail.com', 'SHA1(anu)', '5567685', 'adsfsa', '2018-01-27 17:13:03'), (9, 'asfd', 'safdlkjh', '', 1, 'y@gmaoil.com', 'SHA1(you)', '57463', 'sadfsa', '2018-01-27 17:16:38'), (10, 'ifrsts', '', '', 1, 'j@gmail.com', 'SHA1(hi)', '567658', '56765', '2018-01-27 17:31:18'), (11, 'first', '', '', 2, 'k@gmail.com', 'SHA1(pass)', '35434352', 'asdfkjhgasfj', '2018-01-27 17:32:38'), (16, 'first', '', '', 2, 'k@gmail.com', 'SHA1(pass)', '35434352', 'asdfkjhgasfj', '2018-01-27 18:11:21'), (17, 'first', '', '', 2, 'k@gmail.com', 'SHA1(pass)', '35434352', 'asdfkjhgasfj', '2018-01-27 18:12:38'), (18, 'first', '', '', 2, 'k@gmail.com', 'SHA1(pass)', '35434352', 'asdfkjhgasfj', '2018-01-27 18:19:06'), (19, 'first', '', '', 2, 'k@gmail.com', 'SHA1(pass)', '35434352', 'asdfkjhgasfj', '2018-01-27 18:19:09'), (20, 'first', '', '', 2, 'k@gmail.com', 'SHA1(pass)', '35434352', 'asdfkjhgasfj', '2018-01-27 18:19:32'), (21, 'anu', 'asfsa', '', 1, 'youy@gmail.com', 'SHA1(i)', '58768575', 'askdfjhsa', '2018-01-27 18:57:37'), (22, 'Anurag', '', '', 2, 'dark@gmail.com', 'hello', '969696', 'tagore bhawan', '2018-01-28 12:00:40'), (23, 'Anurag', '', '', 2, 'darkMOON@gmail.com', 'SHA1(\'ASD\')', '969696', 'tagore bhawan', '2018-01-28 12:01:53'), (24, 'cp', '', '', 1, 'cp@gmail.com', 'cpp', '6522', 'asdf', '2018-01-28 20:11:55'), (25, 'First', 'Middl', '', 2, 'tanuT@gmail.com', 'io', '895623', 'my addresss', '2018-01-29 11:43:37'), (26, 'salman', '', '', 1, 'salman@gmail.com', 'salman', '96969696', 'ambedkar', '2018-01-29 13:07:45'), (27, 'sarvesh', '', '', 1, 'sarvesh@gmail.com', 'sar', '9935132239', 'tagore bhawan f-24', '2018-01-29 23:30:04'), (28, 'First', '', '', 2, 'how@gmail.com', 'p', '369', 'safdsafdsa', '2018-01-31 01:35:13'), (29, 'Ausaf', 'Hussain', '', 1, 'ausaf78650@gmail.com', '12345', '9760092797', 'xnf', '2018-01-31 15:05:09'); -- -- Indexes for dumped tables -- -- -- Indexes for table `feedbacks` -- ALTER TABLE `feedbacks` ADD PRIMARY KEY (`feedback_id`), ADD UNIQUE KEY `email` (`email`), ADD KEY `date_entered` (`date_entered`); -- -- Indexes for table `genders` -- ALTER TABLE `genders` ADD PRIMARY KEY (`gender_id`), ADD UNIQUE KEY `gender` (`gender`); -- -- Indexes for table `menus` -- ALTER TABLE `menus` ADD PRIMARY KEY (`menu_id`), ADD UNIQUE KEY `name` (`name`), ADD KEY `category_id` (`category_id`), ADD KEY `name_2` (`name`); -- -- Indexes for table `menu_category` -- ALTER TABLE `menu_category` ADD PRIMARY KEY (`category_id`), ADD UNIQUE KEY `name` (`name`); -- -- Indexes for table `reservations` -- ALTER TABLE `reservations` ADD PRIMARY KEY (`reservation_id`), ADD UNIQUE KEY `table_no` (`table_no`), ADD KEY `user_id` (`user_id`), ADD KEY `table_no_2` (`table_no`), ADD KEY `date_entered` (`date_entered`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`), ADD KEY `gender_id` (`gender_id`), ADD KEY `date_entered` (`date_entered`), ADD KEY `email_2` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `feedbacks` -- ALTER TABLE `feedbacks` MODIFY `feedback_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33; -- -- AUTO_INCREMENT for table `genders` -- ALTER TABLE `genders` MODIFY `gender_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `menus` -- ALTER TABLE `menus` MODIFY `menu_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37; -- -- AUTO_INCREMENT for table `menu_category` -- ALTER TABLE `menu_category` MODIFY `category_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `reservations` -- ALTER TABLE `reservations` MODIFY `reservation_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30; -- -- Constraints for dumped tables -- -- -- Constraints for table `menus` -- ALTER TABLE `menus` ADD CONSTRAINT `menus_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `menu_category` (`category_id`); -- -- Constraints for table `reservations` -- ALTER TABLE `reservations` ADD CONSTRAINT `reservations_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`); -- -- Constraints for table `users` -- ALTER TABLE `users` ADD CONSTRAINT `users_ibfk_1` FOREIGN KEY (`gender_id`) REFERENCES `genders` (`gender_id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
36.4
162
0.62494
20cbc7e919c1060f1af5e0501e5b046321def912
2,157
kt
Kotlin
src/test/kotlin/za/ac/sun/plume/PolyglotExtractorTest.kt
fabsx00/plume-extractor
e100de9ca17192451412e3743ef6fc645ec0c4f0
[ "Apache-2.0" ]
2
2020-12-20T16:08:37.000Z
2021-11-13T15:21:21.000Z
src/test/kotlin/za/ac/sun/plume/PolyglotExtractorTest.kt
fabsx00/plume-extractor
e100de9ca17192451412e3743ef6fc645ec0c4f0
[ "Apache-2.0" ]
null
null
null
src/test/kotlin/za/ac/sun/plume/PolyglotExtractorTest.kt
fabsx00/plume-extractor
e100de9ca17192451412e3743ef6fc645ec0c4f0
[ "Apache-2.0" ]
null
null
null
package za.ac.sun.plume import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import za.ac.sun.plume.domain.models.vertices.* import za.ac.sun.plume.drivers.DriverFactory import za.ac.sun.plume.drivers.GraphDatabase import za.ac.sun.plume.drivers.TinkerGraphDriver import java.io.File class PolyglotExtractorTest { companion object { private val driver = DriverFactory(GraphDatabase.TINKER_GRAPH) as TinkerGraphDriver private val TEST_PATH = "extractor_tests${File.separator}" private lateinit var CLS_PATH: File private lateinit var extractor: Extractor private lateinit var validPy2File: File private lateinit var validJsFile: File private lateinit var polyglotDir: File private fun getTestResource(dir: String): File { val resourceURL = PolyglotExtractorTest::class.java.classLoader.getResource(dir) ?: throw java.lang.NullPointerException("Unable to obtain test resource") return File(resourceURL.file) } @BeforeAll @JvmStatic fun setUpAll() { validPy2File = getTestResource("${TEST_PATH}Test4.py") validJsFile = getTestResource("${TEST_PATH}Test5.js") polyglotDir = getTestResource("${TEST_PATH}polyglot") CLS_PATH = File(getTestResource(TEST_PATH).absolutePath.replace(System.getProperty("user.dir") + File.separator, "").removeSuffix(TEST_PATH.replace(File.separator, ""))) extractor = Extractor(driver, CLS_PATH) } } @AfterEach fun tearDown() { driver.clearGraph() } @Test fun validPy2Test() { extractor.load(validPy2File) extractor.project() } @Test fun validJsTest() { extractor.load(validJsFile) extractor.project() } @Test fun compileMultipleLanguagesTest() { extractor.load(polyglotDir) extractor.project() } }
33.184615
181
0.686602
3dfc04ae8ff07e8a96a740e393e89f16e4f6d67e
740
sql
SQL
tests/queries/0_stateless/01045_bloom_filter_null_array.sql
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
15,577
2019-09-23T11:57:53.000Z
2022-03-31T18:21:48.000Z
tests/queries/0_stateless/01045_bloom_filter_null_array.sql
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
16,476
2019-09-23T11:47:00.000Z
2022-03-31T23:06:01.000Z
tests/queries/0_stateless/01045_bloom_filter_null_array.sql
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
3,633
2019-09-23T12:18:28.000Z
2022-03-31T15:55:48.000Z
DROP TABLE IF EXISTS bloom_filter_null_array; CREATE TABLE bloom_filter_null_array (v Array(LowCardinality(Nullable(String))), INDEX idx v TYPE bloom_filter(0.1) GRANULARITY 1) ENGINE = MergeTree() ORDER BY v; INSERT INTO bloom_filter_null_array VALUES ([]); INSERT INTO bloom_filter_null_array VALUES (['1', '2']) ([]) ([]); INSERT INTO bloom_filter_null_array VALUES ([]) ([]) (['2', '3']); SELECT COUNT() FROM bloom_filter_null_array; SELECT COUNT() FROM bloom_filter_null_array WHERE has(v, '1'); SELECT COUNT() FROM bloom_filter_null_array WHERE has(v, '2'); SELECT COUNT() FROM bloom_filter_null_array WHERE has(v, '3'); SELECT COUNT() FROM bloom_filter_null_array WHERE has(v, '4'); DROP TABLE IF EXISTS bloom_filter_null_array;
46.25
163
0.758108
3ca4b661f6d8acdb5c73c3f9e0e75a8382e1e88e
291
kt
Kotlin
chat-components/framework/src/main/java/com/pubnub/framework/data/Typing.kt
pubnub/chat-components-android
6e682ba069b5a4e425d07942b4f7c6d01382739a
[ "MIT" ]
null
null
null
chat-components/framework/src/main/java/com/pubnub/framework/data/Typing.kt
pubnub/chat-components-android
6e682ba069b5a4e425d07942b4f7c6d01382739a
[ "MIT" ]
5
2021-11-30T06:54:39.000Z
2022-02-23T11:15:34.000Z
chat-components/framework/src/main/java/com/pubnub/framework/data/Typing.kt
pubnub/chat-components-android
6e682ba069b5a4e425d07942b4f7c6d01382739a
[ "MIT" ]
1
2021-11-03T11:21:12.000Z
2021-11-03T11:21:12.000Z
package com.pubnub.framework.data import com.pubnub.framework.util.timetoken data class Typing( val userId: UserId, val channelId: ChannelId, val isTyping: Boolean, val timestamp: Long = System.currentTimeMillis().timetoken, ) typealias TypingMap = HashMap<UserId, Typing>
24.25
63
0.756014
a1628dcd6ce142b7cee6bb80b925ca3e4b5b700f
195
ts
TypeScript
src/features/widgets/view/components/ManagePresets/index.ts
leongaban/redux-saga-exchange
be968a46c95a2324a8e9480bcbc8e528e5518172
[ "MIT" ]
2
2021-07-02T04:56:15.000Z
2021-09-27T16:57:55.000Z
src/features/widgets/view/components/ManagePresets/index.ts
leongaban/redux-saga-exchange
be968a46c95a2324a8e9480bcbc8e528e5518172
[ "MIT" ]
null
null
null
src/features/widgets/view/components/ManagePresets/index.ts
leongaban/redux-saga-exchange
be968a46c95a2324a8e9480bcbc8e528e5518172
[ "MIT" ]
null
null
null
export { default as Presets } from './Presets/Presets'; export { default as NewPreset } from './NewPreset/NewPreset'; export {default as FieldList, IFieldListProps} from './FieldList/FieldList';
48.75
76
0.753846
69e63657ff5dd57f433ce57aeb232ea83e2bec47
409
dart
Dart
lib/blocs/photos/photos_event.dart
bartukaan/flutter_photos
03787694b6cad56c56a22648b1357c045bb1c0d1
[ "MIT" ]
null
null
null
lib/blocs/photos/photos_event.dart
bartukaan/flutter_photos
03787694b6cad56c56a22648b1357c045bb1c0d1
[ "MIT" ]
null
null
null
lib/blocs/photos/photos_event.dart
bartukaan/flutter_photos
03787694b6cad56c56a22648b1357c045bb1c0d1
[ "MIT" ]
1
2021-12-09T09:22:57.000Z
2021-12-09T09:22:57.000Z
part of 'photos_bloc.dart'; abstract class PhotosEvent extends Equatable { const PhotosEvent(); @override List<Object> get props => []; @override bool get stringify => true; } class PhotosSearchPhotos extends PhotosEvent { final String query; const PhotosSearchPhotos({@required this.query}); @override List<Object> get props => [query]; } class PhotosPaginate extends PhotosEvent {}
17.782609
51
0.723716
6d00b7716c9b4901c7b19c4fd8360497fae7ef2c
217
ts
TypeScript
DreamCard/Client/Game_Combat/bin/newaes/newaes.d.ts
XWorldGames/Games
1043903d71d1c8ab5e6ff0047e9b078905b4b712
[ "MIT" ]
8
2021-07-17T20:40:26.000Z
2022-01-24T19:09:49.000Z
libs/modules/newaes/newaes.d.ts
GitHub-Zjw/h5NiuNiu
0386cd01047d6bce8e25630abd5c6d7c4437399e
[ "MIT" ]
null
null
null
libs/modules/newaes/newaes.d.ts
GitHub-Zjw/h5NiuNiu
0386cd01047d6bce8e25630abd5c6d7c4437399e
[ "MIT" ]
8
2021-08-02T04:45:30.000Z
2022-03-18T12:36:03.000Z
/* 模块名称:newaes 模块说明:按照egret的要求,重新组织AES接口,提供加密解密调用; 修改:毛明超; 日期:2016-6-8 QQ:4176244, 3128666862 */ declare class newaes { constructor(); ex(data:any, key:any, iv:any):any; dx(data:any, key:any, iv:any):any; }
15.5
38
0.682028
1a4cfe52e64e1cbc2af980058707dd3747218637
988
py
Python
instance/config.py
koitoror/store-manager-ch-3
62e614bc4cc3d8b48e2a1889eca516e737711edc
[ "MIT" ]
1
2019-10-25T20:51:08.000Z
2019-10-25T20:51:08.000Z
instance/config.py
koitoror/store-manager-ch-3
62e614bc4cc3d8b48e2a1889eca516e737711edc
[ "MIT" ]
4
2018-10-11T09:08:29.000Z
2018-10-27T10:50:56.000Z
instance/config.py
koitoror/StoreManager
f806b8aa989393b4d2b1967c5be99ee3c4b5b9b6
[ "MIT" ]
null
null
null
# config.py import os class Config(object): """Parent configuration class.""" DEBUG = False TESTING = False # SECRET_KEY = os.getenv('SECRET_KEY') SECRET_KEY="some-very-long-string-of-random-characters-CHANGE-TO-YOUR-LIKING" RESTPLUS_VALIDATE = True ERROR_404_HELP = False # db_name = os.getenv("DATABASE") # host = os.getenv("HOST") # role = os.getenv("ROLE") # pwd = os.getenv("PASSWORD") # port = os.getenv("PORT") class DevelopmentConfig(Config): """Configurations for Development.""" DEBUG = True MODE="development" class TestingConfig(Config): """Configurations for Testing, with a separate test database.""" TESTING = True DEBUG = True # db_name = os.getenv("TEST_DB") MODE="testing" class ProductionConfig(Config): """Configurations for Production.""" DEBUG = False app_config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'production': ProductionConfig, }
25.333333
81
0.662955
4bf773b54ad27fd02e6b58ade3b1f3b7e51cdb79
4,547
h
C
gst/gst-kvs-plugin/src/KvsWebRtc.h
adamthesax/amazon-kinesis-video-streams-demos
26bfc487e8de5b4d0a11f87f5f4919e89bc6a186
[ "Apache-2.0" ]
40
2020-04-23T20:13:53.000Z
2022-03-17T03:30:42.000Z
gst/gst-kvs-plugin/src/KvsWebRtc.h
adamthesax/amazon-kinesis-video-streams-demos
26bfc487e8de5b4d0a11f87f5f4919e89bc6a186
[ "Apache-2.0" ]
62
2020-04-23T20:45:42.000Z
2022-01-26T21:36:37.000Z
gst/gst-kvs-plugin/src/KvsWebRtc.h
adamthesax/amazon-kinesis-video-streams-demos
26bfc487e8de5b4d0a11f87f5f4919e89bc6a186
[ "Apache-2.0" ]
28
2020-05-07T12:12:13.000Z
2022-03-09T06:17:08.000Z
#ifndef __KVS_WEBRTC_FUNCTIONALITY_H__ #define __KVS_WEBRTC_FUNCTIONALITY_H__ #define DEFAULT_MASTER_CLIENT_ID "KvsPluginMaster" #define DEFAULT_VIEWER_CLIENT_ID "KvsPluginViewer" #define DEFAULT_CHANNEL_NAME "DEFAULT_CHANNEL" #define DEFAULT_TRICKLE_ICE_MODE TRUE #define DEFAULT_WEBRTC_CONNECTION_MODE WEBRTC_CONNECTION_MODE_DEFAULT #define DEFAULT_WEBRTC_CONNECT TRUE #define GST_PLUGIN_HASH_TABLE_BUCKET_COUNT 50 #define GST_PLUGIN_HASH_TABLE_BUCKET_LENGTH 2 #define GST_PLUGIN_PRE_GENERATE_CERT_START (200 * HUNDREDS_OF_NANOS_IN_A_MILLISECOND) #define GST_PLUGIN_PRE_GENERATE_CERT_PERIOD (1000 * HUNDREDS_OF_NANOS_IN_A_MILLISECOND) #define GST_PLUGIN_PENDING_MESSAGE_CLEANUP_DURATION (20 * HUNDREDS_OF_NANOS_IN_A_SECOND) #define GST_PLUGIN_STATS_DURATION (60 * HUNDREDS_OF_NANOS_IN_A_SECOND) #define GST_PLUGIN_SERVICE_ROUTINE_START (300 * HUNDREDS_OF_NANOS_IN_A_MILLISECOND) #define GST_PLUGIN_SERVICE_ROUTINE_PERIOD (1000 * HUNDREDS_OF_NANOS_IN_A_MILLISECOND) // Default opus frame duration #define GST_PLUGIN_DEFAULT_FRAME_DURATION (20 * HUNDREDS_OF_NANOS_IN_A_MILLISECOND) // IDR NALU type value #define IDR_NALU_TYPE 0x05 #define H264_SPS_NALU_TYPE 0x07 #define H264_PPS_NALU_TYPE 0x08 // H265 IDR NALU type value #define IDR_W_RADL_NALU_TYPE 0x13 #define IDR_N_LP_NALU_TYPE 0x14 #define H265_VPS_NALU_TYPE 0x20 #define H265_SPS_NALU_TYPE 0x21 #define H265_PPS_NALU_TYPE 0x22 #define KVS_WEBRTC_CLIENT_USER_AGENT_NAME "KVS_GST_PLUGIN_WEBRTC" #define IS_NALU_H264_IDR_HEADER(h) (((h) &0x80) == 0 && ((h) &0x60) != 0 && ((h) &0x1f) == IDR_NALU_TYPE) #define IS_NALU_H264_SPS_PPS_HEADER(h) \ (((h) &0x80) == 0 && ((h) &0x60) != 0 && (((h) &0x1f) == H264_SPS_NALU_TYPE || ((h) &0x1f) == H264_PPS_NALU_TYPE)) #define IS_NALU_H265_IDR_HEADER(h) ((((h) >> 1) == IDR_W_RADL_NALU_TYPE || ((h) >> 1) == IDR_N_LP_NALU_TYPE)) #define IS_NALU_H265_VPS_SPS_PPS_HEADER(h) (((h) >> 1) == H265_VPS_NALU_TYPE || ((h) >> 1) == H265_SPS_NALU_TYPE || ((h) >> 1) == H265_PPS_NALU_TYPE) typedef VOID (*StreamSessionShutdownCallback)(UINT64, PWebRtcStreamingSession); STATUS signalingClientStateChangedFn(UINT64, SIGNALING_CLIENT_STATE); STATUS signalingClientErrorFn(UINT64, STATUS, PCHAR, UINT32); STATUS signalingClientMessageReceivedFn(UINT64, PReceivedSignalingMessage); STATUS initKinesisVideoWebRtc(PGstKvsPlugin); STATUS freeGstKvsWebRtcPlugin(PGstKvsPlugin); STATUS createMessageQueue(UINT64, PPendingMessageQueue*); STATUS freeMessageQueue(PPendingMessageQueue); STATUS gatherIceServerStats(PWebRtcStreamingSession); STATUS freeWebRtcStreamingSession(PWebRtcStreamingSession*); STATUS streamingSessionOnShutdown(PWebRtcStreamingSession, UINT64, StreamSessionShutdownCallback); STATUS pregenerateCertTimerCallback(UINT32, UINT64, UINT64); STATUS removeExpiredMessageQueues(PStackQueue); STATUS getPendingMessageQueueForHash(PStackQueue, UINT64, BOOL, PPendingMessageQueue*); STATUS createWebRtcStreamingSession(PGstKvsPlugin, PCHAR, BOOL, PWebRtcStreamingSession*); STATUS initializePeerConnection(PGstKvsPlugin, PRtcPeerConnection*); VOID onIceCandidateHandler(UINT64, PCHAR); STATUS sendSignalingMessage(PWebRtcStreamingSession, PSignalingMessage); STATUS respondWithAnswer(PWebRtcStreamingSession); VOID onDataChannel(UINT64, PRtcDataChannel); VOID onDataChannelMessage(UINT64, PRtcDataChannel, BOOL, PBYTE, UINT32); VOID onConnectionStateChange(UINT64, RTC_PEER_CONNECTION_STATE); STATUS submitPendingIceCandidate(PPendingMessageQueue, PWebRtcStreamingSession); STATUS logSelectedIceCandidatesInformation(PWebRtcStreamingSession); STATUS handleRemoteCandidate(PWebRtcStreamingSession, PSignalingMessage); VOID sampleBandwidthEstimationHandler(UINT64, DOUBLE); STATUS handleOffer(PGstKvsPlugin, PWebRtcStreamingSession, PSignalingMessage); STATUS handleAnswer(PGstKvsPlugin, PWebRtcStreamingSession, PSignalingMessage); STATUS getIceCandidatePairStatsCallback(UINT32, UINT64, UINT64); PVOID receiveGstreamerAudioVideo(PVOID); VOID onGstAudioFrameReady(UINT64, PFrame); VOID onSampleStreamingSessionShutdown(UINT64, PWebRtcStreamingSession); STATUS sessionServiceHandler(UINT32, UINT64, UINT64); STATUS putFrameToWebRtcPeers(PGstKvsPlugin, PFrame, ELEMENTARY_STREAM_NAL_FORMAT); STATUS adaptVideoFrameFromAvccToAnnexB(PGstKvsPlugin, PFrame, ELEMENTARY_STREAM_NAL_FORMAT); #endif //__KVS_WEBRTC_FUNCTIONALITY_H__
56.135802
150
0.806466
ba326a034abca382e454bb687282d5650e20cb6a
930
swift
Swift
Pin.swift
vbrocket/Virtual-Tourist
5efe8f06f201b38c21ad304edb656c1c00d18848
[ "Unlicense" ]
1
2016-06-16T08:03:17.000Z
2016-06-16T08:03:17.000Z
Pin.swift
vbrocket/Virtual-Tourist
5efe8f06f201b38c21ad304edb656c1c00d18848
[ "Unlicense" ]
null
null
null
Pin.swift
vbrocket/Virtual-Tourist
5efe8f06f201b38c21ad304edb656c1c00d18848
[ "Unlicense" ]
null
null
null
// // Pin.swift // VirtualTourist // // Created by Ibrahim.Moustafa on 5/30/16. // Copyright © 2016 Ibrahim.Moustafa. All rights reserved. // import Foundation import CoreData class Pin: NSManagedObject { // In Swift, superclass initializers are not available to subclasses, so it is necessary to include this initializer and call the superclass' implementation of it. override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(lat: Double, long: Double, context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("Pin", inManagedObjectContext: context)! super.init(entity: entity, insertIntoManagedObjectContext: context) self.latitude = lat self.longitude = long self.pageCount = 0 } }
33.214286
167
0.717204
ffd1a6a9299f4ba32be4a5edc57849852e750ecc
1,056
a51
Assembly
LED Interfacing/Patterns/Pattern4.a51
dmdhrumilmistry/8051-Codes
f7c1051daddb17851befe0ebc959ecc444d6def9
[ "MIT" ]
null
null
null
LED Interfacing/Patterns/Pattern4.a51
dmdhrumilmistry/8051-Codes
f7c1051daddb17851befe0ebc959ecc444d6def9
[ "MIT" ]
null
null
null
LED Interfacing/Patterns/Pattern4.a51
dmdhrumilmistry/8051-Codes
f7c1051daddb17851befe0ebc959ecc444d6def9
[ "MIT" ]
null
null
null
// . . . . . . . . // 0 1 2 3 4 5 6 7 // PATTERN 4 ON PORT 2 // // . // . . // . . . // . . . . // . . . . . // . . . . . . // . . . . . . . // . . . . . . . . // . . . . . . . // . . . . . . // . . . . // . . . // . . // . // 0 1 2 3 4 5 6 7 ORG 0000H // MAIN PROGRAM REPEAT: MOV P2,#00H ACALL DELAY SETB P2.0 ACALL DELAY SETB P2.1 ACALL DELAY SETB P2.2 ACALL DELAY SETB P2.3 ACALL DELAY SETB P2.4 ACALL DELAY SETB P2.5 ACALL DELAY SETB P2.6 ACALL DELAY SETB P2.7 ACALL DELAY CLR P2.0 ACALL DELAY CLR P2.1 ACALL DELAY CLR P2.2 ACALL DELAY CLR P2.3 ACALL DELAY CLR P2.4 ACALL DELAY CLR P2.5 ACALL DELAY CLR P2.6 ACALL DELAY CLR P2.7 ACALL DELAY SJMP REPEAT // DELAY FOR 50MS DELAY: MOV TMOD,#10H MOV TL1,#0B0H MOV TH1,#3CH MOV TCON,#40H WAIT: JNB TF1, WAIT CLR TF1 CLR TR1 RET // DELAY 500MS = 0.5S DELAY500: MOV R7,#0AH BACK: ACALL DELAY DJNZ R1, BACK RET END
13.367089
22
0.465909
fa75e9117e534ec6e8c6b5dae4c83b9277ed8ae6
338
cpp
C++
Codeforces Online Judge Solve/68A - Irrational problem.cpp
Remonhasan/programming-solve
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
[ "Apache-2.0" ]
null
null
null
Codeforces Online Judge Solve/68A - Irrational problem.cpp
Remonhasan/programming-solve
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
[ "Apache-2.0" ]
null
null
null
Codeforces Online Judge Solve/68A - Irrational problem.cpp
Remonhasan/programming-solve
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
[ "Apache-2.0" ]
null
null
null
// Remon Hasan #include <iostream> #include <algorithm> using namespace std; int main() { int p[4], a, b; cin >> p[0] >> p[1] >> p[2] >> p[3] >> a >> b; int m = *min_element(p, p + 4); if (a < m) { cout << min(b, m - 1) - a + 1 << endl; } else { cout << 0 << endl; } return 0; }
14.695652
50
0.423077
58004b3bcc718375bf79890bac80e5864033e66f
1,196
css
CSS
archive-main/static/styles.css
cmlohr/library-rating
39c8d5c91bcef806d66d86c64fdbfcbaaf82e716
[ "MIT" ]
null
null
null
archive-main/static/styles.css
cmlohr/library-rating
39c8d5c91bcef806d66d86c64fdbfcbaaf82e716
[ "MIT" ]
null
null
null
archive-main/static/styles.css
cmlohr/library-rating
39c8d5c91bcef806d66d86c64fdbfcbaaf82e716
[ "MIT" ]
null
null
null
html, body { height: 100%; } html { display: table; margin: auto; } body { display: table-cell; vertical-align: middle; background-color: #30475e; color: #eeeeee; text-align: center; } .cust-align { text-align: right; } .front-btn { background-color: #191919; color: #eeeeee; } .front-btn:hover { background-color: #eeeeee; color: #191919; } .landing-title { text-decoration: underline #f05454; color: #e8e8e8; } .cust-field { color: #191919; } .landing-list { list-style-type: none; text-align: right; background: #222831; color: #e8e8e8; padding: 0; } .rating-btn { border-radius: 0; color: #191919; background-color: #dddddd; border: 1px solid #dddddd; } .rating-btn:hover { color: #dddddd; background-color: #191919; border: 1px solid #dddddd; } .dlt-btn { border-radius: 0; } .dlt-btn:hover { background-color: #191919; border: 1px solid #dddddd; } .add-form { background-color: #222831; padding: 10px; } .change-rating-btn { background-color: #111d5e; color: #eeeeee; } .change-rating-btn:hover { background-color: #eeeeee; color: #191919; }
17.085714
39
0.614548
7f0099474c83c98b032252f4caad23bdea46fa58
2,055
cs
C#
src/TilosPlayer.Library/ApiClient.cs
gemolnar/TilosPlayer-b
6b4cffafda2dc3a3d9b93c3baac8648e0136783a
[ "BSD-2-Clause" ]
null
null
null
src/TilosPlayer.Library/ApiClient.cs
gemolnar/TilosPlayer-b
6b4cffafda2dc3a3d9b93c3baac8648e0136783a
[ "BSD-2-Clause" ]
null
null
null
src/TilosPlayer.Library/ApiClient.cs
gemolnar/TilosPlayer-b
6b4cffafda2dc3a3d9b93c3baac8648e0136783a
[ "BSD-2-Clause" ]
null
null
null
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using TilosPlayer.Library.Domain; namespace TilosPlayer.Library { public class ApiClient { private const string API_ENDPOINT = "https://tilos.hu/api/v1/"; public async Task<Episode> GetEpisode(string episodeId) { var apiClient = new HttpClient(); apiClient.BaseAddress = new Uri(API_ENDPOINT); var response = await apiClient.GetAsync($"episode/{episodeId}"); var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<Episode>(responseContent); return result; } //public async Task<ShowDetails> GetShowDetails public async Task<Show[]> GetAllShows() { var apiClient = new HttpClient(); apiClient.BaseAddress = new Uri(API_ENDPOINT); var response = await apiClient.GetAsync("show?status=all"); var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<Show[]>(responseContent); return result; } public async Task<Episode[]> GetEpisodesByTimeRange(DateTimeOffset startDate, DateTimeOffset endDate) { var apiClient = new HttpClient(); apiClient.BaseAddress = new Uri(API_ENDPOINT); var requestUri = $"episode?start={startDate.ToUnixTimeMilliseconds()}&end={endDate.ToUnixTimeMilliseconds()}"; var response = await apiClient.GetAsync(requestUri); var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<Episode[]>(responseContent); return result; } public async Task<Episode[]> GetEpisodesFromLastWeek() { var apiClient = new HttpClient(); apiClient.BaseAddress = new Uri(API_ENDPOINT); var requestUri = $"episode/lastWeek"; var response = await apiClient.GetAsync(requestUri); var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<Episode[]>(responseContent); return result; } } }
29.782609
113
0.749392
3868ef5c6c8821328fae722f61183ebfc33e688f
4,381
php
PHP
app/Http/Controllers/ContactController.php
luiz8910/informatise
27525eeb241e393fa1c918db3e3793b69e3e7444
[ "MIT" ]
null
null
null
app/Http/Controllers/ContactController.php
luiz8910/informatise
27525eeb241e393fa1c918db3e3793b69e3e7444
[ "MIT" ]
null
null
null
app/Http/Controllers/ContactController.php
luiz8910/informatise
27525eeb241e393fa1c918db3e3793b69e3e7444
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use App\Mail\Contact; use App\Mail\Newsletter; use App\Repositories\CompanyDataRepository; use App\Repositories\ContactRepository; use App\Repositories\NewsletterRepository; use App\Repositories\UserRepository; use App\Traits\Config; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Mail; class ContactController extends Controller { use Config; /** * @var ContactRepository */ private $repository; /** * @var UserRepository */ private $users; /** * @var CompanyDataRepository */ private $data; public function __construct(ContactRepository $repository, UserRepository $users, CompanyDataRepository $data) { $this->repository = $repository; $this->users = $users; $this->data = $data; } public function index() { $contacts = $this->repository->orderBy('created_at', 'desc')->findByField('active', 1)->paginate(5); $route = 'contact.index'; return view('admin.index', compact('route', 'contacts')); } public function store(Request $request) { $data = $request->all(); DB::beginTransaction(); try { $this->repository->create($data); if($data['phone'] == "") $data['phone'] = false; else $data['raw_phone'] = $this->raw_phone($data['phone']); $email = $this->data->findByField('id', 1)->first()->email; Mail::to($email)->cc('luiz.sanches8910@gmail.com')->send(new Contact($data)); DB::commit(); return json_encode(['status' => true]); }catch (\Exception $e){ DB::rollBack(); return json_encode(['status' => false, 'msg' => 'Um erro ocorreu, tente novamente mais tarde']); } } public function company_data() { $links[] = '../../assets/lib/summernote/summernote.css'; $scripts[] = '../../assets/lib/summernote/summernote.min.js'; $scripts[] = '../../assets/lib/summernote/summernote-ext-beagle.js'; $scripts[] = '../../assets/lib/bootstrap-markdown/js/bootstrap-markdown.js'; $scripts[] = '../../assets/lib/markdown-js/markdown.js'; $scripts[] = '../../assets/js/app-form-wysiwyg.js'; $scripts[] = '../../js/mask.js'; $route = 'data.company_data'; $data = $this->data->findByField('id', 1)->first(); return view('admin.index', compact('data', 'route', 'scripts', 'links')); } public function company_data_update(Request $request) { $data = $request->all(); DB::beginTransaction(); try { $file = $request->file('file'); if($file) { $path = $file->store('public/uploads'); $data['picture'] = $path; } $this->data->update($data, 1); DB::commit(); $request->session()->flash('success.msg', 'As informações foram salvas'); }catch (\Exception $e){ DB::rollBack(); $request->session()->flash('error.msg', 'Um erro ocorreu'); } return redirect()->back(); } /*public function newsletters() { $news = $this->newsletter->orderBy('created_at', 'desc')->all(); $route = 'contact.newsletter'; return view('admin.index', compact('route', 'news')); } public function newsletter_store(Request $request) { $data = $request->all(); if($data['name'] == "") return json_encode(['status' => false, 'msg' => 'Preencha o campo nome']); if($data['email'] == "") return json_encode(['status' => false, 'msg' => 'Preencha o campo email']); DB::beginTransaction(); try{ $this->newsletter->create($data); $email = $this->data->findByField('id', 1)->first()->email; Mail::to($email)->cc('luiz.sanches8910@gmail.com')->send(new Newsletter($data)); DB::commit(); return json_encode(['status' => true]); }catch (\Exception $e) { DB::rollBack(); return json_encode(['status' => false, 'msg' => 'Um erro ocorreu, tente novamente mais tarde']); } }*/ }
25.770588
114
0.546679
8032e4afa26e26cf54a56974ffd531b2bcc6be6c
363
sql
SQL
v3.1/Database/dbo/Tables/ETunnels.sql
LightosLimited/RailML
df4439865ee55e828cf05b1082bf0197eb825cee
[ "Apache-2.0" ]
null
null
null
v3.1/Database/dbo/Tables/ETunnels.sql
LightosLimited/RailML
df4439865ee55e828cf05b1082bf0197eb825cee
[ "Apache-2.0" ]
null
null
null
v3.1/Database/dbo/Tables/ETunnels.sql
LightosLimited/RailML
df4439865ee55e828cf05b1082bf0197eb825cee
[ "Apache-2.0" ]
null
null
null
CREATE TABLE [dbo].[ETunnels] ( --From MergedXSDs XSD --From 'genericRailML' Namespace [ETunnelsId] BIGINT NOT NULL, [Tunnel] SMALLINT NOT NULL, CONSTRAINT [PK_ETunnelsId] PRIMARY KEY CLUSTERED ([ETunnelsId] ASC), CONSTRAINT [FK_ETunnels_ETunnel] FOREIGN KEY ([Tunnel]) REFERENCES [dbo].[ETunnel] ([ETunnelId]) --ON UPDATE CASCADE, ON DELETE CASCADE, );
33
137
0.738292