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 |
|---|---|---|---|---|
commaOperatorWithSecondOperandAnyType.ts | // @allowUnreachableCode: true
var ANY: any;
var BOOLEAN: boolean;
var NUMBER: number;
var STRING: string;
var OBJECT: Object;
//The second operand type is any
ANY, ANY;
BOOLEAN, ANY;
NUMBER, ANY;
STRING, ANY;
OBJECT, ANY;
//Return type is any
var resultIsAny1 = (ANY, ANY);
var resultIsAny2 = (BOOLEAN, ANY);
var res... | 1, ANY;
++NUMBER, ANY;
"string", [null, 1];
"string".charAt(0), [null, 1];
true, x("any");
!BOOLEAN, x.doSomeThing();
var resultIsAny6 = (1, ANY);
var resultIsAny7 = (++NUMBER, ANY);
var resultIsAny8 = ("string", null);
var resultIsAny9 = ("string".charAt(0), undefined);
var resultIsAny10 = (true, x("any"));
var resul... | //Literal and expression
var x: any;
| random_line_split |
ex5.py | # -*- coding: utf-8 -*-
#
# exercise 5: more variables and printing
#
# string formating
name = 'Zed A. Shaw'
ages = 35 # not a lie
height = 74 # inched
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %d inched tall." % height
print "He's %d pounds hea... | ages, height, weight, ages + height + weight) | random_line_split | |
atomic_load.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_load;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_load<T>(src: *const T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A... | () {
atomic_load_test!( 68 );
}
}
| atomic_load_test1 | identifier_name |
atomic_load.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_load;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_load<T>(src: *const T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
unsafe impl Sync for A... |
}
type T = usize;
macro_rules! atomic_load_test {
($value:expr) => ({
let value: T = $value;
let a: A<T> = A::<T>::new(value);
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = data.clone();
thread::spawn(move || {
let src: *mut T = clone.v.get();
let resul... | {
A { v: UnsafeCell::<T>::new(v) }
} | identifier_body |
atomic_load.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::atomic_load;
use core::cell::UnsafeCell;
use std::sync::Arc;
use std::thread;
// pub fn atomic_load<T>(src: *const T) -> T;
struct A<T> {
v: UnsafeCell<T>
}
| fn new(v: T) -> A<T> {
A { v: UnsafeCell::<T>::new(v) }
}
}
type T = usize;
macro_rules! atomic_load_test {
($value:expr) => ({
let value: T = $value;
let a: A<T> = A::<T>::new(value);
let data: Arc<A<T>> = Arc::<A<T>>::new(a);
let clone: Arc<A<T>> = data.clone();
thread... | unsafe impl Sync for A<T> {}
impl<T> A<T> { | random_line_split |
rangeUtil.js | var rangeUtil = {
focusNode: function(node) {
var range = document.createRange();
range.selectNode(node.childNodes[0]);
range.collapse();
var selection = document.getSelection();
selection.removeAllRanges();
selection.addRange(range);
},
selectNode: function(node) {
var range = document.createRange();
... | n blogContainer;
}
};
module.exports = rangeUtil;
| { //文本节点
blogContainer = blogContainer.parentNode;
}
retur | conditional_block |
rangeUtil.js | var rangeUtil = {
focusNode: function(node) {
var range = document.createRange();
range.selectNode(node.childNodes[0]);
range.collapse();
var selection = document.getSelection(); | selectNode: function(node) {
var range = document.createRange();
range.selectNode(node.childNodes[0]);
var selection = document.getSelection();
selection.removeAllRanges();
selection.addRange(range);
},
getRange: function() {
var selection = window.getSelection();
var sRange = selection.getRangeAt(0);
... | selection.removeAllRanges();
selection.addRange(range);
}, | random_line_split |
dwt-tests.ts | import * as Dynamsoft from 'dwt';
function dwtOnReady() {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
if (DWObject) {
let count = DWObject.SourceCount;
if (count === 0) {
... |
}
function downloadImage() {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
if (DWObject) {
DWObject.HTTPPort = 80;
DWObject.HTTPDownload("www.dynamsoft.com", "img.png", () => {}, (errorCode: number, errorString: string) => {});
}
}
function loadPDF() {
c... | {
DWObject.HTTPPort = 80;
DWObject.IfSSL = false;
DWObject.HTTPUploadThroughPost("www.dynamsoft.com", DWObject.CurrentImageIndexInBuffer, "upload", "tmp.jpg", () => {}, (errorCode: number, errorString: string) => {});
} | conditional_block |
dwt-tests.ts | import * as Dynamsoft from 'dwt';
function dwtOnReady() {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
if (DWObject) {
let count = DWObject.SourceCount;
if (count === 0) {
... | () {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
if (DWObject) {
DWObject.SelectSourceByIndex(0); // Use method SelectSourceByIndex to avoid the 'Select Source' dialog
DWObject.OpenSource();
DWObject.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/cl... | acquireImage | identifier_name |
dwt-tests.ts | import * as Dynamsoft from 'dwt';
function dwtOnReady() {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
if (DWObject) {
let count = DWObject.SourceCount;
if (count === 0) {
... |
function showImageEditor() {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
if (DWObject) {
DWObject.ShowImageEditor();
}
}
function saveImage() {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
if (DWObject) {
DWObject.ConvertToGrayScale(DWObje... | random_line_split | |
dwt-tests.ts | import * as Dynamsoft from 'dwt';
function dwtOnReady() {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
if (DWObject) {
let count = DWObject.SourceCount;
if (count === 0) {
... |
function saveImage() {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
if (DWObject) {
DWObject.ConvertToGrayScale(DWObject.CurrentImageIndexInBuffer);
DWObject.SaveAsJPEG("DynamicWebTWAIN.jpg", DWObject.CurrentImageIndexInBuffer);
DWObject.SaveAllAsMultiPageTIFF("DynamicWeb... | {
const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
if (DWObject) {
DWObject.ShowImageEditor();
}
} | identifier_body |
ast.py | # mako/ast.py
# Copyright 2006-2020 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""utilities for analyzing expressions and blocks of Python
code, as well as generating Python from AST no... |
expr = pyparser.parse(code, "exec", **exception_kwargs)
else:
expr = code
f = pyparser.FindTuple(self, PythonCode, **exception_kwargs)
f.visit(expr)
class PythonFragment(PythonCode):
"""extends PythonCode to provide identifier lookups in partial control
state... | code += "," | conditional_block |
ast.py | # mako/ast.py
# Copyright 2006-2020 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""utilities for analyzing expressions and blocks of Python
code, as well as generating Python from AST no... | kwdefaults = self.kwdefaults[::-1]
# Named arguments
if self.kwargs:
namedecls.append("**" + kwargnames.pop(0))
for name in kwargnames:
# Keyword-only arguments must always be used by name, so even if
# this is a call, print out `foo=foo`
... | argnames = self.argnames[::-1]
kwargnames = self.kwargnames[::-1]
defaults = self.defaults[::-1] | random_line_split |
ast.py | # mako/ast.py
# Copyright 2006-2020 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""utilities for analyzing expressions and blocks of Python
code, as well as generating Python from AST no... | (self, code, **exception_kwargs):
self.codeargs = []
self.args = []
self.declared_identifiers = set()
self.undeclared_identifiers = set()
if isinstance(code, compat.string_types):
if re.match(r"\S", code) and not re.match(r",\s*$", code):
# if theres t... | __init__ | identifier_name |
ast.py | # mako/ast.py
# Copyright 2006-2020 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""utilities for analyzing expressions and blocks of Python
code, as well as generating Python from AST no... |
def get_argument_expressions(self, as_call=False):
"""Return the argument declarations of this FunctionDecl as a printable
list.
By default the return value is appropriate for writing in a ``def``;
set `as_call` to true to build arguments to be passed to the function
inste... | self.code = code
expr = pyparser.parse(code, "exec", **exception_kwargs)
f = pyparser.ParseFunc(self, **exception_kwargs)
f.visit(expr)
if not hasattr(self, "funcname"):
raise exceptions.CompileException(
"Code '%s' is not a function declaration" % code,
... | identifier_body |
crawler_chuongthieu.py | # -*- encoding: utf-8 -*-
import io
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import urllib2
import urlparse
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expecte... | # close file
ftmp.close()
except Exception, e:
print e
# close file
ftmp.close()
def check_numline(filename):
urlsach_list = []
urlsach_file = open(filename, 'r')
for line in urlsach_file:
urlsach_list.append(line.strip())
_len = len(url... | random_line_split | |
crawler_chuongthieu.py | # -*- encoding: utf-8 -*-
import io
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import urllib2
import urlparse
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expecte... |
count = count + 1
# close file
ftmp.close()
except Exception, e:
print e
# close file
ftmp.close()
def check_numline(filename):
urlsach_list = []
urlsach_file = open(filename, 'r')
for line in urlsach_file:
urlsach_list.append(... | data = tr_tags[x].get_text('|')
# print data
# url_ec = url.encode('unicode','utf-8')
ftmp.write(u'' + data + '\n') | conditional_block |
crawler_chuongthieu.py | # -*- encoding: utf-8 -*-
import io
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import urllib2
import urlparse
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expecte... | (sachi):
list_chuongthieu = []
list_stt = getsttchuongthieu(sachi)
fname = 'urlsach/sach' + str(sachi) + '.txt'
fp = open(fname)
lines=fp.readlines()
for stt in list_stt:
list_chuongthieu.append(lines[stt-1])
return list_chuongthieu
def main():
for x in xrange(1,67):
... | getlisturlchuongthieu | identifier_name |
crawler_chuongthieu.py | # -*- encoding: utf-8 -*-
import io
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import urllib2
import urlparse
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expecte... |
def main():
for x in xrange(1,67):
#kiem tra xem duong dan co trong thu muc partcomplete hay khong
f2name = 'urlsach/data/partcomplete/sach' + str(x) + '.txt'
if os.path.isfile(f2name):
list_urlchuongthieu = getlisturlchuongthieu(x)
get_data(list_urlchuongt... | list_chuongthieu = []
list_stt = getsttchuongthieu(sachi)
fname = 'urlsach/sach' + str(sachi) + '.txt'
fp = open(fname)
lines=fp.readlines()
for stt in list_stt:
list_chuongthieu.append(lines[stt-1])
return list_chuongthieu | identifier_body |
gulpfile.js | var gulp = require('gulp');
var setup = require('web3-common-build-setup');
var DEPS_FOLDER = setup.depsFolder;
// Build tools
var _ = require(DEPS_FOLDER + 'lodash');
var insert = require(DEPS_FOLDER + 'gulp-insert');
var del = require(DEPS_FOLDER + 'del');
var plugins = {};
plugins.s... | target: "ES5"
}))
.pipe(insert.wrap(requireJSAppPrefix, requireJSSuffix))
.pipe(gulp.dest(CONFIG.DIST.FOLDER()))
.on('error', cb);
cb();
});
gulpInstance.task('sass', function (cb) {
gulp.src("./sass/main.scss")
.pipe(plugins.sass({
precision: ... | sourceRoot: "/",
| random_line_split |
events.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/... | // 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 later version.
//
// Moodle is distributed in the hope that it will be useful, | random_line_split |
features.service.ts | import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
// FeaturesService asks vtctld for the feature map, and populates
// member variables from it. It is constructed once when the main UI
// is displayed, and can then be used anywhere. | activeReparents = false;
showStatus = false;
showTopologyCRUD = false;
showWorkflows = false;
workflows = [];
private featuresUrl = '../api/features';
constructor(private http: Http) {
this.getFeatures().subscribe(update => {
this.activeReparents = update.activeReparents;
this.showStatus ... | @Injectable()
export class FeaturesService { | random_line_split |
features.service.ts | import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
// FeaturesService asks vtctld for the feature map, and populates
// member variables from it. It is constructed once when the main UI
// is displayed, and can then be used anywhere.
@Inject... | (private http: Http) {
this.getFeatures().subscribe(update => {
this.activeReparents = update.activeReparents;
this.showStatus = update.showStatus;
this.showTopologyCRUD = update.showTopologyCRUD;
this.showWorkflows = update.showWorkflows;
this.workflows = update.workflows;
});
}... | constructor | identifier_name |
features.service.ts | import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
// FeaturesService asks vtctld for the feature map, and populates
// member variables from it. It is constructed once when the main UI
// is displayed, and can then be used anywhere.
@Inject... |
}
| {
return this.http.get(this.featuresUrl)
.map(resp => resp.json());
} | identifier_body |
toast.component.ts | // #docregion
import { Component, OnInit } from 'angular2/core';
@Component({
selector: 'my-toast',
template: `...`
}) |
// private fields
private defaults = {
title: '',
message: 'May the Force be with You'
};
private toastElement: any;
// public methods
activate(message = this.defaults.message, title = this.defaults.title) {
this.title = title;
this.message = message;
this.show();
}
ngOnInit() {
... | // #docregion example
export class ToastComponent implements OnInit {
// public properties
message: string;
title: string; | random_line_split |
toast.component.ts | // #docregion
import { Component, OnInit } from 'angular2/core';
@Component({
selector: 'my-toast',
template: `...`
})
// #docregion example
export class ToastComponent implements OnInit {
// public properties
message: string;
title: string;
// private fields
private defaults = {
title: '',
mess... | () {
this.toastElement.style.opacity = 0;
window.setTimeout(() => this.toastElement.style.zIndex = 0, 400);
}
private show() {
console.log(this.message);
this.toastElement.style.opacity = 1;
this.toastElement.style.zIndex = 9999;
window.setTimeout(() => this.hide(), 2500);
}
}
// #endregi... | hide | identifier_name |
toast.component.ts | // #docregion
import { Component, OnInit } from 'angular2/core';
@Component({
selector: 'my-toast',
template: `...`
})
// #docregion example
export class ToastComponent implements OnInit {
// public properties
message: string;
title: string;
// private fields
private defaults = {
title: '',
mess... |
}
// #endregion example
| {
console.log(this.message);
this.toastElement.style.opacity = 1;
this.toastElement.style.zIndex = 9999;
window.setTimeout(() => this.hide(), 2500);
} | identifier_body |
golden.js | /**
* @license Copyright 2019 The Lighthouse 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... | (filename, data) {
fs.writeFileSync(`${common.goldenFolder}/${filename}`, data);
}
/** @type {typeof common.ProgressLogger['prototype']} */
let log;
async function main() {
log = new common.ProgressLogger();
/** @type {Summary} */
const summary = common.loadSummary();
const goldenSites = [];
for (const ... | saveGoldenData | identifier_name |
golden.js | /**
* @license Copyright 2019 The Lighthouse 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... | },
});
}
/** @type {Golden} */
const golden = {sites: goldenSites};
fs.rmSync(common.goldenFolder, {recursive: true, force: true});
fs.mkdirSync(common.goldenFolder);
saveGoldenData('site-index-plus-golden-expectations.json', JSON.stringify(golden, null, 2));
for (const result of goldenSites) {... | tracePath: medianUnthrottled.trace,
devtoolsLogPath: medianUnthrottled.devtoolsLog, | random_line_split |
golden.js | /**
* @license Copyright 2019 The Lighthouse 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... |
/** @type {typeof common.ProgressLogger['prototype']} */
let log;
async function main() {
log = new common.ProgressLogger();
/** @type {Summary} */
const summary = common.loadSummary();
const goldenSites = [];
for (const [index, {url, wpt, unthrottled}] of Object.entries(summary.results)) {
log.progr... | {
fs.writeFileSync(`${common.goldenFolder}/${filename}`, data);
} | identifier_body |
Client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details.
| import sys, os
from gevent import select, monkey, spawn, Greenlet, GreenletExit, sleep, socket
from base64 import b64encode
from hashlib import md5
from struct import pack, unpack
from zlib import adler32
from Proto import Proto
from Index import Index
from Config import *
class Client(Proto):
def __init__(self, v... | random_line_split | |
Client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details.
import sys, os
from gevent import select, monkey, spawn, Greenlet, GreenletExit, sleep, socket
from base64 import b64encode
from hashlib import md5
from struct import pack, unpack
from zl... |
size = unpack('!I', size)[0]
buffer = self.srecvall(size)
hash = self.srecvall(16)
if md5(buffer).digest() != hash:
self.ssend("\xFF")
raise Exception, "Bad md5 ..."
return buffer
def get_file(self, id, name):
path = os.path.join(inbox, name)... | self.ssend("\xFF")
raise Exception, "Bad checksum" | conditional_block |
Client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details.
import sys, os
from gevent import select, monkey, spawn, Greenlet, GreenletExit, sleep, socket
from base64 import b64encode
from hashlib import md5
from struct import pack, unpack
from zl... |
def recv_file(self):
if self.srecvall(1) != "\x01":
self.ssend("\xFF")
raise Exception, "Bad Flags (0x01 expected)"
size = self.srecvall(4)
checksum = self.srecvall(4)
if adler32(size) != unpack('!I',checksum)[0]:
self.ssend("\xFF")
r... | self.send_id()
myiv = self.send_iv()
iv = self.get_iv(pubkey)
self.init_cipher(pubkey, myiv, iv) | identifier_body |
Client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details.
import sys, os
from gevent import select, monkey, spawn, Greenlet, GreenletExit, sleep, socket
from base64 import b64encode
from hashlib import md5
from struct import pack, unpack
from zl... | (self, exp):
self.close()
def connect(self, host, port, pubkey):
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.handshake(pubkey)
except Exception as e:
self.error(e)
raise
... | error | identifier_name |
utils.rs | mut result = Vec::with_capacity(MAX_PAGE_COMPACT_BUFFER);
// The most recent range of pages is [previous..previous + length).
let mut previous = 0;
let mut length = 1;
for pfn_index in 1..v.len() {
let page_frame_number = v[pfn_index];
// Skip duplicate pages. This will ensure we onl... | result.push((v[previous], length));
result
}
pub(crate) fn remove_range(
guest_memory: &GuestMemoryMmap,
range: (GuestAddress, u64),
restored: bool,
) -> std::result::Result<(), RemoveRegionError> {
let (guest_address, range_len) = range;
if let Some(region) = guest_memory.find_region(gue... | // Don't forget to push the last range to the result. | random_line_split |
utils.rs | mut result = Vec::with_capacity(MAX_PAGE_COMPACT_BUFFER);
// The most recent range of pages is [previous..previous + length).
let mut previous = 0;
let mut length = 1;
for pfn_index in 1..v.len() {
let page_frame_number = v[pfn_index];
// Skip duplicate pages. This will ensure we onl... | ;
// Madvise the region in order to mark it as not used.
let ret = unsafe {
libc::madvise(
phys_address as *mut _,
range_len as usize,
libc::MADV_DONTNEED,
)
};
if ret < 0 {
return Err(RemoveRegionError:... | {
let ret = unsafe {
libc::mmap(
phys_address as *mut _,
range_len as usize,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_FIXED | libc::MAP_ANONYMOUS | libc::MAP_PRIVATE,
-1,
... | conditional_block |
utils.rs | mut result = Vec::with_capacity(MAX_PAGE_COMPACT_BUFFER);
// The most recent range of pages is [previous..previous + length).
let mut previous = 0;
let mut length = 1;
for pfn_index in 1..v.len() {
let page_frame_number = v[pfn_index];
// Skip duplicate pages. This will ensure we onl... | () {
let page_size: usize = 0x1000;
let mem = vm_memory::test_utils::create_anon_guest_memory(
&[(GuestAddress(0), 2 * page_size)],
false,
)
.unwrap();
// Fill the memory with ones.
let ones = vec![1u8; 2 * page_size];
mem.write(&ones[..],... | test_remove_range_on_restored | identifier_name |
utils.rs | // This operation will never overflow because for whatever value `v[previous]`
// has in the u32 range, we know there are at least `length` consecutive numbers
// greater than it in the array (the greatest so far being `page_frame_number`),
// since `v[previous]` is before all of them in the so... | {
// Create a randomly sized vec (max MAX_PAGE_COMPACT_BUFFER elements) filled with random u32 elements.
prop::collection::vec(0..std::u32::MAX, 0..MAX_PAGE_COMPACT_BUFFER)
} | identifier_body | |
stability.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 ... | (&mut self, var: &Variant, g: &'v Generics) {
self.annotate(var.node.id, &var.node.attrs, |v| visit::walk_variant(v, var, g))
}
fn visit_struct_field(&mut self, s: &StructField) {
self.annotate(s.node.id, &s.node.attrs, |v| visit::walk_struct_field(v, s));
}
}
impl Index {
/// Construc... | visit_variant | identifier_name |
stability.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 ... | pub fn lookup(tcx: &ty::ctxt, id: DefId) -> Option<Stability> {
// is this definition the implementation of a trait method?
match ty::trait_item_of_item(tcx, id) {
Some(ty::MethodTraitItemId(trait_method_id))
if trait_method_id != id => {
lookup(tcx, trait_method_id)
... | /// metadata as necessary. | random_line_split |
stability.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
| {
let stab = csearch::get_stability(&tcx.sess.cstore, id);
let mut index = tcx.stability.borrow_mut();
(*index).extern_cache.insert(id, stab.clone());
stab
} | conditional_block |
stability.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 ... |
}
impl Index {
/// Construct the stability index for a crate being compiled.
pub fn build(krate: &Crate) -> Index {
let mut annotator = Annotator {
index: Index {
local: NodeMap::new(),
extern_cache: DefIdMap::new()
},
parent: None
... | {
self.annotate(s.node.id, &s.node.attrs, |v| visit::walk_struct_field(v, s));
} | identifier_body |
setup.py | from __future__ import print_function
import io
import os.path
import re
from distutils.text_file import TextFile
from setuptools import find_packages, setup
home = os.path.abspath(os.path.dirname(__file__))
missing = object()
def read_description(*files, **kwargs):
encoding = kwargs.get('encodin... |
def read_version(module_name):
with open(os.path.join(module_name, '__init__.py'), 'r') as fd:
result = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE)
return result.group(1) if result else '0.0.1'
setup(
name='flask_kits',... | if requirements is None:
return []
if requirements is missing:
requirements = 'requirements.txt'
if not os.path.isfile(requirements):
return []
text = TextFile(requirements, lstrip_ws=True)
try:
return text.readlines()
finally:
text.close() | identifier_body |
setup.py | from __future__ import print_function
import io
import os.path
import re
from distutils.text_file import TextFile
from setuptools import find_packages, setup
home = os.path.abspath(os.path.dirname(__file__))
missing = object()
def read_description(*files, **kwargs):
encoding = kwargs.get('encodin... | (requirements=missing):
if requirements is None:
return []
if requirements is missing:
requirements = 'requirements.txt'
if not os.path.isfile(requirements):
return []
text = TextFile(requirements, lstrip_ws=True)
try:
return text.readlines()
finally:
... | read_dependencies | identifier_name |
setup.py | from __future__ import print_function
import io
import os.path
import re
from distutils.text_file import TextFile
from setuptools import find_packages, setup
home = os.path.abspath(os.path.dirname(__file__))
missing = object()
def read_description(*files, **kwargs):
encoding = kwargs.get('encodin... | with open(os.path.join(module_name, '__init__.py'), 'r') as fd:
result = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE)
return result.group(1) if result else '0.0.1'
setup(
name='flask_kits',
version=read_version('flask_kits... | def read_version(module_name):
| random_line_split |
setup.py | from __future__ import print_function
import io
import os.path
import re
from distutils.text_file import TextFile
from setuptools import find_packages, setup
home = os.path.abspath(os.path.dirname(__file__))
missing = object()
def read_description(*files, **kwargs):
encoding = kwargs.get('encodin... |
if requirements is missing:
requirements = 'requirements.txt'
if not os.path.isfile(requirements):
return []
text = TextFile(requirements, lstrip_ws=True)
try:
return text.readlines()
finally:
text.close()
def read_version(module_name):
with open(o... | return [] | conditional_block |
spelling.py | # Copyright 2014 Michal Nowikowski.
#
# 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
# version.
#
# This program is distributed in... |
@check_messages('wrong-spelling-in-docstring')
def visit_module(self, node):
if not self.initialized:
return
self._check_docstring(node)
@check_messages('wrong-spelling-in-docstring')
def visit_class(self, node):
if not self.initialized:
return
... | if tok_type == tokenize.COMMENT:
self._check_spelling('wrong-spelling-in-comment',
token, start_row) | conditional_block |
spelling.py | # Copyright 2014 Michal Nowikowski.
#
# 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
# version.
#
# This program is distributed in... | (self, tokens):
if not self.initialized:
return
# Process tokens and look for comments.
for (tok_type, token, (start_row, _), _, _) in tokens:
if tok_type == tokenize.COMMENT:
self._check_spelling('wrong-spelling-in-comment',
... | process_tokens | identifier_name |
spelling.py | # Copyright 2014 Michal Nowikowski.
#
# 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
# version.
#
# This program is distributed in... | self.spelling_dict = enchant.Dict(dict_name)
if self.config.spelling_store_unknown_words:
self.unknown_words = set()
# Prepare regex for stripping punctuation signs from text.
# ' and _ are treated in a special way.
puncts = string.punctuation.replace("'", "").r... | self.initialized = False
self.private_dict_file = None
if enchant is None:
return
dict_name = self.config.spelling_dict
if not dict_name:
return
self.ignore_list = [w.strip() for w in self.config.spelling_ignore_words.split(",")]
# "param" appear... | identifier_body |
spelling.py | # Copyright 2014 Michal Nowikowski.
#
# 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
# version.
#
# This program is distributed in... | @check_messages('wrong-spelling-in-docstring')
def visit_module(self, node):
if not self.initialized:
return
self._check_docstring(node)
@check_messages('wrong-spelling-in-docstring')
def visit_class(self, node):
if not self.initialized:
return
se... | self._check_spelling('wrong-spelling-in-comment',
token, start_row)
| random_line_split |
app.js | 'use strict';
// Declare app level module which depends on views, and components
var accountModule = angular.module('accountModule', []);
var partnerModule = angular.module('partnerModule', []);
var dodoModule = angular.module('dodoModule', []); | 'accountModule',
'partnerModule',
'dodoModule'
]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]).factory('storageService', ['$log', '$rootScope', function ($log, $rootScope) {
var localStorageMaxCount = 10;
var storageServic... |
angular.module('myApp', [
'ngMaterial',
'ngRoute',
'myApp.version', | random_line_split |
app.js | 'use strict';
// Declare app level module which depends on views, and components
var accountModule = angular.module('accountModule', []);
var partnerModule = angular.module('partnerModule', []);
var dodoModule = angular.module('dodoModule', []);
angular.module('myApp', [
'ngMaterial',
'ngRoute',
'myApp.v... | else {
return undefined;
}
},
clear: function (storageName) {
delete localStorage[storageName];
$rootScope.$broadcast(storageName);
return undefined;
},
swipeAll: function () {
localStorag... | {
return JSON.parse(storedData);
} | conditional_block |
treeadmin.js | collapsed
if(isExpandedNode(childId)) {
doToggle(childId, show);
}
} else {
$('#item-' + childId).hide();
// always recursively hide children
doToggle(childId, show);
}
}
}
function rowLevel($row) {
return parseInt($row.attr('rel').replace(/[^\d]/ig, ''));
}
/*
* FeinCMS Drag... | () {
var n = $.cookie('treeadmin_collapsed_nodes');
if(n != null) {
try {
n = $.parseJSON(n);
} catch(e) {
n = null;
}
}
return n;
}
function expandOrCollapseNode(item) {
var show = true;
if(!item.hasClass('children'))
return;
var itemId = extract_item_id(item.attr('id'));
if(!... | retrieveCollapsedNodes | identifier_name |
treeadmin.js |
if(isExpandedNode(childId)) {
doToggle(childId, show);
}
} else {
$('#item-' + childId).hide();
// always recursively hide children
doToggle(childId, show);
}
}
}
function rowLevel($row) {
return parseInt($row.attr('rel').replace(/[^\d]/ig, ''));
}
/*
* FeinCMS Drag-n-drop tr... | var moveTo = new Object();
var expandObj = new Object();
$("body").addClass('dragging').disableSelection().bind('mousemove', function(event) {
// attach dragged item to mouse
var cloned = originalRow.html();
if($('#ghost').length == 0) {
$('<div id="ghost"></div>').appendTo('body');
}
... | var childEdge = $(event.target).offset().left + $(event.target).width(); | random_line_split |
treeadmin.js |
function rowLevel($row) {
return parseInt($row.attr('rel').replace(/[^\d]/ig, ''));
}
/*
* FeinCMS Drag-n-drop tree reordering.
* Based upon code by bright4 for Radiant CMS, rewritten for
* FeinCMS by Bjorn Post.
*
* September 2010
*
*/
$.extend($.fn.feinTree = function() {
$('tr', this).each(f... | {
var children = treeadmin.tree_structure[id];
for (var i=0; i<children.length; ++i) {
var childId = children[i];
if(show) {
$('#item-' + childId).show();
// only reveal children if current node is not collapsed
if(isExpandedNode(childId)) {
doToggle(childId, show);
}
} else {
$('#... | identifier_body | |
treeadmin.js | collapsed
if(isExpandedNode(childId)) {
doToggle(childId, show);
}
} else {
$('#item-' + childId).hide();
// always recursively hide children
doToggle(childId, show);
}
}
}
function rowLevel($row) {
return parseInt($row.attr('rel').replace(/[^\d]/ig, ''));
}
/*
* FeinCMS Drag... | else {
item.addClass('closed');
show = false;
markNodeAsCollapsed(itemId);
}
storeCollapsedNodes(treeadmin.collapsed_nodes);
doToggle(itemId, show);
$('#result_list tbody').recolorRows();
}
$.extend($.fn.feinTreeToggleItem = function() {
$(this).click(function(event){
expandOrCollapseNode($... | {
item.removeClass('closed');
markNodeAsExpanded(itemId);
} | conditional_block |
i18n.ts | import Vue, { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue';
import { I18N_NAME } from '../directive-names';
const I18nDirective: DirectiveOptions = {
| (
el: HTMLElement,
binding: VNodeDirective,
vnode: VNode
): void {
if (binding.arg) {
if (vnode.componentInstance) {
Vue.prototype.$log.warn(`i18n Directive souldn't be used on a ${vnode.componentInstance.constructor.name} component. Please use the filter ... | bind | identifier_name |
i18n.ts | import Vue, { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue';
import { I18N_NAME } from '../directive-names';
const I18nDirective: DirectiveOptions = {
bind(
el: HTMLElement,
binding: VNodeDirective,
vnode: VNode
): void |
};
const I18nDirectivePlugin: PluginObject<any> = {
install(v, options): void {
v.directive(I18N_NAME, I18nDirective);
}
};
export default I18nDirectivePlugin;
| {
if (binding.arg) {
if (vnode.componentInstance) {
Vue.prototype.$log.warn(`i18n Directive souldn't be used on a ${vnode.componentInstance.constructor.name} component. Please use the filter instead.`);
}
let expression: any = binding.expression;
c... | identifier_body |
i18n.ts | import Vue, { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue';
import { I18N_NAME } from '../directive-names';
const I18nDirective: DirectiveOptions = {
bind(
el: HTMLElement,
binding: VNodeDirective,
vnode: VNode
): void {
if (binding.arg) {
if (... | }
};
const I18nDirectivePlugin: PluginObject<any> = {
install(v, options): void {
v.directive(I18N_NAME, I18nDirective);
}
};
export default I18nDirectivePlugin; | }
el.setAttribute(binding.arg, expression);
} | random_line_split |
i18n.ts | import Vue, { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue';
import { I18N_NAME } from '../directive-names';
const I18nDirective: DirectiveOptions = {
bind(
el: HTMLElement,
binding: VNodeDirective,
vnode: VNode
): void {
if (binding.arg) {
if (... |
el.setAttribute(binding.arg, expression);
}
}
};
const I18nDirectivePlugin: PluginObject<any> = {
install(v, options): void {
v.directive(I18N_NAME, I18nDirective);
}
};
export default I18nDirectivePlugin;
| {
expression = Vue.prototype.$i18n.translate(
modifiers[0],
options.params,
options.nb,
options.modifier
);
} | conditional_block |
build.rs | (&'static str),
Cmd{key: &'static str, cmd: &'static str},
CmdReq{key: &'static str, cmd: &'static str},
CmdOrEnvReq{key: &'static str, cmd: &'static str},
CmdOrEnv{key: &'static str, cmd: &'static str},
EnvOrCmdInconsistent{key: &'static str, cmd: &'static str},
FileContentsReq{key: &'static st... | }
}
fn fetch_env(key: &str, result_required: bool, empty_is_missing: bool) -> Option<String>{
if result_required {
match env::var(key) {
Ok(ref v) if v.len() == 0 && empty_is_missing => {
panic!("Required env var {} is present - but empty - in the build environment", key);
... | {
let mut args: Vec<&str> = cmd.split(" ").collect::<Vec<&str>>();
if args.len() < 1 {
panic!("");
}
let exe = args.remove(0);
let output: Output = Command::new(exe)
.args(&args)
.output()?;
if !output.status.success() {
return Err(Error::CommandFailed(output));
... | identifier_body |
build.rs | (&'static str),
Cmd{key: &'static str, cmd: &'static str},
CmdReq{key: &'static str, cmd: &'static str},
CmdOrEnvReq{key: &'static str, cmd: &'static str},
CmdOrEnv{key: &'static str, cmd: &'static str},
EnvOrCmdInconsistent{key: &'static str, cmd: &'static str},
FileContentsReq{key: &'static st... | info
}
fn what_to_collect() -> Vec<EnvTidbit>{
let mut c = Vec::new();
c.push(EnvTidbit::CmdOrEnvReq {key: "GIT_COMMIT", cmd: "git rev-parse HEAD"});
c.push(EnvTidbit::CmdOrEnv{key: "GIT_COMMIT_SHORT", cmd: "git rev-parse --short HEAD"});
c.push(EnvTidbit::CmdOrEnv{key: "GIT_DESCRIBE_ALWAYS", cmd: "... | EnvTidbit::CmdOrEnv{key, cmd} => (key, command(key, cmd, false, true)),
EnvTidbit::EnvOrCmdInconsistent{key, cmd} => (key, env_or_cmd(key, cmd)),
};
info.insert(k.to_owned(),v);
} | random_line_split |
build.rs | (&'static str),
Cmd{key: &'static str, cmd: &'static str},
CmdReq{key: &'static str, cmd: &'static str},
CmdOrEnvReq{key: &'static str, cmd: &'static str},
CmdOrEnv{key: &'static str, cmd: &'static str},
EnvOrCmdInconsistent{key: &'static str, cmd: &'static str},
FileContentsReq{key: &'static st... | () {
let todo = what_to_collect();
let utcnow_val =Utc::now();
let mut results = collect_info(todo);
results.insert("GENERATED_DATETIME_UTC".to_owned(), Some(utcnow_val.to_rfc3339()));
results.insert("GENERATED_DATE_UTC".to_owned(), Some(utcnow_val.format("%Y-%m-%d").to_string()));
let mut con... | main | identifier_name |
build.rs | 'static str),
Cmd{key: &'static str, cmd: &'static str},
CmdReq{key: &'static str, cmd: &'static str},
CmdOrEnvReq{key: &'static str, cmd: &'static str},
CmdOrEnv{key: &'static str, cmd: &'static str},
EnvOrCmdInconsistent{key: &'static str, cmd: &'static str},
FileContentsReq{key: &'static str,... |
}
}else{
env::var(key).ok().and_then(|v| if v.len() == 0 && empty_is_missing { None } else { Some(v) })
}
}
fn command(key: &str, cmd: &str, result_required: bool, fallback_to_env: bool) -> Option<String>{
//Panic only if non-UTF-8 output is sent
let output = run(cmd);
//Don't pani... | { panic!("Required env var {} missing in the build environment: {:?}", key, e); } | conditional_block |
current-date-indicator.js | /*
Highcharts Gantt JS v9.3.1 (2021-11-05)
CurrentDateIndicator
(c) 2010-2021 Lars A. V. Cabrera
License: www.highcharts.com/license
*/
'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/current-da... | a=a?a._modules:{};b(a,"Extensions/CurrentDateIndication.js",[a["Core/Axis/Axis.js"],a["Core/Axis/PlotLineOrBand/PlotLineOrBand.js"],
a["Core/Utilities.js"]],function(a,b,d){var e=d.addEvent,f=d.merge;d=d.wrap;var g={color:"#ccd6eb",width:2,label:{format:"%a, %b %d %Y, %H:%M",formatter:function(a,b){return this.axis.cha... | {a.hasOwnProperty(b)||(a[b]=e.apply(null,d))} | identifier_body |
current-date-indicator.js | /*
Highcharts Gantt JS v9.3.1 (2021-11-05)
CurrentDateIndicator
(c) 2010-2021 Lars A. V. Cabrera
License: www.highcharts.com/license
*/
'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/current-da... | (a,b,d,e){a.hasOwnProperty(b)||(a[b]=e.apply(null,d))}a=a?a._modules:{};b(a,"Extensions/CurrentDateIndication.js",[a["Core/Axis/Axis.js"],a["Core/Axis/PlotLineOrBand/PlotLineOrBand.js"],
a["Core/Utilities.js"]],function(a,b,d){var e=d.addEvent,f=d.merge;d=d.wrap;var g={color:"#ccd6eb",width:2,label:{format:"%a, %b %d %... | b | identifier_name |
current-date-indicator.js | /*
Highcharts Gantt JS v9.3.1 (2021-11-05)
CurrentDateIndicator
| (c) 2010-2021 Lars A. V. Cabrera
License: www.highcharts.com/license
*/
'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/current-date-indicator",["highcharts"],function(b){a(b);a.Highcharts=b;return ... | random_line_split | |
allow_deleting_browser_history_webdriver_test.py | # Copyright (c) 2019 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.
from absl import app
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.suppo... | app.run(main) | random_line_split | |
allow_deleting_browser_history_webdriver_test.py | # Copyright (c) 2019 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.
from absl import app
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.suppo... |
else:
return driver.execute_script(
"return arguments[0].shadowRoot.querySelector(arguments[1])", element,
selector)
def main(argv):
driver = test_util.create_chrome_webdriver()
try:
driver.get('http://www.google.com')
driver.get('chrome://history')
# wait for page to be loade... | return None | conditional_block |
allow_deleting_browser_history_webdriver_test.py | # Copyright (c) 2019 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.
from absl import app
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.suppo... | (argv):
driver = test_util.create_chrome_webdriver()
try:
driver.get('http://www.google.com')
driver.get('chrome://history')
# wait for page to be loaded
wait = WebDriverWait(driver, 10)
wait.until(
expected_conditions.visibility_of_element_located((By.TAG_NAME,
... | main | identifier_name |
allow_deleting_browser_history_webdriver_test.py | # Copyright (c) 2019 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.
from absl import app
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.suppo... |
def main(argv):
driver = test_util.create_chrome_webdriver()
try:
driver.get('http://www.google.com')
driver.get('chrome://history')
# wait for page to be loaded
wait = WebDriverWait(driver, 10)
wait.until(
expected_conditions.visibility_of_element_located((By.TAG_NAME,
... | if element is None:
return None
else:
return driver.execute_script(
"return arguments[0].shadowRoot.querySelector(arguments[1])", element,
selector) | identifier_body |
Utils.js | var Utils = {
_parseUrl: function (url) {
var query_string = {};
var url = url.substring(url.lastIndexOf("?") + 1).split("&")[0];
var vars = url.split("&");
for (var i = 0; i < vars.length; i++) |
return query_string;
},
getParameterFromUrl: function (url, parameter) {
//TODO: Check if the parameter exists
return this._parseUrl(url)[parameter];
}
}
export {Utils as default} | {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair... | conditional_block |
Utils.js | var Utils = { | var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0... | _parseUrl: function (url) {
var query_string = {};
var url = url.substring(url.lastIndexOf("?") + 1).split("&")[0];
var vars = url.split("&");
for (var i = 0; i < vars.length; i++) { | random_line_split |
yaml_parser.py | import yaml
# We try to load using the CSafeLoader for speed improvements.
try:
from yaml import CSafeLoader as Loader
except ImportError: #pragma: no cover
from yaml import SafeLoader as Loader #pragma: no cover
from hepdata_validator import LATEST_SCHEMA_VERSION
from hepdata_validator.submission_file_validat... | (self, data_in, *args, **kwargs):
"""
:param data_in: path to submission.yaml
:param args:
:param kwargs:
:raise ValueError:
"""
if not os.path.exists(data_in):
raise ValueError("File / Directory does not exist: %s" % data_in)
if os.path.isdir... | parse | identifier_name |
yaml_parser.py | import yaml
# We try to load using the CSafeLoader for speed improvements.
try:
from yaml import CSafeLoader as Loader
except ImportError: #pragma: no cover
from yaml import SafeLoader as Loader #pragma: no cover
from hepdata_validator import LATEST_SCHEMA_VERSION
from hepdata_validator.submission_file_validat... |
if len(submission_data) == 0:
raise RuntimeError("Submission file (%s) is empty" % data_in)
submission_file_validator = SubmissionFileValidator(schema_version=self.validator_schema_version)
if not submission_file_validator.validate(file_path=data_in,
... |
# first validate submission file:
with open(data_in, 'r') as submission_file:
submission_data = list(yaml.load_all(submission_file, Loader=Loader)) | random_line_split |
yaml_parser.py | import yaml
# We try to load using the CSafeLoader for speed improvements.
try:
from yaml import CSafeLoader as Loader
except ImportError: #pragma: no cover
from yaml import SafeLoader as Loader #pragma: no cover
from hepdata_validator import LATEST_SCHEMA_VERSION
from hepdata_validator.submission_file_validat... |
def parse(self, data_in, *args, **kwargs):
"""
:param data_in: path to submission.yaml
:param args:
:param kwargs:
:raise ValueError:
"""
if not os.path.exists(data_in):
raise ValueError("File / Directory does not exist: %s" % data_in)
i... | return ' '.join(
['%s: %s' % (key, ' | '.join([e.message for e in val])) for
key, val in list(message_dict.items())]) | identifier_body |
yaml_parser.py | import yaml
# We try to load using the CSafeLoader for speed improvements.
try:
from yaml import CSafeLoader as Loader
except ImportError: #pragma: no cover
from yaml import SafeLoader as Loader #pragma: no cover
from hepdata_validator import LATEST_SCHEMA_VERSION
from hepdata_validator.submission_file_validat... |
if os.path.isdir(data_in):
submission_filepath = os.path.join(data_in, 'submission.yaml')
if not os.path.exists(submission_filepath):
submission_filepath = os.path.join(data_in, 'submission.yml')
if not os.path.exists(submission_filepath):
... | raise ValueError("File / Directory does not exist: %s" % data_in) | conditional_block |
ToolsComboBox.js | // Copyright 2014-2022, University of Colorado Boulder
/**
* 'Tools' combo box, for selecting the visual representation for "balanced".
*
* @author Vasily Shakhov (MLearner)
* @author Chris Malley (PixelZoom, Inc.)
*/
import merge from '../../../../phet-core/js/merge.js';
import PhetFont from '../../../../scener... |
options = merge( {
xMargin: 10,
yMargin: 5,
cornerRadius: 4,
maxWidth: 600
}, options );
// options that cannot be specified by client
options.labelNode = new Text( balancingChemicalEquationsStrings.tools, {
font: FONT,
fontWeight: 'bold',
maxWidth: 100
} ... | * @constructor
*/
constructor( balanceRepresentationProperty, parentNode, options ) { | random_line_split |
ToolsComboBox.js | // Copyright 2014-2022, University of Colorado Boulder
/**
* 'Tools' combo box, for selecting the visual representation for "balanced".
*
* @author Vasily Shakhov (MLearner)
* @author Chris Malley (PixelZoom, Inc.)
*/
import merge from '../../../../phet-core/js/merge.js';
import PhetFont from '../../../../scener... | ( balanceRepresentationProperty, parentNode, options ) {
options = merge( {
xMargin: 10,
yMargin: 5,
cornerRadius: 4,
maxWidth: 600
}, options );
// options that cannot be specified by client
options.labelNode = new Text( balancingChemicalEquationsStrings.tools, {
font: F... | constructor | identifier_name |
ToolsComboBox.js | // Copyright 2014-2022, University of Colorado Boulder
/**
* 'Tools' combo box, for selecting the visual representation for "balanced".
*
* @author Vasily Shakhov (MLearner)
* @author Chris Malley (PixelZoom, Inc.)
*/
import merge from '../../../../phet-core/js/merge.js';
import PhetFont from '../../../../scener... | new ComboBoxItem( new Image( scales_png, { scale: 0.1875 } ), BalancedRepresentation.BALANCE_SCALES ),
// bar charts
new ComboBoxItem( new Image( charts_png, { scale: 0.375 } ), BalancedRepresentation.BAR_CHARTS )
];
super( items, balanceRepresentationProperty, parentNode, options );
}
}
... | {
options = merge( {
xMargin: 10,
yMargin: 5,
cornerRadius: 4,
maxWidth: 600
}, options );
// options that cannot be specified by client
options.labelNode = new Text( balancingChemicalEquationsStrings.tools, {
font: FONT,
fontWeight: 'bold',
maxWidth: 100
... | identifier_body |
times.ts | /**
* Multiplies the current matrix with a number, a matrix, a point or a vector.
*
* @param {number|Matrix|Point|Rational|Vector} a The object to multiply to the current matrix
* @return {Matrix|Point|Vector}
*/
times(a) {
var i, ii, j, jj, k, kk,
product = [], entry;
if (a.type === 'rational') {
a = a.co... | product.push(entry);
}
return new a.constructor(product);
}
}
} | for (i = 0, ii = this.rows; i < ii; i++) {
entry = 0;
for (j = 0, jj = this.cols; j < jj; j++) {
entry = MathLib.plus(entry, MathLib.times(this[i][j], a[j]));
} | random_line_split |
times.ts | /**
* Multiplies the current matrix with a number, a matrix, a point or a vector.
*
* @param {number|Matrix|Point|Rational|Vector} a The object to multiply to the current matrix
* @return {Matrix|Point|Vector}
*/
times(a) {
var i, ii, j, jj, k, kk,
product = [], entry;
if (a.type === 'rational') {
a = a.co... |
return new a.constructor(product);
}
}
}
| {
entry = 0;
for (j = 0, jj = this.cols; j < jj; j++) {
entry = MathLib.plus(entry, MathLib.times(this[i][j], a[j]));
}
product.push(entry);
} | conditional_block |
app.js | /*
* app.js
*/
var config = require('./config')
// 用于生产环境
if (!config.debug) {
}
require('colors');
var path = require("path");
var Loader = require("loader");
var express = require("express");
var errorhandler = require('errorhandler');
var session = req... |
// custom middleware
app.use(auth.authUser);
// app.use(auth.blockUser());
if (!config.debug) {
app.use(function (req, res, next) {
if (req.path.indexOf('/api') === -1) {
csurf()(req, res, next);
return;
}
next();
});
app.set('view cache', true);
}
// set static, dynamic helpers
_.exten... | app.use(session);
app.use(passport.initialize()); | random_line_split |
app.js | /*
* app.js
*/
var config = require('./config')
// 用于生产环境
if (!config.debug) {
}
require('colors');
var path = require("path");
var Loader = require("loader");
var express = require("express");
var errorhandler = require('errorhandler');
var session = req... | ire('socket.io')(server);
server.listen(config.port, function () {
logger.log("NodeClub listening on port %d", config.port);
logger.log("God bless love....");
logger.log("You can debug your app with http://" + config.host + ':' + config.port);
logger.log("");
});
io.use(function(socket, next) {
se... | rver 500 error:', err);
return res.status(500).send('500 status');
});
}
// 配置socket.io
var server = require('http').Server(app);
var io = requ | conditional_block |
template.test.ts | import { templateExtend, TemplateName, metroTemplate } from "../template";
describe("templateExtend", () => {
it("should return the given template if we pass no new options", () => {
const extendedTemplate = templateExtend(TemplateName.Metro, {});
expect(extendedTemplate).toEqual(metroTemplate);
});
it... | };
const extendedTemplate = templateExtend(TemplateName.Metro, options);
const expectedTemplate = expect.objectContaining({
colors: ["red", "green", "blue"],
branch: expect.objectContaining({
lineWidth: 20,
spacing: 50, // from original Metro template
}),
commit: ex... | },
}, | random_line_split |
portal_wizard.py |
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
from open... |
class wizard(osv.osv_memory):
"""
A wizard to manage the creation/removal of portal users.
"""
_name = 'portal.wizard'
_description = 'Portal Access Management'
_columns = {
'portal_id': fields.many2one('res.groups', domain=[('is_portal', '=', True)], required=True,
... | """ extract the email address from a user-friendly email address """
addresses = email_split(email)
return addresses[0] if addresses else '' | identifier_body |
portal_wizard.py |
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
from open... |
def _retrieve_user(self, cr, uid, wizard_user, context=None):
""" retrieve the (possibly inactive) user corresponding to wizard_user.partner_id
@param wizard_user: browse record of model portal.wizard.user
@return: browse record of model res.users
"""
context = dict... | if user and (portal in user.groups_id):
# if user belongs to portal only, deactivate it
if len(user.groups_id) <= 1:
user.write({'groups_id': [(3, portal.id)], 'active': False})
else:
user.write({'groups_id': [(3... | conditional_block |
portal_wizard.py |
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
from open... |
def action_apply(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids[0], context)
portal_user_ids = [user.id for user in wizard.user_ids]
self.pool.get('portal.wizard.user').action_apply(cr, uid, portal_user_ids, context)
return {'type': 'ir.actions.act_window_close... | }))
return {'value': {'user_ids': user_changes}} | random_line_split |
portal_wizard.py |
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
from open... | (self, cr, uid, ids, portal_id, context=None):
# for each partner, determine corresponding portal.wizard.user records
res_partner = self.pool.get('res.partner')
partner_ids = context and context.get('active_ids') or []
contact_ids = set()
user_changes = []
for partner in ... | onchange_portal_id | identifier_name |
index.d.ts | // Type definitions for Bootstrap 3.3.5
// Project: http://twitter.github.com/bootstrap/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface ModalOptions {
backdrop?: boolean|s... | dropdown(command: string): JQuery;
scrollspy(command: string): JQuery;
scrollspy(options?: ScrollSpyOptions): JQuery;
tab(): JQuery;
tab(command: string): JQuery;
tooltip(options?: TooltipOptions): JQuery;
tooltip(command: string): JQuery;
popover(options?: PopoverOptions): JQuery;
... | random_line_split | |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('eadid', models.CharField(unique=True, max_length=50, verbose_name=b'EAD Identifier')),
('title', models.CharField(max_length=200)),
('date', models.DateTim... | dependencies = [
]
operations = [
migrations.CreateModel(
name='Archive',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('label', models.CharField(help_text=b'Short label to identify an... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class | (migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Archive',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('label', models.CharField(help_text... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
|
dependencies = [
]
operations = [
migrations.CreateModel(
name='Archive',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('label', models.CharField(help_text=b'Short label to identi... | from django.db import models, migrations
class Migration(migrations.Migration): | random_line_split |
020.rs | extern crate num;
extern crate test;
extern crate time;
use num::bigint::{BigUint,ToBigUint};
use std::iter::{AdditiveIterator,MultiplicativeIterator,range_inclusive};
use std::num::One;
use std::os::args;
use test::black_box;
use time::precise_time_ns;
fn factorial(n: uint) -> BigUint {
range_inclusive(One::one(... |
fn main() {
match args().as_slice() {
[_] => {
println!("{}", f());
},
[_, ref iters] => {
let iters: u64 = from_str(iters.as_slice()).unwrap();
let start = precise_time_ns();
for _ in range(0, iters) {
black_box(f());
... | {
factorial(100).to_str().as_slice()
.chars()
.filter_map(|c| c.to_digit(10))
.sum()
} | identifier_body |
020.rs | extern crate num;
extern crate test;
extern crate time;
use num::bigint::{BigUint,ToBigUint};
use std::iter::{AdditiveIterator,MultiplicativeIterator,range_inclusive};
use std::num::One;
use std::os::args;
use test::black_box;
use time::precise_time_ns;
fn factorial(n: uint) -> BigUint {
range_inclusive(One::one(... |
let start = precise_time_ns();
for _ in range(0, iters) {
black_box(f());
}
let end = precise_time_ns();
println!("{}", end - start);
},
_ => unreachable!(),
}
} | },
[_, ref iters] => {
let iters: u64 = from_str(iters.as_slice()).unwrap(); | random_line_split |
020.rs | extern crate num;
extern crate test;
extern crate time;
use num::bigint::{BigUint,ToBigUint};
use std::iter::{AdditiveIterator,MultiplicativeIterator,range_inclusive};
use std::num::One;
use std::os::args;
use test::black_box;
use time::precise_time_ns;
fn | (n: uint) -> BigUint {
range_inclusive(One::one(), n.to_biguint().unwrap()).product()
}
#[inline]
fn f() -> uint {
factorial(100).to_str().as_slice()
.chars()
.filter_map(|c| c.to_digit(10))
.sum()
}
fn main() {
match args().as_slice() {
[_] =>... | factorial | identifier_name |
non_max_suppression_async.ts | /**
* @license
* Copyright 2020 Google LLC. 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 a... | * boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @return A 1D tensor with the selected box indices.
*... | * @param iouThreshold A float representing the threshold for deciding whether | random_line_split |
non_max_suppression_async.ts | /**
* @license
* Copyright 2020 Google LLC. 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 a... | $boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return tensor1d(selectedIndices, 'int32');
}
export const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
| {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
const inputs = nonMaxSuppSanityCheck(
$boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
maxOutputSize = inputs.maxOutputSize;
iouThreshol... | identifier_body |
non_max_suppression_async.ts | /**
* @license
* Copyright 2020 Google LLC. 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 a... |
return tensor1d(selectedIndices, 'int32');
}
export const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
| {
$scores.dispose();
} | conditional_block |
non_max_suppression_async.ts | /**
* @license
* Copyright 2020 Google LLC. 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 a... | (
boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,
maxOutputSize: number, iouThreshold = 0.5,
scoreThreshold = Number.NEGATIVE_INFINITY): Promise<Tensor1D> {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppres... | nonMaxSuppressionAsync_ | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.