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 |
|---|---|---|---|---|
visitors.js | import * as virtualTypes from "./path/lib/virtual-types";
import * as messages from "babel-messages";
import * as t from "babel-types";
import clone from "lodash/clone";
/**
* explode() will take a visitor object with all of the various shorthands
* that we support, and validates & normalizes it into a common format... | }
function ensureEntranceObjects(obj) {
for (let key in obj) {
if (shouldIgnoreKey(key)) continue;
let fns = obj[key];
if (typeof fns === "function") {
obj[key] = { enter: fns };
}
}
}
function ensureCallbackArrays(obj) {
if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]... | random_line_split | |
visitors.js | import * as virtualTypes from "./path/lib/virtual-types";
import * as messages from "babel-messages";
import * as t from "babel-types";
import clone from "lodash/clone";
/**
* explode() will take a visitor object with all of the various shorthands
* that we support, and validates & normalizes it into a common format... | (dest, src) {
for (let key in src) {
dest[key] = [].concat(dest[key] || [], src[key]);
}
}
| mergePair | identifier_name |
unused-attr.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 ... |
}
}
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
| {} | conditional_block |
unused-attr.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 ... |
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
| {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
} | identifier_body |
unused-attr.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 ... | {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
| Foo | identifier_name |
unused-attr.rs | // Copyright 2014 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![deny(unused_attr... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
__init__.py | #
# Copyright (c) 2005
# The President and Fellows of Harvard College.
#
# 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... | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT... | # ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE | random_line_split |
MediaManager.ts | ///<reference path='refs.ts'/>
module TDev.RT.WinRT {
export function MediaManagerInit() {
MediaManagerWinRT.init();
}
export module MediaManagerWinRT
{
var _url: string;
export function init()
|
function sourceRequested(e : Windows.Media.PlayTo.PlayToSourceRequestedEventArgs) {
if (_url) {
if (Windows.Media.PlayTo.PlayToManager) {
var playToManager = Windows.Media.PlayTo.PlayToManager.getForCurrentView();
playToManager.onsourcereques... | {
if (Browser.isGenStubs) return;
if (Windows.Media.PlayTo.PlayToManager) {
var playToManager = Windows.Media.PlayTo.PlayToManager.getForCurrentView();
playToManager.defaultSourceSelection = false;
playToManager.onsourcerequested = null;
... | identifier_body |
MediaManager.ts | ///<reference path='refs.ts'/>
module TDev.RT.WinRT {
export function MediaManagerInit() {
MediaManagerWinRT.init();
}
export module MediaManagerWinRT
{
var _url: string;
export function | ()
{
if (Browser.isGenStubs) return;
if (Windows.Media.PlayTo.PlayToManager) {
var playToManager = Windows.Media.PlayTo.PlayToManager.getForCurrentView();
playToManager.defaultSourceSelection = false;
playToManager.onsourcerequested = null;... | init | identifier_name |
MediaManager.ts | ///<reference path='refs.ts'/>
module TDev.RT.WinRT {
export function MediaManagerInit() {
MediaManagerWinRT.init();
}
export module MediaManagerWinRT
{
var _url: string;
export function init()
{
if (Browser.isGenStubs) return;
if (Windows.Media.... |
}
}
}
| {
var playToManager = Windows.Media.PlayTo.PlayToManager.getForCurrentView();
playToManager.onsourcerequested = sourceRequested;
(<any>playToManager).showPlayToUI();
} | conditional_block |
MediaManager.ts | ///<reference path='refs.ts'/>
module TDev.RT.WinRT {
export function MediaManagerInit() {
MediaManagerWinRT.init();
}
export module MediaManagerWinRT
{
var _url: string;
export function init()
{
if (Browser.isGenStubs) return;
if (Windows.Media.... | _url = null;
e.sourceRequest.setSource((<any>video).msPlayToSource);
} catch (ex) {
Time.log(ex.message);
}
}
}
export function playMedia(url: string)
{
_url = url;
i... | }
try {
var video = <HTMLVideoElement>elt("video");
video.src = _url; | random_line_split |
barbican-keystone-listener.py | #!/usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 ... |
from barbican.common import config
from barbican.openstack.common import log
from barbican.openstack.common import service
from barbican import queue
from barbican.queue import keystone_listener
from oslo_config import cfg
def fail(returncode, e):
sys.stderr.write("ERROR: {0}\n".format(e))
sys.exit(returnc... | sys.path.insert(0, possible_topdir) | conditional_block |
barbican-keystone-listener.py | #!/usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 ... | (returncode, e):
sys.stderr.write("ERROR: {0}\n".format(e))
sys.exit(returncode)
if __name__ == '__main__':
try:
config.parse_args()
config.setup_remote_pydev_debug()
# Import and configure logging.
log.setup('barbican')
LOG = log.getLogger(__name__)
LOG.in... | fail | identifier_name |
barbican-keystone-listener.py | #!/usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 | # implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Barbican Keystone notification listener server.
"""
import eventlet
import os
import sys
# Oslo messaging notification server uses eventlet.
#
# To have remote debugging, thread module needs to be di... | #
# 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 | random_line_split |
barbican-keystone-listener.py | #!/usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 ... |
if __name__ == '__main__':
try:
config.parse_args()
config.setup_remote_pydev_debug()
# Import and configure logging.
log.setup('barbican')
LOG = log.getLogger(__name__)
LOG.info("Booting up Barbican Keystone listener node...")
# Queuing initialization
... | sys.stderr.write("ERROR: {0}\n".format(e))
sys.exit(returncode) | identifier_body |
collection.js | /* eslint-env mocha */
import { setup, teardown } from "./helpers"
describe("Collection page", () => {
let metaphysics, browser
before(async () => {
;({ metaphysics, browser } = await setup())
metaphysics.post("/", (req, res) => {
res.send(require("./fixtures/metaphysics/collection"))
})
}) | const $ = await browser.page("/collection/kaws-companions")
$.html().should.containEql("KAWS: Companions")
$.html().should.containEql("Collectible Sculptures")
$.html().should.containEql("Brian Donnelly, better known as KAWS")
})
it("renders artwork grid", async () => {
const $ = await browser.... |
after(teardown)
it("renders a title and header info", async () => { | random_line_split |
webgl_conformance_test.py | # Copyright (c) 2012 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.
import os
import sys
import json
from telemetry.page import page_set
from telemetry.page import page_test
from telemetry.core import util
src_path = os.... |
def CustomizeBrowserOptions(self, options):
options.AppendExtraBrowserArg('--enable-webgl')
@staticmethod
def _ParseTests(path, version = None):
test_paths = []
current_dir = os.path.dirname(path)
full_path = os.path.normpath(os.path.join(conformance_path, path))
if not os.path.exists(full... | if _DidWebGLTestSucceed(tab):
results.AddSuccess(page)
else:
results.AddFailureMessage(page, _WebGLTestMessages(tab)) | identifier_body |
webgl_conformance_test.py | # Copyright (c) 2012 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.
import os
import sys
import json
from telemetry.page import page_set
from telemetry.page import page_test
from telemetry.core import util
src_path = os.... | else:
results.AddFailureMessage(page, _WebGLTestMessages(tab))
def CustomizeBrowserOptions(self, options):
options.AppendExtraBrowserArg('--enable-webgl')
@staticmethod
def _ParseTests(path, version = None):
test_paths = []
current_dir = os.path.dirname(path)
full_path = os.path.normpa... | def ValidatePage(self, page, tab, results):
if _DidWebGLTestSucceed(tab):
results.AddSuccess(page) | random_line_split |
webgl_conformance_test.py | # Copyright (c) 2012 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.
import os
import sys
import json
from telemetry.page import page_set
from telemetry.page import page_test
from telemetry.core import util
src_path = os.... |
def CustomizeBrowserOptions(self, options):
options.AppendExtraBrowserArg('--enable-webgl')
@staticmethod
def _ParseTests(path, version = None):
test_paths = []
current_dir = os.path.dirname(path)
full_path = os.path.normpath(os.path.join(conformance_path, path))
if not os.path.exists(full... | results.AddFailureMessage(page, _WebGLTestMessages(tab)) | conditional_block |
webgl_conformance_test.py | # Copyright (c) 2012 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.
import os
import sys
import json
from telemetry.page import page_set
from telemetry.page import page_test
from telemetry.core import util
src_path = os.... | (tab):
return tab.EvaluateJavaScript('webglTestHarness._allTestSucceeded')
def _WebGLTestMessages(tab):
return tab.EvaluateJavaScript('webglTestHarness._messages')
class WebGLConformanceTest(page_test.PageTest):
def __init__(self):
super(WebGLConformanceTest, self).__init__('ValidatePage')
def CreatePage... | _DidWebGLTestSucceed | identifier_name |
Grid.js | /**
* @jsx React.DOM
* @copyright Prometheus Research, LLC 2014
*/
"use strict";
var React = require('react/addons');
var PropTypes = React.PropTypes;
var Header = require('./Header');
var Viewport = require('./Viewport');
var ColumnMetrics = require('./Col... | ,
componentDidUpdate() {
this._onScroll();
},
componentWillMount() {
this._scrollLeft = undefined;
},
componentWillUnmount() {
this._scrollLeft = undefined;
},
onScroll({scrollLeft}) {
if (this._scrollLeft !== scrollLeft) {
this._scrollLeft = scrollLeft;
this._onScroll();
... | {
this._scrollLeft = this.refs.viewport.getScroll().scrollLeft;
this._onScroll();
} | identifier_body |
Grid.js | /**
* @jsx React.DOM
* @copyright Prometheus Research, LLC 2014
*/
"use strict";
var React = require('react/addons');
var PropTypes = React.PropTypes;
var Header = require('./Header');
var Viewport = require('./Viewport');
var ColumnMetrics = require('./Col... | () {
this._scrollLeft = undefined;
},
componentWillUnmount() {
this._scrollLeft = undefined;
},
onScroll({scrollLeft}) {
if (this._scrollLeft !== scrollLeft) {
this._scrollLeft = scrollLeft;
this._onScroll();
}
},
_onScroll() {
if (this._scrollLeft !== undefined) {
t... | componentWillMount | identifier_name |
Grid.js | /**
* @jsx React.DOM
* @copyright Prometheus Research, LLC 2014
*/
"use strict";
var React = require('react/addons');
var PropTypes = React.PropTypes;
var Header = require('./Header');
var Viewport = require('./Viewport');
var ColumnMetrics = require('./Col... |
},
_onScroll() {
if (this._scrollLeft !== undefined) {
this.refs.header.setScrollLeft(this._scrollLeft);
this.refs.viewport.setScrollLeft(this._scrollLeft);
}
}
};
var Grid = React.createClass({
mixins: [
GridScrollMixin,
ColumnMetrics.Mixin,
DOMMetrics.MetricsComputatorMixin
... | {
this._scrollLeft = scrollLeft;
this._onScroll();
} | conditional_block |
Grid.js | /**
* @jsx React.DOM
* @copyright Prometheus Research, LLC 2014
*/
"use strict";
var React = require('react/addons');
var PropTypes = React.PropTypes;
var Header = require('./Header');
var Viewport = require('./Viewport');
var ColumnMetrics = require('./Col... | getStyle: function(){
return{
overflowX: 'scroll',
overflowY: 'hidden',
outline: 0,
position: 'relative',
minHeight: this.props.minHeight
}
},
render() {
var headerRows = this.props.headerRows || [{ref : 'row'}];
return (
<div {...this.props} style={this.getSty... | rows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
columns: PropTypes.array.isRequired
},
| random_line_split |
fancyclick.js | (function ($, window, document, undefined) {
'use strict';
var settings = {
container: '.main',
animationMethod: 'replace',
duration: 1000,
preload: false,
anchors: 'a',
blacklist: '.no-fancyclick',
whitelist: '',
onLoadStart: function () {
... |
return false;
}
function attachLoader() {
var links = $('a');
$.each(links, function (key, element) {
var $element = $(element);
if (!isExternal($element.attr('href'))) {
$element.click(loadPage);
}
});
}
function lo... | {
return true;
} | conditional_block |
fancyclick.js | (function ($, window, document, undefined) {
'use strict';
var settings = {
container: '.main',
animationMethod: 'replace',
duration: 1000,
preload: false,
anchors: 'a',
blacklist: '.no-fancyclick',
whitelist: '',
onLoadStart: function () {
... | (url) {
var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
if (typeof match[1] === 'string' && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) {
return true;
}
if (typeof match[2] === 'string' && match[2].length > 0 && ma... | isExternal | identifier_name |
fancyclick.js | (function ($, window, document, undefined) {
'use strict';
var settings = {
container: '.main',
animationMethod: 'replace',
duration: 1000,
preload: false,
anchors: 'a',
blacklist: '.no-fancyclick',
whitelist: '',
onLoadStart: function () {
... |
/**
* Update the title of the page
* @param title
*/
function updateTitle(title) {
$('title').text(title);
}
/**
* Get the computed animation duration for an element
*/
function getComputedAnimationDuration() {
var element = $('<div>')
.css('vi... | {
e.preventDefault();
var durationFn = getComputedAnimationDuration();
var duration = durationFn() || settings.duration;
var href = e.currentTarget.href || window.location.href;
var element = $(settings.container);
// fire loading start callback
settings.onLoadSt... | identifier_body |
fancyclick.js | (function ($, window, document, undefined) {
'use strict';
var settings = {
container: '.main',
animationMethod: 'replace',
duration: 1000,
preload: false,
anchors: 'a',
blacklist: '.no-fancyclick',
whitelist: '',
onLoadStart: function () {
... | var links = $('a');
$.each(links, function (key, element) {
var $element = $(element);
if (!isExternal($element.attr('href'))) {
$element.click(loadPage);
}
});
}
function loadPage(e, changeBack) {
e.preventDefault();
... | random_line_split | |
use-from-trait-xc.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 ... |
fn main() {
} |
use use_from_trait_xc::Trait::foo; //~ ERROR cannot import from a trait or type implementation
//~^ ERROR failed to resolve import
use use_from_trait_xc::Foo::new; //~ ERROR cannot import from a trait or type implementation
//~^ ERROR failed to resolve import | random_line_split |
use-from-trait-xc.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 ... | {
} | identifier_body | |
use-from-trait-xc.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 ... | () {
}
| main | identifier_name |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct LayoutCo... | }
impl LayoutCollection {
pub fn new(layouts: Vec<Box<Layout>>) -> Box<Layout> {
Box::new(LayoutCollection {
layouts: layouts,
current: 0
})
}
}
impl Layout for LayoutCollection {
fn apply_layout(&mut self, window_system: &WindowSystem, screen: Rectangle, config: &G... | pub current: usize | random_line_split |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct | {
pub layouts: Vec<Box<Layout>>,
pub current: usize
}
impl LayoutCollection {
pub fn new(layouts: Vec<Box<Layout>>) -> Box<Layout> {
Box::new(LayoutCollection {
layouts: layouts,
current: 0
})
}
}
impl Layout for LayoutCollection {
fn apply_layout(&mut self... | LayoutCollection | identifier_name |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct LayoutCo... |
_ => self.layouts[self.current].apply_message(message, window_system, stack,
config)
}
}
fn description(&self) -> String {
self.layouts[self.current].description()
}
fn copy(&self) -> Box<Layout> {
Box::new(LayoutCollection {
current:... | {
self.layouts[self.current].unhook(window_system, stack, config);
self.current = (self.current + (self.layouts.len() - 1)) % self.layouts.len();
true
} | conditional_block |
conversions_tests.rs | use std::convert::TryInto;
use hashing;
use crate::gen::build::bazel::remote::execution::v2 as remexec;
#[test]
fn from_our_digest() {
let our_digest = &hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
... | let bazel_digest = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let want = hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"012... | random_line_split | |
conversions_tests.rs | use std::convert::TryInto;
use hashing;
use crate::gen::build::bazel::remote::execution::v2 as remexec;
#[test]
fn from_our_digest() |
#[test]
fn from_bazel_digest() {
let bazel_digest = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let want = hashing::Digest::new(
hashing::Finge... | {
let our_digest = &hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
10,
);
let converted: remexec::Digest = our_digest.into();
let want = remexec::Digest {
hash: "0123456789abcdeffedcba9876543... | identifier_body |
conversions_tests.rs | use std::convert::TryInto;
use hashing;
use crate::gen::build::bazel::remote::execution::v2 as remexec;
#[test]
fn from_our_digest() {
let our_digest = &hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
... | () {
let bazel_digest = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let want = hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
... | from_bazel_digest | identifier_name |
siphash24.rs | //! `SipHash-2-4`
use ffi;
use libc::c_ulonglong;
use randombytes::randombytes_into;
pub const HASHBYTES: usize = ffi::crypto_shorthash_siphash24_BYTES;
pub const KEYBYTES: usize = ffi::crypto_shorthash_siphash24_KEYBYTES;
/// Digest-structure
#[derive(Copy)]
pub struct Digest(pub [u8; HASHBYTES]);
newtype_clone!(Di... | (b: &mut test::Bencher) {
let k = gen_key();
let ms: Vec<Vec<u8>> = BENCH_SIZES.iter().map(|s| {
randombytes(*s)
}).collect();
b.iter(|| {
for m in ms.iter() {
shorthash(m, &k);
}
});
}
}
| bench_shorthash | identifier_name |
siphash24.rs | //! `SipHash-2-4`
use ffi;
use libc::c_ulonglong;
use randombytes::randombytes_into;
pub const HASHBYTES: usize = ffi::crypto_shorthash_siphash24_BYTES;
pub const KEYBYTES: usize = ffi::crypto_shorthash_siphash24_KEYBYTES;
/// Digest-structure
#[derive(Copy)]
pub struct Digest(pub [u8; HASHBYTES]);
newtype_clone!(Di... | ,[0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f]
,[0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24]
,[0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7]
,[0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea]
... | ,[0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee]
,[0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1]
,[0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a]
,[0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81] | random_line_split |
siphash24.rs | //! `SipHash-2-4`
use ffi;
use libc::c_ulonglong;
use randombytes::randombytes_into;
pub const HASHBYTES: usize = ffi::crypto_shorthash_siphash24_BYTES;
pub const KEYBYTES: usize = ffi::crypto_shorthash_siphash24_KEYBYTES;
/// Digest-structure
#[derive(Copy)]
pub struct Digest(pub [u8; HASHBYTES]);
newtype_clone!(Di... |
}
| {
let k = gen_key();
let ms: Vec<Vec<u8>> = BENCH_SIZES.iter().map(|s| {
randombytes(*s)
}).collect();
b.iter(|| {
for m in ms.iter() {
shorthash(m, &k);
}
});
} | identifier_body |
high_lows.py | import csv
from datetime import datetime
from matplotlib import pyplot as plt
# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_2017.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates, highs, lows = [], [], []
for row in reader:
|
# Plot data.
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red', alpha=0.5)
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# Format plot.
plt.title("Daily high and low temperatures - 2017", fontsize=24)
plt.xlabel('', fontsize=16)
... | current_date = datetime.strptime(row[0], "%Y-%m-%d")
dates.append(current_date)
high = int(row[1])
highs.append(high)
low = int(row[3])
lows.append(low) | conditional_block |
high_lows.py | import csv
from datetime import datetime
from matplotlib import pyplot as plt
# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_2017.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader) |
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[0], "%Y-%m-%d")
dates.append(current_date)
high = int(row[1])
highs.append(high)
low = int(row[3])
lows.append(low)
# Plot data.
fig = plt.figure(dpi=128, figsize=(10, 6))
... | random_line_split | |
devstack.py | """
Specific overrides to the base prod settings to make development easier.
"""
from os.path import abspath, dirname, join
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
... |
########################### PIPELINE #################################
# Skip packaging and optimization in development
PIPELINE_ENABLED = False
STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'
# Revert to the default set of finders as we don't want the production pipeline
STATICFILES_FINDERS =... | return True # We always want the toolbar on devstack regardless of IP, auth, etc. | identifier_body |
devstack.py | """
Specific overrides to the base prod settings to make development easier.
"""
from os.path import abspath, dirname, join
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
... | (_):
return True # We always want the toolbar on devstack regardless of IP, auth, etc.
########################### PIPELINE #################################
# Skip packaging and optimization in development
PIPELINE_ENABLED = False
STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'
# Revert t... | should_show_debug_toolbar | identifier_name |
devstack.py | """
Specific overrides to the base prod settings to make development easier.
"""
from os.path import abspath, dirname, join
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
... | #####################################################################
# See if the developer has any local overrides.
if os.path.isfile(join(dirname(abspath(__file__)), 'private.py')):
from .private import * # pylint: disable=import-error,wildcard-import
###########################################################... | random_line_split | |
devstack.py | """
Specific overrides to the base prod settings to make development easier.
"""
from os.path import abspath, dirname, join
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
... |
################################ EMAIL ########################################
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
FEATURES['ENABLE_INSTRUCTOR_EMAIL'] = True # Enable email for all Studio courses
FEATURES['REQUIRE_COURSE_EMAIL_AUTH'] = False # Give all courses email (don't require... | logging.getLogger(log_name).setLevel(log_level) | conditional_block |
rust.js | // Copyright (c) 2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of con... |
getSharedLibraryPathsAsArguments() {
return [];
}
optionsForFilter(filters, outputFilename, userOptions) {
let options = ['-C', 'debuginfo=1', '-o', this.filename(outputFilename)];
let userRequestedEmit = _.any(userOptions, opt => opt.indexOf("--emit") > -1);
//TODO: Bina... | {
super(info, env);
this.compiler.supportsIntel = true;
this.compiler.supportsIrView = true;
this.compiler.irArg = ['--emit', 'llvm-ir'];
} | identifier_body |
rust.js | // Copyright (c) 2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of con... | (inputFilename) {
return this.getOutputFilename(path.dirname(inputFilename), this.outputFilebase)
.replace('.s', '.ll');
}
getArgumentParser() {
return argumentParsers.Rust;
}
isCfgCompiler(/*compilerVersion*/) {
return true;
}
}
module.exports = RustCompiler;
| getIrOutputFilename | identifier_name |
rust.js | // Copyright (c) 2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of con... | argumentParsers = require("./argument-parsers");
class RustCompiler extends BaseCompiler {
constructor(info, env) {
super(info, env);
this.compiler.supportsIntel = true;
this.compiler.supportsIrView = true;
this.compiler.irArg = ['--emit', 'llvm-ir'];
}
getSharedLibrary... | random_line_split | |
rust.js | // Copyright (c) 2016, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of con... |
if (filters.intel) options = options.concat('-Cllvm-args=--x86-asm-syntax=intel');
}
options = options.concat(['--crate-type', 'rlib']);
return options;
}
// Override the IR file name method for rustc because the output file is different from clang.
getIrOutputFilename(... | {
options = options.concat('--emit', 'asm');
} | conditional_block |
u32.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 ... | } | } | random_line_split |
u32.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 ... |
/// Counts the number of leading zeros. Wraps LLVM's `ctlp` intrinsic.
#[inline(always)]
fn leading_zeros(&self) -> u32 { unsafe { intrinsics::ctlz32(*self as i32) as u32 } }
/// Counts the number of trailing zeros. Wraps LLVM's `cttp` intrinsic.
#[inline(always)]
fn t... | { unsafe { intrinsics::ctpop32(*self as i32) as u32 } } | identifier_body |
u32.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 ... | (&self) -> u32 { unsafe { intrinsics::cttz32(*self as i32) as u32 } }
}
}
| trailing_zeros | identifier_name |
mod.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
mod process;
mod vcpu;
use std::fs::File;
use std::io;
use std::io::Read;
use std::os::unix::net::UnixDatagram;
use std::path::Path;
use std::sync::at... |
fn create_plugin_jail(root: &Path, log_failures: bool, seccomp_policy: &Path) -> Result<Minijail> {
// All child jails run in a new user namespace without any users mapped,
// they run as nobody unless otherwise configured.
let mut j = Minijail::new().context("failed to create jail")?;
j.namespace_pid... | {
match e {
MmapError::SystemCallFailed(e) => e,
_ => SysError::new(EINVAL),
}
} | identifier_body |
mod.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
mod process;
mod vcpu;
use std::fs::File;
use std::io;
use std::io::Read;
use std::os::unix::net::UnixDatagram;
use std::path::Path;
use std::sync::at... |
let res = vcpu_plugin.init(&vcpu);
vcpu_thread_barrier.wait();
if let Err(e) = res {
error!("failed to initialize vcpu {}: {}", cpu_id, e);
} else {
loop {
let mut... | .expect("Failed to set thread id"); | random_line_split |
mod.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
mod process;
mod vcpu;
use std::fs::File;
use std::io;
use std::io::Read;
use std::os::unix::net::UnixDatagram;
use std::path::Path;
use std::sync::at... | {
IoEvent {
evt: Event,
addr: IoeventAddress,
length: u32,
datamatch: u64,
},
Memory {
slot: u32,
length: usize,
},
IrqEvent {
irq_id: u32,
evt: Event,
},
}
impl PluginObject {
fn destroy(self, vm: &mut Vm) -> SysResult<()> {
... | PluginObject | identifier_name |
reducer_posts.js | import fuzzy from 'fuzzy';
import { resolve } from 'redux-simple-promise';
import {
FETCH_POSTS,
FETCH_POST,
FETCH_PAGE,
FETCH_POSTS_CATEGORY,
FETCH_POSTS_TAG
} from '../actions/index';
const INITIAL_STATE = { all: {}, post: {}, page: {}, category: {} };
export default function (state = INITIAL_STATE, acti... | (el) {
return `${el.title} ${el.tags.map((tag) => `${tag} `)} `;
}
};
const results = fuzzy.filter(action.meta.term, data, options);
results.map((el) => {
if (el.score > 6) {
payload.push(el.original);
}
});
return { ...state,... | extract | identifier_name |
reducer_posts.js | import fuzzy from 'fuzzy';
import { resolve } from 'redux-simple-promise';
import {
FETCH_POSTS,
FETCH_POST,
FETCH_PAGE,
FETCH_POSTS_CATEGORY,
FETCH_POSTS_TAG
} from '../actions/index';
const INITIAL_STATE = { all: {}, post: {}, page: {}, category: {} };
export default function (state = INITIAL_STATE, acti... |
};
const results = fuzzy.filter(action.meta.term, data, options);
results.map((el) => {
if (el.score > 6) {
payload.push(el.original);
}
});
return { ...state, all: payload };
}
data.map((el) => {
if (el.meta.type === 'post') ... | {
return `${el.title} ${el.tags.map((tag) => `${tag} `)} `;
} | identifier_body |
reducer_posts.js | import fuzzy from 'fuzzy';
import { resolve } from 'redux-simple-promise';
import {
FETCH_POSTS,
FETCH_POST,
FETCH_PAGE,
FETCH_POSTS_CATEGORY,
FETCH_POSTS_TAG
} from '../actions/index';
const INITIAL_STATE = { all: {}, post: {}, page: {}, category: {} }; | export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case resolve(FETCH_POSTS): {
const data = action.payload.data.entries;
const payload = [];
if (typeof action.meta.term !== 'undefined') {
const options = {
pre: '',
post: '',
e... | random_line_split | |
reducer_posts.js | import fuzzy from 'fuzzy';
import { resolve } from 'redux-simple-promise';
import {
FETCH_POSTS,
FETCH_POST,
FETCH_PAGE,
FETCH_POSTS_CATEGORY,
FETCH_POSTS_TAG
} from '../actions/index';
const INITIAL_STATE = { all: {}, post: {}, page: {}, category: {} };
export default function (state = INITIAL_STATE, acti... |
});
return { ...state, post: payload };
}
case resolve(FETCH_PAGE): {
const data = action.payload.data;
return { ...state, page: data };
}
default:
return state;
}
}
| {
payload = el;
} | conditional_block |
spoilers.py | """Spoilers cog
Filters out messages that start with a certain prefix, and store them for
later retrieval.
"""
from datetime import datetime, timedelta
import logging
import json
import os
import re
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils impo... | if match:
store[KEY_EMBED] = match.group(0)
await self.bot.delete_message(ctx.message)
newMsg = await self.bot.say(":warning: {} created a spoiler! React to see "
"the message!".format(ctx.message.author.mention))
... | store[KEY_EMBED] = data.url
else:
imglinkPattern = r"(?i)http[^ ]+\.(?:png|jpg|jpeg|gif)"
match = re.search(imglinkPattern, msg)
| random_line_split |
spoilers.py | """Spoilers cog
Filters out messages that start with a certain prefix, and store them for
later retrieval.
"""
from datetime import datetime, timedelta
import logging
import json
import os
import re
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils impo... |
def setup(bot):
"""Add the cog to the bot."""
checkFolder() # Make sure the data folder exists!
checkFiles() # Make sure we have settings!
spoilersCog = Spoilers(bot)
global LOGGER # pylint: disable=global-statement
LOGGER = logging.getLogger("red.Spoilers")
if LOGGER.level =... | """Reaction listener (using socket data)
Checks to see if a spoilered message is reacted, and if so, send a DM to the
user that reacted.
"""
# no binary frames
if isinstance(data, bytes):
return
data = json.loads(data)
event = data.get("t")
... | identifier_body |
spoilers.py | """Spoilers cog
Filters out messages that start with a certain prefix, and store them for
later retrieval.
"""
from datetime import datetime, timedelta
import logging
import json
import os
import re
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils impo... | (self, data):
"""Reaction listener (using socket data)
Checks to see if a spoilered message is reacted, and if so, send a DM to the
user that reacted.
"""
# no binary frames
if isinstance(data, bytes):
return
data = json.loads(data)
... | checkForReaction | identifier_name |
spoilers.py | """Spoilers cog
Filters out messages that start with a certain prefix, and store them for
later retrieval.
"""
from datetime import datetime, timedelta
import logging
import json
import os
import re
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils impo... |
await self.bot.delete_message(ctx.message)
newMsg = await self.bot.say(":warning: {} created a spoiler! React to see "
"the message!".format(ctx.message.author.mention))
if not self.messages:
self.messages = {}
... | imglinkPattern = r"(?i)http[^ ]+\.(?:png|jpg|jpeg|gif)"
match = re.search(imglinkPattern, msg)
if match:
store[KEY_EMBED] = match.group(0) | conditional_block |
setup.py | #!/usr/bin/env python
import re
import os
import time
import sys
import unittest
import ConfigParser
from setuptools import setup, Command
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
class SQLiteTest(Command):
"""
Run the tests on SQLite
"""
description = ... | pass
def finalize_options(self):
pass
def run(self):
if self.distribution.tests_require:
self.distribution.fetch_build_eggs(self.distribution.tests_require)
os.environ['TRYTOND_DATABASE_URI'] = 'sqlite://'
os.environ['DB_NAME'] = ':memory:'
from te... |
user_options = []
def initialize_options(self): | random_line_split |
setup.py | #!/usr/bin/env python
import re
import os
import time
import sys
import unittest
import ConfigParser
from setuptools import setup, Command
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
class SQLiteTest(Command):
"""
Run the tests on SQLite
"""
description = ... |
sys.exit(-1)
config = ConfigParser.ConfigParser()
config.readfp(open('tryton.cfg'))
info = dict(config.items('tryton'))
for key in ('depends', 'extras_depend', 'xml'):
if key in info:
info[key] = info[key].strip().splitlines()
major_version, minor_version, _ = info.get('version', '0.0.1').split('... | sys.exit(0) | conditional_block |
setup.py | #!/usr/bin/env python
import re
import os
import time
import sys
import unittest
import ConfigParser
from setuptools import setup, Command
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
class | (Command):
"""
Run the tests on SQLite
"""
description = "Run tests on SQLite"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
if self.distribution.tests_require:
self.distribution.fetch_build_eg... | SQLiteTest | identifier_name |
setup.py | #!/usr/bin/env python
import re
import os
import time
import sys
import unittest
import ConfigParser
from setuptools import setup, Command
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
class SQLiteTest(Command):
"""
Run the tests on SQLite
"""
description = ... |
config = ConfigParser.ConfigParser()
config.readfp(open('tryton.cfg'))
info = dict(config.items('tryton'))
for key in ('depends', 'extras_depend', 'xml'):
if key in info:
info[key] = info[key].strip().splitlines()
major_version, minor_version, _ = info.get('version', '0.0.1').split('.', 2)
major_version ... | if self.distribution.tests_require:
self.distribution.fetch_build_eggs(self.distribution.tests_require)
os.environ['TRYTOND_DATABASE_URI'] = 'postgresql://'
os.environ['DB_NAME'] = 'test_' + str(int(time.time()))
from tests import suite
test_result = unittest.TextTestRunner... | identifier_body |
reducer.ts | import { Reducer } from 'redux';
import { ActionType, getType } from 'typesafe-actions';
import * as actions from './basic-actions';
export interface FarmingState {
// The actively farming store, if any
readonly storeId?: string;
// A counter for pending tasks that interrupt farming
readonly numInterruptions: ... | }
}; | numInterruptions: state.numInterruptions - 1,
};
default:
return state; | random_line_split |
conversion_from_glib.rs | use super::parameter_ffi_call_out;
use crate::{
analysis::{self, try_from_glib::TryFromGlib},
library,
};
#[derive(Clone, Debug)]
pub struct Mode {
pub typ: library::TypeId,
pub transfer: library::Transfer,
pub is_uninitialized: bool,
pub try_from_glib: TryFromGlib,
}
impl From<¶meter_ffi_... | is_uninitialized: orig.is_uninitialized,
try_from_glib: orig.try_from_glib.clone(),
}
}
}
impl From<&analysis::Parameter> for Mode {
fn from(orig: &analysis::Parameter) -> Mode {
Mode {
typ: orig.lib_par.typ,
transfer: orig.lib_par.transfer,
... | random_line_split | |
conversion_from_glib.rs | use super::parameter_ffi_call_out;
use crate::{
analysis::{self, try_from_glib::TryFromGlib},
library,
};
#[derive(Clone, Debug)]
pub struct | {
pub typ: library::TypeId,
pub transfer: library::Transfer,
pub is_uninitialized: bool,
pub try_from_glib: TryFromGlib,
}
impl From<¶meter_ffi_call_out::Parameter> for Mode {
fn from(orig: ¶meter_ffi_call_out::Parameter) -> Mode {
Mode {
typ: orig.typ,
tran... | Mode | identifier_name |
conversion_from_glib.rs | use super::parameter_ffi_call_out;
use crate::{
analysis::{self, try_from_glib::TryFromGlib},
library,
};
#[derive(Clone, Debug)]
pub struct Mode {
pub typ: library::TypeId,
pub transfer: library::Transfer,
pub is_uninitialized: bool,
pub try_from_glib: TryFromGlib,
}
impl From<¶meter_ffi_... |
}
impl From<&analysis::Parameter> for Mode {
fn from(orig: &analysis::Parameter) -> Mode {
Mode {
typ: orig.lib_par.typ,
transfer: orig.lib_par.transfer,
is_uninitialized: false,
try_from_glib: orig.try_from_glib.clone(),
}
}
}
| {
Mode {
typ: orig.typ,
transfer: orig.transfer,
is_uninitialized: orig.is_uninitialized,
try_from_glib: orig.try_from_glib.clone(),
}
} | identifier_body |
payrolls.reducer.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* 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 agr... | {
switch (action.type) {
case payroll.LOAD_ALL_COLLECTIONS: {
return initialState;
}
case payroll.LOAD_ALL_COLLECTIONS_COMPLETE: {
const payrolls: PayrollCollectionHistory[] = action.payload;
const ids = payrolls.map(payroll => payroll.identifier);
const entities = resourcesTo... | identifier_body | |
payrolls.reducer.ts | /**
* Copyright 2017 The Mifos Initiative.
* | *
* http://www.apache.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 governi... | * 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 | random_line_split |
payrolls.reducer.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* 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 agr... | (state = initialState, action: payroll.Actions): ResourceState {
switch (action.type) {
case payroll.LOAD_ALL_COLLECTIONS: {
return initialState;
}
case payroll.LOAD_ALL_COLLECTIONS_COMPLETE: {
const payrolls: PayrollCollectionHistory[] = action.payload;
const ids = payrolls.map(payr... | reducer | identifier_name |
managers.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.contrib.auth.models import BaseU... | __all__ = ('UserManager', )
class UserManager(BaseUserManager):
"""Pootle User manager.
This manager hides the 'nobody' and 'default' users for normal
queries, since they are special users. Code that needs access to these
users should use the methods get_default_user and get_nobody_user.
"""
... | random_line_split | |
managers.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.contrib.auth.models import BaseU... |
@lru_cache()
def get_nobody_user(self):
return self.get_queryset().get(username='nobody')
@lru_cache()
def get_system_user(self):
return self.get_queryset().get(username='system')
def hide_permission_users(self):
return self.get_queryset().exclude(username__in=self.PERMIS... | return self.get_queryset().get(username='default') | identifier_body |
managers.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.contrib.auth.models import BaseU... | (BaseUserManager):
"""Pootle User manager.
This manager hides the 'nobody' and 'default' users for normal
queries, since they are special users. Code that needs access to these
users should use the methods get_default_user and get_nobody_user.
"""
PERMISSION_USERS = ('default', 'nobody')
M... | UserManager | identifier_name |
managers.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.contrib.auth.models import BaseU... |
user_filter = Q(
permissionset__positive_permissions__codename=permission_code
)
language_path = language.directory.pootle_path
project_path = project.directory.pootle_path
user_filter &= (
Q(permissionset__directory__pootle_path=directory.pootle_path)... | return self.hide_meta().filter(is_active=True) | conditional_block |
social-windows-outline.js | import React from 'react'
import Icon from 'react-icon-base' | <g><path d="m33.8 22h-16.9v11.6l16.9 2.5v-14.1z m1.2-1.3v16.8l-19.4-2.8v-14h19.4z m-21.9 1.3h-11.8v9.3l11.8 1.7v-11z m1.3-1.3v13.8l-14.4-2.1v-11.7h14.4z m19.4-16.8l-16.9 2.4v11.9h16.9v-14.3z m1.2-1.4v17h-19.4v-14.3z m-21.9 4.4l-11.8 1.7v9.6h11.8v-11.3z m1.3-1.4v14h-14.4v-12z"/></g>
</Icon>
)
export default... |
const IoSocialWindowsOutline = props => (
<Icon viewBox="0 0 40 40" {...props}> | random_line_split |
AbinsCalculateDWSingleCrystalTest.py | from __future__ import (absolute_import, division, print_function)
import unittest
from mantid.simpleapi import *
import numpy as np
import json
from AbinsModules import CalculateDWSingleCrystal, LoadCASTEP, AbinsTestHelpers
class AbinsCalculateDWSingleCrystalTest(unittest.TestCase):
temperature = 10 # 10 K
... |
# helper functions
def _good_case(self, name=None):
# calculation of DW
good_data = self._get_good_data(filename=name)
good_tester = CalculateDWSingleCrystal(temperature=self.temperature, abins_data=good_data["DFT"])
calculated_data = good_tester.calculate_data()
... | self._good_case(name=self._c6h6)
self._good_case(name=self._si2) | identifier_body |
AbinsCalculateDWSingleCrystalTest.py | from __future__ import (absolute_import, division, print_function)
import unittest
from mantid.simpleapi import *
import numpy as np
import json
from AbinsModules import CalculateDWSingleCrystal, LoadCASTEP, AbinsTestHelpers
class | (unittest.TestCase):
temperature = 10 # 10 K
# data
# Use case: one k-point
_c6h6 = "benzene_CalculateDWSingleCrystal"
# Use case: many k-points
_si2 = "Si2-sc_CalculateDWSingleCrystal"
def tearDown(self):
AbinsTestHelpers.remove_output_files(list_of_names=["CalculateDWSingleCr... | AbinsCalculateDWSingleCrystalTest | identifier_name |
AbinsCalculateDWSingleCrystalTest.py | from __future__ import (absolute_import, division, print_function)
import unittest
from mantid.simpleapi import *
import numpy as np
import json
from AbinsModules import CalculateDWSingleCrystal, LoadCASTEP, AbinsTestHelpers
class AbinsCalculateDWSingleCrystalTest(unittest.TestCase):
temperature = 10 # 10 K
... | return {"DFT": castep_reader.read_phonon_file(), "DW": dw}
# noinspection PyMethodMayBeStatic
def _prepare_data(self, filename=None):
"""Reads a correct values from ASCII file."""
with open(filename) as data_file:
correct_data = json.loads(data_file.read().replace("\n", " ")... | random_line_split | |
AbinsCalculateDWSingleCrystalTest.py | from __future__ import (absolute_import, division, print_function)
import unittest
from mantid.simpleapi import *
import numpy as np
import json
from AbinsModules import CalculateDWSingleCrystal, LoadCASTEP, AbinsTestHelpers
class AbinsCalculateDWSingleCrystalTest(unittest.TestCase):
temperature = 10 # 10 K
... | unittest.main() | conditional_block | |
auth.service.ts | import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { accessTokenKey, baseUrl } from '../core/constants';
import { HubClient } from '../core/hub-client';
import { LocalStorageService } from '../core/local-storage.service';
i... |
}
| {
this._loggerService.trace('AuthService', 'tryToLogin');
return this._httpClient.post<any>(`${this._baseUrl}api/users/token`, options).pipe(
map(response => {
this._localStorageService.put({ name: accessTokenKey, value: response.accessToken });
return response.accessToken;
})
)... | identifier_body |
auth.service.ts | import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { accessTokenKey, baseUrl } from '../core/constants';
import { HubClient } from '../core/hub-client';
import { LocalStorageService } from '../core/local-storage.service';
i... | this._loggerService.trace('AuthService', 'tryToLogin');
return this._httpClient.post<any>(`${this._baseUrl}api/users/token`, options).pipe(
map(response => {
this._localStorageService.put({ name: accessTokenKey, value: response.accessToken });
return response.accessToken;
})
);
... | this._hubClient.disconnect();
this._localStorageService.put({ name: accessTokenKey, value: null });
}
public tryToLogin(options: { username: string; password: string }) { | random_line_split |
auth.service.ts | import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { accessTokenKey, baseUrl } from '../core/constants';
import { HubClient } from '../core/hub-client';
import { LocalStorageService } from '../core/local-storage.service';
i... | () {
this._hubClient.disconnect();
this._localStorageService.put({ name: accessTokenKey, value: null });
}
public tryToLogin(options: { username: string; password: string }) {
this._loggerService.trace('AuthService', 'tryToLogin');
return this._httpClient.post<any>(`${this._baseUrl}api/users/token... | logout | identifier_name |
b-router.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:base/b-router/README.md]]
* @packageDocumentation
*/
import symbolGenerator from 'core/symbol';
import { deprecated } from 'core/functools/d... |
/**
* Compiles the specified static routes with the current base path and returns a new object
* @param [routes]
*/
protected compileStaticRoutes(routes: StaticRoutes = this.engine.routes ?? globalRoutes): router.RouteBlueprints {
return router.compileStaticRoutes(routes, {basePath: this.basePath});
}
pr... | {
return this.initRoute();
} | identifier_body |
b-router.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:base/b-router/README.md]]
* @packageDocumentation
*/
import symbolGenerator from 'core/symbol';
import { deprecated } from 'core/functools/d... | (): void {
super.initBaseAPI();
const
i = this.instance;
this.compileStaticRoutes = i.compileStaticRoutes.bind(this);
this.emitTransition = i.emitTransition.bind(this);
}
/**
* Handler: click on an element with the `href` attribute
* @param e
*/
@watch({
field: 'document:click',
wrapper: (o, ... | initBaseAPI | identifier_name |
b-router.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:base/b-router/README.md]]
* @packageDocumentation
*/
import symbolGenerator from 'core/symbol';
import { deprecated } from 'core/functools/d... | if (currentEngineRoute && method !== 'replace') {
const
currentRouteWithScroll = Object.mixin(true, undefined, currentEngineRoute, scroll);
if (!Object.fastCompare(currentEngineRoute, currentRouteWithScroll)) {
await engine.replace(getEngineRoute()!, currentRouteWithScroll);
}
}
// We haven't f... | };
// To save scroll position before change to a new route
// we need to emit system "replace" transition with padding information about the scroll | random_line_split |
b-router.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:base/b-router/README.md]]
* @packageDocumentation
*/
import symbolGenerator from 'core/symbol';
import { deprecated } from 'core/functools/d... |
if (Object.isArray(val)) {
// eslint-disable-next-line prefer-spread
return this.updateRoutes.apply(this, val);
}
return this.routes;
}
/**
* Initializes the router within an application
* @emits `$root.initRouter(router:` [[bRouter]]`)`
*/
@hook('created')
protected init(): void {
this.fiel... | {
return Promise.all(this.state.set(val)).then(() => val);
} | conditional_block |
apiService.js | import wretch from 'wretch';
const api = wretch()
.url(process.env.API_URL || 'http://localhost:3002/api')
.auth(`Bearer ${localStorage.getItem('authToken')}`);
/*
* Exported methods shouldn't be used directly from a component; use
* one of the actual API libs instead.
*/
export function get(app, path, data =... | export function put(app, path, data = null, config = {}) {
return api
.url(`/${app}/${path}`)
.put(data)
.badRequest(parseValidationError)
.res(parseResponse);
}
export function delete_(app, path, data = null, config = {}) {
return api
.url(`/${app}/${path}`)
.delete(data)
.res(parseRes... | }
| random_line_split |
apiService.js | import wretch from 'wretch';
const api = wretch()
.url(process.env.API_URL || 'http://localhost:3002/api')
.auth(`Bearer ${localStorage.getItem('authToken')}`);
/*
* Exported methods shouldn't be used directly from a component; use
* one of the actual API libs instead.
*/
export function get(app, path, data =... | (app, path, data = null, config = {}) {
return api
.url(`/${app}/${path}`)
.delete(data)
.res(parseResponse);
}
export class ValidationError extends Error {
constructor(message, validationErrors) {
super(message); // 'Error' breaks prototype chain here
Object.setPrototypeOf(this, new.target.pro... | delete_ | identifier_name |
apiService.js | import wretch from 'wretch';
const api = wretch()
.url(process.env.API_URL || 'http://localhost:3002/api')
.auth(`Bearer ${localStorage.getItem('authToken')}`);
/*
* Exported methods shouldn't be used directly from a component; use
* one of the actual API libs instead.
*/
export function get(app, path, data =... |
if (isJSONResponse(response)) {
return response.json();
}
return response.text();
};
const parseValidationError = async ({ response, text }) => {
if (isJSONResponse(response)) {
const json = JSON.parse(text);
throw new ValidationError(json.error, json.message);
}
throw new Error(error.text);... | {
throw new Error(response.status + ' ' + response.statusText);
} | conditional_block |
form.ts | import { Component, ElementRef, ViewChild, EventEmitter, Output, Input, OnInit } from '@angular/core';
import { IonicPage, NavParams, NavController, Events } from 'ionic-angular';
import * as umf from '../../../core/framework/index';
import { UmfApp } from '../../../core/framework/index';
function bindEventHandlersTo... |
var app = this.app;
this.events.publish("form:loaded", { app: app });
// Auto-submit form if necessary.
if (form.metadata.postOnLoad) {
this.submit(app, form, null);
}
}
};
enableForm() {
var formInstance = this.form;... | random_line_split | |
form.ts | import { Component, ElementRef, ViewChild, EventEmitter, Output, Input, OnInit } from '@angular/core';
import { IonicPage, NavParams, NavController, Events } from 'ionic-angular';
import * as umf from '../../../core/framework/index';
import { UmfApp } from '../../../core/framework/index';
function bindEventHandlersTo... |
await app.runFunctions(response.metadata.functionsToRun);
if (response.metadata.handler == "" || response.metadata.handler == null) {
this.renderResponse(response);
}
else {
app.handleResponse(response, formInstance);
}
... | {
throw new Error(`Received null response.`);
} | conditional_block |
form.ts | import { Component, ElementRef, ViewChild, EventEmitter, Output, Input, OnInit } from '@angular/core';
import { IonicPage, NavParams, NavController, Events } from 'ionic-angular';
import * as umf from '../../../core/framework/index';
import { UmfApp } from '../../../core/framework/index';
function bindEventHandlersTo... | () {
this.app = this.params.data.app;
this.form = this.params.data.form;
this.metadata = this.params.data.metadata;
this.self = this;
this.initialized = this.initializedForm;
this.init();
}
async initialiseInputs(field, app) {
field.inputs = app.controlRe... | ngOnInit | identifier_name |
Randomizer.js | /*** @jsx React.DOM */
var React = require('react');
var JigsawStore = require('../stores/JigsawStore');
var JigsawActions = require('../actions/JigsawActions');
/**
* A button to update the random number generator seed.
* @type {*|Function}
*/
var Randomizer = React.createClass({
getInitialState: function() {
... | <button className="btn btn-default" onClick={this._randomize}>Randomize</button>
);
},
_randomize: function() {
JigsawActions.randomize();
return false;
},
_onChange: function() {
this.setState({seed: JigsawStore.getRandSeed()})
}
});
module.exports = Randomizer; | var disabled = ! this.state.canRedo;
return ( | random_line_split |
settings.py | """
Django settings for app project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Bui... | ),
'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
} | 'DEFAULT_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer', | random_line_split |
multi_tenancy.py | # -*- coding: utf-8 -*-
#
# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# 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:
#
# ... |
@step(u'no messages have been received by the secondary RabbitMQ consumer')
def no_messages_received_for_secondary_tenant(context):
print ("> Received main list: " + str(context.secondaty_rabbitmq_consumer.message_list))
print ("> Received seconday list: " + str(context.rabbitmq_consumer.message_list))
ass... | pected_message = dict(element.as_dict())
expected_message = _dataset_utils.prepare_data(expected_message)
assert_that(expected_message, is_message_in_consumer_list(context.secondaty_rabbitmq_consumer.message_list),
"A message with the expected content has not been received by the se... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.