file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
build.rs | use std::path::Path;
use std::path::PathBuf;
use std::env;
use std::process::Command;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let target = env::var("TARGET").unwrap();
// http://doc.crates.io/build-script.html#inputs-to-the-build-script
// "the build script’s current directory is the ... | let qt_dir_default = home_dir.join("Qt")
.join(env::var("QT_VER").unwrap_or(default_qt_ver))
.join(env::var("QT_COMP").unwrap_or(default_qt_comp));
qt_dir_default
});
println!("Using Qt directory: {:?}", qt_dir);
println!("U... | println!(" QT_COMP: {}", default_qt_comp); | random_line_split |
build.rs | use std::path::Path;
use std::path::PathBuf;
use std::env;
use std::process::Command;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let target = env::var("TARGET").unwrap();
// http://doc.crates.io/build-script.html#inputs-to-the-build-script
// "the build script’s current directory is the ... | e {
panic!("Unsuported platform in gallery's build.rs!")
};
println!(" QT_VER: {}", default_qt_ver);
println!(" QT_COMP: {}", default_qt_comp);
let qt_dir_default = home_dir.join("Qt")
.join(env::var("QT_VER").unwrap_or(default_qt_ver)... | "clang_64".to_string()
} els | conditional_block |
JsResource.js | function JsResource(uri,$$jsResource){
$init$JsResource();
if($$jsResource===undefined)$$jsResource=new JsResource.$$;
$$jsResource.uri_=uri;
Resource($$jsResource);
$$jsResource.$prop$getUri={$crtmm$:function(){return{mod:$CCMM$,$t:{t:$_String},$cont:JsResource,an:function(){return[shared(),actual()];},d:['$... | else {
throw Error("Resource handling unsupported in this JS platform");
}
};$$jsResource.textContent.$crtmm$=function(){return{mod:$CCMM$,$t:{t:$_String},ps:[{nm:'encoding',mt:'prm',def:1,$t:{t:$_String},an:function(){return[];}}],$cont:JsResource,an:function(){return[shared(),actual()];},d:['... | {
alert("Resource.textContent() not implemented yet");
} | conditional_block |
JsResource.js | function JsResource(uri,$$jsResource){
$init$JsResource();
if($$jsResource===undefined)$$jsResource=new JsResource.$$;
$$jsResource.uri_=uri;
Resource($$jsResource);
$$jsResource.$prop$getUri={$crtmm$:function(){return{mod:$CCMM$,$t:{t:$_String},$cont:JsResource,an:function(){return[shared(),actual()];},d:['$... | print("Resource handling unsupported in this JS platform.");
}
return -1;
},undefined,function(){return{mod:$CCMM$,$t:{t:Integer},$cont:JsResource,an:function(){return[shared(),actual()];},d:['$','Resource','$at','size']};});
$$jsResource.textContent=function textConte... | } else { | random_line_split |
JsResource.js | function JsResource(uri,$$jsResource){
$init$JsResource();
if($$jsResource===undefined)$$jsResource=new JsResource.$$;
$$jsResource.uri_=uri;
Resource($$jsResource);
$$jsResource.$prop$getUri={$crtmm$:function(){return{mod:$CCMM$,$t:{t:$_String},$cont:JsResource,an:function(){return[shared(),actual()];},d:['$... | (){
if(JsResource.$$===undefined){
initTypeProto(JsResource,'JsResource',Basic,Resource);
(function($$jsResource){
atr$($$jsResource,'uri',function(){return this.uri_;},undefined,function(){return{mod:$CCMM$,$t:{t:$_String},$cont:JsResource,an:function(){return[shared(),actual()];},d:['$','Resource','$a... | $init$JsResource | identifier_name |
JsResource.js | function JsResource(uri,$$jsResource) |
JsResource.$crtmm$=function(){return{mod:$CCMM$,'super':{t:Basic},ps:[{nm:'uri',mt:'prm',$t:{t:$_String},an:function(){return[shared(),actual()];}}],satisfies:[{t:Resource}],d:['$','Resource']};};
function $init$JsResource(){
if(JsResource.$$===undefined){
initTypeProto(JsResource,'JsResource',Basic,Resource);
... | {
$init$JsResource();
if($$jsResource===undefined)$$jsResource=new JsResource.$$;
$$jsResource.uri_=uri;
Resource($$jsResource);
$$jsResource.$prop$getUri={$crtmm$:function(){return{mod:$CCMM$,$t:{t:$_String},$cont:JsResource,an:function(){return[shared(),actual()];},d:['$','Resource','$at','uri']};}};
$$js... | identifier_body |
Rect.d.ts | import Terminal = require("./Terminal");
import ScreenBuffer = require("./ScreenBuffer");
import TextBuffer = require("./TextBuffer");
declare class Rect {
readonly width: number;
readonly height: number;
readonly xmin: number;
readonly ymin: number;
readonly xmax: number;
readonly ymax: number;
readonly... | offsetY: number;
wrapOnly?: "x" | "y" | undefined;
}): void;
set(obj: Rect.Region): void;
clip(
dstRect: Rect,
offsetX: number,
offsetY: number,
dstClipping: boolean
): void;
}
export = Rect;
declare namespace Rect {
type Options = AbsoluteOptions | Region;
interface AbsoluteOpt... |
static wrappingRect(params: {
srcRect: Rect;
dstRect: Rect;
offsetX: number; | random_line_split |
Rect.d.ts | import Terminal = require("./Terminal");
import ScreenBuffer = require("./ScreenBuffer");
import TextBuffer = require("./TextBuffer");
declare class | {
readonly width: number;
readonly height: number;
readonly xmin: number;
readonly ymin: number;
readonly xmax: number;
readonly ymax: number;
readonly isNull: boolean;
constructor(
options:
| Rect.AbsoluteOptions
| Rect.Region
| Rect
| Terminal
| ScreenBuffer
|... | Rect | identifier_name |
app.js | error:not-logged-in]]');
}
require(['chat'], function (chat) {
function loadAndCenter(chatModal) {
chat.load(chatModal.attr('UUID'));
chat.center(chatModal);
chat.focusInput(chatModal);
}
if (chat.modalExists(roomId)) {
loadAndCenter(chat.getModal(roomId));
} else {
socket.emit('mo... | });
}); | random_line_split | |
app.js | function(taskbar, helpers, pagination) {
taskbar.init();
// templates.js helpers
helpers.register();
pagination.init();
$(window).trigger('action:app.load');
});
};
app.logout = function() {
$.ajax(config.relative_path + '/logout', {
type: 'POST',
headers: {
'x-csrf-token': config.cs... | (chatModal) {
chat.load(chatModal.attr('UUID'));
chat.center(chatModal);
chat.focusInput(chatModal);
}
if (chat.modalExists(roomId)) {
loadAndCenter(chat.getModal(roomId));
} else {
socket.emit('modules.chats.loadRoom', {roomId: roomId}, function(err, roomData) {
if (err) {
retu... | loadAndCenter | identifier_name |
app.js | (taskbar, helpers, pagination) {
taskbar.init();
// templates.js helpers
helpers.register();
pagination.init();
$(window).trigger('action:app.load');
});
};
app.logout = function() {
$.ajax(config.relative_path + '/logout', {
type: 'POST',
headers: {
'x-csrf-token': config.csrf_token
... |
});
};
app.processPage = function () {
highlightNavigationLink();
$('.timeago').timeago();
utils.makeNumbersHumanReadable($('.human-readable-number'));
utils.addCommasToNumbers($('.formatted-number'));
app.createUserTooltips();
app.createStatusTooltips();
app.replaceSelfLinks();
// Scroll b... | {
$(this).attr('href', href.replace(/user\/_self_/g, 'user/' + app.user.userslug));
} | conditional_block |
app.js | (taskbar, helpers, pagination) {
taskbar.init();
// templates.js helpers
helpers.register();
pagination.init();
$(window).trigger('action:app.load');
});
};
app.logout = function() {
$.ajax(config.relative_path + '/logout', {
type: 'POST',
headers: {
'x-csrf-token': config.csrf_token
... |
searchButton.on('click', function(e | {
searchFields.addClass('hidden');
searchButton.removeClass('hidden');
} | identifier_body |
models.js | var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
, relationships = require('../../index'); // require('mongoose-relationships');
/**
* Blog Post Schema
* "belongs to one author"
*/
var PostSchema = new Schema({
title : String
, body : String
, autho... | hasMany : "Post"
, through : "posts"
});
/**
* Register the models with Mongoose
*/
var Post = mongoose.model('Post', PostSchema)
, User = mongoose.model('User', UserSchema);
// Have fun here:
var user = new User();
user.posts.create({
title: "Mongoose, now with added love through relationships!"
}, ... | PostSchema.plugin(relationships, {
belongsTo : "User"
, through : "author"
});
UserSchema.plugin(relationships, { | random_line_split |
WantLinks.py | #!/usr/bin/pythonTest
# -*- coding: utf-8 -*-
#
# Web functions want links
#
# 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 vers... | ( sReadFile, sOutFile ):
#
from File.Get import getListFromFileLines
from File.Write import QuickDumpLines
#
from Web.Address import getHostPathTuple, getDomainOffURL
from Web.Test import isURL
#
lLines = getListFromFileLines( sReadFile )
#
setLinks= frozenset... | getUniqueLinks | identifier_name |
WantLinks.py | #!/usr/bin/pythonTest
# -*- coding: utf-8 -*-
#
# Web functions want links
#
# 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 vers... | #
lLines = getListFromFileLines( sReadFile )
#
setLinks= frozenset( filter( isURL, lLines ) )
#
#
lDecorate = [ ( getHostPathTuple( sURL ), sURL ) for sURL in setLinks ]
#
lDecorate = [ ( ( getDomainOffURL( t[0][0] ), t[0][1] ), t[1] ) for t in lDecorate ]
#
lDecorate.sort()... | random_line_split | |
WantLinks.py | #!/usr/bin/pythonTest
# -*- coding: utf-8 -*-
#
# Web functions want links
#
# 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 vers... |
if __name__ == "__main__":
#
from os.path import join
from sys import argv
#
from six import print_ as print3
#
from Dir.Get import sTempDir
from File.Test import isFileThere
from Utils.Result import sayTestResult
#
lProblems = ... | from File.Get import getListFromFileLines
from File.Write import QuickDumpLines
#
from Web.Address import getHostPathTuple, getDomainOffURL
from Web.Test import isURL
#
lLines = getListFromFileLines( sReadFile )
#
setLinks= frozenset( filter( isURL, lLines ) )
#
... | identifier_body |
WantLinks.py | #!/usr/bin/pythonTest
# -*- coding: utf-8 -*-
#
# Web functions want links
#
# 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 vers... |
else:
#
if isFileThere( sReadFile ):
#
getUniqueLinks( sReadFile, sOutFile )
#
else:
#
print3( 'Usage: WantLinks [inputFile [, outputFile] ]' )
print3( 'default inputFile {temp dir}lotsolinks.txt' )
print3(... | sReadFile = args[0]
#
if len( args ) > 1:
#
sOutFile = args[2]
#
# | conditional_block |
Start.py | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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) ... |
def LoadPress():
global StartWindow
if StartWindow:
StartWindow.Unload()
GemRB.SetNextScript("GUILOAD")
return
def QuickLoadPress():
global StartWindow, QuickLoadSlot
LoadScreen.StartLoadScreen()
GemRB.LoadGame(QuickLoadSlot) # load & start game
GemRB.EnterGame()
return
def OptionsPress():
global Star... | global StartWindow, ProtocolWindow
if ProtocolWindow:
ProtocolWindow.Unload()
ProtocolButton = StartWindow.GetControl(0x00)
LastProtocol = GemRB.GetVar("Last Protocol Used")
if LastProtocol == 0:
ProtocolButton.SetText(15413)
elif LastProtocol == 1:
ProtocolButton.SetText(13967)
elif LastProtocol == 2:
... | identifier_body |
Start.py | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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) ... | VersionLabel = StartWindow.GetControl(0x0fff0000)
VersionLabel.SetText(GEMRB_VERSION)
ProtocolButton.SetStatus(IE_GUI_BUTTON_ENABLED)
NewGameButton.SetStatus(IE_GUI_BUTTON_ENABLED)
LoadGameButton.SetStatus(IE_GUI_BUTTON_ENABLED)
GemRB.SetVar("SaveDir",1)
Games=GemRB.GetSaveGames()
#looking for the quicksave
... | random_line_split | |
Start.py | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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) ... |
GemRB.SetNextScript("SPParty")
return
def QuitCancelPress():
global StartWindow, QuitWindow
if QuitWindow:
QuitWindow.Unload()
StartWindow.SetVisible(WINDOW_VISIBLE)
return
def QuitQuitPress():
GemRB.Quit()
return
| StartWindow.Unload() | conditional_block |
Start.py | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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) ... | ():
global StartWindow, QuickLoadSlot
LoadScreen.StartLoadScreen()
GemRB.LoadGame(QuickLoadSlot) # load & start game
GemRB.EnterGame()
return
def OptionsPress():
global StartWindow
if StartWindow:
StartWindow.Unload()
GemRB.SetNextScript("Options")
return
def QuitPress():
global StartWindow, QuitWindow
... | QuickLoadPress | identifier_name |
tokens.rs | use std::collections::HashMap;
pub use self::Block::*;
pub use self::Inline::*;
pub type Document = Vec<Block>;
pub type Text = Vec<Inline>;
pub type LinkMap = HashMap<String, LinkDescription>;
pub struct LinkDescription {
pub id: String,
pub link: String,
pub title: Option<String>
}
#[derive(PartialE... | }
}
}
| {
match *self {
Emphasis(ref mut content) | MoreEmphasis(ref mut content) =>
content.fix_links(link_map),
Link { ref mut link, ref mut title, id: Some(ref id), .. } => {
match link_map.get(id) {
Some(ld) => {
if... | identifier_body |
tokens.rs | use std::collections::HashMap;
pub use self::Block::*;
pub use self::Inline::*;
pub type Document = Vec<Block>;
pub type Text = Vec<Inline>;
pub type LinkMap = HashMap<String, LinkDescription>;
pub struct LinkDescription {
pub id: String,
pub link: String,
pub title: Option<String>
}
#[derive(PartialE... | OrderedList { ref mut items, .. } | UnorderedList { ref mut items } =>
for item in items.iter_mut() {
item.fix_links(link_map);
},
Paragraph(ref mut content) | Heading { ref mut content, .. } =>
content.fix_links(link_map),
... | impl FixLinks for Block {
fn fix_links(&mut self, link_map: &LinkMap) {
match *self {
BlockQuote(ref mut content) => content.fix_links(link_map),
| random_line_split |
tokens.rs | use std::collections::HashMap;
pub use self::Block::*;
pub use self::Inline::*;
pub type Document = Vec<Block>;
pub type Text = Vec<Inline>;
pub type LinkMap = HashMap<String, LinkDescription>;
pub struct LinkDescription {
pub id: String,
pub link: String,
pub title: Option<String>
}
#[derive(PartialE... |
}
}
fn fix_links(&mut self, link_map: &LinkMap);
}
impl FixLinks for Block {
fn fix_links(&mut self, link_map: &LinkMap) {
match *self {
BlockQuote(ref mut content) => content.fix_links(link_map),
OrderedList { ref mut items, .. } | UnorderedList { ref mut items }... | {} | conditional_block |
tokens.rs | use std::collections::HashMap;
pub use self::Block::*;
pub use self::Inline::*;
pub type Document = Vec<Block>;
pub type Text = Vec<Inline>;
pub type LinkMap = HashMap<String, LinkDescription>;
pub struct LinkDescription {
pub id: String,
pub link: String,
pub title: Option<String>
}
#[derive(PartialE... | (&mut self, link_map: &LinkMap) {
match *self {
Emphasis(ref mut content) | MoreEmphasis(ref mut content) =>
content.fix_links(link_map),
Link { ref mut link, ref mut title, id: Some(ref id), .. } => {
match link_map.get(id) {
Some(ld)... | fix_links | identifier_name |
ExifToolsScan.py | # 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/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
import os
import sys
i... |
def scan(filelist, conf=DEFAULTCONF):
if os.path.isfile(conf["path"]):
local = True
elif SSH:
local = False
cmdline = conf["cmdline"]
results = []
output = ""
cmd = cmdline
for item in filelist:
cmd.append('"' + item + '" ')
cmd.insert(0, conf["path"])
ho... | if not conf['ENABLED']:
return False
if os.path.isfile(conf["path"]):
if 'replacement path' in conf:
del conf['replacement path']
return True
if SSH:
return True
else:
return False | identifier_body |
ExifToolsScan.py | # 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/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
import os
import sys
i... | (conf=DEFAULTCONF):
if not conf['ENABLED']:
return False
if os.path.isfile(conf["path"]):
if 'replacement path' in conf:
del conf['replacement path']
return True
if SSH:
return True
else:
return False
def scan(filelist, conf=DEFAULTCONF):
if os.... | check | identifier_name |
ExifToolsScan.py | # 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/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
import os
import sys
i... | results = []
output = ""
cmd = cmdline
for item in filelist:
cmd.append('"' + item + '" ')
cmd.insert(0, conf["path"])
host, port, user = conf["host"]
if local:
try:
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
... | cmdline = conf["cmdline"] | random_line_split |
ExifToolsScan.py | # 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/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
import os
import sys
i... |
except Exception as e:
# TODO: log exception
pass
try:
if row[0] not in conf['remove-entry']:
data[row[0]] = row[1]
except Exception as e:
# TODO: log exception
continue
if data:
results.append((fname, data)... | if data:
results.append((fname, data))
data = {}
fname = row[0][9:]
if re.match('[A-Za-z]:/', fname):
# why exif tools, whyyyyyyyy
fname = fname.replace('/', '\\')
continue | conditional_block |
incar.py | import os
from .input import VaspInput
__author__ = "Guillermo Avendano-Franco"
__copyright__ = "Copyright 2016"
__version__ = "0.1"
__maintainer__ = "Guillermo Avendano-Franco"
__email__ = "gtux.gaf@gmail.com"
__status__ = "Development"
__date__ = "May 13, 2016"
def read_incar(filename='INCAR'):
"""
Load t... | iv.write(filename) | if os.path.isdir(filepath):
filename = filepath + '/INCAR'
else:
filename = filepath
| random_line_split |
incar.py | import os
from .input import VaspInput
__author__ = "Guillermo Avendano-Franco"
__copyright__ = "Copyright 2016"
__version__ = "0.1"
__maintainer__ = "Guillermo Avendano-Franco"
__email__ = "gtux.gaf@gmail.com"
__status__ = "Development"
__date__ = "May 13, 2016"
def | (filename='INCAR'):
"""
Load the file INCAR in the directory 'path' or
read directly the file 'path' and return an object
'inputvars' for pychemia
:param filename: (str) Filename of a INCAR file format
:return:
"""
if os.path.isfile(filename):
filename = filename
elif os.pat... | read_incar | identifier_name |
incar.py | import os
from .input import VaspInput
__author__ = "Guillermo Avendano-Franco"
__copyright__ = "Copyright 2016"
__version__ = "0.1"
__maintainer__ = "Guillermo Avendano-Franco"
__email__ = "gtux.gaf@gmail.com"
__status__ = "Development"
__date__ = "May 13, 2016"
def read_incar(filename='INCAR'):
|
def write_incar(iv, filepath='INCAR'):
"""
Takes an object inputvars from pychemia and
save the file INCAR in the directory 'path' or
save the file 'path' as a VASP INCAR file
:param iv: (VaspInput) VASP Input variables
:param filepath: (str) File path to write the INCAR file
"""
if... | """
Load the file INCAR in the directory 'path' or
read directly the file 'path' and return an object
'inputvars' for pychemia
:param filename: (str) Filename of a INCAR file format
:return:
"""
if os.path.isfile(filename):
filename = filename
elif os.path.isdir(filename) and os... | identifier_body |
incar.py | import os
from .input import VaspInput
__author__ = "Guillermo Avendano-Franco"
__copyright__ = "Copyright 2016"
__version__ = "0.1"
__maintainer__ = "Guillermo Avendano-Franco"
__email__ = "gtux.gaf@gmail.com"
__status__ = "Development"
__date__ = "May 13, 2016"
def read_incar(filename='INCAR'):
"""
Load t... |
else:
raise ValueError('[ERROR] INCAR path not found: %s' % filename)
iv = VaspInput(filename=filename)
return iv
def write_incar(iv, filepath='INCAR'):
"""
Takes an object inputvars from pychemia and
save the file INCAR in the directory 'path' or
save the file 'path' as a VASP I... | filename += '/INCAR' | conditional_block |
skip_while.rs | use core::iter::*;
#[test]
fn test_iterator_skip_while() {
let xs = [0, 1, 2, 3, 5, 13, 15, 16, 17, 19];
let ys = [15, 16, 17, 19];
let it = xs.iter().skip_while(|&x| *x < 15);
let mut i = 0;
for x in it {
assert_eq!(*x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
... | () {
let f = &|acc, x| i32::checked_add(2 * acc, x);
fn p(&x: &i32) -> bool {
(x % 10) <= 5
}
assert_eq!((1..20).skip_while(p).try_fold(7, f), (6..20).try_fold(7, f));
let mut iter = (1..20).skip_while(p);
assert_eq!(iter.nth(5), Some(11));
assert_eq!(iter.try_fold(7, f), (12..20).tr... | test_skip_while_try_fold | identifier_name |
skip_while.rs | use core::iter::*;
#[test]
fn test_iterator_skip_while() {
let xs = [0, 1, 2, 3, 5, 13, 15, 16, 17, 19];
let ys = [15, 16, 17, 19];
let it = xs.iter().skip_while(|&x| *x < 15);
let mut i = 0;
for x in it {
assert_eq!(*x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
... | #[test]
fn test_skip_while_try_fold() {
let f = &|acc, x| i32::checked_add(2 * acc, x);
fn p(&x: &i32) -> bool {
(x % 10) <= 5
}
assert_eq!((1..20).skip_while(p).try_fold(7, f), (6..20).try_fold(7, f));
let mut iter = (1..20).skip_while(p);
assert_eq!(iter.nth(5), Some(11));
assert_e... | });
assert_eq!(i, ys.len());
}
| random_line_split |
skip_while.rs | use core::iter::*;
#[test]
fn test_iterator_skip_while() {
let xs = [0, 1, 2, 3, 5, 13, 15, 16, 17, 19];
let ys = [15, 16, 17, 19];
let it = xs.iter().skip_while(|&x| *x < 15);
let mut i = 0;
for x in it {
assert_eq!(*x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
... |
assert_eq!((1..20).skip_while(p).try_fold(7, f), (6..20).try_fold(7, f));
let mut iter = (1..20).skip_while(p);
assert_eq!(iter.nth(5), Some(11));
assert_eq!(iter.try_fold(7, f), (12..20).try_fold(7, f));
let mut iter = (0..50).skip_while(|&x| (x % 20) < 15);
assert_eq!(iter.try_fold(0, i8::ch... | {
(x % 10) <= 5
} | identifier_body |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
#![allow(uppercase_variables)]
... | * want the script to receive it, then ask Lua to run it.
*/
L.newtable(); // We will pass a table
/*
* To put values into the table, we first push the index, then the
* value, and then call rawset() with the index of the table in the
* stack. Let's see why it's -3: In Lua, the value -1... | {
let mut L = lua::State::new();
L.openlibs(); // Load Lua libraries
// Load the file containing the script we are going to run
let path = Path::new("simpleapi.lua");
match L.loadfile(Some(&path)) {
Ok(_) => (),
Err(_) => {
// If something went wrong, error message is at... | identifier_body |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
#![allow(uppercase_variables)]
... |
// Get the returned value at the to of the stack (index -1)
let sum = L.tonumber(-1);
println!("Script returned: {}", sum);
L.pop(1); // Take the returned value out of the stack
// L's destructor will close the state for us
} | "Failed to run script: {}", L.describe(-1));
os::set_exit_status(1);
return;
}
} | random_line_split |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
#![allow(uppercase_variables)]
... | () {
let mut L = lua::State::new();
L.openlibs(); // Load Lua libraries
// Load the file containing the script we are going to run
let path = Path::new("simpleapi.lua");
match L.loadfile(Some(&path)) {
Ok(_) => (),
Err(_) => {
// If something went wrong, error message is... | main | identifier_name |
extend_corpora.rs | // Copyright 2015-2018 Deyan Ginev. See the LICENSE
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed
// except according to those terms.
use cortex::backend::Backend... | () {
// Note that we realize the initial import via a real cortex worker, but use a simply utility
// script for extensions. this is the case since the goal here is to do a simple sysadmin
// "maintenance update", rather than a full-blown "semantic" union operation
let backend = Backend::default();
// If inp... | main | identifier_name |
extend_corpora.rs | // Copyright 2015-2018 Deyan Ginev. See the LICENSE
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed
// except according to those terms.
use cortex::backend::Backend... |
// Then re-register all services, so that they pick up on the tasks
let register_start = time::get_time();
match corpus.select_services(&backend.connection) {
Ok(services) => {
for service in services {
let service_id = service.id;
if service_id > 2 {
println!(... | let extend_duration = (extend_end - extend_start).num_milliseconds();
println!(
"-- Extending corpus {:?} took {:?}ms",
corpus.name, extend_duration
); | random_line_split |
extend_corpora.rs | // Copyright 2015-2018 Deyan Ginev. See the LICENSE
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed
// except according to those terms.
use cortex::backend::Backend... | };
for corpus in corpora {
// First, build an importer, which will perform the extension
let importer = Importer {
corpus: corpus.clone(),
backend: Backend::default(),
cwd: Importer::cwd(),
};
// Extend the already imported corpus. I prefer that method name to "update", as we won... | {
// Note that we realize the initial import via a real cortex worker, but use a simply utility
// script for extensions. this is the case since the goal here is to do a simple sysadmin
// "maintenance update", rather than a full-blown "semantic" union operation
let backend = Backend::default();
// If input ... | identifier_body |
mod.rs | UnsafeCache<'a, Ast<'a>>,
/// Used to map paths to parse trees or name resolvers
pub modules: HashMap<PathBuf, ModuleId>,
/// Maps ModuleId -> NameResolver
pub name_resolvers: UnsafeCache<'a, NameResolver>,
/// Holds all the previously seen filenames referenced by Locations
/// Used to lengt... | /// The corresponding DefinitionInfoId is attatched to each
/// `ast::Variable` during name resolution.
#[derive(Debug)]
pub struct DefinitionInfo<'a> {
pub name: String,
pub location: Location<'a>,
/// Where this name was defined. It is expected that type checking
/// this Definition kind should resul... | /// Note that two variables defined in the same pattern, e.g: `(a, b) = c`
/// will have their own unique `DefinitionInfo`s, but each DefinitionInfo
/// will refer to the same `ast::Definition` in its definition field.
/// | random_line_split |
mod.rs | Cache<'a, Ast<'a>>,
/// Used to map paths to parse trees or name resolvers
pub modules: HashMap<PathBuf, ModuleId>,
/// Maps ModuleId -> NameResolver
pub name_resolvers: UnsafeCache<'a, NameResolver>,
/// Holds all the previously seen filenames referenced by Locations
/// Used to lengthen the... | (&self) -> Location<'a> {
self.location
}
}
/// An ImplScopeId is attached to an ast::Variable to remember
/// the impls that were in scope when it was used since scopes are
/// thrown away after name resolution but the impls in scope are still
/// needed during type inference.
/// TODO: The concept of an ... | locate | identifier_name |
ide.rs | use machine::{outb, inb, inl};
use malloc::must_allocate;
use core::slice;
use collections::Vec;
use paging::PAGE_SIZE;
const SECTOR_BYTES: usize = 512;
const PORTS: [u16; 2] = [0x1f0, 0x170];
#[inline]
fn controller(drive: u8) -> u8 { (drive >> 1) & 1 }
#[inline]
fn channel(drive: u8) -> u8 { drive & 1 }
#[inline]... |
}
Some(sector_count)
}
pub fn read_sectors(drive: u8, start_sector: u32, buffer: &mut [u32]) {
let base = port(drive);
let channel = channel(drive);
let longs = buffer.len() as u32;
let num_sectors = longs >> 7;
let mut sector = start_sector;
let end_sector = start_sector + num_sector... | {
sector_count = result;
} | conditional_block |
ide.rs | use machine::{outb, inb, inl};
use malloc::must_allocate;
use core::slice;
use collections::Vec;
use paging::PAGE_SIZE;
const SECTOR_BYTES: usize = 512;
const PORTS: [u16; 2] = [0x1f0, 0x170];
#[inline]
fn controller(drive: u8) -> u8 { (drive >> 1) & 1 }
#[inline]
fn channel(drive: u8) -> u8 { drive & 1 }
#[inline]... | wait_for_data(drive);
for _ in 0..(SECTOR_BYTES / ::core::mem::size_of::<u32>()) {
buffer[buffer_idx] = inl(base);
buffer_idx += 1;
}
}
sector += sector_count as u32;
}
}
// You have to manually free the pointer when you stop cari... | {
let base = port(drive);
let channel = channel(drive);
let longs = buffer.len() as u32;
let num_sectors = longs >> 7;
let mut sector = start_sector;
let end_sector = start_sector + num_sectors;
let mut buffer_idx = 0;
while sector < end_sector {
// Read as many sectors as you c... | identifier_body |
ide.rs | use machine::{outb, inb, inl};
use malloc::must_allocate;
use core::slice;
use collections::Vec;
use paging::PAGE_SIZE;
const SECTOR_BYTES: usize = 512;
const PORTS: [u16; 2] = [0x1f0, 0x170];
#[inline]
fn controller(drive: u8) -> u8 { (drive >> 1) & 1 }
#[inline]
fn channel(drive: u8) -> u8 { drive & 1 }
#[inline]... | outb(base + 7, 0x20);
for _ in 0..sector_count {
wait_for_data(drive);
for _ in 0..(SECTOR_BYTES / ::core::mem::size_of::<u32>()) {
buffer[buffer_idx] = inl(base);
buffer_idx += 1;
}
}
sector += sector_count as u32;
... | outb(base + 2, sector_count);
outb(base + 3, sector as u8);
outb(base + 4, (sector >> 8) as u8);
outb(base + 5, (sector >> 16) as u8);
outb(base + 6, 0xE0 | (channel << 4) | (((sector >> 24) & 0xf) as u8)); | random_line_split |
ide.rs | use machine::{outb, inb, inl};
use malloc::must_allocate;
use core::slice;
use collections::Vec;
use paging::PAGE_SIZE;
const SECTOR_BYTES: usize = 512;
const PORTS: [u16; 2] = [0x1f0, 0x170];
#[inline]
fn controller(drive: u8) -> u8 { (drive >> 1) & 1 }
#[inline]
fn channel(drive: u8) -> u8 { drive & 1 }
#[inline]... | (drive: u8) -> Option<Vec<u32>> {
sector_count(drive).map(|count| {
let bytes = (count as usize) * SECTOR_BYTES;
let longs = bytes >> 2;
unsafe {
let pointer = must_allocate(bytes, PAGE_SIZE) as *mut u32; // Code should be page-aligned
read_sectors(drive, 0, slice::fr... | slurp_drive | identifier_name |
core.py | """
#;+
#; NAME:
#; galaxy.core
#; Version 1.0
#;
#; PURPOSE:
#; Core routines for galaxy analysis
#; 29-Nov-2014 by JXP
#;-
#;------------------------------------------------------------------------------
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import os, copy,... |
else:
ras = str(ra)
if dec is None:
decs = '+00 00 00'
else:
decs = str(dec)
self.coord = SkyCoord(ras, decs, 'icrs', unit=(u.hour, u.deg))
# Name
self.name = ('J'+
self.coord.ra.to_string(unit=u.hour,sep='',pad=T... | ras = '00 00 00' | conditional_block |
core.py | """
#;+
#; NAME:
#; galaxy.core
#; Version 1.0
#;
#; PURPOSE:
#; Core routines for galaxy analysis
#; 29-Nov-2014 by JXP
#;-
#;------------------------------------------------------------------------------
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import os, copy,... | ## #################################
if __name__ == '__main__':
# Instantiate
gal = Galaxy()
print(gal) | ## TESTING | random_line_split |
core.py | """
#;+
#; NAME:
#; galaxy.core
#; Version 1.0
#;
#; PURPOSE:
#; Core routines for galaxy analysis
#; 29-Nov-2014 by JXP
#;-
#;------------------------------------------------------------------------------
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import os, copy,... | (object):
"""A Galaxy Class
Attributes:
name: string
Name(s)
z: float
Adopted redshift
coord: Coordinates
mstar: float
Stellar mass (MsolMass)
"""
# Initialize with a .dat file
def __init__(self, ra=None, dec=None, z=0.):
self.z = z
... | Galaxy | identifier_name |
core.py | """
#;+
#; NAME:
#; galaxy.core
#; Version 1.0
#;
#; PURPOSE:
#; Core routines for galaxy analysis
#; 29-Nov-2014 by JXP
#;-
#;------------------------------------------------------------------------------
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import os, copy,... | else:
ras = str(ra)
if dec is None:
decs = '+00 00 00'
else:
decs = str(dec)
self.coord = SkyCoord(ras, decs, 'icrs', unit=(u.hour, u.deg))
# Name
self.name = ('J'+
self.coord.ra.to_string(unit=u.hour,sep='',pad=Tr... | """A Galaxy Class
Attributes:
name: string
Name(s)
z: float
Adopted redshift
coord: Coordinates
mstar: float
Stellar mass (MsolMass)
"""
# Initialize with a .dat file
def __init__(self, ra=None, dec=None, z=0.):
self.z = z
... | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2013 by Erwin Marsi and TST-Centrale
#
# This file is part of the DAESO Framework.
#
# The DAESO Framework 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 Softwa... | (data_dir_prefix, dir):
# data_files specifies a sequence of (directory, files) pairs
# Each (directory, files) pair in the sequence specifies the installation directory
# and the files to install there.
data_files = []
for base, subdirs, files in walk(dir):
install_dir = join(data_dir_pr... | get_data_files | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2013 by Erwin Marsi and TST-Centrale
#
# This file is part of the DAESO Framework.
#
# The DAESO Framework 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 Softwa... |
# data files are installed under sys.prefix/share/pycornetto-%(version)
data_dir = join("share", "%s-%s" % (name, version))
data_files = [(data_dir, ['CHANGES', 'COPYING', 'INSTALL', 'README'])]
data_files += get_data_files(data_dir, "doc")
data_files += get_data_files(data_dir, "data")
sdist_options = dict(
f... | data_files = []
for base, subdirs, files in walk(dir):
install_dir = join(data_dir_prefix, base)
files = [ join(base, f) for f in files
if not f.endswith(".pyc") and not f.endswith("~") ]
data_files.append((install_dir, files))
if '.svn' in subdirs:
... | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2013 by Erwin Marsi and TST-Centrale
#
# This file is part of the DAESO Framework.
#
# The DAESO Framework 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 Softwa... | name = name,
version = version,
description = description,
long_description = long_description,
license = "GNU Public License v3",
author = "Erwin Marsi",
author_email = "e.marsi@gmail.com",
url = "https://github.com/emsrc/timbl-tools",
requires = ["networkx"],
provides = ["tt (... | setup( | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2013 by Erwin Marsi and TST-Centrale
#
# This file is part of the DAESO Framework.
#
# The DAESO Framework 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 Softwa... |
return data_files
# data files are installed under sys.prefix/share/pycornetto-%(version)
data_dir = join("share", "%s-%s" % (name, version))
data_files = [(data_dir, ['CHANGES', 'COPYING', 'INSTALL', 'README'])]
data_files += get_data_files(data_dir, "doc")
data_files += get_data_files(data_dir... | install_dir = join(data_dir_prefix, base)
files = [ join(base, f) for f in files
if not f.endswith(".pyc") and not f.endswith("~") ]
data_files.append((install_dir, files))
if '.svn' in subdirs:
subdirs.remove('.svn') # ignore svn directories | conditional_block |
safety_check_updates_child.ts | // Copyright 2020 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.
/**
* @fileoverview
* 'settings-safety-updates-child' is the settings page containing the safety
* check child showing the browser's update status.
*/... | (): string|null {
switch (this.status_) {
case SafetyCheckUpdatesStatus.DISABLED_BY_ADMIN:
return 'cr20:domain';
default:
return null;
}
}
}
customElements.define(
SettingsSafetyCheckUpdatesChildElement.is,
SettingsSafetyCheckUpdatesChildElement);
| getManagedIcon_ | identifier_name |
safety_check_updates_child.ts | // Copyright 2020 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.
/**
* @fileoverview
* 'settings-safety-updates-child' is the settings page containing the safety
* check child showing the browser's update status.
*/... | }
}
customElements.define(
SettingsSafetyCheckUpdatesChildElement.is,
SettingsSafetyCheckUpdatesChildElement); | } | random_line_split |
safety_check_updates_child.ts | // Copyright 2020 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.
/**
* @fileoverview
* 'settings-safety-updates-child' is the settings page containing the safety
* check child showing the browser's update status.
*/... |
private getManagedIcon_(): string|null {
switch (this.status_) {
case SafetyCheckUpdatesStatus.DISABLED_BY_ADMIN:
return 'cr20:domain';
default:
return null;
}
}
}
customElements.define(
SettingsSafetyCheckUpdatesChildElement.is,
SettingsSafetyCheckUpdatesChildElement)... | {
// Log click both in action and histogram.
this.metricsBrowserProxy_.recordSafetyCheckInteractionHistogram(
SafetyCheckInteractions.UPDATES_RELAUNCH);
this.metricsBrowserProxy_.recordAction(
'Settings.SafetyCheck.RelaunchAfterUpdates');
LifetimeBrowserProxyImpl.getInstance().relaunch(... | identifier_body |
oop6a.py | #!/usr/bin/env python3
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self,first,last):
self.first = first
self.last = last
self.email = first + '.' + last + '@kellynoah.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
def ... |
def __str__(self):
return '{} - {}'.format(self.fullname(), self.email)
def __add__(self, other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
emp_1 = Employee('John', 'Smith')
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname()) | return "Employee('{}', '{}', '{}')".format(self.first, self.last, self.pay) | random_line_split |
oop6a.py | #!/usr/bin/env python3
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self,first,last):
self.first = first
self.last = last
self.email = first + '.' + last + '@kellynoah.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
def ... |
def __len__(self):
return len(self.fullname())
emp_1 = Employee('John', 'Smith')
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())
| return self.pay + other.pay | identifier_body |
oop6a.py | #!/usr/bin/env python3
class | :
num_of_emps = 0
raise_amount = 1.04
def __init__(self,first,last):
self.first = first
self.last = last
self.email = first + '.' + last + '@kellynoah.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
def apply_raise(self):
self.pay = ... | Employee | identifier_name |
Gruntfile.js | /*
* angular-cache
* http://github.com/jmdobry/angular-cache
*
* Copyright (c) 2013 Jason Dobry <http://jmdobry.github.io/angular-cache>
* Licensed under the MIT license. <https://github.com/jmdobry/angular-cache/blob/master/LICENSE>
*/
module.exports = function (grunt) {
'use strict';
// Project configu... | browsers: ['Chrome']
},
drone: {
browsers: ['Firefox', 'Chrome', 'PhantomJS']
},
travis: {
browsers: ['Firefox', 'PhantomJS']
}
},
jsdoc : {
dist : {
src: ['dist/angula... | random_line_split | |
resolveHOC.ts | import { namedTypes as t } from 'ast-types';
import type { NodePath } from 'ast-types/lib/node-path';
import isReactCreateClassCall from './isReactCreateClassCall';
import isReactForwardRefCall from './isReactForwardRefCall';
import resolveToValue from './resolveToValue';
import type { Importer } from '../parse';
/**
... | if (
node.arguments.length > 1 &&
(t.Literal.check(inner.node) ||
t.ObjectExpression.check(inner.node) ||
t.ArrayExpression.check(inner.node) ||
t.SpreadElement.check(inner.node))
) {
return resolveHOC(
resolveToValue(
path.get('arg... | random_line_split | |
resolveHOC.ts | import { namedTypes as t } from 'ast-types';
import type { NodePath } from 'ast-types/lib/node-path';
import isReactCreateClassCall from './isReactCreateClassCall';
import isReactForwardRefCall from './isReactForwardRefCall';
import resolveToValue from './resolveToValue';
import type { Importer } from '../parse';
/**
... | resolveToValue(
path.get('arguments', node.arguments.length - 1),
importer,
),
importer,
);
}
return resolveHOC(resolveToValue(inner, importer), importer);
}
}
return path;
}
| {
const node = path.node;
if (
t.CallExpression.check(node) &&
!isReactCreateClassCall(path, importer) &&
!isReactForwardRefCall(path, importer)
) {
if (node.arguments.length) {
const inner = path.get('arguments', 0);
// If the first argument is one of these types then the component m... | identifier_body |
resolveHOC.ts | import { namedTypes as t } from 'ast-types';
import type { NodePath } from 'ast-types/lib/node-path';
import isReactCreateClassCall from './isReactCreateClassCall';
import isReactForwardRefCall from './isReactForwardRefCall';
import resolveToValue from './resolveToValue';
import type { Importer } from '../parse';
/**
... | (
path: NodePath,
importer: Importer,
): NodePath {
const node = path.node;
if (
t.CallExpression.check(node) &&
!isReactCreateClassCall(path, importer) &&
!isReactForwardRefCall(path, importer)
) {
if (node.arguments.length) {
const inner = path.get('arguments', 0);
// If the fir... | resolveHOC | identifier_name |
resolveHOC.ts | import { namedTypes as t } from 'ast-types';
import type { NodePath } from 'ast-types/lib/node-path';
import isReactCreateClassCall from './isReactCreateClassCall';
import isReactForwardRefCall from './isReactForwardRefCall';
import resolveToValue from './resolveToValue';
import type { Importer } from '../parse';
/**
... | }
return resolveHOC(resolveToValue(inner, importer), importer);
}
}
return path;
}
| {
if (node.arguments.length) {
const inner = path.get('arguments', 0);
// If the first argument is one of these types then the component might be the last argument
// If there are all identifiers then we cannot figure out exactly and have to assume it is the first
if (
node.argument... | conditional_block |
where-clauses-not-parameter.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 ... | () -> bool where Option<isize> : Eq {}
//~^ ERROR cannot bound type `core::option::Option<isize>`, where clause bounds may
#[derive(PartialEq)]
//~^ ERROR cannot bound type `isize`, where clause bounds
enum Foo<T> where isize : Eq { MkFoo }
//~^ ERROR cannot bound type `isize`, where clause bounds
fn test3<T: Eq>() -... | test2 | identifier_name |
where-clauses-not-parameter.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 ... | {
equal(&0is, &0is);
} | identifier_body | |
where-clauses-not-parameter.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 |
fn equal<T>(_: &T, _: &T) -> bool where isize : Eq {
true //~^ ERROR cannot bound type `isize`, where clause bounds may only be attached
}
// This should be fine involves a type parameter.
fn test<T: Eq>() -> bool where Option<T> : Eq {}
// This should be rejected as well.
fn test2() -> bool where Option<isize> ... | // <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. | random_line_split |
sync_exec.py | #! /usr/bin/env python
# encoding: utf-8
"""
Force the execution output to be synchronized
May deadlock with a lot of output (subprocess limitation)
"""
import sys
from waflib.Build import BuildContext
from waflib import Utils, Logs
def | (self, cmd, **kw):
subprocess = Utils.subprocess
kw['shell'] = isinstance(cmd, str)
Logs.debug('runner: %r' % cmd)
Logs.debug('runner_env: kw=%s' % kw)
try:
kw['stdout'] = kw['stderr'] = subprocess.PIPE
p = subprocess.Popen(cmd, **kw)
(out, err) = p.communicate()
if out:
sys.stdout.write(out.decode(sys.... | exec_command | identifier_name |
sync_exec.py | #! /usr/bin/env python
# encoding: utf-8
"""
Force the execution output to be synchronized
May deadlock with a lot of output (subprocess limitation)
"""
import sys | def exec_command(self, cmd, **kw):
subprocess = Utils.subprocess
kw['shell'] = isinstance(cmd, str)
Logs.debug('runner: %r' % cmd)
Logs.debug('runner_env: kw=%s' % kw)
try:
kw['stdout'] = kw['stderr'] = subprocess.PIPE
p = subprocess.Popen(cmd, **kw)
(out, err) = p.communicate()
if out:
sys.stdout.write... | from waflib.Build import BuildContext
from waflib import Utils, Logs
| random_line_split |
sync_exec.py | #! /usr/bin/env python
# encoding: utf-8
"""
Force the execution output to be synchronized
May deadlock with a lot of output (subprocess limitation)
"""
import sys
from waflib.Build import BuildContext
from waflib import Utils, Logs
def exec_command(self, cmd, **kw):
|
BuildContext.exec_command = exec_command
| subprocess = Utils.subprocess
kw['shell'] = isinstance(cmd, str)
Logs.debug('runner: %r' % cmd)
Logs.debug('runner_env: kw=%s' % kw)
try:
kw['stdout'] = kw['stderr'] = subprocess.PIPE
p = subprocess.Popen(cmd, **kw)
(out, err) = p.communicate()
if out:
sys.stdout.write(out.decode(sys.stdout.encoding or '... | identifier_body |
sync_exec.py | #! /usr/bin/env python
# encoding: utf-8
"""
Force the execution output to be synchronized
May deadlock with a lot of output (subprocess limitation)
"""
import sys
from waflib.Build import BuildContext
from waflib import Utils, Logs
def exec_command(self, cmd, **kw):
subprocess = Utils.subprocess
kw['shell'] = isi... |
return p.returncode
except OSError:
return -1
BuildContext.exec_command = exec_command
| sys.stdout.write(err.decode(sys.stdout.encoding or 'iso8859-1')) | conditional_block |
uievent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
event.init_event(Atom::from(type_), can_bubble, cancelable);
self.view.set(view);
self.detail.set(detail);
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
return;
} | conditional_block |
uievent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | pub fn Constructor(
window: &Window,
type_: DOMString,
init: &UIEventBinding::UIEventInit,
) -> Fallible<DomRoot<UIEvent>> {
let bubbles = EventBubbles::from(init.parent.bubbles);
let cancelable = EventCancelable::from(init.parent.cancelable);
let event = UIEvent:... | detail,
);
ev
}
| random_line_split |
uievent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | () -> UIEvent {
UIEvent {
event: Event::new_inherited(),
view: Default::default(),
detail: Cell::new(0),
}
}
pub fn new_uninitialized(window: &Window) -> DomRoot<UIEvent> {
reflect_dom_object(
Box::new(UIEvent::new_inherited()),
... | new_inherited | identifier_name |
service.py | #
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
"""
Base service installer module
"""
from ipalib.util import validate_domain_name
from ipapython.install import common, core, typing
from ipapython.install.core import group, knob
def prepare_only(obj):
"""
Decorator which makes an inst... | (cls):
"""
Returns installer class stripped of attributes not related to the enroll
phase of the install
"""
return _does(cls, 'enroll')
def installs_master(cls):
"""
Returns installer class stripped of attributes not related to master
install
"""
return _does(cls, 'master_inst... | enrolls | identifier_name |
service.py | #
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
"""
Base service installer module
"""
from ipalib.util import validate_domain_name
from ipapython.install import common, core, typing
from ipapython.install.core import group, knob
def prepare_only(obj):
"""
Decorator which makes an inst... |
def _does(cls, arg):
def remove(name):
def removed(self):
raise AttributeError(name)
return property(removed)
return type(
cls.__name__,
(cls,),
{
n: remove(n) for n in dir(cls)
if arg in getattr(getattr(cls, n), '__exclude__', set... | """
Decorator which makes an installer attribute appear only in replica install
"""
obj.__exclude__ = getattr(obj, '__exclude__', set()) | {'master_install'}
return obj | identifier_body |
service.py | #
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
"""
Base service installer module
"""
from ipalib.util import validate_domain_name
from ipapython.install import common, core, typing
from ipapython.install.core import group, knob
def prepare_only(obj):
"""
Decorator which makes an inst... | str, None,
description="a file generated by ipa-replica-prepare",
)
replica_file = replica_install_only(replica_file)
dm_password = knob(
str, None,
sensitive=True,
description="Directory Manager password (for the existing master)",
)
class ServiceAdminInstallI... | )
replica_file = knob( | random_line_split |
trait-object-reference-without-parens-suggestion.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let _: &Copy + 'static;
//~^ ERROR expected a path
//~| HELP try adding parentheses
//~| SUGGESTION let _: &(Copy + 'static);
let _: &'static Copy + 'static;
//~^ ERROR expected a path
//~| HELP try adding parentheses
//~| SUGGESTION let _: &'static (Copy + 'static);
}
| main | identifier_name |
trait-object-reference-without-parens-suggestion.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
... | random_line_split | |
trait-object-reference-without-parens-suggestion.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let _: &Copy + 'static;
//~^ ERROR expected a path
//~| HELP try adding parentheses
//~| SUGGESTION let _: &(Copy + 'static);
let _: &'static Copy + 'static;
//~^ ERROR expected a path
//~| HELP try adding parentheses
//~| SUGGESTION let _: &'static (Copy + 'static);
} | identifier_body | |
S15.5.4.17_A10.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The String.prototype.toLocaleLowerCase.length property has the attribute
ReadOnly
es5id: 15.5.4.17_A10
description: >
Checking if varying the String.prototype.to... | ////////////////////////////////////////////////////////////////////////////// | // | random_line_split |
S15.5.4.17_A10.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The String.prototype.toLocaleLowerCase.length property has the attribute
ReadOnly
es5id: 15.5.4.17_A10
description: >
Checking if varying the String.prototype.to... |
//
//////////////////////////////////////////////////////////////////////////////
var __obj = String.prototype.toLocaleLowerCase.length;
verifyNotWritable(String.prototype.toLocaleLowerCase, "length", null, function(){return "shifted";});
/////////////////////////////////////////////////////////////////////////////... | {
$ERROR('#1: String.prototype.toLocaleLowerCase.hasOwnProperty(\'length\') return true. Actual: '+String.prototype.toLocaleLowerCase.hasOwnProperty('length'));
} | conditional_block |
auth.guard.ts | import { Injectable } from "@angular/core";
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { AuthService } from "./auth.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private auth: AuthService) ... |
}
| {
return this.auth.getAccessTokenId();
} | identifier_body |
auth.guard.ts | import { Injectable } from "@angular/core";
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { AuthService } from "./auth.service";
@Injectable()
export class | implements CanActivate {
constructor(private router: Router, private auth: AuthService) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let path: string = next.url[0] ? next.url[0].path : "";
if (((path === "login") || (path === "register")) && this.isAuthenticated()) {
... | AuthGuard | identifier_name |
auth.guard.ts | import { Injectable } from "@angular/core";
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { AuthService } from "./auth.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private auth: AuthService) ... |
}
isAuthenticated(): boolean {
return this.auth.getAccessTokenId();
}
}
| {
return true;
} | conditional_block |
auth.guard.ts | import { Injectable } from "@angular/core";
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { AuthService } from "./auth.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private auth: AuthService) ... | }
} | random_line_split | |
app.js | 'use strict';
// Declare app level module which depends on views, and components
var ntApp = angular.module('ntApp', [
//'ngRoute',
'ui.router',
'ntApp.myDesigns',
'ntApp.designDetail',
'ntApp.myInfo',
'ntApp.couponList',
'ntApp.createDesign',
'ntApp.activities',
'ntApp.management',... |
}
});
});
| {
$window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
'wxf26855bd0cda23bd' + '&redirect_uri=' +
encodeURIComponent('http://design.weavesfun.com/#/orderList') +
'&response_type=code&scope=snsapi_base&state=mine#wechat_r... | conditional_block |
app.js | 'use strict';
// Declare app level module which depends on views, and components
var ntApp = angular.module('ntApp', [
//'ngRoute',
'ui.router',
'ntApp.myDesigns',
'ntApp.designDetail',
'ntApp.myInfo',
'ntApp.couponList',
'ntApp.createDesign',
'ntApp.activities',
'ntApp.management',... | if (!sTempCode) {
$window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
'wxf26855bd0cda23bd' + '&redirect_uri=' +
encodeURIComponent('http://design.weavesfun.com/#/orderList') +
'&response_type=code&scope=sns... | url: '/orderListAuth',
template: '<div></div>',
controller: function($window, $location) { | random_line_split |
abortable.rs | use crate::task::AtomicWaker;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use pin_utils::unsafe_pinned;
use core::fmt;
use core::pin::Pin;
use core::sync::atomic::{AtomicBool, Ordering};
use alloc::sync::Arc;
/// A future which can be remotely short-circuited using an `AbortHandle`.
#[de... | let (handle, reg) = AbortHandle::new_pair();
(
Abortable::new(future, reg),
handle,
)
}
/// Indicator that the `Abortable` future was aborted.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Aborted;
impl fmt::Display for Aborted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> f... | /// This function is only available when the `std` or `alloc` feature of this
/// library is activated, and it is activated by default.
pub fn abortable<Fut>(future: Fut) -> (Abortable<Fut>, AbortHandle)
where Fut: Future
{ | random_line_split |
abortable.rs | use crate::task::AtomicWaker;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use pin_utils::unsafe_pinned;
use core::fmt;
use core::pin::Pin;
use core::sync::atomic::{AtomicBool, Ordering};
use alloc::sync::Arc;
/// A future which can be remotely short-circuited using an `AbortHandle`.
#[de... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`Abortable` future has been aborted")
}
}
#[cfg(feature = "std")]
impl std::error::Error for Aborted {}
impl<Fut> Future for Abortable<Fut> where Fut: Future {
type Output = Result<Fut::Output, Aborted>;
fn poll(mut self: Pin<&mut Se... | fmt | identifier_name |
abortable.rs | use crate::task::AtomicWaker;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use pin_utils::unsafe_pinned;
use core::fmt;
use core::pin::Pin;
use core::sync::atomic::{AtomicBool, Ordering};
use alloc::sync::Arc;
/// A future which can be remotely short-circuited using an `AbortHandle`.
#[de... |
// attempt to complete the future
if let Poll::Ready(x) = self.as_mut().future().poll(cx) {
return Poll::Ready(Ok(x))
}
// Register to receive a wakeup if the future is aborted in the... future
self.inner.waker.register(cx.waker());
// Check to see if the ... | {
return Poll::Ready(Err(Aborted))
} | conditional_block |
abortable.rs | use crate::task::AtomicWaker;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use pin_utils::unsafe_pinned;
use core::fmt;
use core::pin::Pin;
use core::sync::atomic::{AtomicBool, Ordering};
use alloc::sync::Arc;
/// A future which can be remotely short-circuited using an `AbortHandle`.
#[de... |
}
/// A registration handle for a `Abortable` future.
/// Values of this type can be acquired from `AbortHandle::new` and are used
/// in calls to `Abortable::new`.
#[derive(Debug)]
pub struct AbortRegistration {
inner: Arc<AbortInner>,
}
/// A handle to a `Abortable` future.
#[derive(Debug, Clone)]
pub struct A... | {
Abortable {
future,
inner: reg.inner,
}
} | identifier_body |
initializedb.py | from importlib import import_module
from json import load
from os.path import basename, dirname, join
from sys import argv, exit
from pyramid.paster import get_appsettings, setup_logging
from pyramid.scripts.common import parse_vars
from transaction import manager
from app.fixtures import __file__ as fixture_base_dir... |
config_uri = argv[1]
setup_logging(config_uri)
options = parse_vars(argv[2:])
settings = get_appsettings(config_uri, options=options)
engine = get_engine(settings)
Base.metadata.create_all(engine)
fixture_dir = dirname(fixture_base_dir)
model_tree = TreeHelper(model_base_dir)
m... | usage(argv) | conditional_block |
initializedb.py | from importlib import import_module
from json import load
from os.path import basename, dirname, join
from sys import argv, exit
from pyramid.paster import get_appsettings, setup_logging
from pyramid.scripts.common import parse_vars
from transaction import manager
from app.fixtures import __file__ as fixture_base_dir... | (argv=argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
options = parse_vars(argv[2:])
settings = get_appsettings(config_uri, options=options)
engine = get_engine(settings)
Base.metadata.create_all(engine)
fixture_dir = dirname(fixture_base_d... | main | identifier_name |
initializedb.py | from importlib import import_module
from json import load
from os.path import basename, dirname, join
from sys import argv, exit
from pyramid.paster import get_appsettings, setup_logging
from pyramid.scripts.common import parse_vars
from transaction import manager
from app.fixtures import __file__ as fixture_base_dir... |
def main(argv=argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
options = parse_vars(argv[2:])
settings = get_appsettings(config_uri, options=options)
engine = get_engine(settings)
Base.metadata.create_all(engine)
fixture_dir = dirname(fix... | cmd = basename(argv[0])
print('usage: {} <config_uri> [var=value]'.format(cmd))
print('(example: "{} development.ini"'.format(cmd))
exit(1) | identifier_body |
initializedb.py | from importlib import import_module
from json import load
from os.path import basename, dirname, join
from sys import argv, exit
from pyramid.paster import get_appsettings, setup_logging
from pyramid.scripts.common import parse_vars
from transaction import manager
from app.fixtures import __file__ as fixture_base_dir... | class_name_suffix = 'Model'
class_name = '{}{}'.format(class_name_prefix, class_name_suffix)
class_obj = getattr(module_, class_name)
fixture_ext = 'json'
fixture_name = '{}.{}'.format(module, fixture_ext)
fixture_path = join(fixture_dir, fixture_... | for module in model_modules:
package = '{}.{}'.format(models_qualname, module)
module_ = import_module(package)
class_name_prefix = module.title() | random_line_split |
twit.py | import sys, os
import tweepy
# File with colon-separaten consumer/access token and secret
consumer_file='twitter.consumer'
access_file='twitter.access'
def __load_auth(file):
|
def twit(message, secret_dir='/secret'):
#
# Load the twitter consumer and access tokens and secrets
consumer_token, consumer_secret = __load_auth(os.path.join(secret_dir, consumer_file))
access_token, access_secret = __load_auth(os.path.join(secret_dir, access_file))
#
# Perform OAuth authent... | if os.path.exists(file):
with open(file) as f:
tokens = f.readline().replace('\n','').replace('\r','').split(':')
if len(tokens) == 2:
return tokens[0],tokens[1]
else:
raise ValueError("Expecting two colon-separated tokens")
else:
raise IOError("Fi... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.