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
main.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/. */ //! A Takuzu (a.k.a. Binairo) solver. //! //! # Usage //! //! ```shell //! takuzu [FILE]... //! takuzu {--help | ...
(error: &Error) -> String { error .causes() .skip(1) .fold(error.to_string(), |mut buffer, cause| { write!(&mut buffer, ": {}", cause).unwrap(); buffer }) } /// Returns `true` if `stdout` is a terminal. fn isatty_stdout() -> bool { match unsafe { libc::is...
causes_fold
identifier_name
_codeblock.py
class CodeBlock: """Code fragment for the readable format. """ def __init__(self, head, codes): self._head = '' if head == '' else head + ' ' self._codes = codes def
(self, indent_width=0): codes = [] codes.append(' ' * indent_width + self._head + '{') for code in self._codes: next_indent_width = indent_width + 2 if isinstance(code, str): codes.append(' ' * next_indent_width + code) elif isinstance(code, Co...
_to_str_list
identifier_name
_codeblock.py
class CodeBlock:
def __str__(self): """Emit CUDA program like the following format. <<head>> { <<begin codes>> ...; <<end codes>> } """ return '\n'.join(self._to_str_list())
"""Code fragment for the readable format. """ def __init__(self, head, codes): self._head = '' if head == '' else head + ' ' self._codes = codes def _to_str_list(self, indent_width=0): codes = [] codes.append(' ' * indent_width + self._head + '{') for code in self._...
identifier_body
_codeblock.py
class CodeBlock: """Code fragment for the readable format. """ def __init__(self, head, codes): self._head = '' if head == '' else head + ' ' self._codes = codes def _to_str_list(self, indent_width=0): codes = []
codes.append(' ' * next_indent_width + code) elif isinstance(code, CodeBlock): codes += code._to_str_list(indent_width=next_indent_width) else: assert False codes.append(' ' * indent_width + '}') return codes def __str__(self):...
codes.append(' ' * indent_width + self._head + '{') for code in self._codes: next_indent_width = indent_width + 2 if isinstance(code, str):
random_line_split
_codeblock.py
class CodeBlock: """Code fragment for the readable format. """ def __init__(self, head, codes): self._head = '' if head == '' else head + ' ' self._codes = codes def _to_str_list(self, indent_width=0): codes = [] codes.append(' ' * indent_width + self._head + '{') ...
codes.append(' ' * indent_width + '}') return codes def __str__(self): """Emit CUDA program like the following format. <<head>> { <<begin codes>> ...; <<end codes>> } """ return '\n'.join(self._to_str_list())
next_indent_width = indent_width + 2 if isinstance(code, str): codes.append(' ' * next_indent_width + code) elif isinstance(code, CodeBlock): codes += code._to_str_list(indent_width=next_indent_width) else: assert False
conditional_block
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn
( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, is_forward: bool, ) -> anyhow::Result<()> { let empty_list = Vec::new(); for (module, _) in graph.iter() { // (breadth-first) search and gather the modules in `graph` which are reachable from `module`. let mut dot_src: String ...
generate_diagram_per_module
identifier_name
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, ...
for (module, _) in graph.iter() { // (breadth-first) search and gather the modules in `graph` which are reachable from `module`. let mut dot_src: String = String::new(); let mut visited: BTreeSet<String> = BTreeSet::new(); let mut queue: VecDeque<String> = VecDeque::new(); ...
let empty_list = Vec::new();
random_line_split
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, ...
{ let (inp_dir, out_dir) = locate_inp_out_dir(); let err = generate(inp_dir.as_path(), out_dir.as_path()); if let Err(err) = err { println!("Error: {:?}", err); } }
identifier_body
main.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use regex::Regex; use std::{ collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, env, fs, path::{Path, PathBuf}, }; fn generate_diagram_per_module( graph: &BTreeMap<String, Vec<String>>, out_dir: &Path, ...
let module_name = caps.unwrap()[1].to_string(); if let Entry::Vacant(e) = dep_graph_inverse.entry(module_name.clone()) { e.insert(vec![]); } let mut dep_list: Vec<String> = Vec::new(); // TODO: This is not 100% correct because modules can be used with full qualifica...
{ // skip due to no module declaration found. continue; }
conditional_block
doc.rs
node, we compute its value as the GLB of all its successors. Basically contracting nodes ensure that there is overlap between their successors; we will ultimately infer the largest overlap possible. # The Region Hierarchy ## Without closures Let's first consider the region hierarchy without thinking about closures...
}
random_line_split
login.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import {SharedModule} from "../shared/shared.module"; import { LoginComponent } from './login.component'; import {AuthService} from "../services/auth.service"; import {RouterTestingModule} from "@a...
TestBed.configureTestingModule({ declarations: [ LoginComponent ], imports: [SharedModule, RouterTestingModule.withRoutes([])], providers: [{provide: AuthService, useValue: authServiceStub}] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(LoginCo...
beforeEach(async(() => {
random_line_split
test_protocol_peer.py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in ...
else: txaio.use_asyncio() from autobahn import wamp from autobahn.wamp import message from autobahn.wamp import exception from autobahn.wamp import protocol import unittest2 as unittest class TestPeerExceptions(unittest.TestCase): def test_exception_from_message(self): session = protocol.BaseSessi...
txaio.use_twisted()
conditional_block
test_protocol_peer.py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in ...
# furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRA...
# copies of the Software, and to permit persons to whom the Software is
random_line_split
test_protocol_peer.py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in ...
(self): session = protocol.BaseSession() @wamp.error(u"com.myapp.error1") class AppError1(Exception): pass @wamp.error(u"com.myapp.error2") class AppError2(Exception): pass session.define(AppError1) session.define(AppError2) exc...
test_message_from_exception
identifier_name
test_protocol_peer.py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in ...
emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error2') exc = session._exception_from_message(emsg) self.assertIsInstance(exc, AppError2) self.assertEqual(exc.args, ()) # map undefined error to (generic) exception emsg = message.Error(message.Call.ME...
def test_exception_from_message(self): session = protocol.BaseSession() @wamp.error(u"com.myapp.error1") class AppError1(Exception): pass @wamp.error(u"com.myapp.error2") class AppError2(Exception): pass session.define(AppError1) session...
identifier_body
CHANGELOG.tsx
import { change, date } from 'common/changelog'; import SPELLS from 'common/SPELLS'; import { Juko8, Abelito75, Talby, Hursti } from 'CONTRIBUTORS'; import { SpellLink } from 'interface'; export default [ change(date(2022, 1, 2), <>Changed the <SpellLink id={SPELLS.COORDINATED_OFFENSIVE.id} /> module to work with <S...
change(date(2020, 10, 20), <>Added <SpellLink id={SPELLS.EXPEL_HARM.id} icon /> cast efficiency to checklist</>, Juko8), change(date(2020, 10, 19), <>Added <SpellLink id={SPELLS.LAST_EMPERORS_CAPACITOR.id} /></>, Juko8), change(date(2020, 10, 17), <>Minor changes, <SpellLink id={SPELLS.ENERGIZING_ELIXIR_TALENT.id...
change(date(2020, 12, 6), 'Converted most Windwalker modules to TypeScript', Juko8), change(date(2020, 11, 25), <>Added <SpellLink id={SPELLS.JADE_IGNITION.id} /></>, Juko8),
random_line_split
composition.py
from kivy.graphics import Color, Line, Quad from modeful.ui.diagram.relationship import Trigonometry from modeful.ui.diagram.relationship.association import Association class Composition(Association): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) with self.canv...
super().redraw(x1, y1, x2, y2) points = Trigonometry.get_diamond_points(x1, y1, x2, y2, size=15) self._diamond_bg.points = points self._diamond_line.points = points
identifier_body
composition.py
from kivy.graphics import Color, Line, Quad from modeful.ui.diagram.relationship import Trigonometry from modeful.ui.diagram.relationship.association import Association class Composition(Association): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) with self.canv...
def redraw(self, x1, y1, x2, y2): super().redraw(x1, y1, x2, y2) points = Trigonometry.get_diamond_points(x1, y1, x2, y2, size=15) self._diamond_bg.points = points self._diamond_line.points = points
random_line_split
composition.py
from kivy.graphics import Color, Line, Quad from modeful.ui.diagram.relationship import Trigonometry from modeful.ui.diagram.relationship.association import Association class Composition(Association): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) with self.canv...
(self, x1, y1, x2, y2): super().redraw(x1, y1, x2, y2) points = Trigonometry.get_diamond_points(x1, y1, x2, y2, size=15) self._diamond_bg.points = points self._diamond_line.points = points
redraw
identifier_name
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // ...
test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Equal)); } #[test] fn partial_cmp_test4() { let x: &str = "人口"; let other: &str = "人"; let result: Option<Ordering> = x.partial_cmp(oth...
et x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[
identifier_body
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // ...
let x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); ...
ial_cmp_test2() {
identifier_name
partial_cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl PartialOrd for str { // #[inline] // fn partial_cmp(&self, other: &str) -> Option<Ordering> { // Some(self.cmp(other)) // } // ...
assert_eq!(result, Some::<Ordering>(Greater)); } #[test] fn partial_cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Option<Ordering> = x.partial_cmp(other); assert_eq!(result, Some::<Ordering>(Equal)); } #[test] fn partial_cmp_test4() { let x: &str = "人口"; let other: ...
let other: &str = "地"; // '\u{5730}' let result: Option<Ordering> = x.partial_cmp(other);
random_line_split
eventlet_backdoor.py
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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 a...
] CONF = cfg.CONF CONF.register_opts(eventlet_backdoor_opts) LOG = logging.getLogger(__name__) def list_opts(): """Entry point for oslo.config-generator. """ return [(None, copy.deepcopy(eventlet_backdoor_opts))] class EventletBackdoorConfigValueError(Exception): def __init__(self, port_range, help...
cfg.StrOpt('backdoor_port', help="Enable eventlet backdoor. %s" % help_for_backdoor_port)
random_line_split
eventlet_backdoor.py
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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 a...
(): """Entry point for oslo.config-generator. """ return [(None, copy.deepcopy(eventlet_backdoor_opts))] class EventletBackdoorConfigValueError(Exception): def __init__(self, port_range, help_msg, ex): msg = ('Invalid backdoor_port configuration %(range)s: %(ex)s. ' '%(help)s' %...
list_opts
identifier_name
eventlet_backdoor.py
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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 a...
def _parse_port_range(port_range): if ':' not in port_range: start, end = port_range, port_range else: start, end = port_range.split(':', 1) try: start, end = int(start), int(end) if end < start: raise ValueError return start, end except ValueError ...
print(threadId) traceback.print_stack(stack) print()
conditional_block
eventlet_backdoor.py
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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 a...
def _print_nativethreads(): for threadId, stack in sys._current_frames().items(): print(threadId) traceback.print_stack(stack) print() def _parse_port_range(port_range): if ':' not in port_range: start, end = port_range, port_range else: start, end = port_range.s...
for i, gt in enumerate(_find_objects(greenlet.greenlet)): print(i, gt) traceback.print_stack(gt.gr_frame) print()
identifier_body
ToolDetails.js
/******************************************************************************* * Copyright (c) 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is a...
else { me.buttonText.innerHTML = i18n.DETAILS_OPEN; } //Right now these are not supported me.supportedFieldIcon.style.display = "none"; me.supportedFieldText.style.display = "none"; })); }, setTransitionBackTo : function(viewId) { this.transitionBackTo...
{ if (platform.isPhone()) { me.buttonText.innerHTML = i18n.DETAILS_ADD; } else { me.buttonText.innerHTML = i18n.DETAILS_ADDBUTTON; } }
conditional_block
ToolDetails.js
/******************************************************************************* * Copyright (c) 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is a...
} } else { me.buttonText.innerHTML = i18n.DETAILS_OPEN; } //Right now these are not supported me.supportedFieldIcon.style.display = "none"; me.supportedFieldText.style.display = "none"; })); }, setTransitionBackTo : function(viewId) { ...
} else { me.buttonText.innerHTML = i18n.DETAILS_ADDBUTTON;
random_line_split
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn invalid_request() -> Error { Error { message: "invalid request".to_owned(), code: ...
pub fn method_not_found() -> Error { Error { message: "method not found".to_owned(), code: -32601, data: None, } } // pub fn invalid_params(params: Value) -> Error { // Error { // code: -32602, // message: "invalid params".to_owned(), // data: params, // ...
{ Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, } }
identifier_body
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn
() -> Error { Error { message: "invalid request".to_owned(), code: -32600, data: None, } } pub fn invalid_version() -> Error { Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, } } pub fn method_not_found() ->...
invalid_request
identifier_name
errors.rs
use serde::ser::Serialize; use serde_json::Value; use api::rpc::Error; pub fn parse_error() -> Error { Error { message: "parse error".to_owned(), code: -32700, data: None, } } pub fn invalid_request() -> Error { Error { message: "invalid request".to_owned(), code: ...
} pub fn method_not_found() -> Error { Error { message: "method not found".to_owned(), code: -32601, data: None, } } // pub fn invalid_params(params: Value) -> Error { // Error { // code: -32602, // message: "invalid params".to_owned(), // data: params, // ...
Error { code: -32600, message: "unsupported JSON-RPC protocol version".to_owned(), data: None, }
random_line_split
user.py
#!/usr/bin/env python import re from lilac.controller import ADMIN, LOGGER from lilac.orm import Backend from lilac.tool import access, set_secure_cookie from lilac.model import User from solo.template import render_template from solo.web.util import jsonify from solo.web import ctx from webob import exc from lilac....
@jsonify @access() def edit(self, uid, email, real_name, password, newpass1, newpass2, status, role='user'): real_name, newpass1, newpass2 = real_name.strip(), newpass1.strip(), newpass2.strip() uid = int(uid) user = Backend('user').find(uid) if not user: raise...
uid = int(uid) user = Backend('user').find(uid) if not user: raise exc.HTTPNotFound('Not Found') return render_template('user.edit.html', statuses=USER_STATUSES, roles=ROLES, user=user)
identifier_body
user.py
#!/usr/bin/env python import re from lilac.controller import ADMIN, LOGGER from lilac.orm import Backend from lilac.tool import access, set_secure_cookie from lilac.model import User from solo.template import render_template from solo.web.util import jsonify from solo.web import ctx from webob import exc from lilac....
else: user.email = email if me.uid == 1 and user.uid != 1: if role in (ADMIN, USER): user.role = role if user.status != status and status in USER_STATUSES: user.status = status if re.match(r'^[A-Za-z0-9_ ]{4,...
return {'status' : 'error', 'msg' : 'email:%s is used' %(email)}
conditional_block
user.py
#!/usr/bin/env python import re from lilac.controller import ADMIN, LOGGER from lilac.orm import Backend from lilac.tool import access, set_secure_cookie from lilac.model import User from solo.template import render_template from solo.web.util import jsonify from solo.web import ctx from webob import exc from lilac....
'user': 'user' } def user_menu(m): ctl = UserController() # User Api m.connect('userinfo', '/userinfo', controller=ctl, action='userinfo') m.connect('login_page', '/login', controller=ctl, action='login_page', conditions=dict(method=["GET"])) m.connect('login', '/login', controller...
# 'root' : 'root', 'administrator': 'administrator',
random_line_split
user.py
#!/usr/bin/env python import re from lilac.controller import ADMIN, LOGGER from lilac.orm import Backend from lilac.tool import access, set_secure_cookie from lilac.model import User from solo.template import render_template from solo.web.util import jsonify from solo.web import ctx from webob import exc from lilac....
(self, uid, email, real_name, password, newpass1, newpass2, status, role='user'): real_name, newpass1, newpass2 = real_name.strip(), newpass1.strip(), newpass2.strip() uid = int(uid) user = Backend('user').find(uid) if not user: raise exc.HTTPNotFound('user not found') ...
edit
identifier_name
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(...
{ run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K5)), operand2: Some(Direct(K7)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 239, 99], OperandSize::Qword) }
identifier_body
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(...
() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K5)), operand2: Some(Direct(K7)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 239, 99], OperandSize::Qword) }
kshiftrd_2
identifier_name
kshiftrd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*;
fn kshiftrd_1() { run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K7)), operand2: Some(Direct(K6)), operand3: Some(Literal8(51)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 254, 51], OperandSize::Dwo...
use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*;
random_line_split
test_utils.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) a...
self.assertEqual(get_previous_next_objects(objects, 4), (3, 5)) TEST_SUITE = make_test_suite(HoldingPenUtilsTest) if __name__ == "__main__": run_test_suite(TEST_SUITE)
def test_get_previous_next_objects_previous_next(self): """Test the getting of prev, next object ids from the list.""" from invenio.modules.workflows.utils import get_previous_next_objects objects = [3, 4, 5]
random_line_split
test_utils.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) a...
def test_get_previous_next_objects_next(self): """Test the getting of prev, next object ids from the list.""" from invenio.modules.workflows.utils import get_previous_next_objects objects = [3, 4] self.assertEqual(get_previous_next_objects(objects, 3), (None, 4)) def test_get_pr...
"""Test basic utility functions for Holding Pen.""" def test_get_previous_next_objects_empty(self): """Test the getting of prev, next object ids from the list.""" from invenio.modules.workflows.utils import get_previous_next_objects objects = [] self.assertEqual(get_previous_next_ob...
identifier_body
test_utils.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) a...
run_test_suite(TEST_SUITE)
conditional_block
test_utils.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) a...
(InvenioTestCase): """Test basic utility functions for Holding Pen.""" def test_get_previous_next_objects_empty(self): """Test the getting of prev, next object ids from the list.""" from invenio.modules.workflows.utils import get_previous_next_objects objects = [] self.assertEq...
HoldingPenUtilsTest
identifier_name
solar-app.js
import Shader from "./shader/shader-program"; import { degToRad, makePerspective } from "./utility"; import PerformanceCounter from "./performance-counter"; import TextureManager from "./texture-manager"; import Planet from "./planet"; import config from "./config"; /** * Resizes the given canvas element to fit the ...
/** * Mouse Down Callback */ onMouseDown() { this.isMouseDown = true; } /** * Mouse Up Callback */ onMouseUp() { this.isMouseDown = false; } /** * Mouse Move Callback */ onMouseMove({ clientX, clientY }) { if (this.isMouseDown) { ...
{ const zoomDir = Math.max(-1, Math.min(1, e.deltaY)); this.cameraPosition[2] += zoomDir * config.zoomSpeed; }
identifier_body
solar-app.js
import Shader from "./shader/shader-program"; import { degToRad, makePerspective } from "./utility"; import PerformanceCounter from "./performance-counter"; import TextureManager from "./texture-manager"; import Planet from "./planet"; import config from "./config"; /** * Resizes the given canvas element to fit the ...
() { this.isMouseDown = true; } /** * Mouse Up Callback */ onMouseUp() { this.isMouseDown = false; } /** * Mouse Move Callback */ onMouseMove({ clientX, clientY }) { if (this.isMouseDown) { const { x:lastX , y:lastY } = this.mousePosition...
onMouseDown
identifier_name
solar-app.js
import Shader from "./shader/shader-program"; import { degToRad, makePerspective } from "./utility"; import PerformanceCounter from "./performance-counter"; import TextureManager from "./texture-manager"; import Planet from "./planet"; import config from "./config"; /** * Resizes the given canvas element to fit the ...
this.mousePosition.x = clientX; this.mousePosition.y = clientY; } doAction() { try { this.update(); this.render(); this.renderUI(); } catch (err) { this.onError(err); } } /** * Update function of the SolarAp...
{ const { x:lastX , y:lastY } = this.mousePosition; const dX = clientX - lastX; const dY = clientY - lastY; this.cameraPosition[0] += -1 * dX * config.moveSpeed; this.cameraPosition[1] += dY * config.moveSpeed; }
conditional_block
solar-app.js
import Shader from "./shader/shader-program"; import { degToRad, makePerspective } from "./utility"; import PerformanceCounter from "./performance-counter"; import TextureManager from "./texture-manager"; import Planet from "./planet"; import config from "./config"; /** * Resizes the given canvas element to fit the ...
} } setupSolarSystem(systemConfig) { const planets = []; systemConfig.planets.forEach((planetConfig) => { let p = new Planet({ position: [ planetConfig.distance * config.globalScale, 0, 0 ] , radius: planetConfig.radius * config.globalScale, texture: this.textureManager.get...
return glContext; } catch (e) { this.onError(e); return null;
random_line_split
i386_apple_ios.rs
// Copyright 2014 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 ...
() -> Target { Target { data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\ -i32:32:32-i64:32:64\ -f32:32:32-f64:32:64-v64:64:64\ -v128:128:128-a:0:64-f80:128:128\ -n8:16:32".to_string(), llvm_target: "i386-apple...
target
identifier_name
i386_apple_ios.rs
// Copyright 2014 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 ...
{ Target { data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\ -i32:32:32-i64:32:64\ -f32:32:32-f64:32:64-v64:64:64\ -v128:128:128-a:0:64-f80:128:128\ -n8:16:32".to_string(), llvm_target: "i386-apple-ios".to_stri...
identifier_body
i386_apple_ios.rs
// Copyright 2014 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 ...
arch: "x86".to_string(), target_os: "ios".to_string(), target_env: "".to_string(), options: opts(Arch::I386) } }
random_line_split
debug_utils.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/. */
use std::slice; fn hexdump_slice(buf: &[u8]) { let mut stderr = io::stderr(); stderr.write_all(b" ").unwrap(); for (i, &v) in buf.iter().enumerate() { let output = format!("{:02X} ", v); stderr.write_all(output.as_bytes()).unwrap(); match i % 16 { 15 => { stderr.write...
use std::io::{self, Write}; use std::mem; use std::mem::size_of;
random_line_split
debug_utils.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/. */ use std::io::{self, Write}; use std::mem; use std::mem::size_of; use std::slice; fn hexdump_slice(buf: &[u8]) { ...
{ unsafe { let buf: *const u8 = mem::transmute(obj); debug!("dumping at {:p}", buf); let from_buf = slice::from_raw_parts(buf, size_of::<T>()); hexdump_slice(from_buf); } }
identifier_body
debug_utils.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/. */ use std::io::{self, Write}; use std::mem; use std::mem::size_of; use std::slice; fn
(buf: &[u8]) { let mut stderr = io::stderr(); stderr.write_all(b" ").unwrap(); for (i, &v) in buf.iter().enumerate() { let output = format!("{:02X} ", v); stderr.write_all(output.as_bytes()).unwrap(); match i % 16 { 15 => { stderr.write_all(b"\n ").unwrap(); }, ...
hexdump_slice
identifier_name
meta.py
import json import os.path from hashlib import md5 class TargetFile: def __init__(self, path, data = None): self.path = path self.hash = None self.dependencies = {} if data is not None: self.hash = data['hash'] self.dependencies = data['dependencies'] def raw(self): return { 'hash': self.hash, ...
(self): data = {} for t in self: data[t] = self[t].raw() json.dump(data, open(self._path, 'w'), indent = 4) def __getitem__(self, key): if key not in self: self[key] = Target(self) return dict.__getitem__(self, key)
write
identifier_name
meta.py
import json import os.path from hashlib import md5 class TargetFile: def __init__(self, path, data = None): self.path = path self.hash = None self.dependencies = {} if data is not None: self.hash = data['hash'] self.dependencies = data['dependencies'] def raw(self): return { 'hash': self.hash, ...
class Target(dict): def __init__(self, fp, data = {}): dict.__init__(self) self._file = fp for f in data: self[f] = TargetFile(f, data[f]) def raw(self): data = {} for f in self: data[f] = self[f].raw() return data def tidyup(self, files): for f in [tf for tf in self if tf not in files]: ...
for dependency in [ d for d in dependencies if d not in self.dependencies ]: self.dependencies[dependency] = None for dependency in [d for d in self.dependencies if d not in dependencies]: del self.dependencies[dependency]
identifier_body
meta.py
import json import os.path from hashlib import md5 class TargetFile: def __init__(self, path, data = None): self.path = path self.hash = None self.dependencies = {} if data is not None: self.hash = data['hash'] self.dependencies = data['dependencies'] def raw(self): return { 'hash': self.hash, ...
def __getitem__(self, key): if key not in self: self[key] = TargetFile(key) return dict.__getitem__(self, key) class File(dict): def __init__(self, path): dict.__init__(self) self._path = path if os.path.exists(self._path): data = json.load(open(self._path)) if isinstance(data, dict): fo...
self[f].clean()
conditional_block
meta.py
import json import os.path from hashlib import md5 class TargetFile: def __init__(self, path, data = None): self.path = path self.hash = None self.dependencies = {} if data is not None: self.hash = data['hash'] self.dependencies = data['dependencies'] def raw(self): return { 'hash': self.hash, ...
for dependency in self.dependencies: self.dependencies[dependency] = None def changed(self): changed = False # File Hash computed_hash = md5(open(self.path, 'rb').read()).hexdigest() if self.hash is None or self.hash != computed_hash: changed = True self.hash = computed_hash # File Depen...
def clean(self): self.hash = None
random_line_split
_signalhelper.py
GObject library # Copyright (C) 2012 Simon Feltman # # gi/_signalhelper.py: GObject signal binding decorator object # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2...
def copy(self, newName=None): """Returns a renamed copy of the Signal.""" if newName is None: newName = self.name return type(self)(name=newName, func=self.func, flags=self.flags, return_type=self.return_type, arg_types=self.arg_types, ...
if str(self): name = str(self) else: name = obj.__name__ # Return a new value of this type since it is based on an immutable string. return type(self)(name=name, func=obj, flags=self.flags, return_type=self.return_type, ar...
conditional_block
_signalhelper.py
GObject library # Copyright (C) 2012 Simon Feltman # # gi/_signalhelper.py: GObject signal binding decorator object # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2...
def get_signal_annotations(func): """Attempt pulling python 3 function annotations off of 'func' for use as a signals type information. Returns an ordered nested tuple of (return_type, (arg_type1, arg_type2, ...)). If the given function does not have annotations then (None, tuple()) is returned. ...
"""Returns the string 'override'.""" return 'override'
identifier_body
_signalhelper.py
GObject library # Copyright (C) 2012 Simon Feltman # # gi/_signalhelper.py: GObject signal binding decorator object # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2...
(cls, name, *args, **kargs): return str.__new__(cls, name) def __init__(self, signal, gobj): str.__init__(self) self.signal = signal self.gobj = gobj def __repr__(self): return 'BoundSignal("%s")' % self def __call__(self, *args, **k...
__new__
identifier_name
_signalhelper.py
GObject library # Copyright (C) 2012 Simon Feltman # # gi/_signalhelper.py: GObject signal binding decorator object # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2...
str.__init__(self) if func and not (return_type or arg_types): return_type, arg_types = get_signal_annotations(func) if arg_types is None: arg_types = tuple() self.func = func self.flags = flags self.return_type = return_type self.arg_ty...
name = func.__name__ if func and not doc: doc = func.__doc__
random_line_split
vm.rs
} } } OneChar(c, flags) => { if self.char_eq(flags & FLAG_NOCASE > 0, self.chars.prev, c) { self.add(nlist, pc+1, caps); } } CharClass(ref ranges, flags) => { if self.chars.prev.is_some()...
random_line_split
vm.rs
Continue => {}, } } mem::swap(&mut clist, &mut nlist); nlist.empty(); } match self.which { Exists if matched => vec![Some(0), Some(0)], Exists => vec![None, None], Location | Submatches => groups, ...
Threads
identifier_name
vm.rs
ic: 0, chars: CharReader::new(input), }.run() } struct Nfa<'r, 't> { which: MatchKind, prog: &'r Program, input: &'t str, start: uint, end: uint, ic: uint, chars: CharReader<'t>, } /// Indicates the next action to take after a single non-empty instruction /// is process...
} // This simulates a preceding '.*?' for every regex by adding // a state starting at the current position in the input for the // beginning of the program only if we don't already have a match. if clist.size == 0 || (!prefix_anchor && !matched) { ...
{ let needle = self.prog.prefix.as_bytes(); let haystack = &self.input.as_bytes()[self.ic..]; match find_prefix(needle, haystack) { None => break, Some(i) => { self.ic += i; ...
conditional_block
vm.rs
to read the next character. // As a result, the 'step' method will look at the previous // character. self.ic = next_ic; next_ic = self.chars.advance(); for i in range(0, clist.size) { let pc = clist.pc(i); let step_state = se...
{ self.cur.is_none() }
identifier_body
urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib import auth admin.autodiscover() urlpatterns = patterns('stepup.views',
# url(r'^blog/', include('blog.urls')), #auth url(r'^admin/', include(admin.site.urls)), # homepage url(r'^$', 'index', name = 'homepage'), # about url(r'^about/$', 'about', name = 'view_about'), # person url(r'^person/(?P<slug>[^\.]+)', 'person', name = 'view_person'), ...
# Examples: # url(r'^$', 'volunteer.views.home', name='home'),
random_line_split
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
} impl<'a, S: 'a + EventStopable> Dispatchable<S> for EventDispatcher<'a, EventListener> { fn dispatch(&self, event_name: &str, event: &mut S) { if let Some(listeners) = self.listeners.get(event_name) { for listener in listeners { listener.call(event_name, event); ...
{ if self.listeners.contains_key(event_name) { if let Some(mut listeners) = self.listeners.get_mut(event_name) { match listeners.iter().position(|x| *x == listener) { Some(index) => { listeners.remove(index); }, ...
identifier_body
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
, _ => {}, } } } } } impl<'a, S: 'a + EventStopable> Dispatchable<S> for EventDispatcher<'a, EventListener> { fn dispatch(&self, event_name: &str, event: &mut S) { if let Some(listeners) = self.listeners.get(event_name) { for listener ...
{ listeners.remove(index); }
conditional_block
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
if let Some(mut listeners) = self.listeners.get_mut(event_name) { listeners.push(listener); } } pub fn remove_listener(&mut self, event_name: &'a str, listener: &'a mut L) { if self.listeners.contains_key(event_name) { if let Some(mut listeners) = self.listeners....
if !self.listeners.contains_key(event_name) { self.listeners.insert(event_name, Vec::new()); }
random_line_split
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
(event_name: &str, event: &mut EventStopable) { println!("callback from event: {}", event_name); event.stop_propagation(); } #[test] fn test_dispatcher() { let event_name = "test_a"; let mut event = Event::new(); let callback_one: fn(event_name: &str, event: &mut Ev...
print_event_info
identifier_name
ChangeEventPlugin.js
') && ( !('documentMode' in document) || document.documentMode > 8 ); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled( eventTypes.change, activeElementID, nativeEvent ); EventPropagators.accumulateTwoPhaseDispatches(event); // If change bubbled, we'd ...
nativeEvent) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) {
random_line_split
ChangeEventPlugin.js
theticEvent"); var isEventSupported = require("./isEventSupported"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({onChange: null}), captured: keyOf({onChangeCapture: null}) } } }; /**...
() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /**...
stopWatchingForValueChange
identifier_name
ChangeEventPlugin.js
Event"); var isEventSupported = require("./isEventSupported"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({onChange: null}), captured: keyOf({onChangeCapture: null}) } } }; /** * Fo...
/** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange'...
{ activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor( target.constructor.prototype, 'value' ); Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', ha...
identifier_body
ChangeEventPlugin.js
Event"); var isEventSupported = require("./isEventSupported"); var keyOf = require("./keyOf"); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({onChange: null}), captured: keyOf({onChangeCapture: null}) } } }; /** * Fo...
} /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events isInputEventSupported = isEventSupported('input') && ( !('documentMode' i...
{ stopWatchingForChangeEventIE8(); }
conditional_block
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show ...
fn main() { if cmd_args().len() < 2 { return usage(); } match cmd_args().skip(1).next().unwrap().as_ref() { "set" => display_set(), "show" => display_show(), arg @ _ => { println!("Incorrect command {}", &arg); usage(); } } }
{ let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { println!("Display {}:\nWidth={}\nHeight={}", device_name(&dev_mode.dmDeviceName), &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } else { println!("Failed to retrieve ...
identifier_body
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show ...
fn display_show() { let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { println!("Display {}:\nWidth={}\nHeight={}", device_name(&dev_mode.dmDeviceName), &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } else { println!("F...
///Shows current display resolution.
random_line_split
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show ...
(display_name: &[u16; winapi::winuser::CCHDEVICENAME]) -> String { let len: usize = display_name.iter().position(|&elem| elem == 0).unwrap_or(0); String::from_utf16_lossy(&display_name[..len]) } #[inline] fn enum_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi...
device_name
identifier_name
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show ...
} }
{ println!("Incorrect command {}", &arg); usage(); }
conditional_block
color-contrast.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * 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 a...
extends AxeAudit { /** * @return {LH.Audit.Meta} */ static get meta() { return { id: 'color-contrast', title: 'Background and foreground colors have a sufficient contrast ratio', failureTitle: 'Background and foreground colors do not have a ' + 'sufficient contrast ratio.', ...
ColorContrast
identifier_name
color-contrast.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * 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 a...
} module.exports = ColorContrast;
{ return { id: 'color-contrast', title: 'Background and foreground colors have a sufficient contrast ratio', failureTitle: 'Background and foreground colors do not have a ' + 'sufficient contrast ratio.', description: 'Low-contrast text is difficult or impossible for many users to ...
identifier_body
color-contrast.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * 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 a...
} } module.exports = ColorContrast;
description: 'Low-contrast text is difficult or impossible for many users to read. ' + '[Learn more](https://dequeuniversity.com/rules/axe/2.2/color-contrast?application=lighthouse).', requiredArtifacts: ['Accessibility'], };
random_line_split
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn get_input(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); ...
fn test_part2(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part2(&mut input.as_slice()) }) } macro_rules! day_bench { ( $name:ident, $day:expr ) => { pub mod $name { use super::*; ...
let mut instance = get_impl(day); instance.part1(&mut input.as_slice()) }) }
random_line_split
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn get_input(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); ...
fn test_part2(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part2(&mut input.as_slice()) }) } macro_rules! day_bench { ( $name:ident, $day:expr ) => { pub mod $name { use super::*; ...
{ let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part1(&mut input.as_slice()) }) }
identifier_body
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn
(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); file.read_to_end(&mut buf).unwrap(); buf } fn test_part1(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { ...
get_input
identifier_name
recent-imports.ts
/* * Copyright (C) 2018 Shivam Tripathi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is di...
=> importHolder - holds recentImports classified by entity type => timeStampMap - holds value importedAt value in object with importId as key => originIdMap - holds value originId value in object with importId as key */ const {importHolder: recentImportIdsByType, timeStampMap, originIdMap} = await getRe...
export async function getRecentImports( orm: Record<string, unknown>, transacting: Transaction, limit = 10, offset = 0 ) { /* Fetch most recent ImportIds classified by importTypes
random_line_split
recent-imports.ts
/* * Copyright (C) 2018 Shivam Tripathi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is di...
( orm: Record<string, unknown>, transacting: Transaction, limit = 10, offset = 0 ) { /* Fetch most recent ImportIds classified by importTypes => importHolder - holds recentImports classified by entity type => timeStampMap - holds value importedAt value in object with importId as key => originIdMap - holds v...
getRecentImports
identifier_name
recent-imports.ts
/* * Copyright (C) 2018 Shivam Tripathi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is di...
export async function getRecentImports( orm: Record<string, unknown>, transacting: Transaction, limit = 10, offset = 0 ) { /* Fetch most recent ImportIds classified by importTypes => importHolder - holds recentImports classified by entity type => timeStampMap - holds value importedAt value in object with impor...
{ return transacting.select('*') .from(`bookbrainz.${_.snakeCase(type)}_import`) .whereIn('import_id', importIds); }
identifier_body
app.component.spec.ts
import { async, TestBed } from '@angular/core/testing'; import { IonicModule, Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { MyApp } from './app.component'; import { PlatformMock, StatusBarMock, SplashSc...
imports: [ IonicModule.forRoot(MyApp) ], providers: [ { provide: StatusBar, useClass: StatusBarMock }, { provide: SplashScreen, useClass: SplashScreenMock }, { provide: Platform, useClass: PlatformMock } ] }) })); beforeEach(() => { fixture = TestBed....
random_line_split
db.js
var express = require('express'); var mysql = require('mysql'); var conf = require('./config.js'); var Q = require('q'); var pool = mysql.createPool(conf.db_conn); exports.connection = { query: function () { var queryArgs = Array.prototype.slice.call(arguments), events = [], ...
if (conn) { var q = conn.query.apply(conn, queryArgs); q.on('end', function () { conn.release(); }); events.forEach(function (args) { q.on.apply(q, args); }); } }); ...
{ if (eventNameIndex.error) { eventNameIndex.error(); } }
conditional_block
db.js
var express = require('express'); var mysql = require('mysql'); var conf = require('./config.js');
query: function () { var queryArgs = Array.prototype.slice.call(arguments), events = [], eventNameIndex = {}; pool.getConnection(function (err, conn) { if (err) { if (eventNameIndex.error) { eventNameIndex.error(); ...
var Q = require('q'); var pool = mysql.createPool(conf.db_conn); exports.connection = {
random_line_split
DialogWithTitle.tsx
import Dialog from "@material-ui/core/Dialog"; import IconButton from "@material-ui/core/IconButton"; import { Theme } from "@material-ui/core/styles/createMuiTheme"; import createStyles from "@material-ui/core/styles/createStyles"; import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"; import Ty...
}); interface Props { handleClose: () => void; title: string; } class DialogWithTitle extends React.Component< Props & WithStyles<typeof styles> > { render() { const { classes, handleClose, title } = this.props; return ( <Dialog classes={{ paper: classes.paper }} fullWidth ...
paddingBottom: theme.spacing(3) }
random_line_split
DialogWithTitle.tsx
import Dialog from "@material-ui/core/Dialog"; import IconButton from "@material-ui/core/IconButton"; import { Theme } from "@material-ui/core/styles/createMuiTheme"; import createStyles from "@material-ui/core/styles/createStyles"; import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"; import Ty...
extends React.Component< Props & WithStyles<typeof styles> > { render() { const { classes, handleClose, title } = this.props; return ( <Dialog classes={{ paper: classes.paper }} fullWidth maxWidth="md" onClose={handleClose} open scroll="body" > ...
DialogWithTitle
identifier_name
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn f(x: dyn T, y: Box<dyn T + 'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ ...
let y: Box<dyn Display + 'static> = Box::new(BYTE); // ^^^ meta.generic storage.type.trait let _: &dyn (Display) = &BYTE; // ^^^ storage.type.trait let _: &dyn (::std::fmt::Display) = &BYTE; // ^^^ storage.type.trait const DT: &'static dyn C = &V; // ^^^...
// ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.return-type storage.type.trait let x: &(dyn 'static + Display) = &BYTE; // ^^^ meta.group storage.type.trait
random_line_split
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn
(x: dyn T, y: Box<dyn T + 'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ meta.function.parameters storage.type.trait f: &dyn Fn(CrateNum) -> bool) -> dyn ...
f
identifier_name
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn f(x: dyn T, y: Box<dyn T + 'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ ...
// dyn is not a keyword in all situations (a "weak" keyword). type A0 = dyn; // ^^^ -storage.type.trait type A1 = dyn::dyn; // ^^^^^ meta.path -storage.type.trait // ^^^ -storage.type.trait type A2 = dyn<dyn, dyn>; // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic...
{ // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.return-type storage.type.trait let x: &(dyn 'static + Display) = &BYTE; // ^^^ meta.group storage.type.trait let y: Box<dyn Display + 'static> = Box::new(BYTE); // ^^^ meta.ge...
identifier_body
transform.rs
(or None if /// no outputs currently exist). /// /// `f` is called when a new node should be created, and must return that /// node's ID. pub fn node_id<'a, F>(&self, auto_output_candidate: Option<I>, mut f: F) -> I where F: FnMut() -> I { match self { &Target::AutoO...
=> f(), &Target::AllOutputs => panic!("cannot handle `Target::AllOutputs` variant from `node_id`"), &Target::InputOutput => panic!("cannot handle `Target::InputOutput` variant from `node_id`") } } /// Fetch the ID contained in an `...
&Target::NewOutput | &Target::AutoIntermediate
random_line_split
transform.rs
or None if /// no outputs currently exist). /// /// `f` is called when a new node should be created, and must return that /// node's ID. pub fn node_id<'a, F>(&self, auto_output_candidate: Option<I>, mut f: F) -> I where F: FnMut() -> I { match self { &Target::AutoOut...
<E, F>(&mut self, tgt: Target<G::NodeId>, e: E, mut f: F) -> G::NodeId where F: NodeFn<G, E>, (G::NodeId, G::NodeId, E): Into<G::Edge>, E: Clone { match tgt { Target::InputOutput => { for prev in self.inputs.iter() { ...
append_edge
identifier_name
setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Distutils installer for PyJack # Test for Jack2 #---------------------------------------------------# import os if os.path.exists("/usr/local/include/jack/jack.h"): path = "/usr/local/include/jack/jack.h" elif os.path.exists("/usr/include/jack/jack.h"):
else: print("You don't seem to have the jack headers installed.\nPlease install them first") exit(-1) test = open(path).read() pyjack_macros=[] if ("jack_get_version_string" in test): pyjack_macros+=[('JACK2', '1')] else: pyjack_macros+=[('JACK1', '1')] #----------------------------------------------------# ...
path = "/usr/include/jack/jack.h"
conditional_block
setup.py
#!/usr/bin/python
import os if os.path.exists("/usr/local/include/jack/jack.h"): path = "/usr/local/include/jack/jack.h" elif os.path.exists("/usr/include/jack/jack.h"): path = "/usr/include/jack/jack.h" else: print("You don't seem to have the jack headers installed.\nPlease install them first") exit(-1) test = open(path).read(...
# -*- coding: utf-8 -*- # Distutils installer for PyJack # Test for Jack2 #---------------------------------------------------#
random_line_split
multiAgents.py
# multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.ee...
The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among t...
its alternatives via a state evaluation function.
random_line_split
multiAgents.py
# multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.ee...
(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and compu...
ContestAgent
identifier_name