file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
runner.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! Useful functions for custom test framework.
//!
//! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html.
use crate::test::*;
use std::cell::RefCell;
use std::env;
/// A runner function for running general tes... | };
TestDescAndFn {
desc: case.desc.clone(),
testfn: f,
}
})
.collect();
let args = env::args().collect::<Vec<_>>();
test_main(&args, cases, None)
}
thread_local!(static FS: RefCell<Option<fail::FailScenario<'static>>> = RefCell... | })),
ref f => panic!("unexpected testfn {:?}", f), | random_line_split |
runner.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! Useful functions for custom test framework.
//!
//! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html.
use crate::test::*;
use std::cell::RefCell;
use std::env;
/// A runner function for running general tes... | ;
impl TestHook for Nope {
fn setup(&mut self) {}
fn teardown(&mut self) {}
}
struct CaseLifeWatcher<H: TestHook> {
name: String,
hook: H,
}
impl<H: TestHook + Send + 'static> CaseLifeWatcher<H> {
fn new(name: String, mut hook: H) -> CaseLifeWatcher<H> {
debug!("case start"; "name" => &na... | Nope | identifier_name |
runner.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! Useful functions for custom test framework.
//!
//! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html.
use crate::test::*;
use std::cell::RefCell;
use std::env;
/// A runner function for running general tes... |
}
struct CaseLifeWatcher<H: TestHook> {
name: String,
hook: H,
}
impl<H: TestHook + Send + 'static> CaseLifeWatcher<H> {
fn new(name: String, mut hook: H) -> CaseLifeWatcher<H> {
debug!("case start"; "name" => &name);
hook.setup();
CaseLifeWatcher { name, hook }
}
}
impl<H: T... | {} | identifier_body |
styled.rs | use ascii_canvas::AsciiView;
use std::fmt::{Debug, Formatter, Error};
use style::Style;
use super::*;
pub struct Styled {
style: Style,
content: Box<Content>
}
impl Styled {
pub fn new(style: Style, content: Box<Content>) -> Self {
Styled {
style: style,
content: content,
... | (&self) -> usize {
self.content.min_width()
}
fn emit(&self, view: &mut AsciiView) {
self.content.emit(&mut view.styled(self.style))
}
fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) {
let style = self.style;
super::into_wrap_items_map(self.conte... | min_width | identifier_name |
styled.rs | use ascii_canvas::AsciiView;
use std::fmt::{Debug, Formatter, Error};
use style::Style;
use super::*;
pub struct Styled {
style: Style,
content: Box<Content>
}
impl Styled {
pub fn new(style: Style, content: Box<Content>) -> Self {
Styled {
style: style,
content: content,
... | } | fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
fmt.debug_struct("Styled")
.field("content", &self.content)
.finish()
} | random_line_split |
styled.rs | use ascii_canvas::AsciiView;
use std::fmt::{Debug, Formatter, Error};
use style::Style;
use super::*;
pub struct Styled {
style: Style,
content: Box<Content>
}
impl Styled {
pub fn new(style: Style, content: Box<Content>) -> Self {
Styled {
style: style,
content: content,
... |
}
impl Debug for Styled {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
fmt.debug_struct("Styled")
.field("content", &self.content)
.finish()
}
}
| {
let style = self.style;
super::into_wrap_items_map(self.content,
wrap_items,
|item| Styled::new(style, item))
} | identifier_body |
main.rs | // Copyright 2016 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 ... | .chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.parse(i)
.map(|(_, i)| ((), i))
} | fn test<I>(i: I) -> Result<((), I), ()> where I: Iterator<Item = i32> {
Chain(Token(0), Token(1))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1))) | random_line_split |
main.rs | // Copyright 2016 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 ... | <I>(i: I) -> Result<((), I), ()> where I: Iterator<Item = i32> {
Chain(Token(0), Token(1))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(... | test | identifier_name |
main.rs | // Copyright 2016 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 ... | {
Chain(Token(0), Token(1))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token... | identifier_body | |
tests.js | var expect = require('expect');
var helpers = require('./helpers.js');
var validEmojiFormat = helpers.validEmojiFormat;
var getRandomBanter = helpers.getRandomBanter;
validEmojiFormatTest();
getRandomBanterTest();
function validEmojiFormatTest() {
console.log('validEmojiFormat() test');
console.log('=> should ret... | {
console.log('getRandomBanter() test');
console.log('=> should return a string');
expect(getRandomBanter()).toBeA('string');
expect(getRandomBanter()).toBeA('string');
expect(getRandomBanter()).toBeA('string');
expect(getRandomBanter()).toBeA('string');
console.log('✓ Passed test cases. \n');
}
| tRandomBanterTest() | identifier_name |
tests.js | var expect = require('expect');
var helpers = require('./helpers.js');
var validEmojiFormat = helpers.validEmojiFormat;
var getRandomBanter = helpers.getRandomBanter;
validEmojiFormatTest();
getRandomBanterTest();
function validEmojiFormatTest() | function getRandomBanterTest() {
console.log('getRandomBanter() test');
console.log('=> should return a string');
expect(getRandomBanter()).toBeA('string');
expect(getRandomBanter()).toBeA('string');
expect(getRandomBanter()).toBeA('string');
expect(getRandomBanter()).toBeA('string');
console.log('✓ Passe... | {
console.log('validEmojiFormat() test');
console.log('=> should return a valid emoji format');
expect(validEmojiFormat('heart')).toEqual(':heart:');
expect(validEmojiFormat(':heart:')).toEqual(':heart:');
expect(validEmojiFormat(':heart')).toEqual(':heart:');
expect(validEmojiFormat('heart:')).toEqual(':he... | identifier_body |
tests.js | var expect = require('expect');
var helpers = require('./helpers.js');
var validEmojiFormat = helpers.validEmojiFormat;
var getRandomBanter = helpers.getRandomBanter;
validEmojiFormatTest();
getRandomBanterTest();
function validEmojiFormatTest() {
console.log('validEmojiFormat() test');
console.log('=> should ret... | console.log('✓ Passed test cases. \n');
} | expect(getRandomBanter()).toBeA('string'); | random_line_split |
isaac.rs | // http://rosettacode.org/wiki/The_ISAAC_Cipher
// includes the XOR version of the encryption scheme
#![feature(step_by)]
use std::num::Wrapping as w;
const MSG :&'static str = "a Top Secret secret";
const KEY: &'static str = "this is my secret key";
#[cfg(not(test))]
fn main () {
let mut isaac = Isaac::new();
... |
/// XOR message
fn vernam(&mut self, msg :&[u8]) -> Vec<u8> {
msg.iter().map(|&b| (self.i_rand_ascii() ^ b))
.collect::<Vec<u8>>()
}
}
#[cfg(test)]
mod test {
use super::{Isaac, MSG, KEY};
const ENCRIPTED: [u8; 19] = [0x1C, 0x06, 0x36, 0x19, 0x0B, 0x12,
0x60, 0x23, 0x3... | {
(self.i_random() % 95 + 32) as u8
} | identifier_body |
isaac.rs | // http://rosettacode.org/wiki/The_ISAAC_Cipher
// includes the XOR version of the encryption scheme
#![feature(step_by)]
use std::num::Wrapping as w;
const MSG :&'static str = "a Top Secret secret";
const KEY: &'static str = "this is my secret key";
#[cfg(not(test))]
fn main () {
let mut isaac = Isaac::new();
... |
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
if flag {
// do a second pass to make all of the seed affect all of mm
for i in (0..256).step_by(8) {
for j in 0..8 { a_v[j] = a_v[j] + self.mm[i+j]; }
mix_v!(a_v);
... | {
// use all the information in the seed
for j in 0..8 { a_v[j] = a_v[j] + self.rand_rsl[i+j]; }
} | conditional_block |
isaac.rs | // http://rosettacode.org/wiki/The_ISAAC_Cipher
// includes the XOR version of the encryption scheme
#![feature(step_by)]
use std::num::Wrapping as w;
const MSG :&'static str = "a Top Secret secret";
const KEY: &'static str = "this is my secret key";
#[cfg(not(test))]
fn main () {
let mut isaac = Isaac::new();
... | (&mut self, seed: &str, flag: bool) {
for i in 0..256 { self.mm[i] = w(0); }
for i in 0..256 { self.rand_rsl[i] = w(0); }
for i in 0..seed.len() {
self.rand_rsl[i] = w(seed.as_bytes()[i] as u32);
}
// initialize ISAAC with seed
self.rand_init(flag);
}
... | seed | identifier_name |
isaac.rs | // http://rosettacode.org/wiki/The_ISAAC_Cipher
// includes the XOR version of the encryption scheme
#![feature(step_by)]
use std::num::Wrapping as w;
const MSG :&'static str = "a Top Secret secret";
const KEY: &'static str = "this is my secret key";
#[cfg(not(test))]
fn main () {
let mut isaac = Isaac::new();
... |
for (a, b) in encr.iter().zip(ENCRIPTED.iter()) {
assert_eq!(a, b);
}
}
#[test]
fn decrypt() {
let expected = MSG;
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&ENCRIPTED[..]);
for (&a, b) in decr.iter().... | isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes()); | random_line_split |
discover.py | # -*- coding: utf-8 -*-
#
# Discover the target host types in the subnet
#
# @author: Sreejith Kesavan <sreejithemk@gmail.com>
import arp
import oui
import ipcalc
import sys
class Discovery(object):
""" Find out the host types in the Ip range (CIDR)
NOTE: This finds mac addresses only within the subnet.
... |
except KeyboardInterrupt:
print 'Exiting...'
if __name__ == '__main__':
run() | print 'IP Address: {ip} Manufacturer: {manuf}'.format(ip=ip, manuf=manuf) | conditional_block |
discover.py | # -*- coding: utf-8 -*-
#
# Discover the target host types in the subnet
#
# @author: Sreejith Kesavan <sreejithemk@gmail.com>
import arp
import oui
import ipcalc
import sys
class Discovery(object):
""" Find out the host types in the Ip range (CIDR)
NOTE: This finds mac addresses only within the subnet.
... | ():
if len(sys.argv) < 2:
print
print 'Usage:\t\tidiscover <ip-address/cidr>'
print 'Examples:'
print '\t\tidiscover 10.73.19.0'
print '\t\tidiscover 10.74.215/24'
print
else:
addrs = sys.argv[1:]
d = Discovery()
try:
for addr ... | run | identifier_name |
discover.py | # -*- coding: utf-8 -*-
#
# Discover the target host types in the subnet
#
# @author: Sreejith Kesavan <sreejithemk@gmail.com>
import arp
import oui
import ipcalc
import sys
class Discovery(object):
""" Find out the host types in the Ip range (CIDR)
NOTE: This finds mac addresses only within the subnet.
... |
def discover(self, address):
"""
Traverse the IP subnets and return manufacturer info.
"""
network = ipcalc.Network(address)
for ip in network:
ip = str(ip)
# Ignore broadcast IP Addresses
if '/' in address and ip == str(network.broadcast... | self.__arp = arp.ARP()
self.__oui = oui.OUI() | identifier_body |
discover.py | # -*- coding: utf-8 -*-
#
# Discover the target host types in the subnet
#
# @author: Sreejith Kesavan <sreejithemk@gmail.com>
import arp
import oui
import ipcalc
import sys
class Discovery(object):
""" Find out the host types in the Ip range (CIDR)
NOTE: This finds mac addresses only within the subnet.
... | manuf = self.__oui.find_manuf(manuf_str)
if manuf:
yield (ip, manuf)
def run():
if len(sys.argv) < 2:
print
print 'Usage:\t\tidiscover <ip-address/cidr>'
print 'Examples:'
print '\t\tidiscover 10.73.19.0'
print '\t\tidisco... | mac = '0' + mac
manuf_str = mac.replace(':', '')[:6].upper() | random_line_split |
extHostDocumentsAndEditors.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
this._count++;
}
unref() {
return --this._count === 0;
}
}
export interface IExtHostModelAddedData extends IModelAddedData {
notebook?: vscode.NotebookDocument;
}
export interface IExtHostDocumentsAndEditorsDelta extends IDocumentsAndEditorsDelta {
addedDocuments?: IExtHostModelAddedData[];
}
export cl... | ref | identifier_name |
extHostDocumentsAndEditors.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
export interface IExtHostModelAddedData extends IModelAddedData {
notebook?: vscode.NotebookDocument;
}
export interface IExtHostDocumentsAndEditorsDelta extends IDocumentsAndEditorsDelta {
addedDocuments?: IExtHostModelAddedData[];
}
export class ExtHostDocumentsAndEditors implements ExtHostDocumentsAndEditors... | {
return --this._count === 0;
} | identifier_body |
extHostDocumentsAndEditors.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
activeEditor(): vscode.TextEditor | undefined;
activeEditor(internal: true): ExtHostTextEditor | undefined;
activeEditor(internal?: true): vscode.TextEditor | ExtHostTextEditor | undefined {
if (!this._activeEditorId) {
return undefined;
}
const editor = this._editors.get(this._activeEditorId);
if (inter... | }
getEditor(id: string): ExtHostTextEditor | undefined {
return this._editors.get(id);
} | random_line_split |
extHostDocumentsAndEditors.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
ref.ref();
}
}
if (delta.removedEditors) {
for (const id of delta.removedEditors) {
const editor = this._editors.get(id);
this._editors.delete(id);
if (editor) {
removedEditors.push(editor);
}
}
}
if (delta.addedEditors) {
for (const data of delta.addedEditors) {
con... | {
ref = new Reference(new ExtHostDocumentData(
this._extHostRpc.getProxy(MainContext.MainThreadDocuments),
resource,
data.lines,
data.EOL,
data.versionId,
data.modeId,
data.isDirty,
data.notebook
));
this._documents.set(resource, ref);
addedDocuments.p... | conditional_block |
utils.py | from __future__ import unicode_literals
import os
import paramiko
from django.utils import six
from reviewboard.ssh.client import SSHClient
from reviewboard.ssh.errors import (BadHostKeyError, SSHAuthenticationError,
SSHError)
from reviewboard.ssh.policy import RaiseUnknownHostKey... |
else:
raise SSHError(msg)
def register_rbssh(envvar):
"""Registers rbssh in an environment variable.
This is a convenience method for making sure that rbssh is set properly
in the environment for different tools. In some cases, we need to
specifically place it in the system envir... | raise SSHAuthenticationError | conditional_block |
utils.py | from __future__ import unicode_literals
import os
import paramiko
from django.utils import six
from reviewboard.ssh.client import SSHClient
from reviewboard.ssh.errors import (BadHostKeyError, SSHAuthenticationError,
SSHError)
from reviewboard.ssh.policy import RaiseUnknownHostKey... |
def is_ssh_uri(url):
"""Returns whether or not a URL represents an SSH connection."""
return urllib_parse(url)[0] in ssh_uri_schemes
def check_host(netloc, username=None, password=None, namespace=None):
"""
Checks if we can connect to a host with a known key.
This will raise an exception if we... | """Returns a human-readable key as a series of hex characters."""
return ':'.join(["%02x" % ord(c) for c in key.get_fingerprint()]) | identifier_body |
utils.py | from __future__ import unicode_literals
import os
import paramiko
from django.utils import six
from reviewboard.ssh.client import SSHClient
from reviewboard.ssh.errors import (BadHostKeyError, SSHAuthenticationError,
SSHError)
from reviewboard.ssh.policy import RaiseUnknownHostKey... |
if 'publickey' in allowed_types:
key = client.get_user_key()
else:
key = None
raise SSHAuthenticationError(allowed_types=allowed_types, user_key=key)
except paramiko.SSHException as e:
msg = six.text_type(e)
if msg == 'No authentication methods avail... | except paramiko.AuthenticationException as e:
# Some AuthenticationException instances have allowed_types set,
# and some don't.
allowed_types = getattr(e, 'allowed_types', []) | random_line_split |
utils.py | from __future__ import unicode_literals
import os
import paramiko
from django.utils import six
from reviewboard.ssh.client import SSHClient
from reviewboard.ssh.errors import (BadHostKeyError, SSHAuthenticationError,
SSHError)
from reviewboard.ssh.policy import RaiseUnknownHostKey... | (url):
"""Returns whether or not a URL represents an SSH connection."""
return urllib_parse(url)[0] in ssh_uri_schemes
def check_host(netloc, username=None, password=None, namespace=None):
"""
Checks if we can connect to a host with a known key.
This will raise an exception if we cannot connect t... | is_ssh_uri | identifier_name |
t8100.py | #!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without l... | # Uncomment to enable debugging output
# sensor.setDebug(True);
# output the serial number and firmware revision
print()
print("Device Description:", sensor.getDeviceDescription())
print("Device Location:", sensor.getDeviceLocation())
print()
# update and print available values every 5... | random_line_split | |
t8100.py | #!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without l... | main() | conditional_block | |
t8100.py | #!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without l... |
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# You will need to edit this example to conform to your site and your
# devices, specifically the Device Object Instance ID passed to the
# constructor, and the arguments to initMaster() that are... | print("Exiting...")
sys.exit(0) | identifier_body |
t8100.py | #!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without l... | ():
print("Exiting...")
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
# You will need to edit this example to conform to your site and your
# devices, specifically the Device Object Instance ID passed to the
# cons... | exitHandler | identifier_name |
h5utils.js | // For discussion and comments, see: http://remysharp.com/2009/01/07/html5-enabling-script/
/*@cc_on'abbr article aside audio canvas details figcaption figure footer header hgroup mark menu meter nav output progress section summary time video'.replace(/\w+/g,function(n){document.createElement(n)})@*/
var addEvent = (f... | }
});
})(); | clearInterval(sourceTimer);
document.body.className = '';
}
}, 200); | random_line_split |
near_hundred.py | #!/usr/bin/env python
"""
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.
near_hundred(93) == True | def near_hundred(n):
return 190 <= abs(n) <= 210 or 90 <= abs(n) <= 110
def test_function():
assert near_hundred(93) == True
assert near_hundred(90) == True
assert near_hundred(89) == False
assert near_hundred(110) == True
assert near_hundred(111) == False
assert near_hundred(121) == False... | near_hundred(90) == True
near_hundred(89) == False
"""
| random_line_split |
near_hundred.py | #!/usr/bin/env python
"""
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.
near_hundred(93) == True
near_hundred(90) == True
near_hundred(89) == False
"""
def near_hundred(n):
return 190 <= abs(n) <= 210 or 90 <= abs(n) <= 110
def | ():
assert near_hundred(93) == True
assert near_hundred(90) == True
assert near_hundred(89) == False
assert near_hundred(110) == True
assert near_hundred(111) == False
assert near_hundred(121) == False
assert near_hundred(0) == False
assert near_hundred(5) == False
assert near_hundre... | test_function | identifier_name |
near_hundred.py | #!/usr/bin/env python
"""
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.
near_hundred(93) == True
near_hundred(90) == True
near_hundred(89) == False
"""
def near_hundred(n):
|
def test_function():
assert near_hundred(93) == True
assert near_hundred(90) == True
assert near_hundred(89) == False
assert near_hundred(110) == True
assert near_hundred(111) == False
assert near_hundred(121) == False
assert near_hundred(0) == False
assert near_hundred(5) == False
... | return 190 <= abs(n) <= 210 or 90 <= abs(n) <= 110 | identifier_body |
near_hundred.py | #!/usr/bin/env python
"""
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.
near_hundred(93) == True
near_hundred(90) == True
near_hundred(89) == False
"""
def near_hundred(n):
return 190 <= abs(n) <= 210 or 90 <= abs(n) <= 110
def test_funct... | test_function() | conditional_block | |
truncate.filter.ts | // Copyright 2019 The Oppia Authors. 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 ap... |
if (!angular.isString(input)) {
input = String(input);
}
input = $filter('convertToPlainText')(input);
return (
input.length <= length ? input : (
input.substring(0, length - suffix.length) + suffix));
};
}]);
| {
suffix = '...';
} | conditional_block |
truncate.filter.ts | // Copyright 2019 The Oppia Authors. 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 ap... | suffix = '...';
}
if (!angular.isString(input)) {
input = String(input);
}
input = $filter('convertToPlainText')(input);
return (
input.length <= length ? input : (
input.substring(0, length - suffix.length) + suffix));
};
}]); | random_line_split | |
lib.rs | #![feature(libc)]
extern crate estimate_pi;
use estimate_pi::estimate;
#[cfg(not(target_os = "emscripten"))]
use estimate_pi::ws;
extern crate libc;
use libc::{c_double};
#[no_mangle]
pub extern "C" fn pi_est(points: c_double) -> c_double {
estimate(points)
}
#[cfg(not(target_os = "emscripten"))]
#[no_mangle]
pu... | let pi = ws_pi_est(1e6);
assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 off");
}
} | #[test]
fn ws_pi_est_test() { | random_line_split |
lib.rs | #![feature(libc)]
extern crate estimate_pi;
use estimate_pi::estimate;
#[cfg(not(target_os = "emscripten"))]
use estimate_pi::ws;
extern crate libc;
use libc::{c_double};
#[no_mangle]
pub extern "C" fn | (points: c_double) -> c_double {
estimate(points)
}
#[cfg(not(target_os = "emscripten"))]
#[no_mangle]
pub extern "C" fn ws_pi_est(points: c_double) -> c_double {
ws::estimate(points)
}
#[cfg(test)]
mod pi_est_tests {
use pi_est;
#[test]
fn pi_est_test() {
let pi = pi_est(1e6);
assert!((pi > 2.64) ... | pi_est | identifier_name |
lib.rs | #![feature(libc)]
extern crate estimate_pi;
use estimate_pi::estimate;
#[cfg(not(target_os = "emscripten"))]
use estimate_pi::ws;
extern crate libc;
use libc::{c_double};
#[no_mangle]
pub extern "C" fn pi_est(points: c_double) -> c_double |
#[cfg(not(target_os = "emscripten"))]
#[no_mangle]
pub extern "C" fn ws_pi_est(points: c_double) -> c_double {
ws::estimate(points)
}
#[cfg(test)]
mod pi_est_tests {
use pi_est;
#[test]
fn pi_est_test() {
let pi = pi_est(1e6);
assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 ... | {
estimate(points)
} | identifier_body |
structureMatcher.ts | /* tslint:disable */
import * as assign from "core-js/fn/object/assign";
import * as keys from "core-js/fn/object/keys";
import * as from from "core-js/fn/array/from";
import * as find from "core-js/fn/array/find";
import { ReactChild, ReactElement, isValidElement } from "react";
export type ElementStructure ... | for (let prop in expectedJson.props) {
const difference = compareProp(prop);
if (difference) return difference;
}
if (strict) {
const unexpectedProps = keys(actualJson.props).filter(prop => !(prop in expectedJson.props));
if (unexpectedProps.length > 0) {
r... | }
| random_line_split |
structureMatcher.ts | /* tslint:disable */
import * as assign from "core-js/fn/object/assign";
import * as keys from "core-js/fn/object/keys";
import * as from from "core-js/fn/array/from";
import * as find from "core-js/fn/array/find";
import { ReactChild, ReactElement, isValidElement } from "react";
export type ElementStructure ... | (node: any): ElementStructure | ElementStructure[] {
if (node == null) return "";
if (typeof node === "object" && "nodes" in node) node = node.nodes.length > 1 ? node.nodes : node.nodes[0];
if (Array.isArray(node)) return node.map(n => toElementStructure(n) as ElementStructure);
if (node instanceo... | toElementStructure | identifier_name |
structureMatcher.ts | /* tslint:disable */
import * as assign from "core-js/fn/object/assign";
import * as keys from "core-js/fn/object/keys";
import * as from from "core-js/fn/array/from";
import * as find from "core-js/fn/array/find";
import { ReactChild, ReactElement, isValidElement } from "react";
export type ElementStructure ... | else if (prop === "className") {
const difference = compareClasses(expectedVal, actualVal);
if (difference) return difference;
} else if (!jasmine.matchersUtil.equals(expectedVal, actualVal)) {
return `${msgPrefix} property ${prop} to equal '${jasmine.pp(expectedVal)}' `... | {
if (!expectedVal.asymmetricMatch(actualVal)) {
return `${msgPrefix} property ${prop} to match ${expectedVal.jasmineToString()} `
+ `but it was '${jasmine.pp(actualVal)}'`;
}
} | conditional_block |
structureMatcher.ts | /* tslint:disable */
import * as assign from "core-js/fn/object/assign";
import * as keys from "core-js/fn/object/keys";
import * as from from "core-js/fn/array/from";
import * as find from "core-js/fn/array/find";
import { ReactChild, ReactElement, isValidElement } from "react";
export type ElementStructure ... |
function toString(structure: ElementStructure | ElementStructure[]): string {
if (isJasmineAny(structure)) return structure.jasmineToString();
if (typeof structure === "string" || structure == null) return `text '${structure}'`;
if (Array.isArray(structure)) return "[" + structure.map... | {
let actualIndex = 0;
for (let expectedIndex = 0; expectedIndex < expectedJson.children.length; ++expectedIndex) {
const expectedChild = expectedJson.children[expectedIndex];
let found = false;
for (; !found && actualIndex < actualJson.children.length; actualInd... | identifier_body |
run_local_database.py | #!/usr/bin/env python
"""Command-line tool for starting a local Vitess database for testing.
USAGE:
$ run_local_database --port 12345 \
--topology test_keyspace/-80:test_keyspace_0,test_keyspace/80-:test_keyspace_1 \
--schema_dir /path/to/schema/dir
It will run the tool, logging to stderr. On stdout, a sm... | ' Instead, stdin was closed and the cluster will be shut down now.'
' Make sure to send the empty line instead to proactively shutdown'
' the local cluster. For example, did you forget the shutdown in'
' your test\'s tearDown()?\n' % os.path.basename(__file__))
if __name__ == '... | shards = []
for shard in topology.split(','):
m = shard_exp.match(shard)
if m:
shards.append(
vt_processes.ShardInfo(m.group(1), m.group(2), m.group(3)))
else:
sys.stderr.write('invalid --shard flag format: %s\n' % shard)
sys.exit(1)
environment.base_port = port
with loca... | identifier_body |
run_local_database.py | #!/usr/bin/env python
"""Command-line tool for starting a local Vitess database for testing.
USAGE:
$ run_local_database --port 12345 \
--topology test_keyspace/-80:test_keyspace_0,test_keyspace/80-:test_keyspace_1 \
--schema_dir /path/to/schema/dir
It will run the tool, logging to stderr. On stdout, a sm... |
environment.base_port = port
with local_database.LocalDatabase(shards, schema_dir, vschema, mysql_only) as local_db:
print json.dumps(local_db.config())
sys.stdout.flush()
try:
raw_input()
except EOFError:
sys.stderr.write(
'WARNING: %s: No empty line was received on stdin.'
... | m = shard_exp.match(shard)
if m:
shards.append(
vt_processes.ShardInfo(m.group(1), m.group(2), m.group(3)))
else:
sys.stderr.write('invalid --shard flag format: %s\n' % shard)
sys.exit(1) | conditional_block |
run_local_database.py | #!/usr/bin/env python
"""Command-line tool for starting a local Vitess database for testing.
USAGE:
$ run_local_database --port 12345 \
--topology test_keyspace/-80:test_keyspace_0,test_keyspace/80-:test_keyspace_1 \
--schema_dir /path/to/schema/dir
It will run the tool, logging to stderr. On stdout, a sm... | (port, topology, schema_dir, vschema, mysql_only):
shards = []
for shard in topology.split(','):
m = shard_exp.match(shard)
if m:
shards.append(
vt_processes.ShardInfo(m.group(1), m.group(2), m.group(3)))
else:
sys.stderr.write('invalid --shard flag format: %s\n' % shard)
sy... | main | identifier_name |
run_local_database.py | #!/usr/bin/env python
"""Command-line tool for starting a local Vitess database for testing.
USAGE:
$ run_local_database --port 12345 \
--topology test_keyspace/-80:test_keyspace_0,test_keyspace/80-:test_keyspace_1 \
--schema_dir /path/to/schema/dir
It will run the tool, logging to stderr. On stdout, a sm... | vt_processes.ShardInfo(m.group(1), m.group(2), m.group(3)))
else:
sys.stderr.write('invalid --shard flag format: %s\n' % shard)
sys.exit(1)
environment.base_port = port
with local_database.LocalDatabase(shards, schema_dir, vschema, mysql_only) as local_db:
print json.dumps(local_db.co... | if m:
shards.append( | random_line_split |
realtime.js | $(function() {
// When we're using HTTPS, use WSS too.
$('#all_messages').scrollTop($('#all_messages')[0].scrollHeight);
var to_focus = $("#message");
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.hos... | return;
}
var chat = $("#chat")
var ele = $('<li class="list-group-item"></li>')
ele.append(
'<strong>'+data.user+'</strong> : ')
ele.append(
data.message)
chat.append(ele)
$('#all_messages').scrollTop($('#all_messages')[0].... | {
//update lurkers count
lurkers = data.payload.lurkers;
lurkers_ele = document.getElementById("lurkers-count");
lurkers_ele.innerText = lurkers;
//update logged in users list
user_list = data.payload.members;
document.getElementById("... | conditional_block |
realtime.js | $(function() {
// When we're using HTTPS, use WSS too.
$('#all_messages').scrollTop($('#all_messages')[0].scrollHeight);
var to_focus = $("#message");
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.hos... | $('#all_messages').scrollTop($('#all_messages')[0].scrollHeight);
};
$("#chatform").on("submit", function(event) {
var message = {
message: $('#message').val()
}
chatsock.send(JSON.stringify(message));
$("#message").val('').focus();
return false;
... |
ele.append(
data.message)
chat.append(ele) | random_line_split |
rpc_signrawtransaction.py | 072788ac'},
]
outputs = {'mpLQjfK79b7CCV4VMJWEWAj5Mpx8Up5zxB': 0.1}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[0].signrawtransactionwithkey(rawTx, privKeys, inputs)
# 1) The transaction has a complete set of signatures
assert r... |
# 8) Two script verification errors occurred
assert 'errors' in rawTxSigned
assert_equal(len(rawTxSigned['errors']), 2) | random_line_split | |
rpc_signrawtransaction.py | 4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0},
# Invalid script
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7},
# Missing scriptPubKey
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout'... | run_test | identifier_name | |
rpc_signrawtransaction.py | 2f95050014157059c736f0202e71', 'vout': 0},
# Invalid script
{'txid': '5b8673686910442c644b1f4993d8f7753c7c8fcb5c87ee40d56eaeef25204547', 'vout': 7},
# Missing scriptPubKey
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 1},
]
... | self.successful_signing_test()
self.script_verification_error_test() | identifier_body | |
rpc_signrawtransaction.py | -pubkey scripts
{'txid': '9b907ef1e3c26fc71fe4a4b3580bc75264112f95050014157059c736f0202e71', 'vout': 0,
'scriptPubKey': '76a91460baa0f494b38ce3c940dea67f3804dc52d1fb9488ac'},
{'txid': '83a4f6a6b73660e13ee6cb3c6063fa3759c50c9b7521d0536022961898f4fb02', 'vout': 0,
'script... |
# Make sure decoderawtransaction throws if there is extra data
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].decoderawtransaction, rawTx + "00")
rawTxSigned = self.nodes[0].signrawtransactionwithkey(rawTx, privKeys, scripts)
# 3) The transaction has no complete set o... | assert_equal(decodedRawTx["vin"][i]["txid"], inp["txid"])
assert_equal(decodedRawTx["vin"][i]["vout"], inp["vout"]) | conditional_block |
no084.py | #!/usr/bin/env python
from random import choice
from python.decorators import euler_timer
SQUARES = ["GO",
"A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3",
"JAIL",
"C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3",
"FP",
"E1", "CH2", "E2", "E3", "R3",... |
def next_specific(square, next_type):
if next_type not in ["R", "U"]:
raise Exception("next_specific only intended for R and U")
# R1=5, R2=15, R3=25, R4=35
index = SQUARES.index(square)
if next_type == "R":
if 0 <= index < 5 or 35 < index:
return "R1"
elif 5 < in... | index = SQUARES.index(square)
new_index = (index - step) % len(SQUARES)
return SQUARES[new_index] | identifier_body |
no084.py | #!/usr/bin/env python
from random import choice
from python.decorators import euler_timer
SQUARES = ["GO",
"A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3",
"JAIL",
"C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3",
"FP",
"E1", "CH2", "E2", "E3", "R3",... | (size):
first_die = choice(range(1, size + 1))
second_die = choice(range(1, size + 1))
return (first_die + second_die, (first_die == second_die))
def back(square, step):
index = SQUARES.index(square)
new_index = (index - step) % len(SQUARES)
return SQUARES[new_index]
def next_specific(squar... | roll_die | identifier_name |
no084.py | #!/usr/bin/env python
from random import choice
from python.decorators import euler_timer
SQUARES = ["GO",
"A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3",
"JAIL",
"C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3",
"FP",
"E1", "CH2", "E2", "E3", "R3",... | def back(square, step):
index = SQUARES.index(square)
new_index = (index - step) % len(SQUARES)
return SQUARES[new_index]
def next_specific(square, next_type):
if next_type not in ["R", "U"]:
raise Exception("next_specific only intended for R and U")
# R1=5, R2=15, R3=25, R4=35
index ... | random_line_split | |
no084.py | #!/usr/bin/env python
from random import choice
from python.decorators import euler_timer
SQUARES = ["GO",
"A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3",
"JAIL",
"C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3",
"FP",
"E1", "CH2", "E2", "E3", "R3",... |
if landing_square == "G2J":
return ("JAIL", chance_card, chest_card)
elif landing_square in ["CC1", "CC2", "CC3"]:
# 1/16 Go, Jail
# 14/16 Stay
chest_card = (chest_card + 1) % 16
if chest_card == 0:
return ("GO", chance_card, chest_card)
elif chest_c... | return (landing_square, chance_card, chest_card) | conditional_block |
while-prelude-drop.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 i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i) != a { i += 1; }
}
| main | identifier_name |
while-prelude-drop.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 i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i) != a { i += 1; }
} | identifier_body | |
while-prelude-drop.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 s = ~"hello";
// Ensure s is non-const.
s += ~"there";
return b(s);
}
pub fn main() {
let mut i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i) != a { i += 1; }
}
| { return a; } | conditional_block |
while-prelude-drop.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[deriving(Eq)]
en... | random_line_split | |
lib.rs | ::Parser;
// The following high level functions hide the implementation
// detail of having a static list of parsers. They are intended as the
// only public interface for this crate.
pub fn parse(resource: Resource, code: &str) -> Result<ResourceInfo> {
PARSERS.parse(resource, code)
}
/// The set of registered ... | impl Run for List {
async fn run(&self) -> Result {
let list = PARSERS.list();
result::value(list)
}
}
/// Show the specifications of a parser
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub ... | pub struct List {}
#[async_trait] | random_line_split |
lib.rs | by plugins
struct Parsers {
inner: BTreeMap<String, Parser>,
}
/// A macro to dispatch methods to builtin parsers
///
/// This avoids having to do a search over the parsers's specs for matching `languages`.
macro_rules! dispatch_builtins {
($format:expr, $method:ident $(,$arg:expr)*) => {
match $forma... | {
let path = PathBuf::from("<test>");
let resource = resources::code(&path, "<id>", "<cli>", Some("Calc".to_string()));
let resource_info = parse(resource, "a = 1\nb = a * a")?;
assert!(matches!(resource_info.execute_pure, None));
assert!(!resource_info.is_pure());
assert... | identifier_body | |
lib.rs | ::Parser;
// The following high level functions hide the implementation
// detail of having a static list of parsers. They are intended as the
// only public interface for this crate.
pub fn parse(resource: Resource, code: &str) -> Result<ResourceInfo> {
PARSERS.parse(resource, code)
}
/// The set of registered ... | {}
#[async_trait]
impl Run for List {
async fn run(&self) -> Result {
let list = PARSERS.list();
result::value(list)
}
}
/// Show the specifications of a parser
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::Colo... | List | identifier_name |
lib.rs | ::Parser;
// The following high level functions hide the implementation
// detail of having a static list of parsers. They are intended as the
// only public interface for this crate.
pub fn parse(resource: Resource, code: &str) -> Result<ResourceInfo> {
PARSERS.parse(resource, code)
}
/// The set of registered ... | else {
bail!("Attempting to parse a resource that is not a `Code` resource")
};
let format = match_name(&language);
let resource_info =
if let Some(result) = dispatch_builtins!(format, parse, resource, &path, code) {
result?
} else {
... | {
(code.path.clone(), code.language.clone().unwrap_or_default())
} | conditional_block |
server.js | var express = require('express');
var path = require('path');
var fs = require('fs');
var root = './index.html';
var projects = './www';
var files = fs.readdirSync(projects);
var replacement = '';
for (var i=0;i<files.length; i++) | ;
var result = fs.readFileSync(root).toString().replace(/projects>(.*)</g, 'projects>'+replacement+'<');
fs.writeFileSync(root, result);
var app = express();
app.use(express.static(path.resolve('./')));
app.use(express.static(path.join(__dirname, 'www')));
app.get('/', function(req,res){
res.sendFile('ind... | {
replacement += '<a href="/'+files[i]+'">'+files[i]+'</a>';
} | conditional_block |
server.js | var express = require('express');
var path = require('path');
var fs = require('fs');
var root = './index.html';
var projects = './www';
var files = fs.readdirSync(projects);
var replacement = '';
for (var i=0;i<files.length; i++){
replacement += '<a href="/'+files[i]+'">'+files[i]+'</a>';
};
var result = fs.readFil... | var server = app.listen(port, function() {
console.log('Listening on port:', port);
}); | res.sendFile(req.params.project+'/index.html');
});
var port = process.env.PORT || 8000; | random_line_split |
test.js | casper.test.begin('BAS GeoMap Features site shows a home page and has 1 or more Features', 5, function suite(test) {
casper.start("https://geomap-features.web.bas.ac.uk", function() {
// Basic checks
test.assertTitle("BAS GeoMap Features", "homepage title is the one expected");
test.assertEx... | });
}); | random_line_split | |
plot.py | import matplotlib.pyplot as plt
from h5py import File
from numpy import array
def launch_plots(): # TODO set activation of different plots
| trace = fh5[route + 'trace'].value[0]
initial_position = fh5[route + 'initial_position']
final_position = fh5[route + 'final_position']
xs = array([initial_position[0], final_position[0]])
ys = array([initial_position[1], final_position[1]])
zs = array([initial_position[2... | plot3d = plt.figure('Plot 3D')
xy_plane = plt.figure('XY')
xz_plane = plt.figure('XZ')
yz_plane = plt.figure('YZ')
ax_plot3d = plot3d.add_subplot(111, projection='3d')
ax_xy = xy_plane.add_subplot(111)
ax_xz = xz_plane.add_subplot(111)
ax_yz = yz_plane.add_subplot(111)
ax_plot3d.set_titl... | identifier_body |
plot.py | import matplotlib.pyplot as plt
from h5py import File
from numpy import array
def launch_plots(): # TODO set activation of different plots
plot3d = plt.figure('Plot 3D')
xy_plane = plt.figure('XY')
xz_plane = plt.figure('XZ')
yz_plane = plt.figure('YZ')
ax_plot3d = plot3d.add_subplot(111, project... |
xy_plane.savefig('XY.jpg')
xz_plane.savefig('XZ.jpg')
yz_plane.savefig('YZ.jpg')
plt.show()
| route = '/particles/' + str(particle_count) + '/'
trace = fh5[route + 'trace'].value[0]
initial_position = fh5[route + 'initial_position']
final_position = fh5[route + 'final_position']
xs = array([initial_position[0], final_position[0]])
ys = array([initial_position[1], final_po... | conditional_block |
plot.py | import matplotlib.pyplot as plt
from h5py import File
from numpy import array
def launch_plots(): # TODO set activation of different plots
plot3d = plt.figure('Plot 3D')
xy_plane = plt.figure('XY')
xz_plane = plt.figure('XZ')
yz_plane = plt.figure('YZ')
ax_plot3d = plot3d.add_subplot(111, project... | ax_yz.set_xlabel('y')
fh5 = File('data.h5', 'r')
total_particles = len(list(fh5['/particles'])) + 1
for particle_count in range(1, total_particles):
route = '/particles/' + str(particle_count) + '/'
trace = fh5[route + 'trace'].value[0]
initial_position = fh5[route + 'initial_pos... | ax_yz.set_ylabel('z') | random_line_split |
plot.py | import matplotlib.pyplot as plt
from h5py import File
from numpy import array
def | (): # TODO set activation of different plots
plot3d = plt.figure('Plot 3D')
xy_plane = plt.figure('XY')
xz_plane = plt.figure('XZ')
yz_plane = plt.figure('YZ')
ax_plot3d = plot3d.add_subplot(111, projection='3d')
ax_xy = xy_plane.add_subplot(111)
ax_xz = xz_plane.add_subplot(111)
ax_yz ... | launch_plots | identifier_name |
projects.tsx | import * as React from 'react'
import Head from 'next/head'
import { Box, Flex, Grid, Text, Container, Heading, Link } from 'theme-ui'
import Inline from '../components/Inline'
import { Header, HeaderName, HeaderTitle } from '../components/Header'
import projects from '../constants/projects.json'
import metadata from '... | <Text as="p" sx={{ maxWidth: 'measure', marginTop: 2 }}>
{description}
</Text>
)}
<Inline gap={2} mt={2}>
{website && <Link href={website}>Website</Link>}
{website && repo && '\u00B7'}
{repo && <Link href={repo}>Repository</Link>}
</Inlin... | {description && ( | random_line_split |
pbm2jack.image.py | #!/usr/bin/env python3
"""pgm2jack
Convert a P1 pbm (monochome ascii, a.k.a. "Plain PBM") file to a
jack array (nand2tetris).
One word is 16bits in jack, so image width must be a multiple!
Copyright 2013-2016 Gavin Stewart.
You are required to give attribution to the author (Gavin Stewart) for any
use of this prog... |
def buildWord (self) :
"""buildWord - build a 16bit word MSB to LSB, left to right.
Returns a string of 16 bits.
"""
word = ''
word = self._currentBit
for i in range(1,16):
if self.hasMoreBits():
word = self._currentBit + word
... | if not len(self._nextLine):
if not self.hasMoreLines():
return False
# Shift first bit from string.
self._currentBit = self._nextLine.pop(0)
return True | identifier_body |
pbm2jack.image.py | #!/usr/bin/env python3
"""pgm2jack
Convert a P1 pbm (monochome ascii, a.k.a. "Plain PBM") file to a
jack array (nand2tetris).
One word is 16bits in jack, so image width must be a multiple!
Copyright 2013-2016 Gavin Stewart.
You are required to give attribution to the author (Gavin Stewart) for any
use of this prog... | word = ''
word = self._currentBit
for i in range(1,16):
if self.hasMoreBits():
word = self._currentBit + word
else:
word = '0' + word
return word
def formatWord (bits) :
"""Format input bit string as a 16bit 2s complement Jac... |
""" | random_line_split |
pbm2jack.image.py | #!/usr/bin/env python3
"""pgm2jack
Convert a P1 pbm (monochome ascii, a.k.a. "Plain PBM") file to a
jack array (nand2tetris).
One word is 16bits in jack, so image width must be a multiple!
Copyright 2013-2016 Gavin Stewart.
You are required to give attribution to the author (Gavin Stewart) for any
use of this prog... | (self, filename):
if not os.path.exists(filename):
sys.exit('Parser Error: Input file not found: %s' % filename)
self._fh = open(filename, mode='r')
self._currentWord = 0
self._currentBit = 0;
self._nextLine = None
self._nextBit = ''
self._explodeLin... | __init__ | identifier_name |
pbm2jack.image.py | #!/usr/bin/env python3
"""pgm2jack
Convert a P1 pbm (monochome ascii, a.k.a. "Plain PBM") file to a
jack array (nand2tetris).
One word is 16bits in jack, so image width must be a multiple!
Copyright 2013-2016 Gavin Stewart.
You are required to give attribution to the author (Gavin Stewart) for any
use of this prog... |
index = 0
while index < len(data):
outfh.write(" do i.push({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15});\n".
format(
data[index],
data[index + 1],
data[index + 2],
data[index + 3],
... | bitWord = parser.buildWord()
data[index] = formatWord(bitWord);
index += 1 | conditional_block |
attack_plaidctf.py | #!/usr/bin/env python3
import sys
import os
import deadpool_dfa
import phoenixAES
import binascii
def processinput(iblock, blocksize):
#p=b'%0*x' % (2*blocksize, iblock) # Requires python3.5
p=('%0*x' % (2*blocksize, iblock)).encode('utf8')
open('foo', 'wb').write(binascii.unhexlify(p)*4) | # Patch drmless to always return decrypted version:
if not os.path.isfile('drmless.gold'):
with open('drmless', 'rb') as finput, open('drmless.gold', 'wb') as foutput:
foutput.write(finput.read(0x6C18)+b'\x01'+finput.read()[1:])
engine=deadpool_dfa.Acquisition(targetbin='./drmless', targetdata='./drmless',... | return (None, ['-f', '-E', 'foo'])
def processoutput(output, blocksize):
return int(binascii.hexlify(output[:16]), 16)
| random_line_split |
attack_plaidctf.py | #!/usr/bin/env python3
import sys
import os
import deadpool_dfa
import phoenixAES
import binascii
def | (iblock, blocksize):
#p=b'%0*x' % (2*blocksize, iblock) # Requires python3.5
p=('%0*x' % (2*blocksize, iblock)).encode('utf8')
open('foo', 'wb').write(binascii.unhexlify(p)*4)
return (None, ['-f', '-E', 'foo'])
def processoutput(output, blocksize):
return int(binascii.hexlify(output[:16]), 16)
# ... | processinput | identifier_name |
attack_plaidctf.py | #!/usr/bin/env python3
import sys
import os
import deadpool_dfa
import phoenixAES
import binascii
def processinput(iblock, blocksize):
#p=b'%0*x' % (2*blocksize, iblock) # Requires python3.5
p=('%0*x' % (2*blocksize, iblock)).encode('utf8')
open('foo', 'wb').write(binascii.unhexlify(p)*4)
return (Non... |
engine=deadpool_dfa.Acquisition(targetbin='./drmless', targetdata='./drmless', goldendata='drmless.gold',
dfa=phoenixAES, processinput=processinput, processoutput=processoutput, maxleaf=2048, faults=[('nop', lambda x: 0x90)], verbose=2)
tracefiles_sets=engine.run()
for trace in tracefiles_sets[1]:
if phoe... | with open('drmless', 'rb') as finput, open('drmless.gold', 'wb') as foutput:
foutput.write(finput.read(0x6C18)+b'\x01'+finput.read()[1:]) | conditional_block |
attack_plaidctf.py | #!/usr/bin/env python3
import sys
import os
import deadpool_dfa
import phoenixAES
import binascii
def processinput(iblock, blocksize):
#p=b'%0*x' % (2*blocksize, iblock) # Requires python3.5
|
def processoutput(output, blocksize):
return int(binascii.hexlify(output[:16]), 16)
# Patch drmless to always return decrypted version:
if not os.path.isfile('drmless.gold'):
with open('drmless', 'rb') as finput, open('drmless.gold', 'wb') as foutput:
foutput.write(finput.read(0x6C18)+b'\x01'+finput.... | p=('%0*x' % (2*blocksize, iblock)).encode('utf8')
open('foo', 'wb').write(binascii.unhexlify(p)*4)
return (None, ['-f', '-E', 'foo']) | identifier_body |
comment.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 | use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::characterdata::CharacterData;
use crate::dom::document::Document;
use crate::dom::node::Node;
use crate... | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CommentBinding; | random_line_split |
comment.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 crate::dom::bindings::codegen::Bindings::CommentBinding;
use crate::dom::bindings::codegen::Bindings::WindowBi... | (text: DOMString, document: &Document) -> DomRoot<Comment> {
Node::reflect_node(
Box::new(Comment::new_inherited(text, document)),
document,
CommentBinding::Wrap,
)
}
pub fn Constructor(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> {
... | new | identifier_name |
test_swe_lun_eclipse.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import swisseph as swe
import unittest
class TestSweLunEclipse(unittest.TestCase):
@classmethod
def | (cls):
swe.set_ephe_path()
def test_01(self):
jd = 2454466.5
flags = swe.FLG_SWIEPH
geopos = (12.1, 49.0, 330)
rflags, tret = swe.lun_eclipse_when(jd, flags, 0)
self.assertEqual(rflags, 4)
self.assertEqual(len(tret), 10)
t1 = (2454517.6430690456, 0.... | setUpClass | identifier_name |
test_swe_lun_eclipse.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import swisseph as swe
import unittest
class TestSweLunEclipse(unittest.TestCase):
@classmethod
def setUpClass(cls):
swe.set_ephe_path()
def test_01(self):
jd = 2454466.5
flags = swe.FLG_SWIEPH
geopos = (12.1, 49.0, 330)
... |
if __name__ == '__main__':
unittest.main()
# vi: sw=4 ts=4 et
| self.assertAlmostEqual(attr[i], t1[i]) | conditional_block |
test_swe_lun_eclipse.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import swisseph as swe
import unittest
class TestSweLunEclipse(unittest.TestCase):
@classmethod
def setUpClass(cls):
swe.set_ephe_path()
def test_01(self):
jd = 2454466.5
flags = swe.FLG_SWIEPH
geopos = (12.1, 49.0, 330)
... | 2454517.6258038115, 2454517.6603509136, 2454517.525389122,
2454517.7608554545, 0.0, 0.0)
for i in range(10):
self.assertAlmostEqual(tret[i], t1[i])
tjdut = tret[0]
rflags, tret, attr = swe.lun_eclipse_when_loc(tjdut, geopos, flags)
self.asser... | random_line_split | |
test_swe_lun_eclipse.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import swisseph as swe
import unittest
class TestSweLunEclipse(unittest.TestCase):
| rflags, tret, attr = swe.lun_eclipse_when_loc(tjdut, geopos, flags)
self.assertEqual(rflags, 29584)
self.assertEqual(len(tret), 10)
t1 = (2454695.3820517384, 0.0, 2454695.316710297, 2454695.447390333,
0.0, 0.0, 2454695.2672055247, 2454695.496797575, 0.0, 0.0)
for... | @classmethod
def setUpClass(cls):
swe.set_ephe_path()
def test_01(self):
jd = 2454466.5
flags = swe.FLG_SWIEPH
geopos = (12.1, 49.0, 330)
rflags, tret = swe.lun_eclipse_when(jd, flags, 0)
self.assertEqual(rflags, 4)
self.assertEqual(len(tret), 10)
... | identifier_body |
navigation.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { NgamrsSharedModule } from '../shared/ngamrs-shared.module';
import { SideNavigationComponent } from './side-navigation/side-navigation.component';
import { StaticNavBarCompo... | export class NavigationModule {} | FormSchemaService,
FormSchemaCompiler,
FormListService
]
}) | random_line_split |
navigation.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { NgamrsSharedModule } from '../shared/ngamrs-shared.module';
import { SideNavigationComponent } from './side-navigation/side-navigation.component';
import { StaticNavBarCompo... | {}
| NavigationModule | identifier_name |
craft_output_metadata.rs | use rustc_serialize::{Encodable, Encoder};
use ops;
use package::Package;
use package_id::PackageId;
use resolver::Resolve;
use util::CraftResult;
use workspace::Workspace;
const VERSION: u32 = 1;
pub struct OutputMetadataOptions {
pub features: Vec<String>,
pub no_default_features: bool,
pub all_feature... | }
let encodable = EncodableResolve {
root: self.root.as_ref(),
nodes: self.resolve
.iter()
.map(|id| {
Node {
id: id,
dependencies: self.resolve.deps(id).collect(),
... | id: &'a PackageId,
dependencies: Vec<&'a PackageId>, | random_line_split |
craft_output_metadata.rs | use rustc_serialize::{Encodable, Encoder};
use ops;
use package::Package;
use package_id::PackageId;
use resolver::Resolve;
use util::CraftResult;
use workspace::Workspace;
const VERSION: u32 = 1;
pub struct OutputMetadataOptions {
pub features: Vec<String>,
pub no_default_features: bool,
pub all_feature... | <S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
#[derive(RustcEncodable)]
struct EncodableResolve<'a> {
root: Option<&'a PackageId>,
nodes: Vec<Node<'a>>,
}
#[derive(RustcEncodable)]
struct Node<'a> {
id: &'a PackageId,
de... | encode | identifier_name |
craft_output_metadata.rs | use rustc_serialize::{Encodable, Encoder};
use ops;
use package::Package;
use package_id::PackageId;
use resolver::Resolve;
use util::CraftResult;
use workspace::Workspace;
const VERSION: u32 = 1;
pub struct OutputMetadataOptions {
pub features: Vec<String>,
pub no_default_features: bool,
pub all_feature... |
if opt.no_deps {
metadata_no_deps(ws, opt)
} else {
metadata_full(ws, opt)
}
}
fn metadata_no_deps(ws: &Workspace, _opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
Ok(ExportInfo {
packages: ws.members().cloned().collect(),
workspace_members: ws.members().map(|... | {
bail!("metadata version {} not supported, only {} is currently supported",
opt.version,
VERSION);
} | conditional_block |
transition.py | ##############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# ... | class Transition(object):
def __init__(self, deltacloud, dom):
pass
def __repr__(self):
return self.xml | random_line_split | |
transition.py | ##############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# ... | def __init__(self, deltacloud, dom):
pass
def __repr__(self):
return self.xml | identifier_body | |
transition.py | ##############################################################################
# Copyright 2010 North Carolina State University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# ... | (self):
return self.xml
| __repr__ | identifier_name |
logging.js | let fileInfoOptions = {
name: 'file.info',
filename: 'out.log',
colorize: true,
level : 'info',
levels : {debug: 0, info : 1, warn: 2, error: 3},
colors : {debug: 'blue', info : 'green', warn: 'orange', error: 'red'},
json: true, |
let fileErrorOptions = {
name: 'file.error',
filename: 'err.log',
colorize: true,
level : 'error',
levels : {debug: 0, info : 1, warn: 2, error: 3},
colors : {debug: 'blue', info : 'green', warn: 'orange', error: 'red'},
json: true,
handleExeptions: true,
humanReadableUnhandledException: true,
};
... | handleExeptions: true,
humanReadableUnhandledException: true,
}; | random_line_split |
plot_object.py | check_integrity
class Viewable(MetaHasProps):
""" Any plot object (Data Model) which has its own View Model in the
persistence layer.
One thing to keep in mind is that a Viewable should have a single
unique representation in the persistence layer, but it might have
multiple concurrent client-side... |
def setup_events(self):
pass
def select(self, selector):
''' Query this object and all of its references for objects that
match the given selector.
Args:
selector (JSON-like) :
Returns:
seq[PlotObject]
'''
return find(self.ref... | if "__subtype__" in self.__class__.__dict__:
return {
'type': self.__view_model__,
'subtype': self.__subtype__,
'id': self._id,
}
else:
return {
'type': self.__view_model__,
'id': self._id,
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.