file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
transaction.py | import threading
from collections import defaultdict
from funcy import once, decorator
from django.db import DEFAULT_DB_ALIAS, DatabaseError
from django.db.backends.utils import CursorWrapper
from django.db.transaction import Atomic, get_connection, on_commit
from .utils import monkey_mix
__all__ = ('queue_when_in... |
class TransactionStates(threading.local):
def __init__(self):
super(TransactionStates, self).__init__()
self._states = defaultdict(TransactionState)
def __getitem__(self, key):
return self._states[key or DEFAULT_DB_ALIAS]
def is_dirty(self, dbs):
return any(self[db].is_di... | def begin(self):
self.append({'cbs': [], 'dirty': False})
def commit(self):
context = self.pop()
if self:
# savepoint
self[-1]['cbs'].extend(context['cbs'])
self[-1]['dirty'] = self[-1]['dirty'] or context['dirty']
else:
# transaction
... | identifier_body |
transaction.py | import threading
from collections import defaultdict
from funcy import once, decorator
from django.db import DEFAULT_DB_ALIAS, DatabaseError
from django.db.backends.utils import CursorWrapper
from django.db.transaction import Atomic, get_connection, on_commit
from .utils import monkey_mix
__all__ = ('queue_when_in... | (object):
def callproc(self, procname, params=None):
result = self._no_monkey.callproc(self, procname, params)
if transaction_states[self.db.alias]:
transaction_states[self.db.alias].mark_dirty()
return result
def execute(self, sql, params=None):
result = self._no_mo... | CursorWrapperMixin | identifier_name |
transaction.py | import threading
from collections import defaultdict
from funcy import once, decorator
from django.db import DEFAULT_DB_ALIAS, DatabaseError
from django.db.backends.utils import CursorWrapper
from django.db.transaction import Atomic, get_connection, on_commit
from .utils import monkey_mix
__all__ = ('queue_when_in... |
class CursorWrapperMixin(object):
def callproc(self, procname, params=None):
result = self._no_monkey.callproc(self, procname, params)
if transaction_states[self.db.alias]:
transaction_states[self.db.alias].mark_dirty()
return result
def execute(self, sql, params=None):
... | if not connection.closed_in_transaction and exc_type is None and \
not connection.needs_rollback:
if transaction_states[self.using]:
transaction_states[self.using].commit()
else:
transaction_states[self.using].rollback() | conditional_block |
transaction.py | import threading
from collections import defaultdict
from funcy import once, decorator
from django.db import DEFAULT_DB_ALIAS, DatabaseError
from django.db.backends.utils import CursorWrapper
from django.db.transaction import Atomic, get_connection, on_commit
from .utils import monkey_mix
__all__ = ('queue_when_in... | monkey_mix(CursorWrapper, CursorWrapperMixin) | random_line_split | |
tweet.py | import cherrystrap
import orielpy
from cherrystrap import logger, formatter
from orielpy import common
# parse_qsl moved to urlparse module in v2.6
try:
from urllib.parse import parse_qsl #@UnusedImport
except:
from cgi import parse_qsl #@Reimport
import oauth2 as oauth
import twitter
class T... |
return self._send_tweet(prefix+": "+message)
notifier = TwitterNotifier
| return False | conditional_block |
tweet.py | import cherrystrap
import orielpy
from cherrystrap import logger, formatter
from orielpy import common
# parse_qsl moved to urlparse module in v2.6
try:
from urllib.parse import parse_qsl #@UnusedImport
except:
from cgi import parse_qsl #@Reimport
import oauth2 as oauth
import twitter
class T... |
notifier = TwitterNotifier
| consumer_key = "ZUJt6TLfdoDx5MBZLCOFKQ"
consumer_secret = "9gS5c4AAdhk6YSkL5F4E67Xclyao6GRDnXQKWCAw"
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
... | identifier_body |
tweet.py | import cherrystrap
import orielpy
from cherrystrap import logger, formatter
from orielpy import common
# parse_qsl moved to urlparse module in v2.6
try:
from urllib.parse import parse_qsl #@UnusedImport
except:
from cgi import parse_qsl #@Reimport
import oauth2 as oauth
import twitter
class T... |
def notify_health(self, output):
self._notifyTwitter('OrielPy: '+common.notifyStrings[common.NOTIFY_PREPEND]+output)
def test_notify(self):
return self._notifyTwitter("This is a test notification from OrielPy / " + formatter.now(), force=True)
def _get_authorization(self):
... | AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate'
| random_line_split |
tweet.py | import cherrystrap
import orielpy
from cherrystrap import logger, formatter
from orielpy import common
# parse_qsl moved to urlparse module in v2.6
try:
from urllib.parse import parse_qsl #@UnusedImport
except:
from cgi import parse_qsl #@Reimport
import oauth2 as oauth
import twitter
class T... | (self, message=None):
username=self.consumer_key
password=self.consumer_secret
access_token_key=orielpy.TWITTER_TOKEN
access_token_secret=orielpy.TWITTER_SECRET
logger.info(u"Sending tweet: "+message)
api = twitter.Api(username, password, access_token_key, acc... | _send_tweet | identifier_name |
clone.spec.js | describe("clone", function() {
"use strict";
var link;
beforeEach(function() {
jasmine.sandbox.set("<a id='link'><input id='input'></a>");
link = DOM.find("#link");
});
it("allows to clone all clildren", function() {
var clone = link.clone(true),
child = clone... |
expect(child).not.toBe(link.child(0));
expect(child).toHaveTag("input");
expect(child).toHaveId("input");
});
it("should allow to do a shallow copy", function() {
var clone = link.clone(false);
expect(clone).not.toBe(link);
expect(clone).toHaveTag("a");
... | jasmine.sandbox.set(clone);
expect(clone).not.toBe(link);
expect(clone).toHaveTag("a");
expect(clone).toHaveId("link"); | random_line_split |
parser.py | # Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and... | (file):
receiver_attributes = None
destination = None
messages = []
conditions = []
master_condition = None
superclass = []
for line in file:
match = re.search(r'messages -> (?P<destination>[A-Za-z_0-9]+) \s*(?::\s*(?P<superclass>.*?) \s*)?(?:(?P<attributes>.*?)\s+)?{', line)
... | parse | identifier_name |
parser.py | # Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and... |
elif line.startswith('#endif') and conditions:
conditions.pop()
elif line.startswith('#else') or line.startswith('#elif'):
raise Exception("ERROR: '%s' is not supported in the *.in files" % trimmed)
continue
match = re.search(r'([A-Za-z_0-9]+)... | conditions.append(trimmed[4:]) | conditional_block |
parser.py | # Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and... |
def parse_attributes_string(attributes_string):
if not attributes_string:
return None
return attributes_string.split()
def split_parameters_string(parameters_string):
parameters = []
current_parameter_string = ''
nest_level = 0
for character in parameters_string:
if charact... | receiver_attributes = None
destination = None
messages = []
conditions = []
master_condition = None
superclass = []
for line in file:
match = re.search(r'messages -> (?P<destination>[A-Za-z_0-9]+) \s*(?::\s*(?P<superclass>.*?) \s*)?(?:(?P<attributes>.*?)\s+)?{', line)
if match:
... | identifier_body |
parser.py | # Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and... | else:
return condition
def parse(file):
receiver_attributes = None
destination = None
messages = []
conditions = []
master_condition = None
superclass = []
for line in file:
match = re.search(r'messages -> (?P<destination>[A-Za-z_0-9]+) \s*(?::\s*(?P<superclass>.*?) \s*... | def bracket_if_needed(condition):
if re.match(r'.*(&&|\|\|).*', condition):
return '(%s)' % condition | random_line_split |
borrowck-lend-flow-match.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {}
| {
// Here the guard performs a borrow. This borrow "infects" all
// subsequent arms (but not the prior ones).
let mut a = ~3;
let mut b = ~4;
let mut w = &*a;
match 22 {
_ if cond() => {
b = ~5;
}
_ if link(&*b, &mut w) => {
b = ~6; //~ ERROR can... | identifier_body |
borrowck-lend-flow-match.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
// Here the guard performs a borrow. This borrow "infects" all
// subsequent arms (but not the prior ones).
let mut a = ~3;
let mut b = ~4;
let mut w = &*a;
match 22 {
_ if cond() => {
b = ~5;
}
_ if link(&*b, &mut w) => {
b = ~6; //~ ERROR ... | guard | identifier_name |
borrowck-lend-flow-match.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
_ => {
b = ~7; //~ ERROR cannot assign
}
}
b = ~8; //~ ERROR cannot assign
}
fn main() {} | b = ~6; //~ ERROR cannot assign
} | random_line_split |
mod.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/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bind... | impl Atom {
/// Execute a callback with the atom represented by `ptr`.
pub unsafe fn with<F, R>(ptr: *mut nsAtom, callback: F) -> R
where
F: FnOnce(&Atom) -> R,
{
let atom = Atom(WeakAtom::new(ptr));
let ret = callback(&atom);
mem::forget(atom);
ret
}
///... | random_line_split | |
mod.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/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bind... | <'a>(atom: *const nsAtom) -> &'a mut Self {
&mut *(atom as *mut WeakAtom)
}
/// Clone this atom, bumping the refcount if the atom is not static.
#[inline]
pub fn clone(&self) -> Atom {
unsafe { Atom::from_raw(self.as_ptr()) }
}
/// Get the atom hash.
#[inline]
pub fn ge... | new | identifier_name |
mod.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/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bind... | ,
}
}
/// Return whether two atoms are ASCII-case-insensitive matches
pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
if self == other {
return true;
}
let a = self.as_slice();
let b = other.as_slice();
a.len() == b.len() && a.iter().z... | {
let mut buffer: [u16; 64] = unsafe { mem::uninitialized() };
let mut vec;
let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) {
buffer_prefix.copy_from_slice(slice);
buffer_prefix
} else ... | conditional_block |
mod.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/. */
#![allow(unsafe_code)]
//! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s.
use gecko_bind... |
}
impl fmt::Display for Atom {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
unsafe { (&*self.0).fmt(w) }
}
}
impl<'a> From<&'a str> for Atom {
#[inline]
fn from(string: &str) -> Atom {
debug_assert!(string.len() <= u32::max_value() as usize);
unsafe {
Ato... | {
write!(w, "Gecko Atom({:p}, {})", self.0, self)
} | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
#
## This file is part of Invenio.
## Copyright (C) 2011, 2012, 2013, 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (... | (self, password):
if db.engine.name != 'mysql':
return md5(password).digest()
email = self.__clause_element__().table.columns.email
return db.func.aes_encrypt(email, password)
def autocommit_on_checkin(dbapi_con, con_record):
"""Calls autocommit on raw mysql connection for fixi... | hash | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
#
## This file is part of Invenio.
## Copyright (C) 2011, 2012, 2013, 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (... | models = RegistryProxy('models', ModuleAutoDiscoveryRegistry, 'models')
def setup_app(app):
"""Setup SQLAlchemy extension."""
if 'SQLALCHEMY_DATABASE_URI' not in app.config:
from sqlalchemy.engine.url import URL
cfg = app.config
app.config['SQLALCHEMY_DATABASE_URI'] = URL(
... | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
#
## This file is part of Invenio.
## Copyright (C) 2011, 2012, 2013, 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (... |
db = SQLAlchemy()
"""
Provides access to :class:`~.SQLAlchemy` instance.
"""
models = RegistryProxy('models', ModuleAutoDiscoveryRegistry, 'models')
def setup_app(app):
"""Setup SQLAlchemy extension."""
if 'SQLALCHEMY_DATABASE_URI' not in app.config:
from sqlalchemy.engine.url import URL
... | options.setdefault('execution_options', {'autocommit': True,
'use_unicode': False,
'charset': 'utf8mb4',
})
event.listen(Pool, 'checkin', autocommit_... | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
#
## This file is part of Invenio.
## Copyright (C) 2011, 2012, 2013, 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (... |
db = SQLAlchemy()
"""
Provides access to :class:`~.SQLAlchemy` instance.
"""
models = RegistryProxy('models', ModuleAutoDiscoveryRegistry, 'models')
def setup_app(app):
"""Setup SQLAlchemy extension."""
if 'SQLALCHEMY_DATABASE_URI' not in app.config:
from sqlalchemy.engine.url import URL
... | """
This method is called before engine creation.
"""
# Don't forget to apply hacks defined on parent object.
super(self.__class__, self).apply_driver_hacks(app, info, options)
if info.drivername == 'mysql':
options.setdefault('execution_options', {'autocommit': True,... | identifier_body |
main.rs | use std::collections::HashMap;
use std::io::{self, BufRead};
use lazy_regex::regex;
use regex::Regex;
use structopt::StructOpt;
type H = HashMap<Header, Vec<(String, String, String)>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Header {
Versioned { package: String, version: String },
Missing { package... | println!("\nTESTS\n");
}
for (header, packages) in tests {
for (package, version, component) in packages {
let s = printer(" ", &package, false, &version, &component, &header);
println!("{}", s);
auto_tests.push(s);
}
}
if !benches.is_empty... | }
if !tests.is_empty() { | random_line_split |
main.rs | use std::collections::HashMap;
use std::io::{self, BufRead};
use lazy_regex::regex;
use regex::Regex;
use structopt::StructOpt;
type H = HashMap<Header, Vec<(String, String, String)>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Header {
Versioned { package: String, version: String },
Missing { package... |
fn add() {
let mut lib_exes: H = Default::default();
let mut tests: H = Default::default();
let mut benches: H = Default::default();
let mut last_header: Option<Header> = None;
let header_versioned = regex!(
r#"^(?P<package>[a-zA-z]([a-zA-z0-9.-]*?))-(?P<version>(\d+(\.\d+)*)).+?is out of... | {
commenter::outdated();
} | identifier_body |
main.rs | use std::collections::HashMap;
use std::io::{self, BufRead};
use lazy_regex::regex;
use regex::Regex;
use structopt::StructOpt;
type H = HashMap<Header, Vec<(String, String, String)>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Header {
Versioned { package: String, version: String },
Missing { package... | (s: &str, r: &Regex) -> bool {
r.captures(s).is_some()
}
| is_reg_match | identifier_name |
main.rs | use std::collections::HashMap;
use std::io::{self, BufRead};
use lazy_regex::regex;
use regex::Regex;
use structopt::StructOpt;
type H = HashMap<Header, Vec<(String, String, String)>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Header {
Versioned { package: String, version: String },
Missing { package... | ;
format!(
"{indent}- {package}{lt0} # tried {package}-{version}, but its *{component}* {cause}",
indent = indent,
package = package,
lt0 = lt0,
version = version,
component = component,
cause = match header {
Header::Versioned { package, version }... | { "" } | conditional_block |
devtools.ts | import { expectType } from 'tsd'
browser.enablePerformanceAudits()
browser.enablePerformanceAudits({
networkThrottling: 'online',
cpuThrottling: 0,
cacheEnabled: false,
formFactor: 'desktop'
})
browser.disablePerformanceAudits()
const metrics = browser.getMetrics()
expectType<number>(metrics.totalBloc... |
const cdpResponse = browser.cdp('test', 'test')
expectType<number>(browser.getNodeId('selector'))
expectType<number[]>(browser.getNodeIds('selector'))
browser.startTracing()
browser.startTracing({ path: '/foo' })
browser.endTracing()
const traceLogs = browser.getTraceLogs()
expectType<string>(traceLogs[0].cat)
cons... | random_line_split | |
contentscript.js | (function() {
/* globals chrome */
'use strict';
| var itpubDownloader = {
//http://www.itpub.net/attachment.php?aid=OTIzNzAxfDQyYzhjNDRkfDE0MDQ0NjYwMjB8MzUwMTczfDE4NzU4NDA%3D&fid=61
//href = href.replace("attachment.php?", "forum.php?mod=attachment&");
attachmentRegexp: /attachment.php\?aid=[a-zA-Z0-9]+%3D&fid/,
mapElement: function(element) {
... | random_line_split | |
contentscript.js | (function() {
/* globals chrome */
'use strict';
var itpubDownloader = {
//http://www.itpub.net/attachment.php?aid=OTIzNzAxfDQyYzhjNDRkfDE0MDQ0NjYwMjB8MzUwMTczfDE4NzU4NDA%3D&fid=61
//href = href.replace("attachment.php?", "forum.php?mod=attachment&");
attachmentRegexp: /attachment.php\?aid=[a-zA-Z0-... |
return '';
},
isAttachmentURL: function(url) {
return itpubDownloader.attachmentRegexp.test(url);
},
removeDuplicateOrEmpty: function(images) {
var result = [],
hash = {};
for (var i = 0; i < images.length; i++) {
hash[images[i]] = 0;
}
for (var k... | {
var href = element.href;
if (itpubDownloader.isAttachmentURL(href)) {
href = href.replace(/attachment.php\?/, "forum.php?mod=attachment&");
var text = element.text;
itpubDownloader.attachmentTexts[href] = text;
console.log(text + " | " + href);
itpubDo... | conditional_block |
ozone.py | # -*- coding: utf-8 -*-
"""
Ozone Bricklet Plugin
Copyright (C) 2015 Olaf Lüke <olaf@tinkerforge.com>
ozone.py: Ozone Bricklet Plugin Implementation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; e... | self):
pass
def get_url_part(self):
return 'ozone'
@staticmethod
def has_device_identifier(device_identifier):
return device_identifier == BrickletOzone.DEVICE_IDENTIFIER
def get_current_value(self):
return self.current_value
def cb_ozone_concentration(self, ozone... | estroy( | identifier_name |
ozone.py | # -*- coding: utf-8 -*-
"""
Ozone Bricklet Plugin
Copyright (C) 2015 Olaf Lüke <olaf@tinkerforge.com>
ozone.py: Ozone Bricklet Plugin Implementation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; e... |
def destroy(self):
pass
def get_url_part(self):
return 'ozone'
@staticmethod
def has_device_identifier(device_identifier):
return device_identifier == BrickletOzone.DEVICE_IDENTIFIER
def get_current_value(self):
return self.current_value
def cb_ozone_concentr... | elf.cbe_ozone_concentration.set_period(0)
self.plot_widget.stop = True
| identifier_body |
ozone.py | # -*- coding: utf-8 -*-
"""
Ozone Bricklet Plugin
Copyright (C) 2015 Olaf Lüke <olaf@tinkerforge.com>
ozone.py: Ozone Bricklet Plugin Implementation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; e... |
layout = QVBoxLayout(self)
layout.addLayout(layout_h2)
layout.addWidget(self.plot_widget)
self.spin_average = QSpinBox()
self.spin_average.setMinimum(1)
self.spin_average.setMaximum(50)
self.spin_average.setSingleStep(1)
self.spin_average.setValue(50)
... | layout_h2 = QHBoxLayout()
layout_h2.addStretch()
layout_h2.addWidget(self.ozone_concentration_label)
layout_h2.addStretch() | random_line_split |
mcapi.py | print('Importing command definitions...')
from jycraft.plugin.interpreter import PyContext
from org.bukkit import Bukkit
from org.bukkit import Location
from org.bukkit import Material
from org.bukkit import Effect
from org.bukkit.command import Command
from org.bukkit.event import Listener, EventPriority
from rando... |
def explosion(*args, **kwargs):
r = parseargswithpos(args, kwargs, ledger={'power':['power', 0, 8]})
WORLD.createExplosion(r['x'], r['y'], r['z'], r['power'], True)
def teleport(*args, **kwargs):
r = parseargswithpos(args, kwargs, ledger={'whom':['whom', 0, 'GameStartSchool']})
someone = getplayer(... | WORLD.setStorm(rainsnow)
WORLD.setThundering(thunder) | identifier_body |
mcapi.py | print('Importing command definitions...')
from jycraft.plugin.interpreter import PyContext
from org.bukkit import Bukkit
from org.bukkit import Location
from org.bukkit import Material
from org.bukkit import Effect
from org.bukkit.command import Command
from org.bukkit.event import Listener, EventPriority
from rando... | (rainsnow, thunder):
WORLD.setStorm(rainsnow)
WORLD.setThundering(thunder)
def explosion(*args, **kwargs):
r = parseargswithpos(args, kwargs, ledger={'power':['power', 0, 8]})
WORLD.createExplosion(r['x'], r['y'], r['z'], r['power'], True)
def teleport(*args, **kwargs):
r = parseargswithpos(args... | weather | identifier_name |
mcapi.py | print('Importing command definitions...')
from jycraft.plugin.interpreter import PyContext
from org.bukkit import Bukkit
from org.bukkit import Location
from org.bukkit import Material
from org.bukkit import Effect
from org.bukkit.command import Command
from org.bukkit.event import Listener, EventPriority
from rando... |
results['x'] = pos[0]
results['y'] = pos[1]
results['z'] = pos[2]
for k,v in ledger.iteritems():
results[k] = kwargs.get(v[0], None)
if results[k] is None:
if len(args) > base+v[1]:
results[k] = args[base+v[1]]
else:
results[k] = v... | pos = (int(tr[0]), int(tr[1]), int(tr[2])) | conditional_block |
mcapi.py | print('Importing command definitions...')
from jycraft.plugin.interpreter import PyContext
from org.bukkit import Bukkit
from org.bukkit import Location
from org.bukkit import Material
from org.bukkit import Effect
from org.bukkit.command import Command
from org.bukkit.event import Listener, EventPriority
from rando... | WORLD.setTime(time)
def weather(rainsnow, thunder):
WORLD.setStorm(rainsnow)
WORLD.setThundering(thunder)
def explosion(*args, **kwargs):
r = parseargswithpos(args, kwargs, ledger={'power':['power', 0, 8]})
WORLD.createExplosion(r['x'], r['y'], r['z'], r['power'], True)
def teleport(*args, **k... |
def time(time): | random_line_split |
id.test.ts | import validNodeId from '../../../src/validations/node/id'
describe('Node Id Validations', () => {
describe('When node does not have "id"', () => {
const node = { states: ['T', 'F'] }
it('throws an error that node id is required', () => {
expect(() => {
// @ts-ignore
validNodeId(node)
... | Node id: 123
Node: {"id": 123}`)
})
})
describe('When node has "id" and is a string', () => {
const node = { id: 'node-id' }
it('does not throws an error', () => {
expect(() => {
// @ts-ignore
validNodeId(node)
}).not.toThrow()
})
})
}) | random_line_split | |
libraryExtractor.ts | ///<reference path='refs.ts'/>
module TDev
{
// BUGS:
// - Refs not handled correctly (see TD Junior)
// - we are not generating extension methods whenever possible (see from_string in TD Junior)
// - not show LibraryAbstractKind in dependences
// TODOs:
// - automated testing
// - move rew... |
m.setScroll();
m.fullWhite();
m.show();
}
// if the declaration has not been added to the "pending" set
// then prompt the user if it's OK to move the declaration and all
// declarations in its downward closure
private processDecl(d: AST.Decl... | m.onDismiss = () => {
next();
}; | random_line_split |
libraryExtractor.ts | ///<reference path='refs.ts'/>
module TDev
{
// BUGS:
// - Refs not handled correctly (see TD Junior)
// - we are not generating extension methods whenever possible (see from_string in TD Junior)
// - not show LibraryAbstractKind in dependences
// TODOs:
// - automated testing
// - move rew... | (): AST.DeclAndDeps[] {
return this.split.getRemainingDecls();
}
// everything starts off with the user requesting to move a declaration D
// from a script/app into a library. The identification of a pair
// of app A and library L is needed before we can start the process. C... | getRemainingDecls | identifier_name |
libraryExtractor.ts | ///<reference path='refs.ts'/>
module TDev
{
// BUGS:
// - Refs not handled correctly (see TD Junior)
// - we are not generating extension methods whenever possible (see from_string in TD Junior)
// - not show LibraryAbstractKind in dependences
// TODOs:
// - automated testing
// - move rew... |
});
} else
this.selectFromRemaining();
}
private filterUnwanted(dl: AST.DeclAndDeps[]) {
return dl.filter(dd => !(dd.decl instanceof AST.LibraryRef));
}
private askOKtoMove(toMove: AST.DeclAndDeps, next:(ok:boolean) => void) {
... | {
this.split.addToDeclsToMove([newOne]);
this.selectFromRemaining();
} | conditional_block |
libraryExtractor.ts | ///<reference path='refs.ts'/>
module TDev
{
// BUGS:
// - Refs not handled correctly (see TD Junior)
// - we are not generating extension methods whenever possible (see from_string in TD Junior)
// - not show LibraryAbstractKind in dependences
// TODOs:
// - automated testing
// - move rew... |
private getRemainingDecls(): AST.DeclAndDeps[] {
return this.split.getRemainingDecls();
}
// everything starts off with the user requesting to move a declaration D
// from a script/app into a library. The identification of a pair
// of app A and library L is needed... | {
return this.split.getAllDeclsToMove();
} | identifier_body |
backups.py | # encoding: utf-8
import datetime
import os
from pysteam import shortcuts
import paths
from logs import logger
def | ():
return os.path.join(paths.application_data_directory(), 'Backups')
def backup_filename(user, timestamp_format):
timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
return "shortcuts." + timestamp + ".vdf"
def shortcuts_backup_path(directory, user, timestamp_format="%Y%m%d%H%M%S"):
"""
Returns t... | default_backups_directory | identifier_name |
backups.py | # encoding: utf-8
import datetime
import os
from pysteam import shortcuts
import paths
from logs import logger
def default_backups_directory():
return os.path.join(paths.application_data_directory(), 'Backups')
def backup_filename(user, timestamp_format):
timestamp = datetime.datetime.now().strftime('%Y%m%d%H... |
logger.debug("Creating directory: %s" % directory)
os.makedirs(directory)
backup_dir = backup_directory(config)
if backup_dir is None:
logger.info("No backups directory specified, so not backing up shortcuts.vdf before overwriting. See config.txt for more info")
return
_create_directory_if_need... |
def create_backup_of_shortcuts(config, user, dry_run=False):
def _create_directory_if_needed(directory):
if os.path.exists(directory):
return | random_line_split |
backups.py | # encoding: utf-8
import datetime
import os
from pysteam import shortcuts
import paths
from logs import logger
def default_backups_directory():
return os.path.join(paths.application_data_directory(), 'Backups')
def backup_filename(user, timestamp_format):
timestamp = datetime.datetime.now().strftime('%Y%m%d%H... |
return backup_dir
def create_backup_of_shortcuts(config, user, dry_run=False):
def _create_directory_if_needed(directory):
if os.path.exists(directory):
return
logger.debug("Creating directory: %s" % directory)
os.makedirs(directory)
backup_dir = backup_directory(config)
if backup_dir is N... | backup_dir = default_backups_directory()
logger.debug("Specified empty string as backup directory. Defaulting to %s" % backup_dir) | conditional_block |
backups.py | # encoding: utf-8
import datetime
import os
from pysteam import shortcuts
import paths
from logs import logger
def default_backups_directory():
return os.path.join(paths.application_data_directory(), 'Backups')
def backup_filename(user, timestamp_format):
timestamp = datetime.datetime.now().strftime('%Y%m%d%H... |
def create_backup_of_shortcuts(config, user, dry_run=False):
def _create_directory_if_needed(directory):
if os.path.exists(directory):
return
logger.debug("Creating directory: %s" % directory)
os.makedirs(directory)
backup_dir = backup_directory(config)
if backup_dir is None:
logger.info... | backup_dir = config.backup_directory
if backup_dir is None:
return None
if backup_dir == "":
backup_dir = default_backups_directory()
logger.debug("Specified empty string as backup directory. Defaulting to %s" % backup_dir)
return backup_dir | identifier_body |
trait-cast-generic.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let a = Bar { x: 1 };
let b = &a as &Foo;
} | identifier_body | |
trait-cast-generic.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T> {
x: T,
}
impl<T> Foo for Bar<T> { }
pub fn main() {
let a = Bar { x: 1 };
let b = &a as &Foo;
}
| Bar | identifier_name |
trait-cast-generic.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let b = &a as &Foo;
} | let a = Bar { x: 1 }; | random_line_split |
takeWhile.ts | /*!
Copyright 2018 Ron Buckton (rbuckton@chronicles.org)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... | (): Iterator<T> {
const predicate = this._predicate;
for (const element of this._source) {
if (!predicate(element)) {
break;
}
yield element;
}
}
}
| [Symbol.iterator] | identifier_name |
takeWhile.ts | /*!
Copyright 2018 Ron Buckton (rbuckton@chronicles.org)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... |
}
| {
const predicate = this._predicate;
for (const element of this._source) {
if (!predicate(element)) {
break;
}
yield element;
}
} | identifier_body |
takeWhile.ts | /*!
Copyright 2018 Ron Buckton (rbuckton@chronicles.org)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... | for (const element of this._source) {
if (!predicate(element)) {
break;
}
yield element;
}
}
} |
*[Symbol.iterator](): Iterator<T> {
const predicate = this._predicate;
| random_line_split |
takeWhile.ts | /*!
Copyright 2018 Ron Buckton (rbuckton@chronicles.org)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... |
yield element;
}
}
}
| {
break;
} | conditional_block |
S3_to_FS.py | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | # insert in respective SQS operators | file_paths.append(kpath)
context['ti'].xcom_push(key=kpath, value="")
context['ti'].xcom_push(key="files_added", value=file_paths)
# read in chunks
# start reading from the file. | random_line_split |
S3_to_FS.py | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... |
context['ti'].xcom_push(key="files_added", value=file_paths)
# read in chunks
# start reading from the file.
# insert in respective SQS operators
| kpath = os.path.join(self.local_location, os.path.basename(k))
# Download the file
self.s3.download_file(self.s3_bucket, k, kpath)
file_paths.append(kpath)
context['ti'].xcom_push(key=kpath, value="") | conditional_block |
S3_to_FS.py | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | (BaseOperator):
@apply_defaults
def __init__(
self,
s3_bucket,
s3_key,
download_file_location,
s3_conn_id='s3_default',
* args, **kwargs):
super(S3ToFileSystem, self).__init__(*args, **kwargs)
self.local_location = downlo... | S3ToFileSystem | identifier_name |
S3_to_FS.py | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | @apply_defaults
def __init__(
self,
s3_bucket,
s3_key,
download_file_location,
s3_conn_id='s3_default',
* args, **kwargs):
super(S3ToFileSystem, self).__init__(*args, **kwargs)
self.local_location = download_file_location
... | identifier_body | |
code_section.py | # coding=utf-8
"""This module, code_section.py, is an abstraction for code sections. Needed for ordering code chunks."""
class CodeSection(object):
"""Represents a single code section of a source code file."""
def __init__(self, section_name):
self._section_name = section_name
self._code_chunks = []
def | (self, code_chunk):
"""Adds a code chunk to the start of this code section."""
self._code_chunks.insert(0, code_chunk)
def add_code_chunk(self, code_chunk):
"""Adds a code chunk to this code section."""
self._code_chunks.append(code_chunk)
def get_all_code_chunks(self):
"""Returns a list of all the code c... | add_code_chunk_at_start | identifier_name |
code_section.py | # coding=utf-8
"""This module, code_section.py, is an abstraction for code sections. Needed for ordering code chunks."""
class CodeSection(object):
"""Represents a single code section of a source code file."""
| def add_code_chunk_at_start(self, code_chunk):
"""Adds a code chunk to the start of this code section."""
self._code_chunks.insert(0, code_chunk)
def add_code_chunk(self, code_chunk):
"""Adds a code chunk to this code section."""
self._code_chunks.append(code_chunk)
def get_all_code_chunks(self):
"""Retu... | def __init__(self, section_name):
self._section_name = section_name
self._code_chunks = []
| random_line_split |
code_section.py | # coding=utf-8
"""This module, code_section.py, is an abstraction for code sections. Needed for ordering code chunks."""
class CodeSection(object):
"""Represents a single code section of a source code file."""
def __init__(self, section_name):
self._section_name = section_name
self._code_chunks = []
def add... |
def get_all_code_chunks(self):
"""Returns a list of all the code chunks in this code section."""
return self._code_chunks
@property
def empty(self) -> bool:
"""Returns a boolean indicating if this code section is empty or not."""
return len(self._code_chunks) == 0
@property
def name(self) -> str:
"""... | """Adds a code chunk to this code section."""
self._code_chunks.append(code_chunk) | identifier_body |
autosaveAction.service.ts | import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { services } from 'typescript-angular-utilities';
import TimeoutService = services.timeout.TimeoutService;
import { AsyncHelper, IWaitValue } from '../async/async.service';
export const COMPLETE_MESSAGE_DURATION: n... | (timeoutService: TimeoutService
, asyncService: AsyncHelper) {
this.timeoutService = timeoutService;
this.asyncService = asyncService;
this._saving$ = new BehaviorSubject(false);
this._complete$ = new BehaviorSubject(false);
this._successful$ = new BehaviorSubject(false);
}
private _saving$: BehaviorSub... | constructor | identifier_name |
autosaveAction.service.ts | import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { services } from 'typescript-angular-utilities';
import TimeoutService = services.timeout.TimeoutService;
import { AsyncHelper, IWaitValue } from '../async/async.service';
export const COMPLETE_MESSAGE_DURATION: n... | constructor(timeoutService: TimeoutService
, asyncService: AsyncHelper) {
this.timeoutService = timeoutService;
this.asyncService = asyncService;
this._saving$ = new BehaviorSubject(false);
this._complete$ = new BehaviorSubject(false);
this._successful$ = new BehaviorSubject(false);
}
private _saving$:... | random_line_split | |
pants_run_integration_test.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)
import os
import sub... | (self, target, bundle_name, args=None):
"""Creates the bundle with pants, then does java -jar {bundle_name}.jar to execute the bundle.
:param target: target name to compile
:param bundle_name: resulting bundle filename (minus .jar extension)
:param args: optional arguments to pass to executable
:re... | bundle_and_run | identifier_name |
pants_run_integration_test.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)
import os
import sub... | assertion(value, pants_run.returncode, error_msg) | random_line_split | |
pants_run_integration_test.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)
import os
import sub... |
def run_pants(self, command, config=None, stdin_data=None, extra_env=None, **kwargs):
"""Runs pants in a subprocess.
:param list command: A list of command line arguments coming after `./pants`.
:param config: Optional data for a generated ini file. A map of <section-name> ->
map of key -> value. I... | config = config.copy() if config else {}
# We add workdir to the DEFAULT section, and also ensure that it's emitted first.
default_section = config.pop('DEFAULT', {})
default_section['pants_workdir'] = '%s' % workdir
ini = ''
for section, section_config in [('DEFAULT', default_section)] + config.i... | identifier_body |
pants_run_integration_test.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)
import os
import sub... |
java_run = subprocess.Popen(['java',
'-jar',
'{bundle_name}.jar'.format(bundle_name=bundle_name)]
+ optional_args,
stdout=subprocess.PIPE,
cw... | optional_args = args | conditional_block |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
use docopt::Docopt;
use toml;
use gobjects;
use version::Version;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, //generate widgets etc.
Sys, //generate -sys with ffi
}
impl Default for WorkMode {
fn d... |
let external_libraries = toml.lookup("options.external_libraries")
.map(|a| a.as_slice().unwrap().iter()
.filter_map(|v|
if let &toml::Value::String(ref s) = v { Some(s.clone()) } else { None } )
.collect())
.unwrap_or_else(|| Vec::new... |
let mut objects = toml.lookup("object").map(|t| gobjects::parse_toml(t))
.unwrap_or_else(|| Default::default());
gobjects::parse_status_shorthands(&mut objects, &toml); | random_line_split |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
use docopt::Docopt;
use toml;
use gobjects;
use version::Version;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, //generate widgets etc.
Sys, //generate -sys with ffi
}
impl Default for WorkMode {
fn d... | (s: &str) -> Result<Self, Self::Err> {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
_ => Err("Wrong work mode".into())
}
}
}
static USAGE: &'static str = "
Usage: gir [options] [<library> <version>]
gir --help
Options:
-h, -... | from_str | identifier_name |
config.rs | use std::io::prelude::*;
use std::fs::File;
use std::str::FromStr;
use docopt::Docopt;
use toml;
use gobjects;
use version::Version;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, //generate widgets etc.
Sys, //generate -sys with ffi
}
impl Default for WorkMode {
fn d... |
}
static USAGE: &'static str = "
Usage: gir [options] [<library> <version>]
gir --help
Options:
-h, --help Show this message.
-c CONFIG Config file path (default: Gir.toml)
-d GIRSPATH Directory for girs
-m MODE Work mode: normal or sys
-o PATH ... | {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
_ => Err("Wrong work mode".into())
}
} | identifier_body |
karma.conf.js | // Karma configuration
// Generated on Wed Jun 01 2016 16:04:37 GMT-0400 (EDT)
module.exports = function (config) {
config.set({
basePath: '',
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'browserify'],
// include only tests here; ... |
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: false,
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enabl... | random_line_split | |
dompoint.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 dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... |
}
impl DOMPointMethods for DOMPoint {
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn X(&self) -> f64 {
self.point.X()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn SetX(&self, value: f64) {
self.point.SetX(value);
}
... | {
DOMPoint::new(global, p.x, p.y, p.z, p.w)
} | identifier_body |
dompoint.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 dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... | }
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn SetW(&self, value: f64) {
self.point.SetW(value);
}
} | self.point.W() | random_line_split |
dompoint.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 dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::c... | (&self) -> f64 {
self.point.Z()
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-z
fn SetZ(&self, value: f64) {
self.point.SetZ(value);
}
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-w
fn W(&self) -> f64 {
self.point.W()... | Z | identifier_name |
NestedBinding.ts | import array = require('dojo/_base/array');
import binding = require('../interfaces');
import Binding = require('../Binding');
import lang = require('dojo/_base/lang');
import util = require('../../util');
var SEPARATOR:string = '.';
/**
* The NestedBinding class enables binding to arbitrarily deep children of a sou... |
// If `object` exists, it will be the final object in the chain, the one on which we are actually looking
// for values
var value:any;
if (object) {
// If the values on this final object change we only need to update the value, not rebind
// any intermediate objects
binding = this._binder.createBindi... | {
path = this._path[index];
binding = this._binder.createBinding(object, path, { useScheduler: false });
binding.observe(<binding.IObserver<any>> lang.partial(function (index:number, change:binding.IChangeRecord<T>):void {
self._rebind(change.value, index + 1);
}, index));
bindings.push(binding);
... | conditional_block |
NestedBinding.ts | import array = require('dojo/_base/array');
import binding = require('../interfaces');
import Binding = require('../Binding');
import lang = require('dojo/_base/lang');
import util = require('../../util');
var SEPARATOR:string = '.';
/**
* The NestedBinding class enables binding to arbitrarily deep children of a sou... |
// If any of the intermediate objects between `object` and the property we are actually binding
// change, we need to rebind the entire object chain starting from the changed object
for (; index < length - 1 && object; ++index) {
path = this._path[index];
binding = this._binder.createBinding(object, path, ... | random_line_split | |
NestedBinding.ts | import array = require('dojo/_base/array');
import binding = require('../interfaces');
import Binding = require('../Binding');
import lang = require('dojo/_base/lang');
import util = require('../../util');
var SEPARATOR:string = '.';
/**
* The NestedBinding class enables binding to arbitrarily deep children of a sou... | (fromObject:Object, fromIndex:number):void {
var bindings = this._bindings;
// Stop watching objects that are no longer part of this binding's object chain because a parent object
// was replaced
array.forEach(bindings.splice(fromIndex), function (binding:binding.IBinding<any>):void {
binding.destroy();
}... | _rebind | identifier_name |
base_test_onramp.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Yannick Vaucher, Emanuel Cino
#
# The licence is in the file __openerp__.py
#
#... | self.assertEqual(e.exception.code, 401)
self.assertEqual(e.exception.msg, 'UNAUTHORIZED')
def _test_bad_token(self):
""" Check we have an access denied if token is not valid
"""
self.headers['Authorization'] = 'Bearer notarealtoken'
with self.assertRaises(url... | del self.headers['Authorization']
with self.assertRaises(urllib2.HTTPError) as e:
self._send_post({'nothing': 'nothing'}) | random_line_split |
base_test_onramp.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Yannick Vaucher, Emanuel Cino
#
# The licence is in the file __openerp__.py
#
#... |
def _test_bad_token(self):
""" Check we have an access denied if token is not valid
"""
self.headers['Authorization'] = 'Bearer notarealtoken'
with self.assertRaises(urllib2.HTTPError) as e:
self._send_post({'nothing': 'nothing'})
self.assertEqual(e.exceptio... | """ Check we have an access denied if token is not provided
"""
del self.headers['Authorization']
with self.assertRaises(urllib2.HTTPError) as e:
self._send_post({'nothing': 'nothing'})
self.assertEqual(e.exception.code, 401)
self.assertEqual(e.exception.msg, ... | identifier_body |
base_test_onramp.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Yannick Vaucher, Emanuel Cino
#
# The licence is in the file __openerp__.py
#
#... | (self):
super(TestOnramp, self).setUp()
self.server_url = self.env['ir.config_parameter'].get_param(
'web.base.url',
default='http://localhost:8069'
)
api_client_secret = base64.b64encode("client:secret")
self.rest_url = '{0}/onramp?secret={1}'.format(
... | setUp | identifier_name |
resources.component.ts | import { Component, OnInit } from '@angular/core';
import { IF_result } from '../shared/index';
import { ResourceService } from '../shared/api/resource.service';
/**
* 环境声明
* @type {any}
*/
declare var $:any;
/**
* interface - 资源单
*/
interface IF_resources {
isLoader : boolean;
isLast : boolean;
page : num... | ice.getResourceList(this.Resources)
.subscribe(
result => {
// console.log(result);
if (result.success == "0") {
this.Resources.total = Math.ceil(result.data.count / this.Resources.limit) ;
if(!isGetMore){
for (let value of result.data.... | ources.isLoader = true;
console.log(this.Resources)
this.resourceServ | conditional_block |
resources.component.ts | import { Component, OnInit } from '@angular/core';
import { IF_result } from '../shared/index';
import { ResourceService } from '../shared/api/resource.service';
/**
* 环境声明
* @type {any}
*/
declare var $:any;
/**
* interface - 资源单
*/
interface IF_resources {
isLoader : boolean;
isLast : boolean;
page : num... | this.Resources.page = 1;
}
this.Resources.isLoader = true;
console.log(this.Resources)
this.resourceService.getResourceList(this.Resources)
.subscribe(
result => {
// console.log(result);
if (result.success == "0") {
this.Resources.total = Math.ce... | esult = [];
| identifier_name |
resources.component.ts | import { Component, OnInit } from '@angular/core';
import { IF_result } from '../shared/index';
import { ResourceService } from '../shared/api/resource.service';
/**
* 环境声明
* @type {any}
*/
declare var $:any;
/**
* interface - 资源单
*/
interface IF_resources {
isLoader : boolean;
isLast : boolean;
page : num... | this.getResourceList();
},300);
}
/**
* 排序&条件变更 事件
* @param {boolean = false} type [description]
*/
changeList(type:boolean = false) {
if (type) {
this.Resources.created = "0";
this.Resources.adjusting = "0";
$('#sel-default').mobiscroll('clear');
$('#sel-date').mo... | setTimeout(()=> {
if ($.trim(this.Resources.category) == "") {
this.Resources.category = "";
} | random_line_split |
_configuration_async.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class ArtifactsClientConfiguration(Configuration):
"""Configuration for ArtifactsClient.
Note that all parameters used to create this insta... | random_line_split | |
_configuration_async.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | (
self,
**kwargs: Any
) -> None:
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.Pr... | _configure | identifier_name |
_configuration_async.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | """Configuration for ArtifactsClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param endpoint: The workspace... | identifier_body | |
_configuration_async.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) | conditional_block | |
S15.10.6.3_A1_T22.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
RegExp.prototype.test behavior depends on the lastIndex property:
ToLength(lastIndex) is the starting point for the search, so
negative numbers result in searchi... | if (__re.lastIndex !== 5) {
$ERROR('#2: __re = /(?:ab|cd)\\d?/g; __re.lastIndex=-1; __executed = __re.test("aacd22 "); __re.lastIndex === 5. Actual: ' + (__re.lastIndex));
}
__re.lastIndex=-100;
__executed = __re.test("aacd22 ");
//CHECK#3
if (!__executed) {
$ERROR('#3: __re = /(?:ab|cd)\\d?/g; __re.lastIndex=-1; _... |
//CHECK#2 | random_line_split |
S15.10.6.3_A1_T22.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
RegExp.prototype.test behavior depends on the lastIndex property:
ToLength(lastIndex) is the starting point for the search, so
negative numbers result in searchi... |
//CHECK#4
if (__re.lastIndex !== 5) {
$ERROR('#4: __re = /(?:ab|cd)\\d?/g; __re.lastIndex=-1; __executed = __re.test("aacd22 "); __re.lastIndex=-100; __executed = __re.test("aacd22 "); __re.lastIndex === 5. Actual: ' + (__re.lastIndex));
}
| {
$ERROR('#3: __re = /(?:ab|cd)\\d?/g; __re.lastIndex=-1; __executed = __re.test("aacd22 "); __re.lastIndex=-100; __executed = __re.test("aacd22 "); __executed === true');
} | conditional_block |
DragDrop.ts | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... |
/**
* called when a draggable is released
* @param $element a jQuery object for the draggable
* @private
*/
public static onDragStop($element: JQuery): void {
// Remove css class for the drag shadow
$element.children(DragDrop.dragIdentifier).removeClass('dragitem-shadow');
// Show create n... | {
// Add css class for the drag shadow
DragDrop.originalStyles = $element.get(0).style.cssText;
$element.children(DragDrop.dragIdentifier).addClass('dragitem-shadow');
$element.append('<div class="ui-draggable-copy-message">' + TYPO3.lang['dragdrop.copy.message'] + '</div>');
// Hide create new elem... | identifier_body |
DragDrop.ts | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... | else {
parameters.data.tt_content[contentElementUid] = {
colPos: colPos,
sys_language_uid: language,
};
parameters.cmd.tt_content[contentElementUid] = {move: targetPid};
}
DragDrop.ajaxAction($droppableElement, $draggableElement, parameters, copyAction).then(():... | {
parameters.cmd.tt_content[contentElementUid] = {
copy: {
action: 'paste',
target: targetPid,
update: {
colPos: colPos,
sys_language_uid: language,
},
},
};
} | conditional_block |
DragDrop.ts | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... | import $ from 'jquery';
import 'jquery-ui/droppable';
import DataHandler = require('../AjaxDataHandler');
import Icons = require('../Icons');
import ResponseInterface from '../AjaxDataHandler/ResponseInterface';
interface Parameters {
cmd?: { tt_content: { [key: string]: any } };
data?: { tt_content: { [key: strin... | * based on jQuery UI
*/ | random_line_split |
DragDrop.ts | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... | ($draggableElement: JQuery, $droppableElement: JQuery): void {
if ($droppableElement.hasClass(DragDrop.validDropZoneClass)) {
$droppableElement.addClass(DragDrop.dropPossibleHoverClass);
}
}
/**
* removes the CSS classes after hovering out of a dropzone again
* @param $draggableElement
* @pa... | onDropHoverOver | identifier_name |
xdatcar2xyz.1.04.py | # The MIT License (MIT)
#
# Copyright (c) 2014 Muratahan Aykol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
print element_dict
while True:
line = xdatcar.readline()
if len(line) == 0:
break
xyz.write(str(N) + "\ncomment\n")
xyz_fract.write(str(N)+"\ncomment\n")
for el in element_names:
for i in range(element_dict[el]):
p = xdatcar.readline().rstrip('\n').split()
... | element_dict[element_names[t]] = int(element_numbers[i])
N += int(element_numbers[i])
i += 1 | conditional_block |
xdatcar2xyz.1.04.py | # The MIT License (MIT)
#
# Copyright (c) 2014 Muratahan Aykol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | cartesian_coords = coords[0]*a1+coords[1]*a2+coords[2]*a3
xyz.write(el+ " " + str(cartesian_coords[0])+ " " + str(cartesian_coords[1]) + " " + str(cartesian_coords[2]) +"\n")
xyz_fract.write(el+ " " + str(coords[0])+ " " + str(coords[1]) + " " + str(coords[2]) +"\n")
xdatcar.close()... | for el in element_names:
for i in range(element_dict[el]):
p = xdatcar.readline().rstrip('\n').split()
coords = np.array([ float(s) for s in p ])
# print coords | random_line_split |
mknet_vd2d3d.py | from __future__ import print_function
import sys, os, math
import numpy as np
from numpy import float32, int32, uint8, dtype
# Load PyGreentea
# Relative path to where PyGreentea resides
pygt_path = '../..'
sys.path.append(pygt_path)
import pygreentea.pygreentea as pygt
import caffe
from caffe import layers as L |
net = caffe.NetSpec()
net.data = L.MemoryData(dim=[1, 1], ntop=1)
net.label = L.MemoryData(dim=[1, 1], ntop=1, include=[dict(phase=0)])
fmaps_vd2d3d = [24, 24, 36, 36, 48, 48, 60, 60]
net.sknet = ML.SKNet(net.data,
fmap_start=24,
conv=[[1,3,3],[1,3,3],[1,2,2],[1,3,3],[1,3,3],... | from caffe import params as P
from caffe import to_proto
from pygreentea.pygreentea import metalayers as ML
| random_line_split |
season.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation; version 2 dated June... | (Element):
""" A specified time period of the year, e.g., Spring, Summer, Fall, Winter
"""
# <<< season.attributes
# @generated
# Date season ends
end_date = db.DateTimeProperty()
# Date season starts
start_date = db.DateTimeProperty()
# Name of the Season
name = SeasonName... | Season | identifier_name |
season.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation; version 2 dated June... | """ A specified time period of the year, e.g., Spring, Summer, Fall, Winter
"""
# <<< season.attributes
# @generated
# Date season ends
end_date = db.DateTimeProperty()
# Date season starts
start_date = db.DateTimeProperty()
# Name of the Season
name = SeasonName
# >>>... | from google.appengine.ext import db
# >>> imports
class Season(Element): | random_line_split |
season.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation; version 2 dated June... |
# EOF -------------------------------------------------------------------------
| """ A specified time period of the year, e.g., Spring, Summer, Fall, Winter
"""
# <<< season.attributes
# @generated
# Date season ends
end_date = db.DateTimeProperty()
# Date season starts
start_date = db.DateTimeProperty()
# Name of the Season
name = SeasonName
# >>> sea... | identifier_body |
handlers.py | """App related signal handlers."""
import redis
from django.conf import settings
from django.db.models import signals
from django.dispatch import receiver
from modoboa.admin import models as admin_models
from . import constants
def set_message_limit(instance, key):
"""Store message limit in Redis."""
old_... |
return
if old_message_limit is not None:
diff = instance.message_limit - old_message_limit
else:
diff = instance.message_limit
rclient.hincrby(constants.REDIS_HASHNAME, key, diff)
@receiver(signals.post_save, sender=admin_models.Domain)
def set_domain_message_limit(sender, instanc... | rclient.hdel(constants.REDIS_HASHNAME, key) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.