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 |
|---|---|---|---|---|
common.js | /**
* Common utilities
* @module glMatrix
*/
// Configuration Constants
export var EPSILON = 0.000001;
export var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
export var RANDOM = Math.random;
/**
* Sets the type of array used when creating new vectors and matrices
*
* @param {Typ... | *
* @param {Number} a The first number to test.
* @param {Number} b The second number to test.
* @returns {Boolean} True if the numbers are approximately equal, false otherwise.
*/
export function equals(a, b) {
return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
}
if (!Math.hypot) ... | }
/**
* Tests whether or not the arguments have approximately the same value, within an absolute
* or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less
* than or equal to 1.0, and a relative tolerance is used for larger values)
| random_line_split |
common.js | /**
* Common utilities
* @module glMatrix
*/
// Configuration Constants
export var EPSILON = 0.000001;
export var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
export var RANDOM = Math.random;
/**
* Sets the type of array used when creating new vectors and matrices
*
* @param {Typ... | (a) {
return a * degree;
}
/**
* Tests whether or not the arguments have approximately the same value, within an absolute
* or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less
* than or equal to 1.0, and a relative tolerance is used for larger values)
*
* @param {Number}... | toRadian | identifier_name |
NavigationReducer.test.js | import reducer from '../../src/reducers/NavigationReducer';
import * as types from '../../src/actions/types';
describe('navigation reducer', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(
{
leftClicked: false,
rightClicked: false,
curre... | }
);
});
}); | payload: true
})
).toEqual(
{
updateProfileView: true | random_line_split |
future-prelude-collision-turbofish.rs | // See https://github.com/rust-lang/rust/issues/88442
// run-rustfix
// edition:2018
// check-pass
#![allow(unused)]
#![warn(rust_2021_prelude_collisions)]
trait AnnotatableTryInto {
fn try_into<T>(self) -> Result<T, Self::Error>
where Self: std::convert::TryInto<T> {
std::convert::TryInto::try_into(se... | {
let x: u64 = 1;
x.try_into::<usize>().or(Err("foo"))?.checked_sub(1);
//~^ WARNING trait method `try_into` will become ambiguous in Rust 2021
//~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021!
x.try_into::<usize>().or(Err("foo"))?;
//~^ WARNING ... | identifier_body | |
future-prelude-collision-turbofish.rs | // See https://github.com/rust-lang/rust/issues/88442 | // run-rustfix
// edition:2018
// check-pass
#![allow(unused)]
#![warn(rust_2021_prelude_collisions)]
trait AnnotatableTryInto {
fn try_into<T>(self) -> Result<T, Self::Error>
where Self: std::convert::TryInto<T> {
std::convert::TryInto::try_into(self)
}
}
impl<T> AnnotatableTryInto for T where T:... | random_line_split | |
future-prelude-collision-turbofish.rs | // See https://github.com/rust-lang/rust/issues/88442
// run-rustfix
// edition:2018
// check-pass
#![allow(unused)]
#![warn(rust_2021_prelude_collisions)]
trait AnnotatableTryInto {
fn try_into<T>(self) -> Result<T, Self::Error>
where Self: std::convert::TryInto<T> {
std::convert::TryInto::try_into(se... | () -> Result<(), &'static str> {
let x: u64 = 1;
x.try_into::<usize>().or(Err("foo"))?.checked_sub(1);
//~^ WARNING trait method `try_into` will become ambiguous in Rust 2021
//~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021!
x.try_into::<usize>().or(... | main | identifier_name |
capturing-logging.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 ... |
impl Logger for MyWriter {
fn log(&mut self, _level: u32, args: &fmt::Arguments) {
let MyWriter(ref mut inner) = *self;
fmt::writeln(inner as &mut Writer, args);
}
}
#[start]
fn start(argc: int, argv: **u8) -> int {
native::start(argc, argv, proc() {
main();
})
}
fn main() {
... | use std::io::{ChanReader, ChanWriter};
use log::{set_logger, Logger};
struct MyWriter(ChanWriter); | random_line_split |
capturing-logging.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 ... | (argc: int, argv: **u8) -> int {
native::start(argc, argv, proc() {
main();
})
}
fn main() {
let (tx, rx) = channel();
let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx));
spawn(proc() {
set_logger(~MyWriter(w) as ~Logger:Send);
debug!("debug");
info!("info")... | start | identifier_name |
capturing-logging.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 ... |
}
#[start]
fn start(argc: int, argv: **u8) -> int {
native::start(argc, argv, proc() {
main();
})
}
fn main() {
let (tx, rx) = channel();
let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx));
spawn(proc() {
set_logger(~MyWriter(w) as ~Logger:Send);
debug!("debug");
... | {
let MyWriter(ref mut inner) = *self;
fmt::writeln(inner as &mut Writer, args);
} | identifier_body |
output.py | import sublime, sublime_plugin
def clean_layout(layout):
row_set = set()
col_set = set()
for cell in layout["cells"]:
row_set.add(cell[1])
row_set.add(cell[3])
col_set.add(cell[0])
col_set.add(cell[2])
row_set = sorted(row_set)
col_set = sorted(col_set)
rows =... |
return OutputView(output)
class OutputViewClearCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.erase(edit, sublime.Region(0, self.view.size()))
class OutputViewAppendCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
scroll = self.view.visible_region... | active = window.active_view()
output = window.new_file()
output.settings().set("line_numbers", False)
output.settings().set("scroll_past_end", False)
output.settings().set("scroll_speed", 0.0)
output.settings().set("gutter", False)
output.settings(... | conditional_block |
output.py | import sublime, sublime_plugin
def clean_layout(layout):
row_set = set()
col_set = set()
for cell in layout["cells"]:
row_set.add(cell[1])
row_set.add(cell[3])
col_set.add(cell[0])
col_set.add(cell[2])
row_set = sorted(row_set)
col_set = sorted(col_set)
rows =... | (self, view, key, operator, operand, match_all):
print(key)
if key == "output_visible":
return OutputView.find_view() != None
else:
return None
def on_close(self, view):
if view.is_scratch() and view.name() == "Output":
OutputView.position = view.... | on_query_context | identifier_name |
output.py | import sublime, sublime_plugin
def clean_layout(layout):
row_set = set()
col_set = set()
for cell in layout["cells"]:
row_set.add(cell[1])
row_set.add(cell[3])
col_set.add(cell[0])
col_set.add(cell[2])
row_set = sorted(row_set)
col_set = sorted(col_set)
rows =... |
def append(self, text):
OutputView.content += text
self.run_command("output_view_append", { "text" : text })
def append_finish_message(self, command, working_dir, return_code, elapsed_time):
if return_code != 0:
templ = "[Finished in {:.2f}s with exit code {}]\n"
... | OutputView.content = ""
self.run_command("output_view_clear") | identifier_body |
output.py | import sublime, sublime_plugin
def clean_layout(layout):
row_set = set()
col_set = set()
for cell in layout["cells"]:
row_set.add(cell[1])
row_set.add(cell[3])
col_set.add(cell[0])
col_set.add(cell[2])
row_set = sorted(row_set)
col_set = sorted(col_set)
rows =... | def close():
window = sublime.active_window()
for view in window.views():
if view.is_scratch() and view.name() == "Output":
OutputView(view)._close()
@staticmethod
def find_view():
window = sublime.active_window()
for view in window.views():
... | window.run_command("close_by_index", {"group": group, "index": index})
self._collapse(group)
OutputView.id = None
@staticmethod | random_line_split |
new-room.ts | import { Component } from '@angular/core';
import {
IonicPage,
NavParams,
ViewController,
} from 'ionic-angular';
import {
Validators,
FormBuilder,
FormGroup,
} from '@angular/forms';
import {
RoomsProvider,
} from '../../providers/providers';
@IonicPage()
@Component({
selector: 'page-new-room',
te... | () {
this.form = this.formBuilder.group({
name: ['', Validators.required],
code: ['', Validators.required],
// default: [false, Validators.required]
});
}
submit() {
// clear warnings
this.isCodeTaken = false;
// uuper case code string
this.form.value.code = this.form.val... | initForm | identifier_name |
new-room.ts | import { Component } from '@angular/core';
import {
IonicPage,
NavParams,
ViewController,
} from 'ionic-angular';
import {
Validators,
FormBuilder,
FormGroup,
} from '@angular/forms';
import {
RoomsProvider,
} from '../../providers/providers';
@IonicPage()
@Component({
selector: 'page-new-room',
te... |
initForm() {
this.form = this.formBuilder.group({
name: ['', Validators.required],
code: ['', Validators.required],
// default: [false, Validators.required]
});
}
submit() {
// clear warnings
this.isCodeTaken = false;
// uuper case code string
this.form.value.code = t... | { } | identifier_body |
new-room.ts | import { Component } from '@angular/core';
import {
IonicPage,
NavParams,
ViewController,
} from 'ionic-angular';
import {
Validators,
FormBuilder,
FormGroup,
} from '@angular/forms';
import {
RoomsProvider,
} from '../../providers/providers';
@IonicPage()
@Component({
selector: 'page-new-room',
te... |
close() {
this.viewCtrl.dismiss();
}
} | });
} | random_line_split |
mn-langs-en.js | /**
* TinyMCE 3.x language strings
*
* Loaded only when external plugins are added to TinyMCE.
*/
( function() {
var main = {}, lang = 'en';
if ( typeof tinyMCEPreInit !== 'undefined' && tinyMCEPreInit.ref.language !== 'en' ) |
main[lang] = {
common: {
edit_confirm: "Do you want to use the WYSIWYG mode for this textarea?",
apply: "Apply",
insert: "Insert",
update: "Update",
cancel: "Cancel",
close: "Close",
browse: "Browse",
class_name: "Class",
not_set: "-- Not set --",
clipboard_msg: "Copy/Cut/Paste is not... | {
lang = tinyMCEPreInit.ref.language;
} | conditional_block |
mn-langs-en.js | /**
* TinyMCE 3.x language strings
*
* Loaded only when external plugins are added to TinyMCE.
*/
( function() {
var main = {}, lang = 'en';
if ( typeof tinyMCEPreInit !== 'undefined' && tinyMCEPreInit.ref.language !== 'en' ) {
lang = tinyMCEPreInit.ref.language;
}
main[lang] = {
common: {
edit_confirm... | cell: "Cell"
},
autosave: {
unload_msg: "The changes you made will be lost if you navigate away from this page."
},
fullscreen: {
desc: "Toggle fullscreen mode (Alt + Shift + G)"
},
media: {
desc: "Insert / edit embedded media",
edit: "Edit embedded media"
},
fullpage: {
desc: "Documen... | row: "Row",
col: "Column", | random_line_split |
main.rs | extern crate ncurses;
use std::io;
use std::convert::AsRef;
use ncurses::*;
const CONFIRM_STRING: &'static str = "y";
const OUTPUT_EXAMPLE: &'static str =
"Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。";
fn ex1(s: &str) | initscr();
printw(s);
refresh();
getch();
endwin();
}
fn main() {
let mylocale = LcCategory::all;
setlocale(mylocale, "zh_CN.UTF-8");
let mut input = String::new();
println!("[ncurses-rs examples]\n");
println!(" example_1. Press \"{}\" or [Enter] to run it...:", CON... | {
| identifier_name |
main.rs | extern crate ncurses;
use std::io;
use std::convert::AsRef;
use ncurses::*;
const CONFIRM_STRING: &'static str = "y";
const OUTPUT_EXAMPLE: &'static str =
"Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。";
fn ex1(s: &str) {
initscr();
printw(s); | fn main() {
let mylocale = LcCategory::all;
setlocale(mylocale, "zh_CN.UTF-8");
let mut input = String::new();
println!("[ncurses-rs examples]\n");
println!(" example_1. Press \"{}\" or [Enter] to run it...:", CONFIRM_STRING);
io::stdin().read_line(&mut input)
.ok()
.... | refresh();
getch();
endwin();
}
| random_line_split |
main.rs | extern crate ncurses;
use std::io;
use std::convert::AsRef;
use ncurses::*;
const CONFIRM_STRING: &'static str = "y";
const OUTPUT_EXAMPLE: &'static str =
"Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。";
fn ex1(s: &str) {
initsc | {
let mylocale = LcCategory::all;
setlocale(mylocale, "zh_CN.UTF-8");
let mut input = String::new();
println!("[ncurses-rs examples]\n");
println!(" example_1. Press \"{}\" or [Enter] to run it...:", CONFIRM_STRING);
io::stdin().read_line(&mut input)
.ok()
.expect("Fa... | r();
printw(s);
refresh();
getch();
endwin();
}
fn main() | identifier_body |
dates.ts | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... |
export function parseDate(rawDate: ParsableDate): Date {
return parse(rawDate);
}
export function toShortNotSoISOString(rawDate: ParsableDate): string {
const date = parseDate(rawDate);
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
export function toNotSoISOString(rawDat... | {
if (number < 10) {
return '0' + number.toString();
}
return number;
} | identifier_body |
dates.ts | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... |
return number;
}
export function parseDate(rawDate: ParsableDate): Date {
return parse(rawDate);
}
export function toShortNotSoISOString(rawDate: ParsableDate): string {
const date = parseDate(rawDate);
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
export function toNo... | {
return '0' + number.toString();
} | conditional_block |
dates.ts | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | (rawDate: ParsableDate): string {
const date = parseDate(rawDate);
return date.toISOString().replace(/\..+Z$/, '+0000');
}
export function isValidDate(date: Date): boolean {
return !isNaN(date.getTime());
}
| toNotSoISOString | identifier_name |
dates.ts | /*
* SonarQube | * Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your optio... | random_line_split | |
test_parsable.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# name: test_parsable.py
# author: Harold Bradley III
# email: harold@bradleystudio.net
# created on: 01/16/2016
#
# pylint: disable=invalid-name,no-member
"""
A unit test for ext_pylib file module's Parsable mixin class.
... | DEBUG = True
SECURE = False
DocumentRoot /var/www/example.com
LIST = first_item
LIST = second_item
"""
EMPTY_FILE = ''
def test_parsable_parse_with_existing_attribute():
"""Test Parsable setup_parsing() method on an existing attribute."""
parsable = ParsableFile()
parsable.existing = 'already exists' # p... | FILE = """This is a sample file.
This is a sample file.
This is a sample file.
DocumentRoot /var/www/google.com
This is a sample file. | random_line_split |
test_parsable.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# name: test_parsable.py
# author: Harold Bradley III
# email: harold@bradleystudio.net
# created on: 01/16/2016
#
# pylint: disable=invalid-name,no-member
"""
A unit test for ext_pylib file module's Parsable mixin class.
... | (Parsable, File):
"""Dummy class extending Parsable and File."""
FILE = """This is a sample file.
This is a sample file.
This is a sample file.
DocumentRoot /var/www/google.com
This is a sample file.
DEBUG = True
SECURE = False
DocumentRoot /var/www/example.com
LIST = first_item
LIST = second_item
"""
EMPTY_FILE... | ParsableFile | identifier_name |
test_parsable.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# name: test_parsable.py
# author: Harold Bradley III
# email: harold@bradleystudio.net
# created on: 01/16/2016
#
# pylint: disable=invalid-name,no-member
"""
A unit test for ext_pylib file module's Parsable mixin class.
... |
def test_parsable_setup_parsing():
"""Test Parsable setup_parsing() method."""
the_file = Parsable()
Parsable.read = utils.mock_read_data
the_file.data = FILE
the_file.setup_parsing({
'htdocs' : ('DocumentRoot (.*)',),
'debug' : 'DEBUG = (.*)',
'secure' : ('SECURE[ ]*=[ ]... | """Test Parsable setup_parsing() method on an existing attribute."""
parsable = ParsableFile()
parsable.existing = 'already exists' # pylint: disable=attribute-defined-outside-init
with pytest.raises(AttributeError):
parsable.setup_parsing({'existing' : '*'}) | identifier_body |
conf.py | # -*- coding: utf-8 -*-
#
# cloudtracker documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 5 12:45:40 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
... | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.pngmath']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The maste... | #needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. | random_line_split |
options.js | var expect = require('expect.js'),
options = require('../lib/options');
describe("options", function() {
describe("#firstNumberTest", function() {
it("should be true when divisble by 3", function() {
expect(options.firstNumberTest(3,3)).to.be(true);
});
it("should be false when divisble by 3... | describe("#secondNumberTest", function() {
it("should be true when divisble by 5", function() {
expect(options.secondNumberTest(5,5)).to.be(true);
});
it("should be false when divisble by 5", function() {
expect(options.secondNumberTest(8,5)).to.be(false);
});
});
describe("#noSucce... | expect(options.firstNumberTest(8,3)).to.be(false);
});
});
| random_line_split |
gen_figure_rst.py | import os
from example_builder import ExampleBuilder
RST_TEMPLATE = """
.. _%(sphinx_tag)s:
%(docstring)s
%(image_list)s
.. raw:: html
<div class="toggle_trigger"><a href="#">
**Code output:**
.. raw:: html
</a></div>
<div class="toggle_container">
.. literalinclude:: %(stdout)s
.. raw:: html
... |
EB = ExampleBuilder(source_dir, target_dir,
execute_files=plot_gallery,
contents_file='contents.txt',
dir_info_file='README.rst',
dir_footer_file='FOOTER.rst',
sphinx_tag_base='book_fig',
... | os.makedirs(target_dir) | conditional_block |
gen_figure_rst.py | import os
from example_builder import ExampleBuilder
RST_TEMPLATE = """
.. _%(sphinx_tag)s:
%(docstring)s
%(image_list)s
.. raw:: html
<div class="toggle_trigger"><a href="#">
**Code output:**
.. raw:: html
</a></div>
<div class="toggle_container">
.. literalinclude:: %(stdout)s
.. raw:: html
... | if not os.path.exists(source_dir):
os.makedirs(source_dir)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
EB = ExampleBuilder(source_dir, target_dir,
execute_files=plot_gallery,
contents_file='contents.txt',
... | try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
| random_line_split |
gen_figure_rst.py | import os
from example_builder import ExampleBuilder
RST_TEMPLATE = """
.. _%(sphinx_tag)s:
%(docstring)s
%(image_list)s
.. raw:: html
<div class="toggle_trigger"><a href="#">
**Code output:**
.. raw:: html
</a></div>
<div class="toggle_container">
.. literalinclude:: %(stdout)s
.. raw:: html
... |
def setup(app):
app.connect('builder-inited', main)
#app.add_config_value('plot_gallery', True, 'html')
| target_dir = os.path.join(app.builder.srcdir, 'book_figures')
source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples')
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
if not os.path.exists(s... | identifier_body |
gen_figure_rst.py | import os
from example_builder import ExampleBuilder
RST_TEMPLATE = """
.. _%(sphinx_tag)s:
%(docstring)s
%(image_list)s
.. raw:: html
<div class="toggle_trigger"><a href="#">
**Code output:**
.. raw:: html
</a></div>
<div class="toggle_container">
.. literalinclude:: %(stdout)s
.. raw:: html
... | (app):
target_dir = os.path.join(app.builder.srcdir, 'book_figures')
source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples')
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
if not os.pa... | main | identifier_name |
session.spec.ts | import { expect } from 'chai';
import * as deepFreeze from 'deep-freeze';
import {actionsEnums} from '../common/actionsEnums'
import {sessionReducer} from './session'
import { UserProfile } from '../model/userProfile'
import { LoginEntity } from '../model/login'
describe('sessionReducer', () => {
describe('#handlePe... | }
}
};
// Act
const finalState = sessionReducer(initialState, action);
// Assert
expect(finalState).not.to.be.undefined;
expect(finalState.isUserLoggedIn).to.be.true;
expect(finalState.userProfile.fullname).to.be.equal(userFullname)
expect(finalState.u... | succeeded : true,
userProfile : {
fullname : userFullname,
role : role | random_line_split |
hc_domimplementationfeaturexml.js | /*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY; wi... | nction runTest() {
hc_domimplementationfeaturexml();
}
| var success;
if(checkInitialization(builder, "hc_domimplementationfeaturexml") != null) return;
var doc;
var domImpl;
var state;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "hc_staff");
domImpl = doc... | identifier_body |
hc_domimplementationfeaturexml.js | /*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY; wi... |
return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_domimplementationfeaturexml";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// ... | argetURI() { | identifier_name |
hc_domimplementationfeaturexml.js | /*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY; wi... | /**
*
Retrieve the entire DOM document and invoke its
"getImplementation()" method. This should create a
DOMImplementation object whose "hasFeature(feature,
version)" method is invoked with "feature" equal to "html" or "xml".
The method should return a boolean "true".
* @author Curt Arnold
* @see http:... | setUpPageStatus = 'complete';
}
}
| conditional_block |
hc_domimplementationfeaturexml.js | /*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY; wi... |
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_domimplementationfeaturexml";
}
var docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing f... |
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/ | random_line_split |
MotivationBtnView.js | define([ 'backbone', 'metro', 'util' ], function(Backbone, Metro, Util) {
var MotivationBtnView = Backbone.View.extend({
className: 'motivation-btn-view menu-btn',
events: {
'click': 'toggle',
'mouseover': 'over',
'mouseout': 'out',
},
initialize: function(){
//ensure correct scope
_.... | }, 2000);
},
drawAssignedSection: function() {
$.get('api/elements/sections', {id: this.param.assign}, function(data){
Backbone.trigger('MapView:drawSampleAssignedSection', data);
});
},
drawAugmentedSection: function() {
$.get('api/elements/sections', {id: this.param.augment}, function(da... | Backbone.trigger('MapView:drawSampleGPSPoint', data);
}); | random_line_split |
plot_caustic_3d.py | import numpy as np
import sys
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
if len(sys.argv) != 2:
print "Correct usage: $ %s caustic_file" % sys.argv[1]
exit(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
rows = np.loadtxt(sys.argv[1])
rs = np.array(zip(*cols)[-1... |
plt.show()
| ax.scatter([term_x], [term_y], [term_z], c="r") | conditional_block |
plot_caustic_3d.py | import numpy as np
import sys |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
if len(sys.argv) != 2:
print "Correct usage: $ %s caustic_file" % sys.argv[1]
exit(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
rows = np.loadtxt(sys.argv[1])
rs = np.array(zip(*cols)[-1])
max_r = np.max(rs)
for row ... | random_line_split | |
geo_mutagenesis.py | __author__ = 'Matteo'
__doc__='''This could be made into a handy mutagenesis library if I had time.'''
from Bio.Seq import Seq,MutableSeq
from Bio import SeqIO
from Bio.Alphabet import IUPAC
from difflib import Differ
def Gthg01471():
ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCAT... |
if __name__ == "main":
pass | filepath="Gthg_from_embl_pfamed.gb"
genome = list(SeqIO.parse(open(filepath, "rU"), "genbank"))
z=genome[0].seq[2885410:2887572].reverse_complement().translate(to_stop=1)
x=genome[0].seq[2885410:2887572].reverse_complement().tomutable()
print(x.pop(1748-1))
y=x.toseq().translate(to_stop=1)
print... | identifier_body |
geo_mutagenesis.py | __author__ = 'Matteo'
__doc__='''This could be made into a handy mutagenesis library if I had time.'''
from Bio.Seq import Seq,MutableSeq
from Bio import SeqIO
from Bio.Alphabet import IUPAC
from difflib import Differ
def Gthg01471():
ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCAT... | x=genome[0].seq[2885410:2887572].reverse_complement().tomutable()
print(x.pop(1748-1))
y=x.toseq().translate(to_stop=1)
print(z)
print(y)
print(list(Differ().compare(str(z),str(y))))
print(len(z),len(y))
if __name__ == "main":
pass | z=genome[0].seq[2885410:2887572].reverse_complement().translate(to_stop=1) | random_line_split |
geo_mutagenesis.py | __author__ = 'Matteo'
__doc__='''This could be made into a handy mutagenesis library if I had time.'''
from Bio.Seq import Seq,MutableSeq
from Bio import SeqIO
from Bio.Alphabet import IUPAC
from difflib import Differ
def Gthg01471():
ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCAT... |
print(ori.translate())
print(mut.toseq().translate())
def Gthg04369():
filepath="Gthg_from_embl_pfamed.gb"
genome = list(SeqIO.parse(open(filepath, "rU"), "genbank"))
z=genome[0].seq[3583975:3585290].translate(to_stop=1)
x=genome[0].seq[3583975:3585290].tomutable()
print(x.pop(895-1))
... | print(mut[v-1]+a[i])
mut[v-1]=b[i] | conditional_block |
geo_mutagenesis.py | __author__ = 'Matteo'
__doc__='''This could be made into a handy mutagenesis library if I had time.'''
from Bio.Seq import Seq,MutableSeq
from Bio import SeqIO
from Bio.Alphabet import IUPAC
from difflib import Differ
def Gthg01471():
ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCAT... | ():
filepath="Gthg_from_embl_pfamed.gb"
genome = list(SeqIO.parse(open(filepath, "rU"), "genbank"))
z=genome[0].seq[2885410:2887572].reverse_complement().translate(to_stop=1)
x=genome[0].seq[2885410:2887572].reverse_complement().tomutable()
print(x.pop(1748-1))
y=x.toseq().translate(to_stop=1)
... | Gthg03544 | identifier_name |
header.component.spec.ts | /* tslint:disable:no-unused-variable */
| import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { TranslateService, TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { HttpModule, Http } from '@angular/http';
impor... | random_line_split | |
models.ts | import { SelectableItem, LoadableItem } from '../core/classes';
import { Company, CompanyDetail } from './contracts';
import { StorageItem } from './storage/models';
export class CompanyItem extends SelectableItem {
private _item : Company;
get item() {
return this._item;
}
set item(i : Company) {
this... | get isOpen() {
return !!this._isOpen;
}
set isOpen(val : boolean) {
this._isOpen = val;
}
}
export class CompanyDetailItem extends LoadableItem {
private _item : CompanyDetail;
private _storage : StorageItem[];
constructor(i? : CompanyDetail) {
super();
if(!!i) {
this._item = i;
... | this._item = i;
this.isOpen = false;
}
private _isOpen : boolean; | random_line_split |
models.ts | import { SelectableItem, LoadableItem } from '../core/classes';
import { Company, CompanyDetail } from './contracts';
import { StorageItem } from './storage/models';
export class CompanyItem extends SelectableItem {
private _item : Company;
get item() {
return this._item;
}
set item(i : Company) {
this... |
this.isOpen = false;
}
checkLoading() {
if(!!this._item && !!this._storage) this.isLoading = false;
else this.isLoading = true;
}
get item() {
return this._item;
}
set item(i : CompanyDetail) {
this._item = i;
this.checkLoading();
}
get storage() {
return this._storage;
}
... | {
this._item = i;
this.checkLoading();
} | conditional_block |
models.ts | import { SelectableItem, LoadableItem } from '../core/classes';
import { Company, CompanyDetail } from './contracts';
import { StorageItem } from './storage/models';
export class CompanyItem extends SelectableItem {
private _item : Company;
get item() {
return this._item;
}
set item(i : Company) {
this... |
private _isOpen : boolean;
get isOpen() {
return !!this._isOpen;
}
set isOpen(val : boolean) {
this._isOpen = val;
}
}
export class CompanyDetailItem extends LoadableItem {
private _item : CompanyDetail;
private _storage : StorageItem[];
constructor(i? : CompanyDetail) {
super();
if(!!... | {
super();
this._item = i;
this.isOpen = false;
} | identifier_body |
models.ts | import { SelectableItem, LoadableItem } from '../core/classes';
import { Company, CompanyDetail } from './contracts';
import { StorageItem } from './storage/models';
export class CompanyItem extends SelectableItem {
private _item : Company;
get item() {
return this._item;
}
set item(i : Company) {
this... | () {
if(!!this._item && !!this._storage) this.isLoading = false;
else this.isLoading = true;
}
get item() {
return this._item;
}
set item(i : CompanyDetail) {
this._item = i;
this.checkLoading();
}
get storage() {
return this._storage;
}
set storage(list : StorageItem[]) {
th... | checkLoading | identifier_name |
category.server.model.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');
/**
* Article Schema
*/
var CategorySchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
defaul... |
link: {
type: String,
default: '',
trim: true
},
sourceImage: {
type: String,
default: '',
trim: true
},
sourceName: {
type: String,
default: '',
trim: true
},
// items: [{type: Schema.Types.ObjectId,ref: 'Item'}]
// user: {
// type: Schema.ObjectId,
// ref... | }, | random_line_split |
dialogs.py | # -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*-
# -*- coding: UTF-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms... | (gtk.MessageDialog):
def __init__(self, message, parent=None, close_on_response=True,
secondary_text=None):
gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message)
b = self.action_area.get_children()[0]
b.set_name('... | ErrorDialog | identifier_name |
dialogs.py | # -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*-
# -*- coding: UTF-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms... | gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
self.label = gtk.Label(message)
self.vbox.pack_start(self.label, True, True, 6)
self.label.show()
self.bar = gtk.ProgressBar()
self.bar.show()
self.vbox.pack_end(self.bar, True, True, 6)
... | gtk.Dialog.__init__(self, title, parent, | random_line_split |
dialogs.py | # -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*-
# -*- coding: UTF-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms... |
def _format_secondary_text_backport(self, secondary_text):
self.set_markup('<span weight="bold" size="larger">%s</span>'
'\n\n%s' % (self.message, secondary_text))
def run(self):
# can't run a recursive mainloop, because that mucks with
# twisted's reactor.
... | gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message)
b = self.action_area.get_children()[0]
b.set_name('ok_button')
self.message = message
if close_on_response:
self.connect("response", lambda self, response: self.... | identifier_body |
dialogs.py | # -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*-
# -*- coding: UTF-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms... | text += '</small>'
info = gtk.Label(text)
self.vbox.pack_start(info)
info.set_use_markup(True)
info.set_selectable(True)
info.set_justify(gtk.JUSTIFY_FILL)
info.set_line_wrap(True)
info.show()
def showConnectionErrorDialog(failure, info, parent=None):
... | t += ' %s\n' % author
| conditional_block |
borrowck-preserve-box-in-discr.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 ... | @F {f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x)));
x = @F {f: ~4};
debug!("ptr::to_unsafe_ptr(*b_x) = %x",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_eq!(**b_x, 3);
assert!(ptr::to_un... | struct F { f: ~int }
pub fn main() {
let mut x = @F {f: ~3};
match x { | random_line_split |
borrowck-preserve-box-in-discr.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 ... |
}
}
| {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x)));
x = @F {f: ~4};
debug!("ptr::to_unsafe_ptr(*b_x) = %x",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_eq!(**b_x, 3);
assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr:... | conditional_block |
borrowck-preserve-box-in-discr.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 ... | () {
let mut x = @F {f: ~3};
match x {
@F {f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x)));
x = @F {f: ~4};
debug!("ptr::to_unsafe_ptr(*b_x) = %x",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
a... | main | identifier_name |
3da51a88205a_ckan_api_key_constraint.py | """ckan api key constraint
Revision ID: 3da51a88205a
Revises: 46c3f68e950a
Create Date: 2014-04-01 11:33:01.394220
"""
# revision identifiers, used by Alembic.
revision = '3da51a88205a'
down_revision = '46c3f68e950a'
from alembic import op
import sqlalchemy as sa
def upgrade():
|
def downgrade():
op.drop_constraint('ckan_api_uq', 'user')
| query = '''UPDATE "user"
SET ckan_api=null
WHERE id IN (SELECT id
FROM (SELECT id, row_number() over (partition BY ckan_api ORDER BY id) AS rnum
FROM "user") t
WHERE t.rnum > 1);
'''
op.execute(query)
op.... | identifier_body |
3da51a88205a_ckan_api_key_constraint.py | """ckan api key constraint
Revision ID: 3da51a88205a
Revises: 46c3f68e950a
Create Date: 2014-04-01 11:33:01.394220
"""
# revision identifiers, used by Alembic.
revision = '3da51a88205a'
down_revision = '46c3f68e950a'
from alembic import op
import sqlalchemy as sa
def | ():
query = '''UPDATE "user"
SET ckan_api=null
WHERE id IN (SELECT id
FROM (SELECT id, row_number() over (partition BY ckan_api ORDER BY id) AS rnum
FROM "user") t
WHERE t.rnum > 1);
'''
op.execute(query)... | upgrade | identifier_name |
3da51a88205a_ckan_api_key_constraint.py | """ckan api key constraint
Revision ID: 3da51a88205a
Revises: 46c3f68e950a
Create Date: 2014-04-01 11:33:01.394220
"""
# revision identifiers, used by Alembic.
revision = '3da51a88205a'
down_revision = '46c3f68e950a'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = '''UPDATE "user"
... |
def downgrade():
op.drop_constraint('ckan_api_uq', 'user') | FROM "user") t
WHERE t.rnum > 1);
'''
op.execute(query)
op.create_unique_constraint('ckan_api_uq', 'user', ['ckan_api']) | random_line_split |
state.rs | use specs::{Component, VecStorage};
use specs_derive::*;
use super::intent::{AttackType, DefendType, XAxis, YAxis};
use super::Facing;
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum HitType {
Chopped,
Sliced,
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum Action {
Idle,
Move { x: XAxi... | pub direction: Facing,
pub length: u32,
pub ticks: u32,
} | random_line_split | |
state.rs | use specs::{Component, VecStorage};
use specs_derive::*;
use super::intent::{AttackType, DefendType, XAxis, YAxis};
use super::Facing;
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum | {
Chopped,
Sliced,
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum Action {
Idle,
Move { x: XAxis, y: YAxis },
Attack(AttackType),
AttackRecovery,
Defend(DefendType),
Hit(HitType),
Death(String),
Dead,
Entrance,
}
impl Action {
pub fn is_attack(&self) -> bool {... | HitType | identifier_name |
state.rs | use specs::{Component, VecStorage};
use specs_derive::*;
use super::intent::{AttackType, DefendType, XAxis, YAxis};
use super::Facing;
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum HitType {
Chopped,
Sliced,
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum Action {
Idle,
Move { x: XAxi... | else {
false
}
}
pub fn is_throw_dagger(&self) -> bool {
if let Action::Attack(AttackType::ThrowDagger) = self {
true
} else {
false
}
}
}
impl Default for Action {
fn default() -> Action {
Action::Entrance
}
}
#[derive(... | {
true
} | conditional_block |
eclipse_gen.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import pkg... | (IdeGen):
@classmethod
def register_options(cls, register):
super(EclipseGen, cls).register_options(register)
register('--version', choices=sorted(list(_VERSIONS.keys())), default='3.6',
help='The Eclipse version the project configuration should be generated for.')
def __init__(self, *args,... | EclipseGen | identifier_name |
eclipse_gen.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import pkg... |
configured_project = TemplateData(
name=self.project_name,
java=TemplateData(
jdk=self.java_jdk,
language_level=('1.%d' % self.java_language_level)
),
python=project.has_python,
scala=project.has_scala and not project.skip_scala,
source_bases=source_bases.values... | for source_set in project.py_sources:
pythonpaths.append(create_source_template(linked_folder_id(source_set)))
for source_set in project.py_libs:
lib_path = source_set.path if source_set.path.endswith('.egg') else '%s/' % source_set.path
pythonpaths.append(create_source_template(linked_fol... | conditional_block |
eclipse_gen.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import pkg... | language_level=('1.%d' % self.java_language_level)
),
python=project.has_python,
scala=project.has_scala and not project.skip_scala,
source_bases=source_bases.values(),
pythonpaths=pythonpaths,
debug_port=project.debug_port,
)
outdir = os.path.abspath(os.path.join(se... | configured_project = TemplateData(
name=self.project_name,
java=TemplateData(
jdk=self.java_jdk, | random_line_split |
eclipse_gen.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import pkg... |
def generate_project(self, project):
def linked_folder_id(source_set):
return source_set.source_base.replace(os.path.sep, '.')
def base_path(source_set):
return os.path.join(source_set.root_dir, source_set.source_base)
def create_source_base_template(source_set):
source_base = base_p... | super(EclipseGen, self).__init__(*args, **kwargs)
version = _VERSIONS[self.get_options().version]
self.project_template = os.path.join(_TEMPLATE_BASEDIR, 'project-%s.mustache' % version)
self.classpath_template = os.path.join(_TEMPLATE_BASEDIR, 'classpath-%s.mustache' % version)
self.apt_template = os.... | identifier_body |
play.service.spec.ts | import { PlayService } from './play.service';
describe('Play Service', () => {
let playService: PlayService;
let mockedSeed: any;
beforeAll(() => {
playService = new PlayService();
mockedSeed = [
[
{
coordinates: {x: 0, y: 0},
isAlive: false
},
{
... |
});
});
});
});
| {
expect(cell.isAlive).toBeTruthy();
} | conditional_block |
play.service.spec.ts | import { PlayService } from './play.service';
describe('Play Service', () => {
let playService: PlayService;
let mockedSeed: any;
beforeAll(() => {
playService = new PlayService();
mockedSeed = [
[
{
coordinates: {x: 0, y: 0},
isAlive: false
},
{
... | playService.getSeed().forEach(row => {
row.forEach(cell => {
if ((cell.coordinates.y >= 0 && cell.coordinates.y <= 2) && cell.coordinates.x === 1) {
expect(cell.isAlive).toBeTruthy();
}
});
});
});
}); | random_line_split | |
regions-variance-contravariant-use-contravariant.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 ... | // if 'call <= 'a, which is true, so no error.
collapse(&x, c);
fn collapse<'b>(x: &'b int, c: Contravariant<'b>) { }
}
pub fn main() {} | fn use_<'a>(c: Contravariant<'a>) {
let x = 3;
// 'b winds up being inferred to this call.
// Contravariant<'a> <: Contravariant<'call> is true | random_line_split |
regions-variance-contravariant-use-contravariant.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 ... | <'a>(c: Contravariant<'a>) {
let x = 3;
// 'b winds up being inferred to this call.
// Contravariant<'a> <: Contravariant<'call> is true
// if 'call <= 'a, which is true, so no error.
collapse(&x, c);
fn collapse<'b>(x: &'b int, c: Contravariant<'b>) { }
}
pub fn main() {}
| use_ | identifier_name |
regions-variance-contravariant-use-contravariant.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 ... |
}
pub fn main() {}
| { } | identifier_body |
htmlbaseelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance:... | (&self) -> Url {
let href = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href"))
.expect("The frozen base url is only defined for base elements \
that have a base url.");
let document = document_from_node(self);
let base = document.fallback_base_url();
... | frozen_base_url | identifier_name |
htmlbaseelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance:... | #[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElem... | }
}
| random_line_split |
htmlbaseelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance:... |
if self.upcast::<Element>().has_attribute(&atom!("href")) {
let document = document_from_node(self);
document.refresh_base_element();
}
}
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElemen... | {
return;
} | conditional_block |
htmlbaseelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance:... |
/// https://html.spec.whatwg.org/multipage/#frozen-base-url
pub fn frozen_base_url(&self) -> Url {
let href = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href"))
.expect("The frozen base url is only defined for base elements \
that have a base url.");
... | {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
} | identifier_body |
AnalyticsUtils.js | import { Map, List, fromJS } from 'immutable';
import * as _ from 'lodash';
import appPackage from '../package.json';
import { getPromotions, filterPromotions } from '../utils/marketingUtils';
const productPropertiesMap = Map({
prod_id: ['code'],
prod_name: ['name'],
prod_brand: ['brand', 'name'],
prod_categor... | const clearFilters = (dataLayer = Map({}), productsNumber = 0) =>
dataLayer
.set(LABEL.FILTER_VALUE, List())
.set(LABEL.FILTER_NAME, List())
.set(LABEL.FILTER_RESULT, productsNumber > 12 ? '12' : productsNumber.toString());
const buildReleaseVersion = (worldName = '') => `${_.snakeCase(worldName)}_${app... | return dataLayerWithResult;
};
| random_line_split |
AnalyticsUtils.js | import { Map, List, fromJS } from 'immutable';
import * as _ from 'lodash';
import appPackage from '../package.json';
import { getPromotions, filterPromotions } from '../utils/marketingUtils';
const productPropertiesMap = Map({
prod_id: ['code'],
prod_name: ['name'],
prod_brand: ['brand', 'name'],
prod_categor... |
};
const buildNavigationStore = (navigationStore = Map()) => {
let storeName = '';
if (navigationStore.size > 0) {
const storeN = navigationStore.get('name');
const storeCode = navigationStore.get('code');
storeName = `${storeCode} - ${storeN}`;
}
return Map({ navigation_store: storeName });
};
... | {
return objValue.concat(srcValue);
} | conditional_block |
interrupt.rs | use alloc::boxed::Box;
use collections::string::ToString;
use fs::{KScheme, Resource, Url, VecResource};
use system::error::Result;
pub struct InterruptScheme;
static IRQ_NAME: [&'static str; 16] = [
"Programmable Interval Timer",
"Keyboard",
"Cascade",
"Serial 2 and 4",
"Serial 1 and 3",
"... | _ => "Unknown Interrupt",
};
string.push_str(&format!("{:<6X}{:<16}{}\n", interrupt, count, description));
}
}
}
Ok(box VecResource::new("interrupt:".to_string(), string.into_bytes()))
}
} | 0x14 => "Virtualization exception",
0x1E => "Security exception", | random_line_split |
interrupt.rs | use alloc::boxed::Box;
use collections::string::ToString;
use fs::{KScheme, Resource, Url, VecResource};
use system::error::Result;
pub struct InterruptScheme;
static IRQ_NAME: [&'static str; 16] = [
"Programmable Interval Timer",
"Keyboard",
"Cascade",
"Serial 2 and 4",
"Serial 1 and 3",
"... | (&mut self, _: Url, _: usize) -> Result<Box<Resource>> {
let mut string = format!("{:<6}{:<16}{}\n", "INT", "COUNT", "DESCRIPTION");
{
let interrupts = unsafe { &mut *::env().interrupts.get() };
for interrupt in 0..interrupts.len() {
let count = interrupts[interr... | open | identifier_name |
interrupt.rs | use alloc::boxed::Box;
use collections::string::ToString;
use fs::{KScheme, Resource, Url, VecResource};
use system::error::Result;
pub struct InterruptScheme;
static IRQ_NAME: [&'static str; 16] = [
"Programmable Interval Timer",
"Keyboard",
"Cascade",
"Serial 2 and 4",
"Serial 1 and 3",
"... |
fn open(&mut self, _: Url, _: usize) -> Result<Box<Resource>> {
let mut string = format!("{:<6}{:<16}{}\n", "INT", "COUNT", "DESCRIPTION");
{
let interrupts = unsafe { &mut *::env().interrupts.get() };
for interrupt in 0..interrupts.len() {
let count = inte... | {
"interrupt"
} | identifier_body |
persistence_error.rs | // Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed... | {
/// An error that occurred when recovering from journal
#[error("error recovering from journal: {}", _0)]
Recovery(&'static str),
/// The number of inserted records didn't match the expected amount
#[error("wrong insert count: {} expect: {}", got, expect)]
WrongInsertCount {
/// The ... | ErrorKind | identifier_name |
persistence_error.rs | // Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed... |
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
kind,
backtrack: trace!(),
}
}
}
impl From<ProtoError> for Error {
fn from(e: ProtoError) -> Error {
match *e.kind() {
ProtoErrorKind::Timeout => ErrorKind::Tim... | {
fmt::Display::fmt(&self.kind, f)
} | conditional_block |
persistence_error.rs | // Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed... |
// foreign
/// An error got returned by the trust-dns-proto crate
#[error("proto error: {0}")]
Proto(#[from] ProtoError),
/// An error got returned from the rusqlite crate
#[cfg(feature = "sqlite")]
#[error("sqlite error: {0}")]
Sqlite(#[from] rusqlite::Error),
/// A request timed... | /// The number of inserted records
got: usize,
/// The number of records expected to be inserted
expect: usize,
}, | random_line_split |
persistence_error.rs | // Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed... |
}
impl From<ProtoError> for Error {
fn from(e: ProtoError) -> Error {
match *e.kind() {
ProtoErrorKind::Timeout => ErrorKind::Timeout.into(),
_ => ErrorKind::from(e).into(),
}
}
}
#[cfg(feature = "sqlite")]
impl From<rusqlite::Error> for Error {
fn from(e: rusqlite... | {
Error {
kind,
backtrack: trace!(),
}
} | identifier_body |
VelocityOverTime.py | # -*- coding: Latin-1 -*-
"""
@file VelocityOverTime.py
@author Sascha Krieg
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2008-05-29
Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent.
SUMO, Simulation of Urban MObility; see http:/... |
def plotIt(taxiId):
"""draws the chart"""
width=12 #1200px
height=9 #900px
#fetch data
route,values=fetchData(taxiId)
#check if a route exists for this vehicle
if len(route[1])<1 or len(route[3])<1:
return -1
#make nice labels
maxRoute=max((route[1][-1]),r... | """fetch the data for the given taxi"""
route=[[],[],[],[]] #route of the taxi (edge, length, edgeSimFCD(to find doubles))
values=[[],[],[],[]] #x,y1,x2,y2 (position, vFCD,vSIMFCD)
actLen=0
x=0
def getTime(s,v):
if v==0:
return 0
return s/(v/3.6)
for step ... | identifier_body |
VelocityOverTime.py | # -*- coding: Latin-1 -*-
"""
@file VelocityOverTime.py
@author Sascha Krieg
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2008-05-29
Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent.
SUMO, Simulation of Urban MObility; see http:/... | height=9 #900px
#fetch data
route,values=fetchData(taxiId)
#check if a route exists for this vehicle
if len(route[1])<1 or len(route[3])<1:
return -1
#make nice labels
maxRoute=max((route[1][-1]),route[3][-1])
minDist=(maxRoute/(width-4.5))
def makethemNice(... | width=12 #1200px | random_line_split |
VelocityOverTime.py | # -*- coding: Latin-1 -*-
"""
@file VelocityOverTime.py
@author Sascha Krieg
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2008-05-29
Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent.
SUMO, Simulation of Urban MObility; see http:/... | ():
"""plot all taxis to an folder."""
#kind of progress bar :-)
allT=len(taxis)
lastProz=0
for i in range(5,105,5):
s="%02d" %i
print s,
print "%"
for i in range(allT):
actProz=(100*i/allT)
if actProz!=lastProz and act... | plotAllTaxis | identifier_name |
VelocityOverTime.py | # -*- coding: Latin-1 -*-
"""
@file VelocityOverTime.py
@author Sascha Krieg
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2008-05-29
Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent.
SUMO, Simulation of Urban MObility; see http:/... |
#make nice labels
maxRoute=max((route[1][-1]),route[3][-1])
minDist=(maxRoute/(width-4.5))
def makethemNice(source=SOURCE_FCD):
"""create labels of the x-Axis for the FCD and simFCD chart"""
if source==SOURCE_FCD:
label=0; loc=1
elif source==SOURCE_SIMFCD:
... | return -1 | conditional_block |
index.d.ts | // Type definitions for non-npm package Node.js 14.14
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <https://github.com/Microsoft>
// DefinitelyTyped <https://github.com/DefinitelyTyped>
// Alberto Schiabel <https://github.com/jkomyno>
// Alexande... | // Marcin Kopacz <https://github.com/chyzwar>
// Trivikram Kamat <https://github.com/trivikr>
// Minh Son Nguyen <https://github.com/nguymin4>
// Junxiao Shi <https://github.com/yoursunny>
// Ilia Baryshnikov <https://github.com/qwelias>
//... | random_line_split | |
manipulando_o_dom.js | $(function() {
var resposta = $.ajax({
url:"http://localhost:8080/estados",
method: "GET",
dataType: "jsonp"//usado por estar em domínios diferentes
});
//A requisição Ajax pode demorar a retornar uma resposta
//com Promises é possível utilizar o método done() que executa
//assim que a requisição retornar u... | comboEstado.html("<option>Selecione o estado</option>")
estados.forEach(function(estado) {
//cria uma elemento 'option' e adiciona no select
var optionEstado = $("<option>").val(estado.uf).text(estado.nome);
comboEstado.append(optionEstado);
});
});
resposta.fail(function() {
alert("Erro carregan... | resposta.done(function(estados) {
var comboEstado = $("#combo-estado");
//comboEstado.empty(); | random_line_split |
thrift_util.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
from builtins import open
INCLUDE_PARSER = re.compile(r'^\s*include... | (basedirs, source, log=None):
"""Finds all thrift files included by the given thrift source.
:basedirs: A set of thrift source file base directories to look for includes in.
:source: The thrift source file to scan for includes.
:log: An optional logger
"""
all_basedirs = [os.path.dirname(source)]
all_ba... | find_includes | identifier_name |
thrift_util.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
from builtins import open
INCLUDE_PARSER = re.compile(r'^\s*include... |
return root_sources
def calculate_include_paths(targets, is_thrift_target):
"""Calculates the set of import paths for the given targets.
:targets: The targets to examine.
:is_thrift_target: A predicate to pick out thrift targets for consideration in the analysis.
:returns: Include basedirs for the target... | root_sources.difference_update(find_includes(basedirs, source, log=log)) | conditional_block |
thrift_util.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
from builtins import open
INCLUDE_PARSER = re.compile(r'^\s*include... | for basedir in all_basedirs:
include = os.path.join(basedir, capture)
if os.path.exists(include):
if log:
log.debug('{} has include {}'.format(source, include))
includes.add(include)
added = True
if not added:
raise ValueErr... | added = False | random_line_split |
thrift_util.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import re
from builtins import open
INCLUDE_PARSER = re.compile(r'^\s*include... |
def calculate_include_paths(targets, is_thrift_target):
"""Calculates the set of import paths for the given targets.
:targets: The targets to examine.
:is_thrift_target: A predicate to pick out thrift targets for consideration in the analysis.
:returns: Include basedirs for the target.
"""
basedirs = ... | """Finds the root thrift files in the graph formed by sources and their recursive includes.
:basedirs: A set of thrift source file base directories to look for includes in.
:sources: Seed thrift files to examine.
:log: An optional logger.
"""
root_sources = set(sources)
for source in sources:
root_sou... | identifier_body |
round_trip.rs | // Copyright 2019 The Servo 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... |
#[test]
fn test_phantom_data() {
struct Bar;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PeekPoke)]
struct Foo {
x: u32,
y: u32,
_marker: PhantomData<Bar>,
}
the_same(Foo {
x: 19,
y: 42,
_marker: PhantomData,
});
}
#[test]
fn test_gener... | {
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PeekPoke)]
enum BorderStyle {
None = 0,
Solid = 1,
Double = 2,
Dotted = 3,
Dashed = 4,
Hidden = 5,
Groove = 6,
Ridge = 7,
Inset = 8,
Outset = 9,
}
impl Default ... | identifier_body |
round_trip.rs | // Copyright 2019 The Servo 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... | () -> Self {
BorderStyle::None
}
}
the_same(BorderStyle::None);
the_same(BorderStyle::Solid);
the_same(BorderStyle::Double);
the_same(BorderStyle::Dotted);
the_same(BorderStyle::Dashed);
the_same(BorderStyle::Hidden);
the_same(BorderStyle::Groove);
the_same(Borde... | default | identifier_name |
round_trip.rs | // Copyright 2019 The Servo 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use peek_poke::{Pee... | // | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.