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 |
|---|---|---|---|---|
decorators.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Function/method decorators that provide timeout and retry logic.
"""
import functools
import itertools
import sys
from devil.android import device_erro... | (f, timeout_func, retries_func, pass_values=False):
""" Wraps a funcion with timeout and retry handling logic.
Args:
f: The function to wrap.
timeout_func: A callable that returns the timeout value.
retries_func: A callable that returns the retries value.
pass_values: If True, passes the values ret... | _TimeoutRetryWrapper | identifier_name |
decorators.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Function/method decorators that provide timeout and retry logic.
"""
import functools
import itertools
import sys
from devil.android import device_erro... |
else:
desc = '%s(%s)' % (f.__name__, ', '.join(itertools.chain(
(str(a) for a in args),
('%s=%s' % (k, str(v)) for k, v in kwargs.iteritems()))))
return timeout_retry.Run(impl, timeout, retries, desc=desc)
except reraiser_thread.TimeoutError as e:
raise device_er... | return impl() | conditional_block |
decorators.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Function/method decorators that provide timeout and retry logic.
"""
import functools
import itertools
import sys
from devil.android import device_erro... |
def WithTimeoutAndRetriesFromInstance(
default_timeout_name=DEFAULT_TIMEOUT_ATTR,
default_retries_name=DEFAULT_RETRIES_ATTR,
min_default_timeout=None):
"""Returns a decorator that handles timeouts and retries.
The provided |default_timeout_name| and |default_retries_name| are used to
get the defau... | """Returns a decorator that handles timeouts and retries.
The provided |default_timeout| and |default_retries| values are used only
if timeout and retries values are not provided.
Args:
default_timeout: The number of seconds to wait for the decorated function
to return. Only used if a '... | identifier_body |
lib.rs | // Copyright 2015 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 ... |
use session::Session;
use lint::LintId;
mod builtin;
/// Tell the `LintStore` about all the built-in lints (the ones
/// defined in this crate and the ones defined in
/// `rustc::lint::builtin`).
pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
macro_rules! add_builtin {
($... | pub use rustc::middle as middle;
pub use rustc::session as session;
pub use rustc::util as util; | random_line_split |
lib.rs | // Copyright 2015 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 ... | )
}
add_builtin!(sess,
HardwiredLints,
WhileTrue,
ImproperCTypes,
BoxPointers,
UnusedAttributes,
PathStatements,
UnusedResults,
NonCamelCaseTypes,
... | {
macro_rules! add_builtin {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_pass($sess, false, box builtin::$name);
)*}
)
}
macro_rules! add_builtin_with_new {
($sess:ident, $($name:ident),*,) => (
{$(
... | identifier_body |
lib.rs | // Copyright 2015 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 ... | (store: &mut lint::LintStore, sess: Option<&Session>) {
macro_rules! add_builtin {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_pass($sess, false, box builtin::$name);
)*}
)
}
macro_rules! add_builtin_with_new {
($sess:iden... | register_builtins | identifier_name |
test_uri.py | from __future__ import unicode_literals
from httoop import URI
def test_simple_uri_comparision(uri):
u1 = URI(b'http://abc.com:80/~smith/home.html')
u2 = URI(b'http://ABC.com/%7Esmith/home.html')
u3 = URI(b'http://ABC.com:/%7esmith/home.html')
u4 = URI(b'http://ABC.com:/%7esmith/./home.html')
u5 = URI(b'http://... | assert bytes(URI(b'http://username@example.com')) == b'http://username@example.com'
assert bytes(URI(b'http://username:password@example.com')) == b'http://username:password@example.com' | identifier_body | |
test_uri.py | from __future__ import unicode_literals
from httoop import URI
def test_simple_uri_comparision(uri):
u1 = URI(b'http://abc.com:80/~smith/home.html')
u2 = URI(b'http://ABC.com/%7Esmith/home.html')
u3 = URI(b'http://ABC.com:/%7esmith/home.html')
u4 = URI(b'http://ABC.com:/%7esmith/./home.html')
u5 = URI(b'http://... | def test_request_uri_maxlength():
pass
def test_request_uri_is_star():
pass
def test_request_uri_containig_fragment():
pass
def test_invalid_uri_scheme():
pass
def test_invalid_port():
pass
def test_normalized_uri_redirects():
pass
def test_uri_composing_username_and_password():
assert bytes(URI(b'ht... | assert u1 == u5
| random_line_split |
test_uri.py | from __future__ import unicode_literals
from httoop import URI
def test_simple_uri_comparision(uri):
u1 = URI(b'http://abc.com:80/~smith/home.html')
u2 = URI(b'http://ABC.com/%7Esmith/home.html')
u3 = URI(b'http://ABC.com:/%7esmith/home.html')
u4 = URI(b'http://ABC.com:/%7esmith/./home.html')
u5 = URI(b'http://... | ():
pass
def test_request_uri_containig_fragment():
pass
def test_invalid_uri_scheme():
pass
def test_invalid_port():
pass
def test_normalized_uri_redirects():
pass
def test_uri_composing_username_and_password():
assert bytes(URI(b'http://username@example.com')) == b'http://username@example.com'
assert... | test_request_uri_is_star | identifier_name |
the_test.rs | use std::env;
use std::process;
use std::sync::Arc;
fn main() {
log_ndc_env_logger::init();
let mut server = httpbis::ServerBuilder::new_plain();
server
.service
.set_service("/", Arc::new(httpbis_h2spec_test::Ok200));
server.set_port(8888);
let _server = server.build().expect("ser... | .stderr(process::Stdio::inherit())
.spawn()
.expect("spawn h2spec");
let exit_status = h2spec.wait().expect("h2spec wait");
assert!(exit_status.success(), "{}", exit_status);
} | .stdin(process::Stdio::null())
.stdout(process::Stdio::inherit()) | random_line_split |
the_test.rs | use std::env;
use std::process;
use std::sync::Arc;
fn | () {
log_ndc_env_logger::init();
let mut server = httpbis::ServerBuilder::new_plain();
server
.service
.set_service("/", Arc::new(httpbis_h2spec_test::Ok200));
server.set_port(8888);
let _server = server.build().expect("server.build()");
let mut h2spec = process::Command::new("... | main | identifier_name |
the_test.rs | use std::env;
use std::process;
use std::sync::Arc;
fn main() | assert!(exit_status.success(), "{}", exit_status);
}
| {
log_ndc_env_logger::init();
let mut server = httpbis::ServerBuilder::new_plain();
server
.service
.set_service("/", Arc::new(httpbis_h2spec_test::Ok200));
server.set_port(8888);
let _server = server.build().expect("server.build()");
let mut h2spec = process::Command::new("h2s... | identifier_body |
reactNative.ts | import { trim } from 'ramda'
import exitCodes from '../lib/exit-codes'
import { IgniteToolbox, IgniteRNInstallResult } from '../types'
// DEPRECATED: Please specify React Native version when invoking install
// Example: const rnInstall = await reactNative.install({ name, version: '0.42.0' })
const REACT_NATIVE_VERSION... | if (opts.useNpm) {
rnOptions.push('--npm')
}
// react-native init
const cmd = trim(`npx react-native init ${name} ${rnOptions.join(' ')}`)
log('initializing react native')
log(cmd)
const withTemplate = reactNativeTemplate ? ` with ${print.colors.cyan(reactNativeTemplate)} template` : ''... | rnOptions.push('--skip-jest')
}
| conditional_block |
reactNative.ts | import { trim } from 'ramda'
import exitCodes from '../lib/exit-codes'
import { IgniteToolbox, IgniteRNInstallResult } from '../types'
// DEPRECATED: Please specify React Native version when invoking install
// Example: const rnInstall = await reactNative.install({ name, version: '0.42.0' })
const REACT_NATIVE_VERSION... | )}`,
)
if (parameters.options.debug) spinner.stop()
// ok, let's do this
// react-native init takes about 20s to execute
const stdioMode = parameters.options.debug ? 'inherit' : 'ignore'
try {
log('initializing react native project')
log(`command: ${cmd}`)
await system.e... | log(cmd)
const withTemplate = reactNativeTemplate ? ` with ${print.colors.cyan(reactNativeTemplate)} template` : ''
const spinner = print.spin(
`adding ${print.colors.cyan('React Native ' + reactNativeVersion)}${withTemplate} ${print.colors.muted(
'(30 seconds-ish)', | random_line_split |
reactNative.ts | import { trim } from 'ramda'
import exitCodes from '../lib/exit-codes'
import { IgniteToolbox, IgniteRNInstallResult } from '../types'
// DEPRECATED: Please specify React Native version when invoking install
// Example: const rnInstall = await reactNative.install({ name, version: '0.42.0' })
const REACT_NATIVE_VERSION... | const reactNativeTemplate = opts.template || parameters.options['react-native-template']
const perfStart = new Date().getTime()
// craft the additional options to pass to the react-native cli
const rnOptions = ['--version', reactNativeVersion]
if (!strings.isBlank(reactNativeTemplate)) {
rnO... | {
// fist-full o features
const { parameters, print, system, filesystem, strings, ignite } = toolbox
const { log } = ignite
/**
* Installs React Native.
*/
async function install(
opts: { name?: string; version?: string; template?: string; skipJest?: boolean; useNpm?: boolean } = {},
): Promise<I... | identifier_body |
reactNative.ts | import { trim } from 'ramda'
import exitCodes from '../lib/exit-codes'
import { IgniteToolbox, IgniteRNInstallResult } from '../types'
// DEPRECATED: Please specify React Native version when invoking install
// Example: const rnInstall = await reactNative.install({ name, version: '0.42.0' })
const REACT_NATIVE_VERSION... | (
opts: { name?: string; version?: string; template?: string; skipJest?: boolean; useNpm?: boolean } = {},
): Promise<IgniteRNInstallResult> {
// grab the name & version
const name = opts.name || parameters.first
let reactNativeVersion = opts.version || parameters.options['react-native-version']
... | install | identifier_name |
mod.rs | mod compile_mx;
pub mod cpp;
pub mod paths;
mod template;
use crate::error::Result;
use crate::generate::cpp::modeler::MxModeler;
use crate::generate::paths::Paths;
use crate::model::create::Create;
use crate::model::creator::Creator;
use crate::model::post_process::PostProcess;
use crate::model::transform::Transform;... | (args: GenArgs) -> Result<()> {
let xsd = read_to_string(&args.paths.xsd_3_0).unwrap();
let doc = exile::parse(xsd.as_str()).unwrap();
let new_xsd = Xsd::load(&args.paths.xsd_3_0)?;
let transforms: Vec<Box<dyn Transform>> = vec![Box::new(MxModeler::new())];
let creates: Vec<Box<dyn Create>> = vec![B... | run | identifier_name |
mod.rs | mod compile_mx;
pub mod cpp;
pub mod paths;
mod template;
use crate::error::Result;
use crate::generate::cpp::modeler::MxModeler;
use crate::generate::paths::Paths;
use crate::model::create::Create;
use crate::model::creator::Creator;
use crate::model::post_process::PostProcess;
use crate::model::transform::Transform;... |
}
/// Generate `mx::core` in C++
pub fn run(args: GenArgs) -> Result<()> {
let xsd = read_to_string(&args.paths.xsd_3_0).unwrap();
let doc = exile::parse(xsd.as_str()).unwrap();
let new_xsd = Xsd::load(&args.paths.xsd_3_0)?;
let transforms: Vec<Box<dyn Transform>> = vec![Box::new(MxModeler::new())];
... | {
Self {
paths: Paths::default(),
}
} | identifier_body |
mod.rs | mod compile_mx;
pub mod cpp;
pub mod paths;
mod template;
use crate::error::Result;
use crate::generate::cpp::modeler::MxModeler;
use crate::generate::paths::Paths;
use crate::model::create::Create;
use crate::model::creator::Creator;
use crate::model::post_process::PostProcess;
use crate::model::transform::Transform;... | let creates: Vec<Box<dyn Create>> = vec![Box::new(MxModeler::new())];
let post_processors: Vec<Box<dyn PostProcess>> = vec![Box::new(MxModeler::new())];
let creator = Creator::new_with_default(Some(transforms), Some(creates), Some(post_processors));
let models = creator.create(&new_xsd)?;
let cpp_wr... | random_line_split | |
rclxls.py | #!/usr/bin/env python2
# Extractor for Excel files.
# Mso-dumper is not compatible with Python3. We use sys.executable to
# start the actual extractor, so we need to use python2 too.
import rclexecm
import rclexec1
import xlsxmltocsv
import re
import sys
import os
import xml.sax
class XLSProcessData:
def __init_... | proto = rclexecm.RclExecM()
filter = XLSFilter(proto)
extract = rclexec1.Executor(proto, filter)
rclexecm.main(proto, extract) |
if __name__ == '__main__':
if not rclexecm.which("xls-dump.py"):
print("RECFILTERROR HELPERNOTFOUND ppt-dump.py")
sys.exit(1) | random_line_split |
rclxls.py | #!/usr/bin/env python2
# Extractor for Excel files.
# Mso-dumper is not compatible with Python3. We use sys.executable to
# start the actual extractor, so we need to use python2 too.
import rclexecm
import rclexec1
import xlsxmltocsv
import re
import sys
import os
import xml.sax
class XLSProcessData:
def __init_... | (self, line):
if self.ishtml:
self.out += line + "\n"
return
if not self.gotdata:
self.out += '''<html><head>''' + \
'''<meta http-equiv="Content-Type" ''' + \
'''content="text/html;charset=UTF-8">''' + \
... | takeLine | identifier_name |
rclxls.py | #!/usr/bin/env python2
# Extractor for Excel files.
# Mso-dumper is not compatible with Python3. We use sys.executable to
# start the actual extractor, so we need to use python2 too.
import rclexecm
import rclexec1
import xlsxmltocsv
import re
import sys
import os
import xml.sax
class XLSProcessData:
def __init_... | cmd = rclexecm.which("xls-dump.py")
if cmd:
# xls-dump.py often exits 1 with valid data. Ignore exit value
return ([sys.executable, cmd, "--dump-mode=canonical-xml", \
"--utf-8", "--catch"],
XLSProcessData(self.em), rclexec1.Executor.opt_i... | def __init__(self, em):
self.em = em
self.ntry = 0
def reset(self):
self.ntry = 0
pass
def getCmd(self, fn):
if self.ntry:
return ([], None)
self.ntry = 1
# Some HTML files masquerade as XLS
try:
data = open(fn... | identifier_body |
rclxls.py | #!/usr/bin/env python2
# Extractor for Excel files.
# Mso-dumper is not compatible with Python3. We use sys.executable to
# start the actual extractor, so we need to use python2 too.
import rclexecm
import rclexec1
import xlsxmltocsv
import re
import sys
import os
import xml.sax
class XLSProcessData:
def __init_... |
else:
return ([], None)
if __name__ == '__main__':
if not rclexecm.which("xls-dump.py"):
print("RECFILTERROR HELPERNOTFOUND ppt-dump.py")
sys.exit(1)
proto = rclexecm.RclExecM()
filter = XLSFilter(proto)
extract = rclexec1.Executor(proto, filter)
rclexecm.main(p... | return ([sys.executable, cmd, "--dump-mode=canonical-xml", \
"--utf-8", "--catch"],
XLSProcessData(self.em), rclexec1.Executor.opt_ignxval) | conditional_block |
schema.js | import should from 'should';
import Schema from '../../src/schema'; | const SIMPEL_OBJECT = {
type: 'object',
properties: {
name: { type: 'string' }
}
};
describe('Schema', () => {
describe('#getType', () => {
it('should return string type for child', () => {
const schema = new Schema(SIMPEL_OBJECT);
schema.getType('name').should.equal('string');
});
})... | random_line_split | |
test_anonymous_epic.py | """
Functional test
Anonymous Epic
Storyboard is defined within the comments of the program itself
"""
import unittest
from flask import url_for
from biblib.views.http_errors import NO_PERMISSION_ERROR
from biblib.tests.stubdata.stub_data import UserShop, LibraryShop
from biblib.tests.base import TestCaseDatabase, M... |
self.assertEqual(1, len(end_points))
self.assertEqual('/libraries/<string:library>', end_points[0])
if __name__ == '__main__':
unittest.main(verbosity=2) |
if len(response.json[end_point]['scopes']) == 0:
end_points.append(end_point) | random_line_split |
test_anonymous_epic.py | """
Functional test
Anonymous Epic
Storyboard is defined within the comments of the program itself
"""
import unittest
from flask import url_for
from biblib.views.http_errors import NO_PERMISSION_ERROR
from biblib.tests.stubdata.stub_data import UserShop, LibraryShop
from biblib.tests.base import TestCaseDatabase, M... |
# Dave makes two libraries
# One private library
# One public library
url = url_for('userview')
response = self.client.post(
url,
data=library_dave_private.user_view_post_data_json,
headers=user_dave.headers
)
library_id_privat... | """
Base class used to test the Big Share Admin Epic
"""
def test_anonymous_epic(self):
"""
Carries out the epic 'Anonymous', where a user tries to access a
private library and also a public library. The user also (artificial)
tries to access any other endpoints that do not ... | identifier_body |
test_anonymous_epic.py | """
Functional test
Anonymous Epic
Storyboard is defined within the comments of the program itself
"""
import unittest
from flask import url_for
from biblib.views.http_errors import NO_PERMISSION_ERROR
from biblib.tests.stubdata.stub_data import UserShop, LibraryShop
from biblib.tests.base import TestCaseDatabase, M... | (self):
"""
Separately test the number of scopes that are scopeless. This will only
fail during staging when the scopes are all set to be open. In the
production system, there is only once end point that will be scopeless.
"""
response = self.client.get('/resources')
... | test_scopes | identifier_name |
test_anonymous_epic.py | """
Functional test
Anonymous Epic
Storyboard is defined within the comments of the program itself
"""
import unittest
from flask import url_for
from biblib.views.http_errors import NO_PERMISSION_ERROR
from biblib.tests.stubdata.stub_data import UserShop, LibraryShop
from biblib.tests.base import TestCaseDatabase, M... | unittest.main(verbosity=2) | conditional_block | |
cdgdec.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... | () {
init();
let pipeline = gst::Pipeline::new(Some("cdgdec-test"));
let input_path = {
let mut r = PathBuf::new();
r.push(env!("CARGO_MANIFEST_DIR"));
r.push("tests");
r.push("BrotherJohn");
r.set_extension("cdg");
r
};
// Ensure we are in push mod... | test_cdgdec | identifier_name |
cdgdec.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... | child_proxy
.set_child_property("real-filesrc::blocksize", &blocksize)
.expect("failed to set 'blocksize' property");
}
let parse = gst::ElementFactory::make("cdgparse", None).unwrap();
let dec = gst::ElementFactory::make("cdgdec", None).unwrap();
let sink = gst::Element... | .expect("failed to set 'num-buffers' property");
let blocksize: u32 = 24; // One CDG instruction | random_line_split |
cdgdec.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... |
#[test]
fn test_cdgdec() {
init();
let pipeline = gst::Pipeline::new(Some("cdgdec-test"));
let input_path = {
let mut r = PathBuf::new();
r.push(env!("CARGO_MANIFEST_DIR"));
r.push("tests");
r.push("BrotherJohn");
r.set_extension("cdg");
r
};
// E... | {
use std::sync::Once;
static INIT: Once = Once::new();
INIT.call_once(|| {
gst::init().unwrap();
gstcdg::plugin_register_static().expect("cdgdec tests");
});
} | identifier_body |
a.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | {
let address: Ipv4Addr = tokens
.next()
.ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv4 address".to_string())))
.and_then(|s| Ipv4Addr::from_str(s).map_err(Into::into))?;
Ok(address)
} | identifier_body | |
a.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... |
use std::net::Ipv4Addr;
use std::str::FromStr;
use crate::error::*;
/// Parse the RData from a set of Tokens
pub fn parse<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv4Addr> {
let address: Ipv4Addr = tokens
.next()
.ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken(... | //! Parser for A text form | random_line_split |
a.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | <'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv4Addr> {
let address: Ipv4Addr = tokens
.next()
.ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv4 address".to_string())))
.and_then(|s| Ipv4Addr::from_str(s).map_err(Into::into))?;
Ok(address)
}
| parse | identifier_name |
rendering.py | List.append(oShdEng)
elif isinstance(oObj, pm.general.NurbsSurfaceFace):
oShape = oObj.node()
elif isinstance(oObj, pm.nt.Transform):
oShape = oObj.getShape()
elif isinstance(oObj, (pm.nt.Mesh, pm.nt.NurbsSurface)):
oShape = oObj
elif warn:
logMsg("Can't get shading g... | logMsg("Processing {0}".format(repr(oMat)))
try:
colorAttr = oMat.attr("color")
except pm.MayaAttributeError:
logMsg("\tNo color attribute found.")
continue
try:
oSG = oMat.shadingGroups()[0]
except IndexError:
print "\tNo Sha... | conditional_block | |
rendering.py | :
oObj = obj if isinstance(obj, pm.PyNode) else pm.PyNode(obj)
oShdGrpList.update(shadingGroupsForObject(oObj))
return list(oShdGrpList)
def shadingGroupsForObject(oObj, warn=True):
oShdGrpList = []
oShape = None
if isinstance(oObj, pm.general.MeshFace):
indiceList = oObj.in... | button=['Ok', 'Cancel'],
defaultButton='Cancel',
cancelButton='Cancel',
dismissString='Cancel')
if result == 'Cancel':
return
else :
for oSourceXfm, oTargetXfm in tra... | # if notFoundList:
# pm.sets(oSet, addElement=notFoundList)
result = pm.confirmDialog(title='Transfer Uvs',
message='Found {0}/{1} mismatches :'.format(len(notFoundList), len(transferList)), | random_line_split |
rendering.py |
def shadersFromObjects(objList, connectedTo=""):
sAttrName = connectedTo
if not objList:
return []
oMatSgList = shadingGroupsFromObjects(objList)
oMatList = []
for oMatSg in oMatSgList:
sName = oMatSg.attr(sAttrName).name() if connectedTo else oMatSg.name()
oMatList.ext... | oFileNodeList = set()
for oMat in oMatList:
oFileNodeList.update(oMat.listHistory(type="file"))
return list(oFileNodeList) | identifier_body | |
rendering.py | :
oObj = obj if isinstance(obj, pm.PyNode) else pm.PyNode(obj)
oShdGrpList.update(shadingGroupsForObject(oObj))
return list(oShdGrpList)
def shadingGroupsForObject(oObj, warn=True):
oShdGrpList = []
oShape = None
if isinstance(oObj, pm.general.MeshFace):
indiceList = oObj.in... | (oMeshList, sNamespaceToMatch , **kwargs):
bForce = kwargs.get("force", False)
oShadingGroupMembersDct = {}
oMatNotConformList = []
for oShape in oMeshList:
# print "\nfor shape: ", oShape
oMatSGList = shadingGroupsForObject(oShape)
for oMatSG in oMatSGList:
# print ... | conformShadingNetworkToNamespace | identifier_name |
lower_caser.rs | use super::{Token, TokenFilter, TokenStream};
use crate::tokenizer::BoxTokenStream;
use std::mem;
impl TokenFilter for LowerCaser {
fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> {
BoxTokenStream::from(LowerCaserTokenStream {
tail: token_stream,
buff... | (&mut self) -> bool {
if !self.tail.advance() {
return false;
}
if self.token_mut().text.is_ascii() {
// fast track for ascii.
self.token_mut().text.make_ascii_lowercase();
} else {
to_lowercase_unicode(&mut self.tail.token_mut().text, &mut... | advance | identifier_name |
lower_caser.rs | use super::{Token, TokenFilter, TokenStream};
use crate::tokenizer::BoxTokenStream;
use std::mem;
impl TokenFilter for LowerCaser {
fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> {
BoxTokenStream::from(LowerCaserTokenStream {
tail: token_stream,
buff... | }
true
}
fn token(&self) -> &Token {
self.tail.token()
}
fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
}
#[cfg(test)]
mod tests {
use crate::tokenizer::tests::assert_token;
use crate::tokenizer::{LowerCaser, SimpleTokenizer, TextAnalyzer, ... | to_lowercase_unicode(&mut self.tail.token_mut().text, &mut self.buffer);
mem::swap(&mut self.tail.token_mut().text, &mut self.buffer); | random_line_split |
lower_caser.rs | use super::{Token, TokenFilter, TokenStream};
use crate::tokenizer::BoxTokenStream;
use std::mem;
impl TokenFilter for LowerCaser {
fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> {
BoxTokenStream::from(LowerCaserTokenStream {
tail: token_stream,
buff... |
}
#[cfg(test)]
mod tests {
use crate::tokenizer::tests::assert_token;
use crate::tokenizer::{LowerCaser, SimpleTokenizer, TextAnalyzer, Token};
#[test]
fn test_to_lower_case() {
let tokens = token_stream_helper("Tree");
assert_eq!(tokens.len(), 1);
assert_token(&tokens[0], 0, ... | {
self.tail.token_mut()
} | identifier_body |
lower_caser.rs | use super::{Token, TokenFilter, TokenStream};
use crate::tokenizer::BoxTokenStream;
use std::mem;
impl TokenFilter for LowerCaser {
fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> {
BoxTokenStream::from(LowerCaserTokenStream {
tail: token_stream,
buff... |
true
}
fn token(&self) -> &Token {
self.tail.token()
}
fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
}
#[cfg(test)]
mod tests {
use crate::tokenizer::tests::assert_token;
use crate::tokenizer::{LowerCaser, SimpleTokenizer, TextAnalyzer, Token};
... | {
to_lowercase_unicode(&mut self.tail.token_mut().text, &mut self.buffer);
mem::swap(&mut self.tail.token_mut().text, &mut self.buffer);
} | conditional_block |
findbestmatch.py | instead
#lev_dist = levenshtein_distance(six.text_type(match_against), six.text_type(text))
#ratio = 1 - lev_dist / 10.0
#ratios[text] = ratio
# calculate ratio and store it
ratios[text] = ratio_calc.ratio()
_cache[(match_against, text)]... | names.extend(non_text_names) | conditional_block | |
findbestmatch.py | * **limit_ratio** How well the text has to match the best match.
If the best match matches lower then this then it is not
considered a match and a MatchError is raised, (default = .5)
"""
search_text = _cut_at_eol(_cut_at_tab(search_text))
text_item_map = UniqueDict()
# Clean eac... | """A dictionary subclass that handles making its keys unique"""
def __setitem__(self, text, item):
"""Set an item of the dictionary"""
# this text is already in the map
# so we need to make it unique
if text in self:
# find next unique text after text1
... | identifier_body | |
findbestmatch.py | # list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the ... | # * Redistributions of source code must retain the above copyright notice, this
| random_line_split | |
findbestmatch.py | ratio_calc.set_seq2(text)
# try using the levenshtein distance instead
#lev_dist = levenshtein_distance(six.text_type(match_against), six.text_type(text))
#ratio = 1 - lev_dist / 10.0
#ratios[text] = ratio
# calculate ratio and store it
... | (text):
"""Clean out non characters from the string and return it"""
# remove anything after the first tab
return _after_tab.sub("", text)
def _cut_at_eol(text):
"""Clean out non characters from the string and return it"""
# remove anything after the first EOL
return _after_eol.sub(""... | _cut_at_tab | identifier_name |
pages.js | 'use strict';
var express = require('express');
var router = express.Router();
var models = require('../../models');
/* GET list pages */
router.get('/', function(req, res, next) {
models.Page.findAll({
include: [models.NavigationItem]
}).then(function(pages) {
res.render('admin/pages/index', {
titl... |
res.render('admin/pages/view', {title: page.title, page:page});
});
});
/* POST create page */
router.post('/', function(req, res, next) {
var data = {
title: req.body.title,
url: req.body.url,
content: req.body.content || null,
enabled: !!req.body.enabled
};
models.Page.create(data).the... | {
return next();
} | conditional_block |
pages.js | 'use strict';
var express = require('express');
var router = express.Router();
var models = require('../../models');
/* GET list pages */
router.get('/', function(req, res, next) {
models.Page.findAll({
include: [models.NavigationItem]
}).then(function(pages) {
res.render('admin/pages/index', {
titl... | router.post('/', function(req, res, next) {
var data = {
title: req.body.title,
url: req.body.url,
content: req.body.content || null,
enabled: !!req.body.enabled
};
models.Page.create(data).then(function(page) {
req.flash('success', 'The page has been created!');
res.redirect('/admin/page... | /* POST create page */ | random_line_split |
example_tasks.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | # under the License.
"""
Example Airflow DAG that creates, gets, lists, updates, purges, pauses, resumes
and deletes Queues and creates, gets, lists, runs and deletes Tasks in the Google
Cloud Tasks service in the Google Cloud.
"""
import os
from datetime import datetime, timedelta
from google.api_core.retry import R... | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations | random_line_split |
simple_executor.rs | use crate::task::Task;
use alloc::collections::VecDeque;
use core::task::{RawWaker, RawWakerVTable, Waker};
pub struct SimpleExecutor {
task_queue: VecDeque<Task>, | task_queue: VecDeque::new(),
}
}
pub fn spawn(&mut self, task: Task) { self.task_queue.push_back(task) }
}
fn dummy_raw_waker() -> RawWaker {
fn no_op(_: *const ()) {}
fn clone(_: *const ()) -> RawWaker { dummy_raw_waker() }
let vtable = &RawWakerVTable::new(clone, no_op, no_o... | }
impl SimpleExecutor {
pub fn new() -> SimpleExecutor {
SimpleExecutor { | random_line_split |
simple_executor.rs | use crate::task::Task;
use alloc::collections::VecDeque;
use core::task::{RawWaker, RawWakerVTable, Waker};
pub struct SimpleExecutor {
task_queue: VecDeque<Task>,
}
impl SimpleExecutor {
pub fn new() -> SimpleExecutor {
SimpleExecutor {
task_queue: VecDeque::new(),
}
}
pu... | () -> RawWaker {
fn no_op(_: *const ()) {}
fn clone(_: *const ()) -> RawWaker { dummy_raw_waker() }
let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op);
RawWaker::new(0 as *const (), vtable)
}
fn dummy_waker() -> Waker { unsafe { Waker::from_raw(dummy_raw_waker()) } }
| dummy_raw_waker | identifier_name |
simple_executor.rs | use crate::task::Task;
use alloc::collections::VecDeque;
use core::task::{RawWaker, RawWakerVTable, Waker};
pub struct SimpleExecutor {
task_queue: VecDeque<Task>,
}
impl SimpleExecutor {
pub fn new() -> SimpleExecutor |
pub fn spawn(&mut self, task: Task) { self.task_queue.push_back(task) }
}
fn dummy_raw_waker() -> RawWaker {
fn no_op(_: *const ()) {}
fn clone(_: *const ()) -> RawWaker { dummy_raw_waker() }
let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op);
RawWaker::new(0 as *const (), vtable)
}
... | {
SimpleExecutor {
task_queue: VecDeque::new(),
}
} | identifier_body |
index.d.ts | // Type definitions for Angular xEditable (angular.xeditable module) 0.2
// Project: https://vitalets.github.io/angular-xeditable/
// Definitions by: Joao Monteiro <https://github.com/jpmnteiro>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as angular from "angu... | } | }
} | random_line_split |
utils.py | from django.core.cache import cache
from django.conf import settings
from django.template.loader import render_to_string
from tendenci.apps.navs.cache import NAV_PRE_KEY
def cache_nav(nav, show_title=False):
"""
Caches a nav's rendered html code
"""
keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(n... | """
Clear nav cache
"""
keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(nav.id)]
key = '.'.join(keys)
cache.delete(key) | identifier_body | |
utils.py | from django.core.cache import cache
from django.conf import settings
from django.template.loader import render_to_string
from tendenci.apps.navs.cache import NAV_PRE_KEY
def | (nav, show_title=False):
"""
Caches a nav's rendered html code
"""
keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(nav.id)]
key = '.'.join(keys)
value = render_to_string("navs/render_nav.html", {'nav':nav, "show_title": show_title})
cache.set(key, value, 432000) #5 days
return value
d... | cache_nav | identifier_name |
utils.py | from django.core.cache import cache
from django.conf import settings
from django.template.loader import render_to_string
from tendenci.apps.navs.cache import NAV_PRE_KEY
def cache_nav(nav, show_title=False):
"""
Caches a nav's rendered html code
"""
keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(n... | cache.delete(key) | random_line_split | |
test_base.py | get_run_root('ext/hadoop/hadoop') + '/share/hadoop/common/hadoop-common.jar'
+ ':' +
get_run_root('ext/hadoop/hadoop') + '/share/hadoop/mapreduce/hadoop-mapreduce-client-core.jar'
,
'HADOOP_CLASSPATH': hadoop_cp,
})
if os.getenv("JAVA_HOME"):
env["JAVA_HOME"] = os.getenv("JAVA... |
parameters["file_resources-next_form_id"] = str(len(resources or []))
for i, resources_pair in enumerate(resources or []):
type, path = resources_pair
parameters["file_resources-%d-type" % i] = str(type)
parameters["file_resources-%d-path" % i] = str(path)
parameters["file_resources-%d-_exists" % i... | key, value = settings_pair
parameters["settings-%d-key" % i] = str(key)
parameters["settings-%d-value" % i] = str(value)
parameters["settings-%d-_exists" % i] = 'True' | conditional_block |
test_base.py | +
get_run_root('ext/hadoop/hadoop') + '/share/hadoop/common/hadoop-common.jar'
+ ':' +
get_run_root('ext/hadoop/hadoop') + '/share/hadoop/mapreduce/hadoop-mapreduce-client-core.jar'
,
'HADOOP_CLASSPATH': hadoop_cp,
})
if os.getenv("JAVA_HOME"):
env["JAVA_HOME"] = os.getenv("J... | <name>hive.server2.enable.impersonation</name>
<value>false</value>
</property>
<property>
<name>hive.querylog.location</name>
<value>%(querylog)s</value>
</property>
</configuration>
""" % {'root': cluster._tmpdir, 'querylog': cluster.log_dir + '/hive'}
file(HIVE_CONF + '/hive-site.xml', 'w').write(default_... | HIVE_CONF = cluster.hadoop_conf_dir
finish = (
beeswax.conf.HIVE_SERVER_HOST.set_for_testing(get_localhost_name()),
beeswax.conf.HIVE_SERVER_PORT.set_for_testing(HIVE_SERVER_TEST_PORT),
beeswax.conf.HIVE_SERVER_BIN.set_for_testing(get_run_root('ext/hive/hive') + '/bin/hiveserver2'),
beeswax.conf.H... | identifier_body |
test_base.py | +
get_run_root('ext/hadoop/hadoop') + '/share/hadoop/common/hadoop-common.jar'
+ ':' +
get_run_root('ext/hadoop/hadoop') + '/share/hadoop/mapreduce/hadoop-mapreduce-client-core.jar'
,
'HADOOP_CLASSPATH': hadoop_cp,
})
if os.getenv("JAVA_HOME"):
env["JAVA_HOME"] = os.getenv("J... |
parameters["functions-next_form_id"] = str(len(udfs or []))
for i, udf_pair in enumerate(udfs or []):
name, klass = udf_pair
parameters["functions-%d-name" % i] = name
parameters["functions-%d-class_name" % i] = klass
parameters["functions-%d-_exists" % i] = 'True'
parameters["settings-next_form_... | if name:
parameters['saveform-name'] = name
if desc:
parameters['saveform-desc'] = desc | random_line_split |
test_base.py | be found after: %s' % e)
time.sleep(sleep)
if not started:
raise Exception("Server took too long to come up.")
_SHARED_HIVE_SERVER, _SHARED_HIVE_SERVER_CLOSER = cluster, s
return _SHARED_HIVE_SERVER, _SHARED_HIVE_SERVER_CLOSER
def _start_mini_hs2(cluster):
HIVE_CONF = cluster.hadoop_conf... | init_beeswax_db | identifier_name | |
input.type.spec.ts | import { FormlyFieldConfig } from '@ngx-formly/core';
import { createFieldComponent, ɵCustomEvent } from '@ngx-formly/core/testing';
import { FormlyMatInputModule } from '@ngx-formly/material/input';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
const renderComponent = (field: FormlyFiel... | describe('ui-material: Input Type', () => {
it('should render input type', () => {
const { query } = renderComponent({
key: 'name',
type: 'input',
});
expect(query('formly-wrapper-mat-form-field')).not.toBeNull();
const { attributes } = query('input[type="text"]');
expect(attributes)... | random_line_split | |
xhr_impl.js | 'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(funct... |
MessageBasedXHRImpl.prototype.start = function () {
var broker = this._brokerFactory.createMessageBroker(messaging_api_1.XHR_CHANNEL);
broker.registerMethod("get", [serializer_1.PRIMITIVE], bind_1.bind(this._xhr.get, this._xhr), serializer_1.PRIMITIVE);
};
MessageBasedXHRImpl = __decorate([... | {
this._brokerFactory = _brokerFactory;
this._xhr = _xhr;
} | identifier_body |
xhr_impl.js | 'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(funct... | (_brokerFactory, _xhr) {
this._brokerFactory = _brokerFactory;
this._xhr = _xhr;
}
MessageBasedXHRImpl.prototype.start = function () {
var broker = this._brokerFactory.createMessageBroker(messaging_api_1.XHR_CHANNEL);
broker.registerMethod("get", [serializer_1.PRIMITIVE], bind_1.... | MessageBasedXHRImpl | identifier_name |
xhr_impl.js | 'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(funct... | exports.MessageBasedXHRImpl = MessageBasedXHRImpl;
//# sourceMappingURL=xhr_impl.js.map | __metadata('design:paramtypes', [service_message_broker_1.ServiceMessageBrokerFactory, xhr_1.XHR])
], MessageBasedXHRImpl);
return MessageBasedXHRImpl;
})(); | random_line_split |
lib.rs | pub fn block_indent(mut self, config: &Config) -> Indent {
self.block_indent += config.tab_spaces;
self
}
pub fn block_unindent(mut self, config: &Config) -> Indent {
self.block_indent -= config.tab_spaces;
self
}
pub fn width(&self) -> usize {
self.block_inden... | let main_file = match input {
Input::File(ref file) => file.clone(),
Input::Text(..) => PathBuf::from("stdin"),
}; | random_line_split | |
lib.rs | _use]
mod utils;
pub mod config;
pub mod codemap;
pub mod filemap;
pub mod file_lines;
pub mod visitor;
mod checkstyle;
mod items;
mod missed_spans;
mod lists;
mod types;
mod expr;
mod imports;
mod issues;
mod rewrite;
mod string;
mod comment;
pub mod modules;
pub mod rustfmt_diff;
mod chains;
mod macros;
mod patterns;... | (&self) -> bool {
self.warning_count() > 0
}
}
impl fmt::Display for FormatReport {
// Prints all the formatting errors.
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for (file, errors) in &self.file_error_map {
for error in errors {
try!(wr... | has_warnings | identifier_name |
lib.rs | _use]
mod utils;
pub mod config;
pub mod codemap;
pub mod filemap;
pub mod file_lines;
pub mod visitor;
mod checkstyle;
mod items;
mod missed_spans;
mod lists;
mod types;
mod expr;
mod imports;
mod issues;
mod rewrite;
mod string;
mod comment;
pub mod modules;
pub mod rustfmt_diff;
mod chains;
mod macros;
mod patterns;... |
}
impl Spanned for ast::Ty {
fn span(&self) -> Span {
self.span
}
}
impl Spanned for ast::Arg {
fn span(&self) -> Span {
if items::is_named_arg(self) {
mk_sp(self.pat.span.lo, self.ty.span.hi)
} else {
self.ty.span
}
}
}
#[derive(Copy, Clone, D... | {
self.span
} | identifier_body |
font.rs | sync::Arc;
use std::{fmt, ptr};
use style::values::computed::font::{FontStretch, FontStyle, FontWeight};
const KERN_PAIR_LEN: usize = 6;
pub struct FontTable {
data: CFData,
}
// assumes 72 points per inch, and 96 px per inch
fn px_to_pt(px: f64) -> f64 {
px / 96. * 72.
}
// assumes 72 points per inch, and ... | None => Err(()),
}
}
fn template(&self) -> Arc<FontTemplateData> {
self.font_data.clone()
}
fn family_name(&self) -> Option<String> {
Some(self.ctfont.family_name())
}
fn face_name(&self) -> Option<String> {
Some(self.ctfont.face_name())
}
... | {
let size = match pt_size {
Some(s) => s.to_f64_px(),
None => 0.0,
};
match template.ctfont(size) {
Some(ref ctfont) => {
let mut handle = FontHandle {
font_data: template.clone(),
ctfont: ctfont.clone_w... | identifier_body |
font.rs | ern_subtable(&self) -> Option<CachedKernTable> {
let font_table = self.table_for_tag(KERN)?;
let mut result = CachedKernTable {
font_table: font_table,
pair_data_range: 0..0,
px_per_font_unit: 0.0,
};
// Look for a subtable with horizontal kerning in ... | // see also: https://bugs.webkit.org/show_bug.cgi?id=16768 | random_line_split | |
font.rs | sync::Arc;
use std::{fmt, ptr};
use style::values::computed::font::{FontStretch, FontStyle, FontWeight};
const KERN_PAIR_LEN: usize = 6;
pub struct FontTable {
data: CFData,
}
// assumes 72 points per inch, and 96 px per inch
fn px_to_pt(px: f64) -> f64 {
px / 96. * 72.
}
// assumes 72 points per inch, and ... | (pt: f64) -> Au {
Au::from_f64_px(pt_to_px(pt))
}
impl FontTable {
pub fn wrap(data: CFData) -> FontTable {
FontTable { data: data }
}
}
impl FontTableMethods for FontTable {
fn buffer(&self) -> &[u8] {
self.data.bytes()
}
}
#[derive(Debug)]
pub struct FontHandle {
font_data: ... | au_from_pt | identifier_name |
PostActionButton.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import { post } from '../../api';
class PostActionButton extends Component {
static propTypes = {
bsStyle: PropTypes.string.isRequ... |
onClick = () => {
this.setState({ isWorking: true });
const { body, action, onSuccess, onError } = this.props;
post(action, body).then(() => {
this.setState({ isWorking: false });
onSuccess();
}, (err) => {
console.error(err);
onError(err);
});
};
render() {
co... | {
super(props);
this.state = { isWorking: false };
} | identifier_body |
PostActionButton.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import { post } from '../../api';
class PostActionButton extends Component {
static propTypes = {
bsStyle: PropTypes.string.isRequ... | () {
const { isWorking } = this.state;
const { hideContentOnAction, bsStyle, children } = this.props;
const renderChildren = !isWorking || (isWorking && !hideContentOnAction);
return (
<Button onClick={this.onClick} bsStyle={bsStyle}>
{isWorking &&
<Glyphicon glyph="refresh" classNa... | render | identifier_name |
PostActionButton.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import { post } from '../../api';
class PostActionButton extends Component {
static propTypes = {
bsStyle: PropTypes.string.isRequ... | this.setState({ isWorking: true });
const { body, action, onSuccess, onError } = this.props;
post(action, body).then(() => {
this.setState({ isWorking: false });
onSuccess();
}, (err) => {
console.error(err);
onError(err);
});
};
render() {
const { isWorking } = th... | super(props);
this.state = { isWorking: false };
}
onClick = () => { | random_line_split |
chrome_driver_extension.ts | 'v8,blink.console,disabled-by-default-devtools.timeline,devtools.timeline'
*
* In order to collect the frame rate related metrics, add 'benchmark'
* to the list above.
*/
export class ChromeDriverExtension extends WebDriverExtension {
// TODO(tbosch): use static values when our transpiler supports them
static ... |
gc() { return this._driver.executeScript('window.gc()'); }
timeBegin(name: string): Promise<any> {
return this._driver.executeScript(`console.time('${name}');`);
}
timeEnd(name: string, restartName: string = null): Promise<any> {
var script = `console.timeEnd('${name}');`;
if (isPresent(restartN... | {
if (isBlank(userAgent)) {
return -1;
}
var v = StringWrapper.split(userAgent, /Chrom(e|ium)\//g)[2];
if (isBlank(v)) {
return -1;
}
v = StringWrapper.split(v, /\./g)[0];
if (isBlank(v)) {
return -1;
}
return NumberWrapper.parseInt(v, 10);
} | identifier_body |
chrome_driver_extension.ts | 'v8,blink.console,disabled-by-default-devtools.timeline,devtools.timeline'
*
* In order to collect the frame rate related metrics, add 'benchmark'
* to the list above.
*/
export class ChromeDriverExtension extends WebDriverExtension {
// TODO(tbosch): use static values when our transpiler supports them
static ... | else if (this._isEvent(categories, name, ['v8'], 'majorGC') &&
StringWrapper.equals(ph, 'B')) {
majorGCPids[pid] = true;
}
return null; // nothing useful in this event
}
private _processAsPostChrome44Event(event, categories) {
var name = event['name'];
var args = event['args'... | {
var normArgs = {
'usedHeapSize': isPresent(args['usedHeapSizeAfter']) ? args['usedHeapSizeAfter'] :
args['usedHeapSizeBefore']
};
if (StringWrapper.equals(ph, 'E')) {
normArgs['majorGc'] = isPresent(majorGCPids[pid]) && m... | conditional_block |
chrome_driver_extension.ts | 'v8,blink.console,disabled-by-default-devtools.timeline,devtools.timeline'
*
* In order to collect the frame rate related metrics, add 'benchmark'
* to the list above.
*/
export class ChromeDriverExtension extends WebDriverExtension {
// TODO(tbosch): use static values when our transpiler supports them
static ... | }
var v = StringWrapper.split(userAgent, /Chrom(e|ium)\//g)[2];
if (isBlank(v)) {
return -1;
}
v = StringWrapper.split(v, /\./g)[0];
if (isBlank(v)) {
return -1;
}
return NumberWrapper.parseInt(v, 10);
}
gc() { return this._driver.executeScript('window.gc()'); }
timeB... | }
private _parseChromeVersion(userAgent: string): number {
if (isBlank(userAgent)) {
return -1; | random_line_split |
chrome_driver_extension.ts | {
// TODO(tbosch): use static values when our transpiler supports them
static get BINDINGS(): Binding[] { return _BINDINGS; }
private _majorChromeVersion: number;
constructor(private _driver: WebDriverAdapter, userAgent: string) {
super();
this._majorChromeVersion = this._parseChromeVersion(userAgent... | supports | identifier_name | |
lineNumbers.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
let lineIndex = lineNumber - startLineNumber;
if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
return '';
}
return this._renderResult[lineIndex];
}
}
// theming
registerThemingParticipant((theme, collector) => {
const lineNumbers = theme.getColor(editorLineNumbers);
if (lineNumbers) {
c... | {
return '';
} | conditional_block |
lineNumbers.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
let modelLineNumber = modelPosition.lineNumber;
if (this._renderCustomLineNumbers) {
return this._renderCustomLineNumbers(modelLineNumber);
}
if (this._renderLineNumbers === RenderLineNumbersType.Relative) {
let diff = Math.abs(this._lastCursorModelPosition.lineNumber - modelLineNumber);
if (diff... | const modelPosition = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new Position(viewLineNumber, 1));
if (modelPosition.column !== 1) {
return ''; | random_line_split |
lineNumbers.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
return true;
}
public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean {
return true;
}
public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean {
return true;
}
public onScrollChanged(e: viewEvents.ViewScrollCh... | {
return true;
} | identifier_body |
lineNumbers.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | extends DynamicViewOverlay {
public static readonly CLASS_NAME = 'line-numbers';
private _context: ViewContext;
private _lineHeight: number;
private _renderLineNumbers: RenderLineNumbersType;
private _renderCustomLineNumbers: ((lineNumber: number) => string) | null;
private _lineNumbersLeft: number;
private ... | LineNumbersOverlay | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as | # WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 5... | # published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but | random_line_split |
main.rs | .org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// l... | break;
}
}
}
}
fn main() {
let (mut worker, tx, rx) = Worker::create(1024);
/*
let module = Box::new(modules::ConstCtrl::new(440.0f32.log2()));
worker.handle_node(Node::create(module, 1, [], []));
let module = Box::new(modules::Sin::new(44_100.0));
worke... | self.cur_note = if on { Some(midi_num) } else { None }
}
i += 3;
} else { | random_line_split |
main.rs | /licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limit... | (&self, msg: Message) {
self.tx.send(msg);
}
fn set_ctrl_const(&mut self, value: u8, lo: f32, hi: f32, ix: usize, ts: u64) {
let value = lo + value as f32 * (1.0/127.0) * (hi - lo);
let param = SetParam {
ix: ix,
param_ix: 0,
val: value,
t... | send | identifier_name |
main.rs | /licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limit... | else if data[i] == 0x90 || data[i] == 0x80 {
let midi_num = data[i + 1];
let velocity = data[i + 2];
let on = data[i] == 0x90 && velocity > 0;
if on || self.cur_note == Some(midi_num) {
self.send_note(vec![5, 7], midi_num as f32, veloc... | {
let controller = data[i + 1];
let value = data[i + 2];
match controller {
1 => self.set_ctrl_const(value, 0.0, 22_000f32.log2(), 3, ts),
2 => self.set_ctrl_const(value, 0.0, 0.995, 4, ts),
3 => self.set_ctrl_co... | conditional_block |
banner_generator.py | from osgeo import gdal, osr, ogr
import numpy as np
import scipy.misc
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("banner-generator")
def create_raster_from_band( red, green, blue, output_file):
logger.debug("Create big raster in output_file : %s"%output_file)
red_ds = gd... | dst_ds = gdal.GetDriverByName('GTiff').Create(output_file, ny, nx, 3, gdal.GDT_UInt16)
dst_ds.SetGeoTransform(red_ds.GetGeoTransform())
dst_ds.SetProjection(red_ds.GetProjection())
def write_band(band, index_band):
logger.debug("Write band : %s"%index_band)
band_ds = gdal.Open(band... | nx = red_ds.GetRasterBand(1).XSize
ny = red_ds.GetRasterBand(1).YSize
| random_line_split |
banner_generator.py | from osgeo import gdal, osr, ogr
import numpy as np
import scipy.misc
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("banner-generator")
def create_raster_from_band( red, green, blue, output_file):
logger.debug("Create big raster in output_file : %s"%output_file)
red_ds = gd... | ulx, xres, xskew, uly, yskew, yres = raster_ds.GetGeoTransform()
logger.debug("Upper left coordinate in proj")
logger.debug("Point x : %s"%ulx)
logger.debug("Point x : %s"%uly)
lrx = ulx + (raster_ds.RasterXSize * xres)
lry = uly + (raster_ds.RasterYSize * yres)
logger.debug("Lower rig... | logger.debug("Compute x and y from lon lat")
logger.debug("Longitude : %s"%lon)
logger.debug("Latitude : %s"%lat)
sref = osr.SpatialReference()
sref.ImportFromEPSG(4326)
# create a geometry from coordinates
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(lon, lat)
raster_ds = gdal... | identifier_body |
banner_generator.py | from osgeo import gdal, osr, ogr
import numpy as np
import scipy.misc
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("banner-generator")
def create_raster_from_band( red, green, blue, output_file):
logger.debug("Create big raster in output_file : %s"%output_file)
red_ds = gd... |
if green_clip[0] > green_clip[1] :
logger.error("Maximum clip value should be higther than the Minimum clip value")
return False
def clip_array(band_index, clip):
array = np.array(raster_ds.GetRasterBand(band_index).ReadAsArray())
array = np.clip(array, clip[0], clip[1])
... | logger.error("Maximum clip value should be higther than the Minimum clip value")
return False | conditional_block |
banner_generator.py | from osgeo import gdal, osr, ogr
import numpy as np
import scipy.misc
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("banner-generator")
def create_raster_from_band( red, green, blue, output_file):
logger.debug("Create big raster in output_file : %s"%output_file)
red_ds = gd... | (band_index, clip):
array = np.array(raster_ds.GetRasterBand(band_index).ReadAsArray())
array = np.clip(array, clip[0], clip[1])
array = array - clip[0]
array = (np.float32(array)*bytes_max)/(clip[1]-clip[0])
array = array.astype(int)
return array
logger.debug("P... | clip_array | identifier_name |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { NgModule } from '@angular/core';
import 'hammerjs';
import { AppRoutingModule } from './routing/app-routing.module';
import { AppComponent } from './app.component';
import { LayoutModule } from './layout/la... | { }
| AppModule | identifier_name |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { NgModule } from '@angular/core';
import 'hammerjs';
import { AppRoutingModule } from './routing/app-routing.module';
import { AppComponent } from './app.component';
import { LayoutModule } from './layout/la... | HttpModule,
InMemoryWebApiModule.forRoot(GlobalData, { delay: 1000 }),
LayoutModule,
UserModule,
AppRoutingModule // *** This MUST always be the last import. Or child routes won't work. ***
],
bootstrap: [ AppComponent ]
})
export class AppModule { } | BrowserModule, | random_line_split |
aiplatform_generated_aiplatform_v1beta1_vizier_service_suggest_trials_sync.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
def sample_suggest_trials():
# Create a client
client = aiplatform_v1beta1.VizierServiceClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.SuggestTrialsRequest(
parent="parent_value",
suggestion_count=1744,
client_id="client_id_value",
)
# Make the ... | # [START aiplatform_generated_aiplatform_v1beta1_VizierService_SuggestTrials_sync]
from google.cloud import aiplatform_v1beta1
| random_line_split |
aiplatform_generated_aiplatform_v1beta1_vizier_service_suggest_trials_sync.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
# [END aiplatform_generated_aiplatform_v1beta1_VizierService_SuggestTrials_sync]
| client = aiplatform_v1beta1.VizierServiceClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.SuggestTrialsRequest(
parent="parent_value",
suggestion_count=1744,
client_id="client_id_value",
)
# Make the request
operation = client.suggest_trials(request=re... | identifier_body |
aiplatform_generated_aiplatform_v1beta1_vizier_service_suggest_trials_sync.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | ():
# Create a client
client = aiplatform_v1beta1.VizierServiceClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.SuggestTrialsRequest(
parent="parent_value",
suggestion_count=1744,
client_id="client_id_value",
)
# Make the request
operation = cl... | sample_suggest_trials | identifier_name |
movedex.rs | extern crate csv;
use super::enums;
use super::moves::Technique;
use enum_primitive::FromPrimitive;
use std::collections::HashMap;
/// Manages the list of moves that are available. Contains a bool that is true whenever all
/// available moves are inside the entries to make an easier search possible.
/// By now the ... | move_tmp.clone().unwrap().get_name() == "fling" ||
move_tmp.clone().unwrap().get_name() == "trump-card" ||
move_tmp.clone().unwrap().get_name() == "me-first" ||
move_tmp.clone().unwrap().get_category() == enums::MoveCategory::Unique) ||... | {
let mut new_dex = Vec::new();
let mut move_db = csv::Reader::from_file("./src/db/tables/pokemon_moves.csv").unwrap();
for record in move_db.decode() {
let (poke_id, version, move_id, _, move_level, _): (usize,
u8,
... | identifier_body |
movedex.rs | extern crate csv;
use super::enums;
use super::moves::Technique;
use enum_primitive::FromPrimitive;
use std::collections::HashMap;
/// Manages the list of moves that are available. Contains a bool that is true whenever all
/// available moves are inside the entries to make an easier search possible.
/// By now the ... |
}
Movedex {
entries: moves,
complete: true,
}
}
}
| {
if !(id == last_id) {
moves[last_id - 1].set_flags(flags);
last_id = id;
flags = Vec::new();
}
flags.push(enums::MoveFlags::from_i32(identifier).unwrap());
} | conditional_block |
movedex.rs | extern crate csv;
use super::enums;
use super::moves::Technique;
use enum_primitive::FromPrimitive;
use std::collections::HashMap;
/// Manages the list of moves that are available. Contains a bool that is true whenever all
/// available moves are inside the entries to make an easier search possible.
/// By now the ... | {
entries: Vec<Technique>,
complete: bool,
}
// TODO: last 4 attacks are missing in move_meta.csv, therefore are not implemented right now.
// DB must be extended and if statements adjusted accordingly
impl Movedex {
/// Takes an ID and a movedex and returns an option with the move that can be find with ... | Movedex | identifier_name |
movedex.rs | extern crate csv;
use super::enums;
use super::moves::Technique;
use enum_primitive::FromPrimitive;
use std::collections::HashMap;
/// Manages the list of moves that are available. Contains a bool that is true whenever all
/// available moves are inside the entries to make an easier search possible.
/// By now the ... | }
/// Returns a list of all learnable moves by level for a specific pokemon with a specific
/// level.
pub fn for_token(&self, level: u16, id: usize) -> Movedex {
let mut new_dex = Vec::new();
let mut move_db = csv::Reader::from_file("./src/db/tables/pokemon_moves.csv").unwrap();
... | None | random_line_split |
url.validator.ts | import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
export function urlValidator(control: AbstractControl): ValidationErrors | {
if (Validators.required(control) != null) {
return null;
}
const v: string = control.value;
/* tslint:disable */
return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(... | identifier_body | |
url.validator.ts | import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
export function urlValidator(control: AbstractControl): ValidationErrors {
if (Validators.required(control) != null) {
return null;
} | } |
const v: string = control.value;
/* tslint:disable */
return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.