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 |
|---|---|---|---|---|
parser_utils.rs | use std::collections::LinkedList;
use std::iter::Iterator;
use std::vec::Vec;
use lexer::Token;
use interpreter::ProgramStore;
use interpreter::FunctionInfo;
/// This function filters out comments and doubled newlines
/// It also registers the functions with the program store
pub fn filter_pass(tokens: Vec<Token>, m... |
_ => {}
}
block.push(token);
}
// Add last block to block list
block_list.push_back(block);
Ok(block_list)
}
| {
if block.len() != 0 && block[0] == Token::Define {
block_list.push_back(block);
}
block = Vec::new();
} | conditional_block |
batcher.ts | export default class Batcher<Callback extends (...args: Array<any>) => any> {
private queue: Array<Parameters<Callback>> = []
private callbacks: Array<(...args: Parameters<Callback>) => void> = []
private bulkCallbacks: Array<(args: Array<Parameters<Callback>>) => void> = []
constructor(private threshold: numb... | (callback: (args: Array<Parameters<Callback>>) => void): void {
this.bulkCallbacks.push(callback)
}
}
| bulkCall | identifier_name |
batcher.ts | export default class Batcher<Callback extends (...args: Array<any>) => any> {
private queue: Array<Parameters<Callback>> = []
private callbacks: Array<(...args: Parameters<Callback>) => void> = []
private bulkCallbacks: Array<(args: Array<Parameters<Callback>>) => void> = []
constructor(private threshold: numb... |
}
/** Call all of our callbacks and clear out the queue */
flush(): void {
// call each callback for each item in the queue
this.queue.forEach(args =>
this.callbacks.forEach(callback => callback(...args))
)
// pass the entire queue to all bulk callbacks
this.bulkCallbacks.forEach(call... | {
this.flush()
} | conditional_block |
batcher.ts | export default class Batcher<Callback extends (...args: Array<any>) => any> {
private queue: Array<Parameters<Callback>> = []
private callbacks: Array<(...args: Parameters<Callback>) => void> = []
private bulkCallbacks: Array<(args: Array<Parameters<Callback>>) => void> = []
constructor(private threshold: numb... | this.queue.push(args)
if (this.queue.length >= this.threshold) {
this.flush()
}
}
/** Call all of our callbacks and clear out the queue */
flush(): void {
// call each callback for each item in the queue
this.queue.forEach(args =>
this.callbacks.forEach(callback => callback(...ar... | random_line_split | |
qmverifierTest.py | """
Created on May 17, 2012
@author: nmvdewie
"""
import unittest
import rmgpy.qm.qmtp as qm
import os
import rmgpy.qm.qmverifier as verif
import rmgpy.molecule as mol
class Test(unittest.TestCase):
def testVerifierDoesNotExist(self):
molecule = mol.Molecule()
name = 'UMRZSTCPUPJPOJ-UHFFFAOYSA'
... | unittest.main( testRunner = unittest.TextTestRunner(verbosity=2) ) | conditional_block | |
qmverifierTest.py | """
Created on May 17, 2012
@author: nmvdewie
"""
import unittest
import rmgpy.qm.qmtp as qm
import os
import rmgpy.qm.qmverifier as verif
import rmgpy.molecule as mol
class Test(unittest.TestCase):
| verifier.verify()
self.assertTrue(verifier.succesfulJobExists())
self.assertTrue(verifier.mopacResultExists)
self.assertFalse(verifier.gaussianResultExists)
if __name__ == "__main__":
unittest.main( testRunner = unittest.TextTestRunner(verbosity=2) ) | def testVerifierDoesNotExist(self):
molecule = mol.Molecule()
name = 'UMRZSTCPUPJPOJ-UHFFFAOYSA'
directory = os.path.join(os.path.dirname(__file__),'data','QMfiles')
InChIaug = 'InChI=1S/C7H12/c1-2-7-4-3-6(1)5-7/h6-7H,1-5H2'
molfile = qm.molFile(molecule, name, directory, InChIau... | identifier_body |
qmverifierTest.py | """
Created on May 17, 2012
@author: nmvdewie
"""
import unittest
import rmgpy.qm.qmtp as qm
import os
import rmgpy.qm.qmverifier as verif
import rmgpy.molecule as mol
class Test(unittest.TestCase):
def testVerifierDoesNotExist(self):
molecule = mol.Molecule()
name = 'UMRZSTCPUPJPOJ-UHFFFAOYSA'
... | name = 'GRWFGVWFFZKLTI-UHFFFAOYAF'
directory = os.path.join(os.path.dirname(__file__),'data','QMfiles','MOPAC')
InChIaug = 'InChI=1/C10H16/c1-7-4-5-8-6-9(7)10(8,2)3/h4,8-9H,5-6H2,1-3H3'
molfile = qm.molFile(molecule, name, directory, InChIaug)
verifier = verif.QMVerifier... |
def testVerifierMOPACResultExists(self):
molecule = mol.Molecule() | random_line_split |
qmverifierTest.py | """
Created on May 17, 2012
@author: nmvdewie
"""
import unittest
import rmgpy.qm.qmtp as qm
import os
import rmgpy.qm.qmverifier as verif
import rmgpy.molecule as mol
class Test(unittest.TestCase):
def testVerifierDoesNotExist(self):
molecule = mol.Molecule()
name = 'UMRZSTCPUPJPOJ-UHFFFAOYSA'
... | (self):
molecule = mol.Molecule()
name = 'GRWFGVWFFZKLTI-UHFFFAOYAF'
directory = os.path.join(os.path.dirname(__file__),'data','QMfiles','MOPAC')
InChIaug = 'InChI=1/C10H16/c1-7-4-5-8-6-9(7)10(8,2)3/h4,8-9H,5-6H2,1-3H3'
molfile = qm.molFile(molecule, name, directory, InChIaug)
... | testVerifierMOPACResultExists | identifier_name |
errors.rs | use std::ffi::CStr;
use libc;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
links {} | FromBytesWithNul(::std::ffi::FromBytesWithNulError);
IntoString(::std::ffi::IntoStringError);
Utf8(::std::str::Utf8Error);
IO(::std::io::Error);
}
errors {
Rados(e: u32) {
description("RADOS error")
display("RADOS error code {}: `{}`", e, get_erro... |
foreign_links {
Nul(::ffi_pool::NulError);
NulStd(::std::ffi::NulError); | random_line_split |
errors.rs | use std::ffi::CStr;
use libc;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
links {}
foreign_links {
Nul(::ffi_pool::NulError);
NulStd(::std::ffi::NulError);
FromBytesWithNul(::std::ffi::FromBytesWithNulError);
IntoString(::std::ffi::IntoString... | else {
Ok(())
}
}
/// Convert the integer output of a librados API function into a `Result<u32>`, returning the error
/// value casted to a `u32` if it's positive and returning `Err` otherwise.
pub fn librados_res(err: i32) -> Result<u32> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
... | {
bail!(ErrorKind::Rados(-err as u32));
} | conditional_block |
errors.rs | use std::ffi::CStr;
use libc;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
links {}
foreign_links {
Nul(::ffi_pool::NulError);
NulStd(::std::ffi::NulError);
FromBytesWithNul(::std::ffi::FromBytesWithNulError);
IntoString(::std::ffi::IntoString... | {
let error = unsafe {
let err_str = libc::strerror(err as i32);
try!(
CStr::from_ptr(err_str)
.to_str()
.chain_err(|| "while decoding error string",)
)
};
Ok(error.to_string())
} | identifier_body | |
errors.rs | use std::ffi::CStr;
use libc;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
links {}
foreign_links {
Nul(::ffi_pool::NulError);
NulStd(::std::ffi::NulError);
FromBytesWithNul(::std::ffi::FromBytesWithNulError);
IntoString(::std::ffi::IntoString... | (err: i32) -> Result<u32> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
} else {
Ok(err as u32)
}
}
/// Get the registered error string for a given error number.
pub fn get_error_string(err: u32) -> Result<String> {
let error = unsafe {
let err_str = libc::strerror(err as... | librados_res | identifier_name |
ClientPortChrome.js | /*******************************************************************************
* Copyright (c) 2016, Institute for Pervasive Computing, ETH Zurich.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
... |
callback(port);
};
let firstTimeout = Copper.TimeUtils.setTimeout(connectedCallback, 600);
port.registerDisconnectCallback(function(){
// app not started
Copper.Log.logFine("Starting application");
Copper.TimeUtils.clearTimeout(firstTimeout);
let secondTimeout = Copper... | {
port.registerDisconnectCallback(finalDisconnectHandler);
} | conditional_block |
ClientPortChrome.js | /*******************************************************************************
* Copyright (c) 2016, Institute for Pervasive Computing, ETH Zurich.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
... |
// UPDATE with value from chrome://extensions/
let appId = "olkcgjkdhadideeemhnfbihnbmbpfjnd";
let port = new Copper.Port(chrome.runtime.connect(appId), clientId);
let connectedCallback = function(){
if (port !== undefined){
port.registerDisconnectCallback(finalDisconnectHandler);
}... |
Copper.ClientPort.connect = function(clientId, finalDisconnectHandler, callback){ | random_line_split |
problem_029.py | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
Starting with the number 1 and moving to the right
in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11 |
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals
in a 1001 by 1001 spiral formed in the same way?
'''
import timeit
def calc(a, b):
return len(set([i**j for i in range(2, a+1) for j in range(2, b+1)]))
if __name__ == '__main__':
print c... | 18 5 4 3 12
17 16 15 14 13 | random_line_split |
problem_029.py | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
Starting with the number 1 and moving to the right
in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is th... |
if __name__ == '__main__':
print calc(100, 100)
print timeit.Timer('problem_029.calc(100, 100)', 'import problem_029').timeit(10)
| return len(set([i**j for i in range(2, a+1) for j in range(2, b+1)])) | identifier_body |
problem_029.py | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
Starting with the number 1 and moving to the right
in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is th... | print calc(100, 100)
print timeit.Timer('problem_029.calc(100, 100)', 'import problem_029').timeit(10) | conditional_block | |
problem_029.py | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
Starting with the number 1 and moving to the right
in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is th... | (a, b):
return len(set([i**j for i in range(2, a+1) for j in range(2, b+1)]))
if __name__ == '__main__':
print calc(100, 100)
print timeit.Timer('problem_029.calc(100, 100)', 'import problem_029').timeit(10)
| calc | identifier_name |
fill.rs | use lyon::tessellation::FillOptions;
/// Nodes that support fill tessellation.
///
/// This trait allows the `Drawing` context to automatically provide an implementation of the
/// following builder methods for all primitives that provide some fill tessellation options.
pub trait SetFill: Sized {
/// Provide a mut... |
}
impl SetFill for Option<FillOptions> {
fn fill_options_mut(&mut self) -> &mut FillOptions {
self.get_or_insert_with(Default::default)
}
}
| {
self.fill_options_mut().handle_intersections = handle;
self
} | identifier_body |
fill.rs | use lyon::tessellation::FillOptions;
| ///
/// This trait allows the `Drawing` context to automatically provide an implementation of the
/// following builder methods for all primitives that provide some fill tessellation options.
pub trait SetFill: Sized {
/// Provide a mutable reference to the `FillOptions` field.
fn fill_options_mut(&mut self) ->... | /// Nodes that support fill tessellation. | random_line_split |
fill.rs | use lyon::tessellation::FillOptions;
/// Nodes that support fill tessellation.
///
/// This trait allows the `Drawing` context to automatically provide an implementation of the
/// following builder methods for all primitives that provide some fill tessellation options.
pub trait SetFill: Sized {
/// Provide a mut... | (mut self, orientation: lyon::tessellation::Orientation) -> Self {
self.fill_options_mut().sweep_orientation = orientation;
self
}
/// A fast path to avoid some expensive operations if the path is known to not have any
/// self-intersections.
///
/// Do not set this to `false` if th... | fill_sweep_orientation | identifier_name |
hue-states.ts | var hue = require('node-hue-api');
var lightState = hue.lightState;
// WHITE STATES
var MID = 350;
var WARM = 400;
var X_WARM = 500;
var BRIGHT = 250;
// HUES
const HUE = {
BLOOD_ORANGE: 350,
RED: 0,
GREEN: 145,
BLUE: 250,
PURPLE: 280
}
const BRIGHTNESS = {
MAX: 100,
HIGH: 75,
MED: 50,
LOW: 25,
M... | };
const SATURATION = {
MAX: 100,
HIGH: 75,
MED: 50,
LOW: 25,
MIN: 1
};
export const STATES = {
bright: lightState.create().on().white(BRIGHT, BRIGHTNESS.MAX),
warm: lightState.create().on().white(X_WARM, BRIGHTNESS.MAX),
full: lightState.create().on().white(MID, BRIGHTNESS.MAX),
high: lightState.c... | random_line_split | |
miplayer.py | # -*- coding: utf-8 -*-
import re,urlparse,base64
from resources.lib.modules import client
domains = ['miplayer.net']
def resolve(url):
| try:
try:
referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0]
except:
referer=url
id = urlparse.parse_qs(urlparse.urlparse(url).query)['id'][0]
url = 'http://miplayer.net/embedplayer.php?width=640&height=480&id=%s'%id
resul... | identifier_body | |
miplayer.py | # -*- coding: utf-8 -*-
import re,urlparse,base64
from resources.lib.modules import client
domains = ['miplayer.net']
def | (url):
try:
try:
referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0]
except:
referer=url
id = urlparse.parse_qs(urlparse.urlparse(url).query)['id'][0]
url = 'http://miplayer.net/embedplayer.php?width=640&height=480&id=%s'%id
... | resolve | identifier_name |
miplayer.py | # -*- coding: utf-8 -*-
import re,urlparse,base64
from resources.lib.modules import client
domains = ['miplayer.net']
def resolve(url):
try:
try:
referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0]
except:
referer=url
id = urlpar... | curl = base64.b64decode(curl)
url = curl + ' swfUrl=http://otronivel.me/jw7/jwplayer.flash.swf flashver=WIN/2019,0,0,226 timeout=15 live=true swfVfy=1 pageUrl=http://miplayer.net/embedplayer.php?width=640&height=480&id=%s&autoplay=true&strech=exactfit'%id
return url
except:
re... | result = client.request(url, referer=referer)
curl = re.compile("curl\s*=\s*\"(.+?)\"").findall(result)[0] | random_line_split |
od_glob.py | #!/usr/bin/python3
"""
Global variables for onedrive_d.
"""
import os
import sys
import logging
import atexit
import json
from calendar import timegm
from datetime import timezone, datetime, timedelta
from pwd import getpwnam
from . import od_ignore_list
config_instance = None
logger_instance = None
update_last_run_... | (self, tokens):
d = now() + timedelta(seconds=tokens['expires_in'])
ConfigSet.params['ONEDRIVE_TOKENS'] = tokens
ConfigSet.params['ONEDRIVE_TOKENS_EXP'] = time_to_str(d)
ConfigSet.is_dirty = True
def dump(self):
try:
with open(ConfigSet.APP_CONF_FILE, 'w') as f:
json.dump(ConfigSet.params, f)
os.c... | set_access_token | identifier_name |
od_glob.py | #!/usr/bin/python3
"""
Global variables for onedrive_d.
"""
import os
import sys
import logging
import atexit
import json
from calendar import timegm
from datetime import timezone, datetime, timedelta
from pwd import getpwnam
from . import od_ignore_list
config_instance = None
logger_instance = None
update_last_run_... |
return config_instance
def get_logger(level=logging.DEBUG, file_path=None):
global logger_instance
if logger_instance is None:
logging.basicConfig(format='[%(asctime)-15s] %(levelname)s: %(threadName)s: %(message)s')
logger_instance = logging.getLogger(__name__)
logger_instance.setLevel(level)
if file_pat... | config_instance = ConfigSet(setup_mode)
atexit.register(dump_config) | conditional_block |
od_glob.py | #!/usr/bin/python3
"""
Global variables for onedrive_d.
"""
import os
import sys
import logging
import atexit
import json
from calendar import timegm
from datetime import timezone, datetime, timedelta
from pwd import getpwnam
from . import od_ignore_list
config_instance = None
logger_instance = None
update_last_run_... | s = t.strftime(DATETIME_FORMAT)
if '+' not in s:
s = s + '+0000'
return s
def str_to_time(s):
return datetime.strptime(s, DATETIME_FORMAT)
def str_to_timestamp(s):
return timegm(str_to_time(s).timetuple())
def timestamp_to_time(t):
return datetime.fromtimestamp(t, tz=timezone.utc)
def mkdir(path, uid):
... | return datetime.now(timezone.utc)
def time_to_str(t): | random_line_split |
od_glob.py | #!/usr/bin/python3
"""
Global variables for onedrive_d.
"""
import os
import sys
import logging
import atexit
import json
from calendar import timegm
from datetime import timezone, datetime, timedelta
from pwd import getpwnam
from . import od_ignore_list
config_instance = None
logger_instance = None
update_last_run_... |
def will_update_last_run_time():
update_last_run_timestamp = True
def dump_config():
if update_last_run_timestamp and config_instance is not None:
config_instance.set_last_run_timestamp()
if config_instance is not None and ConfigSet.is_dirty:
config_instance.dump()
class ConfigSet:
params = {
'NETWORK... | global logger_instance
if logger_instance is not None:
logging.shutdown() | identifier_body |
mock-server.py | #!/usr/bin/env python3
# Copyright 2015, 2016 Endless Mobile, Inc.
# This file is part of eos-event-recorder-daemon.
#
# eos-event-recorder-daemon 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 versi... | self.send_response(status_code)
self.end_headers()
# A metrics server that simply prints the requests it receives to stdout
class MockServer(http.server.HTTPServer):
def __init__(self):
SERVER_ADDRESS = ('localhost', 0)
super().__init__(SERVER_ADDRESS, PrintingHTTPRequestHandler)
i... | sys.stdout.buffer.write(decompressed_request_body)
sys.stdout.buffer.flush()
status_code_str = sys.stdin.readline()
status_code = int(status_code_str) | random_line_split |
mock-server.py | #!/usr/bin/env python3
# Copyright 2015, 2016 Endless Mobile, Inc.
# This file is part of eos-event-recorder-daemon.
#
# eos-event-recorder-daemon 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 versi... | mock_server = MockServer()
print(mock_server.server_port, flush=True)
mock_server.serve_forever() | conditional_block | |
mock-server.py | #!/usr/bin/env python3
# Copyright 2015, 2016 Endless Mobile, Inc.
# This file is part of eos-event-recorder-daemon.
#
# eos-event-recorder-daemon 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 versi... |
if __name__ == '__main__':
mock_server = MockServer()
print(mock_server.server_port, flush=True)
mock_server.serve_forever()
| def __init__(self):
SERVER_ADDRESS = ('localhost', 0)
super().__init__(SERVER_ADDRESS, PrintingHTTPRequestHandler) | identifier_body |
mock-server.py | #!/usr/bin/env python3
# Copyright 2015, 2016 Endless Mobile, Inc.
# This file is part of eos-event-recorder-daemon.
#
# eos-event-recorder-daemon 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 versi... | (self):
SERVER_ADDRESS = ('localhost', 0)
super().__init__(SERVER_ADDRESS, PrintingHTTPRequestHandler)
if __name__ == '__main__':
mock_server = MockServer()
print(mock_server.server_port, flush=True)
mock_server.serve_forever()
| __init__ | identifier_name |
ctl_flags.rs | // ctl_flags.rs
use super::consts::*;
// Represents control flags of a sysctl
bitflags! {
pub struct CtlFlags : libc::c_uint {
/// Allow reads of variable
const RD = CTLFLAG_RD;
/// Allow writes to the variable
const WR = CTLFLAG_WR;
const RW = Self::RD.bits | Self::WR.bi... |
/// Readable and writeable tunable
const RWTUN = Self::RW.bits | Self::TUN.bits;
/// Handler is MP safe
const MPSAFE = CTLFLAG_MPSAFE;
/// Prisons with vnet can fiddle
const VNET = CTLFLAG_VNET;
/// Oid is being removed
const DYING = CTLFLAG_DYING;
... | random_line_split | |
ctl_flags.rs | // ctl_flags.rs
use super::consts::*;
// Represents control flags of a sysctl
bitflags! {
pub struct CtlFlags : libc::c_uint {
/// Allow reads of variable
const RD = CTLFLAG_RD;
/// Allow writes to the variable
const WR = CTLFLAG_WR;
const RW = Self::RD.bits | Self::WR.bi... | () {
// This sysctl should be read-only.
#[cfg(any(target_os = "freebsd", target_os = "macos"))]
let ctl: crate::Ctl = crate::Ctl::new("kern.ostype").unwrap();
#[cfg(any(target_os = "android", target_os = "linux"))]
let ctl: crate::Ctl = crate::Ctl::new("kernel.ostype").unwrap();... | ctl_flags | identifier_name |
ctl_flags.rs | // ctl_flags.rs
use super::consts::*;
// Represents control flags of a sysctl
bitflags! {
pub struct CtlFlags : libc::c_uint {
/// Allow reads of variable
const RD = CTLFLAG_RD;
/// Allow writes to the variable
const WR = CTLFLAG_WR;
const RW = Self::RD.bits | Self::WR.bi... |
}
| {
// This sysctl should be read-only.
#[cfg(any(target_os = "freebsd", target_os = "macos"))]
let ctl: crate::Ctl = crate::Ctl::new("kern.ostype").unwrap();
#[cfg(any(target_os = "android", target_os = "linux"))]
let ctl: crate::Ctl = crate::Ctl::new("kernel.ostype").unwrap();
... | identifier_body |
popup.js |
/**
* Returns a new instance of the popup handler
*
* @method buildPopupHandler
* @private
*/
Popup.prototype.buildPopupHandler = function() {
var pluginHandler = this.baseOptions.plugins.get('popup.getPopupHandler');
if (pluginHandler) {
return pluginHandler.getPopupHandler();
}
return new PopupHa... | {
this.baseOptions = options;
this.client = webAuth.client;
this.webAuth = webAuth;
this.transactionManager = new TransactionManager(this.baseOptions.transaction);
this.warn = new Warn({
disableWarnings: !!options._disableDeprecationWarnings
});
} | identifier_body | |
popup.js | (webAuth, options) {
this.baseOptions = options;
this.client = webAuth.client;
this.webAuth = webAuth;
this.transactionManager = new TransactionManager(this.baseOptions.transaction);
this.warn = new Warn({
disableWarnings: !!options._disableDeprecationWarnings
});
}
/**
* Returns a new instance of th... | Popup | identifier_name | |
popup.js | new Warn({
disableWarnings: !!options._disableDeprecationWarnings
});
}
/**
* Returns a new instance of the popup handler
*
* @method buildPopupHandler
* @private
*/
Popup.prototype.buildPopupHandler = function() {
var pluginHandler = this.baseOptions.plugins.get('popup.getPopupHandler');
if (pluginHa... |
if (preload) {
return this.preload(options);
}
return this.buildPopupHandler();
};
/**
* Handles the popup logic for the callback page.
*
* @method callback
* @param {Object} options
* @param {String} options.hash the url hash. If not provided it will extract from window.location.hash
* @param {Stri... | {
return options.popupHandler;
} | conditional_block |
popup.js | new Warn({
disableWarnings: !!options._disableDeprecationWarnings
});
}
/**
* Returns a new instance of the popup handler
*
* @method buildPopupHandler
* @private
*/
Popup.prototype.buildPopupHandler = function() {
var pluginHandler = this.baseOptions.plugins.get('popup.getPopupHandler');
if (pluginHa... | clientID: { optional: true, type: 'string', message: 'clientID option is required' },
redirectUri: { optional: true, type: 'string', message: 'redirectUri option is required' },
responseType: { optional: true, type: 'string', message: 'responseType option is required' },
scope: { optional: true,... | { type: 'object', message: 'options parameter is not valid' },
{ | random_line_split |
codenvy-api-builder.factory.ts | /*
* Copyright (c) [2015] - [2017] Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* ... | () {
}
/**
* The Codenvy Resources builder
*
* @return {CodenvyResourceBuilder}
*/
getResourceBuilder() {
return new CodenvyResourceBuilder();
}
}
| constructor | identifier_name |
codenvy-api-builder.factory.ts | /*
* Copyright (c) [2015] - [2017] Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* ... |
/**
* The Codenvy Resources builder
*
* @return {CodenvyResourceBuilder}
*/
getResourceBuilder() {
return new CodenvyResourceBuilder();
}
} | * @ngInject for Dependency injection
*/
constructor () {
} | random_line_split |
contact.js | 'use strict';
angular.module('myApp.contact', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contact', {
templateUrl: 'app/view/contact.html',
controller: 'contactCtrl'
});
}])
.controller('contactCtrl',['$scope'... | google.maps.event.addDomListener(window, 'load');
}]); | random_line_split | |
contact.js |
'use strict';
angular.module('myApp.contact', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contact', {
templateUrl: 'app/view/contact.html',
controller: 'contactCtrl'
});
}])
.controller('contactCtrl',['$scop... | else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.... | { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data;
$scope.result='bg-success';
} | conditional_block |
Patch.py | import numpy as np
from bokeh.document import Document
from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid
from bokeh.models.glyphs import Patch
from bokeh.plotting import show
N = 30
x1 = np.linspace(-2, 2, N)
x2 = x1[::-1]
y1 = x1**2
y2 = x2**2 + (x2+2.2)
x = np.hstack((x1, x2))
y = np.hs... | xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')
yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
doc = Document()
doc.add(plot)
show(plot) |
glyph = Patch(x="x", y="y", fill_color="#a6cee3")
plot.add_glyph(source, glyph)
| random_line_split |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | };
run_puzzle(window, save_data, view)
}
// ========================================================================= // | &save_data.game_mut().cross_the_line,
) | random_line_split |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... |
// ========================================================================= //
| {
let view = {
let visible_rect = window.visible_rect();
View::new(
&mut window.resources(),
visible_rect,
&save_data.game_mut().cross_the_line,
)
};
run_puzzle(window, save_data, view)
} | identifier_body |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | (
window: &mut Window,
save_data: &mut SaveData,
) -> Mode {
let view = {
let visible_rect = window.visible_rect();
View::new(
&mut window.resources(),
visible_rect,
&save_data.game_mut().cross_the_line,
)
};
run_puzzle(window, save_data, v... | run_cross_the_line | identifier_name |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute... | """,
'version': '1.0',
'author': 'ClearCorp',
'category': 'Sales Management',
'website': "http://clearcorp.co.cr",
'complexity': 'normal',
'images' : [],
'depends': [
'account',
'sale',
'report',
'report_xls_template'
... | 'name': 'Product Invoice Report',
'description': """
Product Invoice Report
=======================
This module permits print the product invoice report. | random_line_split |
string.js | /**
* String utilities
* this one is compatible with frontend too, so written in a way it can be
* included in frontend, and accessible via window.Util_Str | */
(function (w) {
'use strict';
w.Util_Str = {
/**
* capitlise
* @param str
* @returns {string}
*/
capitalise(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
},
/**
* camel case
* @param str
* @param delimiter
* @returns {string}
*/
... | random_line_split | |
string.js | /**
* String utilities
* this one is compatible with frontend too, so written in a way it can be
* included in frontend, and accessible via window.Util_Str
*/
(function (w) {
'use strict';
w.Util_Str = {
/**
* capitlise
* @param str
* @returns {string}
*/
capitalise(str) {
ret... | (tmp, data) {
let output = tmp;
for (let k in data) {
let val = data[k];
// add slash when it's $
if (k.slice(0, 1) == '$') {
k = "\\" + k;
}
output = output.replace(new RegExp('{' + k + '}', 'g'), val);
}
return output;
}
};
if (typeof ... | template | identifier_name |
string.js | /**
* String utilities
* this one is compatible with frontend too, so written in a way it can be
* included in frontend, and accessible via window.Util_Str
*/
(function (w) {
'use strict';
w.Util_Str = {
/**
* capitlise
* @param str
* @returns {string}
*/
capitalise(str) {
ret... |
};
if (typeof module === 'object') {
module.exports = w.Util_Str;
}
})(this);
| {
let output = tmp;
for (let k in data) {
let val = data[k];
// add slash when it's $
if (k.slice(0, 1) == '$') {
k = "\\" + k;
}
output = output.replace(new RegExp('{' + k + '}', 'g'), val);
}
return output;
} | identifier_body |
string.js | /**
* String utilities
* this one is compatible with frontend too, so written in a way it can be
* included in frontend, and accessible via window.Util_Str
*/
(function (w) {
'use strict';
w.Util_Str = {
/**
* capitlise
* @param str
* @returns {string}
*/
capitalise(str) {
ret... |
})(this);
| {
module.exports = w.Util_Str;
} | conditional_block |
a00015.js | var a00015 =
[ | [ "player", "a00015.html#ga423655ccd6f0739c6cd730982fa6de05", null ],
[ "player_init", "a00015.html#ga5c83feea6dbd6e2448404261375365e3", null ],
[ "player_new", "a00015.html#ga75b1ecd76f93fa8893c4f2bab9fbf03b", null ],
[ "player_set_fifo_name", "a00015.html#ga2d7b416518d58ac941d831b808273f2c", null ],
... | [ "player_t", "a00005.html", "a00005" ], | random_line_split |
button.py | '''
Button Behavior
===============
The :class:`~kivy.uix.behaviors.button.ButtonBehavior`
`mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. You can combine this class with
other widgets, such as an :class:`~kivy.uix.image.Image`, to provide
alternative buttons th... |
touch.grab(self)
touch.ud[self] = True
self.last_touch = touch
self.__touch_time = time()
self._do_press()
self.dispatch('on_press')
return True
def on_touch_move(self, touch):
if touch.grab_current is self:
return True
if super(B... | return False | conditional_block |
button.py | '''
Button Behavior
===============
The :class:`~kivy.uix.behaviors.button.ButtonBehavior`
`mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. You can combine this class with
other widgets, such as an :class:`~kivy.uix.image.Image`, to provide
alternative buttons th... | (self, *args):
if self.__state_event:
self.__state_event.cancel()
self.__state_event = None
def on_touch_down(self, touch):
if super(ButtonBehavior, self).on_touch_down(touch):
return True
if touch.is_mouse_scrolling:
return False
if n... | cancel_event | identifier_name |
button.py | '''
Button Behavior
===============
The :class:`~kivy.uix.behaviors.button.ButtonBehavior`
`mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. You can combine this class with
other widgets, such as an :class:`~kivy.uix.image.Image`, to provide
alternative buttons th... | min_state_time = NumericProperty(0)
'''The minimum period of time which the widget must remain in the
`'down'` state.
.. versionadded:: 1.9.1
:attr:`min_state_time` is a float and defaults to 0.035. This value is
taken from :class:`~kivy.config.Config`.
'''
always_release = BooleanPro... | '''
| random_line_split |
button.py | '''
Button Behavior
===============
The :class:`~kivy.uix.behaviors.button.ButtonBehavior`
`mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. You can combine this class with
other widgets, such as an :class:`~kivy.uix.image.Image`, to provide
alternative buttons th... |
def on_press(self):
pass
def on_release(self):
pass
def trigger_action(self, duration=0.1):
'''Trigger whatever action(s) have been bound to the button by calling
both the on_press and on_release callbacks.
This simulates a quick button press without using any to... | if touch.grab_current is not self:
return super(ButtonBehavior, self).on_touch_up(touch)
assert(self in touch.ud)
touch.ungrab(self)
self.last_touch = touch
if (not self.always_release and
not self.collide_point(*touch.pos)):
self._do_release()
... | identifier_body |
validate_account.py | """
This module contains the 'validate_account' menu node.
"""
from textwrap import dedent
from menu.character import _options_choose_characters
def validate_account(caller, input):
"" | received by e-mail? You can try to enter it again, or
enter |yb|n to choose a different e-mail address.
""".strip("\n")).format(input.strip())
else:
player.db.valid = True
player.attributes.remove("validation_code")
text = ""
options = _options_choose... | "Prompt the user to enter the received validation code."""
text = ""
options = (
{
"key": "b",
"desc": "Go back to the e-mail address menu.",
"goto": "email_address",
},
{
"key": "_default",
"desc": "Enter the validation code.",... | identifier_body |
validate_account.py | """
This module contains the 'validate_account' menu node.
"""
from textwrap import dedent
from menu.character import _options_choose_characters
def va | aller, input):
"""Prompt the user to enter the received validation code."""
text = ""
options = (
{
"key": "b",
"desc": "Go back to the e-mail address menu.",
"goto": "email_address",
},
{
"key": "_default",
"desc": "Enter t... | lidate_account(c | identifier_name |
validate_account.py | """
This module contains the 'validate_account' menu node.
"""
from textwrap import dedent
from menu.character import _options_choose_characters
def validate_account(caller, input):
"""Prompt the user to enter the received validation code."""
text = ""
options = (
{
"key": "b",
... | return text, options
| ayer.db.valid = True
player.attributes.remove("validation_code")
text = ""
options = _options_choose_characters(player)
| conditional_block |
validate_account.py | """
This module contains the 'validate_account' menu node.
"""
from textwrap import dedent
from menu.character import _options_choose_characters
def validate_account(caller, input):
"""Prompt the user to enter the received validation code."""
text = ""
options = (
{
"key": "b",
... | player.db.valid = True
player.attributes.remove("validation_code")
text = ""
options = _options_choose_characters(player)
return text, options | enter |yb|n to choose a different e-mail address.
""".strip("\n")).format(input.strip())
else: | random_line_split |
test_location.py | """Test Home Assistant location util methods."""
# pylint: disable=too-many-public-methods
import unittest
import blumate.util.location as location_util
# Paris
COORDINATES_PARIS = (48.864716, 2.349014)
# New York
COORDINATES_NEW_YORK = (40.730610, -73.935242)
# Results for the assertion (vincenty algorithm):
# ... |
def test_get_miles(self):
"""Test getting the distance between given coordinates in miles."""
miles = location_util.vincenty(COORDINATES_PARIS,
COORDINATES_NEW_YORK,
miles=True)
self.assertEqual(round(miles, 2), ... | """Test getting the distance between given coordinates in km."""
kilometers = location_util.vincenty(COORDINATES_PARIS,
COORDINATES_NEW_YORK)
self.assertEqual(round(kilometers, 2), DISTANCE_KM) | identifier_body |
test_location.py | """Test Home Assistant location util methods."""
# pylint: disable=too-many-public-methods
import unittest
import blumate.util.location as location_util
# Paris
COORDINATES_PARIS = (48.864716, 2.349014)
# New York
COORDINATES_NEW_YORK = (40.730610, -73.935242)
# Results for the assertion (vincenty algorithm):
# ... | (unittest.TestCase):
"""Test util location methods."""
def test_get_distance(self):
"""Test getting the distance."""
meters = location_util.distance(COORDINATES_PARIS[0],
COORDINATES_PARIS[1],
COORDINATES_NEW_YORK[0... | TestLocationUtil | identifier_name |
test_location.py | """Test Home Assistant location util methods."""
# pylint: disable=too-many-public-methods
import unittest
import blumate.util.location as location_util
# Paris
COORDINATES_PARIS = (48.864716, 2.349014)
# New York
COORDINATES_NEW_YORK = (40.730610, -73.935242)
# Results for the assertion (vincenty algorithm):
# ... |
def test_get_distance(self):
"""Test getting the distance."""
meters = location_util.distance(COORDINATES_PARIS[0],
COORDINATES_PARIS[1],
COORDINATES_NEW_YORK[0],
COORDINATES_NEW_... |
class TestLocationUtil(unittest.TestCase):
"""Test util location methods.""" | random_line_split |
bufferTime.ts | import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { isScheduler } from '../util/isScheduler';
import { OperatorFunction, SchedulerAction, Sched... |
function dispatchBufferCreation<T>(this: SchedulerAction<DispatchCreateArg<T>>, state: DispatchCreateArg<T>) {
const { bufferCreationInterval, bufferTimeSpan, subscriber, scheduler } = state;
const context = subscriber.openContext();
const action = <SchedulerAction<DispatchCreateArg<T>>>this;
if (!subscriber.... | {
const subscriber: BufferTimeSubscriber<any> = state.subscriber;
const prevContext = state.context;
if (prevContext) {
subscriber.closeContext(prevContext);
}
if (!subscriber.closed) {
state.context = subscriber.openContext();
state.context.closeAction = this.schedule(state, state.bufferTimeSpa... | identifier_body |
bufferTime.ts | import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { isScheduler } from '../util/isScheduler';
import { OperatorFunction, SchedulerAction, Sched... |
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferTimeSubscriber(
subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler
));
}
}
class Context<T> {
buffer: T[] = [];
closeAction: Subscription | undefined;
}
interfac... | private bufferCreationInterval: number | null,
private maxBufferSize: number,
private scheduler: SchedulerLike) {
} | random_line_split |
bufferTime.ts | import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { isScheduler } from '../util/isScheduler';
import { OperatorFunction, SchedulerAction, Sched... |
}
function dispatchBufferCreation<T>(this: SchedulerAction<DispatchCreateArg<T>>, state: DispatchCreateArg<T>) {
const { bufferCreationInterval, bufferTimeSpan, subscriber, scheduler } = state;
const context = subscriber.openContext();
const action = <SchedulerAction<DispatchCreateArg<T>>>this;
if (!subscribe... | {
state.context = subscriber.openContext();
state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
} | conditional_block |
bufferTime.ts | import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { isScheduler } from '../util/isScheduler';
import { OperatorFunction, SchedulerAction, Sched... | (private bufferTimeSpan: number,
private bufferCreationInterval: number | null,
private maxBufferSize: number,
private scheduler: SchedulerLike) {
}
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferTimeSubscriber(
subscriber... | constructor | identifier_name |
F8B38262C2AC00CF4E3E653F2987BDADC86F839E.js | this.NesDb = this.NesDb || {};
NesDb[ 'F8B38262C2AC00CF4E3E653F2987BDADC86F839E' ] = {
"$": {
"name": "Makaimura",
"altname": "魔界村",
"class": "Licensed",
"catalog": "CAP-MK",
"publisher": "Capcom",
"developer": "Capcom",
"portdeveloper": "Micronics / Khaos",
"region": "Japan",
"players": "2",
"dat... | "$": {
"type": "74xx161"
}
},
{
"$": {
"type": "74xx32"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
}
]
}; | }
}
],
"chip": [
{ | random_line_split |
utils.rs | #[allow(dead_code)]
pub struct XorShift {
x : i32,
max : i32,
cur : usize,
count : usize,
}
impl XorShift {
#[allow(dead_code)]
pub fn new(seed : i32, max : i32, count: usize) -> XorShift {
XorShift{x: seed, max: max, count: count, cur: 0}
}
}
impl Iterator for XorShift {
typ... | self.x ^= self.x >> 12; // a
self.x ^= self.x << 25; // b
self.x ^= self.x >> 27; // c
self.cur += 1;
return Some(self.x % self.max);
}
} | return None;
} | random_line_split |
utils.rs | #[allow(dead_code)]
pub struct XorShift {
x : i32,
max : i32,
cur : usize,
count : usize,
}
impl XorShift {
#[allow(dead_code)]
pub fn new(seed : i32, max : i32, count: usize) -> XorShift {
XorShift{x: seed, max: max, count: count, cur: 0}
}
}
impl Iterator for XorShift {
typ... |
self.x ^= self.x >> 12; // a
self.x ^= self.x << 25; // b
self.x ^= self.x >> 27; // c
self.cur += 1;
return Some(self.x % self.max);
}
}
| {
return None;
} | conditional_block |
utils.rs | #[allow(dead_code)]
pub struct | {
x : i32,
max : i32,
cur : usize,
count : usize,
}
impl XorShift {
#[allow(dead_code)]
pub fn new(seed : i32, max : i32, count: usize) -> XorShift {
XorShift{x: seed, max: max, count: count, cur: 0}
}
}
impl Iterator for XorShift {
type Item = i32;
fn next(&mut self) ->... | XorShift | identifier_name |
15.9.5.10-11.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | {
var start = TimeFromYear(YearFromTime(t));
var stop = TimeFromYear(YearFromTime(t) + 1);
for (var d = start; d < stop; d += msPerDay)
{
new TestCase( SECTION,
"(new Date("+d+")).getDate()",
DateFromTime(LocalTime(d)),
(new Date(d)).getDate() );
}
} | identifier_body | |
15.9.5.10-11.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
}
| {
new TestCase( SECTION,
"(new Date("+d+")).getDate()",
DateFromTime(LocalTime(d)),
(new Date(d)).getDate() );
} | conditional_block |
15.9.5.10-11.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | ( t ) {
var start = TimeFromYear(YearFromTime(t));
var stop = TimeFromYear(YearFromTime(t) + 1);
for (var d = start; d < stop; d += msPerDay)
{
new TestCase( SECTION,
"(new Date("+d+")).getDate()",
DateFromTime(LocalTime(d)),
(new Date(d)).getDate() );... | addTestCase | identifier_name |
15.9.5.10-11.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "15.9.5.10";
var VERSION = "ECMA_1";
startTest();
var TITLE = "Date.prototype.getDate()";
writeHeaderToLog( SECTION + " "+ TITLE);
// some daylight savings time cases
var DST_END_1998 = GetDSTEnd(TimeFromYear(1... | 3.Return DateFromTime(LocalTime(t)). | random_line_split |
angular-dragula.js | ;(function(dragula){
'use strict';
angular.module('angular-dragula', [])
.factory('ngDragulaFactory', ['$timeout', function($timeout){
function get(name) | ;
return {
get: get
};
}])
.directive('ngDragula', ['ngDragulaFactory', function(ngDragulaFactory){
return {
restrict: 'A',
scope: {
config: '='
},
link: function(scope, element, attrs){
var drag = scope.config;
ngDragulaFa... | {
return $timeout(function(){
if(name === 'get'){
throw new Error('RESERVE_WORD');
}
if(this[name]){
return this[name]
}else{
throw new Error('NOT_FOUND');
}
}.bind(this), 500)
} | identifier_body |
angular-dragula.js | ;(function(dragula){
'use strict';
angular.module('angular-dragula', [])
.factory('ngDragulaFactory', ['$timeout', function($timeout){
function | (name){
return $timeout(function(){
if(name === 'get'){
throw new Error('RESERVE_WORD');
}
if(this[name]){
return this[name]
}else{
throw new Error('NOT_FOUND');
}
}.bind(this), 500)
};
return {
get... | get | identifier_name |
angular-dragula.js | ;(function(dragula){
'use strict';
angular.module('angular-dragula', [])
.factory('ngDragulaFactory', ['$timeout', function($timeout){
function get(name){
return $timeout(function(){ | if(this[name]){
return this[name]
}else{
throw new Error('NOT_FOUND');
}
}.bind(this), 500)
};
return {
get: get
};
}])
.directive('ngDragula', ['ngDragulaFactory', function(ngDragulaFactory){
return {
restric... | if(name === 'get'){
throw new Error('RESERVE_WORD');
} | random_line_split |
angular-dragula.js | ;(function(dragula){
'use strict';
angular.module('angular-dragula', [])
.factory('ngDragulaFactory', ['$timeout', function($timeout){
function get(name){
return $timeout(function(){
if(name === 'get'){
throw new Error('RESERVE_WORD');
}
if(this[name]) | else{
throw new Error('NOT_FOUND');
}
}.bind(this), 500)
};
return {
get: get
};
}])
.directive('ngDragula', ['ngDragulaFactory', function(ngDragulaFactory){
return {
restrict: 'A',
scope: {
config: '='
},
l... | {
return this[name]
} | conditional_block |
i2c_esp.py | # i2c_esp.py Test program for asi2c.py
# Tests Responder on ESP8266
# The MIT License (MIT)
#
# Copyright (c) 2018 Peter Hinch
#
# 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 restr... |
loop = asyncio.get_event_loop()
loop.create_task(receiver())
loop.create_task(sender())
try:
loop.run_forever()
finally:
chan.close() # for subsequent runs
| await swriter.awrite(''.join((ujson.dumps(txdata), '\n')))
txdata[1] += 1
await asyncio.sleep_ms(1500) | conditional_block |
i2c_esp.py | # i2c_esp.py Test program for asi2c.py
# Tests Responder on ESP8266
# The MIT License (MIT)
#
# Copyright (c) 2018 Peter Hinch
#
# 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 restr... |
loop = asyncio.get_event_loop()
loop.create_task(receiver())
loop.create_task(sender())
try:
loop.run_forever()
finally:
chan.close() # for subsequent runs
| swriter = asyncio.StreamWriter(chan, {})
txdata = [0, 0]
while True:
await swriter.awrite(''.join((ujson.dumps(txdata), '\n')))
txdata[1] += 1
await asyncio.sleep_ms(1500) | identifier_body |
i2c_esp.py | # i2c_esp.py Test program for asi2c.py
# Tests Responder on ESP8266
# The MIT License (MIT)
#
# Copyright (c) 2018 Peter Hinch
#
# 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 restr... | ():
swriter = asyncio.StreamWriter(chan, {})
txdata = [0, 0]
while True:
await swriter.awrite(''.join((ujson.dumps(txdata), '\n')))
txdata[1] += 1
await asyncio.sleep_ms(1500)
loop = asyncio.get_event_loop()
loop.create_task(receiver())
loop.create_task(sender())
try:
loop.run_f... | sender | identifier_name |
i2c_esp.py | # i2c_esp.py Test program for asi2c.py
# Tests Responder on ESP8266
# The MIT License (MIT)
#
# Copyright (c) 2018 Peter Hinch
#
# 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 restr... | from machine import Pin, I2C
import asi2c
import ujson
i2c = I2C(scl=Pin(0),sda=Pin(2)) # software I2C
syn = Pin(5)
ack = Pin(4)
chan = asi2c.Responder(i2c, syn, ack)
async def receiver():
sreader = asyncio.StreamReader(chan)
await chan.ready()
print('started')
for _ in range(5): # Test flow control... | # ack Y8 - 4
# gnd - gnd
import uasyncio as asyncio | random_line_split |
networking.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 script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory};
use task::{Task, TaskCanceller};
use... | impl NetworkingTaskSource {
/// This queues a task that will not be cancelled when its associated
/// global scope gets destroyed.
pub fn queue_unconditionally<T>(&self, msg: Box<T>) -> Result<(), ()>
where
T: Task + Send + 'static,
{
self.0.send(CommonScriptMsg::Task(ScriptThreadEve... | random_line_split | |
networking.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 script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory};
use task::{Task, TaskCanceller};
use... | (pub Box<ScriptChan + Send + 'static>);
impl Clone for NetworkingTaskSource {
fn clone(&self) -> NetworkingTaskSource {
NetworkingTaskSource(self.0.clone())
}
}
impl TaskSource for NetworkingTaskSource {
fn queue_with_canceller<T>(
&self,
msg: Box<T>,
canceller: &TaskCancel... | NetworkingTaskSource | identifier_name |
scraper.py | import abc
import xbmcaddon
abstractstaticmethod = abc.abstractmethod
class abstractclassmethod(classmethod):
__isabstractmethod__ = True
def __init__(self, callable):
callable.__isabstractmethod__ = True
super(abstractclassmethod, self).__init__(callable)
class Scraper:
__metaclass__ = a... | (self, title, year, imdb, debrid = False):
"""
scrapes scraper site for movie links
Args:
title: movie title -> str
year: year the movie came out -> str
imdb: imdb identifier -> str
debrid: boolean indicating whether to use debrid links if available -> bool
Returns:
... | scrape_movie | identifier_name |
scraper.py | import abc
import xbmcaddon
abstractstaticmethod = abc.abstractmethod
class abstractclassmethod(classmethod):
__isabstractmethod__ = True
def __init__(self, callable):
callable.__isabstractmethod__ = True
super(abstractclassmethod, self).__init__(callable)
class Scraper:
__metaclass__ = a... | domains = ['localdomain']
name = "Scraper"
@classmethod
def get_setting(cals, key):
return xbmcaddon.Addon('script.module.universalscrapers').getSetting(key)
@classmethod
def _is_enabled(clas):
return clas.get_setting(clas.name + '_enabled') == 'true'
@classmethod
def ... | random_line_split | |
scraper.py | import abc
import xbmcaddon
abstractstaticmethod = abc.abstractmethod
class abstractclassmethod(classmethod):
__isabstractmethod__ = True
def __init__(self, callable):
callable.__isabstractmethod__ = True
super(abstractclassmethod, self).__init__(callable)
class Scraper:
__metaclass__ = a... |
def scrape_movie(self, title, year, imdb, debrid = False):
"""
scrapes scraper site for movie links
Args:
title: movie title -> str
year: year the movie came out -> str
imdb: imdb identifier -> str
debrid: boolean indicating whether to use debrid links if available ... | xml = [
'<setting id="%s_enabled" ''type="bool" label="Enabled" default="true"/>' % (clas.name)
]
return xml | identifier_body |
sorttargets.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.build_gra... | register('--reverse', action='store_true', default=False,
help='Sort least-dependent to most-dependent.')
def console_output(self, targets):
sorted_targets = sort_targets(targets)
# sort_targets already returns targets in reverse topologically sorted order.
if not self.get_options().reve... | @classmethod
def register_options(cls, register):
super(SortTargets, cls).register_options(register) | random_line_split |
sorttargets.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.build_gra... | sorted_targets = sort_targets(targets)
# sort_targets already returns targets in reverse topologically sorted order.
if not self.get_options().reverse:
sorted_targets = reversed(sorted_targets)
for target in sorted_targets:
if target in self.context.target_roots:
yield target.address.ref... | identifier_body | |
sorttargets.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.build_gra... | (self, targets):
sorted_targets = sort_targets(targets)
# sort_targets already returns targets in reverse topologically sorted order.
if not self.get_options().reverse:
sorted_targets = reversed(sorted_targets)
for target in sorted_targets:
if target in self.context.target_roots:
yie... | console_output | identifier_name |
sorttargets.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.build_gra... |
for target in sorted_targets:
if target in self.context.target_roots:
yield target.address.reference()
| sorted_targets = reversed(sorted_targets) | conditional_block |
transform.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 values::computed::{Length, LengthOrPercentage, Number};
use values::generics::transform::TimingFunction as GenericTimingFunction;
use values::generics::transform::TransformOrigin as GenericTransformOrigin;
/// The computed value of a CSS `<transform-origin>`
pub type TransformOrigin = GenericTransformOrigin<Length... |
//! Computed types for CSS values that are related to transformations.
use properties::animated_properties::Animatable; | random_line_split |
transform.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/. */
//! Computed types for CSS values that are related to transformations.
use properties::animated_properties::Anima... |
}
impl Animatable for TransformOrigin {
#[inline]
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
Ok(Self::new(
self.horizontal.add_weighted(&other.horizontal, self_portion, other_portion)?,
self.vertical.add_weighted(&other.ver... | {
Self::new(
LengthOrPercentage::Percentage(0.5),
LengthOrPercentage::Percentage(0.5),
Length::from_px(0)
)
} | identifier_body |
transform.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/. */
//! Computed types for CSS values that are related to transformations.
use properties::animated_properties::Anima... | (&self, other: &Self) -> Result<f64, ()> {
self.compute_squared_distance(other).map(f64::sqrt)
}
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
Ok(
self.horizontal.compute_squared_distance(&other.horizontal)? +
self.vertical.compute_s... | compute_distance | identifier_name |
webpack.config.babel.js | import path from 'path'
import webpack from 'webpack'
import UglifyJsPlugin from 'uglifyjs-webpack-plugin'
const config = {
mode: process.env.NODE_ENV,
entry: [
'./src/index.js'
], | library: 'threesixty',
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
}
]
}
]
},
plugins: [
new webpack.DefinePlugin({
... | output: {
path: path.resolve(__dirname, 'dist'),
filename: process.env.NODE_ENV === 'production' ? 'threesixty.min.js' : 'threesixty.js', | random_line_split |
eep-service.ts | } from '../app/app-statistics.service';
import { CacheService } from './cache-service';
export enum FileNames {
eepOutJsonOut = 'ak-eep-out.json',
eepOutJsonOutFinished = 'ak-eep-out-json.isfinished',
eepOutLog = 'ak-eep-out.log',
serverOutCommands = 'ak-eep-in.commands',
serverWatching = 'ak-server.iswatch... | fs.writeFileSync(cacheFile, fileContents);
if (data.eventCounter) {
const counterFile = path.resolve(this.dir, FileNames.serverEventCounter);
fs.writeFileSync(counterFile, data.eventCounter);
}
}
} catch (err) {
console.log(err);
}
performance.mark('e... | const fileContents = JSON.stringify(data); | random_line_split |
eep-service.ts | } from '../app/app-statistics.service';
import { CacheService } from './cache-service';
export enum FileNames {
eepOutJsonOut = 'ak-eep-out.json',
eepOutJsonOutFinished = 'ak-eep-out-json.isfinished',
eepOutLog = 'ak-eep-out.log',
serverOutCommands = 'ak-eep-in.commands',
serverWatching = 'ak-server.iswatch... |
}
public createAkServerFile() {
const watchFile = path.resolve(this.dir, FileNames.serverWatching);
// Create the serverWatchingFile
fs.closeSync(fs.openSync(watchFile, 'w'));
this.deleteFileOnExit(FileNames.serverWatching);
}
private deleteFileOnExit(fileName: string) {
// Delete the eve... | {
console.log('[FILE] Wait for: ' + path.basename(expectedFile) + ' in ' + path.dirname(expectedFile));
const watcher = fs.watch(path.dirname(expectedFile), {}, (eventType: string, filename: string) => {
if (filename === path.basename(expectedFile) && fs.existsSync(expectedFile)) {
console... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.