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 |
|---|---|---|---|---|
csssupportsrule.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 cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... |
}
}
impl SpecificCSSRule for CSSSupportsRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::SUPPORTS_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.... | {
let global = self.global();
let win = global.as_window();
let url = win.Document().url();
let quirks_mode = win.Document().quirks_mode();
let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports),
... | conditional_block |
csssupportsrule.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 cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... | let rule = self.supportsrule.write_with(&mut guard);
rule.condition = cond;
rule.enabled = enabled;
}
}
}
impl SpecificCSSRule for CSSSupportsRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleC... | let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports),
PARSING_MODE_DEFAULT,
quirks_mode);
let enabled = cond.eval(&context);
... | random_line_split |
csssupportsrule.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 cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... |
}
impl SpecificCSSRule for CSSSupportsRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::SUPPORTS_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.suppor... | {
let mut input = ParserInput::new(&text);
let mut input = Parser::new(&mut input);
let cond = SupportsCondition::parse(&mut input);
if let Ok(cond) = cond {
let global = self.global();
let win = global.as_window();
let url = win.Document().url();
... | identifier_body |
csssupportsrule.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 cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindi... | (&self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
let rule = self.supportsrule.read_with(&guard);
rule.condition.to_css_string().into()
}
/// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface
pub fn set_condition_text(&self, text:... | get_condition_text | identifier_name |
netns_linux.rs | extern crate nix;
use std::error::Error;
use std::fmt;
use std::path::PathBuf;
use nix::sched::{unshare, setns};
use nix::fcntl::open;
use nix::unistd::{getpid, gettid};
use nix::sys::stat::Mode;
use nix::Error as NError;
pub struct NetNS {
fd: i32,
path: PathBuf,
}
#[derive(Debug)]
pub enum NetNSError {
... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "NetNS {{ fd: {}, path: {} }}", self.fd, self.path.display())
}
}
impl NetNS {
pub fn new() -> Result<NetNS, NetNSError> {
unshare(nix::sched::CLONE_NEWNET).expect("failed");
NetNS::get()
}
pub fn get() -> Result<NetNS,... | fmt | identifier_name |
netns_linux.rs | extern crate nix;
use std::error::Error;
use std::fmt;
use std::path::PathBuf;
use nix::sched::{unshare, setns};
use nix::fcntl::open;
use nix::unistd::{getpid, gettid};
use nix::sys::stat::Mode;
use nix::Error as NError;
pub struct NetNS {
fd: i32,
path: PathBuf,
}
#[derive(Debug)]
pub enum NetNSError {
... |
pub fn set(ns: NetNS) -> Result<(), NError> {
setns(ns.fd, nix::sched::CLONE_NEWNET)
}
pub fn get_from_thread(pid: i32, tid: i32) -> Result<NetNS, NetNSError> {
return NetNS::get_from_path(PathBuf::from(format!("/proc/{}/task/{}/ns/net", pid, tid)
.as_str()));
}
pub f... | {
return NetNS::get_from_thread(getpid(), gettid());
} | identifier_body |
netns_linux.rs | extern crate nix;
use std::error::Error;
use std::fmt; | use nix::unistd::{getpid, gettid};
use nix::sys::stat::Mode;
use nix::Error as NError;
pub struct NetNS {
fd: i32,
path: PathBuf,
}
#[derive(Debug)]
pub enum NetNSError {
CreateNetNSError,
}
impl Error for NetNSError {
fn description(&self) -> &str {
"Cannot create"
}
}
impl fmt::Debug f... | use std::path::PathBuf;
use nix::sched::{unshare, setns};
use nix::fcntl::open; | random_line_split |
config.js | import {writeFile} from 'fs-promise';
import {get, has, merge, set} from 'lodash/fp';
import flatten from 'flat';
import fs from 'fs';
import path from 'path';
const data = new WeakMap();
const initial = new WeakMap(); | }
clone() {
return Object.assign({}, data.get(this));
}
get(keypath) {
return get(keypath, data.get(this));
}
has(keypath) {
return has(keypath, data.get(this));
}
inspect() {
return data.get(this);
}
merge(extra) {
data.set(this, merge(data.get(this), extra));
}
set(ke... |
export default class Config {
constructor(d) {
data.set(this, d);
initial.set(this, Object.assign({}, d)); | random_line_split |
config.js | import {writeFile} from 'fs-promise';
import {get, has, merge, set} from 'lodash/fp';
import flatten from 'flat';
import fs from 'fs';
import path from 'path';
const data = new WeakMap();
const initial = new WeakMap();
export default class Config {
constructor(d) {
data.set(this, d);
initial.set(this, Objec... |
toJSON() {
const keys = Object.keys(flatten(data.get(this), {safe: true}));
const init = initial.get(this);
let target;
try {
const filepath = path.join(process.cwd(), `.boilerizerc`);
// Using sync here because toJSON can't have async functions in it
// eslint-disable-next-line no... | {
const out = this.toString();
return await writeFile(`.boilerizerc`, out);
} | identifier_body |
config.js | import {writeFile} from 'fs-promise';
import {get, has, merge, set} from 'lodash/fp';
import flatten from 'flat';
import fs from 'fs';
import path from 'path';
const data = new WeakMap();
const initial = new WeakMap();
export default class Config {
constructor(d) {
data.set(this, d);
initial.set(this, Objec... |
return acc;
}, target);
}
toString() {
return JSON.stringify(this, null, 2);
}
}
| {
const val = this.get(key);
acc = set(key, val, acc);
} | conditional_block |
config.js | import {writeFile} from 'fs-promise';
import {get, has, merge, set} from 'lodash/fp';
import flatten from 'flat';
import fs from 'fs';
import path from 'path';
const data = new WeakMap();
const initial = new WeakMap();
export default class Config {
| (d) {
data.set(this, d);
initial.set(this, Object.assign({}, d));
}
clone() {
return Object.assign({}, data.get(this));
}
get(keypath) {
return get(keypath, data.get(this));
}
has(keypath) {
return has(keypath, data.get(this));
}
inspect() {
return data.get(this);
}
merg... | constructor | identifier_name |
packed.js | const ASSETS_MODS_LENGTH = 13;//'/assets/mods/'.length;
const CONTENT_TYPES = {
'css': 'text/css',
'js': 'text/javascript',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'html': 'text/html',
'htm': 'text/html'
};
/**
* @type {Map<string, JSZip>}
*/
const jszipCac... |
return url;
}
}
| {
url = url.substr(9); // '/ccloader'.length
} | conditional_block |
packed.js | const ASSETS_MODS_LENGTH = 13;//'/assets/mods/'.length;
const CONTENT_TYPES = {
'css': 'text/css',
'js': 'text/javascript',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'html': 'text/html',
'htm': 'text/html'
};
/**
* @type {Map<string, JSZip>}
*/
const jszipCac... | (url) {
url = this._normalize(url);
return url.substr(url.indexOf('/', ASSETS_MODS_LENGTH) + 1);
}
/**
*
* @param {string} url
*/
_normalize(url) {
url = url.replace(/\\/g, '/').replace(/\/\//, '/');
//TODO: resolve absolute paths
if (!url.startsWith('/')) {
url = '/' + url;
}
if (url.startsW... | _assetPath | identifier_name |
packed.js | const ASSETS_MODS_LENGTH = 13;//'/assets/mods/'.length;
const CONTENT_TYPES = {
'css': 'text/css',
'js': 'text/javascript',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'html': 'text/html',
'htm': 'text/html'
};
/**
* @type {Map<string, JSZip>}
*/
const jszipCac... | return e;
}
}
/**
*
* @param {string} url
* @returns {Promise<string[]>}
*/
async getFiles(url) {
const zip = await this._openZip(url);
const folder = this._openFolder(zip, this._assetPath(url));
const result = [];
folder.forEach((relativePath, file) => {
if (!file.dir) {
result.push(r... | {
try {
const zip = await this._openZip(url);
const file = zip.file(this._assetPath(url));
if (file === null) {
return new Response(new Blob(), {
status: 404,
statusText: 'not found'
});
}
return new Response(await file.async('blob'), {
headers: {
'Content-Type': this._conte... | identifier_body |
packed.js | const ASSETS_MODS_LENGTH = 13;//'/assets/mods/'.length;
const CONTENT_TYPES = {
'css': 'text/css',
'js': 'text/javascript',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'html': 'text/html',
'htm': 'text/html'
};
/**
* @type {Map<string, JSZip>}
*/
const jszipCac... | *
* @param {string} url
*/
async get(url) {
try {
const zip = await this._openZip(url);
const file = zip.file(this._assetPath(url));
if (file === null) {
return new Response(new Blob(), {
status: 404,
statusText: 'not found'
});
}
return new Response(await file.async(... | // eslint-disable-next-line no-unused-vars
class PackedManager {
/** | random_line_split |
20160708081226-readme-in-versions.js | var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
var fs = require('fs');
var path = require('path');
exports.up = function(db, callback) {
var filePath = path.join(__dirname + '/sqls/20160708081226-readme-in-versions-up.sql');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
... | }; | }); | random_line_split |
rest_mod.rs | ///! A helper to make local computer browsing of file paths possible
///! on smarter devices a dialog would do it ....
use dirs;
use std::{fs, path::Path, string::String, vec::Vec};
pub fn return_directory(given: String) -> Vec<String> | if entry.is_err() {
continue;
}
let entry = entry.unwrap();
// filter out ".dirs"
if entry.file_name().to_str().unwrap_or("").starts_with(".") {
continue;
... | {
let trying_path = if given.is_empty() {
dirs::home_dir()
} else {
Path::new(&given).canonicalize().ok()
};
match trying_path {
Some(try_as_dir) => {
if let Ok(good_dir) = fs::read_dir(&try_as_dir) {
let mut return_vec = vec![];
// a... | identifier_body |
rest_mod.rs | ///! A helper to make local computer browsing of file paths possible
///! on smarter devices a dialog would do it ....
use dirs;
use std::{fs, path::Path, string::String, vec::Vec};
pub fn return_directory(given: String) -> Vec<String> {
let trying_path = if given.is_empty() {
dirs::home_dir()
} else {... |
}
for entry in good_dir {
if entry.is_err() {
continue;
}
let entry = entry.unwrap();
// filter out ".dirs"
if entry.file_name().to_str().unwrap_or("").starts_wit... | {
return_vec.push(parent_unicode_str.to_string());
} | conditional_block |
rest_mod.rs | ///! A helper to make local computer browsing of file paths possible
///! on smarter devices a dialog would do it ....
use dirs;
use std::{fs, path::Path, string::String, vec::Vec};
pub fn return_directory(given: String) -> Vec<String> {
let trying_path = if given.is_empty() {
dirs::home_dir()
} else {... |
for entry in good_dir {
if entry.is_err() {
continue;
}
let entry = entry.unwrap();
// filter out ".dirs"
if entry.file_name().to_str().unwrap_or("").starts_with(".") {
... | } | random_line_split |
rest_mod.rs | ///! A helper to make local computer browsing of file paths possible
///! on smarter devices a dialog would do it ....
use dirs;
use std::{fs, path::Path, string::String, vec::Vec};
pub fn | (given: String) -> Vec<String> {
let trying_path = if given.is_empty() {
dirs::home_dir()
} else {
Path::new(&given).canonicalize().ok()
};
match trying_path {
Some(try_as_dir) => {
if let Ok(good_dir) = fs::read_dir(&try_as_dir) {
let mut return_vec ... | return_directory | identifier_name |
scanner.rs | use std::old_io as io;
use std::fmt;
#[derive(Debug, PartialEq)]
pub enum Token {
BinOp(&'static str),
Number(i64),
EOL,
EOF,
}
impl fmt::String for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Token::BinOp(ref op) => write!(f, "BinOp: {}", op),
... | }
struct MockReader {
ch: char
}
impl Reader for MockReader {
fn read_byte(&mut self) -> io::IoResult<u8> {
Ok('+' as u8)
}
fn read(&mut self, buf: &mut [u8]) -> io::IoResult<usize> {
Ok(0)
}
}
#[test]
fn add_token() {
let mut scanner = Scanner::new(MockReader{ch: '+'});
l... | Ok(c) => {debug!("curr char: {}", c); Ok(c as char) },
Err(e) => Err(e),
};
} | random_line_split |
scanner.rs | use std::old_io as io;
use std::fmt;
#[derive(Debug, PartialEq)]
pub enum Token {
BinOp(&'static str),
Number(i64),
EOL,
EOF,
}
impl fmt::String for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
pub struct Scanner<R: io::Reader> {
curr_char: io::IoResult<char>,
reader: R,
}
impl<R: io::Reader> Scanner<R> {
pub fn new(r: R) -> Scanner<R> {
let mut scanner = Scanner {
curr_char: Result::Ok(' '),
reader: r,
};
scanner.get_char();
return scan... | {
match *self {
Token::BinOp(ref op) => write!(f, "BinOp: {}", op),
Token::Number(n) => write!(f, "Number: {}", n),
Token::EOF => write!(f, "EOF"),
Token::EOL => write!(f, "EOL"),
}
} | identifier_body |
scanner.rs | use std::old_io as io;
use std::fmt;
#[derive(Debug, PartialEq)]
pub enum Token {
BinOp(&'static str),
Number(i64),
EOL,
EOF,
}
impl fmt::String for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Token::BinOp(ref op) => write!(f, "BinOp: {}", op),
... | ,
Ok(c) if c.is_digit(10) => Ok(Token::Number(self.get_number())),
Ok(_) => { self.get_char(); Err("Unknown symbol") },
Err(ref e) => { Ok(Token::EOF) },
}
}
fn get_number(&mut self) -> i64 {
let mut number = 0i64;
loop {
match self.curr_c... | { self.curr_char = Ok(' '); Ok(Token::EOL) } | conditional_block |
scanner.rs | use std::old_io as io;
use std::fmt;
#[derive(Debug, PartialEq)]
pub enum Token {
BinOp(&'static str),
Number(i64),
EOL,
EOF,
}
impl fmt::String for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Token::BinOp(ref op) => write!(f, "BinOp: {}", op),
... | (&mut self) -> Result<Token, &'static str> {
match self.curr_char {
Ok(' ') => { self.get_char(); self.get_token() },
Ok('+') => { self.get_char(); Ok(Token::BinOp("+")) },
Ok('-') => { self.get_char(); Ok(Token::BinOp("-")) },
Ok('*') => { self.get_char(); Ok(Tok... | get_token | identifier_name |
index.js | 'use strict';
var intlNameInitials = function () {
};
var pattern = '{0}{1}';
function _firstLetter(text) {
return text.charAt(0);
}
function _upperCase(letter) {
if (letter === 'ı'){
return 'I';
}
return letter.toUpperCase();
}
function _isHangul(l){
if ((l > 44032) && (l < 55203)) {... |
function isThai(a){
var thaiRegex = '[\u0E01-\u0E3A\u0E40-\u0E5B]';
var re = new RegExp(thaiRegex,'i');
if (a.length === 1){
return true;
} else {
var letter = _firstLetter(a);
if (re.test(a)) {
return true;
}
}
return false;
}
function isCJK(a){
... | return true;
}
return false;
}
| random_line_split |
index.js | 'use strict';
var intlNameInitials = function () {
};
var pattern = '{0}{1}';
function _firstLetter(text) {
return text.charAt(0);
}
function _upperCase(letter) |
function _isHangul(l){
if ((l > 44032) && (l < 55203)) {
return true;
}
return false;
}
function _initials(letter) {
var l = letter.charCodeAt(0);
// Generated by regenerate and unicode-8.0.0
// Greek 117
// Latin 991
// Cyrillic 302
var alphaRegex = '[A-Za-z\xAA\xBA\xC0-... | {
if (letter === 'ı'){
return 'I';
}
return letter.toUpperCase();
}
| identifier_body |
index.js | 'use strict';
var intlNameInitials = function () {
};
var pattern = '{0}{1}';
function _firstLetter(text) {
return text.charAt(0);
}
function _upperCase(letter) {
if (letter === 'ı'){
return 'I';
}
return letter.toUpperCase();
}
function _isHangul(l){
if ((l > 44032) && (l < 55203)) {... |
fields.forEach(function(field){
if (name.hasOwnProperty(field)) {
if (name[field] === null || name[field].length === 0){
// Nothing to do. but keeping it as placeholder
} else {
if (_isSupportedInitials(_firstLetter(name[field]))) {
... |
return undefined;
}
| conditional_block |
index.js | 'use strict';
var intlNameInitials = function () {
};
var pattern = '{0}{1}';
function _firstLetter(text) {
return text.charAt(0);
}
function | (letter) {
if (letter === 'ı'){
return 'I';
}
return letter.toUpperCase();
}
function _isHangul(l){
if ((l > 44032) && (l < 55203)) {
return true;
}
return false;
}
function _initials(letter) {
var l = letter.charCodeAt(0);
// Generated by regenerate and unicode-8.0... | _upperCase | identifier_name |
test_saferef.py | import unittest
from django.dispatch.saferef import safeRef
from django.utils.six.moves import xrange
class Test1(object):
def x(self):
pass
def test2(obj):
pass
class Test2(object):
def __call__(self, obj):
pass
class SaferefTests(unittest.TestCase):
def setUp(self):
ts... |
def testShortCircuit(self):
"""Test that creation short-circuits to reuse existing references"""
sd = {}
for s in self.ss:
sd[s] = 1
for t in self.ts:
if hasattr(t, 'x'):
self.assertTrue(safeRef(t.x) in sd)
else:
s... | """Test that the references are valid (return instance methods)"""
for s in self.ss:
self.assertTrue(s()) | identifier_body |
test_saferef.py | import unittest
from django.dispatch.saferef import safeRef
from django.utils.six.moves import xrange
class Test1(object):
def x(self):
pass
def test2(obj):
pass
class Test2(object):
def __call__(self, obj):
pass
class SaferefTests(unittest.TestCase):
def | (self):
ts = []
ss = []
for x in xrange(5000):
t = Test1()
ts.append(t)
s = safeRef(t.x, self._closure)
ss.append(s)
ts.append(test2)
ss.append(safeRef(test2, self._closure))
for x in xrange(30):
t = Test2()
... | setUp | identifier_name |
test_saferef.py | import unittest
from django.dispatch.saferef import safeRef
from django.utils.six.moves import xrange
class Test1(object):
def x(self):
pass
def test2(obj):
pass
class Test2(object):
def __call__(self, obj):
pass
class SaferefTests(unittest.TestCase):
def setUp(self):
ts... | """Test the "in" operator for safe references (cmp)"""
for t in self.ts[:50]:
self.assertTrue(safeRef(t.x) in self.ss)
def testValid(self):
"""Test that the references are valid (return instance methods)"""
for s in self.ss:
self.assertTrue(s())
def test... | def tearDown(self):
del self.ts
del self.ss
def testIn(self): | random_line_split |
test_saferef.py | import unittest
from django.dispatch.saferef import safeRef
from django.utils.six.moves import xrange
class Test1(object):
def x(self):
pass
def test2(obj):
pass
class Test2(object):
def __call__(self, obj):
pass
class SaferefTests(unittest.TestCase):
def setUp(self):
ts... |
else:
self.assertTrue(safeRef(t) in sd)
def testRepresentation(self):
"""Test that the reference object's representation works
XXX Doesn't currently check the results, just that no error
is raised
"""
repr(self.ss[-1])
def _closure(self... | self.assertTrue(safeRef(t.x) in sd) | conditional_block |
index.js | 'use strict';
module.exports = function (verificationToken, onSlackEvent) {
return function (req, res, next) {
if (req.method !== 'POST') return next();
if (!req.body) { | }
var body = req.body.payload ? JSON.parse(req.body.payload) : req.body;
if (verificationToken && body.token !== verificationToken) {
res.statusCode = 403;
res.end('could not verify slack token');
return;
}
if (body.type === 'url_verification') return res.end(body.challenge);
... | res.stausCode = 400;
res.end('bad request - no body found');
return; | random_line_split |
gitlabGroupUpdate.ts | import { sendToLagoonLogs } from '@lagoon/commons/dist/logs';
import { getGroup } from '@lagoon/commons/dist/gitlabApi';
import { updateGroup, sanitizeGroupName } from '@lagoon/commons/dist/api';
import { WebhookRequestData } from '../types';
export async function | (webhook: WebhookRequestData) {
const { webhooktype, event, uuid, body } = webhook;
try {
const group = await getGroup(body.group_id);
const { id, path: name, full_path } = group;
const { old_full_path } = body;
const meta = {
data: group,
group: id
};
await updateGroup(saniti... | gitlabGroupUpdate | identifier_name |
gitlabGroupUpdate.ts | import { sendToLagoonLogs } from '@lagoon/commons/dist/logs';
import { getGroup } from '@lagoon/commons/dist/gitlabApi';
import { updateGroup, sanitizeGroupName } from '@lagoon/commons/dist/api';
import { WebhookRequestData } from '../types';
export async function gitlabGroupUpdate(webhook: WebhookRequestData) | uuid,
`${webhooktype}:${event}:handled`,
meta,
`Updated group ${name}`
);
return;
} catch (error) {
sendToLagoonLogs(
'error',
'',
uuid,
`${webhooktype}:${event}:unhandled`,
{ data: body },
`Could not update group, reason: ${error}`
);
... | {
const { webhooktype, event, uuid, body } = webhook;
try {
const group = await getGroup(body.group_id);
const { id, path: name, full_path } = group;
const { old_full_path } = body;
const meta = {
data: group,
group: id
};
await updateGroup(sanitizeGroupName(old_full_path), {
... | identifier_body |
gitlabGroupUpdate.ts | import { sendToLagoonLogs } from '@lagoon/commons/dist/logs';
import { getGroup } from '@lagoon/commons/dist/gitlabApi';
import { updateGroup, sanitizeGroupName } from '@lagoon/commons/dist/api';
|
export async function gitlabGroupUpdate(webhook: WebhookRequestData) {
const { webhooktype, event, uuid, body } = webhook;
try {
const group = await getGroup(body.group_id);
const { id, path: name, full_path } = group;
const { old_full_path } = body;
const meta = {
data: group,
group:... | import { WebhookRequestData } from '../types'; | random_line_split |
test_upload_docs.py | """build_ext tests
"""
import sys, os, shutil, tempfile, unittest, site, zipfile
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
SETUP_PY = """\
from setuptools import setup
setup(name='foo')
"""
class TestUploadDocsTest(unittest.TestCase):
def | (self):
self.dir = tempfile.mkdtemp()
setup = os.path.join(self.dir, 'setup.py')
f = open(setup, 'w')
f.write(SETUP_PY)
f.close()
self.old_cwd = os.getcwd()
os.chdir(self.dir)
self.upload_dir = os.path.join(self.dir, 'build')
os.mkdir(se... | setUp | identifier_name |
test_upload_docs.py | """build_ext tests
"""
import sys, os, shutil, tempfile, unittest, site, zipfile
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
SETUP_PY = """\
from setuptools import setup
setup(name='foo')
"""
class TestUploadDocsTest(unittest.TestCase):
def setUp(s... | dist = Distribution()
cmd = upload_docs(dist)
cmd.upload_dir = self.upload_dir
zip_file = cmd.create_zipfile()
assert zipfile.is_zipfile(zip_file)
zip_f = zipfile.ZipFile(zip_file) # woh...
assert zip_f.namelist() == ['index.html'] | identifier_body | |
test_upload_docs.py | """build_ext tests
"""
import sys, os, shutil, tempfile, unittest, site, zipfile
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
SETUP_PY = """\
from setuptools import setup
setup(name='foo')
"""
class TestUploadDocsTest(unittest.TestCase):
def setUp(s... |
def test_create_zipfile(self):
# Test to make sure zipfile creation handles common cases.
# This explicitly includes a folder containing an empty folder.
dist = Distribution()
cmd = upload_docs(dist)
cmd.upload_dir = self.upload_dir
zip_file = cmd.create_z... | site.USER_BASE = self.old_base
site.USER_SITE = self.old_site
| random_line_split |
test_upload_docs.py | """build_ext tests
"""
import sys, os, shutil, tempfile, unittest, site, zipfile
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
SETUP_PY = """\
from setuptools import setup
setup(name='foo')
"""
class TestUploadDocsTest(unittest.TestCase):
def setUp(s... |
def test_create_zipfile(self):
# Test to make sure zipfile creation handles common cases.
# This explicitly includes a folder containing an empty folder.
dist = Distribution()
cmd = upload_docs(dist)
cmd.upload_dir = self.upload_dir
zip_file = cmd.create... | shutil.rmtree(site.USER_BASE)
shutil.rmtree(site.USER_SITE)
site.USER_BASE = self.old_base
site.USER_SITE = self.old_site | conditional_block |
dns.rs | use std::io;
use std::net::{SocketAddr, ToSocketAddrs};
use std::vec;
use ::futures::{Future, Poll};
use ::futures_cpupool::{CpuPool, CpuFuture};
#[derive(Clone)]
pub struct Dns {
pool: CpuPool,
}
impl Dns {
pub fn new(threads: usize) -> Dns {
Dns {
pool: CpuPool::new(threads)
}
... | (CpuFuture<IpAddrs, io::Error>);
impl Future for Query {
type Item = IpAddrs;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.0.poll()
}
}
pub struct IpAddrs {
iter: vec::IntoIter<SocketAddr>,
}
impl Iterator for IpAddrs {
type Item = SocketAddr;
... | Query | identifier_name |
dns.rs | use std::io;
use std::net::{SocketAddr, ToSocketAddrs};
use std::vec;
use ::futures::{Future, Poll};
use ::futures_cpupool::{CpuPool, CpuFuture};
#[derive(Clone)]
pub struct Dns {
pool: CpuPool,
}
impl Dns {
pub fn new(threads: usize) -> Dns {
Dns {
pool: CpuPool::new(threads)
}
... | type Item = SocketAddr;
#[inline]
fn next(&mut self) -> Option<SocketAddr> {
self.iter.next()
}
}
pub type Answer = io::Result<IpAddrs>;
fn work(hostname: String, port: u16) -> Answer {
debug!("resolve {:?}:{:?}", hostname, port);
(&*hostname, port).to_socket_addrs().map(|i| IpAddrs { ... |
impl Iterator for IpAddrs { | random_line_split |
services.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | (self, lookup=None):
if lookup is None:
lookup = {}
if lookup:
doc = self.find_one(req=None, **lookup)
self.on_delete(doc)
res = self.delete(lookup)
if lookup and doc:
self.on_deleted(doc)
return res
def is_authorized(self, *... | delete_action | identifier_name |
services.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... |
self.on_create(docs)
resolve_document_etag(docs, self.datasource)
ids = self.create(docs, **kwargs)
self.on_created(docs)
return ids
def patch(self, id, updates):
original = self.find_one(req=None, _id=id)
updated = original.copy()
self.on_update(upd... | resolve_default_values(doc, app.config['DOMAIN'][self.datasource]['defaults']) | conditional_block |
services.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... |
def delete_action(self, lookup=None):
if lookup is None:
lookup = {}
if lookup:
doc = self.find_one(req=None, **lookup)
self.on_delete(doc)
res = self.delete(lookup)
if lookup and doc:
self.on_deleted(doc)
return res
de... | resolve_default_values(document, app.config['DOMAIN'][self.datasource]['defaults'])
original = self.find_one(req=None, _id=id)
self.on_replace(document, original)
resolve_document_etag(document, self.datasource)
res = self.replace(id, document, original)
self.on_replaced(document... | identifier_body |
services.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | return res
def put(self, id, document):
resolve_default_values(document, app.config['DOMAIN'][self.datasource]['defaults'])
original = self.find_one(req=None, _id=id)
self.on_replace(document, original)
resolve_document_etag(document, self.datasource)
res = self.repl... | updates[config.ETAG] = updated[config.ETAG]
res = self.update(id, updates, original)
self.on_updated(updates, original) | random_line_split |
box_renderer.rs | use cgmath::{self, Vector2};
use gfx;
use gfx_device_gl;
use gfx_device_gl::{Resources};
use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt,
Surface, Swapchain, SwapchainExt, WindowExt};
use gfx::traits::DeviceExt;
use graphics::render_thread::{RenderPackage, RenderThread};
type ColorFormat = gfx::for... | {
pub pos: Vector2<f32>,
pub scale: Vector2<f32>,
pub z_rotation: f32,
pub color: [f32; 3],
}
pub struct BoxRenderer {
pso: gfx::PipelineState<Resources, BoxPipeLine::Meta>,
graphics_pool: gfx::GraphicsCommandPool<gfx_device_gl::Backend>,
}
impl BoxRenderer {
pub fn new(device: &mut ... | BoxRenderData | identifier_name |
box_renderer.rs | use cgmath::{self, Vector2};
use gfx;
use gfx_device_gl;
use gfx_device_gl::{Resources};
use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt,
Surface, Swapchain, SwapchainExt, WindowExt};
use gfx::traits::DeviceExt;
use graphics::render_thread::{RenderPackage, RenderThread};
type ColorFormat = gfx::for... |
pub fn render_boxes(&mut self, boxes_to_render: &Vec<BoxRenderData>, render_package: &mut RenderPackage, view: &gfx::handle::RenderTargetView<gfx_device_gl::Resources, (gfx::format::R8_G8_B8_A8, gfx::format::Unorm)>, rt : &mut RenderThread) {
let mut vertex_info = vec![];
let mut index_in... | {
let pso = device.create_pipeline_simple(
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/shaders/box_shader.vs"
)),
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/shaders/b... | identifier_body |
box_renderer.rs | use cgmath::{self, Vector2};
use gfx;
use gfx_device_gl;
use gfx_device_gl::{Resources};
use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt,
Surface, Swapchain, SwapchainExt, WindowExt};
use gfx::traits::DeviceExt;
use graphics::render_thread::{RenderPackage, RenderThread};
type ColorFormat = gfx::for... | out: view.clone(),
};
{
let mut box_encoder = self.graphics_pool.acquire_graphics_encoder();
let _ = box_encoder.update_buffer(&box_data.perp, &[t], 0);
box_encoder.clear(&box_data.out, BLACK);
box_encoder.draw(&index_buffer, &self.pso, &box_d... | vbuf: vertex_buffer.clone(),
perp: constant_buffer, | random_line_split |
test_cli.py | from pathlib import PosixPath
import pytest
from rpmlint.cli import process_lint_args
from rpmlint.config import Config
from rpmlint.lint import Lint
@pytest.mark.parametrize('test_arguments', [['-c', 'rpmlint/configs/thisdoesntexist.toml']])
def test_parsing_non_existing_config_file(test_arguments):
with pytest... | for score_key in score_keys:
if score_key.startswith('percent-in-'):
continue
assert score_key in checks | random_line_split | |
test_cli.py | from pathlib import PosixPath
import pytest
from rpmlint.cli import process_lint_args
from rpmlint.config import Config
from rpmlint.lint import Lint
@pytest.mark.parametrize('test_arguments', [['-c', 'rpmlint/configs/thisdoesntexist.toml']])
def test_parsing_non_existing_config_file(test_arguments):
with pytest... |
@pytest.mark.parametrize('test_arguments', [['-c', 'configs/openSUSE']])
def test_parsing_opensuse_conf(test_arguments):
parsed = process_lint_args(test_arguments)
assert len(parsed['config']) == 7
assert PosixPath('configs/openSUSE/opensuse.toml') in parsed['config']
assert PosixPath('configs/openS... | parsed = process_lint_args(test_arguments)
assert len(parsed['config']) == 1
assert parsed['config'][0] == PosixPath('rpmlint/configdefaults.toml') | identifier_body |
test_cli.py | from pathlib import PosixPath
import pytest
from rpmlint.cli import process_lint_args
from rpmlint.config import Config
from rpmlint.lint import Lint
@pytest.mark.parametrize('test_arguments', [['-c', 'rpmlint/configs/thisdoesntexist.toml']])
def test_parsing_non_existing_config_file(test_arguments):
with pytest... |
assert score_key in checks
| continue | conditional_block |
test_cli.py | from pathlib import PosixPath
import pytest
from rpmlint.cli import process_lint_args
from rpmlint.config import Config
from rpmlint.lint import Lint
@pytest.mark.parametrize('test_arguments', [['-c', 'rpmlint/configs/thisdoesntexist.toml']])
def test_parsing_non_existing_config_file(test_arguments):
with pytest... | (test_arguments):
parsed = process_lint_args(test_arguments)
assert len(parsed['config']) == 7
assert PosixPath('configs/openSUSE/opensuse.toml') in parsed['config']
assert PosixPath('configs/openSUSE/licenses.toml') in parsed['config']
assert PosixPath('configs/openSUSE/pie-executables.toml') in p... | test_parsing_opensuse_conf | identifier_name |
test_client.py | from buildpal_client import compile as buildpal_compile
import os
import subprocess
import asyncio
import sys
import struct
import threading
import pytest
from buildpal.common import MessageProtocol
class ProtocolTester(MessageProtocol):
@classmethod
def check_exit_code(cls, code):
if ... | loop = asyncio.ProactorEventLoop()
[server] = loop.run_until_complete(loop.start_serving_pipe(
lambda : protocol_tester(loop), "\\\\.\\pipe\\BuildPal_{}".format(buildpal_compile_args[-1])))
class ExitCode:
pass
def run_thread():
ExitCode.exit_code = buildpal_compile(*buildp... | identifier_body | |
test_client.py | from buildpal_client import compile as buildpal_compile
import os
import subprocess
import asyncio
import sys
import struct
import threading
import pytest
from buildpal.common import MessageProtocol
class ProtocolTester(MessageProtocol):
@classmethod
def check_exit_code(cls, code):
if ... | def process_response(self, msg):
retcode, stdout, stderr = msg
retcode = int(retcode.memory())
assert retcode != 0
assert not stdout.memory()
assert b'missing source filename' in stderr.tobytes()
self.send_msg([b'EXIT', struct.pack('!I', self.expected_exit_code ... | def send_request(self):
self.send_msg([b'EXECUTE_GET_OUTPUT', b'/nologo'])
| random_line_split |
test_client.py | from buildpal_client import compile as buildpal_compile
import os
import subprocess
import asyncio
import sys
import struct
import threading
import pytest
from buildpal.common import MessageProtocol
class ProtocolTester(MessageProtocol):
@classmethod
def check_exit_code(cls, code):
if ... |
def send_request(self):
raise NotImplementedError()
def process_response(self, msg):
raise NotImplementedError()
def connection_lost(self, exc):
self.loop.stop()
class RunLocallyTester(ProtocolTester):
expected_exit_code = 0
def send_request(self):
... | self.process_response(msg) | conditional_block |
test_client.py | from buildpal_client import compile as buildpal_compile
import os
import subprocess
import asyncio
import sys
import struct
import threading
import pytest
from buildpal.common import MessageProtocol
class ProtocolTester(MessageProtocol):
@classmethod
def check_exit_code(cls, code):
if ... | :
pass
def run_thread():
ExitCode.exit_code = buildpal_compile(*buildpal_compile_args)
thread = threading.Thread(target=run_thread)
thread.start()
loop.run_forever()
thread.join()
@asyncio.coroutine
def close_server():
server.close()
loop.run_until_... | ExitCode | identifier_name |
pr.js | /* global error:false */
/* global done:false */
/* global PaymentRequest:false */
/**
* Updates details based on shipping address.
* @param {object} details - The details to update.
* @param {ShippingAddress} addr - The shipping address.
* @return {object} The updated details.
*/
function | (details, addr) {
if (addr.regionCode === 'US') {
var shippingOption = {
id: '',
label: '',
amount: {
currency: 'USD',
value: '0.00'
}
};
if (addr.administrativeArea === 'CA') {
shippingOption.id = 'ca';
shippingOption.label = 'Free shipping in Californi... | updateDetails | identifier_name |
pr.js | /* global error:false */
/* global done:false */
/* global PaymentRequest:false */
/**
* Updates details based on shipping address.
* @param {object} details - The details to update.
* @param {ShippingAddress} addr - The shipping address.
* @return {object} The updated details.
*/
function updateDetails(details, ... |
details.shippingOptions = [shippingOption];
} else {
delete details.shippingOptions;
}
return details;
}
/**
* Starts PaymentRequest with shipping options that depend on the shipping
* address.
*/
function onBuyClicked() { // eslint-disable-line no-unused-vars
var supportedInstruments = [
'http... | {
details.items.splice(-2, 1, shippingOption);
} | conditional_block |
pr.js | /* global error:false */
/* global done:false */
/* global PaymentRequest:false */
/**
* Updates details based on shipping address.
* @param {object} details - The details to update.
* @param {ShippingAddress} addr - The shipping address.
* @return {object} The updated details.
*/
function updateDetails(details, ... | try {
var request =
new PaymentRequest(supportedInstruments, details, options, schemeData);
request.addEventListener('shippingaddresschange', e => {
e.updateWith(new Promise(resolve => {
resolve(updateDetails(details, request.shippingAddress));
}));
});
request.show()
... | return;
}
| random_line_split |
pr.js | /* global error:false */
/* global done:false */
/* global PaymentRequest:false */
/**
* Updates details based on shipping address.
* @param {object} details - The details to update.
* @param {ShippingAddress} addr - The shipping address.
* @return {object} The updated details.
*/
function updateDetails(details, ... | value: '-10.00'
}
},
{
id: 'total',
label: 'Donation',
amount: {
currency: 'USD',
value: '55.00'
}
}
]
};
var options = {
requestShipping: true
};
var schemeData = {
'https://android.com/pay': {
'gateway'... | { // eslint-disable-line no-unused-vars
var supportedInstruments = [
'https://android.com/pay', 'visa', 'mastercard', 'amex', 'discover',
'maestro', 'diners', 'jcb', 'unionpay'
];
var details = {
items: [{
id: 'original',
label: 'Original donation amount',
amount: {
... | identifier_body |
RelatedPhotos.tsx | import * as React from "react";
require("!style-loader!css-loader!sass-loader!./RelatedPhotos.scss");
import RelatedPhoto from "./RelatedPhoto";
import FlickrPhoto from "../../../vo/FlickrPhoto";
import LoadingIndicator from "../../common/LoadingIndicator";
export interface RelatedPhotosProps {
photos: Array<Flick... | (index: number) {
console.log("Click on photo at index ", index);
this.props.onPhotoClick(index);
}
render() {
return <section className="related-photos">
{this.getPhotos()}
{
(!this.props.photos.length) ?
<LoadingIndicator small/>
... | onPhotoClick | identifier_name |
RelatedPhotos.tsx | import * as React from "react"; | require("!style-loader!css-loader!sass-loader!./RelatedPhotos.scss");
import RelatedPhoto from "./RelatedPhoto";
import FlickrPhoto from "../../../vo/FlickrPhoto";
import LoadingIndicator from "../../common/LoadingIndicator";
export interface RelatedPhotosProps {
photos: Array<FlickrPhoto>;
current: number;
... | random_line_split | |
RelatedPhotos.tsx | import * as React from "react";
require("!style-loader!css-loader!sass-loader!./RelatedPhotos.scss");
import RelatedPhoto from "./RelatedPhoto";
import FlickrPhoto from "../../../vo/FlickrPhoto";
import LoadingIndicator from "../../common/LoadingIndicator";
export interface RelatedPhotosProps {
photos: Array<Flick... |
{
(!this.props.photos.length) ?
<LoadingIndicator small/>
:
null
}
</section>;
}
}
| {
return <section className="related-photos">
{this.getPhotos()} | identifier_body |
RelatedPhotos.tsx | import * as React from "react";
require("!style-loader!css-loader!sass-loader!./RelatedPhotos.scss");
import RelatedPhoto from "./RelatedPhoto";
import FlickrPhoto from "../../../vo/FlickrPhoto";
import LoadingIndicator from "../../common/LoadingIndicator";
export interface RelatedPhotosProps {
photos: Array<Flick... |
while (photoCount < RelatedPhotos.MAX_ITEMS);
const hasPrevious = (currentIndex > 0);
const previousIndex = hasPrevious ? (currentIndex - 1) : (allPhotos.length - 1);
const previousPhoto = allPhotos[previousIndex];
photos.push(<RelatedPhoto photo={previousP... | {
const nextIndex = (index < allPhotos.length - 1) ? index + 1 : 0;
const nexPhoto = allPhotos[nextIndex];
photos.push(<RelatedPhoto photo={nexPhoto} index={nextIndex} onClick={this.onPhotoClick.bind(this)}/>);
photoCount++;
index = nextInd... | conditional_block |
jquery.fatNav.js | (function($, window, document) {
var pluginName = 'fatNav',
defaults = {};
function Plugin(options) |
$.extend(Plugin.prototype, {
init: function() {
var self = this;
var $nav = this.$nav = $('.fat-nav');
var $hamburger = this.$hamburger = $('<a href="javascript:void(0)" class="hamburger"><div class="hamburger__icon"></div></a>');
... | {
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
} | identifier_body |
jquery.fatNav.js | (function($, window, document) {
var pluginName = 'fatNav',
defaults = {};
function Plugin(options) {
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
... | // $body.width($body.width());
$body.css('overflow', isNavOpen ? 'hidden' : self._bodyOverflow);
}
});
if (typeof $[pluginName] === 'undefined') {
$[pluginName] = function(options) {
return new Plugin(this, options);
};
}... |
var isNavOpen = $body.hasClass('no-scroll');
| random_line_split |
jquery.fatNav.js | (function($, window, document) {
var pluginName = 'fatNav',
defaults = {};
function Plugin(options) {
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
... |
}(jQuery, window, document)); | {
$[pluginName] = function(options) {
return new Plugin(this, options);
};
} | conditional_block |
jquery.fatNav.js | (function($, window, document) {
var pluginName = 'fatNav',
defaults = {};
function | (options) {
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
init: function() {
var self = this;
var $nav = this.$nav = $('.fat-nav');
... | Plugin | identifier_name |
ordereddict.py | See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ETE. If not, see <http://www.gnu.org/licenses/>.
#
#
# ABOUT THE ETE PACKAGE
# =====================
#
# ETE is distributed under the GPL c... | elif hasattr(other, 'keys'):
for key in list(other.keys()):
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in list(kwds.items()):
self[key] = value
__update = update # let subclasses... | if isinstance(other, dict):
for key in other:
self[key] = other[key] | random_line_split |
ordereddict.py | See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ETE. If not, see <http://www.gnu.org/licenses/>.
#
#
# ABOUT THE ETE PACKAGE
# =====================
#
# ETE is distributed under the GPL c... |
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link which goes at the end of the linked
# list, and the inherited dictionary is updated with the new key/value pair.
if key not in self:
... | '''Initialize an ordered dictionary. Signature is the same as for
regular dictionaries, but keyword arguments are not recommended
because their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
tr... | identifier_body |
ordereddict.py | _get_ident
try:
from _abcoll import KeysView, ValuesView, ItemsView
except ImportError:
pass
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remainin... | viewitems | identifier_name | |
ordereddict.py | TE: a python Environment for Tree Exploration. Jaime BMC
# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24
#
# Note that extra references to the specific methods implemented in
# the toolkit may be available in the documentation.
#
# More info at http://etetoolkit.org. Contact: huerta@embl.de
#
#
# #END_LICENSE#####... | d[key] = value | conditional_block | |
table-notifications.js | /** Namespace NotificationsTable */
var NotificationsTable = new function()
{
var ns = this; // reference to the namespace
ns.oTable = null;
var asInitVals = [];
/** Update the table to list the notifications. */
this.update = function() {
ns.oTable.fnClearTable( 0 );
ns.oTable.fnDraw();
};
... | NotificationsTable.reject(row_data[0]);
CATMAID.client.get_messages(); // Refresh the notifications icon badge
}
node.selectedIndex = 0;
}
};
this.init = function (pid)
{
ns.pid = pid;
ns.oTable = $('#notificationstable').dataTable({
// http://www.datatables.net/u... | CATMAID.client.get_messages(); // Refresh the notifications icon badge
}
else if (action == 'Reject') { | random_line_split |
table-notifications.js | /** Namespace NotificationsTable */
var NotificationsTable = new function()
{
var ns = this; // reference to the namespace
ns.oTable = null;
var asInitVals = [];
/** Update the table to list the notifications. */
this.update = function() {
ns.oTable.fnClearTable( 0 );
ns.oTable.fnDraw();
};
... |
});
$('select#search_type').change( function() {
ns.oTable.fnFilter( $(this).val(), 1 );
asInitVals[1] = $(this).val();
});
};
}();
| {
this.className = "search_init";
this.value = asInitVals[$("thead input").index(this)+2];
} | conditional_block |
regex.py | import re
from utilRegex import database
class regex:
def __init__(self, botCfg):
"""class initialization function
"""
#intitialize database variables
self.db = database()
#initialize regex variables
self.phrase = ''
self.url = ''
#initialize s... |
pattern = r'(^|\s|[a-z]-)(%s)+([a-z]{1,4})?(\'[a-z]{1,4})?(\s|\.|,|\?|\!|$)' % (pattern)
#compile the regex object
self.phrase = re.compile(pattern, re.IGNORECASE)
#exit the function
self.phraseReady = True
return True
| pattern = re.escape('a placeholder') | conditional_block |
regex.py | import re
from utilRegex import database
class | :
def __init__(self, botCfg):
"""class initialization function
"""
#intitialize database variables
self.db = database()
#initialize regex variables
self.phrase = ''
self.url = ''
#initialize status variables
self.phraseReady = False
... | regex | identifier_name |
regex.py | import re
from utilRegex import database
class regex:
def __init__(self, botCfg):
"""class initialization function
"""
#intitialize database variables
self.db = database()
#initialize regex variables
self.phrase = ''
self.url = ''
#initialize s... | return True | #compile the regex object
self.phrase = re.compile(pattern, re.IGNORECASE)
#exit the function
self.phraseReady = True | random_line_split |
regex.py | import re
from utilRegex import database
class regex:
def __init__(self, botCfg):
"""class initialization function
"""
#intitialize database variables
self.db = database()
#initialize regex variables
self.phrase = ''
self.url = ''
#initialize s... | #pull records from database
try:
self.db.cursor.execute('SELECT *' + \
' FROM phraseprint()' + \
' f(id bigint, phrase text, username text)')
records = self.db.cursor.fetchall()
except:
... | """compile phrase regex object
builds a regex object that includes
existing phrases from the phrase table
in the database.
returns:
success: True
failure: False
"""
#initialize function
self.phraseReady = False
... | identifier_body |
trie.rs | // [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/)
#[derive(Default, Debug)]
struct Trie {
is_ending: bool,
nodes: [Option<Box<Trie>>; 26],
}
impl Trie {
fn new() -> Self {
Default::default()
}
fn insert(&mut self, word: &str) |
fn find(&self, word: &str) -> bool {
let mut curr = self;
for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) {
match curr.nodes[i].as_ref() {
Some(node) => { curr = node; },
None => { return false; },
}
}
curr... | {
let mut curr = self;
for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) {
curr = curr.nodes[i].get_or_insert_with(|| Box::new(Trie::new()));
}
curr.is_ending = true;
} | identifier_body |
trie.rs | // [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/)
#[derive(Default, Debug)]
struct Trie {
is_ending: bool,
nodes: [Option<Box<Trie>>; 26],
}
impl Trie {
fn new() -> Self {
Default::default()
}
fn insert(&mut self, word: &str) {
let mut curr = self;
... | (&self, word: &str) -> bool {
let mut curr = self;
for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) {
match curr.nodes[i].as_ref() {
Some(node) => { curr = node; },
None => { return false; },
}
}
curr.is_ending
... | find | identifier_name |
trie.rs | // [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/)
#[derive(Default, Debug)]
struct Trie {
is_ending: bool,
nodes: [Option<Box<Trie>>; 26],
}
impl Trie {
fn new() -> Self {
Default::default()
}
fn insert(&mut self, word: &str) {
let mut curr = self;
... | ,
None => { return false; },
}
}
curr.is_ending
}
}
fn main() {
let mut m = Trie::new();
m.insert("hello");
m.insert("she");
println!("{:?}", m);
let r = m.search("hello");
println!("{}", r); // true
}
| { curr = node; } | conditional_block |
trie.rs | // [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/)
#[derive(Default, Debug)] | is_ending: bool,
nodes: [Option<Box<Trie>>; 26],
}
impl Trie {
fn new() -> Self {
Default::default()
}
fn insert(&mut self, word: &str) {
let mut curr = self;
for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) {
curr = curr.nodes[i].get_or_i... | struct Trie { | random_line_split |
dateparsetoarray.js | /*
* Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights
* Reserved.
*
* The contents of this file are subject to the Common Public
* Attribution License Version 1.0 (the “License”); you may not use
* this file except in compliance with the License. You may obtain a
* copy of the License at:
*
*... | * The Original Code is the citation formatting software known as
* "citeproc-js" (an implementation of the Citation Style Language
* [CSL]), including the original test fixtures and software located
* under the ./std subdirectory of the distribution archive.
*
* The Original Developer is not the Initial Developer... | * Software distributed under the License is distributed on an “AS IS”
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
* | random_line_split |
conf.py | python
# -*- coding: utf-8 -*-
#
# pywim documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | u'Ivan Ogasawara',
'pywim',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.... | ('index', 'pywim',
u'PyWIM Documentation', | random_line_split |
font.rs | (em: f64) -> f64 { em * 16. }
fn au_from_em(em: f64) -> Au { Au::from_f64_px(em_to_px(em)) }
fn au_from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) }
pub struct FontTable {
data: Vec<u8>,
}
impl FontTable {
pub fn wrap(data: &[u8]) -> FontTable {
FontTable { data: data.to_vec() }
}
}
impl F... | em_to_px | identifier_name | |
font.rs | match metrics {
WindowsMetrics::Version0(ref m) => {
(m.weight_class, m.width_class, m.selection_flags.0 & 1 == 1)
},
WindowsMetrics::Version1(ref m) => {
(m.weight_class, m.width_class, m.selection_flags.0 & 1 == 1)
},
Windows... | {
self.font_data.identifier.clone()
} | identifier_body | |
font.rs | au_from_pt(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) }
pub struct FontTable {
data: Vec<u8>,
}
impl FontTable {
pub fn wrap(data: &[u8]) -> FontTable {
FontTable { data: data.to_vec() }
}
}
impl FontTableMethods for FontTable {
fn buffer(&self) -> &[u8] {
&self.data
}
}
fn ... | family_name: font.family_name(),
face_name: font.face_name(),
style,
weight,
stretch,
})
}
}
#[derive(Debug)]
pub struct FontHandle {
font_data: Arc<FontTemplateData>,
face: FontFace,
info: FontInfo,
em_size: f32,
du_per_em: f3... | FontStretch::ExtraExpanded => FontStretchKeyword::ExtraExpanded,
FontStretch::UltraExpanded => FontStretchKeyword::UltraExpanded,
}.compute());
Ok(FontInfo { | random_line_split |
httpoutput.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Output classes for ETL.
#
# Author: Just van den Broecke
#
from stetl.output import Output
from stetl.util import Util
from stetl.packet import FORMAT
import httplib
import base64
log = Util.get_log('httpoutput')
class HttpOutput(Output):
"""
Output via HTTP p... | (self, configdict, section, consumes=FORMAT.any):
Output.__init__(self, configdict, section, consumes)
self.host = self.cfg.get('host')
self.port = self.cfg.get('port', '80')
self.path = self.cfg.get('path')
self.method = self.cfg.get('method', 'POST')
self.user = self.cf... | __init__ | identifier_name |
httpoutput.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Output classes for ETL.
#
# Author: Just van den Broecke
#
from stetl.output import Output
from stetl.util import Util
from stetl.packet import FORMAT
import httplib
import base64
log = Util.get_log('httpoutput')
class HttpOutput(Output):
"""
Output via HTTP p... |
# get the response
statuscode, statusmessage, header = webservice.getreply()
log.info("Req nr %d - response status: code=%d msg=%s" % (self.req_nr, statuscode, statusmessage))
if statuscode != 200:
log.error("Headers: %s" % str(header))
res = webservice.getfile()... | self.req_nr += 1
webservice = httplib.HTTP(self.host)
# write your headers
webservice.putrequest(self.method, self.path)
webservice.putheader("Host", self.host)
webservice.putheader("User-Agent", "Stetl Python http")
webservice.putheader("Content-Type", self.content_type... | identifier_body |
httpoutput.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Output classes for ETL.
#
# Author: Just van den Broecke
#
from stetl.output import Output | from stetl.util import Util
from stetl.packet import FORMAT
import httplib
import base64
log = Util.get_log('httpoutput')
class HttpOutput(Output):
"""
Output via HTTP protocol, usually via POST.
consumes=FORMAT.etree_doc
"""
def __init__(self, configdict, section, consumes=FORMAT.any):
O... | random_line_split | |
httpoutput.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Output classes for ETL.
#
# Author: Just van den Broecke
#
from stetl.output import Output
from stetl.util import Util
from stetl.packet import FORMAT
import httplib
import base64
log = Util.get_log('httpoutput')
class HttpOutput(Output):
"""
Output via HTTP p... |
else:
# Regular, single data element or list_fanout is False
self.post(packet, self.create_payload(packet))
return packet
| original_data = packet.data
for data_elm in original_data:
packet.data = data_elm
self.post(packet, self.create_payload(packet))
packet.data = original_data | conditional_block |
keys.py | from __future__ import unicode_literals
__all__ = (
'Key',
'Keys',
)
class Key(object):
def __init__(self, name):
#: Descriptive way of writing keys in configuration files. e.g. <C-A>
#: for ``Control-A``.
self.name = name
def __repr__(self):
return '%s(%r)' % (self.... | ControlN = Key('<C-N>')
ControlO = Key('<C-O>')
ControlP = Key('<C-P>')
ControlQ = Key('<C-Q>')
ControlR = Key('<C-R>')
ControlS = Key('<C-S>')
ControlT = Key('<C-T>')
ControlU = Key('<C-U>')
ControlV = Key('<C-V>')
ControlW = Key('<C-W>')
ControlX = Key('<C-X>')
ControlY... | ControlK = Key('<C-K>')
ControlL = Key('<C-L>')
ControlM = Key('<C-M>') # Enter | random_line_split |
keys.py | from __future__ import unicode_literals
__all__ = (
'Key',
'Keys',
)
class | (object):
def __init__(self, name):
#: Descriptive way of writing keys in configuration files. e.g. <C-A>
#: for ``Control-A``.
self.name = name
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.name)
class Keys(object):
Escape = Key('<Escape>')
Co... | Key | identifier_name |
keys.py | from __future__ import unicode_literals
__all__ = (
'Key',
'Keys',
)
class Key(object):
def __init__(self, name):
#: Descriptive way of writing keys in configuration files. e.g. <C-A>
#: for ``Control-A``.
self.name = name
def __repr__(self):
return '%s(%r)' % (self.... | ControlS = Key('<C-S>')
ControlT = Key('<C-T>')
ControlU = Key('<C-U>')
ControlV = Key('<C-V>')
ControlW = Key('<C-W>')
ControlX = Key('<C-X>')
ControlY = Key('<C-Y>')
ControlZ = Key('<C-Z>')
ControlSpace = Key('<C-Space>')
ControlBackslash = Key('<C-Backslash>')
Con... | Escape = Key('<Escape>')
ControlA = Key('<C-A>')
ControlB = Key('<C-B>')
ControlC = Key('<C-C>')
ControlD = Key('<C-D>')
ControlE = Key('<C-E>')
ControlF = Key('<C-F>')
ControlG = Key('<C-G>')
ControlH = Key('<C-H>')
ControlI = Key('<C-I>') # Tab
ControlJ = Key('<C-J>') # Ente... | identifier_body |
google.py | #!/usr/bin/env python
#coding:utf-8
# Author: Beining --<cnbeining#gmail.com>
# Purpose: A Chrome DCP handler.
# Created: 07/15/2015
#Original copyright info:
#Author: Xiaoxia
#Contact: xiaoxia@xiaoxia.org
#Website: xiaoxia.org
import sys
import argparse
from threading import Thread, Lock
from struct import unpac... | response_data = response.read(BufferSize)
if not response_data: break
self.wfile.write(response_data)
do_POST = do_GET = do_CONNECT = sogouProxy
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
address_family = socket.AF_INET6
if __name__=='__main__':
... |
if self.command == "CONNECT": # NO HTTPS, as Chrome DCP does not allow HTTPS traffic
return
else:
while True: | random_line_split |
google.py | #!/usr/bin/env python
#coding:utf-8
# Author: Beining --<cnbeining#gmail.com>
# Purpose: A Chrome DCP handler.
# Created: 07/15/2015
#Original copyright info:
#Author: Xiaoxia
#Contact: xiaoxia@xiaoxia.org
#Website: xiaoxia.org
import sys
import argparse
from threading import Thread, Lock
from struct import unpac... |
#----------------------------------------------------------------------
def get_google_header():
"""None->str
As in https://github.com/cnbeining/datacompressionproxy/blob/master/background.js#L10-L18 .
P.S: This repo is a fork of the original one on google code.
"""
authValue = 'ac4500dd3b7579186c... | """None->int
get a looooooong integer."""
return str(random.randint(100000000, 999999999)) | identifier_body |
google.py | #!/usr/bin/env python
#coding:utf-8
# Author: Beining --<cnbeining#gmail.com>
# Purpose: A Chrome DCP handler.
# Created: 07/15/2015
#Original copyright info:
#Author: Xiaoxia
#Contact: xiaoxia@xiaoxia.org
#Website: xiaoxia.org
import sys
import argparse
from threading import Thread, Lock
from struct import unpac... |
self.remote.sendall(self.requestline.encode('ascii') + b"\r\n")
# Add Verification Tags
self.headers["Chrome-Proxy"] = get_google_header()
headerstr = str(self.headers).replace("\r\n", "\n").replace("\n", "\r\n")
self.remote.sendall(headerstr.encode('ascii') + b"\r\n")
#... | self.remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.remote.settimeout(RemoteTimeout)
self.remote.connect(("compress.googlezip.net", 80)) | conditional_block |
google.py | #!/usr/bin/env python
#coding:utf-8
# Author: Beining --<cnbeining#gmail.com>
# Purpose: A Chrome DCP handler.
# Created: 07/15/2015
#Original copyright info:
#Author: Xiaoxia
#Contact: xiaoxia@xiaoxia.org
#Website: xiaoxia.org
import sys
import argparse
from threading import Thread, Lock
from struct import unpac... | (self):
try:
BaseHTTPRequestHandler.handle(self)
except socket.error: pass
def finish(self):
try:
BaseHTTPRequestHandler.finish(self)
except socket.error: pass
def sogouProxy(self):
if self.headers["Host"].startswith('chrome_dcp_proxy_pac.cnbeinin... | handle | identifier_name |
outwardslip-page.js | /**
* Created by praba on 2/13/2016.
*/
//JS page for outwardslip page
Polymer({
is: "outwardslip-page",
ready:function()
{
//Showing customerinfo page as the initial page in outwardslip page
localStorage.setItem("curr_sess_saveflag","false"); | {
localStorage.setItem("curr_sess_showpage","Out Vehicle Info");
//document.querySelector("webcomponent-service").callWebcomponentService();
this.page="Out Vehicle Info";
}
},
setPage:function(page)
{
//Setting current page in local storage to fetch the labels dynamically
localS... | if(sessionStorage.getItem("curr_sess_roleflag")=="0") | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.