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 |
|---|---|---|---|---|
uploadDataAndTransform.py | #!/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen, Request, HTTPError
except ImportError:
# Fallback to Python 2
from urllib2 import urlopen, Request, HTTPError
import sys | if len(sys.argv) < 4:
print ("Usage:")
print ("\t %s input_rawData transformations_uri transformed_filename" % sys.argv[0])
exit()
input_rawData = sys.argv[1]
transformations_uri = sys.argv[2]
transformed_filename = sys.argv[3]
#endpoint = "http://localhost:8088/jarfter/webresources/jarCreator"
endpoint =... | import os
| random_line_split |
mobile_all.ts | //
// Simply includes each app's javascripts into one big package and
// requires the appropriate one based on location.pathname.
// In the beginning this will be easier for simplicity's sake, but as this
// package gets large, and we micro-optimize initial page load, we'll want
// to get more complex in how we break u... | else if (sd.PARTNER_PROFILE != null) {
return require("../apps/partner_profile/client/index.coffee")
}
},
"^/([^/]+)$": () => {
if (sd.FAIR_ORGANIZER != null) {
return require("../apps/fair_organizer/client/fair_organizer.coffee").init()
} else if (sd.PARTNER_PROFILE != null) {
return... | {
return require("../apps/profile/client.coffee")
} | conditional_block |
mobile_all.ts | //
// Simply includes each app's javascripts into one big package and
// requires the appropriate one based on location.pathname.
// In the beginning this will be easier for simplicity's sake, but as this
// package gets large, and we micro-optimize initial page load, we'll want
// to get more complex in how we break u... | // Last resort
return require("../components/layout/bootstrap.coffee")()
}
},
"^$": require("../apps/home/client/index"),
}
for (let path in routes) {
const init = routes[path]
if (location.pathname.match(path)) {
$(init)
}
} | } else { | random_line_split |
PaperSheet.js | any links and images should
// kill any other marked tokens we don't want here
const walkTokens = token => {
switch (token.type) {
case 'url':
case 'autolink':
case 'reflink':
case 'link':
case 'image':
token.type = 'text';
// Once asset system is up change to some... | () {
document.addEventListener("mousemove", this.handleMouseMove);
document.addEventListener("click", this.handleMouseClick);
}
componentWillUnmount() {
document.removeEventListener("mousemove", this.handleMouseMove);
document.removeEventListener("click", this.handleMouseClick);
}
render() {
... | componentDidMount | identifier_name |
PaperSheet.js | , any links and images should
// kill any other marked tokens we don't want here
const walkTokens = token => {
switch (token.type) {
case 'url':
case 'autolink':
case 'reflink':
case 'link':
case 'image':
token.type = 'text';
// Once asset system is up change to som... | this.handleMouseClick = e => {
if (e.pageY <= 30) { return; }
const { act, data } = useBackend(this.context);
const stamp_obj = {
x: this.state.x, y: this.state.y, r: this.state.rotate,
stamp_class: this.props.stamp_class,
stamp_icon_state: data.stamp_icon_state,
};
... | random_line_split | |
PaperSheet.js | any links and images should
// kill any other marked tokens we don't want here
const walkTokens = token => {
switch (token.type) {
case 'url':
case 'autolink':
case 'reflink':
case 'link':
case 'image':
token.type = 'text';
// Once asset system is up change to some... | const widthMax = (windowRef.clientWidth) - (
stampWidth);
const heightMax = (windowRef.clientHeight - windowRef.scrollTop) - (
stampHeight);
const radians = Math.atan2(
e.pageX - currentWidth,
e.pageY - currentHeight
);
const rotate = rotating ? (radians *... | {
let rotating;
const windowRef = document.querySelector('.Layout__content');
if (e.shiftKey) {
rotating = true;
}
if (document.getElementById("stamp"))
{
const stamp = document.getElementById("stamp");
const stampHeight = stamp.clientHeight;
const stampWidth = stamp.cli... | identifier_body |
PaperSheet.js | any links and images should
// kill any other marked tokens we don't want here
const walkTokens = token => {
switch (token.type) {
case 'url':
case 'autolink':
case 'reflink':
case 'link':
case 'image':
token.type = 'text';
// Once asset system is up change to some... |
// center offset of stamp & rotate
pauseEvent(e);
this.setState({ x: pos[0], y: pos[1], rotate: pos[2] });
};
this.handleMouseClick = e => {
if (e.pageY <= 30) { return; }
const { act, data } = useBackend(this.context);
const stamp_obj = {
x: this.state.x, y: this.st... | { return; } | conditional_block |
tsl2561.py | s+.*(\w{4})$', line)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't fi... |
def readWord(self, reg):
"""Reads a word from the I2C device"""
try:
wordval = self.i2c.readU16(reg)
newval = self.i2c.reverseByteOrder(wordval)
if (self.debug):
print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, wordval... | """ Set the gain """
if (gain != self.gain):
if (gain==1):
self.i2c.write8(0x81, 0x02) # set gain = 1X and timing = 402 mSec
if (self.debug):
print "Setting low gain"
else:
self.i2c.write8(0x81, 0x12) # set gain ... | identifier_body |
tsl2561.py | s+.*(\w{4})$', line)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't fi... | return self.errMsg()
def readU8(self, reg):
"Read an unsigned byte from the I2C device"
try:
result = self.bus.read_byte_data(self.address, reg)
if self.debug:
print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" %
(self.address, result & 0xFF, reg))
return res... | print results
return results
except IOError, err: | random_line_split |
tsl2561.py | s+.*(\w{4})$', line)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't fi... |
return result
except IOError, err:
return self.errMsg()
def readS16(self, reg, little_endian=True):
"Reads a signed 16-bit value from the I2C device"
try:
result = self.readU16(reg,little_endian)
if result > 32767: result -= 65536
return result
except IOError, err:
... | print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) | conditional_block |
tsl2561.py | s+.*(\w{4})$', line)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't fi... | (self, reg, length):
"Read a list of bytes from the I2C device"
try:
results = self.bus.read_i2c_block_data(self.address, reg, length)
if self.debug:
print ("I2C: Device 0x%02X returned the following from reg 0x%02X" %
(self.address, reg))
print results
return results
... | readList | identifier_name |
huffman2.py | #!/usr/bin/python
# -*- encoding: utf-8 -*-
import os
import marshal
import cPickle
import array
class HuffmanNode(object):
recurPrint = False
def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None):
self.L = lnode
self.R = rnode
self.p = parent
self.c = ch
... | (self, filename):
fp = open(filename, 'rb')
unpickled_root, length, array_codes = marshal.load(fp)
self.root = cPickle.loads(unpickled_root)
self.code_length = length
self.array_codes = array.array('B', array_codes)
fp.close()
def decode_as(self, filename):
d... | read | identifier_name |
huffman2.py | #!/usr/bin/python
# -*- encoding: utf-8 -*-
import os
import marshal
import cPickle
import array
class HuffmanNode(object):
recurPrint = False
def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None):
self.L = lnode
self.R = rnode
self.p = parent
self.c = ch
... | else: # bit == '0'
buff = (buff << 1)
length += 1
if length == MAX_BITS:
array_codes.extend([buff])
buff, length = 0, 0
code_length += len(code)
if length != 0:
array_codes.exten... | if bit=='1':
buff = (buff << 1) | 0x01 | random_line_split |
huffman2.py | #!/usr/bin/python
# -*- encoding: utf-8 -*-
import os
import marshal
import cPickle
import array
class HuffmanNode(object):
recurPrint = False
def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None):
self.L = lnode
self.R = rnode
self.p = parent
self.c = ch
... |
else:
return '(%s:%d)'%(self.c, self.fq)
def __cmp__(self, other):
if not isinstance(other, HuffmanNode):
return super(HuffmanNode, self).__cmp__(other)
return cmp(self.fq, other.fq)
def _pop_first_two_nodes(nodes):
if len(nodes)>1:
first=nodes.pop(0)
... | lnode = self.L if self.L else '#'
rnode = self.R if self.R else '#'
return ''.join( ('(%s:%d)'%(self.c, self.fq), str(lnode), str(rnode) ) ) | conditional_block |
huffman2.py | #!/usr/bin/python
# -*- encoding: utf-8 -*-
import os
import marshal
import cPickle
import array
class HuffmanNode(object):
recurPrint = False
def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None):
self.L = lnode
self.R = rnode
self.p = parent
self.c = ch
... |
def _decode(self):
string_buf = []
total_length = 0
node = self.root
for code in self.array_codes:
buf_length = 0
while (buf_length < MAX_BITS and total_length != self.code_length):
buf_length += 1
total_length += 1
... | if filename_or_raw_str:
if os.path.exists(filename_or_raw_str):
filename = filename_or_raw_str
self.read(filename)
else:
print '[Decoder] take \'%s\' as raw string' % filename_or_raw_str
raw_string = filename_or_raw_str
... | identifier_body |
rand_utils.rs | //! Utility functions for random functionality.
//!
//! This module provides sampling and shuffling which are used
//! within the learning modules.
use rand::{Rng, thread_rng};
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// let mut pool = &mut [1,2,3,4];
/// let sample = rand_utils::reservoir_s... | <T: Copy>(pool: &[T], reservoir_size: usize) -> Vec<T> {
assert!(pool.len() >= reservoir_size,
"Sample size is greater than total.");
let mut pool_mut = &pool[..];
let mut res = pool_mut[..reservoir_size].to_vec();
pool_mut = &pool_mut[reservoir_size..];
let mut ele_seen = reservoir_s... | reservoir_sample | identifier_name |
rand_utils.rs | //! Utility functions for random functionality.
//!
//! This module provides sampling and shuffling which are used
//! within the learning modules.
use rand::{Rng, thread_rng};
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// let mut pool = &mut [1,2,3,4];
/// let sample = rand_utils::reservoir_s... | let a = (0..10).collect::<Vec<_>>();
let b = fisher_yates(&a);
for val in a.iter() {
assert!(b.contains(val));
}
}
#[test]
fn test_in_place_fisher_yates() {
let mut a = (0..10).collect::<Vec<_>>();
in_place_fisher_yates(&mut a);
for va... | #[test]
fn test_fisher_yates() { | random_line_split |
rand_utils.rs | //! Utility functions for random functionality.
//!
//! This module provides sampling and shuffling which are used
//! within the learning modules.
use rand::{Rng, thread_rng};
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// let mut pool = &mut [1,2,3,4];
/// let sample = rand_utils::reservoir_s... |
}
res
}
/// The inside out Fisher-Yates algorithm.
///
/// # Examples
///
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// // Collect the numbers 0..5
/// let a = (0..5).collect::<Vec<_>>();
///
/// // Perform a Fisher-Yates shuffle to get a random permutation
/// let permutation = rand_... | {
res[r] = p_0;
} | conditional_block |
rand_utils.rs | //! Utility functions for random functionality.
//!
//! This module provides sampling and shuffling which are used
//! within the learning modules.
use rand::{Rng, thread_rng};
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// let mut pool = &mut [1,2,3,4];
/// let sample = rand_utils::reservoir_s... |
}
| {
let mut a = (0..10).collect::<Vec<_>>();
in_place_fisher_yates(&mut a);
for val in 0..10 {
assert!(a.contains(&val));
}
} | identifier_body |
linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by roadhump
# Copyright (c) 2014 roadhump
#
# License: MIT
#
"""This module exports the ESLint plugin class."""
import sublime
import os
import re
from SublimeLinter.lint import NodeLinter
class ESLint(NodeLinter):
... |
def split_match(self, match):
"""
Extract and return values from match.
We override this method to silent warning by .eslintignore settings.
"""
v1message = 'File ignored because of your .eslintignore file. Use --no-ignore to override.'
v2message = 'File ignored b... | """
Parse errors from linter's output.
We override this method to handle parsing eslint crashes.
"""
match = self.config_fail_regex.match(output)
if match:
return [(match, 0, None, "Error", "", match.group(0), None)]
match = self.crash_regex.match(output)
... | identifier_body |
linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by roadhump
# Copyright (c) 2014 roadhump
#
# License: MIT
#
"""This module exports the ESLint plugin class."""
import sublime
import os
import re
from SublimeLinter.lint import NodeLinter
class ESLint(NodeLinter):
... |
match = self.crash_regex.match(output)
if match:
msg = "ESLint crashed: %s" % match.group(1)
return [(match, 0, None, "Error", "", msg, None)]
return super().find_errors(output)
def split_match(self, match):
"""
Extract and return values from match... | return [(match, 0, None, "Error", "", match.group(0), None)] | conditional_block |
linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by roadhump
# Copyright (c) 2014 roadhump
#
# License: MIT
#
"""This module exports the ESLint plugin class."""
import sublime
import os
import re
from SublimeLinter.lint import NodeLinter
class ESLint(NodeLinter):
... | (self, output):
"""
Parse errors from linter's output.
We override this method to handle parsing eslint crashes.
"""
match = self.config_fail_regex.match(output)
if match:
return [(match, 0, None, "Error", "", match.group(0), None)]
match = self.cra... | find_errors | identifier_name |
linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by roadhump
# Copyright (c) 2014 roadhump
#
# License: MIT
#
"""This module exports the ESLint plugin class."""
import sublime
import os
import re
from SublimeLinter.lint import NodeLinter
class ESLint(NodeLinter):
... | relfilename = os.path.relpath(self.filename, vars['folder'])
cmd[cmd.index('__RELATIVE_TO_FOLDER__')] = relfilename
elif not code:
cmd.append(self.filename)
return super().communicate(cmd, code) | if 'folder' in vars: | random_line_split |
denon.js | function | (){
var denonDiv = document.getElementById("denonState");
denonInputsDiv = document.getElementById("denonInputs");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == "Off") {
denonDiv.innerHTML = this.respons... | loadDenon | identifier_name |
denon.js | function loadDenon(){
var denonDiv = document.getElementById("denonState");
denonInputsDiv = document.getElementById("denonInputs");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == "Off") {
denonDiv.innerH... |
};
xhttp.open("GET","/denon/"+action,true);
xhttp.send();
}
function denonInput(input){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
loadDenon();
}
};
xhttp.open("GET","/denon/input/"+input,true);
xhttp.send();
}
| {
loadDenon();
} | conditional_block |
denon.js | function loadDenon() | "Volume: " + denonJSON['volume'] + "<br />" +
"Muted: " + denonJSON['mute'] + "<br />" +
"Zone: " + denonJSON['zone'];
denonInputsDiv.innerHTML = "<span class=\"heading\">Available inputs:</span><br />";
for (var i=0; i < denonJSON['inputs'].length; i++) {
denonInputsDiv.innerHTML +=
... | {
var denonDiv = document.getElementById("denonState");
denonInputsDiv = document.getElementById("denonInputs");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == "Off") {
denonDiv.innerHTML = this.responseT... | identifier_body |
denon.js | function loadDenon(){
var denonDiv = document.getElementById("denonState");
denonInputsDiv = document.getElementById("denonInputs");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == "Off") {
denonDiv.innerH... | xhttp.send();
}
function denonInput(input){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
loadDenon();
}
};
xhttp.open("GET","/denon/input/"+input,true);
xhttp.send();
} | if (this.readyState == 4 && this.status == 200) {
loadDenon();
}
};
xhttp.open("GET","/denon/"+action,true); | random_line_split |
shared.d.ts | export interface DocumentData {
context: JsonLD.Context;
document: JsonLD.Document;
}
export declare function n3ToJsonldTriple(n3: N3.Triple): JsonLD.Triple;
export declare function jsonldToN3Quads(json: JsonLD.Document): N3.Triple[];
export declare function writeFile(filename: string, data: any): Promise<strin... | Json = 3,
JS = 4,
}
export declare function typeFromFile(filename: string): Type;
export declare function typeFromString(str: string): Type;
export declare function logPromise(annotation: string): (val: any) => any;
/**
* Normalize documents so that the same information produces the same unique output
*/
expo... | Unknown = 0,
TriG = 1,
NQuads = 2, | random_line_split |
dom_html_html_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::si... | f.write_str("DOMHTMLHtmlElement")
}
} | random_line_split | |
dom_html_html_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::si... | <P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMHTMLHtmlElement,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMHTMLHtmlElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLHtmlElement::from_glib_borr... | notify_version_trampoline | identifier_name |
dom_html_html_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::si... | )
}
}
}
impl fmt::Display for DOMHTMLHtmlElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("DOMHTMLHtmlElement")
}
}
| {
unsafe extern "C" fn notify_version_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMHTMLHtmlElement,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMHTMLHtmlElement>,
{
let f: &F = &*(f as *con... | identifier_body |
this.test.ts | import { types } from "../../src"
import { isObservableProp, isComputedProp } from "mobx"
// MWE: disabled test, `this` isn't supposed to work, and afaik nowhere advertised
test.skip("this support", () => {
const M = types
.model({ x: 5 })
.views((self) => ({
get x2() {
... | () {
return (
isObservableProp(this, "x2") &&
isObservableProp(this, "x4") &&
isObservableProp(this, "localState") &&
isComputedProp(this, "x2")
)
}
}))
.volatile((self) => ({
... | isThisObservable | identifier_name |
this.test.ts | import { types } from "../../src"
import { isObservableProp, isComputedProp } from "mobx"
// MWE: disabled test, `this` isn't supposed to work, and afaik nowhere advertised
test.skip("this support", () => {
const M = types
.model({ x: 5 })
.views((self) => ({
get x2() {
... | ,
getLocalState2() {
return this.getLocalState() * 2
}
}))
.actions((self) => {
return {
xBy(by: number) {
return self.x * by
},
setX(x: number) {
self.x = x
... | {
return this.localState
} | identifier_body |
this.test.ts | import { types } from "../../src"
import { isObservableProp, isComputedProp } from "mobx"
// MWE: disabled test, `this` isn't supposed to work, and afaik nowhere advertised
test.skip("this support", () => {
const M = types
.model({ x: 5 })
.views((self) => ({
get x2() {
... | return this.localState
},
getLocalState2() {
return this.getLocalState() * 2
}
}))
.actions((self) => {
return {
xBy(by: number) {
return self.x * by
},
se... | random_line_split | |
test_start.py | import unittest
import cv2 as cv
import numpy as np
import detection
from test_utils import *
class StartTest(unittest.TestCase):
def setUp(self):
|
def test_start_s3(self):
rv = video_loop('./testing/start/t1/t1.mov', self.detector, [(4, 317), (0, 237)], self.detector.detector_states)
self.assertEqual(len(rv['events']), 1)
for event in rv['events']:
self.assertEqual(event['event_type'], 'Lap')
self.assertEqual(... | self.detector = detection.BeginRace(masks_dir='./masks/start/',
freq=1,
threshold=0.16,
default_shape=[(237, 314, 3), (237, 344, 3)])
self.variables = {
'events' : list... | identifier_body |
test_start.py | import unittest
import cv2 as cv
import numpy as np
import detection
from test_utils import *
class | (unittest.TestCase):
def setUp(self):
self.detector = detection.BeginRace(masks_dir='./masks/start/',
freq=1,
threshold=0.16,
default_shape=[(237, 314, 3), (237, 344, 3)])
... | StartTest | identifier_name |
test_start.py | import unittest
import cv2 as cv
import numpy as np
import detection
from test_utils import *
class StartTest(unittest.TestCase):
def setUp(self):
self.detector = detection.BeginRace(masks_dir='./masks/start/',
freq=1,
... |
def test_start_FailCase(self):
rv = video_loop('./testing/start/FailCase/FailCase.mov', self.detector, [(4, 317), (0, 237)], self.detector.detector_states)
self.assertEqual(len(rv['events']), 0)
if __name__ == '__main__':
unittest.main()
| self.assertEqual(event['event_type'], 'Lap')
self.assertEqual(event['event_subtype'], 'BeginRace')
self.assertEqual(event['info'], 'BeginRace') | conditional_block |
test_start.py | import unittest
import cv2 as cv
import numpy as np
import detection
from test_utils import *
class StartTest(unittest.TestCase):
def setUp(self):
self.detector = detection.BeginRace(masks_dir='./masks/start/',
freq=1,
... | self.assertEqual(event['event_subtype'], 'BeginRace')
self.assertEqual(event['info'], 'BeginRace')
def test_start_emulator(self):
rv = video_loop('./testing/start/t2/t2.mov', self.detector, [(4, 317), (0, 237)], self.detector.detector_states)
self.assertEqual(len(rv['events'... | def test_start_s3(self):
rv = video_loop('./testing/start/t1/t1.mov', self.detector, [(4, 317), (0, 237)], self.detector.detector_states)
self.assertEqual(len(rv['events']), 1)
for event in rv['events']:
self.assertEqual(event['event_type'], 'Lap') | random_line_split |
armv7s_apple_ios.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> Target {
Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "arm".to_string(),
target_os: "ios".to_string(),
target_env: "".to_string(),
options: TargetOptions {
... | target | identifier_name |
armv7s_apple_ios.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "arm".to_string(),
target_os: "ios".to_string(),
target_env: "".to_string(),
options: TargetOptions {
feature... | identifier_body | |
armv7s_apple_ios.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "arm".to_string(),
target_os: "ios".to_string(),
target_env: "".to_string(),
options: TargetOptions {
features:... | use super::apple_ios_base::{opts, Arch};
pub fn target() -> Target { | random_line_split |
steps.py | value. This
method does not need to be defined when using the Gibbs sampler.
:param value: The value of the parameter.
"""
return 0.0
def random_posterior(self):
"""
Method to generate a random draw of the parameter from its posterior distribution. This
met... | self._parameter.value = proposed_value
self._parameter._log_posterior = self._parameter.logdensity(proposed_value)
self.naccept += 1 | conditional_block | |
steps.py | one to derive parameter classes from. As a result, it contains
several methods that are expected to be overridden.
"""
__slots__ = ["name", "track", "_temperature", "_log_posterior", "value"]
def __init__(self, name, track, temperature=1.0):
"""
Constructor for the parameter class.
... | The Gibbs update. This works by updating the parameter value with a random draw from the posterior
distribution, conditional on the data and any other parameter objects. The user must have defined the
method random_posterior for the parameter object in order to use this step.
"""
def __init__(self, ... | pass
class GibbStep(Step):
""" | random_line_split |
steps.py | one to derive parameter classes from. As a result, it contains
several methods that are expected to be overridden.
"""
__slots__ = ["name", "track", "_temperature", "_log_posterior", "value"]
def __init__(self, name, track, temperature=1.0):
"""
Constructor for the parameter class.
... | (self):
"""
Method to generate starting values for the parameter. This is empty and must be overridden by the
derived class.
"""
self.value = 0.0
def logdensity(self, value):
"""
Method to compute the logarithm of the posterior, given the input parameter valu... | set_starting_value | identifier_name |
steps.py | for one to derive parameter classes from. As a result, it contains
several methods that are expected to be overridden.
"""
__slots__ = ["name", "track", "_temperature", "_log_posterior", "value"]
def __init__(self, name, track, temperature=1.0):
"""
Constructor for the parameter class.... | self.naccept = 0
self.niter = 0
self._alpha = 0.0
def report(self):
"""
Method to report the average acceptance rates since the beginning of the sampler.
"""
arate = float(self.naccept) / self.niter
print 'Average acceptance rate is:', arate
def ... | """
The Metropolis-Hastings update. This works by generating a proposed parameter value from a proposal
object, and computing the ratio of the posterior under the proposed value compared to the current
parameter value. The proposal is accepted with probability equal to this ratio or one, whichever is
sm... | identifier_body |
mod.rs | use crate::c_str;
use crate::graphic::{GlBuffer, GlProgram, GlProgramBuilder, GlUniform, GlVertexArray};
use crate::opengl;
use nalgebra::{Isometry3, Matrix4, Point3};
use opengl::types::{GLsizeiptr, GLuint};
use std::ffi::c_void;
use std::mem;
use std::rc::Rc;
mod layer;
mod read_write;
pub use layer::TerrainLayer... | .geometry_shader(TERRAIN_GEOMETRY_SHADER)
.fragment_shader(TERRAIN_FRAGMENT_SHADER)
.build();
// TODO(nnmm): If our initial position as returned by local_from_global is very different
// from (0, 0, 0), the first call to camera_changed() will be very reso... | I::Item: AsRef<std::path::Path>,
{
let program =
GlProgramBuilder::new_with_vertex_shader(Rc::clone(&gl), TERRAIN_VERTEX_SHADER) | random_line_split |
mod.rs | use crate::c_str;
use crate::graphic::{GlBuffer, GlProgram, GlProgramBuilder, GlUniform, GlVertexArray};
use crate::opengl;
use nalgebra::{Isometry3, Matrix4, Point3};
use opengl::types::{GLsizeiptr, GLuint};
use std::ffi::c_void;
use std::mem;
use std::rc::Rc;
mod layer;
mod read_write;
pub use layer::TerrainLayer... | (
program: &GlProgram,
vertex_array: &GlVertexArray,
gl: Rc<opengl::Gl>,
) -> (GlBuffer, GlBuffer, usize) {
let num_vertices = (GRID_SIZE + 1) * (GRID_SIZE + 1) * 3;
let mut vertices: Vec<i32> = Vec::with_capacity(num_vertices as usize);
for iy in 0..=GRID_SIZE as i32... | create_mesh | identifier_name |
mod.rs | use crate::c_str;
use crate::graphic::{GlBuffer, GlProgram, GlProgramBuilder, GlUniform, GlVertexArray};
use crate::opengl;
use nalgebra::{Isometry3, Matrix4, Point3};
use opengl::types::{GLsizeiptr, GLuint};
use std::ffi::c_void;
use std::mem;
use std::rc::Rc;
mod layer;
mod read_write;
pub use layer::TerrainLayer... |
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
indices.push(flat_ix(ix + 1, iy + 1));
}
}
// See https://learnopengl.com/Getting-started/Hello-Triangle, section
// "Vertex Array Object" for background on buffers... | {
let num_vertices = (GRID_SIZE + 1) * (GRID_SIZE + 1) * 3;
let mut vertices: Vec<i32> = Vec::with_capacity(num_vertices as usize);
for iy in 0..=GRID_SIZE as i32 {
for ix in 0..=GRID_SIZE as i32 {
vertices.push(ix);
vertices.push(iy);
... | identifier_body |
mod.rs | use crate::c_str;
use crate::graphic::{GlBuffer, GlProgram, GlProgramBuilder, GlUniform, GlVertexArray};
use crate::opengl;
use nalgebra::{Isometry3, Matrix4, Point3};
use opengl::types::{GLsizeiptr, GLuint};
use std::ffi::c_void;
use std::mem;
use std::rc::Rc;
mod layer;
mod read_write;
pub use layer::TerrainLayer... |
unsafe {
self.vertex_array.bind();
// Switch from the point cloud rendering shader to terrain shader
self.program.gl.UseProgram(self.program.id);
// Activate wireframe mode
self.program
.gl
.PolygonMode(opengl::FRONT_AN... | {
return;
} | conditional_block |
LetterProps.js | function | (o, sw, sc, fc, m, p) {
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true,
};
}
LetterProps.prototype.update = function (o, sw, sc, fc, m, p) {
this._mdf.o = fal... | LetterProps | identifier_name |
LetterProps.js | function LetterProps(o, sw, sc, fc, m, p) |
LetterProps.prototype.update = function (o, sw, sc, fc, m, p) {
this._mdf.o = false;
this._mdf.sw = false;
this._mdf.sc = false;
this._mdf.fc = false;
this._mdf.m = false;
this._mdf.p = false;
var updated = false;
if (this.o !== o) {
this.o = o;
this._mdf.o = true;
updated =... | {
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true,
};
} | identifier_body |
LetterProps.js | function LetterProps(o, sw, sc, fc, m, p) {
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true,
};
}
LetterProps.prototype.update = function (o, sw, sc, fc, m, p) {
... |
if (this.sc !== sc) {
this.sc = sc;
this._mdf.sc = true;
updated = true;
}
if (this.fc !== fc) {
this.fc = fc;
this._mdf.fc = true;
updated = true;
}
if (this.m !== m) {
this.m = m;
this._mdf.m = true;
updated = true;
}
if (p.length && (this.p[0] !== p[... | {
this.sw = sw;
this._mdf.sw = true;
updated = true;
} | conditional_block |
LetterProps.js | function LetterProps(o, sw, sc, fc, m, p) {
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true,
};
}
LetterProps.prototype.update = function (o, sw, sc, fc, m, p) {
... | if (this.sc !== sc) {
this.sc = sc;
this._mdf.sc = true;
updated = true;
}
if (this.fc !== fc) {
this.fc = fc;
this._mdf.fc = true;
updated = true;
}
if (this.m !== m) {
this.m = m;
this._mdf.m = true;
updated = true;
}
if (p.length && (this.p[0] !== p[0]... | this._mdf.sw = true;
updated = true;
}
| random_line_split |
test_lms_result_processor.py | """
Tests for the lms_result_processor
"""
import six
import pytest
from lms.djangoapps.courseware.tests.factories import UserFactory
from lms.lib.courseware_search.lms_result_processor import LmsSearchResultProcessor
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tes... | (self):
"""
Build up a course tree with an html control
"""
self.global_staff = UserFactory(is_staff=True)
self.course = CourseFactory.create(
org='Elasticsearch',
course='ES101',
run='test_run',
display_name='Elasticsearch test co... | build_course | identifier_name |
test_lms_result_processor.py | """
Tests for the lms_result_processor
"""
import six
import pytest
from lms.djangoapps.courseware.tests.factories import UserFactory
from lms.lib.courseware_search.lms_result_processor import LmsSearchResultProcessor
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tes... | )
self.subsection = ItemFactory.create(
parent=self.section,
category='sequential',
display_name='Test Subsection',
)
self.vertical = ItemFactory.create(
parent=self.subsection,
category='vertical',
display_name='Tes... | random_line_split | |
test_lms_result_processor.py | """
Tests for the lms_result_processor
"""
import six
import pytest
from lms.djangoapps.courseware.tests.factories import UserFactory
from lms.lib.courseware_search.lms_result_processor import LmsSearchResultProcessor
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tes... |
def test_should_remove(self):
"""
Tests that "visible_to_staff_only" overrides start date.
"""
srp = LmsSearchResultProcessor(
{
"course": six.text_type(self.course.id),
"id": six.text_type(self.html.scope_ids.usage_id),
"... | fake_url = ""
srp = LmsSearchResultProcessor({}, "test")
with pytest.raises(ValueError):
fake_url = srp.url
assert fake_url == ''
srp = LmsSearchResultProcessor(
{
"course": six.text_type(self.course.id),
"id": six.text_type(self.h... | identifier_body |
timeutils.py | """Simple tools for timing functions' execution, when IPython is not available. """
from __future__ import print_function, division
import timeit
import math
from sympy.core.compatibility import range
_scales = [1e0, 1e3, 1e6, 1e9]
_units = [u's', u'ms', u'\N{GREEK SMALL LETTER MU}s', u'ns']
def timed(func, setup... |
elif limit is not None and number >= limit:
break
else:
number *= 10
time = min(timer.repeat(repeat, number)) / number
if time > 0.0:
order = min(-int(math.floor(math.log10(time)) // 3), 3)
else:
order = 3
return (number, time, time*_scales[ord... | break | conditional_block |
timeutils.py | """Simple tools for timing functions' execution, when IPython is not available. """
from __future__ import print_function, division
import timeit
import math
from sympy.core.compatibility import range
_scales = [1e0, 1e3, 1e6, 1e9]
_units = [u's', u'ms', u'\N{GREEK SMALL LETTER MU}s', u'ns']
def timed(func, setup... | oldtimestack[1].append(_timestack)
_timestack = oldtimestack
else:
_print_timestack(_timestack)
_timestack = None
return r
return wrapper
return decorator | if oldtimestack is not None: | random_line_split |
timeutils.py | """Simple tools for timing functions' execution, when IPython is not available. """
from __future__ import print_function, division
import timeit
import math
from sympy.core.compatibility import range
_scales = [1e0, 1e3, 1e6, 1e9]
_units = [u's', u'ms', u'\N{GREEK SMALL LETTER MU}s', u'ns']
def timed(func, setup... |
# Code for doing inline timings of recursive algorithms.
def __do_timings():
import os
res = os.getenv('SYMPY_TIMINGS', '')
res = [x.strip() for x in res.split(',')]
return set(res)
_do_timings = __do_timings()
_timestack = None
def _print_timestack(stack, level=1):
print('-'*level, '%.2f %s%... | """Adaptively measure execution time of a function. """
timer = timeit.Timer(func, setup=setup)
repeat, number = 3, 1
for i in range(1, 10):
if timer.timeit(number) >= 0.2:
break
elif limit is not None and number >= limit:
break
else:
number *= 10... | identifier_body |
timeutils.py | """Simple tools for timing functions' execution, when IPython is not available. """
from __future__ import print_function, division
import timeit
import math
from sympy.core.compatibility import range
_scales = [1e0, 1e3, 1e6, 1e9]
_units = [u's', u'ms', u'\N{GREEK SMALL LETTER MU}s', u'ns']
def timed(func, setup... | (*args, **kwargs):
from time import time
global _timestack
oldtimestack = _timestack
_timestack = [func.func_name, [], 0, args]
t1 = time()
r = func(*args, **kwargs)
t2 = time()
_timestack[2] = t2 - t1
if oldtime... | wrapper | identifier_name |
CollapsableCard.tsx | import * as React from 'react'
import Collapse from 'react-bootstrap/Collapse'
import { classes } from '@framework/Globals'
import { BsColor } from '@framework/Components/Basic';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
export interface CollapsableCardProps {
color?: BsColor;
heade... |
export default function CollapsableCard(p: CollapsableCardProps) {
const [isOpen, setIsOpen] = isControlled(p);
const isRTL = React.useMemo(() => document.body.classList.contains("rtl"), []);
return (
<div className={classes("card", cardStyleClasses(p.cardStyle), p.size && ("card-" + p.size))}>
... | {
if ((p.isOpen != null) && (p.toggle == null))
throw new Error("isOpen and toggle should be set together");
if (p.isOpen != null) {
return [p.isOpen, p.toggle!];
}
const [openState, setOpenState] = React.useState(p.defaultOpen == true);
React.useEffect(() => {
setOpenState(p.default... | identifier_body |
CollapsableCard.tsx | import * as React from 'react'
import Collapse from 'react-bootstrap/Collapse'
import { classes } from '@framework/Globals'
import { BsColor } from '@framework/Components/Basic';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
export interface CollapsableCardProps {
color?: BsColor;
heade... | (style?: CardStyle) {
return classes(
style?.text && "text-" + style.text,
style?.background && "bg-" + style.background,
style?.border && "border-" + style.border,
)
}
export interface CollapsableCardState {
isOpen: boolean,
isRTL: boolean;
}
function isControlled(p: CollapsableCardP... | cardStyleClasses | identifier_name |
CollapsableCard.tsx | import * as React from 'react'
import Collapse from 'react-bootstrap/Collapse'
import { classes } from '@framework/Globals'
import { BsColor } from '@framework/Components/Basic';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
export interface CollapsableCardProps {
color?: BsColor;
heade... | </Collapse>
</div>
);
} | {p.children}
</div>
| random_line_split |
abbr-fill.js | /*! abbr-fill.js | (c) 2014 Daniel Imms | github.com/Tyriar/abbr-fill.js/blob/master/LICENSE */
| var config;
function init (configuration) {
if (!configuration || !configuration.terms || !configuration.selector) {
return;
}
config = configuration;
var nodes = document.querySelectorAll(config.selector);
for (var i = 0; i < nodes.length; i++) {
applyAbbrs(nodes[i]);
}
}
... | var abbrFill = (function (findAndWrap) {
'use strict';
| random_line_split |
abbr-fill.js | /*! abbr-fill.js | (c) 2014 Daniel Imms | github.com/Tyriar/abbr-fill.js/blob/master/LICENSE */
var abbrFill = (function (findAndWrap) {
'use strict';
var config;
function init (configuration) {
if (!configuration || !configuration.terms || !configuration.selector) {
return;
}
config = confi... | }
}
}
return init;
})(findAndWrap);
| {
for (var term in config.terms) {
if (config.terms.hasOwnProperty(term)) {
// This will only match the first instance if there are two instances of
// the term separated by a space. Since it is quite an unlikely scenario
// and probably not desirable to wrap both anyway it's allowed.
... | identifier_body |
abbr-fill.js | /*! abbr-fill.js | (c) 2014 Daniel Imms | github.com/Tyriar/abbr-fill.js/blob/master/LICENSE */
var abbrFill = (function (findAndWrap) {
'use strict';
var config;
function init (configuration) {
if (!configuration || !configuration.terms || !configuration.selector) {
return;
}
config = confi... | (node) {
for (var term in config.terms) {
if (config.terms.hasOwnProperty(term)) {
// This will only match the first instance if there are two instances of
// the term separated by a space. Since it is quite an unlikely scenario
// and probably not desirable to wrap both anyway it's al... | applyAbbrs | identifier_name |
abbr-fill.js | /*! abbr-fill.js | (c) 2014 Daniel Imms | github.com/Tyriar/abbr-fill.js/blob/master/LICENSE */
var abbrFill = (function (findAndWrap) {
'use strict';
var config;
function init (configuration) {
if (!configuration || !configuration.terms || !configuration.selector) {
return;
}
config = confi... |
}
function applyAbbrs(node) {
for (var term in config.terms) {
if (config.terms.hasOwnProperty(term)) {
// This will only match the first instance if there are two instances of
// the term separated by a space. Since it is quite an unlikely scenario
// and probably not desirable ... | {
applyAbbrs(nodes[i]);
} | conditional_block |
shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
import warnings
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from dj... | def resolve_url(to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the ... | return obj_list
| random_line_split |
shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
import warnings
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from dj... |
def redirect(to, *args, permanent=False, **kwargs):
"""
Return an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse... | """
Return a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status) | identifier_body |
shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
import warnings
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from dj... |
if isinstance(to, Promise):
# Expand the lazy instance, as it can cause issues when it is passed
# further to some Python functions like urlparse.
to = str(to)
if isinstance(to, str):
# Handle relative URLs
if to.startswith(('./', '../')):
return to
# ... | return to.get_absolute_url() | conditional_block |
shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
import warnings
from django.http import (
Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from dj... | (to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
... | resolve_url | identifier_name |
evmctl-tests.py | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | (Test):
"""
evmctl-testsuite
:avocado: tags=security,testsuite
"""
def setUp(self):
'''
Install the basic packages to support evmctl
'''
# Check for basic utilities
smm = SoftwareManager()
deps = ['gcc', 'make']
for package in deps:
... | EvmCtl | identifier_name |
evmctl-tests.py | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... |
# If the fail count is more than 0 then there are some failed tests
if count:
self.fail("%s test(s) failed, please refer to the log" % count)
| count = int(line.split(":")[1].strip())
self.log.info(line)
break | conditional_block |
evmctl-tests.py | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | Running tests from evmctl
'''
count = 0
output = process.system_output('./build.sh', ignore_status=True).decode()
for line in reversed(output.splitlines()):
if '# FAIL' in line:
count = int(line.split(":")[1].strip())
self.log.info(line... | process.run('./autogen.sh', ignore_status=True)
def test(self):
''' | random_line_split |
evmctl-tests.py | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | '''
Running tests from evmctl
'''
count = 0
output = process.system_output('./build.sh', ignore_status=True).decode()
for line in reversed(output.splitlines()):
if '# FAIL' in line:
count = int(line.split(":")[1].strip())
self.log.info(... | identifier_body | |
XHR.ts | /**
* Copyright (c) 2015-present, Joshua Hollenbeck
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import Axios, { AxiosResponse } from 'axios';
import * as Promise from 'bluebird';
import { ResourceDes... |
});
});
}
}
| {
reject(err);
} | conditional_block |
XHR.ts | /**
* Copyright (c) 2015-present, Joshua Hollenbeck
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import Axios, { AxiosResponse } from 'axios';
import * as Promise from 'bluebird';
import { ResourceDes... | if (containsMultipart(requestConfig.data)) {
requestConfig.data = composeFormData(requestConfig.data);
}
}
if (store) {
store.touchResource(descriptor, touchParams, options);
}
return new Promise((resolve: (result: TRequestResult) => void, reject: (err: any) => void) => {
... | {
invariant(descriptor instanceof ResourceDescriptor,
`xhrAdapter expected descriptor, but found \`${descriptor}\``
);
const store = descriptor.store;
const touchParams: IKeyValue = {
timestamp: ITimestamp.loading
};
const requestConfig: IKeyValue = {
method: descriptor.action... | identifier_body |
XHR.ts | /**
* Copyright (c) 2015-present, Joshua Hollenbeck
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import Axios, { AxiosResponse } from 'axios';
import * as Promise from 'bluebird';
import { ResourceDes... | extends BaseAdapter {
invoke(this: this, descriptor: ResourceDescriptor, options: IKeyValue = {}): Promise<TRequestResult> {
invariant(descriptor instanceof ResourceDescriptor,
`xhrAdapter expected descriptor, but found \`${descriptor}\``
);
const store = descriptor.store;
const touchParams: I... | XHRAdapter | identifier_name |
XHR.ts | /**
* Copyright (c) 2015-present, Joshua Hollenbeck
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import Axios, { AxiosResponse } from 'axios';
import * as Promise from 'bluebird';
import { ResourceDes... | else {
requestConfig.data = descriptor.payload;
if (containsMultipart(requestConfig.data)) {
requestConfig.data = composeFormData(requestConfig.data);
}
}
if (store) {
store.touchResource(descriptor, touchParams, options);
}
return new Promise((resolve: (result: TR... | } | random_line_split |
iframe.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { delay } from "awaiting";
declare var $: any;
// Cause a file at a given url to get downloaded... using an iframe. Don't await this.
export async function dow | c: string): Promise<void> {
// NOTE: the file has to be served with
// res.setHeader('Content-disposition', 'attachment')
// Create hidden iframe that causes download to happen:
const iframe = $("<iframe>")
.addClass("hide")
.attr("src", src)
.appendTo($("body"));
// Wait a minute...
await ... | nload_file(sr | identifier_name |
iframe.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { delay } from "awaiting";
declare var $: any;
// Cause a file at a given url to get downloaded... using an iframe. Don't await this.
export async function download_fi... | .attr("src", src)
.appendTo($("body"));
// Wait a minute...
await delay(60000);
// Then get rid of that iframe
iframe.remove();
}
// These are used to disable pointer events for iframes when
// dragging something that may move over an iframe. See
// http://stackoverflow.com/questions/3627217/jquer... | const iframe = $("<iframe>")
.addClass("hide") | random_line_split |
iframe.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { delay } from "awaiting";
declare var $: any;
// Cause a file at a given url to get downloaded... using an iframe. Don't await this.
export async function download_fi... | return $("iframe:visible").css("pointer-events", "auto");
}
| identifier_body | |
tsxSpreadAttributesResolution5.tsx | // @filename: file.tsx
// @jsx: preserve
// @noLib: true
// @skipLibCheck: true
// @libFiles: react.d.ts,lib.d.ts
import React = require('react');
interface PoisonedProp {
x: string;
y: 2;
}
class Poisoned extends React.Component<PoisonedProp, {}> {
render() {
return <div>Hello</div>;
}
}
le... | }
// Ok
let e = <EmptyProp {...o} />; | random_line_split | |
tsxSpreadAttributesResolution5.tsx | // @filename: file.tsx
// @jsx: preserve
// @noLib: true
// @skipLibCheck: true
// @libFiles: react.d.ts,lib.d.ts
import React = require('react');
interface PoisonedProp {
x: string;
y: 2;
}
class Poisoned extends React.Component<PoisonedProp, {}> {
render() {
return <div>Hello</div>;
}
}
le... | () {
return <div>Default hi</div>;
}
greeting: string;
}
let o = {
prop1: false
}
// Ok
let e = <EmptyProp {...o} />; | render | identifier_name |
beatbox.py | #!/usr/bin/env python
import pygame
from tools import singleton
@singleton
class Audio(object):
def __init__(self, initial_musics={}, initial_sounds={}):
if pygame.mixer.get_init() is None:
pygame.mixer.init()
self.__mute = False
self.__sounds = initial_sounds
... |
def set_mute(self, new_state=True):
if new_state:
self.mute()
else:
self.unmute()
def set_bgm_music(self, music_id):
if music_id not in self.musics:
return False
pygame.mixer.music.load(self.__musics[music_id])
if not self.is_muted:
... | if not self.is_muted:
return
pygame.mixer.music.play(-1) | identifier_body |
beatbox.py | #!/usr/bin/env python
import pygame
from tools import singleton
@singleton
class Audio(object):
def __init__(self, initial_musics={}, initial_sounds={}):
if pygame.mixer.get_init() is None:
pygame.mixer.init()
self.__mute = False
self.__sounds = initial_sounds
... | (self):
return self.__mute
def mute(self):
if self.is_muted:
return
pygame.mixer.music.stop()
self.__mute = True
def unmute(self):
if not self.is_muted:
return
pygame.mixer.music.play(-1)
def set_mute(self, new_state=True):
i... | is_muted | identifier_name |
beatbox.py | #!/usr/bin/env python
import pygame
from tools import singleton
@singleton
class Audio(object):
def __init__(self, initial_musics={}, initial_sounds={}):
if pygame.mixer.get_init() is None:
pygame.mixer.init()
self.__mute = False
self.__sounds = initial_sounds
... | pygame.mixer.music.stop()
self.__mute = True
def unmute(self):
if not self.is_muted:
return
pygame.mixer.music.play(-1)
def set_mute(self, new_state=True):
if new_state:
self.mute()
else:
self.unmute()
def set_bgm_music(s... | return self.__mute
def mute(self):
if self.is_muted:
return | random_line_split |
beatbox.py | #!/usr/bin/env python
import pygame
from tools import singleton
@singleton
class Audio(object):
def __init__(self, initial_musics={}, initial_sounds={}):
if pygame.mixer.get_init() is None:
pygame.mixer.init()
self.__mute = False
self.__sounds = initial_sounds
... |
del(self.__sounds[sound_id])
def unregister_music(self, music_id):
if music_id not in self.__musics.keys():
return False
del(self.__musics[music_id])
@property
def sounds(self):
return self.__sounds.keys()
@property
def musics(self):
return sel... | return False | conditional_block |
null.ts |
'use strict';
import Type = require('../type');
function resolveYamlNull(data) {
if (null === data) |
var max = data.length;
return (max === 1 && data === '~') ||
(max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
}
function constructYamlNull() {
return null;
}
function isNull(object) {
return null === object;
}
export = new Type('tag:yaml.org,2002:null', {
kind: 'scalar',
... | {
return true;
} | conditional_block |
null.ts |
'use strict';
import Type = require('../type');
function resolveYamlNull(data) {
if (null === data) {
return true;
}
var max = data.length;
return (max === 1 && data === '~') ||
(max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
}
function constructYamlNull() {
return ... | (object) {
return null === object;
}
export = new Type('tag:yaml.org,2002:null', {
kind: 'scalar',
resolve: resolveYamlNull,
construct: constructYamlNull,
predicate: isNull,
represent: {
canonical: function () { return '~'; },
lowercase: function () { return 'null'; },
uppercase: function ()... | isNull | identifier_name |
null.ts | 'use strict';
import Type = require('../type');
function resolveYamlNull(data) {
if (null === data) {
return true;
}
var max = data.length;
return (max === 1 && data === '~') ||
(max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
}
function constructYamlNull() {
return nu... | canonical: function () { return '~'; },
lowercase: function () { return 'null'; },
uppercase: function () { return 'NULL'; },
camelcase: function () { return 'Null'; }
},
defaultStyle: 'lowercase'
}); | represent: { | random_line_split |
null.ts |
'use strict';
import Type = require('../type');
function resolveYamlNull(data) {
if (null === data) {
return true;
}
var max = data.length;
return (max === 1 && data === '~') ||
(max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
}
function constructYamlNull() {
return ... |
export = new Type('tag:yaml.org,2002:null', {
kind: 'scalar',
resolve: resolveYamlNull,
construct: constructYamlNull,
predicate: isNull,
represent: {
canonical: function () { return '~'; },
lowercase: function () { return 'null'; },
uppercase: function () { return 'NULL'; },
camelcase: fu... | {
return null === object;
} | identifier_body |
stop.rs | use async_trait::async_trait;
use cucumber::given;
use mimir::adapters::secondary::elasticsearch::remote::connection_test_pool;
use mimir::domain::ports::secondary::remote::Remote;
use snafu::ResultExt;
use crate::error::{self, Error};
use crate::state::{GlobalState, State, Step, StepStatus};
use crate::steps::admin::... | {
pub region: String,
pub dataset: String,
}
#[async_trait(?Send)]
impl Step for IndexNTFS {
async fn execute(&mut self, state: &State) -> Result<StepStatus, Error> {
let Self { region, dataset } = self;
let client = connection_test_pool()
.conn(ElasticsearchStorageConfig::def... | IndexNTFS | identifier_name |
stop.rs | use async_trait::async_trait;
use cucumber::given;
use mimir::adapters::secondary::elasticsearch::remote::connection_test_pool;
use mimir::domain::ports::secondary::remote::Remote;
use snafu::ResultExt;
use crate::error::{self, Error};
use crate::state::{GlobalState, State, Step, StepStatus};
use crate::steps::admin::... |
#[async_trait(?Send)]
impl Step for IndexNTFS {
async fn execute(&mut self, state: &State) -> Result<StepStatus, Error> {
let Self { region, dataset } = self;
let client = connection_test_pool()
.conn(ElasticsearchStorageConfig::default_testing())
.await
.expect... | pub struct IndexNTFS {
pub region: String,
pub dataset: String,
} | random_line_split |
benchmark.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
// MODULES //
var resolve = require( 'path' ).resolve;
var bench = require( '@stdlib/bench' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float64Array = require( '@stdlib/array/float64' );
var tryRequire = require( '@stdlib/utils/try-require' );... | random_line_split | |
benchmark.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::native:len='+len, opts, f );
}
}
main();
| {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = dmediansorted( x.length, x, 1 );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
} | identifier_body |
benchmark.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | ( len ) {
var x;
var i;
x = new Float64Array( len );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = i;
}
return benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = dmediansorted( x.length, x, 1 );
if ( isnan( v ) ) {
b.fail( 'should not retur... | createBenchmark | identifier_name |
benchmark.native.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i... | {
v = dmediansorted( x.length, x, 1 );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
} | conditional_block |
server.js | var http = require('http')
var https = require('https')
var corsify = require('corsify')
var collect = require('stream-collector')
var pump = require('pump')
var iterate = require('random-iterate')
var limiter = require('size-limit-stream')
var eos = require('end-of-stream')
var flushHeaders = function (res) {
if (r... | if (!channels[name]) return res.end()
var channel = get(name)
server.emit('publish', channel.name, data)
data = Buffer.concat(data).toString()
var ite = iterate(channel.subscribers)
var next
var cnt = 0
while ((next = ite()) && cnt++ < maxBroadcasts) {
... | if (err) return res.end() | random_line_split |
server.js | var http = require('http')
var https = require('https')
var corsify = require('corsify')
var collect = require('stream-collector')
var pump = require('pump')
var iterate = require('random-iterate')
var limiter = require('size-limit-stream')
var eos = require('end-of-stream')
var flushHeaders = function (res) {
if (r... |
res.statusCode = 404
res.end()
})
var server = ((opts && opts.key) ? https : http).createServer(opts)
server.on('request', onRequest)
return server
}
| {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
var app = name.split('/')[0]
var channelNames = name.slice(app.length + 1)
channelNames.split(',').forEach(function (channelName) {
var channel = get(app + '/' + channelName)
server.emit('subscribe', channel.na... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.