file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
upload_clinic_codes.py
from csv import DictReader from django.core.management.base import BaseCommand from registrations.models import ClinicCode class Command(BaseCommand): help = ( "This command takes in a CSV with the columns: uid, code, facility, province," "and location, and creates/updates the cliniccodes in the...
else: updated += 1 self.success(f"Updated {updated} and created {created} clinic codes") def log(self, level, msg): self.stdout.write(level(msg)) def success(self, msg): self.log(self.style.SUCCESS, msg)
created += 1
conditional_block
load.rs
/*! # Reading and loading hyphenation dictionaries To hyphenate words in a given language, it is first necessary to load the relevant hyphenation dictionary into memory. This module offers convenience methods for common retrieval patterns, courtesy of the [`Load`] trait. ``` use hyphenation::Load; use hyphenation::{S...
/// Deserialize a dictionary from the provided reader, verifying that it /// belongs to the expected language. fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self> where R : io::Read; /// Deserialize a dictionary from the provided reader. fn any_from_reader<R>(reader : &mut R) ->...
let file = File::open(path) ?; Self::from_reader(lang, &mut io::BufReader::new(file)) }
identifier_body
load.rs
/*! # Reading and loading hyphenation dictionaries To hyphenate words in a given language, it is first necessary to load the relevant hyphenation dictionary into memory. This module offers convenience methods for common retrieval patterns, courtesy of the [`Load`] trait. ``` use hyphenation::Load; use hyphenation::{S...
a>(code : &str, suffix : &str) -> Result<&'a [u8]> { let name = format!("{}.{}.bincode", code, suffix); let res : Option<ResourceId> = ResourceId::from_name(&name); match res { Some(data) => Ok(data.load()), None => Err(Error::Resource) } } pub type Result<T> = result::Result<T, Error>...
trieve_resource<'
identifier_name
load.rs
/*! # Reading and loading hyphenation dictionaries To hyphenate words in a given language, it is first necessary to load the relevant hyphenation dictionary into memory. This module offers convenience methods for common retrieval patterns, courtesy of the [`Load`] trait. ``` use hyphenation::Load; use hyphenation::{S...
where R : io::Read { let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader) ?; let (found, expected) = (dict.language(), lang); if found != expected { Err(Error::LanguageMismatch { expected, found }) } els...
($dict:ty, $suffix:expr) => { impl Load for $dict { fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self>
random_line_split
ranking-export.component.ts
import { Component, OnInit } from "@angular/core"; import { faDownload } from "@fortawesome/free-solid-svg-icons/faDownload"; import { Store } from "@ngrx/store"; import { flatMapping } from "../../../@core/lib/collections"; import { ALL_DISCIPLINES } from "../../../dto/athletics"; import { GenderDto, genderDtoOfValue...
@Component({ selector: "app-ranking-export", templateUrl: "./ranking-export.component.html", }) export class RankingExportComponent implements OnInit { readonly faDownload = faDownload; readonly isParticipationOpen$ = this.store.select(selectIsParticipationOpen); readonly t...
random_line_split
ranking-export.component.ts
import { Component, OnInit } from "@angular/core"; import { faDownload } from "@fortawesome/free-solid-svg-icons/faDownload"; import { Store } from "@ngrx/store"; import { flatMapping } from "../../../@core/lib/collections"; import { ALL_DISCIPLINES } from "../../../dto/athletics"; import { GenderDto, genderDtoOfValue...
downloadTriathlonRanking(): void { const genders = createGenderListOfTree(this.triathlonTree); this.store.dispatch(downloadTriathlonRankingAction({genders})); } downloadUbsCupRanking(): void { const genders = createGenderListOfTree(this.ubsCupTree); this.store.dispatch(downloadUbsCupRankingActi...
{ const genders = createGenderListOfTree(this.totalTree); this.store.dispatch(downloadTotalRankingAction({genders})); }
identifier_body
ranking-export.component.ts
import { Component, OnInit } from "@angular/core"; import { faDownload } from "@fortawesome/free-solid-svg-icons/faDownload"; import { Store } from "@ngrx/store"; import { flatMapping } from "../../../@core/lib/collections"; import { ALL_DISCIPLINES } from "../../../dto/athletics"; import { GenderDto, genderDtoOfValue...
(): void { const disciplines = this.disciplinesTree.checkedNodes .map(disciplineNode => disciplineNode.checkedNodes.map<DisciplineRanking>(genderNode => ( { discipline: disciplineNode.value, gender: genderDtoOfValue(genderNode.value), ...
downloadDisciplineRanking
identifier_name
nuxt.config.js
module.exports = { head: { title: 'Encounter Tracker', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, { hid: 'description', name: 'description', content: 'Fan-Made Dungeons and Dragons 4th edition Encounter Tracker' } ], link: [ {...
// }) // } // } } }
// loader: 'eslint-loader', // exclude: /(node_modules)/
random_line_split
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::{ContentType, Status}; fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T) where T: Into<Option<&'static str>> { let client = Client::new(rocket()).unwrap(); let query = format!("username={}&password={}&age={}", user, ...
#[test] fn test_invalid_user() { test_login("-1", "password", "30", Status::Ok, "Unrecognized user"); test_login("Mike", "password", "30", Status::Ok, "Unrecognized user"); } #[test] fn test_invalid_password() { test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!"); test_login("Sergi...
{ test_login("Sergio", "password", "30", Status::SeeOther, None); }
identifier_body
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::{ContentType, Status}; fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T) where T: Into<Option<&'static str>> { let client = Client::new(rocket()).unwrap(); let query = format!("username={}&password={}&age={}", user, ...
} #[test] fn test_good_login() { test_login("Sergio", "password", "30", Status::SeeOther, None); } #[test] fn test_invalid_user() { test_login("-1", "password", "30", Status::Ok, "Unrecognized user"); test_login("Mike", "password", "30", Status::Ok, "Unrecognized user"); } #[test] fn test_invalid_passwo...
{ let body_str = response.body_string(); assert!(body_str.map_or(false, |s| s.contains(expected_str))); }
conditional_block
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::{ContentType, Status}; fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T) where T: Into<Option<&'static str>> { let client = Client::new(rocket()).unwrap(); let query = format!("username={}&password={}&age={}", user, ...
() { check_bad_form("&", Status::BadRequest); check_bad_form("=", Status::BadRequest); check_bad_form("&&&===&", Status::BadRequest); } #[test] fn test_bad_form_missing_fields() { let bad_inputs: [&str; 6] = [ "username=Sergio", "password=pass", "age=30", "username=Sergi...
test_bad_form_abnromal_inputs
identifier_name
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::{ContentType, Status}; fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T) where T: Into<Option<&'static str>> { let client = Client::new(rocket()).unwrap(); let query = format!("username={}&password={}&age={}", user, ...
#[test] fn test_bad_form_abnromal_inputs() { check_bad_form("&", Status::BadRequest); check_bad_form("=", Status::BadRequest); check_bad_form("&&&===&", Status::BadRequest); } #[test] fn test_bad_form_missing_fields() { let bad_inputs: [&str; 6] = [ "username=Sergio", "password=pass", ...
assert_eq!(response.status(), status); }
random_line_split
component.js
import type { Config } from '../src/core/config' import type VNode from '../src/core/vdom/vnode' import type Watcher from '../src/core/observer/watcher' declare interface Component { // constructor information static cid: number; static options: Object; // extend static extend: (options: Object) => Function;...
_uid: number; _name: string; // this only exists in dev mode _isVue: true; _self: Component; _renderProxy: Component; _renderContext: ?Component; _watcher: Watcher; _watchers: Array<Watcher>; _computedWatchers: { [key: string]: Watcher }; _data: Object; _props: Object; _events: Object; _inacti...
$createElement: (tag?: string | Component, data?: Object, children?: VNodeChildren) => VNode; // private properties
random_line_split
firestore.spec.ts
import { expect } from 'chai'; import { firestore, initializeApp } from 'firebase-admin'; import fft = require('../../../src/index'); describe('providers/firestore', () => { before(() => { initializeApp(); }); it('clears database with clearFirestoreData', async () => { const test = fft({ projectId: 'not...
.get(), ]); expect(docs[0].exists).to.be.false; expect(docs[1].exists).to.be.false; }); });
.doc('doc1') .collection('test') .doc('doc2')
random_line_split
moviescanner.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # === This file is part of RateItSeven === # # Copyright 2015, Paolo de Vathaire <paolo.devathaire@gmail.com> # # RateItSeven 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...
(self): return self.list_videos_in_types(["movie"]) def list_episodes(self): return self.list_videos_in_types(["episode"]) def list_videos_in_types(self, video_types): file_scanner = FileScanner(self.dir_paths) for abs_path in file_scanner.absolute_file_paths(): gue...
list_movies
identifier_name
moviescanner.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # === This file is part of RateItSeven === # # Copyright 2015, Paolo de Vathaire <paolo.devathaire@gmail.com> # # RateItSeven 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...
yield guess
conditional_block
moviescanner.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # === This file is part of RateItSeven === # # Copyright 2015, Paolo de Vathaire <paolo.devathaire@gmail.com> # # RateItSeven 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...
file_scanner = FileScanner(self.dir_paths) for abs_path in file_scanner.absolute_file_paths(): guess = MovieGuess(guessit.guessit(abs_path), abs_path) if guess.is_video_in_types(video_types): yield guess
identifier_body
moviescanner.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # === This file is part of RateItSeven === # # Copyright 2015, Paolo de Vathaire <paolo.devathaire@gmail.com> # # RateItSeven 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...
from rateItSeven.scan.legacy.containers.movieguess import MovieGuess class MovieScanner(object): """ Scan file system directories for video files Find info for each file wrapped into a MovieGuess """ def __init__(self, dir_paths: list): self.dir_paths = dir_paths def list_movies(self...
random_line_split
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { error!("Not hungry!"); return false; } } } impl noisy for cat { fn speak(&self) { self.meow(); } } impl cat { fn meow(&self) { error!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y ...
{ error!("OM NOM NOM"); self.how_hungry -= 2; return true; }
conditional_block
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } fn main() { let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy; nyan.eat(); //~ ERROR does not implement any method in scope named `eat` }
{ error!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } }
identifier_body
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } fn main() { let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy; nyan.eat(); //~ ERROR does not implement any method in scope named `eat` }
cat
identifier_name
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl noisy for cat { fn speak(&self) { self.meow(); } } impl cat { fn meow(&self) { error!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hun...
return false; } } }
random_line_split
combineLatestWith.ts
import { ObservableInputTuple, OperatorFunction, Cons } from '../types'; import { combineLatest } from './combineLatest'; /** * Create an observable that combines the latest values from all passed observables and the source * into arrays and emits them. * * Returns an observable, that when subscribed to, will subs...
* // Combine the changes by adding them together * input1Changes$.pipe( * combineLatestWith(input2Changes$), * map(([e1, e2]) => (<HTMLInputElement>e1.target).value + ' - ' + (<HTMLInputElement>e2.target).value) * ) * .subscribe(x => console.log(x)); * ``` * * @param otherSources the other sources to subsc...
random_line_split
combineLatestWith.ts
import { ObservableInputTuple, OperatorFunction, Cons } from '../types'; import { combineLatest } from './combineLatest'; /** * Create an observable that combines the latest values from all passed observables and the source * into arrays and emits them. * * Returns an observable, that when subscribed to, will subs...
<T, A extends readonly unknown[]>( ...otherSources: [...ObservableInputTuple<A>] ): OperatorFunction<T, Cons<T, A>> { return combineLatest(...otherSources); }
combineLatestWith
identifier_name
combineLatestWith.ts
import { ObservableInputTuple, OperatorFunction, Cons } from '../types'; import { combineLatest } from './combineLatest'; /** * Create an observable that combines the latest values from all passed observables and the source * into arrays and emits them. * * Returns an observable, that when subscribed to, will subs...
{ return combineLatest(...otherSources); }
identifier_body
cfg-macros-notfoo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ assert!(!bar!()) }
identifier_body
cfg-macros-notfoo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert!(!bar!()) }
main
identifier_name
cfg-macros-notfoo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
macro_rules! bar { () => { true } } } #[cfg(not(foo))] #[macro_escape] mod foo { macro_rules! bar { () => { false } } } fn main() { assert!(!bar!()) }
#[cfg(foo)] #[macro_escape] mod foo {
random_line_split
atom.rs
use pyo3::prelude::*; use rayon::prelude::*; use std::collections::HashMap; use crate::becke_partitioning; use crate::bragg; use crate::bse; use crate::lebedev; use crate::radial; #[pyfunction] pub fn
( basis_set: &str, radial_precision: f64, min_num_angular_points: usize, max_num_angular_points: usize, proton_charges: Vec<i32>, center_index: usize, center_coordinates_bohr: Vec<(f64, f64, f64)>, hardness: usize, ) -> (Vec<(f64, f64, f64)>, Vec<f64>) { let (alpha_min, alpha_max) = ...
atom_grid_bse
identifier_name
atom.rs
use pyo3::prelude::*; use rayon::prelude::*; use std::collections::HashMap; use crate::becke_partitioning; use crate::bragg; use crate::bse; use crate::lebedev; use crate::radial; #[pyfunction] pub fn atom_grid_bse( basis_set: &str, radial_precision: f64, min_num_angular_points: usize, max_num_angula...
#[pyfunction] pub fn atom_grid( alpha_min: HashMap<usize, f64>, alpha_max: f64, radial_precision: f64, min_num_angular_points: usize, max_num_angular_points: usize, proton_charges: Vec<i32>, center_index: usize, center_coordinates_bohr: Vec<(f64, f64, f64)>, hardness: usize, ) -> (...
{ let (alpha_min, alpha_max) = bse::ang_min_and_max(basis_set, proton_charges[center_index] as usize); atom_grid( alpha_min, alpha_max, radial_precision, min_num_angular_points, max_num_angular_points, proton_charges, center_index, center_...
identifier_body
atom.rs
use pyo3::prelude::*; use rayon::prelude::*; use std::collections::HashMap; use crate::becke_partitioning; use crate::bragg; use crate::bse; use crate::lebedev; use crate::radial; #[pyfunction] pub fn atom_grid_bse( basis_set: &str, radial_precision: f64, min_num_angular_points: usize, max_num_angula...
(coordinates, weights) }
{ let w_partitioning: Vec<f64> = coordinates .par_iter() .map(|c| { becke_partitioning::partitioning_weight( center_index, &center_coordinates_bohr, &proton_charges, *c, ha...
conditional_block
atom.rs
use pyo3::prelude::*; use rayon::prelude::*; use std::collections::HashMap; use crate::becke_partitioning; use crate::bragg; use crate::bse; use crate::lebedev; use crate::radial; #[pyfunction] pub fn atom_grid_bse( basis_set: &str, radial_precision: f64, min_num_angular_points: usize, max_num_angula...
num_angular = lebedev::get_closest_num_angular(num_angular); if num_angular < min_num_angular_points { num_angular = min_num_angular_points; } } let (coordinates_angular, weights_angular) = lebedev::angular_grid(num_angular); let wt = 4.0 * pi...
if r < rb { num_angular = ((max_num_angular_points as f64) * r / rb) as usize;
random_line_split
application.js
import Ember from 'ember'; import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'; import config from 'ilios/config/environment'; const { inject } = Ember; const { service } = inject; export default Ember.Route.extend(ApplicationRouteMixin, { flashMessages: service(), commonAjax: ser...
() { if (!Ember.testing) { let logoutUrl = '/auth/logout'; return this.get('commonAjax').request(logoutUrl).then(response => { if(response.status === 'redirect'){ window.location.replace(response.logoutUrl); } else { this.get('flashMessages').success('general.confirmL...
sessionInvalidated
identifier_name
application.js
import Ember from 'ember'; import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'; import config from 'ilios/config/environment'; const { inject } = Ember; const { service } = inject; export default Ember.Route.extend(ApplicationRouteMixin, { flashMessages: service(), commonAjax: ser...
}); } }, beforeModel() { const i18n = this.get('i18n'); const moment = this.get('moment'); moment.setLocale(i18n.get('locale')); }, actions: { willTransition: function() { let controller = this.controllerFor('application'); controller.set('errors', []); controller.s...
{ this.get('flashMessages').success('general.confirmLogout'); window.location.replace(config.rootURL); }
conditional_block
application.js
import Ember from 'ember'; import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'; import config from 'ilios/config/environment'; const { inject } = Ember; const { service } = inject; export default Ember.Route.extend(ApplicationRouteMixin, { flashMessages: service(), commonAjax: ser...
* Leave titles as an array * All of our routes send translations for the 'titleToken' key and we do the translating in head.hbs * and in the application controller. * @param Array tokens * @return Array */ title(tokens){ return tokens; }, //Override the default session invalidator so we can do au...
i18n: service(), moment: service(), /**
random_line_split
application.js
import Ember from 'ember'; import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'; import config from 'ilios/config/environment'; const { inject } = Ember; const { service } = inject; export default Ember.Route.extend(ApplicationRouteMixin, { flashMessages: service(), commonAjax: ser...
, //Override the default session invalidator so we can do auth stuff sessionInvalidated() { if (!Ember.testing) { let logoutUrl = '/auth/logout'; return this.get('commonAjax').request(logoutUrl).then(response => { if(response.status === 'redirect'){ window.location.replace(respons...
{ return tokens; }
identifier_body
index.js
/** * App routes. */ var homepage = require('./homepage'); var user = require('./user'); var news = require('./news'); var test = require('./test'); var passport = require('passport'); function
(req, res, next) { if (req.isAuthenticated()) { return next(); } req.flash('error', '抱歉,您尚未登录。'); return res.redirect('/user/signin?redirect=' + req.path); } function ensureAdmin(req, res, next) { if (req.isAuthenticated() && req.user.isadmin) { return next(); } req.flash('error', '抱歉,您不是管理员。'); ...
ensureAuthenticated
identifier_name
index.js
/** * App routes. */ var homepage = require('./homepage'); var user = require('./user'); var news = require('./news'); var test = require('./test'); var passport = require('passport'); function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } req.flash('error', '抱歉,您尚未登录。'...
} module.exports = function(app) { app.get('/', homepage.index); app.get('/user', ensureAdmin, user.showList); app.get('/user/page/:page(\\d+)', ensureAdmin, user.showList); app.get('/user/register', user.showRegister); app.post('/user/register', user.doRegister); app.get('/user/signin', user...
return res.redirect('/user/signin?redirect=' + req.path);
random_line_split
index.js
/** * App routes. */ var homepage = require('./homepage'); var user = require('./user'); var news = require('./news'); var test = require('./test'); var passport = require('passport'); function ensureAuthenticated(req, res, next)
dmin(req, res, next) { if (req.isAuthenticated() && req.user.isadmin) { return next(); } req.flash('error', '抱歉,您不是管理员。'); return res.redirect('/user/signin?redirect=' + req.path); } function ensurePermission(req, res, next) { if (req.isAuthenticated() && req.user.isadmin) { return next(); } ...
{ if (req.isAuthenticated()) { return next(); } req.flash('error', '抱歉,您尚未登录。'); return res.redirect('/user/signin?redirect=' + req.path); } function ensureA
identifier_body
index.js
/** * App routes. */ var homepage = require('./homepage'); var user = require('./user'); var news = require('./news'); var test = require('./test'); var passport = require('passport'); function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } req.flash('error', '抱歉,您尚未登录。...
req.user.username == req.params.id) { return next(); } req.flash('error', '抱歉,您没有权限。'); return res.redirect('/user/signin?redirect=' + req.path); } module.exports = function(app) { app.get('/', homepage.index); app.get('/user', ensureAdmin, user.showList); app.get('/user/page/:pag...
nticated() &&
conditional_block
Ix.ts
import * as assert from 'assert' import * as _ from '../src/Ix' import * as O from 'fp-ts/lib/Option' import { eqString } from 'fp-ts/lib/Eq' import * as U from './util' describe('Ix', () => { it('indexReadonlyMap', () => { const index = _.indexReadonlyMap(eqString)<number>().index('a') U.deepStrictEqual(ind...
U.deepStrictEqual( index.set(3)( new Map([ ['a', 1], ['b', 2] ]) ), new Map([ ['a', 3], ['b', 2] ]) ) // should return the same reference if nothing changed const x = new Map([ ['a', 1], ['b', 2] ]) assert.st...
]) ), O.some(1) ) U.deepStrictEqual(index.set(3)(new Map([['b', 2]])), new Map([['b', 2]]))
random_line_split
hikashop.js
/** * @package HikaShop for Joomla! * @version 2.3.0 * @author hikashop.com * @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ function tableOrdering( order, dir, task ) { var form = document.adminForm; form.filter_ord...
else d.fireEvent("on"+e); }, fireAjax : function(name,params) { var t = this, ev; if( t.ajaxEvents[name] === undefined ) return false; for(var e in t.ajaxEvents[name]) { if( e != '_id' ) { ev = t.ajaxEvents[name][e]; ev(params); } } return true; }, registerAjax : fun...
{ var evt = document.createEvent('HTMLEvents'); evt.initEvent(e, false, true); d.dispatchEvent(evt); }
conditional_block
hikashop.js
/** * @package HikaShop for Joomla! * @version 2.3.0 * @author hikashop.com * @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ function tableOrdering( order, dir, task ) { var form = document.adminForm; form.filter_ord...
function hikashopCheckChangeForm(type,form) { if(!form) return true; var varform = document[form]; if(typeof hikashopFieldsJs != 'undefined' && typeof hikashopFieldsJs['reqFieldsComp'] != 'undefined' && typeof hikashopFieldsJs['reqFieldsComp'][type] != 'undefined' && hikashopFieldsJs['reqFieldsComp'][type].leng...
{ if (pressbutton) { document.adminForm.task.value=pressbutton; } if( typeof(CodeMirror) == 'function'){ for (x in CodeMirror.instances){ document.getElementById(x).value = CodeMirror.instances[x].getCode(); } } if (typeof document.adminForm.onsubmit == "function") { document.adminForm.onsubmit(); } ...
identifier_body
hikashop.js
/** * @package HikaShop for Joomla! * @version 2.3.0 * @author hikashop.com * @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ function tableOrdering( order, dir, task ) { var form = document.adminForm; form.filter_ord...
} } catch(err) {} }, submitPopup: function(id, task, form) { var d = document, t = this, el = d.getElementById('modal-'+id+'-iframe'); if(el && el.contentWindow.hikashop) { if(task === undefined) task = null; if(form === undefined) form = 'adminForm'; el.contentWindow.hikashop.submitform(ta...
w.jQuery('div.modal.in').modal('hide'); }else if(w.SqueezeBox !== undefined) { w.SqueezeBox.close();
random_line_split
hikashop.js
/** * @package HikaShop for Joomla! * @version 2.3.0 * @author hikashop.com * @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ function tableOrdering( order, dir, task ) { var form = document.adminForm; form.filter_ord...
() { this.cancelBubble = true; } var Oby = { version: 20140128, ajaxEvents : {}, hasClass : function(o,n) { if(o.className == '' ) return false; var reg = new RegExp("(^|\\s+)"+n+"(\\s+|$)"); return reg.test(o.className); }, addClass : function(o,n) { if( !this.hasClass(o,n) ) { if( o.class...
stopPropagation
identifier_name
datepicker-input.ts
import { Component, Input, ChangeDetectionStrategy, ElementRef, Renderer2, TemplateRef, forwardRef, ChangeDetectorRef, Output, EventEmitter, ViewChild, OnInit, Inject, OnChanges, SimpleChanges, OnDestroy, Optional, NgZone, LOCALE_ID } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor, NG_V...
if (changes.dropdownAlign) { this.setPositions(this.dropdownAlign); } if (changes.min || changes.max) { this.validatorChange(); } if ((changes.patternPlaceholder || changes.format || changes.delimiter) && this.patternPlaceholder) { this.inputEl.setPlaceholder(this.getPattern()....
{ this.setPattern(); if (this.value instanceof Date) { this.updateInputValue(); } }
conditional_block
datepicker-input.ts
import { Component, Input, ChangeDetectionStrategy, ElementRef, Renderer2, TemplateRef, forwardRef, ChangeDetectorRef, Output, EventEmitter, ViewChild, OnInit, Inject, OnChanges, SimpleChanges, OnDestroy, Optional, NgZone, LOCALE_ID } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor, NG_V...
isRequired: Boolean; /** * Text for button to open calendar. */ @Input() selectDateLabel = 'Select a date'; /** * Whether to use the accepted pattern as placeholder. */ @Input() @InputBoolean() patternPlaceholder: boolean; /** * Datepicker inputs */ @Input() monthNames: ReadonlyArray<...
{ this.isRequired = toBoolean(required); }
identifier_body
datepicker-input.ts
import { Component, Input, ChangeDetectionStrategy, ElementRef, Renderer2, TemplateRef, forwardRef, ChangeDetectorRef, Output, EventEmitter, ViewChild, OnInit, Inject, OnChanges, SimpleChanges, OnDestroy, Optional, NgZone, LOCALE_ID } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor, NG_V...
(): Date | string | null { return this._value; } /** * Whether to open the datepicker when a mouse user clicks on the input. */ @Input() @InputBoolean() openOnInputClick: boolean; /** * Emits when selected date changes. */ @Output() valueChange = new EventEmitter<Date | string | null>(); ...
value
identifier_name
datepicker-input.ts
import { Component, Input, ChangeDetectionStrategy, ElementRef, Renderer2, TemplateRef, forwardRef, ChangeDetectorRef, Output, EventEmitter, ViewChild, OnInit, Inject, OnChanges, SimpleChanges, OnDestroy, Optional, NgZone, LOCALE_ID } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor, NG_V...
if (this.value instanceof Date) { this.date = this.value; this.formatInputValue(); } else { this.updateInputValue(<string>value || ''); } } get value(): Date | string | null { return this._value; } /** * Whether to open the datepicker when a mouse user clicks on the input. ...
random_line_split
router_module.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {APP_BASE_HREF, HashLocationStrategy, Location, LocationStrategy, PathLocationStrategy, PlatformLocation} fro...
/** * A token for the router initializer that will be called after the app is bootstrapped. * * @experimental */ export const ROUTER_INITIALIZER = new InjectionToken<(compRef: ComponentRef<any>) => void>('Router Initializer'); export function provideRouterInitializer() { return [ { provide: ROUTE...
{ return (bootstrappedComponentRef: ComponentRef<any>) => { if (bootstrappedComponentRef !== ref.components[0]) { return; } router.resetRootComponentType(ref.componentTypes[0]); preloader.setUpPreloading(); if (opts.initialNavigation === false) { router.setUpLocationChangeListener();...
identifier_body
router_module.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {APP_BASE_HREF, HashLocationStrategy, Location, LocationStrategy, PathLocationStrategy, PlatformLocation} fro...
}; } /** * A token for the router initializer that will be called after the app is bootstrapped. * * @experimental */ export const ROUTER_INITIALIZER = new InjectionToken<(compRef: ComponentRef<any>) => void>('Router Initializer'); export function provideRouterInitializer() { return [ { provide...
{ router.initialNavigation(); }
conditional_block
router_module.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {APP_BASE_HREF, HashLocationStrategy, Location, LocationStrategy, PathLocationStrategy, PlatformLocation} fro...
( ref: ApplicationRef, urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[][], opts: ExtraOptions = {}, urlHandlingStrategy?: UrlHandlingStrategy, routeReuseStrategy?: RouteReuseStrategy) { ...
setupRouter
identifier_name
router_module.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {APP_BASE_HREF, HashLocationStrategy, Location, LocationStrategy, PathLocationStrategy, PlatformLocation} fro...
import {RouteReuseStrategy} from './route_reuse_strategy'; import {ErrorHandler, Router} from './router'; import {ROUTES} from './router_config_loader'; import {RouterOutletMap} from './router_outlet_map'; import {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader'; import {A...
import {getDOM} from './private_import_platform-browser';
random_line_split
watchdog.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info> // // 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/LICE...
fn unlock() { use self::reg::WDOG_unlock_unlock::*; reg::WDOG.unlock.set_unlock(UnlockSeq1); reg::WDOG.unlock.set_unlock(UnlockSeq2); // Enforce one cycle delay nop(); } /// Write refresh sequence to refresh watchdog pub fn refresh() { use self::reg::WDOG_refresh_refresh::*; reg::WDOG.refresh.set_refres...
use self::State::*; unlock(); match state { Disabled => { reg::WDOG.stctrlh.set_en(false); }, Enabled => { reg::WDOG.stctrlh.set_allowupdate(true); }, } }
identifier_body
watchdog.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info> // // 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/LICE...
// limitations under the License. //! Watchdog for Kinetis SIM module. use util::support::nop; #[path="../../util/ioreg.rs"] mod ioreg; /// Watchdog state #[allow(missing_docs)] #[derive(Clone, Copy)] pub enum State { Disabled, Enabled, } /// Init watchdog pub fn init(state : State) { use self::State::*; u...
// 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
random_line_split
watchdog.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info> // // 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/LICE...
{ use self::reg::WDOG_refresh_refresh::*; reg::WDOG.refresh.set_refresh(RefreshSeq1); reg::WDOG.refresh.set_refresh(RefreshSeq2); } #[allow(dead_code)] mod reg { use volatile_cell::VolatileCell; use core::ops::Drop; ioregs!(WDOG = { /// Status and Control Register High 0x0 => reg16 stctrlh { ...
fresh()
identifier_name
BuiltInCommands.ts
import {Job} from "./Job"; import {existsSync, statSync} from "fs"; import {homeDirectory, pluralize, resolveDirectory, resolveFile, mapObject} from "../utils/Common"; import {readFileSync} from "fs"; import {EOL} from "os"; import {Session} from "./Session"; import {OrderedSet} from "../utils/OrderedSet"; import {pars...
else { throw `Don't know what to do with ${args.length} arguments.`; } }, unalias: (job: Job, args: string[]): void => { if (args.length === 1) { const name = args[0]; if (job.session.aliases.has(name)) { job.session.aliases.remove(args[0]); ...
{ const parsed = parseAlias(args[0]); job.session.aliases.add(parsed.name, parsed.value); }
conditional_block
BuiltInCommands.ts
import {Job} from "./Job"; import {existsSync, statSync} from "fs"; import {homeDirectory, pluralize, resolveDirectory, resolveFile, mapObject} from "../utils/Common"; import {readFileSync} from "fs"; import {EOL} from "os"; import {Session} from "./Session"; import {OrderedSet} from "../utils/OrderedSet"; import {pars...
(alias: string, historicalDirectories: OrderedSet<string>): string { if (alias === "-") { alias = "-1"; } const index = historicalDirectories.size + parseInt(alias, 10); if (index < 0) { throw new Error(`Error: you only have ${historicalDirectories.size} ${pluralize("directory", histori...
expandHistoricalDirectory
identifier_name
BuiltInCommands.ts
import {Job} from "./Job"; import {existsSync, statSync} from "fs"; import {homeDirectory, pluralize, resolveDirectory, resolveFile, mapObject} from "../utils/Common"; import {readFileSync} from "fs"; import {EOL} from "os"; import {Session} from "./Session"; import {OrderedSet} from "../utils/OrderedSet"; import {pars...
static executor(command: string): (i: Job, args: string[]) => void { return executors[command]; } static isBuiltIn(command: string): boolean { return this.allCommandNames.includes(command); } } export function expandHistoricalDirectory(alias: string, historicalDirectories: OrderedSet<...
} // A class representing built in commands export class Command { static allCommandNames = Object.keys(executors);
random_line_split
BuiltInCommands.ts
import {Job} from "./Job"; import {existsSync, statSync} from "fs"; import {homeDirectory, pluralize, resolveDirectory, resolveFile, mapObject} from "../utils/Common"; import {readFileSync} from "fs"; import {EOL} from "os"; import {Session} from "./Session"; import {OrderedSet} from "../utils/OrderedSet"; import {pars...
export function isHistoricalDirectory(directory: string): boolean { return /^-\d*$/.test(directory); }
{ if (alias === "-") { alias = "-1"; } const index = historicalDirectories.size + parseInt(alias, 10); if (index < 0) { throw new Error(`Error: you only have ${historicalDirectories.size} ${pluralize("directory", historicalDirectories.size)} in the stack.`); } else { const d...
identifier_body
util.format.js
// I used to use `util.format()` which was massive, then I switched to // format-util, although when using rollup I discovered that the index.js // just exported `require('util').format`, and then had the below contents // in another file. at any rate all I want is this function: function format(fmt) { fmt = String(...
var arg = args.shift(); switch(flag) { case 's': arg = '' + arg; break; case 'd': arg = Number(arg); break; case 'j': arg = JSON.stringify(arg); break; } if(!escaped) { return arg; } args.unsh...
args = args[0]; fmt = fmt.replace(re, function(match, escaped, ptn, flag) {
random_line_split
util.format.js
// I used to use `util.format()` which was massive, then I switched to // format-util, although when using rollup I discovered that the index.js // just exported `require('util').format`, and then had the below contents // in another file. at any rate all I want is this function: function
(fmt) { fmt = String(fmt); // this is closer to util.format() behavior var re = /(%?)(%([jds]))/g , args = Array.prototype.slice.call(arguments, 1); if(args.length) { if(Array.isArray(args[0])) args = args[0]; fmt = fmt.replace(re, function(match, escaped, ptn, flag) { var arg = args.shi...
format
identifier_name
util.format.js
// I used to use `util.format()` which was massive, then I switched to // format-util, although when using rollup I discovered that the index.js // just exported `require('util').format`, and then had the below contents // in another file. at any rate all I want is this function: function format(fmt)
export default format;
{ fmt = String(fmt); // this is closer to util.format() behavior var re = /(%?)(%([jds]))/g , args = Array.prototype.slice.call(arguments, 1); if(args.length) { if(Array.isArray(args[0])) args = args[0]; fmt = fmt.replace(re, function(match, escaped, ptn, flag) { var arg = args.shift(); ...
identifier_body
Base.tpl.py
{% block meta %} name: Base description: SMACH base template. language: Python framework: SMACH type: Base tags: [core] includes: [] extends: [] variables: - - manifest: description: ROS manifest name. type: str - - node_name: description: ROS node name for the state machine. type: str - outcome...
{% set defined_headers = [] %} {% set local_vars = [] %} {% block base_header %} #!/usr/bin/env python {{ base_header }} {% endblock base_header %} {% block imports %} {{ import_module(defined_headers, 'smach') }} {{ imports }} {% endblock imports %} {% block defs %} {{ defs }} {% endblock defs %} {% block class_d...
{% endblock meta %} {% from "Utils.tpl.py" import import_module, render_outcomes, render_userdata %}
random_line_split
index.js
/** * @license Apache-2.0 * * Copyright (c) 2022 The Stdlib 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 a...
* // returns Infinity * * v = csch( 2.0 ); * // returns ~0.2757 * * v = csch( -2.0 ); * // returns ~-0.2757 * * v = csch( NaN ); * // returns NaN */ // MODULES // var main = require( './main.js' ); // EXPORTS // module.exports = main;
* * var v = csch( 0.0 );
random_line_split
grid.js
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt frappe.ui.form.Grid = Class.extend({ init: function(opts) { $.extend(this, opts); this.fieldinfo = {}; this.doctype = this.df.options; this.template = null; if(this.frm.meta.__form_grid_templates && t...
this.layout.refresh(this.doc); // copy get_query to fields $.each(this.grid.fieldinfo || {}, function(fieldname, fi) { $.extend(me.fields_dict[fieldname], fi); }) this.toggle_add_delete_button_display(this.wrapper.find(".panel:first")); this.grid.open_grid_row = this; this.frm.script_manager.trigge...
this.fields_dict = this.layout.fields_dict;
random_line_split
react-redux-toastr.d.ts
// Type definitions for react-redux-toastr 3.7.0 // Project: https://github.com/diegoddox/react-redux-toastr // Definitions by: Aleksandar Ivanov <https://github.com/Smiche> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped ///<reference path="../react/react.d.ts" /> ///<reference path="../redux/redux...
extends R.Component<ToastrOptions, any>{ } interface EmitterOptions { /** * Notification popup icon. * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert */ icon?: string, /** * Timeout in milisecon...
ReduxToastr
identifier_name
react-redux-toastr.d.ts
// Type definitions for react-redux-toastr 3.7.0 // Project: https://github.com/diegoddox/react-redux-toastr // Definitions by: Aleksandar Ivanov <https://github.com/Smiche> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped ///<reference path="../react/react.d.ts" /> ///<reference path="../redux/redux...
position?: string, confirmText?: ConfirmText } interface ConfirmText { okText: string, cancelText: string } /** * Toastr react component. */ export default class ReduxToastr extends R.Component<ToastrOptions, any>{ } interface EmitterOptions { ...
/** * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right */
random_line_split
reversi.rs
use std::io::{Write, BufWriter}; static BOARD_SIZE: usize = 10; // 盤面のコマ+2 #[derive(Debug, Clone)] pub enum PieceType { Black, White, Sentinel, Null, } fn flip_turn(t: PieceType) -> PieceType { match t { PieceType::Black => PieceType::White, PieceType::White => PieceType::Black, _ => PieceType::Null, } }...
== half && x == half + 1 || y == half + 1 && x == half { v[y].push(PieceType::Black); } else { v[y].push(PieceType::Null); } } } Reversi { board: v, turn: PieceType::Black, } } pub fn debug_board(&self) { let w = super::std::io::stdout(); let mut w = BufWriter::new(w.lock(...
].push(PieceType::White); } else if y
conditional_block
reversi.rs
use std::io::{Write, BufWriter}; static BOARD_SIZE: usize = 10; // 盤面のコマ+2 #[derive(Debug, Clone)] pub enum PieceType { Black, White, Sentinel, Null, } fn flip_turn(t: PieceType) -> PieceType { match t { PieceType::Black => PieceType::White, PieceType::White => PieceType::Black, _ => PieceType::Null, } }...
ve(Debug, Clone)] pub struct Reversi { board: Vec<Vec<PieceType>>, pub turn: PieceType, } impl Reversi { pub fn new() -> Self { let mut v: Vec<Vec<PieceType>> = Vec::new(); let half = (BOARD_SIZE - 2) / 2; for y in 0..BOARD_SIZE { v.push(Vec::new()); for x in 0..BOARD_SIZE { if y == 0 || x == 0 || ...
= t } } #[deri
identifier_body
reversi.rs
use std::io::{Write, BufWriter}; static BOARD_SIZE: usize = 10; // 盤面のコマ+2 #[derive(Debug, Clone)] pub enum PieceType { Black, White, Sentinel, Null, } fn flip_turn(t: PieceType) -> PieceType { match t { PieceType::Black => PieceType::White, PieceType::White => PieceType::Black, _ => PieceType::Null, } }...
Vec<Vec<PieceType>>, pub turn: PieceType, } impl Reversi { pub fn new() -> Self { let mut v: Vec<Vec<PieceType>> = Vec::new(); let half = (BOARD_SIZE - 2) / 2; for y in 0..BOARD_SIZE { v.push(Vec::new()); for x in 0..BOARD_SIZE { if y == 0 || x == 0 || y == BOARD_SIZE - 1 || x == BOARD_SIZE - 1 ...
board:
identifier_name
reversi.rs
use std::io::{Write, BufWriter}; static BOARD_SIZE: usize = 10; // 盤面のコマ+2 #[derive(Debug, Clone)] pub enum PieceType { Black, White, Sentinel, Null, } fn flip_turn(t: PieceType) -> PieceType { match t { PieceType::Black => PieceType::White, PieceType::White => PieceType::Black, _ => PieceType::Null, } }
#[derive(Debug, Clone)] pub struct Reversi { board: Vec<Vec<PieceType>>, pub turn: PieceType, } impl Reversi { pub fn new() -> Self { let mut v: Vec<Vec<PieceType>> = Vec::new(); let half = (BOARD_SIZE - 2) / 2; for y in 0..BOARD_SIZE { v.push(Vec::new()); for x in 0..BOARD_SIZE { if y == 0 || x ==...
impl PartialEq for PieceType { fn eq(&self, t: &PieceType) -> bool { self == t } }
random_line_split
timecalc.js
/* * timecalc.js * * Parses multi line content for times and calculates a total time duration. * * Author: Eric Lambrecht * License: MIT */ ;(function ($, window, undefined) { "use strict"; var TimeCalculator, Time, defaults = { 'time-delimiter': '\n', 'natlang-sup...
var currentTimeUnit = parts[partIdx + 1].toString().toLowerCase(); switch(currentTimeUnit) { case "hour": case "hours": hours = parseInt(current...
if (stringHasRightFormat) { var currentNumber = parts[partIdx];
random_line_split
timecalc.js
/* * timecalc.js * * Parses multi line content for times and calculates a total time duration. * * Author: Eric Lambrecht * License: MIT */ ;(function ($, window, undefined) { "use strict"; var TimeCalculator, Time, defaults = { 'time-delimiter': '\n', 'natlang-sup...
} // if line has comma or dot, we treat it as hours in decimal representation. else if (lines[i].indexOf(",") !== -1 || lines[i].indexOf(".") !== -1) { var inputNumber = parseFloat(lines[i].replace(",", ".")); mins = Math.round(...
{ var stringHasRightFormat, match, parts, tmpLine = lines[i], partIdx = 0; do { // Search for (first) number ...
conditional_block
Resume.js
import React from 'react'; const Resume = () => { const content = ( <span> <h2>Curriculum Vitae</h2> <p> Sed quis mattis turpis. Ut vitae finibus sem. Donec scelerisque nec nisi non malesuada. Praesent mattis
finibus. Nunc non mi tincidunt, luctus purus tempus. <br/><br/> Vitae dignissim ante est vel erat. Maecenas auctor dolor vitae egestas aliquam. Morbi suscipit, est id malesuada viverra, ex mauris finibus dolor, ac tincidunt justo dui auctor mi. Nunc scelerisque sapien eget tempus ferm...
lacus quis diam imperdiet rhoncus. Ut porta efficitur magna, quis pretium magna. Nam venenatis convallis
random_line_split
output_prn.py
# Copyright (C) 2012 Vivek Haldar # # Take in a dict containing fetched RSS data, and output to printable files in # the current directory. # # Dict looks like: # feed_title -> [list of articles] # each article has (title, body). # # Author: Vivek Haldar <vh@vivekhaldar.com> import codecs import escpos from datetime i...
prn = escpos.Escpos('%s.prn' % f.replace('/', '_')) for a in articles[f]: title, body = a # Cut body down to 100 words. short_body = ' '.join(body.split()[:100]) prn.bigtext(f + '\n') prn.bigtext(textwrap.fill(title, 32) + '\n')...
conditional_block
output_prn.py
# Copyright (C) 2012 Vivek Haldar # # Take in a dict containing fetched RSS data, and output to printable files in # the current directory. # # Dict looks like: # feed_title -> [list of articles] # each article has (title, body). # # Author: Vivek Haldar <vh@vivekhaldar.com> import codecs import escpos from datetime i...
articles = self._articles for f in articles: prn = escpos.Escpos('%s.prn' % f.replace('/', '_')) for a in articles[f]: title, body = a # Cut body down to 100 words. short_body = ' '.join(body.split()[:100]) prn.bigtext(f + '...
identifier_body
output_prn.py
# Copyright (C) 2012 Vivek Haldar # # Take in a dict containing fetched RSS data, and output to printable files in # the current directory. # # Dict looks like: # feed_title -> [list of articles] # each article has (title, body). # # Author: Vivek Haldar <vh@vivekhaldar.com> import codecs import escpos from datetime i...
prn.bigtext(textwrap.fill(title, 32) + '\n') prn.text(textwrap.fill(body, 32)) prn.text('\n\n\n') prn.flush()
for a in articles[f]: title, body = a # Cut body down to 100 words. short_body = ' '.join(body.split()[:100]) prn.bigtext(f + '\n')
random_line_split
output_prn.py
# Copyright (C) 2012 Vivek Haldar # # Take in a dict containing fetched RSS data, and output to printable files in # the current directory. # # Dict looks like: # feed_title -> [list of articles] # each article has (title, body). # # Author: Vivek Haldar <vh@vivekhaldar.com> import codecs import escpos from datetime i...
(output.Output): def output(self): articles = self._articles for f in articles: prn = escpos.Escpos('%s.prn' % f.replace('/', '_')) for a in articles[f]: title, body = a # Cut body down to 100 words. short_body = ' '.join(body.s...
OutputPrn
identifier_name
index.js
'use strict'; let router = require('koa-router')(); let navigation = require('../controllers/navigation.js'); function
() { return function* (next) { console.log('-----', this.user , '---- ', this.state); if (this.state.user || this.user) { yield next; } else { this.throw(401, 'Must be logged in to see this!'); } } }; //navigations router.get('/', navigation.home); router....
isAuth
identifier_name
index.js
'use strict'; let router = require('koa-router')(); let navigation = require('../controllers/navigation.js'); function isAuth() { return function* (next) { console.log('-----', this.user , '---- ', this.state); if (this.state.user || this.user)
else { this.throw(401, 'Must be logged in to see this!'); } } }; //navigations router.get('/', navigation.home); router.get('/about', navigation.about); router.get('/profile', navigation.profile); router.get('/karaoke', navigation.karaoke); router.get('/login', navigation.login); router.get('/l...
{ yield next; }
conditional_block
index.js
'use strict'; let router = require('koa-router')(); let navigation = require('../controllers/navigation.js'); function isAuth() { return function* (next) { console.log('-----', this.user , '---- ', this.state); if (this.state.user || this.user) { yield next; } else { ...
router.get('/', navigation.home); router.get('/about', navigation.about); router.get('/profile', navigation.profile); router.get('/karaoke', navigation.karaoke); router.get('/login', navigation.login); router.get('/logout', navigation.logout); router.get('/signup', navigation.signup); router.post('/authenticate', navig...
random_line_split
index.js
'use strict'; let router = require('koa-router')(); let navigation = require('../controllers/navigation.js'); function isAuth()
; //navigations router.get('/', navigation.home); router.get('/about', navigation.about); router.get('/profile', navigation.profile); router.get('/karaoke', navigation.karaoke); router.get('/login', navigation.login); router.get('/logout', navigation.logout); router.get('/signup', navigation.signup); router.post('/auth...
{ return function* (next) { console.log('-----', this.user , '---- ', this.state); if (this.state.user || this.user) { yield next; } else { this.throw(401, 'Must be logged in to see this!'); } } }
identifier_body
test_commands.py
# -*- coding: utf-8 -*- import os from os import path as op import shutil import glob import warnings from nose.tools import assert_true, assert_raises from numpy.testing import assert_equal, assert_allclose from mne import concatenate_raws, read_bem_surfaces from mne.commands import (mne_browse_raw, mne_bti2fiff, mne...
(): """Test mne bti2fiff.""" check_usage(mne_bti2fiff) def test_compare_fiff(): """Test mne compare_fiff.""" check_usage(mne_compare_fiff) def test_show_fiff(): """Test mne compare_fiff.""" check_usage(mne_show_fiff) with ArgvSetter((raw_fname,)): mne_show_fiff.run() @requires_...
test_bti2fiff
identifier_name
test_commands.py
# -*- coding: utf-8 -*- import os from os import path as op import shutil import glob import warnings from nose.tools import assert_true, assert_raises from numpy.testing import assert_equal, assert_allclose from mne import concatenate_raws, read_bem_surfaces from mne.commands import (mne_browse_raw, mne_bti2fiff, mne...
def test_surf2bem(): """Test mne surf2bem.""" check_usage(mne_surf2bem) @ultra_slow_test @requires_freesurfer @testing.requires_testing_data def test_watershed_bem(): """Test mne watershed bem.""" check_usage(mne_watershed_bem) # Copy necessary files to tempdir tempdir = _TempDir() mrid...
"""Test mne report.""" check_usage(mne_report) tempdir = _TempDir() use_fname = op.join(tempdir, op.basename(raw_fname)) shutil.copyfile(raw_fname, use_fname) with ArgvSetter(('-p', tempdir, '-i', use_fname, '-d', subjects_dir, '-s', 'sample', '--no-browser', '-m', '30')): ...
identifier_body
test_commands.py
# -*- coding: utf-8 -*- import os from os import path as op import shutil import glob import warnings from nose.tools import assert_true, assert_raises from numpy.testing import assert_equal, assert_allclose from mne import concatenate_raws, read_bem_surfaces from mne.commands import (mne_browse_raw, mne_bti2fiff, mne...
@slow_test @requires_mayavi @requires_PIL @testing.requires_testing_data def test_report(): """Test mne report.""" check_usage(mne_report) tempdir = _TempDir() use_fname = op.join(tempdir, op.basename(raw_fname)) shutil.copyfile(raw_fname, use_fname) with ArgvSetter(('-p', tempdir, '-i', use_...
assert_true(check in out.stdout.getvalue(), check)
conditional_block
test_commands.py
# -*- coding: utf-8 -*- import os from os import path as op import shutil import glob import warnings from nose.tools import assert_true, assert_raises from numpy.testing import assert_equal, assert_allclose from mne import concatenate_raws, read_bem_surfaces from mne.commands import (mne_browse_raw, mne_bti2fiff, mne...
with open(bad_fname, 'w') as fid: fid.write('MEG 2443\n') shutil.copyfile(raw_fname, use_fname) with ArgvSetter(('-i', use_fname, '--bad=' + bad_fname, '--rej-eeg', '150')): fun.run() fnames = glob.glob(op.join(tempdir, '*proj.fif')) ...
for fun in (mne_compute_proj_ecg, mne_compute_proj_eog): check_usage(fun) tempdir = _TempDir() use_fname = op.join(tempdir, op.basename(raw_fname)) bad_fname = op.join(tempdir, 'bads.txt')
random_line_split
hooks.ts
import { Observable, of, Subject } from 'rxjs'; import { filter } from 'rxjs/operators'; import { SharedHooks } from '../shared-hooks/hooks'; import { Attributes } from '../types'; export class IntersectionObserverHooks extends SharedHooks<{ isIntersecting: boolean }> { private readonly observers = new WeakMap<Eleme...
rootMargin?: string; }
random_line_split
hooks.ts
import { Observable, of, Subject } from 'rxjs'; import { filter } from 'rxjs/operators'; import { SharedHooks } from '../shared-hooks/hooks'; import { Attributes } from '../types'; export class IntersectionObserverHooks extends SharedHooks<{ isIntersecting: boolean }> { private readonly observers = new WeakMap<Eleme...
(entrys: IntersectionObserverEntry[]) { entrys.forEach((entry) => this.intersectionSubject.next(entry)); } } interface ObserverOptions { root: Element | null; rootMargin?: string; }
loadingCallback
identifier_name
hooks.ts
import { Observable, of, Subject } from 'rxjs'; import { filter } from 'rxjs/operators'; import { SharedHooks } from '../shared-hooks/hooks'; import { Attributes } from '../types'; export class IntersectionObserverHooks extends SharedHooks<{ isIntersecting: boolean }> { private readonly observers = new WeakMap<Eleme...
if (attributes.customObservable) { return attributes.customObservable; } const scrollContainerKey = attributes.scrollContainer || this.uniqKey; const options: ObserverOptions = { root: attributes.scrollContainer || null, }; if (attributes.offset) { options.rootMargin = `${attr...
{ return of({ isIntersecting: true }); }
conditional_block
ShowCertification.js
const certificationUrl = '/certification/developmentuser/responsive-web-design'; const projects = { superBlock: 'responsive-web-design', block: 'responsive-web-design-projects', challenges: [ { slug: 'build-a-tribute-page', solution: 'https://codepen.io/moT01/pen/ZpJpKp' }, { slug: '...
'https://twitter.com/intent/tweet?text=I just earned the Responsive Web Design certification @freeCodeCamp! Check it out here: https://freecodecamp.org/certification/developmentuser/responsive-web-design' ); }); it("should be issued with today's date", () => { const date = new Date(); ...
random_line_split
ShowCertification.js
const certificationUrl = '/certification/developmentuser/responsive-web-design'; const projects = { superBlock: 'responsive-web-design', block: 'responsive-web-design-projects', challenges: [ { slug: 'build-a-tribute-page', solution: 'https://codepen.io/moT01/pen/ZpJpKp' }, { slug: '...
}); // claim certificate cy.get('a[href*="developmentuser/responsive-web-design"]').click({ force: true }); }); describe('while viewing your own,', function () { before(() => { cy.login(); cy.visit(certificationUrl); }); it('should render a LinkedIn button', functio...
{ btn[0].click({ force: true }); cy.wait(1000); }
conditional_block
MaterialUIPickers.tsx
import * as React from 'react'; import Stack from '@material-ui/core/Stack'; import TextField from '@material-ui/core/TextField'; import AdapterDateFns from '@material-ui/lab/AdapterDateFns'; import LocalizationProvider from '@material-ui/lab/LocalizationProvider'; import TimePicker from '@material-ui/lab/TimePicker'; ...
{ const [value, setValue] = React.useState<Date | null>( new Date('2014-08-18T21:11:54'), ); const handleChange = (newValue: Date | null) => { setValue(newValue); }; return ( <LocalizationProvider dateAdapter={AdapterDateFns}> <Stack spacing={3}> <DesktopDatePicker label=...
identifier_body
MaterialUIPickers.tsx
import * as React from 'react'; import Stack from '@material-ui/core/Stack'; import TextField from '@material-ui/core/TextField'; import AdapterDateFns from '@material-ui/lab/AdapterDateFns'; import LocalizationProvider from '@material-ui/lab/LocalizationProvider'; import TimePicker from '@material-ui/lab/TimePicker'; ...
value={value} onChange={handleChange} renderInput={(params) => <TextField {...params} />} /> <TimePicker label="Time picker" value={value} onChange={handleChange} renderInput={(params) => <TextField {...params} />} /> </...
inputFormat="MM/dd/yyyy"
random_line_split
MaterialUIPickers.tsx
import * as React from 'react'; import Stack from '@material-ui/core/Stack'; import TextField from '@material-ui/core/TextField'; import AdapterDateFns from '@material-ui/lab/AdapterDateFns'; import LocalizationProvider from '@material-ui/lab/LocalizationProvider'; import TimePicker from '@material-ui/lab/TimePicker'; ...
() { const [value, setValue] = React.useState<Date | null>( new Date('2014-08-18T21:11:54'), ); const handleChange = (newValue: Date | null) => { setValue(newValue); }; return ( <LocalizationProvider dateAdapter={AdapterDateFns}> <Stack spacing={3}> <DesktopDatePicker lab...
MaterialUIPickers
identifier_name
tokens.rs
//* This file is part of the uutils coreutils package. //* //* (c) Roman Gafiyatullin <r.gafiyatullin@me.com> //* //* For the full copyright and license information, please view the LICENSE //* file that was distributed with this source code. //! //! The following tokens are present in the expr grammar: //! * integer ...
(strings: &[String]) -> Result<Vec<(usize, Token)>, String> { let mut tokens_acc = Vec::with_capacity(strings.len()); let mut tok_idx = 1; for s in strings { let token_if_not_escaped = match s.as_ref() { "(" => Token::ParOpen, ")" => Token::ParClose, "^" => Toke...
strings_to_tokens
identifier_name
tokens.rs
//* This file is part of the uutils coreutils package. //* //* (c) Roman Gafiyatullin <r.gafiyatullin@me.com> //* //* For the full copyright and license information, please view the LICENSE //* file that was distributed with this source code. //! //! The following tokens are present in the expr grammar: //! * integer ...
else { acc.push((tok_idx, token)); } }
{ acc.pop(); acc.push((tok_idx, Token::new_value(s))); }
conditional_block
tokens.rs
//* This file is part of the uutils coreutils package. //* //* (c) Roman Gafiyatullin <r.gafiyatullin@me.com> //* //* For the full copyright and license information, please view the LICENSE //* file that was distributed with this source code. //! //! The following tokens are present in the expr grammar: //! * integer ...
} pub fn strings_to_tokens(strings: &[String]) -> Result<Vec<(usize, Token)>, String> { let mut tokens_acc = Vec::with_capacity(strings.len()); let mut tok_idx = 1; for s in strings { let token_if_not_escaped = match s.as_ref() { "(" => Token::ParOpen, ")" => Token::ParClo...
{ matches!(*self, Token::ParClose) }
identifier_body
tokens.rs
//* This file is part of the uutils coreutils package. //* //* (c) Roman Gafiyatullin <r.gafiyatullin@me.com> //* //* For the full copyright and license information, please view the LICENSE //* file that was distributed with this source code. //! //! The following tokens are present in the expr grammar: //! * integer ...
if debug_var == "1" { println!("EXPR_DEBUG_TOKENS"); for token in tokens_acc { println!("\t{:?}", token); } } } } fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) { // Smells heuristics... :( ...
if let Ok(debug_var) = env::var("EXPR_DEBUG_TOKENS") {
random_line_split
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: readme = f.read() requirements = [ 'prov>=1.5.3', ] test_require...
tests_require=test_requirements, python_requires='>=2', )
],
random_line_split