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 |
|---|---|---|---|---|
embeddings_test.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | (test.TestCase):
def test_embedding(self):
with self.test_session():
testing_utils.layer_test(
keras.layers.Embedding,
kwargs={'output_dim': 4,
'input_dim': 10,
'input_length': 2},
input_shape=(3, 2),
input_dtype='int32',
... | EmbeddingTest | identifier_name |
embeddings_test.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | test.main() | conditional_block | |
embeddings_test.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0 | #
# Unless required by applicable law or agreed to in writing, software
# 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
# limitations under the License.
# ... | random_line_split | |
tabs.ts | import { MunicipioVO } from './../../model/municipioVO';
import { UsuarioVO } from './../../model/usuarioVO';
import { GlobalVar } from './../../shared/global-var';
import { UsuarioService } from './../../providers/service/usuario-service';
import { MensagemListaPage } from './../mensagem-lista/mensagem-lista';
import... |
});
}
private totalNovasMensagens() {
let totalMensage: number = 0;
var mensPromise = this.usuaSrv.getMensagens();
if (mensPromise != null) {
mensPromise.then((snapMsg) => {
snapMsg.forEach(element => {
if (element.val() == true) {
totalMensage++;
}... | {
self.novasMensagem = '';
} | conditional_block |
tabs.ts | import { MunicipioVO } from './../../model/municipioVO';
import { UsuarioVO } from './../../model/usuarioVO';
import { GlobalVar } from './../../shared/global-var';
import { UsuarioService } from './../../providers/service/usuario-service';
import { MensagemListaPage } from './../mensagem-lista/mensagem-lista';
import... | () {
var self = this;
self.events.subscribe('mensagem:nova', (total: number) => {
if (total > 0) {
self.novasMensagem = total.toString();
}
else {
self.novasMensagem = '';
}
});
}
private totalNovasMensagens() {
let totalMensage: number = 0;
var mensPro... | eventoNovaMensagem | identifier_name |
tabs.ts | import { MunicipioVO } from './../../model/municipioVO';
import { UsuarioVO } from './../../model/usuarioVO';
import { GlobalVar } from './../../shared/global-var';
import { UsuarioService } from './../../providers/service/usuario-service';
import { MensagemListaPage } from './../mensagem-lista/mensagem-lista';
import... | public novasMensagem: string = '';
constructor(public nav: NavController,
public navParams: NavParams,
public events: Events,
private usuaSrv: UsuarioService,
private glbVar: GlobalVar) {
this.setMunicipioPadrao();
this.selectedIndex = navParams.data.tabIndex || 1;
}
ngOnInit() {
t... | selectedIndex: number;
public newThreads: string = ''; | random_line_split |
tabs.ts | import { MunicipioVO } from './../../model/municipioVO';
import { UsuarioVO } from './../../model/usuarioVO';
import { GlobalVar } from './../../shared/global-var';
import { UsuarioService } from './../../providers/service/usuario-service';
import { MensagemListaPage } from './../mensagem-lista/mensagem-lista';
import... |
private totalNovasMensagens() {
let totalMensage: number = 0;
var mensPromise = this.usuaSrv.getMensagens();
if (mensPromise != null) {
mensPromise.then((snapMsg) => {
snapMsg.forEach(element => {
if (element.val() == true) {
totalMensage++;
}
... | {
var self = this;
self.events.subscribe('mensagem:nova', (total: number) => {
if (total > 0) {
self.novasMensagem = total.toString();
}
else {
self.novasMensagem = '';
}
});
} | identifier_body |
email-supporter.js | $(function () {
$('#supportsearch').typeahead({
name: 'supsearch',
valueKey: "line1",
limit: 25,
beforeSend: function (jqXhr, settings) {
$.SetLoadingIndicator();
},
remote: '/MissionTripEmail2/Search/{0}?q=%QUERY'.format($("#PeopleId").val()),
mi... | $.post(href, {}, function (ret) {
$("#recipients").html(ret);
});
return false;
});
$("#edit-supporters").click(function (ev) {
ev.preventDefault();
var href = this.href;
$("#edit-supporters").hide();
$("#editing").show();
$("#edit-hel... | random_line_split | |
email-supporter.js | $(function () {
$('#supportsearch').typeahead({
name: 'supsearch',
valueKey: "line1",
limit: 25,
beforeSend: function (jqXhr, settings) {
$.SetLoadingIndicator();
},
remote: '/MissionTripEmail2/Search/{0}?q=%QUERY'.format($("#PeopleId").val()),
mi... | {
var iFrameID = document.getElementById('email-body');
if (iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + 20 + "px";
}
}
... | justIframe() | identifier_name |
email-supporter.js | $(function () {
$('#supportsearch').typeahead({
name: 'supsearch',
valueKey: "line1",
limit: 25,
beforeSend: function (jqXhr, settings) {
$.SetLoadingIndicator();
},
remote: '/MissionTripEmail2/Search/{0}?q=%QUERY'.format($("#PeopleId").val()),
mi... | $('#editor-modal').on('click', '#save-edit', function () {
var h = $('#htmleditor').froalaEditable('getHTML');
$(currentDiv).html(h);
adjustIframe();
$('#editor-modal').modal('hide');
});
$(".send").click(function () {
$('#Body').val($('#email-body').contents().find(... | var iFrameID = document.getElementById('email-body');
if (iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + 20 + "px";
}
}
| identifier_body |
email-supporter.js | $(function () {
$('#supportsearch').typeahead({
name: 'supsearch',
valueKey: "line1",
limit: 25,
beforeSend: function (jqXhr, settings) {
$.SetLoadingIndicator();
},
remote: '/MissionTripEmail2/Search/{0}?q=%QUERY'.format($("#PeopleId").val()),
mi... | };
window.displayEditor = function (div) {
currentDiv = div;
$('#editor-modal').modal('show');
};
$('#editor-modal').on('shown.bs.modal', function () {
if ($('#htmleditor').data('fa.editable')) {
$('#htmleditor').froalaEditable('destroy');
}
var extr... | $.addFunction();
}
| conditional_block |
mpm.py | # -*- coding: utf-8 -*-
import argparse
import six
parser = argparse.ArgumentParser(description="Minecraft Package Manager")
sub = parser.add_subparsers(help="command help")
| # package commands
sync_parser = sub.add_parser("sync",
description="Synchronize local mod archive.",
help="sync --help")
show_parser = sub.add_parser("show",
description="Show mod informations.",
help="s... | random_line_split | |
mpm.py | # -*- coding: utf-8 -*-
import argparse
import six
parser = argparse.ArgumentParser(description="Minecraft Package Manager")
sub = parser.add_subparsers(help="command help")
# package commands
sync_parser = sub.add_parser("sync",
description="Synchronize local mod archive.",
... | cmd = parser.parse_args()
six.print_("Done") | conditional_block | |
gather_moves.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 ... |
mc::cat_deref(b, _, mc::uniq_ptr(*)) |
mc::cat_discr(b, _) => {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
}
| {
match ty::get(b.ty).sty {
ty::ty_struct(did, _) | ty::ty_enum(did, _) => {
if ty::has_dtor(bccx.tcx, did) {
bccx.span_err(
cmt0.span,
fmt!("cannot move out of type `%s`, \
... | conditional_block |
gather_moves.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 ... | (bccx: @BorrowckCtxt,
cmt0: mc::cmt,
cmt: mc::cmt) -> bool {
match cmt.cat {
mc::cat_implicit_self(*) |
mc::cat_deref(_, _, mc::region_ptr(*)) |
mc::cat_deref(_, _, mc::gc_ptr(*)) |
mc::cat_deref(_, _, mc::unsafe_ptr(*)) =... | check_is_legal_to_move_from | identifier_name |
gather_moves.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 ... | move_data.add_move(bccx.tcx, loan_path, closure_expr.id,
Captured(closure_expr));
}
moves::CapCopy | moves::CapRef => {}
}
}
}
pub fn gather_assignment(bccx: @BorrowckCtxt,
move_data: &mut MoveData,
... | moves::CapMove => {
let fvar_id = ast_util::def_id_of_def(captured_var.def).node;
let loan_path = @LpVar(fvar_id); | random_line_split |
gather_moves.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 ... |
pub fn gather_move_from_pat(bccx: @BorrowckCtxt,
move_data: &mut MoveData,
move_pat: @ast::pat,
cmt: mc::cmt) {
gather_move_from_expr_or_pat(bccx, move_data, move_pat.id,
MovePat(move_pat), cmt);
}... | {
gather_move_from_expr_or_pat(bccx, move_data, move_expr.id,
MoveExpr(move_expr), cmt);
} | identifier_body |
mod.rs | // c4puter embedded controller firmware
// Copyright (C) 2017 Chris Pavlina
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later v... | //
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
//! Utilities for processing and displaying data
mod parseint;
mod hexprint;
pub mod base64;
pub mo... | // GNU General Public License for more details. | random_line_split |
enum-discrim-manual-sizing.rs | // Copyright 2013 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 ... |
pub fn main() {
assert_eq!(size_of::<Ei8>(), 1);
assert_eq!(size_of::<Eu8>(), 1);
assert_eq!(size_of::<Ei16>(), 2);
assert_eq!(size_of::<Eu16>(), 2);
assert_eq!(size_of::<Ei32>(), 4);
assert_eq!(size_of::<Eu32>(), 4);
assert_eq!(size_of::<Ei64>(), 8);
assert_eq!(size_of::<Eu64>(), 8);
... | _None,
_Some(T),
} | random_line_split |
enum-discrim-manual-sizing.rs | // Copyright 2013 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 ... | {
Au32 = 0,
Bu32 = 1
}
#[repr(i64)]
enum Ei64 {
Ai64 = 0,
Bi64 = 1
}
#[repr(u64)]
enum Eu64 {
Au64 = 0,
Bu64 = 1
}
#[repr(isize)]
enum Eint {
Aint = 0,
Bint = 1
}
#[repr(usize)]
enum Euint {
Auint = 0,
Buint = 1
}
#[repr(u8)]
enum Eu8NonCLike<T> {
_None,
_Some(T),
}... | Eu32 | identifier_name |
node_style.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Style retrieval from DOM elements.
use css::node_util::NodeUtil;
use layout::incremental::RestyleDamage;
use l... |
}
| {
self.get_restyle_damage()
} | identifier_body |
node_style.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Style retrieval from DOM elements.
use css::node_util::NodeUtil;
use layout::incremental::RestyleDamage;
use l... | /// Node mixin providing `style` method that returns a `NodeStyle`
pub trait StyledNode {
fn style<'a>(&'a self) -> &'a Arc<ComputedValues>;
fn restyle_damage(&self) -> RestyleDamage;
}
impl<'self> StyledNode for LayoutNode<'self> {
#[inline]
fn style<'a>(&'a self) -> &'a Arc<ComputedValues> {
... | use extra::arc::Arc;
use style::ComputedValues;
| random_line_split |
node_style.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Style retrieval from DOM elements.
use css::node_util::NodeUtil;
use layout::incremental::RestyleDamage;
use l... | <'a>(&'a self) -> &'a Arc<ComputedValues> {
self.get_css_select_results()
}
fn restyle_damage(&self) -> RestyleDamage {
self.get_restyle_damage()
}
}
| style | identifier_name |
compilers.js | /*!
* ncss - compilers
* Copyright (c) 2011 Wil Asche <wil@wickedspiral.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var deps = {};
/**
* Compiliers
*/
module.exports = {
'css': function(str, path, callback, next) {
callback(str);
},
'styl': function(str, path, callback, next) {
if (... | (name) {
if (deps[name] === false) return false;
deps[name] = require(name);
return deps[name] !== null;
}
| load | identifier_name |
compilers.js | /*!
* ncss - compilers
* Copyright (c) 2011 Wil Asche <wil@wickedspiral.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var deps = {};
/**
* Compiliers
*/
module.exports = {
'css': function(str, path, callback, next) {
callback(str);
},
'styl': function(str, path, callback, next) {
if (... | {
if (deps[name] === false) return false;
deps[name] = require(name);
return deps[name] !== null;
} | identifier_body | |
compilers.js | /*!
* ncss - compilers | */
/**
* Module dependencies.
*/
var deps = {};
/**
* Compiliers
*/
module.exports = {
'css': function(str, path, callback, next) {
callback(str);
},
'styl': function(str, path, callback, next) {
if ( ! load('stylus') ) next();
deps.stylus(str).set('filename', path).render(function(err, css... | * Copyright (c) 2011 Wil Asche <wil@wickedspiral.com>
* MIT Licensed | random_line_split |
ImageSpacer.tsx | import React from "react"
import styled from "styled-components"
import { StaticImage } from 'gatsby-plugin-image'
const Container = styled.div`
width: 100vw;
left: 0;
overflow: hidden;
`
const ImagesContainer = styled.div`
width: 130%;
left: -15%;
position: relative;
display: flex;
justify-content: s... | <ImageContainer key={index}>
{image}
</ImageContainer>
))}
</ImagesContainer>
</Container>
)
} | {images.map((image, index) => ( | random_line_split |
commandmanager.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|--------------------------------------------------... |
/**
* Registers a new component which can emit a signal
* in order to invoke a command
*
*/
registerCommandInvoker(obj: ICommandInvoker): boolean {
obj.invokeCommand.connect(this._runFromSignal, this);
return true;
}
private _runFromSignal(sender: ICommandInvoker, value: string): void {
... | {
this._commandMap[command.id] = command;
this._addToNamespaces(command.id);
return true;
} | identifier_body |
commandmanager.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|--------------------------------------------------... | (id: string): void {
id.split('.'); // TODO
}
private _commandMap: any = {};
private _namespaces: string[] = []; // TODO: should be a set, not array;
}
| _addToNamespaces | identifier_name |
commandmanager.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|--------------------------------------------------... | return true;
}
private _runFromSignal(sender: ICommandInvoker, value: string): void {
console.log('Run from signal');
this.runCommand(value);
}
/**
* Runs the handler associated with a command id.
*
* This is part of the ICommandManager interface, it takes a string
* which represents t... | */
registerCommandInvoker(obj: ICommandInvoker): boolean {
obj.invokeCommand.connect(this._runFromSignal, this); | random_line_split |
lint.py | # Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, mer... | (msg):
report("%s", msg)
renpy.exports.push_error_handler(error)
try:
node.call("lint")
finally:
renpy.exports.pop_error_handler()
try:
node.get_next()
except:
report("Didn't properly report what the next statement should be.")
check_text_tags... | error | identifier_name |
lint.py | # Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, mer... |
def check_jump(node):
if node.expression:
return
if not renpy.game.script.has_label(node.target):
report("The jump is to nonexistent label '%s'.", node.target)
def check_call(node):
# if not isinstance(node.next.name, basestring):
# report(node, "The call does not ha... | for l, c, b in node.items:
if c:
try_compile("in the if clause of a menuitem", c)
text_checks(l)
| random_line_split |
lint.py | # Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, mer... |
added = { }
# Reports additional information about a message, the first time it
# occurs.
def add(msg):
if not msg in added:
added[msg] = True
print unicode(msg).encode('utf-8')
# Trys to evaluate an expression, announcing an error if it fails.
def try_eval(where, expr, additio... | if report_node:
out = u"%s:%d " % (renpy.parser.unicode_filename(report_node.filename), report_node.linenumber)
else:
out = ""
out += msg % args
print
print out.encode('utf-8') | identifier_body |
lint.py | # Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, mer... |
report_node = None
check_styles()
for f in renpy.config.lint_hooks:
f()
print
print
print "Statistics:"
print
print "The game contains", say_count, "screens of dialogue."
print "These screens contain a total of", say_words, "words,"
... | check_user(node) | conditional_block |
start.py | #!/usr/bin/env python3
# coding:utf-8
import os
import sys
import time
import traceback
from datetime import datetime
import atexit
# reduce resource request for threading
# for OpenWrt
import threading
try:
threading.stack_size(128 * 1024)
except:
pass
try:
import tracemalloc
tracemalloc.start(10)
e... |
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt: # Ctrl + C on console
module_init.stop_all()
os._exit(0)
sys.exit()
except Exception as e:
xlog.exception("launcher except:%r", e)
input("Press Enter to continue...")
| global __file__
__file__ = os.path.abspath(__file__)
if os.path.islink(__file__):
__file__ = getattr(os, 'readlink', lambda x: x)(__file__)
os.chdir(os.path.dirname(os.path.abspath(__file__)))
if sys.platform == "win32" and config.show_compat_suggest:
import win_compat_suggest
w... | identifier_body |
start.py | #!/usr/bin/env python3
# coding:utf-8
import os
import sys
import time
import traceback
from datetime import datetime
import atexit
# reduce resource request for threading
# for OpenWrt
import threading
try:
threading.stack_size(128 * 1024)
except:
pass
try:
import tracemalloc
tracemalloc.start(10)
e... |
def main():
# change path to launcher
global __file__
__file__ = os.path.abspath(__file__)
if os.path.islink(__file__):
__file__ = getattr(os, 'readlink', lambda x: x)(__file__)
os.chdir(os.path.dirname(os.path.abspath(__file__)))
if sys.platform == "win32" and config.show_compat_sugg... |
atexit.register(exit_handler) | random_line_split |
start.py | #!/usr/bin/env python3
# coding:utf-8
import os
import sys
import time
import traceback
from datetime import datetime
import atexit
# reduce resource request for threading
# for OpenWrt
import threading
try:
threading.stack_size(128 * 1024)
except:
pass
try:
import tracemalloc
tracemalloc.start(10)
e... |
elif s == "-no_mess_system":
no_mess_system = 1
if allow_remote or config.allow_remote_connect:
xlog.info("start with allow remote connect.")
module_init.xargs["allow_remote"] = 1
if os.getenv("XXNET_NO_MESS_SYSTEM", "0") != "0" or no_mess_system or config.no_mess_... | allow_remote = 1 | conditional_block |
start.py | #!/usr/bin/env python3
# coding:utf-8
import os
import sys
import time
import traceback
from datetime import datetime
import atexit
# reduce resource request for threading
# for OpenWrt
import threading
try:
threading.stack_size(128 * 1024)
except:
pass
try:
import tracemalloc
tracemalloc.start(10)
e... | (module):
for m in list(sys.modules.keys()):
if m == module or m.startswith(module + "."):
del sys.modules[m]
for p in list(sys.path_importer_cache.keys()):
if module in p:
del sys.path_importer_cache[p]
try:
del module
except:
pass
try:
sy... | unload | identifier_name |
regions-infer-at-fn-not-param.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 ... | {
g: @fn()
}
fn take1(p: parameterized1) -> parameterized1 { p } //~ ERROR mismatched types
fn take3(p: not_parameterized1) -> not_parameterized1 { p }
fn take4(p: not_parameterized2) -> not_parameterized2 { p }
fn main() {}
| not_parameterized2 | identifier_name |
regions-infer-at-fn-not-param.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 ... | g: @fn()
}
fn take1(p: parameterized1) -> parameterized1 { p } //~ ERROR mismatched types
fn take3(p: not_parameterized1) -> not_parameterized1 { p }
fn take4(p: not_parameterized2) -> not_parameterized2 { p }
fn main() {} | g: @fn()
}
struct not_parameterized2 { | random_line_split |
EcsLoadBalancerClusterContainer.tsx | import { isEqual } from 'lodash';
import React from 'react';
import type { ILoadBalancerClusterContainerProps } from '@spinnaker/core';
import { EcsTargetGroup } from './TargetGroup';
import type { IEcsLoadBalancer } from '../domain/IEcsLoadBalancer'; | export class EcsLoadBalancerClusterContainer extends React.Component<ILoadBalancerClusterContainerProps> {
public shouldComponentUpdate(nextProps: ILoadBalancerClusterContainerProps) {
const serverGroupsDiffer = () =>
!isEqual(
(nextProps.serverGroups || []).map((g) => g.name),
(this.props.s... | random_line_split | |
EcsLoadBalancerClusterContainer.tsx | import { isEqual } from 'lodash';
import React from 'react';
import type { ILoadBalancerClusterContainerProps } from '@spinnaker/core';
import { EcsTargetGroup } from './TargetGroup';
import type { IEcsLoadBalancer } from '../domain/IEcsLoadBalancer';
export class EcsLoadBalancerClusterContainer extends React.Compon... | (nextProps: ILoadBalancerClusterContainerProps) {
const serverGroupsDiffer = () =>
!isEqual(
(nextProps.serverGroups || []).map((g) => g.name),
(this.props.serverGroups || []).map((g) => g.name),
);
const targetGroupsDiffer = () =>
!isEqual(
((nextProps.loadBalancer as ... | shouldComponentUpdate | identifier_name |
app.routes.js | /**
* Created by josip on 20.1.2017..
*/
angular.module('mainModule').config(function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl: '/home/home.view.html',
controller: 'homeCtrl',
controllerAs: 'vm'
})
.when('/register', {... | }); | // use the HTML5 History API
$locationProvider.html5Mode(true); | random_line_split |
test_raid.py | #!/usr/bin/python
# pdev
# pdev cbd
# pdev asd cbd
# pdev asd sd cbd
from hba_util import HBA
from raid_util import Raid_Util
from subdev import *
def test_create_remove_raid(raid_util, bdevs):
sub_dev_list = []
for bdev in bdevs:
path = '/dev/' + bdev
sub_dev_list.append(path)
raid_util... | ():
hba = HBA('mv64xx')
hba.get_bdev()
raid_util = get_raid_util()
for i in range(4, 16):
bdevs = hba.get_bdev_balanced(i)
if len(bdevs):
print bdevs
test_create_remove_raid(raid_util, bdevs)
raid_util.exit_raid()
#test_pdev_raid()
def test_pdev_cbd_raid():
#... | test_pdev_raid | identifier_name |
test_raid.py | #!/usr/bin/python
# pdev
# pdev cbd
# pdev asd cbd
# pdev asd sd cbd
from hba_util import HBA
from raid_util import Raid_Util
from subdev import *
def test_create_remove_raid(raid_util, bdevs):
sub_dev_list = []
for bdev in bdevs:
path = '/dev/' + bdev
sub_dev_list.append(path)
raid_util... |
cbds = create_multi_cbd(bdevs)
print '%d %d: %s' % (len(cbds), i, cbds)
if len(cbds) <= i:
remove_multi_cbd(cbds)
break
test_create_remove_raid(raid_util, cbds)
remove_multi_cbd(cbds)
exit_cbd()
raid_util.exit_raid()
test_pdev_cbd_ra... | print bdevs | conditional_block |
test_raid.py | #!/usr/bin/python
# pdev
# pdev cbd
# pdev asd cbd
# pdev asd sd cbd
from hba_util import HBA
from raid_util import Raid_Util
from subdev import *
def test_create_remove_raid(raid_util, bdevs):
sub_dev_list = []
for bdev in bdevs:
path = '/dev/' + bdev
sub_dev_list.append(path)
raid_util... | if len(cbds) <= i:
remove_multi_cbd(cbds)
break
test_create_remove_raid(raid_util, cbds)
remove_multi_cbd(cbds)
exit_cbd()
raid_util.exit_raid()
test_pdev_cbd_raid() | print '%d %d: %s' % (len(cbds), i, cbds)
| random_line_split |
test_raid.py | #!/usr/bin/python
# pdev
# pdev cbd
# pdev asd cbd
# pdev asd sd cbd
from hba_util import HBA
from raid_util import Raid_Util
from subdev import *
def test_create_remove_raid(raid_util, bdevs):
|
def get_raid_util():
#raid_util = Raid_Util('/root/src/mdadm_ext/', '/root/src/md_ext/')
raid_util = Raid_Util('/sbin/', None)
raid_util.set_raid_txn(False)
raid_util.init_raid()
raid_util.set_raid_level(6)
raid_util.set_raid_name('raid6')
raid_util.set_cmd_args('-e1.0')
raid_util.set_... | sub_dev_list = []
for bdev in bdevs:
path = '/dev/' + bdev
sub_dev_list.append(path)
raid_util.set_sub_dev_list(sub_dev_list)
raid_util.zero_raid_sub_dev()
raid_util.create_raid()
raid_util.show_raid_info()
raid_util.wait_sync()
raid_util.fail_one()
raid_util.add_one()
... | identifier_body |
proxy.rs | //! A proxy that forwards data to another server and forwards that server's
//! responses back to clients.
//!
//! You can showcase this by running this in one terminal:
//!
//! cargo run --example proxy
//!
//! This in another terminal
//!
//! cargo run --example echo
//!
//! And finally this in another termin... | impl AsyncWrite for MyTcpStream {
fn shutdown(&mut self) -> Poll<(), io::Error> {
try!(self.0.shutdown(Shutdown::Write));
Ok(().into())
}
} | }
impl AsyncRead for MyTcpStream {}
| random_line_split |
proxy.rs | //! A proxy that forwards data to another server and forwards that server's
//! responses back to clients.
//!
//! You can showcase this by running this in one terminal:
//!
//! cargo run --example proxy
//!
//! This in another terminal
//!
//! cargo run --example echo
//!
//! And finally this in another termin... | (Arc<TcpStream>);
impl Read for MyTcpStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(&*self.0).read(buf)
}
}
impl Write for MyTcpStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(&*self.0).write(buf)
}
fn flush(&mut self) -> io::Result<()> {
... | MyTcpStream | identifier_name |
proxy.rs | //! A proxy that forwards data to another server and forwards that server's
//! responses back to clients.
//!
//! You can showcase this by running this in one terminal:
//!
//! cargo run --example proxy
//!
//! This in another terminal
//!
//! cargo run --example echo
//!
//! And finally this in another termin... |
}
impl Write for MyTcpStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(&*self.0).write(buf)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl AsyncRead for MyTcpStream {}
impl AsyncWrite for MyTcpStream {
fn shutdown(&mut self) -> Poll<(), io::Error> {
... | {
(&*self.0).read(buf)
} | identifier_body |
lbaasHealthMonitor.js | /*
* opLoadBalancer.js: lbaas APIs
* for Openstack networking
*
* (C) 2015 Hopebaytech
*
* P. Hsuan
*/
var urlJoin = require('url-join');
var _ = require('lodash');
var lbaasHealthMonitorPath = '/lb/health_monitors';
// Declaring variables for helper functions defined later
var _convertcreateToWireFormat;
... |
callback(err, new self.models.HealthMonitor(self, body.health_monitor));
});
};
/*
create Health monitor
{
"health_monitor":{
"admin_state_up": true,
"delay": "1",
"expected_codes": "200,201,202",
"http_method": "GET",
"max_retries": 5,
"pool_id": "74aa2010-a59f-4d3... | {
return new Error('Malformed API Response');
} | conditional_block |
lbaasHealthMonitor.js | /*
* opLoadBalancer.js: lbaas APIs
* for Openstack networking
*
* (C) 2015 Hopebaytech
*
* P. Hsuan
*/
var urlJoin = require('url-join');
var _ = require('lodash');
var lbaasHealthMonitorPath = '/lb/health_monitors';
// Declaring variables for helper functions defined later
var _convertcreateToWireFormat;
... | method: 'GET'
}, function (err, body) {
if (err) {
return callback(err);
}
if (!body ||!body.health_monitor) {
return new Error('Malformed API Response');
}
callback(err, new self.models.HealthMonitor(self, body.health_monitor));
});
};
/*
create Health monitor
{
"heal... | var self = this,
monitorID = option instanceof this.models.HealthMonitor ? option.id : option;
self.emit('log::trace', 'Getting details for lbaas health monitor', monitorID);
this._request({
path: urlJoin(lbaasHealthMonitorPath, monitorID), | random_line_split |
run_script.js | module.exports = {
//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------
name: "Run Script",
//-------------------------------------------------------... | this.storeValue(result, storage, varName, cache);
if(data.behavior === "0") {
this.callNextAction(cache);
}
},
//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify exis... | const storage = parseInt(data.storage); | random_line_split |
run_script.js | module.exports = {
//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------
name: "Run Script",
//-------------------------------------------------------... |
const result = this.eval(code, cache);
const varName = this.evalMessage(data.varName, cache);
const storage = parseInt(data.storage);
this.storeValue(result, storage, varName, cache);
if(data.behavior === "0") {
this.callNextAction(cache);
}
},
//---------------------------------------------------------------... | {
code = data.code;
} | conditional_block |
prac1.js | var fs = require('fs');
console.log('Started reading a file');
//read the json file
fs.exists('./'+'source.json', function (exists)
{
if (exists)
|
else
{
console.log('source.json file does not exist');
}
}); | {
fs.readFile('source.json', function(error, data)
{
console.log('Content of file: ' + data);
//parse the received data into json object
try
{
... | conditional_block |
prac1.js | var fs = require('fs');
console.log('Started reading a file');
//read the json file
fs.exists('./'+'source.json', function (exists)
{
if (exists)
{
fs.readFile('source.json', function(error, data)
{
... | //heading line for the text file
var wholeDataString = 'ID | FName | LName | Score' + '\n';
for (var i = 0; i < studentObject.students.length; i++)
{
... | var studentObject = JSON.parse(data);
console.log('First Record: ', studentObject.students[0]);
| random_line_split |
example.rs | static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub fn get_diamond(diamond_char: char) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
let diamond_char = diamond_char.to_ascii_uppercase();
if ABC.find(diamond_char).is_none() {
return result;
}
if diamond_char == 'A' {
re... |
fn get_letter_line(char_in_abc: char) -> String {
let mut r = String::new();
let odd = (0..)
.filter(|x| x % 2 != 0)
.nth(ABC.find(char_in_abc).unwrap())
.unwrap();
for i in 0..odd {
if i == 0 || i == odd - 1 {
r.push(char_in_abc);
} else {
r... | {
let mut r = String::new();
let letter_e = get_letter_line(char_in_abc);
let letter_c = get_letter_line(diamond_char);
let ws = letter_c.len() - letter_e.len(); //number of whitespaces
//left
for _ in 0..ws / 2 {
r.push(' ');
}
//letter line
for i in letter_e.chars() {
... | identifier_body |
example.rs | static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub fn get_diamond(diamond_char: char) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
let diamond_char = diamond_char.to_ascii_uppercase();
if ABC.find(diamond_char).is_none() {
return result;
}
if diamond_char == 'A' {
re... | for i in letter_e.chars() {
r.push(i)
}
//right
for _ in 0..ws / 2 {
r.push(' ');
}
r
}
fn get_letter_line(char_in_abc: char) -> String {
let mut r = String::new();
let odd = (0..)
.filter(|x| x % 2 != 0)
.nth(ABC.find(char_in_abc).unwrap())
.unwr... | //left
for _ in 0..ws / 2 {
r.push(' ');
}
//letter line | random_line_split |
example.rs | static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub fn get_diamond(diamond_char: char) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
let diamond_char = diamond_char.to_ascii_uppercase();
if ABC.find(diamond_char).is_none() {
return result;
}
if diamond_char == 'A' |
//build first half
for char_in_abc in ABC.chars() {
result.push(get_line(char_in_abc, diamond_char).clone());
if char_in_abc == diamond_char {
break;
}
}
//build second half
let mut rev = result.clone();
rev.pop(); //remove middle piece to avoid duplicates
... | {
return vec![String::from("A")];
} | conditional_block |
example.rs | static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub fn get_diamond(diamond_char: char) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
let diamond_char = diamond_char.to_ascii_uppercase();
if ABC.find(diamond_char).is_none() {
return result;
}
if diamond_char == 'A' {
re... | (char_in_abc: char) -> String {
let mut r = String::new();
let odd = (0..)
.filter(|x| x % 2 != 0)
.nth(ABC.find(char_in_abc).unwrap())
.unwrap();
for i in 0..odd {
if i == 0 || i == odd - 1 {
r.push(char_in_abc);
} else {
r.push(' ');
... | get_letter_line | identifier_name |
lib.rs | // Copyright 2016 Phillip Oppermann, Calvin Lee and JJ Garzella.
// See the README.md file at the top-level directory of this
// distribution.
//
// Licensed under the MIT license <LICENSE or
// http://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed
// except accor... | unsafe {
smp::CpuLocal::init()
};
// Initialize the IDT
interrupts::init();
// Initialize the serial port
cpuio::init();
println!("Try to write some things!");
vga_buffer::change_color(vga_buffer::Color::White, vga_buffer::Color::Black);
#[cfg(feature = "test")] {
... |
// Initialize CPU local variables and the scheduler | random_line_split |
lib.rs | // Copyright 2016 Phillip Oppermann, Calvin Lee and JJ Garzella.
// See the README.md file at the top-level directory of this
// distribution.
//
// Licensed under the MIT license <LICENSE or
// http://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed
// except accor... |
}
// Initialize memory
memory::init(&boot_info);
// Initialize CPU local variables and the scheduler
unsafe {
smp::CpuLocal::init()
};
// Initialize the IDT
interrupts::init();
// Initialize the serial port
cpuio::init();
println!("Try to write some things!");
... | {
let addr = module.start_address() as usize + memory::KERNEL_BASE;
unsafe {
interrupts::KEYBOARD.lock()
.change_kbmap(&*(addr as *const [u8; 128]));
}
} | conditional_block |
lib.rs | // Copyright 2016 Phillip Oppermann, Calvin Lee and JJ Garzella.
// See the README.md file at the top-level directory of this
// distribution.
//
// Licensed under the MIT license <LICENSE or
// http://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed
// except accor... | (_: Layout) -> ! {
panic!("Error, out of memory");
}
/// Runs during a `panic!()`
#[panic_handler]
extern "C" fn panic_fmt(pi: &core::panic::PanicInfo) -> ! {
vga_buffer::change_color(vga_buffer::Color::Red, vga_buffer::Color::Black);
println!("\n\nESALP {}", pi);
#[cfg(feature = "test")] {
se... | oom | identifier_name |
lib.rs | // Copyright 2016 Phillip Oppermann, Calvin Lee and JJ Garzella.
// See the README.md file at the top-level directory of this
// distribution.
//
// Licensed under the MIT license <LICENSE or
// http://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed
// except accor... |
#[cfg(feature = "test")]
fn shutdown() -> ! {
use cpuio::port::Port;
let mut p: Port<u8> = unsafe { Port::new(0xf4) };
p.write(0x00);
unreachable!();
}
#[cfg(feature = "test")]
fn run_tests() {
memory::tests::run();
scheduler::tests::run();
smp::tests::run();
interrupts::tests::run()... | {
vga_buffer::clear_screen();
println!("Hello Rust log \x01");
let boot_info = unsafe { multiboot2::load(multiboot_info_address) };
for module in boot_info.module_tags() {
if module.name() == "keyboard" {
let addr = module.start_address() as usize + memory::KERNEL_BASE;
... | identifier_body |
aabb.rs | use cgmath::prelude::*;
use cgmath::Point3;
use crate::consts;
use crate::float::*;
use crate::intersect::{Intersect, Ray};
#[derive(Clone, Debug)]
pub struct Aabb {
pub min: Point3<Float>,
pub max: Point3<Float>,
}
impl Aabb {
pub fn empty() -> Aabb {
Aabb {
min: Point3::max_value(),... | }
p_min
}
pub fn max_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> {
let mut p_max = Point3::min_value();
for i in 0..3 {
p_max[i] = p1[i].max(p2[i]);
}
p_max
} |
pub fn min_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> {
let mut p_min = Point3::max_value();
for i in 0..3 {
p_min[i] = p1[i].min(p2[i]); | random_line_split |
aabb.rs | use cgmath::prelude::*;
use cgmath::Point3;
use crate::consts;
use crate::float::*;
use crate::intersect::{Intersect, Ray};
#[derive(Clone, Debug)]
pub struct Aabb {
pub min: Point3<Float>,
pub max: Point3<Float>,
}
impl Aabb {
pub fn empty() -> Aabb {
Aabb {
min: Point3::max_value(),... |
}
impl Intersect<'_, Float> for Aabb {
fn intersect(&self, ray: &Ray) -> Option<Float> {
let t1 = (self.min - ray.orig).mul_element_wise(ray.reciprocal_dir);
let t2 = (self.max - ray.orig).mul_element_wise(ray.reciprocal_dir);
let mut start = consts::MIN;
let mut end = consts::MAX;... | {
let lengths = self.max - self.min;
2.0 * (lengths.x * lengths.y + lengths.y * lengths.z + lengths.z * lengths.x).max(0.0)
} | identifier_body |
aabb.rs | use cgmath::prelude::*;
use cgmath::Point3;
use crate::consts;
use crate::float::*;
use crate::intersect::{Intersect, Ray};
#[derive(Clone, Debug)]
pub struct Aabb {
pub min: Point3<Float>,
pub max: Point3<Float>,
}
impl Aabb {
pub fn empty() -> Aabb {
Aabb {
min: Point3::max_value(),... |
}
}
pub fn min_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> {
let mut p_min = Point3::max_value();
for i in 0..3 {
p_min[i] = p1[i].min(p2[i]);
}
p_min
}
pub fn max_point(p1: &Point3<Float>, p2: &Point3<Float>) -> Point3<Float> {
let mut p_max = Point3::min_value();
... | {
None
} | conditional_block |
aabb.rs | use cgmath::prelude::*;
use cgmath::Point3;
use crate::consts;
use crate::float::*;
use crate::intersect::{Intersect, Ray};
#[derive(Clone, Debug)]
pub struct | {
pub min: Point3<Float>,
pub max: Point3<Float>,
}
impl Aabb {
pub fn empty() -> Aabb {
Aabb {
min: Point3::max_value(),
max: Point3::min_value(),
}
}
/// Update the bounding box to enclose other aswell
pub fn add_aabb(&mut self, other: &Aabb) {
... | Aabb | identifier_name |
step1_read_print.rs | use rust_mal_lib::env::{Env, Environment};
use rust_mal_lib::reader;
use rust_mal_lib::types::{MalError, MalResult, MalValue};
use rust_mal_steps::scaffold::*;
fn read(string: &str) -> MalResult {
reader::read_str(string)
}
fn eval(ast: MalValue) -> MalResult {
Ok(ast)
}
fn print(expr: MalValue) -> String {... | () -> Result<Env, MalError> {
Ok(Environment::new(None))
}
fn rep(input: &str, _: &Env) -> Result<String, MalError> {
let ast = read(input)?;
let expr = eval(ast)?;
Ok(print(expr))
}
}
fn main() -> Result<(), String> {
cli_loop::<Env, Step1ReadPrint>()
}
#[cfg(test)]
m... | create_env | identifier_name |
step1_read_print.rs | use rust_mal_lib::env::{Env, Environment};
use rust_mal_lib::reader;
use rust_mal_lib::types::{MalError, MalResult, MalValue};
use rust_mal_steps::scaffold::*;
fn read(string: &str) -> MalResult {
reader::read_str(string)
}
fn eval(ast: MalValue) -> MalResult {
Ok(ast)
}
fn print(expr: MalValue) -> String {... | Ok(Environment::new(None))
}
fn rep(input: &str, _: &Env) -> Result<String, MalError> {
let ast = read(input)?;
let expr = eval(ast)?;
Ok(print(expr))
}
}
fn main() -> Result<(), String> {
cli_loop::<Env, Step1ReadPrint>()
}
#[cfg(test)]
mod tests {
use super::*;
... | fn create_env() -> Result<Env, MalError> { | random_line_split |
geth.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (&self, address: &Address) -> Result<(), Error> {
self.dir.remove(address)
}
}
| remove | identifier_name |
geth.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | }
#[cfg(windows)]
/// Default path for ethereum installation on Windows
pub fn geth_dir_path() -> PathBuf {
let mut home = env::home_dir().expect("Failed to get home dir");
home.push("AppData");
home.push("Roaming");
home.push("Ethereum");
home
}
#[cfg(not(any(target_os = "macos", windows)))]
/// Default path fo... | home.push("Ethereum");
home | random_line_split |
geth.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
pub fn open(t: DirectoryType) -> Self {
GethDirectory {
dir: DiskDirectory::at(geth_keystore(t)),
}
}
}
impl KeyDirectory for GethDirectory {
fn load(&self) -> Result<Vec<SafeAccount>, Error> {
self.dir.load()
}
fn insert(&self, account: SafeAccount) -> Result<SafeAccount, Error> {
self.dir.insert(a... | {
let result = GethDirectory {
dir: try!(DiskDirectory::create(geth_keystore(t))),
};
Ok(result)
} | identifier_body |
deep-diff.d.ts | // Type definitions for deep-diff
// Project: https://github.com/flitbit/diff/
// Definitions by: ZauberNerd <https://github.com/ZauberNerd/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module deepDiff {
interface IDiff {
kind: string;
path: string[];
lhs: any;
... | applyDiff(target: Object, source: Object, filter: Function): void;
applyChange(target: Object, source: Object, change: IDiff): void;
revertChange(target: Object, source: Object, change: IDiff): void;
isConflict(): boolean;
noConflict(): IDeepDiff;
}
}
declare var diff: deepD... | observableDiff(lhs: Object, rhs: Object, changes: Function, prefilter?: IPrefilter, path?: string[], key?: string, stack?: Object[]): void; | random_line_split |
part1.rs | // adventofcode - day 12
// part 1
use std::io::prelude::*;
use std::fs::File;
fn main() |
// This function simply imports the data set from a file called input.txt
fn import_data() -> String {
let mut file = match File::open("../../inputs/12.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
... | {
println!("Advent of Code - day 12 | part 1");
// import data
let data = import_data();
let mut value = 0i32;
let mut tmp_val = 0i32;
let mut last: char = '\x00';
let mut multiplier = 1;
for ch in data.chars() {
value += match ch {
'0'...'9' => {
if... | identifier_body |
part1.rs | // adventofcode - day 12
// part 1
use std::io::prelude::*;
use std::fs::File;
fn main(){
println!("Advent of Code - day 12 | part 1");
// import data
let data = import_data();
let mut value = 0i32;
let mut tmp_val = 0i32;
let mut last: char = '\x00';
let mut multiplier = 1;
for ch i... | } | random_line_split | |
part1.rs | // adventofcode - day 12
// part 1
use std::io::prelude::*;
use std::fs::File;
fn main(){
println!("Advent of Code - day 12 | part 1");
// import data
let data = import_data();
let mut value = 0i32;
let mut tmp_val = 0i32;
let mut last: char = '\x00';
let mut multiplier = 1;
for ch i... | () -> String {
let mut file = match File::open("../../inputs/12.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
Ok(_) => {},
Err(e) => panic!("file error: {}", e),
};
data
}
| import_data | identifier_name |
test_init.py | import os
import sys
import pytest
import vtk
import pyvista
developer_note = """
vtk has been directly imported in vtk>=9
Please see:
https://github.com/pyvista/pyvista/pull/1163
"""
@pytest.mark.skipif(not pyvista._vtk.VTK9,
reason='``vtk`` can be loaded directly on vtk<9')
def test_vtk_not_lo... |
# validate all lazy loads
lazy_readers = ['vtkGL2PSExporter',
'vtkFacetReader',
'vtkPDataSetReader',
'vtkMultiBlockPLOT3DReader',
'vtkPlot3DMetaReader']
if pyvista._vtk.VTK9:
lazy_readers.append('vtkSegYReader')
@pytest.mark.parametrize("cls_", laz... | """This test verifies that the vtk module isn't loaded when using vtk>=9
We use ``os.system`` because we need to test the import of pyvista
outside of the pytest unit test framework as pytest loads vtk.
"""
exe_str = "import pyvista; import sys; assert 'vtk' not in sys.modules"
# anything other t... | identifier_body |
test_init.py | import os
import sys
import pytest
import vtk
import pyvista
developer_note = """
vtk has been directly imported in vtk>=9
Please see:
https://github.com/pyvista/pyvista/pull/1163
"""
@pytest.mark.skipif(not pyvista._vtk.VTK9,
reason='``vtk`` can be loaded directly on vtk<9')
def | ():
"""This test verifies that the vtk module isn't loaded when using vtk>=9
We use ``os.system`` because we need to test the import of pyvista
outside of the pytest unit test framework as pytest loads vtk.
"""
exe_str = "import pyvista; import sys; assert 'vtk' not in sys.modules"
# anything... | test_vtk_not_loaded | identifier_name |
test_init.py | import os
import sys
import pytest
import vtk
import pyvista
developer_note = """
vtk has been directly imported in vtk>=9
Please see:
https://github.com/pyvista/pyvista/pull/1163
"""
@pytest.mark.skipif(not pyvista._vtk.VTK9,
reason='``vtk`` can be loaded directly on vtk<9')
def test_vtk_not_lo... | # validate all lazy loads
lazy_readers = ['vtkGL2PSExporter',
'vtkFacetReader',
'vtkPDataSetReader',
'vtkMultiBlockPLOT3DReader',
'vtkPlot3DMetaReader']
if pyvista._vtk.VTK9:
lazy_readers.append('vtkSegYReader')
@pytest.mark.parametrize("cls_", lazy_r... | assert not os.system(f'{sys.executable} -c "{exe_str}"'), developer_note
| random_line_split |
test_init.py | import os
import sys
import pytest
import vtk
import pyvista
developer_note = """
vtk has been directly imported in vtk>=9
Please see:
https://github.com/pyvista/pyvista/pull/1163
"""
@pytest.mark.skipif(not pyvista._vtk.VTK9,
reason='``vtk`` can be loaded directly on vtk<9')
def test_vtk_not_lo... |
@pytest.mark.parametrize("cls_", lazy_readers)
def test_lazy_loads(cls_):
lazy_class = getattr(pyvista._vtk, 'lazy_' + cls_)()
actual_class = getattr(vtk, cls_)()
# can't use isinstance here because these are classes
assert type(lazy_class) == type(actual_class)
| lazy_readers.append('vtkSegYReader') | conditional_block |
single-selection-controller.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
// Style preference for leading underscores.
// tslint:disable:strip-private-property-underscore
/**
* Unique symbol for marking roots
*/
const selectionController = Symbol('selection controller');
/**
* Set of checkable eleme... |
}
| {
if (this.updating) {
return;
}
this.updating = true;
const set = this.getSet(element.name);
if (element.checked) {
for (const e of set.set) {
if (e == element) {
continue;
}
e.checked = false;
}
set.selected = element;
}
// When ta... | identifier_body |
single-selection-controller.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
// Style preference for leading underscores.
// tslint:disable:strip-private-property-underscore
/**
* Unique symbol for marking roots
*/
const selectionController = Symbol('selection controller');
/**
* Set of checkable eleme... | (element: Node) {
element.addEventListener('keydown', (e: Event) => {
this.keyDownHandler(e as KeyboardEvent);
});
element.addEventListener('mousedown', () => {
this.mousedownHandler();
});
element.addEventListener('mouseup', () => {
this.mouseupHandler();
});
}
protected ... | constructor | identifier_name |
single-selection-controller.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
// Style preference for leading underscores.
// tslint:disable:strip-private-property-underscore
/**
* Unique symbol for marking roots
*/
const selectionController = Symbol('selection controller');
/**
* Set of checkable eleme... | if (e.key == 'ArrowRight' || e.key == 'ArrowDown') {
this.selectNext(element);
} else if (e.key == 'ArrowLeft' || e.key == 'ArrowUp') {
this.selectPrevious(element);
}
}
protected mousedownHandler() {
this.mouseIsDown = true;
}
protected mouseupHandler() {
this.mouseIsDown = fa... | return;
}
if (!this.has(element)) {
return;
} | random_line_split |
single-selection-controller.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
// Style preference for leading underscores.
// tslint:disable:strip-private-property-underscore
/**
* Unique symbol for marking roots
*/
const selectionController = Symbol('selection controller');
/**
* Set of checkable eleme... | else if (e.key == 'ArrowLeft' || e.key == 'ArrowUp') {
this.selectPrevious(element);
}
}
protected mousedownHandler() {
this.mouseIsDown = true;
}
protected mouseupHandler() {
this.mouseIsDown = false;
}
/**
* Whether or not the controller controls the given element.
*
* @par... | {
this.selectNext(element);
} | conditional_block |
driver.py | # -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john at nachtimwald.com>'
__docformat__ = 'restructuredtext en'
'''
Generic USB Mass storage device driver. This is not a complete stand alone
driver. It is intended to be subclassed with the relevant parts implemented
for a partic... | changed = update_booklist(f['filename'], f['path'], prefix)
if changed:
need_sync = True
else:
paths = os.listdir(ebook_dir)
for i, filename in enumerate(paths):
self.report_progress((i+1) / f... | random_line_split | |
driver.py | # -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john at nachtimwald.com>'
__docformat__ = 'restructuredtext en'
'''
Generic USB Mass storage device driver. This is not a complete stand alone
driver. It is intended to be subclassed with the relevant parts implemented
for a partic... | (filename, path, prefix):
changed = False
if path_to_ext(filename) in all_formats:
try:
lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2]
if lpath.startswith(os.sep):
lpath = lpath[len(os... | update_booklist | identifier_name |
driver.py | # -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john at nachtimwald.com>'
__docformat__ = 'restructuredtext en'
'''
Generic USB Mass storage device driver. This is not a complete stand alone
driver. It is intended to be subclassed with the relevant parts implemented
for a partic... |
@classmethod
def metadata_from_formats(cls, fmts):
from calibre.ebooks.metadata.meta import metadata_from_formats
from calibre.customize.ui import quick_metadata
with quick_metadata:
return metadata_from_formats(fmts, force_read_metadata=True,
... | return cls.metadata_from_formats([path]) | identifier_body |
driver.py | # -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john at nachtimwald.com>'
__docformat__ = 'restructuredtext en'
'''
Generic USB Mass storage device driver. This is not a complete stand alone
driver. It is intended to be subclassed with the relevant parts implemented
for a partic... |
book = self.book_class(prefix, lpath, other=info)
if book.size is None:
book.size = os.stat(self.normalize_path(path)).st_size
b = booklists[blist].add_book(book, replace_metadata=True)
if b:
b._new_book = True
self.report_progress... | lpath = lpath[1:] | conditional_block |
Code.py | #!/usr/bin/env python
# Copyright NumFOCUS
#
# 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.txt
#
# Unless required by applicable law or ... |
else:
extension = ".png"
fileNameFormat = outputFileName + "-%d" + extension
Dimension = 3
PixelType = itk.UC
InputImageType = itk.Image[PixelType, Dimension]
ReaderType = itk.ImageFileReader[InputImageType]
reader = ReaderType.New()
reader.SetFileName(inputFileName)
OutputPixelType = itk.UC
RescaleImageType ... | extension = sys.argv[3] | conditional_block |
Code.py | #!/usr/bin/env python
# Copyright NumFOCUS
#
# 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.txt
#
# Unless required by applicable law or ... | PixelType = itk.UC
InputImageType = itk.Image[PixelType, Dimension]
ReaderType = itk.ImageFileReader[InputImageType]
reader = ReaderType.New()
reader.SetFileName(inputFileName)
OutputPixelType = itk.UC
RescaleImageType = itk.Image[OutputPixelType, Dimension]
RescaleFilterType = itk.RescaleIntensityImageFilter[InputI... |
Dimension = 3
| random_line_split |
data.rs | use redox::prelude::v1::*;
use table::NodeTable;
/// A data node (file/dir)
pub enum Data {
/// File
File(File),
/// Directory
Dir(Dir),
/// Nothing
Nil,
}
impl Data {
pub fn name(&self) -> &str {
match self {
&Data::File(ref f) => &f.name,
&Data::Dir(ref d)... |
/// A file
pub struct File {
/// The name of the file
name: String,
/// The actual content of the file
data: Vec<u8>,
}
impl File {
/// Create a file from a slice of bytes
pub fn from_bytes(b: &[u8]) -> Self {
let name = unsafe {
String::from_utf8_unchecked(b[0..64].to_vec(... | } | random_line_split |
data.rs | use redox::prelude::v1::*;
use table::NodeTable;
/// A data node (file/dir)
pub enum Data {
/// File
File(File),
/// Directory
Dir(Dir),
/// Nothing
Nil,
}
impl Data {
pub fn | (&self) -> &str {
match self {
&Data::File(ref f) => &f.name,
&Data::Dir(ref d) => &d.name,
&Data::Nil => "\0",
}
}
}
/// A file
pub struct File {
/// The name of the file
name: String,
/// The actual content of the file
data: Vec<u8>,
}
impl Fil... | name | identifier_name |
noDefaultImportRule.d.ts | /**
* @license
* Copyright 2016 Palantir Technologies, Inc.
*
* 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... | extends Lint.Rules.AbstractRule {
static metadata: Lint.IRuleMetadata;
static FAILURE_STRING: string;
static getNamedDefaultImport(namedBindings: ts.NamedImports): ts.Identifier | null;
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[];
private isFromModulesConfigOption;
private getRuleOptio... | Rule | identifier_name |
noDefaultImportRule.d.ts | /**
* @license
* Copyright 2016 Palantir Technologies, Inc.
*
* 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
* | */
import * as ts from "typescript";
import * as Lint from "../index";
export declare class Rule extends Lint.Rules.AbstractRule {
static metadata: Lint.IRuleMetadata;
static FAILURE_STRING: string;
static getNamedDefaultImport(namedBindings: ts.NamedImports): ts.Identifier | null;
apply(sourceFile: ts... | * 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
* limitations under the License. | random_line_split |
parser.rs | mod lex;
use lex::lexeme::Lexeme;
pub struct Parser<'a> {
next: usize,
tokens: Vec<Lexeme>
}
impl<'a> Parser<'a> {
pub fn new(tokens: Vec<Lexeme>) -> Parser {
Parser {
next: 0,
tokens: tokens
}
}
pub fn parse(&self) -> Box<Expr> {
let mut block: Vec... | (&self) -> bool {
match self.get_token() {
Lexeme::Plus | Lexeme::Minus | Lexeme::Multiply | Lexeme::Divide | Lexeme::Modulo => true,
_ => false
}
}
}
| operator | identifier_name |
parser.rs | mod lex;
use lex::lexeme::Lexeme;
pub struct Parser<'a> {
next: usize,
tokens: Vec<Lexeme>
}
impl<'a> Parser<'a> {
pub fn new(tokens: Vec<Lexeme>) -> Parser {
Parser {
next: 0,
tokens: tokens
}
}
pub fn parse(&self) -> Box<Expr> {
let mut block: Vec... |
fn expect(&self, token: Lexeme) -> bool {
if self.get_token() == token { true } else { false }
}
fn operator(&self) -> bool {
match self.get_token() {
Lexeme::Plus | Lexeme::Minus | Lexeme::Multiply | Lexeme::Divide | Lexeme::Modulo => true,
_ => false
}
... | {
self.next == tokens.len()
} | identifier_body |
parser.rs | mod lex; | pub struct Parser<'a> {
next: usize,
tokens: Vec<Lexeme>
}
impl<'a> Parser<'a> {
pub fn new(tokens: Vec<Lexeme>) -> Parser {
Parser {
next: 0,
tokens: tokens
}
}
pub fn parse(&self) -> Box<Expr> {
let mut block: Vec<Box<Expr>> = Vec::new();
... | use lex::lexeme::Lexeme;
| random_line_split |
bytenet_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# 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... |
if __name__ == "__main__":
tf.test.main()
| def testByteNet(self):
vocab_size = 9
x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1))
y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1))
hparams = bytenet.bytenet_base()
p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size)
with s... | identifier_body |
bytenet_test.py | # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# 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... | tf.test.main() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.