file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); ...
impl fmt::Display for Binding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Binding") } }
random_line_split
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); ...
pub fn get_target_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_target_property( self.to_glib_none().0, )) } } pub fn unbind(&self) { unsafe { gobject_sys::g_binding_unbind(self.to_glib_full()); ...
{ unsafe { from_glib_none(gobject_sys::g_binding_get_target(self.to_glib_none().0)) } }
identifier_body
binding.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use std::fmt; use translate::*; use BindingFlags; use GString; use Object; glib_wrapper! { pub struct Binding(Object<gobject_sys::GBinding, BindingClass>); ...
(&self) -> Option<Object> { unsafe { from_glib_none(gobject_sys::g_binding_get_source(self.to_glib_none().0)) } } pub fn get_source_property(&self) -> GString { unsafe { from_glib_none(gobject_sys::g_binding_get_source_property( self.to_glib_none().0, )) ...
get_source
identifier_name
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRY...
} #[cfg(test)] mod tests { use db::Entry; use db::Database; use std::io::Cursor; use std::io::Read; #[test] fn test_save_and_load() { let mut buff: Cursor<Vec<u8>> = Cursor::new(vec![]); { let mut db = Database::empty("test"); db.add(Entry::new("servic...
{ Err(Error::new(ErrorKind::InvalidData, text)) }
identifier_body
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRY...
let mut bcrypt_output = [0u8; PASS_SIZE]; // output 24 bytes let mut version_buffer = [0u8; 1]; match src.read(&mut version_buffer){ Ok(_) => (), Err(why) => return Err(why) }; if version_buffer[0] != DB_VERSION { return Database::invalid_data...
random_line_split
db.rs
use std::path::Path; use std::fs::File; use std::io::{Write, Read, self, Error, ErrorKind}; use db::Entry; use nacl::secretbox::{SecretKey, SecretMsg}; use rand::{ Rng, OsRng }; use crypto::bcrypt::bcrypt; use serde_json; const DB_VERSION: u8 = 1u8; const SALT_SIZE: usize = 16; const PASS_SIZE: usize = 24; const BCRY...
{ pub db: Database, pub filepath: String } impl DatabaseInFile { pub fn save(&self) -> io::Result<()>{ self.db.save_to_file(Path::new(&self.filepath)) } } pub struct Database { bcrypt_salt: [u8; SALT_SIZE], bcrypt_pass: [u8; PASS_SIZE], pub entries: Vec<Entry> } impl Database { ...
DatabaseInFile
identifier_name
rand.rs
[`choose()`]: fn.choose.html //! [`Random`]: trait.Random.html //! [`RandomRange`]: trait.RandomRange.html //! [`RandomSlice`]: trait.RandomSlice.html //! [`Distance`]: ../type.Distance.html //! [`Angle`]: ../type.Angle.html //! [`Speed`]: ../speed/struct.Speed.html //! [`Color`]: ../color/struct.Color.html //! [`Poin...
/// struct Product { /// price: f64, /// quantity: u32, /// } /// ``` /// /// What would `random_range(1.5, 5.2)` mean for this type? It's hard to say because while you /// could generate a random value for `price`, it doesn't make sense to generate a `quantity` /// given that range. /// /// A notable exception...
/// #[derive(Debug, Clone)]
random_line_split
rand.rs
to get the appropriate number of repeats (they're not // actually needed because type inference can figure it out) $( random::<$tyvar>() ),* // Trailing comma for the 1 tuple , ) ...
{ slice.shuffle(); }
identifier_body
rand.rs
number. /// // Notice the type in the numeric literal so Rust knows what to generate /// match RandomRange::random_range(0u8, 3) { /// 0 => Open, /// 1 => Closed, /// 2 => Locked, /// // Even though we know that the value will be between 0 and 2, the comp...
{ Some(Random::random()) }
conditional_block
rand.rs
{ /// if low < MIN_DIFFICULTY || high > MAX_DIFFICULTY { /// panic!("The boundaries must be within the valid range of difficulties"); /// } /// /// RandomRange::random_range(low, high) /// } /// } /// /// fn main() { /// use turtle::rand::{random, random_range}; /// /// ...
shuffle
identifier_name
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from gakkgakk.app import create_app from gakkgakk.models import User from gakkgakk.settings import DevConfig, ProdConfig from gakkgakk.database import db reload(...
(): """Run the tests.""" import pytest exit_code = pytest.main([TEST_PATH, '--verbose']) return exit_code manager.add_command('server', Server(host='0.0.0.0', threaded=True)) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', MigrateCommand) if __name__ == '__ma...
test
identifier_name
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from gakkgakk.app import create_app from gakkgakk.models import User from gakkgakk.settings import DevConfig, ProdConfig from gakkgakk.database import db reload(...
@manager.command def test(): """Run the tests.""" import pytest exit_code = pytest.main([TEST_PATH, '--verbose']) return exit_code manager.add_command('server', Server(host='0.0.0.0', threaded=True)) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', MigrateCo...
"""Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': app, 'db': db, 'User': User}
identifier_body
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from gakkgakk.app import create_app from gakkgakk.models import User from gakkgakk.settings import DevConfig, ProdConfig from gakkgakk.database import db reload(...
manager.run()
conditional_block
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from gakkgakk.app import create_app
reload(sys) sys.setdefaultencoding('utf-8') app = create_app(ProdConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) def _make_context(): """Return context dict for a shell session so you can access app, db, and the User model by default...
from gakkgakk.models import User from gakkgakk.settings import DevConfig, ProdConfig from gakkgakk.database import db
random_line_split
list_to_build_script.py
#!/usr/bin/python # Usage: list_to_make_var.py <input file (mod list)> <output file 1(build script)> <output file 2(clean script)> <OS> # argv: argv[0] argv[1] argv[2] argv[3] argv[4] # # Include library # import os import sys def
(fileName, mode = 'r'): # mode : 'r', 'w', ... try: fp = open(fileName, mode) except OSError as err: print("OS error: {0}".format(err)) sys.exit(1) except: print("Unexpected error:", sys.exc_info()[0]) sys.exit(1) return fp mod_base_path = '../' curr_os = str(sys.argv[4]) if curr_os == 'WIN': mod_buil...
OpenFile
identifier_name
list_to_build_script.py
#!/usr/bin/python # Usage: list_to_make_var.py <input file (mod list)> <output file 1(build script)> <output file 2(clean script)> <OS> # argv: argv[0] argv[1] argv[2] argv[3] argv[4] # # Include library # import os import sys def OpenF...
# # main # if len(sys.argv) != 5: print("Arguments Number Error. It should be 5.") sys.exit(1) finList = OpenFile(str(sys.argv[1])) foutBuildfile = OpenFile(str(sys.argv[2]), 'w') foutCleanfile = OpenFile(str(sys.argv[3]), 'w') for each_line in finList: each_mod = each_line.strip() # build files str = mod...
mod_clean_file = 'clean_mod.sh'
random_line_split
list_to_build_script.py
#!/usr/bin/python # Usage: list_to_make_var.py <input file (mod list)> <output file 1(build script)> <output file 2(clean script)> <OS> # argv: argv[0] argv[1] argv[2] argv[3] argv[4] # # Include library # import os import sys def OpenF...
finList.close() foutBuildfile.close() foutCleanfile.close()
each_mod = each_line.strip() # build files str = mod_base_path + each_mod + '/' + mod_build_file + '\n' foutBuildfile.write(str) # clean files str = mod_base_path + each_mod + '/' + mod_clean_file + '\n' foutCleanfile.write(str)
conditional_block
list_to_build_script.py
#!/usr/bin/python # Usage: list_to_make_var.py <input file (mod list)> <output file 1(build script)> <output file 2(clean script)> <OS> # argv: argv[0] argv[1] argv[2] argv[3] argv[4] # # Include library # import os import sys def OpenF...
mod_base_path = '../' curr_os = str(sys.argv[4]) if curr_os == 'WIN': mod_build_file = 'build_mod.bat' mod_clean_file = 'clean_mod.bat' else: mod_build_file = 'build_mod.sh' mod_clean_file = 'clean_mod.sh' # # main # if len(sys.argv) != 5: print("Arguments Number Error. It should be 5.") sys.exit(1) finLis...
try: fp = open(fileName, mode) except OSError as err: print("OS error: {0}".format(err)) sys.exit(1) except: print("Unexpected error:", sys.exc_info()[0]) sys.exit(1) return fp
identifier_body
test_publisher.py
from lib import broker __author__ = 'ehonlia' import pika import logging logging.basicConfig() connection = pika.BlockingConnection(pika.ConnectionParameters(host=broker.HOST)) channel = connection.channel() channel.exchange_declare(exchange=broker.STREAM_EXCHANGE, type=broker.EXCHANGE_TYPE) message = ''' { "_i...
"name": "[ER Day 2013] Battery North", "resource": { "resource_type": "", "uuid": "" }, "active": true, "subscribers": [], "user_ranking": { "average": 60, "nr_rankings": 1 }, "unit": "", "quality": 1, "history_size": 6995, "polling_freq": 0, "crea...
"_source": { "polling": false, "min_val": "0", "nr_subscribers": 0, "uri": "",
random_line_split
update-license-dump.ts
import * as path from 'path' import * as fs from 'fs-extra' import { promisify } from 'util' import { licenseOverrides } from './license-overrides' import _legalEagle from 'legal-eagle' const legalEagle = promisify(_legalEagle) import { getVersion } from '../../app/package-info' export async function
( projectRoot: string, outRoot: string ): Promise<void> { const appRoot = path.join(projectRoot, 'app') const outPath = path.join(outRoot, 'static', 'licenses.json') let summary = await legalEagle({ path: appRoot, overrides: licenseOverrides, omitPermissive: true, }) if (Object.keys(summary)...
updateLicenseDump
identifier_name
update-license-dump.ts
import * as path from 'path' import * as fs from 'fs-extra' import { promisify } from 'util' import { licenseOverrides } from './license-overrides' import _legalEagle from 'legal-eagle' const legalEagle = promisify(_legalEagle) import { getVersion } from '../../app/package-info' export async function updateLicenseD...
summary = await legalEagle({ path: appRoot, overrides: licenseOverrides, }) // legal-eagle still chooses to ignore the LICENSE at the root // this injects the current license and pins the source URL before we // dump the JSON file to disk const licenseSource = path.join(projectRoot, 'LICENSE') ...
{ let licensesMessage = '' for (const key in summary) { const license = summary[key] licensesMessage += `${key} (${license.repository}): ${license.license}\n` } const overridesPath = path.join(__dirname, 'license-overrides.ts') const message = `The following dependencies have unknown o...
conditional_block
update-license-dump.ts
import * as path from 'path' import * as fs from 'fs-extra' import { promisify } from 'util'
import _legalEagle from 'legal-eagle' const legalEagle = promisify(_legalEagle) import { getVersion } from '../../app/package-info' export async function updateLicenseDump( projectRoot: string, outRoot: string ): Promise<void> { const appRoot = path.join(projectRoot, 'app') const outPath = path.join(outRoot,...
import { licenseOverrides } from './license-overrides'
random_line_split
update-license-dump.ts
import * as path from 'path' import * as fs from 'fs-extra' import { promisify } from 'util' import { licenseOverrides } from './license-overrides' import _legalEagle from 'legal-eagle' const legalEagle = promisify(_legalEagle) import { getVersion } from '../../app/package-info' export async function updateLicenseD...
throw new Error(message) } summary = await legalEagle({ path: appRoot, overrides: licenseOverrides, }) // legal-eagle still chooses to ignore the LICENSE at the root // this injects the current license and pins the source URL before we // dump the JSON file to disk const licenseSource = path...
{ const appRoot = path.join(projectRoot, 'app') const outPath = path.join(outRoot, 'static', 'licenses.json') let summary = await legalEagle({ path: appRoot, overrides: licenseOverrides, omitPermissive: true, }) if (Object.keys(summary).length > 0) { let licensesMessage = '' for (const k...
identifier_body
minimax_test.rs
use crate::minimax::{Minimax, MinimaxConfig, MinimaxMovesSorting, MinimaxType}; use env_logger; use oppai_field::construct_field::construct_field; use oppai_field::player::Player; use oppai_test_images::*; use rand::SeedableRng; use rand_xorshift::XorShiftRng; const SEED: [u8; 16] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29...
macro_rules! minimax_test { ($(#[$($attr:meta),+])* $name:ident, $config:ident, $image:ident, $depth:expr) => { #[test] $(#[$($attr),+])* fn $name() { env_logger::try_init().ok(); let mut rng = XorShiftRng::from_seed(SEED); let mut field = construct_field(&mut rng, $image.image); ...
rebuild_trajectories: false, };
random_line_split
SaveLoad.ts
function
() { const middleViewport = new Viewport() type Saved = { OpenedTimes: number } const loaded = Load<Saved>("Name") const data = loaded || { OpenedTimes: 0 } data.OpenedTimes++ const saved = Save("Name", data) let text = "" if (SaveAndLoadAvailable()) text += "Save and load sho...
SaveLoadDemo
identifier_name
SaveLoad.ts
function SaveLoadDemo() { const middleViewport = new Viewport() type Saved = { OpenedTimes: number } const loaded = Load<Saved>("Name") const data = loaded || { OpenedTimes: 0 } data.OpenedTimes++ const saved = Save("Name", data) let text = "" if (SaveAndLoadAvailable()) text ...
return () => middleViewport.Delete() }
text += `\n\nThis demo has been opened ${data.OpenedTimes} time(s).\n\nThis should persist between runs.` if (!loaded) text += "\n\nA previous save could not be loaded." if (!saved) text += "\n\nThis information could not be saved." FontBig.Write(middleViewport, text, HorizontalAlignment.Middle, Vertic...
random_line_split
SaveLoad.ts
function SaveLoadDemo()
return () => middleViewport.Delete() }
{ const middleViewport = new Viewport() type Saved = { OpenedTimes: number } const loaded = Load<Saved>("Name") const data = loaded || { OpenedTimes: 0 } data.OpenedTimes++ const saved = Save("Name", data) let text = "" if (SaveAndLoadAvailable()) text += "Save and load should...
identifier_body
ReplProbe.js
// ReplProbe.js (c) 2010-2013 Loren West and other contributors // May be freely distributed under the MIT license. // For further details and documentation: // http://lorenwest.github.com/monitor-min (function(root){ // Module loading - this runs server-side only var Monitor = root.Monitor || require('../Monitor'...
t.shellCmd = null; t._output(CONSOLE_PROMPT); }); return null; } }); // Define an internal stream class for the probe var ReplStream = function(probe){ var t = this; t.probe = probe; events.EventEmitter.call(t); if (t.setEncoding) { t.setEncoding('utf8'); ...
{ t._output(stderr); }
conditional_block
ReplProbe.js
// ReplProbe.js (c) 2010-2013 Loren West and other contributors // May be freely distributed under the MIT license. // For further details and documentation: // http://lorenwest.github.com/monitor-min (function(root){ // Module loading - this runs server-side only var Monitor = root.Monitor || require('../Monitor'...
* @class ReplProbe * @extends Probe * @constructor * @param initParams {Object} Probe initialization parameters * @param initParams.uniqueInstance - Usually specified to obtain a unique REPL probe instance * @param model {Object} Monitor data model elements * @param model.output {String} Last (cur...
* A probe based Read-Execute-Print-Loop console for node.js processes *
random_line_split
Folio.js
const models = require('../models'); const Portal = models.Portal; const Folio = models.Folio; const folioPage = (req, res) => res.render('folio', { csrfToken: req.csrfToken() }); const getPortal = (req, res) => Portal.PortalModel.findById(req.params.id, (err, doc) => { if (err) { return res.status(400).json({ ...
const newFolio = new Folio.FolioModel({ name, title, skills, email, portfolio, portalId }); const promise = newFolio.save(); promise.then(() => res.status(200).json({ message: 'Folio successfully created :)' })); promise.catch((err) => { console.log(err); if (err.code === 11000) { return res....
{ return res.status(400).json({ error: 'All fields are required' }); }
conditional_block
Folio.js
const models = require('../models'); const Portal = models.Portal; const Folio = models.Folio; const folioPage = (req, res) => res.render('folio', { csrfToken: req.csrfToken() }); const getPortal = (req, res) => Portal.PortalModel.findById(req.params.id, (err, doc) => { if (err) { return res.status(400).json({ ...
return res.status(200).json({ folios: docs }); }); const createFolio = (req, res) => { const { name, title, skills, email, portfolio, portalId } = req.body; if (!name || !title || !skills || !email || !portfolio) { return res.status(400).json({ error: 'All fields are required' }); } const newFolio = ne...
random_line_split
create_nq.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. ...
repok.new_article() reperr.new_article() for cur_dir, cur_subdir, cur_files in os.walk(args.input): with open(args.output, 'a') as f: for cur_file in cur_files: if cur_file.endswith(".json"): cur_g = ConjunctiveGraph() cur_g = load...
reperr = Reporter(True, prefix="[create_nq.py: ERROR] ")
random_line_split
create_nq.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. ...
reperr.add_sentence("The file specified ('%s') doesn't exist." % rdf_file_path) return cur_graph def __load_graph(current_graph, file_path): errors = "" try: with open(file_path) as f: json_ld_file = json.load(f) if isinstance(json_ld_...
if os.path.isfile(rdf_file_path): try: cur_graph = __load_graph(cur_graph, rdf_file_path) except IOError: if tmp_dir is not None: current_file_path = tmp_dir + os.sep + "tmp_rdf_file_create_nq.rdf" shutil.copyfile(rdf_file_path, current_file_path) ...
identifier_body
create_nq.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. ...
(current_graph, file_path): errors = "" try: with open(file_path) as f: json_ld_file = json.load(f) if isinstance(json_ld_file, dict): json_ld_file = [json_ld_file] for json_ld_resource in json_ld_file: # Trick to force the use of a p...
__load_graph
identifier_name
create_nq.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. ...
for cur_dir, cur_subdir, cur_files in os.walk(args.input): with open(args.output, 'a') as f: for cur_file in cur_files: if cur_file.endswith(".json"): cur_g = ConjunctiveGraph() cur_g = load(cur_g, cur_dir + os.sep + cur_file, args.tmp_dir...
arg_parser = argparse.ArgumentParser("create_nq.py", description="This script create an nt file given a directory containing json-ld files.") arg_parser.add_argument("-i", "--input", dest="input", required=True, help="The directory containing the ...
conditional_block
custom.js
(function ($) { new WOW().init(); jQuery(window).load(function() { jQuery("#preloader").delay(100).fadeOut("slow"); jQuery("#load").delay(100).fadeOut("slow"); }); //jQuery to collapse the navbar on scroll // var scrollTop1=0; // var a=0; $(window).scroll(function() { // if ($(".navbar").offset...
scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); })(jQuery);
$('.page-scroll a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({
random_line_split
everyObject.d.ts
/** * Executes the provided `callback` once for each enumerable own property in the * object until it finds one where callback returns a falsy value. If such a
* * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `everyObject` will not be * visited by `callback`. If the values of existing properties are changed, the * value passed to `callback` will be the value at the time `everyObject` * vi...
* property is found, `everyObject` immediately returns false. Otherwise, it * returns true. * * The `callback` is invoked with three arguments:
random_line_split
mod.rs
/* 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/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance...
<T: Runnable + Send + 'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()> { self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } }
queue
identifier_name
mod.rs
/* 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/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance...
self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } }
-> Result<(), ()> where T: Runnable + Send + 'static; fn queue<T: Runnable + Send + 'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()> {
random_line_split
mod.rs
/* 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/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance...
}
{ self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) }
identifier_body
test_list_all_files_in_directory.py
from raptiformica.utils import list_all_files_in_directory from tests.testcase import TestCase class TestListAllFilesInDirectory(TestCase): def setUp(self): self.walk = self.set_up_patch('raptiformica.utils.walk') self.walk.return_value = [ ('/tmp/a/directory', ['dir'], ['file.txt', 'f...
ret = list_all_files_in_directory('/tmp/a/directory') expected_list = [ '/tmp/a/directory/file.txt', '/tmp/a/directory/file2.txt', '/tmp/a/directory/dir/file3.txt', '/tmp/a/directory/dir/dir2/file4.txt', '/tmp/a/directory/dir/dir2/file5.txt' ]...
identifier_body
test_list_all_files_in_directory.py
from raptiformica.utils import list_all_files_in_directory from tests.testcase import TestCase class TestListAllFilesInDirectory(TestCase): def setUp(self): self.walk = self.set_up_patch('raptiformica.utils.walk') self.walk.return_value = [ ('/tmp/a/directory', ['dir'], ['file.txt', 'f...
'/tmp/a/directory/dir/dir2/file4.txt', '/tmp/a/directory/dir/dir2/file5.txt' ] self.assertCountEqual(ret, expected_list)
'/tmp/a/directory/dir/file3.txt',
random_line_split
test_list_all_files_in_directory.py
from raptiformica.utils import list_all_files_in_directory from tests.testcase import TestCase class TestListAllFilesInDirectory(TestCase): def setUp(self): self.walk = self.set_up_patch('raptiformica.utils.walk') self.walk.return_value = [ ('/tmp/a/directory', ['dir'], ['file.txt', 'f...
(self): ret = list_all_files_in_directory('/tmp/a/directory') expected_list = [ '/tmp/a/directory/file.txt', '/tmp/a/directory/file2.txt', '/tmp/a/directory/dir/file3.txt', '/tmp/a/directory/dir/dir2/file4.txt', '/tmp/a/directory/dir/dir2/file...
test_list_all_files_in_directory_returns_all_files
identifier_name
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capac...
(&mut self, key: u32) { self.insert_elem(key, ()) } //pub(super) fn keys<'a>(&'a self) -> IterType<'a, ()> { pub(super) fn keys(&self) -> IterType<()> { self.data.iter().filter_map(|i| i.get().map(|e| e.key)) } } impl IHM<u32> { pub fn insert(&mut self, key: u32, val: u32) { ...
insert
identifier_name
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capac...
pub fn get(&self, key: u32) -> Option<u32> { let mut addr = self.hash(key); loop { /* let entry = unsafe { self.data.get_unchecked(addr) }; match entry.get() { */ match self.data[addr].get() { None => return None, ...
{ self.insert_elem(key, val) }
identifier_body
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capac...
self.size += 1; let mut addr = self.hash(key); loop { let entry = &mut self.data[addr]; //let entry = unsafe { self.data.get_unchecked_mut(addr) }; if entry.is_none() { // wasn't present, insert and continue *entry = Entry { ke...
{ self.resize(); }
conditional_block
ihm.rs
//! Custom hash map implementation for use in breadth-first search //! This application omits some of the features of a normal hash table and must be very fast, //! so it makes sense to rewrite it to take advantage of certain optimizations. //! These tables are always keyed `i32`s and grow fast enough that their capac...
fn none() -> Self { Entry { key: ENTRY_RESERVED, val: Default::default(), } } } /// Integer hash map: map keyed by integers for a very specific application. /// Has some restrictions: Can't remove entries, capacity must be a power of 2, /// input must be relatively ran...
} } #[inline]
random_line_split
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetwork...
Ok(()) } } impl Debug for BitcoinNetworkConnection { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, r"BitcoinNetworkConnection {{ , }}",) } }
*self.needed.borrow_mut() -= read; } else { *self.needed.borrow_mut() = 0; return Ok(()); }
random_line_split
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetwork...
(host: String, socket: TcpStream) -> Result<BitcoinNetworkConnection, Error> { socket.set_read_timeout(Some(Duration::from_secs(2)))?; // .expect("set_read_timeout call failed"); socket.set_write_timeout(Some(Duration::from_secs(2)))?; Ok(BitcoinNetworkConnection { h...
with_stream
identifier_name
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetwork...
if let Some(message) = self.try_parse() { return Some(message); } None } fn try_parse(&self) -> Option<Result<Message, BitcoinNetworkError>> { let available_data = self.buffer.borrow().available_data(); if available_data == 0 { return None; ...
{ let len = self.buffer.borrow().available_data(); trace!("[{}] Buffer len: {}", self.host, len); if let Some(message) = self.try_parse() { return Some(message); } match self.read() { Ok(_) => {}, Err(e) => { return Some(Err(e)...
identifier_body
bitcoin_network_connection.rs
use std::cell::RefCell; use std::fmt::{self, Debug}; use std::io::{Error, ErrorKind as IoErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::{Duration}; use circular::Buffer; use nom::{ErrorKind, Err, IResult, Needed}; use message::Message; use parser::message; pub struct BitcoinNetwork...
let mut trim = false; let mut consume = 0; let parsed = match message(&self.buffer.borrow().data(), &self.host) { IResult::Done(remaining, msg) => Some((msg, remaining.len())), IResult::Incomplete(len) => { if let Needed::Size(s) = len { ...
{ return None; }
conditional_block
views.py
import base64 import collections import hashlib from datetime import datetime, timedelta from operator import attrgetter import time import uuid from django.core.cache import cache from django.conf import settings from django.db.models import Q, signals as db_signals from django.shortcuts import get_object_or_404 from...
(*args, **kw): # Something in the blocklist changed; invalidate all responses. redis = redisutils.connections['master'] keys = redis.smembers('blocklist:keys') cache.delete_many(keys) redis.delete('blocklist:keys') flush_front_end_cache_urls.delay(['/blocklist/*']) for m in (BlocklistItem, Blo...
clear_blocklist
identifier_name
views.py
import base64 import collections import hashlib from datetime import datetime, timedelta from operator import attrgetter import time import uuid from django.core.cache import cache from django.conf import settings from django.db.models import Q, signals as db_signals from django.shortcuts import get_object_or_404 from...
def get_items(apiver, app, appver=None): # Collapse multiple blocklist items (different version ranges) into one # item and collapse each item's apps. addons = (BlocklistItem.uncached .select_related('details') .filter(Q(app__guid__isnull=True) | Q(app__guid=app)) ...
db_signals.post_save.connect(clear_blocklist, sender=m, dispatch_uid='save_%s' % m) db_signals.post_delete.connect(clear_blocklist, sender=m, dispatch_uid='delete_%s' % m)
conditional_block
views.py
import base64 import collections import hashlib from datetime import datetime, timedelta from operator import attrgetter import time import uuid from django.core.cache import cache from django.conf import settings from django.db.models import Q, signals as db_signals from django.shortcuts import get_object_or_404 from...
for m in (BlocklistItem, BlocklistPlugin, BlocklistGfx, BlocklistApp, BlocklistCA): db_signals.post_save.connect(clear_blocklist, sender=m, dispatch_uid='save_%s' % m) db_signals.post_delete.connect(clear_blocklist, sender=m, dispa...
redis = redisutils.connections['master'] keys = redis.smembers('blocklist:keys') cache.delete_many(keys) redis.delete('blocklist:keys') flush_front_end_cache_urls.delay(['/blocklist/*'])
identifier_body
views.py
import base64 import collections import hashlib from datetime import datetime, timedelta from operator import attrgetter import time import uuid from django.core.cache import cache from django.conf import settings from django.db.models import Q, signals as db_signals from django.shortcuts import get_object_or_404
import jingo import redisutils from amo.utils import sorted_groupby from amo.tasks import flush_front_end_cache_urls from versions.compare import version_int from .models import (BlocklistItem, BlocklistPlugin, BlocklistGfx, BlocklistApp, BlocklistDetail, BlocklistCA) App = collections.namedtupl...
from django.utils.cache import patch_cache_control from django.utils.encoding import smart_str
random_line_split
three-projector.d.ts
// Type definitions for three.js (Projector.js) // Project: https://github.com/mrdoob/three.js/blob/master/examples/js/renderers/Projector.js // Definitions by: Satoru Kimura <https://github.com/gyohk> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export class RenderableObject { constructor(); id: number; object: Object; z: number; } export class RenderableFace { constructor(); id: number; v1: RenderableVertex; v2: RenderableVertex; v3: RenderableVertex; normalModel: V...
/// <reference path="./three.d.ts" /> declare namespace THREE { // Renderers / Renderables /////////////////////////////////////////////////////////////////////
random_line_split
three-projector.d.ts
// Type definitions for three.js (Projector.js) // Project: https://github.com/mrdoob/three.js/blob/master/examples/js/renderers/Projector.js // Definitions by: Satoru Kimura <https://github.com/gyohk> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="./three.d.ts" /> declare nam...
{ constructor(); id: number; v1: RenderableVertex; v2: RenderableVertex; v3: RenderableVertex; normalModel: Vector3; vertexNormalsModel: Vector3[]; vertexNormalsLength: number; color: Color; material: Material; uvs: Vector2[][]; ...
RenderableFace
identifier_name
api.py
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # Copyright (C) 2020 UCLouvain # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program ...
return response.hits.hits[0]._source class Organisation(IlsRecord): """Organisation class.""" minter = organisation_id_minter fetcher = organisation_id_fetcher provider = OrganisationProvider model_cls = OrganisationMetadata @classmethod def get_all(cls): """Get all orga...
raise NotFoundError( f'Organisation viewcode {viewcode}: Result not found.')
conditional_block
api.py
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # Copyright (C) 2020 UCLouvain # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program ...
(self): """Get organisation pid .""" return self.pid def online_circulation_category(self): """Get the default circulation category for online resources.""" results = ItemTypesSearch().filter( 'term', organisation__pid=self.pid).filter( 'term', type='onli...
organisation_pid
identifier_name
api.py
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # Copyright (C) 2020 UCLouvain # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program ...
@classmethod def all_code(cls): """Get all code.""" return [org.get('code') for org in cls.get_all()] @classmethod def get_record_by_viewcode(cls, viewcode): """Get record by view code.""" result = OrganisationsSearch().filter( 'term', code=view...
"""Get all organisations.""" return sorted([ Organisation.get_record_by_id(_id) for _id in Organisation.get_all_ids() ], key=lambda org: org.get('name'))
identifier_body
api.py
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # Copyright (C) 2020 UCLouvain # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, version 3 of the License. # # This program ...
pids = self.get_vendor_pids() for pid in pids: yield Vendor.get_record_by_pid(pid) def get_links_to_me(self, get_pids=False): """Record links. :param get_pids: if True list of linked pids if False count of linked records """ from...
def get_vendors(self): """Get all vendors related to the organisation."""
random_line_split
glyph.rs
glyph, but this does not account for them. fn char_is_space(&self) -> bool { self.has_flag(FLAG_CHAR_IS_SPACE) } fn char_is_tab(&self) -> bool { !self.is_simple() && self.has_flag(FLAG_CHAR_IS_TAB) } fn char_is_newline(&self) -> bool { !self.is_simple() && self.has_flag(FL...
GlyphInfo
identifier_name
glyph.rs
} fn ge(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset >= other.entry_offset } fn gt(&self, other: &DetailedGlyphRecord) -> bool { self.entry_offset > other.entry_offset } } // Manages the lookup table for detailed glyphs. Sorting is deferred // until a lookup is actually performed; thi...
{ fn glyph_is_compressible(data: &GlyphData) -> bool { is_simple_glyph_id(data.index) && is_simple_advance(data.advance) && data.offset == geometry::zero_point() && data.cluster_start // others are stored in detail buffer } assert!(da...
identifier_body
glyph.rs
.to_u32().unwrap(); (unsignedAu & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsignedAu } type DetailedGlyphCount = u16; // Getters and setters for GlyphEntry. Setter methods are functional, // because GlyphEntry is immutable and only a u32 in size. impl GlyphEntry { // getter methods #[inline(always...
random_line_split
pdf.py
Saves the current graphic's context state. Always pair this with a `restore_state()` """ self.gc.saveState() def restore_state(self): """ Restores the previous graphics state. """ self.gc.restoreState() # ---------------------------------------------------...
def rect(self, *args): """ Adds a rectangle as a new subpath. Can be called in two ways: rect(x, y, w, h) rect( (x, y, w, h) ) """ if self.current_pdf_path is None: self.begin_path() if len(args) == 1: args = args[0] se...
self.current_pdf_path.moveTo(start[0], start[1]) self.current_pdf_path.lineTo(end[0], end[1]) self.current_point = (end[0], end[1])
conditional_block
pdf.py
_path_empty not implemented yet on PDF" raise NotImplementedError(msg) def get_path_current_point(self): """ Returns the current point from the graphics context. Note: This should be a tuple or array. """ return self.current_point def get_path_bounding_box(self): ...
eof_fill_path
identifier_name
pdf.py
Saves the current graphic's context state. Always pair this with a `restore_state()` """ self.gc.saveState() def restore_state(self): """ Restores the previous graphics state. """ self.gc.restoreState() # ---------------------------------------------------...
def curve_to(self, cp1x, cp1y, cp2x, cp2y, x, y): """ """ if self.current_pdf_path is None: self.begin_path() self.current_pdf_path.curveTo(cp1x, cp1y, cp2x, cp2y, x, y) self.current_point = (x, y) def quad_curve_to(self, cpx, cpy, x, y): """ ...
""" Closes the path of the current subpath. """ self.current_pdf_path.close()
identifier_body
pdf.py
""" self.gc.setLineWidth(width) def set_line_join(self, style): """ Sets style for joining lines in a drawing. style : join_style The line joining style. The available styles are JOIN_ROUND, JOIN_BEVEL, JOIN_MITER. """ try: ...
random_line_split
setupDevtools.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @provides...
}); } } module.exports = { register, };
{ // Don't steal the DevTools from currently active app. // Note: if you add any AppState subscriptions to this file, // you will also need to guard against `AppState.isAvailable`, // or the code will throw for bundles that don't have it. const isAppActive = () => AppState.currentState !== 'backgrou...
conditional_block
setupDevtools.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @provides...
// Initialize dev tools only if the native module for WebSocket is available if (WebSocket.isAvailable) { // Don't steal the DevTools from currently active app. // Note: if you add any AppState subscriptions to this file, // you will also need to guard against `AppState.isAvailable`, // or the code ...
random_line_split
mod.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
"legacy primitives do not match the input key" ); } #[test] fn test_add_with_invalid_input() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); let dummy_mac = Box::new(DummyMac { name: "".to_string(), }); // unknown prefix type let invalid_key = new_dummy_key(0, KeySt...
),
random_line_split
mod.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
if let Primitive::Mac(dummy_mac) = &entry.primitive { let mut data = vec![1, 2, 3, 4, 5]; let digest = dummy_mac.compute_mac(&data).unwrap(); data.extend_from_slice(test_mac.name.as_bytes()); if digest != data { return false; } } else { panic!("failed...
{ return false; }
conditional_block
mod.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
() { let mut ps = tink_core::primitiveset::PrimitiveSet::new(); assert!(ps.primary.is_none()); assert!(ps.entries.is_empty()); // generate test keys let keys = create_keyset(); // add all test primitives let mut macs = Vec::with_capacity(keys.len()); let mut entries = Vec::with_capacity(...
test_primitive_set_basic
identifier_name
mod.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
{ if entry.key_id != key_id || entry.status != *status || entry.prefix_type != *output_prefix_type { return false; } if let Primitive::Mac(dummy_mac) = &entry.primitive { let mut data = vec![1, 2, 3, 4, 5]; let digest = dummy_mac.compute_mac(&data).unwrap(); data.extend_f...
identifier_body
list.py
"""List iSCSI Snapshots.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers from SoftLayer import utils import click @click.command() @click.argument('iscsi-identifier') @environment.pass_env...
iscsi_identifier, 'iSCSI') iscsi = env.client['Network_Storage_Iscsi'] snapshots = iscsi.getPartnerships( mask='volumeId,partnerVolumeId,createDate,type', id=iscsi_id) snapshots = [utils.NestedDict(n) for n in snapshots] table ...
iscsi_mgr = SoftLayer.ISCSIManager(env.client) iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids,
random_line_split
list.py
"""List iSCSI Snapshots.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers from SoftLayer import utils import click @click.command() @click.argument('iscsi-identifier') @environment.pass_env...
return table
table.add_row([ snapshot['partnerVolumeId'], snapshot['createDate'], snapshot['type']['name'], snapshot['type']['description'], ])
conditional_block
list.py
"""List iSCSI Snapshots.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers from SoftLayer import utils import click @click.command() @click.argument('iscsi-identifier') @environment.pass_env...
(env, iscsi_identifier): """List iSCSI Snapshots.""" iscsi_mgr = SoftLayer.ISCSIManager(env.client) iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids, iscsi_identifier, 'iSCSI') iscsi = env.client['Network_Storage_Iscsi'] snapsho...
cli
identifier_name
list.py
"""List iSCSI Snapshots.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers from SoftLayer import utils import click @click.command() @click.argument('iscsi-identifier') @environment.pass_env...
return table
"""List iSCSI Snapshots.""" iscsi_mgr = SoftLayer.ISCSIManager(env.client) iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids, iscsi_identifier, 'iSCSI') iscsi = env.client['Network_Storage_Iscsi'] snapshots = iscsi.getPartnerships( ...
identifier_body
index.js
/** * Dependencies */ var NOOT = require('../../')('namespace', 'error', 'http'); var _ = require('lodash'); var mongoose; var ValidationError; var CastError; var defineMongoose = function() { if (!mongoose) { mongoose = require('mongoose'); ValidationError = mongoose.Error.ValidationError; CastError...
*/ module.exports = Errors;
* @exports
random_line_split
index.js
/** * Dependencies */ var NOOT = require('../../')('namespace', 'error', 'http'); var _ = require('lodash'); var mongoose; var ValidationError; var CastError; var defineMongoose = function() { if (!mongoose) { mongoose = require('mongoose'); ValidationError = mongoose.Error.ValidationError; CastError...
() { return ErrorClass.apply(this, args); } Wrapper.prototype = ErrorClass.prototype; return new Wrapper(); })(); } }); /** * @exports */ module.exports = Errors;
Wrapper
identifier_name
index.js
/** * Dependencies */ var NOOT = require('../../')('namespace', 'error', 'http'); var _ = require('lodash'); var mongoose; var ValidationError; var CastError; var defineMongoose = function() { if (!mongoose) { mongoose = require('mongoose'); ValidationError = mongoose.Error.ValidationError; CastError...
Wrapper.prototype = ErrorClass.prototype; return new Wrapper(); })(); } }); /** * @exports */ module.exports = Errors;
{ return ErrorClass.apply(this, args); }
identifier_body
toxicity.js
const Command = require('../../structures/Command'); const request = require('node-superfetch'); const { GOOGLE_KEY } = process.env; module.exports = class ToxicityCommand extends Command { constructor(client) { super(client, { name: 'toxicity', aliases: ['perspective', 'comment-toxicity'], group: 'analyze...
};
{ try { const { body } = await request .post('https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze') .query({ key: GOOGLE_KEY }) .send({ comment: { text }, languages: ['en'], requestedAttributes: { TOXICITY: {} } }); const toxicity = Math.round(body.attributeScores.TOX...
identifier_body
toxicity.js
const Command = require('../../structures/Command'); const request = require('node-superfetch'); const { GOOGLE_KEY } = process.env; module.exports = class ToxicityCommand extends Command { constructor(client) { super(client, { name: 'toxicity', aliases: ['perspective', 'comment-toxicity'], group: 'analyze...
], args: [ { key: 'text', prompt: 'What text do you want to test the toxicity of?', type: 'string' } ] }); } async run(msg, { text }) { try { const { body } = await request .post('https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze') .query({ key: GOOGLE_KE...
name: 'Perspective API', url: 'https://www.perspectiveapi.com/#/' }
random_line_split
toxicity.js
const Command = require('../../structures/Command'); const request = require('node-superfetch'); const { GOOGLE_KEY } = process.env; module.exports = class ToxicityCommand extends Command {
(client) { super(client, { name: 'toxicity', aliases: ['perspective', 'comment-toxicity'], group: 'analyze', memberName: 'toxicity', description: 'Determines the toxicity of text.', credit: [ { name: 'Perspective API', url: 'https://www.perspectiveapi.com/#/' } ], args: [ ...
constructor
identifier_name
accordion.ts
/* global fetch */ import * as $ from "jquery"; const cssClasses = { titleSymbolClass: "material-icons titleSymbol", titleSymbolActive: "expand_more", titleSymbolInactive: "expand_less", title: "mdl-button mdl-js-button mdl-button--raised mdl-list__item", titleHover: "mdl-button--colored", titleToggleClass...
(text) { return this.each(function() { const current = $(this).text(); const replacement = text.replace(current, ""); $(this).text(replacement); }); }, }); const doUptutorialClick = function() { $("#uptutorial").val(""); $("#uptutorial").click(); }; const scrollDownUntilTutorialVisible...
toggleText
identifier_name
accordion.ts
/* global fetch */ import * as $ from "jquery"; const cssClasses = { titleSymbolClass: "material-icons titleSymbol", titleSymbolActive: "expand_more", titleSymbolInactive: "expand_less", title: "mdl-button mdl-js-button mdl-button--raised mdl-list__item", titleHover: "mdl-button--colored", titleToggleClass...
, }); const doUptutorialClick = function() { $("#uptutorial").val(""); $("#uptutorial").click(); }; const scrollDownUntilTutorialVisible = function() { const y = $(this).position().top; const height = parseInt($("#home").css("height"), 10); const totalHeight = parseInt($(this).css("height"), 10) + 50; if ...
{ return this.each(function() { const current = $(this).text(); const replacement = text.replace(current, ""); $(this).text(replacement); }); }
identifier_body
accordion.ts
/* global fetch */ import * as $ from "jquery"; const cssClasses = { titleSymbolClass: "material-icons titleSymbol", titleSymbolActive: "expand_more", titleSymbolInactive: "expand_less", title: "mdl-button mdl-js-button mdl-button--raised mdl-list__item", titleHover: "mdl-button--colored", titleToggleClass...
const title = $("#loadTutorialMenu"); const instructions = $("#loadTutorialInstructions"); (expandButton as any).toggleText(cssClasses.titleSymbolInactive + " " + cssClasses.titleSymbolActive); title.toggleClass( cssClasses.titleToggleClass); instructions.slideToggle(scrollDownUntilT...
const expandButton = $("<i>"); expandButton.addClass(cssClasses.titleSymbolClass); expandButton.text(cssClasses.titleSymbolActive); expandButton.click(function() {
random_line_split
accordion.ts
/* global fetch */ import * as $ from "jquery"; const cssClasses = { titleSymbolClass: "material-icons titleSymbol", titleSymbolActive: "expand_more", titleSymbolInactive: "expand_less", title: "mdl-button mdl-js-button mdl-button--raised mdl-list__item", titleHover: "mdl-button--colored", titleToggleClass...
}; const appendTutorialToAccordion = function(tmptitle, lessons, index) { const title = tmptitle.clone(); title.wrapInner("<a href='#' class='" + cssClasses.titleHref + "' tutorialid=" + index + "/>") .addClass(cssClasses.title) .prepend( '<i class="' + cssClasses.titleSymbolClass ...
{ const scroll = totalHeight - height + y; $("#home").animate({ scrollTop: ($("#home").scrollTop() + scroll), }, 400); }
conditional_block
index.js
import { Map, List, fromJS } from 'immutable'; import { memoize, compose, partialRight, call } from 'ramda'; import { Promise } from 'es6-promise'; function createHookStructure() { return fromJS({hooks: Map() }); } function hookAtom() { return Map({ 'before': List(), 'after': List(), }); } function Ho...
() { return hookAPI.getHookStructure().set('hooks', Map()); } function addHook(name, position, hook) { return hookAPI.getHookStructure().setIn( ['hooks', name, position], hookAPI.getHookStructure().getIn(['hooks', name, position]).push(hook) ); } function resolveHook(name, pos) { c...
clearHooks
identifier_name
index.js
import { Map, List, fromJS } from 'immutable'; import { memoize, compose, partialRight, call } from 'ramda'; import { Promise } from 'es6-promise'; function createHookStructure() { return fromJS({hooks: Map() }); } function hookAtom()
function Hook() { const hookAPI = {}; hookAPI.getHookStructure = memoize(()=> createHookStructure()); function updateHookStructure(newStructure) { hookAPI.getHookStructure = memoize(()=> newStructure); return newStructure; } function setHookType(hookName) { return hookAPI.getHookStructure()....
{ return Map({ 'before': List(), 'after': List(), }); }
identifier_body
index.js
import { Map, List, fromJS } from 'immutable'; import { memoize, compose, partialRight, call } from 'ramda'; import { Promise } from 'es6-promise'; function createHookStructure() { return fromJS({hooks: Map() }); } function hookAtom() { return Map({ 'before': List(), 'after': List(), }); } function Hoo...
} function wrapHandler(name, handler) { return function(...args) { return call(resolveHook(name, 'before'), args) .then(function(beforeSeq) { return Promise.resolve(beforeSeq).then(handler).then(resolveHook(name, 'after')); }); }; } hookAPI.addHookType = compose( up...
return initialValue.then(()=> hook.apply(this, args)); }, Promise.resolve(null) ); };
random_line_split
sanity_checks.rs
/* 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/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this?...
() { let mut saw_before = false; let mut saw_after = false; macro_rules! pseudo_element { (":before", $atom:expr, false) => { saw_before = true; }; (":after", $atom:expr, false) => { saw_after = true; }; ($pseudo_str_with_colon:expr, $atom:exp...
assert_basic_pseudo_elements
identifier_name
sanity_checks.rs
/* 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/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this?...
assert!(saw_after); }
random_line_split
sanity_checks.rs
/* 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/. */ //! Different static asserts that ensure the build does what it's expected to. //! //! TODO: maybe cfg(test) this?...
}
{ let mut saw_before = false; let mut saw_after = false; macro_rules! pseudo_element { (":before", $atom:expr, false) => { saw_before = true; }; (":after", $atom:expr, false) => { saw_after = true; }; ($pseudo_str_with_colon:expr, $atom:expr, ...
identifier_body
graph.py
_edges[e1] if e2 not in lsucs: lsucs.append(e2) lpreds = self.reverse_catch_edges[e2] if e1 not in lpreds: lpreds.append(e1) def remove_node(self, node): preds = self.reverse_edges.get(node, []) for pred in preds: self.edges[pred].remove(n...
(self): ''' Split IfNodes in two nodes, the first node is the header node, the second one is only composed of the jump condition. ''' node_map = {n: n for n in self.nodes} to_update = set() for node in self.nodes[:]: if node.type.is_cond: ...
split_if_nodes
identifier_name
graph.py
.catch_edges[e1] if e2 not in lsucs: lsucs.append(e2) lpreds = self.reverse_catch_edges[e2] if e1 not in lpreds: lpreds.append(e1) def remove_node(self, node): preds = self.reverse_edges.get(node, []) for pred in preds: self.edges[pred].re...
def get_ins_from_loc(self, loc): return self.loc_to_ins.get(loc) def get_node_from_loc(self, loc): for (start, end), node in self.loc_to_node.iteritems(): if start <= loc <= end: return node def remove_ins(self, loc): ins = self.get_ins_from_loc(loc) ...
self.loc_to_ins = {} self.loc_to_node = {} num = 0 for node in self.rpo: start_node = num num = node.number_ins(num) end_node = num - 1 self.loc_to_ins.update(node.get_loc_with_ins()) self.loc_to_node[(start_node, end_node)] = node
identifier_body
graph.py
.catch_edges[e1] if e2 not in lsucs: lsucs.append(e2) lpreds = self.reverse_catch_edges[e2] if e1 not in lpreds: lpreds.append(e1) def remove_node(self, node): preds = self.reverse_edges.get(node, []) for pred in preds: self.edges[pred].re...
ancestor[v] = ancestor[u] def _eval(v): if ancestor[v]: _compress(v) return label[v] return v def _link(v, w): ancestor[w] = v parent, ancestor, vertex = {}, {}, {} label, dom = {}, {} pred, bucket = defaultdict(set), defaultdict(set) ...
if semi[label[u]] < semi[label[v]]: label[v] = label[u]
random_line_split
graph.py
for node in self.nodes[:]: if node.type.is_cond: if len(node.get_ins()) > 1: pre_ins = node.get_ins()[:-1] last_ins = node.get_ins()[-1] pre_node = StatementBlock('%s-pre' % node.name, pre_ins) cond_node ...
node = build_node_from_block(block, vmap, gen_ret) block_to_node[block] = node
conditional_block
thermo.py
import scipy.integrate as intg import numpy as np #Physical Constants #Everything is in MKS units #Planck constant [J/s] h = 6.6261e-34 #Boltzmann constant [J/K] kB = 1.3806e-23 #Speed of light [m/s] c = 299792458.0 #Pi PI = 3.14159265 #Vacuum Permitivity eps0 = 8.85e-12 #Resistivity of the mirror rho=2.417e-8 GHz = ...
else: return bbPower(T1, 1.0, f1, f2)/bbPower(T2, 1.0, f1, f2) def getLambdaOptCoeff(chi): geom = (1 / np.cos(chi) - np.cos(chi)) return - 2 * geom * np.sqrt(4 * PI * eps0 * rho ) def getLambdaOpt(nu, chi): geom = (1 / np.cos(chi) - np.cos(chi)) return - 2 * geom * np.sqrt(4 * P...
return 0
conditional_block
thermo.py
import scipy.integrate as intg import numpy as np #Physical Constants #Everything is in MKS units #Planck constant [J/s] h = 6.6261e-34 #Boltzmann constant [J/K] kB = 1.3806e-23 #Speed of light [m/s] c = 299792458.0 #Pi PI = 3.14159265 #Vacuum Permitivity eps0 = 8.85e-12 #Resistivity of the mirror rho=2.417e-8
#Calculates total black body power for a given temp and emis. def bbSpec(freq,temp,emis): occ = 1.0/(np.exp(h*freq/(temp*kB)) - 1) if callable(emis): e = emis(freq) else: e = emis return (2*e*h*freq**3)/(c**2)* occ #Calculates total black body power for a given temp and emis multipli...
GHz = 10 ** 9 Tcmb = 2.725
random_line_split