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 |
|---|---|---|---|---|
test_class_2_find_the_torsional_angle.py | #!/usr/bin/env python3
# https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle
import io
import math
import sys
import unittest
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def subtract(self, other):
x = self.x - other.x
... |
def test_0(self):
self.generalized_test('0')
| handle.close() | conditional_block |
test_class_2_find_the_torsional_angle.py | #!/usr/bin/env python3
# https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle
import io
import math
import sys
import unittest
class Vector:
def | (self, x, y, z):
self.x = x
self.y = y
self.z = z
def subtract(self, other):
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vector(x, y, z)
def dot_product(self, other):
return self.x * other.x + self.y * other.y + self.z *... | __init__ | identifier_name |
chunks.rs | use std::sync::{Arc, Mutex};
use simple_parallel;
use state::LSystem;
use super::{LProcessor, SimpleProcessor};
/// Parallel processor dividing a state into chunks to be individually iterated
/// within a pool of threads.
pub struct | {
/// The number of symbols per full chunk.
chunk_size: usize,
/// The thread pool.
pool: simple_parallel::Pool,
}
impl ChunksProcessor {
/// Try and create a new 'ChunksProcessor' instance with the given parameters.
/// Typical values:
/// - max_tasks : number of CPU logical cores
///... | ChunksProcessor | identifier_name |
chunks.rs | use std::sync::{Arc, Mutex};
use simple_parallel;
use state::LSystem;
use super::{LProcessor, SimpleProcessor};
/// Parallel processor dividing a state into chunks to be individually iterated
/// within a pool of threads.
pub struct ChunksProcessor {
/// The number of symbols per full chunk.
chunk_size: usize... | where S: Clone + Eq + Send + Sync
{
// TODO : better error handling...
fn iterate<'a>(&mut self, lsystem: &LSystem<'a, S>) -> Result<LSystem<'a, S>, String> {
// Set-up
let mut vec: Vec<Vec<S>> = Vec::new();
let state_len = lsystem.state().len();
if state_len == 0 {
... | }
}
impl<S> LProcessor<S> for ChunksProcessor | random_line_split |
chunks.rs | use std::sync::{Arc, Mutex};
use simple_parallel;
use state::LSystem;
use super::{LProcessor, SimpleProcessor};
/// Parallel processor dividing a state into chunks to be individually iterated
/// within a pool of threads.
pub struct ChunksProcessor {
/// The number of symbols per full chunk.
chunk_size: usize... |
}
| {
let mut rules = HashMapRules::new(); // algae rules
rules.set_str('A', "AB", TurtleCommand::None);
rules.set_str('B', "A", TurtleCommand::None);
let expected_sizes = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
2584, 4181, 6765, 10946... | identifier_body |
__init__.py | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... |
def _get_memory_with_ps(self, pid):
# It would be better to eventually switch to psutil,
# which should allow us to test on windows, but for now
# we'll just use ps and run on POSIX platforms.
command_list = ['ps', '-p', str(pid), '-o', 'rss']
p = Popen(command_list, stdout... | self._popen = None
self.memory_samples = [] | identifier_body |
__init__.py | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | self.environ['AWS_ACCESS_KEY_ID'] = 'access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key'
self.environ['AWS_CONFIG_FILE'] = 'no-exist-foo'
self.environ.update(environ)
self.session = create_session()
self.session.config_filename = 'no-exist-foo'
@skip_unless... |
"""
def setUp(self, **environ):
super(BaseSessionTest, self).setUp() | random_line_split |
__init__.py | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | (self):
rlist = [self._popen.stdout.fileno()]
result = select.select(rlist, [], [], 0.01)
if result[0]:
return True
return False
def cmd(self, *cmd):
"""Send a command and block until it finishes.
This method will send a command to the cmd-runner process... | is_cmd_finished | identifier_name |
__init__.py | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... |
return self._cached_clients[service_name]
def _create_stubbed_client(self, service_name, *args, **kwargs):
client = super(StubbedSession, self).create_client(
service_name, *args, **kwargs)
stubber = Stubber(client)
self._client_stubs[service_name] = stubber
ret... | client = self._create_stubbed_client(service_name, *args, **kwargs)
self._cached_clients[service_name] = client | conditional_block |
base.py | """The base command."""
from datetime import datetime
from json import dumps
from watches.util import ESClientProducer
class Base(object):
"""A base command."""
TEXT_PLAIN = 'plain/text'
JSON_APPLICATION = 'application/json'
TRANSFORM_PARAM = '--transform'
TIMESTAMP_PARAM = '--timestamp'
... | s = shards[key]
# convert shard id to number (this is how other admin REST APIs represent it)
s['shard'] = int(key)
shardsArray.append(s)
return shardsArray
else:
return shards
def nestedShardsArray(self, shards):
... | shardsArray = []
for key in shards: | random_line_split |
base.py | """The base command."""
from datetime import datetime
from json import dumps
from watches.util import ESClientProducer
class Base(object):
"""A base command."""
TEXT_PLAIN = 'plain/text'
JSON_APPLICATION = 'application/json'
TRANSFORM_PARAM = '--transform'
TIMESTAMP_PARAM = '--timestamp'
... |
return nodes
def nestedNodesShardsArray(self, nodes):
"""
Helper method to transform nodes shards array.
Subclass can override this if the default behaviour does not apply.
:param nodes:
:return:
"""
if isinstance(nodes, dict):
shardsArr... | nodesArray = []
for key in nodes:
n = nodes[key]
n['node'] = key
nodesArray.append(n)
return nodesArray | conditional_block |
base.py | """The base command."""
from datetime import datetime
from json import dumps
from watches.util import ESClientProducer
class Base(object):
"""A base command."""
TEXT_PLAIN = 'plain/text'
JSON_APPLICATION = 'application/json'
TRANSFORM_PARAM = '--transform'
TIMESTAMP_PARAM = '--timestamp'
... |
def getResponseContentType(self):
"""Response MIME type. By default we assume JSON, make sure to override if needed."""
return self.JSON_APPLICATION
def transformData(self, data):
"""
Data can be transformed before sending to client.
Currently, the only transformation ... | raise NotImplementedError('Method getData() not implemented') | identifier_body |
base.py | """The base command."""
from datetime import datetime
from json import dumps
from watches.util import ESClientProducer
class Base(object):
"""A base command."""
TEXT_PLAIN = 'plain/text'
JSON_APPLICATION = 'application/json'
TRANSFORM_PARAM = '--transform'
TIMESTAMP_PARAM = '--timestamp'
... | (self, shards):
"""
Helper method to transform shards array.
This is useful in case REST API returns shards data in an array.
:param shards:
:return:
"""
shardsArray = []
if isinstance(shards, dict):
for key in shards:
if isins... | nestedShardsArray | identifier_name |
itunes.py | # Support for the iTunes format
# Copyright 2010-2015 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following con... |
def _end_itunes_owner(self):
self.pop('publisher')
self.inpublisher = 0
self._sync_author_detail('publisher')
def _end_itunes_keywords(self):
for term in self.pop('itunes_keywords').split(','):
if term.strip():
self._addTag(term.strip(), 'http://www... | self.inpublisher = 1
self.push('publisher', 0) | identifier_body |
itunes.py | # Support for the iTunes format
# Copyright 2010-2015 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following con... | self._addTag(term.strip(), 'http://www.itunes.com/', None)
def _start_itunes_category(self, attrsD):
self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
self.push('category', 1)
def _start_itunes_image(self, attrsD):
self.push('itunes_image', 0)
if ... | self._sync_author_detail('publisher')
def _end_itunes_keywords(self):
for term in self.pop('itunes_keywords').split(','):
if term.strip(): | random_line_split |
itunes.py | # Support for the iTunes format
# Copyright 2010-2015 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following con... | (self, attrsD):
self._start_name(attrsD)
def _end_itunes_name(self):
self._end_name()
def _start_itunes_email(self, attrsD):
self._start_email(attrsD)
def _end_itunes_email(self):
self._end_email()
def _start_itunes_subtitle(self, attrsD):
self._start_subtitle... | _start_itunes_name | identifier_name |
itunes.py | # Support for the iTunes format
# Copyright 2010-2015 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following con... |
def _start_itunes_category(self, attrsD):
self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
self.push('category', 1)
def _start_itunes_image(self, attrsD):
self.push('itunes_image', 0)
if attrsD.get('href'):
self._getContext()['image'] = FeedParserDi... | self._addTag(term.strip(), 'http://www.itunes.com/', None) | conditional_block |
mod.rs | //! This module contains type definition for ECMAScript values.
//! According to the ECMA-262 specification, there are six "types"
//! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`,
//! and `Object`. Four of these are value types and do not need
//! heap allocation, while `String` and `Object` have to ... | () -> Value {
Value::Null
}
pub fn number(ptr: heap::NumberPtr) -> Value {
Value::Number(ptr)
}
pub fn boolean(ptr: heap::BooleanPtr) -> Value {
Value::Boolean(ptr)
}
pub fn string(ptr: heap::StringPtr) -> Value {
Value::String(ptr)
}
pub fn object(ptr... | null | identifier_name |
mod.rs | //! This module contains type definition for ECMAScript values.
//! According to the ECMA-262 specification, there are six "types"
//! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`,
//! and `Object`. Four of these are value types and do not need
//! heap allocation, while `String` and `Object` have to ... |
}
impl Value {
pub fn undefined() -> Value {
Value::Undefined
}
pub fn null() -> Value {
Value::Null
}
pub fn number(ptr: heap::NumberPtr) -> Value {
Value::Number(ptr)
}
pub fn boolean(ptr: heap::BooleanPtr) -> Value {
Value::Boolean(ptr)
}
pub ... | {
Value::Undefined
} | identifier_body |
mod.rs | //! This module contains type definition for ECMAScript values.
//! According to the ECMA-262 specification, there are six "types"
//! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`,
//! and `Object`. Four of these are value types and do not need
//! heap allocation, while `String` and `Object` have to ... | } else {
vec![].into_iter()
}
}
}
impl Default for Value {
fn default() -> Value {
Value::Undefined
}
}
impl Value {
pub fn undefined() -> Value {
Value::Undefined
}
pub fn null() -> Value {
Value::Null
}
pub fn number(ptr: heap::Nu... | random_line_split | |
mod.rs | //! This module contains type definition for ECMAScript values.
//! According to the ECMA-262 specification, there are six "types"
//! of objects: `undefined`, `null`, `Boolean`, `String`, `Number`,
//! and `Object`. Four of these are value types and do not need
//! heap allocation, while `String` and `Object` have to ... |
}
}
impl Default for Value {
fn default() -> Value {
Value::Undefined
}
}
impl Value {
pub fn undefined() -> Value {
Value::Undefined
}
pub fn null() -> Value {
Value::Null
}
pub fn number(ptr: heap::NumberPtr) -> Value {
Value::Number(ptr)
}
... | {
vec![].into_iter()
} | conditional_block |
metadata.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribu... |
public static isSourceTypeIsStaging(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.STAGING;
}
public static isSourceTypeIsJdbc(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.JDBC;
}
public static ... | {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.ENGINE;
} | identifier_body |
metadata.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribu... | extends AbstractHistoryEntity {
public id: string;
public description: string;
public name: string;
public sourceType: SourceType;
public source: MetadataSource;
public favorite: boolean;
public catalogs: any;
public tags: any;
public popularity: number;
public columns: MetadataColumn[];
public... | Metadata | identifier_name |
metadata.ts | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distribu... | public static isSourceTypeIsStaging(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.STAGING;
}
public static isSourceTypeIsJdbc(sourceType: SourceType) {
return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.JDBC;
}
public static is... | return _.negate(_.isNil)(sourceType)
&& sourceType === SourceType.ENGINE;
}
| random_line_split |
markdown.ts | // Meteor Imports
import { Meteor } from 'meteor/meteor';
import { MeteorComponent } from 'angular2-meteor';
// Angular Imports
import { Component, Input } from '@angular/core';
import { InjectUser } from 'angular2-meteor-accounts-ui';
import { ActivatedRoute, Router } from '@angular/router';
// Angular Ma... | () {
if(typeof this.courseId !== "undefined") {
return Roles.isInstructorFor(this.courseId);
}
else {
return false;
}
}
// Toggle to show either markdown editor or task markdown
mdeToggle() {
this.showMDE = !this.showMDE;
}
// Update new markdown
updateMarkdown() {
Colle... | isInstruct | identifier_name |
markdown.ts | // Meteor Imports
import { Meteor } from 'meteor/meteor';
import { MeteorComponent } from 'angular2-meteor';
// Angular Imports
import { Component, Input } from '@angular/core';
import { InjectUser } from 'angular2-meteor-accounts-ui';
import { ActivatedRoute, Router } from '@angular/router';
// Angular Ma... | }
ngOnInit() {
this.courseId = this.router.routerState.parent(this.route).snapshot.params['courseid'];
this.labId = this.route.snapshot.params['labid'];
}
isInstruct() {
if(typeof this.courseId !== "undefined") {
return Roles.isInstructorFor(this.courseId);
}
else {
return false;... | return "";
} | random_line_split |
markdown.ts | // Meteor Imports
import { Meteor } from 'meteor/meteor';
import { MeteorComponent } from 'angular2-meteor';
// Angular Imports
import { Component, Input } from '@angular/core';
import { InjectUser } from 'angular2-meteor-accounts-ui';
import { ActivatedRoute, Router } from '@angular/router';
// Angular Ma... |
else {
return false;
}
}
// Toggle to show either markdown editor or task markdown
mdeToggle() {
this.showMDE = !this.showMDE;
}
// Update new markdown
updateMarkdown() {
Collections.labs.update({
_id: this.labId,
"tasks.id": this.taskid
}, {
$set: {
"ta... | {
return Roles.isInstructorFor(this.courseId);
} | conditional_block |
Login.ts | import { Component } from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {UserPersonalData} from './UserPersonalData'
import {LoginService} from '../services/LoginService';
import {Http} from '@angular/http';
@Component({
selector: 'login',
templateUrl: './login.html',
styleUrls:... | () {
this.loginService.logOut().subscribe(
response => {
this.router.navigate(['/index']);
},
error => console.log('Error when trying to log out: ' + error)
);
}
}
| logOut | identifier_name |
Login.ts | import { Component } from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {UserPersonalData} from './UserPersonalData'
import {LoginService} from '../services/LoginService';
import {Http} from '@angular/http';
@Component({
selector: 'login',
templateUrl: './login.html',
styleUrls:... | export class LoginComponent {
constructor(private loginService: LoginService, private router: Router) { }
logIn(event: any, user: string, pass: string) {
event.preventDefault();
this.loginService.logIn(user, pass).subscribe(
u =>{ console.log(u);
if (this.loginService.getIsAdmin())
... | random_line_split | |
compiled.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[cfg(test)]
mod test {
use super::{boolnames, boolfnames, numnames, numfnames, stringnames, stringfnames};
#[test]
fn test_veclens() {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
... | {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), b"\x1B[0m".to_vec());
strings.insert("bold".to_string(), b"\x1B[1m".to_vec());
strings.insert("setaf".to_string(), b"\x1B[3%p1%dm".to_vec());
strings.insert("setab".to_string(), b"\x1B[4%p1%dm".to_vec());
box TermInfo {
... | identifier_body |
compiled.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | "stop_char_set_def", "subscript_characters", "superscript_characters", "these_cause_cr",
"zero_motion", "char_set_names", "key_mouse", "mouse_info", "req_mouse_pos", "get_mouse",
"set_a_foreground", "set_a_background", "pkey_plab", "device_type", "code_set_init",
"set0_des_seq", "set1_des_seq", "set2_de... | "set_bottom_margin_parm", "set_left_margin_parm", "set_right_margin_parm", "set_top_margin",
"set_top_margin_parm", "start_bit_image", "start_char_set_def", "stop_bit_image", | random_line_split |
compiled.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(boolfnames.len(), boolnames.len());
assert_eq!(numfnames.len(), numnames.len());
assert_eq!(stringfnames.len(), stringnames.len());
}
#[test]
#[ignore(reason = "no ncurses on buildbots, needs a bundled terminfo file to test against")]
fn test_parse() {
//... | test_veclens | identifier_name |
ForestTrustInformation.py | # encoding: utf-8
# module samba.dcerpc.lsa
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/lsa.so
# by generator 1.135
""" lsa DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class ForestTrustInformation(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real si... | """
S.ndr_pack(object) -> blob
NDR pack
"""
pass
def __ndr_print__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_print(object) -> None
NDR print
"""
pass
def __ndr_unpack__(self, *args, **kwargs): # real signature unk... | pass
def __ndr_pack__(self, *args, **kwargs): # real signature unknown | random_line_split |
ForestTrustInformation.py | # encoding: utf-8
# module samba.dcerpc.lsa
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/lsa.so
# by generator 1.135
""" lsa DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class ForestTrustInformation(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real si... |
def __ndr_pack__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_pack(object) -> blob
NDR pack
"""
pass
def __ndr_print__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_print(object) -> None
NDR print
"""
p... | pass | identifier_body |
ForestTrustInformation.py | # encoding: utf-8
# module samba.dcerpc.lsa
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/lsa.so
# by generator 1.135
""" lsa DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class ForestTrustInformation(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real si... | (self, *args, **kwargs): # real signature unknown
"""
S.ndr_print(object) -> None
NDR print
"""
pass
def __ndr_unpack__(self, *args, **kwargs): # real signature unknown
"""
S.ndr_unpack(class, blob, allow_remaining=False) -> None
NDR unpack
""... | __ndr_print__ | identifier_name |
index.ts | import { recordTracksEvent } from '@automattic/calypso-analytics';
import { dispatch } from '@wordpress/data';
import domReady from '@wordpress/dom-ready';
import { __ } from '@wordpress/i18n';
import { inIframe } from '../../../block-inserter-modifications/contextual-tips/utils';
import { GUTENBOARDING_LAUNCH_FLOW } f... | handled = true;
const awaitSettingsBar = setInterval( () => {
const settingsBar = document.querySelector( '.edit-post-header__settings' );
if ( ! settingsBar ) {
return;
}
clearInterval( awaitSettingsBar );
const body = document.querySelector( 'body' );
if ( ! body ) {
return;
}
const { launc... | return;
} | random_line_split |
overflowing_mul.rs | use num::arithmetic::traits::{OverflowingMul, OverflowingMulAssign};
macro_rules! impl_overflowing_mul {
($t:ident) => {
impl OverflowingMul<$t> for $t {
type Output = $t;
#[inline]
fn overflowing_mul(self, other: $t) -> ($t, bool) {
$t::overflowing_mul(... | /// Replaces `self` with `self * other`.
///
/// Returns a boolean indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred, then the wrapped value is assigned.
///
/// # Worst-case complexity
/// Co... | impl OverflowingMulAssign<$t> for $t { | random_line_split |
main.rs | #![feature(plugin)]
#![allow(dead_code)]
#![allow(unused_variables)]
// error-chain can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate chrono;
extern crate markdown;
extern crate liquid;
extern crate walkdir;
extern crate rustc_serialize;
extern crate docopt;
extern cr... | () {
use std::path::Path;
use std::fs;
let site_dir = Path::new("./blog");
let site_config_file = Path::new("./blog/config.toml");
bootstrap("blog");
assert_eq!(true, site_dir.is_dir());
assert_eq!(true, site_config_file.exists());
fs::remove_dir_all("./bl... | test_create_site | identifier_name |
main.rs | #![feature(plugin)]
#![allow(dead_code)]
#![allow(unused_variables)]
// error-chain can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate chrono;
extern crate markdown;
extern crate liquid;
extern crate walkdir;
extern crate rustc_serialize;
extern crate docopt;
extern cr... | Metadata,
Content,
WeGood,
MarkdownParseError,
NotValidSite,
IOError,
}
enum SilicaParseError {
ConfigFile,
NotASite,
Other,
}
fn watch() {
let site = Site::new();
let (tx, rx) = channel();
thread::spawn(move || {
site.watch_changes(tx.clone());
});
prin... | pub enum State { | random_line_split |
main.rs | #![feature(plugin)]
#![allow(dead_code)]
#![allow(unused_variables)]
// error-chain can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate chrono;
extern crate markdown;
extern crate liquid;
extern crate walkdir;
extern crate rustc_serialize;
extern crate docopt;
extern cr... |
Ok(())
}
// The entry point for silica. Parses command line arguments and acts accordingly
fn main() {
let args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
if let Err(ref e) = process_cmd(&args) {
use ::std::io::Wr... | {
println!("{}", USAGE);
} | conditional_block |
bookshelf.js | 'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
//... |
const bookshelf = {
VERSION: require('../package.json').version
};
const Model = (bookshelf.Model = BookshelfModel.extend(
{
_builder: builderFn,
// The `Model` constructor is referenced as a property on the `Bookshelf`
// instance, mixing in the correct `builder` method, as well as t... | {
throw new Error('Invalid knex instance');
} | conditional_block |
bookshelf.js | 'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
//... | (type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error(
'A valid target model must be defined for the ' + _.result(this, 'tableName') + ' ' + type + ' relation'
);
}
return new Relation(type, Target, options);
}
},
... | _relation | identifier_name |
bookshelf.js | 'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
//... | * }).catch(function(err) {
* console.error(err);
* });
*
* @param {Bookshelf~transactionCallback} transactionCallback
* Callback containing transaction logic. The callback should return a
* promise.
*
* @returns {Promise<mixed>}
* A promise resolv... | * }).then(function(library) {
* console.log(library.related('books').pluck('title')); | random_line_split |
bookshelf.js | 'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
//... |
});
/**
* @member Bookshelf#knex
* @memberOf Bookshelf
* @type {Knex}
* @description
* A reference to the {@link http://knexjs.org Knex.js} instance being used by Bookshelf.
*/
bookshelf.knex = knex;
function builderFn(tableNameOrBuilder) {
let builder = null;
if (_.isString(tableN... | {
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
if (!process.browser) {
require(plugin)(this, options);
}
}
} else ... | identifier_body |
reporter.express.js | /*!
* Copyright(c) 2014 Jan Blaha
*/
/*globals $data */
var async = require("async"),
express = require('express'),
_ = require("underscore"),
path = require("path"),
odata_server = require('odata-server'),
q = require("q"),
bodyParser = require("body-parser"),
cookieParser = require('c... | {
if (reporter.options.httpsPort)
reporter.logger.info("jsreport server successfully started on https port: " + reporter.options.httpsPort);
if (reporter.options.httpPort)
reporter.logger.info("jsreport server successfully started on http port: " + reporter.opti... | gStart() | identifier_name |
reporter.express.js | /*!
* Copyright(c) 2014 Jan Blaha
*/
/*globals $data */
var async = require("async"),
express = require('express'),
_ = require("underscore"),
path = require("path"),
odata_server = require('odata-server'),
q = require("q"),
bodyParser = require("body-parser"),
cookieParser = require('c... | if (definition.options.app) {
reporter.logger.info("Configuring routes for existing express app.");
configureExpressApp(app, reporter, definition);
logStart();
return;
}
reporter.logger.info("Creating default express app.");
configureExpre... | if (reporter.options.httpsPort)
reporter.logger.info("jsreport server successfully started on https port: " + reporter.options.httpsPort);
if (reporter.options.httpPort)
reporter.logger.info("jsreport server successfully started on http port: " + reporter.options... | identifier_body |
reporter.express.js | /*!
* Copyright(c) 2014 Jan Blaha
*/
/*globals $data */
var async = require("async"),
express = require('express'),
_ = require("underscore"),
path = require("path"),
odata_server = require('odata-server'),
q = require("q"),
bodyParser = require("body-parser"),
cookieParser = require('c... | app.use(cors());
reporter.emit("before-express-configure", app);
routes(app, reporter);
reporter.emit("express-configure", app);
};
module.exports = function(reporter, definition) {
reporter.express = {};
var app = definition.options.app;
if (!app) {
app = express();
}
... | app.set('views', path.join(__dirname, '../public/views'));
app.engine('html', require('ejs').renderFile);
app.use(multer({ dest: reporter.options.tempDirectory})); | random_line_split |
urls.py | """djangochat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | urlpatterns = [
url(r'^', include('chatdemo.urls')),
url(r'^admin/', admin.site.urls),
] | random_line_split | |
http.py | # coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Prot... |
else:
yield wait(agent.nextAccess - now)
returnValue(agent)
def removeAgent(self, agent):
self.agents.remove(agent)
class DNSCachingResolver(Resolver):
"""
subclass Resolver to add dns caching mechanism
"""
clear_interval = 1 * 60 * 60
def __init__(s... | returnValue(agent) | conditional_block |
http.py | # coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Prot... | (object):
def __init__(self, agent, retryLimit=1):
self._agent = agent
self.loggedin = False
self.retryLimit = retryLimit
def login(self):
raise NotImplementedError("Must Implement the login method.")
def testLogin(self, content):
raise NotImplementedError("Must Im... | LoginAgent | identifier_name |
http.py | # coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Prot... | class DNSCachingResolver(Resolver):
"""
subclass Resolver to add dns caching mechanism
"""
clear_interval = 1 * 60 * 60
def __init__(self, *args, **kwargs):
Resolver.__init__(self, *args, **kwargs)
self.clear_cache()
def clear_cache(self):
self.cached_url = {}
... | random_line_split | |
http.py | # coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Prot... |
def addAgent(self, agent):
t = random.uniform(self.minTimeInterval,
self.maxTimeInterval)
agent.nextAccess = time.time() + t
if self.defers:
d = self.defers[0]
del self.defers[0]
task.deferLater(reactor, t, d.callback, agent)
... | self.agents.append(agent)
self.idleAgents.append(agent)
agent.nextAccess = 0
agent.pool = self | identifier_body |
test_nde_And.py | from unittest.mock import MagicMock, Mock
from unittest import TestCase
from PartyProblemSimulator.BooleanEquation.BooleanNode import BooleanNode
from PartyProblemSimulator.BooleanEquation.AndNode import AndNode
class aBooleanNode(BooleanNode): # pragma: no cover
""" This class is a boolean node. """
def say(... | nde._lhs_child = fake_true_child
nde._rhs_child = fake_true_child
self.assertTrue(nde.evaluate({}))
# 0 AND 0
nde._lhs_child = fake_false_child
nde._rhs_child = fake_false_child
self.assertFalse(nde.evaluate({}))
# 1 AND 0
nde._lhs_child = fake_t... | # 1 AND 1 | random_line_split |
test_nde_And.py | from unittest.mock import MagicMock, Mock
from unittest import TestCase
from PartyProblemSimulator.BooleanEquation.BooleanNode import BooleanNode
from PartyProblemSimulator.BooleanEquation.AndNode import AndNode
class aBooleanNode(BooleanNode): # pragma: no cover
""" This class is a boolean node. """
def say(... | """ Tests the AndNode class. """
def test_evaluation(self):
""" Test the evaluation of the and function. """
fake_true_child = Mock() # A child to return true.
fake_false_child = Mock() # A child to return false.
nde = AndNode(aBooleanNode(), aBooleanNode()) # Instantiate a n... | identifier_body | |
test_nde_And.py | from unittest.mock import MagicMock, Mock
from unittest import TestCase
from PartyProblemSimulator.BooleanEquation.BooleanNode import BooleanNode
from PartyProblemSimulator.BooleanEquation.AndNode import AndNode
class aBooleanNode(BooleanNode): # pragma: no cover
""" This class is a boolean node. """
def say(... | (self):
""" Test the evaluation of the and function. """
fake_true_child = Mock() # A child to return true.
fake_false_child = Mock() # A child to return false.
nde = AndNode(aBooleanNode(), aBooleanNode()) # Instantiate a node with replaceable children.
fake_true_child.ev... | test_evaluation | identifier_name |
rustdoc.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
};
run(config);
}
/// Runs rustdoc over the given file
fn run(config: Config) {
let source_file = copy config.input_crate;
// Create an AST service from the source code
do astsrv::from_file(source_file.to_str()) |srv| {
// Just time how long it takes for the AST to become available
... | {
io::println(fmt!("error: %s", err));
return;
} | conditional_block |
rustdoc.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn time<T>(what: ~str, f: &fn() -> T) -> T {
let start = extra::time::precise_time_s();
let rv = f();
let end = extra::time::precise_time_s();
info!("time: %3.3f s %s", end - start, what);
rv
}
| {
let source_file = copy config.input_crate;
// Create an AST service from the source code
do astsrv::from_file(source_file.to_str()) |srv| {
// Just time how long it takes for the AST to become available
do time(~"wait_ast") {
do astsrv::exec(srv.clone()) |_ctxt| { }
... | identifier_body |
rustdoc.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (config: Config) {
let source_file = copy config.input_crate;
// Create an AST service from the source code
do astsrv::from_file(source_file.to_str()) |srv| {
// Just time how long it takes for the AST to become available
do time(~"wait_ast") {
do astsrv::exec(srv.clone()) |_c... | run | identifier_name |
rustdoc.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | config::usage();
return;
}
let config = match config::parse_config(args) {
Ok(config) => config,
Err(err) => {
io::println(fmt!("error: %s", err));
return;
}
};
run(config);
}
/// Runs rustdoc over the given file
fn run(config: Config) {
let sour... | let args = os::args();
if args.iter().any(|x| "-h" == *x) || args.iter().any(|x| "--help" == *x) { | random_line_split |
GenEdLookup.py | import numpy as np
import pandas as pd
import pickle
# Return 0 or 1 based on whether Course fulfills a General Education Requirement
def lookupGenEd(cNum, college):
fileName = "data/Dietrich Gen Eds.csv"
picklepath = "data\\dietrich_gen_eds.p"
try:
with open(picklepath,'rb') as file:
... | with open(picklepath,'wb') as file:
pickle.dump(gen_eds,file)
return cNum in gen_eds
'''
genEdubility = lookupGenEd(73100, "dietrich")
print("73100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(70100, "tepper")
print("70100")
print('Is Gen Ed?:', genEdub... | df = pd.read_csv(fileName,names=['Dept','Num','Title','1','2'])
gen_eds = set(df['Dept'].values)
| random_line_split |
GenEdLookup.py | import numpy as np
import pandas as pd
import pickle
# Return 0 or 1 based on whether Course fulfills a General Education Requirement
def lookupGenEd(cNum, college):
|
'''
genEdubility = lookupGenEd(73100, "dietrich")
print("73100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(70100, "tepper")
print("70100")
print('Is Gen Ed?:', genEdubility)
print()
genEdubility = lookupGenEd(15322, "scs")
print("15322")
print('Is Gen Ed?:', genEdubility)
... | fileName = "data/Dietrich Gen Eds.csv"
picklepath = "data\\dietrich_gen_eds.p"
try:
with open(picklepath,'rb') as file:
gen_eds = pickle.load(file)
except:
df = pd.read_csv(fileName,names=['Dept','Num','Title','1','2'])
gen_eds = set(df['Dept'].values)
wit... | identifier_body |
GenEdLookup.py | import numpy as np
import pandas as pd
import pickle
# Return 0 or 1 based on whether Course fulfills a General Education Requirement
def | (cNum, college):
fileName = "data/Dietrich Gen Eds.csv"
picklepath = "data\\dietrich_gen_eds.p"
try:
with open(picklepath,'rb') as file:
gen_eds = pickle.load(file)
except:
df = pd.read_csv(fileName,names=['Dept','Num','Title','1','2'])
gen_eds = set(df['Dept'... | lookupGenEd | identifier_name |
rgb24.rs | #[derive(Clone, Copy, Debug)]
pub struct Rgb24 {
pub red: u8,
pub green: u8,
pub blue: u8,
}
impl Rgb24 {
pub fn new(red: u8, green: u8, blue: u8) -> Self {
Rgb24 {
red: red,
green: green,
blue: blue,
}
}
pub fn | (self) -> u8 {
self.red
}
pub fn green(self) -> u8 {
self.green
}
pub fn blue(self) -> u8 {
self.blue
}
}
pub mod colours {
use super::*;
pub const RED: Rgb24 = Rgb24 { red: 255, green: 0, blue: 0 };
pub const GREEN: Rgb24 = Rgb24 { red: 0, green: 255, blue: 0... | red | identifier_name |
rgb24.rs | #[derive(Clone, Copy, Debug)]
pub struct Rgb24 {
pub red: u8,
pub green: u8,
pub blue: u8,
}
impl Rgb24 {
pub fn new(red: u8, green: u8, blue: u8) -> Self {
Rgb24 {
red: red,
green: green,
blue: blue,
}
}
pub fn red(self) -> u8 {
self... |
pub fn blue(self) -> u8 {
self.blue
}
}
pub mod colours {
use super::*;
pub const RED: Rgb24 = Rgb24 { red: 255, green: 0, blue: 0 };
pub const GREEN: Rgb24 = Rgb24 { red: 0, green: 255, blue: 0 };
pub const BLUE: Rgb24 = Rgb24 { red: 0, green: 0, blue: 255 };
}
| {
self.green
} | identifier_body |
main.py | import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def getCommentsForItem(itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+ite... |
def currentlyDownloading(b):
pyotherside.send('items-currently-downloading', b)
| global eventCount
global itemIDs
global responses
global getItemsCount
eventCount = 0
itemIDs[:] = []
responses[:] = []
getItemsCount = 0 | identifier_body |
main.py | import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def getCommentsForItem(itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+ite... |
if startIDFound is False:
continue
itemIDs.append(i)
if len(itemIDs) >= getItemsCount:
break
if len(itemIDs) == 0:
resetDownloader()
currentlyDownloading(False)
return
if len(itemIDs) < getItemsCount:
getIte... | startIDFound = True
continue | conditional_block |
main.py | import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def | (itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+itemID, None)
# print(item)
# print(item['kids'])
for commentID in item['kids']:
# print("inside loop. kid:", commentID)
commentID = str(commentID)
comment = firebase.get_async('/v0/it... | getCommentsForItem | identifier_name |
main.py | import pyotherside
from firebase import firebase
firebase = firebase.FirebaseApplication('https://hacker-news.firebaseio.com', None)
responses = []
getItemsCount = 0
eventCount = 0
itemIDs = []
def getCommentsForItem(itemID):
itemID = int(itemID)
itemID = str(itemID)
item = firebase.get('/v0/item/'+ite... | global itemIDs
items = str(items)
if count is None:
getItemsCount = 30
else:
getItemsCount = count
if startID is None:
itemIDs = firebase.get('/v0/'+items, None)
if len(itemIDs) < getItemsCount:
getItemsCount = len(itemIDs)
else:
allIDs = fi... | random_line_split | |
xbmc.js | angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',
command = {id: 1, jsonrpc: "2.0" };
//url = 'http://localhost:8200/... | (){
return _.cloneDeep( command );
}
function sendRequest( data ){
$log.debug("Sending " , data , " to " , url + 'jsonrpc');
return $http.post( url + 'jsonrpc' , data );
}
XBMC.sendText = function( text ){
var data = cmd();
data.params = { method: "Player.SendText", item: { text: text, done: true } };
... | cmd | identifier_name |
xbmc.js | angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',
command = {id: 1, jsonrpc: "2.0" };
//url = 'http://localhost:8200/... |
XBMC.sendText = function( text ){
var data = cmd();
data.params = { method: "Player.SendText", item: { text: text, done: true } };
return sendRequest( data );
}
XBMC.input = function( what ){
var data = cmd();
switch( what ){
case 'back':
data.method = "Input.Back";
break;
case 'left':
... | {
$log.debug("Sending " , data , " to " , url + 'jsonrpc');
return $http.post( url + 'jsonrpc' , data );
} | identifier_body |
xbmc.js | angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',
command = {id: 1, jsonrpc: "2.0" };
//url = 'http://localhost:8200/... | return sendRequest( data );
}
XBMC.input = function( what ){
var data = cmd();
switch( what ){
case 'back':
data.method = "Input.Back";
break;
case 'left':
data.method = "Input.Left";
break;
case 'right':
data.method = "Input.right";
break;
case 'up':
data.method = "Inp... | data.params = { method: "Player.SendText", item: { text: text, done: true } }; | random_line_split |
notepad_slow.py | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... |
if __name__ == "__main__":
run_notepad()
| """Run notepad and do some small stuff with it"""
start = time.time()
app = application.Application()
## for distribution we don't want to connect to anybodies application
## because we may mess up something they are working on!
#try:
# app.connect_(path = r"c:\windows\system32\notepa... | identifier_body |
notepad_slow.py | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... | app.Notepad.menu_select("File->PageSetup")
# ----- Page Setup Dialog ----
# Select the 4th combobox item
app.PageSetupDlg.SizeComboBox.select(4)
# Select the 'Letter' combobox item or the Letter
try:
app.PageSetupDlg.SizeComboBox.select("Letter")
except ValueError:
... | random_line_split | |
notepad_slow.py | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... |
# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.OK.close_click()
# ----- Page Setup Dialog ----
app.PageSetupDlg.Ok.close_click()
# type some text - note that extended characters ARE allowed
app.Notepad.Edit.set_edit_text("I am typing s\xe4me text to Notepad\r\n\r\n"
... | doc_props.OK.close_click() | conditional_block |
notepad_slow.py | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... | ():
"""Run notepad and do some small stuff with it"""
start = time.time()
app = application.Application()
## for distribution we don't want to connect to anybodies application
## because we may mess up something they are working on!
#try:
# app.connect_(path = r"c:\windows\system... | run_notepad | identifier_name |
appServerAlertsDetails.ts | ///
/// Copyright 2015 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// 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... | {
}
_module.controller('HawkularMetrics.AppServerAlertsDetailsController', AppServerAlertsDetailsController);
}
| AppServerAlertsDetailsController | identifier_name |
appServerAlertsDetails.ts | ///
/// Copyright 2015 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// 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... |
export class AppServerAlertsDetailsController {
}
_module.controller('HawkularMetrics.AppServerAlertsDetailsController', AppServerAlertsDetailsController);
} | random_line_split | |
cards.js | var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 1024,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
}
f... |
this.input.on('gameobjectdown', function (pointer, gameObject) {
// Will contain the top-most Game Object (in the display list)
this.tweens.add({
targets: gameObject,
x: { value: 1100, duration: 1500, ease: 'Power2' },
y: { value: 500, duration: 500, ease: 'Bo... | {
this.add.image(x, y, 'cards', Phaser.Math.RND.pick(frames)).setInteractive();
x += 4;
y += 4;
} | conditional_block |
cards.js | var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 1024,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
|
function create ()
{
// Create a stack of random cards
var frames = this.textures.get('cards').getFrameNames();
var x = 100;
var y = 100;
for (var i = 0; i < 64; i++)
{
this.add.image(x, y, 'cards', Phaser.Math.RND.pick(frames)).setInteractive();
x += 4;
y += 4;
... | {
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
} | identifier_body |
cards.js | var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 1024,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
}
f... | } | random_line_split | |
cards.js | var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 1024,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
}
f... | ()
{
// Create a stack of random cards
var frames = this.textures.get('cards').getFrameNames();
var x = 100;
var y = 100;
for (var i = 0; i < 64; i++)
{
this.add.image(x, y, 'cards', Phaser.Math.RND.pick(frames)).setInteractive();
x += 4;
y += 4;
}
this.inp... | create | identifier_name |
DistributedCartesianGridAI.py |
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNo... |
def getParentingRules(self):
self.notify.debug("calling getter")
rule = ("%i%s%i%s%i" % (self.startingZone, self.RuleSeparator,
self.gridSize, self.RuleSeparator,
self.gridRadius))
return [self.style, rule]
# Reparent and... | return self.cellWidth | identifier_body |
DistributedCartesianGridAI.py |
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNo... |
if not self.isValidZone(zoneId):
self.notify.warning(
"%s handleAvatarZoneChange %s: not a valid zone (%s) for pos %s" %(self.doId, av.doId, zoneId, pos))
return
# Set the location on the server.
# setLocation will update the gridParent
av.b_set... | pos = None
zoneId = useZoneId | conditional_block |
DistributedCartesianGridAI.py | from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNot... | continue
pos = av.getPos()
if ((pos[0] < 0 or pos[1] < 0) or
(pos[0] > self.cellWidth or pos[1] > self.cellWidth)):
# we are out of the bounds of this current cell
self.handleAvatarZoneChange(av)
# Do this every second, not ... | av = self.gridObjects[avId]
# handle a missing object after it is already gone?
if (av.isEmpty()):
task.setDelay(1.0)
del self.gridObjects[avId] | random_line_split |
DistributedCartesianGridAI.py |
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNo... | (self):
self.notify.debug("calling getter")
rule = ("%i%s%i%s%i" % (self.startingZone, self.RuleSeparator,
self.gridSize, self.RuleSeparator,
self.gridRadius))
return [self.style, rule]
# Reparent and setLocation on av to Distr... | getParentingRules | identifier_name |
block.py | # coding=utf-8
# Copyright 2016 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 app... | node):
for alias in node.names:
self._register_local(alias.asname or alias.name)
def visit_With(self, node):
for item in node.items:
if item.optional_vars:
self._assign_target(item.optional_vars)
self.generic_visit(node)
def _assign_target(self, target):
if isinstance(target, ... | ame or alias.name.split('.')[0])
def visit_ImportFrom(self, | conditional_block |
block.py | # coding=utf-8
# Copyright 2016 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 app... |
def __init__(self, breakvar):
self.breakvar = breakvar
class Block(object):
"""Represents a Python block such as a function or class definition."""
__metaclass__ = abc.ABCMeta
def __init__(self, parent, name):
self.root = parent.root if parent else self
self.parent = parent
self.name = name... |
class Loop(object):
"""Represents a for or while loop within a particular block.""" | random_line_split |
block.py | # coding=utf-8
# Copyright 2016 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 app... | f pop_loop(self):
self.loop_stack.pop()
def top_loop(self):
return self.loop_stack[-1]
def _resolve_global(self, writer, name):
result = self.alloc_temp()
writer.write_checked_call2(
result, 'πg.ResolveGlobal(πF, {})', self.root.intern(name))
return result
class ModuleBlock(Block):
... | Loop(breakvar)
self.loop_stack.append(loop)
return loop
de | identifier_body |
block.py | # coding=utf-8
# Copyright 2016 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 app... | disable=unused-argument
self.is_generator = True
| : # pylint: | identifier_name |
template.ts | import marked from "marked";
import slug from "slug";
import {
DocumentSectionInterface, | PluginInterface,
TypeRef
} from "../interface";
import { Plugin } from "./plugin";
export function slugTemplate() {
return (text, render) => slug(render(text)).toLowerCase();
}
export interface ITemplateData {
title: string;
type?: TypeRef;
description: string;
headers: string;
navigations: Navigation... | NavigationSectionInterface, | random_line_split |
template.ts | import marked from "marked";
import slug from "slug";
import {
DocumentSectionInterface,
NavigationSectionInterface,
PluginInterface,
TypeRef
} from "../interface";
import { Plugin } from "./plugin";
export function | () {
return (text, render) => slug(render(text)).toLowerCase();
}
export interface ITemplateData {
title: string;
type?: TypeRef;
description: string;
headers: string;
navigations: NavigationSectionInterface[];
documents: DocumentSectionInterface[];
projectPackage: any;
graphdocPackage: any;
slug: ... | slugTemplate | identifier_name |
template.ts | import marked from "marked";
import slug from "slug";
import {
DocumentSectionInterface,
NavigationSectionInterface,
PluginInterface,
TypeRef
} from "../interface";
import { Plugin } from "./plugin";
export function slugTemplate() |
export interface ITemplateData {
title: string;
type?: TypeRef;
description: string;
headers: string;
navigations: NavigationSectionInterface[];
documents: DocumentSectionInterface[];
projectPackage: any;
graphdocPackage: any;
slug: typeof slugTemplate;
}
type Headers = string[];
type Navs = Naviga... | {
return (text, render) => slug(render(text)).toLowerCase();
} | identifier_body |
top10artists.component.ts | import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import { Artist } from './../Modules/artist';
import { ArtistService } from './../Services/artist.service';
import { SongService } from '../Services/song.servi... | private height: number;
private radius: number;
private arc: any;
private labelArc: any;
private pie: any;
private color: any;
private svg: any;
constructor(private artistService: ArtistService) {
this.width = 500;
this.height = 500;
this.radius = Math.min(this.... | random_line_split | |
top10artists.component.ts | import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import { Artist } from './../Modules/artist';
import { ArtistService } from './../Services/artist.service';
import { SongService } from '../Services/song.servi... | (): any {
this.color = d3Scale.scaleOrdinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
this.arc = d3Shape.arc()
.outerRadius(this.radius - 10)
.innerRadius(0);
this.labelArc = d3Shape.arc()
.outerRadius... | initSvg | identifier_name |
top10artists.component.ts | import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import { Artist } from './../Modules/artist';
import { ArtistService } from './../Services/artist.service';
import { SongService } from '../Services/song.servi... |
} | {
let g = this.svg.selectAll(".arc")
.data(this.pie(this.artists))
.enter().append("g")
.attr("class", "arc");
g.append("path").attr("d", this.arc)
.style("fill", (d: { data: Artist }) => this.color(d.data._id));
g.append("text").attr("transform", ... | identifier_body |
nehan.tip.js | // nehan.tip.js
// Copyright(c) 2014-, Watanabe Masaki
// license: MIT
| /**
plugin name: tip
description: create link that shows popup message when clicked.
tag_name: tip
close_tag: required
attributes:
- title: tip title
example:
<tip title="this is tip title">this text is popuped when clicked.</tip>
*/
Nehan.setStyle("tip", {
"display":"inline",
"backgro... | random_line_split | |
UnZip.py | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12... |
def list(self, password=None):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
return z.namelist()
def check(self, password):
pass
def verify(self):
with zipfile.ZipFile(fs_encode(self.filename), 'r', a... | return sys.version_info[:2] >= (2, 6) | identifier_body |
UnZip.py | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12... |
@classmethod
def isUsable(cls):
return sys.version_info[:2] >= (2, 6)
def list(self, password=None):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
z.setpassword(password)
return z.namelist()
def check(self, password):
pas... | VERSION = "(python %s.%s.%s)" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) | random_line_split |
UnZip.py | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12... | (self, password):
pass
def verify(self):
with zipfile.ZipFile(fs_encode(self.filename), 'r', allowZip64=True) as z:
badfile = z.testzip()
if badfile:
raise CRCError(badfile)
else:
raise PasswordError
def extract(self, passw... | check | identifier_name |
UnZip.py | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12... |
else:
raise ArchiveError(e)
else:
self.files = z.namelist()
| raise PasswordError | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.