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
6eebba080578e8d8b3ac4f1702a906fc7a60b693
2,526
html
HTML
index.html
Simplon-Roubaix/Random-Herman-Dupont
4bdd067156a96bc21b524db2da580eb4d2206984
[ "MIT" ]
null
null
null
index.html
Simplon-Roubaix/Random-Herman-Dupont
4bdd067156a96bc21b524db2da580eb4d2206984
[ "MIT" ]
null
null
null
index.html
Simplon-Roubaix/Random-Herman-Dupont
4bdd067156a96bc21b524db2da580eb4d2206984
[ "MIT" ]
null
null
null
<!doctype html> <html lang="fr"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>RandomAvecMonBinome</title> <meta name="description" content="Le_jeu_du_Tu_dois_deviner_le_chiffre_que_l_ordinateur_va_sortir!"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <!-- Place favicon.ico in the root directory --> <link rel="icon" href="favicon.png" /> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="bootstrap.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/modernizr-2.8.3.min.js"></script> <script src="js/bootstrap.js"></script> </head> <body> <!--[if lt IE 8]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div class="container"> <p> Trouvez le chiffre sorti par l'ordinateur : il est compris entre 1 et 10 ! <!-- si on choisit le chiffre entre 0 et ..., si entre 0 et ... retirer le +1 en js dans le math.random --> </p> <input type="text" id="userChoice" placeholder="Saisir un nombre compris entre 0 et 10" size="40%" onkeypress="if(event.keyCode==13){pcRandom()}" /> <button id="button">Vérification</button> <p><u>Résultat : </u></p> <p id="result"> </p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>') </script> <script src="js/plugins.js"></script> <script src="js/main.js"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> (function(b, o, i, l, e, r) { b.GoogleAnalyticsObject = l; b[l] || (b[l] = function() { (b[l].q = b[l].q || []).push(arguments) }); b[l].l = +new Date; e = o.createElement(i); r = o.getElementsByTagName(i)[0]; e.src = 'https://www.google-analytics.com/analytics.js'; r.parentNode.insertBefore(e, r) }(window, document, 'script', 'ga')); ga('create', 'UA-XXXXX-X', 'auto'); ga('send', 'pageview'); </script> </body> </html>
36.608696
183
0.582344
7ae55d0de531ec1760c2b718c59c91c5c7252983
1,606
rs
Rust
src/lib.rs
nuclearfurnace/deadpool-memcached
23bfb837f5b3d21e511339b8933a723dc71fa86d
[ "Apache-2.0", "MIT" ]
1
2020-08-20T13:48:36.000Z
2020-08-20T13:48:36.000Z
src/lib.rs
nuclearfurnace/deadpool-memcached
23bfb837f5b3d21e511339b8933a723dc71fa86d
[ "Apache-2.0", "MIT" ]
null
null
null
src/lib.rs
nuclearfurnace/deadpool-memcached
23bfb837f5b3d21e511339b8933a723dc71fa86d
[ "Apache-2.0", "MIT" ]
null
null
null
//! # Deadpool for Memcache //! //! Deadpool is a dead simple async pool for connections and objects of any type. //! //! This crate implements a [`deadpool`](https://crates.io/crates/deadpool) manager for //! [`async-memcached`](https://crates.io/crates/async-memcached). We specifically force users to //! connect via TCP as there is no existing mechanism to parameterize how to deal with different //! unerlying connection types at the moment. #![deny(warnings, missing_docs)] use async_memcached::{Client, Error}; use async_trait::async_trait; /// A type alias for using `deadpool::Pool` with `async-memcached` pub type Pool = deadpool::managed::Pool<Client, Error>; /// A type alias for using `deadpool::PoolError` with `async-memcached` pub type PoolError = deadpool::managed::PoolError<Error>; /// A type alias for using `deadpool::Object` with `async-memcached` pub type Connection = deadpool::managed::Object<Client, Error>; type RecycleResult = deadpool::managed::RecycleResult<Error>; /// The manager for creating and recyling memcache connections pub struct Manager { addr: String, } impl Manager { /// Create a new manager for the given address. pub fn new(addr: String) -> Self { Self { addr } } } #[async_trait] impl deadpool::managed::Manager<Client, Error> for Manager { async fn create(&self) -> Result<Client, Error> { Client::new(&self.addr).await } async fn recycle(&self, conn: &mut Client) -> RecycleResult { match conn.version().await { Ok(_) => Ok(()), Err(e) => Err(e.into()), } } }
32.77551
98
0.681818
e8e431aaa0e0c0342df0906099d3bfe584c4dc40
262
py
Python
MUNDO 1/ex023.py
athavus/Curso-em-video-Python-3
a32be95adbccfcbe512a1ed30d3859141a230b5e
[ "MIT" ]
1
2020-11-12T14:03:32.000Z
2020-11-12T14:03:32.000Z
MUNDO 1/ex023.py
athavus/Curso-em-video-Python-3
a32be95adbccfcbe512a1ed30d3859141a230b5e
[ "MIT" ]
null
null
null
MUNDO 1/ex023.py
athavus/Curso-em-video-Python-3
a32be95adbccfcbe512a1ed30d3859141a230b5e
[ "MIT" ]
1
2021-01-05T22:18:46.000Z
2021-01-05T22:18:46.000Z
n1 = int(input('Digite um número entre 0 e 9999: ')) u = n1 // 1 % 10 d = n1 // 10 % 10 c = n1 // 100 % 10 m = n1 // 1000 % 10 print(f'Analisando o número {n1}') print(f'unidade: {u}') print(f'dezena: {d}') print(f'centena: {c}') print(f'milhar: {m}')
23.818182
53
0.549618
d2d3a0f21a33c97da8c9eb7f83fe02d60b8074b5
1,066
kt
Kotlin
app/src/main/java/com/example/mercadofacil/DebugActivity.kt
tr0v40/ACS--FERNANDO
b593021c7558c89e4a8426e87a4ea33679aa751f
[ "MIT" ]
null
null
null
app/src/main/java/com/example/mercadofacil/DebugActivity.kt
tr0v40/ACS--FERNANDO
b593021c7558c89e4a8426e87a4ea33679aa751f
[ "MIT" ]
null
null
null
app/src/main/java/com/example/mercadofacil/DebugActivity.kt
tr0v40/ACS--FERNANDO
b593021c7558c89e4a8426e87a4ea33679aa751f
[ "MIT" ]
null
null
null
package com.example.mercadofacil import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log open class DebugActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } private val TAG = "MercadoFacil" private val className: String get(){ val s = javaClass.name return s.substring(s.lastIndexOf(".")) } override fun onStart() { super.onStart() Log.d(TAG, ".onStart() chamado") } override fun onRestart() { super.onRestart() Log.d(TAG, ".onRestart() chamado") } override fun onResume() { super.onResume() Log.d(TAG, ".onResume() chamado") } override fun onPause() { super.onPause() Log.d(TAG, ".onPause() chamado") } override fun onStop() { super.onStop() Log.d(TAG, ".onStop() chamado") } override fun onDestroy() { super.onDestroy() Log.d(TAG, ".onDestroy() chamado") } }
24.227273
56
0.601313
1a1e10a234449c05de61ea768b396f6ce7cba30e
497
kt
Kotlin
fints4k/src/commonMain/kotlin/net/dankito/banking/fints/messages/datenelemente/implementierte/tan/TanMedienArtVersion.kt
codinux-gmbh/fints4k.BAK
b4232dffd35346883ad02b220d420c46af83e815
[ "RSA-MD" ]
null
null
null
fints4k/src/commonMain/kotlin/net/dankito/banking/fints/messages/datenelemente/implementierte/tan/TanMedienArtVersion.kt
codinux-gmbh/fints4k.BAK
b4232dffd35346883ad02b220d420c46af83e815
[ "RSA-MD" ]
null
null
null
fints4k/src/commonMain/kotlin/net/dankito/banking/fints/messages/datenelemente/implementierte/tan/TanMedienArtVersion.kt
codinux-gmbh/fints4k.BAK
b4232dffd35346883ad02b220d420c46af83e815
[ "RSA-MD" ]
null
null
null
package net.dankito.banking.fints.messages.datenelemente.implementierte.tan import net.dankito.banking.fints.messages.datenelemente.implementierte.ICodeEnum /** * dient der Klassifizierung der gesamten dem Kunden zugeordneten TAN-Medien. Bei * Geschäftsvorfällen zum Management des TAN-Generators kann aus diesen nach folgender * Codierung selektiert werden. */ enum class TanMedienArtVersion(override val code: String) : ICodeEnum { Alle("0"), Aktiv("1"), Verfuegbar("2") }
26.157895
86
0.772636
af45f02ff827e03f8c2b6f7cdff455e782e54e90
1,244
rb
Ruby
sassy-contour.rb
kiafaldorius/sassy-contour
6c6ed65904bded6ec3a2041bccfadf95e6641a70
[ "MIT" ]
null
null
null
sassy-contour.rb
kiafaldorius/sassy-contour
6c6ed65904bded6ec3a2041bccfadf95e6641a70
[ "MIT" ]
null
null
null
sassy-contour.rb
kiafaldorius/sassy-contour
6c6ed65904bded6ec3a2041bccfadf95e6641a70
[ "MIT" ]
null
null
null
require 'haml' require 'sass' require 'coffee-script' require 'sinatra' require 'bootstrap-sass' require_relative 'app/helpers/template_helper' helpers TemplateHelper # The root path is special. It's not treated as a page because: # a) it would result in an empty symbol name for the template (works, but weird) # b) the file path would be views/pages/.haml (treated as hidden file in *nix) # c) unlike other pages, it should always exist # # It is possible to treat it like the other pages if the notes mentioned above # are acceptable. However, it's cleaner this way. get '/' do haml :index end # This is also available under sprockets get '/css/*.css' do |path| content_type :css if template = template_from_path('styles', path, '.sass') sass template, :style => :expanded elsif template = template_from_path('styles', path, '.scss') scss template, :style => :expanded else pass end end # This is also available under sprockets get '/js/*.js' do |path| content_type :js if template = template_from_path('scripts', path, '.coffee') coffee template else pass end end get '/*' do |path| if template = template_from_path('pages', path, '.haml') haml template else pass end end
23.037037
80
0.70418
3e9719948a8e7817658496929115fe52bda45473
14,370
c
C
kernels/linux-2.6.24/drivers/firewire/fw-card.c
liuhaozzu/linux
bdf9758cd23e34b5f53e8e6339d9b29348615e14
[ "Apache-2.0" ]
null
null
null
kernels/linux-2.6.24/drivers/firewire/fw-card.c
liuhaozzu/linux
bdf9758cd23e34b5f53e8e6339d9b29348615e14
[ "Apache-2.0" ]
1
2021-04-09T09:24:44.000Z
2021-04-09T09:24:44.000Z
drivers/firewire/fw-card.c
KylinskyChen/linuxCore_2.6.24
11e90b14386491cc80477d4015e0c8f673f6d020
[ "MIT" ]
null
null
null
/* * Copyright (C) 2005-2007 Kristian Hoegsberg <krh@bitplanet.net> * * 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 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <linux/module.h> #include <linux/errno.h> #include <linux/device.h> #include <linux/mutex.h> #include <linux/crc-itu-t.h> #include "fw-transaction.h" #include "fw-topology.h" #include "fw-device.h" int fw_compute_block_crc(u32 *block) { __be32 be32_block[256]; int i, length; length = (*block >> 16) & 0xff; for (i = 0; i < length; i++) be32_block[i] = cpu_to_be32(block[i + 1]); *block |= crc_itu_t(0, (u8 *) be32_block, length * 4); return length; } static DEFINE_MUTEX(card_mutex); static LIST_HEAD(card_list); static LIST_HEAD(descriptor_list); static int descriptor_count; #define BIB_CRC(v) ((v) << 0) #define BIB_CRC_LENGTH(v) ((v) << 16) #define BIB_INFO_LENGTH(v) ((v) << 24) #define BIB_LINK_SPEED(v) ((v) << 0) #define BIB_GENERATION(v) ((v) << 4) #define BIB_MAX_ROM(v) ((v) << 8) #define BIB_MAX_RECEIVE(v) ((v) << 12) #define BIB_CYC_CLK_ACC(v) ((v) << 16) #define BIB_PMC ((1) << 27) #define BIB_BMC ((1) << 28) #define BIB_ISC ((1) << 29) #define BIB_CMC ((1) << 30) #define BIB_IMC ((1) << 31) static u32 * generate_config_rom(struct fw_card *card, size_t *config_rom_length) { struct fw_descriptor *desc; static u32 config_rom[256]; int i, j, length; /* * Initialize contents of config rom buffer. On the OHCI * controller, block reads to the config rom accesses the host * memory, but quadlet read access the hardware bus info block * registers. That's just crack, but it means we should make * sure the contents of bus info block in host memory mathces * the version stored in the OHCI registers. */ memset(config_rom, 0, sizeof(config_rom)); config_rom[0] = BIB_CRC_LENGTH(4) | BIB_INFO_LENGTH(4) | BIB_CRC(0); config_rom[1] = 0x31333934; config_rom[2] = BIB_LINK_SPEED(card->link_speed) | BIB_GENERATION(card->config_rom_generation++ % 14 + 2) | BIB_MAX_ROM(2) | BIB_MAX_RECEIVE(card->max_receive) | BIB_BMC | BIB_ISC | BIB_CMC | BIB_IMC; config_rom[3] = card->guid >> 32; config_rom[4] = card->guid; /* Generate root directory. */ i = 5; config_rom[i++] = 0; config_rom[i++] = 0x0c0083c0; /* node capabilities */ j = i + descriptor_count; /* Generate root directory entries for descriptors. */ list_for_each_entry (desc, &descriptor_list, link) { if (desc->immediate > 0) config_rom[i++] = desc->immediate; config_rom[i] = desc->key | (j - i); i++; j += desc->length; } /* Update root directory length. */ config_rom[5] = (i - 5 - 1) << 16; /* End of root directory, now copy in descriptors. */ list_for_each_entry (desc, &descriptor_list, link) { memcpy(&config_rom[i], desc->data, desc->length * 4); i += desc->length; } /* Calculate CRCs for all blocks in the config rom. This * assumes that CRC length and info length are identical for * the bus info block, which is always the case for this * implementation. */ for (i = 0; i < j; i += length + 1) length = fw_compute_block_crc(config_rom + i); *config_rom_length = j; return config_rom; } static void update_config_roms(void) { struct fw_card *card; u32 *config_rom; size_t length; list_for_each_entry (card, &card_list, link) { config_rom = generate_config_rom(card, &length); card->driver->set_config_rom(card, config_rom, length); } } int fw_core_add_descriptor(struct fw_descriptor *desc) { size_t i; /* * Check descriptor is valid; the length of all blocks in the * descriptor has to add up to exactly the length of the * block. */ i = 0; while (i < desc->length) i += (desc->data[i] >> 16) + 1; if (i != desc->length) return -EINVAL; mutex_lock(&card_mutex); list_add_tail(&desc->link, &descriptor_list); descriptor_count++; if (desc->immediate > 0) descriptor_count++; update_config_roms(); mutex_unlock(&card_mutex); return 0; } EXPORT_SYMBOL(fw_core_add_descriptor); void fw_core_remove_descriptor(struct fw_descriptor *desc) { mutex_lock(&card_mutex); list_del(&desc->link); descriptor_count--; if (desc->immediate > 0) descriptor_count--; update_config_roms(); mutex_unlock(&card_mutex); } EXPORT_SYMBOL(fw_core_remove_descriptor); static const char gap_count_table[] = { 63, 5, 7, 8, 10, 13, 16, 18, 21, 24, 26, 29, 32, 35, 37, 40 }; struct bm_data { struct fw_transaction t; struct { __be32 arg; __be32 data; } lock; u32 old; int rcode; struct completion done; }; static void complete_bm_lock(struct fw_card *card, int rcode, void *payload, size_t length, void *data) { struct bm_data *bmd = data; if (rcode == RCODE_COMPLETE) bmd->old = be32_to_cpu(*(__be32 *) payload); bmd->rcode = rcode; complete(&bmd->done); } static void fw_card_bm_work(struct work_struct *work) { struct fw_card *card = container_of(work, struct fw_card, work.work); struct fw_device *root; struct bm_data bmd; unsigned long flags; int root_id, new_root_id, irm_id, gap_count, generation, grace; int do_reset = 0; spin_lock_irqsave(&card->lock, flags); generation = card->generation; root = card->root_node->data; root_id = card->root_node->node_id; grace = time_after(jiffies, card->reset_jiffies + DIV_ROUND_UP(HZ, 10)); if (card->bm_generation + 1 == generation || (card->bm_generation != generation && grace)) { /* * This first step is to figure out who is IRM and * then try to become bus manager. If the IRM is not * well defined (e.g. does not have an active link * layer or does not responds to our lock request, we * will have to do a little vigilante bus management. * In that case, we do a goto into the gap count logic * so that when we do the reset, we still optimize the * gap count. That could well save a reset in the * next generation. */ irm_id = card->irm_node->node_id; if (!card->irm_node->link_on) { new_root_id = card->local_node->node_id; fw_notify("IRM has link off, making local node (%02x) root.\n", new_root_id); goto pick_me; } bmd.lock.arg = cpu_to_be32(0x3f); bmd.lock.data = cpu_to_be32(card->local_node->node_id); spin_unlock_irqrestore(&card->lock, flags); init_completion(&bmd.done); fw_send_request(card, &bmd.t, TCODE_LOCK_COMPARE_SWAP, irm_id, generation, SCODE_100, CSR_REGISTER_BASE + CSR_BUS_MANAGER_ID, &bmd.lock, sizeof(bmd.lock), complete_bm_lock, &bmd); wait_for_completion(&bmd.done); if (bmd.rcode == RCODE_GENERATION) { /* * Another bus reset happened. Just return, * the BM work has been rescheduled. */ return; } if (bmd.rcode == RCODE_COMPLETE && bmd.old != 0x3f) /* Somebody else is BM, let them do the work. */ return; spin_lock_irqsave(&card->lock, flags); if (bmd.rcode != RCODE_COMPLETE) { /* * The lock request failed, maybe the IRM * isn't really IRM capable after all. Let's * do a bus reset and pick the local node as * root, and thus, IRM. */ new_root_id = card->local_node->node_id; fw_notify("BM lock failed, making local node (%02x) root.\n", new_root_id); goto pick_me; } } else if (card->bm_generation != generation) { /* * OK, we weren't BM in the last generation, and it's * less than 100ms since last bus reset. Reschedule * this task 100ms from now. */ spin_unlock_irqrestore(&card->lock, flags); schedule_delayed_work(&card->work, DIV_ROUND_UP(HZ, 10)); return; } /* * We're bus manager for this generation, so next step is to * make sure we have an active cycle master and do gap count * optimization. */ card->bm_generation = generation; if (root == NULL) { /* * Either link_on is false, or we failed to read the * config rom. In either case, pick another root. */ new_root_id = card->local_node->node_id; } else if (atomic_read(&root->state) != FW_DEVICE_RUNNING) { /* * If we haven't probed this device yet, bail out now * and let's try again once that's done. */ spin_unlock_irqrestore(&card->lock, flags); return; } else if (root->config_rom[2] & BIB_CMC) { /* * FIXME: I suppose we should set the cmstr bit in the * STATE_CLEAR register of this node, as described in * 1394-1995, 8.4.2.6. Also, send out a force root * packet for this node. */ new_root_id = root_id; } else { /* * Current root has an active link layer and we * successfully read the config rom, but it's not * cycle master capable. */ new_root_id = card->local_node->node_id; } pick_me: /* * Pick a gap count from 1394a table E-1. The table doesn't cover * the typically much larger 1394b beta repeater delays though. */ if (!card->beta_repeaters_present && card->root_node->max_hops < ARRAY_SIZE(gap_count_table)) gap_count = gap_count_table[card->root_node->max_hops]; else gap_count = 63; /* * Finally, figure out if we should do a reset or not. If we've * done less that 5 resets with the same physical topology and we * have either a new root or a new gap count setting, let's do it. */ if (card->bm_retries++ < 5 && (card->gap_count != gap_count || new_root_id != root_id)) do_reset = 1; spin_unlock_irqrestore(&card->lock, flags); if (do_reset) { fw_notify("phy config: card %d, new root=%x, gap_count=%d\n", card->index, new_root_id, gap_count); fw_send_phy_config(card, new_root_id, generation, gap_count); fw_core_initiate_bus_reset(card, 1); } } static void flush_timer_callback(unsigned long data) { struct fw_card *card = (struct fw_card *)data; fw_flush_transactions(card); } void fw_card_initialize(struct fw_card *card, const struct fw_card_driver *driver, struct device *device) { static atomic_t index = ATOMIC_INIT(-1); kref_init(&card->kref); card->index = atomic_inc_return(&index); card->driver = driver; card->device = device; card->current_tlabel = 0; card->tlabel_mask = 0; card->color = 0; INIT_LIST_HEAD(&card->transaction_list); spin_lock_init(&card->lock); setup_timer(&card->flush_timer, flush_timer_callback, (unsigned long)card); card->local_node = NULL; INIT_DELAYED_WORK(&card->work, fw_card_bm_work); } EXPORT_SYMBOL(fw_card_initialize); int fw_card_add(struct fw_card *card, u32 max_receive, u32 link_speed, u64 guid) { u32 *config_rom; size_t length; card->max_receive = max_receive; card->link_speed = link_speed; card->guid = guid; /* * The subsystem grabs a reference when the card is added and * drops it when the driver calls fw_core_remove_card. */ fw_card_get(card); mutex_lock(&card_mutex); config_rom = generate_config_rom(card, &length); list_add_tail(&card->link, &card_list); mutex_unlock(&card_mutex); return card->driver->enable(card, config_rom, length); } EXPORT_SYMBOL(fw_card_add); /* * The next few functions implements a dummy driver that use once a * card driver shuts down an fw_card. This allows the driver to * cleanly unload, as all IO to the card will be handled by the dummy * driver instead of calling into the (possibly) unloaded module. The * dummy driver just fails all IO. */ static int dummy_enable(struct fw_card *card, u32 *config_rom, size_t length) { BUG(); return -1; } static int dummy_update_phy_reg(struct fw_card *card, int address, int clear_bits, int set_bits) { return -ENODEV; } static int dummy_set_config_rom(struct fw_card *card, u32 *config_rom, size_t length) { /* * We take the card out of card_list before setting the dummy * driver, so this should never get called. */ BUG(); return -1; } static void dummy_send_request(struct fw_card *card, struct fw_packet *packet) { packet->callback(packet, card, -ENODEV); } static void dummy_send_response(struct fw_card *card, struct fw_packet *packet) { packet->callback(packet, card, -ENODEV); } static int dummy_cancel_packet(struct fw_card *card, struct fw_packet *packet) { return -ENOENT; } static int dummy_enable_phys_dma(struct fw_card *card, int node_id, int generation) { return -ENODEV; } static struct fw_card_driver dummy_driver = { .name = "dummy", .enable = dummy_enable, .update_phy_reg = dummy_update_phy_reg, .set_config_rom = dummy_set_config_rom, .send_request = dummy_send_request, .cancel_packet = dummy_cancel_packet, .send_response = dummy_send_response, .enable_phys_dma = dummy_enable_phys_dma, }; void fw_core_remove_card(struct fw_card *card) { card->driver->update_phy_reg(card, 4, PHY_LINK_ACTIVE | PHY_CONTENDER, 0); fw_core_initiate_bus_reset(card, 1); mutex_lock(&card_mutex); list_del(&card->link); mutex_unlock(&card_mutex); /* Set up the dummy driver. */ card->driver = &dummy_driver; fw_destroy_nodes(card); flush_scheduled_work(); fw_flush_transactions(card); del_timer_sync(&card->flush_timer); fw_card_put(card); } EXPORT_SYMBOL(fw_core_remove_card); struct fw_card * fw_card_get(struct fw_card *card) { kref_get(&card->kref); return card; } EXPORT_SYMBOL(fw_card_get); static void release_card(struct kref *kref) { struct fw_card *card = container_of(kref, struct fw_card, kref); kfree(card); } /* * An assumption for fw_card_put() is that the card driver allocates * the fw_card struct with kalloc and that it has been shut down * before the last ref is dropped. */ void fw_card_put(struct fw_card *card) { kref_put(&card->kref, release_card); } EXPORT_SYMBOL(fw_card_put); int fw_core_initiate_bus_reset(struct fw_card *card, int short_reset) { int reg = short_reset ? 5 : 1; int bit = short_reset ? PHY_BUS_SHORT_RESET : PHY_BUS_RESET; return card->driver->update_phy_reg(card, reg, 0, bit); } EXPORT_SYMBOL(fw_core_initiate_bus_reset);
25.614973
77
0.700905
c12f4567f9bd51ee93242bab99b6ae983845a057
779
rs
Rust
examples/client_http2.rs
nox/hyper
45ec6fd8841786b2625e7240507a967bd27a6050
[ "MIT" ]
1
2015-11-26T13:45:36.000Z
2015-11-26T13:45:36.000Z
examples/client_http2.rs
nox/hyper
45ec6fd8841786b2625e7240507a967bd27a6050
[ "MIT" ]
null
null
null
examples/client_http2.rs
nox/hyper
45ec6fd8841786b2625e7240507a967bd27a6050
[ "MIT" ]
null
null
null
#![deny(warnings)] extern crate hyper; extern crate env_logger; use std::env; use std::io; use hyper::Client; use hyper::header::Connection; use hyper::http::h2; fn main() { env_logger::init().unwrap(); let url = match env::args().nth(1) { Some(url) => url, None => { println!("Usage: client <url>"); return; } }; let client = Client::with_protocol(h2::new_protocol()); // `Connection: Close` is not a valid header for HTTP/2, but the client handles it gracefully. let mut res = client.get(&*url) .header(Connection::close()) .send().unwrap(); println!("Response: {}", res.status); println!("Headers:\n{}", res.headers); io::copy(&mut res, &mut io::stdout()).unwrap(); }
22.257143
98
0.577664
dda7923943000c76edf0dcb131f6b8ec96f3358b
102
sql
SQL
backend/de.metas.fresh/de.metas.fresh.base/src/main/sql/postgresql/system/70-de.metas.fresh/5426855_sys_09320_update_orginfo_ReportPrefix.sql
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
1,144
2016-02-14T10:29:35.000Z
2022-03-30T09:50:41.000Z
backend/de.metas.fresh/de.metas.fresh.base/src/main/sql/postgresql/system/70-de.metas.fresh/5426855_sys_09320_update_orginfo_ReportPrefix.sql
vestigegroup/metasfresh
4b2d48c091fb2a73e6f186260a06c715f5e2fe96
[ "RSA-MD" ]
8,283
2016-04-28T17:41:34.000Z
2022-03-30T13:30:12.000Z
backend/de.metas.fresh/de.metas.fresh.base/src/main/sql/postgresql/system/70-de.metas.fresh/5426855_sys_09320_update_orginfo_ReportPrefix.sql
vestigegroup/metasfresh
4b2d48c091fb2a73e6f186260a06c715f5e2fe96
[ "RSA-MD" ]
441
2016-04-29T08:06:07.000Z
2022-03-28T06:09:56.000Z
UPDATE ad_orginfo SET ReportPrefix='file:////opt/metasfresh/jboss/server/adempiere/deploy/reports.war'
102
102
0.823529
1186c68a6703bb69e12830b9a5598ff2af7ad9a3
6,472
rs
Rust
src/graphic_button.rs
GuillaumeGomez/rust-music-player
40b97b3433e6e813d63bf6f16a598660fd58b123
[ "Apache-2.0" ]
24
2015-02-02T14:15:42.000Z
2021-05-18T01:10:09.000Z
src/graphic_button.rs
GuillaumeGomez/rust-music-player
40b97b3433e6e813d63bf6f16a598660fd58b123
[ "Apache-2.0" ]
5
2017-02-14T17:07:15.000Z
2021-07-15T07:54:34.000Z
src/graphic_button.rs
GuillaumeGomez/rust-music-player
40b97b3433e6e813d63bf6f16a598660fd58b123
[ "Apache-2.0" ]
5
2018-03-28T09:25:35.000Z
2020-03-11T11:41:17.000Z
/* * Rust-music-player - Copyright (c) 2014 Gomez Guillaume. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim * that you wrote the original software. If you use this software in a product, * an acknowledgment in the product documentation would be appreciated but is * not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #![allow(dead_code)] #![allow(unused_variables)] use graphic_element::GraphicElement; use sfml::graphics::Shape; use sfml::graphics::Transformable; use sfml::graphics::{Color, Font, RectangleShape, RenderTarget, RenderWindow, Text}; use sfml::system::Vector2f; pub struct GraphicButton<'b> { label: Text<'b>, button: RectangleShape<'b>, need_to_draw: bool, pushed: bool, has_mouse: bool, name: String, } impl<'b> GraphicButton<'b> { fn init(mut self, position: &Vector2f) -> GraphicButton<'b> { self.set_position(position); self.button.set_fill_color(&Color::rgb(10, 10, 10)); self.button.set_outline_color(&Color::rgb(255, 255, 255)); self.button.set_outline_thickness(1f32); self } pub fn set_label(&mut self, label: &String) { if label != &self.label.string() { self.label.set_string(&label); let size = self.label.local_bounds().width; self.label.set_position(Vector2f { x: (self.button.size().x - 1f32 - size as f32) / 2f32 + self.button.position().x as f32, y: self.button.position().y + (self.button.size().y - 20f32) / 2f32 - 2f32, }); self.need_to_draw = true; } } pub fn is_pushed(&self) -> bool { self.pushed } pub fn set_pushed(&mut self, pushed: bool) { if self.pushed != pushed { self.pushed = pushed; if self.pushed { self.button.set_fill_color(&Color::rgb(205, 187, 100)); } else { self.button.set_fill_color(&Color::rgb(10, 10, 10)); } self.need_to_draw = true; } } } impl<'b> GraphicElement<'b> for GraphicButton<'b> { fn new_init( size: &Vector2f, position: &Vector2f, unused: &Color, font: Option<&'b Font>, ) -> GraphicButton<'b> { GraphicButton { label: Text::new("", &font.clone().unwrap(), 20), button: RectangleShape::with_size(Vector2f { x: size.x as f32 - 2f32, y: size.y as f32 - 2f32, }), need_to_draw: true, pushed: false, has_mouse: false, name: String::new(), }.init(position) } fn cursor_moved(&mut self, position: &Vector2f) { if !self.has_mouse { let tmp = self.button.size(); let pos = self.button.position(); self.button.set_outline_thickness(2f32); self.button.set_size(Vector2f { x: tmp.x - 2f32, y: tmp.y - 2f32, }); self.button.set_position(Vector2f { x: pos.x + 1f32, y: pos.y + 1f32, }); self.need_to_draw = true; self.has_mouse = true; } } fn clicked(&mut self, position: &Vector2f) { if self.pushed { self.set_pushed(false) } else { self.set_pushed(true) } } fn draw(&mut self, win: &mut RenderWindow) { win.draw(&self.button); win.draw(&self.label); self.need_to_draw = false; } fn set_position(&mut self, position: &Vector2f) { let size = self.label.local_bounds().width; self.button.set_position(Vector2f { x: position.x + 1f32, y: position.y + 1f32, }); self.label.set_position(Vector2f { x: (self.button.size().x - 1f32 - size as f32) / 2f32 + self.button.position().x, y: self.button.position().y + (self.button.size().y - 20f32) / 2f32 - 2f32, }); self.need_to_draw = true; } fn get_position(&self) -> Vector2f { let tmp = self.button.position(); Vector2f { x: tmp.x - 1f32, y: tmp.y - 1f32, } } fn set_size(&mut self, size: &Vector2f) { let tmp = self.button.position(); self.button.set_size(Vector2f { x: size.x as f32 - 2f32, y: size.y as f32 - 2f32, }); self.set_position(&tmp); } fn get_size(&self) -> Vector2f { let tmp = self.button.size(); Vector2f { x: tmp.x + 2f32, y: tmp.y + 2f32, } } fn get_min_size(&self) -> Vector2f { Vector2f { x: 100f32, y: 40f32, } } fn get_max_size(&self) -> Option<Vector2f> { None } fn is_inside(&self, pos: &Vector2f) -> bool { pos.y >= self.button.position().y && pos.y <= self.button.position().y + self.button.size().y && pos.x >= self.button.position().x && pos.x <= self.button.position().x + self.button.size().x } fn mouse_leave(&mut self) { if self.has_mouse { let tmp = self.button.size(); let pos = self.button.position(); self.button.set_outline_thickness(1f32); self.button.set_size(Vector2f { x: tmp.x + 2f32, y: tmp.y + 2f32, }); self.button.set_position(Vector2f { x: pos.x - 1f32, y: pos.y - 1f32, }); self.need_to_draw = true; self.has_mouse = false; } } fn set_element_name(&mut self, name: &String) { self.name = name.clone(); } fn get_element_name<'a>(&'a self) -> &'a String { &self.name } }
29.418182
93
0.544499
0bf81f379dccf0e7750ed1817fffd697540730b8
8,681
js
JavaScript
src/js/container/Menu.js
tpucci/jobads-webapp
ac1d771e981bd2473e90369909be2342d3c3b1b1
[ "MIT" ]
null
null
null
src/js/container/Menu.js
tpucci/jobads-webapp
ac1d771e981bd2473e90369909be2342d3c3b1b1
[ "MIT" ]
1
2017-02-15T15:38:59.000Z
2017-02-16T13:32:04.000Z
src/js/container/Menu.js
tpucci/jobads-webapp
ac1d771e981bd2473e90369909be2342d3c3b1b1
[ "MIT" ]
2
2017-05-30T09:48:28.000Z
2020-01-22T12:25:11.000Z
import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import {greenA400, grey500, grey300} from 'material-ui/styles/colors'; import Drawer from 'material-ui/Drawer'; import AppBar from 'material-ui/AppBar'; import MenuItem from 'material-ui/MenuItem'; import {primary700, accentA200, accentA400, accentA100} from '../colors'; import IconButton from 'material-ui/IconButton'; import Subheader from 'material-ui/Subheader'; import {Tabs, Tab} from 'material-ui/Tabs'; import SelectField from 'material-ui/SelectField'; import { hashHistory } from 'react-router'; import LogoIcon from './Logo'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; import Help from 'material-ui/svg-icons/communication/live-help'; import Github from 'mdi-svg/d/github'; import SvgIcon from 'material-ui/SvgIcon'; const styles = { tabItemContainer : { background: 'none' }, selectField: { alignSelf: 'center', marginLeft: 25, marginRight: 25, }, separator: { flex: "1 1 0", }, menuStyle: { color: "white", lineHeight: "32px", paddingLeft: 8, paddingRight: 8, borderRadius: 5, marginTop: 10, marginBottom: 10, border: "2px solid rgba(255,255,255,.5)" }, menuStyleScrolled: { color: grey500, lineHeight: "32px", paddingLeft: 8, paddingRight: 8, borderRadius: 5, marginTop: 11, marginBottom: 11, borderWidth: 1, borderStyle: "solid", borderColor: grey300 }, titleStyle : { flex: "0 0 auto", }, underline: { display: 'none' }, selectedMenuItem: { color: greenA400 }, tabTemplate: { }, tabTemplateScrolled: { color: grey500 }, inkBar: { background: greenA400 } }; const tabs = [ {label: "Aide", location: "aide"}, {label: "A propos", location: "a-propos"}, ]; const menuItems = [ {text: "Accueil", value: "accueil"}, {text: "Emplois et stages", value: "rechercher"}, ]; let inertiaTrigger = 30; let appBarHeight = 64; let handleClose = () => {return 1;} export default class Menu extends React.Component { constructor(props) { super(props); this.state = { open: false, value: null, altLocation: false, translateY: 0 }; } _handleTabChange = (value) => { this.setState({ altLocation: value, open: true, }); document.body.className = (window.innerWidth < 1200) ? "body pushed" : "body pushed600"; }; _handleSelectFieldChange = (event, index, value) => { this.setState({value}); if (this.state.value != value) hashHistory.push(value); } componentWillMount () { handleClose = () => { this.setState({open: false, altLocation: false}); document.body.className = "body"; }; let path = this.props.location.replace(/^\/([^\/]*).*$/, '$1'); if (path == '') path = 'rechercher'; this.setState({value: path}); } componentWillReceiveProps(nextProps){ if (nextProps.inertia > inertiaTrigger || this.state.open) this.setState({translateY: 0}); else if (nextProps.inertia < 0 && nextProps.top > 200) { this.setState({translateY: -100}); }; } _mapTabs = () => { return tabs.map((tab)=>{ if (this.props.isAtTop && !this.state.open) { return ( <Tab label={tab.label} value={tab.location} key={tab.location}></Tab> ); } else { return ( <Tab label={tab.label} value={tab.location} key={tab.location} buttonStyle={styles.tabTemplateScrolled}></Tab> ); } }); } _mapMenuItem = () => { return menuItems.map((menuItem)=>{ return ( <MenuItem value={menuItem.value} key={menuItem.value} primaryText={menuItem.text} /> ); }); } render() { return ( <div> <AppBar title={<LogoIcon className={(this.props.isAtTop || this.state.open) ? "logoIcon atTop" : "logoIcon scrolled"}/>} className={(this.props.isAtTop) ? "menuAppBar atTop" : "menuAppBar scrolled"} showMenuIconButton={false} zDepth={(this.props.isAtTop) ? 0 : 1} titleStyle={styles.titleStyle} style={{transform: "translateY("+this.state.translateY+"%)"}} > <SelectField value={this.state.value} onChange={this._handleSelectFieldChange} className={this.state.open ? "menuSelect open" : "menuSelect"} style={styles.selectField} labelStyle={(this.props.isAtTop) ? styles.menuStyle : styles.menuStyleScrolled} underlineStyle={styles.underline} selectedMenuItemStyle={styles.selectedMenuItem} > {this._mapMenuItem()} </SelectField> <div style={styles.separator}/> <Tabs value={this.state.altLocation} onChange={this._handleTabChange} className={(this.state.open) ? "menuTabs":"menuTabs hidden-xs"} tabItemContainerStyle={styles.tabItemContainer} inkBarStyle={styles.inkBar} > {this._mapTabs()} </Tabs> <IconButton className={(this.state.open) ? "helpIcon open visible-xs-block":"helpIcon visible-xs-block"} onClick={()=>this._handleTabChange('aide')}> <Help/> </IconButton> <Drawer open={this.state.open} docked={false} openSecondary={true} width={Math.min(window.innerWidth-84,600)} className="drawerContainer" onRequestChange={handleClose} overlayClassName="overlay" disableSwipeToOpen={true}> <AppBar className="drawerAppBar" iconElementLeft={<IconButton><NavigationClose/></IconButton>} onLeftIconButtonTouchTap={handleClose} style={{background: "white"}} /> <div className={"drawerContent "+this.state.altLocation}> <div className="drawerTabContent"> <h3>Aide</h3> <p>L'application JobApp vous permet de <b>trouver des offres de stage ou d'emploi</b> et vous offre des <b>outils d'analyse de compétences</b></p> <p>Lancez votre recherche, puis via le panneau <span className="fakeButton">Compétences</span> importez votre CV ou ajoutez manuellement votre CV et laissez nos algorithmes travailler !</p> <p>Vous obtiendrez alors :</p> <ul> <li>La liste des offres correspondant à votre profil</li> <li>La liste des compétences attendues pour ces offres</li> </ul> <p>Vous avez égalment la possibilité de filtrer les résultats via le panneau <span className="fakeButton">Filtres</span>.</p> <p> Les offres qui correspondent à votre profil peuvent être <b>affichées sous forme de liste ou réparties sur une carte de France </b> pour faciliter une recherche selon des critères géographiques.</p> </div> <div className="drawerTabContent"> <h3>A propos</h3> <p>Cette application a été développée par une équipe mixte de l'École Centrale de Lyon et emlyon business school dans le cadre d'un projet de fin d'étude.</p> <p>Les données sont fournies et utilisées dans un but pédagogique.</p> <p>Les documents de développement sont stockés sur deux <i>repositories</i> Github publics accessibles via les boutons ci-après.</p> <IconButton href="https://github.com/tpucci/jobads-webapp"> <SvgIcon color={"black"}> <path d={Github} /> </SvgIcon> </IconButton> <IconButton href="https://github.com/yannvgn/jobads-textminer"> <SvgIcon color={"black"}> <path d={Github} /> </SvgIcon> </IconButton> <p>Nous vous informons que les données de votre CV ne sont pas collectées : elles sont temporairement conservées par l’app de manière à en extraire les compétences et vous proposer une analyse de ces dernières.</p> </div> </div> </Drawer> </AppBar> </div> ); } } export {handleClose};
35.577869
238
0.583113
43af3309abb5c0ed24d210d24bf28e9ecef70ca5
6,362
go
Go
src/les/utils/limiter_test.go
wldear/masa-node-v1.0
11def1cff72eef0b5d09289aeaf57df52e707771
[ "MIT" ]
280
2021-05-19T07:34:12.000Z
2021-07-12T01:35:22.000Z
src/les/utils/limiter_test.go
wldear/masa-node-v1.0
11def1cff72eef0b5d09289aeaf57df52e707771
[ "MIT" ]
60
2021-12-10T10:29:26.000Z
2022-03-26T14:58:32.000Z
src/les/utils/limiter_test.go
wldear/masa-node-v1.0
11def1cff72eef0b5d09289aeaf57df52e707771
[ "MIT" ]
86
2021-12-10T06:05:18.000Z
2022-03-26T18:59:54.000Z
// Copyright 2020 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package utils import ( "math/rand" "testing" "github.com/ethereum/go-ethereum/p2p/enode" ) const ( ltTolerance = 0.03 ltRounds = 7 ) type ( ltNode struct { addr, id int value, exp float64 cost uint reqRate float64 reqMax, runCount int lastTotalCost uint served, dropped int } ltResult struct { node *ltNode ch chan struct{} } limTest struct { limiter *Limiter results chan ltResult runCount int expCost, totalCost uint } ) func (lt *limTest) request(n *ltNode) { var ( address string id enode.ID ) if n.addr >= 0 { address = string([]byte{byte(n.addr)}) } else { var b [32]byte rand.Read(b[:]) address = string(b[:]) } if n.id >= 0 { id = enode.ID{byte(n.id)} } else { rand.Read(id[:]) } lt.runCount++ n.runCount++ cch := lt.limiter.Add(id, address, n.value, n.cost) go func() { lt.results <- ltResult{n, <-cch} }() } func (lt *limTest) moreRequests(n *ltNode) { maxStart := int(float64(lt.totalCost-n.lastTotalCost) * n.reqRate) if maxStart != 0 { n.lastTotalCost = lt.totalCost } for n.reqMax > n.runCount && maxStart > 0 { lt.request(n) maxStart-- } } func (lt *limTest) process() { res := <-lt.results lt.runCount-- res.node.runCount-- if res.ch != nil { res.node.served++ if res.node.exp != 0 { lt.expCost += res.node.cost } lt.totalCost += res.node.cost close(res.ch) } else { res.node.dropped++ } } func TestLimiter(t *testing.T) { limTests := [][]*ltNode{ { // one id from an individual address and two ids from a shared address {addr: 0, id: 0, value: 0, cost: 1, reqRate: 1, reqMax: 1, exp: 0.5}, {addr: 1, id: 1, value: 0, cost: 1, reqRate: 1, reqMax: 1, exp: 0.25}, {addr: 1, id: 2, value: 0, cost: 1, reqRate: 1, reqMax: 1, exp: 0.25}, }, { // varying request costs {addr: 0, id: 0, value: 0, cost: 10, reqRate: 0.2, reqMax: 1, exp: 0.5}, {addr: 1, id: 1, value: 0, cost: 3, reqRate: 0.5, reqMax: 1, exp: 0.25}, {addr: 1, id: 2, value: 0, cost: 1, reqRate: 1, reqMax: 1, exp: 0.25}, }, { // different request rate {addr: 0, id: 0, value: 0, cost: 1, reqRate: 2, reqMax: 2, exp: 0.5}, {addr: 1, id: 1, value: 0, cost: 1, reqRate: 10, reqMax: 10, exp: 0.25}, {addr: 1, id: 2, value: 0, cost: 1, reqRate: 1, reqMax: 1, exp: 0.25}, }, { // adding value {addr: 0, id: 0, value: 3, cost: 1, reqRate: 1, reqMax: 1, exp: (0.5 + 0.3) / 2}, {addr: 1, id: 1, value: 0, cost: 1, reqRate: 1, reqMax: 1, exp: 0.25 / 2}, {addr: 1, id: 2, value: 7, cost: 1, reqRate: 1, reqMax: 1, exp: (0.25 + 0.7) / 2}, }, { // DoS attack from a single address with a single id {addr: 0, id: 0, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 1, id: 1, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 2, id: 2, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 3, id: 3, value: 0, cost: 1, reqRate: 10, reqMax: 1000000000, exp: 0}, }, { // DoS attack from a single address with different ids {addr: 0, id: 0, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 1, id: 1, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 2, id: 2, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 3, id: -1, value: 0, cost: 1, reqRate: 1, reqMax: 1000000000, exp: 0}, }, { // DDoS attack from different addresses with a single id {addr: 0, id: 0, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 1, id: 1, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 2, id: 2, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: -1, id: 3, value: 0, cost: 1, reqRate: 1, reqMax: 1000000000, exp: 0}, }, { // DDoS attack from different addresses with different ids {addr: 0, id: 0, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 1, id: 1, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: 2, id: 2, value: 1, cost: 1, reqRate: 1, reqMax: 1, exp: 0.3333}, {addr: -1, id: -1, value: 0, cost: 1, reqRate: 1, reqMax: 1000000000, exp: 0}, }, } lt := &limTest{ limiter: NewLimiter(100), results: make(chan ltResult), } for _, test := range limTests { lt.expCost, lt.totalCost = 0, 0 iterCount := 10000 for j := 0; j < ltRounds; j++ { // try to reach expected target range in multiple rounds with increasing iteration counts last := j == ltRounds-1 for _, n := range test { lt.request(n) } for i := 0; i < iterCount; i++ { lt.process() for _, n := range test { lt.moreRequests(n) } } for lt.runCount > 0 { lt.process() } if spamRatio := 1 - float64(lt.expCost)/float64(lt.totalCost); spamRatio > 0.5*(1+ltTolerance) { t.Errorf("Spam ratio too high (%f)", spamRatio) } fail, success := false, true for _, n := range test { if n.exp != 0 { if n.dropped > 0 { t.Errorf("Dropped %d requests of non-spam node", n.dropped) fail = true } r := float64(n.served) * float64(n.cost) / float64(lt.expCost) if r < n.exp*(1-ltTolerance) || r > n.exp*(1+ltTolerance) { if last { // print error only if the target is still not reached in the last round t.Errorf("Request ratio (%f) does not match expected value (%f)", r, n.exp) } success = false } } } if fail || success { break } // neither failed nor succeeded; try more iterations to reach probability targets iterCount *= 2 } } lt.limiter.Stop() }
30.7343
99
0.60044
5bcc4d69a6fe812325bda110e9d2e3346c0690e7
584
h
C
Homework5/EduServer_IOCP/ClientSessionManager.h
abiles/gameServer2015
043d6565e54d1ca791bd46b1e6954ed5605d710f
[ "MIT" ]
4
2017-08-30T06:01:10.000Z
2020-02-28T04:38:16.000Z
Homework6/EduServer_IOCP/ClientSessionManager.h
abiles/gameServer2015
043d6565e54d1ca791bd46b1e6954ed5605d710f
[ "MIT" ]
null
null
null
Homework6/EduServer_IOCP/ClientSessionManager.h
abiles/gameServer2015
043d6565e54d1ca791bd46b1e6954ed5605d710f
[ "MIT" ]
2
2019-06-06T06:19:49.000Z
2019-09-06T14:01:00.000Z
#pragma once #include <list> #include <WinSock2.h> #include "FastSpinlock.h" class ClientSession; class ClientSessionManager { public: ClientSessionManager() : mCurrentIssueCount(0), mCurrentReturnCount(0) {} ~ClientSessionManager(); void PrepareClientSessions(); bool AcceptClientSessions(); void ReturnClientSession(ClientSession* client); private: typedef std::list<ClientSession*> ClientList; ClientList mFreeSessionList; FastSpinlock mLock; uint64_t mCurrentIssueCount; uint64_t mCurrentReturnCount; }; extern ClientSessionManager* GClientSessionManager;
17.176471
71
0.792808
74475d07a87762dbf08e6cb6dda8cffe3c714d2e
5,011
swift
Swift
tSecreta/tSecreta/NoteDataHandler.swift
mtonosaki/tSecreta
4f21facded0a3654cb08be127e51d8cbfe95b2bb
[ "MIT" ]
null
null
null
tSecreta/tSecreta/NoteDataHandler.swift
mtonosaki/tSecreta
4f21facded0a3654cb08be127e51d8cbfe95b2bb
[ "MIT" ]
14
2021-11-24T11:15:27.000Z
2022-03-29T13:45:07.000Z
tSecreta/tSecreta/NoteDataHandler.swift
mtonosaki/tSecreta
4f21facded0a3654cb08be127e51d8cbfe95b2bb
[ "MIT" ]
null
null
null
// // CloudFileHandler.swift // tSecreta // // Created by Manabu Tonosaki on 2021/12/01. // MIT License (c)2021 Manabu Tonosaki all rights reserved. import UIKit // import AZSClient // no need to import AZSClient here because of imported with Bridging-Header.h as an object-c bridge public func UploadText(text: String, userObjectId: String, callback: @escaping (Bool, String?) -> Void) { let cn = try? AZSCloudStorageAccount(fromConnectionString: MySecret().azureBlob.AzureStorageConnectionString) guard let cn = cn else { callback(false, "Azure connection string error") return } let blobClient = cn.getBlobClient() let blobContainer = blobClient.containerReference(fromName: "tsecret") let blob = blobContainer.blockBlobReference(fromName: "MainData.\(userObjectId).dat") blob.upload(fromText: text) { (error) in if let error = error { callback(false, error.localizedDescription) } else { callback(true, nil) } } } public func DownloadText(userObjectId: String, callback: @escaping (Bool, String?) -> Void) { let cn = try? AZSCloudStorageAccount(fromConnectionString: MySecret().azureBlob.AzureStorageConnectionString) guard let cn = cn else { callback(false, "Azure connection string error") return } let blobClient = cn.getBlobClient() let blobContainer = blobClient.containerReference(fromName: "tsecret") let blob = blobContainer.blockBlobReference(fromName: "MainData.\(userObjectId).dat") blob.downloadToText(){ (error, text) in if let error = error { callback(false, error.localizedDescription) return } if let text = text { callback(true, text) } } } // Calculate hash code of an image implemented based on below source code. // see also https://github.com/coenm/ImageHash/blob/develop/src/ImageHash/HashAlgorithms/AverageHash.cs private func getImageHash(image: UIImage, defaultHash: String) -> String { let targetWidth: CGFloat = 8 let canvasSize = CGSize(width: targetWidth, height: CGFloat(ceil(targetWidth / image.size.width * image.size.height))) UIGraphicsBeginImageContextWithOptions(canvasSize, false, image.scale) defer { UIGraphicsEndImageContext() } let alphaFill = UIImage(named: "alphaFill") alphaFill?.draw(in: CGRect(origin: .zero, size: canvasSize)) image.draw(in: CGRect(origin: .zero, size: canvasSize)) guard let image2 = UIGraphicsGetImageFromCurrentImageContext() else { return defaultHash } guard let cgImage = image2.cgImage else { return defaultHash } guard let cfdata = cgImage.dataProvider.unsafelyUnwrapped.data else { return defaultHash } guard let data = CFDataGetBytePtr(cfdata) else { return defaultHash } let W = Int(cgImage.width) let H = Int(cgImage.height) let WH = W * H var mask = UInt64(1) << (WH - 1) var averageValue: UInt64 = 0 var hashCode: UInt64 = 0 for y in 0..<H { for x in 0..<W { let pos = cgImage.bytesPerRow * y + x * (cgImage.bitsPerPixel / 8) let gray = (CGFloat(data[pos + 0]) + CGFloat(data[pos + 1]) + CGFloat(data[pos + 2])) / 3.0 averageValue += UInt64(gray) } } averageValue /= UInt64(WH) for y in 0..<H { for x in 0..<W { let pos = cgImage.bytesPerRow * y + x * (cgImage.bitsPerPixel / 8) let gray = (CGFloat(data[pos + 0]) + CGFloat(data[pos + 1]) + CGFloat(data[pos + 2])) / 3.0 let pixel = UInt64(gray) if pixel >= averageValue { hashCode |= mask } mask >>= 1 } } let hashData = Data(bytes: &hashCode, count: MemoryLayout<UInt64>.size) let hashStr = hashData.map { byte in return String(NSString(format:"%02x", byte)) }.joined() return hashStr } public func saveLogoPicture(image: UIImage, defaultName: String?, note: Note) async -> String? { guard let data = image.pngData() else { return "Cannot got logo image data." } let hash = getImageHash(image: image, defaultHash: defaultName ?? "no-name") let filename = "logo-\(hash).png" print("saved logo image \(filename)") let message = await saveLogoPicture(imageData: data, filename: filename, note: note) return message } public func saveLogoPicture(imageData: Data, filename: String, note: Note) async -> String? { guard let url = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent(filename) else { return "Cannot got logo url" } do { try imageData.write(to: url) note.setValueNoHistory(field: .logoFilename, text: filename) return nil } catch let error { return error.localizedDescription } }
34.798611
169
0.642387
9d4cc111b1f0061841a5d51339806bd4b0006149
109
asm
Assembly
3° Período/Arquiterura-e-Organiza-o-de-Computadores/Operações Básicas MIPS 1.asm
sullyvan15/UVV
2390cc2881792d036db1d8b098fe366f47cd98c3
[ "MIT" ]
null
null
null
3° Período/Arquiterura-e-Organiza-o-de-Computadores/Operações Básicas MIPS 1.asm
sullyvan15/UVV
2390cc2881792d036db1d8b098fe366f47cd98c3
[ "MIT" ]
1
2020-10-07T23:33:21.000Z
2020-10-08T01:15:11.000Z
3° Período/Arquiterura-e-Organiza-o-de-Computadores/Operações Básicas MIPS 1.asm
sullyvan15/Universidade-Vila-Velha
2390cc2881792d036db1d8b098fe366f47cd98c3
[ "MIT" ]
null
null
null
.data out_string: .ascii "\nHello, World!\n" .text main: li $v0, 4 la $a0, out_string syscall
12.111111
39
0.59633
22249a67a5fa8ed5b23713f20c0a5c0c34fdaa43
1,275
swift
Swift
TableViewIndependantHeader/TableViewIndependantHeader/Views/Main/Views/MainHeaderView.swift
rcasanovan/TableViewIndependantHeader
a10ae891dd24790d5646657268e7ddd1dbddbbe1
[ "Apache-2.0" ]
null
null
null
TableViewIndependantHeader/TableViewIndependantHeader/Views/Main/Views/MainHeaderView.swift
rcasanovan/TableViewIndependantHeader
a10ae891dd24790d5646657268e7ddd1dbddbbe1
[ "Apache-2.0" ]
null
null
null
TableViewIndependantHeader/TableViewIndependantHeader/Views/Main/Views/MainHeaderView.swift
rcasanovan/TableViewIndependantHeader
a10ae891dd24790d5646657268e7ddd1dbddbbe1
[ "Apache-2.0" ]
null
null
null
// // MainHeaderView.swift // TableViewIndependantHeader // // Created by Ricardo Casanova on 30/08/2020. // Copyright © 2020 Ricardo Casanova. All rights reserved. // import UIKit //__ This class extends UIView. Feel free to modify it if needed class MainHeaderView: UIView { public static var height: CGFloat { return 200.0 } // MARK: Lifecycle override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } } // MARK: - Setup views extension MainHeaderView { /** Setup views */ private func setupViews() { //__ Configure your view here //__ Background color, title, safe area backgroundColor = .yellow configureSubviews() addSubviews() } /** Configure subviews */ private func configureSubviews() { //__ Configure all the subviews here } } // MARK: - Layout & constraints extension MainHeaderView { /** Add subviews */ private func addSubviews() { //__ Add all the subviews here //__ Configure the constraints } }
18.75
64
0.585098
70e91dd5cd169a6ebbda70113e910099fdcde335
214
go
Go
testdata/src/a/a.go
gostaticanalysis/lion
b944fed56afaf3b612812054dae90f38271f6f0a
[ "MIT" ]
31
2020-03-09T03:27:22.000Z
2021-03-12T15:01:30.000Z
testdata/src/a/a.go
gostaticanalysis/lion
b944fed56afaf3b612812054dae90f38271f6f0a
[ "MIT" ]
null
null
null
testdata/src/a/a.go
gostaticanalysis/lion
b944fed56afaf3b612812054dae90f38271f6f0a
[ "MIT" ]
1
2020-05-28T05:20:32.000Z
2020-05-28T05:20:32.000Z
package a func F1() {} // OK func F2() {} // want `a\.F2 is not tested` func f3() {} // OK type T struct{} func (T) M1() {} // OK func (T) M2() {} // want `\(a\.T\)\.M2 is not tested` func (T) m3() {} // OK
13.375
53
0.481308
df857599754e12785250aeb36cc3d060fb8b6bd4
581
ts
TypeScript
src/packages/introspection/src/__tests__/handlePanic.test.ts
THEMEKKANIKKA/prisma
db0af08ba0c698d51dee8db5ce02f582ff7aac24
[ "Apache-2.0" ]
null
null
null
src/packages/introspection/src/__tests__/handlePanic.test.ts
THEMEKKANIKKA/prisma
db0af08ba0c698d51dee8db5ce02f582ff7aac24
[ "Apache-2.0" ]
1
2020-10-07T03:10:40.000Z
2020-10-07T03:10:40.000Z
src/packages/introspection/src/__tests__/handlePanic.test.ts
THEMEKKANIKKA/prisma
db0af08ba0c698d51dee8db5ce02f582ff7aac24
[ "Apache-2.0" ]
1
2020-10-07T03:09:39.000Z
2020-10-07T03:09:39.000Z
import path from 'path' import { Introspect } from '../commands/Introspect' // import CaptureStdout from './__helpers__/captureStdout' describe('panic', () => { test('should panic', async () => { process.env.FORCE_PANIC_INTROSPECTION_ENGINE = '1' process.chdir(path.join(__dirname, 'fixture')) const introspect = new Introspect() try { await introspect.parse(['--print']) } catch (e) { expect(e).toMatchInlineSnapshot( `[Error: [introspection-engine/core/src/rpc.rs:156:9] This is the debugPanic artificial panic]`, ) } }) })
30.578947
104
0.652324
6b4cff403c86cf9fb69451e04bebdc2b75c1fd85
623
h
C
nfcd/src/main/jni/include/nfcd/hook/Symbol.h
malexmave/nfcgate
8f9c8330d5507aedbb61803538b4d01a93fc7169
[ "Apache-2.0" ]
569
2015-08-14T14:27:45.000Z
2022-03-31T17:07:39.000Z
nfcd/src/main/jni/include/nfcd/hook/Symbol.h
malexmave/nfcgate
8f9c8330d5507aedbb61803538b4d01a93fc7169
[ "Apache-2.0" ]
45
2015-06-01T09:59:22.000Z
2022-03-24T06:28:40.000Z
nfcd/src/main/jni/include/nfcd/hook/Symbol.h
malexmave/nfcgate
8f9c8330d5507aedbb61803538b4d01a93fc7169
[ "Apache-2.0" ]
89
2016-03-20T01:33:19.000Z
2022-03-17T16:53:38.000Z
#ifndef NFCD_SYMBOL_H #define NFCD_SYMBOL_H #include <cstdint> #include <functional> #include <type_traits> #include <string> #include <nfcd/error.h> class Symbol { public: explicit Symbol(const std::string &name, void *libraryHandle); template <typename Fn, typename... Args> typename std::result_of<Fn*(Args...)>::type call(Args&&... args) { return ((Fn*)mAddress)(std::forward<Args>(args)...); } template<typename T> T *address() const { return reinterpret_cast<T*>(mAddress); } protected: void *mAddress = nullptr; std::string mName; }; #endif //NFCD_SYMBOL_H
20.096774
70
0.658106
6e279755ff808307ab8ff22bcd46b04340a0c050
43,421
html
HTML
src/main/webapp/static/html/page-include/instructor-modal.html
LNMA/course_management_system-controller-view
3d66fca7eb1c1847f719883066003dd8cdb03cf8
[ "Apache-2.0" ]
null
null
null
src/main/webapp/static/html/page-include/instructor-modal.html
LNMA/course_management_system-controller-view
3d66fca7eb1c1847f719883066003dd8cdb03cf8
[ "Apache-2.0" ]
2
2020-09-25T17:54:00.000Z
2020-09-25T18:00:46.000Z
src/main/webapp/static/html/page-include/instructor-modal.html
LNMA/course_management_system-controller-view
3d66fca7eb1c1847f719883066003dd8cdb03cf8
[ "Apache-2.0" ]
null
null
null
<nav ng-controller="InstructorHomeController"> <div id="viewProfileModal"> <div class="modal fade" id="profileModal"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Profile</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <div class="modal-body"> <div class="container-fluid"> <div class="row row-cols-1"> <div class="col col-md-7"> <div class="form-row"> <div class="form-group col col-md-10"> <label for="username" class="font-weight-bold"> Email: </label> <input class="form-control" id="username" name="instructorEmail" type="text" value="{{email}}" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-10"> <label for="accountPermission" class="font-weight-bold"> Account Permission: </label> <input class="form-control" id="accountPermission" name="accountRole" type="text" value="{{userRole}}" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-10"> <label for="dateCreate" class="font-weight-bold"> Date Create: </label> <input class="form-control" id="dateCreate" name="dateCreate" type="text" value="{{joinDate}}" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-10"> <label for="password" class="font-weight-bold"> Password: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#passwordModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="password" name="password" type="password" value="{{password}}" readonly disabled> </div> </div> </div> <div class="align-self-center col col-md-5"> <div class="row justify-content-center "> <img src="data:image/*;base64,{{picture}}" class="rounded-circle" width="256" height="256" alt="My Picture"> <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#ImageModal"> <img src="/static/images/add_photo_alternate-black-48dp.svg" width="28" height="28" alt="add image"> </button> </div> <div class="small text-muted">{{pictureUploadDate}}</div> </div> </div> </div> <div class="container-fluid"> <div class="form-row"> <div class="form-group col col-md-6"> <label for="forename" class="font-weight-bold"> Forename: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#forenameModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="forename" value="{{forename}}" type="text" readonly disabled> </div> <div class="form-group col col-md-6"> <label for="telephone" class="font-weight-bold"> Phone: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#telephoneModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="telephone" value="{{phone}}" type="text" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-6"> <label for="lname" class="font-weight-bold"> Surname: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#surnameModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="lname" value="{{surname}}" type="text" readonly disabled> </div> <div class="form-group col col-md-6"> <label for="country" class="font-weight-bold"> Country: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#addressModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="country" value="{{country}}" type="text" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-6"> <label for="gender" class="font-weight-bold"> Gender: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#genderModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="gender" value="{{gender}}" type="text" readonly disabled> </div> <div class="form-group col col-md-6"> <label for="state" class="font-weight-bold"> State: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#addressModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="state" value="{{state}}" type="text" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-6"> <label for="birthday" class="font-weight-bold"> BirthDay: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#birthdayModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="birthday" value="{{birthday}}" type="text" readonly disabled> </div> <div class="form-group col col-md-6"> <label for="address" class="font-weight-bold"> Address: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#addressModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="address" value="{{address}}" type="text" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-6"> <label for="age" class="font-weight-bold"> Age: </label> <input class="form-control" id="age" value="{{age}}" type="text" readonly disabled> </div> <div class="form-group col col-md-6"> <label for="lLogin" class="font-weight-bold"> Last Login: </label> <input class="form-control" id="lLogin" value="{{lastSignIn}}" type="text" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-6"> <label for="head_line" class="font-weight-bold"> Headline: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#headlineModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="head_line" value="{{headline}}" type="text" readonly disabled> </div> <div class="form-group col col-md-6"> <label for="specialty" class="font-weight-bold"> Specialty: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#specialtyModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="specialty" value="{{specialty}}" type="text" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-6"> <label for="nickname" class="font-weight-bold"> Nickname: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#nicknameModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="nickname" value="{{nickname}}" type="text" readonly disabled> </div> <div class="form-group col col-md-6"> <label for="portfolio" class="font-weight-bold"> Portfolio: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#portfolioModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="portfolio" value="{{portfolio}}" type="text" readonly disabled> </div> </div> <div class="form-row"> <div class="form-group col col-md-6"> <label for="profileVisibility" class="font-weight-bold"> profile Visibility: <button class="btn" data-toggle="modal" data-dismiss="modal" data-target="#profileVisibilityModal"> <img src="/static/images/edit-black-48dp.svg" width="16" height="16" alt="edit"> </button> </label> <input class="form-control" id="profileVisibility" value="{{profileVisibility}}" type="text" readonly disabled> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close </button> </div> </div> </div> </div> <ng-include src="'/static/html/page-include/edit_password-modal.html'"></ng-include> <ng-include src="'/static/html/page-include/edit_user_details-modal.html'"></ng-include> <!-- headline Modal --> <div class="modal fade" id="headlineModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Change Headline</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <div class="container" id="editHeadlineSuccessAlert" ng-model="headlineSuccessMessage" ng-show="isEditHeadlineSuccess" role="alert"> <div class="alert alert-success alert-dismissible fade show"> <strong>Success!</strong> {{headlineSuccessMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> <div class="container" id="editHeadlineErrorAlert" ng-model="headlineErrorMessage" ng-hide="editHeadlineForm.$valid" role="alert"> <div ng-messages="editHeadlineForm.$error || editHeadlineForm.$invalid" ng-show="submitted && (editHeadlineForm.$invalid || editHeadlineForm.$error)"> <div class="alert alert-danger alert-dismissible fade show"> <strong>Error!</strong> <span ng-show="editHeadlineForm.headline.$error.required"> headline Required! </span> <span ng-show="editHeadlineForm.headline.$invalid"> headline Invalid! </span> {{headlineErrorMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> </div> <form ng-submit="updateHeadline()" name="editHeadlineForm" method="post" novalidate> <div class="modal-body"> <div class="container-fluid"> <div class="form-row"> <div class="form-group col col-md-9"> <label class="font-weight-bold" for="inputHeadline"> Headline: </label> <input id="inputHeadline" name="headline" type="text" class="form-control" placeholder="type new headline" ng-minlength="2" ng-maxlength="300" required ng-class="{'is-invalid': submitted && (editHeadlineForm.headline.$error.required || editHeadlineForm.headline.$invalid), 'is-valid': editHeadlineForm.headline.$valid}" ng-model="editHeadline"> </div> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success"> Save </button> <button type="button" class="btn btn-danger" data-dismiss="modal">Close </button> </div> </form> </div> </div> </div> <!-- specialty Modal --> <div class="modal fade" id="specialtyModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Change Specialty</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <div class="container" id="editSpecialtySuccessAlert" ng-model="specialtySuccessMessage" ng-show="isEditSpecialtySuccess" role="alert"> <div class="alert alert-success alert-dismissible fade show"> <strong>Success!</strong> {{specialtySuccessMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> <div class="container" id="editInterestsErrorAlert" ng-model="specialtyErrorMessage" ng-hide="editSpecialtyForm.$valid" role="alert"> <div ng-messages="editSpecialtyForm.$error || editSpecialtyForm.$invalid" ng-show="submitted && (editSpecialtyForm.$invalid || editSpecialtyForm.$error)"> <div class="alert alert-danger alert-dismissible fade show"> <strong>Error!</strong> <span ng-show="editSpecialtyForm.specialty.$error.required"> specialty Required! </span> <span ng-show="editSpecialtyForm.specialty.$invalid"> specialty Invalid! </span> {{specialtyErrorMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> </div> <form ng-submit="updateSpecialty()" name="editSpecialtyForm" method="post" novalidate> <div class="modal-body"> <div class="container-fluid"> <div class="form-row"> <div class="form-group col col-md-9"> <label class="font-weight-bold" for="inputSpecialty"> specialty: </label> <input id="inputSpecialty" name="specialty" type="text" class="form-control" placeholder="type new specialty" ng-minlength="2" ng-maxlength="300" required ng-class="{'is-invalid': submitted && (editSpecialtyForm.specialty.$error.required || editSpecialtyForm.specialty.$invalid), 'is-valid': editSpecialtyForm.specialty.$valid}" ng-model="editSpecialty"> </div> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success"> Save </button> <button type="button" class="btn btn-danger" data-dismiss="modal">Close </button> </div> </form> </div> </div> </div> <!-- nickname Modal --> <div class="modal fade" id="nicknameModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Change Nickname</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <div class="container" id="editNicknameSuccessAlert" ng-model="nicknameSuccessMessage" ng-show="isEditNicknameSuccess" role="alert"> <div class="alert alert-success alert-dismissible fade show"> <strong>Success!</strong> {{nicknameSuccessMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> <div class="container" id="editNicknameErrorAlert" ng-model="nicknameErrorMessage" ng-hide="editNicknameForm.$valid" role="alert"> <div ng-messages="editNicknameForm.$error || editNicknameForm.$invalid" ng-show="submitted && (editNicknameForm.$invalid || editNicknameForm.$error)"> <div class="alert alert-danger alert-dismissible fade show"> <strong>Error!</strong> <span ng-show="editNicknameForm.nickname.$error.required"> nickname Required! </span> <span ng-show="editNicknameForm.nickname.$invalid"> nickname Invalid! </span> {{nicknameErrorMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> </div> <form ng-submit="updateNickname()" name="editNicknameForm" method="post" novalidate> <div class="modal-body"> <div class="container-fluid"> <div class="form-row"> <div class="form-group col col-md-9"> <label class="font-weight-bold" for="inputNickname"> nickname: </label> <input id="inputNickname" name="nickname" type="text" class="form-control" placeholder="type new nickname" ng-minlength="2" ng-maxlength="50" required ng-class="{'is-invalid': submitted && (editNicknameForm.nickname.$error.required || editNicknameForm.nickname.$invalid), 'is-valid': editNicknameForm.nickname.$valid}" ng-model="editNickname"> </div> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success"> Save </button> <button type="button" class="btn btn-danger" data-dismiss="modal">Close </button> </div> </form> </div> </div> </div> <!-- portfolio Modal --> <div class="modal fade" id="portfolioModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Change Portfolio</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <div class="container" id="editportfolioSuccessAlert" ng-model="portfolioSuccessMessage" ng-show="isEditPortfolioSuccess" role="alert"> <div class="alert alert-success alert-dismissible fade show"> <strong>Success!</strong> {{portfolioSuccessMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> <div class="container" id="editPortfolioErrorAlert" ng-model="portfolioErrorMessage" ng-hide="editPortfolioForm.$valid" role="alert"> <div ng-messages="editPortfolioForm.$error || editPortfolioForm.$invalid" ng-show="submitted && (editPortfolioForm.$invalid || editPortfolioForm.$error)"> <div class="alert alert-danger alert-dismissible fade show"> <strong>Error!</strong> <span ng-show="editPortfolioForm.portfolio.$error.required"> portfolio Required! </span> <span ng-show="editPortfolioForm.portfolio.$invalid"> portfolio Invalid! </span> {{portfolioErrorMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> </div> <form ng-submit="updatePortfolio()" name="editPortfolioForm" method="post" novalidate> <div class="modal-body"> <div class="container-fluid"> <div class="form-row"> <div class="form-group col col-md-9"> <label class="font-weight-bold" for="inputPortfolio"> portfolio: </label> <input id="inputPortfolio" name="portfolio" type="text" class="form-control" placeholder="type new portfolio" ng-minlength="2" ng-maxlength="300" required ng-class="{'is-invalid': submitted && (editPortfolioForm.portfolio.$error.required || editPortfolioForm.portfolio.$invalid), 'is-valid': editPortfolioForm.portfolio.$valid}" ng-model="editPortfolio"> </div> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success"> Save </button> <button type="button" class="btn btn-danger" data-dismiss="modal">Close </button> </div> </form> </div> </div> </div> <!-- profileVisibility Modal --> <div class="modal fade" id="profileVisibilityModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Change Profile Visibility</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <div class="container" id="editProfileVisibilitySuccessAlert" ng-model="profileVisibilitySuccessMessage" ng-show="isEditProfileVisibilitySuccess" role="alert"> <div class="alert alert-success alert-dismissible fade show"> <strong>Success!</strong> {{profileVisibilitySuccessMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> <div class="container" id="editProfileVisibilityErrorAlert" ng-model="profileVisibilityErrorMessage" ng-hide="editProfileVisibilityForm.$valid" role="alert"> <div ng-messages="editProfileVisibilityForm.$error || editProfileVisibilityForm.$invalid" ng-show="submitted && (editProfileVisibilityForm.$invalid || editProfileVisibilityForm.$error)"> <div class="alert alert-danger alert-dismissible fade show"> <strong>Error!</strong> <span ng-show="editProfileVisibilityForm.profileVisibility.$error.required"> profile Visibility Required! </span> <span ng-show="editProfileVisibilityForm.profileVisibility.$invalid"> profile Visibility Invalid! </span> {{profileVisibilityErrorMessage}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> </div> <form ng-submit="updateProfileVisibility()" name="editProfileVisibilityForm" method="post" novalidate> <div class="modal-body"> <div class="container-fluid"> <div class="form-row"> <div class="form-group col col-md-9"> <label class="font-weight-bold" for="inputProfileVisibility"> Profile Visibility: </label> <br> <select class="custom-select" id="inputProfileVisibility" name="profileVisibility" ng-model="editProfileVisibility" required ng-class="{'is-invalid': submitted && (editProfileVisibilityForm.profileVisibility.$error.required || editProfileVisibilityForm.profileVisibility.$invalid), 'is-valid': editProfileVisibilityForm.profileVisibility.$valid}"> <option selected disabled value="">Select visibility...</option> <option value="PUBLIC">PUBLIC</option> <option value="PRIVATE">PRIVATE</option> </select> </div> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success"> Save </button> <button type="button" class="btn btn-danger" data-dismiss="modal">Close </button> </div> </form> </div> </div> </div> <!-- image modal --> <div class="modal fade" id="ImageModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Change Picture</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <form action="{{updatePictureUrl}}" method="post" enctype="multipart/form-data"> <div class="modal-body"> <div class="container-fluid justify-content-center"> <div class="form-row"> <div class="form-group col col-md-9"> <div class="custom-file"> <input type="file" class="custom-file-input" id="inputFileModal" name="file" required accept="image/*"> <label class="custom-file-label" for="inputFileModal">Choose file...</label> </div> </div> </div> </div> <script> // Add the following code if you want the name of the file appear on select $(".custom-file-input").on("change", function () { let fileName = $(this).val().split("\\").pop(); $(this).siblings(".custom-file-label").addClass("selected").html(fileName); }); </script> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success"> Save </button> <button type="button" class="btn btn-danger" data-dismiss="modal"> Close </button> </div> </form> </div> </div> </div> </div> </nav>
61.677557
125
0.351005
74b29ff4b76ca4ced428ccc430bb6875c119ca16
638
js
JavaScript
stores/user.js
crispchat/crisp-app-mobile
1a46acb1053189a364454c6f19bd5cd5dc559ac0
[ "MIT" ]
6
2016-05-19T16:01:15.000Z
2016-05-22T15:59:00.000Z
stores/user.js
crispchat/crisp-app-mobile
1a46acb1053189a364454c6f19bd5cd5dc559ac0
[ "MIT" ]
null
null
null
stores/user.js
crispchat/crisp-app-mobile
1a46acb1053189a364454c6f19bd5cd5dc559ac0
[ "MIT" ]
1
2020-11-09T00:17:15.000Z
2020-11-09T00:17:15.000Z
import alt from "../alt"; class UserStore { constructor() { this.displayName = "UserStore"; this.name = "UserStore"; this.UserActions = alt.getActions("UserActions"); this.bindActions(this.UserActions); this.websites = []; } websitesLoaded(event) { this.websites = event.websites; } profileLoaded(event) { this.profile = event.profile; } static getWebsites() { var { websites } = this.getState(); return websites; } static getProfile() { var { profile } = this.getState(); return profile; } } module.exports = alt.createStore(UserStore, 'UserStore');
19.333333
57
0.623824
ace2c7f29cf919b400222a02310a255d7f954b52
216
kt
Kotlin
app/src/main/java/com/maplonki/popularmovieskotlin/data/MovieDataStore.kt
maplonki/popular_movies_kotlin
073b22b60368acd9a88b6b65268dc3755965c248
[ "MIT" ]
null
null
null
app/src/main/java/com/maplonki/popularmovieskotlin/data/MovieDataStore.kt
maplonki/popular_movies_kotlin
073b22b60368acd9a88b6b65268dc3755965c248
[ "MIT" ]
null
null
null
app/src/main/java/com/maplonki/popularmovieskotlin/data/MovieDataStore.kt
maplonki/popular_movies_kotlin
073b22b60368acd9a88b6b65268dc3755965c248
[ "MIT" ]
null
null
null
package com.maplonki.popularmovieskotlin.data import com.maplonki.popularmovieskotlin.data.entity.MovieEntity /** * Created by hugo on 2/15/18. */ interface MovieDataStore { val movieList: List<MovieEntity> }
21.6
63
0.777778
cee5b98412ff980c8ccb5cbd43f7324d19b6592d
3,862
sql
SQL
reports_manager/report_manager_database/utility_functions/test/test_trig_log_reports_history.sql
james-cantrill/funda_components
23ce9cfbd7b70544544b8d9278c21e86fe31da45
[ "Apache-2.0" ]
null
null
null
reports_manager/report_manager_database/utility_functions/test/test_trig_log_reports_history.sql
james-cantrill/funda_components
23ce9cfbd7b70544544b8d9278c21e86fe31da45
[ "Apache-2.0" ]
null
null
null
reports_manager/report_manager_database/utility_functions/test/test_trig_log_reports_history.sql
james-cantrill/funda_components
23ce9cfbd7b70544544b8d9278c21e86fe31da45
[ "Apache-2.0" ]
null
null
null
-- test_action_enter_edit_reports.sql /* the json object containng the inmput data, _in_data, is defined below. _in_data: { report_id: report_name: description: url: containing_folder_name: insert_or_update: // text allowed values, insert, update changing_user_login: parameters: [ ] } */ -- Set the system up DELETE FROM report_manager_schema.report_parameters; DELETE FROM report_manager_schema.reports_history; DELETE FROM report_manager_schema.reports; SELECT * FROM system_user_schema.action_user_login ('{"login": "muser", "password":"ha_melech!16"}'); SELECT * FROM report_manager_schema.action_enter_edit_folders ('{"folder_name": "report_root", "folder_display_name":"All Programs", "description":"List of all reports", "is_root_folder": "TRUE", "changing_user_login": "muser"}'); SELECT 'TEST insert data is complete and correct - Success' AS test_goal; SELECT * FROM report_manager_schema.action_enter_edit_reports ('{"report_name": "Authorizing Psychiatrists with Clients", "description": "This report lists the authorizing psychiatrists for clients enrolled in one or more programs over a defined time period..", "url": "http://192.168.4.10:8080/WebViewerExample/frameset?__report=authorizing_psychiatrists_with_clients.rptdesign", "containing_folder_name": "report_root", "insert_or_update": "insert", "changing_user_login": "muser", "parameters": [{"parameter_name": "ReportStartDate"}, {"parameter_name": "ReportEndDate"}, {"parameter_name": "ProgramIds"}]}'); SELECT 'TEST insert second report' AS test_goal; SELECT * FROM report_manager_schema.action_enter_edit_reports ('{"report_name": "Gateways Openings - Chemung Programs", "description": "This report shows the number of openings on a selected date for the Gateways programs operating in Chemung county.", "url": "http://192.168.4.10:8080/WebViewerExample/frameset?__report=gateways_vacancies_chemung.rptdesign", "containing_folder_name": "report_root", "insert_or_update": "insert", "changing_user_login": "muser", "parameters": [{"parameter_name": "ReportStartDate"}, {"parameter_name": "ReportEndDate"}, {"parameter_name": "ProgramIds"}]}'); SELECT * FROM report_manager_schema.reports; SELECT * FROM report_manager_schema.reports_history ORDER BY report_name, datetime_report_change_started; SELECT 'TEST update first report url' AS test_goal; SELECT * FROM report_manager_schema.action_enter_edit_reports ('{"report_name": "Authorizing Psychiatrists with Clients", "description": "This report lists the authorizing psychiatrists for clients enrolled in one or more programs over a defined time period..", "url": "http://192.168.4.10:8080/WebViewerExample/frameset?__report=admitting_psychiatrists.rptdesign", "containing_folder_name": "report_root", "insert_or_update": "update", "changing_user_login": "muser", "parameters": [{"parameter_name": "ReportStartDate"}, {"parameter_name": "ReportEndDate"}, {"parameter_name": "ProgramIds"}]}'); SELECT 'TEST update second report description' AS test_goal; SELECT * FROM report_manager_schema.action_enter_edit_reports ('{"report_name": "Gateways Openings - Chemung Programs", "description": "This report shows the number of un its occupied and tne number of openings on a selected date for the Gateways programs operating in Chemung county.", "url": "http://192.168.4.10:8080/WebViewerExample/frameset?__report=gateways_vacancies_chemung.rptdesign", "containing_folder_name": "report_root", "insert_or_update": "update", "changing_user_login": "muser", "parameters": [{"parameter_name": "ReportStartDate"}, {"parameter_name": "ReportEndDate"}, {"parameter_name": "ProgramIds"}]}'); SELECT * FROM report_manager_schema.reports; DELETE FROM report_manager_schema.reports; SELECT * FROM report_manager_schema.reports_history ORDER BY report_name, datetime_report_change_started;
82.170213
625
0.779648
e779dea66f56743ca4bcbf70c9760ecad14afe7e
824
js
JavaScript
test/bootstrap.js
Cereceres/codigomx-challenge
f114b1ad8f115a5023cd518272ac8ef405cc264f
[ "MIT" ]
null
null
null
test/bootstrap.js
Cereceres/codigomx-challenge
f114b1ad8f115a5023cd518272ac8ef405cc264f
[ "MIT" ]
null
null
null
test/bootstrap.js
Cereceres/codigomx-challenge
f114b1ad8f115a5023cd518272ac8ef405cc264f
[ "MIT" ]
null
null
null
const supertest = require('supertest'); const User = require('../models/user.model'); const Response = require('../models/response.model'); const Post = require('../models/post.model'); const getServer = require('../index'); before(async() => { const server = await getServer(); global.agent = supertest(server); const user = await User.create({ username: 'testing', password: 'test' }); await User.update({ user_id: user.id.toString() }, { id:user.id }); global.user = user; const { body } = await agent.post('/api/auth') .send({ username:'testing', password:'test', }) .expect(200); global.token = body.token; }); after(async() => { await User.delete({}); await Response.delete({}); await Post.delete({}); });
25.75
71
0.578883
2dee018102a2354c3b2b558e9d311011d226bb10
5,064
rs
Rust
src/parser.rs
smshax/rarc-rs
f437b95d85f0f681ee4e0add7cc00adcb116f090
[ "MIT" ]
1
2021-01-27T15:00:35.000Z
2021-01-27T15:00:35.000Z
src/parser.rs
smshax/rarc-rs
f437b95d85f0f681ee4e0add7cc00adcb116f090
[ "MIT" ]
1
2018-09-08T21:55:48.000Z
2018-09-09T21:52:54.000Z
src/parser.rs
smshax/rarc-rs
f437b95d85f0f681ee4e0add7cc00adcb116f090
[ "MIT" ]
null
null
null
use nom::{IResult, be_u16, be_u32}; use {Entry, Header, Node}; pub fn parse_header(input: &[u8]) -> IResult<&[u8], Header> { do_parse!( input, tag!("RARC") >> file_size: be_u32 >> tag!([0x00, 0x00, 0x00, 0x20]) >> // header length (always 0x20, this is just a validity assert) data_offset: be_u32 >> data_length: be_u32 >> // unknown take!(4) >> // data_length again? take!(8) >> // u32 unknown[2] = {0, 0}; n_nodes: be_u32 >> nodes_offset: be_u32 >> n_entries: be_u32 >> entries_offset: be_u32 >> strings_size: be_u32 >> strings_offset: be_u32 >> n_files: be_u16 >> take!(2) >> take!(4) >> (Header { file_size: file_size, data_offset: data_offset + 0x20, data_length: data_length, n_nodes: n_nodes, nodes_offset: nodes_offset + 0x20, n_entries: n_entries, entries_offset: entries_offset + 0x20, strings_size: strings_size, strings_offset: strings_offset + 0x20, n_files: n_files, }) ) } pub fn parse_node(input: &[u8]) -> IResult<&[u8], Node> { do_parse!( input, id: take_str!(4) >> filename_offset: be_u32 >> filename_hash: be_u16 >> n_entries: be_u16 >> entry_start_id: be_u32 >> (Node { id: String::from(id), name: None, filename_offset: filename_offset, filename_hash: filename_hash, n_entries: n_entries, entry_start_id: entry_start_id, }) ) } pub fn parse_entry(input: &[u8]) -> IResult<&[u8], Entry> { do_parse!( input, idx: be_u16 >> hash: be_u16 >> entry_type: be_u16 >> name_offset: be_u16 >> data_offset_or_node_index: be_u32 >> file_data_length: be_u32 >> take!(4) >> // unknown, always 0 ( match entry_type { 0x200 => Entry::Folder { name_offset: name_offset, hash: hash, name: None, folder_node_idx: data_offset_or_node_index, }, 0x1100 => Entry::File { idx: idx, name_offset: name_offset, hash: hash, name: None, data_offset: data_offset_or_node_index, data_length: file_data_length, }, _ => panic!("unsupported entry type!"), } ) ) } #[cfg(test)] mod test { use super::*; static HANDCRAFTED_RARC_HEADER: &'static [u8] = &[ 0x52, 0x41, 0x52, 0x43, // RARC 0x13, 0x37, 0x13, 0x37, // file_size 0x00, 0x00, 0x00, 0x20, // header length 0x55, 0x55, 0x55, 0x35, // offset to the file data - 0x20 0x00, 0x00, 0x67, 0x76, // data length 0x00, 0x00, 0x67, 0x76, // data length (again) 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, // n_nodes 0x33, 0x33, 0x33, 0x13, // nodes_offset - 0x20 0x00, 0x00, 0x00, 0xff, // n_entries 0x53, 0x35, 0x33, 0x56, // entries_offset - 0x20 0x00, 0x00, 0xff, 0xff, // strings_size 0x32, 0x54, 0x73, 0x62, // strings_offset - 0x20 0x15, 0x32, // number of files 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; /// Check that we can parse the Bianco Hills 0 szs header successfully #[test] fn test_parse_bianco_header() { let data = include_bytes!("../data/bianco0.rarc"); let parse_result = parse_header(data); assert!(parse_result.is_ok()); if let Ok((_, header)) = parse_result { println!("{:?}", header); } } /// Check that a handcrafted header parses properly #[test] fn test_parse_header() { let parse_result = parse_header(HANDCRAFTED_RARC_HEADER); assert!(parse_result.is_ok()); assert_eq!( parse_result.unwrap().1, Header { file_size: 0x13371337, data_offset: 0x55555555, data_length: 0x6776, n_nodes: 0x70, nodes_offset: 0x33333333, n_entries: 0xff, entries_offset: 0x53353376, strings_size: 0xffff, strings_offset: 0x32547382, n_files: 0x1532, } ); } /// Check that a handcrafted header inverts back to the input when `.write()`ing it #[test] fn test_header_invertibility() { let parse_result = parse_header(HANDCRAFTED_RARC_HEADER); assert!(parse_result.is_ok()); let header = parse_result.unwrap().1; let mut new_header_data: Vec<u8> = vec![]; header.write(&mut new_header_data).expect("failed to write header to Vec<u8>"); assert_eq!(&new_header_data[..], &HANDCRAFTED_RARC_HEADER[..]); } }
28.937143
104
0.532188
e4651efe2ad26ae1b00e4c1d66c2c026dd367d56
10,016
swift
Swift
BLE-Swift/Demos/Devices/DeviceInfo/DeviceInfoViewController.swift
hulala1210/LYBluetoothKit
646fdb195247e45fbeb8beada9b86664b5a81e6c
[ "MIT" ]
null
null
null
BLE-Swift/Demos/Devices/DeviceInfo/DeviceInfoViewController.swift
hulala1210/LYBluetoothKit
646fdb195247e45fbeb8beada9b86664b5a81e6c
[ "MIT" ]
null
null
null
BLE-Swift/Demos/Devices/DeviceInfo/DeviceInfoViewController.swift
hulala1210/LYBluetoothKit
646fdb195247e45fbeb8beada9b86664b5a81e6c
[ "MIT" ]
1
2020-03-03T13:50:20.000Z
2020-03-03T13:50:20.000Z
// // DeviceInfoViewController.swift // BLE-Swift // // Created by SuJiang on 2019/1/4. // Copyright © 2019 ss. All rights reserved. // import UIKit class DeviceInfoViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, CharacteristicCellTableViewCellDelegate, CmdKeyBoardViewDelegate { var device: BLEDevice @IBOutlet weak var deviceNameLbl: UILabel! @IBOutlet weak var uuidLbl: UILabel! @IBOutlet weak var stateLbl: UILabel! @IBOutlet weak var connectBtn: UIButton! @IBOutlet weak var disconnectBtn: UIButton! @IBOutlet weak var tableView: UITableView! var deviceInfos: Array<DeviceInfo>! init(device: BLEDevice) { self.device = device super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configNav() createView() reloadData() NotificationCenter.default.addObserver(self, selector: #selector(deviceDataUpdate), name: BLEInnerNotification.deviceDataUpdate, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) DeviceResponseLogView.create() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) DeviceResponseLogView.destroy() } func configNav() { self.title = TR("Device Information") setNavLeftButton(withIcon: "fanhui", sel: #selector(backClick)) setNavRightButton(text: TR("日志"), sel: #selector(showLogBtnClick)) } func createView() { tableView.dataSource = self tableView.delegate = self tableView.register(UINib(nibName: "CharacteristicCellTableViewCell", bundle: nil), forCellReuseIdentifier: "cellId") reloadData() } func reloadData() { deviceInfos = generateInfos(withDevice: device) deviceNameLbl.text = device.name uuidLbl.text = "UUID: " + device.name if device.state == .disconnected { stateLbl.text = TR("Disconnected") stateLbl.textColor = rgb(200, 30, 30) connectBtn.isHidden = false disconnectBtn.isHidden = true } else { stateLbl.text = TR("Connected") stateLbl.textColor = rgb(30, 200, 30) connectBtn.isHidden = true disconnectBtn.isHidden = false } tableView.reloadData() } // MARK: - 业务逻辑 func generateInfos(withDevice deive:BLEDevice) -> Array<DeviceInfo> { var deviceInfoArr = Array<DeviceInfo>(); // advertisement data let adInfo = DeviceInfo(type: .advertisementData) adInfo.name = TR("ADVERTISEMENT DATA") deviceInfoArr.append(adInfo) for (uuid, service) in device.services { let sInfo = DeviceInfo(type: .service, uuid: uuid, name: "", properties: "", id: uuid) deviceInfoArr.append(sInfo) guard let characteristics = service.characteristics else { continue } for ch in characteristics { let uuid = ch.uuid.uuidString let name = uuid.count > 4 ? "Characteristic " + uuid.suffix(4) : "Characteristic " + uuid var properties = "" if ch.properties.contains(.read) { properties += "Read " } if ch.properties.contains(.write) { properties += "Write " } if ch.properties.contains(.writeWithoutResponse) { properties += "Write Without Response " } if ch.properties.contains(.notify) { properties += "Notify" } let cInfo = DeviceInfo(type: .characteristic, uuid: uuid, name: name, properties: properties, id: uuid) sInfo.subItems.append(cInfo) } } return deviceInfoArr; } // MARK: - 事件处理 @objc func backClick() { self.navigationController?.dismiss(animated: true, completion: nil) } @IBAction func connectBtnClick(_ sender: Any) { startLoading(nil) weak var weakSelf = self BLECenter.shared.connect(device: device, callback:{ (d, err) in if err != nil { weakSelf?.handleBleError(error: err) } else { weakSelf?.showSuccess(TR("Connected")) weakSelf?.device = d!; weakSelf?.reloadData() } }) } @IBAction func disconnectBtnClick(_ sender: Any) { startLoading(nil) weak var weakSelf = self BLECenter.shared.disconnect(device: device, callback:{ (d, err) in if err != nil { weakSelf?.handleBleError(error: err) } else { weakSelf?.showSuccess(TR("Connected")) weakSelf?.device = d!; weakSelf?.reloadData() } }) } @objc func showLogBtnClick() { DeviceResponseLogView.show() } // MARK: - 代理 func numberOfSections(in tableView: UITableView) -> Int { return deviceInfos.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let dInfo = deviceInfos[section] return dInfo.subItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! CharacteristicCellTableViewCell let dInfo = deviceInfos[indexPath.section] cell.updateUI(withDeviceInfo: dInfo.subItems[indexPath.row]) cell.delegate = self return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { print(view) if view is UITableViewHeaderFooterView { let headerFooterView:UITableViewHeaderFooterView! = (view as! UITableViewHeaderFooterView) headerFooterView.textLabel?.adjustsFontSizeToFitWidth = true } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let dInfo = deviceInfos[section] if dInfo.type == .advertisementData { return dInfo.name } else { return "UUID: " + dInfo.uuid } } private var keyboard = CmdKeyBoardView() private var textField: UITextField? func didClickSendBtn(cell: UITableViewCell) { let indexPath = tableView.indexPath(for: cell)! let dInfo = deviceInfos[indexPath.section] let cInfo = dInfo.subItems[indexPath.row] keyboard.delegate = self let alert = UIAlertController(title: nil, message: "输入要发送的数据(16进制)", preferredStyle: .alert) let ok = UIAlertAction(title: TR("OK"), style: .default) { (action) in if self.device.state == .ready { guard let sendStr = alert.textFields![0].text, sendStr.count > 0 else { self.showError("不能发送空的") return } self.printLog(log: "向 \(cInfo.uuid) 发送数据:\(sendStr)") _ = self.device.write(sendStr.hexadecimal ?? Data(), characteristicUUID: cInfo.uuid) } else { self.printLog(log: "设备断连了,无法发送数据") } } let cancel = UIAlertAction(title: TR("CANCEL"), style: .cancel, handler: nil) alert.addTextField { (textField) in textField.font = font(12) textField.inputView = self.keyboard self.textField = textField } alert.addAction(ok) alert.addAction(cancel) navigationController?.present(alert, animated: true, completion: nil) } func didEnterStr(str: String) { if str.hasPrefix("Str") || str.hasPrefix("Int") || str.hasPrefix("Len") { return } textField?.text = (textField?.text ?? "") + str } func didFinishInput() { } func didFallback() { guard let text = textField?.text, text.count > 0 else { return } textField?.text = String(text.prefix(text.count - 1)) } @objc func deviceDataUpdate(notification: Notification) { guard let uuid = notification.userInfo?[BLEKey.uuid] as? String else { return } guard let data = notification.userInfo?[BLEKey.data] as? Data else { return } guard let device = notification.userInfo?[BLEKey.device] as? BLEDevice else { return } if device == self.device { DeviceResponseLogView.printLog(log: "(\(uuid)) recv data:\(data.hexEncodedString())") DeviceResponseLogView.show() } // if uuid == self.data.recvFromUuid && device == self.device { // parser.standardParse(data: data, sendData: self.data.sendData, recvCount: self.data.recvDataCount) // } } func printLog(log: String) { DeviceResponseLogView.printLog(log: log) } }
31.696203
162
0.569688
9f40c917149b44593254b583921f0b2a48e4857f
14,116
kt
Kotlin
app/src/main/java/com/revolgenx/anilib/user/service/UserServiceImpl.kt
MrJako2001/AniLib
16e8dba5224095262a9704f8eced3ee0e3c2a5f9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/revolgenx/anilib/user/service/UserServiceImpl.kt
MrJako2001/AniLib
16e8dba5224095262a9704f8eced3ee0e3c2a5f9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/revolgenx/anilib/user/service/UserServiceImpl.kt
MrJako2001/AniLib
16e8dba5224095262a9704f8eced3ee0e3c2a5f9
[ "Apache-2.0" ]
null
null
null
package com.revolgenx.anilib.user.service import com.revolgenx.anilib.UserFollowersQuery import com.revolgenx.anilib.UserFollowingQuery import com.revolgenx.anilib.character.data.model.CharacterModel import com.revolgenx.anilib.character.data.model.CharacterNameModel import com.revolgenx.anilib.character.data.model.toModel import com.revolgenx.anilib.common.data.model.BaseModel import com.revolgenx.anilib.friend.data.field.UserFriendField import com.revolgenx.anilib.common.repository.network.BaseGraphRepository import com.revolgenx.anilib.common.repository.util.Resource import com.revolgenx.anilib.media.data.model.MediaConnectionModel import com.revolgenx.anilib.media.data.model.toModel import com.revolgenx.anilib.staff.data.model.StaffModel import com.revolgenx.anilib.staff.data.model.StaffNameModel import com.revolgenx.anilib.staff.data.model.toModel import com.revolgenx.anilib.studio.data.model.StudioModel import com.revolgenx.anilib.user.data.field.* import com.revolgenx.anilib.user.data.model.* import com.revolgenx.anilib.user.data.model.stats.UserGenreStatisticModel import com.revolgenx.anilib.user.data.model.stats.UserStatisticsModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.coroutines.runBlocking import timber.log.Timber import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class UserServiceImpl(private val baseGraphRepository: BaseGraphRepository) : UserService { override fun getUserOverView( field: UserOverViewField, compositeDisposable: CompositeDisposable, callback: (Resource<UserModel>) -> Unit ) { val disposable = baseGraphRepository.request(field.toQueryOrMutation()).map { response -> response.data?.let { it.user?.let { user -> UserModel().also { model -> model.id = user.id model.name = user.name model.avatar = user.avatar?.userAvatar?.toModel() model.bannerImage = user.bannerImage ?: model.avatar?.image model.isBlocked = user.isBlocked ?: false model.isFollower = user.isFollower ?: false model.isFollowing = user.isFollowing ?: false model.about = user.about ?: "" model.siteUrl = user.siteUrl model.statistics = user.statistics?.let { stats -> UserStatisticTypesModel().also { it.anime = stats.anime?.let { anime -> UserStatisticsModel().also { sModel -> sModel.count = anime.count sModel.daysWatched = anime.minutesWatched.toDouble().div(60).div(24) sModel.episodesWatched = anime.episodesWatched sModel.meanScore = anime.meanScore sModel.genres = anime.genres?.mapNotNull { genre -> genre?.let { g -> UserGenreStatisticModel().also { gModel -> gModel.genre = g.genre gModel.count = g.count } } } } } it.manga = stats.manga?.let { manga -> UserStatisticsModel().also { sModel -> sModel.count = manga.count sModel.volumesRead = manga.volumesRead sModel.chaptersRead = manga.chaptersRead sModel.meanScore = manga.meanScore sModel.genres = manga.genres?.mapNotNull { genre -> genre?.let { g -> UserGenreStatisticModel().also { gModel -> gModel.genre = g.genre gModel.count = g.count } } } } } } } } }?.also { userModel -> if (field.includeFollow) { userModel.following = it.followingPage?.pageInfo?.total ?: 0 userModel.followers = it.followerPage?.pageInfo?.total ?: 0 } else { runBlocking { val fResponse = suspendCoroutine<Resource<Pair<Int, Int>>> { cont -> getUserFollowingFollowerCount(UserFollowingFollowerCountField().also { countField -> countField.userId = userModel.id }, compositeDisposable) { cont.resume(it) } } userModel.following = fResponse.data?.first ?: 0 userModel.followers = fResponse.data?.second ?: 0 } } } } }.observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(it)) }, { Timber.w(it) callback.invoke(Resource.error(it.message, null, it)) }) compositeDisposable.add(disposable) } override fun getUserFollowingFollowerCount( field: UserFollowingFollowerCountField, compositeDisposable: CompositeDisposable, callback: (Resource<Pair<Int, Int>>) -> Unit ) { val disposable = baseGraphRepository.request(field.toQueryOrMutation()).map { it.data?.let { (it.followingPage?.pageInfo?.total ?: 0) to (it.followerPage?.pageInfo?.total ?: 0) } }.observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(it)) }, { Timber.w(it) callback.invoke(Resource.error(it.message, null, it)) }) compositeDisposable.add(disposable) } override fun getFollowersUsers( field: UserFollowerField, compositeDisposable: CompositeDisposable, callback: (Resource<List<UserModel>>) -> Unit ) { val disposable = baseGraphRepository.request(field.toQueryOrMutation()) .map { response -> val data = response.data if (data is UserFollowersQuery.Data) (data as? UserFollowersQuery.Data)?.page?.followers?.mapNotNull {follower-> follower?.let { UserModel().also { model -> model.id = it.id model.name = it.name model.avatar = it.avatar?.userAvatar?.toModel() } } } else (data as? UserFollowingQuery.Data)?.page?.following?.mapNotNull {following-> following?.let { UserModel().also { model -> model.id = it.id model.name = it.name model.avatar = it.avatar?.userAvatar?.toModel() } } } }.observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(it)) }, { Timber.e(it) callback.invoke(Resource.error(it.message , null, it)) }) compositeDisposable.add(disposable) } override fun getUserFavourite( field: UserFavouriteField, compositeDisposable: CompositeDisposable, callback: (Resource<List<BaseModel>>) -> Unit ) { val disposable = baseGraphRepository.request(field.toQueryOrMutation()) .map { it.data?.user?.favourites?.let { fav -> fav.anime?.nodes?.mapNotNull { node -> node?.takeIf { if (field.canShowAdult) true else it.onMedia.mediaContent.isAdult == false }?.onMedia?.mediaContent?.toModel() } ?: fav.manga?.nodes?.mapNotNull { node -> node?.takeIf { if (field.canShowAdult) true else it.onMedia.mediaContent.isAdult == false }?.onMedia?.mediaContent?.toModel() } ?: fav.characters?.nodes?.mapNotNull { node -> node?.onCharacter?.narrowCharacterContent?.let { CharacterModel().also { model -> model.id = it.id model.name = it.name?.let { CharacterNameModel(it.full) } model.image = it.image?.characterImage?.toModel() } } } ?: fav.staff?.nodes?.mapNotNull { map -> map?.onStaff?.narrowStaffContent?.let { StaffModel().also { model -> model.id = it.id model.name = it.name?.let { StaffNameModel(it.full) } model.image = it.image?.staffImage?.toModel() } } } ?: fav.studios?.nodes?.mapNotNull { map -> map?.onStudio?.studioContent?.let { StudioModel().also { model -> model.id = it.id model.studioName = it.name model.media = it.media?.let { MediaConnectionModel().also { mediaConnection -> mediaConnection.nodes = it.nodes?.mapNotNull { it?.takeIf { if (field.canShowAdult) true else it.mediaContent.isAdult == false }?.mediaContent?.toModel() } } } } } } } }.observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(it)) }, { Timber.e(it) callback.invoke(Resource.error(it.message , null, it)) }) compositeDisposable.add(disposable) } override fun getUserFriend( field: UserFriendField, compositeDisposable: CompositeDisposable, callback: ((Resource<List<UserModel>>) -> Unit) ) { val disposable = baseGraphRepository.request(field.toQueryOrMutation()) .map { response -> val data = response.data if (data is UserFollowersQuery.Data) (data as? UserFollowersQuery.Data)?.page?.followers?.mapNotNull { follower -> follower?.let { UserModel().also { model -> model.id = it.id model.name = it.name model.avatar = it.avatar?.userAvatar?.toModel() model.isFollower = it.isFollower ?: false model.isFollowing = it.isFollowing ?: false } } } else (data as? UserFollowingQuery.Data)?.page?.following?.mapNotNull { following -> following?.let { UserModel().also { model -> model.id = it.id model.name = it.name model.avatar = it.avatar?.userAvatar?.toModel() model.isFollower = it.isFollower ?: false model.isFollowing = it.isFollowing ?: false } } } }.observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.invoke(Resource.success(it)) }, { Timber.e(it) callback.invoke(Resource.error(it.message , null, it)) }) compositeDisposable.add(disposable) } }
48.675862
120
0.441485
a46da51d225570e29c6e437d3efe824650825377
39,533
sql
SQL
flarum.sql
maximusblade/Msunery
4015f3e1d1083de01395da3548ee29d7c2f48d09
[ "MIT" ]
null
null
null
flarum.sql
maximusblade/Msunery
4015f3e1d1083de01395da3548ee29d7c2f48d09
[ "MIT" ]
null
null
null
flarum.sql
maximusblade/Msunery
4015f3e1d1083de01395da3548ee29d7c2f48d09
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.0-dev -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Nov 11, 2019 at 02:30 PM -- Server version: 5.7.22 -- PHP Version: 7.3.4 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: `flarum` -- -- -------------------------------------------------------- -- -- Table structure for table `access_tokens` -- CREATE TABLE `access_tokens` ( `token` varchar(40) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` int(10) UNSIGNED NOT NULL, `last_activity_at` datetime NOT NULL, `lifetime_seconds` int(11) NOT NULL, `created_at` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `access_tokens` -- INSERT INTO `access_tokens` (`token`, `user_id`, `last_activity_at`, `lifetime_seconds`, `created_at`) VALUES ('4OCSgGi7n1ObTCHOgXoiA6YVUq8WMybvGlnyARTH', 1, '2019-11-11 09:07:48', 157680000, '2019-11-11 09:06:30'); -- -------------------------------------------------------- -- -- Table structure for table `api_keys` -- CREATE TABLE `api_keys` ( `key` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `id` int(10) UNSIGNED NOT NULL, `allowed_ips` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `scopes` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `user_id` int(10) UNSIGNED DEFAULT NULL, `created_at` datetime NOT NULL, `last_activity_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `discussions` -- CREATE TABLE `discussions` ( `id` int(10) UNSIGNED NOT NULL, `title` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL, `comment_count` int(10) UNSIGNED NOT NULL DEFAULT '0', `participant_count` int(10) UNSIGNED NOT NULL DEFAULT '0', `post_number_index` int(10) UNSIGNED NOT NULL DEFAULT '0', `created_at` datetime NOT NULL, `user_id` int(10) UNSIGNED DEFAULT NULL, `first_post_id` int(10) UNSIGNED DEFAULT NULL, `last_posted_at` datetime DEFAULT NULL, `last_posted_user_id` int(10) UNSIGNED DEFAULT NULL, `last_post_id` int(10) UNSIGNED DEFAULT NULL, `last_post_number` int(10) UNSIGNED DEFAULT NULL, `hidden_at` datetime DEFAULT NULL, `hidden_user_id` int(10) UNSIGNED DEFAULT NULL, `slug` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `is_private` tinyint(1) NOT NULL DEFAULT '0', `is_approved` tinyint(1) NOT NULL DEFAULT '1', `is_locked` tinyint(1) NOT NULL DEFAULT '0', `is_sticky` tinyint(1) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `discussions` -- INSERT INTO `discussions` (`id`, `title`, `comment_count`, `participant_count`, `post_number_index`, `created_at`, `user_id`, `first_post_id`, `last_posted_at`, `last_posted_user_id`, `last_post_id`, `last_post_number`, `hidden_at`, `hidden_user_id`, `slug`, `is_private`, `is_approved`, `is_locked`, `is_sticky`) VALUES (1, 'This is a new table with columns.', 2, 1, 3, '2019-10-29 09:01:03', 1, 1, '2019-10-29 09:01:19', 1, 2, 2, NULL, NULL, 'this-is-a-new-table-with-columns', 0, 1, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `discussion_tag` -- CREATE TABLE `discussion_tag` ( `discussion_id` int(10) UNSIGNED NOT NULL, `tag_id` int(10) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `discussion_tag` -- INSERT INTO `discussion_tag` (`discussion_id`, `tag_id`) VALUES (1, 1); -- -------------------------------------------------------- -- -- Table structure for table `discussion_user` -- CREATE TABLE `discussion_user` ( `user_id` int(10) UNSIGNED NOT NULL, `discussion_id` int(10) UNSIGNED NOT NULL, `last_read_at` datetime DEFAULT NULL, `last_read_post_number` int(10) UNSIGNED DEFAULT NULL, `subscription` enum('follow','ignore') COLLATE utf8mb4_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `discussion_user` -- INSERT INTO `discussion_user` (`user_id`, `discussion_id`, `last_read_at`, `last_read_post_number`, `subscription`) VALUES (1, 1, '2019-10-29 09:02:10', 3, NULL); -- -------------------------------------------------------- -- -- Table structure for table `email_tokens` -- CREATE TABLE `email_tokens` ( `token` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` int(10) UNSIGNED NOT NULL, `created_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `flags` -- CREATE TABLE `flags` ( `id` int(10) UNSIGNED NOT NULL, `post_id` int(10) UNSIGNED NOT NULL, `type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` int(10) UNSIGNED DEFAULT NULL, `reason` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `reason_detail` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `groups` -- CREATE TABLE `groups` ( `id` int(10) UNSIGNED NOT NULL, `name_singular` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `name_plural` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `color` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `icon` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `groups` -- INSERT INTO `groups` (`id`, `name_singular`, `name_plural`, `color`, `icon`) VALUES (1, 'Admin', 'Admins', '#B72A2A', 'fas fa-wrench'), (2, 'Guest', 'Guests', NULL, NULL), (3, 'Member', 'Members', NULL, NULL), (4, 'Mod', 'Mods', '#80349E', 'fas fa-bolt'); -- -------------------------------------------------------- -- -- Table structure for table `group_permission` -- CREATE TABLE `group_permission` ( `group_id` int(10) UNSIGNED NOT NULL, `permission` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `group_permission` -- INSERT INTO `group_permission` (`group_id`, `permission`) VALUES (2, 'viewDiscussions'), (3, 'discussion.flagPosts'), (3, 'discussion.likePosts'), (3, 'discussion.reply'), (3, 'discussion.replyWithoutApproval'), (3, 'discussion.startWithoutApproval'), (3, 'startDiscussion'), (3, 'viewUserList'), (4, 'discussion.approvePosts'), (4, 'discussion.editPosts'), (4, 'discussion.hide'), (4, 'discussion.hidePosts'), (4, 'discussion.lock'), (4, 'discussion.rename'), (4, 'discussion.sticky'), (4, 'discussion.tag'), (4, 'discussion.viewFlags'), (4, 'discussion.viewIpsPosts'), (4, 'user.suspend'), (4, 'user.viewLastSeenAt'); -- -------------------------------------------------------- -- -- Table structure for table `group_user` -- CREATE TABLE `group_user` ( `user_id` int(10) UNSIGNED NOT NULL, `group_id` int(10) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `group_user` -- INSERT INTO `group_user` (`user_id`, `group_id`) VALUES (1, 1), (1, 4); -- -------------------------------------------------------- -- -- Table structure for table `login_providers` -- CREATE TABLE `login_providers` ( `id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED NOT NULL, `provider` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `identifier` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` datetime DEFAULT NULL, `last_login_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `extension` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`migration`, `extension`) VALUES ('2015_02_24_000000_create_access_tokens_table', NULL), ('2015_02_24_000000_create_api_keys_table', NULL), ('2015_02_24_000000_create_config_table', NULL), ('2015_02_24_000000_create_discussions_table', NULL), ('2015_02_24_000000_create_email_tokens_table', NULL), ('2015_02_24_000000_create_groups_table', NULL), ('2015_02_24_000000_create_notifications_table', NULL), ('2015_02_24_000000_create_password_tokens_table', NULL), ('2015_02_24_000000_create_permissions_table', NULL), ('2015_02_24_000000_create_posts_table', NULL), ('2015_02_24_000000_create_users_discussions_table', NULL), ('2015_02_24_000000_create_users_groups_table', NULL), ('2015_02_24_000000_create_users_table', NULL), ('2015_09_15_000000_create_auth_tokens_table', NULL), ('2015_09_20_224327_add_hide_to_discussions', NULL), ('2015_09_22_030432_rename_notification_read_time', NULL), ('2015_10_07_130531_rename_config_to_settings', NULL), ('2015_10_24_194000_add_ip_address_to_posts', NULL), ('2015_12_05_042721_change_access_tokens_columns', NULL), ('2015_12_17_194247_change_settings_value_column_to_text', NULL), ('2016_02_04_095452_add_slug_to_discussions', NULL), ('2017_04_07_114138_add_is_private_to_discussions', NULL), ('2017_04_07_114138_add_is_private_to_posts', NULL), ('2018_01_11_093900_change_access_tokens_columns', NULL), ('2018_01_11_094000_change_access_tokens_add_foreign_keys', NULL), ('2018_01_11_095000_change_api_keys_columns', NULL), ('2018_01_11_101800_rename_auth_tokens_to_registration_tokens', NULL), ('2018_01_11_102000_change_registration_tokens_rename_id_to_token', NULL), ('2018_01_11_102100_change_registration_tokens_created_at_to_datetime', NULL), ('2018_01_11_120604_change_posts_table_to_innodb', NULL), ('2018_01_11_155200_change_discussions_rename_columns', NULL), ('2018_01_11_155300_change_discussions_add_foreign_keys', NULL), ('2018_01_15_071700_rename_users_discussions_to_discussion_user', NULL), ('2018_01_15_071800_change_discussion_user_rename_columns', NULL), ('2018_01_15_071900_change_discussion_user_add_foreign_keys', NULL), ('2018_01_15_072600_change_email_tokens_rename_id_to_token', NULL), ('2018_01_15_072700_change_email_tokens_add_foreign_keys', NULL), ('2018_01_15_072800_change_email_tokens_created_at_to_datetime', NULL), ('2018_01_18_130400_rename_permissions_to_group_permission', NULL), ('2018_01_18_130500_change_group_permission_add_foreign_keys', NULL), ('2018_01_18_130600_rename_users_groups_to_group_user', NULL), ('2018_01_18_130700_change_group_user_add_foreign_keys', NULL), ('2018_01_18_133000_change_notifications_columns', NULL), ('2018_01_18_133100_change_notifications_add_foreign_keys', NULL), ('2018_01_18_134400_change_password_tokens_rename_id_to_token', NULL), ('2018_01_18_134500_change_password_tokens_add_foreign_keys', NULL), ('2018_01_18_134600_change_password_tokens_created_at_to_datetime', NULL), ('2018_01_18_135000_change_posts_rename_columns', NULL), ('2018_01_18_135100_change_posts_add_foreign_keys', NULL), ('2018_01_30_112238_add_fulltext_index_to_discussions_title', NULL), ('2018_01_30_220100_create_post_user_table', NULL), ('2018_01_30_222900_change_users_rename_columns', NULL), ('2018_07_21_000000_seed_default_groups', NULL), ('2018_07_21_000100_seed_default_group_permissions', NULL), ('2018_09_15_041340_add_users_indicies', NULL), ('2018_09_15_041828_add_discussions_indicies', NULL), ('2018_09_15_043337_add_notifications_indices', NULL), ('2018_09_15_043621_add_posts_indices', NULL), ('2018_09_22_004100_change_registration_tokens_columns', NULL), ('2018_09_22_004200_create_login_providers_table', NULL), ('2018_10_08_144700_add_shim_prefix_to_group_icons', NULL), ('2019_06_24_145100_change_posts_content_column_to_mediumtext', NULL), ('2015_09_21_011527_add_is_approved_to_discussions', 'flarum-approval'), ('2015_09_21_011706_add_is_approved_to_posts', 'flarum-approval'), ('2017_07_22_000000_add_default_permissions', 'flarum-approval'), ('2018_09_29_060444_replace_emoji_shorcuts_with_unicode', 'flarum-emoji'), ('2015_09_02_000000_add_flags_read_time_to_users_table', 'flarum-flags'), ('2015_09_02_000000_create_flags_table', 'flarum-flags'), ('2017_07_22_000000_add_default_permissions', 'flarum-flags'), ('2018_06_27_101500_change_flags_rename_time_to_created_at', 'flarum-flags'), ('2018_06_27_101600_change_flags_add_foreign_keys', 'flarum-flags'), ('2018_06_27_105100_change_users_rename_flags_read_time_to_read_flags_at', 'flarum-flags'), ('2018_09_15_043621_add_flags_indices', 'flarum-flags'), ('2015_05_11_000000_create_posts_likes_table', 'flarum-likes'), ('2015_09_04_000000_add_default_like_permissions', 'flarum-likes'), ('2018_06_27_100600_rename_posts_likes_to_post_likes', 'flarum-likes'), ('2018_06_27_100700_change_post_likes_add_foreign_keys', 'flarum-likes'), ('2015_02_24_000000_add_locked_to_discussions', 'flarum-lock'), ('2017_07_22_000000_add_default_permissions', 'flarum-lock'), ('2018_09_15_043621_add_discussions_indices', 'flarum-lock'), ('2015_05_11_000000_create_mentions_posts_table', 'flarum-mentions'), ('2015_05_11_000000_create_mentions_users_table', 'flarum-mentions'), ('2018_06_27_102000_rename_mentions_posts_to_post_mentions_post', 'flarum-mentions'), ('2018_06_27_102100_rename_mentions_users_to_post_mentions_user', 'flarum-mentions'), ('2018_06_27_102200_change_post_mentions_post_rename_mentions_id_to_mentions_post_id', 'flarum-mentions'), ('2018_06_27_102300_change_post_mentions_post_add_foreign_keys', 'flarum-mentions'), ('2018_06_27_102400_change_post_mentions_user_rename_mentions_id_to_mentions_user_id', 'flarum-mentions'), ('2018_06_27_102500_change_post_mentions_user_add_foreign_keys', 'flarum-mentions'), ('2015_02_24_000000_add_sticky_to_discussions', 'flarum-sticky'), ('2017_07_22_000000_add_default_permissions', 'flarum-sticky'), ('2018_09_15_043621_add_discussions_indices', 'flarum-sticky'), ('2015_05_11_000000_add_subscription_to_users_discussions_table', 'flarum-subscriptions'), ('2015_05_11_000000_add_suspended_until_to_users_table', 'flarum-suspend'), ('2015_09_14_000000_rename_suspended_until_column', 'flarum-suspend'), ('2017_07_22_000000_add_default_permissions', 'flarum-suspend'), ('2018_06_27_111400_change_users_rename_suspend_until_to_suspended_until', 'flarum-suspend'), ('2015_02_24_000000_create_discussions_tags_table', 'flarum-tags'), ('2015_02_24_000000_create_tags_table', 'flarum-tags'), ('2015_02_24_000000_create_users_tags_table', 'flarum-tags'), ('2015_02_24_000000_set_default_settings', 'flarum-tags'), ('2015_10_19_061223_make_slug_unique', 'flarum-tags'), ('2017_07_22_000000_add_default_permissions', 'flarum-tags'), ('2018_06_27_085200_change_tags_columns', 'flarum-tags'), ('2018_06_27_085300_change_tags_add_foreign_keys', 'flarum-tags'), ('2018_06_27_090400_rename_users_tags_to_tag_user', 'flarum-tags'), ('2018_06_27_100100_change_tag_user_rename_read_time_to_marked_as_read_at', 'flarum-tags'), ('2018_06_27_100200_change_tag_user_add_foreign_keys', 'flarum-tags'), ('2018_06_27_103000_rename_discussions_tags_to_discussion_tag', 'flarum-tags'), ('2018_06_27_103100_add_discussion_tag_foreign_keys', 'flarum-tags'), ('2019_04_21_000000_add_icon_to_tags_table', 'flarum-tags'), ('2015_09_15_000000_add_twitter_id_to_users_table', 'flarum-auth-twitter'), ('2018_09_22_000000_migrate_users_twitter_id_to_login_providers', 'flarum-auth-twitter'), ('2018_09_22_000001_drop_users_twitter_id_column', 'flarum-auth-twitter'); -- -------------------------------------------------------- -- -- Table structure for table `notifications` -- CREATE TABLE `notifications` ( `id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED NOT NULL, `from_user_id` int(10) UNSIGNED DEFAULT NULL, `type` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `subject_id` int(10) UNSIGNED DEFAULT NULL, `data` blob, `created_at` datetime NOT NULL, `is_deleted` tinyint(1) NOT NULL DEFAULT '0', `read_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `password_tokens` -- CREATE TABLE `password_tokens` ( `token` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` int(10) UNSIGNED NOT NULL, `created_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `posts` -- CREATE TABLE `posts` ( `id` int(10) UNSIGNED NOT NULL, `discussion_id` int(10) UNSIGNED NOT NULL, `number` int(10) UNSIGNED DEFAULT NULL, `created_at` datetime NOT NULL, `user_id` int(10) UNSIGNED DEFAULT NULL, `type` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `content` mediumtext COLLATE utf8mb4_unicode_ci COMMENT ' ', `edited_at` datetime DEFAULT NULL, `edited_user_id` int(10) UNSIGNED DEFAULT NULL, `hidden_at` datetime DEFAULT NULL, `hidden_user_id` int(10) UNSIGNED DEFAULT NULL, `ip_address` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `is_private` tinyint(1) NOT NULL DEFAULT '0', `is_approved` tinyint(1) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `posts` -- INSERT INTO `posts` (`id`, `discussion_id`, `number`, `created_at`, `user_id`, `type`, `content`, `edited_at`, `edited_user_id`, `hidden_at`, `hidden_user_id`, `ip_address`, `is_private`, `is_approved`) VALUES (1, 1, 1, '2019-10-29 09:01:03', 1, 'comment', '<t><p>Flarum is and always will be 100% free and open-source under the MIT license. Fork it on GitHub and help mak<br/>\nFlarum is and always will be 100% free and open-source under the MIT license. Fork it on GitHub and help mak</p>\n\n<p>Flarum is and always will be 100% free and open-source under the MIT license. Fork it on GitHub and help makFlarum is and always will be 100% free and open-source under the MIT license. Fork it on GitHub and help mak</p></t>', NULL, NULL, NULL, NULL, '127.0.0.1', 0, 1), (2, 1, 2, '2019-10-29 09:01:19', 1, 'comment', '<t><p>stack over flow</p></t>', NULL, NULL, NULL, NULL, '127.0.0.1', 0, 1), (3, 1, 3, '2019-10-29 09:02:05', 1, 'discussionRenamed', '[\"This is a forum Sample\",\"This is a new table with columns.\"]', NULL, NULL, NULL, NULL, NULL, 0, 1); -- -------------------------------------------------------- -- -- Table structure for table `post_likes` -- CREATE TABLE `post_likes` ( `post_id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `post_likes` -- INSERT INTO `post_likes` (`post_id`, `user_id`) VALUES (2, 1); -- -------------------------------------------------------- -- -- Table structure for table `post_mentions_post` -- CREATE TABLE `post_mentions_post` ( `post_id` int(10) UNSIGNED NOT NULL, `mentions_post_id` int(10) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `post_mentions_user` -- CREATE TABLE `post_mentions_user` ( `post_id` int(10) UNSIGNED NOT NULL, `mentions_user_id` int(10) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `post_user` -- CREATE TABLE `post_user` ( `post_id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `registration_tokens` -- CREATE TABLE `registration_tokens` ( `token` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `payload` text COLLATE utf8mb4_unicode_ci, `created_at` datetime DEFAULT NULL, `provider` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `identifier` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `user_attributes` text COLLATE utf8mb4_unicode_ci ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `settings` -- CREATE TABLE `settings` ( `key` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `value` text COLLATE utf8mb4_unicode_ci ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `settings` -- INSERT INTO `settings` (`key`, `value`) VALUES ('allow_post_editing', 'reply'), ('allow_renaming', '10'), ('allow_sign_up', '1'), ('custom_less', ''), ('default_locale', 'en'), ('default_route', '/all'), ('extensions_enabled', '[\"flarum-approval\",\"flarum-bbcode\",\"flarum-emoji\",\"flarum-lang-english\",\"flarum-flags\",\"flarum-likes\",\"flarum-lock\",\"flarum-markdown\",\"flarum-mentions\",\"flarum-statistics\",\"flarum-sticky\",\"flarum-subscriptions\",\"flarum-suspend\",\"flarum-tags\"]'), ('flarum-tags.max_primary_tags', '1'), ('flarum-tags.max_secondary_tags', '3'), ('flarum-tags.min_primary_tags', '1'), ('flarum-tags.min_secondary_tags', '0'), ('forum_description', ''), ('forum_title', 'SpellThis'), ('mail_driver', 'mail'), ('mail_from', 'noreply@flarum.nz'), ('show_language_selector', '1'), ('theme_colored_header', '1'), ('theme_dark_mode', '0'), ('theme_primary_color', '#4D698E'), ('theme_secondary_color', '#4D698E'), ('version', '0.1.0-beta.10'), ('welcome_message', 'This is beta software and you should not use it in production.\nthis is a great forum'), ('welcome_title', 'Welcome to SpellThis'); -- -------------------------------------------------------- -- -- Table structure for table `tags` -- CREATE TABLE `tags` ( `id` int(10) UNSIGNED NOT NULL, `name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `slug` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `description` text COLLATE utf8mb4_unicode_ci, `color` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `background_path` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `background_mode` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `position` int(11) DEFAULT NULL, `parent_id` int(10) UNSIGNED DEFAULT NULL, `default_sort` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `is_restricted` tinyint(1) NOT NULL DEFAULT '0', `is_hidden` tinyint(1) NOT NULL DEFAULT '0', `discussion_count` int(10) UNSIGNED NOT NULL DEFAULT '0', `last_posted_at` datetime DEFAULT NULL, `last_posted_discussion_id` int(10) UNSIGNED DEFAULT NULL, `last_posted_user_id` int(10) UNSIGNED DEFAULT NULL, `icon` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `tags` -- INSERT INTO `tags` (`id`, `name`, `slug`, `description`, `color`, `background_path`, `background_mode`, `position`, `parent_id`, `default_sort`, `is_restricted`, `is_hidden`, `discussion_count`, `last_posted_at`, `last_posted_discussion_id`, `last_posted_user_id`, `icon`) VALUES (1, 'General', 'general', NULL, '#888', NULL, NULL, 0, NULL, NULL, 0, 0, 1, '2019-10-29 09:01:03', 1, 1, NULL); -- -------------------------------------------------------- -- -- Table structure for table `tag_user` -- CREATE TABLE `tag_user` ( `user_id` int(10) UNSIGNED NOT NULL, `tag_id` int(10) UNSIGNED NOT NULL, `marked_as_read_at` datetime DEFAULT NULL, `is_hidden` tinyint(1) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(10) UNSIGNED NOT NULL, `username` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL, `is_email_confirmed` tinyint(1) NOT NULL DEFAULT '0', `password` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `bio` text COLLATE utf8mb4_unicode_ci, `avatar_url` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `preferences` blob, `joined_at` datetime DEFAULT NULL, `last_seen_at` datetime DEFAULT NULL, `marked_all_as_read_at` datetime DEFAULT NULL, `read_notifications_at` datetime DEFAULT NULL, `discussion_count` int(10) UNSIGNED NOT NULL DEFAULT '0', `comment_count` int(10) UNSIGNED NOT NULL DEFAULT '0', `read_flags_at` datetime DEFAULT NULL, `suspended_until` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `email`, `is_email_confirmed`, `password`, `bio`, `avatar_url`, `preferences`, `joined_at`, `last_seen_at`, `marked_all_as_read_at`, `read_notifications_at`, `discussion_count`, `comment_count`, `read_flags_at`, `suspended_until`) VALUES (1, 'admin', 'admin@admin.com', 1, '$2y$10$WnFsbL3S/XykhV71kkl8/elLmiX6nTF.He8K6CySBUqAiC/z0GXQu', NULL, '8k3KALTQJXYapQh7.png', 0x7b226e6f746966795f64697363757373696f6e52656e616d65645f616c657274223a747275652c226e6f746966795f706f73744c696b65645f616c657274223a747275652c226e6f746966795f64697363757373696f6e4c6f636b65645f616c657274223a747275652c226e6f746966795f706f73744d656e74696f6e65645f616c657274223a747275652c226e6f746966795f706f73744d656e74696f6e65645f656d61696c223a66616c73652c226e6f746966795f757365724d656e74696f6e65645f616c657274223a747275652c226e6f746966795f757365724d656e74696f6e65645f656d61696c223a66616c73652c226e6f746966795f6e6577506f73745f616c657274223a747275652c226e6f746966795f6e6577506f73745f656d61696c223a747275652c226e6f746966795f7573657253757370656e6465645f616c657274223a747275652c226e6f746966795f75736572556e73757370656e6465645f616c657274223a747275652c22666f6c6c6f7741667465725265706c79223a747275652c22646973636c6f73654f6e6c696e65223a747275652c22696e64657850726f66696c65223a747275652c226c6f63616c65223a6e756c6c7d, '2019-10-29 08:56:18', '2019-11-11 09:07:48', NULL, '2019-10-29 09:02:31', 1, 2, '2019-10-29 09:02:32', NULL); -- -- Indexes for dumped tables -- -- -- Indexes for table `access_tokens` -- ALTER TABLE `access_tokens` ADD PRIMARY KEY (`token`), ADD KEY `access_tokens_user_id_foreign` (`user_id`); -- -- Indexes for table `api_keys` -- ALTER TABLE `api_keys` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `api_keys_key_unique` (`key`), ADD KEY `api_keys_user_id_foreign` (`user_id`); -- -- Indexes for table `discussions` -- ALTER TABLE `discussions` ADD PRIMARY KEY (`id`), ADD KEY `discussions_hidden_user_id_foreign` (`hidden_user_id`), ADD KEY `discussions_first_post_id_foreign` (`first_post_id`), ADD KEY `discussions_last_post_id_foreign` (`last_post_id`), ADD KEY `discussions_last_posted_at_index` (`last_posted_at`), ADD KEY `discussions_last_posted_user_id_index` (`last_posted_user_id`), ADD KEY `discussions_created_at_index` (`created_at`), ADD KEY `discussions_user_id_index` (`user_id`), ADD KEY `discussions_comment_count_index` (`comment_count`), ADD KEY `discussions_participant_count_index` (`participant_count`), ADD KEY `discussions_hidden_at_index` (`hidden_at`), ADD KEY `discussions_is_locked_index` (`is_locked`), ADD KEY `discussions_is_sticky_created_at_index` (`is_sticky`,`created_at`); ALTER TABLE `discussions` ADD FULLTEXT KEY `title` (`title`); -- -- Indexes for table `discussion_tag` -- ALTER TABLE `discussion_tag` ADD PRIMARY KEY (`discussion_id`,`tag_id`), ADD KEY `discussion_tag_tag_id_foreign` (`tag_id`); -- -- Indexes for table `discussion_user` -- ALTER TABLE `discussion_user` ADD PRIMARY KEY (`user_id`,`discussion_id`), ADD KEY `discussion_user_discussion_id_foreign` (`discussion_id`); -- -- Indexes for table `email_tokens` -- ALTER TABLE `email_tokens` ADD PRIMARY KEY (`token`), ADD KEY `email_tokens_user_id_foreign` (`user_id`); -- -- Indexes for table `flags` -- ALTER TABLE `flags` ADD PRIMARY KEY (`id`), ADD KEY `flags_post_id_foreign` (`post_id`), ADD KEY `flags_user_id_foreign` (`user_id`), ADD KEY `flags_created_at_index` (`created_at`); -- -- Indexes for table `groups` -- ALTER TABLE `groups` ADD PRIMARY KEY (`id`); -- -- Indexes for table `group_permission` -- ALTER TABLE `group_permission` ADD PRIMARY KEY (`group_id`,`permission`); -- -- Indexes for table `group_user` -- ALTER TABLE `group_user` ADD PRIMARY KEY (`user_id`,`group_id`), ADD KEY `group_user_group_id_foreign` (`group_id`); -- -- Indexes for table `login_providers` -- ALTER TABLE `login_providers` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `login_providers_provider_identifier_unique` (`provider`,`identifier`), ADD KEY `login_providers_user_id_foreign` (`user_id`); -- -- Indexes for table `notifications` -- ALTER TABLE `notifications` ADD PRIMARY KEY (`id`), ADD KEY `notifications_from_user_id_foreign` (`from_user_id`), ADD KEY `notifications_user_id_index` (`user_id`); -- -- Indexes for table `password_tokens` -- ALTER TABLE `password_tokens` ADD PRIMARY KEY (`token`), ADD KEY `password_tokens_user_id_foreign` (`user_id`); -- -- Indexes for table `posts` -- ALTER TABLE `posts` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `posts_discussion_id_number_unique` (`discussion_id`,`number`), ADD KEY `posts_edited_user_id_foreign` (`edited_user_id`), ADD KEY `posts_hidden_user_id_foreign` (`hidden_user_id`), ADD KEY `posts_discussion_id_number_index` (`discussion_id`,`number`), ADD KEY `posts_discussion_id_created_at_index` (`discussion_id`,`created_at`), ADD KEY `posts_user_id_created_at_index` (`user_id`,`created_at`); ALTER TABLE `posts` ADD FULLTEXT KEY `content` (`content`); -- -- Indexes for table `post_likes` -- ALTER TABLE `post_likes` ADD PRIMARY KEY (`post_id`,`user_id`), ADD KEY `post_likes_user_id_foreign` (`user_id`); -- -- Indexes for table `post_mentions_post` -- ALTER TABLE `post_mentions_post` ADD PRIMARY KEY (`post_id`,`mentions_post_id`), ADD KEY `post_mentions_post_mentions_post_id_foreign` (`mentions_post_id`); -- -- Indexes for table `post_mentions_user` -- ALTER TABLE `post_mentions_user` ADD PRIMARY KEY (`post_id`,`mentions_user_id`), ADD KEY `post_mentions_user_mentions_user_id_foreign` (`mentions_user_id`); -- -- Indexes for table `post_user` -- ALTER TABLE `post_user` ADD PRIMARY KEY (`post_id`,`user_id`), ADD KEY `post_user_user_id_foreign` (`user_id`); -- -- Indexes for table `registration_tokens` -- ALTER TABLE `registration_tokens` ADD PRIMARY KEY (`token`); -- -- Indexes for table `settings` -- ALTER TABLE `settings` ADD PRIMARY KEY (`key`); -- -- Indexes for table `tags` -- ALTER TABLE `tags` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `tags_slug_unique` (`slug`), ADD KEY `tags_parent_id_foreign` (`parent_id`), ADD KEY `tags_last_posted_user_id_foreign` (`last_posted_user_id`), ADD KEY `tags_last_posted_discussion_id_foreign` (`last_posted_discussion_id`); -- -- Indexes for table `tag_user` -- ALTER TABLE `tag_user` ADD PRIMARY KEY (`user_id`,`tag_id`), ADD KEY `tag_user_tag_id_foreign` (`tag_id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_username_unique` (`username`), ADD UNIQUE KEY `users_email_unique` (`email`), ADD KEY `users_joined_at_index` (`joined_at`), ADD KEY `users_last_seen_at_index` (`last_seen_at`), ADD KEY `users_discussion_count_index` (`discussion_count`), ADD KEY `users_comment_count_index` (`comment_count`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `api_keys` -- ALTER TABLE `api_keys` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `discussions` -- ALTER TABLE `discussions` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `flags` -- ALTER TABLE `flags` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `groups` -- ALTER TABLE `groups` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `login_providers` -- ALTER TABLE `login_providers` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `notifications` -- ALTER TABLE `notifications` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `posts` -- ALTER TABLE `posts` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `tags` -- ALTER TABLE `tags` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- Constraints for dumped tables -- -- -- Constraints for table `access_tokens` -- ALTER TABLE `access_tokens` ADD CONSTRAINT `access_tokens_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `api_keys` -- ALTER TABLE `api_keys` ADD CONSTRAINT `api_keys_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `discussions` -- ALTER TABLE `discussions` ADD CONSTRAINT `discussions_first_post_id_foreign` FOREIGN KEY (`first_post_id`) REFERENCES `posts` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `discussions_hidden_user_id_foreign` FOREIGN KEY (`hidden_user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `discussions_last_post_id_foreign` FOREIGN KEY (`last_post_id`) REFERENCES `posts` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `discussions_last_posted_user_id_foreign` FOREIGN KEY (`last_posted_user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `discussions_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL; -- -- Constraints for table `discussion_tag` -- ALTER TABLE `discussion_tag` ADD CONSTRAINT `discussion_tag_discussion_id_foreign` FOREIGN KEY (`discussion_id`) REFERENCES `discussions` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `discussion_tag_tag_id_foreign` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE; -- -- Constraints for table `discussion_user` -- ALTER TABLE `discussion_user` ADD CONSTRAINT `discussion_user_discussion_id_foreign` FOREIGN KEY (`discussion_id`) REFERENCES `discussions` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `discussion_user_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `email_tokens` -- ALTER TABLE `email_tokens` ADD CONSTRAINT `email_tokens_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `flags` -- ALTER TABLE `flags` ADD CONSTRAINT `flags_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `flags_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `group_permission` -- ALTER TABLE `group_permission` ADD CONSTRAINT `group_permission_group_id_foreign` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE; -- -- Constraints for table `group_user` -- ALTER TABLE `group_user` ADD CONSTRAINT `group_user_group_id_foreign` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `group_user_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `login_providers` -- ALTER TABLE `login_providers` ADD CONSTRAINT `login_providers_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `notifications` -- ALTER TABLE `notifications` ADD CONSTRAINT `notifications_from_user_id_foreign` FOREIGN KEY (`from_user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `notifications_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `password_tokens` -- ALTER TABLE `password_tokens` ADD CONSTRAINT `password_tokens_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `posts` -- ALTER TABLE `posts` ADD CONSTRAINT `posts_edited_user_id_foreign` FOREIGN KEY (`edited_user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `posts_hidden_user_id_foreign` FOREIGN KEY (`hidden_user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `posts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL; -- -- Constraints for table `post_likes` -- ALTER TABLE `post_likes` ADD CONSTRAINT `post_likes_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `post_likes_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `post_mentions_post` -- ALTER TABLE `post_mentions_post` ADD CONSTRAINT `post_mentions_post_mentions_post_id_foreign` FOREIGN KEY (`mentions_post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `post_mentions_post_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE; -- -- Constraints for table `post_mentions_user` -- ALTER TABLE `post_mentions_user` ADD CONSTRAINT `post_mentions_user_mentions_user_id_foreign` FOREIGN KEY (`mentions_user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `post_mentions_user_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE; -- -- Constraints for table `post_user` -- ALTER TABLE `post_user` ADD CONSTRAINT `post_user_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `post_user_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; -- -- Constraints for table `tags` -- ALTER TABLE `tags` ADD CONSTRAINT `tags_last_posted_discussion_id_foreign` FOREIGN KEY (`last_posted_discussion_id`) REFERENCES `discussions` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `tags_last_posted_user_id_foreign` FOREIGN KEY (`last_posted_user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL, ADD CONSTRAINT `tags_parent_id_foreign` FOREIGN KEY (`parent_id`) REFERENCES `tags` (`id`) ON DELETE SET NULL; -- -- Constraints for table `tag_user` -- ALTER TABLE `tag_user` ADD CONSTRAINT `tag_user_tag_id_foreign` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `tag_user_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; 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 */;
38.531189
1,143
0.737915
753abb76c9434929486c0386e16b4501a1fbed73
1,359
h
C
classdump_Safari/BookmarksURLMatchingOperation.h
inket/smartPins
2f9a68dccf8b605f863a680488ed4c6c428f4a52
[ "MIT" ]
2
2016-09-29T09:50:04.000Z
2016-09-29T19:39:11.000Z
classdump_Safari/BookmarksURLMatchingOperation.h
inket/smartPins
2f9a68dccf8b605f863a680488ed4c6c428f4a52
[ "MIT" ]
null
null
null
classdump_Safari/BookmarksURLMatchingOperation.h
inket/smartPins
2f9a68dccf8b605f863a680488ed4c6c428f4a52
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <Foundation/NSOperation.h> #import <Safari/CacheableResultBookmarksOperation-Protocol.h> #import <Safari/ReusableResultBookmarksOperation-Protocol.h> @class NSString, NSURL, WebBookmarkLeaf, WebBookmarkList; @protocol NSCopying; __attribute__((visibility("hidden"))) @interface BookmarksURLMatchingOperation : NSOperation <ReusableResultBookmarksOperation, CacheableResultBookmarksOperation> { WebBookmarkList *_bookmarkList; NSURL *_url; WebBookmarkLeaf *_result; } + (BOOL)cachedResultIsInvalidatedWhenBookmarksChange; @property(retain, nonatomic) WebBookmarkLeaf *result; // @synthesize result=_result; @property(readonly, nonatomic) NSURL *url; // @synthesize url=_url; @property(readonly, nonatomic) WebBookmarkList *bookmarkList; // @synthesize bookmarkList=_bookmarkList; - (void).cxx_destruct; @property(readonly, nonatomic) id <NSCopying> cacheKey; - (BOOL)canReuseResultOfOperation:(id)arg1; - (void)main; - (id)initWithBookmarkList:(id)arg1 url:(id)arg2; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
32.357143
124
0.777778
f026a358543c6c191a734341080f8d140032aa93
24,827
js
JavaScript
tests/acceptance/course/session/offerings-test.js
stopfstedt/common
0b6ad5dce02c780850e2db93b00ca1cef3ea70e6
[ "MIT" ]
2
2017-11-01T04:57:34.000Z
2020-07-15T19:29:07.000Z
tests/acceptance/course/session/offerings-test.js
ilios/common
435c88a44c89582da196f7d401e4d31bcc910ed2
[ "MIT" ]
1,517
2017-07-05T17:15:01.000Z
2022-03-31T20:57:55.000Z
tests/acceptance/course/session/offerings-test.js
Trott/common
ed22e988b75695acb333a707b3842276ec45c68f
[ "MIT" ]
9
2017-06-28T01:35:40.000Z
2019-03-19T21:44:27.000Z
import moment from 'moment'; import { module, test } from 'qunit'; import { setupAuthentication } from 'ilios-common'; import { setupApplicationTest } from 'ember-qunit'; import { setupMirage } from 'ember-cli-mirage/test-support'; import page from 'ilios-common/page-objects/session'; module('Acceptance | Session - Offerings', function (hooks) { setupApplicationTest(hooks); setupMirage(hooks); hooks.beforeEach(async function () { this.school = this.server.create('school'); this.user = await setupAuthentication({ school: this.school }); const program = this.server.create('program', { school: this.school }); const programYear = this.server.create('programYear', { program }); const cohort = this.server.create('cohort', { programYear }); const course = this.server.create('course', { cohorts: [cohort], school: this.school, directors: [this.user], }); this.server.create('sessionType', { school: this.school, }); const users = this.server.createList('user', 8); const instructorGroup1 = this.server.create('instructor-group', { users: [users[0], users[1], users[4], users[5]], school: this.school, }); const instructorGroup2 = this.server.create('instructor-group', { users: [users[2], users[3]], school: this.school, }); const learnerGroup1 = this.server.create('learner-group', { users: [users[0], users[1]], cohort, location: 'default 1', instructors: [this.user], url: 'https://iliosproject.org/', }); const learnerGroup2 = this.server.create('learner-group', { users: [users[2], users[3]], cohort, location: 'default 2', instructorGroups: [instructorGroup1], }); const session = this.server.create('session', { course }); this.today = moment().hour(9); this.offering1 = this.server.create('offering', { session, instructors: [users[4], users[5], users[6], users[7]], instructorGroups: [instructorGroup1, instructorGroup2], learnerGroups: [learnerGroup1, learnerGroup2], startDate: this.today.format(), endDate: this.today.clone().add(1, 'hour').format(), url: 'https://ucsf.edu/', }); this.offering2 = this.server.create('offering', { session, instructors: [users[6], users[7]], instructorGroups: [instructorGroup2], learnerGroups: [learnerGroup2], startDate: this.today.clone().add(1, 'day').format(), endDate: this.today.clone().add(1, 'day').add(1, 'hour').format(), }); this.offering3 = this.server.create('offering', { session, instructorGroups: [instructorGroup2], learnerGroups: [learnerGroup2], instructors: [], startDate: this.today.clone().add(2, 'days').format(), endDate: this.today.clone().add(3, 'days').add(1, 'hour').format(), url: 'https://example.edu/', }); }); test('basics', async function (assert) { assert.expect(2); await page.visit({ courseId: 1, sessionId: 1 }); assert.strictEqual(page.details.offerings.header.title, 'Offerings (3)'); assert.strictEqual(page.details.offerings.dateBlocks.length, 3); }); test('offering dates', async function (assert) { assert.expect(23); await page.visit({ courseId: 1, sessionId: 1 }); const blocks = page.details.offerings.dateBlocks; assert.ok(blocks[0].hasStartTime); assert.ok(blocks[0].hasEndTime); assert.notOk(blocks[0].hasMultiDay); assert.strictEqual(blocks[0].dayOfWeek, moment(this.offering1.startDate).format('dddd')); assert.strictEqual(blocks[0].dayOfMonth, moment(this.offering1.startDate).format('MMMM Do')); assert.strictEqual( blocks[0].startTime, 'Starts: ' + moment(this.offering1.startDate).format('LT') ); assert.strictEqual(blocks[0].endTime, 'Ends: ' + moment(this.offering1.endDate).format('LT')); assert.strictEqual(blocks[0].offerings.length, 1); assert.ok(blocks[1].hasStartTime); assert.ok(blocks[1].hasEndTime); assert.notOk(blocks[1].hasMultiDay); assert.strictEqual(blocks[1].dayOfWeek, moment(this.offering2.startDate).format('dddd')); assert.strictEqual(blocks[1].dayOfMonth, moment(this.offering2.startDate).format('MMMM Do')); assert.strictEqual( blocks[1].startTime, 'Starts: ' + moment(this.offering2.startDate).format('LT') ); assert.strictEqual(blocks[1].endTime, 'Ends: ' + moment(this.offering2.endDate).format('LT')); assert.strictEqual(blocks[1].offerings.length, 1); assert.notOk(blocks[2].hasStartTime); assert.notOk(blocks[2].hasEndTime); assert.ok(blocks[2].hasMultiDay); assert.strictEqual(blocks[2].dayOfWeek, moment(this.offering3.startDate).format('dddd')); assert.strictEqual(blocks[2].dayOfMonth, moment(this.offering3.startDate).format('MMMM Do')); const expectedText = 'Multiday ' + 'Starts ' + moment(this.offering3.startDate).format('dddd MMMM Do [@] LT') + ' Ends ' + moment(this.offering3.endDate).format('dddd MMMM Do [@] LT'); assert.strictEqual(blocks[2].offerings.length, 1); assert.strictEqual(blocks[2].multiDay, expectedText); }); test('offering details', async function (assert) { await page.visit({ courseId: 1, sessionId: 1 }); const blocks = page.details.offerings.dateBlocks; assert.strictEqual(blocks[0].offerings[0].learnerGroups.length, 2); assert.strictEqual(blocks[0].offerings[0].learnerGroups[0].title, 'learner group 0'); assert.strictEqual(blocks[0].offerings[0].learnerGroups[1].title, 'learner group 1'); assert.strictEqual(blocks[0].offerings[0].location, this.offering1.room); assert.strictEqual(blocks[0].offerings[0].url, this.offering1.url); assert.strictEqual(blocks[0].offerings[0].instructors.length, 8); assert.strictEqual( blocks[0].offerings[0].instructors[0].userNameInfo.fullName, '1 guy M. Mc1son' ); assert.strictEqual( blocks[0].offerings[0].instructors[1].userNameInfo.fullName, '2 guy M. Mc2son' ); assert.strictEqual( blocks[0].offerings[0].instructors[2].userNameInfo.fullName, '3 guy M. Mc3son' ); assert.strictEqual( blocks[0].offerings[0].instructors[3].userNameInfo.fullName, '4 guy M. Mc4son' ); assert.strictEqual( blocks[0].offerings[0].instructors[4].userNameInfo.fullName, '5 guy M. Mc5son' ); assert.strictEqual( blocks[0].offerings[0].instructors[5].userNameInfo.fullName, '6 guy M. Mc6son' ); assert.strictEqual( blocks[0].offerings[0].instructors[6].userNameInfo.fullName, '7 guy M. Mc7son' ); assert.strictEqual( blocks[0].offerings[0].instructors[7].userNameInfo.fullName, '8 guy M. Mc8son' ); assert.strictEqual(blocks[1].offerings[0].learnerGroups.length, 1); assert.strictEqual(blocks[1].offerings[0].learnerGroups[0].title, 'learner group 1'); assert.strictEqual(blocks[1].offerings[0].location, this.offering2.room); assert.strictEqual(blocks[1].offerings[0].instructors.length, 4); assert.strictEqual( blocks[1].offerings[0].instructors[0].userNameInfo.fullName, '3 guy M. Mc3son' ); assert.strictEqual( blocks[1].offerings[0].instructors[1].userNameInfo.fullName, '4 guy M. Mc4son' ); assert.strictEqual( blocks[1].offerings[0].instructors[2].userNameInfo.fullName, '7 guy M. Mc7son' ); assert.strictEqual( blocks[1].offerings[0].instructors[3].userNameInfo.fullName, '8 guy M. Mc8son' ); assert.strictEqual(blocks[2].offerings[0].learnerGroups.length, 1); assert.strictEqual(blocks[2].offerings[0].learnerGroups[0].title, 'learner group 1'); assert.strictEqual(blocks[2].offerings[0].location, this.offering3.room); assert.strictEqual(blocks[2].offerings[0].url, this.offering3.url); assert.strictEqual(blocks[2].offerings[0].instructors.length, 2); assert.strictEqual( blocks[2].offerings[0].instructors[0].userNameInfo.fullName, '3 guy M. Mc3son' ); assert.strictEqual( blocks[2].offerings[0].instructors[1].userNameInfo.fullName, '4 guy M. Mc4son' ); }); test('confirm removal message', async function (assert) { this.user.update({ administeredSchools: [this.school] }); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.dateBlocks[0].offerings[0].remove(); assert.ok(page.details.offerings.dateBlocks[0].offerings[0].hasRemoveConfirm); assert.strictEqual( page.details.offerings.dateBlocks[0].offerings[0].removeConfirmMessage, 'Are you sure you want to delete this offering with 2 learner groups? This action cannot be undone. Yes Cancel' ); }); test('remove offering', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(2); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.dateBlocks[0].offerings[0].remove(); await page.details.offerings.dateBlocks[0].offerings[0].confirmRemoval(); assert.strictEqual(page.details.offerings.header.title, 'Offerings (2)'); assert.strictEqual(page.details.offerings.dateBlocks.length, 2); }); test('cancel remove offering', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(2); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.dateBlocks[0].offerings[0].remove(); await page.details.offerings.dateBlocks[0].offerings[0].cancelRemoval(); assert.strictEqual(page.details.offerings.header.title, 'Offerings (3)'); assert.strictEqual(page.details.offerings.dateBlocks.length, 3); }); test('users can create a new offering single day', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(14); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.header.createNew(); const { offeringForm: form } = page.details.offerings; await page.details.offerings.singleOffering(); await form.startDate.datePicker.set(new Date(2011, 8, 11)); await form.startTime.timePicker.hour.select('2'); await form.startTime.timePicker.minute.select('15'); await form.startTime.timePicker.ampm.select('am'); await form.duration.hours.set(15); await form.duration.minutes.set(15); await form.location.set('Rm. 111'); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[0].add(); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[1].add(); await form.instructorManager.search.searchBox.set('guy'); await form.instructorManager.search.results.items[0].click(); await form.save(); const block = page.details.offerings.dateBlocks[0]; assert.ok(block.hasStartTime); assert.ok(block.hasEndTime); assert.notOk(block.hasMultiDay); assert.strictEqual(block.dayOfWeek, 'Sunday'); assert.strictEqual(block.dayOfMonth, 'September 11th'); assert.strictEqual(block.startTime, 'Starts: 2:15 AM'); assert.strictEqual(block.endTime, 'Ends: 5:30 PM'); assert.strictEqual(block.offerings.length, 1); assert.strictEqual(block.offerings[0].learnerGroups.length, 2); assert.strictEqual(block.offerings[0].learnerGroups[0].title, 'learner group 0'); assert.strictEqual(block.offerings[0].learnerGroups[1].title, 'learner group 1'); assert.strictEqual(block.offerings[0].location, 'Rm. 111'); assert.strictEqual(block.offerings[0].instructors.length, 1); assert.strictEqual(block.offerings[0].instructors[0].userNameInfo.fullName, '0 guy M. Mc0son'); }); test('users can create a new offering multi-day', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(13); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.header.createNew(); const { offeringForm: form } = page.details.offerings; await page.details.offerings.singleOffering(); await form.startDate.datePicker.set(new Date(2011, 8, 11)); await form.startTime.timePicker.hour.select('2'); await form.startTime.timePicker.minute.select('15'); await form.startTime.timePicker.ampm.select('am'); await form.duration.hours.set(39); await form.duration.minutes.set(15); await form.location.set('Rm. 111'); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[0].add(); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[1].add(); await form.instructorManager.search.searchBox.set('guy'); await form.instructorManager.search.results.items[0].click(); await form.save(); const block = page.details.offerings.dateBlocks[0]; assert.notOk(block.hasStartTime); assert.notOk(block.hasEndTime); assert.ok(block.hasMultiDay); assert.strictEqual(block.dayOfWeek, 'Sunday'); assert.strictEqual(block.dayOfMonth, 'September 11th'); const expectedText = 'Multiday ' + 'Starts Sunday September 11th @ 2:15 AM' + ' Ends Monday September 12th @ 5:30 PM'; assert.strictEqual(block.multiDay, expectedText); assert.strictEqual(block.offerings.length, 1); assert.strictEqual(block.offerings[0].learnerGroups.length, 2); assert.strictEqual(block.offerings[0].learnerGroups[0].title, 'learner group 0'); assert.strictEqual(block.offerings[0].learnerGroups[1].title, 'learner group 1'); assert.strictEqual(block.offerings[0].location, 'Rm. 111'); assert.strictEqual(block.offerings[0].instructors.length, 1); assert.strictEqual(block.offerings[0].instructors[0].userNameInfo.fullName, '0 guy M. Mc0son'); }); test('users can create a new small group offering', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(21); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.header.createNew(); const { offeringForm: form } = page.details.offerings; await page.details.offerings.smallGroup(); await form.startDate.datePicker.set(new Date(2011, 8, 11)); await form.startTime.timePicker.hour.select('2'); await form.startTime.timePicker.minute.select('15'); await form.startTime.timePicker.ampm.select('am'); await form.duration.hours.set(15); await form.duration.minutes.set(15); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[0].add(); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[1].add(); await form.save(); const block = page.details.offerings.dateBlocks[0]; assert.ok(block.hasStartTime); assert.ok(block.hasEndTime); assert.notOk(block.hasMultiDay); assert.strictEqual(block.dayOfWeek, 'Sunday'); assert.strictEqual(block.dayOfMonth, 'September 11th'); assert.strictEqual(block.startTime, 'Starts: 2:15 AM'); assert.strictEqual(block.endTime, 'Ends: 5:30 PM'); assert.strictEqual(block.offerings.length, 2); assert.strictEqual(block.offerings[0].learnerGroups.length, 1); assert.strictEqual(block.offerings[0].learnerGroups[0].title, 'learner group 0'); assert.strictEqual(block.offerings[0].instructors.length, 1); assert.strictEqual(block.offerings[0].instructors[0].userNameInfo.fullName, '0 guy M. Mc0son'); assert.strictEqual(block.offerings[0].url, 'https://iliosproject.org/'); assert.strictEqual(block.offerings[1].learnerGroups.length, 1); assert.strictEqual(block.offerings[1].learnerGroups[0].title, 'learner group 1'); assert.strictEqual(block.offerings[1].instructors.length, 4); assert.strictEqual(block.offerings[1].instructors[0].userNameInfo.fullName, '1 guy M. Mc1son'); assert.strictEqual(block.offerings[1].instructors[1].userNameInfo.fullName, '2 guy M. Mc2son'); assert.strictEqual(block.offerings[1].instructors[2].userNameInfo.fullName, '5 guy M. Mc5son'); assert.strictEqual(block.offerings[1].instructors[3].userNameInfo.fullName, '6 guy M. Mc6son'); assert.notOk(block.offerings[1].hasUrl); }); test('users can edit existing offerings', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(18); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.dateBlocks[0].offerings[0].edit(); const { offeringForm: form } = page.details.offerings.dateBlocks[0].offerings[0]; await form.startDate.datePicker.set(new Date(2011, 9, 5)); await form.startTime.timePicker.hour.select('11'); await form.startTime.timePicker.minute.select('45'); await form.startTime.timePicker.ampm.select('am'); await form.duration.hours.set(6); await form.duration.minutes.set(10); await form.location.set('Rm. 111'); await form.url.set('https://example.org'); await form.learnerManager.selectedLearnerGroups.list.trees[0].removeAllSubgroups(); await form.instructorManager.selectedInstructors[0].remove(); await form.instructorManager.selectedInstructorGroups[0].remove(); await form.save(); const block = page.details.offerings.dateBlocks[0]; assert.ok(block.hasStartTime); assert.ok(block.hasEndTime); assert.notOk(block.hasMultiDay); assert.strictEqual(block.dayOfWeek, 'Wednesday'); assert.strictEqual(block.dayOfMonth, 'October 5th'); assert.strictEqual(block.startTime, 'Starts: 11:45 AM'); assert.strictEqual(block.endTime, 'Ends: 5:55 PM'); assert.strictEqual(block.offerings.length, 1); const offering = block.offerings[0]; assert.strictEqual(offering.learnerGroups.length, 1); assert.strictEqual(offering.learnerGroups[0].title, 'learner group 1'); assert.strictEqual(offering.instructors.length, 5); assert.strictEqual(offering.instructors[0].userNameInfo.fullName, '3 guy M. Mc3son'); assert.strictEqual(offering.instructors[1].userNameInfo.fullName, '4 guy M. Mc4son'); assert.strictEqual(offering.instructors[2].userNameInfo.fullName, '6 guy M. Mc6son'); assert.strictEqual(offering.instructors[3].userNameInfo.fullName, '7 guy M. Mc7son'); assert.strictEqual(offering.instructors[4].userNameInfo.fullName, '8 guy M. Mc8son'); assert.strictEqual(offering.location, 'Rm. 111'); assert.strictEqual(offering.url, 'https://example.org/'); }); test('users can create recurring small groups', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(77); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.header.createNew(); const { offeringForm: form } = page.details.offerings; await page.details.offerings.smallGroup(); await form.startDate.datePicker.set(new Date(2015, 4, 22)); await form.startTime.timePicker.hour.select('2'); await form.startTime.timePicker.minute.select('15'); await form.startTime.timePicker.ampm.select('am'); await form.duration.hours.set(13); await form.duration.minutes.set(8); await form.recurring.yesNoToggle.click(); await form.recurring.setWeeks(4); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[0].add(); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[1].add(); await form.save(); assert.strictEqual(page.details.offerings.dateBlocks.length, 7); assert.strictEqual(page.details.offerings.dateBlocks[0].dayOfMonth, 'May 22nd'); assert.strictEqual(page.details.offerings.dateBlocks[1].dayOfMonth, 'May 29th'); assert.strictEqual(page.details.offerings.dateBlocks[2].dayOfMonth, 'June 5th'); assert.strictEqual(page.details.offerings.dateBlocks[3].dayOfMonth, 'June 12th'); for (let i = 0; i < 4; i++) { const block = page.details.offerings.dateBlocks[i]; assert.ok(block.hasStartTime); assert.ok(block.hasEndTime); assert.notOk(block.hasMultiDay); assert.strictEqual(block.dayOfWeek, 'Friday'); assert.strictEqual(block.startTime, 'Starts: 2:15 AM'); assert.strictEqual(block.endTime, 'Ends: 3:23 PM'); assert.strictEqual(block.offerings.length, 2); assert.strictEqual(block.offerings[0].learnerGroups.length, 1); assert.strictEqual(block.offerings[0].learnerGroups[0].title, 'learner group 0'); assert.strictEqual(block.offerings[0].instructors.length, 1); assert.strictEqual( block.offerings[0].instructors[0].userNameInfo.fullName, '0 guy M. Mc0son' ); assert.strictEqual(block.offerings[1].learnerGroups.length, 1); assert.strictEqual(block.offerings[1].learnerGroups[0].title, 'learner group 1'); assert.strictEqual(block.offerings[1].instructors.length, 4); assert.strictEqual( block.offerings[1].instructors[0].userNameInfo.fullName, '1 guy M. Mc1son' ); assert.strictEqual( block.offerings[1].instructors[1].userNameInfo.fullName, '2 guy M. Mc2son' ); assert.strictEqual( block.offerings[1].instructors[2].userNameInfo.fullName, '5 guy M. Mc5son' ); assert.strictEqual( block.offerings[1].instructors[3].userNameInfo.fullName, '6 guy M. Mc6son' ); } }); test('users can create recurring single offerings', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(57); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.header.createNew(); const { offeringForm: form } = page.details.offerings; await page.details.offerings.singleOffering(); await form.startDate.datePicker.set(new Date(2015, 4, 22)); await form.startTime.timePicker.hour.select('2'); await form.startTime.timePicker.minute.select('15'); await form.startTime.timePicker.ampm.select('am'); await form.duration.hours.set(13); await form.duration.minutes.set(8); await form.location.set('Scottsdale Stadium'); await form.url.set('https://zoom.example.edu'); await form.recurring.yesNoToggle.click(); await form.recurring.setWeeks(4); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[0].add(); await form.learnerManager.availableLearnerGroups.cohorts[0].trees[1].add(); await form.save(); assert.strictEqual(page.details.offerings.dateBlocks.length, 7); assert.strictEqual(page.details.offerings.dateBlocks[0].dayOfMonth, 'May 22nd'); assert.strictEqual(page.details.offerings.dateBlocks[1].dayOfMonth, 'May 29th'); assert.strictEqual(page.details.offerings.dateBlocks[2].dayOfMonth, 'June 5th'); assert.strictEqual(page.details.offerings.dateBlocks[3].dayOfMonth, 'June 12th'); for (let i = 0; i < 4; i++) { const block = page.details.offerings.dateBlocks[i]; assert.ok(block.hasStartTime); assert.ok(block.hasEndTime); assert.notOk(block.hasMultiDay); assert.strictEqual(block.dayOfWeek, 'Friday'); assert.strictEqual(block.startTime, 'Starts: 2:15 AM'); assert.strictEqual(block.endTime, 'Ends: 3:23 PM'); assert.strictEqual(block.offerings.length, 1); assert.strictEqual(block.offerings[0].learnerGroups.length, 2); assert.strictEqual(block.offerings[0].location, 'Scottsdale Stadium'); assert.strictEqual(block.offerings[0].url, 'https://zoom.example.edu/'); assert.strictEqual(block.offerings[0].learnerGroups[0].title, 'learner group 0'); assert.strictEqual(block.offerings[0].learnerGroups[1].title, 'learner group 1'); assert.strictEqual(block.offerings[0].instructors.length, 0); } }); test('edit offerings twice #2850', async function (assert) { this.user.update({ administeredSchools: [this.school] }); assert.expect(2); this.server.create('learnerGroup', { cohortId: 1, }); this.server.create('learnerGroup', { cohortId: 1, parentId: 3, }); this.server.create('learnerGroup', { cohortId: 1, parentId: 4, }); this.server.create('learnerGroup', { cohortId: 1, parentId: 5, }); this.server.db.cohorts.update(1, { learnerGroupIds: [3, 4, 5, 6] }); await page.visit({ courseId: 1, sessionId: 1 }); await page.details.offerings.dateBlocks[0].offerings[0].edit(); await page.details.offerings.dateBlocks[0].offerings[0].offeringForm.save(); assert.strictEqual(page.details.offerings.dateBlocks[0].offerings[0].location, 'room 0'); await page.details.offerings.dateBlocks[0].offerings[0].edit(); await page.details.offerings.dateBlocks[0].offerings[0].offeringForm.save(); assert.strictEqual(page.details.offerings.dateBlocks[0].offerings[0].location, 'room 0'); }); });
43.709507
117
0.694244
4d971c66728e09f33f64491ae81d82f8a8686cde
25,766
html
HTML
target/doc/src/tokio_trace_core/lib.rs.html
kieranjwhite/calendar_mirror
269187e2dddbe448c8c5561d89b30bc44491a1a2
[ "Apache-2.0" ]
null
null
null
target/doc/src/tokio_trace_core/lib.rs.html
kieranjwhite/calendar_mirror
269187e2dddbe448c8c5561d89b30bc44491a1a2
[ "Apache-2.0" ]
null
null
null
target/doc/src/tokio_trace_core/lib.rs.html
kieranjwhite/calendar_mirror
269187e2dddbe448c8c5561d89b30bc44491a1a2
[ "Apache-2.0" ]
null
null
null
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="Source to the Rust file `/home/kieran/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-trace-core-0.2.0/src/lib.rs`."><meta name="keywords" content="rust, rustlang, rust-lang"><title>lib.rs.html -- source</title><link rel="stylesheet" type="text/css" href="../../normalize.css"><link rel="stylesheet" type="text/css" href="../../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" type="text/css" href="../../dark.css"><link rel="stylesheet" type="text/css" href="../../light.css" id="themeStyle"><script src="../../storage.js"></script><noscript><link rel="stylesheet" href="../../noscript.css"></noscript><link rel="shortcut icon" href="../../favicon.ico"><style type="text/css">#crate-search{background-image:url("../../down-arrow.svg");}</style></head><body class="rustdoc source"><!--[if lte IE 8]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="sidebar"><div class="sidebar-menu">&#9776;</div><a href='../../tokio_trace_core/index.html'><div class='logo-container'><img src='../../rust-logo.png' alt='logo'></div></a></nav><div class="theme-picker"><button id="theme-picker" aria-label="Pick another theme!"><img src="../../brush.svg" width="18" alt="Pick another theme!"></button><div id="theme-choices"></div></div><script src="../../theme.js"></script><nav class="sub"><form class="search-form js-only"><div class="search-container"><div><select id="crate-search"><option value="All crates">All crates</option></select><input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"></div><a id="settings-menu" href="../../settings.html"><img src="../../wheel.svg" width="18" alt="Change settings"></a></div></form></nav><section id="main" class="content"><pre class="line-numbers"><span id="1"> 1</span> <span id="2"> 2</span> <span id="3"> 3</span> <span id="4"> 4</span> <span id="5"> 5</span> <span id="6"> 6</span> <span id="7"> 7</span> <span id="8"> 8</span> <span id="9"> 9</span> <span id="10"> 10</span> <span id="11"> 11</span> <span id="12"> 12</span> <span id="13"> 13</span> <span id="14"> 14</span> <span id="15"> 15</span> <span id="16"> 16</span> <span id="17"> 17</span> <span id="18"> 18</span> <span id="19"> 19</span> <span id="20"> 20</span> <span id="21"> 21</span> <span id="22"> 22</span> <span id="23"> 23</span> <span id="24"> 24</span> <span id="25"> 25</span> <span id="26"> 26</span> <span id="27"> 27</span> <span id="28"> 28</span> <span id="29"> 29</span> <span id="30"> 30</span> <span id="31"> 31</span> <span id="32"> 32</span> <span id="33"> 33</span> <span id="34"> 34</span> <span id="35"> 35</span> <span id="36"> 36</span> <span id="37"> 37</span> <span id="38"> 38</span> <span id="39"> 39</span> <span id="40"> 40</span> <span id="41"> 41</span> <span id="42"> 42</span> <span id="43"> 43</span> <span id="44"> 44</span> <span id="45"> 45</span> <span id="46"> 46</span> <span id="47"> 47</span> <span id="48"> 48</span> <span id="49"> 49</span> <span id="50"> 50</span> <span id="51"> 51</span> <span id="52"> 52</span> <span id="53"> 53</span> <span id="54"> 54</span> <span id="55"> 55</span> <span id="56"> 56</span> <span id="57"> 57</span> <span id="58"> 58</span> <span id="59"> 59</span> <span id="60"> 60</span> <span id="61"> 61</span> <span id="62"> 62</span> <span id="63"> 63</span> <span id="64"> 64</span> <span id="65"> 65</span> <span id="66"> 66</span> <span id="67"> 67</span> <span id="68"> 68</span> <span id="69"> 69</span> <span id="70"> 70</span> <span id="71"> 71</span> <span id="72"> 72</span> <span id="73"> 73</span> <span id="74"> 74</span> <span id="75"> 75</span> <span id="76"> 76</span> <span id="77"> 77</span> <span id="78"> 78</span> <span id="79"> 79</span> <span id="80"> 80</span> <span id="81"> 81</span> <span id="82"> 82</span> <span id="83"> 83</span> <span id="84"> 84</span> <span id="85"> 85</span> <span id="86"> 86</span> <span id="87"> 87</span> <span id="88"> 88</span> <span id="89"> 89</span> <span id="90"> 90</span> <span id="91"> 91</span> <span id="92"> 92</span> <span id="93"> 93</span> <span id="94"> 94</span> <span id="95"> 95</span> <span id="96"> 96</span> <span id="97"> 97</span> <span id="98"> 98</span> <span id="99"> 99</span> <span id="100">100</span> <span id="101">101</span> <span id="102">102</span> <span id="103">103</span> <span id="104">104</span> <span id="105">105</span> <span id="106">106</span> <span id="107">107</span> <span id="108">108</span> <span id="109">109</span> <span id="110">110</span> <span id="111">111</span> <span id="112">112</span> <span id="113">113</span> <span id="114">114</span> <span id="115">115</span> <span id="116">116</span> <span id="117">117</span> <span id="118">118</span> <span id="119">119</span> <span id="120">120</span> <span id="121">121</span> <span id="122">122</span> <span id="123">123</span> <span id="124">124</span> <span id="125">125</span> <span id="126">126</span> <span id="127">127</span> <span id="128">128</span> <span id="129">129</span> <span id="130">130</span> <span id="131">131</span> <span id="132">132</span> <span id="133">133</span> <span id="134">134</span> <span id="135">135</span> <span id="136">136</span> <span id="137">137</span> <span id="138">138</span> <span id="139">139</span> <span id="140">140</span> <span id="141">141</span> <span id="142">142</span> <span id="143">143</span> <span id="144">144</span> <span id="145">145</span> <span id="146">146</span> <span id="147">147</span> <span id="148">148</span> <span id="149">149</span> <span id="150">150</span> <span id="151">151</span> <span id="152">152</span> <span id="153">153</span> <span id="154">154</span> <span id="155">155</span> <span id="156">156</span> <span id="157">157</span> <span id="158">158</span> <span id="159">159</span> <span id="160">160</span> <span id="161">161</span> <span id="162">162</span> <span id="163">163</span> <span id="164">164</span> <span id="165">165</span> <span id="166">166</span> <span id="167">167</span> <span id="168">168</span> <span id="169">169</span> <span id="170">170</span> <span id="171">171</span> <span id="172">172</span> <span id="173">173</span> <span id="174">174</span> <span id="175">175</span> <span id="176">176</span> <span id="177">177</span> <span id="178">178</span> <span id="179">179</span> <span id="180">180</span> <span id="181">181</span> <span id="182">182</span> <span id="183">183</span> <span id="184">184</span> <span id="185">185</span> <span id="186">186</span> <span id="187">187</span> <span id="188">188</span> <span id="189">189</span> <span id="190">190</span> <span id="191">191</span> <span id="192">192</span> <span id="193">193</span> <span id="194">194</span> <span id="195">195</span> <span id="196">196</span> <span id="197">197</span> <span id="198">198</span> <span id="199">199</span> <span id="200">200</span> <span id="201">201</span> <span id="202">202</span> <span id="203">203</span> <span id="204">204</span> <span id="205">205</span> <span id="206">206</span> <span id="207">207</span> <span id="208">208</span> <span id="209">209</span> <span id="210">210</span> <span id="211">211</span> <span id="212">212</span> </pre><div class="example-wrap"><pre class="rust "> <span class="attribute">#![<span class="ident">doc</span>(<span class="ident">html_root_url</span> <span class="op">=</span> <span class="string">&quot;https://docs.rs/tokio-trace-core/0.2.0&quot;</span>)]</span> <span class="attribute">#![<span class="ident">deny</span>(<span class="ident">missing_debug_implementations</span>, <span class="ident">missing_docs</span>, <span class="ident">unreachable_pub</span>)]</span> <span class="attribute">#![<span class="ident">cfg_attr</span>(<span class="ident">test</span>, <span class="ident">deny</span>(<span class="ident">warnings</span>))]</span> <span class="doccomment">//! Core primitives for `tokio-trace`.</span> <span class="doccomment">//!</span> <span class="doccomment">//! `tokio-trace` is a framework for instrumenting Rust programs to collect</span> <span class="doccomment">//! structured, event-based diagnostic information. This crate defines the core</span> <span class="doccomment">//! primitives of `tokio-trace`.</span> <span class="doccomment">//!</span> <span class="doccomment">//! This crate provides:</span> <span class="doccomment">//!</span> <span class="doccomment">//! * [`Span`] identifies a span within the execution of a program.</span> <span class="doccomment">//!</span> <span class="doccomment">//! * [`Event`] represents a single event within a trace.</span> <span class="doccomment">//!</span> <span class="doccomment">//! * [`Subscriber`], the trait implemented to collect trace data.</span> <span class="doccomment">//!</span> <span class="doccomment">//! * [`Metadata`] and [`Callsite`] provide information describing `Span`s.</span> <span class="doccomment">//!</span> <span class="doccomment">//! * [`Field`], [`FieldSet`], [`Value`], and [`ValueSet`] represent the</span> <span class="doccomment">//! structured data attached to a `Span`.</span> <span class="doccomment">//!</span> <span class="doccomment">//! * [`Dispatch`] allows span events to be dispatched to `Subscriber`s.</span> <span class="doccomment">//!</span> <span class="doccomment">//! In addition, it defines the global callsite registry and per-thread current</span> <span class="doccomment">//! dispatcher which other components of the tracing system rely on.</span> <span class="doccomment">//!</span> <span class="doccomment">//! Application authors will typically not use this crate directly. Instead,</span> <span class="doccomment">//! they will use the `tokio-trace` crate, which provides a much more</span> <span class="doccomment">//! fully-featured API. However, this crate&#39;s API will change very infrequently,</span> <span class="doccomment">//! so it may be used when dependencies must be very stable.</span> <span class="doccomment">//!</span> <span class="doccomment">//! The [`tokio-trace-nursery`] repository contains less stable crates designed to</span> <span class="doccomment">//! be used with the `tokio-trace` ecosystem. It includes a collection of</span> <span class="doccomment">//! `Subscriber` implementations, as well as utility and adapter crates.</span> <span class="doccomment">//!</span> <span class="doccomment">//! [`Span`]: span/struct.Span.html</span> <span class="doccomment">//! [`Event`]: event/struct.Event.html</span> <span class="doccomment">//! [`Subscriber`]: subscriber/trait.Subscriber.html</span> <span class="doccomment">//! [`Metadata`]: metadata/struct.Metadata.html</span> <span class="doccomment">//! [`Callsite`]: callsite/trait.Callsite.html</span> <span class="doccomment">//! [`Field`]: field/struct.Field.html</span> <span class="doccomment">//! [`FieldSet`]: field/struct.FieldSet.html</span> <span class="doccomment">//! [`Value`]: field/trait.Value.html</span> <span class="doccomment">//! [`ValueSet`]: field/struct.ValueSet.html</span> <span class="doccomment">//! [`Dispatch`]: dispatcher/struct.Dispatch.html</span> <span class="doccomment">//! [`tokio-trace-nursery`]: https://github.com/tokio-rs/tokio-trace-nursery</span> <span class="attribute">#[<span class="ident">macro_use</span>]</span> <span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">lazy_static</span>; <span class="doccomment">/// Statically constructs an [`Identifier`] for the provided [`Callsite`].</span> <span class="doccomment">///</span> <span class="doccomment">/// This may be used in contexts, such as static initializers, where the</span> <span class="doccomment">/// [`Callsite::id`] function is not currently usable.</span> <span class="doccomment">///</span> <span class="doccomment">/// For example:</span> <span class="doccomment">/// ```rust</span> <span class="doccomment">/// # #[macro_use]</span> <span class="doccomment">/// # extern crate tokio_trace_core;</span> <span class="doccomment">/// use tokio_trace_core::callsite;</span> <span class="doccomment">/// # use tokio_trace_core::{Metadata, subscriber::Interest};</span> <span class="doccomment">/// # fn main() {</span> <span class="doccomment">/// pub struct MyCallsite {</span> <span class="doccomment">/// // ...</span> <span class="doccomment">/// }</span> <span class="doccomment">/// impl callsite::Callsite for MyCallsite {</span> <span class="doccomment">/// # fn set_interest(&amp;self, _: Interest) { unimplemented!() }</span> <span class="doccomment">/// # fn metadata(&amp;self) -&gt; &amp;Metadata { unimplemented!() }</span> <span class="doccomment">/// // ...</span> <span class="doccomment">/// }</span> <span class="doccomment">///</span> <span class="doccomment">/// static CALLSITE: MyCallsite = MyCallsite {</span> <span class="doccomment">/// // ...</span> <span class="doccomment">/// };</span> <span class="doccomment">///</span> <span class="doccomment">/// static CALLSITE_ID: callsite::Identifier = identify_callsite!(&amp;CALLSITE);</span> <span class="doccomment">/// # }</span> <span class="doccomment">/// ```</span> <span class="doccomment">///</span> <span class="doccomment">/// [`Identifier`]: callsite/struct.Identifier.html</span> <span class="doccomment">/// [`Callsite`]: callsite/trait.Callsite.html</span> <span class="doccomment">/// [`Callsite`]: callsite/trait.Callsite.html#method.id</span> <span class="attribute">#[<span class="ident">macro_export</span>]</span> <span class="macro">macro_rules</span><span class="macro">!</span> <span class="ident">identify_callsite</span> { (<span class="macro-nonterminal">$</span><span class="macro-nonterminal">callsite</span>:<span class="ident">expr</span>) <span class="op">=&gt;</span> { <span class="macro-nonterminal">$</span><span class="kw">crate</span>::<span class="macro-nonterminal">callsite</span>::<span class="ident">Identifier</span>(<span class="macro-nonterminal">$</span><span class="macro-nonterminal">callsite</span>) }; } <span class="doccomment">/// Statically constructs new span [metadata].</span> <span class="doccomment">///</span> <span class="doccomment">/// This may be used in contexts, such as static initializers, where the</span> <span class="doccomment">/// [`Metadata::new`] function is not currently usable.</span> <span class="doccomment">///</span> <span class="doccomment">/// /// For example:</span> <span class="doccomment">/// ```rust</span> <span class="doccomment">/// # #[macro_use]</span> <span class="doccomment">/// # extern crate tokio_trace_core;</span> <span class="doccomment">/// # use tokio_trace_core::{callsite::Callsite, subscriber::Interest};</span> <span class="doccomment">/// use tokio_trace_core::metadata::{Kind, Level, Metadata};</span> <span class="doccomment">/// # fn main() {</span> <span class="doccomment">/// # pub struct MyCallsite { }</span> <span class="doccomment">/// # impl Callsite for MyCallsite {</span> <span class="doccomment">/// # fn set_interest(&amp;self, _: Interest) { unimplemented!() }</span> <span class="doccomment">/// # fn metadata(&amp;self) -&gt; &amp;Metadata { unimplemented!() }</span> <span class="doccomment">/// # }</span> <span class="doccomment">/// #</span> <span class="doccomment">/// static FOO_CALLSITE: MyCallsite = MyCallsite {</span> <span class="doccomment">/// // ...</span> <span class="doccomment">/// };</span> <span class="doccomment">///</span> <span class="doccomment">/// static FOO_METADATA: Metadata = metadata!{</span> <span class="doccomment">/// name: &quot;foo&quot;,</span> <span class="doccomment">/// target: module_path!(),</span> <span class="doccomment">/// level: Level::DEBUG,</span> <span class="doccomment">/// fields: &amp;[&quot;bar&quot;, &quot;baz&quot;],</span> <span class="doccomment">/// callsite: &amp;FOO_CALLSITE,</span> <span class="doccomment">/// kind: Kind::SPAN,</span> <span class="doccomment">/// };</span> <span class="doccomment">/// # }</span> <span class="doccomment">/// ```</span> <span class="doccomment">///</span> <span class="doccomment">/// [metadata]: metadata/struct.Metadata.html</span> <span class="doccomment">/// [`Metadata::new`]: metadata/struct.Metadata.html#method.new</span> <span class="attribute">#[<span class="ident">macro_export</span>(<span class="ident">local_inner_macros</span>)]</span> <span class="macro">macro_rules</span><span class="macro">!</span> <span class="ident">metadata</span> { ( <span class="ident">name</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">name</span>:<span class="ident">expr</span>, <span class="ident">target</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">target</span>:<span class="ident">expr</span>, <span class="ident">level</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">level</span>:<span class="ident">expr</span>, <span class="ident">fields</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">fields</span>:<span class="ident">expr</span>, <span class="ident">callsite</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">callsite</span>:<span class="ident">expr</span>, <span class="ident">kind</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">kind</span>:<span class="ident">expr</span> ) <span class="op">=&gt;</span> { <span class="macro">metadata</span><span class="macro">!</span> { <span class="ident">name</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">name</span>, <span class="ident">target</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">target</span>, <span class="ident">level</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">level</span>, <span class="ident">fields</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">fields</span>, <span class="ident">callsite</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">callsite</span>, <span class="ident">kind</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">kind</span>, } }; ( <span class="ident">name</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">name</span>:<span class="ident">expr</span>, <span class="ident">target</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">target</span>:<span class="ident">expr</span>, <span class="ident">level</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">level</span>:<span class="ident">expr</span>, <span class="ident">fields</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">fields</span>:<span class="ident">expr</span>, <span class="ident">callsite</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">callsite</span>:<span class="ident">expr</span>, <span class="ident">kind</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">kind</span>:<span class="ident">expr</span>, ) <span class="op">=&gt;</span> { <span class="macro-nonterminal">$</span><span class="kw">crate</span>::<span class="macro-nonterminal">metadata</span>::<span class="ident">Metadata</span> { <span class="ident">name</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">name</span>, <span class="ident">target</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">target</span>, <span class="ident">level</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">level</span>, <span class="ident">file</span>: <span class="prelude-val">Some</span>(<span class="macro">__tokio_trace_core_file</span><span class="macro">!</span>()), <span class="ident">line</span>: <span class="prelude-val">Some</span>(<span class="macro">__tokio_trace_core_line</span><span class="macro">!</span>()), <span class="ident">module_path</span>: <span class="prelude-val">Some</span>(<span class="macro">__tokio_trace_core_module_path</span><span class="macro">!</span>()), <span class="ident">fields</span>: <span class="macro-nonterminal">$</span><span class="kw">crate</span>::<span class="macro-nonterminal">field</span>::<span class="ident">FieldSet</span> { <span class="ident">names</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">fields</span>, <span class="ident">callsite</span>: <span class="macro">identify_callsite</span><span class="macro">!</span>(<span class="macro-nonterminal">$</span><span class="macro-nonterminal">callsite</span>), }, <span class="ident">kind</span>: <span class="macro-nonterminal">$</span><span class="macro-nonterminal">kind</span>, } }; } <span class="attribute">#[<span class="ident">doc</span>(<span class="ident">hidden</span>)]</span> <span class="attribute">#[<span class="ident">macro_export</span>]</span> <span class="macro">macro_rules</span><span class="macro">!</span> <span class="ident">__tokio_trace_core_module_path</span> { () <span class="op">=&gt;</span> { <span class="macro">module_path</span><span class="macro">!</span>() }; } <span class="attribute">#[<span class="ident">doc</span>(<span class="ident">hidden</span>)]</span> <span class="attribute">#[<span class="ident">macro_export</span>]</span> <span class="macro">macro_rules</span><span class="macro">!</span> <span class="ident">__tokio_trace_core_file</span> { () <span class="op">=&gt;</span> { <span class="macro">file</span><span class="macro">!</span>() }; } <span class="attribute">#[<span class="ident">doc</span>(<span class="ident">hidden</span>)]</span> <span class="attribute">#[<span class="ident">macro_export</span>]</span> <span class="macro">macro_rules</span><span class="macro">!</span> <span class="ident">__tokio_trace_core_line</span> { () <span class="op">=&gt;</span> { <span class="macro">line</span><span class="macro">!</span>() }; } <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">callsite</span>; <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">dispatcher</span>; <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">event</span>; <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">field</span>; <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">metadata</span>; <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">span</span>; <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">subscriber</span>; <span class="kw">pub</span> <span class="kw">use</span> <span class="self">self</span>::{ <span class="ident">callsite</span>::<span class="ident">Callsite</span>, <span class="ident">dispatcher</span>::<span class="ident">Dispatch</span>, <span class="ident">event</span>::<span class="ident">Event</span>, <span class="ident">field</span>::<span class="ident">Field</span>, <span class="ident">metadata</span>::{<span class="ident">Kind</span>, <span class="ident">Level</span>, <span class="ident">Metadata</span>}, <span class="ident">subscriber</span>::{<span class="ident">Interest</span>, <span class="ident">Subscriber</span>}, }; <span class="kw">mod</span> <span class="ident">sealed</span> { <span class="kw">pub</span> <span class="kw">trait</span> <span class="ident">Sealed</span> {} } </pre></div> </section><section id="search" class="content hidden"></section><section class="footer"></section><aside id="help" class="hidden"><div><h1 class="hidden">Help</h1><div class="shortcuts"><h2>Keyboard Shortcuts</h2><dl><dt><kbd>?</kbd></dt><dd>Show this help dialog</dd><dt><kbd>S</kbd></dt><dd>Focus the search field</dd><dt><kbd>↑</kbd></dt><dd>Move up in search results</dd><dt><kbd>↓</kbd></dt><dd>Move down in search results</dd><dt><kbd>↹</kbd></dt><dd>Switch tab</dd><dt><kbd>&#9166;</kbd></dt><dd>Go to active search result</dd><dt><kbd>+</kbd></dt><dd>Expand all sections</dd><dt><kbd>-</kbd></dt><dd>Collapse all sections</dd></dl></div><div class="infos"><h2>Search Tricks</h2><p>Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to restrict the search to a given type.</p><p>Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>.</p><p>Search functions by type signature (e.g., <code>vec -> usize</code> or <code>* -> vec</code>)</p><p>Search multiple things at once by splitting your query with comma (e.g., <code>str,u8</code> or <code>String,struct:Vec,test</code>)</p></div></div></aside><script>window.rootPath = "../../";window.currentCrate = "tokio_trace_core";</script><script src="../../aliases.js"></script><script src="../../main.js"></script><script src="../../source-script.js"></script><script src="../../source-files.js"></script><script defer src="../../search-index.js"></script></body></html>
60.34192
2,100
0.654118
3eba7589d3864599d8e36290573953150b1ca369
4,982
swift
Swift
ShopBag/Checkout/CheckoutViewController.swift
altamic/ShopBag
ba9ffc6df78601176c8e814905b270f0a3820113
[ "MIT" ]
1
2021-01-24T11:14:16.000Z
2021-01-24T11:14:16.000Z
ShopBag/Checkout/CheckoutViewController.swift
altamic/ShopBag
ba9ffc6df78601176c8e814905b270f0a3820113
[ "MIT" ]
null
null
null
ShopBag/Checkout/CheckoutViewController.swift
altamic/ShopBag
ba9ffc6df78601176c8e814905b270f0a3820113
[ "MIT" ]
null
null
null
// // CheckoutViewController.swift // ShopBag // // Created by Michelangelo Altamore on 23/09/17. // Copyright © 2017 altamic. All rights reserved. // import UIKit class CheckoutViewController: UITableViewController { let lineItemCellIdentifier = "LineItemIdentifier" var lineItems = [LineItem]() var currencyRatios = [Currency: Double]() let segmentedButtonCurrencyOrder: [Int: Currency] = [0: .usd, 1: .eur, 2: .chf, 3: .gbp] let apiClient = URLSessionNetworkClient() @IBOutlet weak var currencySelectionView: UISegmentedControl! @IBOutlet weak var totalPriceLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() disableSelectCurrencyButton() getCurrencyRates() updateTotalPrice() } @IBAction func currencySelectedChangedAction(_ sender: UISegmentedControl) { setProductsCurrency(segmentedButtonIndex: sender.selectedSegmentIndex) tableView.reloadData() updateTotalPrice() } private func setProductsCurrency(segmentedButtonIndex: Int) { if let currency = segmentedButtonCurrencyOrder[segmentedButtonIndex], let ratio = currencyRatios[currency] { Product.CURRENCY_RATIO = ratio Product.CURRENCY_NAME = currency } else { currencySelectionView.selectedSegmentIndex = 0 currencySelectionView.isEnabled = false } } @IBAction func refreshRatesAction(_ sender: UIBarButtonItem) { disableSelectCurrencyButton() getCurrencyRates() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lineItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: lineItemCellIdentifier, for: indexPath) as! LineItemTableViewCell cell.configure(with: lineItems[indexPath.row]) cell.minusOneBlock = { self.addAndSetPrice(-1, indexPath: indexPath, cell: cell) self.updateTotalPrice() } cell.addOneBlock = { self.addAndSetPrice(1, indexPath: indexPath, cell: cell) self.updateTotalPrice() } return cell } private func addAndSetPrice(_ plusOrMinusOne: Int, indexPath: IndexPath, cell: LineItemTableViewCell) { guard plusOrMinusOne == 1 || plusOrMinusOne == -1 else { return } let currentQuantity = self.lineItems[indexPath.row].quantity self.lineItems[indexPath.row].quantity = plusOrMinusOne == 1 ? min(9, currentQuantity + 1) : max(1, currentQuantity - 1) cell.quantity.text = "\(self.lineItems[indexPath.row].quantity)" cell.priceView.text = formatCurrency(value: self.lineItems[indexPath.row].subTotal(), currencyCode: Product.CURRENCY_NAME) } private func updateTotalPrice() { let total = LineItem.computeTotal(of: lineItems) self.totalPriceLabel.text = formatCurrency(value: total, currencyCode: Product.CURRENCY_NAME) } private func getCurrencyRates() { let getRatesEndpoint = ApiRouter.getRatesFor(currencies: ["EUR","CHF","GBP"]) apiClient.request(to: getRatesEndpoint) { (result: Result<Currencies>) in switch result { case .success(let currencyRates): if currencyRates.success { let dateTime = Date(timeIntervalSince1970: TimeInterval(currencyRates.timestamp)) print("JSON API call success: updated rates at \(dateTime)") self.currencyRatios = self.loadRates(from: currencyRates.quotes) print(self.currencyRatios) self.enableSelectCurrencyButton() } else { self.disableSelectCurrencyButton() } case .failure(let error): print("JSON API call failed: \(error.localizedDescription)") self.disableSelectCurrencyButton() } } } func loadRates(from quotes: [String: Double]) -> [Currency: Double] { let initialValue: [Currency: Double] = [.usd: 1.0] return quotes.reduce(initialValue) { (acc, item) in let key = item.key let index = key.index(key.startIndex, offsetBy: 3) let currencyString = String(describing: key[index...]) return acc.merge(with: [Currency(rawValue: currencyString)!: item.value]) } } func disableSelectCurrencyButton() { DispatchQueue.main.async { let indexes: [Currency: Int] = [.usd: 0, .eur: 1, .chf: 2, .gbp: 3] self.currencySelectionView.selectedSegmentIndex = indexes[Product.CURRENCY_NAME]! self.currencySelectionView.isEnabled = false } } func enableSelectCurrencyButton() { DispatchQueue.main.async { self.currencySelectionView.isEnabled = true self.tableView.reloadData() self.updateTotalPrice() } } }
33.436242
126
0.681052
a4fc3165c3079c302a0df7d0370d0090fbb14655
1,876
swift
Swift
Tests/SettlerTests/OrderedDefinitionBuilderTests.swift
daltonclaybrook/Settler
6ecddc7392f49e866e366d84f6e7619f6d115ede
[ "MIT" ]
4
2020-08-20T15:03:45.000Z
2020-08-21T05:06:12.000Z
Tests/SettlerTests/OrderedDefinitionBuilderTests.swift
daltonclaybrook/Settler
6ecddc7392f49e866e366d84f6e7619f6d115ede
[ "MIT" ]
14
2020-08-20T15:22:29.000Z
2020-08-26T02:34:11.000Z
Tests/SettlerTests/OrderedDefinitionBuilderTests.swift
daltonclaybrook/Settler
6ecddc7392f49e866e366d84f6e7619f6d115ede
[ "MIT" ]
1
2020-08-20T23:50:34.000Z
2020-08-20T23:50:34.000Z
import XCTest @testable import SettlerFramework import SourceKittenFramework final class OrderedDefinitionBuilderTests: XCTestCase { func testSimpleResolverReturnsCorrectOrder() throws { let resolver = try ResolverDefinition.makeSampleDefinition() let definition = try XCTUnwrap(OrderedDefinitionBuilder.build(with: resolver).left) let allCalls = definition.allCallDefinitions let expected = [ try resolver.getResolverFunctionWith(namePrefix: "resolveBar"), try resolver.getResolverFunctionWith(namePrefix: "resolveFoo"), ] XCTAssertEqual(allCalls, expected) } func testResolverWithCircularDependencyReturnsError() throws { let contents = SampleResolverContents.circularResolverContents let resolver = try ResolverDefinition.makeSampleDefinition(contents: contents.strippingMarkers) let result = OrderedDefinitionBuilder.build(with: resolver) let errors = try XCTUnwrap(result.right) XCTAssertEqual(errors.count, 1) assert(located: errors[safe: 0], equals: .circularResolverDependency(keys: ["Key.Bar", "Key.Fizz", "Key.Foo", "Key.Bar"]), in: contents) } func testErrorIsReturnedForThrowingFunctionWithLazyUsage() throws { let contents = SampleResolverContents.throwingWithLazyUsageContents let resolver = try ResolverDefinition.makeSampleDefinition(contents: contents.strippingMarkers) let result = OrderedDefinitionBuilder.build(with: resolver) let errors = try XCTUnwrap(result.right) XCTAssertEqual(errors.count, 1) assert(located: errors[safe: 0], equals: .resolverFunctionCannotBeThrowingIfResultIsUsedLazily, in: contents) } } extension OrderedResolverDefinition { var allCallDefinitions: [ResolverFunctionDefinition] { orderedCalls.map(\.definition) } }
43.627907
144
0.739872
4eb4fed8b1f13c73002863d6cabbf8b69b8cfcf0
3,455
swift
Swift
Frame Grabber/Requesting Assets/Frame Export/FrameExportTask.swift
tiagomartinho/FrameGrabber
bbb7631baa1bd4f79e0de023cb58218ceecbc8d6
[ "MIT" ]
1
2020-04-29T18:38:51.000Z
2020-04-29T18:38:51.000Z
Frame Grabber/Requesting Assets/Frame Export/FrameExportTask.swift
tiagomartinho/FrameGrabber
bbb7631baa1bd4f79e0de023cb58218ceecbc8d6
[ "MIT" ]
null
null
null
Frame Grabber/Requesting Assets/Frame Export/FrameExportTask.swift
tiagomartinho/FrameGrabber
bbb7631baa1bd4f79e0de023cb58218ceecbc8d6
[ "MIT" ]
null
null
null
import AVFoundation class FrameExportTask: Operation { typealias Request = FrameExport.Request typealias Status = FrameExport.Status let request: Request let frameStartIndex: Int let generator: AVAssetImageGenerator let frameProcessedHandler: (Int, Status) -> () /// - Parameter frameStartIndex: If the task represents a chunk of a larger task, the /// index describes the index of generated frames relative to the larger task. The /// value is also used to generate file names for exported images. /// - Parameter frameProcessedHandler: Called on an arbitrary queue. init(generator: AVAssetImageGenerator, request: Request, frameStartIndex: Int = 0, frameProcessedHandler: @escaping (Int, Status) -> ()) { self.generator = generator self.request = request self.frameStartIndex = frameStartIndex self.frameProcessedHandler = frameProcessedHandler super.init() self.qualityOfService = .userInitiated } override func cancel() { super.cancel() generator.cancelAllCGImageGeneration() } override func main() { guard !isCancelled else { return } // Since the operation is already asynchronous, make `generateCGImagesAsynchronously` // synchronous within the current queue. let block = DispatchGroup() block.enter() // Can be safely modified from the generator's callbacks' threads as they are // strictly sequential. let times = request.times.map(NSValue.init) var countProcessed = 0 generator.generateCGImagesAsynchronously(forTimes: times) { [weak self] _, image, _, status, error in guard let self = self else { return } let frameIndex = self.frameStartIndex + countProcessed // When the operation is cancelled, subsequent AVAssetImageGenerator callbacks // might report `succeeded` as images might already have been generated while // the current one is slowly being written to disk. Consider them cancelled too. switch (self.isCancelled, status, image) { case (true, _, _), (_, .cancelled, _): self.frameProcessedHandler(frameIndex, .cancelled) case (_, .succeeded, let image?): let writeResult = self.write(image, for: self.request, index: frameIndex) self.frameProcessedHandler(frameIndex, writeResult) default: self.frameProcessedHandler(frameIndex, .failed(error)) } countProcessed += 1 if countProcessed == times.count { block.leave() } } block.wait() } private func write(_ image: CGImage, for request: Request, index: Int) -> Status { guard let directory = request.directory else { return .failed(nil) } let fileUrl = url(forFrameAt: index, in: directory, format: request.encoding.format) let ok = image.write(to: fileUrl, with: request.encoding) return ok ? .succeeded([fileUrl]) : .failed(nil) } private func url(forFrameAt index: Int, in directory: URL, format: ImageFormat) -> URL { let suffix = (index == 0) ? "" : "-\(index)" let fileName = "Frame\(suffix).\(format.fileExtension)" return directory.appendingPathComponent(fileName) } }
35.255102
109
0.635601
859fd58ce50f17da1dd8d63ab089166904224d19
300
js
JavaScript
test/smoke/fixtures/assertion-inject/expected/class-constructor.js
johnthecat/babel-plugin-jsdoc-runtime-type-check
459235cf231d6e8489d56235a5df8494a56b727f
[ "MIT" ]
14
2017-03-24T06:57:34.000Z
2021-11-13T21:40:41.000Z
test/smoke/fixtures/assertion-inject/expected/class-constructor.js
johnthecat/babel-plugin-jsdoc-runtime-type-check
459235cf231d6e8489d56235a5df8494a56b727f
[ "MIT" ]
1
2020-04-21T02:26:43.000Z
2020-04-24T12:59:17.000Z
test/smoke/fixtures/assertion-inject/expected/class-constructor.js
johnthecat/babel-plugin-jsdoc-runtime-type-check
459235cf231d6e8489d56235a5df8494a56b727f
[ "MIT" ]
2
2019-01-24T16:04:43.000Z
2019-06-21T10:51:21.000Z
class Test { /** * @param {Number} a * @param {Number} b * @typecheck */ constructor(a, b) { __executeTypecheck__("Test.constructor", "a", a, "\"Number\""); __executeTypecheck__("Test.constructor", "b", b, "\"Number\""); this._c = a + b; } }
20
71
0.496667
694015a66fa6d34d0d8d4651f82b24c4c9d36d29
525
lua
Lua
plugins/lua/sand_modules/include.lua
wiox/hash.js
c1de06ed81326fc83753fcb72fd356bc1f10e1db
[ "CC0-1.0" ]
10
2015-04-06T17:43:30.000Z
2015-09-04T19:47:38.000Z
plugins/lua/sand_modules/include.lua
meepen/hash.js
9fe94b946fd1d6cf86ec06362deaa370ec884e89
[ "CC0-1.0" ]
45
2015-04-06T19:51:45.000Z
2015-09-28T09:54:30.000Z
plugins/lua/sand_modules/include.lua
meepen/hash.js
9fe94b946fd1d6cf86ec06362deaa370ec884e89
[ "CC0-1.0" ]
34
2015-04-06T19:56:19.000Z
2015-10-04T00:46:52.000Z
local function include( path ) if type( path ) ~= "string" then error( "bad argument #1 to 'include' (string expected, got " .. type( path ) .. ")", 2 ) end if not path:match( "^[%w/]+$" ) then error( "bad argument #1 to 'include' (path contains illegal characters)", 2 ) end local f, err = loadfile( "user_modules/" .. path .. ".lua", "t", ENV ) if err then error( err, 2 ) end local ret = { pcall( f ) } if not ret[1] then error( ret[2], 2 ) end return table.unpack( ret, 2 ) end return include
21
92
0.6
c936918d1a572a8359e67347c47c0471001dbf01
366
swift
Swift
Sources/DeclarativeLayoutKit/Helpers/MainThread.swift
uuttff8/DeclarativeLayoutKit
4cdea6c38e9da57597373ce7c3d396a3e5b8453e
[ "MIT" ]
40
2020-09-04T15:36:59.000Z
2022-02-01T10:17:39.000Z
Sources/DeclarativeLayoutKit/Helpers/MainThread.swift
uuttff8/DeclarativeLayoutKit
4cdea6c38e9da57597373ce7c3d396a3e5b8453e
[ "MIT" ]
null
null
null
Sources/DeclarativeLayoutKit/Helpers/MainThread.swift
uuttff8/DeclarativeLayoutKit
4cdea6c38e9da57597373ce7c3d396a3e5b8453e
[ "MIT" ]
2
2020-11-28T21:23:35.000Z
2021-07-06T17:55:15.000Z
// // File.swift // // // Created by Ernest Babayan on 05.07.2021. // import Foundation func onMainThread<Input>(_ handler: @escaping (Input) -> Void) -> (Input) -> Void { return { (input: Input) in guard !Thread.isMainThread else { return handler(input) } DispatchQueue.main.async(execute: { handler(input) }) } }
19.263158
83
0.590164
8534ed137fa5dc16de7d90704742370904dd135c
1,734
rs
Rust
src/s4/c27.rs
mishazharov/cryptopals_rust
53b45881c48e385fecf88a9a33bb11564e98511b
[ "MIT" ]
null
null
null
src/s4/c27.rs
mishazharov/cryptopals_rust
53b45881c48e385fecf88a9a33bb11564e98511b
[ "MIT" ]
null
null
null
src/s4/c27.rs
mishazharov/cryptopals_rust
53b45881c48e385fecf88a9a33bb11564e98511b
[ "MIT" ]
null
null
null
use crate::symmetric::aes::*; use crate::s1::c6::xor_vecs; struct Server<'a> { crypter: &'a (dyn CryptoWrapper + 'a) } impl<'a> Server<'a> { pub fn new(crypter: &'a (dyn CryptoWrapper + 'a)) -> Server<'a> { Server { crypter: crypter } } pub fn encrypt(&self, text: &[u8]) -> Vec<u8> { self.crypter.encrypt(text) } // Can't implement CryptoWrapper since we have a different return type :( pub fn decrypt(&self, ct: &[u8]) -> Result<usize, Vec<u8>> { // Ok(status code), Err(plaintext) let pt = self.crypter.decrypt(ct).unwrap(); for i in &pt { if *i >= 128 { return Err(pt); } } return Ok(0); } } fn attack_server(ct: &[u8], s: Server) -> Vec<u8> { let mut new_ct = ct[0..AES_BLOCK_SIZE].to_vec(); new_ct.extend_from_slice(&[0u8; AES_BLOCK_SIZE]); new_ct.extend_from_slice(&ct[0..AES_BLOCK_SIZE]); let pt = s.decrypt(&new_ct); let vec_pt = match pt { Err(e) => e, Ok(_) => { panic!("Failed because decryption succeeded"); } }; xor_vecs(&vec_pt[0..AES_BLOCK_SIZE], &vec_pt[AES_BLOCK_SIZE * 2..AES_BLOCK_SIZE * 3]).unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn test_attack_key_equals_nonce() { let key = gen_random_16_bytes(); let c= AesCbcWrapper::new(&key, Some(key), false); let s = Server::new(&c); let pt = "You would not believe your eyes If ten million fireflies Lit up the world as I fell asleep"; let ct = s.encrypt(pt.as_bytes()); let found_key = attack_server(&ct, s); assert_eq!(key.to_vec(), found_key); } }
27.09375
99
0.556517
e7a25d2a548a3a1fb969f478449309beb775e07f
1,702
swift
Swift
Driver/HomeworkApp1/OnlineKeywordPhotoSlideViewController.swift
Eonil/HomeworkApp1
c9a97e43587d198c023f8607544bf0a0600da73c
[ "MIT" ]
null
null
null
Driver/HomeworkApp1/OnlineKeywordPhotoSlideViewController.swift
Eonil/HomeworkApp1
c9a97e43587d198c023f8607544bf0a0600da73c
[ "MIT" ]
2
2015-02-26T15:34:32.000Z
2015-02-26T15:35:43.000Z
Driver/HomeworkApp1/OnlineKeywordPhotoSlideViewController.swift
Eonil/HomeworkApp1
c9a97e43587d198c023f8607544bf0a0600da73c
[ "MIT" ]
null
null
null
//// //// OnlineKeywordPhotoSlideViewController.swift //// HomeworkApp1 //// //// Created by Hoon H. on 2015/02/26. //// //// // //import Foundation //import UIKit // // // // ///// You must set `keywordData` before this object to be appears. //final class OnlineKeywordPhotoSlideViewController: UIViewController { // // var keywordData:String? { // didSet { // listing?.cancel() // if let s = keywordData { // listing = Client.fetchImageURLs(s, completion: { [unowned self](imageURLs) -> () in // // It's a logic bug if this is called after `self` deallocated. // assert(imageURLs != nil, "Error while loading image URLs.") // dispatch_async(dispatch_get_main_queue()) { // assert(NSThread.mainThread() == NSThread.currentThread()) // // println("URL loaded.") // if let us = imageURLs { // self.core.imageURLs = us // } else { // self.core.imageURLs = [] // } // } // }) // } // } // } // // override func viewDidLoad() { // super.viewDidLoad() // } // override func viewWillAppear(animated: Bool) { // assert(keywordData != nil, "You must set `keywordData` before this object to be appears.") // super.viewWillAppear(animated) // } // override func viewDidAppear(animated: Bool) { // super.viewDidAppear(animated) // } // override func viewWillDisappear(animated: Bool) { // super.viewWillDisappear(animated) // listing?.cancel() // listing = nil // } // override func viewDidDisappear(animated: Bool) { // super.viewDidDisappear(animated) // } // // //// // // private var listing = nil as Transmission? // private let core = PhotoSlideViewController() //} // // // // // // // // // // // // // // // // //
21.012346
94
0.614571
86987657068724f3a30e0acbc9968774de41e182
1,928
swift
Swift
Plant-Reg/UIImage+Extension.swift
sjfeng1999/iOS-coreMLapp-Plant-Pathology-Recognition
aa3b650780bbe32d93b12f74a2b22f73d74930ec
[ "MIT" ]
1
2021-02-21T03:49:59.000Z
2021-02-21T03:49:59.000Z
Plant-Reg/UIImage+Extension.swift
sjfeng1999/iOS-coreMLapp-Plant-Pathology-Recognition
aa3b650780bbe32d93b12f74a2b22f73d74930ec
[ "MIT" ]
null
null
null
Plant-Reg/UIImage+Extension.swift
sjfeng1999/iOS-coreMLapp-Plant-Pathology-Recognition
aa3b650780bbe32d93b12f74a2b22f73d74930ec
[ "MIT" ]
null
null
null
// // ContentView.swift // Plant-Reg // // Created by Willer AI on 2020/4/9. // Copyright © 2020 Willer AI. All rights reserved. // import UIKit extension UIImage { var buffer: CVPixelBuffer? { let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary var pixelBuffer: CVPixelBuffer? let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(self.size.width), Int(self.size.height), kCVPixelFormatType_32ARGB, attrs, &pixelBuffer) guard status == kCVReturnSuccess else { return nil } CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: pixelData, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) context?.translateBy(x: 0, y: self.size.height) context?.scaleBy(x: 1.0, y: -1.0) UIGraphicsPushContext(context!) self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) UIGraphicsPopContext() CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) return pixelBuffer } func resize(size: CGSize) -> UIImage? { UIGraphicsBeginImageContext(CGSize(width: size.width, height: size.height)) self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
38.56
260
0.677905
3b119934fc82592aa6e43b2032a8ea9529264ea6
218
h
C
include/il2cpp/Dpr/SequenceEditor/CameraAnimationDoubleIntro.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
1
2022-01-15T20:20:27.000Z
2022-01-15T20:20:27.000Z
include/il2cpp/Dpr/SequenceEditor/CameraAnimationDoubleIntro.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
include/il2cpp/Dpr/SequenceEditor/CameraAnimationDoubleIntro.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp.h" void Dpr_SequenceEditor_CameraAnimationDoubleIntro___ctor (Dpr_SequenceEditor_CameraAnimationDoubleIntro_o* __this, Dpr_SequenceEditor_Macro_o* macro, const MethodInfo* method_info);
36.333333
182
0.87156
8335fd2a7b90ee725a57851d6d3be678497a8bbb
15,071
swift
Swift
Keyboard/KeyboardKey.swift
mrh-is/Automoji
31c36f8fcf9dedcf3052cdf16f438558002b1c0a
[ "BSD-3-Clause" ]
4
2015-05-13T02:32:53.000Z
2017-01-18T15:30:44.000Z
Keyboard/KeyboardKey.swift
mrh-is/Automoji
31c36f8fcf9dedcf3052cdf16f438558002b1c0a
[ "BSD-3-Clause" ]
null
null
null
Keyboard/KeyboardKey.swift
mrh-is/Automoji
31c36f8fcf9dedcf3052cdf16f438558002b1c0a
[ "BSD-3-Clause" ]
null
null
null
// // KeyboardKey.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 6/9/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit // components // - large letter popup // - if hold, show extra menu — default if finger slides off // - translucent buttons // - light and dark themes // - iPad sizes // - iPad slide apart keyboard // - JSON-like parsing // > storyboard + custom widget // > framework // system bugs // - attach() receives incorrect enum when using -O // - inability to use class generics without compiler crashes // - inability to use method generics without compiler crashes when using -O // - framework (?) compiler crashes when using -Ofast // this is more of a view controller than a view, so we'll let the model stuff slide for now class KeyboardKey: UIControl, KeyboardView { let model: Key var keyView: KeyboardKeyBackground var popup: KeyboardKeyBackground? var connector: KeyboardConnector? var color: UIColor { didSet { updateColors() }} var underColor: UIColor { didSet { updateColors() }} var borderColor: UIColor { didSet { updateColors() }} var drawUnder: Bool { didSet { updateColors() }} var drawBorder: Bool { didSet { updateColors() }} var textColor: UIColor { didSet { updateColors() }} var downColor: UIColor? { didSet { updateColors() }} var downUnderColor: UIColor? { didSet { updateColors() }} var downBorderColor: UIColor? { didSet { updateColors() }} var downTextColor: UIColor? { didSet { updateColors() }} var popupDirection: Direction var ambiguityTimer: NSTimer! // QQQ: var constraintStore: [(UIView, NSLayoutConstraint)] = [] // QQQ: override var enabled: Bool { didSet { updateColors() }} override var selected: Bool { didSet { updateColors() }} override var highlighted: Bool { didSet { updateColors() }} var text: String! { didSet { self.redrawText() } } override var frame: CGRect { didSet { self.redrawText() } } init(frame: CGRect, model: Key) { self.model = model self.keyView = KeyboardKeyBackground(frame: CGRectZero) let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // self.holder0 = UIVisualEffectView(effect: blurEffect) // self.holder = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect)) self.color = UIColor.whiteColor() self.underColor = UIColor.grayColor() self.borderColor = UIColor.blackColor() self.drawUnder = true self.drawBorder = false self.textColor = UIColor.blackColor() self.popupDirection = Direction.Up super.init(frame: frame) self.clipsToBounds = false self.keyView.setTranslatesAutoresizingMaskIntoConstraints(false) self.addSubview(self.keyView) self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)) self.ambiguityTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "timerLoop", userInfo: nil, repeats: true) // self.holder0.contentView.addSubview(self.holder) // self.holder0.clipsToBounds = false // self.holder0.contentView.clipsToBounds = false // self.addSubview(self.holder0) // self.holder.contentView.addSubview(self.keyView) // self.holder.clipsToBounds = false // self.holder.contentView.clipsToBounds = false } required init(coder: NSCoder) { fatalError("NSCoding not supported") } // override func sizeThatFits(size: CGSize) -> CGSize { // return super.sizeThatFits(size) // } // override func updateConstraints() { // // } func timerLoop() { if self.popup != nil && self.popup!.hasAmbiguousLayout() { NSLog("exercising ambiguity...") self.popup!.exerciseAmbiguityInLayout() } } override func layoutSubviews() { super.layoutSubviews() if self.popup != nil { self.popupDirection = Direction.Up self.setupPopupConstraints(self.popupDirection) self.configurePopup(self.popupDirection) super.layoutSubviews() var upperLeftCorner = self.popup!.frame.origin var popupPosition = self.superview!.convertPoint(upperLeftCorner, fromView: self) // TODO: hack // if popupPosition.y < 0 { if self.popup!.bounds.height < 10 { if self.frame.origin.x < self.superview!.bounds.width/2 { // TODO: hack self.popupDirection = Direction.Right } else { self.popupDirection = Direction.Left } self.setupPopupConstraints(self.popupDirection) self.configurePopup(self.popupDirection) super.layoutSubviews() } } // self.holder.frame = self.bounds // self.holder0.frame = self.bounds self.redrawText() } func redrawText() { // self.keyView.frame = self.bounds // self.button.frame = self.bounds // // self.button.setTitle(self.text, forState: UIControlState.Normal) self.keyView.text = ((self.text != nil) ? self.text : "") } // TODO: StyleKit? func updateColors() { var keyboardViews: [KeyboardView] = [self.keyView] if self.popup != nil { keyboardViews.append(self.popup!) } if self.connector != nil { keyboardViews.append(self.connector!) } var switchColors = self.highlighted || self.selected for kv in keyboardViews { var keyboardView = kv keyboardView.color = (switchColors && self.downColor != nil ? self.downColor! : self.color) keyboardView.underColor = (switchColors && self.downUnderColor != nil ? self.downUnderColor! : self.underColor) keyboardView.borderColor = (switchColors && self.downBorderColor != nil ? self.downBorderColor! : self.borderColor) keyboardView.drawUnder = self.drawUnder keyboardView.drawBorder = self.drawBorder } self.keyView.label.textColor = (switchColors && self.downTextColor != nil ? self.downTextColor! : self.textColor) if self.popup != nil { self.popup!.label.textColor = (switchColors && self.downTextColor != nil ? self.downTextColor! : self.textColor) } } func setupPopupConstraints(dir: Direction) { // TODO: superview optional assert(self.popup != nil, "popup not found") for (view, constraint) in self.constraintStore { view.removeConstraint(constraint) } self.constraintStore = [] let gap: CGFloat = 8 let gapMinimum: CGFloat = 3 // size ratios // TODO: fix for direction var widthConstraint = NSLayoutConstraint( item: self.popup!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 26) self.constraintStore.append((self, widthConstraint) as (UIView, NSLayoutConstraint)) // TODO: is this order right??? var heightConstraint = NSLayoutConstraint( item: self.popup!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Height, multiplier: -1, constant: 94) heightConstraint.priority = 750 self.constraintStore.append((self, heightConstraint) as (UIView, NSLayoutConstraint)) // gap from key let directionToAttribute = [ Direction.Up: NSLayoutAttribute.Top, Direction.Down: NSLayoutAttribute.Bottom, Direction.Left: NSLayoutAttribute.Left, Direction.Right: NSLayoutAttribute.Right, ] var gapConstraint = NSLayoutConstraint( item: self.keyView, attribute: directionToAttribute[dir]!, relatedBy: NSLayoutRelation.Equal, toItem: self.popup, attribute: directionToAttribute[dir.opposite()]!, multiplier: 1, constant: gap) gapConstraint.priority = 700 self.constraintStore.append((self, gapConstraint) as (UIView, NSLayoutConstraint)) var gapMinConstraint = NSLayoutConstraint( item: self.keyView, attribute: directionToAttribute[dir]!, relatedBy: NSLayoutRelation.Equal, toItem: self.popup, attribute: directionToAttribute[dir.opposite()]!, multiplier: 1, constant: (dir.horizontal() ? -1 : 1) * gapMinimum) gapMinConstraint.priority = 1000 self.constraintStore.append((self, gapMinConstraint) as (UIView, NSLayoutConstraint)) // can't touch top var cantTouchTopConstraint = NSLayoutConstraint( item: self.popup!, attribute: directionToAttribute[dir]!, relatedBy: (dir == Direction.Right ? NSLayoutRelation.LessThanOrEqual : NSLayoutRelation.GreaterThanOrEqual), toItem: self.superview, attribute: directionToAttribute[dir]!, multiplier: 1, constant: 2) // TODO: layout cantTouchTopConstraint.priority = 1000 self.constraintStore.append((self.superview!, cantTouchTopConstraint) as (UIView, NSLayoutConstraint)) if dir.horizontal() { var cantTouchTopConstraint = NSLayoutConstraint( item: self.popup!, attribute: directionToAttribute[Direction.Up]!, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: self.superview, attribute: directionToAttribute[Direction.Up]!, multiplier: 1, constant: 5) // TODO: layout cantTouchTopConstraint.priority = 1000 self.constraintStore.append((self.superview!, cantTouchTopConstraint) as (UIView, NSLayoutConstraint)) } else { var cantTouchSideConstraint = NSLayoutConstraint( item: self.superview!, attribute: directionToAttribute[Direction.Right]!, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: self.popup, attribute: directionToAttribute[Direction.Right]!, multiplier: 1, constant: 17) // TODO: layout cantTouchSideConstraint.priority = 1000 var cantTouchSideConstraint2 = NSLayoutConstraint( item: self.superview!, attribute: directionToAttribute[Direction.Left]!, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: self.popup, attribute: directionToAttribute[Direction.Left]!, multiplier: 1, constant: 17) // TODO: layout cantTouchSideConstraint2.priority = 1000 self.constraintStore.append((self.superview!, cantTouchSideConstraint) as (UIView, NSLayoutConstraint)) self.constraintStore.append((self.superview!, cantTouchSideConstraint2) as (UIView, NSLayoutConstraint)) } // centering var centerConstraint = NSLayoutConstraint( item: self.keyView, attribute: (dir.horizontal() ? NSLayoutAttribute.CenterY : NSLayoutAttribute.CenterX), relatedBy: NSLayoutRelation.Equal, toItem: self.popup, attribute: (dir.horizontal() ? NSLayoutAttribute.CenterY : NSLayoutAttribute.CenterX), multiplier: 1, constant: 0) centerConstraint.priority = 500 self.constraintStore.append((self, centerConstraint) as (UIView, NSLayoutConstraint)) for (view, constraint) in self.constraintStore { view.addConstraint(constraint) } } func configurePopup(direction: Direction) { assert(self.popup != nil, "popup not found") self.keyView.attach(direction) self.popup!.attach(direction.opposite()) let kv = self.keyView let p = self.popup! self.connector?.removeFromSuperview() self.connector = KeyboardConnector(start: kv, end: p, startConnectable: kv, endConnectable: p, startDirection: direction, endDirection: direction.opposite()) self.connector!.layer.zPosition = -1 self.addSubview(self.connector!) self.drawBorder = true if direction == Direction.Up { self.popup!.drawUnder = false self.connector!.drawUnder = false } } func showPopup() { if self.popup == nil { self.layer.zPosition = 1000 self.popup = KeyboardKeyBackground(frame: CGRectZero) self.popup!.setTranslatesAutoresizingMaskIntoConstraints(false) self.popup!.cornerRadius = 9.0 self.addSubview(self.popup!) self.popup!.text = self.keyView.text self.keyView.label.hidden = true self.popup!.label.font = self.popup!.label.font.fontWithSize(22 * 2.0) } } func hidePopup() { if self.popup != nil { self.connector?.removeFromSuperview() self.connector = nil self.popup?.removeFromSuperview() self.popup = nil self.keyView.label.hidden = false self.keyView.attach(nil) self.keyView.drawBorder = false self.layer.zPosition = 0 } } }
38.742931
217
0.60905
0ef925a13cd432075e101b093fc8c4f4030d72f8
54
ts
TypeScript
libs/vivid/src/lib/vivid.ts
YonatanKra/vivid-nx
d2acccff60ceb70907a5880aa82c2cf555d71903
[ "Apache-2.0" ]
null
null
null
libs/vivid/src/lib/vivid.ts
YonatanKra/vivid-nx
d2acccff60ceb70907a5880aa82c2cf555d71903
[ "Apache-2.0" ]
null
null
null
libs/vivid/src/lib/vivid.ts
YonatanKra/vivid-nx
d2acccff60ceb70907a5880aa82c2cf555d71903
[ "Apache-2.0" ]
null
null
null
export function vivid(): string { return 'vivid'; }
13.5
33
0.666667
20468c4f3569ed953adb6f9cfcc23d15332c0090
707
css
CSS
js/layer.css
hjjia/easylog
919241e4bee01e2f7b37b6d2f0d238780c9ed247
[ "MIT" ]
null
null
null
js/layer.css
hjjia/easylog
919241e4bee01e2f7b37b6d2f0d238780c9ed247
[ "MIT" ]
null
null
null
js/layer.css
hjjia/easylog
919241e4bee01e2f7b37b6d2f0d238780c9ed247
[ "MIT" ]
null
null
null
.mask{position: fixed;width: 100%;height: 100%;top: 0;left: 0;background: rgba(0,0,0,0.5);} .warn{width: 80%;overflow: hidden;position: absolute;top: 50%;left: 0;right: 0;margin:auto;border-radius: 8px;background-color: #fff;transform: translateY(-50%);-webkit-transform: translateY(-50%);} .warn .title{width: 100%;height: 50px;line-height: 57px;text-align: center;font-size: 18px;} .warn .content{margin: 0 auto;font-size: 14px;line-height: 20px;text-align: center;padding-left: 21px;padding-right: 21px;padding-bottom: 24px;} .warn .i_know{border-top: 1px solid #eee;width: 100%;height:46px;color: #4691ee;text-align: center;font-size: 16px;line-height: 46px; cursor:pointer;} .hide {display:none;}
58.916667
198
0.731259
dd75d8b65699cec0797e3dbdd9fc714cca2b89e5
534
swift
Swift
DDMvvm/Classes/Extensions/UIKitExtensions/StringExtensions.swift
duyduong/DDMvvm.Carthage
23d2ecd0cc11f3b8b0aa37ad098c4fe6ee41a43c
[ "MIT" ]
null
null
null
DDMvvm/Classes/Extensions/UIKitExtensions/StringExtensions.swift
duyduong/DDMvvm.Carthage
23d2ecd0cc11f3b8b0aa37ad098c4fe6ee41a43c
[ "MIT" ]
null
null
null
DDMvvm/Classes/Extensions/UIKitExtensions/StringExtensions.swift
duyduong/DDMvvm.Carthage
23d2ecd0cc11f3b8b0aa37ad098c4fe6ee41a43c
[ "MIT" ]
null
null
null
// // StringExtensions.swift // DDMvvm // // Created by Dao Duy Duong on 9/26/18. // import UIKit public extension String { func toURL() -> URL? { return URL(string: self) } func toURLRequest() -> URLRequest? { if let url = toURL() { return URLRequest(url: url) } return nil } func toHex() -> Int? { return Int(self, radix: 16) } func trim() -> String { return trimmingCharacters(in: .whitespacesAndNewlines) } }
15.257143
62
0.526217
712c4ecef24fcbd02e8ae2346d078a8c0c2b43a4
203
ts
TypeScript
lib/PassThroughAdapter.ts
en0/RepoJS
6dafc261123e0f8be96e43bda734a4263a6932d6
[ "MIT" ]
null
null
null
lib/PassThroughAdapter.ts
en0/RepoJS
6dafc261123e0f8be96e43bda734a4263a6932d6
[ "MIT" ]
null
null
null
lib/PassThroughAdapter.ts
en0/RepoJS
6dafc261123e0f8be96e43bda734a4263a6932d6
[ "MIT" ]
null
null
null
import { IColumnAdapter } from "."; export class PassThroughAdapter implements IColumnAdapter<any, any> { public fromEntity(val: any) { return val; } public toEntity(val: any) { return val; } }
29
69
0.704433
0b906bf27fc67aeba61a035efc941b80ca56e405
4,305
py
Python
lib/aquilon/worker/formats/list.py
ned21/aquilon
6562ea0f224cda33b72a6f7664f48d65f96bd41a
[ "Apache-2.0" ]
7
2015-07-31T05:57:30.000Z
2021-09-07T15:18:56.000Z
lib/aquilon/worker/formats/list.py
ned21/aquilon
6562ea0f224cda33b72a6f7664f48d65f96bd41a
[ "Apache-2.0" ]
115
2015-03-03T13:11:46.000Z
2021-09-20T12:42:24.000Z
lib/aquilon/worker/formats/list.py
ned21/aquilon
6562ea0f224cda33b72a6f7664f48d65f96bd41a
[ "Apache-2.0" ]
13
2015-03-03T11:17:59.000Z
2021-09-09T09:16:41.000Z
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2017 Contributor # # 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. """List formatter.""" from operator import attrgetter from six import string_types from sqlalchemy.orm.collections import InstrumentedList from sqlalchemy.orm.query import Query from sqlalchemy.ext.associationproxy import _AssociationList from aquilon.worker.formats.formatters import ObjectFormatter class ListFormatter(ObjectFormatter): def format_raw(self, result, indent="", embedded=True, indirect_attrs=True): if hasattr(self, "template_raw"): return ObjectFormatter.format_raw(self, result, indent, embedded=embedded, indirect_attrs=indirect_attrs) return "\n".join(self.redirect_raw(item, indent, embedded=embedded, indirect_attrs=indirect_attrs) for item in result) def format_csv(self, result, writer): for item in result: self.redirect_csv(item, writer) def format_djb(self, result): return "\n".join(self.redirect_djb(item) for item in result) def format_proto(self, result, container, embedded=True, indirect_attrs=True): for item in result: skeleton = container.add() ObjectFormatter.redirect_proto(item, skeleton, embedded=embedded, indirect_attrs=indirect_attrs) ObjectFormatter.handlers[list] = ListFormatter() ObjectFormatter.handlers[Query] = ListFormatter() ObjectFormatter.handlers[InstrumentedList] = ListFormatter() ObjectFormatter.handlers[_AssociationList] = ListFormatter() class StringList(list): pass class StringListFormatter(ListFormatter): """ Format a list of object as strings, regardless of type """ def format_raw(self, objects, indent="", embedded=True, indirect_attrs=True): return "\n".join(indent + str(obj) for obj in objects) def format_csv(self, objects, writer): for obj in objects: writer.writerow((str(obj),)) ObjectFormatter.handlers[StringList] = StringListFormatter() class StringAttributeList(list): def __init__(self, items, attr): if isinstance(attr, string_types): self.getter = attrgetter(attr) else: self.getter = attr super(StringAttributeList, self).__init__(items) class StringAttributeListFormatter(ListFormatter): """ Format a single attribute of every object as a string """ def format_raw(self, objects, indent="", embedded=True, indirect_attrs=True): return "\n".join(indent + str(objects.getter(obj)) for obj in objects) def format_csv(self, objects, writer): for obj in objects: writer.writerow((str(objects.getter(obj)),)) def format_proto(self, objects, container, embedded=True, indirect_attrs=True): # This method always populates the first field of the protobuf message, # regardless of how that field is called. field_name = None for obj in objects: msg = container.add() if not field_name: field_name = msg.DESCRIPTOR.fields[0].name setattr(msg, field_name, str(objects.getter(obj))) # TODO: if obj is really the full DB object rather than just a # string, and it has other attributes already loaded, then we could # add those attributes to the protobuf message "for free". Let's see # if a usecase comes up. ObjectFormatter.handlers[StringAttributeList] = StringAttributeListFormatter()
38.783784
83
0.673635
3026dcd0103b3f7e363d0466fa59361bb92a942c
1,834
swift
Swift
Client/Frontend/Animators/JumpAndSpinAnimator.swift
durul/Continuous-Delivery-for-Mobile-with-fastlane
5ec3386948d73d32b5ab4c0a907ee3505b0be9d6
[ "MIT" ]
1
2018-09-07T11:16:06.000Z
2018-09-07T11:16:06.000Z
Client/Frontend/Animators/JumpAndSpinAnimator.swift
durul/Continuous-Delivery-for-Mobile-with-fastlane
5ec3386948d73d32b5ab4c0a907ee3505b0be9d6
[ "MIT" ]
null
null
null
Client/Frontend/Animators/JumpAndSpinAnimator.swift
durul/Continuous-Delivery-for-Mobile-with-fastlane
5ec3386948d73d32b5ab4c0a907ee3505b0be9d6
[ "MIT" ]
1
2018-11-17T21:03:12.000Z
2018-11-17T21:03:12.000Z
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class JumpAndSpinAnimator: Animatable { fileprivate let AnimationDuration: Double = 0.5 fileprivate let AnimationOffset: CGFloat = -80 static func animateFromView(_ view: UIView, offset: CGFloat, completion: ((Bool) -> Void)?) { let animator = JumpAndSpinAnimator() animator.animateFromView(view, offset: offset, completion: completion) } func animateFromView(_ viewToAnimate: UIView, offset: CGFloat? = nil, completion: ((Bool) -> Void)?) { let offset = offset ?? AnimationOffset let offToolbar = CGAffineTransform(translationX: 0, y: offset) UIView.animate(withDuration: AnimationDuration, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 2.0, options: [], animations: { () -> Void in viewToAnimate.transform = offToolbar let rotation = CABasicAnimation(keyPath: "transform.rotation") rotation.toValue = CGFloat(2.0 * Double.pi) rotation.isCumulative = true rotation.duration = self.AnimationDuration + 0.075 rotation.repeatCount = 1.0 rotation.timingFunction = CAMediaTimingFunction(controlPoints: 0.32, 0.70, 0.18, 1.00) viewToAnimate.layer.add(rotation, forKey: "rotateStar") }, completion: { finished in UIView.animate(withDuration: self.AnimationDuration, delay: 0.15, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in viewToAnimate.transform = CGAffineTransform.identity }, completion: completion) }) } }
50.944444
177
0.664667
1ea16ce8f7bc21ebd839c70511613b1b2b95e555
5,710
lua
Lua
classes/Vector3.lua
Cheez3D/MTA-Gui
6fcb1028e90000b975ba9d192a1815e6f5c66b94
[ "MIT" ]
null
null
null
classes/Vector3.lua
Cheez3D/MTA-Gui
6fcb1028e90000b975ba9d192a1815e6f5c66b94
[ "MIT" ]
null
null
null
classes/Vector3.lua
Cheez3D/MTA-Gui
6fcb1028e90000b975ba9d192a1815e6f5c66b94
[ "MIT" ]
null
null
null
local classes = classes; local super = classes.Object; local class = inherit({ name = "Vector3", super = super, func = inherit({}, super.func), get = inherit({}, super.get), set = inherit({}, super.set), concrete = true, }, super); classes[class.name] = class; local cache = setmetatable({}, { __mode = "v" }); function class.new(x, y, z) if (x ~= nil) then local x_t = type(x); if (x_t ~= "number") then error("bad argument #1 to '" ..__func__.. "' (number expected, got " ..x_t.. ")", 2); end else x = 0; end if (y ~= nil) then local y_t = type(y); if (y_t ~= "number") then error("bad argument #2 to '" ..__func__.. "' (number expected, got " ..y_t.. ")", 2); end else y = 0; end if (z ~= nil) then local z_t = type(z); if (z_t ~= "number") then error("bad argument #3 to '" ..__func__.. "' (number expected, got " ..z_t.. ")", 2); end else z = 0; end local cacheId = x.. ":" ..y.. ":" ..z; local obj = cache[cacheId]; if (not obj) then local success; success, obj = pcall(super.new, class); if (not success) then error(obj, 2) end obj.x = x; obj.y = y; obj.z = z; cache[cacheId] = obj; end return obj; end class.meta = extend({ __metatable = super.name.. ":" ..class.name, __add = function(obj1, obj2) local obj1_t = type(obj1); if (obj1_t ~= "Vector3" and obj1_t ~= "number") then error("bad operand #1 to '+' (Vector3/number expected, got " ..obj1_t.. ")", 2); end local obj2_t = type(obj2); if (obj2_t ~= "Vector3" and obj2_t ~= "number") then error("bad operand #2 to '+' (Vector3/number expected, got " ..obj2_t.. ")", 2); end return (obj1_t == "number") and class.new(obj1+obj2.x, obj1+obj2.y, obj1+obj2.z) or (obj2_t == "number") and class.new(obj1.x+obj2, obj1.y+obj2, obj1.z+obj2) or class.new(obj1.x+obj2.x, obj1.y+obj2.y, obj1.z+obj2.z); end, __sub = function(obj1, obj2) local obj1_t = type(obj1); if (obj1_t ~= "Vector3" and obj1_t ~= "number") then error("bad operand #1 to '-' (Vector3/number expected, got " ..obj1_t.. ")", 2); end local obj2_t = type(obj2); if (obj2_t ~= "Vector3" and obj2_t ~= "number") then error("bad operand #2 to '-' (Vector3/number expected, got " ..obj2_t.. ")", 2); end return (obj1_t == "number") and class.new(obj1-obj2.x, obj1-obj2.y, obj1-obj2.z) or (obj2_t == "number") and class.new(obj1.x-obj2, obj1.y-obj2, obj1.z-obj2) or class.new(obj1.x-obj2.x, obj1.y-obj2.y, obj1.z-obj2.z); end, __mul = function(obj1, obj2) local obj1_t = type(obj1); if (obj1_t ~= "Vector3" and obj1_t ~= "number") then error("bad operand #1 to '*' (Vector3/number expected, got " ..obj1_t.. ")", 2); end local obj2_t = type(obj2); if (obj2_t ~= "Vector3" and obj2_t ~= "number") then error("bad operand #2 to '*' (Vector3/Matrix3x3/number expected, got " ..obj2_t.. ")", 2); end return (obj1_t == "number") and class.new(obj1*obj2.x, obj1*obj2.y, obj1*obj2.z) or (obj2_t == "Matrix3x3") and class.new( obj1.x*obj2.m00 + obj1.y*obj2.m10 + obj1.z*obj2.m20, obj1.x*obj2.m01 + obj1.y*obj2.m11 + obj1.z*obj2.m21, obj1.x*obj2.m02 + obj1.y*obj2.m12 + obj1.z*obj2.m22 ) or (obj2_t == "number") and class.new(obj1.x*obj2, obj1.y*obj2, obj1.z*obj2) or class.new(obj1.x*obj2.x, obj1.y*obj2.y, obj1.z*obj2.z); end, __div = function(obj1, obj2) local obj1_t = type(obj1); if (obj1_t ~= "Vector3" and obj1_t ~= "number") then error("bad operand #1 to '/' (Vector3/number expected, got " ..obj1_t.. ")", 2); end local obj2_t = type(obj2); if (obj2_t ~= "Vector3" and obj2_t ~= "number") then error("bad operand #2 to '/' (Vector3/number expected, got " ..obj2_t.. ")", 2); end return (obj1_t == "number") and class.new(obj1/obj2.x, obj1/obj2.y, obj1/obj2.z) or (obj2_t == "number") and class.new(obj1.x/obj2, obj1.y/obj2, obj1.z/obj2) or class.new(obj1.x/obj2.x, obj1.y/obj2.y, obj1.z/obj2.z); end, __unm = function(obj) return class.new(-obj.x, -obj.y, -obj.z); end, __tostring = function(obj) return obj.x.. ", " ..obj.y.. ", " ..obj.z; end, }, super.meta); function class.func.unpack(obj) return obj.x, obj.y, obj.z; end function class.get.mag(obj) if (not obj.mag) then obj.mag = math.sqrt(obj.x^2 + obj.y^2 + obj.z^2); end return obj.mag; end function class.get.unit(obj) local mag = obj:get_mag(); if (mag == 0) then error("attempt to get unit of 0 magnitude vector", 2); end if (not obj.unit) then obj.unit = obj/mag; end return obj.unit; end function class.get.vec2(obj) if (not obj.vec2) then obj.vec2 = classes.Vector2.new(obj.x, obj.y); end return obj.vec2; end
28.838384
103
0.499475
9bf55476bfe50a18eb513c7edda6545195880c02
5,809
js
JavaScript
config/router.config.js
familyuu/cloud_admin
1cff2f5a0e35c2d6403d1815fe60bff7c53c0d8f
[ "MIT" ]
null
null
null
config/router.config.js
familyuu/cloud_admin
1cff2f5a0e35c2d6403d1815fe60bff7c53c0d8f
[ "MIT" ]
null
null
null
config/router.config.js
familyuu/cloud_admin
1cff2f5a0e35c2d6403d1815fe60bff7c53c0d8f
[ "MIT" ]
null
null
null
export default [ // user { path: '/user', component: './layouts/UserLayout', routes: [ { path: '/user', redirect: '/user/login' }, { path: '/user/login', name: 'login', component: './User/Login' }, { path: '/user/register', name: 'register', component: './User/Register' }, { path: '/user/register-result', name: 'register.result', component: './User/RegisterResult', }, ], }, // app { path: '/', component: './layouts/SecurityLayout', routes: [ { path: '/', component: './layouts/BasicLayout', Routes: ['src/pages/Authorized'], routes: [ //Home { path: '/', redirect: '/dashboard', authority: ['admin', 'user'] }, { path: '/dashboard', name: 'dashboard', icon: 'dashboard', component: './locDashboard', }, //platform { path: '/platform', icon: 'deployment-unit', name: 'platform', routes: [ { path: '/platform/automation', name: 'automation', component: './locPlatform/Automation', }, { path: '/platform/registration', name: 'registration', component: './locPlatform/Registration', }, { path: '/platform/repository', name: 'repository', component: './locPlatform/Repository', }, { path: '/platform/installation', name: 'installation', component: './locPlatform/Installation', }, { path: '/platform/inventory', name: 'inventory', component: './locPlatform/Inventory', }, ], }, //storage { path: '/storage', icon: 'cluster', name: 'storage', routes: [ { path: '/storage/ceph', name: 'ceph', component: './locStorage/cephCardList', }, { path: '/storage/ceph/:id', name: 'detail', hideInMenu: true, component: './locStorage/cephDetail', }, ], }, //cloud { path: '/cloud', icon: 'cloud', name: 'cloud', routes: [ { path: '/cloud/basic', name: 'basic', component: './locCloud/CloudCardList', }, { path: '/cloud/:id', name: 'detail', hideInMenu: true, component: './locCloud/CloudDetail', routes: [ { path: '/cloud/:id/', redirect: '/cloud/:id/Summary', }, { path: '/cloud/:id/summary', name: 'summary', component: './locCloud/Summary', }, { path: '/cloud/:id/infrastructure', name: 'infrastructure', component: './locCloud/Infrastructure', }, { path: '/cloud/:id/network', name: 'network', component: './locCloud/Network', }, { path: '/cloud/:id/configuration', name: 'configuration', component: './locCloud/Configuration', }, ], }, ], }, // Personal Info { path: '/account', name: 'account', icon: 'user', routes: [ { path: '/account/profile', name: 'profile', component: './locAccount/Profile', routes: [ { path: '/account/Profile', redirect: '/account/profile/basic', }, { path: '/account/profile/basic', component: './locAccount/Profile/Basic', }, { path: '/account/profile/settings', component: './locAccount/Profile/Settings', }, ], }, ], }, //Exception { path: '/exception', name: 'exception', icon: 'warning', hideInMenu: true, routes: [ // exception { path: '/exception/403', name: 'not-permission', component: './Exception/403', }, { path: '/exception/404', name: 'not-find', component: './Exception/404', }, { path: '/exception/500', name: 'server-error', component: './Exception/500', }, { path: '/exception/trigger', name: 'trigger', hideInMenu: true, component: './Exception/TriggerException', }, ], }, { component: './404', }, ], }, ], }, ];
28.757426
81
0.351523
b7eaff2c18faa4f5ed56dc5cc7c9324626535b91
2,076
lua
Lua
scripts/KC01-JP/c100284002.lua
MisterKay7/ygopro-pre-script
a2aac1ae52c584c5ed0b28ad28b89b85e8a88540
[ "Unlicense" ]
73
2016-01-10T03:33:05.000Z
2022-03-16T18:21:12.000Z
scripts/KC01-JP/c100284002.lua
MisterKay7/ygopro-pre-script
a2aac1ae52c584c5ed0b28ad28b89b85e8a88540
[ "Unlicense" ]
220
2016-01-08T18:50:47.000Z
2022-03-31T03:13:22.000Z
scripts/KC01-JP/c100284002.lua
MisterKay7/ygopro-pre-script
a2aac1ae52c584c5ed0b28ad28b89b85e8a88540
[ "Unlicense" ]
157
2016-02-11T01:16:24.000Z
2022-02-15T05:55:37.000Z
--削りゆく命 -- --Script by Trishula9 function c100284002.initial_effect(c) c:SetUniqueOnField(1,0,100284002) c:EnableCounterPermit(0x15f) --activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --add counter local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_COUNTER) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_PHASE+PHASE_END) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(1) e2:SetCondition(c100284002.ctcon) e2:SetTarget(c100284002.cttg) e2:SetOperation(c100284002.ctop) c:RegisterEffect(e2) --discard local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_TOGRAVE+CATEGORY_HANDES) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetCode(EVENT_FREE_CHAIN) e3:SetRange(LOCATION_SZONE) e3:SetHintTiming(0,TIMING_MAIN_END+TIMING_BATTLE_END) e3:SetCondition(c100284002.hdcon) e3:SetTarget(c100284002.hdtg) e3:SetOperation(c100284002.hdop) c:RegisterEffect(e3) end function c100284002.ctcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==1-tp end function c100284002.cttg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_COUNTER,nil,1,0,0x15f) end function c100284002.ctop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then c:AddCounter(0x15f,1) end end function c100284002.hdcon(e,tp,eg,ep,ev,re,r,rp) local ph=Duel.GetCurrentPhase() return ph>=PHASE_MAIN1 and ph<=PHASE_MAIN2 and e:GetHandler():GetCounter(0x15f)>0 end function c100284002.hdtg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsAbleToGrave() and c:GetFlagEffect(100284002)==0 end e:SetLabel(c:GetCounter(0x15f)) c:RegisterFlagEffect(100284002,RESET_CHAIN,0,1) Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,e:GetHandler(),1,0,0) end function c100284002.hdop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsRelateToEffect(e) and Duel.SendtoGrave(e:GetHandler(),REASON_EFFECT) then Duel.BreakEffect() Duel.DiscardHand(1-tp,nil,e:GetLabel(),e:GetLabel(),REASON_EFFECT+REASON_DISCARD) end end
31.938462
94
0.790462
6b52f257a3ba4b678051065376349338fe1cd819
28
kt
Kotlin
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/hierarchy/java/KKJ/kj_.kt
06needhamt/intellij-community
63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b
[ "Apache-2.0" ]
null
null
null
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/hierarchy/java/KKJ/kj_.kt
06needhamt/intellij-community
63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b
[ "Apache-2.0" ]
null
null
null
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/hierarchy/java/KKJ/kj_.kt
06needhamt/intellij-community
63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b
[ "Apache-2.0" ]
null
null
null
fun kj() { KJ().test() }
9.333333
15
0.392857
0a29262ff7ab72ed1494bd3af6f3510555aa2255
2,713
ts
TypeScript
fuse.ts
proudust/hello-world-electron
9adb0a72a8ae01572e94f24a9b929facfddad593
[ "MIT" ]
null
null
null
fuse.ts
proudust/hello-world-electron
9adb0a72a8ae01572e94f24a9b929facfddad593
[ "MIT" ]
null
null
null
fuse.ts
proudust/hello-world-electron
9adb0a72a8ae01572e94f24a9b929facfddad593
[ "MIT" ]
null
null
null
import * as procces from 'child_process'; import * as builder from 'electron-builder'; import { fusebox, sparky } from 'fuse-box'; import { promisify } from 'util'; class Context { public isProduction: boolean | undefined = undefined; public getMainConfig(): ReturnType<typeof fusebox> { return fusebox({ entry: 'index.ts', target: 'electron', output: 'dist/main/$name-$hash', homeDir: 'src/main', useSingleBundle: true, dependencies: { ignoreAllExternal: true }, cache: { enabled: true, root: '.cache/main', }, logging: { level: 'succinct' }, }); } public getRendererConfig(): ReturnType<typeof fusebox> { const template = this.isProduction ? 'index.prod.html' : 'index.dev.html'; return fusebox({ entry: 'index.tsx', target: 'browser', output: 'dist/renderer/$name-$hash', homeDir: 'src/renderer', webIndex: { publicPath: './', template: `src/renderer/${template}`, }, cache: { enabled: false, root: '.cache/renderer', }, dependencies: { include: ['tslib'] }, devServer: { httpServer: false, hmrServer: { port: 7878 }, }, logging: { level: 'succinct' }, }); } } const { task, rm, exec } = sparky(Context); task('dev', async context => { context.isProduction = false; await rm('./dist'); await promisify(procces.exec)(`tsc ./src/main/preload.ts --outDir ./dist`); await context.getRendererConfig().runDev(); await context.getMainConfig().runDev(handler => { handler.onComplete(output => { output.electron.handleMainProcess(); }); }); }); async function build(context: Context, isDir: boolean): Promise<void> { context.isProduction = true; await rm('./dist'); await promisify(procces.exec)(`tsc ./src/main/preload.ts --outDir ./dist`); await context.getRendererConfig().runProd({ uglify: false }); const response = await context.getMainConfig().runProd({ uglify: true }); const main = `./main/${response.bundles[0].stat.localPath}`; await builder.build({ dir: isDir, config: { appId: 'io.github.proudust.helloworld-electron', extraMetadata: { main }, files: [ '!**/*', { filter: 'package.json' }, { from: './dist', filter: ['main', 'renderer', 'preload.js'] }, ], win: { target: 'portable', }, mac: { target: 'zip', }, linux: { target: 'zip', }, }, }); } task('build', () => exec('build:prod')); task('build:prod', async context => build(context, false)); task('build:dir', async context => build(context, true));
25.35514
78
0.582381
1c29cc19d708262c2878810fb2ab289242f423b5
967
kt
Kotlin
src/main/kotlin/at/cpickl/gadsu/preferences/prefs.kt
christophpickl/gadsu
f6a84c42e1985bc53d566730ed0552b3ae71d94b
[ "Apache-2.0" ]
2
2016-05-01T23:04:45.000Z
2020-11-14T23:23:02.000Z
src/main/kotlin/at/cpickl/gadsu/preferences/prefs.kt
christophpickl/gadsu
f6a84c42e1985bc53d566730ed0552b3ae71d94b
[ "Apache-2.0" ]
135
2016-05-01T14:45:07.000Z
2018-06-09T05:50:13.000Z
src/main/kotlin/at/cpickl/gadsu/preferences/prefs.kt
christophpickl/gadsu
f6a84c42e1985bc53d566730ed0552b3ae71d94b
[ "Apache-2.0" ]
1
2020-11-14T23:23:04.000Z
2020-11-14T23:23:04.000Z
package at.cpickl.gadsu.preferences import at.cpickl.gadsu.mail.MailPreferencesData import java.awt.Dimension import java.awt.Point import java.io.File interface Prefs { var preferencesData: PreferencesData var windowDescriptor: WindowDescriptor? var clientPictureDefaultFolder: File var recentSaveReportFolder: File var recentSaveMultiProtocolFolder: File var mailPreferencesData: MailPreferencesData fun clear() } // MINOR @UI - check if screen size changed, or better: just be sure its not over the max (luxury: save per display setting!) data class WindowDescriptor(val location: Point, val size: Dimension) { companion object { private val MIN_WIDTH = 100 private val MIN_HEIGHT = 100 } // MINOR @UI BUG - could be that there is some minor glitch and size calculation/prefs-storage (java.awt.Dimension[width=3,height=4]) val isValidSize = size.width >= MIN_WIDTH && size.height >= MIN_HEIGHT }
30.21875
137
0.745605
018eaefa6c3ff365f1343214f6f7b885bd4545bf
7,479
swift
Swift
Swift/Practice/UdemyInstargramCopy/UdemyInstargramCopy/Controller/Feed/FeedVC.swift
WiSeoungHwan/TIL
702a56a7c23de94062e14c20f6c1d86ad50ff089
[ "MIT" ]
3
2018-09-06T09:07:38.000Z
2019-11-14T13:15:51.000Z
Swift/Practice/UdemyInstargramCopy/UdemyInstargramCopy/Controller/Feed/FeedVC.swift
WiSeoungHwan/TIL
702a56a7c23de94062e14c20f6c1d86ad50ff089
[ "MIT" ]
null
null
null
Swift/Practice/UdemyInstargramCopy/UdemyInstargramCopy/Controller/Feed/FeedVC.swift
WiSeoungHwan/TIL
702a56a7c23de94062e14c20f6c1d86ad50ff089
[ "MIT" ]
null
null
null
// // FeedVC.swift // UdemyInstargramCopy // // Created by Wi on 25/05/2019. // Copyright © 2019 Wi. All rights reserved. // import UIKit import Firebase private let reuseIdentifier = "Cell" class FeedVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, FeedCellDelegate{ // MARK: - Properties var posts = [Post]() var viewSinglePost = false var post: Post? override func viewDidLoad() { super.viewDidLoad() collectionView.backgroundColor = .white // register cell classes self.collectionView!.register(FeedCell.self, forCellWithReuseIdentifier: reuseIdentifier) // configure logout btn configureNavBar() // configure refresh control let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged) collectionView.refreshControl = refreshControl // fetch posts if !viewSinglePost{ fetchPosts() } updateUserFeeds() } // MARK: - UIColectionViewFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = view.frame.width var height = width + 8 + 40 + 8 height += 50 height += 60 return CGSize(width: width, height: height) } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if viewSinglePost { return 1 } else { return posts.count } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FeedCell cell.delegate = self if viewSinglePost { if let post = self.post { cell.post = post } } else { cell.post = posts[indexPath.row] } return cell } // MARK: - FeedCellDelegate func handleUsernameTapped(for cell: FeedCell) { guard let post = cell.post else {return} let userProfileVC = UserProfileVC(collectionViewLayout: UICollectionViewFlowLayout()) userProfileVC.user = post.user navigationController?.pushViewController(userProfileVC, animated: true) } func handleOptionsTapped(for cell: FeedCell) { print("handel o tapped") } func handleLikeTapped(for cell: FeedCell) { guard let post = cell.post else {return} guard let postId = post.postId else {return} if post.didLike{ post.addjustLikes(addLike: false,completion: {likes in print("number of liks is \(likes)") cell.likeButton.setImage(#imageLiteral(resourceName: "like_unselected"), for: .normal) }) } else { post.addjustLikes(addLike: false,completion: {likes in print("number of liks is \(likes)") cell.likeButton.setImage(#imageLiteral(resourceName: "like_selected"), for: .normal) }) } guard let likes = post.likes else {return} cell.likesLabel.text = "\(likes) likes" } func handleCommentTapped(for cell: FeedCell) { print("handel c tapped") } // MARK: - Handlers @objc func handleRefresh(){ posts.removeAll(keepingCapacity: false) fetchPosts() collectionView.reloadData() } @objc func handleShowMessages(){ print("send button tap") } func updateLikesStructures(with postId: String, addLike: Bool){ guard let currentUid = Auth.auth().currentUser?.uid else {return} if addLike{ } else { } } // MARK: - Configuration func configureNavBar(){ if !viewSinglePost{ self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout)) } self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "send2"), style: .plain, target: self, action: #selector(handleShowMessages)) self.navigationItem.title = "Feed" } // MARK: Action @objc func handleLogout(){ let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // add logout action alertController.addAction(UIAlertAction(title: "Logout", style: .destructive, handler: { (_) in do{ // sign out try Auth.auth().signOut() let loginVC = LoginVC() let navController = UINavigationController(rootViewController: loginVC) self.present(navController, animated: true, completion: nil) print("Successfully logout") }catch{ print("failed to sign out") } })) // add cancel action alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } // MARK: - API func updateUserFeeds(){ guard let currentUid = Auth.auth().currentUser?.uid else {return} USER_FOLLOWING_REF.child(currentUid).observe(.childAdded) { (snapshot) in let followingUserId = snapshot.key USER_POSTS_REF.child(followingUserId).observe(.childAdded, with: { (snapshot) in let postId = snapshot.key USER_FEED_REF.child(currentUid).updateChildValues([postId: 1]) }) } USER_POSTS_REF.child(currentUid).observe(.childAdded) { (snapshot) in let postId = snapshot.key USER_FEED_REF.child(currentUid).updateChildValues([postId: 1]) } } func fetchPosts(){ guard let currentUid = Auth.auth().currentUser?.uid else {return} USER_FEED_REF.child(currentUid).observe(.childAdded) { (snapshot) in let postId = snapshot.key Database.fetchPost(with: postId, completion: { (post) in self.posts.append(post) self.posts.sort(by: { (post1, post2) -> Bool in return post1.creationDate > post2.creationDate }) // stop refreshing self.collectionView.refreshControl?.endRefreshing() self.collectionView.reloadData() }) } } }
29.678571
177
0.563845
6d9a9da2e625f25914cfae7b87e9871891a6df56
4,586
lua
Lua
BGAnimations/ScreenTitleMenu overlay/default.lua
raveitoutofficial/raveitout
45ea0fdb1ce3495ed5e0dcf1a94c51733e4ab77c
[ "Unlicense" ]
10
2019-02-01T17:34:42.000Z
2022-03-13T17:28:23.000Z
BGAnimations/ScreenTitleMenu overlay/default.lua
raveitoutofficial/raveitout
45ea0fdb1ce3495ed5e0dcf1a94c51733e4ab77c
[ "Unlicense" ]
46
2018-10-02T18:03:48.000Z
2019-05-16T14:39:02.000Z
BGAnimations/ScreenTitleMenu overlay/default.lua
raveitoutofficial/raveitout
45ea0fdb1ce3495ed5e0dcf1a94c51733e4ab77c
[ "Unlicense" ]
3
2019-02-26T01:40:53.000Z
2019-06-03T21:32:10.000Z
--[[function rectGen(width, height, lineSize, bgColor) return Def.ActorFrame{ --Background transparency Def.Quad{ InitCommand=cmd(setsize,width, height;diffuse,bgColor); }; --Bottom line Def.Quad{ InitCommand=cmd(setsize,width + lineSize, lineSize;addy,height/2;); }; --Top line Def.Quad{ InitCommand=cmd(setsize,width + lineSize, lineSize;addy,-height/2;); --2 = right aligned }; --Left line Def.Quad{ InitCommand=cmd(setsize,lineSize, height + lineSize;addx,-width/2;); --2 = right aligned }; --Right line Def.Quad{ InitCommand=cmd(setsize,lineSize, height + lineSize;addx,width/2;); --2 = bottom aligned }; }; end;]] return Def.ActorFrame{ LoadFont("common normal")..{ Text=SysInfo["InternalName"].."-"..SysInfo["Version"]; InitCommand=cmd(xy,5,5;horizalign,left;vertalign,top;zoom,.5;Stroke,Color("Black")); }; LoadFont("common normal")..{ InitCommand=cmd(xy,5,15;horizalign,left;vertalign,top;zoom,.5;Stroke,Color("Black")); OnCommand=function(self) local aspectRatio = round(GetScreenAspectRatio(),2); if aspectRatio == 1.78 then self:settext("DISPLAY TYPE: HD"); elseif aspectRatio == 1.33 then self:settext("DISPLAY TYPE: SD"); else self:settext("DISPLAY TYPE: ???"); end; end; }; LoadFont("common normal")..{ InitCommand=cmd(xy,5,25;horizalign,left;vertalign,top;zoom,.5;Stroke,Color("Black")); OnCommand=function(self) if PREFSMAN:GetPreference("AllowExtraStage") then self:settext("HEARTS PER PLAY: "..HeartsPerPlay.."+"); else self:settext("HEARTS PER PLAY: "..HeartsPerPlay); end; end; }; --[[Def.ActorFrame{ InitCommand=cmd(xy,120,100;); rectGen(220,100,2,color("0,0,0,.5"))..{ }; LoadFont("facu/_zona pro bold 40px")..{ Text="Update Available"; InitCommand=cmd(addy,-38;zoom,.5;skewx,-0.125); }; Def.Quad{ InitCommand=cmd(setsize,180,2;fadeleft,.2;faderight,.2;addy,-25); }; LoadFont("facu/_zona pro bold 40px")..{ Text="There is an update available.\nRestart the machine to apply it."; InitCommand=cmd(zoom,.3); }; };]] LoadFont("Common normal")..{ --Unlock status data Condition=DoDebug; InitCommand=cmd(x,SCREEN_LEFT+10;y,SCREEN_TOP+10+30;vertalign,top;horizalign,left;zoom,0.5;); OnCommand=function(self) self:settext("Total unlocks: "..UNLOCKMAN:GetNumUnlocks().."\nUnlocked items: "..UNLOCKMAN:GetNumUnlocked()); end; }; LoadFont("Common normal")..{ --Checkear unlock status de EntryID TT002 Condition=DoDebug; InitCommand=cmd(x,_screen.cx;y,_screen.cy+220;zoom,0.5;); OnCommand=function(self) local IsLocked = IsEntryIDLocked("TT002"); if IsLocked ~= -1 then if IsLocked then self:settext("OMG THIS ACTUALLY WORKED? CALL KOTAKU! (EntryID TT002 is locked)"); else self:settext("WHY ARE GORILLAS HERE? (EntryID TT002 is unlocked)"); end; else self:settext("EntryID not valid"); end; end; }; --[[ LoadFont("Common normal")..{ --Make sure of the EntryID InitCommand=cmd(visible,DoDebug;x,SCREEN_RIGHT-10;y,_screen.cy+180;zoom,0.5;horizalign,right;); OnCommand=function(self) if UNLOCKMAN:FindEntryID("All Around the World") then self:settext("EntryID for All Around the World is: ".. UNLOCKMAN:FindEntryID("All Around the World")); end; end; }; ]] LoadFont("Common normal")..{ --Songs played (machine profile) Condition=DoDebug; InitCommand=cmd(x,SCREEN_LEFT+10;y,_screen.cy+180;zoom,0.5;horizalign,left;settext,"Songs played (machine profile): "..PROFILEMAN:GetMachineProfile():GetNumTotalSongsPlayed();); }; -- Memory cards LoadActor(THEME:GetPathG("", "USB icon"))..{ InitCommand=cmd(horizalign,left;vertalign,bottom;xy,SCREEN_LEFT+5,SCREEN_BOTTOM;zoom,.2); OnCommand=cmd(visible,ToEnumShortString(MEMCARDMAN:GetCardState(PLAYER_1)) == 'ready'); StorageDevicesChangedMessageCommand=cmd(playcommand,"On"); }; LoadActor(THEME:GetPathG("", "USB icon"))..{ InitCommand=cmd(horizalign,right;vertalign,bottom;xy,SCREEN_RIGHT-5,SCREEN_BOTTOM;zoom,.2); --OnCommand=cmd(visible,true); OnCommand=cmd(visible,ToEnumShortString(MEMCARDMAN:GetCardState(PLAYER_2)) == 'ready'); StorageDevicesChangedMessageCommand=cmd(playcommand,"On"); }; };
32.992806
180
0.640427
91a672aea2c7d2a8a4838b0c8ba286b630606e61
1,345
kt
Kotlin
app/src/main/java/dev/kissed/podlodka_compose/theming/AppTheme.kt
kissedcode/podlodka_crew_4_compose
1a96defadc46d1315de0ffac27d81138bd0b6b4f
[ "Apache-2.0" ]
1
2021-04-30T09:13:18.000Z
2021-04-30T09:13:18.000Z
app/src/main/java/dev/kissed/podlodka_compose/theming/AppTheme.kt
kissedcode/podlodka_crew_4_compose
1a96defadc46d1315de0ffac27d81138bd0b6b4f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/dev/kissed/podlodka_compose/theming/AppTheme.kt
kissedcode/podlodka_crew_4_compose
1a96defadc46d1315de0ffac27d81138bd0b6b4f
[ "Apache-2.0" ]
null
null
null
package dev.kissed.podlodka_compose.app import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.Colors import androidx.compose.material.MaterialTheme import androidx.compose.material.MaterialTheme.shapes import androidx.compose.material.MaterialTheme.typography import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import dev.kissed.podlodka_compose.theming.AppColors @Composable fun AppTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val themeColors = Colors( primary = AppColors.primary(), primaryVariant = AppColors.primaryVariant(), secondary = AppColors.secondary(), secondaryVariant = AppColors.secondary(), background = AppColors.background(), surface = AppColors.surface(), onPrimary = AppColors.onPrimary(), onSecondary = AppColors.onSecondary(), onBackground = AppColors.onBackground(), onSurface = AppColors.onSurface(), isLight = !darkTheme, error = if (darkTheme) Color(0xFFCF6679) else Color(0xFFB00020), onError = if (darkTheme) Color.White else Color.Black ) MaterialTheme( colors = themeColors, typography = typography, shapes = shapes, content = content ) }
34.487179
91
0.768773
725526507647401fbd4e2915ced9430fbe701cde
6,964
kt
Kotlin
room/room-common/src/main/java/androidx/room/Fts4.kt
semoro/androidx
9edfb9c95d72d2a93f4c13b9634b5dd821aaf193
[ "Apache-2.0" ]
7
2020-07-23T18:52:59.000Z
2020-07-23T20:31:41.000Z
room/room-common/src/main/java/androidx/room/Fts4.kt
semoro/androidx
9edfb9c95d72d2a93f4c13b9634b5dd821aaf193
[ "Apache-2.0" ]
2
2020-07-23T19:17:07.000Z
2020-07-23T19:43:42.000Z
room/room-common/src/main/java/androidx/room/Fts4.kt
semoro/androidx
9edfb9c95d72d2a93f4c13b9634b5dd821aaf193
[ "Apache-2.0" ]
5
2020-07-23T18:45:08.000Z
2020-07-23T18:56:15.000Z
/* * Copyright 2018 The Android Open Source Project * * 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 androidx.room import kotlin.reflect.KClass import androidx.annotation.RequiresApi import androidx.room.FtsOptions.TOKENIZER_SIMPLE import androidx.room.FtsOptions.MatchInfo import androidx.room.FtsOptions.Order /** * Marks an [Entity] annotated class as a FTS4 entity. This class will have a mapping SQLite * FTS4 table in the database. * * [FTS3 and FTS4] (https://www.sqlite.org/fts3.html) are SQLite virtual table modules * that allows full-text searches to be performed on a set of documents. * * An FTS entity table always has a column named `rowid` that is the equivalent of an * `INTEGER PRIMARY KEY` index. Therefore, an FTS entity can only have a single field * annotated with [PrimaryKey], it must be named `rowid` and must be of * `INTEGER` affinity. The field can be optionally omitted in the class but can still be * used in queries. * * All fields in an FTS entity are of `TEXT` affinity, except the for the 'rowid' and * 'languageid' fields. * * Example: * * ``` * @Entity * @Fts4 * data class Mail ( * @PrimaryKey * @ColumnInfo(name = "rowid") * val rowId: Int, * val subject: String, * val body: String * ) * ``` * * @see [Entity] * @see [Dao] * @see [Database] * @see [PrimaryKey] * @see [ColumnInfo] */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.BINARY) @RequiresApi(16) public annotation class Fts4( /** * The tokenizer to be used in the FTS table. * * The default value is [FtsOptions.TOKENIZER_SIMPLE]. Tokenizer arguments can be defined * with [tokenizerArgs]. * * If a custom tokenizer is used, the tokenizer and its arguments are not verified at compile * time. * * For details, see [SQLite tokernizers documentation](https://www.sqlite.org/fts3.html#tokenizer) * * @return The tokenizer to use on the FTS table. Built-in available tokenizers are * [FtsOptions.TOKENIZER_SIMPLE], [FtsOptions.TOKENIZER_PORTER] and * [FtsOptions.TOKENIZER_UNICODE61]. * @see [tokenizerArgs] */ val tokenizer: String = TOKENIZER_SIMPLE, /** * Optional arguments to configure the defined tokenizer. * * Tokenizer arguments consist of an argument name, followed by an "=" character, followed by * the option value. For example, `separators=.` defines the dot character as an * additional separator when using the [FtsOptions.TOKENIZER_UNICODE61] tokenizer. * * The available arguments that can be defined depend on the tokenizer defined, see the * [SQLite tokenizers documentation](https://www.sqlite.org/fts3.html#tokenizer) for details. * * @return A list of tokenizer arguments strings. */ val tokenizerArgs: Array<String> = [], /** * The external content entity who's mapping table will be used as content for the FTS table. * * Declaring this value makes the mapping FTS table of this entity operate in "external content" * mode. In such mode the FTS table does not store its own content but instead uses the data in * the entity mapped table defined in this value. This option allows FTS4 to forego storing the * text being indexed which can be used to achieve significant space savings. * * In "external mode" the content table and the FTS table need to be synced. Room will create * the necessary triggers to keep the tables in sync. Therefore, all write operations should * be performed against the content entity table and not the FTS table. * * The content sync triggers created by Room will be removed before migrations are executed and * are re-created once migrations are complete. This prevents the triggers from interfering with * migrations but means that if data needs to be migrated then write operations might need to be * done in both the FTS and content tables. * * See the [External Content FTS4 Tables](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_) * documentation for details. * * @return The external content entity. */ val contentEntity: KClass<*> = Any::class, /** * The column name to be used as 'languageid'. * * Allows the FTS4 extension to use the defined column name to specify the language stored in * each row. When this is defined a field of type `INTEGER` with the same name must * exist in the class. * * FTS queries are affected by defining this option, see * [the languageid= option documentation](https://www.sqlite.org/fts3.html#the_languageid_option) * for details. * * @return The column name to be used as 'languageid'. */ val languageId: String = "", /** * The FTS version used to store text matching information. * * The default value is [MatchInfo.FTS4]. Disk space consumption can be reduced by * setting this option to FTS3, see * [the matchinfo= option documentation](https://www.sqlite.org/fts3.html#the_matchinfo_option) * for details. * * @return The match info version, either [MatchInfo.FTS4] or [MatchInfo.FTS3]. */ val matchInfo: MatchInfo = MatchInfo.FTS4, /** * The list of column names on the FTS table that won't be indexed. * * For details, see the * [notindexed= option documentation](https://www.sqlite.org/fts3.html#the_notindexed_option). * * @return A list of column names that will not be indexed by the FTS extension. */ val notIndexed: Array<String> = [], /** * The list of prefix sizes to index. * * For details, * [the prefix= option documentation](https://www.sqlite.org/fts3.html#the_prefix_option). * * @return A list of non-zero positive prefix sizes to index. */ val prefix: IntArray = [], /** * The preferred 'rowid' order of the FTS table. * * The default value is [Order.ASC]. If many queries are run against the FTS table use * `ORDER BY row DESC` then it may improve performance to set this option to * [Order.DESC], enabling the FTS module to store its data in a way that optimizes * returning results in descending order by `rowid`. * * @return The preferred order, either [Order.ASC] or [Order.DESC]. */ val order: Order = Order.ASC )
38.263736
110
0.689115
64d14c0a21aa7aaeb478917c6ae610ce85dc2e92
1,585
kt
Kotlin
app/src/main/java/archiveasia/jp/co/hakenman/Activity/SplashActivity.kt
dolfalf/Hakenman_Android
1b4b1f8db31b2923071e77236b03d77a02f26c97
[ "MIT" ]
null
null
null
app/src/main/java/archiveasia/jp/co/hakenman/Activity/SplashActivity.kt
dolfalf/Hakenman_Android
1b4b1f8db31b2923071e77236b03d77a02f26c97
[ "MIT" ]
null
null
null
app/src/main/java/archiveasia/jp/co/hakenman/Activity/SplashActivity.kt
dolfalf/Hakenman_Android
1b4b1f8db31b2923071e77236b03d77a02f26c97
[ "MIT" ]
null
null
null
package archiveasia.jp.co.hakenman.Activity import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.os.Handler import archiveasia.jp.co.hakenman.CustomLog import archiveasia.jp.co.hakenman.Extension.yearMonth import archiveasia.jp.co.hakenman.Manager.WorksheetManager import archiveasia.jp.co.hakenman.R import java.util.* class SplashActivity : AppCompatActivity() { companion object { private const val SPLASH_DELAY: Long = 2000 // 2 秒 } private var mDelayHandler: Handler? = null private val mRunnable: Runnable = Runnable { if (!isFinishing) { val intent = Intent(applicationContext, WorksheetListActivity::class.java) startActivity(intent) finish() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) WorksheetManager.loadLocalWorksheet() val currentYearMonth = Date().yearMonth() if (!WorksheetManager.isAlreadyExistWorksheet(currentYearMonth)) { val worksheet = WorksheetManager.createWorksheet(currentYearMonth) WorksheetManager.addWorksheetToJsonFile(worksheet) } mDelayHandler = Handler() mDelayHandler!!.postDelayed(mRunnable, SPLASH_DELAY) CustomLog.d("スプラッシュ画面") } override fun onDestroy() { if (mDelayHandler != null) { mDelayHandler!!.removeCallbacks(mRunnable) } super.onDestroy() } }
28.303571
86
0.694006
e3fec7208978ed3d4dce5d3cf8fb102502787ba7
292
go
Go
core/DatabaseManagement/DTOTable/Sys_Process_Transition.go
sRafieidev/zframe
cc5c4c1729fd1e97cae4de0c8b8a820faedba8e0
[ "Apache-2.0" ]
1
2022-02-22T11:05:43.000Z
2022-02-22T11:05:43.000Z
core/DatabaseManagement/DTOTable/Sys_Process_Transition.go
sRafieidev/zframe
cc5c4c1729fd1e97cae4de0c8b8a820faedba8e0
[ "Apache-2.0" ]
null
null
null
core/DatabaseManagement/DTOTable/Sys_Process_Transition.go
sRafieidev/zframe
cc5c4c1729fd1e97cae4de0c8b8a820faedba8e0
[ "Apache-2.0" ]
null
null
null
package DTOTable type Sys_Process_Transition struct { SYS_PROCESS_TRANSITION_ID int64 FROM_SYS_PROCESS_STATE_ID int32 TO_SYS_PROCESS_STATE_ID int32 TRANSITIONNAME string DESCRIPTION string TRANSITION_CONDITION string TRANSITIONQUERY string }
24.333333
36
0.75
1d1354dba39e7b49b697a17bd030dc0ab28a92e6
59
sql
SQL
src/test/resources/sql/select/ef126c41.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/select/ef126c41.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/select/ef126c41.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:domain.sql ln:367 expect:true select 'y1234'::dtop
19.666667
37
0.728814
5c69fd77e53c1357270c4079699543d6b416d24b
3,289
h
C
InitializeOpenGL/pch.h
tommai78101/InitializingOpenGL
0ed57e4a7531e16e5694bbfb6638a1c9ff2e6b40
[ "MIT" ]
51
2019-02-10T07:32:41.000Z
2021-12-12T18:02:30.000Z
InitializeOpenGL/pch.h
tommai78101/InitializingOpenGL
0ed57e4a7531e16e5694bbfb6638a1c9ff2e6b40
[ "MIT" ]
17
2018-11-06T03:08:46.000Z
2020-06-01T02:36:30.000Z
InitializeOpenGL/pch.h
tommai78101/InitializingOpenGL
0ed57e4a7531e16e5694bbfb6638a1c9ff2e6b40
[ "MIT" ]
1
2019-01-31T03:36:06.000Z
2019-01-31T03:36:06.000Z
#pragma once #ifndef __PCH_H___ # define __PCH_H___ //Defines # define NOMINMAX //Exceptional rules # include <algorithm> using std::max; using std::min; //Common standard headers # include <iostream> # include <fstream> # include <sstream> # include <thread> # include <utility> # include <memory> # include <functional> # include <cstdio> # include <strsafe.h> # include <initializer_list> //Data structures # include <string> # include <stack> # include <deque> # include <array> # include <vector> # include <set> # include <map> # include <unordered_map> # include <unordered_set> //Massive headers # include <Windows.h> # include <gl/GL.h> # include "gl/glext.h" # include "gl/wglext.h" //OpenGL function declarations //Declare them only when we are to use them. //Function pointers are to be declared only once. //ARB functions extern PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB; extern PFNGLDELETEOBJECTARBPROC glDeleteObjectARB; extern PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB; extern PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB; extern PFNGLSHADERSOURCEARBPROC glShaderSourceARB; extern PFNGLCOMPILESHADERARBPROC glCompileShaderARB; extern PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB; extern PFNGLATTACHOBJECTARBPROC glAttachObjectARB; extern PFNGLGETINFOLOGARBPROC glGetInfoLogARB; extern PFNGLLINKPROGRAMARBPROC glLinkProgramARB; extern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB; extern PFNGLUNIFORM4FARBPROC glUniform4fARB; extern PFNGLUNIFORM3FARBPROC glUniform3fARB; extern PFNGLUNIFORM1FARBPROC glUniform1fARB; extern PFNGLUNIFORM1IARBPROC glUniform1iARB; extern PFNGLUNIFORM2FVARBPROC glUniform2fvARB; extern PFNGLGETATTRIBLOCATIONARBPROC glGetAttribLocationARB; extern PFNGLVERTEXATTRIB3FARBPROC glVertexAttrib3fARB; extern PFNGLVERTEXATTRIBPOINTERARBPROC glVertexAttribPointerARB; extern PFNGLENABLEVERTEXATTRIBARRAYARBPROC glEnableVertexAttribArrayARB; extern PFNGLDISABLEVERTEXATTRIBARRAYARBPROC glDisableVertexAttribArrayARB; extern PFNGLGENBUFFERSARBPROC glGenBuffersARB; extern PFNGLBINDBUFFERARBPROC glBindBufferARB; extern PFNGLBUFFERDATAARBPROC glBufferDataARB; //Non-ARB functions extern PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; extern PFNGLBINDVERTEXARRAYPROC glBindVertexArray; extern PFNGLGENBUFFERSPROC glGenBuffers; extern PFNGLCREATESHADERPROC glCreateShader; extern PFNGLDETACHSHADERPROC glDetachShader; extern PFNGLDELETESHADERPROC glDeleteShader; extern PFNGLDELETEPROGRAMPROC glDeleteProgram; extern PFNGLDELETEBUFFERSPROC glDeleteBuffers; extern PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; extern PFNGLGETSHADERIVPROC glGetShaderiv; extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; extern PFNGLGETPROGRAMIVPROC glGetProgramiv; extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; extern PFNGLUSEPROGRAMPROC glUseProgram; #endif
36.142857
74
0.747036
4a51ba1f3fa4efeea285e189780d57cd76da577f
879
js
JavaScript
test.js
krylova-dinara/redux-presentation
f9f3703fff152bcf9ac6059b34e688fcd1691149
[ "MIT" ]
null
null
null
test.js
krylova-dinara/redux-presentation
f9f3703fff152bcf9ac6059b34e688fcd1691149
[ "MIT" ]
null
null
null
test.js
krylova-dinara/redux-presentation
f9f3703fff152bcf9ac6059b34e688fcd1691149
[ "MIT" ]
null
null
null
import { createStore } from 'redux'; // This is a reducer function rating(state = 0, action) { switch (action.type) { case 'LIKE': return state + 1; case 'DISLIKE': return state - 1; default: return state; } } // This is an action creator function ratingUp() { return { type: 'LIKE' }; } function ratingDown() { return { type: 'DISLIKE' }; } // Create a Redux store holding the state of your app. // Its API is { subscribe, dispatch, getState }. const store = createStore(rating); // You can use subscribe() to update the UI in response to state changes. store.subscribe(() => { console.log(store.getState()); }); // The only way to mutate the internal state is to dispatch an action. store.dispatch(ratingUp()); store.dispatch(ratingDown()); store.dispatch(ratingUp());
22.538462
73
0.615472
eb61051dae37f57dbdf82e20aa75f7397279155c
1,044
rs
Rust
src/language/operations/tableau/cur_tableau_add_sun_light.rs
AustinHaugerud/oxidsys
10fdbee244eac982bae441476d9f44cf47b50cb9
[ "MIT" ]
null
null
null
src/language/operations/tableau/cur_tableau_add_sun_light.rs
AustinHaugerud/oxidsys
10fdbee244eac982bae441476d9f44cf47b50cb9
[ "MIT" ]
32
2018-10-28T02:47:09.000Z
2018-11-05T05:56:00.000Z
src/language/operations/tableau/cur_tableau_add_sun_light.rs
AustinHaugerud/oxidsys
10fdbee244eac982bae441476d9f44cf47b50cb9
[ "MIT" ]
1
2018-12-02T19:34:21.000Z
2018-12-02T19:34:21.000Z
use language::operations::{make_param_doc, Operation, ParamInfo}; pub struct CurTableauAddSunLightOp; const DOC : &str = "Not documented. Typically used for tableaus rendered from 3D objects to add a directional light source. Note that position coordinates do not matter, only rotation (i.e. light rays direction) does."; pub const OP_CODE: u32 = 1991; pub const IDENT: &str = "cur_tableau_add_sun_light"; impl Operation for CurTableauAddSunLightOp { fn op_code(&self) -> u32 { OP_CODE } fn documentation(&self) -> &'static str { DOC } fn identifier(&self) -> &'static str { IDENT } fn param_info(&self) -> ParamInfo { ParamInfo { num_required: 4, num_optional: 0, param_docs: vec![ make_param_doc("<position>", ""), make_param_doc("<red_fixed_point>", ""), make_param_doc("<green_fixed_point>", ""), make_param_doc("<blue_fixed_point>", ""), ], } } }
28.216216
219
0.600575
6ba0f00bcfdd1fb6f5a6f06294e4c3d297d0973c
888
h
C
YLCleaner/Xcode-RuntimeHeaders/IDEFoundation/IDEIndexDBTempTable.h
liyong03/YLCleaner
7453187a884c8e783bda1af82cbbb51655ec41c6
[ "MIT" ]
1
2019-02-15T02:16:35.000Z
2019-02-15T02:16:35.000Z
YLCleaner/Xcode-RuntimeHeaders/IDEFoundation/IDEIndexDBTempTable.h
liyong03/YLCleaner
7453187a884c8e783bda1af82cbbb51655ec41c6
[ "MIT" ]
null
null
null
YLCleaner/Xcode-RuntimeHeaders/IDEFoundation/IDEIndexDBTempTable.h
liyong03/YLCleaner
7453187a884c8e783bda1af82cbbb51655ec41c6
[ "MIT" ]
null
null
null
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "NSObject.h" @class IDEIndexDBConnection, IDEIndexDatabase, NSString; @interface IDEIndexDBTempTable : NSObject { IDEIndexDBConnection *_dbConnection; NSString *_tableName; BOOL _readOnly; long long _count; } @property(readonly, nonatomic) IDEIndexDBConnection *dbConnection; // @synthesize dbConnection=_dbConnection; - (void).cxx_destruct; - (void)enumerateFromOffset:(long long)arg1 limit:(long long)arg2 forEachRow:(id)arg3; - (long long)count; - (void)connectionDidClose; - (void)drop; - (int)insertSQLChanges:(id)arg1 withBindings:(id)arg2; - (void)dumpContents; @property(readonly, nonatomic) IDEIndexDatabase *database; - (id)description; - (id)initWithConnection:(id)arg1 name:(id)arg2 schema:(id)arg3; @end
26.909091
109
0.737613
e7edbdfed8164b295e564361932bcbdae312f33f
10,178
py
Python
armory/scenarios/audio_asr.py
GuillaumeLeclerc/armory
c24928701b4ff6fc37cdb994ea784f9733a8e8da
[ "MIT" ]
1
2021-06-17T23:05:58.000Z
2021-06-17T23:05:58.000Z
armory/scenarios/audio_asr.py
GuillaumeLeclerc/armory
c24928701b4ff6fc37cdb994ea784f9733a8e8da
[ "MIT" ]
null
null
null
armory/scenarios/audio_asr.py
GuillaumeLeclerc/armory
c24928701b4ff6fc37cdb994ea784f9733a8e8da
[ "MIT" ]
null
null
null
""" Automatic speech recognition scenario """ import logging from typing import Optional from tqdm import tqdm import numpy as np from art.preprocessing.audio import LFilter, LFilterPyTorch from armory.utils.config_loading import ( load_dataset, load_model, load_attack, load_adversarial_dataset, load_defense_wrapper, load_defense_internal, load_label_targeter, ) from armory.utils import metrics from armory.scenarios.base import Scenario from armory.utils.export import SampleExporter logger = logging.getLogger(__name__) def load_audio_channel(delay, attenuation, pytorch=True): """ Return an art LFilter object for a simple delay (multipath) channel If attenuation == 0 or delay == 0, return an identity channel Otherwise, return a channel with length equal to delay + 1 NOTE: lfilter truncates the end of the echo, so output length equals input length """ delay = int(delay) attenuation = float(attenuation) if delay < 0: raise ValueError(f"delay {delay} must be a nonnegative number (of samples)") if delay == 0 or attenuation == 0: logger.warning("Using an identity channel") numerator_coef = np.array([1.0]) denominator_coef = np.array([1.0]) else: if not (-1 <= attenuation <= 1): logger.warning(f"filter attenuation {attenuation} not in [-1, 1]") # Simple FIR filter with a single multipath delay numerator_coef = np.zeros(delay + 1) numerator_coef[0] = 1.0 numerator_coef[delay] = attenuation denominator_coef = np.zeros_like(numerator_coef) denominator_coef[0] = 1.0 if pytorch: try: return LFilterPyTorch( numerator_coef=numerator_coef, denominator_coef=denominator_coef ) except ImportError: logger.exception("PyTorch not available. Resorting to scipy filter") logger.warning("Scipy LFilter does not currently implement proper gradients") return LFilter(numerator_coef=numerator_coef, denominator_coef=denominator_coef) class AutomaticSpeechRecognition(Scenario): def _evaluate( self, config: dict, num_eval_batches: Optional[int], skip_benign: Optional[bool], skip_attack: Optional[bool], skip_misclassified: Optional[bool], ) -> dict: """ Evaluate the config and return a results dict """ if skip_misclassified: raise ValueError("skip_misclassified shouldn't be set for ASR scenario") model_config = config["model"] estimator, fit_preprocessing_fn = load_model(model_config) audio_channel_config = config.get("adhoc", {}).get("audio_channel") if audio_channel_config is not None: logger.info("loading audio channel") for k in "delay", "attenuation": if k not in audio_channel_config: raise ValueError(f"audio_channel must have key {k}") audio_channel = load_audio_channel(**audio_channel_config) if estimator.preprocessing_defences: estimator.preprocessing_defences.insert(0, audio_channel) else: estimator.preprocessing_defences = [audio_channel] estimator._update_preprocessing_operations() defense_config = config.get("defense") or {} defense_type = defense_config.get("type") if defense_type in ["Preprocessor", "Postprocessor"]: logger.info(f"Applying internal {defense_type} defense to estimator") estimator = load_defense_internal(config["defense"], estimator) if model_config["fit"]: logger.info( f"Fitting model {model_config['module']}.{model_config['name']}..." ) fit_kwargs = model_config["fit_kwargs"] logger.info(f"Loading train dataset {config['dataset']['name']}...") batch_size = config["dataset"].pop("batch_size") config["dataset"]["batch_size"] = fit_kwargs.get( "fit_batch_size", batch_size ) train_data = load_dataset( config["dataset"], epochs=fit_kwargs["nb_epochs"], split=config["dataset"].get("train_split", "train_clean100"), preprocessing_fn=fit_preprocessing_fn, shuffle_files=True, ) config["dataset"]["batch_size"] = batch_size if defense_type == "Trainer": logger.info(f"Training with {defense_type} defense...") defense = load_defense_wrapper(config["defense"], estimator) defense.fit_generator(train_data, **fit_kwargs) else: logger.info("Fitting estimator on clean train dataset...") estimator.fit_generator(train_data, **fit_kwargs) if defense_type == "Transform": # NOTE: Transform currently not supported logger.info(f"Transforming estimator with {defense_type} defense...") defense = load_defense_wrapper(config["defense"], estimator) estimator = defense() attack_config = config["attack"] attack_type = attack_config.get("type") targeted = bool(attack_config.get("targeted")) metrics_logger = metrics.MetricsLogger.from_config( config["metric"], skip_benign=skip_benign, skip_attack=skip_attack, targeted=targeted, ) if config["dataset"]["batch_size"] != 1: logger.warning("Evaluation batch_size != 1 may not be supported.") predict_kwargs = config["model"].get("predict_kwargs", {}) eval_split = config["dataset"].get("eval_split", "test_clean") if skip_benign: logger.info("Skipping benign classification...") else: # Evaluate the ART estimator on benign test examples logger.info(f"Loading test dataset {config['dataset']['name']}...") test_data = load_dataset( config["dataset"], epochs=1, split=eval_split, num_batches=num_eval_batches, shuffle_files=False, ) logger.info("Running inference on benign examples...") for x, y in tqdm(test_data, desc="Benign"): # Ensure that input sample isn't overwritten by estimator x.flags.writeable = False with metrics.resource_context( name="Inference", profiler=config["metric"].get("profiler_type"), computational_resource_dict=metrics_logger.computational_resource_dict, ): y_pred = estimator.predict(x, **predict_kwargs) metrics_logger.update_task(y, y_pred) metrics_logger.log_task() if skip_attack: logger.info("Skipping attack generation...") return metrics_logger.results() # Imperceptible attack still WIP if (config.get("adhoc") or {}).get("skip_adversarial"): logger.info("Skipping adversarial classification...") return metrics_logger.results() # Evaluate the ART estimator on adversarial test examples logger.info("Generating or loading / testing adversarial examples...") if attack_type == "preloaded": test_data = load_adversarial_dataset( attack_config, epochs=1, split="adversarial", num_batches=num_eval_batches, shuffle_files=False, ) else: attack = load_attack(attack_config, estimator) if targeted != attack.targeted: logger.warning( f"targeted config {targeted} != attack field {attack.targeted}" ) test_data = load_dataset( config["dataset"], epochs=1, split=eval_split, num_batches=num_eval_batches, shuffle_files=False, ) if targeted: label_targeter = load_label_targeter(attack_config["targeted_labels"]) export_samples = config["scenario"].get("export_samples") if export_samples is not None and export_samples > 0: sample_exporter = SampleExporter( self.scenario_output_dir, test_data.context, export_samples ) else: sample_exporter = None for x, y in tqdm(test_data, desc="Attack"): with metrics.resource_context( name="Attack", profiler=config["metric"].get("profiler_type"), computational_resource_dict=metrics_logger.computational_resource_dict, ): if attack_type == "preloaded": x, x_adv = x if targeted: y, y_target = y elif attack_config.get("use_label"): x_adv = attack.generate(x=x, y=y) elif targeted: y_target = label_targeter.generate(y) x_adv = attack.generate(x=x, y=y_target) else: x_adv = attack.generate(x=x) # Ensure that input sample isn't overwritten by estimator x_adv.flags.writeable = False y_pred_adv = estimator.predict(x_adv, **predict_kwargs) metrics_logger.update_task(y, y_pred_adv, adversarial=True) if targeted: metrics_logger.update_task( y_target, y_pred_adv, adversarial=True, targeted=True, ) metrics_logger.update_perturbation(x, x_adv) if sample_exporter is not None: sample_exporter.export(x, x_adv, y, y_pred_adv) metrics_logger.log_task(adversarial=True) if targeted: metrics_logger.log_task(adversarial=True, targeted=True) return metrics_logger.results()
39.449612
91
0.599921
73bfc18962546509cd6ae9089f1bd62c7d8b59da
508
swift
Swift
SwiftHelpers/CoreData/SHManagedObjectContext+CascadeSave.swift
miottid/SwiftHelpers
c8361d533080e53db9c1779ff6134429c84a1805
[ "MIT" ]
null
null
null
SwiftHelpers/CoreData/SHManagedObjectContext+CascadeSave.swift
miottid/SwiftHelpers
c8361d533080e53db9c1779ff6134429c84a1805
[ "MIT" ]
null
null
null
SwiftHelpers/CoreData/SHManagedObjectContext+CascadeSave.swift
miottid/SwiftHelpers
c8361d533080e53db9c1779ff6134429c84a1805
[ "MIT" ]
1
2022-01-03T14:52:23.000Z
2022-01-03T14:52:23.000Z
// // SHManagedObjectContext+CascadeSave.swift // SwiftHelpers // // Created by Guillaume Bellue on 18/01/2017. // Copyright © 2017 Muxu.Muxu. All rights reserved. // import CoreData public extension NSManagedObjectContext { func cascadeSave() throws { var contextToSave: NSManagedObjectContext? = self while let ctx = contextToSave { if ctx.hasChanges { try ctx.save() } contextToSave = contextToSave?.parent } } }
21.166667
57
0.624016
331c51cf21a7edb8c933a3fa13b75a18b05760cc
3,919
py
Python
openverse_catalog/dags/common/loader/smithsonian_unit_codes.py
yavik-kapadia/openverse-catalog
853766f2176a96450f456a9fd6675e134c0866e1
[ "MIT" ]
25
2021-05-06T20:53:45.000Z
2022-03-30T23:18:50.000Z
openverse_catalog/dags/common/loader/smithsonian_unit_codes.py
yavik-kapadia/openverse-catalog
853766f2176a96450f456a9fd6675e134c0866e1
[ "MIT" ]
272
2021-05-17T05:53:00.000Z
2022-03-31T23:57:20.000Z
openverse_catalog/dags/common/loader/smithsonian_unit_codes.py
yavik-kapadia/openverse-catalog
853766f2176a96450f456a9fd6675e134c0866e1
[ "MIT" ]
13
2021-06-12T07:09:06.000Z
2022-03-29T17:39:13.000Z
""" This program helps identify smithsonian unit codes which are not yet added to the smithsonian sub-provider dictionary """ import logging from textwrap import dedent import requests from airflow.providers.postgres.hooks.postgres import PostgresHook from common.loader import provider_details as prov from providers.provider_api_scripts import smithsonian logger = logging.getLogger(__name__) DELAY = smithsonian.DELAY API_KEY = smithsonian.API_KEY API_ROOT = smithsonian.API_ROOT UNITS_ENDPOINT = smithsonian.UNITS_ENDPOINT PARAMS = {"api_key": API_KEY, "q": "online_media_type:Images"} SUB_PROVIDERS = prov.SMITHSONIAN_SUB_PROVIDERS SI_UNIT_CODE_TABLE = "smithsonian_new_unit_codes" def initialise_unit_code_table(postgres_conn_id, unit_code_table): postgres = PostgresHook(postgres_conn_id=postgres_conn_id) """ Create table to store new unit codes if it does not exist """ postgres.run( dedent( f""" CREATE TABLE IF NOT EXISTS public.{unit_code_table} ( new_unit_code character varying(80), action character varying(40) ); """ ) ) """ Delete old unit code entries """ postgres.run( dedent( f""" DELETE FROM public.{unit_code_table}; """ ) ) def get_new_and_outdated_unit_codes(unit_code_set, sub_prov_dict=SUB_PROVIDERS): sub_provider_unit_code_set = set() for sub_prov, unit_code_sub_set in sub_prov_dict.items(): sub_provider_unit_code_set = sub_provider_unit_code_set.union(unit_code_sub_set) new_unit_codes = unit_code_set - sub_provider_unit_code_set outdated_unit_codes = sub_provider_unit_code_set - unit_code_set if bool(new_unit_codes): logger.info( f"The new unit codes {new_unit_codes} must be added to " f"the SMITHSONIAN_SUB_PROVIDERS dictionary" ) if bool(outdated_unit_codes): logger.info( f"The outdated unit codes {outdated_unit_codes} must be " f"deleted from the SMITHSONIAN_SUB_PROVIDERS dictionary" ) return new_unit_codes, outdated_unit_codes def alert_unit_codes_from_api( postgres_conn_id, unit_code_table="smithsonian_new_unit_codes", units_endpoint=UNITS_ENDPOINT, query_params=PARAMS, ): response = requests.get(units_endpoint, params=query_params) unit_code_set = set(response.json().get("response", {}).get("terms", [])) new_unit_codes, outdated_unit_codes = get_new_and_outdated_unit_codes(unit_code_set) initialise_unit_code_table(postgres_conn_id, unit_code_table) postgres = PostgresHook(postgres_conn_id=postgres_conn_id) """ Populate the table with new unit codes """ for new_unit_code in new_unit_codes: postgres.run( dedent( f""" INSERT INTO public.{unit_code_table} (new_unit_code, action) VALUES ( '{new_unit_code}', 'add' ); """ ) ) """ Populate the table with outdated unit codes """ for outdated_unit_code in outdated_unit_codes: postgres.run( dedent( f""" INSERT INTO public.{unit_code_table} (new_unit_code, action) VALUES ( '{outdated_unit_code}', 'delete' ); """ ) ) """ Raise exception if human intervention is needed to update the SMITHSONIAN_SUB_PROVIDERS dictionary by checking the entries in the smithsonian_new_unit_codes table """ if bool(new_unit_codes) or bool(outdated_unit_codes): raise Exception( "Please check the smithsonian_new_unit_codes table for necessary " "updates to the SMITHSONIAN_SUB_PROVIDERS dictionary" )
29.02963
88
0.661393
9bdcc06e008410565390de920caa830bf199e26a
1,669
js
JavaScript
src/redux/reducers/__tests__/index.test.js
alebelcor/react-tic-tac-toe
041e9628a8a3f7db2842e87bb97353729784ffb7
[ "MIT" ]
1
2019-05-21T06:12:51.000Z
2019-05-21T06:12:51.000Z
src/redux/reducers/__tests__/index.test.js
alebelcor/react-tic-tac-toe
041e9628a8a3f7db2842e87bb97353729784ffb7
[ "MIT" ]
4
2019-05-19T22:23:43.000Z
2019-11-01T00:18:11.000Z
src/redux/reducers/__tests__/index.test.js
alebelcor/react-tic-tac-toe
041e9628a8a3f7db2842e87bb97353729784ffb7
[ "MIT" ]
null
null
null
import reducer from '../'; import markSpace from '../markSpace'; import reset from '../reset'; jest.mock('../markSpace') jest.mock('../reset') describe('index', () => { it('should execute the "mark space" reducer', () => { markSpace.mockImplementation(() => { return { turns: [ { player: 1, position: 1, }, { player: 2, position: 2, }, ], }; }); let state; let action; state = { turns: [ { player: 1, position: 1, }, ], }; action = { type: 'MARK_SPACE', payload: { position: 2, }, }; expect(reducer(state, action)).toStrictEqual({ turns: [ { player: 1, position: 1, }, { player: 2, position: 2, }, ], }); expect(markSpace).toHaveBeenCalled(); expect(markSpace).toHaveBeenCalledWith(state, action.payload.position); }); it('should execute the "reset" reducer', () => { reset.mockImplementation(() => { return { turns: [], }; }); let state; let action; state = { turns: [ { player: 1, position: 1, }, ], }; action = { type: 'RESET', }; expect(reducer(state, action)).toStrictEqual({ turns: [], }); expect(reset).toHaveBeenCalled(); expect(reset).toHaveBeenCalledWith(); }); it('should return the current state for unknown actions', () => { let state; let action; state = { turns: [ { player: 1, position: 1, }, ], }; action = { type: 'FOO_BAR', }; expect(reducer(state, action)).toStrictEqual({ turns: [ { player: 1, position: 1, }, ], }); }); });
20.353659
75
0.505093
9a361b78a6c1e62456cb50ebed23807617c7ce9f
5,965
lua
Lua
z/it/tag.lua
UriCW/z
5b8c832340b23320826e243352893064aae186c5
[ "Apache-2.0" ]
null
null
null
z/it/tag.lua
UriCW/z
5b8c832340b23320826e243352893064aae186c5
[ "Apache-2.0" ]
null
null
null
z/it/tag.lua
UriCW/z
5b8c832340b23320826e243352893064aae186c5
[ "Apache-2.0" ]
null
null
null
local setmetatable = setmetatable local pairs=pairs local type=type local table=table local z=z local wibox=require("wibox") local awful=require("awful") local beautiful = require("beautiful") module("z.it.tag") tag={ id=1, label="", rules=nil, widget_background=nil, textbox=nil, icon=nil, buttons=nil, awful_tag=nil, default_client_layout=nil } --[[ Construct a new tag from arguments @args.id - optional number, defaults to -1 @args.label - optional string defaults to "blah" @args.rules - optional table (Not implemented yet) @args.textbox - optional wibox.widget.textbox @args.icon - optional icon (Not implemented yet) @args.default_client_layout - optional awful.layout, defaults to awful.layout.suit.floating @args.awful_tag - optional awful.tag, defaults to creating a new tag "label" on screen @scr @args.buttons - optional table of awful.button() @args.clients - optional table of clients to move to the tag ]]-- function tag.new(args,scr) local ret={} if not scr then scr=1 end ret.id=args.id or -1 ret.label=args.label or "blah" ret.rules=args.rules or {} ret.textbox=args.textbox or wibox.widget.textbox() ret.textbox:set_text(ret.label) --Should probably check args.textbox doesn't already have text ret.widget_background=wibox.widget.background() ret.widget_background:set_widget(ret.textbox) ret.icon=args.icon or nil ret.default_client_layout=args.default_client_layout or awful.layout.suit.floating ret.awful_tag=args.awful_tag or awful.tag({ret.label},scr,ret.default_client_layout) --If we are reusing an existing awful tag, but using a different label, rename it to args.label -- if args.awful_tag and args.label then -- ret.awful_tag.name=ret.label -- end ret.buttons=args.buttons or tag.get_default_buttons(ret.awful_tag,scr) ret.textbox:buttons(ret.buttons) --Should probably check args.textbox doesn't already have buttons and maybe append to it ret.textbox:set_align("center") if args.clients then for i,client in pairs(args.clients) do z.debug.msg("Moving client"..i) awful.client.movetotag(ret.awful_tag[scr],client) end end setmetatable(ret,{__index=tag}) --if args.commands, uses a "hack", make tag, viewonly and awful.util.spawn if args.commands then --z.debug.msg("Commands...") awful.tag.viewonly(ret.awful_tag[scr]) for i,c in pairs(args.commands) do --z.debug.msg("Spawn..."..c) local pid=awful.util.spawn(c,true,scr) --z.debug.msg(pid.." "..c) local cli=z.it.utils.get_client_by_pid(pid,scr) if not cli then z.debug.msg("No Cli"); end --z.it.utils.move_client(cli,z.it.element,{}) end end --setmetatable(ret,{__index=tag}) --awful.tag.viewonly(ret.awful_tag[scr]) --ret.awful_tag[scr]:emit_signal("property::selected") --tag.paint(ret,{screen=scr}) return ret end --[[ In the future, i want to be able to pass the taglist.buttons to this, but this requires implementing the rather complicated and obsecure code in awful.widget.taglist and awful.widget.commn (update_list/update_function) ]]-- function tag.get_default_buttons(t,s) ret=awful.util.table.join( awful.button({},1, function() awful.tag.viewonly(t[s]) end) ) return ret end function tag.paint(me,args) local theme=beautiful.get() local fg_focus = args.fg_focus or theme.taglist_fg_focus or theme.fg_focus local bg_focus = args.bg_focus or theme.taglist_bg_focus or theme.bg_focus local fg_urgent = args.fg_urgent or theme.taglist_fg_urgent or theme.fg_urgent local bg_urgent = args.bg_urgent or theme.taglist_bg_urgent or theme.bg_urgent if me.awful_tag[args.screen].selected then me.widget_background:set_bg(bg_focus) me.widget_background:set_fg(fg_focus) else me.widget_background:set_bg(nil) me.widget_background:set_fg(nil) end me.textbox:set_text(me.label) end function tag.rename(me,args) if not args.name then return end me.label=args.name me.textbox:set_text(args.name) if args.screen then me.awful_tag[args.screen].name=args.name else for i,at in pairs(me.awful_tag) do at.name=args.name end end end --[[ @args.screen screen number @args.rescue_tag - an opitonal tag to move clients to @args.force_kill - if set to true and no rescue_tag then kill the clients on tag. returns true on success, false on failure ]]-- function tag.delete(me,args) if not args then args={} end local screen=args.screen local clients=me:get_clients({screen=screen}) if #clients==0 then --No client, we can delete the tag --DO DELETY STUFF HERE for i,at in pairs(me.awful_tag) do awful.tag.delete(at) end me.background_widget=nil me.textbox=nil me=nil --Is this allowed? return true; else for i,client in pairs(clients) do --TODO Check if client is already on another tag if args.rescue_tag then awful.client.movetotag(args.rescue_tag,client) --DO DELETY STUFF HERE return true elseif args.force_kill==true then client:kill() --DO DELETY STUFF HERE return true else return false end end end end function tag.get_clients(me,args) if not args then args={} end if args.screen then return me.awful_tag[args.screen]:clients() end local ret={} for i,aw in pairs(me.awful_tag) do local clients=aw:clients() for j,c in pairs(clients) do table.insert(ret,c) end end return ret end setmetatable(_M, { __call=function(_, ...) return tag.new(...) end })
32.955801
125
0.665717
7f5e242300c2e5890f116f34436bb49c75ab3bb5
6,044
kt
Kotlin
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewContentManager.kt
tgodzik/intellij-community
f5ef4191fc30b69db945633951fb160c1cfb7b6f
[ "Apache-2.0" ]
null
null
null
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewContentManager.kt
tgodzik/intellij-community
f5ef4191fc30b69db945633951fb160c1cfb7b6f
[ "Apache-2.0" ]
null
null
null
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewContentManager.kt
tgodzik/intellij-community
f5ef4191fc30b69db945633951fb160c1cfb7b6f
[ "Apache-2.0" ]
1
2019-12-02T20:40:59.000Z
2019-12-02T20:40:59.000Z
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.wm.ToolWindowId import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import com.intellij.ui.content.ContentManagerAdapter import com.intellij.ui.content.ContentManagerEvent import com.intellij.util.IJSwingUtilities import com.intellij.util.ObjectUtils import com.intellij.util.containers.ContainerUtil import java.util.* import java.util.function.Predicate class ChangesViewContentManager : ChangesViewContentI, Disposable { private var contentManager: ContentManager? = null private val addedContents = ArrayList<Content>() override fun setContentManager(manager: ContentManager) { contentManager = manager.also { val contentProvidersListener = ContentProvidersListener() it.addContentManagerListener(contentProvidersListener) Disposer.register(this, Disposable { it.removeContentManagerListener(contentProvidersListener) }) } for (content in addedContents) { addIntoCorrectPlace(manager, content) IJSwingUtilities.updateComponentTreeUI(content.component) } addedContents.clear() // Ensure that first tab is selected after tabs reordering val firstContent = manager.getContent(0) if (firstContent != null) manager.setSelectedContent(firstContent) } override fun dispose() { for (content in addedContents) { Disposer.dispose(content) } addedContents.clear() } override fun addContent(content: Content) { val contentManager = contentManager if (contentManager == null) { addedContents.add(content) } else { addIntoCorrectPlace(contentManager, content) } } override fun removeContent(content: Content) { val contentManager = contentManager if (contentManager == null || contentManager.isDisposed) { addedContents.remove(content) Disposer.dispose(content) } else { contentManager.removeContent(content, true) } } override fun setSelectedContent(content: Content) { setSelectedContent(content, false) } override fun setSelectedContent(content: Content, requestFocus: Boolean) { val contentManager = contentManager ?: return contentManager.setSelectedContent(content, requestFocus) } override fun <T> getActiveComponent(aClass: Class<T>): T? { val selectedContent = contentManager?.selectedContent ?: return null return ObjectUtils.tryCast(selectedContent.component, aClass) } fun isContentSelected(contentName: String): Boolean { val selectedContent = contentManager?.selectedContent ?: return false return Comparing.equal(contentName, selectedContent.tabName) } override fun selectContent(tabName: String) { selectContent(tabName, false) } fun selectContent(tabName: String, requestFocus: Boolean) { val contentManager = contentManager ?: return val toSelect = ContainerUtil.find(contentManager.contents) { content -> content.tabName == tabName } if (toSelect != null) { contentManager.setSelectedContent(toSelect, requestFocus) } } override fun findContents(predicate: Predicate<Content>): List<Content> { val contents = contentManager?.contents?.let { listOf(*it) } ?: addedContents return ContainerUtil.filter(contents) { content -> predicate.test(content) } } private inner class ContentProvidersListener : ContentManagerAdapter() { override fun selectionChanged(event: ContentManagerEvent) { val content = event.content val provider = content.getUserData(CONTENT_PROVIDER_SUPPLIER_KEY)?.invoke() ?: return provider.initTabContent(content) IJSwingUtilities.updateComponentTreeUI(content.component) content.putUserData(CONTENT_PROVIDER_SUPPLIER_KEY, null) } } enum class TabOrderWeight(val tabName: String?, val weight: Int) { LOCAL_CHANGES(ChangesViewContentManager.LOCAL_CHANGES, 10), REPOSITORY(ChangesViewContentManager.REPOSITORY, 20), INCOMING(ChangesViewContentManager.INCOMING, 30), SHELF(ChangesViewContentManager.SHELF, 40), BRANCHES(ChangesViewContentManager.BRANCHES, 50), OTHER(null, 100), LAST(null, Integer.MAX_VALUE) } private fun addIntoCorrectPlace(contentManager: ContentManager, content: Content) { val weight = getContentWeight(content) val contents = contentManager.contents var index = -1 for (i in contents.indices) { val oldWeight = getContentWeight(contents[i]) if (oldWeight > weight) { index = i break } } if (index == -1) index = contents.size contentManager.addContent(content, index) } companion object { @JvmField val TOOLWINDOW_ID: String = ToolWindowId.VCS @JvmField val CONTENT_PROVIDER_SUPPLIER_KEY = Key.create<() -> ChangesViewContentProvider>("CONTENT_PROVIDER_SUPPLIER") @JvmStatic fun getInstance(project: Project): ChangesViewContentI { return project.getService(ChangesViewContentI::class.java) } @JvmField val ORDER_WEIGHT_KEY = Key.create<Int>("ChangesView.ContentOrderWeight") const val LOCAL_CHANGES = "Local Changes" const val REPOSITORY = "Repository" const val INCOMING = "Incoming" const val SHELF = "Shelf" const val BRANCHES = "Branches" private fun getContentWeight(content: Content): Int { val userData = content.getUserData(ORDER_WEIGHT_KEY) if (userData != null) return userData val tabName = content.tabName for (value in TabOrderWeight.values()) { if (value.tabName != null && value.tabName == tabName) { return value.weight } } return TabOrderWeight.OTHER.weight } } }
33.577778
140
0.734778
e50cfe7d8efdb0ee8aa65eb1bb9eceeacb3b6a0d
1,681
ts
TypeScript
src/test/suite/jsdos.test.ts
dosasm/vscode-dosbox
3e3fbb4fbcf39c782dd5e77bb19300ccff5b0369
[ "Apache-2.0" ]
1
2021-11-05T10:49:43.000Z
2021-11-05T10:49:43.000Z
src/test/suite/jsdos.test.ts
dosasm/vscode-dosbox
3e3fbb4fbcf39c782dd5e77bb19300ccff5b0369
[ "Apache-2.0" ]
2
2021-11-08T02:31:40.000Z
2021-12-23T14:23:00.000Z
src/test/suite/jsdos.test.ts
dosasm/vscode-dosbox
3e3fbb4fbcf39c782dd5e77bb19300ccff5b0369
[ "Apache-2.0" ]
null
null
null
import * as assert from "assert"; // You can import and use all API from the 'vscode' module // as well as import your extension to test it import * as vscode from "vscode"; import * as myExtension from "../../extension"; import { randomString } from "./util"; let api: myExtension.API; export const jsdosHostTestSuite = suite("test jsdos API", function () { this.beforeEach(async function () { const extension = vscode.extensions.getExtension("xsro.vscode-dosbox"); if (api === undefined) { api = await extension?.activate(); } assert.ok( api !== undefined, api ? Object.keys(api).toString() : "api can't get" ); }); test("launch jsdos in extension host direct", async function () { const ci = await api.jsdos.runInHost(undefined, false); assert.ok(typeof ci.width() === "number"); if (!process.platform) { this.timeout(10000); this.retries(3); } const t = ci.terminal(); t.show(); const testStr = randomString(); t.sendText(`echo ${testStr}\r`); const p = new Promise<string>((resolve) => { let stdout = ""; ci.events().onStdout((val) => { stdout += val; if (stdout.includes(testStr)) { setTimeout(() => { resolve(stdout); }); } }); }); const stdout = await p; assert.ok(stdout, stdout); ci.exit(); t.dispose(); }); test("launch jsdos in extension host webworker", async function () { if (process.platform !== undefined) { this.skip(); } const ci = await api.jsdos.runInHost(undefined, true); assert.ok(typeof ci.width() === "number"); ci.exit(); }); });
27.557377
75
0.588935
e9b7c3b22ae7c254f65917f3fdafd32a3bba49de
167
rb
Ruby
example/lib/external_service.rb
anyperk/cypress-rails
91016b74368de2d979e8894ffb78b86dfac21f8f
[ "MIT" ]
258
2019-09-15T09:59:15.000Z
2022-03-31T23:22:58.000Z
example/lib/external_service.rb
anyperk/cypress-rails
91016b74368de2d979e8894ffb78b86dfac21f8f
[ "MIT" ]
93
2019-09-16T13:09:06.000Z
2022-03-30T22:06:39.000Z
example/lib/external_service.rb
anyperk/cypress-rails
91016b74368de2d979e8894ffb78b86dfac21f8f
[ "MIT" ]
40
2019-10-31T01:20:06.000Z
2021-10-22T02:23:53.000Z
class ExternalService class << self def start_service @job_pid = fork { exec "yarn start" } Process.detach(@job_pid) end end end
15.181818
30
0.586826
dd0829c9f3c9febb175a16ff48a2a06468d90412
169
go
Go
shutdown.go
chibimi/kitty
d299bfbf71e00dfd55c96e680eff92690f76f587
[ "MIT" ]
21
2018-06-19T09:38:42.000Z
2021-04-23T07:37:17.000Z
shutdown.go
chibimi/kitty
d299bfbf71e00dfd55c96e680eff92690f76f587
[ "MIT" ]
12
2018-07-17T15:31:41.000Z
2020-10-02T08:54:41.000Z
shutdown.go
chibimi/kitty
d299bfbf71e00dfd55c96e680eff92690f76f587
[ "MIT" ]
3
2018-06-19T09:10:30.000Z
2019-05-13T00:26:55.000Z
package kitty // Shutdown registers functions to be called when the server is stopped. func (s *Server) Shutdown(fns ...func()) *Server { s.shutdown = fns return s }
21.125
72
0.715976
1a81320dd096a8b74a1fcae9afa20c207f8281a4
5,509
rs
Rust
src/config/app/domain.rs
ArthurKValladares/gradle-bump
ba40bac89ec2f340bbbd242c4ac58ebeeda7e184
[ "Apache-2.0", "MIT" ]
614
2020-08-07T18:38:54.000Z
2022-03-25T12:34:00.000Z
src/config/app/domain.rs
hikecoder/cargo-mobile
8a021a7d21315d0d4ad16d5d3c6526340e2fabb8
[ "Apache-2.0", "MIT" ]
38
2020-11-25T19:31:16.000Z
2022-03-05T03:10:13.000Z
src/config/app/domain.rs
hikecoder/cargo-mobile
8a021a7d21315d0d4ad16d5d3c6526340e2fabb8
[ "Apache-2.0", "MIT" ]
31
2020-10-29T03:44:38.000Z
2022-03-05T03:42:10.000Z
use crate::util::list_display; use std::error::Error; use std::fmt; static RESERVED_PACKAGE_NAMES: [&str; 2] = ["kotlin", "java"]; static RESERVED_KEYWORDS: [&str; 63] = [ "abstract", "as", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "fun", "goto", "if", "implements", "import", "instanceof", "in", "int", "interface", "is", "long", "native", "new", "null", "object", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typealias", "typeof", "val", "var", "void", "volatile", "when", "while", ]; #[derive(Debug)] pub enum DomainError { Empty, NotAsciiAlphanumeric { bad_chars: Vec<char> }, StartsWithDigit { label: String }, ReservedPackageName { package_name: String }, ReservedKeyword { keyword: String }, StartsOrEndsWithADot, EmptyLabel, } impl Error for DomainError {} impl fmt::Display for DomainError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Empty => write!(f, "Domain can't be empty."), Self::NotAsciiAlphanumeric { bad_chars } => write!( f, "{} characters were used in domain, but only ASCII letters and numbers are allowed.", list_display( &bad_chars .iter() .map(|c| format!("'{}'", c)) .collect::<Vec<_>>() ), ), Self::ReservedPackageName { package_name } => write!( f, "\"{}\" is a reserved package name in this project and can't be used as a top-level domain.", package_name ), Self::ReservedKeyword { keyword } => write!( f, "\"{}\" is a reserved keyword in java/kotlin and can't be used. For more info, please visit https://kotlinlang.org/docs/reference/keyword-reference.html and https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html", keyword ), Self::StartsWithDigit { label } => write!( f, "\"{}\" label starts with a digit, which is not allowed in java/kotlin packages.", label ), Self::StartsOrEndsWithADot => write!(f, "Domain can't start or end with a dot."), Self::EmptyLabel => write!(f, "Labels can't be empty."), } } } pub fn check_domain_syntax(domain_name: &str) -> Result<(), DomainError> { if domain_name.is_empty() { return Err(DomainError::Empty); } if domain_name.starts_with(".") || domain_name.ends_with(".") { return Err(DomainError::StartsOrEndsWithADot); } let labels = domain_name.split("."); for label in labels { if label.is_empty() { return Err(DomainError::EmptyLabel); } if RESERVED_KEYWORDS.contains(&label) { return Err(DomainError::ReservedKeyword { keyword: label.to_owned(), }); } if label.chars().nth(0).unwrap().is_digit(10) { return Err(DomainError::StartsWithDigit { label: label.to_owned(), }); } let mut bad_chars = Vec::new(); for c in label.chars() { if !c.is_ascii_alphanumeric() { if !bad_chars.contains(&c) { bad_chars.push(c); } } } if !bad_chars.is_empty() { return Err(DomainError::NotAsciiAlphanumeric { bad_chars }); } } for pkg_name in RESERVED_PACKAGE_NAMES.iter() { if domain_name.ends_with(pkg_name) { return Err(DomainError::ReservedPackageName { package_name: pkg_name.to_string(), }); } } Ok(()) } #[cfg(test)] mod test { use super::*; use rstest::rstest; #[rstest( input, case("com.example"), case("t2900.e1.s709.t1000"), case("kotlin.com"), case("java.test"), case("synchronized2.com") )] fn test_check_domain_syntax_correct(input: &str) { assert_eq!(check_domain_syntax(input).unwrap(), ()) } #[rstest(input, error, case("ラスト.テスト", DomainError::NotAsciiAlphanumeric { bad_chars: vec!['ラ', 'ス', 'ト'] }), case("test.digits.87", DomainError::StartsWithDigit { label: String::from("87") }), case("", DomainError::Empty {}), case(".bad.dot.syntax", DomainError::StartsOrEndsWithADot {}), case("com.kotlin", DomainError::ReservedPackageName { package_name: String::from("kotlin") }), case("some.domain.catch.com", DomainError::ReservedKeyword { keyword: String::from("catch") }), case("com..empty.label", DomainError::EmptyLabel) )] fn test_check_domain_syntax_error(input: &str, error: DomainError) { assert_eq!( check_domain_syntax(input).unwrap_err().to_string(), error.to_string() ) } }
27.964467
247
0.527682
94d07aad53c2f0305af4f3613d8c2e305ceba320
1,634
swift
Swift
Sources/AsciiEdit/Commands/AsciiEdit.swift
daltonclaybrook/AsciiEdit
6e97648236a6dca03a23416018dae52277a60c75
[ "MIT" ]
2
2021-06-10T13:37:36.000Z
2021-07-30T06:55:54.000Z
Sources/AsciiEdit/Commands/AsciiEdit.swift
daltonclaybrook/AsciiEdit
6e97648236a6dca03a23416018dae52277a60c75
[ "MIT" ]
null
null
null
Sources/AsciiEdit/Commands/AsciiEdit.swift
daltonclaybrook/AsciiEdit
6e97648236a6dca03a23416018dae52277a60c75
[ "MIT" ]
null
null
null
import ArgumentParser import PathKit final class AsciiEdit: ParsableCommand { enum Error: Swift.Error { case inputFileDoesNotExist(String) } static let configuration = CommandConfiguration( commandName: "asciiedit", abstract: "A utility for editing `cast` files produced with asciinema", version: "0.1.0" ) @Argument(help: "Path to the cast file to edit") var file: String @Option(name: [.short, .long], help: "A new width to apply to the cast file") var width: Int? @Option(name: [.short, .long], help: "A new height to apply to the cast file") var height: Int? @Option(name: [.customShort("d"), .long], help: "A maximum duration in seconds used to clamp each item in the cast file.") var maxDuration: Double? @Option(name: [.short, .long], help: "Where the output cast file should be saved. The default is to overwrite the input file.") var output: String? func run() throws { let inputPath = Path(file) guard inputPath.exists else { throw Error.inputFileDoesNotExist(file) } var castFile = try CastFile(fileText: inputPath.read()) CastFileUtility.updateSize(of: &castFile, width: width, height: height) CastFileUtility.constrainMaxDuration(of: &castFile, maxDuration: maxDuration) let outputText = try castFile.generateFileText() let outputFilePath = output.map { Path($0) } ?? inputPath if outputFilePath.exists { try outputFilePath.delete() } try outputFilePath.write(outputText) print("✅ Done!") } }
32.68
131
0.649327
a1eb0bcb716bcb26aed025f2e277080e44c2ac91
4,922
lua
Lua
yatm_mining/nodes/quarry.lua
IceDragon200/mt-yatm
7452f2905e1f4121dc9d244d18a23e76b11ebe5d
[ "Apache-2.0" ]
3
2019-03-15T03:17:36.000Z
2020-02-19T19:50:49.000Z
yatm_mining/nodes/quarry.lua
IceDragon200/mt-yatm
7452f2905e1f4121dc9d244d18a23e76b11ebe5d
[ "Apache-2.0" ]
24
2019-12-02T06:01:04.000Z
2021-04-08T04:09:27.000Z
yatm_mining/nodes/quarry.lua
IceDragon200/mt-yatm
7452f2905e1f4121dc9d244d18a23e76b11ebe5d
[ "Apache-2.0" ]
null
null
null
local Directions = assert(foundation.com.Directions) local ItemInterface = assert(yatm.items.ItemInterface) local quarry_item_interface = ItemInterface.new_simple("main") local function quarry_on_construct(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() inv:set_size("main", 4) -- Quarry has a small internal inventory meta:set_int("cx", -8) meta:set_int("cy", 0) meta:set_int("cz", 0) meta:set_int("dx", 1) meta:set_int("dz", 1) yatm.devices.device_on_construct(pos) end local quarry_yatm_network = { kind = "machine", groups = { machine_worker = 1, energy_consumer = 1, }, default_state = "off", states = { conflict = "yatm_mining:quarry_error", error = "yatm_mining:quarry_error", on = "yatm_mining:quarry_on", off = "yatm_mining:quarry_off", idle = "yatm_mining:quarry_idle", }, energy = { capacity = 16000, network_charge_bandwidth = 500, startup_threshold = 1000, passive_lost = 0, } } function quarry_yatm_network:work(ctx) local pos = ctx.pos local meta = ctx.meta local node = ctx.node if ctx.available_energy > 200 then -- get current cursor position local cx = meta:get_int("cx") local cy = meta:get_int("cy") local cz = meta:get_int("cz") local delta_x = meta:get_int("dx") if delta_x == 0 then delta_x = 1 end local delta_z = meta:get_int("dz") if delta_z == 0 then delta_z = 1 end -- determine coords matrix local north_dir = Directions.facedir_to_face(node.param2, Directions.D_NORTH) local east_dir = Directions.facedir_to_face(node.param2, Directions.D_EAST) local down_dir = Directions.facedir_to_face(node.param2, Directions.D_DOWN) local nv = Directions.DIR6_TO_VEC3[north_dir] local ev = Directions.DIR6_TO_VEC3[east_dir] local dv = Directions.DIR6_TO_VEC3[down_dir] local new_nv = vector.multiply(nv, cz) local new_ev = vector.multiply(ev, cx) local new_dv = vector.multiply(dv, cy) local cursor_relative_pos = vector.add(vector.add(new_nv, new_ev), new_dv) cursor_relative_pos = vector.add(cursor_relative_pos, north_dir) -- the cursor is always 1 step ahead of the quarry local cursor_pos = vector.add(pos, cursor_relative_pos) -- TODO: respect permissions print("Removing " .. minetest.pos_to_string(cursor_pos)) minetest.remove_node(cursor_pos) -- TODO: store removed node, or determine if it can be stored -- Finally move the cursor to the next location cx = cx + delta_x if cx > 7 then cx = 7 -- clamp delta_x = -1 -- reverse delta cz = cz + delta_z elseif cx < -8 then cx = -8 delta_x = 1 cz = cz + delta_z end if cz > 16 then cz = 16 delta_z = -1 delta_x = -delta_x cy = cy + 1 elseif cz < 0 then cz = 0 delta_z = 1 delta_x = -delta_x cy = cy + 1 end meta:set_int("cx", cx) meta:set_int("cy", cy) meta:set_int("cz", cz) meta:set_int("dx", delta_x) meta:set_int("dz", delta_z) -- TODO: Spawn a cursor entity which marks the position the quarry is currently working on. -- The cursor should have a simple animation where lines go up the sides of the cube. -- Once the lines reach the top, the target node is removed and added to the internal inventory. -- Then the cursor moves to the next tile and repeats. return 200 end return 0 end yatm.devices.register_stateful_network_device({ basename = "yatm_mining:quarry", description = "Quarry", codex_entry_id = "yatm_mining:quarry", drop = quarry_yatm_network.states.off, groups = { cracky = 1, item_interface_out = 1, }, tiles = { "yatm_quarry_top.off.png", "yatm_quarry_bottom.png", "yatm_quarry_side.off.png", "yatm_quarry_side.off.png^[transformFX", "yatm_quarry_back.off.png", "yatm_quarry_front.off.png", }, paramtype = "none", paramtype2 = "facedir", on_construct = quarry_on_construct, item_interface = quarry_item_interface, yatm_network = quarry_yatm_network, }, { error = { tiles = { "yatm_quarry_top.error.png", "yatm_quarry_bottom.png", "yatm_quarry_side.error.png", "yatm_quarry_side.error.png^[transformFX", "yatm_quarry_back.error.png", "yatm_quarry_front.error.png", }, }, on = { tiles = { "yatm_quarry_top.on.png", "yatm_quarry_bottom.png", "yatm_quarry_side.on.png", "yatm_quarry_side.on.png^[transformFX", "yatm_quarry_back.on.png", "yatm_quarry_front.on.png", }, }, idle = { tiles = { "yatm_quarry_top.idle.png", "yatm_quarry_bottom.png", "yatm_quarry_side.idle.png", "yatm_quarry_side.idle.png^[transformFX", "yatm_quarry_back.idle.png", "yatm_quarry_front.idle.png", }, }, })
25.241026
119
0.657253
4a40a9462ec0d66266a03797d7ffc4e2dba9dc7c
886
js
JavaScript
src/main/webapp/resources/nmrviewer/libs/uglify.js
peakforest/peakforest-webapp
8384d687e23d034925bc74ef8600749c0780fb2a
[ "OML", "RSA-MD" ]
null
null
null
src/main/webapp/resources/nmrviewer/libs/uglify.js
peakforest/peakforest-webapp
8384d687e23d034925bc74ef8600749c0780fb2a
[ "OML", "RSA-MD" ]
null
null
null
src/main/webapp/resources/nmrviewer/libs/uglify.js
peakforest/peakforest-webapp
8384d687e23d034925bc74ef8600749c0780fb2a
[ "OML", "RSA-MD" ]
null
null
null
var fs = require("fs"), uglify = require("uglify-js"); var filename = process.argv[2], toplevel = uglify.parse(fs.readFileSync(filename, "utf8"), {filename: filename}), output = uglify.OutputStream({ascii_only: true}), compressor = uglify.Compressor(true), warn = uglify.AST_Node.warn; uglify.AST_Node.warn = function(s, o) { if (o.msg === "Accidental global?" && o.name === "st" && o.line === 1 && !o.col) return; warn.apply(this, arguments); }; toplevel.figure_out_scope(); toplevel.scope_warnings({ undeclared: false, unreferenced: false, assign_to_global: true, func_arguments: false, nested_defuns: false, eval: false }); toplevel = toplevel.transform(compressor); toplevel.figure_out_scope(); toplevel.compute_char_frequency(true); toplevel.mangle_names(true); toplevel.print(output); require("util").print(output.get());
27.6875
92
0.687359
e775abb2c964a0e3b155e08fadc61923175d58fd
3,378
js
JavaScript
src/pages/login.js
fullstack202/nest-app
9a1470cd0a2d43c2e4a7057cdb0e1c626e9c4276
[ "MIT" ]
null
null
null
src/pages/login.js
fullstack202/nest-app
9a1470cd0a2d43c2e4a7057cdb0e1c626e9c4276
[ "MIT" ]
null
null
null
src/pages/login.js
fullstack202/nest-app
9a1470cd0a2d43c2e4a7057cdb0e1c626e9c4276
[ "MIT" ]
null
null
null
import { Box, Button, Container, TextField, Typography } from '@mui/material'; import { useFormik } from 'formik'; import Head from 'next/head'; import { useRouter } from 'next/router'; import * as Yup from 'yup'; const Login = () => { const router = useRouter(); const formik = useFormik({ initialValues: { username: 'john@test.com', password: 'changeme' }, validationSchema: Yup.object({ username: Yup .string() .email( 'Must be a valid email') .max(255) .required( 'Email is required'), password: Yup .string() .max(255) .required( 'Password is required') }), onSubmit: async () => { // Simple POST request with a JSON body using fetch const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formik.values) }; await fetch('http://localhost:3000/auth/login', requestOptions) .then(response => response.json()) .then(data => { if (data?.statusCode == 401) { formik.setErrors({ password: "Invalid Username or Password." }); } localStorage.setItem('access_token', data.access_token); formik.setSubmitting(false); router.push('/'); }); } }); return ( <> <Head> <title>Login | Material Kit</title> </Head> <Box component="main" sx={{ alignItems: 'center', display: 'flex', flexGrow: 1, minHeight: '100%' }} > <Container maxWidth="sm"> <form onSubmit={formik.handleSubmit}> <Box sx={{ my: 3 }}> <Typography color="textPrimary" variant="h4" > Sign in </Typography> </Box> <TextField error={Boolean(formik.touched.username && formik.errors.username)} fullWidth helperText={formik.touched.username && formik.errors.username} label="Email Address" margin="normal" name="username" onBlur={formik.handleBlur} onChange={formik.handleChange} type="email" value={formik.values.username} variant="outlined" /> <TextField error={Boolean(formik.touched.password && formik.errors.password)} fullWidth helperText={formik.touched.password && formik.errors.password} label="Password" margin="normal" name="password" onBlur={formik.handleBlur} onChange={formik.handleChange} type="password" value={formik.values.password} variant="outlined" /> <Box sx={{ py: 2 }}> <Button color="primary" disabled={formik.isSubmitting} fullWidth size="large" type="submit" variant="contained" > Sign In Now </Button> </Box> </form> </Container> </Box> </> ); }; export default Login;
28.386555
80
0.488455
ac9eb10e7b90bc7e9102b0897de45b8170fb0fdf
4,083
kt
Kotlin
pocketlib/src/main/java/jdp/pocketlib/util/RxImageRequest.kt
jamesdeperio/PocketLib
3e0396012c50743fe7d14c19d7117197abe64205
[ "Apache-2.0" ]
10
2018-08-01T03:02:29.000Z
2021-01-10T23:47:35.000Z
pocketlib/src/main/java/jdp/pocketlib/util/RxImageRequest.kt
jamesdeperio/PocketLib
3e0396012c50743fe7d14c19d7117197abe64205
[ "Apache-2.0" ]
71
2018-09-07T17:57:43.000Z
2021-07-29T21:14:34.000Z
pocketlib/src/main/java/jdp/pocketlib/util/RxImageRequest.kt
jamesdeperio/PocketLib
3e0396012c50743fe7d14c19d7117197abe64205
[ "Apache-2.0" ]
3
2018-10-10T06:55:42.000Z
2019-10-07T03:33:56.000Z
package jdp.pocketlib.util import android.annotation.SuppressLint import android.content.ClipData import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.support.annotation.RequiresApi import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import jdp.pocketlib.base.BaseFragment import jdp.pocketlib.manager.Bus import jdp.pocketlib.manager.EventBusManager @SuppressLint("ValidFragment") private class TempImageFragment(private val eventBusManager: EventBusManager, private val type: String) :BaseFragment() { override fun onInitialization(savedInstanceState: Bundle?) { when (type) { RxImageRequest.GALLERY -> startActivityForResult(Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI),1) RxImageRequest.CAMERA -> startActivityForResult(Intent(MediaStore.ACTION_IMAGE_CAPTURE),1) RxImageRequest.MULTIPLE_IMAGE -> { val i =Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) i.action = Intent.ACTION_GET_CONTENT } startActivityForResult(i,1) } } } override fun onViewDidLoad(savedInstanceState: Bundle?) {} override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data!=null) { when (type) { RxImageRequest.GALLERY -> eventBusManager.sendEvent(RxImageRequest.BITMAP_REQUEST,MediaStore.Images.Media.getBitmap(activity!!.contentResolver, data.data)) RxImageRequest.CAMERA -> eventBusManager.sendEvent(RxImageRequest.BITMAP_REQUEST ,data.extras!!.get("data") as Bitmap) RxImageRequest.MULTIPLE_IMAGE -> { val imageUris = ArrayList<Uri>() val clipData:ClipData? = data.clipData if (clipData != null) (0 until clipData.itemCount).forEach { i -> imageUris.add(clipData.getItemAt(i).uri) } else imageUris.add(data.data!!) eventBusManager.sendEvent(RxImageRequest.BITMAP_REQUEST ,imageUris) } } } } } object RxImageRequest { const val BITMAP_REQUEST="BITMAP_REQUEST" const val GALLERY="GALLERY" const val MULTIPLE_IMAGE="MULTIPLE_IMAGE" const val CAMERA="CAMERA" fun request(type:String,fragmentManager:FragmentManager,callback:(bitmap:Bitmap)-> Unit) { val eventBusManager= EventBusManager(Bus.PublishSubject) val tempFragment :Fragment= TempImageFragment(eventBusManager,type) fragmentManager.beginTransaction() .add(tempFragment, tempFragment.javaClass.simpleName) .commit() eventBusManager.subscribeReceiver(BITMAP_REQUEST) { callback(it as Bitmap) fragmentManager.beginTransaction() .remove(tempFragment) .commit() eventBusManager.disposeAllChannel() } } @Suppress("UNCHECKED_CAST") @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) fun requestMultipleImage(fragmentManager:FragmentManager, callback:(bitmap: ArrayList<Uri>)-> Unit) { val eventBusManager= EventBusManager(Bus.PublishSubject) val tempFragment :Fragment= TempImageFragment(eventBusManager,MULTIPLE_IMAGE) fragmentManager.beginTransaction() .add(tempFragment, tempFragment.javaClass.simpleName) .commit() eventBusManager.subscribeReceiver(BITMAP_REQUEST) { callback(it as ArrayList<Uri>) fragmentManager.beginTransaction() .remove(tempFragment) .commit() eventBusManager.disposeAllChannel() } } }
44.868132
171
0.678913
fb8798aa3286235d25c1388df39ae21563e9686f
2,475
h
C
Arrangement_on_surface_2/include/CGAL/Arr_topology_traits/Arr_bounded_planar_insertion_helper.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Arrangement_on_surface_2/include/CGAL/Arr_topology_traits/Arr_bounded_planar_insertion_helper.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Arrangement_on_surface_2/include/CGAL/Arr_topology_traits/Arr_bounded_planar_insertion_helper.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
// Copyright (c) 2006,2007,2009,2010,2011 Tel-Aviv University (Israel). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // // $URL$ // $Id$ // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : Baruch Zukerman <baruchzu@post.tau.ac.il> // Ron Wein <wein@post.tau.ac.il> // Efi Fogel <efif@post.tau.ac.il> #ifndef CGAL_ARR_BOUNDED_PLANAR_INSERTION_HELPER_H #define CGAL_ARR_BOUNDED_PLANAR_INSERTION_HELPER_H #include <CGAL/license/Arrangement_on_surface_2.h> /*! \file * * Definition of the Arr_bounded_planar_insertion_helper class-template. */ #include <CGAL/Arr_topology_traits/Arr_bounded_planar_construction_helper.h> namespace CGAL { /*! \class Arr_bounded_planar_insertion_helper * * A helper class for the insertion sweep-line visitors, suitable * for an Arrangement_on_surface_2 instantiated with a topology-traits class * for bounded curves in the plane. */ template <typename GeometryTraits_2, typename Arrangement_, typename Event_, typename Subcurve_> class Arr_bounded_planar_insertion_helper : public Arr_bounded_planar_construction_helper<GeometryTraits_2, Arrangement_, Event_, Subcurve_> { public: typedef GeometryTraits_2 Geometry_traits_2; typedef Arrangement_ Arrangement_2; typedef Event_ Event; typedef Subcurve_ Subcurve; private: typedef Geometry_traits_2 Gt2; typedef Arr_bounded_planar_insertion_helper<Gt2, Arrangement_2, Event, Subcurve> Self; typedef Arr_bounded_planar_construction_helper<Gt2, Arrangement_2, Event, Subcurve> Base; public: typedef typename Gt2::X_monotone_curve_2 X_monotone_curve_2; typedef typename Gt2::Point_2 Point_2; typedef typename Arrangement_2::Face_handle Face_handle; typedef typename Base::Indices_list Indices_list; typedef typename Base::Halfedge_indices_map Halfedge_indices_map; public: /*! Constructor. */ Arr_bounded_planar_insertion_helper(Arrangement_2* arr) : Base(arr) {} }; } // namespace CGAL #endif
33.445946
79
0.634343
38dc04714f5ae585beb05c33f8ff450ab3b88e57
6,988
swift
Swift
SwiftWeibo/SwiftWeibo/Classes/Compose/ComposeViewController.swift
coderwjq/swiftweibo
053cdcf81783a422a593ffcfdbc472e7f645edcb
[ "Apache-2.0" ]
null
null
null
SwiftWeibo/SwiftWeibo/Classes/Compose/ComposeViewController.swift
coderwjq/swiftweibo
053cdcf81783a422a593ffcfdbc472e7f645edcb
[ "Apache-2.0" ]
null
null
null
SwiftWeibo/SwiftWeibo/Classes/Compose/ComposeViewController.swift
coderwjq/swiftweibo
053cdcf81783a422a593ffcfdbc472e7f645edcb
[ "Apache-2.0" ]
null
null
null
// // ComposeViewController.swift // SwiftWeibo // // Created by mzzdxt on 2016/11/7. // Copyright © 2016年 wjq. All rights reserved. // import UIKit import SVProgressHUD class ComposeViewController: UIViewController { // MARK:- 控件的属性 @IBOutlet weak var textView: ComposeTextView! @IBOutlet weak var picPickerView: PicPickerCollectionView! // MARK:- 懒加载属性 fileprivate lazy var titleView: ComposeTitleView = ComposeTitleView() fileprivate lazy var images: [UIImage] = [UIImage]() fileprivate lazy var emoticonVc: EmoticonController = EmoticonController {[weak self] (emoticon) in self?.textView.insertEmoticon(emoticon: emoticon) self?.textViewDidChange(self!.textView) } // MARK:- 约束的属性 @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint! @IBOutlet weak var picPickerViewHCons: NSLayoutConstraint! // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置导航栏 setupNavigationBar() // 监听通知 setupNotifications() // 设置代理 textView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 在界面显示完成后再弹出键盘 textView.becomeFirstResponder() } deinit { NotificationCenter.default.removeObserver(self) } } // MARK:- 设置UI界面 extension ComposeViewController { fileprivate func setupNavigationBar() { // 设置左右item navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(ComposeViewController.closeItemClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(ComposeViewController.sendItemClick)) navigationItem.rightBarButtonItem?.isEnabled = false // 设置标题 titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40) navigationItem.titleView = titleView } fileprivate func setupNotifications() { // 监听键盘的弹出 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(note:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) // 监听添加照片按钮的点击 NotificationCenter.default.addObserver(self, selector: #selector(addPhotoClick), name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil) // 监听删除照片按钮的点击 NotificationCenter.default.addObserver(self, selector: #selector(removePhotoClick(note:)), name: NSNotification.Name(rawValue: PicPickerRemovePhotoNote), object: nil) } } // MARK:- 事件监听函数 extension ComposeViewController { @objc fileprivate func closeItemClick() { dismiss(animated: true, completion: nil) } @objc fileprivate func sendItemClick() { // 键盘退出 textView.resignFirstResponder() // 获取要发送的微博正文 let statusText = textView.getEmoticonString() // 定义回调的闭包 let finishedCallback = { (isSucess: Bool) -> () in if !isSucess { SVProgressHUD.showError(withStatus: "发送微博失败") } SVProgressHUD.showSuccess(withStatus: "发送微博成功") self.dismiss(animated: true, completion: nil) } // 获取用户选中的图片 if let image = images.first { NetworkTools.sharedInstance.sendStatus(statusText: statusText, image: image, isSucess: finishedCallback) } else { NetworkTools.sharedInstance.sendStatus(statusText: statusText, isSucess: finishedCallback) } } @objc fileprivate func keyboardWillChangeFrame(note: Notification) { // 获取动画执行的时间 let duration = (note as NSNotification).userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval // 获取键盘的最终Y值 let endFrame = ((note as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let y = endFrame.origin.y // 计算工具栏距离底部的间距 let margin = UIScreen.main.bounds.height - y; // 执行动画 toolBarBottomCons.constant = margin UIView.animate(withDuration: duration, animations: { self.view.layoutIfNeeded() }, completion: nil) } @IBAction func picPickerBtnClick() { // 退出键盘 textView.resignFirstResponder() // 执行动画 picPickerViewHCons.constant = UIScreen.main.bounds.height * 0.65 UIView.animate(withDuration: 0.5, animations: { () -> Void in self.view.layoutIfNeeded() }) } @IBAction func emoticonBtnClick() { // 1.退出键盘 textView.resignFirstResponder() // 2.切换键盘 textView.inputView = textView.inputView != nil ? nil : emoticonVc.view // 3.弹出键盘 textView.becomeFirstResponder() } } // MARK:- 添加照片和删除照片的事件 extension ComposeViewController { @objc fileprivate func addPhotoClick() { // 判断数据源是否可用 if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { return } // 创建照片选择控制器 let ipc = UIImagePickerController() // 设置照片源 ipc.sourceType = .photoLibrary // 设置代理 ipc.delegate = self // 弹出选择照片的控制器 present(ipc, animated: true, completion: nil) } @objc fileprivate func removePhotoClick(note: Notification) { // 获取image对象 guard let image = note.object as? UIImage else { print("未获取到image对象") return } // 获取image对象所在的下标值 guard let index = images.index(of: image) else { print("未获取到index") return } // 将图片从数组删除 images.remove(at: index) // 重新赋值collectionView新的数组 picPickerView.images = images } } // MARK:- UIImagePickerController的代理方法 extension ComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // 获取选中的图片 let image = info[UIImagePickerControllerOriginalImage] as! UIImage // 将选中图片添加到数组 images.append(image) // 将数组赋值给collectionView并展示数据 picPickerView.images = images // 退出选中照片的控制器 picker.dismiss(animated: true, completion: nil) } } // MARK:- UITextView的代理方法 extension ComposeViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { self.textView.placeHolderLabel.isHidden = textView.hasText navigationItem.rightBarButtonItem?.isEnabled = textView.hasText } func scrollViewDidScroll(_ scrollView: UIScrollView) { textView.resignFirstResponder() } }
31.336323
174
0.632656
bf52051197317bf33c295bf684fdec359d33abd6
3,303
rs
Rust
netlink-packet/src/rtnl/link/nlas/inet6/cache.rs
flier/netlink
28ec172de2ba8dcfbde1b1961e429948e00153eb
[ "MITNFA" ]
null
null
null
netlink-packet/src/rtnl/link/nlas/inet6/cache.rs
flier/netlink
28ec172de2ba8dcfbde1b1961e429948e00153eb
[ "MITNFA" ]
2
2019-02-01T03:31:21.000Z
2019-02-02T02:47:42.000Z
netlink-packet/src/rtnl/link/nlas/inet6/cache.rs
flier/netlink
28ec172de2ba8dcfbde1b1961e429948e00153eb
[ "MITNFA" ]
null
null
null
use byteorder::{ByteOrder, NativeEndian}; use crate::{DecodeError, Emitable, Field, Parseable}; const MAX_REASM_LEN: Field = 0..4; const TSTAMP: Field = 4..8; const REACHABLE_TIME: Field = 8..12; const RETRANS_TIME: Field = 12..16; pub const LINK_INET6_CACHE_INFO_LEN: usize = RETRANS_TIME.end; #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub struct LinkInet6CacheInfo { pub max_reasm_len: i32, pub tstamp: i32, pub reachable_time: i32, pub retrans_time: i32, } #[derive(Debug, PartialEq, Eq, Clone)] pub struct LinkInet6CacheInfoBuffer<T> { buffer: T, } impl<T: AsRef<[u8]>> LinkInet6CacheInfoBuffer<T> { pub fn new(buffer: T) -> LinkInet6CacheInfoBuffer<T> { LinkInet6CacheInfoBuffer { buffer } } pub fn new_checked(buffer: T) -> Result<LinkInet6CacheInfoBuffer<T>, DecodeError> { let buf = Self::new(buffer); buf.check_buffer_length()?; Ok(buf) } fn check_buffer_length(&self) -> Result<(), DecodeError> { let len = self.buffer.as_ref().len(); if len < LINK_INET6_CACHE_INFO_LEN { return Err(format!( "invalid LinkInet6CacheInfoBuffer buffer: length is {} instead of {}", len, LINK_INET6_CACHE_INFO_LEN ) .into()); } Ok(()) } pub fn into_inner(self) -> T { self.buffer } pub fn max_reasm_len(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[MAX_REASM_LEN]) } pub fn tstamp(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[TSTAMP]) } pub fn reachable_time(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[REACHABLE_TIME]) } pub fn retrans_time(&self) -> i32 { NativeEndian::read_i32(&self.buffer.as_ref()[RETRANS_TIME]) } } impl<T: AsRef<[u8]> + AsMut<[u8]>> LinkInet6CacheInfoBuffer<T> { pub fn set_max_reasm_len(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[MAX_REASM_LEN], value) } pub fn set_tstamp(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[TSTAMP], value) } pub fn set_reachable_time(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[REACHABLE_TIME], value) } pub fn set_retrans_time(&mut self, value: i32) { NativeEndian::write_i32(&mut self.buffer.as_mut()[RETRANS_TIME], value) } } impl<T: AsRef<[u8]>> Parseable<LinkInet6CacheInfo> for LinkInet6CacheInfoBuffer<T> { fn parse(&self) -> Result<LinkInet6CacheInfo, DecodeError> { self.check_buffer_length()?; Ok(LinkInet6CacheInfo { max_reasm_len: self.max_reasm_len(), tstamp: self.tstamp(), reachable_time: self.reachable_time(), retrans_time: self.retrans_time(), }) } } impl Emitable for LinkInet6CacheInfo { fn buffer_len(&self) -> usize { LINK_INET6_CACHE_INFO_LEN } fn emit(&self, buffer: &mut [u8]) { let mut buffer = LinkInet6CacheInfoBuffer::new(buffer); buffer.set_max_reasm_len(self.max_reasm_len); buffer.set_tstamp(self.tstamp); buffer.set_reachable_time(self.reachable_time); buffer.set_retrans_time(self.retrans_time); } }
30.027273
87
0.639116
cb584a2641a9cf6c273b75a2120793c26b27115e
3,817
go
Go
steam/web/results.go
13k/geyser
296c535ec8e5ae43786231d458eddc1ebc0ca07f
[ "MIT" ]
1
2020-07-21T09:57:29.000Z
2020-07-21T09:57:29.000Z
steam/web/results.go
13k/geyser
296c535ec8e5ae43786231d458eddc1ebc0ca07f
[ "MIT" ]
null
null
null
steam/web/results.go
13k/geyser
296c535ec8e5ae43786231d458eddc1ebc0ca07f
[ "MIT" ]
null
null
null
package web import ( "crypto/rsa" "encoding/json" "fmt" "strconv" "time" "github.com/13k/go-steam/steamid" ) // RSAKeyResult is the result of an RSA Key request. type RSAKeyResult struct { PublicKeyMod string `json:"publickey_mod"` PublicKeyExp string `json:"publickey_exp"` Success bool `json:"success"` Timestamp string `json:"timestamp"` TokenGID string `json:"token_gid"` pub *rsa.PublicKey ts *time.Time } // PubKey returns the RSA public key formed by the PublicKey* fields. func (r *RSAKeyResult) PubKey() (*rsa.PublicKey, error) { if r.pub == nil { var err error r.pub, err = rsaPubKeyFromHexStrings(r.PublicKeyMod, r.PublicKeyExp) if err != nil { return nil, fmt.Errorf("geyser/steam/web: error parsing public key: %w", err) } } return r.pub, nil } // Time returns the parsed Timestamp. func (r *RSAKeyResult) Time() (time.Time, error) { if r.ts == nil { n, err := strconv.ParseInt(r.Timestamp, 10, 64) if err != nil { return time.Time{}, fmt.Errorf("geyser/steam/web: error parsing unix timestamp: %w", err) } ts := time.Unix(n, 0) r.ts = &ts } return *r.ts, nil } // LoginResult is the result of a login request. type LoginResult struct { Success bool `json:"success"` Complete bool `json:"login_complete"` CaptchaNeeded bool `json:"captcha_needed"` CaptchaGID int64 `json:"captcha_gid"` EmailCodeNeeded bool `json:"emailauth_needed"` EmailSteamID steamid.SteamID `json:"emailsteamid"` TwoFactorNeeded bool `json:"requires_twofactor"` ClearPassword bool `json:"clear_password_field"` Message string `json:"message"` OAuthJSON string `json:"oauth"` RedirectURI string `json:"redirect_uri"` TransferURLs []string `json:"transfer_urls"` TransferParameters *LoginResultTransferParameters `json:"transfer_parameters"` oauth *LoginResultOAuth } // OAuth parses the OAuthJSON field. func (r *LoginResult) OAuth() (*LoginResultOAuth, error) { if r.oauth != nil { return r.oauth, nil } if r.OAuthJSON == "" { return nil, nil } result := &LoginResultOAuth{} if err := json.Unmarshal([]byte(r.OAuthJSON), result); err != nil { return nil, err } r.oauth = result return r.oauth, nil } // LoginResultTransferParameters are transfer parameters of a successful login request. type LoginResultTransferParameters struct { SteamIDString string `json:"steamid"` TokenSecure string `json:"token_secure"` Auth string `json:"auth"` RememberLogin bool `json:"remember_login"` steamid steamid.SteamID } // SteamID parses the SteamIDString field. func (p *LoginResultTransferParameters) SteamID() (steamid.SteamID, error) { if p.steamid == 0 { n, err := strconv.ParseUint(p.SteamIDString, 10, 64) if err != nil { return 0, err } p.steamid = steamid.SteamID(n) } return p.steamid, nil } // LoginResultOAuth are OAuth values of a successful login request. type LoginResultOAuth struct { SteamIDString string `json:"steamid"` AccountName string `json:"account_name"` Token string `json:"oauth_token"` WGToken string `json:"wgtoken"` WGTokenSecure string `json:"wgtoken_secure"` steamid steamid.SteamID } // SteamID parses the SteamIDString field. func (p *LoginResultOAuth) SteamID() (steamid.SteamID, error) { if p.steamid == 0 { n, err := strconv.ParseUint(p.SteamIDString, 10, 64) if err != nil { return 0, err } p.steamid = steamid.SteamID(n) } return p.steamid, nil }
26.143836
92
0.636102
f089b2ee0df2c39cb69f3cc09604ca66100e6ff2
3,266
js
JavaScript
true-business-backend/models/business.js
sophiemullerc/true-business
e062165e27344246f865c42f2b7499beae4ac24a
[ "MIT" ]
1
2018-10-08T16:28:05.000Z
2018-10-08T16:28:05.000Z
true-business-backend/models/business.js
Lambda-School-Labs/CS10-business-review
e062165e27344246f865c42f2b7499beae4ac24a
[ "MIT" ]
26
2018-09-12T17:32:38.000Z
2018-10-09T18:16:31.000Z
true-business-backend/models/business.js
sophiemullerc/true-business
e062165e27344246f865c42f2b7499beae4ac24a
[ "MIT" ]
1
2018-09-10T16:06:01.000Z
2018-09-10T16:06:01.000Z
const mongoose = require('mongoose'); const businessSchema = new mongoose.Schema({ // places_details: name // returns a formatted string name: { type: String, required: true, }, // places_details: types // returns an array of strings types: [ { type: String, }, ], // places_details: formatted_address // returns a formatted string formatted_address: { type: String, required: true, }, // places_details: formatted_phone_number // returns a formatted string formatted_phone_number: { type: String, required: true, }, // places_details: website // Some restaurants don't have a website, no required website: { type: String, }, // places_details: photos // returns an array of objects // Unlikely, but possible there won't be any, no required photos: { type: Array, default: [ { link: "https://png.icons8.com/ios/100/000000/organization.png", width: 100, height: 100, }, ], }, // places_details: place_id // returns a string place_id: { type: String, required: true, }, // places_details: opening_hours/weekday_text // returns an array of seven strings opening_hours: { type: Object, }, // places_details: address_components/long_name // Not 100% about this one, but I believe it is what we are looking for // returns full text description supposedly (or name of address component?) address_components: { type: Object, }, // aggregate (may be the wrong word...) number thus far from the reviews // Ex. two reviews, 1 star and 5 star, this number would be 3 // When new review is added, this is calculated; grab the number of reviews, increment that by 1 // grab the stars, add the star rating from the new review to this rating, divide by 2 stars: { type: Number, default: 0, }, // Just the total number of reviews on this business. I would assume it would be as simple // as updating the business each time a new review has been posted. // Alternatively, we could probably just do business.reviews.length or something on the // front end whenever calculating stars / popularity. totalReviews: { type: Number, default: 0, }, reviews: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Review', }, ], // For the map object that will be placed on the business page. location: { type: Object, }, createdOn: { type: Date, required: true, default: Date.now(), }, updatedOn: { type: Date, required: true, default: Date.now(), }, popularity: { type: Boolean, required: true, default: false, }, rating: { type: Number, default: 0, } }); let businessModel = mongoose.model('Business', businessSchema); // Pre-save hook businessSchema.pre('save', function(next) { businessModel.find({ place_id: this.place_id }, (err, docs) => { if (!docs.length) { next(); } else { console.log('Business exists already'); next(new Error('Business exists!')); } }); }); // // Post-save hook // // This is where we update the net promotor score or whatever // businessSchema.pre('save', function(next) { // }); module.exports = businessModel;
24.931298
98
0.642682
a6678655a576c1c47552adbb36d7ab5b697b9917
253
swift
Swift
Sources/SPIDlibraryIOS/Extensions/NSObject+Extension.swift
teogira/SPIDlibraryIOS
92d10962ff5f92fe3b7596628626e043d2c14d37
[ "BSD-3-Clause" ]
49
2021-03-31T10:55:02.000Z
2022-02-14T21:32:46.000Z
Sources/SPIDlibraryIOS/Extensions/NSObject+Extension.swift
teogira/SPIDlibraryIOS
92d10962ff5f92fe3b7596628626e043d2c14d37
[ "BSD-3-Clause" ]
1
2021-11-02T13:37:36.000Z
2021-11-04T12:44:00.000Z
Sources/SPIDlibraryIOS/Extensions/NSObject+Extension.swift
teogira/SPIDlibraryIOS
92d10962ff5f92fe3b7596628626e043d2c14d37
[ "BSD-3-Clause" ]
6
2021-03-31T10:50:55.000Z
2021-10-13T19:35:59.000Z
// // SPDX-FileCopyrightText: 2021 Istituto Nazionale Previdenza Sociale // // SPDX-License-Identifier: BSD-3-Clause import Foundation extension NSObject { static var identifier: String { return String(describing: self) } }
16.866667
69
0.687747
85b54054c359222c7aa70f9ff647dc6732348c5b
988
c
C
code/2212.c
Tarpelite/OJ_research
5c23591a50e755dac800dfaedb561290ce35fc5b
[ "MIT" ]
null
null
null
code/2212.c
Tarpelite/OJ_research
5c23591a50e755dac800dfaedb561290ce35fc5b
[ "MIT" ]
null
null
null
code/2212.c
Tarpelite/OJ_research
5c23591a50e755dac800dfaedb561290ce35fc5b
[ "MIT" ]
null
null
null
#include <stdio.h> int N(int l, int r); int M(int l, int r); int H(int l, int r); int min(int a, int b); int max(int a, int b); int a[100], n; int main() { int K, l, r; scanf("%d %d", &n, &K); for(int i = 0; i < n; i++) { scanf("%d", &a[i]); } for(int i = 0; i < K; i++) { scanf("%d %d", &l, &r); printf("%d\n", H( min( N(l, r), M(l, r) ), max( N(l, r), M(l, r) ) ) ); } return 0; } int N(int l, int r) { int ans = 0; for(int i = l; i <= r; i++) { ans += a[i]; } ans %= n; return ans; } int M(int l, int r) { int ans = 1; for(int i = l; i <= r; i++) { ans *= a[i] % n; ans %= n; } ans %= n; return ans; } int H(int l, int r) { int ans; if(l == r) { return a[l]; } ans = a[l] ^ a[l + 1]; for(int i = l + 2; i <= r; i++) { ans = ans ^ a[i]; } return ans; } int min(int a, int b) { if(a > b) { return b; } else { return a; } } int max(int a, int b) { if(a >= b) { return a; } else { return b; } }
10.185567
73
0.425101
e76e9845676a6157e077e989eda4d1719e69bbca
7,508
js
JavaScript
client/app/sessionPractice/sessionPractice.controller.js
alinaMihai/wakeupApp
a547975d2b43caafafd278e472c609e730a6aee1
[ "MIT" ]
2
2016-01-24T18:18:22.000Z
2018-12-15T22:38:24.000Z
client/app/sessionPractice/sessionPractice.controller.js
alinaMihai/wakeupApp
a547975d2b43caafafd278e472c609e730a6aee1
[ "MIT" ]
null
null
null
client/app/sessionPractice/sessionPractice.controller.js
alinaMihai/wakeupApp
a547975d2b43caafafd278e472c609e730a6aee1
[ "MIT" ]
null
null
null
(function() { 'use strict'; angular .module('wakeupApp') .controller('SessionController', SessionController); SessionController.$inject = ['cached', 'QuestionService', '$timeout', 'PracticeSessionService', '$stateParams', '$state', 'logger', '$sessionStorage', 'QuoteService', '$window', 'AnswersFactory', 'CoreService', 'Auth' ]; /* @ngInject */ function SessionController(cached, QuestionService, $timeout, PracticeSessionService, $stateParams, $state, logger, $sessionStorage, QuoteService, $window, AnswersFactory, CoreService, Auth) { var vm = this; vm.startQuestionSet = startQuestionSet; vm.endQuestionSet = endQuestionSet; vm.isIE = CoreService.detectIE(); vm.processQuestion = processQuestion; vm.practiceSessionService = PracticeSessionService; var questions, questionsNo, timer; var questionSetId = $stateParams.questionSetId; var indexedDbOpened = false; activate(); //////////////// function activate() { cached.getQuestions(questionSetId).then(function(questionSet) { vm.questionSetQuestions = questionSet; questions = questionSet.questions; questionsNo = questions.length; logger.success("Question Set Session successfully started", {}, "Question Set Session"); PracticeSessionService.questionSetSession = true; //is configuration in sessionStorage? PracticeSessionService.questionInterval = $sessionStorage.questionInterval ? $sessionStorage.questionInterval : PracticeSessionService.questionInterval; PracticeSessionService.repeatQS = $sessionStorage.repeatQS ? $sessionStorage.repeatQS : PracticeSessionService.repeatQS; PracticeSessionService.shuffleQuestions = $sessionStorage.shuffleQuestions ? $sessionStorage.shuffleQuestions : PracticeSessionService.shuffleQuestions; if (PracticeSessionService.shuffleQuestions) { questions = shuffle(questions); } PracticeSessionService.currentQuestionIndex = 0; PracticeSessionService.displayProgress = PracticeSessionService.currentQuestionIndex + 1 + "/" + questionsNo; vm.currentQuestion = questions[PracticeSessionService.currentQuestionIndex]; if (vm.currentQuestion.quote) { QuoteService.getQuote(vm.currentQuestion.quote).then(function(quote) { vm.currentQuestion.quote = quote; }); } }); AnswersFactory.openIndexedDb().then(function() { indexedDbOpened = true; }); } function startQuestionSet() { PracticeSessionService.questionSetSession = true; logger.success("Question Set Session successfully started", {}, "Question Set Session"); PracticeSessionService.currentQuestionIndex = 0; PracticeSessionService.displayProgress = PracticeSessionService.currentQuestionIndex + 1 + "/" + questionsNo; vm.currentQuestion = questions[PracticeSessionService.currentQuestionIndex]; } function endQuestionSet() { PracticeSessionService.questionSetSession = false; PracticeSessionService.repeatQS = false; //remove any session configuration from sessionStorage delete $sessionStorage.questionInterval; delete $sessionStorage.repeatQS; delete $sessionStorage.shuffleQuestions; PracticeSessionService.currentQuestionIndex = undefined; logger.success("Question Set Session successfully ended", {}, "Question Set Session"); PracticeSessionService.questionInterval = undefined; QuestionService.registerSession(questionSetId).then(function(questionSet) { QuestionService.isUpdated = true; }, function(err) { console.log(err); }); $timeout(function() { $window.location.href = "/sessionDetails/" + questionSetId + "/" + vm.questionSetQuestions.name; }, 1000); if (timer) { $timeout.cancel(timer); } } function processQuestion(skipObj) { //save answer if (!skipObj) { saveAnswer(); } if (skipObj) { vm.currentAnswer = ""; } //setTimeInterval for next question if any if (PracticeSessionService.currentQuestionIndex >= 0 && PracticeSessionService.currentQuestionIndex < questionsNo - 1) { timer = $timeout(function() { PracticeSessionService.currentQuestionIndex++; PracticeSessionService.displayProgress = PracticeSessionService.currentQuestionIndex + 1 + "/" + questionsNo; vm.currentQuestion = questions[PracticeSessionService.currentQuestionIndex]; if (vm.currentQuestion.quote && typeof vm.currentQuestion.quote !== 'object') { QuoteService.getQuote(vm.currentQuestion.quote).then(function(quote) { vm.currentQuestion.quote = quote; }); } }, PracticeSessionService.questionInterval * 60 * 1000); } else { if (PracticeSessionService.repeatQS) { PracticeSessionService.currentQuestionIndex = undefined; timer = $timeout(function() { startQuestionSet(); }, PracticeSessionService.questionInterval * 60 * 1000); } else { endQuestionSet(); } } } function saveAnswer() { var user = Auth.getCurrentUser(); var questionId = vm.currentQuestion._id; var answerText = vm.currentAnswer; if (answerText !== undefined && answerText.trim() !== "") { var today = new Date().getTime(); var answer = { questionId: questionId, text: answerText, date: today, userId: user._id } //QuestionService.saveAnswer(answer); //QuestionService.isUpdated = true; if (indexedDbOpened) { AnswersFactory.saveAnswer(answer); vm.currentAnswer = ''; } } } function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } } })();
41.711111
129
0.568327
c1f556a18605748a3f80a9c31970172181d081b0
1,335
rs
Rust
shared/rust/src/domain/jig/module/body/legacy/design.rs
mastapegs/ji-cloud
b572289c5987f5e937f5e030fbd2712229ea1204
[ "Apache-2.0", "MIT" ]
null
null
null
shared/rust/src/domain/jig/module/body/legacy/design.rs
mastapegs/ji-cloud
b572289c5987f5e937f5e030fbd2712229ea1204
[ "Apache-2.0", "MIT" ]
null
null
null
shared/rust/src/domain/jig/module/body/legacy/design.rs
mastapegs/ji-cloud
b572289c5987f5e937f5e030fbd2712229ea1204
[ "Apache-2.0", "MIT" ]
null
null
null
pub use super::*; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct Design { /// Background layer pub bgs: Vec<String>, /// Stickers layer pub stickers: Vec<Sticker>, } #[skip_serializing_none] #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Sticker { pub filename: String, pub transform_matrix: [f64; 16], /// hide and hide_toggle are mapped from the top sections /// in "Houdini": HideOnTap, ShowOnTap, and ToggleOnTap /// start out hidden pub hide: bool, /// toggle hidden state pub hide_toggle: Option<HideToggle>, /// animation options are mapped from the bottom animation section pub animation: Option<Animation>, // associated audio pub audio_filename: Option<String>, /// override the size pub override_size: Option<(f64, f64)>, } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum HideToggle { /// only let the toggle fire once Once, /// let the toggle fire indefinitely Always, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Animation { /// do not let the animation loop pub once: bool, /// wait for tap before playing pub tap: bool, }
26.176471
70
0.681648
8ef2876c31b298afca6a85fb3021b51232b31658
446
rb
Ruby
DudeNobButts.rb
pblasser/shrelish
f15ecc23c3cd8fe6a97e7edb9f7ba7af1afd58e3
[ "MIT" ]
1
2021-11-14T00:53:56.000Z
2021-11-14T00:53:56.000Z
DudeNobButts.rb
pblasser/shrelish
f15ecc23c3cd8fe6a97e7edb9f7ba7af1afd58e3
[ "MIT" ]
null
null
null
DudeNobButts.rb
pblasser/shrelish
f15ecc23c3cd8fe6a97e7edb9f7ba7af1afd58e3
[ "MIT" ]
null
null
null
require './Dude.rb' def dudderat(d) end require './Dudetop.rb' class Dudebutt < Duderon def initialize(n,z) super(n,z) end def boxo #curno = 1.5 #while curno<=14.5 do balmet(16-1.5,0) #curno = curno + 1.5 #bomron(curno,1.5) # bomron(curno,-1.5) #curno= curno +1.5 #end end def ducabot end end myclasz = Dudebutt.new("NODES","ZYGOT") myclasz.boxo printf "G0 Z0.5\n" printf "G0 X0 Y0 \n"
15.37931
40
0.59417
a831572782ea7ddbca497fba585a13c91e6b75a2
2,609
rs
Rust
src/bb/bb_isoevtcntloffsetl1.rs
ldicocco/rsl10-pac
007871e940fe30f83de1da0f15fd25b052d1f340
[ "MIT" ]
null
null
null
src/bb/bb_isoevtcntloffsetl1.rs
ldicocco/rsl10-pac
007871e940fe30f83de1da0f15fd25b052d1f340
[ "MIT" ]
null
null
null
src/bb/bb_isoevtcntloffsetl1.rs
ldicocco/rsl10-pac
007871e940fe30f83de1da0f15fd25b052d1f340
[ "MIT" ]
null
null
null
#[doc = "Reader of register BB_ISOEVTCNTLOFFSETL1"] pub type R = crate::R<u32, super::BB_ISOEVTCNTLOFFSETL1>; #[doc = "Writer for register BB_ISOEVTCNTLOFFSETL1"] pub type W = crate::W<u32, super::BB_ISOEVTCNTLOFFSETL1>; #[doc = "Register BB_ISOEVTCNTLOFFSETL1 `reset()`'s with value 0"] impl crate::ResetValue for super::BB_ISOEVTCNTLOFFSETL1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "LSB part of EVT_CNT_OFFSET0\\[39:0\\] field\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u32)] pub enum EVT_CNT_OFFSETL1_A { #[doc = "0: `0`"] EVT_CNT_OFFSETL1_0 = 0, } impl From<EVT_CNT_OFFSETL1_A> for u32 { #[inline(always)] fn from(variant: EVT_CNT_OFFSETL1_A) -> Self { variant as _ } } #[doc = "Reader of field `EVT_CNT_OFFSETL1`"] pub type EVT_CNT_OFFSETL1_R = crate::R<u32, EVT_CNT_OFFSETL1_A>; impl EVT_CNT_OFFSETL1_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u32, EVT_CNT_OFFSETL1_A> { use crate::Variant::*; match self.bits { 0 => Val(EVT_CNT_OFFSETL1_A::EVT_CNT_OFFSETL1_0), i => Res(i), } } #[doc = "Checks if the value of the field is `EVT_CNT_OFFSETL1_0`"] #[inline(always)] pub fn is_evt_cnt_offsetl1_0(&self) -> bool { *self == EVT_CNT_OFFSETL1_A::EVT_CNT_OFFSETL1_0 } } #[doc = "Write proxy for field `EVT_CNT_OFFSETL1`"] pub struct EVT_CNT_OFFSETL1_W<'a> { w: &'a mut W, } impl<'a> EVT_CNT_OFFSETL1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EVT_CNT_OFFSETL1_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "`0`"] #[inline(always)] pub fn evt_cnt_offsetl1_0(self) -> &'a mut W { self.variant(EVT_CNT_OFFSETL1_A::EVT_CNT_OFFSETL1_0) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - LSB part of EVT_CNT_OFFSET0\\[39:0\\] field"] #[inline(always)] pub fn evt_cnt_offsetl1(&self) -> EVT_CNT_OFFSETL1_R { EVT_CNT_OFFSETL1_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - LSB part of EVT_CNT_OFFSET0\\[39:0\\] field"] #[inline(always)] pub fn evt_cnt_offsetl1(&mut self) -> EVT_CNT_OFFSETL1_W { EVT_CNT_OFFSETL1_W { w: self } } }
31.433735
84
0.627827
86f693bfd8851f18d1b620b814e86a57a40f582c
548
rs
Rust
Rust/Algorithms/551.rs
DimitrisJim/leetcode_solutions
765ea578748f8c9b21243dec9dc8a16163e85c0c
[ "Unlicense" ]
2
2021-01-15T17:22:54.000Z
2021-05-16T19:58:02.000Z
Rust/Algorithms/551.rs
DimitrisJim/leetcode_solutions
765ea578748f8c9b21243dec9dc8a16163e85c0c
[ "Unlicense" ]
null
null
null
Rust/Algorithms/551.rs
DimitrisJim/leetcode_solutions
765ea578748f8c9b21243dec9dc8a16163e85c0c
[ "Unlicense" ]
null
null
null
impl Solution { pub fn check_record(s: String) -> bool { let (mut consecutive, mut a_count) = (0, 0); for i in s.chars() { if i == 'L' { consecutive += 1; if consecutive == 3 { return false; } continue; } if i == 'A' { a_count += 1; if a_count > 1 { return false; } } consecutive = 0; } true } }
23.826087
52
0.326642
957fd963724b9cf866b2931f7fa1b7961b6d2b7c
7,534
asm
Assembly
Transynther/x86/_processed/NONE/_zr_/i7-7700_9_0x48.log_21829_451.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_zr_/i7-7700_9_0x48.log_21829_451.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_zr_/i7-7700_9_0x48.log_21829_451.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r8 push %r9 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_UC_ht+0xc122, %rdi nop nop and $28156, %r13 mov $0x6162636465666768, %r10 movq %r10, %xmm7 movups %xmm7, (%rdi) nop nop cmp $46654, %rax lea addresses_WC_ht+0x37c2, %rbp nop nop xor %r8, %r8 mov $0x6162636465666768, %r9 movq %r9, %xmm5 movups %xmm5, (%rbp) nop nop inc %r13 lea addresses_D_ht+0x11c82, %rsi lea addresses_A_ht+0x7f82, %rdi nop nop nop nop nop xor %r9, %r9 mov $6, %rcx rep movsq cmp $38378, %rbp lea addresses_D_ht+0x12d62, %rbp nop nop nop nop nop and %r13, %r13 mov $0x6162636465666768, %r10 movq %r10, %xmm5 movups %xmm5, (%rbp) and %r8, %r8 lea addresses_UC_ht+0xaa82, %rbp nop sub $62476, %rcx mov $0x6162636465666768, %rax movq %rax, %xmm6 vmovups %ymm6, (%rbp) nop nop nop nop and $24971, %r10 lea addresses_UC_ht+0x2982, %rcx clflush (%rcx) nop nop nop sub %r13, %r13 mov $0x6162636465666768, %rax movq %rax, (%rcx) nop nop nop nop nop lfence lea addresses_WT_ht+0x16a82, %rsi lea addresses_WC_ht+0x16f02, %rdi dec %r9 mov $29, %rcx rep movsl nop cmp $16995, %rdi lea addresses_UC_ht+0x18152, %rbp nop nop nop nop and %r10, %r10 mov (%rbp), %esi nop nop nop add %rsi, %rsi lea addresses_normal_ht+0x419a, %rsi lea addresses_UC_ht+0x14d82, %rdi nop nop nop nop sub $52908, %r13 mov $67, %rcx rep movsw nop sub $19003, %rdi lea addresses_D_ht+0x1dd82, %r9 nop cmp %r8, %r8 and $0xffffffffffffffc0, %r9 movaps (%r9), %xmm6 vpextrq $1, %xmm6, %rax lfence lea addresses_A_ht+0x46e2, %rax clflush (%rax) nop nop nop add $36449, %rbp movl $0x61626364, (%rax) nop nop and %rax, %rax pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r9 pop %r8 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r14 push %r15 push %r9 push %rax push %rbp push %rsi // Store lea addresses_WC+0x6e82, %r9 nop nop nop nop nop sub $42600, %r15 movb $0x51, (%r9) nop nop nop nop nop and %r11, %r11 // Load lea addresses_A+0x1f082, %rax inc %r14 movb (%rax), %r15b nop nop nop and $49039, %rbp // Store lea addresses_UC+0xfb22, %r14 nop xor $31134, %r9 movw $0x5152, (%r14) nop nop sub $20315, %r15 // Faulty Load lea addresses_WT+0xa282, %r15 nop nop xor $4925, %r14 mov (%r15), %ebp lea oracles, %rsi and $0xff, %rbp shlq $12, %rbp mov (%rsi,%rbp,1), %rbp pop %rsi pop %rbp pop %rax pop %r9 pop %r15 pop %r14 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 10, 'size': 1, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 9, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 4, 'size': 2, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 4, 'size': 16, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 5, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 9, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 8, 'size': 8, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 3, 'size': 4, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': True}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': True, 'congruent': 3, 'size': 16, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 5, 'size': 4, 'same': False, 'NT': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
33.784753
2,999
0.656092
9c33334930dd9a441a6a371a34f0a7c96e07f887
411
js
JavaScript
React16/SourceCode/Chapter12/snapterest/source/app.js
MikeAlexMartinez/ReactBooks
7fa2f5ab7a29eed00311ca0823784950c8d64e1f
[ "MIT" ]
15
2018-01-02T15:29:14.000Z
2021-07-24T15:48:56.000Z
React16/SourceCode/Chapter12/snapterest/source/app.js
MikeAlexMartinez/ReactBooks
7fa2f5ab7a29eed00311ca0823784950c8d64e1f
[ "MIT" ]
2
2019-03-28T04:00:54.000Z
2019-05-06T09:03:30.000Z
React16/SourceCode/Chapter12/snapterest/source/app.js
MikeAlexMartinez/ReactBooks
7fa2f5ab7a29eed00311ca0823784950c8d64e1f
[ "MIT" ]
17
2017-12-07T08:02:36.000Z
2020-06-03T11:11:37.000Z
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import Application from './components/Application'; import { initializeStreamOfTweets } from './utils/WebAPIUtils'; import store from './stores'; initializeStreamOfTweets(store); ReactDOM.render( <Provider store={store}> <Application/> </Provider>, document.getElementById('react-application') );
24.176471
63
0.742092
f594539ac8e111c47dc2e335fd52e0752094d189
1,228
rs
Rust
src/modular_constant.rs
kagemeka/rust-algorithms
69523507161d1ce97c583b029367ede82ec195e4
[ "MIT" ]
1
2022-02-17T12:52:45.000Z
2022-02-17T12:52:45.000Z
src/modular_constant.rs
kagemeka/dsalgo-rust
d22e747cb2fdaea68aec9c2d19b304eaa3d6551e
[ "MIT" ]
3
2022-01-06T12:50:07.000Z
2022-01-06T23:45:42.000Z
src/modular_constant.rs
kagemeka/rust-algorithms
69523507161d1ce97c583b029367ede82ec195e4
[ "MIT" ]
null
null
null
use crate::modular_static::{IsPrime, Modular, Modulus}; pub trait ConstantModulus: Modulus { const VALUE: usize; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MOD998_244_353; impl ConstantModulus for MOD998_244_353 { const VALUE: usize = 998_244_353; } impl Modulus for MOD998_244_353 { fn value() -> usize { Self::VALUE } } impl IsPrime for MOD998_244_353 {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MOD1_000_000_007; impl ConstantModulus for MOD1_000_000_007 { const VALUE: usize = 1_000_000_007; } impl Modulus for MOD1_000_000_007 { fn value() -> usize { Self::VALUE } } impl IsPrime for MOD1_000_000_007 {} pub type Modular998_244_353 = Modular<MOD998_244_353>; pub type Modular1_000_000_007 = Modular<MOD1_000_000_007>; #[cfg(test)] mod tests { #[test] fn test_static() { type Mint = super::Modular998_244_353; let mut x = Mint::new(998_244_353); assert_eq!(x.value(), 0); x += Mint::new(10); assert_eq!(x.value(), 10); x -= Mint::new(9); assert_eq!(x.value(), 1); x /= Mint::new(2); assert_eq!(x.value(), 499122177); assert_eq!(x, x); assert_eq!(x * x, x * x); } }
24.078431
58
0.645765
0e7f8381d7072a1279101f94b26b8e787eccadbd
23,743
html
HTML
modulaise/lib/commons-net-2.0/apidocs/serialized-form.html
larjen/modulaise
90a48c8f4ce0378389fe8617c6cc7349d3a8d31d
[ "Unlicense" ]
1
2016-04-05T21:14:39.000Z
2016-04-05T21:14:39.000Z
modulaise/lib/commons-net-2.0/apidocs/serialized-form.html
larjen/modulaise
90a48c8f4ce0378389fe8617c6cc7349d3a8d31d
[ "Unlicense" ]
null
null
null
modulaise/lib/commons-net-2.0/apidocs/serialized-form.html
larjen/modulaise
90a48c8f4ce0378389fe8617c6cc7349d3a8d31d
[ "Unlicense" ]
null
null
null
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_04) on Sun Oct 19 17:57:02 BST 2008 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> Serialized Form (Commons Net 2.0 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Serialized Form (Commons Net 2.0 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="index.html?serialized-form.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="serialized-form.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H1> Serialized Form</H1> </CENTER> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.MalformedServerReplyException"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/MalformedServerReplyException.html" title="class in org.apache.commons.net">org.apache.commons.net.MalformedServerReplyException</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/io/IOException.html" title="class or interface in java.io">IOException</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <P> <A NAME="org.apache.commons.net.ProtocolCommandEvent"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/ProtocolCommandEvent.html" title="class in org.apache.commons.net">org.apache.commons.net.ProtocolCommandEvent</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/util/EventObject.html" title="class or interface in java.util">EventObject</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> __replyCode</H3> <PRE> int <B>__replyCode</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> __isCommand</H3> <PRE> boolean <B>__isCommand</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> __message</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>__message</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> __command</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>__command</B></PRE> <DL> <DL> </DL> </DL> <P> <A NAME="org.apache.commons.net.ProtocolCommandSupport"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/ProtocolCommandSupport.html" title="class in org.apache.commons.net">org.apache.commons.net.ProtocolCommandSupport</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html" title="class or interface in java.lang">Object</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> __source</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html" title="class or interface in java.lang">Object</A> <B>__source</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> __listeners</H3> <PRE> <A HREF="org/apache/commons/net/util/ListenerList.html" title="class in org.apache.commons.net.util">ListenerList</A> <B>__listeners</B></PRE> <DL> <DL> </DL> </DL> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.ftp</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.ftp.FTPConnectionClosedException"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/ftp/FTPConnectionClosedException.html" title="class in org.apache.commons.net.ftp">org.apache.commons.net.ftp.FTPConnectionClosedException</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/io/IOException.html" title="class or interface in java.io">IOException</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <P> <A NAME="org.apache.commons.net.ftp.FTPFile"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/ftp/FTPFile.html" title="class in org.apache.commons.net.ftp">org.apache.commons.net.ftp.FTPFile</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html" title="class or interface in java.lang">Object</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> _type</H3> <PRE> int <B>_type</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _hardLinkCount</H3> <PRE> int <B>_hardLinkCount</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _size</H3> <PRE> long <B>_size</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _rawListing</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>_rawListing</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _user</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>_user</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _group</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>_group</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _name</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>_name</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _link</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>_link</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _date</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/util/Calendar.html" title="class or interface in java.util">Calendar</A> <B>_date</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> _permissions</H3> <PRE> boolean[][] <B>_permissions</B></PRE> <DL> <DL> </DL> </DL> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.ftp.parser</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.ftp.parser.ParserInitializationException"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/ftp/parser/ParserInitializationException.html" title="class in org.apache.commons.net.ftp.parser">org.apache.commons.net.ftp.parser.ParserInitializationException</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html" title="class or interface in java.lang">RuntimeException</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> rootCause</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html" title="class or interface in java.lang">Throwable</A> <B>rootCause</B></PRE> <DL> <DD>Root exception that caused this to be thrown <P> <DL> </DL> </DL> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.io</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.io.CopyStreamEvent"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/io/CopyStreamEvent.html" title="class in org.apache.commons.net.io">org.apache.commons.net.io.CopyStreamEvent</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/util/EventObject.html" title="class or interface in java.util">EventObject</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> bytesTransferred</H3> <PRE> int <B>bytesTransferred</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> totalBytesTransferred</H3> <PRE> long <B>totalBytesTransferred</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> streamSize</H3> <PRE> long <B>streamSize</B></PRE> <DL> <DL> </DL> </DL> <P> <A NAME="org.apache.commons.net.io.CopyStreamException"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/io/CopyStreamException.html" title="class in org.apache.commons.net.io">org.apache.commons.net.io.CopyStreamException</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/io/IOException.html" title="class or interface in java.io">IOException</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> totalBytesTransferred</H3> <PRE> long <B>totalBytesTransferred</B></PRE> <DL> <DL> </DL> </DL> <HR> <H3> ioException</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/io/IOException.html" title="class or interface in java.io">IOException</A> <B>ioException</B></PRE> <DL> <DL> </DL> </DL> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.nntp</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.nntp.NNTPConnectionClosedException"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/nntp/NNTPConnectionClosedException.html" title="class in org.apache.commons.net.nntp">org.apache.commons.net.nntp.NNTPConnectionClosedException</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/io/IOException.html" title="class or interface in java.io">IOException</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.ntp</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.ntp.TimeStamp"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/ntp/TimeStamp.html" title="class in org.apache.commons.net.ntp">org.apache.commons.net.ntp.TimeStamp</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html" title="class or interface in java.lang">Object</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <B>serialVersionUID:&nbsp;</B>8139806907588338737L <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> ntpTime</H3> <PRE> long <B>ntpTime</B></PRE> <DL> <DD>NTP timestamp value: 64-bit unsigned fixed-point number as defined in RFC-1305 with high-order 32 bits the seconds field and the low-order 32-bits the fractional field. <P> <DL> </DL> </DL> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.smtp</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.smtp.SMTPConnectionClosedException"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/smtp/SMTPConnectionClosedException.html" title="class in org.apache.commons.net.smtp">org.apache.commons.net.smtp.SMTPConnectionClosedException</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/io/IOException.html" title="class or interface in java.io">IOException</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.telnet</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.telnet.InvalidTelnetOptionException"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/telnet/InvalidTelnetOptionException.html" title="class in org.apache.commons.net.telnet">org.apache.commons.net.telnet.InvalidTelnetOptionException</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Exception.html" title="class or interface in java.lang">Exception</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> optionCode</H3> <PRE> int <B>optionCode</B></PRE> <DL> <DD>Option code <P> <DL> </DL> </DL> <HR> <H3> msg</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A> <B>msg</B></PRE> <DL> <DD>Error message <P> <DL> </DL> </DL> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.tftp</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.tftp.TFTPPacketException"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/tftp/TFTPPacketException.html" title="class in org.apache.commons.net.tftp">org.apache.commons.net.tftp.TFTPPacketException</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Exception.html" title="class or interface in java.lang">Exception</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>org.apache.commons.net.util</B></FONT></TH> </TR> </TABLE> <P> <A NAME="org.apache.commons.net.util.ListenerList"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="org/apache/commons/net/util/ListenerList.html" title="class in org.apache.commons.net.util">org.apache.commons.net.util.ListenerList</A> extends <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html" title="class or interface in java.lang">Object</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> __listeners</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html" title="class or interface in java.util.concurrent">CopyOnWriteArrayList</A>&lt;<A HREF="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html" title="class or interface in java.util.concurrent">E</A>&gt; <B>__listeners</B></PRE> <DL> <DL> </DL> </DL> <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="index.html?serialized-form.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="serialized-form.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 1997-2008 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
34.610787
396
0.656109
3a40162adfd11aba3d8d0804bce8be3161eb92a7
378
sql
SQL
Database/PostgreSQL/Triggers.sql
AlejandroIbarraC/Pandemica
44497ffce12e02b27778260c45b21be823632e33
[ "MIT" ]
null
null
null
Database/PostgreSQL/Triggers.sql
AlejandroIbarraC/Pandemica
44497ffce12e02b27778260c45b21be823632e33
[ "MIT" ]
null
null
null
Database/PostgreSQL/Triggers.sql
AlejandroIbarraC/Pandemica
44497ffce12e02b27778260c45b21be823632e33
[ "MIT" ]
1
2020-10-29T22:26:52.000Z
2020-10-29T22:26:52.000Z
-- Auxiliary function that makes rollback on trigger create or replace function udt_hospital_deleted() returns trigger language plpgsql as $$ begin raise warning 'Hospitals can not be deleted'; rollback; end; $$; -- Trigger that stops hospitals from been deleted create trigger hospital_delete before delete on hospital execute procedure udt_hospital_deleted();
25.2
52
0.780423
50946dbeb85731d3a3e70d1111f4e7625ae99820
265
swift
Swift
DalyCovidReport/DalyCovidReportApp.swift
Dol2oMo/thailand-covid-case-iOS
af2ac16e12aa20e6d3e78b9f36f34d675629fa37
[ "MIT" ]
null
null
null
DalyCovidReport/DalyCovidReportApp.swift
Dol2oMo/thailand-covid-case-iOS
af2ac16e12aa20e6d3e78b9f36f34d675629fa37
[ "MIT" ]
null
null
null
DalyCovidReport/DalyCovidReportApp.swift
Dol2oMo/thailand-covid-case-iOS
af2ac16e12aa20e6d3e78b9f36f34d675629fa37
[ "MIT" ]
null
null
null
// // DalyCovidReportApp.swift // DalyCovidReport // // Created by Sorasak Tungpraisansombut on 20/7/2564 BE. // import SwiftUI @main struct DalyCovidReportApp: App { var body: some Scene { WindowGroup { ContentView() } } }
14.722222
57
0.618868
18dfcf7de8e273d85f70f36e8e7f64257dccb036
1,352
css
CSS
public/css/components/global.css
rbevaristo/routa
d9d3e47475ba0cb0e716ebd2496bc7571286a012
[ "MIT" ]
null
null
null
public/css/components/global.css
rbevaristo/routa
d9d3e47475ba0cb0e716ebd2496bc7571286a012
[ "MIT" ]
null
null
null
public/css/components/global.css
rbevaristo/routa
d9d3e47475ba0cb0e716ebd2496bc7571286a012
[ "MIT" ]
null
null
null
/* Custom Styles */ body { color: #444; font-family: "Montserrat"; } /* Global */ .bg-primary { background-color: #373737 !important; } .navbar .nav-link { color: #fff !important; } .navbar .nav-link:hover { color: #478dd2 !important; } .navbar .active a { color: #478dd2 !important; } section .title { color: #478dd2; margin-bottom: 30px; font-size: 60px; text-transform: uppercase; font-weight: bold; } a .fa-google-plus { font-size: 20px; color: #d34836; } a .fa-facebook-square { font-size: 20px; color: #3B5998; } .nav-item .fa-user, .nav-item .fa-sign-out, .nav-item .fa-gear { color: #478dd2 !important; } a .fa-gear { color: #fff !important; } .dropdown-toggle::after { display: none; } .nav-item .fa-gear { color: #478dd2 !important; } .my-4 { background-color: #efefef; } @media (max-width: 992px) {} @media (max-width: 768px) { section .title { margin-bottom: 30px; font-size: 32px; } section .description { color: #373737; margin-bottom: 30px; font-size: 25px; } } @media (max-width: 576px) { section .title { margin-bottom: 30px; font-size: 27px; } section .description { color: #373737; margin-bottom: 30px; font-size: 15px; } }
14.857143
41
0.572485
b908b563779e505dc23f151c8c6fb6185746c3ff
8,060
c
C
src/ofix/store.c
ohler55/ofix
9988107172c7e3287cc996d8d65d5017bd69299d
[ "MIT" ]
null
null
null
src/ofix/store.c
ohler55/ofix
9988107172c7e3287cc996d8d65d5017bd69299d
[ "MIT" ]
null
null
null
src/ofix/store.c
ohler55/ofix
9988107172c7e3287cc996d8d65d5017bd69299d
[ "MIT" ]
null
null
null
// Copyright 2009, 2015 by Peter Ohler, All Rights Reserved #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> #include "store.h" #include "engine.h" #define LOCS_INC 4096 Store ofix_store_create(ofixErr err, const char *path, const char *id) { char buf[1024]; Store s; if (NULL != err && OFIX_OK != err->code) { return NULL; } if (NULL == id) { if (NULL != err) { err->code = OFIX_ARG_ERR; strcpy(err->msg, "NULL sender identifier argument to session store creation is not valid."); } return NULL; } if (NULL == path) { time_t now = time(NULL); struct tm *tm = gmtime(&now); snprintf(buf, sizeof(buf), "%s-%04d%02d%02d.%02d%02d%02d", id, tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); path = buf; } if (NULL == (s = (Store)malloc(sizeof(struct _Store)))) { if (NULL != err) { err->code = OFIX_MEMORY_ERR; strcpy(err->msg, "Failed to allocate memory for session storage."); } return NULL; } s->sindex.size = LOCS_INC; s->rindex.size = LOCS_INC; if (NULL == (s->sindex.locs = (Loc)malloc(sizeof(struct _Loc) * LOCS_INC))) { if (NULL != err) { err->code = OFIX_MEMORY_ERR; strcpy(err->msg, "Failed to allocate memory for session store index."); } free(s); return NULL; } if (NULL == (s->rindex.locs = (Loc)malloc(sizeof(struct _Loc) * LOCS_INC))) { if (NULL != err) { err->code = OFIX_MEMORY_ERR; strcpy(err->msg, "Failed to allocate memory for session store index."); } free(s->sindex.locs); free(s); return NULL; } if (NULL == (s->file = fopen(path, "w+"))) { if (NULL != err) { err->code = OFIX_WRITE_ERR; snprintf(err->msg, sizeof(err->msg), "Failed to create file '%s'. %s", path, strerror(errno)); } free(s->sindex.locs); free(s); return NULL; } s->where = fprintf(s->file, "sender: %s\n\n", id); if (0 >= s->where) { if (NULL != err) { err->code = OFIX_WRITE_ERR; strcpy(err->msg, "Failed to write header."); } free(s->sindex.locs); free(s); return NULL; } return s; } void ofix_store_destroy(Store store) { if (NULL != store) { if (NULL != store->file) { fclose(store->file); } if (NULL != store->sindex.locs) { free(store->sindex.locs); } if (NULL != store->rindex.locs) { free(store->rindex.locs); } free(store); } } static void index_add(ofixErr err, Index index, int64_t seq, off_t where, off_t len) { Loc loc; if (index->size <= seq) { int64_t new_size = index->size + LOCS_INC; if (new_size - 100 <= seq) { new_size = seq + LOCS_INC; } if (NULL == (index->locs = (Loc)realloc(index->locs, sizeof(struct _Loc) * new_size))) { if (NULL != err) { err->code = OFIX_MEMORY_ERR; strcpy(err->msg, "Failed to allocate memory for session store index."); } return; } memset(index->locs + index->size, 0, sizeof(struct _Loc) * (new_size - index->size)); } loc = index->locs + seq; loc->start = where; loc->size = len; } void ofix_store_add(ofixErr err, Store store, int64_t seq, IoDir dir, ofixMsg msg) { const char* mstr = NULL; off_t mlen = 0; if (NULL != err && OFIX_OK != err->code) { return; } if (NULL == store) { if (NULL != err) { err->code = OFIX_ARG_ERR; strcpy(err->msg, "NULL store in call to staore add."); } return; } if (NULL == msg) { if (NULL != err) { err->code = OFIX_ARG_ERR; strcpy(err->msg, "NULL mesage argument to store add."); } return; } if (NULL == store->file) { if (NULL != err) { err->code = OFIX_ARG_ERR; strcpy(err->msg, "No storage setup for session."); } return; } mlen = ofix_msg_size(err, msg); mstr = ofix_msg_FIX_str(err, msg); if (NULL != err && OFIX_OK != err->code) { return; } if (mlen != fwrite(mstr, 1, mlen, store->file) || 1 != fwrite("\n", 1, 1, store->file)) { fclose(store->file); store->file = NULL; if (NULL != err) { err->code = OFIX_WRITE_ERR; strcpy(err->msg, "Failed to store message."); } return; } switch (dir) { case OFIX_IODIR_SEND: index_add(err, &store->sindex, seq, store->where, mlen); break; case OFIX_IODIR_RECV: index_add(err, &store->rindex, seq, store->where, mlen); break; default: // error break; } store->where += mlen + 1; } ofixMsg ofix_store_get(ofixErr err, Store store, int64_t seq, IoDir dir) { ofixMsg msg = NULL; Loc loc = NULL; char buf[4096]; char *mstr = buf; switch (dir) { case OFIX_IODIR_SEND: if (seq < store->sindex.size) { loc = store->sindex.locs + seq; } break; case OFIX_IODIR_RECV: if (seq < store->rindex.size) { loc = store->rindex.locs + seq; } break; default: if (seq < store->sindex.size) { loc = store->sindex.locs + seq; } else if (seq < store->rindex.size) { loc = store->rindex.locs + seq; } break; } if (NULL == loc || 0 == loc->start || 0 == loc->size) { return NULL; } if (0 != fseek(store->file, loc->start, SEEK_SET)) { if (NULL != err) { err->code = OFIX_READ_ERR; snprintf(err->msg, sizeof(err->msg), "Failed to find message. %s", strerror(errno)); } return NULL; } if (sizeof(buf) <= loc->size) { if (NULL == (mstr = (char*)malloc(loc->size + 1))) { if (NULL != err) { err->code = OFIX_MEMORY_ERR; strcpy(err->msg, "Failed to allocate memory for message."); } return NULL; } } if (loc->size != fread(mstr, 1, loc->size, store->file)) { if (NULL != err) { err->code = OFIX_READ_ERR; snprintf(err->msg, sizeof(err->msg), "Failed to read message. %s", strerror(errno)); } return NULL; } msg = ofix_msg_parse(err, mstr, loc->size); if (0 != fseek(store->file, store->where, SEEK_SET)) { if (NULL != err) { err->code = OFIX_READ_ERR; snprintf(err->msg, sizeof(err->msg), "Failed to reset storage. %s", strerror(errno)); } } if (buf != mstr) { free(mstr); } return msg; } void ofix_store_iterate(ofixErr err, Store store, bool (*cb)(ofixMsg msg, void *ctx), void *ctx) { if (0 != fseek(store->file, 0, SEEK_SET)) { if (NULL != err) { err->code = OFIX_READ_ERR; snprintf(err->msg, sizeof(err->msg), "Failed to read storage. %s", strerror(errno)); } return; } ofix_store_fiterate(err, store->file, cb, ctx); if (0 != fseek(store->file, store->where, SEEK_SET)) { if (NULL != err) { err->code = OFIX_READ_ERR; snprintf(err->msg, sizeof(err->msg), "Failed to reset storage. %s", strerror(errno)); } } } void ofix_store_fiterate(ofixErr err, FILE *f, bool (*cb)(ofixMsg msg, void *ctx), void *ctx) { ofixMsg msg; char buf[4096]; char *b; char *end = buf; size_t cnt; int rcnt = 0; for (b = buf; 2 > rcnt; b++) { if (end <= b) { if (0 == (cnt = fread(buf, 1, sizeof(buf), f))) { // short return; } b = buf; end = buf + cnt; } if ('\n' == *b) { rcnt++; } else { rcnt = 0; } } while (true) { // need at least 22 bytes to read the expected message length if (22 > end - b) { cnt = end - b; memmove(buf, b, cnt); end = buf + cnt; b = buf; if (0 == (cnt = fread(end, 1, sizeof(buf) - cnt, f))) { return; } end += cnt; } cnt = ofix_msg_expected_buf_size(b); if (end - b < cnt + 1) { // If the buf is not big enough then error out for now. if (sizeof(buf) < cnt + 1) { if (NULL != err) { err->code = OFIX_OVERFLOW_ERR; strcpy(err->msg, "Not enough space to read message."); } return; } if (sizeof(buf) < (b - buf) + cnt + 1) { rcnt = end - b; memmove(buf, b, rcnt); end = buf + rcnt; b = buf; } if (0 == (rcnt = fread(end, 1, sizeof(buf) - (end - buf), f))) { return; } end += rcnt; } if (NULL == (msg = ofix_msg_parse(err, b, cnt))) { return; } if (cb(msg, ctx)) { ofix_msg_destroy(msg); } b += cnt; b++; // past \n } }
24.204204
97
0.57134