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 |
|---|---|---|---|---|
utils.js | 'use strict';
const http = require('http');
const selenium = require('selenium-standalone');
const nodeStatic = require('node-static');
let grid, staticServer;
module.exports = {
startStaticServer,
stopStaticServer,
startSelenium,
stopSelenium
};
function startStaticServer() | }
function startSelenium() {
return new Promise((resolve, reject) => {
selenium.start((err, sel) => {
if (err) {
return reject(err);
}
console.log('Started Selenium server');
grid = sel;
resolve(sel);
});
});
}
function stopSelenium() {
return new Promise((resolve,... | {
return new Promise((resolve, reject) => {
const file = new nodeStatic.Server('./test/site');
const server = http
.createServer((request, response) => {
request
.addListener('end', () => {
file.serve(request, response);
})
.resume();
})
.lis... | identifier_body |
utils.js | 'use strict';
const http = require('http');
const selenium = require('selenium-standalone');
const nodeStatic = require('node-static');
let grid, staticServer;
module.exports = {
startStaticServer,
stopStaticServer,
startSelenium,
stopSelenium
};
function startStaticServer() {
return new Promise((resolve... | () {
return new Promise((resolve, reject) => {
selenium.start((err, sel) => {
if (err) {
return reject(err);
}
console.log('Started Selenium server');
grid = sel;
resolve(sel);
});
});
}
function stopSelenium() {
return new Promise((resolve, reject) => {
grid.on(... | startSelenium | identifier_name |
utils.js | 'use strict';
const http = require('http');
const selenium = require('selenium-standalone');
const nodeStatic = require('node-static');
let grid, staticServer;
module.exports = {
startStaticServer,
stopStaticServer,
startSelenium,
stopSelenium
};
function startStaticServer() {
return new Promise((resolve... |
console.log('Started static server on port ' + 8080);
staticServer = server;
resolve(server);
});
});
}
function startSelenium() {
return new Promise((resolve, reject) => {
selenium.start((err, sel) => {
if (err) {
return reject(err);
}
console.log('Star... | {
return reject(err);
} | conditional_block |
index.ts | export const words = [
'alias',
'consequatur',
'aut',
'perferendis',
'sit',
'voluptatem',
'accusantium',
'doloremque',
'aperiam',
'eaque',
'ipsa',
'quae',
'ab',
'illo',
'inventore',
'veritatis',
'et',
'quasi',
'architecto',
'beatae',
'vitae',
'dicta',
'sunt',
'explicabo',... | 'saepe',
'eveniet',
'ut',
'et',
'voluptates',
'repudiandae',
'sint',
'et',
'molestiae',
'non',
'recusandae',
'itaque',
'earum',
'rerum',
'hic',
'tenetur',
'a',
'sapiente',
'delectus',
'ut',
'aut',
'reiciendis',
'voluptatibus',
'maiores',
'doloribus',
'asperiores',
'... | 'aut',
'rerum',
'necessitatibus', | random_line_split |
jquery.pjax.js | hash
var context = options.context = findContainerFor(options.container)
// We want the browser to maintain two separate internal caches: one
// for pjax'd partial page loads and one for normal page loads.
// Without adding this secret parameter, some browsers will often
// confuse the two.
if (!options.d... |
var previousState = pjax.state
var state = event.state
var direction
if (state && state.container) {
// When coming forward from a separate history session, will get an
// initial pop with a state we are already at. Skip reloading the current
// page.
if (initialPop && initialURL == state.url... | {
abortXHR(pjax.xhr)
} | conditional_block |
jquery.pjax.js | if (previousState) {
// If popping back to the same state, just skip.
// Could be clicking back from hashchange rather than a pushState.
if (previousState.id === state.id) return
// Since state IDs always increase, we can deduce the navigation direction
direction = previousState.id < sta... | if (!obj.title)
obj.title = $fragment.attr('title') || $fragment.data('title')
}
| random_line_split | |
jquery.pjax.js | }
// If there is a layout version mismatch, hard load the new url
if (currentVersion && latestVersion && currentVersion !== latestVersion) {
locationReplace(container.url)
return
}
// If the new response is missing a body, hard load the page
if (!container.contents) {
locatio... | cloneContents | identifier_name | |
jquery.pjax.js | if (blurFocus) {
try {
document.activeElement.blur()
} catch (e) {
}
}
if (container.title) document.title = container.title
fire('pjax:beforeReplace', [container.contents, options], {
state: pjax.state,
previousState: previousState
})
context.html(contain... | {
var a = document.createElement('a')
a.href = url
return a
} | identifier_body | |
trait.rs | // Test traits
trait Foo {
fn bar(x: i32 ) -> Baz< U> |
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType ; // Some comment
fn baz(&mut self ) -> i32 ;
fn... | { Baz::new()
} | identifier_body |
trait.rs | // Test traits
trait Foo {
fn | (x: i32 ) -> Baz< U> { Baz::new()
}
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType ; // Some comment
... | bar | identifier_name |
trait.rs | // Test traits
trait Foo {
fn bar(x: i32 ) -> Baz< U> { Baz::new()
}
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetTyp... | trait Ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T> where T: Foo {}
trait FooBar<T> : Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt where J: Bar { fn test(); }
trait WhereList<T, J> where T: Foo, J: Bar {} | }
trait Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T>
where T: Foo {}
| random_line_split |
utils.py | import scipy.misc, numpy as np, os, sys
def save_img(out_path, img):
img = np.clip(img, 0, 255).astype(np.uint8)
scipy.misc.imsave(out_path, img)
def scale_img(style_path, style_scale):
|
def get_img(src, img_size=False):
img = scipy.misc.imread(src, mode='RGB') # misc.imresize(, (256, 256, 3))
if not (len(img.shape) == 3 and img.shape[2] == 3):
img = np.dstack((img,img,img))
if img_size != False:
img = scipy.misc.imresize(img, img_size)
return img
def exists(p, msg):
as... | scale = float(style_scale)
o0, o1, o2 = scipy.misc.imread(style_path, mode='RGB').shape
scale = float(style_scale)
new_shape = (int(o0 * scale), int(o1 * scale), o2)
style_target = _get_img(style_path, img_size=new_shape)
return style_target | identifier_body |
utils.py | import scipy.misc, numpy as np, os, sys
def save_img(out_path, img):
img = np.clip(img, 0, 255).astype(np.uint8)
scipy.misc.imsave(out_path, img)
def scale_img(style_path, style_scale):
scale = float(style_scale)
o0, o1, o2 = scipy.misc.imread(style_path, mode='RGB').shape
scale = float(style_scal... | (p, msg):
assert os.path.exists(p), msg
def list_files(in_path):
files = []
for (dirpath, dirnames, filenames) in os.walk(in_path):
files.extend(filenames)
break
return files
| exists | identifier_name |
utils.py | import scipy.misc, numpy as np, os, sys
def save_img(out_path, img):
img = np.clip(img, 0, 255).astype(np.uint8)
scipy.misc.imsave(out_path, img)
def scale_img(style_path, style_scale):
scale = float(style_scale)
o0, o1, o2 = scipy.misc.imread(style_path, mode='RGB').shape
scale = float(style_scal... |
return img
def exists(p, msg):
assert os.path.exists(p), msg
def list_files(in_path):
files = []
for (dirpath, dirnames, filenames) in os.walk(in_path):
files.extend(filenames)
break
return files
| img = scipy.misc.imresize(img, img_size) | conditional_block |
utils.py | import scipy.misc, numpy as np, os, sys
def save_img(out_path, img):
img = np.clip(img, 0, 255).astype(np.uint8)
scipy.misc.imsave(out_path, img)
def scale_img(style_path, style_scale):
scale = float(style_scale)
o0, o1, o2 = scipy.misc.imread(style_path, mode='RGB').shape
scale = float(style_scal... | return img
def exists(p, msg):
assert os.path.exists(p), msg
def list_files(in_path):
files = []
for (dirpath, dirnames, filenames) in os.walk(in_path):
files.extend(filenames)
break
return files | random_line_split | |
qnotify.py | #!/usr/bin/env python3
# dirtool.py - diff tool for directories
# Copyright (C) 2018 Ingo Ruhnke <grumbel@gmail.com>
#
# 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 3 of the Li... | (path):
print("file_changed: {}".format(path))
def main(argv):
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QCoreApplication([])
watcher = QFileSystemWatcher()
print("Watching /tmp/")
watcher.addPath("/tmp/")
watcher.addPath("/tmp/foo")
# Files have to be watched specifically... | file_changed | identifier_name |
qnotify.py | #!/usr/bin/env python3
# dirtool.py - diff tool for directories
# Copyright (C) 2018 Ingo Ruhnke <grumbel@gmail.com>
#
# 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 3 of the Li... |
# EOF #
| main(sys.argv) | conditional_block |
qnotify.py | #!/usr/bin/env python3
# dirtool.py - diff tool for directories
# Copyright (C) 2018 Ingo Ruhnke <grumbel@gmail.com>
#
# 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 3 of the Li... | sys.exit(app.exec())
if __name__ == "__main__":
main(sys.argv)
# EOF #
| signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QCoreApplication([])
watcher = QFileSystemWatcher()
print("Watching /tmp/")
watcher.addPath("/tmp/")
watcher.addPath("/tmp/foo")
# Files have to be watched specifically for this to trigger.
# Deleting and recreating a file makes this no ... | identifier_body |
qnotify.py | #!/usr/bin/env python3
# dirtool.py - diff tool for directories
# Copyright (C) 2018 Ingo Ruhnke <grumbel@gmail.com>
#
# 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 3 of the Li... | signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QCoreApplication([])
watcher = QFileSystemWatcher()
print("Watching /tmp/")
watcher.addPath("/tmp/")
watcher.addPath("/tmp/foo")
# Files have to be watched specifically for this to trigger.
# Deleting and recreating a file makes this... | def main(argv): | random_line_split |
pyedit_assign_params_to_attributes.py | """Assign Params to Attributes by Joel Hedlund <joel.hedlund at gmail.com>.
PyDev script for generating python code that assigns method parameter
values to attributes of self with the same name. Activates with 'a' by
default. Edit global constants ACTIVATION_STRING and WAIT_FOR_ENTER if this
does not suit your needs... |
assert cmd is not None
assert editor is not None
if DEBUG and cmd == 'onSave':
from org.python.pydev.jython import JythonPlugin #@UnresolvedImport
editor.pyEditScripting.interpreter = JythonPlugin.newPythonInterpreter()
from org.eclipse.jface.action import Action #@UnresolvedImport
#==================... | from org.python.pydev.editor import PyEdit #@UnresolvedImport
cmd = 'command string'
editor = PyEdit | conditional_block |
pyedit_assign_params_to_attributes.py | """Assign Params to Attributes by Joel Hedlund <joel.hedlund at gmail.com>.
PyDev script for generating python code that assigns method parameter
values to attributes of self with the same name. Activates with 'a' by
default. Edit global constants ACTIVATION_STRING and WAIT_FOR_ENTER if this
does not suit your needs... | from org.python.pydev.editor.correctionassist import PythonCorrectionProcessor #@UnresolvedImport
import assign_params_to_attributes_action as helper
import assign_params_to_attributes_assist
#------------------------------------------------------------------------------------... | random_line_split | |
pyedit_assign_params_to_attributes.py | """Assign Params to Attributes by Joel Hedlund <joel.hedlund at gmail.com>.
PyDev script for generating python code that assigns method parameter
values to attributes of self with the same name. Activates with 'a' by
default. Edit global constants ACTIVATION_STRING and WAIT_FOR_ENTER if this
does not suit your needs... | (self):
self.assign_to_attribs_helper.run()
#=======================================================================================================================
# Actually bind the actions
#====================================================================================================================... | run | identifier_name |
pyedit_assign_params_to_attributes.py | """Assign Params to Attributes by Joel Hedlund <joel.hedlund at gmail.com>.
PyDev script for generating python code that assigns method parameter
values to attributes of self with the same name. Activates with 'a' by
default. Edit global constants ACTIVATION_STRING and WAIT_FOR_ENTER if this
does not suit your needs... |
def run(self):
self.assign_to_attribs_helper.run()
#=======================================================================================================================
# Actually bind the actions
#===================================================================================================... | Action.__init__(self)
self.assign_to_attribs_helper = assign_to_attribs_helper | identifier_body |
Reflection.ts | /// <reference path="../mz.ts" />
namespace Reflect {
var originalMetadata = Reflect.metadata;
export var MetadataInfo: string | symbol = Symbol("mz.metadata.typings");
var valueSetter = {
enumerable: false,
writable: false,
configurable: false,
value: null
}
expo... | (metadataKey: any, metadataValue: any) {
if ('design:type' == metadataKey) {
if (typeof MetadataInfo == "string") {
return function decorator(target: Object, targetKey?: string | symbol): void {
let typings = target[MetadataInfo];
if (!typings... | metadata | identifier_name |
Reflection.ts | /// <reference path="../mz.ts" />
namespace Reflect {
var originalMetadata = Reflect.metadata;
export var MetadataInfo: string | symbol = Symbol("mz.metadata.typings");
var valueSetter = {
enumerable: false,
writable: false,
configurable: false,
value: null
}
expo... | typings = setObjectSymbol(target, MetadataInfo, {});
}
typings[targetKey] = metadataValue;
originalMetadata && originalMetadata(metadataKey, metadataValue).apply(this, arguments);
}
} else {
... | if (!typings) { | random_line_split |
Reflection.ts | /// <reference path="../mz.ts" />
namespace Reflect {
var originalMetadata = Reflect.metadata;
export var MetadataInfo: string | symbol = Symbol("mz.metadata.typings");
var valueSetter = {
enumerable: false,
writable: false,
configurable: false,
value: null
}
expo... | else {
return object['__proto__'];
}
}
} | {
return Object.getPrototypeOf(object);
} | conditional_block |
Reflection.ts | /// <reference path="../mz.ts" />
namespace Reflect {
var originalMetadata = Reflect.metadata;
export var MetadataInfo: string | symbol = Symbol("mz.metadata.typings");
var valueSetter = {
enumerable: false,
writable: false,
configurable: false,
value: null
}
expo... |
originalMetadata && originalMetadata(metadataKey, metadataValue).apply(this, arguments);
}
}
} else return originalMetadata && originalMetadata(metadataKey, metadataValue) || undefined;
}
export function setObjectSymbol<T>(target: Object, symbol: strin... | {
if ('design:type' == metadataKey) {
if (typeof MetadataInfo == "string") {
return function decorator(target: Object, targetKey?: string | symbol): void {
let typings = target[MetadataInfo];
if (!typings) {
typings = s... | identifier_body |
main.js | define(function(require) {
var $ = require('./jquery');
var marked = require('./marked');
var prettify = require('./prettify');
var title = document.title;
function initPage() {
marked.setOptions({
highlight: function(code) {
return prettify.prettyPrintOne(escape(code));
}
});
$('.section').each... |
}
}, 'a');
}
$('.footer .top').on({
click: function() {
window.scrollTo(0, 0);
}
});
}
function initShare() {
if (!window.WeixinJSBridge) {
return;
}
try {
WeixinJSBridge.on('menu:share:appmessage', function(argv) {
WeixinJSBridge.invoke('sendAppMessage', getShareData());
}... | {
updateView(this.href.replace(/(?:.*(#\w+)|.*)/, '$1') || '#intro');
} | conditional_block |
main.js | define(function(require) {
var $ = require('./jquery');
var marked = require('./marked');
var prettify = require('./prettify');
var title = document.title;
function initPage() {
marked.setOptions({
highlight: function(code) {
return prettify.prettyPrintOne(escape(code));
}
});
$('.section').each... | WeixinJSBridgeReady: initShare
});
if ('onhashchange' in window) {
$(window).on({
hashchange: function() {
updateView();
}
});
} else {
$('body').on({
click: function() {
if (this.href.indexOf('#') >= 0) {
updateView(this.href.replace(/(?:.*(#\w+)|.*)/, '$1') || '#intro');
... | random_line_split | |
main.js | define(function(require) {
var $ = require('./jquery');
var marked = require('./marked');
var prettify = require('./prettify');
var title = document.title;
function initPage() {
marked.setOptions({
highlight: function(code) {
return prettify.prettyPrintOne(escape(code));
}
});
$('.section').each... |
function escape(code) {
return code
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
initPage();
initEvent();
}); | {
id = id || location.href.replace(/(?:.*(#\w+)|.*)/, '$1') || '#intro';
$('.section').hide();
document.title = title + ' - ' + $(id).show().find('h2').eq(0).text();
setTimeout(window.scrollTo, 0, 0, 0);
ga('send', 'event', 'section', 'view', id);
} | identifier_body |
main.js | define(function(require) {
var $ = require('./jquery');
var marked = require('./marked');
var prettify = require('./prettify');
var title = document.title;
function initPage() {
marked.setOptions({
highlight: function(code) {
return prettify.prettyPrintOne(escape(code));
}
});
$('.section').each... | () {
if (!window.WeixinJSBridge) {
return;
}
try {
WeixinJSBridge.on('menu:share:appmessage', function(argv) {
WeixinJSBridge.invoke('sendAppMessage', getShareData());
});
WeixinJSBridge.on('menu:share:timeline', function(argv) {
WeixinJSBridge.invoke('shareTimeline', getShareData());
});
... | initShare | identifier_name |
views.py | from urllib.parse import urlparse
from django.conf import settings
from django.core.files.storage import default_storage
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from api.applications.models import ShowApplicationSettings
from api.shows.models import upload_to_show_cov... | file = request.FILES['file']
filename = upload_to_show_banner(None, file.name)
default_storage.save(filename, file)
return JsonResponse({'success': True, 'filename': filename}) | cfg = ShowApplicationSettings.get_solo()
if not cfg.applications_open:
return JsonResponse({'success': False, 'message': "Show applications not open."})
if request.method == 'POST': | random_line_split |
views.py | from urllib.parse import urlparse
from django.conf import settings
from django.core.files.storage import default_storage
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from api.applications.models import ShowApplicationSettings
from api.shows.models import upload_to_show_cov... | (request):
if not verify_origin(request):
return JsonResponse({'success': False, 'message': "Invalid origin"})
cfg = ShowApplicationSettings.get_solo()
if not cfg.applications_open:
return JsonResponse({'success': False, 'message': "Show applications not open."})
if request.method == '... | upload_cover | identifier_name |
views.py | from urllib.parse import urlparse
from django.conf import settings
from django.core.files.storage import default_storage
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from api.applications.models import ShowApplicationSettings
from api.shows.models import upload_to_show_cov... | if not verify_origin(request):
return JsonResponse({'success': False, 'message': "Invalid origin"})
cfg = ShowApplicationSettings.get_solo()
if not cfg.applications_open:
return JsonResponse({'success': False, 'message': "Show applications not open."})
if request.method == 'POST':
... | identifier_body | |
views.py | from urllib.parse import urlparse
from django.conf import settings
from django.core.files.storage import default_storage
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from api.applications.models import ShowApplicationSettings
from api.shows.models import upload_to_show_cov... | file = request.FILES['file']
filename = upload_to_show_banner(None, file.name)
default_storage.save(filename, file)
return JsonResponse({'success': True, 'filename': filename}) | conditional_block | |
setupJest.ts | // re: https://github.com/facebook/react-native/issues/19955
// and https://github.com/facebook/metro/pull/198
//
// import applyDecoratedDescriptor from "@babel/runtime/helpers/applyDecoratedDescriptor"
// import initializerDefineProperty from "@babel/runtime/helpers/initializerDefineProperty"
// declare var babelHelp... |
const originalConsoleError = console.error
// TODO: Remove once we're no longer using JSDOM for enzyme static rendering.
console.error = (message?: any) => {
if (
typeof message === "string" &&
(message.includes("is using uppercase HTML. Always use lowercase HTML tags in React.") ||
/Warning: React d... | {
jest.mock(path, () => mockModuleName)
} | identifier_body |
setupJest.ts | // re: https://github.com/facebook/react-native/issues/19955
// and https://github.com/facebook/metro/pull/198
//
// import applyDecoratedDescriptor from "@babel/runtime/helpers/applyDecoratedDescriptor"
// import initializerDefineProperty from "@babel/runtime/helpers/initializerDefineProperty"
// declare var babelHelp... | (path: string, mockModuleName: string) {
jest.mock(path, () => mockModuleName)
}
const originalConsoleError = console.error
// TODO: Remove once we're no longer using JSDOM for enzyme static rendering.
console.error = (message?: any) => {
if (
typeof message === "string" &&
(message.includes("is using upp... | mockedModule | identifier_name |
setupJest.ts | // re: https://github.com/facebook/react-native/issues/19955
// and https://github.com/facebook/metro/pull/198
//
// import applyDecoratedDescriptor from "@babel/runtime/helpers/applyDecoratedDescriptor"
// import initializerDefineProperty from "@babel/runtime/helpers/initializerDefineProperty"
// declare var babelHelp... | imageMediaNotAvailable: "imageMediaNotAvailable",
cameraAccessDenied: "cameraAccessDenied",
saveFailed: "saveFailed",
},
}
NativeModules.ARCocoaConstantsModule = {
UIApplicationOpenSettingsURLString: "UIApplicationOpenSettingsURLString",
AREnabled: true,
}
NativeModules.Emission = {
userAgent: "Jest... | NativeModules.ARTakeCameraPhotoModule = {
errorCodes: {
cameraNotAvailable: "cameraNotAvailable", | random_line_split |
18.rs | use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn | () -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum Terrain {
Open,
Trees,
Lumberyard
}
type Point = (isize, isize);
type Landsca... | get_input | identifier_name |
18.rs | use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn get_input() -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
... | fn get_neighbors((x, y): Point, landscape: &Landscape) -> Vec<Point> {
(x - 1..x + 2)
.flat_map(|x| (y - 1..y + 2).map(move |y| (x, y)))
.filter(|&p| p != (x, y) && landscape.contains_key(&p))
.collect()
}
fn evolve(landscape: &Landscape) -> Landscape {
landscape.iter()
.map(|(&p, &terrain)| {
... | })
}
| random_line_split |
18.rs | use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn get_input() -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
... | Terrain::Lumberyard => {
if neighbors.iter().any(|n| landscape[n] == Terrain::Lumberyard)
&& neighbors.iter().any(|n| landscape[n] == Terrain::Trees) {
Terrain::Lumberyard
} else {
Terrain::Open
}
... | {
landscape.iter()
.map(|(&p, &terrain)| {
let neighbors = get_neighbors(p, &landscape);
(p, match terrain {
Terrain::Open => {
if neighbors.iter().filter(|&n| landscape[n] == Terrain::Trees).count() >= 3 {
Terrain::Trees
} else {
... | identifier_body |
lib.rs | //! This crate is a Rust library for using the [Serde](https://github.com/serde-rs/serde)
//! serialization framework with bencode data.
//!
//! # Examples
//!
//! ```
//! use serde_derive::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
//! struct Product {
//! name: Strin... | //! assert_eq!(
//! deserialized,
//! Product {
//! name: "Apple".to_string(),
//! price: 130,
//! }
//! );
//!
//! Ok(())
//! }
//! ```
pub mod de;
pub mod error;
pub mod ser;
pub mod value;
pub use de::{from_bytes, from_str, Deserializer};
pub use error::{... | //! let deserialized: Product = serde_bencode::from_str(&serialized)?;
//! | random_line_split |
index.d.ts | // Type definitions for ping 0.2
// Project: http://github.com/danielzzz/node-ping
// Definitions by: Richard Honor <https://github.com/RMHonor>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export interface PingConfig {
/**
* Map IP address to hostname or not. ... | export const sys: {
/**
* Performs a system ping utility.
*
* @param addr Hostname or IP address
* @param cb Response callback.
* First argument is successful response boolean.
* Second argument is any error, `null` if no error.
* @param config Optional configuration
*/... | */
stddev: string;
}
| random_line_split |
mytaskprolog.py | #
# Copyright 2019-2022 Ghent University
#
# This file is part of vsc-mympirun,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# the Flemish Research Foundat... | def setUp(self):
"""Prepare to run test."""
super(TaskPrologEnd2End, self).setUp()
self.script = os.path.join(os.path.dirname(self.script), 'mytaskprolog.py')
def test_simple(self):
origaff = sched_getaffinity()
aff = sched_getaffinity()
aff.set_bits([1]) # only us... | identifier_body | |
mytaskprolog.py | #
# Copyright 2019-2022 Ghent University
#
# This file is part of vsc-mympirun,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# the Flemish Research Foundat... | (PMITest):
def setUp(self):
"""Prepare to run test."""
super(TaskPrologEnd2End, self).setUp()
self.script = os.path.join(os.path.dirname(self.script), 'mytaskprolog.py')
def test_simple(self):
origaff = sched_getaffinity()
aff = sched_getaffinity()
aff.set_bits(... | TaskPrologEnd2End | identifier_name |
mytaskprolog.py | #
# Copyright 2019-2022 Ghent University
#
# This file is part of vsc-mympirun,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# the Flemish Research Foundat... |
aff = sched_getaffinity()
aff.set_bits([1]) # only use first core (we can always assume there is one core
sched_setaffinity(aff)
self.pmirun([], pattern='export CUDA_VISIBLE_DEVICES=0')
# restore
sched_setaffinity(origaff) | self.script = os.path.join(os.path.dirname(self.script), 'mytaskprolog.py')
def test_simple(self):
origaff = sched_getaffinity() | random_line_split |
bootstrap3-typeahead.min.js | element.data('active', items[0]);
} else {
this.$element.data('active', null);
}
// Add item
if (this.options.addItem){
items.push(this.options.addItem);
}
if (this.options.items == 'all') {
return this.render(items).show();
} else {
return thi... | autoSelect: true,
afterSelect: $.noop,
addItem: false, | random_line_split | |
day14.rs | use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);... | }
pub fn part2(input: &mut dyn Read) -> String {
parts_common(input, 40)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_implementation;
const SAMPLE: &[u8] = include_bytes!("samples/14.txt");
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 1588);
}
... | .to_string()
}
pub fn part1(input: &mut dyn Read) -> String {
parts_common(input, 10) | random_line_split |
day14.rs | use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);... | (pairs: Pairs, rules: &Rules) -> Pairs {
let mut new_pairs = Pairs::default();
pairs.iter().enumerate().for_each(|(first, row)| {
row.iter().enumerate().for_each(|(second, &count)| {
let product = rules[first][second] as usize;
new_pairs[first][product] += count;
new... | update | identifier_name |
day14.rs | use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);... |
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 2188189693529u64);
}
}
| {
test_implementation(part1, SAMPLE, 1588);
} | identifier_body |
properties_data_metaball.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 ... |
class DATA_PT_metaball(DataButtonsPanel, bpy.types.Panel):
bl_label = "Metaball"
def draw(self, context):
layout = self.layout
mball = context.meta_ball
split = layout.split()
col = split.column()
col.label(text="Resolution:")
sub = col.colum... | layout.template_ID(space, "pin_id", unlink="None") | conditional_block |
properties_data_metaball.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 ... | (self, context):
layout = self.layout
mball = context.meta_ball
split = layout.split()
col = split.column()
col.label(text="Resolution:")
sub = col.column(align=True)
sub.prop(mball, "resolution", text="View")
sub.prop(mball, "render_resoluti... | draw | identifier_name |
properties_data_metaball.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 ... |
@classmethod
def poll(cls, context):
return context.meta_ball
class DATA_PT_context_metaball(DataButtonsPanel, bpy.types.Panel):
bl_label = ""
bl_options = {'HIDE_HEADER'}
def draw(self, context):
layout = self.layout
ob = context.object
mball = con... | bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "data"
| random_line_split |
properties_data_metaball.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 ... |
class DATA_PT_metaball(DataButtonsPanel, bpy.types.Panel):
bl_label = "Metaball"
def draw(self, context):
layout = self.layout
mball = context.meta_ball
split = layout.split()
col = split.column()
col.label(text="Resolution:")
sub = col.colum... | bl_label = ""
bl_options = {'HIDE_HEADER'}
def draw(self, context):
layout = self.layout
ob = context.object
mball = context.meta_ball
space = context.space_data
if ob:
layout.template_ID(ob, "data", unlink="None")
elif mball:
... | identifier_body |
application_credit_test.py | import shopify
import json
from test.test_helper import TestCase
class ApplicationCreditTest(TestCase):
def test_get_application_credit(self):
self.fake("application_credits/445365009", method="GET", body=self.load_fixture("application_credit"), code=200) | self.fake("application_credits", method="GET", body=self.load_fixture("application_credits"), code=200)
application_credits = shopify.ApplicationCredit.find()
self.assertEqual(1, len(application_credits))
self.assertEqual(445365009, application_credits[0].id)
def test_create_applica... | application_credit = shopify.ApplicationCredit.find(445365009)
self.assertEqual("5.00", application_credit.amount)
def test_get_all_application_credits(self): | random_line_split |
application_credit_test.py | import shopify
import json
from test.test_helper import TestCase
class | (TestCase):
def test_get_application_credit(self):
self.fake("application_credits/445365009", method="GET", body=self.load_fixture("application_credit"), code=200)
application_credit = shopify.ApplicationCredit.find(445365009)
self.assertEqual("5.00", application_credit.amount)
def test... | ApplicationCreditTest | identifier_name |
application_credit_test.py | import shopify
import json
from test.test_helper import TestCase
class ApplicationCreditTest(TestCase):
def test_get_application_credit(self):
self.fake("application_credits/445365009", method="GET", body=self.load_fixture("application_credit"), code=200)
application_credit = shopify.ApplicationCr... |
def test_create_application_credit(self):
self.fake(
"application_credits",
method="POST",
body=self.load_fixture("application_credit"),
headers={"Content-type": "application/json"},
code=201,
)
application_credit = shopify.Appli... | self.fake("application_credits", method="GET", body=self.load_fixture("application_credits"), code=200)
application_credits = shopify.ApplicationCredit.find()
self.assertEqual(1, len(application_credits))
self.assertEqual(445365009, application_credits[0].id) | identifier_body |
__init__.py | """The ReCollect Waste integration.""" |
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_... | from __future__ import annotations | random_line_split |
__init__.py | """The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassi... | (hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
| async_unload_entry | identifier_name |
__init__.py | """The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassi... |
return unload_ok
| hass.data[DOMAIN].pop(entry.entry_id) | conditional_block |
__init__.py | """The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassi... |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload an RainMachine config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
| """Handle an options update."""
await hass.config_entries.async_reload(entry.entry_id) | identifier_body |
dictionaryManagementService.ts | import IConfig from 'src/core/IConfig';
import {GithubDictionaryUtil} from 'src/core/githubDictionaryUtil';
import ConfigKeys from 'src/configKeys';
import log from 'src/log';
const console = log.setCategory('Dictionary Mgmt Svc');
export interface AppKeys {
global: string;
local: string;
cache: string;... | (
global: naiveDictionary,
local: naiveDictionary,
): cachedDictionary {
let keySet = new Set(Object.keys(global).concat(Object.keys(local)));
let cache = [...keySet]
.map(key => {
if (key in local) {
return {
k... | generateCachedDictionary | identifier_name |
dictionaryManagementService.ts | import IConfig from 'src/core/IConfig';
import {GithubDictionaryUtil} from 'src/core/githubDictionaryUtil';
import ConfigKeys from 'src/configKeys';
import log from 'src/log';
const console = log.setCategory('Dictionary Mgmt Svc');
export interface AppKeys {
global: string;
local: string;
cache: string;... | export class CachedDictionaryService {
constructor(protected config: IConfig, protected keys: AppKeys) {}
// Performance could be improved by modifying the cache in place instead of constructing it every time
// but this is logically simpler and hasn't been an issue.
protected generateCachedDictionary(... | /**
* An implementation of the dictionary service that provides basic CRUD operations and updates and
* internal cache alongside them.
*/ | random_line_split |
dictionaryManagementService.ts | import IConfig from 'src/core/IConfig';
import {GithubDictionaryUtil} from 'src/core/githubDictionaryUtil';
import ConfigKeys from 'src/configKeys';
import log from 'src/log';
const console = log.setCategory('Dictionary Mgmt Svc');
export interface AppKeys {
global: string;
local: string;
cache: string;... |
});
}
public update(key: string, value: string) {
console.debug(`setting translation for [${key.trim()}] to [${value.trim()}]`);
return this.local
.then(localDict => {
localDict[key.trim()] = value.trim();
return this.config.set(this.keys.loc... | {
return this.global.then(globalDict =>
key in globalDict ? globalDict[key] : undefined,
);
} | conditional_block |
dictionaryManagementService.ts | import IConfig from 'src/core/IConfig';
import {GithubDictionaryUtil} from 'src/core/githubDictionaryUtil';
import ConfigKeys from 'src/configKeys';
import log from 'src/log';
const console = log.setCategory('Dictionary Mgmt Svc');
export interface AppKeys {
global: string;
local: string;
cache: string;... |
public getTranslation(key: string) {
return this.local.then(localDict => {
if (key in localDict) {
return localDict[key];
} else {
return this.global.then(globalDict =>
key in globalDict ? globalDict[key] : undefined,
... | {
const dict = this.config.get(this.keys.global) as Promise<naiveDictionary>;
return dict.catch(() =>
this.config.set(this.keys.global, {}).then(() => this.global),
);
} | identifier_body |
conftest.py | import numpy as np
import pandas as pd
import pytest
from .const import RANDOM_SEED, TARGET_COL
N_CATEGORY = 50
N_OBS = 10000
N_CAT_FEATURE = 10
N_NUM_FEATURE = 5
@pytest.fixture(scope="module")
def generate_data():
generated = False
def _generate_data():
if not generated:
|
return df
yield _generate_data
| assert N_CAT_FEATURE > 1
assert N_NUM_FEATURE > 3
np.random.seed(RANDOM_SEED)
X_num = np.random.normal(size=(N_OBS, N_NUM_FEATURE))
X_cat = np.random.randint(0, N_CATEGORY, size=(N_OBS, N_CAT_FEATURE))
df = pd.DataFrame(
np.hstack((X_num, X_ca... | conditional_block |
conftest.py | import numpy as np
import pandas as pd
import pytest
from .const import RANDOM_SEED, TARGET_COL
N_CATEGORY = 50
N_OBS = 10000
N_CAT_FEATURE = 10
N_NUM_FEATURE = 5
@pytest.fixture(scope="module")
def | ():
generated = False
def _generate_data():
if not generated:
assert N_CAT_FEATURE > 1
assert N_NUM_FEATURE > 3
np.random.seed(RANDOM_SEED)
X_num = np.random.normal(size=(N_OBS, N_NUM_FEATURE))
X_cat = np.random.randint(0, N_CATEGORY, size=... | generate_data | identifier_name |
conftest.py | import numpy as np
import pandas as pd
import pytest
from .const import RANDOM_SEED, TARGET_COL
N_CATEGORY = 50
N_OBS = 10000
N_CAT_FEATURE = 10
N_NUM_FEATURE = 5
@pytest.fixture(scope="module")
def generate_data():
generated = False
def _generate_data():
| return df
yield _generate_data
| if not generated:
assert N_CAT_FEATURE > 1
assert N_NUM_FEATURE > 3
np.random.seed(RANDOM_SEED)
X_num = np.random.normal(size=(N_OBS, N_NUM_FEATURE))
X_cat = np.random.randint(0, N_CATEGORY, size=(N_OBS, N_CAT_FEATURE))
df = pd.DataFrame(
... | identifier_body |
conftest.py | import numpy as np
import pandas as pd
import pytest
| N_OBS = 10000
N_CAT_FEATURE = 10
N_NUM_FEATURE = 5
@pytest.fixture(scope="module")
def generate_data():
generated = False
def _generate_data():
if not generated:
assert N_CAT_FEATURE > 1
assert N_NUM_FEATURE > 3
np.random.seed(RANDOM_SEED)
X_num = np... | from .const import RANDOM_SEED, TARGET_COL
N_CATEGORY = 50 | random_line_split |
test_delete_local_backupstorage.py | import zstackwoodpecker.operations.scheduler_operations as sch_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.tag_operations as tag_ops
import zstackwoodpecker.operations.backupstorage_operations as bs_ops
import zstackwoodpecker.test_lib as test_lib
import zsta... |
if trigger1:
sch_ops.del_scheduler_trigger(trigger1.uuid)
if trigger2:
sch_ops.del_scheduler_trigger(trigger2.uuid)
| sch_ops.del_scheduler_job_group(job_group.uuid) | conditional_block |
test_delete_local_backupstorage.py | import zstackwoodpecker.operations.tag_operations as tag_ops
import zstackwoodpecker.operations.backupstorage_operations as bs_ops
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import time
import os
vmBackup = 'vmBackup'
vol... | import zstackwoodpecker.operations.scheduler_operations as sch_ops
import zstackwoodpecker.operations.resource_operations as res_ops | random_line_split | |
test_delete_local_backupstorage.py | import zstackwoodpecker.operations.scheduler_operations as sch_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.tag_operations as tag_ops
import zstackwoodpecker.operations.backupstorage_operations as bs_ops
import zstackwoodpecker.test_lib as test_lib
import zsta... | ():
global job1
global job2
global job_group
global trigger1
global trigger2
imagestore = test_lib.lib_get_image_store_backup_storage()
if imagestore == None:
test_util.test_skip('Required imagestore to test')
cond = res_ops.gen_query_conditions("tag", '=', "allowbackup")
al... | test | identifier_name |
test_delete_local_backupstorage.py | import zstackwoodpecker.operations.scheduler_operations as sch_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.tag_operations as tag_ops
import zstackwoodpecker.operations.backupstorage_operations as bs_ops
import zstackwoodpecker.test_lib as test_lib
import zsta... | global job1,job2,job_group,trigger1,trigger2
test_lib.lib_error_cleanup(test_obj_dict)
if job1:
sch_ops.del_scheduler_job(job1.uuid)
if job2:
sch_ops.del_scheduler_job(job2.uuid)
if job_group:
sch_ops.del_scheduler_job_group(job_group.uuid)
if trigger1:
sch_ops.del_sc... | identifier_body | |
types.d.ts | import { BoundaryValuesData } from '../../../../shared/utils/values/boundary-values';
import { AxisValuesData, LeftTopValues } from '../../../../shared/utils/values/axis-values';
import { Dictionary } from '../../../../configuration/interfaces';
export interface ElementRectangle {
height: number;
left: number;... | getBordersWidth (el: Element): BoundaryValuesData;
getElementScroll (el: Window | Document | Element): LeftTopValues<number>;
getInnerWidth (el: Element | Window | Document | null): number;
getInnerHeight (el: Element | Window | Document | null): number;
getScrollLeft (el: Window... | getSelectElementSize (select: HTMLSelectElement): number; | random_line_split |
test_languages.py | # This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.utils import translation
from shoop.simple_cms.models import Page
from sh... | ():
with translation.override("de"):
page_id = create_multilanguage_page(url="multi").pk
with translation.override("fi"):
page = Page.objects.get(pk=page_id)
assert page.title == "test, Finnisch"
assert page.url == "multi-fi"
with translation.override("e... | test_create_multilanguage_page | identifier_name |
test_languages.py | # This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.utils import translation
from shoop.simple_cms.models import Page
from sh... | with translation.override("de"):
page_id = create_multilanguage_page(url="multi").pk
with translation.override("fi"):
page = Page.objects.get(pk=page_id)
assert page.title == "test, Finnisch"
assert page.url == "multi-fi"
with translation.override("en"):
... | identifier_body | |
test_languages.py | # This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.utils import translation
from shoop.simple_cms.models import Page
from sh... | with translation.override("en"):
page = Page.objects.get(pk=page_id)
assert page.title == "test, Englisch"
assert page.url == "multi-en" | random_line_split | |
monit.py | #! /usr/bin/python
# vim: set fileencoding=utf-8 sw=4 ts=4 et:
import rrdtool, os
from def_rrds import rrds
import def_metrics
from def_metrics import metrics
for m in metrics:
if isinstance(metrics[m]['rrd'], list):
# multiples rrds
for i,f in enumerate(metrics[m]['rrd']):
if not os.p... | rrdtool.update(metrics[m]['rrd'], 'N:'+':'.join(values)) | conditional_block | |
monit.py | #! /usr/bin/python
# vim: set fileencoding=utf-8 sw=4 ts=4 et:
import rrdtool, os
from def_rrds import rrds
import def_metrics
from def_metrics import metrics | if not os.path.isfile(f):
rrdtool.create(f, rrds[m][i])
else:
if not os.path.isfile(metrics[m]['rrd']):
rrdtool.create(metrics[m]['rrd'], rrds[m])
values = getattr(def_metrics, '_get_'+m)()
#print(m, repr(values))
if isinstance(metrics[m]['rrd'], list):
... |
for m in metrics:
if isinstance(metrics[m]['rrd'], list):
# multiples rrds
for i,f in enumerate(metrics[m]['rrd']): | random_line_split |
publishtestresultstool.ts | import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as tl from 'vsts-task-lib/task';
import * as tr from 'vsts-task-lib/toolrunner';
import { publishEvent } from './cieventlogger';
var uuidV4 = require('uuid/v4');
let uuid = require('uuid');
export class TestResultsPublisher {
... |
private isNullEmptyOrUndefined(obj): boolean {
return obj === null || obj === '' || obj === undefined;
}
private matchingTestResultsFiles: string[];
private mergeResults: string;
private platform: string;
private config: string;
private testRunTitle: string;
private publishRun... | {
if (!this.isNullEmptyOrUndefined(value)) {
envVars[name] = value;
}
return envVars;
} | identifier_body |
publishtestresultstool.ts | import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as tl from 'vsts-task-lib/task';
import * as tr from 'vsts-task-lib/toolrunner';
import { publishEvent } from './cieventlogger';
var uuidV4 = require('uuid/v4');
let uuid = require('uuid');
export class TestResultsPublisher {
... |
private modifyMatchingFileName(matchingTestResultsFiles: string[]): string[] {
for (let i = 0; i < this.matchingTestResultsFiles.length; i++) {
// We need to add quotes around the file name because the file name can contain spaces.
// The quotes will be handled by response file read... | random_line_split | |
publishtestresultstool.ts | import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as tl from 'vsts-task-lib/task';
import * as tr from 'vsts-task-lib/toolrunner';
import { publishEvent } from './cieventlogger';
var uuidV4 = require('uuid/v4');
let uuid = require('uuid');
export class TestResultsPublisher {
... |
return envVars;
}
private isNullEmptyOrUndefined(obj): boolean {
return obj === null || obj === '' || obj === undefined;
}
private matchingTestResultsFiles: string[];
private mergeResults: string;
private platform: string;
private config: string;
private testRunTitle:... | {
envVars[name] = value;
} | conditional_block |
publishtestresultstool.ts | import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as tl from 'vsts-task-lib/task';
import * as tr from 'vsts-task-lib/toolrunner';
import { publishEvent } from './cieventlogger';
var uuidV4 = require('uuid/v4');
let uuid = require('uuid');
export class TestResultsPublisher {
... | (matchingTestResultsFiles: string[], mergeResults: string, platform: string, config: string,
testRunTitle: string, publishRunAttachments: string, testRunner: string) {
this.matchingTestResultsFiles = matchingTestResultsFiles.slice(0);
this.mergeResults = mergeResults;
this.platf... | constructor | identifier_name |
create.ts | import { AsyncIterableX } from './asynciterablex';
import { throwIfAborted } from '../aborterror';
class AnonymousAsyncIterable<T> extends AsyncIterableX<T> {
private _fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>;
constructor(fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<A... |
}
/**
* Creates a new iterable using the specified function implementing the members of AsyncIterable
*
* @template T The type of the elements returned by the enumerable sequence.
* @param {((signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>)} fn The function that creates the [Symbol.asyncIter... | {
throwIfAborted(signal);
const it = await this._fn(signal);
let next: IteratorResult<T> | undefined;
while (!(next = await it.next()).done) {
yield next.value;
}
} | identifier_body |
create.ts | import { AsyncIterableX } from './asynciterablex';
import { throwIfAborted } from '../aborterror';
class AnonymousAsyncIterable<T> extends AsyncIterableX<T> {
private _fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>;
constructor(fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<A... |
}
}
/**
* Creates a new iterable using the specified function implementing the members of AsyncIterable
*
* @template T The type of the elements returned by the enumerable sequence.
* @param {((signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>)} fn The function that creates the [Symbol.async... | {
yield next.value;
} | conditional_block |
create.ts | import { AsyncIterableX } from './asynciterablex';
import { throwIfAborted } from '../aborterror';
class AnonymousAsyncIterable<T> extends AsyncIterableX<T> {
private _fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>;
| (fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>) {
super();
this._fn = fn;
}
async *[Symbol.asyncIterator](signal?: AbortSignal) {
throwIfAborted(signal);
const it = await this._fn(signal);
let next: IteratorResult<T> | undefined;
while (!(next = await it.next())... | constructor | identifier_name |
create.ts | import { AsyncIterableX } from './asynciterablex';
import { throwIfAborted } from '../aborterror';
class AnonymousAsyncIterable<T> extends AsyncIterableX<T> {
private _fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>;
constructor(fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<A... |
/**
* Creates a new iterable using the specified function implementing the members of AsyncIterable
*
* @template T The type of the elements returned by the enumerable sequence.
* @param {((signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>)} fn The function that creates the [Symbol.asyncIterato... | }
}
} | random_line_split |
basicaerjob.py | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... |
else:
_executor = futures.ProcessPoolExecutor()
def __init__(self, backend, job_id, fn, qobj):
super().__init__(backend, job_id)
self._fn = fn
self._qobj = qobj
self._future = None
def submit(self):
"""Submit the job to the backend for execution.
R... | _executor = futures.ThreadPoolExecutor() | conditional_block |
basicaerjob.py | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | concurrent.futures.TimeoutError: if timeout occurred.
concurrent.futures.CancelledError: if job cancelled before completed.
"""
return self._future.result(timeout=timeout)
@requires_submit
def cancel(self):
return self._future.cancel()
@requires_submit
d... | qiskit.Result: Result object
Raises: | random_line_split |
basicaerjob.py | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | # in any of the previous states, is PENDING, ergo INITIALIZING for us.
_status = JobStatus.INITIALIZING
return _status
def backend(self):
"""Return the instance of the backend used for this job."""
return self._backend
def qobj(self):
"""Return the Qob... | """Gets the status of the job by querying the Python's future
Returns:
qiskit.providers.JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
"""
# The order is i... | identifier_body |
basicaerjob.py | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | (self, timeout=None):
# pylint: disable=arguments-differ
"""Get job result. The behavior is the same as the underlying
concurrent Future objects,
https://docs.python.org/3/library/concurrent.futures.html#future-objects
Args:
timeout (float): number of seconds to wai... | result | identifier_name |
levenshtein.js | /*
Copyright (c) 2011 Andrei Mackenzie
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute... | else {
matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution
Math.min(matrix[i][j-1] + 1, // insertion
matrix[i-1][j] + 1)); // deletion
}
}
}
return matrix[b.length][a.length];
};
| {
matrix[i][j] = matrix[i-1][j-1];
} | conditional_block |
levenshtein.js | /*
Copyright (c) 2011 Andrei Mackenzie
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute... | // Compute the edit distance between the two given strings
exports.getEditDistance = function(a, b){
if(a.length == 0) return b.length;
if(b.length == 0) return a.length;
var matrix = [];
// increment along the first column of each row
var i;
for(i = 0; i <= b.length; i++){
matrix[i] = [i];
}
/... | random_line_split | |
auth-service.ts | import {Injectable} from '@angular/core';
import {HttpClient} from "../http/http";
import {Router} from "@angular/router";
import {UserService} from "../user/index";
@Injectable()
export class AuthService{
loggedIn: boolean = false;
constructor(
private http: HttpClient,
private router: Router,
privat... | }
} |
logout(): void{
this.http.post('authService/logout') | random_line_split |
auth-service.ts | import {Injectable} from '@angular/core';
import {HttpClient} from "../http/http";
import {Router} from "@angular/router";
import {UserService} from "../user/index";
@Injectable()
export class AuthService{
loggedIn: boolean = false;
constructor(
private http: HttpClient,
private router: Router,
privat... |
signUp(user:{email: string, password: string, deviceIds: any}): void{
this.http.post('authService/registration', JSON.stringify(user))
.subscribe(
(response) => {
if(response){
this.userService.update(response);
this.router.navigate(['/dashboard'])
}
... | {
this.http.post('authService/login', JSON.stringify(data))
.subscribe(
response => {
if(response) {
this.userService.update(response);
this.router.navigate(['/dashboard']);
}
});
} | identifier_body |
auth-service.ts | import {Injectable} from '@angular/core';
import {HttpClient} from "../http/http";
import {Router} from "@angular/router";
import {UserService} from "../user/index";
@Injectable()
export class AuthService{
loggedIn: boolean = false;
constructor(
private http: HttpClient,
private router: Router,
privat... |
});
}
signUp(user:{email: string, password: string, deviceIds: any}): void{
this.http.post('authService/registration', JSON.stringify(user))
.subscribe(
(response) => {
if(response){
this.userService.update(response);
this.router.navigate(['/dashboard'])... | {
this.userService.update(response);
this.router.navigate(['/dashboard']);
} | conditional_block |
auth-service.ts | import {Injectable} from '@angular/core';
import {HttpClient} from "../http/http";
import {Router} from "@angular/router";
import {UserService} from "../user/index";
@Injectable()
export class AuthService{
loggedIn: boolean = false;
constructor(
private http: HttpClient,
private router: Router,
privat... | () {
return new Promise(resolve => {
this.http.get('authService/check')
.subscribe(
(response) => {
if(response){
this.userService.update(response);
resolve(true)
}
});
});
}
login(data: {email: string, password: string... | check | identifier_name |
http_downloader.ts | ///<reference path="../../../typings/tsd.d.ts"/>
import http = require('http')
import https = require('https')
import url = require('url')
interface HttpOptionsObject {
host:string,
path:string
}
export class HttpDownloader {
constructor() {}
/**
* HTTP GET request
*
* @... | downloadBytes = 0;
response.on('data', function(chunk) {
body += chunk;
downloadBytes += chunk.length;
if (callbackData) {
var progress = (downloadBytes / totalBytes) * 100;
callbackData(chunk, progress)... | http.get(parsedUrl, function(response) {
var body = '',
totalBytes = response.headers["content-length"], | random_line_split |
http_downloader.ts | ///<reference path="../../../typings/tsd.d.ts"/>
import http = require('http')
import https = require('https')
import url = require('url')
interface HttpOptionsObject {
host:string,
path:string
}
export class HttpDownloader {
constructor() |
/**
* HTTP GET request
*
* @param {string} anUrl
* @param {function} callbackDone Called on the 'end' event
* @param {function=} callbackData Called on each 'data' event
*/
get(anUrl: string,
callbackDone: (body:string)=>any,
callbackData?: (chunk:st... | {} | identifier_body |
http_downloader.ts | ///<reference path="../../../typings/tsd.d.ts"/>
import http = require('http')
import https = require('https')
import url = require('url')
interface HttpOptionsObject {
host:string,
path:string
}
export class HttpDownloader {
constructor() {}
/**
* HTTP GET request
*
* @... |
});
response.on('end', function() {
callbackDone(body);
});
});
}
}
| {
var $progress = (downloadBytes / totalBytes) * 100;
callbackData(chunk, $progress);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.