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 |
|---|---|---|---|---|
UnmountOldrootState.py | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... |
def unmount_var(self):
unmounted = False
while not unmounted:
self.command_executor.Execute('systemctl stop NetworkManager')
self.command_executor.Execute('systemctl stop rsyslog')
self.command_executor.Execute('systemctl stop systemd-udevd')
self.co... | random_line_split | |
show.rs | use rustc_serialize::json;
| use types::{Config, Playlist, Runnable};
use utils;
pub struct Show {
playlist: Vec<Box<Runnable>>,
dmx: DmxOutput
}
impl Show {
/// Creates a new show starting at playlist item at index offset, 0-indexed
pub fn new(cfg: &Config, proj_name: &str, dmx_port: &str, offset: u32) -> Result<Show, Error> {
... | use DmxOutput;
use error::Error; | random_line_split |
show.rs | use rustc_serialize::json;
use DmxOutput;
use error::Error;
use types::{Config, Playlist, Runnable};
use utils;
pub struct Show {
playlist: Vec<Box<Runnable>>,
dmx: DmxOutput
}
impl Show {
/// Creates a new show starting at playlist item at index offset, 0-indexed
pub fn new(cfg: &Config, proj_name:... |
}
| {
// Run show
for show_item in self.playlist.into_iter() {
let _ = try!(show_item.run(&mut self.dmx));
}
Ok(())
} | identifier_body |
show.rs | use rustc_serialize::json;
use DmxOutput;
use error::Error;
use types::{Config, Playlist, Runnable};
use utils;
pub struct Show {
playlist: Vec<Box<Runnable>>,
dmx: DmxOutput
}
impl Show {
/// Creates a new show starting at playlist item at index offset, 0-indexed
pub fn | (cfg: &Config, proj_name: &str, dmx_port: &str, offset: u32) -> Result<Show, Error> {
println!("Creating DMX outputter");
let dmx = try!(DmxOutput::new(dmx_port));
println!("Reading playlist");
let plist_path = Playlist::get_path(cfg, proj_name);
let plist_json = try!(u... | new | identifier_name |
scan.py | # -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2017-01-17 23:43:18
# @Last Modified by: yancz1989
# @Last Modified time: 2017-02-22 20:33:29
import utilities as util
from utilities import parse_image_file, filterBoxes, voxel_2_world, mkdir
import numpy as np
import os
import json
import sys
from PIL import I... | (result_map, output_file):
with open(output_file) as fout:
fout.write("seriesuid,coordX,coordY,coordZ,probability\n")
for fkey, val in result_map.items():
itkimage = sitk.ReadImage(fkey)
for it in val:
key, z, boxes = val
for box in boxes:
world_box = voxel_2_world(
... | generate_result | identifier_name |
scan.py | # -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2017-01-17 23:43:18
# @Last Modified by: yancz1989
# @Last Modified time: 2017-02-22 20:33:29
import utilities as util
from utilities import parse_image_file, filterBoxes, voxel_2_world, mkdir
import numpy as np
import os
import json
import sys
from PIL import I... |
else:
result_map = get_image_map(TRUNK_DIR, sys.argv[2], 0.01)
generate_result(result_map, OUTPUT_FILE) | generate_scan_image(sys.argv[2]) | conditional_block |
scan.py | # -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2017-01-17 23:43:18
# @Last Modified by: yancz1989
# @Last Modified time: 2017-02-22 20:33:29
import utilities as util
from utilities import parse_image_file, filterBoxes, voxel_2_world, mkdir
import numpy as np
import os
import json
import sys
from PIL import I... | output_dir = SAMPLE_DIR + subset
mkdir(output_dir)
for root, dirs, files in list_dirs:
for f in files:
if f.lower().endswith('mhd'):
key = os.path.splitext(f)[0]
numpyImage, numpyOrigin, numpySpacing = (
util.load_itk_image(
os.path.join(root, f)))
for z in ... |
def generate_scan_image(subset):
list_dirs = os.walk(TRUNK_DIR + subset)
jsobjs = [] | random_line_split |
scan.py | # -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2017-01-17 23:43:18
# @Last Modified by: yancz1989
# @Last Modified time: 2017-02-22 20:33:29
import utilities as util
from utilities import parse_image_file, filterBoxes, voxel_2_world, mkdir
import numpy as np
import os
import json
import sys
from PIL import I... |
if __name__ == '__main__':
if sys.argv[1] == 'gen':
generate_scan_image(sys.argv[2])
else:
result_map = get_image_map(TRUNK_DIR, sys.argv[2], 0.01)
generate_result(result_map, OUTPUT_FILE) | with open(output_file) as fout:
fout.write("seriesuid,coordX,coordY,coordZ,probability\n")
for fkey, val in result_map.items():
itkimage = sitk.ReadImage(fkey)
for it in val:
key, z, boxes = val
for box in boxes:
world_box = voxel_2_world(
[z, box[1], box[0]], i... | identifier_body |
gulpfile.js | 'use strict';
var gulp = require('gulp');
var del = require('del');
var outputDir = 'static';
gulp.task('clean:static', function() {
return del([`${outputDir}/**/*`]);
});
gulp.task('copy:js', ['clean:static'], function() {
var files = [
'node_modules/firebase/firebase-app.js',
'node_modules/firebase/fi... | })
gulp.task('copy', ['copy:src', 'copy:js', 'copy:css']);
gulp.task('default', ['copy']); | });
gulp.task('copy:src', ['clean:static'], function() {
return gulp.src('src-static/**/*')
.pipe(gulp.dest(outputDir)); | random_line_split |
user-info.js | /**
* 用户业务操作
*/
const validator = require('validator')
const userModel = require('./../models/user-info')
const userCode = require('./../codes/user')
const user = {
/**
* 创建用户
* @param {object} user 用户信息
* @return {object} 创建结果
*/
async create( user ) {
let result = await userModel.create... | ER_NAME
return result
}
if ( !validator.isEmail( userInfo.email ) ) {
result.message = userCode.ERROR_EMAIL
return result
}
if ( !/[\w+]{6,16}/.test( userInfo.password ) ) {
result.message = userCode.ERROR_PASSWORD
return result
}
if ( userInfo.password !== userInf... | erCode.ERROR_US | identifier_name |
user-info.js | /**
* 用户业务操作
*/
const validator = require('validator')
const userModel = require('./../models/user-info')
const userCode = require('./../codes/user')
const user = {
/**
* 创建用户
* @param {object} user 用户信息
* @return {object} 创建结果
*/
async create( user ) {
let result = await userModel.create... | essage = userCode.ERROR_PASSWORD
return result
}
if ( userInfo.password !== userInfo.confirmPassword ) {
result.message = userCode.ERROR_PASSWORD_CONFORM
return result
}
result.success = true
return result
}
}
module.exports = user
| }
if ( !/[\w+]{6,16}/.test( userInfo.password ) ) {
result.m | conditional_block |
user-info.js | /**
* 用户业务操作
*/
const validator = require('validator')
const userModel = require('./../models/user-info')
const userCode = require('./../codes/user')
const user = {
/**
* 创建用户
* @param {object} user 用户信息
* @return {object} 创建结果
*/
async create( user ) {
let result = await userModel.create... | bject} 登录业务操作结果
*/
async signIn( formData ) {
let resultData = await userModel.getOneByUserNameAndPassword({
'password': formData.password,
'name': formData.userName})
return resultData
},
/**
* 根据用户名查找用户业务操作
* @param {string} userName 用户名
* @return {object|null} 查找... | ta.email,
'name': formData.userName
})
return resultData
},
/**
* 登录业务操作
* @param {object} formData 登录表单信息
* @return {o | identifier_body |
user-info.js | /**
* 用户业务操作
*/
const validator = require('validator')
const userModel = require('./../models/user-info')
const userCode = require('./../codes/user')
const user = {
/**
* 创建用户
* @param {object} user 用户信息
* @return {object} 创建结果
*/
async create( user ) {
let result = await userModel.create... | 'name': formData.userName
})
return resultData
},
/**
* 登录业务操作
* @param {object} formData 登录表单信息
* @return {object} 登录业务操作结果
*/
async signIn( formData ) {
let resultData = await userModel.getOneByUserNameAndPassword({
'password': formData.password,
'name': form... | random_line_split | |
app.js | /**
* app.js
*
* Use `app.js` to run your app without `sails lift`.
* To start the server, run: `node app.js`.
*
* This is handy in situations where the sails CLI is not relevant or useful.
*
* For example:
* => `node app.js`
* => `forever start app.js`
* => `node debug app.js`
* => `modulus deploy`... |
// Start server
sails.lift(rc('sails'));
})(); | rc = function () { return {}; };
}
}
| random_line_split |
ripgrepTextSearch.ts | if (strings.startsWith(firstLine, 'error parsing glob') ||
strings.startsWith(firstLine, 'unsupported encoding')) {
// Uppercase first letter
return firstLine.charAt(0).toUpperCase() + firstLine.substr(1);
}
return undefined;
}
}
export class RipgrepParser extends EventEmitter {
private static RESULT... | fixDriveC | identifier_name | |
ripgrepTextSearch.ts | });
this.rgProc = cp.spawn(rgPath, rgArgs.globArgs, { cwd });
process.once('exit', this.killRgProcFn);
this.ripgrepParser = new RipgrepParser(this.config.maxResults, cwd, this.config.extraFiles);
this.ripgrepParser.on('result', (match: ISerializedFileMatch) => {
if (this.postProcessExclusions) {
const... | const rgCmd = `rg ${escapedArgs}\n - cwd: ${cwd}\n`;
onMessage({ message: rgCmd });
if (rgArgs.siblingClauses) {
onMessage({ message: ` - Sibling clauses: ${JSON.stringify(rgArgs.siblingClauses)}\n` });
} | random_line_split | |
ripgrepTextSearch.ts | , so create it here
const singleFile = this.extraSearchFiles[0];
if (!singleFile) {
throw new Error('Got match line for unknown file');
}
this.fileMatch = this.getFileMatch(singleFile);
}
this.fileMatch.addMatch(lineMatch);
let lastMatchEndPos = 0;
let matchTextStartPos = -1;
// Track posi... | {
return new TPromise<string[]>((resolve, reject) => {
extfs.readdir(path.dirname(file), (error: Error, files: string[]) => {
if (error) {
reject(error);
}
resolve(files);
});
});
} | identifier_body | |
ripgrepTextSearch.ts | stderr && !gotData && (displayMsg = this.rgErrorMsgForDisplay(stderr))) {
done(new Error(displayMsg), {
limitHit: false,
stats: null
});
} else {
done(null, {
limitHit: false,
stats: null
});
}
}
});
});
}
/**
* Read the first line of stderr an... | {
globArgs.push(fixDriveC(key));
} | conditional_block | |
glproc.py | Normal3bv",
"glNormal3d",
"glNormal3dv",
"glNormal3f",
"glNormal3fv",
"glNormal3i",
"glNormal3iv",
"glNormal3s",
"glNormal3sv",
"glNormalPointer",
"glOrtho",
"glPassThrough",
"glPixelMapfv",
"glPixelMapuiv",
"glPixelMapusv",
"glPixelStoref",
"glPixelStorei... | print
print '#ifndef _GLPROC_HPP_'
print '#define _GLPROC_HPP_'
print
print '#include "glimports.hpp"'
print '#include "os.hpp"'
print
print
dispatcher = GlDispatcher()
dispatcher.header()
print '#if defined(TRACE_EGL)'
print
dispatcher.dispatch_api(eglapi)
print '#e... | conditional_block | |
glproc.py | LineWidth",
"glListBase",
"glLoadIdentity",
"glLoadMatrixd",
"glLoadMatrixf",
"glLoadName",
"glLogicOp",
"glMap1d",
"glMap1f",
"glMap2d",
"glMap2f",
"glMapGrid1d",
"glMapGrid1f",
"glMapGrid2d",
"glMapGrid2f",
"glMaterialf",
"glMaterialfv",
"glMateriali... | print '''
#if defined(_WIN32)
extern HINSTANCE __libGlHandle;
#else
extern void * __libGlHandle;
#endif
void * __getPublicProcAddress(const char *procName);
void * __getPrivateProcAddress(const char *procName);
''' | identifier_body | |
glproc.py | 2",
"glEvalPoint1",
"glEvalPoint2",
"glFeedbackBuffer",
"glFinish",
"glFlush",
"glFogf",
"glFogfv",
"glFogi",
"glFogiv",
"glFrontFace",
"glFrustum",
"glGenLists",
"glGenTextures",
"glGetBooleanv",
"glGetClipPlane",
"glGetDoublev",
"glGetError",
"gl... | random_line_split | ||
glproc.py | ",
"glLoadIdentity",
"glLoadMatrixd",
"glLoadMatrixf",
"glLoadName",
"glLogicOp",
"glMap1d",
"glMap1f",
"glMap2d",
"glMap2f",
"glMapGrid1d",
"glMapGrid1f",
"glMapGrid2d",
"glMapGrid2f",
"glMaterialf",
"glMaterialfv",
"glMateriali",
"glMaterialiv",
... | is_public_function | identifier_name | |
discord.ts | import { APIMessageContentResolvable, MessageAdditions, MessageOptions, TextChannel } from 'discord.js'
import { defaultClient } from '../lib/discord'
import { WikiWorker } from './wiki'
export interface DiscordMessageActionInput {
channel: string
message: APIMessageContentResolvable | (MessageOptions & { split?: ... | }
export interface DiscordMessageAction {
actionType: 'DISCORD_MESSAGE'
input: DiscordMessageActionInput
output: DiscordMessageActionOutput
}
export class DiscordMessageWorker extends WikiWorker<DiscordMessageAction> {
public async process (): Promise<DiscordMessageActionOutput> {
console.log(this.input)
... |
export interface DiscordMessageActionOutput {
id: string | random_line_split |
discord.ts | import { APIMessageContentResolvable, MessageAdditions, MessageOptions, TextChannel } from 'discord.js'
import { defaultClient } from '../lib/discord'
import { WikiWorker } from './wiki'
export interface DiscordMessageActionInput {
channel: string
message: APIMessageContentResolvable | (MessageOptions & { split?: ... | (): Promise<DiscordMessageActionOutput> {
console.log(this.input)
const channel = await defaultClient.channels.fetch(this.input.channel)
if (channel instanceof TextChannel) {
const message = await channel.send(this.input.message)
return {
id: message.id
}
}
throw new Error... | process | identifier_name |
discord.ts | import { APIMessageContentResolvable, MessageAdditions, MessageOptions, TextChannel } from 'discord.js'
import { defaultClient } from '../lib/discord'
import { WikiWorker } from './wiki'
export interface DiscordMessageActionInput {
channel: string
message: APIMessageContentResolvable | (MessageOptions & { split?: ... |
}
| {
console.log(this.input)
const channel = await defaultClient.channels.fetch(this.input.channel)
if (channel instanceof TextChannel) {
const message = await channel.send(this.input.message)
return {
id: message.id
}
}
throw new Error('NOT_A_TEXT_CHANNEL')
} | identifier_body |
discord.ts | import { APIMessageContentResolvable, MessageAdditions, MessageOptions, TextChannel } from 'discord.js'
import { defaultClient } from '../lib/discord'
import { WikiWorker } from './wiki'
export interface DiscordMessageActionInput {
channel: string
message: APIMessageContentResolvable | (MessageOptions & { split?: ... |
throw new Error('NOT_A_TEXT_CHANNEL')
}
}
| {
const message = await channel.send(this.input.message)
return {
id: message.id
}
} | conditional_block |
utils.py | # Copyright 2018 ETH Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | 'SCION_UID',
'SCION_GID',
'DOCKER_GID'
],
'volumes': [
'/run/shm/dispatcher:/run/shm/dispatcher:rw',
'/run/shm/sciond:/run/shm/sciond:rw',
self.output_base + '/logs:' + cntr_base + '/logs:rw',
... | def __init__(self, args):
"""
:param TesterGenArgs args: Contains the passed command line arguments.
"""
self.args = args
self.dc_tester_conf = {'version': '3', 'services': {}}
self.output_base = os.environ.get('SCION_OUTPUT_BASE', os.getcwd())
def generate(self):
... | identifier_body |
utils.py | # Copyright 2018 ETH Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | 'command': [
'-c',
'tail -f /dev/null'
]
}
self.dc_tester_conf['services']['tester'] = entry | ],
'user': 'root', | random_line_split |
utils.py | # Copyright 2018 ETH Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | (self, args):
"""
:param TesterGenArgs args: Contains the passed command line arguments.
"""
self.args = args
self.dc_tester_conf = {'version': '3', 'services': {}}
self.output_base = os.environ.get('SCION_OUTPUT_BASE', os.getcwd())
def generate(self):
self._... | __init__ | identifier_name |
permutationtable.rs | use math::{Point2, Point3, Point4};
use rand::{Rand, Rng, SeedableRng, XorShiftRng};
use std::fmt;
const TABLE_SIZE: usize = 256;
/// A seed table, required by all noise functions.
///
/// Table creation is expensive, so in most circumstances you'll only want to
/// create one of these per generator.
#[derive(Copy, C... | (&self, pos: Point4<isize>) -> usize {
let w = (pos[3] & 0xff) as usize;
self.values[self.get3([pos[0], pos[1], pos[2]]) ^ w] as usize
}
}
impl fmt::Debug for PermutationTable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PermutationTable {{ .. }}")
}
}
#[cfg(... | get4 | identifier_name |
permutationtable.rs | use math::{Point2, Point3, Point4};
use rand::{Rand, Rng, SeedableRng, XorShiftRng};
use std::fmt;
const TABLE_SIZE: usize = 256;
/// A seed table, required by all noise functions.
///
/// Table creation is expensive, so in most circumstances you'll only want to
/// create one of these per generator.
#[derive(Copy, C... |
}
impl PermutationTable {
/// Deterministically generates a new permutation table based on a `u32` seed value.
///
/// Internally this uses a `XorShiftRng`, but we don't really need to worry
/// about cryptographic security when working with procedural noise.
pub fn new(seed: u32) -> PermutationTa... | {
let mut seq: Vec<u8> = (0..TABLE_SIZE).map(|x| x as u8).collect();
rng.shuffle(&mut *seq);
// It's unfortunate that this double-initializes the array, but Rust
// doesn't currently provide a clean way to do this in one pass. Hopefully
// it won't matter, as Seed creation will ... | identifier_body |
permutationtable.rs | use math::{Point2, Point3, Point4};
use rand::{Rand, Rng, SeedableRng, XorShiftRng};
use std::fmt;
const TABLE_SIZE: usize = 256;
/// A seed table, required by all noise functions.
///
/// Table creation is expensive, so in most circumstances you'll only want to
/// create one of these per generator.
#[derive(Copy, C... | }
} | let _ = perlin.get([-1.0, 2.0, 3.0]); | random_line_split |
tool.ts | import {Component,ViewChild,ElementRef,ComponentFactoryResolver,ViewContainerRef,forwardRef,ContentChildren,QueryList} from '@angular/core';
import { base } from './base';
// Ext Class - Ext.panel.Tool
export class toolMetaData {
public static XTYPE: string = 'tool';
public static INPUTNAMES: string[] = [
'activeCo... | () {this.OnInit(this.dynamicRef,toolMetaData);}
}
| ngOnInit | identifier_name |
tool.ts | import {Component,ViewChild,ElementRef,ComponentFactoryResolver,ViewContainerRef,forwardRef,ContentChildren,QueryList} from '@angular/core';
import { base } from './base';
// Ext Class - Ext.panel.Tool
export class toolMetaData {
public static XTYPE: string = 'tool';
public static INPUTNAMES: string[] = [
'activeCo... | 'ready'
];
}
@Component({
selector: toolMetaData.XTYPE,
inputs: toolMetaData.INPUTNAMES,
outputs: toolMetaData.OUTPUTNAMES,
providers: [{provide: base, useExisting: forwardRef(() => tool)}],
template: '<ng-template #dynamic></ng-template>'
})
export class tool extends base {
constructor(eRef:ElementRef,resolve... | 'staterestore',
'statesave', | random_line_split |
compression.rs | //! A middleware for compressing all transmitted data.
use crate::{wire, Error};
use flate2;
use std::io::prelude::*;
use std::io::Cursor;
/// Defines a compression algorithm.
#[derive(Copy, Clone, Debug)]
pub enum Algorithm
{
/// The zlib compression algorithm.
///
/// https://en.wikipedia.org/wiki/Zlib... |
impl wire::Middleware for Compression
{
fn encode_data(&mut self, data: Vec<u8>) -> Result<Vec<u8>, Error> {
match *self {
Compression::Enabled(algorithm) => match algorithm {
Algorithm::Zlib => {
let e = flate2::write::ZlibEncoder::new(data, flate2::Compress... | random_line_split | |
compression.rs | //! A middleware for compressing all transmitted data.
use crate::{wire, Error};
use flate2;
use std::io::prelude::*;
use std::io::Cursor;
/// Defines a compression algorithm.
#[derive(Copy, Clone, Debug)]
pub enum Algorithm
{
/// The zlib compression algorithm.
///
/// https://en.wikipedia.org/wiki/Zlib... |
{
/// No compression or decompression should be applied to the data.
Disabled,
/// Compression and decompression should be applied to the data.
Enabled(Algorithm),
}
impl wire::Middleware for Compression
{
fn encode_data(&mut self, data: Vec<u8>) -> Result<Vec<u8>, Error> {
match *self {
... | Compression | identifier_name |
personResult.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | () {
}
/**
* Defines the metadata of PersonResult
*
* @returns {object} metadata of PersonResult
*
*/
mapper() {
return {
required: false,
serializedName: 'PersonResult',
type: {
name: 'Composite',
className: 'PersonResult',
modelProperties: {
... | constructor | identifier_name |
personResult.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | /**
* Defines the metadata of PersonResult
*
* @returns {object} metadata of PersonResult
*
*/
mapper() {
return {
required: false,
serializedName: 'PersonResult',
type: {
name: 'Composite',
className: 'PersonResult',
modelProperties: {
personId... | */
constructor() {
}
| random_line_split |
CaretContainerRemove.ts | import { Arr } from '@ephox/katamari';
import * as NodeType from '../dom/NodeType';
import * as Zwsp from '../text/Zwsp';
import * as CaretContainer from './CaretContainer';
import CaretPosition from './CaretPosition';
interface TrimCount {
readonly count: number;
readonly text: string;
}
const isElement = NodeT... | parentNode.removeChild(node);
}
};
const trimCount = (text: string): TrimCount => {
const trimmedText = Zwsp.trim(text);
return {
count: text.length - trimmedText.length,
text: trimmedText
};
};
const deleteZwspChars = (caretContainer: Text): void => {
// We use the Text.deleteData API here so a... | if (parentNode) { | random_line_split |
CaretContainerRemove.ts | import { Arr } from '@ephox/katamari';
import * as NodeType from '../dom/NodeType';
import * as Zwsp from '../text/Zwsp';
import * as CaretContainer from './CaretContainer';
import CaretPosition from './CaretPosition';
interface TrimCount {
readonly count: number;
readonly text: string;
}
const isElement = NodeT... |
};
export {
removeAndReposition,
remove
};
| {
deleteZwspChars(caretContainerNode);
if (caretContainerNode.data.length === 0) {
removeNode(caretContainerNode);
}
} | conditional_block |
day22.rs | use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashSet;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use itertools::Itertools;
use regex::Regex;
use common::Solution;
type Coordinate = (usize, usize);
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, De... |
let mut new_state = State {
grid: state.grid.clone(),
empty_pos: switch,
pos: if switch == state.pos { state.empty_pos } else { state.pos },
};
if !visited.contains(&(new_state.pos, new_state.empty_pos)) {
... | {
// Not enough capacity
continue;
} | conditional_block |
day22.rs | use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashSet;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use itertools::Itertools;
use regex::Regex;
use common::Solution;
type Coordinate = (usize, usize);
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, De... | self.read_input(input);
let fitting = iproduct!(&self.nodes, &self.nodes)
.filter(|&(_, b)| b.used > 0)
.filter(|&(a, b)| a != b)
.filter(|&(a, b)| a.fits(*b))
.count();
fitting.to_string()
}
fn part2(&mut self, input: &mut Read) -> Str... |
impl Solution for Day22 {
fn part1(&mut self, input: &mut Read) -> String { | random_line_split |
day22.rs | use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashSet;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use itertools::Itertools;
use regex::Regex;
use common::Solution;
type Coordinate = (usize, usize);
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, De... | {
pos: Coordinate,
empty_pos: Coordinate,
grid: Vec<usize>,
}
impl State {
fn estimate(&self) -> usize {
self.pos.0 + self.pos.1
+ self.pos.0.max(self.empty_pos.0) + self.pos.1.max(self.empty_pos.1)
- self.pos.0.min(self.empty_pos.0) - self.pos.1.min(self.empty_pos.1)
... | State | identifier_name |
day22.rs | use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashSet;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use itertools::Itertools;
use regex::Regex;
use common::Solution;
type Coordinate = (usize, usize);
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, De... |
fn part2(&mut self, input: &mut Read) -> String {
self.read_input(input);
let (size, used, capacity) = self.build_grid();
let (empty_pos, _) = used.iter()
.find_position(|&&used| used == 0)
.unwrap();
let height = used.len() / size;
let state = S... | {
self.read_input(input);
let fitting = iproduct!(&self.nodes, &self.nodes)
.filter(|&(_, b)| b.used > 0)
.filter(|&(a, b)| a != b)
.filter(|&(a, b)| a.fits(*b))
.count();
fitting.to_string()
} | identifier_body |
privacy4.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
}
}
pub fn foo() {}
fn test2() {
use bar::glob::gpriv; //~ ERROR: function `gpriv` is private
gpriv();
}
#[start] fn main(_: isize, _: *const *const u8) -> isize { 3 }
| gpriv | identifier_name |
privacy4.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // Test to make sure that private items imported through globs remain private
// when they're used.
mod bar {
pub use self::glob::*;
mod glob {
fn gpriv() {}
}
}
pub fn foo() {}
fn test2() {
use bar::glob::gpriv; //~ ERROR: function `gpriv` is private
gpriv();
}
#[start] fn main(_: isi... | random_line_split | |
privacy4.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[start] fn main(_: isize, _: *const *const u8) -> isize { 3 }
| {
use bar::glob::gpriv; //~ ERROR: function `gpriv` is private
gpriv();
} | identifier_body |
test.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
function tryRequire() {
return new Error( 'Cannot find module' );
}
}); | random_line_split | |
test.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
});
| {
return new Error( 'Cannot find module' );
} | identifier_body |
test.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | () {
return mock;
}
function mock() {
// Mock...
}
});
tape( 'if a native implementation is not available, the main export is a JavaScript implementation', opts, function test( t ) {
var smidrange;
var main;
main = require( './../lib/smidrange.js' );
smidrange = proxyquire( './../lib', {
'@stdlib/utils... | tryRequire | identifier_name |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified angles.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::f32::consts::P... |
}
impl Angle {
/// Creates an angle with the given value in degrees.
#[inline]
pub fn from_degrees(value: CSSFloat, was_calc: bool) -> Self {
Angle {
value: AngleDimension::Deg(value),
was_calc,
}
}
/// Returns the value of the angle in degrees, mostly for ... | {
Angle {
value: AngleDimension::Deg(computed.degrees()),
was_calc: false,
}
} | identifier_body |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified angles.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::f32::consts::P... | if self.was_calc {
dest.write_str("calc(")?;
}
self.value.to_css(dest)?;
if self.was_calc {
dest.write_str(")")?;
}
Ok(())
}
}
impl ToComputedValue for Angle {
type ComputedValue = ComputedAngle;
#[inline]
fn to_computed_value(&se... | impl ToCss for Angle {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{ | random_line_split |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified angles.
use cssparser::{Parser, Token};
use parser::{Parse, ParserContext};
use std::f32::consts::P... | (degrees: CSSFloat) -> Self {
Angle {
value: AngleDimension::Deg(degrees),
was_calc: true,
}
}
}
/// Whether to allow parsing an unitless zero as a valid angle.
///
/// This should always be `No`, except for exceptions like:
///
/// https://github.com/w3c/fxtf-drafts/issue... | from_calc | identifier_name |
IElement.ts | /// <reference path="../IElement.ts" />
module xlib.ui.element.elements.address {
import IEvent = elements.IEvent;
export interface IElement<T> extends elements.IElement<T> {
getTitle(): string;
setTitle(value: string): void; | setLang(value: string): void;
getXmlLang(): string;
setXmlLang(value: string): void;
getDir(): string;
setDir(value: string): void;
onClick(listener: (event?: IEvent<T>) => void): void;
onDblClick(listener: (event?: IEvent<T>) => void): void;
onMouseDown(listener: (event?: IEvent<T>) => ... | getLang(): string; | random_line_split |
lualib.rs | pub mod raw {
use libc::c_int;
use raw::lua_State;
pub static LUA_COLIBNAME: &'static str = "coroutine";
pub static LUA_TABLIBNAME: &'static str = "table";
pub static LUA_IOLIBNAME: &'static str = "io";
pub static LUA_OSLIBNAME: &'static str = "os";
pub static LUA_STRLIBNAME: &'static str =... | }
} | random_line_split | |
new-file-service.js | (function () {
'use strict';
angular.module('ramlEditorApp')
.service('newFileService', function newFolderService(
ramlRepository,
newNameModal,
$rootScope,
generateName) {
var self = this;
var specUrl = 'https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/ra... |
self.prompt = function prompt(target, ramlVersion, fragmentLabel) {
var parent = target.isDirectory ? target : ramlRepository.getParent(target);
var validations = [
{
message: 'That file name is already taken.',
validate: function (input) {
var pa... | {
var names = target.children.map(function (file) {
return file.name;
});
var defaultName = (fragment.label !== '' ? fragmentLabel : 'api') + '-';
return generateName(names, defaultName, 'raml');
} | identifier_body |
new-file-service.js | (function () {
'use strict';
angular.module('ramlEditorApp')
.service('newFileService', function newFolderService(
ramlRepository,
newNameModal,
$rootScope,
generateName) {
var self = this;
var specUrl = 'https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/ra... |
return self.prompt(homeDirectory, '1.0', fragmentType);
};
self.newFile = function newFile(homeDirectory, version) {
return self.prompt(homeDirectory, version);
};
return self;
})
;
})();
| {
return self.prompt(homeDirectory, '1.0');
} | conditional_block |
new-file-service.js | (function () {
'use strict';
angular.module('ramlEditorApp')
.service('newFileService', function newFolderService(
ramlRepository,
newNameModal,
$rootScope,
generateName) {
var self = this;
var specUrl = 'https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/ra... | },
'SecurityScheme': {
label: 'SecurityScheme',
name: 'Security Scheme',
description: 'Define a single security scheme that describes the mechanism to secure data access, identify requests, and determine access level and data visibility.',
spec: specUr... | label: 'AnnotationTypeDeclaration',
name: 'Annotation',
description: 'Define a single annotation type declaration that describes additional metadata that can be applied to any RAML node.',
spec: specUrl + 'annotations' | random_line_split |
new-file-service.js | (function () {
'use strict';
angular.module('ramlEditorApp')
.service('newFileService', function newFolderService(
ramlRepository,
newNameModal,
$rootScope,
generateName) {
var self = this;
var specUrl = 'https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/ra... | (target, fragment, fragmentLabel) {
var names = target.children.map(function (file) {
return file.name;
});
var defaultName = (fragment.label !== '' ? fragmentLabel : 'api') + '-';
return generateName(names, defaultName, 'raml');
}
self.prompt = function prompt(ta... | nameSuggestion | identifier_name |
ng_zone.d.ts | export interface NgZoneZone extends Zone {
_innerZone: boolean;
}
/**
* A wrapper around zones that lets you schedule tasks after it has executed a task.
*
* The wrapper maintains an "inner" and an "mount" `Zone`. The application code will executes
* in the "inner" zone unless `runOutsideAngular` is explicitely... | {
_mountZone: any;
_innerZone: any;
_onTurnStart: () => void;
_onTurnDone: () => void;
_onErrorHandler: (error, stack) => void;
_pendingMicrotasks: number;
_hasExecutedCodeInInnerZone: boolean;
_nestedRun: number;
_disabled: boolean;
_inVmTurnDone: boolean;
/**
* Associ... | NgZone | identifier_name |
ng_zone.d.ts | export interface NgZoneZone extends Zone {
_innerZone: boolean;
}
/**
* A wrapper around zones that lets you schedule tasks after it has executed a task.
*
* The wrapper maintains an "inner" and an "mount" `Zone`. The application code will executes
* in the "inner" zone unless `runOutsideAngular` is explicitely... | * A typical application will create a singleton `NgZone`. The outer `Zone` is a fork of the root
* `Zone`. The default `onTurnDone` runs the Angular change detection.
*
* @exportedAs angular2/core
*/
export declare class NgZone {
_mountZone: any;
_innerZone: any;
_onTurnStart: () => void;
_onTurnDo... | * | random_line_split |
DateTimeAxis.js | /* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../Utilities.js';
var addEvent = U.addEvent, getMagnitude = U.getMagnitude, normalizeTickInterval = U.normalizeTickInt... |
/* *
*
* Classes
*
* */
var Additions = /** @class */ (function () {
/* *
*
* Constructors
*
* */
function Additions(axis) {
this.axis = axis;
}
/* *
*
* Functions
*
* */
... | {
var axis = this;
var options = e.userOptions;
if (options.type !== 'datetime') {
axis.dateTime = void 0;
return;
}
if (!axis.dateTime) {
axis.dateTime = new Additions(axis);
}
} | identifier_body |
DateTimeAxis.js | /* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../Utilities.js';
var addEvent = U.addEvent, getMagnitude = U.getMagnitude, normalizeTickInterval = U.normalizeTickInt... | * data on a datetime axis.
*
* @private
* @function Highcharts.Axis#getTimeTicks
*
* @param {Highcharts.TimeNormalizeObject} normalizedInterval
* The interval in axis values (ms) and thecount.
*
* @param {number} min
* The minimum in axis values.
*
* @param {n... | * Set the tick positions to a time unit that makes sense, for example
* on the first of each month or on every Monday. Return an array with
* the time positions. Used in datetime axes as well as for grouping | random_line_split |
DateTimeAxis.js | /* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../Utilities.js';
var addEvent = U.addEvent, getMagnitude = U.getMagnitude, normalizeTickInterval = U.normalizeTickInt... | (axis) {
this.axis = axis;
}
/* *
*
* Functions
*
* */
/**
* Get a normalized tick interval for dates. Returns a configuration
* object with unit range (interval), count and name. Used to prepare
* data for `getTimeTicks... | Additions | identifier_name |
DateTimeAxis.js | /* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import U from '../Utilities.js';
var addEvent = U.addEvent, getMagnitude = U.getMagnitude, normalizeTickInterval = U.normalizeTickInt... |
return AxisClass;
}
DateTimeAxis.compose = compose;
/**
* Set the tick positions to a time unit that makes sense, for example
* on the first of each month or on every Monday. Return an array with
* the time positions. Used in datetime axes as well as for grouping
* data on a dat... | {
composedClasses.push(AxisClass);
AxisClass.keepProps.push('dateTime');
var axisProto = AxisClass.prototype;
axisProto.getTimeTicks = getTimeTicks;
addEvent(AxisClass, 'init', onInit);
} | conditional_block |
model-approval.service.ts | // /*
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writi... | // @Injectable()
// export class ModelApprovalService extends AbstractService {
//
// constructor(protected injector: Injector) {
// super(injector);
// }
//
//
// // Model List를 불러온다
// public searchModels(params: any, page: Page): Promise<any> {
// // public searchModels(name: string, user: string, be... | // import {Injectable, Injector} from '@angular/core';
// import {AbstractService} from '@common/service/abstract.service';
// import {Page} from '@domain/common/page';
// import {CommonUtil} from '@common/util/common.util';
// | random_line_split |
currency.rs | ipe Dobra
#[serde(rename = "svc")]
SVC, // Salvadoran Colón
#[serde(rename = "szl")]
SZL, // Swazi Lilangeni
#[serde(rename = "thb")]
THB, // Thai Baht
#[serde(rename = "tjs")]
TJS, // Tajikistani Somoni
#[serde(rename = "top")]
TOP, // Tongan Paʻanga
#[serde(rename = "try")]... | "szl" => Ok(Currency::SZL), | random_line_split | |
currency.rs | Vatu
#[serde(rename = "wst")]
WST, // Samoan Tala
#[serde(rename = "xaf")]
XAF, // Central African Cfa Franc
#[serde(rename = "xcd")]
XCD, // East Caribbean Dollar
#[serde(rename = "xof")]
XOF, // West African Cfa Franc
#[serde(rename = "xpf")]
XPF, // Cfp Franc
#[serde(rena... | or(/* private */ ( | identifier_name | |
currency.rs | #[serde(rename = "fjd")]
FJD, // Fijian Dollar
#[serde(rename = "fkp")]
FKP, // Falkland Islands Pound
#[serde(rename = "gbp")]
GBP, // British Pound
#[serde(rename = "gel")]
GEL, // Georgian Lari
#[serde(rename = "gip")]
GIP, // Gibraltar Pound
#[serde(rename = "gmd")]
GMD,... | str::FromStr for Currency {
type Err = ParseCurrencyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"aed" => Ok(Currency::AED),
"afn" => Ok(Currency::AFN),
"all" => Ok(Currency::ALL),
"amd" => Ok(Currency::AMD),
"ang" => Ok(C... | (f, "{}", to_snakecase(&format!("{:?}", self)))
}
}
impl ::std:: | identifier_body |
jsdoc.js | var _ = require('lodash');
var jsParser = require('esprima');
var walk = require('dgeni-packages/jsdoc/lib/walk');
var LEADING_STAR = /^[^\S\r\n]*\*[^\S\n\r]?/gm;
module.exports = {
name: 'jsdoc',
description: 'Read js documents',
runAfter: ['files-read'],
runBefore: ['parsing-tags'],
exports: {
//The js... | else {
otherDocs.push(doc);
}
});
return jsdocDocs;
}
};
function parseComments(doc) {
var ast = jsParser.parse(doc.content, {
loc: true,
range: true,
comment: true
});
// Below code is adapted from the jsdoc dgeni-package by Pete Bacon Darwin
// https://github.com/angula... | {
jsdocDocs = jsdocDocs.concat(parseComments(doc));
} | conditional_block |
jsdoc.js | var _ = require('lodash');
var jsParser = require('esprima');
var walk = require('dgeni-packages/jsdoc/lib/walk');
var LEADING_STAR = /^[^\S\r\n]*\*[^\S\n\r]?/gm;
module.exports = {
name: 'jsdoc',
description: 'Read js documents',
runAfter: ['files-read'],
runBefore: ['parsing-tags'],
exports: {
//The js... | (doc) {
var ast = jsParser.parse(doc.content, {
loc: true,
range: true,
comment: true
});
// Below code is adapted from the jsdoc dgeni-package by Pete Bacon Darwin
// https://github.com/angular/dgeni-packages
// https://github.com/angular/dgeni-packages/blob/master/LICENSE
return _(ast.comment... | parseComments | identifier_name |
jsdoc.js | var _ = require('lodash');
var jsParser = require('esprima');
var walk = require('dgeni-packages/jsdoc/lib/walk');
var LEADING_STAR = /^[^\S\r\n]*\*[^\S\n\r]?/gm;
module.exports = {
name: 'jsdoc',
description: 'Read js documents',
runAfter: ['files-read'],
runBefore: ['parsing-tags'],
exports: {
//The js... | }
};
function parseComments(doc) {
var ast = jsParser.parse(doc.content, {
loc: true,
range: true,
comment: true
});
// Below code is adapted from the jsdoc dgeni-package by Pete Bacon Darwin
// https://github.com/angular/dgeni-packages
// https://github.com/angular/dgeni-packages/blob/master/... | random_line_split | |
jsdoc.js | var _ = require('lodash');
var jsParser = require('esprima');
var walk = require('dgeni-packages/jsdoc/lib/walk');
var LEADING_STAR = /^[^\S\r\n]*\*[^\S\n\r]?/gm;
module.exports = {
name: 'jsdoc',
description: 'Read js documents',
runAfter: ['files-read'],
runBefore: ['parsing-tags'],
exports: {
//The js... | // Trim off leading and trailing whitespace
text = text.trim();
// Extract the information about the code directly after this comment
var codeNode = walk.findNodeAfter(ast, comment.range[1]);
var codeAncestors = codeNode && walk.ancestor(ast, codeNode.node);
// Create a doc from th... | {
var ast = jsParser.parse(doc.content, {
loc: true,
range: true,
comment: true
});
// Below code is adapted from the jsdoc dgeni-package by Pete Bacon Darwin
// https://github.com/angular/dgeni-packages
// https://github.com/angular/dgeni-packages/blob/master/LICENSE
return _(ast.comments)
... | identifier_body |
repair_test.py | import time
import pytest
import logging
from repair_tests.repair_test import BaseRepairTest
since = pytest.mark.since
logger = logging.getLogger(__name__)
LEGACY_SSTABLES_JVM_ARGS = ["-Dcassandra.streamdes.initial_mem_buffer_size=1",
"-Dcassandra.streamdes.max_mem_buffer_size=5",
... | (self):
"""
@jira_ticket CASSANDRA-10990
"""
default_install_dir = self.cluster.get_install_dir()
cluster = self.cluster
logger.debug("Setting version to 2.2.5")
cluster.set_install_dir(version="2.2.5")
self._populate_cluster()
self._do_upgrade(de... | test_repair_after_upgrade | identifier_name |
repair_test.py | import time
import pytest
import logging
from repair_tests.repair_test import BaseRepairTest
since = pytest.mark.since
logger = logging.getLogger(__name__)
LEGACY_SSTABLES_JVM_ARGS = ["-Dcassandra.streamdes.initial_mem_buffer_size=1",
"-Dcassandra.streamdes.max_mem_buffer_size=5",
... | cluster = self.cluster
for node in cluster.nodelist():
logger.debug("Upgrading %s to current version" % node.name)
if node.is_running():
node.flush()
time.sleep(1)
node.stop(wait_other_notice=True)
node.set_install_dir(install_... | identifier_body | |
repair_test.py | import time
import pytest
import logging
from repair_tests.repair_test import BaseRepairTest
since = pytest.mark.since
logger = logging.getLogger(__name__)
LEGACY_SSTABLES_JVM_ARGS = ["-Dcassandra.streamdes.initial_mem_buffer_size=1",
"-Dcassandra.streamdes.max_mem_buffer_size=5",
... | class TestUpgradeRepair(BaseRepairTest):
@since('3.0', max_version='3.99')
def test_repair_after_upgrade(self):
"""
@jira_ticket CASSANDRA-10990
"""
default_install_dir = self.cluster.get_install_dir()
cluster = self.cluster
logger.debug("Setting version to 2.2.5... | random_line_split | |
repair_test.py | import time
import pytest
import logging
from repair_tests.repair_test import BaseRepairTest
since = pytest.mark.since
logger = logging.getLogger(__name__)
LEGACY_SSTABLES_JVM_ARGS = ["-Dcassandra.streamdes.initial_mem_buffer_size=1",
"-Dcassandra.streamdes.max_mem_buffer_size=5",
... |
node.set_install_dir(install_dir=default_install_dir)
node.start(wait_other_notice=True, wait_for_binary_proto=True)
cursor = self.patient_cql_connection(node)
cluster.set_install_dir(default_install_dir)
| node.flush()
time.sleep(1)
node.stop(wait_other_notice=True) | conditional_block |
genericcomicreader.py | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Noé Rubinstein
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at you... | b.PAGES = self.PAGES
try:
b.DOMAIN = self.DOMAIN
except AttributeError:
pass
return b
def iter_gallery_images(self, gallery):
with self.browser:
return self.browser.iter_gallery_images(gallery)
def get_gallery(self, _id):
matc... | def create_default_browser(self):
b = self.create_browser(self.BROWSER_PARAMS) | random_line_split |
genericcomicreader.py | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Noé Rubinstein
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at you... | self, gallery):
self.location(gallery.url)
assert self.is_on_page(DisplayPage)
for p in self.page.page_list():
if 'page_to_location' in self.params:
self.location(self.params['page_to_location'] % p)
else:
self.location(p)
ass... | ter_gallery_images( | identifier_name |
genericcomicreader.py | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Noé Rubinstein
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at you... | pass
return b
def iter_gallery_images(self, gallery):
with self.browser:
return self.browser.iter_gallery_images(gallery)
def get_gallery(self, _id):
match = re.match(r'^%s$' % self.URL_REGEXP, _id)
if match:
_id = match.group(1)
else... | AME = 'genericcomicreader'
MAINTAINER = u'Noé Rubinstein'
EMAIL = 'noe.rubinstein@gmail.com'
VERSION = '0.f'
DESCRIPTION = 'Generic comic reader backend; subclasses implement specific sites'
LICENSE = 'AGPLv3+'
BROWSER = GenericComicReaderBrowser
BROWSER_PARAMS = {}
ID_REGEXP = None
... | identifier_body |
genericcomicreader.py | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Noé Rubinstein
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at you... | else:
self.location(p)
assert self.is_on_page(DisplayPage)
yield self.page.get_page(gallery)
def fill_image(self, image, fields):
if 'data' in fields:
image.data = self.readurl(image.url)
class GenericComicReaderBackend(BaseBackend, ICapGal... | elf.location(self.params['page_to_location'] % p)
| conditional_block |
benchmark.js | #!/usr/bin/env node
'use strict';
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
chalk = require('chalk'),
Table = require('cli-table');
var fileNames = [
'abc',
'amazon',
//'eloquentjavascript',
//'es6-draft',
'es6-table',
'google',
'html-minifier... | if (err) {
throw new Error('There was an error reading ' + filePath);
}
var originalSize = stats.size;
exec('gzip --keep --force --best --stdout ' + filePath + ' > ' + gzFilePath, function () {
// Open and read the size of the gzipped original
fs.stat(gzFilePath, function (err, stats)... | var gzMinifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html.gz');
var command = path.normalize('./cli.js') + ' ' + filePath + ' -c benchmark.conf' + ' -o ' + minifiedFilePath;
// Open and read the size of the original input
fs.stat(filePath, function (err, stats) { | random_line_split |
benchmark.js | #!/usr/bin/env node
'use strict';
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
chalk = require('chalk'),
Table = require('cli-table');
var fileNames = [
'abc',
'amazon',
//'eloquentjavascript',
//'es6-draft',
'es6-table',
'google',
'html-minifier... |
function blueTime(time) {
return chalk.cyan.bold(time) + chalk.white(' ms');
}
function test(fileName, done) {
if (!fileName) {
console.log('\n' + table.toString());
return;
}
console.log('Processing...', fileName);
var filePath = path.join('benchmarks/', fileName + '.html');
var minifiedFileP... | {
var savingsPercent = (1 - newSize / oldSize) * 100;
var savings = (oldSize - newSize) / 1024;
return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) + ' KB)');
} | identifier_body |
benchmark.js | #!/usr/bin/env node
'use strict';
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
chalk = require('chalk'),
Table = require('cli-table');
var fileNames = [
'abc',
'amazon',
//'eloquentjavascript',
//'es6-draft',
'es6-table',
'google',
'html-minifier... |
var gzOriginalSize = stats.size;
// Begin timing after gzipped fixtures have been created
var startTime = new Date();
exec('node ' + command, function () {
// Open and read the size of the minified output
fs.stat(minifiedFilePath, function (err, stats) {
... | {
throw new Error('There was an error reading ' + gzFilePath);
} | conditional_block |
benchmark.js | #!/usr/bin/env node
'use strict';
var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
chalk = require('chalk'),
Table = require('cli-table');
var fileNames = [
'abc',
'amazon',
//'eloquentjavascript',
//'es6-draft',
'es6-table',
'google',
'html-minifier... | (size) {
return chalk.green.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}
function blueSavings(oldSize, newSize) {
var savingsPercent = (1 - newSize / oldSize) * 100;
var savings = (oldSize - newSize) / 1024;
return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) +... | greenSize | identifier_name |
main.ts | /// <reference types="aurelia-loader-webpack/src/webpack-hot-interface"/>
// we want font-awesome to load as soon as possible to show the fa-spinner
//import '../static/styles.css';
import 'font-awesome/css/font-awesome.css';
import 'nprogress/nprogress.css';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstra... | .feature(PLATFORM.moduleName('resources/index'))
.developmentLogging();
aurelia.use.plugin(PLATFORM.moduleName('aurelia-bootstrap-datetimepicker'), config => {
config.extra.bootstrapVersion = 4;
config.extra.iconBase = 'font-awesome';
config.extra.withDateIcon = true;
});
aurelia.... | Bluebird.config({ warnings: false });
export async function configure(aurelia: Aurelia) {
aurelia.use
.standardConfiguration() | random_line_split |
main.ts | /// <reference types="aurelia-loader-webpack/src/webpack-hot-interface"/>
// we want font-awesome to load as soon as possible to show the fa-spinner
//import '../static/styles.css';
import 'font-awesome/css/font-awesome.css';
import 'nprogress/nprogress.css';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstra... | // aurelia.use.plugin(PLATFORM.moduleName('aurelia-html-import-template-loader'));
await aurelia.start();
await aurelia.setRoot(PLATFORM.moduleName('app'));
}
| aurelia.use
.standardConfiguration()
.feature(PLATFORM.moduleName('resources/index'))
.developmentLogging();
aurelia.use.plugin(PLATFORM.moduleName('aurelia-bootstrap-datetimepicker'), config => {
config.extra.bootstrapVersion = 4;
config.extra.iconBase = 'font-awesome';
config.extr... | identifier_body |
main.ts | /// <reference types="aurelia-loader-webpack/src/webpack-hot-interface"/>
// we want font-awesome to load as soon as possible to show the fa-spinner
//import '../static/styles.css';
import 'font-awesome/css/font-awesome.css';
import 'nprogress/nprogress.css';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstra... | urelia: Aurelia) {
aurelia.use
.standardConfiguration()
.feature(PLATFORM.moduleName('resources/index'))
.developmentLogging();
aurelia.use.plugin(PLATFORM.moduleName('aurelia-bootstrap-datetimepicker'), config => {
config.extra.bootstrapVersion = 4;
config.extra.iconBase = 'font-awesome'... | nfigure(a | identifier_name |
set_version.py | #! /usr/bin/env python
import os
import sys
import glob
version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
def substitute_file(name):
subst = ''
f = open(name)
for l in f:
if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MAJO... |
subst += l
f.close()
open(name, 'w+').write(subst)
substitute_file('include/libtorrent/version.hpp')
substitute_file('CMakeLists.txt')
substitute_file('configure.ac')
substitute_file('bindings/python/setup.py')
substitute_file('docs/gen_reference_doc.py')
for i in glob.glob('docs/*.rst'):
substitute_file(i)
s... | l = "\tversion = '%d.%d.%d',\n" % (version[0], version[1], version[2]) | conditional_block |
set_version.py | #! /usr/bin/env python
import os
import sys
import glob
version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
def substitute_file(name):
| l = "\tversion = '%d.%d.%d',\n" % (version[0], version[1], version[2])
elif "version = '" in l and name.endswith('setup.py'):
l = "\tversion = '%d.%d.%d',\n" % (version[0], version[1], version[2])
subst += l
f.close()
open(name, 'w+').write(subst)
substitute_file('include/libtorrent/version.hpp')
subst... | subst = ''
f = open(name)
for l in f:
if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MAJOR %d\n' % version[0]
elif '#define LIBTORRENT_VERSION_MINOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MINOR %d\n' % version[1]
elif '#defin... | identifier_body |
set_version.py | #! /usr/bin/env python
import os
import sys
import glob
version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
def substitute_file(name):
subst = ''
f = open(name)
for l in f:
if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MAJO... | subst += l
f.close()
open(name, 'w+').write(subst)
substitute_file('include/libtorrent/version.hpp')
substitute_file('CMakeLists.txt')
substitute_file('configure.ac')
substitute_file('bindings/python/setup.py')
substitute_file('docs/gen_reference_doc.py')
for i in glob.glob('docs/*.rst'):
substitute_file(i)
sub... | random_line_split | |
set_version.py | #! /usr/bin/env python
import os
import sys
import glob
version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
def | (name):
subst = ''
f = open(name)
for l in f:
if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MAJOR %d\n' % version[0]
elif '#define LIBTORRENT_VERSION_MINOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MINOR %d\n' % version[1]
eli... | substitute_file | identifier_name |
CheckOut.js | // ------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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
//... |
if (state == null) {
state = "";
}
$.ajax({
type: "POST",
url: "/layouts/ecommerce/Examples/ajax.asmx/SaveShippingAddress",
data: "{countryCode:'" + countryCode + "',state:'" + state + "'}",
contentType: "application/json; charset=utf-8",
dat... |
alert("Please select country!");
return false;
}
| conditional_block |
CheckOut.js | // ------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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
//... | contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
window.location.href = window.location.href;
return false;
}
});
});
$("a[id*='btnLogIn']").live("click", function () {
$.ajax({
type: "POST",
url: "/l... | $("a[id*='btnLogOut']").live("click", function () {
$.ajax({
type: "POST",
url: "/layouts/ecommerce/Examples/ajax.asmx/LogOutCurrentUser",
data: "{}",
| random_line_split |
index.js | #!/usr/bin/env node
const {argv} = require('yargs')
.usage('$0 [options] <assetsFolder>')
.demand(1)
.env('CDN_UPLOADER')
.option('app-prefix', {
alias: 'a',
describe: 'Application prefix used in the CDN url',
demand: true,
type: 'string',
})
.option('key-filenam... | .version()
.alias('help', ['h', '?'])
.alias('version', 'v');
const updateNotifier = require('update-notifier');
const { upload, getAllAssetsToUpload } = require('./lib/uploader');
const pkg = require('./package.json');
updateNotifier({ pkg }).notify();
const options = { ...argv, assetsFolder: argv._[0]}... | .help() | random_line_split |
index.js | #!/usr/bin/env node
const {argv} = require('yargs')
.usage('$0 [options] <assetsFolder>')
.demand(1)
.env('CDN_UPLOADER')
.option('app-prefix', {
alias: 'a',
describe: 'Application prefix used in the CDN url',
demand: true,
type: 'string',
})
.option('key-filenam... | else {
// Avoid loading credentials if we're in a dry-run
upload(Object.assign(options, { credentials: loadCredentials() })).then(
({results: uploadedAssets, errors}) => {
if (Array.isArray(uploadedAssets) && uploadedAssets.length > 0) {
console.log('\n---Uploaded assets---'... | {
// Lazy load these deps
const { blue, yellow, green } = require('chalk');
const table = require('text-table');
const text = getAllAssetsToUpload(options)
.map(({ path, destination }) => ({
file: path,
destination: getGoogleUrl(destination),
}))
.map(({ ... | conditional_block |
index.js | #!/usr/bin/env node
const {argv} = require('yargs')
.usage('$0 [options] <assetsFolder>')
.demand(1)
.env('CDN_UPLOADER')
.option('app-prefix', {
alias: 'a',
describe: 'Application prefix used in the CDN url',
demand: true,
type: 'string',
})
.option('key-filenam... |
const getGoogleUrl = dest =>
`https://storage.googleapis.com/${options.bucketName}/${dest}`;
if (options.dryRun) {
// Lazy load these deps
const { blue, yellow, green } = require('chalk');
const table = require('text-table');
const text = getAllAssetsToUpload(options)
.map(({ path, desti... | {
if (options.keyFilename) {
return require(options.keyFilename);
} if (options.credentials) {
try {
return JSON.parse(
Buffer.from(options.credentials, 'base64').toString('utf8')
);
} catch (err) {
console.error('Unable to parse creden... | identifier_body |
index.js | #!/usr/bin/env node
const {argv} = require('yargs')
.usage('$0 [options] <assetsFolder>')
.demand(1)
.env('CDN_UPLOADER')
.option('app-prefix', {
alias: 'a',
describe: 'Application prefix used in the CDN url',
demand: true,
type: 'string',
})
.option('key-filenam... | () {
if (options.keyFilename) {
return require(options.keyFilename);
} if (options.credentials) {
try {
return JSON.parse(
Buffer.from(options.credentials, 'base64').toString('utf8')
);
} catch (err) {
console.error('Unable to parse cre... | loadCredentials | identifier_name |
GameClient.ts | import * as WS from "ws";
import {Faction} from "Common/Models";
import * as RPC from "Common/RPC";
import {ServerGame} from "./ServerGame";
export class GameClient extends RPC.RemotePeer {
public ws: WS;
public faction: Faction;
private joinedGame: ServerGame;
| (id: string, ws: WS) {
super(id);
this.ws = ws;
this.ws.on("close", () => {
this.game = null;
this.emit("close");
});
this.ws.on("open", () => {
this.emit("open");
});
this.ws.on("message", (data) => {
this.onMess... | constructor | identifier_name |
GameClient.ts | import * as WS from "ws";
import {Faction} from "Common/Models";
import * as RPC from "Common/RPC";
import {ServerGame} from "./ServerGame";
export class GameClient extends RPC.RemotePeer {
public ws: WS;
public faction: Faction;
private joinedGame: ServerGame;
constructor(id: string, ws: WS) {
... |
public gameUpdate(params: RPC.ClientMethods.IGameUpdateParams) {
return this.call(RPC.ClientMethods.GameUpdate, params);
}
public hi() {
return this.callNoParams(RPC.ClientMethods.Hi);
}
public endTurn() {
if (this.joinedGame && !this.faction.canAct) {
throw n... | {
if (value) {
value.addPeer(this);
} else if (this.joinedGame) {
this.joinedGame.removePeer(this);
}
this.joinedGame = value;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.